pax_global_header00006660000000000000000000000064135275125310014516gustar00rootroot0000000000000052 comment=31217cec69d11b6c6a70dc114fbbf5d4c7204bd3 ossim-Miami-2.9.1/000077500000000000000000000000001352751253100137135ustar00rootroot00000000000000ossim-Miami-2.9.1/.gitignore000066400000000000000000000002161352751253100157020ustar00rootroot00000000000000*~ include/ossim/ossimConfig.h include/ossim/ossimVersion.h doc/html *CMakeFiles* *Makefile cmake_install* *.swp CMakeCache.txt .gradle .idea ossim-Miami-2.9.1/CMakeLists.txt000066400000000000000000000275061352751253100164650ustar00rootroot00000000000000PROJECT(ossim) SET(CMAKE_MODULE_PATH "${${PROJECT_NAME}_SOURCE_DIR}/cmake/CMakeModules;${CMAKE_MODULE_PATH}") set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) Message("################## Setting up OSSIM core library #########################") IF(NOT OSSIM_BUILD_ADDITIONAL_OSSIM_DIRECTORIES) SET(OSSIM_BUILD_ADDITIONAL_OSSIM_DIRECTORIES "" CACHE PATH "Specify full paths separated by ; to additional OSSIM applications you wish to include into the ossim build framework. These will have variables setup for the ossim includes" FORCE) ENDIF(NOT OSSIM_BUILD_ADDITIONAL_OSSIM_DIRECTORIES) cmake_minimum_required(VERSION 2.8) SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/ossim/cmake/CMakeModules" ${CMAKE_MODULE_PATH}) include(CMakeDetermineSystem) INCLUDE(OssimVersion) INCLUDE(OssimCommonVariables) # Expose some build options set(LIB_NAME ossim CACHE STRING "Name of ossim libray (default is ossim).") OPTION(BUILD_OSSIM_FREETYPE_SUPPORT "Set to ON to build OSSIM with freetype support. Use OFF to turn off freetype support." ON) OPTION(BUILD_OSSIM_MPI_SUPPORT "Set to ON to build OSSIM with MPI support. Use OFF to turn off MPI support." OFF) OPTION(BUILD_OSSIM_ID_SUPPORT "Set to ON to build OSSIM GIT ID support into the library. Use OFF to turn off ID support." ON) OPTION(BUILD_OSSIM_APPS "Set to ON to build OSSIM applications." ON) OPTION(BUILD_OSSIM_CURL_APPS "Set to ON to build ossim curl dependent apps. Use ON to enable." OFF) OPTION(BUILD_OSSIM_TESTS "Set to ON to build OSSIM unit/functional tests." ON) ################################################################################### # Include the Utilities in the root make ################################################################################### INCLUDE(OssimUtilities) INCLUDE(CheckIncludeFile) CHECK_INCLUDE_FILE("dirent.h" CMAKE_HAVE_DIRENT_H) CHECK_INCLUDE_FILE("unistd.h" CMAKE_HAVE_UNISTD_H) CHECK_INCLUDE_FILE("getopt.h" CMAKE_HAVE_GETOPT_H) CHECK_INCLUDE_FILE("fcntl.h" CMAKE_HAVE_FCNTL_H) CHECK_INCLUDE_FILE("dbmalloc.h" CMAKE_HAVE_DBMALLOC_H) CHECK_INCLUDE_FILE("malloc.h" CMAKE_HAVE_MALLOC_H) CHECK_INCLUDE_FILE("dlfcn.h" CMAKE_HAVE_DLFCN_H) # Set our include paths: include_directories( ${PROJECT_SOURCE_DIR}/include ) include_directories( ${PROJECT_BINARY_DIR}/include ) include_directories( ${OSSIM_INCLUDE_DIR} ) # Stores list of libs to link with. Initialized throughout. set( ossimDependentLibs ) #--- # Find required and optional packages and add their include paths and libraries: #--- # GEOS - Required: find_package( GEOS ) if( GEOS_FOUND ) include_directories( ${GEOS_INCLUDE_DIR} ) set( ossimDependentLibs ${ossimDependentLibs} ${GEOS_LIBRARY} ) else( GEOS_FOUND ) message( FATAL_ERROR "Could not find required geos package!" ) endif( GEOS_FOUND ) # GEOFIFF - Required: set( OSSIM_HAS_GEOTIFF 0 ) find_package( GEOTIFF ) if( GEOTIFF_FOUND ) include_directories( ${GEOTIFF_INCLUDE_DIR} ) set( ossimDependentLibs ${ossimDependentLibs} ${GEOTIFF_LIBRARY} ) set( OSSIM_HAS_GEOTIFF 1 ) else( GEOTIFF_FOUND ) message( FATAL_ERROR "Could not find required geotiff package!" ) endif( GEOTIFF_FOUND ) # GEOTRANS - Required: (GeoTrans 3.4.x port future...) # find_package( Geotrans ) # if( GEOTRANS_FOUND ) # include_directories( ${GEOTRANS_INCLUDE_DIR} ) # set( ossimDependentLibs ${ossimDependentLibs} ${GEOTRANS_LIBRARY} ) # else( GEOTRANS_FOUND ) # message( FATAL_ERROR "Could not find required geotrans package!" ) # endif( GEOTRANS_FOUND ) # JPEG - Required package: find_package( JPEG ) if( JPEG_FOUND ) include_directories( ${JPEG_INCLUDE_DIR} ) set( ossimDependentLibs ${ossimDependentLibs} ${JPEG_LIBRARY} ) else( JPEG_FOUND ) message( FATAL_ERROR "Could not find required jpeg package!" ) endif( JPEG_FOUND ) # TIFF - Required: find_package( TIFF ) if( TIFF_FOUND ) include_directories( ${TIFF_INCLUDE_DIR} ) set( ossimDependentLibs ${ossimDependentLibs} ${TIFF_LIBRARY} ) else( TIFF_FOUND ) message( FATAL_ERROR "Could not find required tiff package!" ) endif( TIFF_FOUND ) # JSONCPP - Required: find_package( JsonCpp ) if( JSONCPP_FOUND ) include_directories( ${JSONCPP_INCLUDE_DIR} ) set( ossimDependentLibs ${ossimDependentLibs} ${JSONCPP_LIBRARY} ) message("Found JsonCpp" ) else( JSONCPP_FOUND ) message( FATAL_ERROR "Could not find required JsonCpp package!" ) endif( JSONCPP_FOUND ) # This caused a core dump on ossim executables running in jenins pipeline (ossim-test-dev) if (CMAKE_SYSTEM_NAME MATCHES "Linux") find_library( DL_LIBRARY dl ) if ( DL_LIBRARY ) set( ossimDependentLibs ${ossimDependentLibs} ${DL_LIBRARY} ) else( DL_LIBRARY ) # TODO: Is this required on unix? If so move to the required section. message( FATAL_ERROR "Could not find dl library!" ) endif( DL_LIBRARY ) endif() # if (CMAKE_SYSTEM_NAME MATCHES "Linux") #if( UNIX ) # find_library( DL_LIBRARY dl ) # if ( DL_LIBRARY ) # set( ossimDependentLibs ${ossimDependentLibs} ${DL_LIBRARY} ) # else( DL_LIBRARY ) # # TODO: Is this required on unix? If so move to the required section. # message( FATAL_ERROR "Could not find dl library!" ) # endif( DL_LIBRARY ) #endif( UNIX ) # JSONCPP - Optional: set( OSSIM_HAS_JSONCPP 0 ) find_package( JsonCpp ) if( JSONCPP_FOUND ) include_directories( ${JSONCPP_INCLUDE_DIR} ) set( ossimDependentLibs ${ossimDependentLibs} ${JSONCPP_LIBRARY} ) set( OSSIM_HAS_JSONCPP 1 ) else( JSONCPP_FOUND ) message("Could not find optional JSONCPP package! Consider installing this as it will soon become a required package." ) endif( JSONCPP_FOUND ) # FREETYPE - Optional: set( OSSIM_HAS_FREETYPE 0 ) if( BUILD_OSSIM_FREETYPE_SUPPORT ) find_package(Freetype) if( FREETYPE_FOUND ) include_directories( ${FREETYPE_INCLUDE_DIRS} ) set( ossimDependentLibs ${ossimDependentLibs} ${FREETYPE_LIBRARIES} ) set( OSSIM_HAS_FREETYPE 1 ) else( FREETYPE_FOUND ) message( WARNING "Could not find optional freetype package!" ) endif( FREETYPE_FOUND ) endif( BUILD_OSSIM_FREETYPE_SUPPORT ) # MPI - Optional: set( OSSIM_HAS_MPI 0 ) if( BUILD_OSSIM_MPI_SUPPORT ) find_package(MPI) if ( MPI_FOUND ) include_directories( ${MPI_INCLUDE_DIR} ) set( ossimDependentLibs ${ossimDependentLibs} ${MPI_LIBRARY} ) set( OSSIM_HAS_MPI 1 ) else ( MPI_FOUND ) message( WARNING "Could not find optional MPI package!" ) endif ( MPI_FOUND ) endif( BUILD_OSSIM_MPI_SUPPORT ) # ZLIB - Optional: set( OSSIM_HAS_LIBZ 0 ) find_package( ZLIB ) if ( ZLIB_FOUND ) include_directories( ${ZLIB_INCLUDE_DIR} ) set( ossimDependentLibs ${ossimDependentLibs} ${ZLIB_LIBRARY} ) set( OSSIM_HAS_LIBZ 1 ) else ( ZLIB_FOUND ) message( WARNING "Could not find optional zlib package!" ) endif ( ZLIB_FOUND ) # HDF5 - Optional: set( OSSIM_HAS_HDF5 0 ) if (BUILD_OSSIM_HDF5_SUPPORT) message( STATUS "Native HDF5 support requested. Searching for HDF5 library..." ) find_package( HDF5A ) if ( HDF5A_FOUND) include_directories( ${HDF5A_INCLUDE_DIR} ) set( ossimDependentLibs ${ossimDependentLibs} ${HDF5A_LIBRARIES} ) set( OSSIM_HAS_HDF5 1 ) else ( HDF5A_FOUND ) message( WARNING "Could not find optional HDF5A package. Excluding native support." ) endif ( HDF5A_FOUND ) else (BUILD_OSSIM_HDF5_SUPPORT) message( STATUS "Native HDF5 support was not requested. If you want HDF5 support, set the environment BUILD_OSSIM_HDF5_SUPPORT=ON..." ) endif ( BUILD_OSSIM_HDF5_SUPPORT ) find_package( Threads ) set( ossimDependentLibs ${ossimDependentLibs} ${CMAKE_THREAD_LIBS_INIT} ) #--- # Call the OSSIM macros in OssimUtilities.cmake #--- if ( NOT OSSIM_BUILD_DATE ) TODAYS_DATE(OSSIM_BUILD_DATE) endif( NOT OSSIM_BUILD_DATE ) SET(OSSIM_GIT_REVISION_NUMBER "UNKNOWN") GET_GIT_REVISION() if ( NOT ${Project_WC_REVISION} EQUAL 0 ) set( OSSIM_GIT_REVISION_NUMBER ${Project_WC_REVISION} ) endif() ##################################################################################### # Call the configure files for ossimConfig and ossimVersion setup ##################################################################################### set(OSSIM_VERSION_NUMBER "\"${OSSIM_VERSION}\"") set(OSSIM_BUILD_DATE "\"${OSSIM_BUILD_DATE}\"") set(OSSIM_REVISION "\"${OSSIM_GIT_REVISION_NUMBER}\"") # Setting of OSSIM_ID to variable expanded $Id$ results. Embedded troughout code. set(OSSIM_ID_ENABLED 1) IF(NOT BUILD_OSSIM_ID_SUPPORT) set(OSSIM_ID_ENABLED 0) ENDIF(NOT BUILD_OSSIM_ID_SUPPORT) SET(OSSIM_CONFIGURE_HEADER "${CMAKE_CURRENT_SOURCE_DIR}/include/ossim/ossimConfig.h") CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/src/ossimConfig.h.in" "${OSSIM_CONFIGURE_HEADER}") SET(OSSIM_VERSION_HEADER_CONFIG "${CMAKE_CURRENT_SOURCE_DIR}/src/ossimVersion.h.in") SET(OSSIM_VERSION_HEADER "${CMAKE_CURRENT_SOURCE_DIR}/include/ossim/ossimVersion.h") CONFIGURE_FILE("${OSSIM_VERSION_HEADER_CONFIG}" "${OSSIM_VERSION_HEADER}") ################################################################################################## # Point to the CMakeLists.txt in the src dir. OLK: Removed unnecessary src/ossim structure and # replaced with simply src. ################################################################################################## subdirs(src) set(TARGET_COMMON_LIBRARIES ossim) ################################################################################################## # # Setup install destinations for the shared files: # 1) Projection CSV files: # ################################################################################################## FILE(GLOB ossim_projection_codes_csv ${${PROJECT_NAME}_SOURCE_DIR}/share/ossim/projection/*.csv ${${PROJECT_NAME}_SOURCE_DIR}/share/ossim/projection/*.txt) INSTALL(FILES ${ossim_projection_codes_csv} DESTINATION share/ossim/projection COMPONENT ossim) # 2) Utility API JSON files FILE(GLOB ossim_util_api_json ${${PROJECT_NAME}_SOURCE_DIR}/share/ossim/util/*.json) INSTALL(FILES ${ossim_util_api_json} DESTINATION share/ossim/util COMPONENT ossim) # 3) Fonts FILE(GLOB ossim_fonts ${${PROJECT_NAME}_SOURCE_DIR}/share/ossim/fonts/*.ttf) INSTALL(FILES ${ossim_fonts} DESTINATION share/ossim/fonts COMPONENT ossim) ###################### OUTPUT GENERAL VARIABLE SETTINGS ####################### MESSAGE( STATUS "OSSIM_REVISION = ${OSSIM_REVISION}" ) MESSAGE( STATUS "FREETYPE_LIBRARY = ${FREETYPE_LIBRARIES}" ) MESSAGE( STATUS "FREETYPE_INCLUDE = ${FREETYPE_INCLUDE_DIRS}" ) MESSAGE( STATUS "GEOTIFF_LIBRARY = ${GEOTIFF_LIBRARIES}" ) MESSAGE( STATUS "GEOTIFF_INCLUDE = ${GEOTIFF_INCLUDE_DIR}" ) MESSAGE( STATUS "GEOTRANS_LIBRARY = ${GEOTRANS_LIBRARY}" ) MESSAGE( STATUS "GEOTRANS_INCLUDE = ${GEOTRANS_INCLUDE_DIR}" ) MESSAGE( STATUS "GEOS_LIBRARY = ${GEOS_LIBRARY}" ) MESSAGE( STATUS "GEOS_INCLUDE = ${GEOS_INCLUDE_DIR}" ) MESSAGE( STATUS "JPEG_LIBRARY = ${JPEG_LIBRARIES}" ) MESSAGE( STATUS "JPEG_INCLUDE = ${JPEG_INCLUDE_DIR}" ) MESSAGE( STATUS "OSSIM DEPENDENT LIBRARIES = ${ossimDependentLibs}" ) MESSAGE( STATUS "OSSIM_HAS_HDF5 = ${OSSIM_HAS_HDF5}" ) MESSAGE( STATUS "OSSIM_HAS_JSONCPP = ${OSSIM_HAS_JSONCPP}" ) #----------------------------------------------------------------------------- # uninstall target #----------------------------------------------------------------------------- #OSSIM_ADD_COMMON_MAKE_UNINSTALL() IF(BUILD_OSSIM_APPS) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/apps ${CMAKE_CURRENT_BINARY_DIR}/apps) ENDIF() #--- # Building curl dependant apps optional. default=OFF #--- if(BUILD_OSSIM_CURL_APPS) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/apps/curl_apps) endif() IF(BUILD_OSSIM_TESTS) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/test/src ${CMAKE_CURRENT_BINARY_DIR}/test/src) ENDIF() message("################## end of OSSIM core library setup #########################\n") ossim-Miami-2.9.1/Jenkinsfile000066400000000000000000000154371352751253100161110ustar00rootroot00000000000000properties([ parameters ([ string(name: 'BUILD_NODE', defaultValue: 'ossim-build', description: 'The build node to run on'), string(name: 'MAKE_VERBOSE', defaultValue: 'VERBOSE=true', description: ''), booleanParam(name: 'BUILD_WITH_FORTIFY', defaultValue: false, description: 'Check to build and scan source using HP Fortify tool'), booleanParam(name: 'SCAN_WITH_SONARQUBE', defaultValue: false, description: 'Check to perform SonarQube analysis'), booleanParam(name: 'CLEAN_WORKSPACE', defaultValue: true, description: 'Clean the workspace at the end of the run') ]), pipelineTriggers([ [$class: "GitHubPushTrigger"] ]), [$class: 'GithubProjectProperty', displayName: '', projectUrlStr: 'https://github.com/ossimlabs/ossim'], buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '3', daysToKeepStr: '', numToKeepStr: '20')), disableConcurrentBuilds() ]) node ("${BUILD_NODE}"){ try { stage( "Download Artifacts" ) { env.OPENCV_HOME = "${env.WORKSPACE}/opencv-3.2-minimal-install" withCredentials([string(credentialsId: 'o2-artifact-project', variable: 'o2ArtifactProject')]) { step ([$class: "CopyArtifact", projectName: o2ArtifactProject, filter: "common-variables.groovy", flatten: true]) } dir( "${ env.WORKSPACE }" ) { step ([$class: "CopyArtifact", projectName: "kakadu-build", filter: "kakadu.tgz", flatten: true]) sh "tar xvfz kakadu.tgz" step ([$class: "CopyArtifact", projectName: "opencv-build", filter: "opencv-3.2-minimal-install.tgz", flatten: true, target: "${ env.WORKSPACE }/opencv-3.2-minimal-install"]) sh """ pushd opencv-3.2-minimal-install tar xvfz opencv-3.2-minimal-install.tgz popd """ } load "common-variables.groovy" } stage( "Checkout" ) { dir( "ossim" ) { git branch: "$BRANCH_NAME", url: "${ GIT_PUBLIC_SERVER_URL }/ossim.git", credentialsId: "${ CREDENTIALS_ID }" } dir( "ossim-video" ) { git branch: "$BRANCH_NAME", url: "${ GIT_PUBLIC_SERVER_URL }/ossim-video.git", credentialsId: "${ CREDENTIALS_ID }" } dir( "ossim-planet" ) { git branch: "$BRANCH_NAME", url: "${ GIT_PUBLIC_SERVER_URL }/ossim-planet.git", credentialsId: "${ CREDENTIALS_ID }" } dir( "ossim-gui" ) { git branch: "$BRANCH_NAME", url: "${ GIT_PUBLIC_SERVER_URL }/ossim-gui.git", credentialsId: "${ CREDENTIALS_ID }" } dir( "ossim-oms" ) { git branch: "$BRANCH_NAME", url: "${ GIT_PUBLIC_SERVER_URL }/ossim-oms.git", credentialsId: "${ CREDENTIALS_ID }" } dir( "ossim-plugins" ) { git branch: "$BRANCH_NAME", url: "${ GIT_PUBLIC_SERVER_URL }/ossim-plugins.git", credentialsId: "${ CREDENTIALS_ID }" } dir( "ossim-wms" ) { git branch: "$BRANCH_NAME", url: "${ GIT_PUBLIC_SERVER_URL }/ossim-wms.git", credentialsId: "${ CREDENTIALS_ID }" } dir( "ossim-private" ) { git branch: "$BRANCH_NAME", url: "${ GIT_PRIVATE_SERVER_URL }/ossim-private.git", credentialsId: "${ CREDENTIALS_ID }" } } stage( "Build" ) { dir( "${ env.WORKSPACE }" ) { sh """ rm -rf ${ env.WORKSPACE }/build/CMakeCache.txt export PATH=${ PATH }:/opt/HPE_Security/Fortify_SCA_and_Apps_17.20/bin ${ env.WORKSPACE }/ossim/scripts/ossim-build.sh ${ env.WORKSPACE }/ossim/scripts/ossim-install.sh """ } } stage ( "Publish Nexus" ) { withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'nexusCredentials', usernameVariable: 'REPOSITORY_MANAGER_USER', passwordVariable: 'REPOSITORY_MANAGER_PASSWORD']]) { dir( "${ env.WORKSPACE }" ) { sh "${ env.WORKSPACE }/ossim/scripts/oms-deploy.sh" } } } stage( "Archive" ) { dir( "${ env.WORKSPACE }" ) { sh "tar cvfz ossim-install.tgz install" } dir( "${ env.WORKSPACE }/artifacts" ) { sh "mv ${ env.WORKSPACE }/ossim-install.tgz ." sh "cp ${ env.WORKSPACE }/ossim-oms/lib/joms-*.jar ." } archiveArtifacts "artifacts/*" } if (SCAN_WITH_SONARQUBE == "true" ) { stage( 'SonarQube analysis' ) { withSonarQubeEnv( "${ SONARQUBE_NAME }" ) { // requires SonarQube Scanner for Gradle 2.1+ // It's important to add --info because of SONARJNKNS-281 sh "sonar-scanner" } } } if ( BUILD_WITH_FORTIFY == "true" ) { stage( 'Fortify SCA' ) { dir( "${ env.WORKSPACE }/build" ) { sh """ export PATH=${ PATH }:/opt/HPE_Security/Fortify_SCA_and_Apps_17.20/bin sourceanalyzer -64 -b ossimlabs -scan -f fortifyResults-ossim.fpr """ archiveArtifacts "fortifyResults-ossim.fpr" withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'fortifyCredentials', usernameVariable: 'HP_FORTIFY_USERNAME', passwordVariable: 'HP_FORTIFY_PASSWORD']]) { sh """ export PATH=${ PATH }:/opt/HPE_Security/Fortify_SCA_and_Apps_17.20/bin fortifyclient -url ${ HP_FORTIFY_URL } -user "${ HP_FORTIFY_USERNAME }" -password "${ HP_FORTIFY_PASSWORD }" uploadFPR -file fortifyResults-ossim.fpr -project ossim -version 1.0 """ } } } } } finally { stage( "Clean Workspace" ) { if ( "${ CLEAN_WORKSPACE }" == "true" ) step([$class: 'WsCleanup']) } } } ossim-Miami-2.9.1/LICENSE.txt000066400000000000000000000020541352751253100155370ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ossim-Miami-2.9.1/README.md000066400000000000000000000427401352751253100152010ustar00rootroot00000000000000### Jenkins Build Status Resource | *master* | *dev* | ------------ | ------------- | ------------- OSSIM Build Centos7 | ![centos7 Status](https://jenkins.ossim.io/buildStatus/icon/?job=ossim-master&style=plastic) | ![centos7 Status](https://jenkins.ossim.io/buildStatus/icon/?job=ossim-dev&style=plastic) Batch Test| ![centos7 Status](https://jenkins.ossim.io/buildStatus/icon/?job=ossim-test-master&style=plastic) | ![centos7 Status](https://jenkins.ossim.io/buildStatus/icon/?job=ossim-test-dev&style=plastic) RPMS Build Centos7 | ![centos7 Status](https://jenkins.ossim.io/buildStatus/icon/?job=rpm-master&style=plastic) | ![centos7 Status](https://jenkins.ossim.io/buildStatus/icon/?job=rpm-dev&style=plastic) RPMS Publish Centos7 | ![centos7 Status](https://jenkins.ossim.io/buildStatus/icon/?job=rpm-publish-master&style=plastic) | ![centos7 Status](https://jenkins.ossim.io/buildStatus/icon/?job=rpm-publish-dev&style=plastic) Coverity Scan Build Status # Welcome to OSSIM OSSIM is an open source, C++ (mostly), geospatial image processing library used by government, commercial, educational, and private entities throughout the solar system. It has been in active development since the last millenium. This repository contains the full OSSIM package including core library, applications, tests, and build system. It does *not* contain the OSSIM plugins and other OSSIM-related code such as java-bindings ([ossim-oms](https://github.com/ossimlabs/ossim-oms)), and GUI. Those are available for individually cloning. Refer to the root github page for [ossimlabs](https://github.com/ossimlabs). Quick links: * [What to Get](#relationship-between-repositories) * [How to Build](#how-to-build) * [How to Test](#how-to-test) * [OSSIM Command Line Utility](#ossim-command-line-utility) * [Doxygen Source Code Documentation](https://trac.osgeo.org/ossim/doxygen) # Relationship between Repositories (What to Get) The principal repository is this one (ossim), containing not only the core classes but also the command line utility applications code as well as the cmake build system files and related scripts. This repository must be cloned first before attempting to work with other _ossim-*_ repositories. The remaining _ossim-*_ repositories are independent of each other and can be cloned in any order. However, it will be necessary to re-run the [build script (linux version)](/scripts/linux/build.sh) or at least regenerate makefiles with the [cmake script (linux version)](/cmake/scripts/ossim-cmake-config-LINUX.sh) before building. This must be done each time a new ossim-* repository is added to the ossimlabs build. See below for detailed build instructions. # Branching Scheme and Pull Requests The "master" branches (for all OSSIM family repos) contain the most stable code. It is periodically merged with "dev" branch. If you don't plan on developing code, but want to build from source, this is the branch you want. For bleeding edge development, use the "dev" branch. This branch serves as the parent to all feature branches and is frequently merged with those feature branches once those branches are tested by the developers responsible for them. If you want to contribute code, you'll need to: * create your own feature branch from dev, * test your modification, * then create a pull request. The moderators will review the request and merge your changes to "dev". At that point, the automated continuous integration system (Jenkins) will get triggered to perform a build and test. If there are any failures, your merge commit will be backed out. # How to Build The easy way is to just run the script in `ossim/scripts/build.sh`. This approach should work for the default build configuration. This currently works for both linux and Mac. We hope to soon have a Windows `build.bat` file and world peace. Assuming all dependencies were met and no compile/link errors occured, this script will generate all build binaries under a sibling directory to the ossim repo directory, namely, `ossim/../build`. See the section on environment variables below for options on customizing the build location. This repository provides the CMAKE infrastructure necessary to build the OSSIM core library and related plugins and applications. Throughout this document, reference is made to the local, top-level directory containing this repository. We'll call this directory simply *ossim-dev-home*. (In fact, you'll find the shell variable `OSSIM_DEV_HOME` used throughout the various scripts in this and other repositories. The following 3rd-party SDKs are needed in order to build the core ossim library: libtiff-devel (preferably version 4.x for BigTIFF support) OpenThreads-devel libjpeg-devel libgeos-devel (on later Debian / Ubuntu versions, libgeos++-dev) (Mac users: use [MacPorts](https://github.com/macports/macports-base) to install dependencies) Plugins will require additional 3rd-party packages. Building OSSIM and related repos from source is a two-step process: first create the make files using CMake, then run `make` to build the binaries. Scripts are available for Linux/Mac and (soon) Windows to run CMake with default settings. You can run the script from any working directory and default settings will be used for creating the default build environment. It is possible to override specific defaults for your own custom requirements or preferences. Presently, the default setting is to disable the building of all plugins. If you want specific plugin libraries to be built, you'll need to edit your cmake script at `cmake/scripts/ossim-cmake-config.sh` (or similar `.bat` file for Windows). Scroll down to the "Plugins" section and set the corresponding variables to "ON". Note that you could also define those variables in your shell environment in lieu of editing the script. ## Creating the Makefiles ### Creating a Default Build Environment The cmake configuration scripts are available in the `cmake/scripts` subdirectory. Assuming no OSSIM environment variables are available to override the defaults, the "out-of-source" `build` directory will be created under the same parent directory *ossim-dev-home* as this repo. The linux/Mac script `ossim/scripts/build.sh`, if run in an interactive shell will query for the build type. If the script is run as part of a batch process, "Release" is assumed. If the build directory does not exist, it will be created. ### Customizing the Build There are two ways to customize the build: via environment variables and by directly editing the cmake configuration script. #### Environment Variables The CMake system will locally define certain environment variables that live for the lifetime of the cmake config script execution. The following shell variables, if defined, are referenced to override the default settings. The developer has the option to override the default build directory location by setting the environment variable `OSSIM_BUILD_DIR` prior to running the cmake config script. If not present, the `build` directory will be located just under *ossim-dev-home* as described above. Another defaulted environment variable is `OSSIM_INSTALL_PREFIX`. This variable as two distinct functions. First, it indicates where to install the OSSIM SDK when running `make install`. Second, it serves to specify a path to SDKs that OSSIM depends on. The CMake system will scan `OSSIM_INSTALL_PREFIX` for the presence of dependency packages such as GeoTiff, JPEG, and others. This secondary purpose of `OSSIM_INSTALL_PREFIX` used to be handled by the now obsolete environment variable `OSSIM_DEPENDENCIES`. It is a reasonable consolidation since the OSSIM install will need to include these dependencies if they are not available in their standard installation locations (/usr/lib, /usr/local/lib, etc.), so placing these SDKs in the final OSSIM install directory prior to building OSSIM makes sense. If no override is defined for `OSSIM_INSTALL_PREFIX`, then the cmake config script will default to `$OSSIM_DEV_HOME/install`. You can populate that directory with non-standard installs of the OSSIM dependencies prior to running the script. If the directory does not exist, it is created by the script. Obviously, in that case, all OSSIM dependencies will be expected to be found in standard system install folders. As already mentioned, you can enable the building of specific plugins by defining the corresponding environment variable: `BUILD__PLUGIN=ON`. NOTE: For legacy reasons, `OSSIM_DEPENDENCIES` is still scanned for dependency SDKs. New dependencies however should be "installed" in `OSSIM_INSTALL_PREFIX`. #### Editing the CMake Config Script The default configuration relies on the presence of the OSSIM repositories under the *ossim-dev-home* to decide whether to include those in the build (with the exception of the plugins, which default to "OFF"). You may want to selectively exclude certain applications from the build without having to hide the workspaces from CMake. The flags enabling those are defined in the script. Simply set the corresponding variable to "OFF" and rerun the script. Likewise, for the plugins, you can modify the default ("OFF") by changing the corresponding variables in the script to "ON". There are other flags available that direct CMake to generate project files for IDEs such as Eclipse and Visual Studio. You can also specify multi-threaded builds, non-standard output directories, and more. Feel free to experiment, but know that you'll be voiding the warranty. ### _How do I know what dependencies are needed?_ The CMake system will attempt to locate all necessary dependency SDKs in the system's standard install directories. On linux, this includes, but not limited to, /usr and /usr/local. If it cannot find them, the script will exit with an error message indicating the missing library. You can then install the missing library from the third-party repository before trying to run the OSSIM cmake config script again. You may get several dependency errors before CMake succeeds in generating all the Makefiles needed. Remember, you can provide "sandbox" installations of dependency libraries that you want to link with, even though your system may (or may not) have installed different versions of those libraries. That's achieved by "installing" those SDKs inside the directory indicated by the CMake environment variable `OSSIM_INSTALL_PREFIX` (defaults to *ossim-dev-home*/install, see above). Eventually, we hope to provide an artifact repository so that CMake itself can access any missing dependencies without the need for the developer to manually install them. ## Building the Binaries Once the cmake configuration script terminates successfully, you are ready to build the binaries. Build instructions vary slightly between OS's, but generally involve simply running `make` inside the build directory. First change directory to the build folder created by the cmake config script. There you will find a top-level Makefile that will bootstrap the build. From a terminal, run `make`. The build should proceed normally for a few minutes, longer if the first time through. Upon successful completion, you should find a "lib" and "bin" folder containing the ossim library and executable, respectively. Developers have different ways of working -- all we're helping you with here is building the OSSIM library and associated plugins and executables. You may choose to then run `make install` to copy the binaries to some standard system location (you'll need to have the appropriate permissions). Alternatively, you can append your `PATH` environment variable to include the `build/bin` folder containing the executables. You also need to update the library path to include `build/lib`. These settings vary by OS so you're on your own here. ## Integrated Development Environments You may be able to import the build environment into your IDE "as a Makefile project." The Windows cmake configuration script will generate Visual Studio project files for direct import into Visual Studio. You may want to take a look at that script to see if there is a custom setting (or command line argument) you need to tinker with. ### Eclipse Users For convenience, you can specify "eclipse" as the build-type to the script at `ossim/cmake/scripts/ossim-cmake-config-LINUX.sh` that will generate the Eclipse CDT4 project files along with the makefiles for a debug build. The output build directory will be one level up from *ossim-dev-home* since Eclipse does not support the build directory as sibling of source. Eclipse will properly generate "Subprojects" corresponding to each ossimlabs repo present in your *ossim-dev-home* for indexed navigation of the source files. It is built with debug. To import into your Eclipse workspace, right-click in the Project Explorer and select Import->General->"Existing Project...", then select the root directory by browsing to `/../build` and clicking "OK". # How to Test The first check of a successful build is to run the ossim command line utility `ossim-cli --version`. You should get the current version output to the console. More on the `ossim-cli` command below. Testing is generally divided into unit, functional, and integration tests. At the moment, true unit testing in OSSIM is very limited, and likely to stay that way. There is however a _de facto_ scheme in place that has been used for implementing integration and functional testing using the `ossim-batch-test` command line executable. Much of the functional testing supplied through `ossim-batch-test` configuration files is fairly fine-grained, almost to the unit-test level of granularity. This testing platform lets the developer create any level of test, from top-level integration test to individual class method test. This application spawns other OSSIM utility applications to generate results, including dedicated test utilities, which are then compared against an expected-results dataset. This command-line app reads a configuration file that specifies a test or series of tests to run and possibly compare against expected results. There is an option to accept current results as the new expected results. While not explicitly required, the majority of testing done with `ossim-batch-test` will involve input source data, typically imagery, that the tester must preinstall on the target machine. The expected results will also need to be generated and its location specified on the command line. See the usage for `ossim-batch-test` for more detail. A rudimentary test suite is encapsulated in this [test script (linux version)](/scripts/test.sh). It defines the locations of the input source data and expected results, and runs the command-line test applications. The _ossim_ repository contains `test/src` and `test/config` subdirectories which contain items available for testing OSSIM core functionality. At some point when we start including unit tests, there will be a third directory, `test/scripts`, that will contain the commands to run those unit tests. ## test/src This directory contains the source code for unit and functional testing of core OSSIM objects. It is automatically built by the cmake/make system, assuming `BUILD_OSSIM_TESTS` is set to `ON` (the default). The resulting executables, located in `build/bin`, can be run standalone on the command line. The code in this directory is also a good source of examples for interfacing to many important OSSIM classes. This directory also contains the source code for `ossim-batch-test`. ## test/config This subdirectory contains, primarily, configuration files for existing `ossim-batch-test` runs. The input data referenced in the `ossim-batch-test` configuration files are presently hosted on an Amazon S3 storage. Contact the [OSSIM developer list](mailto:ossim-developer@lists.sourceforge.net) if you want access to this public data for your own testing. # OSSIM Command Line Utility The executable `ossim-cli` will eventually consolidate the plethora of ossim utility applications currently existing. For now it supports a small subset of utilities though among them is `info` that reproduces the functionality of the ubiquitous `ossim-info`. The usage is: `ossim-cli [options and parameters]` With no arguments, the app will give a list of capabilities. Currently those are * help -- To get help on specific command. Same as " --help" * bandmerge -- Merges multiple band files into a single RGB image. * hillshade -- Computes shaded representation of input elevation surface with specified lighting parameters. * hlz -- Computes bitmap of helicopter landing zones given ROI and DEM. * info -- Dumps metadata information about input image and OSSIM in general. * ortho -- Utility for orthorectifying and reprojecting image data. * potrace -- Computes vector representation of input raster image. * shoreline -- Computes bitmap of water versus land areas in an input image. * slope -- Utility for computing the slope at each elevation post and generating a corresponding slope image. * vertices -- Utility for determining the active image corner vertices inside larger null-filled image rectangle. * viewshed -- Computes bitmap image representing the viewshed from specified location using only DEM information. For example, to get projection and image information for an image file, use `ossim-cli info -p -i ` You can also give a keyword list (KWL) file as the only arg. The KWL must contain the keyword "tool" with one of the supported commands above, along with the keywords expected by that utility. You can even get KWL templates or enter the keyword/values interactively. ossim-Miami-2.9.1/apps/000077500000000000000000000000001352751253100146565ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/CMakeLists.txt000066400000000000000000000007411352751253100174200ustar00rootroot00000000000000FILE(GLOB OSSIM_APP_DIRS "ossim-*") FILE(GLOB OSSIM_CONFIG_DIR "ossim-config*") LIST(REMOVE_ITEM OSSIM_APP_DIRS ${OSSIM_CONFIG_DIR}) # FIND_PACKAGE(ossim) # if( OSSIM_FOUND ) # include_directories( ${OSSIM_INCLUDE_DIR} ) # else( OSSIM_FOUND ) # message( FATAL_ERROR "Could not find required OSSIM package!" ) # endif( OSSIM_FOUND ) # set(TARGET_COMMON_LIBRARIES ${OSSIM_LIBRARY} ${OPENTHREADS_LIBRARY}) FOREACH(f ${OSSIM_APP_DIRS}) ADD_SUBDIRECTORY(${f}) ENDFOREACH(f) ossim-Miami-2.9.1/apps/curl_apps/000077500000000000000000000000001352751253100166465ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/curl_apps/CMakeLists.txt000066400000000000000000000033011352751253100214030ustar00rootroot00000000000000message( "************** Begin: CMAKE SETUP FOR ossim curl apps ******************" ) cmake_minimum_required (VERSION 2.8) project(ossimcore) set(requiredLibs) # Get the library suffix for lib or lib64. get_property(LIB64 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS) if(LIB64) set(LIBSUFFIX 64) else() set(LIBSUFFIX "") endif() find_package( CURL ) if( CURL_FOUND ) include_directories( ${CURL_INCLUDE_DIR} ) set( requiredLibs ${requiredLibs} ${CURL_LIBRARY} ) else( CURL_FOUND ) message(FATAL_ERROR "Could not find curl") endif( CURL_FOUND ) # Requires ossim: find_package(ossim) if (OSSIM_FOUND) include_directories( ${OSSIM_INCLUDE_DIR} ) set(requiredLibs ${requiredLibs} ${OSSIM_LIBRARIES} ) else(OSSIM_FOUND) message(FATAL_ERROR "Could not find ossim") endif(OSSIM_FOUND) # Add our include... include_directories(".") message( STATUS "CURL_INCLUDE_DIR = ${CURL_INCLUDE_DIR}" ) message( STATUS "CURL_LIBRARY = ${CURL_LIBRARY}" ) message( STATUS "OSSIM_INCLUDE_DIR = ${OSSIM_INCLUDE_DIR}" ) message( STATUS "OSSIM_LIBRARIES = ${OSSIM_LIBRARIES}" ) message( STATUS "Required libs = ${requiredLibs}" ) # --- # omar-data-mgr app: # --- # Add the executable: add_executable(omar-data-mgr omar-data-mgr.cpp omarDataMgrUtil.cpp ) # Set the output dir: set_target_properties(omar-data-mgr PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") # omar-data-mgr application links with required libs. target_link_libraries( omar-data-mgr ${requiredLibs} ) # Install app: install( TARGETS omar-data-mgr DESTINATION bin ) message( "************** End: CMAKE SETUP FOR ossim curl apps ******************" ) ossim-Miami-2.9.1/apps/curl_apps/omar-data-mgr.cpp000066400000000000000000000037461352751253100220140ustar00rootroot00000000000000//--- // File: omar-data-mrg.cpp // // License: See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: omar-data-mrg application for interfacing with OMAR // dataManager services, e.g. "add", "remove" raster via libcurl. //--- #include #include #include #include #include #include #include "omarDataMgrUtil.h" #include using namespace std; int main(int argc, char *argv[]) { #if OSSIM_HAS_MPI ossimMpi::instance()->initialize(&argc, &argv); #endif int rv = 0; // Return value. //--- // Get the arg count so we can tell if an arg was consumed by // ossimInit::instance()->initialize //--- int originalArgCount = argc; ossimArgumentParser ap(&argc, argv); // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); //--- // Avoid going on if a global option was consumed by ossimInit::initialize // like -V or --version option and the arg count is down to 1. //--- if ( ( ap.argc() > 1 ) || ( ap.argc() == originalArgCount ) ) { // Make the info object. ossimRefPtr dm = new omarDataMgrUtil(); try { //--- // Initialize will take the options passed in and set things to output // information for. // // omarDataMgrUtil::initialize can throw an exception. //--- bool continue_after_init = dm->initialize(ap); if ( continue_after_init ) { // This does all the work... rv = (int)dm->execute(); } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; rv = 1; } } // End: if ( ( ap.argc() > 1 ) ... return rv; } // End of main... ossim-Miami-2.9.1/apps/curl_apps/omarDataMgrUtil.cpp000066400000000000000000000707121352751253100224150ustar00rootroot00000000000000//---------------------------------------------------------------------------- // File: omarDataMgrUtil.cpp // // License: See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: omarDataMgrUtil class definition // // Utility class for processing images recursively and calling OMAR // services upon successful open. // //---------------------------------------------------------------------------- // $Id$ #include "omarDataMgrUtil.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static std::string ACCESS_TIME_THRESHOLD_KW = "access_time_threshold"; static std::string CLEAN_KW = "clean"; static std::string DUMP_FILTERED_IMAGES_KW = "dump_filtered_images"; static std::string FALSE_KW = "false"; static std::string FILE_KW = "file"; static std::string OVERRIDE_FILTERED_IMAGES_KW = "override_filtered_images"; static std::string SERVICE_KW = "service"; static std::string THREADS_KW = "threads"; static std::string TRUE_KW = "true"; static std::string URL_KW = "url"; // Static trace for debugging. Use -T omarDataMgrUtil to turn on. static ossimTrace traceDebug = ossimTrace("omarDataMgrUtil:debug"); omarDataMgrUtil::omarDataMgrUtil() : ossimReferenced(), ossimFileProcessorInterface(), m_kwl( new ossimKeywordlist() ), m_fileWalker(0), m_mutex(), m_imageUtil(0), m_errorStatus(0), m_filteredImages(0) { } omarDataMgrUtil::~omarDataMgrUtil() { if ( m_fileWalker ) { delete m_fileWalker; m_fileWalker = 0; } } void omarDataMgrUtil::addArguments(ossimArgumentParser& ap) { // Set the general usage: ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " [options] "; au->setCommandLineUsage(usageString); // Set the command line options: au->addCommandLineOption("--access-time-threshold", " For \"remove\" action. Only remove if last access is greater than days."); au->addCommandLineOption("--clean", "Cleans/removes image file and associated files from file system if present.\n\"remove\" option only.\nLooks for associated files of image, e.g. .ovr, .his, .omd, .geom\nCAUTION: This command is irreversible once envoked!"); au->addCommandLineOption("--dump-filtered-image-list", "Outputs list of filtered images."); au->addCommandLineOption("--override-filtered-images", "Allows processing of file that is in the filtered image list."); au->addCommandLineOption("--threads", " The number of threads to use. (default=1) Note a default can be set in your ossim preferences file by setting the key \"ossim_threads\"."); au->addCommandLineOption("--preproc", "Enables the use of the preproc utility to build overviews and histograms"); au->addCommandLineOption( "-u", " URL, e.g. \"http://omar.osssim.org/omar\"\n(default= url \"http://localhost:8080/omar\"" ); ossimRefPtr imageUtil = new ossimImageUtil(); imageUtil->addOptions(au); imageUtil = 0; } // void omarDataMgrUtil::addArguments(ossimArgumentParser& ap) bool omarDataMgrUtil::initialize(ossimArgumentParser& ap) { static const char M[] = "omarDataMgrUtil::initialize(ossimArgumentParser&)"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } bool result = true; if ( (ap.argc() == 1) || ap.read("-h") || ap.read("--help") ) { usage(ap); // continue_after_init to false result = false; } else { //--- // Start with clean options keyword list. //--- m_kwl->clear(); while ( 1 ) // While forever loop... { // Used throughout below: std::string ts1; ossimArgumentParser::ossimParameter sp1(ts1); if( ap.read("--access-time-threshold", sp1) ) { m_kwl->addPair( ACCESS_TIME_THRESHOLD_KW, ts1 ); if ( ap.argc() < 3 ) { break; } } if( ap.read("--clean") ) { addOption( CLEAN_KW, TRUE_KW ); if ( ap.argc() < 3 ) { break; } } if( ap.read("--dump-filtered-image-list") ) { setDumpFilteredImageListFlag( true ); if ( ap.argc() < 3 ) { break; } } if( ap.read("--override-filtered-images") ) { setOverrideFilteredImagesFlag( true ); if ( ap.argc() < 3 ) { break; } } if( ap.read("--threads", sp1) ) { m_kwl->addPair( THREADS_KW, ts1 ); if ( ap.argc() < 3 ) { break; } } if( ap.read("-u", sp1) ) { m_kwl->addPair( URL_KW, ts1 ); if ( ap.argc() < 3 ) { break; } } if( ap.read("--preproc")) { m_imageUtil = new ossimImageUtil(); if ( getOverrideFilteredImagesFlag() ) { //--- // User requested override but the arg parser for omarDataMgr has // stripped the argument for image util so manually set it. //--- m_imageUtil->setOverrideFilteredImagesFlag( true ); } m_imageUtil->initialize(ap); } if ( ap.argc() < 3 ) { break; } // End of arg parsing. ap.reportRemainingOptionsAsUnrecognized(); if ( ap.errors() ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); std::string errMsg = "Unknown option..."; throw ossimException(errMsg); } break; // Break from while forever. } // End while (forever) loop. if( ap.argc() > 2 ) { // First arg should be service, e.g. "add", "remove". std::string value = ap[1]; m_kwl->addPair( SERVICE_KW, value ); // Check for "clean" used with "add" and issue warning??? if ( getCleanFlag() && ( value == "add" ) ) { ossimNotify(ossimNotifyLevel_NOTICE) << "NOTICE: Using --clean with \"add\" service is illogical!\n"; } // The remaining args should be files to process. for (ossim_int32 i = 1; i < (ap.argc()-1); ++i) { ossimString kw = "file"; kw += ossimString::toString(i); std::string value = ap[i+1]; m_kwl->addPair(kw.string(), value, true); } } else { if ( getDumpFilterImagesFlag() ) { // Caller wants to see filtered image names: dumpFilteredImageList(); } else { usage(ap); result = false; } } } // not usage if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "m_kwl:\n" << *(m_kwl.get()) << "\n" << M << " exit result = " << (result?"true":"false") << "\n"; } return result; } ossim_int32 omarDataMgrUtil::execute() { static const char M[] = "omarDataMgrUtil::execute()"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if ( getDumpFilterImagesFlag() ) { // Caller wants to see filtered image names: if ( m_filteredImages.empty() ) { initializeDefaultFilterList(); } dumpFilteredImageList(); } // Get the number of "file*" keywords. ossim_uint32 fileCount = m_kwl->numberOf("file"); if ( fileCount ) { if ( !m_fileWalker ) { m_fileWalker = new ossimFileWalker(); } if ( !getOverrideFilteredImagesFlag() && m_filteredImages.empty() ) { initializeDefaultFilterList(); m_fileWalker->initializeDefaultFilterList(); } //--- // Passing getNumberOfThreads() to ossimFileWalker::setNumberOfThreads was // kicking up a coverity scan error: // Passing tainted variable "this->getNumberOfThreads()" to a tainted sink. // drb //--- ossim_uint32 threads = getNumberOfThreads(); m_fileWalker->setNumberOfThreads( threads ); // Must set this so we can stop recursion on directory based images. m_fileWalker->setWaitOnDirFlag( true ); // This links the file walker back to our "processFile" method. m_fileWalker->setFileProcessor( this ); // Wrap in try catch block as excptions can be thrown under the hood. try { // Get the list of files passed to us: std::vector files; ossim_uint32 processedFiles = 0;; ossim_uint32 i = 0; while ( processedFiles < fileCount ) { ossimString kw = FILE_KW; kw += ossimString::toString(i); std::string lookup = m_kwl->findKey( kw.string() ); if ( lookup.size() ) { files.push_back( ossimFilename(lookup) ); ++processedFiles; } ++i; if ( i > (fileCount + 100) ) break; } // Process the files: m_fileWalker->walk( files ); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "Caught exception: " << e.what() << endl; setErrorStatus( ossimErrorCodes::OSSIM_ERROR ); } } // if ( fileCount ) if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exit status: " << m_errorStatus << std::endl; } // Zero is good, non zero is bad. return m_errorStatus; } //--- // This method is called back by the ossimFileWalker::walk method for each file it finds that it // deems can be processed. //--- void omarDataMgrUtil::processFile(const ossimFilename& file) { static const char M[] = "omarDataMgrUtil::processFile"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n" << "\nfile: " << file << "\n"; } if ( file.size() ) { bool processFileFlag = true; if ( !getOverrideFilteredImagesFlag() ) { processFileFlag = !isFiltered( file ); } if ( processFileFlag ) { omarDataMgrUtil::OmarDataMgrUtilService service = getService(); if ( service == omarDataMgrUtil::ADD_RASTER ) { callAddRasterService( file ); } else if ( service == omarDataMgrUtil::REMOVE_RASTER ) { callRemoveRasterService( file ); } else { std::string s; getService( s ); ossimNotify(ossimNotifyLevel_WARN) << "Unhandled service: " << s << "\n"; } } else { ossimNotify(ossimNotifyLevel_NOTICE) << "Filtered file, not processing: " << file << std::endl; } } // Matches: if ( file.size() ) if(traceDebug()) { // Since ossimFileWalker is threaded output the file so we know which job exited. ossimNotify(ossimNotifyLevel_DEBUG) << M << "\nfile: " << file << "\nexited...\n"; } } // End: omarDataMgrUtil::processFile(const ossimFilename& file) void omarDataMgrUtil::usage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); // Set app name. ap.getApplicationUsage()->setApplicationName(ap.getApplicationName()); // Add options. addArguments(ap); // Write usage. ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); ossimNotify(ossimNotifyLevel_INFO) << "\nValid services: \"add\" and \"remove\"." << "\nExample usage:\n\n" << "Using default url \"http://localhost:8080/omar\":\n" << ap.getApplicationName() << " add 5V090205M0001912264B220000100072M_001508507.ntf\n\n" << "Build overviews, histogram, and add to database.\n" << ap.getApplicationName() << " --preproc --ot ossim_kakadu_nitf_j2k --ch add " << "5V090205M0001912264B220000100072M_001508507.ntf\n\n" << "Passing in url:\n" << ap.getApplicationName() << " -u http://your_url/omar add 5V090205M0001912264B220000100072M_001508507.ntf\n\n" << "Adding all images in a directory using 32 threads:\n" << ap.getApplicationName() << " --threads 32 add /data1/imagery/2015/09/28/0000\n\n" << "Removing file from database:\n" << ap.getApplicationName() << " remove 5V090205M0001912264B220000100072M_001508507.ntf\n\n" << "Removing file from database and file system:\n" << ap.getApplicationName() << " --clean remove 5V090205M0001912264B220000100072M_001508507.ntf\n\n" << "Removing all images in a directory using 32 threads:\n" << ap.getApplicationName() << " --clean --threads 32 remove /data1/imagery/2015/09/28/0000\n\n" << "Removing all images in a directory using 4 threads that have not been accessed in 30 days:\n" << ap.getApplicationName() << " --access-time-threshold 30 --clean --threads 4 remove /data1/imagery/2015/09/28/0000\n" << std::endl; } // Private method: bool omarDataMgrUtil::isDirectoryBasedImage(const ossimImageHandler* ih) const { bool result = false; if ( ih ) { // Get the image handler name. ossimString imageHandlerName = ih->getClassName(); if ( (imageHandlerName == "ossimAdrgTileSource") || (imageHandlerName == "ossimCibCadrgTileSource") ) { result = true; } } return result; } bool omarDataMgrUtil::isPastLastAccessedThreshold( const ossimFilename& file ) const { // Default to true. bool result = true; std::string value = m_kwl->findKey( ACCESS_TIME_THRESHOLD_KW ); if ( value.size() ) { const ossim_int64 SECONDS_PER_DAY = 86400; // 60 * 60 * 24 ossim_int64 thresholdInDays = ossimString(value).toInt64(); if ( thresholdInDays ) { // Returns -1 if does not exist. ossim_int64 secondsSinceAccessed = file.lastAccessed(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << ACCESS_TIME_THRESHOLD_KW << ": " << thresholdInDays << "\nfile_last_accessed: " << secondsSinceAccessed/SECONDS_PER_DAY << "\n"; } if ( secondsSinceAccessed > 0 ) { if ( secondsSinceAccessed/SECONDS_PER_DAY <= thresholdInDays ) { result = false; } } } } return result; } void omarDataMgrUtil::setNumberOfThreads( ossim_uint32 threads ) { addOption( THREADS_KW, threads ); } void omarDataMgrUtil::setNumberOfThreads( const std::string& threads ) { addOption( THREADS_KW, threads ); } ossim_uint32 omarDataMgrUtil::getNumberOfThreads() const { ossim_uint32 result = 1; std::string lookup = m_kwl->findKey( THREADS_KW ); if ( lookup.size() ) { result = ossimString(lookup).toUInt32(); } else { result = ossim::getNumberOfThreads(); } return result; } void omarDataMgrUtil::addOption( const std::string& key, ossim_uint32 value ) { addOption( key, ossimString::toString( value ).string() ); } void omarDataMgrUtil::addOption( const std::string& key, const std::string& value ) { m_mutex.lock(); if ( m_kwl.valid() ) { if ( key.size() && value.size() ) { m_kwl->addPair( key, value ); } } m_mutex.unlock(); } void omarDataMgrUtil::setErrorStatus( ossim_int32 status ) { m_mutex.lock(); m_errorStatus = status; m_mutex.unlock(); } omarDataMgrUtil::OmarDataMgrUtilService omarDataMgrUtil::getService() const { omarDataMgrUtil::OmarDataMgrUtilService service = omarDataMgrUtil::UNKNOWN; std::string value = m_kwl->findKey( SERVICE_KW ); if ( value.size() ) { ossimString s = value; s.downcase(); if ( s == "add" ) { service = omarDataMgrUtil::ADD_RASTER; } else if ( (s == "remove") || (s == "rm") || (s == "delete") || (s == "erase") ) { service = omarDataMgrUtil::REMOVE_RASTER; } } return service; } void omarDataMgrUtil::getService(std::string& serviceString) const { omarDataMgrUtil::OmarDataMgrUtilService service = getService(); if ( service == omarDataMgrUtil::ADD_RASTER ) { serviceString = "/dataManager/addRaster"; } else if ( service == omarDataMgrUtil::REMOVE_RASTER ) { serviceString = "/dataManager/removeRaster"; } else { serviceString.clear(); } } void omarDataMgrUtil::getUrl( std::string& url ) const { url = m_kwl->findKey( URL_KW ); if ( url.empty() ) { url = "http://localhost:8080/omar"; // default url } } bool omarDataMgrUtil::callAddRasterService( const ossimFilename& file ) { static const char M[] = "omarDataMgrUtil::callAddRasterService"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n" << "\nfile: " << file << "\n"; } bool result = false; // Must be able to open: m_mutex.lock(); ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(file, true, true); m_mutex.unlock(); if ( ih.valid() && !ih->hasError() ) { if ( isDirectoryBasedImage( ih.get() ) ) { // Tell the walker not to recurse this directory. m_mutex.lock(); m_fileWalker->setRecurseFlag(false); m_mutex.unlock(); } // Must have geometry: ossimRefPtr geom = ih->getImageGeometry(); if( geom.valid() ) { // Geometry object must have a valid projection: ossimRefPtr proj = geom->getProjection(); if ( proj.valid() ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Processing file: " << file << std::endl; if( m_imageUtil.valid() ) { m_imageUtil->processFile(file); } std::string service; getService( service ); std::string url; getUrl( url ); if ( service.size() && url.size() ) { CURL* curl = curl_easy_init(); if ( curl ) { // Data for POST: std::string data = std::string("filename=") + file.string(); curl_easy_setopt( curl, CURLOPT_POSTFIELDS, data.c_str() ); // Create the URL string: std::string urlString = url + service; curl_easy_setopt( curl, CURLOPT_URL, urlString.c_str() ); ossimNotify(ossimNotifyLevel_INFO) << "data: " << data << "\nurl: " << urlString.c_str() << std::endl; // Tell libcurl to follow redirection curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // Run it: CURLcode res = curl_easy_perform(curl); // Check for errors: if ( res == CURLE_OK ) { // Response code of the http transaction: long respcode; res = curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &respcode); if ( res == CURLE_OK ) { if ( respcode == 200 ) // OK 200 "The request was fulfilled." { result = true; // Set return status for caller. } } } else { ossimNotify(ossimNotifyLevel_WARN) << "curl_easy_perform() failed: \n" << curl_easy_strerror(res) << std::endl; setErrorStatus( (ossim_int32)res ); } ossimNotify(ossimNotifyLevel_WARN) << std::endl; // Always cleanup: curl_easy_cleanup(curl); } // Cleanup curl: curl_global_cleanup(); } // Matches: if ( url.size() ) } else { ossimNotify(ossimNotifyLevel_WARN) << M << "\nCould create projection for: " << file << std::endl; } } else { ossimNotify(ossimNotifyLevel_WARN) << M << "\nCould create geometry for: " << file << std::endl; } } else { ossimNotify(ossimNotifyLevel_WARN) << M << "\nCould not open: " << file << std::endl; } if(traceDebug()) { // Since ossimFileWalker is threaded output the file so we know which job exited. ossimNotify(ossimNotifyLevel_DEBUG) << M << "\nfile: " << file << "\nexited...\n"; } return result; } // End: omarDataMgrUtil::callAddRasterService( file ) bool omarDataMgrUtil::callRemoveRasterService( const ossimFilename& file ) { static const char M[] = "omarDataMgrUtil::callRemoveRasterService"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n" << "\nfile: " << file << "\n"; } bool result = false; if ( isPastLastAccessedThreshold( file ) ) { std::string service; getService( service ); std::string url; getUrl( url ); if ( service.size() && url.size() ) { CURL* curl = curl_easy_init(); if ( curl ) { // Data for POST: std::string data = std::string("filename=") + file.string(); curl_easy_setopt( curl, CURLOPT_POSTFIELDS, data.c_str() ); // Create the URL string: std::string urlString = url + service; curl_easy_setopt( curl, CURLOPT_URL, urlString.c_str() ); ossimNotify(ossimNotifyLevel_INFO) << "data: " << data << "\nurl: " << urlString.c_str() << std::endl; // Tell libcurl to follow redirection curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // Run it: CURLcode res = curl_easy_perform(curl); // Check for errors: if ( res == CURLE_OK ) { // Response code of the http transaction: long respcode; res = curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &respcode); if ( res == CURLE_OK ) { if ( respcode == 200 ) // OK 200 "The request was fulfilled." { result = true; // Set return status for caller. // Check for clean flag: if ( getCleanFlag() ) { clean( file ); } } } } else { ossimNotify(ossimNotifyLevel_WARN) << "curl_easy_perform() failed: \n" << curl_easy_strerror(res) << std::endl; setErrorStatus( (ossim_int32)res ); } ossimNotify(ossimNotifyLevel_WARN) << std::endl; // Always cleanup: curl_easy_cleanup(curl); } // Cleanup curl: curl_global_cleanup(); } // Matches: if ( service.size() ) } // Matches: if ( isPastLastAccessedThreshold( file ) ) if(traceDebug()) { // Since ossimFileWalker is threaded output the file so we know which job exited. ossimNotify(ossimNotifyLevel_DEBUG) << M << "\nfile: " << file << "\nexited...\n"; } return result; } // End: omarDataMgrUtil::callRemoveRasterService( file, clean ) void omarDataMgrUtil::clean( const ossimFilename& file ) const { // Remove files from disk: ossimFilename f = file; // Base image file: if ( f.exists() ) { ossimNotify(ossimNotifyLevel_NOTICE) << "\nRemoving file: " << f << "\n"; ossimFilename::remove( f ); } // Overview: ossimString e = "ovr"; f.setExtension( e ); if ( f.exists() ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Removing file: " << f << "\n"; ossimFilename::remove( f ); } // Histogram: e = "his"; f.setExtension( e ); if ( f.exists() ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Removing file: " << f << "\n"; ossimFilename::remove( f ); } // Omd file: e = "omd"; f.setExtension( e ); if ( f.exists() ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Removing file: " << f << "\n"; ossimFilename::remove( f ); } } bool omarDataMgrUtil::isFiltered(const ossimFilename& file) const { bool result = false; if ( file.size() ) { // Strip full path to base name. std::string baseName = file.file().string(); if ( baseName.size() ) { std::vector::const_iterator i = m_filteredImages.begin(); while ( i != m_filteredImages.end() ) { if ( baseName == (*i) ) { result = true; break; } ++i; } } } #if 0 /* Please leave for debug. (drb) */ if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimFileWalker::isFiltered file " << (result?"filtered: ":"not filtered: ") << file << "\n"; } #endif return result; } bool omarDataMgrUtil::keyIsTrue( const std::string& key ) const { bool result = false; if ( m_kwl.valid() ) { std::string value = m_kwl->findKey( key ); if ( value.size() ) { result = ossimString(value).toBool(); } } return result; } const std::vector& omarDataMgrUtil::getFilteredImages() const { return m_filteredImages; } std::vector& omarDataMgrUtil::getFilteredImages() { return m_filteredImages; } void omarDataMgrUtil::initializeDefaultFilterList() { m_mutex.lock(); // Common images to filter out, put most common first. m_filteredImages.push_back(std::string("icon.jpg")); m_filteredImages.push_back(std::string("logo.jpg")); m_filteredImages.push_back(std::string("preview.jpg")); m_mutex.unlock(); } void omarDataMgrUtil::dumpFilteredImageList() const { ossimNotify(ossimNotifyLevel_NOTICE) << "Filtered image list:\n"; std::vector::const_iterator i = m_filteredImages.begin(); while ( i != m_filteredImages.end() ) { ossimNotify(ossimNotifyLevel_NOTICE) << (*i) << "\n"; ++i; } ossimNotify(ossimNotifyLevel_NOTICE) << std::endl; } void omarDataMgrUtil::setDumpFilteredImageListFlag( bool flag ) { // Add this for hasRequiredOverview method. std::string key = DUMP_FILTERED_IMAGES_KW; std::string value = ( flag ? TRUE_KW : FALSE_KW ); addOption( key, value ); } bool omarDataMgrUtil::getDumpFilterImagesFlag() const { return keyIsTrue( DUMP_FILTERED_IMAGES_KW ); } bool omarDataMgrUtil::getCleanFlag() const { return keyIsTrue( CLEAN_KW ); } void omarDataMgrUtil::setOverrideFilteredImagesFlag( bool flag ) { std::string key = OVERRIDE_FILTERED_IMAGES_KW; std::string value = ( flag ? TRUE_KW : FALSE_KW ); addOption( key, value ); } bool omarDataMgrUtil::getOverrideFilteredImagesFlag() const { return keyIsTrue( OVERRIDE_FILTERED_IMAGES_KW ); } ossim-Miami-2.9.1/apps/curl_apps/omarDataMgrUtil.h000066400000000000000000000172321352751253100220600ustar00rootroot00000000000000//---------------------------------------------------------------------------- // File: omarDataMgrUtil.h // // License: See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: omarDataMgrUtil // // See class descriptions below for more. // //---------------------------------------------------------------------------- // $Id$ #ifndef omarDataMgrUtil_HEADER #define omarDataMgrUtil_HEADER 1 #include #include #include #include #include #include #include #include #include class ossimArgumentParser; class ossimFileWalker; class ossimGpt; class ossimImageHandler; class ossimPropertyInterface; /** * @brief omarDataMgrUtil class. * * Utility class for processing images recursively and calling OMAR * dataManager services upon successful open. */ class omarDataMgrUtil : public ossimReferenced, public ossimFileProcessorInterface { public: enum OmarDataMgrUtilService { UNKNOWN = 0, ADD_RASTER = 1, REMOVE_RASTER = 2 }; /** default constructor */ omarDataMgrUtil(); /** virtual destructor */ virtual ~omarDataMgrUtil(); /** * @brief Adds application arguments to the argument parser. * @param ap Parser to add to. */ void addArguments(ossimArgumentParser& ap); /** * @brief Initial method. * * Typically called from application prior to execute. This parses * all options and put in keyword list m_kwl. * * @param ap Arg parser to initialize from. * * @return true, indicating process should continue with execute. */ bool initialize(ossimArgumentParser& ap); /** * @brief Execute method. * * This launches file walking mechanism. * * @return int, 0 = good, non-zero something happened. Because this can * process multiple files a non-zero return may indicate just one file * did not complete, e.g. building overviews. * * @note Throws ossimException on error. */ ossim_int32 execute(); /** * @brief ProcessFile method. * * Satisfies pure virtual ossimFileProcessorInterface::processFile. * * This method is linked to the ossimFileWalker::walk method via a callback * mechanism. It is called by the ossimFileWalk (caller). In turn this * class (callee) calls ossimFileWalker::setRecurseFlag and * ossimFileWalker::setAbortFlag to control the waking process. * * @param file to process. */ virtual void processFile(const ossimFilename& file); /** * @brief Set number of threads to use. * * This is only used in execute method if a directory is given to * application to walk. * * @param threads Defaults to 1 if THREADS_KW is not found. */ void setNumberOfThreads( ossim_uint32 threads ); void setNumberOfThreads( const std::string& threads ); /** @return The list of filtered out files. */ const std::vector& getFilteredImages() const; /** * @brief Non const method to allow access for * adding or deleting extensions from the list. * * The list is used by the private isFiltered method to avoid trying to * process unwanted files. */ std::vector& getFilteredImages(); private: /** @return service as enumerated type. */ omarDataMgrUtil::OmarDataMgrUtilService getService() const; /** @brief Gets service string, e.g. /dataManager/addRaster. */ void getService(std::string& serviceString) const; /** @brief Gets url string, e.g. http://localhost:8080/omar */ void getUrl(std::string& url) const; /** * @brief Runs the curl command to call addRaster service. * @param file Image file. * @return true if http status code of 200(OK); else, false */ bool callAddRasterService( const ossimFilename& file ); /** * @brief Runs the curl command to call removeRaster service. * @param file Image file. * @return true if http status code of 200(OK); else, false */ bool callRemoveRasterService( const ossimFilename& file ); /** * @brief Removes files from disk. * * Triggered by the --clean option. * * Given: * base file = foo.ntf * * Currently removes: * foo.ntf * foo.ovr * foo.his * foo.omd * * There are no checks for multi-entry images or directory based image * files. */ void clean( const ossimFilename& file ) const; /** * @brief Convenience method to check file to see is if file should be * processed. * * @param f File to check. * * @return true if f is in filter list, false if not. */ bool isFiltered(const ossimFilename& f) const; /** * @brief Initializes the filter list with a default set of filtered out * file names. */ void initializeDefaultFilterList(); /** @brief Dumps filtered image list to std out. */ void dumpFilteredImageList() const; /** @brief Initializes arg parser and outputs usage. */ void usage(ossimArgumentParser& ap); /** * @return Threads to use. Defaults to 1 if THREADS_KW is not found. */ ossim_uint32 getNumberOfThreads() const; /** * @brief Adds option to m_kwl with mutex lock. * @param key * @param value */ void addOption( const std::string& key, ossim_uint32 value ); void addOption( const std::string& key, const std::string& value ); /** * @brief Sets the m_errorStatus for return on execute. */ void setErrorStatus( ossim_int32 status ); /** * @brief Sets the dump filteredImageList flag. * @param flag */ void setDumpFilteredImageListFlag( bool flag ); /** * @return true if DUMP_FILTERED_IMAGES_KW key is found and value is true; else, * false. * * DUMP_FILTERED_IMAGES_KW = "dump_filtered_images" */ bool getDumpFilterImagesFlag() const; /** * @return true if CLEAN_KW key is found and value is true; else, * false. * * CLEAN_KW = "clean" */ bool getCleanFlag() const; /** * @brief Sets the override filtered images flag. * @param flag */ void setOverrideFilteredImagesFlag( bool flag ); /** * @return true if DUMP_FILTERED_IMAGES_KW key is found and value is true; else, * false. * * DUMP_FILTERED_IMAGES_KW = "dump_filtered_images" */ bool getOverrideFilteredImagesFlag() const; /** * @return true if file is a directory based image and the stager should go * on to next directory; false if stager should continue with directory. */ bool isDirectoryBasedImage(const ossimImageHandler* ih) const; /** * @brief Checks file last access time against threshold. * * This check for option key "access_time_threshold", value in days. If * found will return true if files last access time is greater than the * threshold days. If key is not set the default return is true. * * @return true if file is past last accessed threshold. */ bool isPastLastAccessedThreshold( const ossimFilename& file ) const; /** @return true if key is set to true; false, if not. */ bool keyIsTrue( const std::string& key ) const; /** Holds all options passed into intialize except writer props. */ ossimRefPtr m_kwl; ossimFileWalker* m_fileWalker; std::mutex m_mutex; ossimRefPtr m_imageUtil; ossim_int32 m_errorStatus; /** Hold images we never want to process. */ std::vector m_filteredImages; }; #endif /* #ifndef omarDataMgrUtil_HEADER */ ossim-Miami-2.9.1/apps/ossim-adrg-dump/000077500000000000000000000000001352751253100176665ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-adrg-dump/CMakeLists.txt000066400000000000000000000003231352751253100224240ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-adrg-dump INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-adrg-dump/ossim-adrg-dump.cpp000066400000000000000000000046241352751253100234100ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero // //******************************************************************* // $Id: ossim-adrg-dump.cpp 15122 2009-08-22 15:41:57Z dburken $ #include #include #include using namespace std; // Common includes. #include #include #include #include #include #include #include // Application specfic includes. // #include "imaging/formats/adrg/ossimAdrgZdr.h" #include //*** // Static trace for debugging //*** static ossimTrace traceDebug("adrg_header_dump:debug"); int main(int argc, char* argv[]) { ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()-> setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()-> setDescription(argumentParser.getApplicationName()+" This application dumps to screen the contents of an ADRG Header (.gen) file."); argumentParser.getApplicationUsage()-> setCommandLineUsage(argumentParser.getApplicationName()+" [options] <.imgfile> "); // Parse command line arguments. // ossimInit::instance()->initialize(argc, argv); if (argumentParser.read("-h") || argumentParser.read("--help")||(argumentParser.argc() != 2)) { argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_NOTICE)); exit(0); } // ADRG header file. ossimFilename f = ossimFilename(argv[1]); if(traceDebug()) cout << "Trying to open header: " << f << endl; // Instantiate support data class to parse all needed header files. ossimAdrgHeader* theAdrgHeader = new ossimAdrgHeader(f); // ossimAdrgZdr* theAdrgHeader = new ossimAdrgZdr(f); // Check for errors. if(theAdrgHeader->errorStatus()) { if (traceDebug()) { cerr << "Error in ossimAdrg header detected. " << endl; } exit(1); } // Dump header to stdout. cout << *theAdrgHeader << endl; delete theAdrgHeader; exit(0); } ossim-Miami-2.9.1/apps/ossim-applanix2ogeom/000077500000000000000000000000001352751253100207335ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-applanix2ogeom/CMakeLists.txt000066400000000000000000000003301352751253100234670ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-applanix2ogeom INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-applanix2ogeom/ossim-applanix2ogeom.cpp000066400000000000000000000235571352751253100255300ustar00rootroot00000000000000 //---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Applinix to ossim geometry. // // Application to create an ossim geometry file from Applanix // support data files. // //---------------------------------------------------------------------------- // $Id: applanix2ogeom.cpp 13025 2008-06-13 17:06:30Z sbortman $ #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include static const ossimTrace traceDebug(ossimString("applanix2ogeom:debug")); bool processImage(ossimApplanixEOFile& eo, const ossimKeywordlist& kwl, const ossimString& id, const ossimFilename& outputDir); int main(int argc, char* argv[]) { static const char MODULE[] = "applanix2ogeom"; std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); bool outputDirOverrideFlag = false; ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->setApplicationName( argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription( argumentParser.getApplicationName()+ " Creates ossim geometry file from Applannix support data."); argumentParser.getApplicationUsage()->setCommandLineUsage( argumentParser.getApplicationName()+ " "); argumentParser.getApplicationUsage()->addUsageExplanation( ossimApplicationUsage::OSSIM_COMMAND_LINE_OPTION, std::string("camera_file"), std::string("Serial number specific keyword list with camera parameters.")); argumentParser.getApplicationUsage()->addUsageExplanation( ossimApplicationUsage::OSSIM_COMMAND_LINE_OPTION, std::string("exterior_orientation_file"), std::string("Applanix exterior orientation file.")); argumentParser.getApplicationUsage()->addUsageExplanation( ossimApplicationUsage::OSSIM_COMMAND_LINE_OPTION, std::string("imageToProcess"), std::string("Image to create geometry for. If not present then all geometries are created")); argumentParser.getApplicationUsage()->addUsageExplanation( ossimApplicationUsage::OSSIM_COMMAND_LINE_OPTION, std::string("option_output_directory"), std::string("Option directory to output geometry file(s) to. If not set the imageToProcess directory will be used.")); argumentParser.getApplicationUsage()->addCommandLineOption( "-h or --help", "Shows help"); //--- // Extract optional arguments. //--- if(argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(std::cout); exit(0); } argumentParser.reportRemainingOptionsAsUnrecognized(); if (argumentParser.errors()) { argumentParser.writeErrorMessages(std::cout); exit(1); } // cout << "argc: " << argumentParser.argc() << endl; if(argumentParser.argc() < 4) { argumentParser.getApplicationUsage()->write(std::cout); exit(1); } // if(argumentParser.argc() == 4) // { // if(!ossimFilename(argumentParser.argv()[3]).isDir()) // { // ossimNotify(ossimNotifyLevel_WARN) << "for the 3 argument option the last argument must be a directory" << std::endl; // exit(0); // } // } ossimFilename cameraFile = argumentParser.argv()[1]; ossimFilename eoFile = argumentParser.argv()[2]; ossimFilename imageToProcess; ossimFilename outputDir; ossim_uint32 maxIdx = argumentParser.argc(); if (argumentParser.argc() > 4) { outputDir = argumentParser.argv()[argumentParser.argc()-1]; if (outputDir.isDir() == false) // doesn't exist { --maxIdx; if (outputDir.createDirectory() == false) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nCould not create directory: " << outputDir << endl; exit(1); } } outputDirOverrideFlag = outputDir.exists(); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\ncamera file: " << cameraFile << "\neo file: " << eoFile << endl; } // Keyword list to pass to model loadState. ossimKeywordlist kwl; // Open up the exterior orientation file. ossimApplanixEOFile eo; if (eo.parseFile(eoFile) == false) { ossimNotify(ossimNotifyLevel_WARN) << "Could not open: " << eoFile << endl; exit(1); } eo.indexRecordIds(); if(argc >4) { ossim_uint32 idx = 0; for(idx = 3; idx < maxIdx; ++idx) { kwl.clear(); // Add the eo_file keyword to the keyword list. kwl.add("eo_file", eoFile.c_str(), true); // Add the eo_file keyword to the keyword list. kwl.add("camera_file", cameraFile.c_str(), true); kwl.add("compute_gsd_flag", true, true); // See if the ID is in the eo file. imageToProcess = argumentParser.argv()[idx]; ossimString id = imageToProcess.fileNoExtension(); ossimRefPtr rec = eo.getRecordGivenId(id); if (!rec) { ossimNotify(ossimNotifyLevel_WARN) << "applanix2ogeom ERROR:" << "\nMatching id for imageToProcess not found in eo file!" << "\nfile: " << imageToProcess << "\nid: " << id << "\nReturning..." << endl; exit(1); } kwl.add("image_id", id, true); if (!outputDirOverrideFlag) { outputDir = imageToProcess.path(); } processImage(eo, kwl, id, outputDir); } } else if(argc <=4) { outputDir = argumentParser.argv()[argumentParser.argc()-1]; if(!outputDir .isDir()) { ossimFilename idFile = outputDir.file(); outputDir = outputDir.path(); idFile = idFile.setExtension(""); const ossimRefPtr rec = eo.getRecordGivenId(idFile); if(rec.valid()) { // Add the eo_file keyword to the keyword list. kwl.add("eo_file", eoFile.c_str(), true); kwl.add("eo_id", idFile.c_str(), true); // Add the eo_file keyword to the keyword list. kwl.add("camera_file", cameraFile.c_str(), true); kwl.add("compute_gsd_flag", true, true); processImage(eo, kwl, idFile, outputDir); } } else { ossim_uint32 idx = 0; ossim_uint32 nRecords = eo.getNumberOfRecords(); ossim_int32 idIdx = eo.getFieldIdx("ID"); if(idIdx >= 0) { for(idx = 0; idx < nRecords; ++idx) { const ossimRefPtr rec = eo.getRecord(idx); if(rec.valid()) { ossimString id = (*rec)[idIdx]; // Add the eo_file keyword to the keyword list. kwl.add("eo_file", eoFile.c_str(), true); kwl.add("eo_id", id.c_str(), true); // Add the eo_file keyword to the keyword list. kwl.add("camera_file", cameraFile.c_str(), true); kwl.add("compute_gsd_flag", true, true); processImage(eo, kwl, id, outputDir); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "NO ID RECORD FOUND!!" << std::endl; exit(0); } } } return 0; } bool processImage(ossimApplanixEOFile& eo, const ossimKeywordlist& kwl, const ossimString& id, const ossimFilename& outputDir) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "applanix2ogeom:processImage DEBUG:" << "\nkwl:\n" << kwl << endl; } // ossimRefPtr model = new ossimApplanixEcefModel; ossimRefPtr model; if(eo.isUtmFrame()) { model = new ossimApplanixUtmModel; } else { model = new ossimApplanixEcefModel; } if (model->loadState(kwl) == false) { ossimNotify(ossimNotifyLevel_WARN) << "applanix2ogeom:processImage ERROR:" << "\nossimApplanixEcefModel::loadState failded for id: " << id << endl; return false; } ossimFilename geomFile = id; geomFile.setExtension(ossimString(".geom")); if (outputDir != ossimFilename::NIL) { geomFile = outputDir.dirCat(geomFile); } ossimKeywordlist geomKwl; model->saveState(geomKwl); if (geomKwl.write(geomFile.c_str()) == false) { ossimNotify(ossimNotifyLevel_WARN) << "applanix2ogeom:processImage ERROR:" << "\nCould not write file: " << geomFile << endl; return false; } else { ossimNotify(ossimNotifyLevel_NOTICE) << "Wrote file: " << geomFile << endl; } return true; } ossim-Miami-2.9.1/apps/ossim-autreg/000077500000000000000000000000001352751253100172755ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-autreg/CMakeLists.txt000066400000000000000000000003201352751253100220300ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-autreg INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-autreg/ossim-autreg.cpp000066400000000000000000000051061352751253100224220ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossim-autreg.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Hicks // // Description: Autonomous registration. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug = ossimTrace("ossim-autreg:debug"); int main(int argc, char *argv[]) { // Start the timer. ossimTimer::instance()->setStartTick(); //--- // Get the arg count so we can tell if an arg was consumed by // ossimInit::instance()->initialize //--- int originalArgCount = argc; ossimArgumentParser ap(&argc, argv); // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); //--- // Avoid going on if a global option was consumed by ossimInit::initialize // like -V or --version option and the arg count is down to 1. //--- if ( ( ap.argc() > 1 ) || ( ap.argc() == originalArgCount ) ) { ossimRefPtr autreg = new ossimAutRegUtil; try { //--- // NOTE: ossimAutRegUtil::initialize handles the application usage which will // false, to end things if certain options (e.g. "--help") are provided. // // ossimAutRegUtil::initialize can throw an exception. //--- bool goAhead = autreg->initialize(ap); if (goAhead) { // ossimAutRegUtil::execute can throw an excepion. autreg->execute(); ossimNotify(ossimNotifyLevel_NOTICE) << "elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << endl; } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; exit(1); } } // End: if ( ( ap.argc() > 1 ) ... exit(0); } // End of main... ossim-Miami-2.9.1/apps/ossim-band-merge/000077500000000000000000000000001352751253100200075ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-band-merge/CMakeLists.txt000066400000000000000000000003241352751253100225460ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-band-merge INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-band-merge/ossim-band-merge.cpp000066400000000000000000000232501352751253100236460ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Merges input images together into output image. Images must be of // same scalar type and same number of bands. If image width is different // output image will be expanded to the largest input image width. // //******************************************************************* // $Id: band_merge.cpp 10695 2007-04-12 13:56:50Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("band_merge:main"); static void usage(); static void outputWriterTypes(); int main(int argc, char* argv[]) { static const char MODULE[] = "band_merge:main"; std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" merges band separate images to one image"); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("-o or --create-overview", "Creates and overview for the output image"); argumentParser.getApplicationUsage()->addCommandLineOption("-w or --tile-width", "Defines the tile width for the handlers that support tiled output"); if (traceDebug()) CLOG << " Entered..." << std::endl; if (argumentParser.read("-h") || argumentParser.read("--help")||(argumentParser.argc() < 2)) { argumentParser.getApplicationUsage()->write(std::cout); usage(); // for writer output types exit(0); } // Keyword list to initialize image writers with. ossimKeywordlist kwl; const char* PREFIX = "imagewriter."; ossim_uint32 tile_width = 32; bool create_overview = false; if (argumentParser.read("-o") || argumentParser.read("--crate-overview")) { create_overview = true; std::cout << "\nOutput overview building enabled." << std::endl; } if (argumentParser.read("-w", stringParam) || argumentParser.read("-tile-width", stringParam)) { tile_width = ossimString(tempString).toInt(); if ((tile_width % 16) != 0) { cerr << MODULE << " NOTICE:" << "\nTile width must be a multiple of 16!" << "\nDefaulting to 128" << std::endl; tile_width = 0; } std::cout << "Tile width set to: " << tile_width << std::endl; } argumentParser.reportRemainingOptionsAsUnrecognized(); // Three required args: output_type, input file, and output file. if (argumentParser.errors()) { argumentParser.writeErrorMessages(std::cout); exit(0); } if (argumentParser.argc() == 1) { argumentParser.getApplicationUsage()->write(std::cout); usage(); // for writer output types exit(0); } ossim_uint32 number_of_source_images = argumentParser.argc() - 3; if (traceDebug()) { CLOG << "DEBUG:" << "\nargc: " << argumentParser.argc() << "\nnumber_of_source_images: " << number_of_source_images << "\ntile_width: " << tile_width << "\ncreate_overview: " << (create_overview?"true":"false") << std::endl; } ossimString output_type = argv[1]; output_type.downcase(); std::cout << "Output type: " << output_type << std::endl; // Create the vector of image handlers. ossimConnectableObject::ConnectableObjectList ihs; for(ossim_uint32 h = 0; h < number_of_source_images; ++h) { ossimFilename f = argv[h + 2]; std::cout << "Input_image[" << h << "]: " << f << std::endl; ihs.push_back(ossimImageHandlerRegistry::instance()->open(f)); } // Get the output file. ossimFilename output_file = argv[argumentParser.argc() - 1]; std::cout << "Output file: " << output_file << std::endl; //--- // Set the output writer type and the image type. //--- kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str()); ossimRefPtr bm = new ossimBandMergeSource(ihs); ossimRefPtr fileWriter = ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX); if(!fileWriter) { bm->disconnect(); bm = 0; ossimConnectableObject::ConnectableObjectList::iterator i = ihs.begin(); while (i != ihs.end()) { (*i)->disconnect(); (*i) = 0; ++i; } cerr << "Error making an image writer..." << "\nExiting application..." << std::endl; exit(1); } // Write out a geometry file for new image. ossimKeywordlist bm_geom; ossimRefPtr geom = bm->getImageGeometry(); geom->saveState(bm_geom); ossimFilename geom_file = output_file; geom_file.setExtension("geom"); bm_geom.write(geom_file); fileWriter->connectMyInputTo(0, bm.get()); if (tile_width) { // Set the tile size... fileWriter->setTileSize(ossimIpt(tile_width, tile_width)); } fileWriter->open(output_file); ossimStdOutProgress prog(2); fileWriter->addListener(&prog); fileWriter->setAreaOfInterest(bm->getBoundingRect()); if( fileWriter->canCastTo("ossimTiffWriter") ) { // ossimTiffWriter* twriter = PTR_CAST(ossimTiffWriter, fileWriter); if(fileWriter.valid()) { try { fileWriter->execute(); } catch(std::exception& e) { ossimNotify(ossimNotifyLevel_DEBUG) << "band_merge: ERROR exception caught:\n" << e.what() << std::endl; } catch (...) { ossimNotify(ossimNotifyLevel_DEBUG) << "band_merge: ERROR - Unknown exception caught!" << std::endl; } } } else if(fileWriter->canCastTo("ossimJpegWriter")) { ossimRefPtr remapper = NULL; if(PTR_CAST(ossimJpegWriter, fileWriter.get()) && (bm->getOutputScalarType() != OSSIM_UCHAR)) { remapper = new ossimScalarRemapper(bm.get(), OSSIM_UCHAR); remapper->initialize(); fileWriter->connectMyInputTo(0, remapper.get()); } fileWriter->initialize(); try { fileWriter->execute(); } catch(std::exception& e) { ossimNotify(ossimNotifyLevel_DEBUG) << "band_merge: ERROR exception caught:\n" << e.what() << std::endl; } catch (...) { ossimNotify(ossimNotifyLevel_DEBUG) << "band_merge: ERROR - Unknown exception caught!" << std::endl; } } else { try { fileWriter->execute(); } catch(std::exception& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "band_merge: ERROR exception caught:\n" << e.what() << std::endl; } } catch (...) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "band_merge: ERROR - Unknown exception caught!" << std::endl; } } } if (create_overview == true) { fileWriter->writeOverviewFile(); } fileWriter->disconnect(); fileWriter = 0; bm = 0; ossimConnectableObject::ConnectableObjectList::iterator it = ihs.begin(); while (it != ihs.end()) { (*it)->disconnect(); (*it) = 0; ++it; } exit(0); } void usage() { std::cout << "band_merge: Band Merge\n" << "Usage:\n" << "band_merge [-h][-o][-w tile_width] " << " ... " << "\n\nOptional argument list:" << "\n -h -- display Usage/Help" << "\n -o -- create an ossim overview file with output file" << "\n -w -- tile width (default = 32)" << "\n" << "\nNOTES:" << "\n\"-w\" option only valid with tiff type." << "\n\"Tile width must be a multiple of 32." << "\nValid output writer types:" << "\n"; outputWriterTypes(); } void outputWriterTypes() { ossimImageTypeLut lut; ossim_uint32 index = 0; ossimString type = lut.getTableIndexString(index); while (type.size()) { std::cout << "\t" << type << std::endl; ++index; type = lut.getTableIndexString(index); } std::cout << std::endl; } ossim-Miami-2.9.1/apps/ossim-btoa/000077500000000000000000000000001352751253100167335ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-btoa/CMakeLists.txt000066400000000000000000000003161352751253100214730ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-btoa INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-btoa/ossim-btoa.cpp000066400000000000000000000143251352751253100215210ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Ken Melero // Originally written by Oscar Kramer. // // Description: This app displays a binary file in a nice // formatted view. Very helpful for finding offsets of // binary headers. // //******************************************************************** // $Id: ossim-btoa.cpp 22209 2013-03-29 13:38:38Z dburken $ #include #include #include #include #include using namespace std; // Regular print with offset, hex, and ascii section. static void print( FILE* fptr, bool isEbcdic ) { int offset = 0; unsigned char bin_data[16]; char asc_data[17]; int hex_data[16]; int nbytes; int i; asc_data[16] = '\0'; ossimEbcdicToAscii* e2a = 0; if ( isEbcdic ) { e2a = new ossimEbcdicToAscii; } while (!feof(fptr)) { nbytes = (int)fread(bin_data, 16, 1, fptr); for(i=0; i<16; i++) { hex_data[i] = (int) bin_data[i]; if (e2a) { bin_data[i] = e2a->ebcdicToAscii(bin_data[i]); } if ((bin_data[i] >= 0x20) && (bin_data[i] < 0x7F)) // 0x7F is a DEL { asc_data[i] = bin_data[i]; } else { asc_data[i] = '.'; } } printf("%06d %02X %02X %02X %02X %02X %02X %02X %02X " "%02X %02X %02X %02X %02X %02X %02X %02X %16s\n", offset, hex_data[0], hex_data[1], hex_data[2], hex_data[3], hex_data[4], hex_data[5], hex_data[6], hex_data[7], hex_data[8], hex_data[9], hex_data[10], hex_data[11], hex_data[12], hex_data[13], hex_data[14], hex_data[15], asc_data); offset += 16; } if (e2a) { delete e2a; e2a = 0; } } // End: print(...) // Wide print offset and ascii section only. static void printWide( FILE* fptr, bool isEbcdic ) { const int WIDTH = 64; int offset = 0; unsigned char bin_data[WIDTH]; char asc_data[WIDTH+1]; int nbytes; int i = 0; asc_data[WIDTH] = '\0'; ossimEbcdicToAscii* e2a = 0; if ( isEbcdic ) { e2a = new ossimEbcdicToAscii; } while (!feof(fptr)) { nbytes = (int)fread(bin_data, WIDTH, 1, fptr); for( i = 0; i < WIDTH; ++i ) { if (e2a) { bin_data[i] = e2a->ebcdicToAscii(bin_data[i]); } if ((bin_data[i] >= 0x20) && (bin_data[i] < 0x7F)) // 0x7F is a DEL { asc_data[i] = bin_data[i]; } else { asc_data[i] = '.'; } } printf("%06d %64s\n", offset, asc_data); offset += WIDTH; } if (e2a) { delete e2a; e2a = 0; } } // End printWide( ... ) // Wide print ascii section only. static void printAscii( FILE* fptr, bool isEbcdic ) { const int WIDTH = 80; int offset = 0; unsigned char bin_data[WIDTH]; char asc_data[WIDTH+1]; int nbytes; int i = 0; asc_data[WIDTH] = '\0'; ossimEbcdicToAscii* e2a = 0; if ( isEbcdic ) { e2a = new ossimEbcdicToAscii; } while (!feof(fptr)) { nbytes = (int)fread(bin_data, WIDTH, 1, fptr); for( i = 0; i < WIDTH; ++i ) { if (e2a) { bin_data[i] = e2a->ebcdicToAscii(bin_data[i]); } if ((bin_data[i] >= 0x20) && (bin_data[i] < 0x7F)) // 0x7F is a DEL { asc_data[i] = bin_data[i]; } else { asc_data[i] = '.'; } } printf( "%80s\n", asc_data ); offset += WIDTH; } if (e2a) { delete e2a; e2a = 0; } } // printAscii int main(int argc, char** argv) { // Parse the args: ossimArgumentParser argumentParser(&argc, argv); enum PrintMode { ALL = 0, // offsets hex ascii - default WIDE = 1, // offsets ascii - "-w" option ASCII = 2 // ascii - "-a" option }; // Check for options: bool isEbcdic = false; PrintMode mode = ALL; if ( argumentParser.read("-e") ) { isEbcdic = true; } if ( argumentParser.read("-w") ) { mode = WIDE; } if ( argumentParser.read("-a") ) { if ( mode != ALL ) { std::cerr << "Cannot use -a and -w options." << std::endl; return -1; } mode = ASCII; } if ( argumentParser.read("-h") || argumentParser.read("--help")) { std::cout << "\nDisplays a binary file as ASCII/hexadecimal. If no input file is provided, then\n" << "input is taken from stdin. Non-ascii characters are printed as dot in ascii output.\n" << "Default mode prints offsets, hex and ascii data.\n\n" << "Usage: btoa [options] []\n\n" << "Options:\n\n" << " -e Indicates text characters are ebcdic and should be" << " converted to ascii.\n" << " -h, --help Shows this usage\n" << " -a Ascii mode, prints 64 characters wide with no offset or hex data.\n" << " -w Wide mode, prints offset and 64 characters wide with no hex data.\n" << std::endl; return 0; } FILE* fptr = 0; if (argumentParser.argc() > 1) { fptr = fopen(argv[argumentParser.argc() - 1], "rb"); if (fptr == 0) { std::cout << "\nError opening file " << argv[argumentParser.argc() - 1] << std::endl << std::endl; return -1; } } else fptr = stdin; if ( mode == WIDE ) { printWide( fptr, isEbcdic ); } else if ( mode == ASCII ) { printAscii( fptr, isEbcdic ); } else // default { print( fptr, isEbcdic ); } fclose (fptr); return 0; } // End: main( ... ) ossim-Miami-2.9.1/apps/ossim-chgkwval/000077500000000000000000000000001352751253100176145ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-chgkwval/CMakeLists.txt000066400000000000000000000003221352751253100223510ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-chgkwval INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-chgkwval/ossim-chgkwval.cpp000066400000000000000000000044621352751253100232640ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Ken Melero // // Description: Changes the value of a keyword within a keyword list to // value passed in by user. // //******************************************************************** // $Id: chgkwval.cpp 13083 2008-06-25 19:45:41Z dburken $ #include #include #include int main(int argc, char* argv[]) { enum { OK = 0, ERROR = 1 }; int status = OK; if ( argc == 4 ) { ossimFilename kwlFile = argv[1]; ossimKeywordlist kwl; if ( kwlFile.exists() ) { // Open existing keyword list. if ( kwl.addFile( kwlFile ) == false ) { status = ERROR; std::cerr << "Error opening keyword list: " << kwlFile << std::endl; } } if ( status == OK ) { std::string key = argv[2]; std::string value = argv[3]; // Add or change the value of keyword in the keyword list. kwl.addPair( key, value, true ); // Create or re-write the file. kwl.write(kwlFile); std::cout << "Added or changed key: \"" << key << "\" with value: \"" << value << "\" in " << kwlFile << std::endl; } } else // Usage: { std::cout << "Usage: chgkwval \n" << "Changes the keyword value within the keyword list to " << "value specified.\n" << "Example: chgval band1.spec area.size \"pixels 7689 8031\"\n" << "Changes the keyword value of area.size to pixels 7689 8031\n\n" << "Note 1: Use no colon \":\" after the keyword.\n" << "Note 2: If the keyword is present in the keyword list it will\n" << " be overwritten.\n" << "Note 3: If the keyword is not in the keyword list it will" << " be added.\n" << "Note 4: Enclose value in double quotes if it is more than one" << " string.\n" << "Note 5: Will create file if doesn't exists.\n" << std::endl; } return status; } ossim-Miami-2.9.1/apps/ossim-chipper/000077500000000000000000000000001352751253100174405ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-chipper/CMakeLists.txt000066400000000000000000000003211352751253100221740ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-chipper INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-chipper/ossim-chipper.cpp000066400000000000000000000053551352751253100227360ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossim-chipper.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Utility class definition for processing digital elevation models(dems). // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include /* for exit */ #include #include using namespace std; static ossimTrace traceDebug = ossimTrace("ossim-chipper:debug"); int main(int argc, char* argv[]) { ossimTimer timer; // Start the timer. ossimTimer::Timer_t tickStart = timer.tick(); //--- // Get the arg count so we can tell if an arg was consumed by // ossimInit::instance()->initialize //--- int originalArgCount = argc; ossimArgumentParser ap(&argc, argv); // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); //--- // Avoid going on if a global option was consumed by ossimInit::initialize // like -V or --version option and the arg count is down to 1. //--- if ( ( ap.argc() > 1 ) || ( ap.argc() == originalArgCount ) ) { // Make the generator. ossimRefPtr chipper = new ossimChipperUtil; try { //--- // NOTE: ossimChipperUtil::initialize handles the application usage which will // false, to end things if certain options (e.g. "--help") are provided. // // ossimChipperUtil::initialize can throw an exception. //--- bool continue_after_init = chipper->initialize(ap); if (continue_after_init) { // ossimChipperUtil::execute can throw an excepion. chipper->execute(); ossimTimer::Timer_t tickEnd = timer.tick(); ossimNotify(ossimNotifyLevel_NOTICE) << "elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(3) << timer.delta_s(tickStart, tickEnd) << endl; } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; exit(1); } } // End: if ( ( ap.argc() > 1 ) ... exit(0); } // End of main... ossim-Miami-2.9.1/apps/ossim-cli/000077500000000000000000000000001352751253100165555ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-cli/CMakeLists.txt000066400000000000000000000003151352751253100213140ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-cli INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-cli/ossim-cli.cpp000077500000000000000000000113041352751253100211620ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include using namespace std; #include #include #include #include #include #include #include #include #define CINFO ossimNotify(ossimNotifyLevel_INFO) #define CWARN ossimNotify(ossimNotifyLevel_WARN) #define CFATAL ossimNotify(ossimNotifyLevel_FATAL) void showAvailableCommands() { ossimToolFactoryBase* factory = ossimToolRegistry::instance(); map capabilities; factory->getCapabilities(capabilities); map::iterator iter = capabilities.begin(); CINFO<<"\nAvailable commands:\n"<first<<" -- "<second< [command options and parameters]\n" << " "<\n" << " "< -- To get help on specific command."< utility = factory->createTool(command); if (!utility.valid()) { CWARN << "\nDid not understand command <"<"<setStartTick(); if (!utility->initialize(ap)) { CWARN << "\nCould not execute command <"< with arguments and options " "provided."<helpRequested()) return true; if (!utility->execute()) { CWARN << "\nAn error was encountered executing the command. Check options."<time_s()<<" s.\n"<setApplicationName(argv[0]); bool status_ok = true; try { // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); do { if (argc == 1) { // Blank command line: usage(argv[0]); break; } // Spec file provided containing command's arguments and options? ossimString argv1 = argv[1]; if (( argv1 == "--spec") && (argc > 2)) { // Command line provided in spec file: ifstream ifs (argv[2]); if (ifs.fail()) { CWARN<<"\nCould not open the spec file at <"<\n"<> spec; ifs.close(); ossimArgumentParser new_ap(spec); status_ok = runCommand(new_ap); break; } // Need help with app or specific command? if (argv1.contains("help")) { // If no command was specified, then general usage help shown: if (argc == 2) { // Blank command line: usage(argv[0]); break; } else { // rearrange command line for individual utility help: ostringstream cmdline; cmdline< #include #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const ossimTrace traceDebug(ossimString("cmm:debug")); //************************************************************************** // usage() //************************************************************************** void usage() { ossimNotify(ossimNotifyLevel_INFO) << "\nNOTES:" << "\n - Default output is to a \".omd\" file so if the image was" << " \"foo.tif\" you\n will get a \"foo.omd\"." << "\n - If the .omd file exists already this will open it and add" << "\n or, overwrite the min, max keywords only." << "\n - If the -p option is used no .omd file will be written." << endl; return; } bool isInImageEntryList(const std::vector& imageEntryList, ossim_uint32 entry) { for(ossim_uint32 i=0; iinitialize //--- int originalArgCount = argc; ossimString tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); if ( (ap.argc() == 1) && (originalArgCount > 1) ) { exit(0); // ossimInit consumed all options. } ap.getApplicationUsage()->setApplicationName(ap.getApplicationName()); ap.getApplicationUsage()->setDescription(ap.getApplicationName()+" will force a recompute of Min/Max Pixel Values."); ap.getApplicationUsage()->setCommandLineUsage(ap.getApplicationName()+" \nThis program will force a recompute of Min/Max Pixel Values.\n"); ap.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); ap.getApplicationUsage()->addCommandLineOption("-p","print values to standard output"); ap.getApplicationUsage()->addCommandLineOption("-e or --entry","Give the entry(zero based) to compute min / max for.\nNOTE: Option only valid with a single file."); ap.getApplicationUsage()->addCommandLineOption("-l or --list-entries","Lists the entries within the image and returns without doing anything else."); ap.getApplicationUsage()->addCommandLineOption("-o", "Write omd to file specified. If used on a multi-entry file, given \"foo.omd\" you will get: \"foo_e0.omd\""); ap.getApplicationUsage()->addCommandLineOption("--min","Hard coded min value for all bands"); ap.getApplicationUsage()->addCommandLineOption("--max","Hard coded max value for all bands"); ap.getApplicationUsage()->addCommandLineOption("--null","Hard coded null value for all bands"); ap.getApplicationUsage()->addCommandLineOption("--reader-prop ", "Adds a property to send to the reader. format is name=value"); bool out_data = false; bool listEntriesFlag = false; double nullValue = ossim::nan(); double minValue = ossim::nan(); double maxValue = ossim::nan(); bool hasNull = false; ossimFilename outputFile; std::vector entryList; if (ap.read("-h") || ap.read("--help")||(ap.argc() < 2)) { ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_WARN)); usage(); exit(0); } if(ap.read("--min", stringParam)) { minValue = tempString.toDouble(); } if(ap.read("--max", stringParam)) { maxValue = tempString.toDouble(); } if(ap.read("--null", stringParam)) { nullValue = tempString.toDouble(); if ( !ossim::isnan(nullValue) ) { hasNull = true; } } if(ap.read("-p")) { out_data = true; } if(ap.read("-l") || ap.read("--list-entries")) { listEntriesFlag = true; } if( ap.read("-o", stringParam) ) { outputFile = tempString.trim(); } while(ap.read("-e", stringParam) || ap.read("--entry", stringParam)) { ossim_uint32 entryNumber = ossimString(tempString).toUInt32(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:" << "\nentryNumber: " << entryNumber << endl; } entryList.push_back(entryNumber); } std::map readerPropertyMap; while(ap.read("--reader-prop", stringParam)) { std::vector nameValue; ossimString(tempString).split(nameValue, "="); if(nameValue.size() == 2) { readerPropertyMap.insert( std::make_pair(nameValue[0], nameValue[1]) ); } } ap.reportRemainingOptionsAsUnrecognized(); if(argc == 1) { usage(); exit(1); } // Default variables ossim_uint32 fileCount = argc - 1; // Check for -e option with multiple images. if ( (fileCount > 1) && entryList.size() ) { ossimNotify(ossimNotifyLevel_WARN) << "Entry option only valid with a single file!" << endl; exit(1); } ossim_uint32 idx = 1; for(idx = 1; idx <= fileCount; ++idx) { // Get the image file name. ossimFilename img_file(argv[idx]); ossimNotify(ossimNotifyLevel_INFO) << "Processing image file: " << img_file << endl; // Instantiate image to see if it is supported. ossimRefPtr ih; ih = ossimImageHandlerRegistry::instance()->open(img_file); // Error checking. if (!ih.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "Unsupported image file: " << img_file << endl; continue; // Go to next file. } // Error checking. if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN) << "Error reading image: " << img_file << endl; continue; // Go to next file. } // Set the reader properties if any. if ( readerPropertyMap.size() ) { ossimPropertyInterface* pi = (ossimPropertyInterface*)ih.get(); std::map::iterator iter = readerPropertyMap.begin(); while(iter != readerPropertyMap.end()) { pi->setProperty(iter->first, iter->second); ++iter; } } // Get the list of entries that this image has. std::vector imageEntryList; ih->getEntryList(imageEntryList); if (listEntriesFlag) { std::cout << "File " << img_file << " entries:\n"; std::copy(imageEntryList.begin(), imageEntryList.end(), std::ostream_iterator(std::cout, " ")); std::cout << std::endl; continue; // Go to next file. } //--- // If no entry (-e option) was given assume to do all entries. //--- if(entryList.size() == 0) { for(ossim_uint32 imageEntryIdx = 0; imageEntryIdx < imageEntryList.size(); ++imageEntryIdx) { entryList.push_back(imageEntryList[imageEntryIdx]); } } for(ossim_uint32 entryIdx = 0; entryIdx < entryList.size(); ++entryIdx) { if(isInImageEntryList(imageEntryList, entryList[entryIdx]) == false) { ossimNotify(ossimNotifyLevel_WARN) << "Entry not found: " << entryList[entryIdx] << endl; continue; // Go to next entry. } ossimNotify(ossimNotifyLevel_INFO) << "Computing min/max for entry number: " << entryList[entryIdx] << endl; // Select the entry. ih->setCurrentEntry(entryList[entryIdx]); // Build the .omd file name. ossimFilename omd_file; if (outputFile.size()) { omd_file = outputFile; } else { omd_file = img_file; } if(imageEntryList.size() > 1) { ossim_uint32 currentEntry = ih->getCurrentEntry(); omd_file.setExtension(""); omd_file += "_e"; omd_file += ossimString::toString(currentEntry); //--- // Note: Set extension was not used here deliberately to avoid // messing // up a MODIS file in hdf format with multiple '.'s in the file // name. //--- omd_file += ".omd"; } else { omd_file.setExtension("omd"); } ossimRefPtr is = new ossimImageSourceSequencer(ih.get()); //--- // Note: getImageTileWidth/Height will return zero if the image is not // intenally tiles. //--- ossimIpt tileWidthHeight(ih->getImageTileWidth(), ih->getImageTileHeight()); if (!tileWidthHeight.x) { // make the sequencer read entire strips from the image handler // at a time. This will speed up access time for strip images // tileWidthHeight.x = ih->getBoundingRect().width(); } if(!tileWidthHeight.y) { tileWidthHeight.y = ih->getTileHeight(); } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Sequencer tile size: " << tileWidthHeight << endl; } is->setTileSize(tileWidthHeight); //--- // Make arrays of doubles to hold the min/max values. // Initialize mins to default maxes and maxes to default mins to be // safe. //--- ossim_uint32 i; // for numerous iterations... const ossimScalarType ST = ih->getOutputScalarType(); const double DEFAULT_MIN = ossim::defaultMin(ST); const double DEFAULT_MAX = ossim::defaultMax(ST); const ossim_uint32 BANDS = ih->getNumberOfInputBands(); vector tmin(BANDS); vector tmax(BANDS); vector tnull(BANDS); for (i = 0; i < BANDS; ++i) { tmin[i] = DEFAULT_MAX; tmax[i] = DEFAULT_MIN; if ( hasNull ) { // User passed in with --null option so set here. tnull[i] = nullValue; } else { tnull[i] = ih->getNullPixelValue(i); } } // Scan the image and compute the min and max. const double TOTAL_TILES = is->getNumberOfTiles(); double tile_count = 0.0; ossimNotify(ossimNotifyLevel_INFO) << setiosflags(ios::fixed) << setprecision(0); if((ossim::isnan(minValue))|| (ossim::isnan(maxValue))) { ossimRefPtr id = is->getNextTile(); while(id.valid()) { if ( hasNull ) { // Pass null to image data object so it doesn't get picked up as "min". id->setNullPix( nullValue ); } id->computeMinMaxPix(tmin, tmax); id = is->getNextTile(); ++tile_count; ossimNotify(ossimNotifyLevel_INFO) << "\r" << setw(3) << (tile_count / TOTAL_TILES * 100.0) << "%" << flush; } } if(!ossim::isnan(minValue)) { std::fill(tmin.begin(), tmin.end(), minValue); } if(!ossim::isnan(maxValue)) { std::fill(tmax.begin(), tmax.end(), maxValue); } ossimNotify(ossimNotifyLevel_WARN) << "\r100%\nFinished..." << endl; ossimKeywordlist okwl(omd_file); for(i = 0; i < BANDS; ++i) { //--- // Check to see if values got assigned. If not flip to default and // issue a warning. //--- if (tmin[i] == DEFAULT_MAX) { tmin[i] = DEFAULT_MIN; ossimNotify(ossimNotifyLevel_WARN) << "cmm scan for min failed! Using default min." << std::endl; } if (tmax[i] == DEFAULT_MIN) { tmax[i] = DEFAULT_MAX; ossimNotify(ossimNotifyLevel_WARN) << "cmm scan for max failed! Using default max." << std::endl; } ossimString band = ossimString("band")+ossimString::toString(i+1)+"."; if (tmin[i] == DEFAULT_MAX) { tmin[i] = DEFAULT_MIN; } if (tmax[i] == DEFAULT_MIN) { } okwl.add(band + "min_value", tmin[i], true); okwl.add(band + "max_value", tmax[i], true); okwl.add(band + "null_value", tnull[i], true); if(out_data) { ossimNotify(ossimNotifyLevel_INFO) << setiosflags(ios::fixed) << setprecision(16) << "band" << ossimString::toString(i+1) << ".min_value: " << tmin[i] << "\nband" << ossimString::toString(i+1) << ".max_value: " << tmax[i] << "\nband" << ossimString::toString(i+1) << ".null_value: " << tnull[i] << endl; } } // End of band loop. //---- // ESH 05/2009 -- Fix for ticket #591: // Ingest command errors - when using the ew_ingest -r option // // Add missing info (number of bands, scalar type) to the .omd file //--- okwl.add("number_bands", BANDS, true); okwl.add("scalar_type", (ossimScalarTypeLut::instance()->getEntryString(ST)), true); if(!out_data) { okwl.write(omd_file); ossimNotify(ossimNotifyLevel_INFO) << "wrote file: " << omd_file << endl; } } // End of loop through entries of a file. } // End of loop through file... return 0; } ossim-Miami-2.9.1/apps/ossim-computeSrtmStats/000077500000000000000000000000001352751253100213475ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-computeSrtmStats/CMakeLists.txt000066400000000000000000000003321352751253100241050ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-computeSrtmStats INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-computeSrtmStats/ossim-computeSrtmStats.cpp000066400000000000000000000061761352751253100265560ustar00rootroot00000000000000//************************************************************************** // // License: See top level LICENSE.txt file. // // Written by: David Burken // // Description: This program will open an srtm file. Compute statistics, // then write a ossim meta data (omd) file. // //************************************************************************** // $Id: computeSrtmStats.cpp 13025 2008-06-13 17:06:30Z sbortman $ #include #include #include #include #include using namespace std; #include #include #include #include #include #include #include #include static const ossimTrace traceDebug(ossimString("computeStrmStats:debug")); static void usage() { ossimNotify(ossimNotifyLevel_INFO) << "\nNOTES:" << "\n- Output is to a \".omd\" file so if the image was" << " \"N27W081.hgt\" output will be a \"N27W081.omd\" file." << "\n- Example: computeSrtmStats *.hgt" << endl; } int main(int argc, char* argv[]) { ossimString tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); // Set the app name. argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); // Set usage option. argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // Usage... argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" \n"); if (argumentParser.read("-h") || argumentParser.read("--help")||(argumentParser.argc() < 2)) { argumentParser.getApplicationUsage()-> write(ossimNotify(ossimNotifyLevel_WARN)); usage(); exit(0); } argumentParser.reportRemainingOptionsAsUnrecognized(); if(argc == 1) { argumentParser.getApplicationUsage()-> write(ossimNotify(ossimNotifyLevel_WARN)); usage(); exit(1); } // Default variables ossim_uint32 fileCount = argc - 1; ossim_uint32 idx = 1; for(idx = 1; idx <= fileCount; ++idx) { // Get the srtm file name. ossimFilename srtmFile(argv[idx]); ossimNotify(ossimNotifyLevel_INFO) << "Processing srtm file: " << srtmFile << endl; ossimSrtmSupportData ss; if (ss.setFilename(srtmFile, true) == true) { ossimFilename omdFile = srtmFile; omdFile.setExtension(ossimString("omd")); ossimNotify(ossimNotifyLevel_NOTICE) << "Wrote file: " << omdFile.c_str() << std::endl; } else { ossimNotify(ossimNotifyLevel_WARN) << "Error processing: " << srtmFile.c_str() << std::endl; } } // End of loop through file... return 0; } ossim-Miami-2.9.1/apps/ossim-config.in000066400000000000000000000010161352751253100176010ustar00rootroot00000000000000usage() { cat <&2 fi case $1 in --includes) echo $OSSIM_INCLUDES ;; --libs) echo $OSSIM_LIBS ;; --cflags) echo $OSSIM_CFLAGS ;; --prefix) echo $OSSIM_PREFIX ;; --cppflags) echo $OSSIM_CPPFLAGS ;; --version) echo $OSSIM_VERSION ;; *) usage 1 1>&2 ;; esacossim-Miami-2.9.1/apps/ossim-correl/000077500000000000000000000000001352751253100172745ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-correl/CMakeLists.txt000066400000000000000000000003201352751253100220270ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-correl INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-correl/ossim-correl.cpp000066400000000000000000000204721352751253100224230ustar00rootroot00000000000000//******************************************************************* // // Author: Frederic Claudel // from ../mosaic/mosaic.cpp // //******************************************************************* // #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //error header static const char* PROGERR = "ERROR correl"; int main(int argc, char *argv[]) { //error status : initially ok int result=0; //init OSSIM (prefs, elevation, plugins, etc) std::string tempString; unsigned int tempUint; double tempDouble; ossimArgumentParser::ossimParameter argString(tempString); ossimArgumentParser::ossimParameter argUint(tempUint); ossimArgumentParser::ossimParameter argDouble(tempDouble); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); //default parms ossimRefPtr icObject = ossimObjectFactoryRegistry::instance()->createObject(ossimString("ossimImageCorrelator")); ossimOutputSource* icSource = PTR_CAST(ossimOutputSource, icObject.get()); ossimProcessInterface* icProcessInterface = PTR_CAST(ossimProcessInterface, icObject.get()); ossimPropertyInterface* icPropertyInterface = PTR_CAST(ossimPropertyInterface, icObject.get()); if(!icObject.valid()||!icSource||!icProcessInterface||!icPropertyInterface) { ossimNotify(ossimNotifyLevel_WARN) << "Unable to find object ossimImageCorrelator in registration plugin" << std::endl; exit(1); } ossimRefPtr masterBand = icSource->getProperty("master_band"); ossimRefPtr slaveBand = icSource->getProperty("slave_band"); ossimRefPtr scaleRatio = icSource->getProperty("scale_ratio"); ossimRefPtr cornerDensity = icSource->getProperty("corner_density"); ossimRefPtr minCorrel = icSource->getProperty("min_correl"); ossimRefPtr templateRadius = icSource->getProperty("template_radius"); ossimRefPtr slaveAccuracy = icSource->getProperty("slave_accuracy"); ossimRefPtr projectionType = icSource->getProperty("projection_type"); ossimRefPtr outputFilename = icSource->getProperty("output_filename"); //read args : options argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" coregisters a slave image to a master image"); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] "); argumentParser.getApplicationUsage()->addCommandLineOption("-h", ossimString("display Usage/Help")); argumentParser.getApplicationUsage()->addCommandLineOption("-m", ossimString("band index to use for master (default ") + masterBand->valueToString() + ")"); argumentParser.getApplicationUsage()->addCommandLineOption("-s", ossimString("band index to use for slave (default ") + slaveBand->valueToString() + ")"); argumentParser.getApplicationUsage()->addCommandLineOption("-r", ossimString("scale ratio, >0 and <=1 (default ") + scaleRatio->valueToString() + ")"); argumentParser.getApplicationUsage()->addCommandLineOption("-d", ossimString("corner density, >0 and <=1 (default ") + cornerDensity->valueToString() + ")"); argumentParser.getApplicationUsage()->addCommandLineOption("-c", ossimString("minimum correlation, >=-1 and <=1 (default ") + minCorrel->valueToString() +")"); argumentParser.getApplicationUsage()->addCommandLineOption("-t", ossimString("template radius, pixel >=1 (default ") + templateRadius->valueToString() +")"); argumentParser.getApplicationUsage()->addCommandLineOption("-e", ossimString("absolute accuracy error, in pixels (default ") + slaveAccuracy->valueToString() +")"); argumentParser.getApplicationUsage()->addCommandLineOption("-p", ossimString("projection type: M (master) or S (slave) (default ") + projectionType->valueToString() + ")"); argumentParser.getApplicationUsage()->addCommandLineOption("-o", ossimString("output file name for tie points (default ") + outputFilename->valueToString() +")"); if (argumentParser.read("-h")) { //help/usage argumentParser.getApplicationUsage()->write(std::cout); result = 0; } else { if (argumentParser.read("-m", argUint)) { icPropertyInterface->setProperty("master_band", ossimString::toString(tempUint)); // ic.setMasterBand(tempUint); } if (argumentParser.read("-s",argUint)) { icPropertyInterface->setProperty("slave_band", ossimString::toString(tempUint)); } if (argumentParser.read("-r",argDouble)) { //TBD check boundaries : 0 to 1 icPropertyInterface->setProperty("scale_ratio", ossimString::toString(tempDouble)); // ic.setScaleRatio(tempDouble); } if (argumentParser.read("-d",argDouble)) { //TBD check boundaries // ic.setCornerDensity(tempDouble); icPropertyInterface->setProperty("corner_density", ossimString::toString(tempDouble)); } if (argumentParser.read("-c",argDouble)) { //TBD check boundaries // ic.setMinCorrel(tempDouble); icPropertyInterface->setProperty("min_correl", ossimString::toString(tempDouble)); } if (argumentParser.read("-t",argUint)) { icPropertyInterface->setProperty("template_radius", ossimString::toString(tempUint)); // ic.setTemplateRadius(tempUint); } if (argumentParser.read("-e",argDouble)) { //TBD check boundaries // ic.setSlaveAccuracy(tempDouble); icPropertyInterface->setProperty("slave_accuracy", ossimString::toString(tempDouble)); } if (argumentParser.read("-p",argString)) { ossimString projArg(tempString); projArg = projArg.upcase(); projArg = projArg.trim(); if( (projArg != "S")&& (projArg != "M")&& (projArg != "G") ) { cerr<setProperty("projection_type", projArg); } } if (argumentParser.read("-o",argString)) { icPropertyInterface->setProperty("output_filename", tempString); // ic.setOutputName(tempString); } //read mandatory args : master and slave images //should only remain 2 args int nbargs = argumentParser.argc() - 1; if (nbargs == 2) { icPropertyInterface->setProperty("master_filename", ossimString(argumentParser.argv()[1])); icPropertyInterface->setProperty("slave_filename", ossimString(argumentParser.argv()[2])); // ic.setMaster(argumentParser.argv()[1]); // ic.setSlave( argumentParser.argv()[2]); theStdOutProgress.setFlushStreamFlag(true); icSource->addListener(&theStdOutProgress); // ic.addListener(&theStdOutProgress); result = (icProcessInterface->execute()) ? 0 : 4 ; } else { cerr< #include #include #include #include #include #include #include #include #include #include #include #include // for its keywords #include #include /* for exit */ using namespace std; //************************************************************************************************* // FINALIZE -- Convenient location for placing debug breakpoint for catching program exit. //************************************************************************************************* void finalize(int code) { exit (code); } //************************************************************************************************* // MAIN //************************************************************************************************* int main(int argc, char* argv[]) { ossimString tempString; double tempDouble, tempDouble2; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser::ossimParameter doubleParam(tempDouble); ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+ " Generates a bit-mask given source image and target pixel range to mask out. If the input" " image has overviews, then masks will be generated for all R-levels."); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+ " [options] "); argumentParser.getApplicationUsage()->addCommandLineOption("-d", "Write mask to directory specified."); argumentParser.getApplicationUsage()->addCommandLineOption("-e or --entry", "Give the entry(zero based) for which to build a mask. Only one entry can be processed. " "If the input is multi-entry and no entry was specified, entry 0 is assumed."); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help", "Shows help"); argumentParser.getApplicationUsage()->addCommandLineOption("--mask-mode ", "Specifies how to treat multi-band imagery when determining whether pixel will be masked " "according to the defined target value or range. Possible modes are: " "\"mask_full_and_partial_targets\" (default) | \"mask_only_full_targets\"."); argumentParser.getApplicationUsage()->addCommandLineOption("--mask-range ", "Specifies the range of pixels to target for masking out."); argumentParser.getApplicationUsage()->addCommandLineOption("--mask-value ", "Specifies the unique pixel value to target for masking out."); argumentParser.getApplicationUsage()->addCommandLineOption("-o", "Write mask to file specified. If used on a multi-entry file, given \"foo.mask\" you will " "get: \"foo_e0.mask\". If none specified, the input filename is used with \".mask\" " "extension."); argumentParser.getApplicationUsage()->addCommandLineOption("--ovr-from-image", "Uses exclusively the image overview data when computing subsequent overviews. " "Normally the mask overview from the prior level is referenced for establishing the masks at " "the next level."); argumentParser.getApplicationUsage()->addCommandLineOption("--spec-kwl ", "In lieu of providing mask parameters on the command line, this option specifies a keyword " "list filename that contains all settings. Typically used when spawning from other process."); argumentParser.getApplicationUsage()->addCommandLineOption("-x or --exclude-fullres", "Excludes R0 mask computation. The mask file will start at R1."); if(argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(std::cout); finalize(0); } if ( argumentParser.read("--version") || argumentParser.read("-v")) { ossimNotify(ossimNotifyLevel_NOTICE)<< argumentParser.getApplicationName().c_str() << " " << ossimInit::instance()->instance()->version().c_str()<< std::endl; finalize(0); } // Fetch command line options: ossimFilename outputFile; if (argumentParser.read("-o", stringParam)) outputFile = tempString.trim(); ossimFilename outputDir; if (argumentParser.read("-d", stringParam)) outputDir = tempString.trim(); bool exclude_r0 = false; if (argumentParser.read("-x") || argumentParser.read("--exclude-fullres")) exclude_r0 = true; bool entry_specified = false; ossim_int32 entry = 0; if (argumentParser.read("-e", stringParam) || argumentParser.read("--entry", stringParam)) { entry = ossimString(tempString).toUInt32(); entry_specified = true; } double target_min = 0; double target_max = 0; if (argumentParser.read("--mask-range", doubleParam, doubleParam2)) { target_min = tempDouble; target_max = tempDouble2; } if (argumentParser.read("--mask-value", doubleParam)) { target_min = tempDouble; target_max = target_min; } ossimString mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET"; ossimString mask_mode_arg; if (argumentParser.read("--mask-mode", stringParam)) { mask_mode_arg = tempString; if (mask_mode_arg == "mask_full_and_partial_targets") mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET"; else if (mask_mode_arg == "mask_only_full_targets") mask_mode = "REPLACE_ONLY_FULL_TARGETS"; else { ossimNotify(ossimNotifyLevel_NOTICE)<< argumentParser.getApplicationName().c_str() << " " << " Unknown mask-mode <"< specified. See usage below." << std::endl; argumentParser.getApplicationUsage()->write(std::cout); finalize(1); } } bool ovr_from_image = false; if (argumentParser.read("--ovr-from-image")) ovr_from_image = true; ossimFilename spec_kwl_file; if (argumentParser.read("--spec_kwl", stringParam)) spec_kwl_file = tempString.trim(); // Handle bad command line: argumentParser.reportRemainingOptionsAsUnrecognized(); if (argumentParser.errors()) { argumentParser.writeErrorMessages(std::cout); finalize(1); } if ((argumentParser.argc()<2) && spec_kwl_file.empty()) { argumentParser.getApplicationUsage()->write(std::cout); finalize(1); } // Establish input filename: ossimFilename inputFile; ossimKeywordlist kwl; if (spec_kwl_file.isReadable()) { kwl.addFile(spec_kwl_file); inputFile = kwl.find(ossimKeywordNames::IMAGE_FILE_KW); outputFile = kwl.find(ossimKeywordNames::OUTPUT_FILE_KW); } else { inputFile = argv[1]; } // Establish the input image handler: ossimRefPtr handler = ossimImageHandlerRegistry::instance()->open(inputFile); if (!handler.valid()) { ossimNotify(ossimNotifyLevel_FATAL)<."<getFilenameWithThisExtension("mask", entry_specified); if (!outputDir.empty()) outputFile.setPath(outputDir); else { ossimFilename path (outputFile.path()); if (path.empty()) outputFile.setPath(inputFile.path()); } // Consider input file with multiple entries: std::vector entryList; handler->getEntryList(entryList); if (entryList.size() <= entry) { ossimNotify(ossimNotifyLevel_FATAL)< exceeds total number of entries available <" <. Aborting..."<setCurrentEntry(entry); // Establish a keywordlist to pass to the mask builder. This KWL may have already been specified // on the command line with --spec_kwl option: kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, outputFile.chars()); // may overwrite same value if (kwl.getSize() == 0) { kwl.add(ossimKeywordNames::IMAGE_FILE_KW, inputFile.chars()); ossimString target_str (ossimString::toString(target_min)+" "+ossimString::toString(target_max)); kwl.add(ossimPixelFlipper::PF_TARGET_RANGE_KW, target_str.chars()); kwl.add(ossimPixelFlipper::PF_REPLACEMENT_MODE_KW, mask_mode.chars()); kwl.add(ossimPixelFlipper::PF_REPLACEMENT_VALUE_KW, (int) 0); if (exclude_r0) kwl.add(ossimBitMaskWriter::BM_STARTING_RLEVEL_KW, (int) 1); else kwl.add(ossimBitMaskWriter::BM_STARTING_RLEVEL_KW, (int) 0); } // Instantiate the bit mask processor and write out the mask file: ossimRefPtr mask_writer = new ossimBitMaskWriter; mask_writer->loadState(kwl); mask_writer->connectMyInputTo(handler.get()); // Need to loop over all R-levels. Use a sequencer: ossimRefPtr sequencer = new ossimImageSourceSequencer(handler.get()); sequencer->initialize(); int num_rlevels = handler->getNumberOfDecimationLevels(); int num_tiles = sequencer->getNumberOfTiles(); int tile_idx = 0; int percent_complete = 0; ossimRefPtr tile = 0; int start_res = 0; if (exclude_r0) { start_res = 1; num_tiles = (num_tiles+3)/4; } for (int r=start_res; rgetBoundingRect(r)); sequencer->setAreaOfInterest(rect); sequencer->setToStartOfSequence(); do { tile = sequencer->getNextTile(r); mask_writer->generateMask(tile, r); percent_complete = 100 * tile_idx++/num_tiles; ossimNotify(ossimNotifyLevel_NOTICE)<buildOverviews(num_rlevels); break; } } // Finished sequencing all levels, ready to write out the mask buffers: mask_writer->close(); ossimNotify(ossimNotifyLevel_NOTICE)<<"\nSuccessfully wrote mask file to <"<. Finished."< #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { //--- // Get the arg count so we can tell if an arg was consumed by // ossimInit::instance()->initialize //--- int originalArgCount = argc; ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); if ( (argumentParser.argc() == 1) && (originalArgCount > 1) ) { exit(0); // ossimInit consumed all options. } ossimString appname = argumentParser.getApplicationName(); ossimApplicationUsage* appuse = argumentParser.getApplicationUsage(); appuse->setApplicationName(appname); appuse->setDescription(appname+" Creates OSSIM coarse grid geometry from rigorous sensor model."); appuse->setCommandLineUsage(appname+" [options] "); appuse->addCommandLineOption("-d or --support", " -- Specifies a supplementary directory path to contain the geom and associated " "grid files. The default is to use the image directory."); appuse->addCommandLineOption("-e", " -- default is 0.1. This is the maximum difference tolerated in pixels between the " "rigorous model and the computed coarse grid. The smaller this value, the bigger the " "resulting grid."); appuse->addCommandLineOption("-s", " -- Specifies the min line sample spacing for the coarse grid. " "Helps in converging. Basically will stop splitting if number of pixels per grid cell gets " "below this number."); appuse->addCommandLineOption("-o", " -- Specifies a new base output name for the geom and associated grid files. " "The default is to use the base name of the image file with .geom and .ocg extensions. " "If specified then the output is .geom and .ocg where the " ".ocg contains the coarse grid data. THIS IS NOT COMMON AND MAY PREVENT OSSIM FROM " "SUBSEQUENTLY LOCATING THE GEOMETRY FILE."); appuse->addCommandLineOption("-h or --help", "Shows help"); if(argumentParser.read("-h") || argumentParser.read("--help") || (argc < 2)) { appuse->write(std::cout); exit(0); } // The last argument is always the image filename: ossimFilename image_file = argv[argc-1]; double error = 0.1; if(argumentParser.read("-e", error)) { if (error < 0.0) error = 0.1; } ossim_int32 minSpacing = 100; if(argumentParser.read("-s", minSpacing)) { if (minSpacing < 1) minSpacing = 100; } ossimFilename outputBaseName; argumentParser.read("-o", outputBaseName.string()); ossimFilename outputPath; argumentParser.read("-d", outputPath.string()); if (outputPath.empty()) { argumentParser.read("--support", outputPath); if (outputPath.empty()) outputPath = image_file.path(); } // Establish image handler for access to rigorous model: ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(image_file); if (ih.valid()) { // Instantiate the rigorous model: ossimRefPtr geom = ih->getImageGeometry(); if(geom.valid() && geom->getProjection()) { // Compute the coarse grid: ossimRefPtr cg = new ossimCoarseGridModel; cg->setInterpolationError(error); cg->setMinGridSpacing(minSpacing); ossimNotify(ossimNotifyLevel_NOTICE)<<"\nComputing coarse grid..."<buildGrid(ih->getBoundingRect(), geom.get()); // If no basename was provided, use the defaults for geom file. PREFERRED: if (outputBaseName.empty()) outputBaseName = ih->createDefaultGeometryFilename().file(); // Save the coarse grid to appropriate location: ossimFilename filename (outputPath.dirCat(outputBaseName)); filename.expand(); ossimNotify(ossimNotifyLevel_NOTICE)<<"\nSaving OCG grid and geometry to <" <..."<saveCoarseGrid(filename); // this saves geom file as well } } return 0; } ossim-Miami-2.9.1/apps/ossim-create-histo/000077500000000000000000000000001352751253100203755ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-create-histo/CMakeLists.txt000066400000000000000000000003261352751253100231360ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-create-histo INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-create-histo/ossim-create-histo.cpp000066400000000000000000000243541352751253100246300ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id: create_histo.cpp 11743 2007-09-19 19:57:31Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; void usage() { cout << "examples:\n" << " create_histo foo.tif\n" << " Will create a histogram for the input image and call\n" << " it foo.his\n\n" << " create_histo -i foo.tif -o foo.his\n" << " this will compute a histogram from the input foo.tif\n" << " and write it to foo.his\n\n" << " create_histo -p foo2.his -o foo.his\n" << " will import the proprietary histogram file and output\n" << " an ossim histogram file to foo.his\n\n" << "NOTE: If no output is given it will default to output.his\n" << " unless the special case of a single input image is given\n" << endl; } void importHistogram(const ossimString& importFile, const ossimString& outputFile) { ossimRefPtr histo = new ossimMultiResLevelHistogram; histo->importHistogram(importFile); ossimKeywordlist kwl; histo->saveState(kwl); kwl.write(outputFile.c_str()); } void computeHistogram(const ossimString& imageOption, const ossimString& outputOption, ossim_float64 minValueOverride, ossim_float64 maxValueOverride, ossim_int32 numberOfBinsOverride, ossim_int32 entryNumberOverride, bool fastMode, int maxResLevels=1 ) { theStdOutProgress.setFlushStreamFlag(true); ossimRefPtr handler = ossimImageHandlerRegistry::instance()->open(ossimFilename(imageOption)); if(handler.valid()) { ossimFilename histogramFile; std::vector entryList; handler->getEntryList(entryList); if(entryNumberOverride >= 0) { std::vector::iterator iter= std::find(entryList.begin(), entryList.end(), (ossim_uint32)entryNumberOverride); if(iter != entryList.end()) { entryList.clear(); entryList.push_back(entryNumberOverride); } else { ossimNotify(ossimNotifyLevel_WARN) << "Invalid entry number " << entryNumberOverride << " passed in. Returning...." << std::endl; return; } } ossim_uint32 idx = 0; for(idx = 0; idx < entryList.size(); ++idx) { ossimNotify(ossimNotifyLevel_NOTICE)<<"entry " << entryList[idx] << std::endl; handler->setCurrentEntry(entryList[idx]); // Check handler to see if it's filtering bands. if ( handler->isBandSelector() ) { // Set output list to input. handler->setOutputToInputBandList(); } ossimRefPtr histogramFilename = handler->getProperty("histogram_filename"); if(histogramFilename.valid()) { if (outputOption == "") { histogramFile = ossimFilename(histogramFilename->valueToString()); } else { histogramFile = outputOption; } ossimRefPtr histoSource = new ossimImageHistogramSource; ossimRefPtr writer = new ossimHistogramWriter; if(maxResLevels) { histoSource->setMaxNumberOfRLevels(maxResLevels); } else { histoSource->setMaxNumberOfRLevels(handler->getNumberOfDecimationLevels()); } if(!ossim::isnan(minValueOverride)) { histoSource->setMinValueOverride(minValueOverride); } if(!ossim::isnan(maxValueOverride)) { histoSource->setMaxValueOverride(maxValueOverride); } if(numberOfBinsOverride > 0) { histoSource->setNumberOfBinsOverride(numberOfBinsOverride); } if (fastMode) { histoSource->setComputationMode(OSSIM_HISTO_MODE_FAST); } histoSource->connectMyInputTo(0, handler.get()); histoSource->enableSource(); writer->connectMyInputTo(0, histoSource.get()); writer->setFilename(histogramFile); writer->addListener(&theStdOutProgress); writer->execute(); writer=0; } } } } int main(int argc, char *argv[]) { ossimString tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" creates a histogram from image."); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" "); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("-p", " Imports imagelinks proprietary histogram_file."); argumentParser.getApplicationUsage()->addCommandLineOption("-i", " Creates a histogram from the image_file."); argumentParser.getApplicationUsage()->addCommandLineOption("-l", " Output the specified number of res levels default is, set to 0 if you want all(not supported for import histogram -i option"); argumentParser.getApplicationUsage()->addCommandLineOption("-t", ""); argumentParser.getApplicationUsage()->addCommandLineOption("--create-histogram-fast", "Computes a histogram in fast mode which samples partial tiles."); argumentParser.getApplicationUsage()->addCommandLineOption("-o", " Output the histogram to the indicated file."); argumentParser.getApplicationUsage()->addCommandLineOption("--min", "Minimum value to use"); argumentParser.getApplicationUsage()->addCommandLineOption("--max", "Maximum value to use"); argumentParser.getApplicationUsage()->addCommandLineOption("--bins", "Number of bins to use"); argumentParser.getApplicationUsage()->addCommandLineOption("--entry", "entry number to use"); argumentParser.getApplicationUsage()->addCommandLineOption("-f", "fast mode"); ossimString importOption; ossimString imageOption; ossimString outputOption; ossim_uint32 maxLevels = 1; ossim_int32 entry = -1; ossim_float64 minValueOverride = ossim::nan(); ossim_float64 maxValueOverride = ossim::nan(); ossim_int32 numberOfBinsOverride = -1; bool fastMode = false; if ( (argumentParser.read("-h")) || (argumentParser.read("--help")) ) { argumentParser.getApplicationUsage()->write(std::cout); usage(); exit(0); } if (argumentParser.argc() == 2) { ossimFilename inputImage = argv[1]; imageOption = inputImage; if(!inputImage.exists()) { cerr << "Image does not exist " << inputImage << endl; exit(1); } maxLevels = 1; } else { if(argumentParser.read("--min", stringParam)) { minValueOverride = tempString.toDouble(); } if(argumentParser.read("--max", stringParam)) { maxValueOverride = tempString.toDouble(); } if(argumentParser.read("--bins", stringParam)) { numberOfBinsOverride = tempString.toInt32(); } if(argumentParser.read("--bins", stringParam)) { numberOfBinsOverride = tempString.toInt32(); } if(argumentParser.read("--entry", stringParam)) { entry = tempString.toInt32(); } if(argumentParser.read("-o", stringParam)) { outputOption = tempString; } if ( argumentParser.read("-f") || argumentParser.read("--create-histogram-fast")) { fastMode = true; } if(argumentParser.read("-p", stringParam)) { importOption = tempString; } if(argumentParser.read("-l", stringParam)) { ossimString s = tempString; maxLevels = s.toUInt32(); } } if((importOption != "") && (imageOption != "")) { cout << "you can either import or create a histogram from an image but\n" << "we can't do both" << endl; exit(1); } if(importOption != "") { importHistogram(importOption, ""); } else if(argc > 1) { ossim_uint32 idx = 1; while(argv[idx]) { ossimNotify(ossimNotifyLevel_NOTICE) <<"file " << argv[idx] << std::endl; computeHistogram(ossimString(argv[idx]), outputOption, minValueOverride, maxValueOverride, numberOfBinsOverride, entry, fastMode, maxLevels); ++idx; } } else { argumentParser.getApplicationUsage()->write(std::cout); usage(); } return 0; } ossim-Miami-2.9.1/apps/ossim-deg2dms/000077500000000000000000000000001352751253100173335ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-deg2dms/CMakeLists.txt000066400000000000000000000003211352751253100220670ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-deg2dms INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-deg2dms/ossim-deg2dms.cpp000066400000000000000000000044301352751253100225150ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Application to convert decimal degrees, to degrees, minutes, // seconds (DMS). // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include using namespace std; void getDegrees(double& deg) { std::string s; cout << "Enter degrees: " << flush; cin >> s; if ( (s == "q") || (s == "Q") ) { exit(0); } else { istringstream is(s); is >> deg; if( is.fail() ) { cerr << "Must enter a valid number between -180 and 180 for degrees." << " Exiting..." << endl; exit(1); } else if ( (deg < -180.0) || (deg > 180.0) ) // Check the range. { cerr << "Degrees must be between -180 and 180. Exiting..." << endl; exit(1); } } } int main(int argc, char* argv[]) { enum { FOREVER=1 }; if (argc != 1) { cout << "Usage: " << argv[0] << "\nThis application will convert decimal degrees to degrees, " << "minutes, seconds.\nIt take no arguments, you will be prompted " << "for the decimal degrees.\n" << endl; return 0; } cout << "\nEnter \"q\" to quit.\n\n"; double deg = 0.0; double min = 0.0; double sec = 0.0; int degInt = 0; int minInt = 0; cout << setiosflags(ios::fixed) << setprecision(15); while (FOREVER) { // Get the degrees. getDegrees(deg); // Compute the answer. bool isNegative = (deg < 0.0); if (isNegative) { deg = fabs(deg); } degInt = static_cast(deg); min = (deg - degInt) * 60.0; minInt = static_cast(min); sec = (min - minInt) * 60.0; if (isNegative) { deg = -deg; } cout << deg << " = " << (isNegative?"-":"") << degInt << " degrees, " << minInt << " minutes, " << sec << " seconds." << endl; } return 0; } ossim-Miami-2.9.1/apps/ossim-dms2deg/000077500000000000000000000000001352751253100173335ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-dms2deg/CMakeLists.txt000066400000000000000000000003211352751253100220670ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-dms2deg INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-dms2deg/ossim-dms2deg.cpp000066400000000000000000000065201352751253100225170ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Application to convert degrees, minutes seconds (DMS) // to decimal degrees. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include using namespace std; void getDegrees(double& deg) { std::string s; cout << "Enter degrees: " << flush; cin >> s; if ( (s == "q") || (s == "Q") ) { exit(0); } else { istringstream is(s); is >> deg; if( is.fail() ) { cerr << "Must enter a valid number between -180 and 180 for degrees." << " Exiting..." << endl; exit(1); } else if ( (deg < -180.0) || (deg > 180.0) ) // Check the range. { cerr << "Degrees must be between -180 and 180. Exiting..." << endl; exit(1); } } } void getMinutes(double& min) { std::string s; cout << "Enter minutes: " << flush; cin >> s; if ( (s == "q") || (s == "Q") ) { exit(0); } else { istringstream is(s); is >> min; if(is.fail()) { cerr << "Must enter a valid number between 0 and 60 for minutes." << " Exiting..." << endl; exit(1); } else if ( (min < 0.0) || (min > 60.0) ) // Check the range. { cerr << "Minutes must be between 0 and 60. Exiting\n"; exit(1); } } } void getSeconds(double& sec) { std::string s; cout << "Enter seconds: " << flush; cin >> s; if ( (s == "q") || (s == "Q") ) { exit(0); } else { istringstream is(s); is >> sec; if( is.fail() ) { cerr << "Must enter a valid number between 0 and 60 for seconds." << " Exiting..." << endl; exit(1); } else if ( (sec < 0.0) || (sec > 60.0) ) // Check the range. { cerr << "Seconds must be between 0 and 60. Exiting\n"; exit(1); } } } int main(int argc, char* argv[]) { enum { FOREVER=1 }; if (argc != 1) { cout << "Usage: " << argv[0] << "\nThis application will convert degrees, minutes, seconds to " << "decimal degrees.\nIt take no arguments, you will be prompted " << "for the degrees, minutes, seconds.\n" << endl; return 0; } cout << "\nEnter \"q\" to quit.\n\n"; double deg = 0.0; double min = 0.0; double sec = 0.0; cout << setiosflags(ios::fixed) << setprecision(15); while (FOREVER) { // Get the degrees. getDegrees(deg); // Get the minutes. getMinutes(min); // Get the the seconds. getSeconds(sec); // Compute the answer. if (deg < 0.0) { double d = fabs(deg); deg = -(d + min/60.0 + sec/3600.0); } else { deg = deg + min/60.0 + sec/3600.0; } if ( deg < -180.0 ) { deg += 360.0; } else if ( deg > 180.0 ) { deg -= 360.0; } cout << "Decimal degrees = " << deg << "\n" << endl; } return 0; } ossim-Miami-2.9.1/apps/ossim-dump-ocg/000077500000000000000000000000001352751253100175215ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-dump-ocg/CMakeLists.txt000066400000000000000000000003221352751253100222560ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-dump-ocg INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-dump-ocg/ossim-dump-ocg.cpp000066400000000000000000000022721352751253100230730ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // Description: // // Contains application "dumpocg" for outputing an OSSIM coarse grid data // file in human-friendly format. // //******************************************************************* // $Id: dumpocg.cpp 10253 2007-01-14 17:52:22Z dburken $ #include /* for exit */ #include #include #include #include using namespace std; int main(int argc, char** argv) { ossimInit::instance()->initialize(argc, argv); if (argc < 2) { cout << "USAGE: "<" << endl; exit(-1); } ossimFilename geom_file(argv[1]); ossimCoarseGridModel model (geom_file); if (model.getErrorStatus() != ossimErrorCodes::OSSIM_OK) { cout << "Error encountered instantiating the OCG object given geometry " << "file name: " << geom_file << ". Check the name and try again." << endl; exit(-1); } model.print(std::cout); exit(0); } ossim-Miami-2.9.1/apps/ossim-envi-cg/000077500000000000000000000000001352751253100173365ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-envi-cg/CMakeLists.txt000066400000000000000000000003211352751253100220720ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-envi-cg INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-envi-cg/ossim-envi-cg.cpp000066400000000000000000000034351352751253100225270ustar00rootroot00000000000000//--- // // License: MIT // //--- // System includes: #include #include #include #include // ossim includes: These are here just to save time/typing... #include #include #include #include #include #include #include #include #include #include using namespace std; // Put your includes here: int main(int argc, char *argv[]) { int returnCode = 0; if (argc < 2) { cout<<"\nUsage: "<\n"<addOptions(ap); ossimInit::instance()->initialize(ap); ossimFilename fname (argv[1]); try { ossimRefPtr model = new ossimEnviCgModel; if (model->loadEnviGeocFile(fname)) { ossimFilename geomFname(fname); geomFname.setExtension("geom"); model->saveCoarseGrid(geomFname); ossimKeywordlist kwl; ossimImageGeometry geom; geom.setProjection(model.get()); ossimIpt size (model->imageSize()); geom.setImageSize(size); geom.saveState(kwl); kwl.write(geomFname); } } catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } catch( ... ) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-foo caught unhandled exception!" << std::endl; returnCode = 1; } return returnCode; } ossim-Miami-2.9.1/apps/ossim-equation/000077500000000000000000000000001352751253100176335ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-equation/CMakeLists.txt000066400000000000000000000003221352751253100223700ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-equation INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-equation/ossim-equation.cpp000066400000000000000000000013531352751253100233160ustar00rootroot00000000000000//******************************************************************* // OSSIM // // License: See top level LICENSE.txt file. // //******************************************************************* // $Id: ossim-equation.cpp 23407 2015-07-06 15:59:23Z okramer $ #include #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimArgumentParser argParser(&argc, argv); ossimInit::instance()->addOptions(argParser); ossimInit::instance()->initialize(argParser); // Run: ossimEquationUtil equationUtil (argParser); bool success = equationUtil.execute(); if (success) exit(0); exit(1); } ossim-Miami-2.9.1/apps/ossim-extract-vertices/000077500000000000000000000000001352751253100213025ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-extract-vertices/CMakeLists.txt000066400000000000000000000003321352751253100240400ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-extract-vertices INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-extract-vertices/ossim-extract-vertices.cpp000066400000000000000000000074601352751253100264410ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Application to scan image and attemp to detect the valid image vertices and // write them to a keyword list file for later use. Note that if input // file is "foo.tif" this will create "foo_vertices.kwl". // //******************************************************************* // $Id: extract_vertices.cpp 10074 2006-12-13 13:27:53Z dburken $ #include using namespace std; #include #include #include #include #include #include static ossimTrace traceDebug("extract_vertices:main"); void usage() { cout << "\nextract_vertices [output_file]" << "\nNOTE:\n" << " Scans the image, extracts vertices and writes results to" << " a keyword list.\n" << " The output_file parameter specifies the path for the extracted" << " vertices.\n" << " If not specified, the name of the image_file with " << "\"_vertices.kwl\"\n" << " appended. So if image = \"foo.tif\" then" << " results file = \"foo_vertices.kwl\".\n" << endl; } int main(int argc, char *argv[]) { static const char MODULE[] = "extract_vertices:main"; if (traceDebug()) CLOG << " Entered..." << endl; ossimInit::instance()->initialize(argc, argv); if (argc != 2 && argc != 3) { usage(); exit(0); } ossimFilename input_file = argv[1]; // Get an image handler for the input file. ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(input_file); if (!ih) { cout << "ERROR: Unsupported image file: " << input_file << "\nExiting application." << endl; exit(1); } // Check for errors. if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { cerr << "ERROR: Unable to read image file: " << input_file << "\nExiting application." << endl; ih = 0; exit(2); } // Initialize the image handler. ih->initialize(); ossimFilename output_file; // Get output path from command line. if(argc>2) { output_file = argv[2]; } // Create the output file name from the input file name. else { output_file = output_file.dirCat(input_file.fileNoExtension()); output_file += "_vertices.kwl"; } if (traceDebug()) { CLOG << "DEBUG:" << "\nInput file: " << input_file << "\nOutput_file: " << output_file << endl; } // Give the image handler to the vertex extractor as an input source. ossimRefPtr ve = new ossimVertexExtractor(ih.get()); // Set the file name. ve->setOutputName(output_file); // Set the area of interest to the full bounding rect of the source. ve->setAreaOfInterest(ih->getBoundingRect(0)); // Add a listener for the percent complete to standard output. ossimStdOutProgress prog(0, true); ve->addListener(&prog); // Check that the output file can be created if (!ve->open()) { cerr << "ERROR: Unable to open output file: " << output_file << "\nExiting application." << endl; ih = 0; ve->disconnect(); ve = 0; exit(3); } // Start the extraction... if (!ve->execute()) { cerr << "ERROR: Unable to create output vertices: " << "\nExiting application." << endl; ih = 0; ve->disconnect(); ve = 0; exit(4); } ih = 0; ve->disconnect(); ve = 0; if (traceDebug()) CLOG << " Exited..." << endl; exit(0); } ossim-Miami-2.9.1/apps/ossim-header-crawl/000077500000000000000000000000001352751253100203445ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-header-crawl/CMakeLists.txt000066400000000000000000000003261352751253100231050ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-header-crawl INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-header-crawl/ossim-header-crawl.cpp000066400000000000000000000225271352751253100245460ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Ken Melero // Originally written by Oscar Kramer. // // Description: This app displays a binary file in a nice // formatted view. Very helpful for finding offsets of // binary headers. // //******************************************************************** #include #include #include #include #include #include #include #include using namespace std; // first: header file name only, second: header file's "namespace" or full path if relative typedef map HeaderMap; typedef vector FileList; class CppHeaderCrawler { public: CppHeaderCrawler(); // Mines the CMake output files for include paths and home directory bool loadBuild(const ossimFilename &buildDir); // Opens each source and header to determine external header dependencies bool scanForHeaders(); // Copies all external headers to the sandbox output directory, preserving the relative namespace bool copyHeaders(const ossimFilename &outDir); private: // Scans specified file for include files to record: bool scanFile(const ossimFilename &file); // Finds the path needed to prepend to the includeSpec to locate the existing include file. // Returns empty string if not found: ossimFilename findPath(const ossimFilename &includeSpec); ossimFilename m_ossimDevHome; // = $OSSIM_DEV_HOME as specified in CMakeCache.txt FileList m_includeDirs; // List of all include paths searched in build FileList m_sourceNames; // List of all OSSIM source and header files accessed in build HeaderMap m_includePathMap; // Contains existing include path for every header file }; void usage(char* appname) { cout<<"\nUsage: " << appname << " \n" << endl; cout<<" Utility app to copy all external header files on a system that are referenced by the \n" <<" OSSIM build. The headers are copied into a \"sandbox\" directory (usually appended with \n" <<" \"include\"), preserving namespaces. This is to enable sandbox builds. See the script in\n" <<" ossim/scripts/ocpld.sh for copying the external libraries needed.\n"<" << endl; m_includeDirs.emplace_back(line); } } f.close(); // Read list of sources and headers included in the build: ossimFilename cmakeFilenames (build_dir.dirCat("CMakeFileNames.txt")); f.open(cmakeFilenames.string()); if (f.fail()) { cout << "Failed file open for CMake file: " << cmakeFilenames << endl; return false; } while (getline(f, line)) { cout << "Adding source/header file <" << line << ">" << endl; m_sourceNames.emplace_back(line); } f.close(); return true; } bool CppHeaderCrawler::scanForHeaders() { // First find all files that match pattern: for (auto &sourceName : m_sourceNames) { scanFile(sourceName); } return true; } bool CppHeaderCrawler::scanFile(const ossimFilename& sourceName) { static const ossimString INCLUDE_STRING = "#include "; static const size_t SIZE_INCLUDE_STRING = INCLUDE_STRING.length(); // The file may be an absolute path or may need to be searched among include paths: // Open one file: ifstream f(sourceName.string()); if (f.fail()) { cout << "Failed file open for: " << sourceName << endl; return false; } cout << "Scanning file: " << sourceName << endl; bool foundInclude = false; int noIncludeCount = 0; ossimString lineOfCode; // Loop to read read one line at a time to check for includes: while (getline(f, lineOfCode) && (noIncludeCount < 10)) { ossimString substring(lineOfCode.substr(0, SIZE_INCLUDE_STRING)); if (substring != INCLUDE_STRING) { if (foundInclude) noIncludeCount++; continue; } foundInclude = true; noIncludeCount = 0; // Get the include file path/name. Determine if relative or "namespaced". Truly relative // include spec need not be copied to destination directory since the shall be present with // the source build anyway. ossimString includeSpec = lineOfCode.after(INCLUDE_STRING); includeSpec.trim(); if (includeSpec.empty()) continue; if (includeSpec[0] == '"') { // Relative. Some people are sloppy and use quoted header file spec even when it is really // namespaced, so need to search relative first: includeSpec = includeSpec.after("\"").before("\""); // stop before second quote (in case comments follow) ossimFilename pathFile = sourceName.path().dirCat(includeSpec); if (pathFile.exists()) continue; } else { includeSpec = includeSpec.after("<").before(">"); // stop before second quote (in case comments follow) } // Search the namespaced include spec list if already entered: auto entry = m_includePathMap.find(includeSpec); if (entry != m_includePathMap.end()) continue; // Exclude copying headers that are in the source tree (not external): auto sourcePath = m_sourceNames.begin(); for (; sourcePath != m_sourceNames.end(); ++sourcePath) { if (sourcePath->contains(includeSpec)) break; } if (sourcePath!=m_sourceNames.end()) continue; // First time this external header has been encountered, Find it on the system and save the // associated include path and namespace portion: ossimFilename path = findPath(includeSpec); if (!path.empty()) { cout << "Inserting " << includeSpec << endl; m_includePathMap.emplace(includeSpec, path); } // Now recursion into the rabbit hole of header dependencies: ossimFilename fullPathFile = path.dirCat(includeSpec); if (fullPathFile.ext().empty()) continue; // System include should be on target already scanFile(fullPathFile); } f.close(); return true; } bool CppHeaderCrawler::copyHeaders(const ossimFilename& outputDir) { ossimFilename path, existingLocation, newLocation; for (auto &header : m_includePathMap) { // Check existence of header on system: existingLocation = header.second.dirCat(header.first); if (!existingLocation.isFile()) { cout << "ERROR: Could not find <" << existingLocation << ">. Header was not copied." << endl; continue; } // Copy the file to the output directory: newLocation = outputDir.dirCat(header.first); ossimFilename newDir (newLocation.path()); ossimFilename newFile(newLocation.file()); if (!newDir.createDirectory()) { cout << "ERROR: Could not create directory <" << newDir << ">. Check permissions." << endl; return false; } existingLocation.copyFileTo(newLocation); cout << "Copied <" << header.first << ">"<< endl; } return true; } ossimFilename CppHeaderCrawler::findPath(const ossimFilename &file) { ossimFilename fullPath, result; for (auto &path: m_includeDirs) { fullPath = path.dirCat(file); if (fullPath.exists()) { result = path; break; } } return result; } ossim-Miami-2.9.1/apps/ossim-icp/000077500000000000000000000000001352751253100165615ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-icp/CMakeLists.txt000066400000000000000000000003151352751253100213200ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-icp INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-icp/ossim-icp.cpp000066400000000000000000000564071352751253100212040ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Command line application for copying images "image copy". // Can be used to cut images, convert formats. Works in image space // (no resampler). // //******************************************************************* // $Id: ossim-icp.cpp 3023 2011-11-02 15:02:27Z david.burken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //#include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("icp:main"); static void usage() { ossimNotify(ossimNotifyLevel_NOTICE) << "\nValid output writer types:\n\n"; ossimImageWriterFactoryRegistry::instance()-> printImageTypeList( ossimNotify(ossimNotifyLevel_NOTICE) ); } ossimString massageQuotedValue(const ossimString& value) { char quote = '\0'; if(*value.begin() == '"') { quote = '"'; } else if(*value.begin() == '\'') { quote = '\''; } if(quote == '\0') { return value; } std::vector splitString; value.split(splitString, quote); if(splitString.size() == 3) { return splitString[1]; } return value; } //************************************************************************************************* // FINALIZE -- Convenient location for placing debug breakpoint for catching program exit. //************************************************************************************************* void finalize(int code) { exit (code); } int main(int argc, char* argv[]) { static const char MODULE[] = "icp:main"; std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); ossimApplicationUsage* au = ap.getApplicationUsage(); au->setApplicationName(ap.getApplicationName()); au->setDescription(ap.getApplicationName()+ " copies any supported input image format to any supported output image format format"); au->setCommandLineUsage(ap.getApplicationName()+ " [options] "); au->addCommandLineOption("-h or --help", "Display this information"); au->addCommandLineOption("-a or --use-scalar-remapper", "Uses scalar remapper, transforms to 8-bit"); au->addCommandLineOption("-o or --create-overview", "Creates and overview for the output image"); au->addCommandLineOption("-b or --bands ", "uses the specified bands: ex. \"1, 2, 4\" will select bands 1 2 and 4 of the input image. " "Note: it is 1 based"); au->addCommandLineOption("-c or --compression-type ", "Uses compression. Currently valid for only tiff output -c jpeg will use jpeg compression"); au->addCommandLineOption("-e or --entry ", "For multi image handlers which entry do you wish to extract"); au->addCommandLineOption("-g", "Convert to grey scale."); au->addCommandLineOption("-q or --compression-quality ", "Uses compression. Valid for jpeg type. default is 75 where 100 is best and 1 is worst"); au->addCommandLineOption("--pixel-type ", "Valid values: area or point, this will determine if the tie point is upper left corner of " "the upper left pixel (area) or the center of the upper left corner (point), default=point. " "NOTE: This option will only affect the tiff writer."); au->addCommandLineOption("-r or --res-level ", "Which res level to extract from the input: ex -r 1 will get res level 1"); au->addCommandLineOption("-l or --start-line ", "Which start line do you wish to copy from the input. If none is given then 0 is used"); au->addCommandLineOption("-L or --end-line ", "Which end line do you wish to copy from the input. If none is given then max line is used"); au->addCommandLineOption("-s or --start-sample ", "Which start sample do you wish to copy from the input. If none is given then 0 is used"); au->addCommandLineOption("-p or --end-sample ", "The end sample you wish to copy from the input. If none is given then max sample is used"); au->addCommandLineOption("-t or --create-thumbnail ", "Takes an argument which is the maximum pixel dimension desired."); au->addCommandLineOption("-w or --tile-width ", "Defines the tile width for the handlers that support tiled output"); au->addCommandLineOption("--reader-prop ", "Adds a property to send to the reader. format is name=value"); au->addCommandLineOption("--writer-prop ", "Adds a property to send to the writer. format is name=value"); au->addCommandLineOption("--filter-spec ", "This is an external file spec that describes a chain for filtering the input image."); au->addCommandLineOption("--use-mask []", "Optionally specify name of mask file to use for masking the input image. If no filename " "given, then the default mask filename is used."); if (traceDebug()) CLOG << " Entered..." << std::endl; // Keyword list to initialize image writers with. ossimKeywordlist kwl; const char* PREFIX = "imagewriter."; bool lineEndIsSpecified = false; bool sampEndIsSpecified = false; bool lineStartIsSpecified = false; bool sampStartIsSpecified = false; bool convert_to_greyscale = false; bool create_overview = false; bool create_thumbnail = false; bool use_band_selector = false; bool use_scalar_remapper = false; bool use_mask = false; ossim_int32 tile_width = 0; ossim_int32 max_thumbnail_dimension = 0; ossim_int32 rr_level = 0; ossim_int32 line_start = 0; ossim_int32 line_stop = 0; ossim_int32 sample_start = 0; ossim_int32 sample_stop = 0; ossim_int32 cibcadrg_entry = 0; vector band_list(0); ossimFilename filterSpec, maskFile; std::map readerPropertyMap; std::map writerPropertyMap; if (ap.read("-h") || ap.read("--help")||(ap.argc() < 2)) { au->write(ossimNotify(ossimNotifyLevel_NOTICE)); usage(); // for writer output types finalize(0); } while(ap.read("--reader-prop", stringParam)) { std::vector nameValue; ossimString(tempString).split(nameValue, "="); if(nameValue.size() == 2) { readerPropertyMap.insert(std::make_pair(nameValue[0], massageQuotedValue(nameValue[1]))); } } while(ap.read("--writer-prop", stringParam)) { std::vector nameValue; ossimString(tempString).split(nameValue, "="); if(nameValue.size() == 2) { writerPropertyMap.insert(std::make_pair(nameValue[0], massageQuotedValue(nameValue[1]))); } } while(ap.read("-a") || ap.read("--use-scalar-remapper")) { use_scalar_remapper = true; } while(ap.read("--filter-spec",stringParam)) { filterSpec = ossimFilename(tempString); } while(ap.read("--use-mask") || ap.read("--use-mask",stringParam) ) { maskFile = ossimFilename(tempString); use_mask = true; } while(ap.read("-o") || ap.read("--create-overview")) { create_overview = true; } while(ap.read("-b", stringParam) || ap.read("--bands", stringParam)) { use_band_selector = true; ossimString s = tempString; band_list = s.split(","); } while(ap.read("-c", stringParam) || ap.read("--compression-type", stringParam)) { ossimString s = tempString; s.downcase(); kwl.add(PREFIX, ossimKeywordNames::COMPRESSION_TYPE_KW, s.c_str(), true); } while(ap.read("-e", stringParam) || ap.read("--entry", stringParam)) { cibcadrg_entry = ossimString(tempString).toInt(); } if ( ap.read("-g") ) { convert_to_greyscale = true; } while(ap.read("-q", stringParam) || ap.read("--compression-quality", stringParam)) { // Set the jpeg compression quality level. kwl.add(PREFIX, ossimKeywordNames::COMPRESSION_QUALITY_KW, tempString.c_str(), true); } while(ap.read("-r", stringParam) || ap.read("--res-level", stringParam)) { rr_level = ossimString(tempString).toInt(); } while(ap.read("-l", stringParam) || ap.read("--start-line", stringParam)) { lineStartIsSpecified = true; line_start = ossimString(tempString).toInt(); } while(ap.read("-L", stringParam) || ap.read("--end-line", stringParam)) { lineEndIsSpecified = true; line_stop = ossimString(tempString).toInt(); } while(ap.read("-s", stringParam) || ap.read("--start-sample", stringParam)) { sampStartIsSpecified = true; sample_start = ossimString(tempString).toInt(); } while(ap.read("-p", stringParam) || ap.read("--end-sample", stringParam)) { sampEndIsSpecified = true; sample_stop = ossimString(tempString).toInt(); } while(ap.read("-t", stringParam) || ap.read("--create-thumbnail", stringParam)) { create_thumbnail = true; max_thumbnail_dimension=ossimString(tempString).toInt(); } while(ap.read("-w", stringParam) || ap.read("-tile-width", stringParam)) { tile_width = ossimString(tempString).toInt(); if ((tile_width % 16) != 0) { ossimNotify(ossimNotifyLevel_NOTICE) << MODULE << " NOTICE:" << "\nTile width must be a multiple of 16!" << "\nDefaulting to 128" << std::endl; tile_width = 0; } } if (ap.read("--pixel-type", stringParam)) { ossimString os = tempString; os.downcase(); if (os.contains("area")) { kwl.add(PREFIX, ossimKeywordNames::PIXEL_TYPE_KW, "area", true); } else { kwl.add(PREFIX, ossimKeywordNames::PIXEL_TYPE_KW, "point", true); } } ap.reportRemainingOptionsAsUnrecognized(); // Three required args: output_type, input file, and output file. if (ap.errors()) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); finalize(0); } if (ap.argc() < 4) { au->write(ossimNotify(ossimNotifyLevel_NOTICE)); usage(); // for writer output types finalize(0); } // Set the writer type and the image type. ossimString output_type = ap.argv()[ap.argc()-3]; kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true); // Get the input file. const char* input_file = argv[ap.argc()-2]; // Get the output file. ossimFilename output_file = argv[ap.argc()-1]; if (traceDebug()) { CLOG << "DEBUG:" << "\noutput type: " << ap.argv()[ap.argc()-3] << "\ninput file: " << ap.argv()[ap.argc()-2] << "\noutput file: " << ap.argv()[ap.argc()-1] << std::endl; if (tile_width) { ossimNotify(ossimNotifyLevel_NOTICE) << "tile_width: " << tile_width << std::endl; } } // Get an image handler for the input file. ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(ossimFilename(input_file)); //ossimCibCadrgTileSource* its = PTR_CAST(ossimCibCadrgTileSource, ih.get()); //if (its) //{ if (cibcadrg_entry > 0) { ih->setCurrentEntry(cibcadrg_entry); } //} if (!ih) { ossimNotify(ossimNotifyLevel_NOTICE) << "Unsupported image file: " << input_file << "\nExiting application..." << std::endl; finalize(0); } if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_FATAL) << "Error reading image: " << input_file << "Exiting application..." << std::endl; finalize(1); } // Set the reader properties if any. if ( readerPropertyMap.size() ) { ossimPropertyInterface* pi = (ossimPropertyInterface*)ih.get(); std::map::iterator iter = readerPropertyMap.begin(); while(iter != readerPropertyMap.end()) { pi->setProperty(iter->first, iter->second); ++iter; } } ih->initialize(); ossimRefPtr source = ih.get(); if (traceDebug()) { CLOG << "DEBUG:" << "\nImage Handler: " << ih->getLongName() << std::endl; } // Start band selector section: //--- // If image handler is band selector, start with all bands. // Some sources, e.g. ossimEnviTileSource can pick up default // bands and filter out all other bands. //--- ih->setOutputToInputBandList(); if ( use_band_selector && (source->getNumberOfOutputBands() > 1) ) { // Build the band list. ossim_uint32 bands = source->getNumberOfOutputBands(); vector bl; ossim_uint32 i; for (i=0; i= bands) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " ERROR:" << "\nBand list range error!" << "\nHighest available band: " << bands << std::endl; finalize(1); } } ossimRefPtr bs = new ossimBandSelector(); bs->connectMyInputTo(source.get()); bs->setOutputBandList(bl); bs->enableSource(); bs->initialize(); source = bs.get(); if (traceDebug()) { CLOG << "DEBUG:" << "\nZero based output band list:" << std::endl; for (i=0; i rgb2grey = new ossimRgbToGreyFilter(); rgb2grey->connectMyInputTo( source.get() ); source = rgb2grey.get(); } ossimRefPtr mask_filter = 0; if (use_mask) { if (maskFile.empty()) { maskFile = ih->getFilenameWithThisExtension("mask"); } ossimImageHandler* mh = ossimImageHandlerRegistry::instance()->open(maskFile); if (mh == NULL) { ossimNotify(ossimNotifyLevel_FATAL)<<"ossim-icp -- Could not open raster mask file <" <. Maske request will be ignored. Aborting..."<connectMyInputTo(source.get()); mask_filter->setMaskSource(mh); // assumes ownership of mask handler object source = mask_filter.get(); } if(!filterSpec.empty()&&filterSpec.exists()) { ossimKeywordlist kwl; if(kwl.addFile(filterSpec)) { ossimRefPtr input = ossimObjectFactoryRegistry::instance()->createObject(kwl); if(input.valid()) { ossimImageSource* inputImageSource = dynamic_cast (input.get()); if(inputImageSource) { inputImageSource->connectMyInputTo(source.get()); source = inputImageSource; } } } } if (create_thumbnail == true) { // Get the rlevel that <= max thumbnail dimension. int max = 0; int level = 0; while (level < ((ossim_int32)ih->getNumberOfDecimationLevels()-1)) { int lines = ih->getNumberOfLines(level); int samples = ih->getNumberOfSamples(level); max = lines > samples ? lines : samples; if (max <= max_thumbnail_dimension) { break; } ++level; } if (max > max_thumbnail_dimension) { ossimNotify(ossimNotifyLevel_NOTICE) << " NOTICE:" << "\nLowest rlevel not small enough to fulfill " << "max_thumbnail_dimension requirement!" << std::endl; } // Set the reduced res level. This will override the -r option. rr_level = level; } // end of "if (create_thumbnail == true) // Start rlevel filter section. if( rr_level != 0 ) { //--- // Check for a valid reduced resolution level. // If the operator entered an invalid rr_level with the -r option, // spit out a warning and set to default "0". //--- if (rr_level >= (ossim_int32)(ih->getNumberOfDecimationLevels())) { ossimNotify(ossimNotifyLevel_NOTICE) << " WARNING:" << "\n\t Selected res level greater than available res levels." << "\n\t Defaulting to res level zero. " << std::endl; rr_level = 0; } ossimRefPtr rlevelFilter = new ossimRLevelFilter; rlevelFilter->connectMyInputTo(source.get()); source = rlevelFilter.get(); rlevelFilter->setCurrentRLevel(rr_level); if ( rr_level ) { rlevelFilter->setOverrideGeometryFlag(true); } } // Matches: if( rr_level != 0 ) ossimIrect output_rect = source->getBoundingRect(rr_level); //--- // If any of these are true the user wants to cut the rectangle. //--- if ( lineStartIsSpecified || lineEndIsSpecified || sampStartIsSpecified || sampEndIsSpecified) { if (!lineStartIsSpecified) line_start = output_rect.ul().y; if (!lineEndIsSpecified) line_stop = output_rect.lr().y; if (!sampStartIsSpecified) sample_start = output_rect.ul().x; if (!sampEndIsSpecified) sample_stop = output_rect.lr().x; //--- // Check the start and stop points and make sure they are in // the right order; if not, swap them. //--- if (line_stop < line_start) { ossimNotify(ossimNotifyLevel_NOTICE) << " WARNING:\n" << "\t Line end is less than line start, swapping." << std::endl; int tmp = line_start; line_start = line_stop; line_stop = tmp; } if (sample_stop < sample_start) { ossimNotify(ossimNotifyLevel_WARN) << " WARNING:\n" << "\t Sample end is less than sample start, swapping." << std::endl; int tmp = sample_start; sample_start = sample_stop; sample_stop = tmp; } output_rect.set_ulx(sample_start); output_rect.set_lrx(sample_stop); output_rect.set_uly(line_start); output_rect.set_lry(line_stop); } // End of "if ((lineEndIsSpecified) ||..." if (traceDebug()) { CLOG << "icp:main debug" << "\nrr_level: " << rr_level << "\noutput_rect: " << output_rect << "\nkeyword list: " << kwl << std::endl; } ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX); if( !writer) { ossimNotify(ossimNotifyLevel_NOTICE) << "\nCould not create writer of type: " << output_type << std::endl; usage(); finalize(1); } writer->connectMyInputTo(0, source.get()); if (tile_width) { // Set the tile size... writer->setTileSize(ossimIpt(tile_width, tile_width)); } writer->open(output_file); // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); if (writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK) { if( (ih->getOutputScalarType() != OSSIM_UCHAR) && ((PTR_CAST(ossimJpegWriter, writer.get())) || use_scalar_remapper)) { writer->setScaleToEightBitFlag(true); } ossimRefPtr cache = new ossimCacheTileSource; ossimIpt tileWidthHeight(ih->getImageTileWidth(), ih->getImageTileHeight()); // only use the cache if its stripped if(static_cast(tileWidthHeight.x) == ih->getBoundingRect().width()) { cache->connectMyInputTo(0, source.get()); cache->setTileSize(tileWidthHeight); writer->connectMyInputTo(0, cache.get()); } else { writer->connectMyInputTo(0, source.get()); } writer->initialize(); writer->setAreaOfInterest(output_rect); // Set the output rectangle. try { if ( writerPropertyMap.size() ) { ossimPropertyInterface* propInterface = (ossimPropertyInterface*)writer.get(); std::map::iterator iter = writerPropertyMap.begin(); while(iter!=writerPropertyMap.end()) { propInterface->setProperty(iter->first, iter->second); ++iter; } } writer->execute(); } catch(std::exception& e) { ossimNotify(ossimNotifyLevel_FATAL) << "icp:main ERROR:\n" << "Caught exception!\n" << e.what() << std::endl; } catch(...) { ossimNotify(ossimNotifyLevel_FATAL) << "icp:main ERROR:\n" << "Unknown exception caught!\n" << std::endl; } cache = 0; } else { ossimNotify(ossimNotifyLevel_FATAL) << "Error detected in the image writer..." << "\nExiting application..." << std::endl; finalize(1); } if (create_overview == true) { writer->writeOverviewFile(); } finalize(0); } ossim-Miami-2.9.1/apps/ossim-igen/000077500000000000000000000000001352751253100167305ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-igen/CMakeLists.txt000066400000000000000000000003161352751253100214700ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-igen INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-igen/ossim-igen.cpp000066400000000000000000000072161352751253100215140ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: igen.cpp 13025 2008-06-13 17:06:30Z sbortman $ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("igen:debug"); int main(int argc, char* argv[]) { std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "entered main" << std::endl; } argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" takes a spec file as input and produces a product"); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] "); argumentParser.getApplicationUsage()->addCommandLineOption("-t or --thumbnail", "thumbnail resolution"); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); if(argumentParser.read("-h") || argumentParser.read("--help")|| argumentParser.argc() <2) { argumentParser.getApplicationUsage()->write(std::cout); exit(0); } ossimRefPtr igen = new ossimIgen; double start=0, stop=0; ossimMpi::instance()->initialize(&argc, &argv); start = ossimMpi::instance()->getTime(); ossimKeywordlist kwl; kwl.setExpandEnvVarsFlag(true); while(argumentParser.read("-t", stringParam) || argumentParser.read("--thumbnail", stringParam)); if(ossimMpi::instance()->getRank() > 0) { // since this is not the master process // then it will set the keyword list form the master // so set this to empty // igen->initialize(ossimKeywordlist()); } else if(argumentParser.argc() > 1) { if(kwl.addFile(argumentParser.argv()[1])) { if(tempString != "") { kwl.add("igen.thumbnail", "true", true); kwl.add("igen.thumbnail_res", tempString.c_str(), true); } else { kwl.add("igen.thumbnail", "false", true); } kwl.add("igen.thumbnail_res", tempString.c_str(), true); igen->initialize(kwl); } } try // Can throw exception: { igen->outputProduct(); } catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_FATAL) << "ossim-igen caught exception:\n" << e.what() << std::endl; } if(ossimMpi::instance()->getRank() == 0) { stop = ossimMpi::instance()->getTime(); ossimNotify(ossimNotifyLevel_NOTICE) << "Time elapsed: " << (stop-start) << std::endl; } ossimMpi::instance()->finalize(); return 0; } ossim-Miami-2.9.1/apps/ossim-image-compare/000077500000000000000000000000001352751253100205145ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-image-compare/CMakeLists.txt000066400000000000000000000003311352751253100232510ustar00rootroot00000000000000#FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") #OSSIM_SETUP_APPLICATION(ossim-image-compare INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-image-compare/ossim-image-compare.cpp000066400000000000000000000113761352751253100250660ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-foo.cpp // // Author: Oscar Kramer // // Description: Compares pixel data between two images. Returns with 0 if same or 1 of different. // The input formats can be different -- the pixels are compared after any // unpacking and decompression. Only R0 is compared. // //---------------------------------------------------------------------------- #include #include #include #include #include #include using namespace std; template bool tilesAreDifferent(const ossimImageData* t1, const ossimImageData* t2) { ossimIpt size1 = t1->getImageRectangle().size(); ossimIpt size2 = t2->getImageRectangle().size(); int nbands1 = t1->getNumberOfBands(); int nbands2 = t2->getNumberOfBands(); if ((size1 != size2) || (nbands1 != nbands2)) return true; ossim_uint32 num_pixels = (ossim_uint32) (size1.x * size1.y); for (int band=0; bandgetBuf(band); T* buf2 = (T*) t2->getBuf(band); for ( ossim_uint32 p=0; paddOptions(ap); ossimInit::instance()->initialize(ap); try { if (ap.argc() != 3) { cout << "\nUsage: "< "< to <"<..."< h1 = registry->open(ossimFilename(argv[1])); if (!h1.valid()) { cout<<" Could not open first image at <"<. Aborting..."< h2 = registry->open(ossimFilename(argv[2])); if (!h1.valid()) { cout<<" Could not open second image at <"<. Aborting..."<close(); return 1; } // Establish the tile sequencer to loop over all tiles: ossimRefPtr sequencer1 = new ossimImageSourceSequencer(h1.get()); ossimRefPtr sequencer2 = new ossimImageSourceSequencer(h2.get()); sequencer1->setToStartOfSequence(); sequencer2->setToStartOfSequence(); // Begin loop over all tiles, checking them for any non-empty status: int tile_count = 0; bool diff_found = false; ossimRefPtr tile1 = sequencer1->getNextTile(); ossimRefPtr tile2 = sequencer2->getNextTile(); ossimScalarType stype = tile1->getScalarType(); while (tile1.valid() && tile2.valid() && !diff_found) { switch (stype) { case OSSIM_UINT8: case OSSIM_SINT8: diff_found = tilesAreDifferent(tile1.get(), tile2.get()); break; case OSSIM_UINT16: case OSSIM_SINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: diff_found = tilesAreDifferent(tile1.get(), tile2.get()); break; case OSSIM_UINT32: case OSSIM_SINT32: diff_found = tilesAreDifferent(tile1.get(), tile2.get()); break; case OSSIM_FLOAT32: diff_found = tilesAreDifferent(tile1.get(), tile2.get()); break; case OSSIM_FLOAT64: diff_found = tilesAreDifferent(tile1.get(), tile2.get()); break; default: cout<<" This datatype is not supported. Aborting..."<getNextTile(); tile2 = sequencer2->getNextTile(); ++tile_count; } h1->close(); h2->close(); if (diff_found) { cout << " DIFFERENCE FOUND AT TILE "< #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { int returnCode = 0; ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); if ( (ap.argc() < 2) || ap.read("-h") || ap.read("--help") ) { cout << "\nUsage: "<\n"< mapProj = new ossimEquDistCylProjection(); mapProj->setOrigin(observerGpt); mapProj->setMetersPerPixel(gsd); ossimDpt degPerPixel (mapProj->getDecimalDegreesPerPixel()); mapProj->setElevationLookupFlag(false); ossimGpt ulTiePt (observerGpt); ulTiePt.lat += degPerPixel.lat * (image_size.y-1)/2.0; ulTiePt.lon -= degPerPixel.lon * (image_size.x-1)/2.0; mapProj->setUlTiePoints(ulTiePt); ossimRefPtr geometry = new ossimImageGeometry(0, mapProj.get()); geometry->setImageSize(image_size); // Set the destination image size: ossimRefPtr outImage = ossimImageDataFactory::instance()->create(0, OSSIM_UINT16, 3, image_size.x, image_size.y); typedef uint16_t PIXEL_TYPE; double min = 0.0; double max = 255; if(outImage.valid()) outImage->initialize(); else return -1; outImage->fill(min); PIXEL_TYPE step = 8; PIXEL_TYPE value = 0; PIXEL_TYPE* bufferR = ( PIXEL_TYPE*) outImage->getBuf(0); PIXEL_TYPE* bufferG = ( PIXEL_TYPE*) outImage->getBuf(1); PIXEL_TYPE* bufferB = ( PIXEL_TYPE*) outImage->getBuf(2); ossim_uint32 i = 0; for (uint16_t y=1; y<=image_size.y; y++) { for (uint16_t x=0; x memSource = new ossimMemoryImageSource; memSource->setImage(outImage); memSource->setImageGeometry(geometry.get()); // Create TIFF writer: ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriterFromExtension(filename.ext()); if (!writer) throw runtime_error( "Unable to create writer given filename extension." ); writer->connectMyInputTo(0, memSource.get()); writer->setFilename(filename); bool success = writer->execute(); //writer->writeExternalGeometryFile(); if (success) cout<<"Wrote "< #include using namespace std; #include #include #include #include #include #include #include #include #include #include static void outputWriterTypes(); static void usage(); int main(int argc, char* argv[]) { std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->setApplicationName( argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription( argumentParser.getApplicationName()+" outputs metadata for an image."); argumentParser.getApplicationUsage()->setCommandLineUsage( argumentParser.getApplicationName()+" [options] "); argumentParser.getApplicationUsage()->addCommandLineOption( "-h or --help", "Shows help"); argumentParser.getApplicationUsage()->addCommandLineOption( "-t or --template", "Template to pass to meta data writer."); //--- // Extract optional arguments. //--- ossimFilename templateFile = ossimFilename::NIL; if(argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(std::cout); usage(); // For metadata writer types. exit(0); } if( argumentParser.read("-t", stringParam) || argumentParser.read("--template", stringParam) ) { templateFile = tempString.c_str(); } argumentParser.reportRemainingOptionsAsUnrecognized(); if (argumentParser.errors()) { argumentParser.writeErrorMessages(std::cout); exit(1); } if(argumentParser.argc() < 4) { argumentParser.getApplicationUsage()->write(std::cout); usage(); // For metadata writer types. exit(1); } ossimString metaDataWriterType = argumentParser.argv()[1]; ossimFilename imageFile = argumentParser.argv()[2]; ossimFilename outputFile = argumentParser.argv()[3]; ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(imageFile); if (!ih) { ossimNotify(ossimNotifyLevel_WARN) << "Could not open: " << imageFile << endl; } metaDataWriterType.downcase(); ossimRefPtr mw = ossimImageMetaDataWriterRegistry::instance()->createWriter( metaDataWriterType); if (!mw) { ossimNotify(ossimNotifyLevel_WARN) << "Could not create meta data writer of type: " << metaDataWriterType << endl; exit(1); } ossimKeywordlist kwl; kwl.add(ossimKeywordNames::FILENAME_KW, outputFile.c_str()); if (templateFile != ossimFilename::NIL) { if (kwl.addFile(templateFile) == false) { ossimNotify(ossimNotifyLevel_WARN) << "Could not load template file: " << templateFile << endl; exit(1); } } mw->loadState(kwl); mw->connectMyInputTo(ih.get()); if (mw->execute() == true) { ossimNotify(ossimNotifyLevel_NOTICE) << "Wrote file: " << outputFile.c_str() << endl; } return 0; } void usage() { cout << "\nNOTES:" << "\nValid metadata writer types:" << "\n"; outputWriterTypes(); } void outputWriterTypes() { std::vector metadatatypeList; ossimImageMetaDataWriterRegistry::instance()->getMetadatatypeList( metadatatypeList); std::copy(metadatatypeList.begin(), metadatatypeList.end(), std::ostream_iterator(std::cout, "\t\n")); } ossim-Miami-2.9.1/apps/ossim-img2rr/000077500000000000000000000000001352751253100172105ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-img2rr/CMakeLists.txt000066400000000000000000000003201352751253100217430ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-img2rr INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-img2rr/ossim-img2rr.cpp000066400000000000000000000653311352751253100222560ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Command line application "img2rr" to build overviews. // //---------------------------------------------------------------------------- // $Id: ossim-img2rr.cpp 2684 2011-06-07 15:32:23Z oscar.kramer $ #include /* for clock function */ #include #include #include #include #include #include /* for compression defines */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // for its keywords #include // for its keywords using namespace std; static ossimTrace traceDebug = ossimTrace("img2rr:debug"); static ossimTrace traceTime("time"); //************************************************************************************************* // FINALIZE -- Convenient location for placing debug breakpoint for catching program exit. //************************************************************************************************* static void finalize(int code) { exit (code); } static void outputWriterTypes() { ossimNotify(ossimNotifyLevel_NOTICE) << "\nValid overview types: " << std::endl; std::vector outputType; ossimOverviewBuilderFactoryRegistry::instance()->getTypeNameList(outputType); std::copy(outputType.begin(), outputType.end(), std::ostream_iterator(ossimNotify(ossimNotifyLevel_NOTICE), "\t\n")); } static void usage(ossimApplicationUsage* au, int code) { au->write(std::cout); outputWriterTypes(); ossimNotify(ossimNotifyLevel_NOTICE) << "\nExample command building j2k overviews with a histogram removing/overwriting\n" << "any existing overviews:\n" << "\nossim-img2rr -r -t ossim_kakadu_nitf_j2k --create-histogram image.tif\n" << std::endl; ossimMpi::instance()->finalize(); finalize( code ); } //************************************************************************************************* // Compute histogram after RRDSs have been established (2-pass solution) //************************************************************************************************* static void computeHistogram(ossimImageHandler* ih, const ossimFilename& histogramFile, ossimHistogramMode histoMode, ossim_float64 histoMin, ossim_float64 histoMax, ossim_uint32 histoBins) { if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "computeHistogram entered..." << "\nhistogramFile: " << histogramFile << std::endl; } if(ih) { ossimRefPtr histoSource = new ossimImageHistogramSource; ossimRefPtr writer = new ossimHistogramWriter; histoSource->setMaxNumberOfRLevels(1); // Currently hard coded... if( !ossim::isnan(histoMin) ) { histoSource->setMinValueOverride(histoMin); } if( !ossim::isnan(histoMax) ) { histoSource->setMaxValueOverride(histoMax); } if(histoBins > 0) { histoSource->setNumberOfBinsOverride(histoBins); } histoSource->setComputationMode(histoMode); histoSource->connectMyInputTo(0, ih); histoSource->enableSource(); writer->connectMyInputTo(0, histoSource.get()); writer->setFilename(histogramFile); theStdOutProgress.setFlushStreamFlag(true); writer->addListener(&theStdOutProgress); writer->execute(); writer=0; } } //************************************************************************************************* // Compute bit-mask after RRDSs have been established (2-pass solution). Returns TRUE if successful //************************************************************************************************* static bool computeBitMask(const ossimFilename& f, const ossimKeywordlist& bitMaskKwl) { bool rtn_status = true; ossimFilename tempKwlFile = f; tempKwlFile.setExtension("maskspec.kwl"); if (bitMaskKwl.write(tempKwlFile)) { ossimString command ("ossim-create-bitmask --spec_kwl "); command += tempKwlFile; ossimNotify(ossimNotifyLevel_INFO)<< " NOTICE:" <<" Launching ossim-create-bitmask process.\n"<< std::endl; if (system(command.chars())) { ossimNotify(ossimNotifyLevel_WARN)<<" Error code returned from " <<"ossim-create-bitmask utility. Mask will not be generated."<< std::endl; rtn_status = false; } tempKwlFile.remove(); } else { ossimNotify(ossimNotifyLevel_WARN)<<" Unable to write temporary bit-mask" <<"spec KWL to <"<. Mask will not be generated."<< std::endl; rtn_status = false; } return rtn_status; } //************************************************************************************************* // MAIN //************************************************************************************************* int main(int argc, char* argv[]) { #if OSSIM_HAS_MPI ossimMpi::instance()->initialize(&argc, &argv); #endif double start_time = 0.0; if (ossimMpi::instance()->getRank() == 0) { ossimNotify(ossimNotifyLevel_INFO) << "MPI running with " << ossimMpi::instance()->getNumberOfProcessors() << " processors..." << std::endl; start_time = ossimMpi::instance()->getTime(); } ossimString tempString; double tempDouble, tempDouble2; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser::ossimParameter doubleParam(tempDouble); ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); ossimApplicationUsage* au = ap.getApplicationUsage(); au->setApplicationName(ap.getApplicationName()); au->setDescription(ap.getApplicationName()+ " Creates overviews and optionally a histogram for the passed in image. "); au->setCommandLineUsage(ap.getApplicationName()+ " [options] "); au->addCommandLineOption("-a or --include-fullres", "Wants to include full res dataset as well as reduced res sets."); au->addCommandLineOption("--compression-quality", "Compression quality varies from 0 to 100, where 100 is best. Currently only for JPEG " "compression"); au->addCommandLineOption("--compression-type", "Compression type can be: NONE, JPEG, PACKBITS, or DEFLATE"); au->addCommandLineOption("--create-histogram", "Computes full histogram alongside overview."); au->addCommandLineOption("--create-histogram-fast", "Computes a histogram in fast mode which samples partial tiles."); au->addCommandLineOption("--create-mask", "Computes and writes out an alpha mask to a separate .mask file."); au->addCommandLineOption("-d", "Write overview to directory specified."); au->addCommandLineOption("-e or --entry", "Give the entry(zero based) to build an overview for."); au->addCommandLineOption("-h or --help", "Shows help"); au->addCommandLineOption("--histogram-bins", "Number of histogram bins. This will override the default for scalar type. Also this will " "force a separate pass."); au->addCommandLineOption("--histogram-min", "Minimum histogram value to use. This will override the default for scalar type. Also this " "will force a separate pass."); au->addCommandLineOption("--histogram-max", "Maximum histogram value to use. This will override the default for scalar type. Also this " "will force a separate pass."); au->addCommandLineOption("--histogram-r0", "Forces create-histogram code to compute a histogram using r0 instead of the starting " "resolution for the overview. Requires a separate pass of R0 layer."); au->addCommandLineOption("--list-entries", "Lists the entries within the image"); au->addCommandLineOption("--mask-mode ", "Specifies how to treat multi-band imagery when determining whether pixel will be masked " "according to the defined target value or range. Possible modes are: " "\"mask_full_and_partial_targets\" (default) | \"mask_only_full_targets\"."); au->addCommandLineOption("--mask-range ", "Specifies the range of pixels to target for masking out."); au->addCommandLineOption("--mask-value ", "Specifies the unique pixel value to target for masking out."); au->addCommandLineOption("-o", "Write overview to file specified. If used on a multi-entry file, given \"foo.ovr\" you will" "get: \"foo_e0.ovr\""); au->addCommandLineOption( "-r or --rebuild", "Rebuild overviews even if they are already present."); au->addCommandLineOption("-s", "Stop dimension for overviews. This controls how \nmany layers will be built. If set to 64 " "then the builder will stop when height and width for current level are less than or equal to" " 64. Note a default can be set in the ossim preferences file, setting the keyword " "\"overview_stop_dimension\"."); au->addCommandLineOption("--scanForMinMax", "Turns on min, max scanning when reading tiles. This option assumes the null is known."); au->addCommandLineOption("--scanForMinMaxNull", "Turns on min, max, null scanning when reading tiles. This option tries to find a null value which is useful for float data."); au->addCommandLineOption("--set-property", "key:value NOTE: separate key value by a colon. Deprecated, use --writer-prop instead."); au->addCommandLineOption( "-t or --type", "see list at bottom for valid types. (default = ossim_tiff_box)"); au->addCommandLineOption("--tile-size", "Defines the tile size for the supported overview handler."); au->addCommandLineOption("--version", "Outputs version information."); au->addCommandLineOption("--writer-prop", "Adds a property to send to the writer. format is name=value"); // Optional arguments. bool copyAllFlag = false; bool useEntryIndex = false; bool listEntriesFlag = false; bool tileSizeFlag = false; bool rebuildFlag = false; bool scanForMinMax = false; bool scanForMinMaxNull = false; // Optional histogram creation arguments: ossimHistogramMode histoMode = OSSIM_HISTO_MODE_UNKNOWN; bool histoR0Flag = false; bool histoFastFlag = false; ossim_float64 histoMin = ossim::nan(); ossim_float64 histoMax = ossim::nan(); ossim_uint32 histoBins = 0; ossimFilename inputFile = ossimFilename::NIL; ossimFilename outputFile = ossimFilename::NIL; ossimFilename outputDir = ossimFilename::NIL; std::vector entryList; ossimIpt tileSize(64, 64); ossim_uint32 overviewStopDimension(0); bool listFramesFlag = false; //--- // Temporary way to pass generic things to builder. //--- std::vector< ossimRefPtr > propertyList(0); ossimString overviewType = "ossim_tiff_box"; // Compression typedefs in tiff.h ossimString compressionType = ""; ossimString compressionQuality = "75"; if(ap.read("-h") || ap.read("--help")) { usage( au, 0 ); } if ( ap.read("--version") ) { ossimNotify(ossimNotifyLevel_NOTICE) << ap.getApplicationName().c_str() << " " << ossimInit::instance()->instance()->version().c_str() << std::endl; finalize(0); } if(ap.read("--compression-quality", stringParam)) { compressionQuality = tempString; } if(ap.read("--compression-type", stringParam)) { compressionType = tempString; } if( ap.read("--create-histogram")) { histoMode = OSSIM_HISTO_MODE_NORMAL; } if( ap.read("--create-histogram-fast")) { histoMode = OSSIM_HISTO_MODE_FAST; } if( ap.read("--histogram-r0")) { histoR0Flag = true; } if(ap.read("--histogram-min", stringParam)) { histoMin = tempString.toFloat64(); } if(ap.read("--histogram-max", stringParam)) { histoMax = tempString.toFloat64(); } if(ap.read("--histogram-bins", stringParam)) { histoBins = tempString.toUInt32(); } if(ap.read("--tile-size", stringParam)) { tileSize.x = tempString.toInt32(); tileSize.y = tileSize.x; tileSizeFlag = true; } if( ap.read("--list-entries")) { listEntriesFlag = true; } if( ap.read("-o", stringParam) ) { outputFile = tempString.trim(); } if( ap.read("-d", stringParam) ) { outputDir = tempString.trim(); } if( ap.read("-t", stringParam) || ap.read("--type", stringParam)) { overviewType = tempString.trim(); } if( ap.read("-s", stringParam) ) { overviewStopDimension = tempString.toUInt32(); } if( ap.read("--scanForMinMax" ) ) { scanForMinMax = true; } if( ap.read("--scanForMinMaxNull" ) ) { scanForMinMaxNull = true; } if(ap.read("-a") || ap.read("--include-fullres")) { copyAllFlag = true; } if(ap.read("-r") || ap.read("--rebuild")) { rebuildFlag = true; } while(ap.read("-e", stringParam) || ap.read("--entry", stringParam)) { entryList.push_back(ossimString(tempString).toUInt32()); useEntryIndex = true; } while( ap.read( "--set-property", stringParam) ) { if (tempString.size()) { ossimString propertyName; ossimString propertyValue; std::vector v = tempString.split(":"); if (v.size() == 2) { propertyName = v[0]; propertyValue = v[1]; } else { propertyName = tempString; } ossimRefPtr p = new ossimStringProperty(propertyName, propertyValue); propertyList.push_back(p); } } while(ap.read("--writer-prop", stringParam)) { if (tempString.size()) { ossimString propertyName; ossimString propertyValue; std::vector v = tempString.split("="); if (v.size() == 2) { propertyName = v[0]; propertyValue = v[1]; } else { propertyName = tempString; } ossimRefPtr p = new ossimStringProperty(propertyName, propertyValue); propertyList.push_back(p); } } // Handle Mask options: bool createMaskFlag = false; double target_min = 0; // default double target_max = 0; // default ossimString mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET"; // default if( ap.read("--create-mask")) { createMaskFlag = true; } if (ap.read("--mask-range", doubleParam, doubleParam2)) { target_min = tempDouble; target_max = tempDouble2; createMaskFlag = true; } if (ap.read("--mask-value", doubleParam)) { target_min = tempDouble; target_max = target_min; createMaskFlag = true; } ossimString mask_mode_arg; if (ap.read("--mask-mode", stringParam)) { mask_mode_arg = tempString; createMaskFlag = true; if (mask_mode_arg == "mask_full_and_partial_targets") mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET"; else if (mask_mode_arg == "mask_only_full_targets") mask_mode = "REPLACE_ONLY_FULL_TARGETS"; else { ossimNotify(ossimNotifyLevel_NOTICE)<< ap.getApplicationName().c_str() << " " << " Unknown mask-mode <"< specified. See usage below." << std::endl; usage( au, 1 ); } } ap.reportRemainingOptionsAsUnrecognized(); if (ap.errors()) { ap.writeErrorMessages(std::cout); ossimMpi::instance()->finalize(); finalize(1); } if(ap.argc() < 2) { usage( au, 1 ); } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nhistoMode: " << histoMode << "\nhistoMin: " << histoMin << "\nhistoMax: " << histoMax << "\nhistoBins: " << histoBins << "\nhistoR0Flag: " << histoR0Flag << "\nscanForMinMax: " << scanForMinMax << "\nscanForMinMaxull: " << scanForMinMaxNull << std::endl; } ossim_int32 returnStatus = ossimErrorCodes::OSSIM_OK; // Keep a list of files for time command. std::vector overviewFiles; // BIG LOOP over all input files specified on command line: for (int i=1 ; i < ap.argc(); i++) { inputFile = ap.argv()[i]; ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(inputFile); if (!ih.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: Unable to open image file " << inputFile << std::endl; continue; } // Get the list of entries if (entryList.size() == 0) ih->getEntryList(entryList); // User wants to see entries. if(listEntriesFlag) { std::cout << "Entries: "; std::copy(entryList.begin(), entryList.end(), std::ostream_iterator(std::cout, " ")); std::cout << std::endl; finalize( returnStatus ); } ossimRefPtr ob = ossimOverviewBuilderFactoryRegistry::instance()->createBuilder(overviewType); if ( ob.valid() == false ) { std::cout << "img2rr ERROR:\nCould not create builder for: "<< overviewType << endl; usage( au, 1); } propertyList.push_back(new ossimStringProperty("copy_all_flag", ossimString::toString(copyAllFlag))); propertyList.push_back(new ossimStringProperty(ossimKeywordNames::COMPRESSION_TYPE_KW, compressionType)); propertyList.push_back(new ossimStringProperty(ossimKeywordNames::COMPRESSION_QUALITY_KW, compressionQuality)); if(tileSizeFlag) { propertyList.push_back(new ossimStringProperty(ossimKeywordNames::OUTPUT_TILE_SIZE_KW, tileSize.toString())); } // Generic property setting. if (propertyList.size()) ob->setProperties(propertyList); if (overviewStopDimension) ob->setOverviewStopDimension(overviewStopDimension); // INNER LOOP over each entry in file. At least the default 0 entry is represented: for(ossim_uint32 idx = 0; idx < entryList.size(); ++idx) { // If image is a single entry, avoid using entry index in filename: if ((entryList.size() == 1) && (entryList[0] == 0)) { useEntryIndex = false; } else { useEntryIndex = true; } // Explicitly set an entry number if specified: if (useEntryIndex) { ih->setCurrentEntry(entryList[idx]); std::cout << "Creating overviews for entry number: "<< entryList[idx]<< std::endl; } else std::cout << "Creating overviews for file: " << inputFile << std::endl; if (outputFile.empty()) outputFile = ih->getFilenameWithThisExtension(ossimString(".ovr"), useEntryIndex); // -d "output directory option. if ( (outputDir != ossimFilename::NIL) && (outputDir.isDir()) ) { outputFile = outputDir.dirCat(outputFile.file()); //check if omd file exists ossimFilename omdFileName = inputFile.file(); omdFileName.setExtension("omd"); ossimFilename omdFile = outputDir.dirCat(omdFileName); if (omdFile.exists()) ih->setSupplementaryDirectory(omdFile.path()); } // Force a rebuild of existing OVR file. NOTE: the input image file may still contain // it's own internal RRDSs. if (rebuildFlag) { ih->closeOverview(); if (outputFile.exists()) outputFile.remove(); } if ( scanForMinMax ) ob->setScanForMinMax(scanForMinMax); if ( scanForMinMaxNull ) ob->setScanForMinMaxNull(scanForMinMaxNull); //--- // Histogram creation: // Two paths: // // 1) In conjunction with overview sequencer which is most efficient. // 2) Separate function call in which case the image will be scanned when // building overviews and to create histo. // // Notes: // // Path # 1 is most efficient; however limitted to single process. // // If the source image has overviews and the user wants histogram from r0 we use // path #2. // // If options for min, max or bin count we use path 2. // // NOTE: Similar situation exists for mask creation. If partial or complete overviews // already exist, we'll need to create bitmask after OVRs are generated instead of during. //--- bool singlePassHistoFlag = true; if ( histoMode != OSSIM_HISTO_MODE_UNKNOWN ) { if ( ( ossimMpi::instance()->getNumberOfProcessors() > 1) || ( ih->hasOverviews() && histoR0Flag ) || ( !ossim::isnan(histoMin) ) || ( !ossim::isnan(histoMax) ) || ( histoBins ) || ( overviewType.contains("gdal") ) ) { singlePassHistoFlag = false; } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "singlePassHistoFlag: " << singlePassHistoFlag << std::endl; } if ( singlePassHistoFlag ) { // This will tell the overview builder to make a histogram. ob->setHistogramMode(histoMode); } } ob->setOutputFile(outputFile); ob->setInputSource(ih.get()); // Tell the overview to compute alpha mask according to KWL spec assembled here. ossimKeywordlist bitMaskKwl; bool singlePassMaskPerformed = false; if (createMaskFlag) { bitMaskKwl.add(ossimKeywordNames::IMAGE_FILE_KW, inputFile.chars()); ossimFilename maskFileName = outputFile; maskFileName.setExtension("mask"); bitMaskKwl.add(ossimKeywordNames::OUTPUT_FILE_KW, maskFileName.chars()); ossimString target_str (ossimString::toString(target_min)+" "); target_str += ossimString::toString(target_max); bitMaskKwl.add(ossimPixelFlipper::PF_TARGET_RANGE_KW, target_str.chars()); bitMaskKwl.add(ossimPixelFlipper::PF_REPLACEMENT_MODE_KW, mask_mode.chars()); bitMaskKwl.add(ossimPixelFlipper::PF_REPLACEMENT_VALUE_KW, (int) 0); bitMaskKwl.add(ossimBitMaskWriter::BM_STARTING_RLEVEL_KW, (int) 0); // If the image already has no overviews, we can generate them in a single pass along // with the RRDSs (similar situation to histogram path 1): if (!ih->hasOverviews()) { singlePassMaskPerformed = true; ob->setBitMaskSpec(bitMaskKwl); } } if ( traceTime() ) overviewFiles.push_back(ob->getOutputFile()); // Create the overview for this entry in this file: bool buildOvrStatus = ob->execute(); if ( !buildOvrStatus ) { returnStatus = ossimErrorCodes::OSSIM_ERROR; } //--- // See if we need to run create histo the old way. // Note if the build status is false and a histogram mode was set run // it the old way. The execute may have returned false because there // were already required overviews. //--- if ( ( (histoMode != OSSIM_HISTO_MODE_UNKNOWN) && !singlePassHistoFlag ) || ( (histoMode != OSSIM_HISTO_MODE_UNKNOWN) && !buildOvrStatus ) ) { ossimFilename histoFile (outputFile); histoFile.setExtension(".his"); computeHistogram(ih.get(), histoFile, histoMode, histoMin, histoMax, histoBins); } // If bit-mask was requested but could not be generated in a single pass, then need to // spawn the create-bit-mask app to do it: if (createMaskFlag && !singlePassMaskPerformed) computeBitMask(outputFile, bitMaskKwl); // Specified output filename (if any) is good for only single image/single entry. After // that, reset the filename to null so it assumes default name. The user should never // specify an output file name if multiple images are being processed. outputFile.clear(); } // END of for-loop over image file's entries // Finished with this file's image handler: ih->close(); } // end of for-loop over all input files if(ossimMpi::instance()->getRank() == 0) { double stop_time = ossimMpi::instance()->getTime(); std::cout << "Elapsed time: " << (stop_time-start_time) << std::endl; } ossimMpi::instance()->finalize(); if ( traceTime() ) { cout << "size: " << overviewFiles.size() << endl; if ( overviewFiles.size() ) { const ossim_float64 MB = 1048576.0; // 1024*1024 ossim_float64 size = 0; std::vector::const_iterator i = overviewFiles.begin(); while ( i < overviewFiles.end() ) { size += (*i).fileSize(); ++i; } ossim_float64 seconds = clock()/CLOCKS_PER_SEC; ossim_float64 megaBytes = size/MB; ossim_float64 megaBytesPerSecond = megaBytes/seconds; ossimNotify(ossimNotifyLevel_INFO) << std::setiosflags(ios::fixed) << std::setprecision(2) << "Wrote " << megaBytes << " mega bytes in " << seconds << " seconds. MB/sec=" << megaBytesPerSecond << std::endl; } } finalize( returnStatus ); } ossim-Miami-2.9.1/apps/ossim-info/000077500000000000000000000000001352751253100167415ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-info/CMakeLists.txt000066400000000000000000000003161352751253100215010ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-info INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-info/ossim-info.cpp000066400000000000000000000035571352751253100215420ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossim-info.cpp 18619 2011-01-03 10:33:51Z dburken $ #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { //--- // Get the arg count so we can tell if an arg was consumed by // ossimInit::instance()->initialize //--- int originalArgCount = argc; ossimArgumentParser ap(&argc, argv); // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); //--- // Avoid going on if a global option was consumed by ossimInit::initialize // like -V or --version option and the arg count is down to 1. //--- if ( ( ap.argc() > 1 ) || ( ap.argc() == originalArgCount ) ) { // Make the info object. ossimRefPtr oi = new ossimInfo; try { //--- // Initialize will take the options passed in and set things to output // information for. // // ossimInfo::initialize can throw an exception. //--- bool continue_after_init = oi->initialize(ap); if ( continue_after_init ) { // This will actually output the information. oi->execute(); } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; return 1; } } // End: if ( ( ap.argc() > 1 ) ... return 0; } // End of main... ossim-Miami-2.9.1/apps/ossim-modopt/000077500000000000000000000000001352751253100173105ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-modopt/CMakeLists.txt000066400000000000000000000003201352751253100220430ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-modopt INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-modopt/ossim-modopt.cpp000066400000000000000000000075131352751253100224540ustar00rootroot00000000000000//******************************************************************* // // Author: Frederic Claudel // to use after correl, with a tie points file // //******************************************************************* #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include //error header static const char* PROGERR = "ERROR modopt"; int main(int argc, char *argv[]) { //error status : initially ok int result=0; //init OSSIM (prefs, elevation, plugins, etc) std::string tempString; ossimArgumentParser::ossimParameter argString(tempString); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); //init with default parms ossimRefPtr moObject = ossimObjectFactoryRegistry::instance()->createObject(ossimString("ossimModelOptimizer")); ossimPropertyInterface* moPropertyInterface = PTR_CAST(ossimPropertyInterface, moObject.get()); ossimProcessInterface* moProcessInterface = PTR_CAST(ossimProcessInterface, moObject.get()); if(!moObject.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "Unable to find object ossimModelOptimizer in registration plugin" << std::endl; exit(1); } ossimRefPtr modelDefinition = moPropertyInterface->getProperty("model_definition"); ossimRefPtr outGeomFilename = moPropertyInterface->getProperty("geom_output_filename"); //read args : options argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" optimizes a projection model using tie points"); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] "); argumentParser.getApplicationUsage()->addCommandLineOption("-h", ossimString("display Usage/Help")); argumentParser.getApplicationUsage()->addCommandLineOption("-d", ossimString(" : default=") + (modelDefinition.valid()?modelDefinition->valueToString():ossimString("")) ); argumentParser.getApplicationUsage()->addCommandLineOption("-g", ossimString(" : output geometry file, default=") + (outGeomFilename.valid()?outGeomFilename->valueToString():ossimString("")) ); if (argumentParser.read("-h")) { //help/usage argumentParser.getApplicationUsage()->write(std::cout); result = 0; } else { if (argumentParser.read("-d", argString)) { moPropertyInterface->setProperty("model_definition", tempString); } if (argumentParser.read("-g", argString)) { moPropertyInterface->setProperty("geom_output_filename", tempString); } //read mandatory args : master and slave images //should only remain 2 args int nbargs = argumentParser.argc() - 1; if (nbargs == 1) { ossimString tiePtPath(argumentParser.argv()[1]); moPropertyInterface->setProperty("gml_tieset_filename", tiePtPath); moProcessInterface->execute(); //if (result==0) result = mo.loadGMLTieSet(tiePtPath) ? 0 : 5 ; //if (result==0) result = mo.execute() ? 0 : 4 ; } else { cerr< // currently this option has been tested // with ossimTiffWriter and ossimJpegWriter // writer.type: ossimTiffWriter // writer.filename: // Currently, the mosaic application supports // SIMPLE mosaics (ie. no blending algorithms) // FEATHER mosaic or // BLEND mosaic.type: SIMPLE // product type and projection information // is optional. It will use the first images // geometry information instead. // the type is the class name. Go into the projections/map_projections directory // product.type: // product.meters_per_pixel_y: // product.meters_per_pixel_x: // product.central_meridian: // product.origin_latitude: // product.zone: // product.std_parallel_1: // product.std_parallel_2: // product.scale_factor: // product.false_easting: // product.false_northing: EXAMPLE KEYWORDLIST END then execute: ossim-mosaic -k -o Note: the is an filename with the above options the is the output file the mosaic is written to. Note: I only support geotiff write now. II. USING NO KEYWORDLIST TO GENERATE A MOSAIC EXAMPLE OF MOSAICING COMMAND LINE WITHOUT KEYWORDLIST ossim-mosaic -m -o -i .... Note: 1. can be 1) SIMPLE, 2) BLEND, 3) FEATHER 2. the list of files you wish to mosaic must be last. Notice you don't have the ability to change projections like you did with the keyword list. The default output projection is the first image in the list that is a map projection. III TIPS AND TRICKS 1) How can I use mosaic application to quickly mosaic a number of images in a given directory without hand typing the images in. Under unix based systems we can capture the output of one program and feed it as input into another: Go to the directory that has all the images you wish to mosaic and then issue the following: ossim-mosaic -o ./output.tif -i `ls *.tif` this will feed all images with a .tif extnesion into the mosaic app and output a geotif file called output.tif. 2) What if the files are in separate directories ossim-mosaic -o ./output.tif -i `find . -name "*.tif"` will scan all subdirectories and feed the output as input to the mosaic application. ossim-Miami-2.9.1/apps/ossim-mosaic/ossim-mosaic.cpp000066400000000000000000000431141352751253100223730ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: mosaic.cpp 13312 2008-07-27 01:26:52Z gpotts $ #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug(ossimString("mosaic:main")); void outputTemplateKeywordlist(const ossimFilename &templateFilename) { ofstream out(templateFilename.c_str()); out << "file1.filename: " << endl << "file2.filename: " << endl << "// :\n" << "// :\n" << "// fileN: " << endl << "\n// currently this option has been tested\n" << "// with ossimTiffWriter and ossimJpegWriter\n" << "// writer.type: ossimTiffWriter" << endl << "// writer.filename: " << endl << "\n// Currently, the mosaic application supports\n" << "// SIMPLE mosaics (ie. no blending algorithms)\n" << "// BLEND for maps or layers that you want to blend together\n" << "// FEATHER for applying a spatial feaher along overlapped regions\n" << "// mosaic.type: SIMPLE" << endl << "\n// product type and projection information" << endl << "// is optional. It will use the first images"< result = 0; // if we don't have a prduct output specified // we will just use the first image. if(!productType&&!productGeom) { if(inputSources.size() < 1) { return NULL; } ossimKeywordlist geom; ossimImageChain* imageChain = PTR_CAST(ossimImageChain, inputSources[0].get()); ossimConnectableObject* source = NULL; if(!imageChain) { source = PTR_CAST(ossimImageHandler, inputSources[0].get()); } else { source = imageChain->findFirstObjectOfType(STATIC_TYPE_INFO(ossimImageHandler)); } if(source) { ossimImageHandler* handler = PTR_CAST(ossimImageHandler, source); if(handler) { ossimRefPtr geom = handler->getImageGeometry(); ossimRefPtr temp = geom->getProjection(); result = PTR_CAST(ossimMapProjection, temp.get()); } } else { return NULL; } } else { ossimRefPtr temp = ossimProjectionFactoryRegistry::instance()->createProjection(kwl, "product."); result = PTR_CAST(ossimMapProjection, temp.get()); } return result.release(); } bool buildRenderers(const ossimKeywordlist& specFile, ossimConnectableObject::ConnectableObjectList& imageSources, ossimMapProjection* productProjection) { ossim_int32 index = 0; // add the renderer to each chain. First, look for // the ossimImageHandler and get the image // geometry for this chain. The add the ossimImageRenderer // to each chain and then connect it up // for(index = 0; index < (ossim_int32)imageSources.size(); ++index) { ossimImageChain* imageChain = PTR_CAST(ossimImageChain, imageSources[index].get()); if(imageChain) { ossimConnectableObject* source = imageChain->findFirstObjectOfType(STATIC_TYPE_INFO(ossimImageHandler)); if(source) { ossimImageHandler* imageHandler = PTR_CAST(ossimImageHandler, source); ossimRefPtr geom = imageHandler->getImageGeometry(); // now add the image/view transform to the // renderer. // if(geom.valid()) { ossimImageSource* last = imageChain->getFirstSource(); ossimImageRenderer* renderer = new ossimImageRenderer; renderer->connectMyInputTo(0, PTR_CAST(ossimConnectableObject, last)); imageChain->add(renderer); ossimImageViewProjectionTransform* transform = new ossimImageViewProjectionTransform; transform->setImageGeometry(geom.get()); ossimRefPtr viewGeom = new ossimImageGeometry(); viewGeom->setProjection(productProjection); // Make a copy of the view projection for // each chain by passing in the object and not // the pointer. transform->setViewGeometry(viewGeom.get()); renderer->setImageViewTransform(transform); imageChain->initialize(); } else { return false; } } } } return true; } bool buildChains(std::vector& fileList, ossimConnectableObject::ConnectableObjectList& chains) { bool result = true; chains.clear(); for(ossim_int32 index = 0; index < (ossim_int32)fileList.size();++index) { ossimRefPtr handler = ossimImageHandlerRegistry::instance()->open(fileList[index]); if(handler.valid()) { ossimImageChain* imageChain = new ossimImageChain; imageChain->add(handler.get()); chains.push_back(imageChain); } else { cerr << "Error: Unable to load image " << fileList[index] << endl; result = false; } } return result; } bool buildChains(const ossimKeywordlist& kwl, ossimConnectableObject::ConnectableObjectList& chains) { ossim_int32 index = 0; ossim_int32 result = kwl.getNumberOfSubstringKeys("file[0-9]+\\.filename"); const char* lookup = NULL; ossim_int32 numberOfMatches = 0; vector fileList; while(numberOfMatches < result) { ossimString searchValue = "file" + ossimString::toString(index); ossimString filename = searchValue + ".filename"; lookup = kwl.find(filename.c_str()); if(lookup) { fileList.push_back(ossimFilename(lookup)); ++numberOfMatches; } ++index; } return buildChains(fileList, chains); } ossimRefPtr createMosaic(const ossimKeywordlist& kwl, ossimConnectableObject::ConnectableObjectList& inputSources) { const char* mosaicType = kwl.find("mosaic.type"); //ossimImageCombiner* mosaic = NULL; ossimRefPtr mosaic = 0; if(mosaicType) { if(ossimString(mosaicType).upcase() == "FEATHER") { mosaic = new ossimFeatherMosaic; } else if(ossimString(mosaicType).upcase() == "BLEND") { mosaic = new ossimBlendMosaic; } else { mosaic = PTR_CAST(ossimImageCombiner, ossimObjectFactoryRegistry::instance()->createObject(ossimString(mosaicType))); } } else { mosaic = new ossimImageMosaic; } if (!mosaic) cerr << "Could not create Mosaic!"; for(ossim_int32 index = 0; index < (ossim_int32)inputSources.size(); ++index) { mosaic->connectMyInputTo(inputSources[index].get()); } mosaic->initialize(); return mosaic; } ossimString massageQuotedValue(const ossimString& value) { char quote = '\0'; if(*value.begin() == '"') { quote = '"'; } else if(*value.begin() == '\'') { quote = '\''; } if(quote == '\0') { return value; } std::vector splitString; value.split(splitString, quote); if(splitString.size() == 3) { return splitString[1]; } return value; } int main(int argc, char *argv[]) { ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName() +" Takes a list of images and outputs to mosaic."); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] "); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("-k", "keyword list to load from"); argumentParser.getApplicationUsage()->addCommandLineOption("-m", "Mosiac type (SIMPLE, BLEND, FEATHER, or any MosaicCombinerType [ossimClosestToCenter, ossimFeatherMosaic, etc..]) (default=SIMPLE"); argumentParser.getApplicationUsage()->addCommandLineOption("-w", "Writer type (tiff_strip, jpeg, etc... see ossim-info --writers) (default=tiff_strip)"); argumentParser.getApplicationUsage()->addCommandLineOption("--writer-prop ", "Adds a property to send to the writer. format is name=value"); argumentParser.getApplicationUsage()->addCommandLineOption("-t", "output a keyword list template"); // Allocate some stuff up front for use later ossimKeywordlist kwl; ossimString theWriterType = "tiff_strip"; bool keywordlistSupplied = false; bool optionGiven = false; ossimFilename outfile = ""; std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); std::map writerPropertyMap; // user input writer props, should use those while(argumentParser.read("--writer-prop", stringParam)) { std::vector nameValue; ossimString(tempString).split(nameValue, "="); if(nameValue.size() == 2) { writerPropertyMap.insert(std::make_pair(nameValue[0], massageQuotedValue(nameValue[1]))); } } // User input a writer type while (argumentParser.read("-w", stringParam)) { theWriterType = tempString; } // Keyword list to load from while (argumentParser.read("-k", stringParam)) { kwl.addFile(tempString.c_str()); keywordlistSupplied = true; optionGiven = true; } // Mosiac type while (argumentParser.read("-m", stringParam)) { ossimString opt = tempString; opt = opt.upcase(); opt = opt.trim(); if( (opt != "SIMPLE")&& (opt != "BLEND")&& (opt != "FEATHER")) { opt = tempString; } kwl.add("mosaic.type", opt.c_str(), true); } // Output KWL template while (argumentParser.read("-t", stringParam)) { ossimFilename templateFilename = tempString.c_str(); outputTemplateKeywordlist(templateFilename); exit(0); } // Display Help - changed 3 to 2, because you can just supply a kwl and an output while (argumentParser.read("-h") || argumentParser.read("--help") || (argumentParser.argc() < 2 )) { argumentParser.getApplicationUsage()->write( ossimNotify(ossimNotifyLevel_INFO)); exit(0); } int argCount = argumentParser.argc(); // Get the input files. for (int i=1; i< (argCount-1); ++i) { ossimFilename f = argv[i]; if(f.exists()) { kwl.add((ossimString("file")+ossimString::toString(i)+".").c_str(), "filename", f.c_str(), true); } keywordlistSupplied = true; optionGiven = true; } // Get the output file. outfile = argv[argCount-1]; if(outfile.exists()) { ossimNotify(ossimNotifyLevel_WARN) << "mosaic ERROR:" << "\nOutput file " << outfile << " exits and will not be overwritten!" << "\nExiting..." << std::endl; exit(1); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "kwl:\n" << kwl << "output file: " << outfile << std::endl; } if(keywordlistSupplied) { // NOTE: Got rid of the separate method writeMosaic and moved the code down here so i didn't have to pass a ton of variables to it. ossimConnectableObject::ConnectableObjectList inputSources; if(outfile == "") { outfile = "./output.tif"; } // build the image and a remapper for it. // if we were successful then we will add the image // renderer that will transform it it some output // product projection. // if(buildChains(kwl, inputSources)) { ossimMapProjection* productProjection = buildProductProjection(kwl, inputSources); if(!productProjection) { cerr << "unable to create product projection" << endl; return false; } // now let's build up the renderers // if(buildRenderers(kwl, inputSources, productProjection)) { // Create mosaic object ossimRefPtr mosaic = createMosaic(kwl, inputSources); // Create writer from kwl if supplied ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwl,"writer."); if(!writer) { // If no kwl was supplied, then create a writer from the 'theWriterType' string writer = ossimImageWriterFactoryRegistry::instance()->createWriter(theWriterType); //writer = new ossimTiffWriter; // the default 'theWriterType' is not 'tiff_strip' which should be this class writer->open(outfile); } if(writer.valid()) { ossimStdOutProgress listener; if(mosaic.valid()) { writer->addListener(&listener); writer->connectMyInputTo(0, mosaic.get()); writer->initialize(); if ( writerPropertyMap.size() ) { ossimPropertyInterface* propInterface = (ossimPropertyInterface*)writer.get(); std::map::iterator iter = writerPropertyMap.begin(); while(iter!=writerPropertyMap.end()) { propInterface->setProperty(iter->first, iter->second); ++iter; } } // NOTE: This stuff is copied in anyhow not sure why it was being done in the first place... // still here because maybe it is required! should be more generic. //ossimMapProjectionInfo mapInfo(productProjection, // mosaic->getBoundingRect()); //ossimTiffWriter* tempTiffPtr = PTR_CAST(ossimTiffWriter, writer.get()); // //if(tempTiffPtr) //{ // tempTiffPtr->setProjectionInfo(mapInfo); // tempTiffPtr->execute(); //} //else //{ // Do the hard work here.. if (!writer->execute()) { ossimNotify(ossimNotifyLevel_WARN) << "mosaic ERROR:" << "\nCould not execute writer!" << "\nExiting..." << std::endl; return 1; } //} writer->removeListener(&listener); } writer->disconnect(); mosaic->disconnect(); mosaic = 0; writer = 0; } } else { return 1; } } } if(!optionGiven) { argumentParser.getApplicationUsage()->write( ossimNotify(ossimNotifyLevel_INFO)); } return 0; } ossim-Miami-2.9.1/apps/ossim-ogeom2ogeom/000077500000000000000000000000001352751253100202255ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-ogeom2ogeom/CMakeLists.txt000066400000000000000000000003251352751253100227650ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-ogeom2ogeom INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-ogeom2ogeom/ossim-ogeom2ogeom.cpp000066400000000000000000000156301352751253100243050ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include int main(int argc, char* argv[]) { ossimString tempString1; ossimString tempString2; ossimString tempString3; ossimString tempString4; ossimArgumentParser::ossimParameter tempParam1(tempString1); ossimArgumentParser::ossimParameter tempParam2(tempString2); ossimArgumentParser::ossimParameter tempParam3(tempString3); ossimArgumentParser::ossimParameter tempParam4(tempString4); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); bool rpcFlag = false; bool cgFlag = false; bool enableElevFlag = true; bool enableAdjustmentFlag = true; ossimDrect imageRect; double error = .1; imageRect.makeNan(); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName() + " takes an input geometry (or image) and creates a converted output geometry"); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName() + " [options] "); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("--rpc","Create an RPC projection"); argumentParser.getApplicationUsage()->addCommandLineOption("--rpc-gridsize","defines the grid size for the rpc estimate default is --rpc-gridsize=\"10 10\""); argumentParser.getApplicationUsage()->addCommandLineOption("--noelev","the projection but 0 out the elevation"); argumentParser.getApplicationUsage()->addCommandLineOption("--disable-adjustments","Current applies to coarse grid. It will try to make the grid adjustable if the input projection is adjustable"); argumentParser.getApplicationUsage()->addCommandLineOption("--cg","Create a coarse grid projection"); argumentParser.getApplicationUsage()->addCommandLineOption("--rect"," 4 values ulx uly width height"); argumentParser.getApplicationUsage()->addCommandLineOption("--tolerance","Used as an error tolerance. Currently on coarse grid uses it and is the pixel error for the estimate"); argumentParser.getApplicationUsage()->addCommandLineOption("--output","Override the default output name"); if (argumentParser.read("-h") || argumentParser.read("--help") || (argumentParser.argc() == 1)) { argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); ossimInit::instance()->finalize(); exit(0); } ossimFilename outputFile; ossimIpt rpcGridSize(10,10); if(argumentParser.read("--tolerance", tempParam1)) { error = tempString1.toDouble(); } if (argumentParser.read("--rpc")) { rpcFlag = true; } if (argumentParser.read("--rpc-gridsize",tempParam1, tempParam2)) { rpcGridSize.x = tempString1.toInt32(); rpcGridSize.y = tempString2.toInt32(); if(rpcGridSize.x < 1) { rpcGridSize.x = 8; } if(rpcGridSize.y < 1) { rpcGridSize.y = rpcGridSize.x; } } if (argumentParser.read("--cg")) { cgFlag = true; } if (argumentParser.read("--noelev")) { enableElevFlag = false; } if(argumentParser.read("--disable-adjustments")) { enableAdjustmentFlag = false; } if(argumentParser.read("--output", tempParam1)) { outputFile = ossimFilename(tempString1); } if(argumentParser.read("--rect", tempParam1,tempParam2,tempParam3,tempParam4 )) { double x,y,w,h; x = tempString1.toDouble(); y = tempString2.toDouble(); w = tempString3.toDouble(); h = tempString4.toDouble(); if(w < 1) w = 1; if(h < 1) h = 1; imageRect = ossimDrect(x,y,x+(w-1), y+(h-1)); } argumentParser.reportRemainingOptionsAsUnrecognized(); if (argumentParser.errors()) { argumentParser.writeErrorMessages(std::cout); exit(0); } ossimFilename file(argv[1]); ossimRefPtr h = ossimImageHandlerRegistry::instance()->open(file); ossimRefPtr inputProj = 0; ossimKeywordlist kwl; ossim_int32 minSpacing = 100; ossimRefPtr geom; if(h.valid()) { geom = h->getImageGeometry(); imageRect = h->getBoundingRect(); } else if(!imageRect.hasNans()) { kwl.add(ossimKeywordNames::GEOM_FILE_KW, file.c_str()); inputProj = ossimProjectionFactoryRegistry::instance()->createProjection(kwl); } if(!geom.valid()||!geom->getProjection()) { ossimNotify(ossimNotifyLevel_WARN) << "Unable to obtain an input projection. Returning " << std::endl; argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); } else if(!imageRect.hasNans()) { if(outputFile.empty()) { outputFile = file.setExtension("geom"); } if(rpcFlag) { ossimRefPtr solver = new ossimRpcSolver(enableElevFlag); ossimDrect imageBounds; geom->getBoundingRect(imageBounds); bool converged = solver->solve(imageBounds, geom.get()); if (converged) { ossimRefPtr rpc = solver->getRpcModel(); ossimRefPtr rpcgeom = new ossimImageGeometry(nullptr, rpc.get()); ossimKeywordlist kwl; rpcgeom->saveState(kwl); kwl.write(outputFile); } else { ossimNotify(ossimNotifyLevel_FATAL) << "ERROR: Unable to converge on desired error tolerance." << std::endl; exit(1); } } else if(cgFlag) { ossimCoarseGridModel::setInterpolationError(error); ossimCoarseGridModel::setMinGridSpacing(minSpacing); ossimCoarseGridModel cg; cg.buildGrid(imageRect, inputProj.get(), 500.0, enableElevFlag, enableAdjustmentFlag); kwl.clear(); cg.saveState(kwl); kwl.write(outputFile); cg.saveCoarseGrid(outputFile.setExtension("dat")); } } else { ossimNotify(ossimNotifyLevel_WARN) << "Unable to find an image rect" << std::endl; } return 0; } ossim-Miami-2.9.1/apps/ossim-orthoigen/000077500000000000000000000000001352751253100200045ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-orthoigen/CMakeLists.txt000066400000000000000000000003231352751253100225420ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-orthoigen INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-orthoigen/ossim-orthoigen.cpp000066400000000000000000000132561352751253100236450ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossim-orthoigen.cpp 3023 2011-11-02 15:02:27Z david.burken $ #include #include #include #include #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("orthoigen:debug"); //************************************************************************************************* // USAGE //************************************************************************************************* static void usage() { ossimNotify(ossimNotifyLevel_NOTICE) << "Valid output writer types for \"-w\" or \"--writer\" option:\n\n" << ends; ossimImageWriterFactoryRegistry::instance()-> printImageTypeList(ossimNotify(ossimNotifyLevel_NOTICE)); } //************************************************************************************************* // FINALIZE -- Convenient location for placing debug breakpoint for catching program exit. //************************************************************************************************* void finalize(int code) { exit (code); } //************************************************************************************************* // MAIN //************************************************************************************************* int main(int argc, char* argv[]) { #if OSSIM_HAS_MPI ossimMpi::instance()->initialize(&argc, &argv); if (ossimMpi::instance()->getRank() == 0) { ossimNotify(ossimNotifyLevel_INFO) << "MPI running with " << ossimMpi::instance()->getNumberOfProcessors() << " processors..." << std::endl; } #endif //--- // Start the timer. Note ossimMpi::instance()->getRank() works with or without // mpi being enabled. //--- if (ossimMpi::instance()->getRank() == 0) ossimTimer::instance()->setStartTick(); enum { OK = 0, ERROR = 1 }; // Turn off the initial load of elevation. This will be loaded if needed later. ossimInit::instance()->setElevEnabledFlag(false); ossimRefPtr orthoIgen = new ossimOrthoIgen; ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); ossimApplicationUsage* u = argumentParser.getApplicationUsage(); u->setApplicationName(argumentParser.getApplicationName()); u->setCommandLineUsage( "\n\n" " ossim-orthoigen [options] \"[|switches]\" \"[[|switches]\" ...] \n" "\n" " ossim-orthoigen [options] .src "); u->setDescription( "Creates a product image given an input specification as described below. There are two ways\n" "of specifying the input source list. Switches on explicit form are \n" "\n" " |||. \n" "\n" "The presently can be either \"auto-minmax\" or \"std-stretch-N\" where N=1, 2 or 3.\n" "The .src keyword list contains keyword entries in the form of \n" "\n" " imageN.: value\n" "\n" "Supported keywords are \"file\", \"entry\", \"rgb\", \"hist\", \"ovr\", with values \n" "identical to those specified in the explicit switch form.\n"); orthoIgen->addArguments(argumentParser); u->addCommandLineOption("-h or --help","Display this information"); u->addCommandLineOption( "--enable-entry-decoding","A filename can be separated by a | and a number (NO space). \n" "Example: a.toc|0 will do entry 0 of a.toc file and on unix you might want to use a \\ since\n" "the separator is a pipe sign. Example: ./a.toc\\|0 will do entry 0 of a.toc."); if (argumentParser.read("-h") || argumentParser.read("--help") || (argumentParser.argc() == 1)) { u->write(ossimNotify(ossimNotifyLevel_INFO)); usage(); ossimMpi::instance()->finalize(); ossimInit::instance()->finalize(); finalize(OK); } bool enableEntryDecoding = false; if(argumentParser.read("--enable-entry-decoding")) { enableEntryDecoding = true; } orthoIgen->initialize(argumentParser); argumentParser.reportRemainingOptionsAsUnrecognized(); if (argumentParser.errors()) { argumentParser.writeErrorMessages(ossimNotify(ossimNotifyLevel_WARN)); ossimMpi::instance()->finalize(); finalize(OK); } orthoIgen->clearFilenameList(); orthoIgen->addFiles(argumentParser, enableEntryDecoding); int status = OK; try { orthoIgen->execute(); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; status = ERROR; } if(ossimMpi::instance()->getRank() == 0) { ossimNotify(ossimNotifyLevel_NOTICE) << std::setiosflags(ios::fixed) << std::setprecision(3) << "Time elapsed : " << ossimTimer::instance()->time_s() << std::endl; } ossimMpi::instance()->finalize(); finalize(status); } ossim-Miami-2.9.1/apps/ossim-pc2dem/000077500000000000000000000000001352751253100171605ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-pc2dem/CMakeLists.txt000066400000000000000000000003201352751253100217130ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-pc2dem INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-pc2dem/ossim-pc2dem.cpp000066400000000000000000000563751352751253100222060ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Command line application for copying images "image copy". // Can be used to cut images, convert formats. Works in image space // (no resampler). // //******************************************************************* // $Id: ossim-pc2dem.cpp 23064 2015-01-07 03:20:21Z okramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("icp:main"); static void usage() { ossimNotify(ossimNotifyLevel_NOTICE) << "\nValid output writer types:\n\n"; ossimImageWriterFactoryRegistry::instance()-> printImageTypeList( ossimNotify(ossimNotifyLevel_NOTICE) ); } ossimString massageQuotedValue(const ossimString& value) { char quote = '\0'; if(*value.begin() == '"') { quote = '"'; } else if(*value.begin() == '\'') { quote = '\''; } if(quote == '\0') { return value; } std::vector splitString; value.split(splitString, quote); if(splitString.size() == 3) { return splitString[1]; } return value; } //************************************************************************************************* // FINALIZE -- Convenient location for placing debug breakpoint for catching program exit. //************************************************************************************************* void finalize(int code) { exit (code); } int main(int argc, char* argv[]) { static const char MODULE[] = "icp:main"; std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); ossimApplicationUsage* au = ap.getApplicationUsage(); au->setApplicationName(ap.getApplicationName()); au->setDescription(ap.getApplicationName()+ " copies any supported input image format to any supported output image format format"); au->setCommandLineUsage(ap.getApplicationName()+ " [options] "); au->addCommandLineOption("-h or --help", "Display this information"); au->addCommandLineOption("-a or --use-scalar-remapper", "Uses scalar remapper, transforms to 8-bit"); au->addCommandLineOption("-o or --create-overview", "Creates and overview for the output image"); au->addCommandLineOption("-b or --bands ", "uses the specified bands: ex. \"1, 2, 4\" will select bands 1 2 and 4 of the input image. " "Note: it is 1 based"); au->addCommandLineOption("-c or --compression-type ", "Uses compression. Currently valid for only tiff output -c jpeg will use jpeg compression"); au->addCommandLineOption("-e or --entry ", "For multi image handlers which entry do you wish to extract"); au->addCommandLineOption("-g", "Convert to grey scale."); au->addCommandLineOption("-q or --compression-quality ", "Uses compression. Valid for jpeg type. default is 75 where 100 is best and 1 is worst"); au->addCommandLineOption("--pixel-type ", "Valid values: area or point, this will determine if the tie point is upper left corner of " "the upper left pixel (area) or the center of the upper left corner (point), default=point. " "NOTE: This option will only affect the tiff writer."); au->addCommandLineOption("-r or --res-level ", "Which res level to extract from the input: ex -r 1 will get res level 1"); au->addCommandLineOption("-l or --start-line ", "Which start line do you wish to copy from the input. If none is given then 0 is used"); au->addCommandLineOption("-L or --end-line ", "Which end line do you wish to copy from the input. If none is given then max line is used"); au->addCommandLineOption("-s or --start-sample ", "Which start sample do you wish to copy from the input. If none is given then 0 is used"); au->addCommandLineOption("-p or --end-sample ", "The end sample you wish to copy from the input. If none is given then max sample is used"); au->addCommandLineOption("-t or --create-thumbnail ", "Takes an argument which is the maximum pixel dimension desired."); au->addCommandLineOption("-w or --tile-width ", "Defines the tile width for the handlers that support tiled output"); au->addCommandLineOption("--reader-prop ", "Adds a property to send to the reader. format is name=value"); au->addCommandLineOption("--writer-prop ", "Adds a property to send to the writer. format is name=value"); au->addCommandLineOption("--filter-spec ", "This is an external file spec that describes a chain for filtering the input image."); au->addCommandLineOption("--use-mask []", "Optionally specify name of mask file to use for masking the input image. If no filename " "given, then the default mask filename is used."); if (traceDebug()) CLOG << " Entered..." << std::endl; // Keyword list to initialize image writers with. ossimKeywordlist kwl; const char* PREFIX = "imagewriter."; bool lineEndIsSpecified = false; bool sampEndIsSpecified = false; bool lineStartIsSpecified = false; bool sampStartIsSpecified = false; bool convert_to_greyscale = false; bool create_overview = false; bool create_thumbnail = false; bool use_band_selector = false; bool use_scalar_remapper = false; bool use_mask = false; ossim_int32 tile_width = 0; ossim_int32 max_thumbnail_dimension = 0; ossim_int32 rr_level = 0; ossim_int32 line_start = 0; ossim_int32 line_stop = 0; ossim_int32 sample_start = 0; ossim_int32 sample_stop = 0; ossim_int32 cibcadrg_entry = 0; vector band_list(0); ossimFilename filterSpec, maskFile; std::map readerPropertyMap; std::map writerPropertyMap; if (ap.read("-h") || ap.read("--help")||(ap.argc() < 2)) { au->write(ossimNotify(ossimNotifyLevel_NOTICE)); usage(); // for writer output types finalize(0); } while(ap.read("--reader-prop", stringParam)) { std::vector nameValue; ossimString(tempString).split(nameValue, "="); if(nameValue.size() == 2) { readerPropertyMap.insert(std::make_pair(nameValue[0], massageQuotedValue(nameValue[1]))); } } while(ap.read("--writer-prop", stringParam)) { std::vector nameValue; ossimString(tempString).split(nameValue, "="); if(nameValue.size() == 2) { writerPropertyMap.insert(std::make_pair(nameValue[0], massageQuotedValue(nameValue[1]))); } } while(ap.read("-a") || ap.read("--use-scalar-remapper")) { use_scalar_remapper = true; } while(ap.read("--filter-spec",stringParam)) { filterSpec = ossimFilename(tempString); } while(ap.read("--use-mask") || ap.read("--use-mask",stringParam) ) { maskFile = ossimFilename(tempString); use_mask = true; } while(ap.read("-o") || ap.read("--create-overview")) { create_overview = true; } while(ap.read("-b", stringParam) || ap.read("--bands", stringParam)) { use_band_selector = true; ossimString s = tempString; band_list = s.split(","); } while(ap.read("-c", stringParam) || ap.read("--compression-type", stringParam)) { ossimString s = tempString; s.downcase(); kwl.add(PREFIX, ossimKeywordNames::COMPRESSION_TYPE_KW, s.c_str(), true); } while(ap.read("-e", stringParam) || ap.read("--entry", stringParam)) { cibcadrg_entry = ossimString(tempString).toInt(); } if ( ap.read("-g") ) { convert_to_greyscale = true; } while(ap.read("-q", stringParam) || ap.read("--compression-quality", stringParam)) { // Set the jpeg compression quality level. kwl.add(PREFIX, ossimKeywordNames::COMPRESSION_QUALITY_KW, tempString.c_str(), true); } while(ap.read("-r", stringParam) || ap.read("--res-level", stringParam)) { rr_level = ossimString(tempString).toInt(); } while(ap.read("-l", stringParam) || ap.read("--start-line", stringParam)) { lineStartIsSpecified = true; line_start = ossimString(tempString).toInt(); } while(ap.read("-L", stringParam) || ap.read("--end-line", stringParam)) { lineEndIsSpecified = true; line_stop = ossimString(tempString).toInt(); } while(ap.read("-s", stringParam) || ap.read("--start-sample", stringParam)) { sampStartIsSpecified = true; sample_start = ossimString(tempString).toInt(); } while(ap.read("-p", stringParam) || ap.read("--end-sample", stringParam)) { sampEndIsSpecified = true; sample_stop = ossimString(tempString).toInt(); } while(ap.read("-t", stringParam) || ap.read("--create-thumbnail", stringParam)) { create_thumbnail = true; max_thumbnail_dimension=ossimString(tempString).toInt(); } while(ap.read("-w", stringParam) || ap.read("-tile-width", stringParam)) { tile_width = ossimString(tempString).toInt(); if ((tile_width % 16) != 0) { ossimNotify(ossimNotifyLevel_NOTICE) << MODULE << " NOTICE:" << "\nTile width must be a multiple of 16!" << "\nDefaulting to 128" << std::endl; tile_width = 0; } } if (ap.read("--pixel-type", stringParam)) { ossimString os = tempString; os.downcase(); if (os.contains("area")) { kwl.add(PREFIX, ossimKeywordNames::PIXEL_TYPE_KW, "area", true); } else { kwl.add(PREFIX, ossimKeywordNames::PIXEL_TYPE_KW, "point", true); } } ap.reportRemainingOptionsAsUnrecognized(); // Three required args: output_type, input file, and output file. if (ap.errors()) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); finalize(0); } if (ap.argc() < 4) { au->write(ossimNotify(ossimNotifyLevel_NOTICE)); usage(); // for writer output types finalize(0); } // Set the writer type and the image type. ossimString output_type = ap.argv()[ap.argc()-3]; kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true); // Get the input file. const char* input_file = argv[ap.argc()-2]; // Get the output file. ossimFilename output_file = argv[ap.argc()-1]; if (traceDebug()) { CLOG << "DEBUG:" << "\noutput type: " << ap.argv()[ap.argc()-3] << "\ninput file: " << ap.argv()[ap.argc()-2] << "\noutput file: " << ap.argv()[ap.argc()-1] << std::endl; if (tile_width) { ossimNotify(ossimNotifyLevel_NOTICE) << "tile_width: " << tile_width << std::endl; } } // Get an image handler for the input file. ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(ossimFilename(input_file)); ossimCibCadrgTileSource* its = PTR_CAST(ossimCibCadrgTileSource, ih.get()); if (its) { if (cibcadrg_entry > 0) { its->setCurrentEntry(cibcadrg_entry); } } if (!ih) { ossimNotify(ossimNotifyLevel_NOTICE) << "Unsupported image file: " << input_file << "\nExiting application..." << std::endl; finalize(0); } if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_FATAL) << "Error reading image: " << input_file << "Exiting application..." << std::endl; finalize(1); } // Set the reader properties if any. if ( readerPropertyMap.size() ) { ossimPropertyInterface* pi = (ossimPropertyInterface*)ih.get(); std::map::iterator iter = readerPropertyMap.begin(); while(iter != readerPropertyMap.end()) { pi->setProperty(iter->first, iter->second); ++iter; } } ih->initialize(); ossimRefPtr source = ih.get(); if (traceDebug()) { CLOG << "DEBUG:" << "\nImage Handler: " << ih->getLongName() << std::endl; } // Start band selector section: //--- // If image handler is band selector, start with all bands. // Some sources, e.g. ossimEnviTileSource can pick up default // bands and filter out all other bands. //--- ih->setOutputToInputBandList(); if ( use_band_selector && (source->getNumberOfOutputBands() > 1) ) { // Build the band list. ossim_uint32 bands = source->getNumberOfOutputBands(); vector bl; ossim_uint32 i; for (i=0; i= bands) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " ERROR:" << "\nBand list range error!" << "\nHighest available band: " << bands << std::endl; finalize(1); } } ossimRefPtr bs = new ossimBandSelector(); bs->connectMyInputTo(source.get()); bs->setOutputBandList(bl); bs->enableSource(); bs->initialize(); source = bs.get(); if (traceDebug()) { CLOG << "DEBUG:" << "\nZero based output band list:" << std::endl; for (i=0; i rgb2grey = new ossimRgbToGreyFilter(); rgb2grey->connectMyInputTo( source.get() ); source = rgb2grey.get(); } ossimRefPtr mask_filter = 0; if (use_mask) { if (maskFile.empty()) { maskFile = ih->getFilenameWithThisExtension("mask"); } ossimImageHandler* mh = ossimImageHandlerRegistry::instance()->open(maskFile); if (mh == NULL) { ossimNotify(ossimNotifyLevel_FATAL)<<"ossim-icp -- Could not open raster mask file <" <. Maske request will be ignored. Aborting..."<connectMyInputTo(source.get()); mask_filter->setMaskSource(mh); // assumes ownership of mask handler object source = mask_filter.get(); } if(!filterSpec.empty()&&filterSpec.exists()) { ossimKeywordlist kwl; if(kwl.addFile(filterSpec)) { ossimRefPtr input = ossimObjectFactoryRegistry::instance()->createObject(kwl); if(input.valid()) { ossimImageSource* inputImageSource = dynamic_cast (input.get()); if(inputImageSource) { inputImageSource->connectMyInputTo(source.get()); source = inputImageSource; } } } } if (create_thumbnail == true) { // Get the rlevel that <= max thumbnail dimension. int max = 0; int level = 0; while (level < ((ossim_int32)ih->getNumberOfDecimationLevels()-1)) { int lines = ih->getNumberOfLines(level); int samples = ih->getNumberOfSamples(level); max = lines > samples ? lines : samples; if (max <= max_thumbnail_dimension) { break; } ++level; } if (max > max_thumbnail_dimension) { ossimNotify(ossimNotifyLevel_NOTICE) << " NOTICE:" << "\nLowest rlevel not small enough to fulfill " << "max_thumbnail_dimension requirement!" << std::endl; } // Set the reduced res level. This will override the -r option. rr_level = level; } // end of "if (create_thumbnail == true) // Start rlevel filter section. if( rr_level != 0 ) { //--- // Check for a valid reduced resolution level. // If the operator entered an invalid rr_level with the -r option, // spit out a warning and set to default "0". //--- if (rr_level >= (ossim_int32)(ih->getNumberOfDecimationLevels())) { ossimNotify(ossimNotifyLevel_NOTICE) << " WARNING:" << "\n\t Selected res level greater than available res levels." << "\n\t Defaulting to res level zero. " << std::endl; rr_level = 0; } ossimRefPtr rlevelFilter = new ossimRLevelFilter; rlevelFilter->connectMyInputTo(source.get()); source = rlevelFilter.get(); rlevelFilter->setCurrentRLevel(rr_level); if ( rr_level ) { rlevelFilter->setOverrideGeometryFlag(true); } } // Matches: if( rr_level != 0 ) ossimIrect output_rect = source->getBoundingRect(rr_level); //--- // If any of these are true the user wants to cut the rectangle. //--- if ( lineStartIsSpecified || lineEndIsSpecified || sampStartIsSpecified || sampEndIsSpecified) { if (!lineStartIsSpecified) line_start = output_rect.ul().y; if (!lineEndIsSpecified) line_stop = output_rect.lr().y; if (!sampStartIsSpecified) sample_start = output_rect.ul().x; if (!sampEndIsSpecified) sample_stop = output_rect.lr().x; //--- // Check the start and stop points and make sure they are in // the right order; if not, swap them. //--- if (line_stop < line_start) { ossimNotify(ossimNotifyLevel_NOTICE) << " WARNING:\n" << "\t Line end is less than line start, swapping." << std::endl; int tmp = line_start; line_start = line_stop; line_stop = tmp; } if (sample_stop < sample_start) { ossimNotify(ossimNotifyLevel_WARN) << " WARNING:\n" << "\t Sample end is less than sample start, swapping." << std::endl; int tmp = sample_start; sample_start = sample_stop; sample_stop = tmp; } output_rect.set_ulx(sample_start); output_rect.set_lrx(sample_stop); output_rect.set_uly(line_start); output_rect.set_lry(line_stop); } // End of "if ((lineEndIsSpecified) ||..." if (traceDebug()) { CLOG << "icp:main debug" << "\nrr_level: " << rr_level << "\noutput_rect: " << output_rect << "\nkeyword list: " << kwl << std::endl; } ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX); if( !writer) { ossimNotify(ossimNotifyLevel_NOTICE) << "\nCould not create writer of type: " << output_type << std::endl; usage(); finalize(1); } writer->connectMyInputTo(0, source.get()); if (tile_width) { // Set the tile size... writer->setTileSize(ossimIpt(tile_width, tile_width)); } writer->open(output_file); // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); if (writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK) { if( (ih->getOutputScalarType() != OSSIM_UCHAR) && ((PTR_CAST(ossimJpegWriter, writer.get())) || use_scalar_remapper)) { writer->setScaleToEightBitFlag(true); } ossimRefPtr cache = new ossimCacheTileSource; ossimIpt tileWidthHeight(ih->getImageTileWidth(), ih->getImageTileHeight()); // only use the cache if its stripped if(static_cast(tileWidthHeight.x) == ih->getBoundingRect().width()) { cache->connectMyInputTo(0, source.get()); cache->setTileSize(tileWidthHeight); writer->connectMyInputTo(0, cache.get()); } else { writer->connectMyInputTo(0, source.get()); } writer->initialize(); writer->setAreaOfInterest(output_rect); // Set the output rectangle. try { if ( writerPropertyMap.size() ) { ossimPropertyInterface* propInterface = (ossimPropertyInterface*)writer.get(); std::map::iterator iter = writerPropertyMap.begin(); while(iter!=writerPropertyMap.end()) { propInterface->setProperty(iter->first, iter->second); ++iter; } } writer->execute(); } catch(std::exception& e) { ossimNotify(ossimNotifyLevel_FATAL) << "icp:main ERROR:\n" << "Caught exception!\n" << e.what() << std::endl; } catch(...) { ossimNotify(ossimNotifyLevel_FATAL) << "icp:main ERROR:\n" << "Unknown exception caught!\n" << std::endl; } cache = 0; } else { ossimNotify(ossimNotifyLevel_FATAL) << "Error detected in the image writer..." << "\nExiting application..." << std::endl; finalize(1); } if (create_overview == true) { writer->writeOverviewFile(); } finalize(0); } ossim-Miami-2.9.1/apps/ossim-pixelflip/000077500000000000000000000000001352751253100200025ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-pixelflip/CMakeLists.txt000066400000000000000000000003231352751253100225400ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-pixelflip INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-pixelflip/ossim-pixelflip.cpp000066400000000000000000000336021352751253100236360ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // //******************************************************************* // $Id: ossim-pixelflip.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI # include # endif #endif static ossimTrace traceDebug("pixelflip:main"); static void usage(); static void outputWriterTypes(); int main(int argc, char* argv[]) { #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI ossimMpi::instance()->initialize(&argc, &argv); if (ossimMpi::instance()->getRank() == 0) { ossimNotify(ossimNotifyLevel_INFO) << "MPI running with " << ossimMpi::instance()->getNumberOfProcessors() << " processors..." << std::endl; } # endif #endif std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" flips any null pixels to a valid pixel"); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] "); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("-o or --create-overview", "Creates and overview for the output image"); argumentParser.getApplicationUsage()->addCommandLineOption("-c or --clamp-value", "clamp values (any pixel with value larger than input will be clamped to input)"); argumentParser.getApplicationUsage()->addCommandLineOption("-m", "Replacement mode (see notes below)"); argumentParser.getApplicationUsage()->addCommandLineOption("-w", "output tile width(only valid with tiled output types). Must be a multiply of 16"); static const char MODULE[] = "pixelflip:main"; if (traceDebug()) CLOG << " Entered..." << std::endl; ossimInit::instance()->initialize(argc, argv); // Keyword list to initialize image writers with. ossimKeywordlist kwl; const char* PREFIX = "imagewriter."; bool create_overview = false; ossim_int32 tile_width = 0; double clamp_value = 0.0; bool do_clamp = false; ossimPixelFlipper::ReplacementMode replacement_mode = ossimPixelFlipper::REPLACE_BAND_IF_TARGET; if(argumentParser.read("-h") || argumentParser.read("--help")||(argumentParser.argc() == 1)) { argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); usage(); exit(0); } while(argumentParser.read("-o") || argumentParser.read("--create-overview")) { create_overview = true; } while(argumentParser.read("-c", stringParam)) { clamp_value = ossimString(tempString).toDouble(); do_clamp = true; } while(argumentParser.read("-m", stringParam)) { ossimString mode = tempString; mode.downcase(); if (mode == "replace_band_if_target") { replacement_mode = ossimPixelFlipper::REPLACE_BAND_IF_TARGET; } else if (mode == "replace_band_if_partial_target") { replacement_mode = ossimPixelFlipper::REPLACE_BAND_IF_PARTIAL_TARGET; } else if (mode == "replace_all_bands_if_partial_target") { replacement_mode = ossimPixelFlipper::REPLACE_ALL_BANDS_IF_PARTIAL_TARGET; } else if (mode != "replace_all_targets") { ossimNotify(ossimNotifyLevel_WARN) << "Invalid mode: " << mode << "\nMode remains: replace_band_if_target" << std::endl; } } while(argumentParser.read("-w", stringParam)) { tile_width = ossimString(tempString).toInt32(); if (tile_width % 16) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " NOTICE:" << "\nTile width must be a multiple of 16!" << "\nDefaulting to 128" << std::endl; tile_width = 0; } } if(argumentParser.argc() != 6) { ossimMpi::instance()->finalize(); exit(0); } //*** // Set the writer type and the image type. //*** ossimString output_type = argumentParser.argv()[1]; output_type.downcase(); kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str()); // Get the input file. ossimFilename input_file = argumentParser.argv()[2]; // Get the output file. ossimFilename output_file = argumentParser.argv()[3]; // Get the value to replace. double target_value = ossimString(argumentParser.argv()[4]).toDouble(); // Get the replacement value. double replacement_value = ossimString(argumentParser.argv()[5]).toDouble(); bool master = true; if (ossimMpi::instance()->getRank() != 0) { master = false; } if (master) { ossimNotify(ossimNotifyLevel_INFO) << "pixelflip settings:" << "\noutput type: " << output_type << "\ninput file: " << input_file << "\noutput file: " << output_file << "\ntarget value: " << target_value << "\nreplacement value: " << replacement_value << std::endl; if (tile_width) { ossimNotify(ossimNotifyLevel_INFO) << "tile width: " << tile_width << std::endl; } if (do_clamp) { ossimNotify(ossimNotifyLevel_INFO) << "clamp value: " << clamp_value << std::endl; } } // Get an image handler for the input file. ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(ossimFilename(input_file)); if (!ih) { ossimNotify(ossimNotifyLevel_WARN) << "Unsupported image file: " << input_file << "\nExiting application..." << std::endl; ossimMpi::instance()->finalize(); exit(0); } // Initialize the if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN) << "Error reading image: " << input_file << "Exiting application..." << std::endl; ossimMpi::instance()->finalize(); exit(1); } ih->initialize(); if (traceDebug()) { CLOG << "DEBUG:" << "\nImage Handler: " << ih->getLongName() << std::endl; } // Capture the bounding rectangle of the image handler. ossimIrect output_rect = ih->getBoundingRect(0); // hook up the pixel flipper to the image handler. ossimRefPtr pf = new ossimPixelFlipper(); pf->connectMyInputTo(ih.get()); pf->initialize(); // Setup the pixel flipper target/replacement values, and replace mode. pf->setTargetValue(target_value); pf->setReplacementValue(replacement_value); pf->setReplacementMode(replacement_mode); // Setup pixel flipper clamp value if (do_clamp) { pf->setClampValue(clamp_value); } if (master) { ossimNotify(ossimNotifyLevel_INFO) << "replacement mode: " << pf->getReplacementModeString() << std::endl; } ossimImageSourceSequencer* sequencer = NULL; #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI // only allocate the slave connection if // the number of processors is larger than // 1 // if(ossimMpi::instance()->getNumberOfProcessors() > 1) { if(ossimMpi::instance()->getRank()!=0) { sequencer = new ossimImageMpiSWriterSequenceConnection(NULL, 4); } else { sequencer = new ossimImageMpiMWriterSequenceConnection(); } } else { sequencer = new ossimImageSourceSequencer(); } # else // we will just load a serial connection if MPI is not supported. sequencer = new ossimImageSourceSequencer(NULL); # endif #else sequencer = new ossimImageSourceSequencer(NULL); #endif ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX); ossimImageFileWriter* fileWriter = PTR_CAST(ossimImageFileWriter, writer.get()); if( fileWriter == NULL ) { ossimNotify(ossimNotifyLevel_WARN) << "Error making an image writer..." << "\nExiting application..." << std::endl; ossimMpi::instance()->finalize(); exit(1); } // Change out the sequencer... fileWriter->changeSequencer(sequencer); // Hook up the pixel flipper to the file writer. fileWriter->connectMyInputTo(0, pf.get()); if (tile_width) { // Set the tile size... fileWriter->setTileSize(ossimIpt(tile_width, tile_width)); } fileWriter->open(output_file); // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); fileWriter->addListener(&prog); if (fileWriter->getErrorStatus() == ossimErrorCodes::OSSIM_OK) { fileWriter->initialize(); fileWriter->setAreaOfInterest(output_rect); // Set the output rectangle. #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI double start_time = 0.0; if(ossimMpi::instance()->getRank() == 0) { // Start the timer. ossimTimer::instance()->setStartTick(); //start_time= MPI_Wtime(); } # endif #endif // Filter and write the file... fileWriter->execute(); #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI if(ossimMpi::instance()->getRank() == 0) { ossimNotify(ossimNotifyLevel_NOTICE) << "elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << endl; //double stop_time = MPI_Wtime(); //cout << "Elapsed time: " << (stop_time-start_time) << std::endl; } # endif #endif } else { cerr << "Error detected in the image writer..." << "\nExiting application..." << std::endl; exit(1); } if (create_overview == true) { fileWriter->writeOverviewFile(); } #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI ossimMpi::instance()->finalize(); # endif #endif exit(0); } void usage() { ossimNotify(ossimNotifyLevel_INFO) << "\nNOTES:" << "\n-m Replacement mode option explanation:" << "\n Valid modes (default=replace_all_targets) :" << "\n replace_partial_targets" << "\n replace_partial_targets_all_bands" << "\n replace_full_targets" << "\n replace_all_targets" << " (default=all)" << "\n" << "\nIf mode is \"replace_all_targets\" (default):" << "\nAny pixel with dn of target will be replaced." << "\n" << "\nIf mode is \"replace_partial_targets\":" << "\nTarget will be replaced only at least one subpixel(band) does " << "\nnot have the target." << "\n" << "\nIf mode is \"replace_partial_targets_all_bands\":" << "\nTarget will be replaced only at least one subpixel(band) does " << "\nnot have the target. All bands will be replaced." << "\nThis is a good Landsat7 edge fixer..." << "\n" << "\nIf mode is \"replace_full_targets\":" << "\nTarget will be replaced only if all subpixels(bands) have the " << "target." << "\n" << "\n Example:" << "\n target = 0" << "\n replacement = 1" << "\n Pixel at (0, 0) r=0, g=0, b=0" << "\n Pixel at (0, 1) r=0, g=30, b=21" << "\n" << "\n Mode is \"replace_all_targets\":" << "\n Pixel at (0, 0) becomes r=1, g=1, b=1" << "\n Pixel at (0, 1) becomes r=1, g=30, b=21" << "\n" << "\n Mode is \"replace_partial_targets\":" << "\n Pixel at (0, 0) remains r=0, g=0, b=0" << "\n Pixel at (0, 1) becomes r=1, g=30, b=21" << "\n" << "\n Mode is \"replace_partial_targets_all_bands\":" << "\n Pixel at (0, 0) remains r=0, g=0, b=0" << "\n Pixel at (0, 1) becomes r=1, g=1, b=1" << "\n" << "\n Mode is \"replace_full_targets\":" << "\n Pixel at (0, 0) becomes r=1, g=1, b=1" << "\n Pixel at (0, 1) remains r=0, g=30, b=21" << "\n" << "\nValid output writer types:" << std::endl; outputWriterTypes(); } void outputWriterTypes() { std::vector outputType; ossimImageWriterFactoryRegistry::instance()->getImageTypeList(outputType); std::copy(outputType.begin(), outputType.end(), std::ostream_iterator(std::cout, "\t\n")); } ossim-Miami-2.9.1/apps/ossim-plot-histo/000077500000000000000000000000001352751253100201105ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-plot-histo/CMakeLists.txt000066400000000000000000000003241352751253100226470ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-plot-histo INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-plot-histo/ossim-plot-histo.cpp000066400000000000000000000130041352751253100240440ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id: create_histo.cpp 11743 2007-09-19 19:57:31Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #ifdef WIN32 #define MY_POPEN(arg1, arg2) _popen(arg1, arg2) #else #define MY_POPEN(arg1, arg2) popen(arg1, arg2) #endif void usage() { cout << "examples:\n" << " ossim-plot-histo foo.tif\n" << " Will create a histogram for the input image and call\n" << " it foo.his, then will plot the histogram.\n\n" << " ossim-plot-histo foo.his\n" << " Simply plots existing histogram.\n\n" << " ossim-plot-histo --with dots foo.his\n" << " Uses specified symbol for data point. See \"gnuplot plot with\" " << " documentation.\n\n" << "Note: gnuplot must be installed before using this utility." << endl; } void plotHistogram(const ossimFilename& histoFile, const ossimString& plotWith, const ossimString& xticstr) { // Open the histogram file: ossimRefPtr h = new ossimMultiResLevelHistogram(); if (!h->importHistogram(histoFile)) { cout << "Could not read the histogram file <"<" << endl; exit(1); } // Create temporary data file stream: FILE * gnuplotPipe = MY_POPEN ("gnuplot -persistent", "w"); //FILE * gnuplotPipe = fopen("gnuplot.dat", "w"); if (!gnuplotPipe) { cout << "Could not create temporary gnuplot pipe. "<< endl; exit(1); } if (!xticstr.empty()) { ostringstream xticsCmd; xticsCmd<<"set xtics ("< histogram = h->getHistogram(band); int numBins = histogram->GetRes(); const double* x = histogram->GetVals(); const ossim_int64* y = histogram->GetCounts(); for (int i=0; iaddOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" Plots image histogram."); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" "); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("--with ", "See \"gnuplot plot with\" documentation"); argumentParser.getApplicationUsage()->addCommandLineOption("--xtics ()", "See \"gnuplot plot xtics\" documentation"); ossim_uint32 maxLevels = 1; ossim_int32 entry = -1; ossimFilename plotFile; ossim_float64 minValueOverride = ossim::nan(); ossim_float64 maxValueOverride = ossim::nan(); ossim_int32 numberOfBinsOverride = -1; bool fastMode = false; ossimString plotWith = "dots"; ossimString xtics; if ( (argumentParser.read("-h")) || (argumentParser.read("--help")) ) { argumentParser.getApplicationUsage()->write(std::cout); usage(); exit(0); } if(argumentParser.read("--with", stringParam)) { plotWith = tempString; } if(argumentParser.read("--xtics", stringParam)) { xtics = tempString; cout << "xtics = "<write(std::cout); usage(); } return 0; } ossim-Miami-2.9.1/apps/ossim-preproc/000077500000000000000000000000001352751253100174605ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-preproc/CMakeLists.txt000066400000000000000000000003211352751253100222140ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-preproc INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-preproc/ossim-preproc.cpp000066400000000000000000000045351352751253100227750ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossim-info.cpp 18619 2011-01-03 10:33:51Z dburken $ #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { // Return 0 on success, something else on error. enum { OK = 0, ERROR = 1 }; int result = OK; // Start the timer. ossimTimer::instance()->setStartTick(); //--- // Get the arg count so we can tell if an arg was consumed by // ossimInit::instance()->initialize //--- int originalArgCount = argc; ossimArgumentParser ap(&argc, argv); // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); //--- // Avoid going on if a global option was consumed by ossimInit::initialize // like -V or --version option and the arg count is down to 1. //--- if ( ( ap.argc() > 1 ) || ( ap.argc() == originalArgCount ) ) { // Make the info object. ossimRefPtr oiu = new ossimImageUtil(); try { //--- // Initialize will take the options passed in and set things to output // information for. // // ossimInfo::initialize can throw an exception. //--- bool continue_after_init = oiu->initialize(ap); if ( continue_after_init ) { // Execute the operation(s). result = oiu->execute(); ossimNotify(ossimNotifyLevel_NOTICE) << "elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << endl; } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; result = ERROR; } } // End: if ( ( ap.argc() > 1 ) ... return result; } // End of main... ossim-Miami-2.9.1/apps/ossim-project-point/000077500000000000000000000000001352751253100206035ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-project-point/CMakeLists.txt000066400000000000000000000003271352751253100233450ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-project-point INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-project-point/ossim-project-point.cpp000066400000000000000000000117551352751253100252450ustar00rootroot00000000000000//******************************************************************* // OSSIM // // License: See top level LICENSE.txt file. // // Simple point projector from image to map and visa versa // //******************************************************************* #include #include #include #include #include #include #include #include #include #include using namespace std; static void usage() { cout << "\nSimple point projector that does image->ground->map->ground->image. \n" << "An output map projection (UTM or geographic) is created at the nominal \n" << "GSD of the image. Usage:\n" << "\n" << " ossim-project [options] [ ]\n" << "\n" << "Options:\n" << " -h Displays this. \n" << " -g Use geographic projection. Default is UTM. \n" << "\n" << "If no coordinates are provided, the image center is used.\n" << endl; exit(0); } int main(int argc, char *argv[]) { // This loads ossim-preferences file specifying OSSIM configuration including the location of // elevation data and plugin libraries: ossimInit::instance()->initialize(argc, argv); vector cmdline; for (uint32_t i=1; i handler = ossimImageHandlerRegistry::instance()->open(fname); if (!handler) { cout << "\nNull image handler returned for input file <"<!" << endl; exit(1); } // The handler will use the image projection factories to instantiate the proper sensor model // or map projection (if image is orthorectified. This may include RPC replacement model // if the support data files are available in the image directory. This geometry defines the // transform from image-space (x,y) to world coordinates (lat, lon): ossimRefPtr geom = handler->getImageGeometry(); if (!handler) { cout << "\nNull geometry returned from handler!" << endl; exit(1); } // Fetch UL image and transform to ground: ossimDpt imgUL (0,0); ossimGpt gndUL; // Performs image to world transform. This includes the iterative solution for intersecting the // ray with the elevation surface (unless image is already map projected, in which case the // elevation lookup is straightforward: geom->localToWorld(imgUL, gndUL); ossimDpt gsd (geom->getMetersPerPixel()); cout<<"\nFile: "< proj; if (doGeographic) proj = new ossimEquDistCylProjection(ossimEllipsoid(), gndUL); else proj = new ossimUtmProjection(ossimEllipsoid(), gndUL); // Init map projection with UL tiepoint: proj->setUlTiePoints(gndUL); proj->setMetersPerPixel(gsd); ossimDpt testImgPt(x, y); ossimGpt testGndPt(x, y); if (testImgPt.hasNans()) { ossimIrect imgRect; geom->getBoundingRect(imgRect); testImgPt = imgRect.midPoint(); } ossimDpt testMapPt, testImgPt2; // Perform x,y -> lat,lon transformations: geom->localToWorld(testImgPt, testGndPt); cout<<"Using_image_point: "<worldToLineSample(testGndPt); cout<<" Ground-to-Map: "<lineSampleToWorld(testMapPt); cout<<" Map-to-Ground: "<worldToLocal(testGndPt, testImgPt2); cout<<" Ground-to-Image: "< #include using namespace std; #include #include #include #include #include #include #include #include static ossimTrace traceDebug("prune:main"); static void usage() { cout << "prune: Displays if image is null or not.\n" << "Usage:\n" << "ossim-prune " << "\nMoves image_file to image_file.null if all tiles are null." << "\n"; return; } static void move( const ossimFilename& in, const ossimFilename& out ) { #if defined(WIN32) || defined(_MSC_VER) && !defined(__CYGWIN__) && !defined(__MWERKS__) std::string moveCommand = "ren"; #else std::string moveCommand = "mv"; #endif std::string command = moveCommand; command += " "; command += in.string(); command += " "; command += out.string(); cout << "Executing " << command << endl; system(command.c_str()); } int main(int argc, char* argv[]) { ossimInit::instance()->initialize(argc, argv); // One required arg: input file if (argc != 2) { usage(); exit(0); } const char* input_file = argv[1]; // Get an image handler for the input file. ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(ossimFilename(input_file)); if (!ih) { cout << "ERROR: Unsupported image file: " << input_file << "\nExiting application." << endl; exit(0); } // Initialize the if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { cerr << "ERROR: Unable to read image file: " << input_file << "\nExiting application." << endl; exit(1); } ih->initialize(); int lines = ih->getNumberOfLines(0); int samples = ih->getNumberOfSamples(0); int tileHeight = ih->getTileHeight(); int tileWidth = ih->getTileWidth(); int tilesInLineDir = lines / tileHeight; int tilesInSampDir = samples / tileWidth; if(lines % tileHeight) ++tilesInLineDir; if(samples % tileWidth) ++tilesInSampDir; for(int i=0; i id=ih->getTile(origin); if( id.valid() && (id->getDataObjectStatus() != OSSIM_EMPTY) ) { cout << "RESULT: Image file has data: " << input_file << endl; exit(0); } } } // Move the input file: ossimFilename in = input_file; ossimFilename out = in; out += ".null"; move( in, out ); in = in.fileNoExtension(); in += "_readme.txt"; if ( in.exists() ) { out = in; out += ".null"; move( in, out ); } exit(0); } ossim-Miami-2.9.1/apps/ossim-rejout/000077500000000000000000000000001352751253100173165ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-rejout/CMakeLists.txt000066400000000000000000000003201352751253100220510ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-rejout INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-rejout/ossim-rejout.cpp000066400000000000000000000133571352751253100224730ustar00rootroot00000000000000//******************************************************************* // // Author: Frederic Claudel, CSIR // // rejects outliers and optimize model (RANSAC) // to use after correl, with a tie points file // // front-end for class ossimOutlierRejection // //******************************************************************* #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include //error header static const char* PROGERR = "ERROR rejout"; //globals ossimFilename outGeomName="rejout.geom"; ossimFilename outItptName="inliers.xml"; ossimString modelDefinition="ossimPolynomProjection{1 x y x2 xy y2 x3 y3 xy2 x2y z xz yz}"; int main(int argc, char *argv[]) { //error status : initially ok int result=0; //init OSSIM (prefs, elevation, plugins, etc) std::string tempString; double tempDouble; ossimArgumentParser::ossimParameter argString(tempString); ossimArgumentParser::ossimParameter argDouble(tempDouble); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); //init with default parms // ossimOutlierRejection mo; ossimRefPtr moObject = ossimObjectFactoryRegistry::instance()->createObject(ossimString("ossimOutlierRejection")); ossimPropertyInterface* moPropertyInterface = PTR_CAST(ossimPropertyInterface, moObject.get()); ossimProcessInterface* moProcessInterface = PTR_CAST(ossimProcessInterface, moObject.get()); if(!moObject.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "Unable to find object ossimOutlierRejection in registration plugin" << std::endl; exit(1); } ossimRefPtr inlierRatio = moPropertyInterface->getProperty("inlier_ratio"); ossimRefPtr inlierImageAccuracy = moPropertyInterface->getProperty("inlier_image_accuracy"); //read args : options argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" removes outliers and optimizes model using tie points"); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] "); argumentParser.getApplicationUsage()->addCommandLineOption("-h", ossimString("display Usage/Help")); argumentParser.getApplicationUsage()->addCommandLineOption("-d", ossimString(" : default=") + modelDefinition ); argumentParser.getApplicationUsage()->addCommandLineOption("-i", ossimString(" : default=") + (inlierRatio.valid()?inlierRatio->valueToString():ossimString(""))); argumentParser.getApplicationUsage()->addCommandLineOption("-a", ossimString(" : pixels, default=") + (inlierImageAccuracy.valid()?inlierImageAccuracy->valueToString():ossimString("")) ); argumentParser.getApplicationUsage()->addCommandLineOption("-o", ossimString(" : output inliers tie points path, default=") + outItptName ); argumentParser.getApplicationUsage()->addCommandLineOption("-g", ossimString(" : output geometry file, default=") + outGeomName ); if (argumentParser.read("-h")) { //help/usage argumentParser.getApplicationUsage()->write(std::cout); result = 0; } else { if (argumentParser.read("-d", argString)) { modelDefinition = tempString; } if (argumentParser.read("-i", argDouble)) { moPropertyInterface->setProperty("inlier_ratio", ossimString::toString(tempDouble)); // mo.setInlierRatio(tempDouble); } if (argumentParser.read("-a", argDouble)) { moPropertyInterface->setProperty("inlier_image_accuracy", ossimString::toString(tempDouble)); // mo.setInlierImageAccuracy(tempDouble); } if (argumentParser.read("-g", argString)) { moPropertyInterface->setProperty("geom_output_filename", tempString); // outGeomName = ossimString(tempString); } if (argumentParser.read("-o", argString)) { moPropertyInterface->setProperty("inlier_output_filename", tempString); // outItptName = ossimString(tempString); } //read mandatory args : master and slave images //should only remain 2 args int nbargs = argumentParser.argc() - 1; if (nbargs == 1) { ossimString tiePtPath(argumentParser.argv()[1]); moPropertyInterface->setProperty("gml_tieset_filename", tiePtPath); moPropertyInterface->setProperty("model_definition", modelDefinition); moProcessInterface->execute(); // if (result==0) result = mo.loadGMLTieSet(tiePtPath) ? 0 : 4 ; // if (result==0) result = mo.setupModel(modelDefinition) ? 0 : 5 ; // if (result==0) result = mo.removeOutliers() ? 0 : 6 ; // if ((result==0) && (outGeomName != "")) mo.exportModel(outGeomName); // if ((result==0) && (outItptName != "")) mo.saveGMLTieSet(outItptName); } else { cerr< #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char* argv[]) { ossimString tempString1; ossimString tempString2; ossimString tempString3; ossimString tempString4; ossimArgumentParser::ossimParameter tempParam1(tempString1); ossimArgumentParser::ossimParameter tempParam2(tempString2); ossimArgumentParser::ossimParameter tempParam3(tempString3); ossimArgumentParser::ossimParameter tempParam4(tempString4); ossimArgumentParser argumentParser(&argc, argv); ossimInit* init = ossimInit::instance(); init->addOptions(argumentParser); init->initialize(argumentParser); bool useElevation = init->getElevEnabledFlag(); bool rpcFlag = false; bool cgFlag = false; ossimDrect imageRect; double error = 0.1; imageRect.makeNan(); ossimApplicationUsage* au = argumentParser.getApplicationUsage(); au->setApplicationName(argumentParser.getApplicationName()); au->setDescription( argumentParser.getApplicationName() + " takes an input image and generates a " "corresponding RPC geometry in a variety of formats. If a bounding box is specified, the " "default output filename (based on the input filename) will be appended with the bbox spec" ", unless an output filename is explicitly provided."); au->setCommandLineUsage( argumentParser.getApplicationName() + " [options] []"); au->addCommandLineOption( "-h | --help","Display this information"); au->addCommandLineOption( "--bbox ","Subimage rectangle in image space for constraining " "RPC computation over the AOI only. Note that the RPC image space UL corner will " "correspond to (0,0), i.e., the model will be shifted from the original full-image model."); au->addCommandLineOption( "--tolerance ","Used as an RMS error tolerance in meters between original model " "and RPC."); au->addCommandLineOption( "--geom ", "Specifies format of the subimage RPC geometry file." " Possible values are: \"OGEOM\" (OSSIM geometry, default), \"DG\" (DigitalGlobe WV/QB " ".RPB format), \"JSON\" (MSP-style JSON), or \"XML\". Case insensitive."); int numArgs = argumentParser.argc(); if (argumentParser.read("-h") || argumentParser.read("--help") || (numArgs == 1)) { au->write(ossimNotify(ossimNotifyLevel_INFO)); ossimInit::instance()->finalize(); exit(0); } enum RpcGeomFormat { OGEOM, DG, JSON, XML } rpcGeomFormat=OGEOM; ossimFilename geomFile, jsonFile, xmlFile, rpbFile; ossimString suffix; ossimIpt rpcGridSize(10,10); if(argumentParser.read("--tolerance", tempParam1)) error = tempString1.toDouble(); if(argumentParser.read("--bbox", tempParam1,tempParam2,tempParam3,tempParam4 )) { double ulx,uly,lrx,lry,flip; ulx = tempString1.toDouble(); uly = tempString2.toDouble(); lrx = tempString3.toDouble(); lry = tempString4.toDouble(); if (lrx < ulx) { flip = ulx; ulx = lrx; lrx = flip; } if (lry < uly) { flip = uly; uly = lry; lry = flip; } imageRect = ossimDrect(ulx,uly,lrx,lry); ostringstream s; s<<"_bbox-"< specified. Aborting." << endl; throw ossimException( errMsg.str() ); } } argumentParser.reportRemainingOptionsAsUnrecognized(); if (argumentParser.errors()) { argumentParser.writeErrorMessages(std::cout); exit(1); } // Read remaining args as input and optional output filenames: if (argumentParser.argc() < 2) { ossimNotify(ossimNotifyLevel_WARN)<<"ERROR: Need an input filename."<write(ossimNotify(ossimNotifyLevel_INFO)); ossimInit::instance()->finalize(); exit(0); } ossimFilename inputFile (argumentParser[1]); ossimFilename outputFile; if (argumentParser.argc() > 2) outputFile = argumentParser[2]; // Establish input geometry: ossimRefPtr h = ossimImageHandlerRegistry::instance()->open(inputFile); ossimRefPtr inputProj = 0; ossim_int32 minSpacing = 100; ossimRefPtr geom; if(h.valid()) { geom = h->getImageGeometry(); if(imageRect.hasNans()) imageRect = h->getBoundingRect(); } else { ossimNotify(ossimNotifyLevel_FATAL) << "ERROR: Unable to open the image file <"<" << std::endl; au->write(ossimNotify(ossimNotifyLevel_INFO)); exit(1); } if (!geom || !geom->getProjection()) { ossimNotify(ossimNotifyLevel_FATAL) << "ERROR: Unable to obtain an input projection. " << std::endl; exit(1); } if(imageRect.hasNans()) { ossimNotify(ossimNotifyLevel_FATAL) << "ERROR: Unable to establish the image bounding rect." << std::endl; exit(1); } // First consider if the input is already an RPC (type B), and if so, simply copy it: ossimRefPtr rpc; ossimRpcModel* inputRpc = dynamic_cast(geom->getProjection()); if (inputRpc) { ossimNotify(ossimNotifyLevel_INFO) << "\nThe input image is already using RPC. Simply copying " "the coefficients to the output with offset (if any) applied..." << std::endl; rpc = inputRpc; } else { // Solve for replacement RPC: ossimNotify(ossimNotifyLevel_INFO) << "\nSolving for RPC coefficients..." << std::endl; ossimRefPtr solver = new ossimRpcSolver(useElevation, false); bool converged = solver->solve(imageRect, geom.get(), error); rpc = solver->getRpcModel(); } // Apply the offset to the bbox so that the RPC image-space coordinates will start at 0,0: rpc->setImageOffset(imageRect.ul()); ossimRefPtr rpcgeom = new ossimImageGeometry(nullptr, rpc.get()); rpcgeom->setImageSize(imageRect.size()); ossimKeywordlist kwl; rpcgeom->saveState(kwl); // Write output file(s): bool write_ok = false; switch (rpcGeomFormat) { case JSON: { #if OSSIM_HAS_JSONCPP if (outputFile) jsonFile = outputFile; else jsonFile = inputFile.fileNoExtension()+suffix; jsonFile.setExtension("json"); ossimNotify(ossimNotifyLevel_INFO) << "\nWriting RPC JSON file to <"<." << endl; ofstream jsonStream (jsonFile.string()); if (!jsonStream.fail()) { write_ok = rpc->toJSON(jsonStream); jsonStream.close(); } #else ossimNotify(ossimNotifyLevel_FATAL) << "ERROR: JSON output requested but JSON is not " "available in this build! <"<< std::endl; exit(1); #endif break; } case DG: { if (outputFile) rpbFile = outputFile; else rpbFile = inputFile.fileNoExtension()+suffix; rpbFile.setExtension("RPB"); ossimNotify(ossimNotifyLevel_INFO) << "\nWriting RPB file to <"<." << endl; ofstream rpbStream (rpbFile.string()); if (!rpbStream.fail()) { write_ok = rpc->toRPB(rpbStream); rpbStream.close(); } break; } case XML: { if (outputFile) xmlFile = outputFile; else xmlFile = inputFile.fileNoExtension()+suffix; xmlFile.setExtension("xml"); ossimNotify(ossimNotifyLevel_INFO) << "\nWriting RPC XML file to <"<." << endl; ossimXmlDocument xmlDocument; xmlDocument.fromKwl(kwl); write_ok = xmlDocument.write(xmlFile); break; } case OGEOM: default: { if (outputFile) geomFile = outputFile; else geomFile = inputFile.fileNoExtension()+suffix; geomFile.setExtension("geom"); ossimNotify(ossimNotifyLevel_INFO) << "\nWriting RPC geometry file to <"<." << endl; write_ok = kwl.write(geomFile); break; } } if (write_ok) ossimNotify(ossimNotifyLevel_INFO)<<"Finished.\n"< /* for exit */ #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug = ossimTrace("ossim-rpf:debug"); static const ossimString A_DOT_TOC_FILE = "a.toc"; /** * @brief Prints out the list of frames referred to in the given * input RPF file. Will work even if all the frames files are * missing. Deprecated function which is also available in the * ossim-img2vrr application. */ void printFrameList( const ossimFilename& imageFile, std::ostream& out, const ossimString& prefix ); void framesToToc( const ossimFilename& dotRpfFile, const ossimFilename& outputDir ); void aDotTocToDotRpf( const ossimFilename& aDotTocFile, const ossimFilename& outputDir ); int main(int argc, char* argv[]) { //--- // Get the arg count so we can tell if an arg was consumed by // ossimInit::instance()->initialize //--- int originalArgCount = argc; ossimString tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); if ( (ap.argc() == 1) && (originalArgCount > 1) ) { exit(0); // ossimInit consumed all options. } ossimApplicationUsage* appuse = ap.getApplicationUsage(); appuse->setApplicationName(ap.getApplicationName()); appuse->setDescription(ap.getApplicationName()+" Utility application for a.toc files."); appuse->addCommandLineOption("-h or --help", "Shows help"); appuse->addCommandLineOption("--list-frames"," Lists RPF formatted files of the a.toc passed to this option."); appuse->addCommandLineOption("--create-toc", " \nWrites a toc file out from dot rpf file."); appuse->addCommandLineOption("--create-dot-rpf", " \nWrites a dot rpf file(s) to output directory from an a.toc file."); //--- // Extract optional arguments. //--- bool needUsage = true; bool writeToc = false; bool writeDotRpf = false; ossimFilename inputTocFile = ossimFilename::NIL; ossimFilename outputTocFile = ossimFilename::NIL; if( ap.read("--list-frames", stringParam) ) { inputTocFile = tempString; needUsage = false; } if( ap.read("--create-toc") ) { writeToc = true; needUsage = false; } if( ap.read("--create-dot-rpf") ) { writeDotRpf = true; needUsage = false; } if(ap.read("-h") || ap.read("--help") || needUsage ) { appuse->write(std::cout); exit(0); } ap.reportRemainingOptionsAsUnrecognized(); if (ap.errors()) { ap.writeErrorMessages(std::cout); exit(1); } if ( inputTocFile.size() && inputTocFile.exists() ) { ossimString prefix = "toc."; printFrameList( inputTocFile, std::cout, prefix ); } if (writeToc) { if (argc != 3) { cout << argv[0] << " --create-toc " << std::endl; exit(0); } ossimFilename dotRpfFile = argv[1]; ossimFilename outputDir = argv[2]; framesToToc( dotRpfFile, outputDir ); } if (writeDotRpf) { if (argc != 3) { cout << argv[0] << " --create-dot-rpf " << std::endl; exit(0); } ossimFilename aDotTocFile = argv[1]; ossimFilename outputDir = argv[2]; aDotTocToDotRpf( aDotTocFile, outputDir ); } exit(0); } // End of main... void printFrameList( const ossimFilename& imageFile, std::ostream& out, const ossimString& prefix ) { // Tell the instance to skip the empty check and open // the file no matter if the frame images are there or not. ossimRefPtr pRpf = new ossimCibCadrgTileSource(); if ( pRpf ) { if( pRpf->isOpen() ) { pRpf->close(); } pRpf->setSkipEmptyCheck( true ); pRpf->setFilename(imageFile); if( pRpf->open() ) { int nTotalFramesFound = 0; ossim_uint32 nRows = -1; ossim_uint32 nCols = -1; const ossimRpfToc* pRpfToc = pRpf->getToc(); ossimFilename rootDir; pRpfToc->getRootDirectory( rootDir ); // Number of directories of images unsigned long nEntries = pRpfToc->getNumberOfEntries(); ossim_uint32 iE; for ( iE=0; iE geom = 0; const ossimRpfTocEntry* pEntry = pRpfToc->getTocEntry(iE); if ( pEntry != 0 ) { const ossimRpfBoundaryRectRecord& rpfBRR = pEntry->getBoundaryInformation(); const ossimRpfCoverageSection& rpfCC = rpfBRR.getCoverage(); ossim_float64 ul_lat = (ossim_float64)rpfCC.getUlLat(); ossim_float64 ul_lon = (ossim_float64)rpfCC.getUlLon(); ossim_float64 lr_lat = (ossim_float64)rpfCC.getLrLat(); ossim_float64 lr_lon = (ossim_float64)rpfCC.getLrLon(); // Try to print out ul and lr just as ossim-info outputs them. pRpf->setCurrentEntry(iE); ossimDrect outputRect = pRpf->getBoundingRect(); geom = pRpf->getImageGeometry(); if(geom.valid()) { ossimGpt ulg; ossimGpt lrg; geom->localToWorld(outputRect.ul(), ulg); geom->localToWorld(outputRect.lr(), lrg); ul_lat = ulg.latd(); ul_lon = ulg.lond(); lr_lat = lrg.latd(); lr_lon = lrg.lond(); } // *** HACK *** OLK 06/2010 (same hack as in ossim-orthoigen.cpp) // Encountered CADRG RPF imagery where the left edge was longitude -180 and right // edge +180. The projection code above reasonably maps all -180 to +180. This // however breaks the image footprint since it would appear that the left and // right edges were coincident instead of 360 degrees apart, i.e., a line segment // instead of a rect. So added check here for // coincident left and right edges and remapping left edge to -180. if ((ul_lon == 180.0) && (lr_lon == 180.0)) { ul_lon = -180.0; } // Make sure we use the same number of digits precision as // ossim-info (15), so we can do a per digit comparison. int prec = 15; ossimString ul_lat_str = ossimString::toString( ul_lat, prec ); ossimString ul_lon_str = ossimString::toString( ul_lon, prec ); ossimString lr_lat_str = ossimString::toString( lr_lat, prec ); ossimString lr_lon_str = ossimString::toString( lr_lon, prec ); ossim_uint32 bands = pRpf->getNumberOfOutputBands(); out << setiosflags(std::ios::left) << entryPrefix << std::setw(31) << "ul_lat:" << ul_lat_str.c_str() << "\n" << entryPrefix << std::setw(31) << "ul_lon:" << ul_lon_str.c_str() << "\n" << entryPrefix << std::setw(31) << "lr_lat:" << lr_lat_str.c_str() << "\n" << entryPrefix << std::setw(31) << "lr_lon:" << lr_lon_str.c_str() << "\n" << entryPrefix << std::setw(31) << "bands:" << ossimString::toString(bands) << "\n"; } // if ( pEntry != 0 ) nRows = pRpfToc->getNumberOfFramesVertical(iE); nCols = pRpfToc->getNumberOfFramesHorizontal(iE); ossim_uint32 iV,iH; ossim_uint32 rowIndex = nRows; for ( iV=0; iVgetRelativeFramePath(iE,iV,iH); if ( framePath.length() > 0 ) { ossimString framePrefix = entryPrefix + ossimString( "frame" ) + ossimString::toString( nEntryFramesFound++ ) + "."; out << setiosflags(std::ios::left) << framePrefix << std::setw(24) << "row:" << iV << "\n" << framePrefix << std::setw(24) << "col:" << iH << "\n" << framePrefix << std::setw(24) << "path:" << framePath.c_str() << "\n"; ++nTotalFramesFound; ossimString fullExt = framePath.ext(); ossimString seriesFromExt(""); if ( fullExt.length() > 2 ) { seriesFromExt = fullExt.beforePos(2); } const ossimRpfAttributes* pRpfAttr = 0; ossimRpfFrame rpfFrame; ossimFilename fullPath = rootDir.dirCat(framePath); const char* pFileDateTime = 0; ossimString acqDate(""); ossimGpt ulg; ossimGpt llg; ossimGpt lrg; ossimGpt urg; ossimRefPtr replaceUpdateTable = 0; if ( rpfFrame.parseFile(fullPath,true) == ossimErrorCodes::OSSIM_OK ) { replaceUpdateTable = rpfFrame.getRpfReplaceUpdateTable(); if ( replaceUpdateTable.valid() ) { replaceUpdateTable->print(out, framePrefix); } pRpfAttr = rpfFrame.getAttributes(); const ossimNitfFile* pNitfFile = rpfFrame.getNitfFile(); const ossimNitfFileHeader* pNitfFileHeader = pNitfFile!=0 ? pNitfFile->getHeader() : 0; pFileDateTime = pNitfFileHeader!=0 ? pNitfFileHeader->getDateTime() : 0; ossimNitfImageHeader* pNitfImageHeader = pNitfFile!=0 ? pNitfFile->getNewImageHeader(0) : 0; if ( pNitfImageHeader != 0 ) { acqDate = pNitfImageHeader->getImageDateAndTime(); ossim_uint32 cols = pNitfImageHeader->getNumberOfCols(); ossim_uint32 rows = pNitfImageHeader->getNumberOfRows(); ossimIrect imageRect = ossimIrect(cols*iH, rows*rowIndex-rows-1, cols*iH+cols-1, rows*rowIndex); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "frame image rect: " << imageRect << "\n"; } if (geom.valid()) { geom->localToWorld(imageRect.ul(), ulg); geom->localToWorld(imageRect.ll(), llg); geom->localToWorld(imageRect.lr(), lrg); geom->localToWorld(imageRect.ur(), urg); } // *** HACK *** OLK 06/2010 (same hack as in ossim-orthoigen.cpp) // Encountered CADRG RPF imagery where the left edge was longitude // -180 and right edge +180. The projection code above reasonably maps // all -180 to +180. This however breaks the // image footprint since it would appear that the left and right edges // were coincident instead of 360 degrees apart, i.e., a line segment // instead of a rect. So added check here for coincident left and // right edges and remapping left edge to -180. if ((ulg.lon == 180.0) && (lrg.lon == 180.0)) { ulg.lon = -180.0; llg.lon = -180.0; } } } else if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_WARN) << "ERROR: Failed to parse frame image: " << fullPath.c_str() << std::endl; } if ( pRpfAttr != 0 ) { int prec = 15; ossimString ul_lat_str = ossimString::toString(ulg.latd(), prec); ossimString ul_lon_str = ossimString::toString(ulg.lond(), prec); ossimString ll_lat_str = ossimString::toString(llg.latd(), prec); ossimString ll_lon_str = ossimString::toString(llg.lond(), prec); ossimString lr_lat_str = ossimString::toString(lrg.latd(), prec); ossimString lr_lon_str = ossimString::toString(lrg.lond(), prec); ossimString ur_lat_str = ossimString::toString(urg.latd(), prec); ossimString ur_lon_str = ossimString::toString(urg.lond(), prec); out << setiosflags(std::ios::left) << framePrefix << std::setw(24) << "ul_lat:" << ul_lat_str.c_str() << "\n" << framePrefix << std::setw(24) << "ul_lon:" << ul_lon_str.c_str() << "\n" << framePrefix << std::setw(24) << "ll_lat:" << ll_lat_str.c_str() << "\n" << framePrefix << std::setw(24) << "ll_lon:" << ll_lon_str.c_str() << "\n" << framePrefix << std::setw(24) << "lr_lat:" << lr_lat_str.c_str() << "\n" << framePrefix << std::setw(24) << "lr_lon:" << lr_lon_str.c_str() << "\n" << framePrefix << std::setw(24) << "ur_lat:" << ur_lat_str.c_str() << "\n" << framePrefix << std::setw(24) << "ur_lon:" << ur_lon_str.c_str() << "\n" << framePrefix << std::setw(24) << "present:" << "true" << "\n" << framePrefix << std::setw(24) << "CurrencyDate:" << pRpfAttr->theCurrencyDate << "\n" << framePrefix << std::setw(24) << "ProductionDate:" << pRpfAttr->theProductionDate << "\n" << framePrefix << std::setw(24) << "SignificantDate:" << pRpfAttr->theSignificantDate << "\n" << framePrefix << std::setw(24) << "FileDateTime:" << pFileDateTime << "\n" << framePrefix << std::setw(24) << "AcquisitionDate:" << acqDate << "\n" << framePrefix << std::setw(24) << "SeriesCode:" << seriesFromExt.c_str() << "\n" << framePrefix << std::setw(24) << "ChartSeriesCode:" << pRpfAttr->theChartSeriesCode << "\n" << framePrefix << std::setw(24) << "MapDesignationCode:" << pRpfAttr->theMapDesignationCode << "\n" << framePrefix << std::setw(24) << "Edition:" << pRpfAttr->theEdition << "\n" << framePrefix << std::setw(24) << "DataSource:" << pRpfAttr->theDataSource << "\n"; } else { out << setiosflags(std::ios::left) << framePrefix << std::setw(24) << "present:" << "false" << "\n"; } } } // for ( iH=0; iH toc = new ossimRpfToc(); try { toc->createTocAndCopyFrames( dotRpfFile, outputDir ); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; } } void aDotTocToDotRpf( const ossimFilename& aDotTocFile, const ossimFilename& outputDir ) { const char MODULE[] = "ossim-rpf::aDotTocToDotRpf"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << "\na.toc file: " << aDotTocFile << "\noutput directory: " << outputDir << std::endl; } ossimRefPtr toc = new ossimRpfUtil(); try { toc->writeDotRpfFiles( aDotTocFile, outputDir ); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; } } ossim-Miami-2.9.1/apps/ossim-senint/000077500000000000000000000000001352751253100173065ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-senint/CMakeLists.txt000066400000000000000000000003201352751253100220410ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-senint INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-senint/ossim-senint.cpp000066400000000000000000000727701352751253100224570ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Dave Hicks // // Description: // // Application to do multi-image (sensor model) intersection or single-image/ // earth (ellipsoid, DEM) intersection. Also outputs estimated CE/LE // and error ellipse parameters at the specified probability level for the // intersected point based covariance propagation of support data error. // Propagated CE/LE available only if ossimSensorModelTuple::intersect returns // a (status!=ERROR_PROP_FAIL). This status is only possible if // ossimSensorModelTuple is able to obtain full covariance info from the // sensor model(s) being used. // // Demonstrates use of ossimSensorModelTuple for single and stereo. Also // demonstrates several uses of ossimPositionQualityEvaluator class. // // One or two images may be used. The mensuration files must have the same // number of points for both images, in the same order. // //---------------------------------------------------------------------------- // $Id: senint.cpp 13025 2008-06-13 17:06:30Z sbortman $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceExec("senint:exec"); static ossimTrace traceDebug("senint:debug"); //************************************************************************** // usage() //************************************************************************** void usage() { std::cout << " example:\n\n" << " senint -pt rpc -i1 image1.geom [-i2 image2.geom] [-surf surf.dat]\n" << " For pt=std, performs multi & single-image intersections\n" << " for all image points found in image1.men/image2.men files.\n" << " Second image argument is optional. Defaults to pt=std.\n" << "\n" << " For pt=rpc, exercises optional positionQualityEvaluator\n" << " constructors/extractors. Only valid for RPC models.\n" << "\n" << " The -surf option allows setting of DEM/slope accuracy and\n" << " orientation. The file format is:\n" << " CE90 LE90 [DEM CE/LE]\n" << " x y z [surface normal unit vector]\n" << " varx vary varz [diagonal elements of covariance matrix]\n" << "\n" << " The -losoverride option allows setting of LOS direction\n" << " and accuracy. The file format is:\n" << " elev azim [target elevation, azimuth]\n" << " bias rand [LOS 1-sigma bias, random components]\n" << "\n" << " The -plevel option allows setting of probability level\n" << " for output CE/LE and ellipse. Choices are:\n" << " 0 - 1-sigma\n" << " 1 - .5P\n" << " 2 - .9P Default\n" << " 3 - .95P\n" << "\n" << std::endl; } int main(int argc, char *argv[]) { const char* MODULE = "senint"; ossimString line(100,'~'); ossimString sp26(26,' '); ossimString sp20(20,' '); typedef enum { STD, RPC } procType_t; char timeString[22]; time_t now = time(NULL); strftime(timeString, 21, "%Y-%m-%d %H:%M:%S", localtime(&now)); std::cout << "\n" << line <addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()-> setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()-> setDescription(argumentParser.getApplicationName()+ " Performs single/multi-image intersection"); argumentParser.getApplicationUsage()-> setCommandLineUsage(argumentParser.getApplicationName()+ "-pt processing type -i1 input geometry file"); argumentParser.getApplicationUsage()-> addCommandLineOption("-h", "Display this information"); argumentParser.getApplicationUsage()-> addCommandLineOption("-i1", "REQUIRED: input geometry file for image 1"); argumentParser.getApplicationUsage()-> addCommandLineOption("-i2", "OPTIONAL: input geometry file for image 2"); argumentParser.getApplicationUsage()-> addCommandLineOption("-pt", "OPTIONAL: processing type (std or rpc)"); argumentParser.getApplicationUsage()-> addCommandLineOption("-surf", "OPTIONAL: filename of surface parameters"); argumentParser.getApplicationUsage()-> addCommandLineOption("-losoverride", "OPTIONAL: filename of LOS parameters"); argumentParser.getApplicationUsage()-> addCommandLineOption("-plevel", "OPTIONAL: probability level (0-3)"); if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG senint: entering..." << std::endl; if(argumentParser.read("-h") || argumentParser.read("--help")|| argumentParser.argc() <2) { argumentParser.getApplicationUsage()->write(std::cout); usage(); return 0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Parse the input arguments //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // processing type ossimString senintARGS0; while(argumentParser.read("-pt", stringParam)) { senintARGS0 = tempString; } if (senintARGS0.size() == 0) { senintARGS0 = "std"; } procType_t procType; if (senintARGS0=="std") procType = STD; else if (senintARGS0=="rpc") procType = RPC; else { std::cout << " Invalid processing type..."< model[2]; // Load 1st image inputFile[0] = senintARGS1; model[0] = ossimSensorModelFactory::instance()->createProjection(inputFile[0], 0); if (!dynamic_cast(model[0].get())) { std::cout << " createProjection for image 1 failed..."<0) { inputFile[1] = senintARGS2; model[1] = PTR_CAST(ossimSensorModel, ossimSensorModelFactory::instance()->createProjection(inputFile[1],0)); if (!model[1]) { std::cout << " loadState 2 Failed"<(model[i].get()); if(m) { iSet.addImage(m); } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Load the surface parameters //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ossim_float64 surfCE90 = 0.0; ossim_float64 surfLE90 = 0.0; ossimColumnVector3d surfNormal(0,0,1); NEWMAT::Matrix surfCovMat(3,3); surfCovMat = 0.0; if (senintARGS3.size()>0) { ossimString surfFileName = senintARGS3; ifstream surfFile(surfFileName.data(), ios::in); if (surfFile.good() == 0) { std::cout << "\n "<< surfFileName << " load failed..." << std::endl; return 0; } surfFile >> surfCE90 >> surfLE90; surfFile >> surfNormal[0] >> surfNormal[1] >> surfNormal[2]; surfFile >> surfCovMat(1,1) >> surfCovMat(2,2) >> surfCovMat(3,3); std::cout << "\n "<< surfFileName << " dump...\n" << sp20<0) { ossimString overFileName = senintARGS4; ifstream overFile(overFileName.data(), ios::in); if (overFile.good() == 0) { std::cout << "\n "<< overFileName << " load failed..." << std::endl; return 0; } overFile >> overTel >> overTaz; overFile >> overBias >> overRand; LOSoverride = true; std::cout << "\n "<< overFileName << " dump...\n" << sp20<0) { ossim_int32 lev = senintARGS5.toInt32(); switch (lev) { case ONE_SIGMA: pLev = ONE_SIGMA; pLevC = " 1-Sigma"; break; case P50: pLev = P50; pLevC = " 0.5P"; break; case P90: pLev = P90; pLevC = " 0.9P"; break; case P95: pLev = P95; pLevC = " 0.95P"; break; default: break; } } std::cout << "\n Probability level: "<< pLevC << std::endl; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Load image mensuration info //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ std::vector chkIds; vector obs; vector imageIDs; int numPts = 0; char* tmpBuf = new char[256]; for (int im=0; im> numMeas; DptSet_t meas; numPts = numMeas; for (int j=0; j> tmpBuf; id = tmpBuf; chkIds.push_back(id); imgFile >> u >> v; uv.u = u; uv.v = v; meas.push_back(uv); } imgFile.close(); obs.push_back(meas); } delete [] tmpBuf; tmpBuf = 0; ossimSensorModelTuple::IntersectStatus opOK; ossim_float64 atHgt; ossimEcefPoint intECF; ossim_float64 CEpLev; ossim_float64 LEpLev; NEWMAT::Matrix covMat(3,3); pqeErrorEllipse ell; //======================================================================= // procType switch //======================================================================= switch (procType) { case STD: { std::cout << "\n Standard processing mode...\n"; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Process the measurements // First, stereo if 2 images present, then individual processing // of each image (DEM & ellipsoid intersection) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for (int pt=0; pt> Image: " << imageIDs[img] << " mono..."<getClassName().contains("Rpc")) { std::cout<< "\n >> Image: " << imageIDs[img] << " mono..."<getBiasError(); randError = mdl->getRandError(); } std::cout <<" tel/taz: "<getRpcParameters(rpcPar); rpc.theLineScale = rpcPar.lineScale; rpc.theSampScale = rpcPar.sampScale; rpc.theLatScale = rpcPar.latScale; rpc.theLonScale = rpcPar.lonScale; rpc.theHgtScale = rpcPar.hgtScale; rpc.theLineOffset = rpcPar.lineOffset; rpc.theSampOffset = rpcPar.sampOffset; rpc.theLatOffset = rpcPar.latOffset; rpc.theLonOffset = rpcPar.lonOffset; rpc.theHgtOffset = rpcPar.hgtOffset; rpc.theType = rpcPar.type; for (int i=0; i<20; i++) { rpc.theLineNumCoef[i] = rpcPar.lineNumCoef[i]; rpc.theLineDenCoef[i] = rpcPar.lineDenCoef[i]; rpc.theSampNumCoef[i] = rpcPar.sampNumCoef[i]; rpc.theSampDenCoef[i] = rpcPar.sampDenCoef[i]; } biasError = mdl->getBiasError(); randError = mdl->getRandError(); std::cout << sp26 <<" bias/rand: "< #include #include #include using namespace std; void usage() { cout << "space_imaging [out_geom]" << endl << endl << "Note: out_geom is defaulted to output.kwl" << endl; } int main(int argc, char* argv[]) { ossimFilename inputFile = ""; ossimFilename outputFile = "output.kwl"; if(argc <= 1) { usage(); } else if(argc == 2) { inputFile = argv[1]; } else { inputFile = argv[1]; outputFile = argv[2]; } if(inputFile != "") { ossimKeywordlist kwl; ossimSpaceImagingGeom spaceImg(inputFile); spaceImg.exportToOssim(kwl); kwl.write(ossimFilename(outputFile)); } } ossim-Miami-2.9.1/apps/ossim-src2src/000077500000000000000000000000001352751253100173675ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-src2src/CMakeLists.txt000066400000000000000000000003211352751253100221230ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-src2src INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-src2src/ossim-src2src.cpp000066400000000000000000000404411352751253100226070ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // //******************************************************************* // $Id: ossim-src2src.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //************************************************************************** // usage() //************************************************************************** void usage() { ossimNotify(ossimNotifyLevel_INFO) << " examples:\n\n" << " ossim-create-src --tiling-template ./mytemplate.template ./myfile.tif ./outdir\n" << std::endl;; } //***************************************************************************************** // Centralized point to capture all program exits (aids in debugging -- please leave) //***************************************************************************************** void finalize(int exit_code) { exit(exit_code); } void parseSrcFile(const ossimFilename& srcFile, vector& srcRecordFiles, ossimString& prefix) { if (!srcFile.isReadable()) return; ossimKeywordlist src_kwl (srcFile); unsigned int image_idx = 0; ossimString lookup = src_kwl.find("dem0.file"); if (!lookup.empty()) { prefix = "dem"; } // Loop to read all image file entries: while (true) { ossimSrcRecord srcRecord(src_kwl, image_idx++, prefix); if (!srcRecord.valid()) break; srcRecordFiles.push_back(srcRecord); } } ossimRefPtr getTiling(const ossimFilename& templateFile) { ossimKeywordlist templateKwl; if (!templateKwl.addFile(templateFile)) { return 0; } ossimString prefix ("igen.tiling."); while (1) { if (templateKwl.find(prefix.chars(), "tile_source")) { break; } else { return 0; } // If we got here, then no matches were found in the template. Try again but without a prefix: if (prefix.empty()) break; prefix.clear(); } // Initialize the tiling object if enabled: ossimRefPtr tiling = new ossimTilingPoly; if (!tiling->loadState(templateKwl, prefix)) { return 0; } return tiling; } ossimDrect getRect(ossimRefPtr mapProj, vector points) { std::vector rectTmp; rectTmp.resize(points.size()); for(std::vector::size_type index=0; index < points.size(); ++index) { mapProj->worldToLineSample(points[(int)index], rectTmp[(int)index]); } if (rectTmp.size() > 3) { ossimDrect rect2 = ossimDrect(rectTmp[0], rectTmp[1], rectTmp[2], rectTmp[3]); return rect2; } return ossimDrect(); } //************************************************************************** // Main Application //************************************************************************** int main(int argc, char *argv[]) { std::string tempString1; ossimArgumentParser::ossimParameter stringParam1(tempString1); std::string tempString2; ossimArgumentParser::ossimParameter stringParam2(tempString2); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); ossimApplicationUsage* appuse = argumentParser.getApplicationUsage(); appuse->setApplicationName(argumentParser.getApplicationName()); appuse->setDescription(argumentParser.getApplicationName()+ " generate src files for polygons."); appuse->setCommandLineUsage(argumentParser.getApplicationName()+ "ossim-create-src [--tiling-template] "); appuse->addCommandLineOption("--tiling-template", "Specify an external file that contains tiling information."); ossimFilename templateFile = ""; if(argumentParser.read("--tiling-template", stringParam1)) { templateFile = ossimFilename(tempString1); } // End of arg parsing. argumentParser.reportRemainingOptionsAsUnrecognized(); if ( argumentParser.errors() ) { argumentParser.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); finalize(1); } if (argc == 1) { ossimNotify(ossimNotifyLevel_WARN)<< "Must supply an input file or info option." << std::endl; finalize(0); } ossim_uint32 idx = 0; ossim_uint32 last_idx = argumentParser.argc()-1; ossimFilename inputSrcFile = ""; ossimString prefixStr = "image"; vector inputFiles; while(argumentParser.argv()[idx] && (idx < last_idx)) { ossimString file = argumentParser.argv()[idx]; if (file.contains(".src")) { // input file spec provided via src file. Need to parse it: inputSrcFile = ossimFilename(file); if (!inputSrcFile.exists() ) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-src2src: file does not exist: " << inputSrcFile << std::endl; finalize(1); } parseSrcFile(inputSrcFile, inputFiles, prefixStr); } ++idx; } // The last filename left on the command line should be the product filename: ossimFilename outputFileDir = argumentParser.argv()[last_idx]; if (!outputFileDir.isDir()) { outputFileDir = outputFileDir.path(); if (!outputFileDir.exists() ) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-src2src: output directory does not exist: " << outputFileDir << std::endl; finalize(1); } } if (!templateFile.exists()) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-src2src: template file does not exist:: " << templateFile << std::endl; finalize(1); } ossimRefPtr polyTiling = getTiling(templateFile); if (!polyTiling.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-src2src: error generating tiling: " << templateFile << std::endl; finalize(1); } // Open up src file to get coordinate info from each file listed in src file. ossim_float64 minLat = 90.0; ossim_float64 maxLat = -90.0; ossim_float64 minLon = 180.0; ossim_float64 maxLon = -180.0; ossimString tileName; ossimIrect clipRect; map infos; ossimRefPtr mapProj = 0; for (ossim_uint32 i = 0; i < inputFiles.size(); i++) { ossimFilename inputFile = inputFiles[i].getFilename(); vector entryList; ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(inputFile); if (ih.valid() ) { if(inputFiles[i].getEntryIndex() > -1 ) { entryList.push_back(inputFiles[i].getEntryIndex()); } else { ih->getEntryList(entryList); } for(ossim_uint32 entryIdx = 0; entryIdx < entryList.size(); ++entryIdx) { // Establish the image handler for this particular frame. This may be just // the handler already opened in the case of single image per file: ossimImageHandler* img_handler = 0; if (entryList.size() == 1) { img_handler = ih.get(); } else { img_handler = (ossimImageHandler*)ih->dup(); } img_handler->setCurrentEntry(entryList[entryIdx]); ossimDrect outputRect = img_handler->getBoundingRect(); ossimRefPtr geom = img_handler->getImageGeometry(); if(geom.valid()) { ossimGpt ulg; ossimGpt llg; ossimGpt lrg; ossimGpt urg; geom->localToWorld(outputRect.ul(), ulg); geom->localToWorld(outputRect.ll(), llg); geom->localToWorld(outputRect.lr(), lrg); geom->localToWorld(outputRect.ur(), urg); //find min and max lat, lon for whole src file if (minLat > llg.lat) { minLat = llg.lat; } if (minLon > llg.lon) { minLon = llg.lon; } if (maxLat < urg.lat) { maxLat = urg.lat; } if (maxLon < urg.lon) { maxLon = urg.lon; } ossimString fileInfo = inputFile + "|" + ossimString::toString(entryIdx) + "|" + ossimString::toString(ulg.lon) + "," + ossimString::toString(ulg.lat) + "," + ossimString::toString(urg.lon) + "," + ossimString::toString(urg.lat) + "," + ossimString::toString(lrg.lon) + "," + ossimString::toString(lrg.lat) + "," + ossimString::toString(llg.lon) + "," + ossimString::toString(llg.lat); infos[fileInfo] = inputFiles[i]; if (!mapProj.valid()) { ossimRefPtr proj = geom->getProjection(); if (proj.valid()) { mapProj = PTR_CAST(ossimMapProjection, proj->dup()); if (!mapProj.valid()) //default it to ossimEquDistCylProjection { mapProj = new ossimEquDistCylProjection; mapProj->setMetersPerPixel(geom->getMetersPerPixel()); } } } } img_handler = 0; } ih = 0; } else { continue; } } inputFiles.clear(); //get bounding rect for entire image vector points; if (points.size() == 0) { points.push_back(ossimGpt(maxLat, minLon)); points.push_back(ossimGpt(maxLat, maxLon)); points.push_back(ossimGpt(minLat, maxLon)); points.push_back(ossimGpt(minLat, minLon)); } if(mapProj.valid()) { ossimGpt tie(maxLat, minLon); mapProj->setUlTiePoints(tie); polyTiling->initialize(*(mapProj.get()), getRect(mapProj, points)); } while(polyTiling->next(mapProj, clipRect, tileName)) { ossimFilename outSrc = outputFileDir + "/" + ossimFilename(tileName).noExtension() + ".src"; map::iterator it = infos.begin(); ossim_int32 index = 0; map srcList; while (it != infos.end()) { ossimString fileInfo = it->first; vector fileInfos = fileInfo.split("|"); ossim_int32 entryId = fileInfos[1].toInt(); vector latlonInfo = fileInfos[2].split(","); double ulgLon = latlonInfo[0].toDouble(); double ulgLat = latlonInfo[1].toDouble(); double urgLon = latlonInfo[2].toDouble(); double urgLat = latlonInfo[3].toDouble(); double lrgLon = latlonInfo[4].toDouble(); double lrgLat = latlonInfo[5].toDouble(); double llgLon = latlonInfo[6].toDouble(); double llgLat = latlonInfo[7].toDouble(); points.clear(); points.push_back(ossimGpt(ulgLat, ulgLon)); points.push_back(ossimGpt(urgLat, urgLon)); points.push_back(ossimGpt(lrgLat, lrgLon)); points.push_back(ossimGpt(llgLat, llgLon)); //get bounding for each image listed in src file ossimDrect rect = getRect(mapProj, points); //check if the rect of image intersect with the rect of tile if (rect.intersects(clipRect)) { ossimSrcRecord srcRecord = it->second; srcRecord.setEntryIndex(entryId); srcList[index] = srcRecord; index++; } it++; } //write image files which intersect with the tile to a new src file if (srcList.size() > 0) { ofstream outputSrcFile(outSrc.c_str()); map::iterator srcIt = srcList.begin(); while (srcIt != srcList.end()) { ossimString prefix = prefixStr + ossimString::toString(srcIt->first) + "."; ossimFilename newSrcFile = srcIt->second.getFilename(); ossim_int32 entryId = srcIt->second.getEntryIndex(); ossimFilename supportDir = srcIt->second.getSupportDir(); ossimString hisOp = srcIt->second.getHistogramOp(); vector bands = srcIt->second.getBands(); double weight = srcIt->second.getWeight(); ossimFilename overviewPath = srcIt->second.getOverviewPath(); ossimFilename hisPath = srcIt->second.getHistogramPath(); ossimFilename maskPath = srcIt->second.getMaskPath(); if (!newSrcFile.empty()) { ossimString str = prefix + "file: " + newSrcFile; outputSrcFile << str << "\n"; } if (entryId > -1) { ossimString str = prefix + "entry: " + ossimString::toString(entryId); outputSrcFile << str << "\n"; } if (!supportDir.empty()) { ossimString str = prefix + "support: " + supportDir; outputSrcFile << str << "\n"; } if (!hisOp.empty()) { ossimString str = prefix + "hist-op: " + hisOp; outputSrcFile << str << "\n"; } if (bands.size()) { ossimString str = ""; for (ossim_uint32 bandIndex = 0; bandIndex < bands.size(); bandIndex++) { if (bandIndex == (bands.size()-1)) { str = str + ossimString::toString(bands[bandIndex]+1); } else { str = str + ossimString::toString(bands[bandIndex]+1) + ","; } } str = prefix + "rgb: " + str; outputSrcFile << str << "\n"; } if (weight > 0) { ossimString str = prefix + "opacity: " + ossimString::toString(weight); outputSrcFile << str << "\n"; } if (!overviewPath.empty()) { ossimString str = prefix + "ovr: " + overviewPath; outputSrcFile << str << "\n"; } if (!hisPath.empty()) { ossimString str = prefix + "hist: " + hisPath; outputSrcFile << str << "\n"; } if (!maskPath.empty()) { ossimString str = prefix + "mask: " + maskPath; outputSrcFile << str << "\n"; } outputSrcFile << "\n"; srcIt++; } outputSrcFile.close(); srcList.clear(); } } if (polyTiling.valid()) { polyTiling = 0; } if (mapProj.valid()) { mapProj = 0; } points.clear(); infos.clear(); finalize(0); return 0; // Never reached, but satisfies return type } ossim-Miami-2.9.1/apps/ossim-swapbytes/000077500000000000000000000000001352751253100200275ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-swapbytes/CMakeLists.txt000066400000000000000000000003231352751253100225650ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-swapbytes INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-swapbytes/ossim-swapbytes.cpp000066400000000000000000000132771352751253100237160ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // Contributor: David A. Horner (http://dave.thehorners.com) // // Description: Application to swapbytes. // Reads input pixels from input_file, performs a byte swap, and outputs result // to output_file. // // NOTE: // This application assumes data is of "short" (two bytes per pixel) type. // //******************************************************************* // $Id: swapbytes.cpp 10285 2007-01-16 17:54:33Z dburken $ #include #include #include #include #include #include using namespace std; #include #include #include #include #include int main(int argc, char** argv) { enum { OK, ERROR }; ossimString tempString; ossimArgumentParser argumentParser(&argc, argv); ossimArgumentParser::ossimParameter stringParam(tempString); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" Swaps bytes of input_file and outputs result to output_file.\ \n\nNotes:\n\ - Data type of a short (two bytes per pixel) is the default.\n\ - Supported bytes_per_pixel: 2, 4, and 8"); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [-h][-b ] input_file> "); argumentParser.getApplicationUsage()->addCommandLineOption("-b", "bytes_per_pixel"); argumentParser.getApplicationUsage()->addCommandLineOption("-h", "Prints the usage"); argumentParser.reportRemainingOptionsAsUnrecognized(); if (argumentParser.errors()) { argumentParser.writeErrorMessages(std::cout); exit(1); } if(argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(std::cout); exit(0); } //*** // Extract optional arguments. //*** ossim_uint32 bpp = 2; // bytes per pixel if(argumentParser.read("-b", stringParam)) { bpp = atoi(tempString); } // // Two required args: input_file output_file if(argumentParser.argc() < 3) { argumentParser.getApplicationUsage()->write(std::cout); exit(ERROR); } if (bpp != 2 && bpp != 4 && bpp != 8) { cerr << "swapbytes:main ERROR:" << "\nUnsupported bytes per pixel: " << bpp << "\nSupported values are: 2, 4, and 8" << endl; exit(ERROR); } // Input stream to source file. ifstream is(argv[1], ios::in | ios::binary); if (!is) { cerr << "swapbytes" << " ERROR:\n" << "Cannot open: " << argv[1] << endl; return false; } // Output stream to new file. ofstream os(argv[2], ios::out | ios::binary); if (!os) { cerr << "swapbytes" << " ERROR:\n" << "Cannot open: " << argv[2] << endl; return false; } //*** // Get the file size of the source. //*** struct stat stat_buf; stat(argv[1], &stat_buf); ossim_uint32 inputFileByteSize = stat_buf.st_size; ossim_uint32 totalPixelsToSwap = inputFileByteSize / bpp; double totalPixels = totalPixelsToSwap; // for percent complete cout << "\ninputFile: " << argv[1] << "\noutputFile: " << argv[2] << "\ninputFileByteSize: " << inputFileByteSize << "\npixelsToSwap: " << totalPixelsToSwap << "\nbytes per pixel: " << bpp << endl; //*** // The byte size should be evenly divisible by bytes per pixel (bpp); // if not, consider this an error condition and get out. //*** if (inputFileByteSize % bpp) { cerr << "Error: Byte size of file should be evenly divisible by " << bpp << ".\nExiting..." << endl; is.close(); os.close(); exit(ERROR); } const ossim_uint32 DEFAULT_SAMPLES = 512; unsigned char* lineBuff = new unsigned char[DEFAULT_SAMPLES*bpp]; ossim_uint32 pixelsSwaped = 0; ossimEndian oe; while (pixelsSwaped < totalPixelsToSwap) { ossim_uint32 pixelsLeftToSwap = totalPixelsToSwap - pixelsSwaped; ossim_uint32 itemsToSwap = (DEFAULT_SAMPLES < pixelsLeftToSwap) ? DEFAULT_SAMPLES : pixelsLeftToSwap; ossim_uint32 bytesToSwap = itemsToSwap * bpp; // read the input line. is.read((char*)lineBuff, bytesToSwap); if (!is) { cerr << "\nERROR: Reading image line." << endl; is.close(); os.close(); delete [] lineBuff; exit(ERROR); } pixelsSwaped += itemsToSwap; // Swap the bytes. switch (bpp) { case 2: oe.swapTwoBytes(lineBuff, itemsToSwap); break; case 4: oe.swapFourBytes(lineBuff, itemsToSwap); break; case 8: oe.swapEightBytes(lineBuff, itemsToSwap); break; } os.write((char*)lineBuff, bytesToSwap); if (!os) { cerr << "\nERROR: Writing image line." << endl; is.close(); os.close(); delete [] lineBuff; exit(ERROR); } double pixSwapped = pixelsSwaped; cout << setiosflags(ios::fixed) << setprecision(0) << setw(3) << pixSwapped / totalPixels * 100 << "% \r" << flush; } cout << "\r100%\nFinished..." << endl; // Clean up... is.close(); os.close(); delete [] lineBuff; return OK; } ossim-Miami-2.9.1/apps/ossim-tfw2ogeom/000077500000000000000000000000001352751253100177175ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-tfw2ogeom/CMakeLists.txt000066400000000000000000000003231352751253100224550ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-tfw2ogeom INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-tfw2ogeom/ossim-tfw2ogeom.cpp000066400000000000000000000154371352751253100234760ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: tfw2ogeom.cpp 13025 2008-06-13 17:06:30Z sbortman $ #include #include #include #include #include #include #include #include #include #include #include #include #include void usage() { ossimNotify(ossimNotifyLevel_NOTICE) << "ossim-tfw2ogeom " << " []\n\n" << "Options:\n" << "-h Display usage.\n\n" << "-w Write a template to template_file.\n\n" << " See template.kwl for descriptions\n\n" << "[] optional argumaent and if not supplied\n" << " defaults to the tif world file with a\n" << " .geom extension" << std::endl; } void outputGeom(const ossimFilename& templateFile, const ossimFilename& tfwFile, const ossimFilename& output) { ossimNotify(ossimNotifyLevel_NOTICE) << "tfw2ogeom:" << "\ntemplate file: " << templateFile << "\ntfw file: " << tfwFile << "\noutput geometry file: " << output << std::endl; ossimKeywordlist geomKwl(templateFile.c_str()); ossimTiffWorld tfw; const char* pixel_type = geomKwl.find(ossimKeywordNames::PIXEL_TYPE_KW); const char* pcs_code = geomKwl.find(ossimKeywordNames::PCS_CODE_KW); ossimUnitType unitType = (ossimUnitType)ossimUnitTypeLut::instance()->getEntryNumber(geomKwl); if(ossimString(pixel_type).upcase().contains("POINT")) { tfw = ossimTiffWorld(tfwFile.c_str(), OSSIM_PIXEL_IS_POINT, unitType); } else { tfw = ossimTiffWorld(tfwFile.c_str(), OSSIM_PIXEL_IS_AREA, unitType); } if(pcs_code) { ossimString epsg_spec ("EPSG:"); epsg_spec += ossimString::toString(pcs_code); ossimProjection* proj = ossimEpsgProjectionFactory::instance()->createProjection(epsg_spec); if (proj) proj->saveState(geomKwl); } tfw.saveToOssimGeom(geomKwl); geomKwl.write(output.c_str()); ossimNotify(ossimNotifyLevel_NOTICE) << "Wrote file: " << output.c_str() << std::endl; } void writeTemplate(const ossimFilename& templateFile) { std::ofstream out(templateFile.c_str()); if (!out) { return; } out << "// tfw2ogeom keyword list template\n" << "// Note: Use c++ comments \"//\" for comments.\n\n\n" << "// Units can be any of the below; although typically,\n" << "// meters or degrees.\n" << "// us_survey_feet\n" << "// feet\n" << "// meters\n" << "// degrees\n" << "// seconds\n" << "// minutes\n" << "// miles\n" << "// nautical_miles\n" << "units: meters\n\n" << "// Pixel type specifies where the easting northing values\n" << "// refer to.\n" << "// \"pixel_is_area\" means the tie point is relative to\n" << "// the upper left corner of the pixel.\n" << "// \"pixel_is_point\" means the tie point is relative to\n" << "// the center of the pixel.\n" << "pixel_type: pixel_is_area\n\n\n" << "// Give a pcs code you don't need to give the full projection\n" << "// information defined below.\n" << "// pcs_code: 32149\n\n\n" << "// Projection type. Note that type is the ossim class\n" << "// for the projection. Some common names are listed below.\n" << "// Have only one type or a pcs code.\n" << "// type: ossimAlbersProjection\n" << "// type: ossimEquDistCylProjection\n" << "// type: ossimLambertConformalConicProjection\n" << "// type: ossimUtmProjection\n" << "// type: ossimTransMercatorProjection\n\n\n" << "// Projection pararmeters. These are some common ones.\n" << "// origin_latitude:\n" << "// central_meridian:\n" << "// scale_factor:\n" << "// zone:\n" << "// std_parallel_1:\n" << "// std_parallel_2:\n" << "// Use application \"datums\" to get a list of datum codes.\n" << "// datum:\n" << "// false_easting:\n" << "// false_northing:\n\n\n" << std::endl; out.close(); ossimNotify(ossimNotifyLevel_NOTICE) << "Wrote file: " << templateFile.c_str() << std::endl; } int main(int argc, char* argv[]) { std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()-> setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()-> setDescription(argumentParser.getApplicationName()+" Takes tiff world file and a projection template and makes an ossim geometry file. "); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" []"); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display usage."); argumentParser.getApplicationUsage()->addCommandLineOption("-w", "Writes a template file out to argument after the -w"); if (argumentParser.read("-h") || argumentParser.read("--help")||(argumentParser.argc() < 3)) { usage(); exit(0); } while(argumentParser.read("-w", stringParam)) { ossimFilename geometryTemplateFile = tempString.c_str(); writeTemplate(geometryTemplateFile); exit(0); } ossimFilename templateFile; ossimFilename tfw; ossimFilename output; if (argumentParser.argc() == 3) { templateFile = argumentParser.argv()[argumentParser.argc()-2]; tfw = argumentParser.argv()[argumentParser.argc()-1]; output = tfw; output.setExtension("geom"); } else if (argumentParser.argc() == 4) { templateFile = argumentParser.argv()[argumentParser.argc()-3]; tfw = argumentParser.argv()[argumentParser.argc()-2]; output = argumentParser.argv()[argumentParser.argc()-1]; } else { usage(); exit(0); } outputGeom(templateFile, tfw, output); return 0; } ossim-Miami-2.9.1/apps/ossim-tfw2ogeom/template.kwl000066400000000000000000000015461352751253100222570ustar00rootroot00000000000000// units can be // us_survey_feet // feet // meters // degrees // seconds // minutes // miles // nautical_miles // units: meters // can be either: // pixel_is_point // pixel_is_area // // this specifies where the easting northing values refer to. If the easting northing is the edge // then the value should be pixel_is_area, if the easting northing refers to the center of the // pixel then is is pixel_is_point // pixel_type: pixel_is_area // Give a pcs code you don't need to give the full projection // information defined below // pcs_code: 32149 // If you don't have the pcs code then you must supply // all projection information for the projection desired. // // type: // origin_latitude: // central_meridian: // scale_factor: // zone: // std_parallel_1: // std_parallel_2: // tie_point_easting: // tie_point_northing: ossim-Miami-2.9.1/apps/ossim-tool-client/000077500000000000000000000000001352751253100202375ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-tool-client/CMakeLists.txt000066400000000000000000000003571352751253100230040ustar00rootroot00000000000000IF (UNIX) FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-tool-client INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ENDIF (UNIX)ossim-Miami-2.9.1/apps/ossim-tool-client/ossim-tool-client.cpp000066400000000000000000000024461352751253100243320ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define MAX_BUF_LEN 4096 int main(int argc, char *argv[]) { char buffer [MAX_BUF_LEN]; if (argc < 2) { cout<<"Usage "< #include #include int main(int argc, char *argv[]) { // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(argc, argv); const char* DEFAULT_PORT = "ossimd"; const char* portid = DEFAULT_PORT; if (argc > 1) portid = argv[1]; ossimToolServer ots; ots.startListening(portid); return 0; } ossim-Miami-2.9.1/apps/ossim-viirs-proc/000077500000000000000000000000001352751253100201035ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-viirs-proc/CMakeLists.txt000066400000000000000000000003241352751253100226420ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-viirs-proc INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-viirs-proc/ossim-viirs-proc.cpp000066400000000000000000000176421352751253100240460ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // File: ossim-viirs-proc // // Description: Application to extract VIIRS Radiance layer, shifting // min/max linearly to 16 bit space with coarse grid geometry file. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char* argv[]) { int status = 0; // Timer for elapsed time: ossimTimer::instance()->setStartTick(); ossimInit::instance()->initialize(argc, argv); if (argc == 2 ) { ossimFilename inputFile = argv[1]; if ( inputFile.exists() ) { ossimFilename outputFile = inputFile.expand().noExtension(); outputFile.string() += "_1.tif"; if ( inputFile != outputFile ) { std::string command = "ossim-cmm --null -9999.0 --reader-prop layer=/All_Data/VIIRS-DNB-SDR_All/Radiance "; command += inputFile.string(); cout << "Executing command: " << command << endl; status = system( command.c_str() ); if ( status == 0 ) { ossimRefPtr sic = new ossimSingleImageChain(); if ( sic->open( inputFile, false ) ) { cout << "Opened: " << inputFile << endl; // Set the entry to the Radiance layer. ossimRefPtr readerProp = new ossimStringProperty( ossimString("layer"), ossimString("/All_Data/VIIRS-DNB-SDR_All/Radiance") ); sic->getImageHandler()->setProperty( readerProp ); // Add filter to shift/stretch data uint16 range. ossimRefPtr sf = new ossimShiftFilter(); sf->setNullPixelValue( 0.0 ); sf->setMinPixelValue( 1.0 ); sf->setMaxPixelValue( 65535.0 ); sic->addFirst( sf.get() ); // Cast it to uint16: ossimRefPtr cf = new ossimCastTileSourceFilter(0, OSSIM_UINT16 ); sic->addFirst( cf.get() ); // Put a cache in front of resampler. sic->addCache(); // sic->addResampler(); sic->initialize(); // Write image: ossimRefPtr writer = new ossimTiffWriter(); if ( writer->open( outputFile ) ) { // Turn on overviews and histograms: writer->setWriteOverviewFlag( true ); writer->setWriteHistogramFlag( true ); // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); writer->connectMyInputTo(0, sic.get()); ossimIrect rect = writer->getAreaOfInterest(); writer->execute(); cout << "Wrote file: " << outputFile << endl; ossimRefPtr ih = sic->getImageHandler(); if ( ih.valid() ) { //--- // If there is a coarse grid model write it out so the // oqutput file will pick it up. //--- ossimRefPtr geom = sic->getImageHandler()-> getImageGeometry(); if ( geom.valid() ) { ossimRefPtr proj = geom->getProjection(); if ( proj.valid() ) { ossimFilename geomFile = outputFile.noExtension(); geomFile.string() += ".geom"; ossimRefPtr cg = dynamic_cast( proj.get() ); if ( cg.valid() ) { // this saves geom file as well cg->saveCoarseGrid( geomFile ); cout << "Wrote file: " << geomFile << endl; } else { // Save the state to keyword list. ossimKeywordlist geomKwl; geom->saveState(geomKwl); // Write to file: geomKwl.write( geomFile.c_str() ); cout << "Wrote file: " << geomFile << endl; } } } //--- // If the image handler is a metadata interface pass the metadata // to the dot.omd file and rewrite it. //--- ossimMetadataInterface* mdi = dynamic_cast( ih.get() ); if ( mdi ) { ossimFilename omdFile = outputFile.noExtension(); omdFile += ".omd"; ossimRefPtr kwl = new ossimKeywordlist(); if ( omdFile.exists() ) { kwl->addFile( omdFile ); } std::string prefix = ""; mdi->addMetadata( kwl.get(), prefix ); kwl->write( omdFile.c_str() ); cout << "Wrote file: " << omdFile << endl; } } } else { cerr << "Could not open: " << outputFile << endl; } } } } else // Matches: { cerr << "Input file is same as output file! Returning..." << endl; status = -1; } } else // Match: if ( inputFile.exists() ){ ... } { cerr << "Input file does not exists!" << endl; status = -1; } } else // Matches: if (argc == 2 ){ ... } { cout << argv[0] << " " << "\n\nExtracts VIIRS Radiance layer from hdf5 file, shifting min/max " << "linearly to 16 bit space with coarse grid geometry file.\n" << endl; } cout << "Elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; return status; } ossim-Miami-2.9.1/apps/ossim-ws-cmp/000077500000000000000000000000001352751253100172145ustar00rootroot00000000000000ossim-Miami-2.9.1/apps/ossim-ws-cmp/CMakeLists.txt000066400000000000000000000003201352751253100217470ustar00rootroot00000000000000FILE(GLOB SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp") OSSIM_SETUP_APPLICATION(ossim-ws-cmp INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ${SOURCE_FILES}) ossim-Miami-2.9.1/apps/ossim-ws-cmp/ossim-ws-cmp.cpp000077500000000000000000000135551352751253100222720ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Application to compare to workspaces. // // $Id: foo.cpp 14815 2009-07-01 14:59:11Z gpotts $ //---------------------------------------------------------------------------- #include /* for system command */ #include #include #include #include #include using namespace std; static bool trace = false; // Turn on to see more stuff... static void cmpDir(const ossimFilename& wsa, const ossimFilename& wsb, const ossimFilename& dir); static void cmpFile(const ossimFilename& wsa, const ossimFilename& wsb, const ossimFilename& file); static bool isIgnoredFile(const ossimFilename& file); static void usage() { cout << "Usage: ossim-ws-cmp \n" << "Compares workspace a (wsa) to workspace b (wsb).\n" << "NOTE: requires \"diff\" command." << endl; } int main(int argc, char *argv[]) { if (argc != 3) { usage(); return 0; } ossimFilename wsa = argv[1]; ossimFilename wsb = argv[2]; if ( !wsa.isDir() ) { cout << " is NOT a directory: " << wsa << endl; usage(); return 0; } if ( !wsb.isDir() ) { cout << " is NOT a directory: " << wsb << endl; usage(); return 0; } cout << "wsa: " << wsa << "\nwsb: " << wsb << endl; cmpDir(wsa, wsb, wsa); return 0; } void cmpDir(const ossimFilename& wsa, const ossimFilename& wsb, const ossimFilename& dir) { ossimDirectory d; if ( d.open(dir) ) { ossimFilename f; if (d.getFirst(f)) { while ( f != "" ) { // cout << f << endl; if ( isIgnoredFile(f) == false ) { if ( f.isDir() ) { cmpDir(wsa, wsb, f); } else { cmpFile(wsa, wsb, f); } } d.getNext(f); } } } else { cout << "Could not open: " << wsa << endl; } } void cmpFile(const ossimFilename& wsa, const ossimFilename& wsb, const ossimFilename& file) { ossimFilename bFile = file.substitute(wsa, wsb); if ( !file.exists() ) { cout << "\nnotice: wsb file: " << bFile << "\nnotice: wsa file does not exists: " << file << "\nb -> a copy command:" << "\ncp " << bFile << " " << file << "\n" << endl; } if ( !bFile.exists() ) { cout << "\nnotice: wsa file: " << file << "\nnotice: wsb file does not exists: " << bFile << "\na -> b copy command:" << "\ncp " << file << " " << bFile << "\n" << endl; } if ( file.exists() && bFile.exists() ) { std::string command = "diff -w --ignore-matching-lines=\\$Id "; command += file.string(); command += " "; command += bFile.string(); int status = system( command.c_str() ); if ( status != 0 ) { cout << "\nnotice files differ:" << "\nwsa file: " << file << "\nwsb file: " << bFile << "\na -> b copy command:" << "\ncp " << file << " " << bFile << "\nb -> a copy command:" << "\ncp " << bFile << " " << file << "\n" << endl; } } } bool isIgnoredFile(const ossimFilename& file) { bool status = false; if (trace) { cout << "file: " << file << endl; } if ( file.size() ) { ossimFilename f = file.file(); ossimFilename e = file.ext(); if ( ( f == ".git" ) || ( f == ".moc" ) || ( f == ".svn" ) || ( f == "CMakeCache.txt" ) || ( f == "CMakeFiles" ) || ( f == "cmake_install.cmake" ) || ( f == "cmake_uninstall.cmake" ) || ( f == "CVS" ) || ( f == "doc" ) || ( f == ".cvsignore" ) || ( f == "bin" ) || ( f == "build" ) || ( f == "builds" ) || ( f == "configure") || ( f == "config.log" ) || ( f == "config.status") || ( f == "lib" ) || ( f == "Makefile" ) || ( f == "Makefile.common" ) || ( f == "make.out" ) || ( f == "projects") || ( f == "wxmac.icns") || ( f == "xcode" ) || ( e == "d" ) || // dot d file ( e == "o" ) || // object file ( e == "obj" ) || ( e == "exe" ) || ( e == "tmp" ) ) { status = true; } else if ( file.contains("apps") || file.contains("test") ) { if ( file.isDir() ) // Go into apps and test dir. { status = false; } else if ( (e != "h") && (e != "cpp") ) { // Ignore binary files. Only diff headers and source files. status = true; } } if ( file[file.size()-1] == '~' ) { status = true; // xemacs } } // if ( file.size() ) else { status = true; // empty } if ( trace && (status == true) ) { cout << "ignoring file: " << file << endl; } return status; } ossim-Miami-2.9.1/cmake/000077500000000000000000000000001352751253100147735ustar00rootroot00000000000000ossim-Miami-2.9.1/cmake/CMakeLists.txt000066400000000000000000000451111352751253100175350ustar00rootroot00000000000000PROJECT(ossimlabs) # Allows developer to customize compiler with their own flags (e.g., "-std=c++11") SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} $ENV{OSSIM_CXX_FLAGS}" ) IF ("${OSSIM_DEV_HOME}" STREQUAL "") IF ("$ENV{OSSIM_DEV_HOME}" STREQUAL "") SET(OSSIM_DEV_HOME "${CMAKE_CURRENT_SOURCE_DIR}/../.." CACHE STRING "Cache the OSSIM dev home" FORCE) ELSE() SET(OSSIM_DEV_HOME "$ENV{OSSIM_DEV_HOME}" CACHE STRING "Cache the OSSIM dev home" FORCE) ENDIF() ENDIF() if(EXISTS ${CMAKE_TOOLCHAIN_FILE}) MESSAGE("Using toolchain file ${CMAKE_TOOLCHAIN_FILE}") ENDIF() if(NOT EXISTS ${OSSIM_DEV_HOME}) MESSAGE(FATAL_ERROR "Please pass in or define a valid OSSIM_DEV_HOME root path where all modules are located. This includes ossim, ossim-planet, ... etc.") ENDIF() IF ("$ENV{OSSIM_INSTALL_PREFIX}" STREQUAL "") IF (EXISTS "$ENV{OSSIM_BUILD_DIR}") SET(OSSIM_INSTALL_PREFIX "$ENV{OSSIM_BUILD_DIR}" CACHE STRING "Cache the OSSIM install prefix" FORCE) ELSE() SET(OSSIM_INSTALL_PREFIX "${OSSIM_DEV_HOME}/install" CACHE STRING "Cache the OSSIM install prefix" FORCE) ENDIF() ELSE() SET(OSSIM_INSTALL_PREFIX "$ENV{OSSIM_INSTALL_PREFIX}" CACHE STRING "Cache the OSSIM install prefix" FORCE) ENDIF() IF(NOT OSSIM_BUILD_ADDITIONAL_DIRECTORIES) SET(OSSIM_BUILD_ADDITIONAL_DIRECTORIES "" CACHE PATH "Specify full paths separated by ; to additional libraries you wish to include into the ossim build framework" FORCE) ENDIF(NOT OSSIM_BUILD_ADDITIONAL_DIRECTORIES) SET(CMAKE_MODULE_PATH "${OSSIM_DEV_HOME}/ossim/cmake/CMakeModules") INCLUDE(OssimVersion) INCLUDE(OssimUtilities) INCLUDE(OssimCommonVariables) FILE(REMOVE ${CMAKE_INCLUDE_DIRS_FILE}) FILE(REMOVE ${CMAKE_FILENAMES_FILE}) IF(NOT APPLE) cmake_minimum_required(VERSION 2.6) ELSE(NOT APPLE) cmake_minimum_required(VERSION 2.8) ENDIF(NOT APPLE) IF(EXISTS "$ENV{OSSIM_DEPENDENCIES}") SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} ${OSSIM_DEPENDENCIES}/include ) SET(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} ${OSSIM_DEPENDENCIES}/lib${LIBSUFFIX}) SET(CMAKE_FRAMEWORK_PATH "${CMAKE_FRAMEWORK_PATH};$ENV{OSSIM_DEPENDENCIES}/Frameworks") ENDIF(EXISTS "$ENV{OSSIM_DEPENDENCIES}") SET(CMAKE_INSTALL_PREFIX ${OSSIM_INSTALL_PREFIX}) MESSAGE( STATUS "\n========================== CMAKE FINAL SETTINGS ==========================" ) MESSAGE( STATUS "CMAKE_MODULE_PATH = ${CMAKE_MODULE_PATH}") MESSAGE( STATUS "CMAKE_IGNORE_PATH = ${CMAKE_IGNORE_PATH}") MESSAGE( STATUS "CMAKE_INCLUDE_PATH = ${CMAKE_INCLUDE_PATH}") MESSAGE( STATUS "CMAKE_LIBRARY_PATH = ${CMAKE_LIBRARY_PATH}") MESSAGE( STATUS "CMAKE_PREFIX_PATH = ${CMAKE_PREFIX_PATH}") MESSAGE( STATUS "CMAKE_INSTALL_PREFIX = ${CMAKE_INSTALL_PREFIX}") MESSAGE( STATUS "CMAKE_FRAMEWORK_PATH = ${CMAKE_FRAMEWORK_PATH}") MESSAGE( STATUS "CMAKE_FIND_ROOT_PATH = ${CMAKE_FIND_ROOT_PATH}") MESSAGE( STATUS "CMAKE_FIND_LIBRARY_PREFIXES = ${CMAKE_FIND_LIBRARY_PREFIXES}") MESSAGE( STATUS "CMAKE_FIND_LIBRARY_SUFFIXES = ${CMAKE_FIND_LIBRARY_SUFFIXES}") MESSAGE( STATUS "CMAKE_SYSTEM_IGNORE_PATH = ${CMAKE_SYSTEM_IGNORE_PATH}") MESSAGE( STATUS "CMAKE_SYSTEM_INCLUDE_PATH = ${CMAKE_SYSTEM_INCLUDE_PATH}") MESSAGE( STATUS "CMAKE_SYSTEM_LIBRARY_PATH = ${CMAKE_SYSTEM_LIBRARY_PATH}") MESSAGE( STATUS "CMAKE_SYSTEM_PREFIX_PATH = ${CMAKE_SYSTEM_PREFIX_PATH}") MESSAGE( STATUS "CMAKE_SYSTEM_IGNORE_PATH = ${CMAKE_SYSTEM_IGNORE_PATH}") MESSAGE( STATUS "CMAKE_TOOLCHAIN_FILE = ${CMAKE_TOOLCHAIN_FILE}") MESSAGE( STATUS "\n" ) ####################################################################################################### # Initialize the libraries to be the cmake targets and initialize the includes to the proper dev paths ####################################################################################################### IF(NOT OSSIM_LIBRARY) SET(OSSIM_LIBRARY "ossim" CACHE STRING "Caching" FORCE) ENDIF(NOT OSSIM_LIBRARY) IF(NOT OSSIM_HOME) SET(OSSIM_HOME "${OSSIM_DEV_HOME}/ossim" CACHE STRING "Caching" FORCE) ENDIF(NOT OSSIM_HOME) IF(NOT OSSIM_INCLUDE_DIR) SET(OSSIM_INCLUDE_DIR "${OSSIM_HOME}/include" CACHE STRING "Caching" FORCE) ENDIF(NOT OSSIM_INCLUDE_DIR) #IF(NOT OSSIMPLANETQT_LIBRARY) # SET(OSSIMPLANETQT_LIBRARY "ossimPlanetQt" CACHE STRING "Caching" FORCE) #ENDIF(NOT OSSIMPLANETQT_LIBRARY) #IF(NOT OSSIMPLANETQT_INCLUDE_DIR) # SET(OSSIMPLANETQT_INCLUDE_DIR "${OSSIM_DEV_HOME}/ossimPlanetQt/include" CACHE STRING "Caching" FORCE) #ENDIF(NOT OSSIMPLANETQT_INCLUDE_DIR) #IF(NOT OSSIMQT_LIBRARY) # SET(OSSIMQT_LIBRARY "ossimQt" CACHE STRING "Caching" FORCE) #ENDIF(NOT OSSIMQT_LIBRARY) ############################### Add subdirectories to build based on BUILD variables and presence of repo ########################### add_subdirectory(${OSSIM_HOME} ${CMAKE_CURRENT_BINARY_DIR}/ossim) IF(BUILD_OSSIM_WMS AND EXISTS ${OSSIM_DEV_HOME}/ossim-wms ) IF(NOT OSSIMWMS_LIBRARY) SET(OSSIMWMS_LIBRARY "ossim-wms" CACHE STRING "Caching" FORCE) ENDIF(NOT OSSIMWMS_LIBRARY) IF(NOT OSSIMWMS_INCLUDE_DIR) SET(OSSIMWMS_INCLUDE_DIR "${OSSIM_DEV_HOME}/ossim-wms/include" CACHE STRING "Caching" FORCE) ENDIF(NOT OSSIMWMS_INCLUDE_DIR) add_subdirectory(${OSSIM_DEV_HOME}/ossim-wms ${CMAKE_CURRENT_BINARY_DIR}/ossim-wms) ENDIF() IF(BUILD_OSSIM_VIDEO AND EXISTS ${OSSIM_DEV_HOME}/ossim-video) IF(NOT OSSIMVIDEO_LIBRARY) SET(OSSIMVIDEO_LIBRARY "ossim-video" CACHE STRING "Caching" FORCE) ENDIF() IF(NOT OSSIMVIDEO_INCLUDE_DIR) SET(OSSIMVIDEO_INCLUDE_DIR "${OSSIM_DEV_HOME}/ossim-video/include" CACHE STRING "Caching" FORCE) ENDIF() add_subdirectory(${OSSIM_DEV_HOME}/ossim-video ${CMAKE_CURRENT_BINARY_DIR}/ossim-video) ENDIF() IF(BUILD_MSP_PLUGIN AND EXISTS ${OSSIM_DEV_HOME}/ossim-msp-plugin) add_subdirectory(${OSSIM_DEV_HOME}/ossim-msp-plugin ${CMAKE_CURRENT_BINARY_DIR}/ossim-msp-plugin) ENDIF() IF(BUILD_CSM_PLUGIN AND EXISTS ${OSSIM_DEV_HOME}/ossim-csm-plugin) add_subdirectory(${OSSIM_DEV_HOME}/ossim-csm-plugin ${CMAKE_CURRENT_BINARY_DIR}/ossim-csm-plugin) ENDIF() IF(BUILD_OMS AND EXISTS ${OSSIM_DEV_HOME}/ossim-oms) IF(NOT OMS_LIBRARY) SET(OMS_LIBRARY "ossim-oms" CACHE STRING "Caching" FORCE) ENDIF(NOT OMS_LIBRARY) IF(NOT OMS_INCLUDE_DIR) SET(OMS_INCLUDE_DIR "${OSSIM_DEV_HOME}/ossim-oms/coms/include" CACHE STRING "Caching" FORCE) ENDIF(NOT OMS_INCLUDE_DIR) add_subdirectory(${OSSIM_DEV_HOME}/ossim-oms ${CMAKE_CURRENT_BINARY_DIR}/ossim-oms) ENDIF() IF(BUILD_OSSIM_PLANET AND EXISTS ${OSSIM_DEV_HOME}/ossim-planet) IF(NOT OSSIMPLANET_LIBRARY) SET(OSSIMPLANET_LIBRARY "ossim-planet" CACHE STRING "Caching" FORCE) ENDIF(NOT OSSIMPLANET_LIBRARY) IF(NOT OSSIMPLANET_INCLUDE_DIR) SET(OSSIMPLANET_INCLUDE_DIR "${OSSIM_DEV_HOME}/ossim-planet/include" CACHE STRING "Caching" FORCE) ENDIF(NOT OSSIMPLANET_INCLUDE_DIR) add_subdirectory(${OSSIM_DEV_HOME}/ossim-planet ${CMAKE_CURRENT_BINARY_DIR}/ossim-planet) ENDIF() IF(BUILD_OSSIM_PLANET_GUI AND EXISTS ${OSSIM_DEV_HOME}/ossim-planet-gui) IF(NOT OSSIMPLANETGUI_LIBRARY) SET(OSSIMPLANETGUI_LIBRARY "ossim-planet-gui" CACHE STRING "Caching" FORCE) ENDIF(NOT OSSIMPLANETGUI_LIBRARY) IF(NOT OSSIMPLANETGUI_INCLUDE_DIR) SET(OSSIMPLANETGUI_INCLUDE_DIR "${OSSIM_DEV_HOME}/ossim-planet-gui/include" CACHE STRING "Caching" FORCE) ENDIF(NOT OSSIMPLANETGUI_INCLUDE_DIR) add_subdirectory(${OSSIM_DEV_HOME}/ossim-planet-gui ${CMAKE_CURRENT_BINARY_DIR}/ossim-planet-gui) ENDIF() IF(BUILD_OSSIM_GUI AND EXISTS ${OSSIM_DEV_HOME}/ossim-gui) add_subdirectory(${OSSIM_DEV_HOME}/ossim-gui ${CMAKE_CURRENT_BINARY_DIR}/ossim-gui) ENDIF() IF(BUILD_OSSIM_QT4 AND EXISTS ${OSSIM_DEV_HOME}/ossim-qt4) add_subdirectory(${OSSIM_DEV_HOME}/ossim-qt4 ${CMAKE_CURRENT_BINARY_DIR}/ossim-qt4) ENDIF() IF(EXISTS ${OSSIM_DEV_HOME}/ossim-plugins) add_subdirectory(${OSSIM_DEV_HOME}/ossim-plugins ${CMAKE_CURRENT_BINARY_DIR}/ossim-plugins) ENDIF() IF(OSSIM_BUILD_ADDITIONAL_DIRECTORIES) FOREACH(it IN LISTS OSSIM_BUILD_ADDITIONAL_DIRECTORIES) MESSAGE(STATUS "**********************Adding additional subdirectory ${it}*************************") SUBDIRS(${it}) ENDFOREACH(it) ENDIF() IF(BUILD_DSMG AND EXISTS ${OSSIM_DEV_HOME}/ossim-dsmg) add_subdirectory(${OSSIM_DEV_HOME}/ossim-dsmg ${CMAKE_CURRENT_BINARY_DIR}/ossim-dsmg) ENDIF() IF(BUILD_OSSIM_ISA AND EXISTS ${OSSIM_DEV_HOME}/ossim-isa) add_subdirectory(${OSSIM_DEV_HOME}/ossim-isa ${CMAKE_CURRENT_BINARY_DIR}/ossim-isa) ENDIF() IF(BUILD_OSSIM_FPGA AND EXISTS ${OSSIM_DEV_HOME}/ossim-fpga) add_subdirectory(${OSSIM_DEV_HOME}/ossim-fpga ${CMAKE_CURRENT_BINARY_DIR}/ossim-fpga) ENDIF() ############################## Doxygen installation for current ossim core module ########################################### FIND_PACKAGE(Doxygen) MACRO(OSSIM_GENERATE_DOXYGEN DOXYGEN_OUTPUT_DIRECTORY CONFIGURE_FILE WORKING_DIRECTORY DOXYGEN_INPUT BASE_TARGET_NAME CLASS_PREFIX_TO_IGNORE) SET(DOXYGEN_IGNORE_PREFIX "${CLASS_PREFIX_TO_IGNORE}") IF(NOT EXISTS "${DOXYGEN_OUTPUT_DIRECTORY}") make_directory("${DOXYGEN_OUTPUT_DIRECTORY}") ENDIF() CONFIGURE_FILE("${CONFIGURE_FILE}" "${DOXYGEN_INPUT}" @ONLY IMMEIDATE) ADD_CUSTOM_COMMAND( OUTPUT ${DOXYGEN_OUTPUT_DIRECTORY} COMMAND ${CMAKE_COMMAND} -E echo_append "Building API Documentation..." COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_INPUT} COMMAND ${CMAKE_COMMAND} -E echo "Done." WORKING_DIRECTORY ${WORKING_DIRECTORY} DEPENDS ${DOXYGEN_INPUT} ) ADD_CUSTOM_TARGET(${BASE_TARGET_NAME}-doc ALL DEPENDS ${DOXYGEN_OUTPUT_DIRECTORY}) ADD_CUSTOM_TARGET(${BASE_TARGET_NAME}-doc-forced COMMAND ${CMAKE_COMMAND} -E echo_append "Building API Documentation..." COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_INPUT} COMMAND ${CMAKE_COMMAND} -E echo "Done." WORKING_DIRECTORY "${WORKING_DIRECTORY}") ENDMACRO(OSSIM_GENERATE_DOXYGEN) IF (DOXYGEN_FOUND) OPTION(OSSIM_BUILD_DOXYGEN "Set to ON to generate oxygen documentation files" OFF) IF(OSSIM_BUILD_DOXYGEN) SET(DOXYGEN_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/doc/ossim-${OSSIM_VERSION}/ossimApi") OSSIM_GENERATE_DOXYGEN("${DOXYGEN_OUTPUT_DIRECTORY}" "${OSSIM_DEV_HOME}/ossim/doc/Doxyfile.in" "${OSSIM_DEV_HOME}/ossim/doc" "${CMAKE_BINARY_DIR}/OssimDoxyfile" "ossim-api" "ossim") FILE(GLOB ossim_docs "${DOXYGEN_OUTPUT_DIRECTORY}/html/*") INSTALL(FILES ${ossim_docs} DESTINATION "share/ossim/${OSSIM_VERSION}/docs/doxygen/ossimapi/html" COMPONENT ossim-doc) IF(BUILD_OSSIM_PLANET) SET(DOXYGEN_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/doc/ossim-${OSSIM_VERSION}/ossimPlanetApi") OSSIM_GENERATE_DOXYGEN("${DOXYGEN_OUTPUT_DIRECTORY}" "${OSSIM_DEV_HOME}/ossim/Doxyfile.in" "${OSSIM_DEV_HOME}/ossim-planet" "${CMAKE_BINARY_DIR}/OssimPlanetDoxyfile" "ossimPlanet-api" "ossimPlanet") FILE(GLOB ossim_docs "${DOXYGEN_OUTPUT_DIRECTORY}/html/*") INSTALL(FILES ${ossim_docs} DESTINATION "share/ossim/${OSSIM_VERSION}/docs/doxygen/ossimPlanetApi/html" COMPONENT ossim-doc) ENDIF(BUILD_OSSIM_PLANET) ENDIF(OSSIM_BUILD_DOXYGEN) ENDIF (DOXYGEN_FOUND) ############################## Setup shared file installation ############################## if(EXISTS ${OSSIM_HOME}/share/ossim/geoids/egm96.grd) INSTALL(FILES ${OSSIM_HOME}/share/ossim/geoids/egm96.grd DESTINATION "share/ossim/geoids" COMPONENT ossim) ELSE() MESSAGE(WARNING "File ${OSSIM_HOME}/share/ossim/geoids/egm96.grd not found for install!") ENDIF() # Fonts removed for rpms # INSTALL(FILES ${OSSIM_DEV_HOME}/ossim_package_support/fonts/arial.ttf DESTINATION "share/ossim/fonts" COMPONENT ossim) # INSTALL(FILES ${OSSIM_DEV_HOME}/ossim_package_support/fonts/times.ttf DESTINATION "share/ossim/fonts" COMPONENT ossim) FILE(GLOB ossim_cmake_modules ${OSSIM_DEV_HOME}/ossim/cmake/CMakeModules/*.cmake* ) INSTALL(FILES ${ossim_cmake_modules} DESTINATION share/ossim/CMakeModules COMPONENT ossim) FILE(GLOB projection_files "${OSSIM_HOME}/share/ossim/projection/*.csv" "${OSSIM_HOME}/share/ossim/projection/*.txt") INSTALL(FILES ${projection_files} DESTINATION share/ossim/projection COMPONENT ossim) INSTALL(FILES ${OSSIM_HOME}/share/ossim/templates/ossim_preferences_template DESTINATION "share/ossim" COMPONENT ossim RENAME ossim-preferences-template) ############################## Setup the packages ############################## # present the packaging option only if we have the cpack command defined (effectively >= 2.6.0) IF(CMAKE_CPACK_COMMAND) OPTION(BUILD_OSSIM_PACKAGES "Set to ON to generate CPack configuration files and packaging targets" OFF) IF(BUILD_OSSIM_PACKAGES) INCLUDE(OssimCPack) ENDIF() ENDIF() set(PKGCONFIG_FILES ossim) foreach(PKGCONFIG_FILE ${PKGCONFIG_FILES}) configure_file(${OSSIM_DEV_HOME}/ossim/cmake/packaging/pkgconfig/${PKGCONFIG_FILE}.pc.in ${${PROJECT_NAME}_BINARY_DIR}/packaging/pkgconfig/${PKGCONFIG_FILE}.pc @ONLY ) INSTALL(FILES ${${PROJECT_NAME}_BINARY_DIR}/packaging/pkgconfig/${PKGCONFIG_FILE}.pc DESTINATION lib${LIBSUFFIX}/pkgconfig COMPONENT ossim) ENDFOREACH(PKGCONFIG_FILE) ##################################################################################################### # We may want to add this as a build step instead so it can capture different output directories # Will comment out for now until I figure this out. This is used to symlink the pre built frameworks to the build # dir so you can run things within Xcode # ##################################################################################################### #IF(APPLE) # IF(MAKE_APPENDS_BUILD_TYPE) # IF(OSSIM_DEPENDENCIES) # IF(NOT EXISTS ${CMAKE_BINARY_DIR}/${CMAKE_BUILD_TYPE}/OpenThreads.framework AND EXISTS ${OSSIM_DEPENDENCIES}/Frameworks) # FILE(GLOB framework_files "${OSSIM_DEPENDENCIES}/Frameworks/*.framework") # foreach(x ${framework_files}) # execute_process(COMMAND ln -s ${x} . # WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_BUILD_TYPE}/) # endforeach(x) # ENDIF() # ENDIF() # ENDIF() #ENDIF() ############################ setup common INSTALL support files ############################################# # SET(CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS "YES") include(InstallRequiredSystemLibraries) ################################### SETUP Uninstall TARGETS #################################################### OSSIM_ADD_COMMON_MAKE_UNINSTALL() MESSAGE( STATUS "PROJECT_NAME = ${PROJECT_NAME}" ) MESSAGE( STATUS "OSSIM_DEV_HOME = ${OSSIM_DEV_HOME}" ) MESSAGE( STATUS "OSSIM_INSTALL_PREFIX = ${OSSIM_INSTALL_PREFIX}" ) MESSAGE( STATUS "OSSIM_DEPENDENCIES = ${OSSIM_DEPENDENCIES}" ) MESSAGE( STATUS "CMAKE_CURRENT_BINARY_DIR = ${CMAKE_CURRENT_BINARY_DIR}" ) MESSAGE( STATUS "CMAKE_CURRENT_SOURCE_DIR = ${CMAKE_CURRENT_SOURCE_DIR}" ) MESSAGE( STATUS "CMAKE_MODULE_PATH = ${CMAKE_MODULE_PATH}" ) MESSAGE( STATUS "CMAKE_BUILD_TYPE = ${CMAKE_BUILD_TYPE}" ) MESSAGE( STATUS "CMAKE_C_COMPILER = ${CMAKE_C_COMPILER}" ) MESSAGE( STATUS "CMAKE_CXX_COMPILER = ${CMAKE_CXX_COMPILER}" ) MESSAGE( STATUS "CMAKE_CXX_FLAGS = ${CMAKE_CXX_FLAGS}" ) MESSAGE( STATUS "CMAKE_CXX_FLAGS_DEBUG = ${CMAKE_CXX_FLAGS_DEBUG}" ) MESSAGE( STATUS "CMAKE_CXX_FLAGS_RELEASE = ${CMAKE_CXX_FLAGS_RELEASE}" ) MESSAGE( STATUS "CMAKE_CXX_DEFINES_DEBUG = ${CXX_DEFINES}" ) MESSAGE( STATUS "CMAKE_CXX_DEFINES_RELEASE = ${CMAKE_CXX_DEFINES}" ) MESSAGE( STATUS "CMAKE_DEBUG_POSTFIX = ${CMAKE_DEBUG_POSTFIX}" ) MESSAGE( STATUS "CMAKE_INCLUDE_PATH = ${CMAKE_INCLUDE_PATH}" ) MESSAGE( STATUS "CMAKE_INSTALL_PREFIX = ${CMAKE_INSTALL_PREFIX}" ) MESSAGE( STATUS "CMAKE_SHARED_LINKER_FLAGS = ${CMAKE_SHARED_LINKER_FLAGS}" ) MESSAGE( STATUS "CMAKE_EXE_LINKER_FLAGS = ${CMAKE_EXE_LINKER_FLAGS}" ) MESSAGE( STATUS "COMPILE_DEFINITIONS_DEBUG = ${COMPILE_DEFINITIONS_DEBUG}" ) MESSAGE( STATUS "COMPILE_DEFINITIONS_RELEASE = ${COMPILE_DEFINITIONS_RELEASE}" ) MESSAGE( STATUS "KAKADU_ROOT_SRC = ${KAKADU_ROOT_SRC}") MESSAGE( STATUS "KAKADU_AUX_LIBRARY = ${KAKADU_AUX_LIBRARY}") MESSAGE( STATUS "KAKADU_LIBRARY = ${KAKADU_LIBRARY}") MESSAGE( STATUS "MPI_LIBRARY = ${MPI_LIBRARIES}" ) MESSAGE( STATUS "MPI_INCLUDE = ${MPI_INCLUDE_PATH}" ) MESSAGE( STATUS "OPENTHREADS_LIBRARY = ${OPENTHREADS_LIBRARY}" ) MESSAGE( STATUS "OPENTHREADS_INCLUDE = ${OPENTHREADS_INCLUDE_DIR}" ) MESSAGE( STATUS "OSSIM_COMPILE_WITH_FULL_WARNING = ${OSSIM_COMPILE_WITH_FULL_WARNING}" ) MESSAGE( STATUS "OSSIM_COMMON_COMPILER_FLAGS = ${OSSIM_COMMON_COMPILER_FLAGS}" ) MESSAGE( STATUS "OSSIM_LIBRARY = ${OSSIM_LIBRARY}" ) MESSAGE( STATUS "OSSIM_INCLUDE_DIR = ${OSSIM_INCLUDE_DIR}" ) MESSAGE( STATUS "TIFF_LIBRARY = ${TIFF_LIBRARIES}" ) MESSAGE( STATUS "TIFF_INCLUDE = ${TIFF_INCLUDE_DIR}" ) MESSAGE( STATUS "ZLIB_LIBRARY = ${ZLIB_LIBRARIES}" ) MESSAGE( STATUS "ZLIB_INCLUDE = ${ZLIB_INCLUDE_DIR}" ) MESSAGE( STATUS "BUILD_OMS = ${BUILD_OMS}" ) MESSAGE( STATUS "BUILD_OSSIM = ${BUILD_OSSIM}" ) MESSAGE( STATUS "BUILD_OSSIM_FREETYPE_SUPPORT = ${BUILD_OSSIM_FREETYPE_SUPPORT}" ) MESSAGE( STATUS "BUILD_OSSIM_GUI = ${BUILD_OSSIM_GUI}" ) MESSAGE( STATUS "BUILD_OSSIMJNI = ${BUILD_OSSIMJNI}" ) MESSAGE( STATUS "BUILD_OSSIM_QT4 = ${BUILD_OSSIM_QT4}" ) MESSAGE( STATUS "BUILD_OSSIM_MPI_SUPPORT = ${BUILD_OSSIM_MPI_SUPPORT}" ) MESSAGE( STATUS "BUILD_OSSIM_PLANET = ${BUILD_OSSIM_PLANET}" ) MESSAGE( STATUS "BUILD_OSSIMPLANETQT = ${BUILD_OSSIMPLANETQT}" ) MESSAGE( STATUS "BUILD_OSSIM_VIDEO = ${BUILD_OSSIM_VIDEO}" ) MESSAGE( STATUS "BUILD_OSSIM_WMS = ${BUILD_OSSIM_WMS}" ) MESSAGE( STATUS "BUILD_LIBRARY_DIR = ${BUILD_LIBRARY_DIR}" ) MESSAGE( STATUS "BUILD_RUNTIME_DIR = ${BUILD_RUNTIME_DIR}" ) MESSAGE( STATUS "BUILD_DSMG = ${BUILD_DSMG}" ) MESSAGE( STATUS "BUILD_MSP_PLUGIN = ${BUILD_MSP_PLUGIN}" ) MESSAGE( STATUS "BUILD_CSM_PLUGIN = ${BUILD_CSM_PLUGIN}" ) MESSAGE( STATUS "BUILD_OSSIM_FPGA = ${BUILD_OSSIM_FPGA}" ) MESSAGE( STATUS "Use OSSIM_BUILD_ADDITIONAL_DIRECTORIES to add other cmake builds." ) ossim-Miami-2.9.1/cmake/CMakeModules/000077500000000000000000000000001352751253100173045ustar00rootroot00000000000000ossim-Miami-2.9.1/cmake/CMakeModules/CMakeParseArguments.cmake000066400000000000000000000134541352751253100241560ustar00rootroot00000000000000#.rst: # CMakeParseArguments # ------------------- # # # # CMAKE_PARSE_ARGUMENTS( # args...) # # CMAKE_PARSE_ARGUMENTS() is intended to be used in macros or functions # for parsing the arguments given to that macro or function. It # processes the arguments and defines a set of variables which hold the # values of the respective options. # # The argument contains all options for the respective macro, # i.e. keywords which can be used when calling the macro without any # value following, like e.g. the OPTIONAL keyword of the install() # command. # # The argument contains all keywords for this macro # which are followed by one value, like e.g. DESTINATION keyword of the # install() command. # # The argument contains all keywords for this # macro which can be followed by more than one value, like e.g. the # TARGETS or FILES keywords of the install() command. # # When done, CMAKE_PARSE_ARGUMENTS() will have defined for each of the # keywords listed in , and # a variable composed of the given # followed by "_" and the name of the respective keyword. These # variables will then hold the respective value from the argument list. # For the keywords this will be TRUE or FALSE. # # All remaining arguments are collected in a variable # _UNPARSED_ARGUMENTS, this can be checked afterwards to see # whether your macro was called with unrecognized parameters. # # As an example here a my_install() macro, which takes similar arguments # as the real install() command: # # :: # # function(MY_INSTALL) # set(options OPTIONAL FAST) # set(oneValueArgs DESTINATION RENAME) # set(multiValueArgs TARGETS CONFIGURATIONS) # cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}" # "${multiValueArgs}" ${ARGN} ) # ... # # # # Assume my_install() has been called like this: # # :: # # my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub) # # # # After the cmake_parse_arguments() call the macro will have set the # following variables: # # :: # # MY_INSTALL_OPTIONAL = TRUE # MY_INSTALL_FAST = FALSE (this option was not used when calling my_install() # MY_INSTALL_DESTINATION = "bin" # MY_INSTALL_RENAME = "" (was not used) # MY_INSTALL_TARGETS = "foo;bar" # MY_INSTALL_CONFIGURATIONS = "" (was not used) # MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (no value expected after "OPTIONAL" # # # # You can then continue and process these variables. # # Keywords terminate lists of values, e.g. if directly after a # one_value_keyword another recognized keyword follows, this is # interpreted as the beginning of the new option. E.g. # my_install(TARGETS foo DESTINATION OPTIONAL) would result in # MY_INSTALL_DESTINATION set to "OPTIONAL", but MY_INSTALL_DESTINATION # would be empty and MY_INSTALL_OPTIONAL would be set to TRUE therefor. #============================================================================= # Copyright 2010 Alexander Neundorf # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) if(__CMAKE_PARSE_ARGUMENTS_INCLUDED) return() endif() set(__CMAKE_PARSE_ARGUMENTS_INCLUDED TRUE) function(CMAKE_PARSE_ARGUMENTS prefix _optionNames _singleArgNames _multiArgNames) # first set all result variables to empty/FALSE foreach(arg_name ${_singleArgNames} ${_multiArgNames}) set(${prefix}_${arg_name}) endforeach() foreach(option ${_optionNames}) set(${prefix}_${option} FALSE) endforeach() set(${prefix}_UNPARSED_ARGUMENTS) set(insideValues FALSE) set(currentArgName) # now iterate over all arguments and fill the result variables foreach(currentArg ${ARGN}) list(FIND _optionNames "${currentArg}" optionIndex) # ... then this marks the end of the arguments belonging to this keyword list(FIND _singleArgNames "${currentArg}" singleArgIndex) # ... then this marks the end of the arguments belonging to this keyword list(FIND _multiArgNames "${currentArg}" multiArgIndex) # ... then this marks the end of the arguments belonging to this keyword if(${optionIndex} EQUAL -1 AND ${singleArgIndex} EQUAL -1 AND ${multiArgIndex} EQUAL -1) if(insideValues) if("${insideValues}" STREQUAL "SINGLE") set(${prefix}_${currentArgName} ${currentArg}) set(insideValues FALSE) elseif("${insideValues}" STREQUAL "MULTI") list(APPEND ${prefix}_${currentArgName} ${currentArg}) endif() else() list(APPEND ${prefix}_UNPARSED_ARGUMENTS ${currentArg}) endif() else() if(NOT ${optionIndex} EQUAL -1) set(${prefix}_${currentArg} TRUE) set(insideValues FALSE) elseif(NOT ${singleArgIndex} EQUAL -1) set(currentArgName ${currentArg}) set(${prefix}_${currentArgName}) set(insideValues "SINGLE") elseif(NOT ${multiArgIndex} EQUAL -1) set(currentArgName ${currentArg}) set(${prefix}_${currentArgName}) set(insideValues "MULTI") endif() endif() endforeach() # propagate the result variables to the caller: foreach(arg_name ${_singleArgNames} ${_multiArgNames} ${_optionNames}) set(${prefix}_${arg_name} ${${prefix}_${arg_name}} PARENT_SCOPE) endforeach() set(${prefix}_UNPARSED_ARGUMENTS ${${prefix}_UNPARSED_ARGUMENTS} PARENT_SCOPE) endfunction() ossim-Miami-2.9.1/cmake/CMakeModules/FindAWS.cmake000066400000000000000000000044201352751253100215410ustar00rootroot00000000000000#--- # File: FindAWS.cmake # # Find the native AWS(Amazon Web Services) cpp sdk includes and libraries. # # This module defines: # # AWS_INCLUDE_DIR, where to find Aws.h and S3Client.h. # AWS_LIBRARIES, libraries to link against to use AWS. Currently there are # two looked for, aws-cpp-sdk-core and aws-cpp-sdk-s3 libraries. # AWS_FOUND, True if found, false if one of the above are not found. # # For ossim, typically geos will be system installed which should be found; # or found in the ossim 3rd party dependencies directory from a geos build # and install. If the latter it will rely on CMAKE_INCLUDE_PATH and # CMAKE_LIBRARY_PATH having the path to the party dependencies directory. # # NOTE: # This script is specialized for ossim. # # $Id$ #--- #--- # Find include path: #--- find_path( AWS_CORE_INCLUDE_DIR aws/core/Aws.h PATHS $ENV{AWS_DIR}/include ${AWS_DIR}/include) # We need this so check for it: find_path( AWS_S3_INCLUDE_DIR aws/s3/S3Client.h PATHS $ENV{AWS_DIR}/include ${AWS_DIR}/include) # Set the AWS_INCLUDE_DIR: if( AWS_CORE_INCLUDE_DIR AND AWS_S3_INCLUDE_DIR ) set( AWS_INCLUDE_DIR ${AWS_CORE_INCLUDE_DIR} CACHE STRING INTERNAL ) endif( AWS_CORE_INCLUDE_DIR AND AWS_S3_INCLUDE_DIR ) # Find AWS CPP SDK CORE library: find_library( AWS_CORE_LIB NAMES aws-cpp-sdk-core ) # Find AWS CPP SDK S3 library: find_library( AWS_S3_LIB NAMES aws-cpp-sdk-s3) # Set the AWS_LIBRARY: if( AWS_CORE_LIB AND AWS_S3_LIB ) set( AWS_LIBRARIES ${AWS_CORE_LIB} ${AWS_S3_LIB} CACHE STRING INTERNAL ) endif(AWS_CORE_LIB AND AWS_S3_LIB ) #--- # This function sets AWS_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( AWS DEFAULT_MSG AWS_LIBRARIES AWS_INCLUDE_DIR ) if( AWS_FOUND ) if( NOT AWS_FIND_QUIETLY ) message( STATUS "Found AWS..." ) endif( NOT AWS_FIND_QUIETLY ) else( AWS_FOUND ) if( NOT AWS_FIND_QUIETLY ) message( WARNING "Could not find AWS" ) endif( NOT AWS_FIND_QUIETLY ) endif( AWS_FOUND ) if( NOT AWS_FIND_QUIETLY ) message( STATUS "AWS_INCLUDE_DIR=${AWS_INCLUDE_DIR}" ) message( STATUS "AWS_LIBRARIES=${AWS_LIBRARIES}" ) endif( NOT AWS_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindCPPUNIT.cmake000066400000000000000000000032501352751253100222310ustar00rootroot00000000000000# - Find CPPUNIT # Find the native CPPUNIT includes and library # This module defines # CPPUNIT_INCLUDE_DIR, where to find jpeglib.h, etc. # CPPUNIT_LIBRARIES, the libraries needed to use CPPUNIT. # CPPUNIT_FOUND, If false, do not try to use CPPUNIT. # also defined, but not for general use are # CPPUNIT_LIBRARY, where to find the CPPUNIT library. #============================================================================= # Copyright 2001-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distributed this file outside of CMake, substitute the full # License text for the above reference.) FIND_PATH(CPPUNIT_INCLUDE_DIR cppunit/Test.h) SET(CPPUNIT_NAMES ${CPPUNIT_NAMES} cppunit libcppunit) FIND_LIBRARY(CPPUNIT_LIBRARY NAMES ${CPPUNIT_NAMES} ) # handle the QUIETLY and REQUIRED arguments and set CPPUNIT_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(CPPUNIT DEFAULT_MSG CPPUNIT_LIBRARY CPPUNIT_INCLUDE_DIR) IF(CPPUNIT_FOUND) SET(CPPUNIT_LIBRARIES ${CPPUNIT_LIBRARY}) ENDIF(CPPUNIT_FOUND) # Deprecated declarations. SET (NATIVE_CPPUNIT_INCLUDE_PATH ${CPPUNIT_INCLUDE_DIR} ) IF(CPPUNIT_LIBRARY) GET_FILENAME_COMPONENT (NATIVE_CPPUNIT_LIB_PATH ${CPPUNIT_LIBRARY} PATH) ENDIF(CPPUNIT_LIBRARY) MARK_AS_ADVANCED(CPPUNIT_LIBRARY CPPUNIT_INCLUDE_DIR ) ossim-Miami-2.9.1/cmake/CMakeModules/FindCsmApi.cmake000066400000000000000000000023311352751253100222620ustar00rootroot00000000000000# - Find csmApi library # Find the native csmApi includes and library # This module defines # CSMAPI_INCLUDE_DIR, where to find cam api headers, etc. # CSMAPI_LIBRARY, where to find the CSMAPI library. # CSMAPI_FOUND, If false, do not try to use csmApi. # also defined, but not for general use are # # NOTE: If MSP Distro is available, CSM can be found there. SET(CMAKE_FIND_FRAMEWORK "LAST") FIND_PATH(CSMAPI_INCLUDE_DIR csm/csm.h PATHS ${MSP_HOME}/include/common ${CSM_HOME}/include) find_library(CSMAPI_LIBRARY NAMES MSPcsmapi csmapi PATHS ${MSP_HOME}/lib ${CSM_HOME}/lib) #--- # This function sets CSMAPI_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( CSMAPI DEFAULT_MSG CSMAPI_LIBRARY CSMAPI_INCLUDE_DIR ) if ( NOT CSMAPI_FOUND ) message( WARNING "Could not find CSMAPI" ) else () if( NOT CSMAPI_FIND_QUIETLY ) message( STATUS "CSMAPI_INCLUDE_DIR=${CSMAPI_INCLUDE_DIR}" ) message( STATUS "CSMAPI_LIBRARY=${CSMAPI_LIBRARY}" ) endif( NOT CSMAPI_FIND_QUIETLY ) endif (NOT CSMAPI_FOUND) mark_as_advanced(CSMAPI_INCLUDE_DIR CSMAPI_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindFFTW3.cmake000066400000000000000000000015161352751253100217430ustar00rootroot00000000000000# - Find fftw3 library # Find the native fftw3 includes and library # This module defines # FFTW3_INCLUDE_DIR, where to find tiff.h, etc. # FFTW3_LIBRARIES, libraries to link against to use FFTW3. # FFTW3_FOUND, If false, do not try to use FFTW3. # also defined, but not for general use are # FFTW3_LIBRARY, where to find the FFTW3 library. FIND_PATH(FFTW3_INCLUDE_DIR fftw3.h) SET(FFTW3_NAMES ${FFTW3_NAMES} fftw3 libfftw3) FIND_LIBRARY(FFTW3_LIBRARY NAMES ${FFTW3_NAMES} ) # handle the QUIETLY and REQUIRED arguments and set FFTW3_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(FFTW3 DEFAULT_MSG FFTW3_LIBRARY FFTW3_INCLUDE_DIR) IF(FFTW3_FOUND) SET( FFTW3_LIBRARIES ${FFTW3_LIBRARY} ) ENDIF(FFTW3_FOUND) MARK_AS_ADVANCED(FFTW3_INCLUDE_DIR FFTW3_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindFFmpeg.cmake000066400000000000000000000135351352751253100222620ustar00rootroot00000000000000# Locate ffmpeg # This module defines # FFMPEG_LIBRARIES # FFMPEG_FOUND, if false, do not try to link to ffmpeg # FFMPEG_INCLUDE_DIR, where to find the headers # # $FFMPEG_DIR is an environment variable that would # correspond to the ./configure --prefix=$FFMPEG_DIR # # Created by Robert Osfield. #In ffmpeg code, old version use "#include " and newer use "#include " #In OSG ffmpeg plugin, we use "#include " for compatibility with old version of ffmpeg #We have to search the path which contain the header.h (usefull for old version) #and search the path which contain the libname/header.h (usefull for new version) #Then we need to include ${FFMPEG_libname_INCLUDE_DIRS} (in old version case, use by ffmpeg header and osg plugin code) # (in new version case, use by ffmpeg header) #and ${FFMPEG_libname_INCLUDE_DIRS/libname} (in new version case, use by osg plugin code) # Macro to find header and lib directories # example: FFMPEG_FIND(AVFORMAT avformat avformat.h) MACRO(FFMPEG_FIND varname shortname headername) # old version of ffmpeg put header in $prefix/include/[ffmpeg] # so try to find header in include directory FIND_PATH(FFMPEG_${varname}_INCLUDE_DIRS lib${shortname}/${headername} PATHS ${FFMPEG_ROOT}/include $ENV{FFMPEG_DIR}/include ~/Library/Frameworks /Library/Frameworks /sw/include # Fink /opt/local/include # DarwinPorts /opt/csw/include # Blastwave /opt/include /usr/freeware/include PATH_SUFFIXES ffmpeg DOC "Location of FFMPEG Headers" ) if( FFMPEG_${varname}_INCLUDE_DIRS-NOTFOUND ) FIND_PATH(FFMPEG_${varname}_INCLUDE_DIRS ${headername} PATHS ${FFMPEG_ROOT}/include $ENV{FFMPEG_DIR}/include ~/Library/Frameworks /Library/Frameworks /sw/include # Fink /opt/local/include # DarwinPorts /opt/csw/include # Blastwave /opt/include /usr/freeware/include PATH_SUFFIXES ffmpeg DOC "Location of FFMPEG Headers" ) endif ( FFMPEG_${varname}_INCLUDE_DIRS-NOTFOUND ) FIND_LIBRARY(FFMPEG_${varname}_LIBRARIES NAMES ${shortname} PATHS ${FFMPEG_ROOT} $ENV{FFMPEG_DIR} ~/Library /Library PATH_SUFFIXES lib64 lib Frameworks ) IF (FFMPEG_${varname}_LIBRARIES AND FFMPEG_${varname}_INCLUDE_DIRS) SET(FFMPEG_${varname}_FOUND 1) ENDIF(FFMPEG_${varname}_LIBRARIES AND FFMPEG_${varname}_INCLUDE_DIRS) ENDMACRO(FFMPEG_FIND) SET(FFMPEG_ROOT "$ENV{FFMPEG_DIR}" CACHE PATH "Location of FFMPEG") # find stdint.h IF(WIN32) FIND_PATH(FFMPEG_STDINT_INCLUDE_DIR stdint.h PATHS ${FFMPEG_ROOT}/include $ENV{FFMPEG_DIR}/include ~/Library/Frameworks /Library/Frameworks /usr/local/include /usr/include /sw/include # Fink /opt/local/include # DarwinPorts /opt/csw/include # Blastwave /opt/include /usr/freeware/include PATH_SUFFIXES ffmpeg DOC "Location of FFMPEG stdint.h Header" ) IF (FFMPEG_STDINT_INCLUDE_DIR) SET(STDINT_OK TRUE) ENDIF() ELSE() SET(STDINT_OK TRUE) ENDIF() FFMPEG_FIND(LIBAVFORMAT avformat avformat.h) FFMPEG_FIND(LIBAVDEVICE avdevice avdevice.h) FFMPEG_FIND(LIBAVCODEC avcodec avcodec.h) FFMPEG_FIND(LIBAVUTIL avutil avutil.h) # FFMPEG_FIND(LIBAVCORE avcore avcore.h) FFMPEG_FIND(LIBSWSCALE swscale swscale.h) FFMPEG_FIND(LIBSWRESAMPLE swresample swresample.h) FFMPEG_FIND(LIBAVFILTER avfilter avfilter.h) SET(FFMPEG_FOUND "NO") # Note we don't check FFMPEG_LIBSWSCALE_FOUND here, it's optional. IF (FFMPEG_LIBAVFORMAT_FOUND AND FFMPEG_LIBAVDEVICE_FOUND AND FFMPEG_LIBAVCODEC_FOUND AND FFMPEG_LIBAVUTIL_FOUND AND STDINT_OK) SET(FFMPEG_FOUND "YES") SET( FFMPEG_INCLUDE_DIRS ${FFMPEG_LIBAVFORMAT_INCLUDE_DIRS} ${FFMPEG_LIBAVDEVICE_INCLUDE_DIRS} ${FFMPEG_LIBAVCODEC_INCLUDE_DIRS} ${FFMPEG_LIBAVUTIL_INCLUDE_DIRS} ${FFMPEG_LIBSWSCALE_INCLUDE_DIRS} ${FFMPEG_LIBAVFILTER_INCLUDE_DIRS} ${FFMPEG_LIBSWRESAMPLE_INCLUDE_DIRS} ) SET(FFMPEG_LIBRARY_DIRS ${FFMPEG_LIBAVFORMAT_LIBRARY_DIRS}) # Note we don't add FFMPEG_LIBSWSCALE_LIBRARIES here, it will be added if found later. SET(FFMPEG_LIBRARIES ${FFMPEG_LIBAVCODEC_LIBRARIES} ${FFMPEG_LIBAVFORMAT_LIBRARIES} ${FFMPEG_LIBAVDEVICE_LIBRARIES} ${FFMPEG_LIBAVUTIL_LIBRARIES} ${FFMPEG_LIBSWSCALE_LIBRARIES}) IF(FFMPEG_LIBAVFILTER_LIBRARIES) SET(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} ${FFMPEG_LIBAVFILTER_LIBRARIES}) ENDIF() IF(FFMPEG_LIBSWRESAMPLE_LIBRARIES) SET(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} ${FFMPEG_LIBSWRESAMPLE_LIBRARIES}) ENDIF() IF (FFMPEG_LIBAVCORE_FOUND) SET(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} ${FFMPEG_LIBAVCORE_LIBRARIES} ) SET(FFMPEG_INCLUDE_DIRS ${FFMPEG_INCLUDE_DIRS} ${FFMPEG_LIBAVCORE_INCLUDE_DIRS} ${FFMPEG_LIBAVCORE_INCLUDE_DIRS}/libavformat ) ENDIF() #--- # This function sets FFMPEG_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( FFMPEG DEFAULT_MSG FFMPEG_LIBRARIES FFMPEG_INCLUDE_DIRS ) # use aPPEND instead of set. Seems to work better set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__STDC_CONSTANT_MACROS") ELSE () MESSAGE(STATUS "Could not find FFMPEG") ENDIF() if( NOT FFMPEG_FIND_QUIETLY ) message( STATUS "FFMPEG_INCLUDE_DIRS = ${FFMPEG_INCLUDE_DIRS}" ) message( STATUS "FFMPEG_LIBRARIES = ${FFMPEG_LIBRARIES}" ) endif( NOT FFMPEG_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindFreetype.cmake000066400000000000000000000112401352751253100226700ustar00rootroot00000000000000#.rst: # FindFreetype # ------------ # # Locate FreeType library # # This module defines # # :: # # FREETYPE_LIBRARIES, the library to link against # FREETYPE_FOUND, if false, do not try to link to FREETYPE # FREETYPE_INCLUDE_DIRS, where to find headers. # FREETYPE_VERSION_STRING, the version of freetype found (since CMake 2.8.8) # This is the concatenation of the paths: # FREETYPE_INCLUDE_DIR_ft2build # FREETYPE_INCLUDE_DIR_freetype2 # # # # $FREETYPE_DIR is an environment variable that would correspond to the # ./configure --prefix=$FREETYPE_DIR used in building FREETYPE. #============================================================================= # Copyright 2007-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) # Created by Eric Wing. # Modifications by Alexander Neundorf. # This file has been renamed to "FindFreetype.cmake" instead of the correct # "FindFreeType.cmake" in order to be compatible with the one from KDE4, Alex. # Ugh, FreeType seems to use some #include trickery which # makes this harder than it should be. It looks like they # put ft2build.h in a common/easier-to-find location which # then contains a #include to a more specific header in a # more specific location (#include ). # Then from there, they need to set a bunch of #define's # so you can do something like: # #include FT_FREETYPE_H # Unfortunately, using CMake's mechanisms like include_directories() # wants explicit full paths and this trickery doesn't work too well. # I'm going to attempt to cut out the middleman and hope # everything still works. find_path( FREETYPE_INCLUDE_DIR_ft2build ft2build.h HINTS ENV FREETYPE_DIR ENV GTKMM_BASEPATH PATHS /usr/freeware [HKEY_CURRENT_USER\\SOFTWARE\\gtkmm\\2.4;Path] [HKEY_LOCAL_MACHINE\\SOFTWARE\\gtkmm\\2.4;Path] PATH_SUFFIXES include/freetype2 include freetype2 ) find_path(FREETYPE_INCLUDE_DIR_freetype2 NAMES freetype/config/ftheader.h config/ftheader.h HINTS ENV FREETYPE_DIR ENV GTKMM_BASEPATH PATHS /usr/freeware [HKEY_CURRENT_USER\\SOFTWARE\\gtkmm\\2.4;Path] [HKEY_LOCAL_MACHINE\\SOFTWARE\\gtkmm\\2.4;Path] PATH_SUFFIXES include/freetype2 include freetype2 ) find_library(FREETYPE_LIBRARY NAMES freetype libfreetype freetype219 HINTS ENV FREETYPE_DIR PATHS /usr/freeware ENV GTKMM_BASEPATH [HKEY_CURRENT_USER\\SOFTWARE\\gtkmm\\2.4;Path] [HKEY_LOCAL_MACHINE\\SOFTWARE\\gtkmm\\2.4;Path] PATH_SUFFIXES lib lib64 ) # set the user variables if(FREETYPE_INCLUDE_DIR_ft2build AND FREETYPE_INCLUDE_DIR_freetype2) set(FREETYPE_INCLUDE_DIRS "${FREETYPE_INCLUDE_DIR_ft2build};${FREETYPE_INCLUDE_DIR_freetype2}") list(REMOVE_DUPLICATES FREETYPE_INCLUDE_DIRS) endif() set(FREETYPE_LIBRARIES "${FREETYPE_LIBRARY}") if(EXISTS "${FREETYPE_INCLUDE_DIR_freetype2}/freetype/freetype.h") set(FREETYPE_H "${FREETYPE_INCLUDE_DIR_freetype2}/freetype/freetype.h") elseif(EXISTS "${FREETYPE_INCLUDE_DIR_freetype2}/freetype.h") set(FREETYPE_H "${FREETYPE_INCLUDE_DIR_freetype2}/freetype.h") endif() if(FREETYPE_INCLUDE_DIR_freetype2 AND FREETYPE_H) file(STRINGS "${FREETYPE_H}" freetype_version_str REGEX "^#[\t ]*define[\t ]+FREETYPE_(MAJOR|MINOR|PATCH)[\t ]+[0-9]+$") unset(FREETYPE_VERSION_STRING) foreach(VPART MAJOR MINOR PATCH) foreach(VLINE ${freetype_version_str}) if(VLINE MATCHES "^#[\t ]*define[\t ]+FREETYPE_${VPART}[\t ]+([0-9]+)$") set(FREETYPE_VERSION_PART "${CMAKE_MATCH_1}") if(FREETYPE_VERSION_STRING) set(FREETYPE_VERSION_STRING "${FREETYPE_VERSION_STRING}.${FREETYPE_VERSION_PART}") else() set(FREETYPE_VERSION_STRING "${FREETYPE_VERSION_PART}") endif() unset(FREETYPE_VERSION_PART) endif() endforeach() endforeach() endif() # handle the QUIETLY and REQUIRED arguments and set FREETYPE_FOUND to TRUE if # all listed variables are TRUE include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) find_package_handle_standard_args( Freetype REQUIRED_VARS FREETYPE_LIBRARY FREETYPE_INCLUDE_DIRS VERSION_VAR FREETYPE_VERSION_STRING ) mark_as_advanced( FREETYPE_LIBRARY FREETYPE_INCLUDE_DIR_freetype2 FREETYPE_INCLUDE_DIR_ft2build ) ossim-Miami-2.9.1/cmake/CMakeModules/FindGEOS.cmake000066400000000000000000000042341352751253100216470ustar00rootroot00000000000000#--- # File: FindGEOS.cmake # # Find the native GEOS(Geometry Engine - Open Source) includes and libraries. # # This module defines: # # GEOS_INCLUDE_DIR, where to find geos.h, etc. # GEOS_LIBRARY, libraries to link against to use GEOS. Currently there are # two looked for, geos and geos_c libraries. # GEOS_FOUND, True if found, false if one of the above are not found. # # For ossim, typically geos will be system installed which should be found; # or found in the ossim 3rd party dependencies directory from a geos build # and install. If the latter it will rely on CMAKE_INCLUDE_PATH and # CMAKE_LIBRARY_PATH having the path to the party dependencies directory. # # NOTE: # This script is specialized for ossim, e.g. looking in /usr/local/ossim. # # $Id$ #--- #--- # Find include path: # Note: Ubuntu 14.04+ did not have geos.h (not included in any ossim src). # Instead looking for Geometry.h #--- find_path( GEOS_INCLUDE_DIR geos/geom/Geometry.h PATHS $ENV{GEOS_DIR}/include ${GEOS_DIR}/include) # Find GEOS library: find_library( GEOS_LIB NAMES geos PATHS $ENV{GEOS_DIR}/lib ${GEOS_DIR}/lib) # Find GEOS C library: find_library( GEOS_C_LIB NAMES geos_c PATHS $ENV{GEOS_DIR}/lib ${GEOS_DIR}/lib) # Set the GEOS_LIBRARY: if( GEOS_LIB AND GEOS_C_LIB ) set( GEOS_LIBRARY ${GEOS_LIB} ${GEOS_C_LIB} CACHE STRING INTERNAL ) endif(GEOS_LIB AND GEOS_C_LIB ) #--- # This function sets GEOS_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( GEOS DEFAULT_MSG GEOS_LIBRARY GEOS_INCLUDE_DIR ) if( GEOS_FOUND ) if( NOT GEOS_FIND_QUIETLY ) message( STATUS "Found GEOS..." ) endif( NOT GEOS_FIND_QUIETLY ) else( GEOS_FOUND ) if( NOT GEOS_FIND_QUIETLY ) message( WARNING "Could not find GEOS" ) endif( NOT GEOS_FIND_QUIETLY ) endif( GEOS_FOUND ) if( NOT GEOS_FIND_QUIETLY ) message( STATUS "GEOS_INCLUDE_DIR=${GEOS_INCLUDE_DIR}" ) message( STATUS "GEOS_LIBRARY=${GEOS_LIBRARY}" ) endif( NOT GEOS_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindGEOTIFF.cmake000066400000000000000000000023131352751253100221710ustar00rootroot00000000000000# - Find geotiff library # Find the native geotiff includes and library # This module defines # GEOTIFF_INCLUDE_DIR, where to find tiff.h, etc. # GEOTIFF_LIBRARIES, libraries to link against to use GEOTIFF. # GEOTIFF_FOUND, If false, do not try to use GEOTIFF. # also defined, but not for general use are # GEOTIFF_LIBRARY, where to find the GEOTIFF library. FIND_PATH(GEOTIFF_INCLUDE_DIR geotiff.h PATHS $ENV{GEOTIFF_DIR}/include /usr/include/geotiff /usr/include/libgeotiff /usr/local/include/libgeotiff /usr/local/include/geotiff) SET(GEOTIFF_NAMES ${GEOTIFF_NAMES} geotiff_i geotiff libgeotiff_i libgeotiff) FIND_LIBRARY(GEOTIFF_LIBRARY NAMES ${GEOTIFF_NAMES} PATHS $ENV{GEOTIFF_DIR}/lib $ENV{GEOTIFF_DIR}/lib64) # handle the QUIETLY and REQUIRED arguments and set GEOTIFF_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(GEOTIFF DEFAULT_MSG GEOTIFF_LIBRARY GEOTIFF_INCLUDE_DIR) IF(GEOTIFF_FOUND) SET( GEOTIFF_LIBRARIES ${GEOTIFF_LIBRARY} ) ENDIF(GEOTIFF_FOUND) MARK_AS_ADVANCED(GEOTIFF_INCLUDE_DIR GEOTIFF_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindGPSTK.cmake000066400000000000000000000015271352751253100220040ustar00rootroot00000000000000# - Find gpstk library # Find the native gpstk includes and library # This module defines # GPSTK_INCLUDE_DIR, where to find tiff.h, etc. # GPSTK_LIBRARIES, libraries to link against to use GPSTK. # GPSTK_FOUND, If false, do not try to use GPSTK. # also defined, but not for general use are # GPSTK_LIBRARY, where to find the GPSTK library. FIND_PATH(GPSTK_INCLUDE_DIR gpstk/Matrix.hpp) SET(GPSTK_NAMES ${GPSTK_NAMES} gpstk libgpstk) FIND_LIBRARY(GPSTK_LIBRARY NAMES ${GPSTK_NAMES} ) # handle the QUIETLY and REQUIRED arguments and set GPSTK_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(GPSTK DEFAULT_MSG GPSTK_LIBRARY GPSTK_INCLUDE_DIR) IF(GPSTK_FOUND) SET( GPSTK_LIBRARIES ${GPSTK_LIBRARY} ) ENDIF(GPSTK_FOUND) MARK_AS_ADVANCED(GPSTK_INCLUDE_DIR GPSTK_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindGeotrans.cmake000066400000000000000000000036001352751253100226700ustar00rootroot00000000000000#--- # File: FindGeotrans.cmake # # Find the native GeoTrans includes and libraries. # # This module defines: # # GEOTRANS_INCLUDE_DIR, where to find geotrans_config.h, etc. # GEOTRANS_LIBRARY, libraries to link against to use Geotrans. # GEOTRANS_FOUND, True if found, false if one of the above are not found. # # For ossim, typically geos will be system installed which should be found; # or found in the ossim 3rd party dependencies directory from a geos build # and install. If the latter it will rely on CMAKE_INCLUDE_PATH and # CMAKE_LIBRARY_PATH having the path to the party dependencies directory. # # NOTE: # # This script is specialized for ossim, e.g. looking in /usr/local/ossim. # # $Id$ #--- #--- # Find include path: # Note: Version < 3.3.0 do not have geos.h in the geos sub directory; hence, # the check for both "geos/geos.h" and "geos.h". #--- find_path( GEOTRANS_INCLUDE_DIR geotrans/geotrans_config.h) # Find Geotrans library: find_library( Geotrans_LIB NAMES geotrans ) # Set the Geotrans_LIBRARY: if( Geotrans_LIB ) set( GEOTRANS_LIBRARY ${Geotrans_LIB} CACHE STRING INTERNAL ) endif(Geotrans_LIB ) #--- # This function sets Geotrans_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( GEOTRANS DEFAULT_MSG GEOTRANS_LIBRARY GEOTRANS_INCLUDE_DIR ) if( GEOTRANS_FOUND ) if( NOT GEOTRANS_FIND_QUIETLY ) message( STATUS "Found Geotrans..." ) endif( NOT GEOTRANS_FIND_QUIETLY ) else( Geotrans_FOUND ) if( NOT GEOTRANS_FIND_QUIETLY ) message( WARNING "Could not find Geotrans" ) endif( NOT GEOTRANS_FIND_QUIETLY ) endif( GEOTRANS_FOUND ) if( NOT GEOTRANS_FIND_QUIETLY ) message( STATUS "GEOTRANS_INCLUDE_DIR=${GEOTRANS_INCLUDE_DIR}" ) message( STATUS "GEOTRANS_LIBRARY=${GEOTRANS_LIBRARY}" ) endif( NOT GEOTRANS_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindGit.cmake000066400000000000000000000111141352751253100216300ustar00rootroot00000000000000# - Extract information from a GIT working copy # The module defines the following variables: # GIT_EXECUTABLE - path to git command line client # GIT_FOUND - true if the command line client was found # GIT_VERSION_STRING - the version of git found (since CMake 2.8.8) # # The minimum required version of Git can be specified using the # standard syntax, e.g. FIND_PACKAGE(Git 1.4) # # If the command line client executable is found two macros are defined: # GIT_WC_INFO( ) # GIT_WC_LOG( ) # GIT_WC_INFO extracts information of a GIT working copy at # a given location. This macro defines the following variables: # _WC_URL - url of the repository (at ) # _WC_ROOT - root url of the repository # _WC_REVISION - current revision # _WC_LAST_CHANGED_AUTHOR - author of last commit # _WC_LAST_CHANGED_DATE - date of last commit # _WC_LAST_CHANGED_REV - revision of last commit # _WC_INFO - output of command `git rev-list HEAD --max-count 1' # GIT_WC_LOG retrieves the log message of the base revision of a # GIT working copy at a given location. This macro defines the # variable: # _LAST_CHANGED_LOG - last log of base revision # Example usage: # FIND_PACKAGE(GIT) # IF(GIT_FOUND) # GIT_WC_INFO(${PROJECT_SOURCE_DIR} Project) # MESSAGE("Current revision is ${Project_WC_REVISION}") # GIT_WC_LOG(${PROJECT_SOURCE_DIR} Project) # MESSAGE("Last changed log is ${Project_LAST_CHANGED_LOG}") # ENDIF(GIT_FOUND) # #============================================================================= # Copyright 2010 Kitware, Inc. # Copyright 2012 Rolf Eike Beer # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) # Look for 'git' or 'eg' (easy git) # set(git_names git eg) # Prefer .cmd variants on Windows unless running in a Makefile # in the MSYS shell. # if(WIN32) if(NOT CMAKE_GENERATOR MATCHES "MSYS") set(git_names git.cmd git eg.cmd eg) # GitHub search path for Windows set(github_path "$ENV{LOCALAPPDATA}/Github/PortableGit*/bin") file(GLOB github_path "${github_path}") endif() endif() find_program(GIT_EXECUTABLE NAMES ${git_names} PATHS ${github_path} PATH_SUFFIXES Git/cmd Git/bin DOC "git command line client" ) mark_as_advanced(GIT_EXECUTABLE) IF(GIT_EXECUTABLE) execute_process(COMMAND ${GIT_EXECUTABLE} --version OUTPUT_VARIABLE git_version ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) if (git_version MATCHES "^git version [0-9]") string(REPLACE "git version " "" GIT_VERSION_STRING "${git_version}") endif() unset(git_version) MACRO(GIT_WC_INFO dir prefix) # the GIT commands should be executed with the C locale, otherwise # the message (which are parsed) may be translated, Alex # SET(GIT_SAVED_LC_ALL "$ENV{LC_ALL}") # SET(ENV{LC_ALL} C) execute_process(COMMAND ${GIT_EXECUTABLE} rev-list HEAD --max-count=1 WORKING_DIRECTORY ${dir} OUTPUT_VARIABLE ${prefix}_WC_REVISION ERROR_VARIABLE git_info_error RESULT_VARIABLE git_info_result OUTPUT_STRIP_TRAILING_WHITESPACE) IF(NOT ${git_info_result} EQUAL 0) MESSAGE(WARNING "Command \"${GIT_EXECUTABLE} rev-list HEAD --max-count=1\" failed with output:\n${git_info_error}") ELSE(NOT ${git_info_result} EQUAL 0) set(${prefix}_WC_INFO ${git_info_result}) ENDIF(NOT ${git_info_result} EQUAL 0) # restore the previous LC_ALL # SET(ENV{LC_ALL} ${GIT_SAVED_LC_ALL}) ENDMACRO(GIT_WC_INFO) ENDIF(GIT_EXECUTABLE) # Handle the QUIETLY and REQUIRED arguments and set GIT_FOUND to TRUE if # all listed variables are TRUE include(FindPackageHandleStandardArgs) find_package_handle_standard_args( GIT DEFAULT_MSG GIT_EXECUTABLE GIT_VERSION_STRING ) if( GIT_FOUND ) if( NOT GIT_FIND_QUIETLY ) message( STATUS "GIT_VERSION_STRING = ${GIT_VERSION_STRING}" ) endif( NOT GIT_FIND_QUIETLY ) else( GIT_FOUND ) if( NOT GIT_FIND_QUIETLY ) message( WARNING "Could not find GIT" ) endif( NOT GIT_FIND_QUIETLY ) endif( GIT_FOUND ) ossim-Miami-2.9.1/cmake/CMakeModules/FindHDF5.cmake000066400000000000000000000031001352751253100215670ustar00rootroot00000000000000#--- # File: FindHDF5.cmake # # Find the native HDF5 includes and libraries. # # This module defines: # # HDF5_INCLUDE_DIR, where to find geos.h, etc. # HDF5_LIBRARIES, libraries to link against to use HDF5. # HDF5_FOUND, True if found, false if one of the above are not found. # # NOTE: # # This script is specialized for ossim. HDF5 rpm created to fix conflict with # system installed hdf5 packages that do NOT have compression(szip) support. # # $Id$ #--- # Find include path: find_path( HDF5_INCLUDE_DIR hdf5.h PATHS $ENV{HDF5_DIR}/include) # Find HDF5 library: find_library( HDF5_LIB NAMES hdf5 PATHS $ENV{HDF5_DIR}) # Find HDF5 CPP library: find_library( HDF5_CPP_LIB NAMES hdf5_cpp PATHS $ENV{HDF5_DIR}) # Set the HDF5_LIBRARIES: if( HDF5_LIB AND HDF5_CPP_LIB ) set( HDF5_LIBRARIES ${HDF5_LIB} ${HDF5_CPP_LIB} CACHE STRING INTERNAL ) endif(HDF5_LIB AND HDF5_CPP_LIB ) #--- # This function sets HDF5_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( HDF5 DEFAULT_MSG HDF5_LIBRARIES HDF5_INCLUDE_DIR ) if( HDF5_FOUND ) if( NOT HDF5_FIND_QUIETLY ) message( STATUS "Found HDF5..." ) endif( NOT HDF5_FIND_QUIETLY ) else( HDF5_FOUND ) if( NOT HDF5_FIND_QUIETLY ) message( WARNING "Could not find HDF5" ) endif( NOT HDF5_FIND_QUIETLY ) endif( HDF5_FOUND ) if( NOT HDF5_FIND_QUIETLY ) message( STATUS "HDF5_INCLUDE_DIR=${HDF5_INCLUDE_DIR}" ) message( STATUS "HDF5_LIBRARIES=${HDF5_LIBRARIES}" ) endif( NOT HDF5_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindHDF5A.cmake000066400000000000000000000034041352751253100216770ustar00rootroot00000000000000#--- # File: FindHDF5A.cmake # # Find the native HDF5A includes and libraries. # # This module defines: # # HDF5A_INCLUDE_DIR, where to find geos.h, etc. # HDF5A_LIBRARIES, libraries to link against to use HDF5A. # HDF5A_FOUND, True if found, false if one of the above are not found. # # NOTE: # # This script is specialized for ossim. HDF5A rpm created to fix conflict with # system installed hdf5 packages that do NOT have compression(szip) support. # # $Id$ #--- # Find include path: find_path( HDF5A_INCLUDE_DIR hdf5.h PATHS $ENV{HDF5_DIR}/include) # Find HDF5A library: find_library( HDF5A_LIB NAMES hdf5a hdf5 PATHS $ENV{HDF5_DIR}/lib64 $ENV{HDF5_DIR}/lib) # Find HDF5A CPP library: find_library( HDF5A_CPP_LIB NAMES hdf5a_cpp hdf5_cpp PATHS $ENV{HDF5_DIR}/lib64 $ENV{HDF5_DIR}/lib) # Set the HDF5A_LIBRARIES: if( HDF5A_LIB AND HDF5A_CPP_LIB ) set( HDF5A_LIBRARIES ${HDF5A_LIB} ${HDF5A_CPP_LIB} CACHE STRING INTERNAL ) endif(HDF5A_LIB AND HDF5A_CPP_LIB ) #--- # This function sets HDF5A_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( HDF5A DEFAULT_MSG HDF5A_LIBRARIES HDF5A_INCLUDE_DIR ) if( HDF5A_FOUND ) if( NOT HDF5A_FIND_QUIETLY ) message( STATUS "Found HDF5A..." ) endif( NOT HDF5A_FIND_QUIETLY ) else( HDF5A_FOUND ) if( NOT HDF5A_FIND_QUIETLY ) message( WARNING "Could not find HDF5A" ) endif( NOT HDF5A_FIND_QUIETLY ) endif( HDF5A_FOUND ) if( NOT HDF5A_FIND_QUIETLY ) message( STATUS "HDF5A_INCLUDE_DIR=${HDF5A_INCLUDE_DIR}" ) message( STATUS "HDF5A_LIBRARIES=${HDF5A_LIBRARIES}" ) endif( NOT HDF5A_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindJPEG.cmake000066400000000000000000000031631352751253100216370ustar00rootroot00000000000000# - Find JPEG # Find the native JPEG includes and library # This module defines # JPEG_INCLUDE_DIR, where to find jpeglib.h, etc. # JPEG_LIBRARIES, the libraries needed to use JPEG. # JPEG_FOUND, If false, do not try to use JPEG. # also defined, but not for general use are # JPEG_LIBRARY, where to find the JPEG library. #============================================================================= # Copyright 2001-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distributed this file outside of CMake, substitute the full # License text for the above reference.) FIND_PATH(JPEG_INCLUDE_DIR jpeglib.h) SET(JPEG_NAMES ${JPEG_NAMES} jpeg libjpeg) # Added x86_64-linux-gnu path for Ubuntu install FIND_LIBRARY(JPEG_LIBRARY NAMES ${JPEG_NAMES}) # handle the QUIETLY and REQUIRED arguments and set JPEG_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(JPEG DEFAULT_MSG JPEG_LIBRARY JPEG_INCLUDE_DIR) IF(JPEG_FOUND) SET(JPEG_LIBRARIES ${JPEG_LIBRARY}) ENDIF(JPEG_FOUND) # Deprecated declarations. SET (NATIVE_JPEG_INCLUDE_PATH ${JPEG_INCLUDE_DIR} ) IF(JPEG_LIBRARY) GET_FILENAME_COMPONENT (NATIVE_JPEG_LIB_PATH ${JPEG_LIBRARY} PATH) ENDIF(JPEG_LIBRARY) MARK_AS_ADVANCED(JPEG_LIBRARY JPEG_INCLUDE_DIR ) ossim-Miami-2.9.1/cmake/CMakeModules/FindJPEG12.cmake000066400000000000000000000037021352751253100220010ustar00rootroot00000000000000# - Find JPEG12 # # --- # This is a specialized find for custom built jpeg library with 12 samples # enabled. # Specifically looks for library: /usr/lib64/libjpeg12.so # and header file: /usr/include/jpeg12/jpeglib.h # --- # # # Find the native JPEG includes and library # This module defines # JPEG12_INCLUDE_DIR, where to find jpeglib.h, etc. # JPEG12_LIBRARIES, the libraries needed to use JPEG. # JPEG12_FOUND, If false, do not try to use JPEG. # also defined, but not for general use are # JPEG12_LIBRARY, where to find the JPEG library. #============================================================================= # Copyright 2001-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distributed this file outside of CMake, substitute the full # License text for the above reference.) find_path( JPEG12_INCLUDE_DIR jpeg12/jpeglib.h) set( JPEG12_NAMES ${JPEG12_NAMES} jpeg12 libjpeg12 ) find_library( JPEG12_LIBRARY NAMES ${JPEG12_NAMES}) #--- # This function sets JPEG12_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args(JPEG12 DEFAULT_MSG JPEG12_LIBRARY JPEG12_INCLUDE_DIR) if( JPEG12_FOUND ) if( NOT JPEG12_FIND_QUIETLY ) message( STATUS "Found JPEG12..." ) endif( NOT JPEG12_FIND_QUIETLY ) else( JPEG12_FOUND ) if( NOT JPEG12_FIND_QUIETLY ) message( WARNING "Could not find JPEG12" ) endif( NOT JPEG12_FIND_QUIETLY ) endif( JPEG12_FOUND ) if( NOT JPEG12_FIND_QUIETLY ) message( STATUS "JPEG12_INCLUDE_DIR=${JPEG12_INCLUDE_DIR}" ) message( STATUS "JPEG12_LIBRARY=${JPEG12_LIBRARY}" ) endif( NOT JPEG12_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindJsonCpp.cmake000066400000000000000000000021411352751253100224610ustar00rootroot00000000000000######################################################################## # # Find the JSON CPP include and library. # # This module defines: # # JSONCPP_INCLUDE_DIR, where to find json.h, etc. # JSONCPP_LIBRARY, library to link against to use jsoncpp. # JSONCPP_FOUND, True if found, false if one of the above are not found. # USE_OSSIM_JSONCPP, Set to "YES" if no external package detected. # Directs cmake to include the jsoncpp subirectories in ossim build. # ######################################################################## set(JSONCPP_FOUND "NO") set(OSSIM_HAS_JSONCPP 0) find_path( JSONCPP_INCLUDE_DIR json/json.h PATHS "${CMAKE_INSTALL_PREFIX}" "${CMAKE_INSTALL_PREFIX}/include/jsoncpp" "/usr/include/jsoncpp" ) find_library( JSONCPP_LIBRARY NAMES "jsoncpp") include(FindPackageHandleStandardArgs) find_package_handle_standard_args( JSONCPP DEFAULT_MSG JSONCPP_LIBRARY JSONCPP_INCLUDE_DIR ) if (JSONCPP_FOUND) set(OSSIM_HAS_JSONCPP 1) endif (JSONCPP_FOUND) MARK_AS_ADVANCED(JSONCPP_LIBRARY JSONCPP_INCLUDE_DIR ) ossim-Miami-2.9.1/cmake/CMakeModules/FindLASzip.cmake000066400000000000000000000100101352751253100222410ustar00rootroot00000000000000############################################################################### # # CMake module to search for LASzip library # # On success, the macro sets the following variables: # LASZIP_FOUND = if the library found # LASZIP_INCLUDE_DIR = where to find the library headers also defined, # but not for general use are # LASZIP_LIBRARY = where to find the laszip library. # LASZIP_VERSION = version of library which was found, e.g. "1.2.5" # # Copyright (c) 2009 Mateusz Loskot # # Module source: http://github.com/mloskot/workshop/tree/master/cmake/ # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # ############################################################################### MESSAGE(STATUS "Searching for LASzip ${LASzip_FIND_VERSION}+ library") IF(LASZIP_INCLUDE_DIR) # Already in cache, be silent SET(LASZIP_FIND_QUIETLY TRUE) ENDIF() IF(WIN32) SET(OSGEO4W_IMPORT_LIBRARY laszip) IF(DEFINED ENV{OSGEO4W_ROOT}) SET(OSGEO4W_ROOT_DIR $ENV{OSGEO4W_ROOT}) #MESSAGE(STATUS " FindLASzip: trying OSGeo4W using environment variable OSGEO4W_ROOT=$ENV{OSGEO4W_ROOT}") ELSE() SET(OSGEO4W_ROOT_DIR c:/OSGeo4W) #MESSAGE(STATUS " FindLASzip: trying OSGeo4W using default location OSGEO4W_ROOT=${OSGEO4W_ROOT_DIR}") ENDIF() ENDIF() FIND_PATH(LASZIP_INCLUDE_DIR laszip.hpp PATH_PREFIXES laszip PATHS ${OSGEO4W_ROOT_DIR}/include) SET(LASZIP_NAMES ${OSGEO4W_IMPORT_LIBRARY} laszip) FIND_LIBRARY(LASZIP_LIBRARY NAMES ${LASZIP_NAMES} PATHS ${OSGEO4W_ROOT_DIR}) IF(LASZIP_INCLUDE_DIR) SET(LASZIP_VERSION 0) SET(LASZIP_VERSION_H "${LASZIP_INCLUDE_DIR}/laszip/laszip.hpp") FILE(READ ${LASZIP_VERSION_H} LASZIP_VERSION_H_CONTENTS) IF (DEFINED LASZIP_VERSION_H_CONTENTS) string(REGEX REPLACE ".*#define[ \t]LASZIP_VERSION_MAJOR[ \t]+([0-9]+).*" "\\1" LASZIP_VERSION_MAJOR "${LASZIP_VERSION_H_CONTENTS}") string(REGEX REPLACE ".*#define[ \t]LASZIP_VERSION_MINOR[ \t]+([0-9]+).*" "\\1" LASZIP_VERSION_MINOR "${LASZIP_VERSION_H_CONTENTS}") string(REGEX REPLACE ".*#define[ \t]LASZIP_VERSION_REVISION[ \t]+([0-9]+).*" "\\1" LASZIP_VERSION_REVISION "${LASZIP_VERSION_H_CONTENTS}") if(NOT ${LASZIP_VERSION_MAJOR} MATCHES "[0-9]+") message(FATAL_ERROR "LASzip version parsing failed for LASZIP_VERSION_MAJOR!") endif() if(NOT ${LASZIP_VERSION_MINOR} MATCHES "[0-9]+") message(FATAL_ERROR "LASzip version parsing failed for LASZIP_VERSION_MINOR!") endif() if(NOT ${LASZIP_VERSION_REVISION} MATCHES "[0-9]+") message(FATAL_ERROR "LASzip version parsing failed for LASZIP_VERSION_REVISION!") endif() SET(LASZIP_VERSION "${LASZIP_VERSION_MAJOR}.${LASZIP_VERSION_MINOR}.${LASZIP_VERSION_REVISION}" CACHE INTERNAL "The version string for LASzip library") IF (LASZIP_VERSION VERSION_EQUAL LASzip_FIND_VERSION OR LASZIP_VERSION VERSION_GREATER LASzip_FIND_VERSION) ELSE() MESSAGE(FATAL_ERROR "LASzip version check failed. Version ${LASZIP_VERSION} was found, at least version ${LASzip_FIND_VERSION} is required") ENDIF() ELSE() MESSAGE(FATAL_ERROR "Failed to open ${LASZIP_VERSION_H} file") ENDIF() ENDIF() #--- # This function sets LASZIP_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args(LASzip DEFAULT_MSG LASZIP_LIBRARY LASZIP_INCLUDE_DIR) if( LASZIP_FOUND ) if( NOT LASZIP_FIND_QUIETLY ) message( STATUS "Found LASzip..." ) endif( NOT LASZIP_FIND_QUIETLY ) else( LASZIP_FOUND ) if( NOT LASZIP_FIND_QUIETLY ) message( WARNING "Could not find LASzip" ) endif( NOT LASZIP_FIND_QUIETLY ) endif( LASZIP_FOUND ) #--- # Show the caller what was found regardless of LASZIP_FOUND variable: #--- if( NOT LASZIP_FIND_QUIETLY ) message( STATUS "LASZIP_INCLUDE_DIR=${LASZIP_INCLUDE_DIR}" ) message( STATUS "LASZIP_LIBRARY=${LASZIP_LIBRARY}" ) message( STATUS "Found LASzip version: ${LASZIP_VERSION}") endif( NOT LASZIP_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindLIBLAS.cmake000066400000000000000000000046041352751253100220610ustar00rootroot00000000000000#--- # File: FindLIBLAS.cmake # # Find the native LIBLAS includes and library # # LIBLAS_INCLUDE_DIRS - where to find liblas's includes. # LIBLAS_LIBRARIES - List of libraries when using liblas. # LIBLAS_FOUND - True if liblas found. #--- # Set the include dir: find_path(LIBLAS_INCLUDE_DIR liblas/liblas.hpp) # Macro for setting libraries: macro(FIND_LIBLAS_LIBRARY MYLIBRARY MYLIBRARYNAME) find_library( "${MYLIBRARY}_DEBUG" NAMES "${MYLIBRARYNAME}${CMAKE_DEBUG_POSTFIX}" PATHS ${LIBLAS_DIR}/lib/Debug ${LIBLAS_DIR}/lib64/Debug ${LIBLAS_DIR}/lib ${LIBLAS_DIR}/lib64 $ENV{LIBLAS_DIR}/lib/debug $ENV{LIBLAS_DIR}/lib64/debug NO_DEFAULT_PATH ) find_library( "${MYLIBRARY}_DEBUG" NAMES "${MYLIBRARYNAME}${CMAKE_DEBUG_POSTFIX}" PATHS ~/Library/Frameworks /Library/Frameworks /sw/lib /opt/local/lib /opt/csw/lib /opt/lib [HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session\ Manager\\Environment;LIBLAS_ROOT]/lib /usr/freeware/lib64 ) find_library( ${MYLIBRARY} NAMES "${MYLIBRARYNAME}${CMAKE_RELEASE_POSTFIX}" PATHS ${LIBLAS_DIR}/lib/Release ${LIBLAS_DIR}/lib64/Release ${LIBLAS_DIR}/lib ${LIBLAS_DIR}/lib64 $ENV{LIBLAS_DIR}/lib/Release $ENV{LIBLAS_DIR}/lib64/Release $ENV{LIBLAS_DIR}/lib $ENV{LIBLAS_DIR}/lib64 $ENV{LIBLAS_DIR} $ENV{LIBLASDIR}/lib $ENV{LIBLASDIR}/lib64 $ENV{LIBLASDIR} $ENV{LIBLAS_ROOT}/lib $ENV{LIBLAS_ROOT}/lib64 NO_DEFAULT_PATH ) find_library( ${MYLIBRARY} NAMES "${MYLIBRARYNAME}${CMAKE_RELEASE_POSTFIX}" PATHS ~/Library/Frameworks /Library/Frameworks /sw/lib /opt/local/lib /opt/csw/lib /opt/lib [HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session\ Manager\\Environment;LIBLAS_ROOT]/lib /usr/freeware/lib64 ) if( NOT ${MYLIBRARY}_DEBUG ) if( MYLIBRARY ) set( ${MYLIBRARY}_DEBUG ${MYLIBRARY} ) endif(MYLIBRARY) endif( NOT ${MYLIBRARY}_DEBUG ) endmacro(FIND_LIBLAS_LIBRARY LIBRARY LIBRARYNAME) FIND_LIBLAS_LIBRARY(LIBLAS_LIBRARY las) FIND_LIBLAS_LIBRARY(LIBLASC_LIBRARY las_c) set(LIBLAS_FOUND "NO") if(LIBLAS_LIBRARY AND LIBLASC_LIBRARY AND LIBLAS_INCLUDE_DIR) set(LIBLAS_LIBRARIES ${LIBLAS_LIBRARY} ${LIBLASC_LIBRARY} ) set(LIBLAS_FOUND "YES") endif(LIBLAS_LIBRARY AND LIBLASC_LIBRARY AND LIBLAS_INCLUDE_DIR) ossim-Miami-2.9.1/cmake/CMakeModules/FindMSP.cmake000066400000000000000000000073571352751253100215620ustar00rootroot00000000000000#--- # This module sets MSP_FOUND if variables are valid. #--- SET(CMAKE_FIND_FRAMEWORK "LAST") ############################################################## function(FIND_MSP_LIBRARY LIBNAME LIBSOK) find_library( TARGET_LIBRARY_${LIBNAME} NAMES "${LIBNAME}" PATHS ${MSP_HOME}/lib) if (TARGET_LIBRARY_${LIBNAME}) set (MSP_LIBRARIES ${MSP_LIBRARIES} ${TARGET_LIBRARY_${LIBNAME}} PARENT_SCOPE) else() set(${LIBSOK} "NO" PARENT_SCOPE) endif() endfunction(FIND_MSP_LIBRARY) ############################################################## set(MSP_FOUND "NO") set(OSSIM_HAS_MSP 0) FIND_PATH(MSP_INCLUDE_DIRS Mensuration/MensurationService.h PATHS ${MSP_HOME}/include) if (MSP_INCLUDE_DIRS) set (MSP_INCLUDE_DIRS ${MSP_INCLUDE_DIRS} ${MSP_INCLUDE_DIRS}/CoordinateConversion ${MSP_INCLUDE_DIRS}/Terrain ${MSP_INCLUDE_DIRS}/common ${MSP_INCLUDE_DIRS}/common/utilities ${MSP_INCLUDE_DIRS}/common/geometry ${MSP_INCLUDE_DIRS}/common/math ${MSP_INCLUDE_DIRS}/common/csmutil ${MSP_INCLUDE_DIRS}/common/ntmtre ${MSP_INCLUDE_DIRS}/common/nitf ${MSP_INCLUDE_DIRS}/common/deiutil ${MSP_INCLUDE_DIRS}/common/dtcc ${MSP_INCLUDE_DIRS}/common/csm) set(LIBS_OK "YES") FIND_MSP_LIBRARY(MSPPointExtractionService LIBS_OK) FIND_MSP_LIBRARY(MSPSensorModelService LIBS_OK) FIND_MSP_LIBRARY(MSPSourceSelectionService LIBS_OK) FIND_MSP_LIBRARY(MSPCovarianceService LIBS_OK) FIND_MSP_LIBRARY(MSPSupportDataService LIBS_OK) FIND_MSP_LIBRARY(MSPTerrainService LIBS_OK) FIND_MSP_LIBRARY(MSPCCSUtils LIBS_OK) FIND_MSP_LIBRARY(MSPCoordinateConversionService LIBS_OK) FIND_MSP_LIBRARY(MSPOutputMethodService LIBS_OK) FIND_MSP_LIBRARY(MSPasdetre LIBS_OK) FIND_MSP_LIBRARY(MSPcoordconverter LIBS_OK) FIND_MSP_LIBRARY(MSPcsisd LIBS_OK) FIND_MSP_LIBRARY(MSPcsm LIBS_OK) FIND_MSP_LIBRARY(MSPcsmutil LIBS_OK) FIND_MSP_LIBRARY(MSPdtcc LIBS_OK) FIND_MSP_LIBRARY(MSPlas LIBS_OK) FIND_MSP_LIBRARY(MSPgeometry LIBS_OK) FIND_MSP_LIBRARY(MSPmath LIBS_OK) FIND_MSP_LIBRARY(MSPnitf LIBS_OK) FIND_MSP_LIBRARY(MSPntmtre LIBS_OK) FIND_MSP_LIBRARY(MSPrage LIBS_OK) FIND_MSP_LIBRARY(MSPRageServiceUtils LIBS_OK) FIND_MSP_LIBRARY(MSPrageutilities LIBS_OK) FIND_MSP_LIBRARY(MSPSScovmodel LIBS_OK) FIND_MSP_LIBRARY(MSPSSrutil LIBS_OK) FIND_MSP_LIBRARY(MSPutilities LIBS_OK) FIND_MSP_LIBRARY(CSM_PCAPI LIBS_OK) FIND_MSP_LIBRARY(MSPrsme LIBS_OK) FIND_MSP_LIBRARY(MSPRsmGeneratorService LIBS_OK) FIND_MSP_LIBRARY(MSPdei LIBS_OK) FIND_MSP_LIBRARY(MSPrsmg LIBS_OK) FIND_MSP_LIBRARY(MSPDEIUtil LIBS_OK) FIND_MSP_LIBRARY(MSPrutil LIBS_OK) FIND_MSP_LIBRARY(MSPSensorSpecificService LIBS_OK) FIND_MSP_LIBRARY(MSPImagingGeometryService LIBS_OK) FIND_MSP_LIBRARY(MSPjson LIBS_OK) FIND_MSP_LIBRARY(MSPmens LIBS_OK) FIND_MSP_LIBRARY(MSPTerrainService LIBS_OK) FIND_MSP_LIBRARY(MSPMensurationService LIBS_OK) FIND_MSP_LIBRARY(MSPMensurationSessionRecordService LIBS_OK) FIND_MSP_LIBRARY(MSPwriteRsmNitf LIBS_OK) FIND_MSP_LIBRARY(MSPMSPVersionUtils LIBS_OK) FIND_MSP_LIBRARY(MSPmtdCommon LIBS_OK) FIND_MSP_LIBRARY(pthread LIBS_OK) FIND_MSP_LIBRARY(dl LIBS_OK) # These are optional. Include only if present: FIND_MSP_LIBRARY(MSPsupportdata DUMMY_ARG) FIND_MSP_LIBRARY(MSPHardCopyService DUMMY_ARG) FIND_MSP_LIBRARY(MSPmiisd DUMMY_ARG) if( LIBS_OK ) set(MSP_FOUND "YES") set(OSSIM_HAS_MSP 1) message("-- MSP_INCLUDE_DIRS = ${MSP_INCLUDE_DIRS}") message("-- MSP_LIBRARIES = ${MSP_LIBRARIES}") endif() endif() mark_as_advanced(MSP_INCLUDE_DIRS MSP_LIBRARIES) ossim-Miami-2.9.1/cmake/CMakeModules/FindMiniZip.cmake000066400000000000000000000016151352751253100224710ustar00rootroot00000000000000# - Find minizip # Find the native MINIZIP includes and library # # MINIZIP_INCLUDE_DIRS - where to find minizip's zip.h, etc. # MINIZIP_LIBRARIES - List of libraries when using minizip. # MINIZIP_FOUND - True if minizip found. IF (MINIZIP_INCLUDE_DIR) # Already in cache, be silent SET(MINIZIP_FIND_QUIETLY TRUE) ENDIF (MINIZIP_INCLUDE_DIR) FIND_PATH(MINIZIP_INCLUDE_DIR minizip/zip.h) SET(MINIZIP_NAMES minizip ) FIND_LIBRARY(MINIZIP_LIBRARY NAMES ${MINIZIP_NAMES} ) MARK_AS_ADVANCED( MINIZIP_LIBRARY MINIZIP_INCLUDE_DIR ) # Per-recommendation SET(MINIZIP_INCLUDE_DIRS "${MINIZIP_INCLUDE_DIR}") SET(MINIZIP_LIBRARIES "${MINIZIP_LIBRARY}") # handle the QUIETLY and REQUIRED arguments and set MINIZIP_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(MINIZIP DEFAULT_MSG MINIZIP_LIBRARIES MINIZIP_INCLUDE_DIRS) ossim-Miami-2.9.1/cmake/CMakeModules/FindMrSid.cmake000066400000000000000000000066071352751253100221360ustar00rootroot00000000000000# - Find MrSid # Find the native MrSid includes and library # This module defines # MRSID_INCLUDE_DIR, where to header files. # MRSID_LIBRARIES, the libraries needed to use mrsid. # MRSID_FOUND, If false, do not try to use mrsid. #============================================================================= # Copyright 2001-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distributed this file outside of CMake, substitute the full # License text for the above reference.) #--- # Find the include dirs: #--- FIND_PATH( MRSID_RASTER_INCLUDE_DIR MrSIDImageReader.h PATHS ${MRSID_DIR}/Raster_DSDK/include ) FIND_PATH( MRSID_LIDAR_INCLUDE_DIR lidar/MG4PointReader.h PATHS ${MRSID_DIR}/Lidar_DSDK/include ) #--- # Find the Geo_DSDK (decode) library. #---- # SET(MRSID_RASTER_DSDK_C_NAMES lti_dsdk_cdll ltidsdk_c libltidsdkc) # FIND_LIBRARY( MRSID_RASTER_DSDK_C_LIBRARY # NAMES ${MRSID_RASTER_DSDK_C_NAMES} # PATHS # ${MRSID_DIR}/Raster_DSDK/lib ) SET(MRSID_RASTER_DSDK_NAMES lti_dsdk ltidsdk libltidsdk) FIND_LIBRARY( MRSID_RASTER_DSDK_LIBRARY NAMES ${MRSID_RASTER_DSDK_NAMES} PATHS ${MRSID_DIR}/Raster_DSDK/lib ) SET(MRSID_LIDAR_DSDK_NAMES lti_lidar_dsdk liblti_lidar_dsdk ) FIND_LIBRARY( MRSID_LIDAR_DSDK_LIBRARY NAMES ${MRSID_LIDAR_DSDK_NAMES} PATHS ${MRSID_DIR}/Lidar_DSDK/lib ) # handle the QUIETLY and REQUIRED arguments and set MRSID_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(MRSID DEFAULT_MSG MRSID_RASTER_INCLUDE_DIR MRSID_LIDAR_INCLUDE_DIR MRSID_RASTER_DSDK_LIBRARY MRSID_LIDAR_DSDK_LIBRARY) # FIND_PACKAGE_HANDLE_STANDARD_ARGS(MRSID DEFAULT_MSG MRSID_RASTER_INCLUDE_DIR MRSID_LIDAR_INCLUDE_DIR MRSID_RASTER_DSDK_LIBRARY MRSID_RASTER_DSDK_C_LIBRARY MRSID_LIDAR_DSDK_LIBRARY) IF(MRSID_FOUND) # Combine the includes into MRSID_INCLUDE_DIR variable: set(MRSID_INCLUDE_DIR ${MRSID_RASTER_INCLUDE_DIR} ${MRSID_LIDAR_INCLUDE_DIR}) # Combine the libraries into MRSID_LIBRARY variable: set(MRSID_LIBRARY ${MRSID_RASTER_DSDK_LIBRARY} ${MRSID_LIDAR_DSDK_LIBRARY}) # set(MRSID_LIBRARY ${MRSID_RASTER_DSDK_C_LIBRARY} ${MRSID_RASTER_DSDK_LIBRARY} ${MRSID_LIDAR_DSDK_LIBRARY}) #--- # Find the Geo_ESDK (encode) library. #---- SET(MRSID_ESDK_NAMES ${MRSID_ESDK_NAMES} ltiesdk libltiesdk) FIND_LIBRARY(MRSID_ESDK_LIBRARY NAMES ${MRSID_ESDK_NAMES}) #--- # Find the two includes need for the writer. #--- FIND_FILE(MG2IMAGEWRITER_H MG2ImageWriter.h ${MRSID_INCLUDE_DIR}) FIND_FILE(MG3IMAGEWRITER_H MG3ImageWriter.h ${MRSID_INCLUDE_DIR}) FIND_PACKAGE_HANDLE_STANDARD_ARGS(MRSID_WRITE DEFAULT_MSG MRSID_ESDK_LIBRARY MG2IMAGEWRITER_H MG3IMAGEWRITER_H) IF(MRSID_WRITE_FOUND) add_definitions(-DOSSIM_ENABLE_MRSID_WRITE) SET(MRSID_LIBRARY ${MRSID_DSDK_LIBRARY} ${MRSID_ESDK_LIBRARY}) ENDIF(MRSID_WRITE_FOUND) SET(MRSID_LIBRARIES ${MRSID_LIBRARY}) ENDIF(MRSID_FOUND) MARK_AS_ADVANCED(MRSID_LIBRARIES MRSID_INCLUDE_DIR ) ossim-Miami-2.9.1/cmake/CMakeModules/FindOMS.cmake000066400000000000000000000016061352751253100215500ustar00rootroot00000000000000# - Find ossim library # Find the native ossim includes and library # This module defines # OMS_INCLUDE_DIR, where to find tiff.h, etc. # OMS_LIBRARIES, libraries to link against to use OSSIM. # OMS_FOUND, If false, do not try to use OSSIM. # also defined, but not for general use are # OMS_LIBRARY, where to find the OSSIM library. SET(CMAKE_FIND_FRAMEWORK "LAST") FIND_PATH(OMS_INCLUDE_DIR oms/ossimVersion.h PATHS $ENV{OSSIM_DEV_HOME}/ossim-oms/coms/include) SET(OSSIM_NAMES ${OSSIM_NAMES} oms ) FIND_LIBRARY(OSSIM_LIBRARY NAMES ${OSSIM_NAMES}) # handle the QUIETLY and REQUIRED arguments and set OSSIM_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(OMS DEFAULT_MSG OMS_LIBRARY OMS_INCLUDE_DIR) IF(OMS_FOUND) SET( OMS_LIBRARIES ${OMS_LIBRARY} ) ENDIF(OMS_FOUND) MARK_AS_ADVANCED(OMS_INCLUDE_DIR OMS_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindOSG.cmake000066400000000000000000000065221352751253100215440ustar00rootroot00000000000000# Locate gdal # This module defines # OSG_LIBRARY # OSG_FOUND, if false, do not try to link to gdal # OSG_INCLUDE_DIR, where to find the headers # # $OSG_DIR is an environment variable that would # correspond to the ./configure --prefix=$OSG_DIR # # Created by Robert Osfield. FIND_PATH(OSG_INCLUDE_DIR osg/Node ${OSG_DIR}/include $ENV{OSG_DIR}/include $ENV{OSG_DIR} $ENV{OSGDIR}/include $ENV{OSGDIR} $ENV{OSG_ROOT}/include ${CMAKE_INSTALL_PREFIX}/include NO_DEFAULT_PATH ) FIND_PATH(OSG_INCLUDE_DIR osg/Node) MACRO(FIND_OSG_LIBRARY MYLIBRARY MYLIBRARYNAME) FIND_LIBRARY("${MYLIBRARY}_DEBUG" NAMES "${MYLIBRARYNAME}${CMAKE_DEBUG_POSTFIX}" PATHS ${OSG_DIR}/lib/Debug ${OSG_DIR}/lib64/Debug ${OSG_DIR}/lib ${OSG_DIR}/lib64 $ENV{OSG_DIR}/lib/debug $ENV{OSG_DIR}/lib64/debug $ENV{OSG_DIR}/lib $ENV{OSG_DIR}/lib64 $ENV{OSG_DIR} $ENV{OSGDIR}/lib $ENV{OSGDIR}/lib64 $ENV{OSGDIR} $ENV{OSG_ROOT}/lib $ENV{OSG_ROOT}/lib64 ${CMAKE_INSTALL_PREFIX}/lib ${CMAKE_INSTALL_PREFIX}/lib64 NO_DEFAULT_PATH ) FIND_LIBRARY("${MYLIBRARY}_DEBUG" NAMES "${MYLIBRARYNAME}${CMAKE_DEBUG_POSTFIX}" PATHS ~/Library/Frameworks /Library/Frameworks /sw/lib /opt/local/lib /opt/csw/lib /opt/lib [HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session\ Manager\\Environment;OSG_ROOT]/lib /usr/freeware/lib64 ) FIND_LIBRARY(${MYLIBRARY} NAMES "${MYLIBRARYNAME}${CMAKE_RELEASE_POSTFIX}" PATHS ${OSG_DIR}/lib/Release ${OSG_DIR}/lib64/Release ${OSG_DIR}/lib ${OSG_DIR}/lib64 $ENV{OSG_DIR}/lib/Release $ENV{OSG_DIR}/lib64/Release $ENV{OSG_DIR}/lib $ENV{OSG_DIR}/lib64 $ENV{OSG_DIR} $ENV{OSGDIR}/lib $ENV{OSGDIR}/lib64 $ENV{OSGDIR} $ENV{OSG_ROOT}/lib $ENV{OSG_ROOT}/lib64 ${CMAKE_INSTALL_PREFIX}/lib ${CMAKE_INSTALL_PREFIX}/lib64 NO_DEFAULT_PATH ) FIND_LIBRARY(${MYLIBRARY} NAMES "${MYLIBRARYNAME}${CMAKE_RELEASE_POSTFIX}" PATHS ~/Library/Frameworks /Library/Frameworks /sw/lib /opt/local/lib /opt/csw/lib /opt/lib [HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session\ Manager\\Environment;OSG_ROOT]/lib /usr/freeware/lib64 ) IF( NOT ${MYLIBRARY}_DEBUG) IF(MYLIBRARY) SET(${MYLIBRARY}_DEBUG ${MYLIBRARY}) ENDIF(MYLIBRARY) ENDIF( NOT ${MYLIBRARY}_DEBUG) ENDMACRO(FIND_OSG_LIBRARY LIBRARY LIBRARYNAME) FIND_OSG_LIBRARY(OSG_LIBRARY osg) FIND_OSG_LIBRARY(OSGGA_LIBRARY osgGA) FIND_OSG_LIBRARY(OSGUTIL_LIBRARY osgUtil) FIND_OSG_LIBRARY(OSGDB_LIBRARY osgDB) FIND_OSG_LIBRARY(OSGTEXT_LIBRARY osgText) FIND_OSG_LIBRARY(OSGWIDGET_LIBRARY osgWidget) FIND_OSG_LIBRARY(OSGTERRAIN_LIBRARY osgTerrain) FIND_OSG_LIBRARY(OSGFX_LIBRARY osgFX) FIND_OSG_LIBRARY(OSGVIEWER_LIBRARY osgViewer) FIND_OSG_LIBRARY(OSGSHADOW_LIBRARY osgShadow) FIND_OSG_LIBRARY(OSGVOLUME_LIBRARY osgVolume) FIND_OSG_LIBRARY(OPENTHREADS_LIBRARY OpenThreads) SET(OSG_FOUND "NO") IF(OSG_LIBRARY AND OSG_INCLUDE_DIR) SET(OSG_FOUND "YES") ENDIF(OSG_LIBRARY AND OSG_INCLUDE_DIR) ossim-Miami-2.9.1/cmake/CMakeModules/FindOpenCV.cmake000066400000000000000000000115311352751253100222420ustar00rootroot00000000000000#--- # File: FindOpenCV.cmake # # Locate OPENCV # # The cmake variable space is referenced for $OPENCV_HOME first before the # standard install locations to perit sandbox installations of OpenCV. # # This module defines: # # OPENCV_INCLUDE_DIR # # OPENCV_FOUND, # OPENCV_CORE_FOUND # OPENCV_HIGHGUI_FOUND # OPENCV_IMGPROC_FOUND # OPENCV_LEGACY_FOUND # OPENCV_ML_FOUND # # OPENCV_CORE_LIBRARY # OPENCV_HIGHGUI_LIBRARY # OPENCV_IMGPROC_LIBRARY # OPENCV_LEGACY_LIBRARY # OPENCV_ML_LIBRARY # OPENCV_LIBRARIES # # Created by Garrett Potts. # # $Id$ # Find include path: find_path(OPENCV_INCLUDE_DIR opencv/cv.hpp PATHS ${OPENCV_HOME}/include) macro(FIND_OPENCV_LIBRARY MYLIBRARY MYLIBRARYNAME) # Force first look in OPENCV_HOME, then use CMAKE paths if not found find_library( ${MYLIBRARY} NAMES "${MYLIBRARYNAME}${OPENCV_RELEASE_POSTFIX}" PATHS ${OPENCV_HOME}/lib ${OPENCV_HOME}/share/OpenCV/3rdparty/lib NO_DEFAULT_PATHS) find_library( ${MYLIBRARY} NAMES "${MYLIBRARYNAME}${OPENCV_RELEASE_POSTFIX}") endmacro(FIND_OPENCV_LIBRARY MYLIBRARY MYLIBRARYNAME) # Required FIND_OPENCV_LIBRARY(OPENCV_CORE_LIBRARY opencv_core) FIND_OPENCV_LIBRARY(OPENCV_FEATURES2D_LIBRARY opencv_features2d) FIND_OPENCV_LIBRARY(OPENCV_FLANN_LIBRARY opencv_flann) FIND_OPENCV_LIBRARY(OPENCV_IMGPROC_LIBRARY opencv_imgproc) FIND_OPENCV_LIBRARY(OPENCV_ML_LIBRARY opencv_ml) FIND_OPENCV_LIBRARY(OPENCV_OBJDETECT_LIBRARY opencv_objdetect) FIND_OPENCV_LIBRARY(OPENCV_XFEATURES2D_LIBRARY opencv_xfeatures2d) FIND_OPENCV_LIBRARY(OPENCV_PHOTO_LIBRARY opencv_photo) FIND_OPENCV_LIBRARY(OPENCV_VIDEO_LIBRARY opencv_video) set(OPENCV_LIBRARIES ${OPENCV_OBJDETECT_LIBRARY} ${OPENCV_VIDEO_LIBRARY} ${OPENCV_PHOTO_LIBRARY} ${OPENCV_ML_LIBRARY} ${OPENCV_IMGPROC_LIBRARY} ${OPENCV_FLANN_LIBRARY} ${OPENCV_FEATURES2D_LIBRARY} ${OPENCV_XFEATURES2D_LIBRARY} ${OPENCV_CORE_LIBRARY} ) set(OPENCV_FOUND "NO") if ( OPENCV_INCLUDE_DIR AND OPENCV_CORE_LIBRARY AND OPENCV_FEATURES2D_LIBRARY AND OPENCV_XFEATURES2D_LIBRARY AND OPENCV_FLANN_LIBRARY AND OPENCV_IMGPROC_LIBRARY AND OPENCV_ML_LIBRARY AND OPENCV_OBJDETECT_LIBRARY AND OPENCV_PHOTO_LIBRARY AND OPENCV_VIDEO_LIBRARY) set(OPENCV_FOUND "YES") else() message( WARNING "Could not find all OpenCV libraries. Check the list for NOTFOUND:" ) message( "${OPENCV_LIBRARIES}" ) endif() if (OPENCV_FOUND) FIND_OPENCV_LIBRARY(OPENCV_IPPICV_LIBRARY ippicv) if ( OPENCV_IPPICV_LIBRARY ) set( OPENCV_LIBRARIES ${OPENCV_LIBRARIES} ${OPENCV_IPPICV_LIBRARY} ) else() message( WARNING "Could not find libippicv needed by OpenCV." ) endif() FIND_OPENCV_LIBRARY(OPENCV_ILMIMF_LIBRARY IlmImf) if ( OPENCV_ILMIMF_LIBRARY ) set( OPENCV_LIBRARIES ${OPENCV_LIBRARIES} ${OPENCV_ILMIMF_LIBRARY} ) else() message( WARNING "Could not find IlmImf needed by OpenCV." ) endif() FIND_OPENCV_LIBRARY(OPENCV_LIBTIFF_LIBRARY libtiff) if ( OPENCV_LIBTIFF_LIBRARY ) set( OPENCV_LIBRARIES ${OPENCV_LIBRARIES} ${OPENCV_LIBTIFF_LIBRARY} ) else() message( WARNING "Could not find libtiff needed by OpenCV." ) endif() # Optional FIND_OPENCV_LIBRARY(OPENCV_IMGCODECS_LIBRARY opencv_imgcodecs) FIND_OPENCV_LIBRARY(OPENCV_CUDAARITHM_LIBRARY opencv_cudaarithm) FIND_OPENCV_LIBRARY(OPENCV_CUDAIMGPROC_LIBRARY opencv_cudaimgproc) FIND_OPENCV_LIBRARY(OPENCV_CUDEV_LIBRARY opencv_cudev) FIND_OPENCV_LIBRARY(OPENCV_HIGHGUI_LIBRARY opencv_highgui) set(OPENCV_GPU_FOUND "NO") if ( OPENCV_CUDAARITHM_LIBRARY AND OPENCV_CUDAIMGPROC_LIBRARY AND OPENCV_CUDEV_LIBRARY) set(OPENCV_GPU_FOUND "YES") set(OPENCV_LIBRARIES ${OPENCV_LIBRARIES} ${OPENCV_CUDAARITHM_LIBRARY} ${OPENCV_CUDAIMGPROC_LIBRARY} ${OPENCV_CUDEV_LIBRARY} ) else() message( "Could not find optional OpenCV GPU (CUDA) Libraries. " ) endif() set(OPENCV_IMGCODECS_FOUND "NO") if(OPENCV_IMGCODECS_LIBRARY) set(OPENCV_IMGCODECS_FOUND "YES") set(OPENCV_LIBRARIES ${OPENCV_LIBRARIES} ${OPENCV_IMGCODECS_LIBRARY}) else() message( "Could not find optional OpenCV Image Codecs Library" ) endif() set(OPENCV_HIGHGUI_FOUND 0) if(OPENCV_HIGHGUI_LIBRARY) set(OPENCV_HIGHGUI_FOUND 1) set(OPENCV_LIBRARIES ${OPENCV_LIBRARIES} ${OPENCV_HIGHGUI_LIBRARY}) else() message( "Could not find optional OpenCV HighGui Library" ) endif() # Unfortunately, OpenCV inter-library dependency is so complicated, we just list the libs twice: set(OPENCV_LIBRARIES ${OPENCV_LIBRARIES} ${OPENCV_LIBRARIES} ) endif() if(OPENCV_FOUND) message( STATUS "OPENCV_INCLUDE_DIR = ${OPENCV_INCLUDE_DIR}" ) message( STATUS "OPENCV_LIBRARIES = ${OPENCV_LIBRARIES}" ) endif() ossim-Miami-2.9.1/cmake/CMakeModules/FindOpenJPEG.cmake000066400000000000000000000030551352751253100224610ustar00rootroot00000000000000### # -*- cmake -*- # # File: FindOpenJPEG.cmake # # Original script was copied from: # http://code.google.com/p/emeraldviewer/source/browse/indra/cmake # # $Id$ ### # - Find OpenJPEG # Find the OpenJPEG includes and library # This module defines # OPENJPEG_INCLUDE_DIR, where to find openjpeg.h, etc. # OPENJPEG_LIBRARIES, the libraries needed to use OpenJPEG. # OPENJPEG_FOUND, If false, do not try to use OpenJPEG. # also defined, but not for general use are # OPENJPEG_LIBRARY, where to find the OpenJPEG library. FIND_PATH(OPENJPEG_INCLUDE_DIR openjpeg.h PATH_SUFFIXES openjpeg openjpeg-1.5 openjpeg-2.1 openjpeg-2.3 DOC "Location of OpenJPEG Headers" ) FIND_LIBRARY(MINIZIP_LIBRARY NAMES ${MINIZIP_NAMES} ) MARK_AS_ADVANCED( MINIZIP_LIBRARY MINIZIP_INCLUDE_DIR ) SET(OPENJPEG_NAMES ${OPENJPEG_NAMES} openjp2) SET(OPENJPEG_NAMES ${OPENJPEG_NAMES} openjpeg) FIND_LIBRARY(OPENJPEG_LIBRARY NAMES ${OPENJPEG_NAMES}) IF (OPENJPEG_LIBRARY AND OPENJPEG_INCLUDE_DIR) SET(OPENJPEG_LIBRARIES ${OPENJPEG_LIBRARY}) SET(OPENJPEG_FOUND "YES") ELSE (OPENJPEG_LIBRARY AND OPENJPEG_INCLUDE_DIR) SET(OPENJPEG_FOUND "NO") ENDIF (OPENJPEG_LIBRARY AND OPENJPEG_INCLUDE_DIR) IF (OPENJPEG_FOUND) IF (NOT OPENJPEG_FIND_QUIETLY) MESSAGE(STATUS "Found OpenJPEG: ${OPENJPEG_LIBRARIES}") ENDIF (NOT OPENJPEG_FIND_QUIETLY) ELSE (OPENJPEG_FOUND) IF (OPENJPEG_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find OpenJPEG library") ENDIF (OPENJPEG_FIND_REQUIRED) ENDIF (OPENJPEG_FOUND) MARK_AS_ADVANCED(OPENJPEG_LIBRARY OPENJPEG_INCLUDE_DIR) ossim-Miami-2.9.1/cmake/CMakeModules/FindOssimVideo.cmake000066400000000000000000000021661352751253100231750ustar00rootroot00000000000000# - Find ossimPredator library # Find the native ossimPredator includes and library # This module defines # OSSIMVIDEO_INCLUDE_DIR, where to find tiff.h, etc. # OSSIMVIDEO_LIBRARIES, libraries to link against to use ossimPredator. # OSSIMVIDEO_FOUND, If false, do not try to use ossimPredator. # also defined, but not for general use are # OSSIMVIDEO_LIBRARY, where to find the ossimPredator library. SET(CMAKE_FIND_FRAMEWORK "LAST") FIND_PATH(OSSIMVIDEO_INCLUDE_DIR ossimPredator/ossimPredatorExport.h PATHS ${OSSIM_DEV_HOME}/ossim-video/include) SET(OSSIMVIDEO_NAMES ${OSSIMVIDEO_NAMES} ossim-video ) FIND_LIBRARY(OSSIMVIDEO_LIBRARY NAMES ${OSSIMVIDEO_NAMES}) # handle the QUIETLY and REQUIRED arguments and set OSSIMVIDEO_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(OSSIMVIDEO DEFAULT_MSG OSSIMVIDEO_LIBRARY OSSIMVIDEO_INCLUDE_DIR) IF(OSSIMVIDEO_FOUND) SET( OSSIMVIDEO_LIBRARIES ${OSSIMVIDEO_LIBRARY} ) SET( OSSIMVIDEO_INCLUDES ${OSSIMVIDEO_INCLUDE_DIR} ) ENDIF(OSSIMVIDEO_FOUND) MARK_AS_ADVANCED(OSSIMVIDEO_INCLUDE_DIR OSSIMVIDEO_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindOssimWMS.cmake000066400000000000000000000017061352751253100225740ustar00rootroot00000000000000# - Find wms library # Find the native wms includes and library # This module defines # OSSIMWMS_INCLUDE_DIR, where to find tiff.h, etc. # OSSIMWMS_LIBRARIES, libraries to link against to use WMS. # OSSIMWMS_FOUND, If false, do not try to use WMS. # also defined, but not for general use are # WMS_LIBRARY, where to find the WMS library. SET(CMAKE_FIND_FRAMEWORK "LAST") FIND_PATH(OSSIMWMS_INCLUDE_DIR wms/wms.h PATHS $ENV{OSSIM_DEV_HOME}/ossim-wms/include) SET(OSSIMWMS_NAMES ${OSSIMWMS_NAMES} wms ossim-wms) FIND_LIBRARY(OSSIMWMS_LIBRARY NAMES ${OSSIMWMS_NAMES}) # handle the QUIETLY and REQUIRED arguments and set OSSIMWMS_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(OSSIMWMS DEFAULT_MSG OSSIMWMS_LIBRARY OSSIMWMS_INCLUDE_DIR) IF(OSSIMWMS_FOUND) SET( OSSIMWMS_LIBRARIES ${OSSIMWMS_LIBRARY} ) ENDIF(OSSIMWMS_FOUND) MARK_AS_ADVANCED(OSSIMWMS_INCLUDE_DIR OSSIMWMS_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindPDAL.cmake000066400000000000000000000032331352751253100216300ustar00rootroot00000000000000#--- # File: FindPDAL.cmake # # Find the native Point Data Abstraction Library(PDAL) includes and libraries. # # This module defines: # # PDAL_INCLUDE_DIR, where to find pdal.h, etc. # PDAL_LIBRARIES, libraries to link against to use PDAL and rialto. # PDAL_FOUND, True if found, false if one of the above are not found. # # NOTE: # This script is specialized for ossim, e.g. looking in /usr/local/ossim. # # $Id$ #--- #--- # Find include path: "pdal_defines.h" installs to install "prefix" with pdal # includes under "pdal" sub directory. #--- find_path( PDAL_INCLUDE_DIR pdal/pdal.hpp) find_library(PDAL_CPP_LIBRARY NAMES pdalcpp) find_library(PDAL_UTIL_LIBRARY NAMES pdal_util) find_library(RIALTO_LIBRARY NAMES rialto) find_library(LASZIP_LIBRARY NAMES laszip) message( STATUS "PDAL_INCLUDE_DIR = ${PDAL_INCLUDE_DIR}" ) message( STATUS "PDAL_CPP_LIBRARY = ${PDAL_CPP_LIBRARY}" ) message( STATUS "PDAL_UTIL_LIBRARY = ${PDAL_UTIL_LIBRARY}" ) message( STATUS "RIALTO_LIBRARY = ${RIALTO_LIBRARY}" ) message( STATUS "LASZIP_LIBRARY = ${LASZIP_LIBRARY}" ) set(PDAL_FOUND "NO") if (PDAL_INCLUDE_DIR AND PDAL_CPP_LIBRARY AND PDAL_UTIL_LIBRARY AND RIALTO_LIBRARY AND LASZIP_LIBRARY) set(PDAL_FOUND "YES") set(PDAL_LIBRARIES ${PDAL_CPP_LIBRARY} ${PDAL_UTIL_LIBRARY} ${RIALTO_LIBRARY} ${LASZIP_LIBRARY}) message( STATUS "PDAL_LIBRARIES = ${PDAL_LIBRARIES}" ) else(PDAL_INCLUDE_DIR AND PDAL_CPP_LIBRARY AND PDAL_UTIL_LIBRARY AND RIALTO_LIBRARY AND LASZIP_LIBRARY) message( WARNING "Could not find PDAL" ) endif(PDAL_INCLUDE_DIR AND PDAL_CPP_LIBRARY AND PDAL_UTIL_LIBRARY AND RIALTO_LIBRARY AND LASZIP_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindPackageHandleStandardArgs.cmake000066400000000000000000000347401352751253100260640ustar00rootroot00000000000000#.rst: # FindPackageHandleStandardArgs # ----------------------------- # # # # FIND_PACKAGE_HANDLE_STANDARD_ARGS( ... ) # # This function is intended to be used in FindXXX.cmake modules files. # It handles the REQUIRED, QUIET and version-related arguments to # find_package(). It also sets the _FOUND variable. The # package is considered found if all variables ... listed contain # valid results, e.g. valid filepaths. # # There are two modes of this function. The first argument in both # modes is the name of the Find-module where it is called (in original # casing). # # The first simple mode looks like this: # # :: # # FIND_PACKAGE_HANDLE_STANDARD_ARGS( # (DEFAULT_MSG|"Custom failure message") ... ) # # If the variables to are all valid, then # _FOUND will be set to TRUE. If DEFAULT_MSG is given # as second argument, then the function will generate itself useful # success and error messages. You can also supply a custom error # message for the failure case. This is not recommended. # # The second mode is more powerful and also supports version checking: # # :: # # FIND_PACKAGE_HANDLE_STANDARD_ARGS(NAME # [FOUND_VAR ] # [REQUIRED_VARS ...] # [VERSION_VAR ] # [HANDLE_COMPONENTS] # [CONFIG_MODE] # [FAIL_MESSAGE "Custom failure message"] ) # # In this mode, the name of the result-variable can be set either to # either _FOUND or _FOUND using the # FOUND_VAR option. Other names for the result-variable are not # allowed. So for a Find-module named FindFooBar.cmake, the two # possible names are FooBar_FOUND and FOOBAR_FOUND. It is recommended # to use the original case version. If the FOUND_VAR option is not # used, the default is _FOUND. # # As in the simple mode, if through are all valid, # _FOUND will be set to TRUE. After REQUIRED_VARS the # variables which are required for this package are listed. Following # VERSION_VAR the name of the variable can be specified which holds the # version of the package which has been found. If this is done, this # version will be checked against the (potentially) specified required # version used in the find_package() call. The EXACT keyword is also # handled. The default messages include information about the required # version and the version which has been actually found, both if the # version is ok or not. If the package supports components, use the # HANDLE_COMPONENTS option to enable handling them. In this case, # find_package_handle_standard_args() will report which components have # been found and which are missing, and the _FOUND variable # will be set to FALSE if any of the required components (i.e. not the # ones listed after OPTIONAL_COMPONENTS) are missing. Use the option # CONFIG_MODE if your FindXXX.cmake module is a wrapper for a # find_package(... NO_MODULE) call. In this case VERSION_VAR will be # set to _VERSION and the macro will automatically check whether # the Config module was found. Via FAIL_MESSAGE a custom failure # message can be specified, if this is not used, the default message # will be displayed. # # Example for mode 1: # # :: # # find_package_handle_standard_args(LibXml2 DEFAULT_MSG # LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR) # # # # LibXml2 is considered to be found, if both LIBXML2_LIBRARY and # LIBXML2_INCLUDE_DIR are valid. Then also LIBXML2_FOUND is set to # TRUE. If it is not found and REQUIRED was used, it fails with # FATAL_ERROR, independent whether QUIET was used or not. If it is # found, success will be reported, including the content of . On # repeated Cmake runs, the same message won't be printed again. # # Example for mode 2: # # :: # # find_package_handle_standard_args(LibXslt # FOUND_VAR LibXslt_FOUND # REQUIRED_VARS LibXslt_LIBRARIES LibXslt_INCLUDE_DIRS # VERSION_VAR LibXslt_VERSION_STRING) # # In this case, LibXslt is considered to be found if the variable(s) # listed after REQUIRED_VAR are all valid, i.e. LibXslt_LIBRARIES and # LibXslt_INCLUDE_DIRS in this case. The result will then be stored in # LibXslt_FOUND . Also the version of LibXslt will be checked by using # the version contained in LibXslt_VERSION_STRING. Since no # FAIL_MESSAGE is given, the default messages will be printed. # # Another example for mode 2: # # :: # # find_package(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4) # find_package_handle_standard_args(Automoc4 CONFIG_MODE) # # In this case, FindAutmoc4.cmake wraps a call to find_package(Automoc4 # NO_MODULE) and adds an additional search directory for automoc4. Here # the result will be stored in AUTOMOC4_FOUND. The following # FIND_PACKAGE_HANDLE_STANDARD_ARGS() call produces a proper # success/error message. #============================================================================= # Copyright 2007-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) include(${CMAKE_CURRENT_LIST_DIR}/FindPackageMessage.cmake) include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake) # internal helper macro macro(_FPHSA_FAILURE_MESSAGE _msg) if (${_NAME}_FIND_REQUIRED) message(FATAL_ERROR "${_msg}") else () if (NOT ${_NAME}_FIND_QUIETLY) message(STATUS "${_msg}") endif () endif () endmacro() # internal helper macro to generate the failure message when used in CONFIG_MODE: macro(_FPHSA_HANDLE_FAILURE_CONFIG_MODE) # _CONFIG is set, but FOUND is false, this means that some other of the REQUIRED_VARS was not found: if(${_NAME}_CONFIG) _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: missing: ${MISSING_VARS} (found ${${_NAME}_CONFIG} ${VERSION_MSG})") else() # If _CONSIDERED_CONFIGS is set, the config-file has been found, but no suitable version. # List them all in the error message: if(${_NAME}_CONSIDERED_CONFIGS) set(configsText "") list(LENGTH ${_NAME}_CONSIDERED_CONFIGS configsCount) math(EXPR configsCount "${configsCount} - 1") foreach(currentConfigIndex RANGE ${configsCount}) list(GET ${_NAME}_CONSIDERED_CONFIGS ${currentConfigIndex} filename) list(GET ${_NAME}_CONSIDERED_VERSIONS ${currentConfigIndex} version) set(configsText "${configsText} ${filename} (version ${version})\n") endforeach() if (${_NAME}_NOT_FOUND_MESSAGE) set(configsText "${configsText} Reason given by package: ${${_NAME}_NOT_FOUND_MESSAGE}\n") endif() _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} ${VERSION_MSG}, checked the following files:\n${configsText}") else() # Simple case: No Config-file was found at all: _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: found neither ${_NAME}Config.cmake nor ${_NAME_LOWER}-config.cmake ${VERSION_MSG}") endif() endif() endmacro() function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG) # set up the arguments for CMAKE_PARSE_ARGUMENTS and check whether we are in # new extended or in the "old" mode: set(options CONFIG_MODE HANDLE_COMPONENTS) set(oneValueArgs FAIL_MESSAGE VERSION_VAR FOUND_VAR) set(multiValueArgs REQUIRED_VARS) set(_KEYWORDS_FOR_EXTENDED_MODE ${options} ${oneValueArgs} ${multiValueArgs} ) list(FIND _KEYWORDS_FOR_EXTENDED_MODE "${_FIRST_ARG}" INDEX) if(${INDEX} EQUAL -1) set(FPHSA_FAIL_MESSAGE ${_FIRST_ARG}) set(FPHSA_REQUIRED_VARS ${ARGN}) set(FPHSA_VERSION_VAR) else() CMAKE_PARSE_ARGUMENTS(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN}) if(FPHSA_UNPARSED_ARGUMENTS) message(FATAL_ERROR "Unknown keywords given to FIND_PACKAGE_HANDLE_STANDARD_ARGS(): \"${FPHSA_UNPARSED_ARGUMENTS}\"") endif() if(NOT FPHSA_FAIL_MESSAGE) set(FPHSA_FAIL_MESSAGE "DEFAULT_MSG") endif() endif() # now that we collected all arguments, process them if("x${FPHSA_FAIL_MESSAGE}" STREQUAL "xDEFAULT_MSG") set(FPHSA_FAIL_MESSAGE "Could NOT find ${_NAME}") endif() # In config-mode, we rely on the variable _CONFIG, which is set by find_package() # when it successfully found the config-file, including version checking: if(FPHSA_CONFIG_MODE) list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG) list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS) set(FPHSA_VERSION_VAR ${_NAME}_VERSION) endif() if(NOT FPHSA_REQUIRED_VARS) message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()") endif() list(GET FPHSA_REQUIRED_VARS 0 _FIRST_REQUIRED_VAR) string(TOUPPER ${_NAME} _NAME_UPPER) string(TOLOWER ${_NAME} _NAME_LOWER) if(FPHSA_FOUND_VAR) if(FPHSA_FOUND_VAR MATCHES "^${_NAME}_FOUND$" OR FPHSA_FOUND_VAR MATCHES "^${_NAME_UPPER}_FOUND$") set(_FOUND_VAR ${FPHSA_FOUND_VAR}) else() message(FATAL_ERROR "The argument for FOUND_VAR is \"${FPHSA_FOUND_VAR}\", but only \"${_NAME}_FOUND\" and \"${_NAME_UPPER}_FOUND\" are valid names.") endif() else() set(_FOUND_VAR ${_NAME_UPPER}_FOUND) endif() # collect all variables which were not found, so they can be printed, so the # user knows better what went wrong (#6375) set(MISSING_VARS "") set(DETAILS "") # check if all passed variables are valid unset(${_FOUND_VAR}) foreach(_CURRENT_VAR ${FPHSA_REQUIRED_VARS}) if(NOT ${_CURRENT_VAR}) set(${_FOUND_VAR} FALSE) set(MISSING_VARS "${MISSING_VARS} ${_CURRENT_VAR}") else() set(DETAILS "${DETAILS}[${${_CURRENT_VAR}}]") endif() endforeach() if(NOT "${${_FOUND_VAR}}" STREQUAL "FALSE") set(${_FOUND_VAR} TRUE) endif() # component handling unset(FOUND_COMPONENTS_MSG) unset(MISSING_COMPONENTS_MSG) if(FPHSA_HANDLE_COMPONENTS) foreach(comp ${${_NAME}_FIND_COMPONENTS}) if(${_NAME}_${comp}_FOUND) if(NOT DEFINED FOUND_COMPONENTS_MSG) set(FOUND_COMPONENTS_MSG "found components: ") endif() set(FOUND_COMPONENTS_MSG "${FOUND_COMPONENTS_MSG} ${comp}") else() if(NOT DEFINED MISSING_COMPONENTS_MSG) set(MISSING_COMPONENTS_MSG "missing components: ") endif() set(MISSING_COMPONENTS_MSG "${MISSING_COMPONENTS_MSG} ${comp}") if(${_NAME}_FIND_REQUIRED_${comp}) set(${_FOUND_VAR} FALSE) set(MISSING_VARS "${MISSING_VARS} ${comp}") endif() endif() endforeach() set(COMPONENT_MSG "${FOUND_COMPONENTS_MSG} ${MISSING_COMPONENTS_MSG}") set(DETAILS "${DETAILS}[c${COMPONENT_MSG}]") endif() # version handling: set(VERSION_MSG "") set(VERSION_OK TRUE) set(VERSION ${${FPHSA_VERSION_VAR}}) # check with DEFINED here as the requested or found version may be "0" if (DEFINED ${_NAME}_FIND_VERSION) if(DEFINED ${FPHSA_VERSION_VAR}) if(${_NAME}_FIND_VERSION_EXACT) # exact version required # count the dots in the version string string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${VERSION}") # add one dot because there is one dot more than there are components string(LENGTH "${_VERSION_DOTS}." _VERSION_DOTS) if (_VERSION_DOTS GREATER ${_NAME}_FIND_VERSION_COUNT) # Because of the C++ implementation of find_package() ${_NAME}_FIND_VERSION_COUNT # is at most 4 here. Therefore a simple lookup table is used. if (${_NAME}_FIND_VERSION_COUNT EQUAL 1) set(_VERSION_REGEX "[^.]*") elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 2) set(_VERSION_REGEX "[^.]*\\.[^.]*") elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 3) set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*") else () set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*\\.[^.]*") endif () string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${VERSION}") unset(_VERSION_REGEX) if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _VERSION_HEAD) set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"") set(VERSION_OK FALSE) else () set(VERSION_MSG "(found suitable exact version \"${VERSION}\")") endif () unset(_VERSION_HEAD) else () if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL VERSION) set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"") set(VERSION_OK FALSE) else () set(VERSION_MSG "(found suitable exact version \"${VERSION}\")") endif () endif () unset(_VERSION_DOTS) else() # minimum version specified: if (${_NAME}_FIND_VERSION VERSION_GREATER VERSION) set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"") set(VERSION_OK FALSE) else () set(VERSION_MSG "(found suitable version \"${VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")") endif () endif() else() # if the package was not found, but a version was given, add that to the output: if(${_NAME}_FIND_VERSION_EXACT) set(VERSION_MSG "(Required is exact version \"${${_NAME}_FIND_VERSION}\")") else() set(VERSION_MSG "(Required is at least version \"${${_NAME}_FIND_VERSION}\")") endif() endif() else () if(VERSION) set(VERSION_MSG "(found version \"${VERSION}\")") endif() endif () if(VERSION_OK) set(DETAILS "${DETAILS}[v${VERSION}(${${_NAME}_FIND_VERSION})]") else() set(${_FOUND_VAR} FALSE) endif() # print the result: if (${_FOUND_VAR}) FIND_PACKAGE_MESSAGE(${_NAME} "Found ${_NAME}: ${${_FIRST_REQUIRED_VAR}} ${VERSION_MSG} ${COMPONENT_MSG}" "${DETAILS}") else () if(FPHSA_CONFIG_MODE) _FPHSA_HANDLE_FAILURE_CONFIG_MODE() else() if(NOT VERSION_OK) _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: ${VERSION_MSG} (found ${${_FIRST_REQUIRED_VAR}})") else() _FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} (missing: ${MISSING_VARS}) ${VERSION_MSG}") endif() endif() endif () set(${_FOUND_VAR} ${${_FOUND_VAR}} PARENT_SCOPE) endfunction() ossim-Miami-2.9.1/cmake/CMakeModules/FindPackageMessage.cmake000066400000000000000000000037551352751253100237610ustar00rootroot00000000000000#.rst: # FindPackageMessage # ------------------ # # # # FIND_PACKAGE_MESSAGE( "message for user" "find result details") # # This macro is intended to be used in FindXXX.cmake modules files. It # will print a message once for each unique find result. This is useful # for telling the user where a package was found. The first argument # specifies the name (XXX) of the package. The second argument # specifies the message to display. The third argument lists details # about the find result so that if they change the message will be # displayed again. The macro also obeys the QUIET argument to the # find_package command. # # Example: # # :: # # if(X11_FOUND) # FIND_PACKAGE_MESSAGE(X11 "Found X11: ${X11_X11_LIB}" # "[${X11_X11_LIB}][${X11_INCLUDE_DIR}]") # else() # ... # endif() #============================================================================= # Copyright 2008-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) function(FIND_PACKAGE_MESSAGE pkg msg details) # Avoid printing a message repeatedly for the same find result. if(NOT ${pkg}_FIND_QUIETLY) string(REPLACE "\n" "" details "${details}") set(DETAILS_VAR FIND_PACKAGE_MESSAGE_DETAILS_${pkg}) if(NOT "${details}" STREQUAL "${${DETAILS_VAR}}") # The message has not yet been printed. message(STATUS "${msg}") # Save the find details in the cache to avoid printing the same # message again. set("${DETAILS_VAR}" "${details}" CACHE INTERNAL "Details about finding ${pkg}") endif() endif() endfunction() ossim-Miami-2.9.1/cmake/CMakeModules/FindPodofo.cmake000066400000000000000000000011401352751253100223310ustar00rootroot00000000000000#--- # File: FindPodofo.cmake # # Find the native podofo includes and library # # This module defines: # PODOFO_INCLUDE_DIR, where to find tiff.h, etc. # PODOFO_LIBRARY, library to link against to use PODOFO. # PODOFO_FOUND, If false, do not try to use PODOFO. # # $Id$ #--- # Find include path: find_path(PODOFO_INCLUDE_DIR podofo/podofo.h ) # Find library: find_library(PODOFO_LIBRARY NAMES podofo ) #--- # This function sets PODOFO_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(PODOFO DEFAULT_MSG PODOFO_LIBRARY PODOFO_INCLUDE_DIR) ossim-Miami-2.9.1/cmake/CMakeModules/FindPostgreSQL.cmake000066400000000000000000000176621352751253100231260ustar00rootroot00000000000000#.rst: # FindPostgreSQL # -------------- # # Find the PostgreSQL installation. # # This module defines # # :: # # PostgreSQL_LIBRARIES - the PostgreSQL libraries needed for linking # PostgreSQL_INCLUDE_DIRS - the directories of the PostgreSQL headers # PostgreSQL_LIBRARY_DIRS - the link directories for PostgreSQL libraries # PostgreSQL_VERSION_STRING - the version of PostgreSQL found (since CMake 2.8.8) #============================================================================= # Copyright 2004-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) # ---------------------------------------------------------------------------- # History: # This module is derived from the module originally found in the VTK source tree. # # ---------------------------------------------------------------------------- # Note: # PostgreSQL_ADDITIONAL_VERSIONS is a variable that can be used to set the # version mumber of the implementation of PostgreSQL. # In Windows the default installation of PostgreSQL uses that as part of the path. # E.g C:\Program Files\PostgreSQL\8.4. # Currently, the following version numbers are known to this module: # "9.4" "9.3" "9.2" "9.1" "9.0" "8.4" "8.3" "8.2" "8.1" "8.0" # # To use this variable just do something like this: # set(PostgreSQL_ADDITIONAL_VERSIONS "9.2" "8.4.4") # before calling find_package(PostgreSQL) in your CMakeLists.txt file. # This will mean that the versions you set here will be found first in the order # specified before the default ones are searched. # # ---------------------------------------------------------------------------- # You may need to manually set: # PostgreSQL_INCLUDE_DIR - the path to where the PostgreSQL include files are. # PostgreSQL_LIBRARY_DIR - The path to where the PostgreSQL library files are. # If FindPostgreSQL.cmake cannot find the include files or the library files. # # ---------------------------------------------------------------------------- # The following variables are set if PostgreSQL is found: # PostgreSQL_FOUND - Set to true when PostgreSQL is found. # PostgreSQL_INCLUDE_DIRS - Include directories for PostgreSQL # PostgreSQL_LIBRARY_DIRS - Link directories for PostgreSQL libraries # PostgreSQL_LIBRARIES - The PostgreSQL libraries. # # ---------------------------------------------------------------------------- # If you have installed PostgreSQL in a non-standard location. # (Please note that in the following comments, it is assumed that # points to the root directory of the include directory of PostgreSQL.) # Then you have three options. # 1) After CMake runs, set PostgreSQL_INCLUDE_DIR to /include and # PostgreSQL_LIBRARY_DIR to wherever the library pq (or libpq in windows) is # 2) Use CMAKE_INCLUDE_PATH to set a path to /PostgreSQL<-version>. This will allow find_path() # to locate PostgreSQL_INCLUDE_DIR by utilizing the PATH_SUFFIXES option. e.g. In your CMakeLists.txt file # set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "/include") # 3) Set an environment variable called ${PostgreSQL_ROOT} that points to the root of where you have # installed PostgreSQL, e.g. . # # ---------------------------------------------------------------------------- set(PostgreSQL_INCLUDE_PATH_DESCRIPTION "top-level directory containing the PostgreSQL include directories. E.g /usr/local/include/PostgreSQL/8.4 or C:/Program Files/PostgreSQL/8.4/include") set(PostgreSQL_INCLUDE_DIR_MESSAGE "Set the PostgreSQL_INCLUDE_DIR cmake cache entry to the ${PostgreSQL_INCLUDE_PATH_DESCRIPTION}") set(PostgreSQL_LIBRARY_PATH_DESCRIPTION "top-level directory containing the PostgreSQL libraries.") set(PostgreSQL_LIBRARY_DIR_MESSAGE "Set the PostgreSQL_LIBRARY_DIR cmake cache entry to the ${PostgreSQL_LIBRARY_PATH_DESCRIPTION}") set(PostgreSQL_ROOT_DIR_MESSAGE "Set the PostgreSQL_ROOT system variable to where PostgreSQL is found on the machine E.g C:/Program Files/PostgreSQL/8.4") set(PostgreSQL_KNOWN_VERSIONS ${PostgreSQL_ADDITIONAL_VERSIONS} "9.5" "9.4" "9.3" "9.2" "9.1" "9.0" "8.4" "8.3" "8.2" "8.1" "8.0") # Define additional search paths for root directories. set( PostgreSQL_ROOT_DIRECTORIES ENV PostgreSQL_ROOT ${PostgreSQL_ROOT} ) foreach(suffix ${PostgreSQL_KNOWN_VERSIONS}) if(WIN32) list(APPEND PostgreSQL_LIBRARY_ADDITIONAL_SEARCH_SUFFIXES "PostgreSQL/${suffix}/lib") list(APPEND PostgreSQL_INCLUDE_ADDITIONAL_SEARCH_SUFFIXES "PostgreSQL/${suffix}/include") list(APPEND PostgreSQL_TYPE_ADDITIONAL_SEARCH_SUFFIXES "PostgreSQL/${suffix}/include/server") endif() if(UNIX) list(APPEND PostgreSQL_TYPE_ADDITIONAL_SEARCH_SUFFIXES "postgresql/${suffix}/server") endif() endforeach() # # Look for an installation. # find_path(PostgreSQL_INCLUDE_DIR NAMES libpq-fe.h PATHS # Look in other places. ${PostgreSQL_ROOT_DIRECTORIES} PATH_SUFFIXES pgsql postgresql include ${PostgreSQL_INCLUDE_ADDITIONAL_SEARCH_SUFFIXES} # Help the user find it if we cannot. DOC "The ${PostgreSQL_INCLUDE_DIR_MESSAGE}" ) find_path(PostgreSQL_TYPE_INCLUDE_DIR NAMES catalog/pg_type.h PATHS # Look in other places. ${PostgreSQL_ROOT_DIRECTORIES} PATH_SUFFIXES postgresql pgsql/server postgresql/server include/server ${PostgreSQL_TYPE_ADDITIONAL_SEARCH_SUFFIXES} # Help the user find it if we cannot. DOC "The ${PostgreSQL_INCLUDE_DIR_MESSAGE}" ) # The PostgreSQL library. set (PostgreSQL_LIBRARY_TO_FIND pq) # Setting some more prefixes for the library set (PostgreSQL_LIB_PREFIX "") if ( WIN32 ) set (PostgreSQL_LIB_PREFIX ${PostgreSQL_LIB_PREFIX} "lib") set (PostgreSQL_LIBRARY_TO_FIND ${PostgreSQL_LIB_PREFIX}${PostgreSQL_LIBRARY_TO_FIND}) endif() find_library(PostgreSQL_LIBRARY NAMES ${PostgreSQL_LIBRARY_TO_FIND} PATHS ${PostgreSQL_ROOT_DIRECTORIES} PATH_SUFFIXES lib ${PostgreSQL_LIBRARY_ADDITIONAL_SEARCH_SUFFIXES} # Help the user find it if we cannot. DOC "The ${PostgreSQL_LIBRARY_DIR_MESSAGE}" ) get_filename_component(PostgreSQL_LIBRARY_DIR ${PostgreSQL_LIBRARY} PATH) if (PostgreSQL_INCLUDE_DIR) # Some platforms include multiple pg_config.hs for multi-lib configurations # This is a temporary workaround. A better solution would be to compile # a dummy c file and extract the value of the symbol. file(GLOB _PG_CONFIG_HEADERS "${PostgreSQL_INCLUDE_DIR}/pg_config*.h") foreach(_PG_CONFIG_HEADER ${_PG_CONFIG_HEADERS}) if(EXISTS "${_PG_CONFIG_HEADER}") file(STRINGS "${_PG_CONFIG_HEADER}" pgsql_version_str REGEX "^#define[\t ]+PG_VERSION[\t ]+\".*\"") if(pgsql_version_str) string(REGEX REPLACE "^#define[\t ]+PG_VERSION[\t ]+\"([^\"]*)\".*" "\\1" PostgreSQL_VERSION_STRING "${pgsql_version_str}") break() endif() endif() endforeach() unset(pgsql_version_str) endif() # Did we find anything? include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) find_package_handle_standard_args(PostgreSQL REQUIRED_VARS PostgreSQL_LIBRARY PostgreSQL_INCLUDE_DIR PostgreSQL_TYPE_INCLUDE_DIR VERSION_VAR PostgreSQL_VERSION_STRING) set(PostgreSQL_FOUND ${POSTGRESQL_FOUND}) # Now try to get the include and library path. if(PostgreSQL_FOUND) set(PostgreSQL_INCLUDE_DIRS ${PostgreSQL_INCLUDE_DIR} ${PostgreSQL_TYPE_INCLUDE_DIR} ) set(PostgreSQL_LIBRARY_DIRS ${PostgreSQL_LIBRARY_DIR} ) set(PostgreSQL_LIBRARIES ${PostgreSQL_LIBRARY_TO_FIND}) endif() mark_as_advanced(PostgreSQL_INCLUDE_DIR PostgreSQL_TYPE_INCLUDE_DIR PostgreSQL_LIBRARY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindPotrace.cmake000066400000000000000000000015661352751253100225140ustar00rootroot00000000000000#--- # File: FindPotrace.cmake # # Find the Potrace includes and libraries. # # This module defines: # # POTRACE_INCLUDE_DIR, where to find potracelib.h, etc. # POTRACE_LIBRARIES, libraries to link against to use Potrace and rialto. # POTRACE_FOUND, True if found, false if one of the above are not found. # find_path( POTRACE_INCLUDE_DIR potracelib.h) find_library( POTRACE_LIBRARY NAMES "potrace") message( STATUS "POTRACE_INCLUDE_DIR = ${POTRACE_INCLUDE_DIR}" ) message( STATUS "POTRACE_LIBRARY = ${POTRACE_LIBRARY}" ) set(POTRACE_FOUND "NO") if (POTRACE_INCLUDE_DIR AND POTRACE_LIBRARY ) set(POTRACE_FOUND "YES") set(POTRACE_LIBRARIES ${POTRACE_LIBRARY} ) message( STATUS "POTRACE_LIBRARIES = ${POTRACE_LIBRARIES}" ) else(POTRACE_INCLUDE_DIR AND POTRACE_LIBRARY) message( WARNING "Could not find Potrace" ) endif(POTRACE_INCLUDE_DIR AND POTRACE_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindQt5.cmake000066400000000000000000000155441352751253100215710ustar00rootroot00000000000000# - Find Qt5 # This module can be used to find Qt5. # The most important issues are that Qt5 pkgconfig files are installed with PKG_CONFIG_PATH properly # set, and that Qt5 qmake is available via the system path. # This module defines a number of key variables and macros. # # Below is a detailed list of variables that FindQt5.cmake sets. # QT_FOUND If false, don't try to use Qt. # QT5_FOUND If false, don't try to use Qt5. # # QT_VERSION_MAJOR The major version of Qt found. # QT_VERSION_MINOR The minor version of Qt found. # QT_VERSION_PATCH The patch version of Qt found. # # QT_BINARY_DIR Path to "bin" of Qt4 # QT_DOC_DIR Path to "doc" of Qt4 # # QT_QTCORE_FOUND True if QtCore was found. # QT_QTGUI_FOUND True if QtGui was found. # QT_QTDBUS_FOUND True if QtDBus was found. # QT_QTNETWORK_FOUND True if QtNetwork was found. # QT_QTTEST_FOUND True if QtTest was found. # QT_QTWIDGETS_FOUND True if QtWidgets was found. # QT_QTXML_FOUND True if QtXml was found. # # QT_INCLUDES List of paths to all include directories of Qt5. # QT_INCLUDE_DIR Path to "include" of Qt4 # QT_QTCORE_INCLUDE_DIR Path to "include/QtCore" # QT_QTDBUS_INCLUDE_DIR Path to "include/QtDBus" # QT_QTGUI_INCLUDE_DIR Path to "include/QtGui" # QT_QTNETWORK_INCLUDE_DIR Path to "include/QtNetwork" # QT_QTTEST_INCLUDE_DIR Path to "include/QtTest" # QT_QTWIDGETS_INCLUDE_DIR Path to "include/QtWidgets" # QT_QTXML_INCLUDE_DIR Path to "include/QtXml" # # QT_LIBRARIES List of paths to all libraries of Qt5. # QT_LIBRARY_DIR Path to "lib" of Qt4 # QT_QTCORE_LIBRARY The QtCore library # QT_QTDBUS_LIBRARY The QtDBus library # QT_QTGUI_LIBRARY The QtGui library # QT_QTNETWORK_LIBRARY The QtNetwork library # QT_QTTEST_LIBRARY The QtTest library # QT_QTWIDGETS_LIBRARY The QtWidgets library # QT_QTXML_LIBRARY The QtXml library # # also defined, but NOT for general use are # QT_MOC_EXECUTABLE Where to find the moc tool # QT_CONFIG_FLAGS Flags used when building Qt # Copyright (C) 2001-2009 Kitware, Inc. # Copyright (C) 2011 Collabora Ltd. # Copyright (C) 2011 Nokia Corporation # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. IF(QT_INCLUDES AND QT_LIBRARIES AND QT_MAJOR_VERSION MATCHES 5) # Already in cache, be silent SET(QT_FOUND TRUE) SET(QT5_FOUND TRUE) RETURN() ENDIF(QT_INCLUDES AND QT_LIBRARIES AND QT_MAJOR_VERSION MATCHES 5) IF(NOT QT_QMAKE_EXECUTABLE) FIND_PROGRAM(QT_QMAKE_EXECUTABLE_FINDQT NAMES qmake qmake5 qmake-qt5 PATHS "${QT_SEARCH_PATH}/bin" "$ENV{QTDIR}/bin") SET(QT_QMAKE_EXECUTABLE ${QT_QMAKE_EXECUTABLE_FINDQT} CACHE PATH "Qt qmake program.") ENDIF(NOT QT_QMAKE_EXECUTABLE) EXEC_PROGRAM(${QT_QMAKE_EXECUTABLE} ARGS "-query QT_VERSION" OUTPUT_VARIABLE QTVERSION) IF(NOT QTVERSION MATCHES "5.*") SET(QT_FOUND FALSE) SET(QT5_FOUND FALSE) IF(Qt5_FIND_REQUIRED) MESSAGE(FATAL_ERROR "CMake was unable to find Qt5, put qmake in your path or set QTDIR/QT_QMAKE_EXECUTABLE.") ENDIF(Qt5_FIND_REQUIRED) RETURN() ENDIF(NOT QTVERSION MATCHES "5.*") # FIND_PACKAGE(PkgConfig REQUIRED) IF(NOT Qt5_FIND_COMPONENTS) SET(_COMPONENTS QtCore QtDBus QtGui QtNetwork QtTest QtWidgets QtXml) ELSE(NOT Qt5_FIND_COMPONENTS) SET(_COMPONENTS ${Qt5_FIND_COMPONENTS}) ENDIF(NOT Qt5_FIND_COMPONENTS) FOREACH(_COMPONENT ${_COMPONENTS}) STRING(TOUPPER ${_COMPONENT} _COMPONENT_UPPER) IF(NOT QT_${_COMPONENT_UPPER}_FOUND) IF(Qt5_FIND_REQUIRED) PKG_CHECK_MODULES(PC_${_COMPONENT} REQUIRED ${_COMPONENT}>=${QT_MIN_VERSION}) ELSE(Qt5_FIND_REQUIRED) PKG_CHECK_MODULES(PC_${_COMPONENT} QUIET ${_COMPONENT}>=${QT_MIN_VERSION}) ENDIF(Qt5_FIND_REQUIRED) SET(QT_${_COMPONENT_UPPER}_INCLUDE_DIR ${PC_${_COMPONENT}_INCLUDE_DIRS}) FIND_LIBRARY(QT_${_COMPONENT_UPPER}_LIBRARY NAMES ${_COMPONENT} HINTS ${PC_${_COMPONENT}_LIBDIR}) SET(QT_${_COMPONENT_UPPER}_FOUND ${PC_${_COMPONENT}_FOUND}) #MESSAGE(STATUS "COMPONENT ${_COMPONENT_UPPER}:") #MESSAGE(STATUS " QT_${_COMPONENT_UPPER}_LIBRARY: ${QT_${_COMPONENT_UPPER}_LIBRARY}") #MESSAGE(STATUS " QT_${_COMPONENT_UPPER}_INCLUDE_DIR: ${QT_${_COMPONENT_UPPER}_INCLUDE_DIR}") #MESSAGE(STATUS " QT_${_COMPONENT_UPPER}_FOUND: ${QT_${_COMPONENT_UPPER}_FOUND}") SET(QT_INCLUDES ${QT_INCLUDES} ${QT_${_COMPONENT_UPPER}_INCLUDE_DIR}) SET(QT_LIBRARIES ${QT_LIBRARIES} ${QT_${_COMPONENT_UPPER}_INCLUDE_DIR}) MARK_AS_ADVANCED(QT_${_COMPONENT_UPPER}_LIBRARY QT_${_COMPONENT_UPPER}_INCLUDE_DIR) ENDIF(NOT QT_${_COMPONENT_UPPER}_FOUND) ENDFOREACH(_COMPONENT) #MESSAGE(STATUS "QT_LIBRARIES: ${QT_LIBRARIES}") #MESSAGE(STATUS "QT_INCLUDES: ${QT_INCLUDES}") STRING(REGEX REPLACE "^([0-9]+)\\.[0-9]+\\.[0-9]+.*" "\\1" QT_VERSION_MAJOR "${QTVERSION}") STRING(REGEX REPLACE "^[0-9]+\\.([0-9])+\\.[0-9]+.*" "\\1" QT_VERSION_MINOR "${QTVERSION}") STRING(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" QT_VERSION_PATCH "${QTVERSION}") IF(NOT QT_INCLUDE_DIR) EXEC_PROGRAM(${QT_QMAKE_EXECUTABLE} ARGS "-query QT_INSTALL_HEADERS" OUTPUT_VARIABLE QTHEADERS) SET(QT_INCLUDE_DIR ${QTHEADERS} CACHE INTERNAL "" FORCE) ENDIF(NOT QT_INCLUDE_DIR) IF(NOT QT_LIBRARY_DIR) EXEC_PROGRAM(${QT_QMAKE_EXECUTABLE} ARGS "-query QT_INSTALL_LIBS" OUTPUT_VARIABLE QTLIBS) SET(QT_LIBRARY_DIR ${QTLIBS} CACHE INTERNAL "" FORCE) ENDIF(NOT QT_LIBRARY_DIR) IF(NOT QT_BINARY_DIR) EXEC_PROGRAM(${QT_QMAKE_EXECUTABLE} ARGS "-query QT_INSTALL_BINS" OUTPUT_VARIABLE QTBINS) SET(QT_BINARY_DIR ${QTBINS} CACHE INTERNAL "" FORCE) ENDIF(NOT QT_BINARY_DIR) IF(NOT QT_DOC_DIR) EXEC_PROGRAM(${QT_QMAKE_EXECUTABLE} ARGS "-query QT_INSTALL_DOCS" OUTPUT_VARIABLE QTDOCS) SET(QT_DOC_DIR ${QTDOCS} CACHE INTERNAL "" FORCE) ENDIF(NOT QT_DOC_DIR) IF(NOT QT_MOC_EXECUTABLE) FIND_PROGRAM(QT_MOC_EXECUTABLE NAMES moc moc5 moc-qt5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH NO_CMAKE_FIND_ROOT_PATH) ENDIF(NOT QT_MOC_EXECUTABLE) MARK_AS_ADVANCED(QT_INCLUDES QT_INCLUDE_DIR QT_LIBRARIES QT_LIBRARY_DIR QT_BINARY_DIR QT_DOC_DIR QT_QMAKE_EXECUTABLE_FINDQT QT_QMAKE_EXECUTABLE QT_MOC_EXECUTABLE) # Invokes pkgconfig, cleans up the result and sets variables #EXECUTE_PROCESS(COMMAND ${PKG_CONFIG_EXECUTABLE} --variable qt_config QtCore # OUTPUT_VARIABLE _pkgconfig_flags # RESULT_VARIABLE _pkgconfig_failed) #STRING(REPLACE " " ";" QT_CONFIG_FLAGS "${_pkgconfig_flags}") INCLUDE(Qt5Macros) SET(QT_FOUND TRUE) SET(QT5_FOUND TRUE) ossim-Miami-2.9.1/cmake/CMakeModules/FindRapier.cmake000066400000000000000000000014541352751253100223350ustar00rootroot00000000000000#--- # File: FindRapier.cmake # # Find the native rapier includes and library # # This module defines # RAPIER_INCLUDE_DIR, where to find tiff.h, etc. # RAPIER_LIBRARIES, libraries to link against to use RAPIER. # RAPIER_FOUND, If false, do not try to use RAPIER. # also defined, but not for general use are # RAPIER_LIBRARY, where to find the RAPIER library. # # $Id$ #--- find_path(RAPIER_INCLUDE_DIR rapier/common/rapierConstants.h PATHS $ENV{OSSIM_DEV_HOME}/Rapier/include) find_library(RAPIER_LIBRARY NAMES rapier) #--- # This function sets RAPIER_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(RAPIER DEFAULT_MSG RAPIER_LIBRARY RAPIER_INCLUDE_DIR) if(RAPIER_FOUND) set( RAPIER_LIBRARIES ${RAPIER_LIBRARY} ) endif(RAPIER_FOUND) ossim-Miami-2.9.1/cmake/CMakeModules/FindRegex.cmake000066400000000000000000000040461352751253100221650ustar00rootroot00000000000000# -*- cmake -*- # # FindRegex.cmake: Try to find Regex # # Copyright (C) 2005-2013 EDF-EADS-Phimeca # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # along with this library. If not, see . # # @author dutka # @date 2010-02-04 16:44:49 +0100 (Thu, 04 Feb 2010) # # # - Try to find Regex # Once done this will define # # REGEX_FOUND - System has Regex # REGEX_INCLUDE_DIR - The Regex include directory # REGEX_LIBRARIES - The libraries needed to use Regex # REGEX_DEFINITIONS - Compiler switches required for using Regex IF (REGEX_INCLUDE_DIR AND REGEX_LIBRARIES) # in cache already SET(Regex_FIND_QUIETLY TRUE) ENDIF (REGEX_INCLUDE_DIR AND REGEX_LIBRARIES) #IF (NOT WIN32) # # use pkg-config to get the directories and then use these values # # in the FIND_PATH() and FIND_LIBRARY() calls # FIND_PACKAGE(PkgConfig) # PKG_CHECK_MODULES(PC_REGEX regex) # SET(REGEX_DEFINITIONS ${PC_REGEX_CFLAGS_OTHER}) #ENDIF (NOT WIN32) FIND_PATH(REGEX_INCLUDE_DIR regex.h HINTS ${REGEX_INCLUDEDIR} ${PC_LIBXML_INCLUDE_DIRS} PATH_SUFFIXES regex ) FIND_LIBRARY(REGEX_LIBRARIES NAMES c regex HINTS ${PC_REGEX_LIBDIR} ${PC_REGEX_LIBRARY_DIRS} ) INCLUDE(FindPackageHandleStandardArgs) # handle the QUIETLY and REQUIRED arguments and set REGEX_FOUND to TRUE if # all listed variables are TRUE FIND_PACKAGE_HANDLE_STANDARD_ARGS(Regex DEFAULT_MSG REGEX_LIBRARIES REGEX_INCLUDE_DIR) MARK_AS_ADVANCED(REGEX_INCLUDE_DIR REGEX_LIBRARIES) ossim-Miami-2.9.1/cmake/CMakeModules/FindSQLITE.cmake000066400000000000000000000031221352751253100221060ustar00rootroot00000000000000#--- # File: FindSQLITE.cmake # # Find the native SQLite includes and libraries. # # This module defines: # # SQLITE_INCLUDE_DIR, where to find sqlite3.h, etc. # SQLITE_LIBRARY, libraries to link against to use SQLITE. # SQLITE_FOUND, True if found, false if one of the above are not found. # # For ossim, typically SQLite will be system installed which should be found; # or found in the ossim 3rd party dependencies directory from a SQLite build # and install. If the latter it will rely on CMAKE_INCLUDE_PATH and # CMAKE_LIBRARY_PATH having the path to the party dependencies directory. # # $Id$ #--- #--- # Find include path: #--- find_path( SQLITE_INCLUDE_DIR sqlite3.h) # Find SQLITE library: find_library( SQLITE_LIB NAMES sqlite3) # Set the SQLITE_LIBRARY: if( SQLITE_LIB ) set( SQLITE_LIBRARY ${SQLITE_LIB} CACHE STRING INTERNAL ) endif(SQLITE_LIB ) #--- # This function sets SQLITE_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( SQLITE DEFAULT_MSG SQLITE_LIBRARY SQLITE_INCLUDE_DIR ) if( SQLITE_FOUND ) if( NOT SQLITE_FIND_QUIETLY ) message( STATUS "Found SQLITE..." ) endif( NOT SQLITE_FIND_QUIETLY ) else( SQLITE_FOUND ) if( NOT SQLITE_FIND_QUIETLY ) message( WARNING "Could not find SQLITE" ) endif( NOT SQLITE_FIND_QUIETLY ) endif( SQLITE_FOUND ) if( NOT SQLITE_FIND_QUIETLY ) message( STATUS "SQLITE_INCLUDE_DIR=${SQLITE_INCLUDE_DIR}" ) message( STATUS "SQLITE_LIBRARY=${SQLITE_LIBRARY}" ) endif( NOT SQLITE_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindStlPort.cmake000077500000000000000000000015251352751253100225240ustar00rootroot00000000000000#--- # $Id$ # # Find the stlport includes and library # # This module defines: # STLPORT_INCLUDE_DIR, where to find iostream, string, etc. # STLPORT_LIBRARIES, libraries to link against to use StlPort. # STLPORT_FOUND, If false, do not try to use STLPORT. #--- FIND_PATH(STLPORT_INCLUDE_DIR iostream PATHS C:/STLport-5.2.1/stlport D:/STLport-5.2.1/stlport) SET(STLPORT_NAMES ${STLPORT_NAMES} stlport5.2.lib) FIND_LIBRARY(STLPORT_LIBRARY NAMES ${STLPORT_NAMES} ) # handle the QUIETLY and REQUIRED arguments and set STLPORT_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(STLPORT DEFAULT_MSG STLPORT_LIBRARY STLPORT_INCLUDE_DIR) IF(STLPORT_FOUND) SET( STLPORT_LIBRARIES ${STLPORT_LIBRARY} ) ENDIF(STLPORT_FOUND) MARK_AS_ADVANCED(STLPORT_INCLUDE_DIR STLPORT_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindSubversion.cmake000066400000000000000000000145311352751253100232520ustar00rootroot00000000000000# - Extract information from a subversion working copy # The module defines the following variables: # Subversion_SVN_EXECUTABLE - path to svn command line client # Subversion_VERSION_SVN - version of svn command line client # Subversion_FOUND - true if the command line client was found # SUBVERSION_FOUND - same as Subversion_FOUND, set for compatiblity reasons # # The minimum required version of Subversion can be specified using the # standard syntax, e.g. FIND_PACKAGE(Subversion 1.4) # # If the command line client executable is found two macros are defined: # Subversion_WC_INFO( ) # Subversion_WC_LOG( ) # Subversion_WC_INFO extracts information of a subversion working copy at # a given location. This macro defines the following variables: # _WC_URL - url of the repository (at ) # _WC_ROOT - root url of the repository # _WC_REVISION - current revision # _WC_LAST_CHANGED_AUTHOR - author of last commit # _WC_LAST_CHANGED_DATE - date of last commit # _WC_LAST_CHANGED_REV - revision of last commit # _WC_INFO - output of command `svn info ' # Subversion_WC_LOG retrieves the log message of the base revision of a # subversion working copy at a given location. This macro defines the # variable: # _LAST_CHANGED_LOG - last log of base revision # Example usage: # FIND_PACKAGE(Subversion) # IF(SUBVERSION_FOUND) # Subversion_WC_INFO(${PROJECT_SOURCE_DIR} Project) # MESSAGE("Current revision is ${Project_WC_REVISION}") # Subversion_WC_LOG(${PROJECT_SOURCE_DIR} Project) # MESSAGE("Last changed log is ${Project_LAST_CHANGED_LOG}") # ENDIF(SUBVERSION_FOUND) # # History (yyyymmdd): # 20121002 - Modified to "continue on" if svn is not found. (drb) # #============================================================================= # Copyright 2006-2009 Kitware, Inc. # Copyright 2006 Tristan Carel # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) FIND_PROGRAM(Subversion_SVN_EXECUTABLE svn DOC "subversion command line client") MARK_AS_ADVANCED(Subversion_SVN_EXECUTABLE) IF(Subversion_SVN_EXECUTABLE) # the subversion commands should be executed with the C locale, otherwise # the message (which are parsed) may be translated, Alex SET(_Subversion_SAVED_LC_ALL "$ENV{LC_ALL}") SET(ENV{LC_ALL} C) EXECUTE_PROCESS(COMMAND ${Subversion_SVN_EXECUTABLE} --version OUTPUT_VARIABLE Subversion_VERSION_SVN OUTPUT_STRIP_TRAILING_WHITESPACE) # restore the previous LC_ALL SET(ENV{LC_ALL} ${_Subversion_SAVED_LC_ALL}) STRING(REGEX REPLACE "^(.*\n)?svn, version ([.0-9]+).*" "\\2" Subversion_VERSION_SVN "${Subversion_VERSION_SVN}") MACRO(Subversion_WC_INFO dir prefix) # the subversion commands should be executed with the C locale, otherwise # the message (which are parsed) may be translated, Alex SET(_Subversion_SAVED_LC_ALL "$ENV{LC_ALL}") SET(ENV{LC_ALL} C) EXECUTE_PROCESS(COMMAND ${Subversion_SVN_EXECUTABLE} info ${dir} OUTPUT_VARIABLE ${prefix}_WC_INFO ERROR_VARIABLE Subversion_svn_info_error RESULT_VARIABLE Subversion_svn_info_result OUTPUT_STRIP_TRAILING_WHITESPACE) IF(NOT ${Subversion_svn_info_result} EQUAL 0) MESSAGE(WARNING "Command \"${Subversion_SVN_EXECUTABLE} info ${dir}\" failed with output:\n${Subversion_svn_info_error}") ELSE(NOT ${Subversion_svn_info_result} EQUAL 0) STRING(REGEX REPLACE "^(.*\n)?URL: ([^\n]+).*" "\\2" ${prefix}_WC_URL "${${prefix}_WC_INFO}") STRING(REGEX REPLACE "^(.*\n)?Repository Root: ([^\n]+).*" "\\2" ${prefix}_WC_ROOT "${${prefix}_WC_INFO}") STRING(REGEX REPLACE "^(.*\n)?Revision: ([^\n]+).*" "\\2" ${prefix}_WC_REVISION "${${prefix}_WC_INFO}") STRING(REGEX REPLACE "^(.*\n)?Last Changed Author: ([^\n]+).*" "\\2" ${prefix}_WC_LAST_CHANGED_AUTHOR "${${prefix}_WC_INFO}") STRING(REGEX REPLACE "^(.*\n)?Last Changed Rev: ([^\n]+).*" "\\2" ${prefix}_WC_LAST_CHANGED_REV "${${prefix}_WC_INFO}") STRING(REGEX REPLACE "^(.*\n)?Last Changed Date: ([^\n]+).*" "\\2" ${prefix}_WC_LAST_CHANGED_DATE "${${prefix}_WC_INFO}") ENDIF(NOT ${Subversion_svn_info_result} EQUAL 0) # restore the previous LC_ALL SET(ENV{LC_ALL} ${_Subversion_SAVED_LC_ALL}) ENDMACRO(Subversion_WC_INFO) MACRO(Subversion_WC_LOG dir prefix) # This macro can block if the certificate is not signed: # svn ask you to accept the certificate and wait for your answer # This macro requires a svn server network access (Internet most of the time) # and can also be slow since it access the svn server EXECUTE_PROCESS(COMMAND ${Subversion_SVN_EXECUTABLE} --non-interactive log -r BASE ${dir} OUTPUT_VARIABLE ${prefix}_LAST_CHANGED_LOG ERROR_VARIABLE Subversion_svn_log_error RESULT_VARIABLE Subversion_svn_log_result OUTPUT_STRIP_TRAILING_WHITESPACE) IF(NOT ${Subversion_svn_log_result} EQUAL 0) MESSAGE(SEND_ERROR "Command \"${Subversion_SVN_EXECUTABLE} log -r BASE ${dir}\" failed with output:\n${Subversion_svn_log_error}") ENDIF(NOT ${Subversion_svn_log_result} EQUAL 0) ENDMACRO(Subversion_WC_LOG) ENDIF(Subversion_SVN_EXECUTABLE) #--- # This function sets GEOS_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( SUBVERSION DEFAULT_MSG Subversion_SVN_EXECUTABLE Subversion_VERSION_SVN ) if( SUBVERSION_FOUND ) if( NOT SUBVERSION_FIND_QUIETLY ) message( STATUS "Found SUBVERSION..." ) endif( NOT SUBVERSION_FIND_QUIETLY ) else( SUBVERSION_FOUND ) if( NOT SUBVERSION_FIND_QUIETLY ) message( WARNING "Could not find SUBVERSION" ) endif( NOT SUBVERSION_FIND_QUIETLY ) endif( SUBVERSION_FOUND ) if( NOT SUBVERSION_FIND_QUIETLY ) message( STATUS "Subversion_VERSION_SVN=${Subversion_VERSION_SVN}" ) endif( NOT SUBVERSION_FIND_QUIETLY ) ossim-Miami-2.9.1/cmake/CMakeModules/FindTIFF.cmake000066400000000000000000000032151352751253100216400ustar00rootroot00000000000000# - Find TIFF library # Find the native TIFF includes and library # This module defines # TIFF_INCLUDE_DIR, where to find tiff.h, etc. # TIFF_LIBRARIES, libraries to link against to use TIFF. # TIFF_FOUND, If false, do not try to use TIFF. # also defined, but not for general use are # TIFF_LIBRARY, where to find the TIFF library. #============================================================================= # Copyright 2002-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) FIND_PATH(TIFF_INCLUDE_DIR tiff.h PATHS $ENV{TIFF_DIR}/include $ENV{TIFF_DIR}/include/tiff) SET(TIFF_NAMES ${TIFF_NAMES} tiff libtiff_i libtiff tiff3 libtiff3) FIND_LIBRARY(TIFF_LIBRARY NAMES ${TIFF_NAMES} PATHS $ENV{TIFF_DIR}/lib $ENV{TIFF_DIR}/lib64) # handle the QUIETLY and REQUIRED arguments and set TIFF_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(TIFF DEFAULT_MSG TIFF_LIBRARY TIFF_INCLUDE_DIR) IF(TIFF_FOUND) SET( TIFF_LIBRARIES ${TIFF_LIBRARY} ) ENDIF(TIFF_FOUND) MARK_AS_ADVANCED(TIFF_INCLUDE_DIR TIFF_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/Findossim.cmake000066400000000000000000000031261352751253100222430ustar00rootroot00000000000000#--- # File: FindOSSIM.cmake # # Find OSSIM(Open Source Software Image Map) includes and libraries. # # This module defines: # # OSSIM_INCLUDE_DIR, Where to find ossimVersion.h, etc. # OSSIM_LIBRARIES, Libraries to link against to use OSSIM. # OSSIM_FOUND, True if found, false if one of the above are not found. # also defined, but not for general use are # OSSIM_LIBRARY, where to find the OSSIM library. #--- #--- # Find include path: #--- set(CMAKE_FIND_FRAMEWORK "LAST") find_path(OSSIM_INCLUDE_DIR ossim/ossimVersion.h ossimVersion.h PATHS $ENV{OSSIM_DEV_HOME}/ossim/include $ENV{OSSIM_INSTALL_PREFIX}/include ) set(OSSIM_NAMES ${OSSIM_NAMES} ossim libossim) find_library(OSSIM_LIBRARY NAMES ${OSSIM_NAMES} PATHS $ENV{OSSIM_BUILD_DIR}/lib $ENV{OSSIM_INSTALL_PREFIX}/lib) #--- # This function sets OSSIM_FOUND if variables are valid. #--- include(FindPackageHandleStandardArgs) find_package_handle_standard_args( OSSIM DEFAULT_MSG OSSIM_LIBRARY OSSIM_INCLUDE_DIR ) if(OSSIM_FOUND) set( OSSIM_LIBRARIES ${OSSIM_LIBRARY} ) set( OSSIM_INCLUDES ${OSSIM_INCLUDE_DIR} ) else( OSSIM_FOUND ) if( NOT OSSIM_FIND_QUIETLY ) message( WARNING "Could not find OSSIM" ) endif( NOT OSSIM_FIND_QUIETLY ) endif(OSSIM_FOUND) if( NOT OSSIM_FIND_QUIETLY ) message( STATUS "OSSIM_INCLUDE_DIR=${OSSIM_INCLUDE_DIR}" ) message( STATUS "OSSIM_LIBRARY=${OSSIM_LIBRARY}" ) endif( NOT OSSIM_FIND_QUIETLY ) MARK_AS_ADVANCED(OSSIM_INCLUDES OSSIM_INCLUDE_DIR OSSIM_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/FindossimPlanet.cmake000066400000000000000000000020251352751253100234040ustar00rootroot00000000000000# - Find ossimPlanet library # Find the native ossimPlanet includes and library # This module defines # OSSIMPLANET_INCLUDE_DIR, where to find tiff.h, etc. # OSSIMPLANET_LIBRARIES, libraries to link against to use OSSIM. # OSSIMPLANET_FOUND, If false, do not try to use OSSIM. # also defined, but not for general use are # OSSIMPLANET_LIBRARY, where to find the OSSIM library. SET(CMAKE_FIND_FRAMEWORK "LAST") FIND_PATH(OSSIMPLANET_INCLUDE_DIR ossimPlanet/ossimPlanetExport.h ossimPlanetExport.h) SET(OSSIMPLANET_NAMES ${OSSIMPLANET_NAMES} ossimPlanet ) FIND_LIBRARY(OSSIMPLANET_LIBRARY NAMES ${OSSIMPLANET_NAMES}) # handle the QUIETLY and REQUIRED arguments and set OSSIMPLANET_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(OSSIMPLANET DEFAULT_MSG OSSIMPLANET_LIBRARY OSSIMPLANET_INCLUDE_DIR) IF(OSSIMPLANET_FOUND) SET( OSSIMPLANET_LIBRARIES ${OSSIMPLANET_LIBRARY} ) ENDIF(OSSIMPLANET_FOUND) MARK_AS_ADVANCED(OSSIMPLANET_INCLUDE_DIR OSSIMPLANET_LIBRARY) ossim-Miami-2.9.1/cmake/CMakeModules/OssimCPack.cmake000066400000000000000000000151021352751253100223010ustar00rootroot00000000000000# This script sets up packaging targets for each "COMPONENT" as specified in INSTALL commands # # for each component a CPackConfig-.cmake is generated in the build tree # and a target is added to call cpack for it (e.g. package_ossim # A target for generating a package with everything that gets INSTALLED is generated (package_ossim-all) # A target for making all of the above packages is generated (package_ALL) # # package filenames are created on the form --[-]-[-static].tgz # ...where compiler optionally set using a cmake gui (OSSIM_CPACK_COMPILER). This script tries to guess compiler version for msvc generators # ...build_type matches CMAKE_BUILD_TYPE for all generators but the msvc ones # resolve architecture. The reason i "change" i686 to i386 is that debian packages # require i386 so this is for the future IF("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686") SET(SYSTEM_ARCH "i386") ELSE() SET(SYSTEM_ARCH ${CMAKE_SYSTEM_PROCESSOR}) ENDIF() # set a default system name - use CMake setting (Linux|Windows|...) SET(SYSTEM_NAME ${CMAKE_SYSTEM_NAME}) #message(STATUS "CMAKE_SYSTEM_NAME ${CMAKE_SYSTEM_NAME}") #message(STATUS "CMAKE_SYSTEM_PROCESSOR ${CMAKE_SYSTEM_PROCESSOR}") # for msvc the SYSTEM_NAME is set win32/64 instead of "Windows" IF(MSVC) IF(CMAKE_CL_64) SET(SYSTEM_NAME "win64") ELSE() SET(SYSTEM_NAME "win32") ENDIF() ENDIF() # Guess the compiler (is this desired for other platforms than windows?) IF(NOT DEFINED OSSIM_CPACK_COMPILER) INCLUDE(OssimDetermineCompiler) ENDIF() # expose the compiler setting to the user SET(OSSIM_CPACK_COMPILER "${OSSIM_COMPILER}" CACHE STRING "This ia short string (vc90, vc80sp1, gcc-4.3, ...) describing your compiler. The string is used for creating package filenames") IF(OSSIM_CPACK_COMPILER) SET(OSSIM_CPACK_SYSTEM_SPEC_STRING ${SYSTEM_NAME}-${SYSTEM_ARCH}-${OSSIM_CPACK_COMPILER}) ELSE() SET(OSSIM_CPACK_SYSTEM_SPEC_STRING ${SYSTEM_NAME}-${SYSTEM_ARCH}) ENDIF() ## variables that apply to all packages SET(CPACK_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME}-${OSSIM_VERSION}") IF(NOT CPACK_GENERATOR) # these goes for all platforms. Setting these stops the CPack.cmake script from generating options about other package compression formats (.z .tz, etc.) IF(WIN32) SET(CPACK_GENERATOR "ZIP") SET(CPACK_SOURCE_GENERATOR "ZIP") ELSEIF(APPLE) # SET(CPACK_GENERATOR "PackageMaker") # SET(CPACK_SOURCE_GENERATOR "PackageMaker") SET(CPACK_GENERATOR "TGZ") SET(CPACK_SOURCE_GENERATOR "TGZ") ELSE() SET(CPACK_GENERATOR "TGZ") SET(CPACK_SOURCE_GENERATOR "TGZ") ENDIF() ENDIF(NOT CPACK_GENERATOR) # for ms visual studio we use it's internally defined variable to get the configuration (debug,release, ...) IF(MSVC_IDE) SET(OSSIM_CPACK_CONFIGURATION "$(OutDir)") SET(PACKAGE_TARGET_PREFIX "Package ") ELSE() # on un*x an empty CMAKE_BUILD_TYPE means release IF(CMAKE_BUILD_TYPE) SET(OSSIM_CPACK_CONFIGURATION ${CMAKE_BUILD_TYPE}) ELSE() SET(OSSIM_CPACK_CONFIGURATION "Release") ENDIF() SET(PACKAGE_TARGET_PREFIX "package_") ENDIF() # Get all defined components GET_CMAKE_PROPERTY(CPACK_COMPONENTS_ALL COMPONENTS) IF(NOT CPACK_COMPONENTS_ALL) # cmake 2.6.0 don't supply the COMPONENTS property. # I set it manually to be the packages that can always be packaged MESSAGE("When building packages please consider using cmake version 2.6.1 or above") SET(CPACK_COMPONENTS_ALL ossim) ENDIF() # Create a target that will be used to generate all packages defined below SET(PACKAGE_ALL_TARGETNAME "${PACKAGE_TARGET_PREFIX}ALL") ADD_CUSTOM_TARGET(${PACKAGE_ALL_TARGETNAME}) MACRO(GENERATE_PACKAGING_TARGET package_name) SET(CPACK_PACKAGE_NAME ${package_name}) # the doc packages don't need a system-arch specification IF(${package} MATCHES -doc) SET(OSSIM_PACKAGE_FILE_NAME ${package_name}-${OSSIM_VERSION}) ELSE() SET(OSSIM_PACKAGE_FILE_NAME ${package_name}-${OSSIM_VERSION}-${OSSIM_CPACK_SYSTEM_SPEC_STRING}-${OSSIM_CPACK_CONFIGURATION}) IF(NOT BUILD_SHARED_LIBS) SET(OSSIM_PACKAGE_FILE_NAME ${OSSIM_PACKAGE_FILE_NAME}-static) ENDIF() ENDIF() CONFIGURE_FILE("${${PROJECT_NAME}_SOURCE_DIR}/CMakeModules/OssimCPackConfig.cmake.in" "${${PROJECT_NAME}_BINARY_DIR}/CPackConfig-${package_name}.cmake" IMMEDIATE) SET(PACKAGE_TARGETNAME "${PACKAGE_TARGET_PREFIX}${package_name}") # This is naive and will probably need fixing eventually IF(MSVC) SET(MOVE_COMMAND "move") ELSE() SET(MOVE_COMMAND "mv") ENDIF() IF(NOT ACHIVE_EXT) # Set in and out archive filenames. Windows = zip, others = tgz IF(WIN32) SET(ARCHIVE_EXT "zip") ELSEIF(APPLE) # SET(ARCHIVE_EXT "dmg") SET(ARCHIVE_EXT "tar.gz") ELSE() SET(ARCHIVE_EXT "tar.gz") ENDIF() ENDIF(NOT ACHIVE_EXT) # Create a target that creates the current package # and rename the package to give it proper filename ADD_CUSTOM_TARGET(${PACKAGE_TARGETNAME}) ADD_CUSTOM_COMMAND(TARGET ${PACKAGE_TARGETNAME} COMMAND ${CMAKE_CPACK_COMMAND} -C ${OSSIM_CPACK_CONFIGURATION} --config ${${PROJECT_NAME}_BINARY_DIR}/CPackConfig-${package_name}.cmake COMMAND "${MOVE_COMMAND}" "${CPACK_PACKAGE_FILE_NAME}.${ARCHIVE_EXT}" "${OSSIM_PACKAGE_FILE_NAME}.${ARCHIVE_EXT}" COMMAND ${CMAKE_COMMAND} -E echo "renamed ${CPACK_PACKAGE_FILE_NAME}.${ARCHIVE_EXT} -> ${OSSIM_PACKAGE_FILE_NAME}.${ARCHIVE_EXT}" COMMENT "Run CPack packaging for ${package_name}..." ) # Add the exact same custom command to the all package generating target. # I can't use add_dependencies to do this because it would allow parallel building of packages so am going brute here ADD_CUSTOM_COMMAND(TARGET ${PACKAGE_ALL_TARGETNAME} COMMAND ${CMAKE_CPACK_COMMAND} -C ${OSSIM_CPACK_CONFIGURATION} --config ${${PROJECT_NAME}_BINARY_DIR}/CPackConfig-${package_name}.cmake COMMAND "${MOVE_COMMAND}" "${CPACK_PACKAGE_FILE_NAME}.${ARCHIVE_EXT}" "${OSSIM_PACKAGE_FILE_NAME}.${ARCHIVE_EXT}" COMMAND ${CMAKE_COMMAND} -E echo "renamed ${CPACK_PACKAGE_FILE_NAME}.${ARCHIVE_EXT} -> ${OSSIM_PACKAGE_FILE_NAME}.${ARCHIVE_EXT}" ) ENDMACRO(GENERATE_PACKAGING_TARGET) # Create configs and targets for a package including all components SET(OSSIM_CPACK_COMPONENT ALL) GENERATE_PACKAGING_TARGET(ossim-all) # Create configs and targets for each component FOREACH(package ${CPACK_COMPONENTS_ALL}) SET(OSSIM_CPACK_COMPONENT ${package}) GENERATE_PACKAGING_TARGET(${package}) ENDFOREACH() ossim-Miami-2.9.1/cmake/CMakeModules/OssimCPackConfig.cmake.in000066400000000000000000000101121352751253100240300ustar00rootroot00000000000000# This file will be configured to contain variables for CPack. These variables # should be set in the CMake list file of the project before CPack module is # included. Example variables are: # CPACK_GENERATOR - Generator used to create package # CPACK_INSTALL_CMAKE_PROJECTS - For each project (path, name, component) # CPACK_CMAKE_GENERATOR - CMake Generator used for the projects # CPACK_INSTALL_COMMANDS - Extra commands to install components # CPACK_INSTALL_DIRECTORIES - Extra directories to install # CPACK_PACKAGE_DESCRIPTION_FILE - Description file for the package # CPACK_PACKAGE_DESCRIPTION_SUMMARY - Summary of the package # CPACK_PACKAGE_EXECUTABLES - List of pairs of executables and labels # CPACK_PACKAGE_FILE_NAME - Name of the package generated # CPACK_PACKAGE_ICON - Icon used for the package # CPACK_PACKAGE_INSTALL_DIRECTORY - Name of directory for the installer # CPACK_PACKAGE_NAME - Package project name # CPACK_PACKAGE_VENDOR - Package project vendor # CPACK_PACKAGE_VERSION - Package project version # CPACK_PACKAGE_VERSION_MAJOR - Package project version (major) # CPACK_PACKAGE_VERSION_MINOR - Package project version (minor) # CPACK_PACKAGE_VERSION_PATCH - Package project version (patch) # There are certain generator specific ones # NSIS Generator: # CPACK_PACKAGE_INSTALL_REGISTRY_KEY - Name of the registry key for the installer # CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS - Extra commands used during uninstall # CPACK_NSIS_EXTRA_INSTALL_COMMANDS - Extra commands used during install SET(CPACK_BINARY_BUNDLE "${CPACK_BINARY_BUNDLE}") SET(CPACK_BINARY_CYGWIN "${CPACK_BINARY_CYGWIN}") SET(CPACK_BINARY_DEB "${CPACK_BINARY_DEB}") SET(CPACK_BINARY_NSIS "${CPACK_BINARY_NSIS}") SET(CPACK_BINARY_OSXX11 "${CPACK_BINARY_OSXX11}") SET(CPACK_BINARY_PACKAGEMAKER "${CPACK_BINARY_PACKAGEMAKER}") SET(CPACK_BINARY_RPM "${CPACK_BINARY_RPM}") SET(CPACK_BINARY_STGZ "${CPACK_BINARY_STGZ}") SET(CPACK_BINARY_TBZ2 "${CPACK_BINARY_TBZ2}") SET(CPACK_BINARY_TGZ "${CPACK_BINARY_TGZ}") SET(CPACK_BINARY_TZ "${CPACK_BINARY_TZ}") SET(CPACK_BINARY_ZIP "${CPACK_BINARY_ZIP}") SET(CPACK_CMAKE_GENERATOR "${CMAKE_GENERATOR}") SET(CPACK_COMPONENTS_ALL "${CPACK_COMPONENTS_ALL}") SET(CPACK_COMPONENT_UNSPECIFIED_HIDDEN "TRUE") SET(CPACK_COMPONENT_UNSPECIFIED_REQUIRED "TRUE") SET(CPACK_GENERATOR "${CPACK_GENERATOR}") SET(CPACK_INSTALL_CMAKE_PROJECTS "${${PROJECT_NAME}_BINARY_DIR};ossim;${OSSIM_CPACK_COMPONENT};/") SET(CPACK_INSTALL_PREFIX "${CPACK_INSTALL_PREFIX}") SET(CPACK_MODULE_PATH "${${PROJECT_NAME}_SOURCE_DIR}/CMakeModules;") SET(CPACK_NSIS_DISPLAY_NAME "${CMAKE_PROJECT_NAME} ${OSSIM_VERSION}") SET(CPACK_NSIS_INSTALLER_ICON_CODE "") SET(CPACK_NSIS_INSTALLER_MUI_ICON_CODE "") SET(CPACK_OUTPUT_CONFIG_FILE "${PROJECT_BINARY_DIR}/CPackConfig-${OSSIM_CPACK_COMPONENT}.cmake") SET(CPACK_PACKAGE_DEFAULT_LOCATION "/") SET(CPACK_PACKAGE_DESCRIPTION_FILE "${${PROJECT_NAME}_SOURCE_DIR}/README.txt") SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "OSSIM is an open source high performance sensor modeling and image processing library") SET(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}") SET(CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_INSTALL_DIRECTORY}") SET(CPACK_PACKAGE_INSTALL_REGISTRY_KEY "${CMAKE_PROJECT_NAME}-${OSSIM_VERSION}") SET(CPACK_PACKAGE_NAME "${CPACK_PACKAGE_NAME}") SET(CPACK_PACKAGE_RELOCATABLE "true") SET(CPACK_PACKAGE_VENDOR "OSSIM") SET(CPACK_PACKAGE_VERSION "${OSSIM_VERSION}") SET(CPACK_PACKAGE_VERSION_MAJOR "${OSSIM_MAJOR_VERSION}") SET(CPACK_PACKAGE_VERSION_MINOR "${OSSIM_MINOR_VERSION}") SET(CPACK_PACKAGE_VERSION_PATCH "${OSSIM_PATCH_VERSION}") SET(CPACK_RESOURCE_FILE_LICENSE "${${PROJECT_NAME}_SOURCE_DIR}/LICENSE.txt") SET(CPACK_RESOURCE_FILE_README "${${PROJECT_NAME}_SOURCE_DIR}/README.txt") SET(CPACK_RESOURCE_FILE_WELCOME "${${PROJECT_NAME}_SOURCE_DIR}/NEWS.txt") SET(CPACK_SET_DESTDIR "OFF") SET(CPACK_STRIP_FILES "ON") SET(CPACK_RPM_PACKAGE_DEBUG "1") SET(CPACK_OSX_PACKAGE_VERSION "10.6") ossim-Miami-2.9.1/cmake/CMakeModules/OssimCommonVariables.cmake000066400000000000000000000323531352751253100244100ustar00rootroot00000000000000################################################################################## # This currently sets up the options for the WARNING FLAGS for the compiler we are generating for. # Currently only have gnu ################################################################################## MACRO(OSSIM_ADD_COMMON_LIBRARY_FLAGS) OPTION(OSSIM_COMPILE_WITH_FULL_WARNING "OSSIM developers : Compilation with FULL warning (use only for ossim developers)." OFF) MARK_AS_ADVANCED(OSSIM_COMPILE_WITH_FULL_WARNING) IF(OSSIM_COMPILE_WITH_FULL_WARNING) IF(CMAKE_COMPILER_IS_GNUCXX) SET(OSSIM_COMMON_COMPILER_FLAGS "${OSSIM_COMMON_COMPILER_FLAGS} -Wall -Wunused -Wunused-function -Wunused-label -Wunused-parameter -Wunused-value -Wunused-variable -Wuninitialized -Wsign-compare -Wparentheses -Wunknown-pragmas -Wswitch" CACHE STRING "List of compilation parameters.") ENDIF(CMAKE_COMPILER_IS_GNUCXX) ENDIF(OSSIM_COMPILE_WITH_FULL_WARNING) IF(WIN32) #--- # This option is to enable the /MP to compile multiple source files by using # multiple processes. #--- OPTION(WIN32_USE_MP "Set to ON to build OSSIM with the /MP option (Visual Studio 2005 and above)." OFF) MARK_AS_ADVANCED(WIN32_USE_MP) IF(WIN32_USE_MP) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP") ENDIF(WIN32_USE_MP) set(OSSIM_COMMON_COMPILER_FLAGS "${OSSIM_COMMON_COMPILER_FLAGS} -DNOMINMAX -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE") set(DEBUG_BUILD OFF) IF(CMAKE_BUILD_TYPE) string ( COMPARE EQUAL ${CMAKE_BUILD_TYPE} "Debug" DEBUG_BUILD ) ENDIF(CMAKE_BUILD_TYPE) ### # Currently must set /FORCE:MULTIPLE for Visual Studio 2010. 29 October 2010 - drb ### IF(MSVC) message("MSVC_VERSION: ${MSVC_VERSION}") if( (MSVC_VERSION GREATER 1600) OR (MSVC_VERSION EQUAL 1600)) if (DEBUG_BUILD) SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /NODEFAULTLIB:LIBCMTD /NODEFAULTLIB:MSVCRT /FORCE:MULTIPLE /MANIFEST:NO") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /NODEFAULTLIB:LIBCMTD /FORCE:MULTIPLE /MANIFEST:NO") else ( ) SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /NODEFAULTLIB:LIBCMTD /FORCE:MULTIPLE /MANIFEST:NO") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /NODEFAULTLIB:LIBCMTD /FORCE:MULTIPLE /MANIFEST:NO") endif (DEBUG_BUILD) SET(OSSIM_COMMON_COMPILER_FLAGS "${OSSIM_COMMON_COMPILER_FLAGS} /EHsc") SET(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} /NODEFAULTLIB:LIBCMTD /FORCE:MULTIPLE") else( ) SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /NODEFAULTLIB:LIBCMTD") endif() ENDIF(MSVC) ENDIF(WIN32) OPTION(OSSIM_ADD_FPIC "Compilation with FPIC flag if static library. The default is on since we have plugins that need to be shared." ON) MARK_AS_ADVANCED(OSSIM_ADD_FPIC) IF(OSSIM_ADD_FPIC) IF(UNIX AND NOT BUILD_SHARED_LIBS) STRING(REGEX MATCH "fPIC" REG_MATCHED "${OSSIM_COMMON_COMPILER_FLAGS}") if(NOT REG_MATCHED) set(OSSIM_COMMON_COMPILER_FLAGS "${OSSIM_COMMON_COMPILER_FLAGS} -fPIC") endif(NOT REG_MATCHED) ENDIF(UNIX AND NOT BUILD_SHARED_LIBS) ENDIF(OSSIM_ADD_FPIC) MARK_AS_ADVANCED(OSSIM_COMMON_COMPILER_FLAGS) ENDMACRO(OSSIM_ADD_COMMON_LIBRARY_FLAGS) MACRO(USE_CXX11) if (CMAKE_VERSION VERSION_LESS "3.1") if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") set (CMAKE_CXX_FLAGS "--std=gnu++11 ${CMAKE_CXX_FLAGS}") elseif (APPLE) set (CMAKE_CXX_FLAGS "--std=gnu++11 ${CMAKE_CXX_FLAGS}") endif() else () set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) endif () ENDMACRO(USE_CXX11) MACRO(OSSIM_ADD_COMMON_SETTINGS) ################################################################################### # Set defaults for Universal Binaries. We want 32-bit Intel/PPC on 10.4 # and 32/64-bit Intel/PPC on >= 10.5. Anything <= 10.3 doesn't support. # These are just defaults/recommendations, but how we want to build # out of the box. But the user needs to be able to change these options. # So we must only set the values the first time CMake is run, or we # will overwrite any changes the user sets. # FORCE is used because the options are not reflected in the UI otherwise. # Seems like a good place to add version specific compiler flags too. ################################################################################### USE_CXX11() IF(APPLE) # use, i.e. don't skip the full RPATH for the build tree SET(CMAKE_SKIP_BUILD_RPATH FALSE) # when building, don't use the install RPATH already # (but later on when installing) SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}") # add the automatically determined parts of the RPATH # which point to directories outside the build tree to the install RPATH SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) # the RPATH to be used when installing, but only if it's not a system directory LIST(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_PREFIX}/lib" isSystemDir) IF("${isSystemDir}" STREQUAL "-1") SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}") ENDIF("${isSystemDir}" STREQUAL "-1") SET(TEMP_CMAKE_OSX_ARCHITECTURES "") SET(CMAKE_OSX_SYSROOT "${CMAKE_OSX_SYSROOT}") # This is really fragile, but CMake doesn't provide the OS system # version information we need. (Darwin versions can be changed # independently of OS X versions.) # It does look like CMake handles the CMAKE_OSX_SYSROOT automatically. IF(EXISTS /Developer/SDKs/MacOSX10.6.sdk) SET(TEMP_CMAKE_OSX_ARCHITECTURES "i386;x86_64") IF(NOT ("${CMAKE_CXX_FLAGS}" MATCHES "mmacosx-version-min")) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmacosx-version-min=10.5 -ftree-vectorize -fvisibility-inlines-hidden" CACHE STRING "Flags used by the compiler during all build types.") ENDIF() ELSEIF(EXISTS /Developer/SDKs/MacOSX10.5.sdk) # 64-bit compiles are not supported with Carbon. We should enable SET(TEMP_CMAKE_OSX_ARCHITECTURES "i386;x86_64") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmacosx-version-min=10.5 -ftree-vectorize -fvisibility-inlines-hidden" CACHE STRING "Flags used by the compiler during all build types.") ELSEIF(EXISTS /Developer/SDKs/MacOSX10.4u.sdk) SET(TEMP_CMAKE_OSX_ARCHITECTURES "i386;ppc") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmacosx-version-min=10.4 -ftree-vectorize -fvisibility-inlines-hidden" CACHE STRING "Flags used by the compiler during all build types.") ELSE() # No Universal Binary support # Should break down further to set the -mmacosx-version-min, # but the SDK detection is too unreliable here. ENDIF() IF(NOT CMAKE_OSX_ARCHITECTURES) SET(CMAKE_OSX_ARCHITECTURES "${TEMP_CMAKE_OSX_ARCHITECTURES}" CACHE STRING "Build architectures for OSX" FORCE) ENDIF() OPTION(OSSIM_BUILD_APPLICATION_BUNDLES "Enable the building of applications and examples as OSX Bundles" OFF) MARK_AS_ADVANCED(CMAKE_OSX_ARCHITECTURES) MARK_AS_ADVANCED(CMAKE_CXX_FLAGS) MARK_AS_ADVANCED(CMAKE_OSX_SYSROOT) MARK_AS_ADVANCED(OSSIM_BUILD_APPLICATION_BUNDLES) ENDIF(APPLE) SET(MAKE_APPENDS_BUILD_TYPE "NO") IF(CMAKE_GENERATOR) STRING(TOUPPER ${CMAKE_GENERATOR} CMAKE_GENERATOR_TEST_UPPER) STRING(COMPARE EQUAL "${CMAKE_GENERATOR_TEST_UPPER}" "XCODE" CMAKE_GENERATOR_TEST) IF(CMAKE_GENERATOR_TEST) SET(MAKE_APPENDS_BUILD_TYPE "YES") ELSE() STRING(COMPARE NOTEQUAL "." "${CMAKE_CFG_INTDIR}" CMAKE_GENERATOR_TEST) IF(CMAKE_GENERATOR_TEST) SET(MAKE_APPENDS_BUILD_TYPE "YES") ENDIF() ENDIF() ENDIF(CMAKE_GENERATOR) OSSIM_ADD_COMMON_LIBRARY_FLAGS() # Dynamic vs Static Linking OPTION(BUILD_SHARED_LIBS "Set to ON to build OSSIM for dynamic linking. Use OFF for static." ON) OPTION(BUILD_OSSIM_FRAMEWORKS "Set to ON to build OSSIM for framework if BUILD_SHARED_LIBS is on. Use OFF for dylib if BUILD_SHARED_LIBS is on." ON) IF(BUILD_SHARED_LIBS) SET(OSSIM_USER_DEFINED_DYNAMIC_OR_STATIC "SHARED") ELSE () SET(OSSIM_USER_DEFINED_DYNAMIC_OR_STATIC "STATIC") ENDIF() # IF(NOT OSSIM_LIBRARY_BUILD_OUTPUT_DIRECTORY) # SET(OSSIM_LIBRARY_BUILD_OUTPUT_DIRECTORY ${${PROJECT_NAME}_SOURCE_DIR}/lib) # ENDIF(NOT OSSIM_LIBRARY_BUILD_OUTPUT_DIRECTORY) # IF(NOT OSSIM_RUNTIME_BUILD_OUTPUT_DIRECTORY) # SET(OSSIM_RUNTIME_BUILD_OUTPUT_DIRECTORY ${${PROJECT_NAME}_SOURCE_DIR}/bin) # ENDIF(NOT OSSIM_RUNTIME_BUILD_OUTPUT_DIRECTORY) # Libraries and archives go to lib or lib64. get_property(LIB64 GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS) if(LIB64) set(LIBSUFFIX 64) else() set(LIBSUFFIX "") endif() IF(MAKE_APPENDS_BUILD_TYPE) SET(BUILD_FRAMEWORK_DIR "") SET(BUILD_RUNTIME_DIR "bin") SET(BUILD_LIBRARY_DIR lib${LIBSUFFIX}) SET(BUILD_ARCHIVE_DIR lib${LIBSUFFIX}) SET(BUILD_INCLUDE_DIR "include") ELSE() IF(NOT DEFINED BUILD_FRAMEWORK_DIR) SET(BUILD_FRAMEWORK_DIR "") ENDIF() IF(NOT DEFINED BUILD_RUNTIME_DIR) SET(BUILD_RUNTIME_DIR "bin") ENDIF() IF(NOT DEFINED BUILD_LIBRARY_DIR) SET(BUILD_LIBRARY_DIR lib${LIBSUFFIX}) ENDIF() IF(NOT DEFINED BUILD_ARCHIVE_DIR) SET(BUILD_ARCHIVE_DIR lib${LIBSUFFIX}) ENDIF() IF(NOT DEFINED BUILD_INCLUDE_DIR) SET(BUILD_INCLUDE_DIR "include") ENDIF() ENDIF() SET(INSTALL_FRAMEWORK_DIR "Frameworks") SET(INSTALL_RUNTIME_DIR "bin") SET(INSTALL_INCLUDE_DIR "include") set(INSTALL_LIBRARY_DIR lib${LIBSUFFIX} CACHE PATH "Installation directory for libraries") set(INSTALL_ARCHIVE_DIR lib${LIBSUFFIX} CACHE PATH "Installation directory for archive") mark_as_advanced(LIBSUFFIX) mark_as_advanced(INSTALL_LIBRARY_DIR) mark_as_advanced(INSTALL_ARCHIVE_DIR) IF(WIN32) IF(NOT DEFINED CMAKE_DEBUG_POSTFIX) SET(CMAKE_DEBUG_POSTFIX "d" CACHE STRING "Debug variable used to add the postfix to dll's and exe's. Defaults to 'd' on WIN32 builds and empty on all other platforms" FORCE) ENDIF() ENDIF() IF(NOT CMAKE_BUILD_TYPE) SET(CMAKE_BUILD_TYPE Release) ENDIF(NOT CMAKE_BUILD_TYPE) # force some variables that could be defined in the command line to be written to cache SET( CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}" CACHE PATH "Where to install ${PROJECT_NAME}" FORCE ) SET( CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE ) SET( CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" CACHE PATH "Path to custom CMake Modules" FORCE ) SET( INSTALL_DOC "${INSTALL_DOC}" CACHE BOOL "Set to OFF to skip build/install Documentation" FORCE ) IF(NOT OSSIM_DEV_HOME) SET(OSSIM_DEV_HOME "$ENV{OSSIM_DEV_HOME}") GET_FILENAME_COMPONENT(OSSIM_DEV_HOME "${OSSIM_DEV_HOME}" ABSOLUTE) ENDIF(NOT OSSIM_DEV_HOME) IF(NOT CMAKE_INSTALL_PREFIX) SET(CMAKE_INSTALL_PREFIX "$ENV{OSSIM_INSTALL_PREFIX}") GET_FILENAME_COMPONENT(CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}" ABSOLUTE) ENDIF(NOT CMAKE_INSTALL_PREFIX) IF(NOT OSSIM_DEPENDENCIES) SET(OSSIM_DEPENDENCIES "$ENV{OSSIM_DEPENDENCIES}") GET_FILENAME_COMPONENT(OSSIM_DEPENDENCIES "${OSSIM_DEPENDENCIES}" ABSOLUTE) ENDIF(NOT OSSIM_DEPENDENCIES) # Define paths used by package finders defined in this directory: IF(OSSIM_INSTALL_PREFIX) SET(CMAKE_LIBRARY_PATH "${CMAKE_LIBRARY_PATH};${OSSIM_INSTALL_PREFIX}/lib${LIBSUFFIX}") SET(CMAKE_INCLUDE_PATH "${CMAKE_INCLUDE_PATH};${OSSIM_INSTALL_PREFIX}/include") ENDIF() IF(OSSIM_DEPENDENCIES) SET(CMAKE_LIBRARY_PATH "${CMAKE_LIBRARY_PATH};${OSSIM_DEPENDENCIES}/lib${LIBSUFFIX}") SET(CMAKE_INCLUDE_PATH "${CMAKE_INCLUDE_PATH};${OSSIM_DEPENDENCIES}/include") ENDIF() # SET(CMAKE_LIBRARY_PATH "${CMAKE_LIBRARY_PATH};/usr/lib;/usr/local/lib;/usr/lib64;/usr/lib/x86_64-linux-gnu") SET(CMAKE_INCLUDE_PATH "${CMAKE_INCLUDE_PATH};${OSSIM_DEV_HOME}/ossim/include;/usr/include;/usr/local/include") #################################### ADd some common options for all modules to use ################################### OPTION(BUILD_OSSIM_VIDEO "Set to ON to build the video decoding library. Use OFF to skip this module." OFF) OPTION(BUILD_OSSIM_PLANET "Set to ON to build the 3-D visualization module. Use OFF to skip this module." OFF) OPTION(BUILD_OSSIM_GUI "Set to ON to build the new ossimGui library and geocell application." ON) OPTION(BUILD_OMS "Set to ON to build the oms api library." ON) OPTION(BUILD_OSSIM_WMS "Set to ON to build the wms api library." ON) SET(CMAKE_INCLUDE_DIRS_FILE "${CMAKE_BINARY_DIR}/CMakeIncludeDirs.txt") SET(CMAKE_FILENAMES_FILE "${CMAKE_BINARY_DIR}/CMakeFileNames.txt") ENDMACRO(OSSIM_ADD_COMMON_SETTINGS) OSSIM_ADD_COMMON_SETTINGS() ossim-Miami-2.9.1/cmake/CMakeModules/OssimDetermineCompiler.cmake000066400000000000000000000052261352751253100247350ustar00rootroot00000000000000# - If Visual Studio is being used, this script sets the variable OSG_COMPILER # The principal reason for this is due to MSVC 8.0 SP0 vs SP1 builds. # # Variable: # OSG_COMPILER # # Not currently used... #IF(CMAKE_COMPILER_IS_GNUCXX) # EXEC_PROGRAM( # ${CMAKE_CXX_COMPILER} # ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion # OUTPUT_VARIABLE gcc_compiler_version # ) # #MESSAGE("GCC Version: ${gcc_compiler_version}") IF(MSVC60) SET(OSG_COMPILER "vc60") ELSEIF(MSVC70) SET(OSG_COMPILER "vc70") ELSEIF(MSVC71) SET(OSG_COMPILER "vc71") ELSEIF(MSVC80) SET(OSG_COMPILER "vc80") ELSEIF(MSVC90) SET(OSG_COMPILER "vc90") ELSEIF(MSVC100) SET(OSG_COMPILER "vc100") ENDIF() MESSAGE("OSG_COMPILER ${OSG_COMPILER}") IF(MSVC80) MESSAGE(STATUS "Checking if compiler has service pack 1 installed...") FILE(WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.cxx" "int main() {return 0;}\n") TRY_COMPILE(_TRY_RESULT ${CMAKE_BINARY_DIR} ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.cxx CMAKE_FLAGS -D CMAKE_VERBOSE_MAKEFILE=ON OUTPUT_VARIABLE OUTPUT ) IF(_TRY_RESULT) # parse for exact compiler version STRING(REGEX MATCH "Compiler Version [0-9]+.[0-9]+.[0-9]+.[0-9]+" vc_compiler_version "${OUTPUT}") IF(vc_compiler_version) #MESSAGE("${vc_compiler_version}") STRING(REGEX MATCHALL "[0-9]+" CL_VERSION_LIST "${vc_compiler_version}") LIST(GET CL_VERSION_LIST 0 CL_MAJOR_VERSION) LIST(GET CL_VERSION_LIST 1 CL_MINOR_VERSION) LIST(GET CL_VERSION_LIST 2 CL_PATCH_VERSION) LIST(GET CL_VERSION_LIST 3 CL_EXTRA_VERSION) ENDIF(vc_compiler_version) # Standard vc80 is 14.00.50727.42, sp1 14.00.50727.762, sp2? # Standard vc90 is 9.0.30729.1, sp1 ? IF(CL_EXTRA_VERSION EQUAL 762) SET(OSG_COMPILER "vc80sp1") ELSE(CL_EXTRA_VERSION EQUAL 762) SET(OSG_COMPILER "vc80") ENDIF(CL_EXTRA_VERSION EQUAL 762) # parse for exact visual studio version #IF(MSVC_IDE) # string(REGEX MATCH "Visual Studio Version [0-9]+.[0-9]+.[0-9]+.[0-9]+" vs_version "${OUTPUT}") # IF(vs_version) # MESSAGE("${vs_version}") # string(REGEX MATCHALL "[0-9]+" VS_VERSION_LIST "${vs_version}") # list(GET VS_VERSION_LIST 0 VS_MAJOR_VERSION) # list(GET VS_VERSION_LIST 1 VS_MINOR_VERSION) # list(GET VS_VERSION_LIST 2 VS_PATCH_VERSION) # list(GET VS_VERSION_LIST 3 VS_EXTRA_VERSION) # ENDIF(vs_version) #ENDIF(MSVC_IDE) ENDIF(_TRY_RESULT) ENDIF(MSVC80) ossim-Miami-2.9.1/cmake/CMakeModules/OssimQt4Macros.cmake000066400000000000000000000014511352751253100231370ustar00rootroot00000000000000include(Qt4Macros) MACRO (OSSIM_QT4_WRAP_UI outfiles) if(CMAKE_VERSION VERSION_LESS 2.8.12) QT4_EXTRACT_OPTIONS(ui_files ui_options ${ARGN}) else() QT4_EXTRACT_OPTIONS(ui_files ui_options "" ${ARGN}) endif() FOREACH (it ${ui_files}) GET_FILENAME_COMPONENT(outfile ${it} NAME_WE) GET_FILENAME_COMPONENT(infile ${it} ABSOLUTE) IF(UI_DESTINATION_DIR) SET(outfile ${UI_DESTINATION_DIR}/ui_${outfile}.h) ELSE(UI_DESTINATION_DIR) SET(outfile ${CMAKE_CURRENT_BINARY_DIR}/ui_${outfile}.h) ENDIF(UI_DESTINATION_DIR) ADD_CUSTOM_COMMAND(OUTPUT ${outfile} COMMAND ${QT_UIC_EXECUTABLE} ARGS ${ui_options} -o ${outfile} ${infile} MAIN_DEPENDENCY ${infile}) SET(${outfiles} ${${outfiles}} ${outfile}) ENDFOREACH (it) ENDMACRO (OSSIM_QT4_WRAP_UI) ossim-Miami-2.9.1/cmake/CMakeModules/OssimQt5Macros.cmake000066400000000000000000000012611352751253100231370ustar00rootroot00000000000000include(Qt5Macros) MACRO (OSSIM_QT_WRAP_UI outfiles) QT5_EXTRACT_OPTIONS(ui_files ui_options ${ARGN}) FOREACH (it ${ui_files}) GET_FILENAME_COMPONENT(outfile ${it} NAME_WE) GET_FILENAME_COMPONENT(infile ${it} ABSOLUTE) IF(UI_DESTINATION_DIR) SET(outfile ${UI_DESTINATION_DIR}/ui_${outfile}.h) ELSE(UI_DESTINATION_DIR) SET(outfile ${CMAKE_CURRENT_BINARY_DIR}/ui_${outfile}.h) ENDIF(UI_DESTINATION_DIR) ADD_CUSTOM_COMMAND(OUTPUT ${outfile} COMMAND ${QT_UIC_EXECUTABLE} ARGS ${ui_options} -o ${outfile} ${infile} MAIN_DEPENDENCY ${infile}) SET(${outfiles} ${${outfiles}} ${outfile}) ENDFOREACH (it) ENDMACRO (OSSIM_QT_WRAP_UI) ossim-Miami-2.9.1/cmake/CMakeModules/OssimUtilities.cmake000066400000000000000000000460321352751253100233010ustar00rootroot00000000000000################################################################################# # This was taken from the http://www.cmake.org/Wiki/CMakeMacroParseArguments ################################################################################# MACRO(OSSIM_PARSE_ARGUMENTS prefix arg_names option_names) SET(DEFAULT_ARGS) FOREACH(arg_name ${arg_names}) SET(${prefix}_${arg_name}) ENDFOREACH(arg_name) FOREACH(option ${option_names}) SET(${prefix}_${option} FALSE) ENDFOREACH(option) SET(current_arg_name DEFAULT_ARGS) SET(current_arg_list) FOREACH(arg ${ARGN}) SET(larg_names ${arg_names}) LIST(FIND larg_names "${arg}" is_arg_name) IF (is_arg_name GREATER -1) SET(${prefix}_${current_arg_name} ${current_arg_list}) SET(current_arg_name ${arg}) SET(current_arg_list) ELSE (is_arg_name GREATER -1) SET(loption_names ${option_names}) LIST(FIND loption_names "${arg}" is_option) IF (is_option GREATER -1) SET(${prefix}_${arg} TRUE) ELSE (is_option GREATER -1) SET(current_arg_list ${current_arg_list} ${arg}) ENDIF (is_option GREATER -1) ENDIF (is_arg_name GREATER -1) ENDFOREACH(arg) SET(${prefix}_${current_arg_name} ${current_arg_list}) ENDMACRO(OSSIM_PARSE_ARGUMENTS) ############################################################################################## # This was taken from http://www.cmake.org/Wiki/CMakeMacroListOperations#CAR_and_CDR ############################################################################################## MACRO(OSSIM_CAR var) SET(${var} ${ARGV1}) ENDMACRO(OSSIM_CAR) ############################################################################################# # This was taken from http://www.cmake.org/Wiki/CMakeMacroListOperations#CAR_and_CDR ############################################################################################# MACRO(OSSIM_CDR var junk) SET(${var} ${ARGN}) ENDMACRO(OSSIM_CDR) ################################################################################# # MACRO: TODAYS_DATE # # DESCRIPTION: # MACRO FOR GETTING THE DATE AND TIME INFORMATION ################################################################################# MACRO (TODAYS_DATE RESULT) string(TIMESTAMP ${RESULT} "%Y%m%d" UTC) ENDMACRO (TODAYS_DATE) ################################################################################# # MACRO: GET_GIT_REVISION # # DESCRIPTION: # MACRO FOR GETTING THE GIT revision for this build ################################################################################# MACRO (GET_GIT_REVISION) FIND_PACKAGE(Git) IF(GIT_FOUND) GIT_WC_INFO(${PROJECT_SOURCE_DIR} Project) # MESSAGE("Current revision is ${Project_WC_REVISION}") # Subversion_WC_LOG(${PROJECT_SOURCE_DIR} Project) # MESSAGE("Last changed log is ${Project_LAST_CHANGED_LOG}") ENDIF() ENDMACRO(GET_GIT_REVISION) MACRO(LINK_EXTERNAL TRGTNAME) FOREACH(LINKLIB ${ARGN}) TARGET_LINK_LIBRARIES(${TRGTNAME} "${LINKLIB}" ) ENDFOREACH(LINKLIB) ENDMACRO(LINK_EXTERNAL TRGTNAME) MACRO(LINK_INTERNAL TRGTNAME) IF(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4) TARGET_LINK_LIBRARIES(${TRGTNAME} ${ARGN}) ELSE(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4) FOREACH(LINKLIB ${ARGN}) IF(MSVC AND OSSIM_MSVC_VERSIONED_DLL) #when using versioned names, the .dll name differ from .lib name, there is a problem with that: #CMake 2.4.7, at least seem to use PREFIX instead of IMPORT_PREFIX for computing linkage info to use into projects, # so we full path name to specify linkage, this prevent automatic inferencing of dependencies, so we add explicit depemdencies #to library targets used TARGET_LINK_LIBRARIES(${TRGTNAME} optimized "${OUTPUT_LIBDIR}/${LINKLIB}${CMAKE_RELEASE_POSTFIX}.lib" debug "${OUTPUT_LIBDIR}/${LINKLIB}${CMAKE_DEBUG_POSTFIX}.lib") ADD_DEPENDENCIES(${TRGTNAME} ${LINKLIB}) ELSE(MSVC AND OSSIM_MSVC_VERSIONED_DLL) TARGET_LINK_LIBRARIES(${TRGTNAME} optimized "${LINKLIB}${CMAKE_RELEASE_POSTFIX}" debug "${LINKLIB}${CMAKE_DEBUG_POSTFIX}") ENDIF(MSVC AND OSSIM_MSVC_VERSIONED_DLL) ENDFOREACH(LINKLIB) ENDIF(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4) ENDMACRO(LINK_INTERNAL TRGTNAME) ###################################################################### # # This set up the libraries to link to, it assumes there are two variable: one common for a group of examples or plugins # kept in the variable TARGET_COMMON_LIBRARIES and an example or plugin specific kept in TARGET_ADDED_LIBRARIES # they are combined in a single list checked for unicity # the suffix ${CMAKE_DEBUG_POSTFIX} is used for differentiating optimized and debug # # a second variable TARGET_EXTERNAL_LIBRARIES hold the list of libraries not differentiated between debug and optimized ################################################################################## MACRO(SETUP_LINK_LIBRARIES) SET(TARGET_LIBRARIES ${TARGET_COMMON_LIBRARIES}) FOREACH(LINKLIB ${TARGET_ADDED_LIBRARIES}) SET(TO_INSERT TRUE) FOREACH (value ${TARGET_COMMON_LIBRARIES}) IF (${value} STREQUAL ${LINKLIB}) SET(TO_INSERT FALSE) ENDIF (${value} STREQUAL ${LINKLIB}) ENDFOREACH (value ${TARGET_COMMON_LIBRARIES}) IF(TO_INSERT) LIST(APPEND TARGET_LIBRARIES ${LINKLIB}) ENDIF(TO_INSERT) ENDFOREACH(LINKLIB) LINK_INTERNAL(${TARGET_TARGETNAME} ${TARGET_LIBRARIES}) TARGET_LINK_LIBRARIES(${TARGET_TARGETNAME} ${TARGET_EXTERNAL_LIBRARIES}) IF(TARGET_LIBRARIES_VARS) LINK_WITH_VARIABLES(${TARGET_TARGETNAME} ${TARGET_LIBRARIES_VARS}) ENDIF(TARGET_LIBRARIES_VARS) ENDMACRO(SETUP_LINK_LIBRARIES) MACRO(OSSIM_SETUP_APPLICATION) OSSIM_PARSE_ARGUMENTS(APPLICATION "COMPONENT_NAME;SOURCE_FILES;HEADERS;TARGET_NAME;TARGET_LABEL" "COMMAND_LINE;INSTALL;REQUIRE_WINMAIN_FLAG" ${ARGN}) OSSIM_CAR(APPLICATION_NAME "${APPLICATION_DEFAULT_ARGS}") OSSIM_CDR(APPLICATION_SOURCES "${APPLICATION_DEFAULT_ARGS}") SET(TARGET_NAME ${APPLICATION_NAME}) SET(TARGET_TARGETNAME "${TARGET_DEFAULT_PREFIX}${APPLICATION_NAME}") IF(APPLICATION_TARGET_NAME) set(TARGET_TARGETNAME "${APPLICATION_TARGET_NAME}") ENDIF(APPLICATION_TARGET_NAME) SET(TARGET_LABEL "${TARGET_DEFAULT_LABEL_PREFIX} ${APPLICATION_NAME}") IF(APPLICATION_TARGET_LABEL) SET(TARGET_LABEL "${APPLICATION_TARGET_LABEL}") ENDIF(APPLICATION_TARGET_LABEL) IF(APPLICATION_COMMAND_LINE) ADD_EXECUTABLE(${TARGET_TARGETNAME} ${APPLICATION_SOURCE_FILES} ${APPLICATION_HEADERS}) ELSE(APPLICATION_COMMAND_LINE) IF(APPLE) # SET(MACOSX_BUNDLE_LONG_VERSION_STRING "${OSSIM_MAJOR_VERSION}.${OSSIM_MINOR_VERSION}.${OSSIM_PATCH_VERSION}") # Short Version is the "marketing version". It is the version # the user sees in an information panel. SET(MACOSX_BUNDLE_SHORT_VERSION_STRING "${OSSIM_MAJOR_VERSION}.${OSSIM_MINOR_VERSION}.${OSSIM_PATCH_VERSION}") # Bundle version is the version the OS looks at. SET(MACOSX_BUNDLE_BUNDLE_VERSION "${OSSIM_MAJOR_VERSION}.${OSSIM_MINOR_VERSION}.${OSSIM_PATCH_VERSION}") SET(MACOSX_BUNDLE_GUI_IDENTIFIER "org.ossim.${TARGET_TARGETNAME}" ) SET(MACOSX_BUNDLE_BUNDLE_NAME "${TARGET_TARGETNAME}" ) # SET(MACOSX_BUNDLE_ICON_FILE "myicon.icns") # SET(MACOSX_BUNDLE_COPYRIGHT "") # SET(MACOSX_BUNDLE_INFO_STRING "Info string, localized?") ENDIF(APPLE) IF(WIN32) IF (APPLICATION_REQUIRE_WINMAIN_FLAG) SET(PLATFORM_SPECIFIC_CONTROL WIN32) ENDIF (APPLICATION_REQUIRE_WINMAIN_FLAG) ENDIF(WIN32) IF(APPLE) IF(OSSIM_BUILD_APPLICATION_BUNDLES) SET(PLATFORM_SPECIFIC_CONTROL MACOSX_BUNDLE) ENDIF(OSSIM_BUILD_APPLICATION_BUNDLES) ENDIF(APPLE) ADD_EXECUTABLE(${TARGET_TARGETNAME} ${PLATFORM_SPECIFIC_CONTROL} ${APPLICATION_SOURCE_FILES} ${APPLICATION_HEADERS}) ENDIF(APPLICATION_COMMAND_LINE) if(NOT LIB_NAME) message(FATAL_ERROR "LIB_NAME must be set before calling OSSIM_SETUP_APPLICATION() macro") endif() add_dependencies(${TARGET_TARGETNAME} ${LIB_NAME}) target_link_libraries(${TARGET_TARGETNAME} ${LIB_NAME}) SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PROJECT_LABEL "${TARGET_LABEL}") SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES OUTPUT_NAME ${TARGET_NAME}) SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES DEBUG_OUTPUT_NAME "${TARGET_NAME}${CMAKE_DEBUG_POSTFIX}") SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES RELEASE_OUTPUT_NAME "${TARGET_NAME}${CMAKE_RELEASE_POSTFIX}") SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES RELWITHDEBINFO_OUTPUT_NAME "${TARGET_NAME}${CMAKE_RELWITHDEBINFO_POSTFIX}") SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES MINSIZEREL_OUTPUT_NAME "${TARGET_NAME}${CMAKE_MINSIZEREL_POSTFIX}") IF(MSVC_IDE AND OSSIM_MSVC_VERSIONED_DLL) SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PREFIX "../") ENDIF(MSVC_IDE AND OSSIM_MSVC_VERSIONED_DLL) SETUP_LINK_LIBRARIES() OSSIM_SAVE_INCLUDE_DIRECTORIES() OSSIM_SAVE_FILENAMES() IF(APPLICATION_INSTALL) IF(APPLE) INSTALL(TARGETS ${TARGET_TARGETNAME} RUNTIME DESTINATION ${INSTALL_RUNTIME_DIR} BUNDLE DESTINATION ${INSTALL_RUNTIME_DIR} COMPONENT ${APPLICATION_COMPONENT_NAME}) ELSE(APPLE) INSTALL(TARGETS ${TARGET_TARGETNAME} RUNTIME DESTINATION ${INSTALL_RUNTIME_DIR} ${INSTALL_COMPONENT_INFO} COMPONENT ${APPLICATION_COMPONENT_NAME}) ENDIF(APPLE) ENDIF(APPLICATION_INSTALL) SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${BUILD_RUNTIME_DIR}") ENDMACRO(OSSIM_SETUP_APPLICATION) ##################################################################################################### # MACRO: OSSIM_LINK_LIBRARY # # Example: # OSSIM_LINK_LIBRARY(ossim # COMPONENT_NAME ossim # SOURCE_FILES foo.cpp # HEADERS foo.h # TYPE SHARED # LIBRARIES # INSTALL_LIB # INSTALL_HEADERS) # # The INSTALL_LIB says to add a default install command for the library by default it will setup the following # install(TARGETS ossim # FRAMEWORK DESTINATION ${INSTALL_FRAMEWORK_DIR} # RUNTIME DESTINATION ${INSTALL_RUNTIME_DIR} # LIBRARY DESTINATION ${INSTALL_LIBRARY_DIR} # ARCHIVE DESTINATION ${INSTALL_ARCHIVE_DIR} # PUBLIC_HEADER DESTINATION ${INSTALL_INCLUDE_DIR} # COMPONENT ossim) # # The INSTALL_HEADERS will do a default header installation if the option is passed in # install(FILES DESTINATION "include/ossim" COMPONENT ossim) ##################################################################################################### MACRO(OSSIM_LINK_LIBRARY) # The SO_VERSION and VERSION are here for override purpose only so other libraries with their own # versioning scheme can use the sum linking # OSSIM_PARSE_ARGUMENTS(LINK "COMPONENT_NAME;SOURCE_FILES;HEADERS;TYPE;LIBRARIES;ADDITIONAL_COMPILE_FLAGS;SOVERSION;VERSION;PUBLIC_HEADERS" "INSTALL_LIB;INSTALL_HEADERS;VERSION_SYMLINKS" ${ARGN}) OSSIM_CAR(LINK_NAME "${LINK_DEFAULT_ARGS}") OSSIM_CDR(LINK_SOURCES "${LINK_DEFAULT_ARGS}") ADD_DEFINITIONS("${OSSIM_COMMON_COMPILER_FLAGS}") ADD_LIBRARY(${LINK_NAME} ${LINK_TYPE} ${LINK_HEADERS} ${LINK_SOURCE_FILES}) IF(NOT LINK_PUBLIC_HEADERS) SET(LINK_PUBLIC_HEADERS ${LINK_HEADERS}) ENDIF() IF(LINK_ADDITIONAL_COMPILE_FLAGS) SET_TARGET_PROPERTIES(${LINK_NAME} PROPERTIES COMPILE_FLAGS ${LINK_ADDITIONAL_COMPILE_FLAGS}) ENDIF(LINK_ADDITIONAL_COMPILE_FLAGS) if(APPLE) IF(BUILD_SHARED_LIBS) # SET(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) # SET(CMAKE_INSTALL_RPATH "${OSSIM_COMPILE_FRAMEWORKS_INSTALL_NAME_DIR}") IF(BUILD_OSSIM_FRAMEWORKS) SET_TARGET_PROPERTIES(${LINK_NAME} PROPERTIES FRAMEWORK TRUE BUILD_WITH_INSTALL_RPATH ON INSTALL_NAME_DIR @rpath/Frameworks) ELSE(BUILD_OSSIM_FRAMEWORKS) #--- # Given install prefix=/usr/local and # install lib dir = lib64 and # link name = libossim.dylib # You get "/usr/local/lib64/libossim.dylib" in the rpath. #--- SET_TARGET_PROPERTIES(${LINK_NAME} PROPERTIES FRAMEWORK FALSE BUILD_WITH_INSTALL_RPATH ON INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/${INSTALL_LIBRARY_DIR}") ENDIF(BUILD_OSSIM_FRAMEWORKS) ELSE(BUILD_SHARED_LIBRARY) SET_TARGET_PROPERTIES(${LINK_NAME} PROPERTIES FRAMEWORK FALSE) ENDIF(BUILD_SHARED_LIBS) ENDIF(APPLE) IF(UNIX AND BUILD_SHARED_LIBS AND NOT APPLE) IF(LINK_VERSION_SYMLINKS) IF(NOT LINK_SOVERSION) set(LINK_SOVERSION "${OSSIM_SOVERSION}") ENDIF(NOT LINK_SOVERSION) IF(NOT LINK_VERSION) set(LINK_VERSION "${OSSIM_VERSION}") ENDIF(NOT LINK_VERSION) # ADD_CUSTOM_TARGET( lib DEPENDS ${LINK_NAME} ) # change lib_target properties SET_TARGET_PROPERTIES( ${LINK_NAME} PROPERTIES # create *nix style library versions + symbolic links VERSION ${LINK_VERSION} SOVERSION ${LINK_SOVERSION} # allow creating static and shared libs without conflicts CLEAN_DIRECT_OUTPUT 1 # avoid conflicts between library and binary target names OUTPUT_NAME ${LINK_NAME} ) ENDIF(LINK_VERSION_SYMLINKS) ENDIF(UNIX AND BUILD_SHARED_LIBS AND NOT APPLE) SET_TARGET_PROPERTIES(${LINK_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${BUILD_RUNTIME_DIR}") IF(APPLE AND BUILD_OSSIM_FRAMEWORKS) SET_TARGET_PROPERTIES(${LINK_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${BUILD_FRAMEWORK_DIR}") ELSE(APPLE AND BUILD_OSSIM_FRAMEWORKS) SET_TARGET_PROPERTIES(${LINK_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${BUILD_LIBRARY_DIR}") ENDIF(APPLE AND BUILD_OSSIM_FRAMEWORKS) SET_TARGET_PROPERTIES(${LINK_NAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${BUILD_LIBRARY_DIR}") TARGET_LINK_LIBRARIES(${LINK_NAME} ${LINK_LIBRARIES} ${${LINK_NAME}_EXTRA_LIBS}) IF(LINK_INSTALL_LIB) IF(LINK_INSTALL_HEADERS) SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PUBLIC_HEADER "${LINK_PUBLIC_HEADERS}") install(TARGETS ${LINK_NAME} FRAMEWORK DESTINATION ${INSTALL_FRAMEWORK_DIR} COMPONENT ${LINK_COMPONENT_NAME} RUNTIME DESTINATION ${INSTALL_RUNTIME_DIR} COMPONENT ${LINK_COMPONENT_NAME} LIBRARY DESTINATION ${INSTALL_LIBRARY_DIR} COMPONENT ${LINK_COMPONENT_NAME} ARCHIVE DESTINATION ${INSTALL_ARCHIVE_DIR} COMPONENT ${LINK_COMPONENT_NAME}-dev PUBLIC_HEADER DESTINATION ${INSTALL_INCLUDE_DIR} COMPONENT ${LINK_COMPONENT_NAME}-dev) ELSE(LINK_INSTALL_HEADERS) install(TARGETS ${LINK_NAME} FRAMEWORK DESTINATION ${INSTALL_FRAMEWORK_DIR} COMPONENT ${LINK_COMPONENT_NAME} RUNTIME DESTINATION ${INSTALL_RUNTIME_DIR} COMPONENT ${LINK_COMPONENT_NAME} LIBRARY DESTINATION ${INSTALL_LIBRARY_DIR} COMPONENT ${LINK_COMPONENT_NAME} ARCHIVE DESTINATION ${INSTALL_ARCHIVE_DIR} COMPONENT ${LINK_COMPONENT_NAME}-dev) ENDIF(LINK_INSTALL_HEADERS) ENDIF(LINK_INSTALL_LIB) OSSIM_SAVE_INCLUDE_DIRECTORIES() OSSIM_SAVE_FILENAMES() ENDMACRO(OSSIM_LINK_LIBRARY) MACRO(OSSIM_ADD_COMMON_MAKE_UNINSTALL) # get_target_property(TEST_UNINSTALL uninstall CREATED) # IF(NOT TEST_UNINSTALL) #----------------------------------------------------------------------------- ### uninstall target #----------------------------------------------------------------------------- SET(OSSIM_CMAKE_UNINSTALL_CONFIG "${PROJECT_SOURCE_DIR}/CMakeModules/cmake_uninstall.cmake.in") IF(EXISTS ${OSSIM_CMAKE_UNINSTALL_CONFIG}) CONFIGURE_FILE( "${OSSIM_CMAKE_UNINSTALL_CONFIG}" "${CMAKE_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY) ADD_CUSTOM_TARGET(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_BINARY_DIR}/cmake_uninstall.cmake" ) set_target_properties(uninstall PROPERTIES CREATED 1) ENDIF(EXISTS ${OSSIM_CMAKE_UNINSTALL_CONFIG}) # ENDIF(NOT TEST_UNINSTALL) ENDMACRO(OSSIM_ADD_COMMON_MAKE_UNINSTALL) #################################################################################################### # Writes all include directory paths to a central file for later parsing dependencies #################################################################################################### MACRO(OSSIM_SAVE_INCLUDE_DIRECTORIES) GET_DIRECTORY_PROPERTY(include_dir_list INCLUDE_DIRECTORIES) FOREACH(item ${include_dir_list}) FILE(APPEND ${CMAKE_INCLUDE_DIRS_FILE} "${item}\n" ) ENDFOREACH() ENDMACRO(OSSIM_SAVE_INCLUDE_DIRECTORIES) #################################################################################################### # Caches all source file names to a central file for later parsing dependencies #################################################################################################### MACRO(OSSIM_SAVE_FILENAMES) #GET_DIRECTORY_PROPERTY(lib_sources LINK_SOURCES) FOREACH(item ${LINK_SOURCE_FILES}) FILE(APPEND ${CMAKE_FILENAMES_FILE} "${item}\n" ) ENDFOREACH() #GET_DIRECTORY_PROPERTY(app_sources APPLICATION_SOURCES) FOREACH(item ${APPLICATION_SOURCE_FILES}) FILE(APPEND ${CMAKE_FILENAMES_FILE} "${CMAKE_CURRENT_SOURCE_DIR}/${item}\n" ) ENDFOREACH() FOREACH(item ${LINK_HEADERS}) FILE(APPEND ${CMAKE_FILENAMES_FILE} "${item}\n" ) ENDFOREACH() ENDMACRO(OSSIM_SAVE_FILENAMES) ossim-Miami-2.9.1/cmake/CMakeModules/OssimVersion.cmake000066400000000000000000000004601352751253100227460ustar00rootroot00000000000000SET(OSSIM_MAJOR_VERSION_NUMBER "1") SET(OSSIM_MINOR_VERSION_NUMBER "9") SET(OSSIM_PATCH_VERSION_NUMBER "0") SET(OSSIM_RELEASE_NUMBER "1") SET(OSSIM_VERSION "${OSSIM_MAJOR_VERSION_NUMBER}.${OSSIM_MINOR_VERSION_NUMBER}.${OSSIM_PATCH_VERSION_NUMBER}" ) SET(OSSIM_SOVERSION "${OSSIM_MAJOR_VERSION_NUMBER}" ) ossim-Miami-2.9.1/cmake/CMakeModules/Qt5Macros.cmake000066400000000000000000000061601352751253100221270ustar00rootroot00000000000000# This file is included by FindQt5.cmake, don't include it directly. # Copyright (C) 2001-2009 Kitware, Inc. # Copyright (C) 2011 Collabora Ltd. # Copyright (C) 2011 Nokia Corporation # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. macro (QT5_EXTRACT_OPTIONS _qt5_files _qt5_options) set(${_qt5_files}) set(${_qt5_options}) set(_QT5_DOING_OPTIONS FALSE) foreach(_currentArg ${ARGN}) if ("${_currentArg}" STREQUAL "OPTIONS") set(_QT5_DOING_OPTIONS TRUE) else () if(_QT5_DOING_OPTIONS) list(APPEND ${_qt5_options} "${_currentArg}") else() list(APPEND ${_qt5_files} "${_currentArg}") endif() endif () endforeach() endmacro () MACRO (QT5_GET_MOC_FLAGS _moc_flags) SET(${_moc_flags}) GET_DIRECTORY_PROPERTY(_inc_DIRS INCLUDE_DIRECTORIES) FOREACH(_current ${_inc_DIRS}) IF("${_current}" MATCHES "\\.framework/?$") STRING(REGEX REPLACE "/[^/]+\\.framework" "" framework_path "${_current}") SET(${_moc_flags} ${${_moc_flags}} "-F${framework_path}") ELSE("${_current}" MATCHES "\\.framework/?$") SET(${_moc_flags} ${${_moc_flags}} "-I${_current}") ENDIF("${_current}" MATCHES "\\.framework/?$") ENDFOREACH(_current ${_inc_DIRS}) GET_DIRECTORY_PROPERTY(_defines COMPILE_DEFINITIONS) FOREACH(_current ${_defines}) SET(${_moc_flags} ${${_moc_flags}} "-D${_current}") ENDFOREACH(_current ${_defines}) IF(Q_WS_WIN) SET(${_moc_flags} ${${_moc_flags}} -DWIN32) ENDIF(Q_WS_WIN) ENDMACRO (QT5_GET_MOC_FLAGS) # helper macro to set up a moc rule MACRO (QT5_CREATE_MOC_COMMAND infile outfile moc_flags moc_options) # For Windows, create a parameters file to work around command line length limit IF (WIN32) # Pass the parameters in a file. Set the working directory to # be that containing the parameters file and reference it by # just the file name. This is necessary because the moc tool on # MinGW builds does not seem to handle spaces in the path to the # file given with the @ syntax. GET_FILENAME_COMPONENT(_moc_outfile_name "${outfile}" NAME) GET_FILENAME_COMPONENT(_moc_outfile_dir "${outfile}" PATH) IF(_moc_outfile_dir) SET(_moc_working_dir WORKING_DIRECTORY ${_moc_outfile_dir}) ENDIF(_moc_outfile_dir) SET (_moc_parameters_file ${outfile}_parameters) SET (_moc_parameters ${moc_flags} ${moc_options} -o "${outfile}" "${infile}") STRING (REPLACE ";" "\n" _moc_parameters "${_moc_parameters}") FILE (WRITE ${_moc_parameters_file} "${_moc_parameters}") ADD_CUSTOM_COMMAND(OUTPUT ${outfile} COMMAND ${QT_MOC_EXECUTABLE} @${_moc_outfile_name}_parameters DEPENDS ${infile} ${_moc_working_dir} VERBATIM) ELSE (WIN32) ADD_CUSTOM_COMMAND(OUTPUT ${outfile} COMMAND ${QT_MOC_EXECUTABLE} ARGS ${moc_flags} ${moc_options} -o ${outfile} ${infile} DEPENDS ${infile}) ENDIF (WIN32) ENDMACRO (QT5_CREATE_MOC_COMMAND) ossim-Miami-2.9.1/cmake/CMakeModules/cmake_uninstall.cmake.in000066400000000000000000000013651352751253100240710ustar00rootroot00000000000000IF(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_BINARY_DIR@/install_manifest.txt\"") ENDIF() FILE(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files) STRING(REGEX REPLACE "\n" ";" files "${files}") FOREACH(file ${files}) MESSAGE(STATUS "Uninstalling \"${file}\"") IF(EXISTS "${file}") EXEC_PROGRAM( "@CMAKE_COMMAND@" ARGS "-E remove \"${file}\"" OUTPUT_VARIABLE rm_out RETURN_VALUE rm_retval ) IF(NOT "${rm_retval}" STREQUAL 0) MESSAGE(FATAL_ERROR "Problem when removing \"${file}\"") ENDIF() ELSE() MESSAGE(STATUS "File \"${file}\" does not exist.") ENDIF() ENDFOREACH() ossim-Miami-2.9.1/cmake/fortify/000077500000000000000000000000001352751253100164555ustar00rootroot00000000000000ossim-Miami-2.9.1/cmake/fortify/fortify_ar000077500000000000000000000000571352751253100205510ustar00rootroot00000000000000#!/bin/bash sourceanalyzer -b ossimlabs ar $@ ossim-Miami-2.9.1/cmake/fortify/fortify_cc000077500000000000000000000000611352751253100205270ustar00rootroot00000000000000#!/bin/bash sourceanalyzer -b ossimlabs gcc $@ ossim-Miami-2.9.1/cmake/fortify/fortify_cxx000077500000000000000000000000601352751253100207430ustar00rootroot00000000000000#!/bin/bash sourceanalyzer -b ossimlabs g++ $@ ossim-Miami-2.9.1/cmake/fortify/fortify_linux_toolchain.cmake000077500000000000000000000004521352751253100244240ustar00rootroot00000000000000INCLUDE (CMakeForceCompiler) SET(CMAKE_SYSTEM_NAME Linux) SET(CMAKE_SYSTEM_VERSION 1) #specify the compilers SET(CMAKE_C_COMPILER ${CMAKE_SOURCE_DIR}/fortify/fortify_cc) SET(CMAKE_CXX_COMPILER ${CMAKE_SOURCE_DIR}/fortify/fortify_cxx) SET(CMAKE_AR_COMPILER ${CMAKE_SOURCE_DIR}/fortify/fortify_ar) ossim-Miami-2.9.1/cmake/packaging/000077500000000000000000000000001352751253100167175ustar00rootroot00000000000000ossim-Miami-2.9.1/cmake/packaging/pkgconfig/000077500000000000000000000000001352751253100206665ustar00rootroot00000000000000ossim-Miami-2.9.1/cmake/packaging/pkgconfig/ossim.pc.in000066400000000000000000000005001352751253100227440ustar00rootroot00000000000000# pkg-config source file prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} libdir=${exec_prefix}/lib@LIBSUFFIX@ includedir=${prefix}/include Name: ossim Description: Open Source Software Image Map Version: @OSSIM_VERSION@ Requires: openthreads tiff jpeg Conflicts: Libs: -L${libdir} -lossim Cflags: -I${includedir} ossim-Miami-2.9.1/cmake/scripts/000077500000000000000000000000001352751253100164625ustar00rootroot00000000000000ossim-Miami-2.9.1/cmake/scripts/ossim-cmake-config-WINDOWS.bat000066400000000000000000000162161352751253100237630ustar00rootroot00000000000000@echo off ::************************************************************************************* :: :: Windows Batch file for initializing the CMAKE build system for building OSSIM :: with MicroSoft compiler. :: :: This script must be copied into a dedicated build directory. :: The script can then be invoked from that directory. DO NOT run this script out of :: the ossim_package_support/cmake/build_scripts/windows. :: :: Optional arguments (in any order): :: :: win32 | win64 | x64 (defaults to x64) :: vs2005 | vs2010 | vs2015 (defaults vs2015) :: ide | nmake (defaults to ide) :: :: No environment variables need be defined prior to running this script. However, :: OSSIM_DEV_HOME, OSSIM_DEPENDENCIES and OSSIM_BUILD_DIR need to be edited below. :: :: Author: Oscar Kramer, GEOEYE (Aug, 2011) :: ::************************************************************************************* setlocal enabledelayedexpansion set SCRIPT_DIR="%~dp0" :: Edit these to your local system: if NOT DEFINED OSSIM_DEPENDENCIES ( set OSSIM_DEPENDENCIES=C:\GoAgent\pipelines\ossim-windows-temp\ossim-deps-1.0.0 ) :: Default settings: set PLATFORM=x64 set DEVENV=vs2015 set GEN_TYPE=NMAKE set CMAKE_BUILD_TYPE=Release :while_valid_arg if "%1"=="win32" set PLATFORM=Win32 if "%1"=="win64" set PLATFORM=x64 if "%1"=="vs2005" set DEVENV=vs2005 if "%1"=="vs2008" set DEVENV=vs2008 if "%1"=="vs2015" set DEVENV=vs2015 if "%1"=="nmake" set GEN_TYPE=NMAKE shift if not "%1"=="" goto while_valid_arg if not defined OSSIM_DEV_HOME ( pushd %SCRIPT_DIR%..\.. set OSSIM_DEV_HOME=!CD! popd ) IF NOT DEFINED OSSIM_DEPENDENCIES ( set OSSIM_DEPENDENCIES=%OSSIM_DEV_HOME\ossim-deps-1.0.0 ) IF NOT EXIST %OSSIM_DEPENDENCIES% ( echo ERROR: OSSIM_DEPENDENCIES is not set to a valid path. Aborting GOTO ABORTED_END ) IF NOT DEFINED OSSIM_BUILD_DIR ( set OSSIM_BUILD_DIR=%OSSIM_DEV_HOME%\build ) IF NOT EXIST %OSSIM_BUILD_DIR% MKDIR %OSSIM_BUILD_DIR% pushd %OSSIM_BUILD_DIR% :: Change all backslashes to forward slashes in path env vars: set OSSIM_DEV_HOME=%OSSIM_DEV_HOME:\=/% set OSSIM_DEPENDENCIES=%OSSIM_DEPENDENCIES:\=/% set CMAKE_DIR=%OSSIM_DEV_HOME%\ossim\cmake echo. echo Environment settings: echo OSSIM_DEV_HOME = %OSSIM_DEV_HOME% echo OSSIM_DEPENDENCIES = %OSSIM_DEPENDENCIES% echo PLATFORM = %PLATFORM% echo DEVENV = %DEVENV% echo OSSIM_BUILD_DIR = %OSSIM_BUILD_DIR% echo. :: Create system specific subdirectory if needed: if not exist %DEVENV% mkdir %DEVENV% pushd %DEVENV% :: Create platform and target specific subdirectory if needed: if not exist %PLATFORM% mkdir %PLATFORM% pushd %PLATFORM% if not exist %GEN_TYPE% mkdir %GEN_TYPE% pushd %GEN_TYPE% :: Interpret the target system and set up environment: IF %DEVENV%==vs2005 ( IF %PLATFORM%==Win32 ( set TARGET_SYSTEM="Visual Studio 8 2005" call "C:\Program Files (x86)\Microsoft Visual Studio 8\VC\vcvarsall" x86 ) ELSE ( set TARGET_SYSTEM="Visual Studio 8 2005 Win64" call "C:\Program Files (x86)\Microsoft Visual Studio 8\VC\vcvarsall" x64 ) ) IF %DEVENV%==vs2008 ( IF %PLATFORM%==Win32 ( set TARGET_SYSTEM="Visual Studio 9 Win32" call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall" x86 ) ELSE ( set TARGET_SYSTEM="Visual Studio 9 Win64" call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall" x64 ) ) IF %DEVENV%==vs2010 ( IF %PLATFORM%==Win32 ( set TARGET_SYSTEM="Visual Studio 10 Win32" call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall" x86 ) ELSE ( set TARGET_SYSTEM="Visual Studio 10 Win64" call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall" x64 ) ) IF %DEVENV%==vs2015 ( IF %PLATFORM%==Win32 ( set TARGET_SYSTEM="Visual Studio 14 Win32" call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall" x86 ) ELSE ( set TARGET_SYSTEM="Visual Studio 14 Win64" call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall" x64 ) ) set DEPLIBDIR=%OSSIM_DEPENDENCIES%/lib set DEPINCDIR=%OSSIM_DEPENDENCIES%/include :: Here are the cmake options. Everything is about setting variables except the :: the last line (the business end). Make sure that source path points to the :: ossim_package_support/cmake directory containing the top-level CMakeLists.txt rem set CMAKE_PARAMETERS=^ rem -D%PLATFORM%_USE_MP=ON ^ rem -DBUILD_LIBRARY_DIR=lib ^ rem -DBUILD_OSSIM=ON ^ rem -DBUILD_OSSIM_MPI_SUPPORT=0 ^ rem -DBUILD_RUNTIME_DIR=bin ^ rem -DBUILD_SHARED_LIBS=ON ^ rem -DOPENTHREADS_LIBRARY=%DEPLIBDIR%/OpenThreadsx64.lib ^ rem -DTIFF_LIBRARY=%DEPLIBDIR%/libtiff_i.lib ^ rem -DTIFF_INCLUDE_DIR=%DEPINCDIR%/tiff ^ rem -DPROJ4_LIBRARY=%DEPLIBDIR%/proj.lib ^ rem -DPODOFO_INCLUDE_DIR=%DEPINCDIR% ^ rem -DPODOFO_LIBRARY=%DEPLIBDIR%/podofo.lib ^ rem -DEXPAT_INCLUDE_DIR=%DEPINCDIR%/expat ^ rem -DEXPAT_LIBRARY=%DEPLIBDIR%/podofo.lib ^ rem -DGEOTIFF_LIBRARY=%DEPLIBDIR%/geotiff_i.lib ^ rem -DGEOTIFF_INCLUDE_DIR=%DEPINCDIR%/geotiff ^ rem -DFFTW3_LIBRARY=%DEPLIBDIR%/libfftw3-3.lib ^ rem -DJPEG_LIBRARY=%DEPLIBDIR%/libjpeg.lib ^ rem -DJPEG_INCLUDE_DIR=%DEPINCDIR%/jpeg8a ^ rem -DFREETYPE_LIBRARY=%DEPLIBDIR%/freetype237.lib ^ rem -DFREETYPE_INCLUDE_DIRS=%DEPINCDIR%/freetype ^ rem -DZLIB_LIBRARY=%DEPLIBDIR%/zlib.lib ^ rem -DZLIB_INCLUDE_DIR=%DEPINCDIR%/zlib ^ rem -DOSSIM_COMPILE_WITH_FULL_WARNING=ON ^ rem -DOSSIM_DEPENDENCIES=%OSSIM_DEPENDENCIES%^ rem -DBUILD_SHARED_LIBS=ON ^ rem %OSSIM_BUILD_DIR% set CMAKE_PARAMETERS=^ -DCMAKE_BUILD_TYPE=%CMAKE_BUILD_TYPE% ^ -DOSSIM_DEV_HOME=%OSSIM_DEV_HOME% ^ -D%PLATFORM%_USE_MP=ON ^ -DBUILD_LIBRARY_DIR=lib ^ -DBUILD_OMS=%BUILD_OMS% ^ -DBUILD_CNES_PLUGIN=%BUILD_CNES_PLUGIN% ^ -DBUILD_GEOPDF_PLUGIN=%BUILD_GEOPDF_PLUGIN% ^ -DBUILD_GDAL_PLUGIN=%BUILD_GDAL_PLUGIN% ^ -DBUILD_HDF5_PLUGIN=%BUILD_HDF5_PLUGIN% ^ -DBUILD_KAKADU_PLUGIN=%BUILD_KAKADU_PLUGIN% ^ -DKAKADU_ROOT_SRC=%KAKADU_ROOT_SRC% ^ -DKAKADU_AUX_LIBRARY=%KAKADU_AUX_LIBRARY% ^ -DKAKADU_LIBRARY=%KAKADU_LIBRARY% ^ -DBUILD_KML_PLUGIN=%BUILD_KML_PLUGIN% ^ -DBUILD_MRSID_PLUGIN=%BUILD_MRSID_PLUGIN% ^ -DMRSID_DIR=%MRSID_DIR% ^ -DOSSIM_PLUGIN_LINK_TYPE=SHARED ^ -DBUILD_OPENCV_PLUGIN=%BUILD_OPENCV_PLUGIN% ^ -DBUILD_OPENJPEG_PLUGIN=%BUILD_OPENJPEG_PLUGIN% ^ -DBUILD_PDAL_PLUGIN=5BUILD_PDAL_PLUGIN% ^ -DBUILD_PNG_PLUGIN=%BUILD_PNG_PLUGIN% ^ -DBUILD_SQLITE_PLUGIN=%BUILD_SQLITE_PLUGIN% ^ -DBUILD_OSSIM_VIDEO=%BUILD_OSSIM_VIDEO% ^ -DBUILD_OSSIM_GUI=%BUILD_OSSIM_GUI% ^ -DBUILD_OSSIM_WMS=%BUILD_OSSIM_WMS% ^ -DBUILD_OSSIM_PLANET=%BUILD_OSSIM_PLANET% ^ %CMAKE_DIR% :: Finally the cmake commands themselves: echo TARGET_SYSTEM = %TARGET_SYSTEM% IF %GEN_TYPE%==IDE ( echo Generating IDE solution and project files... cmake -G %TARGET_SYSTEM% %CMAKE_PARAMETERS% ) ELSE ( echo Generating nmake makefiles... cmake -G "NMake Makefiles" %CMAKE_PARAMETERS% ) :: Restore environment popd popd popd popd set OSSIM_DEV_HOME=%OSSIM_DEV_HOME:/=\% set OSSIM_DEPENDENCIES=%OSSIM_DEPENDENCIES:/=\% echo Successfully configured build environment. goto FINISHED :ABORTED_END echo Script terminated prematurely... :FINISHED pause ossim-Miami-2.9.1/cmake/scripts/ossim-cmake-config.sh000077500000000000000000000204501352751253100224750ustar00rootroot00000000000000#!/bin/bash ########################################################################## # # CMake Configuration for OSSIM on Linux # # DO NOT RELOCATE THIS SCRIPT. Its location is used to resolve relative # directory paths. # # Usage: [] # # where the optional is one of the following literals # (case-insensitive): # # "release" (default), # "debug", # "relWithDebInfo", # "minSizeRel", # "eclipse" # # If a build type = "eclipse" is specified, cmake will generate a Debug # build environment along with Eclipse CDT4 project files (in the build # directory) for importing as existing project. # # Instructions: Run this script to build the repository. This script can be # run from any directory, but will assume a default relative directory # heirarchy when searching for related items. # # No env vars need to be predefined. The build output will be written to # $OSSIM_DEV_HOME/build/ where $OSSIM_DEV_HOME is the top-level # folder containing all OSSIM repositories (including this one). # # For customized output location, you can define the env var OSSIM_BUILD_DIR # prior to running this script, and the output will be written there. # ########################################################################## # Uncomment following line to debug script line by line: #set -x; trap read debug # Fetch the build type from command line: BUILD_TYPE_ARG="${1}" case "$BUILD_TYPE_ARG" in DEBUG|Debug) CMAKE_BUILD_TYPE="Debug" ;; ECLIPSE) CMAKE_BUILD_TYPE="Debug" ;; RELEASE|Release) CMAKE_BUILD_TYPE="Release" ;; RELWITHDEBINFO|RelWithDebInfo) CMAKE_BUILD_TYPE="RelWithDebInfo" ;; MINSIZEREL|MinSizeRel) CMAKE_BUILD_TYPE="MinSizeRel" ;; *) CMAKE_BUILD_TYPE="Release" esac # Establish location of master CMakeLists.txt file. This is the cmake file # used to build all OSSIM-related repos (plugins, tests, oms, etc) SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) pushd $SCRIPT_DIR/.. >/dev/null CMAKE_DIR=$PWD popd >/dev/null # Establish the top-level directory above repo containing this script if [ -z $OSSIM_DEV_HOME ]; then pushd $CMAKE_DIR/../.. >/dev/null export OSSIM_DEV_HOME=$PWD popd >/dev/null fi # Establish CMake's output build directory: if [ -z "$OSSIM_BUILD_DIR" ]; then OSSIM_BUILD_DIR=$OSSIM_DEV_HOME/build fi # Establish CMAKE's install directory: if [ -z "$OSSIM_INSTALL_PREFIX" ]; then OSSIM_INSTALL_PREFIX=$OSSIM_DEV_HOME/install fi CMAKE_G_ARG="Unix Makefiles" echo "OSSIM_BUILD_DIR=$OSSIM_BUILD_DIR" mkdir -p $OSSIM_BUILD_DIR pushd $OSSIM_BUILD_DIR >/dev/null rm -f CMakeCache.txt # Check for ENV vars set to override hardcoded plugins switches here: if [ -z $BUILD_OSSIM_VIDEO ]; then BUILD_OSSIM_VIDEO=OFF fi if [ -z $BUILD_OSSIM_PLANET ]; then BUILD_OSSIM_PLANET=OFF fi if [ -z $BUILD_OSSIM_WMS ]; then BUILD_OSSIM_WMS=OFF fi if [ -z $BUILD_OSSIM_GUI ]; then BUILD_OSSIM_GUI=OFF fi if [ -z $BUILD_OSSIM_PLANET_GUI ]; then BUILD_OSSIM_PLANET_GUI=OFF fi if [ -z $BUILD_OSSIM_QT4 ]; then BUILD_OSSIM_QT4=OFF fi if [ -z $BUILD_OMS ]; then BUILD_OMS=OFF fi if [ -z $BUILD_OSSIM_APPS ] ; then export BUILD_OSSIM_APPS=ON fi if [ -z $BUILD_OSSIM_HDF5_SUPPORT ] ; then export BUILD_OSSIM_HDF5_SUPPORT=OFF fi if [ -z $BUILD_OSSIM_CURL_APPS ] ; then export BUILD_OSSIM_CURL_APPS=OFF fi if [ -z $BUILD_OSSIM_ISA ] ; then export BUILD_OSSIM_ISA=OFF fi if [ -z $BUILD_OSSIM_FPGA ] ; then export BUILD_OSSIM_FPGA=OFF fi # Plugins: if [ -z $BUILD_ATP_PLUGIN ]; then BUILD_ATP_PLUGIN=OFF fi if [ -z $BUILD_CNES_PLUGIN ]; then BUILD_CNES_PLUGIN=OFF fi if [ -z $BUILD_CSM_PLUGIN ]; then BUILD_CSM_PLUGIN=OFF fi if [ -z $BUILD_FFTW3_PLUGIN ]; then BUILD_FFTW3_PLUGIN=OFF fi if [ -z $BUILD_GDAL_PLUGIN ]; then BUILD_GDAL_PLUGIN=OFF fi if [ -z $BUILD_GEOPDF_PLUGIN ]; then BUILD_GEOPDF_PLUGIN=OFF fi if [ -z $BUILD_HDF5_PLUGIN ]; then BUILD_HDF5_PLUGIN=OFF fi if [ -z $BUILD_MSP_PLUGIN ]; then BUILD_MSP_PLUGIN=OFF fi if [ -z $BUILD_KAKADU_PLUGIN ]; then BUILD_KAKADU_PLUGIN=OFF fi if [ -z $BUILD_KML_PLUGIN ]; then BUILD_KML_PLUGIN=OFF fi if [ -z $BUILD_MRSID_PLUGIN ]; then BUILD_MRSID_PLUGIN=OFF fi if [ -z $BUILD_OPENCV_PLUGIN ]; then BUILD_OPENCV_PLUGIN=OFF fi if [ -z $BUILD_OPENJPEG_PLUGIN ]; then BUILD_OPENJPEG_PLUGIN=OFF fi if [ -z $BUILD_PDAL_PLUGIN ]; then BUILD_PDAL_PLUGIN=OFF fi if [ -z $BUILD_PNG_PLUGIN ]; then BUILD_PNG_PLUGIN=OFF fi if [ -z $BUILD_POTRACE_PLUGIN ]; then BUILD_POTRACE_PLUGIN=OFF fi if [ -z $BUILD_REG_PLUGIN ]; then BUILD_REG_PLUGIN=OFF fi if [ -z $BUILD_JPEG12_PLUGIN ]; then BUILD_JPEG12_PLUGIN=OFF fi if [ -z $BUILD_SQLITE_PLUGIN ]; then BUILD_SQLITE_PLUGIN=OFF fi if [ -z $BUILD_WEB_PLUGIN ]; then BUILD_WEB_PLUGIN=OFF fi if [ -z $BUILD_AWS_PLUGIN ] ; then export BUILD_AWS_PLUGIN=OFF fi if [ -z $BUILD_OSSIM_FRAMEWORKS ] ; then export BUILD_OSSIM_FRAMEWORKS=ON fi if [ "${BUILD_OSSIM_GUI}" == "ON" ]; then if [ -z $QT_CMAKE_DIR ]; then if [ -d "/usr/lib64/cmake/Qt5Core" ]; then export QT_CMAKE_DIR="/usr/lib64/cmake" elif [ -d "/usr/local/opt/qt5/lib/cmake" ]; then export QT_CMAKE_DIR="/usr/local/opt/qt5/lib/cmake" fi fi if [ -z $Qt5Core_DIR ]; then export Qt5Core_DIR=${QT_CMAKE_DIR}/Qt5Core fi if [ -z $Qt5Widgets_DIR ]; then export Qt5Widgets_DIR=${QT_CMAKE_DIR}/Qt5Widgets fi if [ -z $Qt5OpenGL_DIR ]; then export Qt5OpenGL_DIR=${QT_CMAKE_DIR}/Qt5OpenGL fi fi if [ -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk ] ; then export CMAKE_OSX_SYSROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk elif [ -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/ ] ; then export CMAKE_OSX_SYSROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk fi if [ "${BUILD_WITH_FORTIFY}" == "true" ] ; then INSERT_FORTIFY_TOOLCHAIN=-DCMAKE_TOOLCHAIN_FILE=${CMAKE_DIR}/fortify/fortify_linux_toolchain.cmake echo;echo "Building with fortify toolchain"; echo fi # CMAKE command cmake -G "$CMAKE_G_ARG" "$INSERT_FORTIFY_TOOLCHAIN" \ -DCMAKE_CXX_FLAGS=$CMAKE_CXX_FLAGS \ -DCMAKE_BUILD_TYPE=$CMAKE_BUILD_TYPE \ -DOSSIM_DEV_HOME=$OSSIM_DEV_HOME \ -DCMAKE_OSX_ARCHITECTURES="x86_64" \ -DCMAKE_OSX_SYSROOT=$CMAKE_OSX_SYSROOT \ -DCMAKE_OSX_DEPLOYMENT_TARGET=$CMAKE_OSX_DEPLOYMENT_TARGET \ -DBUILD_OSSIM_FRAMEWORKS=${BUILD_OSSIM_FRAMEWORKS} \ -DBUILD_OMS=$BUILD_OMS \ -DBUILD_OSSIM_PLANET_GUI=${BUILD_OSSIM_PLANET_GUI} \ -DBUILD_ATP_PLUGIN=$BUILD_ATP_PLUGIN \ -DBUILD_CNES_PLUGIN=$BUILD_CNES_PLUGIN \ -DBUILD_CSM_PLUGIN=$BUILD_CSM_PLUGIN \ -DBUILD_DSMG=$BUILD_DSMG \ -DBUILD_OSSIM_ISA=$BUILD_OSSIM_ISA \ -DBUILD_OSSIM_FPGA=$BUILD_OSSIM_FPGA \ -DBUILD_FFTW3_PLUGIN=$BUILD_FFTW3_PLUGIN \ -DBUILD_GEOPDF_PLUGIN=$BUILD_GEOPDF_PLUGIN \ -DBUILD_GDAL_PLUGIN=$BUILD_GDAL_PLUGIN \ -DBUILD_HDF5_PLUGIN=$BUILD_HDF5_PLUGIN \ -DBUILD_MSP_PLUGIN=$BUILD_MSP_PLUGIN \ -DBUILD_KAKADU_PLUGIN=$BUILD_KAKADU_PLUGIN \ -DBUILD_JPEG12_PLUGIN=$BUILD_JPEG12_PLUGIN \ -DKAKADU_ROOT_SRC=$KAKADU_ROOT_SRC \ -DKAKADU_AUX_LIBRARY=$KAKADU_AUX_LIBRARY \ -DKAKADU_LIBRARY=$KAKADU_LIBRARY \ -DBUILD_KML_PLUGIN=$BUILD_KML_PLUGIN \ -DBUILD_MRSID_PLUGIN=$BUILD_MRSID_PLUGIN \ -DMRSID_DIR=$MRSID_DIR \ -DOPENCV_HOME=$OPENCV_HOME \ -DCSM_HOME=$CSM_HOME \ -DMSP_HOME=$MSP_HOME \ -DOSSIM_PLUGIN_LINK_TYPE=SHARED \ -DBUILD_OPENCV_PLUGIN=$BUILD_OPENCV_PLUGIN \ -DBUILD_OPENJPEG_PLUGIN=$BUILD_OPENJPEG_PLUGIN \ -DBUILD_PDAL_PLUGIN=$BUILD_PDAL_PLUGIN \ -DBUILD_PNG_PLUGIN=$BUILD_PNG_PLUGIN \ -DBUILD_AWS_PLUGIN=$BUILD_AWS_PLUGIN \ -DBUILD_POTRACE_PLUGIN=$BUILD_POTRACE_PLUGIN \ -DBUILD_REG_PLUGIN=$BUILD_REG_PLUGIN \ -DBUILD_SQLITE_PLUGIN=$BUILD_SQLITE_PLUGIN \ -DBUILD_WEB_PLUGIN=$BUILD_WEB_PLUGIN \ -DBUILD_OSSIM_VIDEO=$BUILD_OSSIM_VIDEO \ -DBUILD_OSSIM_GUI=$BUILD_OSSIM_GUI \ -DBUILD_OSSIM_QT4=$BUILD_OSSIM_QT4 \ -DBUILD_OSSIM_WMS=$BUILD_OSSIM_WMS \ -DBUILD_OSSIM_PLANET=$BUILD_OSSIM_PLANET \ -DBUILD_OSSIM_APPS=$BUILD_OSSIM_APPS \ -DBUILD_OSSIM_CURL_APPS=$BUILD_OSSIM_CURL_APPS \ -DBUILD_OSSIM_HDF5_SUPPORT=$BUILD_OSSIM_HDF5_SUPPORT \ -DOSSIM_BUILD_ADDITIONAL_DIRECTORIES=$OSSIM_BUILD_ADDITIONAL_DIRECTORIES \ -DOSSIM_BUILD_ADDITIONAL_PLUGIN_DIRECTORIES=$OSSIM_BUILD_ADDITIONAL_PLUGIN_DIRECTORIES \ $CMAKE_DIR echo CMAKE_COMMAND: $CMAKE_COMMAND popd >/dev/null ossim-Miami-2.9.1/doc/000077500000000000000000000000001352751253100144605ustar00rootroot00000000000000ossim-Miami-2.9.1/doc/Doxyfile000066400000000000000000001760041352751253100161760ustar00rootroot00000000000000# Doxyfile 1.7.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = "OSSIM - Open Source Software Image Map" # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = "Version $(OSSIM_VERSION)" # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = . # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful is your file systems # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = YES # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 4 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this # tag. The format is ext=language, where ext is a file extension, and language # is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, # C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make # doxygen treat .inc files as Fortran files (default is PHP), and .f files as C # (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions # you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen to replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penality. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will rougly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols SYMBOL_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = YES # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespace are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or define consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and defines in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. The create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # This WARN_NO_PARAMDOC option can be abled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = ../include \ ../src # ../../ossim-plugins (don't forget backslash after src above) # (other C++ repositories as desired) # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx # *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 FILE_PATTERNS = *.cpp \ *.h \ *.cc \ *.dox # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = CVS \ .git # The EXCLUDE_SYMLINKS tag can be used select whether or not files or # directories that are symbolic links (a Unix filesystem feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = *CVS* # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER # is applied to all files. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = YES # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 4 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = ossim #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # If the HTML_TIMESTAMP tag is set to YES then the generated HTML # documentation will contain the timesstamp. HTML_TIMESTAMP = NO # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # stylesheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = NO # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = doc # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [1..20]) # that doxygen will group on one line in the generated HTML documentation. ENUM_VALUES_PER_LINE = 4 # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. GENERATE_TREEVIEW = NO # By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, # and Class Hierarchy pages using a tree view instead of an ordered list. USE_INLINE_TREES = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all function-like macros that are alone # on a line, have an all uppercase name, and do not end with a semicolon. Such # function macros are typically used for boiler-plate code, and will confuse # the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option is superseded by the HAVE_DOT option below. This is only a # fallback. It is recommended to install and use dot, since it yields more # powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # By default doxygen will write a font called FreeSans.ttf to the output # directory and reference it in all dot files that doxygen generates. This # font does not include all possible unicode characters however, so when you need # these (or just want a differently looking font) you can specify the font name # using DOT_FONTNAME. You need need to make sure dot is able to find the font, # which can be done by putting it in a standard location or by setting the # DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory # containing the font. DOT_FONTNAME = FreeSans.ttf # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the output directory to look for the # FreeSans.ttf font (which doxygen will put there itself). If you specify a # different font using DOT_FONTNAME you can set the path where dot # can find it using this tag. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, jpg, or gif # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES ossim-Miami-2.9.1/doc/dependencies.md000066400000000000000000000024171352751253100174340ustar00rootroot00000000000000# Dependencies for the OSSIM baseline * [curl-7.46.0](https://s3.amazonaws.com/ossimlabs/dependencies/source/curl-7.46.0.zip) * [expat-2.1.0](https://s3.amazonaws.com/ossimlabs/dependencies/source/expat-2.1.0.zip) * [gdal-2.0.1](https://s3.amazonaws.com/ossimlabs/dependencies/source/gdal-2.0.1.zip) * [geos-3.4.2](https://s3.amazonaws.com/ossimlabs/dependencies/source/geos-3.4.2.zip) * [gpstk-2.5](https://s3.amazonaws.com/ossimlabs/dependencies/source/gpstk-2.5.zip) * [hdf5-1.8.16](https://s3.amazonaws.com/ossimlabs/dependencies/source/hdf5-1.8.16.zip) * [libgeotiff-1.4.1.](https://s3.amazonaws.com/ossimlabs/dependencies/source/libgeotiff-1.4.1.zip) * [libjpeg-turbo-1.4.2](https://s3.amazonaws.com/ossimlabs/dependencies/source/libjpeg-turbo-1.4.2.zip) * [libpng-1.2.43](https://s3.amazonaws.com/ossimlabs/dependencies/source/libpng-1.2.43.zip) * [opencv-3.1.0](https://s3.amazonaws.com/ossimlabs/dependencies/source/opencv-3.1.0.zip) * [proj-4.9.2](https://s3.amazonaws.com/ossimlabs/dependencies/source/proj-4.9.2.zip) * [sqlite-3100100](https://s3.amazonaws.com/ossimlabs/dependencies/source/sqlite-3100100.zip) * [tiff-4.0.6](https://s3.amazonaws.com/ossimlabs/dependencies/source/tiff-4.0.6.zip) * [zlib-1.2.5](https://s3.amazonaws.com/ossimlabs/dependencies/source/zlib-1.2.5.zip)ossim-Miami-2.9.1/include/000077500000000000000000000000001352751253100153365ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/000077500000000000000000000000001352751253100164705ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/base/000077500000000000000000000000001352751253100174025ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/base/Barrier.h000066400000000000000000000065761352751253100211570ustar00rootroot00000000000000#ifndef ossimBarrier_HEADER #define ossimBarrier_HEADER 1 #include #include #include #include namespace ossim{ /** * Barrier is a class used to block threads so we can synchronize and entry point. * * In this example we show how to block the threads so they all start at the * same time when executing their work. * Example: * * @code * #include * #include * int nThreads = 2; * ossim::Barrier barrierStart(nThreads) * // one more for main thread * ossim::Barrier barrierFinished(nThreads+1); * * class TestThread : public ossim::Thread * { * public: * TestThread():ossim::Thread(){} * ~TestThread(){ * waitForCompletion(); * } * * protected: * virtual void run() * { * barrierStart.block(); * for(int x =0 ; x < 10;++x){ * std::cout << "THREAD: " << getCurrentThreadId() << "\n"; * sleepInMilliSeconds(10); * interrupt(); * } * barrierFinished.block(); * } * }; * * int main(int agrc, char* argv[]) * { * std::vector > threads(nThreads); * for(auto& thread:threads) * { * thread = std::make_shared(); * thread->start(); * } * // block main until barrier enters their finished state * barrierFinished.block(); * * // you can also reset the barriers and run again * barrierFinished.reset(); * barrierStart.reset(); * for(auto& thread:threads) * { * thread->start(); * } * barrierFinished.block(); * } * * @endcode */ class OSSIM_DLL Barrier { public: /** * Constructor * * @param n is the number of threads you wish to block */ Barrier(ossim_int32 n); /** * Destructor will reset and release all blocked threads. */ ~Barrier(); /** * block will block the thread based on a wait condition. it will verify * if the thread can be blocked by testing if the number * of blocked threads is less than the total number to blocked threads. If * the total is reached then all threads are notified and woken up and released */ void block(); /** * Will reset the barrier to the original values. * It will also release all blocked threads and wait for their release * before resetting. */ void reset(); /** * Will reset the barrier to a new block count. * It will also release all blocked threads and wait for their release * before resetting. * * @param maxCount is the max number of threads to block */ void reset(ossim_int32 maxCount); ossim_int32 getMaxCount()const; ossim_int32 getBlockedCount()const; protected: ossim_int32 m_maxCount; ossim_int32 m_blockedCount; std::atomic m_waitCount; mutable std::mutex m_mutex; std::condition_variable m_conditionalBlock; /** * Will be used for destructing and resetting. * resetting should only happen in the main * thread */ std::condition_variable m_conditionalWait; }; } #endifossim-Miami-2.9.1/include/ossim/base/Block.h000066400000000000000000000061511352751253100206100ustar00rootroot00000000000000#ifndef ossimBlock_HEADER #define ossimBlock_HEADER 1 #include #include #include #include namespace ossim{ /** * This is a very simple block interface. This allows one to control * how their threads are blocked * * There is a release state flag that tells the call to block to block the calling * thread or release the thread(s) that are currently blocked * * For a very simple use case we will start a thread and call block and have * the main sleep for 2 seconds before releasing the thread * @code * #include * #include * std::shared_ptr block = std::make_shared(); * class TestThread : public ossim::Thread * { * public: * * protected: * virtual void run(){ * block->block(); * std::cout << "STARING!!!!!!!\n"; * } * }; * int main(int argc, char *argv[]) * { * TestThread t1; * t1.start(); * * std::cout << "WAITING 2 SECOND to release block\n"; * ossim::Thread::sleepInSeconds(2); * block->release(); * ossim::Thread::sleepInSeconds(2); * } * @endcode */ class OSSIM_DLL Block { public: /** * Allows one the construct a Block with a release state. */ Block(bool releaseFlag=false); /** * Destructor * * Will set internally call release */ ~Block(); /** * Will set the relase flag and wake up all threads to test the condition again. */ void set(bool releaseFlag); /** * Will block the calling thread based on the internal condition. If the internal * condition is set to release then it will return without blocking. */ void block(); /** * Will block the calling thread base on the internal condition. If the internal * condition is set to release the it will return without blocking. If the internal * condition is set to not release then it will block for the specified time in * milliseconds * * @param waitTimeMillis specifies the amount of time to wait for the release */ void block(ossim_uint64 waitTimeMillis); /** * Releases the threads and will not return until all threads are released */ void release(); /** * Simple reset the values. Will not do any releasing */ void reset(); private: /** * Used by the conditions */ mutable std::mutex m_mutex; /** * The release state. */ std::atomic m_release; /** * Condition that tests the release state */ std::condition_variable m_conditionVariable; /** * Used to count the number of threads blocked or * waiting on the condition */ std::atomic m_waitCount; /** * Will be used for destructing and releasing. * resetting should only happen in the main * thread */ std::condition_variable m_conditionalWait; }; } #endifossim-Miami-2.9.1/include/ossim/base/BlockIStream.h000066400000000000000000000036321352751253100220760ustar00rootroot00000000000000#ifndef ossimBlockStream_HEADER #define ossimBlockStream_HEADER 1 #include namespace ossim { /** * * @brief Allows one to adapt any input stream to be block aligned * for any read it will internally read overlapping blocks filling * the request. * * Example: * @code * * ossim_uint64 blockSize = 4096 * std::shared_ptr reader = std::make_shared(streamToAdapt, blockSize) * * reader->seekg(10); * reader->read(buf, 100); * @endcode * * This will read a block of data from 0-4095 and then fill the buffer * with 100 bytes of data. * * if another call to: reader->read(buf, 10) * it will not reload the block but instead read from memory * */ class BlockIStream : public ossim::istream { public: /** * Constructor must be initialized with an inputstream. * * @param adaptStream Currenlty a required parameter and is initialized on construction. Takes an input std::istream to force block aligned * requests * @param blockSize Specify the block size to use */ BlockIStream(std::shared_ptr adaptStream, ossim_uint64 blockSize=4096): ossim::istream(&m_blockStreamBuffer), m_adaptStream(adaptStream), m_blockStreamBuffer(adaptStream.get(), blockSize) { } /** * @brief Destructor will set any shared pointer to 0 */ virtual ~BlockIStream(){ m_adaptStream = 0; } /** * Maintain a shared pointer to the stream we are adapting * to be block aligned. */ std::shared_ptr m_adaptStream; /** * * The buffer where all the block align implementation resides * */ BlockStreamBuffer m_blockStreamBuffer; }; } #endif ossim-Miami-2.9.1/include/ossim/base/BlockStreamBuffer.h000066400000000000000000000211741352751253100231200ustar00rootroot00000000000000#ifndef ossimBlockStreamBuffer_HEADER #define ossimBlockStreamBuffer_HEADER 1 #include #include #include #include namespace ossim{ /** * @brief This is a utility class used by the BlockStreamBuffer. * This class will hold information regarding the block that * is currently loaded. It holds the start byte and the valid * size and the block size of the buffer. The valid size * is used because if we are at the end of a stream we could * have a partial block. * */ class OSSIM_DLL BlockBufInfo{ public: BlockBufInfo(): m_startByte(0), m_blockSize(0), m_validSize(0), m_blockBufferPtr(0), m_blockLoaded(false){ } /** * Returns the index of a block * * @param pos Is the aboslute byte position * @return The block index for the abosolute * position */ ossim_int64 getBlockIndex(ossim_int64 pos){ ossim_int64 result = -1; if(m_blockSize&&m_blockBufferPtr&&(pos>=0)) { result = pos/m_blockSize; } return result; } /** * This just tests if the given abolute position * is within a block window. We will usually call * @see isWithinValidWindow. * @param pos Absolute position * @return true if we are inside the defined window * and false otherwise. */ bool isWithinWindow(ossim_int64 pos)const{ return (m_blockLoaded&& (pos>=m_startByte)&& (pos<(m_startByte+m_blockSize))); } /** * This just tests if the given abolute position * is within a valid window. A valid window represents * partial blocks. * @param pos Absolute position * @return true if we are inside the defined window * and false otherwise. */ bool isWithinValidWindow(ossim_int64 pos)const{ return (m_blockLoaded&& (pos>=m_startByte)&& (pos=0) return m_startByte+(m_validSize); return m_startByte; } /** * Get the starting address in the buffer of the absolute position. * @param absolutePosition The absolute byte position * @return The starting address at the aboslute position or 0 if * the absolute position is outside the windows */ const char* getBufferStart(ossim_int64 absolutePosition)const{ if(isWithinValidWindow(absolutePosition)) { return m_blockBufferPtr+(absolutePosition-m_startByte); } return 0; } /** * @return The starting address of the block buffer */ const char* getBuffer()const{ return m_blockBufferPtr; } /** * @return The starting address of the block buffer */ char* getBuffer(){ return m_blockBufferPtr; } /** * @return true if the the block is valid and loaded or false * otherwise. */ bool isLoaded()const{return m_blockLoaded;} /** * Will set the buffer and then reset the loaded flag to be false. * * @param bufPtr is the starting address of the block buffer * @param blockSize is the size of the buffer * */ void setBuffer(char* bufPtr, ossim_uint32 blockSize) { m_blockBufferPtr = bufPtr; m_blockSize = blockSize; m_blockLoaded = false; } /** * Is the starting absolute byte offset for the buffer */ ossim_int64 m_startByte; /** * Is the size of the buffer */ ossim_int64 m_blockSize; /** * is the valid size of the buffer. In most cases this is equal to the * blockSize but if at the end of a stream you could have a partial * buffer. */ ossim_int64 m_validSize; /** * Starting address of the block. This is not managed by this class and * will not be deleted. */ char* m_blockBufferPtr; /** * Variable used to invalidate a block or specify whether the block is loaded */ bool m_blockLoaded; }; /** * This is the BlockStreamBuffer class and derives from * stream buf. This class * */ class OSSIM_DLL BlockStreamBuffer : public std::streambuf{ public: BlockStreamBuffer(ossim::istream* adaptStream=0, ossim_uint64 blockSize=0); virtual ~BlockStreamBuffer(){ m_adaptStream=0; } protected: /** * The block buffer that we set the buf pointers to */ std::vector m_blockBuffer; /** * holds the current absolute byte position */ ossim_int64 m_currentPosValue; /** * Holds the information about the block. It tells us * if the block is currently loaded and what the valid size * is */ BlockBufInfo m_blockInfo; /** * The stream we are adapting */ ossim::istream* m_adaptStream; /** * This is a virtual method that can be overriden. * pubsetbuf can be called and calls this protected method * to set a buffer. * * @param s The starting address of a byte buffer * @param n The size of the buffer */ virtual std::streambuf* setbuf (char* s, std::streamsize n); /** * * setgPtrs calls setg and sets the eback egptr and gptr. to the * managed buffer's valid window * */ void setgPtrs(); /** * loadBlock will load data into the current block and call the setgPtrs * to adjust the internal pointers tha the base streambuf may use * */ void loadBlock(); /** * this is a protected method overriden from streambuf base. * * we will convert the offset byte to an absolute if we can and * then call the seek pos for the absolute seek */ virtual pos_type seekoff(off_type offset, std::ios_base::seekdir dir, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out); /** * seekpos is overriden from the base streambuf class. This is the * seek of the aboslute position. We will check to see if the new * position resides in the block and if so we just update our pointers * and return the pos. If bnot then we use the adapted stream call * to seek to the position and update our internal pointers. * * @param pos The absolute position to seek to * @mode the mode used. Should be in * @return The absolute position if successful or EOF if not. */ virtual pos_type seekpos(pos_type pos, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out); /** * xsgetn is a protected virtual method that we override from the base * streambuf. The method will load blocks of data to service the requested * buffer to fill. If the request covers several block it will iterate * and load each block of data until the request is satisfied. * * @param s The destination buffer large enough to hold the characters * being requested * @param n The number of characters to request from the input stream * * @return The number of bytes read or -1 if failed */ virtual std::streamsize xsgetn(char_type* s, std::streamsize n); /** * underflow is overriden from the base streambuf. It check to see * if the current block is loaded and if not load the block. The method * returns what is currently pointed to by the absolute offset or basically * return *gptr(). * * @return the current byte we are pointing to. */ virtual int underflow(); /** * syncCurrentPosition is a utility method that we call internally in * the overriden protected methods that will sync the location of the gptr * to the absolute byte offset variable we are using internally. The problem * is, when things like ignore(...) peek(...) and other options are used * on an input stream the base might adjust the gptr location. When this * is adjusted outside our control the offsets might get out of sync * this is called to ensure this does not happen * */ void syncCurrentPosition(); }; } #endif ossim-Miami-2.9.1/include/ossim/base/FactoryListBase.h000066400000000000000000000102541352751253100226130ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Class declaration of ossimFactoryListInterface. // //************************************************************************************************** // $Id$ #ifndef ossimFactoryListBase_HEADER #define ossimFactoryListBase_HEADER 1 #include #include #include namespace ossim { template class FactoryListBase { public: typedef std::vector FactoryListType; typedef std::vector TypeNameList; FactoryListBase(){} /** * This is for backward compatability and calls registerFactory for simple adds. */ void addFactory(T factory) { registerFactory(factory); } /** * Public access method to determine if a factory is already registered to this * list */ bool isFactoryRegistered(T factory)const { if(!factory) return false; ScopeReadLock scopedReadLock(m_rwlock); return findFactory(factory); } /** * Will register a factory to the factory list. Will append the passed in factory if not * already registered to the list. */ void registerFactory(T factory, bool pushToFrontFlag=false) { if(!factory) return; ScopeWriteLock scopedWriteLock(m_rwlock); if(!findFactory(factory)) { if (pushToFrontFlag) { m_factoryList.insert(m_factoryList.begin(), factory); } else { m_factoryList.push_back(factory); } } } /** * Will remove the factory from the registry. */ void unregisterFactory(T factory) { ScopeWriteLock scopedWriteLock(m_rwlock); ossim_uint32 idx = 0; for(idx = 0; idx < m_factoryList.size(); ++idx) { if(factory == m_factoryList[idx]) { m_factoryList.erase(m_factoryList.begin() + idx); return; } } } /** * Will remove all factories from the registry. */ void unregisterAllFactories() { ScopeWriteLock scopedWriteLock(m_rwlock); m_factoryList.clear(); } /** * Inserts the factory to the front of the list. */ void registerFactoryToFront(T factory) { ScopeWriteLock scopedWriteLock(m_rwlock); if(!findFactory(factory)) { m_factoryList.insert(m_factoryList.begin(), factory); } } /** * Will insert the factory before the beforeThisFactory. If not found * it will do a simple append. */ void registerFactoryBefore(T factory, T beforeThisFactory) { ScopeWriteLock scopedWriteLock(m_rwlock); if(!findFactory(factory)) { ossim_uint32 idx = 0; for(idx = 0; idx < m_factoryList.size(); ++idx) { if(beforeThisFactory == m_factoryList[idx]) { m_factoryList.insert(m_factoryList.begin() + idx, factory); return; } } m_factoryList.push_back(factory); } } protected: /** * Utility to find a factory in the list */ bool findFactory(T factory)const { if(!factory) return false; ossim_uint32 idx = 0; for(const auto& testFactory:m_factoryList) { if(factory == testFactory) { return true; } } return false; } mutable ossim::RWLock m_rwlock; FactoryListType m_factoryList; }; } #endif ossim-Miami-2.9.1/include/ossim/base/ItemCache.h000066400000000000000000000276711352751253100214120ustar00rootroot00000000000000#ifndef ossimItemCache_HEADER #define ossimItemCache_HEADER #include #include #include #include namespace ossim { /** * This is a generic cache. The only requirement is that it expects * the item to support shared_ptr. The ItemCache allows one to specify the * maximum items to cache and will use a "Least Recently Used" (LRU) to purge old * items from the cache back to a minimum cache size. * * Example Use: * * @code #include #include int main(int argc, char *argv[]) { int returnCode = 0; ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); try { ossim_uint32 maxStates=10; ossim::ItemCache stateCache; ossim_uint32 idx = 0; stateCache.setMaxItemsToCache(maxStates); while(idx < maxStates) { ossimString id = ossimString::toString(idx); stateCache.addItem(id, std::make_shared()); ++idx; } stateCache.getItem(ossimString::toString(0) stateCache.getItem(ossimString::toString(maxStates-1); // should be shrinking cache size back to a minimum size of default // 80% capacity stateCache.addItem(ossimString::toString(idx++), std::make_shared()); stateCache.addItem(ossimString::toString(idx++), std::make_shared()); stateCache.addItem(ossimString::toString(idx++), std::make_shared()); } catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } catch( ... ) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-foo caught unhandled exception!" << std::endl; returnCode = 1; } return returnCode; } * @endCode */ template class ItemCache { public: typename std::shared_ptr SharedItemType; /** * Holds information about the Item we are chaching. * Holds the current lruId and the cacheId and the item we * are caching * * Lru is adjusted when the item is searched with the getItem * */ struct Node { ossim_uint64 m_lruId; ossimString m_cacheId; std::shared_ptr m_item; }; typedef std::map > CacheType; typedef std::map > LruType; /** * Get item will adjust the LRU if the item is present. * * @param key Is the key used to identify the item you are * trying to retrieve. * @return the shared pointer to the item you are returning or * null otherwise */ std::shared_ptr getItem(const ossimString& key); std::shared_ptr getItem(const ossimString& key)const; /** * Add an item to the cache given the key or id * * @param key Is the identifier for the Item * @param item Is the item to cache */ void addItem(const ossimString& key, std::shared_ptr item); /** * Will remove an item from the cache * * @param key is the identifier for the item to remove * @return the removed item from the cache */ std::shared_ptr removeItem(const ossimString& key); /** * will reset the cache back to empty clearing both the LRU * map and the cache map. */ void reset(); /** * Sets the min and max cavche size. If the cache reaches max size * it uses the min setting to flush values based on an LRU back to the * minimum size */ void setMinAndMaxItemsToCache(ossim_uint32 minItemsToCache, ossim_uint32 maxItemsToCache); /** * @return the setting for the max items to cache */ ossim_uint32 getMaxItemsToCache()const; /** * @return the setting for the min items to cache */ ossim_uint32 getMinItemsToCache()const; protected: mutable RWLock m_itemCacheMutex; mutable RWLock m_lruCacheMutex; mutable ossim_uint64 m_currentId{0}; CacheType m_cache; mutable LruType m_lruCache; ossim_uint32 m_maxItemsToCache{100}; ossim_uint32 m_minItemsToCache{80}; /** * The public methods locks the cache down to a read * or write access. This will not lock and will assume * that a lock has already been done for the Cache * * @param key identifies the item to cache * @param item the item to cache. */ void protectedAddItem(const ossimString& key, std::shared_ptr item); /** * Will shrink the cache based on an LRU back to * the min cache size. */ void shrinkCache(); /** * Will bump the LRU id so that the node is marked * newest * * @param node the node to mark as new for LRU */ void touchNode(std::shared_ptr node)const; /** * Removes a node from the item cache * * @param key the identifier for the node to remove * @return shared ptr to the node removed */ std::shared_ptr removeItemFromCache(const ossimString& key); /** * Removes a node from the LRU cache * * @param key the identifier for the node to remove * @return shared ptr to the node removed */ std::shared_ptr removeItemFromLruCache(ossim_uint64 key)const; /** * This is an LRU id generator. It will bump the id and return the * value * * @return the next LRU id for a node to use. */ ossim_uint64 nextId()const; }; template typename std::shared_ptr ItemCache::getItem(const ossimString& key) { ossim::ScopeReadLock lock(m_itemCacheMutex); std::shared_ptr result; typename CacheType::iterator iter = m_cache.find(key); if(iter != m_cache.end()) { result = iter->second->m_item; touchNode(iter->second); } return result; } template typename std::shared_ptr ItemCache::getItem(const ossimString& key)const { ossim::ScopeReadLock lock(m_itemCacheMutex); std::shared_ptr result; typename CacheType::const_iterator iter = m_cache.find(key); if(iter != m_cache.end()) { result = iter->second->m_item; touchNode(iter->second); } return result; } template void ItemCache::addItem(const ossimString& key, std::shared_ptr item) { ossim::ScopeWriteLock lock(m_itemCacheMutex); protectedAddItem(key, item); } template typename std::shared_ptr ItemCache::removeItem(const ossimString& key) { ossim::ScopeWriteLock lock(m_itemCacheMutex); std::shared_ptr result; std::shared_ptr node = removeItemFromCache(key); if(node) { result = node->m_item; removeItemFromLruCache(node->m_lruId); } return result; } template void ItemCache::protectedAddItem(const ossimString& key, std::shared_ptr item) { if(m_cache.size() > m_maxItemsToCache) { shrinkCache(); } typename CacheType::iterator iter = m_cache.find(key); if(iter!= m_cache.end()) { // update the item and LRU // std::shared_ptr node = iter->second; node->m_item = item; touchNode(node); } else { std::shared_ptr nodePtr = std::make_shared(); nodePtr->m_cacheId = key; nodePtr->m_item = item; nodePtr->m_lruId = nextId(); m_cache.insert(std::make_pair(key, nodePtr)); { ossim::ScopeWriteLock lock(m_lruCacheMutex); if(m_lruCache.size() > 0) { m_lruCache.insert(--m_lruCache.end(), std::make_pair(nodePtr->m_lruId, nodePtr)); } else { m_lruCache.insert(std::make_pair(nodePtr->m_lruId, nodePtr)); } } } } template void ItemCache::touchNode(std::shared_ptr node)const { m_lruCache.erase(node->m_lruId); node->m_lruId = nextId(); { ossim::ScopeWriteLock lock(m_lruCacheMutex); if(m_lruCache.size() > 0) { m_lruCache.insert(m_lruCache.end(), std::make_pair(node->m_lruId, node)); } else { m_lruCache.insert(std::make_pair(node->m_lruId, node)); } } } template ossim_uint64 ItemCache::nextId()const { return m_currentId++; } template void ItemCache::setMinAndMaxItemsToCache(ossim_uint32 maxItemsToCache, ossim_uint32 minItemsToCache) { ossim::ScopeWriteLock lock(m_itemCacheMutex); m_maxItemsToCache = maxItemsToCache; m_minItemsToCache = minItemsToCache; } template void ItemCache::reset() { ossim::ScopeWriteLock lock(m_itemCacheMutex); m_cache.clear(); m_lruCache.clear(); m_currentId = 0; } template void ItemCache::shrinkCache() { if(m_minItemsToCache < 1) { m_lruCache.clear(); m_cache.clear(); } else { typename LruType::iterator iter = m_lruCache.begin(); ossim_uint32 previousSize = m_cache.size(); while((m_cache.size() > m_minItemsToCache)&& (iter != m_lruCache.end())) { removeItemFromCache(iter->second->m_cacheId); iter = m_lruCache.erase(iter); // sanity check to make sure we continue to shrink at // each iteration // avoids infinite loop if(m_cache.size() >= previousSize) { break; } } } } template ossim_uint32 ItemCache::getMaxItemsToCache()const { ossim::ScopeReadLock lock(m_itemCacheMutex); return m_maxItemsToCache; } template ossim_uint32 ItemCache::getMinItemsToCache()const { ossim::ScopeReadLock lock(m_itemCacheMutex); return m_minItemsToCache; } template std::shared_ptr< typename ItemCache::Node> ItemCache::removeItemFromCache(const ossimString& key) { std::shared_ptr result; typename CacheType::iterator iter = m_cache.find(key); if(iter != m_cache.end()) { result = iter->second; m_cache.erase(iter); } return result; } template std::shared_ptr::Node> ItemCache::removeItemFromLruCache(ossim_uint64 key)const { std::shared_ptr result; typename LruType::iterator iter = m_lruCache.find(key); if(iter != m_lruCache.end()) { result = iter->second; m_lruCache.erase(iter); } return result; } } #endif ossim-Miami-2.9.1/include/ossim/base/JsonInterface.h000066400000000000000000000016121352751253100223050ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef JsonInterface_HEADER #define JsonInterface_HEADER 1 #include namespace ossim { /** * Pure virtual interface for classes implementing JSON-based load/save state.. * Refer to 3DISA API document * for JSON formats used. */ class JsonInterface { public: JsonInterface() {} virtual ~JsonInterface() {} virtual void loadJSON(const Json::Value& jsonNode) = 0; virtual void saveJSON(Json::Value& jsonNode) const = 0; }; } #endif ossim-Miami-2.9.1/include/ossim/base/RWLock.h000066400000000000000000000033021352751253100207120ustar00rootroot00000000000000/** * This code was derived from https://gist.github.com/mshockwave * */ #ifndef ossimRWLockHEADER #define ossimRWLockHEADER 1 #include #include #include #include namespace ossim { /** * Code was derived from https://gist.github.com/mshockwave * * Has a pure c++11 implementation for read/write locks * allowing one to choose the locking technique to use. * * At the bottom we added typedefs so you do not have * to specify the template values. * * * Example: * @code * ossim::RWLock mutex; * // enter a section that just needs read only access * { * ossim::ScopeReadLock lock(mutex); * } * // enter some section that requires write * { * ossim::ScopeWriteLock lock(mutex); * } * @endcode */ class RWLock { private: std::mutex m_waitMutex; std::condition_variable m_waitConditional; std::atomic_int m_refCounter; const int MIN_INT; public: RWLock(); void lockWrite(); bool tryLockWrite(); void unlockWrite(); void lockRead(); bool tryLockRead(); void unlockRead(); }; class ScopeReadLock { RWLock& m_lock; public: ScopeReadLock(RWLock &lock) : m_lock(lock) { m_lock.lockRead(); } ~ScopeReadLock() { m_lock.unlockRead(); } }; class ScopeWriteLock { RWLock& m_lock; public: ScopeWriteLock(RWLock& lock) : m_lock(lock) { m_lock.lockWrite(); } ~ScopeWriteLock() { m_lock.unlockWrite(); } }; }; #endifossim-Miami-2.9.1/include/ossim/base/State.h000066400000000000000000000027361352751253100206430ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // //***************************************************************************** #ifndef ossimState_HEADER #define ossimState_HEADER 1 #include #include #include namespace ossim { /** * This is the base for all state objects. We started a new state * object for our first step will be using this interface to cache * the state of ImageHandlers. It is very expensive to keep opening * a resource and then parsing all the meta information that describes * the image. We should be able to do this once and then allow for it * to be saved and reloaded witout ever having to parse the state again * unless the state changes * */ class OSSIM_DLL State { public: State(){} virtual ~State(){} /** * @return the typename of the state that uniquely identifies * the name. Usually the class name will be used */ virtual const ossimString& getTypeName()const=0; /** * Allows a state to be loaded from keywordlist. */ virtual bool load(const ossimKeywordlist& kwl, const ossimString& prefix="")=0; /** * Allows a state to be saved to a keywordlist. */ virtual bool save(ossimKeywordlist& kwl, const ossimString& prefix="")const=0; }; } #endif ossim-Miami-2.9.1/include/ossim/base/StateFactoryBase.h000066400000000000000000000007401352751253100227570ustar00rootroot00000000000000#ifndef ossimStateFactoryBase_HEADER #define ossimStateFactoryBase_HEADER 1 #include #include namespace ossim { template< class T > class OSSIM_DLL StateFactoryBase { public: StateFactoryBase(){} virtual T createState(const ossimKeywordlist& kwl, const ossimString& prefix="")const=0; virtual T createState(const ossimString& typeName)const=0; }; } #endifossim-Miami-2.9.1/include/ossim/base/Thread.h000066400000000000000000000147101352751253100207650ustar00rootroot00000000000000#ifndef ossimThread_HEADER #define ossimThread_HEADER 1 #include #include #include #include #include #include #include namespace ossim{ /** * Thread is an abstract class. It provides a * general purpose thread interface that handles preliminary setup * of the std c++11 thread. It allows one to derive * from Thread and override the run method. Your thread should have calls * to interrupt() whenever your thread is in a location that is * interruptable. If cancel is called then any thread that is interruptable will * throw an Interrupt and be caught in the base Thread class and then exit * the thread. * * Example: * @code * #include * #include * class TestThread : public ossim::Thread * { * public: * TestThread():ossim::Thread(){} * ~TestThread(){ * waitForCompletion(); * } * * protected: * virtual void run() * { * barrierStart.block(); * for(int x =0 ; x < 10;++x){ * std::cout << "THREAD: " << getCurrentThreadId() << "\n"; * // simulate 10 milliseconds of uninterruptable work * sleepInMilliSeconds(10); * interrupt(); * } * barrierFinished.block(); * } * }; * int main(int agrc, char* argv[]) * { * std::vector > threads(nThreads); * for(auto& thread:threads) * { * thread = std::make_shared(); * thread->start(); * } * * // now let's wait for each thread to finish * // before exiting * for(auto& thread:threads) * { * thread->waitForCompletion(); * } * } * @endcode */ class OSSIM_DLL Thread { public: /** * This is an Interrupt exception that is thrown if the @see cancel() * is called and a call to @see interrupt() is made. */ class Interrupt : public std::exception{ public: Interrupt(const std::string& what=""):m_what(what){} virtual const char* what() const throw(){return m_what.c_str();} protected: std::string m_what; }; /** * Constructor for this thread */ Thread(); /** * Destructor for this thread. It will determine if this thread is joinable * to the main thread and if so it will do a join before continuing. If * this is not done then an exeption is thrown by the std. */ virtual ~Thread(); /** * Will actually start the thread and will call the @see internalRun. */ void start(); /** * @return true if the current thread is running and false otherwise. */ bool isRunning()const{return m_running.load(std::memory_order_relaxed);} /** * This is typically set if @see cancel() is called or if @see setCancel * is called with argument set to true. * * @return true if the thread is interruptable and false otherwise. */ bool isInterruptable()const{return m_interrupt.load(std::memory_order_relaxed);} /** * This basically requests that the thread be canceled. @see setCancel. Note, * cancellation is not done immediately and a thread is only cancleed if derived * classes call the interrupt(). * * we will make these virtual just in case derived classes want to set conditions */ virtual void cancel(){setCancel(true);} /** * @param flag if true will enable the thread to be interruptable and if false * the thread is not interruptable. */ virtual void setCancel(bool flag); /** * Convenience to allow one to wait for this thread to finish it's work. * * Allow this to be overriden. */ virtual void waitForCompletion(); /** * Enables the thread to be paused. If the interrupt is called * it will block the thread */ void pause(); /** * This will resume a blocked thread. */ void resume(); /** * @return true if the thread is blocked and false otherwise */ bool isPaused()const; /** * Utility method to allow one to sleep in seconds * * @param seconds to sleep */ static void sleepInSeconds(ossim_uint64 seconds); /** * Utility method to allow one to sleep in milliseconds * * @param millis to sleep */ static void sleepInMilliSeconds(ossim_uint64 millis); /** * Utility method to allow one to sleep in microseconds * * @param micros to sleep */ static void sleepInMicroSeconds(ossim_uint64 micros); /** * Utility method to get the current thread ID * * @return current thread ID */ static std::thread::id getCurrentThreadId(); /** * Utility to return the number of processors (concurrent threads) */ static ossim_uint64 getNumberOfProcessors(); /** * Will yield the current thread. */ static void yieldCurrentThread(); protected: /** * This method must be overriden and is the main entry * point for any work that needs to be done */ virtual void run()=0; /** * This is the interrupt interface and will cause an internal exception that * is caught by @see runInternal */ virtual void interrupt(); /** * runInternal sets up internal flags such as setting m_running to true and checks * to make sure it's not interrupted and will then call the @see run() method. * * runInternal also will trap any Interrupt exceptions. If the thread is interruptable * and the work calls interrupt then an exception is thrown and the work is stopped and * the execution of the thread is marked as not running and returns. */ virtual void runInternal(); private: std::shared_ptr m_thread; std::atomic m_running; std::atomic m_interrupt; std::shared_ptr m_pauseBarrier; std::condition_variable m_runningCondition; mutable std::mutex m_runningMutex; /** * @see cancel and @see setCancel */ void setInterruptable(bool flag); }; } #endif ossim-Miami-2.9.1/include/ossim/base/datum.h000066400000000000000000000550751352751253100207010ustar00rootroot00000000000000#ifndef DATUM_H #define DATUM_H /***************************************************************************/ /* RSC IDENTIFIER: Datum * * ABSTRACT * * This component provides datum shifts for a large collection of local * datums, WGS72, and WGS84. A particular datum can be accessed by using its * standard 5-letter code to find its index in the datum table. The index * can then be used to retrieve the name, type, ellipsoid code, and datum * shift parameters, and to perform shifts to or from that datum. * * By sequentially retrieving all of the datum codes and/or names, a menu * of the available datums can be constructed. The index values resulting * from selections from this menu can then be used to access the parameters * of the selected datum, or to perform datum shifts involving that datum. * * This component supports both 3-parameter local datums, for which only X, * Y, and Z translations relative to WGS 84 have been defined, and * 7-parameter local datums, for which X, Y, and Z rotations, and a scale * factor, are also defined. It also includes entries for WGS 84 (with an * index of 0), and WGS 72 (with an index of 1), but no shift parameter * values are defined for these. * * This component provides datum shift functions for both geocentric and * geodetic coordinates. WGS84 is used as an intermediate state when * shifting from one local datum to another. When geodetic coordinates are * given Molodensky's method is used, except near the poles where the 3-step * step method is used instead. Specific algorithms are used for shifting * between WGS72 and WGS84. * * This component depends on two data files, named 3_param.dat and * 7_param.dat, which contain the datum parameter values. Copies of these * files must be located in the directory specified by the value of the * environment variable "DATUM_DATA", if defined, or else in the current * directory whenever a program containing this component is executed. * * Additional datums can be added to these files, either manually or using * the Create_Datum function. However, if a large number of datums are * added, the datum table array sizes in this component will have to be * increased. * * This component depends on two other components: the Ellipsoid component * for access to ellipsoid parameters; and the Geocentric component for * conversions between geodetic and geocentric coordinates. * * ERROR HANDLING * * This component checks for input file errors and input parameter errors. * If an invalid value is found, the error code is combined with the current * error code using the bitwise or. This combining allows multiple error * codes to be returned. The possible error codes are: * * DATUM_NO_ERROR : No errors occurred in function * DATUM_NOT_INITIALIZED_ERROR : Datum module has not been initialized * DATUM_7PARAM_FILE_OPEN_ERROR : 7 parameter file opening error * DATUM_7PARAM_FILE_PARSING_ERROR : 7 parameter file structure error * DATUM_7PARAM_OVERFLOW_ERROR : 7 parameter table overflow * DATUM_3PARAM_FILE_OPEN_ERROR : 3 parameter file opening error * DATUM_3PARAM_FILE_PARSING_ERROR : 3 parameter file structure error * DATUM_3PARAM_OVERFLOW_ERROR : 3 parameter table overflow * DATUM_INVALID_INDEX_ERROR : Index out of valid range (less than one * or more than Datum_Count) * DATUM_INVALID_SRC_INDEX_ERROR : Source datum index invalid * DATUM_INVALID_DEST_INDEX_ERROR : Destination datum index invalid * DATUM_INVALID_CODE_ERROR : Datum code not found in table * DATUM_LAT_ERROR : Latitude out of valid range (-90 to 90) * DATUM_LON_ERROR : Longitude out of valid range (-180 to * 360) * DATUM_SIGMA_ERROR : Standard error values must be positive * (or -1 if unknown) * DATUM_DOMAIN_ERROR : Domain of validity not well defined * DATUM_ELLIPSE_ERROR : Error in ellipsoid module * * * REUSE NOTES * * Datum is intended for reuse by any application that needs access to * datum shift parameters relative to WGS 84. * * * REFERENCES * * Further information on Datum can be found in the Reuse Manual. * * Datum originated from : U.S. Army Topographic Engineering Center (USATEC) * Geospatial Information Division (GID) * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * Datum has no restrictions. * * ENVIRONMENT * * Datum was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC 2.8.1 * 2. MS Windows 95 with MS Visual C++ 6 * * MODIFICATIONS * * Date Description * ---- ----------- * 03/30/97 Original Code * 05/28/99 Added user-definable datums (for JMTK) * Added datum domain of validity checking (for JMTK) * Added datum shift accuracy calculation (for JMTK) */ /***************************************************************************/ /* * DEFINES */ #define DATUM_NO_ERROR 0x0000 #define DATUM_NOT_INITIALIZED_ERROR 0x0001 #define DATUM_7PARAM_FILE_OPEN_ERROR 0x0002 #define DATUM_7PARAM_FILE_PARSING_ERROR 0x0004 #define DATUM_7PARAM_OVERFLOW_ERROR 0x0008 #define DATUM_3PARAM_FILE_OPEN_ERROR 0x0010 #define DATUM_3PARAM_FILE_PARSING_ERROR 0x0020 #define DATUM_3PARAM_OVERFLOW_ERROR 0x0040 #define DATUM_INVALID_INDEX_ERROR 0x0080 #define DATUM_INVALID_SRC_INDEX_ERROR 0x0100 #define DATUM_INVALID_DEST_INDEX_ERROR 0x0200 #define DATUM_INVALID_CODE_ERROR 0x0400 #define DATUM_LAT_ERROR 0x0800 #define DATUM_LON_ERROR 0x1000 #define DATUM_SIGMA_ERROR 0x2000 #define DATUM_DOMAIN_ERROR 0x4000 #define DATUM_ELLIPSE_ERROR 0x8000 /***************************************************************************/ /* * GLOBAL DECLARATIONS */ typedef enum Datum_Types { Three_Param_Datum, Seven_Param_Datum, WGS84_Datum, WGS72_Datum } Datum_Type; /* different types of datums */ /***************************************************************************/ /* * FUNCTION PROTOTYPES */ /* ensure proper linkage to c++ programs */ #ifdef __cplusplus extern "C" { #endif long Initialize_Datums(void); /* * The function Initialize_Datums creates the datum table from two external * files. If an error occurs, the initialization stops and an error code is * returned. This function must be called before any of the other functions * in this component. */ long Create_Datum ( const char *Code, const char *Name, const char *Ellipsoid_Code, double Delta_X, double Delta_Y, double Delta_Z, double Sigma_X, double Sigma_Y, double Sigma_Z, double South_latitude, double North_latitude, double West_longitude, double East_longitude); /* * Code : 5-letter new datum code. (input) * Name : Name of the new datum (input) * Ellipsoid_Code : 2-letter code for the associated ellipsoid (input) * Delta_X : X translation to WGS84 in meters (input) * Delta_Y : Y translation to WGS84 in meters (input) * Delta_Z : Z translation to WGS84 in meters (input) * Sigma_X : Standard error in X in meters (input) * Sigma_Y : Standard error in Y in meters (input) * Sigma_Z : Standard error in Z in meters (input) * South_latitude : Southern edge of validity rectangle in radians(input) * North_latitude : Northern edge of validity rectangle in radians(input) * West_longitude : Western edge of validity rectangle in radians (input) * East_longitude : Eastern edge of validity rectangle in radians (input) * * The function Create_Datum creates a new local (3-parameter) datum with the * specified code, name, shift values, and standard error values. If the * datum table has not been initialized, the specified code is already in use, * or a new version of the 3-param.dat file cannot be created, an error code * is returned, otherwise DATUM_NO_ERROR is returned. Note that the indexes * of all datums in the datum table may be changed by this function. */ long Datum_Count ( long *Count ); /* * The function Datum_Count returns the number of Datums in the table * if the table was initialized without error. * * Count : number of datums in the datum table (output) */ long Datum_Index ( const char *Code, long *Index ); /* * The function Datum_Index returns the index of the datum with the * specified code. * * Code : The datum code being searched for (input) * Index : The index of the datum in the table with the (output) * specified code */ long Datum_Code ( const long Index, char *Code ); /* * The function Datum_Code returns the 5-letter code of the datum * referenced by index. * * Index : The index of a given datum in the datum table (input) * Code : The datum code of the datum referenced by index (output) */ long Datum_Name ( const long Index, char *Name ); /* * The function Datum_Name returns the name of the datum referenced by * index. * * Index : The index of a given datum in the datum table (input) * Name : The datum name of the datum referenced by index (output) */ long Datum_Ellipsoid_Code ( const long Index, char *Code ); /* * The function Datum_Ellipsoid_Code returns the 2-letter ellipsoid code * for the ellipsoid associated with the datum referenced by index. * * Index : The index of a given datum in the datum table (input) * Code : The ellisoid code for the ellipsoid associated with the (output) * datum referenced by index */ long Get_Datum_Type ( const long Index, Datum_Type *Type ); /* * The function Get_Datum_Type returns the type of the datum referenced by * index. * * Index : The index of a given datum in the datum table (input) * Type : The type of the datum referenced by index (output) */ long Datum_Seven_Parameters ( const long Index, double *Delta_X, double *Delta_Y, double *Delta_Z, double *Rx, double *Ry, double *Rz, double *Scale_Factor ); /* * The function Datum_Seven_Parameters returns the seven parameters * for the datum referenced by index. * * Index : The index of a given datum in the datum table (input) * Delta_X : X translation in meters (output) * Delta_Y : Y translation in meters (output) * Delta_Z : Z translation in meters (output) * Rx : X rotation in radians (output) * Rx : Y rotation in radians (output) * Ry : Z rotation in radians (output) * Scale_Factor : Scale factor (output) */ long Datum_Three_Parameters ( const long Index, double *Delta_X, double *Delta_Y, double *Delta_Z); /* * The function Datum_Three_Parameters returns the three parameters * for the datum referenced by index. * * Index : The index of a given datum in the datum table (input) * Delta_X : X translation in meters (output) * Delta_Y : Y translation in meters (output) * Delta_Z : Z translation in meters (output) */ long Datum_Errors ( const long Index, double *Sigma_X, double *Sigma_Y, double *Sigma_Z); /* * The function Datum_Errors returns the standard errors in X,Y, & Z * for the datum referenced by index. * * Index : The index of a given datum in the datum table (input) * Sigma_X : Standard error in X in meters (output) * Sigma_Y : Standard error in Y in meters (output) * Sigma_Z : Standard error in Z in meters (output) */ long Datum_Valid_Rectangle ( const long Index, double *South_latitude, double *North_latitude, double *West_longitude, double *East_longitude); /* * The function Datum_Valid_Rectangle returns the edges of the validity * rectangle for the datum referenced by index. * * Index : The index of a given datum in the datum table (input) * South_latitude : Southern edge of validity rectangle in radians (input) * North_latitude : Northern edge of validity rectangle in radians (input) * West_longitude : Western edge of validity rectangle in radians (input) * East_longitude : Eastern edge of validity rectangle in radians (input) */ long Valid_Datum ( const long Index, double latitude, double longitude, long *result); /* * This function checks whether or not the specified location is within the * validity rectangle for the specified datum. It returns zero if the specified * location is NOT within the validity rectangle, and returns 1 otherwise. * * Index : The index of a given datum in the datum table (input) * latitude : Latitude of the location to be checked in radians (input) * longitude : Longitude of the location to be checked in radians (input) * result : Indicates whether location is inside (1) or outside (0) * of the validity rectangle of the specified datum (output) */ long Geocentric_Shift_To_WGS84 (const long Index, const double X, const double Y, const double Z, double *X_WGS84, double *Y_WGS84, double *Z_WGS84); /* * This function shifts a geocentric coordinate (X, Y, Z in meters) relative * to the datum referenced by index to a geocentric coordinate (X, Y, Z in * meters) relative to WGS84. * * Index : Index of local datum (input) * X : X coordinate relative to the source datum (input) * Y : Y coordinate relative to the source datum (input) * Z : Z coordinate relative to the source datum (input) * X_WGS84 : X coordinate relative to WGS84 (output) * Y_WGS84 : Y coordinate relative to WGS84 (output) * Z_WGS84 : Z coordinate relative to WGS84 (output) */ long Geocentric_Shift_From_WGS84 (const double X_WGS84, const double Y_WGS84, const double Z_WGS84, const long Index, double *X, double *Y, double *Z); /* * This function shifts a geocentric coordinate (X, Y, Z in meters) relative * to WGS84 to a geocentric coordinate (X, Y, Z in meters) relative to the * local datum referenced by index. * * X_WGS84 : X coordinate relative to WGS84 (input) * Y_WGS84 : Y coordinate relative to WGS84 (input) * Z_WGS84 : Z coordinate relative to WGS84 (input) * Index : Index of destination datum (input) * X : X coordinate relative to the destination datum (output) * Y : Y coordinate relative to the destination datum (output) * Z : Z coordinate relative to the destination datum (output) */ long Geocentric_Datum_Shift ( const long Index_in, const double X_in, const double Y_in, const double Z_in, const long Index_out, double *X_out, double *Y_out, double *Z_out); /* * This function shifts a geocentric coordinate (X, Y, Z in meters) relative * to the source datum to geocentric coordinate (X, Y, Z in meters) relative * to the destination datum. * * Index_in : Index of source datum (input) * X_in : X coordinate relative to source datum (input) * Y_in : Y coordinate relative to source datum (input) * Z_in : Z coordinate relative to source datum (input) * Index_out : Index of destination datum (input) * X_out : X coordinate relative to destination datum (output) * Y_out : Y coordinate relative to destination datum (output) * Z_out : Z coordinate relative to destination datum (output) */ long Geodetic_Shift_To_WGS84 (const long Index, const double Lat_in, const double Lon_in, const double Hgt_in, double *WGS84_Lat, double *WGS84_Lon, double *WGS84_Hgt); /* * This function shifts geodetic coordinates relative to a given source datum * to geodetic coordinates relative to WGS84. * * Index : Index of source datum (input) * Lat_in : Latitude in radians relative to source datum (input) * Lon_in : Longitude in radians relative to source datum (input) * Hgt_in : Height in meters relative to source datum's ellipsoid (input) * WGS84_Lat : Latitude in radians relative to WGS84 (output) * WGS84_Lon : Longitude in radians relative to WGS84 (output) * WGS84_Hgt : Height in meters relative to WGS84 ellipsoid (output) */ long Geodetic_Shift_From_WGS84( const double WGS84_Lat, const double WGS84_Lon, const double WGS84_Hgt, const long Index, double *Lat_out, double *Lon_out, double *Hgt_out); /* * This function shifts geodetic coordinates relative to a WGS84 * to geodetic coordinates relative to a given local datum. * * WGS84_Lat : Latitude in radians relative to WGS84 (input) * WGS84_Lon : Longitude in radians relative to WGS84 (input) * WGS84_Hgt : Height in meters relative to WGS84 ellipsoid (input) * Index : Index of destination datum (input) * Lat_in : Latitude in radians relative to destination datum (output) * Lon_in : Longitude in radians relative to destination datum (output) * Hgt_in : Height in meters relative to destination datum's ellipsoid (output) */ long Geodetic_Datum_Shift ( const long Index_in, const double Lat_in, const double Lon_in, const double Hgt_in, const long Index_out, double *Lat_out, double *Lon_out, double *Hgt_out); /* * This function shifts geodetic coordinates (latitude, longitude in radians * and height in meters) relative to the source datum to geodetic coordinates * (latitude, longitude in radians and height in meters) relative to the * destination datum. * * Index_in : Index of source datum (input) * Lat_in : Latitude in radians relative to source datum (input) * Lon_in : Longitude in radians relative to source datum (input) * Hgt_in : Height in meters relative to source datum's ellipsoid (input) * Index_out : Index of destination datum (input) * Lat_out : Latitude in radians relative to destination datum (output) * Lon_out : Longitude in radians relative to destination datum (output) * Hgt_out : Height in meters relative to destination datum's ellipsoid (output) */ long Datum_Shift_Error (const long Index_in, const long Index_out, double latitude, double longitude, double *ce90, double *le90, double *se90); /* * This function returns the 90% horizontal (circular), vertical (linear), and * spherical errors for a shift from the specified source datum to the * specified destination datum at the specified location. * * Index_in : Index of source datum (input) * Index_out : Index of destination datum (input) * latitude : Latitude of point being converted in radians (input) * longitude : Longitude of point being converted in radians (input) * ce90 : Combined 90% circular horizontal error in meters (output) * le90 : Combined 90% linear vertical error in meters (output) * se90 : Combined 90% spherical error in meters (output) */ #ifdef __cplusplus } #endif #endif /* DATUM_H */ ossim-Miami-2.9.1/include/ossim/base/ossim2dBilinearTransform.h000066400000000000000000000200361352751253100244760ustar00rootroot00000000000000#ifndef ossim2dBilinearTransform_HEADER #define ossim2dBilinearTransform_HEADER #include #include /** * ossim2dBilinearTransform allows one to specify a set of input points and output points * and will fit a bilinear transform to those points. Function of the form is solved for each * output dimension. * * z(x,y) = a + b*x + c*y + d*x*y * * We use the ossimLeastSquareBilin solver to solve for the coefficients. * */ class OSSIM_DLL ossim2dBilinearTransform : public ossim2dTo2dTransform { public: /** * Initialize to the identity */ ossim2dBilinearTransform(); /** * Initialize the transform that best fits the input and output arrays. * If the input and output are well dispersed and are 4 points it should fit * exactly. Both arrays should be of equal number of points * * @param input the list of input points * @param output the list of output points to transform the input to * @param arraySize the number of points for the arrays. */ ossim2dBilinearTransform(const ossimDpt* input, const ossimDpt* output, ossim_uint32 arraySize) { setFromPoints(input, output, arraySize); } /** * Mapping 4 corners to an output 4 corners. * */ ossim2dBilinearTransform(const ossimDpt& in1, const ossimDpt& in2, const ossimDpt& in3, const ossimDpt& in4, const ossimDpt& out1, const ossimDpt& out2, const ossimDpt& out3, const ossimDpt& out4) { setFromPoints(in1, in2, in3, in4, out1, out2, out3, out4); } /** * Copy constructor */ ossim2dBilinearTransform(const ossim2dBilinearTransform& src); /** * Duplication method that duplicates this object */ virtual ossimObject* dup()const{return new ossim2dBilinearTransform(*this);} /** * Overloaded operator equal that allows for assignment. * * @param src the src data to copy into this object. It will call the base classes * equal operator. */ const ossim2dBilinearTransform& operator =(const ossim2dBilinearTransform& src) { if(this == &src) return *this; ossim2dTo2dTransform::operator =(*this); // call base classes equal operator std::copy(src.m_coefficientsXTerm, src.m_coefficientsXTerm+4, m_coefficientsXTerm); std::copy(src.m_coefficientsYTerm, src.m_coefficientsYTerm+4, m_coefficientsYTerm); std::copy(src.m_inverseCoefficientsXTerm, src.m_inverseCoefficientsXTerm+4, m_inverseCoefficientsXTerm); std::copy(src.m_inverseCoefficientsYTerm, src.m_inverseCoefficientsYTerm+4, m_inverseCoefficientsYTerm); return *this; } /** * Mapping 4 corners to an output 4 corners. Will use the ossimLeastSquareBilin class to solve * the bilinear coefficients that maps the given input points to the output points. */ void setFromPoints(const ossimDpt& in1, const ossimDpt& in2, const ossimDpt& in3, const ossimDpt& in4, const ossimDpt& out1, const ossimDpt& out2, const ossimDpt& out3, const ossimDpt& out4); /** * Initialize the transform that best fits the input and output arrays. * If the input and output are well dispersed and are 4 points it should fit * exactly. Both arrays should be of equal number of points * * @param input the list of input points * @param output the list of output points to transform the input to * @param arraySize the number of points for the arrays. */ void setFromPoints(const ossimDpt* input, const ossimDpt* output, ossim_uint32 arraySize); /** * forward transform will transform an input point to the output. */ virtual void forward(const ossimDpt& input, ossimDpt& output) const { output.x = (m_coefficientsXTerm[0] + m_coefficientsXTerm[1]*input.x + m_coefficientsXTerm[2]*input.y + m_coefficientsXTerm[3]*input.x*input.y); output.y = (m_coefficientsYTerm[0] + m_coefficientsYTerm[1]*input.x + m_coefficientsYTerm[2]*input.y + m_coefficientsYTerm[3]*input.x*input.y); } /** * forward transform will transform an input point to the output and modify the passed in point * to the new value */ virtual void forward(ossimDpt& modify_this) const { double saveX = modify_this.x; modify_this.x = (m_coefficientsXTerm[0] + m_coefficientsXTerm[1]*modify_this.x + m_coefficientsXTerm[2]*modify_this.y + m_coefficientsXTerm[3]*modify_this.x*modify_this.y); modify_this.y = (m_coefficientsYTerm[0] + m_coefficientsYTerm[1]*saveX + m_coefficientsYTerm[2]*modify_this.y + m_coefficientsYTerm[3]*saveX*modify_this.y); } /** * Inverts the point back to the original input value. */ virtual void inverse(const ossimDpt& input, ossimDpt& output) const { output.x = (m_inverseCoefficientsXTerm[0] + m_inverseCoefficientsXTerm[1]*input.x + m_inverseCoefficientsXTerm[2]*input.y + m_inverseCoefficientsXTerm[3]*input.x*input.y); output.y = (m_inverseCoefficientsYTerm[0] + m_inverseCoefficientsYTerm[1]*input.x + m_inverseCoefficientsYTerm[2]*input.y + m_inverseCoefficientsYTerm[3]*input.x*input.y); } /** * Inverts the point back to the original input value and modifies the passed in point * to the new value. */ virtual void inverse(ossimDpt& modify_this) const { double saveX = modify_this.x; modify_this.x = (m_inverseCoefficientsXTerm[0] + m_inverseCoefficientsXTerm[1]*modify_this.x + m_inverseCoefficientsXTerm[2]*modify_this.y + m_inverseCoefficientsXTerm[3]*modify_this.x*modify_this.y); modify_this.y = (m_inverseCoefficientsYTerm[0] + m_inverseCoefficientsYTerm[1]*saveX + m_inverseCoefficientsYTerm[2]*modify_this.y + m_inverseCoefficientsYTerm[3]*saveX*modify_this.y); } /** * Saves the state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; /** * loads the state of this object from a keywordlist. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); /** * prints the contents of this object. Will also cal the base classes * print method. */ virtual std::ostream& print(std::ostream& out) const { ossim2dTo2dTransform::print(out); out << "xTerm: " << m_coefficientsXTerm[0] << ", " << m_coefficientsXTerm[1] << ", " << m_coefficientsXTerm[2] << ", " << m_coefficientsXTerm[3] << "\n"; out << "yTerm: " << m_coefficientsYTerm[0] << ", " << m_coefficientsYTerm[1] << ", " << m_coefficientsYTerm[2] << ", " << m_coefficientsYTerm[3] << "\n"; out << "xInverseTerm: " << m_inverseCoefficientsXTerm[0] << ", " << m_inverseCoefficientsXTerm[1] << ", " << m_inverseCoefficientsXTerm[2] << ", " << m_inverseCoefficientsXTerm[3] << "\n"; out << "yInverseTerm: " << m_inverseCoefficientsYTerm[0] << ", " << m_inverseCoefficientsYTerm[1] << ", " << m_inverseCoefficientsYTerm[2] << ", " << m_inverseCoefficientsYTerm[3] << "\n"; return out; } protected: ossim_float64 m_coefficientsXTerm[4]; // constant, linear x, linear y, cross xy ossim_float64 m_coefficientsYTerm[4]; // constant, linear x, linear y, cross xy ossim_float64 m_inverseCoefficientsXTerm[4]; // constant, linear x, linear y, cross xy ossim_float64 m_inverseCoefficientsYTerm[4]; // constant, linear x, linear y, cross xy TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossim2dLinearRegression.h000066400000000000000000000040331352751253100243270ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossim2dLinearRegression.h 23353 2015-06-01 19:19:10Z dburken $ #ifndef ossim2dLinearRegression_HEADER #define ossim2dLinearRegression_HEADER 1 #include #include #include #include class OSSIM_DLL ossim2dLinearRegression { public: friend OSSIM_DLL std::ostream& operator <<(std::ostream& out, const ossim2dLinearRegression& data) { out << "y = " << data.theSlope << "*x + " << data.theIntercept; return out; } ossim2dLinearRegression(); void getEquation(double& slope, double& intercept) { slope = theSlope; intercept = theIntercept; } void addPoint(const ossimDpt& pt) { // thePoints.push_back(pt); ++theNumberOfPoints; theSumX += pt.x; theSumY += pt.y; theSumXX += pt.x*pt.x; theSumYY += pt.y*pt.y; theSumXY += pt.x*pt.y; theSolvedFlag = false; } void clear() { // thePoints.clear(); theNumberOfPoints = 0; theSumX = 0.0; theSumXX = 0.0; theSumY = 0.0; theSumYY = 0.0; theIntercept = 0.0; theSlope = 0.0; theSumXY = 0.0; theSolvedFlag = false; } void solve(); ossim_uint32 getNumberOfPoints()const { return theNumberOfPoints; // return thePoints.size(); } protected: // std::vector thePoints; ossim_uint32 theNumberOfPoints; double theSumX; double theSumY; double theSumXX; double theSumYY; double theSumXY; double theIntercept; double theSlope; bool theSolvedFlag; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossim2dTo2dCompositeTransform.h000066400000000000000000000057331352751253100254530ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Contains class definition for ossim2dTo2dCompositeTransform. // //******************************************************************* // $Id$ #ifndef ossim2dTo2dCompositeTransform_HEADER #define ossim2dTo2dCompositeTransform_HEADER #include #include #include /** * This is the identity transform and just passes the input to the output. */ class OSSIM_DLL ossim2dTo2dCompositeTransform : public ossim2dTo2dTransform { public: typedef std::vector > CompositeTransformList; ossim2dTo2dCompositeTransform(const CompositeTransformList& compositeTransformList = CompositeTransformList()); ossim2dTo2dCompositeTransform(const ossim2dTo2dCompositeTransform& rhs); virtual ~ossim2dTo2dCompositeTransform(); virtual ossimObject* dup()const; void add(ossimRefPtr transform); void clear(); const CompositeTransformList& getCompositeTransformList()const; /** * Will iterate through the list of transforms from index 0 ... n -1 calling * the forward transform. The output of the previous is used as the input to the next * transform. */ virtual void forward(const ossimDpt& input, ossimDpt& output) const; /** * will call the forward method with 2 arguments */ virtual void forward(ossimDpt& /* modify_this */) const; /** * Will iterate through the transformation list in reverse order from * n-1 ... 0 calling the inverse for each one. The output is passed in as input * to the next transform. */ virtual void inverse(const ossimDpt& input, ossimDpt& output) const; /** * will call the inverse method with 2 arguments */ virtual void inverse(ossimDpt& /* modify_this */) const; /** * Pass equality to the parent */ virtual const ossim2dTo2dCompositeTransform& operator=( const ossim2dTo2dCompositeTransform& rhs) { ossim2dTo2dTransform::operator =(rhs); return *this; } /** * Saves the state of the composite by iterating through all transformas and saving * them to the keyword list with it's own prefix. * * values will be: * .object0 * .object1 * .object * */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Will laod the state of the object. Note, it will clear the list and then add * all prefix found from the save state. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: /** * Holds the list of transforms. */ CompositeTransformList m_compositeTransforms; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossim2dTo2dIdentityTransform.h000066400000000000000000000033001352751253100252660ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Contains class definition for ossim2dTo2dIdentityTransform. // //******************************************************************* // $Id$ #ifndef ossim2dTo2dIdentityTransform_HEADER #define ossim2dTo2dIdentityTransform_HEADER #include "ossim2dTo2dTransform.h" /** * This is the identity transform and just passes the input to the output. */ class OSSIM_DLL ossim2dTo2dIdentityTransform : public ossim2dTo2dTransform { public: /** * forward transform just passes the point to the output. */ virtual void forward(const ossimDpt& input, ossimDpt& output) const { output = input; } /** * forward transform nothing is modified on the input point. */ virtual void forward(ossimDpt& /* modify_this */) const { // do nothing this is identity } /** * inverse transform just passes the point to the output. */ virtual void inverse(const ossimDpt& input, ossimDpt& output) const { output = input; } /** * inverse transform nothing is modified on the input point. */ virtual void inverse(ossimDpt& /* modify_this */) const { // do nothing this is identity } /** * Pass equality to the parent */ virtual const ossim2dTo2dIdentityTransform& operator=( const ossim2dTo2dIdentityTransform& rhs) { ossim2dTo2dTransform::operator =(rhs); return *this; } protected: TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossim2dTo2dMatrixTransform.h000066400000000000000000000205451352751253100247530ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: // // Description: // //---------------------------------------------------------------------------- // $Id$ #ifndef ossim2dTo2dMatrixTransform_HEADER #define ossim2dTo2dMatrixTransform_HEADER 1 #include #include /** * ossim2dTo2dMatrixTransform allows one to specify a set of input points and output points * and will fit a bilinear transform to those points. Function of the form is solved for each * output dimension. * * z(x,y) = a + b*x + c*y + d*x*y * * We use the ossimLeastSquareBilin solver to solve for the coefficients. * */ class OSSIM_DLL ossim2dTo2dMatrixTransform : public ossim2dTo2dTransform { public: /** * Initialize to the identity */ ossim2dTo2dMatrixTransform(); /** * Initialize the transform that best fits the input and output arrays. * If the input and output are well dispersed and are 4 points it should fit * exactly. Both arrays should be of equal number of points * * @param input the list of input points * @param output the list of output points to transform the input to * @param arraySize the number of points for the arrays. */ ossim2dTo2dMatrixTransform(const ossimDpt* input, const ossimDpt* output, ossim_uint32 arraySize) { setFromPoints(input, output, arraySize); } /** * Mapping 4 corners to an output 4 corners. * */ ossim2dTo2dMatrixTransform(const ossimDpt& in1, const ossimDpt& in2, const ossimDpt& in3, const ossimDpt& in4, const ossimDpt& out1, const ossimDpt& out2, const ossimDpt& out3, const ossimDpt& out4) { setFromPoints(in1, in2, in3, in4, out1, out2, out3, out4); } /** * Copy constructor */ ossim2dTo2dMatrixTransform(const ossim2dTo2dMatrixTransform& src); /** * Duplication method that duplicates this object */ virtual ossimObject* dup()const{return new ossim2dTo2dMatrixTransform(*this);} /** * Overloaded operator equal that allows for assignment. * * @param src the src data to copy into this object. It will call the base classes * equal operator. */ const ossim2dTo2dMatrixTransform& operator =(const ossim2dTo2dMatrixTransform& src) { if(this == &src) return *this; ossim2dTo2dTransform::operator =(*this); // call base classes equal operator std::copy(src.m_coefficientsXTerm, src.m_coefficientsXTerm+4, m_coefficientsXTerm); std::copy(src.m_coefficientsYTerm, src.m_coefficientsYTerm+4, m_coefficientsYTerm); std::copy(src.m_inverseCoefficientsXTerm, src.m_inverseCoefficientsXTerm+4, m_inverseCoefficientsXTerm); std::copy(src.m_inverseCoefficientsYTerm, src.m_inverseCoefficientsYTerm+4, m_inverseCoefficientsYTerm); return *this; } /** * Mapping 4 corners to an output 4 corners. Will use the ossimLeastSquareBilin class to solve * the bilinear coefficients that maps the given input points to the output points. */ void setFromPoints(const ossimDpt& in1, const ossimDpt& in2, const ossimDpt& in3, const ossimDpt& in4, const ossimDpt& out1, const ossimDpt& out2, const ossimDpt& out3, const ossimDpt& out4); /** * Initialize the transform that best fits the input and output arrays. * If the input and output are well dispersed and are 4 points it should fit * exactly. Both arrays should be of equal number of points * * @param input the list of input points * @param output the list of output points to transform the input to * @param arraySize the number of points for the arrays. */ void setFromPoints(const ossimDpt* input, const ossimDpt* output, ossim_uint32 arraySize); /** * forward transform will transform an input point to the output. */ virtual void forward(const ossimDpt& input, ossimDpt& output) const { output.x = (m_coefficientsXTerm[0] + m_coefficientsXTerm[1]*input.x + m_coefficientsXTerm[2]*input.y + m_coefficientsXTerm[3]*input.x*input.y); output.y = (m_coefficientsYTerm[0] + m_coefficientsYTerm[1]*input.x + m_coefficientsYTerm[2]*input.y + m_coefficientsYTerm[3]*input.x*input.y); } /** * forward transform will transform an input point to the output and modify the passed in point * to the new value */ virtual void forward(ossimDpt& modify_this) const { double saveX = modify_this.x; modify_this.x = (m_coefficientsXTerm[0] + m_coefficientsXTerm[1]*modify_this.x + m_coefficientsXTerm[2]*modify_this.y + m_coefficientsXTerm[3]*modify_this.x*modify_this.y); modify_this.y = (m_coefficientsYTerm[0] + m_coefficientsYTerm[1]*saveX + m_coefficientsYTerm[2]*modify_this.y + m_coefficientsYTerm[3]*saveX*modify_this.y); } /** * Inverts the point back to the original input value. */ virtual void inverse(const ossimDpt& input, ossimDpt& output) const { output.x = (m_inverseCoefficientsXTerm[0] + m_inverseCoefficientsXTerm[1]*input.x + m_inverseCoefficientsXTerm[2]*input.y + m_inverseCoefficientsXTerm[3]*input.x*input.y); output.y = (m_inverseCoefficientsYTerm[0] + m_inverseCoefficientsYTerm[1]*input.x + m_inverseCoefficientsYTerm[2]*input.y + m_inverseCoefficientsYTerm[3]*input.x*input.y); } /** * Inverts the point back to the original input value and modifies the passed in point * to the new value. */ virtual void inverse(ossimDpt& modify_this) const { double saveX = modify_this.x; modify_this.x = (m_inverseCoefficientsXTerm[0] + m_inverseCoefficientsXTerm[1]*modify_this.x + m_inverseCoefficientsXTerm[2]*modify_this.y + m_inverseCoefficientsXTerm[3]*modify_this.x*modify_this.y); modify_this.y = (m_inverseCoefficientsYTerm[0] + m_inverseCoefficientsYTerm[1]*saveX + m_inverseCoefficientsYTerm[2]*modify_this.y + m_inverseCoefficientsYTerm[3]*saveX*modify_this.y); } /** * Saves the state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; /** * loads the state of this object from a keywordlist. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); /** * prints the contents of this object. Will also cal the base classes * print method. */ virtual std::ostream& print(std::ostream& out) const { ossim2dTo2dTransform::print(out); out << "xTerm: " << m_coefficientsXTerm[0] << ", " << m_coefficientsXTerm[1] << ", " << m_coefficientsXTerm[2] << ", " << m_coefficientsXTerm[3] << "\n"; out << "yTerm: " << m_coefficientsYTerm[0] << ", " << m_coefficientsYTerm[1] << ", " << m_coefficientsYTerm[2] << ", " << m_coefficientsYTerm[3] << "\n"; out << "xInverseTerm: " << m_inverseCoefficientsXTerm[0] << ", " << m_inverseCoefficientsXTerm[1] << ", " << m_inverseCoefficientsXTerm[2] << ", " << m_inverseCoefficientsXTerm[3] << "\n"; out << "yInverseTerm: " << m_inverseCoefficientsYTerm[0] << ", " << m_inverseCoefficientsYTerm[1] << ", " << m_inverseCoefficientsYTerm[2] << ", " << m_inverseCoefficientsYTerm[3] << "\n"; return out; } protected: ossim_float64 m_coefficientsXTerm[4]; // constant, linear x, linear y, cross xy ossim_float64 m_coefficientsYTerm[4]; // constant, linear x, linear y, cross xy ossim_float64 m_inverseCoefficientsXTerm[4]; // constant, linear x, linear y, cross xy ossim_float64 m_inverseCoefficientsYTerm[4]; // constant, linear x, linear y, cross xy TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossim2dTo2dShiftTransform.h000066400000000000000000000064251352751253100245650ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossim2dTo2dShiftTransform_HEADER #define ossim2dTo2dShiftTransform_HEADER #include class OSSIM_DLL ossim2dTo2dShiftTransform : public ossim2dTo2dTransform { public: /** * Constructor to initialize the shift transform */ ossim2dTo2dShiftTransform(const ossimDpt& shift = ossimDpt(0.0,0.0)) :ossim2dTo2dTransform(), m_shift(shift) {} /** * Copy constructor */ ossim2dTo2dShiftTransform(const ossim2dTo2dShiftTransform& src) :ossim2dTo2dTransform(src), m_shift(src.m_shift) {} /** * Duplication method that duplicates this object */ virtual ossimObject* dup()const{return new ossim2dTo2dShiftTransform(*this);} /** * operator = allows one to copy the contents of the class through a common = * operator. The = is passed to the derived class. */ const ossim2dTo2dShiftTransform& operator =(const ossim2dTo2dShiftTransform& src) { if(this == &src) return *this; ossim2dTo2dTransform::operator =(*this); // call base classes equal operator m_shift = src.m_shift; return *this; } /** * Apply the shift to the input. * * @param input The value to shift. * @param output the shifted value. */ virtual void forward(const ossimDpt& input, ossimDpt& output) const { output = input + m_shift; } /** * Apply the shift to the input and put the result in the same variable * * @param modify_this The value to shift. The result is placed back into this value. */ virtual void forward(ossimDpt& modify_this) const { modify_this.x += m_shift.x; modify_this.y += m_shift.y; } /** * Negate the shift to the input and put the result in output. * * @param input The value to apply the negated shift. * @param output the shifted value. */ virtual void inverse(const ossimDpt& input, ossimDpt& output) const { output = input - m_shift; } /** * Negate the shift operation and put the result in the same variable * * @param modify_this The value to shift. The result is placed back into this value. */ virtual void inverse(ossimDpt& modify_this) const { modify_this.x -= m_shift.x; modify_this.y -= m_shift.y; } /** * Saves the state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; /** * loads the state of this object from a keywordlist. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); /** * Print the contents of the class and pass to the derived class. */ virtual std::ostream& print(std::ostream& out) const { ossim2dTo2dTransform::print(out); out << "shift: " << m_shift; return out; } protected: virtual ~ossim2dTo2dShiftTransform(){} ossimDpt m_shift; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossim2dTo2dTransform.h000066400000000000000000000034021352751253100235570ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossim2dTo2dTransform.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossim2dTo2dTransform_HEADER #define ossim2dTo2dTransform_HEADER #include #include class OSSIMDLLEXPORT ossim2dTo2dTransform : public ossimObject { public: virtual void forward(const ossimDpt& input, ossimDpt& output) const=0; virtual void forward(ossimDpt& modify_this) const; virtual void inverse(const ossimDpt& input, ossimDpt& output) const; virtual void inverse(ossimDpt& modify_this) const; virtual const ossim2dTo2dTransform& operator=( const ossim2dTo2dTransform& rhs); /*! * Used by the inverse iterator. This will give it a good initial value * that is within the input transforms */ virtual ossimDpt getOrigin() const; virtual std::ostream& print(std::ostream& out) const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); void setConvergenceThreshold(const double& new_threshold); void setMaxIterations(int new_max_iters); void setDxDy(const ossimDpt& dxdy); protected: ossim2dTo2dTransform(); virtual ~ossim2dTo2dTransform(){} double theConvergenceThreshold; int theMaxIterations; ossimDpt theDxDy; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossim2dTo2dTransformFactory.h000066400000000000000000000025641352751253100251170ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Class declaration of ossim2dTo2dTransformFactory. // //************************************************************************************************** // $Id$ #ifndef ossim2dTo2dTransformFactory_HEADER #define ossim2dTo2dTransformFactory_HEADER #include class ossim2dTo2dTransform; class OSSIM_DLL ossim2dTo2dTransformFactory : public ossim2dTo2dTransformFactoryBase { public: ossim2dTo2dTransformFactory(){} static ossim2dTo2dTransformFactory* instance(); /** * Take a transform type name. */ virtual ossim2dTo2dTransform* createTransform(const ossimString& name)const; /** * Take a keywordlist. */ virtual ossim2dTo2dTransform* createTransform(const ossimKeywordlist& kwl, const char* prefix)const; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const; protected: static ossim2dTo2dTransformFactory* m_instance; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossim2dTo2dTransformFactoryBase.h000066400000000000000000000026301352751253100257040ustar00rootroot00000000000000#ifndef ossim2dTo2dTransformFactoryBase_HEADER #define ossim2dTo2dTransformFactoryBase_HEADER #include //************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Class declaration of ossim2dTo2dTransformFactoryBase. // //************************************************************************************************** // $Id$ #include class OSSIM_DLL ossim2dTo2dTransformFactoryBase : public ossimObjectFactory { public: /** * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const { return createTransform(typeName); } /** * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const { return createTransform(kwl, prefix); } /** * Take a transform type name. */ virtual ossim2dTo2dTransform* createTransform(const ossimString& name)const=0; /** * Take a keywordlist. */ virtual ossim2dTo2dTransform* createTransform(const ossimKeywordlist& kwl, const char* prefix)const=0; protected: }; #endif ossim-Miami-2.9.1/include/ossim/base/ossim2dTo2dTransformRegistry.h000066400000000000000000000052071352751253100253150ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Class declaration of ossim2dTo2dTransformRegistry. // //************************************************************************************************** // $Id$ #ifndef ossim2dTo2dTransformRegistry_HEADER #define ossim2dTo2dTransformRegistry_HEADER #include #include #include #include #include #include class OSSIM_DLL ossim2dTo2dTransformRegistry : public ossimObjectFactory, public ossimFactoryListInterface { public: virtual ~ossim2dTo2dTransformRegistry(){} static ossim2dTo2dTransformRegistry* instance(); /*! * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const { return createObjectFromRegistry(typeName); } /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const { return createObjectFromRegistry(kwl, prefix); } /*! * Creates an object given a type name. */ virtual ossim2dTo2dTransform* createTransform(const ossimString& typeName)const { return createNativeObjectFromRegistry(typeName); } /*! * Creates and object given a keyword list. */ virtual ossim2dTo2dTransform* createTransform(const ossimKeywordlist& kwl, const char* prefix=0)const { return createNativeObjectFromRegistry(kwl, prefix); } /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const { getAllTypeNamesFromRegistry(typeList); } protected: ossim2dTo2dTransformRegistry() :ossimObjectFactory() {} ossim2dTo2dTransformRegistry( const ossim2dTo2dTransformRegistry& rhs ) :ossimObjectFactory(rhs) {} void operator =(const ossim2dTo2dTransformRegistry&){} static ossim2dTo2dTransformRegistry* m_instance; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimActiveEdgeTable.h000066400000000000000000000102441352751253100235770ustar00rootroot00000000000000//***************************************************************************** // // License: See top level LICENSE.txt file. // // AUTHOR: Garrett Potts // //***************************************************************************** // $Id: ossimActiveEdgeTable.h 14799 2009-06-30 08:54:44Z dburken $ #include #include #include #include class ossimPolygon; class OSSIMDLLEXPORT ossimActiveEdgeTableNode { public: friend std::ostream& operator <<(std::ostream& out, const ossimActiveEdgeTableNode& rhs) { return out <<"| maxy="<(const ossimActiveEdgeTableNode& right)const { return (theCurrentX > right.theCurrentX); } ossim_int32 theMaxY; // ossim_int32 theDeltaY; double theSlope; double theCurrentX; }; class ossimActiveEdgeTableHelper; /*! * This class is used in fast efficient scanliine rasterization. It will take a polygon and insert * it into the table sorted by y's */ class ossimActiveEdgeTable { public: friend class ossimActiveEdgeTableHelper; ossimActiveEdgeTable(); /*! * Currently will only work on a single polygon. If you call this * twice it currently will use the last called polygon and * will wipe out the previous one. * * Note: this is used for scanline rasterization and will round * to integer values all vertices as they are initially added * to the Active Edge Table. */ void addPolygon(const ossimPolygon& polygon); const std::list& getActiveList()const; // bool getNextScanline(list::const_iterator& iterator)const; ossim_int32 getCurrentScanLine()const { return theCurrentScanLine; } ossim_int32 getYShift()const { return theRectOrigin.y; } void initializeActiveList(); void updateActiveEdges(); void mergeCurrentScanLine(); void printActiveEdgeList()const; protected: std::vector< std::list > theTable; std::list theActiveList; void createTable(const ossimPolygon& polygon); void addEdgeToTable(const ossimActiveEdgeTableNode& edge, ossim_int32 scanLine); /*! * Used in computing the number of scanlines of the passed in polygon and * is also used to shift the y's relative to 0,0 */ ossimIrect theBoundingRect; ossimIpt theRectOrigin; ossim_int32 theLastScanLine; ossim_int32 theCurrentScanLine; }; class ossimActiveEdgeTableHelper { public: ossimActiveEdgeTableHelper(ossimActiveEdgeTable* edgeTable); bool advanceScanLine(); bool getNextLineSegment(ossimIpt& start, ossimIpt& end); ossim_int32 getCurrentScanLine()const { if(theEdgeTable) { return theEdgeTable->getCurrentScanLine(); } return 0; } ossim_int32 getYShift()const { if(theEdgeTable) { return theEdgeTable->getYShift(); } return 0; } protected: ossimActiveEdgeTable* theEdgeTable; bool theTableInitializedFlag; std::list::const_iterator theIterator; }; ossim-Miami-2.9.1/include/ossim/base/ossimAdjSolutionAttributes.h000066400000000000000000000055731352751253100251420ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Helper interface class for ossimAdjustmentExecutive // and ossimWLSBundleSolution. //---------------------------------------------------------------------------- #ifndef ossimAdjSolutionAttributes_HEADER #define ossimAdjSolutionAttributes_HEADER #include #include #include #include #include #include #include typedef std::multimap ObjImgMap_t; typedef ObjImgMap_t::iterator ObjImgMapIter_t; typedef std::map ImgNumparMap_t; typedef ImgNumparMap_t::iterator ImgNumparMapIter_t; typedef std::pair ObjImgMapIterPair_t; class ossimAdjSolutionAttributes { public: ossimAdjSolutionAttributes (const int& numObjObs, const int& numImages, const int& numMeas, const int& rank); ~ossimAdjSolutionAttributes(); // Access traits inline int numObjObs() const { return theNumObjObs; } inline int numImages() const { return theNumImages; } inline int fullRank() const { return theFullRank; } friend class ossimWLSBundleSolution; friend class ossimAdjustmentExecutive; protected: // Traits int theNumObjObs; int theNumImages; int theFullRank; int theNumMeasurements; // Stacked observation evaluation matrices NEWMAT::Matrix theMeasResiduals; // theNumMeasurements X 2 NEWMAT::Matrix theObjPartials; // theNumObjObs*3 X 2 NEWMAT::Matrix theParPartials; // theNumImages*(npar/image) X 2 // Stacked a priori covariance matrices NEWMAT::Matrix theImagePtCov; // theNumMeasurements*2 X 2 NEWMAT::Matrix theObjectPtCov; // theNumObjObs*3 X 3 // Full parameter covariance matrix // TODO.... This is not stacked because npar/image may vary. However, it's // not treated as a full matrix in the solution due to // current use of simple partitioning, assuming no correlation. NEWMAT::Matrix theAdjParCov; // theNumImages*(npar/image) X theNumImages*(npar/image) // Correction vectors NEWMAT::ColumnVector theLastCorrections; // theFullRank X 1 NEWMAT::ColumnVector theTotalCorrections; // theFullRank X 1 // A posteriori full covariance matrix NEWMAT::UpperTriangularMatrix theFullCovMatrix; // Map obj vs. images (measurements) ObjImgMap_t theObjImgXref; // Map images vs. number of adj parameters ImgNumparMap_t theImgNumparXref; // Output operator friend std::ostream& operator << (std::ostream&, ossimAdjSolutionAttributes&); }; #endif // ossimAdjSolutionAttributes_HEADER ossim-Miami-2.9.1/include/ossim/base/ossimAdjustableParameterInfo.h000066400000000000000000000054171352751253100253700ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimAdjustableParameterInfo.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAdjustableParameterInfo_HEADER #define ossimAdjustableParameterInfo_HEADER #include #include #include #include class OSSIM_DLL ossimAdjustableParameterInfo { public: OSSIM_DLL friend std::ostream& operator <<(std::ostream& out, const ossimAdjustableParameterInfo& data); ossimAdjustableParameterInfo() : theParameter(0.0), theSigma(0.0), theCenter(0.0), theUnit(OSSIM_UNIT_UNKNOWN), theDescription(""), theLockFlag(false) { } ossimAdjustableParameterInfo(const ossimAdjustableParameterInfo& rhs) :theParameter(rhs.theParameter), theSigma(rhs.theSigma), theCenter(rhs.theCenter), theUnit(rhs.theUnit), theDescription(rhs.theDescription), theLockFlag(rhs.theLockFlag) { } double getParameter()const { return theParameter; } void setParameter(double parameter) { if(!theLockFlag) { theParameter = parameter; } } double getSigma()const { return theSigma; } void setSigma(double sigma) { if(!theLockFlag) { theSigma = sigma; } } const ossimString& getDescription()const { return theDescription; } void setDescription(const ossimString& description) { if(!theLockFlag) { theDescription = description; } } ossimUnitType getUnit()const { return theUnit; } void setUnit(ossimUnitType unit) { theUnit = unit; } ossimString getUnitAsString()const; void setCenter(double center); double getCenter()const; void setOffset(ossim_float64 value); /*! * will return theCenter + theSigma*theParameter */ double computeOffset()const; void setLockFlag(bool flag) { theLockFlag = flag; } bool getLockFlag()const { return theLockFlag; } bool loadState(const ossimKeywordlist& kwl, const ossimString& prefix=ossimString("")); bool saveState(ossimKeywordlist& kwl, const ossimString& prefix=ossimString(""))const; protected: double theParameter; double theSigma; double theCenter; ossimUnitType theUnit; ossimString theDescription; bool theLockFlag; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimAdjustableParameterInterface.h000066400000000000000000000151131352751253100263670ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimAdjustableParameterInterface.h 22892 2014-09-22 15:17:33Z okramer $ #ifndef ossimAdjustableParameterInterface_HEADER #define ossimAdjustableParameterInterface_HEADER #include #include #include #include #include class OSSIMDLLEXPORT ossimAdjustableParameterInterface { public: ossimAdjustableParameterInterface(); ossimAdjustableParameterInterface(const ossimAdjustableParameterInterface& rhs); virtual ~ossimAdjustableParameterInterface(){} void newAdjustment(ossim_uint32 numberOfParameters=0); void setAdjustmentDescription(const ossimString& description); ossimString getAdjustmentDescription()const; //! Returns adjustmentDescription of specific adjustmentInfo ossimString getAdjustmentDescription(ossim_uint32 adjustmentIdx)const; void setCurrentAdjustment(ossim_uint32 adjustmentIndex, bool notify=false); //! Sets the current adjustment to the adjustment with a matching description. //! Returns true if successfully matched. bool setCurrentAdjustment(const ossimString& description, bool notify=false); void eraseAdjustment(bool notify); void eraseAdjustment(ossim_uint32 idx, bool notify); virtual void initAdjustableParameters(); void resetAdjustableParameters(bool notify=false); void copyAdjustment(ossim_uint32 idx, bool notify); void copyAdjustment(bool notify = false); virtual ossimObject* getBaseObject()=0; virtual const ossimObject* getBaseObject()const=0; /*! * Will copy the adjustment but will set the new center to the * applied current center plus the application of the adjustment * */ void keepAdjustment(ossim_uint32 idx, bool createCopy); virtual void keepAdjustment(bool createCopy=true); const ossimAdjustableParameterInterface& operator = (const ossimAdjustableParameterInterface& rhs); void removeAllAdjustments(); ossim_uint32 getNumberOfAdjustableParameters()const; double getAdjustableParameter(ossim_uint32 idx)const; virtual void setAdjustableParameter(ossim_uint32 idx, double value, bool notify=false); virtual void setAdjustableParameter(ossim_uint32 idx, double value, double sigma, bool notify=false); double getParameterSigma(ossim_uint32 idx)const; void setParameterSigma(ossim_uint32 idx, double value, bool notify=false); ossimUnitType getParameterUnit(ossim_uint32 idx)const; void setParameterUnit(ossim_uint32 idx, ossimUnitType unit); void setParameterUnit(ossim_uint32 idx, const ossimString& unit); void setParameterCenter(ossim_uint32 idx, double center, bool notify = false); double getParameterCenter(ossim_uint32 idx)const; double computeParameterOffset(ossim_uint32 idx)const; void setParameterOffset(ossim_uint32 idx, ossim_float64 value, bool notify = false); ossimString getParameterDescription(ossim_uint32 idx)const; void setParameterDescription(ossim_uint32 idx, const ossimString& descrption); ossim_int32 findParameterIdxGivenDescription(ossim_uint32 adjustmentIdx, const ossimString& name)const; ossim_int32 findParameterIdxContainingDescription(ossim_uint32 adjustmentIdx, const ossimString& name)const; bool isParameterLocked(ossim_uint32 idx)const; void setParameterLockFlag(ossim_uint32 idxParam, bool flag); bool getParameterLockFlag(ossim_uint32 idx)const; void lockAllParametersCurrentAdjustment(); void unlockAllParametersCurrentAdjustment(); void lockAllParameters(ossim_uint32 idxAdjustment); void unlockAllParameters(ossim_uint32 idxAdjustment); void resizeAdjustableParameterArray(ossim_uint32 numberOfParameters); void setAdjustment(const ossimAdjustmentInfo& adj, bool notify=false); void setAdjustment(ossim_uint32 idx, const ossimAdjustmentInfo& adj, bool notify=false); void addAdjustment(const ossimAdjustmentInfo& adj, bool notify); void getAdjustment(ossimAdjustmentInfo& adj) const; void getAdjustment(ossim_uint32 idx, ossimAdjustmentInfo& adj) const; ossim_uint32 getNumberOfAdjustments()const; ossim_uint32 getCurrentAdjustmentIdx()const; void setDirtyFlag(bool flag=true); void setAllDirtyFlag(bool flag = true); bool hasDirtyAdjustments()const; //! Saves the current active adjustment to the KWL file. If an adjustment of the same //! description already exists in the KWL, it is replaced by the current adjustment. //! The object is synced up with contents of KWL. virtual void saveCurrentAdjustmentOnly(ossimKeywordlist &kwl, const ossimString& prefix=ossimString("")); bool saveAdjustments(ossimKeywordlist& kwl, const ossimString& prefix=ossimString(""))const; bool loadAdjustments(const ossimKeywordlist& kwl, const ossimString& prefix=ossimString("")); //! Provides the derived adjustable class an opportunity to update its state after a param change. virtual void updateModel() {} //! Dumps the currently active adjustment to std::ostream. std::ostream& print(std::ostream& out) const; protected: //! Returns true if specified parameter has been modified since last setAllChangeFlag(false) call. bool paramChanged(ossim_uint32 param_idx) const { return theChangeFlags[param_idx]; } //! Sets all the change flags to the boolean indicated to indicate parameters are changed (TRUE) //! or not (FALSE). void setAllChangeFlags(bool areChanged); //! Initializes the change flags to TRUE. void initChangeFlags(); private: std::vector theChangeFlags; std::vector theAdjustmentList; ossim_uint32 theCurrentAdjustment; public: virtual void adjustableParametersChanged(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimAdjustmentExecutive.h000066400000000000000000000077101352751253100246330ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // test // // Description: Executive class for adjustment operations. //---------------------------------------------------------------------------- #ifndef ossimAdjustmentExecutive_HEADER #define ossimAdjustmentExecutive_HEADER #include #include #include #include #include #include #include #include #include #include #include class ossimWLSBundleSolution; class ossimAdjSolutionAttributes; class OSSIM_DLL ossimAdjustmentExecutive : public ossimObject { public: /** * @brief constructor */ ossimAdjustmentExecutive(std::ostream& report); /** @brief ossimObservationSet constructor * * @param obsSet tiepoint observation set. */ ossimAdjustmentExecutive(ossimObservationSet& obsSet, std::ostream& report); /** @brief destructor */ ~ossimAdjustmentExecutive(); /** * @brief initialize adjustment solution * * @param obsSet tiepoint observation set. * * @return true on success, false on error. */ bool initializeSolution(ossimObservationSet& obsSet); /** * @brief run adjustment solution * * @return true on success, false on error. */ bool runSolution(); /** * @brief summarize solution */ void summarizeSolution() const; /** * @brief compute mean and RMS error of residuals * * @param res image residual matrix. * * @return true on success, false on error. */ bool computeResidualStatistics(NEWMAT::Matrix& res); /** * @brief compute SEUW * * @return standard error of unit weight. */ double computeSEUW(); /** * @brief Print parameter correction method. */ std::ostream& printParameterCorrectionSummary(std::ostream& out) const; /** * @brief Print observation correction method. */ std::ostream& printObservationCorrectionSummary(std::ostream& out) const; /** * @brief Print residuals method. */ std::ostream& printResidualSummary(std::ostream& out) const; inline bool isValid() const { return theExecValid; } void setMaxIter(const int maxIter) { theMaxIter = maxIter; } void setConvCriteria(const int convCriteria) { theConvCriteria = convCriteria; } protected: bool theExecValid; // Observation set ossimObservationSet* theObsSet; // Optimizer ossimWLSBundleSolution* theSol; // Attribute interface ossimAdjSolutionAttributes* theSolAttributes; // Status parameters double theConvCriteria; int theMaxIter; bool theMaxIterExceeded; bool theSolDiverged; bool theSolConverged; // Traits int theNumObsInSet; int theNumImages; int theNumParams; int theNumMeasurements; int theRankN; // Solution arrays NEWMAT::Matrix theMeasResiduals; // theNumMeasurements X 2 NEWMAT::Matrix theObjPartials; // theNumObjObs*3 X 2 NEWMAT::Matrix theParPartials; // theNumImages*(npar/image) X 2 // Statistics double theXrms; double theYrms; double theXmean; double theYmean; std::vector theSEUW; // Adjustable parameter info std::vector theParInitialValues; std::vector theParInitialStdDev; std::vector theParDesc; std::vector theImgs; // Observation info std::vector theObsInitialValues; std::vector theObsInitialStdDev; std::ostream& theRep; /** * @brief Update adjustable parameters. */ bool updateParameters(); /** * @brief Update observatin. */ bool updateObservations(); }; #endif // #ifndef ossimAdjustmentExecutive_HEADER ossim-Miami-2.9.1/include/ossim/base/ossimAdjustmentInfo.h000066400000000000000000000034341352751253100235640ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimAdjustmentInfo.h 23258 2015-04-15 15:54:10Z dburken $ #ifndef ossimAdjustmentInfo_HEADER #define ossimAdjustmentInfo_HEADER #include #include #include #include class OSSIM_DLL ossimAdjustmentInfo { public: friend std::ostream& operator <<(std::ostream& out, const ossimAdjustmentInfo& data); ossimAdjustmentInfo(int numberOfAdjustableParameters=0); ossimAdjustmentInfo(const ossimAdjustmentInfo& rhs); void setNumberOfAdjustableParameters(ossim_uint32 numberOfAdjustableParameters); ossim_uint32 getNumberOfAdjustableParameters()const; ossimString getDescription()const; void setDescription(const ossimString& description); bool isDirty()const; void setDirtyFlag(bool flag=true); void setLockParameterFlag(bool flag, ossim_uint32 idx); void keep(); std::vector& getParameterList(); const std::vector& getParameterList()const; void setLockFlag(bool flag,ossim_uint32 idx); bool saveState(ossimKeywordlist& kwl, const ossimString& prefix=ossimString(""))const; bool loadState(const ossimKeywordlist& kwl, const ossimString& prefix=ossimString("")); private: std::vector theParameterList; ossimString theDescription; mutable bool theDirtyFlag; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimAffineTransform.h000066400000000000000000000052471352751253100237220ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimAffineTransform.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAffineTransform_HEADER #define ossimAffineTransform_HEADER #include #include class OSSIMDLLEXPORT ossimAffineTransform : public ossim2dTo2dTransform { public: ossimAffineTransform(); ossimAffineTransform(const ossimAffineTransform& src); /** * @brief assignment operator= * @param rhs The data to assign from. * @param A reference to this object. */ virtual const ossimAffineTransform& operator=( const ossimAffineTransform& rhs); virtual ossimObject* dup()const { return new ossimAffineTransform(*this); } virtual void forward(const ossimDpt& input, ossimDpt& output)const; virtual void inverse(const ossimDpt& input, ossimDpt& output)const; /*! * Used by the inverse iterator. This will give it a good initial value * that is within the input transforms */ virtual ossimDpt getOrigin()const { return ossimDpt(0,0); } bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); void setMatrix(double rotation, const ossimDpt& scale, const ossimDpt& translation); void setScale(const ossimDpt& scale) { theScale = scale; computeMatrix(); } void setRotation(double rotation) { theRotation = rotation; computeMatrix(); } void setTranslation(const ossimDpt& translation) { theTranslation = translation; computeMatrix(); } ossimDpt getScale()const { return theScale; } ossimDpt getTranslation()const { return theTranslation; } double getRotation()const { return theRotation; } void setIdentity(); void setAffineEnabledFlag(bool flag) { theAffineEnabledFlag = flag; } virtual std::ostream& print(std::ostream& out) const; protected: void computeMatrix(); ossimDpt theScale; double theRotation; ossimDpt theTranslation; bool theAffineEnabledFlag; NEWMAT::Matrix theForwardXform; NEWMAT::Matrix theInverseXform; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimApplicationUsage.h000066400000000000000000000051541352751253100240630ustar00rootroot00000000000000//------------------------------------------------------------------------- // // This code was taken from Open Scene Graph and incorporated from into // OSSIM. // //------------------------------------------------------------------------- // $Id: ossimApplicationUsage.h 19692 2011-05-31 16:55:47Z dburken $ #ifndef ossimApplicationUsage_HEADER #define ossimApplicationUsage_HEADER 1 #include #include #include class OSSIMDLLEXPORT ossimApplicationUsage { public: static ossimApplicationUsage* instance(); ossimApplicationUsage() {} ossimApplicationUsage(const ossimString& commandLineUsage); typedef std::map UsageMap; void setApplicationName(const ossimString& name); const ossimString& getApplicationName() const; void setDescription(const ossimString& desc); const ossimString& getDescription() const; enum Type { OSSIM_COMMAND_LINE_OPTION = 0x1, OSSIM_ENVIRONMENTAL_VARIABLE = 0x2 }; void addUsageExplanation(Type type,const ossimString& option,const ossimString& explanation); void setCommandLineUsage(const ossimString& explanation); const ossimString& getCommandLineUsage() const; void addCommandLineOption(const ossimString& option,const ossimString& explanation); const UsageMap& getCommandLineOptions() const; void addEnvironmentalVariable(const ossimString& option,const ossimString& explanation); const UsageMap& getEnvironmentalVariables() const; void getFormatedString(ossimString& str, const UsageMap& um,unsigned int widthOfOutput=80); void write(std::ostream& output,const UsageMap& um,unsigned int widthOfOutput=80); void write(std::ostream& output,unsigned int type=OSSIM_COMMAND_LINE_OPTION|OSSIM_ENVIRONMENTAL_VARIABLE, unsigned int widthOfOutput=80); protected: ossimString theApplicationName; ossimString theDescription; ossimString theCommandLineUsage; UsageMap theCommandLineOptions; UsageMap theEnvironmentalVariables; }; class ApplicationUsageProxy { public: /** register an explanation of commandline/evironmentalvaraible/keyboard mouse usage.*/ ApplicationUsageProxy(ossimApplicationUsage::Type type,const ossimString& option,const ossimString& explanation) { ossimApplicationUsage::instance()->addUsageExplanation(type,option,explanation); } }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimArgumentParser.h000066400000000000000000000206751352751253100235770ustar00rootroot00000000000000//------------------------------------------------------------------------- // // This code was taken from Open Scene Graph and incorporated from into // OSSIM. // //------------------------------------------------------------------------- // $Id: ossimArgumentParser.h 22491 2013-11-26 18:17:29Z dburken $ #ifndef ossimArgumentParser_HEADER #define ossimArgumentParser_HEADER 1 #include #include #include #include #include class ossimApplicationUsage; class OSSIMDLLEXPORT ossimArgumentParser { public: class ossimParameter { public: enum ossimParameterType { OSSIM_FLOAT_PARAMETER, OSSIM_DOUBLE_PARAMETER, OSSIM_INT_PARAMETER, OSSIM_UNSIGNED_INT_PARAMETER, OSSIM_STRING_PARAMETER, }; union ossimValueUnion { float* theFloat; double* theDouble; int* theInt; unsigned int* theUint; std::string* theString; }; ossimParameter(float& value) { theType = OSSIM_FLOAT_PARAMETER; theValue.theFloat = &value; } ossimParameter(double& value) { theType = OSSIM_DOUBLE_PARAMETER; theValue.theDouble = &value; } ossimParameter(int& value) { theType = OSSIM_INT_PARAMETER; theValue.theInt = &value; } ossimParameter(unsigned int& value) { theType = OSSIM_UNSIGNED_INT_PARAMETER; theValue.theUint = &value; } ossimParameter(std::string& value) { theType = OSSIM_STRING_PARAMETER; theValue.theString = &value; } ossimParameter(ossimString& value) { theType = OSSIM_STRING_PARAMETER; theValue.theString = &(value.string()); } bool valid(const char* str) const; bool assign(const char* str); protected: ossimParameterType theType; ossimValueUnion theValue; }; /** return return true if specified string is an option in the form of * -option or --option . */ static bool isOption(const char* str); /** return return true if string is any other string apart from an option.*/ static bool isString(const char* str); /** return return true if specified parameter is an number.*/ static bool isNumber(const char* str); public: ossimArgumentParser(int* argc,char **argv); ossimArgumentParser(const ossimString& commandLine); ~ossimArgumentParser(); /** @brief Initialize from command arguments. */ void initialize(int* argc, const char **argv); void setApplicationUsage(ossimApplicationUsage* usage) { theUsage = usage; } ossimApplicationUsage* getApplicationUsage() { return theUsage; } const ossimApplicationUsage* getApplicationUsage() const { return theUsage; } /** return the argument count.*/ int& argc() { return *theArgc; } /** return the argument array.*/ char** argv() { return theArgv; } /** return char* argument at specificed position.*/ char* operator [] (int pos) { return theArgv[pos]; } /** return const char* argument at specificed position.*/ const char* operator [] (int pos) const { return theArgv[pos]; } /** return the application name, as specified by argv[0] */ std::string getApplicationName() const; /** return the position of an occurence of a string in the argument list. * return -1 when no string is found.*/ int find(const std::string& str) const; /** return return true if specified parameter is an option in the form of -option or --option .*/ bool isOption(int pos) const; /** return return true if specified parameter is an string, which can be any other string apart from an option.*/ bool isString(int pos) const; /** return return true if specified parameter is an number.*/ bool isNumber(int pos) const; bool containsOptions() const; /** remove one or more arguments from the argv argument list, and decrement the argc respectively.*/ void remove(int pos,int num=1); /** Inserts string into the argv argument list, and increment the argc respectively. * If string contains spaces, it will be split up into component simple strings. */ void insert(int pos, const ossimString& arg); /** return true if specified argument matches string.*/ bool match(int pos, const std::string& str) const; /** * search for an occurance of a string in the argument list, on sucess * remove that occurance from the list and return true, otherwise * return false. */ bool read(const std::string& str); bool read(const std::string& str, ossimParameter value1); bool read(const std::string& str, ossimParameter value1, ossimParameter value2); bool read(const std::string& str, ossimParameter value1, ossimParameter value2, ossimParameter value3); bool read(const std::string& str, ossimParameter value1, ossimParameter value2, ossimParameter value3, ossimParameter value4); bool read(const std::string& str, ossimParameter value1, ossimParameter value2, ossimParameter value3, ossimParameter value4, ossimParameter value5); bool read(const std::string& str, ossimParameter value1, ossimParameter value2, ossimParameter value3, ossimParameter value4, ossimParameter value5, ossimParameter value6); /** * Alternate form for reading variable length arguments (must be comma-separated), e.g., * * --input_files file1, file2, file3,file4 next_arg * * Note that spaces between arguments are optional. The next_arg entry will not be considered * part of the list since there's no comma separator and will be left on the argument array. * @param str The option string (with "-" or "--") * @param param_list Vector to contain results as strings. Always cleared before populating * @return True if option found (param_list may be empty f no args followed). */ bool read(const std::string& str, std::vector& param_list); /** * @return The number of parameters of type value associated with specified * option, or -1 if option not found */ int numberOfParams(const std::string& str, const ossimParameter value) const; /** * if the argument value at the position pos matches specified string, and * subsequent paramters are also matched then set the paramter values and * remove the from the list of arguments. */ bool read(int pos, const std::string& str); bool read(int pos, const std::string& str, ossimParameter value1); bool read(int pos, const std::string& str, ossimParameter value1, ossimParameter value2); bool read(int pos, const std::string& str, ossimParameter value1, ossimParameter value2, ossimParameter value3); bool read(int pos, const std::string& str, ossimParameter value1, ossimParameter value2, ossimParameter value3, ossimParameter value4); enum ossimErrorSeverity { OSSIM_BENIGN = 0, OSSIM_CRITICAL = 1 }; typedef std::map ossimErrorMessageMap; /** * @return The error flag, true if an error has occured when * reading arguments. */ bool errors(ossimErrorSeverity severity=OSSIM_BENIGN) const; /** report an error message by adding to the ErrorMessageMap.*/ void reportError(const std::string& message, ossimErrorSeverity severity=OSSIM_CRITICAL); /** for each remaining option report it as an unrecongnized.*/ void reportRemainingOptionsAsUnrecognized( ossimErrorSeverity severity=OSSIM_BENIGN); /** @return The error message, if any has occured.*/ ossimErrorMessageMap& getErrorMessageMap(); /** @return The error message, if any has occured.*/ const ossimErrorMessageMap& getErrorMessageMap() const; /** write out error messages at an above specified .*/ void writeErrorMessages(std::ostream& output, ossimErrorSeverity sevrity=OSSIM_BENIGN); protected: int* theArgc; char** theArgv; ossimErrorMessageMap theErrorMessageMap; ossimApplicationUsage* theUsage; bool theMemAllocated; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimAxes.h000066400000000000000000000060411352751253100215270ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class declaration for ossimAxes. This will allow you to // define three orthogonal ossimAxes and an origin in 3-D space. This // information will be used to allow you to place points relative // to the defined axes. //******************************************************************* // $Id: ossimAxes.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAxes_HEADER #define ossimAxes_HEADER #include #include #include #include class OSSIMDLLEXPORT ossimAxes { public: friend inline std::ostream& operator <<(std::ostream &out, const ossimAxes &axes); /*! * Default constructor is at position 0, 0, 0 with unit axes * */ ossimAxes(const ossimColumnVector3d &origin=ossimColumnVector3d(0,0,0), const ossimColumnVector3d &xAxis=ossimColumnVector3d(1,0,0), const ossimColumnVector3d &yAxis=ossimColumnVector3d(0,1,0), const ossimColumnVector3d &zAxis=ossimColumnVector3d(0,0,1)) : theOrigin(origin), theXAxis(xAxis), theYAxis(yAxis), theZAxis(zAxis) {} ossimColumnVector3d projectPoint(const ossimColumnVector3d &pt) { return ossimColumnVector3d(theXAxis.dot(pt), theYAxis.dot(pt), theZAxis.dot(pt)); } ossimColumnVector3d pointRelative(const ossimColumnVector3d& pt) { return projectPoint(pt - theOrigin); } void rotateAxes(const ossimMatrix3x3& m) { theXAxis = m*theXAxis; theYAxis = m*theYAxis; theZAxis = m*theZAxis; } void rotateAxes(const ossimMatrix4x4& m) { theXAxis = m.rotateOnly(theXAxis); theYAxis = m.rotateOnly(theYAxis); theZAxis = m.rotateOnly(theZAxis); } void transformOrigin(const ossimMatrix3x3& m) { theOrigin = m*theOrigin; } void transformOrigin(const ossimMatrix4x4& m) { theOrigin = m*theOrigin; } const ossimColumnVector3d& origin()const{return theOrigin;} const ossimColumnVector3d& xAxis()const{return theXAxis;} const ossimColumnVector3d& yAxis()const{return theYAxis;} const ossimColumnVector3d& zAxis()const{return theZAxis;} private: ossimColumnVector3d theOrigin; // Is the origin of this axes ossimColumnVector3d theXAxis; // Is the direction of the x axis ossimColumnVector3d theYAxis; // Is the direction of the y axis ossimColumnVector3d theZAxis; // Is the direction of the z axis }; inline std::ostream& operator <<(std::ostream &out, const ossimAxes &axes) { return out << "position: " << axes.theOrigin << std::endl << "x axis : " << axes.theXAxis << std::endl << "Y axis : " << axes.theYAxis << std::endl << "z axis : " << axes.theZAxis; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimBaseObjectFactory.h000066400000000000000000000021531352751253100241600ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimBaseObjectFactory.h 22645 2014-02-28 12:45:52Z gpotts $ #ifndef ossimBaseObjectFactory_HEADER #define ossimBaseObjectFactory_HEADER #include class OSSIMDLLEXPORT ossimBaseObjectFactory : public ossimObjectFactory { public: ossimBaseObjectFactory(); virtual ~ossimBaseObjectFactory(){} static ossimBaseObjectFactory* instance(); virtual ossimObject* createObject(const ossimString& typeName)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const; protected: TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimBilSplitter.h000066400000000000000000000027761352751253100230770ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration for ossimBilSplitter. // // Utility class for splitting an image that is band interleaved by line into // separate files. //******************************************************************* // $Id: ossimBilSplitter.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimBilSplitter_HEADER #define ossimBilSplitter_HEADER #include #include class OSSIMDLLEXPORT ossimBilSplitter { public: ossimBilSplitter(const char* file_to_split, ossim_uint32 header_size_in_bytes, ossim_uint32 bytes_per_pixel, ossim_uint32 samples_per_line, ossim_uint32 number_of_channels); ~ossimBilSplitter(); enum ossimStatus { OSSIM_OK = 0, OSSIM_ERROR = 1 }; /*! * Splits source image into separate bands and writes to output * directory as channel_1.ras, channel_2.ras, ... * Returns true on success, false on error. */ bool output_multi_files(const char* output_dir); int errorStatus() const { return theErrorStatus; } private: ifstream theSourceFileStr; ossim_uint32 theHeaderSizeInBytes; ossim_uint32 theBytesPerLine; ossim_uint32 theLinesToWrite; ossim_uint32 theNumberOfChannels; ossimStatus theErrorStatus; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimBinaryDataProperty.h000066400000000000000000000017041352751253100244130ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // //************************************************************************* #ifndef ossimBinaryDataProperty_HEADER #define ossimBinaryDataProperty_HEADER #include #include #include class OSSIMDLLEXPORT ossimBinaryDataProperty : public ossimProperty { public: ossimBinaryDataProperty(const ossimString& name=ossimString(""), const std::vector& binaryData = std::vector()); virtual ~ossimBinaryDataProperty(); virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult) const; void setBinaryData(const std::vector& binaryData); const std::vector& getBinaryData() const; private: std::vector theBinaryData; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimBlockIStream.h000066400000000000000000000036371352751253100231560ustar00rootroot00000000000000#ifndef ossimBlockStream_HEADER #define ossimBlockStream_HEADER 1 #include namespace ossim { /** * * @brief Allows one to adapt any input stream to be block aligned * for any read it will internally read overlapping blocks filling * the request. * * Example: * @code * * ossim_uint64 blockSize = 4096 * std::shared_ptr reader = std::make_shared(streamToAdapt, blockSize) * * reader->seekg(10); * reader->read(buf, 100); * @endcode * * This will read a block of data from 0-4095 and then fill the buffer * with 100 bytes of data. * * if another call to: reader->read(buf, 10) * it will not reload the block but instead read from memory * */ class BlockIStream : public ossim::istream { public: /** * Constructor must be initialized with an inputstream. * * @param adaptStream Currenlty a required parameter and is initialized on construction. Takes an input std::istream to force block aligned * requests * @param blockSize Specify the block size to use */ BlockIStream(std::shared_ptr adaptStream, ossim_uint64 blockSize=4096): ossim::istream(&m_blockStreamBuffer), m_adaptStream(adaptStream), m_blockStreamBuffer(adaptStream.get(), blockSize) { } /** * @brief Destructor will set any shared pointer to 0 */ virtual ~BlockIStream(){ m_adaptStream = 0; } /** * Maintain a shared pointer to the stream we are adapting * to be block aligned. */ std::shared_ptr m_adaptStream; /** * * The buffer where all the block align implementation resides * */ BlockStreamBuffer m_blockStreamBuffer; }; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimBooleanProperty.h000066400000000000000000000017411352751253100237550ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBooleanProperty.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimBoolenaProperty_HEADER #define ossimBoolenaProperty_HEADER #include class OSSIMDLLEXPORT ossimBooleanProperty : public ossimProperty { public: ossimBooleanProperty(const ossimString& name=ossimString(""), bool value = false); ossimBooleanProperty(const ossimBooleanProperty& rhs); virtual ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); virtual bool setValue(const ossimString& value); bool setBooleanValue(bool value, ossimString& msg); void valueToString(ossimString& valueResult)const; bool getBoolean()const; protected: bool theValue; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimByteStreamBuffer.h000066400000000000000000000040731352751253100240430ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-foo.cpp // // Author: Garrett Potts // // Description: This is a basic_streambuf that can be used for binary in memory streams // // // $Id$ //---------------------------------------------------------------------------- #ifndef ossimByteStreamBuffer_HEADER #define ossimByteStreamBuffer_HEADER #include #include /* for EOF */ #include #include #include class OSSIM_DLL ossimByteStreamBuffer : public std::basic_streambuf > { public: ossimByteStreamBuffer(); ossimByteStreamBuffer(char_type* buf, ossim_int64 bufSize, bool shared=true); ossimByteStreamBuffer(const ossimByteStreamBuffer& src); virtual ~ossimByteStreamBuffer(); virtual std::streambuf* setbuf ( char_type * s, std::streamsize n ); void clear(); // added so we can set a buffer and make it shared std::streambuf* setBuf(char* buf, std::streamsize bufSize, bool shared); virtual int overflow( int c = EOF); /** * Returns a pointer to the buffer */ char_type* buffer(); const char_type* buffer()const; /** * The buffer is no longer managed by this stream buffer and is removed. */ char_type* takeBuffer(); ossim_uint64 bufferSize()const; protected: virtual int_type pbackfail(int_type __c = traits_type::eof()); virtual pos_type seekoff(off_type offset, std::ios_base::seekdir dir, std::ios_base::openmode __mode = std::ios_base::in | std::ios_base::out); virtual pos_type seekpos(pos_type pos, std::ios_base::openmode __mode = std::ios_base::in | std::ios_base::out); virtual std::streamsize xsgetn(char_type* __s, std::streamsize __n); virtual std::streamsize xsputn(const char_type* __s, std::streamsize __n); void deleteBuffer(); void extendBuffer(ossim_uint64 bytes); char_type* m_buffer; ossim_int64 m_bufferSize; bool m_sharedBuffer; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimCallback1.h000066400000000000000000000036071352751253100224110ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimCallback1wRet.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Simple templated callback class that takes a single parameter(argument) "P1" // with void return. // // See link for more detail description: // http://www.tutok.sk/fastgl/callback.html // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimCallback1_HEADER #define ossimCallback1_HEADER 1 /** * @class ossimCallback1 * * Usage example, note template params can be anything: * * Caller interface to register callback: * * @code * void registerCallback(ossimCallback1* cb); * @endcode * * Callee creation of call back mechanism: * * @code * class ProcessFileCB: public ossimCallback1 * { * public: * ProcessFileCB( * ossimImageElevationDatabase* obj, * void (ossimImageElevationDatabase::*func)(const ossimFilename&)) * : * m_obj(obj), * m_func(func) * {} * * virtual void operator()(const ossimFilename& file) const * { * ( m_obj->*m_func)(file); * } * * private: * ossimImageElevationDatabase* m_obj; * void (ossimImageElevationDatabase::*m_func)(const ossimFilename& file); * }; * @endcode * * Making/registering a callback. * * @code * ossimFileWalker* fw = new ossimFileWalker(); * * ossimCallback1wRet* cb = * new ProcessFileCB(this, &ossimImageElevationDatabase::processFile); * * fw->registerProcessFileCallback(cb); * * @endcode */ template class ossimCallback1 { public: ossimCallback1(){} virtual ~ossimCallback1(){} virtual void operator()(P1 p1) const = 0; }; #endif /* #ifndef ossimCallback1_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimCallback1wRet.h000066400000000000000000000037211352751253100232500ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimCallback1wRet.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Simple templated callback class that takes a single parameter(argument) "P1" // and has a return "RT". // // See link for more detail description: // http://www.tutok.sk/fastgl/callback.html // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimCallback1wRet_HEADER #define ossimCallback1wRet_HEADER 1 /** * @class ossimCallback1wRet * * Usage example, note template params can be anything: * * Caller interface to register callback: * * @code * void registerCallback(ossimCallback1wRet* cb); * @endcode * * Callee creation of call back mechanism: * * @code * class ProcessFileCB: public ossimCallback1wRet * { * public: * ProcessFileCB( * ossimImageElevationDatabase* obj, * bool (ossimImageElevationDatabase::*func)(const ossimFilename&)) * : * m_obj(obj), * m_func(func) * {} * * virtual bool operator()(const ossimFilename& file) const * { * return ( m_obj->*m_func)(file); * } * * private: * ossimImageElevationDatabase* m_obj; * bool (ossimImageElevationDatabase::*m_func)(const ossimFilename& file); * }; * @endcode * * Making/registering a callback. * * @code * ossimFileWalker* fw = new ossimFileWalker(); * * ossimCallback1wRet* cb = * new ProcessFileCB(this, &ossimImageElevationDatabase::processFile); * * fw->registerProcessFileCallback(cb); * * @endcode */ template class ossimCallback1wRet { public: ossimCallback1wRet(){} virtual ~ossimCallback1wRet(){} virtual RT operator()(P1 p1) const = 0; }; #endif /* #ifndef ossimCallback1wRet_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimCallback2wRet.h000066400000000000000000000040341352751253100232470ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimCallback2wRet.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Simple templated callback class that takes a two parameters(arguments) "P1" // and has a return "RT". // // See link for more detail description: // http://www.tutok.sk/fastgl/callback.html // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimCallback2wRet_HEADER #define ossimCallback2wRet_HEADER 1 /** * @class ossimCallback2wRet * * Usage example, note template params can be anything: * * Caller interface to register callback: * * @code * void registerCallback(ossimCallback2wRet* cb); * @endcode * * Callee creation of call back mechanism: * * @code * class ProcessFileCB: public ossimCallback2wRet * { * public: * ProcessFileCB( * ossimImageElevationDatabase* obj, * bool (ossimImageElevationDatabase::*func)(const ossimFilename&, bool&)) * : * m_obj(obj), * m_func(func) * {} * * virtual bool operator()(const ossimFilename& file, bool& flag) const * { * return ( m_obj->*m_func)(file, flag); * } * * private: * ossimImageElevationDatabase* m_obj; * bool (ossimImageElevationDatabase::*m_func)(const ossimFilename& file, bool& flag); * }; * @endcode * * Making/registering a callback. * * @code * ossimFileWalker* fw = new ossimFileWalker(); * * ossimCallback2wRet* cb = * new ProcessFileCB(this, &ossimImageElevationDatabase::processFile); * * fw->registerProcessFileCallback(cb); * * @endcode */ template class ossimCallback2wRet { public: ossimCallback2wRet(){} virtual ~ossimCallback2wRet(){} virtual RT operator()(P1 p1, P2 p2) const = 0; }; #endif /* #ifndef ossimCallback2wRet_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimCmyVector.h000066400000000000000000000024041352751253100225410ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimCmyVector.h 14789 2009-06-29 16:48:14Z dburken $ #include #include class ossimJpegYCbCrVector; class ossimHsiVector; class ossimHsvVector; class ossimRgbVector; class OSSIMDLLEXPORT ossimCmyVector { public: friend std::ostream& operator <<(std::ostream& out, const ossimCmyVector& cmy) { out << "<" << cmy.theC << ", " << cmy.theM <<", " << cmy.theY << ">" << std::endl; return out; } ossimCmyVector(unsigned char c, unsigned char m, unsigned char y) : theC(c), theM(m), theY(y) {} ossimCmyVector(const ossimRgbVector& rgb); ossim_uint8 getC()const { return theC; } ossim_uint8 getM()const { return theC; } ossim_uint8 getY()const { return theC; } const ossimCmyVector& operator = (const ossimRgbVector& rgb); protected: ossim_uint8 theC; ossim_uint8 theM; ossim_uint8 theY; }; ossim-Miami-2.9.1/include/ossim/base/ossimColorProperty.h000066400000000000000000000024551352751253100234570ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimColorProperty.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimColorProperty_HEADER #define ossimColorProperty_HEADER #include #include #include class OSSIMDLLEXPORT ossimColorProperty : public ossimProperty { public: ossimColorProperty(const ossimString& name=ossimString(""), const ossimRgbVector& value = ossimRgbVector(0,0,0)); ossimColorProperty(const ossimColorProperty& rhs); virtual ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; const ossimRgbVector& getColor()const; void setColor(const ossimRgbVector& value); ossim_uint8 getRed()const; ossim_uint8 getGreen()const; ossim_uint8 getBlue()const; void setRed(ossim_uint8 r); void setGreen(ossim_uint8 r); void setBlue(ossim_uint8 r); protected: virtual ~ossimColorProperty(); ossimRgbVector theValue; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimColumnVector3d.h000066400000000000000000000167751352751253100235150ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This is a 3-D vector without the homogeneous // coordinate. // //******************************************************************* // $Id: ossimColumnVector3d.h 20074 2011-09-08 16:16:27Z gpotts $ #ifndef ossimColumnVector3d_HEADER #define ossimColumnVector3d_HEADER #include #include #include // for FLT_EPSILON #include #include #include #include #include class OSSIMDLLEXPORT ossimColumnVector3d { public: ossimColumnVector3d() { data[0]=0; data[1]=0; data[2]=0; } ossimColumnVector3d(double x, double y, double z=0) { data[0]=x; data[1]=y; data[2]=z; } // Default copy-constructor is perfect // ossimColumnVector3d(const ossimColumnVector3d &rhs) = default; explicit ossimColumnVector3d(const NEWMAT::ColumnVector& rhs) { if ( (rhs.Ncols() == 1) && (rhs.Nrows() > 2) ) { data[0] = rhs[0]; data[1] = rhs[1]; data[2] = rhs[2]; } else { data[0]=0; data[1]=0; data[2]=0; } } const ossimColumnVector3d& operator=(const NEWMAT::ColumnVector& rhs) { if ( (rhs.Ncols() == 1) && (rhs.Nrows() == 3) ) { data[0] = rhs[0]; data[1] = rhs[1]; data[2] = rhs[2]; } return *this; } friend std::ostream& operator <<(std::ostream& out, const ossimColumnVector3d& v) { return out << std::setiosflags(std::ios::fixed) << std::setprecision(15) << v[0] << " " << v[1] <<" " << v[2]; } friend ossimColumnVector3d operator*(double scalar, const ossimColumnVector3d &v) { return ossimColumnVector3d(v.data[0]*scalar, v.data[1]*scalar, v.data[2]*scalar); } /*! * Multiplies column vector times matrix. * Note: * If "lhs" is not a 3x3 that's an error and a blank column vector * is returned. */ friend ossimColumnVector3d operator*(const NEWMAT::Matrix& lhs, const ossimColumnVector3d& rhs) { if ((lhs.Ncols() == 3) && (lhs.Nrows() == 3)) { return ossimColumnVector3d( (lhs[0][0]*rhs[0] + lhs[0][1]*rhs[1] + lhs[0][2]*rhs[2]), (lhs[1][0]*rhs[0] + lhs[1][1]*rhs[1] + lhs[1][2]*rhs[2]), (lhs[2][0]*rhs[0] + lhs[2][1]*rhs[1] + lhs[2][2]*rhs[2])); } else if((lhs.Ncols() == 4) && (lhs.Nrows() == 4)) { return ossimColumnVector3d( (lhs[0][0]*rhs[0] + lhs[0][1]*rhs[1] + lhs[0][2]*rhs[2] + lhs[0][3]) , (lhs[1][0]*rhs[0] + lhs[1][1]*rhs[1] + lhs[1][2]*rhs[2] + lhs[1][3]) , (lhs[2][0]*rhs[0] + lhs[2][1]*rhs[1] + lhs[2][2]*rhs[2] + lhs[2][3])); } ossimNotify(ossimNotifyLevel_WARN) << "Multiplying a 3 row column vector by an invalid matrix" << std::endl; return rhs; } double& operator [](int index) { return data[index]; } const double& operator [](int index)const { return data[index]; } ossimColumnVector3d operator*(double scalar)const { return ossimColumnVector3d(data[0]*scalar, data[1]*scalar, data[2]*scalar); } ossimColumnVector3d operator +(const ossimColumnVector3d &rhs)const { return ossimColumnVector3d( data[0]+rhs[0], data[1]+rhs[1], data[2]+rhs[2]); } const ossimColumnVector3d& operator +=(const ossimColumnVector3d &rhs) { data[0] += rhs[0]; data[1] += rhs[1]; data[2] += rhs[2]; return *this; } ossimColumnVector3d operator - ()const { return ossimColumnVector3d(-data[0], -data[1], -data[2]); } ossimColumnVector3d operator /(double scalar)const { return ossimColumnVector3d( data[0]/scalar, data[1]/scalar, data[2]/scalar); } const ossimColumnVector3d& operator /=(double scalar) { data[0]/=scalar; data[1]/=scalar; data[2]/=scalar; return *this; } ossimColumnVector3d operator -(const ossimColumnVector3d &rhs)const { return ossimColumnVector3d( data[0]-rhs[0], data[1]-rhs[1], data[2]-rhs[2]); } const ossimColumnVector3d& operator -=(const ossimColumnVector3d &rhs) { data[0] -= rhs[0]; data[1] -= rhs[1]; data[2] -= rhs[2]; return *this; } bool operator ==(const ossimColumnVector3d &rhs) const { return ((fabs(data[0] - rhs[0]) <= FLT_EPSILON) && (fabs(data[1] - rhs[1]) <= FLT_EPSILON) && (fabs(data[2] - rhs[2]) <= FLT_EPSILON)); } bool operator !=(const ossimColumnVector3d &rhs) const { return !(*this == rhs); } double magnitude()const { return sqrt(data[0]*data[0] + data[1]*data[1] + data[2]*data[2]); } inline double norm2()const //!speedup { return data[0]*data[0] + data[1]*data[1] + data[2]*data[2]; } double dot(const ossimColumnVector3d &rhs) const { return (data[0]*rhs[0]+ data[1]*rhs[1]+ data[2]*rhs[2]); } ossimColumnVector3d unit() const { double mag = magnitude(); if(fabs(mag) > FLT_EPSILON) { mag = 1.0/mag; return (*this *mag); } return *this; } ossimColumnVector3d cross(const ossimColumnVector3d &rhs) const { return ossimColumnVector3d( data[1]*rhs[2] - data[2]*rhs[1], data[2]*rhs[0] - data[0]*rhs[2], data[0]*rhs[1] - data[1]*rhs[0]); } const ossimColumnVector3d& xAligned() { data[0] = 1; data[1] = 0; data[2] = 0; return *this; } const ossimColumnVector3d& yAligned()// { data[0] = 0; data[1] = 1; data[2] = 0; return *this; } const ossimColumnVector3d& zAligned() // { data[0] = 0; data[1] = 0; data[2] = 1; return *this; } /** * @brief To string method. * * @param precision Output floating point precision. * * @return ossimString representing point. * * Output format: * ( 0.0000000, 0.0000000, 0.00000000 ) * -----x---- -----y---- ------z---- */ ossimString toString(ossim_uint32 precision=15) const; /** * @brief Initializes this point from string. * * Expected format: * * ( 0.0000000, 0.0000000, 0.00000000 ) * -----x---- -----y---- ------z---- * * @param s String to initialize from. */ void toPoint(const std::string& s); private: double data[3]; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimColumnVector4d.h000066400000000000000000000114501352751253100234770ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This is your 3-D vector where the 4-th dimension is // for the homogenious coordinate. // //******************************************************************* // $Id: ossimColumnVector4d.h 11346 2007-07-23 12:59:48Z gpotts $ #ifndef ossimColumnVector4d_HEADER #define ossimColumnVector4d_HEADER #include #include #include // for FLT_EPSILON #include #include #include class OSSIMDLLEXPORT ossimColumnVector4d { public: ossimColumnVector4d() { data[0]=0; data[1]=0; data[2]=0; data[3]=1; } ossimColumnVector4d(double x, double y, double z, double w=1.0) { data[0]=x; data[1]=y; data[2]=z; data[3]=w; } ossimColumnVector4d(const ossimColumnVector4d &rhs) { data[0] = rhs.data[0]; data[1] = rhs.data[1]; data[2] = rhs.data[2]; data[3] = rhs.data[3]; } friend std::ostream& operator <<(std::ostream& out, const ossimColumnVector4d& v) { return out << std::setiosflags(std::ios::fixed) << std::setprecision(15) << v[0] << " " << v[1] <<" " << v[2] << " " << v[3]; } friend ossimColumnVector4d operator*(double scalar, const ossimColumnVector4d &v) { return ossimColumnVector4d(v.data[0]*scalar, v.data[1]*scalar, v.data[2]*scalar); } double& operator [](int index) { return data[index]; } const double& operator [](int index)const { return data[index]; } ossimColumnVector4d operator*(double scalar)const { return ossimColumnVector4d(data[0]*scalar, data[1]*scalar, data[2]*scalar); } ossimColumnVector4d operator +(const ossimColumnVector4d &rhs)const { return ossimColumnVector4d( data[0]+rhs[0], data[1]+rhs[1], data[2]+rhs[2]); } ossimColumnVector4d operator +=(const ossimColumnVector4d &rhs) { data[0] += rhs[0]; data[1] += rhs[1]; data[2] += rhs[2]; return *this; } ossimColumnVector4d operator - ()const { return ossimColumnVector4d(-data[0], -data[1], -data[2]); } ossimColumnVector4d operator /(double scalar)const { return ossimColumnVector4d( data[0]/scalar, data[1]/scalar, data[2]/scalar); } ossimColumnVector4d& operator /=(double scalar) { data[0]/=scalar; data[1]/=scalar; data[2]/=scalar; return *this; } ossimColumnVector4d operator -(const ossimColumnVector4d &rhs)const { return ossimColumnVector4d( data[0]-rhs[0], data[1]-rhs[1], data[2]-rhs[2]); } ossimColumnVector4d operator -=(const ossimColumnVector4d &rhs) { data[0] -= rhs[0]; data[1] -= rhs[1]; data[2] -= rhs[2]; return *this; } double magnitude()const { return std::sqrt(data[0]*data[0] + data[1]*data[1] + data[2]*data[2]); } double dot(const ossimColumnVector4d &rhs)const { return (data[0]*rhs[0]+ data[1]*rhs[1]+ data[2]*rhs[2]); } ossimColumnVector4d unit()const { double mag = magnitude(); if(std::abs(mag) > DBL_EPSILON) { mag = 1.0/mag; return (*this *mag); } return *this; } ossimColumnVector4d cross(const ossimColumnVector4d &rhs) { return ossimColumnVector4d( data[1]*rhs[2] - data[2]*rhs[1], data[2]*rhs[0] - data[0]*rhs[2], data[0]*rhs[1] - data[1]*rhs[0]); } ossimColumnVector4d& xAligned()// creates 4-D homogeneous vectors { data[0] = 1; data[1] = 0; data[2] = 0; data[3] = 1; return *this; } ossimColumnVector4d& yAligned()// { data[0] = 0; data[1] = 1; data[2] = 0; data[3] = 1; return *this; } ossimColumnVector4d& zAligned() // { data[0] = 0; data[1] = 0; data[2] = 1; data[3] = 1; return *this; } private: double data[4]; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimCommon.h000066400000000000000000000602341352751253100220630ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts, with some additions and modifciations by // Patrick Melody // // Description: Common file for utility functions. // //************************************************************************* // $Id: ossimCommon.h 23131 2015-02-06 13:35:55Z gpotts $ #ifndef ossimCommon_HEADER #define ossimCommon_HEADER 1 // XXX nullify these for now, but eventually replace with a #include #define ossimREQUIRE(expr) #define ossimENSURE(expr) #define ossimCHECK(expr) #define ossimSTATIC_CHECK(expr,msg) #include #include #include #include #include #include #include #include #include #include #include class ossimIpt; class ossimIrect; class ossimDpt; class ossimGpt; class ossimImageSource; namespace NEWMAT { class Matrix; } namespace ossim { OSSIM_DLL std::istream& skipws(std::istream& in); OSSIM_DLL bool isWhiteSpace(int c); template /* inline bool almostEqual(T x, T y, T tolerence = std::numeric_limits::epsilon()) */ /* // are x and y within tolerance distance of each other? */ /* { return std::abs(x - y) <= tolerence; } */ inline bool almostEqual(T x, T y, T tolerance = FLT_EPSILON) // are x and y within tolerance distance of each other? { return std::fabs(x - y) <= tolerance; } template inline bool inInterval(T x, T a, T b) // is x in the closed interval [a,b]? { return x >= a && x <= b; } template inline bool inOpenInterval(T x, T a, T b) // is x in the open interval (a,b)? { return x > a && x < b; } /** * isnan Test for floating point Not A Number (NAN) value. * This should be used test for nan. * DO NOT USE operator==. Like "if (height == ossim::nan())" * * @return true if nan, false if not. * * @see nan() */ #if defined(WIN32) || defined(_MSC_VER) && !defined(__CYGWIN__) && !defined(__MWERKS__) inline bool isnan(const float& v) { return _isnan(v); } inline bool isnan(const double& v) { return _isnan(v); } #elif defined(sun) || defined(__sun) # if defined(__SVR4) || defined(__svr4__) /* Solaris */ inline bool isnan(const float& v) { return ( ::isnan(v) ); } inline bool isnan(const double& v) { return ( ::isnan(v) ); } # else /* SunOS */ inline bool isnan(const float& v) { return ( ::isnan(v) ); } inline bool isnan(const double& v) { return ( ::isnan(v) ); } # endif #else inline bool isnan(const float& v) { return ( std::isnan(v) ); } inline bool isnan(const double& v) { return ( std::isnan(v) ); } #endif /* #if defined(WIN32) || defined(_MSC_VER) && !defined(__CYGWIN__) && !defined(__MWERKS__) */ /* inline bool isnan(const float& v) { return _isnan(v); } */ /* inline bool isnan(const double& v) { return _isnan(v); } */ /* #else */ /* inline bool isnan(const float& v) { return ( std::isnan(v) ); } */ /* inline bool isnan(const double& v) { return ( std::isnan(v) ); } */ /* #endif */ /** @brief Class lets us see bit patterns of floats. */ class OSSIM_DLL IntFloatBitCoercion { public: union { ossim_int64 intname; ossim_float64 floatname; } bits; IntFloatBitCoercion(ossim_int64 x) { bits.intname = x; } IntFloatBitCoercion(ossim_float64 x) { bits.floatname = x; } }; /** * @brief Declaration of nan part of nan() declared here for inline * ossim::nan(). */ extern OSSIM_DLL_DATA(const IntFloatBitCoercion) nanValue; /** * @brief Method to return ieee floating point double precision NAN. * * @return ieee floating point double precision NAN. * * @see isnan() * * @note casts seamlessly to float and long double. * * @note Use ossim::isnan(v) to test for nan. * Like "if (isnan(myDoubleValue)) { doSomething; }" * DO NOT USE operator==. Like "if (myDoubleValue == ossim::nan())" */ inline double nan() { return nanValue.bits.floatname; } template inline T abs(const T& value) { if(value < 0) { return -value; } return value; } template inline T lerp(S x, T begin, T end) // linear interpolation from begin to end by x { return x*(end - begin) + begin; } template inline T inverseLerp(T x, T begin, T end) // inverse of lerp: if lerp(z,begin,end) = x, then inverseLerp(x,begin,end) = z. // when begin=end, inverseLerp is underconstrained, so we define it to be 0. { return begin == end ? (ossim::isnan(x) ? x : T(0)) : (x - begin)/(end - begin); } template T quaderp(S x, T begin, T middle, T end) // quadratic interpolation through begin,middle,end by x { // newton interpolation const T a1 = S(2)*(middle - begin); const T a2 = S(2)*(end - middle) - a1; return x*((x - S(0.5))*a2 + a1) + begin; } template inline T clamp(T x, T a, T b) // clamp x to [a, b] { ossimREQUIRE(a <= b); // input must make sense, disallow nans if (ossim::isnan(x)) return x; if (x < a) return a; if (b < x) return b; return x; } template T wrap(T x, T a, T b) // wrap x modularly into [a,b) { ossimREQUIRE(a <= b); // input must make sense, disallow nans if (a == b && !ossim::isnan(x)) return a; else { T z = x < a ? b : a; return std::fmod(x - z, b - a) + z; } } // XXX to Garrett from PJM: // min and max routines. std::min/max do not in fact correctly handle nan. // this is troublesome, i think my code always was asserting no nans before values got // through std::min/std::max. i agree with you that if any of the input is nan, // then the result should be nan, but the STL doesn't really consider the possibility // that inputs to min/max have a "strange" ordering to them. we could overload // std::min/max to do this behavior but that's evil. for all my whining, i think // we should have ossim::max/max that do the right thing wrt nan. however: // if we "correctly" handle nans like this, does that subtly break any existing code? template inline T min(T a, T b) // min of a,b; nan if either a or b are nan { return (a < b) ? a : b; } template <> inline ossim_float32 min(ossim_float32 a, ossim_float32 b) { if (ossim::isnan(a)||ossim::isnan(b)) { return ossim::nan(); } else { return (a < b) ? a : b; } } template <> inline ossim_float64 min(ossim_float64 a, ossim_float64 b) { if (ossim::isnan(a)||ossim::isnan(b)) { return ossim::nan(); } else { return (a < b) ? a : b; } } template inline T max(T a, T b) // max of a,b; nan if either a or b are nan { return (a < b) ? b : a; } template <> inline ossim_float32 max(ossim_float32 a, ossim_float32 b) { if (ossim::isnan(b)) return b; else return (a < b) ? b : a; } template <> inline ossim_float64 max(ossim_float64 a, ossim_float64 b) { if (ossim::isnan(b)) return b; else return (a < b) ? b : a; } inline double radiansToDegrees(double x) { return x*DEG_PER_RAD;} inline double degreesToRadians(double x) { return x*RAD_PER_DEG;} inline double cosd(double x) { return std::cos(x*RAD_PER_DEG); } inline double sind(double x) { return std::sin(x*RAD_PER_DEG); } inline double tand(double x) { return std::tan(x*RAD_PER_DEG); } // trig fncs with parameter in degrees inline double acosd(double x) { return DEG_PER_RAD*std::acos(x); } inline double asind(double x) { return DEG_PER_RAD*std::asin(x); } inline double atand(double x) { return DEG_PER_RAD*std::atan(x); } inline double atan2d(double y, double x) { return DEG_PER_RAD*std::atan2(y,x); } // trig fncs with result in degrees template IntType gcd(IntType n, IntType m) // greatest common divisor of two ints // NB: We use n and m as temporaries in this function, so there is no value // in using const IntType& as we would only need to make a copy anyway... { IntType zero(0); // Avoid repeated construction // This is abs() - given the existence of broken compilers with Koenig // lookup issues and other problems, I code this explicitly. (Remember, // IntType may be a user-defined type). if (n < zero) n = -n; if (m < zero) m = -m; // As n and m are now positive, we can be sure that %= returns a // positive value (the standard guarantees this for built-in types, // and we require it of user-defined types). for (;;) { if (m == zero) return n; n %= m; if (n == zero) return m; m %= n; } } template <> inline int gcd(int n, int m) // greatest common divisor specialize for int. // XXX this is the old gcd, the above code is the old ossimGcd(). // i made this a specialization of the template above, // is this really necessary or more efficient, or can we safely delete this specialization? // i don't know why this fnc must be decled inline, otherwise there's a compile error. // the simple test case doesn't have this problem. { if (m == 0) return n; else return gcd(m, n % m); // gcc can optimize tail calls right? } template IntType lcm(IntType n, IntType m) // least common multiple // NB: We use n and m as temporaries in this function, so there is no value // in using const IntType& as we would only need to make a copy anyway... { IntType zero(0); // Avoid repeated construction if (n == zero || m == zero) { return zero; } else { n /= gcd(n, m); n *= m; if (n < zero) n = -n; return n; } } template inline T square(T x) { return x*x; } // identical to copysign() but usable in templates template inline T sgn(T x) // signum function, returns 0, 1, -1, or nan { const T table[] = {T(0), T(1), T(-1)}; return table[((x < T(0)) << 1) | (x > T(0))]; } template <> inline ossim_float32 sgn(ossim_float32 x) // signum function, returns 0, 1, -1, or nan { const ossim_float32 table[] = {ossim_float32(0), ossim_float32(1), ossim_float32(-1)}; return ossim::isnan(x) ? x : table[((x < ossim_float32(0)) << 1) | (x > ossim_float32(0))]; } template <> inline ossim_float64 sgn(ossim_float64 x) // signum function, returns 0, 1, -1, or nan { const ossim_float64 table[] = {ossim_float64(0), ossim_float64(1), ossim_float64(-1)}; return ossim::isnan(x) ? x : table[((x < ossim_float64(0)) << 1) | (x > ossim_float64(0))]; } template inline R round(F x) // correctly round a float, and cast to desired type R { R result = static_cast((x < F(0)) ? std::ceil(x - F(0.5)) : std::floor(x + F(0.5))); ossimENSURE(ossim::isnan(x) == ossim::isnan(result)); // if x is nan, R must be a float type return result; // XXX is this better than use of ceil/floor?: return static_cast((x < T(0)) ? x - T(0.5) : x + T(0.5)); } inline double ft2mtrs(double feet) { return (feet * MTRS_PER_FT); } inline double usft2mtrs(double feet) { return (feet * US_METERS_PER_FT); } inline double mtrs2ft(double meters) { return (meters / MTRS_PER_FT); } inline double mtrs2usft(double meters) { return (meters / US_METERS_PER_FT); } // Common conversion functions template std::pair quadraticRoots(T a, T b, T c) // evaluates quadradic formula (positive sqrt is first) { // XXX could suffer from catastrophic cancellation, // see David Goldberg's "What Every Computer Scientist Should Know About Floating-Point Arithmetic" T s = std::sqrt(b*b - T(4)*a*c); T twoA = T(2)*a; return std::pair((-b + s)/twoA, (-b - s)/twoA); } template inline void memClear(T& var, int z = 0) // zero out a variable's memory (for a given value of zero) { memset(&var, z, sizeof(T)); } template inline void memClear(T* var) // prevent user from accidentally passing in a pointer to his struct { ossimSTATIC_CHECK(false, YOU_PROBABLY_WANT_TO_MEMCLEAR_WHAT_THE_POINTER_POINTS_TO_NOT_THE_POINTER_ITSELF); } OSSIM_DLL ossimByteOrder byteOrder(); // test endianness of current machine // values for various scalar types OSSIM_DLL double defaultMin(ossimScalarType scalarType); OSSIM_DLL double defaultMax(ossimScalarType scalarType); OSSIM_DLL double defaultNull(ossimScalarType scalarType); OSSIM_DLL ossim_uint32 scalarSizeInBytes(ossimScalarType scalarType); /** @brief @return true if scalar type is signed, false if not. */ OSSIM_DLL bool isInteger(ossimScalarType scalarType); /** @brief @return true if scalar type is signed, false if not. */ OSSIM_DLL bool isSigned(ossimScalarType scalarType); /** * @brief Get actual bits per pixel for a given scalar type. * * This is bits used. (OSSIM_USHORT11 = 11) * * @returns The actual bits per pixel. This will return 0 if the * input connection is not hooked up or there is an unhandled scalar type. */ OSSIM_DLL ossim_uint32 getActualBitsPerPixel(ossimScalarType scalarType); /** * @brief Get bits per pixel for a given scalar type. * * This the total bits per pixel. (OSSIM_USHORT11 = 16) * * @returns The bits per pixel. This will return 0 if the * input connection is not hooked up or there is an unhandled scalar type. */ OSSIM_DLL ossim_uint32 getBitsPerPixel(ossimScalarType scalarType); OSSIM_DLL void defaultTileSize(ossimIpt& tileSize); OSSIM_DLL std::string convertHtmlSpecialCharactersToNormalCharacter(const std::string& src); /** Heading pitch roll extraction from a matrix. */ OSSIM_DLL bool matrixToHpr( ossim_float64 hpr[3], const NEWMAT::Matrix& rotation ); /** Heading pitch roll extraction from a matrix. */ OSSIM_DLL bool matrixToHpr( ossim_float64 hpr[3], const NEWMAT::Matrix& lsrMatrix, const NEWMAT::Matrix& rotationalMatrix); OSSIM_DLL void lexQuotedTokens(const std::string& str, ossim_uint32 start, const char* whitespace, const char* quotes, std::vector& tokens, bool& unbalancedQuotes); /** * Will take a vector of ossimDpt and convert to a string list separated by spaces * For example: * (45,34) (12,34) */ OSSIM_DLL void toStringList(ossimString& resultStringOfPoints, const std::vector& pointList, char separator=' '); OSSIM_DLL void toStringList(ossimString& resultStringOfPoints, const std::vector& pointList, char separator = ' '); OSSIM_DLL void toStringList(ossimString& resultStringOfPoints, const std::vector& pointList, char seaprator = ' '); /** * Will take a string list separated by spaces and convert to a vector of ossimDpts. It will not clear * the passed in list but will append all points found. */ OSSIM_DLL void toVector(std::vector& result, const ossimString& stringOfPoints); OSSIM_DLL void toVector(std::vector& result, const ossimString& stringOfPoints); OSSIM_DLL void toVector(std::vector& result, const ossimString& stringOfPoints); /** * This will output a vector of values inst a string * * (value1,...,valueN) * * Parenthesis are required */ template void toSimpleStringList(ossimString& result, const std::vector& valuesList) { std::ostringstream out; if(!valuesList.empty()) { ossim_uint32 idx = 0; ossim_uint32 size = (ossim_uint32) (valuesList.size()-1); for(idx = 0; idx < size; ++idx) { out << valuesList[idx] << ","; } out << valuesList[size]; } result = "("+out.str()+")"; } /** * This will output a vector of values inst a string * * (value1,...,valueN) * * Specialize the char for it will output the actual ascii char instead of the numeric value * * Parenthesis are required */ template <> OSSIM_DLL void toSimpleStringList(ossimString& result, const std::vector& valuesList); template <> OSSIM_DLL void toSimpleStringList(ossimString& result, const std::vector& valuesList); template <> OSSIM_DLL void toSimpleStringList(ossimString& result, const std::vector& valuesList); template <> OSSIM_DLL void toSimpleStringList(ossimString& result, const std::vector& valuesList); /** * Generic function to extract a list of values into a vector of string where * the string of points is of the form: * * (value1,value2, ... , ) * * Parenthesis are required */ OSSIM_DLL bool extractSimpleValues(std::vector& values, const ossimString& stringOfPoints); template bool toSimpleVector(std::vector& result, const ossimString& stringOfPoints) { std::istringstream in(stringOfPoints); ossim::skipws(in); bool returnValue = true; char c = in.get(); ossimString value = ""; if(c == '(') { c = (char)in.get(); while( (c!=')') && (c!= '\n') && (in.good()) ) { if(c!= ',') { value += ossimString(c); } else { result.push_back(static_cast(value.toDouble())); value = ""; } c = in.get(); } } if(c!= ')') { returnValue = false; } else { if(!value.empty()) { result.push_back(static_cast(value.toDouble())); } } return returnValue; } /** * Takes input format of the form: * (value1,value2,...,valueN) */ OSSIM_DLL bool toSimpleVector(std::vector& result, const ossimString& stringOfPoints); /** * Takes input format of the form: * (value1,value2,...,valueN) */ OSSIM_DLL bool toSimpleVector(std::vector& result, const ossimString& stringOfPoints); /** * Takes input format of the form: * (value1,value2,...,valueN) */ OSSIM_DLL bool toSimpleVector(std::vector& result, const ossimString& stringOfPoints); /** * Takes input format of the form: * (value1,value2,...,valueN) */ OSSIM_DLL bool toSimpleVector(std::vector& result, const ossimString& stringOfPoints); /** * Takes input format of the form: * (value1,value2,...,valueN) */ OSSIM_DLL bool toSimpleVector(std::vector& result, const ossimString& stringOfPoints); /** * Takes input format of the form: * (value1,value2,...,valueN) */ OSSIM_DLL bool toSimpleVector(std::vector& result, const ossimString& stringOfPoints); /** * Takes input format of the form: * (value1,value2,...,valueN) */ OSSIM_DLL bool toSimpleVector(std::vector& result, const ossimString& stringOfStrings); // lex str into tokens starting at position start using whitespace // chars as delimiters and quotes[0] and quotes[1] as the opening // and closing quotation chars (for quoting tokens containing whitespace). // unbalancedQuotes is true iff it aborted when detecting unbalanced quoting. // REQUIRE(whitespace != NULL); // REQUIRE(quotes != NULL); // REQUIRE(tokens != NULL); // REQUIRE(unbalancedQuotes != NULL); /** * @brief Get the number threads to use from ossimPreferences or ossim::Thread. * * Keyword searched for is: "ossim_threads" * * If keyword is not found ossim::Thread::getNumberOfProcessors() is used. * * @return Number of threads. Default=1 */ OSSIM_DLL ossim_uint32 getNumberOfThreads(); /** * @brief Gets the current time. * * Example formats and output: * format = "%Y-%m-%dT%H:%M:%SZ" output = "2014-03-06T13:55:10Z" * * @param format E.g. "%Y-%m-%dT%H:%M:%SZ" * * @param gmtFlag If true get the zulu time; else, gets the local time. * * @param result Initialized by this with result. * * E.g. "2014-03-06T13:55:10Z" * * @note If an error occurs result will be empty. */ OSSIM_DLL void getFormattedTime( const std::string& format, bool gmtFlag, std::string& result ); /** * @brief Gets the current time. * * Wrapper around time.h time_t time(time_t *t) with a mutex lock. * * Note that time_t is a long int. Returning ossim_int64 to avoid include * of time.h. * * @return The time as the number of seconds since the Epoch, * 1970-01-01 00:00:00 +0000 (UTC). */ OSSIM_DLL ossim_int64 getTime(); /** * @brief Computes the number of decimation levels to get to the overview * stop dimension. * * This uses ossim preferences "overview_stop_dimension" value if set else * it uses the default tile size to compute the number of levels. * * @param rect The rectangle of the first level. * * @return The number of decimation levels needed. */ OSSIM_DLL ossim_uint32 computeLevels(const ossimIrect& rect); /** * @brief Convenience method to get histogram bin infomation. * * Typically band 0 is used as input from the image source and it's assumed * all bands have the same min, max, null values. In most cases the number * of bins is (maxValue-minValue)+1. Exceptions being: * * OSSIM_SINT16: * Min is adjusted for DTED and SRTM to be -32766 instead of -32767. * This is because of DTED which has a null of -32767 and SRTM has * a null of -32768. * OSSIM_SINT32, OSSIM_UINT32, and all float data: * Number of bins is defaulted to: 32768 * * @param imageSource * @param band Band to use from imageSource. * @param numberOfBins Initialized by this. * @param minValue Initialized by this. * @param maxValue Initialized by this. * @param nullValue Initialized by this. * @return true on success, false on error. */ bool getBinInformation( const ossimImageSource* imageSource, ossim_uint32 band, ossim_uint32& numberOfBins, ossim_float32& minValue, ossim_float32& maxValue, ossim_float32& nullValue ); } // End: namespace ossim #endif /* #ifndef ossimCommon_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimConnectableContainer.h000066400000000000000000000213031352751253100247050ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimConnectableContainer.h 20316 2011-12-02 15:56:38Z oscarkramer $ #ifndef ossimConnectableContainer_HEADER #define ossimConnectableContainer_HEADER #include #include #include #include #include class OSSIMDLLEXPORT ossimConnectableContainerChildListener; class OSSIMDLLEXPORT ossimConnectableContainer : public ossimConnectableObject, public ossimConnectableContainerInterface, public ossimConnectableObjectListener { public: typedef std::map > connectablObjectMapType; ossimConnectableContainer(ossimConnectableObject* owner=0); virtual ossimObject* getObject(); virtual const ossimObject* getObject()const; /** * @param index Index of object to get. * * @see getNumberOfObjects(false) to get the number of objects inside * the container. * * @return Container's object at that index or NULL if out of range. * * @note This does not recurse into other containers. */ virtual ossimConnectableObject* getConnectableObject(ossim_uint32 index); /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimTypeNameVisitor visitor("", false, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimCollectionVisitor::List& collection = visitor.getObjects();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject::ConnectableObjectList findAllObjectsOfType(const RTTItypeid& typeInfo, bool recurse=true)); /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimConnectableTypeIdVisitor visitor(typeId, false, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimConnectableCollectionVisitor::List& collection = visitor.getObjects();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject::ConnectableObjectList findAllObjectsOfType(const ossimString& className, bool recurse=true)); /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimTypeIdVisitor visitor(typeId, true, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr obj = visitor.getObject();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findFirstObjectOfType(const RTTItypeid& typeInfo, bool recurse=true)); /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimTypeNameVisitor visitor(className, true, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr obj = visitor.getObject();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findFirstObjectOfType(const ossimString& className, bool recurse=true)); /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimIdVisitor visitor(id, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr obj = visitor.object();
    * 
*/ OSSIM_DEPRECATE_METHOD(ossimConnectableObject* findObject(const ossimId& id, bool recurse=true)); /** * Please use the new ossimVisitor design pattern to visit objects in the container. */ OSSIM_DEPRECATE_METHOD(ossimConnectableObject* findObject(const ossimConnectableObject* obj, bool recurse=true)); /*! * Will cycle through all sources setting their ids. the idLast wlil be * updated * so we can recurse into other containers. */ void makeUniqueIds(); /*! * Returns the number of objects within this container and all child * containers. */ ossim_uint32 getNumberOfObjects(bool recurse=true)const; /*! * Will add an object to the container and then set the added objects owner * to this. */ virtual bool addChild(ossimConnectableObject* attachableObject); virtual bool removeChild(ossimConnectableObject* object); virtual bool canConnectMyInputTo(ossim_int32 index, const ossimConnectableObject* obj) const; virtual bool canConnectMyOutputTo(ossim_int32 index, const ossimConnectableObject* obj) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; //____________________PLACE ALL EVENT HANDLING STUFF HERE_____________ // virtual void objectDestructingEvent(ossimObjectDestructingEvent& event); // virtual void propertyEvent(ossimPropertyEvent& event); // virtual void disconnectInputEvent(ossimConnectionEvent& event); // virtual void connectInputEvent(ossimConnectionEvent& event); // virtual void disconnectOutputEvent(ossimConnectionEvent& event); // virtual void connectOutputEvent(ossimConnectionEvent& event); virtual void getChildren(std::vector& children, bool immediateChildrenOnlyFlag); void deleteAllChildren(); virtual void accept(ossimVisitor& visitor); // void propagateEventToOutputs(ossimEvent& event, // ossimConnectableObject* start); // void propagateEventToInputs(ossimEvent& event, // ossimConnectableObject* start); /*! * Inserts all of this object's children and inputs into the container provided. Since this is * itself a container, this method will consolidate this with the argument container. * Consequently, this object will not be represented in the argument container but its children * will be. Ownership of children will pass to the argument container. * @return Returns TRUE if successful. */ virtual bool fillContainer(ossimConnectableContainer& container); protected: virtual ~ossimConnectableContainer(); ossimConnectableContainer(const ossimConnectableContainer& rhs); void removeAllListeners(); bool addAllObjects(std::map >& idMapping, const ossimKeywordlist& kwl, const char* prefix); bool connectAllObjects(const std::map >& idMapping); void findInputConnectionIds(std::vector& result, const ossimKeywordlist& kwl, const char* prefix); /*! * Every object added must have a unique id. We will sort them in a easy to * query form. Since the container can have hundreds of objects we will use a * more efficient map that allows us to do binary searches of the objects. * * map The key will be the objectsUnique id and the value * is a pointer to the attachable object. */ connectablObjectMapType theObjectMap; ossimConnectableContainerChildListener* theChildListener; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimConnectableContainerInterface.h000066400000000000000000000106201352751253100265260ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: A brief description of the contents of the file. // //************************************************************************* // $Id: ossimConnectableContainerInterface.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimConnectableContainerInterface_HEADER #define ossimConnectableContainerInterface_HEADER #include #include #include #include #include class ossimString; class OSSIMDLLEXPORT ossimConnectableContainerInterface { public: ossimConnectableContainerInterface(ossimObject* obj):theBaseObject(obj){} virtual ~ossimConnectableContainerInterface(){theBaseObject=NULL;} /*! * Will find all objects of the past in type. Use the RTTI type info. An optional * recurse flag will say if there is another container then recurse it to * find the type you are looking for else it just looks within its immediate * children * * Example: passing STATIC_TYPE_INFO(ossimImageRenderer) as an argument will * look for all ossimImageRenderer's and return the list. */ virtual ossimConnectableObject::ConnectableObjectList findAllObjectsOfType(const RTTItypeid& typeInfo, bool recurse=true)=0; virtual ossimConnectableObject::ConnectableObjectList findAllObjectsOfType(const ossimString& className, bool recurse=true)=0; /*! * Will find the firt object of the past in type. Use the RTTI type info.An optional * recurse flag will say if there is another container then recurse it to * find the type you are looking for else it just looks within its immediate * children * * Example: passing STATIC_TYPE_INFO(ossimImageRenderer) as an argument will * look for the first ossimImageRenderer and return that object. */ virtual ossimConnectableObject* findFirstObjectOfType(const RTTItypeid& typeInfo, bool recurse=true)=0; virtual ossimConnectableObject* findFirstObjectOfType(const ossimString& className, bool recurse=true)=0; /*! * will search for the object given an id. If recurse is true it will recurse * to other containers. */ virtual ossimConnectableObject* findObject(const ossimId& id, bool recurse=true)=0; virtual ossimConnectableObject* findObject(const ossimConnectableObject* obj, bool recurse=true)=0; /*! * Will cycle through all sources setting their ids. the idLast wlil be updated * so we can recurse into other containers. */ virtual void makeUniqueIds()=0; /*! * Returns the number of objects within this container and all child containers. */ virtual ossim_uint32 getNumberOfObjects(bool recurse=true)const=0; /*! * Will add an object to the container and then set the added objects owner * to this. */ virtual bool addChild(ossimConnectableObject* attachableObject)=0; /*! * Will remove the child from the container. Changes the owner of the * child to be NULL; */ virtual bool removeChild(ossimConnectableObject* object)=0; /*! * Gives access to the this point of the base object that everyone derives * from. */ ossimObject* getObject(){return theBaseObject;} const ossimObject* getObject()const{return theBaseObject;} /** * @param index Index of object to get. * * @see getNumberOfObjects(false) to get the number of objects inside * the container. * * @return Container's object at that index or NULL if out of range. * * @note This does not recurse into other containers. */ virtual ossimConnectableObject* getConnectableObject(ossim_uint32 index)=0; void deleteAllChildren(); virtual void getChildren(std::vector& children, bool immediateChildrenOnlyFlag)=0; protected: ossimObject* theBaseObject; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimConnectableDisplayListener.h000066400000000000000000000067361352751253100261130ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2004, David Burken, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: ossimConnectableDisplayListener // // This class is intended for connectable displays that wants to be a // ossimConnectableObjectListener and a ossimDisplayEventListener to avoid // a triangle inheritance. // //---------------------------------------------------------------------------- // $Id: ossimConnectableDisplayListener.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimConnectableDisplayListener_HEADER #define ossimConnectableDisplayListener_HEADER #include class ossimConnectionEvent; class ossimObjectDestructingEvent; class ossimPropertyEvent; class ossimContainerEvent; class oossimDisplayListEvent; class ossimRefreshEvent; class ossimDisplayListEvent; class ossimDisplayRefreshEvent; /** * This class is intended for connectable displays that wants to be a * ossimConnectableObjectListener and a ossimDisplayEventListener to avoid * a triangle inheritance. */ class OSSIMDLLEXPORT ossimConnectableDisplayListener : public ossimListener { public: /** default constructor */ ossimConnectableDisplayListener(); /** * Method called by listener managers. This will in turn call the correct * xxxEvent method. * * @param event Event to handle. */ virtual void processEvent(ossimEvent& event); /** @param event Event to handle signifying an object destroying. */ virtual void objectDestructingEvent(ossimObjectDestructingEvent& event); /** @param event Event to handle signifying an object connecting. */ virtual void connectionEvent(ossimConnectionEvent& event); /** @param event Event to handle signifying a disconnect input event. */ virtual void disconnectInputEvent(ossimConnectionEvent& event); /** @param event Event to handle signifying an output disconnect event. */ virtual void disconnectOutputEvent(ossimConnectionEvent& event); /** @param event Event to handle signifying a connect input event. */ virtual void connectInputEvent(ossimConnectionEvent& event); /** @param event Event to handle signifying a connect output event. */ virtual void connectOutputEvent(ossimConnectionEvent& event); /** * @param event Event to handle signifying a property has changed event. */ virtual void propertyEvent(ossimPropertyEvent& event); /** * @param event Event to handle signifying a dislay list has changed * event. */ virtual void displayListEvent(ossimDisplayListEvent&); /** * @param event Event to handle signifying a dislay refresh * is needed. */ virtual void displayRefreshEvent(ossimDisplayRefreshEvent&); /** * @param event Event to handle signifying a refresh is needed. */ virtual void refreshEvent(ossimRefreshEvent& event); /** * Container Events: * Typically isued by objects that contain children. If anyone is * interested, can latch on to this event. Other objects within the * system might be interest in this event even */ /** @param event Event signifying an object was added to a container. */ virtual void addObjectEvent(ossimContainerEvent& event); /** @param event Event signifying an object was removed from a container. */ virtual void removeObjectEvent(ossimContainerEvent& event); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimConnectableObject.h000066400000000000000000000517101352751253100241760ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class declaration for ossimConnectableObject the base class for // all connectable objects. // //************************************************************************* // $Id$ #ifndef ossimConnectableObject_HEADER #define ossimConnectableObject_HEADER 1 #include #include #include #include #include #include #include class ossimVisitor; class ossimConnectableContainer; class OSSIMDLLEXPORT ossimConnectableObject : public ossimObject, public ossimListenerManager, public ossimPropertyInterface { public: typedef std::vector > ConnectableObjectList; enum ossimConnectableObjectDirectionType { CONNECTABLE_DIRECTION_NONE = 0, CONNECTABLE_DIRECTION_INPUT = 1, CONNECTABLE_DIRECTION_OUTPUT = 2 }; /** * Base constructor of this object. */ ossimConnectableObject(ossimObject* owner=0); ossimConnectableObject(ossimObject* owner, ossim_int32 inputListSize, ossim_int32 outputListSize, bool inputListIsFixedFlag=true, bool outputListIsFixedFlag=true); virtual ~ossimConnectableObject(); /** * All connectable objects will have id's. This allows us to * set the id of this object. */ void setId(const ossimId& id); /** * Will allow us to get this object's id. */ const ossimId& getId()const; /** * Fetches the current owner, most likely a container but not limited to one. */ const ossimObject* getOwner() const; /** * Permits changing the object's owner. */ virtual void changeOwner(ossimObject* owner); virtual void setDescription(const ossimString& description); virtual ossimString getDescription()const; /** * will check the direction specified to see if all slots are full. * If any slot is null then false is returned. * If a filter requires options testing they * need to override this method. The argument can be ored together. If you * want both checked then pass * CONNECTABLE_DIRECTION_INPUT | CONNECTABLE_DIRECTION_OUTPUT */ virtual bool isConnected( ossimConnectableObjectDirectionType direction = CONNECTABLE_DIRECTION_INPUT)const; /*! * These methods are now deprecated. You can achieve the same thing by * using the new visitor design pattern. If this does not achieve exactly * what you want then you can derive new rules by overriding the virtual * visit method in ossimVisitor * *
    *    ossimIdVisitor visitor(id, false, ossimVisitor::VISIT_CHILDREN |
    *    ossimVisitor::VISIT_INPUTS);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr object = visitor.getObject();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findConnectableObject( const ossimId& id)); /*! * These methods are now deprecated. You can achieve the same thing by * using the new visitor design pattern. If this does not achieve exactly * what you want then you can derive new rules by overriding the virtual * visit method in ossimVisitor * *
    *    ossimTypeIdVisitor visitor(typeId, true, ossimVisitor::VISIT_CHILDREN |
    *    ossimVisitor::VISIT_INPUTS);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr object = visitor.getObject();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findObjectOfType( RTTItypeid typeId, ossimConnectableObjectDirectionType directionType, bool recurse = true)); /*! * These methods are now deprecated. You can achieve the same thing by * using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding * the virtual visit method in ossimVisitor * *
    *    ossimTypeNameVisitor visitor(typeName, true,
    *    ossimVisitor::VISIT_CHILDREN | ossimVisitor::VISIT_INPUTS);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr object = visitor.getObject();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findObjectOfType( const ossimString& obj, ossimConnectableObjectDirectionType directionType, bool recurse = true)); /*! * These methods are now deprecated. You can achieve the same thing by * using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding * the virtual visit method in ossimVisitor * *
    *    ossimTypeNameVisitor visitor(typeName, true,
    *    ossimVisitor::VISIT_CHILDREN | ossimVisitor::VISIT_INPUTS);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr object = visitor.getObject();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findInputObjectOfType( const ossimString& className)); /** * Return a valid index of the input list if the passed in object * is found else return -1. */ virtual ossim_int32 findInputIndex(const ossimConnectableObject* object); /** * Return a valid index of the input list if the passed id * is found else return -1. */ virtual ossim_int32 findInputIndex(const ossimId& id); /** * Return a valid index of the output list if the passed in object * is found else return -1. */ virtual ossim_int32 findOutputIndex(const ossimConnectableObject* object); /** * Return a valid index of the output list if the passed in object * is found else return -1. */ virtual ossim_int32 findOutputIndex(const ossimId& id); /** * Should return the first available index to connect to. The * connectMyInputTo that just takes another ossimConnectableObject as input * and not an index will call this method. By default this method will find * the first open slot (not null) or append o the list if it's dynamic. If * the list is dynamic it calls conConnectMyInputTo(index, object) on an * index = to listSize. */ virtual ossim_int32 getMyInputIndexToConnectTo( ossimConnectableObject* object)const; /** * Should return the first available index to connect to. The * connectMyOutputTo that just takes another ossimConnectableObject as input\ * and not an index will call this method. By default this method will find * the first open slot (not null) or append to the list if it's dynamic. If * the list is dynamic it calls canConnectMyOutputTo(index, object) on an * index = to listSize. */ virtual ossim_int32 getMyOutputIndexToConnectTo( ossimConnectableObject* object)const; /** * required to be overriden by derived classes */ virtual bool canConnectMyInputTo( ossim_int32 myInputIndex, const ossimConnectableObject* object)const=0; /** * default implementation is to allow anyone to connect to us. */ virtual bool canConnectMyOutputTo(ossim_int32 myOutputIndex, const ossimConnectableObject* object)const; /** * Will disconnect the object passed in. */ virtual void disconnect(ossimConnectableObject* object=0); /** * Will disconnect the object passed in. */ virtual void disconnect(const ossimId& id); /** * Will disconnect the object at the given input index and generate * a connection event. */ virtual ossimRefPtr disconnectMyInput( ossim_int32 inputIndex, bool disconnectOutputFlag=true, bool createEventFlag = true); /** * Finds the index of the passed in input and calls * disconnectMyInput(inputIndex, disconnectOutputFlag, createEventFlag); */ virtual void disconnectMyInput(ossimConnectableObject* input, bool disconnectOutputFlag=true, bool createEventFlag = true); /** * */ virtual void disconnectMyInputs( ConnectableObjectList& inputList, bool disconnectOutputFlag=true, bool createEventFlag=true); /** * Will disconnect the object at the given output index and generate * a connection event. If there is no object at that index then no * event is generated and NULL is returned. The disconnectOutputFlag * says do you want this method to disconnect the output pointer to * this object. */ virtual ossimRefPtr disconnectMyOutput( ossim_int32 outputIndex, bool disconnectInputFlag=true, bool createEventFlag = true); /** * Will disconnect the output object. It will get the index of * the object and call disconnectMyOutput(index, disconnectOutputFlag). */ virtual void disconnectMyOutput(ossimConnectableObject* output, bool disconnectInputFlag=true, bool createEventFlag=true); virtual void disconnectMyOutputs( ConnectableObjectList& outputList, bool disconnectOutputFlag=true, bool createEventFlag=true); /** * Will disconnect all of the input objects. */ virtual void disconnectAllInputs(); /** * Will disconnect all of the output objects. */ virtual void disconnectAllOutputs(); /** * Will try to connect this objects input to the passed in object. * It will return a valid index >= 0 if successful. Will use the * getMyInputIndexToConnectTo method to implement the connection */ virtual ossim_int32 connectMyInputTo(ossimConnectableObject* inputObject, bool makeOutputConnection=true, bool createEventFlag=true); /** * Will connect the specified input to the passed in object */ virtual ossim_int32 connectMyInputTo(ossim_int32 inputIndex, ossimConnectableObject* inputObject, bool makeOutputConnection=true, bool createEventFlag=true); virtual bool connectMyInputTo( ConnectableObjectList& inputList, bool makeOutputConnection=true, bool createEventFlag = true); /** * Will try to connect this objects output to the passed in object. * It will return a valid index >= 0 if successful. It will in turn call * the passed in objects connect input command if makeInputConnection * is set to true. * * Will use the getMyOutputIndexToConnectTo to implement this method */ virtual ossim_int32 connectMyOutputTo(ossimConnectableObject* outputObject, bool makeInputConnection=true, bool createEventFlag=true); virtual bool connectMyOutputTo( ConnectableObjectList& outputList, bool makeInputConnection=true, bool createEventFlag=true); /** * Will disconnect itself from all inputs and reset to the passed in * input list. It will return true if all objects were successfully * added. */ virtual bool connectInputList( ConnectableObjectList& inputList); /** * Will disconnect itself from all outputs and reset to the passed in * output list. It will return true if all objects were successfully * added. */ virtual bool connectOutputList( ConnectableObjectList& outputList); /** * Returns the number of input objects. */ virtual ossim_uint32 getNumberOfInputs()const; /** * Return the number of output objects */ virtual ossim_uint32 getNumberOfOutputs()const; /** * returns the object at the specified index. * if the index is not valid then NULL is * returned */ ossimConnectableObject* getInput(ossim_uint32 index=0); /** * returns the object at the specified index. * if the index is not valid then NULL is * returned */ const ossimConnectableObject* getInput(ossim_uint32 index=0)const; /** * returns the object at the specified index. * if the index is not valid then NULL is * returned */ ossimConnectableObject* getOutput(ossim_uint32 index=0); /** * returns the object at the specified index. * if the index is not valid then NULL is * returned */ const ossimConnectableObject* getOutput(ossim_uint32 index=0)const; /** * Will set the number of inputs. This will expand the list if the number * of inputs is larger than the current number of inputs. Will shrink * the list if the current number of inputs is larger than the passed in * inputs. */ virtual void setNumberOfInputs(ossim_int32 numberOfInputs); virtual bool getInputListIsFixedFlag()const; virtual bool getOutputListIsFixedFlag()const; /** * Will set the number of outputs. This will expand the list if the * number of outputs is larger than the current number of outputs. * Will shrink the list if the current number of outputs is larger than * the passed in outputs. */ virtual void setNumberOfOutputs(ossim_int32 numberOfInputs); const ConnectableObjectList& getInputList()const; const ConnectableObjectList& getOutputList()const; ConnectableObjectList& getInputList(); ConnectableObjectList& getOutputList(); /*! * These methods are now deprecated. You can achieve the same thing by * using the new visitor design pattern. If this does not achieve exactly * what you want then you can derive new rules by overriding the virtual * visit method in ossimVisitor * *
    *    ossimTypeNameVisitor visitor("",
    *    false, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimCollectionVisitor::List& collection = visitor.getObjects();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual void findAllObjectsOfType( ConnectableObjectList& result, const RTTItypeid& typeInfo, bool recurse=true) ); /*! * These methods are now deprecated. You can achieve the same thing by * using the new visitor design pattern. If this does not achieve exactly * what you want then you can derive new rules by overriding the virtual * visit method in ossimVisitor * *
    *    ossimTypeNameVisitor visitor("", false,
    *    ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimCollectionVisitor::List& collection = visitor.getObjects();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual void findAllObjectsOfType( ConnectableObjectList& result, const ossimString& className, bool recurse=true)); #if 0 /* Deprecated code. Left here until thoroughly debugged. (drb) */ /*! * These methods are now deprecated. You can achieve the same thing by * using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding * the virtual visit method in ossimVisitor * *
    *    ossimTypeIdVisitor visitor(, false,
    *    ossimVisitor::VISIT_CHILDREN | ossimVisitor::VISIT_INPUTS);
    *    connectableObject->accept(visitor);
    *    ossimCollectionVisitor::List& collection = visitor.getObjects();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual void findAllInputsOfType( ConnectableObjectList& result, const RTTItypeid& typeInfo, bool propagateToInputs=true, bool recurseChildren=false)); /*! * These methods are now deprecated. You can achieve the same thing by * using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding * the virtual visit method in ossimVisitor * *
    *    ossimTypeNameVisitor visitor("",
    *    false, ossimVisitor::VISIT_CHILDREN | ossimVisitor::VISIT_INPUTS);
    *    connectableObject->accept(visitor);
    *    ossimCollectionVisitor::List& collection = visitor.getObjects();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual void findAllInputsOfType( ConnectableObjectList& result, const ossimString& className, bool propagateToInputs=true, bool recurseChildren=false)); #endif /* deprecated code. (drb) */ virtual void propagateEventToOutputs(ossimEvent& event); virtual void propagateEventToInputs(ossimEvent& event); /* ------------------- PROPERTY INTERFACE -------------------- */ virtual void setProperty(ossimRefPtr property); virtual void setProperty(const ossimString& name, const ossimString& value); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /* ------------------ PROPERTY INTERFACE END ------------------- */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; /** * Save the state of all inputs to a keyword list. This will do a * recursive call through all inputs and save their state to a * keyword list. * * @param kwl Keyword list to save state to. * * @param saveThisStateFlag If the true the state of this object will be * saved as well as all inputs. Default = true. * * @param objectIndex Index to be used for prefix. So if * objectIndex = 1, the first object will have a prefix of: "object1." * Default = 1. * * @param prefix Prefix to tack onto keyword. If prefix = "myChain." and * objectIndex = 1, then the first keyword would be * "myChain.object1.some_keyword". * * @return Returns the next object index. This is the last index used * plus one. Used internally to keep track of index to use for prefix. */ virtual ossim_uint32 saveStateOfAllInputs(ossimKeywordlist& kwl, bool saveThisStateFlag=true, ossim_uint32 objectIndex=1, const char* prefix=0) const; /** * Inserts this object and all of its children and inputs into the container * provided. * @return Returns TRUE if successful. */ virtual bool fillContainer(ossimConnectableContainer& container); /** * Moves the input connection matching id up one in the connection list. * @param id The id to move. * @return true if action was performed, false if not. */ bool moveInputUp(const ossimId& id); /** * Moves the input connection matching id down one in the connection list. * @param id The id to move. * @return true if action was performed, false if not. */ bool moveInputDown(const ossimId& id); /** * Moves the input connection matching id to the top of the connection list. * @param id The id to move. * @return true if action was performed, false if not. */ bool moveInputToTop(const ossimId& id); /** * Moves the input connection matching id to the bottom of the connection * list. * @param id The id to move. * @return true if action was performed, false if not. */ bool moveInputToBottom(const ossimId& id); /** * We will add a visitor interface for all connectable objects. */ virtual void accept(ossimVisitor& visitor); protected: ossimConnectableObject* findObjectOfType( ConnectableObjectList* connectableList, ossimVisitor& visitor ); ossimId theId; ossimString theDescription; ossimObject* theOwner; /** * Indicates whether the theInputObjectList is fixed */ bool theInputListIsFixedFlag; /** * Indicates whether the theOutputObjectList is fixed */ bool theOutputListIsFixedFlag; /** * Holds a list of input objects. */ ConnectableObjectList theInputObjectList; /** * Holds a list of output objects. */ ConnectableObjectList theOutputObjectList; private: TYPE_DATA }; #endif /* #ifndef ossimConnectableObject_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimConnectableObjectListener.h000066400000000000000000000037701352751253100257070ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: A brief description of the contents of the file. // // //************************************************************************* // $Id: ossimConnectableObjectListener.h 19962 2011-08-16 18:10:52Z gpotts $ #ifndef ossimConnectableObjectListener_HEADER #define ossimConnectableObjectListener_HEADER #include #include #include #include #include #include class OSSIMDLLEXPORT ossimConnectableObjectListener : public ossimListener { public: ossimConnectableObjectListener():ossimListener(){} virtual ~ossimConnectableObjectListener(){} virtual void processEvent(ossimEvent& event); virtual void objectDestructingEvent(ossimObjectDestructingEvent& /*event*/) {} virtual void connectionEvent(ossimConnectionEvent& /* event */) {} virtual void disconnectInputEvent(ossimConnectionEvent& /* event */) {} virtual void disconnectOutputEvent(ossimConnectionEvent& /* event */) {} virtual void connectInputEvent(ossimConnectionEvent& /* event */) {} virtual void connectOutputEvent(ossimConnectionEvent& /* event */) {} virtual void propertyEvent(ossimPropertyEvent& /* event */) {} /*! * Typically isued by objects that contain children. If anyone is * interested, can latch on to this event. Other objects within the * system might be interest in this event even */ virtual void addObjectEvent(ossimContainerEvent& /* event */) {} virtual void removeObjectEvent(ossimContainerEvent& /* event */) {} virtual void containerEvent(ossimContainerEvent& /* event */) {} virtual void refreshEvent(ossimRefreshEvent& /* event */) {} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimConnectionEvent.h000066400000000000000000000046301352751253100237320ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimConnectionEvent.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimConnectionEvent_HEADER #define ossimConnectionEvent_HEADER #include #include #include #include class OSSIMDLLEXPORT ossimConnectionEvent : public ossimEvent { public: enum ossimConnectionDirectionType { OSSIM_DIRECTION_UNKNOWN = 0, OSSIM_INPUT_DIRECTION = 1, OSSIM_OUTPUT_DIRECTION = 2, OSSIM_INPUT_OUTPUT_DIRECTION = 3 }; ossimConnectionEvent(ossimObject* object=NULL, long id=OSSIM_EVENT_NULL_ID); ossimConnectionEvent(ossimObject* object, long id, const ossimConnectableObject::ConnectableObjectList& newList, const ossimConnectableObject::ConnectableObjectList& oldList, ossimConnectionDirectionType whichDirection); ossimConnectionEvent(ossimObject* object, long id, ossimConnectableObject* newConnectableObject, ossimConnectableObject* oldConnectableObject, ossimConnectionDirectionType whichDirection); ossimConnectionEvent(const ossimConnectionEvent& rhs); ossimObject* dup()const; virtual void setDirection(ossimConnectionDirectionType direction); virtual ossimConnectionDirectionType getDirection()const; virtual ossim_uint32 getNumberOfNewObjects()const; virtual ossim_uint32 getNumberOfOldObjects()const; virtual ossimConnectableObject* getOldObject(ossim_uint32 i=0); virtual ossimConnectableObject* getNewObject(ossim_uint32 i=0); virtual bool isDisconnect()const; virtual bool isConnect()const; virtual bool isInputDirection()const; virtual bool isOutputDirection()const; protected: ossimConnectableObject::ConnectableObjectList theNewObjectList; ossimConnectableObject::ConnectableObjectList theOldObjectList; ossimConnectionDirectionType theDirectionType; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimConstants.h000066400000000000000000000463211352751253100226100ustar00rootroot00000000000000/******************************************************************** * * License: See top level LICENSE.txt file. * * Author: Ken Melero * * Description: Common file for global constants. * ************************************************************************** * $Id: ossimConstants.h 22476 2013-11-07 16:08:32Z dburken $ */ #ifndef ossimConstants_HEADER #define ossimConstants_HEADER 1 #include #ifdef __cplusplus # include #else # include #endif /** * WARNINGS SECTION: */ #ifdef _MSC_VER /* Quiet a bunch of MSVC warnings... */ # pragma warning(disable:4786) /* visual c6.0 compiler */ # pragma warning(disable:4251)/* for std:: member variable to have dll interface */ # pragma warning(disable:4275) /* for std:: base class to have dll interface */ # pragma warning(disable:4800) /* int forcing value to bool */ # pragma warning(disable:4244) /* conversion, possible loss of data */ #endif #if defined(__GNUC__) # define OSSIM_DEPRECATE_METHOD(func) func __attribute__ ((deprecated)) #elif defined(_MSC_VER) # define OSSIM_DEPRECATE_METHOD(func) __declspec(deprecated) func #else # define OSSIM_DEPRECATE_METHOD(func) #endif /** * DLL IMPORT/EXORT SECTION */ #if defined(OSSIM_STATIC) # define OSSIMEXPORT # define OSSIMIMPORT # define OSSIMDLLEXPORT # define OSSIM_DLL # define OSSIMDLLEXPORT_DATA(type) type # define OSSIM_DLL_DATA(type) type # define OSSIMDLLEXPORT_CTORFN #elif defined(__MINGW32__) || defined(__CYGWIN__) || defined(_MSC_VER) || defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__) # define OSSIMEXPORT __declspec(dllexport) # define OSSIMIMPORT __declspec(dllimport) # ifdef OSSIMMAKINGDLL # define OSSIMDLLEXPORT OSSIMEXPORT # define OSSIM_DLL OSSIMEXPORT # define OSSIMDLLEXPORT_DATA(type) OSSIMEXPORT type # define OSSIM_DLL_DATA(type) OSSIMEXPORT type # define OSSIMDLLEXPORT_CTORFN # else # define OSSIMDLLEXPORT OSSIMIMPORT # define OSSIM_DLL OSSIMIMPORT # define OSSIMDLLEXPORT_DATA(type) OSSIMIMPORT type # define OSSIM_DLL_DATA(type) OSSIMIMPORT type # define OSSIMDLLEXPORT_CTORFN # endif #else /* not #if defined(_MSC_VER) */ # define OSSIMEXPORT # define OSSIMIMPORT # define OSSIMDLLEXPORT # define OSSIM_DLL # define OSSIMDLLEXPORT_DATA(type) type # define OSSIM_DLL_DATA(type) type # define OSSIMDLLEXPORT_CTORFN #endif /* #if defined(_MSC_VER) */ /** * Previous DLL import export section. Commented out, but left just in case. */ #if 0 /* Comment out ALL this mess! */ #if defined(_MSC_VER) || defined(__VISUALC__) || defined(__BORLANDC__) || defined(__GNUC__) || defined(__WATCOMC__) # if (_MSC_VER >= 1300) /* MSVC .NET 2003 version */ # define OSSIMEXPORT __declspec(dllexport) # define OSSIMIMPORT __declspec(dllimport) # else # define OSSIMEXPORT __declspec(dllexport) # define OSSIMIMPORT __declspec(dllimport) # endif #else /* compiler doesn't support __declspec() */ # define OSSIMEXPORT # define OSSIMIMPORT #endif #if defined(__WXPM__) # if defined (__WATCOMC__) # define OSSIMEXPORT __declspec(dllexport) /* __declspec(dllimport) prepends __imp to imported symbols. We do NOT want that! */ # define OSSIMIMPORT # elif (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 ))) # define OSSIMEXPORT _Export # define OSSIMIMPORT _Export # endif #elif defined(__OSSIMMAC__) # ifdef __MWERKS__ # define OSSIMEXPORT __declspec(export) # define OSSIMIMPORT __declspec(import) # endif #endif #if defined(_MSC_VER) # pragma warning(disable:4786) /* visual c6.0 compiler */ # pragma warning(disable:4251) /* for std:: member variable to have dll interface */ # pragma warning(disable:4275) /* for std:: base class to have dll interface */ # pragma warning(disable:4800) /* int forcing value to bool */ # pragma warning(disable:4244) /* conversion, possible loss of data */ # ifdef OSSIMSINGLEDLL /* one gigantic dll, all declared export */ # ifdef EXPORT_OSMMATRIX # define EXPORT_OSMMATRIX OSSIMEXPORT # endif # ifndef OSSIMDLLEXPORT # define OSSIMDLLEXPORT OSSIMEXPORT # endif # ifdef EXPORT_OSMELEV # define EXPORT_OSMELEV OSSIMEXPORT # endif # ifdef EXPORT_OSMSPTDATA # define EXPORT_OSMSPTDATA OSSIMEXPORT # endif # ifdef EXPORT_ISO8211 # define EXPORT_ISO8211 OSSIMEXPORT # endif # ifdef EXPORT_OSMPROJ # define EXPORT_OSMPROJ OSSIMEXPORT # endif # ifndef EXPORT_OSMIMAGING # define EXPORT_OSMIMAGING OSSIMEXPORT # endif # else /* individual dlls, each with their own import/export symbols */ # ifndef EXPORT_OSMMATRIX # ifdef OSMMATRIX_EXPORTS # define EXPORT_OSMMATRIX OSSIMEXPORT # else # define EXPORT_OSMMATRIX OSSIMIMPORT # endif # endif # ifndef OSSIMDLLEXPORT # ifdef OSMBASE_EXPORTS # define OSSIMDLLEXPORT OSSIMEXPORT # else # define OSSIMDLLEXPORT OSSIMIMPORT # endif # endif # ifndef EXPORT_OSMELEV # ifdef OSMELEV_EXPORTS # define EXPORT_OSMELEV OSSIMEXPORT # else # define EXPORT_OSMELEV OSSIMIMPORT # endif # endif # ifndef EXPORT_OSMSPTDATA # ifdef OSMSPTDATA_EXPORTS # define EXPORT_OSMSPTDATA OSSIMEXPORT # else # define EXPORT_OSMSPTDATA OSSIMIMPORT # endif # endif # ifndef EXPORT_OSMPROJ # ifdef OSMPROJ_EXPORTS # define EXPORT_OSMPROJ OSSIMEXPORT # else # define EXPORT_OSMPROJ OSSIMIMPORT # endif # endif # ifndef EXPORT_ISO8211 # ifdef ISO8211_EXPORTS # define EXPORT_ISO8211 OSSIMEXPORT # else # define EXPORT_ISO8211 OSSIMIMPORT # endif # endif # ifndef EXPORT_OSMIMAGING # ifdef OSMIMAGING_EXPORTS # define EXPORT_OSMIMAGING OSSIMEXPORT # else # define EXPORT_OSMIMAGING OSSIMIMPORT # endif # endif # endif #else /* defined(_MSC_VER) */ # ifdef OSSIMMAKINGDLL # define OSSIMDLLEXPORT OSSIMEXPORT # define OSSIM_DLL OSSIMEXPORT # define OSSIMDLLEXPORT_DATA(type) OSSIMEXPORT type # define OSSIM_DLL_DATA(type) OSSIMEXPORT type # define OSSIMDLLEXPORT_CTORFN # elif defined(OSSIMUSINGDLL) # define OSSIMDLLEXPORT OSSIMIMPORT # define OSSIM_DLL OSSIMIMPORT # define OSSIMDLLEXPORT_DATA(type) OSSIMIMPORT type # define OSSIM_DLL_DATA(type) OSSIMIMPORT type # define OSSIMDLLEXPORT_CTORFN # else /* not making nor using DLL */ # define OSSIMDLLEXPORT # define OSSIM_DLL # define OSSIM_DLL_DATA(type) type # define OSSIMDLLEXPORT_DATA(type) type # define OSSIMDLLEXPORT_CTORFN # endif # define EXPORT_OSMMATRIX OSSIMDLLEXPORT # define EXPORT_OSMELEV OSSIMDLLEXPORT # define EXPORT_OSMSPTDATA OSSIMDLLEXPORT # define EXPORT_OSMPROJ OSSIMDLLEXPORT # define EXPORT_OSMIMAGING OSSIMDLLEXPORT #endif #endif /* End of commented out "#if 0" old DLL import/export section. */ /* we know that if this is defined all other types are defined since its included from ossimConfig.h */ typedef char ossim_int8; typedef unsigned char ossim_uint8; typedef signed char ossim_sint8; typedef short ossim_int16; typedef unsigned short ossim_uint16; typedef signed short ossim_sint16; typedef int ossim_int32; typedef unsigned int ossim_uint32; typedef signed int ossim_sint32; typedef float ossim_float32; typedef double ossim_float64; typedef long long ossim_int64; typedef unsigned long long ossim_uint64; typedef signed long long ossim_sint64; typedef ossim_int32 ossimErrorCode; enum ossimVertexOrdering { OSSIM_VERTEX_ORDER_UNKNOWN = 0, OSSIM_CLOCKWISE_ORDER = 1, OSSIM_COUNTERCLOCKWISE_ORDER = 2 }; //--- // For histogram builders. Note that FAST computation mode will not sample all tiles. //--- enum ossimHistogramMode { OSSIM_HISTO_MODE_UNKNOWN = 0, OSSIM_HISTO_MODE_NORMAL = 1, OSSIM_HISTO_MODE_FAST = 2 }; /* Corner coordinates are relative to center (0) of pixel or relative to the upper left of pixel (1). */ enum ossimPixelType { OSSIM_PIXEL_IS_POINT = 0, OSSIM_PIXEL_IS_AREA = 1 }; /* Definitions for scalar type identification. */ enum ossimScalarType { OSSIM_SCALAR_UNKNOWN = 0, OSSIM_UINT8 = 1, /**< 8 bit unsigned integer */ OSSIM_UINT9 = 2, /**< 16 bit unsigned integer (9 bits used) */ OSSIM_UINT10 = 3, /**< 16 bit unsigned integer (10 bits used) */ OSSIM_UINT11 = 4, /**< 16 bit unsigned integer (11 bits used) */ OSSIM_UINT12 = 5, /**< 16 bit unsigned integer (12 bits used) */ OSSIM_UINT13 = 6, /**< 16 bit unsigned integer (13 bits used) */ OSSIM_UINT14 = 7, /**< 16 bit unsigned integer (14 bits used) */ OSSIM_UINT15 = 8, /**< 16 bit unsigned integer (15 bits used) */ OSSIM_UINT16 = 9, /**< 16 bit unsigned integer */ OSSIM_UINT32 = 10, /**< 32 bit unsigned integer */ OSSIM_UINT64 = 11, /**< 64 bit unsigned integer */ OSSIM_SINT8 = 12, /**< 8 bit signed integer */ OSSIM_SINT16 = 13, /**< 16 bit signed integer */ OSSIM_SINT32 = 14, /**< 32 bit signed integer */ OSSIM_SINT64 = 15, /**< 64 bit signed integer */ OSSIM_FLOAT32 = 16, /**< 32 bit floating point */ OSSIM_FLOAT64 = 17, /**< 64 bit floating point */ OSSIM_CINT16 = 18, /**< 16 bit complex integer */ OSSIM_CINT32 = 19, /**< 32 bit complex integer */ OSSIM_CFLOAT32 = 20, /**< 32 bit complex floating point */ OSSIM_CFLOAT64 = 21, /**< 64 bit complex floating point */ OSSIM_NORMALIZED_FLOAT = 22, /**< 32 bit normalized floating point */ OSSIM_NORMALIZED_DOUBLE = 23, /**< 64 bit normalized floating point */ //--- // Below for backward compatibility only. Please use above enums in // conjunction with null, min, max settings to determine bit depth. //--- OSSIM_UCHAR = 1, /**< 8 bit unsigned integer */ OSSIM_USHORT11 = 4, /**< 16 bit unsigned integer (11 bits used) */ OSSIM_USHORT12 = 5, /**< 16 bit unsigned integer (12 bits used) */ OSSIM_USHORT13 = 6, /**< 16 bit unsigned integer (13 bits used) */ OSSIM_USHORT14 = 7, /**< 16 bit unsigned integer (14 bits used) */ OSSIM_USHORT15 = 8, /**< 16 bit unsigned integer (15 bits used) */ OSSIM_USHORT16 = 9, /**< 16 bit unsigned integer */ OSSIM_SSHORT16 = 13, /**< 16 bit signed integer */ OSSIM_FLOAT = 16, /**< 32 bit floating point */ OSSIM_DOUBLE = 17 /**< 64 bit floating point */ }; /* Definitions for interleave type identification. */ enum ossimInterleaveType { OSSIM_INTERLEAVE_UNKNOWN = 0, OSSIM_BIL = 1, /* band interleaved by line */ OSSIM_BIP = 2, /* band interleaved by pixel */ OSSIM_BSQ = 3, /* band sequential */ OSSIM_BSQ_MULTI_FILE = 4 /* band sequential in separate files */ }; /* Definitions for origin location. */ enum ossimOriginLocationType { OSSIM_ORIGIN_LOCATION_UNKNOWN = 0, OSSIM_CENTER = 1, OSSIM_UPPER_LEFT = 2, OSSIM_UPPER_LEFT_CENTER = 3, OSSIM_LOWER_LEFT = 4, OSSIM_LOWER_LEFT_CENTER = 5 }; /* Definitions for coordinate system type. */ enum ossimCoordinateSystemType { OSSIM_COORDINATE_SYSTEM_UNKNOWN = 0, OSSIM_IMAGE_SPACE = 1, OSSIM_GEOGRAPHIC_SPACE = 2, OSSIM_PROJECTED_SPACE = 3, OSSIM_GEOCENTRIC_SPACE = 4 }; /* Definitions for coordinate system orientation mode . */ enum ossimCoordSysOrientMode { OSSIM_LEFT_HANDED = 0, OSSIM_RIGHT_HANDED = 1 }; /* Definitions for unit type. */ enum ossimUnitType { OSSIM_UNIT_UNKNOWN = 0, OSSIM_METERS = 1, OSSIM_FEET = 2, OSSIM_US_SURVEY_FEET = 3, OSSIM_DEGREES = 4, OSSIM_RADIANS = 5, OSSIM_NAUTICAL_MILES = 6, OSSIM_SECONDS = 7, OSSIM_MINUTES = 8, OSSIM_PIXEL = 9, OSSIM_MILES = 10, OSSIM_MILLIMETERS = 11, OSSIM_MICRONS = 12, OSSIM_CENTIMETERS = 13, OSSIM_YARDS = 14, OSSIM_INCHES = 15, OSSIM_KILOMETERS = 16 }; /** Definitions for data object status. */ enum ossimDataObjectStatus { OSSIM_STATUS_UNKNOWN = 0, OSSIM_NULL = 1, // not initialized OSSIM_EMPTY = 2, // initialized but blank or empty OSSIM_PARTIAL = 3, // contains some null/invalid values OSSIM_FULL = 4 // all valid data }; /** Definitions for image type identification. */ enum ossimImageType { OSSIM_IMAGE_TYPE_UNKNOWN = 0, OSSIM_TIFF_STRIP = 1, OSSIM_TIFF_STRIP_BAND_SEPARATE = 2, OSSIM_TIFF_TILED = 3, OSSIM_TIFF_TILED_BAND_SEPARATE = 4, OSSIM_GENERAL_RASTER_BIP = 5, OSSIM_GENERAL_RASTER_BIL = 6, OSSIM_GENERAL_RASTER_BSQ = 7, OSSIM_JPEG = 8, OSSIM_PDF = 9 }; /** Definitions for metadata type identification. */ enum ossimMetadataType { OSSIM_META_UNKNOWN = 0, OSSIM_META_TFW = 1, OSSIM_META_JGW = 2, OSSIM_META_GEOM = 3, OSSIM_META_README = 4, OSSIM_META_FGDC = 5, OSSIM_META_ENVI = 6 }; enum ossimByteOrder { OSSIM_LITTLE_ENDIAN = 0, OSSIM_BIG_ENDIAN = 1 }; enum ossimCompareType { OSSIM_COMPARE_FULL=0, // compares full traversal if supported. Not just instance pointers OSSIM_COMPARE_IMMEDIATE=1 // Only immediate attributes are compared }; #ifndef FLT_EPSILON # define FLT_EPSILON __FLT_EPSILON__ #endif #ifndef DBL_EPSILON # define DBL_EPSILON __DBL_EPSILON__ #endif #ifndef M_PI # define M_PI ((ossim_float64)3.141592653589793238462643) #endif #ifndef TWO_PI # define TWO_PI ((ossim_float64)(2.0 * M_PI)) #endif #ifndef DEG_PER_RAD # define DEG_PER_RAD ((ossim_float64)(180.0/M_PI)) #endif #ifndef SEC_PER_RAD # define SEC_PER_RAD ((ossim_float64)206264.8062471) #endif #ifndef RAD_PER_DEG # define RAD_PER_DEG ((ossim_float64)(M_PI/180.0)) #endif #ifndef MTRS_PER_FT # define MTRS_PER_FT ((ossim_float64)0.3048) #endif #ifndef FT_PER_MTRS # define FT_PER_MTRS ((ossim_float64)3.280839895013122) #endif #ifndef FT_PER_MILE # define FT_PER_MILE ((ossim_float64)5280.0) #endif #ifndef SQRT_TWO_PI # define SQRT_TWO_PI ((ossim_float64)2.50662827463100050242) #endif #ifndef SQRT_TWO_PI_DIV2 # define SQRT_TWO_PI_DIV2 ((ossim_float64)7.07106781186547524401E-1) #endif #define TIFFTAG_OSSIM_METADATA 50955 #define OSSIM_DEFAULT_TILE_HEIGHT ((ossim_int32)64) #define OSSIM_DEFAULT_TILE_WIDTH ((ossim_int32)64) /* NOTE Reference for U.S. feet value: U.S.G.S. "Map Projections - A Working Manual" USGS Professional paper 1395 page 51 */ #ifndef US_METERS_PER_FT # define US_METERS_PER_FT ((ossim_float64)0.3048006096) #endif //--- // Integer nan kept for ossimIpt and templated ossim::Pt // This should be the most negative int. // 32 bit: -2147483648 // 64 bit: -9223372036854775808 //--- #define OSSIM_INT_NAN ((ossim_sint32)0x80000000) #define OSSIM_INT32_NAN ((ossim_sint32)0x80000000) #define OSSIM_INT64_NAN ((ossim_sint64)0x8000000000000000) // UCHAR for backwards compatibility. */ #define OSSIM_DEFAULT_NULL_PIX_UCHAR ((ossim_uint8)0) #define OSSIM_DEFAULT_MIN_PIX_UCHAR ((ossim_uint8)1) #define OSSIM_DEFAULT_MAX_PIX_UCHAR ((ossim_uint8)255) #define OSSIM_DEFAULT_NULL_PIX_SINT8 ((ossim_sint8)0x80) #define OSSIM_DEFAULT_MIN_PIX_SINT8 ((ossim_sint8)0x81) #define OSSIM_DEFAULT_MAX_PIX_SINT8 ((ossim_sint8)0x7F) #define OSSIM_DEFAULT_NULL_PIX_UINT8 ((ossim_uint8)0) #define OSSIM_DEFAULT_MIN_PIX_UINT8 ((ossim_uint8)1) #define OSSIM_DEFAULT_MAX_PIX_UINT8 ((ossim_uint8)255) #define OSSIM_DEFAULT_NULL_PIX_UINT9 ((ossim_uint16)0) #define OSSIM_DEFAULT_MIN_PIX_UINT9 ((ossim_uint16)1) #define OSSIM_DEFAULT_MAX_PIX_UINT9 ((ossim_uint16)0x01FF) #define OSSIM_DEFAULT_NULL_PIX_UINT10 ((ossim_uint16)0) #define OSSIM_DEFAULT_MIN_PIX_UINT10 ((ossim_uint16)1) #define OSSIM_DEFAULT_MAX_PIX_UINT10 ((ossim_uint16)0x03FF) #define OSSIM_DEFAULT_NULL_PIX_UINT11 ((ossim_uint16)0) #define OSSIM_DEFAULT_MIN_PIX_UINT11 ((ossim_uint16)1) #define OSSIM_DEFAULT_MAX_PIX_UINT11 ((ossim_uint16)0x07FF) #define OSSIM_DEFAULT_NULL_PIX_UINT12 ((ossim_uint16)0) #define OSSIM_DEFAULT_MIN_PIX_UINT12 ((ossim_uint16)1) #define OSSIM_DEFAULT_MAX_PIX_UINT12 ((ossim_uint16)0x0FFF) #define OSSIM_DEFAULT_NULL_PIX_UINT13 ((ossim_uint16)0) #define OSSIM_DEFAULT_MIN_PIX_UINT13 ((ossim_uint16)1) #define OSSIM_DEFAULT_MAX_PIX_UINT13 ((ossim_uint16)0x1FFF) #define OSSIM_DEFAULT_NULL_PIX_UINT14 ((ossim_uint16)0) #define OSSIM_DEFAULT_MIN_PIX_UINT14 ((ossim_uint16)1) #define OSSIM_DEFAULT_MAX_PIX_UINT14 ((ossim_uint16)0x3FFF) #define OSSIM_DEFAULT_NULL_PIX_UINT15 ((ossim_uint16)0) #define OSSIM_DEFAULT_MIN_PIX_UINT15 ((ossim_uint16)1) #define OSSIM_DEFAULT_MAX_PIX_UINT15 ((ossim_uint16)0x7FFF) #define OSSIM_DEFAULT_NULL_PIX_SINT16 ((ossim_sint16)0x8000) #define OSSIM_DEFAULT_MIN_PIX_SINT16 ((ossim_sint16)0x8001) #define OSSIM_DEFAULT_MAX_PIX_SINT16 ((ossim_sint16)0x7FFF) #define OSSIM_DEFAULT_NULL_PIX_UINT16 ((ossim_uint16)0) #define OSSIM_DEFAULT_MIN_PIX_UINT16 ((ossim_uint16)1) #define OSSIM_DEFAULT_MAX_PIX_UINT16 ((ossim_uint16)0xFFFF) #define OSSIM_DEFAULT_NULL_PIX_SINT32 ((ossim_sint32)0x80000000) #define OSSIM_DEFAULT_MIN_PIX_SINT32 ((ossim_sint32)0x80000001) #define OSSIM_DEFAULT_MAX_PIX_SINT32 ((ossim_sint32)0x7FFFFFFF) #define OSSIM_DEFAULT_NULL_PIX_UINT32 ((ossim_uint32)0) #define OSSIM_DEFAULT_MIN_PIX_UINT32 ((ossim_uint32)1) #define OSSIM_DEFAULT_MAX_PIX_UINT32 ((ossim_uint32)0xFFFFFFFF) #define OSSIM_DEFAULT_NULL_PIX_SINT64 ((ossim_sint64)0x8000000000000000) #define OSSIM_DEFAULT_MIN_PIX_SINT64 ((ossim_sint64)0x8000000000000001) #define OSSIM_DEFAULT_MAX_PIX_SINT64 ((ossim_sint64)0x7FFFFFFFFFFFFFFF) #define OSSIM_DEFAULT_NULL_PIX_UINT64 ((ossim_uint64)0) #define OSSIM_DEFAULT_MIN_PIX_UINT64 ((ossim_uint64)1) #define OSSIM_DEFAULT_MAX_PIX_UINT64 ((ossim_uint64)0xFFFFFFFFFFFFFFFF) #define OSSIM_DEFAULT_NULL_PIX_FLOAT ((ossim_float32)-1.0/FLT_EPSILON) #define OSSIM_DEFAULT_MIN_PIX_FLOAT ((ossim_float32)((-1.0/FLT_EPSILON) + 1)) #define OSSIM_DEFAULT_MAX_PIX_FLOAT ((ossim_float32)((1.0/FLT_EPSILON))) #define OSSIM_DEFAULT_NULL_PIX_NORM_FLOAT ((ossim_float32)0) #define OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT ((ossim_float32)((2*FLT_EPSILON))) #define OSSIM_DEFAULT_MAX_PIX_NORM_FLOAT ((ossim_float32)1.0) #define OSSIM_DEFAULT_NULL_PIX_DOUBLE ((ossim_float64)-1.0/DBL_EPSILON) #define OSSIM_DEFAULT_MIN_PIX_DOUBLE ((ossim_float64)((-1.0/DBL_EPSILON) + 1)) #define OSSIM_DEFAULT_MAX_PIX_DOUBLE ((ossim_float64)((1.0/DBL_EPSILON))) #define OSSIM_DEFAULT_NULL_PIX_NORM_DOUBLE ((ossim_float64)0) #define OSSIM_DEFAULT_MIN_PIX_NORM_DOUBLE ((ossim_float64)((2*DBL_EPSILON))) #define OSSIM_DEFAULT_MAX_PIX_NORM_DOUBLE ((ossim_float64)(1.0)) #define OSSIM_DEFAULT_MEAN_SEA_LEVEL ((ossim_float64)0.0) #endif /* #ifndef ossimConstants_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimContainerEvent.h000066400000000000000000000023751352751253100235610ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimContainerEvent.h 19966 2011-08-16 18:12:56Z gpotts $ #ifndef ossimContainerEvent_HEADER #define ossimContainerEvent_HEADER #include #include #include #include class OSSIMDLLEXPORT ossimContainerEvent : public ossimEvent { public: typedef std::vector > ObjectList; /** constuctor */ ossimContainerEvent(ossimObject* obj1,// the object firing the event. long id); void setObjectList(ossimObject* obj); void setObjectList(ObjectList& objects); ObjectList& getObjectList(){return m_objectList;} const ObjectList& getObjectList()const{return m_objectList;} protected: /*! * This is the object associated with the container event. * if this was an add then it s the object added to the * container. */ ObjectList m_objectList; TYPE_DATA }; #endif /* end of: "#ifndef ossimContainerEvent_HEADER" */ ossim-Miami-2.9.1/include/ossim/base/ossimContainerProperty.h000066400000000000000000000040721352751253100243200ustar00rootroot00000000000000//******************************************************************* // // LICENSE: See top level LICENSE.txt // // Author: Garrett Potts // //************************************************************************* // $Id: ossimContainerProperty.h 19917 2011-08-09 11:12:24Z gpotts $ #ifndef ossimContainerProperty_HEADER #define ossimContainerProperty_HEADER #include #include #include class OSSIMDLLEXPORT ossimContainerProperty : public ossimProperty { public: friend class ossimProperty; ossimContainerProperty(const ossimString& name=ossimString("")); ossimContainerProperty(const ossimContainerProperty& rhs); virtual ~ossimContainerProperty(); virtual ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); virtual void addChildren(std::vector >& propertyList); virtual void addChild(ossimProperty* propery); virtual void addStringProperty(const ossimString& name, const ossimString& value, bool readOnlyFlag = false); virtual const ossimContainerProperty* asContainer()const; virtual ossimContainerProperty* asContainer(); virtual ossimRefPtr getProperty(const ossimString& name, bool recurse=false); virtual void deleteChildren(); virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; virtual ossim_uint32 getNumberOfProperties()const; virtual ossimRefPtr getProperty(ossim_uint32 idx); virtual void getPropertyList( std::vector >& children) const; virtual ossimRefPtr toXml()const; virtual void setReadOnlyFlag(bool flag); virtual void accept(ossimVisitor& visitor); protected: std::vector > theChildPropertyList; virtual void copyList(const ossimContainerProperty& rhs); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimCplUtil.h000066400000000000000000000047571352751253100222170ustar00rootroot00000000000000/* * Copied from "gdal" project. See licence below. * * Global functions for gdal code compatibility. * * Project: ISO 8211 Access * Purpose: Main declarations for ISO 8211. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** * $Id: ossimCplUtil.h 13013 2008-06-10 13:34:01Z dburken $ */ #ifndef ossimCplUtil_HEADER #define ossimCplUtil_HEADER #include /* to pick up "size_t" */ #include OSSIMDLLEXPORT char** ossimCSLTokenizeString(const char *pszString ); OSSIMDLLEXPORT char** ossimCSLTokenizeStringComplex(const char *pszString, const char *pszDelimiter, int bHonourStrings, int bAllowEmptyTokens ); OSSIMDLLEXPORT char** ossimCSLTokenizeString2( const char *pszString, const char *pszDelimeter, int nCSLTFlags ); OSSIMDLLEXPORT int ossimCSLCount(char **papszStrList); OSSIMDLLEXPORT void ossimCSLDestroy(char **papszStrList); OSSIMDLLEXPORT void* ossimCPLRealloc( void * pData, size_t nNewSize ); #endif /* ossimCplUtil_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimCsvFile.h000066400000000000000000000060301352751253100221600ustar00rootroot00000000000000#ifndef ossimCsvFile_HEADER #define ossimCsvFile_HEADER #include #include #include #include #include #include #include #include class OSSIM_DLL ossimCsvFile : public ossimReferenced { public: typedef std::vector StringListType; class OSSIM_DLL Record : public ossimReferenced { public: typedef std::map FieldMapType; typedef std::vector FieldValueListType; Record(ossimCsvFile* csvFile); void setCsvFile(ossimCsvFile* file) { theCsvFile = file; } ossimCsvFile* csvFile() { return theCsvFile; } const ossimCsvFile* csvFile()const { return theCsvFile; } StringListType& values() { return theValues; } const StringListType& values()const { return theValues; } /** * Allows access to a field as read only. */ bool valueAt(const ossimString& fieldName, ossimString& value)const; bool valueAt(ossim_uint32 idx, ossimString& value)const; /** * Allows one to access and write to the field. */ ossimString& operator [](const ossimString& fieldName); const ossimString& operator [](const ossimString& fieldName)const; ossimString& operator [](ossim_uint32 idx); const ossimString& operator [](ossim_uint32 idx)const; protected: // used in out of bounds returns on the operators [] // ossimString theDummyValue; StringListType theValues; ossimCsvFile* theCsvFile; }; friend class Record; ossimCsvFile(const ossimString& separatorList=","); ~ossimCsvFile(); /** * For now we will only support the read flag and open existing * csv files. Later we can add support for creating and writing csv files * */ bool open(const ossimFilename& file, const ossimString& flags="r"); void close(); bool readHeader(); /** * Read one record and returns null if no more records exist or returns a valid pointer * if a record exists. */ ossimRefPtr nextRecord(); /** * Returns the header of the CSV file. */ const StringListType& fieldHeaderList()const; ossim_int32 indexOfField(const ossimString& fieldName)const; static ossim_int32 INVALID_INDEX; protected: bool readCsvLine(std::istream& inStream, ossimCsvFile::StringListType& tokens)const; StringListType theFieldHeaderList; ossimRefPtr theRecordBuffer; std::istream* theInputStream; ossimString theSeparatorList; bool theOpenFlag; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimCustomEditorWindow.h000066400000000000000000000027661352751253100244520ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimCustomEditorWindow.h 17108 2010-04-15 21:08:06Z dburken $ #ifndef ossimCustomEditorWindow_HEADER #define ossimCustomEditorWindow_HEADER #include class OSSIMDLLEXPORT ossimCustomEditorWindow : public ossimObject { public: /*! * Returns the system dependent window. If you are in wx it * will probalby be some type of wxWindow*. */ virtual void* getWindow()=0; /*! * This is the parent window. If the parent can be * set by the derived classes it will return true. */ virtual void setParent(void* parent)=0; /*! * Will return the parent of the managed wxWindow */ virtual void* getParent()=0; /*! * WIll set the object to edit. If this editor does not know * anything about the passed in obj it will return false. */ virtual bool setObjectToEdit(ossimObject* obj)=0; /*! * Just asks if I can edit the passed in object. */ virtual bool canEdit(ossimObject* obj)const=0; /*! * Returns the object we are editing. */ virtual ossimObject* getObject()=0; protected: ossimCustomEditorWindow(){} ossimCustomEditorWindow(const ossimCustomEditorWindow&){} void operator =(const ossimCustomEditorWindow& /*rhs*/){} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimCustomEditorWindowFactoryBase.h000066400000000000000000000024251352751253100265650ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimCustomEditorWindowFactoryBase.h 14789 2009-06-29 16:48:14Z dburken $ #ifndef ossimCustomEditorWindowFactoryBase_HEADER #define ossimCustomEditorWindowFactoryBase_HEADER #include class ossimCustomEditorWindow; class OSSIMDLLEXPORT ossimCustomEditorWindowFactoryBase : public ossimObjectFactory { public: virtual ossimCustomEditorWindow* createCustomEditor(ossimObject* obj, void* parent=NULL)const=0; virtual ossimCustomEditorWindow* createCustomEditor(const ossimString& classType, void* parent=NULL)const=0; /*! * Returns a native GUI Editor with popup */ virtual void* createPopupEditor(ossimObject* obj, void* parent=NULL)const=0; /*! * Returns a native GUI child window without a popup. */ virtual void* createPanelEditor(ossimObject* obj, void* parent=NULL)const=0; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimCustomEditorWindowRegistry.h000066400000000000000000000044321352751253100261730ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimCustomEditorWindowRegistry.h 17108 2010-04-15 21:08:06Z dburken $ #ifndef ossimCustomEditorWindowRegistry_HEADER #define ossimCustomEditorWindowRegistry_HEADER #include #include #include #include class ossimCustomEditorWindowFactoryBase; class OSSIMDLLEXPORT ossimCustomEditorWindowRegistry : public ossimCustomEditorWindowFactoryBase { public: virtual ~ossimCustomEditorWindowRegistry(); static ossimCustomEditorWindowRegistry* instance(); bool registerFactory(ossimCustomEditorWindowFactoryBase* factory); virtual ossimCustomEditorWindow* createCustomEditor(ossimObject* obj, void* parent=NULL)const; virtual ossimCustomEditorWindow* createCustomEditor(const ossimString& classType, void* parent=NULL)const; virtual ossimObject* createObject(const ossimString& typeName)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Returns a native GUI Editor with popup */ virtual void* createPopupEditor(ossimObject* obj, void* parent=NULL)const; /*! * Returns a native GUI child window without a popup. */ virtual void* createPanelEditor(ossimObject* obj, void* parent=NULL)const; virtual void getTypeNameList(std::vector& typeList)const; protected: ossimCustomEditorWindowRegistry(){} ossimCustomEditorWindowRegistry(const ossimCustomEditorWindowRegistry&){} void operator =(const ossimCustomEditorWindowRegistry& /*rhs*/){} std::vector theFactoryList; static ossimCustomEditorWindowRegistry* theInstance; TYPE_DATA }; extern "C" { OSSIMDLLEXPORT void* ossimCustomEditorWindowRegistryGetInstance(); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimDataObject.h000066400000000000000000000065471352751253100226420ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimDataObject.h 23505 2015-09-08 19:04:19Z dburken $ #ifndef ossimDataObject_HEADER #define ossimDataObject_HEADER #include #include #include class ossimSource; class OSSIMDLLEXPORT ossimDataObject : public ossimObject { public: ossimDataObject(ossimSource* source=0, ossimDataObjectStatus status=OSSIM_STATUS_UNKNOWN); ossimDataObject(const ossimDataObject& rhs); virtual ~ossimDataObject(); virtual ossim_uint32 getHashId()const=0; /** * Sets the owner of this Data object. */ virtual void setOwner(ossimSource* aSource); virtual ossimSource* getOwner(); virtual const ossimSource* getOwner() const; /** * Full list found in ossimConstants.h * * OSSIM_STATUS_UNKNOWN * OSSIM_NULL Null data. The buffers are never allocated * OSSIM_EMPTY Allocated data but its empty. Most of the * time this will be the default for an initialized * data object. * OSSIM_PARTIAL Says that some of the object is empty and is only * partially full * OSSIM_FULL This data is completey full */ virtual void setDataObjectStatus(ossimDataObjectStatus status) const; /** * @return Returns enumerated status: * OSSIM_STATUS_UNKNOWN = 0 * OSSIM_NULL = 1 * OSSIM_EMPTY = 2 * OSSIM_PARTIAL = 3 * OSSIM_FULL = 4 */ virtual ossimDataObjectStatus getDataObjectStatus() const; /** * @return Returns the status as a string, like "OSSIM_NULL". */ virtual ossimString getDataObjectStatusString() const; virtual ossim_uint64 getObjectSizeInBytes()const; virtual ossim_uint64 getDataSizeInBytes() const = 0; /** * This is to be overriden in the derived classes so they can check * If their data is null. */ virtual bool isInitialize() const; /** * Will allow derived classes to initialize their buffers. This class * does nothing with this and reset any internal attributes. */ virtual void initialize()=0; virtual void assign(const ossimDataObject* rhs); virtual const ossimDataObject* operator =(const ossimDataObject* rhs); virtual const ossimDataObject& operator=(const ossimDataObject& rhs); virtual bool operator==(const ossimDataObject& rhs) const; virtual bool operator!=(const ossimDataObject& rhs) const; virtual std::ostream& print(std::ostream& out) const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: //*** // Note: This object is not responsible for deletion of the ossimSource* // "theSource". It is simply a hook to his owner for things // like unregister and so forth... //*** ossimSource* theOwner; mutable ossimDataObjectStatus theDataObjectStatus; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDate.h000066400000000000000000000277571352751253100215250ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimDate.h 22765 2014-05-08 15:20:10Z gpotts $ #ifndef ossimDate_HEADER #define ossimDate_HEADER #include #include #include #include #include class OSSIM_DLL ossimLocalTm : public std::tm { public: friend OSSIM_DLL std::ostream& operator<<(std::ostream& out, const ossimLocalTm& src); friend OSSIM_DLL int operator== (const ossimLocalTm& t1, const ossimLocalTm& src); friend OSSIM_DLL int operator!= (const ossimLocalTm& t1, const ossimLocalTm& src); friend OSSIM_DLL int operator< (const ossimLocalTm& t1, const ossimLocalTm& src); friend OSSIM_DLL int operator<= (const ossimLocalTm& t1, const ossimLocalTm& src); friend OSSIM_DLL int operator> (const ossimLocalTm& t1, const ossimLocalTm& src); friend OSSIM_DLL int operator>= (const ossimLocalTm& t1, const ossimLocalTm& src); ossimLocalTm (time_t t=0); // Set to time, 0 is magic for 'now' ossimLocalTm (tm const & t); // Copy constructor ossimLocalTm (const ossimLocalTm& t); // Copy constructor ossimLocalTm & operator= (tm const & t); // Assignment ossimLocalTm & operator= (const ossimLocalTm & t); // Assignment operator time_t (void) const; // Conversion operator int isValid (void) const; // Test for validity void now(); int compare (ossimLocalTm const & t) const; // Compare times int compare (std::time_t const tt) const; // Compare times enum ossimLocalTmFormat // Date format flags { ossimLocalTmFormatYear = (int)0x0001, // Print year ossimLocalTmFormatYearShort = (int)0x0002, // Print last two digits ossimLocalTmFormatPadYear = (int)0x0004, // Pad year to 2 or 4 ossimLocalTmFormatZeroYear = (int)0x0008, // Zero fill year ossimLocalTmFormatMonth = (int)0x0010, // Print month ossimLocalTmFormatMonText = (int)0x0020, // Print month in text ossimLocalTmFormatPadMon = (int)0x0040, // Pad to 2 (trunc to 3) ossimLocalTmFormatZeroMon = (int)0x0080, // Zero fill month ossimLocalTmFormatDay = (int)0x0100, // Print date ossimLocalTmFormatDayOfWeek = (int)0x0200, // Print day of week ossimLocalTmFormatPadDay = (int)0x0400, // Pad date to 2 ossimLocalTmFormatZeroDay = (int)0x0800, // Zero fill day ossimLocalTmFormatDMY = (int)0x0111, // Print date, mth, year ossimLocalTmFormatPadDMY = (int)0x0444, // Pad all three ossimLocalTmFormatZeroDMY = (int)0x0888, // Zero fill all three ossimLocalTmFormatYearFirst = (int)0x1000, // Print year first ossimLocalTmFormatMonFirst = (int)0x2000, // Print month first ossimLocalTmFormatSepChar = (int)0x4000,// Separate fields datech ossimLocalTmFormatSepSpace = (int)0x8000, // Separate fields space ossimLocalTmFormatInternational = (int)(ossimLocalTmFormatDMY|ossimLocalTmFormatMonText|ossimLocalTmFormatPadMon| ossimLocalTmFormatSepSpace), ossimLocalTmFormatIntlShort = (int)(ossimLocalTmFormatDMY|ossimLocalTmFormatMonText|ossimLocalTmFormatPadMon| ossimLocalTmFormatSepSpace|ossimLocalTmFormatYearShort), ossimLocalTmFormatUsa = (int)(ossimLocalTmFormatDMY|ossimLocalTmFormatMonFirst|ossimLocalTmFormatPadDMY| ossimLocalTmFormatZeroDMY|ossimLocalTmFormatYearShort|ossimLocalTmFormatSepChar), ossimLocalTmFormatEnglish = (int)(ossimLocalTmFormatDMY|ossimLocalTmFormatYearShort|ossimLocalTmFormatPadDMY| ossimLocalTmFormatZeroDMY|ossimLocalTmFormatSepChar), ossimLocalTmFormatJapanese = (int)(ossimLocalTmFormatDMY|ossimLocalTmFormatYearFirst|ossimLocalTmFormatPadDMY| ossimLocalTmFormatZeroDMY|ossimLocalTmFormatYearShort|ossimLocalTmFormatMonFirst| ossimLocalTmFormatSepChar), ossimLocalTmFormatFull = (int)(ossimLocalTmFormatDMY|ossimLocalTmFormatDayOfWeek|ossimLocalTmFormatMonText| ossimLocalTmFormatSepSpace) }; enum ossimTimeFormat // Time format (nb: time zones not implemented) { ossimTimeFormatSecs = (int)0x0001, // Print seconds ossimTimeFormatZeroSecs = (int)0x0002, // Zero fill seconds ossimTimeFormatPadSecs = (int)0x0004, // Pad seconds to 2 ossimTimeFormatSecsAll = (int)0x0007, ossimTimeFormatTimeZone = (int)0x0008, // Print timezone ossimTimeFormatMins = (int)0x0010, // Print minutes ossimTimeFormatZeroMins = (int)0x0020, // Zero fill minutes ossimTimeFormatPadMins = (int)0x0040, // Pad minutes to 2 ossimTimeFormatMinsAll = (int)0x0070, ossimTimeFormatTZNumeric = (int)0x0080, // Print numeric TZ ossimTimeFormatHour = (int)0x0100, // Print hour ossimTimeFormatZeroHour = (int)0x0200, // Zero fill hour ossimTimeFormatPadHour = (int)0x0400, // Pad hour to 2 digits ossimTimeFormatHourAll = (int)0x0700, ossimTimeFormat24hour = (int)0x0800, // 24hour clock ossimTimeFormatSepChar = (int)0x1000, // Separate field timech ossimTimeFormatSepSpace = (int)0x2000, // Separate fields space ossimTimeFormatSepAbbrev = (int)0x4000, // Add abbreviations ossimTimeFormatAmPm = (int)0x8000, // Add 'am' or 'pm' ossimTimeFormatInternational = (int)(ossimTimeFormatHourAll|ossimTimeFormatMinsAll|ossimTimeFormatSecsAll| ossimTimeFormat24hour|ossimTimeFormatSepChar), ossimTimeFormatShortTime = (int)(ossimTimeFormatHourAll|ossimTimeFormatMinsAll|ossimTimeFormat24hour| ossimTimeFormatSepChar), ossimTimeFormatClockTime = (int)(ossimTimeFormatHour|ossimTimeFormatPadHour|ossimTimeFormatMinsAll| ossimTimeFormatAmPm|ossimTimeFormatSepChar), ossimTimeFormatLongTime = (int)(ossimTimeFormatHour|ossimTimeFormatPadHour|ossimTimeFormatMinsAll| ossimTimeFormatSecsAll|ossimTimeFormatSepAbbrev|ossimTimeFormatSepSpace), ossimTimeFormatMillitary = (int)(ossimTimeFormatHourAll|ossimTimeFormatMinsAll|ossimTimeFormat24hour) }; static char timech; // Character used for time separator static char datech; // Character used for date separator static int datefmt; // Default date format static int timefmt; // Default time format // Output methods std::ostream& print(std::ostream & os, int df =datefmt, int tf =timefmt) const; std::ostream& printTime(std::ostream & os, int f =timefmt) const; std::ostream& printDate(std::ostream & os, int f =datefmt) const; /** * @brief method to dump all the data members. This is the tm struct + * the theFractionalSecond from this class. * * @note: tm_gmtoff and tm_zone from tm struct are not printed as they * are not standard. * * @param os Stream to dump to. * * @return stream. */ std::ostream& dump(std::ostream& os) const; int getYear()const; int getShortYear()const; /*! * This is one based i.e. values are returned between 1-12 */ int getMonth()const; /*! * returns the day 1-31 */ int getDay()const; double getJulian()const; double getModifiedJulian()const; ossimLocalTm& setDay(int day); /*! * The month is a number bewteen 1 and 12. We will shift it to the internal * representation */ ossimLocalTm& setMonth(int month); ossimLocalTm& setYear(int year); ossimLocalTm& setDateFromJulian(double jd); ossimLocalTm& setDateFromModifiedJulian(double mjd); void setFractionalDay(double fractionalDay); static void extractHmsFromFractionalDay(double fractionalDay, int &h, int &m, int &s, double& fractionalSecond); int getHour()const; int getMin()const; int getSec()const; double getFractionalSecond()const; ossimLocalTm& setHour(int h); ossimLocalTm& setMin(int m); ossimLocalTm& setSec(int s); ossimLocalTm& setFloatSec(double s); ossimLocalTm& setFractionalSecond(double fractS); /** * getTicks() will call getEpoc. This is te number of microseconds passed * since (00:00:00 UTC, January 1, 1970) */ time_t getTicks()const; time_t getEpoc()const; void addSeconds(ossim_float64 n); void addMinutes(ossim_float64 n); void addHours(ossim_float64 n); void addDays(ossim_float64 n); ossim_float64 deltaInSeconds(const ossimLocalTm& d)const; ossim_float64 deltaInMinutes(const ossimLocalTm& d)const; ossim_float64 delatInHours(const ossimLocalTm& d)const; ossim_float64 deltaInDays(const ossimLocalTm& d)const; ossimLocalTm convertToGmt()const; /** * Will not adjust for timezone. The passed in value is based on seconds. */ void setTimeNoAdjustmentGivenEpoc(time_t ticks); /** * Will adjust for timezone. The passed in value is based on seconds. */ void setTimeGivenEpoc(time_t ticks); bool setIso8601(const std::string& timeString, bool shiftToGmtOffsetZero=false); ossimRefPtr saveXml()const; bool loadXml(ossimRefPtr dateNode); protected: // Time suffix void tSfx(std::ostream & os, int fmt, char ch) const; // Time field formatters void pHour(std::ostream & os, int fmt) const; void pMins(std::ostream & os, int fmt) const; void pSecs(std::ostream & os, int fmt) const; // Date suffix void dSfx(std::ostream & os, int fmt) const; // Date field formatters void pDate(std::ostream & os, int fmt) const; void pMonth(std::ostream & os, int fmt) const; void pYear(std::ostream & os, int fmt) const; void setTimezoneOffsetFromGmt(); static std::mutex m_mutex; double theFractionalSecond; mutable int m_timezoneOffset; }; class OSSIM_DLL ossimDate : public ossimLocalTm { public: friend OSSIM_DLL std::ostream& operator<<(std::ostream& out, const ossimDate& src); ossimDate(int datefmt =ossimLocalTm::datefmt); ossimDate (ossimLocalTm const & t, int dtfmt =ossimLocalTm::datefmt); ossimDate (time_t t, int dtfmt =ossimLocalTm::datefmt); ossimDate(int month, int day, int year,int dtfmt=ossimLocalTm::datefmt); int fmt(int f); int fmt(void) const; std::ostream & print (std::ostream & os) const; private: int _fmt; }; class OSSIM_DLL ossimTime :public ossimLocalTm { public: friend OSSIM_DLL std::ostream& operator<<(std::ostream& out, const ossimTime& src); ossimTime(int tmfmt =ossimLocalTm::timefmt); ossimTime (ossimTime const & t, int tmfmt =ossimLocalTm::timefmt); ossimTime (time_t t, int tmfmt =ossimLocalTm::timefmt); int fmt (int f); int fmt (void) const; std::ostream& print (std::ostream & os) const; private: int _fmt; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDateProperty.h000066400000000000000000000021451352751253100232520ustar00rootroot00000000000000//******************************************************************* // // LICENSE: MIT see top level license.txt // // Author: Garrett Potts // //************************************************************************* // $Id: ossimDateProperty.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimDateProperty_HEADER #define ossimDateProperty_HEADER #include #include class OSSIM_DLL ossimDateProperty : public ossimProperty { public: ossimDateProperty(); ossimDateProperty(const ossimString& name, const ossimString& value); ossimDateProperty(const ossimString& name, const ossimLocalTm& value); ossimDateProperty(const ossimDateProperty& src); virtual ossimObject* dup()const; void setDate(const ossimLocalTm& localTm); const ossimLocalTm& getDate()const; virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; virtual const ossimProperty& assign(const ossimProperty& rhs); protected: ossimLocalTm theValue; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDatum.h000066400000000000000000000136641352751253100217120ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // Contains class declaration for OssimDatum. This is a class wrapper // for Geotrans datum. For more thorough description of each function // look at the datum.h file. //******************************************************************* // $Id: ossimDatum.h 19793 2011-06-30 13:26:56Z gpotts $ #ifndef ossimDatum_HEADER #define ossimDatum_HEADER #include #include #include #include #include class OSSIMDLLEXPORT ossimDatum : public ossimObject { friend class ossimDatumFactory; public: /** * @param alpha_code new OSSIM/Geotrans datum code. (input) * @param name Name of the new datum (input) * @param SigmaX Standard error in X in meters (input) * @param SigmaY Standard error in Y in meters (input) * @param SigmaZ Standard error in Z in meters (input) * @param southLatitude Southern edge of validity rectangle in radians(input) * @param northLatitude Northern edge of validity rectangle in radians(input) * @param westLongitude Western edge of validity rectangle in radians (input) * @param eastLongitude Eastern edge of validity rectangle in radians (input) */ ossimDatum(const ossimString &alpha_code, const ossimString &name, const ossimEllipsoid* anEllipsoid, ossim_float64 sigmaX, ossim_float64 sigmaY, ossim_float64 sigmaZ, ossim_float64 westLongitude, ossim_float64 eastLongitude, ossim_float64 southLatitude, ossim_float64 northLatitude); // Argument holds the source point and datum. Returns another // point with this datum. // virtual ossimGpt shift(const ossimGpt &aPt)const=0; //utility functions to shift to and from the standard coordinates. //Users should use the shift instead!!! // virtual ossimGpt shiftToWgs84(const ossimGpt &aPt)const = 0; virtual ossimGpt shiftFromWgs84(const ossimGpt &aPt)const = 0; virtual bool isTheSameAs(const ossimDatum *aDatum)const {return this == aDatum;} virtual const ossimString& code()const{return theCode;} virtual const ossimString& name()const{return theName;} virtual ossim_uint32 epsgCode()const{return theEpsgCode;} virtual const ossimEllipsoid* ellipsoid()const{return theEllipsoid;} virtual ossim_float64 sigmaX()const{return theSigmaX;} virtual ossim_float64 sigmaY()const{return theSigmaY;} virtual ossim_float64 sigmaZ()const{return theSigmaZ;} virtual ossim_float64 westLongitude()const{return theWestLongitude;} virtual ossim_float64 eastLongitude()const{return theEastLongitude;} virtual ossim_float64 southLatitude()const{return theSouthLatitude;} virtual ossim_float64 northLatitude()const{return theNorthLatitude;} virtual ossim_float64 param1()const=0; virtual ossim_float64 param2()const=0; virtual ossim_float64 param3()const=0; virtual ossim_float64 param4()const=0; virtual ossim_float64 param5()const=0; virtual ossim_float64 param6()const=0; virtual ossim_float64 param7()const=0; virtual bool isInside(ossim_float64 latitude, ossim_float64 longitude)const { return ((theSouthLatitude <= latitude) && (latitude <= theNorthLatitude) && (theWestLongitude <= longitude) && (longitude <= theEastLongitude)); } bool operator==(const ossimDatum& rhs) const; bool operator!=(const ossimDatum& rhs)const { return (!(*this == rhs)); } virtual bool isEqualTo(const ossimObject& obj, ossimCompareType compareType=OSSIM_COMPARE_FULL)const; protected: //! Only friend ossimDatumFactory is permitted to delete virtual ~ossimDatum(){}; /*! * This is directly from Geotrans: * Begin Molodensky_Shift * This function shifts geodetic coordinates using the Molodensky method. * * a : Semi-major axis of source ellipsoid in meters (input) * da : Destination a minus source a (input) * f : Flattening of source ellipsoid (input) * df : Destination f minus source f (input) * dx : X coordinate shift in meters (input) * dy : Y coordinate shift in meters (input) * dz : Z coordinate shift in meters (input) */ virtual void molodenskyShift( double a, double da, double f, double df, double dx, double dy, double dz, double Lat_in, double Lon_in, double Hgt_in, double &Lat_out, double &Lon_out, double &Hgt_out)const; bool withinMolodenskyRange(const ossimGpt& pt)const { double lat = pt.latd(); return ((lat < 89.75) && (lat > -89.75)); } protected: ossimString theCode; ossim_uint32 theEpsgCode; ossimString theName; const ossimEllipsoid *theEllipsoid; ossim_float64 theSigmaX; ossim_float64 theSigmaY; ossim_float64 theSigmaZ; ossim_float64 theWestLongitude; ossim_float64 theEastLongitude; ossim_float64 theSouthLatitude; ossim_float64 theNorthLatitude; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDatumFactory.h000066400000000000000000000035561352751253100232410ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // This is the DatumFactory class. You give it a code and it will // construct a Datum class. It returns NULL if no code was found. //******************************************************************* // $Id: ossimDatumFactory.h 22851 2014-08-05 12:02:55Z gpotts $ #ifndef ossimDatumFactory_HEADER #define ossimDatumFactory_HEADER 1 #include #include #include #include #include class ossimFilename; class ossimDatum; class ossimWgs84Datum; class ossimWgs72Datum; class ossimString; class OSSIM_DLL ossimDatumFactory : public ossimDatumFactoryInterface { public: /** virtual destructor */ virtual ~ossimDatumFactory(); /** * create method * * Implements pure virtual ossimDatumFactoryInterface::create. * * @return const pointer to a datum. */ virtual const ossimDatum* create(const ossimString &code)const; virtual const ossimDatum* create(const ossimKeywordlist& kwl, const char *prefix=0)const; const ossimDatum* create(const ossimDatum* copy) const; static ossimDatumFactory* instance(); const ossimDatum* wgs84()const{return theWgs84Datum;} const ossimDatum* wgs72()const{return theWgs72Datum;} std::vector getList()const; virtual void getList(std::vector& list)const; void writeCStructure(const ossimFilename& file); protected: // static ossimDatumFactory* theInstance; const ossimDatum* theWgs84Datum; const ossimDatum* theWgs72Datum; std::map theDatumTable; ossimDatumFactory(); void deleteAll(); void initializeDefaults(); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDatumFactoryInterface.h000066400000000000000000000023311352751253100250500ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file // // Author: David Burken // // Description: Interface class for datum factories. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimDatumFactoryInterface_HEADER #define ossimDatumFactoryInterface_HEADER #include /* for OSSIM_DLL macro */ #include // Forward class declarations: class ossimString; class ossimDatum; class ossimKeywordlist; class OSSIM_DLL ossimDatumFactoryInterface { public: /** default constructor */ ossimDatumFactoryInterface(){} /** virtual destructor */ virtual ~ossimDatumFactoryInterface(){} /** * Pure virtual create method. * * @return const pointer to a datum. */ virtual const ossimDatum* create(const ossimString& code) const = 0; virtual const ossimDatum* create(const ossimKeywordlist& kwl, const char *prefix=0) const = 0; /** * Pure virtual getList method. * * @param list The list to add to. */ virtual void getList(std::vector& list) const = 0; }; #endif /* #ifndef ossimDatumFactoryInterface_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimDatumFactoryRegistry.h000066400000000000000000000037321352751253100247660ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file // // Author: David Burken // // Description: Class declaration of Registry (singleton) for datum factories. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimDatumFactoryRegistry_HEADER #define ossimDatumFactoryRegistry_HEADER #include #include /* for OSSIM_DLL macro */ #include #include // Forward class declarations. class ossimDatumFactoryInterface; class ossimString; class ossimDatum; class OSSIM_DLL ossimDatumFactoryRegistry : public ossimDatumFactoryInterface { public: /** destructor */ ~ossimDatumFactoryRegistry(); /** * instance method * * @return Point to the instance of the registry. */ static ossimDatumFactoryRegistry* instance(); /** * Method to add factory to registry. * @param factory Factory to register. */ void registerFactory(ossimDatumFactoryInterface* factory); /** * create method * * Implements pure virtual ossimDatumFactoryInterface::create. * * @return const pointer to a datum. */ virtual const ossimDatum* create(const ossimString& code)const; virtual const ossimDatum* create(const ossimKeywordlist& kwl, const char *prefix=0) const; /** * getList method to return a combined list of all datums from registered * datum factories. * * @param list The list to add to. */ virtual void getList(std::vector& list) const; protected: /** hidden from use default constructor */ ossimDatumFactoryRegistry(); /** Single static instance of this class. */ //static ossimDatumFactoryRegistry* theInstance; mutable std::mutex theFactoryListMutex; std::vector theFactoryList; }; #endif /* #ifndef ossimDatumFactoryRegistry_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimDblGrid.h000066400000000000000000000201331352751253100221340ustar00rootroot00000000000000//***************************************************************************** // O S S I M // // FILE: ossimDblGrid.h // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // // DESCRIPTION: // Contains declaration of class ossimDblGrid. This object class maintains // a regular grid of floating point (double) values. Access methods to the // grid include interpolation between grid nodes. Capability is included // to address the grid in an arbitrary, floating-point u, v coordinate // system which is related to the integer grid x, y system by scale and // offset: // // u = Sx*(x + Xo), v = Sy*(y + Y0) // // where Xo, Yo is the origin of the U/V cood system. Sx, Sy are the scale // relations. For example, if the grid is being used to hold a grid of // elevation posts, then the origin will be the SW corner post ground point, // and the scale will be derived from the post spacing. Both origin and // spacing are specified to the constructor. // //***************************************************************************** // $Id: ossimDblGrid.h 20044 2011-09-06 15:02:43Z oscarkramer $ #ifndef ossimDblGrid_HEADER #define ossimDblGrid_HEADER #include #include #include #include class ossimDrect; /*!**************************************************************************** * * CLASS: ossimDblGrid * *****************************************************************************/ class OSSIMDLLEXPORT ossimDblGrid { public: /*! * Default Constructor. */ ossimDblGrid (); /*! * Copy Constructor. */ ossimDblGrid (const ossimDblGrid& source_to_copy); /*! * Constructs given a U/V origin and spacing, and a grid size. */ ossimDblGrid (const ossimIpt& size, const ossimDpt& origin, const ossimDpt& spacing, double null_value = OSSIM_DEFAULT_NULL_PIX_DOUBLE); /*! * Constructs given a rectangle in U/V space and grid spacing. The origin is * taken as the upper-left corner of the rectangle. The lower-rightmost grid * point may not coincide with the rectangles LR corner if the side is not * evenly divisible by the corresponding spacing. */ ossimDblGrid (const ossimDrect& uv_rect, const ossimDpt& spacing, double null_value = OSSIM_DEFAULT_NULL_PIX_DOUBLE); ~ossimDblGrid (); /*! * When constructed with default, permits initialization afterward. */ void initialize(const ossimIpt& size, const ossimDpt& origin, const ossimDpt& spacing, double null_value = OSSIM_DEFAULT_NULL_PIX_DOUBLE ); void initialize(const ossimDrect& uv_rect, const ossimDpt& spacing, double null_value = OSSIM_DEFAULT_NULL_PIX_DOUBLE); /*! * Enables/disables extrapolation functionality. If extrapolation is enabled, then calls to * operator() will handle points outside of the grid. */ void enableExtrapolation(bool arg=true) { theExtrapIsEnabled = arg;} void deallocate(); /*! * Fills the current grid with the value specified. */ void fill(double fill_value); /*! * Fills the current grid with null values. */ void clear() { fill(theNullValue); } /*! * Access individual node value by node index in the X/Y (grid) coord system. */ void setNode (const ossimIpt& p, const double& value) { setNode(p.x, p.y, value); } void setNode (int x, int y, const double& value); double getNode (const ossimIpt& p) const { return getNode(p.x, p.y); } double getNode (int x, int y) const; /*! * Sets the node nearest the U,V point specified to the value given. This is * different from setNode() in that the UV coordinate system is used to * address a node instead of an XY grid point. */ void setNearestNode(const ossimDpt& uv_point, const double& value); /*! * This method performs a resampling of the defined grid nodes in order to * compute interpolated values for those uninitialized nodes. This is * necessary when only a subset of nodes are available for initializing the * grid. */ void interpolateNullValuedNodes(const double& decay_rate=10.0); /*! * Passes the grid data through a convolution filter given the kernel array. * The grid must not contain any NULL nodes as these are treated as valid * quantities. The kernel sizes should be odd numbers. To avoid shrinking * the grid by the kernel radius, the edge nodes outside of the filter's * reach are computed by extrapolation. X is the contiguous * axis in the kernel array, i.e., kernel(x,y) = kernel[y*size_x + x]. */ void filter(int size_x, int size_y, double* kernel); /*! * Interpolate between grid nodes given arbitrary u/v coord system: */ enum InterpType { BILINEAR }; void setInterpolationType (InterpType interp); enum DomainType { CONTINUOUS = 0, // Default continuous grid with no limits on values SAWTOOTH_90= 1, // For angles between -90 and 90 deg such as latitude WRAP_180 = 2, // For angles between -180 and 180 with discontinuity at limits (typically used for longitude) WRAP_360 = 3 // For angles between 0 and 360 with discontinuity at limits (typically used for rotations) }; void setDomainType(DomainType dt) { theDomainType = dt; } /*! * Access an interpolated value in the U/V (output) coordinate system. */ double operator() (const ossimDpt& uv_point) const {return (*this)(uv_point.u, uv_point.v);} double value (const ossimDpt& uv_point) const {return (*this)(uv_point.u, uv_point.v);} double operator() (const double& u, const double& v) const; double value (const double& u, const double& v) const {return (*this)(u,v);} /*! * operator for initializing this grid with another. */ const ossimDblGrid& operator = (const ossimDblGrid& grid); /*! *Statistics methods: */ double minValue() const { return theMinValue; } double maxValue() const { return theMaxValue; } double nullValue() const { return theNullValue; } double meanValue(); double meanStdDev(); void setMinValue(double value) {theMinValue = value;} void setMaxValue(double value) {theMaxValue = value;} void setNullValue(double value) {theNullValue = value;} /*! * Other member access methods: */ const ossimIpt& size() const { return theSize; } const ossimDpt& origin() const { return theOrigin; } const ossimDpt& spacing() const { return theSpacing; } unsigned long getSizeInBytes() const { return theSize.x*theSize.y*sizeof(double); } /*! * Returns true if double point lies within world space coverage: */ bool isInside(const ossimDpt& p) const {return isInside(p.u, p.v);} bool isInside(const double& u, const double& v) const; /*! * Loads and saves the grid from/to a stream. Returns TRUE if successful. */ bool save(std::ostream& os, const char* descr) const; bool load(std::istream& is); friend std::ostream& operator << (std::ostream& os, const ossimDblGrid& grid); private: void computeMean(); double interpolate(double x, double y) const; double extrapolate(double x, double y) const; //! Constrains the value to the numerical domain specified in theDomainType. void constrain(double& value) const; ossim_uint32 index(int x, int y) const { return y*theSize.x + x; } double* theGridData; ossimIpt theSize; ossimDpt theOrigin; ossimDpt theSpacing; double theMinValue; double theMaxValue; double theNullValue; double theMeanValue; double theDeviation; bool theMeanIsComputed; bool theExtrapIsEnabled; DomainType theDomainType; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDirectory.h000066400000000000000000000062301352751253100225730ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // //************************************************************************* // $Id: ossimDirectory.h 22656 2014-02-28 17:51:42Z dburken $ #ifndef ossimDirectory_HEADER #define ossimDirectory_HEADER #include #ifndef _WIN32 class ossimDirectoryData; #endif class OSSIMDLLEXPORT ossimDirectory { public: /*! * These flags define what kind of filenames is included in the list * of files enumerated by GetFirst/GetNext. */ enum { OSSIM_DIR_FILES = 0x0001, // include files OSSIM_DIR_DIRS = 0x0002, // include directories OSSIM_DIR_HIDDEN = 0x0004, // include hidden files OSSIM_DIR_DOTDOT = 0x0008, // include '.' and '..' // by default, enumerate everything except '.' and '..' OSSIM_DIR_DEFAULT = OSSIM_DIR_FILES | OSSIM_DIR_DIRS | OSSIM_DIR_HIDDEN }; ossimDirectory(); ossimDirectory(const ossimFilename& dir); ~ossimDirectory(); bool open(const ossimFilename& dir); bool isOpened() const; bool getFirst(ossimFilename &filename, int flags = OSSIM_DIR_DEFAULT); /*! * Get next file in the enumeration started with either GetFirst() or * GetFirstNormal(). */ bool getNext(ossimFilename &filename) const; void findAllFilesThatMatch(std::vector& result, const ossimString& regularExpressionPattern, int flags = OSSIM_DIR_DEFAULT); #if defined (_WIN32) void setFlags(int flags) { theFlags = flags; }; bool fileMatched(ossimFilename &filename) const; #endif // ESH 07/2008, Trac #234: OSSIM is case sensitive // when using worldfile templates during ingest /*! * Case insensitive search for files with the same name but * with letters that have different case than the input name. * * On Windows there can only be one match, but the case can be * different than the input name. On UNIX there can be multiple * matches. * * If the bExcludeExactMatch input parameter is set to false, * the original input name will be included in the 'result' * vector if it is found in the directory. Otherwise (the default), * the input name is excluded from the 'result' vector even if it * is found in the directory. * * Returns true if a name has been added to the result vector. */ bool findCaseInsensitiveEquivalents( const ossimFilename &filename, std::vector& result, bool bExcludeExactMatch = true ); // TODO using scandir() when available later, emulating it otherwise private: #if defined (_WIN32) intptr_t theData; ossimFilename theDirectoryName; int theFlags; #else ossimDirectoryData* theData; #endif }; #endif /* #ifndef ossimDirectory_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimDirectoryData.h000066400000000000000000000020271352751253100233650ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // // Description: // Class designed to be used by ossimDirectory class. Should not be used // directly. // //************************************************************************* // $Id: ossimDirectoryData.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimDirectoryData_HEADER #define ossimDirectoryData_HEADER #ifndef _MSC_VER #include #include class OSSIMDLLEXPORT ossimDirectoryData { public: ossimDirectoryData(const ossimFilename& dirname); ~ossimDirectoryData(); bool isOk() const { return theDir != NULL; } void setFlags(int flags); int getFlags() const; void rewind(); bool read(ossimFilename &filename); private: DIR* theDir; ossimFilename theDirectoryName; int theFlags; }; #endif /* #ifndef _MSC_VER */ #endif /* #ifndef ossimDirectoryData_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimDirectoryTree.h000066400000000000000000000037651352751253100234250ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: A brief description of the contents of the file. // //************************************************************************* // $Id: ossimDirectoryTree.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimDirectoryTree_HEADER #define ossimDirectoryTree_HEADER #include #include #include class OSSIMDLLEXPORT ossimDirectoryTree { public: ossimDirectoryTree(); ~ossimDirectoryTree(); bool open(const ossimFilename& dir); bool isOpened() const; bool getFirst(ossimFilename &filename, int flags = ossimDirectory::OSSIM_DIR_DEFAULT); // get next file in the enumeration started with either GetFirst() or // GetFirstNormal() bool getNext(ossimFilename &filename) ; void findAllFilesThatMatch(std::vector& result, const ossimString& regularExpressionPattern, int flags = ossimDirectory::OSSIM_DIR_DEFAULT); private: class OSSIMDLLEXPORT ossimDirData { public: ~ossimDirData() { if(theDirectory) { delete theDirectory; theFilename = ""; } } ossimDirData(ossimDirectory *aDir, const ossimFilename &filename) :theDirectory(aDir), theFilename(filename) { } ossimDirectory* theDirectory; ossimFilename theFilename; }; std::queue theDirectoryQueue; ossimDirData* theCurrentDirectoryData; int theFlags; void deleteAll(); void checkToPushDirectory(const ossimFilename &filename); // for now we will hide copy ossimDirectoryTree(const ossimDirectoryTree &rhs); const ossimDirectoryTree& operator =(const ossimDirectoryTree& rhs); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDisplayEventListener.h000066400000000000000000000014631352751253100247470ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id #ifndef ossimDisplayEventListener_HEADER #define ossimDisplayEventListener_HEADER #include class ossimDisplayListEvent; class ossimDisplayRefreshEvent; class OSSIMDLLEXPORT ossimDisplayEventListener : public ossimListener { public: ossimDisplayEventListener(); virtual ~ossimDisplayEventListener(); virtual void processEvent(ossimEvent& event); virtual void displayListEvent(ossimDisplayListEvent&); virtual void displayRefreshEvent(ossimDisplayRefreshEvent&); TYPE_DATA }; #endif /* End of "#ifndef ossimDisplayEventListener_HEADER". */ ossim-Miami-2.9.1/include/ossim/base/ossimDisplayInterface.h000066400000000000000000000020131352751253100240500ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimDisplayInterface.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimDisplayInterface_HEADER #define ossimDisplayInterface_HEADER #include #include class OSSIMDLLEXPORT ossimDisplayInterface { public: ossimDisplayInterface(); virtual ~ossimDisplayInterface(); /*! * Returns the display back to the caller */ virtual void* getDisplayDevice()=0; virtual void setTitle(const ossimString& title)=0; virtual void getTitle(ossimString& title)const=0; virtual ossimString getTitle()const; virtual void close()=0; virtual bool isOpen() const=0; virtual bool open()=0; virtual bool isMinimized()const=0; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDisplayListEvent.h000066400000000000000000000012741352751253100240750ustar00rootroot00000000000000#ifndef ossimDisplayListEvent_HEADER #define ossimDisplayListEvent_HEADER #include #include class OSSIMDLLEXPORT ossimDisplayListEvent : public ossimEvent { public: ossimDisplayListEvent(ossimObject* obj = NULL) :ossimEvent(obj, OSSIM_EVENT_DISPLAY_LIST_ID) { theDisplayIterator = theDisplayMap.end(); } void addDisplay(void* display); virtual ossimObject* dup()const { return new ossimDisplayListEvent(*this); } void* firstDisplay(); void* nextDisplay(); void clearList(); protected: std::map theDisplayMap; std::map::iterator theDisplayIterator; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDisplayRefreshEvent.h000066400000000000000000000005321352751253100245540ustar00rootroot00000000000000#ifndef ossimDisplayRefreshEvent_HEADER #define ossimDisplayRefreshEvent_HEADER #include #include class OSSIMDLLEXPORT ossimDisplayRefreshEvent : public ossimEvent { public: ossimDisplayRefreshEvent(ossimObject* obj = NULL) :ossimEvent(obj, OSSIM_EVENT_DISPLAY_REFRESH_ID) {} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDms.h000066400000000000000000000153401352751253100213540ustar00rootroot00000000000000//******************************************************************* // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class definition for Degrees Minutes Seconds (ossimDms) //******************************************************************* // $Id: ossimDms.h 19682 2011-05-31 14:21:20Z dburken $ #ifndef ossimDms_HEADER #define ossimDms_HEADER // #include #include /* for OSSIM_DLL macro */ #include class OSSIM_DLL ossimDms { public: // friend std::ostream& operator << (std::ostream& out, const ossimDms &dms); /** * Default constructor. Initializes to 0.0 degrees latitude. */ ossimDms(); /** * * Constructor ossimDms(double, bool) * * You can construct a DMS class with a decimal * degree and specify if its for the lat or lon. * * latFlag true its for the lat * false its for the lon * */ ossimDms(double someDegrees, bool latFlag = true); /** *` Constructor. You can specify the value in a formated * string. Example: * "45N" will set the decimal degree to 45 and will * set the lat flag to true * * "45W" will set the internal degree to negative and * set the lat flag to false. */ ossimDms(const std::string& value); /** * You can specify a number of different formats. * special characters: * * @ is replaced with a degree character. * ' minutes character * " seconds character * d replaced with degree portion * m replaced with minute portion * s replaced with second portion * c or C replaces with N/S or E/W * * examples for format string * * */ ossimString toString(const ossimString& formatString=ossimString(""))const; double getDegrees() const { return theDegrees; } bool getLatFlag() const { return theLatFlag; } /** * setDegrees(char*). Will allow you to set the internal * paramters through a string. examples: * * "45 5 6" will assume degrees minutes seconds * "45" will assume degrees. * "-45" * "45W" * * @return true on success, false if unhandled characters are found. */ bool setDegrees(const std::string& value); ossimDms& setDegrees(double degrees); ossimDms& setLatFlag(bool latFlag){theLatFlag = latFlag;return *this;} static const ossim_uint8 theDegreeSign; private: static const char* DEFAULT_FORMAT; static const char* SPACES; double theDegrees; bool theLatFlag; // This is a port of the dts written by Christine Hammond // into the OSSIM dms class. We will use this to aid in // formatting DMS data. mutable double theDecDegs;/* decimal part of degrees */ mutable bool theAfterDot;/* decimal values flag */ mutable bool theDoingSeconds; mutable int theIntDegs;/* integer part of double degrees */ mutable int theSign;/* what sign is degrees */ mutable double theWorking;/* degrees value to use during calc */ /** * char * function degree_to_string * * requires: dts.h * input: double precision, string, integer params * returns: pointer to a string * * purpose: to convert a double precision number "degrees" * to a character string based on the input "format" and a * flag indicating whether or not the degrees are latitude. * If 'lat_flag' is TRUE, then degrees are latitude, otherwise * they are longitude. default format: ddd mm.mmC * * returns: a pointer to a string which contains the formatted * degree value. * * written as part of the DIAL facility, G&G, WHOI * April 1992 * Christine L. Hammond ************************************************************************/ ossimString degree_to_string(double degrees, char format[], bool lat_flag)const; void calc_mins_or_secs(double *dd, std::string::const_iterator& formatIter, std::string& result)const; /** * integer function calc_mins_or_secs * * calculates minutes from degrees, seconds from minutes, * based on "format", returning the resultant string * in "res". "dd" is the part of 'degrees' that provides * the value to manipulate. the integer returned as the * value of this function is the number of places in the * format that have been parsed here, to be used in the * main function to advance the format-parsing pointer. */ int calc_mins_or_secs(double *dd, const char *format, char *res)const; /** * function setup_printf * the C library function sprintf takes as its second * argument, a format specifier. this function constructs * that specifier based on 'ival', an integer indicating * the number of d's or m's or s's seen in the group * just parsed. */ void setup_printf(int ival, char *fmt)const; /** * function set_default * * assigns a default format to be used as the template for * the conversion of the double precision value, degrees. * either an error was detected in parsing the format that * the user entered, or no format was entered at all. * also, clears the result string of any characters which * may have been placed therein prior to the call here. */ void set_default(char *fp, char *rp)const; /** * function init_values * initializes the global values used throughout the * function. see notes in header file. */ void init_values(double d)const; /** * double function string_to_degree * * requires: dts.h * input: string variable parameter * returns: double precision number * * purpose: to calculate a double precision number, representing * degrees latitude or longitude, given a string "cdegrees". * valid input consists of the following characters: * * +, -, N, n, S, s, E, e, W, w -- direction indicators * any digit [0-9] * a decimal point, '.' -- says decimal degrees follow * an ascii delimiter, for example ' ', TAB, '/' to * indicate that either minutes or seconds follow. * * output is a double precision number, which will be either * latitude or longitude degrees and decimal degree * * written as part of the DIAL facility, G&G, WHOI * April 1992 * Christine L. Hammond */ double string_to_degree(const std::string& cdegrees); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDoubleGridProperty.h000066400000000000000000000036041352751253100244160ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimDoubleGridProperty.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimDoubleGridProperty_HEADER #define ossimDoubleGridProperty_HEADER #include class OSSIMDLLEXPORT ossimDoubleGridProperty : public ossimProperty { public: ossimDoubleGridProperty(const ossimString& name = ossimString(""), int numberOfRows = 0, int numberOfCols = 0, const std::vector& values = std::vector()); ossimDoubleGridProperty(const ossimDoubleGridProperty& rhs); virtual ~ossimDoubleGridProperty(); ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; void clearConstraints(); /*! * Setting both values to -1 will say no constraints. * if min is constrained and max not then it will not allow * the cols to grow any larger than the passed in max. * * If the min is -1 and max not then it will not exceed the * max number of cols */ void setColConstraints(int minNumberOfCols, int maxNumberOfCols); void setRowConstraints(int minNumberOfRows, int maxNumberOfRows); void setContraints(int minNumberOfRows, int maxNumberOfRows, int minNumberOfCols, int maxNumberOfCols); ossim_uint32 getNumberOfRows()const; ossim_uint32 getNumberOfCols()const; double getValue(ossim_uint32 row, ossim_uint32 col)const; protected: int theMinNumberOfCols; int theMaxNumberOfCols; int theMinNumberOfRows; int theMaxNumberOfRows; std::vector< std::vector > theValues; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDpt.h000066400000000000000000000114061352751253100213570ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration for ossimDpt. // Used to represent an double point containing an x and y data member. // //******************************************************************* // $Id: ossimDpt.h 19793 2011-06-30 13:26:56Z gpotts $ #ifndef ossimDpt_HEADER #define ossimDpt_HEADER #include #include #include #include #include // Forward class declarations. class ossimIpt; class ossimFpt; class ossimDpt3d; class ossimGpt; class OSSIMDLLEXPORT ossimDpt { public: ossimDpt() : x(0), y(0) {} ossimDpt(double anX, double aY) : x(anX), y(aY) {} // trust the default generated copy-constructor // ossimDpt(const ossimDpt& pt) = default; ossimDpt(const ossimFpt& pt); ossimDpt(const ossimIpt& pt); ossimDpt(const ossimDpt3d &pt); ossimDpt(const ossimGpt &pt); // assigns lat, lon only // trust the default generated copy-constructor // const ossimDpt& operator=(const ossimDpt&) = default; const ossimDpt& operator=(const ossimFpt&); const ossimDpt& operator=(const ossimIpt&); const ossimDpt& operator=(const ossimDpt3d&); const ossimDpt& operator=(const ossimGpt&); // assigns lat, lon only bool operator==(const ossimDpt& pt) const { return ( ossim::almostEqual(x, pt.x) && ossim::almostEqual(y, pt.y) ); } bool operator!=(const ossimDpt& pt) const { return !(*this == pt ); } void makeNan(){x = ossim::nan(); y=ossim::nan();} bool hasNans()const { return (ossim::isnan(x) || ossim::isnan(y)); } bool isNan()const { return (ossim::isnan(x) && ossim::isnan(y)); } /*! * METHOD: length() * Returns the RSS of the components. */ double length() const { return sqrt(x*x + y*y); } //*** // OPERATORS: +, -, +=, -= // Point add/subtract with other point: //*** ossimDpt operator+(const ossimDpt& p) const { return ossimDpt(x+p.x, y+p.y); } ossimDpt operator-(const ossimDpt& p) const { return ossimDpt(x-p.x, y-p.y); } const ossimDpt& operator+=(const ossimDpt& p) { x += p.x; y += p.y; return *this; } const ossimDpt& operator-=(const ossimDpt& p) { x -= p.x; y -= p.y; return *this; } //*** // OPERATORS: *, / // Scale point components by scalar: //*** ossimDpt operator*(const double& d) const { return ossimDpt(d*x, d*y); } ossimDpt operator/(const double& d) const { return ossimDpt(x/d, y/d); } const ossimDpt& operator*=(const double& d) { x*=d; y*=d; return *this; } /** Dot product */ ossim_float64 operator*(const ossimDpt& pt)const { return (x*pt.x+y*pt.y); } std::ostream& print(std::ostream& os, ossim_uint32 precision=15) const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& os, const ossimDpt& pt); /** * @param precision Output floating point precision. * * @return ossimString representing point. * * Output format: ( 30.00000000000000, -90.00000000000000 ) * --------x-------- ---------y-------- */ ossimString toString(ossim_uint32 precision=15) const; /** * Initializes this point from string. This method opens an std::istream to * s and then calls operator>>. * * Expected format: ( 30.00000000000000, -90.00000000000000 ) * --------x-------- ---------y-------- * * @param s String to initialize from. * * @see operator>> */ void toPoint(const std::string& s); /** * Method to input the formatted string of the "operator<<". * * Expected format: ( 30.00000000000000, -90.00000000000000 ) * --------x-------- ---------y-------- * * This method starts by doing a "makeNan" on pt. So if anything goes * wrong with the stream or parsing pt could be all or partially nan. * * @param is Input stream std::istream to formatted text. * @param pt osimDpt to be initialized from stream. * @return std::istream pass in. */ friend OSSIMDLLEXPORT std::istream& operator>>(std::istream& is, ossimDpt& pt); bool isEqualTo(const ossimDpt& rhs, ossimCompareType compareType=OSSIM_COMPARE_FULL)const; /** * Returns the average of x and y */ double mean() const { return (x + y) / 2.0; } //*** // Public data members: //*** union {double x; double samp; double u; double lon;}; union {double y; double line; double v; double lat;}; }; #endif /* #ifndef ossimDpt_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimDpt3d.h000066400000000000000000000077351352751253100216200ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // // Contains class declaration for dpt3d // Used to represent a 3d double point containing an x, y and z data member. //******************************************************************* // $Id: ossimDpt3d.h 22937 2014-11-01 11:30:13Z okramer $ #ifndef ossimDpt3d_HEADER #define ossimDpt3d_HEADER #include #include #include #include /* for ossim::isnan */ #include class ossimIpt; class ossimDpt; class OSSIMDLLEXPORT ossimDpt3d { public: friend OSSIMDLLEXPORT std::ostream & operator <<(std::ostream &out, const ossimDpt3d &rhs); ossimDpt3d(const double &aX=0, const double &aY=0, const double &aZ=0) :x(aX), y(aY), z(aZ) {} ossimDpt3d(const ossimDpt &aPt); ossimDpt3d(const ossimIpt &aPt); //! Argument gPt is converted to WGS84 datum before coordinates are stored in x, y, z. //! Likewise, ossimGpt has a constructor that accepts an ossimDpt3d with assumed WGS84 datum. ossimDpt3d(const ossimGpt &gPt); ossimDpt3d(const ossimColumnVector3d &pt) : x(pt[0]), y(pt[1]), z(pt[2]) {} bool operator ==(const ossimDpt3d &rhs) const { return ( (x == rhs.x) && (y == rhs.y) && (z == rhs.z)); } bool operator !=(const ossimDpt3d &rhs) const { return ( (x != rhs.x) || (y != rhs.y) || (z != rhs.z) ); } void makeNan(){x = ossim::nan(); y=ossim::nan(); z=ossim::nan();} bool hasNans()const { return (ossim::isnan(x) || ossim::isnan(y) || ossim::isnan(z)); } /*! * METHOD: length() * Returns the RSS of the components. */ double length() const { return std::sqrt(x*x + y*y + z*z); } double length2() const { return x*x + y*y + z*z; } //*** // OPERATORS: +, -, +=, -= // Point add/subtract with other point: //*** ossimDpt3d operator+(const ossimDpt3d& p) const { return ossimDpt3d(x+p.x, y+p.y, z+p.z); } ossimDpt3d operator-(const ossimDpt3d& p) const { return ossimDpt3d(x-p.x, y-p.y, z-p.z); } const ossimDpt3d& operator+=(const ossimDpt3d& p) { x += p.x; y += p.y; z += p.z; return *this; } const ossimDpt3d& operator-=(const ossimDpt3d& p) { x -= p.x; y -= p.y; z -= p.z; return *this; } //*** // OPERATORS: *, / // Scale point components by scalar: //*** ossimDpt3d operator*(const double& d) const { return ossimDpt3d(d*x, d*y, d*z); } ossimDpt3d operator/(const double& d) const { return ossimDpt3d(x/d, y/d, z/d); } void operator /=(double value) { x /= value; y /= value; z /= value; } void operator *=(double value) { x *= value; y *= value; z *= value; } double operator *(const ossimDpt3d& src)const { return (x*src.x + y*src.y + z*src.z); } inline const ossimDpt3d operator ^ (const ossimDpt3d& rhs) const { return ossimDpt3d(y*rhs.z-z*rhs.y, z*rhs.x-x*rhs.z , x*rhs.y-y*rhs.x); } /** * @brief To string method. * * @param precision Output floating point precision. * * @return std::string representing point. * * Output format: * ( 0.0000000, 0.0000000, 0.00000000 ) * -----x---- -----y---- ------z---- */ std::string toString(ossim_uint32 precision=15) const; /** * @brief Initializes this point from string. * * Expected format: * * ( 0.0000000, 0.0000000, 0.00000000 ) * -----x---- -----y---- ------z---- * * @param s String to initialize from. */ void toPoint(const std::string& s); double x; double y; double z; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimDrect.h000066400000000000000000000646411352751253100217020ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration for drect. // Container class for four double points representing a rectangle. // //******************************************************************* // $Id: ossimDrect.h 22197 2013-03-12 02:00:55Z dburken $ #ifndef ossimDrect_HEADER #define ossimDrect_HEADER #include #include #include #include #include //*** // NOTE: A word on corner points... // // There is the concept of "pixel is area" and "pixel is point". // - Pixel is area means the (x,y) pixel coordinate refers to the upper left // corner of the pixel, NOT the center of the pixel. // - Pixel is point means the (x,y) pixel coordinate refers to the center // of the pixel, NOT the upper left corner. // // For the uniformity purposes, all pixel points should be in the // "pixel is point" form; therefore, the (x,y) point should represent the // CENTER of the pixel. //*** //*** // Forward class declarations. //*** class ossimIrect; class ossimPolygon; class ossimKeywordlist; //******************************************************************* // CLASS: ossimDrect //******************************************************************* class OSSIMDLLEXPORT ossimDrect { public: enum { UPPER_LEFT = 1, LOWER_LEFT = 2, LOWER_RIGHT = 4, UPPER_RIGHT = 8 }; ossimDrect() : theUlCorner(0.0, 0.0), theUrCorner(0.0, 0.0), theLrCorner(0.0, 0.0), theLlCorner(0.0, 0.0), theOrientMode(OSSIM_LEFT_HANDED) {} ossimDrect(const ossimDpt& ul_corner, const ossimDpt& lr_corner, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED) : theUlCorner(ul_corner), theUrCorner(lr_corner.x, ul_corner.y), theLrCorner(lr_corner), theLlCorner(ul_corner.x, lr_corner.y), theOrientMode(mode) { } ossimDrect(const double& ul_corner_x, const double& ul_corner_y, const double& lr_corner_x, const double& lr_corner_y, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED) : theUlCorner(ul_corner_x, ul_corner_y), theUrCorner(lr_corner_x, ul_corner_y), theLrCorner(lr_corner_x, lr_corner_y), theLlCorner(ul_corner_x, lr_corner_y), theOrientMode(mode) {} ossimDrect(const ossimDrect& rect) : theUlCorner(rect.ul()), theUrCorner(rect.ur()), theLrCorner(rect.lr()), theLlCorner(rect.ll()), theOrientMode(rect.orientMode()) {} ossimDrect(const ossimIrect& rect); /*! * Must compute a bounding rect given a collection of points or polygon: */ ossimDrect(const std::vector& points, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED); ossimDrect(const ossimDpt& p1, const ossimDpt& p2, const ossimDpt& p3, const ossimDpt& p4, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED); ossimDrect(const ossimPolygon& polygon, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED); /** destructor */ ~ossimDrect(); //! Constructs an Drect surrounding the specified point, and of specified size. ossimDrect(const ossimDpt& center, const double& size_x, const double& size_y, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED); inline const ossimDrect& operator= (const ossimDrect& rect); const ossimDrect& operator= (const ossimIrect& rect); inline bool operator!= (const ossimDrect& rect) const; inline bool operator== (const ossimDrect& rect) const; friend ossimDrect operator*(double scalar, const ossimDrect& rect) { ossimDpt ul(rect.theUlCorner.x*scalar, rect.theUlCorner.y*scalar); if(rect.theOrientMode == OSSIM_LEFT_HANDED) { return ossimDrect(ul.x, ul.y, ul.x+rect.width()*scalar-1, ul.y+rect.height()*scalar-1, rect.theOrientMode); } return ossimDrect(ul.x, ul.y, ul.x+rect.width()*scalar-1, ul.y-(rect.height()*scalar-1), rect.theOrientMode); } const ossimDrect& operator *=(double scalar) { ossimDpt ul(theUlCorner.x*scalar, theUlCorner.y*scalar); if(theOrientMode == OSSIM_LEFT_HANDED) { *this = ossimDrect(ul.x, ul.y, (ul.x+width()*scalar-1), (ul.y+height()*scalar-1), theOrientMode); } else { *this = ossimDrect(ul.x, ul.y, (ul.x+width()*scalar-1), (ul.y-(height()*scalar-1)), theOrientMode); } return *this; } ossimDrect operator *(double scalar)const { ossimDpt ul((theUlCorner.x*scalar), (theUlCorner.y*scalar)); if(theOrientMode == OSSIM_LEFT_HANDED) { return ossimDrect(ul.x, ul.y, (ul.x+width()*scalar-1), (ul.y+height()*scalar-1), theOrientMode); } return ossimDrect(ul.x, ul.y, (ul.x+width()*scalar-1), ul.y-(height()*scalar-1), theOrientMode); } const ossimDrect& operator *=(const ossimDpt& scalar) { ossimDpt ul((theUlCorner.x*scalar.x), (theUlCorner.y*scalar.y)); if(theOrientMode == OSSIM_LEFT_HANDED) { *this = ossimDrect(ul.x, ul.y, (ul.x+width()*scalar.x - 1), (ul.y+height()*scalar.y - 1), theOrientMode); } else { *this = ossimDrect(ul.x, ul.y, (ul.x+width()*scalar.x - 1), (ul.y-(height()*scalar.y - 1)), theOrientMode); } return *this; } ossimDrect operator *(const ossimDpt& scalar)const { ossimDpt ul((theUlCorner.x*scalar.x), (theUlCorner.y*scalar.y)); if(theOrientMode == OSSIM_LEFT_HANDED) { return ossimDrect(ul.x, ul.y, (ul.x+width()*scalar.x-1), (ul.y+height()*scalar.y-1), theOrientMode); } return ossimDrect(ul.x, ul.y, (ul.x+width()*scalar.x-1), (ul.y-(height()*scalar.y-1)), theOrientMode); } const ossimDrect& operator +=(const ossimDpt& shift) { ossimDpt ul((theUlCorner.x+shift.x), (theUlCorner.y+shift.y)); if(theOrientMode == OSSIM_LEFT_HANDED) { *this = ossimDrect(ul.x, ul.y, ul.x+width()-1, ul.y+height()-1, theOrientMode); } else { *this = ossimDrect(ul.x, ul.y, ul.x+width()-1, ul.y-(height()-1), theOrientMode); } return *this; } const ossimDrect& operator -=(const ossimDpt& shift) { ossimDpt ul((theUlCorner.x-shift.x), (theUlCorner.y-shift.y)); if(theOrientMode == OSSIM_LEFT_HANDED) { *this = ossimDrect(ul.x, ul.y, ul.x+width()-1, ul.y+height()-1, theOrientMode); } else { *this = ossimDrect(ul.x, ul.y, ul.x+width()-1, ul.y-(height()-1), theOrientMode); } return *this; } ossimDrect operator +(const ossimDpt& shift)const { ossimDpt ul((theUlCorner.x+shift.x), (theUlCorner.y+shift.y)); if(theOrientMode == OSSIM_LEFT_HANDED) { return ossimDrect(ul.x, ul.y, ul.x+width()-1, ul.y+height()-1, theOrientMode); } else { return ossimDrect(ul.x, ul.y, ul.x+width()-1, ul.y-(height()-1), theOrientMode); } } ossimDrect operator -(const ossimDpt& shift)const { ossimIpt ul(ossim::round(theUlCorner.x-shift.x), ossim::round(theUlCorner.y-shift.y)); if(theOrientMode == OSSIM_LEFT_HANDED) { return ossimDrect(ul.x, ul.y, ul.x+width()-1, ul.y+height()-1, theOrientMode); } else { return ossimDrect(ul.x, ul.y, ul.x+width()-1, ul.y-(height()-1), theOrientMode); } } const ossimDpt& ul() const { return theUlCorner; } const ossimDpt& ur() const { return theUrCorner; } const ossimDpt& lr() const { return theLrCorner; } const ossimDpt& ll() const { return theLlCorner; } const ossimDrect& changeOrientationMode(ossimCoordSysOrientMode mode) { // if we are already in the orientation then return // if(mode == theOrientMode) return *this; if(mode == OSSIM_LEFT_HANDED) { // we must be right handed so change to left handed *this = ossimDrect(theUlCorner.x, theLlCorner.y, theLrCorner.x, theUlCorner.y, OSSIM_LEFT_HANDED); } else { // we must be left handed so change to RIGHT handed *this = ossimDrect(theUlCorner.x, theLlCorner.y, theLrCorner.x, theUlCorner.y, OSSIM_RIGHT_HANDED); } theOrientMode = mode; return *this; } void getBounds(double& minx, double& miny, double& maxx, double& maxy)const { minx = theUlCorner.x; maxx = theUrCorner.x; if(theOrientMode == OSSIM_LEFT_HANDED) { miny = theUlCorner.y; maxy = theLrCorner.y; } else { maxy = theUlCorner.y; miny = theLrCorner.y; } } void makeNan() { theUlCorner.makeNan(); theLlCorner.makeNan(); theLrCorner.makeNan(); theUrCorner.makeNan(); } bool hasNans()const{ return (theUlCorner.hasNans() || theLlCorner.hasNans() || theLrCorner.hasNans() || theUrCorner.hasNans());} bool isNan()const{ return (theUlCorner.hasNans() && theLlCorner.hasNans() && theLrCorner.hasNans() && theUrCorner.hasNans());} double area()const { return width()*height(); } //*** // This class supports both left and right-handed coordinate systems. For // both, the positive x-axis extends to the "right". //*** ossimCoordSysOrientMode orientMode() const { return theOrientMode; } void setOrientMode(ossimCoordSysOrientMode mode) { theOrientMode = mode; } /*! * Sets the upper left corner to "pt". Adjusts the remaining corners * accordingly. */ inline void set_ul(const ossimDpt& pt); /*! * Sets the upper right corner to "pt". Adjusts the remaining corners * accordingly. */ inline void set_ur(const ossimDpt& pt); /*! * Sets the lower right corner to "pt". Adjusts the remaining corners * accordingly. */ inline void set_lr(const ossimDpt& pt); /*! * Sets the lower left corner to "pt". Adjusts the remaining corners * accordingly. */ inline void set_ll(const ossimDpt& pt); /*! * Sets the upper left x. Adjusts the remaining corners accordingly. */ inline void set_ulx(ossim_float64 x); /*! * Sets the upper left y. Adjusts the remaining corners accordingly. */ inline void set_uly(ossim_float64 y); /*! * Sets the upper right x. Adjusts the remaining corners accordingly. */ inline void set_urx(ossim_float64 x); /*! * Sets the upper right y. Adjusts the remaining corners accordingly. */ inline void set_ury(ossim_float64 y); /*! * Sets the lower right x. Adjusts the remaining corners accordingly. */ inline void set_lrx(ossim_float64 x); /*! * Sets the lower right y. Adjusts the remaining corners accordingly. */ inline void set_lry(ossim_float64 y); /*! * Sets the lower left x. Adjusts the remaining corners accordingly. */ inline void set_llx(ossim_float64 x); /*! * Sets the lower left y. Adjusts the remaining corners accordingly. */ inline void set_lly(ossim_float64 y); /*! * METHOD: initBoundingRect(points) * Initializes this rect to the bounding rect containing all points in the * collection passed in. */ void initBoundingRect(const std::vector& points); /*! * Returns true if "pt" falls within rectangle. Fall on an edge is also * considered to be within. The edge is expanded by epsilon value so any value * within epsilon is inside */ bool pointWithin(const ossimDpt& pt, double epsilon=0.0) const; /*! * Returns true if "pt" falls within rectangle. Fall on an edge is also * considered to be within. */ bool pointWithin(const ossimFpt& pt, double epsilon=0.0) const; /*! * Returns true if any portion of an input rectangle "rect" intersects * "this" rectangle. */ bool intersects(const ossimDrect& rect) const; /*! * Returns true if "this" rectangle is contained completely within the * input rectangle "rect". */ bool completely_within(const ossimDrect& rect) const; ossimCoordSysOrientMode orientationMode()const{return theOrientMode;} /*! * Returns the height of a rectangle. */ ossim_float64 height() const { return fabs(theLlCorner.y - theUlCorner.y) + 1.0; } /*! * Returns the width of a rectangle. */ ossim_float64 width() const { return fabs(theLrCorner.x - theLlCorner.x) + 1.0; } ossimDpt size() const { return ossimDpt(width(), height()); } /*! * Stretches this rectangle out to integer boundaries. */ void stretchOut(); /*! * Will stretch the rect to the passed in tiled boundary. */ void stretchToTileBoundary(const ossimDpt& widthHeight); const ossimDrect& expand(const ossimDpt& padding); /** * @return ossimString representing ossimIrect. * * Format: ( 30, -90, 512, 512, [LH|RH] ) * -x- -y- -w- -h- -Right or left handed- * * where: * x and y are origins either upper left if LEFT HANDED (LH) or * lower left if RIGHT HANDED (RH) * w and h are width and height respectively * The last value is LH or RH to indicate LeftHanded or RightHanded * */ ossimString toString()const; /** * expected Format: form 1: ( 30, -90, 512, 512, [LH|RH] ) * -x- -y- -w- -h- -Right or left handed- * * form 2: ( 30, -90, 512, 512) * -x- -y- -w- -h- * * NOTE: Form 2 assumes Left handed were x,y is origin upper left and y positive down. * * This method starts by doing a "makeNan" on rect. * * @param rectString String to initialize from. * @return true or false to indicate successful parsing. */ bool toRect(const ossimString& rectString); bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /*! * Will subdivide this rect into four partitions. */ void splitToQuad(ossimDrect& ulRect, ossimDrect& urRect, ossimDrect& lrRect, ossimDrect& llRect); /*! * Finds the point on the rect boundary that is closest to the arg_point. Closest is defined as * the minimum perpendicular distance. */ ossimDpt findClosestEdgePointTo(const ossimDpt& arg_point) const; ossimDrect clipToRect(const ossimDrect& rect)const; inline ossimDpt midPoint()const; void print(std::ostream& os) const; ossimDrect combine(const ossimDrect& rect)const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& os, const ossimDrect& rect); bool clip(ossimDpt &p1, ossimDpt &p2)const; static long getCode(const ossimDpt& aPoint, const ossimDrect& clipRect); private: enum ossimCohenSutherlandClipCodes { NONE = 0, LEFT = 1, RIGHT = 2, BOTTOM = 4, TOP = 8 }; //*** // Private data members representing the rectangle corners. //*** ossimDpt theUlCorner; ossimDpt theUrCorner; ossimDpt theLrCorner; ossimDpt theLlCorner; ossimCoordSysOrientMode theOrientMode; }; //******************************************************************* // Inline Method: ossimDrect::operator=(ossimDrect) //******************************************************************* inline const ossimDrect& ossimDrect::operator=(const ossimDrect& rect) { if (this != &rect) { theUlCorner = rect.theUlCorner; theUrCorner = rect.theUrCorner; theLrCorner = rect.theLrCorner; theLlCorner = rect.theLlCorner; theOrientMode = rect.theOrientMode; } return *this; } //******************************************************************* // Inline Method: ossimDrect::operator!= //******************************************************************* inline bool ossimDrect::operator!=(const ossimDrect& rect) const { return ( (theUlCorner != rect.theUlCorner) || (theUrCorner != rect.theUrCorner) || (theLrCorner != rect.theLrCorner) || (theLlCorner != rect.theLlCorner) || (theOrientMode != rect.theOrientMode)); } //******************************************************************* // Inline Method: ossimDrect::operator== //******************************************************************* inline bool ossimDrect::operator==(const ossimDrect& rect) const { return ( (theUlCorner == rect.theUlCorner) && (theUrCorner == rect.theUrCorner) && (theLrCorner == rect.theLrCorner) && (theLlCorner == rect.theLlCorner) && (theOrientMode == rect.theOrientMode)); } //******************************************************************* // Inline Method: ossimDrect::set_ul //******************************************************************* inline void ossimDrect::set_ul(const ossimDpt& pt) { theUlCorner = pt; theUrCorner.y = pt.y; theLlCorner.x = pt.x; } //******************************************************************* // Inline Method: ossimDrect::set_ur //******************************************************************* inline void ossimDrect::set_ur(const ossimDpt& pt) { theUrCorner = pt; theUlCorner.y = pt.y; theLrCorner.x = pt.x; } //******************************************************************* // Inline Method: ossimDrect::set_lr //******************************************************************* inline void ossimDrect::set_lr(const ossimDpt& pt) { theLrCorner = pt; theUrCorner.x = pt.x; theLlCorner.y = pt.y; } //******************************************************************* // Inline Method: ossimDrect::set_ll //******************************************************************* inline void ossimDrect::set_ll(const ossimDpt& pt) { theLlCorner = pt; theUlCorner.x = pt.x; theLrCorner.y = pt.y; } //******************************************************************* // Inline Method: ossimDrect::set_ulx //******************************************************************* inline void ossimDrect::set_ulx(ossim_float64 x) { theUlCorner.x = x; theLlCorner.x = x; } //******************************************************************* // Inline Method: ossimDrect::set_uly //******************************************************************* inline void ossimDrect::set_uly(ossim_float64 y) { theUlCorner.y = y; theUrCorner.y = y; } //******************************************************************* // Inline Method: ossimDrect::set_urx //******************************************************************* inline void ossimDrect::set_urx(ossim_float64 x) { theUrCorner.x = x; theLrCorner.x = x; } //******************************************************************* // Inline Method: ossimDrect::set_ury //******************************************************************* inline void ossimDrect::set_ury(ossim_float64 y) { theUrCorner.y = y; theUlCorner.y = y; } //******************************************************************* // Inline Method: ossimDrect::set_lrx //******************************************************************* inline void ossimDrect::set_lrx(ossim_float64 x) { theLrCorner.x = x; theUrCorner.x = x; } //******************************************************************* // Inline Method: ossimDrect::set_lry //******************************************************************* inline void ossimDrect::set_lry(ossim_float64 y) { theLrCorner.y = y; theLlCorner.y = y; } //******************************************************************* // Inline Method: ossimDrect::set_llx //******************************************************************* inline void ossimDrect::set_llx(ossim_float64 x) { theLlCorner.x = x; theUlCorner.x = x; } //******************************************************************* // Inline Method: ossimDrect::set_lly //******************************************************************* inline void ossimDrect::set_lly(ossim_float64 y) { theLlCorner.y = y; theLrCorner.y = y; } //******************************************************************* // Inline Method: ossimDrect::pointWithin(const ossimDpt& pt) //******************************************************************* inline bool ossimDrect::pointWithin(const ossimDpt& pt, double epsilon) const { if (theOrientMode == OSSIM_LEFT_HANDED) { return ((pt.x >= (ul().x-epsilon)) && (pt.x <= (ur().x+epsilon)) && (pt.y >= (ul().y-epsilon)) && (pt.y <= (ll().y+epsilon))); } return ((pt.x >= (ul().x-epsilon)) && (pt.x <= (ur().x+epsilon)) && (pt.y <= (ul().y+epsilon)) && (pt.y >= (ll().y-epsilon))); } //******************************************************************* // Inline Method: ossimDrect::pointWithin(const ossimFpt& pt) //******************************************************************* inline bool ossimDrect::pointWithin(const ossimFpt& pt, double epsilon) const { if (theOrientMode == OSSIM_LEFT_HANDED) { return ((pt.x >= (ul().x-epsilon)) && (pt.x <= (ur().x+epsilon)) && (pt.y >= (ul().y-epsilon)) && (pt.y <= (ll().y+epsilon))); } return ((pt.x >= (ul().x-epsilon)) && (pt.x <= (ur().x+epsilon)) && (pt.y <= (ul().y+epsilon)) && (pt.y >= (ll().y-epsilon))); } //******************************************************************* // Inline Method: ossimDrect::midPoint() //******************************************************************* inline ossimDpt ossimDrect::midPoint()const { return ossimDpt( (ul().x + ur().x + ll().x + lr().x)*.25, (ul().y + ur().y + ll().y + lr().y)*.25); } //******************************************************************* // Inline Method: ossimDrect::combine(const ossimDrect& rect) //******************************************************************* inline ossimDrect ossimDrect::combine(const ossimDrect& rect)const { if(rect.hasNans() || hasNans()) { ossimDrect result; result.makeNan(); return result; } if (theOrientMode != rect.theOrientMode) return(*this); ossimDpt ulCombine; ossimDpt lrCombine; if(theOrientMode == OSSIM_LEFT_HANDED) { ulCombine.x = ((ul().x <= rect.ul().x)?ul().x:rect.ul().x); ulCombine.y = ((ul().y <= rect.ul().y)?ul().y:rect.ul().y); lrCombine.x = ((lr().x >= rect.lr().x)?lr().x:rect.lr().x); lrCombine.y = ((lr().y >= rect.lr().y)?lr().y:rect.lr().y); } else { ulCombine.x = ((ul().x <= rect.ul().x)?ul().x:rect.ul().x); ulCombine.y = ((ul().y >= rect.ul().y)?ul().y:rect.ul().y); lrCombine.x = ((lr().x >= rect.lr().x)?lr().x:rect.lr().x); lrCombine.y = ((lr().y <= rect.lr().y)?lr().y:rect.lr().y); } return ossimDrect(ulCombine, lrCombine, theOrientMode); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimDuration.h000066400000000000000000000102701352751253100224130ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id$ #ifndef ossimDuration_HEADER #define ossimDuration_HEADER #include #include #include #include class OSSIM_DLL ossimDuration { public: /** * This will take an iso8601 encoded duration string and parse out * the individual values */ ossimDuration(const ossimString& iso8601Duration = ossimString("")); /** * zero out all fields */ void clearFields(); /** * This will take an iso8601 encoded duration stream and parse out * the individual values it will stop when a blank character or whitespace is found */ bool readIso8601Encoding(std::istream& in); /** * This will take an iso8601 encoded duration stream and parse out * the individual values it will stop when a blank character or whitespace is found */ bool setByIso8601DurationString(const ossimString& iso8601Duration); /** * Will take the field values and encode into a iso8601 string format. * Note, anything that is 0 will not be output. * */ void toIso8601DurationString(ossimString& result); /** * this will not use the months field or the years field but will use all other * fields to calculate a total value in seconds. We can not determine leap years * and how many days are in a month so those are omitted and so this serves as * a utility method to just calculate the total seconds if you give a duration string * that contains only one or all or any of the following: weeks, days, minutes, hours, * and/or seconds. * * If the sign is set to negative it will return a negative value. */ ossim_float64 toSeconds()const; void setSign(ossim_int32 value) { theSign = ((value < 0)?-1:1); } /** * returns the sign. Should be either -1 or 1 for the return */ ossim_int32 sign()const { return theSign; } void setYears(ossim_uint64 value) { theYears = value; } ossim_int64 years()const { return theYears; } void setMonths(ossim_uint64 value) { theMonths = value; } ossim_int64 months()const { return theMonths; } void setWeeks(ossim_uint64 value) { theWeeks = value; } ossim_int64 weeks()const { return theWeeks; } void setDays(ossim_uint64 value) { theDays = value; } ossim_int64 days()const { return theDays; } void setHours(ossim_uint64 value) { theHours = value; } ossim_int64 hours()const { return theHours; } void setMinutes(ossim_uint64 value) { theMinutes = value; } ossim_int64 minutes()const { return theMinutes; } void setSeconds(ossim_float64 value) { theSeconds = value; } ossim_float64 seconds()const { return theSeconds; } /** * Sets all values in one call */ void setAll(ossim_int32 signValue, ossim_uint64 yearsValue, ossim_uint64 monthsValue, ossim_uint64 weeksValue, ossim_uint64 daysValue, ossim_uint64 hoursValue, ossim_uint64 minutesValue, ossim_float64 secondsValue) { theSign = ((signValue < 0)?-1:1); theYears = yearsValue; theMonths = monthsValue; theWeeks = weeksValue; theDays = daysValue; theHours = hoursValue; theMinutes = minutesValue; theSeconds = secondsValue; } protected: ossim_int32 theSign; // indicates -1 for negative and anything else is positive ossim_int64 theYears; // number of years ossim_int64 theMonths; // number of months ossim_int64 theWeeks; // number of months ossim_int64 theDays; // number of days ossim_int64 theHours; // number of hours ossim_int64 theMinutes; // number of minutes ossim_float64 theSeconds; // umber of Seconds }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimEbcdicToAscii.h000066400000000000000000000030221352751253100232500ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Utility class to convert to/from EBCDIC/ASCII // // ASCII = American National Standard Code for Information Interchange // // EBCDIC = Extended Binary Coded Decimal Interchange Code // // $Id: ossimEbcdicToAscii.h 9094 2006-06-13 19:12:40Z dburken $ //---------------------------------------------------------------------------- #ifndef ossimEbcdicToAscii_HEADER #define ossimEbcdicToAscii_HEADER #include class OSSIM_DLL ossimEbcdicToAscii { public: /** default constructor */ ossimEbcdicToAscii(); /** destructor */ ~ossimEbcdicToAscii(); /** * @brief Converts ascii character c to ebcdic character. * * @param c ascii character to convert. * * @return ebcdic character. */ ossim_uint8 asciiToEbcdic(ossim_uint8 c) const; /** * @brief Converts ebcdic character c to ascii character. * * @param c ebcdic character to convert. * * @return ascii character. */ ossim_uint8 ebcdicToAscii(ossim_uint8 c) const; /** * @brief Converts ebcdic character string "str" to ascii characters. * * @param str ebcdic character string to convert. * * @param size Number of characters to convert. Note that "str" should be * at least >= size. */ void ebcdicToAscii(char* str, ossim_uint32 size) const; }; #endif /* ossimEbcdicToAcsii_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimEcefPoint.h000066400000000000000000000133421352751253100225050ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimEcefPoint.h // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of a 3D point object in the Earth-centered, earth // fixed (ECEF) coordinate system. // // SOFTWARE HISTORY: //> // 08Aug2001 Oscar Kramer (http://www.oscarkramer.com) // Initial coding. //< //***************************************************************************** // $Id: ossimEcefPoint.h 20043 2011-09-06 15:00:55Z oscarkramer $ #ifndef ossimEcefPoint_HEADER #define ossimEcefPoint_HEADER #include #include #include #include #include #include class ossimGpt; class ossimEcefVector; class ossimDpt3d; //***************************************************************************** // CLASS: ossimEcefPoint // //***************************************************************************** class OSSIMDLLEXPORT ossimEcefPoint { public: /*! * CONSTRUCTORS: */ ossimEcefPoint() : theData(0,0,0) {} // Default definition is perfect // ossimEcefPoint(const ossimEcefPoint& copy_this) = default; ossimEcefPoint(const ossimGpt& convert_this); ossimEcefPoint(const double& x, const double& y, const double& z) : theData(x, y, z) {} ossimEcefPoint(const ossimColumnVector3d& assign_this) : theData(assign_this) {} ossimEcefPoint(const NEWMAT::ColumnVector& assign_this) : theData(assign_this) {} ossimEcefPoint(const ossimDpt3d& pt); void makeNan() { theData[0] = ossim::nan(); theData[1] = ossim::nan(); theData[2] = ossim::nan(); } bool hasNans()const { return ( ossim::isnan(theData[0]) || ossim::isnan(theData[1]) || ossim::isnan(theData[2]) ); } bool isNan()const { return ( ossim::isnan(theData[0]) && ossim::isnan(theData[1]) && ossim::isnan(theData[2]) ); } /*! * OPERATORS: */ ossimEcefVector operator- (const ossimEcefPoint&) const; ossimEcefPoint operator+ (const ossimEcefVector&) const; ossimEcefPoint operator- (const ossimEcefVector&) const; // ossimEcefPoint& operator= (const ossimEcefPoint&) = default; bool operator==(const ossimEcefPoint&) const; // inline bool operator!=(const ossimEcefPoint&) const; // inline /*! * COMPONENT ACCESS METHODS: */ double x() const { return theData[0]; } double& x() { return theData[0]; } double y() const { return theData[1]; } double& y() { return theData[1]; } double z() const { return theData[2]; } double& z() { return theData[2]; } double& operator[](int idx){return theData[idx];} const double& operator[](int idx)const{return theData[idx];} const ossimColumnVector3d& data() const { return theData; } ossimColumnVector3d& data() { return theData; } double getMagnitude() const { return theData.magnitude(); } double magnitude()const { return theData.magnitude(); } double length()const { return theData.magnitude(); } double normalize() { double result = magnitude(); if(result > 1e-15) { theData[0]/=result; theData[1]/=result; theData[2]/=result; } return result; } /** * @brief To string method. * * @param precision Output floating point precision. * * @return ossimString representing point. * * Output format: * ( 0.0000000, 0.0000000, 0.00000000 ) * -----x---- -----y---- ------z---- */ ossimString toString(ossim_uint32 precision=15) const; /** * @brief Initializes this point from string. * * Expected format: * * ( 0.0000000, 0.0000000, 0.00000000 ) * -----x---- -----y---- ------z---- * * @param s String to initialize from. */ void toPoint(const std::string& s); //! Converts this point to a 3D column vector. NEWMAT::ColumnVector toVector() const { NEWMAT::ColumnVector v (3); v(0) = theData[0]; v(1) = theData[1]; v(2) = theData[2]; return v; } //! Converts 3D column vector to this point. void toPoint(const NEWMAT::ColumnVector& v) { if (v.Nrows() == 3) { theData[0] = v[0]; theData[1] = v[1]; theData[2] = v[2]; } } /*! * Debug Dump: */ void print(std::ostream& os = ossimNotify(ossimNotifyLevel_INFO)) const; friend OSSIM_DLL std::ostream& operator<<(std::ostream& os , const ossimEcefPoint& instance); protected: ossimColumnVector3d theData; }; //================== BEGIN DEFINITIONS FOR INLINE METHODS ===================== //***************************************************************************** // INLINE METHOD: ossimEcefPoint::operator==(ossimEcefPoint) //***************************************************************************** inline bool ossimEcefPoint::operator==(const ossimEcefPoint& p) const { return (theData == p.theData); } //***************************************************************************** // INLINE METHOD: ossimEcefPoint::operator!=(ossimEcefPoint) //***************************************************************************** inline bool ossimEcefPoint::operator!=(const ossimEcefPoint& p) const { return (theData != p.theData); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimEcefRay.h000066400000000000000000000132051352751253100221450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Class for representing a ray in the earth-centered, earth-fixed (ECEF) // coordinate system. A ray is defined as having an origin point and a // unit direction vector radiating from the origin. // // SOFTWARE HISTORY: //> // 08Aug2001 Oscar Kramer (okramer@imagelinks.com) // Initial coding. //< //***************************************************************************** // $Id: ossimEcefRay.h 12769 2008-04-30 17:46:18Z dburken $ #ifndef ossimEcefRay_HEADER #define ossimEcefRay_HEADER #include #include #include #include #include class ossimGpt; class ossimLsrRay; //***************************************************************************** // CLASS: ossimEcefRay // //***************************************************************************** class OSSIMDLLEXPORT ossimEcefRay { public: /*! * CONSTRUCTORS: */ ossimEcefRay() {}; ossimEcefRay(const ossimEcefRay& copy_this) : theOrigin(copy_this.theOrigin), theDirection(copy_this.theDirection) {} ossimEcefRay(const ossimEcefPoint& origin, const ossimEcefVector& direction) : theOrigin(origin), theDirection(direction.unitVector()) {} ossimEcefRay(const ossimEcefPoint& from, const ossimEcefPoint& to); ossimEcefRay(const ossimGpt& from, const ossimGpt& to); bool isNan()const { return theOrigin.isNan()&&theDirection.isNan(); } bool hasNans()const { return theOrigin.isNan()||theDirection.isNan(); } void makeNan() { theOrigin.makeNan(); theDirection.makeNan(); } /*! * OPERATORS: */ const ossimEcefRay& operator= (const ossimEcefRay& r); // inline below bool operator==(const ossimEcefRay& r) const; // inline below bool operator!=(const ossimEcefRay& r) const; // inline below /*! * DATA ACCESS METHODS: */ const ossimEcefPoint& origin() const { return theOrigin; } const ossimEcefVector& direction() const { return theDirection; } void setOrigin(const ossimEcefPoint& orig) { theOrigin = orig; } void setDirection(const ossimEcefVector& d) { theDirection=d.unitVector();} /*! * Extends the ray by distance t (meters) from the origin to the ECEF * point returned. */ ossimEcefPoint extend(const double& t) const; // inline below /*! * This method computes a ray with the same origin but a new direction * corresponding to a reflection from some surface defined by its normal * vector (assumed to be a unit vector): */ ossimEcefRay reflectRay(const ossimEcefVector& normal) const;// inline below /*! * Intersects the ray with the given elevation above the earth ellipsoid. */ ossimEcefPoint intersectAboveEarthEllipsoid (const double& heightAboveEllipsoid, const ossimDatum* aDatum = ossimDatumFactory::instance()->wgs84()) const; /*! * Debug Dump */ std::ostream& print( std::ostream& os = ossimNotify(ossimNotifyLevel_INFO))const; friend std::ostream& operator<<(std::ostream& os , const ossimEcefRay& instance); private: ossimEcefPoint theOrigin; ossimEcefVector theDirection; }; //================== BEGIN DEFINITIONS FOR INLINE METHODS ===================== //***************************************************************************** // INLINE METHOD: ossimEcefRay::operator=(ossimEcefRay) //***************************************************************************** inline const ossimEcefRay& ossimEcefRay::operator=(const ossimEcefRay& r) { theOrigin = r.theOrigin; theDirection = r.theDirection; return *this; } //***************************************************************************** // INLINE METHOD: ossimEcefRay::operator==(ossimEcefRay) //***************************************************************************** inline bool ossimEcefRay::operator==(const ossimEcefRay& r) const { return ((theOrigin == r.theOrigin) && (theDirection == r.theDirection)); } //***************************************************************************** // INLINE METHOD: ossimEcefRay::operator!=(ossimEcefRay) //***************************************************************************** inline bool ossimEcefRay::operator!=(const ossimEcefRay& r) const { return !(*this == r); } //***************************************************************************** // INLINE METHOD: ossimEcefRay::extend(double t) // // Extends the ray by distance t (meters) from the origin to the ECEF // point returned. //***************************************************************************** inline ossimEcefPoint ossimEcefRay::extend(const double& t) const { return (theOrigin + theDirection*t); } //***************************************************************************** // INLINE METHOD: ossimEcefRay::reflectRay(normal) // // This method computes a ray with the same origin but a new direction // corresponding to a reflection from some surface defined by its normal // vector: //***************************************************************************** inline ossimEcefRay ossimEcefRay::reflectRay(const ossimEcefVector& normal) const { ossimEcefVector new_dir(theDirection - normal*2.0*normal.dot(theDirection)); return ossimEcefRay(theOrigin, new_dir); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimEcefVector.h000066400000000000000000000263571352751253100226700ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimEcefVector.h // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of a 3D vector object in the Earth-centered, earth // fixed (ECEF) coordinate system. // // NOTE: There is no associated ossimEcefVector.cc file. All methods are // inlined here // // SOFTWARE HISTORY: //> // 08Aug2001 Oscar Kramer // Initial coding. //< //***************************************************************************** // $Id: ossimEcefVector.h 20043 2011-09-06 15:00:55Z oscarkramer $ #ifndef ossimEcefVector_HEADER #define ossimEcefVector_HEADER #include #include #include #include #include #include class ossimGpt; //***************************************************************************** // CLASS: ossimEcefVector // //***************************************************************************** class OSSIMDLLEXPORT ossimEcefVector { public: /*! * CONSTRUCTORS: */ ossimEcefVector() : theData(0,0,0) {} ossimEcefVector(const ossimEcefVector& copy_this) : theData (copy_this.theData) {} ossimEcefVector(const NEWMAT::ColumnVector& assign_this) : theData (assign_this) {} ossimEcefVector(const ossimEcefPoint& from, const ossimEcefPoint& to) : theData (to.data() - from.data()) {} ossimEcefVector(const ossimGpt& from, const ossimGpt& to) : theData ((ossimEcefPoint(to) - ossimEcefPoint(from)).data()) {} ossimEcefVector(const double& x, const double& y, const double& z) : theData(x, y, z) {} ossimEcefVector(const ossimColumnVector3d& assign_this) : theData(assign_this) {} void makeNan() { theData[0] = ossim::nan(); theData[1] = ossim::nan(); theData[2] = ossim::nan(); } bool hasNans()const { return ( ossim::isnan(theData[0]) || ossim::isnan(theData[1]) || ossim::isnan(theData[2]) ); } bool isNan()const { return ( ossim::isnan(theData[0]) && ossim::isnan(theData[1]) && ossim::isnan(theData[2]) ); } /*! * OPERATORS: (all inlined below) */ inline ossimEcefVector operator- () const; inline ossimEcefVector operator+ (const ossimEcefVector&) const; inline ossimEcefVector operator- (const ossimEcefVector&) const; inline ossimEcefPoint operator+ (const ossimEcefPoint&) const; inline ossimEcefVector operator* (const double&) const; inline ossimEcefVector operator/ (const double&) const; inline bool operator==(const ossimEcefVector&) const; inline bool operator!=(const ossimEcefVector&) const; inline const ossimEcefVector& operator= (const ossimEcefVector&); /*! * Vector-related functions: (all inlined below) */ inline double dot (const ossimEcefVector&) const; inline double angleTo(const ossimEcefVector&) const; // degrees inline ossimEcefVector cross (const ossimEcefVector&) const; inline ossimEcefVector unitVector() const; inline double magnitude() const; // meters inline double norm2() const; // squared meters inline double length() const; inline double normalize(); /*! * COMPONENT ACCESS METHODS: */ double x() const { return theData[0]; } double& x() { return theData[0]; } double y() const { return theData[1]; } double& y() { return theData[1]; } double z() const { return theData[2]; } double& z() { return theData[2]; } double& operator [](int idx){return theData[idx];} const double& operator [](int idx)const{return theData[idx];} const ossimColumnVector3d& data() const { return theData; } ossimColumnVector3d& data() { return theData; } /** * @brief To string method. * * @param precision Output floating point precision. * * @return ossimString representing point. * * Output format: * ( 0.0000000, 0.0000000, 0.00000000 ) * -----x---- -----y---- ------z---- */ ossimString toString(ossim_uint32 precision=15) const; /** * @brief Initializes this point from string. * * Expected format: * * ( 0.0000000, 0.0000000, 0.00000000 ) * -----x---- -----y---- ------z---- * * @param s String to initialize from. */ void toPoint(const std::string& s); //! Converts this point to a 3D column vector. NEWMAT::ColumnVector toVector() const { NEWMAT::ColumnVector v (3); v(0) = theData[0]; v(1) = theData[1]; v(2) = theData[2]; return v; } /*! * Debug Dump: */ void print(std::ostream& os = ossimNotify(ossimNotifyLevel_INFO)) const { os << "(ossimEcefVector) " << theData; } friend std::ostream& operator<< (std::ostream& os , const ossimEcefVector& instance) { instance.print(os); return os; } protected: ossimColumnVector3d theData; }; //================== BEGIN DEFINITIONS FOR INLINE METHODS ===================== //***************************************************************************** // INLINE METHOD: ossimEcefVector::operator-() // Reverses direction of vector. //***************************************************************************** inline ossimEcefVector ossimEcefVector::operator-() const { return ossimEcefVector(-theData); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::operator+(const ossimEcefVector&) //***************************************************************************** inline ossimEcefVector ossimEcefVector::operator+(const ossimEcefVector& v) const { return ossimEcefVector(theData + v.theData); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::operator-(const ossimEcefVector&) //***************************************************************************** inline ossimEcefVector ossimEcefVector::operator-(const ossimEcefVector& v) const { return ossimEcefVector(theData - v.theData); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::operator+(const ossimEcefPoint&) //***************************************************************************** inline ossimEcefPoint ossimEcefVector::operator+(const ossimEcefPoint& p) const { return ossimEcefPoint(theData + p.data()); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::operator*(const double&) //***************************************************************************** inline ossimEcefVector ossimEcefVector::operator*(const double& scalar) const { return ossimEcefVector(theData*scalar); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::operator/(const double&) //***************************************************************************** inline ossimEcefVector ossimEcefVector::operator/(const double& scalar) const { return ossimEcefVector(theData/scalar); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::operator==(const ossimEcefVector&) //***************************************************************************** inline bool ossimEcefVector::operator==(const ossimEcefVector& v) const { return (theData == v.theData); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::operator!=(const ossimEcefVector&) //***************************************************************************** inline bool ossimEcefVector::operator!=(const ossimEcefVector& v) const { return (theData != v.theData); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::operator= //***************************************************************************** inline const ossimEcefVector& ossimEcefVector::operator=(const ossimEcefVector& v) { theData = v.theData; return *this; } //***************************************************************************** // INLINE METHOD: ossimEcefVector::dot() // Computes the scalar product. //***************************************************************************** inline double ossimEcefVector::dot(const ossimEcefVector& v) const { return theData.dot(v.theData); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::angleTo() // Returns the angle subtended (in DEGREES) between this and arg vector //***************************************************************************** inline double ossimEcefVector::angleTo(const ossimEcefVector& v) const { double mag_product = theData.magnitude() * v.theData.magnitude(); return ossim::acosd(theData.dot(v.theData)/mag_product); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::cross() // Computes the cross product. //***************************************************************************** inline ossimEcefVector ossimEcefVector::cross(const ossimEcefVector& v) const { return ossimEcefVector(theData.cross(v.theData)); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::unitVector() // Returns a unit vector parallel to this. //***************************************************************************** inline ossimEcefVector ossimEcefVector::unitVector() const { return ossimEcefVector(theData/theData.magnitude()); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::magnitude() //***************************************************************************** inline double ossimEcefVector::magnitude() const { return theData.magnitude(); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::norm2() //***************************************************************************** inline double ossimEcefVector::norm2() const { return theData.norm2(); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::length() //***************************************************************************** inline double ossimEcefVector::length() const { return theData.magnitude(); } //***************************************************************************** // INLINE METHOD: ossimEcefVector::normalize() // Normalizes this vector. //***************************************************************************** inline double ossimEcefVector::normalize() { double result = theData.magnitude(); if(result > 1e-15) { theData /= result; } return result; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimElevationManagerEvent.h000066400000000000000000000011771352751253100250570ustar00rootroot00000000000000#ifndef ossimElevationManagerEvent_HEADER #define ossimElevationManagerEvent_HEADER #include class ossimObject; class OSSIMDLLEXPORT ossimElevationManagerEvent : public ossimEvent { public: ossimElevationManagerEvent( ossimObject* object=NULL, long id=OSSIM_EVENT_NULL_ID ) : ossimEvent( object, id ) { } ossimElevationManagerEvent( const ossimElevationManagerEvent& rhs ) : ossimEvent( rhs ) { } virtual ossimObject* dup() const { return new ossimElevationManagerEvent( *this ); } TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimElevationManagerEventListener.h000066400000000000000000000010001352751253100265460ustar00rootroot00000000000000#ifndef ossimElevationManagerEventListener_HEADER #define ossimElevationManagerEventListener_HEADER #include #include class OSSIMDLLEXPORT ossimElevationManagerEventListener : public ossimListener { public: ossimElevationManagerEventListener(); virtual ~ossimElevationManagerEventListener(); virtual void processEvent( ossimEvent& event ); virtual void processEvent( ossimElevationManagerEvent& event ); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimEllipsoid.h000066400000000000000000000157511352751253100225630ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // This is the class declaration for ossimEllipsoid. Though valid for the // general class of geometric shape, this implementation contains additional // methods suited to the Earth ellipsoid. // //******************************************************************* // $ID$ #ifndef ossimEllipsoid_HEADER #define ossimEllipsoid_HEADER 1 #include /* std::sqrt */ #include #include #include #include class ossimEcefRay; class ossimEcefPoint; class ossimEcefVector; class ossimMatrix4x4; class ossimKeywordlist; class ossimDpt; /*!**************************************************************************** * * CLASS: ossimEllipsoid * *****************************************************************************/ class OSSIMDLLEXPORT ossimEllipsoid { public: /*! * CONSTRUCTORS... */ ossimEllipsoid(const ossimEllipsoid &ellipsoid); ossimEllipsoid(const ossimString &name, const ossimString &code, const double &major_axis, const double &minor_axis, ossim_uint32 epsg_code=0); ossimEllipsoid(const double &major_axis, const double &minor_axis); ossimEllipsoid(); virtual ~ossimEllipsoid(){}; /*! * ACCESS METHOD... */ const ossimString& name()const{return theName;} const ossimString& code()const{return theCode;} const double& a()const{return theA;} // major axis const double& b()const{return theB;} // minor axis const double& getA()const{return theA;} const double& getB()const{return theB;} const double& getFlattening()const{return theFlattening;} void setA(double a){theA = a;computeFlattening();} void setB(double b){theB = b;computeFlattening();} void setAB(double a, double b){theA = a; theB = b; computeFlattening();} void setEpsgCode(ossim_uint32 code) {theEpsgCode = code;} double eccentricitySquared() const { return theEccentricitySquared; } double flattening()const { return theFlattening; } double eccentricity()const { return std::sqrt(theEccentricitySquared); } ossim_uint32 getEpsgCode() const; /*! * METHOD: nearestIntersection() * Returns the point of nearest intersection of the ray with the ellipsoid. * The first version performs the intersection at the ellipsoid surface. * The second version computes the ray's intersection with a surface at * some offset outside (for positive offset) of the ellipsoid (think * elevation). */ bool nearestIntersection(const ossimEcefRay& ray, ossimEcefPoint& rtnPt) const; bool nearestIntersection(const ossimEcefRay& ray, const double& offset, ossimEcefPoint& rtnPt) const; /*! * METHOD: evaluate() * evaluate will evalate the function at location x, y, z (ECEF). */ double evaluate(const ossimEcefPoint&)const; /*! * METHOD: gradient() * Compute the partials along location x, y, and z and place * the result in the result vector. */ void gradient(const ossimEcefPoint& location, ossimEcefVector& result)const; ossimEcefVector gradient(const ossimEcefPoint& loc)const; /*! * METHOD: prinRadiiOfCurv() * Computes the meridional radius and prime vertical at given point. */ void prinRadiiOfCurv(const ossimEcefPoint& location, double& merRadius, double& primeVert)const; /*! * METHOD: jacobianWrtEcef() * Forms Jacobian of partials of geodetic WRT ECF. */ void jacobianWrtEcef(const ossimEcefPoint& location, NEWMAT::Matrix& jMat)const; /*! * METHOD: jacobianWrtGeo() * Forms Jacobian of partials of ECF WRT geodetic. */ void jacobianWrtGeo(const ossimEcefPoint& location, NEWMAT::Matrix& jMat)const; /*! * Computes the "geodetic" radius for a given latitude in DEGREES: */ double geodeticRadius(const double& latitude) const; /*! * Computes the "geodetic" radius of curvature of the ellipsoid in the east-west (x) and * north-south (y) directions for a given latitude in DEGREES: */ void geodeticRadii(const double& latitude, ossimDpt& radii) const; void latLonHeightToXYZ(double lat, double lon, double height, double &x, double &y, double &z)const; void XYZToLatLonHeight(double x, double y, double z, double& lat, double& lon, double& height)const; //--- // this is a utility from open scene graph that allows you to create a // local space rotational // and translation matrix //--- void computeLocalToWorldTransformFromXYZ(double x, double y, double z, ossimMatrix4x4& localToWorld)const; bool operator ==(const ossimEllipsoid& rhs)const { return ( (theName == rhs.theName)&& (theCode == rhs.theCode)&& (theA == rhs.theA)&& (theB == rhs.theB)&& (theFlattening == rhs.theFlattening)); } bool operator!=(const ossimEllipsoid& rhs) const { return ( (theName != rhs.theName)|| (theCode != rhs.theCode)|| (theA != rhs.theA)|| (theB != rhs.theB)|| (theFlattening != rhs.theFlattening)); } bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; const ossimEllipsoid& operator=(const ossimEllipsoid& copy_me); virtual bool isEqualTo(const ossimEllipsoid& rhs, ossimCompareType compareType=OSSIM_COMPARE_FULL)const; protected: void computeFlattening() { theFlattening = (theA - theB)/theA; } ossimString theName; ossimString theCode; mutable ossim_uint32 theEpsgCode; double theA; //semi-major axis in meters double theB; //semi-minor axis in meters double theFlattening; double theA_squared; double theB_squared; double theEccentricitySquared; }; // class OSSIMDLLEXPORT ossimEllipsoid inline bool ossimEllipsoid::isEqualTo(const ossimEllipsoid& rhs, ossimCompareType /* compareType */)const { return ((theName == rhs.theName)&& (theCode == rhs.theCode)&& (theEpsgCode ==rhs.theEpsgCode)&& ossim::almostEqual(theA, rhs.theA)&& ossim::almostEqual(theB, rhs.theB)&& ossim::almostEqual(theFlattening, rhs.theFlattening)&& ossim::almostEqual(theEccentricitySquared, rhs.theEccentricitySquared)); } #endif /* #ifndef ossimEllipsoid_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimEllipsoidFactory.h000066400000000000000000000030341352751253100241020ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Thie file contains the ossimEllipsoidFactory. //******************************************************************* // $Id: ossimEllipsoidFactory.h 22857 2014-08-05 15:02:58Z gpotts $ #ifndef ossimEllipsoidFactory_HEADER #define ossimEllipsoidFactory_HEADER #include #include #include class ossimEllipsoid; class ossimString; class ossimWgs84Ellipsoid; class ossimWgs72Ellipsoid; class OSSIMDLLEXPORT ossimEllipsoidFactory { public: virtual ~ossimEllipsoidFactory(); const ossimEllipsoid* create(const ossimString &code)const; const ossimEllipsoid* wgs84()const{return theWgs84Ellipsoid;} const ossimEllipsoid* wgs72()const{return theWgs72Ellipsoid;} //! Given an alpha code (for example "WE" for WGS84), returns the corresponding EPSG code or 0 //! if not found. ossim_uint32 findEpsgCode(const ossimString &alpha_code) const; static ossimEllipsoidFactory* instance(); private: typedef std::map TableType; typedef std::map EpsgTableType; //static ossimEllipsoidFactory* theInstance; ossimEllipsoid* theWgs84Ellipsoid; ossimEllipsoid* theWgs72Ellipsoid; TableType theEllipsoidTable; EpsgTableType theEpsgTable; ossimEllipsoidFactory(); void initializeTable(); void deleteAll(); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimEndian.h000066400000000000000000000166131352751253100220330ustar00rootroot00000000000000//****************************************************************** // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This file contains the interface to the // endian byte swap // //*********************************** // $ID$ #ifndef ossimEndian_HEADER #define ossimEndian_HEADER // for OSSIM_LITTLE_ENDIAN AND BIG_ENDIAN #include class OSSIMDLLEXPORT ossimEndian { public: ossimEndian(); /*! * Swap bytes methods that work on a single pixel. */ inline void swap(ossim_sint8 &/*data*/){} inline void swap(ossim_uint8 &/*data*/){} inline void swap(ossim_int16 &data) const; inline void swap(ossim_uint16 &data) const; inline void swap(ossim_int32 &data) const; inline void swap(ossim_uint32 &data) const; inline void swap(ossim_uint64 &data) const; inline void swap(ossim_sint64 &data) const; inline void swap(ossim_float32 &data) const; inline void swap(ossim_float64 &data) const; /*! * Swap bytes methods that work on arrays of pixels. * * @note size is number of pixels, not number of bytes. */ inline void swap(ossimScalarType scalar, void* data, ossim_uint32 size) const; // only here to allow template based swaps to compile correctly // inline void swap(ossim_sint8* data, ossim_uint32 size)const; inline void swap(ossim_uint8* data, ossim_uint32 size)const; inline void swap(ossim_int16* data, ossim_uint32 size) const; inline void swap(ossim_uint16* data, ossim_uint32 size) const; inline void swap(ossim_int32* data, ossim_uint32 size) const; inline void swap(ossim_uint32* data, ossim_uint32 size) const; inline void swap(ossim_int64* data, ossim_uint32 size) const; inline void swap(ossim_uint64* data, ossim_uint32 size) const; inline void swap(ossim_float32* data, ossim_uint32 size) const; inline void swap(ossim_float64* data, ossim_uint32 size) const; inline void swapTwoBytes(void* data, ossim_uint32 size) const; inline void swapFourBytes(void* data, ossim_uint32 size) const; inline void swapEightBytes(void* data, ossim_uint32 size) const; inline ossimByteOrder getSystemEndianType() const; private: // Holds the Endian of the architecture that you are running on. ossimByteOrder theSystemEndianType; void swapTwoBytes(void *data) const; void swapFourBytes(void *data) const; void swapEightBytes(void *data) const; void swapPrivate(ossim_uint8 *c1, ossim_uint8 *c2) const; }; inline ossimByteOrder ossimEndian::getSystemEndianType() const { return theSystemEndianType; } inline void ossimEndian::swap(ossim_sint8* /* data */, ossim_uint32 /* size */ )const { //intentionally left blank } inline void ossimEndian::swap(ossim_uint8* /* data */, ossim_uint32 /* size */ )const { //intentionally left blank } inline void ossimEndian::swap(ossim_int16 &data) const { swapTwoBytes(reinterpret_cast(&data)); } inline void ossimEndian::swap(ossim_uint16 &data) const { swapTwoBytes(reinterpret_cast(&data)); } inline void ossimEndian::swap(ossim_int32 &data) const { swapFourBytes(reinterpret_cast(&data)); } inline void ossimEndian::swap(ossim_uint32 &data) const { swapFourBytes(reinterpret_cast(&data)); } inline void ossimEndian::swap(ossim_uint64 &data) const { swapEightBytes(reinterpret_cast(&data)); } inline void ossimEndian::swap(ossim_sint64 &data) const { swapEightBytes(reinterpret_cast(&data)); } inline void ossimEndian::swap(ossim_float32 &data) const { swapFourBytes(reinterpret_cast(&data)); } inline void ossimEndian::swap(ossim_float64 &data) const { swapEightBytes(reinterpret_cast(&data)); } inline void ossimEndian::swapTwoBytes(void *data) const { unsigned char *c = reinterpret_cast(data); swapPrivate(&c[0], &c[1]); } inline void ossimEndian::swapFourBytes(void* data) const { unsigned char *c = reinterpret_cast(data); swapPrivate(&c[0], &c[3]); swapPrivate(&c[1], &c[2]); } inline void ossimEndian::swapEightBytes(void* data) const { unsigned char *c = reinterpret_cast(data); swapPrivate(&c[0], &c[7]); swapPrivate(&c[1], &c[6]); swapPrivate(&c[2], &c[5]); swapPrivate(&c[3], &c[4]); } inline void ossimEndian::swapPrivate(ossim_uint8 *c1, ossim_uint8 *c2) const { ossim_uint8 temp_c = *c1; *c1 = *c2; *c2 = temp_c; } inline void ossimEndian::swap(ossimScalarType scalar, void* data, ossim_uint32 size) const { switch (scalar) { case OSSIM_USHORT16: case OSSIM_SSHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: swapTwoBytes(data, size); return; case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: swapFourBytes(data, size); return; case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: swapEightBytes(data, size); break; default: return; } } inline void ossimEndian::swap(ossim_int16* data, ossim_uint32 size) const { swapTwoBytes(data, size); } inline void ossimEndian::swap(ossim_uint16* data, ossim_uint32 size) const { swapTwoBytes(data, size); } inline void ossimEndian::swap(ossim_int32* data, ossim_uint32 size) const { swapFourBytes(data, size); } inline void ossimEndian::swap(ossim_uint32* data, ossim_uint32 size) const { swapFourBytes(data, size); } inline void ossimEndian::swap(ossim_int64* data, ossim_uint32 size) const { swapEightBytes(data, size); } inline void ossimEndian::swap(ossim_uint64* data, ossim_uint32 size) const { swapEightBytes(data, size); } inline void ossimEndian::swap(ossim_float32* data, ossim_uint32 size) const { swapFourBytes(data, size); } inline void ossimEndian::swap(ossim_float64* data, ossim_uint32 size) const { swapEightBytes(data, size); } inline void ossimEndian::swapTwoBytes(void* data, ossim_uint32 size) const { ossim_uint16* buf = reinterpret_cast(data); for (ossim_uint32 i=0; i> 8); } } inline void ossimEndian::swapFourBytes(void* data, ossim_uint32 size) const { ossim_uint32* buf = reinterpret_cast(data); for (ossim_uint32 i=0; i> 24) | ((buf[i] & 0x00ff0000) >> 8) | ((buf[i] & 0x0000ff00) << 8) | ((buf[i] & 0x000000ff) << 24)); } } inline void ossimEndian::swapEightBytes(void* data, ossim_uint32 size) const { ossim_uint64* buf = reinterpret_cast(data); for (ossim_uint32 i=0; i> 56) | ((buf[i] & 0x00ff000000000000ull) >> 40) | ((buf[i] & 0x0000ff0000000000ull) >> 24) | ((buf[i] & 0x000000ff00000000ull) >> 8) | ((buf[i] & 0x00000000ff000000ull) << 8) | ((buf[i] & 0x0000000000ff0000ull) << 24) | ((buf[i] & 0x000000000000ff00ull) << 40) | ((buf[i] & 0x00000000000000ffull) << 56)); } } #endif /* End of #ifndef ossimEndian_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimEnvironmentUtility.h000066400000000000000000000040761352751253100245250ustar00rootroot00000000000000#ifndef ossimEnvironmentUtility_HEADER #define ossimEnvironmentUtility_HEADER #include #include class OSSIM_DLL ossimEnvironmentUtility { public: typedef std::vector FilenameListType; static ossimEnvironmentUtility* instance(); ossimString getEnvironmentVariable(const ossimString& variable)const; void setEnvironmentVariable(const char* variable, const char* value) const; ossimFilename getUserDir()const; ossimString getUserName()const; ossimFilename getUserOssimSupportDir()const; ossimFilename getUserOssimPreferences()const; ossimFilename getUserOssimPluginDir()const; ossimFilename getInstalledOssimSupportDir()const; ossimFilename getInstalledOssimPluginDir()const; ossimFilename getInstalledOssimPreferences()const; /** * @return The current working dir which is $(PWD) for unix $(CD) for * windows. */ ossimFilename getCurrentWorkingDir()const; ossimFilename searchAllPaths(const ossimFilename& file)const; ossimFilename findPlugin(const ossimFilename& plugin)const; ossimFilename findData(const ossimFilename& data)const; void addDataSearchPath(const ossimFilename& path); void addDataSearchPathToFront(const ossimFilename& path); void addPluginSearchPath(const ossimFilename& path); void addPluginSearchPathToFront(const ossimFilename& path); ossimEnvironmentUtility::FilenameListType& getPluginSearchPath(); const ossimEnvironmentUtility::FilenameListType& getPluginSearchPath()const; ossimEnvironmentUtility::FilenameListType& getDataSearchPath(); const ossimEnvironmentUtility::FilenameListType& getDataSearchPath()const; private: static ossimEnvironmentUtility* theInstance; ossimEnvironmentUtility::FilenameListType thePluginSearchPath; ossimEnvironmentUtility::FilenameListType theDataSearchPath; ossimEnvironmentUtility(); ossimEnvironmentUtility(const ossimEnvironmentUtility& obj); const ossimEnvironmentUtility& operator= (const ossimEnvironmentUtility& rhs); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimEpsgDatumFactory.h000066400000000000000000000054151352751253100240540ustar00rootroot00000000000000//************************************************************************************************* // OSSIM -- Open Source Software Image Map // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // //************************************************************************************************* // $Id$ #ifndef ossimEpsgDatumFactory_HEADER #define ossimEpsgDatumFactory_HEADER 1 #include #include #include class ossimDatum; class ossimString; //************************************************************************************************* //! Class for creating datum instances from EPSG codes. //! Presently only a small subset of EPSG datums are supported. These are hardcoded here or, //! alternatively, the EPSG code is mapped to the OSSIM/Geotrans code and ossimDatumFactory is //! used to produce the final datum. //! //! TO DO: //! Eventually we should have a disk-file based database lookup of datums with associated parameters //! similar to the EPSG projection factory and database. //************************************************************************************************* class OSSIM_DLL ossimEpsgDatumFactory : public ossimDatumFactoryInterface { public: //! Singleton implementation. static ossimEpsgDatumFactory* instance(); //! Destructor virtual ~ossimEpsgDatumFactory(); //! Creates a datum instance given an EPSG spec in the form "EPSG:". virtual const ossimDatum* create(const ossimString &epsg_spec)const; //! Creates a datum instance given a KWL and prefix virtual const ossimDatum* create(const ossimKeywordlist& kwl, const char *prefix=0)const; //! Returns list of all datums supported, in the form of "EPSG:, ". virtual void getList(std::vector& list)const; //! Specific to this factory only. Creates a datum instance given an EPSG integer code. const ossimDatum* create(ossim_uint32 epsg_code)const; //! Specific to this factory only. Given an alpha-code, returns equivalent EPSG datum code or //! 0 if not found. ossim_uint32 findEpsgCode(const ossimString& alpha_code) const; //! Specific to this factory only. Given an EPSG, returns equivalent alpha-code datum code or //! empty string if not found. ossimString findAlphaCode(ossim_uint32 epsg_code) const; protected: //! Hidden constructors for singleton implementation. ossimEpsgDatumFactory(); //! Presently implemented as a mapping from EPSG code to OSSIM/Geotrans alpha-codes found in //! ossimDatumFactory. Eventually should be independent (and deprecate) ossimDatumFactory. std::map m_epsgToAlphaMap; // static ossimEpsgDatumFactory* m_instance; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimEquTokenDefines.h000066400000000000000000000037661352751253100236730ustar00rootroot00000000000000#ifndef ossimEquTokenDefines_HEADER #define ossimEquTokenDefines_HEADER #define OSSIM_EQU_TOKEN_LEFT_PAREN 1 #define OSSIM_EQU_TOKEN_RIGHT_PAREN 2 #define OSSIM_EQU_TOKEN_LOG 3 #define OSSIM_EQU_TOKEN_MULT 4 #define OSSIM_EQU_TOKEN_DIV 5 #define OSSIM_EQU_TOKEN_MINUS 6 #define OSSIM_EQU_TOKEN_PLUS 7 #define OSSIM_EQU_TOKEN_IMAGE_VARIABLE 8 #define OSSIM_EQU_TOKEN_CONSTANT 9 #define OSSIM_EQU_TOKEN_EXP 10 #define OSSIM_EQU_TOKEN_LOG10 11 #define OSSIM_EQU_TOKEN_PI 12 #define OSSIM_EQU_TOKEN_POWER 13 #define OSSIM_EQU_TOKEN_SIN 14 #define OSSIM_EQU_TOKEN_SIND 15 #define OSSIM_EQU_TOKEN_COS 16 #define OSSIM_EQU_TOKEN_COSD 17 #define OSSIM_EQU_TOKEN_ABS 18 #define OSSIM_EQU_TOKEN_MIN 19 #define OSSIM_EQU_TOKEN_MAX 20 #define OSSIM_EQU_TOKEN_SQRT 21 #define OSSIM_EQU_TOKEN_COMMA 22 #define OSSIM_EQU_TOKEN_BLURR 23 #define OSSIM_EQU_TOKEN_SHIFT 24 #define OSSIM_EQU_TOKEN_CONV 25 #define OSSIM_EQU_TOKEN_BAND 26 #define OSSIM_EQU_TOKEN_ASSIGN_BAND 27 #define OSSIM_EQU_TOKEN_MOD 28 #define OSSIM_EQU_TOKEN_ASIN 29 #define OSSIM_EQU_TOKEN_ASIND 30 #define OSSIM_EQU_TOKEN_ACOS 31 #define OSSIM_EQU_TOKEN_ACOSD 32 #define OSSIM_EQU_TOKEN_TAN 33 #define OSSIM_EQU_TOKEN_TAND 34 #define OSSIM_EQU_TOKEN_ATAN 35 #define OSSIM_EQU_TOKEN_ATAND 36 #define OSSIM_EQU_TOKEN_LEFT_ARRAY_BRACKET 37 #define OSSIM_EQU_TOKEN_RIGHT_ARRAY_BRACKET 38 #define OSSIM_EQU_TOKEN_AMPERSAND 39 #define OSSIM_EQU_TOKEN_OR_BAR 40 #define OSSIM_EQU_TOKEN_TILDE 41 #define OSSIM_EQU_TOKEN_XOR 42 #define OSSIM_EQU_TOKEN_CLAMP 43 #define OSSIM_EQU_TOKEN_CLIP 44 #define OSSIM_EQU_TOKEN_BEQUAL 45 #define OSSIM_EQU_TOKEN_BGREATER 46 #define OSSIM_EQU_TOKEN_BGREATEROREQUAL 47 #define OSSIM_EQU_TOKEN_BLESS 48 #define OSSIM_EQU_TOKEN_BLESSOREQUAL 49 #define OSSIM_EQU_TOKEN_BDIFFERENT 50 #endif ossim-Miami-2.9.1/include/ossim/base/ossimEquTokenizer.h000066400000000000000000000004041352751253100232510ustar00rootroot00000000000000#ifndef ossimEquTokenizer_HEADER #define ossimEquTokenizer_HEADER #define yyFlexLexer ossimEquTokenizerFlexLexer #include #include typedef ossimEquTokenizerFlexLexer ossimEquTokenizer; #endif ossim-Miami-2.9.1/include/ossim/base/ossimErrorCodes.h000066400000000000000000000056671352751253100227130ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration with common error codes and methods to go // from code to string and string to code. // //************************************************************************* // $Id: ossimErrorCodes.h 14789 2009-06-29 16:48:14Z dburken $ #ifndef ossimErrorCodes_HEADER #define ossimErrorCodes_HEADER #include #include /*! * class ossimErrorCodes * Contains class declaration with common error codes and methods to go * from code to string and string to code. */ class OSSIMDLLEXPORT ossimErrorCodes { public: ~ossimErrorCodes(); /*! * Returns a pointer to "theInstance". */ static ossimErrorCodes* instance(); /*! * Returns the error code from a string. Returns OSSIM_ERROR_UNKNOWN if * the string does not match. */ ossimErrorCode getErrorCode(const ossimString& error_string) const; /*! * Returns the string matching the error code. * Returns "OSSIM_ERROR_UNKNOWN" if code is not valid. */ ossimString getErrorString(ossimErrorCode error_code) const; static const ossimErrorCode OSSIM_OK; static const ossimErrorCode OSSIM_NO_ERROR; static const ossimErrorCode OSSIM_WARNING; static const ossimErrorCode OSSIM_ERROR; static const ossimErrorCode OSSIM_ERROR_STD_PARALLEL_1; static const ossimErrorCode OSSIM_LAT_ERROR; static const ossimErrorCode OSSIM_LON_ERROR; static const ossimErrorCode OSSIM_NORTHING_ERROR; static const ossimErrorCode OSSIM_ORIGIN_LAT_ERROR; static const ossimErrorCode OSSIM_CENT_MER_ERROR; static const ossimErrorCode OSSIM_A_ERROR; static const ossimErrorCode OSSIM_B_ERROR; static const ossimErrorCode OSSIM_A_LESS_B_ERROR; static const ossimErrorCode OSSIM_FIRST_STDP_ERROR; static const ossimErrorCode OSSIM_SEC_STDP_ERROR; static const ossimErrorCode OSSIM_FIRST_SECOND_ERROR; static const ossimErrorCode OSSIM_HEMISPHERE_ERROR; static const ossimErrorCode OSSIM_EASTING_ERROR; static const ossimErrorCode OSSIM_RADIUS_ERROR; static const ossimErrorCode OSSIM_ORIGIN_LON_ERROR; static const ossimErrorCode OSSIM_ORIENTATION_ERROR; static const ossimErrorCode OSSIM_SCALE_FACTOR_ERROR; static const ossimErrorCode OSSIM_ZONE_ERROR; static const ossimErrorCode OSSIM_ZONE_OVERRIDE_ERROR; static const ossimErrorCode OSSIM_INVALID_FILE_ERROR; static const ossimErrorCode OSSIM_OPEN_FILE_ERROR; static const ossimErrorCode OSSIM_WRITE_FILE_ERROR; static const ossimErrorCode OSSIM_ERROR_UNKNOWN; protected: // Only allow instantiation through the "instance()" method. ossimErrorCodes(); ossimErrorCodes(const ossimErrorCodes& rhs); const ossimErrorCodes& operator=(const ossimErrorCodes &rhs); static ossimErrorCodes* theInstance; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimErrorContext.h000066400000000000000000000007321352751253100232660ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class declaration for ossimErrorContext. //******************************************************************* // $Id: ossimErrorContext.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimErrorContext_HEADER #define ossimErrorContext_HEADER #include #endif ossim-Miami-2.9.1/include/ossim/base/ossimErrorStatusInterface.h000066400000000000000000000041341352751253100247460ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration for common error interfaces. // //************************************************************************* // $Id: ossimErrorStatusInterface.h 22149 2013-02-11 21:36:10Z dburken $ #ifndef ossimErrorStatusInterface_HEADER #define ossimErrorStatusInterface_HEADER #include #include #include #include /*! * class ossimErrorStatusInterface * Provides common interfaces for error handling. * * Note: For error codes and associated strings use the ossimErrorCodes class. */ class OSSIMDLLEXPORT ossimErrorStatusInterface { public: ossimErrorStatusInterface(); virtual ~ossimErrorStatusInterface(); /*! return theErrorStatus */ virtual ossimErrorCode getErrorStatus() const; /*! return theErrorStatus as an ossimString */ virtual ossimString getErrorStatusString() const; /*! Sets theErrorStatus to error_status. */ virtual void setErrorStatus(ossimErrorCode error_status) const; /*! Set theErrorStatus to ossimErrorCodes::OSSIM_ERROR. */ virtual void setErrorStatus() const; /*! Clears theErrorStatus by setting to ossimErrorCodes::OSSIM_OK or 0. */ virtual void clearErrorStatus() const; /*! @return true if theErrorStatus != ossimErrorCodes::OSSIM_OK. */ bool hasError() const; /** * Outputs theErrorStatus as an ossimErrorCode and an ossimString. * * @return std::ostream& * * @note Derived classes should only have to implement a virtual print, * not an operator<< funtion as it's implemented here. */ virtual std::ostream& print(std::ostream& out) const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& out, const ossimErrorStatusInterface& obj); protected: mutable ossimErrorCode theErrorStatus; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimEvent.h000066400000000000000000000033041352751253100217070ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: A brief description of the contents of the file. // // //************************************************************************* // $Id: ossimEvent.h 13362 2008-08-01 14:02:32Z gpotts $ #ifndef ossimEvent_HEADER #define ossimEvent_HEADER #include #include class OSSIMDLLEXPORT ossimEvent : public ossimObject { public: enum PropagationType { PROPAGATION_NONE = 0, PROPAGATION_INPUT = 1, PROPAGATION_OUTPUT = 2 }; /** * @param object The object associated with the event if any. * * @param id The event id. */ ossimEvent(ossimObject* object=NULL, long id=OSSIM_EVENT_NULL_ID); ossimEvent(const ossimEvent& rhs); long getId()const; void setId(long id); bool isConsumed()const; void setConsumedFlag(bool flag=true); void consume(); /** * This is the originating object that originally * produced the event. */ const ossimObject* getObject()const; ossimObject* getObject(); const ossimObject* getCurrentObject()const; ossimObject* getCurrentObject(); void setObject(ossimObject* object); void setCurrentObject(ossimObject* object); void setPropagationType(PropagationType type); bool isPropagatingToOutputs()const; bool isPropagatingToInputs()const; protected: ossimObject* theObject; ossimObject* theCurrentObject; long theId; bool theIsConsumedFlag; PropagationType thePropagationType; TYPE_DATA }; #endif /* #ifndef ossimEvent_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimEventIds.h000066400000000000000000000040111352751253100223430ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: A brief description of the contents of the file. // // //************************************************************************* // $Id: ossimEventIds.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimEventIds_HEADER #define ossimEventIds_HEADER #define OSSIM_EVENT_NULL_ID -1 // destruction event #define OSSIM_EVENT_OBJECT_DESTRUCTING_ID 1 // connection events #define OSSIM_EVENT_CONNECTION_DISCONNECT_ID 3 #define OSSIM_EVENT_CONNECTION_CONNECT_ID 4 #define OSSIM_EVENT_REFRESH_ID 5 #define OSSIM_EVENT_PROCESS_PROGRESS_ID 20 #define OSSIM_EVENT_ADD_OBJECT_ID 40 #define OSSIM_EVENT_REMOVE_OBJECT_ID 41 #define OSSIM_EVENT_PROPERTY_ID 80 #define OSSIM_EVENT_STATE_CHANGED_ID 90 #define OSSIM_EVENT_AOI_RECTANGLE_ID 200 #define OSSIM_EVENT_AOI_POLYGON_ID 201 #define OSSIM_MOUSE_EVENT_ID 400 #define OSSIM_MOUSE_EVENT_LEAVE_WINDOW_ID 401 #define OSSIM_MOUSE_EVENT_MOTION_ID 402 #define OSSIM_MOUSE_EVENT_LEFT_DOWN_ID 403 #define OSSIM_MOUSE_EVENT_RIGHT_DOWN_ID 404 #define OSSIM_MOUSE_EVENT_MIDDLE_DOWN_ID 405 #define OSSIM_MOUSE_EVENT_LEFT_UP_ID 406 #define OSSIM_MOUSE_EVENT_RIGHT_UP_ID 407 #define OSSIM_MOUSE_EVENT_MIDDLE_UP_ID 408 #define OSSIM_MOUSE_EVENT_LEFT_DCLICK_ID 409 #define OSSIM_MOUSE_EVENT_RIGHT_DCLICK_ID 410 #define OSSIM_MOUSE_EVENT_MIDDLE_DCLICK_ID 411 #define OSSIM_MOUSE_EVENT_ENTER_WINDOW_ID 412 #define OSSIM #define OSSIM_KEYBOARD_EVENT_ID 500 #define OSSIM_EVENT_VIEW_ID 600 #define OSSIM_EVENT_DISPLAY_LIST_ID 700 #define OSSIM_EVENT_DISPLAY_REFRESH_ID 701 #define OSSIM_EVENT_IMAGE_GEOMETRY_ID 800 // this is the first user defined id. If users want to add // additional id's they need to start at this id. That way // we have no conflicts. // #define OSSIM_FIRST_USER_DEFINED_EVENT_ID 1000000 #endif ossim-Miami-2.9.1/include/ossim/base/ossimException.h000066400000000000000000000023261352751253100225670ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Generic OSSIM Exception that is a std::exception with a // what() method implemented. //---------------------------------------------------------------------------- // $Id: ossimException.h 10029 2006-12-04 23:23:11Z dburken $ #ifndef ossimException_HEADER #define ossimException_HEADER #include #include #include class OSSIM_DLL ossimException : public std::exception { public: /** @brief default construction */ ossimException() throw(); /** * @brief construction that takes an error string. * @param errorMessage The error message. */ ossimException(const std::string& errorMessage) throw(); /** @brief virtual destructor. */ virtual ~ossimException() throw(); /** * @brief Returns the error message. * @return The error message as a C-style character string. */ virtual const char* what() const throw(); private: /** This is the error message returned by what(). */ std::string theErrorMessage; }; #endif /* End of #ifndef ossimException_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimFactoryBaseTemplate.h000066400000000000000000000100621352751253100245230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of template class ossimFactory. This is the base // type for all factories. // // SOFTWARE HISTORY: //> // 14Jun2001 Oscar Kramer (okramer@imagelinks.com) // Initial coding. //< //***************************************************************************** // $Id: ossimFactoryBaseTemplate.h 14799 2009-06-30 08:54:44Z dburken $ #ifndef ossimFactory_HEADER #define ossimFactory_HEADER #include #include class ossimKeywordlist; class ossimString; /*!**************************************************************************** * * TEMPLATE: ossimFactoryBase * * NOTE: This is primarily intended as an interface template only to insure * that all factories prescribe to a common type. Concrete classes shall * be derived from an instance of this template as: * * class MyFactory : public ossimFactoryBase * * where MyProductClass is the class type being produced. * * This template is applicable to "Registry" type factories that have * one or more sub-factories. Thus, a common interface is provided * without the client distinguishing between registries and factories. * * EXAMPLE: Refer to the projection factories for a working example of the * use of this base class template. Specifically, refer to the files: * - ../ossim_core/projections/factory/ossimProjectionFactory.h * - ../ossim_core/projections/factory/ossimMapProjectionFactory.h * - ../ossim_core/projections/factory/ossimSensorModelFactory.h * *****************************************************************************/ template class OSSIMDLLEXPORT ossimFactoryBase { public: /*! * METHOD: instance() * For accessing static singleton instance of concrete factory. The derived * class implementation of this method invokes the factory's private * constructor. MUST BE PROVIDED BY CONCRETE DERIVED CLASS as follows: * static * instance(); */ /*! * PURE VIRTUAL METHODS: create(string), create(keywordlist, prefix) * * Attempts to create an instance of the Product given a string or * keywordlist. It is up to the concrete factory implementation to decide * how to interpret string. It could conceivably represent a "magic * number" specification of a product (such as the class name). Or, it could * be a filename that the factory must open to decide which product * to instantiate. The derived factory can also define other create methods * following the model used here. * * Returns successfully constructed product or NULL. */ virtual Product* create(const ossimString&) const = 0; virtual Product* create(const ossimKeywordlist& kwl, const char* prefix) const = 0; /*! * PURE VIRTUAL METHOD: getList() * Returns name list of all products represented by this factory: */ virtual std::list getList() const = 0; /*! * METHOD: registerFactory() * Adds sub-factories to this one. Relevant for the case where the * derived factory maintains a registry of sub-factories. */ void registerFactory(ossimFactoryBase* new_factory) { if(new_factory) theRegistry.push_back(new_factory); } protected: /*! * PROTECTED DEFAULT CONSTRUCTOR * Gives concrete class the opportunity to perform initialization * tasks since this is called once with first instance() call. If the * derived factory is to serve as a sub-factory registry, then have the * derived class' constructor call registerFactory() for all of the default * sub-factories involved. */ ossimFactoryBase() {}; virtual ~ossimFactoryBase() {} /*! * Member contains list of sub-factories associated with this factory: */ std::list*> theRegistry; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimFactoryListInterface.h000066400000000000000000000222051352751253100247130ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Class declaration of ossimFactoryListInterface. // //************************************************************************************************** // $Id$ #ifndef ossimFactoryListInterface_HEADER #define ossimFactoryListInterface_HEADER #include #include #include #include #include #include /** * The is a factory list interface that allows registries to be accessed in a common way. * * This is typically used by the Registries. The registries derive from this * interface so that it will have the ability to give access to others * to add to it's registry: * * Pseudo Code: * @code * someRegistry::instance()->addFactory(someFactory::instance()); * @endcode */ template class ossimFactoryListInterface { public: typedef std::vector FactoryListType; typedef T FactoryType; typedef NativeType NativeReturnType; ossimFactoryListInterface(){} /** * This is for backward compatability and calls registerFactory for simple adds. */ void addFactory(T* factory) { registerFactory(factory); } /** * Public access method to determine if a factory is already registered to this * list */ bool isFactoryRegistered(T* factory)const { if(!factory) return false; std::lock_guard lock(m_factoryListMutex); return findFactory(factory); } /** * Will register a factory to the factory list. Will append the passed in factory if not * already registered to the list. */ void registerFactory(T* factory, bool pushToFrontFlag=false) { if(!factory) return; std::lock_guard lock(m_factoryListMutex); if(!findFactory(factory)) { if (pushToFrontFlag) { m_factoryList.insert(m_factoryList.begin(), factory); } else { m_factoryList.push_back(factory); } } } /** * Will remove the factory from the registry. */ void unregisterFactory(T* factory) { std::lock_guard lock(m_factoryListMutex); ossim_uint32 idx = 0; for(idx = 0; idx < m_factoryList.size(); ++idx) { if(factory == m_factoryList[idx]) { m_factoryList.erase(m_factoryList.begin() + idx); return; } } } /** * Will remove the factory from the registry by name. * @param factoryTypeName The class name of the factory, (e.g. "ossimCsmProjectionFactory") */ void unregisterFactory(const ossimString& factoryTypeName) { std::lock_guard lock(m_factoryListMutex); ossim_uint32 idx = 0; for(idx = 0; idx < m_factoryList.size(); ++idx) { if (m_factoryList[idx]) { ossimString mangledName (typeid(*(m_factoryList[idx])).name()); if (mangledName.contains(factoryTypeName)) { m_factoryList.erase(m_factoryList.begin() + idx); return; } } } } /** * Will remove all factories from the registry. */ void unregisterAllFactories() { std::lock_guard lock(m_factoryListMutex); m_factoryList.clear(); } /** * Inserts the factory to the front of the list. */ void registerFactoryToFront(T* factory) { std::lock_guard lock(m_factoryListMutex); if(!findFactory(factory)) { m_factoryList.insert(m_factoryList.begin(), factory); } } /** * Will insert the factory before the beforeThisFactory. If not found * it will do a simple append. */ void registerFactoryBefore(T* factory, T* beforeThisFactory) { std::lock_guard lock(m_factoryListMutex); if(!findFactory(factory)) { ossim_uint32 idx = 0; for(idx = 0; idx < m_factoryList.size(); ++idx) { if(beforeThisFactory == m_factoryList[idx]) { m_factoryList.insert(m_factoryList.begin() + idx, factory); return; } } m_factoryList.push_back(factory); } } /** * * Will add all object types the factories can allocate. Typically a list of classnames are returned * */ void getAllTypeNamesFromRegistry(std::vector& typeList)const; /** * This is the base object return for all objects in the system. This is used for * backward compatability. */ ossimObject* createObjectFromRegistry(const ossimString& typeName)const; /** * This is the base object return for all objects in the system. This is used for * backward compatability. */ ossimObject* createObjectFromRegistry(const ossimKeywordlist& kwl, const char* prefix=0)const; /** * This is a helper method that calls the createObject and makes sure that the * returned object is of the NativeType base type this registry supports. */ NativeType* createNativeObjectFromRegistry(const ossimString& typeName)const; /** * This is a helper method that calls the createObject and makes sure that the * returned object is of the NativeType base type this registry supports. * * @param kwl is a state keywordlist allowing one to instantiate an object * defined by a set of name value pairs. It will use the type * keyword to create an object of the defined type and then load the * state. */ NativeType* createNativeObjectFromRegistry(const ossimKeywordlist& kwl, const char* prefix=0)const; protected: /** * Utility to find a factory in the list */ bool findFactory(T* factory)const { if(!factory) return false; ossim_uint32 idx = 0; for(;idx < m_factoryList.size();++idx) { if(m_factoryList[idx] == factory) { return true; } } return false; } mutable std::mutex m_factoryListMutex; FactoryListType m_factoryList; }; template void ossimFactoryListInterface::getAllTypeNamesFromRegistry(std::vector& typeList)const { //std::lock_guard lock(m_factoryListMutex); ossim_uint32 idx = 0; for(; idxgetTypeNameList(typeList); } } template ossimObject* ossimFactoryListInterface::createObjectFromRegistry(const ossimString& typeName)const { //std::lock_guard lock(m_factoryListMutex); ossimObject* result = 0; ossim_uint32 idx = 0; for(;((idxcreateObject(typeName); } return result; } template ossimObject* ossimFactoryListInterface::createObjectFromRegistry(const ossimKeywordlist& kwl, const char* prefix)const { // std::lock_guard lock(m_factoryListMutex); ossimObject* result = 0; ossim_uint32 idx = 0; for(;((idxcreateObject(kwl, prefix); } return result; } template NativeType* ossimFactoryListInterface::createNativeObjectFromRegistry(const ossimString& typeName)const { NativeType* result = 0; ossimRefPtr tempObject = createObjectFromRegistry(typeName); if(tempObject.valid()) { result = dynamic_cast(tempObject.get()); if(result) { tempObject.release(); } } return result; } template NativeType* ossimFactoryListInterface::createNativeObjectFromRegistry(const ossimKeywordlist& kwl, const char* prefix)const { NativeType* result = 0; ossimRefPtr tempObject = createObjectFromRegistry(kwl, prefix); if(tempObject.valid()) { result = dynamic_cast(tempObject.get()); if(result) { tempObject.release(); } } return result; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimFileInfoInterface.h000066400000000000000000000013401352751253100241400ustar00rootroot00000000000000//--- // File: ossimFileInfoInterface.h // // License: MIT // // Description: Class ossimFileInfoInterface. // // Interface class for file info things. Written for stream code from url, // e.g. AWS ossim::S3IStream. // //--- // $Id$ #ifndef ossimFileInfoInterface_HEADER #define ossimFileInfoInterface_HEADER 1 #include /** @class ossimFileInfoInterface */ class ossimFileInfoInterface { public: /** @brief virtual destructor. */ virtual ~ossimFileInfoInterface(){} /** * @brief Pure virtual file size method. Derived classed must implement. * @return File size in bytes. */ virtual ossim_int64 getFileSize() const = 0; }; #endif /* #ifndef ossimFileInfoInterface_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimFileProcessorInterface.h000066400000000000000000000021061352751253100252250ustar00rootroot00000000000000//---------------------------------------------------------------------------- // File: ossimFileProcessorInterface.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class interface ossimFileProcessorInterface. // // Has pure virtual "processFile" method that derived classes must // implement to be concrete. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimFileProcessorInterface_HEADER #define ossimFileProcessorInterface_HEADER 1 class ossimFilename; /** @class ossimFileProcessorInterface */ class ossimFileProcessorInterface { public: /** @brief default constructor */ ossimFileProcessorInterface(){} /** @brief virtual destructor. */ virtual ~ossimFileProcessorInterface(){} /** * @brief Pure virtual processFile method. Derived classed must implement. * @param file to process. */ virtual void processFile(const ossimFilename& file) = 0; }; #endif /* #ifndef ossimFileProcessorInterface_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimFilename.h000066400000000000000000000176171352751253100223620ustar00rootroot00000000000000//--- // // License: MIT // // Author: Ken Melero // // Description: This class provides manipulation of filenames. // //--- // $Id$ #ifndef ossimFilename_HEADER #define ossimFilename_HEADER 1 #include #include class ossimLocalTm; class OSSIM_DLL ossimFilename : public ossimString { public: enum AccessModes { OSSIM_READ_WRITE = 6, OSSIM_READ = 4, OSSIM_WRITE = 2, OSSIM_EXE = 1, // The PC docs say that this is ignored OSSIM_EXIST = 0 }; ossimFilename(); ossimFilename(const ossimFilename& src); ossimFilename(const ossimString& src); ossimFilename(const std::string& src); ossimFilename(const char* src); const ossimFilename& operator=(const ossimFilename& f); template ossimFilename(Iter s, Iter e); static const ossimFilename NIL; bool operator == (const ossimFilename& rhs)const; bool operator == (const ossimString& rhs)const; bool operator == (const char* rhs)const; /** @brief Writes f to the output stream os. */ // friend std::ostream& operator<<(std::ostream& os, // const ossimFilename& s); // void convertBackToForwardSlashes(); // void convertForwardToBackSlashes(); bool setTimes(ossimLocalTm* accessTime, ossimLocalTm* modTime, ossimLocalTm* createTime)const; bool getTimes(ossimLocalTm* accessTime, ossimLocalTm* modTime, ossimLocalTm* createTime)const; /** * @brief Time in seconds since last accessed. * * @return The number of seconds since last accessed or -1 if file does not * exist. */ ossim_int64 lastAccessed() const; bool touch()const; /** * Method to do file name expansion. * * Like: ~/docs will be expanded to /home/user/docs * * @return The expanded file name. * * @note METHOD IS NOT COMPLETE YET. */ ossimFilename expand() const; // Methods to test ossimFilename for various states. bool exists() const; bool isFile() const; bool isDir() const; bool isReadable() const; bool isUrl() const; bool isWriteable() const; bool isExecutable() const; ossim_int64 fileSize() const; // Methods to access parts of the ossimFilename. /** * @return "tif" if file is "/data/images/t1.tif". * * @note The '.' (dot) is not returned. */ ossimString ext() const; /** * @return @return "/data/images" if file is "/data/images/t1.tif". */ ossimFilename path() const; /** * @return @return "c:" if file is "c:\data\images\t1.tif". */ ossimFilename drive() const; /** * @return @return "t1.tif" if file is "/data/images/t1.tif". */ ossimFilename file() const; /** * @return @return "t1" if file is "/data/images/t1.tif". */ ossimFilename fileNoExtension() const; /** * @return @return "/data/images/t1" if file is "/data/images/t1.tif". * * @note The '.' (dot) is not returned. */ ossimFilename noExtension() const; /** * Sets the extension of a file name. * * Given: * ossimFilename f = "foo"; * f.setExtension("tif"); * f now equals "foo.tif" * * Given: * ossimFilename f = "foo.jpg"; * f.setExtension("tif"); * f now equals "foo.tif" * * Given: * ossimFilename f = "foo.jpg"; * f.setExtension(".tif"); * f now equals "foo.tif" * * Given: * ossimFilename f = "foo."; * ossimFilename f2; * f2 = f.setExtension("tif"); * f now equals "foo.tif" * f2 now equals "foo.tif" * * @param e Extension to add or replace. * * @returns a reference to this. */ ossimFilename& setExtension(const ossimString& e); /** * Sets the file path and drive. * Input: the drive to be set (this should come from the user's preferences) * Example: "x:" * Given: "/filepath/file.ext" * @return @return "c:\filepath\file.ext". */ ossimFilename& setDrive(const ossimString& d); ossimFilename& setPath(const ossimString& p); ossimFilename& setFile(const ossimString& f); void split(ossimString& drivePart, ossimString& pathPart, ossimString& filePart, ossimString& extPart)const; void merge(const ossimString& drivePart, const ossimString& pathPart, const ossimString& filePart, const ossimString& extPart); /*! * Returns file appended onto this string. Path seperator is always placed * between this and file. Returns file if this string is empty. * Given: this = /foo and file = bar output = /foo/bar * Given: this = /foo/ and file = bar output = /foo/bar */ ossimFilename dirCat(const ossimFilename& file) const; /*! */ bool createDirectory(bool recurseFlag=true, int perm=0775)const; /*! * @brief Removes pathname from filesystem if supported by platform. * * If pathname is a directory it will only be removed if empty. If supported * will set errno and output equivalent string if one occurs. * * @return true on success, false on error. */ static bool remove(const ossimFilename& pathname); /** * Will use a wildcard remove. NOTE: This is in * a regular expression format so if you want all * files with prefix myfile to be erased then you would give * it /myfile.* * * The . here is a regular expression '.' character which says any character * and the * "is any number of" * */ static bool wildcardRemove(const ossimFilename& pathname); bool rename(const ossimFilename& destFile, bool overwriteDestinationFlag=true)const; bool remove()const; bool wildcardRemove()const; /** * @brief Copies this file to output file. * * Copies this to output file. If output file is a directory, this->file() is * appended to output file. * * @param outputFile File name to copy to. * * @return True on success, false on error. */ bool copyFileTo(const ossimFilename& outputFile) const; /** * @brief Checks whether file name is relative or absolute. * * @return true if file name has a relative path, false if absolute. * * @note This will return true if file name is empty. */ bool isRelative() const; /** * @brief Method to check if expansion is needed. * * This checks if file isRelative() first if isRelative is false (has * absolute path) it then walks the file and looks for '$'. * * @return true if file name is relative or has environment vars. * * @note This will return false if file name is empty. */ bool needsExpansion() const; /** @return The path separator. */ char getPathSeparator() const; /** * Convenience method to append a generic timestamp to the base-name portion of the filename. * This is useful for establishing rolling names for temporary files and logs. Returns this. */ ossimFilename& appendTimestamp(); /** * Convenience method to append a string to the base-name portion of the filename. Returns this. */ ossimFilename& append(const ossimString& append_this_to_filename); /** * @return This as a string converted to native slashes. */ std::string native() const; protected: /** * @brief Converts slashes of this to internal '/' format. */ void converPathSeparator(); // void convertToNative(); /*! * since windows uses \ for path separation * and unix / we need to be consistent. */ static const char OSSIM_NATIVE_PATH_SEPARATOR; static const char OSSIM_FILENAME_PATH_SEPARATOR; }; // inline std::ostream& operator<<(std::ostream& os, const ossimFilename& f) // { // return os << f.string().c_str(); // } #endif ossim-Miami-2.9.1/include/ossim/base/ossimFilenameProperty.h000066400000000000000000000041531352751253100241160ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimFilenameProperty.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimFilenameProperty_HEADER #define ossimFilenameProperty_HEADER #include #include #include #include class OSSIMDLLEXPORT ossimFilenameProperty : public ossimProperty { public: enum ossimFilenamePropertyIoType { ossimFilenamePropertyIoType_NOT_SPECIFIED = 0, ossimFilenamePropertyIoType_INPUT = 1, ossimFilenamePropertyIoType_OUTPUT = 2 }; ossimFilenameProperty(const ossimString& name = ossimString(""), const ossimFilename& value = ossimFilename(""), const std::vector& filterList = std::vector()); ossimFilenameProperty(const ossimFilenameProperty& rhs); virtual ~ossimFilenameProperty(); ossimObject* dup()const; virtual void valueToString(ossimString& valueResult)const; virtual bool setValue(const ossimString& value); const ossimFilenameProperty& operator = (ossimFilenameProperty& rhs); virtual const ossimProperty& assign(const ossimProperty& rhs); void clearFilterList(); ossim_uint32 getNumberOfFilters()const; void setFilter(ossim_uint32 idx, const ossimString& filterValue); ossimString getFilter(ossim_uint32 idx)const; ossimString getFilterListAsString(const ossimString& separator=ossimString("\n"))const; const std::vector& getFilterList()const; void addFilter(const ossimString& filter); void setIoType(ossimFilenamePropertyIoType ioType); ossimFilenamePropertyIoType getIoType()const; bool isIoTypeInput()const; bool isIoTypeOutput()const; protected: ossimFilename theValue; std::vector theFilterList; ossimFilenamePropertyIoType theIoType; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimFlexLexer.h000066400000000000000000000136151352751253100225320ustar00rootroot00000000000000// $Header$ // FlexLexer.h -- define interfaces for lexical analyzer classes generated // by flex // Copyright (c) 1993 The Regents of the University of California. // All rights reserved. // // This code is derived from software contributed to Berkeley by // Kent Williams and Tom Epperly. // // Redistribution and use in source and binary forms with or without // modification are permitted provided that: (1) source distributions retain // this entire copyright notice and comment, and (2) distributions including // binaries display the following acknowledgement: ``This product includes // software developed by the University of California, Berkeley and its // contributors'' in the documentation or other materials provided with the // distribution and in all advertising materials mentioning features or use // of this software. Neither the name of the University nor the names of // its contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // This file defines FlexLexer, an abstract class which specifies the // external interface provided to flex C++ lexer objects, and yyFlexLexer, // which defines a particular lexer class. // // If you want to create multiple lexer classes, you use the -P flag // to rename each yyFlexLexer to some other xxFlexLexer. You then // include in your other sources once per lexer class: // // #undef yyFlexLexer // #define yyFlexLexer xxFlexLexer /*#include */ // // #undef yyFlexLexer // #define yyFlexLexer zzFlexLexer /* #include */ // ... #ifndef OSSIM__FLEX_LEXER_H // Never included before - need to define base class. #define OSSIM__FLEX_LEXER_H #include #include extern "C++" { struct yy_buffer_state; typedef int yy_state_type; class OSSIMDLLEXPORT FlexLexer { public: virtual ~FlexLexer() { } const char* YYText() { return yytext; } int YYLeng() { return yyleng; } virtual void yy_switch_to_buffer( struct yy_buffer_state* new_buffer ) = 0; virtual struct yy_buffer_state* yy_create_buffer( std::istream* s, int size ) = 0; virtual void yy_delete_buffer( struct yy_buffer_state* b ) = 0; virtual void yyrestart( std::istream* s ) = 0; virtual int yylex() = 0; // Call yylex with new input/output sources. int yylex( std::istream* new_in, std::ostream* new_out = 0 ) { switch_streams( new_in, new_out ); return yylex(); } // Switch to new input/output streams. A nil stream pointer // indicates "keep the current one". virtual void switch_streams( std::istream* new_in = 0, std::ostream* new_out = 0 ) = 0; int lineno() const { return yylineno; } int debug() const { return yy_flex_debug; } void set_debug( int flag ) { yy_flex_debug = flag; } protected: char* yytext; int yyleng; int yylineno; // only maintained if you use %option yylineno int yy_flex_debug; // only has effect with -d or "%option debug" }; } #endif #if defined(yyFlexLexer) || ! defined(yyFlexLexerOnce) // Either this is the first time through (yyFlexLexerOnce not defined), // or this is a repeated include to define a different flavor of // yyFlexLexer, as discussed in the flex man page. #define yyFlexLexerOnce class OSSIMDLLEXPORT yyFlexLexer : public FlexLexer { public: // arg_yyin and arg_yyout default to the cin and cout, but we // only make that assignment when initializing in yylex(). yyFlexLexer( std::istream* arg_yyin = 0, std::ostream* arg_yyout = 0 ); virtual ~yyFlexLexer(); void yy_switch_to_buffer( struct yy_buffer_state* new_buffer ); struct yy_buffer_state* yy_create_buffer( std::istream* s, int size ); void yy_delete_buffer( struct yy_buffer_state* b ); void yyrestart( std::istream* s ); virtual int yylex(); virtual void switch_streams( std::istream* new_in, std::ostream* new_out ); protected: virtual int LexerInput( char* buf, int max_size ); virtual void LexerOutput( const char* buf, int size ); virtual void LexerError( const char* msg ); void yyunput( int c, char* buf_ptr ); int yyinput(); void yy_load_buffer_state(); void yy_init_buffer( struct yy_buffer_state* b, std::istream* s ); void yy_flush_buffer( struct yy_buffer_state* b ); int yy_start_stack_ptr; int yy_start_stack_depth; int* yy_start_stack; void yy_push_state( int new_state ); void yy_pop_state(); int yy_top_state(); yy_state_type yy_get_previous_state(); yy_state_type yy_try_NUL_trans( yy_state_type current_state ); int yy_get_next_buffer(); std::istream* yyin; // input source for default LexerInput std::ostream* yyout; // output sink for default LexerOutput struct yy_buffer_state* yy_current_buffer; // yy_hold_char holds the character lost when yytext is formed. char yy_hold_char; // Number of characters read into yy_ch_buf. int yy_n_chars; // Points to current character in buffer. char* yy_c_buf_p; int yy_init; // whether we need to initialize int yy_start; // start state number // Flag which is used to allow yywrap()'s to do buffer switches // instead of setting up a fresh yyin. A bit of a hack ... int yy_did_buffer_switch_on_eof; // The following are not always needed, but may be depending // on use of certain flex features (like REJECT or yymore()). yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; yy_state_type* yy_state_buf; yy_state_type* yy_state_ptr; char* yy_full_match; int* yy_full_state; int yy_full_lp; int yy_lp; int yy_looking_for_trail_begin; int yy_more_flag; int yy_more_len; int yy_more_offset; int yy_prev_more_offset; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimFontInformation.h000066400000000000000000000057771352751253100237620ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimFontInformation.h 23353 2015-06-01 19:19:10Z dburken $ #ifndef ossimFontInformation_HEADER #define ossimFontInformation_HEADER #include #include #include class ossimKeywordlist; class OSSIM_DLL ossimFontInformation { public: friend OSSIMDLLEXPORT std::ostream& operator << (std::ostream& out, const ossimFontInformation& rhs); ossimFontInformation(); ossimFontInformation(const ossimString& family, const ossimString& style, const ossimIpt& pointSize, bool fixedFlag, const ossimDpt& scale=ossimDpt(1.0,1.0), double rotation = 0.0, const ossimDpt& shear=ossimDpt(0.0, 0.0)); ossimFontInformation(const ossimFontInformation& rhs); bool isFixed()const; /** * Saves the current state of this object. * * For keywords see loadState: */ bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. * * Keywords: * * family_name: * style_name: * fixed_flag: * point_size: ( x, y ) * scale: ( x, y ) * shear: ( x, y ) * rotation: * * point_size_x: (deprecated) * point_size_y: (deprecated) * scale_x: (deprecated) * scale_y: (deprecated) * shear_x: (deprecated) * shear_y: (deprecated) */ bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); bool operator ==(const ossimFontInformation& rhs)const; bool operator !=(const ossimFontInformation& rhs)const; const ossimFontInformation& operator =(const ossimFontInformation& rhs); static const char* FAMILY_NAME_KW; static const char* STYLE_NAME_KW; static const char* POINT_SIZE_KW; // point_size: ( x, y ) static const char* POINT_SIZE_X_KW; // deprecated static const char* POINT_SIZE_Y_KW; // deprecated static const char* FIXED_FLAG_KW; static const char* SHEAR_KW; // shear: ( x, y ) static const char* SHEAR_X_KW; // deprecated static const char* SHEAR_Y_KW; // deprecated static const char* SCALE_KW; // scale: ( x, y ) static const char* SCALE_X_KW; // deprecated static const char* SCALE_Y_KW; // deprecated static const char* ROTATION_KW; ossimString theFamilyName; ossimString theStyleName; ossimIpt thePointSize; bool theFixedFlag; ossimDpt theScale; double theRotation; ossimDpt theShear; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimFontProperty.h000066400000000000000000000021431352751253100233010ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimFontProperty.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimFontProperty_HEADER #define ossimFontProperty_HEADER #include #include class OSSIMDLLEXPORT ossimFontProperty : public ossimProperty { public: ossimFontProperty(const ossimString& name, const ossimFontInformation& value); ossimFontProperty(const ossimFontProperty& rhs); virtual ~ossimFontProperty(); virtual ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; void setFontInformation(ossimFontInformation& fontInfo); const ossimFontInformation& getFontInformation()const; protected: ossimFontInformation theValue; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimFpt.h000066400000000000000000000034361352751253100213650ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration for fpt. // Used to represent a two dimensional point containing data members x and y. //******************************************************************* // $Id: ossimFpt.h 14789 2009-06-29 16:48:14Z dburken $ #ifndef ossimFpt_HEADER #define ossimFpt_HEADER #include #include // Forward class declarations. class ossimIpt; class ossimDpt; class OSSIMDLLEXPORT ossimFpt { public: ossimFpt() : x(0), y(0) {} ossimFpt(ossim_float32 x, ossim_float32 y) : x(x), y(y) {} ossimFpt(ossim_float64 x, ossim_float64 y) : x((ossim_float64)x), y((ossim_float64)y) {} ossimFpt(const ossimFpt& pt) : x(pt.x), y(pt.y) {} ossimFpt(const ossimDpt& pt); ossimFpt(const ossimIpt& pt); const ossimFpt& operator=(const ossimFpt& pt); const ossimFpt& operator=(const ossimDpt&); const ossimFpt& operator=(const ossimIpt&); bool operator==(const ossimFpt& pt) const { return ( (x == pt.x) && (y == pt.y) ); } bool operator!=(const ossimFpt& pt) const { return ( (x != pt.x) || (y != pt.y) ); } void makeNan(){x = ossim::nan(); y=ossim::nan();} bool hasNans()const { return (ossim::isnan(x) || ossim::isnan(y)); } void print(std::ostream& os) const; friend std::ostream& operator<<(std::ostream& os, const ossimFpt& pt); //*** // Public data members: //*** ossim_float32 x; ossim_float32 y; }; inline const ossimFpt& ossimFpt::operator=(const ossimFpt& pt) { if (this != &pt) { x = pt.x; y = pt.y; } return *this; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimFpt3d.h000066400000000000000000000022011352751253100216010ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken (dburken@imagelinks.com) // // Description: // // Contains class declaration for fpt3d. // // Used to represent a three dimensional point containing an x and y data // member. // //******************************************************************* // $Id: ossimFpt3d.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimFpt3d_HEADER #define ossimFpt3d_HEADER #include #include class OSSIMDLLEXPORT ossimFpt3d { public: ossimFpt3d() : x(0.0), y(0.0), z(0.0) {} ossimFpt3d(const ossim_float32& aX, const ossim_float32& aY, const ossim_float32& aZ) : x(aX), y(aY), z(aZ) {} ossimFpt pt2d() const { return ossimFpt(x, y); } ostream& print(std::ostream& os) const; friend std::ostream& operator<<(std::ostream& os, const ossimFpt3d& pt); friend std::istream& operator>>(std::istream& is, ossimFpt3d& pt); ossim_float32 x; ossim_float32 y; ossim_float32 z; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGDoptimizer.h000066400000000000000000000034731352751253100230720ustar00rootroot00000000000000/** * @author Dylan Thomas Cannisi * @date 07/24/2017 * * @brief Simple Gradient Descent optimizer for ossim. * * See top level LICENSE.txt file. */ #ifndef OSSIM_GDOPTIMIZER_H #define OSSIM_GDOPTIMIZER_H #include #include #include class OSSIMDLLEXPORT ossimGDoptimizer{ public: /** * @brief Public Copy constructor */ ossimGDoptimizer(); /** * @brief Public Copy constructor * * @param[in] src The object to be copied (copies pointer not a copy of function) */ ossimGDoptimizer(const ossimGDoptimizer& src); /** * @brief Destroys the object !DOES NOT DELETE FUNCTION! */ ~ossimGDoptimizer(); /** * @brief Public Constructor with a preset function * * @param function The function to be optimized */ ossimGDoptimizer(ossimTerm* function); /** * @brief Sets the function to be optimized * * @param function The function to be optimized * * @return whether or not the optimizer already contained a function */ bool setFunction(ossimTerm* function); /** * @brief Optimizes the function * * @param[in] startPoint The start point at which the algorithm starts its descent * @param[in] gamma Determins the step size as a function of the gradient * @param[in] precision The stopping point at which the algorithm will no longer descend * @param[in] maxEpoch The stopping point to limit infinite loops. * * @return the optimial minima */ std::vector optimize(std::vector startPoint, ossim_float64 gamma = 0.001, ossim_float64 precision = 0.0001, ossim_uint32 maxEpoch = 10000) const; private: // Stores the multivariant function to be optimized. ossimTerm* m_func; }; #endif // OSSIM_GDOPTIMIZER_Hossim-Miami-2.9.1/include/ossim/base/ossimGeoPolygon.h000066400000000000000000000067501352751253100227200ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimPolygon.h // // Copyright (C) 2001 ImageLinks, Inc. // // License: See top level LICENSE.txt file. // // AUTHOR: Garrett Potts // //***************************************************************************** // $Id: ossimGeoPolygon.h 23166 2015-02-24 20:57:50Z dburken $ #ifndef ossimGeoPolygon_HEADER #define ossimGeoPolygon_HEADER #include #include class ossimKeywordlist; class OSSIMDLLEXPORT ossimGeoPolygon { public: friend OSSIM_DLL std::ostream& operator <<(std::ostream& out, const ossimGeoPolygon& poly); ossimGeoPolygon(); ossimGeoPolygon(const std::vector& points); ossimGeoPolygon(const ossimGeoPolygon& rhs); bool addWmsBbox(const ossimString& wmsBbox); void addPoint(const ossimGpt& pt) { theVertexList.push_back(pt); } void addPoint(double lat, double lon, double h=ossim::nan(), const ossimDatum* datum=0) { theVertexList.push_back(ossimGpt(lat, lon, h, datum)); } void addAttribute( const ossimString& attribute ) { theAttributeList.push_back( attribute ); } void addHole( const ossimGeoPolygon& polygon ) { theHoleList.push_back( polygon ); } ossimGpt& operator[](int index) { return theVertexList[index]; } const ossimGpt& operator[](int index)const { return theVertexList[index]; } const std::vector& getVertexList()const { return theVertexList; } std::vector& getAttributeList() { return theAttributeList; } std::vector& getHoleList() { return theHoleList; } void clear() { theVertexList.clear(); } ossim_uint32 size()const { return (ossim_uint32)theVertexList.size(); } void resize(ossim_uint32 newSize) { theVertexList.resize(newSize); theCurrentVertex = 0; theOrderingType = OSSIM_VERTEX_ORDER_UNKNOWN; } const ossimGeoPolygon& operator = (const std::vector& rhs) { theVertexList = rhs; theCurrentVertex = 0; theOrderingType = OSSIM_VERTEX_ORDER_UNKNOWN; return *this; } const ossimGeoPolygon& operator = (const ossimGeoPolygon& rhs); void stretchOut(ossimGeoPolygon& newPolygon, double displacement); double area()const; ossimGpt computeCentroid()const; bool vertex(int index, ossimGpt& v) const; bool nextVertex(ossimDpt& v) const; bool hasNans()const; void reverseOrder(); bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); void checkOrdering()const; ossimVertexOrdering getOrdering()const { if(theOrderingType == OSSIM_VERTEX_ORDER_UNKNOWN) { checkOrdering(); } return theOrderingType; } void setOrdering(ossimVertexOrdering ordering) { theOrderingType = ordering; } protected: std::vector theVertexList; std::vector theAttributeList; std::vector theHoleList; mutable ossim_int32 theCurrentVertex; /*! * This enumeration is found in ossimConstants.h */ mutable ossimVertexOrdering theOrderingType; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGeoTiffCoordTransformsLut.h000066400000000000000000000044131352751253100257060ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration for GeoTiffCoordTransformsLut. Used to map a // geotiff coordinate transformation code to an ossim projection. //******************************************************************* // $Id: ossimGeoTiffCoordTransformsLut.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimGeoTiffCoordTransformsLut_HEADER #define ossimGeoTiffCoordTransformsLut_HEADER #include #include class OSSIMDLLEXPORT ossimGeoTiffCoordTransformsLut : public ossimLookUpTable { public: enum { //*** // Coordinate Transformation Codes cut from geotiff specification // section 6.3.3.3. //*** CT_TransverseMercator = 1, CT_TransvMercator_Modified_Alaska = 2, CT_ObliqueMercator = 3, CT_ObliqueMercator_Laborde = 4, CT_ObliqueMercator_Rosenmund = 5, CT_ObliqueMercator_Spherical = 6, CT_Mercator = 7, CT_LambertConfConic_2SP = 8, CT_LambertConfConic_Helmert = 9, CT_LambertAzimEqualArea = 10, CT_AlbersEqualArea = 11, CT_AzimuthalEquidistant = 12, CT_EquidistantConic = 13, CT_Stereographic = 14, CT_PolarStereographic = 15, CT_ObliqueStereographic = 16, CT_Equirectangular = 17, CT_CassiniSoldner = 18, CT_Gnomonic = 19, CT_MillerCylindrical = 20, CT_Orthographic = 21, CT_Polyconic = 22, CT_Robinson = 23, CT_Sinusoidal = 24, CT_VanDerGrinten = 25, CT_NewZealandMapGrid = 26, CT_TransvMercator_SouthOriented = 27 }; ossimGeoTiffCoordTransformsLut(); virtual ~ossimGeoTiffCoordTransformsLut(){} virtual ossimKeyword getKeyword() const { return ossimKeyword("geotiff_coordinate_transform_code", ""); } }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGeoTiffDatumLut.h000066400000000000000000000044511352751253100236350ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2001 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration for GeoTiffDatumLut. Used to map a // geotiff coordinate transformation code to an ossim projection. //******************************************************************* // $Id: ossimGeoTiffDatumLut.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimGeoTiffDatumLut_HEADER #define ossimGeoTiffDatumLut_HEADER #include #include class OSSIMDLLEXPORT ossimGeoTiffDatumLut : public ossimLookUpTable { public: enum { //--- // Datum codes cut from geotiff specification section 6.3.2.1. //--- GCS_Adindan = 4201, GCS_Arc_1950 = 4209, GCS_Arc_1960 = 4210, GCS_ED50 = 4230, GCS_NAD27 = 4267, GCS_NAD83 = 4269, GCS_OSGB_1936 = 4277, GCS_WGS_72 = 4322, GCS_WGS_84 = 4326, GCS_Tokyo = 4301, GCS_NAD83_HARN = 4152, //--- // Datum codes cut from geotiff specification section 6.3.2.1. // NOTE: These codes imply an ellipsoid only! //--- GCS_Clark_1866 = 4008, //--- // Datum codes cut from geotiff specification section 6.3.2.2. //--- DatumE_WGS84 = 6030, Datum_Adindan = 6201, Datum_Arc_1950 = 6209, Datum_Arc_1960 = 6210, Datum_European_Datum_1950 = 6230, Datum_North_American_Datum_1927 = 6267, Datum_North_American_Datum_1983 = 6269, Datum_OSGB_1936 = 6277, Datum_Tokyo = 6301, Datum_WGS72 = 6322, Datum_WGS84 = 6326, Datum_NAD83_HARN = 6152 }; ossimGeoTiffDatumLut(); virtual ~ossimGeoTiffDatumLut(); virtual ossimKeyword getKeyword() const; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGeocent.h000066400000000000000000000130221352751253100222100ustar00rootroot00000000000000#ifndef GEOCENT_H #define GEOCENT_H 1 /***************************************************************************/ /* RSC IDENTIFIER: GEOCENTRIC * * ABSTRACT * * This component provides conversions between Geodetic coordinates (latitude, * longitude in radians and height in meters) and Geocentric coordinates * (X, Y, Z) in meters. * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid value * is found, the error code is combined with the current error code using * the bitwise or. This combining allows multiple error codes to be * returned. The possible error codes are: * * GEOCENT_NO_ERROR : No errors occurred in function * GEOCENT_LAT_ERROR : Latitude out of valid range * (-90 to 90 degrees) * GEOCENT_LON_ERROR : Longitude out of valid range * (-180 to 360 degrees) * GEOCENT_A_ERROR : Semi-major axis less than or equal to zero * GEOCENT_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * * * REUSE NOTES * * GEOCENTRIC is intended for reuse by any application that performs * coordinate conversions between geodetic coordinates and geocentric * coordinates. * * * REFERENCES * * An Improved Algorithm for Geocentric to Geodetic Coordinate Conversion, * Ralph Toms, February 1996 UCRL-JC-123138. * * Further information on GEOCENTRIC can be found in the Reuse Manual. * * GEOCENTRIC originated from : U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * GEOCENTRIC has no restrictions. * * ENVIRONMENT * * GEOCENTRIC was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC version 2.8.1 * 2. Windows 95 with MS Visual C++ version 6 * * MODIFICATIONS * * Date Description * ---- ----------- * * */ #include /***************************************************************************/ /* * DEFINES */ #define GEOCENT_NO_ERROR 0x0000 #define GEOCENT_LAT_ERROR 0x0001 #define GEOCENT_LON_ERROR 0x0002 #define GEOCENT_A_ERROR 0x0004 #define GEOCENT_INV_F_ERROR 0x0008 /***************************************************************************/ /* * FUNCTION PROTOTYPES */ /* ensure proper linkage to c++ programs */ #ifdef __cplusplus extern "C" { #endif OSSIM_DLL long Set_Geocentric_Parameters (double a, double f); /* * The function Set_Geocentric_Parameters receives the ellipsoid parameters * as inputs and sets the corresponding state variables. * * a : Semi-major axis of ellipsoid, in meters. (input) * f : Flattening of ellipsoid. (input) */ OSSIM_DLL void Get_Geocentric_Parameters (double *a, double *f); /* * The function Get_Geocentric_Parameters returns the ellipsoid parameters * to be used in geocentric coordinate conversions. * * a : Semi-major axis of ellipsoid, in meters. (output) * f : Flattening of ellipsoid. (output) */ OSSIM_DLL long Convert_Geodetic_To_Geocentric (double Latitude, double Longitude, double Height, double *X, double *Y, double *Z); /* * The function Convert_Geodetic_To_Geocentric converts geodetic coordinates * (latitude, longitude, and height) to geocentric coordinates (X, Y, Z), * according to the current ellipsoid parameters. * * Latitude : Geodetic latitude in radians (input) * Longitude : Geodetic longitude in radians (input) * Height : Geodetic height, in meters (input) * X : Calculated Geocentric X coordinate, in meters. (output) * Y : Calculated Geocentric Y coordinate, in meters. (output) * Z : Calculated Geocentric Z coordinate, in meters. (output) * */ OSSIM_DLL void Convert_Geocentric_To_Geodetic (double X, double Y, double Z, double *Latitude, double *Longitude, double *Height); /* * The function Convert_Geocentric_To_Geodetic converts geocentric * coordinates (X, Y, Z) to geodetic coordinates (latitude, longitude, * and height), according to the current ellipsoid parameters. * * X : Geocentric X coordinate, in meters. (input) * Y : Geocentric Y coordinate, in meters. (input) * Z : Geocentric Z coordinate, in meters. (input) * Latitude : Calculated latitude value in radians. (output) * Longitude : Calculated longitude value in radians. (output) * Height : Calculated height value, in meters. (output) */ #ifdef __cplusplus } #endif #endif /* GEOCENT_H */ ossim-Miami-2.9.1/include/ossim/base/ossimGeodeticEvaluator.h000066400000000000000000000037211352751253100242370ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: GeodeticEvaluator class. //---------------------------------------------------------------------------- #ifndef ossimGeodeticEvaluator_HEADER #define ossimGeodeticEvaluator_HEADER 1 #include #include #include class OSSIM_DLL ossimGeodeticEvaluator { public: /** * @brief constructor. * Defaults to WGS-84 */ ossimGeodeticEvaluator(const ossimEllipsoid& ell = ossimEllipsoid()); /** * @brief virtual destructor. */ ~ossimGeodeticEvaluator(); /** * @brief Evaluate direct problem. * @brief Given: Point 1 position, azimuth & distance to point 2. * @brief Find: Point 2 position, azimuth from point 2 to point 1. * * @param p1 Point 1. * @param az1 Azimuth from point 1 to point 2. * @param d Distance between points 1 & 2. * @param p2 Point 2. * @param az2 Azimuth from point 2 to point 1. */ bool direct( const ossimGpt& p1, const double& az1, const double& d, ossimGpt& p2, double& az2); /** * @brief Evaluate Vincenty inverse problem. * @brief Given: Point 1 & point 2 positions. * @brief Find: Distance and azimuths between points. * * @param p1 Point 1. * @param p2 Point 2. * @param d Distance between points 1 & 2. * @param az12 Azimuth from point 1 to point 2. * @param az21 Azimuth from point 2 to point 1. */ bool inverse( const ossimGpt& p1, const ossimGpt& p2, double& d, double& az12, double& az21); protected: double m_A; double m_B; double m_F; double m_A2; double m_B2; double m_Ecc2; double m_2ndEcc2; private: }; #endif // #ifndef ossimGeodeticEvaluator_HEADER ossim-Miami-2.9.1/include/ossim/base/ossimGeoid.h000066400000000000000000000030001352751253100216460ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of class ossimGeoid. Maintains a grid of elevation // offsets for the geoid (mean sea level) relative to WGS-84 ellipsoid. // // SOFTWARE HISTORY: //> // 17Apr2001 Oscar Kramer // Initial coding. //< //***************************************************************************** #ifndef ossimGeoid_HEADER #define ossimGeoid_HEADER #include #include class ossimGpt; class ossimFilename; class OSSIMDLLEXPORT ossimGeoid : public ossimObject, public ossimErrorStatusInterface { public: ossimGeoid(); virtual bool open(const ossimFilename& dir, ossimByteOrder byteOrder=OSSIM_BIG_ENDIAN) = 0; /** * @return The offset from the ellipsoid to the geoid. Returns * ossim::nan() if grid does not contain the point. */ virtual double offsetFromEllipsoid(const ossimGpt& gpt) = 0; protected: virtual ~ossimGeoid(); TYPE_DATA }; /** * Identity geoid. */ class OSSIM_DLL ossimIdentityGeoid : public ossimGeoid { public: virtual ossimString getShortName()const { return ossimString("identity"); } virtual bool open(const ossimFilename& /*dir*/, ossimByteOrder) { return false; // can't be opened } virtual double offsetFromEllipsoid(const ossimGpt& /*gpt*/) { return 0.0; } TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGeoidEgm96.h000066400000000000000000000034471352751253100224750ustar00rootroot00000000000000//******************************************************************* // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class definition for ossimGeoidEgm96 which is // "Earth Gravity Model 1996". // //******************************************************************* // $Id: ossimGeoidEgm96.h 22900 2014-09-30 09:56:11Z dburken $ #ifndef ossimGeoidEgm96_HEADER #define ossimGeoidEgm96_HEADER #include #include #define GEOID_NO_ERROR 0x0000 #define GEOID_FILE_OPEN_ERROR 0x0001 #define GEOID_INITIALIZE_ERROR 0x0002 #define GEOID_NOT_INITIALIZED_ERROR 0x0004 #define GEOID_LAT_ERROR 0x0008 #define GEOID_LON_ERROR 0x0010 class ossimGpt; class OSSIMDLLEXPORT ossimGeoidEgm96 : public ossimGeoid { public: ossimGeoidEgm96(); ossimGeoidEgm96(const ossimFilename& grid_file, ossimByteOrder byteOrder=OSSIM_BIG_ENDIAN); virtual ~ossimGeoidEgm96(); virtual bool open(const ossimFilename& grid_file, ossimByteOrder byteOrder=OSSIM_BIG_ENDIAN); virtual ossimString getShortName()const; /** * @return The offset from the ellipsoid to the geoid or ossim::nan() * (IEEE NAN) if grid does not contain the point. */ virtual double offsetFromEllipsoid(const ossimGpt& gpt); double geoidToEllipsoidHeight(double lat, double lon, double geoidHeight); double ellipsoidToGeoidHeight(double lat, double lon, double ellipsoidHeight); protected: std::vector theGeoidHeightBuffer; mutable float* theGeoidHeightBufferPtr; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGeoidImage.h000066400000000000000000000064551352751253100226320ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Generic geoid source which uses an image handler for reading the grid. // //---------------------------------------------------------------------------- #ifndef ossimGeoidImage_HEADER #define ossimGeoidImage_HEADER 1 #include #include #include #include #include class ossimFilename; /** * @class ossimGeoidImage * * Generic geoid source which uses a image handler for reading the grid. * * The settable keyword "geoid.type", e.g. "egm2008" is used to attach a given geoid * to an elevation source. * * The keyword "type" is fixed for this object as "geoid_image". */ class OSSIM_DLL ossimGeoidImage : public ossimGeoid { public: /** @brief default constructor */ ossimGeoidImage(); /** @brief destructor */ virtual ~ossimGeoidImage(); /** * @brief open method * @param file This can be any image that ossim can open and get geometry * info for. * @param byteOrder Not used by this object. * @return true on success, false on erro. */ virtual bool open( const ossimFilename& file, ossimByteOrder byteOrder=OSSIM_BIG_ENDIAN ); /** * @return The short name which represents the "geoid.type" keyword which is * used by ossimGeoidFactory. */ virtual ossimString getShortName() const; /** @brief Sets the geoid type name string. */ void setShortName( const std::string& geoidTypeName ); /** * @brief Gets the memory map flag. * @return true if geoid image is memory mapped; else, false. */ bool getMemoryMapFlag() const; /** * @brief Set the memory map flag. */ void setMemoryMapFlag( bool flag ); /** * Method to save the state of the object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /** * Method to the load (recreate) the state of the object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @return The offset from the ellipsoid to the geoid or ossim::nan() * (IEEE NAN) if grid does not contain the point. */ virtual double offsetFromEllipsoid(const ossimGpt& gpt); bool getEnableFlag() const; void setEnableFlag(bool flag); protected: template double offsetFromEllipsoidTemplate(T dummy, const ossimGpt& gpt); ossimRefPtr m_geom; ossimRefPtr m_handler; ossimRefPtr m_cacheTile; std::string m_connectionString; ossimString m_geoidTypeName; bool m_memoryMapFlag; bool m_enabledFlag; ossimIrect m_imageRect; ossimScalarType m_scalarType; }; #endif /* #define ossimGeoidImage_HEADER 1 */ ossim-Miami-2.9.1/include/ossim/base/ossimGeoidManager.h000066400000000000000000000050051352751253100231500ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains declaration of class ossimGeoidManager. Maintains // a list of geoids. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimGeoidManager.h 22900 2014-09-30 09:56:11Z dburken $ #ifndef ossimGeoidManager_HEADER #define ossimGeoidManager_HEADER #include #include #include /***************************************************************************** * * CLASS: ossimGeoidManager * *****************************************************************************/ class OSSIMDLLEXPORT ossimGeoidManager : public ossimGeoid { public: virtual ~ossimGeoidManager(); /** * Implements singelton pattern: */ static ossimGeoidManager* instance(); /** * Permits initialization of geoids from directory name. Should never be * called since called on specific geoid types: */ virtual bool open(const ossimFilename& dir, ossimByteOrder byteOrder); /** * @return The offset from the ellipsoid to the geoid or ossim::nan() * if grid does not contain the point. */ virtual double offsetFromEllipsoid(const ossimGpt& gpt); /** * Method to save the state of the object to a keyword list. * Return true if ok or false on error. DO NOTHING */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /** * Method to the load (recreate) the state of the object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Permits adding additional geoids to the list: */ virtual void addGeoid(ossimRefPtr geoid, bool toFrontFlag=false); ossimGeoid* findGeoidByShortName(const ossimString& shortName, bool caseSensitive=true); /** * Permits to clear the GeoidList */ virtual void clear(); private: /** * Private constructor. Use "instance" method. */ ossimGeoidManager(); //static ossimGeoidManager* theInstance; mutable std::vector< ossimRefPtr > theGeoidList; // will use this as a identity if one wants but don't want it part of the internal list // ossimRefPtr theIdentityGeoid; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGeoidNgs.h000066400000000000000000000035521352751253100223320ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id: ossimGeoidNgs.h 22900 2014-09-30 09:56:11Z dburken $ #ifndef ossimGeoidNgs_HEADER #define ossimGeoidNgs_HEADER #include #include class OSSIMDLLEXPORT ossimGeoidNgs : public ossimGeoid { public: ossimGeoidNgs(); ossimGeoidNgs(const ossimFilename& dir, ossimByteOrder byteOrder = OSSIM_LITTLE_ENDIAN); virtual ~ossimGeoidNgs(); virtual ossimString getShortName()const; virtual bool open(const ossimFilename& dir, ossimByteOrder byteOrder = OSSIM_LITTLE_ENDIAN); virtual bool addFile(const ossimFilename& file, ossimByteOrder byteOrder = OSSIM_LITTLE_ENDIAN); /** * @return The offset from the ellipsoid to the geoid or ossim::nan() * if grid does not contain the point. */ virtual double offsetFromEllipsoid(const ossimGpt&); /** * @return Geoid to ellipsoid height or ossim::nan() * if grid does not contain the point. */ double geoidToEllipsoidHeight(double lat, double lon, double geoidHeight) const; /** * @return Ellipsoid to geoid height or ossim::nan() * if grid does not contain the point. */ double ellipsoidToGeoidHeight(double lat, double lon, double ellipsoidHeight) const; protected: void fixLatLon(double &lat, double &lon) const; double deltaHeight(double lat, double lon)const; std::vector theGridVector; ossimString theShortName; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGeoidNgsHeader.h000066400000000000000000000044061352751253100234420ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimGeoidNgsHeader.h 23353 2015-06-01 19:19:10Z dburken $ #ifndef ossimGeoidNgsHeader_HEADER #define ossimGeoidNgsHeader_HEADER 1 #include #include class OSSIM_DLL ossimGeoidNgsHeader { public: friend OSSIM_DLL std::ostream& operator << (std::ostream &out, const ossimGeoidNgsHeader &data); ossimGeoidNgsHeader(); ossimGeoidNgsHeader(const ossimFilename &fileName, ossimByteOrder byteOrder=OSSIM_LITTLE_ENDIAN); bool initialize(const ossimFilename &fileName, ossimByteOrder byteOrder=OSSIM_LITTLE_ENDIAN); double southernMostLat()const{return theSouthernMostLatitude;} double westernMostLon()const{return theWesternMostLongitude;} double latDelta()const{return theLatDelta;} double lonDelta()const{return theLonDelta;} int rows()const{return theRows;} int cols()const{return theCols;} int dataType()const{return theDataType;} bool pointWithin(double lat, double lon)const; const ossimFilename& filename()const{return theFilename;} int headerSize()const{return 44;} int dataTypeSize()const{return theDataType==1?4:0;} /** @return Height delta or ossim::nan() if not found. */ double getHeightDelta(double lat, double lon)const; private: ossimFilename theFilename; ossimByteOrder theByteOrder; double theSouthernMostLatitude; /*! * Important: The geoid.bin files expresses this as a possitive value. * * example: -90.0 is 270 degrees. */ double theWesternMostLongitude; /*! * Specifies the spacing of the latitude direction. */ double theLatDelta; /*! * longitude spacing. */ double theLonDelta; /*! * theRows specifies the number of lat increments */ int theRows; /*! * theCols specifies the number of lon increments */ int theCols; /*! * Specifies the datatype. if this is 1 then the data that follows * is 4 byte floats. */ int theDataType; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGeoref.h000066400000000000000000000054241352751253100220420ustar00rootroot00000000000000#ifndef ossimGeoref_HEADER #define ossimGeoref_HEADER #include #include class OSSIMDLLEXPORT ossimGeoref { public: ossimGeoref(const ossimString &georefString, long precision); ossimGeoref(const ossimGpt &groundPt); ossimGeoref(); /*! * This function converts Geodetic (latitude and longitude in radians) * coordinates to a GEOREF coordinate string. Precision specifies the * number of digits in the GEOREF string for latitude and longitude: * 0 for nearest degree * 1 for nearest 10 minutes * 2 for nearest minute * 3 for nearest tenth of a minute * 4 for nearest hundredth of a minute * 5 for nearest thousandth of a minute * * Precision : level of precision specified by the user (input) * ossimGeoref : GEOREF coordinate string (return) */ ossimString toString(long precision); private: ossimGpt thePt; // This code belongs to Geotrans /*! * This function converts Geodetic (latitude and longitude in radians) * coordinates to a GEOREF coordinate string. Precision specifies the * number of digits in the GEOREF string for latitude and longitude: * 0 for nearest degree * 1 for nearest 10 minutes * 2 for nearest minute * 3 for nearest tenth of a minute * 4 for nearest hundredth of a minute * 5 for nearest thousandth of a minute * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Precision : level of precision specified by the user (input) * ossimGeoref : GEOREF coordinate string (output) */ long Convert_Geodetic_To_GEOREF (double Latitude, double Longitude, long Precision, char *georef); /*! * This function converts a GEOREF coordinate string to Geodetic (latitude * and longitude in radians) coordinates. * * ossimGeoref : GEOREF coordinate string (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ long Convert_GEOREF_To_Geodetic (char *georef, double *Latitude, double *Longitude); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimGpt.h000066400000000000000000000226061352751253100213660ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt. // // Author: Garrett Potts // // Description: // // Contains class declaration for gpt. // // CONSTRUCTOR TAKES LAT/LON IN DEGREES!!! // // Height is relative to the ellipsoid in meters. // //******************************************************************* // $Id: ossimGpt.h 23159 2015-02-20 20:09:20Z okramer $ #ifndef ossimGpt_HEADER #define ossimGpt_HEADER 1 #include #include #include #include #include #include #include class ossimDatum; class OSSIM_DLL ossimGpt { public: /** * Constructor. The values are assumed to be in DEGREES. */ ossimGpt(const double alat = 0, // degrees const double alon = 0, // degrees const double ahgt = 0, const ossimDatum *aDatum = ossimDatumFactory::instance()->wgs84()) : lat(alat), lon(alon), hgt(ahgt), // relative to the ellipsoid theDatum(aDatum) { } //limitLonTo180();} /** * Copy Constructor: */ ossimGpt(const ossimGpt &src); /** * Constructor. Conversion from geocentric to ground. */ ossimGpt(const ossimEcefPoint &aPt, const ossimDatum *aDatum = ossimDatumFactory::instance()->wgs84()); /** * Argument aPt (x, y, z) is understood to represent (lon, lat, hgt) relative to WGS84 datum. */ ossimGpt(const ossimDpt3d &aPt) : lat(aPt.y), lon(aPt.x), hgt(aPt.z), theDatum(ossimDatumFactory::instance()->wgs84()) {} /** * latr(). Returns the latitude in radian measure. */ double latr() const { return lat * RAD_PER_DEG; } /** * Returns the latitude in radian measure. */ void latr(double radianValue) { lat = radianValue * DEG_PER_RAD; } /** * Returns the longitude in radian measure. */ double lonr() const { return lon * RAD_PER_DEG; } /** * Assumes the value being passed in is in radians. */ void lonr(double radianValue) { lon = radianValue * DEG_PER_RAD; } //limitLonTo180();} /** * Will convert the radian measure to degrees. */ double latd() const { return lat; } /** * Assumes the passed in value is in degrees. */ void latd(double degreeValue) { lat = degreeValue; } /** * Will convert the radian measure to degrees. */ double lond() const { return lon; } /** * Assumes the passed in value is in degrees. */ void lond(double degreeValue) { lon = degreeValue; } //limitLonTo180();} /** * @return Returns the height in meters above the ellipsoid. */ double height() const { return hgt; } /** * @return Returns the height in meters above mean sea level (msl). * * @note This is the height above the ellipsoid minus any geoid offset. */ double heightMSL() const; /** * Sets the "hgt" data member to height. * * @param height Height above the ellipsoid in meters. */ void height(double height) { hgt = height; } /** * Sets the "hgt" data member to heightMsl adding any geiod offset. * * @param heightMSL Height in meters above msl. */ void heightMSL(double heightMSL); void makeNan() { lat = ossim::nan(); lon = ossim::nan(); hgt = ossim::nan(); } bool isNan() const { return (ossim::isnan(lat) && ossim::isnan(lon) && ossim::isnan(hgt)); } bool hasNans() const { return (ossim::isnan(lat) || ossim::isnan(lon) || ossim::isnan(hgt)); } bool isLatNan() const { return ossim::isnan(lat); } bool isLonNan() const { return ossim::isnan(lon); } bool isLonLatNan() const { return (ossim::isnan(lat) || ossim::isnan(lon)); } bool isLatLonNan() const { return (ossim::isnan(lat) || ossim::isnan(lon)); } bool isHgtNan() const { return ossim::isnan(hgt); } std::ostream &print(std::ostream &os, ossim_uint32 precision = 15) const; friend OSSIMDLLEXPORT std::ostream &operator<<(std::ostream &os, const ossimGpt &pt); /** * @param precision Output floating point precision. * * @return ossimString representing point. * * Output format: * ( 30.00000000000000, -90.00000000000000, 0.00000000000000, WGE ) * -----latitude---- -----longitude---- ------height---- datum */ ossimString toString(ossim_uint32 precision = 15) const; /** * Initializes this point from string. This method opens an std::istream to * s and then calls operator>>. * * Expected format: * ( 30.00000000000000, -90.00000000000000, 0.00000000000000, WGE ) * -----latitude---- -----longitude---- ------height---- datum * * @param s String to initialize from. * * @see operator>> */ void toPoint(const std::string &s); /** * Method to input the formatted string of the "operator<<". * * This method starts by doing a "makeNan" on aPt. So if anything goes * wrong with the stream or parsing aPt could be all or partially nan. * * @param is Input stream std::istream to formatted text. * @param aPt osimGpt to be initialized from stream. * @return std::istream pass in. * * Expected format: * ( 30.00000000000000, -90.00000000000000, 0.00000000000000, WGE ) * -----latitude---- -----longitude---- ------height---- datum */ friend OSSIMDLLEXPORT std::istream &operator>>(std::istream &is, ossimGpt &pt); /** * datum(). returns the datum associated with this ground. * */ const ossimDatum *datum() const { return theDatum; } /** * Note: this will not do a shift. This just allows you to set the datum. * If you want an automatic shift to occur then you must call the * changeDatum method */ void datum(const ossimDatum *aDatum) { theDatum = aDatum ? aDatum : theDatum; } /** * This will actually perform a shift. */ void changeDatum(const ossimDatum *datum); const ossimGpt &operator=(const ossimGpt &aPt); bool operator==(const ossimGpt &gpt) const; bool operator!=(const ossimGpt &gpt) const { return !(*this == gpt); } /** * METHOD: limitLonTo180() * Converts the lon data member to a value between -180 and +180: */ void limitLonTo180() { if (lon <= -180.0) lon += 360.0; else if (lon > 180.0) lon -= 360.0; } /** * @brief Wrap method to maintain longitude between -180 and +180 and latitude between * -90 and +90. Inlined below. */ void wrap(); void clampLon(double low, double high) { if (lon < low) lon = low; if (lon > high) lon = high; } void clampLat(double low, double high) { if (lat < low) lat = low; if (lat > high) lat = high; } void clampHgt(double low, double high) { if (hgt < low) hgt = low; if (hgt > high) hgt = high; } /** * METHOD: distanceTo(ossimGpt) * Computes straight-line distance in meters between this and arg gpt: */ double distanceTo(const ossimGpt &arg_gpt) const; /** * METHOD: azimuthTo(ossimGpt) * Computes the great-circle starting azimuth (i.e., at this gpt) to the argument gpt in degrees. * In other words, what direction we would need to start walking in to travel the shortest * distance to arg_gpt (assumes spherical earth) */ double azimuthTo(const ossimGpt &arg_gpt) const; ossimDpt metersPerDegree() const; ossimString toDmsString() const; bool isEqualTo(const ossimGpt &rhs, ossimCompareType compareType = OSSIM_COMPARE_FULL) const; ossim_float64 lat; //> latitude in degrees measure ossim_float64 lon; //> longitude in degrees measure /** * Height in meters above the ellipsiod. * * @note This is NOT the same as "height msl". "Height msl" is above * the geoid or better know as mean sea level. */ ossim_float64 hgt; private: /** * Know reference location plus an implied ellipsoid. */ const ossimDatum *theDatum; }; inline const ossimGpt &ossimGpt::operator=(const ossimGpt &aPt) { if (this != &aPt) { lat = aPt.lat; lon = aPt.lon; hgt = aPt.hgt; if (aPt.datum()) { theDatum = aPt.datum(); } if (!theDatum) { theDatum = ossimDatumFactory::instance()->wgs84(); } } return *this; } inline void ossimGpt::wrap() { // only wrap if values are not nan // may want to change this to isbad because // hey could be INF instead of NAN if (ossim::isnan(lon) || ossim::isnan(lat)) return; if (lon > 180.0) { do { lon = lon - 360.0; } while (lon > 180.0); } else if (lon < -180.0) { do { lon = lon + 360.0; } while (lon < -180.0); } if (lat > 90.0) { if (lat > 360.0) // Remove total wraps. { do { lat = lat - 360.0; } while (lat > 360.0); } if (lat > 270.0) // Between 270 and 360. { lat = lat - 360.0; } else if (lat > 90) // Between 90 and 270. { lat = 180.0 - lat; } } else if (lat < -90.0) { if (lat < -360.0) // Remove total wraps. { do { lat = lat + 360.0; } while (lat < -360.0); } if (lat < -270.0) { lat = 360.0 + lat; // Between -270 and -360; } else if (lat < -90.0) { lat = -180.0 - lat; } } } #endif /* #ifndef ossimGpt_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimGrect.h000066400000000000000000000216651352751253100217040ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGrect.h 23461 2015-08-05 20:20:20Z okramer $ #ifndef ossimGrect_HEADER #define ossimGrect_HEADER 1 #include #include #include #include #include #include class OSSIM_DLL ossimGrect { public: friend OSSIM_DLL std::ostream& operator<<(std::ostream& os, const ossimGrect& rect); /** * Will default to 0,0,0,0. */ ossimGrect() : theUlCorner(0.0, 0.0, 0.0), theLrCorner(0.0, 0.0, 0.0) {} /** * Copies the passed in rectangle to this * object. */ ossimGrect(const ossimGrect& rect) : theUlCorner(rect.ul()), theLrCorner(rect.lr()) {} /** * WIll take two ground points and fill the * bounding rect appropriately. */ ossimGrect(const ossimGpt& p1, const ossimGpt& p2); /** * Takes the upper left and lower right ground * points */ ossimGrect(double ulLat, double ulLon, double lrLat, double lrLon, const ossimDatum* aDatum=ossimDatumFactory::instance()->wgs84()) : theUlCorner(ulLat, ulLon,0, aDatum), theLrCorner(lrLat, lrLon, 0, aDatum) {} ossimGrect(const ossimGpt& point, double latSpacingInDegrees, double lonSpacingInDegrees) : theUlCorner(point), theLrCorner(point) { std::vector v; computeEvenTiles(v, latSpacingInDegrees, lonSpacingInDegrees); if(v.size()) *this = v[0]; } ossimGrect(std::vector& points); ossimGrect(const ossimGpt& p1, const ossimGpt& p2, const ossimGpt& p3, const ossimGpt& p4); const ossimGrect& operator=(const ossimGrect& rect) { theUlCorner = rect.ul(); theLrCorner = rect.lr(); return *this; } inline ossimGpt midPoint()const; /** Returns the height of a rectangle in deg. */ inline ossim_float64 height() const; /** Returns the width of a rectangle in deg. */ inline ossim_float64 width() const; /** Returns the height of a rectangle in meters. */ ossim_float64 heightMeters() const; /** Returns the width of a rectangle in meters using the center lat for scaling EW direction. */ ossim_float64 widthMeters() const; inline const ossimGpt& ul()const; inline const ossimGpt& lr()const; inline ossimGpt ur() const; inline ossimGpt ll() const; inline ossimGpt& ul(); inline ossimGpt& lr(); inline void makeNan(); inline bool isLonLatNan()const; inline bool hasNans()const; inline bool isNan()const; /*! * Returns true if "this" rectangle is contained completely within the * input rectangle "rect". */ bool completely_within(const ossimGrect& rect) const; /*! * Returns true if any portion of an input rectangle "rect" intersects * "this" rectangle. */ bool intersects(const ossimGrect& rect) const; inline ossimGrect clipToRect(const ossimGrect& rect)const; inline ossimGrect combine(const ossimGrect& rect)const; /** * Expands existing rect to accommodate argument point. If this object contains NaNs * (uninitialized), then the rect is set to 0-area with the arg point as both UL and LR -- * convenient for establishing bounds in a loop over collection of points. This method does not * consider height. * @param gpt Argument point. */ void expandToInclude(const ossimGpt& gpt); void expandToInclude(const ossimGrect& rect); /** * METHOD: pointWithin(ossimGpt) * * @param gpt Point to test for withinness. * @param considerHgt true if the height is to be compared to be between ul.hgt and lr.hgt * @return true if argument is inside rectangle (or cuboid when hgt considered) * * @note There is no datum shift applied if * gpt is of a different datum than this datum. */ inline bool pointWithin(const ossimGpt& gpt, bool considerHgt=false) const; //inline below ossimGrect stretchToEvenBoundary(double latSpacingInDegrees, double lonSpacingInDegrees)const; void computeEvenTiles(std::vector& result, double latSpacingInDegrees, double lonSpacingInDegrees, bool clipToGeographicBounds = true)const; private: ossimGpt theUlCorner; // Contains max height as well ossimGpt theLrCorner; // Contains min height as well }; //==================== BEGIN INLINE DEFINITIONS =============================== //***************************************************************************** // INLINE METHOD: ossimGrect::midPoint() //***************************************************************************** inline ossimGpt ossimGrect::midPoint()const { return ossimGpt((ul().latd() + ur().latd() + ll().latd() + lr().latd())*.25, (ul().lond() + ur().lond() + ll().lond() + lr().lond())*.25, (ul().height()+ur().height()+ll().height()+ lr().height())*.25, ul().datum() ); } //***************************************************************************** // INLINE METHOD: ossimGrect::clipToRect() //***************************************************************************** inline ossimGrect ossimGrect::clipToRect(const ossimGrect& rect)const { double ulx, uly, lrx, lry; ulx = ossim::max(rect.ul().lond(),ul().lond()); uly = ossim::min(rect.ul().latd(),ul().latd()); lrx = ossim::min(rect.lr().lond(),lr().lond()); lry = ossim::max(rect.lr().latd(),lr().latd()); if( lrx < ulx || lry > uly ) { return ossimGrect(ossimGpt(0,0,0),ossimGpt(0,0,0)); } else { return ossimGrect(ossimGpt(uly, ulx, 0, rect.ul().datum()), ossimGpt(lry, lrx, 0, rect.ul().datum())); } } //******************************************************************* // Inline Method: ossimDrect::combine(const ossimDrect& rect) //******************************************************************* inline ossimGrect ossimGrect::combine(const ossimGrect& rect)const { if (isLonLatNan()) return rect; ossimGpt ulCombine; ossimGpt lrCombine; ulCombine.lon = ((ul().lon <= rect.ul().lon)?ul().lon:rect.ul().lon); ulCombine.lat = ((ul().lat >= rect.ul().lat)?ul().lat:rect.ul().lat); lrCombine.lon = ((lr().lon >= rect.lr().lon)?lr().lon:rect.lr().lon); lrCombine.lat = ((lr().lat <= rect.lr().lat)?lr().lat:rect.lr().lat); return ossimGrect(ulCombine, lrCombine); } //***************************************************************************** // INLINE METHOD: ossimGrect::pointWithin() //***************************************************************************** inline bool ossimGrect::pointWithin(const ossimGpt& gpt, bool considerHgt) const { bool within = (gpt.lat <= theUlCorner.lat) && (gpt.lat >= theLrCorner.lat) && (gpt.lon >= theUlCorner.lon) && (gpt.lon <= theLrCorner.lon); if (considerHgt) within &= (gpt.hgt <= theUlCorner.hgt) && (gpt.hgt >= theLrCorner.hgt); return within; } inline ossim_float64 ossimGrect::height() const { return (theUlCorner.latd() - theLrCorner.latd()); } inline ossim_float64 ossimGrect::width() const { return (theLrCorner.lond() - theUlCorner.lond()); } inline const ossimGpt& ossimGrect::ul() const { return theUlCorner; } inline ossimGpt ossimGrect::ur() const { ossimGpt gpt (theUlCorner.lat, theLrCorner.lon, theUlCorner.hgt, theUlCorner.datum()); return gpt; } inline ossimGpt ossimGrect::ll() const { ossimGpt gpt (theLrCorner.lat, theUlCorner.lon, theLrCorner.hgt, theLrCorner.datum()); return gpt; } inline const ossimGpt& ossimGrect::lr() const { return theLrCorner; } inline ossimGpt& ossimGrect::ul() { return theUlCorner; } inline ossimGpt& ossimGrect::lr() { return theLrCorner; } inline void ossimGrect::makeNan() { theUlCorner.makeNan(); theLrCorner.makeNan(); } inline bool ossimGrect::isLonLatNan() const { return ( ossim::isnan(theUlCorner.lat) || ossim::isnan(theUlCorner.lon) || ossim::isnan(theLrCorner.lat) || ossim::isnan(theLrCorner.lon) ); } inline bool ossimGrect::hasNans() const { return ( theUlCorner.hasNans() || theLrCorner.hasNans() ); } inline bool ossimGrect::isNan()const { return ( theUlCorner.hasNans() && theLrCorner.hasNans() ); } #endif /* End of "#ifndef ossimGrect_HEADER" */ ossim-Miami-2.9.1/include/ossim/base/ossimGzStream.h000066400000000000000000000116761352751253100223750ustar00rootroot00000000000000// ============================================================================ // gzstream, C++ iostream classes wrapping the zlib compression library. // Copyright (C) 2001 Deepak Bandyopadhyay, Lutz Kettner // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ============================================================================ // // File : gzstream.h // Revision : $Revision: 13050 $ // Revision_date : $Date: 2008-06-19 14:07:35 -0400 (Thu, 19 Jun 2008) $ // Author(s) : Deepak Bandyopadhyay, Lutz Kettner // // Standard streambuf implementation following Nicolai Josuttis, "The // Standard C++ Library". // ============================================================================ #ifndef ossimGzStream_HEADER #define ossimGzStream_HEADER // standard C++ with new header file names and std:: namespace #include #include #include #include #include #include #if OSSIM_HAS_LIBZ // ---------------------------------------------------------------------------- // Internal classes to implement gzstream. See below for user classes. // ---------------------------------------------------------------------------- class OSSIM_DLL ossimGzStreamBuf : public std::streambuf { public: ossimGzStreamBuf(); virtual ~ossimGzStreamBuf(); bool is_open()const; ossimGzStreamBuf* open( const char* name, int open_mode); ossimGzStreamBuf* close(); virtual int overflow( int c = EOF); // will not use buffer for get. virtual std::streamsize xsgetn(char_type* __s, std::streamsize n); virtual int underflow(); virtual int sync(); virtual pos_type seekoff(off_type t, std::ios_base::seekdir dir, std::ios_base::openmode omode = std::ios_base::in | std::ios_base::out); /* virtual pos_type seekpos(pos_type posType, */ /* std::ios_base::openmode __mode = std::ios_base::in | */ /* std::ios_base::out); */ private: struct PrivateData; int flush_buffer(); static const int bufferSize = 303; // 47+256 size of data buff // totals 512 bytes under g++ for igzstream at the end. PrivateData* prvtData; char buffer[bufferSize]; // data buffer bool opened; // open/close state of stream int mode; // I/O mode }; // End of class ossimGzStreamBuf /* class OSSIM_DLL ossimGzStreamBase : virtual public ossimProtocolStream */ /* { */ /* protected: */ /* ossimGzStreamBuf buf; */ /* public: */ /* ossimGzStreamBase():ossimProtocolStream(&buf) { } */ /* ossimGzStreamBase( const char* name, int open_mode); */ /* virtual ~ossimGzStreamBase(); */ /* virtual void open( const char* name, int open_mode); */ /* virtual void close(); */ /* ossimGzStreamBuf* rdbuf() { return &buf; } */ /* TYPE_DATA */ /* }; */ //class OSSIM_DLL ossimIgzStream : public ossimGzStreamBase, public std::istream class OSSIM_DLL ossimIgzStream : public ossimIFStream { public: ossimIgzStream(); ossimIgzStream( const char* name, std::ios_base::openmode mode = std::ios_base::in); virtual ~ossimIgzStream(); ossimGzStreamBuf* rdbuf(); virtual void open( const char* name, std::ios_base::openmode mode = std::ios_base::in); virtual void close(); virtual bool is_open()const; virtual bool isCompressed()const; protected: ossimGzStreamBuf buf; }; // End of class ossimIgzStream class OSSIM_DLL ossimOgzStream : public ossimOFStream { public: ossimOgzStream(); ossimOgzStream( const char* name, std::ios_base::openmode mode = std::ios_base::out|std::ios_base::trunc ); virtual ~ossimOgzStream(); ossimGzStreamBuf* rdbuf(); void open( const char* name, std::ios_base::openmode mode = std::ios_base::out|std::ios_base::trunc ); virtual void close(); virtual bool is_open()const; virtual bool isCompressed()const; protected: ossimGzStreamBuf buf; }; // End of class ossimOgzStream #endif /* #if OSSIM_HAS_LIBZ */ #endif /* #define ossimGzStream_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimHexString.h000066400000000000000000000076071352751253100225530ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************** // $Id: ossimHexString.h 23584 2015-10-18 13:03:33Z dburken $ #ifndef ossimHexString_H #define ossimHexString_H 1 #include #include #include class OSSIMDLLEXPORT ossimHexString : public ossimString { public: ossimHexString():ossimString() {} template ossimHexString(Iter start, Iter end):ossimString(start, end){} ossimHexString(const std::string& aString):ossimString(aString) {} ossimHexString(const char *aString):ossimString(aString?aString:"") {} ossimHexString(const ossimString& aString):ossimString(aString.c_str()) {} ossimHexString(char value):ossimString() { assign(value); } ossimHexString(ossim_int16 value):ossimString() { assign(value); } ossimHexString(ossim_int32 value):ossimString() { assign(value); } ossimHexString(ossim_uint8 value):ossimString() { assign(value); } ossimHexString(ossim_uint16 value):ossimString() { assign(value); } ossimHexString(ossim_uint32 value):ossimString() { assign(value); } bool operator==(const ossimHexString& s) const {return (std::strcmp(this->c_str(),s.c_str())==0);} bool operator==(const char* s) const {return (std::strcmp(this->c_str(),s)==0);} bool operator!=(const ossimHexString& s) const {return (std::strcmp(this->c_str(),s.c_str())!=0);} bool operator!=(const char* s) const {return (std::strcmp(this->c_str(),s)!=0);} operator const char*()const{return c_str();} const char* chars()const{return c_str();} char& operator[](int i) { return *( const_cast(c_str())+i); } const char& operator[](int i)const { return *(c_str()+i); } const ossimHexString& operator =(ossim_int16 value) { assign(value); return *this; } const ossimHexString& operator =(ossim_int32 value) { assign(value); return *this; } const ossimHexString& operator =(ossim_uint16 value) { assign(value); return *this; } const ossimHexString& operator =(ossim_uint32 value) { assign(value); return *this; } const ossimHexString& operator =(ossim_int8 value) { assign(value); return *this; } const ossimHexString& operator =(ossim_uint8 value) { assign(value); return *this; } const ossimHexString& operator =(const ossim_int8* value) { ossimString::operator=(value); return *this; } const ossimHexString& operator =(const ossimString& value) { ossimString::operator=(value); return *this; } const ossimHexString& operator =(const ossimHexString& value) { ossimString::operator=(value); return *this; } const ossimHexString& operator =(const std::string& value) { ossimString::operator=(value); return *this; } ossim_int32 toInt32()const; ossim_int16 toInt16()const; ossim_int8 toChar()const; ossim_uint8 toUchar()const; ossim_uint32 toUint32()const; ossim_uint16 toUint16()const; void assign(ossim_int16 value) { assign((ossim_uint16)value); } void assign(ossim_int32 value) { assign((ossim_uint32)value); } void assign(ossim_int8 value) { assign((ossim_uint8)value); } void assign(ossim_uint16 value); void assign(ossim_uint32 value); void assign(ossim_uint8 value); }; #endif /* #ifndef ossimHexString_H */ ossim-Miami-2.9.1/include/ossim/base/ossimHistogram.h000066400000000000000000000176651352751253100226020ustar00rootroot00000000000000//--- // // License: MIT // // See top level LICENSE.txt file for more. // // Author: Ken Melero // Orginally developed by: // Copyright (c) 1997 TargetJr Consortium // GE Corporate Research and Development (GE CRD) // 1 Research Circle // Niskayuna, NY 12309 // Adapted from: IUE v4.1.2 // Description: // A Histogram contains an array of "buckets", which represent finite // segments of some value axis, along with a corresponding array of // frequency m_counts for each of these buckets. // //--- // $Id$ // #ifndef ossimHistogram_HEADER #define ossimHistogram_HEADER 1 #include #include #include #include #include #include class OSSIMDLLEXPORT ossimHistogram : public ossimObject { private: mutable int m_statsConsistent; // A 2 bit state flag Mean =1 | StandDev = 2 protected: /** * @brief Updates m_vmin and m_vmax. This will be the value for the first * and last bin with a count in it. */ void updateMinMax(); virtual void deleteAll(); double * m_vals; // histogram x array // (value = midpoint of each bucket) ossim_int64* m_counts; // histogram y array ie. count[i] is // the number of pixels with value within range // of bucket i int m_num; // number of indices double m_delta; // "Width" of each bucket on value axis double m_vmin, m_vmax; // Maximum and minimum values on plot mutable double m_mean; // Mean value of the distribution mutable double m_standardDev; // //--- // For counting nulls only. // Nulls counted separately, i.e. not stored in a m_counts bin, as they are // not used in any computations. //--- double m_nullValue; ossim_uint64 m_nullCount; //--- // This was added to determine if pixel values are integers. // If so save the state in this form for each bin: "(pixelValue,count)" // else: "(binIndex,count)" //--- ossimScalarType m_scalarType; class ossimProprietaryHeaderInformation { public: ossimProprietaryHeaderInformation(){clear();} bool parseStream(std::istream& in); long getNumberOfBins() { return m_numberOfBins.toLong(); } void clear() { m_fileType = ""; m_version = ""; m_mapperType = ""; m_numberOfBins = ""; } ossimString m_fileType; ossimString m_version; ossimString m_mapperType; ossimString m_numberOfBins; }; public: enum FillAlgorithmType { HISTOGRAM_FILL_DEFAULT = 0, HISTOGRAM_FILL_THIN_PLATE = 1 }; // Constructors ossimHistogram(); ossimHistogram(int xres, double min, double max, double nullValue, ossimScalarType scalar); // ossimHistogram(double*, double*, int); ossimHistogram(const ossimHistogram& his); // Copy constructor ossimHistogram(const ossimHistogram*, double width); // Resampling constructor /** * Uses samples array to establish a histogram with numBins: */ ossimHistogram(const double* samples, ossim_uint32 size, ossim_uint32 numBins); virtual int GetIndex(double)const; // Other histogram formation operations /** * @brief Fill empty bins. * * This is used for code that does not like holes. The ossim-gui * HistogramWidget being one of them. * * @param interiorOnly If true only bins between first bin with a * count, and last bin with a count will be filled. If false, any * bins with a zero count will be set to a count of one. * * @param type Fill type. Currently thin plate spline is the only * type used regardless of setting. * * @return A new histogram from the this. */ ossimRefPtr fillEmptyBins(bool interiorOnly, int type=HISTOGRAM_FILL_THIN_PLATE)const; ossimRefPtr Scale(double scale_factor); // Scale Transformation // From density to cumulative ossimRefPtr CumulativeGreaterThanEqual()const; ossimRefPtr CumulativeLessThanEqual()const; //Suppress non-peak values. ossimRefPtr NonMaximumSupress(int radius = 1, bool cyclic = false); // void create(int xres, float val1, float val2); void create(int bins, double minValue, double maxValue, double nullValue, ossimScalarType scalar); // Attribute accessors void UpCount(double newval, double occurences=1); double GetCount(double uval)const; double SetCount(double pixelval, double count); double GetMinVal()const; double GetMaxVal()const; double GetMaxCount()const; double GetRangeMin()const { return m_vmin; } double GetRangeMax()const { return m_vmax; } double * GetVals() { m_statsConsistent = 0; // Values might change. return m_vals; } const double * GetVals()const { m_statsConsistent = 0; // Values might change. return m_vals; } ossim_int64 * GetCounts() { m_statsConsistent = 0; // m_counts might change. return m_counts; } const ossim_int64 * GetCounts()const { //m_statsConsistent = 0; // m_counts might change. return m_counts; } int GetRes()const { return m_num; } double GetBucketSize()const { return m_delta; } double * GetMinValAddr() { return m_vals+GetIndex(GetMinVal()); } ossim_int64 * GetMinCountAddr() { return m_counts+GetIndex(GetMinVal()); } const double * GetMinValAddr()const { return m_vals+GetIndex(GetMinVal()); } const ossim_int64 * GetMinCountAddr()const { return m_counts+GetIndex(GetMinVal()); } double ComputeArea(double low, double high)const;// bounded area double ComputeArea()const;//total area /*! * Returns the fraction of accumulation up to and including "val" bucket * from min divided by the total accumulation. * returns OSSIM_FLT_NAN if "val" is not between GetMinVal and GetMaxVal. */ double getLowFractionFromValue(double val) const; /*! * Returns the fraction of accumulation down to and including "val" bucket * from max divided by the total accumulation. * returns OSSIM_FLT_NAN if "val" is not between GetMin() and GetMax(). */ double getHighFractionFromValue(double val) const; //Find bounds that clip off a given percent of the area double LowClipVal(double clip_fraction)const; double HighClipVal(double clip_fraction)const; double GetValFromIndex(ossim_uint32 idx)const; double GetMinValFromIndex(ossim_uint32 idx)const; double GetMaxValFromIndex(ossim_uint32 idx)const; int GetValIndex(double val)const; double GetMean()const; double GetStandardDev()const; void Print()const; void Dump(char *)const; int WritePlot(const char* fname)const; virtual ~ossimHistogram(); virtual bool importHistogram(const ossimFilename& inputFile); virtual bool importHistogram(std::istream& in); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimRefPtr xmlNode)const; virtual bool loadState(const ossimRefPtr xmlNode); ossimScalarType getScalarType() const; void setScalarType( ossimScalarType scalar ); const double& getNullValue() const; void setNullValue(const double& nullValue); const ossim_uint64& getNullCount() const; void upNullCount( const ossim_uint64& count ); // Inlined for pixel loops. void upNullCount() { ++m_nullCount; } TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimHistogramSource.h000066400000000000000000000034451352751253100237520ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHistogramSource.h 11721 2007-09-13 13:19:34Z gpotts $ #ifndef ossimHistogramSource_HEADER #define ossimHistogramSource_HEADER #include #include #include class OSSIM_DLL ossimHistogramSource : public ossimSource { public: virtual ~ossimHistogramSource(); virtual ossimRefPtr getHistogram(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: ossimHistogramSource(ossimObject* owner=NULL, ossim_uint32 numberOfInputs=0, ossim_uint32 numberOfOutputs=0, bool inputListFixedFlag=true, bool outputListFixedFlag=true); ossimRefPtr theHistogram; /*! * if the filename is not "" then it will use * this to store the histogram outside the keywordlist. * * it will set the filename keyword to the filename and * during a save state will save it out to the file * instead of inline to the keyword list. */ ossimFilename theFilename; private: /** Hidden from use copy constructor. */ ossimHistogramSource(const ossimHistogramSource&); TYPE_DATA }; #endif /* End of "#ifndef ossimHistogramSource_HEADER" */ ossim-Miami-2.9.1/include/ossim/base/ossimHsiVector.h000066400000000000000000000036311352751253100225370ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimHsiVector.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimHsiVector_HEADER #define ossimHsiVector_HEADER #include #include class ossimRgbVector; class ossimNormRgbVector; class OSSIMDLLEXPORT ossimHsiVector { public: friend std::ostream& operator << (std::ostream& out, const ossimHsiVector & data) { out << "<" << data.theBuf[0] << ", " << data.theBuf[1] << ", " << data.theBuf[2] << ">"; return out; } // assumed normalized ossim_float64s // // ossimHsiVector(ossim_float64 h=0, ossim_float64 s=0, ossim_float64 i=0) { theBuf[0] = h; theBuf[1] = s; theBuf[2] = i; } ossimHsiVector(const ossimRgbVector& rgb); ossimHsiVector(const ossimNormRgbVector& rgb); ossimHsiVector& operator =(const ossimRgbVector& rgb); ossimHsiVector& operator =(const ossimNormRgbVector& rgb); void setFromRgb(ossim_float64 r, ossim_float64 g, ossim_float64 b); ossim_float64 getH()const { return theBuf[0]; } ossim_float64 getS()const { return theBuf[1]; } ossim_float64 getI()const { return theBuf[2]; } void setH(ossim_float64 H) { theBuf[0] = H; } void setS(ossim_float64 S) { theBuf[1] = S; } void setI(ossim_float64 I) { theBuf[2] = I; } ossim_float64 clamp(ossim_float64 colorValue, ossim_float64 min=0, ossim_float64 max=1)const { colorValue = colorValue > max? max:colorValue; colorValue = colorValue < min? min:colorValue; return colorValue; } protected: /*! * buf[0] = hue * buf[1] = saturation * buf[2] = intensity */ ossim_float64 theBuf[3]; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimHsvVector.h000066400000000000000000000034551352751253100225600ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimHsvVector.h 14789 2009-06-29 16:48:14Z dburken $ #ifndef ossimHsvVector_HEADER #define ossimHsvVector_HEADER #include #include class ossimRgbVector; class OSSIMDLLEXPORT ossimHsvVector { public: friend std::ostream& operator << (std::ostream& out, const ossimHsvVector & data) { out << "<" << data.theBuf[0] << ", " << data.theBuf[1] << ", " << data.theBuf[2] << ">"; return out; } // assumed normalized floats // // ossimHsvVector(float h=0, float s=0, float i=0) { theBuf[0] = h; theBuf[1] = s; theBuf[2] = i; } ossimHsvVector(const ossimRgbVector& rgb); const ossimHsvVector& operator =(const ossimRgbVector& rgb); float getH()const { return theBuf[0]; } float getS()const { return theBuf[1]; } float getV()const { return theBuf[2]; } unsigned char getVUnNormalized()const { return static_cast(theBuf[2]*255); } void setH(float H) { theBuf[0] = H; } void setS(float S) { theBuf[1] = S; } void setV(float V) { theBuf[2] = V; } float clamp(float colorValue, float min=0, float max=255)const { colorValue = colorValue > max? max:colorValue; colorValue = colorValue < min? min:colorValue; return colorValue; } static const float OSSIM_HSV_UNDEFINED; protected: /*! * buf[0] = hue [0..1] * buf[1] = saturation [0..1] * buf[2] = value [0..1] */ float theBuf[3]; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimHttpRequest.h000066400000000000000000000031071352751253100231170ustar00rootroot00000000000000#ifndef ossimHttpRequest_HEADER #define ossimHttpRequest_HEADER #include #include #include #include #include class OSSIM_DLL ossimHttpRequest :public ossimWebRequest { public: enum HttpMethodType { HTTP_METHOD_UNKNOWN = 0, HTTP_METHOD_GET = 1, HTTP_METHOD_POST = 2 // later we will add support for post }; ossimHttpRequest() :m_methodType(HTTP_METHOD_UNKNOWN) { } bool set(const ossimUrl& url, const ossimKeywordlist& headerOptions, HttpMethodType methodType=HTTP_METHOD_GET) { bool result = setUrl(url); m_headerOptions = headerOptions; m_methodType = methodType; return result; } virtual ~ossimHttpRequest() { } void setHeaderOptions(const ossimKeywordlist& options) { m_headerOptions = options; } void addHeaderOption(const ossimString& name, const ossimString& value) { m_headerOptions.add(name, value); } void clearHeaderOptions(){m_headerOptions.clear();} ossimKeywordlist& getHeaderOptions(){return m_headerOptions;} const ossimKeywordlist& getHeaderOptions()const{return m_headerOptions;} virtual ossimString getLastError()const{return m_lastError;} virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: ossimKeywordlist m_headerOptions; HttpMethodType m_methodType; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimHttpResponse.h000066400000000000000000000051371352751253100232720ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file // // Author: Garrett Potts // // Description: This is an initial cut at an http response object. The HttpResponse is // returned from the HttpRequest base object. //---------------------------------------------------------------------------- // $Id$ #ifndef ossimHttpResponse_HEADER #define ossimHttpResponse_HEADER #include #include #include #include #include #include class OSSIM_DLL ossimHttpResponse : public ossimWebResponse { public: ossimHttpResponse() :m_headerStream(&m_headerBuffer), m_bodyStream(&m_bodyBuffer) { clear(); } ossimByteStreamBuffer& headerBuffer(){return m_headerBuffer;} const ossimByteStreamBuffer& headerBuffer()const{return m_headerBuffer;} ossimByteStreamBuffer& bodyBuffer(){return m_bodyBuffer;} const ossimByteStreamBuffer& bodyBuffer()const{return m_bodyBuffer;} std::iostream& headerStream(){return m_headerStream;} std::iostream& bodyStream(){return m_bodyStream;} virtual std::istream* getInputStream() {return static_cast(&m_bodyStream);} /** * Clears out the Response and prepares for a new response. */ virtual void clear() { m_headerBuffer.clear(); m_bodyBuffer.clear(); m_headerKwl.clear(); m_statusLine = ""; m_statusCode = 200; } /** * This will parse out the response code from the status line and initialize * the header variables into a keywordlist. */ void convertHeaderStreamToKeywordlist(); virtual void clearLastError(){m_statusCode = 200;m_statusLine="";} virtual ossimString getLastError()const{return ((m_statusCode == 200)?ossimString(""):m_statusLine);} ossimKeywordlist& headerKwl(){return m_headerKwl;} const ossimKeywordlist& headerKwl()const{return m_headerKwl;} ossim_int64 getContentLength()const; ossimString getHeaderValue(const ossimString& headerName)const; const ossimString& statusLine()const{return m_statusLine;} ossim_uint32 getStatusCode()const{return m_statusCode;} protected: ossimKeywordlist m_headerKwl; ossimByteStreamBuffer m_headerBuffer; ossimByteStreamBuffer m_bodyBuffer; std::iostream m_headerStream; std::iostream m_bodyStream; ossimString m_statusLine; ossim_uint32 m_statusCode; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimId.h000066400000000000000000000035411352751253100211650ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimId.h 20314 2011-12-01 21:46:37Z oscarkramer $ #ifndef ossimId_HEADER #define ossimId_HEADER #include #include class OSSIM_DLL ossimId { public: friend OSSIM_DLL std::ostream& operator <<(std::ostream &out, const ossimId& data); explicit ossimId(ossim_int64 id = 0) :theId(id) {} virtual ~ossimId(){} virtual void print(std::ostream& out)const; void setId(ossim_int64 id){theId = id;} ossim_int64 getId()const{return theId;} bool operator ==(const ossimId& rhs)const { return (theId == rhs.theId); } bool operator !=(const ossimId& rhs)const { return (theId != rhs.theId); } bool operator == (ossim_int64 rhs) const { return (theId == rhs); } bool operator != (ossim_int64 rhs) const { return (theId != rhs); } bool operator <(const ossimId& rhs)const { return (theId < rhs.theId); } bool operator <=(const ossimId& rhs)const { return (theId <= rhs.theId); } bool operator >(const ossimId& rhs)const { return (theId > rhs.theId); } bool operator >=(const ossimId& rhs)const { return (theId >= rhs.theId); } bool operator <(ossim_int64 rhs)const { return (theId < rhs); } bool operator >(ossim_int64 rhs)const { return (theId > rhs); } bool operator <=(ossim_int64 rhs)const { return (theId <= rhs); } bool operator >=(ossim_int64 rhs)const { return (theId >= rhs); } static const ossim_int64 INVALID_ID; protected: ossim_int64 theId; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimIdManager.h000066400000000000000000000011141352751253100224520ustar00rootroot00000000000000#ifndef ossimIdManager_HEADER #define ossimIdManager_HEADER #include class OSSIMDLLEXPORT ossimIdManager { public: static ossimIdManager* instance(); ossimId generateId(); ossimId generateId(ossim_int64 customId); void setCurrentId(ossim_int64 customId); protected: ossimIdManager(); // make sure this can't be constructed outside ossimIdManager(const ossimIdManager& rhs); ~ossimIdManager(); void operator =(const ossimIdManager& rhs); static ossimIdManager* theInstance; static ossim_int64 theCurrentId; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimImageAoiListener.h000066400000000000000000000015311352751253100240070ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageAoiListener.h 17195 2010-04-23 17:32:18Z dburken $ #ifndef ossimImageAoiListener_HEADER #define ossimImageAoiListener_HEADER #include class ossimImageRectangleEvent; class ossimImagePolygonEvent; class OSSIMDLLEXPORT ossimImageAoiListener : public ossimListener { public: ossimImageAoiListener():ossimListener(){} virtual ~ossimImageAoiListener(){} virtual void processEvent(ossimEvent& event); virtual void imageRectangleEvent(ossimImageRectangleEvent& /* event */) {} virtual void imagePolygonEvent(ossimImagePolygonEvent& /* event */) {} }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimImageGeometryEvent.h000066400000000000000000000034051352751253100243700ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageGeometryEvent.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimImageGeometryEvent_HEADER #define ossimImageGeometryEvent_HEADER #include #include #include class ossimImageGeometryEvent : public ossimEvent { public: ossimImageGeometryEvent(ossimObject* object=0, long id=OSSIM_EVENT_IMAGE_GEOMETRY_ID) :ossimEvent(object, id) { } ossimImageGeometryEvent(const ossimKeywordlist& geomKwl, ossimObject* object=NULL, long id=OSSIM_EVENT_IMAGE_GEOMETRY_ID) :ossimEvent(object, id), theGeomKwl(geomKwl) { } ossimImageGeometryEvent(const ossimImageGeometryEvent& rhs) :ossimEvent(rhs), theGeomKwl(rhs.theGeomKwl) { } virtual ~ossimImageGeometryEvent(){} virtual ossimObject* dup()const { return new ossimImageGeometryEvent(*this); } void setGeometry(const ossimKeywordlist& geomKwl) { theGeomKwl = geomKwl; } void getGeometry(ossimKeywordlist& geomKwl)const { geomKwl = theGeomKwl; } const ossimKeywordlist& getGeometry()const { return theGeomKwl; } bool isGeometrySet()const { return (theGeomKwl.getSize() != 0); } void clearGeometry() { theGeomKwl.clear(); } protected: ossimKeywordlist theGeomKwl; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimImageGeometryEventListener.h000066400000000000000000000015621352751253100261000ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: A brief description of the contents of the file. // // //************************************************************************* // $Id: ossimImageGeometryEventListener.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimImageGeometryEventListener_HEADER #define ossimImageGeometryEventListener_HEADER #include #include class ossimImageGeometryEventListener : public ossimListener { public: ossimImageGeometryEventListener():ossimListener(){} virtual ~ossimImageGeometryEventListener(){} virtual void processEvent(ossimEvent& event); virtual void imageGeometryEvent(ossimImageGeometryEvent& /* event */) {} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimImagePolygonEvent.h000066400000000000000000000036351352751253100242310ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimImagePolygonEvent.h 13016 2008-06-10 16:06:58Z dburken $ #ifndef ossimImagePolygonEvent_HEADER #define ossimImagePolygonEvent_HEADER #include #include #include #include #include class OSSIMDLLEXPORT ossimImagePolygonEvent : public ossimEvent { public: ossimImagePolygonEvent(const std::vector& polygon, ossimObject* obj=0) : ossimEvent(obj,OSSIM_EVENT_AOI_POLYGON_ID) , thePolygon(polygon) { } ossimImagePolygonEvent(const std::vector& polygon, ossimObject* obj=0) : ossimEvent(obj,OSSIM_EVENT_AOI_POLYGON_ID), thePolygon(polygon.size()) { for (std::vector::size_type i = 0; i < polygon.size(); ++i) { thePolygon[i] = polygon[i]; } } virtual ossimObject* dup()const { return new ossimImagePolygonEvent(*this); } const std::vector& getpolygon()const { return thePolygon; } const std::vector& getPolygon()const { return thePolygon; } void setPolygon(const std::vector& polygon) { thePolygon = polygon; } void setPolygon(const std::vector& polygon) { thePolygon.resize(polygon.size()); for (std::vector::size_type i = 0; i < polygon.size(); ++i) { thePolygon[i] = polygon[i]; } } protected: std::vector thePolygon; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimImageRectangleEvent.h000066400000000000000000000021211352751253100244730ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageRectangleEvent.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimImageRectangleEvent_HEADER #define ossimImageRectangleEvent_HEADER #include #include #include class OSSIMDLLEXPORT ossimImageRectangleEvent : public ossimEvent { public: ossimImageRectangleEvent(const ossimIrect& rect, ossimObject* obj=NULL) : ossimEvent(obj,OSSIM_EVENT_AOI_RECTANGLE_ID) , theRectangle(rect) { } virtual ossimObject* dup()const { return new ossimImageRectangleEvent(*this); } const ossimIrect& getRectangle()const { return theRectangle; } void setRectangle(const ossimIrect& rect) { theRectangle = rect; } protected: ossimIrect theRectangle; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimImageTypeLut.h000066400000000000000000000015141352751253100232000ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken (dburken@imagelinks.com) // // Description: // // Contains class declaration for ImageTypeLut. Currently has mapping of // output image writes from enumeration to string and string to // enumeration. // //******************************************************************* // $Id: ossimImageTypeLut.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ImageTypeLUT_HEADER #define ImageTypeLUT_HEADER #include class OSSIMDLLEXPORT ossimImageTypeLut : public ossimLookUpTable { public: ossimImageTypeLut(); virtual ~ossimImageTypeLut(){} virtual ossimKeyword getKeyword() const { return IMAGE_TYPE_KW; } static const ossimKeyword IMAGE_TYPE_KW; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimInterleaveTypeLut.h000066400000000000000000000014721352751253100242570ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken (dburken@imagelinks.com) // // Description: // // Contains class declaration for InterleaveTypeLUT. //******************************************************************* // $Id: ossimInterleaveTypeLut.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimInterleaveTypeLUT_HEADER #define ossimInterleaveTypeLUT_HEADER #include #include class OSSIMDLLEXPORT ossimInterleaveTypeLut : public ossimLookUpTable { public: ossimInterleaveTypeLut(); virtual ~ossimInterleaveTypeLut(){} virtual ossimKeyword getKeyword() const { return ossimKeyword(ossimKeywordNames::INTERLEAVE_TYPE_KW, ""); } }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimIoStream.h000066400000000000000000000144351352751253100223600ustar00rootroot00000000000000//--- // // License: MIT // // Author: Garrett Potts // // Description: // // Class declarations for: // // ossimIStream // ossimOStream // ossimIOStream // ossimIOMemoryStream // ossimIMemoryStream // ossimOMemoryStream // ossimIOFStream // ossimIFStream // ossimOFStream // //--- // $Id$ #ifndef ossimIoStream_HEADER #define ossimIoStream_HEADER 1 #include // NOTE: All below includes will go away once deprecated code is replaced. // drb 04 Nov. 2016 #include #include #include #include #include #include #include #include // needed by std::shared_ptr #include //--- // Depreciated: //--- class OSSIM_DLL ossimIStream : public ossimStreamBase, public std::basic_istream { public: //ossimIStream(); ossimIStream(std::streambuf* sb); virtual ~ossimIStream(); }; class OSSIM_DLL ossimOStream : public ossimStreamBase, public std::basic_ostream { public: //ossimOStream(); ossimOStream(std::streambuf* sb); virtual ~ossimOStream(); }; class OSSIM_DLL ossimIOStream : public ossimStreamBase, public std::basic_iostream { public: //ossimIOStream(); ossimIOStream(std::streambuf* sb); virtual ~ossimIOStream(); }; class OSSIM_DLL ossimIOMemoryStream : public ossimIOStream { public: ossimIOMemoryStream(); virtual ~ossimIOMemoryStream(); // ??? (drb) bool is_open()const; // ??? (drb) virtual void open(const char* /* protocolString */, int /* openMode */); ossimString str(); // ??? (drb) virtual void close(); // ??? (drb) std::streamsize ossim_uint64 size()const; protected: std::stringbuf theBuf; }; class OSSIM_DLL ossimIMemoryStream : public ossimIStream { public: ossimIMemoryStream(const ossimString& inputBuf); virtual ~ossimIMemoryStream(); bool is_open()const; ossim_uint64 size()const; virtual void open(const char* /* protocolString */, int /* openMode */ ); virtual void close(); ossimString str(); protected: std::stringbuf theBuf; }; class OSSIM_DLL ossimOMemoryStream : public ossimOStream { public: ossimOMemoryStream(); virtual ~ossimOMemoryStream(); bool is_open()const; ossim_uint64 size()const; virtual void open(const char* /* protocolString */, int /* openMode */ ); virtual void close(); ossimString str(); protected: std::stringbuf theBuf; }; class OSSIM_DLL ossimIOFStream : public ossimStreamBase, public std::basic_fstream { public: ossimIOFStream(); ossimIOFStream(const char* name, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out); virtual ~ossimIOFStream(); }; class OSSIM_DLL ossimIFStream : public ossimStreamBase, public std::basic_ifstream { public: ossimIFStream(); ossimIFStream(const char* file, std::ios_base::openmode mode = std::ios_base::in); virtual ~ossimIFStream(); }; class OSSIM_DLL ossimOFStream : public ossimStreamBase, public std::basic_ofstream { public: ossimOFStream(); ossimOFStream(const char* name, std::ios_base::openmode mode = std::ios_base::out|std::ios_base::trunc); virtual ~ossimOFStream(); }; /** * Alows one to create a buffered input stream */ class OSSIM_DLL ossimBufferedInputStream : public ossim::istream { public: /** * will use the read buffer of the passed in input stream and * will set the buffer based on the buffer size passed in */ ossimBufferedInputStream(std::shared_ptr in, ossim_uint32 bufferSize=1024 ) :ossim::istream(in->rdbuf()), m_inputStream(in) { if(bufferSize > 0) { m_buffer.resize(bufferSize); rdbuf()->pubsetbuf(&m_buffer.front(), m_buffer.size()); } } virtual ~ossimBufferedInputStream() { m_inputStream = 0; } protected: /** * We have a buffer that we allocate so it does not * loose scope through the life of this stream */ std::vector m_buffer; /** * We will save the input stream we set the buffer to. */ std::shared_ptr m_inputStream; }; #ifdef _MSC_VER class ossimIFStream64 : public std::basic_ifstream { public: ossimIFStream64(const char* pFilename, std::ios_base::openmode mode = ios_base::in, int prot = ios_base::_Openprot); virtual ~ossimIFStream64(); void seekg64(off_type off, ios_base::seekdir way); void seekg64(streampos pos, ios_base::seekdir way); static void seekg64(std::istream& str, off_type off, ios_base::seekdir way); static void seekg64(std::istream& str, std::streampos pos, ios_base::seekdir way); private: FILE* theFile; }; class ossimOFStream64 : public std::basic_ofstream { public: ossimOFStream64(const char* pFilename, std::ios_base::openmode mode = ios_base::out, int prot = ios_base::_Openprot); virtual ~ossimOFStream64(); ossim_uint64 tellp64(); }; #else class ossimIFStream64 : public std::basic_ifstream { public: ossimIFStream64(const char* pFilename, std::ios_base::openmode mode = ios_base::in, long prot = 0666); virtual ~ossimIFStream64(); void seekg64(off_type off, ios_base::seekdir way); static void seekg64(std::istream& str, off_type off, ios_base::seekdir way); }; class ossimOFStream64 : public std::basic_ofstream { public: ossimOFStream64(const char* pFilename, std::ios_base::openmode mode = ios_base::out, long prot = 0666); virtual ~ossimOFStream64(); ossim_uint64 tellp64(); }; #endif // _MSC_VER OSSIM_DLL void operator >> (ossimIStream& in,ossimOStream& out); OSSIM_DLL ossimIOStream& operator >> (ossimIStream& in,ossimIOStream& out); OSSIM_DLL void operator >> (ossimIOStream& in,ossimOStream& out); OSSIM_DLL ossimIOStream& operator >> (ossimIOStream& in,ossimIOStream& out); OSSIM_DLL void operator << (ossimOStream& out, ossimIStream& in); OSSIM_DLL void operator << (ossimOStream& out, ossimIOStream& in); OSSIM_DLL ossimIOStream& operator << (ossimIOStream& out, ossimIStream& in); OSSIM_DLL ossimIOStream& operator << (ossimIOStream& out, ossimIOStream& in); #endif ossim-Miami-2.9.1/include/ossim/base/ossimIosFwd.h000066400000000000000000000030551352751253100220240ustar00rootroot00000000000000//--- // License: MIT // Description: Forward ossim stream declarations. // $Id$ //--- #ifndef ossimIosFwd_H #define ossimIosFwd_H 1 #include namespace ossim { //--- // Straight from include. ossim namespace so we have a common // factory stream return that can be derived from. //--- /// Base class for @c char input streams. typedef std::basic_istream istream; /// Base class for @c char output streams. typedef std::basic_ostream ostream; /// Base class for @c char mixed input and output streams. typedef std::basic_iostream iostream; /// Class for @c char memory buffers. typedef std::basic_stringbuf stringbuf; /// Class for @c char input memory streams. typedef std::basic_istringstream istringstream; /// Class for @c char output memory streams. typedef std::basic_ostringstream ostringstream; /// Class for @c char mixed input and output memory streams. typedef std::basic_stringstream stringstream; /// Class for @c char file buffers. typedef std::basic_filebuf filebuf; /// Class for @c char input file streams. typedef std::basic_ifstream ifstream; /// Class for @c char output file streams. typedef std::basic_ofstream ofstream; /// Class for @c char mixed input and output file streams. typedef std::basic_fstream fstream; } // End: namespace ossim #endif /* #ifndef ossimIosFwd_H */ ossim-Miami-2.9.1/include/ossim/base/ossimIpt.h000066400000000000000000000100171352751253100213610ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration for ipt. // Used to represent an interger point containing an x and y data member. // //******************************************************************* // $Id: ossimIpt.h 19793 2011-06-30 13:26:56Z gpotts $ #ifndef ossimIpt_HEADER #define ossimIpt_HEADER #include #include #include #include // Forward class declarations. class ossimFpt; class ossimDpt3d; class ossimString; class OSSIMDLLEXPORT ossimIpt { public: ossimIpt() : x(0), y(0) {} ossimIpt(ossim_int32 anX, ossim_int32 aY) : x(anX), y(aY) {} ossimIpt(const ossimIpt& pt) : x(pt.x), y(pt.y) {} ossimIpt(const ossimDpt& pt); ossimIpt(const ossimFpt& pt); ossimIpt(const ossimDpt3d &pt); const ossimIpt& operator=(const ossimIpt& pt); const ossimIpt& operator=(const ossimDpt& pt); const ossimIpt& operator=(const ossimFpt& pt); bool operator==(const ossimIpt& pt) const { return ( (x == pt.x) && (y == pt.y) ); } bool operator!=(const ossimIpt& pt) const { return ( (x != pt.x) || (y != pt.y) ); } void makeNan(){x = OSSIM_INT_NAN; y=OSSIM_INT_NAN;} bool hasNans()const { return ( (x==OSSIM_INT_NAN) || (y==OSSIM_INT_NAN) ); } bool isNan()const { return ( (x==OSSIM_INT_NAN) && (y==OSSIM_INT_NAN) ); } std::ostream& print(std::ostream& os) const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& os, const ossimIpt& pt); /** * @return ossimString representing point. * * Format: ( 30, -90 ) * -x- -y- */ ossimString toString() const; /** * Initializes this point from string. This method opens an std::istream to * s and then calls operator>>. * * Expected format: ( 30, -90 ) * -x- -y- * * @param s String to initialize from. * * @see operator>> */ void toPoint(const std::string& s); /** * Method to input the formatted string of the "operator<<". * * Expected format: ( 30, -90 ) * -x- -y- * * This method starts by doing a "makeNan" on pt. So if anything goes * wrong with the stream or parsing pt could be all or partially nan. * * @param is Input stream std::istream to formatted text. * @param pt osimIpt to be initialized from stream. * @return std::istream pass in. */ friend OSSIMDLLEXPORT std::istream& operator>>(std::istream& is, ossimIpt& pt); bool isEqualTo(const ossimIpt& rhs, ossimCompareType compareType=OSSIM_COMPARE_FULL)const; /*! * METHOD: length() * Returns the RSS of the components. */ double length() const { return sqrt((double)x*x + (double)y*y); } //*** // OPERATORS: +, -, +=, -= // Point add/subtract with other point: //*** ossimIpt operator+(const ossimIpt& p) const { return ossimIpt(x+p.x, y+p.y); } ossimIpt operator-(const ossimIpt& p) const { return ossimIpt(x-p.x, y-p.y); } const ossimIpt& operator+=(const ossimIpt& p) { x += p.x; y += p.y; return *this; } const ossimIpt& operator-=(const ossimIpt& p) { x -= p.x; y -= p.y; return *this; } //*** // OPERATORS: *, / // Scale point components by scalar: //*** ossimDpt operator*(const double& d) const { return ossimDpt(d*x, d*y); } ossimDpt operator/(const double& d) const { return ossimDpt(x/d, y/d); } //*** // Public data members: //*** union {ossim_int32 x; ossim_int32 u; ossim_int32 samp;}; union {ossim_int32 y; ossim_int32 v; ossim_int32 line;}; }; inline const ossimIpt& ossimIpt::operator=(const ossimIpt& pt) { if (this != &pt) { x = pt.x; y = pt.y; } return *this; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimIpt64.h000066400000000000000000000076261352751253100215470ustar00rootroot00000000000000//--- // License: MIT // // Description: Contains class definition for 64 bit integer point. //--- // $Id$ #ifndef ossimIpt64_H #define ossimIpt64_H 1 #include #include #include // Forward class declarations. class ossimFpt; class ossimDpt3d; class ossimIpt; class ossimString; class OSSIMDLLEXPORT ossimIpt64 { public: ossimIpt64() : x(0), y(0) {} ossimIpt64(ossim_int64 anX, ossim_int64 aY) : x(anX), y(aY) {} ossimIpt64(ossim_int32 anX, ossim_int32 aY) : x(anX), y(aY) {} ossimIpt64(const ossimIpt64& pt) : x(pt.x), y(pt.y) {} ossimIpt64(const ossimIpt& pt); ossimIpt64(const ossimDpt& pt); ossimIpt64(const ossimFpt& pt); ossimIpt64(const ossimDpt3d &pt); const ossimIpt64& operator=(const ossimIpt64& pt) { if (this != &pt) { x = pt.x; y = pt.y; } return *this; } const ossimIpt64& operator=(const ossimIpt& pt); const ossimIpt64& operator=(const ossimDpt& pt); const ossimIpt64& operator=(const ossimFpt& pt); bool operator==(const ossimIpt64& pt) const { return ( (x == pt.x) && (y == pt.y) ); } bool operator!=(const ossimIpt64& pt) const { return ( (x != pt.x) || (y != pt.y) ); } void makeNan(){x = OSSIM_INT64_NAN; y=OSSIM_INT64_NAN;} bool hasNans()const { return ( (x==OSSIM_INT64_NAN) || (y==OSSIM_INT64_NAN) ); } bool isNan()const { return ( (x==OSSIM_INT64_NAN) && (y==OSSIM_INT64_NAN) ); } std::ostream& print(std::ostream& os) const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& os, const ossimIpt64& pt); /** * @return ossimString representing point. * * Format: ( 30, -90 ) * -x- -y- */ std::string toString() const; /** * Initializes this point from string. This method opens an istream to * s and then calls operator>>. * * Expected format: ( 30, -90 ) * -x- -y- * * @param s String to initialize from. * * @see operator>> */ void toPoint(const std::string& s); /** * Method to input the formatted string of the "operator<<". * * Expected format: ( 30, -90 ) * -x- -y- * * This method starts by doing a "makeNan" on pt. So if anything goes * wrong with the stream or parsing pt could be all or partially nan. * * @param is Input stream istream to formatted text. * @param pt osimIpt to be initialized from stream. * @return istream pass in. */ friend OSSIMDLLEXPORT std::istream& operator>>(std::istream& is, ossimIpt64& pt); bool isEqualTo(const ossimIpt64& rhs, ossimCompareType compareType=OSSIM_COMPARE_FULL)const; /*! * METHOD: length() * Returns the RSS of the components. */ double length() const { return sqrt((double)x*x + (double)y*y); } //*** // OPERATORS: +, -, +=, -= // Point add/subtract with other point: //*** ossimIpt64 operator+(const ossimIpt64& p) const { return ossimIpt64(x+p.x, y+p.y); } ossimIpt64 operator-(const ossimIpt64& p) const { return ossimIpt64(x-p.x, y-p.y); } const ossimIpt64& operator+=(const ossimIpt64& p) { x += p.x; y += p.y; return *this; } const ossimIpt64& operator-=(const ossimIpt64& p) { x -= p.x; y -= p.y; return *this; } //*** // OPERATORS: *, / // Scale point components by scalar: //*** ossimDpt operator*(const double& d) const { return ossimDpt(d*x, d*y); } ossimDpt operator/(const double& d) const { return ossimDpt(x/d, y/d); } //*** // Public data members: //*** union {ossim_int64 x; ossim_int64 u; ossim_int64 samp;}; union {ossim_int64 y; ossim_int64 v; ossim_int64 line;}; }; #endif /* #ifndef ossimIpt64_H */ ossim-Miami-2.9.1/include/ossim/base/ossimIrect.h000066400000000000000000000560101352751253100216760ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration for ossimIrect. // Container class for four integer points representing a rectangle. // //******************************************************************* // $Id: ossimIrect.h 22197 2013-03-12 02:00:55Z dburken $ #ifndef ossimIrect_HEADER #define ossimIrect_HEADER 1 #include #include #include #include //*** // NOTE: A word on corner points... // // There is the concept of "pixel is area" and "pixel is point". // - Pixel is area means the (x,y) pixel coordinate refers to the upper left // corner of the pixel, NOT the center of the pixel. // - Pixel is point means the (x,y) pixel coordinate refers to the center // of the pixel, NOT the upper left corner. // // For the uniformity purposes, all pixel points should be in the // "pixel is point" form; therefore, the (x,y) point should represent the // CENTER of the pixel. //*** //*** // Forward class declarations. //*** class ossimDrect; class ossimKeywordlist; //******************************************************************* // CLASS: ossimIrect //******************************************************************* class OSSIMDLLEXPORT ossimIrect { public: enum { UPPER_LEFT = 1, LOWER_LEFT = 2, LOWER_RIGHT = 4, UPPER_RIGHT = 8 }; ossimIrect() : theUlCorner(0, 0), theUrCorner(0, 0), theLrCorner(0, 0), theLlCorner(0, 0), theOrientMode(OSSIM_LEFT_HANDED) {} ossimIrect(ossimIpt ul_corner, ossimIpt lr_corner, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED) : theUlCorner(ul_corner), theUrCorner(lr_corner.x, ul_corner.y), theLrCorner(lr_corner), theLlCorner(ul_corner.x, lr_corner.y), theOrientMode(mode) {} ossimIrect(ossim_int32 ul_corner_x, ossim_int32 ul_corner_y, ossim_int32 lr_corner_x, ossim_int32 lr_corner_y, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED) : theUlCorner(ul_corner_x, ul_corner_y), theUrCorner(lr_corner_x, ul_corner_y), theLrCorner(lr_corner_x, lr_corner_y), theLlCorner(ul_corner_x, lr_corner_y), theOrientMode(mode) {} ossimIrect(const ossimIrect& rect) : theUlCorner(rect.ul()), theUrCorner(rect.ur()), theLrCorner(rect.lr()), theLlCorner(rect.ll()), theOrientMode(rect.orientMode()) {} ossimIrect(const ossimDrect& rect); /*! * Must compute a bounding rect given these image * points. */ ossimIrect(const std::vector& points, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED); ossimIrect(const ossimIpt& p1, const ossimIpt& p2, const ossimIpt& p3, const ossimIpt& p4, ossimCoordSysOrientMode=OSSIM_LEFT_HANDED); //! Constructs an Irect surrounding the specified point, and of specified size. ossimIrect(const ossimIpt& center, ossim_uint32 size_x, ossim_uint32 size_y, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED); /** destructor */ ~ossimIrect(); inline const ossimIrect& operator= (const ossimIrect& rect); const ossimIrect& operator= (const ossimDrect& rect); inline bool operator!= (const ossimIrect& rect) const; inline bool operator== (const ossimIrect& rect) const; friend ossimIrect operator*(double scalar, const ossimIrect& rect) { return ossimIrect((int)floor(rect.theUlCorner.x*scalar), (int)floor(rect.theUlCorner.y*scalar), (int)ceil(rect.theUlCorner.x*scalar+rect.width()*scalar-1), (int)ceil(rect.theUlCorner.y*scalar+rect.height()*scalar-1), rect.theOrientMode); } const ossimIrect& operator*=(ossim_int32 scalar) { *this = ossimIrect((theUlCorner.x*scalar), (theUlCorner.y*scalar), (theUlCorner.x*scalar+width()*scalar-1), (theUlCorner.y*scalar+height()*scalar-1), theOrientMode); return *this; } ossimIrect operator*(ossim_int32 scalar)const { return ossimIrect((theUlCorner.x*scalar), (theUlCorner.y*scalar), (theUlCorner.x*scalar+width()*scalar-1), (theUlCorner.y*scalar+height()*scalar-1), theOrientMode); } const ossimIrect& operator *=(double scalar) { *this = ossimIrect((int)floor(theUlCorner.x*scalar), (int)floor(theUlCorner.y*scalar), (int)ceil(theUlCorner.x*scalar+width()*scalar-1), (int)ceil(theUlCorner.y*scalar+height()*scalar-1), theOrientMode); return *this; } ossimIrect operator *(double scalar)const { return ossimIrect((int)floor(theUlCorner.x*scalar), (int)floor(theUlCorner.y*scalar), (int)ceil(theUlCorner.x*scalar+width()*scalar-1), (int)ceil(theUlCorner.y*scalar+height()*scalar-1), theOrientMode); } const ossimIrect& operator *=(const ossimDpt& scalar) { *this = ossimIrect((int)floor(theUlCorner.x*scalar.x), (int)floor(theUlCorner.y*scalar.y), (int)ceil(theUlCorner.x*scalar.x+width()*scalar.x-1), (int)ceil(theUlCorner.y*scalar.y+height()*scalar.y-1), theOrientMode); return *this; } ossimIrect operator *(const ossimDpt& scalar)const { return ossimIrect((int)floor(theUlCorner.x*scalar.x), (int)floor(theUlCorner.y*scalar.y), (int)ceil(theUlCorner.x*scalar.x+width()*scalar.x-1), (int)ceil(theUlCorner.y*scalar.y+height()*scalar.y-1), theOrientMode); } const ossimIrect& operator +=(const ossimIpt& shift) { *this = ossimIrect(theUlCorner.x+shift.x, theUlCorner.y+shift.y, theLrCorner.x+shift.x, theLrCorner.y+shift.y, theOrientMode); return *this; } const ossimIrect& operator -=(const ossimIpt& shift) { *this = ossimIrect(theUlCorner.x-shift.x, theUlCorner.y-shift.y, theLrCorner.x-shift.x, theLrCorner.y-shift.y, theOrientMode); return *this; } ossimIrect operator +(const ossimIpt& shift)const { return ossimIrect(theUlCorner.x+shift.x, theUlCorner.y+shift.y, theLrCorner.x+shift.x, theLrCorner.y+shift.y, theOrientMode); } ossimIrect operator -(const ossimIpt& shift)const { return ossimIrect(theUlCorner.x-shift.x, theUlCorner.y-shift.y, theLrCorner.x-shift.x, theLrCorner.y-shift.y, theOrientMode); } const ossimIrect& operator +=(const ossimDpt& shift) { *this = ossimIrect((int)floor(theUlCorner.x+shift.x), (int)floor(theUlCorner.y+shift.y), (int)ceil(theUlCorner.x+shift.x+width()-1), (int)ceil(theUlCorner.y+shift.y+height()-1), theOrientMode); return *this; } const ossimIrect& operator -=(const ossimDpt& shift) { *this = ossimIrect((int)floor(theUlCorner.x-shift.x), (int)floor(theUlCorner.y-shift.y), (int)ceil(theUlCorner.x-shift.x+width()-1), (int)ceil(theUlCorner.y-shift.y+height()-1), theOrientMode); return *this; } ossimIrect operator +(const ossimDpt& shift)const { return ossimIrect((int)floor(theUlCorner.x+shift.x), (int)floor(theUlCorner.y+shift.y), (int)ceil(theUlCorner.x+shift.x+width()-1), (int)ceil(theUlCorner.y+shift.y+height()-1), theOrientMode); } ossimIrect operator -(const ossimDpt& shift)const { return ossimIrect((int)floor(theUlCorner.x-shift.x), (int)floor(theUlCorner.y-shift.y), (int)ceil(theUlCorner.x-shift.x+width()-1), (int)ceil(theUlCorner.y-shift.y+height()-1), theOrientMode); return *this; } const ossimIpt& ul() const { return theUlCorner; } const ossimIpt& ur() const { return theUrCorner; } const ossimIpt& lr() const { return theLrCorner; } const ossimIpt& ll() const { return theLlCorner; } const ossimIrect& changeOrientationMode(ossimCoordSysOrientMode mode) { // if we are already in the orientation then return // if(mode == theOrientMode) return *this; if(mode == OSSIM_LEFT_HANDED) { // we must be right handed so change to left handed *this = ossimIrect(theUlCorner.x, theLlCorner.y, theLrCorner.x, theUlCorner.y, OSSIM_LEFT_HANDED); } else { // we must be left handed so change to RIGHT handed *this = ossimIrect(theUlCorner.x, theLlCorner.y, theLrCorner.x, theUlCorner.y, OSSIM_RIGHT_HANDED); } theOrientMode = mode; return *this; } void getBounds(ossim_int32& minx, ossim_int32& miny, ossim_int32& maxx, ossim_int32& maxy)const { minx = theUlCorner.x; maxx = theLrCorner.x; if(theOrientMode == OSSIM_LEFT_HANDED) { miny = theUlCorner.y; maxy = theLrCorner.y; } else { maxy = theUlCorner.y; miny = theLrCorner.y; } } /*! * Initializes center_point with center of the rectangle. * Makes center_point nan if this rectangle has nans. */ void getCenter(ossimDpt& center_point) const; void makeNan() { theUlCorner.makeNan(); theLlCorner.makeNan(); theLrCorner.makeNan(); theUrCorner.makeNan(); } bool hasNans()const{ return (theUlCorner.hasNans() || theLlCorner.hasNans() || theLrCorner.hasNans() || theUrCorner.hasNans());} bool isNan()const{ return (theUlCorner.isNan() && theLlCorner.isNan() && theLrCorner.isNan() && theUrCorner.isNan());} //*** // This class supports both left and right-handed coordinate systems. For // both, the positive x-axis extends to the "right". //*** ossimCoordSysOrientMode orientMode() const { return theOrientMode; } void setOrientMode(ossimCoordSysOrientMode mode) { theOrientMode = mode; } void stretchToTileBoundary(const ossimIpt& tileWidthHeight); /** * @return ossimString representing ossimIrect. * * Format: ( 30, -90, 512, 512, [LH|RH] ) * -x- -y- -w- -h- -Right or left handed- * * where: * x and y are origins either upper left if LEFT HANDED (LH) or * lower left if RIGHT HANDED (RH) * w and h are width and height respectively * The last value is LH or RH to indicate LeftHanded or RightHanded * */ ossimString toString()const; /** * expected Format: form 1: ( 30, -90, 512, 512, [LH|RH] ) * -x- -y- -w- -h- -Right or left handed- * * form 2: ( 30, -90, 512, 512) * -x- -y- -w- -h- * * NOTE: Form 2 assumes Left handed were x,y is origin upper left and y positive down. * * This method starts by doing a "makeNan" on rect. * * @param rectString String to initialize from. * @return true or false to indicate successful parsing. */ bool toRect(const ossimString& rectString); const ossimIrect& expand(const ossimIpt& padding); //! Guarantees that this rect will be at least w X h big. If smaller than specified, the //! corresponding side will be stretched equally in + and - direction to meet required size. //! Returns TRUE if resizing occurred. bool insureMinimumSize(const ossimIpt& width_height); ossim_uint32 area()const { return width()*height(); } /*! * Sets the upper left corner to "pt". Adjusts the remaining corners * accordingly. */ inline void set_ul(const ossimIpt& pt); /*! * Sets the upper right corner to "pt". Adjusts the remaining corners * accordingly. */ inline void set_ur(const ossimIpt& pt); /*! * Sets the lower right corner to "pt". Adjusts the remaining corners * accordingly. */ inline void set_lr(const ossimIpt& pt); /*! * Sets the lower left corner to "pt". Adjusts the remaining corners * accordingly. */ inline void set_ll(const ossimIpt& pt); /*! * Sets the upper left x. Adjusts the remaining corners accordingly. */ inline void set_ulx(ossim_int32 x); /*! * Sets the upper left y. Adjusts the remaining corners accordingly. */ inline void set_uly(ossim_int32 y); /*! * Sets the upper right x. Adjusts the remaining corners accordingly. */ inline void set_urx(ossim_int32 x); /*! * Sets the upper right y. Adjusts the remaining corners accordingly. */ inline void set_ury(ossim_int32 y); /*! * Sets the lower right x. Adjusts the remaining corners accordingly. */ inline void set_lrx(ossim_int32 x); /*! * Sets the lower right y. Adjusts the remaining corners accordingly. */ inline void set_lry(ossim_int32 y); /*! * Sets the lower left x. Adjusts the remaining corners accordingly. */ inline void set_llx(ossim_int32 x); /*! * Sets the lower left y. Adjusts the remaining corners accordingly. */ inline void set_lly(ossim_int32 y); /*! * Returns true if "pt" falls within rectangle. Fall on an edge is also * considered to be within. */ inline bool pointWithin(const ossimIpt& pt) const; /*! * Returns true if any portion of an input rectangle "rect" intersects * "this" rectangle. */ bool intersects(const ossimIrect& rect) const; /*! * Returns true if "this" rectangle is contained completely within * the input rectangular "rect". */ bool completely_within(const ossimIrect& rect) const; ossimCoordSysOrientMode orientationMode()const{return theOrientMode;} /*! * Returns the height of the rectangle. */ ossim_uint32 height() const { ossim_int32 h = theLlCorner.y - theUlCorner.y; if (h < 0) { h = -h; } return static_cast( h + 1 ); } /*! * Returns the width of a rectangle. */ ossim_uint32 width() const { ossim_int32 w = theLrCorner.x - theLlCorner.x; if (w < 0) { w = -w; } return static_cast( w + 1 ); } ossimIpt size() const { return ossimIpt(width(), height()); } ossimIrect clipToRect(const ossimIrect& rect)const; inline ossimIpt midPoint()const; void print(std::ostream& os) const; ossimIrect combine(const ossimIrect& rect)const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& os, const ossimIrect& rect); bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); private: //*** // Private data members representing the rectangle corners. //*** ossimIpt theUlCorner; ossimIpt theUrCorner; ossimIpt theLrCorner; ossimIpt theLlCorner; ossimCoordSysOrientMode theOrientMode; }; //******************************************************************* // Inline Method: ossimIrect::operator=(ossimIrect) //******************************************************************* inline const ossimIrect& ossimIrect::operator=(const ossimIrect& rect) { if (this != &rect) { theUlCorner = rect.ul(); theUrCorner = rect.ur(); theLrCorner = rect.lr(); theLlCorner = rect.ll(); theOrientMode = rect.theOrientMode; if(rect.hasNans()) { makeNan(); } } return *this; } //******************************************************************* // Inline Method: ossimIrect::operator!= //******************************************************************* inline bool ossimIrect::operator!=(const ossimIrect& rect) const { return ( (theUlCorner != rect.ul()) || (theUrCorner != rect.ur()) || (theLrCorner != rect.lr()) || (theLlCorner != rect.ll()) || (theOrientMode != rect.theOrientMode)); } //******************************************************************* // Inline Method: ossimIrect::operator== //******************************************************************* inline bool ossimIrect::operator==(const ossimIrect& rect) const { return ( (theUlCorner == rect.ul()) && (theUrCorner == rect.ur()) && (theLrCorner == rect.lr()) && (theLlCorner == rect.ll()) && (theOrientMode == rect.theOrientMode) ); } //******************************************************************* // Inline Method: ossimIrect::set_ul //******************************************************************* inline void ossimIrect::set_ul(const ossimIpt& pt) { if(pt.hasNans()) { makeNan(); } else { theUlCorner = pt; theUrCorner.y = pt.y; theLlCorner.x = pt.x; } } //******************************************************************* // Inline Method: ossimIrect::set_ur //******************************************************************* inline void ossimIrect::set_ur(const ossimIpt& pt) { if(pt.hasNans()) { makeNan(); } else { theUrCorner = pt; theUlCorner.y = pt.y; theLrCorner.x = pt.x; } } //******************************************************************* // Inline Method: ossimIrect::set_lr //******************************************************************* inline void ossimIrect::set_lr(const ossimIpt& pt) { if(pt.hasNans()) { makeNan(); } else { theLrCorner = pt; theUrCorner.x = pt.x; theLlCorner.y = pt.y; } } //******************************************************************* // Inline Method: ossimIrect::set_ll //******************************************************************* inline void ossimIrect::set_ll(const ossimIpt& pt) { if(pt.hasNans()) { makeNan(); } else { theLlCorner = pt; theUlCorner.x = pt.x; theLrCorner.y = pt.y; } } //******************************************************************* // Inline Method: ossimIrect::set_ulx //******************************************************************* inline void ossimIrect::set_ulx(ossim_int32 x) { theUlCorner.x = x; theLlCorner.x = x; } //******************************************************************* // Inline Method: ossimIrect::set_uly //******************************************************************* inline void ossimIrect::set_uly(ossim_int32 y) { theUlCorner.y = y; theUrCorner.y = y; } //******************************************************************* // Inline Method: ossimIrect::set_urx //******************************************************************* inline void ossimIrect::set_urx(ossim_int32 x) { theUrCorner.x = x; theLrCorner.x = x; } //******************************************************************* // Inline Method: ossimIrect::set_ury //******************************************************************* inline void ossimIrect::set_ury(ossim_int32 y) { theUrCorner.y = y; theUlCorner.y = y; } //******************************************************************* // Inline Method: ossimIrect::set_lrx //******************************************************************* inline void ossimIrect::set_lrx(ossim_int32 x) { theLrCorner.x = x; theUrCorner.x = x; } //******************************************************************* // Inline Method: ossimIrect::set_lry //******************************************************************* inline void ossimIrect::set_lry(ossim_int32 y) { theLrCorner.y = y; theLlCorner.y = y; } //******************************************************************* // Inline Method: ossimIrect::set_llx //******************************************************************* inline void ossimIrect::set_llx(ossim_int32 x) { theLlCorner.x = x; theUlCorner.x = x; } //******************************************************************* // Inline Method: ossimIrect::set_lly //******************************************************************* inline void ossimIrect::set_lly(ossim_int32 y) { theLlCorner.y = y; theLrCorner.y = y; } //******************************************************************* // Inline Method: ossimIrect::pointWithin //******************************************************************* inline bool ossimIrect::pointWithin(const ossimIpt& pt) const { if(hasNans()) { return false; } if (theOrientMode == OSSIM_LEFT_HANDED) return ((pt.x >= ul().x) && (pt.x <= ur().x) && (pt.y >= ul().y) && (pt.y <= ll().y)); else return ((pt.x >= ul().x) && (pt.x <= ur().x) && (pt.y <= ul().y) && (pt.y >= ll().y)); } //******************************************************************* // Inline Method: ossimIrect::midPoint //******************************************************************* inline ossimIpt ossimIrect::midPoint()const { if(hasNans()) { return ossimIpt(OSSIM_INT_NAN, OSSIM_INT_NAN); } double x = (ul().x + ur().x + ll().x + lr().x) * 0.25; double y = (ul().y + ur().y + ll().y + lr().y) * 0.25; return ossimIpt(ossim::round(x), ossim::round(y)); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimIrect64.h000066400000000000000000000231331352751253100220500ustar00rootroot00000000000000//--- // // License: MIT // // Description: // // Contains class declaration for ossimIrect64. // //--- // $Id$ #ifndef ossimIrect64_H #define ossimIrect64_H 1 #include #include #include // Forward class declarations. class ossimDrect; class ossimIrect; class ossimKeywordlist; /** * @class ossimIrect64 * * This class supports both left and right-handed coordinate systems. For both, * the positive x-axis extends to the "right". * * Notes: * 1) If size == 0, operations that return "origin + size - 1" will just return * the origin. * 2) No support for negative size right now. Not sure if we want to support * that. * 3) There are very few nan checks. */ class OSSIMDLLEXPORT ossimIrect64 { public: /** @brief Default constructor. */ ossimIrect64(); /** * @brief Constructor that takes an origin, size and mode. * @param origin * @param size * @param mode */ ossimIrect64(ossimIpt64 origin, ossimIpt64 size, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED); /** * @brief Constructor that takes an origin, size and mode. * @param origin_x * @param origin_y * @param size_x * @param size_y * @param mode */ ossimIrect64(ossim_int64 origin_x, ossim_int64 origin_y, ossim_int64 size_x, ossim_int64 size_y, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED); /** * @brief Copy Constructor. * @rect */ ossimIrect64(const ossimIrect64& rect); /** * @brief Constructor that takes 32 bit rect. * @rect */ ossimIrect64(const ossimIrect& rect); /** * @brief Constructor that takes double rect. * @rect */ ossimIrect64(const ossimDrect& rect); /** * @brief assignment operator from a 64 bit rect. * @param rect */ const ossimIrect64& operator=(const ossimIrect64& rect); /** * @brief assignment operator from a 32 bit rect. * @param rect */ const ossimIrect64& operator=(const ossimIrect& rect); /** * @brief assignment operator from a doubl rect. * @param rect */ const ossimIrect64& operator=(const ossimDrect& rect); /** * @brief Access to origin data member. * * If orientation mode is left handed this will be the upper left; else * lower left for right handed. * * @return Const reference to origin data member. */ const ossimIpt64& origin() const; /** * @brief Access to origin data member. * * If orientation mode is left handed this will be the upper left; else * lower left for right handed. * * @return Reference to origin data member. */ ossimIpt64& origin(); /** * @brief Access to size data member. * @return Const reference to size data member. */ const ossimIpt64& size() const; /** * @brief Access to size data member. * @return Reference to size data member. */ ossimIpt64& size(); /** * @brief Access to orientation mode data member. * @return Const reference to orientation mode data member. */ ossimCoordSysOrientMode orientationMode() const; /** * @brief Access to orientation mode data member. * @return Reference to orientation mode data member. */ ossimCoordSysOrientMode orientationMode(); /** * @brief Get the end point, i.e. origin + size - 1. * * If mode is left handed this is lower right. * If mode is right handed this is upper right. * * @param pt Initialized by this. */ void end(ossimIpt64& pt) const; /** @return the end point. */ ossimIpt64 end() const; /** * @brief Upper left corner. * @param pt Initialized by this. */ void ul(ossimIpt64& pt) const; /** @return Upper left corner. */ ossimIpt64 ul() const; /** * @brief Upper right corner. * @param pt Initialized by this. */ void ur(ossimIpt64& pt) const; /** @return Upper right corner. */ ossimIpt64 ur() const; /** * @brief Lower right corner. * @param pt Initialized by this. */ void lr(ossimIpt64& pt) const; /** @return Lower right corner. */ ossimIpt64 lr() const; /** * @brief Lower left corner. * @param pt Initialized by this. */ void ll(ossimIpt64& pt) const; /** @return Lower left corner. */ ossimIpt64 ll() const; /** * @brief height * @return height */ ossim_uint64 height() const; /** * @brief width * @return width */ ossim_uint64 width() const; /** * @brief Area * @return width*height */ ossim_uint64 area() const; /** * @brief operator!= * @param rect * @return true if not equal; else, false. */ bool operator!=(const ossimIrect64& rect) const; /** * @brief operator== * @param rect * @return true if equal; else, false. */ bool operator==(const ossimIrect64& rect) const; /** * @brief operator+= * @param shift Added to this. * @return Reference to this. */ const ossimIrect64& operator+=(const ossimIpt64& shift); const ossimIrect64& operator+=(const ossimIpt& shift); const ossimIrect64& operator+=(const ossimDpt& shift); /** * @brief operator-= * @param shift Subtracted from this. * @return Reference to this. */ const ossimIrect64& operator-=(const ossimIpt64& shift); const ossimIrect64& operator-=(const ossimIpt& shift); const ossimIrect64& operator-=(const ossimDpt& shift); /** * @brief operator+ * @param shift Added to this. * @return Rectangle with this + shift. */ ossimIrect64 operator+(const ossimIpt64& shift)const; ossimIrect64 operator+(const ossimIpt& shift) const; ossimIrect64 operator+(const ossimDpt& shift) const; /** * @brief operator- * @param shift Subtracted from this. * @return Rectangle with this - shift. */ ossimIrect64 operator-(const ossimIpt64& shift) const; ossimIrect64 operator-(const ossimIpt& shift) const; ossimIrect64 operator-(const ossimDpt& shift) const; /** * @brief Gets the bounds of the rectangle. * @param minx * @param miny * @param maxx * @param maxy */ void getBounds(ossim_int64& minx, ossim_int64& miny, ossim_int64& maxx, ossim_int64& maxy) const; /** * Initializes center_point with center of the rectangle. * Makes center_point nan if this rectangle has nans. */ void getCenter(ossimDpt& center_point) const; /** * @brief Assigns m_origin and m_size to OSSIM_INT64_NAN. */ void makeNan(); /** * @brief Test for nans. * @return true if any nans; false, if not. */ bool hasNans() const; /** * @brief Test for nans. * @return true if everything is nan; false, if not. */ bool isNan() const; /** * @brief Stretches this rectangle to tile boundaries. * @param tileWidthHeight */ bool stretchToTileBoundary(const ossimIpt64& tileWidthHeight); /** * @return ossimString representing ossimIrect64. * * Format: ( 30, -90, 512, 512, [LH|RH] ) * -x- -y- -w- -h- -Right or left handed- * * where: * x and y are origins either upper left if LEFT HANDED (LH) or * lower left if RIGHT HANDED (RH) * w and h are width and height respectively * The last value is LH or RH to indicate LeftHanded or RightHanded * */ ossimString toString()const; /** * expected Format: form 1: ( 30, -90, 512, 512, [LH|RH] ) * -x- -y- -w- -h- -Right or left handed- * * form 2: ( 30, -90, 512, 512) * -x- -y- -w- -h- * * NOTE: Form 2 assumes Left handed were x,y is origin upper left and y * positive down. * * This method starts by doing a "makeNan" on rect. * * @param rectString String to initialize from. * @return true or false to indicate successful parsing. */ bool toRect(const ossimString& rectString); /** * @brief Expands rect by padding. * @param padding */ const ossimIrect64& expand(const ossimIpt64& padding); /*! * Returns true if "pt" falls within rectangle. Fall on an edge is also * considered to be within. */ bool pointWithin(const ossimIpt64& pt) const; /*! * @return true if any portion of an input rectangle "rect" intersects * "this" rectangle. */ bool intersects(const ossimIrect64& rect) const; /*! * @brief Overloaded intersect for ossimIrect. * @return true if any portion of an input rectangle "rect" intersects * "this" rectangle. */ bool intersects(const ossimIrect& rect) const; /*! * Returns true if "this" rectangle is contained completely within * the input rectangular "rect". */ bool completely_within(const ossimIrect64& rect) const; ossimIrect64 clipToRect(const ossimIrect64& rect)const; ossimIpt64 midPoint()const; void print(std::ostream& os) const; friend OSSIM_DLL std::ostream& operator<<(std::ostream& os, const ossimIrect64& rect); ossimIrect64 combine(const ossimIrect64& rect)const; bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); private: // Private data members: ossimIpt64 m_origin; ossimIpt64 m_size; ossimCoordSysOrientMode m_mode; }; #endif /* #ifndef ossimIrect64_H */ ossim-Miami-2.9.1/include/ossim/base/ossimJpegYCbCrVector.h000066400000000000000000000035201352751253100235610ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimJpegYCbCrVector.h 14789 2009-06-29 16:48:14Z dburken $ #ifndef ossimJpegYCbCrVector_HEADER #define ossimJpegYCbCrVector_HEADER #include #include class ossimRgbVector; class OSSIMDLLEXPORT ossimJpegYCbCrVector { public: friend std::ostream& operator << (std::ostream& out, const ossimJpegYCbCrVector& data) { out << "<" << (long)data.theBuf[0] << ", " << (long)data.theBuf[1] << ", " << (long)data.theBuf[2] << ">"; return out; } ossimJpegYCbCrVector(unsigned char Y=0, unsigned char Cb=0, unsigned char Cr=0) { theBuf[0] = Y; theBuf[1] = Cb; theBuf[2] = Cr; } ossimJpegYCbCrVector(const ossimRgbVector&); long clamp(long colorValue, unsigned char min=0, unsigned char max=255)const { colorValue = colorValue > max? max:colorValue; colorValue = colorValue < min? min:colorValue; return colorValue; } ossimJpegYCbCrVector& operator =(const ossimRgbVector&); unsigned char getY() const { return theBuf[0]; } unsigned char getCb()const { return theBuf[1]; } unsigned char getCr()const { return theBuf[2]; } void setY(unsigned char Y) { theBuf[0] = Y; } void setCb(unsigned char Cb) { theBuf[1] = Cb; } void setCr(unsigned char Cr) { theBuf[2] = Cr; } protected: /*! * JpegYCbCr is an 8-bit YCbCr color model. We * will let: * buf[0] = Y * buf[1] = Cb * buf[2] = Cr */ unsigned char theBuf[3]; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimKMeansClustering.h000066400000000000000000000065061352751253100240530ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef ossimKmeansClassifier_HEADER #define ossimKmeansClassifier_HEADER #include #include #include #include /*************************************************************************************************** * * This class provides a sample set clustering capability using the traditional K-means scheme for * partitioning datasets into K distinct groups according to sample value. * * The samples can be provided as a simple array of samples, or as a histogram when the * populations of the corresponding samples are provided as well. The latter scheme is used by the * ossimKMeansFilter for clustering pixel values given the image histogram. * **************************************************************************************************/ class OSSIM_DLL ossimKMeansClustering : public ossimReferenced { public: class Cluster { public: Cluster() : min(0), max(0), mean(0), sigma(0), new_mean(0), n(0) {} double min; // samples in group are => this, used for detecting convergence double max; // samples in group are < this, used for detecting convergence double mean; double sigma; double new_mean; double n; // number of samples collected for running mean }; ossimKMeansClustering(); ~ossimKMeansClustering(); void setNumClusters(ossim_uint32 K); template void setSamples(T* samples, ossim_uint32 num_entries); template void setPopulations(T* populations, ossim_uint32 num_entries); bool computeKmeans(); ossim_uint32 getNumClusters() const { return m_clusters.size(); } double getMean(ossim_uint32 groupId) const; double getSigma(ossim_uint32 groupId) const; double getMinValue(ossim_uint32 groupId) const; double getMaxValue(ossim_uint32 groupId) const; const ossimKMeansClustering::Cluster* getCluster(ossim_uint32 i) const; void setVerbose(bool v=true) const { m_verbose = v; } private: ossim_uint32 m_numEntries; double* m_samples; double* m_populations; // use double to handle arbitrarily large datasets std::vector m_clusters; bool m_clustersValid; mutable bool m_verbose; }; template void ossimKMeansClustering::setSamples(T* samples, ossim_uint32 num_entries) { if ((num_entries == 0) || (samples == 0)) return; m_clustersValid = false; m_numEntries = num_entries; m_samples = new double[num_entries]; for (ossim_uint32 i=0; i void ossimKMeansClustering::setPopulations(T* populations, ossim_uint32 num_entries) { if ((num_entries == 0) || (populations == 0)) return; m_clustersValid = false; m_populations = new double[num_entries]; for (ossim_uint32 i=0; i class OSSIMDLLEXPORT ossimKeyword { public: ossimKeyword(); ossimKeyword(const char* key, const char* description); ossimKeyword(const char* key, const char* description, const char* value); ossimKeyword(const ossimKeyword& src); ~ossimKeyword(); const ossimKeyword& operator=(const ossimKeyword& kw); operator const char*() const; const char* key() const; const char* description() const; const char* value() const; ossimString keyString() const; ossimString descriptionString() const; ossimString valueString() const; void setValue(const char* val); void setValue(const ossimString& val); void setDescription(const char* desc); void setDescription(const ossimString& desc); friend OSSIM_DLL std::ostream& operator<<(std::ostream& os, const ossimKeyword& kw); private: ossimString theKey; ossimString theDesc; ossimString theValue; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimKeywordNames.h000066400000000000000000000172371352751253100232500ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file // // Author: Ken Melero (kmelero@remotesensing.org) // // Description: Common file for global Keywors. // //************************************************************************* // $Id: ossimKeywordNames.h 23037 2014-12-11 20:37:51Z okramer $ #ifndef ossimKeywordNames_HEADER #define ossimKeywordNames_HEADER #include class OSSIMDLLEXPORT ossimKeywordNames { public: //*** // NOTE: List keyword in alphabetical order. //*** static const char* AZIMUTH_ANGLE_KW; static const char* BAND_KW; static const char* BANDS_KW; static const char* BORDER_SIZE_KW; static const char* BRUSH_COLOR_KW; static const char* BYTE_ORDER_KW; static const char* CE90_ABSOLUTE_KW; static const char* CE90_RELATIVE_KW; static const char* CENTER_PIXEL_X_KW; static const char* CENTER_PIXEL_Y_KW; static const char* CENTRAL_MERIDIAN_KW; static const char* CENTRAL_POINT1_LAT_KW; static const char* CENTRAL_POINT1_LON_KW; static const char* CENTRAL_POINT2_LAT_KW; static const char* CENTRAL_POINT2_LON_KW; static const char* COMPRESS_KW; static const char* COMPRESSION_QUALITY_KW; static const char* COMPRESSION_TYPE_KW; static const char* CONVERGENCE_THRESHOLD_KW; static const char* CREATE_EX_KW; static const char* CREATE_EXTERNAL_GEOMETRY_KW; static const char* CREATE_IMAGE_KW; static const char* CREATE_HISTOGRAM_KW; static const char* CREATE_OVERVIEW_KW; static const char* DATA_FILE_KW; static const char* DATE_KW; static const char* DATE_YEAR_KW; static const char* DATE_MONTH_KW; static const char* DATE_DAY_KW; static const char* DATE_HOUR_KW; static const char* DATE_MIN_KW; static const char* DATE_SEC_KW; static const char* DATE_FRACT_SEC_KW; static const char* DATUM_KW; static const char* DECIMAL_DEGREES_PER_PIXEL_LAT; static const char* DECIMAL_DEGREES_PER_PIXEL_LON; static const char* DESCRIPTION_KW; static const char* ELEVATION_ANGLE_KW; static const char* ELEVATION_CELL_KW; static const char* ELEVATION_SOURCE_KW; static const char* ELEVATION_LOOKUP_FLAG_KW; static const char* ELLIPSE_CODE_KW; static const char* ELLIPSE_EPSG_CODE_KW; static const char* ELLIPSE_NAME_KW; static const char* ENABLED_KW; static const char* ENABLE_CACHE_KW; static const char* EXTRACT_VERTICES_KW; static const char* ENTRY_KW; static const char* FALSE_EASTING_NORTHING_KW; static const char* FALSE_EASTING_NORTHING_UNITS_KW; static const char* FALSE_EASTING_KW; static const char* FALSE_NORTHING_KW; static const char* FEATURE_NAME_KW; static const char* FILE_KW; static const char* FILENAME_KW; static const char* FILEPATH_KW; static const char* FILL_FLAG_KW; static const char* FRAME_INDEX_KW; static const char* GCS_CODE_KW; static const char* GEOM_FILE_KW; static const char* HEMISPHERE_KW; static const char* HORIZONTAL_SIZE_KW; static const char* HAS_LUT_KW; static const char* ID_KW; static const char* IMAGE_CE90_KW; static const char* IMAGE_FILE_KW; static const char* IMAGE_ID_KW; static const char* IMAGE_MODEL_ROTATION_KW; static const char* IMAGE_MODEL_TRANSFORM_MATRIX_KW; static const char* IMAGE_MODEL_TRANSFORM_UNIT_KW; static const char* IMAGE_PATH_KW; static const char* IMAGE_TYPE_KW; static const char* IMAGE_DATE_KW; static const char* IMAGE_FILE_SIZE_KW; static const char* INPUT_RR_LEVEL_KW; static const char* INTERLEAVE_TYPE_KW; static const char* JULIAN_DAY_KW; static const char* LAT_INCREMENT_KW; static const char* LL_LAT_KW; static const char* LL_LON_KW; static const char* LR_LAT_KW; static const char* LR_LON_KW; static const char* LL_X_KW; static const char* LL_Y_KW; static const char* LR_X_KW; static const char* LR_Y_KW; static const char* LON_INCREMENT_KW; static const char* MAJOR_AXIS_KW; static const char* MAX_VALUE_KW; static const char* MAX_ITERATIONS_KW; static const char* MAX_QUADTREE_LEVELS_KW; static const char* METADATA_TYPE_KW; static const char* METERS_PER_PIXEL_KW; static const char* METERS_PER_PIXEL_X_KW; static const char* METERS_PER_PIXEL_Y_KW; static const char* MINOR_AXIS_KW; static const char* MIN_VALUE_KW; static const char* NULL_VALUE_KW; static const char* NUMBER_BANDS_KW; static const char* NUMBER_ENTRIES_KW; static const char* NUMBER_INPUT_BANDS_KW; static const char* NUMBER_INPUTS_KW; static const char* NUMBER_OUTPUTS_KW; static const char* NUMBER_OUTPUT_BANDS_KW; static const char* NUMBER_LINES_KW; static const char* NUMBER_REDUCED_RES_SETS_KW; static const char* NUMBER_SAMPLES_KW; static const char* ORIGIN_LATITUDE_KW; static const char* ORIGIN_X_KW; static const char* ORIGIN_Y_KW; static const char* ORIGINAL_MAP_UNITS_KW; static const char* OUTPUT_FILE_KW; static const char* OUTPUT_FILE_PREFIX_KW; static const char* OUTPUT_FILE_EXTENSION_KW; static const char* OUTPUT_TILE_SIZE_KW; static const char* OVERVIEW_COMPRESSION_QUALITY_KW; static const char* OVERVIEW_COMPRESSION_TYPE_KW; static const char* OVERVIEW_FILE_KW; static const char* OVERVIEW_STOP_DIMENSION_KW; static const char* PCS_CODE_KW; static const char* PEN_COLOR_KW; static const char* PHOTOMETRIC_KW; static const char* PIXEL_SCALE_XY_KW; // static const char* PIXEL_SCALE_Y_KW; static const char* PIXEL_SCALE_UNITS_KW; static const char* PIXEL_TYPE_KW; static const char* PLANAR_CONFIG_KW; static const char* POINT_WIDTH_HEIGHT_KW; static const char* PROJECTION_KW; static const char* QUALITY_KW; static const char* QUERY_KW; static const char* RADIOMETRY_KW; static const char* REDUCED_RES_LEVEL_KW; static const char* REF_GPT_LAT_KW; static const char* REF_GPT_LON_KW; static const char* REF_GPT_HGT_KW; static const char* REF_IPT_LINE_KW; static const char* REF_IPT_SAMP_KW; static const char* ROTATION_KW; static const char* SCALAR_TYPE_KW; static const char* SCALE_PER_PIXEL_X_KW; static const char* SCALE_PER_PIXEL_Y_KW; static const char* SCALE_FACTOR_KW; static const char* SCALE_X_KW; static const char* SCALE_Y_KW; static const char* SCALE_FACTOR_X_KW; static const char* SCALE_FACTOR_Y_KW; static const char* SENSOR_ID_KW; static const char* SRS_NAME_KW; static const char* STD_PARALLEL_1_KW; static const char* STD_PARALLEL_2_KW; static const char* THICKNESS_KW; static const char* THREADS_KW; static const char* TIE_POINT_EASTING_KW; static const char* TIE_POINT_NORTHING_KW; static const char* TIE_POINT_XY_KW; // static const char* TIE_POINT_Y_KW; static const char* TIE_POINT_UNITS_KW; static const char* TIE_POINT_LAT_KW; static const char* TIE_POINT_LON_KW; static const char* TILE_SOURCE_KW; static const char* TILE_TYPE_KW; static const char* TILE_SIZE_X_KW; static const char* TILE_SIZE_Y_KW; static const char* TRANSLATION_X_KW; static const char* TRANSLATION_Y_KW; static const char* TYPE_KW; static const char* UL_LAT_KW; static const char* UL_LON_KW; static const char* UNITS_KW; static const char* UR_LAT_KW; static const char* UR_LON_KW; static const char* UL_X_KW; static const char* UL_Y_KW; static const char* UR_X_KW; static const char* UR_Y_KW; static const char* VALID_VERTICES_KW; static const char* VERTICAL_SIZE_KW; static const char* ZONE_KW; protected: ossimKeywordNames(); ossimKeywordNames(const ossimKeywordNames& rhs); const ossimKeywordNames& operator =(const ossimKeywordNames &rhs); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimKeywordlist.h000066400000000000000000000471631352751253100231610ustar00rootroot00000000000000//--- // // License: MIT // // Author: Ken Melero // // Description: This class provides capabilities for keywordlists. // //--- // $Id$ #ifndef ossimKeywordlist_HEADER #define ossimKeywordlist_HEADER 1 #include #include #include #include #include #include #include #include #include #include static const char DEFAULT_DELIMITER = ':'; class ossimFilename; /** * Represents serializable keyword/value map. The format is * * [.]: value [value ...] * * The map is not a multimap, i.e., the keywords must be unique. Only the last occurrence of * identical keywords will be saved in the map. Methods are provided for reading from and writing * to an ascii file. Methods are also provided for merging multiple maps (a.k.a. "lists" or "KWLs") * as well as assorted operations for pruning and counting. * * Disk files representing a KWL can use the C-style "#include " preprocessor directive, * where specifies another external KWL file that will be merged with the current list. * This is convenient for sourcing common settings needed by multiple KWL files. Instead of * duplicating all common keywords/value pairs, the various KWL files can all specify, for example, * * #include common_prefs.kwl * #include "common config.kwl" * * The second form with quotes can be used, especially if the filename has spaces. */ class OSSIM_DLL ossimKeywordlist : public ossimErrorStatusInterface, public ossimReferenced { public: typedef std::map KeywordMap; ossimKeywordlist(const ossimKeywordlist& src); ossimKeywordlist(const std::map& keywordMap); ossimKeywordlist(char delimiter = DEFAULT_DELIMITER, bool expandEnvVars = false); ossimKeywordlist(const char* file, char delimiter = DEFAULT_DELIMITER, bool ignoreBinaryChars = false, bool expandEnvVars = false ); ossimKeywordlist(const ossimFilename& fileName, char delimiter = DEFAULT_DELIMITER, bool ignoreBinaryChars = false, bool expandEnvVars = false); ~ossimKeywordlist(); static const std::string NULL_KW; /*! * Reads file and adds keywords to the KeywordMap. * Returns true if file was parsed, false on error. */ bool addFile(const char* file); /*! * Reads file and adds keywords to the KeywordMap. * Returns true if file was parsed, false on error. */ bool addFile(const ossimFilename& file); /*! * Method to change default delimiter. Handy when parsing * files similar to a ossimKeywordlist. (DEFAULT = ':') */ void change_delimiter(char del); ossimString delimiter_str() const; /*! * If set to true, then strings found having the format * "$(env_var_name)" are expanded in place. */ void setExpandEnvVarsFlag( bool flag ); /*! * Returns the flag that determines whether or not * environment variables are expanded. */ bool getExpandEnvVarsFlag( void ) const; void add(const char* prefix, const ossimKeywordlist& kwl, bool overwrite=true); /** * This is a generic find method that takes a comparator type and iterates through * the map executing the overloaded operator (). * Typical code example format
    typedef std::unary_function, bool> KwlCompareFunctionType;
    
    class KwlKeyCaseInsensitiveEquals : public KwlCompareFunctionType
    {
    public:
       KwlKeyCaseInsensitiveEquals(const ossimString& key):m_key(key){}
       virtual bool operator()(const KwlComparePairType& rhs)const
       {
          return (m_key == rhs.first.downcase());
       }
       ossimString m_key;
    };

    // now for use case example:
    kwl.findValue(value, KwlKeyCaseInsensitiveEquals("foo"));
    
This example shows how to supplly your own comparator and do a case insensitive search for the key foo and the value is set to the variable value. * */ template bool findValue(ossimString& value, const CompareType& compare)const { KeywordMap::const_iterator iter = std::find_if(m_map.begin(), m_map.end(), compare); bool result = (iter != m_map.end()); if(result) value = iter->second; return result; } std::string& operator[](const std::string& key) { return m_map[key]; } std::string operator[](const std::string& key)const { ossimString result = find(key.c_str()); return result.c_str(); } // Methods to add keywords to list. void addPair(const std::string& key, const std::string& value, bool overwrite = true); void addPair(const std::string& prefix, const std::string& key, const std::string& value, bool overwrite = true); /*! * Allows you to extract out a sub keywordlist from another * you can also collapse the hieracrchy by setting * strip prefix to true. */ void add(const ossimKeywordlist& kwl, const char* prefix=0, bool stripPrefix=true); void add(const char* key, const char* value, bool overwrite = true); void add(const char* prefix, const char* key, const char* value, bool overwrite = true); void add(const char* key, char value, bool overwrite = true); void add(const char* prefix, const char* key, char value, bool overwrite = true); void add(const char* key, ossim_int16 value, bool overwrite = true); void add(const char* prefix, const char* key, ossim_int16 value, bool overwrite = true); void add(const char* key, ossim_uint16 value, bool overwrite = true); void add(const char* prefix, const char* key, ossim_uint16 value, bool overwrite = true); void add(const char* key, ossim_int32 value, bool overwrite = true); void add(const char* prefix, const char* key, ossim_int32 value, bool overwrite = true); void add(const char* key, ossim_uint32 value, bool overwrite = true); void add(const char* prefix, const char* key, ossim_uint32 value, bool overwrite = true); void add(const char* key, ossim_int64 value, bool overwrite = true); void add(const char* prefix, const char* key, ossim_int64 value, bool overwrite = true); void add(const char* key, ossim_uint64 value, bool overwrite = true); void add(const char* prefix, const char* key, ossim_uint64 value, bool overwrite = true); /** * @param key Key for key-value pair. * * @param value Value to pair with key. Note this will be stored as a * string. * * @param precision Decimal point precision of the output. (default = 8) * * @param trimZeroFlag If true trailing '0's and any trailing '.' will * be trimmed from the converted string. (default = false) * * @param scientific If true output will be in scientific notation else * fixed is used. (default = false) */ void add(const char* key, ossim_float32 value, bool overwrite = true, int precision = 8); /** * @param key Key for key-value pair. * * @param value Value to pair with key. Note this will be stored as a * string. * * @param precision Decimal point precision of the output. (default = 8) * * @param trimZeroFlag If true trailing '0's and any trailing '.' will * be trimmed from the converted string. (default = false) * * @param scientific If true output will be in scientific notation else * fixed is used. (default = false) */ void add(const char* prefix, const char* key, ossim_float32 value, bool overwrite = true, int precision = 8); /** * @param key Key for key-value pair. * * @param value Value to pair with key. Note this will be stored as a * string. * * @param precision Decimal point precision of the output. (default = 15) * * @param trimZeroFlag If true trailing '0's and any trailing '.' will * be trimmed from the converted string. (default = false) * * @param scientific If true output will be in scientific notation else * fixed is used. (default = false) */ void add(const char* key, ossim_float64 value, bool overwrite = true, int precision = 15); /** * @param key Key for key-value pair. * * @param value Value to pair with key. Note this will be stored as a * string. * * @param precision Decimal point precision of the output. (default = 15) * * @param trimZeroFlag If true trailing '0's and any trailing '.' will * be trimmed from the converted string. (default = false) * * @param scientific If true output will be in scientific notation else * fixed is used. (default = false) */ void add(const char* prefix, const char* key, ossim_float64 value, bool overwrite = true, int precision = 15); /** * @brief Checks for key in map. * * Note that "find" and findKey will alway return an empty string even if * the key in not in the map. * * @return true if key is in map even if value is empty; false, if not. */ bool hasKey( const std::string& key ) const; /** * @brief Find methods that take std::string(s). * Searches the map for key(/prefix) and returns the resulting value * or an empty string if the key was not found. * @param key e.g. "number_line" * @param prefix e..g "image0." * @return Reference to string. This will be empty if not found or * if value is empty. */ const std::string& findKey(const std::string& key) const; const std::string& findKey(const std::string& prefix, const std::string& key) const; const char* find(const char* key) const; const char* find(const char* prefix, const char* key) const; void remove(const char * key); void remove(const char* prefix, const char * key); /*! * Searches the map for the number of keys containing the string. */ ossim_uint32 numberOf(const char* str) const; /*! * Searches the map for the number of keys containing the prefix+key. * * Given the keyword list contains: * * source.type1: foo * source.type2: you * * This: * * int number_of_sources = numberOf("source", "type"); * * number_of_sources equals 2 */ ossim_uint32 numberOf(const char* prefix, const char* key) const; /** * Methods to dump the ossimKeywordlist to a file on disk. * * @param file Name of output file. * @param comment Optional string that will be written to line 1 * as a C++-style comment. A "//" is prepended to the input string. * * @return true on success, false on error. */ virtual bool write(const char* file, const char* comment = 0) const; virtual ossimString toString()const; virtual void toString(ossimString& result)const; virtual void writeToStream(std::ostream &out)const; /** * Outputs in xml format. * @param out Stream to write to. * @param rootTag name of the root XML element/tag */ void toXML(std::ostream &out, const std::string& rootTag="info")const; /** * Outputs in json format. * @param out Stream to write to. * @param rootTag name of the root json element/tag */ void toJSON(std::ostream &out, const std::string& rootTag="info")const; virtual std::ostream& print(std::ostream& os) const; OSSIMDLLEXPORT friend std::ostream& operator<<(std::ostream& os, const ossimKeywordlist& kwl); bool operator ==(ossimKeywordlist& kwl)const; bool operator !=(ossimKeywordlist& kwl)const; /*! * Clear all contents out of the ossimKeywordlist. */ void clear(); /*! * Add contents of another keyword list to this one. * * @param src the keyword list to copy items from. * @param overwrite true if keys existing in this and src should have * their value overwritten by the src value, otherwise false to preserve * the original value. Defaults to true. */ void addList( const ossimKeywordlist &src, bool overwrite = true ); /** deprecated method */ virtual bool parseStream(ossim::istream& is, bool ignoreBinaryChars); virtual bool parseStream(ossim::istream& is); virtual bool parseString(const std::string& inString); /** * This return the sorted keys if you have a list. * Example: * @code * // given a keywordlist called kwl with contents: * // my.list.element1.prop * // my.list.element345.prop * // my.list.element22.prop * std::vector sortedPrefixValues; * kwl.getSortedList(sortedPrefixValues, "my.list.element"); * if(sortedPrefixValues.size()) * { * // contents should be my.list.element1, my.list.element22, my.list.element345 * * } * @endcode * */ void getSortedList(std::vector& prefixValues, const ossimString &prefixKey)const; /*! * Will return a list of keys that contain the string passed in. * Later we will need to allow a user to specify regular expresion * searches. */ std::vector findAllKeysThatContains( const ossimString &searchString)const; /** * @brief Finds keys that match regular expression. * * Note: This does not clear vector passed to it. * * @param result Initialized by this. * @param regularExpression e.g. "image[0-9]*\\.file" */ void findAllKeysThatMatch( std::vector& result, const ossimString ®ularExpression ) const; /** * @brief Gets number keys that match regular expression. * @param regularExpression e.g. "image[0-9]*\\.file" * @return Number of keys matching regular expression. */ ossim_uint32 getNumberOfKeysThatMatch( const ossimString ®ularExpression ) const; void extractKeysThatMatch(ossimKeywordlist& kwl, const ossimString ®ularExpression)const; void removeKeysThatMatch(const ossimString ®ularExpression); /*! * Will return only the portion of the key that * matches the regular expression. * * example: * * source1.source1.a: * source1.source2.a: * source1.source3.a: * source1.source4.a: * source1.source10.a: * * kwl.getSubstringKeyList("source1.source[0-9]*\\."); * * will return: * * source1.source1. * source1.source2. * source1.source3. * source1.source4. * source1.source10. * */ std::vector getSubstringKeyList(const ossimString& regularExpression)const; void getSubstringKeyList(std::vector& result, const ossimString& regularExpression)const; ossim_uint32 getNumberOfSubstringKeys( const ossimString& regularExpression)const; void addPrefixToAll(const ossimString& prefix); void addPrefixToKeysThatMatch(const ossimString& prefix, const ossimString& regularExpression); void stripPrefixFromAll(const ossimString& regularExpression); /*! * Returns the number of elements. */ ossim_uint32 getSize()const; const ossimKeywordlist::KeywordMap& getMap()const; ossimKeywordlist::KeywordMap& getMap(); ossimKeywordlist& downcaseKeywords(); ossimKeywordlist& upcaseKeywords(); ossimKeywordlist& trimAllValues(const ossimString& valueToTrim= ossimString(" \t\n\r")); ossimKeywordlist trimAllValues(const ossimString& valueToTrim= ossimString(" \t\n\r"))const; //! [OLK, Aug/2008] //! Sets the boolean depending on value associated with keyword for values = //! (yes|no|true|false|1|0). Returns TRUE if keyword found, otherwise false. Also returns false //! if none of the above permitted values are specified (rtn_val left unchanged in this case). bool getBoolKeywordValue(bool& rtn_val, const char* keyword, const char* prefix=0) const; protected: enum KeywordlistParseState { KeywordlistParseState_OK = 0, // Used to say this set of token has failed the rules. KeywordlistParseState_FAIL = 1, // Means an error occured that is a mal formed stream for Keywordlist. KeywordlistParseState_BAD_STREAM = 2, }; /*! * Method to parse files to initialize the list. Method will error on * binary characters if "ignoreBinaryChars = false". This is used by * ImageHandler factories that can be passed a binary file inadvertently * by a user. The "ignoreBinaryChars" flag should be set to true if * a text file contains mixed ascii/binary values. * Returns true if file was parsed, false on error. */ bool parseFile(const ossimFilename& file, bool ignoreBinaryChars = false); bool isValidKeywordlistCharacter(ossim_uint8 c)const; void skipWhitespace(ossim::istream& in)const; KeywordlistParseState readComments(ossimString& sequence, ossim::istream& in)const; KeywordlistParseState readPreprocDirective(ossim::istream& in); KeywordlistParseState readKey(ossimString& sequence, ossim::istream& in)const; KeywordlistParseState readValue(ossimString& sequence, ossim::istream& in)const; KeywordlistParseState readKeyAndValuePair(ossimString& key, ossimString& value, ossim::istream& in)const; // Method to see if keyword exists in list. KeywordMap::iterator getMapEntry(const std::string& key); KeywordMap::iterator getMapEntry(const ossimString& key); KeywordMap::iterator getMapEntry(const char* key); // For toXML method lifted from oms::DataInfo. bool isSpecialXmlCharacters(const ossimString& value) const; bool isValidTag(const std::string& value)const; void replaceSpecialCharacters(ossimString& value)const; /** * @return true if a == b, false if not. */ bool isSame( const std::vector& a, const std::vector& b ) const; KeywordMap m_map; char m_delimiter; // enables preserving empty field values, multi lines, ... etc bool m_preserveKeyValues; bool m_expandEnvVars; // enables relative paths in #include directive ossimFilename m_currentlyParsing; }; #endif /* #ifndef ossimKeywordlist_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimLagrangeInterpolator.h000066400000000000000000000032411352751253100247510ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer, GeoEye Inc. // // DESCRIPTION: Contains Lagrange Interpolator class // // $Id$ //************************************************************************************************** #ifndef LagrangeInterp_HEADER #define LagrangeInterp_HEADER #include #include #include #include //****************************************************************************** // CLASS: ossimLagrangeInterpolator //****************************************************************************** class ossimLagrangeInterpolator : public ossimReferenced { friend std::ostream& operator<<(std::ostream&, const ossimLagrangeInterpolator&); friend std::istream& operator>>(std::istream&, ossimLagrangeInterpolator&); public: ossimLagrangeInterpolator() : theNumElements(0) {} ossimLagrangeInterpolator(std::istream&); ossimLagrangeInterpolator(const std::vector& t_array, const std::vector& data_array); ~ossimLagrangeInterpolator(); void addData(const double& t, const NEWMAT::ColumnVector& data); bool interpolate(const double& t, NEWMAT::ColumnVector& result) const; private: std::vector theTeeArray; std::vector theDataArray; mutable std::vector theNormalizer; mutable ossim_uint32 theNumElements; void initializeNormalizer()const; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimLeastSquaresBilin.h000066400000000000000000000065471352751253100242340ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com // // Description: Source code produced by Dave Knopp // //******************************************************************* // $Id: ossimLeastSquaresBilin.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimLeastSquaresBilin_INCLUDE #define ossimLeastSquaresBilin_INCLUDE #include #include /** * @brief Provide 2D Least Squares Bilinear model fitting * The math model is that of a bilinear surface of the form: @code z(x,y) = a + b*x + c*y + d*x*y @endcode * The getLSParms() method returns parameter values which are the least * squares solution associated with the samples added via addSample(). Note * that it is necessary to add at least four sample to obtain a solution. */ class OSSIMDLLEXPORT ossimLeastSquaresBilin { public: ossimLeastSquaresBilin(const ossimLeastSquaresBilin &); /** * Instantiate as zero surface. */ ossimLeastSquaresBilin(); ossimLeastSquaresBilin & operator = (const ossimLeastSquaresBilin &); /** * Free internal storage. */ virtual ~ossimLeastSquaresBilin(); /** * Will clear everything and set it up to * for another solve. Just add points * and call the solve method. */ virtual void clear(); /** * add a single data sample. * * @param xx "x" coordinate of sample location. * @param yy "y" "y" coordinate of sample location. * @param zmea sample value measured at (xx,yy) */ virtual void addSample(double x, double yy, double zmea); /** * return LS solution parameters. * * @param pa set to constant coefficient. * @param pb_x set to linear coefficient of "x" * @param pc_y set to linear coefficient of "y" * @param pd_xy set to cross coefficient of "x*y" */ virtual bool getLSParms(double& pa, double& pb_x, double& pc_y, double& pd_xy)const; /** * @param pa set to constant coefficient. * @param pb_x set to linear coefficient of "x" * @param pc_y set to linear coefficient of "y" * @param pd_xy set to cross coefficient of "x*y" */ virtual void setLSParams(double pa, //constant double pb_x, // linear coefficient of x, double pc_y, // linear coefficient of y double pd_xy); // coefficient of x*y /** * interpolate LS-fit value at location (xx,yy) - returns z(xx,yy). * * @param xx "x" coordinate at which to interpolate. * @param yy "y" "y" coordinate at which to interpolate. * */ virtual inline double lsFitValue(double xx, double yy) const { return (bl_a + bl_b*xx + bl_c*yy + bl_d*xx*yy); } /** * compute least squares parameter solution - true if succesfull. */ bool solveLS(); private: /** * constant term. */ double bl_a; /** * linear-X term. */ double bl_b; /** * linear-Y term. */ double bl_c; /** * cross-XY term */ double bl_d; /** * Normal system coefficient matrix. */ NEWMAT::Matrix* AtA; /** * Normal system RHS vector */ NEWMAT::Matrix* Atb; }; #endif // LeastSquaresBilinilin_INCL_ ossim-Miami-2.9.1/include/ossim/base/ossimLeastSquaresPlane.h000066400000000000000000000055361352751253100242330ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com // // Description: Source code produced by Dave Knopp // //******************************************************************* // $Id: ossimLeastSquaresPlane.h 23167 2015-02-24 22:07:14Z okramer $ #ifndef ossimLeastSquaresPlane_INCLUDE #define ossimLeastSquaresPlane_INCLUDE #include #include /** * @brief Provide 2D Least Squares Plane model fitting * The math model is that of a plane of the form: @code z(x,y) = ax + b*y + c @endcode * The getLSParms() method returns parameter values which are the least * squares solution associated with the samples added via addSample(). Note * that it is necessary to add at least three sample to obtain a solution. */ class OSSIMDLLEXPORT ossimLeastSquaresPlane { public: ossimLeastSquaresPlane(const ossimLeastSquaresPlane &); /** * Instantiate as zero surface. */ ossimLeastSquaresPlane(); ossimLeastSquaresPlane & operator = (const ossimLeastSquaresPlane &); /** * Free internal storage. */ virtual ~ossimLeastSquaresPlane(); /** * Will clear everything and set it up to * for another solve. Just add points * and call the solve method. */ virtual void clear(); /** * add a single data sample. * * @param x coordinate of sample location. * @param y coordinate of sample location. * @param zmea sample value measured at (x,y) */ virtual void addSample(double x, double y, double z_mea); /** * return LS solution parameters. * * @param pa set to x coefficient. * @param pb set to y coefficient * @param pc set to constant term */ virtual bool getLSParms(double& pa, double& pb, double& pc) const; /** * @param pa set to x coefficient. * @param pb set to y coefficient * @param pc set to constant term */ virtual void setLSParams(double pa, double pb, double pc); /** * interpolate LS-fit value at location (xx,yy) - returns z(xx,yy). * * @param xx "x" coordinate at which to interpolate. * @param yy "y" "y" coordinate at which to interpolate. * */ virtual inline double lsFitValue(double xx, double yy) const { return (m_a*xx + m_b*yy + m_c); } /** * compute least squares parameter solution - true if succesfull. */ bool solveLS(); private: /** * linear-X term. */ double m_a; /** * linear-Y term. */ double m_b; /** * constant term. */ double m_c; /** * Normal system coefficient matrix. */ NEWMAT::Matrix* AtA; /** * Normal system RHS vector */ NEWMAT::Matrix* Atb; ossim_uint32 m_numSamples; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimLine.h000066400000000000000000000043111352751253100215140ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts //******************************************************************* // $Id: ossimLine.h 23353 2015-06-01 19:19:10Z dburken $ #ifndef ossimLine_HEADER #define ossimLine_HEADER #include #include class OSSIM_DLL ossimLine { public: friend OSSIM_DLL std::ostream& operator <<(std::ostream& out, const ossimLine& rhs); ossimLine(const ossimDpt& p1=ossimDpt(0,0), const ossimDpt& p2=ossimDpt(0,0)) :theP1(p1), theP2(p2) { } ossimDpt getVector()const { return (theP2-theP1); } /*! * Computes the following equation: * * Note: this object will be line a and the passed * in object will be line b; * and * P1 and P2 coorespond to this object and * P3 and P4 will coorespond to the passed in object. * * Now find point formed at the intersection of line a and b: * * Pa = P1 + ua ( P2 - P1 ) * Pb = P3 + ub ( P4 - P3 ) *const ossimDpt& ul_corner, const ossimDpt& lr_corner, ossimCoordSysOrientMode mode=OSSIM_LEFT_HANDED); * x1 + ua (x2 - x1) = x3 + ub (x4 - x3) * and * y1 + ua (y2 - y1) = y3 + ub (y4 - y3) * * Solve: * ua = ((x4-x3)(y1-y3) - (y4-y3)(x1-x3))/ * ((y4-y3)(x2-x1) - (x4-x3)(y2-y1)) * ub = ((x2-x1)(y1-y3) - (y2-y1)(x1-x3))/ * ((y4-y3)(x2-x1) - (x4-x3)(y2-y1)) * substitute: * * x = x1 + ua (x2 - x1) * y = y1 + ua (y2 - y1) * */ ossimDpt intersectInfinite(const ossimLine& line)const; ossimDpt intersectSegment(const ossimLine& line)const; ossimDpt midPoint()const; double length()const; ossimDpt normal()const; /*! * Will return true if the point is on the line. */ bool isPointWithin(const ossimDpt& point, double delta=FLT_EPSILON)const; bool isPointOnInfiniteLine(const ossimDpt& point, double delta=FLT_EPSILON)const; ossimDpt theP1; ossimDpt theP2; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimListener.h000066400000000000000000000021221352751253100224100ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimListener.h 14789 2009-06-29 16:48:14Z dburken $ #ifndef ossimListener_HEADER #define ossimListener_HEADER #include class ossimEvent; /*! * Base class for all listners. Listners nned to derive from this * class and override the processEvent method. */ class OSSIMDLLEXPORT ossimListener { public: ossimListener(); virtual ~ossimListener(); /** * ProcessEvent. The defaul is to do nothing. Derived * classes need to override this class. */ virtual void processEvent(ossimEvent& event); void enableListener(); void disableListener(); void setListenerEnableFlag(bool flag); bool isListenerEnabled() const; bool getListenerEnableFlag() const; protected: bool theListenerEnableFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimListenerManager.h000066400000000000000000000071231352751253100237110ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: A brief description of the contents of the file. // // //************************************************************************* // $Id: ossimListenerManager.h 14789 2009-06-29 16:48:14Z dburken $ #ifndef ossimListenerManager_HEADER #define ossimListenerManager_HEADER #include #include #include class ossimListener; class ossimEvent; class OSSIMDLLEXPORT ossimListenerManager { public: /*! * Default constructor and needs no initialization. */ ossimListenerManager(); /*! * Default destructor. Note the Manager doesn't own the listeners * and will not delete them */ virtual ~ossimListenerManager(); /*! * Traverses through all listeners and fires an event to them. * if any listener sets the consumed flag on the event it * will stop traversing the list. */ virtual void fireEvent(ossimEvent& event); /*! * Appends the listener onto the list. */ virtual bool addListener(ossimListener* listener); /*! * Will push the lister to the front of the list. */ // virtual bool insertFrontListener(ossimListener* listener); /*! * Finds and removes the listener. */ virtual bool removeListener(ossimListener* listener); /*! * Will find the listener passed in as the first argument * and insert the passed in listener before it. If not * found then it will default to a push to front. */ // virtual bool insertBeforeListener(ossimListener* listenerSearchKey, // ossimListener* listener); /*! * Will find the listener passed in as the first argument * and insert the passed in listener after it. If not * found then it will default to an append. */ // virtual bool insertAfterListener(ossimListener* listenerSearchKey, // ossimListener* listener); /*! * Will insert the listener before the specified * listener. If the index is invalid it defaults * to a push to front. An invalid index is any * index < 0 or larger than the number of items * currently in the list. */ // virtual bool insertBeforeListener(ossimListener* listener, // long index); /*! * Will insert the listener after the specified * listener. If the index is invalid it defaults * to an addListener. An invalid index is any * index < 0 or larger than the number of items * currently in the list. */ // virtual bool insertAfterListener(ossimListener* listener, // long index); /*! * Searches the list and sees if a listener is found */ virtual bool findListener(ossimListener* listener); /*! * Will search the list and return the index if found else * returns a negative value. */ // virtual long getIndexOfListener(ossimListener* listener); // const std::vector& getListeners()const{return theListenerList;} protected: ossimListenerManager(const ossimListenerManager& rhs); /*! * Holds the list of listeners. */ std::list theListenerList; bool theEnabledFlag; mutable std::list theDelayedAdd; mutable std::list theDelayedRemove; mutable bool theFireEventFlag; // mutable std::list::iterator theCurrentIterator; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimLookUpTable.h000066400000000000000000000075241352751253100230170ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration for LookUpTable. //******************************************************************* // $Id: ossimLookUpTable.h 19448 2011-04-26 15:15:07Z dburken $ #ifndef ossimLookUpTable_HEADER #define ossimLookUpTable_HEADER #include #include #include #include #include class ossimKeywordlist; //******************************************************************* // CLASS: LookUpTable //******************************************************************* class OSSIMDLLEXPORT ossimLookUpTable { public: enum { NOT_FOUND = -1 }; /** * By default if you just give an initializer list with strings * then it will assume keys 0..n-1 for each string. */ ossimLookUpTable(const std::initializer_list& stringInitializer); virtual ~ossimLookUpTable(); /*! * @return * Returns the entry string associated with the entry number (key) passed * in. Returns empty string if entry number is not in the list. */ virtual ossimString getEntryString(ossim_int32 entry_number) const; /*! * @param table_index Index into the table * Note: This is not the key mapped to the but the index into the table. * @return * Returns the entry string associated with the table index passed in. * Returns empty string if index is out of range. */ virtual ossimString getTableIndexString(ossim_uint32 table_index) const; /*! * Returns the entry string associated with the entry number passed in. * Returns empty string if entry number is not in the list. */ virtual ossimString operator[](ossim_int32 entry_number) const; /*! * Returns the entry string associated with lookup table keyword entry * in the Keywordlist passed in. * Returns empty string if keyword entry is not in the Keywordlist. */ virtual ossimString getEntryString(const ossimKeywordlist& kwl, const char* prefix=0) const; /*! * Returns the entry number associated with the entry string passed in. * Returns NOT_FOUND(-1) if entry string is not in the list. * If case_insensitive == true(default), the test is case insensitive; * else, the test will be case sensitive. */ virtual ossim_int32 getEntryNumber(const char* entry_string, bool case_insensitive = true) const; /*! * Returns the entry number associated with the lookup table keyword * entry in the Keywordlist passed in. Returns NOT_FOUND(-1) if no * matching entry. * If case_insensitive == true(default), the test is case insensitive; * else, the test will be case sensitive. */ virtual ossim_int32 getEntryNumber(const ossimKeywordlist& kwl, const char* prefix=0, bool case_insensitive = true) const; /*! * Returns keyword for lookups from a Keywordlist. */ virtual ossimKeyword getKeyword() const; virtual ossim_uint32 getTableSize() const; void dumpValues(std::ostream& out)const; protected: ossimLookUpTable(ossim_int32 table_size); class ossimKeyValueMap { public: ossimKeyValueMap(ossim_int32 key=0, const ossimString& value=""): theKey(key), theValue(value) {} void init (ossim_int32 key, const ossimString& value) { theKey=key; theValue=value; } ossim_int32 theKey; ossimString theValue; }; std::vector theTable; ossimLookUpTable(){} }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimLsrPoint.h000066400000000000000000000142031352751253100224000ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Class for representing points in some local space rectangular (LSR) // coordinate system. This coordinate system is related to the ECEF system // by the ossimLsrSpace member object. This class simplifies coordinate // conversions between LSR and ECEF, and other LSR points. // // SOFTWARE HISTORY: //> // 08Aug2001 Oscar Kramer (okramer@imagelinks.com) // Initial coding. //< //***************************************************************************** // $Id: ossimLsrPoint.h 22197 2013-03-12 02:00:55Z dburken $ #ifndef ossimLsrPoint_HEADER #define ossimLsrPoint_HEADER #include #include #include class ossimGpt; class ossimLsrVector; //***************************************************************************** // CLASS: ossimLsrPoint // //***************************************************************************** class OSSIMDLLEXPORT ossimLsrPoint { public: /*! * CONSTRUCTORS: */ ossimLsrPoint() : theData(0,0,0) {} ossimLsrPoint(const ossimLsrPoint& copy_this) : theData(copy_this.theData), theLsrSpace(copy_this.theLsrSpace) {} ossimLsrPoint(const ossimColumnVector3d& assign_this, const ossimLsrSpace& space) : theData(assign_this), theLsrSpace(space) {} ossimLsrPoint(const double& x, const double& y, const double& z, const ossimLsrSpace& space) : theData(x, y, z), theLsrSpace(space) {} ossimLsrPoint(const ossimLsrPoint& convert_this, const ossimLsrSpace&); ossimLsrPoint(const ossimGpt& convert_this, const ossimLsrSpace&); ossimLsrPoint(const ossimEcefPoint& convert_this, const ossimLsrSpace&); /*! * OPERATORS: */ inline const ossimLsrPoint& operator= (const ossimLsrPoint&); //inline below ossimLsrVector operator- (const ossimLsrPoint&) const; ossimLsrPoint operator+ (const ossimLsrVector&) const; inline bool operator==(const ossimLsrPoint&) const;//inline below inline bool operator!=(const ossimLsrPoint&) const;//inline below /*! * CASTING OPERATOR: * Used as: myEcefVector = ossimEcefPoint(this) -- looks like a constructor * but is an operation on this object. ECEF knows nothing about LSR, so * cannot provide an ossimEcefVector(ossimLsrPoint) constructor. */ operator ossimEcefPoint() const; // inline below /*! * DATA ACCESS METHODS: */ double x() const { return theData[0]; } double& x() { return theData[0]; } double y() const { return theData[1]; } double& y() { return theData[1]; } double z() const { return theData[2]; } double& z() { return theData[2]; } ossimColumnVector3d& data() { return theData; } const ossimColumnVector3d& data() const { return theData; } ossimLsrSpace& lsrSpace() { return theLsrSpace; } const ossimLsrSpace& lsrSpace() const { return theLsrSpace; } bool hasNans()const { return (ossim::isnan(theData[0])|| ossim::isnan(theData[1])|| ossim::isnan(theData[2])); } void makeNan() { theData[0] = ossim::nan(); theData[1] = ossim::nan(); theData[2] = ossim::nan(); } /*! * Debug Dump: */ inline void print(std::ostream& stream = ossimNotify(ossimNotifyLevel_INFO)) const; friend std::ostream& operator<< (std::ostream& os , const ossimLsrPoint& instance) { instance.print(os); return os; } protected: /*! * METHOD: initialize(ossimEcefPoint) * Convenience method used by several constructors for initializing theData * given an ECEF point. Assumes theLsrSpace has been previously initialized. */ void initialize(const ossimEcefPoint& ecef_point); ossimColumnVector3d theData; ossimLsrSpace theLsrSpace; }; //================== BEGIN DEFINITIONS FOR INLINE METHODS ===================== //***************************************************************************** // INLINE OPERATOR: ossimLsrPoint::operator=(ossimLsrPoint) //***************************************************************************** inline const ossimLsrPoint& ossimLsrPoint::operator=(const ossimLsrPoint& p) { theData = p.theData; theLsrSpace = p.theLsrSpace; return *this; } //***************************************************************************** // INLINE OPERATOR: ossimLsrPoint::operator==(ossimLsrPoint) //***************************************************************************** inline bool ossimLsrPoint::operator==(const ossimLsrPoint& p) const { return ((theData == p.theData) && (theLsrSpace == p.theLsrSpace)); } //***************************************************************************** // INLINE OPERATOR: ossimLsrPoint::operator!=(ossimLsrPoint) //***************************************************************************** inline bool ossimLsrPoint::operator!=(const ossimLsrPoint& p) const { return (!(*this == p)); } //***************************************************************************** // INLINE OPERATOR: ossimLsrPoint::operator ossimEcefPoint() // // Looks like a constructor for an ossimEcefPoint but is an operation on this // object. Returns the ossimEcefPoint equivalent. //***************************************************************************** inline ossimLsrPoint::operator ossimEcefPoint() const { return ossimEcefPoint(theLsrSpace.origin().data() + theLsrSpace.lsrToEcefRotMatrix()*theData); } //***************************************************************************** // INLINE METHOD: ossimLsrPoint::print(std::ostream) // // Dumps contents for debug purposes. //***************************************************************************** inline void ossimLsrPoint::print(std::ostream& os) const { os << "(ossimLsrPoint)\n" << " theData = " << theData << "\n theLsrSpace = " << theLsrSpace; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimLsrRay.h000066400000000000000000000127351352751253100220520ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimLsrRay.h // // Copyright (C) 2001 ImageLinks, Inc. // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Class for representing rays in some local space rectangular (LSR) // coordinate system. This coordinate system is related to the ECEF system // by the ossimLsrSpace member object. This class simplifies coordinate // conversions between LSR and ECEF, and other LSR spaces. // // An LSR ray is defined as having an LSR origin point and an LSR unit // direction vector radiating from the origin. // // SOFTWARE HISTORY: //> // 08Aug2001 Oscar Kramer // Initial coding. //< //***************************************************************************** // $Id: ossimLsrRay.h 11428 2007-07-27 18:44:18Z gpotts $ #ifndef ossimLsrRay_HEADER #define ossimLsrRay_HEADER #include #include #include #include //***************************************************************************** // CLASS: ossimLsrRay // //***************************************************************************** class OSSIMDLLEXPORT ossimLsrRay { public: /*! * CONSTRUCTORS: */ ossimLsrRay() {} ossimLsrRay(const ossimLsrRay& copy_this) : theOrigin(copy_this.theOrigin), theDirection(copy_this.theDirection) {} ossimLsrRay(const ossimLsrPoint& origin, const ossimLsrVector& direction); ossimLsrRay(const ossimLsrPoint& origin, const ossimLsrPoint& towards); ossimLsrRay(const ossimLsrRay& convert_this, const ossimLsrSpace& new_space) : theOrigin(convert_this.theOrigin, new_space), theDirection(convert_this.theDirection, new_space) {} /*! * OPERATORS: */ const ossimLsrRay& operator= (const ossimLsrRay& r); // inline below bool operator==(const ossimLsrRay& r) const; // inline below bool operator!=(const ossimLsrRay& r) const; // inline below /*! * DATA ACCESS METHODS: */ const ossimLsrPoint& origin() const { return theOrigin; } const ossimLsrVector& direction() const { return theDirection; } const ossimLsrSpace& lsrSpace() const { return theOrigin.lsrSpace(); } /*! * CASTING OPERATOR: ossimEcefRay() * Looks like a constructor for an ossimEcefRay but is an operation on this * object. Returns the ossimEcefRay equivalent. */ operator ossimEcefRay () const; // inline below bool hasNans()const { return (theOrigin.hasNans()||theDirection.hasNans()); } void makeNan() { theOrigin.makeNan(); theDirection.makeNan(); } /*! * METHOD: extend(t) * Extends the ray by distance t (meters) from the origin to the LSR * point returned (in same space). */ ossimLsrPoint extend(const double& t) const { if(!hasNans()) { return (theOrigin + theDirection*t); } ossimLsrPoint p; p.makeNan(); return p; } /*! * Debug Dump: */ void print(std::ostream& stream = ossimNotify(ossimNotifyLevel_INFO)) const; // inline below friend std::ostream& operator<< (std::ostream& os , const ossimLsrRay& instance) { instance.print(os); return os; } private: ossimLsrPoint theOrigin; ossimLsrVector theDirection; }; //================== BEGIN DEFINITIONS FOR INLINE METHODS ===================== //***************************************************************************** // INLINE METHOD: ossimEcefRay::operator=(ossimEcefRay) //***************************************************************************** inline const ossimLsrRay& ossimLsrRay::operator=(const ossimLsrRay& r) { theOrigin = r.theOrigin; theDirection = r.theDirection; return *this; } //***************************************************************************** // INLINE METHOD: ossimEcefRay::operator==(ossimEcefRay) //***************************************************************************** inline bool ossimLsrRay::operator==(const ossimLsrRay& r) const { return ((theOrigin == r.theOrigin) && (theDirection == r.theDirection)); } //***************************************************************************** // INLINE METHOD: ossimEcefRay::operator!=(ossimEcefRay) //***************************************************************************** inline bool ossimLsrRay::operator!=(const ossimLsrRay& r) const { return !(*this == r); } //***************************************************************************** // INLINE CASTING OPERATOR: ossimEcefRay() // // Looks like a constructor for an ossimEcefRay but is an operation on this // object. Returns the ossimEcefRay equivalent. //***************************************************************************** inline ossimLsrRay::operator ossimEcefRay() const { return ossimEcefRay(ossimEcefPoint(theOrigin), ossimEcefVector(theDirection)); } //***************************************************************************** // INLINE METHOD: ossimLsrRay::print(std::ostream) // Dumps contents for debug purposes. //***************************************************************************** inline void ossimLsrRay::print(std::ostream& os) const { os << "(ossimLsrRay)" << "\n theOrigin = " << theOrigin << "\n theDirection = " << theDirection << std::ends; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimLsrSpace.h000066400000000000000000000105021352751253100223400ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // This class maintains the relationship between a local space rectangular // (LSR) coordinate system and the earth-centered, earth-fixed (ECEF) system. // // SOFTWARE HISTORY: //> // 08Aug2001 Oscar Kramer (okramer@imagelinks.com) // Initial coding. //< //***************************************************************************** // $Id: ossimLsrSpace.h 12790 2008-05-05 13:41:33Z dburken $ #ifndef ossimLsrSpace_HEADER #define ossimLsrSpace_HEADER #include // #include #include #include class ossimGpt; class ossimEcefVector; //***************************************************************************** // CLASS: ossimLsrSpace // // This class maintains the relationship between a local space rectangular // (LSR) coordinate system and the earth-centered, earth-fixed (ECEF) system. // //***************************************************************************** class OSSIMDLLEXPORT ossimLsrSpace { public: /*! * DEFAULT & COPY CONSTRUCTOR: */ ossimLsrSpace() {} ossimLsrSpace(const ossimLsrSpace& copy_this) : theLsrToEcefRotMatrix(copy_this.theLsrToEcefRotMatrix), theOrigin(copy_this.theOrigin) {} /*! * CONSTRUCTORS: The following three constructors accept an ECEF origin * and two of the three axes direction vectors. Note the use of the dummy * "int" argument (not used) to hold the place of the unspecified axes. */ ossimLsrSpace(const ossimEcefPoint& origin, const ossimEcefVector& x_dir_ecf_vec, const ossimEcefVector& y_dir_ecf_vec, const int z_not_provided_space_holder); ossimLsrSpace(const ossimEcefPoint& origin, const ossimEcefVector& x_dir_ecf_vec, const int y_not_provided_space_holder, const ossimEcefVector& z_dir_ecf_vec); ossimLsrSpace(const ossimEcefPoint& origin, const int x_not_provided_space_holder, const ossimEcefVector& y_dir_ecf_vec, const ossimEcefVector& z_dir_ecf_vec); /*! * CONSTRUCTOR: ossimLsrSpace(ossimGpt, y_azimuth) * This constructor sets up a local coordinate system centered at the * specified groundpoint, with the Z-axis normal to the ellipsoid and the * Y-axis rotated clockwise from north by the y_azimuth. This angle defaults * to 0, producing an East-North-Up (ENU) system. */ ossimLsrSpace(const ossimGpt& origin, const double& y_azimuth=0); /*! * CONSTRUCTOR: ossimLsrSpace(ossimEcefPt, NEWMAT::Matrix) * This constructor sets up a local coordinate system centered at the * specified ECF, with given LSR-to-ECF rotation. */ ossimLsrSpace(const ossimEcefPoint& origin, const NEWMAT::Matrix& lsrToEcfRot) : theLsrToEcefRotMatrix (lsrToEcfRot), theOrigin (origin) {} ~ossimLsrSpace() {} /*! * OPERATORS: */ bool operator == (const ossimLsrSpace&) const; bool operator != (const ossimLsrSpace& that) const { return !(*this == that); } const ossimLsrSpace& operator = (const ossimLsrSpace& space); /*! * DATA ACCESS METHODS: */ const ossimEcefPoint& origin() const { return theOrigin; } const NEWMAT::Matrix& lsrToEcefRotMatrix() const { return theLsrToEcefRotMatrix; } NEWMAT::Matrix ecefToLsrRotMatrix() const { return theLsrToEcefRotMatrix.t(); } /*! * METHOD: lsrSpaceErrorMessage() * Convenience method accessible to all owners of an ossimLsrSpace for * displaying an error message when LSR spaces do not match between * objects. All operations between LSR objects must be in a common space. */ static std::ostream& lsrSpaceErrorMessage(std::ostream& os=ossimNotify(ossimNotifyLevel_INFO)); /*! * Debug Dump: */ void print(std::ostream& stream = ossimNotify(ossimNotifyLevel_INFO)) const; friend std::ostream& operator<< (std::ostream& os , const ossimLsrSpace& instance) { instance.print(os); return os; } private: NEWMAT::Matrix theLsrToEcefRotMatrix; ossimEcefPoint theOrigin; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimLsrVector.h000066400000000000000000000252021352751253100225520ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Class for representing vectors in some local space rectangular (LSR) // coordinate system. This coordinate system is related to the ECEF system // by the ossimLsrSpace member object. This class simplifies coordinate // conversions between LSR and ECEF, and other LSR vectors. // // SOFTWARE HISTORY: //> // 08Aug2001 Oscar Kramer // Initial coding. //< //***************************************************************************** // $Id: ossimLsrVector.h 12790 2008-05-05 13:41:33Z dburken $ #ifndef ossimLsrVector_HEADER #define ossimLsrVector_HEADER #include #include #include #include #include #include class ossimGpt; //***************************************************************************** // CLASS: ossimLsrVector // //***************************************************************************** class OSSIMDLLEXPORT ossimLsrVector { public: /*! * CONSTRUCTORS: */ ossimLsrVector() : theData (0,0,0) {} ossimLsrVector(const ossimLsrVector& copy_this) : theData(copy_this.theData), theLsrSpace(copy_this.theLsrSpace) {} ossimLsrVector(const ossimColumnVector3d& assign_this, const ossimLsrSpace& space) : theData(assign_this), theLsrSpace(space) {} ossimLsrVector(const double& x, const double& y, const double& z, const ossimLsrSpace& space) : theData(x,y,z), theLsrSpace(space) {} ossimLsrVector(const ossimEcefVector& convert_this, const ossimLsrSpace&); ossimLsrVector(const ossimLsrVector& convert_this, const ossimLsrSpace&); /*! * OPERATORS: (all methods inlined below) */ const ossimLsrVector& operator= (const ossimLsrVector&); ossimLsrVector operator- () const; ossimLsrVector operator+ (const ossimLsrVector&) const; ossimLsrVector operator- (const ossimLsrVector&) const; ossimLsrPoint operator+ (const ossimLsrPoint&) const; ossimLsrVector operator* (const double& scalar) const; ossimLsrVector operator/ (const double& scalar) const; bool operator==(const ossimLsrVector&) const; bool operator!=(const ossimLsrVector&) const; /*! * CASTING OPERATOR: * Used as: myEcefVector = ossimEcefVector(this) -- looks like a constructor * but is an operation on this object. ECEF knows nothing about LSR, so * cannot provide an ossimEcefVector(ossimLsrVector) constructor. */ operator ossimEcefVector() const; // inline below /*! * Vector-related functions: */ double dot(const ossimLsrVector&) const; double angleTo(const ossimLsrVector&) const; ossimLsrVector cross(const ossimLsrVector&) const; ossimLsrVector unitVector() const;//inline below double magnitude() const;//inline below void normalize(); // inline below /*! * DATA ACCESS METHODS: */ double x() const { return theData[0]; } double& x() { return theData[0]; } double y() const { return theData[1]; } double& y() { return theData[1]; } double z() const { return theData[2]; } double& z() { return theData[2]; } bool hasNans()const { return (ossim::isnan(theData[0])|| ossim::isnan(theData[1])|| ossim::isnan(theData[2])); } void makeNan() { theData[0] = ossim::nan(); theData[1] = ossim::nan(); theData[2] = ossim::nan(); } ossimColumnVector3d& data() { return theData; } const ossimColumnVector3d& data() const { return theData; } ossimLsrSpace& lsrSpace() { return theLsrSpace; } const ossimLsrSpace& lsrSpace() const { return theLsrSpace; } /*! * Debug Dump: */ std::ostream& print(std::ostream& stream) const; friend std::ostream& operator<< (std::ostream& os , const ossimLsrVector& instance); protected: /*! * METHOD: initialize(ossimEcefVector) * Convenience method used by several constructors for initializing theData * given an ECEF vector. Assumes theLsrSpace has been previously initialized */ void initialize(const ossimEcefVector& ecef_point); ossimColumnVector3d theData; ossimLsrSpace theLsrSpace; }; //================== BEGIN DEFINITIONS FOR INLINE METHODS ===================== //***************************************************************************** // INLINE OPERATOR: ossimLsrVector::operator=(ossimLsrVector) //***************************************************************************** inline const ossimLsrVector& ossimLsrVector::operator=(const ossimLsrVector& v) { theData = v.theData; theLsrSpace = v.theLsrSpace; return *this; } //***************************************************************************** // INLINE OPERATOR: ossimLsrVector::operator-() (negate) //***************************************************************************** inline ossimLsrVector ossimLsrVector::operator-() const { return ossimLsrVector(-theData, theLsrSpace); } //***************************************************************************** // INLINE OPERATOR: ossimLsrVector::operator+(ossimLsrVector) //***************************************************************************** inline ossimLsrVector ossimLsrVector::operator+(const ossimLsrVector& v) const { if ((theLsrSpace != v.theLsrSpace)||hasNans()||v.hasNans()) { theLsrSpace.lsrSpaceErrorMessage(); return ossimLsrVector(ossim::nan(), ossim::nan(), ossim::nan(), theLsrSpace); } return ossimLsrVector(theData + v.theData, theLsrSpace); } //***************************************************************************** // INLINE OPERATOR: ossimLsrVector::operator-(ossimLsrVector) //***************************************************************************** inline ossimLsrVector ossimLsrVector::operator-(const ossimLsrVector& v) const { if ((theLsrSpace != v.theLsrSpace)||hasNans()||v.hasNans()) { theLsrSpace.lsrSpaceErrorMessage(); return ossimLsrVector(ossim::nan(), ossim::nan(), ossim::nan(), theLsrSpace); } return ossimLsrVector(theData - v.data(), theLsrSpace); } //***************************************************************************** // INLINE OPERATOR: ossimLsrVector::operator+(ossimLsrPoint) //***************************************************************************** inline ossimLsrPoint ossimLsrVector::operator+(const ossimLsrPoint& p) const { if ((theLsrSpace != p.lsrSpace())||hasNans()||p.hasNans()) { theLsrSpace.lsrSpaceErrorMessage(); return ossimLsrPoint(ossim::nan(), ossim::nan(), ossim::nan(), theLsrSpace); } return ossimLsrPoint(theData + p.data(), theLsrSpace); } //***************************************************************************** // INLINE OPERATOR: ossimLsrVector::operator*(double scalar) //***************************************************************************** inline ossimLsrVector ossimLsrVector::operator*(const double& scalar) const { return ossimLsrVector(theData*scalar, theLsrSpace); } //***************************************************************************** // INLINE OPERATOR: ossimLsrVector::operator/(double scalar) //***************************************************************************** inline ossimLsrVector ossimLsrVector::operator/(const double& scalar) const { return ossimLsrVector(theData/scalar, theLsrSpace); } //***************************************************************************** // INLINE OPERATOR: ossimLsrVector::operator==(ossimLsrVector) //***************************************************************************** inline bool ossimLsrVector::operator==(const ossimLsrVector& v) const { return ((theData == v.theData) && (theLsrSpace == v.theLsrSpace)); } //***************************************************************************** // INLINE OPERATOR: ossimLsrVector::operator!=(ossimLsrVector) //***************************************************************************** inline bool ossimLsrVector::operator!=(const ossimLsrVector& v) const { return (!(*this == v)); } //***************************************************************************** // INLINE OPERATOR: ossimEcefVector() // // Looks like a constructor for an ossimEcefVector but is an operation on this // object. Returns the ossimEcefVector equivalent. // //***************************************************************************** inline ossimLsrVector::operator ossimEcefVector() const { return ossimEcefVector(theLsrSpace.lsrToEcefRotMatrix()*theData); } //***************************************************************************** // INLINE METHOD: ossimLsrVector::unitVector() // Returns a unit vector parallel to this. //***************************************************************************** inline ossimLsrVector ossimLsrVector::unitVector() const { if(hasNans()) return ossimLsrVector(ossim::nan(), ossim::nan(), ossim::nan(), theLsrSpace); return ossimLsrVector(theData/theData.magnitude(), theLsrSpace); } //***************************************************************************** // INLINE METHOD: ossimLsrVector::magnitude() //***************************************************************************** inline double ossimLsrVector::magnitude() const { if(hasNans()) return ossim::nan(); return theData.magnitude(); } //***************************************************************************** // INLINE METHOD: ossimLsrVector::normalize() // Normalizes this vector. //***************************************************************************** inline void ossimLsrVector::normalize() { theData /= theData.magnitude(); } //***************************************************************************** // PROTECTED INLINE METHOD: ossimLsrPoint::initialize(ossimEcefPoint) // // Convenience method used by several constructors for initializing theData // given an ECEF point. Assumes theLsrSpace has been previously initialized. // //***************************************************************************** inline void ossimLsrVector::initialize(const ossimEcefVector& ecef_vector) { theData = theLsrSpace.ecefToLsrRotMatrix() * ecef_vector.data(); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimMatrix3x3.h000066400000000000000000000050431352751253100224320ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // Helper class for using NEWMAT::Matrix's. // //******************************************************************* // $Id: ossimMatrix3x3.h 14789 2009-06-29 16:48:14Z dburken $ #ifndef ossimMatrix3x3_HEADER #define ossimMatrix3x3_HEADER #include #include #include #include class ossimColumnVector3d; class OSSIMDLLEXPORT ossimMatrix3x3 { public: /*! * Uses the matrix package to compute the eigenvalues for this * matrix */ ossimColumnVector3d getEigenValues(const NEWMAT::Matrix& rhs); /*! * Returns a blank 3x3 matrix. */ static NEWMAT::Matrix create(); /*! * Returns a copy of "m". * Note: * If "m" is not a 3x3 that's an error and a blank matrix is returned. */ static NEWMAT::Matrix create(const NEWMAT::Matrix& m); /*! * Create a 3x3 with assigned values. */ static NEWMAT::Matrix create(double v00, double v01, double v02, double v10, double v11, double v12, double v20, double v21, double v22); static NEWMAT::Matrix createIdentity(); static NEWMAT::Matrix createZero(); static NEWMAT::Matrix createRotationMatrix(double angleX, double angleY, double angleZ, ossimCoordSysOrientMode orientationMode=OSSIM_RIGHT_HANDED); static NEWMAT::Matrix createRotationXMatrix(double angle, ossimCoordSysOrientMode orientationMode=OSSIM_RIGHT_HANDED); static NEWMAT::Matrix createRotationYMatrix(double angle, ossimCoordSysOrientMode orientationMode=OSSIM_RIGHT_HANDED); static NEWMAT::Matrix createRotationZMatrix(double angle, ossimCoordSysOrientMode orientationMode=OSSIM_RIGHT_HANDED); static NEWMAT::Matrix createScaleMatrix(double X, double Y, double Z); static NEWMAT::Matrix createTranslationMatrix(double dx,double dy); protected: ossimMatrix3x3(){} // To squash un-warranted compiler warnings... private: ossimMatrix3x3(const ossimMatrix3x3& rhs); const ossimMatrix3x3& operator=(const ossimMatrix3x3& rhs); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimMatrix4x4.h000066400000000000000000000362351352751253100224430ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimMatrix4x4.h 19824 2011-07-15 16:01:34Z dburken $ #ifndef ossimMatrix4x4_HEADER #define ossimMatrix4x4_HEADER #include #include #include #include #include #include class OSSIM_DLL ossimMatrix4x4 { public: friend std::ostream& operator<<(std::ostream& out, const ossimMatrix4x4& data) { return out << data.getData(); } ossimMatrix4x4(); ossimMatrix4x4(const NEWMAT::Matrix& m); ossimMatrix4x4(double v00, double v01, double v02, double v03, double v10, double v11, double v12, double v13, double v20, double v21, double v22, double v23, double v30, double v31, double v32, double v33); inline explicit ossimMatrix4x4(const ossim::Quaternion& quat){ makeRotate(quat);} ossimMatrix4x4(const ossimMatrix4x4& rhs) :theData(4,4) { theData[0][0] = rhs.theData[0][0]; theData[0][1] = rhs.theData[0][1]; theData[0][2] = rhs.theData[0][2]; theData[0][3] = rhs.theData[0][3]; theData[1][0] = rhs.theData[1][0]; theData[1][1] = rhs.theData[1][1]; theData[1][2] = rhs.theData[1][2]; theData[1][3] = rhs.theData[1][3]; theData[2][0] = rhs.theData[2][0]; theData[2][1] = rhs.theData[2][1]; theData[2][2] = rhs.theData[2][2]; theData[2][3] = rhs.theData[2][3]; theData[3][0] = rhs.theData[3][0]; theData[3][1] = rhs.theData[3][1]; theData[3][2] = rhs.theData[3][2]; theData[3][3] = rhs.theData[3][3]; } void makeRotate( const ossim::Quaternion& quat); void setRotate( const ossim::Quaternion& quat); ossim::Quaternion getRotate()const; void getRotate(ossim::Quaternion& quat)const; ossimMatrix4x4 operator=(const ossimMatrix4x4& rhs) { theData[0][0]=rhs.theData[0][0]; theData[0][1]=rhs.theData[0][1]; theData[0][2]=rhs.theData[0][2]; theData[0][3]=rhs.theData[0][3]; theData[1][0]=rhs.theData[1][0]; theData[1][1]=rhs.theData[1][1]; theData[1][2]=rhs.theData[1][2]; theData[1][3]=rhs.theData[1][3]; theData[2][0]=rhs.theData[2][0]; theData[2][1]=rhs.theData[2][1]; theData[2][2]=rhs.theData[2][2]; theData[2][3]=rhs.theData[2][3]; theData[3][0]=rhs.theData[3][0]; theData[3][1]=rhs.theData[3][1]; theData[3][2]=rhs.theData[3][2]; theData[3][3]=rhs.theData[3][3]; return *this; } ossimMatrix4x4 operator+ (const ossimMatrix4x4& rhs)const { return ossimMatrix4x4(theData[0][0] + rhs.theData[0][0], theData[0][1] + rhs.theData[0][1], theData[0][2] + rhs.theData[0][2], theData[0][3] + rhs.theData[0][3], theData[1][0] + rhs.theData[1][0], theData[1][1] + rhs.theData[1][1], theData[1][2] + rhs.theData[1][2], theData[1][3] + rhs.theData[1][3], theData[2][0] + rhs.theData[2][0], theData[2][1] + rhs.theData[2][1], theData[2][2] + rhs.theData[2][2], theData[2][3] + rhs.theData[2][3], theData[3][0] + rhs.theData[3][0], theData[3][1] + rhs.theData[3][1], theData[3][2] + rhs.theData[3][2], theData[3][3] + rhs.theData[3][3]); } ossimMatrix4x4 operator- (const ossimMatrix4x4& rhs)const { return ossimMatrix4x4(theData[0][0] - rhs.theData[0][0], theData[0][1] - rhs.theData[0][1], theData[0][2] - rhs.theData[0][2], theData[0][3] - rhs.theData[0][3], theData[1][0] - rhs.theData[1][0], theData[1][1] - rhs.theData[1][1], theData[1][2] - rhs.theData[1][2], theData[1][3] - rhs.theData[1][3], theData[2][0] - rhs.theData[2][0], theData[2][1] - rhs.theData[2][1], theData[2][2] - rhs.theData[2][2], theData[2][3] - rhs.theData[2][3], theData[3][0] - rhs.theData[3][0], theData[3][1] - rhs.theData[3][1], theData[3][2] - rhs.theData[3][2], theData[3][3] - rhs.theData[3][3]); } friend ossimColumnVector4d operator * (const ossimMatrix4x4& lhs, const ossimColumnVector4d& rhs) { return ossimColumnVector4d( (lhs.theData[0][0]*rhs[0] + lhs.theData[0][1]*rhs[1] + lhs.theData[0][2]*rhs[2] + lhs.theData[0][3]*rhs[3]), (lhs.theData[1][0]*rhs[0] + lhs.theData[1][1]*rhs[1] + lhs.theData[1][2]*rhs[2] + lhs.theData[1][3]*rhs[3]), (lhs.theData[2][0]*rhs[0] + lhs.theData[2][1]*rhs[1] + lhs.theData[2][2]*rhs[2] + lhs.theData[2][3]*rhs[3]), (lhs.theData[3][0]*rhs[0] + lhs.theData[3][1]*rhs[1] + lhs.theData[3][2]*rhs[2] + lhs.theData[3][3]*rhs[3])); } friend ossimColumnVector3d operator * (const ossimMatrix4x4& lhs, const ossimColumnVector3d& rhs) { // assume the 4 coordinate (homogeneous coord) of the 3d vector is 1 return ossimColumnVector3d( (lhs.theData[0][0]*rhs[0] + lhs.theData[0][1]*rhs[1] + lhs.theData[0][2]*rhs[2] + lhs.theData[0][3]), (lhs.theData[1][0]*rhs[0] + lhs.theData[1][1]*rhs[1] + lhs.theData[1][2]*rhs[2] + lhs.theData[1][3]), (lhs.theData[2][0]*rhs[0] + lhs.theData[2][1]*rhs[1] + lhs.theData[2][2]*rhs[2] + lhs.theData[2][3])); } ossimColumnVector4d rotateOnly(const ossimColumnVector4d& rhs)const { // multiply only by the 3x3 submatrix. return ossimColumnVector4d( (theData[0][0]*rhs[0] + theData[0][1]*rhs[1] + theData[0][2]*rhs[2]), (theData[1][0]*rhs[0] + theData[1][1]*rhs[1] + theData[1][2]*rhs[2]), (theData[2][0]*rhs[0] + theData[2][1]*rhs[1] + theData[2][2]*rhs[2])); } ossimColumnVector3d rotateOnly(const ossimColumnVector3d& rhs)const { // assume the 4 coordinate (homogeneous coord) of the 3d vector is 1 return ossimColumnVector3d( (theData[0][0]*rhs[0] + theData[0][1]*rhs[1] + theData[0][2]*rhs[2]), (theData[1][0]*rhs[0] + theData[1][1]*rhs[1] + theData[1][2]*rhs[2]), (theData[2][0]*rhs[0] + theData[2][1]*rhs[1] + theData[2][2]*rhs[2])); } ossimMatrix4x4 operator*(double scalar)const { return ossimMatrix4x4(theData[0][0]*scalar, theData[0][1]*scalar, theData[0][2]*scalar, theData[0][3]*scalar, theData[1][0]*scalar, theData[1][1]*scalar, theData[1][2]*scalar, theData[1][3]*scalar, theData[2][0]*scalar, theData[2][1]*scalar, theData[2][2]*scalar, theData[2][3]*scalar, theData[0][0]*scalar, theData[0][1]*scalar, theData[0][2]*scalar, theData[0][3]*scalar); } ossimMatrix4x4 operator*(const ossimMatrix4x4& rhs)const { ossimMatrix4x4 m; // element 0,0 is first row time first column m.theData[0][0] = (theData[0][0]*rhs.theData[0][0] + theData[0][1]*rhs.theData[1][0] + theData[0][2]*rhs.theData[2][0] + theData[0][3]*rhs.theData[3][0]); // element 0, 1 is first row second column m.theData[0][1] = (theData[0][0]*rhs.theData[0][1] + theData[0][1]*rhs.theData[1][1] + theData[0][2]*rhs.theData[2][1] + theData[0][3]*rhs.theData[3][1]); // element 0, 2 is first row third column m.theData[0][2] = (theData[0][0]*rhs.theData[0][2] + theData[0][1]*rhs.theData[1][2] + theData[0][2]*rhs.theData[2][2] + theData[0][3]*rhs.theData[3][2]); // element 0, 3 is first row fourth column m.theData[0][3] = (theData[0][0]*rhs.theData[0][3] + theData[0][1]*rhs.theData[1][3] + theData[0][2]*rhs.theData[2][3] + theData[0][3]*rhs.theData[3][3]); // element 1, 0 is second row first column m.theData[1][0] = (theData[1][0]*rhs.theData[0][0] + theData[1][1]*rhs.theData[1][0] + theData[1][2]*rhs.theData[2][0] + theData[1][3]*rhs.theData[3][0]); // element 1, 1 is second row second column m.theData[1][1] = (theData[1][0]*rhs.theData[0][1] + theData[1][1]*rhs.theData[1][1] + theData[1][2]*rhs.theData[2][1] + theData[1][3]*rhs.theData[3][1]); // element 1, 2 is second row third column m.theData[1][2] = (theData[1][0]*rhs.theData[0][2] + theData[1][1]*rhs.theData[1][2] + theData[1][2]*rhs.theData[2][2] + theData[1][3]*rhs.theData[3][2]); // element 1, 3 is second row fourth column m.theData[1][3] = (theData[1][0]*rhs.theData[0][3] + theData[1][1]*rhs.theData[1][3] + theData[1][2]*rhs.theData[2][3] + theData[1][3]*rhs.theData[3][3]); // element 2, 0 is third row first column m.theData[2][0] = (theData[2][0]*rhs.theData[0][0] + theData[2][1]*rhs.theData[1][0] + theData[2][2]*rhs.theData[2][0] + theData[2][3]*rhs.theData[3][0]); // element 2, 1 is third row second column m.theData[2][1] = (theData[2][0]*rhs.theData[0][1] + theData[2][1]*rhs.theData[1][1] + theData[2][2]*rhs.theData[2][1] + theData[2][3]*rhs.theData[3][1]); // element 2, 2 is third row third column m.theData[2][2] = (theData[2][0]*rhs.theData[0][2] + theData[2][1]*rhs.theData[1][2] + theData[2][2]*rhs.theData[2][2] + theData[2][3]*rhs.theData[3][2]); // element 2, 3 is third row fourth column m.theData[2][3] = (theData[2][0]*rhs.theData[0][3] + theData[2][1]*rhs.theData[1][3] + theData[2][2]*rhs.theData[2][3] + theData[2][3]*rhs.theData[3][3]); // element 3, 0 is fourth row first column m.theData[3][0] = (theData[3][0]*rhs.theData[0][0] + theData[3][1]*rhs.theData[1][0] + theData[3][2]*rhs.theData[2][0] + theData[3][3]*rhs.theData[3][0]); // element 3, 1 is fourth row second column m.theData[3][1] = (theData[3][0]*rhs.theData[0][1] + theData[3][1]*rhs.theData[1][1] + theData[3][2]*rhs.theData[2][1] + theData[3][3]*rhs.theData[3][1]); // element 3, 2 is fourth row third column m.theData[3][2] = (theData[3][0]*rhs.theData[0][2] + theData[3][1]*rhs.theData[1][2] + theData[3][2]*rhs.theData[2][2] + theData[3][3]*rhs.theData[3][2]); // element 3, 3 is fourth row fourth column m.theData[3][3] = (theData[3][0]*rhs.theData[0][3] + theData[3][1]*rhs.theData[1][3] + theData[3][2]*rhs.theData[2][3] + theData[3][3]*rhs.theData[3][3]); return m; } /*! * uses the matrix package to compute the inverse */ ossimMatrix4x4& i() { theData = theData.i(); return *this; } /*! * Uses the matrix package to compute the transpose. */ ossimMatrix4x4& t() { theData = theData.t(); return *this; } /*! * uses the matrix package to compute the determinant */ double getDeterminant()const { return theData.Determinant(); } /*! * Uses the matrix package to compute the eigenvalues for this * matrix */ ossimColumnVector3d getEigenValues()const; bool isEqualTo(const ossimMatrix4x4& rhs, ossimCompareType compareType=OSSIM_COMPARE_FULL)const; void setZero(); void setIdentity(); static NEWMAT::Matrix createIdentity(); static NEWMAT::Matrix createRotateOnly(const ossimMatrix4x4& aMatrix); static NEWMAT::Matrix createZero(); static NEWMAT::Matrix createTranslationMatrix(double x, double y, double z); static NEWMAT::Matrix createRotationMatrix(double angleX, double angleY, double angleZ, ossimCoordSysOrientMode orientationMode=OSSIM_RIGHT_HANDED); static NEWMAT::Matrix createRotationXMatrix(double angle, ossimCoordSysOrientMode orientationMode=OSSIM_RIGHT_HANDED); static NEWMAT::Matrix createRotationYMatrix(double angle, ossimCoordSysOrientMode orientationMode=OSSIM_RIGHT_HANDED); static NEWMAT::Matrix createRotationZMatrix(double angle, ossimCoordSysOrientMode orientationMode=OSSIM_RIGHT_HANDED); static NEWMAT::Matrix createScaleMatrix(double X, double Y, double Z); const NEWMAT::Matrix& getData()const{return theData;} NEWMAT::Matrix& getData(){return theData;} private: NEWMAT::Matrix theData; }; // class OSSIM_DLL ossimMatrix4x4 inline bool ossimMatrix4x4::isEqualTo(const ossimMatrix4x4& rhs, ossimCompareType /* compareType */)const { return (ossim::almostEqual(theData[0][0], rhs.theData[0][0])&& ossim::almostEqual(theData[0][1], rhs.theData[0][1])&& ossim::almostEqual(theData[0][2], rhs.theData[0][2])&& ossim::almostEqual(theData[0][3], rhs.theData[0][3])&& ossim::almostEqual(theData[1][0], rhs.theData[1][0])&& ossim::almostEqual(theData[1][1], rhs.theData[1][1])&& ossim::almostEqual(theData[1][2], rhs.theData[1][2])&& ossim::almostEqual(theData[1][3], rhs.theData[1][3])&& ossim::almostEqual(theData[2][0], rhs.theData[2][0])&& ossim::almostEqual(theData[2][1], rhs.theData[2][1])&& ossim::almostEqual(theData[2][2], rhs.theData[2][2])&& ossim::almostEqual(theData[2][3], rhs.theData[2][3])&& ossim::almostEqual(theData[3][0], rhs.theData[3][0])&& ossim::almostEqual(theData[3][1], rhs.theData[3][1])&& ossim::almostEqual(theData[3][2], rhs.theData[3][2])&& ossim::almostEqual(theData[3][3], rhs.theData[3][3])); } #endif /* #ifndef ossimMatrix4x4_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimMatrixProperty.h000066400000000000000000000047631352751253100236510ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimMatrixProperty.h 17074 2010-04-14 18:49:11Z dburken $ #ifndef ossimMatrixProperty_HEADER #define ossimMatrixProperty_HEADER #include #include class OSSIMDLLEXPORT ossimMatrixProperty : public ossimProperty { public: ossimMatrixProperty(const ossimString& name=ossimString(""), const std::vector& values = std::vector(), int numberOfRows = 0, int numberOfColumns = 0); ossimMatrixProperty(const ossimMatrixProperty& rhs); virtual ~ossimMatrixProperty(); virtual ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; void resize(int numberOfRows, int numberOfColumns); double& operator ()(int rowIdx, int colIdx); const double& operator()(int rowIdx, int colIdx)const; int getNumberOfRows()const; int getNumberOfCols()const; void clearConstraints(); /*! * If any of the constraints are set to something < 0 then it means there * isn't a constraint for that value. So if you give a min value of -1 * and a max value of 10 then the column can grow from 10 downto 0. */ void setColConstraints(int minNumberOfColumns, int maxNumberOfColumns); /*! * If any of the contraints are set to something < 0 then it means there * isn't a constraint for that value. So if you give a min value of -1 * and a max value of 10 then the row can grow from 10 downto 0. */ void setRowConstraints(int minNumberOfRows, int maxNumberOfRows); void getColConstraints(int& minNumberOfColumns, int& maxNumberOfColumns) const; void getRowConstraints(int& minNumberOfRows, int& maxNumberOfRows) const; void normalize(); void zero(); protected: std::vector< std::vector > theValueArray; int theMinNumberOfCols; int theMaxNumberOfCols; int theMinNumberOfRows; int theMaxNumberOfRows; double density()const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimMetadataInterface.h000066400000000000000000000022511352751253100241670ustar00rootroot00000000000000//---------------------------------------------------------------------------- // File: ossimFileProcessorInterface.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class interface ossimMetadataInterface. // // Has pure virtual "addMetadata" method that derived classes must // implement to be concrete. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimMetadataInterface_HEADER #define ossimMetadataInterface_HEADER 1 #include class ossimKeywordlist; /** @class ossimMetadataInterface */ class ossimMetadataInterface { public: /** @brief default constructor */ ossimMetadataInterface(){} /** @brief virtual destructor. */ virtual ~ossimMetadataInterface(){} /** * @brief Pure virtual addMetadata method. Derived classed must implement. * @param kwl Initialized by this. * @param prefix e.g. "image0." (can be empty) */ virtual void addMetadata( ossimKeywordlist* kwl, const std::string& prefix ) const = 0; }; #endif /* #ifndef ossimMetadataInterface_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimMouseEvent.h000066400000000000000000000061321352751253100227220ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimMouseEvent.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimMouseEvent_HEADER #define ossimMouseEvent_HEADER #include #include class OSSIMDLLEXPORT ossimMouseEvent : public ossimEvent { public: ossimMouseEvent(const ossimDpt& scenePoint=ossimDpt(0,0), const ossimDpt& relViewPoint=ossimDpt(0,0), ossimObject* object = NULL, long id = OSSIM_MOUSE_EVENT_ID, long mouseType = 0) :ossimEvent(object, id), theScenePoint(scenePoint), theRelViewPoint(relViewPoint), theMouseType(mouseType) { } virtual ossimObject* dup()const{return new ossimMouseEvent(*this);} bool controlDown() const { return theControlKeyDown; } bool altDown() const { return theAltKeyDown; } bool shiftDown() const { return theShiftKeyDown; } // Find which event was just generated bool leftDown() const{ return (theMouseType == OSSIM_MOUSE_EVENT_LEFT_DOWN_ID); } bool middleDown() const{ return (theMouseType == OSSIM_MOUSE_EVENT_MIDDLE_DOWN_ID); } bool rightDown() const{ return (theMouseType == OSSIM_MOUSE_EVENT_RIGHT_DOWN_ID); } bool leftUp() const{ return (theMouseType == OSSIM_MOUSE_EVENT_LEFT_UP_ID); } bool middleUp() const{ return (theMouseType == OSSIM_MOUSE_EVENT_MIDDLE_UP_ID); } bool rightUp() const{ return (theMouseType == OSSIM_MOUSE_EVENT_RIGHT_UP_ID); } bool leftDClick() const { return (theMouseType == OSSIM_MOUSE_EVENT_LEFT_DCLICK_ID); } bool middleDClick() const { return (theMouseType == OSSIM_MOUSE_EVENT_MIDDLE_DCLICK_ID); } bool rightDClick() const { return (theMouseType == OSSIM_MOUSE_EVENT_RIGHT_DCLICK_ID); } // Find the current state of the mouse buttons (regardless // of current event type) bool leftIsDown() const { return theLeftDown; } bool middleIsDown() const { return theMiddleDown; } bool rightIsDown() const { return theRightDown; } // True if a button is down and the mouse is moving bool dragging() const { return (moving() && (leftIsDown() || middleIsDown() || rightIsDown())); } // True if the mouse is moving, and no button is down bool moving() const { return (theMouseType == OSSIM_MOUSE_EVENT_MOTION_ID); } // True if the mouse is just entering the window bool entering() const { return (theMouseType == OSSIM_MOUSE_EVENT_ENTER_WINDOW_ID); } // True if the mouse is just leaving the window bool leaving() const { return (theMouseType == OSSIM_MOUSE_EVENT_LEAVE_WINDOW_ID); } ossimDpt theScenePoint; ossimDpt theRelViewPoint; int theMouseType; bool theAltKeyDown; bool theControlKeyDown; bool theShiftKeyDown; bool theLeftDown; bool theRightDown; bool theMiddleDown; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimMouseListener.h000066400000000000000000000014341352751253100234260ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimMouseListener.h 17195 2010-04-23 17:32:18Z dburken $ #ifndef ossimMouseListener_HEADER #define ossimMouseListener_HEADER #include #include class OSSIMDLLEXPORT ossimMouseListener : public ossimListener { public: ossimMouseListener():ossimListener(){} virtual ~ossimMouseListener(){} virtual void processEvent(ossimEvent& event); /*! * processes all mouse events */ virtual void mouseEvent(ossimMouseEvent& /* event */) {} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimMultiBandHistogram.h000066400000000000000000000057601352751253100243730ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimMultiBandHistogram.h 17205 2010-04-24 18:10:01Z dburken $ #ifndef ossimMultiBandHistogram_HEADER #define ossimMultiBandHistogram_HEADER #include #include #include #include #include #include #include class ossimKeywordlist; class ossimImageSource; class OSSIMDLLEXPORT ossimMultiBandHistogram : public ossimReferenced { public: ossimMultiBandHistogram(); ossimMultiBandHistogram(const ossimMultiBandHistogram& rhs); ossimMultiBandHistogram(ossim_int32 numberOfBands, ossim_int32 numberOfBuckets, float minValue, float maxValue, float nullValue, ossimScalarType scalar); void create(const ossimImageSource* input); void create(ossim_int32 numberOfBands, ossim_int32 numberOfBuckets, float minValue, float maxValue, float nullValue, ossimScalarType scalar); ossim_uint32 getNumberOfBands() const; void create(ossim_int32 numberOfBands); void setBinCount(double binNumber, double count); ossimRefPtr getHistogram(ossim_int32 band); const ossimRefPtr getHistogram(ossim_int32 band)const; ossimRefPtr createAccumulationLessThanEqual()const; ossimRefPtr createAccumulationGreaterThanEqual()const; /*! * Imports a text file that has histogram data */ virtual bool importHistogram(const ossimFilename& inputFile); virtual bool importHistogram(std::istream& in); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; virtual bool saveState(ossimRefPtr xmlNode)const; virtual bool loadState(const ossimRefPtr xmlNode); protected: virtual ~ossimMultiBandHistogram(); class ossimProprietaryHeaderInformation { public: ossimProprietaryHeaderInformation(){clear();} bool parseStream(std::istream& in); ossim_uint32 getNumberOfBands() const; void clear(); ossimString theFileType; ossimString theVersion; ossimString theNumberOfBands; }; /*! * Holds the histograms for each band */ std::vector > theHistogramList; void deleteHistograms(); bool parseProprietaryHistogram(std::istream& in); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimMultiResLevelHistogram.h000066400000000000000000000071341352751253100252450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimMultiResLevelHistogram.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimMultiResLevelHistogram_HEADER #define ossimMultiResLevelHistogram_HEADER #include #include #include #include #include #include #include class OSSIMDLLEXPORT ossimMultiResLevelHistogram : public ossimReferenced { public: ossimMultiResLevelHistogram(); ossimMultiResLevelHistogram(ossim_uint32 numberOfResLevels); ossimMultiResLevelHistogram(const ossimMultiResLevelHistogram& rhs); virtual ~ossimMultiResLevelHistogram(); ossimRefPtr getHistogram(ossim_uint32 band, ossim_uint32 resLevel=0); const ossimRefPtr getHistogram(ossim_uint32 band, ossim_uint32 resLevel=0)const; ossim_uint32 getNumberOfResLevels()const; ossim_uint32 getNumberOfBands(ossim_uint32 resLevel=0) const; void create(ossim_uint32 numberOfResLevels); ossimRefPtr getMultiBandHistogram(ossim_uint32 resLevel) const; ossimRefPtr createAccumulationLessThanEqual()const; ossimRefPtr createAccumulationGreaterThanEqual()const; void setBinCount(double binNumber, double count); /*! * Will append to the list the passed in histogram. */ virtual void addHistogram(ossimMultiBandHistogram* histo); /*! * This will create and append a histogram to the * list and return a pointer to the new histogram. */ virtual ossimRefPtr addHistogram(); /*! * Will set the histogram to the passed in res level. * It will delete the histogram at the res level before * setting the pointer to the passed in histogram. if * the resLevel is out of range it will return false meaning * it was unable to assign the pointer. */ virtual bool setHistogram(ossimRefPtr histo, ossim_uint32 resLevel); virtual ossimFilename getHistogramFile() const; virtual bool importHistogram(const ossimFilename& inputFile); virtual bool importHistogram(std::istream& in); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: class ossimProprietaryHeaderInformation { public: ossimProprietaryHeaderInformation(){clear();} bool parseStream(std::istream& in); ossim_uint32 getNumberOfResLevels() { return theNumberOfResLevels.toUInt32(); } void clear() { theFileType = ""; theVersion = ""; theCreatorId = ""; theNumberOfResLevels = ""; } ossimString theFileType; ossimString theVersion; ossimString theCreatorId; ossimString theNumberOfResLevels; }; std::vector > theHistogramList; ossimFilename theHistogramFile; void deleteHistograms(); bool parseProprietaryHistogram(std::istream& in); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimNBandLutDataObject.h000066400000000000000000000330611352751253100242210ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // LICENSE: MIT See top level license file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimNBandLutDataObject.h 19732 2011-06-06 22:24:54Z dburken $ #ifndef ossimNBandLutDataObject_HEADER #define ossimNBandLutDataObject_HEADER 1 #include #include #include #include /** * class ossimNBandLutDataObject * * Sample CADRG LUT taken from an arbitrary CADRG image entry. This is a keywordlist * support by the loadstate of this class. * *
 * entry0:  25 39 116 
 * entry1:  245 242 242 
 * entry10:  92 89 115 
 * entry100:  74 55 85 
 * entry101:  233 165 53 
 * entry102:  75 2 4 
 * entry103:  162 118 42 
 * entry104:  233 159 130 
 * entry105:  189 129 40 
 * entry106:  154 109 66 
 * entry107:  145 97 85 
 * entry108:  121 86 31 
 * entry109:  238 151 118 
 * entry11:  52 31 76 
 * entry110:  239 167 42 
 * entry111:  236 137 100 
 * entry112:  179 112 88 
 * entry113:  92 37 33 
 * entry114:  121 66 24 
 * entry115:  120 133 151 
 * entry116:  76 92 192 
 * entry117:  36 50 117 
 * entry118:  57 75 191 
 * entry119:  125 45 50 
 * entry12:  235 217 204 
 * entry120:  102 65 81 
 * entry121:  172 148 199 
 * entry122:  204 145 95 
 * entry123:  81 19 5 
 * entry124:  91 4 1 
 * entry125:  109 54 31 
 * entry126:  137 114 118 
 * entry127:  230 150 52 
 * entry128:  82 38 87 
 * entry129:  190 120 76 
 * entry13:  244 218 172 
 * entry130:  170 109 45 
 * entry131:  95 20 22 
 * entry132:  150 80 61 
 * entry133:  225 122 82 
 * entry134:  122 37 16 
 * entry135:  146 88 49 
 * entry136:  122 94 122 
 * entry137:  230 135 63 
 * entry138:  137 73 75 
 * entry139:  119 46 29 
 * entry14:  189 167 141 
 * entry140:  190 142 128 
 * entry141:  242 216 187 
 * entry142:  176 125 95 
 * entry143:  193 117 143 
 * entry144:  19 0 0 
 * entry145:  12 1 42 
 * entry146:  24 4 26 
 * entry147:  38 40 52 
 * entry148:  8 24 175 
 * entry149:  40 23 45 
 * entry15:  245 213 142 
 * entry150:  39 11 58 
 * entry151:  10 0 22 
 * entry152:  236 148 41 
 * entry153:  101 41 11 
 * entry154:  230 113 67 
 * entry155:  148 44 46 
 * entry156:  225 144 133 
 * entry157:  115 2 13 
 * entry158:  159 79 49 
 * entry159:  164 95 33 
 * entry16:  246 241 205 
 * entry160:  97 6 22 
 * entry161:  175 90 133 
 * entry162:  112 23 20 
 * entry163:  105 22 6 
 * entry164:  148 59 33 
 * entry165:  215 118 104 
 * entry166:  211 122 41 
 * entry167:  233 129 34 
 * entry168:  153 73 25 
 * entry169:  208 102 39 
 * entry17:  240 215 89 
 * entry170:  206 101 133 
 * entry171:  229 113 96 
 * entry172:  127 16 25 
 * entry173:  224 104 28 
 * entry174:  171 76 74 
 * entry175:  221 94 78 
 * entry176:  229 86 94 
 * entry177:  213 80 57 
 * entry178:  161 44 36 
 * entry179:  155 54 19 
 * entry18:  115 92 157 
 * entry180:  130 25 5 
 * entry181:  150 29 24 
 * entry182:  198 54 34 
 * entry183:  224 61 70 
 * entry184:  213 82 37 
 * entry185:  186 28 31 
 * entry186:  200 64 15 
 * entry187:  110 2 2 
 * entry188:  195 38 12 
 * entry189:  151 6 8 
 * entry19:  160 163 37 
 * entry190:  193 13 10 
 * entry191:  205 1 3 
 * entry192:  44 62 193 
 * entry193:  35 14 16 
 * entry194:  15 30 118 
 * entry195:  28 47 189 
 * entry196:  25 3 80 
 * entry197:  7 16 118 
 * entry198:  33 10 6 
 * entry199:  39 24 95 
 * entry2:  216 212 237 
 * entry20:  38 29 21 
 * entry200:  82 58 159 
 * entry201:  55 29 142 
 * entry202:  33 4 23 
 * entry203:  17 14 36 
 * entry204:  58 26 41 
 * entry205:  11 13 14 
 * entry206:  74 87 85 
 * entry207:  50 60 41 
 * entry208:  119 123 98 
 * entry209:  193 187 172 
 * entry21:  208 202 156 
 * entry210:  124 126 128 
 * entry211:  47 68 84 
 * entry212:  110 119 60 
 * entry213:  63 145 121 
 * entry214:  154 166 147 
 * entry215:  107 156 104 
 * entry22:  242 202 152 
 * entry23:  168 148 140 
 * entry24:  31 22 25 
 * entry25:  245 205 114 
 * entry26:  245 191 137 
 * entry27:  175 161 172 
 * entry28:  17 6 11 
 * entry29:  172 170 137 
 * entry3:  247 230 113 
 * entry30:  51 27 20 
 * entry31:  239 210 73 
 * entry32:  185 176 129 
 * entry33:  35 2 13 
 * entry34:  60 52 51 
 * entry35:  101 78 70 
 * entry36:  141 124 101 
 * entry37:  206 184 107 
 * entry38:  244 174 106 
 * entry39:  82 98 136 
 * entry4:  246 231 132 
 * entry40:  190 191 239 
 * entry41:  241 188 161 
 * entry42:  67 51 38 
 * entry43:  244 184 122 
 * entry44:  211 201 142 
 * entry45:  61 27 16 
 * entry46:  182 182 82 
 * entry47:  243 188 87 
 * entry48:  86 83 60 
 * entry49:  61 40 43 
 * entry5:  204 198 166 
 * entry50:  146 141 93 
 * entry51:  44 4 4 
 * entry52:  231 210 51 
 * entry53:  85 74 39 
 * entry54:  197 169 127 
 * entry55:  182 151 60 
 * entry56:  121 98 73 
 * entry57:  243 182 145 
 * entry58:  58 18 21 
 * entry59:  241 157 91 
 * entry6:  2 0 2 
 * entry60:  59 4 1 
 * entry61:  155 162 223 
 * entry62:  154 133 80 
 * entry63:  73 21 16 
 * entry64:  195 183 116 
 * entry65:  76 51 29 
 * entry66:  234 181 63 
 * entry67:  58 59 98 
 * entry68:  42 22 79 
 * entry69:  134 143 219 
 * entry7:  204 204 239 
 * entry70:  106 117 205 
 * entry71:  48 65 117 
 * entry72:  63 54 117 
 * entry73:  125 93 62 
 * entry74:  137 138 41 
 * entry75:  104 68 59 
 * entry76:  113 99 41 
 * entry77:  76 30 11 
 * entry78:  239 184 48 
 * entry79:  161 129 98 
 * entry8:  31 4 66 
 * entry80:  241 170 126 
 * entry81:  145 109 105 
 * entry82:  207 163 116 
 * entry83:  79 41 40 
 * entry84:  175 138 41 
 * entry85:  10 0 56 
 * entry86:  180 151 77 
 * entry87:  72 12 24 
 * entry88:  242 154 105 
 * entry89:  91 26 15 
 * entry9:  246 238 162 
 * entry90:  160 118 53 
 * entry91:  228 166 141 
 * entry92:  231 160 69 
 * entry93:  61 2 11 
 * entry94:  132 83 60 
 * entry95:  86 46 24 
 * entry96:  243 143 86 
 * entry97:  108 60 46 
 * entry98:  109 76 38 
 * entry99:  96 86 84 
 * null_value:  -1
 * number_bands:  3
 * number_entries:  216
 * scalar_type:  ossim_uint8
 * type:  ossimNBandLutDataObject
 *
 *
 * NOTES:
 * 
 * - The null_value keyword above is the index in the lut that correspnds to an invalid pixel value.
 * - Each entry will have number_bands.  SO if number of bands is 3 then there will be 3 values
 *   Where the first value is for band 1, ... etc.
 * - scalar_type is a hint as to the scalar type of the entries.  Is the resulting lut for 8 bit, 16 bit , etc data.
 * - You should always use the LUT_ENTRY_TYPE when getting values from the lut.  This value could change to an
 *   ossim_float32 precision and if you use the LUT_ENTRY_TYPE then your code will not have to change.
 *   
 * 
*/ class OSSIM_DLL ossimNBandLutDataObject : public ossimObject { public: typedef ossim_int32 LUT_ENTRY_TYPE; friend std::ostream& operator <<(std::ostream& out, const ossimNBandLutDataObject& lut); /*! * Will allocate 256 values for the color table */ ossimNBandLutDataObject(ossim_uint32 numberOfEntries=0, ossim_uint32 numberOfBands=0, ossimScalarType bandScalarType = OSSIM_UINT8, ossim_int32 nullPixelIndex=-1); ossimNBandLutDataObject(const ossimNBandLutDataObject& lut); ossimObject* dup()const { return new ossimNBandLutDataObject(*this); } void create(ossim_uint32 numberOfEntries, ossim_uint32 numberOfBands=3); const LUT_ENTRY_TYPE* operator[](ossim_uint32 idx)const { if(theLut) { return &theLut[idx*theNumberOfBands]; } return 0; } LUT_ENTRY_TYPE* operator[](ossim_uint32 idx) { if(theLut) { return &theLut[idx*theNumberOfBands]; } return 0; } const LUT_ENTRY_TYPE* operator[](ossim_int32 idx)const { if(theLut) { return &theLut[idx*theNumberOfBands]; } return 0; } LUT_ENTRY_TYPE* operator[](ossim_int32 idx) { if(theLut) { return &theLut[idx*theNumberOfBands]; } return 0; } const LUT_ENTRY_TYPE* operator[](double normalizedIndex)const { int idx = int(normalizedIndex*theNumberOfEntries); if (idx < 0) { idx = 0; } return (*this)[idx]; } /** * @param normalizedIndex If a double precision value is passed in then it is * assumed to be in normalized space where the value ranges from 0.0 to 1.0 * @return the starting address of the band values. */ LUT_ENTRY_TYPE* operator[](double normalizedIndex) { ossim_uint32 idx = int(normalizedIndex*(theNumberOfEntries-1)); if (idx >= theNumberOfEntries) { idx = theNumberOfEntries-1; } return (*this)[idx]; } bool hasNullPixelIndex()const { return (theNullPixelIndex >= 0); } /** * Will return the min max value for a given band * * @param band band number to query. This is 0 based so the first band * is indicated by the value of 0. * @param minValue is the minimum value returned for the passed in band * @param maxValue is the maximum value returned for the passed in band */ void getMinMax(ossim_uint32 band, LUT_ENTRY_TYPE& minValue, LUT_ENTRY_TYPE& maxValue); /** * @return First index with alpha of 0 or -1 if not found or there is no alpha. * * Currently only works on 4 band data. May consider adding an alpha channel * class data member in the future. */ ossim_int32 getFirstNullAlphaIndex() const; /** * Allows you to specify which entry is to be designated as an invalid * entry. Note: setting this to -1 indicates no null entry is set. * * @param idx is the entry number that will be used for the null value */ void setNullPixelIndex(ossim_int32 idx){theNullPixelIndex = idx;} /** * @return Return either a positive value indicating the entry designated for * a null pixel value or a -1 to say no null pixel has been designated * yet. */ ossim_int32 getNullPixelIndex()const{return theNullPixelIndex;} /** * @return Return the number of bands this lut is indexed for. */ ossim_uint32 getNumberOfBands()const{return theNumberOfBands;} /** * @return Return the number of entries in the lut. */ ossim_uint32 getNumberOfEntries()const{return theNumberOfEntries;} /** * This method gives you a way to find an entry index closest to the passed in * band values. * * @param values Is an array of band values. This array must be equal to the number * of bands for the lut. * @return Returns the nearest index to the passed in value. */ ossim_uint32 findIndex(ossim_int32* values) const; /** * @brief This method gives you a way to find an entry index closest to the * passed in band values. * * @param values Is an array of band values. * @param size Size of values array. Note if size is less than the LUT * number of bands, the trailing bands get dropped. This allows finding * an index dropping the alpha channel. * * @return Returns the nearest index to the passed in value. */ ossim_uint32 findIndex(ossim_int32* values, ossim_uint32 size) const; /** * Will do a simple memset to '\0' all */ void clearLut(); /** * does a deep copy from the passed in lut to the object. * * @param lut The lut to copy. */ const ossimNBandLutDataObject& operator =(const ossimNBandLutDataObject& lut); /** * Determines if the state of this lut is identical to the passed in lut * * @param lut Checks equality of the this object to the lut parameter. * @return True if equal and false otherwise */ bool operator ==(const ossimNBandLutDataObject& lut)const; /** * Reads in an external lut file. The external file is in a keywordlist format specified by the saveState. */ bool open(const ossimFilename& lutFile); /** *
    * 
    * Keywords:
    *  
    * entry0:
    * entry1:
    * :
    * entry:
    * null_value:  -1
    * number_bands:  3
    * number_entries:  216
    * scalar_type:  ossim_uint8
    * type:  ossimNBandLutDataObject
    *
    * Where entry is repeasted for each entry number where idx start from 0 and goes to number_entries-1
    * each entry must have number_bands values.
    * 
* * @param kwl The keyword list to store the keywords to. Each keyword could be prefixed by an optional * prefix parameter. * @param prefix The optional prefix parameter used to prefix each keyword. * */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; std::vector getEntryLabels(ossim_uint32 band); void setEntryLables(ossim_uint32 band, std::vector entryLabels); /** * Loads the state of the object by reading in the keywords listed in the save state. * * @param kwl The keywordlist to extract the classes keywords from to restore its state. * @param prefix Optional prefix value used to prefix each keyword. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimNBandLutDataObject(); LUT_ENTRY_TYPE *theLut; ossim_uint32 theNumberOfEntries; ossim_uint32 theNumberOfBands; ossimScalarType theBandScalarType; ossim_int32 theNullPixelIndex; std::map > m_entryLabels; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimNadconGridDatum.h000066400000000000000000000023771352751253100236420ustar00rootroot00000000000000#ifndef ossimNadconGridDatum_HEADER #define ossimNadconGridDatum_HEADER 1 #include #include #include #include class OSSIM_DLL ossimNadconGridDatum : public ossimThreeParamDatum { public: ossimNadconGridDatum(const ossimFilename& datumDirectory, const ossimString &code, const ossimString &name, const ossimEllipsoid* anEllipsoid, double sigmaX, double sigmaY, double sigmaZ, double westLongitude, double eastLongitude, double southLatitude, double northLatitude, double param1, double param2, double param3); protected: mutable ossimDrect theConusRect; mutable ossimDrect theHawaiiRect; mutable ossimDrect theAlaskaRect; mutable ossimDrect theStGeorgeRect; mutable ossimDrect theLatStLaurenceRect; mutable ossimDrect theStPaulRect; mutable ossimDrect thePrviRect; mutable ossimNadconGridFile theLatGrid; mutable ossimNadconGridFile theLonGrid; mutable ossimDrect theCurrentGridRect; ossimFilename theDatumDirectory; void checkGrid(const ossimDpt& latLon)const; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimNadconGridFile.h000066400000000000000000000024511352751253100234400ustar00rootroot00000000000000//************************************************************************** // Copyright (C) 2003 Storage Area Networks, Inc. // // Written by: Kenneth Melero // //************************************************************************** #ifndef ossimNadconGridFile_HEADER #define ossimNadconGridFile_HEADER 1 #include #include #include class OSSIM_DLL ossimNadconGridFile { public: ossimNadconGridFile() : theFileOkFlag(false) {} ~ossimNadconGridFile(); bool open(const ossimFilename& file); void close(); /*! */ double getShiftAtLatLon(double lat, double lon)const; bool pointWithin(double lat, double lon)const; const ossimDrect getBoundingRect()const { return theBoundingRect; } const ossimFilename& getFilename()const { return theFilename; } bool getFileOkFlag()const { return theFileOkFlag; } ossimDpt getSpacing()const { return theHeader.getSpacing(); } protected: mutable std::ifstream theInputFile; mutable bool theFileOkFlag; ossimFilename theFilename; ossimNadconGridHeader theHeader; ossimDrect theBoundingRect; ossimDpt theLatLonOrigin; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimNadconGridHeader.h000066400000000000000000000037041352751253100237530ustar00rootroot00000000000000//************************************************************************** // Copyright (C) 2003 Storage Area Networks, Inc. // // Written by: Kenneth Melero // //************************************************************************** #ifndef ossimNadconGridHeader_HEADER #define ossimNadconGridHeader_HEADER 1 #include #include #include #include class OSSIM_DLL ossimNadconGridHeader { public: friend OSSIM_DLL std::ostream& operator <<(std::ostream& out, const ossimNadconGridHeader& rhs); ossimNadconGridHeader() :theCols(0), theRows(0), theZ(0), theMinX(0), theDx(0), theMinY(0), theDy(0) { } bool readHeader(const ossimFilename& file); bool readHeader(std::istream& in); int getStartOffset()const { return (theCols+2)*4; } int getBytesPerRow()const { return (theCols+1)*4; } int getNumberOfRows()const { return theRows; } int getNumberOfCols()const { return theCols; } double getDeltaX()const { return (double)theDx; } double getDeltaY()const { return (double)theDy; } ossimDrect getBoundingRect()const { return ossimDrect(theMinX, theMinY + (theRows)*theDy, theMinX + (theCols)*theDx, theMinY, OSSIM_RIGHT_HANDED); } double getMinX()const { return theMinX; } double getMinY()const { return theMinY; } ossimDpt getSpacing()const { return ossimDpt(theDx, theDy); } protected: int* theCharBuf[64]; int theCols; int theRows; int theZ; double theMinX; double theDx; double theMinY; double theDy; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimNadconNarDatum.h000066400000000000000000000011271352751253100234650ustar00rootroot00000000000000#ifndef ossimNadconNarDatum_HEADER #define ossimNadconNarDatum_HEADER 1 #include #include class OSSIM_DLL ossimNadconNarDatum : public ossimNadconGridDatum { public: ossimNadconNarDatum(const ossimFilename& nadconDirectory); // Argument holds the source point and datum. Returns another // point with this datum. // virtual ossimGpt shift(const ossimGpt &aPt)const; //utility functions to shift to and from the standard coordinates. //Users should use the shift instead!!! // TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimNadconNasDatum.h000066400000000000000000000010131352751253100234600ustar00rootroot00000000000000#ifndef ossimNadconNasDatum_HEADER #define ossimNadconNasDatum_HEADER 1 #include #include #include class OSSIM_DLL ossimNadconNasDatum : public ossimNadconGridDatum { public: ossimNadconNasDatum(const ossimFilename& nadconDirectory); // Argument holds the source point and datum. Returns another // point with this datum. // virtual ossimGpt shift(const ossimGpt &aPt)const; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimNormRgbVector.h000066400000000000000000000067671352751253100233770ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // License: MIT // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimNormRgbVector.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNormRgbVector_HEADER #define ossimNormRgbVector_HEADER #include #include class ossimJpegYCbCrVector; class ossimHsiVector; class ossimHsvVector; class ossimCmyVector; class ossimRgbVector; class OSSIM_DLL ossimNormRgbVector { public: friend std::ostream& operator <<(std::ostream& out, const ossimNormRgbVector& data) { out << "<" << data.theBuf[0] << ", " << data.theBuf[1] << ", " << data.theBuf[2] << ">"; return out; } ossimNormRgbVector(ossim_float64 r=0, ossim_float64 g=0, ossim_float64 b=0) { theBuf[0] = r; theBuf[1] = g; theBuf[2] = b; } ossimNormRgbVector(ossim_float64 grey) { theBuf[0] = grey; theBuf[1] = grey; theBuf[2] = grey; } ossimNormRgbVector(ossim_float64 colorData[3]) { theBuf[0] = colorData[0]; theBuf[1] = colorData[1]; theBuf[2] = colorData[2]; } ossimNormRgbVector(const ossimNormRgbVector& rgb) { theBuf[0] = rgb.theBuf[0]; theBuf[1] = rgb.theBuf[1]; theBuf[2] = rgb.theBuf[2]; } ossimNormRgbVector(const ossimRgbVector& rgb); ossimNormRgbVector(const ossimJpegYCbCrVector& YCbCr); ossimNormRgbVector(const ossimHsiVector& hsi); ossimNormRgbVector(const ossimHsvVector& hsv); ossimNormRgbVector(const ossimCmyVector& cmy); ossimNormRgbVector operator -(const ossimNormRgbVector& rgb)const { return ossimNormRgbVector(clamp(theBuf[0] - rgb.theBuf[0]), clamp(theBuf[1] - rgb.theBuf[1]), clamp(theBuf[2] - rgb.theBuf[2])); } ossimNormRgbVector operator *(ossim_float64 t)const { return ossimNormRgbVector(clamp(theBuf[0]*t), clamp(theBuf[1]*t), clamp(theBuf[2]*t)); } const ossimNormRgbVector& operator =(const ossimJpegYCbCrVector& data); const ossimNormRgbVector& operator =(const ossimHsiVector& hsi); const ossimNormRgbVector& operator =(const ossimHsvVector& hsv); const ossimNormRgbVector& operator =(const ossimCmyVector& cmy); bool operator ==(const ossimNormRgbVector& rgb) { return ( (rgb.theBuf[0] == theBuf[0])&& (rgb.theBuf[1] == theBuf[1])&& (rgb.theBuf[2] == theBuf[2])); } bool operator !=(const ossimNormRgbVector& rgb) { return ( (rgb.theBuf[0] != theBuf[0])|| (rgb.theBuf[1] != theBuf[1])|| (rgb.theBuf[2] != theBuf[2])); } static ossim_float64 clamp(ossim_float64 colorValue, ossim_float64 min=0.0, ossim_float64 max=1.0) { colorValue = colorValue > max? max:colorValue; colorValue = colorValue < min? min:colorValue; return colorValue; } ossim_float64 getR() const { return theBuf[0]; } ossim_float64 getG()const { return theBuf[1]; } ossim_float64 getB()const { return theBuf[2]; } void setR(ossim_float64 r) { theBuf[0] = r; } void setG(ossim_float64 g) { theBuf[1] = g; } void setB(ossim_float64 b) { theBuf[2] = b; } protected: ossim_float64 theBuf[3]; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimNotify.h000066400000000000000000000062271352751253100221050ustar00rootroot00000000000000//------------------------------------------------------------------- // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class declaration for ossimNotify //------------------------------------------------------------------- // $Id: ossimNotify.h 23467 2015-08-14 13:59:09Z gpotts $ #ifndef ossimNotify_HEADER #define ossimNotify_HEADER 1 #include #include #include #include #include /** * Notification level enumeration. This specifies the * level of the mesage being written. */ enum ossimNotifyLevel { ossimNotifyLevel_ALWAYS = 0, ossimNotifyLevel_FATAL = 1, ossimNotifyLevel_WARN = 2, ossimNotifyLevel_NOTICE = 3, ossimNotifyLevel_INFO = 4, ossimNotifyLevel_DEBUG = 5 }; /** * Flags to allow the user to turn off certain notification levels * */ enum ossimNotifyFlags { ossimNotifyFlags_NONE = 0, ossimNotifyFlags_FATAL = 1, ossimNotifyFlags_WARN = 2, ossimNotifyFlags_NOTICE = 4, ossimNotifyFlags_INFO = 8, ossimNotifyFlags_DEBUG = 16, ossimNotifyFlags_ALL = (ossimNotifyFlags_FATAL| ossimNotifyFlags_WARN| ossimNotifyFlags_NOTICE| ossimNotifyFlags_INFO| ossimNotifyFlags_DEBUG) }; OSSIMDLLEXPORT void ossimSetDefaultNotifyHandlers(); OSSIMDLLEXPORT void ossimSetNotifyStream(std::ostream* outputStream, ossimNotifyFlags whichLevelsToRedirect=ossimNotifyFlags_ALL); OSSIMDLLEXPORT std::ostream* ossimGetNotifyStream(ossimNotifyLevel whichLevel); OSSIMDLLEXPORT bool ossimIsReportingEnabled(); OSSIMDLLEXPORT std::ostream& ossimNotify(ossimNotifyLevel level = ossimNotifyLevel_WARN); OSSIMDLLEXPORT void ossimNotify(ossimString msg, ossimNotifyLevel notifyLevel = ossimNotifyLevel_WARN); /** * */ OSSIMDLLEXPORT void ossimSetLogFilename(const ossimFilename& filename); /** @brief Returns the log filename if set. */ /* OSSIMDLLEXPORT const char* ossimGetLogFilename(); */ OSSIMDLLEXPORT void ossimGetLogFilename(ossimFilename& logFile); /** * */ OSSIMDLLEXPORT void ossimDisableNotify(ossimNotifyFlags notifyLevel=ossimNotifyFlags_ALL); /** * */ OSSIMDLLEXPORT void ossimEnableNotify(ossimNotifyFlags notifyLevel=ossimNotifyFlags_ALL); OSSIMDLLEXPORT void ossimSetNotifyFlag(ossimNotifyFlags notifyFlags); OSSIMDLLEXPORT void ossimPushNotifyFlags(); OSSIMDLLEXPORT void ossimPopNotifyFlags(); OSSIMDLLEXPORT ossimNotifyFlags ossimGetNotifyFlags(); /** * */ OSSIMDLLEXPORT void ossimSetError( const char *className, ossim_int32 error, const char *fmtString=0, ...); /** * This is for general warnings and information feedback * * @param fmtString a C printf() style formatting string used (with the * following arguments) to prepare an error message. */ OSSIMDLLEXPORT void ossimSetInfo( const char *className, const char *fmtString=0, ...); #endif /* #ifndef ossimNotify_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimNotifyContext.h000066400000000000000000000007351352751253100234500ustar00rootroot00000000000000//------------------------------------------------------------------- // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // NOTE: // // Depreciated header file. Please use ossim/base/ossimNotify.h // //------------------------------------------------------------------- // $Id: ossimNotifyContext.h 9372 2006-08-02 22:07:07Z dburken $ #ifndef ossimNotifyContext_HEADER #define ossimNotifyContext_HEADER #include #endif ossim-Miami-2.9.1/include/ossim/base/ossimNumericProperty.h000066400000000000000000000041231352751253100237750ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimNumericProperty.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimNumericProperty_HEADER #define ossimNumericProperty_HEADER #include class OSSIMDLLEXPORT ossimNumericProperty : public ossimProperty { public: enum ossimNumericPropertyType { ossimNumericPropertyType_INT = 0, ossimNumericPropertyType_UINT, ossimNumericPropertyType_FLOAT32, ossimNumericPropertyType_FLOAT64 }; ossimNumericProperty(const ossimString& name=ossimString(""), const ossimString& value=ossimString("0")); ossimNumericProperty(const ossimString& name, const ossimString& value, double minValue, double maxValue); ossimNumericProperty(const ossimNumericProperty& rhs); virtual ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); virtual bool hasConstraints()const; double getMinValue()const; double getMaxValue()const; virtual void clearConstraints(); virtual void setConstraints(double minValue, double maxValue); virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; virtual ossimNumericPropertyType getNumericType()const; virtual void setNumericType(ossimNumericPropertyType type); virtual ossim_float64 asFloat64()const; virtual ossim_float32 asFloat32()const; virtual ossim_uint32 asUInt32()const; virtual ossim_uint16 asUInt16()const; virtual ossim_uint8 asUInt8()const; virtual ossim_sint32 asInt32()const; virtual ossim_sint16 asInt16()const; virtual ossim_sint8 asInt8()const; protected: ossimString theValue; ossimNumericPropertyType theType; std::vector theRangeConstraint; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimObject.h000066400000000000000000000051261352751253100220400ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Base class for ossim objects. // //************************************************************************* // $Id: ossimObject.h 19852 2011-07-21 15:26:12Z gpotts $ #ifndef ossimObject_HEADER #define ossimObject_HEADER #include #include #include #include class ossimKeywordlist; class ossimString; class ossimVisitor; class OSSIMDLLEXPORT ossimObject : public ossimReferenced { public: ossimObject(); virtual ~ossimObject(); virtual ossimObject* dup() const; virtual ossimString getShortName() const; virtual ossimString getLongName() const; virtual ossimString getDescription() const; virtual ossimString getClassName() const; /*! * Will return the type of this class in an RTTI format. */ virtual RTTItypeid getType() const; virtual bool canCastTo(ossimObject* obj) const; virtual bool canCastTo(const RTTItypeid& id) const; /*! * Will use RTTI to search the derived classes to see if it derives from * the passed in type. If so then this object can be casted to the * passed in class name. */ virtual bool canCastTo(const ossimString& parentClassName) const; /*! * Method to save the state of the object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /*! * Method to the load (recreate) the state of the object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Generic print method. Derived classes should re-implement as they see * fit. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; /** * @note Since the print method is virtual, derived classes only need * to implement that, not an addition operator<<. */ friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& out, const ossimObject& obj); virtual bool isEqualTo(const ossimObject& obj, ossimCompareType compareType = OSSIM_COMPARE_FULL)const; virtual void accept(ossimVisitor& visitor); protected: TYPE_DATA }; #endif /* #ifndef ossimObject_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimObjectDestructingEvent.h000066400000000000000000000010011352751253100252420ustar00rootroot00000000000000#ifndef ossimObjectDestructingEvent_HEADER #define ossimObjectDestructingEvent_HEADER #include #include class ossimObject; class OSSIMDLLEXPORT ossimObjectDestructingEvent : public ossimEvent { public: ossimObjectDestructingEvent(ossimObject* objectDestructing=NULL) :ossimEvent(objectDestructing, OSSIM_EVENT_OBJECT_DESTRUCTING_ID) {} virtual ossimObject* dup()const{return new ossimObjectDestructingEvent(*this);} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimObjectEvents.h000066400000000000000000000004551352751253100232250ustar00rootroot00000000000000#ifndef ossimObjectEvents_HEADER #define ossimObjectEvents_HEADER #include #include #include #include #include #endif ossim-Miami-2.9.1/include/ossim/base/ossimObjectFactory.h000066400000000000000000000022421352751253100233640ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimObjectFactory.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimObjectFactory_HEADER #define ossimObjectFactory_HEADER #include #include class OSSIMDLLEXPORT ossimObjectFactory : public ossimObject { public: virtual ~ossimObjectFactory(){} /*! * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const=0; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const=0; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const=0; protected: TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimObjectFactoryRegistry.h000066400000000000000000000045061352751253100251220ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimObjectFactoryRegistry.h 22650 2014-02-28 14:39:20Z gpotts $ #ifndef ossimObjectFactoryRegistry_HEADER #define ossimObjectFactoryRegistry_HEADER #include #include #include #include class ossimKeywordlist; class ossimString; class OSSIMDLLEXPORT ossimObjectFactoryRegistry : public ossimObject, public ossimFactoryListInterface { public: virtual ~ossimObjectFactoryRegistry(); static ossimObjectFactoryRegistry* instance(); virtual ossimObject* createObject(const ossimString& name)const { return createObjectFromRegistry(name); } virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const { return createObjectFromRegistry(kwl, prefix); } /*! * Returns a type list of all objects that can be instantiated * through the createObjectMethods above. */ virtual void getTypeNameList(std::vector& typeList)const { getAllTypeNamesFromRegistry(typeList); } /*! * returns a list of objects that are of the passed in * base type. for example: * * If I want all ossimImageSource objects then I call: * * ossimObjectFactoryRegistry::instance()->getTypeNameList(l, * "ossimImageSource"); */ virtual void getTypeNameList(std::vector& typeList, const ossimString& baseType)const; protected: ossimObjectFactoryRegistry();//hide ossimObjectFactoryRegistry(const ossimObjectFactoryRegistry&):ossimObject(){}//hide void operator =(const ossimObjectFactoryRegistry&){}//hide // std::vector theFactoryList; // ossimObjectFactory* findFactory(ossimObjectFactory* factory)const; TYPE_DATA }; extern "C" { OSSIMDLLEXPORT void* ossimObjectFactoryRegistryGetInstance(); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimObservationSet.h000066400000000000000000000063351352751253100236040ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Storage class for observations. //---------------------------------------------------------------------------- #ifndef ossimObservationSet_HEADER #define ossimObservationSet_HEADER 1 #include #include #include #include #include #include #include #include #include class OSSIM_DLL ossimObservationSet : public ossimObject { public: ossimObservationSet(); ~ossimObservationSet(); inline ossim_uint32 numImages()const { return (ossim_uint32)theImageHandlers.size(); } inline ossim_uint32 numObs()const { return (ossim_uint32)theObs.size(); } inline ossim_uint32 numAdjPar()const { return (ossim_uint32)theNumAdjPar; } inline ossim_uint32 numMeas()const { return (ossim_uint32)theNumMeas; } // observation accessor inline ossimRefPtr observ(const int& i)const{ return theObs[i]; } // image accessor ossimImageGeometry* getImageGeom(const int index); void setImageGeom(const int index, ossimImageGeometry* geom); // image index accessor inline int imIndex(const int& i)const { return theImageIndex[i]; } // adjustable parameter count accessor inline int adjParCount(const int& i)const { return theNumAdjParams[i]; } // Image file access inline ossimFilename imageFile(const int index)const { return theImageFiles[index]; } /** * standard evaluation * [1] measResiduals: [x,y] residuals (numMeas X 2) * [2] objPartials: object point partial derivatives (numMeas*3 X 2) * [3] parPartials: image parameter partial derivatives (numParams X 2) */ bool evaluate(NEWMAT::Matrix& measResiduals, NEWMAT::Matrix& objPartials, NEWMAT::Matrix& parPartials); /** * operations */ bool addObservation(ossimRefPtr obs); /** * text output : header + tab separated tie points */ std::ostream& print(std::ostream& os) const; protected: int theNumAdjPar; int theNumMeas; int theNumPartials; // member observations std::vector< ossimRefPtr > theObs; // measurement -> image index std::vector theImageIndex; // image files std::vector theImageFiles; // image adjustable parameter count std::vector theNumAdjParams; std::vector< ossimRefPtr > theImageHandlers; // groups (TODO in future integration of correlated parameters) // Note: Currently, each image is assumed to be independent, which can result // in redundant parameters. For example, images from a single flight line // clearly share a common focal length and, most likely, a common position // bias. Implementation of this enhancement will require a mechanism for // defining inter-image parametric relationships. //std::vector theGroups; }; #endif // #ifndef ossimObservationSet_HEADER ossim-Miami-2.9.1/include/ossim/base/ossimOutputSource.h000066400000000000000000000050561352751253100233150ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class declaration for ossimImageWriter //******************************************************************* // $Id: ossimOutputSource.h 9968 2006-11-29 14:01:53Z gpotts $ // #ifndef ossimOutputSource_HEADER #define ossimOutputSource_HEADER #include #include #include class OSSIMDLLEXPORT ossimOutputSource : public ossimSource { public: ossimOutputSource(ossimObject* owner=NULL) :ossimSource(owner) {} ossimOutputSource(ossimObject* owner, ossim_uint32 inputListSize, ossim_uint32 outputListSize, bool inputListIsFixedFlag=true, bool outputListIsFixedFlag=true) :ossimSource(owner, inputListSize, outputListSize, inputListIsFixedFlag, outputListIsFixedFlag) { } virtual ~ossimOutputSource(){} virtual bool isOpen()const = 0; /*! * Allows a generic interface to open a consumer for writing. If * you are a display writer then you would probably show the window or * init the device context for writing. */ virtual bool open()=0; /*! * Will set the output name and open the output device. */ virtual bool open(const ossimString& outputName) { setOutputName(outputName); return open(); } /*! * This is a generic interface to allow one to set the output name of * the writer. If its a Visual display this could be used to * set the title. If this is a file output then this could be a * directory or a file name. */ virtual void setOutputName(const ossimString& outputName) { theOutputName = outputName; } virtual const ossimString& getOutputName() { return theOutputName; } /*! * Generic interface to allow one to close a consumer. For displays * this might minimize the window and free up internal pointers for * file writers it will make sure the file stream is closed and flushed. */ virtual void close()=0; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: ossimString theOutputName; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimPackedBits.h000066400000000000000000000027461352751253100226500ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2004 Garrett Potts. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class declaration for ossimPackBits. // //******************************************************************* // $Id: ossimPackedBits.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimPackedBits_HEADER #define ossimPackedBits_HEADER #include /** * This class will allow access to individual packed pixels given an offset and * return as an ossim_uint32 type. */ class OSSIM_DLL ossimPackedBits { public: /** * @brief Constructor that takes packed bits array and word size in bits. * * @param packedBits The unsigned eight bit array of packed bits. This * pointer is not owned by this class, only used. * * @param bits The number of bits in the packed bits word. */ ossimPackedBits(const ossim_uint8* packedBits, ossim_uint16 bits); /** * Extract out the value at offset indicated by idx and convert the * the vale to an ossim_uint32. This class only supports packed bits * less than 32. * * @param idx The packed bit word index to grab and stuff into an * unsigned 32 bit integer. */ ossim_uint32 getValueAsUint32(ossim_uint32 idx)const; protected: const ossim_uint8* thePackedBits; ossim_uint16 theBits; ossim_uint16 theBytes; ossim_uint16 theBitsLeft; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimPointHash.h000066400000000000000000000013771352751253100225330ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Point Hash is a base for hashing functions // //******************************************************************* // $Id: ossimPointHash.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimPointHash_HEADER #define ossimPointHash_HEADER #include #include class OSSIMDLLEXPORT ossimPointHash { public: virtual ~ossimPointHash(){} virtual long operator ()(const ossimDpt &aPoint)=0; virtual long operator ()(const ossimFpt &aPoint)=0; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimPointObservation.h000066400000000000000000000120201352751253100241260ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Class container for multi-ray point observation. //---------------------------------------------------------------------------- #ifndef ossimPointObservation_HEADER #define ossimPointObservation_HEADER #include #include #include #include #include #include #include #include #include #include class OSSIM_DLL ossimPointObservation : public ossimObject { public: ossimPointObservation(); ossimPointObservation(const ossimString& anID); ossimPointObservation(const ossimGpt& aPt, const ossimString& anID, const ossimColumnVector3d& latLonHgtSigmas); ossimPointObservation(const ossimPointObservation& tpt); ~ossimPointObservation(); void reset(); inline ossimGpt& Gpt() { return thePt; } inline ossimString ID()const { return theID; } inline void setID(const std::string& anID) { theID=anID; } inline unsigned int numImages()const { return (unsigned int)theImageFiles.size(); } inline unsigned int numMeas()const { return (unsigned int)theMeas.size(); } // Image geometry access ossimImageGeometry* getImageGeom(const int index); void setImageGeom(const int index, ossimImageGeometry* imgGeom); // Image file access inline ossimFilename imageFile(const int index)const { return theImageFiles[index]; } // Measurement addition void addMeasurement(const ossimDpt& meas, const ossimFilename& imgFile, const ossimDpt& measSigma = ossimDpt(1.0,1.0)); void addMeasurement(const double& x, const double& y, const std::string& imgFile, const ossimDpt& measSigma = ossimDpt(1.0,1.0)); // Measurement access void getResiduals(const int index, NEWMAT::Matrix& resid); void getMeasCov(const int index, NEWMAT::Matrix& cov)const; void getObsCov(NEWMAT::Matrix& cov)const; void getMeasurement(const int index, NEWMAT::Matrix& meas)const; inline ossimDpt getMeasurement(const int index)const { return theMeas[index]; } inline int numPars(const int index)const { return theNumPars[index]; } // Partial derivative access void getParameterPartials(const int index, NEWMAT::Matrix& parPartials); void getObjSpacePartials(const int index, NEWMAT::Matrix& objPartials); const ossimPointObservation& operator=(const ossimPointObservation&); inline void setGroundPoint(const double& lat, const double& lon, const double& hgt) { thePt.latd(lat); thePt.lond(lon); thePt.height(hgt); } inline void setGroundSigmas(const double& latSig, const double& lonSig, const double& hgtSig) { theObsSigmas[0] = latSig; theObsSigmas[1] = lonSig; theObsSigmas[2] = hgtSig; } inline void setGroundPoint(const ossimGpt& mPt) { thePt = mPt; } inline const ossimGpt& getGroundPoint()const { return thePt; } inline ossimGpt& refGroundPoint() { return thePt; } // Note: Member variable "theScore" is currently unused. Eventually, it is // intended as a figure-of-merit representation. inline void setScore(const double& s) { theScore = s; } inline const double& getScore()const { return theScore; } inline double& refScore() { return theScore; } void makeNan() { thePt.makeNan(); theScore=ossim::nan(); } bool hasNans()const { return (thePt.hasNans() || (ossim::isnan(theScore))); } bool isNan()const { return (thePt.isNan() && (ossim::isnan(theScore))); } std::ostream& print(std::ostream& os) const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& os, const ossimPointObservation& pt); /** * Method to input the formatted string of the "operator<<". * * Expected format: ( ( ossimGpt ), ( ossimDpt ), 0.50000000000000 ) * --*this---- , ----tie-----, ---score-------- */ friend OSSIMDLLEXPORT std::istream& operator>>(std::istream& is, ossimPointObservation& pt); protected: ossimGpt thePt; ossimString theID; double theObsSigmas[3]; double theScore; std::vector theMeas; std::vector theMeasSigmas; std::vector theImageFiles; std::vector theNumPars; std::vector< ossimRefPtr > theImageHandlers; }; #endif // #ifndef ossimPointObservation_HEADER ossim-Miami-2.9.1/include/ossim/base/ossimPolyArea2d.h000066400000000000000000000127131352751253100225740ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts //******************************************************************* //$Id: ossimPolyArea2d.h 23608 2015-10-28 13:51:35Z gpotts $ #ifndef ossimPolyArea2d_HEADER #define ossimPolyArea2d_HEADER 1 #include #include #include #include #include #include class ossimDrect; class ossimIrect; class OssimPolyArea2dPrivate; namespace geos { namespace geom { class Geometry; } } class OSSIM_DLL ossimPolyArea2d : public ossimReferenced { public: friend class OssimPolyArea2dPrivate; friend OSSIM_DLL std::ostream& operator <<(std::ostream& out, const ossimPolyArea2d& data); ossimPolyArea2d(); ossimPolyArea2d(const std::vector& polygon); ossimPolyArea2d(const std::vector& polygon); ossimPolyArea2d(const ossimPolygon& shell, const std::vector& holes); ossimPolyArea2d(const ossimDpt& p1, const ossimDpt& p2, const ossimDpt& p3, const ossimDpt& p4); ossimPolyArea2d(const ossimPolyArea2d& rhs); ossimPolyArea2d(const ossimIrect& rect); ossimPolyArea2d(const ossimDrect& rect); ossimPolyArea2d(const ossimPolygon& polygon); ~ossimPolyArea2d(); void clear() { clearPolygons(); } const ossimPolyArea2d& operator =(const ossimPolyArea2d& rhs); const ossimPolyArea2d& operator =(const ossimPolygon& rhs); const ossimPolyArea2d& operator =(const ossimIrect& rect); const ossimPolyArea2d& operator =(const ossimDrect& rect); const ossimPolyArea2d& operator =(const std::vector& polygon); const ossimPolyArea2d& operator =(const std::vector& polygon); const ossimPolyArea2d& operator &=(const ossimPolyArea2d& rhs); ossimPolyArea2d operator &(const ossimPolyArea2d& rhs)const; ossimPolyArea2d operator +(const ossimPolyArea2d& rhs)const; const ossimPolyArea2d& operator +=(const ossimPolyArea2d& rhs); ossimPolyArea2d operator -(const ossimPolyArea2d& rhs)const; const ossimPolyArea2d& operator -=(const ossimPolyArea2d& rhs); bool intersects(const ossimPolyArea2d& rhs)const; void add(const ossimPolyArea2d& rhs); bool getVisiblePolygons(std::vector& polyList)const; bool getPolygonHoles(std::vector& polyList)const; /** * @brief Gets all of the polygons stored with their holes embedded. This * may be useful if an operation was performed on the original ossimPolyArea2d * that caused multiple polygons to be created internally. * * For example, if a rectangle is intersected with a U shape, the two top * portions of the U would be their own separate polygon. It's also possible * for these polygons to contain their own holes. This function will return * the two top polygons as separate ossimPolyArea2d objects (with any of * their holes embedded inside them). * * -------------------------------- * | | * | | * | ........ ......... | * | . . . . | * -.------.-----------.-------.--- * . . . . * . ............. . * . . * ............................ * * @param polylist an empty vector of ossimPolyArea2d that will be filled * @return returns true if it successfully places polygons in the input vector */ bool getCompletePolygons(std::vector& polyList)const; bool isEmpty()const; bool isValid(bool displayValidationError = false)const; bool isPointWithin(const ossimDpt& point)const; bool isPointWithin(double x, double y)const; void getBoundingRect(ossimDrect& rect); /** * Returns the Well Known Text string */ std::string toString()const; /** * @brief Buffers the ossimPolyArea2d shape and returns a copy. This method * does not alter polygon. * * @param distance is the distance to buffer the shape by. Positive values * will expand the shape, and negative values will shrink the shape. * @return A shape that is a buffered (expanded/contracted) version of this * shape */ ossimPolyArea2d getBufferedShape(double distance=FLT_EPSILON) const; ossimPolyArea2d& setToBufferedShape(double distance=FLT_EPSILON); ossimPolyArea2d& toMultiPolygon(); bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: void clearPolygons(); void recurseVisibleGeometries(ossimPolygon::Vector& polyList, const geos::geom::Geometry* geom) const; void recurseHoles(ossimPolygon::Vector& polyList, const geos::geom::Geometry* geom) const; /** * @brief Recurses over the Geometry object to load all complete polygons * (a shell and any internal holes) into the ossimPolyArea2d. */ void recurseCompleteGeometries(std::vector& polyList, const geos::geom::Geometry* geom) const; OssimPolyArea2dPrivate* m_privateData; }; #endif /* #ifndef ossimPolyArea2d_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimPolyLine.h000066400000000000000000000150151352751253100223630ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains declaration of class ossimPolygon. // This class provides utilities associated with N-vertex, convex // (i.e., only two intersections for any line passing through the polygon). // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimPolyLine.h 15833 2009-10-29 01:41:53Z eshirschorn $ #ifndef ossimPolyLine_HEADER #define ossimPolyLine_HEADER #include #include #include #include #include #include class ossimLine; class ossimPolygon; /*!**************************************************************************** * * CLASS: ossimPolyLine * *****************************************************************************/ class OSSIMDLLEXPORT ossimPolyLine { public: ossimPolyLine() :theCurrentVertex(0) {} ossimPolyLine(const std::vector& polygon); ossimPolyLine(const std::vector& polygon); ossimPolyLine(int numVertices, const ossimDpt* vertex_array); ossimPolyLine(const ossimPolyLine& copy_this); ossimPolyLine(const ossimPolygon& polygon); /*! * CONSTRUCTOR: Provided for convenience. Does not imply the polygon is * limited to four vertices: */ ossimPolyLine(ossimDpt v1, ossimDpt v2, ossimDpt v3, ossimDpt v4); ossimPolyLine(const ossimIrect& rect); ossimPolyLine(const ossimDrect& rect); ~ossimPolyLine(); ossimDpt& operator[](int index) { return theVertexList[index]; } const ossimDpt& operator[](int index)const { return theVertexList[index]; } ossim_uint32 getNumberOfVertices()const { return (ossim_uint32)theVertexList.size(); } void getIntegerBounds(ossim_int32& minX, ossim_int32& minY, ossim_int32& maxX, ossim_int32& maxY)const; void getBounds(double& minX, double& minY, double& maxX, double& maxY)const; void getBoundingRect(ossimDrect& rect)const { ossim_int32 minX; ossim_int32 minY; ossim_int32 maxX; ossim_int32 maxY; getIntegerBounds(minX, minY, maxX, maxY); rect = ossimDrect(minX, minY, maxX, maxY); } ossimDrect getBoundingRect()const { ossimDrect result; getBoundingRect(result); return result; } void roundToIntegerBounds(bool compress=true); void clear() { theVertexList.clear(); } void addPoint(const ossimDpt& pt) { theVertexList.push_back(pt); } void addPoint(double x, double y) { theVertexList.push_back(ossimDpt(x, y)); } void addAttribute( const ossimString& attribute ) { theAttributeList.push_back( attribute ); } ossimDpt midPoint()const; /*! * will sequence through the polygon and check to see if any values are NAN */ bool hasNans()const; ossim_uint32 size() { return getNumberOfVertices(); } void resize(ossim_uint32 newSize) { theVertexList.resize(newSize); } const std::vector& getVertexList()const { return theVertexList; } std::vector& getVertexList() { return theVertexList; } std::vector& getAttributeList() { return theAttributeList; } bool clipToRect(std::vector& result, const ossimDrect& rect)const; /*! * Will clip this poly line list to the past in rect and * will return true if any part of this object is visible within * the rectangle; */ bool isWithin(const ossimDrect& rect)const; /*! * METHOD: pointWithin(ossimDpt) * Returns TRUE if point is inside polygon. */ bool pointWithin(const ossimDpt& point) const { return isPointWithin(point); } bool isPointWithin(const ossimDpt& point) const; /*! * METHOD: vertex(index) * Returns the ossimDpt vertex given the index. Returns false if no vertex * defined. */ bool vertex(int index, ossimDpt& tbd_vertex) const; /*! * METHOD: nextVertex() * Assigns the ossimDpt tbd_vertex following the current vertex. The current * vertex is initialized with a call to vertex(int), or after the last * vertex is reached. Returns false if no vertex defined. Intended to be * when cycling through all vertices. */ bool nextVertex(ossimDpt& tbd_vertex) const; void reverseOrder(); /*! * OPERATORS: (Some are inlined at bottom) */ const ossimPolyLine& operator= (const ossimPolyLine& copy_this); const ossimPolyLine& operator= (const std::vector& vertexList); const ossimPolyLine& operator= (const std::vector& vertexList); const ossimPolyLine& operator= (const ossimIrect& rect); const ossimPolyLine& operator= (const ossimPolygon& polygon); const ossimPolyLine& operator= (const ossimDrect& rect); bool operator==(const ossimPolyLine& compare_this) const; bool operator!=(const ossimPolyLine& compare_this) const; const ossimPolyLine& operator *=(const ossimDpt& scale); const ossimPolyLine& operator *=(double scale) { return ((*this)*=ossimDpt(scale, scale)); } ossimPolyLine operator *(const ossimDpt& scale)const; ossimPolyLine operator *(double scale)const { return ((*this)*ossimDpt(scale, scale)); } /*! * METHOD: print() */ void print(std::ostream& os) const; friend std::ostream& operator<<(std::ostream&, const ossimPolyLine&); bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: std::vector theVertexList; std::vector theAttributeList; mutable ossim_int32 theCurrentVertex; }; inline bool ossimPolyLine::operator!=(const ossimPolyLine& compare_this) const { return !(*this == compare_this); } inline std::ostream& operator<<(std::ostream& os, const ossimPolyLine& polyLine) { polyLine.print(os); return os; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimPolygon.h000066400000000000000000000173311352751253100222620ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimPolygon.h // // Copyright (C) 2001 ImageLinks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains declaration of class ossimPolygon. // This class provides utilities associated with N-vertex, convex // (i.e., only two intersections for any line passing through the polygon). // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimPolygon.h 22333 2013-07-26 15:55:36Z dlucas $ #ifndef ossimPolygon_HEADER #define ossimPolygon_HEADER #include #include #include #include #include #include class ossimLine; /****************************************************************************** * * CLASS: ossimPolygon * *****************************************************************************/ class OSSIMDLLEXPORT ossimPolygon { public: typedef std::vector Vector; ossimPolygon(); ossimPolygon(const std::vector& polygon); ossimPolygon(const std::vector& polygon); ossimPolygon(const std::vector& polygon); ossimPolygon(int numVertices, const ossimDpt* vertex_array); ossimPolygon(const ossimPolygon& copy_this); /** * CONSTRUCTOR: Provided for convenience. Does not imply the polygon is * limited to four vertices: */ ossimPolygon(ossimDpt v1, ossimDpt v2, ossimDpt v3, ossimDpt v4); ossimPolygon(const ossimIrect& rect); ossimPolygon(const ossimDrect& rect); ~ossimPolygon(); ossimDpt& operator[](int index); const ossimDpt& operator[](int index)const; ossim_uint32 getVertexCount()const; ossim_uint32 getNumberOfVertices()const; //! Returns polygon area. Negative indicates CW ordering of vertices (in right-handed coordinates) double area()const; void getIntegerBounds(ossim_int32& minX, ossim_int32& minY, ossim_int32& maxX, ossim_int32& maxY)const; void getFloatBounds(ossim_float64& minX, ossim_float64& minY, ossim_float64& maxX, ossim_float64& maxY)const; void getBoundingRect(ossimIrect& rect)const; void getBoundingRect(ossimDrect& rect)const; /** * Initializes minRect with the minimum area rect (not-necessarily * aligned with axes) that bounds this polygon. * * @param minRect Polygon to initialize with the minimum rect. */ void getMinimumBoundingRect(ossimPolygon& minRect) const; void roundToIntegerBounds(bool compress=false); void clear(); void addPoint(const ossimDpt& pt); void addPoint(double x, double y); ossimDpt midPoint()const; /** * will sequence through the polygon and check to see if any values are NAN */ bool hasNans()const; const std::vector& getVertexList()const; /** * Uses the ossimPolyArea2d class for the intersection */ bool clipToRect(std::vector& result, const ossimDrect& rect)const; /** * METHOD: clipLineSegment(p1, p2) * Implements Cyrus-Beck clipping algorithm as described in: * http://www.daimi.au.dk/~mbl/cgcourse/wiki/cyrus-beck_line-clipping_.html * Clips the line segment defined by thw two endpoints provided. The * endpoints are modified as needed to represent the clipped line. Returnes * true if intersection present. */ bool clipLineSegment(ossimDpt& p1, ossimDpt& p2) const; /** * METHOD: pointWithin(ossimDpt) * Returns TRUE if point is inside polygon. */ bool pointWithin(const ossimDpt& point) const; bool isPointWithin(const ossimDpt& point) const; /** * METHOD: isRectWithin() * Returns true if all the corner points of the given rect fit within. */ bool isRectWithin(const ossimIrect &rect) const; /** * METHOD: rectIntersects() * Returns true if at least one corner points of the given rect is within. */ bool rectIntersects(const ossimIrect &rect) const; /** * METHOD: isPolyWithin() * Returns true if all the vertices of the given polygon fit within. */ bool isPolyWithin(const ossimPolygon &poly) const; /** * METHOD: vertex(index) * Returns the ossimDpt vertex given the index. Returns false if no vertex * defined. */ bool vertex(int index, ossimDpt& tbd_vertex) const; /** * METHOD: nextVertex() * Assigns the ossimDpt tbd_vertex following the current vertex. The current * vertex is initialized with a call to vertex(int), or after the last * vertex is reached. Returns false if no vertex defined. Intended to be * when cycling through all vertices. */ bool nextVertex(ossimDpt& tbd_vertex) const; void reverseOrder(); /** * OPERATORS: (Some are inlined at bottom) */ const ossimPolygon& operator= (const ossimPolygon& copy_this); const ossimPolygon& operator= (const std::vector& vertexList); const ossimPolygon& operator= (const std::vector& vertexList); const ossimPolygon& operator= (const std::vector& vertexList); const ossimPolygon& operator= (const ossimIrect& rect); const ossimPolygon& operator= (const ossimDrect& rect); bool operator==(const ossimPolygon& compare_this) const; bool operator!=(const ossimPolygon& compare_this) const; const ossimPolygon& operator *=(const ossimDpt& scale); const ossimPolygon& operator *=(double scale); ossimPolygon operator *(const ossimDpt& scale)const; ossimPolygon operator *(double scale)const; void resize(ossim_uint32 newSize); /** * METHOD: remove() * Removes the vertex from the polygon. */ void removeVertex(int vertex); /** * METHOD: print() */ void print(std::ostream& os) const; friend std::ostream& operator<<(std::ostream&, const ossimPolygon&); bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); ossimVertexOrdering checkOrdering()const; ossimVertexOrdering getOrdering()const; protected: /** * METHOD: getCentroid() * Assigns the ossimDpt centroid the polygon. * Warning: centroid is not guaranteed to be inside the polygon! */ void getCentroid(ossimDpt ¢roid) const; /** * METHOD: shrink() * Shrinks the current polygon by inset, return true if success. */ bool shrink(ossimPolygon &dest, double inset) const; /** * METHOD: removeSmallestContributingVertex() * Removes the vertex that contributes the smallest area to the polygon. */ void removeSmallestContributingVertex(); void intersectEdge(ossimDpt& result, const ossimLine& segment, const ossimDrect& rect, int edge); bool isInsideEdge(const ossimDpt& pt, const ossimDrect& rect, int edge)const; /** * Assigns destPt the point that fits a circle of given radius inside the polygon vertex. * Warning: destPt is not guaranteed to be inside the polygon! * (you may not be able to fit a circle of the given radius inside the polygon) */ void fitCircleInsideVertex(ossimDpt &destPt, unsigned int vertex, double radius) const; mutable ossimVertexOrdering theOrderingType; std::vector theVertexList; mutable ossim_int32 theCurrentVertex; }; #endif /* End of "#ifndef ossimPolygon_HEADER" */ ossim-Miami-2.9.1/include/ossim/base/ossimPolynom.h000066400000000000000000000572571352751253100223030ustar00rootroot00000000000000/////////////////////////////////////////////////////////////////////////////// // ossimPolynom.h // Author: Frederic Claudel Meraka/CSIR, 2005 /////////////////////////////////////////////////////////////////////////////// // //TODO : check if automatically removing small monoms is actually viable // //TBD : normalization for Least Mean Square fit //TBD : copy constructor for different DIM //TBD : LOW PRIORITY redo serialization so that doesn't have to use strings (streams only) #ifndef ossimPolynom_HEADER #define ossimPolynom_HEADER #include #include #include #include #include #include #include #include #include #include /** * template class for multivariate polynom algebra * * T : the storage type, constraints: must have 0 (zero) as value, support ops fabs + - * / * DIM : the dimension of the input space, integer (>=1, default : 1) * * stores a set of monoms, a monom is (exponent tuples + coefficient) * requires a precion (epsilon) for comparisons * note: monoms absolute values below epsilon are removed from the map */ template < class T, int DIM = 1 > class ossimPolynom { public: /** * inner types */ typedef std::vector< int > EXP_TUPLE; //! type to store exponent tuples typedef std::vector< T > VAR_TUPLE; //! type to store multivariate input struct EXP_TUPLE_LESSTHAN //! inner functor for sorting exponent tuples { //warning both EXP_TUPLE should have same dimension (not necessarily DIM) bool operator()(const EXP_TUPLE& o1, const EXP_TUPLE& o2)const { for(unsigned int i=0;io2[i]) { return false; } } return false; } }; typedef std::map< EXP_TUPLE, T , EXP_TUPLE_LESSTHAN > MONOM_MAP; //! for storing polynom typedef std::set< EXP_TUPLE, EXP_TUPLE_LESSTHAN > EXPT_SET; //! for storing set of exponent tuples /** * construction : * */ //TBD : by default, adapt epsilon to template type T ossimPolynom(const T& epsilon = 0) //! must supply epsilon value, default 0 : theEpsilon(epsilon) {} ossimPolynom(const ossimPolynom& p) : theMonoms(p.getMonoms()), theEpsilon(p.getEpsilon()) {} ~ossimPolynom() {} const ossimPolynom& operator=(const ossimPolynom< T, DIM >& pt) { if (this != &pt) { theEpsilon = pt.getEpsilon(); theMonoms = pt.getMonoms(); } return *this; } void setMonom(const EXP_TUPLE& m, const T& v) { if (isNegligible(v)) { theMonoms.erase(m); //TBC TBD: what happens if m is not in the map? } else { theMonoms[m] = v; } } void setMonom(const int mexp[DIM], const T& v) { EXP_TUPLE mexpV(mexp,mexp+DIM); if (isNegligible(v)) { theMonoms.erase(mexpV); //TBC TBD: what happens if m is not in the map? } else { theMonoms[mexpV] = v; } } inline void delMonom(const EXP_TUPLE& m) { theMonoms.erase(m); //TBC TBD: what happens if m is not in the map? } T getCoeff(const EXP_TUPLE& m)const { typename MONOM_MAP::const_iterator it = theMonoms.find(m); if (it != theMonoms.end()) { return it->second; } else { return 0; } } void nullify() //set to 0 { theMonoms.clear(); } inline bool isNull()const { return (theMonoms.size() == 0); } inline const MONOM_MAP& getMonoms()const { return theMonoms; } inline const T& getEpsilon()const //! no setEpsilon beacause might erase monoms { return theEpsilon; } /** * comparison operators * -don't compare theEpsilon values * -use my own epsilon in comparisons (not the compared to's epsilon) */ bool operator==(const ossimPolynom& pt)const { if (getMonoms().size() != pt.getMonoms().size()) return false; // loop on my monoms typename MONOM_MAP::const_iterator it; for ( it = getMonoms().begin(); it != getMonoms().end() ; ++it ) { if ( !isNegligible(it->second - pt.getCoeff(it->first)) ) return false; } return true; //same number of identical monoms } bool operator!=(const ossimPolynom& pt)const { return !operator==(pt); } inline bool isNegligible(const T& v)const //! can v be considered as zero? { return ( fabs(v) <= theEpsilon ); } /** * orders */ int getOrder(int d)const //! returns maximum order of monoms for a specific dimension (d starts at 0) { if ((d>=DIM) || (d<0)) return -1; //error = no dimension // loop on monoms int order = -1; //for null polynom int corder; typename MONOM_MAP::const_iterator it; for ( it = getMonoms().begin(); it != getMonoms().end() ; ++it ) { corder = (it->first)[d]; if ( corder > order ) order = corder; } return order; } int getTotalOrder()const //! returns maximum order of monoms { int order = -1; //for null polynom int sorder; typename MONOM_MAP::const_iterator it; for ( it = getMonoms().begin(); it != getMonoms().end() ; ++it ) { sorder = 0; for (int d=0;dfirst)[d]; if ( sorder > order ) order = sorder; } return order; } /** * evaluation : needs DIM values as input */ T eval(const VAR_TUPLE& v)const { T ev = 0; //loop on monoms. TBD optimize powers using map order typename MONOM_MAP::const_iterator it; int p; for ( it = getMonoms().begin(); it != getMonoms().end() ; ++it ) { //compute powers T mv = it->second; for(int d=0;dfirst)[d]; if (p != 0) { mv *= std::pow( v[d], p ); } } //add momom value ev += mv; } return ev; } /** * partial differentiation polynom */ void pdiff(int pdim, ossimPolynom& result)const { result.nullify(); int ord; //loop on monoms for ( typename MONOM_MAP::const_iterator it = getMonoms().begin(); it != getMonoms().end() ; ++it ) { ord = it->first[pdim]; if (ord>=1) { EXP_TUPLE expDiff(it->first); expDiff[pdim] -= 1; result.setMonom(expDiff, it->second * ord); } } } /** * operations with scalar */ const ossimPolynom& operator*=(const T& k) { //loop on monoms for ( typename MONOM_MAP::const_iterator it = getMonoms().begin(); it != getMonoms().end() ; ++it ) { it->second *= k; } discardNullMonoms(); } /** * arithmetic operators */ ossimPolynom operator+(const ossimPolynom& p)const { ossimPolynom< T , DIM > sum(*this); return (sum+=p); } ossimPolynom operator-(const ossimPolynom& p)const { ossimPolynom< T , DIM > diff(*this); return (diff-=p); } const ossimPolynom& operator+=(const ossimPolynom& p) { typename MONOM_MAP::const_iterator it; //loop on p monoms for ( it = p.getMonoms().begin(); it != p.getMonoms().end() ; ++it ) { setMonom( it->first, getCoeff(it->first) + it->second ); } return *this; } const ossimPolynom& operator-=(const ossimPolynom& p) { typename MONOM_MAP::const_iterator it; //loop on p monoms for ( it = p.getMonoms().begin(); it != p.getMonoms().end() ; ++it ) { setMonom( it->first, getCoeff(it->first) - it->second ); } return *this; } /** * product operator : use epsilon from left side */ ossimPolynom operator*(const ossimPolynom& p)const { //do a stupid multiplication (sum all monom pairs) ossimPolynom< T , DIM > prod(getEpsilon()); T coeff; //loop on p monoms for ( typename MONOM_MAP::const_iterator it = getMonoms().begin(); it != getMonoms().end() ; ++it ) { for ( typename MONOM_MAP::const_iterator pit = p.getMonoms().begin(); pit != p.getMonoms().end() ; ++pit ) { coeff = it->second * pit->second; if (coeff!=0) { EXP_TUPLE prodExp(it->first); addExpTuple(prodExp, pit->first); prod.addMonomQuick(prodExp, coeff); } } } //scan for null monoms and discard prod.discardNullMonoms(); return prod; } const ossimPolynom& operator*=(const ossimPolynom& p) { return operator=( this->operator*(p) ); } static void addExpTuple(EXP_TUPLE& m1, const EXP_TUPLE& m2) { for(int i=0;i 0) { os<second<<"("; for(int d=0 ; d0) */ /* { */ /* os<<","; */ /* } */ os<<(it->first)[d]; } os<<")"; use_sep=monom_sep; } os<<"]"; return os; } std::ostream& printNice(std::ostream& os, const char symbols[DIM]) //!classic representation (bad accuracy, for display only) { if (getMonoms().size() == 0) { os<<"0"; //zero } else { os<second; if (coeff>0) { os<<"+"; } os<first)[d]; if (ord>0) { os<<""<= BUFSIZE-1) { std::cerr<<"ossimPolynom::import ERROR, cannot find right bracket ] after "< subparts = tempString.explode(";"); //loop on subparts for (typename std::vector< ossimString >::const_iterator it=subparts.begin() ; it!=subparts.end() ; ++it ) { ossimString sp = it->trim(); //check for epsilon ossimString aft_eps=sp.after("eps="); if (aft_eps.size()>0) { //get epsilon value aft_eps.trim(); theEpsilon = static_cast< T >(aft_eps.toDouble()); } else { //no epsilon : must be a monom ossimString scalpart=sp.before("("); if (scalpart.size() < sp.size()) { T coeff = static_cast< T >(scalpart.toDouble()); ossimString expopart = ((sp.before(")")).after("(")).trim(); if (expopart.size() == 0) { std::cerr<<"ossimPolynom::import ERROR, cannot find ) in monom or empty monom"< vexpo = expopart.explode(","); if (vexpo.size() != DIM) { std::cerr<<"ossimPolynom::import ERROR, bad number of exponents in monom (need "<::const_iterator eit; for (eit=vexpo.begin() , d=0 ; eit != vexpo.end() ; ++eit, ++d ) { expt[d] = eit->toInt(); //TBD : could check that value is integer, but how? } //add new monom (if duplicate...error) if (getMonoms().find(expt) != getMonoms().end()) { std::cerr<<"ossimPolynom::import ERROR, duplicate exponent tuple in polynom"<=0 ; --d) { if ((et[d] > orders[d]) && (d>0)) { et[d] = 0; et[d-1]++; } } } return eset; } /** * concatenate exponents (at the right) to existing tuple set, for a given maximum total order * eg: with eset={(0,1),(0,0)} , * then addExpTuple(2,1,eset) = {(0,1,0,0),(0,1,0,1),(0,1,1,0), (0,0,0,0),(0,0,0,1),(0,0,1,0)} */ void addExpTupleRight(int newdim, int totalOrder, EXPT_SET& eset )const { EXPT_SET newset; // add a copy off eset for each order with the specific last dim for(int o=0; o<=totalOrder ; ++o) { EXPT_SET extset; //extended set if (eset.size()==0) { EXP_TUPLE tu(1); tu[0]=o; extset.insert(tu); } else { //we have to construct a new set from eset, extending dimension // cause: stored tuples cannot be compared at different dimensions for(typename EXPT_SET::iterator sit = eset.begin(); sit != eset.end(); ++sit) { EXP_TUPLE tu(*sit); tu.push_back(o); extset.insert(tu); } } //recursively add remaining dimensions if (newdim>1) { addExpTupleRight(newdim-1, totalOrder-o, extset); //only dimension decreases } //add full set for the specific order newset.insert(extset.begin(), extset.end()); } eset=newset; //overwrite } /** * fits the polynom to the observations using Least Mean Squares * returns true on success (can fail if not enough observations) * + also updates rms error(root mean square) * NOTES: inputs must have same size and must be ordered the same way * use builExpSet() to construct classic polynoms * TODO: add weights to observations */ bool LMSfit(const EXPT_SET& expset, const std::vector< VAR_TUPLE > obs_input, const std::vector< T > obs_output, T* prms = NULL) { //init nullify(); //check size int nobs = (int)obs_input.size(); if (nobs != (int)obs_output.size()) { std::cerr<<"ossimPolynom::LMSfit ERROR observation input/output must have the same size"<::const_iterator oit; int i,j; for (cit=expset.begin(), j=1; cit != expset.end() ; ++cit, ++j) //loop on exponent tuples { for(oit=obs_input.begin(), i=1; oit!=obs_input.end();++oit, ++i) //loop on observations { //compute powers using observation position elt=1.0; for(int d=0;d obs_input, const std::vector< T > obs_output, T* prms = NULL) { //init nullify(); //check size int nobs = (int)obs_input.size(); if (nobs != (int)obs_output.size()) { std::cerr<<"ossimPolynom::LMSfit ERROR observation input/output must have the same size"<::const_iterator oit; int i,j; for (cit=expset.begin(), j=1; cit != expset.end() ; ++cit, ++j) //loop on exponent tuples { for(oit=obs_input.begin(), i=1; oit!=obs_input.end();++oit, ++i) //loop on observations { elt=1.0; for(int d=0;d erasev; //storage for iterators on elements to erase for (typename MONOM_MAP::iterator it = theMonoms.begin(); it != theMonoms.end() ; ++it ) { if (isNegligible(it->second)) erasev.push_back(it); } //erase all elements afterwards for ( typename std::vector< typename MONOM_MAP::iterator >::const_iterator vit = erasev.begin(); vit != erasev.end() ; ++vit ) { theMonoms.erase(*vit); //*vit is an iterator in theMonoms } } /** * add value without testing for negligible */ void addMonomQuick(const EXP_TUPLE& m, const T& v) { typename MONOM_MAP::iterator it = theMonoms.find(m); if (it != theMonoms.end()) { it->second += v; } else { theMonoms.insert( MONOM_MAP::value_type(m,v)); } } /** * invert stolen from ossimRpcSolver */ NEWMAT::Matrix invert(const NEWMAT::Matrix& m)const { ossim_uint32 idx = 0; NEWMAT::DiagonalMatrix d; NEWMAT::Matrix u; NEWMAT::Matrix v; // decompose m.t*m which is stored in Temp into the singular values and vectors. // NEWMAT::SVD(m, d, u, v, true, true); // invert the diagonal // this is just doing the reciprical fo all diagonal components and store back int // d. ths compute d inverse. // for(idx=0; idx < (ossim_uint32)d.Ncols(); ++idx) { if(d[idx] > getEpsilon()) //adpated here for epsilon { d[idx] = 1.0/d[idx]; } else { d[idx] = 0.0; } } //compute inverse of decomposed m; return v*d*u.t(); } }; //class ossimPolynom /** * stream operators */ template < class T, int DIM > std::ostream& operator<<(std::ostream& os, const ossimPolynom& pt) { return pt.print(os); } template < class T, int DIM > std::istream& operator>>(std::istream& is, ossimPolynom& pt) { return pt.import(is); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimPool.h000066400000000000000000000067761352751253100215570ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //********************************************************************** // $Id: ossimPool.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimPool_HEADER #define ossimPool_HEADER #include #include #include #include #include #include #include #include #define OSSIM_DEFAULT_POOL_SIZE (ossim_uint32)10 /** * Container pool to be used for things like threads. */ template class ossimPool { public: /** * Contructor * @param n Number of pooled objects to create. */ ossimPool(ossim_uint32 n=OSSIM_DEFAULT_POOL_SIZE) throw(std::bad_alloc) : thePool(n) { for(ossim_uint32 idx = 0; idx < n; ++idx) { try { ossimPoolObject* poolObject = new ossimPoolObject(); poolObject->theAvailableFlag = true; poolObject->theObjectPtr = new T(); thePool[idx] = poolObject; } catch(std::bad_alloc) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPool::ossimPool(): Bad allocation" << std::endl; } } } /** * Destructor */ ~ossimPool() { thePool.clear(); } /** * @return A pooled object of type T*. Will return null if the pool is * used up or pool size is zero. */ T* checkout() { T* t = NULL; theCriticalSectionMutex.lock(); for (ossim_uint32 idx = 0; idx < thePool.size(); ++idx) { if (thePool[idx]->theAvailableFlag == true) { thePool[idx]->theAvailableFlag = false; t = thePool[idx]->theObjectPtr; break; } } theCriticalSectionMutex.unlock(); return t; } /** * Resets and eturns object to the pool. * @param obj Object to be returned to the pool. * * @note The object is required to have a "reset()" method. * * @return Returns void unless object was not from pool then throws * a std::out_of_range error. */ void checkin(T* obj) throw(std::out_of_range) { theCriticalSectionMutex.lock(); for (ossim_uint32 idx = 0; idx < thePool.size(); ++idx) { if (obj == thePool[idx]->theObjectPtr) { obj->reset(); thePool[idx]->theAvailableFlag = true; theCriticalSectionMutex.unlock(); return; } } theCriticalSectionMutex.unlock(); throw std::out_of_range(string("ossimPool::checkin Error Object not managed by this pool!")); } /** * Outputs object addresses and theAvailableFlag. */ std::ostream& print(std::ostream& out) const { for (ossim_uint32 idx = 0; idx < thePool.size(); ++idx) { out << "obj address: " << (hex) << thePool[idx]->theObjectPtr << " is " << (thePool[idx]->theAvailableFlag ? "available":"unavailable") << std::endl; } return out; } template friend std::ostream& operator<<(std::ostream& out, const ossimPool& obj) { return obj.print(out); } protected: std::vector*> thePool; }; #endif /* #ifndef ossimPool_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimPoolObject.h000066400000000000000000000014411352751253100226660ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // //********************************************************************** // $Id: ossimPoolObject.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimPoolObject_HEADER #define ossimPoolObject_HEADER /** * Templated container for an object pointer and a flag. */ template class ossimPoolObject { public: ~ossimPoolObject() { if(theObjectPtr) { cout << "deleting obj: " << (hex) << theObjectPtr << std::endl; delete theObjectPtr; theObjectPtr = NULL; } theAvailableFlag = false; } bool theAvailableFlag; T* theObjectPtr; }; #endif /* #ifndef ossimPoolObject_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimPreferences.h000066400000000000000000000067401352751253100230760ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of class ossimPreferences. This class provides // a static keywordlist for global preferences. Objects needing access to // application-wide global parameters shall do so through this class. // // SOFTWARE HISTORY: //> // 23Apr2001 Oscar Kramer // Initial coding. //< //***************************************************************************** #ifndef ossimPreferences_HEADER #define ossimPreferences_HEADER #include #include /*!**************************************************************************** * * CLASS: ossimPreferences * *****************************************************************************/ class OSSIMDLLEXPORT ossimPreferences { public: // This is only here so we can swig wrap this. The destructor should never be called directly. ~ossimPreferences(); /*! * METHOD: instance() * The static singleton instance of this object is accessed via this method: */ static ossimPreferences* instance(); /*! * METHOD: loadPreferences() * These methods clear the current preferences and load either the default * preferences file or the specified file. Returns TRUE if loaded properly: */ bool loadPreferences(); bool loadPreferences(const ossimFilename& pathname); /*! * METHOD: savePrefences() * This method permits saving the preferences file to the default location * or to a specified location: */ bool savePreferences() const; bool savePreferences(const ossimFilename& pathname); /*! * METHOD: findPreference() * Performs a lookup for the specified keyword in the preferences KWL: */ const char* findPreference(const char* key) const {return theKWL.find(key);} /*! * METHOD: addPreference() * Inserts keyword/value pair into the in-memory preferences KWL. It does * save to disk. App must do a savePreferences() for changes to be saved. */ void addPreference(const char* key, const char* value); /*! * METHOD: preferencesKWL() * An alternative to utilizing findPreference(), for objects derived from * ossimObject, is to access the preferences KWL with this method * (typically during construction) and provide it to the object's * loadState() method. */ const ossimKeywordlist& preferencesKWL() const { return theKWL; } /*! * METHOD: preferencesKWL() * An alternative to utilizing findPreference(), for objects derived from * ossimObject, is to access the preferences KWL with this method * (typically during construction) and provide it to the object's * loadState() method. */ ossimKeywordlist& preferencesKWL() { return theKWL; } void addPreferences(const ossimKeywordlist& kwl, const char* prefix=0, bool stripPrefix=true); /** @return The preference filename. */ ossimFilename getPreferencesFilename() const; protected: /*! * Override the compiler default constructors: */ ossimPreferences(); ossimPreferences(const ossimPreferences&) {} void operator = (const ossimPreferences&) const {} static ossimPreferences* theInstance; ossimKeywordlist theKWL; ossimFilename thePrefFilename; mutable bool theInstanceIsModified; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimProcessInterface.h000066400000000000000000000042201352751253100240630ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimProcessInterface.h 23353 2015-06-01 19:19:10Z dburken $ #ifndef ossimProcessInterface_HEADER #define ossimProcessInterface_HEADER 1 #include #include #include #include #include class ossimObject; class ossimListenerManager; class OSSIMDLLEXPORT ossimProcessInterface { public: enum ossimProcessStatus { PROCESS_STATUS_UNKNOWN = 0, PROCESS_STATUS_EXECUTING = 1, PROCESS_STATUS_ABORTED = 2, PROCESS_STATUS_ABORT_REQUEST = 3, PROCESS_STATUS_NOT_EXECUTING = 4 }; ossimProcessInterface(); virtual ~ossimProcessInterface(); virtual ossimObject* getObject()=0; virtual const ossimObject* getObject()const=0; virtual bool execute()=0; virtual void abort(); bool needsAborting()const; bool isAbortRequested()const; bool isAborted()const; bool isExecuting()const; ossimProcessStatus getProcessStatus()const; virtual void setProcessStatus(ossimProcessStatus processStatus); virtual double getPercentComplete()const; virtual void setPercentComplete(double percentComplete); virtual ossimListenerManager* getManager(); void enableEvents(); void disableEvents(); void setCurrentMessage(const ossimString& message); /*! * Called by friend operator<< function, derived classes should override * if something different is desired. */ virtual std::ostream& print(std::ostream& out) const; friend OSSIM_DLL std::ostream& operator<<(std::ostream& out, const ossimProcessInterface& data); protected: double thePercentComplete; ossimProcessStatus theProcessStatus; ossimString theMessage; bool theEventFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimProcessListener.h000066400000000000000000000014571352751253100237610ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // $Id: ossimProcessListener.h 14799 2009-06-30 08:54:44Z dburken $ //---------------------------------------------------------------------------- #ifndef ossimProcessListener_HEADER #define ossimProcessListener_HEADER #include class ossimProcessProgressEvent; class OSSIMDLLEXPORT ossimProcessListener : public ossimListener { public: ossimProcessListener(); virtual ~ossimProcessListener(); virtual void processEvent(ossimEvent& event); virtual void processProgressEvent(ossimProcessProgressEvent& event); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimProcessProgressEvent.h000066400000000000000000000025611352751253100247770ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Event for process progress. // // $Id: ossimProcessProgressEvent.h 9094 2006-06-13 19:12:40Z dburken $ //---------------------------------------------------------------------------- #ifndef ossimProcessProgressEvent_HEADER #define ossimProcessProgressEvent_HEADER #include #include class OSSIMDLLEXPORT ossimProcessProgressEvent : public ossimEvent { public: ossimProcessProgressEvent(ossimObject* owner=NULL, double percentComplete=0.0, const ossimString message="", bool outputMessageFlag=false); virtual ossimObject* dup()const; double getPercentComplete()const; ossimString getMessage()const; void getMessage(ossimString& message)const; void setPercentComplete(double percentComplete); void setMessage(const ossimString& message); void setOutputMessageFlag(bool flag); bool getOutputMessageFlag() const; protected: double thePercentComplete; ossimString theMessage; bool theOutputMessageFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimProperty.h000066400000000000000000000056021352751253100224550ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimProperty.h 19917 2011-08-09 11:12:24Z gpotts $ #ifndef ossimProperty_HEADER #define ossimProperty_HEADER #include #include #include class ossimContainerProperty; class OSSIM_DLL ossimProperty : public ossimObject { public: /*! * This are bitwise and can be ored together * The change type is very important and * it determines how things are refreshed. */ enum ossimPropertyChangeType { ossimPropertyChangeType_NOTSPECIFIED = 0, ossimPropertyChangeType_CACHE_REFRESH = 1, ossimPropertyChangeType_FULL_REFRESH = 2, ossimPropertyChangeType_AFFECTS_OTHERS = 4, // used to identify if this property modification affects the values of other properties once set ossimPropertyChangeType_ALL = (ossimPropertyChangeType_CACHE_REFRESH|ossimPropertyChangeType_FULL_REFRESH|ossimPropertyChangeType_AFFECTS_OTHERS) }; ossimProperty(const ossimString& name=ossimString("")); ossimProperty(const ossimProperty& rhs); const ossimProperty& operator = (const ossimProperty& rhs); virtual const ossimProperty& assign(const ossimProperty& rhs); const ossimString& getName()const; void setName(const ossimString& name); virtual bool setValue(const ossimString& value)=0; virtual void valueToString(ossimString& valueResult)const=0; virtual ossimString valueToString()const; virtual const ossimContainerProperty* asContainer()const; virtual ossimContainerProperty* asContainer(); bool isChangeTypeSet(int type)const; void clearChangeType(); void setChangeType(int type, bool on=true); void setFullRefreshBit(); void setCacheRefreshBit(); ossimPropertyChangeType getChangeType()const; bool isFullRefresh()const; bool isCacheRefresh()const; bool isChangeTypeSpecified()const; bool affectsOthers()const; virtual void setReadOnlyFlag(bool flag); bool getReadOnlyFlag()const; bool isReadOnly()const; void setModifiedFlag(bool flag); bool getModifiedFlag()const; bool isModified()const; void clearModifiedFlag(); void setDescription(const ossimString& description); virtual ossimString getDescription()const; virtual ossimRefPtr toXml()const; virtual void saveState(ossimKeywordlist& kwl, const ossimString& prefix = "")const; virtual void accept(ossimVisitor& visitor); protected: virtual ~ossimProperty(); ossimString theName; ossimString theDescription; bool theReadOnlyFlag; ossimPropertyChangeType theChangeType; bool theModifiedFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimPropertyEvent.h000066400000000000000000000005721352751253100234600ustar00rootroot00000000000000#ifndef ossimPropertyEvent_HEADER #define ossimPropertyEvent_HEADER #include class OSSIMDLLEXPORT ossimPropertyEvent : public ossimEvent { public: ossimPropertyEvent(ossimObject* object) // the event id :ossimEvent(object, OSSIM_EVENT_PROPERTY_ID) {} virtual ossimObject* dup()const{return new ossimPropertyEvent(*this);} }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimPropertyInterface.h000066400000000000000000000024661352751253100243030ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // LICENSE: MIT see top level license.txt // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimPropertyInterface.h 12989 2008-06-04 17:05:41Z gpotts $ #ifndef ossimPropertyInterface_HEADER #define ossimPropertyInterface_HEADER #include #include #include #include class OSSIM_DLL ossimPropertyInterface { public: ossimPropertyInterface() {} virtual ~ossimPropertyInterface() {} virtual void setProperty(const ossimString& name, const ossimString& value); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual ossimString getPropertyValueAsString(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; void getPropertyList(std::vector >& propertyList)const; void setProperties(std::vector >& propertyList); protected: TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimPropertyInterfaceFactory.h000066400000000000000000000015431352751253100256260ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimPropertyInterfaceFactory.h 14789 2009-06-29 16:48:14Z dburken $ #ifndef ossimPropertyInterfaceFactory_HEADER #define ossimPropertyInterfaceFactory_HEADER #include #include class ossimObject; class ossimPropertyInterface; class OSSIMDLLEXPORT ossimPropertyInterfaceFactory : public ossimObjectFactory { public: ossimPropertyInterfaceFactory() :ossimObjectFactory() {} virtual ~ossimPropertyInterfaceFactory() {} virtual ossimPropertyInterface* createInterface( const ossimObject* obj ) const = 0; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimPropertyInterfaceRegistry.h000066400000000000000000000033211352751253100260230ustar00rootroot00000000000000#ifndef ossimPropertyInterfaceRegistry_HEADER #define ossimPropertyInterfaceRegistry_HEADER #include class ossimPropertyInterfaceFactory; class ossimPropertyInterface; #include #include class OSSIMDLLEXPORT ossimPropertyInterfaceRegistry : public ossimObjectFactory { public: virtual ~ossimPropertyInterfaceRegistry(); static ossimPropertyInterfaceRegistry* instance(); virtual ossimPropertyInterface* createInterface( const ossimObject* obj ) const; /*! * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const; bool addFactory( ossimPropertyInterfaceFactory* factory ); bool registerFactory(ossimPropertyInterfaceFactory* factory); protected: ossimPropertyInterfaceRegistry() :ossimObjectFactory() {} ossimPropertyInterfaceRegistry( const ossimPropertyInterfaceRegistry& rhs ) :ossimObjectFactory(rhs) {} void operator =(const ossimPropertyInterfaceRegistry&){} static ossimPropertyInterfaceRegistry* theInstance; std::vector theFactoryList; TYPE_DATA }; extern "C" { OSSIMDLLEXPORT void* ossimPropertyInterfaceRegistryGetInstance(); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimProtocolStream.h000066400000000000000000000013431352751253100236040ustar00rootroot00000000000000#ifndef ossimProtocolStream_HEADER #define ossimProtocolStream_HEADER #include class ossimProtocolStream : public ossimStreamBase { public: ossimProtocolStream(){} ossimProtocolStream(std::streambuf* buf):ossimStreamBase(buf) { } /** * This is a generic interface to any stream for opening and closing * If supported this could be an interface to not only file streams * but also http, https, ftp, ... etc */ virtual void open(const char* protocolString, int openMode=0)=0; /** * Closes the stream */ virtual void close()=0; virtual bool is_open()const=0; virtual bool isCompressed()const=0; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimQuadTreeWarp.h000066400000000000000000000221721352751253100231760ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimQuadTreeWarp.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimQuadTreeWarp_HEADER #define ossimQuadTreeWarp_HEADER #include #include #include #include #include #include #include #include class ossimQuadTreeWarpNode; class OSSIMDLLEXPORT ossimQuadTreeWarpVertex { public: friend std::ostream& operator<<(std::ostream& out, const ossimQuadTreeWarpVertex& rhs); ossimQuadTreeWarpVertex(const ossimDpt& position=ossimDpt(0,0), const ossimDpt& delta=ossimDpt(0,0)); ~ossimQuadTreeWarpVertex(); void setPosition(const ossimDpt& position); void setDelta(const ossimDpt& delta); const ossimDpt& getDelta()const; const ossimDpt& getPosition()const; void addSharedNode(ossimQuadTreeWarpNode* node); void removeNode(ossimQuadTreeWarpNode* node); bool isShared()const; bool saveState(ossimKeywordlist& kwl, const char* prefix)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix); std::vector theSharedNodeList; ossimDpt thePosition; ossimDpt theDelta; bool theLockedFlag; }; class ossimQuadTreeWarpNode { public: friend std::ostream& operator <<(std::ostream& out, const ossimQuadTreeWarpNode& rhs); ossimQuadTreeWarpNode(); ossimQuadTreeWarpNode(const ossimDrect& bounds, ossimQuadTreeWarpNode* parent=NULL, ossimQuadTreeWarpVertex* ulVertex=(ossimQuadTreeWarpVertex*)NULL, ossimQuadTreeWarpVertex* urVertex=(ossimQuadTreeWarpVertex*)NULL, ossimQuadTreeWarpVertex* lrVertex=(ossimQuadTreeWarpVertex*)NULL, ossimQuadTreeWarpVertex* llVertex=(ossimQuadTreeWarpVertex*)NULL); ~ossimQuadTreeWarpNode(); bool hasValidVertices()const; void removeVertex(ossimQuadTreeWarpVertex* v); void removeVertices(); bool isLeaf()const; void clear(); void removeChild(ossimQuadTreeWarpNode* node); bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); ossimDrect theBoundingRect; ossimQuadTreeWarpVertex* theUlVertex; ossimQuadTreeWarpVertex* theUrVertex; ossimQuadTreeWarpVertex* theLrVertex; ossimQuadTreeWarpVertex* theLlVertex; ossimQuadTreeWarpNode* theParent; std::vector theChildren; }; class ossimQuadTreeWarp : public ossim2dTo2dTransform { public: friend std::ostream& operator<<(std::ostream& out, const ossimQuadTreeWarp& rhs); ossimQuadTreeWarp(); ossimQuadTreeWarp(const ossimDrect& boundingRect, const ossimDpt& ulShift=ossimDpt(0,0), const ossimDpt& urShift=ossimDpt(0,0), const ossimDpt& lrShift=ossimDpt(0,0), const ossimDpt& llShift=ossimDpt(0,0)); ossimQuadTreeWarp(const ossimQuadTreeWarp& rhs); virtual ossimObject* dup()const; virtual ossimDpt getOrigin()const; void create(const ossimDrect& boundingRect, const ossimDpt& ulShift=ossimDpt(0,0), const ossimDpt& urShift=ossimDpt(0,0), const ossimDpt& lrShift=ossimDpt(0,0), const ossimDpt& llShift=ossimDpt(0,0)); /*! * Will warp the passed in point and placed the warped value in result */ virtual void forward(const ossimDpt& pt, ossimDpt& result)const; /*! * Will warp the passed in point and overwrite it */ virtual void forward(ossimDpt& pt)const; // void inverse(const ossimDpt& input, // ossimDpt& output) const; virtual std::ostream& print(std::ostream& out) const; virtual void printVertices(std::ostream& out)const; ossimQuadTreeWarpNode* getRoot(); const ossimQuadTreeWarpNode* getRoot()const; bool isEmpty()const; ossimQuadTreeWarpVertex* findClosestVertex(ossimDpt& position); /*! * This method will go through the tree and try to locate the * vertex. This is faster sine the tree is sorted. Use * the getVertex to just search the internal shared vertex list. */ ossimQuadTreeWarpVertex* findVertex(const ossimDpt& position); /*! * Searches the shared vetex list. This will not go through the tree. * this is needed for load states to perform correctly. */ ossimQuadTreeWarpVertex* getVertex(const ossimDpt& position); /*! * Will get the shift or delta value for the passed in pt. */ void getShift(ossimDpt& result, const ossimDpt& pt)const; /*! * The initial passed in node must not be a leaf. It will * turn the passed in node into a leaf by recursively * pruning its children. */ void pruneTree(ossimQuadTreeWarpNode* node); // Search methods ossimQuadTreeWarpNode* findNode(const ossimDpt& pt); const ossimQuadTreeWarpNode* findNode(const ossimDpt& pt)const; /*! * Will get the shift or delta value for the passed in pt. */ ossimDpt getShift(const ossimDpt& pt)const; void clear(); void split(const ossimDpt& point, double splitHoriCoefficient=0.0, double splitVertCoefficient=0.0); /*! * The passed in node is suppose to be a leaf node. * it splits the leaf node horizontally and vertically * by the passed in percentage. Use find node to * find the leaf node of a given point */ void split(ossimQuadTreeWarpNode* node, double splitHoriCoefficient=.5, double splitVertCoefficient=.5); const ossimQuadTreeWarpNode* findNode(const ossimQuadTreeWarpNode* node, const ossimDpt& pt)const; ossimQuadTreeWarpNode* findNode(ossimQuadTreeWarpNode* node, const ossimDpt& pt); void findAllNodes(std::vector& result, const ossimDpt& pt); void findAllNodes(std::vector& result, const ossimDpt& pt)const; void findAllNodes(std::vector& result, ossimQuadTreeWarpNode* node, const ossimDpt& pt); void findAllNodes(std::vector& result, ossimQuadTreeWarpNode* node, const ossimDpt& pt)const; bool isOnEdge(ossimQuadTreeWarpNode* node, const ossimDpt& point)const; bool isOnPoint(ossimQuadTreeWarpNode* node, const ossimDpt& point)const; void updateAllVericeLockFlags(); const std::vector& getVertices()const; void setWarpEnabledFlag(bool flag); void setToIdentity(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimQuadTreeWarp(); bool theWarpEnabledFlag; ossimQuadTreeWarpNode* theTree; std::vector theVertexList; void getShift(ossimDpt& result, const ossimQuadTreeWarpNode* node, const ossimDpt& pt)const; void recursivePruneTree(ossimQuadTreeWarpNode* node); void pruneSharedVertices(); void removeSharedVertex(ossimQuadTreeWarpVertex* v); void recursivePrint(std::ostream& out, ossimQuadTreeWarpNode* node)const; void recursiveDelete(ossimQuadTreeWarpNode* node); void getNewQuads(ossimQuadTreeWarpNode* parent, const ossimDrect& ul, const ossimDrect& ur, const ossimDrect& lr, const ossimDrect& ll, ossimQuadTreeWarpNode*& ulNode, ossimQuadTreeWarpNode*& urNode, ossimQuadTreeWarpNode*& lrNode, ossimQuadTreeWarpNode*& llNode); void updateLockFlag(ossimQuadTreeWarpVertex* v); void updateDelta(ossimQuadTreeWarpVertex* v); bool recursiveSave(ossimQuadTreeWarpNode* node, ossimKeywordlist& kwl, const char* prefix)const; bool recursiveLoad(ossimQuadTreeWarpNode* node, const ossimKeywordlist& kwl, const char* prefix); // bool resetAllSharedLists(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimQuadrilateralMap.h000066400000000000000000000031471352751253100240630ustar00rootroot00000000000000#ifndef ossimQuadrilateralMap_HEADER #define ossimQuadrilateralMap_HEADER #include class OSSIMDLLEXPORT ossimQuadrilateralMap { public: ossimQuadrilateralMap(const ossimDpt& sourceP1, const ossimDpt& sourceP2, const ossimDpt& sourceP3, const ossimDpt& sourceP4, const ossimDpt& destP1, const ossimDpt& destP2, const ossimDpt& destP3, const ossimDpt& destP4); ossimQuadrilateralMap(); ossimQuadrilateralMap(const ossimQuadrilateralMap& rhs); /*! * Uses a standard form of quadrilateral to quadrilateral * mapping: * * X = (a*U + b*V + c) / (g*U + h*V + 1) * Y = (d*U + e*V+f)/(g*U + h*V + 1) * * where: * X and Y are the mapped destination point. * U and V are the source point to warp * a, b, c, d, e, f, g, h are coefficients sovled by * the points passed to the constructor. */ void map(const ossimDpt& source, ossimDpt& dest)const; void solveCoefficients(const ossimDpt& sourceP1, const ossimDpt& sourceP2, const ossimDpt& sourceP3, const ossimDpt& sourceP4, const ossimDpt& destP1, const ossimDpt& destP2, const ossimDpt& destP3, const ossimDpt& destP4); protected: double a; double b; double c; double d; double e; double f; double g; double h; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimQuaternion.h000066400000000000000000000343201352751253100227550ustar00rootroot00000000000000#ifndef ossimQuaternion_HEADER #define ossimQuaternion_HEADER 1 #include #include #include #include class ossimMatrix4x4; namespace ossim { /** A quaternion class. It can be used to represent an orientation in 3D space.*/ class OSSIM_DLL Quaternion { public: typedef ossim_float64 value_type; value_type theVector[4]; // a four-vector inline Quaternion() { theVector[0]=0.0; theVector[1]=0.0; theVector[2]=0.0; theVector[3]=1.0; } inline Quaternion( value_type x, value_type y, value_type z, value_type w ) { theVector[0]=x; theVector[1]=y; theVector[2]=z; theVector[3]=w; } /* inline Quaternion( const Vec4f& v ) */ /* { */ /* theVector[0]=v.x(); */ /* theVector[1]=v.y(); */ /* theVector[2]=v.z(); */ /* theVector[3]=v.w(); */ /* } */ /* inline Quaternion( const Vec4d& v ) */ /* { */ /* theVector[0]=v.x(); */ /* theVector[1]=v.y(); */ /* theVector[2]=v.z(); */ /* theVector[3]=v.w(); */ /* } */ inline Quaternion(ossim_float64 angle, const ossimDpt3d& axis) { makeRotate(angle,axis); } inline Quaternion(ossim_float64 angle, const ossimColumnVector3d& axis) { makeRotate(angle,axis); } /* inline Quaternion( value_type angle, const Vec3d& axis) */ /* { */ /* makeRotate(angle,axis); */ /* } */ /* inline Quaternion( value_type angle1, const Vec3f& axis1, */ /* value_type angle2, const Vec3f& axis2, */ /* value_type angle3, const Vec3f& axis3) */ /* { */ /* makeRotate(angle1,axis1,angle2,axis2,angle3,axis3); */ /* } */ /* inline Quaternion( value_type angle1, const Vec3d& axis1, */ /* value_type angle2, const Vec3d& axis2, */ /* value_type angle3, const Vec3d& axis3) */ /* { */ /* makeRotate(angle1,axis1,angle2,axis2,angle3,axis3); */ /* } */ inline Quaternion& operator = (const Quaternion& v) { theVector[0]=v.theVector[0]; theVector[1]=v.theVector[1]; theVector[2]=v.theVector[2]; theVector[3]=v.theVector[3]; return *this; } inline bool operator == (const Quaternion& v) const { return theVector[0]==v.theVector[0] && theVector[1]==v.theVector[1] && theVector[2]==v.theVector[2] && theVector[3]==v.theVector[3]; } inline bool operator != (const Quaternion& v) const { return theVector[0]!=v.theVector[0] || theVector[1]!=v.theVector[1] || theVector[2]!=v.theVector[2] || theVector[3]!=v.theVector[3]; } inline bool operator < (const Quaternion& v) const { if (theVector[0]v.theVector[0]) return false; else if (theVector[1]v.theVector[1]) return false; else if (theVector[2]v.theVector[2]) return false; else return (theVector[3] #include #include class ossimPolygon; class ossimPolyLine; class ossimIrect; class OSSIMDLLEXPORT ossimROIEvent : public ossimEvent { public: ossimROIEvent( ossimObject* object=NULL, long id=OSSIM_EVENT_NULL_ID ); ossimROIEvent( const ossimROIEvent& rhs ); virtual ossimObject* dup() const; enum ossimRegionType { OSSIM_RECTANGLE_ROI = 0, OSSIM_POLYGON_ROI = 1, OSSIM_POLYLINE_ROI = 2 }; const std::vector& getPoints()const; void getPoint(std::vector& points)const ; void setPoints( const std::vector& points ); void setRect(const ossimIrect& rect); void setEventType( ossimRegionType eventType ); ossimRegionType getEventType()const; void setTypeToPolygon(); void setTypeToRectangle(); void setTypeToPolyline(); bool isRectangleRegion()const; bool isPolygonRegion()const; bool isPolylineRegion()const; void getRect(ossimIrect& rect)const; void getPolygon(ossimPolygon& polygon)const; void getPolyLine(ossimPolyLine& polyline)const; /** * @param flag If true indicates region of interest is moving and size is * not to change. */ void setMovingFlag(bool flag); /** * @return Returns theMoving flag. If true indicates region of interest * is moving and size is not to change. */ bool getMovingFlag() const; protected: std::vector thePoints; ossimRegionType theType; // Indicates moving so keep the same size on a redraw. bool theMovingFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimROIEventListener.h000066400000000000000000000010771352751253100237740ustar00rootroot00000000000000#ifndef ossimROIEventListener_HEADER #define ossimROIEventListener_HEADER #include #include #include class OSSIMDLLEXPORT ossimROIEventListener : public ossimListener { public: ossimROIEventListener() { } virtual void processEvent(ossimEvent& event); virtual void handleRectangleROIEvent( ossimROIEvent& event ); virtual void handlePolygonROIEvent( ossimROIEvent& event ); virtual void handlePolylineROIEvent( ossimROIEvent& event ); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimRationalNumber.h000066400000000000000000000127111352751253100235520ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimRationalNumber.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimRationalNumber_HEADER #define ossimRationalNumber_HEADER #include #include #include class OSSIMDLLEXPORT ossimRationalNumber { public: friend std::ostream& operator<<(std::ostream& out, const ossimRationalNumber& rhs) { out<(theNum)/ static_cast(theDen)); } float toFloat()const { return (static_cast(theNum)/ static_cast(theDen)); } void normalize(); const ossimRationalNumber& operator=(ossim_int32 n) { return assign(n, 1); } const ossimRationalNumber& operator=(double n) { return assign(n); } ossimRationalNumber operator-()const { return ossimRationalNumber(-theNum, theDen); } const ossimRationalNumber& operator+= (const ossimRationalNumber& r); const ossimRationalNumber& operator-= (const ossimRationalNumber& r); const ossimRationalNumber& operator*= (const ossimRationalNumber& r); const ossimRationalNumber& operator/= (const ossimRationalNumber& r); inline const ossimRationalNumber& operator+= (ossim_int32 i); inline const ossimRationalNumber& operator-= (ossim_int32 i); inline const ossimRationalNumber& operator*= (ossim_int32 i); inline const ossimRationalNumber& operator/= (ossim_int32 i); ossimRationalNumber operator+ (const ossimRationalNumber& r)const; ossimRationalNumber operator- (const ossimRationalNumber& r)const; ossimRationalNumber operator* (const ossimRationalNumber& r)const; ossimRationalNumber operator/ (const ossimRationalNumber& r)const; inline ossimRationalNumber operator+ (ossim_int32 i)const; inline ossimRationalNumber operator- (ossim_int32 i)const; inline ossimRationalNumber operator* (ossim_int32 i)const; inline ossimRationalNumber operator/ (ossim_int32 i)const; friend inline ossimRationalNumber operator+ (ossim_int32 i, ossimRationalNumber& r); friend inline ossimRationalNumber operator- (ossim_int32 i, ossimRationalNumber& r); friend inline ossimRationalNumber operator* (ossim_int32 i, ossimRationalNumber& r); friend inline ossimRationalNumber operator/ (ossim_int32 i, ossimRationalNumber& r); // Comparison operators // inline bool operator< (const ossimRationalNumber& r) const; inline bool operator== (const ossimRationalNumber& r) const; inline bool operator== (ossim_int32 i) const; // Increment and decrement inline const ossimRationalNumber& operator++(); inline const ossimRationalNumber& operator--(); // Assign in place inline const ossimRationalNumber& assign(ossim_int32 n, ossim_int32 d); /*! * default estimation is out to the 10000 place. Will set this * rational to a value that is close to the passed in number. */ const ossimRationalNumber& assign(double value, long precision=10000); /*! * Holds the value of the numberator. */ ossim_int32 theNum; /*! * Holds the value of the denominator. */ ossim_int32 theDen; }; inline const ossimRationalNumber& ossimRationalNumber::assign(ossim_int32 n, ossim_int32 d) { theNum = n; theDen = d; normalize(); return *this; } // Mixed-mode operators inline ossimRationalNumber ossimRationalNumber::operator+(ossim_int32 i)const { return operator + (ossimRationalNumber(i)); } inline ossimRationalNumber ossimRationalNumber::operator-(ossim_int32 i)const { return operator - (ossimRationalNumber(i)); } inline ossimRationalNumber ossimRationalNumber::operator*(ossim_int32 i)const { return operator * (ossimRationalNumber(i)); } inline ossimRationalNumber ossimRationalNumber::operator/(ossim_int32 i)const { return operator / (ossimRationalNumber(i)); } inline ossimRationalNumber operator+ (ossim_int32 i, ossimRationalNumber& r) { return ossimRationalNumber(i)+r; } inline ossimRationalNumber operator- (ossim_int32 i, ossimRationalNumber& r) { return ossimRationalNumber(i)-r; } inline ossimRationalNumber operator* (ossim_int32 i, ossimRationalNumber& r) { return ossimRationalNumber(i)*r; } inline ossimRationalNumber operator/ (ossim_int32 i, ossimRationalNumber& r) { return ossimRationalNumber(i)/r; } inline const ossimRationalNumber& ossimRationalNumber::operator++() { theNum += theDen; return *this; } inline const ossimRationalNumber& ossimRationalNumber::operator--() { theNum -= theDen; return *this; } inline bool ossimRationalNumber::operator== (const ossimRationalNumber& r)const { return ((theNum == r.theNum) && (theDen == r.theDen)); } inline bool ossimRationalNumber::operator== (ossim_int32 i) const { return ((theDen == ossim_int32(1)) && (theNum == i)); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimRectanglePartitioner.h000066400000000000000000000111421352751253100247520ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (C) 2004 David Burken, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // Utility class to partition up a rectangle. // // $Id: ossimRectanglePartitioner.h 9094 2006-06-13 19:12:40Z dburken $ //---------------------------------------------------------------------------- #ifndef ossimRectanglePartitioner_HEADER #define ossimRectanglePartitioner_HEADER #include #include class ossimIrect; /** * class ossimRectanglePartitioner * Utility class to partition up a rectangle. */ class OSSIMDLLEXPORT ossimRectanglePartitioner { public: /** default construtor */ ossimRectanglePartitioner(); /** destructor */ ~ossimRectanglePartitioner(); /** * Partitions the rectangle doing a binary split on the longest dimension * until the total size is less than or equal to the "maxSizeInBytes". * Initializes "result" with the resulting rectangles starting at the * upper left corner. * * @param inputRectangle The source rectangle usually the bounding rectangle * of a scene. * * @param result The vector of ossimIrects to hold the result. * * @param maxSizeInBytes Maximum size of the resulting rectangle partitions * in bytes. * * @param bands The number of bands in the image. * * @param bytesPerPixel. The number of bytes per pixel for a single band. * * @param internalOverlapPixels Overlap in pixels for desired partitions. * (default = 0) This is added to all four sides of the rectangle so * * @note The result rectangle passed in will be cleared for starters. * * @note Edge rectangles will be clipped to the inputRectangle. */ void binaryPartition(const ossimIrect& inputRectangle, std::vector& result, ossim_uint64 maxSizeInBytes, ossim_uint32 bands, ossim_uint32 bytesPerPixel, ossim_uint32 internalOverlapPixels = 0) const; private: /** * Recursively splits the input rectangle until the size is less than * or equal to maxSizeInBytes. * * @param rect Input rectangle to split. * * @param maxSizeInBytes Maximum size of the resulting rectangle partitions * in bytes. * * @param bands The number of bands in the image. * * @param bytesPerPixel. The number of bytes per pixel for a single band. * * @param internalOverlapPixels Overlap in pixels for desired partitions. * (default = 0) * * @note Will split the longest dimension. If square will split in the * lengthwise direction. */ void splitUntilLessThanMax(ossimIrect& rect, ossim_uint64 maxSizeInBytes, ossim_uint32 bands, ossim_uint32 bytesPerPixel, ossim_uint32 internalOverlapPixels = 0) const; /** * Splits rectangle in half rounding up if needed. * * @param input Rectangle to split. * * @note output will be a zero base rect. * * @notes Will split the longest dimension. If square will split in the * lengthwise direction. */ void splitRect(ossimIrect& rect) const; /** * @param rect Rectangle to give size for in bytes. * * @param bands The number of bands in the image. * * @param bytesPerPixel. The number of bytes per pixel for a single band. * * @param internalOverlapPixels Overlap in pixels. * (default = 0) * * @return size of rectangle in bytes. */ ossim_uint64 getSize(const ossimIrect& rect, ossim_uint32 bands, ossim_uint32 bytesPerPixel, ossim_uint32 internalOverlapPixels = 0) const; /** * Convenience trace method. * * @param r Input rectangle. * * @param v Vector of resulting partitioned rectangles. * * @param maxSizeInBytes Maximum size of the resulting rectangle partitions * in bytes. * * @param bands The number of bands in the image. * * @param bytesPerPixel. The number of bytes per pixel for a single band. */ void trace(const ossimIrect& r, const std::vector& v, ossim_uint64 maxSizeInBytes, ossim_uint32 bands, ossim_uint32 bytesPerPixel) const; }; #endif /* End of "#ifndef ossimRectanglePartitioner_HEADER" */ ossim-Miami-2.9.1/include/ossim/base/ossimRectilinearDataObject.h000066400000000000000000000127521352751253100250170ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRectilinearDataObject.h 22828 2014-07-11 15:56:19Z dburken $ #ifndef ossimRectilinearDataObject_HEADER #define ossimRectilinearDataObject_HEADER #include class OSSIMDLLEXPORT ossimRectilinearDataObject : public ossimDataObject { public: /** default constructor */ ossimRectilinearDataObject(); ossimRectilinearDataObject(const ossimRectilinearDataObject&rhs); ossimRectilinearDataObject(ossim_uint64 numberOfSpatialComponents, ossimSource *owner, ossim_uint64 numberOfDataComponents, ossimScalarType scalarType = OSSIM_SCALAR_UNKNOWN, ossimDataObjectStatus status = OSSIM_NULL); /** * This is a helper constructor that allows one to instantiate a one * dimensional Spatial component with N number of data components. * It will internally allocate theSpatialExtent to 1 and set the * contents equal to the value passed in to length. */ ossimRectilinearDataObject(ossimSource *owner, ossim_uint64 numberOfDataComponents, ossim_uint64 length, ossimScalarType scalarType = OSSIM_SCALAR_UNKNOWN, ossimDataObjectStatus status = OSSIM_NULL); /** * This is a helper constructor that allows one to instantiate a two * dimensional Spatial component (WidthxHeight) with N number of * data components. It will internally allocate theSpatialExtent * to 2 and set the contents equal to the value passed in to width, and * height. */ ossimRectilinearDataObject(ossimSource *owner, ossim_uint64 numberOfDataComponents, ossim_uint64 width, ossim_uint64 height, ossimScalarType scalarType = OSSIM_SCALAR_UNKNOWN, ossimDataObjectStatus status = OSSIM_NULL); /** * This is a helper constructor that allows one to instantiate a two * dimensional Spatial component (WidthxHeightxDepth) with N number of * data components. It will internally allocate theSpatialExtent * to 3 and set the contents equal to the value passed in to width, * height, and depth. */ ossimRectilinearDataObject(ossimSource *owner, ossim_uint64 numberOfDataComponents, ossim_uint64 width, ossim_uint64 height, ossim_uint64 depth, ossimScalarType scalarType = OSSIM_SCALAR_UNKNOWN, ossimDataObjectStatus status = OSSIM_NULL); virtual ~ossimRectilinearDataObject(); /** * How many components make up this data object. For * example: If this were an RGB image data object then * the number of components would be set to 3 and the * RGB would be seen as a single data object being * passed through. */ virtual void setNumberOfDataComponents(ossim_uint64 n); virtual void setSpatialExtents(ossim_uint64 *extents, ossim_uint64 size); /** * See ossimScalarType in ossimConstants for a full list * * OSSIM_SCALAR_UNKNOWN * OSSIM_UCHAR Unsigned char * OSSIM_USHORT16 16bit unsigned short * OSSIM_SSHORT16 16bit signed short * OSSIM_USHORT11 11bit unsigned short * OSSIM_FLOAT float * OSSIM_NORMALIZED_DOUBLE normalized 0 to 1 data */ virtual void setScalarType(ossimScalarType type); virtual ossim_uint64 getNumberOfDataComponents() const; virtual ossim_uint64 getNumberOfSpatialComponents() const; virtual const ossim_uint64 *getSpatialExtents() const; virtual ossimScalarType getScalarType() const; virtual ossim_uint64 getScalarSizeInBytes() const; virtual void* getBuf(); virtual const void* getBuf() const; virtual void assign(const ossimRectilinearDataObject* data); /** * Initializes m_dataBuffer to current spatial extents. * * @notes * * 1) The underlying std::vector::resize() call with only be performed if * m_dataBuffer.size() is not equal to getDataSizeInBytes(). * * 2) The status will be set to OSSIM_STATUS_UNKNOWN if a resize was * performed. * * 3) On error: catches std::bad_alloc exception and rethrows as * ossimException. */ virtual void initialize(); virtual ossim_uint64 computeSpatialProduct() const; virtual ossim_uint64 getDataSizeInBytes()const; virtual std::ostream& print(std::ostream& out) const; /** * @brief assignment operator= * @param rhs The data to assign from. * @param A reference to this object. */ virtual const ossimRectilinearDataObject& operator=( const ossimRectilinearDataObject& rhs); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: ossim_uint64 m_numberOfDataComponents; ossimScalarType m_scalarType; std::vector m_dataBuffer; std::vector m_spatialExtents; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimRefPtr.h000066400000000000000000000100771352751253100220350ustar00rootroot00000000000000/* -*-c++-*- ossim - Copyright (C) since 2004 Garrett Potts * * This was taken directly from OpenSceneGraph and will retain OSGGPL license. * This is basically an MIT. * */ #ifndef ossimRefPtr_HEADER #define ossimRefPtr_HEADER #include #include #include template class ossimRefPtr { public: typedef T element_type; ossimRefPtr() :m_ptr(0) {} ossimRefPtr(T* t):m_ptr(t) { if (m_ptr) m_ptr->ref(); } ossimRefPtr(const ossimRefPtr& rp):m_ptr(rp.m_ptr) { if (m_ptr) m_ptr->ref(); } ~ossimRefPtr() { if (m_ptr) m_ptr->unref(); m_ptr=0; } inline ossimRefPtr& operator = (const ossimRefPtr& rp) { if (m_ptr==rp.m_ptr) return *this; T* tmpPtr = m_ptr; m_ptr = rp.m_ptr; if (m_ptr) m_ptr->ref(); // unref second to prevent any deletion of any object which might // be referenced by the other object. i.e rp is child of the // original _ptr. if (tmpPtr) tmpPtr->unref(); return *this; } inline ossimRefPtr& operator = (T* ptr) { if (m_ptr==ptr) return *this; T* tmpPtr = m_ptr; m_ptr = ptr; if (m_ptr) m_ptr->ref(); // unref second to prevent any deletion of any object which might // be referenced by the other object. i.e rp is child of the // original m_ptr. if (tmpPtr) tmpPtr->unref(); return *this; } // comparison operators for ossimRefPtr. inline bool operator < (const ossimRefPtr& rp) const { return (m_ptr (const ossimRefPtr& rp) const { return (m_ptr>rp.m_ptr); } // comparion operator for const T*. inline bool operator == (const T* ptr) const { return (m_ptr==ptr); } inline bool operator != (const T* ptr) const { return (m_ptr!=ptr); } inline bool operator < (const T* ptr) const { return (m_ptr (const T* ptr) const { return (m_ptr>ptr); } inline T& operator*() { return *m_ptr; } inline const T& operator*() const { return *m_ptr; } inline T* operator->() { return m_ptr; } inline const T* operator->() const { return m_ptr; } inline bool operator!() const { return m_ptr==0L; } inline bool valid() const { return m_ptr!=0L; } /** * Used in boolean expression. Example: "if (obj)" is same as "if (obj.valid())". This is * the same syntax as c++11 shared_ptr. */ explicit operator bool() const { return m_ptr == 0 ? false : true; } inline T* get() { return m_ptr; } inline const T* get() const { return m_ptr; } /** take control over the object pointed to by ref_ptr, unreference but do not delete even if ref count goes to 0, * return the pointer to the object. * Note, do not use this unless you are 100% sure your code handles the deletion of the object correctly, and * only use when absolutely required.*/ inline T* take() { return release();} inline T* release() { T* tmp=m_ptr; if (m_ptr) m_ptr->unref_nodelete(); m_ptr=0; return tmp;} private: T* m_ptr; }; // Copied from std::shared_ptr: template inline bool operator==(const ossimRefPtr<_Tp1>& __a, const ossimRefPtr<_Tp2>& __b) noexcept { return __a.get() == __b.get(); } template inline bool operator==(const ossimRefPtr<_Tp>& __a, std::nullptr_t) noexcept { return !__a; } template inline bool operator==(std::nullptr_t, const ossimRefPtr<_Tp>& __a) noexcept { return !__a; } template inline bool operator!=(const ossimRefPtr<_Tp1>& __a, const ossimRefPtr<_Tp2>& __b) noexcept { return __a.get() != __b.get(); } template inline bool operator!=(const ossimRefPtr<_Tp>& __a, std::nullptr_t) noexcept { return (bool)__a; } template inline bool operator!=(std::nullptr_t, const ossimRefPtr<_Tp>& __a) noexcept { return (bool)__a; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimReferenced.h000066400000000000000000000047261352751253100227010ustar00rootroot00000000000000/* -*-c++-*- libossim - Copyright (C) since 2004 Garrett Potts * LICENSE: MIT * Author: Garrett Potts */ #ifndef ossimReferenced_HEADER #define ossimReferenced_HEADER #include #include #include /** * ossimReferenced allows for shared object ref counting * if the reference count ever gets to 0 or less it will * delete 'this' object. * * Currently uses std::mutex to control the locking of the reference * count variable. * * Eventually we would like to replace all of ossimReferenced and ossimRefPtr * with C++11 std::shared_ptr */ class OSSIMDLLEXPORT ossimReferenced { public: ossimReferenced() : m_refCount(0) {} ossimReferenced(const ossimReferenced&) : m_refCount(0) {} inline ossimReferenced& operator = (const ossimReferenced&) { return *this; } /** * increment the reference count by one, indicating that * this object has another pointer which is referencing it. */ inline void ref() const; /** * decrement the reference count by one, indicating that * a pointer to this object is referencing it. If the * reference count goes to zero, it is assumed that this object * is no longer referenced and is automatically deleted. */ inline void unref() const; /** * decrement the reference count by one, indicating that * a pointer to this object is referencing it. However, do * not delete it, even if ref count goes to 0. Warning, unref_nodelete() * should only be called if the user knows exactly who will * be resonsible for, one should prefer unref() over unref_nodelete() * as the later can lead to memory leaks. */ inline void unref_nodelete() const { // std::lock_guard lock(theRefMutex); --m_refCount; } /** * @return the number pointers currently referencing this object. */ inline int referenceCount() const { return m_refCount.load(); } protected: virtual ~ossimReferenced(); private: mutable std::atomic_int m_refCount; }; inline void ossimReferenced::ref() const { ++m_refCount; } inline void ossimReferenced::unref() const { bool needDelete = false; { // fetch_sub should return the value before subtraction. // so if 1 was before the subtraction that means it should // be zero after the subtraction so we will test <=1 needDelete = m_refCount.fetch_sub(1) <= 1; } if (needDelete) { delete this; } } #endif ossim-Miami-2.9.1/include/ossim/base/ossimRefreshEvent.h000066400000000000000000000041011352751253100232220ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: A brief description of the contents of the file. // // //************************************************************************* // $Id: ossimRefreshEvent.h 19819 2011-07-14 17:28:48Z gpotts $ #ifndef ossimRefreshEvent_HEADER #define ossimRefreshEvent_HEADER #include #include class OSSIMDLLEXPORT ossimRefreshEvent : public ossimEvent { public: enum RefreshType { REFRESH_NONE = 0, REFRESH_POSITION = 1, REFRESH_PIXELS = 2, REFRESH_GEOMETRY = 4, REFRESH_ALL = (REFRESH_POSITION|REFRESH_PIXELS|REFRESH_GEOMETRY) }; enum PositionAnchor { ANCHOR_UPPER_LEFT = 1, ANCHOR_CENTER = 2 }; ossimRefreshEvent(ossimObject* object=0) // the object associated with the event if any :ossimEvent(object, OSSIM_EVENT_REFRESH_ID), m_refreshType(static_cast(REFRESH_PIXELS|REFRESH_GEOMETRY)), m_anchor(ANCHOR_CENTER) {m_position.makeNan();} ossimRefreshEvent(RefreshType refreshType, ossimObject* object=0) :ossimEvent(object, OSSIM_EVENT_REFRESH_ID), m_refreshType(refreshType), m_anchor(ANCHOR_CENTER) { m_position.makeNan(); } ossimRefreshEvent(const ossimRefreshEvent& src) :ossimEvent(src), m_refreshType(src.m_refreshType), m_position(src.m_position), m_anchor(src.m_anchor) { } virtual ossimObject* dup()const { return new ossimRefreshEvent(*this); } void setRefreshType(int refreshType, bool on=true); RefreshType getRefreshType()const{return m_refreshType;} void setPosition(const ossimDpt& position) { m_position = position; if(!m_position.hasNans())setRefreshType(REFRESH_POSITION); } const ossimDpt& getPosition()const{return m_position;} protected: RefreshType m_refreshType; ossimDpt m_position; PositionAnchor m_anchor; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimRegExp.h000066400000000000000000000171221352751253100220230ustar00rootroot00000000000000// // Copyright (C) 1991 Texas Instruments Incorporated. // // Permission is granted to any individual or institution to use, copy, modify, // and distribute this software, provided that this complete copyright and // permission notice is maintained, intact, in all copies and supporting // documentation. // // Texas Instruments Incorporated provides this software "as is" without // express or implied warranty. // // .NAME CoolRegExp - Pattern matching with regular expressions. // .LIBRARY cool // .HEADER String Classes // .INCLUDE cool/RegExp.h // .FILE cool/RegExp.C // .FILE cool/RegExp.h // .EXAMPLE examples/ex_RegExp.C // // // .SECTION Description // A regular expression allows a programmer to specify complex // patterns that can be searched for and matched against the // character string of a string object. In its simplest form, a // regular expression is a sequence of characters used to // search for exact character matches. However, many times the // exact sequence to be found is not known, or only a match at // the beginning or end of a string is desired. The cool regu- // lar expression class implements regular expression pattern // matching as is found and implemented in many UNIX commands // and utilities. // // The regular expression class provides a convenient mechanism // for specifying and manipulating regular expressions. The // regular expression object allows specification of such pat- // terns by using the following regular expression metacharac- // ters: // // ^ Matches at beginning of a line // // $ Matches at end of a line // // . Matches any single character // // [ ] Matches any character(s) inside the brackets // // [^ ] Matches any character(s) not inside the brackets // // - Matches any character in range on either side of a dash // // * Matches preceding pattern zero or more times // // + Matches preceding pattern one or more times // // ? Matches preceding pattern zero or once only // // () Saves a matched expression and uses it in a later match // // Note that more than one of these metacharacters can be used // in a single regular expression in order to create complex // search patterns. For example, the pattern [^ab1-9] says to // match any character sequence that does not begin with the // characters "ab" followed by numbers in the series one // through nine. #ifndef ossimRegExph #define ossimRegExph #include const int NSUBEXP = 10; class OSSIMDLLEXPORT ossimRegExp { public: inline ossimRegExp (); // ossimRegExp with program=NULL inline ossimRegExp (const char*); // ossimRegExp with compiled char* ossimRegExp (const ossimRegExp&); // Copy constructor inline ~ossimRegExp(); // Destructor void compile (const char*); // Compiles char* --> regexp bool find (const char*); // true if regexp in char* arg inline ossim_uint32 start() const; // Index to start of first find inline ossim_uint32 end() const; // Index to end of first find bool operator== (const ossimRegExp&) const; // Equality operator inline bool operator!= (const ossimRegExp&) const; // Inequality operator bool deep_equal (const ossimRegExp&) const; // Same regexp and state? inline bool is_valid() const; // true if compiled regexp inline void set_invalid(); // Invalidates regexp // awf added ossim_uint32 start(ossim_uint32 n) const; ossim_uint32 end(ossim_uint32 n) const; std::string match(ossim_uint32 n) const; private: const char* startp[NSUBEXP]; const char* endp[NSUBEXP]; char regstart; // Internal use only char reganch; // Internal use only const char* regmust; // Internal use only ossim_uint32 regmlen; // Internal use only char* program; ossim_uint32 progsize; const char* searchstring; // work variables mutable const char* regparse; mutable int regnpar; // () count. mutable char regdummy; mutable char* regcode; // Code-emit pointer; ®dummy = don't. mutable long regsize; // Code size. const char* reginput; // String-input pointer. const char* regbol; // Beginning of input, for ^ check. const char* *regstartp; // Pointer to startp array. const char* *regendp; // Ditto for endp. char* reg (int, int*); char* regbranch (int*); char* regpiece (int*); char* regatom (int*); char* regnode (char); const char* regnext (const char*); char* regnext (char*); void regc (unsigned char); void reginsert (char, char*); void regtail (char*, const char*); void regoptail (char*, const char*); int regtry (const char*, const char* *, const char* *, const char*); int regmatch (const char*); int regrepeat (const char*); #ifdef STRCSPN int strcspn (); #endif }; // ossimRegExp -- Creates an empty regular expression. inline ossimRegExp::ossimRegExp (): regstart(0), // Internal use only reganch(0), // Internal use only regmust(0), // Internal use only regmlen(0), // Internal use only program(0), progsize(0), searchstring(0), // work variables regparse(0), regnpar(0), // () count. regdummy(0), regcode(0), // Code-emit pointer; ®dummy = don't. regsize(0), // Code size. reginput(0), // String-input pointer. regbol(0), // Beginning of input, for ^ check. regstartp(0), // Pointer to startp array. regendp(0) // Ditto for endp. { } // ossimRegExp -- Creates a regular expression from string s, and // compiles s. inline ossimRegExp::ossimRegExp (const char* s) : regstart(0), // Internal use only reganch(0), // Internal use only regmust(0), // Internal use only regmlen(0), // Internal use only program(0), progsize(0), searchstring(0), // work variables regparse(0), regnpar(0), // () count. regdummy(0), regcode(0), // Code-emit pointer; ®dummy = don't. regsize(0), // Code size. reginput(0), // String-input pointer. regbol(0), // Beginning of input, for ^ check. regstartp(0), // Pointer to startp array. regendp(0) // Ditto for endp. { this->program = NULL; compile(s); } // ~ossimRegExp -- Frees space allocated for regular expression. inline ossimRegExp::~ossimRegExp () { //#ifndef WIN32 if(program) { delete [] this->program; this->program = 0; } //#endif } // Start -- inline ossim_uint32 ossimRegExp::start () const { return(this->startp[0] - searchstring); } // End -- Returns the start/end index of the last item found. inline ossim_uint32 ossimRegExp::end () const { return(this->endp[0] - searchstring); } // operator!= // inline bool ossimRegExp::operator!= (const ossimRegExp& r) const { return(!(*this == r)); } // is_valid -- Returns true if a valid regular expression is compiled // and ready for pattern matching. inline bool ossimRegExp::is_valid () const { return (this->program != NULL); } // set_invalid -- Invalidates regular expression. inline void ossimRegExp::set_invalid () { //#ifndef WIN32 delete [] this->program; //#endif this->program = NULL; } // -- Return start index of nth submatch. start(0) is the start of the full match. inline ossim_uint32 ossimRegExp::start(ossim_uint32 n) const { return this->startp[n] - searchstring; } // -- Return end index of nth submatch. end(0) is the end of the full match. inline ossim_uint32 ossimRegExp::end(ossim_uint32 n) const { return this->endp[n] - searchstring; } // -- Return nth submatch as a string. inline std::string ossimRegExp::match(ossim_uint32 n) const { return std::string(this->startp[n], this->endp[n] - this->startp[n]); } #endif // CoolRegExph ossim-Miami-2.9.1/include/ossim/base/ossimRgbLutDataObject.h000066400000000000000000000056171352751253100237570ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbLutDataObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimRgbLutDataObject_HEADER #define ossimRgbLutDataObject_HEADER #include #include #include class ossimKeywordlist; class OSSIMDLLEXPORT ossimRgbLutDataObject : public ossimObject { public: friend std::ostream& operator <<(std::ostream& out, const ossimRgbLutDataObject& lut); /*! * Will allocate 256 values for the color table */ ossimRgbLutDataObject(unsigned long numberOfEntries=0); ossimRgbLutDataObject(const ossimRgbLutDataObject& lut); virtual ossimObject* dup()const { return new ossimRgbLutDataObject(*this); } const ossimRgbVector& operator[](unsigned int index)const { return index #include class ossimJpegYCbCrVector; class ossimHsiVector; class ossimHsvVector; class ossimCmyVector; class OSSIMDLLEXPORT ossimRgbVector { public: friend std::ostream& operator <<(std::ostream& out, const ossimRgbVector& data) { out << "<" << (long)data.theBuf[0] << ", " << (long)data.theBuf[1] << ", " << (long)data.theBuf[2] << ">"; return out; } ossimRgbVector(unsigned char r=0, unsigned char g=0, unsigned char b=0) { theBuf[0] = r; theBuf[1] = g; theBuf[2] = b; } ossimRgbVector(const ossimRgbVector& copy_this) { theBuf[0] = copy_this.theBuf[0]; theBuf[1] = copy_this.theBuf[1]; theBuf[2] = copy_this.theBuf[2]; } ossimRgbVector(unsigned char grey) { theBuf[0] = grey; theBuf[1] = grey; theBuf[2] = grey; } ossimRgbVector(unsigned char colorData[3]) { theBuf[0] = colorData[0]; theBuf[1] = colorData[1]; theBuf[2] = colorData[2]; } ossimRgbVector(const ossimJpegYCbCrVector& YCbCr); ossimRgbVector(const ossimHsiVector& hsi); ossimRgbVector(const ossimHsvVector& hsv); ossimRgbVector(const ossimCmyVector& cmy); ossimRgbVector operator -(const ossimRgbVector& rgb)const { return ossimRgbVector((unsigned char)clamp((long)theBuf[0] - (long)rgb.theBuf[0]), (unsigned char)clamp((long)theBuf[1] - (long)rgb.theBuf[1]), (unsigned char)clamp((long)theBuf[2] - (long)rgb.theBuf[2])); } ossimRgbVector operator +(const ossimRgbVector& rgb)const { return ossimRgbVector((unsigned char)clamp((long)theBuf[0] + (long)rgb.theBuf[0]), (unsigned char)clamp((long)theBuf[1] + (long)rgb.theBuf[1]), (unsigned char)clamp((long)theBuf[2] + (long)rgb.theBuf[2])); } ossimRgbVector operator *(double t)const { return ossimRgbVector((unsigned char)clamp((long)(theBuf[0]*t)), (unsigned char)clamp((long)(theBuf[1]*t)), (unsigned char)clamp((long)(theBuf[2]*t))); } const ossimRgbVector& operator =(const ossimJpegYCbCrVector& data); const ossimRgbVector& operator =(const ossimHsiVector& hsi); const ossimRgbVector& operator =(const ossimHsvVector& hsv); const ossimRgbVector& operator =(const ossimCmyVector& cmy); bool operator ==(const ossimRgbVector& rgb) { return ( (rgb.theBuf[0] == theBuf[0])&& (rgb.theBuf[1] == theBuf[1])&& (rgb.theBuf[2] == theBuf[2])); } bool operator !=(const ossimRgbVector& rgb) { return ( (rgb.theBuf[0] != theBuf[0])|| (rgb.theBuf[1] != theBuf[1])|| (rgb.theBuf[2] != theBuf[2])); } static long clamp(long colorValue, unsigned char min=0, unsigned char max=255) { colorValue = colorValue > (long)max? (long)max:colorValue; colorValue = colorValue < (long)min? (long)min:colorValue; return colorValue; } unsigned char getR() const { return theBuf[0]; } unsigned char getG()const { return theBuf[1]; } unsigned char getB()const { return theBuf[2]; } void setR(unsigned char R) { theBuf[0] = R; } void setG(unsigned char G) { theBuf[1] = G; } void setB(unsigned char B) { theBuf[2] = B; } protected: unsigned char theBuf[3]; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimRtti.h000066400000000000000000000456571352751253100215710ustar00rootroot00000000000000#ifndef RTTI_H #define RTTI_H ///////////////////////////////////////////////////////////////////////////////////////// /* RTTI_H: This file provides support for RTTI and generalized (virtual-base to derived and separate hierarchy branches) casting. There is also support for RT obj creation from type names. In order to enable these features for a class, two things should be done: 1) insert the text TYPE_DATA (without ';') as the last item in the class-decl. 2) in the .C file where the class's implementation resides, insert the following (without';'): RTTI_DEF(classname,"RT classname") if the class has no bases with RTTI RTTI_DEFn(classname,"RT classname",b1,...bn) if the class has bases b1,...bn with RTTI Use RTTI_DEF_INST instead of RTTI_DEF if you want to enable RT obj creation for classname. You should provide then a public default ctor. RTTI is used via a class called RTTItypeid. A typeid describes a type of a class. typeids can be compared with operator== and operator!= and can be retrieved from classes/pointers. They should provide all necessary support for any kind of RTTI/casting, as described by the macros below (by RTTI-class we mean a class having RTTI, as described above). The 'return type' of the macros is listed between quotes: 'RTTItypeid' STATIC_TYPE_INFO(T) T=RTTI-class name. Returns a RTTItypeid with T's type. if T hasn't RTTI, a compile-time error occurs. 'RTTItypeid' TYPE_INFO(p) p=ptr to a RTTI-class. Returns the RTTItypeid of the class-obj p is really pointing at. If *p hasn't RTTI, a compile-time error occurs. If p==NULL, a special typeid for the NULL pointer is returned. This typeid has the name (const char*) "NULL". 'T*' PTR_CAST(T,p) T=RTTI-class, p=RTTI-class ptr. Returns p cast to the type T as a T*, if cast is possible, else returns NULL. If *p or T have no RTTI, a compile-time error occurs. Note that p can point to virtual base classes. Casting between separate branches of a class hierarchy is also supported, as long as all classes have RTTI. Therefore PTR_CAST is a fully general and safe operator. If p==NULL, the operator returns NULL. Some other macros. Not essential, provided mostly for convenience: ================= const char* STATIC_TYPE_NAME(T) T=RTTI-class name. Returns the name (const char*) of T's type. Provided for convenience. Compile-time error if T hasn't RTTI. const char* TYPE_NAME(p) p=RTTI-class ptr. Returns the class name (char*) of real *p. Provided for convenience. Compile-time error if *p hasn't RTTI. int If p==NULL, "NULL" is returned. DYN_CAST(t,p) t=RTTItypeid. p=RTTI-class ptr. Returns 1 if p can indeed be cast to t, else returns 0. Compile-time error if *p hasn't RTTI. If p==NULL, 1 is returned (NULL can be cast to anything). This operator is useful when we just want to check that a pointer can be cast to a RTTItypeid variable (which can be created/selected at run-time). For creating a RTTItypeid, construct a subclass of RTTItypeid called RTTIdyntypeid which allows construction from a const char*, i.e. from a user specification and pass it to DYN_CAST. DYN_TYPE can't return a typed pointer (since t is a RTTItypeid var and C++ has no 'real' type variables), but returns a 1/0 indicating whether the cast is possible or not. void* UPTR_CAST(t,p) t=RTTItypeid. p=RTTI-class ptr. Returns p cast to a void* if cast succeeds, else returns NULL. Again, p can point to virtual-bases and casts between separate branches of a class dag are supported. this operator is practically the 'untyped' version of PTR_CAST, offering the extra feature that the type is expressed by a run-time type variable (RTTItypeid). Compile-time error if *p hasn't RTTI. Obsolete macros: This set of macros is based on Stroustrup. They are not general and safe =============== (e.g. virtual-base to derived casts are trapped as compile-time errors and casts between separate class-dag branches are incorrectly done without any warnings). The above macros are including ALL functionality of these macros, which are provided only for completeness: OLD_PTR_CAST(T,p) Like PTR_CAST(T,p), but without accepting p=ptr to virtual bases and performing incorrect casts between separate branches of a class-dag. OLD_UPTR_CAST(t,p) Like UPTR_CAST(t,p), but with same problems as above. OLD_DYN_CAST(t,p) Like DYN_CAST(t,p), but with same problems as above. RT Object Creation: This feature enables the user to create objects of a RT-selected type in a generic manner. ================== Typically, we create/obtain a RT type (via a RTTItypeid t1). Then, having another RTTItypeid t2 (typically from the (STATIC_)TYPE_INFO of some ROOT class / ROOT* ptr, we call: ROOT* new_obj = (ROOT*)t2.create(t1); create() searches for t1 in the class DAG rooted at t2. If found, it creates a new obj of type t1 and returns it as a '(void*)(t2*)'. For example, we know above that we get a ROOT* since t2 is ROOT's RTTItypeid, so we can _safely_ cast the void* to ROOT. If create() can't make the t1 object (there's no such type or the type is not declared via RTTI_DEF_INST), it returns NULL. This gives a fully generic typeid-based factory method for RT obj creation. REMARK: RTTI support adds some additional info, both static+virtual, to a class. The current implementation ======= adds a static object and some static functions and 2 virtual functions to each class desiring RTTI. This may of course cause potential name-clash problems. In order to avoid this, all added identifiers in the RTTI system are prefixed with RTTI_ (see the TYPE_DATA macro). REMARK_2: There are two classes related to RTTI: RTTItypeid and RTTITypeinfo. A RTTItypeid is, as it says, an 'id for a type' ======== It actually wraps a RTTITypeinfo*, where a RTTITypeinfo contains the actual encoding of a class type. You can freely create/copy/destroy/manipulate RTTItypeid's, but you should NEVER deal directly with RTTITypeinfo. A RTTITypeinfo should actually be created ONLY by the TYPE_DATA macros, as part of a class definition, since the RTTITypeinfo encodes a type info for an EXISTING class. All type-related stuff should be therefore handled via RTTItypeid's. If you really want to dynamically create a dummy typeid, use RTTIdyntypeid class. REMARK 3: All names introduced by this RTTI implementation (RTTItypeid,RTTIdyntypeid,RTTITypeinfo,etc) ========= are prefixed by RTTI, to make this system easily acceptable by e.g. C++ environments which happen to already support typeids. */ ////////////////////////////////////////////////////////////// #include // for strdup,strcmp #include // for strdup,strcmp #include #include ///////////////////////////////////////////////////////////// class RTTITypeinfo; class OSSIMDLLEXPORT RTTItypeid { // Main class for RTTI interface. public: RTTItypeid(const RTTITypeinfo* p): theId(p) {} RTTItypeid(); int operator==(RTTItypeid) const; int operator!=(RTTItypeid) const; const RTTITypeinfo* get_info() const { return theId; } int can_cast(RTTItypeid) const; // 1 if the arg can be cast to this, else 0 const char* getname() const; int num_subclasses() const; // Return # subclasses of this RTTItypeid subclass(int) const; // Return ith subclass of this int num_baseclasses() const; // Return # baseclasses of this RTTItypeid baseclass(int) const; // Return ith baseclass of this void* create(RTTItypeid) const; // Tries to create an instance of a subclass of this // having of type given by the RTTItypeid arg. If ok, it returns it // casted to the class-type of this and then to void* int can_create() const; // Return 1 if this type is instantiable, else 0 RTTItypeid find_baseclass(const char* name)const;// static RTTItypeid null_type(); // the RTTItypeid for NULL ptrs protected: const RTTITypeinfo* theId; // RTTItypeid implementation (the only data-member) }; class OSSIMDLLEXPORT RTTIdyntypeid : public RTTItypeid //Class for dynamic type creation from user strings. { //Useful for creating typeids at RT for comparison public: //purposes. RTTIdyntypeid(const char*); ~RTTIdyntypeid(); private: static const RTTITypeinfo* a[]; }; /////////////////////////////////////////////////////////////////// class OSSIMDLLEXPORT RTTITypeinfo { //Implementation of type-related info public: typedef std::vector SubtypesConstVector; RTTITypeinfo(const char* name, const RTTITypeinfo* bb[], void* (*)(int,void*),void* (*)()); ~RTTITypeinfo(); const char* getname() const; //Returns name of this RTTITypeinfo int same(const RTTITypeinfo*) const; //Compares 2 RTTITypeinfo objs int can_cast(const RTTITypeinfo*) const; //1 if the arg can be cast to this, else 0 int has_base(const RTTITypeinfo*) const; //1 if this has the arg as some base, else 0 const RTTITypeinfo* subclass(int=0) const; //get i-th subclass of this, if any, else NULL int num_subclasses() const; //get # subclasses of this void* create(const RTTITypeinfo*,const char*) const; //search for a subclass named char*, //create obj of it and return it cast to //the RTTITypeinfo* type, which is either //this or a direct base of this. int can_create() const; //Returns 1 if this type has a default ctor, else 0 private: //char* n; //type name std::string n; const RTTITypeinfo** b; //base types (NULL-ended array of RTTITypeinfo's for this's direct bases) int ns; //#subtypes of this type SubtypesConstVector subtypes; //const RTTITypeinfo** subtypes; //types derived from this type static const RTTITypeinfo null_type; //convenience type info for a 'null' type void* (*new_obj)(); //func to create a new obj of this type void* (*cast)(int,void*); //func to cast an obj of this type to //ith baseclass of it or to itself void add_subtype(const RTTITypeinfo*);//adds a subtype to this's subtypes[] void del_subtype(const RTTITypeinfo*);//dels a subtype from this's subtypes[] friend class RTTItypeid; //for null_type }; inline int RTTITypeinfo::num_subclasses() const //Return # subclasses of this { return ns; } inline const RTTITypeinfo* RTTITypeinfo::subclass(int i) const //Return ith subclass of this, else NULL; { return (i>=0 && in.c_str()); //'physical' RTTITypeinfo (which should be the case, } //since we create them per-class and not per-obj). //If this fails, still do a textual name comaprison. inline int RTTITypeinfo::can_cast(const RTTITypeinfo* p) const { return same(p) || p->has_base(this); } inline int RTTITypeinfo::can_create() const { return new_obj!=0; } ///////////////////////////////////////////////////////////////// // // RTTItypeid methods: // inline RTTItypeid RTTItypeid::null_type() { return &(RTTITypeinfo::null_type); } inline RTTItypeid::RTTItypeid(): theId(null_type().theId) { } inline int RTTItypeid::operator==(RTTItypeid i) const { return theId->same(i.theId); } inline int RTTItypeid::operator!=(RTTItypeid i) const { return !(theId->same(i.theId)); } inline int RTTItypeid::can_cast(RTTItypeid i) const { return theId->can_cast(i.theId); } inline const char* RTTItypeid::getname() const { return theId->getname(); } inline int RTTItypeid::num_subclasses() const { return theId->num_subclasses(); } inline RTTItypeid RTTItypeid::subclass(int i) const { return theId->subclass(i); } inline int RTTItypeid::num_baseclasses() const { int i; for(i=0;theId->b[i];i++){} return i; } inline RTTItypeid RTTItypeid::baseclass(int i) const { return theId->b[i]; } inline void* RTTItypeid::create(RTTItypeid t) const { return theId->create(theId,t.getname()); } inline int RTTItypeid::can_create() const { return theId->can_create(); } //////////////////////////////////////////////////////////////////////////////// inline RTTIdyntypeid::RTTIdyntypeid(const char* c) : RTTItypeid(new RTTITypeinfo(c,a,0,0)) { } //create a dummy RTTITypeinfo inline RTTIdyntypeid::~RTTIdyntypeid() { if(theId) { delete theId; theId = 0; } } //delete the dummy RTTITypeinfo ///////////////////////////////////////////////////////////////////////////////////// // 1. Main operators #define STATIC_TYPE_INFO(T) T::RTTI_sinfo() #define TYPE_INFO(p) ((p)? (p)->RTTI_vinfo() : RTTItypeid::null_type() ) #define PTR_CAST(T,p) ((p)? (T*)((p)->RTTI_cast(STATIC_TYPE_INFO(T))) : 0) // 2. Convenience operators #define STATIC_TYPE_NAME(T) (STATIC_TYPE_INFO(T).getname()) #define TYPE_NAME(p) ((p)? ((p)->RTTI_vinfo().getname()) : RTTItypeid::null_type().getname()) #define DYN_CAST(t,p) ((p)? ((p)->RTTI_cast((t))!=0) : 1) #define UPTR_CAST(t,p) ((p)? ((p)->RTTI_cast((t))) : 0) // 3. Unsafe operators (see Stroustrup) #define OLD_PTR_CAST(T,p) ((p)? ((STATIC_TYPE_INFO(T).can_cast((p)->RTTI_vinfo()))? (T*)p : 0) : 0) #define OLD_UPTR_CAST(t,p) ((p)? ((t).can_cast((p)->RTTI_vinfo())? (void*)p : 0) : 0) #define OLD_DYN_CAST(t,p) ((p)? ((t).can_cast((p)->RTTI_vinfo())? 1 : 0) : 1) // Definition of TYPE_DATA for a RTTI-class: introduces one static RTTITypeinfo data-member // and a couple of virtuals. #define TYPE_DATA \ protected: \ static const RTTITypeinfo RTTI_obj; \ static void* RTTI_scast(int,void*); \ static void* RTTI_new(); \ public: \ virtual RTTItypeid RTTI_vinfo() const { return &RTTI_obj; }\ static RTTItypeid RTTI_sinfo() { return &RTTI_obj; }\ virtual void* RTTI_cast(RTTItypeid);\ virtual const void* RTTI_cast(RTTItypeid)const; // Definition of auxiliary data-structs supporting RTTI for a class: defines the static RTTITypeinfo // object of that class and its associated virtuals. // Auxiliary definition of the construction method: #define RTTI_NEW(cls,name) void* cls::RTTI_new() { return new cls; } \ const RTTITypeinfo cls::RTTI_obj = RTTITypeinfo(name,RTTI_base_##cls,cls::RTTI_scast,cls::RTTI_new); #define RTTI_NO_NEW(cls,name) const RTTITypeinfo cls::RTTI_obj = RTTITypeinfo(name,RTTI_base_##cls,cls::RTTI_scast,0); ////////////////////////////////////////////////////////////////// // // Top-level macros: // #define RTTI_DEF_BASE(cls,name) \ static const RTTITypeinfo* RTTI_base_##cls [] = { 0 };\ void* cls::RTTI_cast(RTTItypeid t) \ { \ if (t == &RTTI_obj) return this; \ return 0; \ } \ const void* cls::RTTI_cast(RTTItypeid t)const \ { \ if (t == &RTTI_obj) return this; \ return 0; \ } \ void* cls::RTTI_scast(int /* i */,void* p) \ { cls* ptr = (cls*)p; return ptr; } #define RTTI_DEF1_BASE(cls,name,b1) \ static const RTTITypeinfo* RTTI_base_##cls [] = \ { STATIC_TYPE_INFO(b1).get_info(),0 }; \ void* cls::RTTI_cast(RTTItypeid t) \ { \ if (t == &RTTI_obj) return this; \ void* ptr; \ if ((ptr=b1::RTTI_cast(t))) return ptr; \ return 0; \ } \ const void* cls::RTTI_cast(RTTItypeid t)const \ { \ if (t == &RTTI_obj) return this; \ const void* ptr; \ if ((ptr=b1::RTTI_cast(t))) return ptr; \ return 0; \ } \ void* cls::RTTI_scast(int i,void* p) \ { cls* ptr = (cls*)p; \ switch(i) \ { case 0: return (b1*)ptr; } \ return ptr; \ } #define RTTI_DEF2_BASE(cls,name,b1,b2) \ static const RTTITypeinfo* RTTI_base_##cls [] = \ { STATIC_TYPE_INFO(b1).get_info(), \ STATIC_TYPE_INFO(b2).get_info(),0 }; \ void* cls::RTTI_cast(RTTItypeid t) \ { \ if (t == &RTTI_obj) return this; \ void* ptr; \ if ((ptr=b1::RTTI_cast(t))) return ptr; \ if ((ptr=b2::RTTI_cast(t))) return ptr; \ return 0; \ } \ const void* cls::RTTI_cast(RTTItypeid t)const \ { \ if (t == &RTTI_obj) return this; \ const void* ptr; \ if ((ptr=b1::RTTI_cast(t))) return ptr; \ if ((ptr=b2::RTTI_cast(t))) return ptr; \ return 0; \ } \ void* cls::RTTI_scast(int i,void* p) \ { cls* ptr = (cls*)p; \ switch(i) \ { case 0: return (b1*)ptr; \ case 1: return (b2*)ptr; \ } \ return ptr; \ } #define RTTI_DEF3_BASE(cls,name,b1,b2,b3) \ static const RTTITypeinfo* RTTI_base_##cls [] = \ { STATIC_TYPE_INFO(b1).get_info(), \ STATIC_TYPE_INFO(b2).get_info(), \ STATIC_TYPE_INFO(b3).get_info(), 0 }; \ void* cls::RTTI_cast(RTTItypeid t) \ { \ if (t == &RTTI_obj) return this; \ void* ptr; \ if ((ptr=b1::RTTI_cast(t))) return ptr; \ if ((ptr=b2::RTTI_cast(t))) return ptr; \ if ((ptr=b3::RTTI_cast(t))) return ptr; \ return 0; \ } \ const void* cls::RTTI_cast(RTTItypeid t)const \ { \ if (t == &RTTI_obj) return this; \ const void* ptr; \ if ((ptr=b1::RTTI_cast(t))) return ptr; \ if ((ptr=b2::RTTI_cast(t))) return ptr; \ if ((ptr=b3::RTTI_cast(t))) return ptr; \ return 0; \ } \ void* cls::RTTI_scast(int i,void* p) \ { cls* ptr = (cls*)p; \ switch(i) \ { case 0: return (b1*)ptr; \ case 1: return (b2*)ptr; \ case 2: return (b3*)ptr; \ } \ return ptr; \ } #define RTTI_DEF_INST(cls,name) \ RTTI_DEF_BASE(cls,name) \ RTTI_NEW(cls,name) #define RTTI_DEF(cls,name) \ RTTI_DEF_BASE(cls,name) \ RTTI_NO_NEW(cls,name) #define RTTI_DEF1_INST(cls,name,b1) \ RTTI_DEF1_BASE(cls,name,b1) \ RTTI_NEW(cls,name) #define RTTI_DEF1(cls,name,b1) \ RTTI_DEF1_BASE(cls,name,b1) \ RTTI_NO_NEW(cls,name) #define RTTI_DEF2_INST(cls,name,b1,b2) \ RTTI_DEF2_BASE(cls,name,b1,b2) \ RTTI_NEW(cls,name) #define RTTI_DEF2(cls,name,b1,b2) \ RTTI_DEF2_BASE(cls,name,b1,b2) \ RTTI_NO_NEW(cls,name) #define RTTI_DEF3_INST(cls,name,b1,b2,b3) \ RTTI_DEF3_BASE(cls,name,b1,b2,b3) \ RTTI_NEW(cls,name) #define RTTI_DEF3(cls,name,b1,b2,b3) \ RTTI_DEF3_BASE(cls,name,b1,b2,b3) \ RTTI_NO_NEW(cls,name) #endif ossim-Miami-2.9.1/include/ossim/base/ossimScalarTypeLut.h000066400000000000000000000024061352751253100233640ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration for ossimScalarTypeLut. // //******************************************************************* // $Id: ossimScalarTypeLut.h 11914 2007-10-28 18:28:18Z dburken $ #ifndef ossimScalarTypeLut_HEADER #define ossimScalarTypeLut_HEADER #include #include /** * Used to convert from scalar type enumeration to strings and vice versa. * See ossimConstants.h for a complete list of enumerations. This class is * a singleton, only one of them so all callers must go through the * instance method like: * ossimScalarTypeLut::instance()->getEntryString(scalar); */ class OSSIMDLLEXPORT ossimScalarTypeLut : public ossimLookUpTable { public: /** * Returns the static instance of an ossimScalarTypeLut object. */ static ossimScalarTypeLut* instance(); virtual ~ossimScalarTypeLut(); ossimScalarType getScalarTypeFromString(const ossimString& s) const; virtual ossimKeyword getKeyword() const; protected: ossimScalarTypeLut(); private: static ossimScalarTypeLut* theInstance; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimSevenParamDatum.h000066400000000000000000000074171352751253100236730ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // SevenParamDatum. This is a base class for all // seven param datums. //******************************************************************* // $Id: ossimSevenParamDatum.h 19795 2011-06-30 15:04:48Z gpotts $ #ifndef ossimSevenParamDatum_HEADER #define ossimSevenParamDatum_HEADER #include class ossimEllipsoid; class OSSIM_DLL ossimSevenParamDatum : public ossimDatum { public: /** * @param code new datum code. (input) * @param name Name of the new datum (input) * @param SigmaX Standard error in X in meters (input) * @param SigmaY Standard error in Y in meters (input) * @param SigmaZ Standard error in Z in meters (input) * @param southLatitude Southern edge of validity rectangle in radians(input) * @param northLatitude Northern edge of validity rectangle in radians(input) * @param westLongitude Western edge of validity rectangle in radians (input) * @param eastLongitude Eastern edge of validity rectangle in radians (input) * @param param1 X translation * @param param2 Y translation * @param param3 Z translation * @param param4 X Rotation * @param param5 Y Rotation * @param param6 Z Rotation * @param param7 x,y,z Scale */ ossimSevenParamDatum(const ossimString &code, const ossimString &name, const ossimEllipsoid* anEllipsoid, ossim_float64 sigmaX, ossim_float64 sigmaY, ossim_float64 sigmaZ, ossim_float64 westLongitude, ossim_float64 eastLongitude, ossim_float64 southLatitude, ossim_float64 northLatitude, ossim_float64 aParam1, ossim_float64 aParam2, ossim_float64 aParam3, ossim_float64 aParam4, ossim_float64 aParam5, ossim_float64 aParam6, ossim_float64 aParam7) : ossimDatum(code, name, anEllipsoid, sigmaX, sigmaY, sigmaZ, westLongitude, eastLongitude, southLatitude, northLatitude), theParam1(aParam1), theParam2(aParam2), theParam3(aParam3), theParam4(aParam4), theParam5(aParam5), theParam6(aParam6), theParam7(aParam7) {} /*! * Will shift the ground point relative to this datum. */ ossimGpt shift(const ossimGpt &aPt)const; virtual ossimGpt shiftToWgs84(const ossimGpt &aPt)const; virtual ossimGpt shiftFromWgs84(const ossimGpt &aPt)const; virtual ossim_float64 param1()const{return theParam1;} virtual ossim_float64 param2()const{return theParam2;} virtual ossim_float64 param3()const{return theParam3;} virtual ossim_float64 param4()const{return theParam4;} virtual ossim_float64 param5()const{return theParam5;} virtual ossim_float64 param6()const{return theParam6;} virtual ossim_float64 param7()const{return theParam7;} virtual bool isEqualTo(const ossimObject& obj, ossimCompareType compareType=OSSIM_COMPARE_FULL)const; private: ossim_float64 theParam1; ossim_float64 theParam2; ossim_float64 theParam3; ossim_float64 theParam4; ossim_float64 theParam5; ossim_float64 theParam6; ossim_float64 theParam7; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimSource.h000066400000000000000000000042431352751253100220710ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // Base class for any object that can be a source. Derives from // ossimConnectableObject since all source's should be connectable // //************************************************************************* // $Id: ossimSource.h 15798 2009-10-23 19:15:20Z gpotts $ #ifndef ossimSource_HEADER #define ossimSource_HEADER #include #include #include class ossimDataObject; class OSSIMDLLEXPORT ossimSource : public ossimConnectableObject, public ossimErrorStatusInterface { public: ossimSource(ossimObject* owner=0); ossimSource(ossimObject* owner, ossim_uint32 inputListSize, ossim_uint32 outputListSize, bool inputListIsFixedFlag=true, bool outputListIsFixedFlag=true); virtual ~ossimSource(); virtual bool isSourceEnabled()const; virtual void enableSource(); virtual void disableSource(); virtual bool getEnableFlag() const; virtual void setEnableFlag(bool flag); virtual bool isInitialized() const; virtual void setInitializedFlag(bool flag); virtual void initialize(); /*---------------------- PROPERTY INTERFACE ---------------------------*/ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /*--------------------- PROPERTY INTERFACE END ------------------------*/ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual std::ostream& print(std::ostream& out) const; protected: ossimSource(const ossimSource &rhs); const ossimSource& operator=(const ossimSource &rhs); bool theEnableFlag; bool theInitializedFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimStateChangedEvent.h000066400000000000000000000016621352751253100241670ustar00rootroot00000000000000#ifndef ossimStateChangedEvent_HEADER #define ossimStateChangedEvent_HEADER #include #include #include #include #include class OSSIMDLLEXPORT ossimStateChangedEvent : public ossimEvent { public: ossimStateChangedEvent( ossimObject* object=NULL, long id=OSSIM_EVENT_STATE_CHANGED_ID ); void setObjId( std::string objId ); void setNewKeywordlist( ossimKeywordlist kwl ); void setOldKeywordlist( ossimKeywordlist kwl ); std::string getObjId(); ossimKeywordlist getNewKeywordlist(); ossimKeywordlist getOldKeywordlist(); // HACK - Need to set keywordlists too!!! virtual ossimObject* dup()const{return new ossimStateChangedEvent(*this);} private: std::string theObjId; ossimKeywordlist theNewKeywordlist; ossimKeywordlist theOldKeywordlist; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimStdOutProgress.h000066400000000000000000000020441352751253100235750ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimStdOutProgress.h 10422 2007-02-06 04:03:13Z gpotts $ #ifndef ossimStdOutProgress_HEADER #define ossimStdOutProgress_HEADER #include #include #include class OSSIM_DLL ossimStdOutProgress : public ossimProcessListener { public: ossimStdOutProgress(ossim_uint32 precision = 0, bool flushStream=false); virtual void processProgressEvent(ossimProcessProgressEvent& event); virtual void setFlushStreamFlag(bool flag); protected: ossim_uint32 thePrecision; bool theFlushStreamFlag; bool theRunningInConsoleFlag; TYPE_DATA }; OSSIM_DLL extern ossimStdOutProgress theStdOutProgress; #endif ossim-Miami-2.9.1/include/ossim/base/ossimStreamBase.h000066400000000000000000000020441352751253100226540ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // Base class for all ossim streams... Derives from ossimReferenced. // //******************************************************************* // $Id: ossimStreamBase.h 11176 2007-06-07 19:45:56Z dburken $ // #ifndef ossimStreamBase_HEADER #define ossimStreamBase_HEADER #include /* for OSSIM_DLL */ #include /* for base class */ class OSSIM_DLL ossimStreamBase : public ossimReferenced { public: /** @brief default constructor */ ossimStreamBase(); /** @brief virtual destructor */ virtual ~ossimStreamBase(); /** * @brief isCompressed method. * @return true if compressed false if not compressed. * @note This default implementation returns false. Derived classes should * override if needed. */ virtual bool isCompressed() const; }; #endif /* end of "#ifndef ossimStreamBase_HEADER" */ ossim-Miami-2.9.1/include/ossim/base/ossimStreamFactory.h000066400000000000000000000043131352751253100234120ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // //******************************************************************* // $Id$ #ifndef ossimStreamFactory_HEADER #define ossimStreamFactory_HEADER 1 #include #include namespace ossim { class OSSIM_DLL StreamFactory : public StreamFactoryBase { public: static StreamFactory* instance(); virtual ~StreamFactory(); virtual std::shared_ptr createIstream(const std::string& connectionString, const ossimKeywordlist& options=ossimKeywordlist(), std::ios_base::openmode mode= std::ios_base::in|std::ios_base::binary) const; virtual std::shared_ptr createOstream(const std::string& connectionString, const ossimKeywordlist& options=ossimKeywordlist(), std::ios_base::openmode mode= std::ios_base::out|std::ios_base::binary) const; virtual std::shared_ptr createIOstream(const std::string& connectionString, const ossimKeywordlist& options=ossimKeywordlist(), std::ios_base::openmode mode= std::ios_base::in|std::ios_base::out|std::ios_base::binary) const; /** * @brief Methods to test if connection exists. * * @param connectionString * * @param continueFlag Initializes by this, if set to false, indicates factory * handles file/url and no more factory checks are necessary. If true, * connection is not handled by this factory. * * @return true on success, false, if not. */ virtual bool exists(const std::string& connectionString, bool& continueFlag) const; protected: StreamFactory(); StreamFactory(const StreamFactory&); static StreamFactory* m_instance; }; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimStreamFactoryBase.h000066400000000000000000000036351352751253100242130ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id$ #ifndef ossimStreamFactoryBase_HEADER #define ossimStreamFactoryBase_HEADER 1 #include #include #include #include #include #include #include class ossimFilename; namespace ossim { class OSSIM_DLL StreamFactoryBase { public: virtual ~StreamFactoryBase(){} virtual std::shared_ptr createIstream(const std::string& connectionString, const ossimKeywordlist& options, std::ios_base::openmode mode) const=0; virtual std::shared_ptr createOstream(const std::string& connectionString, const ossimKeywordlist& options, std::ios_base::openmode mode) const=0; virtual std::shared_ptr createIOstream(const std::string& connectionString, const ossimKeywordlist& options, std::ios_base::openmode mode) const=0; /** * @brief Methods to test if connection exists. * * @param connectionString * * @param continueFlag Initializes by this, if set to false, indicates factory * handles file/url and no more factory checks are necessary. If true, * connection is not handled by this factory. * * @return true on success, false, if not. */ virtual bool exists(const std::string& connectionString, bool& continueFlag) const = 0; }; } #endif ossim-Miami-2.9.1/include/ossim/base/ossimStreamFactoryRegistry.h000066400000000000000000000175621352751253100251550ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id$ #ifndef ossimStreamFactoryRegistry_HEADER #define ossimStreamFactoryRegistry_HEADER 1 #include #include #include #include #include #include #include #include #include namespace ossim { /** * This is a generic stream registry. We could try to create streams for * http, https, s3 protocols as well as local file. We have also exposed an * exists for supporting exists() calls for different stream types. * * We have added support for Buffered reads. You can enable buffered * reads to be block boundary. If it's not block then it will use * a pubsetbuf for a buffered I/O * It will read the @see ossimPreferences for the prefix key * ossim.stream.factory.registry.istream.buffer[0-9]+ * Example key list: * @code * ossim.stream.factory.registry.istream.buffer1.enabled: false * ossim.stream.factory.registry.istream.buffer1.includePattern: ^/ * ossim.stream.factory.registry.istream.buffer1.enableBlocked: true * ossim.stream.factory.registry.istream.buffer1.size: 65536 * @endcode * * The includePattern keyword is a regular expression. * Examples: * - ^/ Anything that starts with / * - ^s3:// Anything starting with s3:// * * Local file example: * @code * ossimString connectionString = "/data/foo.ntf" * std::shared_ptr in = ossim::StreamFactoryRegistry::instance()->createIstream(connectionString); * if(in) * { * std::vector buf(1024) * in->seekg(0); * in->read(&buf.front(), buf.size()); * } * @endcode * S3 file example: * @code * ossimString connectionString = "s3://foo-bucket/path/foo.ntf" * std::shared_ptr in = ossim::StreamFactoryRegistry::instance()->createIstream(connectionString); * if(in) * { * std::vector buf(1024) * in->seekg(0); * in->read(&buf.front(), buf.size()); * } * @endcode * https or https file example: * @code * ossimString connectionString = "https://foo-host/path/foo.ntf" * std::shared_ptr in = ossim::StreamFactoryRegistry::instance()->createIstream(connectionString); * if(in) * { * std::vector buf(1024) * in->seekg(0); * in->read(&buf.front(), buf.size()); * } * @endcode */ class OSSIM_DLL StreamFactoryRegistry : public StreamFactoryBase { public: static StreamFactoryRegistry* instance(); virtual ~StreamFactoryRegistry(); /** * Registers a stream factory. This allows for a pluggable stream * Please see ossim-plugins and look at curl, aws for example * stream definitions. * * @param factory To be added to the registry */ void registerFactory(StreamFactoryBase* factory); /** * Removes a factory from the registry. * @param factory To be removed from the registry */ void unregisterFactory(StreamFactoryBase* factory); /** * Will try to creates an std::istream interface to the connectionString * passed in * * @param connectionString Is the connection string used to create * a stream. Possible examples: s3:///path or * /data/foo.tif or https:/// * @param options If a stream is found then this holds specific options * for the stream. Defaults to empty options * @param mode Is the mode to be used. Defaults to a binary input stream. * @return A shared pointer to an std::istream if successful. */ virtual std::shared_ptr createIstream(const std::string& connectionString, const ossimKeywordlist& options=ossimKeywordlist(), std::ios_base::openmode mode= std::ios_base::in|std::ios_base::binary) const; /** * Will try to creates an std::ostream interface to the connectionString * passed in * * @param connectionString Is the connection string used to create the * stream * @param options If a stream is found then this holds specific options * for the stream. Defaults to empty options * @param mode Is the mode to be used. Defaults to a binary output * stream. * @return A shared pointer to an std::ostream if successful. */ virtual std::shared_ptr createOstream(const std::string& connectionString, const ossimKeywordlist& options=ossimKeywordlist(), std::ios_base::openmode mode= std::ios_base::out|std::ios_base::binary) const; /** * Will try to creates an iostream interface to the connectionString * passed in * * @param connectionString Is the connection string used to create the * stream * @param options If a stream is found then this holds specific options * for the stream. Defaults to empty options * @param mode Is the mode to be used. Defaults to a binary output * stream. * @return A shared pointer to an std::ostream if successful. */ virtual std::shared_ptr createIOstream(const std::string& connectionString, const ossimKeywordlist& options=ossimKeywordlist(), std::ios_base::openmode mode= std::ios_base::in|std::ios_base::out|std::ios_base::binary) const; /** * @brief Methods to test if connection exists. * @return true on success, false, if not. */ bool exists(const std::string& connectionString) const; /** * @brief Methods to test if connection exists. * @param connectionString * @param continueFlag Initializes by this, if set to true, indicates factory * handles file/url and no more factory checks are necessary. * @return true on success, false, if not. */ virtual bool exists(const std::string& connectionString, bool& continueFlag) const; /** * This will load the buffer information from the * preferences. */ void loadPreferences(); protected: StreamFactoryRegistry(); private: /** * This is an internal class used to store the buffer information * loaded from the preferences. * @see StreamFactoryRegistry */ class BufferInfo{ public: BufferInfo():m_enabled(false), m_enableBlocked(false), m_pattern(""), m_size(4096){} bool m_enabled; bool m_enableBlocked; ossimString m_pattern; ossim_uint64 m_size; }; /** @brief copy constructor hidden from use */ StreamFactoryRegistry(const StreamFactoryRegistry&); /** * @param bufferInfo Holds the result of the first buffer info * matching the connection string * @param connecitonString The connection string */ bool getBufferInfo(BufferInfo& bufferInfo, const ossimString& connectionString)const; std::vector m_factoryList; std::vector m_bufferInfoList; static StreamFactoryRegistry* m_instance; mutable ossimRegExp m_patternMatcher; mutable std::mutex m_mutex; }; } // End: namespace ossim #endif ossim-Miami-2.9.1/include/ossim/base/ossimString.h000066400000000000000000000720031352751253100220760ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This class extends the stl's string class. // //******************************************************************** // $Id: ossimString.h 20491 2012-01-23 20:10:06Z dburken $ #ifndef ossimString_HEADER #define ossimString_HEADER 1 #include #include #include #include class OSSIM_DLL ossimString { public: typedef std::string::const_iterator const_iterator; typedef std::string::iterator iterator; typedef std::string::size_type size_type; /** @brief default constructor */ ossimString(): m_str() {} /** @brief constructor that takes a std::string */ ossimString(const std::string& s):m_str(s) {} /** * @brief constructor that takes char* * NOTE: std::string construtor throws exception given null pointer; * hence, the null check. */ ossimString(const char *aString):m_str( aString?aString:"" ){} /** @brief copy constructor */ ossimString(const ossimString& aString):m_str(aString.m_str){} /** @brief constructor - constructs with n copies of c */ ossimString(std::string::size_type n, char c):m_str(n,c){} /** @brief constructor - constructs with 1 c. */ ossimString(char aChar):m_str(1, aChar){} template ossimString(Iter startIter, Iter endIter):m_str(startIter, endIter){} /** @brief destructor */ ~ossimString(){} bool contains(char aChar) const { return m_str.find(aChar)!=std::string::npos; } bool contains(const ossimString& aString) const { return m_str.find(aString.m_str)!=std::string::npos; } bool contains(const char* aString) const { return m_str.find(aString)!=std::string::npos; } /** @brief Type conversion operator to a const std::string&. */ operator const std::string&() const { return m_str; } /** @brief Type conversion operator to a std::string&. */ operator std::string&() { return m_str; } /** @brief Type conversion operator to a const char*. */ operator const char*() const { return m_str.c_str(); } /** @brief For backward compatibility. */ const char* chars() const { return m_str.c_str(); } /** @brief Reads s from the input stream is. */ friend OSSIM_DLL std::istream& operator>>(std::istream& is, ossimString& s); /** @brief Writes s to the output stream os. */ friend OSSIM_DLL std::ostream& operator<<(std::ostream& os, const ossimString& s); /** * @brief Reads a string from the input stream is, stopping when it * reaches delim. */ friend OSSIM_DLL std::istream& getline( std::istream& is, ossimString& str, char delim ); /** @brief Reads a single line from the input stream is. */ friend OSSIM_DLL std::istream& getline( std::istream& is, ossimString& str ); explicit operator bool() const { return m_str.empty() ? false : true; } const ossimString& operator=(const std::string& s) { m_str = s; return *this; } const ossimString& operator=(const char* s) { if (s) // std::string::operator= throws exception given null pointer. { m_str = s; } else { m_str = ""; } return *this; } const ossimString& operator=(char c) { m_str = c; return *this; } const ossimString& operator=(const ossimString& s) { if ( this != &s ) { m_str = s.m_str; } return *this; } const ossimString& operator+=(const ossimString& s) { m_str.append(s.m_str); return *this; } const ossimString& operator+=(const std::string& s) { m_str.append(s); return *this; } const ossimString& operator+=(const char* s) { if ( s ) m_str.append(s); return *this; } const ossimString& operator+=(char c) { m_str.append(1, c); return *this; } const ossimString& append(const ossimString& s); const ossimString& append(const std::string& s); const ossimString& append(const char* s); /** * @brief Provides access to the data contained in the %string. * @param n The index of the character to access. * @return Read-only (const) reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. */ const char& at(std::string::size_type n) const; /** * @brief Provides access to the data contained in the %string. * @param n The index of the character to access. * @return Read/write reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. Success results in * unsharing the string. */ char& at(std::string::size_type n); /** @brief Append n copies of c to *this. */ const ossimString& append(std::string::size_type n, char c); ossimString operator+(const ossimString& s)const { ossimString returnS(*this); returnS.m_str.append(s.m_str); return returnS; } ossimString operator+(const std::string& s)const { ossimString returnS(*this); returnS.m_str.append(s); return returnS; } ossimString operator+(const char* s)const { ossimString returnS(*this); if ( s ) returnS.m_str.append(s); return returnS; } ossimString operator+(char c)const { ossimString returnS(*this); returnS.m_str.append(1, c); return returnS; } friend OSSIM_DLL ossimString operator+(const char* s1, const ossimString& s2); friend OSSIM_DLL ossimString operator+(const std::string s1, const ossimString& s2); friend OSSIM_DLL ossimString operator+(char c, const ossimString& s2); friend OSSIM_DLL bool operator==(const char* lhs, const ossimString& rhs); friend OSSIM_DLL bool operator==(const std::string& lhs, const ossimString& rhs); /** * @brief Test if this ossimString is equal to another ossimString. * @param rhs ossimString to compare. * @return True if strings are equal. False otherwise. */ bool operator==(const ossimString& rhs) const { return (m_str == rhs.m_str); } /** * @brief Test if this ossimString is equal to a C sting. * @param rhs C string to compare. * @return True if strings are equal. * False if rhs is not equal null or null. */ bool operator==(const char* rhs) const { bool result = false; if (rhs) { result = (m_str.compare(std::string(rhs)) == 0); } return result; } /** * @brief Test if this ossimString is not equal to another ossimString. * @param rhs ossimString to compare. * @return True if strings are not equal. False otherwise. */ bool operator!=(const ossimString& rhs) const { return !(m_str.compare(rhs.m_str) == 0); } /** * @brief Test if this ossimString is not equal to a C sting. * @param rhs C string to compare. * @return True if strings are not equal or rhs is null. * False if rhs equal to this string. */ bool operator!=(const char* rhs) const { bool result = true; if (rhs) { result = !(m_str.compare(std::string(rhs)) == 0); } return result; } bool operator<(const ossimString& rhs) const { return m_str < rhs.m_str; } bool operator<=(const ossimString& rhs) const { return m_str <= rhs.m_str; } bool operator>(const ossimString& rhs) const { return m_str > rhs.m_str; } bool operator>=(const ossimString& rhs) const { return m_str >= rhs.m_str; } char& operator[](std::string::size_type i) { return m_str[i]; // return *( const_cast(m_strc_str())+i); } const char& operator[](std::string::size_type i)const { return m_str[i]; } /** * @brief If pos > size(), throws out_of_range. Otherwise, equivalent to * insert(begin() + pos, s, s + traits::length(s)). */ std::string& insert(std::string::size_type pos, const char* s); /** @brief Equivalent to insert(end(), c). */ void push_back(char c); /** @brief Equivalent to basic_string(*this, pos, n). */ std::string substr(std::string::size_type pos = 0, std::string::size_type n = std::string::npos) const; /** * this will strip lead and trailing character passed in. * So if you want to remove blanks: * ossimString temp(" asdfasdf "); * ossimString trimmedString = temp.trim(" \n\t\r"); * * this will now contain "asdfasdf" without the blanks. * */ ossimString trim(const ossimString& valueToTrim= ossimString(" \t\n\r"))const; ossimString& trim(const ossimString& valueToTrim= ossimString(" \t\n\r")); ossimString beforePos(std::string::size_type pos)const; ossimString afterPos(std::string::size_type pos)const; /** * Substitutes searchKey string with replacementValue and returns a * string. Will replace all occurrences found if "replaceAll" is true. */ ossimString substitute(const ossimString &searchKey, const ossimString &replacementValue, bool replaceAll=false)const; /** * Substitutes searchKey string with replacementValue and returns a * reference to *this. Will replace all occurrences found if * "replaceAll" is true. (like substitute only works on "this") */ ossimString& gsub(const ossimString &searchKey, const ossimString &replacementValue, bool replaceAll=false); std::vector explode(const ossimString& delimeter) const; /** * If the variable "$(env_var_name)" is found in the string, where * "env_var_name" is any system environment variable resolvable by * the getenv() function, the variable is expanded in place and the * result returned. */ ossimString expandEnvironmentVariable() const; /** * @param aString String to make an upcased copy of. * * @return An upcased version of aString. */ static ossimString upcase(const ossimString& aString); /** * @param aString String to make an downcased copy of. * * @return A downcased version of aString. */ static ossimString downcase(const ossimString& aString); /** * Upcases this string. * * @return Reference to this. */ ossimString& upcase(); ossimString upcase()const; /** * Downcases this string. * * @return Reference to this. */ ossimString& downcase(); ossimString downcase()const; /** * @return true if the string ends in the pattern specified */ bool endsWith(const ossimString &pattern) const; /** * @return true if the string starts with the pattern specified */ bool startsWith(const ossimString &pattern) const; /** * @brief Returns a pointer to a null-terminated array of characters * representing the string's contents. */ const char* c_str() const { return m_str.c_str(); } /** * @brief Returns a pointer to an array of characters (not necessarily * null-terminated) representing the string's contents. */ const char* data() const { return m_str.data(); } /** @return The size of the string. */ std::string::size_type size() const { return m_str.size(); } /** @return The size of the string. */ std::string::size_type length() const { return m_str.size(); } /** @return True if size is 0. */ bool empty() const { return m_str.empty(); } /** @return The underlying std::string container. */ const std::string& string() const { return m_str; } /** @return The underlying std::string container. */ std::string& string() { return m_str; } /** @return An iterator pointing to the beginning of the string. */ std::string::iterator begin() { return m_str.begin(); } /** @return An iterator pointing to the end of the string. */ std::string::iterator end() { return m_str.end(); } /** @return An const_iterator pointing to the beginning of the string. */ std::string::const_iterator begin() const { return m_str.begin(); } /** @return An const_iterator pointing to the end of the string. */ std::string::const_iterator end() const { return m_str.end(); } /** @brief Erases the entire container. */ void clear() { m_str.clear(); } /** @brief Erases the character at position p. */ std::string::iterator erase(std::string::iterator p); /** @brief Erases the range [first, last). */ std::string::iterator erase(std::string::iterator first, std::string::iterator last); /** @brief Erases a range. */ std::string& erase(std::string::size_type pos = 0, std::string::size_type n = std::string::npos); /** * @brief Searches for s as a substring of *this, beginning at character * pos of *this. */ std::string::size_type find(const std::string& s, std::string::size_type pos = 0) const; /** * @brief Searches for the first n characters of s as a substring of *this, * beginning at character pos of *this. */ std::string::size_type find(const char* s, std::string::size_type pos, std::string::size_type n) const; /** * @brief Searches for a null-terminated character array as a substring * of *this, beginning at character pos of *this. */ std::string::size_type find(const char* s, std::string::size_type pos = 0) const; /** * @brief Searches for the character c, beginning at character position * pos. */ std::string::size_type find(char c, std::string::size_type pos = 0) const; /** * @brief Searches backward for s as a substring of *this, beginning at * character position min(pos, size()). */ std::string::size_type rfind(const std::string& s, std::string::size_type pos = 0) const; /** * @brief Searches backward for the first n characters of s as a substring * of *this, beginning at character position min(pos, size()). */ std::string::size_type rfind(const char* s, std::string::size_type pos, std::string::size_type n) const; /** * @brief Searches backward for a null-terminated character array as a * substring of *this, beginning at character min(pos, size()). */ std::string::size_type rfind(const char* s, std::string::size_type pos = 0) const; /** * @brief Searches backward for the character c, beginning at character * position min(pos, size(). */ std::string::size_type rfind(char c, std::string::size_type pos = 0) const; /** @brief Equivalent to find(c, pos). */ std::string::size_type find_first_of( char c, std::string::size_type pos = 0) const; /** * @brief Returns the smallest character position N such that * pos <= N < size(), and such that (*this)[N] does not compare equal to c. * Returns npos if no such character position exists. */ std::string::size_type find_first_not_of( char c, std::string::size_type pos = 0) const; /** * @brief Equivalent to find_first_of(s, pos, traits::length(s)). */ std::string::size_type find_first_of( const char* s, std::string::size_type pos = 0) const; /** * @brief Equivalent to find_first_not_of(s, pos, traits::length(s)). */ std::string::size_type find_first_not_of( const char* s, std::string::size_type pos = 0) const; /** @brief Equivalent to rfind(c, pos). */ std::string::size_type find_last_of( char c, std::string::size_type pos = std::string::npos) const; /** * @brief Erases the existing characters and replaces them by n copies * of c. */ std::string& assign(std::string::size_type n, char c); /** @brief Replaces a substring of *this with the string s. */ std::string& replace(std::string::size_type pos, std::string::size_type n, const std::string& s); /** brief Equivalent to insert(erase(first, last), s.begin(), s.end()). */ std::string& replace(std::string::iterator first, std::string::iterator last, const std::string& s); /** @brief Replaces a substring of *this with a substring of s. */ std::string& replace(std::string::size_type pos, std::string::size_type n, const std::string& s, std::string::size_type pos1, std::string::size_type n1); /** @brief Requests that the string's capacity be changed. */ void reserve(std::string::size_type n); /** * METHOD: before(str, pos) * Returns string beginning at pos and ending one before the token str * If string not found or pos out of range the whole string will be * returned. */ ossimString before(const ossimString& str, std::string::size_type pos=0)const; /** * METHOD: after(str, pos) * Returns string immediately after the token str. The search for str * begins at pos. Returns an empty string if not found or pos out of * range. */ ossimString after (const ossimString& str, std::string::size_type pos=0)const; char* stringDup()const; /** * String to numeric methods. */ bool toBool()const; static bool toBool(const ossimString& aString); ossim_uint8 toUInt8()const; static ossim_uint8 toUInt8(const ossimString& aString); int toInt()const; static int toInt(const ossimString& aString); ossim_int16 toInt16()const; static ossim_int16 toInt16(const ossimString& aString); ossim_uint16 toUInt16()const; static ossim_uint16 toUInt16(const ossimString& aString); ossim_int32 toInt32()const; static ossim_int32 toInt32(const ossimString& aString); ossim_uint32 toUInt32()const; static ossim_uint32 toUInt32(const ossimString& aString); ossim_int64 toInt64()const; static ossim_int64 toInt64(const ossimString& aString); ossim_uint64 toUInt64()const; static ossim_uint64 toUInt64(const ossimString& aString); /** * This takes a string and will test for * numeric followed by a unit type: * * 123K is 123 kilobytes * 123k is 123 kilobytes * 64G is 123 gigabytes * 64g is 64 gigabytes * * you can use any of the following modifiers * k|K = kilobytes * b|B = bytes * m|M = megabytes * g|G = gigabytes * t|T = terrabyte * * If no unit is present then it will assume bytes and just return * the value */ ossim_int64 memoryUnitToInt64()const; static ossim_int64 memoryUnitToInt64(const ossimString& aString); /** * toLong's deprecated, please use the toInts... */ long toLong()const; static long toLong(const ossimString& aString); unsigned long toULong()const; static unsigned long toULong(const ossimString& aString); ossim_float32 toFloat32()const; static ossim_float32 toFloat32(const ossimString& aString); ossim_float64 toFloat64()const; static ossim_float64 toFloat64(const ossimString& aString); double toDouble()const; static double toDouble(const ossimString& aString); /** * Numeric to string methods. */ static ossimString toString(bool aValue); static ossimString toString(ossim_int16 aValue); static ossimString toString(ossim_uint16 aValue); static ossimString toString(ossim_int32 aValue); static ossimString toString(ossim_uint32 aValue); static ossimString toString(ossim_int64 aValue); static ossimString toString(ossim_uint64 aValue); /** * @param aValue Value to convert to string. * * @param precision Decimal point precision of the output. * * @param fixed If true setiosflags(std::ios::fixed) will be called. */ static ossimString toString(ossim_float32 aValue, ossim_int32 precision = 8, bool fixed = false); /** * @param aValue Value to convert to string. * * @param precision Decimal point precision of the output. * * @param fixed If true setiosflags(std::ios::fixed) will be called. */ static ossimString toString(ossim_float64 aValue, ossim_int32 precision = 15, bool fixed = false); static ossimString stripLeading(const ossimString &value, char characterToStrip); /** * Splits this string into a vector of strings (fields) using the delimiter list specified. * If a delimiter is encountered at the beginning or the end of this, or two delimiters are * contiguous, a blank field is inserted in the vector, unless skipBlankFields is true. */ void split(std::vector& result, const ossimString& separatorList, bool skipBlankFields=false)const; std::vector split(const ossimString& separatorList, bool skipBlankFields=false)const; const ossimString& join(const std::vector& stringList, const ossimString& separator); //--- // Regular expression pattern utilities //--- /** * Returns from start of string up to but not including found pattern. * Returns "" if pattern not found. */ ossimString beforeRegExp(const char *regularExpressionPattern) const; /** * Returns from position of found pattern to end of string. * Returns "" if pattern not found. */ ossimString fromRegExp(const char *regularExpressionPattern) const; /** * Returns from position after found pattern to end of string. * Returns "" if pattern not found. */ ossimString afterRegExp(const char *regularExpressionPattern) const; /** * Returns from found pattern to end of pattern. * Returns "" if pattern not found. */ ossimString match(const char *regularExpressionPattern) const; ossimString replaceAllThatMatch(const char *regularExpressionPattern, const char *value="") const; ossimString replaceStrThatMatch(const char *regularExpressionPattern, const char *value="") const; ossimString urlEncode()const; /** * If OSSIM_ID_ENABLED returns the OSSIM_ID which currently is the * expanded cvs $Id: ossimString.h 20491 2012-01-23 20:10:06Z dburken $ macro; else, an empty string. */ ossimString getOssimId() const; protected: std::string m_str; }; inline std::string::iterator ossimString::erase(std::string::iterator p) { return m_str.erase(p); } inline std::string::iterator ossimString::erase(std::string::iterator first, std::string::iterator last) { return m_str.erase(first, last); } inline std::string& ossimString::erase(std::string::size_type pos, std::string::size_type n) { return m_str.erase(pos, n); } inline std::string::size_type ossimString::find( const std::string& s, std::string::size_type pos) const { return m_str.find(s, pos); } inline std::string::size_type ossimString::find( const char* s, std::string::size_type pos, std::string::size_type n) const { return m_str.find(s, pos, n); } inline std::string::size_type ossimString::find( const char* s, std::string::size_type pos) const { return m_str.find(s, pos); } inline std::string::size_type ossimString::find( char c, std::string::size_type pos) const { return m_str.find(c, pos); } inline std::string::size_type ossimString::rfind( const std::string& s, std::string::size_type pos) const { return m_str.rfind(s, pos); } inline std::string::size_type ossimString::rfind( const char* s, std::string::size_type pos, std::string::size_type n) const { return m_str.rfind(s, pos, n); } inline std::string::size_type ossimString::rfind( const char* s, std::string::size_type pos) const { return m_str.rfind(s, pos); } inline std::string::size_type ossimString::rfind( char c, std::string::size_type pos) const { return m_str.rfind(c, pos); } inline std::string::size_type ossimString::find_first_of( char c, std::string::size_type pos) const { return m_str.find_first_of(c, pos); } inline std::string::size_type ossimString::find_first_of( const char* s, std::string::size_type pos) const { return m_str.find_first_of(s, pos); } inline std::string::size_type ossimString::find_first_not_of( const char c, std::string::size_type pos) const { return m_str.find_first_not_of(c, pos); } inline std::string::size_type ossimString::find_first_not_of( const char* s, std::string::size_type pos) const { return m_str.find_first_not_of(s, pos); } inline std::string::size_type ossimString::find_last_of( char c, std::string::size_type pos) const { return m_str.find_last_of(c, pos); } inline const ossimString& ossimString::append(const ossimString& s) { m_str.append(s.m_str); return *this; } inline const ossimString& ossimString::append(const std::string& s) { m_str.append(s); return *this; } inline const ossimString& ossimString::append(const char* s) { if ( s ) m_str.append(s); return *this; } inline const ossimString& ossimString::append(std::string::size_type n, char c) { m_str.append(n, c); return *this; } inline const char& ossimString::at(std::string::size_type n) const { return m_str.at(n); } inline char& ossimString::at(std::string::size_type n) { return m_str.at(n); } inline std::string& ossimString::assign(std::string::size_type n, char c) { return m_str.assign(n, c); } inline std::string& ossimString::replace( std::string::size_type pos, std::string::size_type n, const std::string& s) { return m_str.replace(pos, n, s); } inline std::string& ossimString::replace(std::string::iterator first, std::string::iterator last, const std::string& s) { return m_str.replace(first, last, s); } inline std::string& ossimString::replace(std::string::size_type pos, std::string::size_type n, const std::string& s, std::string::size_type pos1, std::string::size_type n1) { return m_str.replace(pos, n, s, pos1, n1); } inline void ossimString::reserve(std::string::size_type n) { m_str.reserve(n); } inline std::string& ossimString::insert(std::string::size_type pos, const char* s) { if (s) m_str.insert(pos, s); return m_str; } inline void ossimString::push_back(char c) { m_str.push_back(c); } inline std::string ossimString::substr(std::string::size_type pos, std::string::size_type n) const { return m_str.substr(pos, n); } inline std::istream& getline( std::istream& is, ossimString& str, char delim ) { return std::getline( is, str.string(), delim ); } inline std::istream& getline( std::istream& is, ossimString& str ) { // Not sure why getline( is, str.string()) doesn't work. (drb) return std::getline( is, str.string(), '\n' ); } inline std::istream& operator>>(std::istream& is, ossimString& s) { return is >> s.string(); } inline std::ostream& operator<<(std::ostream& os, const ossimString& s) { return os << s.string(); } inline ossimString operator+(const char* s1, const ossimString& s2) { ossimString result; if ( s1 ) result = ossimString( s1 + s2.string() ); else result = s2; return result; } inline ossimString operator+(const std::string s1, const ossimString& s2) { return ossimString( s1 + s2.string() ); } inline ossimString operator+(char c, const ossimString& s2) { return ossimString( c + s2.string() ); } inline bool operator==(const char* lhs, const ossimString& rhs) { return (rhs.operator ==(lhs)); } inline bool operator==(const std::string& lhs, const ossimString& rhs) { return (rhs.operator ==(lhs)); } /** * @brief For use with std::map as a compare operator: * std::map * * This will allow the find method on map to work. */ struct ossimStringLtstr { bool operator()(const ossimString& s1, const ossimString& s2) const { return s1.string().compare(s2.string()) < 0; } }; #endif /* #ifndef ossimString_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimStringListProperty.h000066400000000000000000000046541352751253100245060ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimStringListProperty.h 9968 2006-11-29 14:01:53Z gpotts $ // #ifndef ossimStringListProperty_HEADER #define ossimStringListProperty_HEADER #include class OSSIMDLLEXPORT ossimStringListProperty : public ossimProperty { public: ossimStringListProperty(const ossimString& name=ossimString(""), const std::vector& value = std::vector()); ossimStringListProperty(const ossimStringListProperty& rhs); ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; void clearValueList(); ossimString getValueAt(int idx)const; bool setValueAt(int idx, const ossimString& value); bool addValue(const ossimString& value); ossim_uint32 getNumberOfValues()const; ossim_uint32 getNumberOfContraints()const; ossimString getConstraintAt(ossim_uint32 idx)const; void setConstraints(const std::vector& constraints); bool hasConstraints()const; void setUniqueFlag(bool flag); void setOrderMattersFlag(bool flag); /*! * You can specify how many values are allowed in the value list * If any of the values are less than 0 then now constraints are * placed on that value. So if the min was < 0 then there is * no minumum number of values. If the max is < 0 then there is * no maximum number of values. */ void setNumberOfValuesBounds(int minNumber, int maxNumber); void getNumberofValuesBounds(int& minNumber, int& maxNumber)const; protected: std::vector theValueList; std::vector theConstraintList; bool theUniqueFlag; bool theOrderMattersFlag; int theMinNumberOfValues; int theMaxNumberOfValues; bool findValueInConstraintList(const ossimString& value)const; bool findValueInValueList(const ossimString& value)const; bool canAddValue(const ossimString& value)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimStringProperty.h000066400000000000000000000042461352751253100236470ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // LICENSE: MIT see top level license.txt // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimStringProperty.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimStringProperty_HEADER #define ossimStringProperty_HEADER #include #include class OSSIMDLLEXPORT ossimStringProperty : public ossimProperty { public: ossimStringProperty(const ossimString& name = ossimString(""), const ossimString& value = ossimString(""), bool editableFlag = true, const std::vector& constraintList = std::vector()); ossimStringProperty(const ossimStringProperty& rhs); /*! * Duplicates the object and returns a new one */ virtual ossimObject* dup()const; virtual const ossimProperty& assign(const ossimProperty& rhs); void setEditableFlag(bool flag); bool getEditableFlag()const; bool isEditable()const; /*! * Clears the constraints for this string. You can constrain * it to a string list by calling setConstraints. */ void clearConstraints(); /*! * Sets the constraints for this property. If the editable * flag is present then this says the editing is not readonly * and one can hand type the value in without only selecting * from a choice list. */ void setConstraints(const std::vector& constraintList); void addConstraint(const ossimString& value); const std::vector& getConstraints()const; bool hasConstraints()const; /*! * will try to set the value. If the constraints are set * it will make sure that the value is in the list and * if its not then it will return false */ virtual bool setValue(const ossimString& value); virtual void valueToString(ossimString& valueResult)const; protected: ossimString theValue; bool theEditableFlag; std::vector theConstraints; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimTDpt.h000066400000000000000000000046551352751253100215130ustar00rootroot00000000000000// ossimTDpt // storage class for tie point (no height, no projection information) // based on ossimDpt // #ifndef ossimTDpt_HEADER #define ossimTDpt_HEADER #include #include // Forward class declarations. class ossimIpt; class ossimFpt; class ossimDpt3d; class ossimGpt; class OSSIMDLLEXPORT ossimTDpt : public ossimDpt { public: inline ossimTDpt() : ossimDpt(), tie(), score(0.0) {} inline ossimTDpt(const ossimDpt& aPt, const ossimDpt& aTie, const ossim_float64& aScore) : ossimDpt(aPt), tie(aTie), score(aScore) {} inline ossimTDpt(const ossimTDpt& tpt) : ossimDpt(tpt), tie(tpt.tie), score(tpt.score) {} const ossimTDpt& operator=(const ossimTDpt&); inline void setMasterPoint(const ossimDpt& mPt) { ossimDpt::operator=(mPt); } inline const ossimDpt& getMasterPoint()const { return *this; } inline ossimDpt& refMasterPoint() { return *this; } inline void setSlavePoint(const ossimDpt& sPt) { tie=sPt; } inline const ossimDpt& getSlavePoint()const { return tie; } inline ossimDpt& refSlavePoint() { return tie; } void makeNan() { ossimDpt::makeNan(); tie.makeNan(); score=ossim::nan(); } bool hasNans()const { return (ossimDpt::hasNans() || tie.hasNans() || (ossim::isnan(score))); } bool isNan()const { return (ossimDpt::isNan() && tie.isNan() && (ossim::isnan(score))); } std::ostream& print(std::ostream& os) const; std::ostream& printTab(std::ostream& os) const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& os, const ossimTDpt& pt); /** * Method to input the formatted string of the "operator<<". * * Expected format: ( ( ossimDpt ), ( ossimDpt ), 0.50000000000000 ) * --*this---- , ----tie-----, ---score-------- * */ friend OSSIMDLLEXPORT std::istream& operator>>(std::istream& is, ossimTDpt& pt); //*** // Public data members: //*** ossimDpt tie; ossim_float64 score; }; inline const ossimTDpt& ossimTDpt::operator=(const ossimTDpt& pt) { if (this != &pt) { ossimDpt::operator=(pt); tie = pt.tie; score = pt.score; } return *this; } #endif /* #ifndef ossimTDpt_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimTempFilename.h000066400000000000000000000023351352751253100231770ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // Description: This is a tmeporary filename class it will create a temporary // file and will also delete it upon destruction // //************************************************************************* // $Id: ossimTempFilename.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimTempFilename_HEADER #define ossimTempFilename_HEADER #include class OSSIM_DLL ossimTempFilename : public ossimFilename { public: ossimTempFilename(const ossimString& tempDir="", const ossimString& prefix = "", const ossimString& extension = "", bool autodelete=true, bool useWildcardDelete=true); void generateRandomFile(); void generateRandomDir(); ~ossimTempFilename(); protected: ossimString theTempDir; ossimString thePrefix; ossimString theExtension; bool theAutoDeleteFlag; bool theWildCardDeleteFlag; void generate(bool createAsDirectoryFlag); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimTerm.h000066400000000000000000000243051352751253100215410ustar00rootroot00000000000000/** * @author Dylan Thomas Cannisi * @date 07/24/2017 * * @brief Mathematical term data structure for ossim. * * See top level LICENSE.txt file. */ #ifndef OSSIM_TERM_H #define OSSIM_TERM_H 1 #include #include #include /** * @brief Different types for terms in a function */ enum termType : ossim_uint32 { monomial, polynomial, variable, constant, product }; /** * An abstract class to containing a multivariable function. */ class OSSIMDLLEXPORT ossimTerm { public: /** * @brief Virtual destructor for destroying tree from the top node. */ virtual ~ossimTerm() {} /** * @brief Evaluates a term at a given point PURE VIRTUAL * * @param[in] point The point to be evaluated * * @return the value at a point */ virtual ossim_float64 evaluate(std::vector /* point */ ) const = 0; /** * @brief Calculates the derivative of the term * * @param[in] variable The variable in which the derivative is with respect too * * @return A pointer containing the derivative of the term. */ virtual ossimTerm* derivative(const ossim_uint32& variable) const = 0; /** * @brief Gets the type * * @return The type */ virtual ossim_uint32 getType() const = 0; /** * @brief Returns a pointer to a copy of the term * * @return A pointer to a copy of the term */ virtual ossimTerm* copy() const = 0; /** * @brief Evaluates the function for a point * * @param point The point at which the function is being evaluated * * @return The value at a point */ inline ossim_float64 operator()(std::vector point) const{ return this->evaluate(point); } /** * @brief Returns a copy of the two terms in a polynomial * * @param rhs The right hand term of the polynomial * * @return A polynomial with !COPIES! of the two terms */ inline ossimTerm* operator+(ossimTerm* rhs) const; /** * @brief Returns a copy of the two terms in a product * * @param rhs The right hand term of the product * * @return A product with !COPIES! of the two terms */ inline ossimTerm* operator*(ossimTerm* rhs) const; }; /** * A monomial class to hold a monomial as a term. Example (c_0 * x_0 ^ e_0) */ class OSSIMDLLEXPORT ossimMonom : public ossimTerm{ public: /** * @brief Public Constructor * * @param[in] coeffient The coeffient of the term * @param variable The variable the variable number of the term * @param[in] exponential The exponential of the term */ ossimMonom(const ossim_float64& coeffient, ossimTerm* variable, const ossim_float64& exponential) : coef(coeffient), var(variable), exp(exponential) {} /** * @brief Public Copy Constructor * * @param[in] src The source to be copied */ ossimMonom(const ossimMonom& src) : coef(src.coef), var(src.var->copy()), exp(src.exp) {} /** * @brief Destroys the monomial */ ~ossimMonom() { delete var; } /** * @brief Evaluates a monomial for a point * * @param[in] point The point to be evaluated * * @return The value at a point. */ ossim_float64 evaluate(std::vector point) const { return (coef * pow(var->evaluate(point), exp)); } /** * @brief Calculates the derivative for a monomial * * @param[in] variable The variable in which the derivative is with respect too. * * @return A pointer to that contains the derivative of the term. */ ossimTerm* derivative(const ossim_uint32& variable) const; /** * @brief Gets the type of a monomial * * @return The type of a monomial */ ossim_uint32 getType() const { return termType::monomial; } /** * @brief Creates a copy of the monomial * * @return A pointer to a copy of the monomial */ ossimTerm* copy() const; private: ossim_float64 coef; // The coefficent of the monomial ossimTerm* var; // The variable number of the monomial (starts at 0 - n) ossim_float64 exp; // The exponenent of the monomial }; /** * A polynomial class to hold a polynomial as a term. */ class OSSIMDLLEXPORT ossimPolynomial : public ossimTerm{ public: /** * @brief Public Constructor * * @param leftTerm The left term * @param rightTerm The right term */ ossimPolynomial(ossimTerm* leftTerm, ossimTerm* rightTerm) : lTerm(leftTerm), rTerm(rightTerm) {} /** * @brief Public Copy Constructor * * @param[in] src The source to be copied */ ossimPolynomial(const ossimPolynomial& src) : lTerm(src.lTerm->copy()), rTerm(src.rTerm->copy()) {} /** * @brief Destroys the polynomial */ ~ossimPolynomial() { delete lTerm; delete rTerm; } /** * @brief Evaluates a polynomial for a point * * @param[in] point The point to be evaluated * * @return The value at a point. */ ossim_float64 evaluate(std::vector point) const { return lTerm->evaluate(point) + rTerm->evaluate(point); } /** * @brief Calculates the derivative for a polynomial * * @param[in] variable The variable in which the derivative is with respect too. * * @return A pointer to that contains the derivative of the term. */ ossimTerm* derivative(const ossim_uint32& variable) const; /** * @brief Gets the type of a polynomial * * @return The type of a polynomial */ ossim_uint32 getType() const { return termType::polynomial; } /** * @brief Creates a copy of the polynomial * * @return A pointer to a copy of the polynomial */ ossimTerm* copy() const; private: ossimTerm* lTerm; // The left term of the polynomial ossimTerm* rTerm; // The right term of the polynomial }; /** * A polynomial class to hold a product as a term. */ class OSSIMDLLEXPORT ossimProd : public ossimTerm{ public: /** * @brief Public Constructor * * @param leftTerm The left term * @param rightTerm The right term */ ossimProd(ossimTerm* leftTerm, ossimTerm* rightTerm) : lTerm(leftTerm), rTerm(rightTerm) {} /** * @brief Public Copy Constructor * * @param[in] src The source to be copied */ ossimProd(const ossimProd& src) : lTerm(src.lTerm->copy()), rTerm(src.rTerm->copy()) {} /** * @brief Destroys the product */ ~ossimProd() { delete lTerm; delete rTerm; } /** * @brief Evaluates a product for a point * * @param[in] point The point to be evaluated * * @return The value at a point. */ ossim_float64 evaluate(std::vector point) const { return lTerm->evaluate(point) * rTerm->evaluate(point); } /** * @brief Calculates the derivative for a product * * @param[in] variable The variable in which the derivative is with respect too. * * @return A pointer to that contains the derivative of the term. */ ossimTerm* derivative(const ossim_uint32& variable) const; /** * @brief Gets the type of a product * * @return The type of a product */ ossim_uint32 getType() const { return termType::product; } /** * @brief Creates a copy of the product * * @return A pointer to a copy of the product */ ossimTerm* copy() const; private: ossimTerm* lTerm; // The left term of the product ossimTerm* rTerm; // The right term of the product }; /** * A variable class to hold a variable as a term. */ class OSSIMDLLEXPORT ossimVar : public ossimTerm{ public: /** * @brief Public Constructor * * @param[in] variable The variable number */ ossimVar(const ossim_uint32& variable) : var(variable) {} /** * @brief Public Copy Constructor * * @param[in] src The source to be copied */ ossimVar(const ossimVar& src) : var(src.var) {} /** * @brief Destroys the variable */ ~ossimVar() {} /** * @brief Evaluates a variable for a point * * @param[in] point The point to be evaluated * * @return The value at a point. */ ossim_float64 evaluate(std::vector point) const{ return point[var]; } /** * @brief Calculates the derivative for a variable * * @param[in] variable The variable in which the derivative is with respect too. * * @return A pointer to that contains the derivative of the term. */ ossimTerm* derivative(const ossim_uint32& variable) const; /** * @brief Gets the type of a variable * * @return The type of a variable */ ossim_uint32 getType() const { return termType::variable; } /** * @brief Creates a copy of the variable * * @return A pointer to a copy of the variable */ ossimTerm* copy() const; private: ossim_uint32 var; // The number of the variable (0-n) }; /** * A constant class to hold a constant as a term. */ class OSSIMDLLEXPORT ossimConst : public ossimTerm { public: /** * @brief Public Constructor * * @param[in] value The value of the constant */ ossimConst(const ossim_float64& value) : val(value) {} /** * @brief Public Copy Constructor * * @param[in] src The source to be copied */ ossimConst(const ossimConst& src) : val(src.val) {} /** * @brief Destroys the constant */ ~ossimConst() {} /** * @brief Evaluates a constant for a point * * @param[in] point The point to be evaluated * * @return The value at a point. */ ossim_float64 evaluate(std::vector /* point */ ) const{ return val; } /** * @brief Calculates the derivative for a constant * * @param[in] variable The variable in which the derivative is with respect too. * * @return A pointer to that contains the derivative of the term. */ ossimTerm* derivative(const ossim_uint32& variable) const; /** * @brief Gets the type of a constant * * @return The type of a constant */ ossim_uint32 getType() const { return termType::constant; } /** * @brief Creates a copy of the constant * * @return A pointer to a copy of the constant */ ossimTerm* copy() const; private: ossim_float64 val; // The value of the constant }; #endif // OSSIM_TERM_H ossim-Miami-2.9.1/include/ossim/base/ossimTextProperty.h000066400000000000000000000021021352751253100233120ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimTextProperty.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimTextProperty_HEADER #define ossimTextProperty_HEADER #include class OSSIMDLLEXPORT ossimTextProperty : public ossimProperty { public: ossimTextProperty(const ossimString& name = ossimString(""), const ossimString& value = ossimString(""), bool isMultiLine = false); ossimTextProperty(const ossimTextProperty& rhs); virtual ossimObject* dup()const; bool isMulitLine()const; void setMultiLineFlag(bool flag); virtual void valueToString(ossimString& valueResult)const; virtual bool setValue(const ossimString& value); virtual const ossimProperty& assign(const ossimProperty& rhs); protected: ossimString theValue; bool theMultiLineFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimThinPlateSpline.h000066400000000000000000000106331352751253100236740ustar00rootroot00000000000000/****************************************************************************** * $Id: thinplatespline.h 14122 2008-03-30 10:33:39Z rouault $ * * Project: GDAL Warp API * Purpose: Declarations for 2D Thin Plate Spline transformer. * Author: VIZRT Development Team. * * This code was provided by Gilad Ronnen (gro at visrt dot com) with * permission to reuse under the following license. * ****************************************************************************** * Copyright (c) 2004, VIZRT Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef ossimThinPlateSpline_HEADER #define ossimThinPlateSpline_HEADER #include #include #include class OSSIM_DLL ossimThinPlateSpline { public: typedef enum { VIZ_GEOREF_SPLINE_ZERO_POINTS, VIZ_GEOREF_SPLINE_ONE_POINT, VIZ_GEOREF_SPLINE_TWO_POINTS, VIZ_GEOREF_SPLINE_ONE_DIMENSIONAL, VIZ_GEOREF_SPLINE_FULL, VIZ_GEOREF_SPLINE_POINT_WAS_ADDED, VIZ_GEOREF_SPLINE_POINT_WAS_DELETED } vizGeorefInterType; ossimThinPlateSpline(int nof_vars = 1){ _tx = _ty = 0.0; _ta = 10.0; _nof_points = 0; _nof_vars = nof_vars; _max_nof_points = 0; rhs.resize(_nof_vars); coef.resize(_nof_vars); growPoints(); for ( int v = 0; v < _nof_vars; v++ ) for ( int i = 0; i < 3; i++ ) // rhs[i][v] = 0.0; rhs[v][i] = 0.0; type = VIZ_GEOREF_SPLINE_ZERO_POINTS; } ~ossimThinPlateSpline(){ _AA.clear(); _Ainv.clear(); x.clear(); y.clear(); u.clear(); unused.clear(); index.clear(); rhs.clear(); coef.clear(); } int getNumberOfPoints()const { return _nof_points; } void setToler( double tx, double ty ){ _tx = tx; _ty = ty; } void getToler( double& tx, double& ty)const { tx = _tx; ty = _ty; } vizGeorefInterType getInterpolationType ( )const{ return type; } int deleteList() { _nof_points = 0; type = VIZ_GEOREF_SPLINE_ZERO_POINTS; _AA.clear(); _Ainv.clear(); return _nof_points; } void growPoints(); int addPoint( const double Px, const double Py, const double *Pvars ); int deletePoint(const double Px, const double Py ); int getPoint( const double Px, const double Py, double *Pvars )const; bool getXy(int index, double& x, double& y)const; bool changePoint(int index, double x, double y, double* Pvars); void reset(void) { _nof_points = 0; } int solve(void); private: double baseFunc( const double x1, const double y1, const double x2, const double y2 )const; vizGeorefInterType type; int _nof_vars; int _nof_points; int _max_nof_points; int _nof_eqs; double _tx, _ty; double _ta; double _dx, _dy; std::vector x; // [VIZ_GEOREF_SPLINE_MAX_POINTS+3]; std::vector y; // [VIZ_GEOREF_SPLINE_MAX_POINTS+3]; std::vector > rhs; std::vector > coef; std::vector u; // [VIZ_GEOREF_SPLINE_MAX_POINTS]; std::vector unused; // [VIZ_GEOREF_SPLINE_MAX_POINTS]; std::vector index; // [VIZ_GEOREF_SPLINE_MAX_POINTS]; std::vector _AA, _Ainv; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimThreeParamDatum.h000066400000000000000000000064051352751253100236560ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // ossimThreeParamDatum. This is a base class for all // three param datums. //******************************************************************* // $Id: ossimThreeParamDatum.h 19795 2011-06-30 15:04:48Z gpotts $ #ifndef ossimThreeParamDatum_HEADER #define ossimThreeParamDatum_HEADER #include class OSSIMDLLEXPORT ossimThreeParamDatum : public ossimDatum { public: /** * @param code new datum code. (input) * @param name Name of the new datum (input) * @param SigmaX Standard error in X in meters (input) * @param SigmaY Standard error in Y in meters (input) * @param SigmaZ Standard error in Z in meters (input) * @param southLatitude Southern edge of validity rectangle in radians(input) * @param northLatitude Northern edge of validity rectangle in radians(input) * @param westLongitude Western edge of validity rectangle in radians (input) * @param eastLongitude Eastern edge of validity rectangle in radians (input) * @param param1 X translation * @param param2 Y translation * @param param3 Z translation */ ossimThreeParamDatum(const ossimString &code, const ossimString &name, const ossimEllipsoid* anEllipsoid, ossim_float64 sigmaX, ossim_float64 sigmaY, ossim_float64 sigmaZ, ossim_float64 westLongitude, ossim_float64 eastLongitude, ossim_float64 southLatitude, ossim_float64 northLatitude, ossim_float64 param1, ossim_float64 param2, ossim_float64 param3) : ossimDatum(code, name, anEllipsoid, sigmaX, sigmaY, sigmaZ, westLongitude, eastLongitude, southLatitude, northLatitude), theParam1(param1), theParam2(param2), theParam3(param3) {} virtual ~ossimThreeParamDatum(){} /*! * Will shift a ground point to this datum. If they are the same * datum then nothing happens. */ virtual ossimGpt shift(const ossimGpt &aPt)const; virtual ossimGpt shiftToWgs84(const ossimGpt &aPt)const; virtual ossimGpt shiftFromWgs84(const ossimGpt &aPt)const; virtual ossim_float64 param1()const{return theParam1;} virtual ossim_float64 param2()const{return theParam2;} virtual ossim_float64 param3()const{return theParam3;} virtual ossim_float64 param4()const{return 0.0;} virtual ossim_float64 param5()const{return 0.0;} virtual ossim_float64 param6()const{return 0.0;} virtual ossim_float64 param7()const{return 1.0;} virtual bool isEqualTo(const ossimObject& obj, ossimCompareType compareType=OSSIM_COMPARE_FULL)const; protected: ossim_float64 theParam1; ossim_float64 theParam2; ossim_float64 theParam3; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimTieGpt.h000066400000000000000000000070161352751253100220260ustar00rootroot00000000000000#ifndef ossimTieGpt_HEADER #define ossimTieGpt_HEADER #include #include #include #include class ossimDpt; /** * storage class for tie point between ground and image * based on ossimGpt * + GML feature (OGC) serialization * * NOTES * accuracy is not stored here (need to derive object if need a per-point accuracy) * GML storage is WGS84 only, it stores above ellipsoid height (m) * * TODO : * -support other datum (easy) / ground projection (big change in OSSIM) * -unify with ossimTDpt */ class OSSIMDLLEXPORT ossimTieGpt : public ossimReferenced, public ossimGpt { public: inline ossimTieGpt() : ossimReferenced(), ossimGpt(), tie(), score(0.0) {} inline ossimTieGpt(const ossimGpt& aPt, const ossimDpt& aTie, const ossim_float64& aScore) : ossimReferenced(), ossimGpt(aPt), tie(aTie), score(aScore) {} inline ossimTieGpt(const ossimTieGpt& tpt) : ossimReferenced(tpt), ossimGpt(tpt), tie(tpt.tie), score(tpt.score) {} inline ~ossimTieGpt() {} const ossimTieGpt& operator=(const ossimTieGpt&); inline void setGroundPoint(const ossimGpt& mPt) { ossimGpt::operator=(mPt); } inline const ossimGpt& getGroundPoint()const { return *this; } inline ossimGpt& refGroundPoint() { return *this; } inline void setImagePoint(const ossimDpt& sPt) { tie=sPt; } inline const ossimDpt& getImagePoint()const { return tie; } inline ossimDpt& refImagePoint() { return tie; } inline void setScore(const ossim_float64& s) { score=s; } inline const ossim_float64& getScore()const { return score; } inline ossim_float64& refScore() { return score; } void makeNan() { ossimGpt::makeNan(); tie.makeNan(); score=ossim::nan(); } bool hasNans()const { return (ossimGpt::hasNans() || tie.hasNans() || (ossim::isnan(score))); } bool isNan()const { return (ossimGpt::isNan() && tie.isNan() && (ossim::isnan(score))); } /** * text serialization */ std::ostream& print(std::ostream& os) const; std::ostream& printTab(std::ostream& os) const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& os, const ossimTieGpt& pt); /** * Method to input the formatted string of the "operator<<". * * Expected format: ( ( ossimGpt ), ( ossimDpt ), 0.50000000000000 ) * --*this---- , ----tie-----, ---score-------- * */ friend OSSIMDLLEXPORT std::istream& operator>>(std::istream& is, ossimTieGpt& pt); /** * GML feauture (XML) serialization */ ossimRefPtr exportAsGmlNode(ossimString aGmlVersion="2.1.2")const; bool importFromGmlNode(ossimRefPtr aGmlNode, ossimString aGmlVersion="2.1.2"); /** * Public data members */ ossimDpt tie; ossim_float64 score; }; inline const ossimTieGpt& ossimTieGpt::operator=(const ossimTieGpt& pt) { if (this != &pt) { ossimReferenced::operator=(pt); ossimGpt::operator=(pt); tie = pt.tie; score = pt.score; } return *this; } #endif /* #ifndef ossimTieGpt_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimTieGptSet.h000066400000000000000000000100311352751253100224710ustar00rootroot00000000000000#ifndef ossimTieGptSet_HEADER #define ossimTieGptSet_HEADER #include #include #include #include #include #include class ossimDpt; /** * storage class for a set of geographic tie points, between master and slave images * + GML (OGC) serialization * * NOTES * master points are stored on the ground * ground SRS is EPSG:4326 only (WGS84) + height in meters above ellispoid * * slave points are stored as image positions * * general ground/image accuracy values are stored * * TODO : */ class OSSIMDLLEXPORT ossimTieGptSet { public: inline ossimTieGptSet() {} inline ossimTieGptSet(const ossimTieGptSet& aSet) : theTies(aSet.getTiePoints()), theMasterPath(aSet.getMasterPath()), theSlavePath(aSet.getSlavePath()), theImageCov(aSet.getImageCov()), theGroundCov(aSet.getGroundCov()) {} inline ~ossimTieGptSet() {} const ossimTieGptSet& operator=(const ossimTieGptSet&); // accessors inline void setTiePoints(const std::vector >& aTieSet) { theTies = aTieSet; } inline const std::vector >& getTiePoints()const { return theTies; } inline std::vector >& refTiePoints() { return theTies; } inline void setMasterPath(const ossimString& aPath) { theMasterPath = aPath; } inline const ossimString& getMasterPath()const { return theMasterPath; } inline void setSlavePath(const ossimString& aPath) { theSlavePath = aPath; } inline const ossimString& getSlavePath()const { return theSlavePath; } inline void setImageCov(const NEWMAT::SymmetricMatrix& aCovMat) { theImageCov = aCovMat; } inline const NEWMAT::SymmetricMatrix& getImageCov()const { return theImageCov; } inline NEWMAT::SymmetricMatrix& refImageCov() { return theImageCov; } inline void setGroundCov(const NEWMAT::SymmetricMatrix& aCovMat) { theGroundCov = aCovMat; } inline const NEWMAT::SymmetricMatrix& getGroundCov()const { return theGroundCov; } inline NEWMAT::SymmetricMatrix& refGroundCov() { return theGroundCov; } void getSlaveMasterPoints(std::vector& imv, std::vector& gdv)const; inline unsigned int size()const { return (unsigned int)theTies.size(); } /** * operations */ void addTiePoint(ossimRefPtr aTiePt); void clearTiePoints(); void getGroundBoundaries(ossimGpt& gBoundInf, ossimGpt& gBoundSup)const; /** * text output : header + tab separated tie points */ std::ostream& printTab(std::ostream& os) const; /** * GML features (XML) serialization */ ossimRefPtr exportAsGmlNode(ossimString aGmlVersion="2.1.2")const; bool importFromGmlNode(ossimRefPtr aGmlNode, ossimString aGmlVersion="2.1.2"); /** * Public data members */ static const char* TIEPTSET_TAG; protected: /** * Protected data members */ std::vector > theTies; //store by reference so derived classes can be used ossimString theMasterPath; //!full or relative path to master dataset ossimString theSlavePath; //!full or relative path to slave dataset NEWMAT::SymmetricMatrix theImageCov; //! image error covariance matrix NEWMAT::SymmetricMatrix theGroundCov; //! ground error covariance matrix /** * Protected methods */ ossimString symMatrixToText(const NEWMAT::SymmetricMatrix& sym, const ossimString& el_sep=" ", const ossimString& row_sep=";")const; NEWMAT::SymmetricMatrix textToSymMatrix(const ossimString& text, unsigned int dim, const ossimString& seps=" ;\t\r\n")const; //list of possible elements or row separators }; #endif /* #ifndef ossimTieGptSet_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimTieMeasurementGeneratorInterface.h000066400000000000000000000052361352751253100272530ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimTieMeasurementGeneratorInterface.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David hicks // // Description: OSSIM interface for tie measurement generator plugin. //---------------------------------------------------------------------------- // $Id #ifndef ossimTieMeasurementGeneratorInterface_HEADER #define ossimTieMeasurementGeneratorInterface_HEADER 1 #include #include #include #include class ossimImageSource; class ossimTieMeasurementGeneratorInterface { public: /** @brief Virtual destructor defined to squash compiler errors. */ virtual ~ossimTieMeasurementGeneratorInterface(){} // Initializer virtual bool init(std::ostream& report = std::cout) = 0; virtual bool setImageList(std::vector src) = 0; // Define collection ROIs, coordinate system depends on derived class use. List of AOIs // must correspond to the list of images. virtual bool setROIs(std::vector roi) = 0; virtual bool isValidCollectionBox() const = 0; // Measurement collection virtual bool run() = 0; // Report run parameters virtual void summarizeRun() const = 0; // Patch grid configuration accessors virtual void setUseGrid(const bool useGrid) = 0; virtual bool getUseGrid() const = 0; virtual bool setGridSize(const ossimIpt& gridDimensions) = 0; virtual ossimIpt getGridSize() const = 0; // Max matches in patch accessors virtual bool setMaxMatches(const int& maxMatches) = 0; virtual int getMaxMatches() const = 0; // Set the feature detector virtual bool setFeatureDetector(const ossimString& name) = 0; virtual ossimString getFeatureDetector() const = 0; // Set the descriptor-extractor virtual bool setDescriptorExtractor(const ossimString& name) = 0; virtual ossimString getDescriptorExtractor() const = 0; // Set the matcher virtual bool setDescriptorMatcher(const ossimString& name) = 0; virtual ossimString getDescriptorMatcher() const = 0; // Measured point access virtual int numMeasurements() const = 0; virtual ossimDpt pointIndexedAt(const ossim_uint32 imgIdx, const ossim_uint32 measIdx) = 0; // OpenCV drawMatches window virtual void closeCvWindow(const bool waitKeyPress = false) = 0; virtual void setShowCvWindow(const bool showCvWindow) = 0; virtual bool getShowCvWindow() const = 0; }; #endif /* #ifndef ossimTieMeasurementGeneratorInterface_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimTiffConstants.h000066400000000000000000000135661352751253100234260ustar00rootroot00000000000000//--- // // License: MIT // // Description: TIFF constants. Here for stand alone code; i.e., // code that does not use libtiff. // //--- // $Id$ #ifndef ossimTiffConstants_HEADER #define ossimTiffConstants_HEADER 1 namespace ossim { /** * Anonymous enumerations. Note prefixed with 'O' to avoid conflict with * libtiff. */ enum { OPIXEL_IS_AREA = 1, OPIXEL_IS_POINT = 2, OTIFFTAG_SUBFILETYPE = 254, OTIFFTAG_IMAGEWIDTH = 256, OTIFFTAG_IMAGELENGTH = 257, OTIFFTAG_BITSPERSAMPLE = 258, OTIFFTAG_COMPRESSION = 259, OTIFFTAG_PHOTOMETRIC = 262, OTIFFTAG_FILLORDER = 266, OTIFFTAG_IMAGEDESCRIPTION = 270, OTIFFTAG_MAKE = 271, OTIFFTAG_MODEL = 272, OTIFFTAG_STRIPOFFSETS = 273, OTIFFTAG_ORIENTATION = 274, OTIFFTAG_SAMPLESPERPIXEL = 277, OTIFFTAG_ROWSPERSTRIP = 278, OTIFFTAG_STRIPBYTECOUNTS = 279, OTIFFTAG_MINSAMPLEVALUE = 280, OTIFFTAG_MAXSAMPLEVALUE = 281, OTIFFTAG_XRESOLUTION = 282, OTIFFTAG_YRESOLUTION = 283, OTIFFTAG_PLANARCONFIG = 284, OTIFFTAG_PLANARCONFIG_CONTIG = 1, OTIFFTAG_PLANARCONFIG_SEPARATE = 2, OTIFFTAG_RESOLUTIONUNIT = 296, OTIFFTAG_PAGENUMBER = 297, OTIFFTAG_SOFTWARE = 305, // FORMAT is YYYY:MM:DD HH:MM:SS OTIFFTAG_DATETIME = 306, OTIFFTAG_ARTIST = 315, OTIFFTAG_PREDICTOR = 317, OTIFFTAG_COLORMAP = 320, OTIFFTAG_SUBIFD = 330, OTIFFTAG_TILEWIDTH = 322, OTIFFTAG_TILELENGTH = 323, OTIFFTAG_TILEOFFSETS = 324, OTIFFTAG_TILEBYTECOUNTS = 325, OTIFFTAG_EXTRASAMPLES = 338, OTIFFTAG_SAMPLEFORMAT = 339, OTIFFTAG_SMINSAMPLEVALUE = 340, OTIFFTAG_SMAXSAMPLEVALUE = 341, OTIFFTAG_YCBCRSUBSAMPLING = 530, OTIFFTAG_YCBCRPOSITIONING = 531, OTIFFTAG_REFERENCEBLACKWHITE = 532, OTIFFTAG_XMLPACKET = 700, OSAMPLEFORMAT_UINT = 1, OSAMPLEFORMAT_INT = 2, OSAMPLEFORMAT_IEEEFP = 3, OSAMPLEFORMAT_VOID = 4, OSAMPLEFORMAT_COMPLEXINT = 5, OSAMPLEFORMAT_COMPLEXIEEEFP = 6, OGT_MODEL_TYPE_GEO_KEY = 1024, OGT_RASTER_TYPE_GEO_KEY = 1025, OGT_CITATION_GEO_KEY = 1026, OGEOGRAPHIC_TYPE_GEO_KEY = 2048, OGEOG_CITATION_GEO_KEY = 2049, OGEOG_GEODETIC_DATUM_GEO_KEY = 2050, OGEOG_PRIME_MERIDIAN_GEOKEY = 2051, OGEOG_LINEAR_UNITS_GEO_KEY = 2052, OGEOG_ANGULAR_UNITS_GEO_KEY = 2054, OGEOG_ANGULAR_UNIT_SIZE_GEO_KEY = 2055, OGEOG_ELLIPSOID_GEO_KEY = 2056, OGEOG_SEMI_MAJOR_AXIS = 2057, OGEOG_SEMI_MINOR_AXIS = 2058, OGEOG_INV_FLATTENING_GEO_KEY = 2059, OGEOG_PRIME_MERIDIAN_LONG_GEO_KEY = 2061, OPROJECTED_CS_TYPE_GEO_KEY = 3072, OPCS_CITATION_GEO_KEY = 3073, OPROJECTION_GEO_KEY = 3074, OPROJ_COORD_TRANS_GEO_KEY = 3075, OPROJ_LINEAR_UNITS_GEO_KEY = 3076, OPROJ_LINEAR_UNIT_SIZE_GEO_KEY = 3077, OPROJ_STD_PARALLEL1_GEO_KEY = 3078, OPROJ_STD_PARALLEL2_GEO_KEY = 3079, OPROJ_NAT_ORIGIN_LONG_GEO_KEY = 3080, OPROJ_NAT_ORIGIN_LAT_GEO_KEY = 3081, OPROJ_FALSE_EASTING_GEO_KEY = 3082, OPROJ_FALSE_NORTHING_GEO_KEY = 3083, OPROJ_FALSE_ORIGIN_LONG_GEO_KEY = 3084, OPROJ_FALSE_ORIGIN_LAT_GEO_KEY = 3085, OPROJ_FALSE_ORIGIN_EASTING_GEO_KEY = 3086, OPROJ_FALSE_ORIGIN_NORTHING_GEO_KEY = 3087, OPROJ_CENTER_LONG_GEO_KEY = 3088, OPROJ_CENTER_LAT_GEO_KEY = 3089, OPROJ_SCALE_AT_NAT_ORIGIN_GEO_KEY = 3092, OPROJ_SCALE_AT_CENTER_GEO_KEY = 3093, OVERTICAL_Cs_TYPE_GEO_KEY = 4096, OVERTICAL_CITATION_GEO_KEY = 4097, OVERTICAL_DATUM_GEO_KEY = 4098, OVERTICAL_UNITS_GEO_KEY = 4099, OLINEAR_METER = 9001, OLINEAR_FOOT = 9002, OLINEAR_FOOT_US_SURVEY = 9003, OANGULAR_DEGREE = 9102, OANGULAR_ARC_MINUTE = 9103, OANGULAR_ARC_SECOND = 9104, OANGULAR_GRAD = 9105, OANGULAR_GON = 9106, OANGULAR_DMS = 9107, OANGULAR_DMS_HEMISPHERE = 9108, OPCS_BRITISH_NATIONAL_GRID = 27700, OUSER_DEFINED = 32767, OTIFFTAG_COPYRIGHT = 33432, OMODEL_PIXEL_SCALE_TAG = 33550, OMODEL_TIE_POINT_TAG = 33922, OMODEL_TRANSFORM_TAG = 34264, OTIFFTAG_PHOTOSHOP = 34377, OGEO_KEY_DIRECTORY_TAG = 34735, OGEO_DOUBLE_PARAMS_TAG = 34736, OGEO_ASCII_PARAMS_TAG = 34737, OGDAL_METADATA_TAG = 42112, OGDAL_NODATA = 42113, ORPC_COEFFICIENT_TAG = 50844 }; enum CompressType { COMPRESSION_NONE = 1 }; enum PhotoInterpretation { OPHOTO_MINISWHITE = 0, // min value is white OPHOTO_MINISBLACK = 1, // min value is black OPHOTO_RGB = 2, // RGB color model OPHOTO_PALETTE = 3, // color map indexed OPHOTO_MASK = 4, // $holdout mask OPHOTO_SEPARATED = 5, // !color separations OPHOTO_YCBCR = 6, // !CCIR 601 OPHOTO_CIELAB = 7, // !1976 CIE L*a*b* OPHOTO_ICCLAB = 9, OPHOTO_ITULAB = 10, OPHOTO_LAST = 11, // this is here for range checking OPHOTO_LOGL = 32844, OPHOTO_LOGLUV = 32845 }; enum ModelType { UNKNOWN = 0, OMODEL_TYPE_PROJECTED = 1, // Projection Coordinate System OMODEL_TYPE_GEOGRAPHIC = 2, // Geographic latitude-longitude System OMODEL_TYPE_GEOCENTRIC = 3 }; enum { OTIFF_NOTYPE = 0, /* placeholder */ OTIFF_BYTE = 1, /* 8-bit unsigned integer */ OTIFF_ASCII = 2, /* 8-bit bytes w/ last byte null */ OTIFF_SHORT = 3, /* 16-bit unsigned integer */ OTIFF_LONG = 4, /* 32-bit unsigned integer */ OTIFF_RATIONAL = 5, /* 64-bit unsigned fraction */ OTIFF_SBYTE = 6, /* !8-bit signed integer */ OTIFF_UNDEFINED = 7, /* !8-bit untyped data */ OTIFF_SSHORT = 8, /* !16-bit signed integer */ OTIFF_SLONG = 9, /* !32-bit signed integer */ OTIFF_SRATIONAL = 10, /* !64-bit signed fraction */ OTIFF_FLOAT = 11, /* !32-bit IEEE floating point */ OTIFF_DOUBLE = 12, /* !64-bit IEEE floating point */ OTIFF_IFD = 13, /* %32-bit unsigned integer (offset) */ OTIFF_LONG8 = 16, /* BigTIFF 64-bit unsigned integer */ OTIFF_SLONG8 = 17, /* BigTIFF 64-bit signed integer */ OTIFF_IFD8 = 18 /* BigTIFF 64-bit unsigned integer (offset) */ }; } // End: namespace ossim #endif /* End of "#ifndef ossimTiffConstants_HEADER" */ ossim-Miami-2.9.1/include/ossim/base/ossimTileHash.h000066400000000000000000000024611352751253100223320ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken Copied from TiledImageHash. // // Description: Hashing function for tiled rectangles. Will hash a // dpt or fpt to a single index value. // // NOTE: Works on rectangles that are positive in the line up (y) // direction. Use TiledImageHash for rectangles that are positive // in the line down direction. // //******************************************************************* // $Id: ossimTileHash.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef TileHash_HEADER #define TileHash_HEADER #include #include class OSSIMDLLEXPORT ossimTileHash : public ossimPointHash { public: ossimTileHash(const ossimDrect &imageRect, double tileWidth, double tileHeight); virtual ~ossimTileHash(); virtual long operator()(const ossimDpt &aPoint); virtual long operator()(const ossimFpt &aPoint); private: ossimDrect theImageRect; double theTileWidth; double theTileHeight; long theNumberOfHorizTiles; long theNumberOfVertTiles; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimTiledImageHash.h000066400000000000000000000022211352751253100234330ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Hashing function for tiled rectangles. Will hash a // dpt to a single index value. // //******************************************************************* // $Id: ossimTiledImageHash.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimTiledImageHash_HEADER #define ossimTiledImageHash_HEADER #include #include class OSSIMDLLEXPORT ossimTiledImageHash : public ossimPointHash { public: ossimTiledImageHash(const ossimDrect &imageRect, double tileWidth, double tileHeight); virtual ~ossimTiledImageHash(); virtual long operator()(const ossimDpt &aPoint); virtual long operator()(const ossimFpt &aPoint); private: ossimDrect theImageRect; double theTileWidth; double theTileHeight; long theNumberOfHorizTiles; long theNumberOfVertTiles; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimTimer.h000066400000000000000000000045351352751253100217150ustar00rootroot00000000000000/* * This code was taken from the OpenScene graph. */ #ifndef ossimTimer_HEADER #define ossimTimer_HEADER 1 #include "ossimConstants.h" /** Timer class is used for measuring elapsed time or time between two points. */ class OSSIM_DLL ossimTimer { public: #if defined(_MSC_VER) typedef __int64 Timer_t; #else typedef unsigned long long Timer_t; #endif ossimTimer(); ~ossimTimer() {m_instance = 0;} static ossimTimer* instance(); /** Get the timers tick value.*/ Timer_t tick() const; /** Set the start.*/ void setStartTick() { m_startTick = tick(); } void setStartTick(Timer_t t) { m_startTick = t; } Timer_t getStartTick() const { return m_startTick; } /** Get elapsed time in seconds.*/ inline double time_s() const { return delta_s(m_startTick, tick()); } /** Get elapsed time in milliseconds.*/ inline double time_m() const { return delta_m(m_startTick, tick()); } /** Get elapsed time in micoseconds.*/ inline double time_u() const { return delta_u(m_startTick, tick()); } /** Get elapsed time in nanoseconds.*/ inline double time_n() const { return delta_n(m_startTick, tick()); } /** Get the time in seconds between timer ticks t1 and t2.*/ inline double delta_s( Timer_t t1, Timer_t t2 ) const { return (double)(t2 - t1)*m_secsPerTick; } inline double delta_s( Timer_t t1) const { return (double)(tick() - t1)*m_secsPerTick; } /** Get the time in milliseconds between timer ticks t1 and t2.*/ inline double delta_m( Timer_t t1, Timer_t t2 ) const { return delta_s(t1,t2)*1e3; } inline double delta_m( Timer_t t1) const { return delta_s(t1,tick())*1e3; } /** Get the time in microseconds between timer ticks t1 and t2.*/ inline double delta_u( Timer_t t1, Timer_t t2 ) const { return delta_s(t1,t2)*1e6; } inline double delta_u( Timer_t t1) const { return delta_s(t1,tick())*1e6; } /** Get the time in nanoseconds between timer ticks t1 and t2.*/ inline double delta_n( Timer_t t1, Timer_t t2 ) const { return delta_s(t1,t2)*1e9; } inline double delta_n( Timer_t t1) const { return delta_s(t1,tick())*1e9; } /** Get the the number of seconds per tick. */ inline double getSecondsPerTick() const { return m_secsPerTick; } protected: static ossimTimer* m_instance; Timer_t m_startTick; double m_secsPerTick; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimTrace.h000066400000000000000000000033171352751253100216700ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimTrace.h // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of class ossimTrace. Used for tracing code execution. // Implemented as a singluy linked list of ossimTrace objects. // // SOFTWARE HISTORY: // 24Apr2001 Oscar Kramer // Initial coding. //***************************************************************************** // $Id: ossimTrace.h 11650 2007-08-24 12:02:47Z dburken $ #ifndef ossimTrace_HEADER #define ossimTrace_HEADER #include #include // Macro for use with trace... #define CLOG ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " (\"" __FILE__ "\", line " << __LINE__ << ") DEBUG: " class OSSIMDLLEXPORT ossimTrace { public: ossimTrace( const ossimString& trace_name ); ~ossimTrace(); /** * @returns true if enabled false if not. */ bool isEnabled() const { return theEnabledFlag; } /** * Returns "theTraceName" as an ossimString. */ ossimString getTraceName() const { return theTraceName; } /** * Sets "theEnabled" flag. * * @param flag true == enabled, false == disabled. */ void setTraceFlag(bool flag) { theEnabledFlag = flag; } /** * Operator() for ossimTrace. Given the static instance: * static ossimTrace traceDebug("myTrace"); * * You can do: * if (traceDebug()) * { * CLOG << "Your trace stuff goes here..." << std::endl; * } */ bool operator()() const { return theEnabledFlag; } private: ossimString theTraceName; bool theEnabledFlag; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimTraceManager.h000066400000000000000000000035031352751253100231600ustar00rootroot00000000000000//***************************************************************************** // Copyright (C) 2005 Garrett Potts, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // DESCRIPTION: // Contains declaration of class ossimTraceManager. // //***************************************************************************** // $Id: ossimTraceManager.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimTraceManager_HEADER #define ossimTraceManager_HEADER #include class ossimTrace; class OSSIMDLLEXPORT ossimTraceManager { public: /** * @return ossimTraceManager* to instance of the ossim trace manager. */ static ossimTraceManager* instance(); /** * Sets "thePattern" to "pattern", then calls setTraceFlags(true). * * @param pattern Regular expression to enable trace for. */ void setTracePattern(const ossimString& pattern); /** * @param traceObj ossimTrace* to add to "theTraceList". */ void addTrace(ossimTrace* traceObj); /** * @param traceObj ossimTrace* to remove from "theTraceList". */ void removeTrace(ossimTrace* traceObj); protected: /** Protected default constructor. */ ossimTraceManager(); private: /** * Loops through "theTraceList" and sets any trace object's enable flag to * flag if it matches regular expression of "thePattern". * For trace objects not matching "thePattern" no action is taken. */ void setTraceFlags(bool flag); /** The instance of this manager. */ static ossimTraceManager* theInstance; /** The regular expression pattern like "ossimDynamic|ossimGdal". */ ossimString thePattern; /** The list of trace objects. */ std::vector theTraceList; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimUnitConversionTool.h000066400000000000000000000044771352751253100244650ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimUnitConversionTool.h 10378 2007-01-26 14:27:21Z gpotts $ #ifndef ossimUnitConversionTool_HEADER #define ossimUnitConversionTool_HEADER #include #include #include class OSSIM_DLL ossimUnitConversionTool { public: friend std::ostream& operator<<(std::ostream& out, const ossimUnitConversionTool& data); ossimUnitConversionTool(double value=1.0, ossimUnitType unitType=OSSIM_METERS); ossimUnitConversionTool(const ossimGpt& origin, double value, ossimUnitType unitType=OSSIM_METERS); void setOrigin(const ossimGpt& gpt); ossimGpt getOrigin()const; void getOrigin(ossimGpt& result)const; void setValue(double value, ossimUnitType unitType=OSSIM_METERS); double getValue(ossimUnitType unitType=OSSIM_METERS) const; void setMeters(double value); void setRadians(double value); void setDegrees(double value); void setMinutes(double value); void setSeconds(double value); void setUsSurveyFeet(double value); void setFeet(double value); void setNauticalMiles(double value); void setMiles(double value); void setMillimeters(double value); void setMicrons(double value); void setCentimeters(double value); void setYards(double value); void setInches(double value); void setKilometers(double value); double getMeters()const; double getRadians()const; double getDegrees()const; double getMinutes()const; double getSeconds()const; double getUsSurveyFeet()const; double getFeet()const; double getNauticalMiles()const; double getMiles()const; double getMillimeters()const; double getMicrons()const; double getCentimeters()const; double getYards()const; double getInches()const; double getKilometers()const; protected: double theValue; ossimUnitType theUnitType; ossimGpt theOrigin; double computeMeters()const; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimUnitTypeLut.h000066400000000000000000000033601352751253100230760ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimUnitTypeLut.h 22857 2014-08-05 15:02:58Z gpotts $ #ifndef ossimUnitTypeLut_HEADER #define ossimUnitTypeLut_HEADER #include #include class OSSIMDLLEXPORT ossimUnitTypeLut : public ossimLookUpTable { public: /** * Returns the static instance of an ossimUnitTypeLut object. */ static ossimUnitTypeLut* instance(); virtual ~ossimUnitTypeLut(); /*! * Returns the entry number associated with the entry string passed in. * Returns OSSIM_UNIT_UNKNOWN if entry string is not in the list. * If case_insensitive == true(default), the test is case insensitive; * else, the test will be case sensitive. */ virtual ossim_int32 getEntryNumber(const char* entry_string, bool case_insensitive = true) const; /*! * Returns the entry number associated with the lookup table keyword * entry in the Keywordlist passed in. Returns NOT_FOUND(-1) if no * matching entry. * If case_insensitive == true(default), the test is case insensitive; * else, the test will be case sensitive. */ virtual ossim_int32 getEntryNumber(const ossimKeywordlist& kwl, const char* prefix=0, bool case_insensitive = true) const; virtual ossimKeyword getKeyword() const; protected: ossimUnitTypeLut(); private: // static ossimUnitTypeLut* theInstance; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimUrl.h000066400000000000000000000024511352751253100213720ustar00rootroot00000000000000#ifndef ossimUrl_HEADER #define ossimUrl_HEADER #include #include #include class OSSIM_DLL ossimUrl { public: ossimUrl(); ossimUrl(const ossimString& url); ossimUrl(const ossimString& protocol, const ossimString& ip, const ossimString& port, const ossimString& path, const ossimString& params); const ossimString& getProtocol()const{return m_protocol;} const ossimString& getIp()const{return m_ip;} const ossimString& getPort()const{return m_port;} const ossimString& getPath()const{return m_path;} const ossimString& getParams()const{return m_params;} void setProtocol(const ossimString& protocol){m_protocol = protocol;} void setIp(const ossimString& ip); void setPort(const ossimString& port){m_port = port;} void setPath(const ossimString& path){m_path = path;} void setParams(const ossimString& params){m_params = params;} void setParams(const ossimKeywordlist& kwl); void setFieldsFromUrl(const ossimString& url); ossimString toString()const; protected: ossimString m_protocol; ossimString m_ip; ossimString m_port; ossimString m_path; ossimString m_params; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimUsgsQuad.h000066400000000000000000000063241352751253100223670ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimUsgsQuad.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimUsgsQuad_HEADER #define ossimUsgsQuad_HEADER #include #include #include #include #include #include class OSSIMDLLEXPORT ossimUsgsQuad { public: ossimUsgsQuad(const ossimGpt& lrGpt); ossimUsgsQuad(const ossimString& name, const ossimDatum* datum); // double paddingInMeters = 100); void setQuadName(const ossimString& name); /*! Returns the bounding rectangle of the quarter quad segment. * A segment is 1/4 of a quarter quad. * Segment assingments: upper_left=A, upper_right=B, lower_left=C, * lower_right=D NOTE: padding is added in. */ ossimGrect quarterQuadSegRect(char seg); /*! Returns the bounding rectangle of the quarter quad segment * in the "area.lat_lon" keyword format: * start_lat, start_lon, stop_lat, stop_lon * NOTE: padding is added in. */ ossimString quarterQuadSegKwRect(char seg); /*! Returns the bounding rectangle of the quarter quad (3.75 minutes). * NOTE: padding is added in. */ ossimGrect quarterQuadRect() const; /*! Returns the bounding rectangle of the quarter quad (3.75 minutes) * in the "area.lat_lon" keyword format: * start_lat, start_lon, stop_lat, stop_lon * NOTE: padding is added in. */ ossimString quarterQuadKwRect() const; /*! Returns the bounding rectangle of the quarter quad (7.5 minutes). * NOTE: padding is added in. */ ossimGrect quadRect() const; /*! Returns the bounding rectangle of the quarter quad (7.5 minutes) * in the "area.lat_lon" keyword format: * start_lat, start_lon, stop_lat, stop_lon * NOTE: padding is added in. */ ossimString quadKwRect() const; /*! * Returns the USGS quarter quad name. */ ossimString quarterQuadName() const { return ossimString(theName.begin(), theName.begin()+7); } ossimString quarterQuadSegName() const { return theName; } /*! * Returns the lower right hand corner of quad with no padding. */ ossimGpt lrQuadCorner() const { return theQuadLowerRightCorner ; } /*! * Returns the lower right hand corner of quarter quad with no padding. */ ossimGpt lrQuarterQuadCorner() const { return theQuarterQuadLowerRightCorner; } static void getQuadList(std::vector& result, const ossimGrect& rect); protected: ossimString theName; ossimGpt theQuadLowerRightCorner; // Lower right corner of quad. ossimGpt theQuarterQuadLowerRightCorner;// quarter quad lr corner. // ossimDpt thePaddingInDegrees; char theQuarterQuadSegment; // A, B, C, D }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimViewController.h000066400000000000000000000031371352751253100236100ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimViewController.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimViewController_HEADER #define ossimViewController_HEADER #include #include /*! * All view sources will derive from this class. For example * we can have a mapped view or Perspective view of the scene * being rendered. All sources within the containers are expected * to derive from the view interface. */ class OSSIMDLLEXPORT ossimViewController : public ossimSource { public: ossimViewController(); ossimViewController(ossimObject* owner, ossim_uint32 inputListSize, ossim_uint32 outputListSize, bool inputListFixedFlag=true, bool outputListFixedFlag=false); virtual ~ossimViewController(); virtual ossimString getShortName()const; virtual ossimString getLongName()const; virtual bool propagateView(); virtual bool setView(ossimObject* object); virtual ossimObject* getView(); virtual const ossimObject* getView()const; virtual bool canConnectMyInputTo(ossim_int32 index, const ossimConnectableObject* obj)const; virtual const ossimObject* findFirstViewOfType(RTTItypeid typeId)const; protected: ossimRefPtr theView; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimViewEvent.h000066400000000000000000000105431352751253100225450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: A brief description of the contents of the file. // // //************************************************************************* // $Id: ossimViewEvent.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimViewEvent_HEADER #define ossimViewEvent_HEADER #include #include class OSSIMDLLEXPORT ossimViewEvent : public ossimEvent { public: enum ossimViewEventType { OSSIM_VIEW_EVENT_TYPE_GENERIC = 0, OSSIM_VIEW_EVENT_SCALE_CHANGE, OSSIM_VIEW_EVENT_TRANSFORM_CHANGE, OSSIM_VIEW_EVENT_VIEW_TYPE_CHANGE }; enum ossimViewPropagateType { OSSIM_VIEW_EVENT_PROPAGATE_NONE = 0, OSSIM_VIEW_EVENT_PROPAGATE_ALL_DISPLAYS = 1, OSSIM_VIEW_EVENT_PROPAGATE_ALL_CHAINS = 2, }; ossimViewEvent(ossimObject* view, ossimGpt centerPt, ossimViewPropagateType propagateType = OSSIM_VIEW_EVENT_PROPAGATE_NONE, ossimViewEventType eventType = OSSIM_VIEW_EVENT_TYPE_GENERIC, ossimObject* object=NULL) :ossimEvent(object, OSSIM_EVENT_VIEW_ID), theView(view), theCenterPoint(centerPt), theEventType(eventType), thePropagateType(propagateType), theUpdateInputViewFlag(true), theRefreshDisplayFlag(true) { } ossimViewEvent(const ossimViewEvent& rhs) :ossimEvent(rhs), theView(rhs.theView), theCenterPoint(rhs.theCenterPoint), theEventType(rhs.theEventType), thePropagateType(rhs.thePropagateType), theUpdateInputViewFlag(rhs.theUpdateInputViewFlag), theRefreshDisplayFlag(rhs.theRefreshDisplayFlag) { } virtual ossimObject* dup()const { return new ossimViewEvent(*this); } virtual void setView(ossimObject* view) { theView = view; } virtual ossimObject* getView() { return theView; } void disablePropagation() { thePropagateType = OSSIM_VIEW_EVENT_PROPAGATE_NONE; } void setPropagateType(ossimViewPropagateType type) { thePropagateType = type; } void setViewEventType(ossimViewEventType eventType) { theEventType = eventType; } void setEventTypeViewTypeChange() { theEventType = OSSIM_VIEW_EVENT_VIEW_TYPE_CHANGE; } void setEventTypeTransformChange() { theEventType = OSSIM_VIEW_EVENT_TRANSFORM_CHANGE; } void setEventTypeGeneric() { theEventType = OSSIM_VIEW_EVENT_TYPE_GENERIC; } void setCenterGroundPoint(const ossimGpt& gpt) { theCenterPoint = gpt; } const ossimGpt& getCenterGroundPoint()const { return theCenterPoint; } ossimViewEventType getViewEventType()const { return theEventType; } bool isViewChange()const { return (theEventType == OSSIM_VIEW_EVENT_VIEW_TYPE_CHANGE); } bool isTransformChange()const { return (theEventType == OSSIM_VIEW_EVENT_TRANSFORM_CHANGE); } bool isScaleChange()const { return (theEventType == OSSIM_VIEW_EVENT_SCALE_CHANGE); } bool isPropagateEnabled()const { return (thePropagateType != OSSIM_VIEW_EVENT_PROPAGATE_NONE); } bool isPropagateToDisplays()const { return (thePropagateType & OSSIM_VIEW_EVENT_PROPAGATE_ALL_DISPLAYS); } bool isPropagateToChains()const { return (thePropagateType & OSSIM_VIEW_EVENT_PROPAGATE_ALL_CHAINS); } void setUpdateInputViewFlag(bool flag) { theUpdateInputViewFlag = flag; } bool getUpdateInputViewFlag()const { return theUpdateInputViewFlag; } void setRefreshDisplayFlag(bool flag) { theRefreshDisplayFlag = flag; } bool getRefreshDisplayFlag()const { return theRefreshDisplayFlag; } protected: ossimObject* theView; ossimGpt theCenterPoint; ossimViewEventType theEventType; ossimViewPropagateType thePropagateType; bool theUpdateInputViewFlag; bool theRefreshDisplayFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimViewInterface.h000066400000000000000000000025361352751253100233670ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimViewInterface.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimViewInterface_HEADER #define ossimViewInterface_HEADER #include class ossimObject; class OSSIMDLLEXPORT ossimViewInterface { public: ossimViewInterface(); ossimViewInterface(ossimObject* base); virtual ~ossimViewInterface(); /*! * The derived classes should overrid this method and * return true or false whether it was able to cast the * past in view to a view that it can interface to. * So if you are a projective view you might * cast to an ossimProjection. The ownsTheView specifies * whether or not it owns the passed in view pointer. * This will specifiy whether or not the derived classes * need to re-allocate the pointer or just delete its old * pointer and set it to the passed in pointer. */ virtual bool setView(ossimObject* baseObject)=0; virtual ossimObject* getView()=0; virtual const ossimObject* getView()const=0; virtual void refreshView(); ossimObject* getBaseObject(); protected: ossimObject* theObject; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimViewListener.h000066400000000000000000000021261352751253100232470ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: A brief description of the contents of the file. // // //************************************************************************* // $Id: ossimViewListener.h 17195 2010-04-23 17:32:18Z dburken $ #ifndef ossimViewListener_HEADER #define ossimViewListener_HEADER #include #include class OSSIMDLLEXPORT ossimViewListener : public ossimListener { public: ossimViewListener():ossimListener(){} virtual ~ossimViewListener(){} virtual void processEvent(ossimEvent& event); virtual void viewScaleChangeEvent(ossimViewEvent& /* event */) {} virtual void viewTypeChangeEvent(ossimViewEvent& /* event */) {} virtual void viewEvent(ossimViewEvent& /* event */ ) {} virtual void viewTransformChangeEvent(ossimViewEvent& /* event */) {} virtual void allViewEvents(ossimViewEvent& /* event */) {} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimVisitor.h000066400000000000000000000152761352751253100223000ustar00rootroot00000000000000// $Id: ossimVisitor.h 22790 2014-05-16 19:19:30Z gpotts $ #ifndef ossimVisitor_HEADER #define ossimVisitor_HEADER 1 #include #include #include #include #include #include #include class ossimConnectableObject; class OSSIM_DLL ossimVisitor : public ossimReferenced { public: typedef std::set > MarkCollectionRef; typedef std::set > CollectionRef; typedef std::vector > ListRef; typedef std::set Collection; typedef std::vector List; /** * Enumeration type can be a mask and will traverse a graph of connectables based on the values. */ enum VisitorType { VISIT_NONE = 0, VISIT_CHILDREN = 1, VISIT_INPUTS = 2, VISIT_OUTPUTS = 4, VISIT_ALL = (VISIT_CHILDREN|VISIT_INPUTS|VISIT_OUTPUTS) }; ossimVisitor(int visitorType = VISIT_NONE); ossimVisitor(const ossimVisitor& src); virtual void reset(); virtual ossimRefPtr dup()const=0; virtual void visit(ossimObject* obj); virtual void visit(ossimConnectableObject* obj); VisitorType getVisitorType()const; void setVisitorType(int vType, bool on=true); void turnOffVisitorType(int vType); bool hasVisited(ossimObject* obj)const; bool stopTraversal()const; protected: VisitorType m_visitorType; mutable Collection m_markNode; mutable bool m_stopTraversalFlag; }; class OSSIM_DLL ossimCollectionVisitor : public ossimVisitor { public: ossimCollectionVisitor(int visitorType =(VISIT_INPUTS|VISIT_CHILDREN)); ossimCollectionVisitor(const ossimCollectionVisitor& src); ListRef& getObjects(); const ListRef& getObjects()const; ossimObject* getObject(ossim_uint32 idx = 0); const ossimObject* getObject(ossim_uint32 idx = 0)const; // Inlined to force template instantiation. template T* getObjectAs(ossim_uint32 idx=0) { if(idx < m_collection.size()) { return dynamic_cast(m_collection[idx].get()); } return 0; } // Inlined to force template instantiation. template const T* getObjectAs(ossim_uint32 idx=0)const { if(idx < m_collection.size()) { return dynamic_cast(m_collection[idx].get()); } return 0; } virtual void reset(); protected: ListRef m_collection; }; class OSSIM_DLL ossimIdVisitor : public ossimVisitor { public: /** * @brief Default constructor * Constructs with id of 0 and vistor type of VISIT_INPUTS|VISIT_CHILDREN. */ ossimIdVisitor(); ossimIdVisitor(int visitorType); ossimIdVisitor(const ossimId& id, int visitorType =(VISIT_INPUTS|VISIT_CHILDREN)); ossimIdVisitor(const ossimIdVisitor& src); virtual ossimRefPtr dup()const; virtual void visit(ossimConnectableObject* obj); /** @brief Resets m_object to 0, calls ossimVisitor::reset(). */ virtual void reset(); ossimConnectableObject* getObject(); const ossimConnectableObject* getObject()const; void setId(const ossimId& id); const ossimId& getId()const; protected: ossimConnectableObject* m_object; ossimId m_id; }; class OSSIM_DLL ossimTypeNameVisitor : public ossimCollectionVisitor { public: ossimTypeNameVisitor(int visitorType =(VISIT_INPUTS|VISIT_CHILDREN)); ossimTypeNameVisitor(const ossimString& typeName, bool firstofTypeFlag=false, int visitorType =(VISIT_INPUTS|VISIT_CHILDREN)); ossimTypeNameVisitor(const ossimTypeNameVisitor& src); virtual ossimRefPtr dup()const; virtual void visit(ossimObject* obj); void setTypeName(const ossimString& typeName); const ossimString& getTypeName()const; /** * @brief Set the m_firstOfTypeFlag. * * @param flag If flag is true, ossimTypeNameVisitor::visit will stop traversing if it * finds an object of m_typeName. */ void setFirstOfTypeFlag(bool flag); /** @return m_firstOfTypeFlag */ bool getFirstOfTypeFlag() const; protected: ossimString m_typeName; bool m_firstOfTypeFlag; }; class OSSIM_DLL ossimTypeIdVisitor : public ossimCollectionVisitor { public: ossimTypeIdVisitor(int visitorType =(VISIT_INPUTS|VISIT_CHILDREN)); ossimTypeIdVisitor(const RTTItypeid& typeId, bool firstofTypeFlag=false, int visitorType =(VISIT_INPUTS|VISIT_CHILDREN)); ossimTypeIdVisitor(const ossimTypeIdVisitor& src); virtual ossimRefPtr dup()const; virtual void visit(ossimObject* obj); void setTypeId(const RTTItypeid& typeId); const RTTItypeid& getTypeId()const; protected: RTTItypeid m_typeId; bool m_firstOfTypeFlag; }; class OSSIM_DLL ossimEventVisitor : public ossimVisitor { public: ossimEventVisitor(ossimEvent* evt, int visitorType =(VISIT_OUTPUTS|VISIT_CHILDREN)); ossimEventVisitor(const ossimEventVisitor& src); virtual ossimRefPtr dup()const; virtual void visit(ossimObject* obj); protected: ossimRefPtr m_event; }; /** * @class ossimViewInterfaceVisitor * * Visitor to update view and then propagate property event to outputs. */ class OSSIM_DLL ossimViewInterfaceVisitor : public ossimVisitor { public: ossimViewInterfaceVisitor(ossimObject* view, int visitorType =(VISIT_OUTPUTS|VISIT_CHILDREN)); ossimViewInterfaceVisitor(const ossimViewInterfaceVisitor& src); virtual ossimRefPtr dup()const; /** * @brief Calls ossimViewInterface::setView if obj cast to * ossimViewInterface*. On success a property event is sent to * output side so that things like ossimCombiner can reinitialize if * needed. * * @param obj Object to visit. */ virtual void visit(ossimObject* obj); ossimObject* getView(); const ossimObject* getView()const; protected: ossimRefPtr m_view; }; /** * @class ossimSourceInitializeVisitor * * Visitor to update view and then propagate property event to outputs. */ class OSSIM_DLL ossimSourceInitializeVisitor : public ossimVisitor { public: ossimSourceInitializeVisitor(int visitorType = VISIT_OUTPUTS); ossimSourceInitializeVisitor(const ossimSourceInitializeVisitor& src); virtual ossimRefPtr dup()const; /** * @brief Calls ossimViewInterface::setView if obj cast to * ossimViewInterface*. On success a property event is sent to * output side so that things like ossimCombiner can reinitialize if * needed. * * @param obj Object to visit. */ virtual void visit(ossimObject* obj); }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimVrect.h000066400000000000000000000107141352751253100217140ustar00rootroot00000000000000//******************************************************************* // // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // // Contains class declaration for vrect. // Container class for four double points representing a rectangle // where y is up // //******************************************************************* // $Id: ossimVrect.h 11955 2007-10-31 16:10:22Z gpotts $ #ifndef ossimVrect_HEADER #define ossimVrect_HEADER #include #include class OSSIMDLLEXPORT ossimVrect { public: ossimVrect() :theUlCorner(0.0, 0.0), theLlCorner(0.0, 0.0), theLrCorner(0.0, 0.0), theUrCorner(0.0, 0.0) {} ossimVrect(const ossimDpt &ul, const ossimDpt &lr) :theUlCorner(ul), theLlCorner(ul.x, lr.y), theLrCorner(lr), theUrCorner(lr.x, ul.y) {} ossimVrect(double ul_corner_x, double ul_corner_y, double lr_corner_x, double lr_corner_y) : theUlCorner(ul_corner_x, ul_corner_y), theLlCorner(ul_corner_x, lr_corner_y), theLrCorner(lr_corner_x, lr_corner_y), theUrCorner(lr_corner_x, ul_corner_y) {} ossimVrect(const ossimVrect& rect) : theUlCorner(rect.ul()), theLlCorner(rect.ll()), theLrCorner(rect.lr()), theUrCorner(rect.ur()) {} ~ossimVrect(); const ossimVrect& operator= (const ossimVrect& rect); bool operator!= (const ossimVrect& rect) const; bool operator== (const ossimVrect& rect) const; const ossimDpt &ul() const { return theUlCorner; } const ossimDpt &ur() const { return theUrCorner; } const ossimDpt &lr() const { return theLrCorner; } const ossimDpt &ll() const { return theLlCorner; } /*! * Returns the height of a rectangle. */ ossim_float64 height() const { return fabs(theLlCorner.y - theUlCorner.y) + 1.0; } /*! * Returns the width of a rectangle. */ ossim_float64 width() const { return fabs(theLrCorner.x - theLlCorner.x) + 1.0; } inline ossimDpt midPoint()const; void print(std::ostream& os) const; ossimVrect combine(const ossimVrect& rect)const; inline ossimVrect clipToRect(const ossimVrect& rect)const; friend std::ostream& operator<<(std::ostream& os, const ossimVrect& rect); private: ossimDpt theUlCorner; ossimDpt theLlCorner; ossimDpt theLrCorner; ossimDpt theUrCorner; }; inline const ossimVrect& ossimVrect::operator=(const ossimVrect& rect) { if (this != &rect) { theUlCorner = rect.ul(); theUrCorner = rect.ur(); theLrCorner = rect.lr(); theLlCorner = rect.ll(); } return *this; } inline bool ossimVrect::operator!=(const ossimVrect& rect) const { return ( (theUlCorner != rect.ul()) || (theUrCorner != rect.ur()) || (theLrCorner != rect.lr()) || (theLlCorner != rect.ll()) ); } inline bool ossimVrect::operator==(const ossimVrect& rect) const { return ( (theUlCorner == rect.ul()) && (theUrCorner == rect.ur()) && (theLrCorner == rect.lr()) && (theLlCorner == rect.ll()) ); } inline ossimVrect ossimVrect::clipToRect(const ossimVrect& rect)const { ossim_float64 ulx, uly, lrx, lry; // XXX not replaced with std::max or ossim::max since the test is backward // here and will give a different answer in the case of nan. #define d_MAX(a,b) (((a)>(b)) ? a : b) ulx = d_MAX(rect.ul().x,ul().x); uly = d_MAX(rect.ul().y,ul().y); #undef d_MAX lrx = std::min(rect.lr().x,lr().x); lry = std::min(rect.lr().y,lr().y); if( lrx <= ulx || lry <= uly ) return ossimVrect(ossimDpt(0,0),ossimDpt(0,0)); else return ossimVrect(ulx,uly,lrx,lry); } inline ossimDpt ossimVrect::midPoint()const { return ossimDpt( (ul().x + ur().x + ll().x + lr().x)*.25, (ul().y + ur().y + ll().y + lr().y)*.25); } inline ossimVrect ossimVrect::combine(const ossimVrect& rect)const { ossimDpt ulCombine; ossimDpt lrCombine; ulCombine.x = ((ul().x <= rect.ul().x)?ul().x:rect.ul().x); ulCombine.y = ((ul().y >= rect.ul().y)?ul().y:rect.ul().y); lrCombine.x = ((lr().x >= rect.lr().x)?lr().x:rect.lr().x); lrCombine.y = ((lr().y <= rect.lr().y)?lr().y:rect.lr().y); return ossimVrect(ulCombine, lrCombine); } #endif ossim-Miami-2.9.1/include/ossim/base/ossimWLSBundleSolution.h000066400000000000000000000025151352751253100241650ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // test // // Description: Weighted least squares bundle adjustment solution. //---------------------------------------------------------------------------- #ifndef ossimWLSBundleSolution_HEADER #define ossimWLSBundleSolution_HEADER #include #include #include #include class ossimAdjSolutionAttributes; class OSSIM_DLL ossimWLSBundleSolution { public: /** * @brief Constructor */ ossimWLSBundleSolution(); /** * @brief Run solution */ bool run(ossimAdjSolutionAttributes* solAttributes); /** * @brief Destructor */ ~ossimWLSBundleSolution(); protected: bool theSolValid; // Internal solution methods bool solveSystem(double* d, double* c, double* delta, int jb); bool recurFwd(double* d, double* c, std::vector& rc, std::vector& nz, int jb); bool recurBack(double* d, int jb); void trimv(double* pc, double* h, int pcIndex, int hIndex, int mr, std::vector& sum); void moveAndNegate(std::vector& from, double* to, int indexFrom, int indexTo, int nElements); }; #endif // #ifndef ossimWLSBundleSolution_HEADER ossim-Miami-2.9.1/include/ossim/base/ossimWebRequest.h000066400000000000000000000014251352751253100227160ustar00rootroot00000000000000#ifndef ossimWebRequest_HEADER #define ossimWebRequest_HEADER #include #include #include #include class OSSIM_DLL ossimWebRequest : public ossimObject { public: ossimWebRequest(){} ossimWebRequest(const ossimUrl& url) :m_url(url) {} const ossimUrl& getUrl()const{return m_url;} virtual bool setUrl(const ossimUrl& url){m_url = url; return true;} void clearLastError(){m_lastError = "";} void clearLastError()const{m_lastError = "";} const ossimString getLastError(){return m_lastError;} virtual ossimRefPtr getResponse(){return 0;} protected: ossimUrl m_url; mutable ossimString m_lastError; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimWebRequestFactoryBase.h000066400000000000000000000011211352751253100250320ustar00rootroot00000000000000#ifndef ossimWebRequestFactoryBase_HEADER #define ossimWebRequestFactoryBase_HEADER #include #include #include /** * We will for now hard code to be ossimHttpRequest but later * we will refactor and add a base ossimWebRequest so we can handle * other schema definitions such as ftp, scp, smtp, ... etc. */ class OSSIM_DLL ossimWebRequestFactoryBase : public ossimBaseObjectFactory { public: virtual ossimWebRequest* create(const ossimUrl& /*url*/) { return 0; } }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimWebRequestFactoryRegistry.h000066400000000000000000000031131352751253100257730ustar00rootroot00000000000000#ifndef ossimWebFactoryRegistry_HEADER #define ossimWebFactoryRegistry_HEADER #include #include #include /** * This will later be changed fro ossimHttpRequest to ossimWebRequest so we have * a base class for general schema access such as ftp, sftp,smtp, ... etc and not * just restricted to http and https schema definitions. */ class OSSIM_DLL ossimWebRequestFactoryRegistry : public ossimWebRequestFactoryBase, public ossimFactoryListInterface { public: static ossimWebRequestFactoryRegistry* instance(); virtual ossimWebRequest* create(const ossimUrl& url); virtual ossimHttpRequest* createHttp(const ossimUrl& url); /*! * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const { return createObjectFromRegistry(typeName); } /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const { getAllTypeNamesFromRegistry(typeList); } protected: ossimWebRequestFactoryRegistry(); static ossimWebRequestFactoryRegistry* m_instance; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimWebResponse.h000066400000000000000000000014271352751253100230660ustar00rootroot00000000000000#ifndef ossimWebResponse_HEADER #define ossimWebResponse_HEADER #include #include #include class OSSIM_DLL ossimWebResponse : public ossimObject { public: typedef std::vector ByteBuffer; ossimWebResponse():ossimObject(){} /** * This might have to change in the future if we start doing other protocols * such as ftp scp, ... etc. * * We currently will return the main input stream that can be used to read the * bytes returned from the request. If you need access to say a header stream * from an http protocol then you can dynamic_cast to an ossimHttpResponse. */ virtual std::istream* getInputStream()=0; void copyAllDataFromInputStream(ByteBuffer& buffer); TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimWgs72Datum.h000066400000000000000000000016001352751253100225270ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // Wgs72Datum. Special hardcoded datum. It will create a static // instance of a Wgs72Ellipsoid and set the initial defaults for // that are specific to a Wgs72Datum //******************************************************************* // $ID$ #ifndef ossimWgs72Datum_HEADER #define ossimWgs72Datum_HEADER #include class OSSIMDLLEXPORT ossimWgs72Datum : public ossimThreeParamDatum { public: ossimWgs72Datum(); virtual ~ossimWgs72Datum(){} virtual ossimGpt shift(const ossimGpt &aPt)const; virtual ossimGpt shiftToWgs84(const ossimGpt &aPt)const; virtual ossimGpt shiftFromWgs84(const ossimGpt &aPt)const; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimWgs84Datum.h000066400000000000000000000017161352751253100225420ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // ossimWgs84Datum. Special hardcoded datum. It will create a static // instance of a Wgs84Ellipsoid and set the initial defaults for // that are specific to a ossimWgs84Datum //******************************************************************* // $Id: ossimWgs84Datum.h 19795 2011-06-30 15:04:48Z gpotts $ #ifndef ossimWgs84Datum_HEADER #define ossimWgs84Datum_HEADER #include class OSSIMDLLEXPORT ossimWgs84Datum : public ossimThreeParamDatum { public: ossimWgs84Datum(); virtual ~ossimWgs84Datum(){} virtual ossimGpt shift(const ossimGpt &aPt)const; virtual ossimGpt shiftToWgs84(const ossimGpt &aPt)const; virtual ossimGpt shiftFromWgs84(const ossimGpt&aPt)const; protected: TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimWms.h000066400000000000000000000255171352751253100214060ustar00rootroot00000000000000// $Id$ #ifndef ossimWms_HEADER #define ossimWms_HEADER #include #include #include class ossimWmsStyle; class ossimWmsLayer; typedef std::vector ossimWmsStringListType; typedef std::vector > ossimWmsStyleListType; typedef const std::vector > ossimConstWmsStyleListType; typedef std::vector > ossimWmsLayerListType; typedef const std::vector > ossimConstWmsLayerListType; class OSSIM_DLL ossimWmsGetMap : public ossimReferenced { public: ossimWmsGetMap() { clearFields(); } virtual bool read(ossimRefPtr node); ossimWmsStringListType& getFormatTypes() { return theFormatTypes; } const ossimWmsStringListType& getFormatTypes()const { return theFormatTypes; } bool hasFormats()const { return theFormatTypes.size() > 0; } /** * Will do an exact compare on the input format. You can also specify if you want case sensitive * compares */ bool hasFormat(const ossimString& format, bool caseSensitive=true)const; /** * Will not do an exact compare but instead will test if the passed in string is contained within * the formats. You can also specify case sensitive. */ bool containsFormat(const ossimString& format, bool caseSensitive=true)const; void clearFields() { theUrl = ""; thePostUrl = ""; theFormatTypes.clear(); } const ossimString& getUrl()const { return theUrl; } const ossimString& getPostUrl()const { return thePostUrl; } protected: ossimString theUrl; ossimString thePostUrl; ossimWmsStringListType theFormatTypes; }; class OSSIM_DLL ossimWmsGetCapabilities : public ossimReferenced { public: ossimWmsGetCapabilities() { } virtual bool read(ossimRefPtr node); const ossimString& getUrl()const { return theUrl; } protected: ossimString theUrl; }; class OSSIM_DLL ossimWmsRequest : public ossimReferenced { public: ossimWmsRequest() { } virtual bool read(ossimRefPtr node); ossimRefPtr getCapabilities() { return theGetCapabilities; } const ossimRefPtr getCapabilities()const { return theGetCapabilities; } ossimRefPtr getMap() { return theGetMap; } const ossimRefPtr getMap()const { return theGetMap; } protected: ossimRefPtr theGetCapabilities; ossimRefPtr theGetMap; }; class OSSIM_DLL ossimWmsContactAdress : public ossimReferenced { public: ossimWmsContactAdress() {} protected: ossimString theAddressType; ossimString theAddress; ossimString theCity; ossimString theStateOrProvince; ossimString thePostCode; ossimString theCountry; }; class OSSIM_DLL ossimWmsContactInformation : public ossimReferenced { public: virtual bool read(ossimRefPtr /* node */ ) { return true; } protected: ossimString thePrimaryContactPerson; ossimString thePrimaryContactOrganization; ossimString theContactPosition; ossimRefPtr theContactAddress; ossimString theContactVoiceTelephone; ossimString theContactEmailAddress; }; class OSSIM_DLL ossimWmsService : public ossimReferenced { public: ossimWmsService() { } virtual bool read(ossimRefPtr /* xml */ ) { return true; } protected: ossimString theName; ossimString theTitle; ossimString theAbstract; std::vector theKeywordList; ossimString theOnlineResource; ossimRefPtr theContactInformation; ossimString theFees; ossimString theAccessConstraints; }; class OSSIM_DLL ossimWmsTimeExtent : public ossimReferenced { public: ossimWmsTimeExtent() { } virtual bool read(ossimRefPtr node); void clearFields() { theDefaultValue = ""; theTimes.clear(); } protected: ossimString theDefaultValue; std::vector theTimes; }; class OSSIM_DLL ossimWmsMetadataUrl : public ossimReferenced { public: ossimWmsMetadataUrl() { } protected: ossimString theFormat; ossimString theOnlineResourceHref; }; class OSSIM_DLL ossimWmsDataUrl : public ossimReferenced { public: protected: ossimString theFormat; ossimString theOnlineResourceHref; }; class OSSIM_DLL ossimWmsStyle : public ossimReferenced { public: ossimWmsStyle() {} virtual bool read(ossimRefPtr node); void clearFields() { theName = ""; theTitle = ""; theAbstract = ""; } const ossimString& getName()const { return theName; } const ossimString& getTitle()const { return theTitle; } const ossimString& getAbstract()const { return theAbstract; } protected: ossimString theName; ossimString theTitle; ossimString theAbstract; }; class OSSIM_DLL ossimWmsScaleHint : public ossimReferenced { public: virtual bool read(ossimRefPtr node); void clearFields() { theMin = 0.0; theMax = 0.0; } void getMinMax(double& min, double& max) { min = theMin; max = theMax; } double getMin()const { return theMin; } double getMax()const { return theMax; } protected: double theMin; double theMax; }; class OSSIM_DLL ossimWmsBoundingBox : public ossimReferenced { public: ossimWmsBoundingBox() { } virtual bool read(ossimRefPtr node); void clearFields() { theSrs = ""; theMinX = 0.0; theMinY = 0.0; theMaxX = 0.0; theMaxY = 0.0; } bool isGeographic()const { return theSrs.contains("4326"); } const ossimString& getSrs()const { return theSrs; } double getMinX()const { return theMinX; } double getMinY()const { return theMinY; } double getMaxX()const { return theMaxX; } double getMaxY()const { return theMaxY; } protected: ossimString theSrs; double theMinX; double theMinY; double theMaxX; double theMaxY; }; class OSSIM_DLL ossimWmsLayer : public ossimReferenced { public: ossimWmsLayer() :theParent(0) { clearFields(); } virtual bool read(ossimRefPtr node); void clearFields() { theName = ""; theTitle = ""; theAbstract = ""; theSrs = ""; theTimeExtent = 0; theDimensionUnits = ""; theDimensionName = ""; theBoundingBox = 0; theScaleHint = 0; theStyles.clear(); theLayers.clear(); } const ossimWmsLayer* getParent()const { return theParent; } ossimWmsLayer* getParent() { return theParent; } void setParent(ossimWmsLayer* parent) { theParent = parent; } const ossimRefPtr findBoundingBox()const { const ossimWmsLayer* currentLayer = this; while(currentLayer) { if(currentLayer->theBoundingBox.valid()) { return currentLayer->theBoundingBox; } currentLayer = currentLayer->theParent; } return 0; } void getNamedLayers(ossimWmsLayerListType& namedLayers); const ossimString& getName()const { return theName; } const ossimString& getTitle()const { return theTitle; } const ossimString& getAbstract()const { return theAbstract; } const ossimString& getSrs()const { return theSrs; } const ossimRefPtr getTimeExtent() { return theTimeExtent; } const ossimString& getDimensionUnits()const { return theDimensionUnits; } const ossimString& getDimensionName()const { return theDimensionName; } const ossimRefPtr getBoundingBox()const { return theBoundingBox; } const ossimRefPtr getScaleHint()const { return theScaleHint; } const ossimWmsStyleListType& getStyles()const { return theStyles; } ossimWmsStyleListType& getStyles() { return theStyles; } const ossimWmsLayerListType& getLayers()const { return theLayers; } ossimWmsLayerListType& getLayers() { return theLayers; } ossim_uint32 getNumberOfChildren()const { return (ossim_uint32)theLayers.size(); } ossim_uint32 getNumberOfStyles()const { return (ossim_uint32)theStyles.size(); } protected: ossimWmsLayer* theParent; ossimString theName; ossimString theTitle; ossimString theAbstract; ossimString theSrs; ossimRefPtr theTimeExtent; ossimString theDimensionUnits; ossimString theDimensionName; ossimRefPtr theBoundingBox; ossimRefPtr theScaleHint; ossimWmsStyleListType theStyles; ossimWmsLayerListType theLayers; }; class OSSIM_DLL ossimWmsCapability : public ossimReferenced { public: virtual bool read(const ossimRefPtr node); void getNamedLayers(ossimWmsLayerListType& layers); ossimRefPtr getRequest() { return theRequest; } const ossimRefPtr getRequest()const { return theRequest; } protected: ossimRefPtr theRequest; std::vector > theLayers; }; class OSSIM_DLL ossimWmsCapabilitiesDocument : public ossimReferenced { public: ossimWmsCapabilitiesDocument() { } bool read(const std::string& inString); virtual bool read(ossimRefPtr node); void clearFields() { theVersion = ""; theCapability=0; } ossimRefPtr getCapability() { return theCapability; } const ossimRefPtr getCapability()const { return theCapability; } ossimRefPtr getRequestGetMap(); const ossimRefPtr getRequestGetMap()const; ossimRefPtr getRequestGetCapabilities(); const ossimRefPtr getRequestGetCapabilities()const; protected: ossimString theVersion; ossimRefPtr theCapability; }; #endif ossim-Miami-2.9.1/include/ossim/base/ossimXmlAttribute.h000066400000000000000000000033331352751253100232540ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2001 ImageLinks Inc. All rights reserved. // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer (ossim port by D. Burken) // // Description: // // Contains declaration of class ossimAttribute. // //***************************************************************************** // $Id: ossimXmlAttribute.h 12521 2008-02-28 20:09:25Z gpotts $ #ifndef ossimXmlAttribute_HEADER #define ossimXmlAttribute_HEADER #include #include #include class OSSIMDLLEXPORT ossimXmlAttribute : public ossimObject, public ossimErrorStatusInterface { public: ossimXmlAttribute(ossimString& spec); // attribute removed from spec string ossimXmlAttribute(); ossimXmlAttribute(const ossimXmlAttribute& src); ossimXmlAttribute(const ossimString& name, const ossimString& value); virtual ossimObject* dup() const { return new ossimXmlAttribute(*this); } ~ossimXmlAttribute(); bool read(std::istream& in); const ossimString& getName() const; const ossimString& getValue() const; void setNameValue(const ossimString& name, const ossimString& value); void setName(const ossimString& name); void setValue(const ossimString& value); OSSIMDLLEXPORT friend std::ostream& operator<<( std::ostream& os, const ossimXmlAttribute* xml_attr); protected: ossimString theName; ossimString theValue; bool readName(std::istream& in); bool readValue(std::istream& in); TYPE_DATA }; #endif /* #ifndef ossimXmlAttribute_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimXmlDocument.h000066400000000000000000000042331352751253100230670ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer (ossim port by D. Burken) // // Description: // // Contains declaration of class ossimXmlDocument. This class provides read-only // parsing and accessing of an XML document file. // //***************************************************************************** // $Id: ossimXmlDocument.h 21579 2012-08-31 14:24:11Z dburken $ #ifndef ossimXmlDocument_HEADER #define ossimXmlDocument_HEADER 1 #include #include #include #include #include #include class OSSIMDLLEXPORT ossimXmlDocument : public ossimObject, public ossimErrorStatusInterface { public: ossimXmlDocument(const ossimFilename& xmlFileName=""); ossimXmlDocument(const ossimXmlDocument& src); virtual ossimObject* dup()const { return new ossimXmlDocument(*this); } virtual ~ossimXmlDocument(); bool write(const ossimFilename& file); bool openFile(const ossimFilename &filename); bool readString(const ossimString& xmlString); bool read(std::istream &in); /** * Appends any matching nodes to the list supplied (should be empty): */ void findNodes(const ossimString& xpath, std::vector >& nodelist) const; OSSIMDLLEXPORT friend std::ostream& operator << (std::ostream& os, const ossimXmlDocument& xml_doc); void initRoot(ossimRefPtr node); ossimRefPtr getRoot(); const ossimRefPtr getRoot()const; ossimRefPtr removeRoot(); void fromKwl(const ossimKeywordlist& kwl); void toKwl(ossimKeywordlist& kwl, const ossimString& prefix = "")const; private: ossimRefPtr theRootNode; ossimString theXmlHeader; ossimFilename theFilename; bool theStrictCheckFlag; bool readHeader(std::istream& in); TYPE_DATA }; #endif /* #ifndef ossimXmlDocument_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimXmlNode.h000066400000000000000000000123261352751253100222000ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer (ossim port by D. Burken) // // Description: // // Contains declaration of class ossimXmlNode. // //***************************************************************************** // $Id: ossimXmlNode.h 12527 2008-03-04 17:02:55Z gpotts $ #ifndef ossimXmlNode_HEADER #define ossimXmlNode_HEADER #include #include #include #include #include #include class OSSIMDLLEXPORT ossimXmlNode : public ossimObject, public ossimErrorStatusInterface { public: typedef std::vector > ChildListType; typedef std::vector > AttributeListType; ossimXmlNode(std::istream& xml_stream, ossimXmlNode* parent=0); ossimXmlNode(); ossimXmlNode(const ossimXmlNode& src); virtual ossimObject* dup() const { return new ossimXmlNode(*this); } void duplicateAttributes(ossimXmlNode::AttributeListType result)const; void duplicateChildren(ossimXmlNode::ChildListType& result)const; bool read(std::istream& in); // Appends any matching nodes to the list supplied void findChildNodes(const ossimString& rel_xpath, ossimXmlNode::ChildListType& nodelist)const; // Prefer this version when possible const ossimRefPtr & findFirstNode(const ossimString& rel_xpath)const; ossimRefPtr findFirstNode(const ossimString& rel_xpath); ossimRefPtr findAttribute(const ossimString& name); const ossimRefPtr findAttribute(const ossimString& name)const; void setTag(const ossimString& tag); ossimString const& getTag() const { return theTag; } const ossimXmlNode* getParentNode() const; ossimXmlNode* getParentNode(); void setParent(ossimXmlNode* parent); const ossimXmlNode::ChildListType& getChildNodes() const; ossimXmlNode::ChildListType& getChildNodes(); const ossimXmlNode::AttributeListType& getAttributes() const; bool getAttributeValue(ossimString& value, const ossimString& name)const; ossimString getAttributeValue(const ossimString& name)const { ossimString value; getAttributeValue(value, name); return value; } bool getChildTextValue(ossimString& value, const ossimString& relPath)const; ossimString getChildTextValue(const ossimString& relPath)const { ossimString value; getChildTextValue(value, relPath); return value; } void addAttribute(ossimRefPtr attribute); void addAttribute(const ossimString& name, const ossimString& value); bool setAttribute(const ossimString& name, const ossimString& value, bool addIfNotPresentFlag=false); ossimRefPtr addNode(const ossimString& relPath, const ossimString& text = ""); ossimRefPtr addOrSetNode(const ossimString& relPath, const ossimString& text = ""); void addChildNode(ossimRefPtr node); ossimRefPtr addChildNode(const ossimString& tagName, const ossimString& text=""); void addChildren(ossimXmlNode::ChildListType& children); void setChildren(ossimXmlNode::ChildListType& children); void addAttributes(ossimXmlNode::AttributeListType& children); void setAttributes(ossimXmlNode::AttributeListType& children); void setText(const ossimString& text); const ossimString& getText() const { return theText; } bool cdataFlag()const; void setCDataFlag(bool value); OSSIMDLLEXPORT friend std::ostream& operator << (std::ostream& os, const ossimXmlNode* xml_node); OSSIMDLLEXPORT friend std::ostream& operator << (std::ostream& os, const ossimXmlNode& xml_node); ossimRefPtr removeChild(ossimRefPtr node); ossimRefPtr removeChild(const ossimString& tag); void clear(); void clearChildren(); void clearAttributes(); void toKwl(ossimKeywordlist& kwl, const ossimString& prefix="", bool includeTag=true)const; void fromKwl(const ossimKeywordlist& kwlToConvert); protected: ~ossimXmlNode(); bool readTag(std::istream& in, ossimString& tag); bool readTextContent(std::istream& in); bool readEndTag(std::istream& in, ossimString& endTag); void skipCommentTag(std::istream& in); bool readCDataContent(std::istream& in); ossimString theTag; ossimXmlNode* theParentNode; std::vector > theChildNodes; std::vector > theAttributes; ossimString theText; bool theCDataFlag; /* ossimString theCData; */ TYPE_DATA }; #endif /* #ifndef ossimXmlNode_HEADER */ ossim-Miami-2.9.1/include/ossim/base/ossimXmlString.h000066400000000000000000000031721352751253100225600ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: This class provides manipulation of filenames. // //************************************************************************* // $Id: ossimXmlString.h 22326 2013-07-25 17:13:55Z gpotts $ #ifndef ossimXmlString_HEADER #define ossimXmlString_HEADER #include #include class OSSIM_DLL ossimXmlString : public ossimString { public: ossimXmlString() : ossimString() {} ossimXmlString(const ossimXmlString& src) : ossimString(src) {} ossimXmlString(const ossimString& src) : ossimString("") { assign(src); } ossimXmlString(const char* src) : ossimString("") { assign(src); } template ossimXmlString(Iter s, Iter e) :ossimString("") { assign(ossimString(s, e)); } const ossimXmlString& operator =(const char* s) { return assign(ossimString(s)); } const ossimXmlString& operator =(const ossimString& s) { return assign(ossimString(s)); } const ossimXmlString& operator =(const std::string& s) { return assign(ossimString(s)); } static ossimString wrapCDataIfNeeded(const ossimString& input); static ossimString wrapCData(const ossimString& input); static bool containsSpecialXmlCharacters(const ossimString& value); const ossimXmlString& assign(const ossimString& s); }; #endif ossim-Miami-2.9.1/include/ossim/elevation/000077500000000000000000000000001352751253100204565ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/elevation/ossimDtedElevationDatabase.h000066400000000000000000000062561352751253100260670ustar00rootroot00000000000000#ifndef ossimDtedElevationDatabase_HEADER #define ossimDtedElevationDatabase_HEADER 1 #include #include #include #include /** * The DTED elevation data base is also an elevation source but allows * one to point to an file based elevation tree. The general format of * a DTED elevation tree: * * /e|w/n|s. * Exmaple 1 kilometer: * /w023/n15.dt0 * * Note for 1 kilimeter the extension is dt0 and for 90 meter post spacing * it is .dt1 and for 30 meter spacing it is .dt2 * */ class OSSIM_DLL ossimDtedElevationDatabase : public ossimElevationCellDatabase { public: typedef std::vector > DirectMap; // 360x180 cell grid ossimDtedElevationDatabase(); ossimDtedElevationDatabase(const ossimDtedElevationDatabase& rhs); virtual ~ossimDtedElevationDatabase(); virtual ossimObject* dup() const; virtual bool open(const ossimString& connectionString); virtual bool pointHasCoverage(const ossimGpt& gpt) const { ossimFilename filename; createFullPath(filename, gpt); return filename.exists(); } virtual bool getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& gpt) const; virtual double getHeightAboveMSL(const ossimGpt&); virtual double getHeightAboveEllipsoid(const ossimGpt& gpt); virtual ossim_uint64 createId(const ossimGpt& pt)const { ossim_uint64 y = static_cast(ossim::wrap(pt.latd(), -90.0, 90.0)+90.0); ossim_uint64 x = static_cast(ossim::wrap(pt.lond(),-180.0,180.0)+180.0); // map the extreme edge to the same ID ax the 179 west cell and the same for the 89 // degree north cell. // x = x==360?359:x; y = y==180?179:y; // dted databases are 1x1 degree cells and we will use a world // grid for id generation. // return (y*360+x); } virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; virtual std::ostream& print(std::ostream& out) const; protected: bool openDtedDirectory(const ossimFilename& dir); void createRelativePath(ossimFilename& file, const ossimGpt& gpt)const; void createFullPath(ossimFilename& file, const ossimGpt& gpt)const { ossimFilename relativeFile; createRelativePath(relativeFile, gpt); file = ossimFilename(m_connectionString).dirCat(relativeFile); } virtual ossimRefPtr createCell(const ossimGpt& gpt); /** * @brief Scans directory and set m_extension to extension of first dted * file found. * @param dir Directory to scan. * @return true on success, false on error. */ bool inititializeExtension( const ossimFilename& dir ); // DTED extension. E.g. ".dt2", ".dt1", ".dt0" ossimString m_extension; // Upcase or not when scanning for file. E.g. E045/N34.DT2 or e045/n34.dt2 bool m_upcase; ossimRefPtr m_lastHandler; mutable std::mutex m_mutex; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimDtedFactory.h000066400000000000000000000020001352751253100241020ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimDtedFactory.cc // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration for ossimDtedFactory. // This is the base class interface for elevation cell factories. //***************************************************************************** // $Id: ossimDtedFactory.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimDtedFactory_HEADER #define ossimDtedFactory_HEADER #include /** CLASS: ossimDtedFactory */ class OSSIM_DLL ossimDtedFactory : public ossimElevSourceFactory { public: ossimDtedFactory(); ossimDtedFactory(const ossimFilename& dir); virtual ossimElevSource* getNewElevSource(const ossimGpt& gpt) const; virtual void createIndex(); protected: virtual ~ossimDtedFactory(); TYPE_DATA }; #endif /* End of "#ifndef ossimDtedFactory_HEADER" */ ossim-Miami-2.9.1/include/ossim/elevation/ossimDtedHandler.h000066400000000000000000000205011352751253100240560ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimDtedHandler.h // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of class ossimDtedHandler. This class derives from // ossimElevHandler. It is responsible for loading an individual DTED cell // from disk. This elevation files are memory mapped. // // SOFTWARE HISTORY: //> // 05Feb2001 Ken Melero // Initial coding of ossimDted.h // 19Apr2001 Oscar Kramer // Derived from ossimElevCellHandler. //< //***************************************************************************** // $Id: ossimDtedHandler.h 23497 2015-08-28 15:28:59Z okramer $ #ifndef ossimDtedHandler_HEADER #define ossimDtedHandler_HEADER #include #include #include #include #include #include #include #include #include #include #include /** * the DTED handler is an elevation source that allows for handling of a * single cell of data. DTED is typically a 1x1 degree cell. * * This can open from an ossim::istream or from a filename. It allows * one to query the cell by overriding the getHeightAboveMSL. * * For reference @see ossimGpt * Example: * @code * ossimRefPtr h = new ossimDtedHandler(); * if(h->open(someFile)) * { * h->getHeightAboveMSL(ossimGpt(28, -110)); * } * @endcode * * When a height is calculated it will use a weighted average of 4 neighboring * posts. */ class OSSIM_DLL ossimDtedHandler : public ossimElevCellHandler { public: // number of Dted posts per point. static const int TOTAL_POSTS = 4; // number of Dted posts per block static const int NUM_POSTS_PER_BLOCK= 2; /** * Constructor */ ossimDtedHandler() { } /** * Constructor * * @param dted_file is a file path to the dted cell we wish to * open * @param memoryMapFlag If this is set we will pull the entire cell * into memory and treat that memory location as an * inputstream. */ ossimDtedHandler(const ossimFilename& dted_file, bool memoryMapFlag=false); enum { DATA_RECORD_OFFSET_TO_POST = 8, // bytes DATA_RECORD_CHECKSUM_SIZE = 4, // bytes POST_SIZE = 2, // bytes NULL_POST = -32767 // Fixed by DTED specification. }; /** * opens a cell * * @param file is a file path to the dted cell we wish to * open * @param memoryMapFlag If this is set we will pull the entire cell * into memory and treat that memory location as an * inputstream. */ virtual bool open(const ossimFilename& file, bool memoryMapFlag=false); /** * opens a cell given a stream * * @param fileStr is a stream that was opened and has access * to a cell. * @param connectionString is the connection string used to open the * input stream. * @param memoryMapFlag If this is set we will pull the entire cell * into memory and treat that memory location as an * inputstream. */ virtual bool open(std::shared_ptr& fileStr, const std::string& connectionString, bool memoryMapFlag=false); virtual void close(); /** * @param gpt is a ground point that is used to * lookup the elevation pos value. * @return height above Mean Sea Level (MSL). */ virtual double getHeightAboveMSL(const ossimGpt& gpt); /*! * METHOD: getSizeOfElevCell * Returns the number of post in the cell. Satisfies pure virtual. * Note: x = longitude, y = latitude */ virtual ossimIpt getSizeOfElevCell() const; /*! * METHOD: getPostValue * Returns the value at a given grid point as a double. * Satisfies pure virtual. */ virtual double getPostValue(const ossimIpt& gridPt) const; ossimString edition() const; ossimString productLevel() const; ossimString compilationDate() const; virtual bool isOpen()const; virtual bool getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& gpt) const; const ossimDtedVol& vol()const { return *m_vol; } const ossimDtedHdr& hdr()const { return *m_hdr; } const ossimDtedUhl& uhl()const { return *m_uhl; } const ossimDtedDsi& dsi()const { return *m_dsi; } const ossimDtedAcc& acc()const { return *m_acc; } virtual ossimObject* dup () const { return new ossimDtedHandler(this->getFilename(), (m_memoryMap.size() != 0)); } virtual ~ossimDtedHandler(); protected: /// DtedPost, this class contains the height, weighting factor and status class DtedPost { public: // constructor - initialise variables DtedPost(): m_height(0), m_weight(0), m_status(false) { } // destructor virtual ~DtedPost(); // member variables double m_height; double m_weight; bool m_status; }; /// DtedHeight is a class for storing DTED information /// - 4 posts are used to generate an interpolated height value. class DtedHeight { public: // constructor DtedHeight(); // destructor virtual ~DtedHeight(); // calculate the interpolated Height for the posts double calcHeight(); // debug void debug(); // post data DtedPost m_posts[TOTAL_POSTS]; }; // Disallow operator= and copy construction... const ossimDtedHandler& operator=(const ossimDtedHandler& rhs); ossimDtedHandler(const ossimDtedHandler&); /*! * If statistics file exist, stats will be initialized from that; else, * this scans the dted cell and gets stats, then, writes new stats file. * The statistics file will be named accordingly: * If dted cell = n27.dt1 then the stats file = n27.statistics. * Currently method only grabs the min and max posts value. */ void gatherStatistics(); ossim_sint16 convertSignedMagnitude(ossim_uint16& s) const; virtual double getHeightAboveMSL(const ossimGpt&, bool readFromFile); /** * read the height posts from the File * @param postData - post heights, status & weight * @param offset - file contents offset to start reading from */ void readPostsFromFile(DtedHeight &postData, int offset); mutable std::mutex m_fileStrMutex; // mutable std::ifstream m_fileStr; mutable std::shared_ptr m_fileStr; mutable std::string m_connectionString; ossim_int32 m_numLonLines; // east-west dir ossim_int32 m_numLatPoints; // north-south ossim_int32 m_dtedRecordSizeInBytes; ossimString m_edition; ossimString m_productLevel; ossimString m_compilationDate; ossim_int32 m_offsetToFirstDataRecord; double m_latSpacing; // degrees double m_lonSpacing; // degrees ossimDpt m_swCornerPost; // cell origin; // Indicates whether byte swapping is needed. bool m_swapBytesFlag; mutable std::mutex m_memoryMapMutex; mutable std::vector m_memoryMap; std::shared_ptr m_vol; std::shared_ptr m_hdr; std::shared_ptr m_uhl; std::shared_ptr m_dsi; std::shared_ptr m_acc; TYPE_DATA }; inline ossim_sint16 ossimDtedHandler::convertSignedMagnitude(ossim_uint16& s) const { // DATA_VALUE_MASK 0x7fff = 0111 1111 1111 1111 // DATA_SIGN_MASK 0x8000 = 1000 0000 0000 0000 // First check to see if the bytes need swapped. s = (m_swapBytesFlag ? ( ((s & 0x00ff) << 8) | ((s & 0xff00) >> 8) ) : s); // If the sign bit is set, mask it out then multiply by negative one. if (s & 0x8000) { return (static_cast(s & 0x7fff) * -1); } return static_cast(s); } inline bool ossimDtedHandler::isOpen()const { if(!m_memoryMap.empty()) return true; std::lock_guard lock(m_fileStrMutex); return (m_fileStr != 0); } inline void ossimDtedHandler::close() { m_fileStr.reset(); m_memoryMap.clear(); } #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimElevCellHandler.h000066400000000000000000000060501352751253100246740ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimElevCellHandler.h // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of class osimElevHandler. This class provides a // base-class interface for the various DEM file formats. // // SOFTWARE HISTORY: //> // 13Apr2001 Oscar Kramer // Initial coding. //< //***************************************************************************** // $Id: ossimElevCellHandler.h 23117 2015-01-29 22:33:13Z okramer $ #ifndef ossimElevCellHandler_HEADER #define ossimElevCellHandler_HEADER #include #include #include #include class ossimGpt; /****************************************************************************** * * CLASS: ossimElevCellHandler * *****************************************************************************/ class OSSIM_DLL ossimElevCellHandler : public ossimElevSource { public: /** * Constructors: */ ossimElevCellHandler (const char* elev_filename); ossimElevCellHandler (const ossimElevCellHandler& src); virtual const ossimFilename& getFilename() const; /** * METHOD: getSizeOfElevCell * Returns the number of post in the cell. * Note: x = longitude, y = latitude */ virtual ossimIpt getSizeOfElevCell() const = 0; /** * METHOD: getPostValue * Returns the value at a given grid point as a double. */ virtual double getPostValue(const ossimIpt& gridPt) const = 0; /** * METHOD: meanSpacingMeters() * Implements pure virtual for. This method is used for deterrming * preferred DEM among multiple overlapping elev sources: */ virtual double getMeanSpacingMeters() const; /** * METHOD: pointIsInsideRect() * Method to check if the ground point elevation is defined: */ virtual bool pointHasCoverage(const ossimGpt&) const; virtual bool getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& gpt) const; /** * METHODS: accuracyLE90(), accuracyCE90() * Returns the vertical and horizontal accuracy (90% confidence): */ // virtual double getAccuracyLE90(const ossimGpt&) const; // virtual double getAccuracyCE90(const ossimGpt&) const; bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; virtual void close(){} virtual bool open(const ossimFilename&, bool=false){return false;} virtual std::ostream& print(std::ostream& out) const; protected: ossimElevCellHandler (); virtual ~ossimElevCellHandler(); /** * Virtual method for reading */ ossimFilename theFilename; double theMeanSpacing; // meters double theAbsLE90; double theAbsCE90; TYPE_DATA }; inline bool ossimElevCellHandler::pointHasCoverage(const ossimGpt& gpt) const { return theGroundRect.pointWithin(gpt); } #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimElevCellHandlerFactory.h000066400000000000000000000026111352751253100262230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of class ossimElevCellHandlerFactory. This factory // class instantiates the proper ossimElevCellHandler given a file name. // // SOFTWARE HISTORY: //> // 26Apr2001 Oscar Kramer (okramer@imagelinks.com) // Initial coding. //< //***************************************************************************** #ifndef ossimElevCellHandlerFactory_HEADER #define ossimElevCellHandlerFactory_HEADER #include #include class ossimElevCellHandler; class ossimGpt; /*!**************************************************************************** * * CLASS: ossimElevCellHandlerFactory * *****************************************************************************/ class ossimElevCellHandlerFactory : public ossimFactoryBase { public: static ossimElevCellHandlerFactory* instance(); virtual ossimElevCellHandler* create(const ossimString&) const; virtual ossimElevCellHandler* create(const ossimKeywordlist& kwl, const char* prefix) const; virtual std::list getList() const; protected: ossimElevCellHandlerFactory(); static ossimElevCellHandlerFactory* theInstance; }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimElevLess.h000066400000000000000000000015701352751253100234270ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Function object (functor) to for stl's sort method for sorting // a vector of ossimElevSource* by best post spacing. //***************************************************************************** // $Id: ossimElevLess.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimElevLess_HEADER #define ossimElevLess_HEADER #include #include class ossimElevLess : public std::binary_function, const ossimRefPtr, bool> { public: bool operator() (const ossimRefPtr a, const ossimRefPtr< ossimElevSource> b) const { return (a->getMeanSpacingMeters() < b->getMeanSpacingMeters()); } }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimElevManager.h000066400000000000000000000171511352751253100240750ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimElevManager.h // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of class ossimElevManager. This object provides a // single interface to an imaging chain for accessing multiple elevation // sources. This object owns one or more elevation sources in an ordered // list. When queried for an elevation at a particular point, it searches // the available sources for the best result, instantiating new sources if // necessary. // // SOFTWARE HISTORY: //> // 13Apr2001 Oscar Kramer // Initial coding. //< //***************************************************************************** #ifndef ossimElevManager_HEADER #define ossimElevManager_HEADER #include #include #include #include #include #include class OSSIM_DLL ossimElevManager : public ossimElevSource { public: typedef std::vector > ElevationDatabaseListType; class OSSIM_DLL ConnectionStringVisitor : public ossimVisitor { public: ConnectionStringVisitor(const ossimString& value); virtual ossimRefPtr dup()const{return new ConnectionStringVisitor(*this);} const ossimString& getConnectionString()const{return m_connectionString;} virtual void visit(ossimObject* obj); ossimElevationDatabase* getElevationDatabase(){return m_database.get();} protected: ossimString m_connectionString; ossimRefPtr m_database; }; virtual ~ossimElevManager(); /** * METHOD: instance() * Implements singelton pattern */ static ossimElevManager* instance(); virtual double getHeightAboveEllipsoid(const ossimGpt& gpt); virtual double getHeightAboveMSL(const ossimGpt& gpt); virtual bool pointHasCoverage(const ossimGpt&) const; /** * Returns the mean post spacing (in meters) for the highest resolution DEM in the list or NaN * if no DEMs have been loaded. Recommended to perform a getHeight() call for a central * ground pt first to load the relevant cells before calling this method. */ virtual double getMeanSpacingMeters() const; virtual bool getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& gpt) const; ossim_uint32 getNumberOfElevationDatabases()const { return (ossim_uint32) m_dbRoundRobin[0].size(); } ossimElevationDatabase* getElevationDatabase(ossim_uint32 idx) { return m_dbRoundRobin[0][idx].get(); } const ossimElevationDatabase* getElevationDatabase(ossim_uint32 idx)const { return m_dbRoundRobin[0][idx].get(); } /** * Adds a new elevation database to the collection. Normally pushed on to the tail of the list, * unless set_as_first=true, in which case this database will receive the first requests. */ void addDatabase(ossimElevationDatabase* database, bool set_as_first=false); /** * Adds a new elevation file (or multiple files if path is a directory) to the collection. * Normally pushed on to the tail of the list, unless set_as_first=true, in which case this * source will receive the first requests. */ bool loadElevationPath(const ossimFilename& path, bool set_as_first=false); void setDefaultHeightAboveEllipsoid(double meters) {m_defaultHeightAboveEllipsoid=meters;} void setElevationOffset(double meters) {m_elevationOffset=meters;} double getElevationOffset() const { return m_elevationOffset; } void getOpenCellList(std::vector& list) const; /** * @brief Gets a list of elevation cells needed to cover bounding box. * @param connectionString Typically elevation repository, e.g.: * "/data1/elevation/srtm/1arc" * @param minLat Minimum latitude of bounding box. * @param minLon Minimum longitude of bounding box. * @param maxLat Maximum latitude of bounding box. * @param maxLon Maximum longitude of bounding box. * @param cells Initialized by this. * @param maxNumberOfCells Value of 0 indicates return as many as you can. Any positive * number will only return that number of cells. */ void getCellsForBounds( const std::string& connectionString, const ossim_float64& minLat, const ossim_float64& minLon, const ossim_float64& maxLat, const ossim_float64& maxLon, std::vector& cells, ossim_uint32 maxNumberOfCells=0 ); /** * @brief Gets a list of elevation cells needed to cover bounding box. * * This implementation sorts elevation repositories by resolution, best * first, then searches cells for bounds. Search is stopped on the first * repository that has cells. * * @param minLat Minimum latitude of bounding box. * @param minLon Minimum longitude of bounding box. * @param maxLat Maximum latitude of bounding box. * @param maxLon Maximum longitude of bounding box. * @param cells Initialized by this. * @param maxNumberOfCells Value of 0 indicates return as many as you can. Any positive * number will only return that number of cells. */ void getCellsForBounds( const ossim_float64& minLat, const ossim_float64& minLon, const ossim_float64& maxLat, const ossim_float64& maxLon, std::vector& cells, ossim_uint32 maxNumberOfCells=0 ); void getCellsForBounds( const ossimGrect& bounds, std::vector& cells, ossim_uint32 maxNumberOfCells=0 ); void setUseGeoidIfNullFlag(bool flag) { m_useGeoidIfNullFlag = flag; } bool getUseGeoidIfNullFlag() const { return m_useGeoidIfNullFlag; } void setRoundRobinMaxSize(ossim_uint32 size); void clear(); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void accept(ossimVisitor& visitor); virtual std::ostream& print(std::ostream& out) const; protected: virtual ossimObject* dup() const { return 0; } // required to implement but not permitted to call ossimElevManager(); void loadStandardElevationPaths(); ElevationDatabaseListType& getNextElevDbList() const; // for multithreading //static ossimElevManager* m_instance; mutable std::vector m_dbRoundRobin; ossim_uint32 m_maxRoundRobinSize; ossim_float64 m_defaultHeightAboveEllipsoid; ossim_float64 m_elevationOffset; // if an elevation is returned that's null for ellipsoid then use the geoid manager to calculate a shift bool m_useGeoidIfNullFlag; bool m_useStandardPaths; mutable ossim_uint32 m_currentDatabaseIdx; /** * I have tried the readwrite lock interfaces but have found it unstable. I am using the standard Mutex * and it seems to be much more stable across all platforms. More testing needs to occur for the ReadWriteMutex. * For now we will use Mutex. */ mutable std::mutex m_mutex; }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimElevSource.h000066400000000000000000000124001352751253100237530ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimElevSource.h // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // // DESCRIPTION: // Contains declaration of class ossimElevSource. This is the base class for // all objects providing height information given horizontal ground position. // //***************************************************************************** // $Id: ossimElevSource.h 23117 2015-01-29 22:33:13Z okramer $ #ifndef ossimElevSource_HEADER #define ossimElevSource_HEADER #include #include #include #include #include #include class ossimEcefRay; class ossimKeywordlist; /****************************************************************************** * CLASS: ossimElevSource * *****************************************************************************/ class OSSIM_DLL ossimElevSource : public ossimSource { public: /** * Height access methods: */ virtual double getHeightAboveMSL(const ossimGpt&) = 0; virtual double getHeightAboveEllipsoid(const ossimGpt&); // Forces all concrete subtypes to implement: virtual ossimObject* dup() const = 0; /** * METHOD: intersectRay() * * Service method for intersecting a ray with the elevation surface to * arrive at a ground point. The ray is expected to originate ABOVE the * surface and pointing down. * * NOTE: the gpt argument is expected to be initialized with the desired * datum, including ellipsoid, for the proper intersection point to be * computed. * * LIMITATION: This release supports only single valued solutions, i.e., it * is possible a ray passing through one side of a mountain and out the * other will return an intersection with the far side. Eventually, * a more robust algorithm will be employed. * * Returns true if good intersection found. */ bool intersectRay(const ossimEcefRay& ray, ossimGpt& gpt, double defaultElevValue = 0.0); /** * Access methods for the bounding elevations: */ virtual double getMinHeightAboveMSL() const; virtual double getMaxHeightAboveMSL() const; /** * Special numeric quantities as defined by this source: */ double getNullHeightValue() const; double getSeaLevelValue() const; /** * METHOD: pointHasCoverage(gpt) * Returns TRUE if coverage exists over gpt: */ virtual bool pointHasCoverage(const ossimGpt&) const = 0; /** * METHOD: meanSpacingMeters() * This method returns the post spacing in the region of gpt: */ virtual double getMeanSpacingMeters() const = 0; virtual bool getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& gpt) const =0; /** * METHODS: accuracyLE90(), accuracyCE90() * Returns the vertical and horizontal accuracy (90% confidence) in the * region of gpt: */ //virtual double getAccuracyLE90(const ossimGpt& gpt) const = 0; //virtual double getAccuracyCE90(const ossimGpt& gpt) const = 0; /** * METHOD: getBoundingGndRect * * @return The bounding geograpic rectangle in decimal degrees. */ virtual const ossimGrect& getBoundingGndRect() const; virtual bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; /** * Implement ossimSource base-class pure virtuals: */ virtual void initialize(); /** * Opens a stream to an elevation cell. * * @return Returns true on success, false on error. * * @note This implementation always returns true. This should be * overridden in derived classes that have streams to files. */ // virtual bool open(); /** * Closes the stream to the file. * * @note This implementation does nothing. This should be * overridden in derived classes that have streams to files. */ // virtual void close(); /** * @return Returns the flag which controls whether or not statistics will * be computed upon opening a cell and not finding a corresponding * statistics file. */ virtual bool getComputeStatisticsFlag() const; /** * Sets the flag which controls whether or not statistics will * be computed upon opening a cell and not finding a corresponding * statistics file. * * @param flag true to enable, false to disable. * * @note This flag can also be controlled by user via the ossim preferences * keyword = "elevation.compute_statistics.enabled". */ virtual void setComputeStatisticsFlag(bool flag); virtual std::ostream& print(std::ostream& out) const; protected: virtual ~ossimElevSource(); /** * Constructors/Destructors: */ ossimElevSource(); ossimElevSource(const ossimElevSource& src); /** * Data members: */ double theMinHeightAboveMSL; double theMaxHeightAboveMSL; double theNullHeightValue; double theSeaLevelValue; ossimGrect theGroundRect; //> Controls statistics gathering. Defaulted to true. bool theComputeStatsFlag; private: TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimElevSourceFactory.h000066400000000000000000000040521352751253100253070ustar00rootroot00000000000000//---------------------------------------------------------------------------- // FILE: ossimElevSourceFactory.cc // // Copyright (C) 2002 ImageLinks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration for ossimElevSourceFactory. // // This is the base class interface for elevation source factories which main // function is to return an elevation source that covers the ground point // passed to the "getElevSource" method. // // Note the caller of "getElevSource" is responsible for managing the memory // new'd from the method. // //---------------------------------------------------------------------------- // $Id: ossimElevSourceFactory.h 13269 2008-07-25 14:27:36Z dburken $ #ifndef ossimElevSourceFactory_HEADER #define ossimElevSourceFactory_HEADER #include #include class ossimElevSource; class ossimGpt; /*!**************************************************************************** * CLASS: ossimElevSourceFactory * *****************************************************************************/ class OSSIM_DLL ossimElevSourceFactory : public ossimObject { public: /** default constructor */ ossimElevSourceFactory(); /** virtual destructor */ virtual ~ossimElevSourceFactory(); /** * Pure virtual method. * return an elevation source pointer that has elevation coverage for the * ground point passed in. * Note the caller of this method is responsible for managing the memory * allocated. */ virtual ossimElevSource* getNewElevSource(const ossimGpt& gpt)const=0; /** * @return The directory the factory returns data from. */ virtual ossimFilename getDirectory() const; /** * @param directory The directory to return data from. */ virtual void setDirectory(const ossimFilename& directory); protected: ossimFilename theDirectory; TYPE_DATA }; #endif /* End of "#ifndef ossimElevSourceFactory_HEADER" */ ossim-Miami-2.9.1/include/ossim/elevation/ossimElevationAccuracyInfo.h000066400000000000000000000034471352751253100261270ustar00rootroot00000000000000#ifndef ossimElevationAccuracyInfo_HEADER #define ossimElevationAccuracyInfo_HEADER 1 #include #include #include class OSSIM_DLL ossimElevationAccuracyInfo: public ossimReferenced { public: ossimElevationAccuracyInfo(): m_confidenceLevel(0.9), m_relativeCE(ossim::nan()), m_absoluteCE(ossim::nan()), m_relativeLE(ossim::nan()), m_absoluteLE(ossim::nan()), m_surfaceName("None") {} void makeNan() { m_relativeCE = ossim::nan(); m_absoluteCE = ossim::nan(); m_relativeLE = ossim::nan(); m_absoluteLE = ossim::nan(); } double getConfidenceLevel()const{return m_confidenceLevel;} bool hasValidRelativeError()const { return ((!ossim::isnan(m_relativeCE)) && (!ossim::isnan(m_relativeLE))); } bool hasValidAbsoluteError()const{ return ((!ossim::isnan(m_absoluteCE)) && (!ossim::isnan(m_absoluteLE))); } double getRelativeCE()const{return m_relativeCE;} void setRelativeCE(double value){m_relativeCE = value;} double getAbsoluteCE()const{return m_absoluteCE;} void setAbsoluteCE(double value){m_absoluteCE = value;} double getRelativeLE()const{return m_relativeLE;} void setRelativeLE(double value){m_relativeLE = value;} double getAbsoluteLE()const{return m_absoluteLE;} void setAbsoluteLE(double value){m_absoluteLE = value;} const ossimString& getSurfaceName()const{return m_surfaceName;} void setSurfaceName(const ossimString& value){m_surfaceName = value;} double m_confidenceLevel; double m_relativeCE; double m_absoluteCE; double m_relativeLE; double m_absoluteLE; ossimString m_surfaceName; }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimElevationCellDatabase.h000066400000000000000000000117351352751253100260640ustar00rootroot00000000000000#ifndef ossimElevationCellDatabase_HEADER #define ossimElevationCellDatabase_HEADER 1 #include #include class OSSIM_DLL ossimElevationCellDatabase : public ossimElevationDatabase { public: struct CellInfo : ossimReferenced { CellInfo(ossim_uint64 id, ossimElevCellHandler* handler = 0) :ossimReferenced(), m_id(id), m_handler(handler), m_timestamp(0) { m_timestamp = ossimTimer::instance()->tick(); } CellInfo(const CellInfo& src) :ossimReferenced(src), m_id(src.m_id), m_handler(src.m_handler), m_timestamp(src.m_timestamp) { } CellInfo() :ossimReferenced(), m_id(0), m_handler(0), m_timestamp(0) { } const CellInfo& operator =(const CellInfo& src) { if (this != &src) { m_id = src.m_id; m_handler = src.m_handler; m_timestamp = src.m_timestamp; } return *this; } void updateTimestamp() { m_timestamp = ossimTimer::instance()->tick(); } ossim_uint64 id()const { return m_id; } ossim_uint64 m_id; ossimRefPtr m_handler; ossimTimer::Timer_t m_timestamp; }; typedef std::map > CellMap; ossimElevationCellDatabase() :ossimElevationDatabase(), m_minOpenCells(5), m_maxOpenCells(10), m_memoryMapCellsFlag(false) { } ossimElevationCellDatabase(const ossimElevationCellDatabase& src) :ossimElevationDatabase(src), m_minOpenCells(src.m_minOpenCells), m_maxOpenCells(src.m_maxOpenCells), m_cacheMap(src.m_cacheMap), m_memoryMapCellsFlag(src.m_memoryMapCellsFlag) { } virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual ossim_uint32 getMinOpenCells()const { return m_minOpenCells; } virtual ossim_uint32 getMaxOpenCells()const { return m_maxOpenCells; } virtual void setMinMaxOpenCells(ossim_uint64 minCellCount, ossim_uint64 maxCellCount) { m_minOpenCells = minCellCount; m_maxOpenCells = maxCellCount; } virtual bool getMemoryMapCellsFlag()const { return m_memoryMapCellsFlag; } virtual void setMemoryMapCellsFlag(bool flag) { m_memoryMapCellsFlag = flag; } virtual void getOpenCellList(std::vector& list) const; /** * @brief Gets a list of elevation cells needed to cover bounding box. * @param connectionString Typically elevation repository, e.g.: * "/data1/elevation/srtm/1arc" * @param minLat Minimum latitude of bounding box. * @param minLon Minimum longitude of bounding box. * @param maxLat Maximum latitude of bounding box. * @param maxLon Maximum longitude of bounding box. * @param cells Initialized by this. * @param maxNumberOfCells Value of 0 indicates return as many as you can. Any positive * number will only return that number of cells. */ void getCellsForBounds( const ossim_float64& minLat, const ossim_float64& minLon, const ossim_float64& maxLat, const ossim_float64& maxLon, std::vector& cells, ossim_uint32 maxNumberOfCells=0 ); virtual ossim_uint64 createId(const ossimGpt& /* pt */)const { return 0; } virtual ossimRefPtr getOrCreateCellHandler(const ossimGpt& gpt); virtual std::ostream& print(std::ostream& out) const; protected: virtual ossimRefPtr createCell(const ossimGpt& /* gpt */) { return 0; } virtual void remove(ossim_uint64 id) { CellMap::iterator iter = m_cacheMap.find(id); if(iter != m_cacheMap.end()) { m_cacheMap.erase(iter); } } void flushCacheToMinOpenCells() { // lets flush the cache from least recently used to recent. // CellMap sortedMap; CellMap::iterator iter = m_cacheMap.begin(); while(iter != m_cacheMap.end()) { sortedMap.insert(std::make_pair(iter->second->m_timestamp, iter->second)); ++iter; } iter = sortedMap.begin(); while((iter!=sortedMap.end())&&(m_cacheMap.size() > m_minOpenCells)) { remove(iter->second->id()); ++iter; } } ossim_uint32 m_minOpenCells; ossim_uint32 m_maxOpenCells; mutable std::mutex m_cacheMapMutex; CellMap m_cacheMap; ossim_uint32 m_memoryMapCellsFlag; TYPE_DATA; }; #endif /* #ifndef ossimElevationCellDatabase_HEADER */ ossim-Miami-2.9.1/include/ossim/elevation/ossimElevationDatabase.h000066400000000000000000000043351352751253100252620ustar00rootroot00000000000000#ifndef ossimElevationDatabase_HEADER #define ossimElevationDatabase_HEADER 1 #include #include #include #include #include #include #include #include #include #include #include #include #include class OSSIM_DLL ossimElevationDatabase : public ossimElevSource { public: ossimElevationDatabase() : ossimElevSource(), m_meanSpacing(0.0) { } ossimElevationDatabase(const ossimElevationDatabase& src) : ossimElevSource(src), m_connectionString(src.m_connectionString), m_geoid(src.m_geoid), m_meanSpacing(src.m_meanSpacing) { } virtual bool getAccuracyInfo(ossimElevationAccuracyInfo& /*info*/, const ossimGpt& /*gpt*/) const { return false; } virtual double getMeanSpacingMeters() const { return m_meanSpacing; } virtual void setGeoid(ossimGeoid* geoid) { m_geoid = geoid; } ossimGeoid* getGeoid() { return m_geoid.get(); } const ossimGeoid* getGeoid()const { return m_geoid.get(); } /** * Open a connection to a database. In most cases this will be a pointer * to a directory like in a Dted directory reader. * */ virtual bool open(const ossimString& connectionString)=0; const ossimString& getConnectionString()const { return m_connectionString; } virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual std::ostream& print(std::ostream& out) const; protected: virtual ~ossimElevationDatabase() { m_geoid = 0; } virtual double getOffsetFromEllipsoid(const ossimGpt& gpt); ossimString m_connectionString; ossimRefPtr m_geoid; ossim_float64 m_meanSpacing; TYPE_DATA }; // End: class ossimElevationDatabase #endif /* #ifndef ossimElevationDatabase_HEADER */ ossim-Miami-2.9.1/include/ossim/elevation/ossimElevationDatabaseFactory.h000066400000000000000000000074231352751253100266130ustar00rootroot00000000000000#ifndef ossimElevationDatabaseFactory_HEADER #define ossimElevationDatabaseFactory_HEADER #include "ossimElevationDatabaseFactoryBase.h" /** * This is our default elevation factory in the ossim core. It supports * general_raster, general imagery, DTED and SRTM directory layouts. * * Example DTED Keywordlist: * @code * elevation_manager.elevation_source1.type: dted_directory * elevation_manager.elevation_source1.connection_string: /data/elevation/dted/level0 * elevation_manager.elevation_source1.min_open_cells: 5 * elevation_manager.elevation_source1.max_open_cells: 25 * elevation_manager.elevation_source1.enabled: true * elevation_manager.elevation_source1.memory_map_cells: true * @endcode * Note: only use memory_map_cells to true if they are small files. DTED0 is * small so we set it to true. * Where the dted file tree has the form: /w056/n49.dt0 * * Example General Raster directory: * @code * elevation_manager.elevation_source2.type: general_raster_directory * elevation_manager.elevation_source2.connection_string: /data/tutorial/data/elevation/general_raster_pk_90m * elevation_manager.elevation_source2.min_open_cells: 25 * elevation_manager.elevation_source2.max_open_cells: 50 * elevation_manager.elevation_source2.enabled: false * elevation_manager.elevation_source2.memory_map_cells: false * @endcode * where the directory is a flat directory with general raster files * * Example SRTM directory: * @code * elevation_manager.elevation_source10.type: srtm_directory * elevation_manager.elevation_source10.connection_string: /Volumes/DataDrive/data/elevation/srtm1/ * elevation_manager.elevation_source10.min_open_cells: 25 * elevation_manager.elevation_source10.max_open_cells: 50 * elevation_manager.elevation_source10.memory_map_cells: false * elevation_manager.elevation_source10.enabled: true * @endcode * where the directory has files of the form N39W112.hgt and are 1x1 degree * cells * * Example image directory format: * @code * elevation_manager.elevation_source20.type: image_directory * elevation_manager.elevation_source20.connection_string: /data/elevation/image * elevation_manager.elevation_source20.min_open_cells: 25 * elevation_manager.elevation_source20.max_open_cells: 50 * elevation_manager.elevation_source20.memory_map_cells: false * elevation_manager.elevation_source20.enabled: false * @endcode * * where the directory can have any image the ossim supports and is a flat directory */ class OSSIM_DLL ossimElevationDatabaseFactory : public ossimElevationDatabaseFactoryBase { public: ossimElevationDatabaseFactory() { m_instance = this; } /** * @return a singleton instance of this factory */ static ossimElevationDatabaseFactory* instance(); /** * @param typeName is the type name of the database you wish to * create. * @return the elevation database or null otherwise */ ossimElevationDatabase* createDatabase(const ossimString& typeName)const; /** * @param kwl kewyord list that has state information about how to * create a database * @param prefix prefix key to use when loading the state information. * @return the elevation database or null otherwise */ ossimElevationDatabase* createDatabase(const ossimKeywordlist& kwl, const char* prefix=0)const; /** * @param connectionString used to determine which database can support * that connection. * @return the elevation database or null otherwise */ virtual ossimElevationDatabase* open(const ossimString& connectionString)const; /** * @param typeList appends to the typeList all the type names this factory * supports */ virtual void getTypeNameList(std::vector& typeList)const; protected: static ossimElevationDatabaseFactory* m_instance; }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimElevationDatabaseFactoryBase.h000066400000000000000000000021021352751253100273730ustar00rootroot00000000000000#ifndef ossimElevationDatabaseFactoryBase_HEADER #define ossimElevationDatabaseFactoryBase_HEADER 1 #include #include #include class OSSIM_DLL ossimElevationDatabaseFactoryBase : public ossimObjectFactory { public: /** * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const { return createDatabase(typeName); } /** * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const { return createDatabase(kwl, prefix); } virtual ossimElevationDatabase* createDatabase(const ossimString& typeName)const=0; virtual ossimElevationDatabase* createDatabase(const ossimKeywordlist& kwl, const char* prefix=0)const=0; virtual ossimElevationDatabase* open(const ossimString& connectionString)const=0; }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimElevationDatabaseRegistry.h000066400000000000000000000033221352751253100270060ustar00rootroot00000000000000#ifndef ossimElevationDatabaseRegistry_HEADER #define ossimElevationDatabaseRegistry_HEADER #include #include #include /** * * This is the elevation database registry. * @see ossimElevationDatabaseFactory for more details on the factories * supported within the ossim core. * */ class OSSIM_DLL ossimElevationDatabaseRegistry : public ossimFactoryListInterface { public: ossimElevationDatabaseRegistry() { m_instance = 0; } static ossimElevationDatabaseRegistry* instance(); void getTypeNameList(std::vector& typeList) const { getAllTypeNamesFromRegistry(typeList); } /** * @param typeName is the type name of the database you wish to * create * @return the elevation database or null otherwise */ ossimElevationDatabase* createDatabase(const ossimString& typeName)const; /** * @param kwl kewyord list that has state information about how to * create a database * @param prefix prefix key to use when loading the state information. * @return the elevation database or null otherwise */ ossimElevationDatabase* createDatabase(const ossimKeywordlist& kwl, const char* prefix=0)const; /** * @param connectionString used to determine which database can support * that connection. * @return the elevation database or null otherwise */ ossimElevationDatabase* open(const ossimString& connectionString); protected: static ossimElevationDatabaseRegistry* m_instance; }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimGeneralRasterElevFactory.h000066400000000000000000000047311352751253100266110ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: see top level LICENSE.txt file // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // // elevation handler for general raster elevation files. // //---------------------------------------------------------------------------- // $Id: ossimGeneralRasterElevFactory.h 13269 2008-07-25 14:27:36Z dburken $ #ifndef ossimGeneralRasterElevFactory_HEADER #define ossimGeneralRasterElevFactory_HEADER #include #include #include /** * @class ossimSrtmFactory Used by the elevation manager, this class returns * an ossimSrtmElevSource given a ground point and some directory with srtm * files in it. */ class OSSIM_DLL ossimGeneralRasterElevFactory : public ossimElevSourceFactory { public: typedef std::vector BoundingRectListType; /** Constructor that takes a file name. */ /** default constructor */ ossimGeneralRasterElevFactory(); /** Constructor that takes a directory name. */ ossimGeneralRasterElevFactory(const ossimFilename& dir); /** destructor */ virtual ~ossimGeneralRasterElevFactory(); void setDirectory(const ossimFilename& directory); /** * Open the appropriate handler that covers given a * ground point. * * @param gpt Ground point that an elevation source is need for. * * @return Returns a pointer to an ossimElevSource if an elevation file is found * that can cover the ground point. Returns NULL if no cell is found * for the point. */ virtual ossimElevSource* getNewElevSource(const ossimGpt& gpt) const; /** To satisfy pure virtual. */ virtual void createIndex(); protected: /* void initializeList(const ossimFilename& file); */ /* bool initializeInfo(ossimGeneralRasterElevHandler::GeneralRasterInfo& info, */ /* const ossimFilename& file); */ void addInfo(const ossimGeneralRasterElevHandler::GeneralRasterInfo& info); std::vector theGeneralRasterInfoList; ossimDrect theBoundingRect; /* mutable std::ifstream theFileStr; */ mutable ossim_int32 theCurrentIdx; mutable bool theHandlerReturnedFlag; TYPE_DATA }; #endif /* End of "#ifndef ossimSrtmFactory_HEADER" */ ossim-Miami-2.9.1/include/ossim/elevation/ossimGeneralRasterElevHandler.h000066400000000000000000000127301352751253100265550ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: see top level LICENSE.txt // // Author: Garrett Potts // // Description: // // //---------------------------------------------------------------------------- // $Id: ossimGeneralRasterElevHandler.h 23117 2015-01-29 22:33:13Z okramer $ #ifndef ossimGeneralRasterElevHandler_HEADER #define ossimGeneralRasterElevHandler_HEADER #include #include //#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class ossimProjection; /** * @class ossimGeneralRasterElevHandler Elevation source for an srtm file. */ class OSSIM_DLL ossimGeneralRasterElevHandler : public ossimElevCellHandler { public: class GeneralRasterInfo { public: GeneralRasterInfo() :theWidth(0), theHeight(0), theNullHeightValue(ossim::nan()), theScalarType(OSSIM_SCALAR_UNKNOWN), theBytesPerRawLine(0), theDatum(0), theGeometry(0) { } GeneralRasterInfo(const ossimGeneralRasterElevHandler::GeneralRasterInfo& src) :theFilename(src.theFilename), theImageRect(src.theImageRect), theUl(src.theUl), theLr(src.theLr), theWidth(src.theWidth), theHeight(src.theHeight), theWgs84GroundRect(src.theWgs84GroundRect), theNullHeightValue(src.theNullHeightValue), theByteOrder(src.theByteOrder), theScalarType(src.theScalarType), theBytesPerRawLine(src.theBytesPerRawLine), theDatum(src.theDatum), theGeometry(src.theGeometry) { } ossimFilename theFilename; ossimIrect theImageRect; ossimIpt theUl; ossimIpt theLr; ossim_uint32 theWidth; ossim_uint32 theHeight; ossimDrect theWgs84GroundRect; ossim_float64 theNullHeightValue; ossimByteOrder theByteOrder; ossimScalarType theScalarType; ossim_uint32 theBytesPerRawLine; const ossimDatum* theDatum; ossimRefPtr theGeometry; //add by simbla }; ossimGeneralRasterElevHandler(const ossimFilename& file=""); ossimGeneralRasterElevHandler(const ossimGeneralRasterElevHandler::GeneralRasterInfo& generalRasterInfo); ossimGeneralRasterElevHandler(const ossimGeneralRasterElevHandler& rhs); /** destructor */ virtual ~ossimGeneralRasterElevHandler(); virtual ossimObject* dup() const { return new ossimGeneralRasterElevHandler(this->theFilename); } /** * METHOD: getHeightAboveMSL * Height access methods. */ virtual double getHeightAboveMSL(const ossimGpt&); /** * METHOD: getSizeOfElevCell * Returns the number of post in the cell. Satisfies pure virtual. * Note: x = longitude, y = latitude */ virtual ossimIpt getSizeOfElevCell() const; /** * METHOD: getPostValue * Returns the value at a given grid point as a double. * Satisfies pure virtual. */ virtual double getPostValue(const ossimIpt& gridPt) const; virtual bool isOpen()const; /** * Opens a stream to the srtm cell. * * @return Returns true on success, false on error. */ bool open(const ossimFilename& file, bool memoryMapFlag=false); /** * Closes the stream to the file. */ virtual void close(); /** * This method does not really fit the handler since this handle a * directory not a cell that could have holes in it. So users looking for * valid coverage should call "pointHasCoverage". */ ossimDrect getBoundingRect()const; /** * Loops through ossimGeneralRasterElevHandler::BoundingRectListType and * checks for coverage. * * @param gpt Point to look for. * * @return true if coverage is found false if not. */ virtual bool pointHasCoverage(const ossimGpt& gpt) const; const ossimGeneralRasterElevHandler::GeneralRasterInfo& generalRasterInfo()const; private: template double getHeightAboveMSLFileTemplate(T dummy, const ossimGeneralRasterElevHandler::GeneralRasterInfo& info, const ossimGpt& gpt); template double getHeightAboveMSLMemoryTemplate(T dummy, const ossimGeneralRasterElevHandler::GeneralRasterInfo& info, const ossimGpt& gpt); virtual bool setFilename(const ossimFilename& file); ossimGeneralRasterElevHandler::GeneralRasterInfo theGeneralRasterInfo; mutable std::mutex m_inputStreamMutex; std::ifstream m_inputStream; /** @brief true if stream is open. */ bool m_streamOpen; std::vector m_memoryMap; TYPE_DATA }; #endif /* End of "#ifndef ossimGeneralRasterElevHandler_HEADER" */ ossim-Miami-2.9.1/include/ossim/elevation/ossimGeneralRasterElevationDatabase.h000066400000000000000000000053321352751253100277370ustar00rootroot00000000000000#ifndef ossimGeneralRasterElevationDatabase_HEADER #define ossimGeneralRasterElevationDatabase_HEADER 1 #include #include #include #include class OSSIM_DLL ossimGeneralRasterElevationDatabase : public ossimElevationCellDatabase { public: ossimGeneralRasterElevationDatabase() :ossimElevationCellDatabase() { } ossimGeneralRasterElevationDatabase(const ossimGeneralRasterElevationDatabase& rhs) :ossimElevationCellDatabase(rhs) { } virtual ~ossimGeneralRasterElevationDatabase() { if(m_cellHandler.valid()) { m_cellHandler->close(); } m_cellHandler = 0; } virtual ossimObject* dup() const { ossimGeneralRasterElevationDatabase* duped = new ossimGeneralRasterElevationDatabase; duped->open(m_connectionString); return duped; } virtual bool open(const ossimString& connectionString); virtual bool pointHasCoverage(const ossimGpt& gpt) const; virtual bool getAccuracyInfo(ossimElevationAccuracyInfo& /*info*/, const ossimGpt& /*gpt*/) const { return false; } /** * METHODS: accuracyLE90(), accuracyCE90() * Returns the vertical and horizontal accuracy (90% confidence) in the * region of gpt: */ // virtual double getAccuracyLE90(const ossimGpt& /* gpt */) const // { // std::cout << "ossimGeneralElevationDatabase::getAccuracyLE90 \n"; // return 0.0; // } // virtual double getAccuracyCE90(const ossimGpt& /* gpt */) const // { // std::cout << "ossimGeneralElevationDatabase::getAccuracyCE90 \n"; // return 0.0; // } virtual double getHeightAboveMSL(const ossimGpt&); virtual double getHeightAboveEllipsoid(const ossimGpt& gpt); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; virtual ossim_uint64 createId(const ossimGpt& /* pt */)const { return 0; } virtual std::ostream& print(std::ostream& out) const; protected: ossimRefPtr m_cellHandler; bool openGeneralRasterDirectory(const ossimFilename& dir); void createRelativePath(ossimFilename& file, const ossimGpt& gpt)const; void createFullPath(ossimFilename& file, const ossimGpt& gpt)const { ossimFilename relativeFile; createRelativePath(relativeFile, gpt); file = ossimFilename(m_connectionString).dirCat(relativeFile); } ossimRefPtr createHandler(const ossimGpt& /* gpt */); virtual ossimRefPtr createCell(const ossimGpt& /* gpt */); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimHgtRef.h000066400000000000000000000060341352751253100230640ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Height reference class. //---------------------------------------------------------------------------- #ifndef ossimHgtRef_HEADER #define ossimHgtRef_HEADER 1 #include #include #include #include #include enum HeightRefType_t { AT_HGT = 0, AT_DEM = 1 }; class OSSIM_DLL ossimHgtRef { public: /** * @brief constructor. */ ossimHgtRef(HeightRefType_t cRefType); ossimHgtRef(HeightRefType_t cRefType, const ossim_float64& atHgt); /** * @brief virtual destructor. */ virtual ~ossimHgtRef(); /** * @brief Method to get height reference type (ellipsoid or DEM). */ HeightRefType_t getHeightRefType() const {return theCurrentHeightRefType;} /** * @brief Method to get height reference. * * @param pg Reference point. * * @return Height at reference point. */ virtual ossim_float64 getRefHeight(const ossimGpt& pg) const; /** * @brief Method to get surface information string. * * @param pg Reference point. * @param info ossimElevationAccuracyInfo string. * * @return true on success, false on error. */ // virtual bool getSurfaceInfo // (const ossimGpt& pg, ossimElevationAccuracyInfo& info) const; /** * @brief Method to get surface covariance matrix. * * @param pg Reference point. * @param cov 3X3 ENU covariance matrix. * * @return true on success, false on error. */ virtual bool getSurfaceCovMatrix (const ossimGpt& pg, NEWMAT::Matrix& cov) const; /** * @brief Method to get surface covariance matrix. * * @param refCE Reference surface 90% CE [m] * @param refLE Reference surface 90% LE [m] * @param cov 3X3 ENU covariance matrix. * * @return true on success, false on error. */ virtual bool getSurfaceCovMatrix (const ossim_float64 refCE, const ossim_float64 refLE, NEWMAT::Matrix& cov) const; /** * @brief Method to get surface normal covariance matrix. * * @param pg Reference point. * @param surfCov 3X3 ENU surface covariance matrix. * @param normCov 3X3 ECF normal covariance matrix. * * @return true on success, false on error. */ bool getSurfaceNormalCovMatrix (const ossimGpt& pg, const NEWMAT::Matrix& surfCov, NEWMAT::Matrix& normCov) const; /** * @brief Method to get local terrain normal unit vector (slope). * * @param pg Reference point. * * @return ossimColumnVector3D. */ virtual ossimColumnVector3d getLocalTerrainNormal(const ossimGpt& pg) const; protected: private: HeightRefType_t theCurrentHeightRefType; ossim_float64 theCurrentRefHeight; }; #endif /* #ifndef ossimHgtRef_HEADER */ ossim-Miami-2.9.1/include/ossim/elevation/ossimImageElevationDatabase.h000066400000000000000000000143151352751253100262240ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimImageElevationDatabase.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: See description for class below. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimImageElevationDatabase_HEADER #define ossimImageElevationDatabase_HEADER 1 #include #include #include #include #include #include #include #include class ossimString; /** * @class ossimTiledElevationDatabase * * Elevation source used for working with generic images opened by an * ossimImageHandler. This class is typically utilized through the * ossimElevManager. */ class OSSIM_DLL ossimImageElevationDatabase : public ossimElevationCellDatabase, public ossimFileProcessorInterface { public: /** default constructor */ ossimImageElevationDatabase(); /** * @brief Open a connection to a database. * * @param connectionString File or directory to open. In most cases this * will point to a directory containing DEMs. Satisfies pure virtual * ossimElevationDatabase::open(). * * @return true on success, false on error. */ virtual bool open(const ossimString& connectionString); /** @brief close method. Unreferences all data. */ virtual void close(); virtual ossimObject* dup() const { ossimImageElevationDatabase* duped = new ossimImageElevationDatabase; duped->open(m_connectionString); return duped; } /** * @brief Maps elevation data for region to a grid. * * This uses connectionString passed to open method as starting point. */ void mapRegion(const ossimGrect& region); /** * @brief Get height above MSL for point. * * Satisfies pure virtual ossimElevSource::getHeightAboveMSL(). * * @return Height above MSL. */ virtual double getHeightAboveMSL(const ossimGpt& gpt); /** * @brief Get height above ellipsoid for point. * * Satisfies pure virtual ossimElevSource::getHeightAboveMSL(). * * @return Height above MSL. */ virtual double getHeightAboveEllipsoid(const ossimGpt&); /** * Satisfies pure virtual ossimElevSource::pointHasCoverage * * @return true if database has coverage for point. */ virtual bool pointHasCoverage(const ossimGpt& gpt) const; virtual bool getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& gpt) const; /** * Statisfies pure virtual ossimElevSource::getAccuracyLE90. * @return The vertical accuracy (90% confidence) in the * region of gpt: */ //virtual double getAccuracyLE90(const ossimGpt& gpt) const; /** * Statisfies pure virtual ossimElevSource::getAccuracyCE90. * @return The horizontal accuracy (90% confidence) in the * region of gpt. */ //virtual double getAccuracyCE90(const ossimGpt& gpt) const; /** @brief Initialize from keyword list. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** @brief Save the state to a keyword list. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * @brief Gets the bounding rectangle/coverage of elevation. * * @param rect Rectangle to initialize. */ void getBoundingRect(ossimGrect& rect) const; /** * @brief ProcessFile method. * * Satisfies pure virtual ossimFileProcessorInterface::processFile. * * This method is linked to the ossimFileWalker::walk method via a pointer * to this class. * * @param file to process. */ virtual void processFile(const ossimFilename& file); virtual std::ostream& print(std::ostream& out) const; protected: /** * @Brief Protected destructor. * * This class is derived from ossimReferenced so users should always use * ossimRefPtr to hold instance. */ virtual ~ossimImageElevationDatabase(); virtual ossimRefPtr createCell(const ossimGpt& gpt); // virtual ossim_uint64 createId(const ossimGpt& pt) const; /** * @brief Gets cell for point. * * This override ossimElevationCellDatabase::getOrCreateCellHandler as we cannot use * the createId as our cells could be of any size. */ virtual ossimRefPtr getOrCreateCellHandler(const ossimGpt& gpt); /** * @brief Removes an entry from the m_cacheMap and m_entryMap maps. */ virtual void remove(ossim_uint64 id); private: // Private container to hold bounding rect, nominal GSD, and image handler. struct ossimImageElevationFileEntry { /** @brief default constructor */ ossimImageElevationFileEntry(); /** @brief Constructor that takes a file name. */ ossimImageElevationFileEntry(const ossimFilename& file); ossimImageElevationFileEntry(const ossimImageElevationFileEntry& copy_this); /** file name */ ossimFilename m_file; /** Bounding rectangle in decimal degrees. */ ossimGrect m_rect; ossimDpt m_nominalGSD; // post spacing at center /** True if in ossimElevationCellDatabase::m_cacheMap. */ bool m_loadedFlag; }; /** * @brief Initializes m_entryMap with all loadable files from * m_connectionString. */ void loadFileMap(); /** Hidden from use copy constructor */ ossimImageElevationDatabase(const ossimImageElevationDatabase& copy_this); std::map m_entryMap; ossim_uint64 m_lastMapKey; ossim_uint64 m_lastAccessedId; TYPE_DATA }; inline void ossimImageElevationDatabase::remove(ossim_uint64 id) { std::map::iterator entryIter = m_entryMap.find(id); if ( entryIter != m_entryMap.end() ) { (*entryIter).second.m_loadedFlag = false; } ossimElevationCellDatabase::remove(id); } #endif /* ossimImageElevationDatabase_HEADER */ ossim-Miami-2.9.1/include/ossim/elevation/ossimImageElevationHandler.h000066400000000000000000000103111352751253100260650ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimImageElevationHandler.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: See description for class below. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimImageElevationHandler_HEADER #define ossimImageElevationHandler_HEADER 1 #include #include #include #include #include #include #include /** * @class ossimImageElevationHandler * * Elevation source for a generic image opened via ossimImageHandler. */ class OSSIM_DLL ossimImageElevationHandler : public ossimElevCellHandler { public: /** default constructor */ ossimImageElevationHandler(); ossimImageElevationHandler(const ossimFilename& file); /** * METHOD: getHeightAboveMSL * Height access methods. */ virtual double getHeightAboveMSL(const ossimGpt&); /** * METHOD: getSizeOfElevCell * Returns the number of post in the cell. Satisfies pure virtual. * Note: x = longitude, y = latitude */ virtual ossimIpt getSizeOfElevCell() const; /** * METHOD: getPostValue * Returns the value at a given grid point as a double. * Satisfies pure virtual. */ virtual double getPostValue(const ossimIpt& gridPt) const; /** @return True if open, false if not. */ virtual bool isOpen()const; /** * Opens a stream to the srtm cell. * * @return Returns true on success, false on error. */ virtual bool open(const ossimFilename& file); /** @brief Closes the stream to the file. */ virtual void close(); /** * @brief pointHasCoverage(gpt) * * Overrides ossimElevCellHandler::pointHasCoverage * @return TRUE if coverage exists over gpt. */ virtual bool pointHasCoverage(const ossimGpt&) const; virtual ossimObject* dup () const { return new ossimImageElevationHandler(this->getFilename()); } protected: /** * @Brief Protected destructor. * * This class is derived from ossimReferenced so users should always use * ossimRefPtr to hold instance. */ virtual ~ossimImageElevationHandler(); private: class TileCacheEntry { public: TileCacheEntry() : id(99999) {} TileCacheEntry(ossim_uint32 xid, ossimImageData* xdata) : id(xid), data(xdata) {} TileCacheEntry(const TileCacheEntry& copy) : id(copy.id), data(copy.data) {} const TileCacheEntry& operator=(const TileCacheEntry& copy) { id = copy.id; data = copy.data; return *this; } ossim_uint32 id; ossimRefPtr data; }; /** Hidden from use copy constructor */ ossimImageElevationHandler(const ossimImageElevationHandler&); /** Hidden from use assignment operator */ const ossimImageElevationHandler& operator= (const ossimImageElevationHandler& rhs); /** Looks for an elevation tile in the cache first before reading the tile from the input handler */ ossimImageData* getTile(ossim_uint32 x, ossim_uint32 y) const; /** Pointers to links in chain. */ mutable ossimRefPtr m_ih; ossimRefPtr m_geom; mutable std::vector m_tileCache; /** Image space rect stored as drect for inlined pointHasCoverage method. */ ossimDrect m_rect; ossimIpt m_tileSize; ossim_uint32 m_numTilesPerRow; mutable std::mutex m_mutex; TYPE_DATA }; inline bool ossimImageElevationHandler::isOpen() const { return m_ih.valid(); } inline void ossimImageElevationHandler::close() { m_geom = 0; m_ih = 0; } inline bool ossimImageElevationHandler::pointHasCoverage(const ossimGpt& gpt) const { if ( m_geom.valid() ) { ossimDpt dpt; m_geom->worldToLocal(gpt, dpt); return m_rect.pointWithin(dpt); } return false; } #endif /* ossimImageElevationHandler_HEADER */ ossim-Miami-2.9.1/include/ossim/elevation/ossimSrtmElevationDatabase.h000066400000000000000000000043461352751253100261320ustar00rootroot00000000000000//--- // // License: MIT // //--- // $Id$ #ifndef ossimSrtmElevationDatabase_HEADER #define ossimSrtmElevationDatabase_HEADER 1 #include #include #include #include class OSSIM_DLL ossimSrtmElevationDatabase : public ossimElevationCellDatabase { public: typedef std::vector > DirectMap; // 360x180 cell grid ossimSrtmElevationDatabase(); ossimSrtmElevationDatabase(const ossimSrtmElevationDatabase& rhs); virtual ~ossimSrtmElevationDatabase(); virtual ossimObject* dup() const; virtual bool open(const ossimString& connectionString); bool getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& /*gpt*/) const; virtual bool pointHasCoverage(const ossimGpt& gpt) const { ossimFilename filename; createFullPath(filename, gpt); return filename.exists(); } virtual double getHeightAboveMSL(const ossimGpt&); virtual double getHeightAboveEllipsoid(const ossimGpt& gpt); virtual ossim_uint64 createId(const ossimGpt& pt)const { ossim_uint64 y = static_cast(ossim::wrap(pt.latd(), -90.0, 90.0)+90.0); ossim_uint64 x = static_cast(ossim::wrap(pt.lond(),-180.0,180.0)+180.0); // map the extreme edge to the same ID ax the 179 west cell and the same for the 89 // degree north cell. // x = x==360?359:x; y = y==180?179:y; // Srtm databases are 1x1 degree cells and we will use a world // grid for id generation. // return (y*360+x); } virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; protected: bool openSrtmDirectory(const ossimFilename& dir); void createRelativePath(ossimFilename& file, const ossimGpt& gpt)const; void createFullPath(ossimFilename& file, const ossimGpt& gpt)const { ossimFilename relativeFile; createRelativePath(relativeFile, gpt); file = ossimFilename(m_connectionString).dirCat(relativeFile); } ossimRefPtr createCell(const ossimGpt& gpt); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/elevation/ossimSrtmFactory.h000066400000000000000000000031311352751253100241550ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Shuttle Radar Topography Mission (SRTM) factory to return an // ossimSrtmElevSource given a ground point. // //---------------------------------------------------------------------------- // $Id: ossimSrtmFactory.h 13269 2008-07-25 14:27:36Z dburken $ #ifndef ossimSrtmFactory_HEADER #define ossimSrtmFactory_HEADER #include /** * @class ossimSrtmFactory Used by the elevation manager, this class returns * an ossimSrtmElevSource given a ground point and some directory with srtm * files in it. */ class OSSIM_DLL ossimSrtmFactory : public ossimElevSourceFactory { public: /** default constructor */ ossimSrtmFactory(); /** Constructor that takes a directory name. */ ossimSrtmFactory(const ossimFilename& dir); /** destructor */ virtual ~ossimSrtmFactory(); /** * Open the appropriate ossimSrtmElevSource that covers given a * ground point. * * @param gpt Ground point that an elevation source is need for. * * @return Returns a pointer to an ossimElevSource if an srtm file is found * that can cover the ground point. Returns NULL if no cell is found * for the point. */ virtual ossimElevSource* getNewElevSource(const ossimGpt& gpt) const; protected: TYPE_DATA }; #endif /* End of "#ifndef ossimSrtmFactory_HEADER" */ ossim-Miami-2.9.1/include/ossim/elevation/ossimSrtmHandler.h000066400000000000000000000056041352751253100241320ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See tope level LICENSE.txt file. // // Author: David Burken // // Description: // // Shuttle Radar Topography Mission (SRTM) elevation source. // //---------------------------------------------------------------------------- // $Id: ossimSrtmHandler.h 23117 2015-01-29 22:33:13Z okramer $ #ifndef ossimSrtmHandler_HEADER #define ossimSrtmHandler_HEADER #include //#include #include #include #include #include class ossimEndian; /** * @class ossimSrtmHandler Elevation source for an srtm file. */ class OSSIMDLLEXPORT ossimSrtmHandler : public ossimElevCellHandler { public: /** Constructor that takes a file name. */ ossimSrtmHandler(); ossimSrtmHandler(const ossimSrtmHandler&); enum { NULL_POST = -32768 // Fixed by SRTM specification. }; /** * METHOD: getHeightAboveMSL * Height access methods. */ virtual double getHeightAboveMSL(const ossimGpt&); /** * METHOD: getSizeOfElevCell * Returns the number of post in the cell. Satisfies pure virtual. * Note: x = longitude, y = latitude */ virtual ossimIpt getSizeOfElevCell() const; /** * METHOD: getPostValue * Returns the value at a given grid point as a double. * Satisfies pure virtual. */ virtual double getPostValue(const ossimIpt& gridPt) const; virtual bool isOpen()const; /** * Opens a stream to the srtm cell. * * @return Returns true on success, false on error. */ virtual bool open(const ossimFilename& file, bool memoryMapFlag=false); /** * Closes the stream to the file. */ virtual void close(); virtual ossimObject* dup() const { ossimSrtmHandler* obj = new ossimSrtmHandler(); obj->open(theFilename, (m_memoryMap.size() != 0)); return obj; } protected: /** destructor */ virtual ~ossimSrtmHandler(); ossimSrtmSupportData m_supportData; mutable std::mutex m_fileStrMutex; std::ifstream m_fileStr; /** @brief true if stream is open. */ bool m_streamOpen; ossim_int32 m_numberOfLines; ossim_int32 m_numberOfSamples; ossim_int32 m_srtmRecordSizeInBytes; double m_latSpacing; // degrees double m_lonSpacing; // degrees ossimDpt m_nwCornerPost; // cell origin; ossimEndian* m_swapper; ossimScalarType m_scalarType; mutable std::vector m_memoryMap; template double getHeightAboveMSLFileTemplate(T dummy, const ossimGpt& gpt); template double getHeightAboveMSLMemoryTemplate(T dummy, const ossimGpt& gpt); TYPE_DATA }; #endif /* End of "#ifndef ossimSrtmHandler_HEADER" */ ossim-Miami-2.9.1/include/ossim/elevation/ossimTiledElevationDatabase.h000066400000000000000000000151521352751253100262430ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimTiledElevationDatabase.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: See description for class below. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimTiledElevationDatabase_HEADER #define ossimTiledElevationDatabase_HEADER 1 #include #include #include #include #include #include class ossimDblGrid; class ossimFilename; class ossimFileWalker; class ossimImageData; class ossimImageGeometry; class ossimImageHandler; class ossimProjection; class ossimSingleImageChain; class ossimString; /** * @class ossimTiledElevationDatabase * * Elevation source used for working with generic images opened by an * ossimImageHandler. This class supplies a mapRegion method used to map a * region of elevation to a grid. The grid in turn is used for the * getHeightAboveMSL. This class is for applications that know their region * of interest up front and want to bypass the ossimElevManager and grid the * elevation prior to processing for speed. Can work on a file or a * directory of files. */ class OSSIM_DLL ossimTiledElevationDatabase : public ossimElevationDatabase, public ossimFileProcessorInterface { public: /** default constructor */ ossimTiledElevationDatabase(); /** * @brief Open a connection to a database. * * @param connectionString File or directory to open. In most cases this * will point to a directory containing DEMs. Satisfies pure virtual * ossimElevationDatabase::open(). * * @return true on success, false on error. */ virtual bool open(const ossimString& connectionString); /** @brief close method. Unreferences all data. */ virtual void close(); /** * @brief Maps elevation data for region to a grid. * * This uses connectionString passed to open method as starting point. */ void mapRegion(const ossimGrect& region); /** * @brief Get height above MSL for point. * * Satisfies pure virtual ossimElevSource::getHeightAboveMSL(). * * @return Height above MSL. */ virtual double getHeightAboveMSL(const ossimGpt& gpt); /** * @brief Get height above ellipsoid for point. * * Satisfies pure virtual ossimElevSource::getHeightAboveMSL(). * * @return Height above MSL. */ virtual double getHeightAboveEllipsoid(const ossimGpt&); /** * Satisfies pure virtual ossimElevSource::pointHasCoverage * * @return true if database has coverage for point. */ virtual bool pointHasCoverage(const ossimGpt& gpt) const; /** @brief Initialize from keyword list. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** @brief Save the state to a keyword list. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& /*gpt*/) const { info.makeNan(); return false; } /** * @brief ProcessFile method. * * Satisfies pure virtual ossimFileProcessorInterface::processFile. * * This method is linked to the ossimFileWalker::walk method via a callback * mechanism. It is called by the ossimFileWalk (caller). This class * (callee) sets recurse and return flags accordingly to control * the ossimFileWalker, e.g. don't recurse, stop altogether. * * @param file to process. */ virtual void processFile(const ossimFilename& file); virtual std::ostream& print(std::ostream& out) const; virtual ossimObject* dup() const { ossimTiledElevationDatabase* duped = new ossimTiledElevationDatabase; duped->open(m_connectionString); return duped; } protected: /** Protected destructor as this is derived from ossimRefenced. */ virtual ~ossimTiledElevationDatabase(); private: // Private container to hold bounding rect and image handler. struct ossimTiledElevationEntry { /** @brief default constructor */ ossimTiledElevationEntry(); /** @brif Constructor that takes rectangle and chain. */ ossimTiledElevationEntry(const ossimGrect& rect, ossimRefPtr sic ); /** Bounding rectangle in decimal degrees. */ ossimGrect m_rect; /** Hold pointer to single image chain. */ ossimRefPtr m_sic; }; /** * @brief adds entry to the list checking for duplicates. */ void addEntry(const ossimTiledElevationEntry& entry); /** * @brief Initializes m_referenceProj from the first entry. */ void initializeReferenceProjection(); /** * @return true if file is a directory based image and the stager should go * on to next directory; false if stager should continue with directory. */ bool isDirectoryBasedImage(ossimRefPtr ih); /** * @brief Check for match of the following against the first entry of: * bands, projection, scalar type and scale. * @returns true if good, false if not the same. */ bool isCompatible(ossimImageHandler* ih, ossimImageGeometry* geom, ossimProjection* proj) const; /** * @brief Initialize bounding rectangle from image handler. * * Sets boundingRect to nan if ossimImageGeometry::getCornerGpts returns false. * * @param ih Image handler. * @param boundingRect Initialized by method. */ void getBoundingRect(ossimRefPtr geom, ossimGrect& boundingRect) const; /** @brief Loads m_requestedRect into m_grid from m_entries. */ void mapRegion(); /** @brief Templated fill grid method. */ template void fillGrid(T dummyTemplate, ossimRefPtr data); /** Hidden from use copy constructor */ ossimTiledElevationDatabase(const ossimTiledElevationDatabase& copy_this); std::vector m_entries; /** Hold region of elevation. */ ossimDblGrid* m_grid; /** Projection of the first entry. Stored for convenience. */ ossimRefPtr m_referenceProj; ossimGrect m_requestedRect; ossimGrect m_entryListRect; ossimGrect m_mappedRect; // Requested expanded to even post boundary. ossimFileWalker* m_fileWalker; TYPE_DATA }; #endif /* ossimTiledElevationDatabase_HEADER */ ossim-Miami-2.9.1/include/ossim/font/000077500000000000000000000000001352751253100174365ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/font/ossimFont.h000066400000000000000000000227221352751253100215750ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: // //******************************************************************** // $Id: ossimFont.h 17106 2010-04-15 19:12:59Z dburken $ #ifndef ossimFont_HEADER #define ossimFont_HEADER #include #include #include #include #include #include #include #include #include #define OSSIM_FONT_DEFAULT_SIZE_X 12 #define OSSIM_FONT_DEFAULT_SIZE_Y 12 class ossimFont : public ossimObject, public ossimErrorStatusInterface { public: ossimFont() :theStringToRasterize(""), theFamilyName(""), theStyleName(""), theRotation(0), theHorizontalShear(0.0), theVerticalShear(0.0), theHorizontalScale(1.0), theVerticalScale(1.0), theHorizontalPixelSize(8), theVerticalPixelSize(8), theHorizontalDeviceUnits(72), theVerticalDeviceUnits(72), theAffineTransform(2,2) { theAffineTransform << 1.0 << 0.0 << 0.0 << 1.0; } ossimFont(const ossimString& familyName, const ossimString& styleName, int horizontalPixelSize, int verticalPixelSize, int horizontalDeviceUnits=72,// 72 dpi is default, int verticalDeviceUnits=72)// 72 dpi is default :theStringToRasterize(""), theFamilyName(familyName), theStyleName(styleName), theRotation(0), theHorizontalShear(0.0), theVerticalShear(0.0), theHorizontalScale(1.0), theVerticalScale(1.0), theHorizontalPixelSize(horizontalPixelSize), theVerticalPixelSize(verticalPixelSize), theHorizontalDeviceUnits(horizontalDeviceUnits), theVerticalDeviceUnits(verticalDeviceUnits), theAffineTransform(2,2) { theAffineTransform << 1.0 << 0.0 << 0.0 << 1.0; } ossimFont(const ossimFont& rhs) { theStringToRasterize = rhs.theStringToRasterize; theFamilyName = rhs.theFamilyName; theStyleName = rhs.theStyleName; theRotation = rhs.theRotation; theHorizontalShear = rhs.theHorizontalShear; theVerticalShear = rhs.theVerticalShear; theHorizontalScale = rhs.theHorizontalScale; theVerticalScale = rhs.theVerticalScale; theHorizontalPixelSize = rhs.theHorizontalPixelSize; theHorizontalDeviceUnits = rhs.theHorizontalDeviceUnits; theVerticalDeviceUnits = rhs.theVerticalDeviceUnits; theAffineTransform = rhs.theAffineTransform; theClippingBox = rhs.theClippingBox; theLocalOrigin = rhs.theLocalOrigin; theAffineTransform = rhs.theAffineTransform; } virtual ossimObject* dup()const=0; /*! * Returns true if this font is a fixed size font */ virtual bool isFixed()const=0; /*! * You can get a list of fixed sizes supported by * this font. */ virtual void getFixedSizes(std::vector& sizes)const=0; /*! * Will return the previously rasterized buffer. */ virtual const ossim_uint8* getBuf()const=0; /*! * Will return an internal buffer for rasterizing and will * also set the width, and height arguments of the returned buffer. */ virtual const ossim_uint8* rasterize()=0; virtual const ossim_uint8* rasterize(const ossimString& s) { setString(s); return rasterize(); } virtual void setString(const ossimString& s) { theStringToRasterize = s; } /*! * Will return the bounding box of the last string that was set * to be rasterized in pixel space */ virtual void getBoundingBox(ossimIrect& box)=0; /*! * Specifies if its helvetica, times new roman ... etc. */ virtual ossimString getFamilyName()const { return theFamilyName; } /*! * Specifies if its bold or italic .. etc */ virtual ossimString getStyleName()const { return theStyleName; } /*! * Allow us to rotate a font. */ virtual void setRotation(double rotationInDegrees); virtual double getRotation()const { return theRotation; } virtual void getRotation(double& rotation)const { rotation = theRotation; } virtual void setHorizontalVerticalShear(double horizontalShear, double verticalShear) { theVerticalShear = verticalShear; theHorizontalShear = horizontalShear; computeMatrix(); } virtual void setVerticalShear(double verticalShear) { setHorizontalVerticalShear(theHorizontalShear, verticalShear); } virtual void setHorizontalShear(double horizontalShear) { setHorizontalVerticalShear(horizontalShear, theVerticalShear); } virtual double getVerticalShear()const { return theVerticalShear; } virtual double getHorizontalShear()const { return theHorizontalShear; } /*! * Sets the scale of the font. I'll have code in place to perform * reflections. This can be specified with a - scale along the direction * you wish to reflect. */ virtual void setScale(double horizontal, double vertical); virtual void getScale(double& horizontal, double& vertical) { horizontal = theHorizontalScale; vertical = theVerticalScale; } virtual void setPixelSize(int horizontalPixelSize, int verticalPixelSize) { theHorizontalPixelSize = horizontalPixelSize; theVerticalPixelSize = verticalPixelSize; } virtual void setPixelSize(int pixelSize) { setPixelSize(pixelSize, pixelSize); } virtual void getPixelSize(int& horizontal, int& vertical) { horizontal = theHorizontalPixelSize; vertical = theVerticalPixelSize; } virtual long getHorizontalPixelSize()const { return theHorizontalPixelSize; } virtual ossimIpt getPixelSize()const { return ossimIpt(theHorizontalPixelSize, theVerticalPixelSize); } virtual long getVerticalPixelSize()const { return theVerticalPixelSize; } virtual void setDeviceDpi(int horizontalDeviceUnits, int verticalDeviceUnits) { theHorizontalDeviceUnits = horizontalDeviceUnits; theVerticalDeviceUnits = verticalDeviceUnits; } /*! * Will clip the clipping box with the bounding box of the string and this * is the viewable information. * * If the clipping box is set then this should be used to get the dimensions * of the buffer. */ virtual void getBufferRect(ossimIrect& bufRect) { getBoundingClipBox(bufRect); } virtual ossimIrect getBufferRect() { return getBoundingClipBox(); } virtual void getBoundingClipBox(ossimIrect& clippedBox); virtual ossimIrect getBoundingClipBox(); virtual void setClippingBox(const ossimIrect& clipBox=ossimIrect(0,0,0,0)) { theClippingBox = clipBox; } virtual ossimIrect getClippingBox()const { return theClippingBox; } bool isIdentityTransform()const { return ( (theAffineTransform[0][0] == 1.0) && (theAffineTransform[1][0] == 0.0)&& (theAffineTransform[0][1] == 0.0) && (theAffineTransform[1][1] == 1.0)); } virtual void getFontInformation(std::vector& fontInformationList)const { fontInformationList.push_back(ossimFontInformation(getFamilyName(), getStyleName(), getPixelSize(), isFixed())); } protected: virtual ~ossimFont() {} ossimString theStringToRasterize; ossimString theFamilyName; ossimString theStyleName; double theRotation; double theHorizontalShear; double theVerticalShear; double theHorizontalScale; double theVerticalScale; int theHorizontalPixelSize; int theVerticalPixelSize; int theHorizontalDeviceUnits; int theVerticalDeviceUnits; ossimIrect theClippingBox; /*! * During the compution of the global bounding rect we will * Make sure that we save off the upper left since its not really 0,0. * We will make sure that the bounding rect is shifted to 0,0 but the * shift will be saved. That way we can render the shape correctly * later. */ mutable ossimIpt theLocalOrigin; NEWMAT::Matrix theAffineTransform; void computeMatrix(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/font/ossimFontFactoryBase.h000066400000000000000000000022241352751253100237130ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimFontFactoryBase.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimFontFactoryBase_HEADER #define ossimFontFactoryBase_HEADER #include #include #include class ossimFont; class ossimFontFactoryBase { public: virtual ~ossimFontFactoryBase(){} /*! * Will find the best font for the passed in infromation. * If none is found a default font should be returned. */ virtual ossimFont* createFont(const ossimFontInformation& information)const=0; /*! * Usually for trutype fonts but any font stored in a file it * will try to create a font from it. */ virtual ossimFont* createFont(const ossimFilename& file)const=0; virtual void getFontInformation(std::vector& informationList)const=0; }; #endif ossim-Miami-2.9.1/include/ossim/font/ossimFontFactoryRegistry.h000066400000000000000000000042721352751253100246560ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: // //******************************************************************** // $Id: ossimFontFactoryRegistry.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimFontFactoryRegistry_HEADER #define ossimFontFactoryRegistry_HEADER #include #include #include #include #include #include class OSSIMDLLEXPORT ossimFontFactoryRegistry { public: static ossimFontFactoryRegistry* instance(); bool registerFactory(ossimFontFactoryBase* factory); void unregisterFactory(ossimFontFactoryBase* factory); bool findFactory(ossimFontFactoryBase* factory)const; ossimFont* createFont(const ossimFontInformation& information)const; ossimFont* createFont(const ossimFilename& file)const; /*! * Returns all font information. */ void getFontInformation(std::vector& informationList)const; /*! * Matches the entire string. Does a case insensitive match. */ void getFontInformationFamilyName(std::vector& informationList, const ossimString& familyName)const; /*! * Matches the sub-string. Does a case insensitive match. */ void getFontInformationContainingFamilyName(std::vector& informationList, const ossimString& familyName)const; /*! * This font should not be deleted. It returns the default font. If you * want to make a copy then just call the dup method on * font. */ ossimFont* getDefaultFont()const; protected: mutable ossimRefPtr theDefaultFont; //static ossimFontFactoryRegistry* theInstance; std::vector theFactoryList; ossimFontFactoryRegistry(); private: ossimFontFactoryRegistry(const ossimFontFactoryRegistry& rhs); void operator =(const ossimFontFactoryRegistry& rhs); }; #endif ossim-Miami-2.9.1/include/ossim/font/ossimFreeTypeFont.h000066400000000000000000000124141352751253100232360ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimFreeTypeFont.h 21749 2012-09-18 14:06:13Z dburken $ #ifndef ossimFreeTypeFont_HEADER #define ossimFreeTypeFont_HEADER #include /* To pick up OSSIM_HAS_FREETYPE. */ #if OSSIM_HAS_FREETYPE # include # include # include FT_FREETYPE_H //#include # include FT_MODULE_H // for FT_Done_Library # include FT_GLYPH_H # include "ossim/base/ossimFilename.h" typedef struct TGlyph_ { FT_UInt glyph_index; /* glyph index in face */ FT_Vector pos; /* position of glyph origin */ FT_Glyph image; /* glyph image */ } TGlyph, *PGlyph; class ossimFreeTypeFont: public ossimFont { public: ossimFreeTypeFont(const ossimFilename& fontFile); ossimFreeTypeFont(const ossimFreeTypeFont& rhs); virtual ossimObject* dup()const { return new ossimFreeTypeFont(*this); } virtual const ossim_uint8* getBuf()const { return theOutputBuffer; } void layoutGlyphs(std::vector& glyphs, const ossimString& s ); virtual const ossim_uint8* rasterize(); void getBoundingBox(ossimIrect& box); long getNumberOfFaces()const { if(theFontFace) { return theFontFace->num_faces; } return 0; } void setCurrentFace(long index); /*! * Fonts found in files .FNT and .PCF are fixed */ bool isFixed()const { if(theFontFace) { return (theFontFace->num_fixed_sizes > 0); } return false; } virtual void getFixedSizes(std::vector& sizeArray)const; /*! * Will enable kerning support. This is enabled * by default. This is for true type fonts and * if its available for the current font this * will tell us to make sure we use it. This * adjusts spacing between pairs of glyphs. */ virtual void enableKerningSupport() { theKerningEnabledFlag = true; theBoundingRectIsValid = false; } /*! * Will disable kerning support. */ virtual void disableKerningSupport() { theKerningEnabledFlag = false; theBoundingRectIsValid = false; } virtual void setHorizontalVerticalShear(double horizontalShear, double verticalShear) { ossimFont::setHorizontalVerticalShear(horizontalShear, verticalShear); theBoundingRectIsValid = false; } virtual void setScale(double horizontal, double vertical) { ossimFont::setScale(horizontal, vertical); theBoundingRectIsValid = false; } virtual void setPixelSize(int horizontalPixelSize, int verticalPixelSize) { ossimFont::setPixelSize(horizontalPixelSize, verticalPixelSize); theBoundingRectIsValid = false; } virtual void setPixelSize(int pixelSize) { ossimFont::setPixelSize(pixelSize); theBoundingRectIsValid = false; } virtual void setDeviceDpi(int horizontalDeviceUnits, int verticalDeviceUnits) { ossimFont::setDeviceDpi(horizontalDeviceUnits, verticalDeviceUnits); theBoundingRectIsValid = false; } virtual void setString(const ossimString& s) { ossimFont::setString(s); theBoundingRectIsValid = false; theNeedToLayoutGlyphsFlag = true; } const FT_Face getFontFace()const { return theFontFace; } protected: virtual ~ossimFreeTypeFont(); FT_Face theFontFace; FT_Library theLibrary; FT_Matrix theMatrix; ossimFilename theFontFile; ossim_uint8* theOutputBuffer; long theBufferSize; bool theKerningEnabledFlag; bool theNeedToLayoutGlyphsFlag; FT_Vector theStringCenter; ossimIpt theShift; /*! * Pre-compute all glyphs but don't render it */ std::vector theStringLayout; /*! * We will precompute the bounding rect only when we have to. * this will avoid re-computing on all rasterization calls. We * will use the dirty flag to tell us if we need to re-compute. */ mutable ossimIrect thePrecomputedBoundingRect; /*! * Used to tell us when we need to recompute. */ mutable bool theBoundingRectIsValid; void layoutGlyphs(const ossimString& s); void setBaseClassInformation(); void setupForRasterization(); void allocateBuffer(); void drawBitmap(FT_Bitmap* bitmap, const ossimIrect& bufRect, const ossimIrect& glyphBox); void computeGlyphBox(FT_Glyph, ossimIrect& box)const; void deleteGlyphs(std::vector& glyphs); TYPE_DATA }; #endif #endif ossim-Miami-2.9.1/include/ossim/font/ossimFreeTypeFontFactory.h000066400000000000000000000030051352751253100245620ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimFreeTypeFontFactory.h 17108 2010-04-15 21:08:06Z dburken $ #ifndef ossimFreeTypeFontFactory_HEADER #define ossimFreeTypeFontFactory_HEADER #include class ossimFreeTypeFontInformation { public: ossimFreeTypeFontInformation(const ossimFilename& file, const ossimFontInformation& info) :theFilename(file), theFontInformation(info) {} ossimFilename theFilename; ossimFontInformation theFontInformation; }; class ossimFreeTypeFontFactory : public ossimFontFactoryBase { public: virtual ~ossimFreeTypeFontFactory(); static ossimFreeTypeFontFactory* instance(); virtual ossimFont* createFont(const ossimFontInformation& information)const; virtual ossimFont* createFont(const ossimFilename& file)const; virtual void getFontInformation(std::vector& informationList)const; bool addFile(const ossimFilename& file); protected: ossimFreeTypeFontFactory(); static ossimFreeTypeFontFactory* theInstance; std::vector theFontInformationList; void initializeDefaults(); private: ossimFreeTypeFontFactory(const ossimFreeTypeFontFactory& /*rhs*/){} void operator =(const ossimFreeTypeFontFactory& /*rhs*/){} }; #endif ossim-Miami-2.9.1/include/ossim/font/ossimGdBitmapFont.h000066400000000000000000000042051352751253100232010ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //******************************************************************** // $Id: ossimGdBitmapFont.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimGdBitmapFont_HEADER #define ossimGdBitmapFont_HEADER #include struct ossimGdFont { /* # of characters in font */ int nchars; /* First character is numbered... (usually 32 = space) */ int offset; /* Character width and height */ int w; int h; /* Font data; array of characters, one row after another. Easily included in code, also easily loaded from data files. */ char *data; }; typedef ossimGdFont* ossimGdFontPtr; /*! * This is a wrapper for the gd library fonts. * Note that this class will currently only support scaling. It will not support * any other affine operation. */ class ossimGdBitmapFont : public ossimFont { public: ossimGdBitmapFont(const ossimString& familyName, const ossimString& styleName, const ossimGdFont* gdFontPtr); ossimGdBitmapFont(const ossimGdBitmapFont& rhs); virtual ~ossimGdBitmapFont(); virtual ossimObject* dup()const { return new ossimGdBitmapFont(*this); } virtual const ossim_uint8* getBuf()const { return theOutputBuffer; } /*! * Will return an internal buffer for rasterizing and will */ virtual const ossim_uint8* rasterize(); virtual void getBoundingBox(ossimIrect& box); bool isFixed()const { return true; } virtual void getFixedSizes(std::vector& sizes)const; protected: const ossimGdFont* theGdFontPtr; long theBufferSize; ossim_uint8* theOutputBuffer; /*! * This will take into consideration the point size along * the horizontal and vertical and also the scale * values. So the actual scale will be: * * Scale*(pointSize/fixedSize); */ void getActualScale(ossimDpt& scales)const; void rasterizeNormal(); void allocateBuffer(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/font/ossimGdSansBold.inc000066400000000000000000003423311352751253100231720ustar00rootroot00000000000000 /* This is a header file for gd font, generated using bdftogd version 0.51 by Jan Pazdziora, adelton@fi.muni.cz from bdf font -Misc-Fixed-Bold-R-Normal-Sans-15-140-75-75-C-90-ISO8859-2 at Mon Jan 26 14:45:58 1998. The original bdf was holding following copyright: "Libor Skarvada, libor@informatics.muni.cz" */ #include "ossimGdBitmapFont.h" char ossimGdSansBoldData[] = { /* Char 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 1 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 2 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, /* Char 3 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 4 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 5 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 6 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 7 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 8 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 9 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 10 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 11 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 12 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 13 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 14 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 15 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 17 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 18 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 19 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 20 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 21 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 22 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 23 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 24 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 25 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 26 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 27 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 28 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 29 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 30 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 31 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 33 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 34 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 35 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 36 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 37 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 38 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 39 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 40 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 41 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 42 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 43 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 44 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 45 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 46 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 47 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 49 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 50 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 51 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 52 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 53 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 54 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 55 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 56 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 57 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 58 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 59 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 60 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 61 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 62 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 63 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 64 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 65 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 66 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 67 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 68 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 69 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 70 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 71 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 72 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 73 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 74 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 75 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 76 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 77 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 78 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 79 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 81 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 82 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 83 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 84 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 85 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 86 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 87 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 88 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 89 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 90 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 91 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 92 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 93 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 94 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 95 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 96 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 97 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 98 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 99 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 100 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 101 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 102 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 103 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, /* Char 104 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 105 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 106 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, /* Char 107 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 108 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 109 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 110 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 111 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 112 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 113 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 114 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 115 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 116 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 117 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 118 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 119 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 120 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 121 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, /* Char 122 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 123 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 124 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 125 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 126 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 127 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 129 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 130 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 131 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 132 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 133 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 134 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 135 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 136 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 137 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 138 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 139 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 140 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 141 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 142 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 143 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 145 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 146 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 147 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 148 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 149 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 150 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 151 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 152 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 153 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 154 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 155 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 156 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 157 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 158 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 159 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 161 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 162 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 163 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 164 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 165 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 166 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 167 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 168 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 169 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 170 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, /* Char 171 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 172 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 173 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 174 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 175 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 177 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, /* Char 178 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, /* Char 179 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 180 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 181 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 182 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 183 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 184 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 185 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 186 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, /* Char 187 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 188 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 189 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 190 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 191 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 192 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 193 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 194 */ 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 195 */ 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 196 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 197 */ 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 198 */ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 199 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 200 */ 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 201 */ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 202 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, /* Char 203 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 204 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 205 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 206 */ 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 207 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 209 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 210 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 211 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 212 */ 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 213 */ 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 214 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 215 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 216 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 217 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 218 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 219 */ 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 220 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 221 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 222 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 223 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 225 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 226 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 227 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 228 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 229 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 230 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 231 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 232 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 233 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 234 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, /* Char 235 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 236 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 237 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 238 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 239 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 241 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 242 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 243 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 244 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 245 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 246 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 247 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 248 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 249 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 250 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 251 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 252 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 253 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, /* Char 254 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 255 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; ossimGdFont ossimGdSansBoldRep = { 256, 0, 9, 15, ossimGdSansBoldData }; ossimGdFontPtr ossimGdSansBold = &ossimGdSansBoldRep; /* This file has not been truncated. */ ossim-Miami-2.9.1/include/ossim/hdf5/000077500000000000000000000000001352751253100173165ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/hdf5/ossimHdf5.h000066400000000000000000000117641352751253100213410ustar00rootroot00000000000000/***************************************************************************** * * * O S S I M * * Open Source, Geospatial Image Processing Project * * License: MIT, see LICENSE at the top-level directory * * * ******************************************************************************/ #ifndef ossimHdf5_HEADER #define ossimHdf5_HEADER 1 #include #include #include #include #include #include #include #include #include /** * Low-level OSSIM interface to HDF5 libraries. Catches HDF5 exceptions on common operations. * Note, all methods return by value as that is the way HDF5 returns objects. This seems very * inefficient, particularly for large datasets. Hopefully they are shallow copies. */ class OSSIM_DLL ossimHdf5 : public ossimReferenced { public: ossimHdf5(); ~ossimHdf5(); /** Opens specified HDF5 file. */ bool open(const ossimFilename& hdf5File); bool isOpen() const { return (m_h5File != NULL); } /** Closes the file and deletes all pointers. * @return True if close successful. */ bool close(); /** Assigns the root group. * @return True if result valid */ bool getRoot(H5::Group& root) const; /** Assigns list of groups under specified group. * @param recursive If true, recursively visits all subgroups * @return True if result valid */ static bool getChildGroups(H5::Group group, std::vector& groupList, bool recursive=false); /** Assigns list of datasets under specified group. * @param recursive If true, recursively visits all datasets for this group and subgroups * @return True if result valid */ static bool getDatasets(H5::Group group, std::vector& datasetList, bool recursive=false); /** Assigns list of all multi-dimensional datasets under current active group. * @param recursive If true, recursively visits all datasets for this group and subgroups * @return True if result valid */ static bool getNdimDatasets(H5::Group group, std::vector& datasetList, bool recursive=false); /** * @param objPath Either relative or absolute path in file to object. * @return True if result valid */ static bool getAttributes(const H5::H5Object& obj, std::vector& attrList); /** Finds a group by name. The first object with specified name (can be relative path -- a * naive string comparison is performed) under the specified parent group is returned. * @param group If null, implies root group. * @param recursive If true, recursively visits all subgroups. * @return result Set to valid dataset object if found (caller assumes ownership), else NULL. */ H5::Group* findGroupByName(const std::string& group_name, const H5::Group* parent_group=0, bool recursive=false)const; /** Finds a dataset by name. The first object with specified name (can be relative path -- a * naive string comparison is performed) under the specified group is returned. * @param group If null, implies root group. * @param recursive If true, recursively visits all subgroups. * @return result Set to valid dataset object if found (caller assumes ownership), else NULL. * The return value must be deleted by the caller */ H5::DataSet* findDatasetByName(const std::string& dataset_name, const H5::Group* group=0, bool recursive=false)const ; static ossimByteOrder getByteOrder( const H5::AbstractDs* obj ); static ossimByteOrder getByteOrder( const H5::AtomType& obj ); static std::string getDatatypeClassType( ossim_int32 type ); static void getExtents( const H5::DataSet& dataset, std::vector& extents ); static ossimScalarType getScalarType( const H5::DataSet& dataset ); static ossimScalarType getScalarType( const H5::DataType& datatype ); static bool floatTypeToString(std::string& result, const H5::FloatType& dataType, const char* dataPtr); static bool intTypeToString(std::string& result, const H5::IntType& dataType, const char* dataPtr); static bool stringTypeToString(std::string& result, const H5::StrType& dataType, const char* dataPtr); private: ossimFilename m_filename; H5::H5File* m_h5File; }; #endif /* #ifndef ossimHdf5_HEADER */ ossim-Miami-2.9.1/include/ossim/hdf5/ossimHdf5GridModel.h000066400000000000000000000037461352751253100231310ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimHdf5GridModel.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: David Burken // // Copied from Mingjie Su's ossimHdfGridModel. // // DESCRIPTION: // Contains declaration of class ossimHdfGridModel. This is an // implementation of an interpolation sensor model. // //***************************************************************************** // $Id$ #ifndef ossimHdf5GridModel_HEADER #define ossimHdf5GridModel_HEADER 1 #include #include #include #include #include #include /****************************************************************************** * * CLASS: ossimHdf5GridModel * *****************************************************************************/ class OSSIM_DLL ossimHdf5GridModel : public ossimCoarseGridModel { public: /** @brief default constructor. */ ossimHdf5GridModel(); /** @brief virtual destructor */ virtual ~ossimHdf5GridModel(); /** Initializes from an open HDF5 file */ bool initialize(ossimHdf5* hdf5, const ossimString& projDataPath=""); /** Makes sure that the "type" keyword entry reflects the base class, not this one. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix) const; protected: bool initCoarseGrid(const char* datasetName, ossimDblGrid& coarseGrid); bool crossesDateline(); // This polygon differs from base "theBoundGndPolygon" in that if the // scene crosses the dateline the longitude values are stored between // 0 and 360 degress as opposed to -180 to 180. ossimPolygon m_boundGndPolygon; ossimRefPtr m_hdf5; ossimIpt m_imageSize; ossimString m_projDataPath; TYPE_DATA }; #endif /* Matches: #ifndef ossimHdf5GridModel_HEADER */ ossim-Miami-2.9.1/include/ossim/hdf5/ossimHdf5ImageDataset.h000066400000000000000000000106141352751253100236030ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: OSSIM HDF5 Image DataSet. // //---------------------------------------------------------------------------- // $Id #ifndef ossimHdf5ImageDataset_HEADER #define ossimHdf5ImageDataset_HEADER 1 #include #include #include #include #include #include #include // Forward class declarations: class ossimImageData; class ossimEndian; class ossimIpt; class ossimIrect; class ossimHdf5ImageHandler; /** * @brief Class encapsulates a HDF5 Data set that can be loaded as an image. */ class OSSIM_DLL ossimHdf5ImageDataset : public ossimReferenced { public: /** default constructor */ ossimHdf5ImageDataset(ossimHdf5ImageHandler* owner=0); /** copy constructor */ ossimHdf5ImageDataset( const ossimHdf5ImageDataset& obj ); /** destructor */ ~ossimHdf5ImageDataset(); /** @brief Calls H5::DataSet::close then deletes data set. */ void close(); const ossimHdf5ImageDataset& operator=( const ossimHdf5ImageDataset& rhs ); /** * @brief Opens datasetName and initializes all data members on success. * @return true on success, false on error. */ bool initialize( const H5::DataSet& dataset); /** * @brief Get const pointer to dataset. * * This can be null if not open. * * @return const pointer to dataset. */ const H5::DataSet* getDataset() const; /** * @brief Get pointer to dataset. * * This can be null if not open. * * @return pointer to dataset. */ H5::DataSet* getDataset(); /** @return The dataset name. This is the full path used for open. */ std::string getName() const; /** @return The output scalar type. */ ossimScalarType getScalarType() const; /** @return the number of . */ ossim_uint32 getNumberOfBands() const; /** @return The number of lines. */ ossim_uint32 getNumberOfLines() const; /** @return The number of samples. */ ossim_uint32 getNumberOfSamples() const; /** @return The swap flag. */ bool getSwapFlag() const; const ossimIpt& getSubImageOffset() const; const ossimIrect& getValidImageRect() const; double getMaxPixelValue(ossim_uint32 band=0) const; double getMinPixelValue(ossim_uint32 band=0) const; bool isMinPixelSet()const; bool isMaxPixelSet()const; /** * @brief Method to grab a tile(rectangle) from image. * * @param buffer Buffer for data for this method to copy data to. * Should be the size of rect * bytes_per_pixel for scalar type. * * @param rect The zero based rectangle to grab. Rectangle is relative to * any sub image offset. E.g. A request for 0,0 is the upper left corner * of the valid image rect. * * @param scale If true, uses min and max to stretch the data to a UINT16 range. */ void getTileBuf(void* buffer, const ossimIrect& rect, ossim_uint32 band, bool scale=true); /** * @brief print method. * @return std::ostream& */ std::ostream& print(std::ostream& out) const; friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& out, const ossimHdf5ImageDataset& obj); private: /** Returns true if datasets's endianness differs from this platform */ bool determineExtents(); bool scanForValidImageRect(); bool determineScalarType(); bool scanForMinMax(); ossimRefPtr m_handler; ossimRefPtr m_hdf5; H5::DataSet m_dataset; H5::DataSpace m_dataSpace; ossimScalarType m_scalar; ossim_uint32 m_bands; ossim_uint32 m_lines; ossim_uint32 m_samples; ossimEndian* m_endian; // For byte swapping if needed. std::vector m_minValue; std::vector m_maxValue; /** H5 data can have null rows on the front or end. The valid rect is the scanned rectangle * disregarding leading or trailing nulls. This doesn't handle nulls in the middle of image. */ ossimIrect m_validRect; // image rect offset relative to full image }; // End: class ossimH5ImageDataset #endif /* #ifndef ossimH5ImageDataset_HEADER */ ossim-Miami-2.9.1/include/ossim/hdf5/ossimHdf5ImageHandler.h000066400000000000000000000177331352751253100236040ustar00rootroot00000000000000/***************************************************************************** * * * O S S I M * * Open Source, Geospatial Image Processing Project * * License: MIT, see LICENSE at the top-level directory * * * *****************************************************************************/ #ifndef ossimHdf5ImageHandler_HEADER #define ossimHdf5ImageHandler_HEADER 1 #include #include #include #include #include #include #include #include #include /** * This is the base class for all imagery using HDF5 as the file format. HDF5 is unique in that it * represents a variety of subformats for raster and projection information. The derived classes * will need to specify the group and dataset names where the needed data lives. */ class OSSIM_DLL ossimHdf5ImageHandler : public ossimImageHandler { friend class ossimHdf5ImageDataset; public: /** default constructor */ ossimHdf5ImageHandler(); /** virtual destructor */ virtual ~ossimHdf5ImageHandler(); /** @return "hdf5" */ virtual ossimString getShortName() const; /** @return "ossim hdf5" */ virtual ossimString getLongName() const; /** @return "ossimH5Reader" */ virtual ossimString getClassName() const; /** * Returns a pointer to a tile given an origin representing the upper * left corner of the tile to grab from the image. * Satisfies pure virtual from TileSource class. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Returns the number of bands in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; /** * Returns the number of bands in a tile returned from this TileSource. * Note: we are supporting sources that can have multiple data objects. * If you want to know the scalar type of an object you can pass in the */ virtual ossim_uint32 getNumberOfOutputBands()const; /** * Returns the number of lines in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; /** * Returns the number of samples in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; /** * Returns the zero based image rectangle for the reduced resolution data * set (rrds) passed in. Note that rrds 0 is the highest resolution rrds. */ virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; virtual bool isOpen() const; /** Close method. */ virtual void close(); virtual void loadMetaData(); /** * @return The number of entries (images) in the image file. */ virtual ossim_uint32 getNumberOfEntries()const; /** * @brief Get the name of entry as a string. * * Example given from HDF5 file: * * entry_name: /All_Data/VIIRS-IMG-GTM-EDR-GEO_All/QF1_VIIRSGTMGEO * * @param entryIdx Zero based entry index. If out of range name will * be cleared. * * @param name Initialized by this. */ virtual void getEntryNames(std::vector& entryNames) const; /** * @param entryList This is the list to initialize with entry indexes. * * @note This implementation returns puts one entry "0" in the list. */ virtual void getEntryList(std::vector& entryList) const; virtual bool setCurrentEntry(ossim_uint32 entryIdx); /** * @return The current entry number. */ virtual ossim_uint32 getCurrentEntry() const; ossimRefPtr getCurrentDataset(); /** @return Null pixel value. */ virtual double getNullPixelValue(ossim_uint32 band=0) const; virtual double getMaxPixelValue(ossim_uint32 band=0) const; virtual double getMinPixelValue(ossim_uint32 band=0) const; /** * @brief Set propterty method. Overrides ossimImageHandler::setProperty. * * Current property name handled: * "scale" One double value representing the scale in meters per pixel. It is * assumed the scale is same for x and y direction. * * @param property to set. */ virtual void setProperty(ossimRefPtr property); /** * @brief Get propterty method. Overrides ossimImageHandler::getProperty. * @param name Property name to get. */ virtual ossimRefPtr getProperty(const ossimString& name) const; /** * @brief Get propterty names. Overrides ossimImageHandler::getPropertyNames. * @param propertyNames Array to initialize. */ virtual void getPropertyNames(std::vector& propertyNames) const; /** The derived class needs to initialize the raster dataset names m_renderableNames in their * constructor, for this method to work. This should be implemented by the derived HDF5-format * readers defined in plugins. * @return true on success, false on error. */ virtual bool open(); const std::vector& getRenderableSetNames() { return m_renderableNames; } /** Adds the dataset name, either the full HDF5 path or the simple object name, to the list of * renderable datasets */ void addRenderable(const ossimString& datasetName) { m_renderableNames.push_back(datasetName); } protected: /** @brief Allocates the tile. */ void allocate(); std::vector m_renderableNames; ossimRefPtr m_hdf5; std::vector > m_entries; ossim_uint32 m_currentEntry; ossimRefPtr m_tile; std::mutex m_mutex; TYPE_DATA }; #endif /* #ifndef ossimH5Reader_HEADER */ ossim-Miami-2.9.1/include/ossim/hdf5/ossimHdf5Info.h000066400000000000000000000121141352751253100221430ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: HDF5 Info class. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimH5Info_HEADER #define ossimH5Info_HEADER 1 #include #include #include #include #include #include #include #include class ossimEndian; /** * @brief TIFF info class. * * Encapsulates the listgeo functionality. */ class OSSIM_DLL ossimHdf5Info : public ossimInfoBase { public: /** default constructor */ ossimHdf5Info(); /** Accepts already opened HDF5 file object. */ ossimHdf5Info(ossimHdf5* hdf5); /** virtual destructor */ virtual ~ossimHdf5Info(); /** * @param file File name to open. * @return true on success false on error. */ virtual bool open(const ossimFilename& file); /** * @param out Stream to print to. * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; virtual bool getKeywordlist(ossimKeywordlist& kwl) const; virtual bool getKeywordlistDataset(ossimKeywordlist& kwl, const std::string& datasetName) const; virtual bool getKeywordlistGroup(ossimKeywordlist& kwl, const std::string& groupName) const; // Methods for printing collections. These are public to enable dumping debug information: std::ostream& printSubGroups (std::ostream& out, const H5::Group& obj, const ossimString& lm=ossimString()) const; std::ostream& printAttributes(std::ostream& out, const H5::H5Object& obj, const ossimString& lm=ossimString()) const; std::ostream& printDatasets (std::ostream& out, const H5::Group& obj, const ossimString& lm=ossimString()) const; // Methods for printing individual objects: std::ostream& print(std::ostream& out, const H5::Group& obj, const ossimString& lm=ossimString()) const; std::ostream& print(std::ostream& out, const H5::DataSet& obj, const ossimString& lm=ossimString()) const; std::ostream& print(std::ostream& out, const H5::DataType& obj, const ossimString& lm=ossimString()) const; std::ostream& print(std::ostream& out, const H5::DataSpace& obj, const ossimString& lm=ossimString()) const; std::ostream& print(std::ostream& out, const H5::Attribute& obj, const ossimString& lm=ossimString()) const; private: void dumpGroup(const H5::Group& group, const std::string& prefix, ossim_uint32& recursedCount) const; void dumpDataset(const H5::DataSet& dataset, const std::string& prefix) const; void dumpCompound(const H5::DataSet& dataset, const H5::CompType& compound, const std::string& prefix)const; void dumpCompoundTypeInfo(const H5::CompType& compound, const std::string& prefix) const; void dumpEnumTypeInfo(H5::EnumType datatype, const std::string& prefix) const; void dumpArrayTypeInfo(H5::ArrayType datatype, const std::string& prefix) const; void dumpNumericalTypeInfo(const H5::DataSet& dataset, ossimByteOrder order, const std::string& prefix) const; void dumpIntType( const H5::IntType& dataType, const char* dataPtr, const std::string& prefix)const; void dumpFloatType(const H5::FloatType& dataType, const char* dataPtr, const std::string& prefix)const; void dumpStringType(const H5::StrType& dataType, const char* dataPtr, const std::string& prefix)const; void dumpArrayType( H5::ArrayType& dataType, const char* dataPtr, const std::string& prefix)const; void dumpNumerical(const H5::DataSet& dataset, const char* dataPtr, const std::string& prefix) const; void dumpStr(const H5::DataSet& dataset, const H5::StrType& dataType, const char* dataPtr, const std::string& prefix) const; void dumpAttributes(const H5::H5Object& container, const std::string& prefix) const; void dumpAttribute(const H5::Attribute& attr, const std::string& prefix) const; bool getGroupAttributeValue(const std::string& group, const std::string& key, std::string& value ) const; bool getDatasetAttributeValue(const std::string& objectName, const std::string& key, std::string& value ) const; ossimString getObjectPrefix(const ossimString& prefix, const ossimString& fullPathName) const; ossimRefPtr m_hdf5; mutable ossimKeywordlist m_kwl; mutable bool m_byteOrder; }; #endif ossim-Miami-2.9.1/include/ossim/hdf5/ossimHdf5ProjectionFactory.h000066400000000000000000000045211352751253100247170ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: MIT // // See LICENSE.txt file in the top level directory for more details. //---------------------------------------------------------------------------- // $Id$ #ifndef ossimH5ProjectionFactory_HEADER #define ossimH5ProjectionFactory_HEADER 1 #include #include class OSSIM_DLL ossimHdf5ProjectionFactory : public ossimProjectionFactoryBase { public: static ossimHdf5ProjectionFactory* instance(); /** * @bief Takes a filename. This filename can be an image file or * it can also be a ossim .geom file. It could be other * forms of geom files as well. The factories job will be to * determine what parser to use and return a projection if * successful. */ virtual ossimProjection* createProjection(const ossimFilename& filename, ossim_uint32 entryIdx)const; /** @brief Take a projection type name. */ virtual ossimProjection* createProjection(const ossimString& name)const; /** @brief Take a keywordlist. */ virtual ossimProjection* createProjection(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual ossimObject* createObject(const ossimString& typeName)const; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual void getTypeNameList(std::vector& typeList)const; /** * Specifies which HDF5 internal paths to search through to locate geometry information. This * can be either explicit dataset names, or group names containing known datasets, such as * "Latitude" and "longitude". The plugins depending on HDF5 should register their geometry * groups here in the same order as image entries. */ void addProjDataPath(const ossimString& projPath) { m_projDataPaths.push_back(projPath); } protected: ossimHdf5ProjectionFactory(); std::vector m_projDataPaths; // List of paths (groups or datasets) containing proj info }; // End: class ossimH5ProjectionFactory{ ... } #endif /* #ifndef ossimH5ProjectionFactory_HEADER */ ossim-Miami-2.9.1/include/ossim/hdf5/ossimHdf5Tool.h000066400000000000000000000043151352751253100221710ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef ossimHdf5Tool_HEADER #define ossimHdf5Tool_HEADER 1 #include #include #include #include #include #include #include // class ossimHdf5; /*! * Class for computing the slope on each elevation post and generatinga corresponding slope image. * The output scalar type is a normalized float unless unsigned 8-bit is selected via the options. */ class OSSIM_DLL ossimHdf5Tool : public ossimChipProcTool { public: ossimHdf5Tool(); ~ossimHdf5Tool(); /** * Initializes the aurgument parser with expected parameters and options. It does not output * anything. To see the usage, the caller will need to do something like: * * ap.getApplicationUsage()->write(); */ virtual void setUsage(ossimArgumentParser& ap); /** * Initializes from command line arguments. * @return FALSE if --help option requested or no params provided, so that derived classes can * @note Throws ossimException on error. */ virtual bool initialize(ossimArgumentParser& ap); /** * Reads processing params from KWL and prepares for execute. Returns TRUE if successful. * @note Throws ossimException on error. */ virtual void initialize(const ossimKeywordlist& kwl); virtual bool execute(); virtual ossimString getClassName() const { return "ossimHdf5Tool"; } /** Used by ossimUtilityFactory */ static const char* DESCRIPTION; protected: virtual void initProcessingChain(); virtual void loadImageFiles(); ossimString m_imageDataPath; ossimString m_geomDataPath; bool m_dumpInfo; bool m_dumpKwl; bool m_listDatasets; bool m_listNdimDatasets; ossimFilename m_geomFilename; ossimRefPtr m_hdf5; }; #endif ossim-Miami-2.9.1/include/ossim/hdf5/ossimViirsHandler.h000066400000000000000000000022141352751253100231330ustar00rootroot00000000000000/***************************************************************************** * * * O S S I M * * Open Source, Geospatial Image Processing Project * * License: MIT, see LICENSE at the top-level directory * * * *****************************************************************************/ #ifndef ossimViirsHandler_HEADER #define ossimViirsHandler_HEADER 1 #include #include #include #include #include /** * Concrete class for reading VIIRS data from HDF5 file */ class OSSIM_DLL ossimViirsHandler : public ossimHdf5ImageHandler { public: ossimViirsHandler(); virtual ossimRefPtr getImageGeometry(); virtual double getNullPixelValue(ossim_uint32 band=0)const; }; #endif /* #ifndef ossimViirsHandler_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/000077500000000000000000000000001352751253100201035ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/imaging/gdfontg.inc000066400000000000000000003423311352751253100222340ustar00rootroot00000000000000 /* This is a header file for gd font, generated using bdftogd version 0.51 by Jan Pazdziora, adelton@fi.muni.cz from bdf font -Misc-Fixed-Bold-R-Normal-Sans-15-140-75-75-C-90-ISO8859-2 at Mon Jan 26 14:45:58 1998. The original bdf was holding following copyright: "Libor Skarvada, libor@informatics.muni.cz" */ #include "ossimGdFont.h" char ossimGdFontGiantData[] = { /* Char 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 1 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 2 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, /* Char 3 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 4 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 5 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 6 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 7 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 8 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 9 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 10 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 11 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 12 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 13 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 14 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 15 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 17 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 18 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 19 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 20 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 21 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 22 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 23 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 24 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 25 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 26 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 27 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 28 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 29 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 30 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 31 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 33 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 34 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 35 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 36 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 37 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 38 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 39 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 40 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 41 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 42 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 43 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 44 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 45 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 46 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 47 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 49 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 50 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 51 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 52 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 53 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 54 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 55 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 56 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 57 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 58 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 59 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 60 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 61 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 62 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 63 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 64 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 65 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 66 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 67 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 68 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 69 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 70 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 71 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 72 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 73 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 74 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 75 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 76 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 77 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 78 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 79 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 81 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 82 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 83 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 84 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 85 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 86 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 87 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 88 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 89 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 90 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 91 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 92 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 93 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 94 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 95 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 96 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 97 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 98 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 99 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 100 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 101 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 102 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 103 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, /* Char 104 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 105 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 106 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, /* Char 107 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 108 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 109 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 110 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 111 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 112 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 113 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 114 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 115 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 116 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 117 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 118 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 119 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 120 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 121 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, /* Char 122 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 123 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 124 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 125 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 126 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 127 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 129 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 130 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 131 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 132 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 133 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 134 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 135 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 136 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 137 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 138 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 139 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 140 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 141 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 142 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 143 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 145 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 146 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 147 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 148 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 149 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 150 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 151 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 152 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 153 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 154 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 155 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 156 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 157 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 158 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 159 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 161 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 162 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 163 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 164 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 165 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 166 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 167 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 168 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 169 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 170 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, /* Char 171 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 172 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 173 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 174 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 175 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 177 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, /* Char 178 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, /* Char 179 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 180 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 181 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 182 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 183 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 184 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 185 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 186 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, /* Char 187 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 188 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 189 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 190 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 191 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 192 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 193 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 194 */ 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 195 */ 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 196 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 197 */ 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 198 */ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 199 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 200 */ 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 201 */ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 202 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, /* Char 203 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 204 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 205 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 206 */ 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 207 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 209 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 210 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 211 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 212 */ 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 213 */ 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 214 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 215 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 216 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 217 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 218 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 219 */ 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 220 */ 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 221 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 222 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 223 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 225 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 226 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 227 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 228 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 229 */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 230 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 231 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 232 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 233 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 234 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, /* Char 235 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 236 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 237 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 238 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 239 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 241 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 242 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 243 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 244 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 245 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 246 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 247 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 248 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 249 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 250 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 251 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 252 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 253 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, /* Char 254 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, /* Char 255 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; ossimGdFont ossimGdFontGiantRep = { 256, 0, 9, 15, ossimGdFontGiantData }; ossimGdFontPtr ossimGdFontGiant = &ossimGdFontGiantRep; /* This file has not been truncated. */ ossim-Miami-2.9.1/include/ossim/imaging/gdfontl.inc000066400000000000000000003307271352751253100222470ustar00rootroot00000000000000 /* This is a header file for gd font, generated using bdftogd version 0.5 by Jan Pazdziora, adelton@fi.muni.cz from bdf font -misc-fixed-medium-r-normal--16-140-75-75-c-80-iso8859-2 at Tue Jan 6 19:39:27 1998. The original bdf was holding following copyright: "Libor Skarvada, libor@informatics.muni.cz" */ #include "ossimGdFont.h" char ossimGdFontLargeData[] = { /* Char 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 1 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 2 */ 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, /* Char 3 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 4 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 5 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 6 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 7 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 8 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 9 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 10 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 11 */ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 12 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 13 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 14 */ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 15 */ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 17 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 18 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 19 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 20 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 21 */ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 22 */ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 23 */ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 24 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 25 */ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 26 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 27 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 28 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 29 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 30 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 31 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 33 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 34 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 35 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 36 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 37 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 38 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 39 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 40 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 41 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 42 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 43 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 44 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 45 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 46 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 47 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 49 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 50 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 51 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 52 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 53 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 54 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 55 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 56 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 57 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 58 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 59 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 60 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 61 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 62 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 63 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 64 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 65 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 66 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 67 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 68 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 69 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 70 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 71 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 72 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 73 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 74 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 75 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 76 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 77 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 78 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 79 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 81 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 82 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 83 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 84 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 85 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 86 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 87 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 88 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 89 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 90 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 91 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 92 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 93 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 94 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 95 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 96 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 97 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 98 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 99 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 100 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 101 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 102 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 103 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, /* Char 104 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 105 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 106 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 107 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 108 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 109 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 110 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 111 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 112 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 113 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, /* Char 114 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 115 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 116 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 117 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 118 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 119 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 120 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 121 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, /* Char 122 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 123 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 124 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 125 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 126 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 127 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 129 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 130 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 131 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 132 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 133 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 134 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 135 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 136 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 137 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 138 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 139 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 140 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 141 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 142 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 143 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 145 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 146 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 147 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 148 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 149 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 150 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 151 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 152 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 153 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 154 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 155 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 156 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 157 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 158 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 159 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 161 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 162 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 163 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 164 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 165 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 166 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 167 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 168 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 169 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 170 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 171 */ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 172 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 173 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 174 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 175 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 177 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 178 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, /* Char 179 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 180 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 181 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 182 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 183 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 184 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, /* Char 185 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 186 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 187 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 188 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 189 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 190 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 191 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 192 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 193 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 194 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 195 */ 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 196 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 197 */ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 198 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 199 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, /* Char 200 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 201 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 202 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 203 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 204 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 205 */ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 206 */ 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 207 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 209 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 210 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 211 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 212 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 213 */ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 214 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 215 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 216 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 217 */ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 218 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 219 */ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 220 */ 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 221 */ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 222 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 223 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 225 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 226 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 227 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 228 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 229 */ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 230 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 231 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, /* Char 232 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 233 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 234 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, /* Char 235 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 236 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 237 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 238 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 239 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 241 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 242 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 243 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 244 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 245 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 246 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 247 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 248 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 249 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 250 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 251 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 252 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 253 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, /* Char 254 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 255 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; ossimGdFont ossimGdFontLargeRep = { 256, 0, 8, 16, ossimGdFontLargeData }; ossimGdFontPtr ossimGdFontLarge = &ossimGdFontLargeRep; /* This file has not been truncated. */ ossim-Miami-2.9.1/include/ossim/imaging/gdfontmb.inc000066400000000000000000002363011352751253100224030ustar00rootroot00000000000000 /* This is a header file for gd font, generated using bdftogd version 0.5 by Jan Pazdziora, adelton@fi.muni.cz from bdf font -misc-fixed-bold-r-normal-sans-13-94-100-100-c-70-iso8859-2 at Thu Jan 8 13:54:57 1998. No copyright info was found in the original bdf. */ #include "ossimGdFont.h" char ossimGdFontMediumBoldData[] = { /* Char 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 1 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 2 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 3 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 4 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 5 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 6 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 7 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 8 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 9 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 10 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 11 */ 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 12 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 13 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 14 */ 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 15 */ 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 17 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 18 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 19 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 20 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 21 */ 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 22 */ 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 23 */ 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 24 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 25 */ 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 26 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 27 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 28 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 29 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 30 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 31 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 33 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 34 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 35 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 36 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 37 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 38 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 39 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 40 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 41 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 42 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 43 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 44 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 45 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 46 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 47 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 49 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 50 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 51 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 52 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 53 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 54 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 55 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 56 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 57 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 58 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 59 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 60 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 61 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 62 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 63 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 64 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 65 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 66 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 67 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 68 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 69 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 70 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 71 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 72 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 73 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 74 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 75 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 76 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 77 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 78 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 79 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 81 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 82 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 83 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 84 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 85 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 86 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 87 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 88 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 89 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 90 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 91 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 92 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 93 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 94 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 95 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 96 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 97 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 98 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 99 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 100 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 101 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 102 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 103 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, /* Char 104 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 105 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 106 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, /* Char 107 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 108 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 109 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 110 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 111 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 112 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, /* Char 113 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 114 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 115 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 116 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 117 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 118 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 119 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 120 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 121 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, /* Char 122 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 123 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 124 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 125 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 126 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 127 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 129 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 130 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 131 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 132 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 133 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 134 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 135 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 136 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 137 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 138 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 139 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 140 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 141 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 142 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 143 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 145 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 146 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 147 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 148 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 149 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 150 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 151 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 152 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 153 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 154 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 155 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 156 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 157 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 158 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 159 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 161 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 162 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 163 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 164 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 165 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 166 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 167 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 168 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 169 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 170 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 171 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 172 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 173 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 174 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 175 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 177 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 178 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, /* Char 179 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 180 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 181 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 182 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 183 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 184 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, /* Char 185 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 186 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 187 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 188 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 189 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 190 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 191 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 192 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 193 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 194 */ 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 195 */ 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 196 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 197 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 198 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 199 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 200 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 201 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 202 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 203 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 204 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 205 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 206 */ 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 207 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 209 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 210 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 211 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 212 */ 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 213 */ 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 214 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 215 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 216 */ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 217 */ 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 218 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 219 */ 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 220 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 221 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 222 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 223 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 225 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 226 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 227 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 228 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 229 */ 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 230 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 231 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 232 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 233 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 234 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, /* Char 235 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 236 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 237 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 238 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 239 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 241 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 242 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 243 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 244 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 245 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 246 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 247 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 248 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 249 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 250 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 251 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 252 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 253 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, /* Char 254 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, /* Char 255 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; ossimGdFont ossimGdFontMediumBoldRep = { 256, 0, 7, 13, ossimGdFontMediumBoldData }; ossimGdFontPtr ossimGdFontMediumBold = &ossimGdFontMediumBoldRep; /* This file has not been truncated. */ ossim-Miami-2.9.1/include/ossim/imaging/gdfonts.inc000066400000000000000000002126611352751253100222520ustar00rootroot00000000000000 /* This is a header file for gd font, generated using bdftogd version 0.5 by Jan Pazdziora, adelton@fi.muni.cz from bdf font -misc-fixed-medium-r-semicondensed-sans-12-116-75-75-c-60-iso8859-2 at Thu Jan 8 14:13:20 1998. No copyright info was found in the original bdf. */ #include "ossimGdFont.h" char ossimGdFontSmallData[] = { /* Char 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 1 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 2 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, /* Char 3 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 4 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 5 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 6 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 7 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 8 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 9 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 10 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 11 */ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 12 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, /* Char 13 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, /* Char 14 */ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 15 */ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, /* Char 16 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 17 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 18 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 19 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 20 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 21 */ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, /* Char 22 */ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, /* Char 23 */ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 24 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, /* Char 25 */ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, /* Char 26 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 27 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 28 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 29 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 30 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 31 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 33 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 34 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 35 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 36 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 37 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 38 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 39 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 40 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 41 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 42 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 43 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 44 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 45 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 46 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 47 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 48 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 49 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 50 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 51 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 52 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 53 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 54 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 55 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 56 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 57 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 58 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 59 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 60 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 61 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 62 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 63 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 64 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 65 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 66 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 67 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 68 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 69 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 70 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 71 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 72 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 73 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 74 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 75 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 76 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 77 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 78 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 79 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 80 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 81 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 82 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 83 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 84 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 85 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 86 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 87 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 88 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 89 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 90 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 91 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 92 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 93 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 94 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 95 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 96 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 97 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 98 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 99 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 100 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 101 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 102 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 103 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, /* Char 104 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 105 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 106 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 107 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 108 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 109 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 110 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 111 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 112 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* Char 113 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, /* Char 114 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 115 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 116 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 117 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 118 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 119 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 120 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 121 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, /* Char 122 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 123 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 124 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 125 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 126 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 127 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 129 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 130 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 131 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 132 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 133 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 134 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 135 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 136 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 137 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 138 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 139 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 140 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 141 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 142 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 143 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 145 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 146 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 147 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 148 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 149 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 150 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 151 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 152 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 153 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 154 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 155 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 156 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 157 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 158 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 159 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 161 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, /* Char 162 */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 163 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 164 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 165 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 166 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 167 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 168 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 169 */ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 170 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 171 */ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 172 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 173 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 174 */ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 175 */ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 176 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 177 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, /* Char 178 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 179 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 180 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 181 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 182 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 183 */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 184 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 185 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 186 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 187 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 188 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 189 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 190 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 191 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 192 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 193 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 194 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 195 */ 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 196 */ 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 197 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 198 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 199 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 200 */ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 201 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 202 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 203 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 204 */ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 205 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 206 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 207 */ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 208 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 209 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 210 */ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 211 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 212 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 213 */ 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 214 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 215 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 216 */ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 217 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 218 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 219 */ 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 220 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 221 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 222 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, /* Char 223 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 224 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 225 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 226 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 227 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 228 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 229 */ 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 230 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 231 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, /* Char 232 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 233 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 234 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 235 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 236 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 237 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 238 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 239 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 240 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 241 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 242 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 243 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 244 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 245 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 246 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 247 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 248 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 249 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 250 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 251 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 252 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 253 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, /* Char 254 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, /* Char 255 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; ossimGdFont ossimGdFontSmallRep = { 256, 0, 6, 13, ossimGdFontSmallData }; ossimGdFontPtr ossimGdFontSmall = &ossimGdFontSmallRep; /* This file has not been truncated. */ ossim-Miami-2.9.1/include/ossim/imaging/gdfontt.inc000066400000000000000000001147131352751253100222520ustar00rootroot00000000000000 /* This is a header file for gd font, generated using bdftogd version 0.5 by Jan Pazdziora, adelton@fi.muni.cz from bdf font -Misc-Fixed-Medium-R-Normal--8-80-75-75-C-50-ISO8859-2 at Thu Jan 8 13:49:54 1998. The original bdf was holding following copyright: "Libor Skarvada, libor@informatics.muni.cz" */ #include "ossimGdFont.h" char ossimGdFontTinyData[] = { /* Char 0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 1 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 2 */ 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, /* Char 3 */ 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, /* Char 4 */ 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, /* Char 5 */ 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, /* Char 6 */ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, /* Char 7 */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 8 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 9 */ 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, /* Char 10 */ 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, /* Char 11 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 12 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, /* Char 13 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, /* Char 14 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 15 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, /* Char 16 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 17 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 18 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 19 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 20 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 21 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, /* Char 22 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, /* Char 23 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 24 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, /* Char 25 */ 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, /* Char 26 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 27 */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 28 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 29 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 30 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 31 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 32 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 33 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 34 */ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 35 */ 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 36 */ 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 37 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, /* Char 38 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, /* Char 39 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 40 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 41 */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 42 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 43 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 44 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 45 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 46 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 47 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 48 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 49 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 50 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 51 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 52 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 53 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 54 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 55 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 56 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 57 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 58 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 59 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, /* Char 60 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 61 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 62 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 63 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 64 */ 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, /* Char 65 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 66 */ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 67 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 68 */ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 69 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 70 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 71 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 72 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 73 */ 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 74 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 75 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 76 */ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 77 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 78 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 79 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 80 */ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 81 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, /* Char 82 */ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 83 */ 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 84 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 85 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 86 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 87 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 88 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 89 */ 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 90 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 91 */ 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 92 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* Char 93 */ 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 94 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 95 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, /* Char 96 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 97 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 98 */ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 99 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 100 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 101 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 102 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 103 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, /* Char 104 */ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 105 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 106 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, /* Char 107 */ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 108 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 109 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* Char 110 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 111 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 112 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, /* Char 113 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, /* Char 114 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 115 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 116 */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 117 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 118 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 119 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 120 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 121 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, /* Char 122 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 123 */ 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 124 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 125 */ 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 126 */ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 127 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 128 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 129 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 130 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 131 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 132 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 133 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 134 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 135 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 136 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 137 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 138 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 139 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 140 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 141 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 142 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 143 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 144 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 145 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 146 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 147 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 148 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 149 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 150 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 151 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 152 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 153 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 154 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 155 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 156 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 157 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 158 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 159 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 160 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 161 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, /* Char 162 */ 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 163 */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* Char 164 */ 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 165 */ 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 166 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 167 */ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, /* Char 168 */ 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 169 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 170 */ 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, /* Char 171 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 172 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 173 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 174 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 175 */ 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 176 */ 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 177 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, /* Char 178 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, /* Char 179 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 180 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 181 */ 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 182 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 183 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 184 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, /* Char 185 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 186 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, /* Char 187 */ 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 188 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 189 */ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 190 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 191 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 192 */ 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 193 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 194 */ 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 195 */ 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 196 */ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 197 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 198 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 199 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, /* Char 200 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 201 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 202 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, /* Char 203 */ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 204 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 205 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 206 */ 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 207 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 208 */ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 209 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 210 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 211 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 212 */ 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 213 */ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 214 */ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 215 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 216 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 217 */ 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 218 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 219 */ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 220 */ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 221 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 222 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, /* Char 223 */ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, /* Char 224 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 225 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 226 */ 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 227 */ 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 228 */ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 229 */ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 230 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 231 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, /* Char 232 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 233 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 234 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, /* Char 235 */ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 236 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 237 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 238 */ 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* Char 239 */ 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 240 */ 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 241 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 242 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 243 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 244 */ 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 245 */ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 246 */ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 247 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* Char 248 */ 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Char 249 */ 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 250 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 251 */ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 252 */ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, /* Char 253 */ 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, /* Char 254 */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, /* Char 255 */ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; ossimGdFont ossimGdFontTinyRep = { 256, 0, 5, 8, ossimGdFontTinyData }; ossimGdFontPtr ossimGdFontTiny = &ossimGdFontTinyRep; /* This file has not been truncated. */ ossim-Miami-2.9.1/include/ossim/imaging/ossim3x3ConvolutionFilter.h000066400000000000000000000057101352751253100253550ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossim3x3ConvolutionFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossim3x3ConvolutionFilter_HEADER #define ossim3x3ConvolutionFilter_HEADER #include class ossim3x3ConvolutionFilter : public ossimImageSourceFilter { public: ossim3x3ConvolutionFilter(ossimObject* owner=NULL); virtual ossimString getShortName()const{return ossimString("3x3 Convolution");} virtual ossimString getLongName()const{return ossimString("Convolves the input image with a 3x3 kernel");} virtual void getKernel(double kernel[3][3]); virtual void setKernel(double kernel[3][3]); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); virtual double getNullPixelValue(ossim_uint32 band=0) const; virtual double getMinPixelValue(ossim_uint32 band=0) const; virtual double getMaxPixelValue(ossim_uint32 band=0) const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; protected: virtual ~ossim3x3ConvolutionFilter(); /** * Allocates theTile. */ void allocate(); /** * Clears data members theNullPixValue, theMinPixValue, and * theMaxPixValue. */ void clearNullMinMax(); /** * Computes null, min, and max considering input connection and theKernel. */ void computeNullMinMax(); ossimRefPtr theTile; double theKernel[3][3]; std::vector theNullPixValue; std::vector theMinPixValue; std::vector theMaxPixValue; /*! * Convolve full means that the input data is full and has * no null data. We don't have to compare for nulls here */ template void convolveFull(T, ossimRefPtr inputData, ossimRefPtr outputData); /*! * Convolve partial means that the input data is has some * null data. We will have to compare nulls */ template void convolvePartial(T, ossimRefPtr inputData, ossimRefPtr outputData); TYPE_DATA }; #endif /* #ifndef ossim3x3ConvolutionFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimAOD.h000066400000000000000000000032131352751253100217310ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Kathy Minear // // Description: // // Class to compute Aerosol Optical Depth (AOD) for with atmospheric // correction. // //************************************************************************* // $Id: ossimAOD.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAOD_HEADER #define ossimAOD_HEADER #include class ossimAOD : public ossimImageSourceFilter { public: ossimAOD(ossimObject* owner=NULL); ossimAOD(ossimImageSource* inputSource); ossimAOD(ossimObject* owner, ossimImageSource* inputSource); virtual ossimString getShortName() const; virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual std::ostream& print(std::ostream& os) const; friend std::ostream& operator << (std::ostream& os, const ossimAOD& hr); static void writeTemplate(std::ostream& os); protected: virtual ~ossimAOD(); void allocate(); /*! * Method to set unset the enable flag. */ void verifyEnabled(); ossimRefPtr theTile; TYPE_DATA }; #endif /* #ifndef ossimAOD_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimAdrgHeader.h000066400000000000000000000073241352751253100233230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero // Description: This class encapsulates the image parameters and // support data for a ADRG image file(s). // //******************************************************************** // $Id: ossimAdrgHeader.h 10266 2007-01-14 19:27:14Z dburken $ #ifndef ossimAdrgHeader_H #define ossimAdrgHeader_H #include #include #include class OSSIM_DLL ossimAdrgHeader { public: // Instantiated with the image file (.img) ossimAdrgHeader(const ossimFilename& img_file); ~ossimAdrgHeader(); enum ErrorStatus { OSSIM_OK = 0, OSSIM_ERROR = 1 }; enum { ADRG_TILE_SIZE = 128 }; int errorStatus() const { return theErrorStatus; } ossimFilename file() const { return theHeaderFile; } ossimFilename imageFile() const { return theImageFile; } ossimIrect validImageRect() const { return theValidImageRect; } ossim_uint32 pixelType() const { return thePixelType; } ossim_uint32 interleaveType() const { return theInterleaveType; } ossim_uint32 numberOfBands() const { return theNumberOfBands; } ossim_uint32 lines() const { return theLines; } ossim_uint32 tlines() const { return theLinesInTiles; } ossim_uint32 samples() const { return theSamples; } ossim_uint32 tsamples() const { return theSamplesInTiles; } ossim_uint32 headerSize() const { return theHeaderSize; } ossim_uint32 startRow() const { return theStartRow; } ossim_uint32 startCol() const { return theStartCol; } ossim_uint32 stopRow() const { return theStopRow; } ossim_uint32 stopCol() const { return theStopCol; } ossim_uint32 tim(ossim_uint32 row, ossim_uint32 col) const; ossimString minLon() const { return theMinLon; } ossimString minLat() const { return theMinLat; } ossimString maxLon() const { return theMaxLon; } ossimString maxLat() const { return theMaxLat; } double minLongitude() const; double minLatitude() const; double maxLongitude() const; double maxLatitude() const; friend OSSIM_DLL std::ostream& operator<<(std::ostream& os, const ossimAdrgHeader& adrg); private: // Returns the longitude in decimal degrees given the formatted string. double parseLongitudeString(const ossimString& lon) const; // Returns the latitude in decimal degrees given the formatted string. double parseLatitudeString(const ossimString& lat) const; // prevent use. ossimAdrgHeader(); ossimAdrgHeader(const ossimAdrgHeader& source); ErrorStatus theErrorStatus; ossimFilename theHeaderFile; ossimFilename theImageFile; ossimIrect theValidImageRect; ossim_uint32 thePixelType; ossim_uint32 theInterleaveType; ossim_uint32 theNumberOfBands; ossim_uint32 theLines; ossim_uint32 theLinesInTiles; ossim_uint32 theSamples; ossim_uint32 theSamplesInTiles; ossim_uint32 theHeaderSize; ossim_uint32 theStartRow; ossim_uint32 theStartCol; ossim_uint32 theStopRow; ossim_uint32 theStopCol; ossim_uint32* theTim; // Tile index map value -- only valid if TIF is 'Y'. ossimString theMinLon; ossimString theMinLat; ossimString theMaxLon; ossimString theMaxLat; ossimString theTif; // Tile index map flag -- Y indicates there are tiles // with no data; N indicates that all tiles contain // RGB graphic data. void parse(); }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAdrgTileSource.h000066400000000000000000000136771352751253100242210ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class give the capability to access tiles from an // ADRG file. // //******************************************************************** // $Id: ossimAdrgTileSource.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimAdrgTileSource_HEADER #define ossimAdrgTileSource_HEADER #include #include class ossimImageData; class ossimAdrgHeader; class OSSIM_DLL ossimAdrgTileSource : public ossimImageHandler { public: enum { ADRG_TILE_WIDTH = 128, ADRG_TILE_HEIGHT = 128, ADRG_TILE_SIZE = 16384, // 128 * 128, BAND_OFFSET = 16384, // 8 * 2048, NUMBER_OF_BANDS = 3 }; enum ADRG_COLOR { RED_BAND = 0, // the ADRG rgb value GREEN_BAND = 1, BLUE_BAND = 2 }; ossimAdrgTileSource(); virtual ossimString getShortName()const; virtual ossimString getLongName()const; /** * @return Returns true on success, false on error. * * @note This method relies on the data member ossimImageData::theImageFile * being set. Callers should do a "setFilename" prior to calling this * method or use the ossimImageHandler::open that takes a file name and an * entry index. */ virtual bool open(); /** * Returns a pointer to a tile given an origin representing the upper * left corner of the tile to grab from the image. * Satisfies pure virtual requirement from TileSource class. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Returns the number of bands in the image. * Satisfies pure virtual requirement from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; virtual ossim_uint32 getNumberOfOutputBands()const; /** * Returns the number of lines in the image. * Satisfies pure virtual requirement from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; /** * Returns the number of samples in the image. * Satisfies pure virtual requirement from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; /** * Returns the zero based image rectangle for the reduced resolution data * set (rrds) passed in. Note that rrds 0 is the highest resolution rrds. */ virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Returns the image geometry object associated with this tile source or NULL if non defined. */ virtual ossimRefPtr getImageGeometry(); /** * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; virtual void close(); /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; virtual bool isOpen()const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width, which can be different than the * internal image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileHeight which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; /** * @brief Gets a property for matching name. * @param name The name of the property to get. * @return Returns property matching "name". */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Gets a list of property names available. * @param propertyNames The list to push back names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimAdrgTileSource(); /** * Adjust point to even 128 boundary. Assumes 0,0 origin. */ void adjustToStartOfTile(ossimIpt& pt) const; /** * Returns true on success, false on error. */ bool fillBuffer(const ossimIrect& tile_rect, const ossimIrect& clip_rect, ossimImageData* tile); ossimRefPtr m_Tile; ossim_uint8* m_TileBuffer; std::ifstream m_FileStr; ossimAdrgHeader* m_AdrgHeader; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationEllipseObject.h000066400000000000000000000061201352751253100261050ustar00rootroot00000000000000//******************************************************************* // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationEllipseObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAnnotationEllipseObject_HEADER #define ossimAnnotationEllipseObject_HEADER #include class OSSIMDLLEXPORT ossimAnnotationEllipseObject : public ossimAnnotationObject { public: ossimAnnotationEllipseObject(const ossimDpt& center = ossimDpt(0,0), const ossimDpt& widthHeight = ossimDpt(1,1), ossim_float64 azimuthInDegrees=0.0, bool enableFill = false, ossim_uint8 r = 255, ossim_uint8 g = 255, ossim_uint8 b = 255, ossim_uint8 thickness = 1); ossimAnnotationEllipseObject(const ossimAnnotationEllipseObject& rhs); virtual ossimObject* dup()const; virtual void applyScale(double x, double y); virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject( const ossimDrect& rect)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void computeBoundingRect(); /*! */ virtual bool isPointWithin(const ossimDpt& imagePoint)const; virtual void setCenterWidthHeight(const ossimDpt& center, const ossimDpt& widthHeight); /** * @brief Sets the azimuth. * @param azimuth in degrees. */ virtual void setAzimuth(ossim_float64 azimuth); /** * @brief Gets the azimuth. * @return The azimuth in decimal degrees. */ virtual ossim_float64 getAzimuth() const; virtual void setFillFlag(bool enabled); /** @return theFillEnabled flag. */ virtual bool getFillFlag() const; /** * @brief Turns on and off drawing of axes on the ellipse. * This flag is only used if fill is turned off. * * @param flag true to enable, false to disable. */ virtual void setDrawAxesFlag(bool flag); /** @return The draw axes flag. */ virtual bool getDrawAxesFlag() const; /** * Saves the current state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimAnnotationEllipseObject(); ossimDpt theCenter; ossimDpt theWidthHeight; ossim_float64 theAzimuthInDegrees; bool theFillEnabled; bool theDrawAxesFlag; ossimDrect theBoundingRect; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationFontObject.h000066400000000000000000000063611352751253100254250ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationFontObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAnnotationFontObject_HEADER #define ossimAnnotationFontObject_HEADER #include #include #include #include /** * Class to draw fonts onto an image. * @note This class requires a font path to be set for the factory: * "ossimFontFactoryRegistry". You should set at a minimum the keyword * "font.dir1" in your ossim_prefernces file. * Example from a RedHat 9.0 system: * font.dir1: /usr/share/fonts/default/Type1 * * @see file ossim/etc/templates/ossim_prefernces_template */ class OSSIMDLLEXPORT ossimAnnotationFontObject : public ossimAnnotationObject { public: friend class ossimGeoAnnotationFontObject; ossimAnnotationFontObject(); ossimAnnotationFontObject(const ossimIpt& upperLeft, const ossimString& s, const ossimIpt& pixelSize = ossimIpt(12, 12), double rotation = 0.0, const ossimDpt& scale = ossimDpt(1.0, 1.0), const ossimDpt& shear = ossimDpt(0.0,0.0), unsigned char r=255, unsigned char g=255, unsigned char b=255); ossimAnnotationFontObject(const ossimAnnotationFontObject& rhs); virtual ossimObject* dup()const; virtual void draw(ossimRgbImage& anImage)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void setString(const ossimString& s); virtual ossimString getString()const; virtual void computeBoundingRect(); virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual bool intersects(const ossimDrect& rect)const; virtual bool isPointWithin(const ossimDpt& imagePoint)const; virtual void setFont(ossimFont* font); virtual void setCenterPosition(const ossimIpt& position); virtual void setUpperLeftPosition(const ossimIpt& position); virtual void setPointSize(const ossimIpt& size); virtual void setRotation(double rotation); virtual void setScale(const ossimDpt& scale); virtual void setShear(const ossimDpt& shear); virtual void setGeometryInformation(const ossimFontInformation& info); virtual void applyScale(double x, double y); protected: virtual ~ossimAnnotationFontObject(); mutable ossimRefPtr theFont; ossimIpt thePosition; ossimString theString; ossimIpt thePixelSize; double theRotation; double theHorizontalScale; double theVerticalScale; double theHorizontalShear; double theVerticalShear; ossimIrect theBoundingRect; void setFontInfo()const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationGdBitmapFont.h000066400000000000000000000072041352751253100257030ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimAnnotationGdBitmapFont.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAnnotationGdBitmapFont_HEADER #define ossimAnnotationGdBitmapFont_HEADER #include #include #include #include /*! * This is a class that will have hardcoded * bitmap fonts. These fonts will be from * the gd library. */ class OSSIMDLLEXPORT ossimAnnotationGdBitmapFont : public ossimAnnotationObject { public: ossimAnnotationGdBitmapFont(const ossimDpt& position=ossimDpt(0,0), const ossimString &text=ossimString(""), ossimGdFontPtr font = ossimGdFontLarge, unsigned char r = 255, unsigned char g = 255, unsigned char b = 255, long thickness = 1); ossimAnnotationGdBitmapFont(const ossimAnnotationGdBitmapFont& rhs); virtual ossimObject* dup()const { return new ossimAnnotationGdBitmapFont(*this); } virtual void applyScale(double x, double y); /*! * Will draw the bitmap to the screen. */ virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const { return rect.intersects(theBoundingRect); } virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual std::ostream& print(std::ostream& out)const; /*! * Will retrieve the bound rectangle for this * object. */ virtual void getBoundingRect(ossimDrect& rect)const; /*! * will compute the bounding rectangle. */ virtual void computeBoundingRect(); /*! * Sets the current bitmap font to use. */ virtual void setFont(ossimGdFontPtr font); /*! * Set's the text string to render. */ virtual void setText(const ossimString& text); /*! * Set's the text string to render. This * will assume that the x,y passed in is * suppose to be the center. We will compute * the upper left corner from this */ virtual void setCenterText(const ossimDpt& center, const ossimString& text); /*! * Set's the text string to render. This * will assume that the x,y passed in is * suppose to be the upper left. */ virtual void setUpperLeftText(const ossimDpt& upperLeft, const ossimString& text); /*! * Sets the center position of the string. * will use this value to compute the actual * origin of upper left corner of the first * character. Make sure you have the text * set before you call this method */ virtual void setCenterTextPosition(const ossimDpt& position); /*! * The actual upper left corner of the character. */ virtual void setUpperLeftTextPosition(const ossimDpt& position); /*! * Will determine if the point is within the font */ virtual bool isPointWithin(const ossimDpt& imagePoint)const; protected: virtual ~ossimAnnotationGdBitmapFont(); ossimGdFontPtr theFontPtr; ossimString theText; ossimDrect theBoundingRect; /*! * This position is suppose to be the upperleft * corner of the first character in the string */ ossimDpt thePosition; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationLineObject.h000066400000000000000000000040001352751253100253720ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimAnnotationLineObject.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAnnotationLineObject_HEADER #define ossimAnnotationLineObject_HEADER #include #include class OSSIMDLLEXPORT ossimAnnotationLineObject : public ossimAnnotationObject { public: ossimAnnotationLineObject(); ossimAnnotationLineObject(const ossimIpt& start, const ossimIpt& end, unsigned char r=255, unsigned char g=255, unsigned char b=255, long thickness=1); ossimAnnotationLineObject(long x1, long y1, long x2, long y2, unsigned char r=255, unsigned char g=255, unsigned char b=255, long thickness=1); ossimAnnotationLineObject(const ossimAnnotationLineObject& rhs); virtual ossimObject* dup()const; virtual void applyScale(double x, double y); virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual bool intersects(const ossimDrect& rect)const; virtual void draw(ossimRgbImage& anImage)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual bool isPointWithin(const ossimDpt& imagePoint)const; virtual void computeBoundingRect(); void setLine(const ossimDpt& start, const ossimDpt& end); void getLine(ossimDpt& start, ossimDpt& end); protected: ossimIpt theStart; ossimIpt theEnd; ossimDrect theBoundingRect; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationMapGridSource.h000066400000000000000000000004271352751253100260710ustar00rootroot00000000000000#ifndef ossimAnnotationMapGridSource_HEADER #define ossimAnnotationMapGridSource_HEADER #include class ossimAnnotationMapGridSource : public ossimAnnotationSource { public: ossimAnnotationMapGridSource(); protected: }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationMultiEllipseObject.h000066400000000000000000000046161352751253100271300ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationMultiEllipseObject.h 23239 2015-04-08 01:02:44Z gpotts $ #ifndef ossimAnnotationMultiEllipseObject_HEADER #define ossimAnnotationMultiEllipseObject_HEADER #include #include class OSSIMDLLEXPORT ossimAnnotationMultiEllipseObject : public ossimAnnotationObject { public: ossimAnnotationMultiEllipseObject(const std::vector& pointList, const ossimDpt& widthHeight = ossimDpt(1,1), bool enableFill = false, unsigned char r = 255, unsigned char g = 255, unsigned char b = 255, long thickness = 1); ossimAnnotationMultiEllipseObject(const ossimDpt& widthHeight = ossimDpt(1,1), bool enableFill = false, unsigned char r = 255, unsigned char g = 255, unsigned char b = 255, long thickness = 1); ossimAnnotationMultiEllipseObject(const ossimAnnotationMultiEllipseObject& rhs); virtual ~ossimAnnotationMultiEllipseObject(); ossimObject* dup()const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual void applyScale(double x, double y); virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void computeBoundingRect(); /*! */ virtual bool isPointWithin(const ossimDpt& imagePoint)const; void setFillFlag(bool flag); void resize(ossim_uint32 size); virtual void setWidthHeight(const ossimDpt& widthHeight); ossimDpt& operator[](int i); const ossimDpt& operator[](int i)const; protected: std::vector thePointList; ossimDpt theWidthHeight; bool theFillFlag; ossimDrect theBoundingRect; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationMultiLineObject.h000066400000000000000000000054641352751253100264240ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationMultiLineObject.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAnnotationMultiLineObject_HEADER #define ossimAnnotationMultiLineObject_HEADER #include #include #include class OSSIMDLLEXPORT ossimAnnotationMultiLineObject : public ossimAnnotationObject { public: ossimAnnotationMultiLineObject(); ossimAnnotationMultiLineObject(const std::vector& lineList, unsigned char r=255, unsigned char g=255, unsigned char b=255, long thickness=1) :ossimAnnotationObject(r, g, b, thickness), thePolyLineList(lineList) { computeBoundingRect(); } ossimAnnotationMultiLineObject(const ossimPolyLine& lineList, unsigned char r=255, unsigned char g=255, unsigned char b=255, long thickness=1) :ossimAnnotationObject(r, g, b, thickness) { thePolyLineList.push_back(lineList); computeBoundingRect(); } ossimAnnotationMultiLineObject(const ossimAnnotationMultiLineObject& rhs) :ossimAnnotationObject(rhs), thePolyLineList(rhs.thePolyLineList), theBoundingRect(rhs.theBoundingRect) { } virtual ossimObject* dup()const { return new ossimAnnotationMultiLineObject(*this); } virtual void applyScale(double x, double y); virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual bool intersects(const ossimDrect& rect)const; virtual void draw(ossimRgbImage& anImage)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const { rect = theBoundingRect; } virtual bool isPointWithin(const ossimDpt& imagePoint)const; virtual void computeBoundingRect(); virtual const std::vector& getPolyLineList()const { return thePolyLineList; } virtual std::vector& getPolyLineList() { return thePolyLineList; } virtual void setPolyLine(const ossimPolyLine& line) { thePolyLineList.clear(); thePolyLineList.push_back(line); } protected: std::vector thePolyLineList; ossimDrect theBoundingRect; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationMultiPolyLineObject.h000066400000000000000000000040711352751253100272610ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimAnnotationMultiPolyLineObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAnnotationMultiPolyLineObject_HEADER #define ossimAnnotationMultiPolyLineObject_HEADER #include #include #include class OSSIMDLLEXPORT ossimAnnotationMultiPolyLineObject : public ossimAnnotationObject { public: ossimAnnotationMultiPolyLineObject(); ossimAnnotationMultiPolyLineObject(const std::vector& multiPoly, unsigned char r, unsigned char g, unsigned char b, long thickness); ossimAnnotationMultiPolyLineObject(const ossimAnnotationMultiPolyLineObject& rhs); virtual ossimObject* dup()const; virtual void applyScale(double x, double y); virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void addPolyLine(const ossimPolyLine& poly); virtual void addPoint(ossim_uint32 polygonIndex, const ossimDpt& pt); virtual void setMultiPolyLine(const std::vector& multiPoly); virtual void computeBoundingRect(); virtual bool isPointWithin(const ossimDpt& imagePoint)const; const std::vector& getMultiPolyLine()const; std::vector& getMultiPolyLine(); protected: virtual ~ossimAnnotationMultiPolyLineObject(); std::vector theMultiPolyLine; ossimDrect theBoundingRect; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationMultiPolyObject.h000066400000000000000000000056511352751253100264560ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimAnnotationMultiPolyObject.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimAnnotationMultiPolyObject_HEADER #define ossimAnnotationMultiPolyObject_HEADER #include #include #include class OSSIMDLLEXPORT ossimAnnotationMultiPolyObject : public ossimAnnotationObject { public: ossimAnnotationMultiPolyObject(); ossimAnnotationMultiPolyObject(const std::vector& multiPoly, bool enableFill, unsigned char r, unsigned char g, unsigned char b, long thickness); ossimAnnotationMultiPolyObject(const ossimAnnotationMultiPolyObject& rhs) : ossimAnnotationObject(rhs), theMultiPolygon(rhs.theMultiPolygon), theBoundingRect(rhs.theBoundingRect), theFillEnabled(rhs.theFillEnabled) { } virtual ossimObject* dup()const { return new ossimAnnotationMultiPolyObject(*this); } virtual void applyScale(double x, double y); virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void clear(); virtual void addPolygon(ossim_uint32 polygonIndex, const ossimPolygon& poly) { if(polygonIndex < theMultiPolygon.size()) { theMultiPolygon[polygonIndex] = poly; } } virtual void addPoint(ossim_uint32 polygonIndex, const ossimDpt& pt) { if(polygonIndex < theMultiPolygon.size()) { theMultiPolygon[polygonIndex].addPoint(pt); } } virtual void setMultiPolygon(const std::vector& multiPoly) { theMultiPolygon = multiPoly; computeBoundingRect(); } virtual void computeBoundingRect(); virtual bool isPointWithin(const ossimDpt& imagePoint)const; const std::vector& getMultiPolygon()const{return theMultiPolygon;} std::vector& getMultiPolygon(){return theMultiPolygon;} void setFillFlag(bool flag) { theFillEnabled = flag; } protected: virtual ~ossimAnnotationMultiPolyObject(); std::vector theMultiPolygon; ossimDrect theBoundingRect; bool theFillEnabled; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationObject.h000066400000000000000000000062221352751253100245720ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationObject.h 23239 2015-04-08 01:02:44Z gpotts $ #ifndef ossimAnnotationObject_HEADER #define ossimAnnotationObject_HEADER #include #include #include #include #include #include #include class OSSIMDLLEXPORT ossimAnnotationObject : public ossimObject { public: virtual ~ossimAnnotationObject(); ossimAnnotationObject(ossim_uint8 r=255, ossim_uint8 g=255, ossim_uint8 b=255, ossim_uint8 thickness=1); virtual void applyScale(double x, double y)=0; virtual void applyScale(const ossimDpt& scale); virtual std::ostream& print(std::ostream& out)const; virtual void draw(ossimRgbImage& anImage)const=0; virtual bool intersects(const ossimDrect& rect)const=0; /*! * Will allocate a new object that is clipped to the passed. * in rect. Look at derived classes to see if the object is actually * clipped or not. A new object is returned if it clips to the rect * else NULL should be returned it doesn't clip. */ virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const=0; virtual void getBoundingRect(ossimDrect& rect)const=0; virtual ossimDrect getBoundingRect()const; virtual void computeBoundingRect()=0; virtual void setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); void getColor(ossim_uint8 &r, ossim_uint8 &g, ossim_uint8 &b)const; ossim_uint8 getThickness()const; virtual void setThickness(ossim_uint8 thickness); /*! * This method allows you to pick an object. It will * return true or false if the point falls somewhere * on an object. Look at derived classes for further * information. */ virtual bool isPointWithin(const ossimDpt& imagePoint) const; /** * Saves the current state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual ossimString getName() const; virtual void setName(const ossimString& name); ossim_uint32 getId()const; virtual ossim_uint32 setId(); static ossim_uint32 getNextId(); static void restIdCounter(); protected: ossim_uint8 theRed; ossim_uint8 theGreen; ossim_uint8 theBlue; ossim_uint8 theThickness; ossimString theName; ossim_uint32 theId; static ossim_uint32 theIdCounter; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationObjectFactory.h000066400000000000000000000026321352751253100261230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimAnnotationObjectFactory.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAnnotationObjectFactory_HEADER #define ossimAnnotationObjectFactory_HEADER #include #include class ossimAnnotationObjectFactory : public ossimFactoryBase { public: /*! * METHOD: instance() * For accessing static instance of concrete factory. */ static ossimAnnotationObjectFactory* instance(); /*! * METHOD: create() * Attempts to create an instance of the Product given a Specifier or * keywordlist. Returns successfully constructed product or NULL. */ virtual ossimAnnotationObject* create(const ossimString& spec) const; virtual ossimAnnotationObject* create(const ossimKeywordlist& kwl, const char* prefix=0) const; /*! * METHOD: getList() * Returns name list of all products represented by this factory: */ virtual std::list getList() const; protected: ossimAnnotationObjectFactory(); static ossimAnnotationObjectFactory* theInstance; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationPolyObject.h000066400000000000000000000044511352751253100254400ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationPolyObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAnnotationPolyObject_HEADER #define ossimAnnotationPolyObject_HEADER #include #include #include class OSSIMDLLEXPORT ossimAnnotationPolyObject : public ossimAnnotationObject { public: ossimAnnotationPolyObject(bool enableFill = false, ossim_uint8 r=255, ossim_uint8 g=255, ossim_uint8 b=255, ossim_uint8 thickness=1); ossimAnnotationPolyObject(const std::vector& imagePts, bool enableFill = false, ossim_uint8 r=255, ossim_uint8 g=255, ossim_uint8 b=255, ossim_uint8 thickness=1); ossimAnnotationPolyObject(const ossimAnnotationPolyObject& rhs); ossimObject* dup()const; virtual void applyScale(double x, double y); virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject( const ossimDrect& rect)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void addPoint(const ossimDpt& pt); virtual void setPolygon(const std::vector& imagePoints); virtual void setPolygon(const ossimPolygon& polygon); virtual void setPolygon(const ossimIrect& rect); virtual void setPolygon(const ossimDrect& rect); virtual void computeBoundingRect(); virtual bool isPointWithin(const ossimDpt& imagePoint)const; const ossimPolygon& getPolygon()const; ossimPolygon& getPolygon(); virtual void setFillFlag(bool flag); protected: virtual ~ossimAnnotationPolyObject(); ossimPolygon thePolygon; ossimDrect theBoundingRect; bool theFillEnabled; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAnnotationSource.h000066400000000000000000000107331352751253100246260ustar00rootroot00000000000000//******************************************************************* // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // // Description: // // Class to annotate or draw things on tiles like text, ellipses and so on. // // Notes: // 1) The output scalar type of this object is ALWAYS 8 bit or OSSIM_UINT8 so // if your input connection is something other than 8 bit it will be // remapped to 8 bit. // 2) This can handle any number of input bands; however, it will never draw // to more than three. So if you have an input connection of four bands // the fourth band will not be drawn to. // //************************************************************************* // $Id: ossimAnnotationSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAnnotationSource_HEADER #define ossimAnnotationSource_HEADER #include #include #include #include #include #include class ossimKeywordlist; class OSSIMDLLEXPORT ossimAnnotationSource : public ossimImageSourceFilter { public: typedef std::vector > AnnotationObjectListType; ossimAnnotationSource(ossimImageSource* inputSource=0); virtual ~ossimAnnotationSource(); virtual ossim_uint32 getNumberOfOutputBands() const; virtual ossimScalarType getOutputScalarType() const; virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel = 0); /*! * Will allow this source to initialize its data objects. If it needs to * it should call its connection to get what it needs. */ virtual void initialize(); /*! * Will return the bounding rectangle. */ virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; /*! * @param bands This can be any number of bands; however, the * annotator will only write to a max of 3, so if you have a 4 band * image the fourth band will not be annotated. */ virtual void setNumberOfBands(ossim_uint32 bands); /*! * Will add an object to the list. * it will own the object added. */ virtual bool addObject(ossimAnnotationObject* anObject); /*! * Will delete an object from the list. * Note: the passed in pointer is no long * valid. */ virtual bool deleteObject(ossimAnnotationObject* anObject); /*! * Saves the current state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void computeBoundingRect(); /*! * Calls the isPointWithin all Annotation * Objects. Note: Do not delete these objects. */ AnnotationObjectListType pickObjects(const ossimDpt& imagePoint); /*! * Note: do not delete the objects returned. */ AnnotationObjectListType pickObjects(const ossimDrect& imageRect); const AnnotationObjectListType& getObjectList()const; AnnotationObjectListType& getObjectList(); /*! Clears theAnnotationObjectList vector. All elements are deleted. */ void deleteAll(); virtual void drawAnnotations(ossimRefPtr tile); protected: void allocate(const ossimIrect& rect); void destroy(); ossimAnnotationSource(const ossimAnnotationSource& rhs):ossimImageSourceFilter(rhs){} /*! * What is the size of the image. This class * is an image producer and it needs to know about * its bounds. We will default the rectangle to an * empty region. */ ossimDrect theRectangle; /*! * The output band can be set to 1 or 3 for * grey or RGB scale. We will default this to * a 1 band image. */ ossim_uint32 theNumberOfBands; /*! * This has all the routines we need for drawing * lines, circles and polygons. */ ossimRefPtr theImage; ossimRefPtr theTile; /*! * These will be all your primitives in * Example: lines, circles, text ... */ AnnotationObjectListType theAnnotationObjectList; TYPE_DATA }; #endif /* #ifndef ossimAnnotationSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimAppFixedTileCache.h000066400000000000000000000077451352751253100246060ustar00rootroot00000000000000//****************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This file contains the Application cache algorithm // //*********************************** // $Id: ossimAppFixedTileCache.h 20127 2011-10-12 11:27:10Z gpotts $ #ifndef ossimAppFixedTileCache_HEADER #define ossimAppFixedTileCache_HEADER #include #include #include #include #include #include #include class ossimFixedTileCache; class ossimImageData; class OSSIM_DLL ossimAppFixedTileCache { public: friend std::ostream& operator <<(std::ostream& out, const ossimAppFixedTileCache& rhs); static const ossim_uint32 DEFAULT_SIZE; typedef ossim_int32 ossimAppFixedCacheId; static ossimAppFixedTileCache *instance(ossim_uint32 maxSize = 0); virtual ~ossimAppFixedTileCache(); /*! * Will flush all cache registered */ virtual void flush(); virtual void flush(ossimAppFixedCacheId cacheId); virtual void deleteCache(ossimAppFixedCacheId cacheId); /*! * Will create a new Tile cache for this application if the tile size is 0,0 it will * use the default tile size. Will * return 0 if not successful. */ ossimAppFixedCacheId newTileCache(const ossimIrect& tileBoundaryRect, const ossimIpt& tileSize=ossimIpt(0,0)); ossimAppFixedCacheId newTileCache(); virtual void setRect(ossimAppFixedCacheId cacheId, const ossimIrect& boundaryTileRect); virtual void setTileSize(ossimAppFixedCacheId cacheId, const ossimIpt& tileSize); ossimRefPtr getTile(ossimAppFixedCacheId cacheId, const ossimIpt& origin); ossimRefPtr addTile(ossimAppFixedCacheId cacheId, ossimRefPtr data, bool duplicateData=true); ossimRefPtr removeTile(ossimAppFixedCacheId cacheId, const ossimIpt& origin); void deleteTile(ossimAppFixedCacheId cacheId, const ossimIpt& origin); const ossimIpt& getTileSize(ossimAppFixedCacheId cacheId); virtual void setMaxCacheSize(ossim_uint32 cacheSize); virtual ossim_uint32 getMaxCacheSize() const { return theMaxCacheSize; } protected: // struct ossimAppFixedCacheTileInfo // { // public: // ossimAppFixedCacheTileInfo(ossimAppFixedCacheId appId, // const ossimIpt& origin) // :theAppCacheId(appId), // theOrigin(origin) // {} // ossimAppFixedCacheId theAppCacheId; // ossimIpt theOrigin; // bool operator ==(const ossimAppFixedCacheTileInfo &rhs)const // { // return (theAppCacheId == rhs.theAppCacheId && // theOrigin == rhs.theOrigin); // } // }; ossimAppFixedTileCache(); ossimFixedTileCache* getCache(ossimAppFixedCacheId cacheId); void shrinkGlobalCacheSize(ossim_int32 byteCount); void shrinkCacheSize(ossimAppFixedCacheId id, ossim_int32 byteCount); void shrinkCacheSize(ossimFixedTileCache* cache, ossim_int32 byteCount); void deleteAll(); static ossimAppFixedTileCache *theInstance; /*! * Will hold the current unique Application id. */ static ossimAppFixedCacheId theUniqueAppIdCounter; ossimIpt theTileSize; ossim_uint32 theMaxCacheSize; ossim_uint32 theMaxGlobalCacheSize; ossim_uint32 theCurrentCacheSize; std::map theAppCacheMap; std::mutex theMutex; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAppTileCache.h000066400000000000000000000112011352751253100236040ustar00rootroot00000000000000//****************************************************************** // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This file contains the Application cache algorithm // //*********************************** // $Id: ossimAppTileCache.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAppTileCache_HEADER #define ossimAppTileCache_HEADER #include #include #include #include #include // class ossimTile; class ossimTileCache; class ossimDataObject; class ossimAppTileCache { public: static const ossim_uint32 DEFAULT_SIZE; static const ossim_uint32 DEFAULT_BUCKET_SIZE; typedef ossim_int32 ossimAppCacheId; typedef ossim_int32 ossimTileId; typedef std::map::iterator AppIdIterator; ~ossimAppTileCache(); /*! * We will force a singleton on this class. */ static ossimAppTileCache *instance(ossim_uint32 maxSize = 0); /*! * Will create a new Tile cache for this application. Will * return 0 if not successful. */ ossimAppCacheId newTileCache(ossim_uint32 bucketSize=DEFAULT_BUCKET_SIZE); /*! * Will retrieve a tile from the cache. Will return NULL * if not found. */ ossimDataObject *get(ossimAppCacheId id, const ossimDpt3d &origin, ossim_uint32 resLevel=0); /*! * Will remove a tile completly from the cache. The * returned tile is no longer owned by the cache. */ ossimRefPtr removeTile(ossimAppCacheId id, const ossimDpt3d &origin, unsigned long resLevel); /*! * Will insert a tile into the cache. */ ossimRefPtr insert(ossimAppCacheId id, const ossimDpt3d &origin, const ossimDataObject* data, ossim_uint32 resLevel=0); /*! * This will delete the specified cache. The LRU queue will * be updated accordingly */ void deleteCache(ossimAppCacheId appId); protected: struct ossimAppCacheTileInfo { public: ossimAppCacheTileInfo(ossimAppCacheId appId, const ossimDpt3d& origin, ossim_uint32 resLevel) :theAppCacheId(appId), theOrigin(origin), theResLevel(resLevel) {} ossimAppCacheId theAppCacheId; ossimDpt3d theOrigin; ossim_uint32 theResLevel; bool operator ==(const ossimAppCacheTileInfo &rhs) { return (theAppCacheId == rhs.theAppCacheId && theOrigin == rhs.theOrigin && theResLevel == rhs.theResLevel); } }; ossimAppTileCache(ossim_uint32 maxSize = DEFAULT_SIZE) : theMaxCacheSize(maxSize), theCurrentCacheSize(0) {} void deleteAll(); /*! * Used to get access to the App cache. */ ossimTileCache* get(ossimAppCacheId id); /*! * will remove all occurances of the appId from the * queue */ void deleteAppCacheFromQueue(ossimAppCacheId appId); /*! * Will remove a single instance of a tile from the queue. */ void removeTileFromQueue(ossimAppCacheId appId, const ossimDpt3d &origin, ossim_uint32 resLevel); void adjustQueue(ossimAppCacheId id, const ossimDpt3d &origin, ossim_uint32 resLevel); /*! * will pop the queue and remove that tile from its cache * and return it to the caller. This is used by the insert * when the max cache size is exceeded. */ ossimRefPtr removeTile(); static ossimAppTileCache *theInstance; /*! * Will hold the current unique Application id. */ static ossimAppCacheId theUniqueAppIdCounter; /*! * Will hold the list of application caches */ std::map theAppCache; /*! * Is the maximum size of the cache. */ ossim_uint32 theMaxGlobalCacheSize; ossim_uint32 theMaxCacheSize; /*! * This holds the current cache size. */ ossim_uint32 theCurrentCacheSize; /*! * Is used in an Least recently used algorithm */ std::list theUsedQueue; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimArcInfoGridWriter.h000066400000000000000000000036731352751253100246640ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimArcInfoGridWriter.h 16081 2009-12-10 20:56:36Z eshirschorn $ #ifndef ossimArcInfoGridWriter_HEADER #define ossimArcInfoGridWriter_HEADER #include #include //******************************************************************* // CLASS: ossimArdcInfoGridWriterFactory //******************************************************************* class OSSIM_DLL ossimArcInfoGridWriter : public ossimImageFileWriter { public: ossimArcInfoGridWriter(); virtual ~ossimArcInfoGridWriter(); ossimArcInfoGridWriter(ossimImageSource *inputSource, const ossimFilename& filename); virtual bool isOpen()const; virtual bool open(); virtual void close(); /*! * saves the state of the object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Returns a 3-letter extension from the image type descriptor * (theOutputImageType) that can be used for image file extensions. * * @param imageType string representing image type. * * @return the 3-letter string extension. */ virtual ossimString getExtension() const; private: virtual bool writeFile(); virtual bool writeBinaryAigHeader(); virtual bool writeBinaryAigBounds(); virtual bool writeBinaryAigStats(); ossimIpt theOutputTileSize; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAtCorrGridRemapper.h000066400000000000000000000073061352751253100250310ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimAtCorrGridRemapper.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAtCorrGridRemapper_HEADER #define ossimAtCorrGridRemapper_HEADER #include /*! * The grid is encoded into band separate grid and allows bilinear interpolation * of atmospheric correction coefficients. It uses the implementation found in * ossimAtCorrRemapper. The base class will call interpolate to calculate the * a, b, c coefficients used. This class just overrides the base interpolation method. For * gridded remappers * * * * Sample keywordlist includes: * * band1.grid.rows: 4 * band1.grid.cols: 4 * band1.grid.a1: * band1.grid.b1: * band1.grid.c1: * band1.grid.a2: * band1.grid.b2: * band1.grid.c2: * band1.grid.a3: * band1.grid.b3: * band1.grid.c3: * band1.grid.a4: * band1.grid.b4: * band1.grid.c4: * band2.grid.rows: 4 * band2.grid.cols: 4 * band2.grid.a1: * band2.grid.b1: * band2.grid.c1: * band2.grid.a2: * band2.grid.b2: * band2.grid.c2: * band2.grid.a3: * band2.grid.b3: * band2.grid.c3: * band2.grid.a4: * band2.grid.b4: * band2.grid.c4: * * : * : * : */ class ossimAtCorrGridRemapper: public ossimAtCorrRemapper { public: ossimAtCorrGridRemapper(ossimObject* owner = NULL, ossimImageSource* inputSource = NULL, const ossimString& sensorType = ""); void setGridRect(const ossimIrect& rect) { theGridBounds = rect; theUlGridBound = rect.ul(); } void setGridSize(ossim_uint32 numberOfBands, const ossimIpt& gridSize); ossimIpt getGridSize()const { return theGridSize; } void getValues(ossim_uint32 band, ossim_uint32 row, ossim_uint32 col, double& a, double& b, double& c) { a = theAGrid[band][row][col]; b = theAGrid[band][row][col]; c = theAGrid[band][row][col]; } void getValues(const ossimDpt& pt, ossim_uint32 band, double& a, double& b, double& c) { interpolate(pt, band, a, b, c); } void setValues(ossim_uint32 band, ossim_uint32 row, ossim_uint32 col, const double& a, const double& b, const double& c) { theAGrid[band][row][col] = a; theBGrid[band][row][col] = b; theCGrid[band][row][col] = c; } virtual void initialize(); /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: virtual ~ossimAtCorrGridRemapper(); ossimIrect theGridBounds; ossimIpt theUlGridBound; ossimIpt theGridSize; std::vector< std::vector< std::vector > >theAGrid; std::vector< std::vector< std::vector > >theBGrid; std::vector< std::vector< std::vector > >theCGrid; virtual void interpolate(const ossimDpt& pt, int band, double& a, double& b, double& c)const; virtual void setBaseToAverage(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAtCorrKeywords.h000066400000000000000000000016711352751253100242560ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // Keywords utilized by atmospheric correction code. // //************************************************************************* // $Id: ossimAtCorrKeywords.h 9968 2006-11-29 14:01:53Z gpotts $ static const char AT_CORR_XA_KW[] = "atmospheric_correction.xa"; static const char AT_CORR_XB_KW[] = "atmospheric_correction.xb"; static const char AT_CORR_XC_KW[] = "atmospheric_correction.xc"; static const char AT_CORR_BIAS_KW[] = "atmospheric_correction.bias"; static const char AT_CORR_GAIN_KW[] = "atmospheric_correction.gain"; static const char AT_CORR_CALCOEF_KW[] = "atmospheric_correction.calcoef"; static const char AT_CORR_BANDWIDTH_KW[] = "atmospheric_correction.bandwidth"; static const char GAMMA_REMAPPER_GAMMA_KW[] = "gamma_remapper.gamma"; ossim-Miami-2.9.1/include/ossim/imaging/ossimAtCorrRemapper.h000066400000000000000000000054231352751253100242210ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Kathy Minear // // Description: // Takes in DNs for any number of bands // Converts DNs to Radiance at the satellite values Lsat // Converts Lsat to Surface Reflectance values // //************************************************************************* // $Id: ossimAtCorrRemapper.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAtCorrRemapper_HEADER #define ossimAtCorrRemapper_HEADER #include class ossimAtCorrRemapper : public ossimImageSourceFilter { public: ossimAtCorrRemapper(ossimObject* owner = NULL, ossimImageSource* inputSource = NULL, const ossimString& sensorType = ""); virtual ossimString getShortName() const; virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual std::ostream& print(std::ostream& os) const; friend std::ostream& operator << (std::ostream& os, const ossimAtCorrRemapper& hr); std::vector getNormMinPixelValues() const; std::vector getNormMaxPixelValues() const; void getNormMinPixelValues(std::vector& v) const; void getNormMaxPixelValues(std::vector& v) const; const ossimString& getSensorType() const; void setSensorType(const ossimString& sensorType); protected: virtual ~ossimAtCorrRemapper(); /*! * Method to set unset the enable flag. */ void verifyEnabled(); virtual void interpolate(const ossimDpt& pt, int band, double& a, double& b, double& c)const; ossimRefPtr theTile; double* theSurfaceReflectance; bool theUseInterpolationFlag; std::vector theMinPixelValue; std::vector theMaxPixelValue; std::vector theXaArray; std::vector theXbArray; std::vector theXcArray; std::vector theBiasArray; std::vector theGainArray; std::vector theCalCoefArray; std::vector theBandWidthArray; ossimString theSensorType; TYPE_DATA }; #endif /* #ifndef ossimAtCorrRemapper_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimAtbController.h000066400000000000000000000102141352751253100240770ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains declaration of class ossimAtbController. // This is the class for the top-level object controlling the automated // tonal balancing (ATB) function. The controller accepts a mosaic. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimAtbController.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAtbController_HEADER #define ossimAtbController_HEADER #include #include #include #include #include class ossimImageCombiner; class ossimKeywordlist; class ossimAtbMatchPoint; class ossimGridRemapSource; class ossimGridRemapEngine; class ossimConnectableContainer; /***************************************************************************** * * CLASS: ossimAtbController * *****************************************************************************/ class ossimAtbController : public ossimConnectableObject, public ossimProcessInterface { public: /*! * default Constructor initializes the member combiner pointer to NULL. */ ossimAtbController(); /*! * Constructor with Combiner reference. This combiner is used for the ATB. */ ossimAtbController(ossimImageCombiner* combiner, ossimGridRemapEngine* engine=0); /*! * Constructor with a specified remap engine. */ ossimAtbController(ossimGridRemapEngine* engine); ~ossimAtbController(); virtual ossimObject* getObject() { return this; } virtual const ossimObject* getObject()const { return this; } /*! * Provide alternate means of initialization in case default constructor * used. */ void initializeWithCombiner(ossimImageCombiner* combiner, ossimGridRemapEngine* engine=0); /*! * Enable an image in the mosaic for the tonal balancing process */ bool enableImage (unsigned int index); /*! * Disnable an image in the mosaic from the tonal balancing process */ bool disableImage(unsigned int index); /*! * Locks a particular source for adjustment. A locked image * effectively defines the target values for all overlapping imagery. */ bool lockImage (unsigned int index); /*! * Unlock a particular source for adjustment. */ bool unlockImage (unsigned int index); /*! * Implementation of ossimProcessInterface pure virtual method. */ virtual bool execute(); virtual void abort(); /*! * Hook to set the size of the kernel used by all point sources in computing * their mean pixel value. The kernels will be resized to NxN. */ void setKernelSize(int side_size); /*! * Sets the grid spacing used in gridding the mosaic's bounding rectangle. */ void setGridSpacing(const ossimIpt& spacing); /*! * Sets the ATB remap engine. This object implements the specific tonal * balancing algorithm. The dependency on number of bands and color space, * is limited only to this engine. This facilitates the implementation of * various grid-based image matching schemes. */ void setGridRemapEngine(ossimGridRemapEngine* engine); /*! * Implementations of ossimStateInterface pure virtuals */ virtual bool saveState(ossimKeywordlist& kwl) const; virtual bool loadState(const ossimKeywordlist& kwl); /*! * Implementation of ossimConnectableObject pure virtual. */ virtual bool canConnectMyInputTo(ossim_int32 myInputIndex, const ossimConnectableObject* object)const; protected: void initializeRemappers(); ossimDrect theBoundingRect; ossimRefPtr theContainer; ossimGridRemapEngine* theGridRemapEngine; std::vector > theMatchPoints; ossimIpt theGridSpacing; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAtbMatchPoint.h000066400000000000000000000053051352751253100240270ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains declaration of class ossimAtbMatchPoint. This class // is used by the automated tonal balancing code for bookkeeping and // statistics associated with match-points. Match points are points shared in // common between two or more images being adjusted. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimAtbMatchPoint.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAtbMatchPoint_HEADER #define ossimAtbMatchPoint_HEADER #include #include #include class ossimAtbPointSource; class ossimGridRemapEngine; class ossimGridRemapSource; /*!**************************************************************************** * * CLASS: ossimAtbMatchPoint * *****************************************************************************/ class ossimAtbMatchPoint : public ossimReferenced { public: ossimAtbMatchPoint() : theGridRemapEngine(0) {} ossimAtbMatchPoint(const ossimDpt& view_point, ossimGridRemapEngine* engine) : theViewPoint(view_point), theGridRemapEngine(engine) {} /*! * Returns the point in view coordinates associated with this object. */ const ossimDpt& viewPoint() const { return theViewPoint; } /*! * Adds a new contribution to the sample set. */ void addImage(ossimGridRemapSource* image_source); /*! * The target parameter value computed given all contributions. Returns true * if a valid quantity is returned. */ bool assignRemapValues(); /*! * Hook to set the size of the kernel used by all point sources in computing * their mean pixel value. The kernels will be resized to NxN. */ void setKernelSize(int side_size); /*! * Sets the ATB remap engine reference owned by the controller. This engine * is the only object that understands how to compute remap parameters from * pixel data. This permits easily modifying the ATB algorithm without * the support classes such as this one. */ void setGridRemapEngine(ossimGridRemapEngine* engine); /*! * Dumps the contents of the object to the stream in human readable format. */ // void print(std::ostream& os) const; // friend std::ostream& operator << (std::ostream& os); protected: virtual ~ossimAtbMatchPoint(); ossimDpt theViewPoint; std::vector thePointSourceList; ossimGridRemapEngine* theGridRemapEngine; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimAtbPointSource.h000066400000000000000000000057741352751253100242450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains declaration of class ossimAtbPointSource. // This object provides the statistics associated with a given point on a // given image corresponding to a matchpoint. A matchpoint contains a // collection of these point sources, one for each contributing image. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimAtbPointSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAtbPointSource_HEADER #define ossimAtbPointSource_HEADER #include #include #include class ossimImageSource; class ossimImageData; class ossimGridRemapSource; class ossimGridRemapEngine; /*!**************************************************************************** * * CLASS: ossimAtbPointSource * *****************************************************************************/ class ossimAtbPointSource : public ossimReferenced { public: ossimAtbPointSource(); ossimAtbPointSource(ossimGridRemapSource* remap_source, const ossimDpt& view_point); /*! * Sets the pointer of the source of pixels used to compute the stats. */ void setRemapSource(ossimGridRemapSource* image_source); /*! * Returns the reference to the remapper feeding this source. */ ossimGridRemapSource* getRemapSource() { return theRemapSource.get(); } /*! * Sets the view coordinates corresponding to this point. */ void setViewPoint(const ossimDpt& view_point); /*! * Returns the view point corresponding to this point source. */ const ossimDpt& getViewPoint() const { return theViewPoint; } /*! * Returns the computed value vector corresponding to the region about the * view point. The ATB Remap engine performs the actual computation, since * the definition of "value" is algorithm dependent (the value may be in a * different color space). */ void getSourceValue(void* value); /*! * Method to set the kernel size used in computing statistics. The kernel * will be resized to NxN. */ void setKernelSize(int side_size); /*! * Sets the ATB remap engine reference owned by the controller. This engine * is the only object that understands how to compute remap parameters from * pixel data. This permits easily modifying the ATB algorithm without * the support classes such as this one. */ void setGridRemapEngine(ossimGridRemapEngine* engine) { theGridRemapEngine = engine; } protected: virtual ~ossimAtbPointSource(); private: ossimRefPtr theRemapSource; ossimDpt theViewPoint; ossimRefPtr theGridRemapEngine; int theKernelSize; bool theViewPointIsValid; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimBandAverageFilter.h000066400000000000000000000066231352751253100246430ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBandAverageFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimBandAverageFilter_HEADER #define ossimBandAverageFilter_HEADER #include #include /** * This filter outputs a single band that is the weighted average of all the * input bands retrieved from the getTile. This filter will work with any * input scalar type. Note the OSSIMDLLEXPORT is used for the different * compilers that require importing and exporting symbols for shared library * support. */ class OSSIMDLLEXPORT ossimBandAverageFilter : public ossimImageSourceFilter { public: ossimBandAverageFilter(); ossimBandAverageFilter(ossimImageSource* input, const std::vector& weights); virtual ~ossimBandAverageFilter(); /** * The data object argument is deprecated and should not be used. * eventually we will remove it from the base classes. This method will * return 1 if our source is enabled else it calls the base class * getNumberOfOutputBands. */ virtual ossim_uint32 getNumberOfOutputBands()const; /** * Since this filter is going to operate in native pixel type we will use * a tmeplate method to do this. It will check the scalar tpe of the input * and then cat it to set the template variabel to be used within the * template method averageInput. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Since we are merging all bands we will use the null pix of the * first input band as our null pix. If we are disabled we just * return the input s null */ virtual double getNullPixelValue(ossim_uint32 band=0)const; /** * We will use the min of all bands as our min. If we aredisabled * we just return the inputs min */ virtual double getMinPixelValue(ossim_uint32 band=0)const; /** * We will use the max of all bands as our max. If we aredisabled * we just return the inputs max */ virtual double getMaxPixelValue(ossim_uint32 band=0)const; /** * simple access method to get a weight */ double getWeight(ossim_uint32 band)const; /** * Sinple access method to set the weight of a band, * We make sure that it is a positive weight */ void setWeight(ossim_uint32 band, double weight); /** * allocates its tile buffer */ virtual void initialize(); /** * loads its weights to a keywordlist */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Saves its weights to a keywordlist */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: ossimRefPtr theTile; std::vector theWeights; void checkWeights(); template void averageInput( T dummyVariable, // used only for template type, value ignored ossimRefPtr inputDataObject); // for Runtime Type Info (RTTI) TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimBandClipFilter.h000066400000000000000000000052161352751253100241550ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBandClipFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimBandClipFilter_HEADER #define ossimBandClipFilter_HEADER #include #include class ossimBandClipFilter : public ossimImageSourceFilter { public: /*! * Specifies the type of clipping. The first will * just clip and */ enum ossimBandClipType { ossimBandClipType_NONE = 0, ossimBandClipType_CLIP = 1, ossimBandClipType_CLAMP = 2, ossimBandClipType_LINEAR_STRETCH = 3, ossimBandClipType_MEDIAN_STRETCH = 4 }; ossimBandClipFilter(); ossimBandClipFilter(ossimImageSource*, const std::vector& minPix, const std::vector& maxPix, ossimBandClipType clipType=ossimBandClipType_NONE); ossimBandClipFilter(ossimImageSource*, double minPix, double maxPix, ossimBandClipType clipType=ossimBandClipType_NONE); void setClipType(ossimBandClipType clipType); ossimBandClipType getClipType()const; virtual ossim_uint32 getNumberOfValues()const; void setNumberOfValues(ossim_uint32 size); void setMinMaxPix(const std::vector& minPix, const std::vector& maxPix); const std::vector& getMinPixList()const; const std::vector getMaxPixList()const; double getMinPix(ossim_uint32 index)const; double getMaxPix(ossim_uint32 index)const; ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual void initialize(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = NULL); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = NULL)const; protected: virtual ~ossimBandClipFilter(); void runClip(); void runClamp(); void runLinearStretch(); void runMedianStretch(); std::vector theMinPix; // normalized min std::vector theMaxPix; // normalized max std::vector theMedian; // normalized median. ossimBandClipType theClipType; ossimRefPtr theTile; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimBandLutFilter.h000066400000000000000000000142771352751253100240410ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //************************************************************************* // $Id: ossimBandLutFilter.h 23616 2015-11-11 19:50:29Z dburken $ #ifndef ossimBandLutFilter_HEADER #define ossimBandLutFilter_HEADER #include #include #include #include class ossimImageData; /*************************************************************************************************** * * This class provides a look-up-table remap capability for performing band-separate remapping to * an output with the same number of bands. This is similar to ossimIndexToRgbLutFilter except it * works independently on the input bands. The number of output bands is necessarily equal to the * number of input bands, but the scalar data type between input and output can be different (just * like with the ossimScalarRemapper). * * The LUT is provided as a KWL with several remapping modes supported: * * Literal: Only those indices represented in the KWL are remapped to the values indicated. All * other pixel values are mapped to the NULL pixel (0,0,0). Note that this is only meaningful for * integer input scalar types since a normalized input will likely not find an exact match. * * Arbitrary piecewise linear ("vertices"): The LUT KWL provides vertices to contiguous line * segments. Pixel values falling between specified indices are linearly interpolated between * adjacent vertices. Any index pixel values falling outside the range between min and max vertex * indices will be mapped to the NULL pixel. * * Regular piecewise linear ("regular"): The entries in the KWL do not correspond to any specific * index (except the first and the last entries that correspond to the min and max pixel values). * Remaining intermediate entries are equally spaced in index space so that the line segments are of * equal length. The min and max values are queried from the input source, but can be overriden with * the "min_value" and "max_value" keywords in the LUT KWL. * * Here are example KWLs for the three modes, Note that the band identifier is optional if the input * image is single band, or if the same LUT is to be applied to all bands. * * If the input is multi-band, the same mode applies to all bands. The band numbers are 0-based. * If band-specific entries are being provided (i.e., the "band" prefix is being used) then at least * one entry for each band must be provided, otherwise remaining bands will be ignored. * * First for the "literal" remap: * * type: ossimBandLutFilter * mode: literal * [band0.]entry0.in: 0 * [band0.]entry0.out: 1 * [band0.]entry1.in: 128 * [band0.]entry1.out: 2 * [band0.]entry2.in: 255 * [band0.]entry2.out: 3 * * The above KWL will map only pixels with input values of 0, 128, and 255. All other indices will * map to the null value. This mode is not appropriate for floating-point input scalar types. * However, no checks are made so pay attention to what you put in your LUT! * * Example for arbitrary piecewise linear, a.k.a. "interpolated" mode: * * type: ossimBandLutFilter * mode: interpolated * [band0.]entry0.in: 0.1 * [band0.]entry0.out: 255 * [band0.]entry1.in: 0.5 * [band0.]entry1.out: 128 * [band0.]entry2.in: 0.90 * [band0.]entry2.out: 1 * * The above KWL is a sort of heat map where input values between 0 and 0.5 will linearly map to * discrete numbers 255 to 128. Then values between 0.5 to 1.0 will linearly map to * values 128 down to 0. Effectively this inverts the colors and performs a scalar remap to UInt8. * Note that any input values below 0.1 ad above 0.9 are outside of the remap range and will map to * the null pixel. This mode is appropriate for both integer and floating-point inputs. * * The table can be contained in a separate file from the main KWL state file. In this case, the * loadState can accept a file name in place of a complete table: * * type: ossimBandLutFilter * lut_file: * * The format of the LUT KWL file is just as specified above for the inline case. * * If you want an output scalar type different from the input scalar type, you will need to indicate * that either programmatically or via the keyword (specified in the state KWL or LUT KWL file: * * scalar_type: (see ossimScalarTypeLut for list of enumerated strings) * **************************************************************************************************/ class OSSIM_DLL ossimBandLutFilter : public ossimImageSourceFilter { public: enum Mode { UNKNOWN=0, LITERAL = 1, INTERPOLATED = 2 }; ossimBandLutFilter(); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); void setMode(Mode mode) { theMode = mode; } Mode getMode() const { return theMode; } virtual ossimScalarType getOutputScalarType() const { return theOutputScalarType; } /** * Sets the output scalar type. */ virtual void setOutputScalarType(ossimScalarType scalarType); virtual void setOutputScalarType(ossimString scalarType); /** * This opens the keyword list and initializes lut. * @param file Keyword list containing lut. */ void setLut(const ossimFilename& file); virtual void initialize(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); protected: virtual ~ossimBandLutFilter(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); bool initializeLut(const ossimKeywordlist& kwl, const char* prefix=0); std::vector< std::map > theLut; Mode theMode; ossimRefPtr theTile; ossimFilename theLutFile; ossimScalarType theOutputScalarType; TYPE_DATA }; #endif /* #ifndef ossimBandLutFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimBandMergeSource.h000066400000000000000000000042261352751253100243400ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBandMergeSource.h 23108 2015-01-27 17:00:20Z okramer $ #ifndef ossimBandMergeSource_HEADER #define ossimBandMergeSource_HEADER #include class ossimImageSourceConnection; class ossimImageSource; class OSSIM_DLL ossimBandMergeSource : public ossimImageCombiner { public: ossimBandMergeSource(); ossimBandMergeSource(ossimConnectableObject::ConnectableObjectList& inputSources); /** * This will merge all the bands from the input source list * into one contiguous ossimImageData object. This is very * useful when you want to split off an intesity channel in * HSI and then run some algorithms on it and then merge it back. * You can also try to do fusions by converting to an YCbCr and * replace the Y or intensity channel with maybe a high-pass * convolution on the pan. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual bool getTile(ossimImageData* tile, ossim_uint32 resLevel=0); virtual void initialize(); /** * Returns the number of bands in a tile returned from this TileSource. * Note: we are supporting sources that can have multiple data objects. * If you want to know the scalar type of an object you can pass in the */ virtual ossim_uint32 getNumberOfOutputBands() const; virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; protected: virtual ~ossimBandMergeSource(); /** Performs allocation of "theTile". */ void allocate(); ossim_uint32 theNumberOfOutputBands; ossimRefPtr theTile; ossim_uint32 computeNumberOfInputBands()const; TYPE_DATA }; #endif /* #ifndef ossimBandMergeSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimBandSelector.h000066400000000000000000000150601352751253100236760ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts // // Description: Contains class declaration for ossimBandSelector. // //******************************************************************* // $Id$ #ifndef ossimBandSelector_HEADER #define ossimBandSelector_HEADER 1 #include #include class ossimImageData; class ossimImageHandler; class OSSIM_DLL ossimBandSelector : public ossimImageSourceFilter { public: enum ossimBandSelectorWithinRangeFlagState { ossimBandSelectorWithinRangeFlagState_NOT_SET = 0, ossimBandSelectorWithinRangeFlagState_IN_RANGE = 1, ossimBandSelectorWithinRangeFlagState_OUT_OF_RANGE = 2, }; ossimBandSelector(); virtual ~ossimBandSelector(); virtual ossimString getLongName() const; virtual ossimString getShortName() const; virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); /** * Initializes bandList to the zero based order of output bands. */ virtual void getOutputBandList(std::vector& bandList) const; /** * @brief Will set to three bands (rgb) out. * * This will attempt to auto detect the zero based rgb band order from the * input image handler. If the result is < 3 bands we will * not increase the band output by adding more bands. For example, * if the input is grey or thermal then it will just output one band for * a default allocation. Note, this can be overriden by explicitly setting * the output band list. * * If the image handler implemented getRgbBandList(...) it will use that: * bands = 2,1,0 ( or whatever handler thinks rgb is ) * else if 3 band or greater and can't determine rgb: * bands = 0,1,2 * else (less than three bands) * bands = 0 */ virtual void setThreeBandRgb(); /** * Sets the output band list. * * @param outputBandList List of zero based bands. * @param disablePassThru If true, forces the band selection to be performed by this filter. * Otherwise, the image handler to the left is directed to select bands if it has that * capability (default behavior). * * @note The input connection should be established prior to calling this. * * @note Bands can be duplicated. So if you have a single band input you * can do a band list like "1, 1, 1". Any band within the list must be * available from the input. So if you have a 3 band input bands must be * constrained to zero based bands "0, 1, or 2". * * @note Calling this method does not enable filter so callers should do: * theBandSelector->enableSource(); * theBandSelector->setOutputBandList(bandList); */ virtual void setOutputBandList(const std::vector& outputBandList, bool disablePassThru=false); /** * Returns the number of bands in a tile returned from this TileSource. */ virtual ossim_uint32 getNumberOfOutputBands() const; /** * @brief Returns the number of input bands. * * Overrides ossimImageSourceFilter::getNumberOfInputBands to check for a * single image chain band selectable image handler on the input. If one * is present it returns it's number of input bands instead of the number * of the input connection's output bands(our input). This is needed so * callers, e.g. band selector dialog box can query the number of bands * available. * * @return Number of bands available. */ virtual ossim_uint32 getNumberOfInputBands()const; virtual void initialize(); virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual double getNullPixelValue(ossim_uint32 band=0)const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); /** * Override base class so that a disableSource event does not * reinitialize the object and enable itself. */ //virtual void propertyEvent(ossimPropertyEvent& event); //virtual void refreshEvent(ossimRefreshEvent& event); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool isSourceEnabled()const; protected: /** * Called on first getTile, will initialize all data needed. */ void allocate(); /** * Will check all combinations of the band list to see if its */ void checkPassThrough(); /** * @return true if all bands in theOutputBandList are less than the * number of input's bands. */ bool outputBandsWithinInputRange() const; /** * @brief Finds and returns band selectable image handler. * * To get a valid pointer there must be one and only one image handler on * the input connection and it must be a band selector. In other words, * must be a single image chain input and * ossimImageHandler::isBandSelector() must return true. * * @return Pointer to image handler wrapped in an ossimRefPtr on success; * null, on error. */ ossimRefPtr getBandSelectableImageHandler() const; /** * @brief Attempts to derive rgb bands from image handler to the left of the * band selector. * * Must be one and only one image handler on the input connection. * In other words, must be a single image chain input. * * @return true on success, false on error. */ bool getRgbBandList(std::vector& bandList) const; ossimRefPtr m_tile; std::vector m_outputBandList; ossimBandSelectorWithinRangeFlagState m_withinRangeFlag; bool m_passThroughFlag; bool m_delayLoadRgbFlag; bool m_inputIsSelectable; TYPE_DATA }; #endif /* #ifndef ossimBandSelector_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimBandSeparateHandler.h000066400000000000000000000074621352751253100251670ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: // // Image handler used when the multi-band image has each band represented by a different disk file. // This is the case for some Ikonos imagery. // //************************************************************************************************** // $Id: ossimBandSeparateHandler.h 2644 2011-05-26 15:20:11Z oscar.kramer $ #ifndef ossimBandSeparateHandler_HEADER #define ossimBandSeparateHandler_HEADER #include #include #include /** * This class defines an abstract Handler which all image handlers(loaders) * should derive from. */ class OSSIMDLLEXPORT ossimBandSeparateHandler : public ossimImageHandler { public: //! Constructor (default): ossimBandSeparateHandler(); //! Destructor: virtual ~ossimBandSeparateHandler(); //! Opens multiple band-files based on info in metadata file. //! @return Returns true on success, false on error. virtual bool open(); //! Closes all band-files and clears input handler list. virtual void close(); //! @return true if open, false if not. virtual bool isOpen()const; virtual ossim_uint32 getNumberOfInputBands() const; //! @param resLevel Reduced resolution level to return lines of. //! Default = 0 //! @return The number of lines for specified reduced resolution level. virtual ossim_uint32 getNumberOfLines(ossim_uint32 resLevel = 0) const; //! @param resLevel Reduced resolution level to return samples of. //! Default = 0 //! @return The number of samples for specified reduced resolution level. virtual ossim_uint32 getNumberOfSamples(ossim_uint32 resLevel = 0) const; //! Method to save the state of an object to a keyword list. //! Return true if ok or false on error. virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; //! Method to the load (recreate) the state of an object from a keyword //! list. Return true if ok or false on error. virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Fills the requested tile by pulling pixels from multiple file tiles as needed. virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel); //! Returns scalar type of first band (should be the same for all bands) virtual ossimScalarType getOutputScalarType() const; //! Overrides base connection method to connect output of merge source. virtual bool canConnectMyOutputTo(ossim_int32 index, const ossimConnectableObject* obj); //! Returns the geometry of the first band: virtual ossimRefPtr getImageGeometry(); //! These images are not tiled virtual ossim_uint32 getImageTileWidth() const { return 0; } virtual ossim_uint32 getImageTileHeight() const { return 0; } protected: //! Fetches the list of band file names from the header file. The header file name is contained //! in ossimImageHandler::theImageFile. //! NOTE TO PROGRAMMER: This class is presently tailored to the Ikonos metadata file specifying //! the individual band files. If other "metadata" formats are to be supported, then this class //! should be derived from. This method would therefore be pure virtual in this base-class and //! only this method would need to be implemented in the derived classes. virtual void getBandFileNames(std::vector& file_names); std::vector > m_bandFiles; ossimRefPtr m_mergeSource; TYPE_DATA }; #endif /* #ifndef ossimBandSeparateHandler_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimBitMaskTileSource.h000066400000000000000000000132311352751253100246600ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //******************************************************************* // $Id: ossimBitMaskTileSource.h 2644 2011-05-26 15:20:11Z oscar.kramer $ #ifndef ossimBitMaskTileSource_HEADER #define ossimBitMaskTileSource_HEADER #include #include class ossimImageGeometry; //************************************************************************************************* //! This is the image handler for providing mask pixels to an ossimMaskFilter object. //! //! This class takes care of reading the custom, bit-compressed OSSIM bit mask file format. //! //! When the developer needs to mask an image, the following needs to be done: //! //! Creating the Mask: //! 1. A mask file first needs to be created using ossimBitMaskWriter and a source image. The app //! "img2rr --create-mask" directs that program to use ossimBitMaskWriter to generate a mask //! during overview generation. There is also create-bitmask app that will generate the mask. //! 2. An OSSIM ".mask" file should exist on disk after step 0. This is typically the same base //! name as the source image file being masked. //! //! Using the Mask: //! 1. An ossimBitMaskTileSource (derived from ossimImageHandler) needs to be instantiated and //! the mask file name used to open it. //! 3. An ossimMaskFilter (derived from ossimImageCombiner) is the actual filter that combines //! the source image handler and the ossimBitMaskTileSource object to provide the resultant //! masked tiles. //! //! The OSSIM bit mask file contains a small header that consists of: //! magic number, //! starting res level, //! number of res levels //! num columns at starting res level, //! num rows at starting res level, //! num columns at 2nd res level, //! num rows at 2nd res level, //! etc., for all res levels //! //! //! //! The number of rows and columns represents the number of bytes in the mask, with each byte //! containing 8 alpha mask bits representing 8 pixels in the original image. //! //! This class functions as an image handler, returning 255 for unmasked pixels, and 0 for masked //! pixels. //! //! For debug purposes, this code initializes the tile to all 128's so that the //! ossimMaskFilter can recognize uninitialized mask data. //! //************************************************************************************************* class OSSIM_DLL ossimBitMaskTileSource : public ossimImageHandler { public: ossimBitMaskTileSource(); //! Return a tile of masks. These are "bit masks", i.e., either 0 (hide) or 1 (show). //! The pixels' remaining 7 bits are cleared and should not be used. virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 rLevel=0); virtual bool isValidRLevel (ossim_uint32 res_level) const; virtual ossim_uint32 getNumberOfLines (ossim_uint32 res_level=0) const; virtual ossim_uint32 getNumberOfSamples(ossim_uint32 res_level=0) const; virtual ossim_uint32 getNumberOfInputBands() const { return 1; } virtual ossim_uint32 getNumberOfOutputBands() const { return 1; } virtual ossimScalarType getOutputScalarType() const { return OSSIM_UINT8; } virtual ossim_uint32 getImageTileWidth() const { return 0; } virtual ossim_uint32 getImageTileHeight() const { return 0; } virtual bool isOpen() const; virtual bool open(); virtual void close(); virtual double getNullPixelValue(ossim_uint32 /*band=0*/) const { return 0; } virtual double getMinPixelValue (ossim_uint32 /*band=0*/) const { return 0; } virtual double getMaxPixelValue (ossim_uint32 /*band=0*/) const { return 1.0; } //! There is no geometry associated with a mask file -- it is pixel-for-pixel mapped to //! an image file. The image file must have the valid geometry. virtual ossimRefPtr getImageGeometry(); //! Overrides base class implementation. virtual ossim_uint32 getNumberOfDecimationLevels() const; //! For backward compatibility with older mask format ("Ming Mask"), provide for associating //! the mask with an image handler: void setAssociatedImageHandler(ossimImageHandler* handler); //! This class can be used during overview generation, in which case there will be a simultaneous //! mask writing. Instead of accessing a mask file (which may not yet exist), the mask buffer //! of the writer will be accessed directly instead of our own buffer. void setAssociatedMaskWriter(ossimBitMaskWriter* maskWriter); protected: virtual ~ossimBitMaskTileSource(); //! Returns true if this handler recognizes the file name extension as an OSSIM raster mask file. bool isSupportedExtension(); virtual void establishDecimationFactors(); ossimRefPtr m_tile; std::vector m_buffers; std::vector m_bufferSizes; //! For backward compatibility with older mask format ("Ming Mask"), provide for associating //! the mask with an image handler: ossimRefPtr m_handler; //! This class can be used during overview generation, in which case there will be a simultaneous //! mask writing. Instead of accessing a mask file (which may not yet exist), the mask buffer //! of the writer will be accessed directly instead of our own buffer. ossimRefPtr m_maskWriter; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimBitMaskWriter.h000066400000000000000000000132451352751253100240630ustar00rootroot00000000000000//************************************************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //************************************************************************************************* // $Id: ossimBitMaskWriter.h 2644 2011-05-26 15:20:11Z oscar.kramer $ #ifndef ossimBitMaskWriter_HEADER #define ossimBitMaskWriter_HEADER #include #include #include #include #include #include class ossimFilename; class ossimKeywordlist; class ossimImageHandler; class ossimBitMaskTileSource; //************************************************************************************************* //! //! Class for computing a mask from an input image source and writing the mask file to disk. //! //! This class takes care of all details associated with computing, writing and reading the custom, //! bit-compressed OSSIM bit mask file format. //! //! When the developer needs to mask an image, the following needs to be done: //! //! Creating the Mask: //! 1. A mask file first needs to be created using ossimBitMaskWriter and a source image. The app //! "img2rr --create-mask" directs that program to use ossimBitMaskWriter to generate a mask //! during overview generation. There is also create-bitmask app that will generate the mask. //! 2. An OSSIM ".mask" file should exist on disk after step 0. This is typically the same base //! name as the source image file being masked. //! //! Using the Mask: //! 1. An ossimBitMaskTileSource (derived from ossimImageHandler) needs to be instantiated and //! the mask file name used to open it. //! 3. An ossimMaskFilter (derived from ossimImageCombiner) is the actual filter that combines //! the source image handler and the ossimBitMaskTileSource object to provide the resultant //! masked tiles. //! //! The OSSIM bit mask file contains a small header that consists of: //! magic number, //! starting res level, //! number of res levels //! num columns at starting res level, //! num rows at starting res level, //! num columns at 2nd res level, //! num rows at 2nd res level, //! etc., for all res levels //! //! //! //! The number of rows and columns represents the number of bytes in the mask, with each byte //! containing 8 alpha mask bits representing 8 pixels in the original image. //! //! The mask is computed here using the specified values for bogus pixels. If a pixel in the source //! image is in the range of bogus values, a mask of 0 is assigned to that pixel, otherwise 1. //! //************************************************************************************************* class OSSIM_DLL ossimBitMaskWriter : public ossimOutputSource { public: static const char* BM_STARTING_RLEVEL_KW; static const char* MASK_FILE_MAGIC_NUMBER; //! Default constructor typically used when reading a mask from disk. ossimBitMaskWriter(); ~ossimBitMaskWriter(); //! Sets the NULL pixel value to consider when computing mask: void setBogusPixel(double pixel_value); //! Sets the range of pixels (inclusive) to be regarded as NULL pixels when computing mask void setBogusPixelRange(double min, double max); //! Sets the starting resolution level for the mask. void setStartingResLevel(ossim_uint32 res_level) { m_startingResLevel = res_level; } //! Given a source's tile, derives the alpha mask and saves it in buffer for later writing to //! disk. void generateMask(ossimRefPtr tile, ossim_uint32 rLevel); //! For imagery that already has overviews built, but with artifact edge pixels (such as JP2- //! compressed data), it is preferred to build the mask overviews directly from the R0 mask. //! This method will build the remaining number of R-levels from the last defined mask buffer //! such that the total number of R-levels (counting R0) are represented. Returns TRUE if successful. bool buildOverviews(ossim_uint32 total_num_rlevels); //! Computes and writes the mask file according to the specification in the KWL. //! Returns TRUE if successful. virtual bool loadState(const ossimKeywordlist& spec, const char* prefix=0); virtual bool isOpen() const; virtual bool open(); virtual void close(); virtual bool canConnectMyInputTo(ossim_int32 myInputIndex, const ossimConnectableObject* object) const; virtual ossim_int32 connectMyInputTo (ossimConnectableObject *inputObject, bool makeOutputConnection=true, bool createEventFlag=true); protected: friend class ossimBitMaskTileSource; //! Initializes the flipper (used for identifying pixels for masking) to default values void initializeFlipper(); //! Deletes allocated buffers and resets all values to defaults. void reset(); //! Since overviews may not yet exist when the mask is being written, we must compute the //! size of the source image based on the original R0 image size. ossimIpt computeImageSize(ossim_uint32 rlevel, ossimImageData* tile) const; ossimRefPtr m_flipper; ossimRefPtr m_memoryImage; std::vector m_buffers; std::vector m_bufferSizes; ossim_uint32 m_startingResLevel; ossimIpt m_imageSize; //!< Size of full res source image }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimBlendMosaic.h000066400000000000000000000050241352751253100235100ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBlendMosaic.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimBlendMosaic_HEADER #define ossimBlendMosaic_HEADER #include class OSSIMDLLEXPORT ossimBlendMosaic : public ossimImageMosaic { public: ossimBlendMosaic(); ossimBlendMosaic(ossimConnectableObject::ConnectableObjectList& inputSources); virtual ~ossimBlendMosaic(); virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); void setWeight(ossim_uint32 index, double weight); void setWeights(const std::vector& weights); double getWeight(ossim_uint32 index) const; const std::vector& getWeights()const; void setNumberOfWeights(ossim_uint32 numberOfWeights); void setAllWeightsTo(double value); /** * Will find the min and max values and then * normalize all weights to be from 0 to 1 */ void normalizeWeights(); void findMinMax(double& minValue, double& maxValue)const; protected: std::vector theWeights; ossimRefPtr theNormResult; /** * If our inputs have output of different scalar * types then we must normalize so we can blend * different scalar data together. */ template ossimRefPtr combine(T, const ossimIrect& tileRect, ossim_uint32); template ossimRefPtr combineNorm(T, const ossimIrect& tileRect, ossim_uint32); TYPE_DATA }; #endif /* #ifndef ossimBlendMosaic_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimBrightnessContrastSource.h000066400000000000000000000077401352751253100263460ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBrightnessContrastSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimBrightnessContrastSource_HEADER #define ossimBrightnessContrastSource_HEADER #include class OSSIM_DLL ossimBrightnessContrastSource : public ossimImageSourceFilter { public: /** * Currently works in hsi space so must be one or three bands. * * Todo: Make work with nband. */ ossimBrightnessContrastSource(); /** * Will apply the algorithm: * i*c + b * where b is brightnes * c is contrast * i is the input value. * */ virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); /** * @param brightness Value between -1.0 and +1.0 with zero being no * brightness offset. * * @param contrast Value between 0.0 and 2.0 with 1.0 being no contrast * adjustment. */ virtual void setBrightnessContrast(ossim_float64 brightness, ossim_float64 contrast); /** * @param brightness Value between -1.0 and +1.0 with zero being no * brightness offset. */ virtual void setBrightness(ossim_float64 brightness); /** * @param contrast Value between 0.0 and 2.0 with 1.0 being no contrast * adjustment. */ virtual void setContrast(ossim_float64 contrast); /** @return Brightness value between -1.0 and +1.0. */ virtual ossim_float64 getBrightness()const; /** @return Contrast value between 0.0 and +2.0. */ virtual ossim_float64 getContrast()const; /** * Calls base ossimImageSourceFilter::initialize() to reset connection if * needed then nulls out tiles. * * @note This does not initialize tiles intentionally to avoid repeated * deletes and news. Tiles will be initialized by allocate() method on * the first getTile call after an initialize. */ virtual void initialize(); /*---------------------- PROPERTY INTERFACE ---------------------------*/ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /*--------------------- PROPERTY INTERFACE END ------------------------*/ /** * Keywords searched for by this method. * * brightness: 0.0 * * contrast: 1.0 */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Keywords saved to list by this method. * * brightness: 0.0 * * contrast: 1.0 */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: virtual ~ossimBrightnessContrastSource(); /** * Called to initialize tiles by first get tile when theTile or theNormTile * are not initialized. */ void allocate(); /** * Applies the brightness contrast to tile. This method works in hsi * space on the intensity channel; thus, preserving hue and saturation * of an rgb pixel. Called if input has three bands. */ void processRgbTile(); /** * Applies the brightness contrast to tile. This method simply applies * brightness contrast to all bands. Called if input does not have * three bands. */ void processNBandTile(); ossim_float64 theBrightness; ossim_float64 theContrast; ossimRefPtr theTile; ossimRefPtr theNormTile; TYPE_DATA }; #endif /* End of "#ifndef ossimBrightnessContrastSource_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimBrightnessMatch.h000066400000000000000000000035041352751253100244160ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: A brief description of the contents of the file. // //************************************************************************* // $Id: ossimBrightnessMatch.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimBrightnessMatch_HEADER #define ossimBrightnessMatch_HEADER #include #include class ossimBrightnessMatch : public ossimImageSourceFilter { public: ossimBrightnessMatch(); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); /*---------------------- PROPERTY INTERFACE ---------------------------*/ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /*--------------------- PROPERTY INTERFACE END ------------------------*/ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: virtual ~ossimBrightnessMatch(); double theTargetBrightness; double theInputBrightness; ossimRefPtr theNormTile; ossimRefPtr theBrightnessContrastSource; ossimRefPtr runBrightnessMatch(); void computeInputBrightness(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimBumpShadeTileSource.h000066400000000000000000000177471352751253100252160ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBumpShadeTileSource.h 23108 2015-01-27 17:00:20Z okramer $ #ifndef ossimBumpShadeTileSource_HEADER #define ossimBumpShadeTileSource_HEADER #include #include #include class ossimImageData; class ossimImageSourceConnection; /** * This uses a derivative of Blinn's bump function to compute a 3-D * looking image. The elevation data can be from Grey Scale image or from * a Dted file. This class can take one or two inputs. The First input is an * elevation input that is used to compute a perturbed Normal which is * used in a simple lambertian shading equation. The second input is some * color source (Grey or RGB) that defines the diffuse color used within * the illumination equation for each pixel. If the diffuse color input is not * supplied then an all white color is used for the color. There are several * adjustable parameters that can be set: * 1) the Incident light vector described by the Azimuth and Elevation Angle, * 2) the pixel scale used along the x and y direction, and * 3) the partial derivative matrix used for the partial derivative * computation along the x and y direction. * *
 * 
 * Some examples of good values:
 *
 * If we are using dted 90 meters as input for shading then:
 * 1) set pixel scale to 180.  Since the partials do 2*dx and 2*dy then
 *    the scale is 2*90meters = 180.
 * 2) set azimuth angle to 45 and set elevation angle to 45 degrees.  Change
 *    them to see the effects.
 * 3) use the following matrix -1 0 1
 *                             -1 0 1
 *                             -1 0 1
 *                                &
 *                              1  1  1
 *                              0  0  0
 *                             -1 -1 -1
 * 
 *    for the partials along x and y directions respectively.  These matrices
 *
 *    (f(x+dx, y) - f(x-dx, y))/2*dx and
 *    (f(x, y+dy) - f(x, y-dy))/2*dy
 *
 *    for an apprximate derivative about some point x, y
 *
 * If we are using pixel intesity (1 - 255) then set the scales to around
 * 100.
 *
 *  Note: varying the scales will vary the smoothness/roughness of the surface
 *        Smaller the scale the rougher the surface will look.
 *
 * The output of this source is always a 3-band 8-bit image.
 *
 * Keywords:
 *   type:               ossimBumpShadeTileSource
 *   azimuth_angle:      45.000000000000000
 *   elevation_angle:    45.000000000000000
 *   scale_per_pixel_x:  180.000000000000000  // this is the 2*dx defined above
 *   scale_per_pixel_y:  180.000000000000000  // this is the 2*dy defined above
 *
 *   the next set of keywords are optional and the default is as defined above.
 *   these define the matrix.
 *
 *
 * A typical chain would look something like this:
 * 
 * OrthoMosaicOfElevation-->Normals-->Renderer-->|
 *                                               |--> BumpShade-->Output 
 * ColorSource----------------------->Renderer-->|
 *
 * NOTES:
 *
 * 1) "Normals" is an ossimImageToPlaneNormalFilter class
 *
 * 2) The bump map input source is used to bump or shade the input color
 * source.  The input color source currently must be a 1 or 3 band
 * image.  Note that the output of this source is always
 * 3 bands (r, g, b).
 *
 * 3) If no color source (2nd input layer) is present the r,g,b values will be
 * used.  The method setRgbColorSource can be used to control this.
 * 
 * 
* */ class OSSIMDLLEXPORT ossimBumpShadeTileSource : public ossimImageCombiner { public: ossimBumpShadeTileSource(); ossimString getShortName()const; ossimString getLongName()const; ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual bool getTile(ossimImageData* tile, ossim_uint32 resLevel=0); /** * This should always return 3 */ virtual ossim_uint32 getNumberOfOutputBands() const; /** * The output scalar type should always be 8-bit */ virtual ossimScalarType getOutputScalarType() const; /** * the null pixel is 0.0. * \return null pixel value is always 0 * */ virtual double getNullPixelValue()const; /** * the min pixel is 1.0. * \return min pixel value is always 1 * */ virtual double getMinPixelValue(ossim_uint32 band=0)const; /** * the max pixel is 255. * \return max pixel value is always 255 * */ virtual double getMaxPixelValue(ossim_uint32 band=0)const; /** * \return Returns the rotation of the incident vector.. */ virtual double getAzimuthAngle()const; /** * \return Returns the elevation of the incident vector. */ virtual double getElevationAngle()const; /** * */ virtual void setAzimuthAngle(double angle); /** * */ virtual void setElevationAngle(double angle); /** * */ virtual void initialize(); /** * */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * */ bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; /** * */ virtual void connectInputEvent(ossimConnectionEvent& event); /** * */ virtual void disconnectInputEvent(ossimConnectionEvent& event); /** * */ virtual void propertyEvent(ossimPropertyEvent& event); virtual void refreshEvent(ossimRefreshEvent& event); /** * Will re-compute the light direction given the elevation angle and * azimuth angle. */ void computeLightDirection(); /* ------------------- PROPERTY INTERFACE -------------------- */ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /* ------------------ PROPERTY INTERFACE END ------------------- */ /** * @brief Set the red, green and blue color source values. * * This sets the rgb value used when no second layer is present. * * The default is: r = 255, g = 255, b = 255 * * @param r red * @param g green * @param b blue */ void setRgbColorSource(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); /** * Gets the red, green and blue color source values. * @param r red * @param g green * @param b blue */ void getRgbColorSource(ossim_uint8& r, ossim_uint8& g, ossim_uint8& b) const; protected: virtual ~ossimBumpShadeTileSource(); void allocate(); /** * The result of the illumination equation is stored in * here. This is populated on each call to getTile. */ ossimRefPtr m_tile; /** * Used for the light vector computation. */ double m_lightSourceElevationAngle; /** * Used for the light vector computation. */ double m_lightSourceAzimuthAngle; /** * This is computed from the elevation and * azimuth angles of the light source. */ NEWMAT::ColumnVector m_lightDirection; /** * rgb values used when no color source (2nd layer) is present. */ ossim_uint8 m_r; ossim_uint8 m_g; ossim_uint8 m_b; void computeColor(ossim_uint8& r, ossim_uint8& g, ossim_uint8& b, ossim_float64 normalX, ossim_float64 normalY, ossim_float64 normalZ, ossim_uint8 dr, ossim_uint8 dg, ossim_uint8 db)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimCacheTileSource.h000066400000000000000000000056771352751253100243500ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts // // Description: ossimCacheTileSource // //******************************************************************* // $Id$ #ifndef ossimCacheTileSource_HEADER #define ossimCacheTileSource_HEADER 1 #include #include #include #include /** Cache Tile Source */ class OSSIMDLLEXPORT ossimCacheTileSource : public ossimImageSourceFilter { public: typedef std::vector RLevelCacheList; /** * Will construct a new Application cache */ ossimCacheTileSource(); // ossimCacheTileSource(ossimImageSource* inputSource); virtual ~ossimCacheTileSource(); virtual ossimString getLongName() const; virtual ossimString getShortName() const; virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); virtual void flush(); virtual void setCachingEnabledFlag(bool value); virtual void setEventProgressFlag(bool value); void getTileSize(ossimIpt& size) const; /** * @brief Set the tile size. This changes underlying cache tile size. * @param Size of cache tile. */ void setTileSize(const ossimIpt& size); virtual ossim_uint32 getTileWidth() const; virtual ossim_uint32 getTileHeight() const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void setProperty(ossimRefPtr property); virtual void getPropertyNames(std::vector& propertyNames)const; protected: void allocate(); void deleteRlevelCache(); void initializeRlevelCache(); ossimAppFixedTileCache::ossimAppFixedCacheId getCacheId(ossim_uint32 resLevel); virtual void fireProgressEvent(double percentComplete); // virtual ossimRefPtr fillTile(ossim_uint32 resLevel); virtual ossimRefPtr fillTile( const ossimIrect& tileRect, ossim_uint32 resLevel, ossimAppFixedTileCache::ossimAppFixedCacheId cacheId ); ossimRefPtr theTile; ossimIpt theFixedTileSize; bool theCachingEnabled; bool theEventProgressFlag; bool theUseInputTileSizeFlag; RLevelCacheList theRLevelCacheList; ossimIpt theTileSizeXY; /** For lock and unlock. */ TYPE_DATA }; #endif /* end of "#ifndef ossimCacheTileSource_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimCastTileSourceFilter.h000066400000000000000000000063711352751253100253750ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimCastTileSourceFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimCastTileSourceFilter_HEADER #define ossimCastTileSourceFilter_HEADER #include class OSSIMDLLEXPORT ossimCastTileSourceFilter : public ossimImageSourceFilter { public: ossimCastTileSourceFilter(ossimImageSource* inputSource=NULL, ossimScalarType scalarType=OSSIM_UCHAR); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); virtual ossimScalarType getOutputScalarType() const; virtual ossimString getOutputScalarTypeString()const; /** * Sets the output scalar type. */ virtual void setOutputScalarType(ossimScalarType scalarType); virtual void setOutputScalarType(ossimString scalarType); /** * Sets the current resolution level. Returns true on success, false * on error. */ virtual double getNullPixelValue(ossim_uint32 band)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; ossimRefPtr applyCast(ossimRefPtr input); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); /** * Override base class so that a disableSource event does not * reinitialize the object and enable itself. */ virtual void propertyEvent(ossimPropertyEvent& event); virtual void refreshEvent(ossimRefreshEvent& event); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimCastTileSourceFilter(); void allocate(const ossimRefPtr inputTile); ossimRefPtr theTile; ossimScalarType theOutputScalarType; template void castInputToOutput(inType **inBuffer, const double *nullPix, bool inPartialFlag); template void castInputToOutput(inType *inBuffer[], const double *nullInPix, bool inPartialFlag, outType *outBuffer[], const double *nullOutPix, ossim_uint32 numberOfBands); TYPE_DATA }; #endif /* #ifndef ossimCastTileSourceFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimCcfHead.h000066400000000000000000000130441352751253100226060ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: // // Contains class declaration for CcfHead. // // Notes: // - This is not a full blown CCF header class as it only captures the // data needed for loading. // - Currently only version 6 is supported. // //--- // $Id$ #ifndef ossimCcfHead_HEADER #define ossimCcfHead_HEADER 1 #include #include #include #include #include #include #include class ossimIrect; //*************************************************************************** // CLASS: ossimCcfHead //*************************************************************************** class OSSIM_DLL ossimCcfHead : public ossimErrorStatusInterface { public: ossimCcfHead(); ossimCcfHead(const char* ccf_file); ossimCcfHead(std::shared_ptr& str, const std::string& connectionString); ~ossimCcfHead (); /*! * Reads the ccf header and initializes data members. Returns true on * successful read, false on error. */ bool parseCcfHeader(const char* ccf_file); bool parseCcfHeader(std::shared_ptr& str, const std::string& connectionString); virtual std::ostream& print(std::ostream& out) const; ossim_uint32 numberOfReducedResSets() const { return theNumberOfRLevels; } ossim_uint32 numberOfLines(ossim_uint32 reduced_res_level) const; ossim_uint32 numberOfSamples(ossim_uint32 reduced_res_level) const; ossim_uint32 chunksInLineDir(ossim_uint32 reduced_res_level) const; ossim_uint32 chunksInSampleDir(ossim_uint32 reduced_res_level) const; std::streampos startOfData(ossim_uint32 reduced_res_level) const; /*! * Returns the highest available reduced resolution level. * Zero based. */ ossim_uint32 highestReducedResSet() const { return !theNumberOfRLevels ? 0 : (theNumberOfRLevels - 1); } /*! * Returns the zero based image rectangle for the reduced resolution * level passed in. Returns a rectangle of (0,0,0,0) if reduced_res_level * is out of range. */ ossimIrect imageRect(ossim_uint32 reduced_res_level) const; /*! * Returns the ccf file name as a String. */ ossimString imageFile() const { return m_connectionString; } /*! * Returns the radiometry string. */ ossimString radiometry() const { return theRadiometryString; } /*! * Returns the number of bands. */ ossim_uint32 numberOfBands() const { return theNumberOfBands; } /*! * Returns the enumerated pixel type. */ ossimScalarType pixelType() const { return thePixelType; } /*! * Returns the bytes per chunk. */ ossim_uint32 bytesPerChunk() const { return theBytesPerChunk; } /*! * Returns the bytes per chip. */ ossim_uint32 bytesPerChip() const { return theBytesPerChip; } /*! * Returns the number of chips in sample direction of a chunk. */ ossim_uint32 sampleChipsPerChunk() const { return theSampleChipsPerChunk; } /*! * Returns the number of chips in line direction of a chunk. */ ossim_uint32 lineChipsPerChunk() const { return theLineChipsPerChunk; } /*! * Returns the samples per chip. */ ossim_uint32 samplesPerChip() const { return theSamplesPerChip; } /*! * Returns the lines per chip. */ ossim_uint32 linesPerChip() const { return theLinesPerChip; } /*! * Returns the number of pixels in a single band of a chip. * Note: This is not in bytes but in pixels. */ ossim_uint32 chipSizePerBand() const { return theLinesPerChip * theSamplesPerChip; } const std::vector& getValidImageVertices()const { return theValidImageVertices; } private: /*! * Parses a version five header. */ bool parseV5CcfHeader(std::istream& is); /*! * Parses a version six header. */ bool parseV6CcfHeader(std::istream& is); /*! * Parses the radiometry string and initializes "theNumberOfBands" and * "thePixelType". */ void parseRadString(); std::shared_ptr m_ccfStr; std::string m_connectionString; ossim_uint32 theNumberOfBands; ossimScalarType thePixelType; ossimString theFileType; ossim_uint32 theVersionNumber; ossim_uint32 theLinesPerChip; ossim_uint32 theSamplesPerChip; ossim_uint32 theLineChipsPerChunk; ossim_uint32 theSampleChipsPerChunk; ossim_uint32 theRectInFullImageStartLine; ossim_uint32 theRectInFuleImageStartSample; ossim_uint32 theRectInFullImageStopLine; ossim_uint32 theRectInFuleImageStopSample; ossim_uint32 theNumberOfValidImageVertices; std::vector theValidImageVertices; ossim_uint32 theFirstBandHeaderPointer; ossimString theRadiometryString; ossim_uint32 theBytesPerPixel; ossim_uint32 theBytesPerChip; ossim_uint32 theBytesPerChunk; ossimString theCompressionType; ossim_uint32 theNumberOfRLevels; std::vector theOccupiedFlag; std::vector theStartOfData; std::vector theNumberOfLines; std::vector theNumberOfSamples; std::vector theChunksInLineDir; std::vector theChunksInSampleDir; }; #endif // #ifndef CcfHead_HEADER ossim-Miami-2.9.1/include/ossim/imaging/ossimCcfTileSource.h000066400000000000000000000164131352751253100240260ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration for CcfTileSource. // // A ccf (Chip Chunk Format) is a double tiled format. Image data is // arranged in chips and chunks. Each chip is 32 x 32 pixels. Each chunk // is 8 x 8 chips for a single band image. Bands are interleaved by chip // so a rgb image has a red chip a green chip, then a blue chip which // would make the chunk 24 x 8 chips. // //******************************************************************* // $Id: ossimCcfTileSource.h 16075 2009-12-10 15:46:43Z gpotts $ #ifndef ossimCcfTileSource_HEADER #define ossimCcfTileSource_HEADER #include #include #include class ossimImageData; class OSSIM_DLL ossimCcfTileSource : public ossimImageHandler { public: ossimCcfTileSource(); virtual ossimString getShortName()const; virtual ossimString getLongName()const; /** * @return Returns true on success, false on error. * * @note This method relies on the data member ossimImageData::theImageFile * being set. Callers should do a "setFilename" prior to calling this * method or use the ossimImageHandler::open that takes a file name and an * entry index. */ virtual bool open(); virtual void close(); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Returns the number of bands in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; virtual ossim_uint32 getNumberOfOutputBands()const; /** * Returns the number of lines in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines( ossim_uint32 reduced_res_level = 0) const; /** * Returns the number of samples in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples( ossim_uint32 reduced_res_level = 0) const; /** * Returns the number of reduced resolution data sets (rrds). * Note: The full res image is counted as a data set so an image with no * reduced resolution data set will have a count of one. */ virtual ossim_uint32 getNumberOfDecimationLevels() const; /** * Returns the zero based image rectangle for the reduced resolution data * set (rrds) passed in. Note that rrds 0 is the highest resolution rrds. */ virtual ossimIrect getImageRectangle( ossim_uint32 reduced_res_level = 0) const; /** * Set the output band list. Use to set the number and order of output * bands. Will set an error if out of range. */ bool setOutputBandList(const std::vector& outputBandList); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; virtual bool isOpen()const; /** * @brief Gets a property for matching name. * @param name The name of the property to get. * @return Returns property matching "name". */ virtual ossimRefPtr getProperty( const ossimString& name)const; /** * @brief Gets a list of property names available. * @param propertyNames The list to push back names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimCcfTileSource(); void initVerticesFromHeader(); // Disallow these... ossimCcfTileSource(const ossimCcfTileSource& source); ossimCcfTileSource& operator=(const ossimCcfTileSource& source); /** * Returns true on success, false on error. */ bool fillBuffer(const ossimIrect& tile_rect, const ossimIrect& clip_rect, const ossimIrect& image_rect, ossim_uint32 reduced_res_level, ossimImageData* tile); /** * Returns true on success, false on error. */ bool fillUshortBuffer(const ossimIrect& tile_rect, const ossimIrect& clip_rect, const ossimIrect& image_rect, ossim_uint32 reduced_res_level, ossimImageData* tile); /** * Returns true on success, false on error. */ bool fillUcharBuffer(const ossimIrect& tile_rect, const ossimIrect& clip_rect, const ossimIrect& image_rect, ossim_uint32 reduced_res_level, ossimImageData* tile); /** * Adjust point to even 256 boundary. Assumes 0,0 origin. */ void adjustToStartOfChunk(ossimIpt& pt) const; /** * Adjust point to even 32 boundary. Assumes 0,0 origin. */ void adjustToStartOfChip(ossimIpt& pt) const; bool isEcgGeom(const ossimFilename& filename)const; ossimCcfHead theCcfHead; ossimRefPtr theTile; ossim_uint8* theChipBuffer; std::ifstream* theFileStr; std::vector theOutputBandList; ossim_int32 theByteOrder; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimCibCadrgTileSource.h000066400000000000000000000500611352751253100247660ustar00rootroot00000000000000//----------------------------------------------------------------------- // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This class give the capability to access tiles from an // CADRG file. // //----------------------------------------------------------------------- //$Id: ossimCibCadrgTileSource.h 17954 2010-08-21 20:39:47Z dburken $ #ifndef ossimCibCadrgTileSource_HEADER #define ossimCibCadrgTileSource_HEADER 1 #include #include class ossimRpfToc; class ossimRpfTocEntry; class ossimRpfFrame; /** * CIB/CADRG formats are encoded the same except that the CIB is a grey * scale image and the CADRG is a color image. Both are VQ compressed. * The images are encoded into an NITF format with embedded RPF headers. * It reads the embedded RPF tags from the NITF file and parses the data. * It allows for you to select which CIB/CADRG entry to render. The handler * is opened by giving it the associated a.toc file. This is a table of * contents file that describes all the entries found in the CIB/CADRG * product. You must set which entry you wish to render. By default it * will render the first product it comes to. * * Note: This handler will eventually merge into the nitf handler. */ class OSSIMDLLEXPORT ossimCibCadrgTileSource : public ossimImageHandler { public: friend class ossimMultiEntryCibCadrg; /** * Basic enumeration. This should * be either a CIB or a CADRG product * type. */ enum ossimCibCadrgProductType { OSSIM_PRODUCT_TYPE_UNKNOWN = 0, OSSIM_PRODUCT_TYPE_CIB = 1, OSSIM_PRODUCT_TYPE_CADRG = 2 }; /** * Default constructor. * * Initializes all internal attributes to a default state. */ ossimCibCadrgTileSource(); /** * This method is defined in the base class ossimObject. * This class overrides the default implementation * to return its own short name. * * @return The short name for this class as an ossimString. */ virtual ossimString getShortName()const; /** * This method is defined in the base class ossimObject. * This class overrides the default implementation * to return its own long name. * * @return The long name for this class as an ossimString. */ virtual ossimString getLongName()const; /** * Closes this image handler and deletes any allocated data. */ virtual void close(); /** */ virtual bool open(); /** * Changes the way the open() routine functions slightly. * * @param bSkipEmptyCheck If true, the RPF file is opened even * if all the frame files are missing. By default this is * set to false. */ void setSkipEmptyCheck( bool bSkipEmptyCheck = false ); /** * Returns a pointer to an ossimImageDataObject given a rectangluar * region of interest. * * @param rect The region of interest to return. * @param resLevel From which resolution set are we querying * (default is 0 full res). * * @return The ossimImageData object to the caller. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel = 0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Satisfies pure virtual requirement from ImageHandler class. * * @param reduced_res_level The reduced res level to query number of lines from. * @return The number of lines in the image. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; /** * Satisfies pure virtual requirement from ImageHandler class. * * @param reduced_res_level The reduced res level to query number of samples from. * @return The number of samples in the image. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; /** * @param reduced_res_level Which res level to get the bounds for. 0 represents * the default and is the full resolution. * * @return A rectangle representing the bounds for the passed in resolution level. */ virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const; /** * Method to save the state of an object to a keyword list. * * Saving data without a prefix. * @code * ossimCibCadrgTileSource* cibCadrgHandler = new ossimCibCadrgTileSource; * ossimKeywordlist kwl; * cibCadrgHandler->open(filename); * cibCadrgHandler->saveState(kwl); * @endcode * * and saving data with a prefix. * @code * ossimCibCadrgTileSource* cibCadrgHandler = new ossimCibCadrgTileSource; * ossimKeywordlist kwl; * cibCadrgHandler->open(filename); * cibCadrgHandler->saveState(kwl, "handler1."); * @endcode * * Saving with a prefix will help uniquely identify objects in the kwl. * To see what is in the keywordlist after a save state then do: * * @code * cout << kwl << std::endl; * @endcode * * There is only 1 keyword for this object: * * entry: * * where is the index value for the current entry. * * @see ossimImageHandler for additional keywords. * * @param kwl Keywordlist to save the state of the object to. * @param prefix prefix to prepend to the keywords. This will * help uniquely identify each keyword if multiple * objects are saved to the same list. * @return True if successfully saved the state of the object and * false otherwise. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to load the state of an object from a keyword list. * * Loading with a prefix. * @code * cibCadrgHandler->laodState(kwl, "handler1."); * @endcode * * Loading without a prefix. * @code * cibCadrgHandler->laodState(kwl); * @endcode * * Since all objects are factory created you can go through the * registry and pass the keyword list in. * @code * ossimImageHandler* handler = ossimImageHandlerRegistry::instance()->open(kwl, prefix); * @endcode * * @param kwl Keywordlist that holds the state information for this * object. * * * @param prefix prefix value prepended to all keywords to uniquely * locate the state attributes for this object. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Populates the geometry object with image geometry information. This * method is used to relay projection/model information to users. * Returns true if geometry info is present, false if not. * Keywords supported by this class are: * @verbatim * datum: // datum code> // Datum code * ul_lat: // upper left latitude * ul_lon: // upper left longitude * ll_lat: // lower left latitude * ll_lon: // lower left longitude * lr_lat: // lower right latitude * lr_lon: // lower right longitude * ur_lat: // upper right latitude * ur_lon: // upper right longitude * number_input_bands: * number_output_bands: * number_lines: * number_samples: * decimal_degrees_per_pixel_lat: // specifies the spacing per pixel along Y direction * decimal_degrees_per_pixel_lon: // specifies the spacing per pixel along X direction * origin_latitude: // specifies the origin or center of the projector for the latitude * central_meridian: // specifies the origin or center of the projector for the longitude * tie_point_lat: // tie point lat. Represents the latitude of the upper left center of pixel * tie_point_lon: // tie point lon. Represents the longitude of the upper left center of pixel * zone: // zone read from the CIB/CADRG boundary info * type: // class name of the object for factory driven reconstruction * map_scale: // Map scale of the image * @endverbatim * @see ossimImageSource for further code example on using the geometry. */ virtual ossimRefPtr getImageGeometry(); /** * This method allows you to query the scalar type of the output data. * This is simply the data type, i.e. whether its OSSIM_FLOAT, OSSIM_DOUBLE, * OSSIM_UCHAR, ... etc. This means that if there are bands of different * scalar types from a single image then they must be casted to the highest * precision type. @see ossimConstants.h for all ossimScalarType. * * @return The output scalar type. * */ virtual ossimScalarType getOutputScalarType() const; /** * This method allows you to query the number of input bands. If an image * is band selectable this will allow one to select the bands you wish * to read in. This indicates that the number of input bands might not * match the number of output bands. * @return number of input bands. */ virtual ossim_uint32 getNumberOfInputBands()const; /** * This method allows one to query the number of output bands. This might not * be the same as the n umber of input bands. * * @see getNumberOfInputBands(). * @return number of output bands. */ virtual ossim_uint32 getNumberOfOutputBands()const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; virtual ossim_uint32 getCurrentEntry()const; virtual bool setCurrentEntry(ossim_uint32 entryIdx); virtual void getEntryList(std::vector& entryList)const; /** * Returns -1 if invalid */ virtual ossim_int32 getCurrentEntryIndex()const; /** * @return The current entry being rendered */ virtual const ossimRpfTocEntry* getCurrentTocEntry()const; /** * @return The table of contents object. */ virtual const ossimRpfToc* getToc()const; /** * @param reduced_res_level passed in resolution level. * @return True if the reduced_res_level is within an acceptable range * and false otherwise. */ bool isValidRLevel(ossim_uint32 reduced_res_level) const; /** * Determines if its open if there eists a table of contents object. * * @return True if the handler is open and flase otherwise. */ bool isOpen()const; /** @return true if CIB */ bool isCib() const; /** @return true if CADRG */ bool isCadrg() const; /** @return Scale string ( like 1:24000 ) for current entry. */ ossimString getProductScale() const; /** * This retrieves all product scales that are within the Table of contents. * I make no assumptions that a CIB/CADRG has only one product. A product * here is 1meter, 5 meter, 10 meter ... etc for CIB and 1:24000, 1:50000, * ... etc for CADRG. * * @return The prduct list as a vector of strings. */ std::vector getProductScaleList()const; /** * Using the product scales from getProductScaleList() you can pass each string * in so you can get all associated indices for a given product. * * @return Entry indices for a passed in product scale. */ std::vector getProductEntryList(const ossimString& productScale)const; ossimString getSecurityClassification()const; /** * @brief Gets a property for matching name. * @param name The name of the property to get. * @return Returns property matching "name". */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Gets a list of property names available. * @param propertyNames The list to push back names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; /** * CONSTANT representing the width of a Frame. This should be 1536. */ static const ossim_uint32 CIBCADRG_FRAME_WIDTH; /** * CONSTANT representing the height of a Frame. This should be 1536. */ static const ossim_uint32 CIBCADRG_FRAME_HEIGHT; protected: /** * Destructor. * * Will return allocated memory back to the heap. */ virtual ~ossimCibCadrgTileSource(); void updatePropertiesToFirstValidFrame(); /** * Sets the entry to be renderer. The entry within the table * of contents are stored in an Toc entry object. * * @param entry the Rpf toc entry object to set to. */ virtual void setTocEntryToRender(const ossimRpfTocEntry* entry); /** * Protected structure that is only used internally by this class. * * This is used to establish which entry data is being used. * all we need is the ro, col of the entry. We can compute the * image rect from this since the CibCadrg are 1536x1536 frame. * */ struct ossimFrameEntryData { ossimFrameEntryData() :theRow(-1), theCol(-1), thePixelRow(-1), thePixelCol(-1) {} ossimFrameEntryData(ossim_int32 row, ossim_int32 col, ossim_int32 pixelRow, ossim_int32 pixelCol, const ossimRpfFrameEntry& entry) :theRow(row), theCol(col), thePixelRow(pixelRow), thePixelCol(pixelCol), theFrameEntry(entry) {} ossimFrameEntryData(const ossimFrameEntryData& rhs) :theRow(rhs.theRow), theCol(rhs.theCol), thePixelRow(rhs.thePixelRow), thePixelCol(rhs.thePixelCol), theFrameEntry(rhs.theFrameEntry) {} ossim_int32 theRow; ossim_int32 theCol; ossim_int32 thePixelRow; ossim_int32 thePixelCol; ossimRpfFrameEntry theFrameEntry; }; /** * Sets the entry to render. * */ virtual bool setEntryToRender(ossim_uint32 index); /** * It is important to note that each frame is organized into an easting northing * type orientation. This means that a frame at 0,0 is at the lower left corner. * Each frame's pixel data is has 0,0 at the upper left. * * It will take the curent region to render and then find all entries that intersect * that region. * * @param rect the current region to render. * @return The list of entry data objects found for this rect. */ std::vector getIntersectingEntries(const ossimIrect& rect); /** * This is a wrapper for the fill cib and fill cadrg. It takes the frames * involved that were found in the getIntersectingEntries and call the * appropriate fill cib or fill cadrg on each frame entry data. It will * loop through making sure that the frame file exists before calling * the associated fill routines. * * @param tileRect Region to fill. * @param framesInvolved All intersecting frames used to render the region. */ void fillTile(const ossimIrect& tileRect, const std::vector& framesInvolved, ossimImageData* tile); /** * Will uncompress the CIB file using a VQ decompression algorithm. * * @param aFrame Frame that overlaps the requested tile rect. * @param tileRect The region requested to render. * @param frameEntryData The frame entry data. */ void fillSubTileCib(const ossimRpfFrame& aFrame, const ossimIrect& tileRect, const ossimFrameEntryData& frameEntryData, ossimImageData* tile); /** * Will uncompress the CADRG file using a VQ decompression algorithm. * * @param aFrame Frame that overlaps the requested tile rect. * @param tileRect The region requested to render. * @param frameEntryData The frame entry data. */ void fillSubTileCadrg(const ossimRpfFrame& aFrame, const ossimIrect& tileRect, const ossimFrameEntryData& frameEntryData, ossimImageData* tile); /** * Will allocate an internal buffer for the given product. If the product is * a CIB then it is a single band OSSIM_UCHAR buffer and if its a CADRG it * is a 3 band OSSIM_UCHAR buffer. */ void allocateForProduct(); /** * This will search each entry in the table and look for a certain * entry. The first entry it comes to that has Geographic coverage * will be the frame to render. This method is best here instead of * in the ossimRpfToc. I am not sure, but I feel these types of * searches are specific to the product (CADRG, CIB ...). This * is called immediately after a succesful open of the ossimRpfToc */ const ossimRpfTocEntry* findFirstFrame(); void deleteAll(); void populateLut(); /** * This is for storage of a single compressed buffer. */ unsigned char* theCompressedBuffer; /** * This is used as a buffer to uncompress the data to */ unsigned char* theUncompressedBuffer; /** * This will be computed based on the frames organized within * the directory. The CibCadrg have fixed size frames of 1536x1536 * and we must count how many there are. */ ossim_uint32 theNumberOfLines; /** * This will be computed based on the frames organized within * the directory. The CibCadrg have fixed size frames of 1536x1536 * and we must count how many there are. */ ossim_uint32 theNumberOfSamples; /** * This is the actual data returned from a getTile request. */ ossimRefPtr theTile; /** * Will own a table of contents. This describes all entries within * the CIB/CADRG. */ ossimRpfToc* theTableOfContents; /** * This is the actual frame file to render. This should be * divided into frames where each frame is 1536x1536 in * size. */ const ossimRpfTocEntry* theEntryToRender; /** * This will be the entry number that we are currently * rendering. This will mainly be used when using * overviews. */ ossim_int32 theEntryNumberToRender; /** * Holds the enumeration specifying the product type. * The product type can be a CIB or a CADRG product. */ ossimCibCadrgProductType theProductType; mutable ossimRpfFrame* theWorkFrame; /** * If true during the call to open(), the RPF file is opened even * if all the frame files are missing. By default this is set to false. */ bool theSkipEmptyCheck; // data to use in property retrieval TYPE_DATA }; #endif /* #ifndef ossimCibCadrgTileSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimClosestToCenterCombiner.h000066400000000000000000000037041352751253100260720ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimClosestToCenterCombiner.h 22162 2013-02-26 01:37:48Z gpotts $ #ifndef ossimClosestToCenterCombiner_HEADER #define ossimClosestToCenterCombiner_HEADER #include #include /** * This implements a closest to center combiner. * * It will first grab all images overlapping a given rectangle query. The first non-null * closest pixel to the center of the image is used. This basically uses only pixels along * the "sweet" spot of the image. This combiner is typically used when there is overlapping * sensor data. * */ class OSSIM_DLL ossimClosestToCenterCombiner : public ossimImageMosaic { public: ossimClosestToCenterCombiner(); /** * Executes the ossimClosestToCenterCombiner algorithm. sets the pixels to the closest * Valid value. This simulates a sweet spot cutter. * * @param rect The region of interest. * @param resLevel. For this combiner this is assumed to always be 0 */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); protected: class ossimClosestToCenterCombinerInfo { public: ossimClosestToCenterCombinerInfo(ossimRefPtr tile, ossim_int32 idx) :theTile(tile), theIndex(idx) { } ossimRefPtr theTile; ossim_int32 theIndex; }; ossim_int32 findIdx(const std::vector& normTileList, const ossimIpt& pt, ossim_uint32 offset)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimCodecBase.h000066400000000000000000000035031352751253100231400ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: class declaration for base codec(encoder/decoder). // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimCodecBase_HEADER #define ossimCodecBase_HEADER 1 #include #include #include class OSSIM_DLL ossimCodecBase : public ossimObject, public ossimPropertyInterface { public: /** * Will return the identifier used to identify the codec type. For example the Jpeg codec * will have "jpeg" as the identifier * * @return Codec identifier */ virtual ossimString getCodecType()const=0; /** * @brief Encode method. * * Pure virtual method that encodes the passed in buffer to this codec. * * @param in Input data to encode. * * @param out Encoded output data. * * @return true on success, false on failure. */ virtual bool encode( const ossimRefPtr& in, std::vector& out ) const=0; /** * @brief Decode method. * * @param in Input data to decode. * * @param out Output tile. If the pointer to ossimImageData is null * internally it will be created. For code loops it is better to pre * initialized to correct size. * * @note Caller should set "out's" image rectangle upon successful * decode. * * @return true on success, false on failure. */ virtual bool decode( const std::vector& in, ossimRefPtr& out ) const=0; virtual const std::string& getExtension() const=0; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimCodecFactory.h000066400000000000000000000040221352751253100236720ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Factory class declaration for codec(encoder/decoder). // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimCodecFactory_HEADER #define ossimCodecFactory_HEADER 1 #include #include class ossimFilename; class ossimCodecBase; /** * @brief Codec factory. */ class OSSIM_DLL ossimCodecFactory : public ossimCodecFactoryInterface { public: /** virtual destructor */ virtual ~ossimCodecFactory(); /** * @return instance */ static ossimCodecFactory* instance(); /** * createCodec takes a type and will return a new codec to encode decode image buffers * * @param in type. Type identifer used to allocate the proper codec. * @return ossimCodecBase type. */ virtual ossimCodecBase* createCodec(const ossimString& type)const; /** * createCodec takes a type in the keywordlist and will return a new codec to encode decode image buffers * * @param in kwl. Type identifer used to allocate the proper codec. * @param in prefix. prefix used to prefix keywords during the construction * of the codec * @return ossimCodecBase type. */ virtual ossimCodecBase* createCodec(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual void getTypeNameList(std::vector& typeNames)const; private: /** hidden from use default constructor */ ossimCodecFactory(); /** hidden from use copy constructor */ ossimCodecFactory(const ossimCodecFactory& obj); /** hidden from use operator = */ const ossimCodecFactory& operator=(const ossimCodecFactory& rhs); /** The single instance of this class. */ static ossimCodecFactory* theInstance; }; #endif /* End of "#ifndef ossimCodecFactory_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimCodecFactoryInterface.h000066400000000000000000000051531352751253100255210ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Interface for codec(encoder/decoder) factories. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimCodecFactoryInterface_HEADER #define ossimCodecFactoryInterface_HEADER 1 #include #include #include #include #include class ossimObject; class ossimCodecBase; /** * @brief Codec factory interface. */ class OSSIM_DLL ossimCodecFactoryInterface // : public ossimObjectFactory { public: /** default constructor */ ossimCodecFactoryInterface(){} /** virtual destructor */ virtual ~ossimCodecFactoryInterface(){} /** * This is a bridge to the generic factory list interface that trys to call createObject * * We will bridge it in this interface to just call createCodec. These are not pure virtual. * */ virtual ossimObject* createObject(const ossimString& type)const; /** * This is a bridge to the generic factory list interface that trys to call createObject * * We will bridge it in this interface to just call createCodec. These are not pure virtual. * */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual ossimCodecBase* createCodec(const ossimString& type)const=0; virtual ossimCodecBase* createCodec(const ossimKeywordlist& kwl, const char* prefix=0)const=0; virtual void getTypeNameList(std::vector& typeNames)const=0; /** * @brief Pure virtual decode method. Derived classes must implement to * be concrete. * * @param in Input data to decode. * * @param out Output tile. * * @return true on success, false on failure. */ // virtual bool decode( const std::vector& in, // ossimRefPtr& out ) const = 0; /** * @brief Pure virtual encode method. Derived classes must implement to * be concrete. * * @param in Input data to encode. * * @param out Encoded output data. * * @return true on success, false on failure. */ // virtual bool encode( const ossimKeywordlist& options, // const ossimRefPtr& in, // std::vector& out ) const = 0; }; #endif /* End of "#ifndef ossimCodecFactoryInterface_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimCodecFactoryRegistry.h000066400000000000000000000034431352751253100254310ustar00rootroot00000000000000#ifndef ossimCodecFactoryRegistry_HEADER #define ossimCodecFactoryRegistry_HEADER #include #include #include class OSSIM_DLL ossimCodecFactoryRegistry : public ossimFactoryListInterface { public: static ossimCodecFactoryRegistry* instance(); virtual ~ossimCodecFactoryRegistry(); /** * Will loop through all registered factories trying to allocate a codec for the passed * in type. * * @param in type. Type of Codec to allocate. * @return ossimCodecBase. Newly allocated Codec */ virtual ossimCodecBase* createCodec(const ossimString& type)const; /** * Will loop through all registered factories trying to allocate a codec for the passed * in type in the type keyword of the keywordlist. * * @param in kwl. State infromation to load when allocating the codec * @param in prefix. prefix value for all keys * * @return ossimCodecBase. Newly allocated codec */ virtual ossimCodecBase* createCodec(const ossimKeywordlist& kwl, const char* prefix=0)const; /** * Loop through all factories and get a list of supported types. * * @param out typeNames. The resulting typename list. Values will be appended. */ virtual void getTypeNameList(std::vector& typeNames)const; private: /** hidden from use default constructor */ ossimCodecFactoryRegistry(); /** hidden from use copy constructor */ ossimCodecFactoryRegistry(const ossimCodecFactoryRegistry& obj); /** hidden from use operator = */ const ossimCodecFactoryRegistry& operator=(const ossimCodecFactoryRegistry& rhs); static ossimCodecFactoryRegistry* m_instance; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimColorNormalizedFusion.h000066400000000000000000000016461352751253100256250ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Color normalized fusion // //************************************************************************* // $Id: ossimColorNormalizedFusion.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimColorNormalizedFusion_HEADER #define ossimColorNormalizedFusion_HEADER #include class ossimColorNormalizedFusion : public ossimFusionCombiner { public: ossimColorNormalizedFusion(); ossimColorNormalizedFusion(ossimObject* owner); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); protected: virtual ~ossimColorNormalizedFusion(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimConvolutionFilter1D.h000066400000000000000000000107601352751253100252050ustar00rootroot00000000000000//******************************************************************* // License: MIT // // See LICENSE.txt file in the top level directory for more details. // class ossimImageGaussianFilter : tile source // class ossimConvolutionFilter1D // one dimensional convolution // // efficient for gradients & separable convolution kernels (like gaussian) //******************************************************************* // $Id: ossimConvolutionFilter1D.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimConvolutionFilter1D_HEADER #define ossimConvolutionFilter1D_HEADER #include /** * class for vertical or horizontal convolution * * PROPERTIES: * -KernelSize : length of linear kernel (>=1) NOTE - you need to exit the property editor for the kernel to be resized * -Kernel : Kernel vector (line matrix) * -Horizontal : boolean, otherwise vertical kernel * -CenterOffset : center pixel position in the kernel, starting at 0 * -StrictNoData : controls NODATA use * true : any NODATA pixel in the convolution will make the center pixel NODATA * false : if center is NODATA, then output center is NODATA, * other NODATA pixels are processed as if they were zero in the convolution */ class OSSIM_DLL ossimConvolutionFilter1D : public ossimImageSourceFilter { public: /** * own class methods */ ossimConvolutionFilter1D(ossimObject* owner=NULL); virtual inline const std::vector& getKernel()const { return theKernel; } virtual void setKernel(const std::vector& aKernel); virtual inline bool isHorizontal()const { return theIsHz; } virtual inline void setIsHorizontal(bool aIsHz) { theIsHz = aIsHz; } virtual inline ossim_int32 getCenterOffset()const { return theCenterOffset; } virtual inline void setCenterOffset(ossim_int32 aCenterOffset) { theCenterOffset = aCenterOffset; } virtual inline bool isStrictNoData()const { return theStrictNoData; } virtual inline void setStrictNoData(bool aStrict) { theStrictNoData = aStrict; } /** * inherited methods */ virtual ossimString getShortName()const{return ossimString("1D Convolution");} virtual ossimString getLongName()const{return ossimString("Convolves the input image with a one dimensional convolution kernel");} virtual ossimRefPtr getTile(const ossimIrect& tileRect,ossim_uint32 resLevel=0); virtual void initialize(); virtual double getNullPixelValue(ossim_uint32 band=0) const; virtual double getMinPixelValue(ossim_uint32 band=0) const; virtual double getMaxPixelValue(ossim_uint32 band=0) const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool loadState(const ossimKeywordlist& kwl,const char* prefix = 0); virtual bool saveState(ossimKeywordlist& kwl,const char* prefix = 0)const; protected: virtual ~ossimConvolutionFilter1D(); /** * Allocates theTile. */ void allocate(); /** * Clears data members theNullPixValue, theMinPixValue, and * theMaxPixValue. */ void clearNullMinMax(); /** * Computes null, min, and max considering input connection and theKernel. */ void computeNullMinMax(); /*! * Convolve full means that the input data is full and has * no null data. We don't have to compare for nulls here */ template void convolveFull(T, ossimRefPtr inputData, ossimRefPtr outputData); /*! * Convolve partial means that the input data is has some * null data. We will have to compare nulls */ template void convolvePartial(T, ossimRefPtr inputData, ossimRefPtr outputData); //! offset of center point in the Kernel ossim_int32 theCenterOffset; ossimRefPtr theTile; std::vector theKernel; bool theIsHz; //! isHorizontal convolution? bool theStrictNoData; //! strictly no NODATA values used std::vector theNullPixValue; std::vector theMinPixValue; std::vector theMaxPixValue; TYPE_DATA }; #endif /* #ifndef ossimConvolutionFilter1D_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimConvolutionSource.h000066400000000000000000000046031352751253100250320ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimConvolutionSource.h 22233 2013-04-15 15:12:54Z gpotts $ #ifndef ossimConvolutionSource_HEADER #define ossimConvolutionSource_HEADER #include #include #include #include class ossimTilePatch; class ossimDiscreteConvolutionKernel; class OSSIM_DLL ossimConvolutionSource : public ossimImageSourceFilter { public: ossimConvolutionSource(); ossimConvolutionSource(ossimImageSource* inputSource, const NEWMAT::Matrix& convolutionMatix); ossimConvolutionSource(ossimImageSource* inputSource, const std::vector& convolutionList); virtual void setConvolution(const double* kernel, int nrows, int ncols, bool doWeightedAverage=false); virtual void setConvolution(const NEWMAT::Matrix& convolutionMatrix, bool doWeightedAverage=false); virtual void setConvolutionList(const std::vector& convolutionList, bool doWeightedAverage=false); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); protected: virtual ~ossimConvolutionSource(); void allocate(); ossimRefPtr theTile; ossim_int32 theMaxKernelWidth; ossim_int32 theMaxKernelHeight; std::vector theConvolutionKernelList; virtual void setKernelInformation(); virtual void deleteConvolutionList(); template void convolve(T dummyVariable, ossimRefPtr inputTile, ossimDiscreteConvolutionKernel* kernel); TYPE_DATA }; #endif /* #ifndef ossimConvolutionSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimDespeckleFilter.h000066400000000000000000000032661352751253100244030ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //******************************************************************* // $Id: ossimDespeckleFilter.h 2644 2011-05-26 15:20:11Z oscar.kramer $ #ifndef ossimDespeckleFilter_HEADER #define ossimDespeckleFilter_HEADER #include class ossimDespeckleFilter : public ossimImageSourceFilter { public: ossimDespeckleFilter(); ossimDespeckleFilter(ossimImageSource* inputSource, ossim_uint32 filter_radius=1); virtual void setRadius(ossim_uint32 radius) { theFilterRadius = (ossim_int32) radius; } virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); /* ------------------- PROPERTY INTERFACE -------------------- */ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /* ------------------ PROPERTY INTERFACE END ------------------- */ protected: virtual ~ossimDespeckleFilter(); template void despeckle(T dummyVariable, ossimRefPtr inputTile); void allocate(); ossimRefPtr theTile; ossim_int32 theFilterRadius; TYPE_DATA }; #endif /* #ifndef ossimDespeckleFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimDilationFilter.h000066400000000000000000000051251352751253100242430ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM // // License: MIT. See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #ifndef ossimDilationFilter_HEADER #define ossimDilationFilter_HEADER #include #include /*! * class ossimDilationFilter * * Allows you to change between a median or mean filter. You can * also specify a window size which the median or mean is computed and * the center pixel is replaced. * */ class OSSIM_DLL ossimDilationFilter : public ossimImageSourceFilter { public: ossimDilationFilter(ossimObject* owner=NULL); virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Size of resampling kernel width & height */ void setWindowSize(ossim_uint32 windowSize) { theWindowSize = windowSize; } ossim_uint32 getWindowSize() const { return theWindowSize; } /** * Set if getTile is to be called recursively until all pixels have been assigned non-null. * This is only valid for "fill null" modes. */ void setRecursiveFlag(bool flag=true) { theRecursiveFlag = flag; } bool getRecursiveFlag() const { return theRecursiveFlag; } virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimDilationFilter(); ossimRefPtr theTile; ossimRefPtr theTempTile; //!> Used for recursion when recursive fill enabled ossim_uint32 theWindowSize; bool theRecursiveFlag; ossimPolygon theValidImagePoly; bool theNullFoundFlag; template void doDilation(T scalarType, ossimRefPtr& inputData); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimDiscrete3x3HatFilter.h000066400000000000000000000034431352751253100252360ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimDiscrete3x3HatFilter.h 11418 2007-07-27 16:24:15Z dburken $ #ifndef ossimDiscrete3x3HatFilter_HEADER #define ossimDiscrete3x3HatFilter_HEADER #include class ossimDiscrete3x3HatFilter : public ossimDiscreteConvolutionKernel { public: ossimDiscrete3x3HatFilter(); /*! * Will expect a data buffer of size width*height * and is row ordered. */ virtual void convolve(const float* data, double& result, float nullPixel=OSSIM_DEFAULT_NULL_PIX_FLOAT)const; virtual void convolveSubImage(const float* data, long dataWidth, double& result, float nullPixel=OSSIM_DEFAULT_NULL_PIX_FLOAT)const; virtual void convolve(const unsigned char* data, double& result, ossim_uint8 nullPixel=OSSIM_DEFAULT_NULL_PIX_UINT8)const; /*! * this allows you to pass a subImage to * the convolution engine. It needs to know * the width of the buffer so it can increment * to the next element. */ virtual void convolveSubImage(const unsigned char* data, long dataWidth, double& result, ossim_uint8 nullPixel=OSSIM_DEFAULT_NULL_PIX_UINT8)const; virtual void buildConvolution(double widthPercent, double heightPercent); }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimDiscreteConvolutionKernel.h000066400000000000000000000117721352751253100265020ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id: ossimDiscreteConvolutionKernel.h 17195 2010-04-23 17:32:18Z dburken $ #ifndef ossimDiscreteConvolutionKernel_HEADER #define ossimDiscreteConvolutionKernel_HEADER #include #include #include #include class ossimDiscreteConvolutionKernel { public: ossimDiscreteConvolutionKernel(long width, long height, bool doWeightedAverage=true); ossimDiscreteConvolutionKernel(const NEWMAT::Matrix& kernel, bool doWeightedAverage=true); virtual ~ossimDiscreteConvolutionKernel(); static void buildSymmetric(const std::vector& coefficients, NEWMAT::Matrix& result); static void buildSymmetric(float* coefficients, long size, NEWMAT::Matrix& result); virtual void setKernel(const NEWMAT::Matrix& kernel); /*! * Will expect a data buffer of size width*height * and is row ordered. */ virtual void convolve(const float* data, double& result, float nullPixel=OSSIM_DEFAULT_NULL_PIX_FLOAT)const; virtual void convolveSubImage(const float* data, long dataWidth, double& result, float nullPixel=OSSIM_DEFAULT_NULL_PIX_FLOAT)const; /*! * Will expect a data buffer of size width*height * and is row ordered. */ virtual void convolve(const double* data, double& result, double nullPixel=OSSIM_DEFAULT_NULL_PIX_DOUBLE)const; virtual void convolveSubImage(const double* data, long dataWidth, double& result, double nullPixel=OSSIM_DEFAULT_NULL_PIX_DOUBLE)const; /*! * Will expect a data buffer of size width*height * and is row ordered. */ virtual void convolve(const short* data, double& result, ossim_sint16 nullPixel=OSSIM_DEFAULT_NULL_PIX_SINT16)const; virtual void convolveSubImage(const short* data, long dataWidth, double& result, ossim_sint16 nullPixel=OSSIM_DEFAULT_NULL_PIX_SINT16)const; /*! * Will expect a data buffer of size width*height * and is row ordered. */ virtual void convolve(const unsigned short* data, double& result, ossim_uint16 nullPixel=OSSIM_DEFAULT_NULL_PIX_UINT16)const; virtual void convolveSubImage(const unsigned short* data, long dataWidth, double& result, ossim_uint16 nullPixel=OSSIM_DEFAULT_NULL_PIX_UINT16)const; virtual void convolve(const unsigned char* data, double& result, ossim_uint8 nullPixel=OSSIM_DEFAULT_NULL_PIX_UINT8)const; /*! * this allows you to pass a subImage to * the convolution engine. It needs to know * the width of the buffer so it can increment * to the next element. */ virtual void convolveSubImage(const unsigned char* data, long dataWidth, double& result, ossim_uint8 nullPixel=OSSIM_DEFAULT_NULL_PIX_UINT8)const; /*! * This is used to allow me to continually adjust a convolution kernel * based on where it center lies on a pixel. The xLocation and yLocation * are all from the center of pixel. If I am convolving at full resolution * then xLocation and yLocation should both be 0. Let's pretend that we * contract an image by .5 scale factor or zooming out by a factor of 2. Then * we actually of it .5 off from cneter of pixel in both the x and y direction. * This information can be used to allow a kernel to adjust it's waits accordingly. * * Typically if the xLocation and yLocation is directly on the center indicated * by 0 vor both then the kernel defaults to 1 in the middle and all other weights * are zero. */ virtual void buildConvolution(double /* xLocation */, double /* yLocation */) {} virtual long getWidth()const { return theWidth; } virtual long getHeight()const { return theHeight; } const NEWMAT::Matrix& getKernel()const { return *theKernel; } protected: NEWMAT::Matrix *theKernel; long theWidth; long theHeight; bool theComputeWeightedAverageFlag; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimDiscreteNearestNeighbor.h000066400000000000000000000056611352751253100261010ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id: ossimDiscreteNearestNeighbor.h 17195 2010-04-23 17:32:18Z dburken $ #ifndef ossimDiscreteNearestNeighbor_HEADER #define ossimDiscreteNearestNeighbor_HEADER #include class ossimDiscreteNearestNeighbor : public ossimDiscreteConvolutionKernel { public: ossimDiscreteNearestNeighbor() :ossimDiscreteConvolutionKernel(1, 1) { } /*! * We will override and optimize by unrolling the * loop */ virtual void convolveFloat(const float* data, double& result)const { result = *data; } /*! * We will override and optimize by unrolling the * loop */ virtual void convolveSubImageFloat(const float* data, long /* dataWidth */, double& result)const { result = *data; } virtual void convolveDouble(const double* data, double& result)const { result = *data; } virtual void convolveSubImageDouble(const double* data, long /* dataWidth */, double& result)const { result = *data; } /*! * We will override and optimize by unrolling the * loop */ virtual void convolveUchar(const unsigned char* data, double& result)const { result = *data; } /*! * We will override and optimize by unrolling the * loop */ virtual void convolveSubImageUchar(const unsigned char* data, long /* dataWidth */, double& result)const { result = *data; } virtual void convolveSshort(const short* data, double& result)const { result = *data; } virtual void convolveSubImageSshort(const short* data, long /* dataWidth */, double& result)const { result = *data; } virtual void convolveUshort(const unsigned short* data, double& result)const { result = *data; } virtual void convolveSubImageUshort(const unsigned short* data, long /* dataWidth */, double& result)const { result = *data; } virtual void buildConvolution(double /* widthPercent */, double /* heightPercent */) { } }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimDoqqTileSource.h000066400000000000000000000034501352751253100242340ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimDoqqTileSource.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimDoqqTileSource_HEADER #define ossimDoqqTileSource_HEADER #include #include class OSSIM_DLL ossimDoqqTileSource: public ossimGeneralRasterTileSource { public: ossimDoqqTileSource(); ossimString getShortName()const; ossimString getLongName()const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = NULL); //! Returns the image geometry object associated with this tile source or NULL if non defined. //! The geometry contains full-to-local image transform as well as projection (image-to-world) virtual ossimRefPtr getImageGeometry(); bool open(const ossimFilename& filename); bool open(const ossimGeneralRasterInfo& info); ossimString acqdate() const; /** * @brief Gets a property for matching name. * @param name The name of the property to get. * @return Returns property matching "name". */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Gets a list of property names available. * @param propertyNames The list to push back names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimDoqqTileSource(); ossimRefPtr theHeaderInformation; ossimString theAcqDate; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimDtedTileSource.h000066400000000000000000000203311352751253100242050ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration of ossimDtedTileSource. The ossimDtedTileSource // class is derived from ossimImageHandler and is intended to be an image // handler for DTED files. // //******************************************************************** // $Id: ossimDtedTileSource.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimDtedTileSource_HEADER #define ossimDtedTileSource_HEADER #include #include #include #include #include #include #include #include #include class ossimImageData; class OSSIM_DLL ossimDtedTileSource : public ossimImageHandler { public: ossimDtedTileSource(); enum { DATA_RECORD_OFFSET_TO_POST = 8, // bytes DATA_RECORD_CHECKSUM_SIZE = 4, // bytes POST_SIZE = 2, // bytes NULL_PIXEL = -32767 }; virtual ossimString getShortName()const; virtual ossimString getLongName()const; /** * Returns true if "theImageFile" can be opened and is a valid adrg file. */ virtual bool open(); virtual void close(); virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Returns the number of bands in the image. * Satisfies pure virtual requirement from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; virtual ossim_uint32 getNumberOfOutputBands()const; /** * Returns the number of lines in the image. * Satisfies pure virtual requirement from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines( ossim_uint32 reduced_res_level = 0) const; /** * Returns the number of samples in the image. * Satisfies pure virtual requirement from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples( ossim_uint32 reduced_res_level = 0) const; virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; /** * Returns the zero based image rectangle for the reduced resolution data * set (rrds) passed in. Note that rrds 0 is the highest resolution rrds. */ virtual ossimIrect getImageRectangle( ossim_uint32 reduced_res_level = 0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Returns the image geometry object associated with this tile source or NULL if not defined. //! The geometry contains full-to-local image transform as well as projection (image-to-world) virtual ossimRefPtr getImageGeometry(); /** * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; virtual bool isOpen()const; /** * Initializes spacing to the post spacing of the cell. * * @param postSpacing ossimDpt to initialize with spacing where * postspacing.x = longitude interval and postspacing.y = latitude interval. */ void getPostSpacing(ossimDpt& postSpacing) const; /** * @brief Gets a property for name. * @param name Property name to get. * @return ossimRefPtr Note that this can be empty if * property for name was not found. */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Adds this class's properties to list. * @param propertyNames list to append to. */ virtual void getPropertyNames( std::vector& propertyNames)const; /** * @brief Sets the min/max. * * looks for an omd or statistics file for min/max. If not found * calls gatherStatistics method. Overrides ossimImageHandler::loadMetaData * called by completeOpen. */ virtual void loadMetaData(); protected: virtual ~ossimDtedTileSource(); // Disallow operator= and copy constrution... const ossimDtedTileSource& operator=(const ossimDtedTileSource& rhs); ossimDtedTileSource(const ossimDtedTileSource&); /** * Allocated the tiles. */ void allocate(); /** * Returns true on success, false on error. */ bool fillBuffer(const ossimIrect& tile_rect, const ossimIrect& clip_rect, ossimImageData* tile); /** * @brief Scans for min and max. * @param writeStatsFile If true and statistics file does not exists it * will write one; else, no file will be written. */ void gatherStatistics(bool writeStatsFile); ossim_sint16 convertSignedMagnitude(ossim_uint16& s) const; ossimRefPtr theTile; mutable std::shared_ptr m_fileStr; mutable std::shared_ptr m_dtedInfo; ossim_uint32 theTileWidth; ossim_uint32 theTileHeight; ossim_uint32 theNumberOfLines; ossim_uint32 theNumberOfSamps; ossim_uint32 theOffsetToFirstDataRecord; ossim_uint32 theDataRecordSize; ossim_sint16 theMinHeight; ossim_sint16 theMaxHeight; ossimDpt thePostSpacing; ossimDtedVol m_vol; ossimDtedHdr m_hdr; ossimDtedUhl m_uhl; ossimDtedDsi m_dsi; ossimDtedAcc m_acc; /** * DTED data is always stored as BIG_ENDIAN. This flag indicates that * byte swapping is needed (LITTLE_ENDIAN machine). */ bool theSwapBytesFlag; TYPE_DATA }; inline ossim_sint16 ossimDtedTileSource::convertSignedMagnitude(ossim_uint16& s) const { // DATA_VALUE_MASK 0x7fff = 0111 1111 1111 1111 // DATA_SIGN_MASK 0x8000 = 1000 0000 0000 0000 // First check to see if the bytes need swapped. s = (theSwapBytesFlag ? ( ((s&0x00ff) << 8) | ((s&0xff00) >> 8) ) : s); // If the sign bit is set, mask it out then multiply by negative one. if (s & 0x8000) { return (static_cast(s & 0x7fff) * -1); } return static_cast(s); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimERSFileWriter.h000066400000000000000000000037301352751253100237600ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Andrew Huang // // Description: // // Class declaration for ossimERSFileWriter. Meta data class for // writing an ERS header file. // //---------------------------------------------------------------------------- // $Id: ossimERSFileWriter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimERSFileWriter_H #define ossimERSFileWriter_H #include #include #include #include /** * Class for writing a "ERS" style header. */ class OSSIM_DLL ossimERSFileWriter : public ossimMetadataFileWriter { public: /** default constructor */ ossimERSFileWriter(); /** * Initializes the state of the writer. Users should use this to set * the ERS header fields that are not taken from theInputConnection prior * to calling execute. * * @return true on success, false on failure. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); /** * Satisfies pure virtual from ossimMetadataWriter base. * * Appends the writers image types to the "metadatatypeList". * * @param metadatatypeList stl::vector list to append to. * * @note Appends to the list, does not clear it first. */ virtual void getMetadatatypeList( std::vector& metadatatypeList) const; /** * Satisfies pure virtual from ossimMetadataWriter base. * * @param imageType string representing image type. * * @return true if "metadataType" is supported by writer. */ virtual bool hasMetadataType(const ossimString& metadataType)const; protected: /** virtual destructor */ virtual ~ossimERSFileWriter(); virtual bool writeFile(); ossimERS theHdr; TYPE_DATA }; #endif /* End of #ifndef ossimERSFileWriter_H */ ossim-Miami-2.9.1/include/ossim/imaging/ossimERSTileSource.h000066400000000000000000000027661352751253100237720ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Chong-Ket Chuah // // Description: // // Contains class definition for the class "ossimERSTileSource". // //******************************************************************* // $Id: ossimERSTileSource.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimERSTileSource_HEADER #define ossimERSTileSource_HEADER #include #include class OSSIM_DLL ossimERSTileSource : public ossimGeneralRasterTileSource { public: ossimERSTileSource(); ossimERSTileSource(const ossimKeywordlist& kwl, const char* prefix=0); virtual ossimString getShortName() const; virtual ossimString getLongName() const; virtual ossimString className() const; virtual bool open(const ossimFilename& filename); //! Returns the image geometry object associated with this tile source or NULL if not defined. //! The geometry contains full-to-local image transform as well as projection (image-to-world) virtual ossimRefPtr getImageGeometry(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = NULL); protected: virtual ~ossimERSTileSource(); private: void openHeader(const ossimFilename& file); ossimERS* theHdr; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimEastingNorthingCutter.h000066400000000000000000000024651352751253100256300ustar00rootroot00000000000000#ifndef ossimEastingNorthingCutter_HEADER #define ossimEastingNorthingCutter_HEADER #include #include class ossimProjection; class ossimEastingNorthingCutter : public ossimRectangleCutFilter, public ossimViewInterface { public: ossimEastingNorthingCutter(ossimObject* owner, ossimImageSource* inputSource=NULL); ossimEastingNorthingCutter(ossimImageSource* inputSource=NULL); void setEastingNorthingRectangle(const ossimDpt& ul, const ossimDpt& lr); ossimDpt getUlEastingNorthing()const; ossimDpt getLrEastingNorthing()const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool setView(ossimObject* baseObject); virtual ossimObject* getView(); virtual const ossimObject* getView()const; virtual void initialize(); protected: virtual ~ossimEastingNorthingCutter(); ossimDpt theUlEastingNorthing; ossimDpt theLrEastingNorthing; ossimRefPtr theViewProjection; void transformVertices(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimEdgeFilter.h000066400000000000000000000055421352751253100233470ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimEdgeFilter.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimEdgeFilter_HEADER #define ossimEdgeFilter_HEADER #include /** * class ossimEdgeFilter * * This has default implementation for the certain filter types. For the * different filter type please see method setFilterType. * * */ class ossimEdgeFilter : public ossimImageSourceFilter { public: ossimEdgeFilter(ossimObject* owner=NULL); ossimEdgeFilter(ossimImageSource* inputSource); ossimEdgeFilter(ossimObject* owner, ossimImageSource* inputSource); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual void initialize(); virtual void getFilterTypeNames(std::vector& filterNames)const; virtual ossimString getFilterType()const; /** * The filter type can be one of the following strings. It is * case insensitive for the compares. * * Sobel * Laplacian * Prewitt * */ virtual void setFilterType(const ossimString& filterType); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool saveState(ossimKeywordlist& kwl,const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl,const char* prefix=0); protected: ossimRefPtr theTile; ossimString theFilterType; void adjustRequestRect(ossimIrect& requestRect)const; template void runFilter(T dummyVariable, ossimRefPtr inputData); template void runSobelFilter(T dummyVariable, ossimRefPtr inputData); template void runPrewittFilter(T dummyVariable, ossimRefPtr inputData); template void runLaplacianFilter(T dummyVariable, ossimRefPtr inputData); template void runRobertsFilter(T dummyVariable, ossimRefPtr inputData); template void runSimpleFilter(T dummyVariable, ossimRefPtr inputData); template void runLocalMax8Filter(T dummyVariable, ossimRefPtr inputData); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimElevImageSource.h000066400000000000000000000124521352751253100243520ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class provides an elevation image source from the elevation // manager. // //******************************************************************** // $Id: ossimElevImageSource.h 17108 2010-04-15 21:08:06Z dburken $ #ifndef ossimElevImageSource_HEADER #define ossimElevImageSource_HEADER #include #include #include class ossimElevSource; class ossimElevImageSource : public ossimImageSource { public: ossimElevImageSource(); ossimElevImageSource(ossimObject* owner); ossimElevImageSource(ossimObject* owner, const ossimGpt& tie, double latSpacing, // decimal degrees double lonSpacing , ossim_uint32 numberLines, ossim_uint32 numberSamples); ossimElevImageSource(ossimObject* owner, const ossimKeywordlist& kwl, const char* prefix=0); /*! * Returns a pointer to a tile given an origin representing the upper left * corner of the tile to grab from the image. * Satisfies pure virtual from TileSource class. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /*! * Populates the keyword list with image geometry information. This * method is used to relay projection/model information to users. * Returns true if geometry info is present, false if not. */ virtual bool getImageGeometry(ossimKeywordlist& kwl, const char* prefix=0); /*! * Returns the number of bands in the image. Alway one for this source. */ virtual ossim_uint32 getNumberOfOutputBands()const { return 1; } /*! * Returns the zero-based (relative) image rectangle for the reduced * resolution data set (rrds) passed in. Note that rrds 0 is the highest * resolution rrds. */ virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const; /*! * Returns the absolute bounding rectangle of the image. The upper left * corner may be non-zero if this is a subimage. */ virtual ossimIrect getBoundingRect(ossim_uint32 resLevel = 0) const { return getImageRectangle(resLevel); } /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); bool canConnectMyInputTo(ossim_int32 /* inputIndex */, const ossimConnectableObject* /* object */ )const { return false; } virtual void initialize(); /*! * Satisfy pure virtuals from base classes... */ virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const; virtual void getDecimationFactors(std::vector& decimations) const; virtual ossim_uint32 getNumberOfDecimationLevels()const; virtual ossim_uint32 getNumberOfInputBands() const; virtual ossimScalarType getOutputScalarType() const; virtual ossim_uint32 getTileWidth() const; virtual ossim_uint32 getTileHeight() const; virtual void changeTileSize(const ossimIpt& size); // access methods virtual ossimGpt getTiePoint() const { return theTiePoint; } virtual ossim_float64 getLatitudeSpacing() const { return theLatSpacing; } virtual ossim_float64 getLongitudeSpacing() const { return theLonSpacing; } virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; // set methods virtual void setTiePoint(const ossimGpt& gpt) { theTiePoint = gpt; } virtual void setLatitudeSpacing(ossim_float64 sp) { theLatSpacing = sp; } virtual void setLongitudeSpacing(ossim_float64 sp) { theLonSpacing = sp; } virtual void setNumberOfLines(ossim_uint32 lines) { theNumberOfLines = lines; } virtual void setNumberOfSamples(ossim_uint32 samps) { theNumberOfSamps = samps;} virtual void setMinPixelValue(ossim_float64 min_pix); virtual void setMaxPixelValue(ossim_float64 max_pix); protected: virtual ~ossimElevImageSource(); ossimElevSource* theElevManager; ossimRefPtr theTile; ossimGpt theTiePoint; // upper left tie point ossim_float64 theLatSpacing; // in decimal degrees ossim_float64 theLonSpacing; // in decimal degrees ossim_uint32 theNumberOfLines; ossim_uint32 theNumberOfSamps; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimElevRemapper.h000066400000000000000000000023511352751253100237170ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: RP // // Description: // // //******************************************************************* // $Id$ #ifndef ossimElevRemapper_HEADER #define ossimElevRemapper_HEADER #include class OSSIM_DLL ossimElevRemapper : public ossimImageSourceFilter { public: static const char REMAP_MODE_KW[]; enum ReplacementType { ReplacementType_ELLIPSOID = 0, ReplacementType_GEOID = 1 }; ossimElevRemapper(); virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); protected: virtual ~ossimElevRemapper(); template void elevRemap(T dummy, ossimImageData* inpuTile, ossim_uint32 resLevel); ReplacementType m_replacementType; bool saveState(ossimKeywordlist& kwl, const char* prefix)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix); ossimRefPtr m_imageGeometry; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimElevationMosaic.h000066400000000000000000000042511352751253100244130ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: // //************************************************************************* // $Id: ossimElevationMosaic.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimElevationMosaic_HEADER #define ossimElevationMosaic_HEADER #include #include /** * An image mosaic is a simple combiner that will * just do a simple mosaic. It just checks NULL pix values until it finds a * pixel that is not empty and copies it out to the output. The list will * have same size tiles and have the same number of bands. */ class OSSIMDLLEXPORT ossimElevationMosaic : public ossimImageCombiner { public: ossimElevationMosaic(); ossimElevationMosaic(ossimConnectableObject::ConnectableObjectList& inputSources); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual void initialize(); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimElevationMosaic(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); ossimRefPtr theTile; template ossimRefPtr combine( T, // dummy template variable not used const ossimIrect& tileRect, ossim_uint32 resLevel=0); template ossimRefPtr combineNorm( T, // dummy template variable not used const ossimIrect& tileRect, ossim_uint32 resLevel=0); TYPE_DATA }; #endif /* #ifndef ossimElevationMosaic_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimEnviHeaderFileWriter.h000066400000000000000000000042731352751253100253440ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration for ossimEnviHeaderFileWriter. Meta data class for // writing an ENVI (The Environment for Visualizing Images) header file. // //---------------------------------------------------------------------------- // $Id: ossimEnviHeaderFileWriter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimEnviHeaderFileWriter_H #define ossimEnviHeaderFileWriter_H #include #include #include #include /** * Class for writing a "ENVI" style header. */ class OSSIMDLLEXPORT ossimEnviHeaderFileWriter : public ossimMetadataFileWriter { public: /** default constructor */ ossimEnviHeaderFileWriter(); /** * Initializes the state of the writer. Users should use this to set * the envi header fields that are not taken from theInputConnection prior * to calling execute. * * @return true on success, false on failure. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); /** * Satisfies pure virtual from ossimMetadataWriter base. * * Appends the writers image types to the "metadatatypeList". * * @param metadatatypeList stl::vector list to append to. * * @note Appends to the list, does not clear it first. */ virtual void getMetadatatypeList( std::vector& metadatatypeList) const; /** * Satisfies pure virtual from ossimMetadataWriter base. * * @param imageType string representing image type. * * @return true if "metadataType" is supported by writer. */ virtual bool hasMetadataType(const ossimString& metadataType)const; protected: /** virtual destructor */ virtual ~ossimEnviHeaderFileWriter(); private: virtual bool writeFile(); ossimEnviHeader theHdr; TYPE_DATA }; #endif /* End of #ifndef ossimEnviHeaderFileWriter_H */ ossim-Miami-2.9.1/include/ossim/imaging/ossimEnviTileSource.h000066400000000000000000000056721352751253100242410ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Image handler class for a raster files with an ENVI header file. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimEnviTileSource_HEADER #define ossimEnviTileSource_HEADER 1 #include #include class OSSIMDLLEXPORT ossimEnviTileSource : public ossimGeneralRasterTileSource { public: /** @brief default constructor */ ossimEnviTileSource(); /** @return "ENVI" */ virtual ossimString getShortName() const; /** @return "ENVI reader" */ virtual ossimString getLongName() const; /** @brief open method. */ virtual bool open(); /** * @return The image geometry object associated with this tile source or * NULL if not defined. The geometry contains full-to-local image transform * as well as projection (image-to-world). */ virtual ossimRefPtr getImageGeometry(); /** * Method to save the state of an object to a keyword list. * @return true on success, false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. * * @return true on success, false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = NULL); /** * @brief Gets a property. * @param The name of the property to get. * @return The property if found. */ virtual ossimRefPtr getProperty( const ossimString& name)const; /** * @brief Adds property names to array. * @param propertyNames Array to populate with property names. */ virtual void getPropertyNames(std::vector& propertyNames)const; /** * @brief Get the zero based rgb output band list from envi header. * * @param bandList Initialized by this on success. * * @return true on success; false, on error. */ virtual bool getRgbBandList(std::vector& bandList) const; protected: /** @brief Hidden from use destructor. This is a ref ptr. */ virtual ~ossimEnviTileSource(); private: /** * @brief Sets default output band list if we are a band selector and * "default bands" is found in the header file. */ void setDefaultBandList(); /** * @brief Creates geometry from known support data, i.e. envi header, * and so on if found. */ ossimRefPtr getInternalImageGeometry() const; ossimEnviHeader m_enviHdr; TYPE_DATA }; // End: class ossimEnviTileSource #endif /* #ifndef ossimEnviTileSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimEquationCombiner.h000066400000000000000000000267451352751253100246110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimEquationCombiner.h 23649 2015-12-08 15:00:50Z gpotts $ #ifndef ossimEquationCombiner_HEADER #define ossimEquationCombiner_HEADER #include #include #include #include //class ossimCastTileSourceFilter; /** * Will combine the input data based on a supplied equation. * * This combiner uses the ossimEquTokenizer to create unique id's * for all tokens in the formula. The parser is based on the following * rules: * *
 * 
 * Prog -> Expr EOF 
 * Expr -> Term RestExpr 
 * RestExpr -> + Term RestExpr | - Term RestExpr |  
 * Term -> Storable RestTerm 
 * RestTerm -> * Factor RestTerm | / Factor RestTerm |  
 * Factor -> number | R | ( Expr )
 *
 *
 * The equation string represents input images as in[i] for i = 0, 1, ..., n.
 * The following tokens are supported, where I, I1, I2, ..., In are inputs (either input images or
 * image solutions of other equations):
 *
 * sin(I)                 takes the sine of the input
 * sind(I)                takes the sin of the input and assumes degree input
 * asin(I)                computes the arc-sine of input in radians (input must be normalized)
 * asind(I)               computes the arc-sine of input in degrees (input must be normalized)
 * cos(I)                 takes cosine of input
 * cosd(I)                takes the cosine of input and assumes input in degrees
 * acos(I)                computes the arc-cosine of input in radians (input must be normalized)
 * acosd(I)               computes the arc-cosine of input in degrees (input must be normalized)
 * tan(I)                 takes tangent of input
 * tand(I)                takes the tangent of input and assumes input in degrees
 * atan(I)                computes the arc-tangent of input in radians
 * atand(I)               computes the arc-tangent of input in degrees
 * sqrt(I)                takes square root of input
 * log(I)                 takes the natural log of input
 * log10(I)               takes the log base 10 of the input
 * exp(I)                 takes the e raised to the passed in argument
 * abs(I)                 takes the absolute value of the passed in value
 * min(I1, I2, ... In)    takes the min of all values in the list
 * max(I1, I2, ... In)    takes the max of all values in the list.
 *
 * clamp(I, min, max)     will clamp all data to be between the min max values.
 *                        will set anything less than min to min and anythin
 *                        larger than max to max
 *
 * band(I, band_index)    returns a single band image object
 *                        by selecting band num from input image I.  Note
 *                        the first argument must be an image
 *                        and the second argument must be a number
 *
 * shift(I, rows, cols)
 *                        currently, the first argument must be an image
 *                        variable and rows, cols must be numbers
 *                        indicating the delta in that direction to shift the
 *                        input.
 *
 * blurr(I, rows, cols)   Will blurr the input image I with a
 *                        rows-by-cols kernel.  All values are equal
 *                        weight.  Note the fist argument must by an image
 *                        variable (ex: i1, i2,....in).
 *
 * conv(index, rows, cols,  )
 *                        this allows you to define an arbitrary matrix.  The
 *                         is a comma separated
 *                        list of constant values.
 *
 * assign_band(I1, num1, I2, num2)
 *                        will take band num2 from image data I2 and assign it to
 *                        band num1 in image data I1.
 *
 * assign_band(I1, num1, I2)
 *                        will take band 1 from image data I2 and assign it to
 *                        band num1 in image data I1.
 *
 * assign_band(I, num1, num2)
 *                        will assin to band num1 of data I the value of num2
 *
 * I1 * I2                will multiply I1 and I2
 * I1 + I2                will add I1 and I2
 * I1 - I2                will subtract I1 and I2
 * I1 / I2                will divide I1 and I2
 * I1 ^ I2                will do a power, raises I1 to I2
 * I1 | I2                will do a bitwise or operation
 *                        ( will do it in unisgned char precision)
 *
 * I1 & I2                will do a bitwise and operation
 *                        ( will do it in unsigned char precision)
 *
 * ~I1                    will do the ones complement of the input
 *
 * I1 xor I2              will do an exclusive or operation
 *                        (will do it in unsigned char precision)
 *
 * - I1                   will negative of I1
 *
 * Boolean ops: 1=true, 0=false
 * I1 > I2
 * I1 >= I2
 * I1 == I2
 * I1 <= I2
 * I1 < I2
 * I1 <> I2
 *
 * Note:
 *
 * Currently an image input is reference by the variable "in[i]" where i
 * represents the input image index starting from 0.  So in[1] referes to the second image
 * in the input source list.
 *
 * Some examples:
 *
 *  (in[0] + in[1])/2
 *  Will take image 0 and add it to image 1 and average them.
 *
 *  exp(sqrt(in[0])/4)
 *  Will take the root of the image and divide by 4 and then raise e to that
 *  amount.
 *
 *  128
 *  Will return a constant value of 128 for all input bands.
 *
 * shift(0, 1, 1) - in[0]
 * Will shift the first input (0) by 1 pixel along the diagonal and then subtract
 * the original from the shifted (edge detect).
 *
 * assign_band(in[1], 1, blurr(in[1], 5, 5), 2)
 * Will assign to the first band of input 1 the 2nd band of the 5x5 blurr of same image.
 *
 * conv(0, 3, 3, -1, -2, -1, 0, 0, 0, 1, 2, 1)
 * Will convolve the first input connection with a 3x3 matrix.
 * The args are row ordered:
 *                          -1, -2, -1
 *                           0,  0,  0
 *                           1,  2,  1
 *
 * NDVI:
 * N=(in[0]-in[1])/(in[0]+in[1])
 *
 * For indexed-type values,like NDVI, (with limited values) it is better
 * to rescale between 0.0 and 1.0 and use type NormalizedFloat.
 * 
 * Rescaled NDVI between 0 and 1:
 * (N+1)/2 = in[0]/(in[0]+in[1])
 * 
 * With an ossimImageToPlaneNormalFilter feeding the DEM-image input, the slope at each pixel,
 * normalized so that 1.0 = 90 deg from vertical, is computed with:
 * "acosd(band(in[0],2))/90"
 *
 * 
*/ class OSSIMDLLEXPORT ossimEquationCombiner : public ossimImageCombiner { public: ossimEquationCombiner(); ossimEquationCombiner(ossimConnectableObject::ConnectableObjectList& inputSources); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual void initialize(); virtual void setEquation(const ossimString& equ) { theEquation = equ; } virtual ossimString getEquation()const { return theEquation; } virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual ossimScalarType getOutputScalarType() const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual void setOutputScalarType(ossimScalarType scalarType); /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); class ossimBinaryOp { public: virtual ~ossimBinaryOp(){} virtual double apply(double v1, double v2)const=0; }; class ossimUnaryOp { public: virtual ~ossimUnaryOp(){} virtual double apply(double v)const=0; }; protected: enum ossimEquValueType { OSSIM_EQU_TYPE_UNKNOWN = 0, OSSIM_EQU_DOUBLE_TYPE = 1, OSSIM_EQU_IMAGE_DATA_TYPE = 2 }; union ossimEquDataType { double doubleValue; ossimImageData* imageDataValue; }; struct ossimEquValue { int type; ossimEquDataType d; }; virtual ~ossimEquationCombiner(); ossimScalarType theOutputScalarType; ossimString theEquation; mutable ossimEquTokenizer *theLexer; ossimRefPtr theTile; ossimRefPtr theCastFilter; ossimRefPtr theCastOutputFilter; mutable int theCurrentId; mutable std::stack theValueStack; ossim_uint32 theCurrentResLevel; virtual void assignValue(); virtual void clearStacks(); virtual void clearArgList(std::vector& argList); virtual ossimRefPtr getImageData(ossim_uint32 index); virtual ossimRefPtr getNewImageData(ossim_uint32 index); virtual void deleteArgList(std::vector& args); virtual bool parseArgList(std::vector& args, bool popValueStack = true); virtual ossimRefPtr parseEquation(); virtual bool parseAssignBand(); virtual bool parseExpression(); virtual bool parseRestOfExp(); virtual bool parseTerm(); virtual bool parseRestOfTerm(); virtual bool parseFactor(); virtual bool parseStdFuncs(); virtual bool parseUnaryFactor(); virtual bool applyClamp(ossimImageData* &result, const std::vector& argList); virtual bool applyConvolution(ossimImageData* &result, const std::vector& argList); virtual bool applyBlurr(ossimImageData* &result, const std::vector& argList); virtual bool applyShift(ossimImageData* &result, const std::vector& argList); virtual bool applyOp(const ossimBinaryOp& op, ossimEquValue& result, ossimEquValue& v1, ossimEquValue& v2); virtual bool applyOp(const ossimBinaryOp& op, ossimImageData* v1, double v2); virtual bool applyOp(const ossimBinaryOp& op, double v1, ossimImageData* v2); virtual bool applyOp(const ossimBinaryOp& op, ossimImageData* v1, ossimImageData* v2); virtual bool applyOp(const ossimUnaryOp& op, ossimEquValue& result, ossimEquValue& v1); virtual bool applyOp(const ossimUnaryOp& op, ossimImageData* v); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimErosionFilter.h000066400000000000000000000042561352751253100241220ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef ossimErosionFilter_HEADER #define ossimErosionFilter_HEADER #include #include /*! * class ossimErosionFilter * * Causes null pixels to erode neighboring valid pixels. This is the opposite of dilation. * If a null pixel is detected inside the sampling window, the center pixel is set to null. */ class OSSIM_DLL ossimErosionFilter : public ossimImageSourceFilter { public: ossimErosionFilter(ossimObject* owner=NULL); virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Size of resampling kernel width & height */ void setWindowSize(ossim_uint32 windowSize) { theWindowSize = windowSize; } ossim_uint32 getWindowSize() const { return theWindowSize; } virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimErosionFilter(); ossimRefPtr theTile; ossimRefPtr theTempTile; //!> Used for recursion when recursive fill enabled ossim_uint32 theWindowSize; ossimPolygon theValidImagePoly; template void doErosion(T scalarType, ossimRefPtr& inputData); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimEsriShapeFileInterface.h000066400000000000000000000022471352751253100256400ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file // // Author: Mingjie Su // // Description: Interface class for ESRI Shape file. // //---------------------------------------------------------------------------- // $Id: ossimEsriShapeFileInterface.h 1916 2010-12-16 16:08:33Z ming.su $ #ifndef ossimEsriShapeFileInterface_HEADER #define ossimEsriShapeFileInterface_HEADER //Std Includes #include //Ossim Includes #include /* for OSSIM_DLL macro */ #include class ossimAnnotationObject; class ossimString; class OSSIMDLLEXPORT ossimEsriShapeFileInterface { public: /** * Pure virtual getFeatureTable method. * */ virtual std::multimap getFeatureTable() = 0; /** * Pure virtual setQuery method. * */ virtual void setQuery(const ossimString& query) = 0; /** * Pure virtual setGeometryBuffer method. * */ virtual void setGeometryBuffer(ossim_float64 distance, ossimUnitType type) = 0; TYPE_DATA }; #endif /* #ifndef ossimEsriShapeFileInterface_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimFeatherMosaic.h000066400000000000000000000050421352751253100240420ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimFeatherMosaic.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimFeatherMosaic_HEADER #define ossimFeatherMosaic_HEADER #include #include #include #include /** * Performs a spatial blend accross overlapping regions */ class OSSIMDLLEXPORT ossimFeatherMosaic : public ossimImageMosaic { public: ossimFeatherMosaic(); ossimFeatherMosaic(ossimConnectableObject::ConnectableObjectList& inputSources); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual void initialize(); protected: virtual ~ossimFeatherMosaic(); /** * This is only visible by this class and will remain here * unless we want to move it later. */ class ossimFeatherInputInformation { public: ossimFeatherInputInformation(const std::vector& validVertices=std::vector()); void setVertexList(const std::vector& validVertices); ossimDpt theCenter; ossimDpt theAxis1; ossimDpt theAxis2; double theAxis1Length; double theAxis2Length; std::vector theValidVertices; }; friend std::ostream& operator<<(std::ostream& out, const ossimFeatherInputInformation& data); /** * will hold an array of input information * */ ossimFeatherInputInformation* theInputFeatherInformation; ossimRefPtr theAlphaSum; ossimRefPtr theResult; /** * Will hold the count for the feather information list. */ long theFeatherInfoSize; /** * The dummy variable is used for the template type. See the getTile * method for the call. */ template ossimRefPtr combine(T dummyVariableNotUsed, const ossimIrect& tileRect, ossim_uint32 resLevel); virtual double computeWeight(long index, const ossimDpt& point)const; TYPE_DATA }; #endif /* #ifndef ossimFeatherMosaic_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimFftFilter.h000066400000000000000000000054561352751253100232260ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimFftFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimFftFilter_HEADER #define ossimFftFilter_HEADER #include class ossimScalarRemapper; class OSSIM_DLL ossimFftFilter : public ossimImageSourceFilter { public: enum ossimFftFilterDirectionType { FORWARD = 0, INVERSE }; ossimFftFilter(ossimObject* owner=NULL); ossimFftFilter(ossimImageSource* inputSource); ossimFftFilter(ossimObject* owner, ossimImageSource* inputSource); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual void initialize(); virtual ossim_uint32 getNumberOfOutputBands() const; virtual double getMinPixelValue(ossim_uint32 band=0)const; /*! * Returns the max pixel of the band. */ virtual double getMaxPixelValue(ossim_uint32 band=0)const; /*! * Each band has a null pixel associated with it. The null pixel * represents an invalid value. */ virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual ossimScalarType getOutputScalarType() const; void setForward(); void setInverse(); ossimString getDirectionTypeAsString()const; void setDirectionType(const ossimString& directionType); void setDirectionType(ossimFftFilterDirectionType directionType); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void setProperty(ossimRefPtr property); virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; protected: virtual ~ossimFftFilter(); ossimRefPtr theTile; ossimFftFilterDirectionType theDirectionType; ossimRefPtr theScalarRemapper; virtual void runFft(ossimRefPtr& input, ossimRefPtr& output); template void fillMatrixForward(T *realPart, T nullPix, NEWMAT::Matrix& real, NEWMAT::Matrix& img)const; template void fillMatrixInverse(T *realPart, T *imgPart, NEWMAT::Matrix& real, NEWMAT::Matrix& img)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimFgdcFileWriter.h000066400000000000000000000102131352751253100241640ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class to write out meta data in a Federal Geographic Data // Committe (FGDC) format. // //---------------------------------------------------------------------------- // $Id: ossimFgdcFileWriter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimFgdcFileWriter_HEADER #define ossimFgdcFileWriter_HEADER #include #include #include /** * Class to write out meta data in a Federal Geographic Data * Committe (FGDC) format. */ class OSSIMDLLEXPORT ossimFgdcFileWriter : public ossimMetadataFileWriter { public: /** constructor */ ossimFgdcFileWriter(); /** * Method to load the state from a keyword list. * * @param kwl Keyword list to load state from. * * @param prefix Prefix to attatch to keyword (like "object1."). * default=NULL * * @return true if ok or false on error. * * Keywords picked up by this loadState: * * source_image_filename: foo.ntf * tab_string: "\t" * fgdc_template_doc: fgdc_template.xml * */ virtual bool loadState(const ossimKeywordlist &kwl, const char *prefix=0); /** * Satisfies pure virtual from ossimMetadataWriter base. * * Appends the writers image types to the "metadatatypeList". * * @param metadatatypeList stl::vector list to append to. * * @note Appends to the list, does not clear it first. */ virtual void getMetadatatypeList( std::vector& metadatatypeList) const; /** * Satisfies pure virtual from ossimMetadataWriter base. * * @param imageType string representing image type. * * @return true if "metadataType" is supported by writer. */ virtual bool hasMetadataType(const ossimString& metadataType)const; /** @return Returns the current indentation level. */ ossim_uint32 getIndentionLevel() const; /** * Sets the current indentation level. * * @param level Indentation level. "0" equals no indentation. */ void setIndentionLevel(ossim_uint32 level); /** * @return The current tab string e.g.: "\t". */ ossimString getTabString() const; /** * Sets the tab string. Usually "\t" or spaces " ". * * @param tabString String to use for indentation. */ void setTabString(const ossimString& tabString); /** * @param title Tile of data usually the image file name. */ void setTitle(const ossimString& pubDate); void setTemplate(const ossimFilename& xmlTemplateFile); ossimString find(const ossimString& xpath) const; bool writeTemplate(const ossimFilename& file) const; protected: /** destructor */ virtual ~ossimFgdcFileWriter(); /** * Writes file to disk. * * @return true on success, false on failure. */ virtual bool writeFile(); private: /** * Writes openning tag adding any indentation and brackets. Increments * indentation level. * * @param os otream to write to. * * @param tag String representing tag with no brackets, i.e. "metadata". * * @param newLine If true a new line "\n" is added. */ void openTag(std::ostream& os, const ossimString& tag, bool newLine) const; /** * Closes tag decrementing indentation. * e.g.: * * @param os otream to write to. * * @param tag String representing tag with no brackets. * * @param decrementLevel If true indentation level is decremented. */ void closeTag(std::ostream& os, const ossimString& tag, bool decrementLevel) const; mutable ossim_uint32 theIndentionLevel; ossimString theTabString; ossimXmlDocument theTemplate; ossimFilename theSourceImageFilename; TYPE_DATA }; #endif /* End of "#ifndef ossimFgdcFileWriter_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimFilter.h000066400000000000000000000267421352751253100225670ustar00rootroot00000000000000#ifndef ossimFilter_HEADER #define ossimFilter_HEADER #include #include #include #include class ossimFilter { public: ossimFilter() {} virtual ~ossimFilter() {} virtual double filter (double x, double support)const = 0; /*! * Will call the filter method to create a * convolution matrix. This matrix will not * have normalized weights. * * Will generate a matrix by creating an outer * product of the 1-D filter array. This matrix * will be square width-by-width. * * note: the matrix is a new matrix and needs to * be destroyed by the caller */ virtual NEWMAT::Matrix *newMatrix(long width=3, double middle=0.0, double scale=0.0)const; virtual void createMatrix(NEWMAT::Matrix& m, long width=3, double middle=0.0, double scale=0.0)const; virtual NEWMAT::RowVector *newVector(long width, double middle=0.0, double scale = 1.0)const; static double Sinc(double x) { if (x != 0.0) { x*=M_PI; return(sin(x)/x); } return(1.0); } static double Sinc(double x, double /* support */ ) { if (x != 0.0) { x*=M_PI; return(sin(x)/x); } return(1.0); } virtual double getSupport()const=0; TYPE_DATA }; class ossimBoxFilter : public ossimFilter { public: ossimBoxFilter (){} virtual ~ossimBoxFilter() {} virtual double filter (double x, double /* support */ )const { if (x < -0.5) return(0.0); if (x < 0.5) return(1.0); return(0.0); } virtual double getSupport()const { return .5; } TYPE_DATA }; class ossimSincFilter : public ossimFilter { public: ossimSincFilter(){} virtual ~ossimSincFilter(){} double filter(double x, double /* support */ )const { x*=M_PI; if (x != 0.0) return(sin(x)/x); return(1.0); } virtual double getSupport()const { return 1.0; } TYPE_DATA }; class ossimBellFilter : public ossimFilter { public: ossimBellFilter(){} virtual ~ossimBellFilter(){} virtual double getSupport()const { return 1.5; } virtual double filter(double value, double /* support */ )const { if(value < 0) value = -value; if(value < .5) return(.75 - (value * value)); if(value < 1.5) { value = (value - 1.5); return(.5 * (value * value)); } return(0.0); } TYPE_DATA }; class ossimNearestNeighborFilter: public ossimBoxFilter { public: ossimNearestNeighborFilter (){} virtual ~ossimNearestNeighborFilter() {} virtual double getSupport()const { return 0.0; } TYPE_DATA }; class ossimBesselOrderOneFilter : public ossimFilter { public: ossimBesselOrderOneFilter(){} virtual ~ossimBesselOrderOneFilter(){} virtual double filter(double value, double /* support */ )const; virtual double getSupport()const { return 1.0; } TYPE_DATA }; class ossimBesselFilter : public ossimFilter { public: ossimBesselFilter(){} virtual ~ossimBesselFilter(){} virtual double filter(double x, double support)const { if (x == 0.0) { return(M_PI/4.0); } return(ossimBesselOrderOneFilter().filter((M_PI*x)/(2.0*x), support)); } virtual double getSupport()const { return 1.0; } TYPE_DATA }; class ossimBlackmanFilter : public ossimFilter { public: ossimBlackmanFilter (){} virtual ~ossimBlackmanFilter() {} virtual double filter (double x, double /* support */ ) const { return(0.42+0.50*cos(M_PI*x)+0.08*cos(2.0*M_PI*x)); } virtual double getSupport()const { return 1.0; } TYPE_DATA }; class ossimBlackmanSincFilter : public ossimBlackmanFilter { public: ossimBlackmanSincFilter (){} virtual ~ossimBlackmanSincFilter() {} virtual double filter (double x, double support) const { return ((ossimBlackmanFilter::filter(x/support,support))* (ossimSincFilter().filter(x, support))); } virtual double getSupport()const { return 4.0; } TYPE_DATA }; class ossimBlackmanBesselFilter : public ossimBlackmanFilter { public: ossimBlackmanBesselFilter(){} virtual ~ossimBlackmanBesselFilter() {} virtual double filter (double x, double support) const { return ((ossimBlackmanFilter::filter(x/support,support))* (ossimBesselFilter().filter(x, support))); } virtual double getSupport()const { return 3.2383; } TYPE_DATA }; class ossimCatromFilter : public ossimFilter { public: ossimCatromFilter(){} virtual ~ossimCatromFilter(){} double filter(double x, double /* support */ )const { if (x < -2.0) return(0.0); if (x < -1.0) return(0.5*(4.0+x*(8.0+x*(5.0+x)))); if (x < 0.0) return(0.5*(2.0+x*x*(-5.0-3.0*x))); if (x < 1.0) return(0.5*(2.0+x*x*(-5.0+3.0*x))); if (x < 2.0) return(0.5*(4.0+x*(-8.0+x*(5.0-x)))); return(0.0); } virtual double getSupport()const { return 2.0; } TYPE_DATA }; class ossimCubicFilter : public ossimFilter { public: ossimCubicFilter(){} virtual ~ossimCubicFilter(){} double filter(double x, double /* support */ )const { if (x < -2.0) return(0.0); if (x < -1.0) return((2.0+x)*(2.0+x)*(2.0+x)/6.0); if (x < 0.0) return((4.0+x*x*(-6.0-3.0*x))/6.0); if (x < 1.0) return((4.0+x*x*(-6.0+3.0*x))/6.0); if (x < 2.0) return((2.0-x)*(2.0-x)*(2.0-x)/6.0); return(0.0); } virtual double getSupport()const { return 2.0; } TYPE_DATA }; class ossimBSplineFilter : public ossimFilter { public: ossimBSplineFilter(){} virtual ~ossimBSplineFilter(){} virtual double filter(double value, double /* support */ )const { double tt; if(value < 0) value = -value; if(value < 1) { tt = value * value; return((.5 * tt * value) - tt + (2.0 / 3.0)); } else if(value < 2) { value = 2 - value; return((1.0 / 6.0) * (value * value * value)); } return(0.0); } virtual double getSupport()const { return 2.0; } TYPE_DATA }; class ossimGaussianFilter : public ossimFilter { public: ossimGaussianFilter (){} virtual ~ossimGaussianFilter() {} virtual double filter (double x, double /* support */ ) const { return(exp(-2.0*x*x)*sqrt(2.0/M_PI)); } virtual double getSupport()const { return 1.25; } TYPE_DATA }; class ossimHanningFilter : public ossimFilter { public: ossimHanningFilter(){} virtual ~ossimHanningFilter(){} double filter(double x, double /* support */ )const { return(0.5+0.5*cos(M_PI*x)); } virtual double getSupport()const { return 1.0; } TYPE_DATA }; class ossimHammingFilter : public ossimFilter { public: ossimHammingFilter (){} virtual ~ossimHammingFilter() {} virtual double filter (double x, double /* support */ ) const { return(0.54+0.46*cos(M_PI*x)); } virtual double getSupport()const { return 1.0; } TYPE_DATA }; class ossimHermiteFilter : public ossimFilter { public: ossimHermiteFilter(){} virtual ~ossimHermiteFilter(){} double filter(double x, double /* support */ )const { if (x < -1.0) return(0.0); if (x < 0.0) return((2.0*(-x)-3.0)*(-x)*(-x)+1.0); if (x < 1.0) return((2.0*x-3.0)*x*x+1.0); return(0.0); } virtual double getSupport()const { return 1.0; } TYPE_DATA }; class ossimLanczosFilter : public ossimFilter { public: ossimLanczosFilter(){} virtual ~ossimLanczosFilter(){} double filter(double x, double /* support */ )const { if (x < -3.0) return(0.0); if (x < 0.0) return(Sinc(-x,getSupport())*Sinc(-x/3.0,getSupport())); if (x < 3.0) return(Sinc(x,getSupport())*Sinc(x/3.0,getSupport())); return(0.0); } virtual double getSupport()const { return 3.0; } TYPE_DATA }; class ossimMagicFilter : public ossimFilter { public: ossimMagicFilter(){} virtual ~ossimMagicFilter(){} double filter(double x, double /* support */ )const { if (x <= -1.5) return(0.0); if (x <= -0.5) return (0.5*ossim::square(x + 1.5)); if (x <=0.5) return (0.75-ossim::square(x)); if(x <= 0.75) return (0.5*ossim::square(x-1.5)); return(0.0); } virtual double getSupport()const { return 1.5; } TYPE_DATA }; class ossimMitchellFilter : public ossimFilter { public: ossimMitchellFilter(){} virtual ~ossimMitchellFilter(){} double filter(double x, double /* support */ )const { #define MITCHELL_B (1.0/3.0) #define MITCHELL_C (1.0/3.0) #define MITCHELL_P0 (( 6.0- 2.0*MITCHELL_B )/6.0) #define MITCHELL_P2 ((-18.0+12.0*MITCHELL_B+ 6.0*MITCHELL_C)/6.0) #define MITCHELL_P3 (( 12.0- 9.0*MITCHELL_B- 6.0*MITCHELL_C)/6.0) #define MITCHELL_Q0 (( 8.0*MITCHELL_B+24.0*MITCHELL_C)/6.0) #define MITCHELL_Q1 (( -12.0*MITCHELL_B-48.0*MITCHELL_C)/6.0) #define MITCHELL_Q2 (( 6.0*MITCHELL_B+30.0*MITCHELL_C)/6.0) #define MITCHELL_Q3 (( - 1.0*MITCHELL_B- 6.0*MITCHELL_C)/6.0) if (x < -2.0) return(0.0); if (x < -1.0) return(MITCHELL_Q0-x*(MITCHELL_Q1-x*(MITCHELL_Q2-x*MITCHELL_Q3))); if (x < 0.0) return(MITCHELL_P0+x*x*(MITCHELL_P2-x*MITCHELL_P3)); if (x < 1.0) return(MITCHELL_P0+x*x*(MITCHELL_P2+x*MITCHELL_P3)); if (x < 2.0) return(MITCHELL_Q0+x*(MITCHELL_Q1+x*(MITCHELL_Q2+x*MITCHELL_Q3))); return(0.0); } virtual double getSupport()const { return 2.0; } TYPE_DATA }; class ossimQuadraticFilter : public ossimFilter { public: ossimQuadraticFilter(){} virtual ~ossimQuadraticFilter(){} double filter(double x, double /* support */ )const { if (x < -1.5) return(0.0); if (x < -0.5) return(0.5*(x+1.5)*(x+1.5)); if (x < 0.5) return(0.75-x*x); if (x < 1.5) return(0.5*(x-1.5)*(x-1.5)); return(0.0); } double getSupport()const { return 1.5; } TYPE_DATA }; class ossimTriangleFilter : public ossimFilter { public: ossimTriangleFilter(){} virtual ~ossimTriangleFilter() {} virtual double filter (double x, double /* support */ )const { if (x < -1.0) return(0.0); if (x < 0.0) return(1.0+x); if (x < 1.0) return(1.0-x); return(0.0); } virtual double getSupport()const { return 1.0; } TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimFilterResampler.h000066400000000000000000000115701352751253100244330ustar00rootroot00000000000000//******************************************************************* // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Contributor: // David A. Horner (DAH) http://dave.thehorners.com // //************************************************************************* // $Id: ossimFilterResampler.h 23586 2015-10-19 10:45:22Z gpotts $ #ifndef ossimFilterResampler_HEADER #define ossimFilterResampler_HEADER #include #include #include #include #include #include #include class OSSIMDLLEXPORT ossimFilterResampler { public: enum ossimFilterResamplerType { ossimFilterResampler_NEAREST_NEIGHBOR = 0, ossimFilterResampler_BOX = 1, ossimFilterResampler_GAUSSIAN = 2, ossimFilterResampler_CUBIC = 3, ossimFilterResampler_HANNING = 4, ossimFilterResampler_HAMMING = 5, ossimFilterResampler_LANCZOS = 6, ossimFilterResampler_MITCHELL = 7, ossimFilterResampler_CATROM = 8, ossimFilterResampler_BLACKMAN = 9, ossimFilterResampler_BLACKMAN_SINC = 10, ossimFilterResampler_BLACKMAN_BESSEL = 11, ossimFilterResampler_QUADRATIC = 12, ossimFilterResampler_TRIANGLE = 13, ossimFilterResampler_BILINEAR = 13, ossimFilterResampler_HERMITE = 14, ossimFilterResampler_BELL = 15, ossimFilterResampler_BSPLINE = 16, ossimFilterResampler_MAGIC = 17 }; ossimFilterResampler(); virtual ~ossimFilterResampler(); virtual void resample(const ossimRefPtr& input, ossimRefPtr& output, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length); virtual void resample(const ossimRefPtr& input, ossimRefPtr& output, const ossimIrect& outputSubRect, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length); void setFilterType(ossimFilterResamplerType filterType); void setFilterType(ossimFilterResamplerType minifyFilterType, ossimFilterResamplerType magnifyFilterType); void setFilterType(const ossimString& type); void setFilterType(const ossimString& minifyType, const ossimString& magnifyType); void setMinifyFilterType(const ossimString& minifyType); void setMagnifyFilterType(const ossimString& magnifyType); void setMinifyFilterType(ossimFilterResamplerType filterType); void setMagnifyFilterType(ossimFilterResamplerType filterType); ossimString getMinifyFilterTypeAsString()const; ossimString getMagnifyFilterTypeAsString()const; void setScaleFactor(const ossimDpt& scale); void setBlurFactor(ossim_float64 blur); void setBoundingInputRect(const ossimIrect& rect) { theInputRect = rect; } ossimIrect getBoundingInputRect()const { return theInputRect; } ossim_float64 getBlurFactor()const; const ossimDpt& getScaleFactor()const { return theScaleFactor; } /*! * Saves the state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Loads the state of this object. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void getKernelSupport(double& x, double & y)const; virtual void getFilterTypes(std::vector& filterTypes)const; private: const ossimFilter* getHorizontalFilter()const; const ossimFilter* getVerticalFilter()const; template void resampleBilinearTile(T dummy, const ossimRefPtr& input, ossimRefPtr& output, const ossimIrect& outputSubRect, const ossimDpt& inputUl, const ossimDpt& inputUr, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& outLength); void computeTable(); ossimString getFilterTypeAsString(ossimFilterResamplerType type)const; ossimFilterResamplerType getFilterType(const ossimString& type)const; ossimFilter* createNewFilter(ossimFilterResamplerType filterType, ossimFilterResamplerType& result); ossimFilter* theMinifyFilter; ossimFilter* theMagnifyFilter; ossimFilterTable theFilterTable; ossimFilterResamplerType theMinifyFilterType; ossimFilterResamplerType theMagnifyFilterType; ossimDpt theScaleFactor; ossimDpt theInverseScaleFactor; ossimIrect theInputRect; ossim_float64 theBlurFactor; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimFilterTable.h000066400000000000000000000051571352751253100235340ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //---------------------------------------------------------------------------- // $Id: ossimFilterTable.h 23353 2015-06-01 19:19:10Z dburken $ #ifndef ossimFilterTable_HEADER #define ossimFilterTable_HEADER 1 #include #include class ossimFilter; class OSSIM_DLL ossimFilterTable { public: /** default constructor */ ossimFilterTable(); /** destructor */ ~ossimFilterTable(); /** Builds a table with filter being used in both x and y direction. */ void buildTable(ossim_uint32 filterSteps, const ossimFilter& filter); /** Builds a table. */ void buildTable(ossim_uint32 filterSteps, const ossimFilter& xFilter, const ossimFilter& yFilter); /** @return theWidth*theHeight */ ossim_uint32 getWidthByHeight() const; /** @return theXSupport */ ossim_uint32 getXSupport() const; /** @return theYSupport */ ossim_uint32 getYSupport() const; /** @return theWidth */ ossim_uint32 getWidth() const; /** @return theHeight */ ossim_uint32 getHeight() const; /** * Inlined below. * * @return const double* to the closest weight of x and y. */ const double* getClosestWeights(const double& x, const double& y)const; protected: /** * Creates the weight array "theWeights". Will delete if previously * allocated. */ void allocateWeights(); double* theWeights; ossim_uint32 theWidth; ossim_uint32 theHeight; ossim_uint32 theWidthHeight; ossim_uint32 theXSupport; ossim_uint32 theYSupport; ossim_uint32 theFilterSteps; }; /** * Method inlined for speed as it is used in the inner pixel loop of * ossimFilterResampler::resampleBilinearTile method. */ inline const double* ossimFilterTable::getClosestWeights(const double& x, const double& y)const { // Extract the decimal part of x and y. double intPartDummy; double decimalPrecisionX = fabs(modf(x, &intPartDummy)); double decimalPrecisionY = fabs(modf(y, &intPartDummy)); ossim_int32 kernelLine = (ossim_int32)(theFilterSteps*decimalPrecisionY); ossim_int32 kernelSamp = (ossim_int32)(theFilterSteps*decimalPrecisionX); return &theWeights[(kernelLine*theFilterSteps + kernelSamp)*theWidthHeight]; } #endif /* End of "#ifndef ossimFilterTable_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimFixedTileCache.h000066400000000000000000000102251352751253100241300ustar00rootroot00000000000000//****************************************************************** // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This file contains the Application cache algorithm // //*********************************** // $Id: ossimFixedTileCache.h 16276 2010-01-06 01:54:47Z gpotts $ #ifndef ossimFixedTileCache_HEADER #define ossimFixedTileCache_HEADER #include #include #include #include #include #include #include class ossimFixedTileCacheInfo { public: ossimFixedTileCacheInfo(ossimRefPtr& tile, ossim_int32 tileId=-1) :theTile(tile), theTileId(tileId) { } bool operator <(const ossimFixedTileCacheInfo& rhs)const { return (theTileId < rhs.theTileId); } bool operator <(ossim_int32 tileId)const { return (theTileId < tileId); } bool operator >(const ossimFixedTileCacheInfo& rhs)const { return (theTileId > rhs.theTileId); } bool operator >(ossim_int32 tileId)const { return (theTileId > tileId); } bool operator ==(const ossimFixedTileCacheInfo& rhs)const { return (theTileId == rhs.theTileId); } bool operator ==(ossim_int32 tileId)const { return (theTileId == tileId); } ossimRefPtr theTile; ossim_int32 theTileId; }; class ossimFixedTileCache : public ossimReferenced { public: ossimFixedTileCache(); virtual void setRect(const ossimIrect& rect); virtual void setRect(const ossimIrect& rect, const ossimIpt& tileSize); void keepTilesWithinRect(const ossimIrect& rect); virtual ossimRefPtr addTile(ossimRefPtr imageData, bool duplicateData=true); virtual ossimRefPtr getTile(ossim_int32 id); virtual ossimRefPtr getTile(const ossimIpt& origin) { return getTile(computeId(origin)); } virtual void setUseLruFlag(bool flag) { theUseLruFlag = flag; } virtual bool getUseLruFlag()const { return theUseLruFlag; } virtual void flush(); virtual void deleteTile(const ossimIpt& origin) { deleteTile(computeId(origin)); } virtual void deleteTile(ossim_int32 tileId); virtual ossimRefPtr removeTile(const ossimIpt& origin) { return removeTile(computeId(origin)); } virtual ossimRefPtr removeTile(ossim_int32 tileId); virtual const ossimIrect& getTileBoundaryRect()const { return theTileBoundaryRect; } virtual ossim_uint32 getNumberOfTiles()const { return (ossim_uint32)theTileMap.size(); } virtual const ossimIpt& getTileSize()const { return theTileSize; } virtual ossim_uint32 getCacheSize()const { return theCacheSize; } virtual void deleteTile(); virtual ossimRefPtr removeTile(); virtual void setMaxCacheSize(ossim_uint32 cacheSize) { theMaxCacheSize = cacheSize; } ossim_uint32 getMaxCacheSize()const { return theMaxCacheSize; } virtual ossimIpt getTileOrigin(ossim_int32 tileId); virtual ossim_int32 computeId(const ossimIpt& tileOrigin)const; virtual void setTileSize(const ossimIpt& tileSize); protected: virtual ~ossimFixedTileCache(); std::mutex theMutex; ossimIrect theTileBoundaryRect; ossimIpt theTileSize; ossimIpt theBoundaryWidthHeight; ossim_uint32 theTilesHorizontal; ossim_uint32 theTilesVertical; ossim_uint32 theCacheSize; ossim_uint32 theMaxCacheSize; std::map theTileMap; std::list theLruQueue; bool theUseLruFlag; virtual void eraseFromLru(ossim_int32 id); void adjustLru(ossim_int32 id); }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimFusionCombiner.h000066400000000000000000000031271352751253100242540ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Implementation for Base fusion. // This base class assumes two inputs where the second input is // the intensity source. // //************************************************************************* // $Id: ossimFusionCombiner.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimFusionCombiner_HEADER #define ossimFusionCombiner_HEADER #include class OSSIMDLLEXPORT ossimFusionCombiner : public ossimImageCombiner { public: ossimFusionCombiner(); ossimFusionCombiner(ossimObject* owner); virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0) const; bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; ossimScalarType getOutputScalarType() const; virtual void initialize(); protected: virtual ~ossimFusionCombiner(); ossimRefPtr theTile; ossimRefPtr theNormTile; ossimRefPtr theNormIntensity; ossimImageSource* theInputConnection; ossimImageSource* theIntensityConnection; ossimRefPtr getNormIntensity(const ossimIrect& rect, ossim_uint32 resLevel); ossimRefPtr getNormTile(const ossimIrect& rect, ossim_uint32 resLevel); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGammaRemapper.h000066400000000000000000000047371352751253100240600ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Gamma remapper. // //************************************************************************* // $Id: ossimGammaRemapper.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGammaRemapper_HEADER #define ossimGammaRemapper_HEADER #include /* * The gamma remapper is based on the equation: * * pow(, gammaValue) * * * @code * // assume we have an input image source that we wish to gamma correct * // called inputSource. * ossimRefPtr gamma = new ossimGammaRemapper() * * gamma->setGamma(0.7); * gamma->connectMyInputTo(inputSource.get()); * * @endcode */ class ossimGammaRemapper : public ossimImageSourceFilter { public: ossimGammaRemapper(); ossimGammaRemapper(const double& gamma); virtual ossimString getShortName() const; virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); void setGamma(const double& gamma); double getGamma()const { return m_gamma; } /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimGammaRemapper(); void allocate(); void computeLookup(); void calculateGamma(ossimRefPtr input); void calculateGammaWithLookup(ossimRefPtr input); template void calculateGammaWithLookupTemplate(ossimRefPtr input, T /*dummy*/); ossim_float64 m_gamma; mutable bool m_dirtyFlag; ossimRefPtr m_tile; ossimRefPtr m_normalizedTile; mutable std::vector m_lookupTable; static const ossim_float64 MIN_GAMMA; static const ossim_float64 MAX_GAMMA; static const ossim_float64 DEFAULT_GAMMA; TYPE_DATA }; #endif /* #ifndef ossimGammaRemapper_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimGdFont.h000066400000000000000000000026671352751253100225230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimGdFont.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimGdFont_HEADER #define ossimGdFont_HEADER /* gd.h: declarations file for the graphic-draw module. * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation. This software is provided "AS IS." Thomas Boutell and * Boutell.Com, Inc. disclaim all warranties, either express or implied, * including but not limited to implied warranties of merchantability and * fitness for a particular purpose, with respect to this code and accompanying * documentation. */ typedef struct { /* # of characters in font */ int nchars; /* First character is numbered... (usually 32 = space) */ int offset; /* Character width and height */ int w; int h; /* Font data; array of characters, one row after another. Easily included in code, also easily loaded from data files. */ char *data; } ossimGdFont; /* Text functions take these. */ typedef ossimGdFont *ossimGdFontPtr; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGdFontExterns.h000066400000000000000000000012051352751253100240570ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimGdFontExterns.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimGdFontExterns_HEADER #define ossimGdFontExterns_HEADER #include extern ossimGdFontPtr ossimGdFontGiant; extern ossimGdFontPtr ossimGdFontTiny; extern ossimGdFontPtr ossimGdFontSmall; extern ossimGdFontPtr ossimGdFontLarge; extern ossimGdFontPtr ossimGdFontMediumBold; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeneralRasterInfo.h000066400000000000000000000273211352751253100247060ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration for ossimGeneralRasterInfo //******************************************************************* // $Id: ossimGeneralRasterInfo.h 22197 2013-03-12 02:00:55Z dburken $ #ifndef ossimGeneralRasterInfo_HEADER #define ossimGeneralRasterInfo_HEADER 1 #include #include #include #include #include #include #include #include #include //--- // Forward class declarations. //--- class ossimEnviHeader; class ossimKeywordlist; /** * @class ossimGeneralRasterInfo * */ class OSSIMDLLEXPORT ossimGeneralRasterInfo : public ossimObject { public: enum ossimFillMode { NONE, ZEROES_TO_MIN, ZEROES_TO_NULL_EDGES_ONLY }; enum { UNKNOWN = -1 }; /* @brief default constructor */ ossimGeneralRasterInfo(); ossimGeneralRasterInfo(const std::vector& imageFileList, ossimScalarType pixelType, ossimInterleaveType il_type, ossim_int32 numberOfBands, ossim_int32 lines, ossim_int32 samples, ossim_int32 headerSize, ossimFillMode nullsMode, ossim_int32 pixelsToChop); ossimGeneralRasterInfo(const ossimKeywordlist& kwl, const char* prefix=0); /* @brief copy constructor */ ossimGeneralRasterInfo( const ossimGeneralRasterInfo& obj ); /** @brief Assignment operator=. */ const ossimGeneralRasterInfo& operator=( const ossimGeneralRasterInfo& rhs ); virtual ~ossimGeneralRasterInfo (); /** * Zero based rectangle of the valid image. */ const ossimIrect& imageRect() const; /** * Returns the rectangle of where the image is within the raster file. * In most cases this will be the same as the rawImageRect. (zero based) */ const ossimIrect& validImageRect() const; /** * Zero based rectangle of the raw image. */ const ossimIrect& rawImageRect() const; /** * Returns the offset of this image's origin to a full-image's origin, in * the case where this image is a sub-image of a larger full-image. */ const ossimIpt& subImageOffset() const; /** * Returns the size of header in bytes. */ ossim_int32 headerSize() const; /** * Returns the fill mode. This is used to flip values on ingest. * Valid Mode Enumerations: * - 0 Do nothing to the pixels on ingest. * - 1 Flip all zeroes to the minimum pixel value. * - 2 Flip zeroes within the image line to minimum pixel value. * This is used by edge walking code. */ ossim_uint32 fillToNullsMode() const; /** * Sets theSetNullsMode. */ void setFillToNullsMode(ossim_uint32 mode); /** * @brief Number of bands. Inlined below. * @return Number of bands from theMetaData class member cast to an int32. */ inline ossim_int32 numberOfBands() const; /** * @brief Bytes per pixel. Inlined below. * @return Bytes per pixel from theMetaData class member cast to an int32. */ inline ossim_int32 bytesPerPixel() const; /** * Returns the number of pixels from the edge of a line * to set to the fill value. This can be used to eliminate * resampling error on the edge of an image and still keep * the image demensions relative to the geometry file. */ ossim_int32 pixelsToChop() const; /** * Enumerated in InterleaveTypeLUT. Should be either bip, * bil or bsq. Defaulted to bip. */ ossimInterleaveType interleaveType() const; /** * Returns the number of lines within "theValidImageRect". */ inline ossim_int32 validLines() const; /** * Returns the number of lines within "theRawImageRect". */ inline ossim_int32 rawLines() const; /** * Returns the number of bytes in a raw line. */ inline ossim_int32 bytesPerRawLine() const; /** * Returns the number of bytes in a valid line. */ inline ossim_int32 bytesPerValidLine() const; /** * Returns the number of samples within "theValidImageRect". */ inline ossim_int32 validSamples() const; /** * Returns the number of samples within "theRawImageRect". */ inline ossim_int32 rawSamples() const; /** * Returns the offset in bytes to the first valid sample in the image. */ inline std::streamoff offsetToFirstValidSample() const; const std::vector& getImageFileList() const; void setImageFileList(const std::vector& list); /** * @brief Sets the image file list to file. Performs a clear, prior to * setting. * @param file Image file. */ void setImageFile(const ossimFilename& file); void setHeaderSize(ossim_int32 headerSize); void setInterleaveType(ossimInterleaveType il_type); virtual std::ostream& print(std::ostream& out) const; void setImageRect(const ossimIrect& imageRect); void setValidImageRect(const ossimIrect &imageRect); void setRawImageRect(const ossimIrect &imageRect); void setSubImageOffset(const ossimIpt& d); ossimByteOrder getImageDataByteOrder() const; void setImageDataByteOrder(ossimByteOrder byteOrder); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @brief Takes image file and attempts to derive/find header file to * parse for general raster data, i.e. lines, samples, bands and so on. * @param image file. * @return true on success, false on error. */ bool open( const ossimFilename& imageFile ); /** @return Const reference to theMetaData class member. */ inline const ossimImageMetaData& getImageMetaData() const; /** @return Reference to theMetaData class member. */ inline ossimImageMetaData& getImageMetaData(); /** * @brief Initialize from envi header file. * @param enviHeader * @return true on success, false on error. */ bool initializeFromEnviHdr( const ossimEnviHeader& enviHdr ); private: /** * @brief Initialize from header file. * @param headerFile * @return true on success, false on error. */ bool initializeFromHdr( const ossimFilename& imageFile, const ossimFilename& headerFile ); /** * @brief Initialize from envi header file. * @param headerFile * @return true on success, false on error. */ bool initializeFromEnviHdr( const ossimFilename& headerFile ); /** * @brief Initialize from omd file. * @param file * @return true on success, false on error. */ bool initializeFromXml( const ossimFilename& imageFile, const ossimFilename& headerFile ); /** * @brief Private method to get bits per pixel from file size, * lines, samples and bands. Method created to avoid duplicate code * in "initizeFrom" methods. * * This assumes that "theRawImageRect" and "theNumberOfBands" has been * set. * * @param imageFile This image file. * @param Calculated bits per pixel. * @return bits per pixel or 0 on error. */ ossim_int32 getBitsPerPixel( const ossimFilename& imageFile ) const; /** @brief Clears data members. */ void clear(); ossimImageMetaData theMetaData; std::vector theImageFileList; ossimInterleaveType theInterleaveType; /** * The zero based rectangle of the entire image not including any header. */ ossimIrect theRawImageRect; /** * The rectangle representing where the valid part of the image lies * within "theRawImageRect". */ ossimIrect theValidImageRect; /** * The valid image rectangle normalized to be zero based. */ ossimIrect theImageRect; /** * The offset from the full-image origin to this image's origin */ ossimIpt theSubImageOffset; /** * Size of header in bytes. */ ossim_int32 theHeaderSize; /** * Mode of how to handle pixels on import. * 0 = Do nothing the pixels. * 1 = Set any zeroes to min value of radiometry. * 2 = Set zeroes on line edges only to nulls; any other zeroes are * set to min value of radiometry. */ ossimFillMode theSetNullsMode; /** * Amount of pixels to chop for each line edge. */ ossim_int32 thePixelsToChop; /** * The byte order the image data is stored in. */ ossimByteOrder theImageDataByteOrder; }; //--- // Inlines: // // These methods are used throughout raster read/write code; hence, inlines. // Note that most of these are used in calculating std::streamoff which is // a signed 64 bit integer on most machines; hence, the cast to an int from // an unsigned int for convenience. //--- inline const ossimImageMetaData& ossimGeneralRasterInfo::getImageMetaData() const { return theMetaData; } inline ossimImageMetaData& ossimGeneralRasterInfo::getImageMetaData() { return theMetaData; } inline ossim_int32 ossimGeneralRasterInfo::numberOfBands() const { return static_cast( theMetaData.getNumberOfBands() ); } inline ossim_int32 ossimGeneralRasterInfo::bytesPerPixel() const { return static_cast( theMetaData.getBytesPerPixel() ); } inline ossim_int32 ossimGeneralRasterInfo::validLines() const { return static_cast(theValidImageRect.height()); } inline ossim_int32 ossimGeneralRasterInfo::rawLines() const { return static_cast(theRawImageRect.height()); } inline ossim_int32 ossimGeneralRasterInfo::bytesPerRawLine() const { if (interleaveType() == OSSIM_BIP) { return rawSamples() * bytesPerPixel() * numberOfBands(); } else { return rawSamples() * bytesPerPixel(); } } inline ossim_int32 ossimGeneralRasterInfo::bytesPerValidLine() const { if (interleaveType() == OSSIM_BIP) { return validSamples() * bytesPerPixel() * numberOfBands(); } else { return validSamples() * bytesPerPixel(); } } inline ossim_int32 ossimGeneralRasterInfo::validSamples() const { return static_cast(theValidImageRect.width()); } inline ossim_int32 ossimGeneralRasterInfo::rawSamples() const { return static_cast(theRawImageRect.width()); } inline std::streamoff ossimGeneralRasterInfo::offsetToFirstValidSample() const { if (interleaveType() == OSSIM_BIP) { return headerSize() + ( bytesPerRawLine() * validImageRect().ul().y ) + ( validImageRect().ul().x * numberOfBands() * bytesPerPixel() ); } else if (interleaveType() == OSSIM_BIL) { return headerSize() + ( bytesPerRawLine() * validImageRect().ul().y * numberOfBands() ) + ( validImageRect().ul().x * bytesPerPixel() ); } else // BSQ { return headerSize() + ( bytesPerRawLine() * validImageRect().ul().y ) + ( validImageRect().ul().x * bytesPerPixel() ); } } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeneralRasterTileSource.h000066400000000000000000000163021352751253100260660ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration for ossimGeneralRasterTileSource. // ossimGeneralRasterTileSource is derived from ImageHandler which is // derived from ossimTileSource. //******************************************************************* // $Id: ossimGeneralRasterTileSource.h 21631 2012-09-06 18:10:55Z dburken $ #ifndef ossimGeneralRasterTileSource_HEADER #define ossimGeneralRasterTileSource_HEADER 1 #include #include #include #include #include class ossimImageData; class OSSIM_DLL ossimGeneralRasterTileSource : public ossimImageHandler { public: ossimGeneralRasterTileSource(); virtual ossimString getShortName()const; virtual ossimString getLongName()const; /** * Returns a pointer to a tile given an origin representing the upper * left corner of the tile to grab from the image. * Satisfies pure virtual from TileSource class. */ virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Returns the number of bands in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; /** * Returns the number of bands in a tile returned from this TileSource. * Note: we are supporting sources that can have multiple data objects. * If you want to know the scalar type of an object you can pass in the */ virtual ossim_uint32 getNumberOfOutputBands() const; /** * Returns the number of lines in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; /** * Returns the number of samples in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. * Note: This handler will always return 0 for this method. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. * Note: This handler will always return 0 for this method. */ virtual ossim_uint32 getImageTileHeight() const; bool isValidRLevel(ossim_uint32 reduced_res_level) const; virtual void close(); virtual bool isOpen() const; virtual bool open(); virtual bool open(const ossimGeneralRasterInfo& info); /** * Override base getXXXXPixValue methods since the null/min/max can be set * to something different. Currently returns the same value for all bands. */ virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual ossimRefPtr getImageGeometry(); /** * @brief Indicates whether or not the image handler can control output * band selection via the setOutputBandList method. * * Overrides: ossimImageHandler::isBandSelector * * @return true */ virtual bool isBandSelector() const; /** * @brief If the image handler "isBandSeletor()" then the band selection * of the output chip can be controlled. * * Overrides: ossimImageHandler::setOutputBandList * * @return true on success, false on error. */ virtual bool setOutputBandList(const std::vector& band_list); /** @brief Initializes bandList to the zero based order of output bands. */ virtual void getOutputBandList(std::vector& bandList) const; protected: virtual ~ossimGeneralRasterTileSource(); /** * Methods return true on succes false on error. */ virtual bool fillBuffer(const ossimIpt& origin, const ossimIpt& size); virtual bool fillBIP(const ossimIpt& origin, const ossimIpt& size); virtual bool fillBIL(const ossimIpt& origin, const ossimIpt& size); virtual bool fillBSQ(const ossimIpt& origin, const ossimIpt& size); virtual bool fillBsqMultiFile(const ossimIpt& origin, const ossimIpt& size); virtual ossimKeywordlist getHdrInfo(ossimFilename hdrFile); virtual ossimKeywordlist getXmlInfo(ossimFilename xmlFile); bool initializeHandler(); ossimRefPtr m_tile; ossim_uint8* m_buffer; ossim_uint8* m_lineBuffer; ossimInterleaveType m_bufferInterleave; std::vector< std::shared_ptr > m_fileStrList; // std::vector< std::ifstream* > m_fileStrList; ossimGeneralRasterInfo m_rasterInfo; ossimIrect m_bufferRect; bool m_swapBytesFlag; ossim_uint32 m_bufferSizeInPixels; std::vector m_outputBandList; private: /** @brief Allocates m_tile. */ void allocateTile(); /** @brief Allocates m_buffer */ void allocateBuffer( const ossimImageData* tile ); TYPE_DATA }; #endif /* #ifndef ossimGeneralRasterTileSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimGeneralRasterWriter.h000066400000000000000000000102261352751253100252630ustar00rootroot00000000000000 //******************************************************************* // Copyright (C) 2001 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declaration for ossimGeneralRasterWriter. // //******************************************************************* // $Id: ossimGeneralRasterWriter.h 22197 2013-03-12 02:00:55Z dburken $ #ifndef ossimGeneralRasterWriter_HEADER #define ossimGeneralRasterWriter_HEADER 1 #include #include #include #include #include #include class OSSIM_DLL ossimGeneralRasterWriter : public ossimImageFileWriter { public: /** @brief default constructor */ ossimGeneralRasterWriter(); /** * void getImageTypeList(std::vector& imageTypeList)const * * Appends this writer image types to list "imageTypeList". * * This writer has the following types: * general_raster_bip * general_raster_bil * general_raster_bsq * * @param imageTypeList stl::vector list to append to. */ virtual void getImageTypeList(std::vector& imageTypeList)const; /** * Returns a 3-letter extension from the image type descriptor * (theOutputImageType) that can be used for image file extensions. * * @param imageType string representing image type. * * @return the 3-letter string extension. */ virtual ossimString getExtension() const; virtual void set_rr_level(ossim_uint32 rr) { theRlevel = rr; } virtual bool isOpen()const; virtual bool open(); virtual void close(); /** * saves the state of the object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @brief Method to write the image to a stream. * * Callers must call setOutputStream(...) method prior to this. * * @return true on success, false on error. */ virtual bool writeStream(); /** * @brief Sets the output stream to write to. * * The stream will not be closed/deleted by this object. * * @param output The stream to write to. */ virtual bool setOutputStream(std::ostream& stream); protected: /** * Write out the file. * @return true on success, false on error. */ virtual bool writeFile(); /** @brief Protected ( this is a ossimRefPtr) destructor. */ virtual ~ossimGeneralRasterWriter(); private: /** * Writes image data to output file in BIP(Band Interleaved by Pixel) * format. * @return true on success, false on error. */ bool writeToBip(); /** * Writes image data to output file in BIL(Band Interleaved by Line) * format. * @return true on success, false on error. */ bool writeToBil(); /** * Writes image data to output file in BSQ(Band Sequential) format. * @return true on success, false on error. */ bool writeToBsq(); /** * Writes an ossim header file which can be used to load file in ossim. * Returns true on success, false on error. */ void writeHeader() const; /** * Writes an envi header file which can be used to load file in envi. * If the output image file is "foo.ras" then the ossim header file will * be "foo.hdr". */ void writeEnviHeader() const; /** * @return The interleave as a string of either: bil, bip, or bsq */ ossimString getInterleaveString() const; std::ostream* theOutputStream; bool theOwnsStreamFlag; ossim_uint32 theRlevel; ossimByteOrder theOutputByteOrder; /** * Populated while writting the data */ std::vector theMinPerBand; std::vector theMaxPerBand; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationBitmap.h000066400000000000000000000033321352751253100252320ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationBitmap.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeoAnnotationBitmap_HEADER #define ossimGeoAnnotationBitmap_HEADER #include class OSSIMDLLEXPORT ossimGeoAnnotationBitmap: public ossimGeoAnnotationObject { public: ossimGeoAnnotationBitmap(const ossimGpt& center= ossimGpt(0,0,0), ossimRefPtr imageData=0, unsigned char r = 255, unsigned char g = 255, unsigned char b = 255); ossimGeoAnnotationBitmap(const ossimGeoAnnotationBitmap& rhs); virtual ossimObject* dup()const; virtual bool intersects(const ossimDrect& rect) const; virtual ossimGeoAnnotationBitmap* getNewClippedObject(const ossimDrect& rect)const; virtual void applyScale(double x, double y); virtual std::ostream& print(std::ostream& out)const; virtual void draw(ossimRgbImage& anImage)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void transform(ossimImageGeometry* projection); virtual void setImageData(ossimRefPtr& imageData); virtual void computeBoundingRect(); protected: virtual ~ossimGeoAnnotationBitmap(); ossimGpt theCenterPoint; ossimDpt theProjectedPoint; ossimRefPtr theImageData; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationEllipseObject.h000066400000000000000000000110471352751253100265440ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationEllipseObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeoAnnotationEllipseObject_HEADER #define ossimGeoAnnotationEllipseObject_HEADER #include #include class OSSIMDLLEXPORT ossimGeoAnnotationEllipseObject : public ossimGeoAnnotationObject { public: /*! * It is important to note that the width and height * should be specified in width = deltaLon and * height = deltaLat. Use the ossimDpt .lat and .lon * attributes to set it. */ ossimGeoAnnotationEllipseObject(const ossimGpt& center = ossimGpt(0,0), const ossimDpt& widthHeight = ossimDpt(0,0), bool enableFill = false, ossim_uint8 r = 255, ossim_uint8 g = 255, ossim_uint8 b = 255, ossim_uint8 thickness = 1); ossimGeoAnnotationEllipseObject(const ossimGeoAnnotationEllipseObject& rhs); virtual ossimObject* dup()const; virtual void applyScale(double x, double y); virtual std::ostream& print(std::ostream& out)const; virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void computeBoundingRect(); virtual void transform(ossimImageGeometry* projection); /** * Saves the current state of this object. * * Keywords: * * center: ( 42.403388263727003, -90.708557648541046, 0.0, WGE ) * * ellipse_width: 500 * * ellipse_height: 500 * * units: meters */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void setEllipseWidthHeightUnitType(ossimUnitType type); /** * Sets the width and height of point. * * @param pt Point with pt.x being width and pt.y being height. */ virtual void setWidthHeight(const ossimDpt& pt); /** * @brief Sets the azimuth. * @param azimuth in degrees. */ virtual void setAzimuth(ossim_float64 azimuth); /** * @brief Gets the azimuth. * @return The azimuth in decimal degrees. */ virtual ossim_float64 getAzimuth() const; /** * Sets the color of theProjectedEllipse. RGB range 0 to 255 * * @param r DN value for red. * @param g DN value for green. * @param b DN value for blue. */ virtual void setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); /** * Sets the pen thickness of theProjectedEllipse. range 0 to 255 * * @param thickness Pen thickness. */ virtual void setThickness(ossim_uint8 thickness); /** * Sets the fill flag. * * @bool flag True to fill, false to not fill. */ virtual void setFillFlag(bool flag); /** @return The fill flag. */ virtual bool getFillFlag() const; /** * @brief Turns on and off drawing of axes on the ellipse. * This flag is only used if fill is turned off. * * @param flag true to enable, false to disable. */ virtual void setDrawAxesFlag(bool flag); /** @return The draw axes flag. */ virtual bool getDrawAxesFlag() const; /** * @brief Sets the center ground point. * @param gpt The center ground point. */ virtual void setCenter(const ossimGpt& gpt); /** @param gpt The point to initialize with the center. */ virtual void getCenter(ossimGpt& gpt) const; protected: virtual ~ossimGeoAnnotationEllipseObject(); void getWidthHeightInPixels(ossimDpt& widthHeight, const ossimImageGeometry* projection) const; ossimRefPtr theProjectedEllipse; ossimGpt theCenter; ossimDpt theWidthHeight; ossimUnitType theEllipseWidthHeightUnitType; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationFontObject.h000066400000000000000000000073671352751253100260670ustar00rootroot00000000000000//************************************************************************* // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationFontObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeoAnnotationFontObject_HEADER #define ossimGeoAnnotationFontObject_HEADER #include #include class ossimFont; class ossimGeoAnnotationFontObject : public ossimGeoAnnotationObject { public: ossimGeoAnnotationFontObject(); ossimGeoAnnotationFontObject(const ossimGpt& location, const ossimString& s, const ossimIpt& pixelSize = ossimIpt(12, 12), double rotation = 0.0, const ossimDpt& scale = ossimDpt(1.0, 1.0), const ossimDpt& shear = ossimDpt(0.0,0.0), ossim_uint8 r=255, ossim_uint8 g=255, ossim_uint8 b=255); ossimGeoAnnotationFontObject(const ossimGeoAnnotationFontObject& rhs); virtual ossimObject* dup()const; ossimAnnotationFontObject* getFontObject(); void setFont(ossimFont* font); ossimFont* getFont(); virtual void setPointSize(const ossimIpt& size); virtual void setRotation(double rotation); virtual void setScale(const ossimDpt& scale); virtual void setShear(const ossimDpt& shear); virtual void setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); virtual void transform(ossimImageGeometry* projection); virtual void setCenterGround(const ossimGpt& gpt); virtual void draw(ossimRgbImage& anImage)const; virtual void computeBoundingRect(); virtual void getBoundingRect(ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject( const ossimDrect& rect)const; virtual bool intersects(const ossimDrect& rect)const; virtual void applyScale(double x, double y); /** * Saves the current state of this object. * * @see loadState for keywords. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. * * Keywords: * * For center format is: ( latitude, longitude, height, datum_code ) * center: ( 42.01, -90.71, 0.0, WGE ) * * For point_size format is: "( x, y )" * point_size: ( 18, 18 ) * * For scale format is: "( x, y )" * scale: ( 1.0, 1.0 ) * * For shear format is: "( x, y )" * shear: ( 0.0, 0.0 ) * * text: Airport * * USE ONE OF family_name: * family_name: URW Palladio L * family_name: gd sans * family_name: URW Bookman L * family_name: Nimbus Roman No9 L * family_name: Nimbus Sans L * family_name: URW Palladio L * family_name: Century Schoolbook L * family_name: Nimbus Mono L * family_name: Nimbus Sans L Condensed * * USE ONE OF style_name: * style_name: normal * style_name: bold * style_name: italic * style_name: bold italic */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimGeoAnnotationFontObject(); ossimGpt theCenterGround; ossimRefPtr theFont; ossimFontInformation theFontInfo; ossimRefPtr theAnnotationFontObject; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationGdBitmapFont.h000066400000000000000000000041261352751253100263360ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // //************************************************************************* // $Id: ossimGeoAnnotationGdBitmapFont.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeoAnnotationGdBitmapFont_HEADER #define ossimGeoAnnotationGdBitmapFont_HEADER #include #include #include class ossimAnnotationGdBitmapFont; class OSSIMDLLEXPORT ossimGeoAnnotationGdBitmapFont : public ossimGeoAnnotationObject { public: ossimGeoAnnotationGdBitmapFont(const ossimGpt& position=ossimGpt(0,0,0), const ossimString &text=ossimString(""), ossimGdFontPtr font = ossimGdFontLarge, unsigned char r = 255, unsigned char g = 255, unsigned char b = 255, long thickness = 1); ossimGeoAnnotationGdBitmapFont(const ossimGeoAnnotationGdBitmapFont& rhs); virtual ossimObject* dup()const; virtual void applyScale(double x, double y); virtual std::ostream& print(std::ostream& out)const; virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void computeBoundingRect(); /*! * Add the projection interface to all * geographically defined objects. */ virtual void transform(ossimImageGeometry* projection); virtual void setText(const ossimString& text); virtual void setFont(ossimGdFontPtr font); protected: virtual ~ossimGeoAnnotationGdBitmapFont(); ossimRefPtr theProjectedFont; /*! * Will be the upper left corner of text; */ ossimGpt thePosition; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationLineObject.h000066400000000000000000000032671352751253100260430ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimGeoAnnotationLineObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeoAnnotationLineObject_HEADER #define ossimGeoAnnotationLineObject_HEADER #include #include class ossimAnnotationLineObject; class ossimGeoAnnotationLineObject : public ossimGeoAnnotationObject { public: ossimGeoAnnotationLineObject(const ossimGpt& start, const ossimGpt& end, unsigned char r=255, unsigned char g=255, unsigned char b=255, long thickness=1); ossimGeoAnnotationLineObject(const ossimGeoAnnotationLineObject& rhs); virtual ossimObject* dup()const; virtual void applyScale(double x, double y); virtual void transform(ossimImageGeometry* projection); virtual std::ostream& print(std::ostream& out)const; virtual bool intersects(const ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual void draw(ossimRgbImage& anImage)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void computeBoundingRect(); protected: virtual ~ossimGeoAnnotationLineObject(); ossimAnnotationLineObject* theProjectedLineObject; ossimGpt theStart; ossimGpt theEnd; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationMultiEllipseObject.h000066400000000000000000000054611352751253100275620ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationMultiEllipseObject.h 23239 2015-04-08 01:02:44Z gpotts $ #ifndef ossimGeoAnnotationMultiEllipseObject_HEADER #define ossimGeoAnnotationMultiEllipseObject_HEADER #include #include class ossimAnnotationMultiEllipseObject; class OSSIM_DLL ossimGeoAnnotationMultiEllipseObject : public ossimGeoAnnotationObject { public: ossimGeoAnnotationMultiEllipseObject(); virtual ~ossimGeoAnnotationMultiEllipseObject(); ossimGeoAnnotationMultiEllipseObject(const std::vector& centerPoints, const ossimDpt& widthHeight, bool enableFill = false, unsigned char r = 255, unsigned char g = 255, unsigned char b = 255, long thickness = 1); ossimGeoAnnotationMultiEllipseObject(const ossimDpt& widthHeight, bool enableFill = false, unsigned char r = 255, unsigned char g = 255, unsigned char b = 255, long thickness = 1); ossimGeoAnnotationMultiEllipseObject(const ossimGeoAnnotationMultiEllipseObject& rhs); virtual ossimObject* dup()const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual void transform(ossimImageGeometry* projection); virtual void applyScale(double x, double y); virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual void addPoint(const ossimGpt& point); virtual void setColor(unsigned char r, unsigned char g, unsigned char b); virtual void setThickness(ossim_uint8 thickness); virtual void setPoint(int i, const ossimGpt& point); virtual void setWidthHeight(const ossimDpt& widthHeight); virtual void resize(ossim_uint32 newSize); virtual void setFillFlag(bool fillFlag); virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void computeBoundingRect(); protected: ossimAnnotationMultiEllipseObject* theProjectedObject; std::vector thePointList; ossimDpt theWidthHeight; bool theFillFlag; }; #endif /* #ifndef ossimGeoAnnotationMultiEllipseObject_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationMultiPolyLineObject.h000066400000000000000000000060101352751253100277070ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationMultiPolyLineObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeoAnnotationMultiPolyLineObject_HEADER #define ossimGeoAnnotationMultiPolyLineObject_HEADER #include #include #include #include #include class ossimDatum; class OSSIM_DLL ossimGeoAnnotationMultiPolyLineObject : public ossimGeoAnnotationObject { public: ossimGeoAnnotationMultiPolyLineObject(); ossimGeoAnnotationMultiPolyLineObject(const std::vector& multiPolyLine, ossim_uint8 r=255, ossim_uint8 g=255, ossim_uint8 b=255, ossim_uint8 thickness=1); ossimGeoAnnotationMultiPolyLineObject(const ossimGeoAnnotationMultiPolyLineObject& rhs); virtual ossimObject* dup()const; virtual void transform(ossimImageGeometry* projection); virtual void applyScale(double x, double y); virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void addPoint(ossim_uint32 polygonIndex, const ossimGpt& pt); virtual void setMultiPolyLine(const std::vector& multiPoly); virtual void computeBoundingRect(); virtual bool isPointWithin(const ossimDpt& imagePoint)const; virtual void setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); virtual void setThickness(ossim_uint8 thickness); void setDatum(const ossimDatum* datum); const ossimDatum* getDatum()const; const std::vector& getMultiPolyLine()const; std::vector& getMultiPolyLine(); /** * Saves the current state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimGeoAnnotationMultiPolyLineObject(); std::vector theMultiPolyLine; ossimDrect theBoundingRect; const ossimDatum* theDatum; ossimRefPtr theProjectedPolyLineObject; void allocateProjectedPolyLine(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationMultiPolyObject.h000066400000000000000000000051471352751253100271110ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: // //************************************************************************* // $Id: ossimGeoAnnotationMultiPolyObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeoAnnotationMultiPolyObject_HEADER #define ossimGeoAnnotationMultiPolyObject_HEADER #include #include #include #include class OSSIM_DLL ossimGeoAnnotationMultiPolyObject : public ossimGeoAnnotationObject { public: ossimGeoAnnotationMultiPolyObject(); ossimGeoAnnotationMultiPolyObject(const std::vector& multiPoly, bool enableFill=false, unsigned char r=255, unsigned char g=255, unsigned char b=255, long thickness=1); ossimGeoAnnotationMultiPolyObject(const ossimGeoAnnotationMultiPolyObject& rhs); virtual ossimObject* dup()const; virtual void transform(ossimImageGeometry* projection); virtual void applyScale(double x, double y); virtual void draw(ossimRgbImage& anImage)const; virtual bool intersects(const ossimDrect& rect)const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual std::ostream& print(std::ostream& out)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void addPoint(ossim_uint32 polygonIndex, const ossimGpt& pt); virtual void setMultiPolygon(const std::vector& multiPoly); virtual void setColor(unsigned char r, unsigned char g, unsigned char b); virtual void setThickness(ossim_uint8 thickness); virtual void computeBoundingRect(); virtual bool isPointWithin(const ossimDpt& imagePoint)const; virtual void setFillFlag(bool flag); const std::vector& getMultiPolygon()const{return theMultiPolygon;} std::vector& getMultiPolygon(){return theMultiPolygon;} protected: virtual ~ossimGeoAnnotationMultiPolyObject(); std::vector theMultiPolygon; ossimDrect theBoundingRect; bool theFillEnabled; ossimRefPtr theProjectedPolyObject; void allocateProjectedPolygon(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationObject.h000066400000000000000000000030531352751253100252240ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeoAnnotationObject_HEADER #define ossimGeoAnnotationObject_HEADER #include #include #include class ossimImageProjectionModel; class OSSIM_DLL ossimGeoAnnotationObject : public ossimAnnotationObject { public: ossimGeoAnnotationObject(unsigned char r=255, unsigned char g=255, unsigned char b=255, long thickness=1); ossimGeoAnnotationObject(const ossimGeoAnnotationObject& rhs); /*! * Add the projection interface to all * geographically defined objects. */ virtual void transform(ossimImageGeometry* projection)=0; /** * Saves the current state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimGeoAnnotationObject(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationPolyLineObject.h000066400000000000000000000042451352751253100267040ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationPolyLineObject.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeoAnnotationPolyLineObject_HEADER #define ossimGeoAnnotationPolyLineObject_HEADER #include #include class ossimAnnotationMultiLineObject; class OSSIMDLLEXPORT ossimGeoAnnotationPolyLineObject : public ossimGeoAnnotationObject { public: ossimGeoAnnotationPolyLineObject(const std::vector& groundPts, ossim_uint8 r=255, ossim_uint8 g=255, ossim_uint8 b=255, ossim_uint8 thickness=1); ossimGeoAnnotationPolyLineObject(const ossimGeoAnnotationPolyLineObject& rhs); virtual ossimObject* dup()const; virtual void applyScale(double x, double y); virtual void transform(ossimImageGeometry* projection); virtual std::ostream& print(std::ostream& out)const; virtual void draw(ossimRgbImage& anImage)const; virtual ossimAnnotationObject* getNewClippedObject(const ossimDrect& rect)const; virtual bool intersects(const ossimDrect& rect)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void computeBoundingRect(); /** * Sets the color of thePolygon. RGB range 0 to 255 * * @param r DN value for red. * @param g DN value for green. * @param b DN value for blue. */ virtual void setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); /** * Sets the pen thickness of thePolygon. range 0 to 255 * * @param thickness Pen thickness. */ virtual void setThickness(ossim_uint8 thickness); protected: virtual ~ossimGeoAnnotationPolyLineObject(); std::vector thePolygon; ossimAnnotationMultiLineObject* theProjectedMultiLineObject; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationPolyObject.h000066400000000000000000000061421352751253100260720ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationPolyObject.h 19734 2011-06-06 23:45:36Z dburken $ #ifndef ossimGeoAnnotationPolyObject_HEADER #define ossimGeoAnnotationPolyObject_HEADER #include #include #include #include class OSSIMDLLEXPORT ossimGeoAnnotationPolyObject : public ossimGeoAnnotationObject { public: enum ossimPolyType { OSSIM_POLY_EXTERIOR_RING = 0, OSSIM_POLY_INTERIOR_RING = 1 }; ossimGeoAnnotationPolyObject(bool enableFill = false, ossim_uint8 r=255, ossim_uint8 g=255, ossim_uint8 b=255, ossim_uint8 thickness=1); ossimGeoAnnotationPolyObject(const std::vector& groundPts, bool enableFill = false, ossim_uint8 r=255, ossim_uint8 g=255, ossim_uint8 b=255, ossim_uint8 thickness=1); ossimGeoAnnotationPolyObject(const ossimGeoAnnotationPolyObject& rhs); virtual ossimObject* dup()const; virtual void applyScale(double x, double y); virtual void transform(ossimImageGeometry* projection); virtual std::ostream& print(std::ostream& out)const; virtual void draw(ossimRgbImage& anImage)const; virtual ossimAnnotationObject* getNewClippedObject( const ossimDrect& rect)const; virtual bool intersects(const ossimDrect& rect)const; virtual void getBoundingRect(ossimDrect& rect)const; virtual void computeBoundingRect(); virtual const std::vector& getPolygon()const; virtual void setPolygon(const std::vector& poly); virtual void setFillFlag(bool flag); virtual void setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); virtual void setThickness(ossim_uint8 thickness); /** * Saves the current state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual std::vector getPoints() { return thePolygon; } virtual ossimPolyType getPolyType () { return m_PolyType; } virtual void setPolyType(ossimPolyType polyType) { m_PolyType = polyType; } protected: virtual ~ossimGeoAnnotationPolyObject(); std::vector thePolygon; ossimRefPtr theProjectedPolyObject; ossimPolyType m_PolyType; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoAnnotationSource.h000066400000000000000000000043051352751253100252570ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimGeoAnnotationSource.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimGeoAnnotationSource_HEADER #define ossimGeoAnnotationSource_HEADER #include #include #include #include class ossimGeoAnnotationObject; class ossimProjection; class OSSIM_DLL ossimGeoAnnotationSource : public ossimAnnotationSource, public ossimViewInterface { public: friend std::ostream& operator <<(std::ostream& out, const ossimGeoAnnotationSource& rhs); ossimGeoAnnotationSource(ossimImageGeometry* geom=NULL, bool ownsProjectionFlag=false); ossimGeoAnnotationSource(ossimImageSource* inputSource, ossimImageGeometry* geom=NULL, bool ownsProjectionFlag=false); /*! * Will add an object to the list. * it will own the object added. If the * object is not geographic */ virtual bool addObject(ossimAnnotationObject* anObject); virtual void computeBoundingRect(); virtual void transformObjects(ossimImageGeometry* geom=0); virtual void setGeometry(ossimImageGeometry* projection); virtual bool setView(ossimObject* baseObject); virtual ossimRefPtr getImageGeometry(); virtual ossimObject* getView(); virtual const ossimObject* getView()const; /** * Saves the current state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimGeoAnnotationSource(); ossimRefPtr m_geometry; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeoPolyCutter.h000066400000000000000000000167061352751253100241060ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimGeoPolyCutter.h 22303 2013-07-04 18:15:52Z dburken $ #ifndef ossimGeoPolyCutter_HEADER #define ossimGeoPolyCutter_HEADER 1 #include #include #include #include class ossimImageData; class ossimProjection; /*! * ossimGeoPolyCutter. * * This classes overrides the 2-d counter part ossimPolyCutter. It will automatically * map 2-D to 3-D (ground) polygons if you add 2-D polygons and will automatically * compute the forward transform when adding a ground polygon. * * you can set the view trough the ossimViewInterface by calling setView(object, true); * it will cast to an ossimProjection and use that as the transformation. For igen this is * set automatically and does not need to be set by the user. * * This class has no keywords but does use 2 prefix values to store out the view * and the ground polygon for example if we have only one polygon then here is a sample * keyword list for the polygons: NOTE we can have any number of polygons just increment * the geo_polygon0 to geo_polygon1 .. geo_polygonN for the Nth one * *
 *
 * geo_polygon0.datum:  WGE
 * geo_polygon0.number_vertices:  18
 * geo_polygon0.type:  ossimGeoPolygon
 * geo_polygon0.v0:  38.023634368488452 -122.542245818545709 nan
 * geo_polygon0.v1:  38.016619667868909 -122.548990722987568 nan
 * geo_polygon0.v2:  38.018238444934966 -122.546292761210807 nan
 * geo_polygon0.v3:  38.012932453440698 -122.547911538276864 nan
 * geo_polygon0.v4:  38.014731094625191 -122.542065954427244 nan
 * geo_polygon0.v5:  38.007446597827986 -122.541796158249582 nan
 * geo_polygon0.v6:  38.009694899308606 -122.537569351466018 nan
 * geo_polygon0.v7:  38.005108364288141 -122.537119691169892 nan
 * geo_polygon0.v8:  38.008255986361007 -122.532353292030976 nan
 * geo_polygon0.v9:  38.003039926925965 -122.531274107320272 nan
 * geo_polygon0.v10:  38.013292181677599 -122.529565398195004 nan
 * geo_polygon0.v11:  38.009874763427050 -122.526867436418243 nan
 * geo_polygon0.v12:  38.019587425823332 -122.528306349365849 nan
 * geo_polygon0.v13:  38.023904164666128 -122.537299555288328 nan
 * geo_polygon0.v14:  38.024983349376825 -122.544584052085540 nan
 * geo_polygon0.v15:  38.023904164666128 -122.548720926809878 nan
 * geo_polygon0.v16:  38.022195455540853 -122.562210735693611 nan
 * geo_polygon0.v17:  38.019317629645663 -122.562930192167400 nan
 *
 *
 * the example for the view information is
 *
 * view.central_meridian:  -123.000000000000000
 * view.datum:  WGE
 * view.decimal_degrees_per_pixel_lat:  0.000089932059225
 * view.decimal_degrees_per_pixel_lon:  0.000089932059225
 * view.ellipse_code:  WE
 * view.ellipse_name:  WGS 84
 * view.false_easting:  0.000000000000000
 * view.false_northing:  0.000000000000000
 * view.major_axis:  6378137.000000000000000
 * view.meters_per_pixel_x:  10.000000000000000
 * view.meters_per_pixel_y:  10.000000000000000
 * view.minor_axis:  6356752.314199999906123
 * view.origin_latitude:  0.000000000000000
 * view.rotation:  0.000000000000000
 * view.scale_x:  1.000000000000000
 * view.scale_y:  1.000000000000000
 * view.tie_point_easting:  0.000000000000000
 * view.tie_point_lat:  0.000000000000000
 * view.tie_point_lon:  -123.000000000000000
 * view.tie_point_northing:  0.000000000000000
 * view.translation_x:  0.000000000000000
 * view.translation_y:  0.000000000000000
 * view.type:  ossimEquDistCylProjection
 *
 * 
*/ class OSSIM_DLL ossimGeoPolyCutter : public ossimPolyCutter, public ossimViewInterface { public: ossimGeoPolyCutter(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /*! * Sets the polygon to the specified polygon index. * /param polygon A vector of points in projected 2-D. * /param i index of the polygon to change. */ virtual void setPolygon(const std::vector& polygon, ossim_uint32 i = 0); /*! * Sets the polygon to the specified polygon index. * /param polygon A vector of points in projected 2-D. * /param i index of the polygon to change. */ virtual void setPolygon(const std::vector& polygon, ossim_uint32 i = 0); /*! * Sets the polygon to the specified polygon index. * /param polygon A Ground polygon. * /param i index of the polygon to change. */ virtual void setPolygon(const std::vector& polygon, ossim_uint32 i = 0); virtual void setPolygon(const ossimGeoPolygon& polygon, ossim_uint32 i = 0); /*! * Will invert this polygon out to world space and add it to the * polygon list */ virtual void addPolygon(const std::vector& polygon); /*! * Will invert the passed in polygon to world space and add to the * polygon list */ virtual void addPolygon(const std::vector& polygon); /*! * Will add the ground polygon to the list */ virtual void addPolygon(const std::vector& polygon); /*! * Will invert te polygon to ground and add. */ virtual void addPolygon(const ossimPolygon& polygon); /*! * Will add the passed in polygon. */ virtual void addPolygon(const ossimGeoPolygon& polygon); /*! * Will set the number of polygons and will call the base * class set number of polygons. */ virtual void setNumberOfPolygons(ossim_uint32 count); /*! * This should only be used for informational uses only. If updates * are to be made please go through the access methods that change * the polygon data. */ virtual std::vector& getGeoPolygonList(); virtual const std::vector& getGeoPolygonList()const; /*! * Will set the view to the passed in object. Once set it will project the * ground polygon relative to the passed in view. */ virtual bool setView(ossimObject* baseObject); /*! * \return The current view for this object. */ virtual ossimObject* getView(); /*! * \return The constant pointer to the current view for this object. */ virtual const ossimObject* getView()const; protected: virtual ~ossimGeoPolyCutter(); /*! * Utility method used to invert any passed in projected polygons to * be changed or added to the list. * \param polygonNumber the index of the polygon to invert to ground. */ void invertPolygon(int polygonNumber); /*! * Transforms all vertices based on the current m_viewProjection. */ void transformVertices(); /*! * Transforms the specified polygon index. * \param i The polygon index to project. */ void transformVertices(int i); /*! * The view projection used to project the ground coordinates. */ ossimRefPtr m_viewGeometry; std::vector m_geoPolygonList; TYPE_DATA }; #endif /* #ifndef ossimGeoPolyCutter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimGeographicAnnotationGrid.h000066400000000000000000000025741352751253100262500ustar00rootroot00000000000000#ifndef ossimGeographicAnnotationGrid_HEADER #define ossimGeographicAnnotationGrid_HEADER #include #include #include #include class ossimMapProjection; class ossimGeographicAnnotationGrid : public ossimAnnotationObject { public: ossimGeographicAnnotationGrid(); virtual void draw(ossimRgbImage& anImage)const; /*! * We need to know what projection the view * and we need to know the bounding rect for * the view in geographic space. The bounding * rect is there for an area of interest. */ virtual void setViewProjectionInformation(ossimMapProjection* projection, const ossimGrect& boundingGroundRect); virtual void getBoundingRect(ossimDrect& rect)const; virtual void computeBoundingRect(); virtual std::ostream& print(std::ostream& out)const; protected: /*! * Holds the view projection. */ ossimRefPtr theViewProjection; ossimGrect theGroundRect; /*! * This will be computed based on the bounding * ground and projection. */ ossimDrect theBoundingRect; /*! * Will hold the spacing of the grid cells in * geographic lat lon change. */ double theDeltaLatSpacing; double theDeltaLonSpacing; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGeomFileWriter.h000066400000000000000000000030361352751253100242150ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2003 Storage Area Networks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Kenneth Melero (kmelero@sanz.com) // //******************************************************************* // $Id: ossimGeomFileWriter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGeomFileWriter_H #define ossimGeomFileWriter_H #include /** ossimGeomFileWriter */ class OSSIMDLLEXPORT ossimGeomFileWriter : public ossimMetadataFileWriter { public: /** default constructor */ ossimGeomFileWriter(); /** * Satisfies pure virtual from ossimMetadataWriter base. * * Appends the writers image types to the "metadatatypeList". * * @param metadatatypeList stl::vector list to append to. * * @note Appends to the list, does not clear it first. */ virtual void getMetadatatypeList( std::vector& metadatatypeList) const; /** * Satisfies pure virtual from ossimMetadataWriter base. * * @param imageType string representing image type. * * @return true if "metadataType" is supported by writer. */ virtual bool hasMetadataType(const ossimString& metadataType)const; protected: /** virtual destructor */ virtual ~ossimGeomFileWriter(); /** Write a geometry file to "theFilename". */ virtual bool writeFile(); TYPE_DATA }; #endif /* End of #ifndef ossimGeomFileWriter_H */ ossim-Miami-2.9.1/include/ossim/imaging/ossimGpkgWriterInterface.h000066400000000000000000000045751352751253100252500ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Interface for GeoPackage(gpkg) writers. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimGpkgWriterInterface_HEADER #define ossimGpkgWriterInterface_HEADER 1 #include #include class ossimImageData; class ossimKeywordlist; /** * @class GeoPackage writer interface. * * This interface is for using the ossimGeopackageWriter in a connectionless * manner. See ossim-gpkg-writer-test.cpp for example usage. */ class OSSIM_DLL ossimGpkgWriterInterface { public: /** * GP: I had to add this or windows would not link with the latest * compiler. Also had to put in dot.cpp for debug mode(again windows). * (drb) */ ossimGpkgWriterInterface(); /** * @brief Opens file for writing, appending, merging without an input * connection. I.e. opening, then calling writeTile directly. * * @param options. Keyword list containing all options. */ virtual bool openFile( const ossimKeywordlist& options ) = 0; /** * @brief Calls initial sqlite3_prepare_v2 statement. Must be called * prior to calling writeTile. * @return SQLITE_OK(0) on success, something other(non-zero) on failure. */ virtual ossim_int32 beginTileProcessing() = 0; /** * @brief Direct interface to writing a tile to database. * @param tile to write. * @param zoolLevel * @param row * @param col * @return true on success, false on error. */ virtual bool writeTile( ossimRefPtr& tile, ossim_int32 zoomLevel, ossim_int64 row, ossim_int64 col ) = 0; virtual bool writeCodecTile( ossim_uint8* codecTile, ossim_int32 codecTileSize, ossim_int32 zoomLevel, ossim_int64 row, ossim_int64 col ) = 0; /** * @brief Calls sqlite3_finalize(pStmt) terminating tile processing. */ virtual void finalizeTileProcessing() = 0; }; #endif /* End of "#ifndef ossimGpkgWriterInterface_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimGridRemapEngine.h000066400000000000000000000040421352751253100243270ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimGridRemapEngine.h // // Copyright (C) 2001 ImageLinks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains declaration of class // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimGridRemapEngine.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGridRemapEngine_HEADER #define ossimGridRemapEngine_HEADER #include #include #include class ossimDpt; class ossimGridRemapSource; class ossimImageData; class ossimAtbPointSource; /*!**************************************************************************** * * CLASS: ossimGridRemapEngine * *****************************************************************************/ class ossimGridRemapEngine : public ossimObject { public: virtual ossimObject* dup() const = 0; virtual void remapTile(const ossimDpt& origin_point, ossimGridRemapSource* remapper, ossimRefPtr& tile) = 0; virtual void assignRemapValues(std::vector& sources)=0; virtual void computeSourceValue(ossimRefPtr& source, void* result) = 0; int getNumberOfParams() const { return theNumberOfParams; } int getNumberOfBands() const { return theNumberOfBands; } protected: ossimGridRemapEngine(int numParams, int numBands) : theNumberOfParams(numParams), theNumberOfBands(numBands) {} ossimGridRemapEngine() {} virtual ~ossimGridRemapEngine() {} virtual void computeRemapNode(ossimAtbPointSource* point_source, void* source_value, void* target_value) = 0; int theNumberOfParams; int theNumberOfBands; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGridRemapEngineFactory.h000066400000000000000000000021171352751253100256600ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains declaration of class ossimGridRemapEngineFactory // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimGridRemapEngineFactory.h 23356 2015-06-03 18:28:03Z dburken $ #ifndef ossimGridRemapEngineFactory_HEADER #define ossimGridRemapEngineFactory_HEADER 1 #include /*!**************************************************************************** * * CLASS: ossimGridRemapEngineFactory (SIMPLETON) * *****************************************************************************/ class OSSIM_DLL ossimGridRemapEngineFactory { public: /*! * Attempts to create an instance of the Product given a Specifier. Returns * successfully constructed product or NULL. */ static ossimGridRemapEngine* create(const char* spec); protected: ossimGridRemapEngineFactory() {} }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimGridRemapSource.h000066400000000000000000000101301352751253100243550ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimGridRemapSource.h // // Copyright (C) 2001 ImageLinks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains declaration of class ossimGridRemapSource. This is // a spacially variant remapper that utilizes a grid for interpolating the // remap value given an image x, y. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimGridRemapSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimGridRemapSource_HEADER #define ossimGridRemapSource_HEADER #include #include #include #include class ossimDblGrid; class ossimDrect; class ossimDpt; class ossimImageData; /*!**************************************************************************** * * CLASS: ossimGridRemapSource * *****************************************************************************/ class ossimGridRemapSource : public ossimImageSourceFilter { public: /*! * Constructors: */ ossimGridRemapSource(); ossimGridRemapSource(ossimImageSource* inputSource, ossimGridRemapEngine* engine); /*!ossimAtbPointSource * Initializes the remap engine. This object implements specific algorithms * for interpreting the grids owned by this remapper. It actually performs * the remapping. */ void setRemapEngine(ossimGridRemapEngine* engine); /*! * Provides access to the remap engine: */ ossimGridRemapEngine* getRemapEngine() { return theRemapEngine; } /*! * Permits initializing the remap grid after construction. */ virtual void initialize(const ossimDrect& uv_rect, const ossimDpt& grid_spacing); /*! * Sets a node of the member grid to the value specified. The grid is flagged * as unfilled. */ void setGridNode(const ossimDpt& view_pt, const double* value); /*! * Implementation of virtual method to return remapped tile. */ virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); /*! * Restore the state of the object from a keywordlist. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /*! * Save the state of the object to a keywordlist. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Locks the image to prevent grid adjustment. The remapper continues to * remap given the current grid (if enabled), but all target values computed * are such that no change in the grids will occur in an adjsutment. If more * than one overlapping image is locked, the target will may be influenced * by all locked images, but the remap grids will not be updated. */ void lock() { theRemapIsLockedFlag = true; } /*! * Unlocks the grids for adjustment. */ void unlock() { theRemapIsLockedFlag = false; } /*! * Returns the status of the lock flag. */ bool isLocked() const { return theRemapIsLockedFlag; } /*! * Provides access to individual grids (pointer) given an index. Null pointer * returned if index out of range. */ ossimDblGrid* getGrid(unsigned int index); /*! * Returns grid filename (may be empty) */ const ossimFilename& getGridFilename() const { return theGridFilename; } /*! * Sets the grid filename and initiates read. */ void setGridFilename(const ossimFilename& grid_filename); protected: virtual ~ossimGridRemapSource(); /*! * Deallocates grid memory. */ void deallocateGrids(); std::vector theGrids; ossimFilename theGridFilename; ossimGridRemapEngine* theRemapEngine; bool theRemapIsLockedFlag; bool theGridIsFilled; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimHistoMatchRemapper.h000066400000000000000000000070161352751253100250720ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimHistoMatchRemapper.h 23353 2015-06-01 19:19:10Z dburken $ #ifndef ossimHistoMatchRemapper_HEADER #define ossimHistoMatchRemapper_HEADER 1 #include #include #include class OSSIM_DLL ossimHistoMatchRemapper: public ossimImageSourceFilter { public: ossimHistoMatchRemapper(); ossimHistoMatchRemapper(ossimImageSource* inputSource, const std::vector& targetMeanPerBand = std::vector(), const std::vector& targetSigmaPerBand = std::vector(), const std::vector& inputMeanPerBand = std::vector(), const std::vector& inputSigmaPerBand = std::vector() ); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); const std::vector& getInputMeanValues()const; const std::vector& getInputSigmaValues()const; const std::vector& getTargetMeanValues()const; const std::vector& getTargetSigmaValues()const; void setInputMeanValues(const std::vector& newValues); void setInputSigmaValues(const std::vector& newValues); void setTargetMeanValues(const std::vector& newValues); void setTargetSigmaValues(const std::vector& newValues); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL); protected: virtual ~ossimHistoMatchRemapper(); ossimRefPtr theBlankTile; std::vector theTargetMeanPerBand; std::vector theTargetSigmaPerBand; std::vector theInputMeanPerBand; std::vector theInputSigmaPerBand; /** * transLean * @param vIn input value to be transformed * @param vBias bias value to be removed * @param vTarget value that will replace bias * @param vMin minimum valid value of vIn (inclusive) * @param vMax maximum valid value of vIn (inclusive) * @return vOut */ double transLean(double vIn, double vBias, double vTarget, double vMin, double vMax); /** * transLeanStretch * @param vin Input value to be transformed. * @param vBias Bias value to be removed. * @param vBiasStretch dispersion (+/-) about vBias * @param vTarget value that will replace bias * @param vTargetStretch dispersion (+/-) about vTarget * @param vMin minimum valid value of vIn (inclusive) * @param vMax maximum valid value of vIn (inclusive) * @return vOut */ double transLeanStretch(double vIn, double vBias, double vBiasStretch, double vTarget, double vTargetStretch, double vMin, double vMax); }; #endif /* #ifndef ossimHistoMatchRemapper_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimHistogramEqualization.h000066400000000000000000000065521352751253100256620ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHistogramEqualization.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimHistogramEqualization_HEADER #define ossimHistogramEqualization_HEADER #include class OSSIMDLLEXPORT ossimHistogramEqualization : public ossimImageSourceHistogramFilter { public: ossimHistogramEqualization(); ossimHistogramEqualization(ossimImageSource* inputSource, ossimRefPtr histogram); ossimHistogramEqualization(ossimImageSource* inputSource, ossimRefPtr histogram, bool inverseFlag); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void setHistogram(ossimRefPtr histogram); virtual bool setHistogram(const ossimFilename& filename); virtual bool getInverseFlag()const; virtual void initialize(); virtual void setInverseFlag(bool inverseFlag); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; virtual std::ostream& print(std::ostream& out) const; protected: virtual ~ossimHistogramEqualization(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); ossimRefPtr theTile; /*! * This will be used in some of the histogram * based operations. */ ossimRefPtr theAccumulationHistogram; /*! * Indicates if you should equalize or unequalize an input stream. * If the inverse flag is true then it will indicate that we should * assume that the input stream is already equalized and we should * invert based on the current accumulation histogram. * * * This flag is defaulted to false. */ bool theInverseFlag; /*! * We will create a LUT for each band that directly maps * an input value to an equalized output. */ std::vector theForwardLut; /*! * We will create a LUT for each band that directly maps * an input value to an un-equalized output. */ std::vector theInverseLut; std::vector theBandList; virtual void computeAccumulationHistogram(); template ossimRefPtr runEqualizationAlgorithm(T dummyVariable, ossimRefPtr tile); /*! * We will pre-compute the luts for the forward and inverse * equalization. Note: the inverse is a little more tricky * and since we must fill the empty spots missed by the * inverse. We use a linear interpolation between valid * values for this. */ virtual void initializeLuts(); virtual void deleteLuts(); TYPE_DATA }; #endif /* #ifndef ossimHistogramEqualization_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimHistogramMatchFilter.h000066400000000000000000000123511352751253100254110ustar00rootroot00000000000000#ifndef ossimHistogramMatchFilter_HEADER #define ossimHistogramMatchFilter_HEADER #include #include /** * class ossimHistogramMatchFilter * *
 *
 * This class owns two ossimHistogramEqualization filters and will chain them together.  It will
 * make the left most filter the forward transform by transforming the input input to an equalized
 * space defined by the input histogram.  The right filter is the target histogram to match.  It will
 * take the equalized space and invert it to a target histogram.
 *
 * There is an auto load input histogram flag that if set true will always try to search for an input handler
 * and get the input handlers histogram file. and set it.  If this is enabled then the only other field that
 * is required is to specify the target histogram.  If a target histogram is not specified then the output
 *
 * will be an equalized image without the target applied.
 *
 * 
*/ class OSSIM_DLL ossimHistogramMatchFilter : public ossimImageSourceFilter { public: ossimHistogramMatchFilter(); /** * Calls the owned equalizers to create a match composite image. * * @return Histogram matched composite image */ virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); /** * Initializes the input and target equalizer filters. */ virtual void initialize(); /** * @param inputHistogram Input histogram to load */ void setInputHistogram(const ossimFilename& inputHistogram); /** * @param targetHistogram Target histogram to match */ void setTargetHistogram(const ossimFilename& targetHistogram); /** * @param event Connection event */ virtual void connectInputEvent(ossimConnectionEvent& event); /** * @param event Connection event */ virtual void disconnectInputEvent(ossimConnectionEvent& event); /** *
    *
    * Valid properties are:
    *
    * auto_load_input_histogram_flag
    *                   Is a boolean property and specifes whether or not the input histogram will be auto searched from
    *                   the conected input source chain.
    *
    * input_histogram_filename
    *                   Holds the input histogram filename
    *
    * output_histogram_filename
    *                   holds the output histogram filename
    *                   
    * 
* @param property Is the property to set. */ virtual void setProperty(ossimRefPtr property); /** * Returns a property given the name * * Valid names are: * auto_load_input_histogram_flag * input_histogram_filename * output_histogram_filename * * Example: * * ossimRefPtr prop = obj->getProperty("auto_load_input_histogram_flag"); * */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * Returns a list of proeprties. * *
    *
    * Valid properties are:
    *
    * auto_load_input_histogram_flag
    *                   Is a boolean property and specifes whether or not the input histogram will be auto searched from
    *                   the conected input source chain.
    *
    * input_histogram_filename
    *                   Holds the input histogram filename
    *
    * output_histogram_filename
    *                   holds the output histogram filename
    *                  
    * 
*/ virtual void getPropertyNames(std::vector& propertyNames)const; /** * *
    * Keywords to search and load:
    *
    * auto_load_input_histogram_flag
    * input_histogram_filename
    * output_histogram_filename
    *
    * 
* * @param kwl Holds the keywords for this object to load prefixed by the passed in prefix parameter * @param prefix Is the prefix value prepended to all keywords * * @return True if succesful or flase otherwise * */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); /** * *
    * Keywords:
    *
    * auto_load_input_histogram_flag
    * input_histogram_filename
    * output_histogram_filename
    *
    * 
* * @param kwl This object will store the keywords in kwl and prefix by the parameter prefix * @param prefix Is the prefix value prepended to all keywords * @return True if succesful or flase otherwise * */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; protected: /** * Will search the input chain and get the histogram_filename property of the image handler. * Once retrieved it calls the setInputHistogram with the found histogram filename. It does nothing * if the histogram filename does not exist * */ void autoLoadInputHistogram(); ossimRefPtr theInputHistogramEqualizer; ossimRefPtr theTargetHistogramEqualizer; ossimFilename theInputHistogramFilename; ossimFilename theTargetHistogramFilename; bool theAutoLoadInputHistogramFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimHistogramRemapper.h000066400000000000000000000430041352751253100247610ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: // // Histogram remapper class declaration. Derived from ossimTableRemapper. // // Remaps a tile based on mode and histogram clip points. This object uses // a precomputed remap table for speed; hence, derived from the // ossimTableRemapper // // NOTE on bands: // // - All methods take zero based bands. In other words the first // band is band "0". // // - This objects band 0 is the same band 0 as it's input connection. If // the band order was changed by a ossimBandSelector then this band 0 will // not map to the histogram files band 0. To handle this, // the "getOutputBandList()" method is used to get the correct histogram for // the input band. // // - The "get" methods that do not take a band, simply return the average of // all bands. This really only makes sense if all bands are the same // but is provided for convenience. // //--- // $Id$ #ifndef ossimHistogramRemapper_HEADER #define ossimHistogramRemapper_HEADER 1 #include #include class OSSIMDLLEXPORT ossimHistogramRemapper : public ossimTableRemapper { public: enum StretchMode { LINEAR_ONE_PIECE = 0, LINEAR_1STD_FROM_MEAN = 1, LINEAR_2STD_FROM_MEAN = 2, LINEAR_3STD_FROM_MEAN = 3, LINEAR_AUTO_MIN_MAX = 4, LINEAR_AUTO_PERCENTILE = 5, STRETCH_UNKNOWN = 6 // Alway last as used for number of modes method. }; /** default constructor */ ossimHistogramRemapper(); virtual ossimString getLongName() const; virtual ossimString getShortName() const; virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); /** * - Disables this source. * - Sets all clip points to default. * - Removes current table. */ void reset(); /** * @brief Sets remap mode to mode. * @param mode The stretch mode. */ void setStretchMode(StretchMode mode); // For backwards compatibility only... void setStretchMode(StretchMode mode, bool rebuildTableFlag); void setStretchModeAsString(const ossimString& mode, bool rebuildTableFlag); /** * @brief Stretch mode values can be linear_one_piece, linear_1std_from_mean, * linear_2std_from_mean, linear_3std_from_mean, linear_auto_min_max, * @param mode The stretch mode. */ void setStretchModeAsString(const ossimString& mode); /** * Returns the current enumerated node. */ StretchMode getStretchMode() const; /** * Returns the string for current remap mode. */ ossimString getStretchModeString() const; /** * Returns the number of stretch modes. */ ossim_uint32 getNumberOfStretchModes() const; /** * Returns the mode string for a given index. * Returns "stretch_unknown" if index is out of range. * * NOTE: * - If you're building gui buttons you can: * // pseudo code... * ossim_uint32 number_of_modes = remapper->getNumberOfModes() * for (ossim_uint32 i = 0; i < number_of_modes; ++i) * { * addButton(getModeString(i).c_str()); * } */ ossimString getStretchModeString(ossim_uint32 index) const; /** * Sets the low clip point. * * Note on null bin: * - The null bin is ignored when considering a percent of penetration from * the low end. * * Notes on clip point: * - If input chip source is mutiband this will set all band to same * percentage of clip. * - Clip points should be normalized between zero and one. * - A low clip point of 0.0 means no penetration. * - A low clip point of 0.02 means penetrate in two percent. */ void setLowNormalizedClipPoint(const ossim_float64& clip); /** * Sets the low clip point for band. * * Note on null bin: * - The null bin is ignored when considering a percent of penetration from * the low end. * * Notes on clip points: * - Clip point should be normalized between zero and one. * - A low clip point of 0.0 means no penetration. * - A low clip point of 0.02 means penetrate in two percent. */ void setLowNormalizedClipPoint(const ossim_float64& clip, ossim_uint32 zero_based_band); /** * Sets the high clip point. * * Notes on clip points: * - If input chip source is mutiband this will set all band to same * percentage of clip. * - Clip point should be normalized between zero and one. * - A high clip point of 1.0 means no penetration. * - A high clip point of .98 mean a 2 % penetration from the high end. */ void setHighNormalizedClipPoint(const ossim_float64& clip); /** * Sets the high clip point. * * Notes on clip points: * - Clip point should be normalized between zero and one. * - A high clip point of 1.0 means no penetration. * - A high clip point of .98 mean a 2 % penetration from the high end. */ void setHighNormalizedClipPoint(const ossim_float64& clip, ossim_uint32 zero_based_band); /** * Sets the low clip point. * * Notes on clip point: * - If input chip source is mutiband this will set all band to same * percentage of clip. * - Clip points are in DN values. * - If histogram is not set no action is taken. */ void setLowClipPoint(const ossim_float64& clip); /** * Sets the low clip point for band. * * Notes on clip points: * - Clip points are DN values. * - If histogram is not set no action is taken. */ void setLowClipPoint(const ossim_float64& clip, ossim_uint32 zero_based_band); /** * Sets the high clip point. * * Notes on clip points: * - If input chip source is mutiband this will set all band to same * percentage of clip. * - Clip points are DN values. * - If histogram is not set no action is taken. */ void setHighClipPoint(const ossim_float64& clip); /** * Sets the high clip point. * * Notes on clip points: * - Clip points are DN values. * - If histogram is not set no action is taken. */ void setHighClipPoint(const ossim_float64& clip, ossim_uint32 zero_based_band); /** * Sets the mid clip point. * * Notes on clip points: * - If input chip source is mutiband this will set all band to same * percentage of clip. * * Note: The midpoint is normalized between 0 to 1 where the default is 0.5 or the * average of the high low values when used. */ void setMidPoint(const ossim_float64& value); /** * Sets the mid clip point for band. * * Note: The midpoint is normalized between 0 to 1 where the default is 0.5 or the * average of the high low values when used. */ void setMidPoint(const ossim_float64& value, ossim_uint32 zero_based_band); /** * Sets the min output value. * * Notes on clip points: * - If input chip source is mutiband this will set all band to same * percentage of clip. */ void setMinOutputValue(const ossim_float64& value); /** * Sets the min output value for band. */ void setMinOutputValue(const ossim_float64& value, ossim_uint32 zero_based_band); /** * Sets the max output value. * * Notes on clip points: * - If input chip source is mutiband this will set all band to same * percentage of clip. */ void setMaxOutputValue(const ossim_float64& value); /** * Sets the min output value for band. */ void setMaxOutputValue(const ossim_float64& value, ossim_uint32 zero_based_band); /** * Returns the normalized low clip point for band. * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getLowNormalizedClipPoint(ossim_uint32 zero_based_band) const; /** * Returns the normalized low clip point which is the average of all bands. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getLowNormalizedClipPoint() const; /** * Returns the normalized high clip point for band. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getHighNormalizedClipPoint(ossim_uint32 zero_based_band) const; /** * Returns the normalized High clip point which is the average of all bands. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getHighNormalizedClipPoint() const; /** * Returns the low clip point for band. * Clip points are DN values relative to the scalar type. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getLowClipPoint(ossim_uint32 zero_based_band) const; /** * Returns the low clip point which is the average of all bands. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getLowClipPoint() const; /** * Returns the high clip point for band. * Clip points are DN values relative to the scalar type. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getHighClipPoint(ossim_uint32 zero_based_band) const; /** * Returns the high clip point which is the average of all bands. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getHighClipPoint() const; /** * Returns the mid point for band * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getMidPoint(ossim_uint32 zero_based_band) const; /** * Returns the mid clip point which is the average of all bands. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. * - Histogram has not been set. */ ossim_float64 getMidPoint() const; /** * Returns the minimum output value for band. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. */ ossim_float64 getMinOutputValue(ossim_uint32 zero_based_band) const; /** * Returns the minimum output value which is the average of all bands. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. */ ossim_float64 getMinOutputValue() const; /** * Returns the maximum output value for band. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. */ ossim_float64 getMaxOutputValue(ossim_uint32 zero_based_band) const; /** * Returns the maximum output value which is the average of all bands. * * Will return OSSIM_DBL_NAN if: * - Band is out of range. * - Connection is not complete. */ ossim_float64 getMaxOutputValue() const; /** * Sets the histogram. * If (own_histogram == true) this object will delete theHistogram * on destruction. */ void setHistogram(ossimRefPtr histogram); ossimRefPtr getHistogram(); ossimRefPtr getHistogram()const; /** * Returns pointer to histogram for band and reduced res level. * - Band is zero based relative to the input connection. This will be * remapped to the histogram band using the "getOutputBandList()" to * get the correct histogram band. * * Will return NULL if: * - band is out range * - res_level is out of range * - theHistogram has not been initialized yet. */ ossimRefPtr getHistogram(ossim_uint32 zero_based_band, ossim_uint32 res_level=0) const; /** * Open the histogram file. * With this method the histogram is owned by this object. * Returns true on success, false on error. */ bool openHistogram(const ossimFilename& histogram_file); /** * Compute the histogram from input connection and region of interest. * With this method the histogram is owned by this object. * * @param roi Region of inte * Returns true on success, false on error. */ bool computeHistogram(const ossimIrect& roi); /** * Returns the currently opened histogram. * Returns ossimFilename::NIL if no histogram is loaded. */ ossimFilename getHistogramFile() const; void setBiasFactor(ossim_float64 factor); ossim_float64 getBiasFactor()const; void setAutoMinMaxBias(ossim_float64 bias); ossim_float64 getAutoMinMaxBias()const; void setPercentPenetration(ossim_float64 percent); ossim_float64 getPercentPenetration()const; /** * Method to the save the state to a keyword list. * Returns true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. * Returns true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual std::ostream& print(std::ostream& os) const; /** * Returns the min pixel of the band. */ virtual double getMinPixelValue(ossim_uint32 band=0)const; /** * Returns the max pixel of the band. */ virtual double getMaxPixelValue(ossim_uint32 band=0)const; /** * Will test for the input being a ossimHistogramSource and allow pulling the histogram * from a histogram source. */ bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; protected: /** virtual destructor */ virtual ~ossimHistogramRemapper(); private: // Do not allow copy constructor, operator=. ossimHistogramRemapper(const ossimHistogramRemapper& hr); ossimHistogramRemapper& operator=(const ossimHistogramRemapper& hr); void buildTable(); void buildLinearTable(); /** * @brief All of these build methods, set the clip points, then call * the buildLinearTable method. */ void buildLinearTableStdFromMean(); void buildAutoLinearMinMaxTable(); void buildAutoLinearPercentileTable(); template void buildLinearTable(T dummy); template void buildAutoLinearMinMaxTableTemplate(T dummy); template void buildAutoLinearPercentileTableTemplate(T dummy); /** * Uses getNumberOfInputBands() to determine BANDS then calls * initializeClips(BANDS) */ void initializeClips(); /** * Initializes data members to some default state and size. */ void initializeClips(ossim_uint32 bands); /* * Sets the count of the null bin to 0 so that clips from the low end * ignore the null bin. */ void setNullCount(); void initializeMinMaxOutput(); /** * Initialized base class (ossimTableRemapper) values: * - theTableBinCount * - theTableBandCount * - theTableType * - theTable (resizes if not correct size. */ void setupTable(); /** * This set theBypassFlag. This is an internally used flag to signal that * there is nothing to do in this filter; hence, bypass. */ void verifyEnabled(); /** * Returns the histogram band that maps to the input band. * Note: * - This uses the current band list from "getOutputBandList()". */ ossim_uint32 getHistogramBand(ossim_uint32 input_band) const; /** * Sets theBypassFlag. If the start changes from bypassed to not bypassed * this will set theDirtyFlag to true. */ void setBypassFlag(bool flag); /** * If we are dirty then it will init what it needs and then set * the dirty back to false; */ void makeClean(); StretchMode theStretchMode; bool theDirtyFlag; mutable ossimRefPtr theHistogram; std::vector theNormalizedLowClipPoint; std::vector theNormalizedHighClipPoint; std::vector theMidPoint; std::vector theMinOutputValue; std::vector theMaxOutputValue; // Maps zero based band to histogram band. std::vector theBandList; // Internally bypassed flag. bool theBypassFlag; bool theResetBandIndicesFlag; ossim_float64 m_percentPenetration; // Internal bias used to find the clip points ossim_float64 m_autoMinMaxBias; // this is a multiplier for any of the current bias factors // This will serve as a fudge factor for the Internal bias values. // // Will vary between 0 and 1 // ossim_float64 m_biasFactor; TYPE_DATA }; #endif /* #ifndef ossimHistogramRemapper_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimHistogramThreshholdFilter.h000066400000000000000000000034171352751253100264640ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHistogramThreshholdFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimHistogramThreshholdFilter_HEADER #define ossimHistogramThreshholdFilter_HEADER #include class ossimHistogramThreshholdFilter : public ossimImageSourceHistogramFilter { public: ossimHistogramThreshholdFilter(); ossimHistogramThreshholdFilter(double minValuePercent, double maxValuePercent, ossimImageSource* inputSource, ossimMultiResLevelHistogram* histogram); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void setMinValuePercent(double minValue); virtual void setMaxValuePercent(double maxValue); virtual double getMinValuePercent()const; virtual double getMaxValuePercent()const; virtual void initialize(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: virtual ~ossimHistogramThreshholdFilter(); double theMinValuePercent; double theMaxValuePercent; template ossimRefPtr runThreshholdStretchAlgorithm( T dummyVariable, ossimRefPtr& tile); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimHistogramWriter.h000066400000000000000000000060641352751253100244670ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHistogramWriter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimHistogramWriter_HEADER #define ossimHistogramWriter_HEADER #include #include #include #include #include #include #include #include #include #include #include #include class ossimImageSource; class ossimHistogramWriterProcessListener; class ossimImageHistogramSource; class OSSIMDLLEXPORT ossimHistogramWriter : public ossimOutputSource, public ossimProcessInterface, public ossimConnectableObjectListener { public: friend class ossimHistogramWriterProcessListener; ossimHistogramWriter(ossimImageSource* inputSource=0, ossimObject* owner=0); void setAreaOfInterest(const ossimIrect& rect); virtual ossimObject* getObject(); virtual const ossimObject* getObject()const; virtual bool execute(); virtual bool isOpen()const; /*! * open the histogram file for output. Note if the file was * previously open then it will close it and re-opens the * file. */ virtual bool open(); virtual bool open(const ossimFilename& filename); virtual void close(); /*! * Overrides the base class and maps the outputName to a filename. */ virtual void setOutputName(const ossimString& outputName); virtual void setFilename(const ossimFilename& filename); bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void processProgressEvent(ossimProcessProgressEvent& event); virtual void connectInputEvent(ossimConnectionEvent& event); virtual void disconnectInputEvent(ossimConnectionEvent& event); /** * Overrides base to pass on abort to theHistogramSource. */ virtual void abort(); protected: virtual ~ossimHistogramWriter(); virtual void writeHistogram(); ossimIrect theAreaOfInterest; ossimFilename theFilename; std::ofstream* theFileStream; ossimHistogramWriterProcessListener* theProcessListener; /** stored for abort call only. */ ossimHistogramSource* theHistogramSource; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimHsiRemapper.h000066400000000000000000000214321352751253100235500ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Remapper to adjust hue, saturation and intensity. // //************************************************************************* // $Id: ossimHsiRemapper.h 19689 2011-05-31 15:55:21Z gpotts $ #ifndef ossimHsiRemapper_HEADER #define ossimHsiRemapper_HEADER #include class OSSIMDLLEXPORT ossimHsiRemapper : public ossimImageSourceFilter { public: enum { RED = 0, YELLOW = 1, GREEN = 2, CYAN = 3, BLUE = 4, MAGENTA = 5, ALL = 6 }; ossimHsiRemapper(); virtual ossimString getLongName() const; virtual ossimString getShortName() const; virtual void initialize(); /*---------------------- PROPERTY INTERFACE ---------------------------*/ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /*---------------------- END PROPERTY INTERFACE ---------------------------*/ virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); ossim_uint32 getNumberOfOutputBands() const; virtual std::ostream& print(std::ostream& os) const; friend std::ostream& operator << (std::ostream& os, const ossimHsiRemapper& hr); void setHueOffset (int color_group, double offset); void setHueLowRange (int color_group, double range); void setHueHighRange (int color_group, double range); void setHueBlendRange (int color_group, double range); void setSaturationOffset (int color_group, double offset); void setIntensityOffset (int color_group, double offset); void setMasterHueOffset (double offset); void setMasterSaturationOffset (double offset); void setMasterIntensityOffset (double offset); void setMasterIntensityLowClip (double clip); void setMasterIntensityHighClip (double clip); void setRedHueOffset (double offset); void setRedHueLowRange (double range); void setRedHueHighRange (double range); void setRedHueBlendRange (double range); void setRedSaturationOffset (double offset); void setRedIntensityOffset (double offset); void setYellowHueOffset (double offset); void setYellowHueLowRange (double range); void setYellowHueHighRange (double range); void setYellowHueBlendRange (double range); void setYellowSaturationOffset (double offset); void setYellowIntensityOffset (double offset); void setGreenHueOffset (double offset); void setGreenHueLowRange (double range); void setGreenHueHighRange (double range); void setGreenHueBlendRange (double range); void setGreenSaturationOffset (double offset); void setGreenIntensityOffset (double offset); void setCyanHueOffset (double offset); void setCyanHueLowRange (double range); void setCyanHueHighRange (double range); void setCyanHueBlendRange (double range); void setCyanSaturationOffset (double offset); void setCyanIntensityOffset (double offset); void setBlueHueOffset (double offset); void setBlueHueLowRange (double range); void setBlueHueHighRange (double range); void setBlueHueBlendRange (double range); void setBlueSaturationOffset (double offset); void setBlueIntensityOffset (double offset); void setMagentaHueOffset (double offset); void setMagentaHueLowRange (double range); void setMagentaHueHighRange (double range); void setMagentaHueBlendRange (double range); void setMagentaSaturationOffset (double offset); void setMagentaIntensityOffset (double offset); double getHueOffset (int color_group) const; double getHueLowRange (int color_group) const; double getHueHighRange (int color_group) const; double getHueBlendRange (int color_group) const; double getSaturationOffset (int color_group) const; double getIntensityOffset (int color_group) const; double getMasterHueOffset () const; double getMasterSaturationOffset () const; double getMasterIntensityOffset () const; double getMasterIntensityLowClip () const; double getMasterIntensityHighClip () const; double getRedHueOffset () const; double getRedHueLowRange () const; double getRedHueHighRange () const; double getRedHueBlendRange () const; double getRedSaturationOffset () const; double getRedIntensityOffset () const; double getYellowHueOffset () const; double getYellowHueLowRange () const; double getYellowHueHighRange () const; double getYellowHueBlendRange () const; double getYellowSaturationOffset () const; double getYellowIntensityOffset () const; double getGreenHueOffset () const; double getGreenHueLowRange () const; double getGreenHueHighRange () const; double getGreenHueBlendRange () const; double getGreenSaturationOffset () const; double getGreenIntensityOffset () const; double getCyanHueOffset () const; double getCyanHueLowRange () const; double getCyanHueHighRange () const; double getCyanHueBlendRange () const; double getCyanSaturationOffset () const; double getCyanIntensityOffset () const; double getBlueHueOffset () const; double getBlueHueLowRange () const; double getBlueHueHighRange () const; double getBlueHueBlendRange () const; double getBlueSaturationOffset () const; double getBlueIntensityOffset () const; double getMagentaHueOffset () const; double getMagentaHueLowRange () const; double getMagentaHueHighRange () const; double getMagentaHueBlendRange () const; double getMagentaSaturationOffset () const; double getMagentaIntensityOffset () const; void setWhiteObjectClip (double clip); double getWhiteObjectClip () const; void resetWhiteObjectClip (); void resetGroup(int color_group); void resetAll(); void resetMaster(); void resetRed(); void resetYellow(); void resetGreen(); void resetCyan(); void resetBlue(); void resetMagenta(); protected: virtual ~ossimHsiRemapper(); void allocate(const ossimIrect& rect); void verifyEnabled(); double calculateMinNormValue(); bool theValidFlag; ossimRefPtr theTile; double* theBuffer; double theNormalizedMinPix; double theMasterHueOffset; double theMasterSaturationOffset; double theMasterIntensityOffset; double theMasterIntensityLowClip; double theMasterIntensityHighClip; double theRedHueOffset; double theRedHueLowRange; double theRedHueHighRange; double theRedHueBlendRange; double theRedSaturationOffset; double theRedIntensityOffset; double theYellowHueOffset; double theYellowHueLowRange; double theYellowHueHighRange; double theYellowHueBlendRange; double theYellowSaturationOffset; double theYellowIntensityOffset; double theGreenHueOffset; double theGreenHueLowRange; double theGreenHueHighRange; double theGreenHueBlendRange; double theGreenSaturationOffset; double theGreenIntensityOffset; double theCyanHueOffset; double theCyanHueLowRange; double theCyanHueHighRange; double theCyanHueBlendRange; double theCyanSaturationOffset; double theCyanIntensityOffset; double theBlueHueOffset; double theBlueHueLowRange; double theBlueHueHighRange; double theBlueHueBlendRange; double theBlueSaturationOffset; double theBlueIntensityOffset; double theMagentaHueOffset; double theMagentaHueLowRange; double theMagentaHueHighRange; double theMagentaHueBlendRange; double theMagentaSaturationOffset; double theMagentaIntensityOffset; double theWhiteObjectClip; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimHsiToRgbSource.h000066400000000000000000000026101352751253100241700ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHsiToRgbSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimHsiToRgbSource_HEADER #define ossimHsiToRgbSource_HEADER #include class ossimHsiToRgbSource : public ossimImageSourceFilter { public: ossimHsiToRgbSource(); ossimHsiToRgbSource(ossimImageSource* inputSource); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual ossimScalarType getOutputScalarType() const; virtual double getNullPixelValue()const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void initialize(); protected: virtual ~ossimHsiToRgbSource(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); ossimRefPtr theBlankTile; ossimRefPtr theTile; void initializeBuffers(ossimRefPtr& data); TYPE_DATA }; #endif /* #ifndef ossimHsiToRgbSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimHsvGridRemapEngine.h000066400000000000000000000032021352751253100250050ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimHsvGridRemapEngine.h // // Copyright (C) 2001 ImageLinks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains declaration of class ossimHsvGridRemapEngine // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimHsvGridRemapEngine.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimHsvGridRemapEngine_HEADER #define ossimHsvGridRemapEngine_HEADER #include /*!**************************************************************************** * * CLASS: ossimHsvGridRemapEngine * *****************************************************************************/ class ossimHsvGridRemapEngine : public ossimGridRemapEngine { public: ossimHsvGridRemapEngine() : ossimGridRemapEngine(3, 3) {} virtual ossimObject* dup() const; virtual void remapTile(const ossimDpt& origin_point, ossimGridRemapSource* remapper, ossimRefPtr& tile); virtual void assignRemapValues(std::vector& sources); virtual void computeSourceValue(ossimRefPtr& source, void* result); protected: virtual void computeRemapNode(ossimAtbPointSource* point_source, void* source_value, void* target_value); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimHsvToRgbSource.h000066400000000000000000000023671352751253100242160ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHsvToRgbSource.h 22874 2014-08-26 10:21:34Z dburken $ #ifndef ossimHsvToRgbSource_HEADER #define ossimHsvToRgbSource_HEADER #include class OSSIM_DLL ossimHsvToRgbSource : public ossimImageSourceFilter { public: ossimHsvToRgbSource(); ossimHsvToRgbSource(ossimImageSource* inputSource); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual ossimScalarType getOutputScalarType() const; virtual double getNullPixelValue()const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void initialize(); protected: virtual ~ossimHsvToRgbSource(); virtual void allocate(); ossimRefPtr theBlankTile; ossimRefPtr theTile; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimIgenGenerator.h000066400000000000000000000213361352751253100240650ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimIgenGenerator.h 15833 2009-10-29 01:41:53Z eshirschorn $ #ifndef ossimIgenGenerator_HEADER #define ossimIgenGenerator_HEADER #include #include #include #include #include #include #include #include #include class OSSIMDLLEXPORT ossimIgenGenerator { public: ossimIgenGenerator(ossimConnectableObject* input=NULL, ossimConnectableObject* output=NULL, ossimObject* view=NULL) :thePixelType(OSSIM_PIXEL_IS_POINT), theTilingFlag(false), theTileSpacing(7.5, 7.5), theTileSpacingUnits(OSSIM_MINUTES), theTilePadding(0,0), theTilePaddingUnits(OSSIM_PIXEL), theNamingConvention("DEFAULT"), theSpecFileLocation(""), theIgenExecutable("igen"), theSpecFileIndex(0), theSpecListIndex(0), theTileNamingConvention("id") { theUpperLeftTileStart.makeNan(); setInput(input); setOutput(output); setView(view); theInputBoundingRect.makeNan(); } ~ossimIgenGenerator() { } void setOutput(ossimConnectableObject* output) { theSpecList.clear(); generateOutputKwl(output); } void setOutput(const ossimKeywordlist& kwl); void setInput(ossimConnectableObject* input); void setView(ossimObject* view) { generateViewKwl(view); } void generateSpecList(bool outputToFileFlag = false); void getImageFilenamesFromSpecList(std::vector& filenameList); ossimGrect getBoundingGround()const; void executeSpecList(); void setIteratorsToStart() { theSpecFileIndex = 0; theSpecListIndex = 0; } bool nextSpecFile(ossimFilename& specFile) { if(theSpecFileIndex >= theSpecFileList.size()) { return false; } specFile = theSpecFileList[theSpecFileIndex]; ++theSpecFileIndex; return true; } void getSpecs(std::vector& specList)const { specList = theSpecList; } ossim_uint32 getNumberOfSpecFiles()const { return (ossim_uint32)theSpecFileList.size(); } ossimFilename getSpecFilename(ossim_uint32 specFileIndex = 0)const { if(specFileIndex < theSpecFileList.size()) { return theSpecFileList[specFileIndex]; } return ossimFilename(""); } ossimFilename buildExe(ossim_uint32 i = 0)const { ossimFilename igenExe = getIgenExecutable(); ossimFilename specFile = getSpecFilename(i); return ossimFilename( igenExe + " " + specFile); } void getSpec(ossimKeywordlist& kwl, ossim_uint32 specIndex=0) { kwl.clear(); if(specIndex < theSpecList.size()) { kwl = theSpecList[specIndex]; } } void getInput(ossimKeywordlist& kwl, const char* prefix=NULL)const { kwl.add(prefix, theInputKwl, true); } void getOutput(ossimKeywordlist& kwl, const char* prefix=NULL)const { kwl.add(prefix, theOutputKwl, true); } void getView(ossimKeywordlist& kwl, const char* prefix=NULL)const { kwl.add(prefix, theViewKwl, true); } void setView(ossimKeywordlist& kwl, const char* prefix = NULL) { theViewKwl.clear(); theViewKwl.add(prefix, kwl, true); } void setOutput(ossimKeywordlist& kwl, const char* prefix = NULL) { theOutputKwl.clear(); theOutputKwl.add(prefix, kwl, true); } void setSpecFileLocation(const ossimFilename& filename) { theSpecFileLocation = filename; } const ossimFilename& getSpecFileLocation()const { return theSpecFileLocation; } void setIgenExecutable(const ossimFilename& igenExecutable) { theIgenExecutable = igenExecutable; } const ossimFilename& getIgenExecutable()const { return theIgenExecutable; } void setOutputPolygon(const ossimGeoPolygon& poly) { theOutputGeoPolygon = poly; } void setPixelType(ossimPixelType pixelType) { thePixelType = pixelType; } void getOutputGeoPolygon(ossimGeoPolygon& poly)const { poly = theOutputGeoPolygon; } const ossimGeoPolygon& getOutputGeoPolygon()const { return theOutputGeoPolygon; } void setTilingFlag(bool flag) { theTilingFlag = flag; } void setTileSpacing(const ossimDpt& spacing) { theTileSpacing = spacing; } void setTilePadding(const ossimDpt& padding) { theTilePadding = padding; } void setTileSpacingUnits(ossimUnitType unitType) { theTileSpacingUnits = unitType; } void setTilePaddingUnits(ossimUnitType unitType) { theTilePaddingUnits = unitType; } bool getTilingFlag()const { return theTilingFlag; } const ossimDpt& getTileSpacing()const { return theTileSpacing; } const ossimDpt& getTilePadding()const { return theTilePadding; } ossimUnitType getTileSpacingUnits()const { return theTileSpacingUnits; } ossimUnitType getTilePaddingUnits()const { return theTilePaddingUnits; } ossimPixelType getPixelType()const { return thePixelType; } /*! * Tile naming convention is a string that can be "id" or "usgs". * this is used if tiling is enabled. If id is used it will use the filename * as the prefix and then add to it the id's. If usgs is used it will name * it based on the USGS name. */ void setTileNamingConvention(const ossimString& namingConvention) { theTileNamingConvention = namingConvention; theTileNamingConvention = theTileNamingConvention.downcase(); } const ossimString& getTileNamingConvention()const { return theTileNamingConvention; } ossimIrect getInputBoundingRect()const; ossimProjection* createProductProjection()const; ossimObject* createOutput()const; ossimObject* createInput()const; protected: ossimKeywordlist theInputKwl; ossimKeywordlist theOutputKwl; ossimKeywordlist theViewKwl; ossimPixelType thePixelType; bool theTilingFlag; ossimDpt theUpperLeftTileStart; ossimDpt theTileSpacing; ossimUnitType theTileSpacingUnits; ossimDpt theTilePadding; ossimUnitType theTilePaddingUnits; ossimString theNamingConvention; ossimFilename theSpecFileLocation; ossimFilename theIgenExecutable; ossim_uint32 theSpecFileIndex; ossim_uint32 theSpecListIndex; ossimIrect theInputBoundingRect; ossimGeoPolygon theOutputGeoPolygon; ossimString theTileNamingConvention; std::vector theSpecList; std::vector theSpecFileList; void generateInputKwl(ossimConnectableObject* connectable); void generateOutputKwl(ossimConnectableObject* connectable); void generateViewKwl(ossimObject* view); void setDefaultOutput(); void generateTiledSpecList(bool outputToFileFlag); void generateGeoTiledSpecList(const ossimDpt& spacing, bool outputToFileFlag); void generatePixelTiledSpecList(bool outputToFileFlag); void generateNoTiledSpecList(bool outputToFileFlag); void generateChainForMultiInput(ossimConnectableObject* connectable); void generateChainForMultiInputRecurse(std::stack& aStack, ossimConnectableObject* connectable); int getTileId(const ossimDrect& rect, const ossimDpt& currentPt, const ossimDpt& spacing)const; void addPadding(ossimGeoPolygon& output, const ossimGeoPolygon& input)const; void addPixelType(ossimKeywordlist& kwl, const char* prefix="product."); }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageCacheBase.h000066400000000000000000000260201352751253100240700ustar00rootroot00000000000000//----------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Mingjie Su // // Description: This class give the capability to access tiles from the // input frames. // //----------------------------------------------------------------------- //$Id: ossimImageCacheBase.h 2685 2011-06-07 16:24:41Z david.burken $ #ifndef ossimImageCacheBase_HEADER #define ossimImageCacheBase_HEADER 1 #include #include class ossimRpfToc; class ossimRpfTocEntry; class ossimRpfFrame; class OSSIMDLLEXPORT ossimImageCacheBase : public ossimImageHandler { public: /** * Default constructor. * * Initializes all internal attributes to a default state. */ ossimImageCacheBase(); /** * Closes this image handler and deletes any allocated data. */ virtual void close(); /** */ virtual bool open() = 0; /** * Satisfies pure virtual requirement from ImageHandler class. * * @param reduced_res_level The reduced res level to query number of lines from. * @return The number of lines in the image. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; /** * Satisfies pure virtual requirement from ImageHandler class. * * @param reduced_res_level The reduced res level to query number of samples from. * @return The number of samples in the image. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; /** * @param reduced_res_level Which res level to get the bounds for. 0 represents * the default and is the full resolution. * * @return A rectangle representing the bounds for the passed in resolution level. */ virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const ; /** * @param kwl Keywordlist to save the state of the object to. * @param prefix prefix to prepend to the keywords. This will * help uniquely identify each keyword if multiple * objects are saved to the same list. * @return True if successfully saved the state of the object and * false otherwise. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to load the state of an object from a keyword list. * * Loading with a prefix. * @code * cibCadrgHandler->laodState(kwl, "handler1."); * @endcode * * Loading without a prefix. * @code * cibCadrgHandler->laodState(kwl); * @endcode * * Since all objects are factory created you can go through the * registry and pass the keyword list in. * @code * ossimImageHandler* handler = ossimImageHandlerRegistry::instance()->open(kwl, prefix); * @endcode * * @param kwl Keywordlist that holds the state information for this * object. * * * @param prefix prefix value prepended to all keywords to uniquely * locate the state attributes for this object. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * This method allows you to query the number of input bands. If an image * is band selectable this will allow one to select the bands you wish * to read in. This indicates that the number of input bands might not * match the number of output bands. * @return number of input bands. */ virtual ossim_uint32 getNumberOfInputBands()const; /** * This method allows one to query the number of output bands. This might not * be the same as the n umber of input bands. * * @see getNumberOfInputBands(). * @return number of output bands. */ virtual ossim_uint32 getNumberOfOutputBands()const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; virtual void getEntryList(std::vector& entryList)const; /** * @param reduced_res_level passed in resolution level. * @return True if the reduced_res_level is within an acceptable range * and false otherwise. */ bool isValidRLevel(ossim_uint32 reduced_res_level) const; /** * Determines if its open if there eists a table of contents object. * * @return True if the handler is open and flase otherwise. */ bool isOpen()const; /** * Populates the geometry object with image geometry information. This * method is used to relay projection/model information to users. * Returns true if geometry info is present, false if not. * Keywords supported by this class are: * @verbatim * datum: // datum code> // Datum code * ul_lat: // upper left latitude * ul_lon: // upper left longitude * ll_lat: // lower left latitude * ll_lon: // lower left longitude * lr_lat: // lower right latitude * lr_lon: // lower right longitude * ur_lat: // upper right latitude * ur_lon: // upper right longitude * number_input_bands: * number_output_bands: * number_lines: * number_samples: * decimal_degrees_per_pixel_lat: // specifies the spacing per pixel along Y direction * decimal_degrees_per_pixel_lon: // specifies the spacing per pixel along X direction * origin_latitude: // specifies the origin or center of the projector for the latitude * central_meridian: // specifies the origin or center of the projector for the longitude * tie_point_lat: // tie point lat. Represents the latitude of the upper left center of pixel * tie_point_lon: // tie point lon. Represents the longitude of the upper left center of pixel * zone: // zone read from the CIB/CADRG boundary info * type: // class name of the object for factory driven reconstruction * map_scale: // Map scale of the image * @endverbatim * @see ossimImageSource for further code example on using the geometry. */ virtual ossimRefPtr getImageGeometry(); protected: /** * Destructor. * * Will return allocated memory back to the heap. */ virtual ~ossimImageCacheBase(); /** * Will shift the rect and clamp it so not to go outside the -180 to 180 * degree range. */ void setActualImageRect(); /** * @brief Method to test for 180.0 <--> 180.00 and set leftLon to -180 if * both left and right are 180.0 degrees. * * @param leftLon Left hand side longitude of scene. This is the value * that will be flipped to -180 if test is true. * * @param rightLon Right hand side of scene. */ void checkLongitude(ossim_float64& leftLon, const ossim_float64& rightLon) const; /** * Protected structure that is only used internally by this class. * * This is used to establish which entry data is being used. * all we need is the ro, col of the entry. We can compute the * image rect from this since the CibCadrg are 1536x1536 frame. * */ struct ossimFrameEntryData { ossimFrameEntryData() :theRow(-1), theCol(-1), thePixelRow(-1), thePixelCol(-1) {} ossimFrameEntryData(ossim_int32 row, ossim_int32 col, ossim_int32 pixelRow, ossim_int32 pixelCol, const ossimRpfFrameEntry& entry) :theRow(row), theCol(col), thePixelRow(pixelRow), thePixelCol(pixelCol), theFrameEntry(entry) {} ossimFrameEntryData(const ossimFrameEntryData& rhs) :theRow(rhs.theRow), theCol(rhs.theCol), thePixelRow(rhs.thePixelRow), thePixelCol(rhs.thePixelCol), theFrameEntry(rhs.theFrameEntry) {} ossim_int32 theRow; ossim_int32 theCol; ossim_int32 thePixelRow; ossim_int32 thePixelCol; ossimRpfFrameEntry theFrameEntry; }; /** * It is important to note that each frame is organized into an easting northing * type orientation. This means that a frame at 0,0 is at the lower left corner. * Each frame's pixel data is has 0,0 at the upper left. * * It will take the curent region to render and then find all entries that intersect * that region. * * @param rect the current region to render. * @return The list of entry data objects found for this rect. */ std::vector getIntersectingEntries(const ossimIrect& rect); void deleteAll(); bool buildFrameEntryArray(ossimFilename imageFile, ossim_uint32 frameWidth, ossim_uint32 frameHeight); virtual void establishDecimationFactors(); /** * This holds the image bounds for the current entry. */ ossimIrect m_actualImageRect; /** * This will be computed based on the frames organized within * the directory. The CibCadrg have fixed size frames of 1536x1536 * and we must count how many there are. */ ossim_uint32 m_numberOfLines; /** * This will be computed based on the frames organized within * the directory. The CibCadrg have fixed size frames of 1536x1536 * and we must count how many there are. */ ossim_uint32 m_numberOfSamples; /** * This is the actual data returned from a getTile request. */ ossim_uint32 m_numberOfBands; /** * The size of the input frames. */ std::vector m_fileNames; /** * The size of the output tile. */ ossimIpt m_tileSize; mutable ossimRpfFrame* m_workFrame; // data to use in property retrieval ossim_float64 m_bBox_LL_Lon; ossim_float64 m_bBox_LL_Lat; ossim_float64 m_bBox_UR_Lon; ossim_float64 m_bBox_UR_Lat; ossim_uint32 m_numOfFramesVertical; ossim_uint32 m_numOfFramesHorizontal; ossim_uint32 m_frame_width; ossim_uint32 m_frame_height; std::vector< std::vector > m_frameEntryArray; TYPE_DATA }; #endif /* #ifndef ossimImageCacheBase_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageCacheTileSource.h000066400000000000000000000115551352751253100253030ustar00rootroot00000000000000//----------------------------------------------------------------------- // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Mingjie Su // // Description: This class give the capability to access tiles from the // input frames. // //----------------------------------------------------------------------- //$Id: ossimImageCacheTileSource.h 2644 2011-05-26 15:20:11Z oscar.kramer $ #ifndef ossimImageCacheTileSource_HEADER #define ossimImageCacheTileSource_HEADER 1 #include class OSSIMDLLEXPORT ossimImageCacheTileSource : public ossimImageCacheBase { public: /** * Default constructor. * * Initializes all internal attributes to a default state. */ ossimImageCacheTileSource(); /** * This method is defined in the base class ossimObject. * This class overrides the default implementation * to return its own short name. * * @return The short name for this class as an ossimString. */ virtual ossimString getShortName()const; /** * This method is defined in the base class ossimObject. * This class overrides the default implementation * to return its own long name. * * @return The long name for this class as an ossimString. */ virtual ossimString getLongName()const; /** * Closes this image handler and deletes any allocated data. */ virtual void close(); /** */ virtual bool open(); /** * Returns a pointer to an ossimImageDataObject given a rectangluar * region of interest. * * @param rect The region of interest to return. * @param resLevel From which resolution set are we querying * (default is 0 full res). * * @return The ossimImageData object to the caller. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel = 0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * This method allows you to query the scalar type of the output data. * This is simply the data type, i.e. whether its OSSIM_FLOAT, OSSIM_DOUBLE, * OSSIM_UCHAR, ... etc. This means that if there are bands of different * scalar types from a single image then they must be casted to the highest * precision type. @see ossimConstants.h for all ossimScalarType. * * @return The output scalar type. * */ virtual ossimScalarType getOutputScalarType() const; /** * This method allows you to query the number of input bands. If an image * is band selectable this will allow one to select the bands you wish * to read in. This indicates that the number of input bands might not * match the number of output bands. * @return number of input bands. */ virtual ossim_uint32 getNumberOfInputBands()const; /** * This method allows one to query the number of output bands. This might not * be the same as the n umber of input bands. * * @see getNumberOfInputBands(). * @return number of output bands. */ virtual ossim_uint32 getNumberOfOutputBands()const; /** * Retuns the min pixel value. If there was an external eta data file * then use the meta data from that file. If not given then we will * return the default min */ virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual double getNullPixelValue(ossim_uint32 band=0)const; protected: /** * Destructor. * * Will return allocated memory back to the heap. */ virtual ~ossimImageCacheTileSource(); /** * * @param tileRect Region to fill. * @param framesInvolved All intersecting frames used to render the region. */ void fillTile(const ossimIrect& tileRect, const std::vector& framesInvolved, ossimImageData* tile); bool buildFrameEntryArray(ossimFilename imageFile); /** * This is the actual data returned from a getTile request. */ ossimRefPtr m_tile; ossimRefPtr m_imageHandler; double m_minPixelValue; double m_maxPixelValue; double m_nullPixelValue; TYPE_DATA }; #endif /* #ifndef ossimImageCacheTileSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageChain.h000066400000000000000000000366441352751253100233310ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageChain.h 20316 2011-12-02 15:56:38Z oscarkramer $ #ifndef ossimImageChain_HEADER #define ossimImageChain_HEADER #include #include #include #include #include #include class OSSIMDLLEXPORT ossimImageChain : public ossimImageSource, public ossimConnectableObjectListener, public ossimConnectableContainerInterface { public: ossimImageChain(); virtual ~ossimImageChain(); ossimConnectableObject::ConnectableObjectList& getChainList(){return theImageChainList;} const ossimConnectableObject::ConnectableObjectList& getChainList()const{return theImageChainList;} /** * @param index Index of object to get. * * @see getNumberOfObjects(false) to get the number of objects inside * the container. * * @return Container's object at that index or NULL if out of range. */ ossimConnectableObject* operator[](ossim_uint32 index); /** * Same as operator[](ossim_uint32 i) * * @param index Index of object to get. * * @see getNumberOfObjects(false) to get the number of objects inside * the container. * * @return Container's object at that index or NULL if out of range. * * @note This does not recurse into other containers. */ virtual ossimConnectableObject* getConnectableObject(ossim_uint32 index); virtual ossim_int32 indexOf(ossimConnectableObject* obj)const; /** * Return the first source which is the one that first receives the * getTile request */ virtual ossimImageSource* getFirstSource(); virtual const ossimImageSource* getFirstSource() const; virtual ossimObject* getFirstObject(); /** * Return the last source which is the one that last receives the * getTile request. */ virtual ossimImageSource* getLastSource(); virtual const ossimImageSource* getLastSource() const; virtual ossimObject* getLastObject(); /** * Adds it to the start of the chain. This is the first one to receive * the getTile request. This basically inserts it to the right of the * right most filter. * Returns true on success, false on error. */ bool addFirst(ossimConnectableObject* obj); /** * Adds it to the end. this is the last one to receive the getTile * request. This basically inserts it to the left of the left most filter. * Returns true on success, false on error. */ bool addLast(ossimConnectableObject* obj); /** * Deletes the first object. * Note this is really most right of the chain. * Returns true if deletion occurred, false if the chain is empty. */ bool deleteFirst(); /** * Deletes the last object. * Note this is really most left of the chain. * Returns true if deletion occurred, false if the chain is empty. */ bool deleteLast(); /** * */ bool insertRight(ossimConnectableObject* newObj, ossimConnectableObject* rightOfThisObj); /** * */ bool insertRight(ossimConnectableObject* newObj, const ossimId& id); /** * */ bool insertLeft(ossimConnectableObject* newObj, const ossimId& id); /** * */ bool insertLeft(ossimConnectableObject* newObj, ossimConnectableObject* leftOfThisObj); bool replace(ossimConnectableObject* newObj, ossimConnectableObject* oldObj); /** * Will return true or false if an image source was * added to the chain. It will add and do a connection * to the previous source automatically. This is a * chain and the order of insertion matters. It adds it to the beginning * of the list. The last one added is the first one to receive * the getTile. Basically inserts to the right of the rightmost filter * */ virtual bool add(ossimConnectableObject* source); /** * Within the image chain will pass the head of the * list. */ virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); /** * this call is passed to the head of the list. */ virtual ossim_uint32 getNumberOfInputBands() const; /** * This call is passed to the head of the list. */ virtual ossimScalarType getOutputScalarType() const; virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void getOutputBandList(std::vector& bandList) const; /** * This call is passed to the head of the list. */ virtual ossim_uint32 getTileWidth()const; /** * This call is passed to the head of the list. */ virtual ossim_uint32 getTileHeight()const; /** * Will pass this call to the head of the list. */ virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; virtual void getValidImageVertices(std::vector& validVertices, ossimVertexOrdering ordering=OSSIM_CLOCKWISE_ORDER, ossim_uint32 resLevel=0)const; virtual ossimRefPtr getImageGeometry(); virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const; virtual void getDecimationFactors(std::vector& decimations) const; virtual ossim_uint32 getNumberOfDecimationLevels()const; /** * Will save the state of the chain. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; /** * Will load the state. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); virtual void initialize(); virtual void enableSource(); virtual void disableSource(); bool canConnectMyInputTo(ossim_int32 myInputIndex, const ossimConnectableObject* object)const { if(theImageChainList.size()&& theImageChainList[theImageChainList.size()-1].valid()) { ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, theImageChainList[theImageChainList.size()-1].get()); if(obj) { return obj->canConnectMyInputTo(myInputIndex, object); } } else if(!theImageChainList.size()) { return true; } return false; } // bool canConnectMyOutputTo(int32 myOutputIndex, // const ossimConnectableObject* object)const // { // if(theImageChainList.size()&&theImageChainList[0]) // { // ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, theImageChainList[0]); // if(obj) // { // return obj->canConnectMyOutputTo(myOutputIndex, // object); // } // } // return false; // } // ________________________CONNECTABLE CONTAINER DEFINTIONS_________________ // /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimTypeIdVisitor visitor(tyeId, false, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimCollectionVisitor::List& collection = visitor.getObjects();
    * 
*/ OSSIM_DEPRECATE_METHOD( virtual ossimConnectableObject::ConnectableObjectList findAllObjectsOfType(const RTTItypeid& typeInfo, bool recurse=true)); /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimTypeNameVisitor visitor(typeName, false, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimCollectionVisitor::List& collection = visitor.getObjects();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject::ConnectableObjectList findAllObjectsOfType(const ossimString& className, bool recurse=true)); /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimTypeIdVisitor visitor(tyeId, true, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr obj = visitor.getObject();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findFirstObjectOfType(const RTTItypeid& typeInfo, bool recurse=true)); /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimTypeNameVisitor visitor(className, true, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr obj = visitor.getObject();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findFirstObjectOfType(const ossimString& className, bool recurse=true)); /*! * These methods are now deprecated. You can achieve the same thing by using the new visitor design pattern. If this does not * achieve exactly what you want then you can derive new rules by overriding the virtual visit method in ossimVisitor * *
    *    ossimIdVisitor visitor(tyeId, true, ossimVisitor::VISIT_CHILDREN);
    *    connectableObject->accept(visitor);
    *    ossimRefPtr obj = visitor.getObject();
    * 
*/ OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findObject(const ossimId& id, bool recurse=true)); OSSIM_DEPRECATE_METHOD(virtual ossimConnectableObject* findObject(const ossimConnectableObject* obj, bool recurse=true)); /** * Will cycle through all sources setting their ids. the idLast wlil * be updated * so we can recurse into other containers. */ virtual void makeUniqueIds(); /** * Returns the number of objects within this container and all child * containers. * * @param recurse If true and object is a contains containers; all objects * will be conter. If false only the objects of this container will be * counted (theImageChainList.size()). */ virtual ossim_uint32 getNumberOfObjects(bool recurse=true)const; /** * Deprecated! Please use getNumberOfObjects(false). * * @return The number of objects in this container or * (theImageChainList.size()). */ virtual ossim_uint32 getNumberOfSources() const; /** * Will add an object to the container and then set the added objects owner * to this. */ virtual bool addChild(ossimConnectableObject* attachableObject); /** * Will remove the child from the container. Changes the owner of the * child to be NULL; */ virtual bool removeChild(ossimConnectableObject* object); virtual ossimConnectableObject* removeChild(const ossimId& id); virtual void getChildren(std::vector& children, bool immediateChildrenOnlyFlag); //______________END CONNECTABLE CONTAINER INTERFACE____________ virtual void disconnectInputEvent(ossimConnectionEvent& event); virtual void disconnectOutputEvent(ossimConnectionEvent& event); virtual void connectInputEvent(ossimConnectionEvent& event); virtual void connectOutputEvent(ossimConnectionEvent& event); virtual void objectDestructingEvent(ossimObjectDestructingEvent& event); virtual void propagateEventToOutputs(ossimEvent& event); virtual void propagateEventToInputs(ossimEvent& event); virtual void processEvent(ossimEvent& event); virtual void accept(ossimVisitor& visitor); void deleteList(); /** * These access methods greatly facilitate the implementation of an image chain adaptor class. * They shouldn't be accessed directly by any other classes. These methods really should be * "protected" but the compiler complains if this base class' declarations are "protected". */ virtual ossimConnectableObject::ConnectableObjectList& imageChainList() { return theImageChainList; } virtual const ossimConnectableObject::ConnectableObjectList& imageChainList() const { return theImageChainList; } /** * Inserts all of this object's children and inputs into the container provided. Since this is * itself a form of container, this method will consolidate this chain with the argument * container. Consequently, this chain object will not be represented in the container, but its * children will be, with correct input and output connections to external objects. Ownership * of children will pass to the argument container. * @return Returns TRUE if successful. */ //virtual bool fillContainer(ossimConnectableContainer& container); protected: void prepareForRemoval(ossimConnectableObject* connectableObject); /** * This will hold a sequence of image sources. * theFirst one in the list will be the head of the * list and the last one is the tail. */ ossimConnectableObject::ConnectableObjectList theImageChainList; ossimRefPtr theBlankTile; // mutable bool thePropagateEventFlag; mutable bool theLoadStateFlag; /** * For dynamic loading to take place we must allocate all objects first and * then assign id's later. We must remember the id's so we can do this. * we will create a map that takes the id of the source as a key and a * vector of input id's to connect it's inputs to. */ bool addAllSources(std::map >& idMapping, const ossimKeywordlist& kwl, const char* prefix = NULL); void findInputConnectionIds(std::vector& result, const ossimKeywordlist& kwl, const char* prefix=NULL); bool connectAllSources(const std::map >& idMapping); TYPE_DATA }; #endif /* #ifndef ossimImageChain_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageCombiner.h000066400000000000000000000136621352751253100240400ustar00rootroot00000000000000//******************************************************************* // // License: See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageCombiner.h 23108 2015-01-27 17:00:20Z okramer $ #ifndef ossimImageCombiner_HEADER #define ossimImageCombiner_HEADER #include #include #include #include /** * This will be a base for all combiners. Combiners take N inputs and * will produce a single output. */ class OSSIMDLLEXPORT ossimImageCombiner : public ossimImageSource, public ossimConnectableObjectListener { public: ossimImageCombiner(); ossimImageCombiner(ossimObject* owner, int numberOfInputs, int numberOfOutputs, bool inputListIsFixedFlag, bool outputListIsFixedFlag); ossimImageCombiner(ossimConnectableObject::ConnectableObjectList& inputSources); virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0) const; virtual void initialize(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; /** * This will go through and precompute the * bounding rects of each input image. */ virtual void updateRects(); /** * Returns the number of bands available from the input. */ virtual ossim_uint32 getNumberOfInputBands()const; virtual ossimScalarType getOutputScalarType() const; virtual ossim_uint32 getTileWidth()const; virtual ossim_uint32 getTileHeight()const; virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; /** * Used to retrieve the number of overlapping images withint the given * rect. */ virtual ossim_uint32 getNumberOfOverlappingImages(const ossimIrect& rect, ossim_uint32 resLevel=0)const; /** * Used to populate the result with the index of the overlapping images. */ virtual void getOverlappingImages(std::vector& result, const ossimIrect& rect, ossim_uint32 resLevel=0)const; /* virtual ossimRefPtr getNextTile(ossim_uint32& returnedIdx, */ /* ossim_uint32 startIdx, */ /* const ossimIpt& origin, */ /* ossim_uint32 resLevel=0); */ /* virtual ossimRefPtr getNextTile(ossim_uint32& returnedIdx, */ /* const ossimIpt& origin, */ /* ossim_uint32 resLevel=0); */ virtual ossimRefPtr getNextTile(ossim_uint32& returnedIdx, const ossim_uint32 startIdx, const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual ossimRefPtr getNextTile(ossim_uint32& returnedIdx, const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual bool getNextTile(ossim_uint32& returnedIdx, const ossim_uint32 startIdx, ossimImageData* tile, ossim_uint32 resLevel=0); virtual ossimRefPtr getNextNormTile(ossim_uint32& returnedIdx, const ossim_uint32 index, const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual ossimRefPtr getNextNormTile(ossim_uint32& returnedIdx, const ossimIrect& tileRect, ossim_uint32 resLevel=0); /* virtual ossimRefPtr getNextNormTile(ossim_uint32& returnedIdx, */ /* ossim_uint32 index, */ /* const ossimIpt& origin, */ /* ossim_uint32 resLevel=0); */ /* virtual ossimRefPtr getNextNormTile(ossim_uint32& returnedIdx, */ /* const ossimIpt& origin, */ /* ossim_uint32 resLevel=0); */ virtual bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; virtual void connectInputEvent(ossimConnectionEvent& event); virtual void disconnectInputEvent(ossimConnectionEvent& event); virtual void propertyEvent(ossimPropertyEvent& event); virtual void refreshEvent(ossimRefreshEvent& event); virtual bool hasDifferentInputs()const; protected: virtual ~ossimImageCombiner(); void precomputeBounds()const; ossim_uint32 theLargestNumberOfInputBands; ossim_uint32 theInputToPassThrough; bool theHasDifferentInputs; ossimRefPtr theNormTile; mutable std::vector theFullResBounds; mutable bool theComputeFullResBoundsFlag; ossim_uint32 theCurrentIndex; TYPE_DATA }; #endif /* #ifndef ossimImageCombiner_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageData.h000066400000000000000000001440351352751253100231520ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Container class for a tile of image data. // //******************************************************************* // $Id$ #ifndef ossimImageData_HEADER #define ossimImageData_HEADER 1 #include #include #include #include #include #include #include #include /* for std::ostream */ class ossimMultiBandHistogram; class OSSIMDLLEXPORT ossimImageData : public ossimRectilinearDataObject { public: /** Definitions for the unloadBand routines. */ enum OverwriteBandRule { /* * The COLOR_DISCREPANCY rule directs that the selected band of a pixel * of the destination buffer is to be overwritten if *any* one of the * other bands of the same destination pixel have color values that * deviate from its color. * Deprecated in favor of COLOR_DISCREPANCY_OF_ANY_FROM_DEST. */ COLOR_DISCREPANCY = 0, /* * The COLOR_DISCREPANCY_OF_ANY_FROM_DEST rule directs that the selected * band of a pixel of the destination buffer is to be overwritten if * *any* one of the other bands of the same destination pixel have color * values that deviate from its color. * Same as the deprecated COLOR_DISCREPANCY. */ COLOR_DISCREPANCY_OF_ANY_FROM_DEST = 1, /* * The COLOR_DISCREPANCY_OF_ALL_FROM_DEST rule directs that the selected * band of a pixel of the destination buffer is to be overwritten only if * *all* of the other bands of the same destination pixel have color * values that deviate from its color. */ COLOR_DISCREPANCY_OF_ALL_FROM_DEST = 2, /* * The COLOR_EQUALITY_OF_ANY_TO_SRC rule directs that the selected * band of a pixel of the destination buffer is to be overwritten if * *any* one of the other bands of the same destination pixel have color * values that are equal to the color of the selected band of the source * pixel. */ COLOR_EQUALITY_OF_ANY_TO_SRC = 3, /* * The COLOR_EQUALITY_OF_ALL_TO_SRC rule directs that the selected * band of a pixel of the destination buffer is to be overwritten only if * *all* of the other bands of the same destination pixel have color * values that are equal to the color of the selected band of the source * pixel. */ COLOR_EQUALITY_OF_ALL_TO_SRC = 4, /* * The selected band of the destination buffer is to be overwritten * by the selected band of the source image data (no questions asked). */ NULL_RULE = 5 }; /** @brief copy constructor */ ossimImageData(const ossimImageData &rhs); ossimImageData(); /** * @brief Constructor * @param source The owner. This can be null. * @param scalar The Scalar type like OSSIM_UINT8, OSSIM_UINT16... * @param bands The number of bands. * * @note This does not initialize the undelying data buffer. * Call the initialize method to allocate storage. */ ossimImageData(ossimSource* source, ossimScalarType scalar, ossim_uint32 bands = 1); /** * @brief Constructor * @param source The owner. This can be null. * @param scalar The Scalar type like OSSIM_UINT8, OSSIM_UINT16... * @param bands The number of bands. * @param width The width or number of samples in the buffer. * @param height The height or numer of lines in the buffer. * * @note This does not initialize the undelying data buffer. * Call the initialize method to allocate storage. */ ossimImageData(ossimSource* source, ossimScalarType scalar, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height); /** @brief virtual destructor */ virtual ~ossimImageData(); /** * @brief assignment operator= * @param rhs The data to assign from. * @param A reference to this object. */ virtual const ossimImageData& operator=(const ossimImageData &rhs); /** * @return The width of the data object. */ virtual ossim_uint64 getWidth() const; /** * @return The height of the data object. */ virtual ossim_uint64 getHeight() const; /** * @return The image rectangle relative to origin, height and width. */ virtual ossimIrect getImageRectangle() const; virtual void getWidthHeight(ossim_uint32& w, ossim_uint32& h); virtual void setWidth(ossim_uint32 width); virtual void setHeight(ossim_uint32 height); virtual void setWidthHeight(ossim_uint32 w, ossim_uint32 h); virtual void setImageRectangleAndBands(const ossimIrect& rect, ossim_uint32 numberOfBands); virtual void setImageRectangle(const ossimIrect& rect); virtual void setOrigin(const ossimIpt& origin); virtual void assign(const ossimDataObject* data); virtual void assign(const ossimImageData* data); virtual void assignBand(const ossimImageData* data, ossim_uint32 source_band, ossim_uint32 output_band); virtual ossimObject* dup() const; /** * Uses prime numbers as coefficients for this summation. * Take the the fours bytes of each origin and multiply * by the prime numbers and sum together. This has * been proven by others to give nicely distributed * id number. */ virtual ossim_uint32 getHashId()const; virtual void setNullPix(ossim_float64 null_pix); virtual void setNullPix(ossim_float64 null_pix, ossim_uint32 band); virtual void setNullPix(const ossim_float64* nullPixArray, ossim_uint32 numberOfValues); virtual void setMinPix(ossim_float64 min_pix); virtual void setMinPix(ossim_float64 min_pix, ossim_uint32 band); virtual void setMinPix(const ossim_float64* minPixArray, ossim_uint32 numberOfValues); virtual void setMaxPix(ossim_float64 max_pix); virtual void setMaxPix(ossim_float64 max_pix, ossim_uint32 band); virtual void setMaxPix(const ossim_float64* maxPixArray, ossim_uint32 numberOfValues); virtual const ossimIpt& getOrigin()const{return m_origin;} /** * If the minBands and maxBands are empty or not equal to the imageData's * current number of bands it will erase the contents, resize, and then * replace the values in the passed in array with this objects min max * values. If the arrays are the same size as this objects number of * bands it will just update the values and use the current values in the * arrays as initial min max values. * * If the status of this object(getDataObjectStatus()) is OSSIM_NULL or * OSSIM_EMPTY no action is performed. */ virtual void computeMinMaxPix(std::vector& minBands, std::vector& maxBands) const; /** * @brief Scans tile for min, max, nulls. * * If the nullBands, minBands and maxBands are empty or not equal to the * imageData's current number of bands it will erase the contents, resize, * and then replace the values in the passed in array with this objects * min max values. If the arrays are the same size as this objects number * of bands it will just update the values and use the current values in the * arrays as initial min max values. * * If the status of this object(getDataObjectStatus()) is OSSIM_NULL no * action is performed. */ virtual void computeMinMaxNulPix( std::vector& minBands, std::vector& maxBands, std::vector& nulBands) const; virtual const ossim_float64* getNullPix()const; virtual const ossim_float64* getMinPix()const; virtual const ossim_float64* getMaxPix()const; virtual ossim_float64 getNullPix(ossim_uint32 band) const; virtual ossim_float64 getMinPix(ossim_uint32 band) const; virtual ossim_float64 getMaxPix(ossim_uint32 band) const; /** * returns normalized minimum pixel value of band zero. */ virtual ossim_float64 getMinNormalizedPix() const; virtual ossimString getScalarTypeAsString()const; virtual ossim_uint32 getNumberOfBands() const; virtual void setNumberOfBands(ossim_uint32 bands, bool reallocate=false); /** * Will return the pixel at location position. Note it will first get * the passed in position relative to the origin or upper left * corner of this tile and then return the result. */ virtual ossim_float64 getPix(const ossimIpt& position, ossim_uint32 band=0) const; /** * Will return the pixel at offset and band number. */ virtual ossim_float64 getPix(ossim_uint32 offset, ossim_uint32 band = 0) const; /** * will fill the entire band with * the value. */ void fill(ossim_uint32 band, ossim_float64 value); /** * will fill all bands with the passed in * value. */ void fill(ossim_float64 value); /** * @brief Creates a step wedge for testing only. * * Writes line at a time of a single value, starting at scalar null, * and going to scalar max in increments of scalar range/tile_lines. */ void createTestTile(); bool isNull(ossim_uint32 offset)const; bool isNull(ossim_uint32 offset, ossim_uint32 band)const; void setNull(ossim_uint32 offset); void setNull(ossim_uint32 offset, ossim_uint32 band); bool isNull(const ossimIpt& pt)const; void setNull(const ossimIpt& pt); bool isNull(const ossimIpt& pt, ossim_uint32 band)const; void setNull(const ossimIpt& pt, ossim_uint32 band); virtual bool isValidBand(ossim_uint32 band) const; virtual ossimDataObjectStatus validate() const; /** * Will take this tile and normalize it to a newly * allocated floating point tile. */ virtual ossimRefPtr newNormalizedFloat()const; /** * will go to the band and offset and compute the * normalized float and return it back to the * caller through the result argument. */ virtual void getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, ossim_float32& result)const; /** * This will assign to this object a normalized * value by unnormalizing to its native type. */ virtual void setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, ossim_float32 input); /** * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedFloat(ossimImageData* result)const; /** * Will take this tile and normalize it to a newly * allocated double point tile. */ virtual ossimImageData* newNormalizedDouble()const; /** * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedDouble(ossimImageData* result)const; template void copyTileToFloatBuffer( T /* dummyTemplate*/, ossim_float32* buf)const { const ossim_uint64 SIZE = getSizePerBand(); const ossim_uint64 BANDS = getNumberOfBands(); for (ossim_uint64 band = 0; band < BANDS; ++band) { const T* s = (T*)getBuf(band); // source ossim_float32* d = (ossim_float32*)(buf + (band*SIZE)); // destination for (ossim_uint64 offset = 0; offset < SIZE; ++offset) { ossim_float32 p = s[offset]; d[offset] = p; } } } /** * Will take the normalized input and convert it * to this tile's data type. Example: if this * tile is of type UCHAR and its input is of type * NORALIZED_FLOAT it will unnormalize the data by * doing: * * minPix + normalizedInput*(maxPix-minPix) * * on a per band basis. */ virtual void unnormalizeInput(ossimImageData* normalizedInput); /** * This will compute the average value for the band. */ virtual ossim_float64 computeAverageBandValue( ossim_uint32 bandNumber = 0) const; /** * This will call the compute average band value and then * use that in the calculation of: * It will then do a SUM[(Mean - Actual)^2]/width*height. * * This is the average variance from the passed in * mean. */ virtual ossim_float64 computeMeanSquaredError( ossim_float64 meanValue, ossim_uint32 bandNumber = 0) const; /** * @brief Populates the histogram with data from this tile. * @param histo Populated by this. * @param clip_rect Should be the rectangle of valid data so as to not * count pixels outside of image area on edge tiles. This will be clipped * to the tile rectangle so callers can simply pass the full image rectangle * in. */ virtual void populateHistogram(ossimRefPtr histo, const ossimIrect& clip_rect); virtual void setHistogram(ossimRefPtr histo); ossimRefPtr getHistogram(); /** * @return true if alpha channel is initialized, false if not. */ virtual bool hasAlpha() const; /** * @return const ossim_uint8* to the alpha channel or null if the alpha * channel was not computed. */ virtual const ossim_uint8* getAlphaBuf() const; /** * @return ossim_uint8* to the alpha channel or null if the alpha channel * was not computed. */ virtual ossim_uint8* getAlphaBuf(); /** * @return const void* to theDataBuffer */ virtual const void* getBuf() const; /** * @return const ossim_uint8* to theDataBuffer if scalar is of type * OSSIM_UCHAR; else, NULL. */ virtual const ossim_uint8* getUcharBuf() const; /** * @return const ossim_uint16* to theDataBuffer if scalar is of type * OSSIM_USHORT16 or USHORT11; else, NULL. */ virtual const ossim_uint16* getUshortBuf() const; /** * @return const ossim_sint16* to theDataBuffer if scalar is of type * OSSIM_SSHORT16; else, NULL. */ virtual const ossim_sint16* getSshortBuf() const; /** * @return const ossim_float32* to theDataBuffer if scalar is of type * OSSIM_FLOAT or OSSIM_NORMALIZED_FLOAT; else, NULL. */ virtual const ossim_float32* getFloatBuf() const; /** * @return const ossim_float64* to theDataBuffer if scalar is of type * OSSIM_DOUBLE or OSSIM_NORMALIZED_DOUBLE; else, NULL. */ virtual const ossim_float64* getDoubleBuf() const; /** * @return void* to theDataBuffer */ virtual void* getBuf(); /** * @return ossim_uint8* to theDataBuffer if scalar is of type * OSSIM_UCHAR; else, NULL. */ virtual ossim_uint8* getUcharBuf(); /** * @return ossim_uint16* to theDataBuffer if scalar is of type * OSSIM_USHORT16 or OSSIM_USHORT11; else, NULL. */ virtual ossim_uint16* getUshortBuf(); /** * @return ossim_sint16* to theDataBuffer if scalar is of type * OSSIM_SSHORT16; else, NULL. */ virtual ossim_sint16* getSshortBuf(); /** * @return ossim_float32* to theDataBuffer if scalar is of type * OSSIM_FLOAT or OSSIM_NORMALIZED_FLOAT; else, NULL. */ virtual ossim_float32* getFloatBuf(); /** * @return float64* to theDataBuffer if scalar is of type OSSIM_DOUBLE or * OSSIM_NORMALIZED_DOUBLE; else, NULL. */ virtual ossim_float64* getDoubleBuf(); /** * @param band (zero based) * @return void* to theDataBuffer positioned at band. */ virtual const void* getBuf(ossim_uint32 band) const; /** * @param band (zero based) * @return ossim_uint8* to theDataBuffer positioned at band if scalar is * of type OSSIM_UCHAR; else, NULL. */ virtual const ossim_uint8* getUcharBuf(ossim_uint32 band) const; /** * @param band (zero based) * @return ossim_uint16* to theDataBuffer positioned at band if scalar is * of type OSSIM_USHORT16 or OSSIM_USHORT11; else, NULL. */ virtual const ossim_uint16* getUshortBuf(ossim_uint32 band) const; /** * @param band (zero based) * @return ossim_sint16* to theDataBuffer positioned at band if scalar is * of type OSSIM_SSHORT16; else, NULL. */ virtual const ossim_sint16* getSshortBuf(ossim_uint32 band) const; /** * @param band (zero based) * @return ossim_float32* to theDataBuffer positioned at band if scalar is * of type OSSIM_FLOAT or OSSIM_NORMALIZED_FLOAT; else, NULL. */ virtual const ossim_float32* getFloatBuf(ossim_uint32 band) const; /** * @param band (zero based) * @return ossim_float64* to theDataBuffer positioned at band if scalar is * of type OSSIM_DOUBLE or OSSIM_NORMALIZED_DOUBLE; else, NULL. */ virtual const ossim_float64* getDoubleBuf(ossim_uint32 band) const; /** * @param band (zero based) * @return void* to theDataBuffer positioned at band. */ virtual void* getBuf(ossim_uint32 band); /** * @param band (zero based) * @return ossim_uint8* to theDataBuffer positioned at band if scalar is * of type OSSIM_UCHAR; else, NULL. */ virtual ossim_uint8* getUcharBuf(ossim_uint32 band); /** * @param band (zero based) * @return ossim_uint16* to theDataBuffer positioned at band if scalar is * of type OSSIM_USHORT16 or OSSIM_USHORT11; else, NULL. */ virtual ossim_uint16* getUshortBuf(ossim_uint32 band); /** * @param band (zero based) * @return ossim_sint16* to theDataBuffer positioned at band if scalar is * of type OSSIM_SSHORT16; else, NULL. */ virtual ossim_sint16* getSshortBuf(ossim_uint32 band); /** * @param band (zero based) * @return ossim_float32* to theDataBuffer positioned at band if scalar is * of type OSSIM_FLOAT or OSSIM_NORMALIZED_FLOAT; else, NULL. */ virtual ossim_float32* getFloatBuf(ossim_uint32 band); /** * @param band (zero based) * @return ossim_float64* to theDataBuffer positioned at band if scalar is * of type OSSIM_DOUBLE or OSSIM_NORMALIZED_DOUBLE; else, NULL. */ virtual ossim_float64* getDoubleBuf(ossim_uint32 band); /** * Returns the total number of pixels in a tile for all bands. * Note: This is not in bytes but in pixels. */ virtual ossim_uint64 getSize() const; /** * Returns the number of pixels in a single band in a tile. * Note: This is not in bytes but in pixels. */ virtual ossim_uint64 getSizePerBand() const; /** * Returns the number of bytes in single band of the tile. */ virtual ossim_uint64 getSizePerBandInBytes() const; virtual ossim_uint64 getDataSizeInBytes() const; /** * Returns the total number of bytes for all bands. */ virtual ossim_uint64 getSizeInBytes() const; /** * Initializes data to null pixel values. */ virtual void makeBlank(); /** * Initialize the data buffer. */ virtual void initialize(); /** * @brief Writes tile to stream. * * This will write the buffer to file with an associated header file. * Assuming a contiguous buffer in BSQ format. Currently does not * support converting to BIP or BIL or byte swapping but probably * should add at some point. * * @param f File to write. * * @return true on success, false on error. */ virtual bool write(const ossimFilename& f) const; /** * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(ossim_float64* buf) const; virtual void copyTileToNormalizedBuffer(ossim_float32* buf)const; /** * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. * * @param band Zero based band to copy. * * @param buf Buffer to copy to. */ virtual void copyTileBandToNormalizedBuffer(ossim_uint32 band, ossim_float64* buf) const; /** * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. * * @param band Zero based band to copy. * * @param buf Buffer to copy to. */ virtual void copyTileBandToNormalizedBuffer(ossim_uint32 band, ossim_float32* buf)const; /** * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(ossim_float64* buf); virtual void copyNormalizedBufferToTile(ossim_float32* buf); /** * Will copy the normalized buffer to this tiles * specified band. If band is out of range then nothing * * is done and returns. */ virtual void copyNormalizedBufferToTile(ossim_uint32 band, ossim_float64* buf); virtual void copyNormalizedBufferToTile(ossim_uint32 band, ossim_float32* buf); virtual bool isWithin(ossim_int32 x, ossim_int32 y); /** Sets the pixel at x,y to color value for all bands */ virtual void setValue(ossim_int32 x, ossim_int32 y, ossim_float64 color); /** Sets the pixel at x,y to color on specified band */ virtual void setValue(ossim_int32 x, ossim_int32 y, ossim_float64 color, ossim_uint32 band); virtual void loadBand(const void* src, const ossimIrect& src_rect, ossim_uint32 band); virtual void loadBand(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, ossim_uint32 band); virtual void loadTile(const void* src, const ossimIrect& src_rect, ossimInterleaveType il_type); virtual void loadTileWithAlpha(const void* src, const ossimIrect& src_rect, ossimInterleaveType il_type); virtual void loadTile(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, ossimInterleaveType il_type); virtual void nullTileAlpha(const ossim_uint8* src, const ossimIrect& src_rect, bool mutliplyAlphaFlag=false); virtual void nullTileAlpha(const ossim_uint8* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, bool multiplyAlphaFlag=false); /** * Will load a tile of different types. If they * are the same then it will call loadTile(void*...) * method. Note if they are of different types we * will have to go through a much slower assign * process by normalizing the right side and then * unnormalizing to the destination type. For this * method to work they both must have the same * number of bands. */ virtual void loadTile(const ossimImageData* src); virtual void loadTileFrom1Band(const ossimImageData* data); virtual void loadTileFrom1Band(const void* src, const ossimIrect& src_rect); /** * @brief Loads a tile from a tile. * This assumes last band of src is an alpha channel. * * Written for compressed data where alpha channel may have been compressed * lossy, e.g. 0s flipped to 1s. * * Alpha is applied in the following manner: * if alpha pixel is less than half of bit depth the input pixel is assumed * null; else, valid. If alpha is valid and input is null, output pixel is * set to min pixel value. */ void loadTileFromBsqAlpha(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect); /** * Specialized to load a tile from a short (16 bit scalar type) buffer. * Performs byte swapping if swap_bytes is set to true. */ virtual void loadShortBand(const void* src, const ossimIrect& src_rect, ossim_uint32 band, bool swap_bytes=false); /** * This routine is designed for overwriting a selected band of the * destination buffer 'dest' by an independent selected band of the * source buffer according to a user-selected rule, defined by * OverwriteBandRule. * * Currently the rules available in OverwriteBandRule are: * * The COLOR_DISCREPANCY_OF_ANY_FROM_DEST rule directs that the selected * band of a pixel of the destination buffer is to be overwritten if *any* * one of the other bands of the same destination pixel have color values * that deviate from its color. Same as the deprecated COLOR_DISCREPANCY. * * The COLOR_DISCREPANCY_OF_ALL_FROM_DEST rule directs that the selected * band of a pixel of the destination buffer is to be overwritten only if * *all* of the other bands of the same destination pixel have color values * that deviate from its color. * * The COLOR_EQUALITY_OF_ANY_TO_SRC rule directs that the selected * band of a pixel of the destination buffer is to be overwritten if * *any* one of the other bands of the same destination pixel have color * values that are equal to the color of the selected band of the source * pixel. * * The COLOR_EQUALITY_OF_ALL_TO_SRC rule directs that the selected * band of a pixel of the destination buffer is to be overwritten only if * *all* of the other bands of the same destination pixel have color * values that are equal to the color of the selected band of the source * pixel. * * The NULL_RULE rule directs that the selected band of the * destination buffer is to be overwritten by the selected band of the * source image data (no questions asked). * * @note: The 'dest' buffer should have at least the same number of bands * as the 'src' object. * * Currently this routine is only implemented for il_type set to OSSIM_BSQ. * * @param dest The destination buffer, which should have at least the * same number of bands as the 'src' object. * @param src_band The 0-based band of the source image data. * @param dest_band The 0-based band of the dest buffer. * @param dest_rect The rectangle of the destination buffer. * @param il_type The interleave type. Only OSSIM_BSQ available. * @param ow_type The rule for overwriting the destination buffer. */ virtual void unloadBand( void* dest, ossim_uint32 src_band, ossim_uint32 dest_band, const ossimIrect& dest_rect, ossimInterleaveType il_type=OSSIM_BSQ, OverwriteBandRule ow_type=NULL_RULE ) const; /** * This routine is designed for overwriting a selected band of the * destination buffer 'dest' by an independent selected band of the * source buffer according to a user-selected rule, defined by * OverwriteBandRule. * * Currently the rules available in OverwriteBandRule are: * * The COLOR_DISCREPANCY_OF_ANY_FROM_DEST rule directs that the selected * band of a pixel of the destination buffer is to be overwritten if *any* * one of the other bands of the same destination pixel have color values * that deviate from its color. Same as the deprecated COLOR_DISCREPANCY. * * The COLOR_DISCREPANCY_OF_ALL_FROM_DEST rule directs that the selected * band of a pixel of the destination buffer is to be overwritten only if * *all* of the other bands of the same destination pixel have color values * that deviate from its color. * * The COLOR_EQUALITY_OF_ANY_TO_SRC rule directs that the selected * band of a pixel of the destination buffer is to be overwritten if * *any* one of the other bands of the same destination pixel have color * values that are equal to the color of the selected band of the source * pixel. * * The COLOR_EQUALITY_OF_ALL_TO_SRC rule directs that the selected * band of a pixel of the destination buffer is to be overwritten only if * *all* of the other bands of the same destination pixel have color * values that are equal to the color of the selected band of the source * pixel. * * The NULL_RULE rule directs that the selected band of the * destination buffer is to be overwritten by the selected band of the * source image data (no questions asked). * * @note: The 'dest' buffer should have at least the same number of bands * as the 'src' object. * * Currently this routine is only implemented for il_type set to OSSIM_BSQ. * * @param dest The destination buffer, which should have at least the * same number of bands as the 'src' object. * @param src_band The 0-based band of the source image data. * @param dest_band The 0-based band of the dest buffer. * @param dest_rect The rectangle of the destination buffer. * @param clip_rect Only data within will be copied. * @param il_type The interleave type. Only OSSIM_BSQ available. * @param ow_type The rule for overwriting the destination buffer. */ virtual void unloadBand( void* dest, ossim_uint32 src_band, ossim_uint32 dest_band, const ossimIrect& dest_rect, const ossimIrect& clip_rect, ossimInterleaveType il_type=OSSIM_BSQ, OverwriteBandRule ow_type=NULL_RULE ) const; /** * @param dest The destination buffer. It is assumed this is a single band * and the size of dest_rect. * @param dest_rect The rectangle of the destination buffer. * @param src_band The band to copy (unload) from the tile. */ virtual void unloadBand(void* dest, const ossimIrect& dest_rect, ossim_uint32 src_band) const; /** * @param dest The destination buffer. It is assumed this is a single band * and the size of dest_rect. * @param dest_rect The rectangle of the destination buffer. * param clip_rect Only data within the clip_rect will be copied. * @param src_band The band to copy (unload) from the tile. */ virtual void unloadBand(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect, ossim_uint32 src_band) const; virtual void unloadTile(void* dest, const ossimIrect& dest_rect, ossimInterleaveType il_type ) const; virtual void unloadTile(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect, ossimInterleaveType il_type) const; /** * @param dest The destination buffer. * @param dest_rect The rectangle of the destination buffer. * param clip_rect Only data within the clip_rect will be copied. * @param src_band The band to copy (unload) from the tile. */ virtual void unloadTileToBipAlpha(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const; virtual bool isPointWithin(const ossimIpt& point)const; virtual bool isPointWithin(ossim_int32 x, ossim_int32 y)const; virtual std::ostream& print(std::ostream& out) const; /** * @brief Performs linear stretch on tile data from min/max to limits of * scalar type. */ virtual void stretchMinMax(); /** * @brief Computes the alpha channel. * * For each pixel if any band value is not null then alpha will be 255; * else, 0. */ virtual void computeAlphaChannel(); /** * @brief Method to copy a single line to the tile. * * This will copy a line to the tile. It is assumed that all bands are in * the buffer "src". Only pixels within the tile rect will be copied. * Note that all coordinates are relative to the tile coordinates. * Clipping will be performed on pixels outside of the tile rectangle. * No fill is added if a partial tile line is copied so callers * should do a ossimImageData::makeBlank if the whole tile is not to be * stuffed. ossimImageData::validate should be called after all lines * are copied if in doubt of a full tile. * * @param src The source buffer or line to copy containing all bands. * * @param lineNumber Line number to copy. * * @param lineStartSample The start sample of the source buffer relative * to tile coordinates. * * @param lineStopSample The stop sample of the source buffer relative * to tile coordinates. * * @param lineInterleave Interleave of src buffer. If OSSIM_BIP assumed * rgbrgbrgb; else, red row, green row, blue row. * * Usage example in method: ossimTiffTileSource::loadFromScanLine */ virtual void copyLine(const void *src, ossim_int64 lineNumber, ossim_int64 lineStartSample, ossim_int64 lineStopSample, ossimInterleaveType lineInterleave); /** * @brief Sets the indexed flag. * * This indicates the data contains palette indexes. Default is false. * * @param flag If true data is indexed. */ void setIndexedFlag(bool flag); /** @return The indexed flag. */ bool getIndexedFlag() const; /** * @brief Returns the percentage (0-100) of data buffer containing non-null * (valid) entries. Undefined until validate() is called. */ ossim_float64 percentFull() const; /** * @brief External means to set percent full. * @param percent full. */ void setPercentFull( const ossim_float64& percentFull ); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: /** @brief Templated copy line method. */ template void copyLineTemplate(T dummyTemplate, const void *src, ossim_int64 lineNumber, ossim_int64 lineStartSample, ossim_int64 lineStopSample, ossimInterleaveType lineInterleave); /** * @brief Templated stretch method. * * Performs linear stretches on tile data from min/max to limits of * scalar type. */ template void stretchMinMax(T dummyTemplate); /** * @brief Templated compute alpha channel. * * For each pixel if any band value is not null then alpha will be 255; * else, 0. */ template void computeAlphaChannel(T dummyTemplate); /** * Templated validate method. * * @return The status of the ossimImageDataMethod. * * @note See ossimConstants.h for ossimDataObjectStatus enumerations. */ template ossimDataObjectStatus validate(T dummyTemplate) const; /** * Templated makeBlank method. */ template void makeBlank(T dummyTemplate); /** * Templated computeMeanSquaredError method. */ template ossim_float64 computeMeanSquaredError(T dummyTemplate, ossim_float64 meanValue, ossim_uint32 bandNumber) const; /** * Templated computeAverageBandValue method. */ template ossim_float64 computeAverageBandValue(T dummyTemplate, ossim_uint32 bandNumber) const; void loadTileFromBip(const void* src, const ossimIrect& src_rect); void loadTileFromBipAlpha(const void* src, const ossimIrect& src_rect); void loadTileFromBil(const void* src, const ossimIrect& src_rect); void loadTileFromBsq(const void* src, const ossimIrect& src_rect); void loadTileFromBip(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect); void loadTileFromBil(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect); void loadTileFromBsq(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect); void unloadTileToBip(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const; void unloadTileToBil(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const; void unloadTileToBsq(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const; /** * Called from public unloadBand() routines that have an * OverwriteBandRule interface. * * @param dest The destination buffer. * @param src_band The 0-based band of the source image data. * @param dest_band The 0-based band of the destination buffer. * @param dest_rect The rectangle of the destination buffer. * @param clip_rect Only data within will be copied. * @param ow_type The rule for overwriting the destination buffer. */ virtual void unloadBandToBsq( void* dest, ossim_uint32 src_band, ossim_uint32 dest_band, const ossimIrect& dest_rect, const ossimIrect& clip_rect, OverwriteBandRule ow_type=NULL_RULE ) const; /** * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ template void copyTileToNormalizedBuffer(T dummyTemplate, ossim_float64* buf) const; template void copyTileToNormalizedBuffer(T dummyTemplate, ossim_float32* buf)const; /** * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. */ template void copyTileToNormalizedBuffer(T dummyTemplate, ossim_uint32 band, ossim_float64* buf) const; template void copyTileToNormalizedBuffer(T dummyTemplate, ossim_uint32 band, ossim_float32* buf)const; /** * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ template void copyNormalizedBufferToTile(T dummyTemplate, ossim_float64* buf); template void copyNormalizedBufferToTile(T dummyTemplate, ossim_float32* buf); template void copyNormalizedBufferToTile(T dummyTemplate, ossim_uint32 band, ossim_float64* buf); template void copyNormalizedBufferToTile(T dummyTemplate, ossim_uint32 band, ossim_float32* buf); template void computeMinMaxPix(T dummyValue, std::vector& minBands, std::vector& maxBands) const; template void computeMinMaxNulPix(T dummyValue, std::vector& minBands, std::vector& maxBands, std::vector& nulBands) const; template void loadBandTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, ossim_uint32 band); template void loadBandTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, ossim_uint32 band); template void nullTileAlphaTemplate(T, const ossim_uint8* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, bool multiplyAlphaFlag=false); template void loadTileFromBipTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect); template void loadTileFromBipAlphaTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect); template void loadTileFromBipTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect); template void loadTileFromBipAlphaTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect); template void loadTileFromBilTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect); template void loadTileFromBilTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect); template void loadTileFromBsqTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect); template void loadTileFromBsqTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect); template void loadTileFromBsqAlphaTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect); template void unloadTileToBipTemplate(T, // dummy template variable void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const; template void unloadTileToBipAlphaTemplate(T, // dummy template variable void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const; template void unloadTileToBilTemplate(T, // dummy template variable void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const; template void unloadTileToBsqTemplate(T, // dummy template variable void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const; template void unloadBandTemplate(T, // dummy template variable void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect, ossim_uint32 band) const; template void unloadBandToBsqTemplate(T, // dummy template variable void* dest, ossim_uint32 src_band, ossim_uint32 dest_band, const ossimIrect& dest_rect, const ossimIrect& clip_rect, OverwriteBandRule ow_type=NULL_RULE) const; /** * @brief Creates a test tile for scalar type for testing only. * * Protected template implementation of matching public createTestTile. */ template void createTestTile(T); /** * @brief initializeDefaults() Resizes and sets min/max/null arrays to * number of bands and some default value for scalar type. */ virtual void initializeDefaults(); /** * @brief initializeMinDefault() Resizes theMinPixelValue array to number * of bands and initializes to the default min for scalar type. */ virtual void initializeMinDefault(); /** * @brief initializeMaxDefault() Resizes theMaxPixelValue array to number * of bands and initializes to the default max for scalar type. */ virtual void initializeMaxDefault(); /** * @brief initializeNullDefault() Resizes theNullPixelValue array to number * of bands and initializes to the default null for scalar type. */ virtual void initializeNullDefault(); virtual bool isEqualTo(const ossimDataObject& rhs, bool deepTest=false)const; bool hasSameDimensionsAs(ossimImageData* data)const { bool result = false; if(data) { result = ((m_spatialExtents.size() == data->m_spatialExtents.size())&& (m_spatialExtents[0] == data->m_spatialExtents[0])&& (m_spatialExtents[1] == data->m_spatialExtents[1])&& (m_scalarType == data->m_scalarType)); } return result; } /** Null pixel value for each band. */ std::vector m_nullPixelValue; /** Min pixel value for each band. */ std::vector m_minPixelValue; /** Max pixel value for each band. */ std::vector m_maxPixelValue; /** Alpha channel */ std::vector m_alpha; ossimIpt m_origin; /** Indicates data contains palette indexes. */ bool m_indexedFlag; ossimRefPtr m_histogram; /** percentage (0-100) of image tile that has valid (non-null) pixel values. This is computed * in validate() method. */ mutable ossim_float64 m_percentFull; private: TYPE_DATA }; inline bool ossimImageData::hasAlpha() const { return (m_alpha.size()?true:false); } inline ossimIrect ossimImageData::getImageRectangle() const { ossimIpt lr(m_origin.x + getWidth() - 1, m_origin.y + getHeight() - 1); return ossimIrect(m_origin, lr); } inline const ossim_float64* ossimImageData::getNullPix()const { return ( m_nullPixelValue.size() > 0 ? &m_nullPixelValue.front() : 0 ); } inline const ossim_float64* ossimImageData::getMinPix()const { return ( m_minPixelValue.size() > 0 ? &m_minPixelValue.front() : 0 ); } inline const ossim_float64* ossimImageData::getMaxPix()const { return ( m_maxPixelValue.size() > 0 ? &m_maxPixelValue.front() : 0 ); } inline ossim_float64 ossimImageData::getNullPix(ossim_uint32 band) const { return ( band < m_nullPixelValue.size() ? m_nullPixelValue[band] : ossim::defaultNull( getScalarType() ) ); } inline ossim_float64 ossimImageData::getMinPix(ossim_uint32 band) const { return ( band < m_minPixelValue.size() ? m_minPixelValue[band] : ossim::defaultMin( getScalarType() ) ); } inline ossim_float64 ossimImageData::getMaxPix(ossim_uint32 band) const { return ( band < m_maxPixelValue.size() ? m_maxPixelValue[band] : ossim::defaultMax( getScalarType() ) ); } inline ossim_uint32 ossimImageData::getHashId()const { const unsigned char *bufx = (unsigned char*)(&m_origin.x); const unsigned char *bufy = (unsigned char*)(&m_origin.y); return (ossim_uint32)(bufx[0]*101 + bufx[1]*103 + bufx[2]*107 + bufx[3]*109 + bufy[0]*139 + bufy[1]*149 + bufy[2]*151 + bufy[3]*157); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageDataFactory.h000066400000000000000000000036171352751253100245020ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // //************************************************************************* // $Id: ossimImageDataFactory.h 13474 2008-08-22 14:20:42Z gpotts $ #ifndef ossimImageDataFactory_HEADER #define ossimImageDataFactory_HEADER #include #include #include class ossimSource; class ossimImageSource; /*! * This factory should be called by all image source producers to allocate * an image tile. */ class OSSIM_DLL ossimImageDataFactory { public: virtual ~ossimImageDataFactory(); static ossimImageDataFactory* instance(); virtual ossimRefPtr create(ossimSource* owner, ossimScalarType scalar, ossim_uint32 bands = 1)const; virtual ossimRefPtr create(ossimSource* owner, ossimScalarType scalar, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height)const; virtual ossimRefPtr create( ossimSource* owner, ossim_uint32 bands, ossimImageSource* inputSource)const; virtual ossimRefPtr create( ossimSource* owner, ossimImageSource* inputSource)const; protected: ossimImageDataFactory(); // hide ossimImageDataFactory(const ossimImageDataFactory&){}//hide void operator = (ossimImageDataFactory&){}// hide static ossimImageDataFactory* theInstance; static std::mutex theInstanceMutex; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageDataHelper.h000066400000000000000000000054751352751253100243160ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimImageDataHelper.h 23356 2015-06-03 18:28:03Z dburken $ #ifndef ossimImageDataHelper_HEADER #define ossimImageDataHelper_HEADER 1 #include #include #include #include class OSSIM_DLL ossimImageDataHelper { public: /*! * This must be a valid image data object */ ossimImageDataHelper(ossimImageData* imageData=0); void setImageData(ossimImageData* imageData); void fill(const double* values, const ossimIrect& rect, bool clipPoly=true); void fill(const double* values, std::vector& regionList, bool clipPoly=true); void fill(const ossimRgbVector& color, std::vector& regionList, bool clipPoly=true); void fill(const ossimRgbVector& color, const ossimIrect& rect, bool clipPoly=true); /*! * Values must be of the same type as the image data that * we are writing to. */ void fill(const double* values, const ossimPolygon& region, bool clipPoly=true); void fill(const ossimRgbVector& color, const ossimPolygon& region, bool clipPoly=true); /*! * The input is assumed to have the same origin, size and scalar * as this object. This will implement a selection */ void copyInputToThis(const void* input, const ossimPolygon& region, bool clipPoly=true); ossimImageData* theImageData; protected: ossimIpt theOrigin; ossimIrect theImageRectangle; ossimPolyArea2d thePolyImageRectangle; template void fill(T dummyVariable, const double* values, const ossimPolygon& region, bool clipPoly); template void fill(T dummyVariable, const double* values, const ossimIrect& region, bool clipPoly); template void copyInputToThis(const T* inputBuf, const ossimPolygon& region, bool clipPoly); template void fill(T dummyVariable, const double* values, const ossimPolygon& region); template void fill(T dummyVariable, const double* values, const ossimIrect& region); template void copyInputToThis(const T* inputBuf, const ossimPolygon& region); }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageDisplayWriter.h000066400000000000000000000040721352751253100250770ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Frank Warmerdam (warmerdam@pobox.com) // // Description: // // Contains class declaration for ossimImageWriter //******************************************************************* // $Id: ossimImageDisplayWriter.h 17195 2010-04-23 17:32:18Z dburken $ #ifndef ossimImageDisplayWriter_HEADER #define ossimImageDisplayWriter_HEADER #include #include #include #include #include #include class ossimImageDisplayWriter : public ossimImageWriter, public ossimDisplayInterface, public ossimConnectableObjectListener { public: bool canConnectMyInputTo(ossim_int32 /* inputIndex */, const ossimConnectableObject* object)const { return (object&& PTR_CAST(ossimImageSource, object)); } virtual void setOutputName(const ossimString& out) { setTitle(out); } /*! * Sets the title of a display. */ virtual void setTitle( const ossimString& title )=0; /*! * will return true if its minimized */ virtual bool isMinimized()const=0; virtual bool isMaximized()const=0; /*! * Will repaint the display */ virtual void refreshDisplay()=0; virtual void minimize()=0; virtual void maximize()=0; /*! * Will show a display */ virtual void show()=0; protected: virtual ~ossimImageDisplayWriter(){} ossimImageDisplayWriter(ossimObject* owner=NULL); ossimImageDisplayWriter(ossimObject* owner, ossim_uint32 numberOfInputs, ossim_uint32 numberOfOutputs, bool inputListIsFixed, bool outputListIsFixed); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageFileWriter.h000066400000000000000000000405401352751253100243510ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Frank Warmerdam (warmerdam@pobox.com) // // Description: // // Contains class declaration for ossimImageWriter //******************************************************************* // $Id: ossimImageFileWriter.h 21963 2012-12-04 16:28:12Z dburken $ #ifndef ossimImageFileWriter_HEADER #define ossimImageFileWriter_HEADER #include #include #include #include #include #include #include #include #include /** * Pure virtual base class for image file writers. * * There is normally one subclass of this class for each format supported * for writing. This class roughly corresponds to the ImageHandler class * used for reading images. Format specific ossimImageWriter's are normally * instantiated by the ossimImageWriterFactory::createWriterInstance() method. * ossimImageWriters should not be directly instantiated by application code. */ class OSSIMDLLEXPORT ossimImageFileWriter : public ossimImageWriter, public ossimProcessInterface, public ossimConnectableObjectListener { public: /** * The writer will own the sequencer. */ ossimImageFileWriter(const ossimFilename& filename = ossimFilename(), ossimImageSource* inputSource=0, ossimObject* owner=0); virtual ~ossimImageFileWriter(); virtual ossimObject* getObject(); virtual const ossimObject* getObject()const; /** * void getImageTypeList(std::vector& imageTypeList)const * * pure virtual * * Appends the writers image types to the "imageTypeList". * * This is the actual image type name. So for * example, ossimTiffWriter has several image types. Some of these * include TIFF_TILED, TIFF_TILED_BAND_SEPARATE ... etc. * The ossimGdalWriter * may include GDAL_IMAGINE_HFA, GDAL_RGB_NITF, GDAL_JPEG20000, ... etc. * * @param imageTypeList stl::vector list to append to. * * @note All writers should append to the list, not, clear it and then add * their types. */ virtual void getImageTypeList(std::vector& imageTypeList)const=0; /** * Returns a 3-letter extension from the image type descriptor * (theOutputImageType) that can be used for image file extensions. * * @param imageType string representing image type. * * @return the 3-letter string extension. */ virtual ossimString getExtension() const; /** * Examples of writers that always generate internal * overviews are ossim_kakadu_jp2 and ossim_kakadu_nitf_j2k. * * @return true if the output of the writer will have * internal overviews. The default is false. */ virtual bool getOutputHasInternalOverviews( void ) const; /** * bool hasImageType(const ossimString& imageType) const * * @param imageType string representing image type. * * @return true if "imageType" is supported by writer. */ virtual bool hasImageType(const ossimString& imageType) const; /** * Sets the output image tiling size if supported by the writer. If not * supported this simply sets the sequencer(input) tile size. */ virtual void setTileSize(const ossimIpt& tileSize); /** * Will write an envi header file. If "theFilename" is "foo.tif" * then this will write out "foo.hdr". */ virtual bool writeEnviHeaderFile() ; /** * Will write an ER Mapper header file. If "theFilename" is "foo.tif" * then this will write out "foo.hdr". */ virtual bool writeErsHeaderFile() ; /** * Will write an external geometry file. If "theFilename" is "foo.tif" * then this will write out "foo.geom". */ virtual bool writeExternalGeometryFile() ; /** * Will write an fgdc file. If "theFilename" is "foo.tif" * then this will write out "foo.xml". */ virtual bool writeFgdcFile() ; /** * Returns true on success, false on error. */ virtual bool writeHistogramFile() ; /** * Will write a jpeg world file. If "theFilename" is "foo.tif" * then this will write out "foo.jpw". */ virtual bool writeJpegWorldFile() ; /** * Write out an ossim overview file from the source_file. * If source file is "foo.tif", this will create a "foo.ovr" in * the same directory. * * @param source_file The file to create overview from. * * @param tiff_compress_type valid types: * - COMPRESSION_JPEG * - COMPRESSION_DEFLATE * - COMPRESSION_PACKBITS * - COMPRESSION_NONE=1 (default) * * @param jpeg_compress_quality Compression quality. Only valid with * COMPRESSION_JPEG. Range 1 to 100 with 100 being the best. * default = 75 * * @return true on success, false on error. */ virtual bool writeOverviewFile(ossim_uint16 tiff_compress_type = 1, ossim_int32 jpeg_compress_quality = 75, bool includeR0 = false ); /** * Will write a readme file. If "theFilename" is "foo.tif" * then this will write out "foo_readme.txt". */ virtual bool writeReadmeFile() ; /** * Will write a world file. If "theFilename" is "foo.tif" * then this will write out "foo.tfw". */ virtual bool writeTiffWorldFile() ; /** * Will write a world file. The extension will be derived from the * image extension. * * Currently handles the following image extensions: * * "tif" or "tiff" -> "tfw" * "jpg" of "jpeg" -> "jpw" * "png" -> "pgw" * "sid" -> "sdw" * * If extension does not match one of the above no file will be written * and false will be returned. * * @return true on success false on error. */ virtual bool writeWorldFile() ; /** * Convenience method that calls meta data write methods that are flagged * to be called. Attempts to write all files flagged to be written even * if one file writer returns false. * * Currently calls these methods if flagged: * writeEnviHeaderFile * writeExternalGeometryFile * writeFgdcFile * writeJpegWorldFile * writeReadmeFile * writeTiffWorldFile * writeOverviewFile * writeHistogramFile * * @return true if all files flagged are written, false if not. */ virtual bool writeMetaDataFiles() ; virtual void setAreaOfInterest(const ossimIrect& inputRect); /** * @brief Sets the sequencer and connects it to the input of this. * * This does not set the area of interest. Note stored as an ossimRefPtr. * * @param sequencer Pointer to a sequencer. */ virtual void changeSequencer(ossimImageSourceSequencer* sequencer); virtual ossimImageSourceSequencer* getSequencer(); /** * @brief Initialize method. * * Calls theInputConnection->initialize() then syncs area of interest(AOI) * with ossimImageWriter::theAreaOfInterest taking precedence over * ossimImageSourceSequencer::theAreaOfInterest. */ virtual void initialize(); /** * Calls: * writeFile() * writeMetaDataFiles() * * @return true on success, false on error. */ virtual bool execute(); /** * @brief Method to write the image to a stream. * * This implementation does nothing and returns false. * Derived classed should implement as needed. * * @return true on success, false on error. */ virtual bool writeStream(); /** * @brief Sets the output stream to write to. * * This implementation in this class does nothing and returns false. * Derived classed should implement as needed. * * @param stream The stream to write to. * * @return true if object can write to stream, false if not. */ virtual bool setOutputStream(ossimRefPtr stream); /** tmp drb */ virtual bool setOutputStream(std::ostream& str); /** * @brief Method to return the stream attached to output. * * This implementation in this class does nothing and returns an empty * ossimRefPtr. * Derived classed should implement as needed. * * @return The stream wrapped around a ref pointer. */ virtual ossimRefPtr getOutputStream() const; virtual void setPercentComplete(double percentComplete); virtual void setOutputImageType(ossim_int32 type); virtual void setOutputImageType(const ossimString& type); virtual ossim_int32 getOutputImageType() const; virtual ossimString getOutputImageTypeString() const; virtual void setOutputName(const ossimString& outputName); virtual void setFilename(const ossimFilename& file); virtual const ossimFilename& getFilename()const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; virtual void disconnectInputEvent(ossimConnectionEvent& event); virtual void connectInputEvent(ossimConnectionEvent& event); virtual void propertyEvent(ossimPropertyEvent& event); /** * Control flags... */ virtual bool getWriteImageFlag() const; virtual bool getWriteHistogramFlag() const; virtual bool getWriteOverviewFlag() const; virtual bool getScaleToEightBitFlag() const; virtual bool getWriteEnviHeaderFlag() const; virtual bool getWriteErsHeaderFlag() const; virtual bool getWriteExternalGeometryFlag() const; virtual bool getWriteFgdcFlag() const; virtual bool getWriteJpegWorldFileFlag() const; virtual bool getWriteReadmeFlag() const; virtual bool getWriteTiffWorldFileFlag() const; virtual bool getWriteWorldFileFlag() const; virtual void setWriteImageFlag(bool flag); virtual void setWriteOverviewFlag(bool flag); virtual void setWriteHistogramFlag(bool flag); virtual void setScaleToEightBitFlag(bool flag); virtual void setWriteEnviHeaderFlag(bool flag); virtual void setWriteErsHeaderFlag(bool flag); virtual void setWriteExternalGeometryFlag(bool flag); virtual void setWriteFgdcFlag(bool flag); virtual void setWriteJpegWorldFile(bool flag); virtual void setWriteReadme(bool flag); virtual void setWriteTiffWorldFile(bool flag); virtual void setWriteWorldFile(bool flag); virtual ossim_uint16 getOverviewCompressType() const; virtual ossim_int32 getOverviewJpegCompressQuality() const; virtual void setOverviewCompressType(ossim_uint16 type); virtual void setOverviewJpegCompressQuality(ossim_int32 quality); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * Overrides base "addListener" this will capture the pointer and then call * the base class "addListener". If overview building is enabled, the * listener will be passed to the overview builder::addListener, and * subsequently removed from the overview builder after the build overview * call is complete. This it transparent to the caller of this method. * * @param listener The listener to add. * * @return Currently always returns true. * * @note Callers still should call "removeListener" after the writing * process is complete. * * @note If called more than once, theProgressListener will contain * the latest listener. */ virtual bool addListener(ossimListener* listener); /** * Overrides base "removeListener". Calls base "removeListener which will * find and removes the listener. * If "theProgressListener" pointer matches listener "theProgressListener" * will be set to NULL. * * @param listener The listener to remove. * * @return Currently always returns true. */ virtual bool removeListener(ossimListener* listener); /** * If "point" the coordinate tie points are relative to the center of the * pixel. If "area" the coordinate tie points are relative to the upper * left corner of the pixel. * * For image types that are keyed, tiff for instance, this will set the * geotiff key: GTRasterTypeGeoKey * * If meta data writers are enabled, world file writers for instance, * this will also be propagated to them. * * Default in this writer is: OSSIM_PIXEL_IS_POINT * * @param type * OSSIM_PIXEL_IS_POINT = center of pixel * OSSIM_PIXEL_IS_AREA = upper left corner of pixel */ virtual void setPixelType(ossimPixelType type); /** * If "point" the coordinate tie points are relative to the center of the * pixel. If "area" the coordinate tie points are relative to the upper * left corner of the pixel. * * For image types that are keyed, tiff for instance, this will set the * geotiff key: GTRasterTypeGeoKey * * If meta data writers are enabled, world file writers for instance, * this will also be propagated to them. * Default in this writer is: OSSIM_PIXEL_IS_POINT * * @param type * "point" = center of pixel * "area" = upper left corner of pixel * * @note If the downcased "type" is not equal to "point" or "area" pixel * type will remain unchanged. */ virtual void setPixelType(const ossimString& type); /** * @return The pixel type as either OSSIM_PIXEL_IS_POINT or * OSSIM_PIXEL_IS_AREA. */ virtual ossimPixelType getPixelType() const; /** * @param type ossimString to initialize which will either be "point" or * "area". */ virtual void getPixelTypeString(ossimString& type) const; protected: /** * Common world file writer method. * * @param file The file to write like "foo.tfw" or "foo.jpw". * * @return true on success, false on error. */ bool writeWorldFile(const ossimFilename& file); /** * Write out the file. * @return true on success, false on error. */ virtual bool writeFile() = 0; ossimRefPtr theInputConnection; ossimRefPtr theViewController; ossimListener* theProgressListener; ossimFilename theFilename; ossimString theOutputImageType; bool theWriteImageFlag; bool theWriteOverviewFlag; bool theWriteHistogramFlag; bool theScaleToEightBitFlag; ossim_uint16 theOverviewCompressType; ossim_int32 theOverviewJpegCompressQuality; /** * External meta data writer flags. Not really part of an image writer, put * here for convenience. If true the writer will do the connection work * for you. */ bool theWriteEnviHeaderFlag; bool theWriteErsHeaderFlag; bool theWriteExternalGeometryFlag; bool theWriteFgdcFlag; bool theWriteJpegWorldFileFlag; bool theWriteReadmeFlag; bool theWriteTiffWorldFileFlag; bool theWriteWorldFileFlag; bool theAutoCreateDirectoryFlag; /** * If not a geographic projection this allows the user to set the linear * units of the output tag to be: * * meters (default) * us_survey_feet * feet * * This will be propagated to writers that can switch types and to the * associated metadata writers. */ ossimUnitType theLinearUnits; /** OSSIM_PIXEL_IS_POINT = 0, OSSIM_PIXEL_IS_AREA = 1 */ ossimPixelType thePixelType; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageGaussianFilter.h000066400000000000000000000050471352751253100252200ustar00rootroot00000000000000//******************************************************************* // License: MIT // // See LICENSE.txt file in the top level directory for more details. // class ossimImageGaussianFilter : tile source //******************************************************************* // $Id: ossimImageGaussianFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimImageGaussianFilter_HEADER #define ossimImageGaussianFilter_HEADER #include #include /** * class for symmetric Gaussian filtering * implemented as two separable horizontal/vertical gaussian filters * * PROPERTIES: * -GaussStd is the standard deviation of the gaussian * (filter widths are equal to 2*floor(2.5*GaussStd+0.5)+1) * -strictNoData selects the behaviour for NODATA pixels * true : any NODATA pixels in the convolution will Nullify the center pixel * false : center pixel will be NODATA only if it was NODATA before * other NODATA pixels are processed as zero in the convolution calculation */ class OSSIM_DLL ossimImageGaussianFilter : public ossimImageSourceFilter { public: /** * own methods */ ossimImageGaussianFilter(); inline ossim_float64 getGaussStd()const { return theGaussStd; } void setGaussStd(const ossim_float64& v); inline bool isStrictNoData()const { return theStrictNoData; } void setStrictNoData(bool aStrict); /** * inherited methods */ virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect &tileRect,ossim_uint32 resLevel=0); virtual void connectInputEvent(ossimConnectionEvent &event); virtual void disconnectInputEvent(ossimConnectionEvent &event); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool loadState(const ossimKeywordlist& kwl,const char* prefix = 0); virtual bool saveState(ossimKeywordlist& kwl,const char* prefix = 0)const; protected: virtual ~ossimImageGaussianFilter(); /** * protected methods */ void initializeProcesses(); void updateKernels(); /** * parameters */ ossim_float64 theGaussStd; bool theStrictNoData; /** * subprocesses */ ossimRefPtr theHF; //horizontal filter ossimRefPtr theVF; //vertical filter TYPE_DATA }; #endif /* #ifndef ossimImageGaussianFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageGeometry.h000066400000000000000000000537071352751253100241010ustar00rootroot00000000000000//*********************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer (oscarkramer@yahoo.com) // // Description: Class declaration of ossimImageGeometry. // //*********************************************************************************************** // $Id: ossimImageGeometry.h 3102 2012-01-18 15:30:20Z oscar.kramer $ #ifndef ossimImageGeometry_HEADER #define ossimImageGeometry_HEADER 1 #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Forward class declarations: class ossimDrect; class ossimIrect; class ossimGrect; //*********************************************************************************************** //! Container class that holds both 2D transform and 3D projection information for an image //! Only one instance of this is alive per image. This is the object that is returned from //! a call to ossimImageSource::getImageGeometry() //! //! All images in OSSIM have at least a 2D transformation from local (relative to start of file) //! to full-image coordinates. Often this transform is an identity transform (does nothing). In //! some cases however, the first pixel in the file does not correspond to the upper-left pixel of //! the original, full image. Since the image's sensor model may only apply to full-image pixel //! coordinates, it is necessary to reference the latter when making computing ground point //! location. Also the local image could be a reduced resolution level of the full image. So //! the image could be a decimated sub image of the full image. //! //! Additionally, images typically are accompanied by some form of metadata that defines the mapping //! from 2D image coordinates to 3D world coordinates. This mapping may be in the form of a map //! projection for orthorectified images, or a perspective projection such as a sensor model. //! //! This object class maintains both 2D transform and 3D projection information for the associated //! image. This object will typically be created and "owned" by the image handler object. Therefore, //! only one copy per image will exist at a time. //! //! Notes: //! 1) Shifts are relative to "full image space". So if you have a sub image from r2 the shift //! given to the transform should be relative to "full image space". // //! 2) A decimation of 1.0 is the full image. This may or may not be r0 as r0 can be decimated. //! //*********************************************************************************************** class OSSIM_DLL ossimImageGeometry : public ossimObject { public: typedef std::vector DeltaParamList; //! Default constructor defaults to unity transform with no projection. ossimImageGeometry(); virtual ~ossimImageGeometry(); //! Copy constructor -- performs a deep copy. This is needed when an imageSource in the chain //! needs to modify the image geometry at that point in the chain. The image geometry to the //! left of that imageSource must remain unchanged. This constructor permits that imageSource to //! maintain its own geometry based on the input geometry. All chained objects to the right //! would see this alternate geometry. See ossimScaleFilter for an example of this case. ossimImageGeometry(const ossimImageGeometry& copy_this); //! Constructs with projection and transform objects available for referencing. Either pointer //! can be NULL -- the associated mapping would be identity. ossimImageGeometry(ossim2dTo2dTransform* transform, ossimProjection* projection); //! Shortcut way of getting to an image's geometry when access to pixels is not needed. //! @param image Image to open //! @return true if open was successful and a valid geometry was initialized. bool open(const ossimFilename& image); //! rnToRn is a utility method that takes a rn resolution image point and maps it to the another //! rn resolution image point. //! //! @param inRnPt Is a point in resolution n. //! @param inResolutionLevel Is the resolution of the point inRnPt. //! @param outResolutionLevel Is the resolution of the point outRnPt. //! @param outRnPt Is the result of the transform. //! void rnToRn(const ossimDpt& inRnPt, ossim_uint32 inResolutionLevel, ossim_uint32 outResolutionLevel,ossimDpt& outRnPt) const; //! rnToFull is a utility method that takes a rn resolution image point and maps it to the full //! image point. //! //! @param rnPt Is a point in resolution n. //! @param resolutionLevel Is the resolution of the point rnPt. a value of 0 is the local image //! @param fullPt Is the result of the transform //! void rnToFull(const ossimDpt& rnPt, ossim_uint32 resolutionLevel, ossimDpt& fullPt) const; //! @brief fullToRn is a utility method that takes a full image point and maps it to a rn //! resolution image point. //! //! @param fullPt Is a point in full image space. //! @param resolutionLevel Is the resolution of the point rnPt. A value of 0 is the local image. //! @param fullPt Is the result of the transform void fullToRn(const ossimDpt& fullPt, ossim_uint32 resolutionLevel, ossimDpt& rnPt) const; //! rnToWorld is a utility method that takes a rn resolution image point and maps it to the //! world point. //! //! @param rnPt Is a point in resolution n. //! @param resolutionLevel Is the resolution of the point rnPt. a value of 0 is the local image //! @param wpt Is the result of the transform //! void rnToWorld(const ossimDpt& rnPt, ossim_uint32 resolutionLevel, ossimGpt& wpt) const; //! worldToRn is a utility method that takes a world point allows one to transform all the way back to //! an rn point. //! //! @param wpt Ground point. //! @param resolutionLevel Is the resolution of the point rnPt. a value of 0 is the local image //! @param rnPt Is the resoltion point. //! void worldToRn(const ossimGpt& wpt, ossim_uint32 resolutionLevel, ossimDpt& rnPt) const; //! Exposes the 3D projection from image to world coordinates. The caller should verify that //! a valid projection exists before calling this method. Returns TRUE if a valid ground point //! is available in the ground_pt argument. This method depends on the existence of elevation //! information. If no DEM is available, the results will be incorrect or inaccurate. bool localToWorld(const ossimDpt& local_pt, ossimGpt& world_pt) const; bool localToWorld(const ossimDrect& local_rect, ossimGrect& world_rect) const; //! Exposes the 3D projection from image to world coordinates given a constant height above //! ellipsoid. The caller should verify that a valid projection exists before calling this //! method. Returns TRUE if a valid ground point is available in the ground_pt argument. bool localToWorld(const ossimDpt& local_pt, const double& h_ellipsoid, ossimGpt& world_pt) const; //! Exposes the 3D world-to-local image coordinate reverse projection. The caller should verify //! that a valid projection exists before calling this method. Returns TRUE if a valid image //! point is available in the local_pt argument. bool worldToLocal(const ossimGpt& world_pt, ossimDpt& local_pt) const; bool worldToLocal(const ossimGrect& world_rect, ossimDrect& local_rect) const; //! Sets the transform to be used for local-to-full-image coordinate transformation void setTransform(ossim2dTo2dTransform* transform); //! Sets the projection to be used for local-to-world coordinate transformation void setProjection(ossimProjection* projection); //! Access methods for transform (may be NULL pointer). const ossim2dTo2dTransform* getTransform() const { return m_transform.get(); } ossim2dTo2dTransform* getTransform() { return m_transform.get(); } //! Access methods for projection (may be NULL pointer). const ossimProjection* getProjection() const { return m_projection.get(); } ossimProjection* getProjection() { return m_projection.get(); } /** * @brief Returns true if underlying projection is derived from * ossimMapProjection. * @return true if map projected; false, if not. */ bool isMapProjected() const; /** * @return const ossimMapProjection* or NULL if projection not set or not * derived from ossimMapProjection. */ const ossimMapProjection* getAsMapProjection() const { return dynamic_cast( m_projection.get() ); } /** * @return ossimMapProjection* or NULL if projection not set or not * derived from ossimMapProjection. */ ossimMapProjection* getAsMapProjection() { return dynamic_cast( m_projection.get() ); } //! Returns TRUE if valid projection defined bool hasProjection() const { return m_projection.valid(); } //! Returns TRUE if valid transform defined bool hasTransform() const { return m_transform.valid(); } //! Returns TRUE if this geometry is sensitive to elevation bool isAffectedByElevation() const; //! Returns the GSD associated with this image in the active projection. Note that this only //! makes sense if there is a projection associated with the image. Returns NaNs if no //! projection defined. ossimDpt getMetersPerPixel() const; /** * @brief Get the ground sample distance(GSD) associated with this image * in the active projection. * * GSD is taken from projection if there is no transform set; else, * taken from three localToWorld calls (one pixel apart) at the image * center. If the projection or the image size(if needed) is not set the * point will be set to NaNs. * * @param gsd Point to intialize with GSD. * * @note This only makes sense if there is a projection associated with * the image. * * @note Result should be checked for NaNs after call. */ void getMetersPerPixel( ossimDpt& gsd ) const; //! Returns the resolution of this image in degrees/pixel. Note that this only //! makes sense if there is a projection associated with the image. Returns NaNs if no //! projection defined. ossimDpt getDegreesPerPixel() const; /** * @brief Get the resolution of this image in degrees/pixel. * * Degrees/pixel is taken from projection if there is no transform set; * else, taken from three localToWorld calls (one pixel apart) at the image * center. If the projection or the image size(if needed) is not set the * point will be set to NaNs. * * @param dpp Point to intialize with degrees/pixel. * * @note This only makes sense if there is a projection associated with * the image. * * @note Result should be checked for NaNs after call. */ void getDegreesPerPixel( ossimDpt& dpp ) const; //! Assigns the ossimGpts with the ground coordinates of the four corresponding image //! corner points. Returns true if points are valid. bool getCornerGpts(ossimGpt& ul, ossimGpt& ur, ossimGpt& lr, ossimGpt& ll) const; /** * @brief Get the latitude, longitude of the tie point. * * This is the bounding upper left point of the image which is not * necessarily the image (0, 0) point. * * @param tie ossimGpt to assign. * * @param edge If true the tie point is shifted up and to the right by * half the gsd. * * @note Requires projection and image size to be initialized or the * latitude and longitue will be set to nan. * * @note The height parameter of the ossimGpt is not touched by this method. */ void getTiePoint(ossimGpt& tie, bool edge) const; /** * @brief Get the easting, northing of the tie point. * * This is the bounding upper left point of the image which is not * necessarily the image (0, 0) point. * * @param tie ossimDpt to assign. * * @param edge If true the tie point is shifted up and to the right by * half the gsd. * * @note Requires projection and image size to be initialized or the * easting and northing will be set to nan. */ void getTiePoint(ossimDpt& tie, bool edge) const; //! Prints contents to output stream. std::ostream& print(std::ostream& out) const; //! Returns TRUE if argument geometry has exactly the same instances for transform and //! m_projection. This should be expanded to permit different instances of same transforms bool operator==(const ossimImageGeometry& compare_this) const; //! Replaces any existing transform and projection with those in the copy_this object const ossimImageGeometry& operator=(const ossimImageGeometry& copy_this); //! Returns the decimation factor from R0 for the resolution level specified. For r_index=0, the //! decimation factor is by definition 1.0. For the non-discrete case, r_index=1 returns a //! decimation of 0.5. If the vector of discrete decimation factors (m_decimationFactors) is //! empty, the factor will be computed as f=1/2^n ossimDpt decimationFactor(ossim_uint32 r_index) const; /** * @brief Method to get the decimation factor for a given resolution * level. * * If the array of decimations is not initialized by owner, the default is: * r_index=0 is by definition 1.0. * r_index=n Where n is some level the factor will be computed as f=1/2^n. * * @param resLevel Reduced resolution set for requested decimation. * * @param result ossimDpt to initialize with requested decimation. */ void decimationFactor(ossim_uint32 r_index, ossimDpt& result) const; /** * @brief Gets array of all decimation levels. * @param decimations Array to initialiaze. */ void decimationFactors(std::vector& decimations) const; //! Sets the decimation scheme to a discrete list of decimation factors. void setDiscreteDecimation(const std::vector& decimation_list) { m_decimationFactors = decimation_list; } //! @return The number of decimation factors ossim_uint32 getNumberOfDecimations()const { return (ossim_uint32)m_decimationFactors.size(); } void setImageSize(const ossimIpt& size) { m_imageSize = size; } const ossimIpt& getImageSize()const { return m_imageSize; } bool getCrossesDateline()const; void getImageEdgePoints(std::vector& result, ossim_uint32 partitions = 25)const; /** * This is the first stage implementation. It will determine if it crosses the dateline * and do a special multi polygon for the ossimPolyArea2d result. For each edge * of the image we walk "partitions" number of points. If we cross a dateline we calculate * the crossing lat by using the parametric form of the equation. For example, if we * are crossing from positive to negative that means we are going through the 180 degree lon * location and we will need to solve for the paramtetric parameter t and plug back into the parametric * equation to solve for the latitude. Basic form: start + (end-start)*t = 180. If we are coming from * negative to positive then we solve basic form: start + (end-start)*t = -180. Where deltaPoint is (end-start) * * ossim_float64 t = ((180-start.x)/deltaPoint.x); * ossim_float64 lat = (start.y+deltaPoint.y*t); * * If we do not cross the dateline then if the image is affected by elevation (i.e. a sensor model) then we use the partitions * parameter to calculate that number of partitions to sample along each edge. * * if The geometry is not affected by elevation then we just use the corner points and ignore the partitions parameter * * @param poly holds the resulting polygon. This could be a MultiPolygon depending on the geometry * @param partitions These are the number of steps you want when walking the border. */ void calculatePolyBounds(ossimPolyArea2d& result, ossim_uint32 partitions = 25)const; /** * @brief Get the bounding rect of (0, 0) to (imageSize.x-1, imageSize.y-1). * * Relies on image size being initialized. * * @param bounding_rect Initialized by this method. Will do a * ossimIrect::makeNan() if the image size is not initialized. */ void getBoundingRect(ossimIrect& bounding_rect) const; void getBoundingRect(ossimDrect& bounding_rect) const; // Overloaded for drect. void getBoundingGroundRect(ossimGrect& bounding_grect) const; //! Creates a new instance of ossimImageGeometry with the same transform and projection. //! Overrides base-class version requiring loadState() and saveState() (not implemented yet) virtual ossimObject* dup() const { return new ossimImageGeometry(*this); } //! Attempts to initialize a transform and a projection given the KWL. Returns TRUE if no //! error encountered. virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Saves the transform (if any) and projection (if any) states to the KWL. virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /** * @brief Set m_targetRrds data member. * * This is used by methods worldToRn and localToWorld that do not take a rrds * argument and methods rnToWorld and worldToRn. If the target rrds is set to 2, * then the resulting point from worldToLocal is relative to reduced * resolution level 2. Vice versa for localToWorld it is assumed the local * point is relative to the target * reduced resolution data set. * * @param rrds Target (zero based) reduced resolution data set. */ void setTargetRrds(ossim_uint32 rrds); /** * @return The target zero based reduced resolution data set used for localToWorld and * worldToLocal. * @see setTargetRrds */ ossim_uint32 getTargetRrds() const; //! @brief Changes the GSD and image size to reflect the scale provided. //! @param scale The scale to be applied in x and y directions //! @param recenterTiePoint If true the will adjust the tie point by shifting the original tie //! to the upper left corner, applying scale, then shifting back by half of either the new //! theDeltaLat/lon or theMetersPerPixel depending on if underlying projection isGeographic. void applyScale(const ossimDpt& scale, bool recenterTiePoint); virtual bool isEqualTo(const ossimObject& obj, ossimCompareType compareType = OSSIM_COMPARE_FULL)const; // If we have an adjustable parameter interface return one. // // @return a pointer to an ossimAdjustableParameterInterface or NULL if no // adjustable paramters exist // virtual ossimAdjustableParameterInterface* getAdjustableParameterInterface(); virtual const ossimAdjustableParameterInterface* getAdjustableParameterInterface()const; // Compute partials from image to ground with respect to the adjustable parameters. // // bool computeImageToGroundPartialsWRTAdjParam(ossimDpt& result, const ossimGpt& gpt, ossim_uint32 idx, ossim_float64 paramDelta=1.0); bool computeImageToGroundPartialsWRTAdjParams(NEWMAT::Matrix& result, const ossimGpt& gpt, ossim_float64 paramDelta=1.0); bool computeImageToGroundPartialsWRTAdjParams(NEWMAT::Matrix& result, const ossimGpt& gpt, const DeltaParamList& deltas); bool computeGroundToImagePartials(NEWMAT::Matrix& result, const ossimGpt& gpt, const ossimDpt3d& deltaLlh); bool computeGroundToImagePartials(NEWMAT::Matrix& result, const ossimGpt& gpt); /** * @return Returns the angle to "up is up" in decimal degrees, 0.0 if image * is not affected by elevation, ossim::nan on error. */ ossim_float64 upIsUpAngle(const ossimDpt&) const; ossim_float64 upIsUpAngle() const; /** * @return Returns the angle to "north up" in decimal degrees, ossim::nan * on error. */ ossim_float64 northUpAngle() const; protected: //! @brief Method to back out decimation of a point. //! @param rnPt Is a point in resolution n. //! @param resolutionLevel Is the resolution of the point rnPt. //! @param outPt Is the result of the transform a non-decimated point. void undecimatePoint(const ossimDpt& rnPt, ossim_uint32 resolutionLevel, ossimDpt& outPt) const; //! @brief Method to apply decimation of a point. //! @param inPt Is a point with no decimation. //! @param resolutionLevel Is the resolution of the point rnPt. //! @param rnPt Is the result of the transform void decimatePoint(const ossimDpt& inPt, ossim_uint32 resolutionLevel, ossimDpt& rnPt) const; ossimRefPtr m_transform; //!< Maintains local_image-to-full_image transformation ossimRefPtr m_projection; //!< Maintains full_image-to-world_space transformation std::vector m_decimationFactors; //!< List of decimation factors for R-levels ossimIpt m_imageSize; // Image width and height /** @brief Target rrds for localToWorld and worldToLocal methods. */ ossim_uint32 m_targetRrds; TYPE_DATA }; #endif /* #ifndef ossimImageGeometry_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageGeometryFactory.h000066400000000000000000000035671352751253100254300ustar00rootroot00000000000000//***************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Class declaration of ossimImageGeometryFactory. // //***************************************************************************** // $Id$ #ifndef ossimImageGeometryFactory_HEADER #define ossimImageGeometryFactory_HEADER 1 #include class ossim2dTo2dTransform; class ossimNitfTileSource; class ossimProjection; class OSSIM_DLL ossimImageGeometryFactory : public ossimImageGeometryFactoryBase { public: static ossimImageGeometryFactory* instance(); virtual ossimImageGeometry* createGeometry(const ossimString& typeName)const; virtual ossimImageGeometry* createGeometry(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual ossimImageGeometry* createGeometry(const ossimFilename& filename, ossim_uint32 entryIdx)const; virtual bool extendGeometry(ossimImageHandler* handler)const; virtual void getTypeNameList(std::vector& typeList)const; /** * This is a utility method used by crateGeoemtry that takes an image handler */ virtual ossim2dTo2dTransform* createTransform(ossimImageHandler* handler)const; /** * @brief Utility method to create a projection from an image handler. * @param handler The image handler to create projection from. * @return Pointer to an ossimProjection on success, null on error. */ virtual ossimProjection* createProjection(ossimImageHandler* handler) const; protected: ossimImageGeometryFactory(); virtual ossim2dTo2dTransform* createTransformFromNitf(ossimNitfTileSource* handler)const; static ossimImageGeometryFactory* m_instance; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageGeometryFactoryBase.h000066400000000000000000000031071352751253100262110ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Class declaration of ossimImageGeometryFactoryBase. See .h file for class documentation. // //************************************************************************************************** // $Id$ #ifndef ossimImageGeometryFactoryBase_HEADER #define ossimImageGeometryFactoryBase_HEADER #include #include class ossimImageHandler; class OSSIM_DLL ossimImageGeometryFactoryBase : public ossimBaseObjectFactory { public: /** * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const { return createGeometry(typeName); } /** * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const { return createGeometry(kwl, prefix); } virtual ossimImageGeometry* createGeometry(const ossimString& typeName)const=0; virtual ossimImageGeometry* createGeometry(const ossimKeywordlist& kwl, const char* prefix=0)const=0; virtual ossimImageGeometry* createGeometry(const ossimFilename& filename, ossim_uint32 entryIdx)const = 0; virtual bool extendGeometry(ossimImageHandler* handler)const=0; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageGeometryRegistry.h000066400000000000000000000051511352751253100256200ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Class declaration of ossimImageGeometryRegistry. See .h file for class documentation. // //************************************************************************************************** // $Id$ #ifndef ossimImageGeometryRegistry_HEADER #define ossimImageGeometryRegistry_HEADER #include #include #include #include class OSSIM_DLL ossimImageGeometryRegistry : public ossimImageGeometryFactoryBase, public ossimFactoryListInterface { public: virtual ~ossimImageGeometryRegistry(){m_instance=0;} static ossimImageGeometryRegistry* instance(); virtual ossimImageGeometry* createGeometry(const ossimString& typeName)const; virtual ossimImageGeometry* createGeometry(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual ossimImageGeometry* createGeometry(const ossimFilename& filename, ossim_uint32 entryIdx)const; #if 0 /*! * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const { return createObjectFromRegistry(typeName); } /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const { return createObjectFromRegistry(kwl, prefix); } #endif virtual bool extendGeometry(ossimImageHandler* handler)const; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const { getAllTypeNamesFromRegistry(typeList); } protected: ossimImageGeometryRegistry() :ossimImageGeometryFactoryBase() {} ossimImageGeometryRegistry( const ossimImageGeometryRegistry& rhs ) :ossimImageGeometryFactoryBase(rhs) {} void operator =(const ossimImageGeometryRegistry&){} static ossimImageGeometryRegistry* m_instance; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageHandler.h000066400000000000000000000730261352751253100236570ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // // This class defines an abstract image handler which all loaders should // derive from. // //******************************************************************** // $Id: ossimImageHandler.h 22960 2014-11-06 15:42:13Z okramer $ #ifndef ossimImageHandler_HEADER #define ossimImageHandler_HEADER 1 #include #include #include #include #include #include #include #include #include class ossimMultiResLevelHistogram; /** * This class defines an abstract Handler which all image handlers(loaders) * should derive from. */ class OSSIMDLLEXPORT ossimImageHandler : public ossimImageSource { public: enum ossimImageHandlerOverviewCompressionType { OSSIM_OVERVIEW_COMPRESSION_NONE= 0, OSSIM_OVERVIEW_COMPRESSION_JPEG, OSSIM_OVERVIEW_COMPRESSION_LZW, OSSIM_OVERVIEW_COMPRESSION_DEFLATE, OSSIM_OVERVIEW_COMPRESSION_PACKBITS }; /** Constructor (default): */ ossimImageHandler(); /** * Destructor: * Derived classes should implement. */ virtual ~ossimImageHandler(); /** * initialize * Does nothing in this class. Implemented to satisfy pure virtual. */ virtual void initialize(); /** * Searches for an overview. Uses theImageFile as a key. * If theImageFile = "foo.tif" it will look for "foo.ovr" first, * then "foo_ovr.tif" next. * Calls openOverview(const ossimFilename& overview_file) * @return true on success, false on error. * @see openOverview(const ossimFilename& overview_file) */ virtual bool openOverview(); /** * Calls closeOverview(), then attempts to open the overview_file. * On success, theOverviewFile will be set and theOverview will be * initialized. On failure, theOverviewFile will be cleared and * theOverview deleted and set to NULL. * @param overview_file ossimFilename representing overview file. * @return true on success, false on error. * @see closeOverview() */ virtual bool openOverview(const ossimFilename& overview_file); /** * If theOverview is initialized it will be deleted and set to NULL. Also * clears theOverviewFile. * @return void */ virtual void closeOverview(); /** * @return the image handler of the overview, if it has been * successfully opened. */ virtual const ossimImageHandler* getOverview() const; /** * @return true if getNumberOfReducedResSets > 1, false if not. * @see getNumberOfReducedResSets() */ virtual bool hasOverviews() const; /** * @return ossimFilename represents an external OSSIM overview filename. */ virtual ossimFilename createDefaultOverviewFilename() const; /** * @return ossimFilename represents an external OSSIM geometry filename. */ virtual ossimFilename createDefaultGeometryFilename() const; /** * @return ossimFilename represents an external OSSIM metadata filename. */ virtual ossimFilename createDefaultMetadataFilename() const; /** * @return ossimFilename represents an external OSSIM histogram filename. */ virtual ossimFilename createDefaultHistogramFilename() const; /** * @return ossimFilename represents an external OSSIM valid vertices filename. */ virtual ossimFilename createDefaultValidVerticesFilename() const; /** * Outputs vertices to file and updates the internal vertex * array variable "theValidImageVertices". * @param vertices Array of ossimIpts to write. * @param file Name of output file to write to. If file is empty, the * output file will be the image file with no extension + _vertices.kwl. * So if the image is "foo.tif" you'll get "foo_vertices.kwl". * @return true on success, false on error. */ virtual bool writeValidImageVertices(const std::vector& vertices, const ossimFilename& file=ossimFilename("")); /** * Opens the valid image vertices file and sets theValidImageVerticesFile * variable. * @param vertices_file File name containing valid vertices for image. * @return true on success, false on error. */ virtual bool openValidVertices(const ossimFilename& vertices_file); /** * Creates vertices file name based on image, then tries to open. * If theImageFile = "foo.tif" it will look for "foo_vertices.kwl". * @return true on success, false on error. */ virtual bool openValidVertices(); /** * Pure virtual open. Derived classes must implement. * * @return Returns true on success, false on error. * * @note This method relies on the data member ossimImageData::theImageFile * being set. Callers should do a "setFilename" prior to calling this * method or use the ossimImageHandler::open that takes a file name and an * entry index. */ virtual bool open() = 0; /** * Opens the image file. * * @param imageFile File to open. * * @param entryIndex * @return true on success, false on error. */ virtual bool open(const ossimFilename& imageFile, ossim_uint32 entryIndex); virtual bool open(const ossimFilename& imageFile); virtual bool open(std::shared_ptr state); /** * Deletes the overview and clears the valid image vertices. Derived * classes should implement. */ virtual void close(); /** * Derived classes must implement this method to be concrete. * * @return true if open, false if not. */ virtual bool isOpen()const=0; /** * Build a histogram for image file. * * @param numberOfRLevels sets the maximum number of reduced resolution * level to compute histogram for. * * @param mode OSSIM_HISTO_MODE_NORMAL or OSSIM_HISTO_MODE_FAST. * * @return true on success, false if not open. */ virtual bool buildHistogram( int numberOfRLevels=0, ossimHistogramMode mode=OSSIM_HISTO_MODE_NORMAL ); /** * Build a histograms for all image entries. * * @param numberOfRLevels sets the maximum number of reduced resolution * level to compute histogram for. * * @param mode OSSIM_HISTO_MODE_NORMAL or OSSIM_HISTO_MODE_FAST. * * @return true on success, false if not open. */ virtual bool buildAllHistograms( int numberOfRLevels=0, ossimHistogramMode mode=OSSIM_HISTO_MODE_NORMAL ); /** * Will build over file for theImageFile. * * @param includeFullResFlag if true the full resolution layer will also * be put in the overview format. This is handly for inefficeint formats. */ virtual bool buildOverview(ossimImageHandlerOverviewCompressionType compressionType = OSSIM_OVERVIEW_COMPRESSION_NONE, ossim_uint32 quality = 75, ossimFilterResampler::ossimFilterResamplerType resampleType = ossimFilterResampler::ossimFilterResampler_BOX, bool includeFullResFlag=false); /** * Will build over file for all image entries. * * @param includeFullResFlag if true the full resolution layer will also * be put in the overview format. This is handly for inefficeint formats. */ virtual bool buildAllOverviews(ossimImageHandlerOverviewCompressionType compressionType = OSSIM_OVERVIEW_COMPRESSION_NONE, ossim_uint32 quality = 75, ossimFilterResampler::ossimFilterResamplerType resampleType = ossimFilterResampler::ossimFilterResampler_BOX, bool includeFullResFlag=false); /** * Will build an over file for filename. * @param filename Name of image file. * * @param includeFullResFlag if true the full resolution layer will also * be put in the overview format. This is handly for inefficeint formats. */ virtual bool buildOverview(const ossimFilename& filename, ossimImageHandlerOverviewCompressionType compressionType = OSSIM_OVERVIEW_COMPRESSION_NONE, ossim_uint32 quality = 75, ossimFilterResampler::ossimFilterResamplerType resampleType = ossimFilterResampler::ossimFilterResampler_BOX, bool includeFullResFlag=false); /** * @brief Fetches the current entry image's histogram. * * @return Ref pointer to histogram or null if histogram does not exist. * * @note Old behaviour: "If none exists, it will be created." taken out. * * Do: * ossimRefPtr his = ih->getImageHistogram(); * if ( ih.valid() ) * { * } * else * { * ih->buildHistogram(); * } * */ ossimRefPtr getImageHistogram() const; /** * Returns the image geometry object associated with this tile source or * NULL if non defined. The geometry contains full-to-local image * transform as well as projection (image-to-world). */ virtual ossimRefPtr getImageGeometry(); /** * Sets the image geometry object. * * @note Callers should note that this will override any existing * geometry. * * @note This does not write the geometry to disk, to do so call * one of the saveImageGeometry methods. */ virtual void setImageGeometry(ossimImageGeometry* geom); /** * Saves the image geometry to a file that will be made based on the image * file name. */ virtual void saveImageGeometry() const; /** * Saves the image geometry to a file that will be made based on the image * file name. */ virtual void saveImageGeometry(const ossimFilename& geometry_file) const; /** * Pure virtual, derived classes must implement. * * @param resLevel Reduced resolution level to return lines of. * Default = 0 * * @return The number of lines for specified reduced resolution level. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 resLevel = 0) const = 0; /** * Pure virtual, derived classes must implement. * * @param resLevel Reduced resolution level to return samples of. * Default = 0 * * @return The number of samples for specified reduced resolution level. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 resLevel = 0) const = 0; /** * @brief Returns zero-based bounding rectangle of the image. * Note sub-image offset now in ossimImageGeometry class. * * @param resLevel Reduced resolution level for rectangle. * * @return Rectangle of reduced resolution level. */ virtual ossimIrect getImageRectangle(ossim_uint32 resLevel = 0) const; /** * @brief Returns zero-based bounding rectangle of the image. * Same as getImageRectangle() call. Note sub-image offset now * in ossimImageGeometry class. * * @param resLevel Reduced resolution level for rectangle. * * @return Rectangle of reduced resolution level. */ virtual ossimIrect getBoundingRect(ossim_uint32 resLevel = 0) const; /** * @param resLevel Reduced resolution set for requested decimation. * * @param result ossimDpt to initialize with requested decimation. * * @note Initialized "result" with the decimation factor for the passed in * resLevel. * Most of the time the returned factor is a square decimation along x * and y indicated by result.x and .y = 1.0/(resLevel^2) where ^ * means rasing to the power of. If the resLevel is 1 then the return * decimation .5, .5. this is not the decimation to each resolution * level but the total decimation from res level 0. * So if resLevel is 2 then the return is .25, .25. * * @note Derived classes should override if the decimation is anything other * than a power of two change in each direction per res level. */ virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const; /** * This returns all decimation for all levels. */ virtual void getDecimationFactors(std::vector& decimations) const; /** * This returns the total number of decimation levels. It is important to * note that res level 0 or full resolution is included in the list and has * decimation values 1.0, 1.0 */ virtual ossim_uint32 getNumberOfDecimationLevels() const; /** * This method is obsolete. Please use getNumberOfDecimationLevels. * * For backwards compatibility this calls getNumberOfDecimationLevels. */ virtual ossim_uint32 getNumberOfReducedResSets()const; /** * Sets the filename */ virtual void setFilename(const ossimFilename& filename); /** * Returns the filename */ virtual const ossimFilename& getFilename()const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @brief Determines if the passed in reslution level is valid. * * If this reader is used as an overview the caller should pass in a * resLevel relative to the full image. * * @param resLevel zero base resolution level. * @return true on success, false on error. */ virtual bool isValidRLevel(ossim_uint32 resLevel) const; /** * Connection rule. Since image handler currently don't have any * inputs this will just return false saying we can't connect anything * to an image handler. */ bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object) const; /** * ordering specifies how the vertices should be arranged. * valid image vertices is basically the tightly fit convex hull * of the image. Usually an image has NULL values and are * internally not upright rectangular. This can cause * problems some spatial filters. * * The default implementation is to return the bounding rect. */ virtual void getValidImageVertices(std::vector& validVertices, ossimVertexOrdering ordering=OSSIM_CLOCKWISE_ORDER, ossim_uint32 resLevel=0)const; /** * @brief Indicates whether or not the image handler can control output * band selection via the setOutputBandList method. * @return true if band selector; false, if not. */ virtual bool isBandSelector() const; /** * @brief If the image handler "isBandSeletor()" then the band selection * of the output chip can be controlled. * * This method returns false. Derived classes that are band selectors should * override. * * @param band_list Requested bands. * * @return true on success, false on error. */ virtual bool setOutputBandList(const std::vector& band_list); /** * @brief If the image handler "isBandSeletor()" then the band selection * of the output are set to input or identity. Does nothing and returns * false if not a band selector. * * @return If band selector, returns the output of setOutputBandList; if * not, returns false. */ virtual bool setOutputToInputBandList(); /** * @brief Convenience method to see if band list is identity. * @param bandList List to check. * @return true if band selector; false, if not. */ virtual bool isIdentityBandList( const std::vector& bandList ) const; /** * Indicates whether or not the image is tiled internally. * This implementation returns true if (getImageTileWidth() && * getImageTileHeight()) are both non zero. * Override in the image handler if something else is desired. * Returns true if tiled, false if not. */ virtual bool isImageTiled() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const = 0; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const = 0; virtual bool hasMetaData() const; virtual ossimRefPtr getLut()const; virtual bool hasLut() const; /** * There is an external file with an omd extension. this file contains * additional information about the image such as the null pixel, min and * max values. * For general raster it will contain much more than that. */ virtual void loadMetaData(); /** * Retuns the min pixel value. If there was an external eta data file * then use the meta data from that file. If not given then we will * return the default min */ virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual double getNullPixelValue(ossim_uint32 band=0)const; /** * @brief convenience method to set min pixel value. * * Added for overview readers so that the image handler that owns the * overview reader can pass on it's min value. * * @param band Zero based band to set. * * @param pix Min pixel value. */ virtual void setMinPixelValue(ossim_uint32 band, const ossim_float64& pix); /** * @brief convenience method to set max pixel value. * * Added for overview readers so that the image handler that owns the * overview reader can pass on it's max value. * * @param band Zero based band to set. * * @param pix Max pixel value. */ virtual void setMaxPixelValue(ossim_uint32 band, const ossim_float64& pix); /** * @brief convenience method to set null pixel value. * * Added for overview readers so that the image handler that owns the * overview reader can pass on it's max value. * * @param band Zero based band to set. * * @param pix Null pixel value. */ virtual void setNullPixelValue(ossim_uint32 band, const ossim_float64& pix); /** * @return The current entry number. * * @note This implementation returns 0. Derived classes should override * if of multiple entry image type. */ virtual ossim_uint32 getCurrentEntry()const; /** * @return The number of entries (images) in the image file. */ virtual ossim_uint32 getNumberOfEntries()const; /** * @brief Get the name of entry as a string. * * This implementation clears name. Derived classes that support multiple * entries and have "named" entries should re-implement to provide entry * names. Example given from HDF5 file: * * entry_name: /All_Data/VIIRS-IMG-GTM-EDR-GEO_All/QF1_VIIRSGTMGEO * * @param entryIdx Zero based entry index. If out of range name will * be cleared. * * @param name Initialized by this. */ virtual void getEntryName( ossim_uint32 entryIdx, std::string& name ) const; /** * @param entryList This is the list to initialize with entry indexes. * * @note This implementation returns puts one entry "0" in the list. */ virtual void getEntryList(std::vector& entryList) const; /** * @param getEntryNames List to initialize with strings associated with * entries. * * @note This implementation calls getEntryList and converts entries in * the list to strings. Derived classes that support multiple entries * with associated strings should re-implement. */ virtual void getEntryNames(std::vector& entryNames) const; /** * @brief Convenience method to determine if entry index should be used for * support files, e.g. file.his or file_e1.his. * * @returns true if file is open, && * ( (entryList.size() > 1) || (entryList[0] != 0) ) * false otherwise. * * @note This is just a hint. Put here as code was duplicated everywhere. * Callers can do what they wish. */ bool useEntryIndex() const; ossimFilename getOverviewFile()const; /** * @param entryIdx Entry number to select. * * @note The implementation does nothing. Derived classes that handle * multiple images should override. * * @return true if it was able to set the current entry and false otherwise. */ virtual bool setCurrentEntry(ossim_uint32 entryIdx); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * @brief Returns the image file with extension set using supplentary * directory for dirname if set. * * Default behaviour is to add the "_en.ext" only if the file is * multi-entry. Use set_e0_prefix to override this. * * Examples: * * - theImageFile = "foo.hdf" * - The number of entries = 1 * - ext parameter = "geom" * - return of method will = "foo.geom" * * - theImageFile = "foo.hdf" * - The number of entries = 12 * - The current entry = 3 * - ext parameter = "geom" * - return of method will = "foo_e3.geom" * * @param ext Extension to tack onto file. Can have or have not ".", it * will be added if "." is not the first character. * * @param set_e0_prefix If true and the number of entries = 1 then * "foo.geom" would come out "foo_e0.geom" instead. Default = false. * * @return theImageFile with the extension replaced with ext. */ ossimFilename getFilenameWithThisExtension(const ossimString& ext, bool set_e0_prefix=false) const; /** * Returns the image file with extension set using supplentary directory * for dirname if set. This is like the getFilenameWithThisExtension(...) * method except it does NOT add the "_en" if image is multi entry. * * Examples: * * - theImageFile = "foo.tif" * - ext parameter = "geom" * - return of method will = "foo.geom" * * @param ext Extension to tack onto file. Can have or have not ".", it * will be added if "." is not the first character. * * @param f Initialized by this. */ void getFilenameWithThisExt( const ossimString& ext, ossimFilename& f ) const; ossim_uint32 getStartingResLevel() const; void setStartingResLevel(ossim_uint32 level); /** @return theOpenOverviewFlag */ bool getOpenOverviewFlag() const; /** * @brief Sets theOpenOverviewFlag. * * If true opening of overviews will be attempted on normal open. If * false only the base image will be opened (shallow open). * Defaulted to true in constructor. */ void setOpenOverviewFlag(bool flag); /** * Sets the supplementary directory */ virtual void setSupplementaryDirectory(const ossimFilename& dir); /** * Returns the supplementary directory */ virtual const ossimFilename& getSupplementaryDirectory()const; //! Fetches the image ID. This is initialized to -1 in the constructor but is searched for in //! loadState(): const ossimString& getImageID() const { return theImageID; } //! Sets the image ID in case it is externally generated void setImageID(const ossimString& id) { theImageID = id; } //! Returns the raster pixel alignment type. OSSIM treats all alignments internally as //! pixel-is-point. This is only a flag to identify the source's alignment type. ossimPixelType getPixelType() const { return thePixelType; } /** * @brief Convenience method to get the zero based rgb output band list. * * This method returns false and is here only so derived classes can * override. * * @param bandList * @return false */ virtual bool getRgbBandList(std::vector& bandList) const; template std::shared_ptr getStateAs(){return std::dynamic_pointer_cast (m_state);} template std::shared_ptr getStateAs()const{return std::dynamic_pointer_cast (m_state);} std::shared_ptr getState(){return m_state;} std::shared_ptr getState()const{return m_state;} void setState(std::shared_ptr state){m_state = state;} protected: /** * Returns the image geometry object associated with this tile source or * NULL if non defined. The geometry contains full-to-local image * transform as well as projection (image-to-world). * * This method just looks for external .geom style override only. * If you want to go through a registry then call getImageGeometry(). */ virtual ossimRefPtr getExternalImageGeometry() const; virtual ossimRefPtr getInternalImageGeometry() const; /** * @brief Method to get an overview tile. Derived classes should override if * they have built in overviews or something different than the standard * external overview file. Image handlers can call this method from getTile * in place of inlining code or if derived class needs to override this * method. * * @param resLevel The resolution level to pull from with resLevel 0 being * full res. * * @param result The tile to stuff. * passing. * * @return true on success false on error. Typically this will return false * if resLevel==0 unless the overview has r0. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getOverviewTile(ossim_uint32 resLevel, ossimImageData* result); /** * Opens file and attempts to initialize the valid image vertices. * Returns true on success, false on error. */ bool initVertices(const char* file); /** * Will complete the opening process. * If there are overviews it will open them. * If there is meta data it will open that and if there * is valid vertices it will open that. */ virtual void completeOpen(); /** * @brief Convenience method to set things needed in the image geometry from * the image handler. At time of writing sets the decimation and image size. * @param geom ossimImageGeometry to initiale. */ void initImageParameters(ossimImageGeometry* geom) const; /** * @brief Virtual method determines the decimation factors at each resolution level. This * base class implementation computes the decimation by considering the ratios in image size * between resolution levels, with fuzzy logic for rounding ratios to the nearest power of 2 * if possible. Derived classes need to override this method if the decimations are provided * as part of the image metadata. */ virtual void establishDecimationFactors(); /** * @brief Convenience method to set output band list. * * This performs range checking and calls theOverview->setOutputBandList * on success. * * @param inBandList The new band list. * @param outBandList Band list to initialize. * @return true on success, false on error. */ virtual bool setOutputBandList(const std::vector& inBandList, std::vector& outBandList); /** * @brief Get filename with no extension, using supplentary directory for * dirname if set. * * Examples: * * f = "foo.tif" * f = "foo" */ void getFilenameWithNoExtension( ossimFilename& f ) const; ossimFilename theImageFile; ossimFilename theOverviewFile; ossimFilename theSupplementaryDirectory; ossimRefPtr theOverview; std::vector theValidImageVertices; ossimImageMetaData theMetaData; mutable ossimRefPtr theGeometry; ossimRefPtr theLut; std::vector theDecimationFactors; ossimString theImageID; /** * theStartingResLevel If set to something other than zero(default) this is * indicative that the reader is an overview. */ ossim_uint32 theStartingResLevel; // 0 being full or highest res. /** * If true opening of overviews will be attempted. If false only the base * image will be opened (shallow open). Defaulted to true in constructor. */ bool theOpenOverviewFlag; mutable ossimPixelType thePixelType; // pixel-is-point or pixel-is-area std::shared_ptr m_state; TYPE_DATA }; #endif /* #ifndef ossimImageHandler_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageHandlerFactory.h000066400000000000000000000110721352751253100252000ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: David Burken // // Description: // // Contains class declaration for ossimImageHandlerFactoryMaker. //******************************************************************* // $Id$ #ifndef ossimImageHandlerFactory_HEADER #define ossimImageHandlerFactory_HEADER 1 #include #include class ossimImageHandler; class ossimFilename; class ossimKeywordlist; //******************************************************************* // CLASS: ossimImageHandlerFactory //******************************************************************* class OSSIMDLLEXPORT ossimImageHandlerFactory : public ossimImageHandlerFactoryBase { public: virtual ~ossimImageHandlerFactory(); static ossimImageHandlerFactory* instance(); /** * @param openOverview If true image handler will attempt to open overview. * default = true */ virtual ossimImageHandler* open(const ossimFilename& fileName, bool openOverview=true)const; virtual ossimImageHandler* open(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual ossimRefPtr open(std::shared_ptr state)const; /** * @brief Open method that takes a stream. * @param str Open stream to image. * @param connectionString * @param openOverview If true attempt to open overview file. * @return ossimImageHandler */ virtual ossimRefPtr open( std::shared_ptr& str, const std::string& connectionString, bool openOverview ) const; /** * @brief Open overview that takes a file name. * * @param file File to open. * * @return ossimRefPtr to image handler on success or null on failure. */ virtual ossimRefPtr openOverview( const ossimFilename& file ) const; virtual ossimObject* createObject(const ossimString& typeName)const; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const; virtual void getSupportedExtensions(ossimImageHandlerFactoryBase::UniqueStringList& extensionList)const; virtual void getImageHandlersBySuffix(ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& ext)const; virtual void getImageHandlersByMimeType(ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& mimeType)const; protected: /** * @brief Open dot.src (ossimSrcRecord). * * Currently only opens a single image. Can be used for split base image * with overviews and histograms in a separate "support" directory. * * Input record example: * * ossim_src_record_version: 1.0 * image0.entry: 0 * image0.file: s3://your_bucket/data1/test/data/public/tif/ls7-ff-fusion.tif * image0.ovr: /data1/s3_test/ls7-ff-fusion.ovr * image0.hist: /data1/s3_test/ls7-ff-fusion.his * image0.support: /data1/s3_test * * @param str Open stream to src record. * @param connectionString Path to src file. * @param openOverview If true attempt to open overview file. * @return ossimRefPtr to image handler on success or null on failure. */ ossimRefPtr openSrcRecord(std::shared_ptr& str, const std::string& connectionString, bool openOverview ) const; /** * @brief Open method that looks at extension e.g. "tif", "jpg" to select * class to open. * * This is to be called by standard open before just going down the list * of classes the brute force hard way. * * @param fileName The filename to open. * * @return Pointer to image handler or null if nothing opened. */ // virtual ossimImageHandler* openFromExtension( // const ossimFilename& fileName) const; ossimImageHandlerFactory(){} ossimImageHandlerFactory(const ossimImageHandlerFactory&){} void operator = (const ossimImageHandlerFactory&){} static ossimImageHandlerFactory* theInstance; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageHandlerFactoryBase.h000066400000000000000000000103301352751253100257670ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts // //******************************************************************* // $Id$ #ifndef ossimImageHandlerFactoryBase_HEADER #define ossimImageHandlerFactoryBase_HEADER 1 #include #include #include #include #include #include #include #include #include #include class ossimFilename; class ossimKeywordlist; class OSSIM_DLL ossimImageHandlerFactoryBase : public ossimObjectFactory { public: template class UniqueList { public: void push_back(const T& value) { if(std::find(theList.begin(),theList.end(), value) == theList.end()) { theList.push_back(value); } } const std::vector& getList()const { return theList; } ossim_uint32 size()const { return theList.size(); } const T& operator[](ossim_uint32 idx)const { return theList[idx]; } T& operator[](ossim_uint32 idx) { return theList[idx]; } protected: std::vector theList; }; typedef UniqueList UniqueStringList; typedef std::vector > ImageHandlerList; virtual ossimImageHandler* open(const ossimFilename& fileName, bool openOverview=true)const = 0; virtual ossimImageHandler* open(const ossimKeywordlist& kwl, const char* prefix=0)const = 0; #if 0 /** * @brief Open method. * * This open takes a stream, position and a flag. * * @param str Open stream to image. * * @param restartPosition Typically 0, this is the stream offset to the * front of the image. * * @param youOwnIt If true the opener takes ownership of the stream * pointer and will destroy on close. * * @return This implementation returns an ossimRefPtr with a null pointer. */ virtual ossimRefPtr open( ossim::istream* str, std::streamoff restartPosition, bool youOwnIt ) const; #endif /** * @brief Open method that takes a stream. * * This implementation returns an ossimRefPtr with a null pointer. * * @param str Open stream to image. * @param connectionString * @param openOverview If true attempt to open overview file. * @return ossimImageHandler */ virtual ossimRefPtr open( std::shared_ptr& str, const std::string& connectionString, bool openOverview=true ) const; virtual ossimRefPtr open(std::shared_ptr state)const; /** * @brief Open overview that takes a file name. * * This default implementation returns a null ref pointer. * Derived factories that have overview readers should override. * * @param file File to open. * * @return This default implementation returns a null ref pointer. */ virtual ossimRefPtr openOverview( const ossimFilename& file ) const; /** * @brief Open method that takes a stream. * * This implementation returns an ossimRefPtr with a null pointer. * * @param str Open stream to image. * @param connectionString * @return ossimImageHandler */ virtual ossimRefPtr openOverview( std::shared_ptr& str, const ossimString& connectionString ) const; virtual void getImageHandlersBySuffix(ImageHandlerList& result, const ossimString& ext)const; virtual void getImageHandlersByMimeType(ImageHandlerList& result, const ossimString& mimeType)const; virtual void getSupportedExtensions(ossimImageHandlerFactoryBase::UniqueStringList& extensionList)const=0; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageHandlerRegistry.h000066400000000000000000000156271352751253100254130ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Contains class definition for the class // ImageHandlerRegistry. // //******************************************************************* // $Id: ossimImageHandlerRegistry.h 22636 2014-02-23 17:55:50Z dburken $ #ifndef ossimImageHandlerRegistry_HEADER #define ossimImageHandlerRegistry_HEADER 1 #include #include #include #include #include #include #include #include #include class ossimImageHandler; class ossimFilename; class ossimKeywordlist; /** * ossimImageHandlerRegistry supports the new state cache. During initialization the properties are * read from the global preferences. The keywords are: * * ossim.imaging.handler.registry.state_cache.enabled: true or false * ossim.imaging.handler.registry.state_cache.min_size: min number of items * ossim.imaging.handler.registry.state_cache.max_size: max number of items * * On open if the state cache is enabled it will determine if a state exists when a file is passed * in to be open and if a state exists it will try to open the handler based on the state. */ class OSSIMDLLEXPORT ossimImageHandlerRegistry : public ossimObjectFactory, public ossimFactoryListInterface { public: virtual ~ossimImageHandlerRegistry(); static ossimImageHandlerRegistry* instance(); std::shared_ptr getState(const ossimString& connectionString, ossim_uint32 entry)const; std::shared_ptr getState(const ossimString& id)const; ossimRefPtr openConnection( const ossimString& connectionString, bool openOverview=true )const; /** * @brief open that takes a filename. * @param fileName File to open. * @param trySuffixFirst If true calls code to try to open by suffix first, * then goes through the list of available handlers. default=true. * @param openOverview If true image handler will attempt to open overview. * default = true * @return Pointer to image handler or null if cannot open. */ virtual ossimImageHandler* open(const ossimFilename& fileName, bool trySuffixFirst=true, bool openOverview=true)const; /** * Given a keyword list return a pointer to an ImageHandler. Returns * null if a valid handler cannot be found. */ virtual ossimImageHandler* open(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual ossimRefPtr open(std::shared_ptr state)const; /** * @brief Open method that takes a stream. * @param str Open stream to image. * @param connectionString * @param openOverview If true attempt to open overview file. * @return ossimImageHandler */ virtual ossimRefPtr open( std::shared_ptr& str, const std::string& connectionString, bool openOverview ) const; #if 0 /** * @brief Open method. * * This open takes a stream, position and a flag. * * @param str Open stream to image. * * @param restartPosition Typically 0, this is the stream offset to the * front of the image. * * @param youOwnIt If true the opener takes ownership of the stream * pointer and will destroy on close. * * @return This implementation returns an ossimRefPtr with a null pointer. */ virtual ossimRefPtr open( ossim::istream* str, std::streamoff restartPosition, bool youOwnIt ) const; #endif /** * @brief Open overview that takes a file name. * * This will only check readers that can be overview handlers. * * @param file File to open. * * @return ossimRefPtr to image handler on success or null on failure. */ virtual ossimRefPtr openOverview( const ossimFilename& file ) const; /*! * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName) const; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /** * openBySuffix will call the mthod getImageHandlersBySuffix and go through * each handler to try and open the file. This should be a faster open * for we do not have to do a magic number compare on all prior files and * keep opening and closing files. * @param openOverview If true image handler will attempt to open overview. * default = true */ virtual ossimRefPtr openBySuffix(const ossimFilename& file, bool openOverview=true)const; /** * * Will add to the result list any handler that supports the passed in extensions * */ virtual void getImageHandlersBySuffix(ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& ext)const; /** * * Will add to the result list and handler that supports the passed in mime type * */ virtual void getImageHandlersByMimeType(ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& mimeType)const; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList( std::vector& typeList ) const; virtual void getSupportedExtensions( ossimImageHandlerFactoryBase::UniqueStringList& extensionList)const; /** * @brief Prints list of readers and properties. * @param out Stream to print to. * @return std::ostream& */ std::ostream& printReaderProps(std::ostream& out) const; protected: ossimImageHandlerRegistry(); ossimImageHandlerRegistry(const ossimImageHandlerRegistry& rhs); const ossimImageHandlerRegistry& operator=(const ossimImageHandlerRegistry& rhs); void initializeStateCache()const; void addToStateCache(ossimImageHandler* handler)const; mutable std::shared_ptr > m_stateCache; //static ossimImageHandlerRegistry* theInstance; TYPE_DATA }; extern "C" { OSSIM_DLL void* ossimImageHandlerRegistryGetInstance(); } #endif /* #ifndef ossimImageHandlerRegistry_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageHistogramSource.h000066400000000000000000000072621352751253100254170ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageHistogramSource.h 22737 2014-04-16 18:53:57Z gpotts $ #ifndef ossimImageHistogramSource_HEADER #define ossimImageHistogramSource_HEADER #include #include #include #include #include #include /*! * This source expects as input an ossimImageSource. * it will slice up the requested region into tiles and compute * the histogram of the passed in rectangle. */ class OSSIMDLLEXPORT ossimImageHistogramSource : public ossimHistogramSource, public ossimConnectableObjectListener, public ossimProcessInterface { public: ossimImageHistogramSource(ossimObject* owner = 0); virtual ossimObject* getObject(); virtual const ossimObject* getObject()const; void setAreaOfInterest(const ossimIrect& rect); ossimIrect getAreaOfInterest()const; void getAreaOfInterest(ossimIrect& rect)const; virtual ossim_uint32 getMaxNumberOfRLevels()const; virtual void setMaxNumberOfRLevels(ossim_uint32 number); /*! * The first argument is the region of interest that you wish to * use for the histogram. If the region is different than * what it has already computed before then the histogram is considered * dirty and will be re-computed. The returned object is a * multi-reslevel histogram */ virtual ossimRefPtr getHistogram(const ossimIrect& rect); virtual ossimRefPtr getHistogram(); virtual bool execute(); virtual bool canConnectMyInputTo(ossim_int32 myInputIndex, const ossimConnectableObject* object)const; void setNumberOfBinsOverride(ossim_int32 numberOfBinsOverride); void setMinValueOverride(ossim_float32 minValueOverride); void setMaxValueOverride(ossim_float32 maxValueOverride); void setNumberOfTiles(ossim_uint32 numberOfTiles); ossimHistogramMode getComputationMode()const; void setComputationMode(ossimHistogramMode mode); virtual void propertyEvent(ossimPropertyEvent& event); virtual void connectInputEvent(ossimConnectionEvent& event); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: virtual ~ossimImageHistogramSource(); bool getBinInformation(ossim_uint32& numberOfBins, ossim_float32& minValue, ossim_float32& maxValue, ossim_float32& nullValue, ossim_uint32 band)const; virtual void computeNormalModeHistogram(); virtual void computeFastModeHistogram(); /*! * Initialized to ossimNAN'S */ ossimIrect theAreaOfInterest; bool theHistogramRecomputeFlag; /*! * Will default to 1. This means it will use up to max * number of res levels for the histogram. */ ossim_uint32 theMaxNumberOfResLevels; ossim_float64 theMinValueOverride; ossim_float64 theMaxValueOverride; ossim_int32 theNumberOfBinsOverride; ossimHistogramMode theComputationMode; // ossim_uint32 theNumberOfTilesToUseInFastMode; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageMetaDataWriterFactory.h000066400000000000000000000053621352751253100265050ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2003 Storage Area Networks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Kenneth Melero (kmelero@sanz.com) // //******************************************************************* // $Id: ossimImageMetaDataWriterFactory.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimImageMetaDataWriterFactory_HEADER #define ossimImageMetaDataWriterFactory_HEADER #include #include class ossimMetadataFileWriter; class OSSIMDLLEXPORT ossimImageMetaDataWriterFactory: public ossimImageMetaDataWriterFactoryBase { public: ~ossimImageMetaDataWriterFactory(); static ossimImageMetaDataWriterFactory* instance(); virtual ossimObject* createObject(const ossimString& typeName)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /** * Creates a writer from either a class name or a string representing the * meta data type like "tiff_world_file". * * @return ossimRefPtr * * @note Return can have a null pointer if type is not found in a factory so * the caller should always check the pointer like: * ossimRefPtr mw = * ossimImageMetaDataWriterRegistry::instance("ossim_readme"); * if (!mw.valid()) * { * // not in factory * } */ virtual ossimRefPtr createWriter( const ossimString& type)const; /** * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const; /** * Satisfies pure virtual from ossimImageMetaDataWriterFactoryBase. * * Appends the meta data writers types from each of the supported meta * data writers in this factor to the "metadatatypeList". * * This is the actual metadata type name like: * ossim_geometry * envi_header * tiff_world_file * jpeg_world_file * * @param metadatatypeList stl::vector List to append to. */ virtual void getMetadatatypeList( std::vector& metadatatypeList) const; protected: static ossimImageMetaDataWriterFactory* theInstance; ossimImageMetaDataWriterFactory(); ossimImageMetaDataWriterFactory(const ossimImageMetaDataWriterFactory& rhs); const ossimImageMetaDataWriterFactory& operator =( const ossimImageMetaDataWriterFactory& rhs); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageMetaDataWriterFactoryBase.h000066400000000000000000000042321352751253100272730ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: MIT // // See LICENSE.txt file in the top level directory for more details. //---------------------------------------------------------------------------- // $Id: ossimImageMetaDataWriterFactoryBase.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimImageMetaDataWriterFactoryBase_HEADER #define ossimImageMetaDataWriterFactoryBase_HEADER #include #include class ossimMetadataFileWriter; class ossimImageMetaDataWriterFactoryBase : public ossimObjectFactory { public: /** * Pure virtual. All ossimImageMetaDataWriterFactories must implement. * * Creates a writer from either a class name or a string representing the * meta data type like "tiff_world_file". * * @return ossimRefPtr * * @note Return can have a null pointer if type is not found in a factory so * the caller should always check the pointer like: * ossimRefPtr mw = * ossimImageMetaDataWriterRegistry::instance("ossim_readme"); * if (!mw.valid()) * { * // not in factory * } */ virtual ossimRefPtr createWriter( const ossimString& type)const=0; /** * Pure virtual. All ossimImageMetaDataWriterFactories must implement. * * Appends the meta data writers types to the "metadatatypeList". * * This is the actual metadata type name like: * ossim_geometry * envi_header * tiff_world_file * jpeg_world_file * * @param metadatatypeList stl::vector List to append to. * * @note All writers should append to the list, not, clear it and then add * their types. */ virtual void getMetadatatypeList( std::vector& metadatatypeList) const=0; protected: ossimImageMetaDataWriterFactoryBase(); ossimImageMetaDataWriterFactoryBase( const ossimImageMetaDataWriterFactoryBase&); const ossimImageMetaDataWriterFactoryBase& operator=( const ossimImageMetaDataWriterFactoryBase&); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageMetaDataWriterRegistry.h000066400000000000000000000062451352751253100267070ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: MIT // // See LICENSE.txt file in the top level directory for more details. //---------------------------------------------------------------------------- // $Id: ossimImageMetaDataWriterRegistry.h 13508 2008-08-27 15:51:38Z gpotts $ #ifndef ossimImageMetaDataWriterRegistry_HEADER #define ossimImageMetaDataWriterRegistry_HEADER #include #include class ossimMetadataFileWriter; class OSSIMDLLEXPORT ossimImageMetaDataWriterRegistry : public ossimImageMetaDataWriterFactoryBase { public: ~ossimImageMetaDataWriterRegistry(); static ossimImageMetaDataWriterRegistry* instance(); void registerFactory(ossimImageMetaDataWriterFactoryBase* factory); void unregisterFactory(ossimImageMetaDataWriterFactoryBase* factory); bool findFactory(ossimImageMetaDataWriterFactoryBase* factory)const; /** * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const; /** * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /** * Creates a writer from either a class name or a string representing the * meta data type like "tiff_world_file". * * @return ossimRefPtr * * @note Return can have a null pointer if type is not found in a factory so * the caller should always check the pointer like: * ossimRefPtr mw = * ossimImageMetaDataWriterRegistry::instance("ossim_readme"); * if (!mw.valid()) * { * // not in factory * } */ virtual ossimRefPtr createWriter( const ossimString& type)const; /** * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const; /** * Initializes list with meta data types from all registered * metadata factories. * * This is the actual image type name like: * ossim_geometry * envi_header * tiff_world_file * jpeg_world_file * * @param metadatatypeList stl::vector list to append to. * * @note Since this is the master registry for all meta data factories * this method starts by clearing the metadatatypeList. */ virtual void getMetadatatypeList( std::vector& metadatatypeList)const; protected: ossimImageMetaDataWriterRegistry(); ossimImageMetaDataWriterRegistry( const ossimImageMetaDataWriterRegistry& rhs); const ossimImageMetaDataWriterRegistry& operator=( const ossimImageMetaDataWriterRegistry &rhs); // static ossimImageMetaDataWriterRegistry* theInstance; std::vector theFactoryList; }; extern "C" { OSSIMDLLEXPORT void* ossimImageMetaDataWriterRegistryGetInstance(); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageModel.h000066400000000000000000000115701352751253100233360ustar00rootroot00000000000000//----------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class declaration of ossimImageModel. // //----------------------------------------------------------------------------- // $Id$ #ifndef ossimImageModel_HEADER #define ossimImageModel_HEADER 1 #include #include #include #include #include class ossimDrect; class ossimImageHandler; /** * @brief Class to handle transforming image points, rectangles, and offsets * from one reduced resolution data set (rrds) level to another. * * Derived from ossimObject only so users can pass via the * ossimViewInterface::setView method. */ class OSSIM_DLL ossimImageModel : public ossimObject { public: /** @brief default constructor */ ossimImageModel(); /** * @brief Method to initialize class from an image handler. * * @param ih Image handler. */ virtual void initialize(const ossimImageHandler& ih); /** * @brief Get r0 point from rn point. * * @param rrds Source (rnPt) reduced resolution data set. * * @param rnPt The image point to tranform. * * @param r0Pt the Point to initialize. * * @note Throws ossimException on out of range rrds. */ void rnToR0(ossim_uint32 rrds, const ossimDpt& rnPt, ossimDpt& r0Pt) const; /** * @brief Get r0 point from rn point. * * This requires calling setTargetRrds(ossim_uint32 rrds) to the level * for rnPt. * * @param rnPt The image point to tranform. * * @param r0Pt the Point to initialize. * * @note Throws ossimException on out of range rrds. * * @see setTargetRrds */ void rnToR0(const ossimDpt& rnPt, ossimDpt& r0Pt) const; /** * @brief Get rn point from r0 point. * * @param rrds Target (rnPt) reduced resolution data set. * * @param r0Pt The image point to tranform. * * @param rnPt the Point to initialize. * * @note Throws ossimException on out of range rrds. */ void r0ToRn(ossim_uint32 rrds, const ossimDpt& r0Pt, ossimDpt& rnPt) const; /** * @brief Get rn point from r0 point. * * This requires calling setTargetRrds(ossim_uint32 rrds) to the level * for rnPt. * * @param r0Pt The image point to tranform. * * @param rnPt the Point to initialize. * * @note Throws ossimException on out of range rrds. * * @see setTargetRrds */ void r0ToRn(const ossimDpt& r0Pt, ossimDpt& rnPt) const; /** * @brief Get the sub image offset for a given resolution level. * * @param rrds The reduced resolution data set. * * @param offset the Point to initialize. * * @note Throws ossimException on out of range rrds. */ void getSubImageOffset(ossim_uint32 rrds, ossimDpt& offset) const; /** * @brief Gets the zero-based image rectangle for a given reduced resolution * data set. * * @param rrds The reduced resolution data set. * * @param rect Initialized with image rectangle for rrds. * * @note Throws ossimException on out of range rrds. */ void getImageRectangle(ossim_uint32 rrds, ossimDrect& rect) const; /** * @brief Gets the model-based image rectangle for a given reduced * resolution data set. * * If this image is a sub image the offset is applied. So if the image * has a sub image offset of (1024, 1024), and has 1024 lines and 1024 * samples the rectangle for r0 will be: (1024, 1024) (2047, 2047) * * @param rrds The reduced resolution data set. * * @param rect Initialized with image rectangle for rrds. * * @note Throws ossimException on out of range rrds. */ void getBoundingRectangle(ossim_uint32 rrds, ossimDrect& rect) const; /** * @return This returns the total number of decimation levels. */ ossim_uint32 getNumberOfDecimationLevels()const; /** * @brief Set theTargetRrds data member. * * This is used by methods rnToR0 and r0ToRn that do not take a rrds * argument. * * @param rrds Target reduced resolution data set. */ void setTargetRrds(ossim_uint32 rrds); /** * @return The target reduced resolution data set. */ ossim_uint32 getTargetRrds() const; protected: /** @brief virtual destructor */ virtual ~ossimImageModel(); /** Offset from the full image. */ ossimDpt theSubImageOffset; /** Decimation factors for each rrds level. */ std::vector theDecimationFactors; ossim_uint32 theLines; ossim_uint32 theSamples; ossim_uint32 theTargetRrds; TYPE_DATA }; #endif /* #ifndef ossimImageModel_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageMosaic.h000066400000000000000000000042261352751253100235110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageMosaic.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimImageMosaic_HEADER #define ossimImageMosaic_HEADER #include #include /** * An image mosaic is a simple combiner that will * just do a simple mosaic. It just checks NULL pix values until it finds a * pixel that is not empty and copies it out to the output. The list will * have same size tiles and have the same number of bands. */ class OSSIMDLLEXPORT ossimImageMosaic : public ossimImageCombiner { public: ossimImageMosaic(); ossimImageMosaic(ossimConnectableObject::ConnectableObjectList& inputSources); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual void initialize(); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimImageMosaic(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); ossimRefPtr theTile; template ossimRefPtr combine( T, // dummy template variable not used const ossimIrect& tileRect, ossim_uint32 resLevel=0); template ossimRefPtr combineNorm( T, // dummy template variable not used const ossimIrect& tileRect, ossim_uint32 resLevel=0); TYPE_DATA }; #endif /* #ifndef ossimImageMosaic_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageReconstructionFilterFactory.h000066400000000000000000000024141352751253100300120ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimImageReconstructionFilterFactory.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimImageReconstructionFilterFactory_HEADER #define ossimImageReconstructionFilterFactory_HEADER #include class ossimImageReconstructionFilterFactory : public ossimImageSourceFactoryBase { public: virtual ~ossimImageReconstructionFilterFactory(); static ossimImageReconstructionFilterFactory* instance(); virtual ossimObject* createObject(const ossimString& name)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual void getTypeNameList(std::vector& typeList)const; protected: ossimImageReconstructionFilterFactory(); // hide ossimImageReconstructionFilterFactory(const ossimImageReconstructionFilterFactory&){}//hide void operator = (ossimImageReconstructionFilterFactory&){}// hide static ossimImageReconstructionFilterFactory* theInstance; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageReconstructionFilterRegistry.h000066400000000000000000000030001352751253100302030ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageReconstructionFilterRegistry.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimImageReconstructionFilterRegistry_HEADER #define ossimImageReconstructionFilterRegistry_HEADER #include class ossimImageReconstructionFilterRegistry : public ossimImageSourceFactoryBase { public: static ossimImageReconstructionFilterRegistry* instance(); virtual ossimObject* createObject(const ossimString& name)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual void getTypeNameList(std::vector& typeList)const; void registerFactory(ossimImageSourceFactoryBase* factory); void unregisterFactory(ossimImageSourceFactoryBase* factory); bool findFactory(ossimImageSourceFactoryBase* factory)const; protected: virtual ~ossimImageReconstructionFilterRegistry(); ossimImageReconstructionFilterRegistry(); // hide ossimImageReconstructionFilterRegistry(const ossimImageReconstructionFilterRegistry&){}//hide void operator = (ossimImageReconstructionFilterRegistry&){}// hide static ossimImageReconstructionFilterRegistry* theInstance; std::vector theFactoryList; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageRenderer.h000066400000000000000000000373031352751253100240460ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2001 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimImageRenderer.h 23548 2015-09-28 21:01:36Z dburken $ #ifndef ossimImageRenderer_HEADER #define ossimImageRenderer_HEADER #include #include #include #include #include #include class ossimImageData; class ossimDiscreteConvolutionKernel; class ossimFilterResampler; class OSSIMDLLEXPORT ossimImageRenderer : public ossimImageSourceFilter, public ossimViewInterface { public: ossimImageRenderer(); ossimImageRenderer(ossimImageSource* inputSource, ossimImageViewTransform* imageViewTrans = NULL); virtual ~ossimImageRenderer(); virtual ossimString getLongName() const; virtual ossimString getShortName() const; /** * the resampler will need the tile request to come from the view. * It will use the view to transoform this to world and then use the * image's projection to get it into final line sample. This way * the resampler can fill a tile width by height on the screen * correctly. */ virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual void initialize(); /** * m_Resampler will adjust the rect to whatever the view is. So it * will project the full image rect onto the view and return the upright * bounding rect. */ virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; /** * @brief Gets the bounding rectangle of the source. * * This is the output view bounds. * * @param rect Initialized with bounding rectangle by this. * @param resLevel Reduced resolution level if applicable. */ virtual void getBoundingRect(ossimIrect& rect, ossim_uint32 resLevel=0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); void setImageViewTransform(ossimImageViewTransform* transform); ossimImageViewTransform* getImageViewTransform() { return m_ImageViewTransform.get(); } //! Returns instance to the input image geometry. This may be a NULL pointer. //! This is only valid if the IVT is a projection type IVT (IVPT) virtual ossimRefPtr getImageGeometry(); virtual bool setView(ossimObject* baseObject); ossimFilterResampler* getResampler() { return m_Resampler; } virtual ossimObject* getView(); virtual const ossimObject* getView()const; virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result)const; virtual void getDecimationFactors(std::vector& decimations)const; virtual ossim_uint32 getNumberOfDecimationLevels()const; virtual void setAutoUpdateInputTransformFlag(bool flag){ m_AutoUpdateInputTransform = flag; } /** * ordering specifies how the vertices should be arranged. * valid image vertices is basically the tightly fit convex hull * of the image. Usually an image has NULL values and are * internally not upright rectangular. This can cause * problems some spatial filters. * * We need to make sure that the resampler overrides this method. * it needs to transform the vertices to the view's side. */ virtual void getValidImageVertices(std::vector& validVertices, ossimVertexOrdering ordering=OSSIM_CLOCKWISE_ORDER, ossim_uint32 resLevel=0)const; void setMaxLevelsToCompute(ossim_uint32 maxLevels); ossim_uint32 getMaxLevelsToCompute()const; void connectInputEvent(ossimConnectionEvent& event); void disconnectInputEvent(ossimConnectionEvent& event); void propertyEvent(ossimPropertyEvent& event); virtual void refreshEvent(ossimRefreshEvent& event); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * @brief Enables source. * * Overrides ossimSource::enableSource so bounding rects are recomputed on * state change. */ virtual void enableSource(); /** * @brief Disables source. * * Overrides ossimSource::disableSource so bounding rects are recomputed on * state change. */ virtual void disableSource(); /** * @brief Sets the enable flag. * * @param flag True to enable, false to disable. * * Overrides ossimSource::setEnableFlag so bounding rects are recomputed on * state change. */ virtual void setEnableFlag(bool flag); protected: private: class ossimRendererSubRectInfo { enum SplitFlag{ SPLIT_NONE = 0, UPPER_LEFT_SPLIT_FLAG = 1, UPPER_RIGHT_SPLIT_FLAG = 2, LOWER_RIGHT_SPLIT_FLAG = 4, LOWER_LEFT_SPLIT_FLAG = 8, SPLIT_ALL = UPPER_LEFT_SPLIT_FLAG|UPPER_RIGHT_SPLIT_FLAG|LOWER_RIGHT_SPLIT_FLAG|LOWER_LEFT_SPLIT_FLAG }; public: friend std::ostream& operator <<(std::ostream& out, const ossimRendererSubRectInfo& rhs) { return out << "vul: " << rhs.m_Vul << std::endl << "vur: " << rhs.m_Vur << std::endl << "vlr: " << rhs.m_Vlr << std::endl << "vll: " << rhs.m_Vll << std::endl << "iul: " << rhs.m_Iul << std::endl << "iur: " << rhs.m_Iur << std::endl << "ilr: " << rhs.m_Ilr << std::endl << "ill: " << rhs.m_Ill << std::endl << "scale: " << rhs.m_ViewToImageScale << std::endl; } ossimRendererSubRectInfo(ossimImageViewTransform* transform=0); ossimRendererSubRectInfo(ossimImageViewTransform* transform, const ossimDpt& vul, const ossimDpt& vur, const ossimDpt& vlr, const ossimDpt& vll); bool imageHasNans()const; bool imageIsNan()const; bool viewHasNans()const; bool viewIsNan()const; void splitView(std::vector& result)const; //void splitView(ossimRendererSubRectInfo& ulRect, // ossimRendererSubRectInfo& urRect, // ossimRendererSubRectInfo& lrRect, // ossimRendererSubRectInfo& llRect)const; void transformViewToImage(); void transformImageToView(); bool tooBig()const; void roundToInteger(); void stretchImageOut(bool enableRound=false); ossimDrect getViewRect()const; ossimDrect getImageRect()const; void roundImageToInteger(); void roundViewToInteger(); bool isViewEqual(const ossimRendererSubRectInfo& infoRect)const; bool isViewEqual(const ossimDrect& viewRect)const; ossimDpt computeViewToImageScale(const ossimDpt& viewPt, const ossimDpt& delta=ossimDpt(1.0,1.0))const; ossimDpt getAbsValueViewToImageScales()const; ossimDpt getAbsValueImageToViewScales()const; ossimDpt computeRoundTripErrorViewPt(const ossimDpt& dpt)const; bool isViewAPoint()const; bool isIdentity()const; //bool canBilinearInterpolate(double error) const; bool canBilinearInterpolate() const; ossimDpt getParametricCenter(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll)const; void getViewMids(ossimDpt& upperMid, ossimDpt& rightMid, ossimDpt& bottomMid, ossimDpt& leftMid, ossimDpt& center)const; void getImageMids(ossimDpt& upperMid, ossimDpt& rightMid, ossimDpt& bottomMid, ossimDpt& leftMid, ossimDpt& center)const; ossim_uint16 getSplitFlags()const; ossimDpt m_Iul; ossimDpt m_Iur; ossimDpt m_Ilr; ossimDpt m_Ill; ossimIpt m_Vul; ossimIpt m_Vur; ossimIpt m_Vlr; ossimIpt m_Vll; ossimDpt m_ViewToImageScale; ossimDpt m_ImageToViewScale; ossimDpt m_VulScale; ossimDpt m_VurScale; ossimDpt m_VlrScale; ossimDpt m_VllScale; mutable ossimRefPtr m_transform; mutable const ossimPolyArea2d* m_viewBounds; private: void splitHorizontal(std::vector& result)const; void splitVertical(std::vector& result)const; void splitAll(std::vector& result)const; }; void recursiveResample(ossimRefPtr outputData, const ossimRendererSubRectInfo& rectInfo, ossim_uint32 level); void fillTile(ossimRefPtr outputData, const ossimRendererSubRectInfo& rectInfo); ossimIrect getBoundingImageRect()const; //! this is called on a property event and on input connection changes. void checkIVT(); /** * @brief Initializes m_inputR0Rect and m_viewBoundingRect and sets * m_rectsDirty appropriately. */ void initializeBoundingRects(); ossimRefPtr getTileAtResLevel(const ossimIrect& boundingRect, ossim_uint32 resLevel); template void resampleTileToDecimation(T dummyVariable, ossimRefPtr result, ossimRefPtr tile, ossim_uint32 multiplier); long computeClosestResLevel(const std::vector& decimationFactors, double scale)const; void stretchQuadOut(const ossimDpt& amount, ossimDpt& ul, ossimDpt& ur, ossimDpt& lr, ossimDpt& ll); /** * Called on first getTile, will initialize all data needed. */ void allocate(); /** * Deletes all allocated tiles. */ void deallocate(); ossimFilterResampler* m_Resampler; ossimRefPtr m_BlankTile; ossimRefPtr m_Tile; ossimRefPtr m_TemporaryBuffer; /** * This is going to allow us to chain multiple * renderers together. So if we have one * renderer doing a scale and they pass an r-level * down and we have another renderer within the * chain we will be starting at a different r-level. * The default will be r-level 0 request coming * from the right. */ ossim_uint32 m_StartingResLevel; ossimRefPtr m_ImageViewTransform; ossimIrect m_inputR0Rect; ossimIrect m_viewRect; bool m_rectsDirty; ossim_uint32 m_MaxRecursionLevel; bool m_AutoUpdateInputTransform; ossim_uint32 m_MaxLevelsToCompute; ossimPolyArea2d m_viewArea; bool m_crossesDateline; double m_averageViewToImageScale; double m_averageViewToImageRLevelScale; static double m_interpErrorThreshold; TYPE_DATA }; inline ossimImageRenderer::ossimRendererSubRectInfo::ossimRendererSubRectInfo(ossimImageViewTransform* transform) :m_transform(transform), m_viewBounds(0) { m_Vul.makeNan(); m_Vur.makeNan(); m_Vlr.makeNan(); m_Vll.makeNan(); m_Iul.makeNan(); m_Iur.makeNan(); m_Ilr.makeNan(); m_Ill.makeNan(); m_ViewToImageScale.makeNan(); m_ImageToViewScale.makeNan(); } inline ossimImageRenderer::ossimRendererSubRectInfo::ossimRendererSubRectInfo(ossimImageViewTransform* transform, const ossimDpt& vul, const ossimDpt& vur, const ossimDpt& vlr, const ossimDpt& vll) :m_Vul(vul), m_Vur(vur), m_Vlr(vlr), m_Vll(vll), m_transform(transform), m_viewBounds(0) { m_Iul.makeNan(); m_Iur.makeNan(); m_Ilr.makeNan(); m_Ill.makeNan(); m_ViewToImageScale.makeNan(); m_ImageToViewScale.makeNan(); } inline bool ossimImageRenderer::ossimRendererSubRectInfo::imageHasNans()const { return ( m_Iul.hasNans()|| m_Iur.hasNans()|| m_Ilr.hasNans()|| m_Ill.hasNans()); } inline bool ossimImageRenderer::ossimRendererSubRectInfo::imageIsNan()const { return ( m_Iul.hasNans()&& m_Iur.hasNans()&& m_Ilr.hasNans()&& m_Ill.hasNans()); } inline bool ossimImageRenderer::ossimRendererSubRectInfo::viewHasNans()const { return ( m_Vul.hasNans()|| m_Vur.hasNans()|| m_Vlr.hasNans()|| m_Vll.hasNans()); } inline bool ossimImageRenderer::ossimRendererSubRectInfo::viewIsNan()const { return ( m_Vul.hasNans()&& m_Vur.hasNans()&& m_Vlr.hasNans()&& m_Vll.hasNans()); } inline void ossimImageRenderer::ossimRendererSubRectInfo::roundToInteger() { m_Iul = ossimIpt(m_Iul); m_Iur = ossimIpt(m_Iur); m_Ilr = ossimIpt(m_Ilr); m_Ill = ossimIpt(m_Ill); m_Vul = ossimIpt(m_Vul); m_Vur = ossimIpt(m_Vur); m_Vlr = ossimIpt(m_Vlr); m_Vll = ossimIpt(m_Vll); } inline ossimDrect ossimImageRenderer::ossimRendererSubRectInfo::getViewRect()const { return ossimDrect(m_Vul, m_Vur, m_Vlr, m_Vll); } inline ossimDrect ossimImageRenderer::ossimRendererSubRectInfo::getImageRect()const { return ossimDrect(m_Iul, m_Iur, m_Ilr, m_Ill); } inline void ossimImageRenderer::ossimRendererSubRectInfo::roundImageToInteger() { m_Iul = ossimIpt(m_Iul); m_Iur = ossimIpt(m_Iur); m_Ilr = ossimIpt(m_Ilr); m_Ill = ossimIpt(m_Ill); } inline void ossimImageRenderer::ossimRendererSubRectInfo::roundViewToInteger() { m_Vul = ossimIpt(m_Vul); m_Vur = ossimIpt(m_Vur); m_Vlr = ossimIpt(m_Vlr); m_Vll = ossimIpt(m_Vll); } inline bool ossimImageRenderer::ossimRendererSubRectInfo::isViewEqual(const ossimRendererSubRectInfo& infoRect)const { return ( (m_Vul == infoRect.m_Vul)&& (m_Vur == infoRect.m_Vur)&& (m_Vlr == infoRect.m_Vlr)&& (m_Vll == infoRect.m_Vll)); } inline bool ossimImageRenderer::ossimRendererSubRectInfo::isViewEqual(const ossimDrect& viewRect)const { return ( (m_Vul == viewRect.ul())&& (m_Vur == viewRect.ur())&& (m_Vlr == viewRect.lr())&& (m_Vll == viewRect.ll())); } inline ossimDpt ossimImageRenderer::ossimRendererSubRectInfo::getAbsValueViewToImageScales()const { if(m_ViewToImageScale.hasNans()) { return m_ImageToViewScale; } return ossimDpt(fabs(m_ViewToImageScale.x), fabs(m_ViewToImageScale.y)); } inline ossimDpt ossimImageRenderer::ossimRendererSubRectInfo::getAbsValueImageToViewScales()const { if(m_ImageToViewScale.hasNans()) { return m_ImageToViewScale; } return ossimDpt(fabs(m_ImageToViewScale.x), fabs(m_ImageToViewScale.y)); } inline bool ossimImageRenderer::ossimRendererSubRectInfo::isViewAPoint()const { return ((m_Vul == m_Vur)&& (m_Vul == m_Vlr)&& (m_Vul == m_Vll)); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageSharpenFilter.h000066400000000000000000000053301352751253100250410ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageSharpenFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimImageSharpenFilter_HEADER #define ossimImageSharpenFilter_HEADER #include #include class OSSIMDLLEXPORT ossimImageSharpenFilter : public ossimImageSourceFilter { public: ossimImageSharpenFilter(ossimObject* owner=NULL); virtual ossimString getShortName()const; virtual ossimString getLongName()const; /** * @param percent Sets the percentage of sharpen. A value of 0 is no sharpen and a * value of 1 is fully sharpened. The range is between and including * 0 and 1 */ void setSharpenPercent(ossim_float64 percent); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); virtual void connectInputEvent(ossimConnectionEvent &event); virtual void disconnectInputEvent(ossimConnectionEvent &event); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: virtual ~ossimImageSharpenFilter(); template void sharpenLut(T, const ossimRefPtr &inputData, ossimRefPtr &outputData); template void sharpenLutRemap(T, const ossimRefPtr &inputData, ossimRefPtr &outputData); void buildConvolutionLuts(); void allocate(); std::vector m_posLut; std::vector m_posNegLut; ossim_float64 m_sharpenPercent; ossimRefPtr m_tile; /** * This is a flag to indicate whether or not * to remap values. This means we do not have a * way to directly map values to a lut and so * need to get remapped. to a sampled LUT. */ bool m_remapValue; TYPE_DATA }; #endif /* #ifndef ossimImageSharpenFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageSource.h000066400000000000000000000204641352751253100235400ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageSource.h 23100 2015-01-26 19:43:08Z okramer $ #ifndef ossimImageSource_HEADER #define ossimImageSource_HEADER 1 #include #include #include #include #include #include class ossimDpt; class OSSIMDLLEXPORT ossimImageSource : public ossimSource { public: ossimImageSource(ossimObject* owner = 0); ossimImageSource(ossimObject* owner, ossim_uint32 inputListSize, ossim_uint32 outputListSize, bool inputListIsFixedFlag=true, bool outputListIsFixedFlag=true); virtual ~ossimImageSource(); /** * @return from origin out to tile_width-1, and tile_height-1. */ virtual ossimRefPtr getTile(const ossimIpt& origin, ossim_uint32 resLevel=0); /** * @return the requested region of interest */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. This is the default implementation that is not thread-friendly as it uses the * object's tile then simply copies its buffer to the provided tile. Eventually, all image * sources should override this method. * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or whatever. * * @note Derived classes should override this method to most efficiently stuff result. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * For RTTI support. overrides ossimImageSource * get object to return the correct casted base pointer * for RTTI casting */ virtual ossimObject* getObject() { return this; } /** * For RTTI support. overrides ossimImageSource * get object to return the correct casted base pointer * for RTTI casting */ virtual const ossimObject* getObject() const { return this; } /** * Will return the decimation factor for the given resolution * level. the decimation is the scale from Resolution 0 or full * res. Usually this is a power of 2 decimation where * the decimation result is 1.0/2^resoltion. */ virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result)const; /** * Will return an array of all decimations for each resolution level. */ virtual void getDecimationFactors(std::vector& decimations) const; /** * Will return the number of resolution levels. Note: resolution * level 0 is included in the return count. */ virtual ossim_uint32 getNumberOfDecimationLevels() const; /*! * Returns the number of bands available from the input. */ virtual ossim_uint32 getNumberOfInputBands() const = 0; /** * Returns the number of bands in a tile returned from this TileSource. */ virtual ossim_uint32 getNumberOfOutputBands() const; /** * @brief Initializes bandList. * * This implementation initializes to the zero based order of input bands. * Derived classes that are band selectors should override. * * @param bandList Initialized by this. */ virtual void getOutputBandList( std::vector& bandList ) const; /** * This will be used to query the output pixel type of the tile source. * Please ignore the argument. It will soon be removed. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the default processing tile width */ virtual ossim_uint32 getTileWidth() const; /** * Returns the default processing tile height */ virtual ossim_uint32 getTileHeight() const; /** * Each band has a null pixel associated with it. The null pixel * represents an invalid value. */ virtual double getNullPixelValue(ossim_uint32 band=0)const; /** * Returns the min pixel of the band. */ virtual double getMinPixelValue(ossim_uint32 band=0)const; /** * Returns the max pixel of the band. */ virtual double getMaxPixelValue(ossim_uint32 band=0)const; /** * This will return the bounding rect of the source. We can have several * sources which are in a chain to modify the bounding image rect. * lets say you are next to an image handler then it will return the * bounding rect for that image. If you are at the right side of a * resampler then you will get a bounding rect along the image view plane. * This is going to be a very import method for both image writers, * mosaics or anything that needs to operate only within the bounds of an * image. */ virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0) const; /** * @brief Gets the bounding rectangle of the source. * * This default implementation calls the getBoundingRect interface that * returns a rectangle. Derived classes should override as needed. * * @param rect Initialized with bounding rectangle by this. * @param resLevel Reduced resolution level if applicable. */ virtual void getBoundingRect(ossimIrect& rect, ossim_uint32 resLevel=0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * ordering specifies how the vertices should be arranged. * valid image vertices is basically the tightly fit convex hull * of the image. Usually an image has NULL values and are * internally not upright rectangular. This can cause * problems some spatial filters. * * The default implementation is to return the bounding rect. */ virtual void getValidImageVertices( std::vector& validVertices, ossimVertexOrdering ordering=OSSIM_CLOCKWISE_ORDER, ossim_uint32 resLevel=0)const; /** * Returns the image geometry object associated with this tile source or * NULL if not defined. The geometry contains full-to-local image transform * as well as projection (image-to-world). Default implementation returns * the image geometry object associated with the next * (left) input source (if any) connected to this source in the chain, or * NULL. */ virtual ossimRefPtr getImageGeometry(); /** * Default implementation sets geometry of the first input to the geometry * specified. */ virtual void setImageGeometry(const ossimImageGeometry* geom); /** Default method to call input's saveImageGeometry. */ virtual void saveImageGeometry() const; /** Default method to call input's saveImageGeometry. */ virtual void saveImageGeometry(const ossimFilename& geometry_file) const; virtual void initialize()=0; virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void setProperty(ossimRefPtr property); virtual void getPropertyNames(std::vector& propertyNames)const; /** * @return Flag indicating the data contains pallete indexes. * * This should be replaced by a getPhotoInterpretation(). */ virtual bool isIndexedData() const; protected: ossimImageSource (const ossimImageSource& rhs); const ossimImageSource& operator= (const ossimImageSource&); private: TYPE_DATA }; #endif /* #ifndef ossimImageSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageSourceFactory.h000066400000000000000000000021531352751253100250630ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageSourceFactory.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimImageSourceFactory_HEADER #define ossimImageSourceFactory_HEADER #include class ossimImageSourceFactory : public ossimImageSourceFactoryBase { public: virtual ~ossimImageSourceFactory(); static ossimImageSourceFactory* instance(); virtual ossimObject* createObject(const ossimString& name)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual void getTypeNameList(std::vector& typeList)const; protected: // Hide from use. ossimImageSourceFactory(); ossimImageSourceFactory(const ossimImageSourceFactory&); const ossimImageSourceFactory& operator=(ossimImageSourceFactory&); static ossimImageSourceFactory* theInstance; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageSourceFactoryBase.h000066400000000000000000000021501352751253100256530ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageSourceFactoryBase.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimImageSourceFactoryBase_HEADER #define ossimImageSourceFactoryBase_HEADER #include class ossimImageSource; class OSSIMDLLEXPORT ossimImageSourceFactoryBase : public ossimObjectFactory { public: /*! * Convenient conversion method. Gurantees an ossimImageSource is returned. Returns * NULL otherwise */ virtual ossimImageSource* createImageSource(const ossimString& name)const; virtual ossimImageSource* createImageSource(const ossimKeywordlist& kwl, const char* prefix=0)const; protected: // Hide from use. ossimImageSourceFactoryBase(); ossimImageSourceFactoryBase(const ossimImageSourceFactoryBase&); const ossimImageSourceFactoryBase& operator=(const ossimImageSourceFactoryBase&); }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageSourceFactoryRegistry.h000066400000000000000000000030171352751253100266140ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageSourceFactoryRegistry.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimImageSourceFactoryRegistry_HEADER #define ossimImageSourceFactoryRegistry_HEADER #include class OSSIM_DLL ossimImageSourceFactoryRegistry : public ossimImageSourceFactoryBase { public: static ossimImageSourceFactoryRegistry* instance(); virtual ~ossimImageSourceFactoryRegistry(); virtual ossimObject* createObject(const ossimString& name)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual void getTypeNameList(std::vector& typeList)const; void registerFactory(ossimImageSourceFactoryBase* factory); void unregisterFactory(ossimImageSourceFactoryBase* factory); bool findFactory(ossimImageSourceFactoryBase* factory)const; protected: ossimImageSourceFactoryRegistry(); // hide ossimImageSourceFactoryRegistry(const ossimImageSourceFactoryRegistry&);//hide void operator = (ossimImageSourceFactoryRegistry&);// hide static ossimImageSourceFactoryRegistry* theInstance; std::vector theFactoryList; TYPE_DATA }; extern "C" { OSSIMDLLEXPORT void* ossimImageSourceFactoryRegistryGetInstance(); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageSourceFilter.h000066400000000000000000000043761352751253100247120ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id: ossimImageSourceFilter.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimImageSourceFilter_HEADER #define ossimImageSourceFilter_HEADER #include #include #include class OSSIMDLLEXPORT ossimImageSourceFilter : public ossimImageSource, public ossimConnectableObjectListener { public: ossimImageSourceFilter(ossimObject* owner=NULL); ossimImageSourceFilter(ossimImageSource* inputSource); ossimImageSourceFilter(ossimObject* owner, ossimImageSource* inputSource); /*! * Returns the input connection's output band list. * If not connected calls ossimImageSource::getOutputBandList. */ virtual void getOutputBandList(std::vector& bandList) const; /*! * Returns the number of bands available from the input. */ virtual ossim_uint32 getNumberOfInputBands()const; virtual void initialize(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; virtual void connectInputEvent(ossimConnectionEvent& event); virtual void disconnectInputEvent(ossimConnectionEvent& event); virtual void propertyEvent(ossimPropertyEvent& event); virtual void refreshEvent(ossimRefreshEvent& event); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimImageSourceFilter(); ossimImageSource* theInputConnection; TYPE_DATA }; #endif /* #ifndef ossimImageSourceFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageSourceHistogramFilter.h000066400000000000000000000036341352751253100265640ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageSourceHistogramFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimImageSourceHistogramFilter_HEADER #define ossimImageSourceHistogramFilter_HEADER #include #include #include class OSSIMDLLEXPORT ossimImageSourceHistogramFilter : public ossimImageSourceFilter { public: ossimImageSourceHistogramFilter(); ossimImageSourceHistogramFilter(ossimImageSource* inputSource, ossimRefPtr histogram); virtual void setHistogram(ossimRefPtr histogram); virtual bool setHistogram(const ossimFilename& filename); virtual const ossimFilename& getHistogramFilename()const; virtual ossimRefPtr getHistogram(); virtual const ossimRefPtr getHistogram()const; bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; virtual void connectInputEvent(ossimConnectionEvent& event); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = NULL); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = NULL)const; virtual std::ostream& print(std::ostream& out) const; protected: virtual ~ossimImageSourceHistogramFilter(); ossim_int32 theCurrentResLevel; private: ossimRefPtr theHistogram; ossimFilename theFilename; TYPE_DATA }; #endif /* #ifndef ossimImageSourceHistogramFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimImageSourceSequencer.h000066400000000000000000000131721352751253100254110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimImageSourceSequencer.h 23081 2015-01-14 21:38:42Z dburken $ #ifndef ossimImageSourceSequencer_HEADER #define ossimImageSourceSequencer_HEADER 1 #include #include #include #include #include class OSSIMDLLEXPORT ossimImageSourceSequencer : public ossimImageSource, public ossimConnectableObjectListener { public: ossimImageSourceSequencer(ossimImageSource* inputSource=NULL, ossimObject* owner=NULL); virtual ~ossimImageSourceSequencer(); /*! * This will return the number of tiles within the * area of interest. */ ossim_int64 getNumberOfTiles()const; /*! * Will return the number of tiles along the * x or horizontal direction. */ ossim_int64 getNumberOfTilesHorizontal()const; /*! * Will return the number of tiles along the * y or vertical direction. */ ossim_int64 getNumberOfTilesVertical()const; /*! * This must be called. We can only initialize this * object completely if we know all connections * are valid. Some other object drives this and so the * connection's initialize will be called after. The job * of this connection is to set up the sequence. It will * default to the bounding rect. The area of interest can be * set to some other rectagle (use setAreaOfInterest). */ virtual void initialize(); /*! * Will set the current area of interest. */ virtual void setAreaOfInterest(const ossimIrect& areaOfInterest); /*! * Just returns the current area of interest. */ const ossimIrect& getAreaOfInterest()const; /*! * Will set the internal pointers to the upperleft * tile number. To go to the next tile in the sequence * just call getNextTile. */ virtual void setToStartOfSequence(); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /*! * Will allow you to get the next tile in the sequence. * Note the last tile returned will be an invalid * ossimRefPtr. Callers should be able to do: * * ossimRefPtr id = sequencer->getNextTile(); * while (id.valid()) * { * doSomething; * id = sequencer->getNextTile(); * } * */ virtual ossimRefPtr getNextTile(ossim_uint32 resLevel=0); virtual bool getNextTileStream(std::ostream& bos); virtual bool getTileOrigin(ossim_int64 id, ossimIpt& origin)const; /*! * @brief Establishes a tile rect given tile ID. * @param tile_id * @param rect Rectangle to initialize. * @return true if valid; else, false. */ bool getTileRect(ossim_int64 tile_id, ossimIrect& rect) const; virtual ossimRefPtr getTile(ossim_int64 id, ossim_uint32 resLevel=0); virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const; virtual void getDecimationFactors(std::vector& decimations) const; virtual ossim_uint32 getNumberOfDecimationLevels()const; /*! * Returns the number of bands available from the input. */ virtual ossim_uint32 getNumberOfInputBands()const; virtual ossimScalarType getOutputScalarType() const; virtual ossim_uint32 getTileWidth() const; virtual ossim_uint32 getTileHeight() const; virtual void slaveProcessTiles(); virtual bool isMaster()const; virtual ossimIpt getTileSize()const; virtual void setTileSize(const ossimIpt& tileSize); virtual void setTileSize(ossim_int32 width, ossim_int32 height); virtual void connectInputEvent(ossimConnectionEvent& event); virtual void disconnectInputEvent(ossimConnectionEvent& event); virtual bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; void setCreateHistogram(bool create_histogram); bool loadState(const ossimKeywordlist& kwl, const char* prefix); void getBinInformation(ossim_uint32& numberOfBins, ossim_float64& minValue, ossim_float64& maxValue, ossimScalarType stype)const; protected: ossimImageSource* theInputConnection; ossimRefPtr theBlankTile; ossimRefPtr theHistogram; /*! * Is the area of interest. The default will * */ ossimIrect theAreaOfInterest; /*! * Called during initialize. */ ossimIpt theTileSize; //--- // These need to be big(64 bit) for high resolution tile servers. Made // signed for ease of going to/from ipt and irect which are both signed. //--- ossim_int64 theNumberOfTilesHorizontal; ossim_int64 theNumberOfTilesVertical; ossim_int64 theCurrentTileNumber; bool theCreateHistogram; virtual void updateTileDimensions(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageStatisticsSource.h000066400000000000000000000016041352751253100256060ustar00rootroot00000000000000#ifndef ossimImageStatistics_HEADER #define ossimImageStatistics_HEADER #include class OSSIMDLLEXPORT ossimImageStatisticsSource : public ossimSource { public: ossimImageStatisticsSource(); virtual void computeStatistics(); virtual bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; const std::vector& getMean()const; const std::vector& getMin()const; const std::vector& getMax()const; protected: virtual ~ossimImageStatisticsSource(); void clearStatistics(); template void computeStatisticsTemplate(T dummyVariable); void setStatsSize(ossim_uint32 size); std::vector theMean; std::vector theMin; std::vector theMax; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageToPlaneNormalFilter.h000066400000000000000000000051671352751253100261640ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageToPlaneNormalFilter.h 20078 2011-09-09 12:25:50Z gpotts $ #ifndef ossimImageToPlaneNormalFilter_HEADER #define ossimImageToPlaneNormalFilter_HEADER #include class OSSIMDLLEXPORT ossimImageToPlaneNormalFilter : public ossimImageSourceFilter { public: ossimImageToPlaneNormalFilter(); ossimImageToPlaneNormalFilter(ossimImageSource* inputSource); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual ossimScalarType getOutputScalarType() const; virtual ossim_uint32 getNumberOfOutputBands() const; void setXScale(const double& scale); void setYScale(const double& scale); double getXScale()const; double getYScale()const; void setTrackScaleFlag(bool flag); bool getTrackScaleFlag()const; void setSmoothnessFactor(double value); double getSmoothnessFactor()const; bool loadState(const ossimKeywordlist& kwl, const char* prefix); bool saveState(ossimKeywordlist& kwl, const char* prefix)const; virtual void initialize(); /* ------------------- PROPERTY INTERFACE -------------------- */ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /* ------------------ PROPERTY INTERFACE END ------------------- */ protected: ossimRefPtr theTile; ossimRefPtr theBlankTile; ossimIrect theInputBounds; bool theTrackScaleFlag; double theXScale; double theYScale; double theSmoothnessFactor; void initializeTile(); virtual void computeNormals(ossimRefPtr& inputTile, ossimRefPtr& outputTile); template void computeNormalsTemplate(T inputScalarTypeDummy, ossimRefPtr& inputTile, ossimRefPtr& outputTile); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageWriter.h000066400000000000000000000035171352751253100235540ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Frank Warmerdam (warmerdam@pobox.com) // // Description: // // Contains class declaration for ossimImageWriter //******************************************************************* // $Id: ossimImageWriter.h 15798 2009-10-23 19:15:20Z gpotts $ #ifndef ossimImageWriter_HEADER #define ossimImageWriter_HEADER #include #include #include #include class ossimImage; class ossimImageSource; class ossimImageWriter; class ossimImageWriterFactory; class ossimKeywordlist; class ossimFilename; #include class OSSIM_DLL ossimImageWriter : public ossimOutputSource { public: ossimImageWriter(ossimObject* owner=NULL); ossimImageWriter(ossimObject* owner, ossim_uint32 numberOfInputs, ossim_uint32 numberOfOutputs, bool inputListIsFixed, bool outputListIsFixed); virtual ~ossimImageWriter(); /** * @param aRect the rectangle to write. * * @return true on success, false if the rectangle is invalid. */ virtual bool setViewingRect(const ossimIrect &aRect); /** * @return Returns theAreaOfInterest. */ virtual ossimIrect getAreaOfInterest() const; virtual void setAreaOfInterest(const ossimIrect& inputAreaOfInterest); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: ossimIrect theAreaOfInterest; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageWriterFactory.h000066400000000000000000000047311352751253100251030ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Frank Warmerdam (warmerda@home.com) // //******************************************************************* // $Id: ossimImageWriterFactory.h 18002 2010-08-30 18:01:10Z gpotts $ #ifndef ossimImageWriterFactory_HEADER #define ossimImageWriterFactory_HEADER #include class ossimImageWriter; class ossimKeywordlist; class ossimImageWriterFactory: public ossimImageWriterFactoryBase { public: virtual ~ossimImageWriterFactory(); static ossimImageWriterFactory* instance(); ossimImageFileWriter *createWriterFromExtension(const ossimString& fileExtension)const; virtual ossimImageFileWriter* createWriter(const ossimKeywordlist& kwl, const char *prefix=0)const; virtual ossimImageFileWriter* createWriter(const ossimString& typeName)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char *prefix=0)const; virtual ossimObject* createObject(const ossimString& typeName)const; virtual void getExtensions(std::vector& result)const; virtual void getTypeNameList(std::vector& typeList)const; /*! * getImageTypeList. This is the actual image type name. So for * example, ossimTiffWriter has several image types. Some of these * include TIFF_TILED, TIFF_TILED_BAND_SEPARATE ... etc. The * ossimGdalWriter * may include GDAL_IMAGINE_HFA, GDAL_RGB_NITF, GDAL_JPEG20000, ... etc * A writer should be able to be instantiated by this name as well as a * class name */ virtual void getImageTypeList(std::vector& imageTypeList)const; virtual void getImageFileWritersBySuffix(ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& ext)const; virtual void getImageFileWritersByMimeType(ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& mimeType)const; protected: ossimImageWriterFactory() {} static ossimImageWriterFactory* theInstance; ossimImageFileWriter* createFromMimeType(const ossimString& mimeType)const; bool isImageTypeName(const ossimString& name)const; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageWriterFactoryBase.h000066400000000000000000000036241352751253100256760ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimImageWriterFactoryBase.h 18011 2010-08-31 12:48:56Z dburken $ #ifndef ossimImageWriterFactoryBase_HEADER #define ossimImageWriterFactoryBase_HEADER #include #include #include #include class ossimKeywordlist; class OSSIM_DLL ossimImageWriterFactoryBase : public ossimObjectFactory { public: typedef std::vector > ImageFileWriterList; virtual ~ossimImageWriterFactoryBase() {} virtual ossimImageFileWriter* createWriter(const ossimKeywordlist& kwl, const char *prefix=0)const=0; virtual ossimImageFileWriter* createWriter(const ossimString& typeName)const=0; virtual void getExtensions(std::vector& result)const=0; /*! * getImageTypeList. This is the actual image type name. So for * example, ossimTiffWriter has several image types. Some of these * include tiff_tiled, tiff_tiled_band_separate ... etc. The ossimGdalWriter * may include gdal_imagine_hfa,gdal_nitf_rgb_band_separate, ... etc * A writer should be able to be instantiated by this name as well as a class name */ virtual void getImageTypeList(std::vector& imageTypeList)const=0; virtual void getImageFileWritersBySuffix(ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& ext)const; virtual void getImageFileWritersByMimeType(ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& mimeType)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimImageWriterFactoryRegistry.h000066400000000000000000000064141352751253100266340ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Frank Warmerdam (warmerda@home.com) // //******************************************************************* // $Id: ossimImageWriterFactoryRegistry.h 22865 2014-08-06 11:17:03Z gpotts $ #ifndef ossimImageWriterFactoryRegistry_HEADER #define ossimImageWriterFactoryRegistry_HEADER #include #include #include #include #include class ossimImageFileWriter; class ossimKeywordlist; class OSSIMDLLEXPORT ossimImageWriterFactoryRegistry : public ossimObjectFactory, public ossimFactoryListInterface { public: static ossimImageWriterFactoryRegistry* instance(); ossimImageFileWriter *createWriter(const ossimFilename& filename)const; ossimImageFileWriter *createWriterFromExtension(const ossimString& fileExtension)const; ossimImageFileWriter *createWriter(const ossimKeywordlist &kwl, const char *prefix=0)const; ossimImageFileWriter* createWriter(const ossimString& typeName)const; ossimObject* createObject(const ossimKeywordlist &kwl, const char *prefix=0)const; ossimObject* createObject(const ossimString& typeName)const; /** * getTypeNameList. This should return the class type of the object being * used to perform the writting. */ virtual void getTypeNameList(std::vector& typeList)const; /** * getImageTypeList. This is the actual image type name. So for * example, ossimTiffWriter has several image types. Some of these * include TIFF_TILED, TIFF_TILED_BAND_SEPARATE ... etc. * The ossimGdalWriter * may include GDAL_IMAGINE_HFA, GDAL_RGB_NITF, GDAL_JPEG20000, ... etc * A writer should be able to be instantiated by this name as well as a * class name */ virtual void getImageTypeList(std::vector& imageTypeList)const; virtual void getImageFileWritersBySuffix(ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& ext)const; virtual void getImageFileWritersByMimeType(ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& mimeType)const; /** * @brief Prints list of writers from getImageTypeList. * @param out Stream to print to. * @return std::ostream& */ std::ostream& printImageTypeList(std::ostream& out)const; /** * @brief Prints list of writers from getImageTypeList. * @param out Stream to print to. * @return std::ostream& */ std::ostream& printWriterProps(std::ostream& out)const; protected: ossimImageWriterFactoryRegistry(); ossimImageWriterFactoryRegistry(const ossimImageWriterFactoryRegistry&); void operator=(const ossimImageWriterFactoryRegistry&); //static ossimImageWriterFactoryRegistry* theInstance; }; extern "C" { OSSIMDLLEXPORT void* ossimImageWriterFactoryRegistryGetInstance(); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimIndexToRgbLutFilter.h000066400000000000000000000150061352751253100251710ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //************************************************************************* // $Id: ossimIndexToRgbLutFilter.h 23616 2015-11-11 19:50:29Z dburken $ #ifndef ossimIndexToRgbLutFilter_HEADER #define ossimIndexToRgbLutFilter_HEADER #include #include #include #include class ossimImageData; /*************************************************************************************************** * * This class provides a look-up-table remap from a single band input (the index), to a 3-band RGB * output. The LUT is provided as a KWL with several remapping modes supported: * * Literal: Only those indices represented in the KWL are remapped to the values indicated. All * other pixel values are mapped to the NULL pixel (0,0,0). Note that this is only meaningful for * integer input scalar types since a normalized input will likely not find an exact match. * * Arbitrary piecewise linear ("vertices"): The LUT KWL provides vertices to contiguous line * segments. Pixel values falling between specified indices are linearly interpolated between * adjacent vertices. Any index pixel values falling outside the range between min and max vertex * indices will be mapped to the NULL pixel. * * Regular piecewise linear ("regular"): The entries in the KWL do not correspond to any specific * index (except the first and the last entries that correspond to the min and max pixel values). * Remaining intermediate entries are equally spaced in index space so that the line segments are of * equal length. The min and max values are queried from the input source, but can be overriden with * the "min_value" and "max_value" keywords in the LUT KWL. * * Here are example KWLs for the three modes, first for the literal remap: * * type: ossimIndexToRgbLutFilter * mode: literal * entry0.index: 0 * entry0.color: 1 1 1 * entry1.index: 128 * entry1.color: 255 0 0 * entry2.index: 255 * entry2.color: 0 255 0 * * The above KWL will map only pixels with input values of 0, 128, and 255. All other indices will * map to the null value. * * Example for arbitrary piecewise linear: * * type: ossimIndexToRgbLutFilter * mode: vertices * entry0.index: 1 * entry0.color: 0 0 255 * entry1.index: 128 * entry1.color: 0 255 0 * entry2.index: 250 * entry2.color: 255 0 0 * * The above KWL is a sort of heat map where indices between 1 and 128 will linearly map from blue * to green, and then 128 to 250 will map from green (through yellow) to red. Note that any value * above 250 as well as 0 are outside of the remap range and will map to the null pixel (0,0,0). * * Example of regular piecewise linear. This is the default mode. For backward compatibility, the * mode keyword here is optional and if omitted will imply this mode. Also, unlike previous form, * the number_of_entries keyword is not required and is ignored if present. * * type: ossimIndexToRgbLutFilter * mode: regular * entry0: 0 0 255 * entry1: 0 255 0 * entry2: 255 0 0 * max_value: 250 * min_value: 1 * * The above KWL is almost equivalent to the "vertices" example above, i.e., a heat map. However, * the individual vertices are not specified. Instead, three entries will define two line segments. * The first line segment will commence with index 1 (min_value) and finish at: * * [(max_value-min_value)/(number_of_entries-1)] + min_value * * In this case it will be 125.5. The quantity in square-brackets (124.5) is the interval, or * length of each line segment, so the second line segment will go from 125.5 to 250. Input pixel * values below the min_value will clamp to the min value (except the null pixel) and those above * the max value will clamp to the max value. * * The table can be contained in a separate file from the main KWL state file. In this case, the * loadState can accept a file name in place of a complete table: * * type: ossimIndexToRgbLutFilter * lut_file: * * The format of the LUT KWL file is just as specified above for the inline case. * **************************************************************************************************/ class OSSIM_DLL ossimIndexToRgbLutFilter : public ossimImageSourceFilter { public: enum Mode { LITERAL = 0, VERTICES = 1, REGULAR = 2 }; ossimIndexToRgbLutFilter(); virtual ~ossimIndexToRgbLutFilter(); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); ossim_uint32 getNumberOfOutputBands() const; virtual ossimScalarType getOutputScalarType() const; void setMode(Mode mode) { theMode = mode; } Mode getMode() const { return theMode; } /** * @brief Set lookup table(lut) method. * * This opens the keyword list and initializes lut. * * CAUTION: Requires theMinValue, theMaxValue, and theMode to be set. Typically a * connection is made prior to this call. If not connected to an input, "min", * "max" and "mode" keywords should be passed in the keyword list file. * * @param file Keyword list containing lut. */ void setLut(const ossimFilename& file); double getMinValue()const; double getMaxValue()const; void setMinValue(double value); void setMaxValue(double value); virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void initialize(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); protected: /** * Called on first getTile, will initialize all data needed. */ void allocate(); bool initializeLut(const ossimKeywordlist* kwl, const char* prefix=0); std::map theLut; double theMinValue; double theMaxValue; bool theMinValueOverride; bool theMaxValueOverride; Mode theMode; ossimRefPtr theTile; ossimFilename theLutFile; TYPE_DATA }; #endif /* #ifndef ossimIndexToRgbLutFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimIntensityAdjustmentFilter.h000066400000000000000000000043411352751253100265240ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimIntensityAdjustmentFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimIntensityAdjustmentFilter_HEADER #define ossimIntensityAdjustmentFilter_HEADER #include #include class ossimIntensityAdjustmentFilter : public ossimImageSourceFilter { public: ossimIntensityAdjustmentFilter(); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); const ossimIrect& getGridBounds()const { return theGridBounds; } virtual void setIntensityGrid(const ossimDblGrid& grid) { theMeanIntensityGrid = grid; } void setMeanIntensityTarget(double targetMean) { theMeanIntensityTarget = targetMean; } double getMeanIntensityTarget()const { return theMeanIntensityTarget; } ossimDblGrid& getMeanIntensityGrid() { return theMeanIntensityGrid; } const ossimDblGrid& getMeanIntensityGrid()const { return theMeanIntensityGrid; } void createAndPopulateGrid(const ossimIpt& spacing, double targetMean = .5); virtual void initialize(); protected: virtual ~ossimIntensityAdjustmentFilter(); virtual void allocate(); ossimDblGrid theMeanIntensityGrid; double theMeanIntensityTarget; ossimRefPtr theNormTile; ossimRefPtr theTile; ossimRefPtr theBlankTile; ossimIrect theGridBounds; double computeMeanIntensity(ossimRefPtr& data); void loadNormTile(ossimRefPtr& data); double matchTargetMean(double inputValue, double meanValue, double targetMean, double minValue, double maxValue); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimIso8211.h000066400000000000000000000450401352751253100224000ustar00rootroot00000000000000/****************************************************************************** * Copied from "gdal" project. See licence below. * * Project: ISO 8211 Access * Purpose: Main declarations for ISO 8211. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** * $Id: ossimIso8211.h 7238 2005-02-13 16:08:04Z dburken $ */ #ifndef ossimIso8211_HEADER #define ossimIso8211_HEADER #include #include /** General data type */ typedef enum { DDFInt, DDFFloat, DDFString, DDFBinaryString } DDFDataType; /************************************************************************/ /* These should really be private to the library ... they are */ /* mostly conveniences. */ /************************************************************************/ long ossimDDFScanInt( const char *pszString, int nMaxChars ); int ossimDDFScanVariable( const char * pszString, int nMaxChars, int nDelimChar ); char *ossimDDFFetchVariable( const char *pszString, int nMaxChars, int nDelimChar1, int nDelimChar2, int *pnConsumedChars ); #ifndef OSSIM_DDF_FIELD_TERMINATOR # define OSSIM_DDF_FIELD_TERMINATOR 30 #endif #ifndef OSSIM_DDF_UNIT_TERMINATOR # define OSSIM_DDF_UNIT_TERMINATOR 31 #endif /************************************************************************/ /* Predeclarations */ /************************************************************************/ class ossimDDFFieldDefn; class ossimDDFSubfieldDefn; class ossimDDFRecord; class ossimDDFField; /************************************************************************/ /* DDFModule */ /************************************************************************/ /** The primary class for reading ISO 8211 files. This class contains all the information read from the DDR record, and is used to read records from the file. */ class ossimDDFModule { public: ossimDDFModule(); ~ossimDDFModule(); int Open( const char * pszFilename, int bFailQuietly = false ); int Create( const char *pszFilename ); void Close(); int Initialize( char chInterchangeLevel = '3', char chLeaderIden = 'L', char chCodeExtensionIndicator = 'E', char chVersionNumber = '1', char chAppIndicator = ' ', const char *pszExtendedCharSet = " ! ", int nSizeFieldLength = 3, int nSizeFieldPos = 4, int nSizeFieldTag = 4 ); void Dump( FILE * fp ); ossimDDFRecord *ReadRecord( void ); void Rewind( long nOffset = -1 ); ossimDDFFieldDefn *FindFieldDefn( const char * ); /** Fetch the number of defined fields. */ int GetFieldCount() { return nFieldDefnCount; } ossimDDFFieldDefn *GetField(int); void AddField( ossimDDFFieldDefn *poNewFDefn ); // This is really just for internal use. int GetFieldControlLength() { return _fieldControlLength; } void AddCloneRecord( ossimDDFRecord * ); void RemoveCloneRecord( ossimDDFRecord * ); // This is just for DDFRecord. FILE *GetFP() { return fpDDF; } private: FILE *fpDDF; int bReadOnly; long nFirstRecordOffset; char _interchangeLevel; char _inlineCodeExtensionIndicator; char _versionNumber; char _appIndicator; int _fieldControlLength; char _extendedCharSet[4]; long _recLength; char _leaderIden; long _fieldAreaStart; long _sizeFieldLength; long _sizeFieldPos; long _sizeFieldTag; // One DirEntry per field. int nFieldDefnCount; ossimDDFFieldDefn **papoFieldDefns; ossimDDFRecord *poRecord; int nCloneCount; int nMaxCloneCount; ossimDDFRecord **papoClones; }; /************************************************************************/ /* DDFFieldDefn */ /************************************************************************/ typedef enum { dsc_elementary, dsc_vector, dsc_array, dsc_concatenated } DDF_data_struct_code; typedef enum { dtc_char_string, dtc_implicit_point, dtc_explicit_point, dtc_explicit_point_scaled, dtc_char_bit_string, dtc_bit_string, dtc_mixed_data_type } DDF_data_type_code; /** * Information from the DDR defining one field. Note that just because * a field is defined for a DDFModule doesn't mean that it actually occurs * on any records in the module. DDFFieldDefns are normally just significant * as containers of the DDFSubfieldDefns. */ class ossimDDFFieldDefn { public: ossimDDFFieldDefn(); ~ossimDDFFieldDefn(); int Create( const char *pszTag, const char *pszFieldName, const char *pszDescription, DDF_data_struct_code eDataStructCode, DDF_data_type_code eDataTypeCode, const char *pszFormat = NULL ); void AddSubfield( ossimDDFSubfieldDefn *poNewSFDefn, int bDontAddToFormat = false ); void AddSubfield( const char *pszName, const char *pszFormat ); int GenerateDDREntry( char **ppachData, int *pnLength ); int Initialize( ossimDDFModule * poModule, const char *pszTag, int nSize, const char * pachRecord ); void Dump( FILE * fp ); /** Fetch a pointer to the field name (tag). * @return this is an internal copy and shouldn't be freed. */ const char *GetName() { return pszTag; } /** Fetch a longer descriptio of this field. * @return this is an internal copy and shouldn't be freed. */ const char *GetDescription() { return _fieldName; } /** Get the number of subfields. */ int GetSubfieldCount() { return nSubfieldCount; } ossimDDFSubfieldDefn *GetSubfield( int i ); ossimDDFSubfieldDefn *FindSubfieldDefn( const char * ); /** * Get the width of this field. This function isn't normally used * by applications. * * @return The width of the field in bytes, or zero if the field is not * apparently of a fixed width. */ int GetFixedWidth() { return nFixedWidth; } /** * Fetch repeating flag. * @see DDFField::GetRepeatCount() * @return TRUE if the field is marked as repeating. */ int IsRepeating() { return bRepeatingSubfields; } static char *ExpandFormat( const char * ); /** this is just for an S-57 hack for swedish data */ void SetRepeatingFlag( int n ) { bRepeatingSubfields = n; } char *GetDefaultValue( int *pnSize ); private: static char *ExtractSubstring( const char * ); ossimDDFModule * poModule; char * pszTag; char * _fieldName; char * _arrayDescr; char * _formatControls; int bRepeatingSubfields; int nFixedWidth; // zero if variable. int BuildSubfields(); int ApplyFormats(); DDF_data_struct_code _data_struct_code; DDF_data_type_code _data_type_code; int nSubfieldCount; ossimDDFSubfieldDefn **papoSubfields; }; /************************************************************************/ /* DDFSubfieldDefn */ /* */ /* Information from the DDR record for one subfield of a */ /* particular field. */ /************************************************************************/ /** * Information from the DDR record describing one subfield of a DDFFieldDefn. * All subfields of a field will occur in each occurance of that field * (as a DDFField) in a DDFRecord. Subfield's actually contain formatted * data (as instances within a record). */ class ossimDDFSubfieldDefn { public: ossimDDFSubfieldDefn(); ~ossimDDFSubfieldDefn(); void SetName( const char * pszName ); /** Get pointer to subfield name. */ const char *GetName() { return pszName; } /** Get pointer to subfield format string */ const char *GetFormat() { return pszFormatString; } int SetFormat( const char * pszFormat ); /** * Get the general type of the subfield. This can be used to * determine which of ExtractFloatData(), ExtractIntData() or * ExtractStringData() should be used. * @return The subfield type. One of DDFInt, DDFFloat, DDFString or * DDFBinaryString. */ DDFDataType GetType() { return eType; } double ExtractFloatData( const char *pachData, int nMaxBytes, int * pnConsumedBytes ); int ExtractIntData( const char *pachData, int nMaxBytes, int * pnConsumedBytes ); const char *ExtractStringData( const char *pachData, int nMaxBytes, int * pnConsumedBytes ); int GetDataLength( const char *, int, int * ); void DumpData( const char *pachData, int nMaxBytes, FILE * fp ); int FormatStringValue( char *pachData, int nBytesAvailable, int *pnBytesUsed, const char *pszValue, int nValueLength = -1 ); int FormatIntValue( char *pachData, int nBytesAvailable, int *pnBytesUsed, int nNewValue ); int FormatFloatValue( char *pachData, int nBytesAvailable, int *pnBytesUsed, double dfNewValue ); /** Get the subfield width (zero for variable). */ int GetWidth() { return nFormatWidth; } // zero for variable. int GetDefaultValue( char *pachData, int nBytesAvailable, int *pnBytesUsed ); void Dump( FILE * fp ); /** Binary format: this is the digit immediately following the B or b for binary formats. */ typedef enum { NotBinary=0, UInt=1, SInt=2, FPReal=3, FloatReal=4, FloatComplex=5 } DDFBinaryFormat; DDFBinaryFormat GetBinaryFormat(void) const { return eBinaryFormat; } private: char *pszName; // a.k.a. subfield mnemonic char *pszFormatString; DDFDataType eType; DDFBinaryFormat eBinaryFormat; /* -------------------------------------------------------------------- */ /* bIsVariable determines whether we using the */ /* chFormatDelimeter (TRUE), or the fixed width (false). */ /* -------------------------------------------------------------------- */ int bIsVariable; char chFormatDelimeter; int nFormatWidth; /* -------------------------------------------------------------------- */ /* Fetched string cache. This is where we hold the values */ /* returned from ExtractStringData(). */ /* -------------------------------------------------------------------- */ int nMaxBufChars; char *pachBuffer; }; /************************************************************************/ /* DDFRecord */ /* */ /* Class that contains one DR record from a file. We read into */ /* the same record object repeatedly to ensure that repeated */ /* leaders can be easily preserved. */ /************************************************************************/ /** * Contains instance data from one data record (DR). The data is contained * as a list of DDFField instances partitioning the raw data into fields. */ class ossimDDFRecord { public: ossimDDFRecord( ossimDDFModule * ); ~ossimDDFRecord(); ossimDDFRecord *Clone(); ossimDDFRecord *CloneOn( ossimDDFModule * ); void Dump( FILE * ); /** Get the number of DDFFields on this record. */ int GetFieldCount() { return nFieldCount; } ossimDDFField *FindField( const char *, int = 0 ); ossimDDFField *GetField( int ); int GetIntSubfield( const char *, int, const char *, int, int * = NULL ); double GetFloatSubfield( const char *, int, const char *, int, int * = NULL ); const char *GetStringSubfield( const char *, int, const char *, int, int * = NULL ); int SetIntSubfield( const char *pszField, int iFieldIndex, const char *pszSubfield, int iSubfieldIndex, int nValue ); int SetStringSubfield( const char *pszField, int iFieldIndex, const char *pszSubfield, int iSubfieldIndex, const char *pszValue, int nValueLength=-1 ); int SetFloatSubfield( const char *pszField, int iFieldIndex, const char *pszSubfield, int iSubfieldIndex, double dfNewValue ); /** Fetch size of records raw data (GetData()) in bytes. */ int GetDataSize() { return nDataSize; } /** * Fetch the raw data for this record. The returned pointer is effectively * to the data for the first field of the record, and is of size * GetDataSize(). */ const char *GetData() { return pachData; } /** * Fetch the DDFModule with which this record is associated. */ ossimDDFModule * GetModule() { return poModule; } int ResizeField( ossimDDFField *poField, int nNewDataSize ); int DeleteField( ossimDDFField *poField ); ossimDDFField* AddField( ossimDDFFieldDefn * ); int CreateDefaultFieldInstance( ossimDDFField *poField, int iIndexWithinField ); int SetFieldRaw( ossimDDFField *poField, int iIndexWithinField, const char *pachRawData, int nRawDataSize ); int UpdateFieldRaw( ossimDDFField *poField, int iIndexWithinField, int nStartOffset, int nOldSize, const char *pachRawData, int nRawDataSize ); int Write(); // This is really just for the DDFModule class. int Read(); void Clear(); int ResetDirectory(); private: int ReadHeader(); ossimDDFModule *poModule; int nReuseHeader; int nFieldOffset; // field data area, not dir entries. int _sizeFieldTag; int _sizeFieldPos; int _sizeFieldLength; int nDataSize; // Whole record except leader with header char *pachData; int nFieldCount; ossimDDFField *paoFields; int bIsClone; }; /************************************************************************/ /* DDFField */ /* */ /* This object represents one field in a DDFRecord. */ /************************************************************************/ /** * This object represents one field in a DDFRecord. This * models an instance of the fields data, rather than it's data definition * which is handled by the DDFFieldDefn class. Note that a DDFField * doesn't have DDFSubfield children as you would expect. To extract * subfield values use GetSubfieldData() to find the right data pointer and * then use ExtractIntData(), ExtractFloatData() or ExtractStringData(). */ class ossimDDFField { public: void Initialize( ossimDDFFieldDefn *, const char *pszData, int nSize ); void Dump( FILE * fp ); const char *GetSubfieldData( ossimDDFSubfieldDefn *, int * = NULL, int = 0 ); const char *GetInstanceData( int nInstance, int *pnSize ); /** * Return the pointer to the entire data block for this record. This * is an internal copy, and shouldn't be freed by the application. */ const char *GetData() { return pachData; } /** Return the number of bytes in the data block returned by GetData(). */ int GetDataSize() { return nDataSize; } int GetRepeatCount(); /** Fetch the corresponding DDFFieldDefn. */ ossimDDFFieldDefn *GetFieldDefn() { return poDefn; } private: ossimDDFFieldDefn *poDefn; int nDataSize; const char *pachData; }; #endif /* ifndef ossimIso8211_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimJpegCodec.h000066400000000000000000000070551352751253100231610ustar00rootroot00000000000000//--- // // License: MIT // // Description: class declaration for base codec(encoder/decoder). // //--- // $Id$ #ifndef ossimJpegCodec_HEADER #define ossimJpegCodec_HEADER 1 #include class OSSIM_DLL ossimJpegCodec : public ossimCodecBase { public: ossimJpegCodec(); virtual ~ossimJpegCodec(); /** * @return Codec type. "jpeg" */ virtual ossimString getCodecType()const; /** * @brief Encode jpeg method. * * Current options handled by this factory: * * type: jpeg * quality: 75 * * @param in Input data to encode. * * @param out Encoded output data. * * @return true on success, false on failure. */ virtual bool encode( const ossimRefPtr& in, std::vector& out ) const; /** * @brief Decode jpeg method. * * @param in Input data to decode. * * @param out Output tile. If the pointer to ossimImageData is null * internally it will be created. For code loops it is better to pre * initialized to correct size. * * @note Caller should set "out's" image rectangle upon successful * decode. * * @return true on success, false on failure. */ virtual bool decode( const std::vector& in, ossimRefPtr& out ) const; virtual const std::string& getExtension() const; /** * Ineterface to allow for specific properties to be set. * */ virtual void setProperty(ossimRefPtr property); /** * Interface to get the value of a specific property * * @param in name. Property name to retrieve * * @return property value */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * Get a list of all supported property names. Currently only "quality" property * is exposed * * @param out proeprtyNames. push the list of proeprty names to the list */ virtual void getPropertyNames(std::vector& propertyNames)const; /** * Allocate the state of the object thorugh a factory load/keywordlist * * @param in kwl. Input keywordlist that holds the values. * * @param in prefix. prefix to use for all keywords. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Save the state of the codec to the keywordlist * * @param out kwl. Input keywordlist that holds the values. * * @param in prefix. prefix to use for all keywords. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: /** * @brief For decoding standard jpeg block. * Curently only handles CMYK. * @param in Input jpeg buffer. * @param out Initialized by this. * @return true on success, false on error. */ bool decodeJpeg(const std::vector& in, ossimRefPtr& out ) const; /** * @brief For decoding color spaces other that mono and rgb. * Curently only handles CMYK. * @param in Input jpeg buffer. * @param out Initialized by this. * @return true on success, false on error. */ bool decodeJpegToRgb(const std::vector& in, ossimRefPtr& out ) const; /** * @return The enumerated libjpeg out_color_space. */ ossim_int32 getColorSpace( const std::vector& in ) const; ossim_uint32 m_quality; std::string m_ext; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimJpegDefaultTable.h000066400000000000000000000142131352751253100244720ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // // Description: Default JPEG Huffman tables. Values from: MIL-STD-188-198, APPENDIX B // Default JPEG quantization tables. Values from: MIL-STD-188-198, APPENDIX A // //******************************************************************** // $Id: ossimJpegDefaultTable.h 958 2010-06-03 23:00:32Z ming.su $ #ifndef ossimJpegDefaultTable_HEADER #define ossimJpegDefaultTable_HEADER static const int AC_BITS[16] = { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125 }; static const int DC_BITS[16] = { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }; static const int AC_HUFFVAL[256] = { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const int DC_HUFFVAL[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const static int Q1table[64] = { 8, 72, 72, 72, 72, 72, 72, 72, // 0 - 7 72, 72, 78, 74, 76, 74, 78, 89, // 8 - 15 81, 84, 84, 81, 89, 106, 93, 94, // 16 - 23 99, 94, 93, 106, 129, 111, 108, 116, // 24 - 31 116, 108, 111, 129, 135, 128, 136, 145, // 32 - 39 136, 128, 135, 155, 160, 177, 177, 160, // 40 - 47 155, 193, 213, 228, 213, 193, 255, 255, // 48 - 55 255, 255, 255, 255, 255, 255, 255, 255 // 56 - 63 }; const static int Q2table[64] = { 8, 36, 36, 36, 36, 36, 36, 36, // 0 - 7 36, 36, 39, 37, 38, 37, 39, 45, // 8 - 15 41, 42, 42, 41, 45, 53, 47, 47, // 16 -23 50, 47, 47, 53, 65, 56, 54, 59, // 24 - 31 59, 54, 56, 65, 68, 64, 69, 73, // 32 - 39 69, 64, 68, 78, 81, 89, 89, 81, // 40 - 47 78, 98, 108, 115, 108, 98, 130, 144, // 48 - 55 144, 130, 178, 190, 178, 243, 243, 255 // 56 - 63 }; const static int Q3table[64] = { 8, 10, 10, 10, 10, 10, 10, 10, // 0 - 7 10, 10, 11, 10, 11, 10, 11, 13, // 8 - 15 11, 12, 12, 11, 13, 15, 13, 13, // 16 - 23 14, 13, 13, 15, 18, 16, 15, 16, // 24 - 31 16, 15, 16, 18, 19, 18, 19, 21, // 32 - 39 19, 18, 19, 22, 23, 25, 25, 23, // 40 - 47 22, 27, 30, 32, 30, 27, 36, 40, // 48 - 56 40, 36, 50, 53, 50, 68, 68, 91 // 57 - 63 }; const static int Q4table[64] = { 8, 7, 7, 7, 7, 7, 7, 7, // 0 - 7 7, 7, 8, 7, 8, 7, 8, 9, // 8 - 15 8, 8, 8, 8, 9, 11, 9, 9, // 16 - 23 10, 9, 9, 11, 13, 11, 11, 12, // 24 - 31 12, 11, 11, 13, 14, 13, 14, 15, // 32 - 39 14, 13, 14, 16, 16, 18, 18, 16, // 40 - 47 16, 20, 22, 23, 22, 20, 26, 29, // 48 - 55 29, 26, 36, 38, 36, 49, 49, 65 // 56 - 63 }; const static int Q5table[64] = { 4, 4, 4, 4, 4, 4, 4, 4, // 0 - 7 4, 4, 4, 4, 4, 4, 4, 5, // 8 - 15 5, 5, 5, 5, 5, 6, 5, 5, // 16 - 23 6, 5, 5, 6, 7, 6, 6, 6, // 24 - 31 6, 6, 6, 7, 8, 7, 8, 8, // 32 - 39 8, 7, 8, 9, 9, 10, 10, 9, // 40 - 47 9, 11, 12, 13, 12, 11, 14, 16, // 48 - 55 16, 14, 20, 21, 20, 27, 27, 36 // 56 - 63 }; const static int* QTABLE_ARRAY[5]={Q1table,Q2table,Q3table,Q4table,Q5table}; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimJpegMemDest.h000066400000000000000000000027751352751253100235060ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: See top level LICENSE.txt file. // // Author: Oscar Kramer, original code from Thomas G. Lane // // Most of code and comments below are from jpeg-6b "example.c" file. See // http://www4.cs.fau.de/Services/Doc/graphics/doc/jpeg/libjpeg.html // // Description: // Code interfaces to use with jpeg-6b library to write a jpeg image from memory. //---------------------------------------------------------------------------- // $Id$ #ifndef ossimJpegMemDest_HEADER #define ossimJpegMemDest_HEADER 1 #include /** for OSSIM_DLL export macro */ #include /* std::ostream& */ // Forward declaration: struct jpeg_compress_struct; #if 0 /* Avoiding jpeg library includes in header files. */ #include /** for std::ostream */ #include /** for size_t */ #include /** for jmp_buf */ extern "C" { #if defined(_MSC_VER) || defined(__MINGW32__) # ifndef XMD_H # define XMD_H # endif #endif // #include /** for jpeg stuff */ } #endif /* End: #if 0 */ /** * @brief Method which uses memory instead of a FILE* to write to. * @note Used in place of "jpeg_stdio_dest(&cinfo, outfile)". */ // OSSIM_DLL void jpeg_cpp_stream_dest (j_compress_ptr cinfo, std::ostream& stream); OSSIM_DLL void jpeg_cpp_stream_dest (jpeg_compress_struct* cinfo, std::ostream& stream); #endif /* #ifndef ossimJpegMemDest_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimJpegMemSrc.h000066400000000000000000000022521352751253100233240ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: See top level LICENSE.txt file. // // Author: David Burken, original code from Thomas G. Lane // // Description: // Code interfaces to use with jpeg-6b library to read a jpeg image from // memory. //---------------------------------------------------------------------------- // $Id$ #ifndef ossimJpegMemSrc_HEADER #define ossimJpegMemSrc_HEADER 1 #include /** for OSSIM_DLL export macro */ #include /* size_t */ // Forward declaration: struct jpeg_common_struct; struct jpeg_decompress_struct; extern "C" { /** * @brief Error routine that will replace jpeg's standard error_exit method. */ OSSIM_DLL void ossimJpegErrorExit (jpeg_common_struct* cinfo); /** * @brief Method which uses memory instead of a FILE* to read from. * @note Used in place of "jpeg_stdio_src(&cinfo, infile)". * @note "unsigned char = JOCTET */ OSSIM_DLL void ossimJpegMemorySrc (jpeg_decompress_struct* cinfo, const ossim_uint8* buffer, std::size_t bufsize); } #endif /* #ifndef ossimJpegMemSrc_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimJpegStdIOSrc.h000066400000000000000000000024021352751253100235650ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: See top level LICENSE.txt file. // // Author: David Burken, original code from Thomas G. Lane // // Description: // Code interfaces to use with jpeg-6b library to read a jpeg image from // memory. //---------------------------------------------------------------------------- // $Id$ #ifndef ossimJpegStdIOSrc_HEADER #define ossimJpegStdIOSrc_HEADER #include /** for OSSIM_DLL export macro */ #include /* For FILE* */ struct jpeg_decompress_struct; extern "C" { // #include /** for size_t */ // #include /** for jmp_buf */ // #include /** for jpeg stuff */ //#include //#include /** * @brief Method which uses memory instead of a FILE* to read from. * @note Used in place of "jpeg_stdio_src(&cinfo, infile)". */ /* OSSIM_DLL void ossimJpegStdIOSrc ( j_decompress_ptr cinfo, FILE* infile); */ OSSIM_DLL void ossimJpegStdIOSrc ( jpeg_decompress_struct* cinfo, FILE* infile); } #endif /* #ifndef ossimJpegMemSrc_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimJpegTileSource.h000066400000000000000000000152341352751253100242200ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration for JpegTileSource. // JpegTileSource is derived from ImageHandler which is derived from // TileSource. //******************************************************************* // $Id: ossimJpegTileSource.h 22117 2013-01-18 21:04:23Z dburken $ #ifndef ossimJpegTileSource_HEADER #define ossimJpegTileSource_HEADER #include #include class ossimImageData; class OSSIM_DLL ossimJpegTileSource : public ossimImageHandler { public: ossimJpegTileSource(); ossimJpegTileSource(const ossimKeywordlist& kwl, const char* prefix=0); ossimJpegTileSource(const char* jpeg_file); virtual ossimString getShortName() const; virtual ossimString getLongName() const; /** * Returns a pointer to a tile given an origin representing the upper * left corner of the tile to grab from the image. * Satisfies pure virtual from TileSource class. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Returns the number of bands in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; /** * Returns the number of bands in a tile returned from this TileSource. * Note: we are supporting sources that can have multiple data objects. * If you want to know the scalar type of an object you can pass in the */ virtual ossim_uint32 getNumberOfOutputBands()const; /** * Returns the number of lines in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; /** * Returns the number of samples in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; /** * Returns the zero based image rectangle for the reduced resolution data * set (rrds) passed in. Note that rrds 0 is the highest resolution rrds. */ virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; bool isValidRLevel(ossim_uint32 reduced_res_level) const; bool isOpen()const; /** * Returns true if the image_file can be opened and is a valid tiff file. */ bool open(const ossimFilename& jpeg_file); virtual void close(); /** * @brief Gets a property for matching name. * @param name The name of the property to get. * @return Returns property matching "name". */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Gets a list of property names available. * @param propertyNames The list to push back names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; /** * Returns the image geometry object associated with this tile source or * NULL if non defined. The geometry contains full-to-local image * transform as well as projection (image-to-world). */ virtual ossimRefPtr getImageGeometry(); protected: /** * @param Method to get geometry from the xml file or internal geotiff * tags. */ virtual ossimRefPtr getInternalImageGeometry() const; virtual ~ossimJpegTileSource(); class PrivateData; /** * Returns true if no errors initializing object. * * Notes: * - Callers of this method must ensure "theTiffPtr" data member * is initialized. * - This method was added to consolidate object initialization code * between constructor and public open method. */ virtual bool open(); void allocate(); void destroy(); void restart(); /** * @note this method assumes that setImageRectangle has been called on * theTile. */ void fillTile(const ossimIrect& clip_rect, ossimImageData* tile); ossimRefPtr theTile; ossimRefPtr theCacheTile; ossim_uint8* theLineBuffer; FILE* theFilePtr; ossimIrect theBufferRect; ossimIrect theImageRect; ossim_uint32 theNumberOfBands; ossimIpt theCacheSize; PrivateData* thePrivateData; ossimAppFixedTileCache::ossimAppFixedCacheId theCacheId; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimJpegWriter.h000066400000000000000000000061061352751253100234140ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class definition for JpegWriter. // //******************************************************************* // $Id: ossimJpegWriter.h 16597 2010-02-12 15:10:53Z dburken $ #ifndef ossimJpegWriter_HEADER #define ossimJpegWriter_HEADER #include #include //******************************************************************* // CLASS: ossimJpegWriterFactory //******************************************************************* class OSSIMDLLEXPORT ossimJpegWriter : public ossimImageFileWriter { public: /** default constructor */ ossimJpegWriter(); /** * void getImageTypeList(std::vector& imageTypeList)const * * Appends this writer image types to list "imageTypeList". * * This writer only has one type "jpeg". * * @param imageTypeList stl::vector list to append to. */ virtual void getImageTypeList(std::vector& imageTypeList)const; /** * Sets the jpeg compression quality. * * @param quality Compression quality. (valid range is 1 to 100) */ virtual void setQuality(ossim_int32 quality); virtual bool isOpen()const; virtual bool open(); virtual void close(); /** * saves the state of the object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Will set the property whose name matches the argument * "property->getName()". * * @param property Object containing property to set. */ virtual void setProperty(ossimRefPtr property); /** * @param name Name of property to return. * * @returns A pointer to a property object which matches "name". */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * Pushes this's names onto the list of property names. * * @param propertyNames array to add this's property names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; /** * Returns a 3-letter extension from the image type descriptor * (theOutputImageType) that can be used for image file extensions. * * @param imageType string representing image type. * * @return the 3-letter string extension. */ virtual ossimString getExtension() const; bool hasImageType(const ossimString& imageType) const; protected: /** virtual destructor */ virtual ~ossimJpegWriter(); private: virtual bool writeFile(); ossim_int32 theQuality; FILE* theOutputFilePtr; TYPE_DATA }; #endif /* #ifndef ossimJpegWriter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimJpegYCbCrToRgbSource.h000066400000000000000000000017761352751253100252310ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimJpegYCbCrToRgbSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimJpegYCbCrToRgbSource_HEADER #define ossimJpegYCbCrToRgbSource_HEADER #include class ossimJpegYCbCrToRgbSource : public ossimImageSourceFilter { public: ossimJpegYCbCrToRgbSource(); ossimJpegYCbCrToRgbSource(ossimImageSource* inputSource); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual void initialize(); protected: virtual ~ossimJpegYCbCrToRgbSource(); virtual void allocate(); ossimRefPtr theBlankTile; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimKMeansFilter.h000066400000000000000000000137021352751253100236560ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef ossimKMeansFilter_HEADER #define ossimKMeansFilter_HEADER #include #include #include class ossimImageData; class ossimImageSourceSequencer; class ossimHistogram; /*************************************************************************************************** * * This class provides a pixel classification capability using the traditional K-means scheme for * partitioning datasets into K distinct clusters according to pixel value. The output tile consists * of the input pixels remapped according to their classification to a digital number representing * the cluster. Null pixels are ignored and left null. * * The caller can set the digital values representing the classification clusters. Otherwise they are * mapped to integers 1, 2, ..., K. * * The output pixel type will be the minimum necessary to hold K clusters + null pixel. Typically * this would be UInt8. Multiple bands are treated separately, so the number of output bands is * the same as the number of input bands. * * This filter requires a histogram for the input source. If none is provided, one is computed. * * A common use for this class is for thresholding an image based on the histogram. This corresponds * to K=2. The threshold point can be left at the default boundary between the two clusters, or * alternatively, can be set to some standard deviation departure from one of the cluster's mean. * See setThreshold() for this specific use case. * * Important Note: * The histogram provided (or computed) should reflect all of the pixels that will be processed * over multiple calls to getTile(). In other words, it doesn't compute the clustering on * a per-tile basis, since that would cause each tile running through to use a different * classification criteria. Therefore, it is important that if a sub-image AOI is being used by the * output sink, the cut-rect filter needs to be inserted on the input-side of this filter so that it * only considers pixels in the AOI. Alternatively, the AOI (in pixel coordinates) can be specified * to this class directly and only those pixels in the AOI will be used in computing a histogram * for use in the clustering. * **************************************************************************************************/ class OSSIM_DLL ossimKMeansFilter : public ossimImageSourceFilter { public: enum ThresholdMode { NONE=0, MEAN=1, SIGMA_WEIGHTED=2, VARIANCE_WEIGHTED=3 }; ossimKMeansFilter(); /** * Quicker constructor handles connections to source and optional histogram. */ ossimKMeansFilter(ossimImageSource* input_source, ossimMultiBandHistogram* histogram=0); ~ossimKMeansFilter(); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual ossimScalarType getOutputScalarType() const; /** * Sets the input source's histogram for quicker K-means analysis. */ void setInputHistogram(ossimMultiBandHistogram* histo); /** * Defines how many classification clusters will be resolved. The input connection should be made * prior so that the number of bands is known. * LIMITATION: Curently, only K values < 256 are supported. */ void setNumClusters(ossim_uint32 K); /** * Optionally define the output digital numbers for each cluster to be used for remapping the * input pixels. K is the size of the array, resetting any previously set K value. If * thresholding enabled (see setThreshold()), then only the first two values are referenced. * LIMITATION: Curently, only UInt8 supported, so dns and K values must be 0-255. */ void setClusterPixelValues(const ossim_uint32* dns, ossim_uint32 K); /** * Special use case is to use K-means for thresholding an image into two values based on * the histogram's clustering. The threshold point can be left at the default boundary between * clusters, or alternatively, can be computed according to predefined modes. Currently support * the following modes (where mn and sn is the mean and sigma of nth cluster, respectively): * * NONE Implies MEAN for multiple clusters. * MEAN (m0 + m1)/2 * SIGMA_WEIGHTED (s1*m0 + s0*m1)/(s0 + s1) * VARIANCE_WEIGHTED (s1*s1*m0 + s0*s0*m1)/(s0*s0 + s1*s1) */ void setThresholdMode(ThresholdMode mode); /** * Callers may be interested in reporting the cluster statistics computed by this class. Returns * the clusters (of size K) for the band index specified. */ const ossimKMeansClustering* getBandClassifier(ossim_uint32 band=0) const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void initialize(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); protected: bool computeKMeans(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); void clear(); std::vector > m_classifiers; //! Have num_bands entries ossimRefPtr m_histogram; ossim_uint32 m_numClusters; // a.k.a. K std::vector m_pixelValues; std::vector m_minPixelValue; std::vector m_maxPixelValue; ossimRefPtr m_tile; ossimScalarType m_outputScalarType; bool m_initialized; ThresholdMode m_thresholdMode; std::vector m_thresholds; TYPE_DATA }; #endif /* #ifndef ossimKMeansFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimKakaduCompressorInterface.h000066400000000000000000000075571352751253100264430ustar00rootroot00000000000000//--- // // License: MIT // Author: David Burken // Description: Interface for Kakadu compressor. // //--- // $Id$ #ifndef ossimKakaduCompressorInterface_HEADER #define ossimKakaduCompressorInterface_HEADER 1 #include #include #include class ossimImageData; class ossimIpt; class ossimIrect; class ossimNitfJ2klraTag; class ossimProperty; /** * @class GeoPackage writer interface. * * This interface is for using the ossimKakaduCompressor outside of the * kakadu plugin. */ class OSSIM_DLL ossimKakaduCompressorInterface { public: // Matches static "COMPRESSION_QUALITY" string array in .cpp. enum ossimKakaduCompressionQuality { // Prefixed with OKP for OSSIM Kakadu Plugin to avoid clashes. OKP_UNKNOWN = 0, OKP_USER_DEFINED = 1, OKP_NUMERICALLY_LOSSLESS = 2, OKP_VISUALLY_LOSSLESS = 3, OKP_LOSSY = 4, OKP_LOSSY2 = 5, OKP_LOSSY3 = 6, OKP_EPJE = 7, // Exploitation Preferred J2K Encoding }; /** * GP: I had to add this or windows would not link with the latest * compiler. Also had to put in dot.cpp for debug mode(again windows). * (drb) */ ossimKakaduCompressorInterface(); /** * @brief Create method. * @param os Stream to write to. * @param scalar Scalar type of source tiles to be fed to compressor. * @param bands Number of bands in source tiles to be fed to compressor. * @param imageRect The image rectangle. * @param tileSize The size of a tile. * @param tilesTileWrite The number of tiles to be written. * If zero, the tlm marker segment will not be used. * @param jp2 If true jp2 header and jp2 geotiff block will be written out. * @note Throws ossimException on error. */ virtual void create(ossim::ostream* os, ossimScalarType scalar, ossim_uint32 bands, const ossimIrect& imageRect, const ossimIpt& tileSize, ossim_uint32 tilesToWrite, bool jp2) = 0; /** * @brief Write tile method. * * Writes tiles stream provided to create method. Note that tiles should * be fed to compressor in left to right, top to bottom order. * * @param srcTile The source tile to write. * * @return true on success, false on error. */ virtual bool writeTile(ossimImageData& srcTile) = 0; /** * @brief Finish method. Every call to "create" should be matched by a * "finish". Note the destructor calls finish. */ virtual void finish() = 0; /** * Set the writer to add an alpha channel to the output. * * @param flag true to create an alpha channel. */ virtual void setAlphaChannelFlag( bool flag ) = 0; /** * @brief Sets the number of levels. * * This must be positive and at least 1. * Default = 5 ( r0 - r5 ) * * @param levels Levels to set. */ virtual void setLevels(ossim_int32 levels) = 0; /** * Will set the property whose name matches the argument * "property->getName()". * * @param property Object containing property to set. * * @return true if property was consumed, false if not. */ virtual bool setProperty(ossimRefPtr property) = 0; /** * @brief Sets the quality type. * * Type enumerations: * OKP_UNKNOWN = 0, * OKP_USER_DEFINED = 1, * OKP_NUMERICALLY_LOSSLESS = 2, * OKP_VISUALLY_LOSSLESS = 3, * OKP_EPJE = 4 * * @param type See enumeration for types. */ virtual void setQualityType(ossimKakaduCompressionQuality type) = 0; }; #endif /* End of "#ifndef ossimKakaduCompressorInterface_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimLandsatTileSource.h000066400000000000000000000046711352751253100247240ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class definition for the class "ossimLandsatTileSource". // ossimLandsatTileSource is derived from ImageHandler which is derived from // TileSource. // //******************************************************************* // $Id: ossimLandsatTileSource.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimLandsatTileSource_HEADER #define ossimLandsatTileSource_HEADER #include #include #include class OSSIM_DLL ossimLandsatTileSource : public ossimGeneralRasterTileSource { public: ossimLandsatTileSource(); ossimLandsatTileSource(const ossimKeywordlist& kwl, const char* prefix=0); virtual ossimString getShortName() const; virtual ossimString getLongName() const; virtual bool open(); virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual ossimScalarType getOutputScalarType() const; bool getAcquisitionDate(ossimDate& date)const; ossimString getSatelliteName()const; ossimFilename getBandFilename(ossim_uint32 idx)const; bool isPan()const; bool isVir()const; bool isTm()const; //! Returns the image geometry object associated with this tile source or NULL if non defined. //! The geometry contains full-to-local image transform as well as projection (image-to-world) virtual ossimRefPtr getImageGeometry(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = NULL); /** * @brief Gets a property for matching name. * @param name The name of the property to get. * @return Returns property matching "name". */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Gets a list of property names available. * @param propertyNames The list to push back names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; private: virtual ~ossimLandsatTileSource(); void openHeader(const ossimFilename& file); ossimRefPtr theFfHdr; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimLandsatTopoCorrectionFilter.h000066400000000000000000000026541352751253100267640ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimLandsatTopoCorrectionFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimLandsatTopoCorrectionFilter_HEADER #define ossimLandsatTopoCorrectionFilter_HEADER #include #include class OSSIM_DLL ossimLandsatTopoCorrectionFilter : public ossimTopographicCorrectionFilter { public: ossimLandsatTopoCorrectionFilter(); ossimLandsatTopoCorrectionFilter(ossimImageSource* colorSource, ossimImageSource* elevSource, const ossimFilename& landsatFileName=ossimFilename("")); virtual void initialize(); virtual void setLandsatHeader(const ossimFilename& header); virtual ossimFilename getLandsatHeader()const { return theLandsatHeader; } virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: virtual ~ossimLandsatTopoCorrectionFilter(); ossimFilename theLandsatHeader; ossimFilename findLandsatHeader(); // virtual void computeC(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimLasReader.h000066400000000000000000000237431352751253100232020ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasReader.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimLasReader_HEADER #define ossimLasReader_HEADER 1 #include #include #include #include #include #include #include #include class ossimLasHdr; class ossimLasPointRecordInterface; /** * @class ossimLasReader * * OSSIM LAS LIDAR reader. */ class ossimLasReader : public ossimImageHandler { public: /** default constructor */ ossimLasReader(); /** virtual destructor */ virtual ~ossimLasReader(); /** * @brief open method. * * Satisfies ossimImageHandler::open pure virtual. * * @return Returns true on success, false on error. * * @note This method relies on the data member ossimImageData::theImageFile * being set. Callers should do a "setFilename" prior to calling this * method or use the ossimImageHandler::open that takes a file name and an * entry index. */ virtual bool open(); /** * @brief is open method. * * Satisfies ossimImageHandler::isOpen pure virtual. * * @return true if open, false if not. */ virtual bool isOpen()const; /** * @brief Close method. */ virtual void close(); /** * Returns a pointer to a tile given an origin representing the upper left * corner of the tile to grab from the image. * Satisfies pure virtual from TileSource class. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * @brief Gets bands. * * Satisfies ossimImageSource::getNumberOfInputBands pure virtual. * * @retrun Number of bands. */ virtual ossim_uint32 getNumberOfInputBands() const; /** * @brief Gets lines. * * Satisfies ossimImageHandler::getNumberOfLines pure virtual. * * @param resLevel Reduced resolution level to return lines of. * Default = 0 * * @return The number of lines for specified reduced resolution level. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 resLevel = 0) const; /** * @brief Gets samples. * * Satisfies ossimImageHandler::getNumberOfSamples * * @param resLevel Reduced resolution level to return samples of. * Default = 0 * * @return The number of samples for specified reduced resolution level. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 resLevel = 0) const; /** * @brief Gets tile width. * * Satisfies ossimImageHandler::getImageTileWidth pure virtual. * * @return The tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * @brief Gets tile height. * * Satisfies ossimImageHandler::getImageTileHeight pure virtual. * * @return The tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; /** @return The width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** @returns The height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** @return The output pixel type of the tile source. */ ossimScalarType getOutputScalarType() const; /** * @brief Gets entry list. * @param entryList This is the list to initialize with entry indexes. */ virtual void getEntryList(std::vector& entryList) const; /** @return The current entry number. */ virtual ossim_uint32 getCurrentEntry() const; /** * @param entryIdx Entry number to select. * @return true if it was able to set the current entry and false otherwise. */ virtual bool setCurrentEntry(ossim_uint32 entryIdx); /** @return "las" */ virtual ossimString getShortName() const; /** @return "ossim las (liblas) reader" */ virtual ossimString getLongName() const; /** * Returns the image geometry object associated with this tile source or * NULL if non defined. The geometry contains full-to-local image * transform as well as projection (image-to-world). */ virtual ossimRefPtr getImageGeometry(); /** @return Min pixel value. */ virtual double getMinPixelValue(ossim_uint32 band=0) const; /** @return Min pixel value. */ virtual double getMaxPixelValue(ossim_uint32 band=0) const; /** @return Min pixel value. */ virtual double getNullPixelValue(ossim_uint32 band=0) const; /** * @brief Method to save the state of an object to a keyword list. * @return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * @brief Method to the load (recreate) the state of an object from a keyword list. * @return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @brief Set propterty method. Overrides ossimImageHandler::setProperty. * * Current property name handled: * "scale" One double value representing the scale in meters per pixel. It is * assumed the scale is same for x and y direction. * * @param property to set. */ virtual void setProperty(ossimRefPtr property); /** * @brief Get propterty method. Overrides ossimImageHandler::getProperty. * @param name Property name to get. */ virtual ossimRefPtr getProperty(const ossimString& name) const; /** * @brief Get propterty names. Overrides ossimImageHandler::getPropertyNames. * @param propertyNames Array to initialize. */ virtual void getPropertyNames(std::vector& propertyNames) const; /** @return The total number of decimation levels. */ virtual ossim_uint32 getNumberOfDecimationLevels() const; virtual ossim_uint32 getNumberOfOutputBands() const; protected: /** * @brief Will complete the opening process. * * Overrides ossimImageHandler::completeOpen() as we do not ever have overviews. */ virtual void completeOpen(); private: /** * @brief Container class to hold accumulated point data. Currently single * band. */ class Bucket { public: Bucket(): a(0.0), c(0), red(0), green(0), blue(0) {} void add(const ossim_float64& point) { a += point; ++c; } ossim_float64 getValue() const { return ( c ? a/c : -99999.0 ); } void setRed(const ossim_uint16& value) { red = value; } void setGreen(const ossim_uint16& value) { green = value; } void setBlue(const ossim_uint16& value) { blue = value; } void setIntensity(const ossim_uint16& value) { intensity = value; } ossim_uint16 getRed() const { return red; } ossim_uint16 getGreen() const { return green; } ossim_uint16 getBlue() const { return blue; } ossim_uint16 getIntensity() const { return intensity; } ossim_float64 a; // accumulation ossim_uint32 c; // count ossim_uint16 red; ossim_uint16 green; ossim_uint16 blue; ossim_uint16 intensity; }; bool init(); void initValues(); // m_ul, m_lr, m_minZ bool initProjection(); void initTile(); void initUnits(const ossimKeywordlist& geomKwl); bool parseVarRecords(); /** * @brief Looks for external FGDC text file to initialize projection from. */ bool initFromExternalMetadata(); /** @brief Get the scale for resLevel. */ void getScale(ossimDpt& scale, ossim_uint32 resLevel) const; /** @brief Sets m_gsd data member and projection if projection is set. */ void setGsd( const ossim_float64& gsd ); void convertToMeters(ossim_float64& value) const; /** * Returns a point of type. */ ossimLasPointRecordInterface* getNewPointRecord() const; std::ifstream m_str; ossimLasHdr* m_hdr; ossimRefPtr m_proj; ossimDpt m_ul; ossimDpt m_lr; ossim_float64 m_maxZ; ossim_float64 m_minZ; ossimDpt m_gsd; ossimRefPtr m_tile; ossim_uint8 m_entry; std::mutex m_mutex; bool m_scan; // Scan for bounds at open. ossimUnitType m_units; ossimUnitConversionTool* m_unitConverter; TYPE_DATA }; inline bool ossimLasReader::isOpen()const { return ( m_str.is_open() && m_hdr ); } inline void ossimLasReader::convertToMeters(ossim_float64& value) const { if ( value ) { m_unitConverter->setValue(value, m_units); value = m_unitConverter->getMeters(); } } #endif /* #ifndef ossimLasReader_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimLinearStretchRemapper.h000066400000000000000000000046431352751253100256010ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //************************************************************************* // $Id: ossimLinearRemapper.h 23616 2015-11-11 19:50:29Z dburken $ #ifndef ossimLinearRemapper_HEADER #define ossimLinearRemapper_HEADER #include #include #include #include class ossimImageData; /*************************************************************************************************** * * This class provides a linear remap between a min and a max value. Default is to do a linear * stretch between the input connection's min and max, but the user can also define specific min * and max. In the latter case, the input pixels outside the range will be clamped. * * If non-default min and max values are to be used, the min and max values must be set for all * bands, otherwise the defaults will be used for all bands. * * The output scalar type is normalized double. * **************************************************************************************************/ class OSSIM_DLL ossimLinearStretchRemapper : public ossimImageSourceFilter { public: ossimLinearStretchRemapper(); virtual ~ossimLinearStretchRemapper(); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); void setMinPixelValue(double value, ossim_uint32 band=0); void setMaxPixelValue(double value, ossim_uint32 band=0); virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void initialize(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); virtual ossimScalarType getOutputScalarType() const { return OSSIM_NORMALIZED_DOUBLE; } protected: /** * Called on first getTile, will initialize all data needed. */ void allocate(); std::vector m_minValues; std::vector m_maxValues; ossimRefPtr m_tile; TYPE_DATA }; #endif /* #ifndef ossimLinearRemapper_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimLocalCorrelationFusion.h000066400000000000000000000062331352751253100257530ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // LICENSE: See top level LICENSE.txt // // Author: Garrett Potts // //******************************************************************* // $Id: ossimLocalCorrelationFusion.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimLocalCorrelationFusion_HEADER #define ossimLocalCorrelationFusion_HEADER #include #include #include #include /** * This implements a Local correlation fusion based on the paper: * * "A Local Correlation Approach For the Fusion of Remote Sensing Data With Different * Spatial Resolution In Forestry Applications" * by J. Hill, C. Diemer, O. Stover, and Th. Udelhoven * Published in: * International Archives of Photogrammetry and Remote Sensing, Vol 32, Part 7-4-3 W6, * Valladolid, Spain, 3-4 June, 1999 * * A new band is computed by the formula: * * ColorHigh = ColorLow + RegressionSlope*(PanHigh-PanLow); * * Adjustable paraemters have been added to clamp the regression slope and attenuate * colorLowOffset value and blurring the Pan. * * ColorHigh = ColorLow + Clamp(RegressionSlope)*Attenuator(PanHigh-PanLow); * * The regression coefficient is coputed for each color band. */ class OSSIM_DLL ossimLocalCorrelationFusion : public ossimFusionCombiner, public ossimAdjustableParameterInterface { public: ossimLocalCorrelationFusion(); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual void initialize(); virtual ossimObject* getBaseObject() { return this; } virtual const ossimObject* getBaseObject()const { return this; } virtual void initAdjustableParameters(); virtual void adjustableParametersChanged(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimLocalCorrelationFusion(); void setFilters(); bool computeRegression(ossim_float64& slopeResult, const ossimIpt& origin, ossimRefPtr panData, ossimRefPtr colorData, ossim_uint32 colorBandIdx); ossim_float64 theBlurrKernelWidth; ossim_uint32 theHighPassKernelWidth; ossim_uint32 theRegressionWidth; // These are low and high pass filters for the single pan band // ossimRefPtr theLowPassFilter; ossimRefPtr theHighPassFilter; ossimRefPtr theNormLowPassTile; ossimRefPtr theNormHighPassTile; ossimRefPtr theNormColorData; NEWMAT::Matrix theHighPassMatrix; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimMapCompositionSource.h000066400000000000000000000317631352751253100254630ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimMapCompositionSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimMapCompositionSource_HEADER #define ossimMapCompositionSource_HEADER #include #include #include #include #include class ossimFont; class ossimMapProjection; class ossimU8ImageData; class ossimMapCompositionSource : public ossimAnnotationSource { public: enum ossimGridLineType { OSSIM_GRID_NONE = 0, OSSIM_GRID_LINE = 1, OSSIM_GRID_RESEAUX = 2 }; ossimMapCompositionSource(); virtual ossimScalarType getOutputScalarType() const; virtual ossim_uint32 getNumberOfOutputBands() const; virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); ossimIpt getViewWidthHeight()const; void getViewWidthHeight(ossimIpt& widthHeight)const; void setViewWidthHeight(const ossimIpt& widthHeight); // all borders here virtual ossim_int32 getTopBorderLength()const; virtual ossim_int32 getBottomBorderLength()const; virtual ossim_int32 getLeftBorderLength()const; virtual ossim_int32 getRightBorderLength()const; virtual void setTopBorderLength(ossim_int32 length); virtual void setBottomBorderLength(ossim_int32 length); virtual void setLeftBorderLength(ossim_int32 length); virtual void setRightBorderLength(ossim_int32 length); //all spacing here void setGeographicSpacingLat(double value); void setGeographicSpacingLon(double value); void setMeterSpacingX(double value); void setMeterSpacingY(double value); void setMeterSpacing(double x, double y); void setGeographicSpacing(double lat, double lon); ossimDpt getGeographicSpacing()const; ossimDpt getMeterSpacing()const; // All geographic formatting here virtual ossimString getTopGeographicLabelFormat()const; virtual ossimString getBottomGeographicLabelFormat()const; virtual ossimString getLeftGeographicLabelFormat()const; virtual ossimString getRightGeographicLabelFormat()const; virtual void setGeographicLabelFormat(const ossimString format); virtual void setTopGeographicLabelFormat(const ossimString& format); virtual void setBottomGeographicLabelFormat(const ossimString& format); virtual void setLeftGeographicLabelFormat(const ossimString& format); virtual void setRightGeographicLabelFormat(const ossimString& format); // All font funtions here. virtual ossimString getTitle()const; virtual ossimRgbVector getTitleColor()const; virtual void setTitleFont(const ossimFontInformation& fontInfo); virtual void setTitleColor(const ossimRgbVector& color); virtual void setTitle(const ossimString& s); virtual void setGeographicTopLabelFont(const ossimFontInformation& fontInfo); virtual void setGeographicBottomLabelFont(const ossimFontInformation& fontInfo); virtual void setGeographicLeftLabelFont(const ossimFontInformation& fontInfo); virtual void setGeographicRightLabelFont(const ossimFontInformation& fontInfo); virtual void setMeterTopLabelFont(const ossimFontInformation& fontInfo); virtual void setMeterBottomLabelFont(const ossimFontInformation& fontInfo); virtual void setMeterLeftLabelFont(const ossimFontInformation& fontInfo); virtual void setMeterRightLabelFont(const ossimFontInformation& fontInfo); virtual ossimFontInformation getTitleFont()const; virtual ossimFontInformation getGeographicTopLabelFontInfo()const; virtual ossimFontInformation getGeographicBottomLabelFontInfo()const; virtual ossimFontInformation getGeographicLeftLabelFontInfo()const; virtual ossimFontInformation getGeographicRightLabelFontInfo()const; virtual ossimFontInformation getMeterTopLabelFontInfo()const; virtual ossimFontInformation getMeterBottomLabelFontInfo()const; virtual ossimFontInformation getMeterLeftLabelFontInfo()const; virtual ossimFontInformation getMeterRightLabelFontInfo()const; // All color funtions here virtual ossimRgbVector getBorderColor()const; virtual void setBorderColor(const ossimRgbVector& color); virtual ossimRgbVector getGeographicGridColor()const; virtual ossimRgbVector getMeterGridColor()const; virtual ossimRgbVector getTopGeographicLabelColor()const; virtual ossimRgbVector getBottomGeographicLabelColor()const; virtual ossimRgbVector getLeftGeographicLabelColor()const; virtual ossimRgbVector getRightGeographicLabelColor()const; virtual void setGeographicGridColor(const ossimRgbVector& color); virtual void setTopGeographicLabelColor(const ossimRgbVector& color); virtual void setBottomGeographicLabelColor(const ossimRgbVector& color); virtual void setLeftGeographicLabelColor(const ossimRgbVector& color); virtual void setRightGeographicLabelColor(const ossimRgbVector& color); virtual void setGeographicLabelColor(const ossimRgbVector& color); virtual ossimRgbVector getTopMeterLabelColor()const; virtual ossimRgbVector getBottomMeterLabelColor()const; virtual ossimRgbVector getLeftMeterLabelColor()const; virtual ossimRgbVector getRightMeterLabelColor()const; virtual void setTopMeterLabelColor(const ossimRgbVector& color); virtual void setBottomMeterLabelColor(const ossimRgbVector& color); virtual void setLeftMeterLabelColor(const ossimRgbVector& color); virtual void setRightMeterLabelColor(const ossimRgbVector& color); virtual void setMeterLabelColor(const ossimRgbVector& color); virtual void setMeterGridColor(const ossimRgbVector& color); // All grid types here virtual void setMeterGridType(ossimGridLineType gridType); virtual void setGeographicGridType(ossimGridLineType gridType); virtual void setBorderColor(ossimRgbVector& color); virtual ossimGridLineType getGeographicGridType()const; virtual ossimGridLineType getMeterGridType()const; // all grid flags here void setGeographicTickMarkFlag(bool flag); void setTopGeographicTickMarkFlag(bool flag); void setBottomGeographicTickMarkFlag(bool flag); void setLeftGeographicTickMarkFlag(bool flag); void setRightGeographicTickMarkFlag(bool flag); void setTopGeographicLabelFlag(bool flag); void setBottomGeographicLabelFlag(bool flag); void setLeftGeographicLabelFlag(bool flag); void setRightGeographicLabelFlag(bool flag); virtual bool getTopGeographicTickMarkFlag()const; virtual bool getBottomGeographicTickMarkFlag()const; virtual bool getLeftGeographicTickMarkFlag()const; virtual bool getRightGeographicTickMarkFlag()const; virtual bool getTopGeographicLabelFlag()const; virtual bool getBottomGeographicLabelFlag()const; virtual bool getLeftGeographicLabelFlag()const; virtual bool getRightGeographicLabelFlag()const; void setMeterTickMarkFlag(bool flag); virtual void setTopMeterTickMarkFlag(bool flag); virtual void setBottomMeterTickMarkFlag(bool flag); virtual void setLeftMeterTickMarkFlag(bool flag); virtual void setRightMeterTickMarkFlag(bool flag); virtual void setTopMeterLabelFlag(bool flag); virtual void setBottomMeterLabelFlag(bool flag); virtual void setLeftMeterLabelFlag(bool flag); virtual void setRightMeterLabelFlag(bool flag); virtual bool getTopMeterTickMarkFlag()const; virtual bool getBottomMeterTickMarkFlag()const; virtual bool getLeftMeterTickMarkFlag()const; virtual bool getRightMeterTickMarkFlag()const; virtual bool getTopMeterLabelFlag()const; virtual bool getBottomMeterLabelFlag()const; virtual bool getLeftMeterLabelFlag()const; virtual bool getRightMeterLabelFlag()const; virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; virtual void initialize(); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimMapCompositionSource(); ossimIpt theViewWidthHeight; ossimGridLineType theMeterGridType; ossimGridLineType theGeographicGridType; ossim_uint32 theTopBorderLength; ossim_uint32 theBottomBorderLength; ossim_uint32 theLeftBorderLength; ossim_uint32 theRightBorderLength; ossimRgbVector theBorderColor; ossimRgbVector theGeographicGridColor; ossimRgbVector theMeterGridColor; // title info // ossimString theTitleString; ossimRefPtr theTitleFont; ossimFontInformation theTitleFontInfo; ossimRgbVector theTitleColor; // grid label colors // ossimRgbVector theTopGeographicLabelColor; ossimRgbVector theBottomGeographicLabelColor; ossimRgbVector theLeftGeographicLabelColor; ossimRgbVector theRightGeographicLabelColor; ossimRgbVector theTopMeterLabelColor; ossimRgbVector theBottomMeterLabelColor; ossimRgbVector theLeftMeterLabelColor; ossimRgbVector theRightMeterLabelColor; // grid label font // ossimFontInformation theGeographicTopLabelFontInfo; ossimRefPtr theGeographicTopLabelFont; ossimFontInformation theGeographicBottomLabelFontInfo; ossimRefPtr theGeographicBottomLabelFont; ossimFontInformation theGeographicLeftLabelFontInfo; ossimRefPtr theGeographicLeftLabelFont; ossimFontInformation theGeographicRightLabelFontInfo; ossimRefPtr theGeographicRightLabelFont; ossimFontInformation theMeterTopLabelFontInfo; ossimRefPtr theMeterTopLabelFont; ossimFontInformation theMeterBottomLabelFontInfo; ossimRefPtr theMeterBottomLabelFont; ossimFontInformation theMeterLeftLabelFontInfo; ossimRefPtr theMeterLeftLabelFont; ossimFontInformation theMeterRightLabelFontInfo; ossimRefPtr theMeterRightLabelFont; // grid label dms format strings // ossimString theTopGeographicFormat; ossimString theBottomGeographicFormat; ossimString theLeftGeographicFormat; ossimString theRightGeographicFormat; // grid label flag // bool theTopGeographicLabelFlag; bool theBottomGeographicLabelFlag; bool theLeftGeographicLabelFlag; bool theRightGeographicLabelFlag; bool theTopGeographicTickFlag; bool theBottomGeographicTickFlag; bool theLeftGeographicTickFlag; bool theRightGeographicTickFlag; bool theTopMeterLabelFlag; bool theBottomMeterLabelFlag; bool theLeftMeterLabelFlag; bool theRightMeterLabelFlag; bool theTopMeterTickFlag; bool theBottomMeterTickFlag; bool theLeftMeterTickFlag; bool theRightMeterTickFlag; ossimIrect theTopBorder; ossimIrect theBottomBorder; ossimIrect theLeftBorder; ossimIrect theRightBorder; // geo-tick spacing in lat lon ossimDpt theGeographicSpacing; // tick spacing in meter units ossimDpt theMeterSpacing; ossimAnnotationSource::AnnotationObjectListType theFixedAnnotationList; /*! * Override base classes drawAnnotations so we can layout * any fixed annotations first. */ virtual void drawAnnotations(ossimRefPtr tile); virtual void computeBorderRects(); virtual void drawBorders(); virtual void addGridLabels(); virtual void addGeographicTopGridLabels(); virtual void addGeographicBottomGridLabels(); virtual void addGeographicLeftGridLabels(); virtual void addGeographicRightGridLabels(); virtual void addGeographicGridLines(); virtual void addGeographicGridReseaux(); virtual void addMeterGridLabels(); virtual void addMeterGridLines(); virtual void addMeterGridReseaux(); virtual void addTitle(); virtual void layoutAnnotations(); virtual void addFixedAnnotation(ossimAnnotationObject* obj); virtual void deleteFixedAnnotations(); ossimIrect getViewingRect()const; //! Fetches the input connection's image geometry and verifies that it is a map projection. //! Returns NULL if no valid projection found. const ossimMapProjection* inputMapProjection() const; // For RTTI TYPE_DATA }; #endif /* #ifndef ossimMapCompositionSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimMaskFilter.h000066400000000000000000000230631352751253100233740ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // Modified by: Elan Sharghi (1/20/2009) // Description: Class declaration for ossimMaskFilter. // //************************************************************************* // $Id: ossimMaskFilter.h 20409 2011-12-22 16:57:05Z dburken $ #ifndef ossimMaskFilter_HEADER #define ossimMaskFilter_HEADER 1 #include /** *
     * class ossimMaskFilter
     *
     *    Requires 2 inputs.  The first input is assumed to be the image input
     *    and the second input is assumed to be the mask data.  It will only
     *    use one band of the mask and multi band masks are not supported.
     *
     *    the number of bands, min pix, max pix, null pix ...etc are mapped
     *    to the first input.
     *
     * Keywords:
     *    mask_type:
     *
     * keywords description: This keyword can have the following values:
     *    select, select_clamp, invert, weighted, binary, or binary_inverse
     *         
     *    - select will use the input data and every where
     *      the mask is greater than 0 it will copy the input to the output.
     *
     *    - select_clamp_min If mask pixel is non zero, output pixel is input
     *      pixel; else, null pixel value. Differs from select in that output
     *      pixel is clamped to min pixel if input pixel is used. 
     *      
     *    - invert will use the input data and every where the mask is 0 it
     *      will copy the input to the output else it will place a null in
     *      the output.
     *      
     *    - weighted will normalize the mask between 0 and 1 and then multiply
     *      the input by that normalized value and copy to the output.
     *
     *    - binary If mask pixel is non zero, output pixel is max pixel value;
     *      else, null.
     *
     *    - binary_inverse If mask pixel is non zero, output pixel is max pixel
     *      value; else, null pixel value. 
     *    
     * example of keywords:
     *
     *      mask_type: select
     *
     * 
*/ class OSSIMDLLEXPORT ossimMaskFilter : public ossimImageSource { public: /** * Enumeration used to identify what the selection type for this mask is to * be used: * * - OSSIM_MASK_TYPE_SELECT * If the mask is non zero then the input is kept if it's 0 then the input * is nulled out. * - OSSIM_MASK_TYPE_INVERT * If the input is non zero then the output is nulled else the input is kept * - OSSIM_MASK_TYPE_WEIGHTED * works as a multiplier of the input data. The mask is normalized to be * between 0 and 1 and multiplies the input by that normalized value. * - OSSIM_MASK_TYPE_BINARY * If mask pixel is non zero, output pixel is null pixel value; else, max * pixel value. * - OSSIM_MASK_TYPE_BINARY_INVERSE * If mask pixel is non zero, output pixel is max pixel value; else, null * pixel value. * - OSSIM_MASK_TYPE_SELECT_CLAMP_MIN * If mask pixel is non zero, output pixel is input pixel; else, null pixel * value. Differs from OSSIM_MASK_TYPE_SELECT in that output pixel is * clamped to min pixel if input pixel is used. The clampling has the * affect of flipping null pixels to min pixel value if the mask pixel is * non zero and input pixel is a null. */ enum ossimFileSelectionMaskType { /**< standard select if mask is true then keep */ OSSIM_MASK_TYPE_SELECT = 1, /**< standard invert if mask is true the don't keep */ OSSIM_MASK_TYPE_INVERT = 2, /**< weighted operation. Normalize the mask and multiply the input */ OSSIM_MASK_TYPE_WEIGHTED = 3, /**< binary image> */ OSSIM_MASK_TYPE_BINARY = 4, /**< inverse binary image> */ OSSIM_MASK_TYPE_BINARY_INVERSE = 5, /**< Standard select if mask is true then keep with min. */ OSSIM_MASK_TYPE_SELECT_CLAMP_MIN = 6, }; /** * Default Constructor. */ ossimMaskFilter(ossimObject* owner=NULL); /** * This set method is necessary when this object is being added to an ossimImageChain because * ossimImageChain::addLast() performs a disconnect of all the input sources, thus losing the * assignments made via constructor accepting source pointers. If the intent is to insert this * object in place of the image handler in a chain, First remove the handler from the chain, then * add a default-constructed mask filter object, then call this method to assign the inputs. */ void setMaskSource(ossimImageSource* maskSource); /** * Sets the mask type. * @param type The mask algorithm type to be used. * see ossimFileSelectionMaskType */ virtual void setMaskType(ossimFileSelectionMaskType type); /** * @brief Sets the mask type from string. * * Valid strings are: "select", "invert" and "weighted". * * @param type The mask algorithm type to be used. */ virtual void setMaskType(const ossimString& type); /** * Returns the current mask algorithm used. * \return the current ossimFileSelectionMaskType used. */ virtual ossimFileSelectionMaskType getMaskType() const; /** * @brief Returns the current mask algorithm used as a string. * @return the current ossimFileSelectionMaskType used. */ virtual ossimString getMaskTypeString() const; /** * Main entry point for the algorithm. * \param rect * */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual void initialize(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool canConnectMyInputTo(ossim_int32 index, const ossimConnectableObject* object)const; virtual ossim_uint32 getNumberOfInputBands() const; virtual ossimRefPtr executeMaskFilter( ossimRefPtr imageSourceData, ossimRefPtr maskSourceData); /** @brief Interface to set the mask type. */ virtual void setProperty(ossimRefPtr property); /** @return "mask_type" property. */ virtual ossimRefPtr getProperty( const ossimString& name)const; /** @brief Adds "mask_type" to list. */ virtual void getPropertyNames(std::vector& propertyNames)const; protected: /** * Will delete its owned tile. */ virtual ~ossimMaskFilter(); void allocate(); /** * will execute the section algorithm. everywhere the mask is not 0 it * copies the input data to the output and everywhere the input is null it * writes a null pixel to the output. */ ossimRefPtr executeMaskFilterSelect( ossimRefPtr imageSourceData, ossimRefPtr maskSourceData); /** * will execute the invert selection algorithm. everywhere the mask is 0 * it copies the input data to the output else it outputs null. */ ossimRefPtr executeMaskFilterInvertSelect( ossimRefPtr imageSourceData, ossimRefPtr maskSourceData); /** * will execute the weighted algorithm. It normalizes the mask value to * be between 0 and 1 and multiplies the input data by that value and * outputs it. */ ossimRefPtr executeMaskFilterWeighted( ossimRefPtr imageSourceData, ossimRefPtr maskSourceData); /** * Will execute the binary algorithm. Copies the values in the mask to each * tile. Values will be either NULL or MAX pixel value, typically 0 or 255. */ ossimRefPtr executeMaskFilterBinary( ossimRefPtr imageSourceData, ossimRefPtr maskSourceData); template ossimRefPtr executeMaskFilterSelection( inputT dummyInput, maskT dummyMask, ossimRefPtr imageSourceData, ossimRefPtr maskSourceData); template ossimRefPtr executeMaskFilterInvertSelection( inputT dummyInput, maskT dummyMask, ossimRefPtr imageSourceData, ossimRefPtr maskSourceData); template ossimRefPtr executeMaskFilterWeighted( inputT dummyInput, maskT dummyMask, ossimRefPtr imageSourceData, ossimRefPtr maskSourceData); template ossimRefPtr executeMaskFilterBinarySelection( inputT dummyInput, maskT dummyMask, ossimRefPtr imageSourceData, ossimRefPtr maskSourceData); /** * Member variable that holds the algorithm type to run on the calls to getTile. */ ossimFileSelectionMaskType theMaskType; /** * Member used to store the result of the applied algorithm type. This is returned * from the call to getTile. */ ossimRefPtr theTile; ossimRefPtr theMaskSource; TYPE_DATA }; #endif /* #ifndef ossimMaskFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimMaxMosaic.h000066400000000000000000000046101352751253100232110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 SANZ Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Kenneth Melero (kmelero@sanz.com) // // Description: This combiner is designed to "float" the maximum pixel value // of all inputs to the top of the mosaic output. // //************************************************************************* // $Id: ossimMaxMosaic.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimMaxMosaic_HEADER #define ossimMaxMosaic_HEADER #include #include /** * An image mosaic is a simple combiner that will * just do a simple mosaic. It just checks NULL pix values until it finds a * pixel that is not empty and copies it out to the output. The list will * have same size tiles and have the same number of bands. */ class OSSIMDLLEXPORT ossimMaxMosaic : public ossimImageCombiner { public: ossimMaxMosaic(); ossimMaxMosaic(ossimConnectableObject::ConnectableObjectList& inputSources); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual void initialize(); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual ossimString getShortName() const; virtual ossimString getLongName() const; virtual ossimString getDescription()const; protected: virtual ~ossimMaxMosaic(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); ossimRefPtr theTile; template ossimRefPtr combine( T, // dummy template variable not used const ossimIrect& tileRect, ossim_uint32 resLevel=0); template ossimRefPtr combineNorm( T, // dummy template variable not used const ossimIrect& tileRect, ossim_uint32 resLevel=0); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimMeanMedianFilter.h000066400000000000000000000101561352751253100244760ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimMeanMedianFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimMeanMedianFilter_HEADER #define ossimMeanMedianFilter_HEADER #include /*! * class ossimMeanMedianFilter * * Allows you to change between a median or mean filter. You can * also specify a window size which the median or mean is computed and * the center pixel is replaced. * */ class OSSIM_DLL ossimMeanMedianFilter : public ossimImageSourceFilter { public: enum ossimMeanMedianFilterType { /** Applies filter to any non-null center pixel. */ OSSIM_MEDIAN = 0, /** Applies filter to all pixels including null center pixels. */ OSSIM_MEDIAN_FILL_NULLS = 1, /** Applies filter to only null center pixels. */ OSSIM_MEDIAN_NULL_CENTER_ONLY = 2, /** Applies filter to any non-null center pixel. */ OSSIM_MEAN = 3, /* Applies filter to all pixels including null center pixels. */ OSSIM_MEAN_FILL_NULLS = 4, /** Applies filter to only null center pixels. */ OSSIM_MEAN_NULL_CENTER_ONLY = 5 }; ossimMeanMedianFilter(ossimObject* owner=NULL); virtual ~ossimMeanMedianFilter(); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual void initialize(); void setWindowSize(ossim_uint32 windowSize); ossim_uint32 getWindowSize()const; /** * @param flag Set "theAutoGrowRectFlag". This only affects filter types * that set nulls. Will have a growing affect on the edges. */ void setAutoGrowRectFlag(bool flag); bool getAutoGrowRectFlag() const; void setFilterType(ossimMeanMedianFilterType type); void setFilterType(const ossimString& type); ossimString getFilterTypeString() const; void getFilterTypeList(std::vector& list) const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @return Returns the bounding rectangle which is the input bounding * rectangle with any expansion (from autogrow) added in. */ virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; protected: ossimRefPtr theTile; ossimMeanMedianFilterType theFilterType; ossim_uint32 theWindowSize; /** Used by applyMean and applyMedian for "fill null" modes. */ bool theEnableFillNullFlag; /** * If true rectangle is expanded by half filter in each direction if the * theFilterType fills nulls. */ bool theAutoGrowRectFlag; void applyFilter(ossimRefPtr& input); template void applyMean(T dummyVariable, ossimRefPtr& inputData); template void applyMeanNullCenterOnly(T dummyVariable, ossimRefPtr& inputData); template void applyMedian(T dummyVariable, ossimRefPtr& inputData); template void applyMedianNullCenterOnly(T dummyVariable, ossimRefPtr& inputData); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimMemoryImageSource.h000066400000000000000000000070301352751253100247230ustar00rootroot00000000000000//*******************************************************************. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // #ifndef ossimMemoryImageSource_HEADER #define ossimMemoryImageSource_HEADER 1 #include #include #include #include class OSSIM_DLL ossimMemoryImageSource : public ossimImageSource { public: ossimMemoryImageSource(); ossimMemoryImageSource(const ossimMemoryImageSource& src) :ossimImageSource(src), m_image(src.m_image.valid()?(ossimImageData*)src.m_image->dup():(ossimImageData*)0), m_result(0), m_geometry(src.m_geometry.valid()?(ossimImageGeometry*)src.m_geometry->dup():(ossimImageGeometry*)0), m_boundingRect(src.m_boundingRect) { } ossimMemoryImageSource* dup()const { return new ossimMemoryImageSource(*this); } void setImage(ossimRefPtr image); void setImage(ossimScalarType scalarType, ossim_uint32 numberOfBands, ossim_uint32 width, ossim_uint32 height); void setRect(ossim_uint32 ulx, ossim_uint32 uly, ossim_uint32 width, ossim_uint32 height); virtual ossim_uint32 getNumberOfInputBands() const; virtual ossim_uint32 getNumberOfOutputBands() const; virtual ossimScalarType getOutputScalarType() const; virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual bool canConnectMyInputTo(ossim_int32 myInputIndex, const ossimConnectableObject* object)const; virtual void initialize(); virtual ossim_uint32 getNumberOfDecimationLevels() const; virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const; virtual void getDecimationFactors(std::vector& decimations)const; //! Returns the image geometry object associated with this tile source or NULL if not defined. //! The geometry contains full-to-local image transform as well as projection (image-to-world) //! Default implementation returns the image geometry object associated with the next //! (left) input source (if any) connected to this source in the chain, or NULL. virtual ossimRefPtr getImageGeometry() { return m_geometry; } //! Default implementation sets geometry of the first input to the geometry specified. virtual void setImageGeometry(ossimImageGeometry* geom) { m_geometry = geom; } /** * save state is not implemented for this source and only passes to the base. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * loadState is here so one can construct a memory source as a blank tile. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: ossimRefPtr m_image; ossimRefPtr m_result; ossimRefPtr m_geometry; ossimIrect m_boundingRect; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimMetadataFileWriter.h000066400000000000000000000120011352751253100250360ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2003 Storage Area Networks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Kenneth Melero (kmelero@sanz.com) // //******************************************************************* // $Id: ossimMetadataFileWriter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimMetadataFileWriter_H #define ossimMetadataFileWriter_H #include #include #include #include #include #include #include #include class ossimImageSource; /** * ossimMetadataFileWriter * * Typical usage something like this: * * ossimObject* obj = ossimImageMetaDataWriterRegistry::instance()-> * createObject(ossimString("ossimReadmeFileWriter")); * if (!obj) * { * return; * } * ossimMetadataFileWriter* mw = PTR_CAST(ossimMetadataFileWriter, obj); * if (!mw) * { * return; * } * * mw->setFilename(xmlFile); * mw->loadState(kwl); * mw->connectMyInputTo(ih.get()); * mw->execute(); * delete mw; */ class OSSIMDLLEXPORT ossimMetadataFileWriter : public ossimConnectableObject, public ossimProcessInterface, public ossimConnectableObjectListener { public: ossimMetadataFileWriter(); virtual ossimObject* getObject(); virtual const ossimObject* getObject() const; virtual void initialize(); virtual bool execute(); virtual void setPercentComplete(double percentComplete); virtual void setFilename(const ossimFilename& file); const ossimFilename& getFilename()const; /** * Load state method: * * This method call base class ossimConnectableObject::loadState then * looks for its keywords. * * @param kwl Keyword list to initialize from. * * @param prefix Usually something like: "object1." * * @return This method will alway return true as it is intended to be * used in conjuction with the set methods. * * Keywords picked up by loadState: * * filename: foo.tfw * * (pixel_type should be area or point) * * pixel_type: area */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object) const; virtual void disconnectInputEvent(ossimConnectionEvent& event); virtual void connectInputEvent(ossimConnectionEvent& event); virtual void propertyEvent(ossimPropertyEvent& event); /** * Ossim uses a concept of "pixel is point" internally. * * This means that if you say a tie point is 30.0N -81.0W, the center of * the pixel at the tie point is 30.0N -81.0W. * */ virtual void setPixelType(ossimPixelType pixelType); virtual ossimPixelType getPixelType() const; /** * Sets the area of interest to write the meta data for. * * @param areaOfInterest Sets theAreaOfInterest. * * @note By default the writers will use * "theInputConnection->getBoundingRect()" if theAreaOfInterest has nans. */ virtual void setAreaOfInterest(const ossimIrect& areaOfInterest); /** * @returns theAreaOfInterest. */ virtual ossimIrect getAreaOfInterest() const; /** * void getMetadatatypeList(std::vector& metadatatypeList)const * * pure virtual * * Appends the writers metadata types to the "metadatatypeList". * * This is the actual image type name. So for * example, ossimTiffWorldFileWriter has tiff_world_file type. * * @param metadatatypeList stl::vector list to append to. * * @note All writers should append to the list, not, clear it and then add * their types. */ virtual void getMetadatatypeList( std::vector& metadatatypeList)const=0; /** * bool hasMetadataType(const ossimString& metadataType) const * * @param imageType string representing image type. * * @return true if "metadataType" is supported by writer. */ virtual bool hasMetadataType(const ossimString& metadataType)const=0; /*! * property interface */ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimMetadataFileWriter(); /** * Write out the file. * @return true on success, false on error. */ virtual bool writeFile() = 0; ossimImageSource* theInputConnection; ossimFilename theFilename; ossimPixelType thePixelType; ossimIrect theAreaOfInterest; TYPE_DATA }; #endif /* End of #ifndef ossimMetadataFileWriter_H */ ossim-Miami-2.9.1/include/ossim/imaging/ossimMonoGridRemapEngine.h000066400000000000000000000032111352751253100251550ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimMonoGridRemapEngine.h // // Copyright (C) 2001 ImageLinks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains declaration of class ossimMonoGridRemapEngine // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimMonoGridRemapEngine.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimMonoGridRemapEngine_HEADER #define ossimMonoGridRemapEngine_HEADER #include /*!**************************************************************************** * * CLASS: ossimMonoGridRemapEngine * *****************************************************************************/ class ossimMonoGridRemapEngine : public ossimGridRemapEngine { public: ossimMonoGridRemapEngine() : ossimGridRemapEngine(1, 1) {} virtual ossimObject* dup() const; virtual void remapTile(const ossimDpt& origin_point, ossimGridRemapSource* remapper, ossimRefPtr& tile); virtual void assignRemapValues(std::vector& sources); virtual void computeSourceValue(ossimRefPtr& source, void* result); protected: virtual void computeRemapNode(ossimAtbPointSource* point_source, void* source_value, void* target_value); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimMultiBandHistogramTileSource.h000066400000000000000000000066321352751253100270720ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimMultiBandHistogramTileSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimMultiBandHistogramTileSource_HEADER #define ossimMultiBandHistogramTileSource_HEADER #include #include class OSSIMDLLEXPORT ossimMultiBandHistogramTileSource : public ossimImageSourceHistogramFilter { public: enum ossimMultiBandHistogramAlgorithm { OSSIM_HISTOGRAM_NO_ALGORITHM = 0, OSSIM_HISTOGRAM_LINEAR_STRETCH_ALGORITHM = 1 }; ossimMultiBandHistogramTileSource(); ossimMultiBandHistogramTileSource(double minValuePercent, double maxValuePercent, ossimImageSource* inputSource, ossimMultiResLevelHistogram* histogram); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void setMinValuePercent(const std::vector& arrayPercents) { theMinValuePercentArray = arrayPercents; } virtual void setMaxValuePercent(const std::vector& arrayPercents) { theMaxValuePercentArray = arrayPercents; } virtual void setMinValuePercent(ossim_uint32 arrayIndex, double minValue) { if(arrayIndex < theMinValuePercentArray.size()) { theMinValuePercentArray[arrayIndex] = minValue; } } virtual void setMaxValuePercent(ossim_uint32 arrayIndex, double maxValue) { if(arrayIndex < theMaxValuePercentArray.size()) { theMaxValuePercentArray[arrayIndex] = maxValue; } } virtual double getMinValuePercent(ossim_uint32 arrayIndex)const { if(arrayIndex < theMinValuePercentArray.size()) { return theMinValuePercentArray[arrayIndex]; } return ossim::nan(); } virtual double getMaxValuePercent(ossim_uint32 arrayIndex)const { if(arrayIndex < theMaxValuePercentArray.size()) { return theMaxValuePercentArray[arrayIndex]; } return ossim::nan(); } virtual ossim_uint32 getNumberOfMinValues()const { return (ossim_uint32)theMinValuePercentArray.size(); } virtual ossim_uint32 getNumberOfMaxValues()const { return (ossim_uint32)theMinValuePercentArray.size(); } virtual void initialize(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: virtual ~ossimMultiBandHistogramTileSource(); void allocate(); ossimRefPtr theTile; ossimMultiBandHistogramAlgorithm theAlgorithm; std::vector theMinValuePercentArray; std::vector theMaxValuePercentArray; template ossimRefPtr runLinearStretchAlgorithm( T dummyVariable, ossimRefPtr& tile); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNBandToIndexFilter.h000066400000000000000000000100021352751253100247430ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimNBandToIndexFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimNBandToIndexFilter_HEADER #define ossimNBandToIndexFilter_HEADER #include #include #include #include class ossimImageData; /*! * It will map the input data to an 8-bit index table. The table *
 *
 * Example keyword list:
 *
 * type:  ossimNBandToIndexFilter
 *
 * If you want to load from a file then just do:
 *
 * lut.filename: 
 *
 * If you have the lut table in line then it must look like this:
 *
 * lut.entry0:  204 102 1
 * lut.entry1:  255 204 153
 * lut.entry2:  51 204 204
 * lut.number_of_entries:  3
 * lut.type:  ossimNBandLutDataObject
 *
 * 
*/ class OSSIM_DLL ossimNBandToIndexFilter : public ossimImageSourceFilter { public: /*! * Initializes the min value to 0 and the max value to 4000. */ ossimNBandToIndexFilter(); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual ossim_uint32 getNumberOfOutputBands() const; virtual ossimScalarType getOutputScalarType() const; void setLut(ossimNBandLutDataObject& lut); void setLut(const ossimFilename& file); virtual bool isSourceEnabled()const; virtual void disableSource(); virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void initialize(); /*! * Saves the state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Loads the state of this object. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Will set the property whose name matches the argument * "property->getName()". * * @param property Object containing property to set. */ virtual void setProperty(ossimRefPtr property); /** * @param name Name of property to return. * * @returns A pointer to a property object which matches "name". Returns * NULL if no match is found. */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * Pushes this's names onto the list of property names. * * @param propertyNames array to add this's property names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimNBandToIndexFilter(); void allocate(); virtual ossimRefPtr convertInputTile(ossimImageData* inputTile); template ossimRefPtr convertOutputTileTemplate(T inputDummy, ossimImageData* inputTile); template ossimRefPtr convertInputTileToOutputTemplate(T1 inputDummy, T2 outputDummy, ossimImageData* inputTile); ossimRefPtr theLut; ossimRefPtr theTile; ossimFilename theLutFilename; bool theKeepQuantizedValueFlag; std::vector theMinValues; std::vector theMaxValues; std::vector theNullValues; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNitf20Writer.h000066400000000000000000000076141352751253100235760ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimNitfWriter.h 9256 2006-07-14 15:28:19Z dburken $ #ifndef ossimNitf20Writer_HEADER #define ossimNitf20Writer_HEADER #include #include #include #include #include #include #include #include #include class ossimProjection; class OSSIM_DLL ossimNitf20Writer : public ossimNitfWriterBase { public: ossimNitf20Writer(const ossimFilename& filename=ossimFilename(""), ossimImageSource* inputSource = (ossimImageSource*)NULL); virtual ~ossimNitf20Writer(); virtual bool isOpen()const; virtual bool open(); virtual void close(); /** * void getImageTypeList(std::vector& imageTypeList)const * * Appends this writer image types to list "imageTypeList". * * This writer has the following types: * nitf_block_band_separate * nitf_block_band_sequential * * @param imageTypeList stl::vector list to append to. */ virtual void getImageTypeList(std::vector& imageTypeList)const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty( const ossimString& name)const; /** * @param propertyNames Array to populate with property names. * * @note The following names are handled: * file_header * image_header */ virtual void getPropertyNames(std::vector& propertyNames)const; void addRegisteredTag(ossimRefPtr registeredTag); /** * Saves the state of the writer to kwl with prefix then calls * base class ossimImageFileWriter::saveState * * @param kwl Keyword list to save to. * * @param prefix Usually something like: "object2." * @return true on success, false on failure. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /** * Initializes the state of the writer from kwl with prefix then calls * base class ossimImageFileWriter::loadState * * @param kwl Keyword list to initialize from. * * @param prefix Usually something like: "object2." * @return true on success, false on failure. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: /** * @return true on success false on error. */ virtual bool writeFile(); /** * write out block band separate * * @return true on success and false on error */ virtual bool writeBlockBandSeparate(); /** * Outputs in band sequential format. Band 1 is followed by band * 2, ... etc. */ virtual bool writeBlockBandSequential(); void addTags(); std::ofstream* theOutputStream; ossimRefPtr theFileHeader; ossimRefPtr theImageHeader; /** If true user wants to set RPC00B tag. (DEFAULT = false) */ bool theEnableRpcbTagFlag; /** * If true user wants to set BLOCKA tag. (DEFAULT = true) * Currently only valid for map projected images. */ bool theEnableBlockaTagFlag; /** * * If true this will enable searching the input connnection for another NITF handler and * bring the fields to this writers output fields and will maintin as many field values as possible * */ bool theCopyFieldsFlag; TYPE_DATA }; #endif /* #ifndef ossimNitfWriter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimNitfCodecFactory.h000066400000000000000000000020151352751253100245130ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Factory class declaration for codec(encoder/decoder). // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimNitfCodecFactory_HEADER #define ossimNitfCodecFactory_HEADER #include #include #include /** * This is a convenience class that is used by the NITF handler to create the proper keywordlist * from the TREs and then calls the CodecRegistry to actuall return and allocate a new codec */ class ossimNitfCodecFactory { public: ~ossimNitfCodecFactory(); static ossimNitfCodecFactory* instance(); ossimCodecBase* createCodec(ossimRefPtr imageHeader); protected: static std::mutex m_mutex; static ossimNitfCodecFactory* m_instance; ossimNitfCodecFactory(); }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNitfTileSource.h000066400000000000000000000416371352751253100242410ustar00rootroot00000000000000//--- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration for NitfTileSource. // //--- // $Id$ #ifndef ossimNitfTileSource_HEADER #define ossimNitfTileSource_HEADER 1 #include #include #include #include #include #include #include struct jpeg_decompress_struct; class OSSIM_DLL ossimNitfTileSource : public ossimImageHandler { public: enum ReadMode { READ_MODE_UNKNOWN = 0, /** IMODE = B "Band Interleaved By Block or a single band" */ READ_BIB_BLOCK = 1, /** IMODE = P "Band Interleaved By Pixel" */ READ_BIP_BLOCK = 2, /** IMODE = R "Band Interleaved By Row" */ READ_BIR_BLOCK = 3, /** IMODE = S "Band Sequential" */ READ_BSQ_BLOCK = 4, /** IMODE = B of S "single block or one block for each band" */ READ_BIB = 5, /** IMODE = P "single block Band Interleaved By Pixel" */ READ_BIP = 6, /** IMODE = R "single block Band Interleaved By Row" */ READ_BIR = 7, /** IMODE = B, IC = C3 "JPEG compressed blocks" */ READ_JPEG_BLOCK = 8 }; ossimNitfTileSource(); virtual ossimString getShortName() const; virtual ossimString getLongName() const; /** * Returns true if the image_file can be opened and is a valid nitf file. */ virtual bool open(); /** * @brief This open takes a stream and stores/captures the shared pointer * on success. * @param str Open stream to image. * @param connectionString Stored on success as the file name. * @return true on success, false on error. */ bool open( std::shared_ptr& str, const std::string& connectionString ); /** @brief Closes file and destroys all memory allocated. */ virtual void close(); /** * @param tileRect Requested rectangle. * * @param resLevel Reduced resolution level to grab tileRect from. * Default = 0 or the full resolution data set. * * @return Returns an image data object with requested rectangle from the * image. Depending on the overlap of tileRect with respect to the image * rectangle, the returned tile could be full, partial, or an empty(blank) * tile. */ virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); /** * @return Returns the number of bands in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; /** * @return Number of output bands. */ virtual ossim_uint32 getNumberOfOutputBands() const; /** * Returns the number of lines in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 resLevel = 0) const; /** * Returns the number of samples in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 resLevel = 0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; virtual bool isOpen()const; /** * @return The current entry number. * * @note NITF's can contain multiple images in a single file. This returns * the index of the current image being read. */ virtual ossim_uint32 getCurrentEntry() const; /** * @param entryList This is the list to initialize with entry indexes. */ virtual void getEntryList(std::vector& entryList) const; /** * @return Returns the number of entries (or images) within the nitf * file. */ ossim_uint32 getNumberOfEntries() const; /** * @param entryIdx Zero base entry number to select. Sets data member * "theCurrentEntry". * * @note "theCurrentEntry" will not be set if "entryIdx" is out of range. */ virtual bool setCurrentEntry(ossim_uint32 entryIdx); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void setProperty(ossimRefPtr property); virtual void getPropertyNames(std::vector& propertyNames)const; ossimString getSecurityClassification()const; /** * @return Returns theCacheEnabledFlag. */ bool getCacheEnabledFlag() const; /** * @param flag Sets theCacheEnabledFlag and disables/enables caching * accordingly. If cache is disabled it is also flushed at the same time. * If cache is enabled, blocks read from the image will be cached. */ void setCacheEnabledFlag(bool flag); virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual double getNullPixelValue(ossim_uint32 band=0)const; const ossimNitfFileHeader* getFileHeader()const; ossimNitfFileHeader* getFileHeader(); ossimNitfFile *getNitfFile(); const ossimNitfFile *getNitfFile()const; /** * @return The image header for the current entry. */ const ossimNitfImageHeader* getCurrentImageHeader() const; ossimNitfImageHeader* getCurrentImageHeader(); /** * @brief Convenience method to get the zero based rgb output band list. * * Attempts to derive RGB bands from nitf fields. * * @param bandList Initialized by this. * @return true on success, false if number of bands is less than 3 or if * rgb bands could not be derived from nitf fields. */ virtual bool getRgbBandList(std::vector& bandList) const; protected: virtual ~ossimNitfTileSource(); /** * @param imageRect The full resolution image rectangle. * * @note Should contain offsets if there are any. */ void setBoundingRectangle(const ossimIrect& imageRect); /** Copy constructor, disallow... */ ossimNitfTileSource(const ossimNitfTileSource& obj); /** Operator=, disallow... */ ossimNitfTileSource& operator=(const ossimNitfTileSource& rhs); /** * Returns true on success, false on error. */ bool loadTile(const ossimIrect& clipRect); /** * @return Returns the block number given an origin. */ ossim_uint32 getBlockNumber(const ossimIpt& block_origin) const; /** * Deletes all memory allocated by this object. */ void destroy(); /** * @brief Parses "theImageFile" and initializes all nitf headers. * @return true on success, false on error. */ virtual bool parseFile(); /** * @brief Allocates everything for current entry. * * This is called on an open() or a entry change to an already open nitf * file. * * This does not allocate buffers and tiles to keep open and * setCurrentEntry times to a minimum. Buffers are allocated on first * grab of pixel data by allocatBuffers method. * * @return True on success, false on error. */ virtual bool allocate(); /** * @brief Allocates buffers for current entry. * * This is called on first getTile(). * * @return True on success, false on error. */ virtual bool allocateBuffers(); /** * @param hdr Pointer to image header. * @return true if reader can uncompress nitf. * */ virtual bool canUncompress(const ossimNitfImageHeader* hdr) const; /** * Initializes the data member "theScalarType" from the current entry. */ virtual void initializeScalarType(); /** * Initializes the data member "theSwapBytesFlag" from the current entry. */ virtual void initializeSwapBytesFlag(); /** * Initializes the data member "theReadMode" from the current entry. */ virtual void initializeReadMode(); /** * Initializes the data member "theNumberOfBands" from the current entry. */ void initializeBandCount(); /** * Initializes the data member "theBlockSize" from the current entry. * * @note This should be performed after setting the read mode and * band count. * * @note This is the size of a single block read. So if the bands are * separated by block, a read of this size will get one block. * * @return true on success, false on error. */ bool initializeBlockSize(); /** * Initializes the data members "theImageRect" and "theBlockRect" * from the current entry. * * @return true on success, false on error. */ virtual bool initializeImageRect(); /** * Initializes the data member "theCacheSize". */ void initializeCacheSize(); /** * Initializes the data member "theCacheTileInterLeaveType". */ virtual void initializeCacheTileInterLeaveType(); /** * Initializes the cache tile size(width and height). For block images * this will be the size of one block. For images that are a single block, * this will be the image width by the height of one tile. */ void initializeCacheTile(); /** * Initializes the data member theCompressedBuf. */ virtual void initializeCompressedBuf(); /** * Initializes the output tile size(width and height). */ virtual void initializeOutputTile(); /** * @brief Initializes "theLut" if applicable. */ void initializeLut(); /** * Loads a block of data to theCacheTile. * * @param x Starting x position of block to load. * * @param y Starting y position of block to load. * * @return true on success, false on error. * * @note x and y are zero based relative to the upper left corner so any * sub image offset should be subtracted off. */ bool loadBlockFromCache(ossim_uint32 x, ossim_uint32 y, const ossimIrect& clipRect); /** * Loads a block of data to theCacheTile. * * @param x Starting x position of block to load. * * @param y Starting y position of block to load. * * @return true on success, false on error. * * @note x and y are zero based relative to the upper left corner so any * sub image offset should be subtracted off. */ virtual bool loadBlock(ossim_uint32 x, ossim_uint32 y); /** * @param x Horizontal upper left pixel position of the requested block. * * @param y Vertical upper left pixel position of the requested block. * * @param band Band of block. Only relative with IMODES that have bands * in separate blocks. * * @return true if the stream offset was settable and false otherwise. */ bool getPosition(std::streamoff& position, ossim_uint32 x, ossim_uint32 y, ossim_uint32 band) const; /** * @return the total number of blocks for the current entry. * * @note For band separated blocks, all bands will be counted as on block. */ ossim_uint32 getNumberOfBlocks() const; /** * @return The number of bytes to get from one block band to the next band. */ std::streampos getBandOffset() const; /** * @return The number of bytes to get from one block to the next block. */ std::streampos getBlockOffset() const; void explodePackedBits(ossimRefPtr packedBuffer)const; void convertTransparentToNull(ossimRefPtr tile)const; ossim_uint32 getPartialReadSize(const ossimIpt& blockOrigin)const; bool isVqCompressed(const ossimString& compressionCode)const; /** * @brief Uncompresses Vector Quantization unmasked image data. * IC field = C4 * @param destination tile to stuff. * @param source Pointer to compressed data. */ void vqUncompressC4(ossimRefPtr destination, ossim_uint8* source); /** * @brief Uncompresses Vector Quantization masked image data. * IC field = M4 * @param destination tile to stuff. * @param source Pointer to compressed data. */ void vqUncompressM4(ossimRefPtr destination, ossim_uint8* source); void lutUncompress(ossimRefPtr destination, ossim_uint8* source); /** * @brief scans the file storing in offsets in "theNitfBlockOffset" and * block sizes in "theNitfBlockSize". * @return true on success, false on error. This checks for arrays being * the same size as number of blocks. */ virtual bool scanForJpegBlockOffsets(); /** * @brief Uncompresses a jpeg block using the jpeg-6b library. * This method does eight bit jpeg compressed blocks. Note there is * specialized jpeg12 plugin for 12 bit. * @param x sample location in image space. * @param y line location in image space. * @return true on success, false on error. */ virtual bool uncompressJpegBlock(ossim_uint32 x, ossim_uint32 y); /** * @brief Loads one of the default tables based on COMRAT value. * * @return true if comrat had valid table value(1-5) and table was loaded, * false if COMRAT value did not contain a valid value. Will also return * false if there is already a table loaded. * * @note COMRAT is nitf compression rate code field: * - "00.2" == default compression table 2 * - "00.5" == default compression table 5 and so on. */ bool loadJpegQuantizationTables(jpeg_decompress_struct& cinfo) const; /** * @brief Loads default huffman tables. * * @return true success, false on error. */ bool loadJpegHuffmanTables(jpeg_decompress_struct& cinfo) const; /** * @brief Virtual method determines the decimation factors at each resolution level. * This method derives the decimations from the image metadata. */ virtual void establishDecimationFactors(); ossimRefPtr theTile; ossimRefPtr theCacheTile; ossimRefPtr theNitfFile; std::vector > theNitfImageHeader; ReadMode theReadMode; ossimScalarType theScalarType; bool theSwapBytesFlag; ossim_uint32 theNumberOfInputBands; ossim_uint32 theNumberOfOutputBands; ossim_uint32 theBlockSizeInBytes; ossim_uint32 theReadBlockSizeInBytes; ossim_uint32 theNumberOfImages; ossim_uint32 theCurrentEntry; ossimIrect theImageRect; std::shared_ptr theFileStr; std::vector theSelectorBandList; std::vector theOutputBandList; ossimIpt theCacheSize; ossimInterleaveType theCacheTileInterLeaveType; bool theCacheEnabledFlag; std::vector theEntryList; ossimAppFixedTileCache::ossimAppFixedCacheId theCacheId; bool thePackedBitsFlag; ossimIrect theBlockImageRect; std::vector theCompressedBuf; //--- // Have compressed jpeg blocks of variable length so we must scan and // capture the offsetts and block sizes for reading. //--- std::vector theNitfBlockOffset; std::vector theNitfBlockSize; //--- // If set to true indicates scanForJpegBlockOffsets() needs to be called // prior to grabbing a block. //--- bool m_jpegOffsetsDirty; TYPE_DATA }; #endif /* #ifndef ossimNitfTileSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimNitfWriter.h000066400000000000000000000124431352751253100234300ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id$ #ifndef ossimNitfWriter_HEADER #define ossimNitfWriter_HEADER 1 #include #include #include #include #include #include #include #include #include #include #include #include #include #include class ossimProjection; class OSSIM_DLL ossimNitfWriter : public ossimNitfWriterBase { public: ossimNitfWriter(const ossimFilename& filename=ossimFilename(""), ossimImageSource* inputSource = (ossimImageSource*)NULL); virtual ~ossimNitfWriter(); virtual bool isOpen()const; virtual bool open(); virtual void close(); /** * void getImageTypeList(std::vector& imageTypeList)const * * Appends this writer image types to list "imageTypeList". * * This writer has the following types: * nitf_block_band_separate * nitf_block_band_sequential * * @param imageTypeList stl::vector list to append to. */ virtual void getImageTypeList(std::vector& imageTypeList)const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; /** * @param propertyNames Array to populate with property names. * * @note The following names are handled: * file_header * image_header * des_header */ virtual void getPropertyNames(std::vector& propertyNames)const; void addRegisteredTag(ossimRefPtr registeredTag, bool unique = true); void addRegisteredTag(ossimRefPtr registeredTag, bool unique, const ossim_uint32& ownerIndex, const ossimString& tagType); /** * Saves the state of the writer to kwl with prefix then calls * base class ossimImageFileWriter::saveState * * @param kwl Keyword list to save to. * * @param prefix Usually something like: "object2." * @return true on success, false on failure. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /** * Initializes the state of the writer from kwl with prefix then calls * base class ossimImageFileWriter::loadState * * @param kwl Keyword list to initialize from. * * @param prefix Usually something like: "object2." * @return true on success, false on failure. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool addTextToNitf(std::string& inputText); /** @brief Gets the block size. */ virtual void getTileSize(ossimIpt& size) const; /** * Sets the nitf output block size. Must be divisible by 16. * * Note: This is not called setBlockSize just because there was already * a virtual setTileSize. * * @param tileSize Block size. */ virtual void setTileSize(const ossimIpt& tileSize); /** * Get the image header used for export. * * @warning Many values will be overwritten at export time. This includes the * ossimNitfImageBandV2_1, if the number of bands on the image header * does not match that on the writer. * * @return The image header. */ virtual ossimNitfImageHeaderV2_1 *getImageHeader(); /** * Get the file header used for export. * * @warning Many values will be overwritten at export time. * * @return The file header. */ virtual ossimNitfFileHeaderV2_1 *getFileHeader(); /** * Add a DES to the file. * * @param des The DES to add to the file. */ virtual void addDataExtensionSegment(const ossimNitfDataExtensionSegmentV2_1& des, bool allowTreOverflow); protected: /** * @return true on success false on error. */ virtual bool writeFile(); /** * write out block band separate * * @return true on success and false on error */ virtual bool writeBlockBandSeparate(); /** * Outputs in band sequential format. Band 1 is followed by band * 2, ... etc. */ virtual bool writeBlockBandSequential(); /** Currently disabled... */ // virtual void addStandardTags(); std::shared_ptr m_str; ossimRefPtr m_fileHeader; ossimRefPtr m_imageHeader; std::vector m_dataExtensionSegments; ossimRefPtr m_textHeader; std::string m_textEntry; ossimIpt m_blockSize; TYPE_DATA private: void takeOverflowTags(bool useFileHeader, bool userDefinedTags); }; #endif /* #ifndef ossimNitfWriter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimNitfWriterBase.h000066400000000000000000000142041352751253100242200ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: OSSIM nitf writer base class to hold methods common to // all nitf writers. // //--- // $Id$ #ifndef ossimNitfWriterBase_HEADER #define ossimNitfWriterBase_HEADER 1 #include #include #include #include #include #include class ossimFilename; class ossimImageSourceSequencer; class ossimMapProjectionInfo; class ossimNitfFileHeaderV2_X; class ossimNitfImageHeaderV2_X; class ossimProjection; /** * @brief OSSIM nitf writer base class to hold methods common to * all nitf writers. */ class OSSIM_DLL ossimNitfWriterBase : public ossimImageFileWriter { public: /** @brief default constructor */ ossimNitfWriterBase(); /** * @brief Constructor that takes filename and input source. * @param filename The output file name. * @param inputSource The input source to write to file. */ ossimNitfWriterBase(const ossimFilename& filename, ossimImageSource* inputSource); /* @brief virtual destructor */ virtual ~ossimNitfWriterBase(); /** * @brief Set the properties. * @param property The property to set. */ virtual void setProperty(ossimRefPtr property); /** * @brief Gets a property. * @param The name of the property to get. * @return The property if found. */ virtual ossimRefPtr getProperty( const ossimString& name)const; /** * @param propertyNames Array to populate with property names. * * @note The following names are handled: * enable_rpcb_tag * enable_blocka_tag */ virtual void getPropertyNames(std::vector& propertyNames)const; /** * Saves the state of the writer to kwl with prefix then calls * base class ossimImageFileWriter::saveState * * @param kwl Keyword list to save to. * * @param prefix Usually something like: "object2." * @return true on success, false on failure. * * Keywords saved by saveState: * * enable_rpcb_tag: true * * enable_blocka_tag: true */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /** * Initializes the state of the writer from kwl with prefix then calls * base class ossimImageFileWriter::loadState * * @param kwl Keyword list to initialize from. * * @param prefix Usually something like: "object2." * @return true on success, false on failure. * * Keywords picked up by loadState: * * enable_rpcb_tag: true * * enable_blocka_tag: true */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Returns a 3-letter extension from the image type descriptor * (theOutputImageType) that can be used for image file extensions. * * @param imageType string representing image type. * * @return the 3-letter string extension. */ virtual ossimString getExtension() const; virtual void addRegisteredTag(ossimRefPtr registeredTag); virtual void addRegisteredTag(ossimRefPtr registeredTag, bool unique); virtual void addRegisteredTag(ossimRefPtr registeredTag, bool unique, const ossim_uint32& ownerIndex, const ossimString& tagType); virtual void setFileHeaderV2_1(ossimRefPtr, bool preferSource=false); virtual void setImageHeaderV2_1(ossimRefPtr, bool preferSource=false); protected: /** * @brief Populates tags with geometry info from projection. Will write an * rpcb tag if theEnableRpcbTagFlag if set to true. * @param hdr The header to write to. * @param seq The input connection or image source. */ void writeGeometry(ossimNitfImageHeaderV2_X* hdr, ossimImageSourceSequencer* seq); /** * @brief Adds the BLOCKA tag. * * @param mapInfo ossimMapProjectionInfo to use to set tag with. * @param hdr The header to write to. * * @note Currently only used with map projected images. */ void addBlockaTag(ossimMapProjectionInfo& mapInfo, ossimNitfImageHeaderV2_X* hdr); /** * @brief Adds the GEOLOB tag. * * This will only be added if projection is geographic. * * @param mapInfo ossimMapProjectionInfo to use to set tag with. * @param hdr The header to write to. * * @note Currently only used with map projected images. */ void addGeolobTag(ossimMapProjectionInfo& mapInfo, ossimNitfImageHeaderV2_X* hdr); /** * @brief Adds the RPC00B tag. * * @param rect Requested rectangle of image to write. * * @param proj The output projection. */ void addRpcbTag(const ossimIrect& rect, ossimProjection* proj, ossimNitfImageHeaderV2_X* hdr); /** * @brief Sets the complexity level of theFileHeader. * * @param endPosition This should be the end seek position of the file. */ void setComplexityLevel(std::streamoff, ossimNitfFileHeaderV2_X* hdr); void setComplexityLevel(ossimNitfFileHeaderV2_X* hdr, ossim_uint64 width=0, ossim_uint64 height=0); /** * @brief Sets file header and image header defaults from config file if * found in preferences. */ virtual void initializeDefaultsFromConfigFile( ossimNitfFileHeaderV2_X* fileHdr, ossimNitfImageHeaderV2_X* imgHdr ); /** @brief If true user wants to set RPC00B tag. (DEFAULT = false) */ bool theEnableRpcbTagFlag; /** * @brief If true user wants to set BLOCKA tag. (DEFAULT = true) * Currently only valid for map projected images. */ bool theEnableBlockaTagFlag; /** * @brief If true user wants to set GEOLOG tag. (DEFAULT = true) * This will only be set if a geographic projection. */ bool theEnableGeolobTagFlag; private: TYPE_DATA }; #endif /* #ifndef ossimKakaduNitfVoid Writer_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimNormalizedRemapTable.h000066400000000000000000000043431352751253100253740ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for base class ossimNormalizedRemapTable. // //******************************************************************* // $Id: ossimNormalizedRemapTable.h 15742 2009-10-17 12:59:43Z dburken $ #ifndef ossimNormalizedRemapTable_HEADER #define ossimNormalizedRemapTable_HEADER #include /** * @class ossimNormalizedRemapTable * * @brief Base class implemetation of normalized remap tables to go to/from * normalized value to pixel value. */ class OSSIM_DLL ossimNormalizedRemapTable { public: /** default constructor */ ossimNormalizedRemapTable(); /** virtual destructor */ virtual ~ossimNormalizedRemapTable(); /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 operator[](ossim_int32 pix) const = 0; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 normFromPix(ossim_int32 pix) const = 0; /** * @brief Returns an pixel value as an int from a normalized value. * * @return Value between scalar range of remap table. */ virtual ossim_int32 pixFromNorm(ossim_float64 normPix) const = 0; /** * @brief Pure virtual method to get the number of table entries. * @return The number of entries in a table. */ virtual ossim_int32 getEntries() const = 0; /** * @brief Get the value used to normalize and un-normalize table entries. * @return Value used to normalize and un-normalize table entries. */ virtual ossim_float64 getNormalizer() const; private: // Forbid copy constructor and asignment operator. ossimNormalizedRemapTable(const ossimNormalizedRemapTable& source); ossimNormalizedRemapTable& operator=(const ossimNormalizedRemapTable&); }; inline ossim_float64 ossimNormalizedRemapTable::getNormalizer() const { return static_cast(getEntries()-1); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNormalizedS16RemapTable.h000066400000000000000000000075411352751253100256710ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for ossimNormalizedS16RemapTable. Table for // normalizing signed 16 bit data. // //******************************************************************* // $Id: ossimNormalizedS16RemapTable.h 10456 2007-02-08 14:17:50Z gpotts $ #ifndef ossimNormalizedS16RemapTable_HEADER #define ossimNormalizedS16RemapTable_HEADER #include #include /* for round */ /** * @class ossimNormalizedS16RemapTable * * @brief Signed 16 bit normalized remap tables to go to/from * normalized value to pixel value. */ class OSSIM_DLL ossimNormalizedS16RemapTable : public ossimNormalizedRemapTable { public: /** @brief default constructor */ ossimNormalizedS16RemapTable(); /** @brief virtual destructor */ virtual ~ossimNormalizedS16RemapTable(); enum { TABLE_ENTRIES = 65536, // 2^16 32767-(-32768)+1 OFFSET_TO_ZERO = 32768, // Gets -32768 to zero. NULL_PIX = -32768, MIN_PIX = -32767 }; /** * @brief Gets the number of table entries. * @return The number of entries in a table. */ virtual ossim_int32 getEntries() const; /** * @brief Gets normalized value (between '0.0' and '1.0') from an * int which should in scalar range of a signed 16 bit. * * @note This table is specialized to map both -32768 and -32767 to 0 since * dted data has a null of -32767. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 operator[](ossim_int32 pix) const; /** * @brief Gets normalized value (between '0.0' and '1.0') from an * int which should in scalar range of a signed 16 bit. * * @note This table is specialized to map both -32768 and -32767 to 0 since * dted data has a null of -32767. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 normFromPix(ossim_int32 pix) const; /** * @brief Gets pixel value from normalized value. * * Valid returns range is signed 16 bit range or -32768 to 32767. * * @return Value between -32768 to 32767. */ virtual ossim_int32 pixFromNorm(ossim_float64 normPix) const; private: static ossim_float64 theTable[TABLE_ENTRIES]; static bool theTableIsInitialized; }; inline ossim_int32 ossimNormalizedS16RemapTable::getEntries() const { return TABLE_ENTRIES; } inline ossim_float64 ossimNormalizedS16RemapTable::operator[]( ossim_int32 pix) const { ossim_float64 result = 0; // Move pix into table range. This will take -32768 to 0. ossim_int32 p = pix + OFFSET_TO_ZERO; result = (p < TABLE_ENTRIES ? ( p >= 0 ? theTable[p] : 0.0) : 1.0); return result; } inline ossim_float64 ossimNormalizedS16RemapTable::normFromPix( ossim_int32 pix) const { ossim_float64 result = 0; // Move pix into table range. This will take -32768 to 0. ossim_int32 p = pix + OFFSET_TO_ZERO; result = (p < TABLE_ENTRIES ? ( p >= 0 ? theTable[p] : 0.0) : 1.0); return result; } inline ossim_int32 ossimNormalizedS16RemapTable::pixFromNorm( ossim_float64 normPix) const { if(normPix <= 0.0) return NULL_PIX; // Clamp between 0 and 1 on the way in. ossim_float64 p = (normPix<1.0) ? ( (normPix>0.0) ? normPix : 0.0) : 1.0; // Un-normalize. p = p * getNormalizer(); // TABLE_ENTRIES - 1; //--- // Move pixel into sign range then round it. This will take 65535 to // 32767 which is the max pixel for this scalar type. //--- p = ossim::round(p - OFFSET_TO_ZERO); if (p == NULL_PIX) { // norm pixel came in just above zero so should be at least min. p = MIN_PIX; } return static_cast(p); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNormalizedU11RemapTable.h000066400000000000000000000055541352751253100256700ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for ossimNormalizedU11RemapTable. Table for // normalizing unsigned 11 bit data. // //******************************************************************* // $Id: ossimNormalizedU11RemapTable.h 16034 2009-12-03 14:49:25Z dburken $ #ifndef ossimNormalizedU11RemapTable_HEADER #define ossimNormalizedU11RemapTable_HEADER #include #include /* for round */ /** * @class ossimNormalizedU11RemapTable * * @brief Eleven bit normalized remap table to go to/from normalized value * to pixel value. */ class OSSIM_DLL ossimNormalizedU11RemapTable : public ossimNormalizedRemapTable { public: /** @brief default constructor */ ossimNormalizedU11RemapTable(); /** @brief virtual destructor */ virtual ~ossimNormalizedU11RemapTable(); enum { TABLE_ENTRIES = 2048 // 2^11 }; /** * @brief Gets the number of table entries. * @return The number of entries in a table. */ virtual ossim_int32 getEntries() const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 operator[](ossim_int32 pix) const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 normFromPix(ossim_int32 pix) const; /** * @brief Returns an pixel value as an int from a normalized value. * * @return Value between scalar range of remap table. */ virtual ossim_int32 pixFromNorm(ossim_float64 normPix) const; private: static ossim_float64 theTable[TABLE_ENTRIES]; static bool theTableIsInitialized; }; inline ossim_int32 ossimNormalizedU11RemapTable::getEntries() const { return TABLE_ENTRIES; } inline ossim_float64 ossimNormalizedU11RemapTable::operator[]( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_float64 ossimNormalizedU11RemapTable::normFromPix( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_int32 ossimNormalizedU11RemapTable::pixFromNorm( ossim_float64 normPix) const { if(normPix <= 0.0) return 0; // un-normalize... ossim_float64 p = normPix * getNormalizer(); // Ensure pixel is in range. p = ( (p < TABLE_ENTRIES) ? (p >= 0.0 ? p : 0.0) : getNormalizer()); // Since going from double to int round... p = ossim::round(p); if(p == 0.0) { p = 1.0; } return static_cast(p); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNormalizedU12RemapTable.h000066400000000000000000000055541352751253100256710ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for ossimNormalizedU12RemapTable. Table for // normalizing unsigned 11 bit data. // //******************************************************************* // $Id: ossimNormalizedU12RemapTable.h 16034 2009-12-03 14:49:25Z dburken $ #ifndef ossimNormalizedU12RemapTable_HEADER #define ossimNormalizedU12RemapTable_HEADER #include #include /* for round */ /** * @class ossimNormalizedU12RemapTable * * @brief Twelve bit normalized remap table to go to/from normalized value * to pixel value. */ class OSSIM_DLL ossimNormalizedU12RemapTable : public ossimNormalizedRemapTable { public: /** @brief default constructor */ ossimNormalizedU12RemapTable(); /** @brief virtual destructor */ virtual ~ossimNormalizedU12RemapTable(); enum { TABLE_ENTRIES = 4096 // 2^12 }; /** * @brief Gets the number of table entries. * @return The number of entries in a table. */ virtual ossim_int32 getEntries() const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 operator[](ossim_int32 pix) const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 normFromPix(ossim_int32 pix) const; /** * @brief Returns an pixel value as an int from a normalized value. * * @return Value between scalar range of remap table. */ virtual ossim_int32 pixFromNorm(ossim_float64 normPix) const; private: static ossim_float64 theTable[TABLE_ENTRIES]; static bool theTableIsInitialized; }; inline ossim_int32 ossimNormalizedU12RemapTable::getEntries() const { return TABLE_ENTRIES; } inline ossim_float64 ossimNormalizedU12RemapTable::operator[]( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_float64 ossimNormalizedU12RemapTable::normFromPix( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_int32 ossimNormalizedU12RemapTable::pixFromNorm( ossim_float64 normPix) const { if(normPix <= 0.0) return 0; // un-normalize... ossim_float64 p = normPix * getNormalizer(); // Ensure pixel is in range. p = ( (p < TABLE_ENTRIES) ? (p >= 0.0 ? p : 0.0) : getNormalizer()); // Since going from double to int round... p = ossim::round(p); if(p == 0.0) { p = 1.0; } return static_cast(p); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNormalizedU13RemapTable.h000066400000000000000000000055561352751253100256740ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for ossimNormalizedU13RemapTable. Table for // normalizing unsigned 11 bit data. // //******************************************************************* // $Id: ossimNormalizedU13RemapTable.h 16034 2009-12-03 14:49:25Z dburken $ #ifndef ossimNormalizedU13RemapTable_HEADER #define ossimNormalizedU13RemapTable_HEADER #include #include /* for round */ /** * @class ossimNormalizedU13RemapTable * * @brief Thirteen bit normalized remap table to go to/from normalized value * to pixel value. */ class OSSIM_DLL ossimNormalizedU13RemapTable : public ossimNormalizedRemapTable { public: /** @brief default constructor */ ossimNormalizedU13RemapTable(); /** @brief virtual destructor */ virtual ~ossimNormalizedU13RemapTable(); enum { TABLE_ENTRIES = 8192 // 2^13 }; /** * @brief Gets the number of table entries. * @return The number of entries in a table. */ virtual ossim_int32 getEntries() const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 operator[](ossim_int32 pix) const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 normFromPix(ossim_int32 pix) const; /** * @brief Returns an pixel value as an int from a normalized value. * * @return Value between scalar range of remap table. */ virtual ossim_int32 pixFromNorm(ossim_float64 normPix) const; private: static ossim_float64 theTable[TABLE_ENTRIES]; static bool theTableIsInitialized; }; inline ossim_int32 ossimNormalizedU13RemapTable::getEntries() const { return TABLE_ENTRIES; } inline ossim_float64 ossimNormalizedU13RemapTable::operator[]( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_float64 ossimNormalizedU13RemapTable::normFromPix( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_int32 ossimNormalizedU13RemapTable::pixFromNorm( ossim_float64 normPix) const { if(normPix <= 0.0) return 0; // un-normalize... ossim_float64 p = normPix * getNormalizer(); // Ensure pixel is in range. p = ( (p < TABLE_ENTRIES) ? (p >= 0.0 ? p : 0.0) : getNormalizer()); // Since going from double to int round... p = ossim::round(p); if(p == 0.0) { p = 1.0; } return static_cast(p); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNormalizedU14RemapTable.h000066400000000000000000000055571352751253100256760ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for ossimNormalizedU14RemapTable. Table for // normalizing unsigned 11 bit data. // //******************************************************************* // $Id: ossimNormalizedU14RemapTable.h 16034 2009-12-03 14:49:25Z dburken $ #ifndef ossimNormalizedU14RemapTable_HEADER #define ossimNormalizedU14RemapTable_HEADER #include #include /* for round */ /** * @class ossimNormalizedU14RemapTable * * @brief Fourteen bit normalized remap table to go to/from normalized value * to pixel value. */ class OSSIM_DLL ossimNormalizedU14RemapTable : public ossimNormalizedRemapTable { public: /** @brief default constructor */ ossimNormalizedU14RemapTable(); /** @brief virtual destructor */ virtual ~ossimNormalizedU14RemapTable(); enum { TABLE_ENTRIES = 16384 // 2^14 }; /** * @brief Gets the number of table entries. * @return The number of entries in a table. */ virtual ossim_int32 getEntries() const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 operator[](ossim_int32 pix) const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 normFromPix(ossim_int32 pix) const; /** * @brief Returns an pixel value as an int from a normalized value. * * @return Value between scalar range of remap table. */ virtual ossim_int32 pixFromNorm(ossim_float64 normPix) const; private: static ossim_float64 theTable[TABLE_ENTRIES]; static bool theTableIsInitialized; }; inline ossim_int32 ossimNormalizedU14RemapTable::getEntries() const { return TABLE_ENTRIES; } inline ossim_float64 ossimNormalizedU14RemapTable::operator[]( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_float64 ossimNormalizedU14RemapTable::normFromPix( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_int32 ossimNormalizedU14RemapTable::pixFromNorm( ossim_float64 normPix) const { if(normPix <= 0.0) return 0; // un-normalize... ossim_float64 p = normPix * getNormalizer(); // Ensure pixel is in range. p = ( (p < TABLE_ENTRIES) ? (p >= 0.0 ? p : 0.0) : getNormalizer()); // Since going from double to int round... p = ossim::round(p); if(p == 0.0) { p = 1.0; } return static_cast(p); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNormalizedU15RemapTable.h000066400000000000000000000055561352751253100256760ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for ossimNormalizedU15RemapTable. Table for // normalizing unsigned 11 bit data. // //******************************************************************* // $Id: ossimNormalizedU15RemapTable.h 16034 2009-12-03 14:49:25Z dburken $ #ifndef ossimNormalizedU15RemapTable_HEADER #define ossimNormalizedU15RemapTable_HEADER #include #include /* for round */ /** * @class ossimNormalizedU15RemapTable * * @brief Fifteen bit normalized remap table to go to/from normalized value * to pixel value. */ class OSSIM_DLL ossimNormalizedU15RemapTable : public ossimNormalizedRemapTable { public: /** @brief default constructor */ ossimNormalizedU15RemapTable(); /** @brief virtual destructor */ virtual ~ossimNormalizedU15RemapTable(); enum { TABLE_ENTRIES = 32768 // 2^15 }; /** * @brief Gets the number of table entries. * @return The number of entries in a table. */ virtual ossim_int32 getEntries() const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 operator[](ossim_int32 pix) const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 normFromPix(ossim_int32 pix) const; /** * @brief Returns an pixel value as an int from a normalized value. * * @return Value between scalar range of remap table. */ virtual ossim_int32 pixFromNorm(ossim_float64 normPix) const; private: static ossim_float64 theTable[TABLE_ENTRIES]; static bool theTableIsInitialized; }; inline ossim_int32 ossimNormalizedU15RemapTable::getEntries() const { return TABLE_ENTRIES; } inline ossim_float64 ossimNormalizedU15RemapTable::operator[]( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_float64 ossimNormalizedU15RemapTable::normFromPix( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_int32 ossimNormalizedU15RemapTable::pixFromNorm( ossim_float64 normPix) const { if(normPix <= 0.0) return 0; // un-normalize... ossim_float64 p = normPix * getNormalizer(); // Ensure pixel is in range. p = ( (p < TABLE_ENTRIES) ? (p >= 0.0 ? p : 0.0) : getNormalizer()); // Since going from double to int round... p = ossim::round(p); if(p == 0.0) { p = 1.0; } return static_cast(p); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNormalizedU16RemapTable.h000066400000000000000000000055761352751253100257010ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for ossimNormalizedU16RemapTable. Table for // normalizing unsigned 16 bit data. // //******************************************************************* // $Id: ossimNormalizedU16RemapTable.h 16034 2009-12-03 14:49:25Z dburken $ #ifndef ossimNormalizedU16RemapTable_HEADER #define ossimNormalizedU16RemapTable_HEADER #include #include /* for round */ /** * @class ossimNormalizedU16RemapTable * * @brief Unsigned 16 bit normalized remap table to go to/from normalized value * to pixel value. */ class OSSIM_DLL ossimNormalizedU16RemapTable : public ossimNormalizedRemapTable { public: /** @brief default constructor */ ossimNormalizedU16RemapTable(); /** @brief virtual destructor */ virtual ~ossimNormalizedU16RemapTable(); enum { TABLE_ENTRIES = 65536 // 2^16 }; /** * @brief Gets the number of table entries. * @return The number of entries in a table. */ virtual ossim_int32 getEntries() const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 operator[](ossim_int32 pix) const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 normFromPix(ossim_int32 pix) const; /** * @brief Returns an pixel value as an int from a normalized value. * * @return Value between scalar range of remap table. */ virtual ossim_int32 pixFromNorm(ossim_float64 normPix) const; protected: static ossim_float64 theTable[TABLE_ENTRIES]; static bool theTableIsInitialized; }; inline ossim_int32 ossimNormalizedU16RemapTable::getEntries() const { return TABLE_ENTRIES; } inline ossim_float64 ossimNormalizedU16RemapTable::operator[]( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_float64 ossimNormalizedU16RemapTable::normFromPix( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_int32 ossimNormalizedU16RemapTable::pixFromNorm( ossim_float64 normPix) const { if(normPix <= 0.0) return 0; // un-normalize... ossim_float64 p = normPix * getNormalizer(); // Ensure pixel is in range. p = ( (p < TABLE_ENTRIES) ? (p >= 0.0 ? p : 0.0) : getNormalizer()); // Since going from double to int round... p = ossim::round(p); if(p == 0.0) { p = 1.0; } return static_cast(p); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNormalizedU8RemapTable.h000066400000000000000000000055071352751253100256140ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for ossimNormalizedU8RemapTable. Table for // normalizing unsigned 8 bit data. // //******************************************************************* // $Id: ossimNormalizedU8RemapTable.h 16034 2009-12-03 14:49:25Z dburken $ #ifndef ossimNormalizedU8RemapTable_HEADER #define ossimNormalizedU8RemapTable_HEADER #include #include /* for round */ /** * @class ossimNormalizedU8RemapTable * * @brief Eight bit normalized remap table to go to/from normalized value * to pixel value. */ class OSSIM_DLL ossimNormalizedU8RemapTable : public ossimNormalizedRemapTable { public: /** @brief default constructor */ ossimNormalizedU8RemapTable(); /** @brief virtual destructor */ virtual ~ossimNormalizedU8RemapTable(); enum { TABLE_ENTRIES = 256 // 2^8 }; /** * @brief Gets the number of table entries. * @return The number of entries in a table. */ virtual ossim_int32 getEntries() const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 operator[](ossim_int32 pix) const; /** * @brief Gets a normalized value (between '0.0' and '1.0') from * a pixel value. * * @return Value between 0.0 and 1.0. */ virtual ossim_float64 normFromPix(ossim_int32 pix) const; /** * @brief Returns an pixel value as an int from a normalized value. * * @return Value between scalar range of remap table. */ virtual ossim_int32 pixFromNorm(ossim_float64 normPix) const; protected: static ossim_float64 theTable[TABLE_ENTRIES]; static bool theTableIsInitialized; }; inline ossim_int32 ossimNormalizedU8RemapTable::getEntries() const { return TABLE_ENTRIES; } inline ossim_float64 ossimNormalizedU8RemapTable::operator[]( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_float64 ossimNormalizedU8RemapTable::normFromPix( ossim_int32 pix) const { return ( (pix < TABLE_ENTRIES) ? (pix >= 0 ? theTable[pix] : 0.0) : 1.0); } inline ossim_int32 ossimNormalizedU8RemapTable::pixFromNorm( ossim_float64 normPix) const { if(normPix <= 0.0) return 0; ossim_float64 p = normPix * getNormalizer(); // Ensure pixel is in range. p = ( (p < TABLE_ENTRIES) ? (p >= 0.0 ? p : 0.0) : getNormalizer()); // Since going from double to int round... p = ossim::round(p); if(p == 0.0) { p = 1; } return static_cast(p); } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimNullPixelFlip.h000066400000000000000000000026211352751253100240570ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // //******************************************************************* // $Id$ #ifndef ossimNullPixelFlip_HEADER #define ossimNullPixelFlip_HEADER #include class OSSIM_DLL ossimNullPixelFlip : public ossimImageSourceFilter { public: enum ClipMode { ClipMode_NONE = 0, ClipMode_BOUNDING_RECT = 1 }; enum ReplacementType { ReplacementType_MINPIX = 0, ReplacementType_MAXPIX = 1 }; ossimNullPixelFlip(ClipMode clipMode = ClipMode_BOUNDING_RECT, ReplacementType replacementType=ReplacementType_MINPIX); virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); protected: template void flipPixels(T dummy, ossimImageData* inpuTile, ossim_uint32 resLevel); template ossimImageData* clipTile(T dummy, ossimImageData* inpuTile, ossim_uint32 resLevel); ClipMode m_clipMode; ReplacementType m_replacementType; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimOrthoImageMosaic.h000066400000000000000000000046601352751253100245270ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimOrthoImageMosaic.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimOrthoImageMosaic_HEADER #define ossimOrthoImageMosaic_HEADER #include class OSSIMDLLEXPORT ossimOrthoImageMosaic : public ossimImageMosaic { public: ossimOrthoImageMosaic(); ossimOrthoImageMosaic(ossimConnectableObject::ConnectableObjectList& inputSources); virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0) const; virtual void initialize(); //! Returns the geometry associated with the full mosaic. This object maintains it's own //! geometry instance. virtual ossimRefPtr getImageGeometry(); //! Used to retrieve the number of overlapping images withint the given rect. virtual ossim_uint32 getNumberOfOverlappingImages(const ossimIrect& rect, ossim_uint32 resLevel=0)const; //! Used to populate the result with the index of the overlapping images. virtual void getOverlappingImages(std::vector& result, const ossimIrect& rect, ossim_uint32 resLevel=0)const; virtual ossimRefPtr getNextTile(ossim_uint32& returnedIdx, const ossimIrect& origin, ossim_uint32 resLevel=0); ossimIrect getRelativeRect(ossim_uint32 index, ossim_uint32 resLevel = 0)const; protected: virtual ~ossimOrthoImageMosaic(); void computeBoundingRect(ossim_uint32 resLevel=0); //! If this object is maintaining an ossimImageGeometry, this method needs to be called after //! each time the contents of the mosaic changes. void updateGeometry(); std::vector m_InputTiePoints; ossimDpt m_Delta; //!< Holds R0 delta and will be scaled for different r-level requests ossimDpt m_UpperLeftTie; //!< Will hold the upper left tie of the mosaic. ossimIrect m_BoundingRect; ossimString m_Units; ossimRefPtr m_Geometry; //!< The input image geometry, altered by the map tiepoint TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimOverviewBuilderBase.h000066400000000000000000000164671352751253100252550ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Base class for overview builders. // //---------------------------------------------------------------------------- // $Id: ossimOverviewBuilderBase.h 21653 2012-09-07 15:03:08Z dburken $ #ifndef ossimOverviewBuilderBase_HEADER #define ossimOverviewBuilderBase_HEADER 1 #include #include #include #include #include #include #include #include #include #include class ossimImageFileWriter; class ossimFilename; class OSSIM_DLL ossimOverviewBuilderBase : public ossimSource, public ossimProcessInterface, public ossimConnectableObjectListener { public: /** default constructor */ ossimOverviewBuilderBase(); /** * @brief Sets an optional file writer to the builder. * Currently used by the virtual overview builder. * * @param outputWriter The file writer of the builder. * * @return True on successful initialization, false on error. */ virtual bool setOutputWriter(ossimImageFileWriter* outputWriter); /** * @brief Sets the input to the builder. * * @param imageSource The input to the builder. * * @return True on successful initialization, false on error. */ virtual bool setInputSource(ossimImageHandler* imageSource); /** * @brief Sets the output file name. (pure virtual) * @prama file This will be the output file name like foo.ovr */ virtual void setOutputFile(const ossimFilename& file)=0; /** * @brief Gets the output file name. (pure virtual) * * @return The output file name or ossimFilename::NIL if it was not set * yet and the image handle has not been initialized. * * @note This will return ossimFilename::NIL unless one of was called, * setInputSource or setOutputFile. */ virtual ossimFilename getOutputFile() const=0; /** * @brief Sets the overview output type. (pure virtual) * @param type This should be the string representing the type. This method * will do nothing if type is not handled and return false. * @return true if type is handled, false if not. * @note Currently handled types are */ virtual bool setOverviewType(const ossimString& type)=0; /** * @brief Gets the overview type. (pure virtual) * @return The overview output type as a string. */ virtual ossimString getOverviewType() const=0; /** * @brief Method to check if builder can handle type. * @return true if type is handled by builder, false if not. */ virtual bool hasOverviewType(const ossimString& type) const; /** * @brief Method to populate class supported types. (pure virtual) * Example: * ossimTiffOverviewNearest * ossimTiffOverviewBox * * @param typeList List of ossimStrings to add to. */ virtual void getTypeNameList(std::vector& typeList)const=0; /** * @brief Get the overview stop dimension. * @return The overview stop dimension. */ virtual ossim_uint32 getOverviewStopDimension() const; /** * @brief Sets the overview stop dimension. * * This controls how many layers will be built. If set to 64 then the * builder will stop when height and width for current level are less * than or equal to 64. Note a default can be set in the ossim preferences * file, setting the keyword "overview_stop_dimension". * * @param dim The overview stop dimension */ virtual void setOverviewStopDimension(ossim_uint32 dim); /** * @brief Gets the histogram accumulation mode. * @return mode NONE, NORMAL or FAST. */ ossimHistogramMode getHistogramMode() const; /** * @brief Sets the histogram accumulation mode. * @param mode NONE, NORMAL or FAST. */ void setHistogramMode(ossimHistogramMode mode); /** * @brief Builds the overviews. (pure virtual) * * @return true on success, false on error. */ virtual bool execute()=0; /** * @brief Finalize method. Should be called at end of execute. * * This implementation will reset the the output band list if the source * image handler is a band selector. */ virtual void finalize(); /** * @brief Specifies parameters (in KWL) for generation of an alpha (bit) * mask such that any full or partial null pixels will be masked out. A * mask file will be written to the source image directory with the image * file name and extension ".mask". */ void setBitMaskSpec(const ossimKeywordlist& bit_mask_spec); /** * @brief Turn on/off scan for min max flag. * This method assumes the null is known. * @param flag true turns scan on, false off. Default=off. */ void setScanForMinMax(bool flag); /** @return scan for min max flag. */ bool getScanForMinMax() const; /** * @brief Turn on/off scan for min, max, null flag. * Attempts to find null, min and max where null is the minimum value found, * min is the second most min and max is max. * @param flag true turns scan on, false off. Default=off. */ void setScanForMinMaxNull(bool flag); /** @return scan for min max flag. */ bool getScanForMinMaxNull() const; protected: /** virtual destructor */ virtual ~ossimOverviewBuilderBase(); /** * @brief Gets the required number of res levels. * * Convenience method to get the required number of reduced resolution * data sets to get to the smallest dimension of the output tile size. * Note that this include r0. * * @param ih Pointer to the image handler. * * @return number of res levels. */ ossim_uint32 getRequiredResLevels(const ossimImageHandler* ih) const; /** * @brief Initializes preference settings. * * Currently: * * 1) Gets the default stop dimension. * * Looks for overview_stop_dimension, then will use minimum default tile * size if that is not found. * * 2) Set scan float data flag. * * Looks for overview_builder.scan_for_min_max_null_if_float. * * If true this will turn the m_scanForMinMaxNull on if the scalar type of * image handler is float. */ void initializePreferenceSettings(); /** * @brief Checks scalar type and turns on scanning for min, max, nulls if * needed. */ void initializeScanOptions(); ossim_uint32 m_overviewStopDimension; ossimHistogramMode m_histoMode; ossimKeywordlist m_bitMaskSpec; ossimRefPtr m_imageHandler; std::vector m_originalBandList; ossimRefPtr m_maskWriter; ossimRefPtr m_maskFilter; ossimFilename m_outputFile; bool m_scanForMinMax; bool m_scanForMinMaxNull; bool m_scanFloatData; /** for rtti stuff */ TYPE_DATA }; #endif /* End of "#ifndef ossimOverviewBuilderBase_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimOverviewBuilderFactory.h000066400000000000000000000037201352751253100257760ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // See top level LICENSE.txt file. // // Author: David Burken // // Description: The ossim overview builder factory. // //---------------------------------------------------------------------------- // $Id: ossimOverviewBuilderFactory.h 15833 2009-10-29 01:41:53Z eshirschorn $ #ifndef ossimOverviewBuilderFactory_HEADER #define ossimOverviewBuilderFactory_HEADER #include #include class ossimOverviewBuilderBase; class ossimString; /** * @class ossimOverviewBuilderFactory * @brief The ossim overview builder factory. */ class OSSIM_DLL ossimOverviewBuilderFactory : public ossimOverviewBuilderFactoryBase { public: /** @brief static instance method. */ static ossimOverviewBuilderFactory* instance(); /** virtual destructor */ virtual ~ossimOverviewBuilderFactory(); /** * @brief Creates a builder from a string. This should match a string from * the getTypeNameList() method. Pure virtual. * * @return Pointer to ossimOverviewBuilderBase or NULL is not found * within registered factories. */ virtual ossimOverviewBuilderBase* createBuilder( const ossimString& typeName) const; /** * @brief Method to populate a list of supported types for the factory. * registered to this registry. Pure virtual. * * @param typeList List of ossimStrings to add to. */ virtual void getTypeNameList(std::vector& typeList)const; private: /** default constructor hidden from use */ ossimOverviewBuilderFactory(); /** copy constructor hidden from use */ ossimOverviewBuilderFactory(const ossimOverviewBuilderFactory& obj); /** operator= hidden from use. */ void operator=(const ossimOverviewBuilderFactory& rhs); static ossimOverviewBuilderFactory* theInstance; }; #endif /* #ifndef ossimOverviewBuilderFactory_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimOverviewBuilderFactoryBase.h000066400000000000000000000037171352751253100265770ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // See top level LICENSE.txt file. // // Author: David Burken // // Description: The base class for overview builders. // //---------------------------------------------------------------------------- // $Id: ossimOverviewBuilderFactoryBase.h 19187 2011-03-23 12:21:58Z gpotts $ #ifndef ossimOverviewBuilderFactoryBase_HEADER #define ossimOverviewBuilderFactoryBase_HEADER #include #include #include class ossimOverviewBuilderBase; class ossimString; /** * @class ossimOverviewBuilderFactoryBase * @brief The base class for factory overview builder factories. */ class OSSIM_DLL ossimOverviewBuilderFactoryBase : public ossimObjectFactory { public: /** default constructor hidden from use */ ossimOverviewBuilderFactoryBase(); /** virtual destructor */ virtual ~ossimOverviewBuilderFactoryBase(); /** * @brief Creates a builder from a string. This should match a string from * the getTypeNameList() method. Pure virtual. * * @return Pointer to ossimOverviewBuilderBase or NULL is not found * within registered factories. */ virtual ossimOverviewBuilderBase* createBuilder(const ossimString& typeName) const = 0; /** * @brief Method to populate a list of supported types for the factory. * registered to this registry. Pure virtual. * * @param typeList List of ossimStrings to add to. */ virtual void getTypeNameList(std::vector& typeList)const = 0; /*! * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName)const; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; }; #endif /* #ifndef ossimOverviewBuilderFactoryBase_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimOverviewBuilderFactoryRegistry.h000066400000000000000000000056441352751253100275360ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // See top level LICENSE.txt file. // // Author: David Burken // // Description: The factory registry for overview builders. // //---------------------------------------------------------------------------- // $Id: ossimOverviewBuilderFactoryRegistry.h 19907 2011-08-05 19:55:46Z dburken $ #ifndef ossimOverviewBuilderFactoryRegistry_HEADER #define ossimOverviewBuilderFactoryRegistry_HEADER 1 #include #include #include #include #include #include /** * @class ossimOverviewBuilderFactoryRegistry * @brief The factory registry for overview builders. * * Typical usage: * std::vector typeList; * ossimOverviewBuilderFactoryRegistry::instance()->getTypeNameList(typeList); * ossimOverviewBuilderBase* builder = * ossimOverviewBuilderFactoryRegistry::instance()->createBuilder( * someStringFromTypeList); */ class OSSIM_DLL ossimOverviewBuilderFactoryRegistry : public ossimObjectFactory, public ossimFactoryListInterface { public: /** * @brief instance method for access to theInstance pointer. * @return Pointer to this class. */ static ossimOverviewBuilderFactoryRegistry* instance(); /*! * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName) const; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0) const; /** * @brief Creates a builder from a string. This should match a string from * the getTypeNameList() method. * @return Pointer to ossimOverviewBuilderBase or NULL is not found * within registered factories. */ ossimOverviewBuilderBase* createBuilder(const ossimString& typeName) const; /** * @brief Method to populate a list of supported types of all factories * registered to this registry. * * Example: * * ossimTiffOverviewNearest * ossimTiffOverviewBox * * @param typeList List of ossimStrings to add to. */ virtual void getTypeNameList(std::vector& typeList) const; private: /** default constructor hidden from use */ ossimOverviewBuilderFactoryRegistry(); /** copy constructor hidden from use */ ossimOverviewBuilderFactoryRegistry(const ossimOverviewBuilderFactoryRegistry& obj); /** operator= hidden from use. */ void operator=(const ossimOverviewBuilderFactoryRegistry& rhs); /** The static instance of this class. */ static ossimOverviewBuilderFactoryRegistry* m_instance; }; #endif /* #ifndef ossimOverviewBuilderFactoryRegistry_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimOverviewSequencer.h000066400000000000000000000216141352751253100250140ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Class definition for sequencer for building overview files. // //---------------------------------------------------------------------------- // $Id: ossimOverviewSequencer.h 22149 2013-02-11 21:36:10Z dburken $ #ifndef ossimOverviewSequencer_HEADER #define ossimOverviewSequencer_HEADER 1 #include #include #include #include #include #include #include #include #include #include class ossimFilename; /** * @class Sequencer for building overview files. */ class OSSIM_DLL ossimOverviewSequencer : public ossimReferenced, public ossimErrorStatusInterface { public: /** default constructor */ ossimOverviewSequencer(); /** * @return The number of tiles within the area of interest. */ ossim_uint32 getNumberOfTiles()const; /** * @return The number of tiles along the x or horizontal direction. */ ossim_uint32 getNumberOfTilesHorizontal()const; /** * @return The number of tiles along the y or vertical direction. */ ossim_uint32 getNumberOfTilesVertical()const; /** * @brief Gets the zero-based image rectangle for the output reduced * resolution data set (rrds). * * @param rect The rectangle to initialize. */ virtual void getOutputImageRectangle(ossimIrect& rect) const; /** * @brief Sets the input source or connection. * @param input Pointer to ossimImageHandler. * @note This object does not own the image handler. */ void setImageHandler(ossimImageHandler* input); /** * @brief Enabled the generation of an alpha (bit) mask such that any full * or partial null pixels will be masked out. A mask file will be written to * the source image directory with the image file name and extension ".mask" */ void setBitMaskObjects(ossimBitMaskWriter* mask_writer, ossimMaskFilter* mask_filter); /** * @brief Sets the input source resolution to decimate from. * @param level The level to decimate. */ void setSourceLevel(ossim_uint32 level); /** * @brief Gets the histogram accumulation mode. * @return mode UNKNOWN, NORMAL or FAST. */ ossimHistogramMode getHistogramMode() const; /** * @brief Sets the histogram accumulation mode. * @param mode NONE, NORMAL or FAST. */ void setHistogramMode(ossimHistogramMode mode); /** * @brief Write histogram method. */ void writeHistogram(); /** * @brief Write histogram method that takes a file name. * @param file File to write to. */ void writeHistogram(const ossimFilename& file); /** * This must be called. We can only initialize this * object completely if we know all connections * are valid. Some other object drives this and so the * connection's initialize will be called after. The job * of this connection is to set up the sequence. It will * default to the bounding rect. The area of interest can be * set to some other rectagle (use setAreaOfInterest). */ virtual void initialize(); /** * @brief Will set the internal pointers to the upperleft * tile number. To go to the next tile in the sequence * just call getNextTile. */ virtual void setToStartOfSequence(); /** * Will allow you to get the next tile in the sequence. * Note the last tile returned will be an invalid * ossimRefPtr. Callers should be able to do: * * ossimRefPtr id = sequencer->getNextTile(); * while (id.valid()) * { * doSomething; * id = sequencer->getNextTile(); * } * */ virtual ossimRefPtr getNextTile(); /** * @brief This implementation does nothing. Derived slave would use this * as a trigger to start resampling tiles. */ virtual void slaveProcessTiles(); /** * @return Always true for this implementation. */ virtual bool isMaster()const; /** @return The tile size. */ ossimIpt getTileSize() const; /** * @brief updated the tile size. This will update the number of horizontal * and vertical tiles. * @param pt The tile size. pt.x = width, pt.y = height * @param height The tile height. */ void setTileSize(const ossimIpt& pt); /** * @brief Sets the resampling type. * * Supports BOX or NEAREST NEIGHBOR. * When indexed you should probably use nearest neighbor. * default = ossimFilterResampler::ossimFilterResampler_BOX * * @param resampleType The resampling method to use. */ void setResampleType( ossimFilterResampler::ossimFilterResamplerType resampleType); /** * @brief Turn on/off scan for min max flag. * This method assumes the null is known. * @param flag true turns scan on, false off. Default=off. */ void setScanForMinMax(bool flag); /** @return scan for min max flag. */ bool getScanForMinMax() const; /** * @brief Turn on/off scan for min, max, null flag. * Attempts to find null, min and max where null is the minimum value found, * min is the second most min and max is max. * @param flag true turns scan on, false off. Default=off. */ void setScanForMinMaxNull(bool flag); /** @return scan for min max flag. */ bool getScanForMinMaxNull() const; /** * @brief Writes an ossim metadata(omd) file with min, max, null values. * * Writes omd file to disk with min, max, null values. If file existed * previously it will be ingested into keyword list prior to addition * of the min, max, nulls computed in this method. * * Note that prior to writing a sanity check is performed on the values as * a scan for null value might actually pick up the min if the image is * full. * * @param file to write. */ bool writeOmdFile(const std::string& file); protected: /** virtual destructor */ virtual ~ossimOverviewSequencer(); /** * @brief Gets the image rectangle for the input tile for * theCurrentTileNumber. * @param inputRect The rectangle to initialize. */ void getInputTileRectangle(ossimIrect& inputRect) const; /** * @brief Gets the image rectangle for the output tile for * theCurrentTileNumber. * @param outputRect The rectangle to initialize. */ void getOutputTileRectangle(ossimIrect& outputRect) const; /** * @brief Updates theNumberOfTilesHorizontal and theNumberOfTilesVertical. * * This required theAreaOfInterest and theTileSize to be set. */ void updateTileDimensions(); /** * Resamples a patch of data. */ void resampleTile(const ossimImageData* inputTile); template void resampleTile(const ossimImageData* inputTile, T dummy); /** @brief Clears out the arrays from a scan for min, max, nulls. */ void clearMinMaxNullArrays(); ossimRefPtr m_imageHandler; ossimRefPtr m_maskWriter; ossimRefPtr m_maskFilter; ossimRefPtr m_tile; ossimIrect m_areaOfInterest; ossimIpt m_tileSize; ossim_uint32 m_numberOfTilesHorizontal; ossim_uint32 m_numberOfTilesVertical; ossim_uint32 m_currentTileNumber; /** This is the resolution level to build overviews from. */ ossim_uint32 m_sourceResLevel; /** Dirty flag - if true, this object is not initialized. */ bool m_dirtyFlag; /** TODO make this handle any decimation. Right now hard coded to two. */ ossim_int32 m_decimationFactor; /** Currently only handles NEAREST_NEIGHBOR and BOX (default = BOX) */ ossimFilterResampler::ossimFilterResamplerType m_resampleType; ossimRefPtr m_histogram; ossimHistogramMode m_histoMode; /** * Used to determine which tiles to accumulate a histogram from. If set to * 1 every tile is accumulated, 2 every other tile, 3 every 3rd tile, and * so on. Set in initialize method based on mode and image size. */ ossim_uint32 m_histoTileIndex; /** Control flags for min, max, null scanning. */ bool m_scanForMinMax; bool m_scanForMinMaxNull; /** Arrays o hold the min value for each band for scan min/max methods. */ std::vector m_minValues; std::vector m_maxValues; std::vector m_nulValues; }; #endif /* #ifndef ossimOverviewSequencer_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimPdfWriter.h000066400000000000000000000362321352751253100232430ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file // // Author: David Burken // // Description: OSSIM Portable Document Format (PDF) writer. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimPdfWriter_HEADER #define ossimPdfWriter_HEADER 1 #include #include #include #include #include #include #include #include #include // Forward class declarations: class ossimImageData; class ossimIpt; class ossimIrect; /** * @class ossimPdfWriter * * References: * * Adobe PDF Reference sixth edition, Version 1.7 November 2006 * pdf_reference_1-7.pdf * * PDF Georegistration Encoding Best Practice Version (2.2 OGC 08-139r3) * 08-139r3_PDF_Geo-registration_Encoding_Best_Practice_Version_2.2.pdf * * @note Spaces and newlines for formatting have been left in the code for * sanity purposes only. Code is heavily traced. You can enable trace on any * ossim application with "-T ossimPdfWriter". */ class OSSIM_DLL ossimPdfWriter : public ossimImageFileWriter { public: enum ossimPdfImageType { UNKNOWN = 0, JPEG = 1, // JPEG RAW = 2 // general raster, band interleaved by pixel(BIP) }; /** @brief default constructor */ ossimPdfWriter(); /** @brief virtual destructor */ virtual ~ossimPdfWriter(); /** @return "pdf writer" */ virtual ossimString getShortName() const; /** @return "ossim pdf writer" */ virtual ossimString getLongName() const; /** @return "ossimPdfWriter" */ virtual ossimString getClassName() const; /** * @brief Returns a 3-letter extension from the image type descriptor * (theOutputImageType) that can be used for image file extensions. * * @param imageType string representing image type. * * @return the 3-letter string extension. */ virtual ossimString getExtension() const; /** * @brief void getImageTypeList(std::vector& imageTypeList)const * * Appends this writer image types to list "imageTypeList". * * This writer only has one type "pdf". * * @param imageTypeList stl::vector list to append to. */ virtual void getImageTypeList(std::vector& imageTypeList)const; /** @return true if open, false if not. */ virtual bool isOpen() const; /** * @brief Open method. * @return True on success, false on error. */ virtual bool open(); /** @brief Closes file. */ virtual void close(); /** @brief saves the state of the object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * @brief Method to the load (recreate) the state of an object from a keyword * list. * @return True on success, false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @brief Will set the property whose name matches the argument * "property->getName()". * * @param property Object containing property to set. */ virtual void setProperty(ossimRefPtr property); /** * @brief Gets property for name. * * @param name Name of property to return. * * @returns A pointer to a property object which matches "name". */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Pushes this's names onto the list of property names. * * @param propertyNames array to add this's property names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool hasImageType(const ossimString& imageType) const; /** * @brief Method to write the image to a stream. * * @return true on success, false on error. */ virtual bool writeStream(); /** * @brief Sets the output stream to write to. * * The stream will not be closed/deleted by this object. * * @param output The stream to write to. */ virtual bool setOutputStream( std::ostream& stream ); private: /** * @brief Writes the file to disk or a stream. * @return true on success, false on error. */ virtual bool writeFile(); /** * @brief Writes header. * @param str Stream to write to. */ void writeHeader( std::ostream* str ); /** * @brief Writes Catalog object. * @param str Stream to write to. * @param xref To capture object positions. */ void writeCatalog( std::ostream* str, std::vector& xref ); /** * @brief Writes Outlines object. * @param str Stream to write to. * @param xref To capture object positions. */ #if 0 void writeOutlines( std::ostream* str, std::vector& xref ); #endif /** * @brief Writes Pages object. * @param str Stream to write to. * @param xref To capture object positions. */ void writePages( std::ostream* str, std::vector& xref ); /** * @brief Writes document infomation dictionary. * @param str Stream to write to. * @param xrefOffset Offset to cross reference(xref) table. */ void writeInfo( std::ostream* str, std::vector& xref ); /** * @brief Writes the image dictionary and associated objects. * @param str Stream to write to. * @return true on success, false on error. */ bool writeImage( std::ostream* str ); /** * @brief Write a JPEG-compresses the raster tile buffer to the output stream * provided. * @param str Stream to write to. * @param xref To capture object positions. * @param id Pointer to tile data. * @param aoi Area of interest. * @param outputTileRect Initialized by this with output tile rect clamped * to aoi. */ void writeJpegTile( std::ostream* str, std::vector& xref, ossimImageData* id, const ossimIrect& aoi, ossimIrect& outputTileRect ); /** * @brief Write raw raster tile buffer to the output stream * provided. * @param str Stream to write to. * @param xref To capture object positions. * @param id Pointer to tile data. * @param aoi Area of interest. * @param outputTileRect Initialized by this with output tile rect clamped * to aoi. */ void writeRawTile( std::ostream* str, std::vector& xref, ossimImageData* id, const ossimIrect& aoi, ossimIrect& outputTileRect ); /** * @brief Writes Cross Reference(xref) section. * @param str Stream to write to. * @param xref Array of object offsets. */ void writeXref( std::ostream* str, const std::vector& xref ); /** * @brief Writes trailer. * @param str Stream to write to. * @param entrySize Number of entries, one plus object count. * @param xrefOffset Offset to cross reference(xref) table. */ void writeTrailer( std::ostream* str, ossim_uint32 entrySize, std::streamoff xrefOffset ); /** * @brief Writes "dummy" or blank object just to keep object references * in line. * @param str Stream to write to. * @param xref To capture object positions. */ #if 0 void writeDummy( std::ostream* str, std::vector& xref ); #endif /** * @brief Sets up input image source. * This sets up the chain fed to theInputConnection which is an image * source sequencer. This will remap input to eight bit if not already and * make input one or three band depending on number of bands. Also sets * m_saveInput for reconnection at the end of write. */ void setupInputChain(); /** * @brief Gets the enumerated value of IMAGE_TYPE_KW lookup. * * This is the image type of the stream embedded in the pdf. * Default "raw" if not found. * * @return ossimPdfImageType, e.g. PNG, RAW... */ ossimPdfImageType getImageType() const; /** * @brief Initializes image type from IMAGE_TYPE_KW lookup. * * This is the image type of the stream embedded in the pdf. * Default "raw" if not found. * * @param type Initialized by this. */ void getImageType( std::string& type ) const; /** * @brief Adds option to m_kwl with mutex lock. * @param key * @param value */ void addOption( const std::string& key, const std::string& value ); /** * @brief Gets the page size. * * Takes into account image width, height, and annotations. * * @param width Width of image. * @param height Height of image. * @param size Initialized by this. */ #if 0 void getMediaBoxSize( ossim_uint32 imageWidth, ossim_uint32 imageHeight, ossimIpt& size ) const; #endif /** * @brief Gets page offset for image from lower left corner of media box. * @param aoi Area of interest. * @param offset Initialized by this. */ void getLowerLeftPageOffset( const ossimIrect& aoi, ossimIpt& offset ) const; /** * @brief Get the LGIDict string. * @param geom Image geometry. * @param aoi Area of interest. * @param s Initialized by this. */ void getLgiDict( ossimImageGeometry* geom, const ossimIrect& aoi, std::string& s ) const; /** * @brief Gets projection part of LGIDict string. * @param geom Image geometry. * @param s Initialized by this. */ void getLgiDictProjection( ossimImageGeometry* geom, std::string& s ) const; /** * @brief Gets Coordinate Transformation Matrix(CTM) part of * LGIDict string from geom. * @param geom Image geometry. * @param aoi Area of interest. * @param s Initialized by this or cleared on error. */ void getLgiDictCtm( ossimImageGeometry* geom, const ossimIrect& aoi, std::string& s ) const; /** * @brief Gets datum part of LGIDict string from geom. * @param geom Image geometry. * @param s Initialized by this or cleared on error. */ void getLgiDictDatum( ossimImageGeometry* geom, std::string& s ) const; /** * @brief Gets description part of LGIDict string from geom. * @param geom Image geometry. * @param s Initialized by this or cleared on error. */ void getLgiDictDescription( ossimImageGeometry* geom, std::string& s ) const; /** * @brief Gets neatline part of LGIDict string from geom. * @param geom Image geometry. * @param s Initialized by this or cleared on error. */ #if 0 void getLgiDictNeatline( ossimImageGeometry* geom, std::string& s ) const; #endif /** * @brief Gets projection type part of LGIDict string from geom. * @param geom Image geometry. * @param s Initialized by this or cleared on error. */ void getLgiDictProjectionType( ossimImageGeometry* geom, std::string& s ) const; /** * @brief Gets the EPSG/PCS code from geometry. * @param geom Image geometry. * @return EPSG code or 32767 on error. */ ossim_uint32 getEpsgCode( const ossimImageGeometry* geom ) const; #if 0 void getNumberOfTiles( ossim_uint32 imageWidth, ossim_uint32 imageHeight, ossimIpt& size ) const; #endif /** * @brief Gets the Title. * * Looks in m_kwl for options keyword: "Title" * * Defaults to basename of output file if not found. * * @param s Initialed by this. */ void getTitle( std::string& s ) const; /** * @brief Gets the Author. * * Looks in m_kwl for options keyword: "Author" * * Defaults to "ossim" if not found. * * @param s Initialed by this. */ void getAuthor( std::string& s ) const; /** * @brief Gets the Subject. * * Looks in m_kwl for options keyword: "Subject" * * Default: No default, empty string if not found. * * @param s Initialed by this. */ void getSubject( std::string& s ) const; /** * @brief Gets the Keywords. * * Looks in m_kwl for options keyword: "Keywords" * * Default: No default, empty string if not found. * * @param s Initialed by this. */ void getKeywords( std::string& s ) const; /** * @brief Gets the Creator. * * Looks in m_kwl for options keyword: "Creator" * * Defaults to "ossim" if not found. * * @param s Initialed by this. */ void getCreator( std::string& s ) const; /** * @brief Gets the Producer. * * Looks in m_kwl for options keyword: "Producer" * * Defaults to "ossim" if not found. * * @param s Initialed by this. */ void getProducer( std::string& s ) const; /** * @brief Gets the Producer. * * Looks in m_kwl for options keyword: "CreationDate" * * Defaults to current time if not found. * * @param s Initialed by this. * * NOTE: This is a formatted string in the form of: * D:YYYYMMDDHHmmSSOHH'mm' */ void getCreationDate( std::string& s ) const; /** * @brief Gets the Producer. * * Looks in m_kwl for options keyword: "ModDate" * * Defaults to current time if not found. * * @param s Initialed by this. * * NOTE: This is a formatted string in the form of: * D:YYYYMMDDHHmmSSOHH'mm' */ void getModDate( std::string& s ) const; /** * @brief Get's the date in format of: * (D:YYYYMMDDHHmmSSZ00'00') * * @param s Initialed by this. * * NOTE: Date code is NOT thread safe. */ void getGmtDate( std::string& s ) const; /** * @brief Gets tiles size as string. * * Looks in m_kwl for options keyword: "output_tile_size" * * Defaults to 1024 if not found. * * @param s Initialized by this. */ void getTileSize( std::string& s ) const; /** * @brief Gets Tile size as integer point. * * Defaults to 1024x1024 if not found. * @param tileSize Initialized by this. */ void getTileSize( ossimIpt& tileSize ) const; /** * @return string for x and y in the form of (x=1, y=3): "/Tile_0001_0003" */ std::string getTileString( ossim_uint32 x, ossim_uint32 y ) const; std::ostream* m_str; bool m_ownsStream; /** * Holds the origin end of the chain connected to theInputConnection. */ ossimRefPtr m_savedInput; /** Holds all options in key, value pair map. */ ossimRefPtr m_kwl; std::mutex m_mutex; TYPE_DATA }; #endif /* #ifndef ossimPdfWriter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimPiecewiseRemapper.h000066400000000000000000000176351352751253100247540ustar00rootroot00000000000000//--- // License: MIT // // Author: David Burken // // Description: // // Piecewise remapper class declaration. // //--- // $Id$ #ifndef ossimPiecewiseRemapper_HEADER #define ossimPiecewiseRemapper_HEADER 1 #include #include #include /** * @class ossimPiecewiseRemapper * * This class provides piecewise linear remapping of input pixels to output pixels. The * object's state is represented as: * * band0.remap0: ( , , ...) * band0.remap1: ( , ... ) * * The vertices of each linear segment are specified as four numbers in parentheses: * * (, , , ) * * A linear function is computed to map min_in to min_out and likewise max_in to max_out, * with all intermediate points distributed linearly between the two extremes. Multiple * remaps are cascaded: if an input pixel's value falls outside the ranges defined in the * first remapper, then the second remapper's table is referenced. The cascading continues * until a value is found. If no lookup is available, the output pixel is assigned to the * NULL value. * * Example: Given object2 with a state of: * * object2.type: ossimPiecewiseRemapper * object2.remap_type: linear_native * object2.band0.remap0: ( (0, 127, 0, 127), (128, 255, 128, 382) ) * object2.band0.remap1: ( (0, 382, 0, 255) ) * * remap0 applied: * The input range 0 <-> 127 passes through with a one-to-one mapping. * 128 <-> 255 is stretched out to 128 <-> 382. * * remap0 output is fed to remap1: * 0 maps to 0 and 382 maps to 255 (compression). * * Notes: * * 1) Currently there is only one remap type (linear_native) is supported so it's not * needed but left in the code for future type remaps, e.g. a remap where there is * a linear and a logarithmic section. * * 2) Any number of "remaps" are allowed. * */ class OSSIMDLLEXPORT ossimPiecewiseRemapper : public ossimTableRemapper { public: enum PiecewiseRemapType { UNKNOWN = 0, LINEAR_NATIVE = 1 }; /** default constructor */ ossimPiecewiseRemapper(); /** @return "ossimPiecewiseRemapper" */ virtual ossimString getClassName()const; /** @return "OSSIM Piecewise Remapper" */ virtual ossimString getLongName() const; /** @return "Piecewise Remapper" */ virtual ossimString getShortName() const; /** * @brief Get tile method. * @param tileRect Region of interest. * @param resLevel Resolution level. * @param The requested region of interest for resolution level. */ virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel = 0); /** @brief Initialization method. Called on state change of chain. */ virtual void initialize(); /** * @brief Sets remap type. * * Current types: "linear_native" * * @param type */ void setRemapType( const std::string& type ); /** * @brief Saves the state to a keyword list. * @return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * @brief Loads (recreates) the state of an object from a keyword * list. * @return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** @brief Print method. Called by ossimObject::operator<<. */ virtual std::ostream& print(std::ostream& os) const; /** @return The min pixel of the band. */ virtual double getMinPixelValue(ossim_uint32 band=0)const; /** @return The max pixel of the band. */ virtual double getMaxPixelValue(ossim_uint32 band=0)const; protected: /** * @brief Protected virtual destructor. * * This class is derived from ossimReferenced; hence, will auto destruct * provided it is wrapped/stored in an ossimRefPtr. Example usage: * * ossimRefPtr pwr = new ossimPiecewiseRemapper(); */ virtual ~ossimPiecewiseRemapper(); private: /** * @class ossimRemapSet * * Private container class. Currently hold an array of doubles. */ class ossimRemapSet { public: ossimRemapSet(); ossimRemapSet(const ossimRemapSet& obj); const ossimRemapSet& operator=(const ossimRemapSet& rhs); std::vector m_set; }; /** * @class ossimBandRemap * * Private container class. Holds array of ossimRemapSets for a given band. */ class ossimBandRemap { public: ossimBandRemap(); ossimBandRemap(const ossimBandRemap& obj); const ossimBandRemap& operator=(const ossimBandRemap& rhs); void loadState( const ossimKeywordlist& kwl, const std::string& prefix, ossim_uint32 band ); void saveState( ossimKeywordlist& kwl, const std::string& prefix, ossimPiecewiseRemapper::PiecewiseRemapType remapType, ossim_uint32 band ) const; /** * @brief Initializes set from string. * * Example input: ((0, 127, 0, 127), (128, 255, 128, 382)) * * @param s String to initialize from. * @param set Initialized by this. */ bool initRemapSetFromString( const std::string& s, ossimPiecewiseRemapper::ossimRemapSet& set ) const; /** * @brief Gets a string from remap set for type. * @param remapType * @param set * @param s Initialized by this. */ void getRemapSetString( ossimPiecewiseRemapper::PiecewiseRemapType remapType, const ossimPiecewiseRemapper::ossimRemapSet& set, std::string& s ) const; void getLinearRemapSetString( const ossimPiecewiseRemapper::ossimRemapSet& set, std::string& s ) const; std::vector m_remap; }; // End: class ossimBandRemap /** * @brief Gets a string from remap type. * @param remapType * @param s Initialized by this. */ void getRemapTypeString( ossimPiecewiseRemapper::PiecewiseRemapType remapType, std::string& s ) const; /** * @brief Gets a string from remap set. * * Example output: ((0, 127, 0, 127), (128, 255, 128, 382)) * * @param set * @param s Initialized by this. */ void getLinearRemapSetString( const ossimPiecewiseRemapper::ossimRemapSet& set, std::string& s ) const; /** @brief Builds the table. */ void buildTable(); /** @brief Builds the linear native table. */ void buildLinearNativeTable(); /** @brief Builds the linear native table for scalar type T. */ template void buildLinearNativeTable(T dummy); /** * @brief Initialized base class (ossimTableRemapper) values: * - theTableBinCount * - theTableBandCount * - theTableType * - theTable (resizes if not correct size. */ void setupTable(); /** @brief Computes min/max from remaps in m_bandRemap. */ void initMinMax(); /** @private(not allowed) copy constructor. */ ossimPiecewiseRemapper(const ossimPiecewiseRemapper& obj); /** @private(not allowed) assignment(operator=) */ ossimPiecewiseRemapper& operator=(const ossimPiecewiseRemapper& hr); /** @brief Dirty flag to indicate table needs to be rebuilt. */ bool m_dirty; PiecewiseRemapType m_remapType; // One set per band. std::vector m_bandRemap; #if 1 /* Not sure if we need min/max right now.(drb) */ // Stores the min/max from the table for each band. std::vector m_min; std::vector m_max; #endif TYPE_DATA }; #endif /* #ifndef ossimPiecewiseRemapper_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimPixelFlipper.h000066400000000000000000000234421352751253100237370ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class to scan pixels and flip target dn pixel value to new dn pixel value. // This was written to fix partial null pixels. // //************************************************************************* // $Id: ossimPixelFlipper.h 19728 2011-06-06 21:31:17Z dburken $ #ifndef ossimPixelFlipper_HEADER #define ossimPixelFlipper_HEADER #include #include #include /** * Class to scan pixels and flip target dn value to a replacement dn * value. * * This was written to fix problems with null pixels, i.e. an image has a * digital number(dn) of 255 for null and it is desired to use a dn of 0 as * a null. This can really be used to flip any pixel value to another. * * @note This filter currently works on the input tile directly and does * not copy the data. * * @see theReplacementMode data member documentation for more info. */ class OSSIM_DLL ossimPixelFlipper : public ossimImageSourceFilter { public: static const char PF_TARGET_VALUE_KW[]; static const char PF_TARGET_RANGE_KW[]; static const char PF_REPLACEMENT_VALUE_KW[]; static const char PF_REPLACEMENT_MODE_KW[]; static const char PF_CLAMP_VALUE_KW[]; static const char PF_CLAMP_VALUE_LO_KW[]; static const char PF_CLAMP_VALUE_HI_KW[]; static const char PF_CLIP_MODE_KW[]; /** * Target Replacement Mode: * * Examples given for 3-band pixel values as (R, G, B) with target = 0, and replacement = 1 * If mode is REPLACE_BAND_IF_TARGET (default): * Any pixel band with value of target will be replaced. * (0, 0, 0) becomes (1, 1, 1) * (0, 3, 2) becomes (1, 3, 2) * * If mode is REPLACE_BAND_IF_PARTIAL_TARGET: * A band with target value will be replaced only if at least one other band in the pixel does * not have the target. * (0, 0, 0) remains (0, 0, 0) * (0, 3, 2) becomes (1, 3, 2) * * If mode is REPLACE_ALL_BANDS_IF_PARTIAL_TARGET: * All bands of the pixel will be replaced if any but not all bands in the pixel have the * target value. * (0, 0, 0) remains (0, 0, 0) * (0, 3, 2) becomes (1, 1, 1) * * If mode is REPLACE_ONLY_FULL_TARGETS: * All bands in the pixel will be replaced only if they all have the target. * (0, 0, 0) becomes (1, 1, 1) * (0, 3, 2) remains (0, 3, 2) * * If mode is REPLACE_ALL_BANDS_IF_ANY_TARGET: * All bands in the pixel will be replaced if even one band has the target. * (0, 0, 0) becomes (1, 1, 1) * (0, 3, 2) remains (1, 1, 1) */ enum ReplacementMode { REPLACE_BAND_IF_TARGET = 0, REPLACE_BAND_IF_PARTIAL_TARGET = 1, REPLACE_ALL_BANDS_IF_PARTIAL_TARGET = 2, REPLACE_ONLY_FULL_TARGETS = 3, REPLACE_ALL_BANDS_IF_ANY_TARGET = 4, }; /** * When either a lo and/or hi clamp value is set, the clamping mode will be enabled accordingly * and override any target replacement defined */ enum ClampingMode { DISABLED = 0, CLAMPING_LO = 1, CLAMPING_HI = 2, CLAMPING_LO_AND_HI = 3, }; enum ClipMode { NONE = 0, BOUNDING_RECT = 1, VALID_VERTICES = 2 }; /** default constructor */ ossimPixelFlipper(ossimObject* owner=NULL); /** @return "Pixel flipper" as an ossimString. */ virtual ossimString getShortName()const; /** Initializes the state of the object from theInputConnection. */ virtual void initialize(); /** * @param tile_rect Rectangle to fill tile with. * * @param resLevel Reduced resolution level to grab from. * * @return ossimRefPtr This is tile that was filled with * tile_rect. * * @note Callers should check the ossimRefPtr::valid method. * The internal pointer of the ossimRefPtr can be * null if the tile_rect did not intersect the input connection's * bounding rectangle. */ virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual ossimScalarType getOutputScalarType() const; virtual ossim_float64 getMaxPixelValue (ossim_uint32 band = 0 ) const; virtual ossim_float64 getMinPixelValue (ossim_uint32 band = 0 ) const; virtual std::ostream& print(std::ostream& out) const; /** * @param target_value This is the value to flip. * @note If clamping is specified, it will take precedence over any target value (or range) test */ void setTargetValue(ossim_float64 target_value); /** * Instead of a single value for a target, this method allows for specifying a range of values * to flip to the replacement. The replacement mode is still referenced. * @param This is the value to flip. * @note If clamping is specified, it will take precedence over any target range test. */ void setTargetRange(ossim_float64 target_min, ossim_float64 target_max); /** * @param replacement_value This is the value to flip target to. * @note If clamping is specified, it will take precedence over any target replacement. */ void setReplacementValue(ossim_float64 replacement_value); /** * @param clamp_value If set all pixel values above this range will (or below if clamp_max_value * = false) be clamped to clamp_value. Must be less than max pixel (or greater than the min * pixel) value of the input and cannot be null. * @note If any clamp limit is defined, it will take precedence over any target value (or range) * replacement. The replacement mode is referenced when deciding whether a pixel should be * clamped or left alone. */ void setClampValue(ossim_float64 clamp_value, bool is_high_clamp_value=true); void setClampValues(ossim_float64 clamp_value_lo, ossim_float64 clamp_value_hi); /** @see enum ReplacementMode */ void setReplacementMode(ossimPixelFlipper::ReplacementMode mode); /** Accepts a string that must match the enumerator's label (can be lower case) and sets the * replacement mode accordingly. If the string is not understood, the mode remains unchanged and * FALSE is returned. */ bool setReplacementMode(const ossimString& modeString); /** * Clipping here refers to bounding rect or valid polygon (spacial) clipping, where all pixels * outside the valid area are mapped to the replacement value. */ void setClipMode(const ossimString& modeString); void setClipMode(ClipMode mode); //ossim_float64 getTargetValue() const; ossim_float64 getReplacementValue() const; //ossim_float64 getClampValue() const; ossimPixelFlipper::ReplacementMode getReplacementMode() const; ossimString getReplacementModeString() const; ossimString getClipModeString() const; ClipMode getClipMode() const; virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void setProperty(ossimRefPtr property); virtual void getPropertyNames(std::vector& propertyNames)const; protected: /** destructor */ virtual ~ossimPixelFlipper(); //! This object can be used outside of an image chain for offline processing of existing tile. template void flipPixels(T dummy, ossimImageData *inpuTile, ossim_uint32 resLevel); template void clipTile(T dummy, ossimImageData *inpuTile, ossim_uint32 resLevel); /** * Verifies pixel is in range. * @return Returns true if in range else false. */ bool inRange(ossim_float64 value) const; void allocateClipTileBuffer(ossimRefPtr inputImage); /** The value range to replace. For a single value replacement, both Lo and Hi are equal. Any * pixel within this range will be remapped to the replacement value */ ossim_float64 theTargetValueLo; ossim_float64 theTargetValueHi; /** When target values are defined, this is the value the pixel will assume if the pixel falls * within the target range (according to the rules for replacement mode) */ ossim_float64 theReplacementValue; ReplacementMode theReplacementMode; //!< See documentation for ReplacementMode enum above /** The range of desired pixel values. Any pixels outside this range are set to the corresponding * clamp value. Note that theReplacementValue is not referenced when clamping. */ ossim_float64 theClampValueLo; ossim_float64 theClampValueHi; ClampingMode theClampingMode; /** * Border Clip mode * * This will flip to nulls any pixel value outside the specified mode. * * Valid modes are: * * none * bounding_rect * valid_vertices * * if the mode is "none" then nothing is done. * if the mode is "bounding_rect" then the bounding rect for the requested rlevel * is used and every pixel outside that */ ClipMode theClipMode; /** For lock and unlock. */ mutable std::recursive_mutex theMutex; mutable std::vector theValidVertices; mutable std::vector theBoundingRects; ossimRefPtr theClipTileBuffer; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimPolyCutter.h000066400000000000000000000062061352751253100234450ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimPolyCutter.h 19907 2011-08-05 19:55:46Z dburken $ #ifndef ossimPolyCutter_HEADER #define ossimPolyCutter_HEADER #include #include #include #include //class ossimPolyArea2d; class ossimImageData; class OSSIMDLLEXPORT ossimPolyCutter : public ossimImageSourceFilter { public: enum ossimPolyCutterCutType { OSSIM_POLY_NULL_INSIDE = 0, OSSIM_POLY_NULL_OUTSIDE = 1 }; ossimPolyCutter(); ossimPolyCutter(ossimImageSource* inputSource, const ossimPolygon& polygon); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; virtual void initialize(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void setPolygon(const std::vector& polygon, ossim_uint32 i = 0); virtual void setPolygon(const std::vector& polygon, ossim_uint32 i = 0); virtual void addPolygon(const std::vector& polygon); virtual void addPolygon(const std::vector& polygon); virtual void addPolygon(const ossimPolygon& polygon); virtual void setNumberOfPolygons(ossim_uint32 count); virtual std::vector& getPolygonList(); virtual const std::vector& getPolygonList()const; void setCutType(ossimPolyCutterCutType cutType); ossimPolyCutterCutType getCutType()const; void clear(); const ossimIrect& getRectangle() const; void setRectangle(const ossimIrect& rect); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimPolyCutter(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); void computeBoundingRect(); ossimRefPtr theTile; /*! * Will hold a pre-computed bounding rect of the * polygon data. */ ossimIrect theBoundingRect; std::vector thePolygonList; /*! * theDefault fill will be outside. */ ossimPolyCutterCutType theCutType; ossimImageDataHelper theHelper; bool m_boundingOverwrite; TYPE_DATA }; #endif /* #ifndef ossimPolyCutter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimQbTileFilesHandler.h000066400000000000000000000026021352751253100247700ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //************************************************************************************************** // $Id: ossimQbTileFilesHandler.h 2669 2011-06-06 12:28:20Z oscar.kramer $ #ifndef ossimQbTileFilesHandler_HEADER #define ossimQbTileFilesHandler_HEADER #include // Enable this flag to utilize the system of separate overviews for each tile-file #define USING_SUB_OVRS 0 //! Image handler used for tiled Quickbird imagery. class OSSIMDLLEXPORT ossimQbTileFilesHandler : public ossimTiledImageHandler { public: //! Constructor (default): ossimQbTileFilesHandler(); //! Destructor: virtual ~ossimQbTileFilesHandler(); //! @return Returns true on success, false on error. //! @note This method relies on the data member ossimImageData::theImageFile being set. virtual bool open(); virtual ossimRefPtr getImageGeometry(); protected: //! Initializes tile image rects by considering adjacent row/col offsets. Called when TIL //! doesn't contain the info. Returns true if successful. bool computeImageRects(); TYPE_DATA }; #endif /* #ifndef ossimQbTileFilesHandler_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimQuickbirdNitfTileSource.h000066400000000000000000000024541352751253100260710ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimQuickbirdNitfTileSource.h 22836 2014-07-25 15:13:47Z dburken $ #ifndef ossimQuickbirdNitfTileSource_HEADER #define ossimQuickbirdNitfTileSource_HEADER #include #include class ossimQuickbirdNitfTileSource : public ossimNitfTileSource { public: virtual bool open(); virtual ossimRefPtr getImageGeometry(); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: ossimRefPtr m_transform; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimQuickbirdTiffTileSource.h000066400000000000000000000020351352751253100260540ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Copied from ossimQuickbirdNitfTileSource written by Garrett Potts. // // Description: // // Class declaration for specialized image handler to pick up offsets from // Quick Bird ".TIL" files. // //---------------------------------------------------------------------------- // $Id: ossimQuickbirdTiffTileSource.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimQuickbirdTiffTileSource_HEADER #define ossimQuickbirdTiffTileSource_HEADER #include #include class OSSIM_DLL ossimQuickbirdTiffTileSource : public ossimTiffTileSource { public: virtual bool open(); virtual ossimRefPtr getImageGeometry(); protected: ossimFilename m_tileInfoFilename; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimRLevelFilter.h000066400000000000000000000070601352751253100236710ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRLevelFilter.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimRLevelFilter_HEADER #define ossimRLevelFilter_HEADER #include /*! * This filter is used to adjust the RLevel. If you would like to * continually change between RLevels or Reslolutions then you can use this * filter to do so. You can also specify whether or not the rLevel * passed in from the getTile request is added to this classes current * Rlevel. This is so if you concatenate multiple filters that reduce * the RLevels then it will keep reducing. For example if I have * 2 filters that both go to RLevel 1 then it actually will go to * 2 since there are 2 decimations happening. This can be turned off * by specifying the Rlevel not to be additive. */ class OSSIMDLLEXPORT ossimRLevelFilter : public ossimImageSourceFilter { public: /** @brief default constructor */ ossimRLevelFilter(); virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result)const; //! Returns a pointer reference to the active image geometry at this filter. The input source //! geometry is modified, so we need to maintain our own geometry object as a data member. ossimRefPtr getImageGeometry(); virtual void setCurrentRLevel(ossim_uint32 rlevel); virtual ossim_uint32 getCurrentRLevel()const; /*! * Get/set of the data member "theOverrideGeometryFlag". * If set this will override the "getImageGeometry" method and adjust * the getMetersPerPixel or the getDecimalDegreesPerPixel. * Default behavior is to not override method. */ virtual bool getOverrideGeometryFlag() const; virtual void setOverrideGeometryFlag(bool override); /** * @brief Returns the bounding rectangle. * * @param resLevel This argument is only passed onto the input connection * if this filter is disabled. @see disableSource(). * * To get the bounding rectangle of an rlevel when source is enabled do: * myRLevelFilter->setCurrentRLevel(level); * myRLevelFilter->getBoundingRect(); * * @return Rectangle of the current rlevel if enabled; else, the rectangle * of the input connection for resLevel. */ virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0) const; virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: /** @brief virtual destructor. */ virtual ~ossimRLevelFilter(); /*! * Initializes result with the sum of decimations from rlevel one to * theCurrentRLevel. */ void getSummedDecimation(ossimDpt& result) const; //! If this object is maintaining an ossimImageGeometry, this method needs to be called after //! a scale change so that the geometry's projection is modified accordingly. void updateGeometry(); ossim_uint32 theCurrentRLevel; bool theOverrideGeometryFlag; ossimRefPtr m_ScaledGeometry; //!< The input image geometry, altered by the scale TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimRangeDomeTileSource.h000077500000000000000000000075471352751253100252070ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id: ossimRangeDomeTileSource.h 23464 2015-08-07 18:39:47Z okramer $ #ifndef ossimRangeDomeTileSource_HEADER #define ossimRangeDomeTileSource_HEADER 1 #include #include #include #include #include #include class ossimImageData; struct ossimRangeDome { enum Classification { UNASSIGNED = 0, FRIENDLY_UNSPECIFIED = 1, FRIENDLY_LEVEL_1= 2, FRIENDLY_LEVEL_2 = 3, FRIENDLY_LEVEL_3 = 4, THREAT_UNSPECIFIED = 101, THREAT_LEVEL_1 = 102, THREAT_LEVEL_2 = 103, THREAT_LEVEL_3 = 104 }; ossimRangeDome(std::vector& tokens); ossimGrect boundingRect() const; bool valid; ossim_uint32 id; ossimGpt centerGpt; ossimDpt centerIpt; double radiusMeters; ossim_uint32 radiusPixelsSq; Classification classification; double startAz; double endAz; ossimString description; }; /** * Class used for rendering range domes (a.k.a. "threat domes") as 2-D ortho-images. * * This base class has the rudimentary capability of reading range dome specifications as a CSV file * in the following format (one line per dome object): * * id, lat, lon, hgt, R, C [,Az0, Az1] [, description] * * where * * id -- integer ID of data object * lat, lon, hgt -- Location of center of dome (actually sphere) in WGS84 * R -- radius (in meters) of dome boundary * C -- classification id (unsigned 8-bit) corresponding to area inside r * Az0, Az1 -- [optional] starting and ending azimuth (clockwise from Az0 in degrees). If both * Az0 and Az1 are equal, then 360 deg is implied. * description -- [optional] string */ class OSSIMDLLEXPORT ossimRangeDomeTileSource : public ossimImageHandler { public: ossimRangeDomeTileSource(); virtual ~ossimRangeDomeTileSource(); /** @brief Reads CSV file representing range domes. */ virtual bool open(); virtual bool isOpen() const; virtual void close(); virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); virtual ossim_uint32 getNumberOfInputBands() const; virtual ossim_uint32 getNumberOfLines(ossim_uint32 resLevel = 0) const; virtual ossim_uint32 getNumberOfSamples(ossim_uint32 resLevel = 0) const; virtual ossim_uint32 getImageTileWidth() const { return 0; } virtual ossim_uint32 getImageTileHeight() const { return 0; } virtual ossimScalarType getOutputScalarType() const { return OSSIM_UINT8; } virtual ossimRefPtr getImageGeometry() { return theGeometry; } virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * The reader properties are: * -- the GSD ("meters_per_pixel") */ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name) const; virtual void getGSD(ossimDpt& gsd, ossim_uint32 resLevel) const; virtual void setGSD( const ossim_float64& gsd ); ossim_uint32 getNumRangeDomes() const { return (ossim_uint32)m_rangeDomes.size(); } protected: std::vector m_rangeDomes; ossimDpt m_gsd; static const ossimString OSSIM_RANGE_DOME_SPEC_MAGIC_NUMBER; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimReadmeFileWriter.h000066400000000000000000000030231352751253100245170ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2003 Storage Area Networks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Kenneth Melero (kmelero@sanz.com) // //******************************************************************* // $Id: ossimReadmeFileWriter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimReadmeFileWriter_H #define ossimReadmeFileWriter_H #include #include /** ossimReadmeFileWriter */ class OSSIMDLLEXPORT ossimReadmeFileWriter : public ossimMetadataFileWriter { public: /** default constructor */ ossimReadmeFileWriter(); /** * Satisfies pure virtual from ossimMetadataWriter base. * * Appends the writers image types to the "metadatatypeList". * * @param metadatatypeList stl::vector list to append to. * * @note Appends to the list, does not clear it first. */ virtual void getMetadatatypeList( std::vector& metadatatypeList) const; /** * Satisfies pure virtual from ossimMetadataWriter base. * * @param imageType string representing image type. * * @return true if "metadataType" is supported by writer. */ virtual bool hasMetadataType(const ossimString& metadataType)const; protected: /** virtual destructor */ virtual ~ossimReadmeFileWriter(); virtual bool writeFile(); TYPE_DATA }; #endif /* End of #ifndef ossimReadmeFileWriter_H */ ossim-Miami-2.9.1/include/ossim/imaging/ossimRectangleCutFilter.h000066400000000000000000000036611352751253100250630ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRectangleCutFilter.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimRectangleCutFilter_HEADER #define ossimRectangleCutFilter_HEADER #include class OSSIM_DLL ossimRectangleCutFilter : public ossimImageSourceFilter { public: enum ossimRectangleCutType { OSSIM_RECTANGLE_NULL_INSIDE = 0, OSSIM_RECTANGLE_NULL_OUTSIDE = 1 }; ossimRectangleCutFilter(ossimObject* owner, ossimImageSource* inputSource=NULL); ossimRectangleCutFilter(ossimImageSource* inputSource=NULL); void setRectangle(const ossimIrect& rect); const ossimIrect& getRectangle()const; ossimRectangleCutType getCutType()const; void setCutType(ossimRectangleCutType cutType); ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; virtual void getValidImageVertices(std::vector& validVertices, ossimVertexOrdering ordering=OSSIM_CLOCKWISE_ORDER, ossim_uint32 resLevel=0)const; ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual void initialize(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); protected: ossimIrect theRectangle; ossimRectangleCutType theCutType; std::vector theDecimationList; TYPE_DATA }; #endif /* #ifndef ossimRectangleCutFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimResampler.h000066400000000000000000000175721352751253100232750ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts //******************************************************************* // $Id: ossimResampler.h 17195 2010-04-23 17:32:18Z dburken $ #ifndef ossimResampler_HEADER #define ossimResampler_HEADER #include #include #include #include class ossimImageData; /*! * This is currently implemented as a symmetric kernel resampler. * It will use a lookup table idea to precompute * * The resampler will support Nearest neighbor, Bilinear and Bicubic * * The lookup table approach will be borrowed from Michael J. Aramini * implementation of the Bicubic convolution: * * http://www.ultranet.com/~aramini/ * under: * Efficient Image Magnification by Bicubic Spline Interpolation. */ class ossimResampler : public ossimConnectableObject { public: enum ossimResLevelResamplerType { ossimResampler_NONE = 0, ossimResampler_NEAREST_NEIGHBOR = 1, ossimResampler_BILINEAR = 2, ossimResampler_BICUBIC = 3 }; ossimResampler(); /*! * Will apply the kernel to the input and write it to the output. * * Note: theTable is re-generated if the Max(out_width, out_height). * changes from the previous call. */ virtual void resample(ossimImageData* input, // input buffer ossimImageData* output); virtual void resample(ossimImageData* input, ossimImageData* output, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length); virtual void resample(ossimImageData* input, ossimImageData* output, const ossimIrect& outputSubRect, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length); virtual void resampleNearestNeighbor(ossimImageData* input, ossimImageData* output, const ossimIrect& outputSubRect, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length); virtual void resampleNearestNeighbor(ossimImageData* input, ossimImageData* output, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length); /*! * Will re-allocate the table */ virtual void setResamplerType(ossimResLevelResamplerType type); virtual ossimResLevelResamplerType getResamplerType()const { return theResamplerType; } virtual double getCubicParameter()const { return theCubicAdjustableParameter; } virtual void setCubicParameter(double parameter) { theCubicAdjustableParameter = parameter; theCubicAdjustableParameter = theCubicAdjustableParameter<-1?-1:theCubicAdjustableParameter; theCubicAdjustableParameter = theCubicAdjustableParameter>0?0:theCubicAdjustableParameter; if(theResamplerType == ossimResampler_BICUBIC) { generateWeightTable(); } } /*! * Will reallocate the table */ void setRatio(double outputToInputRatio); void setRatio(const ossimDpt& outputToInputRatio); ossimDpt getRatio()const { return theOutputToInputRatio; } virtual ossim_int32 getKernelWidth()const; virtual ossim_int32 getKernelHeight()const; /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); bool canConnectMyInputTo(ossim_int32 /* inputIndex */, const ossimConnectableObject* /* object */)const { return false; } protected: virtual ~ossimResampler(); ossimDpt theOutputToInputRatio; ossimResLevelResamplerType theResamplerType; ossim_int32 theTableWidthX; ossim_int32 theTableWidthY; ossim_int32 theTableHeight; ossim_int32 theKernelWidth; ossim_int32 theKernelHeight; /*! */ double **theWeightTableX; double **theWeightTableY; /*! * This adjustable parameter can vary between * -1 to 0. as the paramter goes from 0 * to -1 the output goes from blocky to smooth. * The default value is -.5 */ double theCubicAdjustableParameter; template void resampleTile(T, // dummy tmeplate variable ossimImageData* input, ossimImageData* output); template void resampleFullTile(T, // dummy tmeplate variable ossimImageData* input, ossimImageData* output); template void resamplePartialTile(T, // dummy tmeplate variable ossimImageData* input, ossimImageData* output); template void resampleTile(T, // dummy template variable ossimImageData* input, ossimImageData* output, const ossimIrect& outputSubRect, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length); template void resampleTileNearestNeighbor(T, // dummy template variable ossimImageData* input, ossimImageData* output, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length); template void resampleTileNearestNeighbor(T, // dummy template variable ossimImageData* input, ossimImageData* output, const ossimIrect& subRect, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length); virtual void deleteWeightTable(); virtual void allocateWeightTable(); virtual void generateWeightTable(); double getCubicC0(double t)const; double getCubicC1(double t)const; double getCubicC2(double t)const; double getCubicC3(double t)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimRgbGridRemapEngine.h000066400000000000000000000032011352751253100247560ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimRgbGridRemapEngine.h // // Copyright (C) 2001 ImageLinks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains declaration of class ossimRgbGridRemapEngine // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimRgbGridRemapEngine.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimRgbGridRemapEngine_HEADER #define ossimRgbGridRemapEngine_HEADER #include /*!**************************************************************************** * * CLASS: ossimRgbGridRemapEngine * *****************************************************************************/ class ossimRgbGridRemapEngine : public ossimGridRemapEngine { public: ossimRgbGridRemapEngine() : ossimGridRemapEngine(3, 3) {} virtual ossimObject* dup() const; virtual void remapTile(const ossimDpt& origin_point, ossimGridRemapSource* remapper, ossimRefPtr& tile); virtual void assignRemapValues(std::vector& sources); virtual void computeSourceValue(ossimRefPtr& source, void* result); protected: virtual void computeRemapNode(ossimAtbPointSource* point_source, void* source_value, void* target_value); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimRgbImage.h000066400000000000000000000275141352751253100230150ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbImage.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimRgbImage_HEADER #define ossimRgbImage_HEADER #include #include #include #include class OSSIM_DLL ossimRgbImage : public ossimReferenced { public: ossimRgbImage(); /** * @param currentImageData The tile to annotate or draw to. * @note This can be any number of bands; however, will only draw * to up to 3. */ ossimRgbImage(ossimRefPtr& currentImageData); /** * Will construct a new single band image data object. */ virtual void createNewGrey(ossim_int32 width, ossim_int32 height); /** * Will construct a new 3 band rgb data object. */ virtual void createNewTrueColor(ossim_int32 width, ossim_int32 height); /** * Will initilize any pre-computations that are needed. * Example: setting up the origin for adjustments and * setting up the offsets. */ virtual void initialize(); /** * This will plot a pixel and will do inside outside compares. * This assumes the pixel has already been put into a relative * 0,0 to the upper left corner of the image data. * * example: if the upperleft corner or origin of the image was * 34, 55 then it assumes that the points passed in are * already relative to that corner not absolute. */ inline void slowPlotPixel(ossim_int32 x, ossim_int32 y, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); /** * same thing as slowPlotPixel but without the inside outside compare */ inline void fastPlotPixel(ossim_int32 x, ossim_int32 y, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); /** * All the drawing algorithms have thickness. So you can draw a line * that has thickness of 3 pixels if you want. Note: the thickness is in * pixels */ void setThickness(ossim_int32 thickness); /** @return The thickness. */ ossim_int32 getThickness() const; /** * Allows you to change the image data that this RgbImage object * operates on. You can specify if the image owns the data or not. * if it doesn't own the data then it will not destroy it when the * data is changed to a different data object or if this object * is deleted. * * @param imageData The tile to annotate or draw to. * * @note This can be any number of bands; however, will only draw * to up to 3. */ void setCurrentImageData(ossimRefPtr& imageData); /** * Will return the image data. */ ossimRefPtr getImageData(); /** * We will cut and paste the code from * drawFilledPolygon(ossimIpt *p, int n). */ void drawFilledPolygon(const std::vector& p); /** * We will cut and paste the code from * drawFilledPolygon(ossimIpt *p, int n). */ void drawFilledPolygon(const std::vector& p); /** * This will draw a polygon and fill it with the specified color. */ void drawFilledPolygon(ossimDpt *p, int n); /** * This will draw a polygon and fill it with the specified color. */ void drawFilledPolygon(ossimIpt *p, int n); /** * will draw an arc. The cx and cy specifies the center point in image * space. The parameters w, h are the width and height of the arc. * The s and e are the starting and ending angles. So if I want to * draw a complete circle at point 45, 45 with width 10 and height 23 then * we set the angles s =0 and e = 360: * drawArc(45, 45, 10, 23, 0, 360). * */ void drawArc(double cx, double cy, double w, double h, double s, double e); /** * will draw an arc. The cx and cy specifies the center point in image * space. The parameters w, h are the width and height of the arc. * The s and e are the starting and ending angles. So if I want to * draw a complete circle at point 45, 45 with width 10 and height 23 then * we set the angles s =0 and e = 360: * drawArc(45, 45, 10, 23, 0, 360). * */ void drawArc(int cx, int cy, int w, int h, int s, int e); /** * Draws a filled ellipse. Rot is the major axis rotation from up. * rot (rotaition) is in radians. */ void drawFilledEllipse(int cx, int cy, int sminor, int smajor, double rot); /** * Draws an ellipse. Rot is the major axis rotation from up. * rot (rotation is in radians). */ void drawEllipse(int cx, int cy, int sminor, int smajor, double rot, bool drawAxes = false); /** * This will draw a filled arc. See drawArc for documentation of * parameters. */ void drawFilledArc(double cx, double cy, double w, double h, double s, double e); /** * This will draw a filled arc. See drawArc for documentation of * parameters. */ void drawFilledArc(int cx, int cy, int w, int h, int s, int e); void drawPolygon(const std::vector& p); void drawPolygon(const std::vector& p); /** * Draws a polygon. The first argument is an array of points. The second * argument is the number of points and the rest are the rgb color values. * theColor used is set by the setDrawColor. */ void drawPolygon(ossimDpt *p, int n); /** * Draws a polygon. The first argument is an array of points. The second * argument is the number of points and the rest are the rgb color values. * theColor used is set by the setDrawColor. */ void drawPolygon(ossimIpt *p, int n); /** * About all the draw routines will call draw line. it takes a start and * an end point and a color value. * theColor used is set by the setDrawColor. */ void drawLine(double x1, double y1, double x2, double y2); /** * About all the draw routines will call draw line. it takes a start and * an end point and a color value. * theColor used is set by the setDrawColor. */ void drawLine(int x1, int y1, int x2, int y2); /** * About all the draw routines will call draw line. it takes a start and * an end point and a color value. * theColor used is set by the setDrawColor. */ void drawLine(const ossimIpt& start, const ossimIpt& end); /** * About all the draw routines will call draw line. it takes a start and * an end point and a color value. * theColor used is set by the setDrawColor. */ void drawLine(const ossimDpt& start, const ossimDpt& end); /** * Will draw a rectangle. The color used is set by setDrawColor. */ void drawRectangle(double x1, double y1, double x2, double y2); /** * Will draw a rectangle. The color used is set by setDrawColor. */ void drawRectangle(int x1, int y1, int x2, int y2); /** * Will draw a filled rectangle with the current draw color. * Use setDrawColor to set it. */ void drawFilledRectangle(double x1, double y1, double x2, double y2); /** * Will draw a filled rectangle with the current draw color. * Use setDrawColor to set it. */ void drawFilledRectangle(int x1, int y1, int x2, int y2); /** * Will fill the entire data object with the specified color set in * setDrawColor. */ void fill(); void setDrawColor(ossim_uint8 r = 255, ossim_uint8 g = 255, ossim_uint8 b = 255); void getDrawColor(ossim_uint8& rCurr, ossim_uint8& gCurr, ossim_uint8& bCurr); /** * Will take the point passed in and translate * to a 0,0. * Example: * Let's say that we have origin 45,34 for the * image's upper left corner. then a call to this * method will translate the point passed in * x-45, y-34 */ // inline void translateToOrigin(ossim_int32& x, ossim_int32& y); /** * Will take the point passed in and translate * to a 0,0. * Example: * Let's say that we have origin 45,34 for the * image's upper left corner. then a call to this * method will translate the point passed in * x-45, y-34 */ // inline void translateToOrigin(ossimDpt& pt); const ossimRefPtr getImageData()const; protected: virtual ~ossimRgbImage(); /** * This object operates on the ossimImageData. Note the * ossimImageData is a band separate so the bands follow sequentially: * all the reds followed by all the blues followed by all greens */ ossimRefPtr theImageData; /** * This will hold precomputed offsets to the * start of each row. This will get rid of a multiplication * per access. Since we will be accessing on a per pixel basis * this will be needed. */ ossim_int32* theOffsets; /** * This is a fast access to the start of each band. */ ossim_uint8* theBands[3]; /** * This is here so we don't have to call theWidth and theHeight * of the ossimImageData. */ ossim_int32 theWidth; /** * This is here so we don't have to call theWidth and theHeight * of the ossimImageData. */ ossim_int32 theHeight; /** * Holds the draw thickness. */ ossim_int32 theThickness; /** * The red component of the color used in drawing the shapes */ ossim_uint8 theRed; /** * The green component of the color used in drawing the shapes */ ossim_uint8 theGreen; /** * The blue component of the color used in drawing the shapes */ ossim_uint8 theBlue; }; inline void ossimRgbImage::slowPlotPixel(ossim_int32 x, ossim_int32 y, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { if((x > -1) && (x < theWidth) && (y > -1) && (y < theHeight)) { theBands[0][theOffsets[y]+x] = r; theBands[1][theOffsets[y]+x] = g; theBands[2][theOffsets[y]+x] = b; } } inline void ossimRgbImage::fastPlotPixel(ossim_int32 x, ossim_int32 y, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { theBands[0][theOffsets[y]+x] = r; theBands[1][theOffsets[y]+x] = g; theBands[2][theOffsets[y]+x] = b; } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimRgbToGreyFilter.h000066400000000000000000000042521352751253100243440ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToGreyFilter.h 20197 2011-11-03 13:22:02Z dburken $ #ifndef ossimRgbToGreyFilter_HEADER #define ossimRgbToGreyFilter_HEADER #include class OSSIMDLLEXPORT ossimRgbToGreyFilter : public ossimImageSourceFilter { public: ossimRgbToGreyFilter(ossimObject* owner=NULL); ossimRgbToGreyFilter(ossimImageSource* inputSource, double c1 = 1.0/3.0, double c2 = 1.0/3.0, double c3 = 1.0/3.0); ossimRgbToGreyFilter(ossimObject* owner, ossimImageSource* inputSource, double c1 = 1.0/3.0, double c2 = 1.0/3.0, double c3 = 1.0/3.0); virtual ossimString getShortName()const; virtual ossimString getLongName()const; virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual void initialize(); virtual ossimScalarType getOutputScalarType() const; ossim_uint32 getNumberOfOutputBands() const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimRgbToGreyFilter(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); ossimRefPtr theBlankTile; ossimRefPtr theTile; void runUcharTransformation(ossimRefPtr& tile); double theC1; double theC2; double theC3; TYPE_DATA }; #endif /* #ifndef ossimRgbToGreyFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimRgbToHsiSource.h000066400000000000000000000026341352751253100241760ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToHsiSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimRgbToHsiSource_HEADER #define ossimRgbToHsiSource_HEADER #include class ossimRgbToHsiSource : public ossimImageSourceFilter { public: ossimRgbToHsiSource(); ossimRgbToHsiSource(ossimImageSource* inputSource); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual ossimScalarType getOutputScalarType() const; virtual ossim_uint32 getNumberOfOutputBands()const; virtual double getNullPixelValue()const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void initialize(); protected: virtual ~ossimRgbToHsiSource(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); ossimRefPtr theBlankTile; ossimRefPtr theTile; TYPE_DATA }; #endif /* #ifndef ossimRgbToHsiSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimRgbToHsvSource.h000066400000000000000000000025421352751253100242110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToHsvSource.h 22724 2014-04-10 16:27:46Z gpotts $ #ifndef ossimRgbToHsvSource_HEADER #define ossimRgbToHsvSource_HEADER #include class ossimRgbToHsvSource : public ossimImageSourceFilter { public: ossimRgbToHsvSource(); ossimRgbToHsvSource(ossimImageSource* inputSource); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual ossimScalarType getOutputScalarType() const; virtual ossim_uint32 getNumberOfOutputBands()const; virtual double getNullPixelValue()const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void initialize(); protected: virtual ~ossimRgbToHsvSource(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); ossimRefPtr theBlankTile; ossimRefPtr theTile; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimRgbToIndexFilter.h000066400000000000000000000050521352751253100245040ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToIndexFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimRgbToIndexFilter_HEADER #define ossimRgbToIndexFilter_HEADER #include #include #include #include #include class ossimImageData; /*! * It will map the input data to an 8-bit index table. The table *
 *
 * Example keyword list:
 *
 * type:  ossimRgbToIndexFilter
 *
 * If you want to load from a file then just do:
 *
 * lut.filename: 
 *
 * If you have the lut table in line then it must look like this:
 *
 * lut.entry0:  204 102 1
 * lut.entry1:  255 204 153
 * lut.entry2:  51 204 204
 * lut.number_of_entries:  3
 * lut.type:  ossimRgbLutDataObject
 *
 * 
*/ class ossimRgbToIndexFilter : public ossimImageSourceFilter { public: /*! * Initializes the min value to 0 and the max value to 4000. */ ossimRgbToIndexFilter(); ossimRgbToIndexFilter(ossimImageSource* inputSource, const ossimRgbLutDataObject& rgbLut); virtual ossimRefPtr getTile(const ossimIrect& origin, ossim_uint32 resLevel=0); virtual ossim_uint32 getNumberOfOutputBands() const; virtual ossimScalarType getOutputScalarType() const; void setLut(ossimRgbLutDataObject& lut); void setLut(const ossimFilename& file); virtual void disableSource(); virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual void initialize(); /*! * Saves the state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Loads the state of this object. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimRgbToIndexFilter(); void allocate(); virtual ossimRefPtr convertInputTile(ossimRefPtr& tile); ossimRefPtr theLut; ossimRefPtr theTile; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimRgbToJpegYCbCrSource.h000066400000000000000000000017001352751253100252140ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToJpegYCbCrSource.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimRgbToJpegYCbCrSource_HEADER #define ossimRgbToJpegYCbCrSource_HEADER #include class ossimRgbToJpegYCbCrSource : public ossimImageSourceFilter { public: ossimRgbToJpegYCbCrSource(); ossimRgbToJpegYCbCrSource(ossimImageSource* inputSource); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); protected: virtual ~ossimRgbToJpegYCbCrSource(); ossimRefPtr theBlankTile; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimRpfCacheTileSource.h000066400000000000000000000404541352751253100250100ustar00rootroot00000000000000//----------------------------------------------------------------------- // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This class give the capability to access tiles from the // input frames. // //----------------------------------------------------------------------- //$Id: ossimRpfCacheTileSource.h 1361 2010-08-26 00:24:22Z david.burken $ #ifndef ossimRpfCacheTileSource_HEADER #define ossimRpfCacheTileSource_HEADER 1 #include #include class ossimRpfToc; class ossimRpfTocEntry; class ossimRpfFrame; class OSSIMDLLEXPORT ossimRpfCacheTileSource : public ossimImageHandler { public: /** * Basic enumeration. This should * be either a CIB or a CADRG product * type. */ enum ossimRpfCacheProductType { OSSIM_PRODUCT_TYPE_UNKNOWN = 0, OSSIM_PRODUCT_TYPE_CIB = 1, OSSIM_PRODUCT_TYPE_CADRG = 2 }; /** * Default constructor. * * Initializes all internal attributes to a default state. */ ossimRpfCacheTileSource(); /** * This method is defined in the base class ossimObject. * This class overrides the default implementation * to return its own short name. * * @return The short name for this class as an ossimString. */ virtual ossimString getShortName()const; /** * This method is defined in the base class ossimObject. * This class overrides the default implementation * to return its own long name. * * @return The long name for this class as an ossimString. */ virtual ossimString getLongName()const; /** * Closes this image handler and deletes any allocated data. */ virtual void close(); /** */ virtual bool open(); /** * Returns a pointer to an ossimImageDataObject given a rectangluar * region of interest. * * @param rect The region of interest to return. * @param resLevel From which resolution set are we querying * (default is 0 full res). * * @return The ossimImageData object to the caller. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel = 0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Satisfies pure virtual requirement from ImageHandler class. * * @param reduced_res_level The reduced res level to query number of lines from. * @return The number of lines in the image. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; /** * Satisfies pure virtual requirement from ImageHandler class. * * @param reduced_res_level The reduced res level to query number of samples from. * @return The number of samples in the image. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; /** * @param reduced_res_level Which res level to get the bounds for. 0 represents * the default and is the full resolution. * * @return A rectangle representing the bounds for the passed in resolution level. */ virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const; /** * @param kwl Keywordlist to save the state of the object to. * @param prefix prefix to prepend to the keywords. This will * help uniquely identify each keyword if multiple * objects are saved to the same list. * @return True if successfully saved the state of the object and * false otherwise. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to load the state of an object from a keyword list. * * Loading with a prefix. * @code * cibCadrgHandler->laodState(kwl, "handler1."); * @endcode * * Loading without a prefix. * @code * cibCadrgHandler->laodState(kwl); * @endcode * * Since all objects are factory created you can go through the * registry and pass the keyword list in. * @code * ossimImageHandler* handler = ossimImageHandlerRegistry::instance()->open(kwl, prefix); * @endcode * * @param kwl Keywordlist that holds the state information for this * object. * * * @param prefix prefix value prepended to all keywords to uniquely * locate the state attributes for this object. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Populates the geometry object with image geometry information. This * method is used to relay projection/model information to users. * Returns true if geometry info is present, false if not. * Keywords supported by this class are: * @verbatim * datum: // datum code> // Datum code * ul_lat: // upper left latitude * ul_lon: // upper left longitude * ll_lat: // lower left latitude * ll_lon: // lower left longitude * lr_lat: // lower right latitude * lr_lon: // lower right longitude * ur_lat: // upper right latitude * ur_lon: // upper right longitude * number_input_bands: * number_output_bands: * number_lines: * number_samples: * decimal_degrees_per_pixel_lat: // specifies the spacing per pixel along Y direction * decimal_degrees_per_pixel_lon: // specifies the spacing per pixel along X direction * origin_latitude: // specifies the origin or center of the projector for the latitude * central_meridian: // specifies the origin or center of the projector for the longitude * tie_point_lat: // tie point lat. Represents the latitude of the upper left center of pixel * tie_point_lon: // tie point lon. Represents the longitude of the upper left center of pixel * zone: // zone read from the CIB/CADRG boundary info * type: // class name of the object for factory driven reconstruction * map_scale: // Map scale of the image * @endverbatim * @see ossimImageSource for further code example on using the geometry. */ virtual ossimRefPtr getImageGeometry(); /** * This method allows you to query the scalar type of the output data. * This is simply the data type, i.e. whether its OSSIM_FLOAT, OSSIM_DOUBLE, * OSSIM_UCHAR, ... etc. This means that if there are bands of different * scalar types from a single image then they must be casted to the highest * precision type. @see ossimConstants.h for all ossimScalarType. * * @return The output scalar type. * */ virtual ossimScalarType getOutputScalarType() const; /** * This method allows you to query the number of input bands. If an image * is band selectable this will allow one to select the bands you wish * to read in. This indicates that the number of input bands might not * match the number of output bands. * @return number of input bands. */ virtual ossim_uint32 getNumberOfInputBands()const; /** * This method allows one to query the number of output bands. This might not * be the same as the n umber of input bands. * * @see getNumberOfInputBands(). * @return number of output bands. */ virtual ossim_uint32 getNumberOfOutputBands()const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; virtual bool setCurrentEntry(ossim_uint32 entryIdx); virtual void getEntryList(std::vector& entryList)const; /** * @param reduced_res_level passed in resolution level. * @return True if the reduced_res_level is within an acceptable range * and false otherwise. */ bool isValidRLevel(ossim_uint32 reduced_res_level) const; /** * Determines if its open if there eists a table of contents object. * * @return True if the handler is open and flase otherwise. */ bool isOpen()const; /** @return true if CIB */ bool isCib() const; /** @return true if CADRG */ bool isCadrg() const; /** * @brief Gets a property for matching name. * @param name The name of the property to get. * @return Returns property matching "name". */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * CONSTANT representing the width of a Frame. This should be 1536. */ static const ossim_uint32 CIBCADRG_FRAME_WIDTH; /** * CONSTANT representing the height of a Frame. This should be 1536. */ static const ossim_uint32 CIBCADRG_FRAME_HEIGHT; protected: /** * Destructor. * * Will return allocated memory back to the heap. */ virtual ~ossimRpfCacheTileSource(); /** * Will shift the rect and clamp it so not to go outside the -180 to 180 * degree range. */ void setActualImageRect(); /** * @brief Method to test for 180.0 <--> 180.00 and set leftLon to -180 if * both left and right are 180.0 degrees. * * @param leftLon Left hand side longitude of scene. This is the value * that will be flipped to -180 if test is true. * * @param rightLon Right hand side of scene. */ void checkLongitude(ossim_float64& leftLon, const ossim_float64& rightLon) const; /** * Protected structure that is only used internally by this class. * * This is used to establish which entry data is being used. * all we need is the ro, col of the entry. We can compute the * image rect from this since the CibCadrg are 1536x1536 frame. * */ struct ossimFrameEntryData { ossimFrameEntryData() :theRow(-1), theCol(-1), thePixelRow(-1), thePixelCol(-1) {} ossimFrameEntryData(ossim_int32 row, ossim_int32 col, ossim_int32 pixelRow, ossim_int32 pixelCol, const ossimRpfFrameEntry& entry) :theRow(row), theCol(col), thePixelRow(pixelRow), thePixelCol(pixelCol), theFrameEntry(entry) {} ossimFrameEntryData(const ossimFrameEntryData& rhs) :theRow(rhs.theRow), theCol(rhs.theCol), thePixelRow(rhs.thePixelRow), thePixelCol(rhs.thePixelCol), theFrameEntry(rhs.theFrameEntry) {} ossim_int32 theRow; ossim_int32 theCol; ossim_int32 thePixelRow; ossim_int32 thePixelCol; ossimRpfFrameEntry theFrameEntry; }; /** * Sets the entry to render. * */ virtual bool setEntryToRender(ossim_uint32 index); /** * It is important to note that each frame is organized into an easting northing * type orientation. This means that a frame at 0,0 is at the lower left corner. * Each frame's pixel data is has 0,0 at the upper left. * * It will take the curent region to render and then find all entries that intersect * that region. * * @param rect the current region to render. * @return The list of entry data objects found for this rect. */ std::vector getIntersectingEntries(const ossimIrect& rect); /** * This is a wrapper for the fill cib and fill cadrg. It takes the frames * involved that were found in the getIntersectingEntries and call the * appropriate fill cib or fill cadrg on each frame entry data. It will * loop through making sure that the frame file exists before calling * the associated fill routines. * * @param tileRect Region to fill. * @param framesInvolved All intersecting frames used to render the region. */ void fillTile(const ossimIrect& tileRect, const std::vector& framesInvolved, ossimImageData* tile); /** * Will uncompress the CIB file using a VQ decompression algorithm. * * @param aFrame Frame that overlaps the requested tile rect. * @param tileRect The region requested to render. * @param frameEntryData The frame entry data. */ void fillSubTileCib(const ossimRpfFrame& aFrame, const ossimIrect& tileRect, const ossimFrameEntryData& frameEntryData, ossimImageData* tile); /** * Will uncompress the CADRG file using a VQ decompression algorithm. * * @param aFrame Frame that overlaps the requested tile rect. * @param tileRect The region requested to render. * @param frameEntryData The frame entry data. */ void fillSubTileCadrg(const ossimRpfFrame& aFrame, const ossimIrect& tileRect, const ossimFrameEntryData& frameEntryData, ossimImageData* tile); /** * Will allocate an internal buffer for the given product. If the product is * a CIB then it is a single band OSSIM_UCHAR buffer and if its a CADRG it * is a 3 band OSSIM_UCHAR buffer. */ void allocateForProduct(); void deleteAll(); void populateLut(); bool buildFrameEntryArray(ossimFilename imageFile); virtual void establishDecimationFactors(); /** * This holds the image bounds for the current entry. */ ossimIrect m_actualImageRect; /** * This is for storage of a single compressed buffer. */ unsigned char* m_compressedBuffer; /** * This is used as a buffer to uncompress the data to */ unsigned char* m_uncompressedBuffer; /** * This will be computed based on the frames organized within * the directory. The CibCadrg have fixed size frames of 1536x1536 * and we must count how many there are. */ ossim_uint32 m_numberOfLines; /** * This will be computed based on the frames organized within * the directory. The CibCadrg have fixed size frames of 1536x1536 * and we must count how many there are. */ ossim_uint32 m_numberOfSamples; /** * This is the actual data returned from a getTile request. */ ossimRefPtr m_tile; /** * The size of the input frames. */ std::vector m_fileNames; /** * The size of the output tile. */ ossimIpt m_tileSize; /** * Holds the enumeration specifying the product type. * The product type can be a CIB or a CADRG product. */ ossimRpfCacheProductType m_productType; mutable ossimRpfFrame* m_workFrame; // data to use in property retrieval ossim_float64 m_bBox_LL_Lon; ossim_float64 m_bBox_LL_Lat; ossim_float64 m_bBox_UR_Lon; ossim_float64 m_bBox_UR_Lat; ossim_uint32 m_numOfFramesVertical; ossim_uint32 m_numOfFramesHorizontal; std::vector< std::vector > m_frameEntryArray; TYPE_DATA }; #endif /* #ifndef ossimRpfCacheTileSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimS16ImageData.h000066400000000000000000000130201352751253100234310ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2001 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration of ossimS16ImageData. Specialized image data object for // signed short data. // //************************************************************************* // $Id: ossimS16ImageData.h 16052 2009-12-08 22:20:40Z dburken $ #ifndef ossimS16ImageData_HEADER #define ossimS16ImageData_HEADER #include #include class OSSIMDLLEXPORT ossimS16ImageData : public ossimImageData { public: ossimS16ImageData(ossimSource* source, ossim_uint32 bands = 1); ossimS16ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height); ossimS16ImageData(const ossimS16ImageData &rhs); /*! * Perform object duplication. */ virtual ossimObject* dup()const; /*! * will fill the entire band with * the value. */ void fill(ossim_uint32 band, double value); bool isNull(ossim_uint32 offset)const; void setNull(ossim_uint32 offset); virtual ossimDataObjectStatus validate() const; /*! * will go to the band and offset and compute the * normalized float and return it back to the * caller through the result argument. */ virtual void getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float& result)const; /*! * This will assign to this object a normalized * value by unnormalizing to its native type. */ virtual void setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float input); /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedFloat(ossimImageData* result)const; /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedDouble(ossimImageData* result)const; /*! * Will take the normalized input and convert it * to this tile's data type. Example: if this * tile is of type UCHAR and its input is of type * NORALIZED_FLOAT it will unnormalize the data by * doing: * * minPix + normalizedInput*(maxPix-minPix) * * on a per band basis. */ virtual void unnormalizeInput(ossimImageData* normalizedInput); /*! * This will compute the average value for the band. */ virtual double computeAverageBandValue(ossim_uint32 bandNumber = 0); /*! * This will call the compute average band value and then * use that in the calculation of: * It will then do a SUM[(Mean - Actual)^2]/width*height. * * This is the average variance from the passed in * mean. Basically think of the mean as a completely * grey image and we would like to see how this * image varies from the passed in mean. */ virtual double computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber = 0); virtual void setValue(ossim_int32 x, ossim_int32 y, double color); /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(double* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(double* buf); /*! * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. */ virtual void copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const; virtual void copyTileToNormalizedBuffer(ossim_uint32 band, float* buf)const; /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(float* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(float* buf); /*! * Will copy the normalized buffer to this tiles * specified band. If band is out of range then nothing * is done and returns. */ virtual void copyNormalizedBufferToTile(ossim_uint32 band, double* buf); virtual void copyNormalizedBufferToTile(ossim_uint32 band, float* buf); /** @return The first non-null index of the normalized remap table. */ virtual ossim_float64 getMinNormalizedPix() const; protected: virtual ~ossimS16ImageData(); ossimS16ImageData(); private: static const ossimNormalizedS16RemapTable m_remapTable; TYPE_DATA }; inline ossim_float64 ossimS16ImageData::getMinNormalizedPix() const { return m_remapTable[1]; } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimSFIMFusion.h000066400000000000000000000055371352751253100232630ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // LICENSE: See top level LICENSE.txt // // Author: Garrett Potts // //******************************************************************* // $Id: ossimSFIMFusion.h 19827 2011-07-15 19:47:30Z gpotts $ #ifndef ossimSFIMFusion_HEADER #define ossimSFIMFusion_HEADER #include #include #include #include /** * This class imlements the fusion algorithm from the paper: * * "Smoothing Filter-based Intesity Modulation: a spectral preserve * image fusion technique for improving spatial details" * * Pulished in INT. J. Remote Sensing, 2000, Vol. 21 NO. 18, 3461-3472 * * By J. G. LIU * * * Auther: Garrett Potts * LICENSE: MIT */ class OSSIM_DLL ossimSFIMFusion : public ossimFusionCombiner, public ossimAdjustableParameterInterface { public: ossimSFIMFusion(); virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual void initialize(); virtual ossimObject* getBaseObject() { return this; } virtual const ossimObject* getBaseObject()const { return this; } virtual void initAdjustableParameters(); virtual void adjustableParametersChanged(); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimSFIMFusion(); void setFilters(); bool computeRegression(ossim_float64& slopeResult, const ossimIpt& origin, ossimRefPtr panData, ossimRefPtr colorData, ossim_uint32 colorBandIdx); ossim_float64 theLowPassKernelWidth; ossim_uint32 theHighPassKernelWidth; // These are low and high pass filters for the single pan band // ossimRefPtr theLowPassFilter; ossimRefPtr theHighPassFilter; ossimRefPtr theNormLowPassTile; ossimRefPtr theNormHighPassTile; ossimRefPtr theNormColorData; NEWMAT::Matrix theHighPassMatrix; bool theAutoAdjustScales; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimSICDToDetectedImage.h000066400000000000000000000047371352751253100247740ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2010 Radiant Blue Tecnologies Inc. // // License: See LICENSE.txt file in the top level directory. // // Author: William Watkins // //************************************************************************* #ifndef ossimSICDToDetectedImage_HEADER #define ossimSICDToDetectedImage_HEADER #include class OSSIM_DLL ossimSICDToDetectedImage : public ossimImageSourceFilter { public: /** * Currently works with SICD data but will generally work for conforming Complex formats */ ossimSICDToDetectedImage(); /** * Applies the sqrt(I^2 + Q^2) to generate the Detected SAR image. For 8 bit data the input is assumed to be Magnitude and Phase (Not complex format) and so it simply returns the magnitude which is the Detected SAR image. */ virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); /** * Calls base ossimImageSourceFilter::initialize() to reset connection if * needed then nulls out tiles. * * @note This does not initialize tiles intentionally to avoid repeated * deletes and news. Tiles will be initialized by allocate() method on * the first getTile call after an initialize. */ virtual void initialize(); // virtual ossim_uint32 getNumberOfOutputBands() const // { // return 1; // } /*---------------------- PROPERTY INTERFACE ---------------------------*/ virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /*--------------------- PROPERTY INTERFACE END ------------------------*/ protected: virtual ~ossimSICDToDetectedImage(); /** * Called to initialize tiles by first get tile when theTile or theNormTile * are not initialized. */ void allocate(); /** * Applies the brightness contrast to tile. This method simply applies * brightness contrast to all bands. Called if input does not have * three bands. */ template void processComplexTile(T dummy, ossimImageData* tile); template void processAmplitudeAngleTile(T dummy, ossimImageData* tile); ossimRefPtr theTile; TYPE_DATA }; #endif /* End of "#ifndef ossimSICDToDetectedImage_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimScalarRemapper.h000066400000000000000000000067231352751253100242400ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2001 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class declartion for ossimScalarRemapper. // This class is used to remap image data from one scalar type to another. // //******************************************************************* // $Id: ossimScalarRemapper.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimScalarRemapper_HEADER #define ossimScalarRemapper_HEADER #include class OSSIMDLLEXPORT ossimScalarRemapper : public ossimImageSourceFilter { public: ossimScalarRemapper(); ossimScalarRemapper(ossimImageSource* inputSource, ossimScalarType outputScalarType); virtual ~ossimScalarRemapper(); virtual void initialize(); virtual ossimString getLongName() const; virtual ossimString getShortName() const; virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); /** * Returns the output pixel type of the tile source. This override the * base class since it simply returns it's input scalar type which is * not correct with this object. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the output pixel type of the tile source as a string. */ virtual ossimString getOutputScalarTypeString() const; /** * Sets the output scalar type. */ virtual void setOutputScalarType(ossimScalarType scalarType); virtual void setOutputScalarType(ossimString scalarType); virtual void setPreserveMagnitude(bool value); /** * Sets the current resolution level. Returns true on success, false * on error. */ virtual double getNullPixelValue(ossim_uint32 band) const; virtual double getMinPixelValue(ossim_uint32 band=0) const; virtual double getMaxPixelValue(ossim_uint32 band=0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); /** * Override base class so that a disableSource event does not * reinitialize the object and enable itself. */ virtual void propertyEvent(ossimPropertyEvent& event); virtual void refreshEvent(ossimRefreshEvent& event); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; protected: /** * Called on first getTile, will initialize all data needed. */ void allocate(); /** * Deletes allocated memory. Used by both allocate and destructor. */ void destroy(); double* theNormBuf; ossimRefPtr theTile; ossimScalarType theOutputScalarType; bool theByPassFlag; bool thePreserveMagnitudeFlag; TYPE_DATA }; #endif /* #ifndef ossimScalarRemapper_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimScaleFilter.h000066400000000000000000000143061352751253100235300ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimScaleFilter.h 22874 2014-08-26 10:21:34Z dburken $ #ifndef ossimScaleFilter_HEADER #define ossimScaleFilter_HEADER #include #include #include #include #include /*! */ class OSSIM_DLL ossimScaleFilter : public ossimImageSourceFilter { public: enum ossimScaleFilterType { ossimScaleFilter_NEAREST_NEIGHBOR = 0, ossimScaleFilter_BOX = 1, ossimScaleFilter_GAUSSIAN = 2, ossimScaleFilter_CUBIC = 3, ossimScaleFilter_HANNING = 4, ossimScaleFilter_HAMMING = 5, ossimScaleFilter_LANCZOS = 6, ossimScaleFilter_MITCHELL = 7, ossimScaleFilter_CATROM = 8, ossimScaleFilter_BLACKMAN = 9, ossimScaleFilter_BLACKMAN_SINC = 10, ossimScaleFilter_BLACKMAN_BESSEL = 11, ossimScaleFilter_QUADRATIC = 12, ossimScaleFilter_TRIANGLE = 13, ossimScaleFilter_HERMITE = 14 }; ossimScaleFilter(); ossimScaleFilter(ossimImageSource* inputSource, const ossimDpt& scaleFactor); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; virtual ossimRefPtr getImageGeometry(); virtual void initialize(); virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result)const { result.makeNan(); if(resLevel == 0) { result.x = 1.0; result.y = 1.0; } } virtual void getDecimationFactors(std::vector& decimations)const { decimations.push_back(ossimDpt(1.0, 1.0)); } virtual ossim_uint32 getNumberOfDecimationLevels()const { // only full res output since we are scaling // return 1; } void setFilterType(ossimScaleFilterType filterType); void setFilterType(ossimScaleFilterType minifyFilterType, ossimScaleFilterType magnifyFilterType); void setFilterType(const ossimString& minifyType, const ossimString& magnifyType) { setFilterType(getFilterType(minifyType), getFilterType(magnifyType)); } void setMinifyFilterType(const ossimString& minifyType) { setMinifyFilterType(getFilterType(minifyType)); } void setMagnifyFilterType(const ossimString& magnifyType) { setMagnifyFilterType(getFilterType(magnifyType)); } void setMinifyFilterType(ossimScaleFilterType filterType) { setFilterType(filterType, m_MagnifyFilterType); } void setMagnifyFilterType(ossimScaleFilterType filterType) { setFilterType(m_MinifyFilterType,filterType); } ossimString getMinifyFilterTypeAsString()const { return getFilterTypeAsString(m_MinifyFilterType); } ossimString getMagnifyFilterTypeAsString()const { return getFilterTypeAsString(m_MagnifyFilterType); } void setScaleFactor(const ossimDpt& scale); void setBlurFactor(ossim_float64 blur) { m_BlurFactor = blur; } ossim_float64 getBlurFactor()const { return m_BlurFactor; } const ossimDpt& getScaleFactor()const { return m_ScaleFactor; } /*! * Saves the state of this object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Loads the state of this object. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimScaleFilter(); void allocate(); //! If this object is maintaining an ossimImageGeometry, this method needs to be called after //! a scale change so that the geometry's projection is modified accordingly. void updateGeometry(); ossimRefPtr m_BlankTile; ossimRefPtr m_Tile; ossimFilter* m_MinifyFilter; ossimFilter* m_MagnifyFilter; ossimScaleFilterType m_MinifyFilterType; ossimScaleFilterType m_MagnifyFilterType; ossimDpt m_ScaleFactor; ossimDpt m_InverseScaleFactor; ossimIpt m_TileSize; ossimIrect m_InputRect; ossim_float64 m_BlurFactor; ossimRefPtr m_ScaledGeometry; //!< The input image geometry, altered by the scale template void runFilterTemplate(T dummy, const ossimIrect& imageRect, const ossimIrect& viewRect); template void runHorizontalFilterTemplate(T dummy, const ossimRefPtr& input, ossimRefPtr& output); template void runVerticalFilterTemplate(T dummy, const ossimRefPtr& input, ossimRefPtr& output); void runFilter(const ossimIrect& imageRect, const ossimIrect& viewRect); void getSupport(double& x, double& y); const ossimFilter* getHorizontalFilter()const; const ossimFilter* getVerticalFilter()const; ossimString getFilterTypeAsString(ossimScaleFilterType type)const; ossimScaleFilterType getFilterType(const ossimString& type)const; ossimIrect scaleRect(const ossimIrect input, const ossimDpt& scaleFactor)const; ossimFilter* createNewFilter(ossimScaleFilterType filterType, ossimScaleFilterType& result); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimShiftFilter.h000066400000000000000000000055371352751253100235640ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Filter for shifting input to an output range. See class description // below for more. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimShiftFilter_HEADER #define ossimShiftFilter_HEADER 1 #include #include #include /** * @class ossimShiftFilter * * Class to shift/stretch input values to given min/max. Callers must set * the min, max, null output values. Input data shifted stretch base on: * * pix = outMin + (inPix - inMin) * (outMax-outMin)/(inMax-inMin) * * See ossim-shift-filter-test.cpp for concrete example of usage. */ class OSSIMDLLEXPORT ossimShiftFilter : public ossimImageSourceFilter { public: /** default constructor */ ossimShiftFilter(); virtual void initialize(); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); /** @return "ossimShiftFilter" */ virtual ossimString getClassName() const; /** @return "OSSIM shift filter" */ virtual ossimString getLongName() const; /** @return "shift filter" */ virtual ossimString getShortName() const; /** @return The null pixel of the band. */ virtual double getNullPixelValue(ossim_uint32 band)const; /** @return The min pixel of the band. */ virtual double getMinPixelValue(ossim_uint32 band)const; /** @return The max pixel of the band. */ virtual double getMaxPixelValue(ossim_uint32 band)const; /** @brief Set the null output pixel. */ void setNullPixelValue(double null); /** @brief Set the min output pixel. */ void setMinPixelValue(double min); /** @brief Set the max output pixel. */ void setMaxPixelValue(double max); protected: /** virtual protected destructor */ virtual ~ossimShiftFilter(); private: /** @brief Private to disallow use... */ ossimShiftFilter(const ossimShiftFilter&); /** @brief Private to disallow use... */ ossimShiftFilter& operator=(const ossimShiftFilter&); /** @brief Allocates the tile. Called on first getTile. */ void allocate(); /** * @brief Template to fill the tile. * @param dummy template type. * @param inputTile * @param outputTile */ template void fillTile(T dummy, const ossimImageData* inputTile, ossimImageData* outputTile) const; ossimRefPtr m_tile; double m_min; double m_max; double m_null; TYPE_DATA }; #endif /* #ifndef ossimShiftFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimSingleImageChain.h000066400000000000000000000444541352751253100244710ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Utility class declaration for a single image chain. // //--- // $Id$ #ifndef ossimSingleImageChain_HEADER #define ossimSingleImageChain_HEADER 1 #include /* OSSIM_DLL */ #include #include #include #include #include #include #include #include #include #include #include #include #include // Forward class declarations: class ossimFilename; class ossimGeoPolygon; class ossimSrcRecord; /** * @class ossimSingleImageChain * * @brief Single image chain class. * * Convenience class for a single image chain. * * For code example see: ossim/src/test/ossim-single-image-chain-test.cpp * * Just a clarification on "start of chain" versus "end of chain" in this * file. * * Given chain of: * 1) image handler * 2) band selector (optional) * 3) histogram remapper(optional) * 4) scalar remapper (optional) * 5) resampler cache * 6) resampler * 7) band selector (optional when going one band to three) * 8) chain cache * * The "image handle" is the "start of chain". * The "chain cache" is the "end of chain". */ class OSSIM_DLL ossimSingleImageChain : public ossimImageChain { public: /** default constructor */ ossimSingleImageChain(); /** Constructor that takes flags.*/ ossimSingleImageChain(bool addNullPixelFlipFlag, bool addHistogramFlag, bool addResamplerCacheFlag, bool addChainCacheFlag, bool remapToEightBitFlag, bool threeBandFlag, bool threeBandReverseFlag, bool brightnessContrastFlag=false, bool sharpenFlag=false, bool geoPolyCutterFlag=false); /** virtual destructor */ virtual ~ossimSingleImageChain(); /** * @brief reset method * This deletes all links in the chain, zero's out all data members, and * sets all flags back to default. */ void reset(); /** * @brief open method that takes an image file. * * Opens file and creates a simple chain with ossimImageHandler. * * @param file File to open. * @param openOverview If true image handler will attempt to open overview. * Note that if you are planning on doing a rendered chain or want to go * between res levels you should set this to true. default = true * * @return true on success, false on error. * * @note This will close previous chain if one was opened. */ bool open(const ossimFilename& file, bool openOverview=true); /** * @brief open method that takes an ossimSrcRecord. * * Opens file and creates a simple chain with ossimImageHandler. * * @return true on success, false on error. * * @note This will close previous chain if one was opened. */ bool open(const ossimSrcRecord& src); /** @return true if image handler is opened. */ bool isOpen() const; /** @brief close method to delete the image handler. */ void close(); /** @return The filename of the image. */ ossimFilename getFilename() const; /** * @brief Create a rendered image chain. * * Typical usage is to call this after "open" method returns true like: * if ( myChain->open(myFile) == true ) * { * myChain->createRenderedChain(); * code-goes-here(); * } * * Typical chain is: * * 1) image handler * 2) band selector (optional) * 3) histogram remapper(optional) * 4) scalar remapper (optional) * 5) resampler cache * 6) resampler * 7) band selector (optional when going one band to three) * 8) chain cache * * NOTES: * 1) Cache on left hand side of resampler is critical to speed if you * have the ossimImageRender enabled. * * 2) If doing a sequential write where tiles to the right of the * resampler will not be revisited the chain cache could be * disabled to save memory. */ void createRenderedChain(); /** * @brief Create a rendered image chain that takes an ossimSrcRecord. */ void createRenderedChain(const ossimSrcRecord& src); /** * @brief Adds an image handler for file. * * @param file File to open. * * @param openOverview If true image handler will attempt to open overview. * Note that if you are planning on doing a rendered chain or want to go * between res levels you should set this to true. default = true * * @return true on success, false on error. */ bool addImageHandler(const ossimFilename& file, bool openOverview=true); /** * @brief Adds an image handler from src record. * * This take an ossimSrcRecord which can contain a supplemental directory * to look for overviews. * * @param rec Record to open. * @return true on success, false on error. */ bool addImageHandler(const ossimSrcRecord& src); /** @brief Adds a band selector to the end of the chain. */ void addBandSelector(); /** * @brief Adds a band selector. * * This takes an ossimSrcRecord which can contain a band selection list. * * @param src Record to initialize band selector from. * */ void addBandSelector(const ossimSrcRecord& src); /** @brief Adds histogram remapper to the chain. */ void addHistogramRemapper(); /** * @brief Adds a band selector. * * This takes an ossimSrcRecord which can contain a histogram * operation to be performed. * * @param src Record to initialize band selector from. */ void addHistogramRemapper(const ossimSrcRecord& src); /** @brief Adds histogram remapper to the chain. */ void addGammaRemapper(); /** * @brief Adds a band selector. * * This takes an ossimSrcRecord which can contain a histogram * operation to be performed. * * @param src Record to initialize band selector from. */ void addGammaRemapper(const ossimSrcRecord& src); /** * @brief Adds a new cache to the current end of the chain. * @return Pointer to cache. */ ossimRefPtr addCache(); /** @brief Adds a resampler (a.k.a. "renderer") to the end of the chain. */ void addResampler(); /** * @brief Adds a resampler (a.k.a. "renderer") to the end of the chain. * This method in turn calls "addResampler()". */ void addRenderer(); /** * @brief Adds scalar remapper either to the left of the resampler cache * or at the end of the chain if not present. */ void addScalarRemapper(); /** * @brief Adds brightness contrast filter the end of the chain if not * present. */ void addBrightnessContrast(); /** * @brief Adds sharpen filter the end of the chain if not present. */ void addSharpen(); /** * Adds the null pixel flip just after the band selection */ void addNullPixelFlip(); void addNullPixelFlip(const ossimSrcRecord& src); /** * * @brief Adds a geo polycutter to allow for cropping imagery or nulling out * regions. This has no affect on modification of the bounds * */ void addGeoPolyCutter(); void addGeoPolyCutterPolygon(const std::vector& polygon); void addGeoPolyCutterPolygon(const ossimGeoPolygon& polygon); /** * @return ossimRefPtr containing the image handler. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getImageHandler() const; /** * @return ossimRefPtr containing the image handler. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getImageHandler(); /** * @return ossimRefPtr containing the band selector. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getBandSelector() const; /** * @return the null pixel flip */ ossimRefPtr getNullPixelFlip() const; /** * @return ossimRefPtr containing the band selector. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getBandSelector(); /** * @return ossimRefPtr containing the histogram remapper. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getHistogramRemapper() const; /** * @return ossimRefPtr containing the histogram remapper. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getHistogramRemapper(); /** * @return ossimRefPtr containing the histogram remapper. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getGammaRemapper() const; /** * @return ossimRefPtr containing the histogram remapper. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getGammaRemapper(); /** * @return ossimRefPtr containing the resampler cache. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getResamplerCache() const; /** * @return ossimRefPtr containing the resampler cache. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getResamplerCache(); /** * @return ossimRefPtr containing the resampler (a.k.a. "renderer"). * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getImageRenderer() const; /** * @return ossimRefPtr containing the resampler (a.k.a. "renderer"). * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getImageRenderer(); /** * @return ossimRefPtr containing the scalar remapper. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getScalarRemapper() const; /** * @return ossimRefPtr containing the scalar remapper. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getScalarRemapper(); /** * @return ossimRefPtr containing the brightness contrast filter. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getBrightnessContrast() const; /** * @return ossimRefPtr containing the brightness contrast filter. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getBrightnessContrast(); /** * @return ossimRefPtr containing the sharpen filter. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getSharpenFilter() const; /** * @return ossimRefPtr containing the sharpen. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getSharpenFilter(); /** * @return ossimRefPtr containing the chain cache. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getChainCache() const; /** * @return ossimRefPtr containing the chain cache. * @note Can contain a null pointer so callers should validate. */ ossimRefPtr getChainCache(); /** * @brief If flag is true a null pixel flip will be added to the chain at create time. * @param flag */ void setAddNullPixelFlipFlag(bool flag); /** * @brief Gets the add histogram flag. * @return true or false. */ bool getNullPixelFlipFlag() const; /** * @brief If flag is true a histogram will be added to the chain at create time. * @param flag */ void setAddHistogramFlag(bool flag); /** * @brief Gets the add histogram flag. * @return true or false. */ bool getAddHistogramFlag() const; /** * @brief If flag is true a gamma remapper will be added to the chain at create time. * @param flag */ void setAddGammaFlag(bool flag); /** * @brief Gets the add gamma flag. * @return true or false. */ bool getAddGammaFlag() const; /** * @brief If flag is true a resampler cache will be added to the chain at create time. * This is a cache to the left of the resampler. * @param flag */ void setAddResamplerCacheFlag(bool flag); /** * @brief Gets the add resampler cache flag. * @return true or false. */ bool getAddResamplerCacheFlag() const; /** * @brief If flag is true a chain cache will be added to the chain at create time. * This is a cache at the end of the chain. * @param flag */ void setAddChainCacheFlag(bool flag); /** * @brief Gets the add chain cache flag. * @return true or false. */ bool getAddChainCacheFlag() const; /** * @brief Sets remap to eigth bit flag. * @param flag */ void setRemapToEightBitFlag(bool flag); /** * @brief Get the remap to eight bit flag. * @return true or false. */ bool getRemapToEightBitFlag() const; /** * @brief Sets the three band flag. * * If set will for a three band output. So if one band it will duplicate * so that rgb = b1,b1,b1. An attempt is made to derive rgb bands from the * image handler. * * @param flag */ void setThreeBandFlag(bool flag); /** * @brief Get the three band flag. * @return true or false. */ bool getThreeBandFlag() const; /** * @brief Sets the three band reverse flag. * * @param flag */ void setThreeBandReverseFlag(bool flag); /** * @brief Get the three band reverse flag. * @return true or false. */ bool getThreeBandReverseFlag() const; /** * @brief Sets the brightness contrast flag. * * @param flag */ void setBrightnessContrastFlag(bool flag); /** * @brief Get the brightness contrast flag. * @return true or false. */ bool getBrightnessContrastFlag() const; /** * @brief Sets the sharpenflag. * * @param flag */ void setSharpenFlag(bool flag); /** * @brief Get the sharpen flag. * @return true or false. */ bool getSharpenFlag() const; /** * @brief Utility method to force 3 band output. * * Set band selector to a three band (rgb) output. If image has less than * three bands it will set to rgb = b1,b1,b1. If image has three or * more bands the band selector will be see to rgb = b1, b2, b3. * * @note This will not work unless the image handler is initialized. */ void setToThreeBands(); /** * @brief Utility method to set to 3 bandsand reverse them. This is * mainly used by NITF and Lndsat color data where the bands are in bgr * format and you want it in rgb combination. If image has less than * three bands it will set to rgb = b1,b1,b1. If image has three or * more bands the band selector will be see to rgb = b3, b2, b1. * * @note This will not work unless the image handler is initialized. */ void setToThreeBandsReverse(); /** * @brief method to set band selector. * * This will set the band selection to bandList. If a band selector is * not in the chain yet it will be added. * * @param bandList The list of bands. */ void setBandSelection(const std::vector& bandList); void setDefaultBandSelection(); /** * @brief Convenience method to return the scalar type of the image handler. * * @return Scalar type of the image handler. * * This can return OSSIM_SCALAR_UNKNOWN if the image handler has not been * set yet. Also, this is NOT the same as calling getOutputScalarType * which could have a different scalar type than the image if the * m_remapToEightBitFlag has been set. */ ossimScalarType getImageHandlerScalarType() const; /** * @brief Convenience method to open the histogram and apply a default * stretch. * * This will only work if the image is open, there is a histogram remapper * in the chain, and there was a histogram created. * * Valid stretches (from ossimHistogramRemapper.h): * @verbatim ossimHistogramRemapper::LINEAR_ONE_PIECE ossimHistogramRemapper::LINEAR_1STD_FROM_MEAN ossimHistogramRemapper::LINEAR_2STD_FROM_MEAN ossimHistogramRemapper::LINEAR_3STD_FROM_MEAN ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX @endverbatim * * @return true on success, false on error. */ bool openHistogram( ossimHistogramRemapper::StretchMode mode ); private: /** Pointers to links in chain. */ ossimRefPtr m_handler; ossimRefPtr m_bandSelector; ossimRefPtr m_nullPixelFlip; ossimRefPtr m_histogramRemapper; ossimRefPtr m_gammaRemapper; ossimRefPtr m_brightnessContrast; ossimRefPtr m_sharpen; ossimRefPtr m_scalarRemapper; ossimRefPtr m_resamplerCache; ossimRefPtr m_resampler; ossimRefPtr m_geoPolyCutter; ossimRefPtr m_chainCache; /** control flags */ bool m_addNullPixelFlipFlag; bool m_addHistogramFlag; bool m_addGammaFlag; bool m_addResamplerCacheFlag; bool m_addChainCacheFlag; bool m_remapToEightBitFlag; bool m_threeBandFlag; bool m_threeBandReverseFlag; bool m_brightnessContrastFlag; bool m_sharpenFlag; bool m_geoPolyCutterFlag; }; #endif /* #ifndef ossimSingleImageChain_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimSlopeFilter.h000066400000000000000000000062761352751253100235720ustar00rootroot00000000000000//******************************************************************* // OSSIM // // License: See top level LICENSE.txt file. // //******************************************************************* // $Id: ossimSlopeFilter.h 23451 2015-07-27 15:42:17Z okramer $ #ifndef ossimSlopeFilter_HEADER #define ossimSlopeFilter_HEADER #include #include /** * Filter class for computing the slope image of the input image connection. The slope * dP/dR is defined as the maximum change in pixel value for a differential change in ground * position. This filter would typically be applied to elevation data (represented as an image), * where dP is the change in height when walking some distance dR either straight uphill or * downhill. Numerically , this quantity is computed from the dot product of the normal vector with * the local vertical. * * The output is a floating point single-band image. The input should be a single-band, floating * point image. The slope quantity can be represented as an angle from local vertical, i.e., the * arccos(dP/dR) (in radians, degrees, or normalized) or as the simple ratio dP/dR. */ class OSSIMDLLEXPORT ossimSlopeFilter : public ossimImageSourceFilter { public: /** Specifies how the slope quantity is represented */ enum SlopeType { RADIANS, // Angle from local vertical in radians DEGREES, // Angle from local vertical in degrees (default) RATIO, // dH/dR ratio of change in height to change in horizontal ground distance NORMALIZED // Angle from local vertical normalized so that 0.0 = 0 deg, 1.0 = 90 deg) }; ossimSlopeFilter(); ossimSlopeFilter(ossimImageSource* inputSource); virtual void initialize(); virtual ossimString getLongName() const; virtual ossimString getShortName() const; virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 rLevel=0); /** * Returns the output pixel type of the tile source. This override the * base class since it simply returns it's input scalar type which is * not correct with this object. */ virtual ossimScalarType getOutputScalarType() const { return OSSIM_FLOAT32; } /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; void setSlopeType(SlopeType t) { m_slopeType = t; } protected: virtual ~ossimSlopeFilter(); static ossimString getSlopeTypeString(SlopeType t); ossimRefPtr m_normals; SlopeType m_slopeType; TYPE_DATA }; #endif /* #ifndef ossimSlopeFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimSrtmTileSource.h000066400000000000000000000042341352751253100242560ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Image handler class for a Shuttle Radar Topography Mission (SRTM) file. // //---------------------------------------------------------------------------- // $Id: ossimSrtmTileSource.h 17932 2010-08-19 20:34:35Z dburken $ #ifndef ossimSrtmTileSource_HEADER #define ossimSrtmTileSource_HEADER #include #include class OSSIMDLLEXPORT ossimSrtmTileSource : public ossimGeneralRasterTileSource { public: ossimSrtmTileSource(); virtual ossimString getShortName() const; virtual ossimString getLongName() const; virtual bool open(); //! Returns the image geometry object associated with this tile source or NULL if not defined. //! The geometry contains full-to-local image transform as well as projection (image-to-world) virtual ossimRefPtr getImageGeometry(); /** * Method to save the state of an object to a keyword list. * @return true on success, false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. * * @return true on success, false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = NULL); /** * @brief Gets a property. * @param The name of the property to get. * @return The property if found. */ virtual ossimRefPtr getProperty( const ossimString& name)const; /** * @brief Adds property names to array. * @param propertyNames Array to populate with property names. */ virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimSrtmTileSource(); ossimSrtmSupportData m_SrtmSupportData; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimStreamReaderInterface.h000066400000000000000000000025521352751253100255320ustar00rootroot00000000000000//---------------------------------------------------------------------------- // File: ossimStreamReaderInterface.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Class interface ossimMetadataInterface. // // Has pure virtual "open" method that derived classes must // implement to be concrete. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimStreamReaderInterface_HEADER #define ossimStreamReaderInterface_HEADER 1 #include #include #include /** @class ossimStreamReaderInterface */ class ossimStreamReaderInterface { public: /** @brief default constructor */ ossimStreamReaderInterface(){} /** @brief virtual destructor. */ virtual ~ossimStreamReaderInterface(){} /** * @brief Pure virtual open method that takes a stream. * @param str Open stream to image. * @param connectionString * @return true on success, false on error. */ virtual bool open( std::shared_ptr& str, const std::string& connectionString ) = 0; #if 0 virtual bool open( std::istream* str, std::streamoff restartPosition, bool youOwnIt ) = 0; #endif }; #endif /* #ifndef ossimStreamReaderInterface_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimSubImageTileSource.h000066400000000000000000000055001352751253100250220ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimSubImageTileSource.h // // Copyright (C) 2001 ImageLinks, Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains declaration of class ossimSubImageTileSource. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimSubImageTileSource.h 22233 2013-04-15 15:12:54Z gpotts $ #ifndef ossimSubImageTileSource_HEADER #define ossimSubImageTileSource_HEADER #include /*!**************************************************************************** * * CLASS: ossimSubImageTileSource * * This tile source permits specifying an offset that is to be applied to the * tile origin for all getTile() requests. It is intended for converting * a full-image space coordinate to a sub-image coordinate. * *****************************************************************************/ class OSSIM_DLL ossimSubImageTileSource : public ossimImageSourceFilter { public: /*! * Default constructor initializes the sub-image offset to zero. */ ossimSubImageTileSource(); /*! * Constructor accepts an input source pointer. Offset is defaulted to (0,0). */ ossimSubImageTileSource(ossimImageSource* inputSource); /*! * Constructs with specified input source and offset. */ ossimSubImageTileSource(ossimImageSource* inputSource, const ossimIpt& offset); /*! * Permits setting the image's offset relative to the full image space. */ void setSubImageOffset(const ossimIpt& offset) { theSubImageOffset=offset; } ossimIpt getSubImageOffset()const{ return theSubImageOffset;} virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 rr_level=0); /*! * Fetches the sub-image's bounding rect in FULL-IMAGE SPACE. */ virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0) const; /*! * Fetches the sub-image's valid image vertices in FULL-IMAGE SPACE. */ virtual void getValidImageVertices(std::vector& validVertices, ossimVertexOrdering ordering=OSSIM_CLOCKWISE_ORDER, ossim_uint32 resLevel=0)const; virtual void initialize(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; private: virtual ~ossimSubImageTileSource(); ossimIpt theSubImageOffset; ossimRefPtr theTile; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimTableRemapper.h000066400000000000000000000055111352751253100240540ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Table remapper class declaration. // // Takes input tile, remaps it through a table, then output tile in the desired // scalar type. // // Two modes one that works on native remap tables, that being of the same // scalar type (like ossim_uint8) of the input connection, and another that // uses a normalized remap table (more scalar independent). // //************************************************************************* // $Id: ossimTableRemapper.h 22479 2013-11-12 02:18:55Z dburken $ #ifndef ossimTableRemapper_HEADER #define ossimTableRemapper_HEADER #include class OSSIMDLLEXPORT ossimTableRemapper : public ossimImageSourceFilter { public: enum RemapTableType { UKNOWN = 0, NATIVE = 1, MIN_MAX = 2, // the data is native but must use min max for scale NORMALIZED = 3 }; /** default constructor */ ossimTableRemapper(); virtual ossimScalarType getOutputScalarType() const; virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); virtual void initialize(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual std::ostream& print(std::ostream& os) const; friend std::ostream& operator << (std::ostream& os, const ossimTableRemapper& tr); protected: /** virtual destructor */ virtual ~ossimTableRemapper(); ossimRefPtr theTile; ossimRefPtr theTmpTile; std::vector theTable; ossim_float64* theNormBuf; ossim_uint32 theTableBinCount; ossim_uint32 theTableBandCount; RemapTableType theTableType; ossimScalarType theInputScalarType; ossimScalarType theOutputScalarType; void allocate(const ossimIrect& rect); void destroy(); void remapFromNativeTable(ossimRefPtr& inputTile); template void remapFromNativeTable( T dummy, ossimRefPtr& inputTile); void remapFromNormalizedTable(ossimRefPtr& inputTile); template void dumpTable(T dummy, std::ostream& os) const; // Do not allow copy constructor, operator=. ossimTableRemapper(const ossimTableRemapper& tr); ossimTableRemapper& operator=(const ossimTableRemapper& tr); TYPE_DATA }; #endif /* #ifndef ossimTableRemapper_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimTiffOverviewBuilder.h000066400000000000000000000225321352751253100252610ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class declaration for TiffOverviewBuilder. // //******************************************************************* // $Id: ossimTiffOverviewBuilder.h 22232 2013-04-13 20:06:19Z dburken $ #ifndef ossimTiffOverviewBuilder_HEADER #define ossimTiffOverviewBuilder_HEADER #include #include #include #include #include #include class ossimConnectableObject; class ossimFilename; class ossimImageGeometry; class OSSIM_DLL ossimTiffOverviewBuilder : public ossimOverviewBuilderBase { public: enum { DEFAULT_COMPRESS_QUALITY=75 }; /** default constructor */ ossimTiffOverviewBuilder(); /** virtual destructor */ virtual ~ossimTiffOverviewBuilder(); /** * Supports BOX or NEAREST NEIGHBOR. When indexed you should probably use nearest neighbor */ void setResampleType(ossimFilterResampler::ossimFilterResamplerType resampleType); /** * Builds overview file and sets "theOutputFile" to that of * the overview_file. * * @param overview_file The overview file name to output. * * @param copy_all If set to true the entire image will be * copied. This can be used to convert an image to a tiled tif. * * @return trueon success, false on error. */ bool buildOverview(const ossimFilename& overview_file, bool copy_all=false); /** * Calls buildOverview. This method uses "theOutputFile" for the file * name. * * If the copy_all flag is set the entire image will be copied. This can * be used to convert an image to a tiled tif. * * @return true on success, false on error. * * @note If setOutputFile was not called the output name will be derived * from the image name. If image was "foo.tif" the overview file will * be "foo.ovr". */ virtual bool execute(); /** * Sets the compression type to use when building overviews. * * @param compression_type Current supported types: * - COMPRESSION_JPEG * - COMPRESSION_LZW * - COMPRESSION_DEFLATE * - COMPRESSION_PACKBITS * - COMPRESSION_NONE (default) */ void setCompressionType(ossim_uint16 compression_type); /** * Sets the compression quality for use when using a compression type * of COMPRESSION_JPEG. * * @param quality Range 1 to 100 with 100 being best quality. */ void setJpegCompressionQuality(ossim_int32 quality); /** * @brief Method to return copy all flag. * @return The copy all flag. If true all data will be written to the * overview including R0. */ bool getCopyAllFlag() const; /** * @brief Sets internal overviews flag. * @param flag If true, and input source is tiff format, overviews will be * built internally. */ void setInternalOverviewsFlag(bool flag); /** @return The intenal overview flag. */ bool getInternalOverviewsFlag() const; /** * @brief Sets theCopyAllFlag. * @param flag The flag. If true all data will be written to the * overview including R0. */ void setCopyAllFlag(bool flag); /** @return ossimObject* to this object. */ virtual ossimObject* getObject(); /** * @return const ossimObject* to this object. */ virtual const ossimObject* getObject() const; /** * @return true if input is an image handler. */ virtual bool canConnectMyInputTo(ossim_int32 index, const ossimConnectableObject* obj) const; /** * @brief Sets the input to the builder. Satisfies pure virtual from * ossimOverviewBuilderBase. * * @param imageSource The input to the builder. * * @return True on successful initializion, false on error. */ virtual bool setInputSource(ossimImageHandler* imageSource); /** * @brief Sets the output filename. * Satisfies pure virtual from ossimOverviewBuilderBase. * @param file The output file name. */ virtual void setOutputFile(const ossimFilename& file); /** * @brief Gets the output file name. (pure virtual) * * @return The output file name or ossimFilename::NIL if it was not set * yet and the image handle has not been initialized. * * @note This is non-const as a call to this may force initialization of * overview builder output file name if the it was not set already. * * @note This will return ossimFilename::NIL unless one of was called, * setInputSource or setOutputFile. */ virtual ossimFilename getOutputFile() const; void setOutputTileSize(const ossimIpt& tileSize); /** * @brief Sets the overview output type. * * Satisfies pure virtual from ossimOverviewBuilderBase. * * Currently handled types are: * "ossim_tiff_nearest" and "ossim_tiff_box" * * @param type This should be the string representing the type. This method * will do nothing if type is not handled and return false. * * @return true if type is handled, false if not. */ virtual bool setOverviewType(const ossimString& type); /** * @brief Gets the overview type. * Satisfies pure virtual from ossimOverviewBuilderBase. * @return The overview output type as a string. */ virtual ossimString getOverviewType() const; /** * @brief Method to populate class supported types. * Satisfies pure virtual from ossimOverviewBuilderBase. * @param typeList List of ossimStrings to add to. */ virtual void getTypeNameList(std::vector& typeList)const; /** * @brief Method to set properties. * @param property Property to set. * * @note Currently supported property: * name=levels, value should be list of levels separated by a comma with * no spaces. Example: "2,4,8,16,32,64" */ virtual void setProperty(ossimRefPtr property); /** * @brief Method to populate the list of property names. * @param propertyNames List to populate. This does not clear the list * just adds to it. */ virtual void getPropertyNames(std::vector& propertyNames)const; private: /** * Copy the full resolution image data to the output tif image. */ bool writeR0(TIFF* tif); /** * Write reduced resolution data set to the tif file. * * @param firstRestLevel used to tell method that if a histogram is needed, do it on * that res level. */ bool writeRn(ossimImageHandler* imageHandler, TIFF* tif, ossim_uint32 resLevel, bool firstResLevel); /** * Set the tiff tags for the appropriate resLevel. Level zero is the * full resolution image. * * @param tif Pointer to the tif file. * @param outputRect The dimensions (zero based) of res set. * @param rrds_level The current reduced res level. */ bool setTags(TIFF* tif, const ossimIrect& outputRect, ossim_int32 resLevel) const; /** * Writes geotiff tags. * @param geom * @param boundingRect * @param resLevel Zero base, 0 being full res. * @param tif * @return true on success, false on error. */ bool setGeotiffTags(const ossimImageGeometry* geom, const ossimDrect& boundingRect, ossim_uint32 resLevel, TIFF* tif); TIFF* openTiff( const ossimString& filename ) const; void closeTiff(TIFF* tif); /** * @returns true if m_internalOverviewsFlag and input image supports * building internal overviews. Currently only tiff reader. */ bool buildInternalOverviews() const; /** * @return true if m_copyAllFlag is set and build internal overviews is not * set. */ bool copyR0() const; // Disallow these... ossimTiffOverviewBuilder(const ossimTiffOverviewBuilder& source); ossimTiffOverviewBuilder& operator=(const ossimTiffOverviewBuilder& rhs); std::vector m_nullDataBuffer; ossim_int32 m_bytesPerPixel; ossim_int32 m_bitsPerSample; ossim_int32 m_tileWidth; ossim_int32 m_tileHeight; ossim_int32 m_tileSizeInBytes; ossim_int32 m_sampleFormat; ossim_int32 m_currentTiffDir; ossim_uint16 m_tiffCompressType; ossim_int32 m_jpegCompressQuality; ossimFilterResampler::ossimFilterResamplerType m_resampleType; std::vector m_nullPixelValues; bool m_copyAllFlag; ossimString m_tempExtension; bool m_outputTileSizeSetFlag; bool m_internalOverviewsFlag; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimTiffTileSource.h000066400000000000000000000315671352751253100242320ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // Frank Warmerdam (warmerdam@pobox.com) // // Description: // // Contains class declaration for ossimTiffTileSource. // ossimTiffTileSource is derived from ImageHandler which is derived from // TileSource. //******************************************************************* // $Id$ #ifndef ossimTiffTileSource_HEADER #define ossimTiffTileSource_HEADER 1 #include #include #include #include #include /* * TIFF is defined as an incomplete type to hide the tiff library's internal * data structures from clients. */ typedef struct tiff TIFF; class ossimImageData; class ossimTiffOverviewTileSource; class TiffStreamAdaptor; class OSSIMDLLEXPORT ossimTiffTileSource : public ossimImageHandler { public: friend class TiffStreamAdaptor; enum ReadMethod { UNKNOWN, READ_RGBA_U8_TILE, READ_RGBA_U8_STRIP, READ_RGBA_U8A_STRIP, READ_SCAN_LINE, READ_TILE, READ_U16_STRIP }; ossimTiffTileSource(); virtual ossimString getLongName() const; virtual ossimString getShortName() const; /** * Returns true if the image_file can be opened and is a valid tiff file. */ virtual bool open(const ossimFilename& image_file); /** * @brief This open takes a stream and stores/captures the shared pointer * on success. * @param str Open stream to image. * @param connectionString Stored on success as the file name. * @return true on success, false on error. */ bool open( std::shared_ptr& str, const std::string& connectionString ); virtual void close(); /** * Returns a pointer to a tile given an origin representing the upper left * corner of the tile to grab from the image. * Satisfies pure virtual from TileSource class. */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Returns the number of bands in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; virtual ossim_uint32 getNumberOfOutputBands () const; /** * @brief Indicates whether or not the image handler can control output * band selection via the setOutputBandList method. * * Overrides: ossimImageHandler::isBandSelector * * @return true */ virtual bool isBandSelector() const; /** * @brief If the image handler "isBandSeletor()" then the band selection * of the output chip can be controlled. * * Overrides: ossimImageHandler::setOutputBandList * * @return true on success, false on error. */ virtual bool setOutputBandList(const std::vector& band_list); /** @brief Initializes bandList to the zero based order of output bands. */ virtual void getOutputBandList(std::vector& bandList) const; /** * Returns the number of lines in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 resLevel = 0) const; /** * Returns the number of samples in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 resLevel = 0) const; /** * Returns the number of image file directories in the tiff image. */ virtual ossim_uint32 getNumberOfDirectories() const; /** * Returns the number of reduced resolution data sets (rrds). * Notes: * * - The full res image is counted as a data set so an image with no * reduced resolution data set will have a count of one. * - This method counts R0 as a res set even if it does not have one. * This was done deliberately so as to not screw up code down the * line. */ virtual ossim_uint32 getNumberOfDecimationLevels() const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool isOpen()const; /** * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns true if the first directory of the tiff image did not have * the reduced resolution file type set. */ bool hasR0() const; virtual ossim_float64 getMinPixelValue(ossim_uint32 band=0)const; virtual ossim_float64 getMaxPixelValue(ossim_uint32 band=0)const; virtual ossim_float64 getNullPixelValue(ossim_uint32 band=0)const; virtual bool isValidRLevel(ossim_uint32 resLevel) const; /** * @return The tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width, which can be different than the * internal image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * @return The tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileHeight which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; void setApplyColorPaletteFlag(bool flag); bool getApplyColorPaletteFlag()const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; bool isColorMapped() const; virtual std::ostream& print(std::ostream& os) const; TIFF* tiffPtr() { return theTiffPtr; } #if 0 /** * @brief Method to get the image geometry object associated with this * image. * * The geometry contains full-to-local image transform as well as * projection (image-to-world). * * @return ossimImageGeometry* or null if not defined. */ virtual ossimImageGeometry* getImageGeometry(); #endif protected: virtual ~ossimTiffTileSource(); /** * Returns true if no errors initializing object. * * Notes: * - Callers of this method must ensure "theTiffPtr" data member * is initialized. * - This method was added to consolidate object initialization code * between constructor and public open method. */ bool open(); // Must be protected for derived ossimTerraSarTiffReader. TIFF* theTiffPtr; /** Returns false if image is stripped, even though the input tile size is non-zero. In the case * of stripped format, the image tile size is set to numColsInImage X numRowsPerStrip. */ virtual bool isImageTiled() const; private: /** * Adjust point to even tile boundary. Assumes 0,0 origin. * Shifts in the upper left direction. */ void adjustToStartOfTile(ossimIpt& pt) const; /** * If the tiff source has R0 then this returns the current tiff directory * that the tiff pointer is pointing to; else, it returns the current * directory + 1. */ ossim_uint32 getCurrentTiffRLevel() const; /** * @brief Convenience method to get the zero based rgb output band list. * * * @param bandList Initialized by this. * @return true on success, false if number of bands is less than 3 or if * rgb bands could not be derived. */ virtual bool getRgbBandList(std::vector &bandList) const; ossimString getReadMethod(ossim_uint32 directory) const; bool loadTile(const ossimIrect& tile_rect, const ossimIrect& clip_rect, ossimImageData* result); bool loadFromRgbaU8Tile(const ossimIrect& tile_rect, const ossimIrect& clip_rect, ossimImageData* result); bool loadFromRgbaU8Strip(const ossimIrect& tile_rect, const ossimIrect& clip_rect, ossimImageData* result); bool loadFromRgbaU8aStrip(const ossimIrect& tile_rect, const ossimIrect& clip_rect, ossimImageData* result); bool loadFromU16Strip(const ossimIrect& clip_rect, ossimImageData* result); bool loadFromScanLine(const ossimIrect& clip_rect, ossimImageData* result); bool loadFromTile(const ossimIrect& clip_rect, ossimImageData* result); void setReadMethod(); /** * Change tiff directory and sets theCurrentDirectory. * * @return true on success, false on error. */ bool setTiffDirectory(ossim_uint16 directory); void populateLut(); /** * @brief validateMinMaxNull Checks min, max and null to make sure they are not equal * to the scalar type nan or double nan; sets to default min max if so. */ void validateMinMaxNull(); /** * @brief Checks line/samples of level for power of two decimation from the * previous rlevel. * * Used to weed out thumbnail directories being used as a reduced * resolution layer. * * Note this shuts off the thumbnail which someone may * want to see. We could make this a reader prop if it becomes an issue. * drb - 09 Jan. 2012. * * @param dir The tiff directory index. * * @return true is so; else, false. If level is zero returns false. */ bool isPowerOfTwoDecimation(ossim_uint32 dir) const; /** @brief Allocates theTile. */ void allocateTile(); /** * @brief Allocates theBuffer * @return true on success; false, on error. */ bool allocateBuffer(); ossimRefPtr theTile; ossim_uint8* theBuffer; ossim_uint32 theBufferSize; ossimIrect theBufferRect; ossim_uint32 theBufferRLevel; ossim_uint16 theSamplesPerPixel; ossim_uint16 theBitsPerSample; ossim_uint16 theSampleFormatUnit; ossim_float64 theMaxSampleValue; ossim_float64 theMinSampleValue; ossim_float64 theNullSampleValue; ossim_uint16 theNumberOfDirectories; ossim_uint16 theCurrentDirectory; bool theR0isFullRes; ossim_uint32 theBytesPerPixel; ossimScalarType theScalarType; bool theApplyColorPaletteFlag; // Things we need from each directory as they can be different. std::vector theImageWidth; std::vector theImageLength; std::vector theReadMethod; std::vector thePlanarConfig; std::vector thePhotometric; std::vector theRowsPerStrip; std::vector theImageDirectoryList; /** theInputTileSize reflects the most efficient tiling scheme for reading from disk. If the * image is tiled, then the output tile size will match the tiling on disk. If it is stripped, * then the input "tile" size will be the size of the strip, while the output tile size will * be different and equal to the ossim default tile size. Strips are cached internally to * speed up output tiling. */ std::vector theInputTileSize; mutable ossimIpt theOutputTileSize; // Formerly known as theCurrentTileWidth/Length ossim_uint32 theCurrentTiffRlevel; ossim_int32 theCompressionType; std::vector theOutputBandList; std::shared_ptr m_streamAdaptor; TYPE_DATA }; #endif /* #ifndef ossimTiffTileSource_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimTiffWriter.h000066400000000000000000000150241352751253100234160ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Frank Warmerdam (warmerda@home.com) // // Description: // // Contains class declaration for TiffWriter. // //******************************************************************* // $Id: ossimTiffWriter.h 20026 2011-09-01 16:33:18Z dburken $ #ifndef ossimTiffWriter_HEADER #define ossimTiffWriter_HEADER #include #include #include #include #include #include class ossimMapProjectionInfo; class OSSIMDLLEXPORT ossimTiffWriter : public ossimImageFileWriter { public: ossimTiffWriter(); virtual ~ossimTiffWriter(); enum UnitType { UNDEFINED = 0, LINEAR_METER = 9001, LINEAR_FOOT = 9002, LINEAR_FOOT_US_SURVEY = 9003, ANGULAR_DEGREES = 9102 }; enum { USER_DEFINED = 32767 }; /** * void getImageTypeList(std::vector& imageTypeList)const * * Appends this writer image types to list "imageTypeList". * * This writer has the following types: * tiff_strip * tiff_strip_band_separate * tiff_tiled * tiff_tiled_band_separate * * @param imageTypeList stl::vector list to append to. */ virtual void getImageTypeList(std::vector& imageTypeList)const; virtual bool isOpen()const; virtual bool open(); virtual void close(); /** * Ranges from 1 to 100 with 100 being the best. This value is only used * if the compression type is set to jpeg. (default = 75) * * @param quality Value to set theJpegQuality to. * * @note If quality is out of range it will be set to DEFAULT_JPEG_QUALITY. */ virtual void setJpegQuality(ossim_int32 quality); /** * @return theJpegQuality */ virtual ossim_int32 getJpegQuality()const; /** * compression type can be JPEG, PACKBITS, or ZIP/DEFLATE */ virtual void setCompressionType(const ossimString& type); virtual ossimString getCompressionType()const; virtual bool getGeotiffFlag()const; virtual void setGeotiffFlag(bool flag); virtual void setTileSize(const ossimIpt& tileSize); virtual ossimIpt getOutputTileSize()const; virtual ossim_int32 setProjectionInfo(const ossimMapProjectionInfo& proj); void setLut(const ossimNBandLutDataObject& lut); /** * saves the state of the object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Will set the property whose name matches the argument * "property->getName()". * * @param property Object containing property to set. */ virtual void setProperty(ossimRefPtr property); /** * @param name Name of property to return. * * @returns A pointer to a property object which matches "name". Returns * NULL if no match is found. */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * Pushes this's names onto the list of property names. * * @param propertyNames array to add this's property names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; /** * Returns a 3-letter extension from the image type descriptor * (theOutputImageType) that can be used for image file extensions. * * @param imageType string representing image type. * * @return the 3-letter string extension. */ virtual ossimString getExtension() const; bool hasImageType(const ossimString& imageType) const; //! Will take an ossimIMageData tile and write it to disk as a general raster file. static void dumpTileToFile(ossimRefPtr t, const ossimFilename& f); protected: virtual bool writeFile(); /** * @return true on success, false on error. */ bool openTiff(); /** * @return true on success, false on error. */ bool closeTiff(); /** * Writes image data to a tiled tiff format. * @return true on success, false on error. */ bool writeToTiles(); /** * Writes image data to a tiled tiff band separate format. * @return true on success, false on error. */ bool writeToTilesBandSep(); /** * Writes image data to a strip tiff format. * @return true on success, false on error. */ bool writeToStrips(); /** * Writes image data to a strip tiff band separate format. * @return true on success, false on error. */ bool writeToStripsBandSep(); /** * Writes tiff tags from ossimMapProjectionInfo to tiff file. * @return true on success, false on error. */ bool writeTiffTags(); /** * Writes geotiff tags from ossimMapProjectionInfo to tiff file. * @return true on success, false on error. */ bool writeGeotiffTags(ossimRefPtr projectionInfo); /** * @return true if the output type is tiled, false if not. */ bool isTiled() const; void writeMinMaxTags(const std::vector& minBand, const std::vector& maxBand); bool isLutEnabled()const; UnitType getUnitType(ossim_int32 pcsCode, const ossimString& projName) const; UnitType getPcsUnitType(ossim_int32 pcsCode) const; void checkColorLut(); void* theTif; ossimString theCompressionType; ossimString thePhotoMetric; ossim_int32 theJpegQuality; bool theOutputGeotiffTagsFlag; bool theColorLutFlag; ossimRefPtr theProjectionInfo; ossimIpt theOutputTileSize; ossimRefPtr theColorLut; ossimFilename theLutFilename; bool theForceBigTiffFlag; bool theBigTiffFlag; mutable ossimRefPtr theNBandToIndexFilter; TYPE_DATA }; #endif /* End of "#ifndef ossimTiffWriter_HEADER" */ ossim-Miami-2.9.1/include/ossim/imaging/ossimTileCache.h000066400000000000000000000060411352751253100231510ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: This file contains the cache algorithm // //*********************************** // $Id: ossimTileCache.h 17207 2010-04-25 23:21:14Z dburken $ #ifndef DataCache_HEADER #define DataCache_HEADER #include #include #include #include #include #include #include class OSSIM_DLL ossimTileCache { public: ossimTileCache(long numberOfBuckets = 10); virtual ~ossimTileCache(); /*! * This will return a tile if found. Note this tile is still * owned by the cache. */ virtual ossimDataObject* get(const ossimDpt3d &origin, unsigned long resLevel=0); /*! * Will remove the tile from the cache and will not delete. Note: * the cache no longer owns the tile. */ virtual ossimDataObject* remove(const ossimDpt3d &origin, unsigned long resLevel=0); /*! * This will not duplicate the tile. Note the tile is owned * by the cache. */ virtual ossimDataObject* insert(const ossimDpt3d &origin, ossimDataObject* data, unsigned long resLevel=0); /*! * Not implemented */ void invalidate(); /*! * Not implemented */ virtual void invalidate(const ossimDpt3d &origin, ossim_uint32 resLevel); virtual long numberOfItems()const{return theCache?(long)theCache->size():(long)0;} virtual void display()const; virtual ossim_uint32 sizeInBytes(){return theSizeInBytes;} protected: struct ossimTileInformation { public: friend std::ostream& operator <<(std::ostream &out, const ossimTileInformation& /* info */) { return out; } ossimTileInformation(ossimDataObject* aTile, const ossimDpt3d &origin = ossimDpt(0,0), unsigned long resLevel = 0) : theCachedTile(aTile), theOrigin(origin), theResLevel(resLevel) {} ossimRefPtr theCachedTile; ossimDpt3d theOrigin; unsigned long theResLevel; }; typedef std::multimap::iterator Iterator; typedef ossimTileInformation* CacheDataPtr; typedef ossimTileInformation CacheData; void deleteAll(); virtual ossim_uint32 bucketHash(const ossimDpt3d &aPt); virtual ossim_uint32 tileId(const ossimDpt3d &aPt); std::multimap *theCache; long theNumberOfBuckets; ossim_uint32 theSizeInBytes; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimTilePatch.h000066400000000000000000000110301352751253100231770ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimTilePatch.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimTilePatch_HEADER #define ossimTilePatch_HEADER #include #include #include #include #include #include class ossimImageSource; class ossimTilePatch : public ossimObject { public: ossimTilePatch(ossimImageSource* input); /*! * The rect is assumed up right and all we need * to do is compute the even tile boundary rect */ ossimTilePatch(ossimScalarType scalarType = OSSIM_UCHAR, long numberOfComponents = 1, long width=128, long height=128); /*! * return the tile boundary aligned rectangle for this * patch. */ virtual ossimIrect getRect()const; /*! * The padding is for any convolution that must take * place. */ virtual void setRect(const ossimDpt &p1, const ossimDpt &p2, const ossimDpt &p3, const ossimDpt &p4, const ossimDpt &tile_size, const ossimDpt &padding=ossimDpt(0,0)); virtual void setRect(const ossimDrect &aRect, const ossimDpt &tile_size, const ossimDpt &padding=ossimDpt(0,0)); virtual void setRect(const ossimDpt ¢er_of_rect, const ossimDpt &rect_size, const ossimDpt &tile_size, const ossimDpt &padding=ossimDpt(0,0)); /*! * This will fill the tile from the tile patch. */ virtual void fillTile(ossimRefPtr& aTile)const; /*! * This will fill the tile from the tile patch and apply the convolution * kernel. This is optimized for upright rectangles. Use the bilinear * fill tile bellow for arbitrary 4-sided polygons. */ virtual void fillTile(ossimRefPtr& result, ossimDiscreteConvolutionKernel* kernel)const; /*! * We will assume that the patch is already * big enough to satisfy the kernel size. */ virtual void fillTile(ossimRefPtr& result, const ossimDpt &ul, const ossimDpt &ur, const ossimDpt &deltaUl, const ossimDpt &deltaUr, const ossimDpt &length)const; virtual void fillPatch(ossimImageSource *imageSource, long resLevel = 0); // static ossimIrect alignRectToBoundary(const ossimDrect &aRect, // const ossimDpt &tile_size); static ossimDrect findBoundingRect(const ossimDpt &p1, const ossimDpt &p2, const ossimDpt &p3, const ossimDpt &p4); /*! * Do not delete this data. We give raw access to the buffer * if there are special things you wish to have done. */ ossimRefPtr getData(){return thePatchData;} void setData(ossimRefPtr& patchData); /*! * This will implement an in place convolution. It will * allocate a buffer pass it to the convolution algorithm * and then replace the internal buffer. */ void convolve(ossimDiscreteConvolutionKernel* kernel); protected: virtual ~ossimTilePatch(); ossimRefPtr thePatchData; static ossimDiscreteNearestNeighbor nearestNeighborKernel; template void fillTileTemplate(T dummyVariable, ossimRefPtr& result, const ossimDpt &ul, const ossimDpt &ur, const ossimDpt &deltaUl, const ossimDpt &deltaUr, const ossimDpt &length)const; template void fillTileTemplate(T dummyVariable, ossimRefPtr& result, ossimDiscreteConvolutionKernel* kernel)const; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimTiledImageHandler.h000066400000000000000000000137621352751253100246420ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: // // Image handler used when the full image is distributed across multiple files, // As is the case for tiled Quickbird imagery. This is not for use with band-separate formats, // but only "spatially-separate" schemes. Throughout, MFT = multiple file tiles, the disk storage // scheme handled by this class. // //************************************************************************************************** // $Id: ossimTiledImageHandler.h 2644 2011-05-26 15:20:11Z oscar.kramer $ #ifndef ossimTiledImageHandler_HEADER #define ossimTiledImageHandler_HEADER #include // Enable this flag to utilize the system of separate overviews for each tile-file #define USING_SUB_OVRS 0 /** * This class defines an abstract Handler which all image handlers(loaders) * should derive from. */ class OSSIMDLLEXPORT ossimTiledImageHandler : public ossimImageHandler { public: //! Constructor (default): ossimTiledImageHandler(); //! Destructor: virtual ~ossimTiledImageHandler(); //! @return Returns true on success, false on error. //! @note This method relies on the data member ossimImageData::theImageFile //! being set. virtual bool open() = 0; //! Deletes the overview and clears the valid image vertices. Derived //! classes should implement. */ virtual void close(); //! Derived classes must implement this method to be concrete. //! @return true if open, false if not. virtual bool isOpen()const; virtual ossim_uint32 getNumberOfInputBands() const; //! @param resLevel Reduced resolution level to return lines of. //! Default = 0 //! @return The number of lines for specified reduced resolution level. virtual ossim_uint32 getNumberOfLines(ossim_uint32 resLevel = 0) const; //! @param resLevel Reduced resolution level to return samples of. //! Default = 0 //! @return The number of samples for specified reduced resolution level. virtual ossim_uint32 getNumberOfSamples(ossim_uint32 resLevel = 0) const; //! Method to save the state of an object to a keyword list. //! Return true if ok or false on error. virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; //! Method to the load (recreate) the state of an object from a keyword //! list. Return true if ok or false on error. virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Indicates whether or not the image is tiled internally. //! This implementation returns true if (getImageTileWidth() && //! getImageTileHeight()) are both non zero. //! Override in the image handler if something else is desired. //! Returns true if tiled, false if not. virtual bool isImageTiled() const; //! Returns the tile width of the image or 0 if the image is not tiled. //! Note: this is not the same as the ossimImageSource::getTileWidth which //! returns the output tile width which can be different than the internal //! image tile width on disk. virtual ossim_uint32 getImageTileWidth() const; //! Returns the tile height of the image or 0 if the image is not tiled. //! Note: this is not the same as the ossimImageSource::getTileHeight which //! returns the output tile height which can be different than the internal //! image tile height on disk. virtual ossim_uint32 getImageTileHeight() const; //! Fills the requested tile by pulling pixels from multiple file tiles as needed. virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel); //! Returns scalar type of first tile (should be the same for all tiles) virtual ossimScalarType getOutputScalarType() const; //! Returns overall bounding rect in image space. virtual ossimIrect getImageRectangle(ossim_uint32 resLevel = 0) const; protected: //! Class for record of one tile file: class ossimTileFile { public: ossimTileFile() : overviewIsOpen(false) {} ossimFilename tileFilename; std::vector subImageRects; // one rect per resolution level ossimRefPtr imageHandler; bool overviewIsOpen; }; //! Initialize tile buffer to match image datatype. void allocate(); std::vector m_tileFiles; ossimRefPtr m_tile; ossimRefPtr m_blankTile; ossimIrect m_fullImgRect; ossim_uint32 m_startOvrResLevel; #if USING_SUB_OVRS public: //! Will build over files, one for each tile file. //! @param includeFullResFlag if true the full resolution layer will also //! be put in the overview format. This is handy for inefficient formats. virtual bool buildOverview( ossimImageHandlerOverviewCompressionType compressionType = OSSIM_OVERVIEW_COMPRESSION_NONE, ossim_uint32 quality = 75, ossimFilterResampler::ossimFilterResamplerType resampleType = ossimFilterResampler::ossimFilterResampler_BOX, bool includeFullResFlag=false); virtual bool openOverview(); virtual void closeOverview(); //! This is not an allowed operation since there are many overviews (one per tile) and the //! precise overview being requested is ambiguous: virtual const ossimImageHandler* getOverview() const { return NULL; } //! @return true if getNumberOfReducedResSets > 1, false if not. //! @see getNumberOfReducedResSets() virtual bool hasOverviews() const; //! Returns the number of decimation (reduced resolution) levels. This is the minimum number //! among all sub-image tile-files. virtual ossim_uint32 getNumberOfDecimationLevels() const; protected: //! Will complete the opening process. If there are overviews it will open them. virtual void completeOpen(); bool m_lockSubOvrs; #endif /* #if USING_SUB_OVRS */ TYPE_DATA }; #endif /* #ifndef ossimTiledImageHandler_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimTiledImagePatch.h000066400000000000000000000066241352751253100243230ustar00rootroot00000000000000//--- // License: MIT // // Author: David Burken // // Description: See class declaration below. // //--- // $Id$ #ifndef ossimTiledImagePatch_HEADER #define ossimTiledImagePatch_HEADER 1 #include #include #include #include #include class ossimIrect; /** * @class ossimTiledImagePatch * * Class to fill a patch from input tiles requested on even tile boundaries * with a tile size typically matching the input, with some output tile size * different from the input. */ class OSSIMDLLEXPORT ossimTiledImagePatch : public ossimImageSourceFilter { public: /** default constructor */ ossimTiledImagePatch(); /** * @brief Initializes bounding rects and tile size(if not set) from input. */ virtual void initialize(); /** * Returns a pointer to a tile given an origin representing the upper left * corner of the tile to grab from the image. * Satisfies pure virtual from TileSource class. */ virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** @return "ossimTiledImagePatch" */ virtual ossimString getClassName() const; /** @return "OSSIM tiled image patch" */ virtual ossimString getLongName() const; /** @return "tiled_image_patch" */ virtual ossimString getShortName() const; /** @return The reference to the input tile size. */ const ossimIpt& getInputTileSize() const; /** * @brief Sets the input tile size. * @param tileSize * @return true on success, false on error. * On error m_inpuTileSize is set to nans. */ bool setInputTileSize( const ossimIpt& tileSize ); /** * @biref Method to the load the class state from a keyword list. * @param kwl * @param prefix * @return true on success, false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Method to save the state of an object to a keyword list. * @param kwl * @param prefix * @return true on success, false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: /** virtual protected destructor */ virtual ~ossimTiledImagePatch(); private: /** @brief Allocates the tile. Called on first getTile. */ void allocateTile(); /** @brief Test the bounds of resLevel. */ bool isValidRLevel(ossim_uint32 resLevel) const; /** @brief Private to disallow use... */ ossimTiledImagePatch(const ossimTiledImagePatch&); /** @brief Private to disallow use... */ ossimTiledImagePatch& operator=(const ossimTiledImagePatch&); ossimRefPtr m_tile; ossimIpt m_inputTileSize; TYPE_DATA }; #endif /* #ifndef ossimTiledImagePatch_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimTiling.h000066400000000000000000000145001352751253100225550ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2004 Garrett Potts // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: implementation for image generator // //************************************************************************* // $Id: ossimTiling.h 20103 2011-09-17 16:10:42Z dburken $ #ifndef ossimTiling_HEADER #define ossimTiling_HEADER #include #include #include #include #include #include #include class OSSIM_DLL ossimTiling : public ossimObject { public: enum ossimTilingDeltaType { ossimTilingDeltaType_TOTAL_PIXELS, ossimTilingDeltaType_PER_PIXEL }; ossimTiling(); bool initialize(const ossimMapProjection& proj, const ossimIrect& boundingRect); bool next(ossimRefPtr& resultProjection, ossimIrect& resultingBounds, ossimString& resultingName)const; void reset(); /** * * @param tilingDistance Distance in the specified units. * @param unitType Currently only angular unit degrees, * and linear unit meters are supported. * If unitType is pixel unit then the * delta per unit will be set to 1. * */ void setTilingDistance(const ossimDpt& tilingDistance, ossimUnitType unitType); /** * This sets the pixel delta. The delta can either be TOTAL_PIXELS or * UNIT_PER_PIXEL. * * If the delta type is TOTAL_PIXELS then the unit per pixel is calculated * from the theTilingDistance. This is very useful when wanting to be on * even geographic boundaries and would like to have a fixed width and * height for * the pixels. Flight simulators use this tiling scheme for power of 2 * outputs. * * if the delta type is unit per pixel then the total pixels is computed * form the * theTilingDistance. This is useful when you might want whole number * GSD's and whole numbered tile boundaries. */ void setDelta(const ossimDpt& delta, ossimTilingDeltaType deltaType); /** * This sets the tilename mask. The key tokens that are supported are. * * %r% Replaces with the row number of the current tile * %c% Replaces with the column number of the current tile * %i% Replaces with the current tile id. * %or% Replaces with the origin of the row * %oc% Replaces with the origin of the col * %SRTM% Replaces all filenames with the SRTM file name convention * * * Examples: * tile%r%_%c% assume r = 0 and c = 100 then * this is replaced with tile0_100 * */ void setTileNameMask(const ossimString& mask); ossimString getTileNameMask()const; bool getRowCol(ossim_int64& row, ossim_int64& col, ossim_int64 tileId)const; bool getOrigin(ossimDpt& origin, ossim_int64 tileId)const; bool getOrigin(ossimDpt& origin, ossim_int64 row, ossim_int64 col)const; void setPaddingSizeInPixels(const ossimIpt& pizelOverlap); ossimDpt getDeltaPerPixel()const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual std::ostream& print(std::ostream& out) const; protected: /** * @return The tiling distance converted to either degrees or meters. */ void getConvertedTilingDistance(ossimDpt& pt) const; /** The size of a tile in theTilingDistanceUnitType. */ ossimDpt theTilingDistance; /** The unit type for "theDelta", and "theTilingDistance". */ ossimUnitType theTilingDistanceUnitType; /** * If (theDeltaType == ossimTilingDeltaType_TOTAL_PIXELS) then * this is the size of the tile in pixels like 1024 x 1024. * * If (theDeltaType == ossimTilingDeltaType_PER_PIXEL) then * this is the size of a single pixel like 1.0 meter. */ ossimDpt theDelta; /** @see theDelta */ ossimTilingDeltaType theDeltaType; /** * @brief If set tiling size is controlled by the desired output size in * bytes. Set by one of output_size_in_bytes, output_size_in_kilo_bytes, or * output_size_in_mega_bytes. Always stored in bytes. * * @note kilo_byte = 1024 X 1024, mega_byte = 1024 X 1024 X 1024. * * @note If set this relys on theNumberOfBands and theNumberOfBytesPerPixel * need to alse be set correctly. */ ossim_int64 theOutputSizeInBytes; /** * @brief Output number of bands. Needed to tile by output size in bytes. * * default = 1 * * @see theOutputSizeInBytes */ ossim_uint32 theNumberOfBands; /** * @brief Output number of bytes per pixel. * Needed to tile by output size in bytes. * * default = 1 * * @see theOutputSizeInBytes * * @note This bytes per single pixel, not all bands. */ ossim_uint32 theNumberOfBytesPerPixelPerBand; ossimDpt thePaddingSizeInPixels; mutable ossimRefPtr theMapProjection; ossimIrect theImageRect; ossimDrect theTilingRect; mutable ossim_int64 theTileId; ossim_int64 theTotalHorizontalTiles; ossim_int64 theTotalVerticalTiles; ossim_int64 theTotalTiles; ossimString theTileNameMask; /** * This flags the code to shift the tie point so that the edge of the pixel * falls on the tile boundary. default=false */ bool theEdgeToEdgeFlag; bool validate()const; bool isAngularUnit(ossimUnitType unitType)const; bool isLinearUnit(ossimUnitType unitType)const; void getTileName(ossimString& resultingName, ossim_int64 row, ossim_int64 col, ossim_int64 id)const; void clampGeographic(ossimDrect& rect)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimTilingPoly.h000066400000000000000000000045721352751253100234310ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // // Description: implementation for image generator // //************************************************************************* // $Id: ossimTilingPoly.h 2725 2011-06-15 18:13:07Z david.burken $ #ifndef ossimTilingPoly_HEADER #define ossimTilingPoly_HEADER 1 #include #include #include class OSSIM_DLL ossimTilingPoly : public ossimTilingRect { public: ossimTilingPoly(); virtual ~ossimTilingPoly(); virtual bool initialize(const ossimMapProjection& proj, const ossimIrect& boundingRect); virtual bool next(ossimRefPtr& resultProjection, ossimIrect& resultingBounds, ossimString& resultingName); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); bool useMbr() const; /** return true if exterior cut is initialized. */ bool hasExteriorCut() const; /** return true if interior cut is initialized. */ bool hasInteriorCut() const; ossimRefPtr& getExteriorCut(); ossimRefPtr& getInteriorCut(); bool isFeatureBoundingIntersect() const; protected: struct ossimShpFeature { ossimShpFeature(ossim_int32 fid, ossim_int32 polyType, std::vector polygon, std::vector multiPolys) :m_fid(fid), m_polyType(polyType), m_polygon(polygon), m_multiPolys(multiPolys) {} ossim_int32 m_fid; ossim_int32 m_polyType; std::vector m_polygon; std::vector m_multiPolys; }; bool parseShpFile(); bool nextFeature(); void setRect(); ossimFilename m_shpFilename; bool m_useMbr; ossim_float64 m_bufferDistance; ossimRefPtr m_exteriorCut; ossimRefPtr m_interiorCut; std::vector m_features; bool m_featureBoundingIntersect; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimTilingRect.h000066400000000000000000000037121352751253100233760ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // // Description: implementation for image generator // //************************************************************************* // $Id: ossimTilingRect.h 2725 2011-06-15 18:13:07Z david.burken $ #ifndef ossimTilingRect_HEADER #define ossimTilingRect_HEADER 1 #include #include #include #include class OSSIM_DLL ossimTilingRect : public ossimTiling { public: ossimTilingRect(); virtual ~ossimTilingRect(); virtual bool initialize(const ossimMapProjection& proj, const ossimIrect& boundingRect); virtual bool next(ossimRefPtr& resultProjection, ossimIrect& resultingBounds, ossimString& resultingName); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: bool initializeBase(const ossimMapProjection& proj, const ossimIrect& boundingRect, ossimDpt& convertedTilingDistance); void getConvertedDistance(ossimDpt& pt, ossimDpt inputDistance) const; ossimDpt getPaddingSize() const; bool m_clipToAoi; ossim_float64 m_lastWidth; ossim_float64 m_lastHeight; bool m_useOffset; ossimDpt m_offsetInPixels; ossimDpt m_tilingDistanceInPixels; ossimDpt m_tilinResolutionDistance; ossimUnitType m_tilingResolutionUnitType; ossimDpt m_fractionalPixelMisalignment; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimTopographicCorrectionFilter.h000066400000000000000000000166751352751253100270230ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimTopographicCorrectionFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimTopographicCorrectionFilter_HEADER #define ossimTopographicCorrectionFilter_HEADER #include #include #include #include #include #include class ossimImageData; class ossimImageSourceConnection; class ossimImageToPlaneNormalFilter; /*! * * class ossimTopographicCorrectionFilter * * This clas is used to execute terrain correction. I t requires 2 inputs * where the first input is a multi band data source to correct and the * second is elevation normals used in light incident calculations. * * A sample chain might look like: * * landsatHandler ---> Cache ---> renderer ---> cache --------------------------------------- * |--> Topo correction filter ---> Output * ortho mosaic of elevation data----> imageToPlaneNormals --> Cache ---> Renderer -->Cache -- * * the ossimImageToPlaneNormalsFilter is used to take a single band elevation source and compute normals at each post. I suggest that you * set the renderer to use a higher order convolution than just nearest neighbor, maybe Cubic. This way you have smoother interpolation * as you change zoom levels. * * * Correction Types: * * Cosine correction: In order for this to run it does not need any additional informat but the multi band source and * an normal calculation input. * * Cosine-C correction: In order for this to run it will need theC array populated for each band. It defaults * to 0 forcing a default Cosine correction to take place. * * Minnaert correction: In order for this to run it will need theK array populated for each band. The defaults should work pretty good * */ class OSSIMDLLEXPORT ossimTopographicCorrectionFilter : public ossimImageCombiner { public: enum ossimTopoCorrectionType { TOPO_CORRECTION_COSINE = 0, TOPO_CORRECTION_COSINE_C = 1, TOPO_CORRECTION_MINNAERT = 2 }; ossimTopographicCorrectionFilter(); ossimTopographicCorrectionFilter(ossimImageSource* colorSource, ossimImageSource* elevSource); ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); virtual ossim_uint32 getNumberOfOutputBands() const; virtual ossimScalarType getOutputScalarType() const; virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; virtual void getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const; virtual void getDecimationFactors(std::vector& decimations) const; virtual ossim_uint32 getNumberOfDecimationLevels()const; virtual double getAzimuthAngle()const; virtual double getElevationAngle()const; virtual void setAzimuthAngle(double angle); virtual void setElevationAngle(double angle); virtual void initialize(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; virtual void connectInputEvent(ossimConnectionEvent& event); virtual void disconnectInputEvent(ossimConnectionEvent& event); virtual void propertyEvent(ossimPropertyEvent& event); virtual void refreshEvent(ossimRefreshEvent& event); virtual ossimTopoCorrectionType getTopoCorrectionType()const; virtual void setTopoCorrectionType(ossimTopoCorrectionType topoType); const std::vector& getGainValues()const; void setGainValues(const std::vector& gainValues); const std::vector& getBiasValues()const; void setBiasValues(const std::vector& biasValues); const std::vector& getKValues()const; double getK(int idx)const; void setK(int idx, double value); void setKValues(const std::vector& kValues); double getC(int idx)const; void setC(int idx, double value); void setCValues(const std::vector& cValues); void computeLightDirection(); protected: virtual ~ossimTopographicCorrectionFilter(); virtual void allocate(); /*! * The result of the illumination equation is stored in * here. This is populated on each call to getTile. */ ossimRefPtr theTile; std::vector theBandMapping; // ossimImageToPlaneNormalFilter* theNormalFilter; // ossimScalarRemapper* theScalarRemapper; std::vector theC; std::vector theK; std::vector theBias; std::vector theGain; /*! * Used for the light vector computation. */ double theLightSourceElevationAngle; /*! * Used for the light vector computation. */ double theLightSourceAzimuthAngle; /*! * This is computed from the elevation and * azimuth angles of the light source. */ double theLightDirection[3]; double theJulianDay; mutable bool theCComputedFlag; ossimTopoCorrectionType theTopoCorrectionType; double theNdviLowTest; double theNdviHighTest; virtual void executeTopographicCorrection( ossimRefPtr& outputData, ossimRefPtr& colorData, ossimRefPtr& normalData); template void executeTopographicCorrectionTemplate( T dummy, ossimRefPtr& outputData, ossimRefPtr& colorData, ossimRefPtr& normalData); template void executeTopographicCorrectionMinnaertTemplate( T dummy, ossimRefPtr& outputData, ossimRefPtr& colorData, ossimRefPtr& normalData); // virtual void computeC(); // template // void addRegressionPointsTemplate(T, //dummy // std::vector& regressionPoints, // std::vector& cosineIBucketCount, // ossim_int32 maxCountPerBucket, // ossimImageData* colorData, // ossimImageData* normalData); template bool computeNdvi(T dummy, ossim_float64& result, ossim_uint32 offset, const std::vector& bands)const; void resizeArrays(ossim_uint32 newSize); bool setCCmputedFlag(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimTrimFilter.h000066400000000000000000000042121352751253100234070ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimTrimFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimTrimFilter_HEADER #define ossimTrimFilter_HEADER #include #include class ossimTrimFilter : public ossimImageSourceFilter { public: ossimTrimFilter(); virtual ossimIrect getBoundingRect(ossim_uint32 resLevel=0)const; virtual void getValidImageVertices(std::vector& validVertices, ossimVertexOrdering ordering=OSSIM_CLOCKWISE_ORDER, ossim_uint32 resLevel=0)const; ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); virtual void initialize(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); virtual ossimRefPtr getProperty( const ossimString& name)const; /** * Set property. * * @param property Property to set if property->getName() matches a * property name of this object. */ virtual void setProperty(ossimRefPtr property); /** * Adds this objects properties to the list. * * @param propertyNames Array to add to. * * @note This method does not clear propertyNames prior to adding it's * names. */ virtual void getPropertyNames(std::vector& propertyNames)const; protected: virtual ~ossimTrimFilter(); double theLeftPercent; double theRightPercent; double theTopPercent; double theBottomPercent; std::vector theValidVertices; ossimRefPtr theCutter; TYPE_DATA }; #endif /* #ifndef ossimTrimFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimTwoColorView.h000066400000000000000000000074621352751253100237430ustar00rootroot00000000000000//------------------------------------------------------------------- // License: MIT. See top level LICENSE.txt file. // // Author: Garrett Potts // //------------------------------------------------------------------- // $Id$ #ifndef ossimTwoColorView_HEADER #define ossimTwoColorView_HEADER 1 #include #include /** * This is a 2 color view of the input. It basically allows for a change detection and by default * will take the first input and map it to the blue channel and takes the second input and maps to * the red channel. The unused channel is mapped to a min pixel value. */ class OSSIM_DLL ossimTwoColorView : public ossimImageCombiner { public: /** * @brief Enumerations for mapping inputs to red, green and blue * output channels. */ enum ossimTwoColorMultiViewOutputSource { UNKNOWN = 0, MIN = 1, OLD = 2, NEW = 3 }; ossimTwoColorView(); virtual ossim_uint32 getNumberOfOutputBands() const; /** * @return the requested region of interest */ virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); ossimScalarType getOutputScalarType() const; double getNullPixelValue(ossim_uint32 band)const; double getMinPixelValue(ossim_uint32 band)const; double getMaxPixelValue(ossim_uint32 band)const; /** * @brief Sets which bands to use from inputs, and which inputs to use for * output red, green and blue channels. * * This method does no error checking as the inputs may or may not be set * prior to this call. ossimTwoColorView::initialize() will verify once * inputs are established. So if an input band is out of range band * 0 (first band) will be used. * * Callers should ensure initialize is called after this. * * @param oldInputBandIndex Zero based band index for old input. Default=0 * * * @param newInputBandIndex Zero based band index for new input. Default=0. * * @param redOutputSource default=OLD. Can be: * ossimTwoColorMultiViewOutputSource::OLD * ossimTwoColorMultiViewOutputSource::NEW * ossimTwoColorMultiViewOutputSource::MIN * * @param grnOutputSource default=NEW. Can be: * ossimTwoColorMultiViewOutputSource::OLD * ossimTwoColorMultiViewOutputSource::NEW * ossimTwoColorMultiViewOutputSource::MIN * * @param bluOutputSource default=NEW. Can be: * ossimTwoColorMultiViewOutputSource::OLD * ossimTwoColorMultiViewOutputSource::NEW * ossimTwoColorMultiViewOutputSource::MIN */ void setBandIndexMapping( ossim_uint32 oldInputBandIndex, ossim_uint32 newInputBandIndex, ossimTwoColorMultiViewOutputSource redOutputSource, ossimTwoColorMultiViewOutputSource grnOutputSource, ossimTwoColorMultiViewOutputSource bluOutputSource); virtual void initialize(); protected: void allocate(); void runAlgorithm(ossimImageData* newData, ossimImageData* oldData); void runNative8(ossimImageData* newData, ossimImageData* oldData); void runNorm(ossimImageData* newData, ossimImageData* oldData); bool m_byPassFlag; bool m_nativeFlag; ossimRefPtr m_twoColorTile; ossimRefPtr m_newInput; ossimRefPtr m_oldInput; ossim_uint32 m_newInputBandIndex; ossim_uint32 m_oldInputBandIndex; ossimTwoColorMultiViewOutputSource m_redSource; ossimTwoColorMultiViewOutputSource m_grnSource; ossimTwoColorMultiViewOutputSource m_bluSource; TYPE_DATA }; #endif /* #ifndef ossimTwoColorView_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimU11ImageData.h000066400000000000000000000135121352751253100234340ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration of ossimU16ImageData. Specialized image data object for // unsigned short data with an 11 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 2047.0 (2^11 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU11ImageData.h 16052 2009-12-08 22:20:40Z dburken $ #ifndef ossimU11ImageData_HEADER #define ossimU11ImageData_HEADER #include #include class OSSIMDLLEXPORT ossimU11ImageData : public ossimImageData { public: ossimU11ImageData(ossimSource* source, ossim_uint32 bands = 1); ossimU11ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height); ossimU11ImageData(const ossimU11ImageData &rhs); virtual ossimObject* dup()const; /*! * will fill the entire band with * the value. */ void fill(ossim_uint32 band, double value); bool isNull(ossim_uint32 offset)const; void setNull(ossim_uint32 offset); virtual ossimDataObjectStatus validate() const; /*! * will go to the band and offset and compute the * normalized float and return it back to the * caller through the result argument. */ virtual void getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float& result)const; /*! * This will assign to this object a normalized * value by unnormalizing to its native type. */ virtual void setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float input); /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedFloat(ossimImageData* result)const; /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedDouble(ossimImageData* result)const; /*! * Will take the normalized input and convert it * to this tile's data type. Example: if this * tile is of type UCHAR and its input is of type * NORALIZED_FLOAT it will unnormalize the data by * doing: * * minPix + normalizedInput*(maxPix-minPix) * * on a per band basis. */ virtual void unnormalizeInput(ossimImageData* normalizedInput); /*! * This will compute the average value for the band. */ virtual double computeAverageBandValue(ossim_uint32 bandNumber = 0); /*! * This will call the compute average band value and then * use that in the calculation of: * It will then do a SUM[(Mean - Actual)^2]/width*height. * * This is the average variance from the passed in * mean. Basically think of the mean as a completely * grey image and we would like to see how this * image varies from the passed in mean. */ virtual double computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber = 0); virtual void setValue(long x, long y, double color); /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(double* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(double* buf); /*! * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. */ virtual void copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const; virtual void copyTileToNormalizedBuffer(ossim_uint32 band, float* buf)const; /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(float* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(float* buf); /*! * Will copy the normalized buffer to this tiles * specified band. If band is out of range then nothing * is done and returns. */ virtual void copyNormalizedBufferToTile(ossim_uint32 band, double* buf); virtual void copyNormalizedBufferToTile(ossim_uint32 band, float* buf); /** @return The first non-null index of the normalized remap table. */ virtual ossim_float64 getMinNormalizedPix() const; protected: virtual ~ossimU11ImageData(); ossimU11ImageData(); private: static const ossimNormalizedU11RemapTable m_remapTable; TYPE_DATA }; inline ossim_float64 ossimU11ImageData::getMinNormalizedPix() const { return m_remapTable[1]; } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimU12ImageData.h000066400000000000000000000135121352751253100234350ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration of ossimU16ImageData. Specialized image data object for // unsigned short data with an 12 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 4095.0 (2^12 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU12ImageData.h 16052 2009-12-08 22:20:40Z dburken $ #ifndef ossimU12ImageData_HEADER #define ossimU12ImageData_HEADER #include #include class OSSIMDLLEXPORT ossimU12ImageData : public ossimImageData { public: ossimU12ImageData(ossimSource* source, ossim_uint32 bands = 1); ossimU12ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height); ossimU12ImageData(const ossimU12ImageData &rhs); virtual ossimObject* dup()const; /*! * will fill the entire band with * the value. */ void fill(ossim_uint32 band, double value); bool isNull(ossim_uint32 offset)const; void setNull(ossim_uint32 offset); virtual ossimDataObjectStatus validate() const; /*! * will go to the band and offset and compute the * normalized float and return it back to the * caller through the result argument. */ virtual void getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float& result)const; /*! * This will assign to this object a normalized * value by unnormalizing to its native type. */ virtual void setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float input); /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedFloat(ossimImageData* result)const; /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedDouble(ossimImageData* result)const; /*! * Will take the normalized input and convert it * to this tile's data type. Example: if this * tile is of type UCHAR and its input is of type * NORALIZED_FLOAT it will unnormalize the data by * doing: * * minPix + normalizedInput*(maxPix-minPix) * * on a per band basis. */ virtual void unnormalizeInput(ossimImageData* normalizedInput); /*! * This will compute the average value for the band. */ virtual double computeAverageBandValue(ossim_uint32 bandNumber = 0); /*! * This will call the compute average band value and then * use that in the calculation of: * It will then do a SUM[(Mean - Actual)^2]/width*height. * * This is the average variance from the passed in * mean. Basically think of the mean as a completely * grey image and we would like to see how this * image varies from the passed in mean. */ virtual double computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber = 0); virtual void setValue(long x, long y, double color); /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(double* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(double* buf); /*! * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. */ virtual void copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const; virtual void copyTileToNormalizedBuffer(ossim_uint32 band, float* buf)const; /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(float* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(float* buf); /*! * Will copy the normalized buffer to this tiles * specified band. If band is out of range then nothing * is done and returns. */ virtual void copyNormalizedBufferToTile(ossim_uint32 band, double* buf); virtual void copyNormalizedBufferToTile(ossim_uint32 band, float* buf); /** @return The first non-null index of the normalized remap table. */ virtual ossim_float64 getMinNormalizedPix() const; protected: virtual ~ossimU12ImageData(); ossimU12ImageData(); private: static const ossimNormalizedU12RemapTable m_remapTable; TYPE_DATA }; inline ossim_float64 ossimU12ImageData::getMinNormalizedPix() const { return m_remapTable[1]; } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimU13ImageData.h000066400000000000000000000135121352751253100234360ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration of ossimU16ImageData. Specialized image data object for // unsigned short data with an 13 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 8191.0 (2^13 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU13ImageData.h 16052 2009-12-08 22:20:40Z dburken $ #ifndef ossimU13ImageData_HEADER #define ossimU13ImageData_HEADER #include #include class OSSIMDLLEXPORT ossimU13ImageData : public ossimImageData { public: ossimU13ImageData(ossimSource* source, ossim_uint32 bands = 1); ossimU13ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height); ossimU13ImageData(const ossimU13ImageData &rhs); virtual ossimObject* dup()const; /*! * will fill the entire band with * the value. */ void fill(ossim_uint32 band, double value); bool isNull(ossim_uint32 offset)const; void setNull(ossim_uint32 offset); virtual ossimDataObjectStatus validate() const; /*! * will go to the band and offset and compute the * normalized float and return it back to the * caller through the result argument. */ virtual void getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float& result)const; /*! * This will assign to this object a normalized * value by unnormalizing to its native type. */ virtual void setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float input); /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedFloat(ossimImageData* result)const; /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedDouble(ossimImageData* result)const; /*! * Will take the normalized input and convert it * to this tile's data type. Example: if this * tile is of type UCHAR and its input is of type * NORALIZED_FLOAT it will unnormalize the data by * doing: * * minPix + normalizedInput*(maxPix-minPix) * * on a per band basis. */ virtual void unnormalizeInput(ossimImageData* normalizedInput); /*! * This will compute the average value for the band. */ virtual double computeAverageBandValue(ossim_uint32 bandNumber = 0); /*! * This will call the compute average band value and then * use that in the calculation of: * It will then do a SUM[(Mean - Actual)^2]/width*height. * * This is the average variance from the passed in * mean. Basically think of the mean as a completely * grey image and we would like to see how this * image varies from the passed in mean. */ virtual double computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber = 0); virtual void setValue(long x, long y, double color); /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(double* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(double* buf); /*! * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. */ virtual void copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const; virtual void copyTileToNormalizedBuffer(ossim_uint32 band, float* buf)const; /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(float* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(float* buf); /*! * Will copy the normalized buffer to this tiles * specified band. If band is out of range then nothing * is done and returns. */ virtual void copyNormalizedBufferToTile(ossim_uint32 band, double* buf); virtual void copyNormalizedBufferToTile(ossim_uint32 band, float* buf); /** @return The first non-null index of the normalized remap table. */ virtual ossim_float64 getMinNormalizedPix() const; protected: virtual ~ossimU13ImageData(); ossimU13ImageData(); private: static const ossimNormalizedU13RemapTable m_remapTable; TYPE_DATA }; inline ossim_float64 ossimU13ImageData::getMinNormalizedPix() const { return m_remapTable[1]; } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimU14ImageData.h000066400000000000000000000135131352751253100234400ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration of ossimU16ImageData. Specialized image data object for // unsigned short data with an 14 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 16383.0 (2^14 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU14ImageData.h 16052 2009-12-08 22:20:40Z dburken $ #ifndef ossimU14ImageData_HEADER #define ossimU14ImageData_HEADER #include #include class OSSIMDLLEXPORT ossimU14ImageData : public ossimImageData { public: ossimU14ImageData(ossimSource* source, ossim_uint32 bands = 1); ossimU14ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height); ossimU14ImageData(const ossimU14ImageData &rhs); virtual ossimObject* dup()const; /*! * will fill the entire band with * the value. */ void fill(ossim_uint32 band, double value); bool isNull(ossim_uint32 offset)const; void setNull(ossim_uint32 offset); virtual ossimDataObjectStatus validate() const; /*! * will go to the band and offset and compute the * normalized float and return it back to the * caller through the result argument. */ virtual void getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float& result)const; /*! * This will assign to this object a normalized * value by unnormalizing to its native type. */ virtual void setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float input); /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedFloat(ossimImageData* result)const; /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedDouble(ossimImageData* result)const; /*! * Will take the normalized input and convert it * to this tile's data type. Example: if this * tile is of type UCHAR and its input is of type * NORALIZED_FLOAT it will unnormalize the data by * doing: * * minPix + normalizedInput*(maxPix-minPix) * * on a per band basis. */ virtual void unnormalizeInput(ossimImageData* normalizedInput); /*! * This will compute the average value for the band. */ virtual double computeAverageBandValue(ossim_uint32 bandNumber = 0); /*! * This will call the compute average band value and then * use that in the calculation of: * It will then do a SUM[(Mean - Actual)^2]/width*height. * * This is the average variance from the passed in * mean. Basically think of the mean as a completely * grey image and we would like to see how this * image varies from the passed in mean. */ virtual double computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber = 0); virtual void setValue(long x, long y, double color); /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(double* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(double* buf); /*! * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. */ virtual void copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const; virtual void copyTileToNormalizedBuffer(ossim_uint32 band, float* buf)const; /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(float* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(float* buf); /*! * Will copy the normalized buffer to this tiles * specified band. If band is out of range then nothing * is done and returns. */ virtual void copyNormalizedBufferToTile(ossim_uint32 band, double* buf); virtual void copyNormalizedBufferToTile(ossim_uint32 band, float* buf); /** @return The first non-null index of the normalized remap table. */ virtual ossim_float64 getMinNormalizedPix() const; protected: virtual ~ossimU14ImageData(); ossimU14ImageData(); private: static const ossimNormalizedU14RemapTable m_remapTable; TYPE_DATA }; inline ossim_float64 ossimU14ImageData::getMinNormalizedPix() const { return m_remapTable[1]; } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimU15ImageData.h000066400000000000000000000135131352751253100234410ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration of ossimU16ImageData. Specialized image data object for // unsigned short data with an 15 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 32767.0 (2^15 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU15ImageData.h 16052 2009-12-08 22:20:40Z dburken $ #ifndef ossimU15ImageData_HEADER #define ossimU15ImageData_HEADER #include #include class OSSIMDLLEXPORT ossimU15ImageData : public ossimImageData { public: ossimU15ImageData(ossimSource* source, ossim_uint32 bands = 1); ossimU15ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height); ossimU15ImageData(const ossimU15ImageData &rhs); virtual ossimObject* dup()const; /*! * will fill the entire band with * the value. */ void fill(ossim_uint32 band, double value); bool isNull(ossim_uint32 offset)const; void setNull(ossim_uint32 offset); virtual ossimDataObjectStatus validate() const; /*! * will go to the band and offset and compute the * normalized float and return it back to the * caller through the result argument. */ virtual void getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float& result)const; /*! * This will assign to this object a normalized * value by unnormalizing to its native type. */ virtual void setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float input); /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedFloat(ossimImageData* result)const; /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedDouble(ossimImageData* result)const; /*! * Will take the normalized input and convert it * to this tile's data type. Example: if this * tile is of type UCHAR and its input is of type * NORALIZED_FLOAT it will unnormalize the data by * doing: * * minPix + normalizedInput*(maxPix-minPix) * * on a per band basis. */ virtual void unnormalizeInput(ossimImageData* normalizedInput); /*! * This will compute the average value for the band. */ virtual double computeAverageBandValue(ossim_uint32 bandNumber = 0); /*! * This will call the compute average band value and then * use that in the calculation of: * It will then do a SUM[(Mean - Actual)^2]/width*height. * * This is the average variance from the passed in * mean. Basically think of the mean as a completely * grey image and we would like to see how this * image varies from the passed in mean. */ virtual double computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber = 0); virtual void setValue(long x, long y, double color); /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(double* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(double* buf); /*! * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. */ virtual void copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const; virtual void copyTileToNormalizedBuffer(ossim_uint32 band, float* buf)const; /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(float* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(float* buf); /*! * Will copy the normalized buffer to this tiles * specified band. If band is out of range then nothing * is done and returns. */ virtual void copyNormalizedBufferToTile(ossim_uint32 band, double* buf); virtual void copyNormalizedBufferToTile(ossim_uint32 band, float* buf); /** @return The first non-null index of the normalized remap table. */ virtual ossim_float64 getMinNormalizedPix() const; protected: virtual ~ossimU15ImageData(); ossimU15ImageData(); private: static const ossimNormalizedU15RemapTable m_remapTable; TYPE_DATA }; inline ossim_float64 ossimU15ImageData::getMinNormalizedPix() const { return m_remapTable[1]; } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimU16ImageData.h000066400000000000000000000134411352751253100234420ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration of ossimU16ImageData. Specialized image data object for // unsigned short data. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 65536.0 (2^16 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU16ImageData.h 16052 2009-12-08 22:20:40Z dburken $ #ifndef ossimU16ImageData_HEADER #define ossimU16ImageData_HEADER #include #include class OSSIMDLLEXPORT ossimU16ImageData : public ossimImageData { public: ossimU16ImageData(ossimSource* source, ossim_uint32 bands = 1); ossimU16ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height); ossimU16ImageData(const ossimU16ImageData &rhs); /*! * Perform object duplication. */ virtual ossimObject* dup()const; /*! * will fill the entire band with * the value. */ void fill(ossim_uint32 band, double value); /*! * will fill all bands with the passed in * value. */ void fill(double value); virtual ossimDataObjectStatus validate() const; /*! * will go to the band and offset and compute the * normalized float and return it back to the * caller through the result argument. */ virtual void getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float& result)const; /*! * This will assign to this object a normalized * value by unnormalizing to its native type. */ virtual void setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float input); /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedFloat(ossimImageData* result)const; /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedDouble(ossimImageData* result)const; /*! * Will take the normalized input and convert it * to this tile's data type. Example: if this * tile is of type UCHAR and its input is of type * NORALIZED_FLOAT it will unnormalize the data by * doing: * * minPix + normalizedInput*(maxPix-minPix) * * on a per band basis. */ virtual void unnormalizeInput(ossimImageData* normalizedInput); /*! * This will compute the average value for the band. */ virtual double computeAverageBandValue(ossim_uint32 bandNumber = 0); /*! * This will call the compute average band value and then * use that in the calculation of: * It will then do a SUM[(Mean - Actual)^2]/width*height. * * This is the average variance from the passed in * mean. Basically think of the mean as a completely * grey image and we would like to see how this * image varies from the passed in mean. */ virtual double computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber = 0); virtual void setValue(long x, long y, double color); /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(double* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(double* buf); /*! * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. */ virtual void copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const; virtual void copyTileToNormalizedBuffer(ossim_uint32 band, float* buf)const; /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(float* buf) const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(float* buf); /*! * Will copy the normalized buffer to this tiles * specified band. If band is out of range then nothing * is done and returns. */ virtual void copyNormalizedBufferToTile(ossim_uint32 band, double* buf); virtual void copyNormalizedBufferToTile(ossim_uint32 band, float* buf); /** @return The first non-null index of the normalized remap table. */ virtual ossim_float64 getMinNormalizedPix() const; protected: virtual ~ossimU16ImageData(); ossimU16ImageData(); private: static const ossimNormalizedU16RemapTable m_remapTable; TYPE_DATA }; inline ossim_float64 ossimU16ImageData::getMinNormalizedPix() const { return m_remapTable[1]; } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimU8ImageData.h000066400000000000000000000125331352751253100233640ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class declaration of ossimU8ImageData. Specialized image data object for // unsigned char data. // // NOTE: This object is optimized for unsigned char data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 255.0 // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU8ImageData.h 16052 2009-12-08 22:20:40Z dburken $ #ifndef ossimU8ImageData_HEADER #define ossimU8ImageData_HEADER #include #include class OSSIMDLLEXPORT ossimU8ImageData : public ossimImageData { public: ossimU8ImageData(ossimSource* source=NULL, ossim_uint32 bands = 1); ossimU8ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height); ossimU8ImageData(const ossimU8ImageData& rhs) :ossimImageData(rhs) {} virtual ossimObject* dup()const; /*! * will fill the entire band with * the value. */ void fill(ossim_uint32 band, double value); void fill(double value); bool isNull(ossim_uint32 offset)const; void setNull(ossim_uint32 offset); virtual ossimDataObjectStatus validate() const; /*! * will go to the band and offset and compute the * normalized float and return it back to the * caller through the result argument. */ virtual void getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float& result)const; /*! * This will assign to this object a normalized * value by unnormalizing to its native type. */ virtual void setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float input); /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedFloat(ossimImageData* result)const; /*! * Will use the memory that you pass in to normalize * this data object. */ virtual void convertToNormalizedDouble(ossimImageData* result)const; /*! * Will take the normalized input and convert it * to this tile's data type. Example: if this * tile is of type UCHAR and its input is of type * NORALIZED_FLOAT it will unnormalize the data by * doing: * * minPix + normalizedInput*(maxPix-minPix) * * on a per band basis. */ virtual void unnormalizeInput(ossimImageData* normalizedInput); /*! * This will compute the average value for the band. */ virtual double computeAverageBandValue(ossim_uint32 bandNumber = 0); /*! * This will call the compute average band value and then * use that in the calculation of: * It will then do a SUM[(Mean - Actual)^2]/width*height. * * This is the average variance from the passed in * mean. Basically think of the mean as a completely * grey image and we would like to see how this * image varies from the passed in mean. */ virtual double computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber = 0); virtual void setValue(ossim_int32 x, ossim_int32 y, double color); /*! * Copies entire tile to buf passed in. Data put in buf is normalized. * The "buf" passed to method is assumed to be at least as big as: * "getSize() * sizeof(double)" */ virtual void copyTileToNormalizedBuffer(double* buf) const; virtual void copyTileToNormalizedBuffer(float* buf) const; /*! * Will copy this tiles specified band number to the normalized buffer. * if the band is out of range then nothing is done and returns. */ virtual void copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const; virtual void copyTileToNormalizedBuffer(ossim_uint32 band, float* buf)const; /*! * Copies buf passed in to tile. Data is unnormalized to the tile's * scalar type. * The "buf" passed to method is assumed to be at least as big as the tiles: * "getSize() * sizeof(double)" */ virtual void copyNormalizedBufferToTile(double* buf); virtual void copyNormalizedBufferToTile(float* buf); /*! * Will copy the normalized buffer to this tiles * specified band. If band is out of range then nothing * is done and returns. */ virtual void copyNormalizedBufferToTile(ossim_uint32 band, double* buf); virtual void copyNormalizedBufferToTile(ossim_uint32 band, float* buf); /** @return The first non-null index of the normalized remap table. */ virtual ossim_float64 getMinNormalizedPix() const; protected: virtual ~ossimU8ImageData(); private: static const ossimNormalizedU8RemapTable m_remapTable; TYPE_DATA }; inline ossim_float64 ossimU8ImageData::getMinNormalizedPix() const { return m_remapTable[1]; } #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimUsgsDemTileSource.h000066400000000000000000000146721352751253100247070ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration of ossimUsgsDemTileSource. // The ossimUsgsDemTileSource class is derived from ossimImageHandler and // is intended to be an image handler for USGS dem files. // //******************************************************************** // $Id: ossimUsgsDemTileSource.h 19640 2011-05-25 15:58:00Z oscarkramer $ #ifndef ossimUsgsDemTileSource_HEADER #define ossimUsgsDemTileSource_HEADER #include class ossimImageData; class ossimDemGrid; class OSSIM_DLL ossimUsgsDemTileSource : public ossimImageHandler { public: ossimUsgsDemTileSource(); virtual ossimString getShortName() const; virtual ossimString getLongName() const; /** * Returns true if the "theImageFile can be opened. * * If the extension is not equal to ".dem" this will attempt to look for * an ".omd" file with the keyword pair "dem_type: usgs_dem" in it. * * Optionally users can change the scalar type from signed 16 bit to * float with the keyword pair "scalar_type: ossim_float32" */ virtual bool open(); virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); /** * Method to get a tile. * * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); /** * Returns the number of bands in the image. * Satisfies pure virtual requirement from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; virtual ossim_uint32 getNumberOfOutputBands() const; /** * Returns the number of lines in the image. * Satisfies pure virtual requirement from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; /** * Returns the number of samples in the image. * Satisfies pure virtual requirement from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; /** * Returns the zero based image rectangle for the reduced resolution data * set (rrds) passed in. Note that rrds 0 is the highest resolution rrds. */ virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. * * Keywords picked up by this method: * dem_type: usgs_dem * scalar_type: ossim_sint16 (default) * or * scalar_type: ossim_float32 */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /** * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /** * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /** * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; virtual bool isOpen()const; /** * Override base-class method to make sure the internal geometry is explored before extending. */ virtual ossimRefPtr getImageGeometry(); protected: /** * @brief Initializes theGeometry from USGS DEM header. * * This is called by base ossimImageHandler::getImageGeometry if * theGeometry is not set. External callers should not go through this * method but call "getImageGeometry" instead for efficiency reasons. * * @return Pointer to geometry or null if header not found. */ virtual ossimRefPtr getInternalImageGeometry() const; virtual ~ossimUsgsDemTileSource(); // Disallow operator= and copy constrution... const ossimUsgsDemTileSource& operator=(const ossimUsgsDemTileSource& rhs); ossimUsgsDemTileSource(const ossimUsgsDemTileSource&); /** * Returns true on success, false on error. */ template bool fillBuffer(T, // dummy template variable const ossimIrect& tile_rect, const ossimIrect& clip_rect, ossimImageData* tile); void gatherStatistics(); ossimDemGrid* theDem; ossimRefPtr theTile; ossim_float64 theNullValue; ossim_float64 theMinHeight; ossim_float64 theMaxHeight; bool theFeetFlag; // elevation units = feet bool theIsDemFlag; /** * This can be either OSSIM_SINT16 or OSSIM_FLOAT32. Default = OSSIM_SINT16 * Can be changed via ".omd" file keyword: */ ossimScalarType theScalarType; TYPE_DATA }; #endif // #ifndef ossimUsgsDemTileSource_HEADER ossim-Miami-2.9.1/include/ossim/imaging/ossimValueAssignImageSourceFilter.h000066400000000000000000000061741352751253100270520ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimValueAssignImageSourceFilter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimValueAssignImageSourceFilter_HEADER #define ossimValueAssignImageSourceFilter_HEADER #include /** * This allows one to assign a value to a group of bands. It will test * for equality band separate or as group. For example: * * if we are testing as a group then the assign will not happen unless * all values equal theInputValue array * * inputValue = <1, 2, 3> * outputValue = <100, 100, 100> * * then it will only convert to 100, 100, 100 if the input equals all * values of the output. * * input <1, 55, 3> would become <1, 55, 3> * input <1, 2, 3> would become <100, 100, 100> * * Now for band separate it means you want to change on a per band and * not as a group. For example: * * inputValue = <1, 2, 3> * outputValue = <100, 100, 100> * * input <1, 55, 3> would become <100, 55, 100> * */ class OSSIMDLLEXPORT ossimValueAssignImageSourceFilter : public ossimImageSourceFilter { public: enum ossimValueAssignType { ossimValueAssignType_SEPARATE = 1, ossimValueAssignType_GROUP = 2 }; ossimValueAssignImageSourceFilter(ossimObject* owner=NULL); virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); void setInputOutputValues(const std::vector& inputValues, const std::vector& outputValues); const std::vector& getInputValues()const; const std::vector& getOutputValues()const; ossimValueAssignType getValueAssignType()const; void setValueAssignType(ossimValueAssignType type); virtual void initialize(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); protected: virtual ~ossimValueAssignImageSourceFilter(); /** * Called on first getTile, will initialize all data needed. */ void allocate(); std::vector theInputValueArray; std::vector theOutputValueArray; ossimValueAssignType theAssignType; ossimRefPtr theTile; void validateArrays(); template void executeAssign(T, ossimRefPtr& data); template void executeAssignSeparate(T, ossimRefPtr& data); template void executeAssignGroup(T, ossimRefPtr& data); TYPE_DATA }; #endif /* #ifndef ossimValueAssignImageSourceFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimVectorRenderer.h000066400000000000000000000070041352751253100242610ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Abstract class for rendering vector data. Derived classes should implement // the "rasterizeVectorData" data method. // //******************************************************************* // $Id: ossimVectorRenderer.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimVectorRenderer_HEADER #define ossimVectorRenderer_HEADER #include #include #include class ossimImageViewTransform; class ossimImageData; class ossimVectorRenderer : public ossimImageSourceFilter { public: ossimVectorRenderer(); ossimVectorRenderer(ossimImageSource* inputSource, ossimImageViewTransform *transform = NULL); /** * Renders the vector data to a data object. The area which is * imaged is the area of interest. The scale is determined by the output * view projection of the ImageViewTransform. */ virtual ossimImageData* renderVectorData() const = 0; /** * Returns vector of ossimDpt3d points representing the data object at * the index passed in. Implementors should set an error and return an * empty vector if the index is out of range. */ virtual std::vector getObject(ossim_uint32 index) const = 0; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Sets the ImageViewTransform to be used for converting vector data. */ virtual void setImageViewTransform(ossimImageViewTransform* transform); /** * Sets the area of interest. This will be used by the renderVectorData. */ virtual void setAreaOfInterest(const ossimDrect& aoi); /** * Returns the current area of interest as an ossimDrect. */ virtual ossimDrect getAreaOfInterest() const; /** * Returns the full bounding rectangle of current vector data loaded. */ virtual ossimDrect getBoundingRect(long resLevel=0)const; /** * Returns the number of vector objects in the area of interest. */ virtual ossim_int32 getNumberOfAoiObjects() const; /** * Returns the total number of vector objects in the full bounding * rectangle. */ virtual ossim_int32 getNumberOfObjects() const; protected: virtual ~ossimVectorRenderer(); /** * Sets the bounding rectangle of current vector data loaded. */ virtual void setBoundingRect(ossimDrect& rect); /** * Sets the number of vector objects in the area of interest. */ virtual void setNumberOfAoiObjects(ossim_int32 number_of_objects); /** * Sets the number of vector objects in the full bounding rectangle. */ virtual void setNumberOfObjects(ossim_int32 number_of_objects); private: ossimImageViewTransform* theImageViewTransform; ossimDrect theBoundingRect; ossimDrect theAreaOfInterest; ossim_int32 theNumberOfAoiObjects; ossim_int32 theNumberOfObjects; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimVertexExtractor.h000066400000000000000000000105521352751253100245030ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken (dburken@imagelinks.com) // //************************************************************************* // $Id: ossimVertexExtractor.h 17207 2010-04-25 23:21:14Z dburken $ #ifndef ossimVertexExtractor_HEADER #define ossimVertexExtractor_HEADER #include #include #include #include #include #include #include class ossimImageSource; //! Class ossimVertexExtractor /*! * Class designed to scan the area of interest and detect the valid vertices * of non null image data. */ class OSSIMDLLEXPORT ossimVertexExtractor : public ossimOutputSource, public ossimProcessInterface { public: ossimVertexExtractor(ossimImageSource* inputSource=NULL); virtual ossimObject* getObject() { return this; } virtual const ossimObject* getObject()const { return this; } /*! * Sets the area of interest in the source to extract the vertices from. * @param rect ossimIrec representing source area of interest. */ void setAreaOfInterest(const ossimIrect& rect); /*! * Sets the name of the output keyword list file which the vertices will * be dumped to. * @param filename ossimFilename representing the output file. * * Note: * - If "theFileStream" is open it will be closed. */ virtual void setOutputName(const ossimString& filename); /*! * Returns true if "theFileStream" is open, false if not. */ virtual bool isOpen() const; /*! * Opens "theFilename" for output. * Returns true on success, false on error. * Notes: * - If the file was previously open then it will close it and re-opens the * file. * - Returns false if "theFilename" has not been set. */ virtual bool open(); /*! * Closes "theFileStream". */ virtual void close(); /*! * Calls protected methods scanForEdges, extractVertices, and * writeVertices. Will error out if "theFilename" or "theAreaOfInterest * has not been set or "theFilename" could not be opened. */ virtual bool execute(); virtual ossimObject* getObjectInterface() { return this; } virtual ossimListenerManager* getListenerManagerInterface() { return this; } virtual void setPercentComplete(double percentComplete) { ossimProcessInterface::setPercentComplete(percentComplete); ossimProcessProgressEvent event(this, percentComplete); fireEvent(event); } bool canConnectMyInputTo(ossim_int32 /* inputIndex */, const ossimConnectableObject* object)const { return (object&& PTR_CAST(ossimImageSource, object)); } const std::vector& getVertices() const { return theVertice; } protected: virtual ~ossimVertexExtractor(); /*! * Walks each line from left and right side detecting first non null pixel. * Returns true on success, false on error. */ bool scanForEdges(); /*! * Extracts the vertices of the source. Uses "theLeftEdge" and * "theRightEdge" data members. * Returns true on success, false on error. */ bool extractVertices(); template void getMinAndIndex(T1* start, T1* end, T1& minValue, ossim_int32& offsetFromStart); template void getMaxAndIndex(T2* start, T2* end, T2& maxValue, ossim_int32& offsetFromStart); /*! * Writes the result to the output file (theFilename). * Returns true on success, false on error. */ bool writeVertices(); ossimIrect theAreaOfInterest; ossimFilename theFilename; std::ofstream theFileStream; std::vector theVertice; std::vector theLeftEdge; std::vector theRightEdge; //! Disallow copy constructor and operator= ossimVertexExtractor(const ossimVertexExtractor&) : theLeftEdge(0), theRightEdge(0) {} const ossimVertexExtractor& operator=(const ossimVertexExtractor& rhs) {return rhs;} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimVpfAnnotationCoverageInfo.h000066400000000000000000000037301352751253100264100ustar00rootroot00000000000000//************************************************************************* // Copyright (C) 2004 Intelligence Data Systems, Inc. All rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************** // $Id: ossimVpfAnnotationCoverageInfo.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimVpfAnnotationCoverageInfo_HEADER #define ossimVpfAnnotationCoverageInfo_HEADER #include #include class ossimVpfLibrary; class ossimRgbImage; class ossimVpfAnnotationCoverageInfo { public: ossimVpfAnnotationCoverageInfo(const ossimString& name="") :theName(name) { } virtual ~ossimVpfAnnotationCoverageInfo() { deleteAllFeatures(); } bool hasRenderableFeature()const; void getEnabledFeatures(std::vector& result); void getAllFeatures(std::vector& result); void transform(ossimImageGeometry* geom); ossimIrect getBoundingProjectedRect()const; void buildCoverage(); void buildCoverage(const ossimString& feature); void setName(const ossimString& name) { theName = name; } ossimString getName()const { return theName; } void setLibrary(ossimVpfLibrary* library) { theLibrary = library; } ossimVpfLibrary* getLibrary() { return theLibrary; } const ossimVpfLibrary* getLibrary()const { return theLibrary; } void drawAnnotations(ossimRgbImage* tile); void deleteAllFeatures(); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: ossimString theName; /*! * Not owned. */ ossimVpfLibrary* theLibrary; std::vector theFeatureInfoArray; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimVpfAnnotationFeatureInfo.h000066400000000000000000000144521352751253100262530ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimVpfAnnotationFeatureInfo.h 19636 2011-05-24 16:48:45Z gpotts $ #ifndef ossimVpfAnnotationFeatureInfo_HEADER #define ossimVpfAnnotationFeatureInfo_HEADER #include #include #include #include #include #include #include class ossimGeoAnnotationObject; class ossimVpfCoverage; class ossimVpfFeatureClassSchema; class ossimPolyLine; class OSSIMDLLEXPORT ossimVpfAnnotationFeatureInfo : public ossimObject { public: enum ossimVpfAnnotationFeatureType { ossimVpfAnnotationFeatureType_UNKNOWN = 0, ossimVpfAnnotationFeatureType_POINT = 1, ossimVpfAnnotationFeatureType_LINE = 2, ossimVpfAnnotationFeatureType_POLYGON = 3, ossimVpfAnnotationFeatureType_TEXT = 4, }; ossimVpfAnnotationFeatureInfo(const ossimString& featureName = "", const ossimRgbVector& penColor = ossimRgbVector(255,255,255), const ossimRgbVector& brushColor = ossimRgbVector(255,255,255), const ossimDpt& pointRadius=ossimDpt(1,1), int thickness=0, bool enabledFlag = true); ~ossimVpfAnnotationFeatureInfo(); void setCoverage(const ossimVpfCoverage& coverage) { theCoverage = coverage; } const ossimVpfCoverage& getCoverage()const { return theCoverage; } ossimVpfCoverage& getCoverage() { return theCoverage; } void setColor(const ossimRgbVector& color) { setPenColor(color); setBrushColor(color); } void setPenColor(const ossimRgbVector& penColor) { thePenColor = penColor; } ossimRgbVector getPenColor()const { return thePenColor; } void setBrushColor(const ossimRgbVector& brushColor) { theBrushColor = brushColor; } ossimRgbVector getBrushColor()const { return theBrushColor; } void setFillEnabledFlag(bool flag) { theFillEnabledFlag = flag; } bool getFillEnabledFlag()const { return theFillEnabledFlag; } void setEnabledFlag(bool flag); bool getEnabledFlag()const { return theEnabledFlag; } void setThickness(int thickness) { theThickness = thickness; } int getThickness()const { return theThickness; } void setName(const ossimString& name) { theName = name; } const ossimString& getName()const { return theName; } bool isPoint()const { return (theFeatureType == ossimVpfAnnotationFeatureType_POINT); } bool isLine()const { return (theFeatureType == ossimVpfAnnotationFeatureType_LINE); } bool isPolygon()const { return (theFeatureType == ossimVpfAnnotationFeatureType_POLYGON); } bool isText()const { return (theFeatureType == ossimVpfAnnotationFeatureType_TEXT); } void getFontInformation(ossimFontInformation& fontInfo)const { fontInfo = theFontInformation; } void setFontInformation(const ossimFontInformation& fontInfo) { theFontInformation = fontInfo; } void setPointRadius(const ossimDpt& radius) { thePointRadius = radius; } ossimDpt getPointRadius()const { return thePointRadius; } void setDrawingFeaturesToAnnotation(); ossimIrect getBoundingProjectedRect()const; void transform(ossimImageGeometry* proj); void buildFeature(); void deleteAllObjects(); void drawAnnotations(ossimRgbImage* tile); bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); ossimString getFeatureTypeAsString()const; ossimVpfAnnotationFeatureType getFeatureTypeFromString(const ossimString& featureType)const; private: void readAttributes(ossimPolyLine& polyLine, ossimVpfTable& table, int row); void readAttributes(ossimGeoPolygon& polygon, ossimVpfTable& table, int row); protected: ossimString theName; ossimString theDescription; ossimRgbVector thePenColor; ossimRgbVector theBrushColor; ossimVpfCoverage theCoverage; ossimDpt thePointRadius; int theThickness; bool theFillEnabledFlag; bool theEnabledFlag; ossimVpfAnnotationFeatureType theFeatureType; ossimFontInformation theFontInformation; std::vector > theAnnotationArray; void buildTxtFeature(const ossimFilename& table, const ossimString& tableKey, const ossimFilename& primitive, const ossimString& primitiveKey); void buildEdgFeature(const ossimFilename& table, const ossimString& tableKey, const ossimFilename& primitive, const ossimString& primitiveKey); void buildPointFeature(const ossimString& primitiveName, const ossimFilename& table, const ossimString& tableKey, const ossimFilename& primitive, const ossimString& primitiveKey); void buildFaceFeature(const ossimFilename& table, const ossimString& tableKey, const ossimFilename& primitive, const ossimString& primitiveKey); void readEdge(ossimPolyLine& polyLine, int rowNumber, int colPosition, ossimVpfTable& edgeTable); int readTableCellAsInt (int rowNumber, // should replace calls to readRngId, readStartEdgeId with this int colNumber, ossimVpfTable& table); int readRngId(int rowNumber, int colNumber, ossimVpfTable& faceTable); int readStartEdgeId(int rowNumber, int colNumber, ossimVpfTable& rngTable); void readGeoPolygon(ossimGeoPolygon& polygon, int faceId, int startEdgeId, ossimVpfTable& edgTable); ossimDpt* getXy(vpf_table_type table, row_type row, ossim_int32 pos, ossim_int32* count); int getEdgeKeyId (vpf_table_type& table, row_type& row, int col); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimVpfAnnotationLibraryInfo.h000066400000000000000000000026051352751253100262610ustar00rootroot00000000000000#ifndef ossimVpfAnnotationLibraryInfo_HEADER #define ossimVpfAnnotationLibraryInfo_HEADER #include #include #include class ossimVpfDatabase; class ossimRgbImage; class ossimVpfAnnotationFeatureInfo; class OSSIMDLLEXPORT ossimVpfAnnotationLibraryInfo { public: ossimVpfAnnotationLibraryInfo(const ossimString& libraryName = "", bool enabledFlag=true); virtual ~ossimVpfAnnotationLibraryInfo(); bool getEnabledFlag()const; void setEnabledFlag(bool flag); const ossimString& getName()const; void setName(const ossimString& libraryName); void setDatabase(ossimVpfDatabase* database); ossimVpfDatabase* getDatabase(); ossimIrect getBoundingProjectedRect()const; void transform(ossimImageGeometry* geom); void buildLibrary(); void buildLibrary(const ossimString& coverageName, const ossimString& feature); void deleteAllCoverage(); void drawAnnotations(ossimRgbImage* tile); void getAllFeatures(std::vector& features); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: ossimString theName; bool theEnabledFlag; ossimVpfDatabase* theDatabase; std::vector theCoverageLayerList; }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimVpfAnnotationSource.h000066400000000000000000000030461352751253100253010ustar00rootroot00000000000000#ifndef ossimVpfAnnotationSource_HEADER #define ossimVpfAnnotationSource_HEADER #include #include #include #include #include #include class ossimVpfAnnotationFeatureInfo; class ossimVpfAnnotationSource : public ossimGeoAnnotationSource { public: ossimVpfAnnotationSource(); virtual bool open(); virtual bool open(const ossimFilename& file); virtual bool isOpen()const; virtual void close(); virtual ossimFilename getFilename()const; virtual void computeBoundingRect(); virtual void transformObjects(ossimImageGeometry* geom=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); virtual void drawAnnotations(ossimRefPtr tile); virtual void getAllFeatures(std::vector& features); virtual void setAllFeatures(const std::vector& features); protected: virtual ~ossimVpfAnnotationSource(); ossimVpfDatabase theDatabase; ossimFilename theFilename; std::vector theLibraryInfo; std::vector theFeatureList; void deleteAllLibraries(); bool openDatabase(const ossimFilename& file); }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimVpfTileSource.h000066400000000000000000000123441352751253100240650ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (C) 2004 Garrett Potts, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // $Id: ossimVpfTileSource.h 17932 2010-08-19 20:34:35Z dburken $ //---------------------------------------------------------------------------- #ifndef ossimVpfTileSource_HEADER #define ossimVpfTileSource_HEADER #include #include #include #include class OSSIMDLLEXPORT ossimVpfTileSource : public ossimImageHandler, public ossimViewInterface { public: ossimVpfTileSource(); virtual void close(); /** * @return Returns true on success, false on error. * * @note This method relies on the data member ossimImageData::theImageFile * being set. Callers should do a "setFilename" prior to calling this * method or use the ossimImageHandler::open that takes a file name and an * entry index. */ virtual bool open(); /*! * Returns a pointer to a tile given an origin representing the upper * left corner of the tile to grab from the image. * Satisfies pure virtual from TileSource class. */ virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); /*! * Returns the number of bands in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfInputBands() const; /*! * Returns the number of bands in a tile returned from this TileSource. * Note: we are supporting sources that can have multiple data objects. * If you want to know the scalar type of an object you can pass in the */ virtual ossim_uint32 getNumberOfOutputBands() const; /*! * Returns the number of bands in the image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfLines(ossim_uint32 reduced_res_level = 0) const; /*! * Returns the number of bands available from an image. * Satisfies pure virtual from ImageHandler class. */ virtual ossim_uint32 getNumberOfSamples(ossim_uint32 reduced_res_level = 0) const; /*! * Returns the number of reduced resolution data sets (rrds). * Note: The full res image is counted as a data set so an image with no * reduced resolution data set will have a count of one. */ virtual ossim_uint32 getNumberOfDecimationLevels() const; /*! * Returns the zero based image rectangle for the reduced resolution data * set (rrds) passed in. Note that rrds 0 is the highest resolution rrds. */ virtual ossimIrect getImageRectangle(ossim_uint32 reduced_res_level = 0) const; /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix); //! Returns the image geometry object associated with this tile source or NULL if non defined. virtual ossimRefPtr getImageGeometry(); /*! * Returns the output pixel type of the tile source. */ virtual ossimScalarType getOutputScalarType() const; /*! * Returns the width of the output tile. */ virtual ossim_uint32 getTileWidth() const; /*! * Returns the height of the output tile. */ virtual ossim_uint32 getTileHeight() const; /*! * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileWidth() const; /*! * Returns the tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ virtual ossim_uint32 getImageTileHeight() const; virtual bool isOpen()const; virtual double getNullPixelValue(ossim_uint32 band=0)const; virtual double getMinPixelValue(ossim_uint32 band=0)const; virtual double getMaxPixelValue(ossim_uint32 band=0)const; virtual ossimObject* getView(); virtual const ossimObject* getView()const; virtual bool setView(ossimObject* baseObject); void getAllFeatures(std::vector& featureList); void setAllFeatures(std::vector& featureList); void transformObjects(); void computeBoundingRect(); protected: virtual ~ossimVpfTileSource(); ossimRefPtr m_AnnotationSource; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/imaging/ossimWatermarkFilter.h000066400000000000000000000232741352751253100244420ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class declaration of ossimWatermarkFilter. // Applies an image or watermark to image. Positioning is based on mode. // Density is base on alpha weight. // //---------------------------------------------------------------------------- // $Id: ossimWatermarkFilter.h 16276 2010-01-06 01:54:47Z gpotts $ #ifndef ossimWatermarkFilter_HEADER #define ossimWatermarkFilter_HEADER #include #include #include #include #include /** * class ossimWatermarkFilter * Applies an image or watermark to image. * Positioning is based on mode. * Density is base on alpha weight. */ class OSSIMDLLEXPORT ossimWatermarkFilter : public ossimImageSourceFilter { public: enum WatermarkMode { UPPER_LEFT = 0, UPPER_CENTER = 1, UPPER_RIGHT = 2, CENTER = 3, LOWER_LEFT = 4, LOWER_CENTER = 5, LOWER_RIGHT = 6, UNIFORM_DENSE = 7, UNIFORM_SPARSE = 8, END = 9 //< Number of modes. }; /** contructor */ ossimWatermarkFilter(); /** @return Short name of filter. */ virtual ossimString getShortName() const; /** @return Long name of filter. */ virtual ossimString getLongName() const; /** @return Descriptive name of filter. */ virtual ossimString getDescription() const; /** * @param tile_rect Rectangle to fill tile with. * * @param resLevel Reduced resolution level to grab from. * * @return ossimRefPtr This is tile that was filled with * tile_rect. * * @note Callers should check the ossimRefPtr::valid method. * The internal pointer of the ossimRefPtr can be * null if the tile_rect did not intersect the input connection's * bounding rectangle. */ virtual ossimRefPtr getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel=0); /** * Initializes state of the object from the input connection. */ virtual void initialize(); /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. * * Keywords picked saved by saveState * * filename: my_colormap_file.jpg * * weight: .25 * * watermark_mode: upper_left */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of the object from a keyword * list. * * @param kwl Keyword list to initialize from. * * @param prefix Usually something like: "object1." * * @return This method will alway return true as it is intended to be * used in conjuction with the set methods. * * Keywords picked up by loadState: * * filename: my_colormap_file.jpg * * weight: .25 * * watermark_mode: upper_left */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @param The property to get as a string like "watermark_mode". * * @return ossimRefPt holding pointer to ossimProperty * matching string or null pointer if string does not match. * * @note Internal pointer can be null so callers should check prior to * accessing like: * ossimRefPtr p = myFilter->getProperty(ossimString("foo")); * if (p.valid() == NULL) * { * some_error; * } */ virtual ossimRefPtr getProperty( const ossimString& name)const; /** * Set property. * * @param property Property to set if property->getName() matches a * property name of this object. */ virtual void setProperty(ossimRefPtr property); /** * Adds this objects properties to the list. * * @param propertyNames Array to add to. * * @note This method does not clear propertyNames prior to adding it's * names. */ virtual void getPropertyNames(std::vector& propertyNames)const; /** * @param list List initialized with watermark mode strings. * * @note This method clears the "list" prior to stuffing. */ void getModeList(std::vector& list) const; /** @return theMode */ ossimWatermarkFilter::WatermarkMode getMode() const; /** @return theMode as a string like "upper_left". */ ossimString getModeString() const; /** * Sets theFilename to file. * * @param file The watermark image file. */ void setFilename(const ossimFilename& file); /** * Sets the filter mode. * * @param mode String representing mode. */ void setMode(const ossimString& mode); /** * Sets the weight. * * @param weight Weight to use for watermark pixels normalize between * 0.0 and 1.0. */ void setWeight(ossim_float64 weight); /** * Print method. Called by: friend operator<< * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; protected: /** destructor */ virtual ~ossimWatermarkFilter(); /** * Allocates / recomputes things that are needed. Clears theDirtyFlag * by setting it to false on success. * * @return true on success, false on error. */ bool allocate(); /** * Attempts to open "theFilename". This will load "theWatermark" with * the image converting it to the scalar type of the input connection. * * @return true on success, false if no image handler is found for the * image or theInputConnection has not been established. */ bool openWatermarkFile(); // void verifyEnable(); /** * Writes watermark(s) to theTile. * Performs theTile->validate() at the end if theTile was touched. */ template void fill(T dummy); /** * Computes the bounding rectangles. These are the rectangles in image * space of the input connection to paint the watermark(s) on. The start of * each rectangle will be the start of where "theWatermark" is painted. */ void getIntersectingRects(std::vector& rects); /** * Addes upper left watermark rectangle to rects if it intersects * theTile rect clipped to input bounding rect. * * @param rects Array to add rect to. */ void getUpperLeftRect(std::vector& rects); /** * Addes upper center watermark rectangle to rects if it intersects * theTile rect clipped to input bounding rect. * * @param rects Array to add rect to. */ void getUpperCenterRect(std::vector& rects); /** * Addes upper right watermark rectangle to rects if it intersects * theTile rect clipped to input bounding rect. * * @param rects Array to add rect to. */ void getUpperRightRect(std::vector& rects); /** * Addes center watermark rectangle to rects if it intersects * theTile rect clipped to input bounding rect. * * @param rects Array to add rect to. */ void getCenterRect(std::vector& rects); /** * Addes lower left watermark rectangle to rects if it intersects * theTile rect clipped to input bounding rect. * * @param rects Array to add rect to. */ void getLowerLeftRect(std::vector& rects); /** * Addes lower center watermark rectangle to rects if it intersects * theTile rect clipped to input bounding rect. * * @param rects Array to add rect to. */ void getLowerCenterRect(std::vector& rects); /** * Addes lower right watermark rectangle to rects if it intersects * theTile rect clipped to input bounding rect. * * @param rects Array to add rect to. */ void getLowerRightRect(std::vector& rects); /** * Addes rectangles to rects if it intersects * theTile rect clipped to input bounding rect. * * This will repeat the watermark throughout the input bounding rect. * * @param rects Array to add rect to. */ void getUniformDenseRects(std::vector& rects); /** * Addes rectangles to rects if it intersects * theTile rect clipped to input bounding rect. * * This will repeat the watermark sparsly throughout the input bounding * rect. * * @param rects Array to add rect to. */ void getUniformSparceRects(std::vector& rects); /** File name of watermark image. */ ossimFilename theFilename; /** Normalized between 0.0 and 1.0. */ ossim_float64 theWatermarkWeight; /** The returned tile. */ ossimRefPtr theTile; /** Tile storage for watermark image. */ ossimRefPtr theWatermark; /** The number of watermark bands. */ ossim_uint32 theWatermarkNumberOfBands; /** The filter mode. */ WatermarkMode theMode; /** The bounding rectangle of the input connection. */ ossimIrect theInputBoundingRect; /** The number of input bands. */ ossim_uint32 theInputNumberOfBands; /** The input scalar type. */ ossimScalarType theInputScalarType; /** * Set in the initialize method this instructs the getTile that something * has changes and it need to call initialize. */ bool theDirtyFlag; TYPE_DATA }; // End of class ossimWatermarkFilter. #endif /* #ifndef ossimWatermarkFilter_HEADER */ ossim-Miami-2.9.1/include/ossim/imaging/ossimWorldFileWriter.h000066400000000000000000000050411352751253100244130ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2003 Storage Area Networks, Inc. // // License: See top level LICENSE.txt file. // // Author: Kenneth Melero (kmelero@sanz.com) // //******************************************************************* // $Id: ossimWorldFileWriter.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimWorldFileWriter_H #define ossimWorldFileWriter_H #include /** ossimWorldFileWriter */ class OSSIMDLLEXPORT ossimWorldFileWriter : public ossimMetadataFileWriter { public: /** default constructor */ ossimWorldFileWriter(); /** * Load state method: * * This method call base class ossimMetadataFileWriter::loadState after * looking for its keywords. * * @param kwl Keyword list to initialize from. * * @param prefix Usually something like: "object1." * * @return This method will alway return true as it is intended to be * used in conjuction with the set methods. * * Keywords picked up by loadState: * * (linear units must be "feet", "us_survey_feet", or "meters") * (If projection is geographic units will always be decimal degrees.) * * linear_units: us_survey_feet */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Satisfies pure virtual from ossimMetadataWriter base. * * Appends the writers image types to the "metadatatypeList". * * @param metadatatypeList stl::vector list to append to. * * @note Appends to the list, does not clear it first. */ virtual void getMetadatatypeList( std::vector& metadatatypeList) const; /** * Satisfies pure virtual from ossimMetadataWriter base. * * @param imageType string representing image type. * * @return true if "metadataType" is supported by writer. */ virtual bool hasMetadataType(const ossimString& metadataType)const; /** * Sets the linear units of the output file to either feet, * us_survey_feet, or meters. * * If the projection is geographic, the call has no affect. * * If units is not feet, us_survey_feet or meters this call has no effect. * * @param units Desired output units of the world file. */ void setLinearUnits(ossimUnitType units); protected: /** default constructor */ virtual ~ossimWorldFileWriter(); virtual bool writeFile(); ossimUnitType theUnits; TYPE_DATA }; #endif /* End of #ifndef ossimWorldFileWriter_H */ ossim-Miami-2.9.1/include/ossim/imaging/ossimWriter.h000066400000000000000000000211571352751253100226110ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Generic image writer class. // //--- // $Id$ #ifndef ossimWriter_HEADER #define ossimWriter_HEADER 1 #include #include #include #include #include class ossimKeywordlist; class ossimProperty; /** * @brief ossimWriter - Generic image writer. * * Please do NOT add any external library dependencies. drb - 26 May 2016 */ class OSSIM_DLL ossimWriter : public ossimImageFileWriter { public: /** default constructor */ ossimWriter(); /** virtual destructor */ virtual ~ossimWriter(); /** @return "ossim_writer" */ virtual ossimString getShortName() const; /** @return "ossim writer" */ virtual ossimString getLongName() const; /** @return "ossimWriter" */ virtual ossimString getClassName() const; /** * Returns a 3-letter extension from the image type descriptor * (theOutputImageType) that can be used for image file extensions. * * @param imageType string representing image type. * * @return the 3-letter string extension. */ virtual ossimString getExtension() const; /** * @brief getImageTypeList method. * * Satisfies ossimImageFileWriter::getImageTypeList pure virtual. * * Appends the writers image types to the "imageTypeList". * * Current write type: * ossim_ttbs - tiled tiff band separate, big tiff format. * * @param imageTypeList list to append to. */ virtual void getImageTypeList(std::vector& imageTypeList) const; /** * @brief isOpen * @return true if open; else, false. */ virtual bool isOpen()const; /** * @brief open * @return true on success, false on error. */ virtual bool open(); /** @brief close Flushes and deletes stream if we own it. */ virtual void close(); bool hasImageType(const ossimString& imageType) const; /** * @brief Method to write the image to a stream. * * @return true on success, false on error. */ virtual bool writeStream(); /** * @brief Sets the output stream to write to. * * This sets the stream and sets m_ownsStreamFlag to false. So destructor * will not delete the stream if this method is used. * * @param stream The stream to write to. * @return true if object can write to stream, false if not. */ virtual bool setOutputStream(std::ostream& str); /** * @brief Sets the output tile size for tiled formats. * @param tileSize Must be a multiple of 16. */ virtual void setTileSize(const ossimIpt& tileSize); /** * @brief Gets the tile size. * @return Reference to tile size. */ virtual const ossimIpt& getOutputTileSize() const; /** * @brief Saves the state of the object. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Will set the property whose name matches the argument * "property->getName()". * * @param property Object containing property to set. */ virtual void setProperty(ossimRefPtr property); /** * @param name Name of property to return. * * @returns A pointer to a property object which matches "name". Returns * NULL if no match is found. */ virtual ossimRefPtr getProperty(const ossimString& name) const; /** * Pushes this's names onto the list of property names. * * @param propertyNames array to add this's property names to. */ virtual void getPropertyNames(std::vector& propertyNames) const; protected: /** * @brief Write out the file. * @return true on success, false on error. */ virtual bool writeFile(); private: /** * @brief Writes a tiled tiff band separate to stream. * @return true on success, false on error. */ bool writeStreamTtbs(); /** * @brief Writes tiff header to stream. * @return true on success, false on error. */ bool writeTiffHdr(); /** * @brief Writes tags to image file directory(IFD). * @param tile_offsets * @param tile_byte_counts * @param minBands * @param maxBands * @return true on success, false on error. */ bool writeTiffTags( const std::vector& tile_offsets, const std::vector& tile_byte_counts, const std::vector& minBands, const std::vector& maxBands ); /** * @brief Writes tags TIFFTAG_MINSAMPLEVALUE(280) and * TIFFTAG_MAXSAMPLEVALUE(281). Only written if scalar type is an unsigned * byte or short. * @return true on success, false on error. */ bool writeMinMaxTiffTags( std::streamoff& arrayWritePos ); /** * @brief Writes tags TIFFTAG_SMINSAMPLEVALUE(340) and * TIFFTAG_SMAXSAMPLEVALUE(341). Only written if scalar type is not an * unsigned byte or short. * @param minBands Array of min values from image write. * @param maxBands Array of max values from image write. * @return true if tags are written, false if not. * A false return is not necessarily an error, just means the * tags were not written due to the scalar type. */ bool writeSMinSMaxTiffTags( const std::vector& minBands, const std::vector& maxBands, std::streamoff& arrayWritePos ); /** * @brief Writes tiff tag to image file directory(IFD). * @param tag * @param type * @param count * @param value(s) or offset to array. * @param arrayWritePos Position to write array to. This will be updated * if array is written with new offset. */ template void writeTiffTag(ossim_uint16 tag, ossim_uint16 type, ossim_uint64 count, const T* value, std::streamoff& arrayWritePos ); /** * @brief Writes image data to stream. * * Data is in a band separate tile layout(PLANARCONFIG_SEPARATE), i.e. all * the red tiles, all the green tiles, all the blue tiles. * * @param tile_offsets Initialized by this with offset for each tile. * @param tile_byte_counts Initialized by this with the byte count of each * tile. * @param minBands Initialized by this with the min values for each band. * @param maxBands Initialized by this with the max values for each band. * @return true on success, false on error. */ bool writeTiffTilesBandSeparate( std::vector& tile_offsets, std::vector& tile_byte_counts, std::vector& minBands, std::vector& maxBands ); /** * @brief Gets the tiff sample format based on scalar type. * E.g SAMPLEFORMAT_UINT, SAMPLEFORMAT_INT or SAMPLEFORMAT_IEEEFP. * @return TIFF sample format or 0 if not mapped to a scalar type. */ ossim_uint16 getTiffSampleFormat() const; /** * @return true if the output type is tiled, false if not. */ bool isTiled() const; /** * @return Value of options key: "align_tiles". * If true, aligns tile addresses to 4096 boundary. * default=true */ bool getAlignTilesFlag() const; /** * @return Value of options key: "flush_tiles". * If true, aligns tile addresses to block boundary. * default=true */ ossim_int64 getBlockSize() const; /** * @return Value of options key: "flush_tiles". * If true, std::ostream::flush() is called after each tile write. * default=true */ bool getFlushTilesFlag() const; /** * @return Value of options key: "include_blank_tiles". * If true, empty/blank tiles will be written; if false, the tile will not * be written, the tile offset and byte count will be set to zero. * default=true (write blanks). */ bool getWriteBlanksFlag() const; bool needsMinMax() const; std::ostream* m_str; bool m_ownsStreamFlag; /** Hold all options. */ ossimRefPtr m_kwl; ossimIpt m_outputTileSize; }; // End: class ossimWriter #endif /* End of "#ifndef ossimWriter_HEADER" */ ossim-Miami-2.9.1/include/ossim/init/000077500000000000000000000000001352751253100174335ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/init/JsonConfig.h000066400000000000000000000134451352751253100216520ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #pragma once #include #include #include #include #include #include namespace ossim { // Forward decl defined after JsonParam class JsonParam; /** * Base class for maintaining parameters affecting the runtime configuration of OSSIM executables. * The state is imported and exported via JSON. There are default configuration files that should * be part of the install, that are accessed by this class. Custom settings can also be loaded. * * There are two functionally equivalent forms for specifying parameters: long and short. * Parameters are initially declared via the long form with descriptions and default values. These * values must be supplied in default JSON files as part of the OSSIM install. * * Once the parameters are declared via the long form, the short form can be used to supply runtime * overrides. * * The long form format is * * { "parameters": [ * { * "name": "", * "descr": " * }, ... * ] * } * * The short form is: * * { "parameters": [ * "": , ... * ] * } * * The short form parameter is only accepted if it has previously been loaded via the long form so * that the data type is known. * * Parameters are usually accessed knowing the data type ahead of time. For example, a string * parameter is accessed as: * * string paramVal = jsonConfig.getParameter("param_name").asSTring(); * * If the parameter is not found, the special null-parameter is returned from getParameter(), and * casting to a tye will return 0, false, or empty string. */ class OSSIM_DLL JsonConfig : public ossim::JsonInterface { public: /** Default Ctor loads all default .json files in the share/ossim system dir */ JsonConfig(); JsonConfig(const ossimFilename& configFile); //! Destructor virtual ~JsonConfig(); //! Opens and parses JSON file. The "parameters" keyword is expected in the root node bool open(const ossimFilename& configFile); //! Reads the params controlling the process from the JSON node named "parameters". virtual void loadJSON(const Json::Value& params_json_node); //! Reads the params controlling the process from the JSON node named "parameters". virtual void saveJSON(Json::Value& params_json_node) const; //! Returns a parameter (might be a null parameter if paramName not found in the configuration. JsonParam& getParameter(const char* paramName); /** Adds parameter to the configuration. Any previous parameter of the same name is replaced. */ void setParameter(const JsonParam& p); //! Convenience method returns TRUE if the currently set diagnostic level is <= level bool diagnosticLevel(unsigned int level) const; //! Outputs JSON to output stream provided. friend std::ostream& operator<<(std::ostream& out, const JsonConfig& obj); bool paramExists(const char* paramName) const; protected: JsonConfig(const JsonConfig& /*hide_this*/) {} bool getBoolValue(bool& rtn_val, const std::string& json_value) const; std::map m_paramsMap; static JsonParam s_nullParam; }; /** * Represents a single configuration parameter. This class provides for packing and unpacking the * parameter from JSON payload, and provides for handling all datatypes of parameters. */ class JsonParam { public: enum ParamType { UNASSIGNED=0, BOOL=1, INT=2, UINT=3, FLOAT=4, STRING=5, VECTOR=6 }; JsonParam() : _type(UNASSIGNED), _value(0) {} JsonParam(const ossimString& argname, const ossimString& arglabel, const ossimString& argdescr, ParamType argparamType, void* value); JsonParam(const JsonParam& copy); ~JsonParam() { resetValue(); } /** Initializes from a JSON node. Return true if successful */ bool loadJSON(const Json::Value& json_node); void saveJSON(Json::Value& json_node) const; const ossimString& name() const { return _name; } const ossimString& label() const { return _label; } const ossimString& descr() const { return _descr; } ParamType type() const { return _type; } bool isBool() const {return (_type == BOOL); } bool asBool() const; bool isUint() const {return (_type == UINT); } unsigned int asUint() const; bool isInt() const {return (_type == INT);} int asInt() const; bool isFloat() const {return (_type == FLOAT);} double asFloat() const; bool isString() const {return (_type == STRING);} std::string asString() const; bool isVector() const {return (_type == VECTOR);} void asVector(std::vector& v) const; bool operator==(const JsonParam& p) const { return (p._name == _name); } /** Outputs JSON to output stream provided */ friend std::ostream& operator<<(std::ostream& out, const JsonParam& obj); private: void setValue(void* value); void resetValue(); ossimString _name; ossimString _label; ossimString _descr; ParamType _type; void* _value; std::vector _allowedValues; // only used for multiple-choice string parameters }; } ossim-Miami-2.9.1/include/ossim/init/ossimInit.h000066400000000000000000000106701352751253100215660ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains declaration of class ossimInit. This object handles all aspects // of initialization for OSSIM applications. These tasks include: // // 1. Parsing the command line. // 2. Instantiating all class factories as declared in ossimFactories.h // 3. Initializing the "trace" code execution tracing functionality. // 4. Scanning the preferences file for relevant values. // // SOFTWARE HISTORY: //> // 24Apr2001 Oscar Kramer // Initial coding. //< //***************************************************************************** // $Id: ossimInit.h 19440 2011-04-25 16:41:28Z dburken $ #ifndef ossimInit_HEADER #define ossimInit_HEADER 1 #include class ossimPreferences; class ossimArgumentParser; class OSSIMDLLEXPORT ossimInit { public: ~ossimInit(); /*! * Returns the static instance of an ossimInit object. This is of no use * until non-static methods are implemented. */ static ossimInit* instance(); void addOptions(ossimArgumentParser& parser); /*! * METHOD: initialize() * This method shall be called from the application's main module with * the command-line arguments. Every OSSIM application should have the * following line early in the main module: * * ossimInit::initialize(argc, argv); * * OR * * ossimInit::instance()->initialize(argc, argv); * * The two forms are functionally identical. Pick the latter form if you * like to type. The argv command line options are parsed and may be * stripped. the value of argc will be adjusted to account for stripped * options. */ void initialize(int& argc, char** argv); void initialize(ossimArgumentParser& parser); void initialize(); void finalize(); /*! * METHOD: usage() * Prints to stdout the list of command line options that this object parses */ void usage(); /** @return theElevEnabledFlag */ bool getElevEnabledFlag() const; /** * @brief Sets theElevEnabledFlag. * @param flag If true ossimElevManager will be initialized. Set to false * to NOT initialize the ossimElevManager from preferences. * Default in class is true. */ void setElevEnabledFlag(bool flag); void setPluginLoaderEnabledFlag(bool flag); /** * Can take a file or a directory. If a directory is givien then it will check all files in * the directory and add each file that is detected to be a valid plugin. * * @param plugin Is the filename of the plugin to load * @param options Is a keywordlist of plugin specific options */ void loadPlugins(const ossimFilename& plugin, const char* options=0); void initializePlugins(); void initializeDefaultFactories(); void initializeElevation(); /** * @brief Initializes log file from preferences keyword lookup * of "ossim.log.file" if log file has not already been set and * keyword is set in preferences. * * So this should be called after parse options as the --ossim-logfile * should override any preferences setting. */ void initializeLogFile(); /** * @return The version in the form of: * "version major.minor.release (yyyymmdd)" * where * yyyymmdd is the build date. * * e.g. "version 1.7.0 (20071003)" */ ossimString version() const; ossimFilename appName()const; protected: /** protected default constructor. */ ossimInit(); /** Hidden from use copy constructor. */ ossimInit(const ossimInit& obj); /** Hidden from use assignment operator. */ void operator=(const ossimInit& rhs) const; void parseOptions(ossimArgumentParser& parser); void parseNotifyOption(ossimArgumentParser& parser); void parseEnvOptions(ossimArgumentParser& parser); void parsePrefsOptions(ossimArgumentParser& parser); /*! * METHOD: removeOptions() * Utility for stripping from argv all characters associated with a * particular option: */ void removeOption(int& argc, char** argv, int argToRemove); static ossimInit* theInstance; bool theInitializedFlag; ossimFilename theAppName; ossimPreferences* thePreferences; bool theElevEnabledFlag; bool thePluginLoaderEnabledFlag; }; #endif ossim-Miami-2.9.1/include/ossim/matrix/000077500000000000000000000000001352751253100177745ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/matrix/controlw.h000066400000000000000000000027211352751253100220160ustar00rootroot00000000000000//$$ controlw.h Control word class #ifndef CONTROL_WORD_LIB #define CONTROL_WORD_LIB 0 // for organising an int as a series of bits which indicate whether an // option is on or off. class ControlWord { protected: int cw; // the control word public: ControlWord() : cw(0) {} // do nothing ControlWord(int i) : cw(i) {} // load an integer // select specific bits (for testing at least one set) ControlWord operator*(ControlWord i) const { return ControlWord(cw & i.cw); } void operator*=(ControlWord i) { cw &= i.cw; } // set bits ControlWord operator+(ControlWord i) const { return ControlWord(cw | i.cw); } void operator+=(ControlWord i) { cw |= i.cw; } // reset bits ControlWord operator-(ControlWord i) const { return ControlWord(cw - (cw & i.cw)); } void operator-=(ControlWord i) { cw -= (cw & i.cw); } // check if all of selected bits set or reset bool operator>=(ControlWord i) const { return (cw & i.cw) == i.cw; } bool operator<=(ControlWord i) const { return (cw & i.cw) == cw; } // flip selected bits ControlWord operator^(ControlWord i) const { return ControlWord(cw ^ i.cw); } ControlWord operator~() const { return ControlWord(~cw); } // convert to integer int operator+() const { return cw; } int operator!() const { return cw==0; } FREE_CHECK(ControlWord) }; #endif ossim-Miami-2.9.1/include/ossim/matrix/include.h000066400000000000000000000040731352751253100215740ustar00rootroot00000000000000//$$ include.h include files required by various versions of C++ #ifndef INCLUDE_LIB #define INCLUDE_LIB #define use_namespace // define name spaces #include #define SETUP_C_SUBSCRIPTS // allow element access via A[i][j] // Activate just one of the following 3 statements //#define SimulateExceptions // use simulated exceptions #define UseExceptions // use C++ exceptions //#define DisableExceptions // do not use exceptions //#define TEMPS_DESTROYED_QUICKLY // for compilers that delete // temporaries too quickly //#define TEMPS_DESTROYED_QUICKLY_R // the same thing but applied // to return from functions only //#define DO_FREE_CHECK // check news and deletes balance #define USING_DOUBLE // elements of type double //#define USING_FLOAT // elements of type float #define bool_LIB 0 // for compatibility with my older libraries //#define ios_format_flags ios::fmtflags // for Gnu 3 and Intel for Linux //#define _STANDARD_ // using standard library //#define use_float_h // use float.h for precision data //#define HAS_INT64 // if unsigned _int64 is recognised // used by newran03 // comment out next line if Exception causes a problem #define TypeDefException //*********************** end of options set by user ******************** #ifdef use_namespace namespace RBD_COMMON { #endif #ifdef USING_FLOAT // set precision type to float typedef float Real; typedef double long_Real; #endif #ifdef USING_DOUBLE // set precision type to double typedef double Real; //typedef long double long_Real; typedef double long_Real; #endif #ifdef use_namespace } #endif #ifdef use_namespace namespace RBD_COMMON {} namespace RBD_LIBRARIES // access all my libraries { using namespace RBD_COMMON; } #endif #endif ossim-Miami-2.9.1/include/ossim/matrix/myexcept.h000066400000000000000000000267611352751253100220170ustar00rootroot00000000000000//$$ myexcept.h Exception handling classes // A set of classes to simulate exceptions in C++ // // Partially copied from Carlos Vidal s article in the C users journal // September 1992, pp 19-28 // // Operations defined // Try { } // Throw ( exception object ) // ReThrow // Catch ( exception class ) { } // CatchAll { } // CatchAndThrow // // All catch lists must end with a CatchAll or CatchAndThrow statement // but not both. // // When exceptions are finally implemented replace Try, Throw(E), Rethrow, // Catch, CatchAll, CatchAndThrow by try, throw E, throw, catch, // catch(...), and {}. // // All exception classes must be derived from BaseException, have no // non-static variables and must include the statement // // static unsigned long Select; // // Any constructor in one of these exception classes must include // // Select = BaseException::Select; // // For each exceptions class, EX_1, some .cpp file must include // // unsigned long EX_1::Select; // #ifndef EXCEPTION_LIB #define EXCEPTION_LIB #ifdef use_namespace namespace RBD_COMMON { #endif void Terminate(); //********** classes for setting up exceptions and reporting ************// class BaseException; class Tracer // linked list showing how { // we got here const char* entry; Tracer* previous; public: Tracer(const char*); ~Tracer(); void ReName(const char*); static void PrintTrace(); // for printing trace static void AddTrace(); // insert trace in exception record static Tracer* last; // points to Tracer list friend class BaseException; }; class BaseException // The base exception class { protected: static char* what_error; // error message static int SoFar; // no. characters already entered static int LastOne; // last location in error buffer public: static void AddMessage(const char* a_what); // messages about exception static void AddInt(int value); // integer to error message static unsigned long Select; // for identifying exception BaseException(const char* a_what = 0); static const char* what() { return what_error; } // for getting error message }; #ifdef TypeDefException typedef BaseException Exception; // for compatibility with my older libraries #endif inline Tracer::Tracer(const char* e) : entry(e), previous(last) { last = this; } inline Tracer::~Tracer() { last = previous; } inline void Tracer::ReName(const char* e) { entry=e; } #ifdef SimulateExceptions // SimulateExceptions #include //************* the definitions of Try, Throw and Catch *****************// class JumpItem; class Janitor; class JumpBase // pointer to a linked list of jmp_buf s { public: static JumpItem *jl; static jmp_buf env; }; class JumpItem // an item in a linked list of jmp_buf s { public: JumpItem *ji; jmp_buf env; Tracer* trace; // to keep check on Tracer items Janitor* janitor; // list of items for cleanup JumpItem() : ji(JumpBase::jl), trace(0), janitor(0) { JumpBase::jl = this; } ~JumpItem() { JumpBase::jl = ji; } }; void Throw(); inline void Throw(const BaseException&) { Throw(); } #define Try \ if (!setjmp( JumpBase::jl->env )) { \ JumpBase::jl->trace = Tracer::last; \ JumpItem JI387256156; #define ReThrow Throw() #define Catch(EXCEPTION) \ } else if (BaseException::Select == EXCEPTION::Select) { #define CatchAll } else #define CatchAndThrow } else Throw(); //****************** cleanup heap following Throw ***********************// class Janitor { protected: static bool do_not_link; // set when new is called bool OnStack; // false if created by new public: Janitor* NextJanitor; virtual void CleanUp() {} Janitor(); virtual ~Janitor(); }; // The tiresome old trick for initializing the Janitor class // this is needed for classes derived from Janitor which have objects // declared globally class JanitorInitializer { public: JanitorInitializer(); private: static int ref_count; }; static JanitorInitializer JanInit; #endif // end of SimulateExceptions #ifdef UseExceptions #define Try try #define Throw(E) throw E #define ReThrow throw #define Catch catch #define CatchAll catch(...) #define CatchAndThrow {} #endif // end of UseExceptions #ifdef DisableExceptions // Disable exceptions #define Try { #define ReThrow Throw() #define Catch(EXCEPTION) } if (false) { #define CatchAll } if (false) #define CatchAndThrow } inline void Throw() { Terminate(); } inline void Throw(const BaseException&) { Terminate(); } #endif // end of DisableExceptions #ifndef SimulateExceptions // ! SimulateExceptions class Janitor // a dummy version { public: virtual void CleanUp() {} Janitor() {} virtual ~Janitor() {} }; #endif // end of ! SimulateExceptions //******************** FREE_CHECK and NEW_DELETE ***********************// #ifdef DO_FREE_CHECK // DO_FREE_CHECK // Routines for tracing whether new and delete calls are balanced class FreeCheck; class FreeCheckLink { protected: FreeCheckLink* next; void* ClassStore; FreeCheckLink(); virtual void Report()=0; // print details of link friend class FreeCheck; }; class FCLClass : public FreeCheckLink // for registering objects { char* ClassName; FCLClass(void* t, char* name); void Report(); friend class FreeCheck; }; class FCLRealArray : public FreeCheckLink // for registering real arrays { char* Operation; int size; FCLRealArray(void* t, char* o, int s); void Report(); friend class FreeCheck; }; class FCLIntArray : public FreeCheckLink // for registering int arrays { char* Operation; int size; FCLIntArray(void* t, char* o, int s); void Report(); friend class FreeCheck; }; class FreeCheck { static FreeCheckLink* next; static int BadDelete; public: static void Register(void*, char*); static void DeRegister(void*, char*); static void RegisterR(void*, char*, int); static void DeRegisterR(void*, char*, int); static void RegisterI(void*, char*, int); static void DeRegisterI(void*, char*, int); static void Status(); friend class FreeCheckLink; friend class FCLClass; friend class FCLRealArray; friend class FCLIntArray; }; #define FREE_CHECK(Class) \ public: \ void* operator new(size_t size) \ { \ void* t = ::operator new(size); FreeCheck::Register(t,#Class); \ return t; \ } \ void operator delete(void* t) \ { FreeCheck::DeRegister(t,#Class); ::operator delete(t); } #ifdef SimulateExceptions // SimulateExceptions #define NEW_DELETE(Class) \ public: \ void* operator new(size_t size) \ { \ do_not_link=true; \ void* t = ::operator new(size); FreeCheck::Register(t,#Class); \ return t; \ } \ void operator delete(void* t) \ { FreeCheck::DeRegister(t,#Class); ::operator delete(t); } #endif // end of SimulateExceptions #define MONITOR_REAL_NEW(Operation, Size, Pointer) \ FreeCheck::RegisterR(Pointer, Operation, Size); #define MONITOR_INT_NEW(Operation, Size, Pointer) \ FreeCheck::RegisterI(Pointer, Operation, Size); #define MONITOR_REAL_DELETE(Operation, Size, Pointer) \ FreeCheck::DeRegisterR(Pointer, Operation, Size); #define MONITOR_INT_DELETE(Operation, Size, Pointer) \ FreeCheck::DeRegisterI(Pointer, Operation, Size); #else // DO_FREE_CHECK not defined #define FREE_CHECK(Class) public: #define MONITOR_REAL_NEW(Operation, Size, Pointer) {} #define MONITOR_INT_NEW(Operation, Size, Pointer) {} #define MONITOR_REAL_DELETE(Operation, Size, Pointer) {} #define MONITOR_INT_DELETE(Operation, Size, Pointer) {} #ifdef SimulateExceptions // SimulateExceptions #define NEW_DELETE(Class) \ public: \ void* operator new(size_t size) \ { do_not_link=true; void* t = ::operator new(size); return t; } \ void operator delete(void* t) { ::operator delete(t); } #endif // end of SimulateExceptions #endif // end of ! DO_FREE_CHECK #ifndef SimulateExceptions // ! SimulateExceptions #define NEW_DELETE(Class) FREE_CHECK(Class) #endif // end of ! SimulateExceptions //********************* derived exceptions ******************************// class Logic_error : public BaseException { public: static unsigned long Select; Logic_error(const char* a_what = 0); }; class Runtime_error : public BaseException { public: static unsigned long Select; Runtime_error(const char* a_what = 0); }; class Domain_error : public Logic_error { public: static unsigned long Select; Domain_error(const char* a_what = 0); }; class Invalid_argument : public Logic_error { public: static unsigned long Select; Invalid_argument(const char* a_what = 0); }; class Length_error : public Logic_error { public: static unsigned long Select; Length_error(const char* a_what = 0); }; class Out_of_range : public Logic_error { public: static unsigned long Select; Out_of_range(const char* a_what = 0); }; //class Bad_cast : public Logic_error //{ //public: // static unsigned long Select; // Bad_cast(const char* a_what = 0); //}; //class Bad_typeid : public Logic_error //{ //public: // static unsigned long Select; // Bad_typeid(const char* a_what = 0); //}; class Range_error : public Runtime_error { public: static unsigned long Select; Range_error(const char* a_what = 0); }; class Overflow_error : public Runtime_error { public: static unsigned long Select; Overflow_error(const char* a_what = 0); }; class Bad_alloc : public BaseException { public: static unsigned long Select; Bad_alloc(const char* a_what = 0); }; #ifdef use_namespace } #endif #endif // end of EXCEPTION_LIB // body file: myexcept.cpp ossim-Miami-2.9.1/include/ossim/matrix/newmat.h000066400000000000000000002073171352751253100214520ustar00rootroot00000000000000//$$ newmat.h definition file for new version of matrix package // Copyright (C) 1991,2,3,4,7,2000,2,3: R B Davies #ifndef NEWMAT_LIB #define NEWMAT_LIB 0 #include #include #ifdef use_namespace namespace NEWMAT { using namespace RBD_COMMON; } namespace RBD_LIBRARIES { using namespace NEWMAT; } namespace NEWMAT { #endif //#define DO_REPORT // to activate REPORT #ifdef NO_LONG_NAMES #define UpperTriangularMatrix UTMatrix #define LowerTriangularMatrix LTMatrix #define SymmetricMatrix SMatrix #define DiagonalMatrix DMatrix #define BandMatrix BMatrix #define UpperBandMatrix UBMatrix #define LowerBandMatrix LBMatrix #define SymmetricBandMatrix SBMatrix #define BandLUMatrix BLUMatrix #endif // ************************** general utilities ****************************/ class GeneralMatrix; void MatrixErrorNoSpace(const void*); // no space handler class LogAndSign // Return from LogDeterminant function // - value of the log plus the sign (+, - or 0) { Real log_value; int sign; public: LogAndSign() { log_value=0.0; sign=1; } LogAndSign(Real); void operator*=(Real); void PowEq(int k); // raise to power of k void ChangeSign() { sign = -sign; } Real LogValue() const { return log_value; } int Sign() const { return sign; } Real Value() const; FREE_CHECK(LogAndSign) }; // the following class is for counting the number of times a piece of code // is executed. It is used for locating any code not executed by test // routines. Use turbo GREP locate all places this code is called and // check which ones are not accessed. // Somewhat implementation dependent as it relies on "cout" still being // present when ExeCounter objects are destructed. #ifdef DO_REPORT class ExeCounter { int line; // code line number int fileid; // file identifier long nexe; // number of executions static int nreports; // number of reports public: ExeCounter(int,int); void operator++() { nexe++; } ~ExeCounter(); // prints out reports }; #endif // ************************** class MatrixType *****************************/ // Is used for finding the type of a matrix resulting from the binary operations // +, -, * and identifying what conversions are permissible. // This class must be updated when new matrix types are added. class GeneralMatrix; // defined later class BaseMatrix; // defined later class MatrixInput; // defined later class OSSIM_DLL MatrixType { public: enum Attribute { Valid = 1, Diagonal = 2, // order of these is important Symmetric = 4, Band = 8, Lower = 16, Upper = 32, Square = 64, Skew = 128, LUDeco = 256, Ones = 512 }; enum { US = 0, UT = Valid + Upper + Square, LT = Valid + Lower + Square, Rt = Valid, Sq = Valid + Square, Sm = Valid + Symmetric + Square, Sk = Valid + Skew + Square, Dg = Valid + Diagonal + Band + Lower + Upper + Symmetric + Square, Id = Valid + Diagonal + Band + Lower + Upper + Symmetric + Square + Ones, RV = Valid, // do not separate out CV = Valid, // vectors BM = Valid + Band + Square, UB = Valid + Band + Upper + Square, LB = Valid + Band + Lower + Square, SB = Valid + Band + Symmetric + Square, Ct = Valid + LUDeco + Square, BC = Valid + Band + LUDeco + Square, Mask = ~Square }; static int nTypes() { return 12; } // number of different types // exclude Ct, US, BC public: int attribute; bool DataLossOK; // true if data loss is OK when // this represents a destination public: MatrixType () : DataLossOK(false) {} MatrixType (int i) : attribute(i), DataLossOK(false) {} MatrixType (int i, bool dlok) : attribute(i), DataLossOK(dlok) {} MatrixType (const MatrixType& mt) : attribute(mt.attribute), DataLossOK(mt.DataLossOK) {} void operator=(const MatrixType& mt) { attribute = mt.attribute; DataLossOK = mt.DataLossOK; } void SetDataLossOK() { DataLossOK = true; } int operator+() const { return attribute; } MatrixType operator+(MatrixType mt) const { return MatrixType(attribute & mt.attribute); } MatrixType operator*(const MatrixType&) const; MatrixType SP(const MatrixType&) const; MatrixType KP(const MatrixType&) const; MatrixType operator|(const MatrixType& mt) const { return MatrixType(attribute & mt.attribute & Valid); } MatrixType operator&(const MatrixType& mt) const { return MatrixType(attribute & mt.attribute & Valid); } bool operator>=(MatrixType mt) const { return ( attribute & ~mt.attribute & Mask ) == 0; } bool operator<(MatrixType mt) const // for MS Visual C++ 4 { return ( attribute & ~mt.attribute & Mask ) != 0; } bool operator==(MatrixType t) const { return (attribute == t.attribute); } bool operator!=(MatrixType t) const { return (attribute != t.attribute); } bool operator!() const { return (attribute & Valid) == 0; } MatrixType i() const; // type of inverse MatrixType t() const; // type of transpose MatrixType AddEqualEl() const // Add constant to matrix { return MatrixType(attribute & (Valid + Symmetric + Square)); } MatrixType MultRHS() const; // type for rhs of multiply MatrixType sub() const // type of submatrix { return MatrixType(attribute & Valid); } MatrixType ssub() const // type of sym submatrix { return MatrixType(attribute); } // not for selection matrix GeneralMatrix* New() const; // new matrix of given type GeneralMatrix* New(int,int,BaseMatrix*) const; // new matrix of given type const char* Value() const; // to print type friend bool Rectangular(MatrixType a, MatrixType b, MatrixType c); friend bool Compare(const MatrixType&, MatrixType&); // compare and check conv. bool IsBand() const { return (attribute & Band) != 0; } bool IsDiagonal() const { return (attribute & Diagonal) != 0; } bool IsSymmetric() const { return (attribute & Symmetric) != 0; } bool CannotConvert() const { return (attribute & LUDeco) != 0; } // used by operator== FREE_CHECK(MatrixType) }; // *********************** class MatrixBandWidth ***********************/ class OSSIM_DLL MatrixBandWidth { public: int lower; int upper; MatrixBandWidth(const int l, const int u) : lower(l), upper (u) {} MatrixBandWidth(const int i) : lower(i), upper(i) {} MatrixBandWidth operator+(const MatrixBandWidth&) const; MatrixBandWidth operator*(const MatrixBandWidth&) const; MatrixBandWidth minimum(const MatrixBandWidth&) const; MatrixBandWidth t() const { return MatrixBandWidth(upper,lower); } bool operator==(const MatrixBandWidth& bw) const { return (lower == bw.lower) && (upper == bw.upper); } bool operator!=(const MatrixBandWidth& bw) const { return !operator==(bw); } int Upper() const { return upper; } int Lower() const { return lower; } FREE_CHECK(MatrixBandWidth) }; // ********************* Array length specifier ************************/ // This class is introduced to avoid constructors such as // ColumnVector(int) // being used for conversions class OSSIM_DLL ArrayLengthSpecifier { int value; public: int Value() const { return value; } ArrayLengthSpecifier(int l) : value(l) {} }; // ************************* Matrix routines ***************************/ class MatrixRowCol; // defined later class MatrixRow; class MatrixCol; class MatrixColX; class GeneralMatrix; // defined later class AddedMatrix; class MultipliedMatrix; class SubtractedMatrix; class SPMatrix; class KPMatrix; class ConcatenatedMatrix; class StackedMatrix; class SolvedMatrix; class ShiftedMatrix; class NegShiftedMatrix; class ScaledMatrix; class TransposedMatrix; class ReversedMatrix; class NegatedMatrix; class InvertedMatrix; class RowedMatrix; class ColedMatrix; class DiagedMatrix; class MatedMatrix; class GetSubMatrix; class ReturnMatrix; class Matrix; class SquareMatrix; class nricMatrix; class RowVector; class ColumnVector; class SymmetricMatrix; class UpperTriangularMatrix; class LowerTriangularMatrix; class DiagonalMatrix; class CroutMatrix; class BandMatrix; class LowerBandMatrix; class UpperBandMatrix; class SymmetricBandMatrix; class LinearEquationSolver; class GenericMatrix; #define MatrixTypeUnSp 0 //static MatrixType MatrixTypeUnSp(MatrixType::US); // // AT&T needs this class OSSIM_DLL BaseMatrix : public RBD_COMMON::Janitor // base of all matrix classes { protected: virtual int search(const BaseMatrix*) const = 0; // count number of times matrix // is referred to public: virtual GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp) = 0; // evaluate temporary // for old version of G++ // virtual GeneralMatrix* Evaluate(MatrixType mt) = 0; // GeneralMatrix* Evaluate() { return Evaluate(MatrixTypeUnSp); } AddedMatrix operator+(const BaseMatrix&) const; // results of operations MultipliedMatrix operator*(const BaseMatrix&) const; SubtractedMatrix operator-(const BaseMatrix&) const; ConcatenatedMatrix operator|(const BaseMatrix&) const; StackedMatrix operator&(const BaseMatrix&) const; ShiftedMatrix operator+(Real) const; ScaledMatrix operator*(Real) const; ScaledMatrix operator/(Real) const; ShiftedMatrix operator-(Real) const; TransposedMatrix t() const; // TransposedMatrix t; NegatedMatrix operator-() const; // change sign of elements ReversedMatrix Reverse() const; InvertedMatrix i() const; // InvertedMatrix i; RowedMatrix AsRow() const; ColedMatrix AsColumn() const; DiagedMatrix AsDiagonal() const; MatedMatrix AsMatrix(int,int) const; GetSubMatrix SubMatrix(int,int,int,int) const; GetSubMatrix SymSubMatrix(int,int) const; GetSubMatrix Row(int) const; GetSubMatrix Rows(int,int) const; GetSubMatrix Column(int) const; GetSubMatrix Columns(int,int) const; Real AsScalar() const; // conversion of 1 x 1 matrix virtual LogAndSign LogDeterminant() const; Real Determinant() const; virtual Real SumSquare() const; Real NormFrobenius() const; virtual Real SumAbsoluteValue() const; virtual Real Sum() const; virtual Real MaximumAbsoluteValue() const; virtual Real MaximumAbsoluteValue1(int& i) const; virtual Real MaximumAbsoluteValue2(int& i, int& j) const; virtual Real MinimumAbsoluteValue() const; virtual Real MinimumAbsoluteValue1(int& i) const; virtual Real MinimumAbsoluteValue2(int& i, int& j) const; virtual Real Maximum() const; virtual Real Maximum1(int& i) const; virtual Real Maximum2(int& i, int& j) const; virtual Real Minimum() const; virtual Real Minimum1(int& i) const; virtual Real Minimum2(int& i, int& j) const; virtual Real Trace() const; Real Norm1() const; Real NormInfinity() const; virtual MatrixBandWidth BandWidth() const; // bandwidths of band matrix virtual void CleanUp() {} // to clear store void IEQND() const; // called by ineq. ops // virtual ReturnMatrix Reverse() const; // reverse order of elements //protected: // BaseMatrix() : t(this), i(this) {} friend class GeneralMatrix; friend class Matrix; friend class SquareMatrix; friend class nricMatrix; friend class RowVector; friend class ColumnVector; friend class SymmetricMatrix; friend class UpperTriangularMatrix; friend class LowerTriangularMatrix; friend class DiagonalMatrix; friend class CroutMatrix; friend class BandMatrix; friend class LowerBandMatrix; friend class UpperBandMatrix; friend class SymmetricBandMatrix; friend class AddedMatrix; friend class MultipliedMatrix; friend class SubtractedMatrix; friend class SPMatrix; friend class KPMatrix; friend class ConcatenatedMatrix; friend class StackedMatrix; friend class SolvedMatrix; friend class ShiftedMatrix; friend class NegShiftedMatrix; friend class ScaledMatrix; friend class TransposedMatrix; friend class ReversedMatrix; friend class NegatedMatrix; friend class InvertedMatrix; friend class RowedMatrix; friend class ColedMatrix; friend class DiagedMatrix; friend class MatedMatrix; friend class GetSubMatrix; friend class ReturnMatrix; friend class LinearEquationSolver; friend class GenericMatrix; NEW_DELETE(BaseMatrix) }; // ***************************** working classes **************************/ class OSSIM_DLL GeneralMatrix : public BaseMatrix // declarable matrix types { virtual GeneralMatrix* Image() const; // copy of matrix protected: int tag; // shows whether can reuse int nrows, ncols; // dimensions int storage; // total store required Real* store; // point to store (0=not set) GeneralMatrix(); // initialise with no store GeneralMatrix(ArrayLengthSpecifier); // constructor getting store void Add(GeneralMatrix*, Real); // sum of GM and Real void Add(Real); // add Real to this void NegAdd(GeneralMatrix*, Real); // Real - GM void NegAdd(Real); // this = this - Real void Multiply(GeneralMatrix*, Real); // product of GM and Real void Multiply(Real); // multiply this by Real void Negate(GeneralMatrix*); // change sign void Negate(); // change sign void ReverseElements(); // internal reverse of elements void ReverseElements(GeneralMatrix*); // reverse order of elements void operator=(Real); // set matrix to constant Real* GetStore(); // get store or copy GeneralMatrix* BorrowStore(GeneralMatrix*, MatrixType); // temporarily access store void GetMatrix(const GeneralMatrix*); // used by = and initialise void Eq(const BaseMatrix&, MatrixType); // used by = void Eq(const GeneralMatrix&); // version with no conversion void Eq(const BaseMatrix&, MatrixType, bool);// used by << void Eq2(const BaseMatrix&, MatrixType); // cut down version of Eq int search(const BaseMatrix*) const; virtual GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void CheckConversion(const BaseMatrix&); // check conversion OK void ReSize(int, int, int); // change dimensions virtual short SimpleAddOK(const GeneralMatrix* /* gm */ ) { return 0; } // see bandmat.cpp for explanation virtual void MiniCleanUp() { store = 0; storage = 0; nrows = 0; ncols = 0; tag = -1;} // CleanUp when the data array has already been deleted void PlusEqual(const GeneralMatrix& gm); void MinusEqual(const GeneralMatrix& gm); void PlusEqual(Real f); void MinusEqual(Real f); public: GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); virtual MatrixType Type() const = 0; // type of a matrix int Nrows() const { return nrows; } // get dimensions int Ncols() const { return ncols; } int Storage() const { return storage; } Real* Store() const { return store; } virtual ~GeneralMatrix(); // delete store if set void tDelete(); // delete if tag permits bool reuse(); // true if tag allows reuse void Protect() { tag=-1; } // cannot delete or reuse int Tag() const { return tag; } bool IsZero() const; // test matrix has all zeros void Release() { tag=1; } // del store after next use void Release(int t) { tag=t; } // del store after t accesses void ReleaseAndDelete() { tag=0; } // delete matrix after use void operator<<(const Real*); // assignment from an array void operator<<(const int*); // assignment from an array void operator<<(const BaseMatrix& X) { Eq(X,this->Type(),true); } // = without checking type void Inject(const GeneralMatrix&); // copy stored els only void operator+=(const BaseMatrix&); void operator-=(const BaseMatrix&); void operator*=(const BaseMatrix&); void operator|=(const BaseMatrix&); void operator&=(const BaseMatrix&); void operator+=(Real); void operator-=(Real r) { operator+=(-r); } void operator*=(Real); void operator/=(Real r) { operator*=(1.0/r); } virtual GeneralMatrix* MakeSolver(); // for solving virtual void Solver(MatrixColX&, const MatrixColX&) {} virtual void GetRow(MatrixRowCol&) = 0; // Get matrix row virtual void RestoreRow(MatrixRowCol&) {} // Restore matrix row virtual void NextRow(MatrixRowCol&); // Go to next row virtual void GetCol(MatrixRowCol&) = 0; // Get matrix col virtual void GetCol(MatrixColX&) = 0; // Get matrix col virtual void RestoreCol(MatrixRowCol&) {} // Restore matrix col virtual void RestoreCol(MatrixColX&) {} // Restore matrix col virtual void NextCol(MatrixRowCol&); // Go to next col virtual void NextCol(MatrixColX&); // Go to next col Real SumSquare() const; Real SumAbsoluteValue() const; Real Sum() const; Real MaximumAbsoluteValue1(int& i) const; Real MinimumAbsoluteValue1(int& i) const; Real Maximum1(int& i) const; Real Minimum1(int& i) const; Real MaximumAbsoluteValue() const; Real MaximumAbsoluteValue2(int& i, int& j) const; Real MinimumAbsoluteValue() const; Real MinimumAbsoluteValue2(int& i, int& j) const; Real Maximum() const; Real Maximum2(int& i, int& j) const; Real Minimum() const; Real Minimum2(int& i, int& j) const; LogAndSign LogDeterminant() const; virtual bool IsEqual(const GeneralMatrix&) const; // same type, same values void CheckStore() const; // check store is non-zero virtual void SetParameters(const GeneralMatrix*) {} // set parameters in GetMatrix operator ReturnMatrix() const; // for building a ReturnMatrix ReturnMatrix ForReturn() const; virtual bool SameStorageType(const GeneralMatrix& A) const; virtual void ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B); virtual void ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B); virtual void ReSize(const GeneralMatrix& A); MatrixInput operator<<(Real); // for loading a list MatrixInput operator<<(int f); // ReturnMatrix Reverse() const; // reverse order of elements void CleanUp(); // to clear store friend class Matrix; friend class SquareMatrix; friend class nricMatrix; friend class SymmetricMatrix; friend class UpperTriangularMatrix; friend class LowerTriangularMatrix; friend class DiagonalMatrix; friend class CroutMatrix; friend class RowVector; friend class ColumnVector; friend class BandMatrix; friend class LowerBandMatrix; friend class UpperBandMatrix; friend class SymmetricBandMatrix; friend class BaseMatrix; friend class AddedMatrix; friend class MultipliedMatrix; friend class SubtractedMatrix; friend class SPMatrix; friend class KPMatrix; friend class ConcatenatedMatrix; friend class StackedMatrix; friend class SolvedMatrix; friend class ShiftedMatrix; friend class NegShiftedMatrix; friend class ScaledMatrix; friend class TransposedMatrix; friend class ReversedMatrix; friend class NegatedMatrix; friend class InvertedMatrix; friend class RowedMatrix; friend class ColedMatrix; friend class DiagedMatrix; friend class MatedMatrix; friend class GetSubMatrix; friend class ReturnMatrix; friend class LinearEquationSolver; friend class GenericMatrix; NEW_DELETE(GeneralMatrix) }; class OSSIM_DLL Matrix : public GeneralMatrix // usual rectangular matrix { GeneralMatrix* Image() const; // copy of matrix public: Matrix():GeneralMatrix() {} ~Matrix() {} Matrix(int, int); // standard declaration Matrix(const BaseMatrix&); // evaluate BaseMatrix void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const Matrix& m) { Eq(m); } MatrixType Type() const; Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+m*ncols; } const Real* operator[](int m) const { return store+m*ncols; } #endif Matrix(const Matrix& gm):GeneralMatrix(gm) { GetMatrix(&gm); } GeneralMatrix* MakeSolver(); Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&); void RestoreCol(MatrixColX&); void NextRow(MatrixRowCol&); void NextCol(MatrixRowCol&); void NextCol(MatrixColX&); virtual void ReSize(int,int); // change dimensions // virtual so we will catch it being used in a vector called as a matrix void ReSize(const GeneralMatrix& A); Real MaximumAbsoluteValue2(int& i, int& j) const; Real MinimumAbsoluteValue2(int& i, int& j) const; Real Maximum2(int& i, int& j) const; Real Minimum2(int& i, int& j) const; void operator+=(const Matrix& M) { PlusEqual(M); } void operator-=(const Matrix& M) { MinusEqual(M); } void operator+=(Real f) { GeneralMatrix::Add(f); } void operator-=(Real f) { GeneralMatrix::Add(-f); } friend OSSIM_DLL Real DotProduct(const Matrix& A, const Matrix& B); NEW_DELETE(Matrix) }; class OSSIM_DLL SquareMatrix : public Matrix // square matrix { GeneralMatrix* Image() const; // copy of matrix public: SquareMatrix() {} ~SquareMatrix() {} SquareMatrix(ArrayLengthSpecifier); // standard declaration SquareMatrix(const BaseMatrix&); // evaluate BaseMatrix void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const SquareMatrix& m) { Eq(m); } void operator=(const Matrix& m); MatrixType Type() const; SquareMatrix(const SquareMatrix& gm):Matrix(gm) { GetMatrix(&gm); } SquareMatrix(const Matrix& gm); void ReSize(int); // change dimensions virtual void ReSize(int,int); // change dimensions // virtual so we will catch it being used in a vector called as a matrix void ReSize(const GeneralMatrix& A); void operator+=(const Matrix& M) { PlusEqual(M); } void operator-=(const Matrix& M) { MinusEqual(M); } void operator+=(Real f) { GeneralMatrix::Add(f); } void operator-=(Real f) { GeneralMatrix::Add(-f); } NEW_DELETE(SquareMatrix) }; class OSSIM_DLL nricMatrix : public Matrix // for use with Numerical // Recipes in C { GeneralMatrix* Image() const; // copy of matrix Real** row_pointer; // points to rows void MakeRowPointer(); // build rowpointer void DeleteRowPointer(); public: nricMatrix():Matrix() {} nricMatrix(int m, int n) // standard declaration : Matrix(m,n) { MakeRowPointer(); } nricMatrix(const BaseMatrix& bm) // evaluate BaseMatrix : Matrix(bm) { MakeRowPointer(); } void operator=(const BaseMatrix& bm) { DeleteRowPointer(); Matrix::operator=(bm); MakeRowPointer(); } void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const nricMatrix& m) { DeleteRowPointer(); Eq(m); MakeRowPointer(); } void operator<<(const BaseMatrix& X) { DeleteRowPointer(); Eq(X,this->Type(),true); MakeRowPointer(); } nricMatrix(const nricMatrix& gm):Matrix(gm) { GetMatrix(&gm); MakeRowPointer(); } void ReSize(int m, int n) // change dimensions { DeleteRowPointer(); Matrix::ReSize(m,n); MakeRowPointer(); } void ReSize(const GeneralMatrix& A); ~nricMatrix() { DeleteRowPointer(); } Real** nric() const { CheckStore(); return row_pointer-1; } void CleanUp(); // to clear store void MiniCleanUp(); void operator+=(const Matrix& M) { PlusEqual(M); } void operator-=(const Matrix& M) { MinusEqual(M); } void operator+=(Real f) { GeneralMatrix::Add(f); } void operator-=(Real f) { GeneralMatrix::Add(-f); } NEW_DELETE(nricMatrix) }; class OSSIM_DLL SymmetricMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: SymmetricMatrix():GeneralMatrix() {} ~SymmetricMatrix() {} SymmetricMatrix(ArrayLengthSpecifier); SymmetricMatrix(const BaseMatrix&); void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const SymmetricMatrix& m) { Eq(m); } Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+(m*(m+1))/2; } const Real* operator[](int m) const { return store+(m*(m+1))/2; } #endif MatrixType Type() const; SymmetricMatrix(const SymmetricMatrix& gm):GeneralMatrix(gm) { GetMatrix(&gm); } Real SumSquare() const; Real SumAbsoluteValue() const; Real Sum() const; Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&) {} void RestoreCol(MatrixColX&); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int); // change dimensions void ReSize(const GeneralMatrix& A); void operator+=(const SymmetricMatrix& M) { PlusEqual(M); } void operator-=(const SymmetricMatrix& M) { MinusEqual(M); } void operator+=(Real f) { GeneralMatrix::Add(f); } void operator-=(Real f) { GeneralMatrix::Add(-f); } NEW_DELETE(SymmetricMatrix) }; class OSSIM_DLL UpperTriangularMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: UpperTriangularMatrix():GeneralMatrix() {} ~UpperTriangularMatrix() {} UpperTriangularMatrix(ArrayLengthSpecifier); void operator=(const BaseMatrix&); void operator=(const UpperTriangularMatrix& m) { Eq(m); } UpperTriangularMatrix(const BaseMatrix&); UpperTriangularMatrix(const UpperTriangularMatrix& gm):GeneralMatrix(gm) { GetMatrix(&gm); } void operator=(Real f) { GeneralMatrix::operator=(f); } Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+m*ncols-(m*(m+1))/2; } const Real* operator[](int m) const { return store+m*ncols-(m*(m+1))/2; } #endif MatrixType Type() const; GeneralMatrix* MakeSolver() { return this; } // for solving void Solver(MatrixColX&, const MatrixColX&); LogAndSign LogDeterminant() const; Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&); void RestoreCol(MatrixColX& c) { RestoreCol((MatrixRowCol&)c); } void NextRow(MatrixRowCol&); void ReSize(int); // change dimensions void ReSize(const GeneralMatrix& A); MatrixBandWidth BandWidth() const; void operator+=(const UpperTriangularMatrix& M) { PlusEqual(M); } void operator-=(const UpperTriangularMatrix& M) { MinusEqual(M); } void operator+=(Real f) { GeneralMatrix::operator+=(f); } void operator-=(Real f) { GeneralMatrix::operator-=(f); } NEW_DELETE(UpperTriangularMatrix) }; class OSSIM_DLL LowerTriangularMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: LowerTriangularMatrix():GeneralMatrix() {} ~LowerTriangularMatrix() {} LowerTriangularMatrix(ArrayLengthSpecifier); LowerTriangularMatrix(const LowerTriangularMatrix& gm):GeneralMatrix(gm) { GetMatrix(&gm); } LowerTriangularMatrix(const BaseMatrix& M); void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const LowerTriangularMatrix& m) { Eq(m); } Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+(m*(m+1))/2; } const Real* operator[](int m) const { return store+(m*(m+1))/2; } #endif MatrixType Type() const; GeneralMatrix* MakeSolver() { return this; } // for solving void Solver(MatrixColX&, const MatrixColX&); LogAndSign LogDeterminant() const; Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&); void RestoreCol(MatrixColX& c) { RestoreCol((MatrixRowCol&)c); } void NextRow(MatrixRowCol&); void ReSize(int); // change dimensions void ReSize(const GeneralMatrix& A); MatrixBandWidth BandWidth() const; void operator+=(const LowerTriangularMatrix& M) { PlusEqual(M); } void operator-=(const LowerTriangularMatrix& M) { MinusEqual(M); } void operator+=(Real f) { GeneralMatrix::operator+=(f); } void operator-=(Real f) { GeneralMatrix::operator-=(f); } NEW_DELETE(LowerTriangularMatrix) }; class OSSIM_DLL DiagonalMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: DiagonalMatrix():GeneralMatrix() {} ~DiagonalMatrix() {} DiagonalMatrix(ArrayLengthSpecifier); DiagonalMatrix(const BaseMatrix&); DiagonalMatrix(const DiagonalMatrix& gm):GeneralMatrix(gm) { GetMatrix(&gm); } void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const DiagonalMatrix& m) { Eq(m); } Real& operator()(int, int); // access element Real& operator()(int); // access element Real operator()(int, int) const; // access element Real operator()(int) const; Real& element(int, int); // access element Real& element(int); // access element Real element(int, int) const; // access element Real element(int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real& operator[](int m) { return store[m]; } const Real& operator[](int m) const { return store[m]; } #endif MatrixType Type() const; LogAndSign LogDeterminant() const; Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void NextRow(MatrixRowCol&); void NextCol(MatrixRowCol&); void NextCol(MatrixColX&); GeneralMatrix* MakeSolver() { return this; } // for solving void Solver(MatrixColX&, const MatrixColX&); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int); // change dimensions void ReSize(const GeneralMatrix& A); Real* nric() const { CheckStore(); return store-1; } // for use by NRIC MatrixBandWidth BandWidth() const; // ReturnMatrix Reverse() const; // reverse order of elements void operator+=(const DiagonalMatrix& M) { PlusEqual(M); } void operator-=(const DiagonalMatrix& M) { MinusEqual(M); } void operator+=(Real f) { GeneralMatrix::operator+=(f); } void operator-=(Real f) { GeneralMatrix::operator-=(f); } NEW_DELETE(DiagonalMatrix) }; class OSSIM_DLL RowVector : public Matrix { GeneralMatrix* Image() const; // copy of matrix public: RowVector():Matrix() { nrows = 1; } ~RowVector() {} RowVector(ArrayLengthSpecifier n) : Matrix(1,n.Value()) {} RowVector(const BaseMatrix&); RowVector(const RowVector& gm):Matrix(gm) { GetMatrix(&gm); } void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const RowVector& m) { Eq(m); } Real& operator()(int); // access element Real& element(int); // access element Real operator()(int) const; // access element Real element(int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real& operator[](int m) { return store[m]; } const Real& operator[](int m) const { return store[m]; } #endif MatrixType Type() const; void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void NextCol(MatrixRowCol&); void NextCol(MatrixColX&); void RestoreCol(MatrixRowCol&) {} void RestoreCol(MatrixColX& c); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int); // change dimensions void ReSize(int,int); // in case access is matrix void ReSize(const GeneralMatrix& A); Real* nric() const { CheckStore(); return store-1; } // for use by NRIC void CleanUp(); // to clear store void MiniCleanUp() { store = 0; storage = 0; nrows = 1; ncols = 0; tag = -1; } // friend ReturnMatrix GetMatrixRow(Matrix& A, int row); void operator+=(const Matrix& M) { PlusEqual(M); } void operator-=(const Matrix& M) { MinusEqual(M); } void operator+=(Real f) { GeneralMatrix::Add(f); } void operator-=(Real f) { GeneralMatrix::Add(-f); } NEW_DELETE(RowVector) }; class OSSIM_DLL ColumnVector : public Matrix { GeneralMatrix* Image() const; // copy of matrix public: ColumnVector():Matrix() { ncols = 1; } ~ColumnVector() {} ColumnVector(ArrayLengthSpecifier n) : Matrix(n.Value(),1) {} ColumnVector(const BaseMatrix&); ColumnVector(const ColumnVector& gm):Matrix(gm) { GetMatrix(&gm); } void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const ColumnVector& m) { Eq(m); } Real& operator()(int); // access element Real& element(int); // access element Real operator()(int) const; // access element Real element(int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real& operator[](int m) { return store[m]; } const Real& operator[](int m) const { return store[m]; } #endif MatrixType Type() const; GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int); // change dimensions void ReSize(int,int); // in case access is matrix void ReSize(const GeneralMatrix& A); Real* nric() const { CheckStore(); return store-1; } // for use by NRIC void CleanUp(); // to clear store void MiniCleanUp() { store = 0; storage = 0; nrows = 0; ncols = 1; tag = -1; } // ReturnMatrix Reverse() const; // reverse order of elements void operator+=(const Matrix& M) { PlusEqual(M); } void operator-=(const Matrix& M) { MinusEqual(M); } void operator+=(Real f) { GeneralMatrix::Add(f); } void operator-=(Real f) { GeneralMatrix::Add(-f); } NEW_DELETE(ColumnVector) }; class OSSIM_DLL CroutMatrix : public GeneralMatrix // for LU decomposition { int* indx; bool d; bool sing; void ludcmp(); void operator=(const CroutMatrix& /* m */) {} // not allowed public: CroutMatrix(const BaseMatrix&); MatrixType Type() const; void lubksb(Real*, int=0); ~CroutMatrix(); GeneralMatrix* MakeSolver() { return this; } // for solving LogAndSign LogDeterminant() const; void Solver(MatrixColX&, const MatrixColX&); void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX& c) { GetCol((MatrixRowCol&)c); } void CleanUp(); // to clear store void MiniCleanUp(); bool IsEqual(const GeneralMatrix&) const; bool IsSingular() const { return sing; } NEW_DELETE(CroutMatrix) }; // ***************************** band matrices ***************************/ class OSSIM_DLL BandMatrix : public GeneralMatrix // band matrix { GeneralMatrix* Image() const; // copy of matrix protected: void CornerClear() const; // set unused elements to zero short SimpleAddOK(const GeneralMatrix* gm); public: int lower, upper; // band widths BandMatrix():GeneralMatrix() { lower=0; upper=0; CornerClear(); } ~BandMatrix() {} BandMatrix(int n,int lb,int ub) { ReSize(n,lb,ub); CornerClear(); } // standard declaration BandMatrix(const BaseMatrix&); // evaluate BaseMatrix void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const BandMatrix& m) { Eq(m); } MatrixType Type() const; Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+(upper+lower)*m+lower; } const Real* operator[](int m) const { return store+(upper+lower)*m+lower; } #endif BandMatrix(const BandMatrix& gm):GeneralMatrix(gm) { GetMatrix(&gm); } LogAndSign LogDeterminant() const; GeneralMatrix* MakeSolver(); Real Trace() const; Real SumSquare() const { CornerClear(); return GeneralMatrix::SumSquare(); } Real SumAbsoluteValue() const { CornerClear(); return GeneralMatrix::SumAbsoluteValue(); } Real Sum() const { CornerClear(); return GeneralMatrix::Sum(); } Real MaximumAbsoluteValue() const { CornerClear(); return GeneralMatrix::MaximumAbsoluteValue(); } Real MinimumAbsoluteValue() const { int i, j; return GeneralMatrix::MinimumAbsoluteValue2(i, j); } Real Maximum() const { int i, j; return GeneralMatrix::Maximum2(i, j); } Real Minimum() const { int i, j; return GeneralMatrix::Minimum2(i, j); } void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&); void RestoreCol(MatrixColX& c) { RestoreCol((MatrixRowCol&)c); } void NextRow(MatrixRowCol&); virtual void ReSize(int, int, int); // change dimensions void ReSize(const GeneralMatrix& A); bool SameStorageType(const GeneralMatrix& A) const; void ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B); void ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B); MatrixBandWidth BandWidth() const; void SetParameters(const GeneralMatrix*); MatrixInput operator<<(Real); // will give error MatrixInput operator<<(int f); void operator<<(const Real* r); // will give error void operator<<(const int* r); // will give error // the next is included because Zortech and Borland // cannot find the copy in GeneralMatrix void operator<<(const BaseMatrix& X) { GeneralMatrix::operator<<(X); } NEW_DELETE(BandMatrix) }; class OSSIM_DLL UpperBandMatrix : public BandMatrix // upper band matrix { GeneralMatrix* Image() const; // copy of matrix public: UpperBandMatrix():BandMatrix() {} ~UpperBandMatrix() {} UpperBandMatrix(int n, int ubw) // standard declaration : BandMatrix(n, 0, ubw) {} UpperBandMatrix(const BaseMatrix&); // evaluate BaseMatrix void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const UpperBandMatrix& m) { Eq(m); } MatrixType Type() const; UpperBandMatrix(const UpperBandMatrix& gm):BandMatrix(gm) { GetMatrix(&gm); } GeneralMatrix* MakeSolver() { return this; } void Solver(MatrixColX&, const MatrixColX&); LogAndSign LogDeterminant() const; void ReSize(int, int, int); // change dimensions void ReSize(int n,int ubw) // change dimensions { BandMatrix::ReSize(n,0,ubw); } void ReSize(const GeneralMatrix& A) { BandMatrix::ReSize(A); } Real& operator()(int, int); Real operator()(int, int) const; Real& element(int, int); Real element(int, int) const; #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+upper*m; } const Real* operator[](int m) const { return store+upper*m; } #endif NEW_DELETE(UpperBandMatrix) }; class OSSIM_DLL LowerBandMatrix : public BandMatrix // upper band matrix { GeneralMatrix* Image() const; // copy of matrix public: LowerBandMatrix():BandMatrix() {} ~LowerBandMatrix() {} LowerBandMatrix(int n, int lbw) // standard declaration : BandMatrix(n, lbw, 0) {} LowerBandMatrix(const BaseMatrix&); // evaluate BaseMatrix void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const LowerBandMatrix& m) { Eq(m); } MatrixType Type() const; LowerBandMatrix(const LowerBandMatrix& gm):BandMatrix(gm) { GetMatrix(&gm); } GeneralMatrix* MakeSolver() { return this; } void Solver(MatrixColX&, const MatrixColX&); LogAndSign LogDeterminant() const; void ReSize(int, int, int); // change dimensions void ReSize(int n,int lbw) // change dimensions { BandMatrix::ReSize(n,lbw,0); } void ReSize(const GeneralMatrix& A) { BandMatrix::ReSize(A); } Real& operator()(int, int); Real operator()(int, int) const; Real& element(int, int); Real element(int, int) const; #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+lower*(m+1); } const Real* operator[](int m) const { return store+lower*(m+1); } #endif NEW_DELETE(LowerBandMatrix) }; class OSSIM_DLL SymmetricBandMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix void CornerClear() const; // set unused elements to zero short SimpleAddOK(const GeneralMatrix* gm); public: int lower; // lower band width SymmetricBandMatrix():GeneralMatrix() { lower=0; CornerClear(); } ~SymmetricBandMatrix() {} SymmetricBandMatrix(int n, int lb) { ReSize(n,lb); CornerClear(); } SymmetricBandMatrix(const BaseMatrix&); void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const SymmetricBandMatrix& m) { Eq(m); } Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+lower*(m+1); } const Real* operator[](int m) const { return store+lower*(m+1); } #endif MatrixType Type() const; SymmetricBandMatrix(const SymmetricBandMatrix& gm):GeneralMatrix(gm) { GetMatrix(&gm); } GeneralMatrix* MakeSolver(); Real SumSquare() const; Real SumAbsoluteValue() const; Real Sum() const; Real MaximumAbsoluteValue() const { CornerClear(); return GeneralMatrix::MaximumAbsoluteValue(); } Real MinimumAbsoluteValue() const { int i, j; return GeneralMatrix::MinimumAbsoluteValue2(i, j); } Real Maximum() const { int i, j; return GeneralMatrix::Maximum2(i, j); } Real Minimum() const { int i, j; return GeneralMatrix::Minimum2(i, j); } Real Trace() const; LogAndSign LogDeterminant() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&) {} void RestoreCol(MatrixColX&); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int,int); // change dimensions void ReSize(const GeneralMatrix& A); bool SameStorageType(const GeneralMatrix& A) const; void ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B); void ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B); MatrixBandWidth BandWidth() const; void SetParameters(const GeneralMatrix*); void operator<<(const Real* r); // will give error void operator<<(const int* r); // will give error void operator<<(const BaseMatrix& X) { GeneralMatrix::operator<<(X); } NEW_DELETE(SymmetricBandMatrix) }; class OSSIM_DLL BandLUMatrix : public GeneralMatrix // for LU decomposition of band matrix { int* indx; bool d; bool sing; // true if singular Real* store2; int storage2; void ludcmp(); int m1,m2; // lower and upper void operator=(const BandLUMatrix& /* m */) {} // no allowed public: BandLUMatrix(const BaseMatrix&); MatrixType Type() const; void lubksb(Real*, int=0); ~BandLUMatrix(); GeneralMatrix* MakeSolver() { return this; } // for solving LogAndSign LogDeterminant() const; void Solver(MatrixColX&, const MatrixColX&); void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX& c) { GetCol((MatrixRowCol&)c); } void CleanUp(); // to clear store void MiniCleanUp(); bool IsEqual(const GeneralMatrix&) const; bool IsSingular() const { return sing; } NEW_DELETE(BandLUMatrix) }; // ************************** special matrices **************************** class OSSIM_DLL IdentityMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: IdentityMatrix():GeneralMatrix() {} ~IdentityMatrix() {} IdentityMatrix(ArrayLengthSpecifier n) : GeneralMatrix(1) { nrows = ncols = n.Value(); *store = 1; } IdentityMatrix(const IdentityMatrix& gm):GeneralMatrix(gm) { GetMatrix(&gm); } IdentityMatrix(const BaseMatrix&); void operator=(const BaseMatrix&); void operator=(const IdentityMatrix& m) { Eq(m); } void operator=(Real f) { GeneralMatrix::operator=(f); } MatrixType Type() const; LogAndSign LogDeterminant() const; Real Trace() const; Real SumSquare() const; Real SumAbsoluteValue() const; Real Sum() const { return Trace(); } void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void NextRow(MatrixRowCol&); void NextCol(MatrixRowCol&); void NextCol(MatrixColX&); GeneralMatrix* MakeSolver() { return this; } // for solving void Solver(MatrixColX&, const MatrixColX&); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int n); void ReSize(const GeneralMatrix& A); MatrixBandWidth BandWidth() const; // ReturnMatrix Reverse() const; // reverse order of elements NEW_DELETE(IdentityMatrix) }; // ************************** GenericMatrix class ************************/ class OSSIM_DLL GenericMatrix : public BaseMatrix { GeneralMatrix* gm; int search(const BaseMatrix* bm) const; friend class BaseMatrix; public: GenericMatrix() : gm(0) {} GenericMatrix(const BaseMatrix& bm) { gm = ((BaseMatrix&)bm).Evaluate(); gm = gm->Image(); } GenericMatrix(const GenericMatrix& bm) : BaseMatrix(bm) { gm = bm.gm->Image(); } void operator=(const GenericMatrix&); void operator=(const BaseMatrix&); void operator+=(const BaseMatrix&); void operator-=(const BaseMatrix&); void operator*=(const BaseMatrix&); void operator|=(const BaseMatrix&); void operator&=(const BaseMatrix&); void operator+=(Real); void operator-=(Real r) { operator+=(-r); } void operator*=(Real); void operator/=(Real r) { operator*=(1.0/r); } ~GenericMatrix() { delete gm; } void CleanUp() { delete gm; gm = 0; } void Release() { gm->Release(); } GeneralMatrix* Evaluate(MatrixType = MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(GenericMatrix) }; // *************************** temporary classes *************************/ class OSSIM_DLL MultipliedMatrix : public BaseMatrix { protected: // if these union statements cause problems, simply remove them // and declare the items individually union { const BaseMatrix* bm1; GeneralMatrix* gm1; }; // pointers to summands union { const BaseMatrix* bm2; GeneralMatrix* gm2; }; MultipliedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : bm1(bm1x),bm2(bm2x) {} int search(const BaseMatrix*) const; friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~MultipliedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(MultipliedMatrix) }; class OSSIM_DLL AddedMatrix : public MultipliedMatrix { protected: AddedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : MultipliedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~AddedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(AddedMatrix) }; class OSSIM_DLL SPMatrix : public AddedMatrix { protected: SPMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : AddedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~SPMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; friend SPMatrix SP(const BaseMatrix&, const BaseMatrix&); NEW_DELETE(SPMatrix) }; class OSSIM_DLL KPMatrix : public MultipliedMatrix { protected: KPMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : MultipliedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~KPMatrix() {} MatrixBandWidth BandWidth() const; GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); friend KPMatrix KP(const BaseMatrix&, const BaseMatrix&); NEW_DELETE(KPMatrix) }; class OSSIM_DLL ConcatenatedMatrix : public MultipliedMatrix { protected: ConcatenatedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : MultipliedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~ConcatenatedMatrix() {} MatrixBandWidth BandWidth() const; GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); NEW_DELETE(ConcatenatedMatrix) }; class OSSIM_DLL StackedMatrix : public ConcatenatedMatrix { protected: StackedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : ConcatenatedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~StackedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); NEW_DELETE(StackedMatrix) }; class OSSIM_DLL SolvedMatrix : public MultipliedMatrix { SolvedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : MultipliedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class InvertedMatrix; // for operator* public: ~SolvedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(SolvedMatrix) }; class OSSIM_DLL SubtractedMatrix : public AddedMatrix { SubtractedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : AddedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~SubtractedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); NEW_DELETE(SubtractedMatrix) }; class OSSIM_DLL ShiftedMatrix : public BaseMatrix { protected: union { const BaseMatrix* bm; GeneralMatrix* gm; }; Real f; ShiftedMatrix(const BaseMatrix* bmx, Real fx) : bm(bmx),f(fx) {} int search(const BaseMatrix*) const; friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~ShiftedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); friend ShiftedMatrix operator+(Real f, const BaseMatrix& BM); NEW_DELETE(ShiftedMatrix) }; class OSSIM_DLL NegShiftedMatrix : public ShiftedMatrix { protected: NegShiftedMatrix(Real fx, const BaseMatrix* bmx) : ShiftedMatrix(bmx,fx) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~NegShiftedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); friend NegShiftedMatrix operator-(Real, const BaseMatrix&); NEW_DELETE(NegShiftedMatrix) }; class OSSIM_DLL ScaledMatrix : public ShiftedMatrix { ScaledMatrix(const BaseMatrix* bmx, Real fx) : ShiftedMatrix(bmx,fx) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~ScaledMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; friend ScaledMatrix operator*(Real f, const BaseMatrix& BM); NEW_DELETE(ScaledMatrix) }; class OSSIM_DLL NegatedMatrix : public BaseMatrix { protected: union { const BaseMatrix* bm; GeneralMatrix* gm; }; NegatedMatrix(const BaseMatrix* bmx) : bm(bmx) {} int search(const BaseMatrix*) const; private: friend class BaseMatrix; public: ~NegatedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(NegatedMatrix) }; class OSSIM_DLL TransposedMatrix : public NegatedMatrix { TransposedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~TransposedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(TransposedMatrix) }; class OSSIM_DLL ReversedMatrix : public NegatedMatrix { ReversedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~ReversedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); NEW_DELETE(ReversedMatrix) }; class OSSIM_DLL InvertedMatrix : public NegatedMatrix { InvertedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} public: ~InvertedMatrix() {} SolvedMatrix operator*(const BaseMatrix&) const; // inverse(A) * B ScaledMatrix operator*(Real t) const { return BaseMatrix::operator*(t); } friend class BaseMatrix; GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(InvertedMatrix) }; class OSSIM_DLL RowedMatrix : public NegatedMatrix { RowedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~RowedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(RowedMatrix) }; class OSSIM_DLL ColedMatrix : public NegatedMatrix { ColedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~ColedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(ColedMatrix) }; class OSSIM_DLL DiagedMatrix : public NegatedMatrix { DiagedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~DiagedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(DiagedMatrix) }; class OSSIM_DLL MatedMatrix : public NegatedMatrix { int nr, nc; MatedMatrix(const BaseMatrix* bmx, int nrx, int ncx) : NegatedMatrix(bmx), nr(nrx), nc(ncx) {} friend class BaseMatrix; public: ~MatedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(MatedMatrix) }; class OSSIM_DLL ReturnMatrix : public BaseMatrix // for matrix return { GeneralMatrix* gm; int search(const BaseMatrix*) const; public: ~ReturnMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); friend class BaseMatrix; ReturnMatrix(const ReturnMatrix& tm) :BaseMatrix(tm), gm(tm.gm) {} ReturnMatrix(const GeneralMatrix* gmx) : gm((GeneralMatrix*&)gmx) {} // ReturnMatrix(GeneralMatrix&); MatrixBandWidth BandWidth() const; NEW_DELETE(ReturnMatrix) }; // ************************** submatrices ******************************/ class OSSIM_DLL GetSubMatrix : public NegatedMatrix { int row_skip; int row_number; int col_skip; int col_number; bool IsSym; GetSubMatrix (const BaseMatrix* bmx, int rs, int rn, int cs, int cn, bool is) : NegatedMatrix(bmx), row_skip(rs), row_number(rn), col_skip(cs), col_number(cn), IsSym(is) {} void SetUpLHS(); friend class BaseMatrix; public: GetSubMatrix(const GetSubMatrix& g) : NegatedMatrix(g.bm), row_skip(g.row_skip), row_number(g.row_number), col_skip(g.col_skip), col_number(g.col_number), IsSym(g.IsSym) {} ~GetSubMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); void operator=(const BaseMatrix&); void operator+=(const BaseMatrix&); void operator-=(const BaseMatrix&); void operator=(const GetSubMatrix& m) { operator=((const BaseMatrix&)m); } void operator<<(const BaseMatrix&); void operator<<(const Real*); // copy from array void operator<<(const int*); // copy from array MatrixInput operator<<(Real); // for loading a list MatrixInput operator<<(int f); void operator=(Real); // copy from constant void operator+=(Real); // add constant void operator-=(Real r) { operator+=(-r); } // subtract constant void operator*=(Real); // multiply by constant void operator/=(Real r) { operator*=(1.0/r); } // divide by constant void Inject(const GeneralMatrix&); // copy stored els only MatrixBandWidth BandWidth() const; NEW_DELETE(GetSubMatrix) }; // ******************** linear equation solving ****************************/ class OSSIM_DLL LinearEquationSolver : public BaseMatrix { GeneralMatrix* gm; int search(const BaseMatrix*) const { return 0; } friend class BaseMatrix; public: LinearEquationSolver(const BaseMatrix& bm); ~LinearEquationSolver() { delete gm; } void CleanUp() { delete gm; } GeneralMatrix* Evaluate(MatrixType) { return gm; } // probably should have an error message if MatrixType != UnSp NEW_DELETE(LinearEquationSolver) }; // ************************** matrix input *******************************/ class OSSIM_DLL MatrixInput // for reading a list of values into a matrix // the difficult part is detecting a mismatch // in the number of elements { int n; // number values still to be read Real* r; // pointer to next location to be read to public: MatrixInput(const MatrixInput& mi) : n(mi.n), r(mi.r) {} MatrixInput(int nx, Real* rx) : n(nx), r(rx) {} ~MatrixInput(); MatrixInput operator<<(Real); MatrixInput operator<<(int f); friend class GeneralMatrix; }; // **************** a very simple integer array class ********************/ // A minimal array class to imitate a C style array but giving dynamic storage // mostly intended for internal use by newmat class OSSIM_DLL SimpleIntArray : public RBD_COMMON::Janitor { protected: int* a; // pointer to the array int n; // length of the array public: SimpleIntArray(int xn); // build an array length xn ~SimpleIntArray(); // return the space to memory int& operator[](int i); // access element of the array - start at 0 int operator[](int i) const; // access element of constant array void operator=(int ai); // set the array equal to a constant void operator=(const SimpleIntArray& b); // copy the elements of an array SimpleIntArray(const SimpleIntArray& b); // make a new array equal to an existing one int Size() const { return n; } // return the size of the array int* Data() { return a; } // pointer to the data const int* Data() const { return a; } // pointer to the data void ReSize(int i, bool keep = false); // change length, keep data if keep = true void CleanUp() { ReSize(0); } NEW_DELETE(SimpleIntArray) }; // *************************** exceptions ********************************/ class OSSIM_DLL NPDException : public Runtime_error // Not positive definite { public: static unsigned long Select; // for identifying exception NPDException(const GeneralMatrix&); }; class OSSIM_DLL ConvergenceException : public Runtime_error { public: static unsigned long Select; // for identifying exception ConvergenceException(const GeneralMatrix& A); ConvergenceException(const char* c); }; class OSSIM_DLL SingularException : public Runtime_error { public: static unsigned long Select; // for identifying exception SingularException(const GeneralMatrix& A); }; class OSSIM_DLL OverflowException : public Runtime_error { public: static unsigned long Select; // for identifying exception OverflowException(const char* c); }; class OSSIM_DLL ProgramException : public Logic_error { protected: ProgramException(); public: static unsigned long Select; // for identifying exception ProgramException(const char* c); ProgramException(const char* c, const GeneralMatrix&); ProgramException(const char* c, const GeneralMatrix&, const GeneralMatrix&); ProgramException(const char* c, MatrixType, MatrixType); }; class OSSIM_DLL IndexException : public Logic_error { public: static unsigned long Select; // for identifying exception IndexException(int i, const GeneralMatrix& A); IndexException(int i, int j, const GeneralMatrix& A); // next two are for access via element function IndexException(int i, const GeneralMatrix& A, bool); IndexException(int i, int j, const GeneralMatrix& A, bool); }; class OSSIM_DLL VectorException : public Logic_error // cannot convert to vector { public: static unsigned long Select; // for identifying exception VectorException(); VectorException(const GeneralMatrix& A); }; class OSSIM_DLL NotSquareException : public Logic_error { public: static unsigned long Select; // for identifying exception NotSquareException(const GeneralMatrix& A); NotSquareException(); }; class OSSIM_DLL SubMatrixDimensionException : public Logic_error { public: static unsigned long Select; // for identifying exception SubMatrixDimensionException(); }; class OSSIM_DLL IncompatibleDimensionsException : public Logic_error { public: static unsigned long Select; // for identifying exception IncompatibleDimensionsException(); IncompatibleDimensionsException(const GeneralMatrix&, const GeneralMatrix&); }; class OSSIM_DLL NotDefinedException : public Logic_error { public: static unsigned long Select; // for identifying exception NotDefinedException(const char* op, const char* matrix); }; class OSSIM_DLL CannotBuildException : public Logic_error { public: static unsigned long Select; // for identifying exception CannotBuildException(const char* matrix); }; class OSSIM_DLL InternalException : public Logic_error { public: static unsigned long Select; // for identifying exception InternalException(const char* c); }; // ************************ functions ************************************ // bool operator==(const GeneralMatrix& A, const GeneralMatrix& B); bool operator==(const BaseMatrix& A, const BaseMatrix& B); inline bool operator!=(const GeneralMatrix& A, const GeneralMatrix& B) { return ! (A==B); } inline bool operator!=(const BaseMatrix& A, const BaseMatrix& B) { return ! (A==B); } // inequality operators are dummies included for compatibility // with STL. They throw an exception if actually called. inline bool operator<=(const BaseMatrix& A, const BaseMatrix&) { A.IEQND(); return true; } inline bool operator>=(const BaseMatrix& A, const BaseMatrix&) { A.IEQND(); return true; } inline bool operator<(const BaseMatrix& A, const BaseMatrix&) { A.IEQND(); return true; } inline bool operator>(const BaseMatrix& A, const BaseMatrix&) { A.IEQND(); return true; } bool IsZero(const BaseMatrix& A); OSSIM_DLL Matrix CrossProduct(const Matrix& A, const Matrix& B); OSSIM_DLL ReturnMatrix CrossProductRows(const Matrix& A, const Matrix& B); OSSIM_DLL ReturnMatrix CrossProductColumns(const Matrix& A, const Matrix& B); // Definition: newmat8.cpp: OSSIM_DLL Real DotProduct(const Matrix& A, const Matrix& B); // ********************* inline functions ******************************** // inline LogAndSign LogDeterminant(const BaseMatrix& B) { return B.LogDeterminant(); } inline Real Determinant(const BaseMatrix& B) { return B.Determinant(); } inline Real SumSquare(const BaseMatrix& B) { return B.SumSquare(); } inline Real NormFrobenius(const BaseMatrix& B) { return B.NormFrobenius(); } inline Real Trace(const BaseMatrix& B) { return B.Trace(); } inline Real SumAbsoluteValue(const BaseMatrix& B) { return B.SumAbsoluteValue(); } inline Real Sum(const BaseMatrix& B) { return B.Sum(); } inline Real MaximumAbsoluteValue(const BaseMatrix& B) { return B.MaximumAbsoluteValue(); } inline Real MinimumAbsoluteValue(const BaseMatrix& B) { return B.MinimumAbsoluteValue(); } inline Real Maximum(const BaseMatrix& B) { return B.Maximum(); } inline Real Minimum(const BaseMatrix& B) { return B.Minimum(); } inline Real Norm1(const BaseMatrix& B) { return B.Norm1(); } inline Real Norm1(RowVector& RV) { return RV.MaximumAbsoluteValue(); } inline Real NormInfinity(const BaseMatrix& B) { return B.NormInfinity(); } inline Real NormInfinity(ColumnVector& CV) { return CV.MaximumAbsoluteValue(); } inline bool IsZero(const GeneralMatrix& A) { return A.IsZero(); } inline MatrixInput MatrixInput::operator<<(int f) { return *this << (Real)f; } inline MatrixInput GeneralMatrix::operator<<(int f) { return *this << (Real)f; } inline MatrixInput BandMatrix::operator<<(int f) { return *this << (Real)f; } inline MatrixInput GetSubMatrix::operator<<(int f) { return *this << (Real)f; } #ifdef use_namespace } #endif #endif // body file: newmat1.cpp // body file: newmat2.cpp // body file: newmat3.cpp // body file: newmat4.cpp // body file: newmat5.cpp // body file: newmat6.cpp // body file: newmat7.cpp // body file: newmat8.cpp // body file: newmatex.cpp // body file: bandmat.cpp // body file: submat.cpp ossim-Miami-2.9.1/include/ossim/matrix/newmatap.h000066400000000000000000000130221352751253100217570ustar00rootroot00000000000000//$$ newmatap.h definition file for matrix package applications // Copyright (C) 1991,2,3,4,8: R B Davies #ifndef NEWMATAP_LIB #define NEWMATAP_LIB 0 #include #ifdef use_namespace namespace NEWMAT { #endif // ************************** applications *****************************/ void QRZT(Matrix&, LowerTriangularMatrix&); void QRZT(const Matrix&, Matrix&, Matrix&); void QRZ(Matrix&, UpperTriangularMatrix&); void QRZ(const Matrix&, Matrix&, Matrix&); inline void HHDecompose(Matrix& X, LowerTriangularMatrix& L) { QRZT(X,L); } inline void HHDecompose(const Matrix& X, Matrix& Y, Matrix& M) { QRZT(X, Y, M); } void UpdateQRZT(Matrix& X, LowerTriangularMatrix& L); void UpdateQRZ(Matrix& X, UpperTriangularMatrix& U); ReturnMatrix Cholesky(const SymmetricMatrix&); ReturnMatrix Cholesky(const SymmetricBandMatrix&); // produces the Cholesky decomposition of A + x.t() * x where A = chol.t() * chol // and x is a RowVector void UpdateCholesky(UpperTriangularMatrix &chol, RowVector r1Modification); // produces the Cholesky decomposition of A - x.t() * x where A = chol.t() * chol // and x is a RowVector void DowndateCholesky(UpperTriangularMatrix &chol, RowVector x); // a RIGHT circular shift of the rows and columns from // 1,...,k-1,k,k+1,...l,l+1,...,p to // 1,...,k-1,l,k,k+1,...l-1,l+1,...p void RightCircularUpdateCholesky(UpperTriangularMatrix &chol, int k, int l); // a LEFT circular shift of the rows and columns from // 1,...,k-1,k,k+1,...l,l+1,...,p to // 1,...,k-1,k+1,...l,k,l+1,...,p to void LeftCircularUpdateCholesky(UpperTriangularMatrix &chol, int k, int l); void SVD(const Matrix&, DiagonalMatrix&, Matrix&, Matrix&, bool=true, bool=true); void SVD(const Matrix&, DiagonalMatrix&); inline void SVD(const Matrix& A, DiagonalMatrix& D, Matrix& U, bool withU = true) { SVD(A, D, U, U, withU, false); } void SortSV(DiagonalMatrix& D, Matrix& U, bool ascending = false); void SortSV(DiagonalMatrix& D, Matrix& U, Matrix& V, bool ascending = false); void Jacobi(const SymmetricMatrix&, DiagonalMatrix&); void Jacobi(const SymmetricMatrix&, DiagonalMatrix&, SymmetricMatrix&); void Jacobi(const SymmetricMatrix&, DiagonalMatrix&, Matrix&); void Jacobi(const SymmetricMatrix&, DiagonalMatrix&, SymmetricMatrix&, Matrix&, bool=true); void EigenValues(const SymmetricMatrix&, DiagonalMatrix&); void EigenValues(const SymmetricMatrix&, DiagonalMatrix&, SymmetricMatrix&); void EigenValues(const SymmetricMatrix&, DiagonalMatrix&, Matrix&); class SymmetricEigenAnalysis // not implemented yet { public: SymmetricEigenAnalysis(const SymmetricMatrix&); private: DiagonalMatrix diag; DiagonalMatrix offdiag; SymmetricMatrix backtransform; FREE_CHECK(SymmetricEigenAnalysis) }; void SortAscending(GeneralMatrix&); void SortDescending(GeneralMatrix&); // class for deciding which fft to use and containing new fft function class OSSIM_DLL FFT_Controller { public: static bool OnlyOldFFT; static bool ar_1d_ft (int PTS, Real* X, Real *Y); static bool CanFactor(int PTS); }; void FFT(const ColumnVector&, const ColumnVector&, ColumnVector&, ColumnVector&); void FFTI(const ColumnVector&, const ColumnVector&, ColumnVector&, ColumnVector&); void RealFFT(const ColumnVector&, ColumnVector&, ColumnVector&); void RealFFTI(const ColumnVector&, const ColumnVector&, ColumnVector&); void DCT_II(const ColumnVector&, ColumnVector&); void DCT_II_inverse(const ColumnVector&, ColumnVector&); void DST_II(const ColumnVector&, ColumnVector&); void DST_II_inverse(const ColumnVector&, ColumnVector&); void DCT(const ColumnVector&, ColumnVector&); void DCT_inverse(const ColumnVector&, ColumnVector&); void DST(const ColumnVector&, ColumnVector&); void DST_inverse(const ColumnVector&, ColumnVector&); void FFT2(const Matrix& U, const Matrix& V, Matrix& X, Matrix& Y); void FFT2I(const Matrix& U, const Matrix& V, Matrix& X, Matrix& Y); // This class is used by the new FFT program // Suppose an integer is expressed as a sequence of digits with each // digit having a different radix. // This class supposes we are counting with this multi-radix number // but also keeps track of the number with the digits (and radices) // reversed. // The integer starts at zero // operator++() increases it by 1 // Counter gives the number of increments // Reverse() gives the value with the digits in reverse order // Swap is true if reverse is less than counter // Finish is true when we have done a complete cycle and are back at zero class MultiRadixCounter { const SimpleIntArray& Radix; // radix of each digit // n-1 highest order, 0 lowest order SimpleIntArray& Value; // value of each digit const int n; // number of digits int reverse; // value when order of digits is reversed int product; // product of radices int counter; // counter bool finish; // true when we have gone over whole range public: MultiRadixCounter(int nx, const SimpleIntArray& rx, SimpleIntArray& vx); void operator++(); // increment the multi-radix counter bool Swap() const { return reverse < counter; } bool Finish() const { return finish; } int Reverse() const { return reverse; } int Counter() const { return counter; } }; #ifdef use_namespace } #endif #endif // body file: cholesky.cpp // body file: evalue.cpp // body file: fft.cpp // body file: hholder.cpp // body file: jacobi.cpp // body file: newfft.cpp // body file: sort.cpp // body file: svd.cpp ossim-Miami-2.9.1/include/ossim/matrix/newmatio.h000066400000000000000000000020261352751253100217700ustar00rootroot00000000000000//$$ newmatio.h definition file for matrix package input/output // Copyright (C) 1991,2,3,4: R B Davies #ifndef NEWMATIO_LIB #define NEWMATIO_LIB 0 #ifndef WANT_STREAM #define WANT_STREAM #endif #include #include #ifdef use_namespace namespace NEWMAT { #endif /**************************** input/output *****************************/ OSSIM_DLL std::ostream& operator<<(std::ostream&, const BaseMatrix&); OSSIM_DLL std::ostream& operator<<(std::ostream&, const GeneralMatrix&); /* Use in some old versions of G++ without complete iomanipulators class Omanip_precision { int x; public: Omanip_precision(int i) : x(i) {} friend std::ostream& operator<<(std::ostream& os, Omanip_precision i); }; Omanip_precision setprecision(int i); class Omanip_width { int x; public: Omanip_width(int i) : x(i) {} friend std::ostream& operator<<(std::ostream& os, Omanip_width i); }; Omanip_width setw(int i); */ #ifdef use_namespace } #endif #endif // body file: newmat9.cpp ossim-Miami-2.9.1/include/ossim/matrix/newmatnl.h000066400000000000000000000255471352751253100220070ustar00rootroot00000000000000//$$ newmatnl.h definition file for non-linear optimisation // Copyright (C) 1993,4,5: R B Davies #ifndef NEWMATNL_LIB #define NEWMATNL_LIB 0 #include #ifdef use_namespace namespace NEWMAT { #endif /* This is a beginning of a series of classes for non-linear optimisation. At present there are two classes. FindMaximum2 is the basic optimisation strategy when one is doing an optimisation where one has first derivatives and estimates of the second derivatives. Class NonLinearLeastSquares is derived from FindMaximum2. This provides the functions that calculate function values and derivatives. A third class is now added. This is for doing maximum-likelihood when you have first derviatives and something like the Fisher Information matrix (eg the variance covariance matrix of the first derivatives or minus the second derivatives - this matrix is assumed to be positive definite). class FindMaximum2 Suppose T is the ColumnVector of parameters, F(T) the function we want to maximise, D(T) the ColumnVector of derivatives of F with respect to T, and S(T) the matrix of second derivatives. Then the basic iteration is given a value of T, update it to T - S.i() * D where .i() denotes inverse. If F was quadratic this would give exactly the right answer (except it might get a minimum rather than a maximum). Since F is not usually quadratic, the simple procedure would be to recalculate S and D with the new value of T and keep iterating until the process converges. This is known as the method of conjugate gradients. In practice, this method may not converge. FindMaximum2 considers an iteration of the form T - x * S.i() * D where x is a number. It tries x = 1 and uses the values of F and its slope with respect to x at x = 0 and x = 1 to fit a cubic in x. It then choses x to maximise the resulting function. This gives our new value of T. The program checks that the value of F is getting better and carries out a variety of strategies if it is not. The program also has a second strategy. If the successive values of T seem to be lying along a curve - eg we are following along a curved ridge, the program will try to fit this ridge and project along it. This does not work at present and is commented out. FindMaximum2 has three virtual functions which need to be over-ridden by a derived class. void Value(const ColumnVector& T, bool wg, Real& f, bool& oorg); T is the column vector of parameters. The function returns the value of the function to f, but may instead set oorg to true if the parameter values are not valid. If wg is true it may also calculate and store the second derivative information. bool NextPoint(ColumnVector& H, Real& d); Using the value of T provided in the previous call of Value, find the conjugate gradients adjustment to T, that is - S.i() * D. Also return d = D.t() * S.i() * D. NextPoint should return true if it considers that the process has converged (d very small) and false otherwise. The previous call of Value will have set wg to true, so that S will be available. Real LastDerivative(const ColumnVector& H); Return the scalar product of H and the vector of derivatives at the last value of T. The function Fit is the function that calls the iteration. void Fit(ColumnVector&, int); The arguments are the trial parameter values as a ColumnVector and the maximum number of iterations. The program calls a DataException if the initial parameters are not valid and a ConvergenceException if the process fails to converge. class NonLinearLeastSquares This class is derived from FindMaximum2 and carries out a non-linear least squares fit. It uses a QR decomposition to carry out the operations required by FindMaximum2. A prototype class R1_Col_I_D is provided. The user needs to derive a class from this which includes functions the predicted value of each observation its derivatives. An object from this class has to be provided to class NonLinearLeastSquares. Suppose we observe n normal random variables with the same unknown variance and such the i-th one has expected value given by f(i,P) where P is a column vector of unknown parameters and f is a known function. We wish to estimate P. First derive a class from R1_Col_I_D and override Real operator()(int i) to give the value of the function f in terms of i and the ColumnVector para defined in class R1_CoL_I_D. Also override ReturnMatrix Derivatives() to give the derivates of f at para and the value of i used in the preceeding call to operator(). Return the result as a RowVector. Construct an object from this class. Suppose in what follows it is called pred. Now constuct a NonLinearLeastSquaresObject accessing pred and optionally an iteration limit and an accuracy critierion. NonLinearLeastSquares NLLS(pred, 1000, 0.0001); The accuracy critierion should be somewhat less than one and 0.0001 is about the smallest sensible value. Define a ColumnVector P containing a guess at the value of the unknown parameter, and a ColumnVector Y containing the unknown data. Call NLLS.Fit(Y,P); If the process converges, P will contain the estimates of the unknown parameters. If it does not converge an exception will be generated. The following member functions can be called after you have done a fit. Real ResidualVariance() const; The estimate of the variance of the observations. void GetResiduals(ColumnVector& Z) const; The residuals of the individual observations. void GetStandardErrors(ColumnVector&); The standard errors of the observations. void GetCorrelations(SymmetricMatrix&); The correlations of the observations. void GetHatDiagonal(DiagonalMatrix&) const; Forms a diagonal matrix of values between 0 and 1. If the i-th value is larger than, say 0.2, then the i-th data value could have an undue influence on your estimates. */ class FindMaximum2 { virtual void Value(const ColumnVector&, bool, Real&, bool&) = 0; virtual bool NextPoint(ColumnVector&, Real&) = 0; virtual Real LastDerivative(const ColumnVector&) = 0; public: void Fit(ColumnVector&, int); virtual ~FindMaximum2() {} // to keep gnu happy }; class R1_Col_I_D { // The prototype for a Real function of a ColumnVector and an // integer. // You need to derive your function from this one and put in your // function for operator() and Derivatives() at least. // You may also want to set up a constructor to enter in additional // parameter values (that will not vary during the solve). protected: ColumnVector para; // Current x value public: virtual bool IsValid() { return true; } // is the current x value OK virtual Real operator()(int i) = 0; // i-th function value at current para virtual void Set(const ColumnVector& X) { para = X; } // set current para bool IsValid(const ColumnVector& X) { Set(X); return IsValid(); } // set para, check OK Real operator()(int i, const ColumnVector& X) { Set(X); return operator()(i); } // set para, return value virtual ReturnMatrix Derivatives() = 0; // return derivatives as RowVector virtual ~R1_Col_I_D() {} // to keep gnu happy }; class NonLinearLeastSquares : public FindMaximum2 { // these replace the corresponding functions in FindMaximum2 void Value(const ColumnVector&, bool, Real&, bool&); bool NextPoint(ColumnVector&, Real&); Real LastDerivative(const ColumnVector&); Matrix X; // the things we need to do the ColumnVector Y; // QR triangularisation UpperTriangularMatrix U; // see the write-up in newmata.txt ColumnVector M; Real errorvar, criterion; int n_obs, n_param; const ColumnVector* DataPointer; RowVector Derivs; SymmetricMatrix Covariance; DiagonalMatrix SE; R1_Col_I_D& Pred; // Reference to predictor object int Lim; // maximum number of iterations public: NonLinearLeastSquares(R1_Col_I_D& pred, int lim=1000, Real crit=0.0001) : criterion(crit), Pred(pred), Lim(lim) {} void Fit(const ColumnVector&, ColumnVector&); Real ResidualVariance() const { return errorvar; } void GetResiduals(ColumnVector& Z) const { Z = Y; } void GetStandardErrors(ColumnVector&); void GetCorrelations(SymmetricMatrix&); void GetHatDiagonal(DiagonalMatrix&) const; private: void MakeCovariance(); }; // The next class is the prototype class for calculating the // log-likelihood. // I assume first derivatives are available and something like the // Fisher Information or variance/covariance matrix of the first // derivatives or minus the matrix of second derivatives is // available. This matrix must be positive definite. class LL_D_FI { protected: ColumnVector para; // current parameter values bool wg; // true if FI matrix wanted public: virtual void Set(const ColumnVector& X) { para = X; } // set parameter values virtual void WG(bool wgx) { wg = wgx; } // set wg virtual bool IsValid() { return true; } // return true is para is OK bool IsValid(const ColumnVector& X, bool wgx=true) { Set(X); WG(wgx); return IsValid(); } virtual Real LogLikelihood() = 0; // return the loglikelihhod Real LogLikelihood(const ColumnVector& X, bool wgx=true) { Set(X); WG(wgx); return LogLikelihood(); } virtual ReturnMatrix Derivatives() = 0; // column vector of derivatives virtual ReturnMatrix FI() = 0; // Fisher Information matrix virtual ~LL_D_FI() {} // to keep gnu happy }; // This is the class for doing the maximum likelihood estimation class MLE_D_FI : public FindMaximum2 { // these replace the corresponding functions in FindMaximum2 void Value(const ColumnVector&, bool, Real&, bool&); bool NextPoint(ColumnVector&, Real&); Real LastDerivative(const ColumnVector&); // the things we need for the analysis LL_D_FI& LL; // reference to log-likelihood int Lim; // maximum number of iterations Real Criterion; // convergence criterion ColumnVector Derivs; // for the derivatives LowerTriangularMatrix LT; // Cholesky decomposition of FI SymmetricMatrix Covariance; DiagonalMatrix SE; public: MLE_D_FI(LL_D_FI& ll, int lim=1000, Real criterion=0.0001) : LL(ll), Lim(lim), Criterion(criterion) {} void Fit(ColumnVector& Parameters); void GetStandardErrors(ColumnVector&); void GetCorrelations(SymmetricMatrix&); private: void MakeCovariance(); }; #ifdef use_namespace } #endif #endif // body file: newmatnl.cpp ossim-Miami-2.9.1/include/ossim/matrix/newmatrc.h000066400000000000000000000162341352751253100217730ustar00rootroot00000000000000//$$ newmatrc.h definition file for row/column classes // Copyright (C) 1991,2,3,4,7: R B Davies #ifndef NEWMATRC_LIB #define NEWMATRC_LIB 0 #ifdef use_namespace namespace NEWMAT { #endif #include /************** classes MatrixRowCol, MatrixRow, MatrixCol *****************/ // Used for accessing the rows and columns of matrices // All matrix classes must provide routines for calculating matrix rows and // columns. Assume rows can be found very efficiently. enum LSF { LoadOnEntry=1,StoreOnExit=2,DirectPart=4,StoreHere=8,HaveStore=16 }; class LoadAndStoreFlag : public ControlWord { public: LoadAndStoreFlag() {} LoadAndStoreFlag(int i) : ControlWord(i) {} LoadAndStoreFlag(LSF lsf) : ControlWord(lsf) {} LoadAndStoreFlag(const ControlWord& cwx) : ControlWord(cwx) {} }; class OSSIM_DLL MatrixRowCol // the row or column of a matrix { public: // these are public to avoid // numerous friend statements int length; // row or column length int skip; // initial number of zeros int storage; // number of stored elements int rowcol; // row or column number GeneralMatrix* gm; // pointer to parent matrix Real* data; // pointer to local storage LoadAndStoreFlag cw; // Load? Store? Is a Copy? void IncrMat() { rowcol++; data += storage; } // used by NextRow void IncrDiag() { rowcol++; skip++; data++; } void IncrId() { rowcol++; skip++; } void IncrUT() { rowcol++; data += storage; storage--; skip++; } void IncrLT() { rowcol++; data += storage; storage++; } public: void Zero(); // set elements to zero void Add(const MatrixRowCol&); // add a row/col void AddScaled(const MatrixRowCol&, Real); // add a multiple of a row/col void Add(const MatrixRowCol&, const MatrixRowCol&); // add two rows/cols void Add(const MatrixRowCol&, Real); // add a row/col void NegAdd(const MatrixRowCol&, Real); // Real - a row/col void Sub(const MatrixRowCol&); // subtract a row/col void Sub(const MatrixRowCol&, const MatrixRowCol&); // sub a row/col from another void RevSub(const MatrixRowCol&); // subtract from a row/col void ConCat(const MatrixRowCol&, const MatrixRowCol&); // concatenate two row/cols void Multiply(const MatrixRowCol&); // multiply a row/col void Multiply(const MatrixRowCol&, const MatrixRowCol&); // multiply two row/cols void KP(const MatrixRowCol&, const MatrixRowCol&); // Kronecker Product two row/cols void Copy(const MatrixRowCol&); // copy a row/col void CopyCheck(const MatrixRowCol&); // ... check for data loss void Check(const MatrixRowCol&); // just check for data loss void Check(); // check full row/col present void Copy(const Real*&); // copy from an array void Copy(const int*&); // copy from an array void Copy(Real); // copy from constant void Add(Real); // add a constant void Multiply(Real); // multiply by constant Real SumAbsoluteValue(); // sum of absolute values Real MaximumAbsoluteValue1(Real r, int& i); // maximum of absolute values Real MinimumAbsoluteValue1(Real r, int& i); // minimum of absolute values Real Maximum1(Real r, int& i); // maximum Real Minimum1(Real r, int& i); // minimum Real Sum(); // sum of values void Inject(const MatrixRowCol&); // copy stored els of a row/col void Negate(const MatrixRowCol&); // change sign of a row/col void Multiply(const MatrixRowCol&, Real); // scale a row/col friend Real DotProd(const MatrixRowCol&, const MatrixRowCol&); // sum of pairwise product Real* Data() { return data; } int Skip() { return skip; } // number of elements skipped int Storage() { return storage; } // number of elements stored int Length() { return length; } // length of row or column void Skip(int i) { skip=i; } void Storage(int i) { storage=i; } void Length(int i) { length=i; } void SubRowCol(MatrixRowCol&, int, int) const; // get part of a row or column MatrixRowCol() {} // to stop warning messages ~MatrixRowCol(); FREE_CHECK(MatrixRowCol) }; class OSSIM_DLL MatrixRow : public MatrixRowCol { public: // bodies for these are inline at the end of this .h file MatrixRow(GeneralMatrix*, LoadAndStoreFlag, int=0); // extract a row ~MatrixRow(); void Next(); // get next row FREE_CHECK(MatrixRow) }; class OSSIM_DLL MatrixCol : public MatrixRowCol { public: // bodies for these are inline at the end of this .h file MatrixCol(GeneralMatrix*, LoadAndStoreFlag, int=0); // extract a col MatrixCol(GeneralMatrix*, Real*, LoadAndStoreFlag, int=0); // store/retrieve a col ~MatrixCol(); void Next(); // get next row FREE_CHECK(MatrixCol) }; // MatrixColX is an alternative to MatrixCol where the complete // column is stored externally class OSSIM_DLL MatrixColX : public MatrixRowCol { public: // bodies for these are inline at the end of this .h file MatrixColX(GeneralMatrix*, Real*, LoadAndStoreFlag, int=0); // store/retrieve a col ~MatrixColX(); void Next(); // get next row Real* store; // pointer to local storage // less skip FREE_CHECK(MatrixColX) }; /**************************** inline bodies ****************************/ inline MatrixRow::MatrixRow(GeneralMatrix* gmx, LoadAndStoreFlag cwx, int row) { gm=gmx; cw=cwx; rowcol=row; gm->GetRow(*this); } inline void MatrixRow::Next() { gm->NextRow(*this); } inline MatrixCol::MatrixCol(GeneralMatrix* gmx, LoadAndStoreFlag cwx, int col) { gm=gmx; cw=cwx; rowcol=col; gm->GetCol(*this); } inline MatrixCol::MatrixCol(GeneralMatrix* gmx, Real* r, LoadAndStoreFlag cwx, int col) { gm=gmx; data=r; cw=cwx+StoreHere; rowcol=col; gm->GetCol(*this); } inline MatrixColX::MatrixColX(GeneralMatrix* gmx, Real* r, LoadAndStoreFlag cwx, int col) { gm=gmx; store=data=r; cw=cwx+StoreHere; rowcol=col; gm->GetCol(*this); } inline void MatrixCol::Next() { gm->NextCol(*this); } inline void MatrixColX::Next() { gm->NextCol(*this); } #ifdef use_namespace } #endif #endif ossim-Miami-2.9.1/include/ossim/matrix/newmatrm.h000066400000000000000000000106141352751253100220010ustar00rootroot00000000000000//$$newmatrm.h rectangular matrix operations // Copyright (C) 1991,2,3,4: R B Davies #ifndef NEWMATRM_LIB #define NEWMATRM_LIB 0 #ifdef use_namespace namespace NEWMAT { #endif // operations on rectangular matrices class RectMatrixCol; class RectMatrixRowCol // a class for accessing rows and columns of rectangular matrices { protected: #ifdef use_namespace // to make namespace work public: #endif Real* store; // pointer to storage int n; // number of elements int spacing; // space between elements int shift; // space between cols or rows RectMatrixRowCol(Real* st, int nx, int sp, int sh) : store(st), n(nx), spacing(sp), shift(sh) {} void Reset(Real* st, int nx, int sp, int sh) { store=st; n=nx; spacing=sp; shift=sh; } public: Real operator*(const RectMatrixRowCol&) const; // dot product void AddScaled(const RectMatrixRowCol&, Real); // add scaled void Divide(const RectMatrixRowCol&, Real); // scaling void Divide(Real); // scaling void Negate(); // change sign void Zero(); // zero row col Real& operator[](int i) { return *(store+i*spacing); } // element Real SumSquare() const; // sum of squares Real& First() { return *store; } // get first element void DownDiag() { store += (shift+spacing); n--; } void UpDiag() { store -= (shift+spacing); n++; } friend void ComplexScale(RectMatrixCol&, RectMatrixCol&, Real, Real); friend void Rotate(RectMatrixCol&, RectMatrixCol&, Real, Real); FREE_CHECK(RectMatrixRowCol) }; class RectMatrixRow : public RectMatrixRowCol { public: RectMatrixRow(const Matrix&, int, int, int); RectMatrixRow(const Matrix&, int); void Reset(const Matrix&, int, int, int); void Reset(const Matrix&, int); Real& operator[](int i) { return *(store+i); } void Down() { store += shift; } void Right() { store++; n--; } void Up() { store -= shift; } void Left() { store--; n++; } FREE_CHECK(RectMatrixRow) }; class RectMatrixCol : public RectMatrixRowCol { public: RectMatrixCol(const Matrix&, int, int, int); RectMatrixCol(const Matrix&, int); void Reset(const Matrix&, int, int, int); void Reset(const Matrix&, int); void Down() { store += spacing; n--; } void Right() { store++; } void Up() { store -= spacing; n++; } void Left() { store--; } friend void ComplexScale(RectMatrixCol&, RectMatrixCol&, Real, Real); friend void Rotate(RectMatrixCol&, RectMatrixCol&, Real, Real); FREE_CHECK(RectMatrixCol) }; class RectMatrixDiag : public RectMatrixRowCol { public: RectMatrixDiag(const DiagonalMatrix& D) : RectMatrixRowCol(D.Store(), D.Nrows(), 1, 1) {} Real& operator[](int i) { return *(store+i); } void DownDiag() { store++; n--; } void UpDiag() { store--; n++; } FREE_CHECK(RectMatrixDiag) }; inline RectMatrixRow::RectMatrixRow (const Matrix& M, int row, int skip, int length) : RectMatrixRowCol( M.Store()+row*M.Ncols()+skip, length, 1, M.Ncols() ) {} inline RectMatrixRow::RectMatrixRow (const Matrix& M, int row) : RectMatrixRowCol( M.Store()+row*M.Ncols(), M.Ncols(), 1, M.Ncols() ) {} inline RectMatrixCol::RectMatrixCol (const Matrix& M, int skip, int col, int length) : RectMatrixRowCol( M.Store()+col+skip*M.Ncols(), length, M.Ncols(), 1 ) {} inline RectMatrixCol::RectMatrixCol (const Matrix& M, int col) : RectMatrixRowCol( M.Store()+col, M.Nrows(), M.Ncols(), 1 ) {} inline Real square(Real x) { return x*x; } inline Real sign(Real x, Real y) { return (y>=0) ? x : -x; } // assume x >=0 // Misc numerical things Real pythag(Real f, Real g, Real& c, Real& s); inline void GivensRotation(Real cGivens, Real sGivens, Real& x, Real& y) { // allow for possibility &x = &y Real tmp0 = cGivens * x + sGivens * y; Real tmp1 = -sGivens * x + cGivens * y; x = tmp0; y = tmp1; } inline void GivensRotationR(Real cGivens, Real sGivens, Real& x, Real& y) { // also change sign of y // allow for possibility &x = &y Real tmp0 = cGivens * x + sGivens * y; Real tmp1 = sGivens * x - cGivens * y; x = tmp0; y = tmp1; } #ifdef use_namespace } #endif #endif // body file: newmatrm.cpp ossim-Miami-2.9.1/include/ossim/matrix/precisio.h000066400000000000000000000137551352751253100217750ustar00rootroot00000000000000//$$ precisio.h floating point constants #ifndef PRECISION_LIB #define PRECISION_LIB 0 #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef _STANDARD_ // standard library available class FloatingPointPrecision { public: static int Dig() // number of decimal digits or precision { return numeric_limits::digits10 ; } static Real Epsilon() // smallest number such that 1+Eps!=Eps { return numeric_limits::epsilon(); } static int Mantissa() // bits in mantisa { return numeric_limits::digits; } static Real Maximum() // maximum value { return numeric_limits::max(); } static int MaximumDecimalExponent() // maximum decimal exponent { return numeric_limits::max_exponent10; } static int MaximumExponent() // maximum binary exponent { return numeric_limits::max_exponent; } static Real LnMaximum() // natural log of maximum { return (Real)std::log(Maximum()); } static Real Minimum() // minimum positive value { return numeric_limits::min(); } static int MinimumDecimalExponent() // minimum decimal exponent { return numeric_limits::min_exponent10; } static int MinimumExponent() // minimum binary exponent { return numeric_limits::min_exponent; } static Real LnMinimum() // natural log of minimum { return (Real)std::log(Minimum()); } static int Radix() // exponent radix { return numeric_limits::radix; } static int Rounds() // addition rounding (1 = does round) { return numeric_limits::round_style == round_to_nearest ? 1 : 0; } }; #else // _STANDARD_ not defined #ifndef SystemV // if there is float.h #ifdef USING_FLOAT class FloatingPointPrecision { public: static int Dig() { return FLT_DIG; } // number of decimal digits or precision static Real Epsilon() { return FLT_EPSILON; } // smallest number such that 1+Eps!=Eps static int Mantissa() { return FLT_MANT_DIG; } // bits in mantisa static Real Maximum() { return FLT_MAX; } // maximum value static int MaximumDecimalExponent() { return FLT_MAX_10_EXP; } // maximum decimal exponent static int MaximumExponent() { return FLT_MAX_EXP; } // maximum binary exponent static Real LnMaximum() { return (Real)std::log(Maximum()); } // natural log of maximum static Real Minimum() { return FLT_MIN; } // minimum positive value static int MinimumDecimalExponent() { return FLT_MIN_10_EXP; } // minimum decimal exponent static int MinimumExponent() { return FLT_MIN_EXP; } // minimum binary exponent static Real LnMinimum() { return (Real)std::log(Minimum()); } // natural log of minimum static int Radix() { return FLT_RADIX; } // exponent radix static int Rounds() { return FLT_ROUNDS; } // addition rounding (1 = does round) }; #endif // USING_FLOAT #ifdef USING_DOUBLE class FloatingPointPrecision { public: static int Dig() { return DBL_DIG; } // number of decimal digits or precision static Real Epsilon() { return DBL_EPSILON; } // smallest number such that 1+Eps!=Eps static int Mantissa() { return DBL_MANT_DIG; } // bits in mantisa static Real Maximum() { return DBL_MAX; } // maximum value static int MaximumDecimalExponent() { return DBL_MAX_10_EXP; } // maximum decimal exponent static int MaximumExponent() { return DBL_MAX_EXP; } // maximum binary exponent static Real LnMaximum() { return (Real)std::log(Maximum()); } // natural log of maximum static Real Minimum() { //#ifdef __BCPLUSPLUS__ // return 2.225074e-308; // minimum positive value //#else return DBL_MIN; //#endif } static int MinimumDecimalExponent() { return DBL_MIN_10_EXP; } // minimum decimal exponent static int MinimumExponent() { return DBL_MIN_EXP; } // minimum binary exponent static Real LnMinimum() { return (Real)std::log(Minimum()); } // natural log of minimum static int Radix() { return FLT_RADIX; } // exponent radix static int Rounds() { return FLT_ROUNDS; } // addition rounding (1 = does round) }; #endif // USING_DOUBLE #else // if there is no float.h #ifdef USING_FLOAT class FloatingPointPrecision { public: static Real Epsilon() { return pow(2.0,(int)(1-FSIGNIF)); } // smallest number such that 1+Eps!=Eps static Real Maximum() { return MAXFLOAT; } // maximum value static Real LnMaximum() { return (Real)std::log(Maximum()); } // natural log of maximum static Real Minimum() { return MINFLOAT; } // minimum positive value static Real LnMinimum() { return (Real)std::log(Minimum()); } // natural log of minimum }; #endif // USING_FLOAT #ifdef USING_DOUBLE class FloatingPointPrecision { public: static Real Epsilon() { return pow(2.0,(int)(1-DSIGNIF)); } // smallest number such that 1+Eps!=Eps static Real Maximum() { return MAXDOUBLE; } // maximum value static Real LnMaximum() { return LN_MAXDOUBLE; } // natural log of maximum static Real Minimum() { return MINDOUBLE; } static Real LnMinimum() { return LN_MINDOUBLE; } // natural log of minimum }; #endif // USING_DOUBLE #endif // SystemV #endif // _STANDARD_ #ifdef use_namespace } #endif // use_namespace #endif // PRECISION_LIB ossim-Miami-2.9.1/include/ossim/matrix/solution.h000066400000000000000000000062131352751253100220230ustar00rootroot00000000000000//$$ solution.h // solve routines // #include #include #ifdef use_namespace namespace RBD_COMMON { #endif // Solve the equation f(x)=y for x where f is a monotone continuous // function of x // Essentially Brent s method // You need to derive a class from R1_R1 and override "operator()" // with the function you want to solve. // Use an object from this class in OneDimSolve class R1_R1 { // the prototype for a Real function of a Real variable // you need to derive your function from this one and put in your // function for operator() at least. You probably also want to set up a // constructor to put in additional parameter values (e.g. that will not // vary during a solve) protected: Real x; // Current x value bool xSet; // true if a value assigned to x public: virtual ~R1_R1(); Real minX, maxX; // range of value x bool minXinf, maxXinf; // true if these are infinite R1_R1() : xSet(false), minXinf(true), maxXinf(true) {} virtual Real operator()() = 0; // function value at current x // set current x virtual void Set(Real X); // set x, check OK Real operator()(Real X) { Set(X); return operator()(); } // set x, return value virtual bool IsValid(Real X); operator Real(); // implicit conversion }; class SolutionException : public Exception { public: static unsigned long Select; SolutionException(const char* a_what = 0); }; class OneDimSolve { R1_R1& function; // reference to the function Real accX; // accuracy in X direction Real accY; // accuracy in Y direction int lim; // maximum number of iterations public: OneDimSolve(R1_R1& f, Real AccY = 0.0001, Real AccX = 0.0) : function(f), accX(AccX), accY(AccY) {} // f is an R1_R1 function Real Solve(Real Y, Real X, Real Dev, int Lim=100); // Solve for x in Y=f(x) // X is the initial trial value of x // X+Dev is the second trial value // program returns a value of x such that // |Y-f(x)| <= accY or |f.inv(Y)-x| <= accX private: Real x[3], y[3]; // Trial values of X and Y int L,C,U,Last; // Locations of trial values int vpol, hpol; // polarities Real YY; // target value int i; void LookAt(int); // get new value of function bool Finish; // true if LookAt finds conv. bool Captured; // true when target surrounded void VFlip(); void HFlip(); void Flip(); void State(int I, int J, int K); void Linear(int, int, int); void Quadratic(int, int, int); }; #ifdef use_namespace } #endif // body file: solution.cpp ossim-Miami-2.9.1/include/ossim/ossimConfig.h.vc000066400000000000000000000026541352751253100215370ustar00rootroot00000000000000/* $Id: ossimConfig.h.vc 13809 2008-10-30 13:28:17Z gpotts $ */ #ifndef ossimConfig_HEADER #define ossimConfig_HEADER /* Define if you have dirent.h. */ #define HAVE_DIRENT_H 0 /* Define as 1 if you have unistd.h. */ #define HAVE_UNISTD_H 0 /* Define as 1 if you have getopt.h. */ #define HAVE_GETOPT_H 0 /* * Define as 1 if you have fcntl.h. Note this is defined on windows in gdal. * #define HAVE_FCNTL_H 0 */ /* Define as 1 if you have dbmalloc.h. */ #define HAVE_DBMALLOC_H 0 /* Define as 1 if you have malloc.h. */ #define HAVE_MALLOC_H 1 /* Define as 1 if you have dlfcn.h. */ #define HAVE_DLFCN_H 0 #define OSSIM_HAS_LIBZ 1 /* Define if you have support for large (64 bit size) files */ #define HAVE_LARGEFILE_SUPPORT 0 /* Define to "1" if you have MPI(lam/mpi), "0" if not. */ #define OSSIM_HAS_MPI 0 /* Define to "1" if you have FREETYPE, "0" if not. */ #define OSSIM_HAS_FREETYPE 1 /* Define to "1" if you have GEOTIFF, "0" if not. */ #define OSSIM_HAS_GEOTIFF 1 /* Define to "1" if you have HDF5, "0" if not. */ #define OSSIM_HAS_HDF5 0 /* Define to "1" if you have OpenThreads for mutex support, "0" if not. */ #define OSSIM_HAS_OPEN_THREADS 1 /* Enable cvs id strings for use with "ident" application. */ #define OSSIM_ID_ENABLED 1 /* Enable dynamic library support for plugins. * Usually set to 0 for static applications. */ #define OSSIM_DYNAMIC_ENABLED 1 #endif /* End of "#ifndef ossimConfig_HEADER" */ ossim-Miami-2.9.1/include/ossim/parallel/000077500000000000000000000000001352751253100202645ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/parallel/ossimIgen.h000066400000000000000000000037161352751253100224010ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Class declaration for image generator. // //************************************************************************* // $Id: ossimIgen.h 20303 2011-11-29 16:11:46Z oscarkramer $ #ifndef ossimIgen_HEADER #define ossimIgen_HEADER #include #include #include #include #include #include #include #include class ossimImageChain; class ossimImageFileWriter; class ossimMapProjection; class ossimImageViewTransform; class ossimImageSource; class ossimImageMpiMWriterSequenceConnection; class ossimImageMpiSWriterSequenceConnection; class ossimObject; class ossimArgumentParser; class OSSIM_DLL ossimIgen : public ossimReferenced { public: ossimIgen(); virtual ~ossimIgen(); virtual void initialize(const ossimKeywordlist& kwl); virtual void outputProduct(); protected: void initializeAttributes(); void slaveSetup(); bool loadProductSpec(); void setView(); void initThumbnailProjection(); void initializeChain(); bool writeToFile(ossimImageFileWriter* writer); ossimRefPtr theContainer; ossimRefPtr theProductProjection; ossimRefPtr theProductChain; ossimRefPtr theTiling; ossimDrect theOutputRect; bool theBuildThumbnailFlag; ossimIpt theThumbnailSize; long theNumberOfTilesToBuffer; ossimKeywordlist theKwl; bool theTilingEnabled; bool theProgressFlag; bool theStdoutFlag; ossim_uint32 theThreadCount; }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimImageChainMtAdaptor.h000066400000000000000000000147671352751253100253300ustar00rootroot00000000000000//************************************************************************************************* // OSSIM // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //************************************************************************************************* // $Id$ #ifndef ossimImageChainMtAdaptor_HEADER #define ossimImageChainMtAdaptor_HEADER #include #include #include #include #include //************************************************************************************************* //! This class supports multi-threading of image chain getTile() requests and associated chain //! updating. It accepts an original ossimImageChain object which is then cloned (replicated). //! One clone per thread is created, counting the original as clone(0), with all clones //! sharing a common input handler (if directed) so that disk access is serialized and thread-safe. //************************************************************************************************* class OSSIMDLLEXPORT ossimImageChainMtAdaptor : public ossimImageChain { friend class ossimMultiThreadSequencer; //### FOR DEBUG ONLY public: ossimImageChainMtAdaptor(); //! Full constructor accepts the original image chain to clone. //! @param num_threads Total number of cloned chains to make available. //! ossimImageChainMtAdaptor(ossimImageChain* original, ossim_uint32 num_threads=0, bool use_shared_handlers=false, bool use_cache=false, ossim_uint32 cache_tile_size=64); ~ossimImageChainMtAdaptor(); //! Alternate way of specifying number of threads to support. This is the same as the number of //! clones that will be available after replicating the original chain. //! @param num_threads Total number of cloned chains to make available. void setNumberOfThreads(ossim_uint32 num_threads); void setUseSharedHandlers(bool use_shared_handlers); void setCacheTileSize(ossim_uint32 cache_tile_size); void setUseCache(bool use_cache); //! Alternate way of specifying the original chain being adapted for multi-threading. //! @param original Image chain to be adapted. void setOriginalChain(ossimImageChain* original); //! Intercepts the getTile because it should never be called directly. The tile request must go //! to the specific chain clone. virtual ossimRefPtr getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0); //! Adapts call to original chain so that all clones are initialized. virtual void initialize(); //! Adapts call to original chain so that clones are replicated after original's loadState. virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); //! Adapts call to original chain so that adapter-specific keywords can be added to KWL. virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const; //! Adapts the image chain event handler. If the event involves a change to the original image //! chain, then the clones will need to be regenerated here. virtual void processEvent(ossimEvent& event); //! Returns pointer to a specific clone image chain, or NULL if index exceeds the max available. //! The clone at index=0 corresponds to the original, though this detail should be ignored. ossimImageSource* getClone(ossim_uint32 index); //! Returns the number of clones available. The original chain always counts as the first clone. ossim_uint32 getNumberOfClones() const { return (ossim_uint32) m_clones.size(); } //! These overriding access methods greatly facilitate the implementation of an image chain //! adapter class operating on the member original chain. These methods really should be //! "protected" but the compiler complains if the base class declarations are "protected". virtual ossimConnectableObject::ConnectableObjectList& imageChainList(); virtual const ossimConnectableObject::ConnectableObjectList& imageChainList() const; //! Overrides base class implementation in order to make the connection to each clone. This //! connection is typically to the multi-thread sequencer object. virtual ossim_int32 connectMyOutputTo(ossimConnectableObject* outputObject, bool makeInputConnection=true, bool createEventFlag=true); protected: //! Deletes instances of all replicas from the clone list and leaves only the original. void deleteReplicas(); //! Creates clones of original and pushes them onto the clone list. Returns TRUE if successful. bool replicate(); //! Manages reconnecting shared image handlers to a cloned image chain (identified by index) //! after its creation. This is in support of shared image handlers. Returns TRUE if successful. bool connectSharedHandlers(ossim_uint32 index); //! This is the adaptee image chain. ossimRefPtr m_adaptedChain; //! List of replicated child chains' first source (the one receiving the getTile call). The //! first in the list is always the original (adaptee) source. These are owned by the //! m_chainContainers that are maintained here. std::vector< ossimRefPtr > m_clones; //! The container objects must be kept alive in this vector while their child chains in //! m_clones are used. Containers are used because they are the only way of "duping" a complete //! chain with all connections properly done. The containers need to persist in order for the //! chain connections to be maintained (apparent bug in connectable object code). I found it //! impossible to dissociate the chain from its container. As soon as the container disappeared, //! the chain's internal connections would be disrupted. (OLK 11/11) std::vector< ossimRefPtr > m_chainContainers; //! List of handlers that are being shared among all clones (if requested). It is a list since //! the original chain may involve a combiner with multiple image inputs. typedef std::vector > SharedHandlerList; SharedHandlerList m_sharedHandlers; ossim_uint32 m_numThreads; bool d_useSharedHandlers; ossim_uint32 d_cacheTileSize; bool d_useCache; bool d_debugEnabled; }; #endif /* #ifndef ossimImageChain_HEADER */ ossim-Miami-2.9.1/include/ossim/parallel/ossimImageHandlerMtAdaptor.h000066400000000000000000000102411352751253100256420ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // //************************************************************************************************** // $Id$ #ifndef ossimImageHandlerMtAdaptor_HEADER #define ossimImageHandlerMtAdaptor_HEADER 1 #include #include #include //************************************************************************************************** //! Intended mainly to provide a mechanism for mutex-locking access to a shared resource during //! a getTile operation on an ossimImageHandler. This is needed for multi-threaded implementation. //************************************************************************************************** class OSSIMDLLEXPORT ossimImageHandlerMtAdaptor : public ossimImageHandler { public: static const char* ADAPTEE_ID_KW; ossimImageHandlerMtAdaptor(ossimImageHandler* adaptee = 0, bool use_cache=false, ossim_uint32 cache_tile_size=64); //! Sets the handler being adapted. void setAdaptee(ossimImageHandler* handler); //! Only an ossimImageHandler is allowed as input here. virtual bool canConnectMyInputTo(ossim_int32 i, const ossimConnectableObject* obj) const; //! Intercepts the getTile call intended for the adaptee and sets a mutex lock around the //! adaptee's getTile call. virtual ossimRefPtr getTile(const ossimIpt& origin, ossim_uint32 resLevel=0); //! Intercepts the getTile call intended for the adaptee and sets a mutex lock around the //! adaptee's getTile call. virtual ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0); //! Intercepts the getTile call intended for the adaptee and sets a mutex lock around the //! adaptee's getTile call. virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel=0); //! Method to save the state of an object to a keyword list. //! Return true if ok or false on error. virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; //! Method to the load (recreate) the state of an object from a keyword //! list. Return true if ok or false on error. virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); // The following are virtuals in the base class. Implemented here as pass-through to adaptee virtual ossim_uint32 getNumberOfInputBands() const; virtual bool isOpen() const; virtual bool open(); virtual ossim_uint32 getNumberOfLines(ossim_uint32 resLevel = 0) const; virtual ossim_uint32 getNumberOfSamples(ossim_uint32 resLevel = 0) const; virtual ossim_uint32 getImageTileWidth() const; virtual ossim_uint32 getImageTileHeight() const; virtual ossimString getLongName() const; virtual ossimString getShortName() const; virtual void close(); virtual ossim_uint32 getNumberOfOutputBands() const; virtual ossim_uint32 getNumberOfDecimationLevels() const; virtual ossimScalarType getOutputScalarType() const; virtual ossim_uint32 getTileWidth() const; virtual ossim_uint32 getTileHeight() const; virtual ossim_float64 getMinPixelValue(ossim_uint32 band=0)const; virtual ossim_float64 getMaxPixelValue(ossim_uint32 band=0)const; virtual ossim_float64 getNullPixelValue(ossim_uint32 band=0)const; void setCacheTileSize(ossim_uint32 cache_tile_size); void setUseCache(bool use_cache); void writeTime() const; double d_getTileT; ossim_uint32 d_cacheTileSize; protected: //! Protected destructor forces using reference pointer for instantiation. virtual ~ossimImageHandlerMtAdaptor(); ossimRefPtr m_adaptedHandler; ossimRefPtr m_cache; mutable std::mutex m_mutex; bool d_useCache; bool d_useFauxTile; ossimRefPtr d_fauxTile; friend class ossimMtDebug; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimImageMpiMWriterSequenceConnection.h000066400000000000000000000037751352751253100302370ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // // This class is specific to the Master connection and is optimized // for the writer sequence and batch processing chain. For the Slave // implementation look for the ossimImageMpiSWriterSequenceConnection.cc and .h // files. The Master connection is currently implemented to allways do // a recieve and does no processing itself. The slave connection does // all the actual work and processing. // //******************************************************************* // $Id: ossimImageMpiMWriterSequenceConnection.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimImageMpiMWriterSequenceConnection_HEADER #define ossimImageMpiMWriterSequenceConnection_HEADER #include class ossimImageData; class ossimImageMpiMWriterSequenceConnection : public ossimImageSourceSequencer { public: ossimImageMpiMWriterSequenceConnection(ossimObject* owner=NULL); ossimImageMpiMWriterSequenceConnection(ossimImageSource* inputSource, ossimObject* owner=NULL); virtual ~ossimImageMpiMWriterSequenceConnection(); /*! * This is a virtual method that can be overriden * by derived classes (MPI, or PVM or other * parallel connections. This method is to indicate * whether or not this connection is the master/ * controlling connection. */ virtual void initialize(); virtual void setToStartOfSequence(); virtual bool isMaster()const { return true; } /*! * Will allow you to get the next tile in the sequence. */ virtual ossimRefPtr getNextTile(ossim_uint32 resLevel=0); protected: int theNumberOfProcessors; int theRank; bool theNeedToSendRequest; ossimRefPtr theOutputTile; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimImageMpiSWriterSequenceConnection.h000066400000000000000000000031071352751253100302320ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimImageMpiSWriterSequenceConnection.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimImageMpiSWriterSequenceConnection_HEADER #define ossimImageMpiSWriterSequenceConnection_HEADER #include class ossimImageData; class ossimImageMpiSWriterSequenceConnection : public ossimImageSourceSequencer { public: ossimImageMpiSWriterSequenceConnection(ossimObject* owner=NULL, long numberOfTilesToBuffer = 2); ossimImageMpiSWriterSequenceConnection(ossimImageSource* inputSource, ossimObject* owner=NULL, long numberOfTilesToBuffer = 2); virtual ~ossimImageMpiSWriterSequenceConnection(); virtual bool isMaster()const { return false; } virtual void initialize(); virtual void setToStartOfSequence(); /*! * Will allow you to get the next tile in the sequence. */ virtual ossimRefPtr getNextTile(ossim_uint32 resLevel=0); virtual void slaveProcessTiles(); protected: int theNumberOfProcessors; int theRank; int theNumberOfTilesToBuffer; ossimRefPtr* theOutputTile; void deleteOutputTiles(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimJob.h000066400000000000000000000274111352751253100222270ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // //************************************************************************************************** // $Id$ #ifndef ossimJob_HEADER #define ossimJob_HEADER #include #include #include #include #include class ossimJob; /** * This is the job callback interface * It allows one to attach and listen for different states of the job * and if properties have changed * * @code * #include * #include * // Put your includes here: * * // System includes: * #include * #include * * class TestJob : public ossimJob * { * public: * TestJob(){} * protected: * virtual void run() * { * std:cout << "Running Job\n"; * ossim::Thread::sleepInSeconds(2); * std::cout << "Finished Running Job\n"; * } * }; * class MyCallback : public ossimJobCallback * { * public: * MyCallback(){} * virtual void started(std::shared_ptr job) * { * std::cout << "Started job\n"; * ossimJobCallback::started(job); * } * virtual void finished(std::shared_ptr job) * { * std::cout << "Finished job\n"; * ossimJobCallback::finished(job); * } * }; * int main(int argc, char *argv[]) * { * std::shared_ptr job = std::make_shared(); * job->setCallback(std::make_shared()); * job->start(); * * return 0; * } * @endcode */ class OSSIM_DLL ossimJobCallback { public: ossimJobCallback(std::shared_ptr nextCallback=0):m_nextCallback(nextCallback){} virtual void ready(std::shared_ptr job) {if(m_nextCallback) m_nextCallback->ready(job); } virtual void started(std::shared_ptr job) {if(m_nextCallback) m_nextCallback->started(job); } virtual void finished(std::shared_ptr job) {if(m_nextCallback) m_nextCallback->finished(job);} virtual void canceled(std::shared_ptr job) {if(m_nextCallback) m_nextCallback->canceled(job);} virtual void nameChanged(const ossimString& name, std::shared_ptr job) {if(m_nextCallback) m_nextCallback->nameChanged(name, job);} virtual void descriptionChanged(const ossimString& description, std::shared_ptr job) {if(m_nextCallback) m_nextCallback->descriptionChanged(description, job);} virtual void idChanged(const ossimString& id, std::shared_ptr job) {if(m_nextCallback) m_nextCallback->idChanged(id, job);} virtual void percentCompleteChanged(double percentValue, std::shared_ptr job) {if(m_nextCallback) m_nextCallback->percentCompleteChanged(percentValue, job);} void setCallback(std::shared_ptr c){m_nextCallback = c;} std::shared_ptr callback(){return m_nextCallback;} protected: std::shared_ptr m_nextCallback; }; /** * This is the job callback interface * It allows one to attach and listen for different states of the job * and if properties have changed * * @code * #include * #include * // Put your includes here: * * // System includes: * #include * #include * * class TestJob : public ossimJob * { * public: * TestJob(){} * protected: * virtual void run() * { * std:cout << "Running Job\n"; * ossim::Thread::sleepInSeconds(2); * std::cout << "Finished Running Job\n"; * } * }; * class MyCallback : public ossimJobCallback * { * public: * MyCallback(){} * virtual void started(std::shared_ptr job) * { * std::cout << "Started job\n"; * ossimJobCallback::started(job); * } * virtual void finished(std::shared_ptr job) * { * std::cout << "Finished job\n"; * ossimJobCallback::finished(job); * } * }; * int main(int argc, char *argv[]) * { * std::shared_ptr job = std::make_shared(); * job->setCallback(std::make_shared()); * job->start(); * * return 0; * } * @endcode */ class OSSIM_DLL ossimJob : public std::enable_shared_from_this { public: typedef std::list > List; /** * This is a Bit vector. The only value that can be assigned as both active is FINISHED and CANCEL. * CANCELED job may not yet be finished. Once the job is finished the Cancel is complete */ enum State { ossimJob_NONE = 0, ossimJob_READY = 1, ossimJob_RUNNING = 2, ossimJob_CANCEL = 4, ossimJob_FINISHED = 8, ossimJob_ALL = (ossimJob_READY|ossimJob_RUNNING|ossimJob_CANCEL|ossimJob_FINISHED) }; ossimJob() : m_state(ossimJob_READY), m_priority(0.0) {} /** * Main entry point to the job. It will set the state as running and then * call the pure virtual method run. Once completed the job is marked finished * only if the job was not canceled. * * Classes must override the run method. @see run. */ virtual void start(); /** * This is a convenience method to get the shared representation * of this pointer * * @return the shared pointer */ std::shared_ptr getSharedFromThis(){ return shared_from_this(); } /** * This is a convenience method to get the shared representation * of this pointer * * @return the shared pointer */ std::shared_ptr getSharedFromThis()const{ return shared_from_this(); } /** * When the pernet complete is set for the job it will call any callbacks * and nofity percentCompleteChanged. * * @value percent complete */ void setPercentComplete(double value) { std::lock_guard lock(m_jobMutex); if(m_callback) { m_callback->percentCompleteChanged(value, getSharedFromThis()); } } /** * sets the priority of the job * * @param value priority value */ void setPriority(double value) { std::lock_guard lock(m_jobMutex); m_priority = value; } /* * @return the priotiy of the job */ double priority()const { return m_priority; } /** * If derived interfaces implement a block this will allow one to release. * Derived classes must override. */ virtual void release(){} /** * @return the state of the object */ State state()const { std::lock_guard lock(m_jobMutex); return m_state; } /** * Will clear out the state and the call setState * * @param value is the state you wish to reset to */ virtual void resetState(int value) { m_jobMutex.lock(); if(value != m_state) { m_state = ossimJob_NONE; m_jobMutex.unlock(); setState(value); } else { m_jobMutex.unlock(); } } /** * Will allow you to set the state of the job * * @param value is the state you wish to set to * @param on will turn the value on if on is true * and turn it off otherwise. */ virtual void setState(int value, bool on=true); /** * @return true if the job is in a cancel state and false * otherwise */ bool isCanceled()const { std::lock_guard lock(m_jobMutex); return (m_state & ossimJob_CANCEL); } /** * Sets the state if the object as cancelled */ virtual void cancel() { // append the cancel flag to current state setState(ossimJob_CANCEL); } /** * Sets the state if the object as ready */ virtual void ready() { resetState(ossimJob_READY); } /** * Sets the state if the object as running */ virtual void running() { resetState(ossimJob_RUNNING); } /** * Sets the state if the object as finished */ virtual void finished() { int newState = 0; { // maintain the cancel flag so we can indicate the job has now finished std::lock_guard lock(m_jobMutex); newState = ((m_state & ossimJob_CANCEL) | (ossimJob_FINISHED)); } // now reset to the new state resetState(newState); } /** * @return true if the state of the object is in a ready state. */ bool isReady()const { std::lock_guard lock(m_jobMutex); return m_state & ossimJob_READY; } /** * @return true if the state of the object is in some kind of stopped state. */ bool isStopped()const { std::lock_guard lock(m_jobMutex); return (m_state & ossimJob_FINISHED); } /** * @return true if the state of the object is in a finished state. */ bool isFinished()const { std::lock_guard lock(m_jobMutex); return (m_state & ossimJob_FINISHED); } /** * @return true if the state of the object is in a running state. */ bool isRunning()const { std::lock_guard lock(m_jobMutex); return (m_state & ossimJob_RUNNING); } /** * @param callback callback used to call different state of a job */ void setCallback(std::shared_ptr callback) { std::lock_guard lock(m_jobMutex); m_callback = callback; } /** * Sets the name of a job * * @param value the name of the job */ void setName(const ossimString& value) { bool changed = false; std::shared_ptr callback; { std::lock_guard lock(m_jobMutex); changed = value!=m_name; m_name = value; callback = m_callback; } if(changed&&callback) { callback->nameChanged(value, getSharedFromThis()); } } /** * @return the name of the job */ const ossimString& name()const { std::lock_guard lock(m_jobMutex); return m_name; } /* * sets the ID * * @param value the id to set the job to */ void setId(const ossimString& value) { bool changed = false; std::shared_ptr callback; { std::lock_guard lock(m_jobMutex); changed = value!=m_id; m_id = value; callback = m_callback; } if(changed&&callback) { callback->idChanged(value, getSharedFromThis()); } } /* * @return id of the job */ const ossimString& id()const { std::lock_guard lock(m_jobMutex); return m_id; } /* * @param value the description to set on the job */ void setDescription(const ossimString& value) { bool changed = false; std::shared_ptr callback; { std::lock_guard lock(m_jobMutex); changed = value!=m_description; m_description = value; callback = m_callback; } if(changed&&callback) { callback->descriptionChanged(value, getSharedFromThis()); } } /** * @return the desciption of the job */ const ossimString& description()const { std::lock_guard lock(m_jobMutex); return m_description; } /** * @return the callback */ std::shared_ptr callback() {return m_callback;} protected: mutable std::mutex m_jobMutex; ossimString m_name; ossimString m_description; ossimString m_id; State m_state; double m_priority; std::shared_ptr m_callback; /** * Abstract method and must be overriden by the base class. The base ossimJob * will call run from the start method after setting some variables. */ virtual void run()=0; }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimJobMultiThreadQueue.h000066400000000000000000000066221352751253100254000ustar00rootroot00000000000000#ifndef ossimJobMultiThreadQueue_HEADER #define ossimJobMultiThreadQueue_HEADER #include #include /** * This allocates a thread pool used to listen on a shared job queue * * @code * #include * #include * #include * #include * #include * #include * * class TestJob : public ossimJob * { * public: * TestJob(){} * protected: * virtual void run() * { * ossim::Thread::sleepInSeconds(2); * } * }; * class MyCallback : public ossimJobCallback * { * public: * MyCallback(){} * virtual void started(std::shared_ptr job) * { * std::cout << "Started job\n"; * ossimJobCallback::started(job); * } * virtual void finished(std::shared_ptr job) * { * std::cout << "Finished job\n"; * ossimJobCallback::finished(job); * } * }; * * int main(int argc, char *argv[]) * { * int nThreads = 5; * int nJobs = 10; * std::shared_ptr jobQueue = std::make_shared(); * std::shared_ptr jobThreadQueue = std::make_shared(jobQueue, nThreads); * for(int i = 0; i < nJobs; ++i) * { * std::shared_ptr job = std::make_shared(); * job->setCallback(std::make_shared()); * jobQueue->add(job); * } * * while(jobThreadQueue->hasJobsToProcess()) * { * ossim::Thread::sleepInMilliSeconds(10); * } * * std::cout << "Finished and cancelling thread queue\n"; * jobThreadQueue->cancel(); * jobThreadQueue->waitForCompletion(); * * return 0; * } * @endcode */ class OSSIM_DLL ossimJobMultiThreadQueue { public: typedef std::vector > ThreadQueueList; /** * allows one to create a pool of threads with a shared job queue */ ossimJobMultiThreadQueue(std::shared_ptr q=0, ossim_uint32 nThreads=0); /** * Will cancel all threads and wait for completion and clear the thread queue * list */ virtual ~ossimJobMultiThreadQueue(); /** * @return the job queue */ std::shared_ptr getJobQueue(); /** * @return the job queue */ const std::shared_ptr getJobQueue()const; /** * set the job queue to all threads * * @param q the job queue to set */ void setJobQueue(std::shared_ptr q); /** * Will set the number of threads */ void setNumberOfThreads(ossim_uint32 nThreads); /** * @return the number of threads */ ossim_uint32 getNumberOfThreads() const; /** * @return the number of threads that are busy */ ossim_uint32 numberOfBusyThreads()const; /** * @return true if all threads are busy and false otherwise */ bool areAllThreadsBusy()const; /** * @return true if it has jobs that it's processing */ bool hasJobsToProcess()const; /** * Allows one to cancel all threads */ void cancel(); /** * Allows on to wait for all thread completions. Usually called after * @see cancel */ void waitForCompletion(); protected: mutable std::mutex m_mutex; std::shared_ptr m_jobQueue; ThreadQueueList m_threadQueueList; }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimJobQueue.h000066400000000000000000000171471352751253100232410ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // //************************************************************************************************** // $Id$ #ifndef ossimJobQueue_HEADER #define ossimJobQueue_HEADER #include #include #include #include /** * This is the base implementation for the job queue. It allows one to add and remove * jobs and to call the nextJob and, if specified, block the call if no jobs are on * the queue. we derived from std::enable_shared_from_this which allows us access to * a safe shared 'this' pointer. This is used internal to our callbacks. * * The job queue is thread safe and can be shared by multiple threads. * * Here is a quick code example on how to create a shared queue and to attach * a thread to it. In this example we do not block the calling thread for nextJob * @code * #include * #include * #include * #include * class TestJobQueueThread : public ossim::Thread * { * public: * TestJobQueueThread(std::shared_ptr q):m_q(q){} * void run() * { * if(m_q) * { * while(true) * { * interrupt(); * std::shared_ptr job = m_q->nextJob(false); * if(job) * { * job->start(); * } * yieldCurrentThread(); * sleepInMilliSeconds(20); * } * } * } * * private: * std::shared_ptr m_q; * }; * * class TestJob : public ossimJob * { * public: * virtual void run() * { * std:cout << "Running Job\n"; * ossim::Thread::sleepInSeconds(2); * std::cout << "Finished Running Job\n"; * } * }; * int main(int argc, char *argv[]) * { * std::shared_ptr q = std::make_shared(); * std::shared_ptr jobQueueThread = std::make_shared(q); * * jobQueueThread->start(); * * q->add(std::make_shared()); * q->add(std::make_shared()); * q->add(std::make_shared()); * * ossim::Thread::sleepInSeconds(10); * jobQueueThread->cancel(); * jobQueueThread->waitForCompletion(); * } * @endcode */ class OSSIM_DLL ossimJobQueue : public std::enable_shared_from_this { public: /** * The callback allows one to attach and listen for certain things. In * the ossimJobQueue it will notify just before adding a job, after adding a job * and if a job is removed. */ class OSSIM_DLL Callback { public: Callback(){} /** * Called just before a job is added * * @param q Is a shared_ptr to 'this' job queue * @param job Is a shared ptr to the job we are adding */ virtual void adding(std::shared_ptr /*q*/, std::shared_ptr /*job*/){}; /** * Called after a job is added to the queue * @param q Is a shared_ptr to 'this' job queue * @param job Is a shared ptr to the job we are added */ virtual void added(std::shared_ptr /*q*/, std::shared_ptr /*job*/){} /** * Called after a job is removed from the queue * @param q Is a shared_ptr to 'this' job queue * @param job Is a shared ptr to the job we have removed */ virtual void removed(std::shared_ptr /*q*/, std::shared_ptr/*job*/){} }; /** * Default constructor */ ossimJobQueue(); /** * This is the safe way to create a std::shared_ptr for 'this'. Calls the derived * method shared_from_this */ std::shared_ptr getSharedFromThis(){ return shared_from_this(); } /** * This is the safe way to create a std::shared_ptr for 'this'. Calls the derived * method shared_from_this */ std::shared_ptr getSharedFromThis()const{ return shared_from_this(); } /** * Will add a job to the queue and if the guaranteeUniqueFlag is set it will * scan and make sure the job is not on the queue before adding * * @param job The job to add to the queue. * @param guaranteeUniqueFlag if set to true will force a find to make sure the job * does not already exist */ virtual void add(std::shared_ptr job, bool guaranteeUniqueFlag=true); /** * Allows one to remove a job passing in it's name. * * @param name The job name * @return a shared_ptr to the job. This will be nullptr if not found. */ virtual std::shared_ptr removeByName(const ossimString& name); /** * Allows one to remove a job passing in it's id. * * @param id The job id * @return a shared_ptr to the job. This will be nullptr if not found. */ virtual std::shared_ptr removeById(const ossimString& id); /** * Allows one to pass in a job pointer to remove * * @param job the job you wish to remove from the list */ virtual void remove(const std::shared_ptr Job); /** * Will remove any stopped jobs from the queue */ virtual void removeStoppedJobs(); /** * Will clear the queue */ virtual void clear(); /** * Will grab the next job on the list and will return the job or * a null shared_ptr. You can block the caller if the queueis empty forcing it * to wait for more jobs to come onto the queue * * @param blockIfEmptyFlag If true it will block the calling thread until more jobs appear * on the queue. If false, it will return without blocking * @return a shared pointer to a job */ virtual std::shared_ptr nextJob(bool blockIfEmptyFlag=true); /** * will release the block and have any blocked threads continue */ virtual void releaseBlock(); /** * @return true if the queue is empty false otherwise */ bool isEmpty()const; /** * @return the number of jobs on the queue */ ossim_uint32 size(); /** * Allows one to set the callback to the list * * @param c shared_ptr to a callback */ void setCallback(std::shared_ptr c); /** * @return the callback */ std::shared_ptr callback(); protected: /** * Internal method that returns an iterator * * @param the id of the job to search for * @return the iterator */ ossimJob::List::iterator findById(const ossimString& id); /** * Internal method that returns an iterator * * @param name the name of the job to search for * @return the iterator */ ossimJob::List::iterator findByName(const ossimString& name); /** * Internal method that returns an iterator * * @param job the job to search for * @return the iterator */ ossimJob::List::iterator findByPointer(const std::shared_ptr job); /** * Internal method that returns an iterator * * @param job it will find by the name or by the pointer * @return the iterator */ ossimJob::List::iterator findByNameOrPointer(const std::shared_ptr job); /** * Internal method that determines if we have the job * * @param job the job you wish to search for */ bool hasJob(std::shared_ptr job); mutable std::mutex m_jobQueueMutex; ossim::Block m_block; ossimJob::List m_jobQueue; std::shared_ptr m_callback; }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimJobThreadQueue.h000066400000000000000000000076201352751253100243640ustar00rootroot00000000000000#ifndef ossimJobThreadQueue_HEADER #define ossimJobThreadQueue_HEADER #include #include #include /** * ossimJobThreadQueue allows one to instantiate a thread with a shared * queue. the thread will block if the queue is empty and will continue * to pop jobs off the queue calling the start method on the job. Once it * finishes the job it is disguarded and then the next job will be popped off the * queue. * * @code * class TestJob : public ossimJob * { * public: * TestJob(){} * protected: * virtual void run() * { * ossim::Thread::sleepInSeconds(2); * } * }; * class MyCallback : public ossimJobCallback * { * public: * MyCallback(){} * virtual void started(std::shared_ptr job) * { * std::cout << "Started job\n"; * ossimJobCallback::started(job); * } * virtual void finished(std::shared_ptr job) * { * std::cout << "Finished job\n"; * ossimJobCallback::finished(job); * } * }; * int main(int argc, char *argv[]) * { * std::shared_ptr jobQueue = std::make_shared(); * std::shared_ptr jobThreadQueue = std::make_shared(jobQueue); * jobThreadQueue->start(); * std::shared_ptr job = std::make_shared(); * job->setCallback(std::make_shared()); * jobQueue->add(job); * std::cout << "Waiting 5 seconds before terminating\n"; * ossim::Thread::sleepInSeconds(5); * jobThreadQueue->cancel(); * jobThreadQueue->waitForCompletion(); * * return 0; * } * @endcode */ class OSSIM_DLL ossimJobThreadQueue : public ossim::Thread { public: /** * constructor that allows one to instantiat the thread with * a shared job queue. * * @param jqueue shared job queue */ ossimJobThreadQueue(std::shared_ptr jqueue=0); /** * destructor. Will terminate the thread and stop current jobs */ virtual ~ossimJobThreadQueue(); /** * * Sets the shared queue that this thread will be pulling jobs from * * @param jqueue the shared job queue to set */ void setJobQueue(std::shared_ptr jqueue); /** * @return the current shared job queue */ std::shared_ptr getJobQueue(); /** * @return the current shared job queue */ const std::shared_ptr getJobQueue() const; /** * @return the current job that is being handled. */ std::shared_ptr currentJob(); /** * Will cancel the current job */ void cancelCurrentJob(); /** * @return is the queue valid */ bool isValidQueue()const; /** * This is method is overriden from the base thread class and is * the main entry point of the thread */ virtual void run(); /** * Sets the done flag. * * @param done the value to set */ void setDone(bool done); /** * @return if the done flag is set */ bool isDone()const; /** * Cancels the thread */ virtual void cancel(); /** * @return true if the queue is empty * false otherwise. */ bool isEmpty()const; /** * @return true if a job is currently being processed * false otherwise. */ bool isProcessingJob()const; /** * @return true if there are still jobs to be processed * false otherwise. */ bool hasJobsToProcess()const; protected: /** * Internal method. If setJobQueue is set on this thread * it will auto start this thread. */ void startThreadForQueue(); /** * Will return the next job on the queue */ virtual std::shared_ptr nextJob(); bool m_doneFlag; mutable std::mutex m_threadMutex; std::shared_ptr m_jobQueue; std::shared_ptr m_currentJob; }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimMpi.h000066400000000000000000000025241352751253100222400ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimMpi.h 13602 2008-09-25 14:23:32Z gpotts $ #ifndef ossimMpi_HEADER #define ossimMpi_HEADER #include #include class OSSIM_DLL ossimMpi { public: static ossimMpi* instance(); ossim_float64 getTime()const; /*! * Typically called only one time */ void initialize(int* argc, char*** argv); /*! * Called only once when we would like to * shutdown mpi */ void finalize(); int getRank()const; int getNumberOfProcessors()const; void setEnabledFlag(bool flag); bool isEnabled()const; /** * @brief MPI Barrier method. * Blocks until all processes have reached this routine. * * If MPI is enabled this will call: MPI_Barrier( MPI_COMM_WORLD ); * else it will simply return. */ void barrier(); protected: ossimMpi(); // hide ossimMpi(const ossimMpi&); // hide void operator =(const ossimMpi&); // hide /*! * We will have only a single instance of * this class. */ static ossimMpi* theInstance; bool theEnabledFlag; }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimMpiMasterOverviewSequencer.h000066400000000000000000000042261352751253100270170ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Class definition for mpi master sequencer for building // overview files. // //---------------------------------------------------------------------------- // $Id: ossimMpiMasterOverviewSequencer.h 17194 2010-04-23 15:05:19Z dburken $ #ifndef ossimMpiMasterOverviewSequencer_HEADER #define ossimMpiMasterOverviewSequencer_HEADER #include #include #include #include /** * @class MPI master sequencer for building overview files. */ class OSSIM_DLL ossimMpiMasterOverviewSequencer : public ossimOverviewSequencer { public: /** default constructor */ ossimMpiMasterOverviewSequencer(); /** * This must be called. We can only initialize this * object completely if we know all connections * are valid. Some other object drives this and so the * connection's initialize will be called after. The job * of this connection is to set up the sequence. It will * default to the bounding rect. The area of interest can be * set to some other rectagle (use setAreaOfInterest). */ virtual void initialize(); /** * @brief Will set the internal pointers to the upperleft * tile number. To go to the next tile in the sequence * just call getNextTile. */ virtual void setToStartOfSequence(); /** * Will allow you to get the next tile in the sequence. * Note the last tile returned will be an invalid * ossimRefPtr. Callers should be able to do: * * ossimRefPtr id = sequencer->getNextTile(); * while (id.valid()) * { * doSomething; * id = sequencer->getNextTile(); * } * */ virtual ossimRefPtr getNextTile(); protected: /** virtual destructor */ virtual ~ossimMpiMasterOverviewSequencer(); int m_rank; int m_numberOfProcessors; }; #endif /* #ifndef ossimMpiMasterOverviewSequencer_HEADER */ ossim-Miami-2.9.1/include/ossim/parallel/ossimMpiSlaveOverviewSequencer.h000066400000000000000000000035441352751253100266400ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Class definition for mpi slave sequencer for building // overview files. // //---------------------------------------------------------------------------- // $Id: ossimMpiSlaveOverviewSequencer.h 17194 2010-04-23 15:05:19Z dburken $ #ifndef ossimMpiSlaveOverviewSequencer_HEADER #define ossimMpiSlaveOverviewSequencer_HEADER #include #include /** * @class MPI slave sequencer for building overview files. */ class OSSIM_DLL ossimMpiSlaveOverviewSequencer : public ossimOverviewSequencer { public: /** default constructor */ ossimMpiSlaveOverviewSequencer(); /** * @return Always false for this implementation. */ virtual bool isMaster()const; /** * This must be called. We can only initialize this * object completely if we know all connections * are valid. Some other object drives this and so the * connection's initialize will be called after. The job * of this connection is to set up the sequence. It will * default to the bounding rect. The area of interest can be * set to some other rectagle (use setAreaOfInterest). */ virtual void initialize(); /** * @brief Will set the internal pointers to the upperleft * tile number. To go to the next tile in the sequence * just call getNextTile. */ virtual void setToStartOfSequence(); /** * @brief This is a trigger to start resampling tiles. */ virtual void slaveProcessTiles(); protected: /** virtual destructor */ virtual ~ossimMpiSlaveOverviewSequencer(); int m_rank; int m_numberOfProcessors; }; #endif /* #ifndef ossimMpiSlaveOverviewSequencer_HEADER */ ossim-Miami-2.9.1/include/ossim/parallel/ossimMtDebug.h000066400000000000000000000023211352751253100230350ustar00rootroot00000000000000#ifndef ossimMtDebug_HEADER #define ossimMtDebug_HEADER //************************************************************************************************* //! For debugging purposes. To be removed with final release: //************************************************************************************************* class OSSIMDLLEXPORT ossimMtDebug { friend class ossimMultiThreadSequencer; friend class ossimImageChainMtAdaptor; friend class ossimImageHandlerMtAdaptor; public: ossimMtDebug() : handlerCacheEnabled (false), handlerUseFauxTile (false), chainDebugEnabled (false), chainSharedHandlers (false), seqDebugEnabled (false), seqTimedBlocksDt (0), seqMetricsEnabled (false), maxTileCacheSize (0) { m_instance = this; } static ossimMtDebug* instance() { if (m_instance == NULL) m_instance = new ossimMtDebug; return m_instance; } bool handlerCacheEnabled; bool handlerUseFauxTile; bool chainDebugEnabled; bool chainSharedHandlers; bool seqDebugEnabled; ossim_uint32 seqTimedBlocksDt; bool seqMetricsEnabled; ossim_uint32 maxTileCacheSize; private: static ossimMtDebug* m_instance; }; #endif ossim-Miami-2.9.1/include/ossim/parallel/ossimMultiThreadSequencer.h000066400000000000000000000141241352751253100256070ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // // $Id$ //************************************************************************************************** #ifndef ossimMultiThreadSequencer_HEADER #define ossimMultiThreadSequencer_HEADER #include #include #include #include #include #include #include #include //************************************************************************************************* //! This class manages the sequencing of tile requests across multiple threads. Note that multi- //! threading can only be achieved through the use of getNextTile() method for sequencing. //! Conventional getTiles will not be multi-threaded. //************************************************************************************************* class OSSIMDLLEXPORT ossimMultiThreadSequencer : public ossimImageSourceSequencer { public: ossimMultiThreadSequencer(ossimImageSource* inputSource=NULL, ossim_uint32 num_threads=0, ossimObject* owner=NULL); virtual ~ossimMultiThreadSequencer(); //! Overrides base class implementation. This call initiates the multi-threaded getTile jobs for //! the first N tiles. virtual void setToStartOfSequence(); //! Overrides base class in order to implement multi-threaded tile requests. The output tile //! should be available in the tile cache, otherwise, method waits until it becomes available. virtual ossimRefPtr getNextTile(ossim_uint32 resLevel=0); //! Specifies number of thread to support. Default behavior (if this method is never called) is //! to query the system for number of cores available. void setNumberOfThreads(ossim_uint32 num_threads); //! Fetches the number of threads being used. Useful when this object decides the quantity. ossim_uint32 getNumberOfThreads() const { return m_numThreads; } //! Accessed for performance logging. ossim_uint32 maxCacheSize() const { return m_maxCacheSize; } bool loadState(const ossimKeywordlist& kwl, const char* prefix); void setUseSharedHandlers(bool use_shared_handlers); void setCacheTileSize(ossim_uint32 cache_tile_size); void setUseCache(bool use_cache); // FOR DEBUG: ossim_uint32 d_maxCacheUsed; ossim_uint32 d_cacheEmptyCount; double d_idleTime1; double d_idleTime2; double d_idleTime3; double d_idleTime4; double d_idleTime5; double d_idleTime6; double d_jobGetTileT; double handlerGetTileT(); bool d_useSharedHandlers; ossim_uint32 d_cacheTileSize; bool d_useCache; protected: // Associates a job with a tile ID for quick access to its tile data when finished: typedef std::map > TileCache; //! Private class representing a getTile job. class ossimGetTileJob : public ossimJob { public: ossimGetTileJob(ossim_uint32 tile_id, ossim_uint32 chain_id, ossimMultiThreadSequencer& sequencer) : m_tileID(tile_id), m_chainID(chain_id), m_sequencer(sequencer), t_launchNewJob(true) {} protected: virtual void run(); private: ossim_uint32 m_tileID; ossim_uint32 m_chainID; ossimMultiThreadSequencer& m_sequencer; bool t_launchNewJob; //### for experimental purposes friend class ossimMultiThreadSequencer; //### for experimental purposes }; friend class ossimGetTileJob; //! Private class for getTile job callbacks. class ossimGetTileCallback : public ossimJobCallback { public: ossimGetTileCallback() {} virtual void finished(std::shared_ptr job) { if (job != NULL) job->finished(); } }; //! Queues up the optimum amount of jobs given the availability of thread chains and space in //! the output tile cache. void initJobs(); //! Access method to tile cache with scope lock to avoid multiple threads writing to //! the cache simultaneously. //! NOTE: chain_id being passed only for debug. To be removed. void setTileInCache(ossim_uint32 tile_id, ossimImageData* tile, ossim_uint32 chain_id, double dt /*for debug*/); //! Method to job queue with scope lock to avoid multiple threads modifying the queue //! simultaneously. void nextJob(ossim_uint32 chain_id); //! For debug -- thread-safe console output void print(std::ostringstream& msg) const; ossimRefPtr m_inputChain; //!< Same as base class' theInputConnection std::shared_ptr m_jobMtQueue; ossim_uint32 m_numThreads; std::shared_ptr m_callback; ossim_uint32 m_nextTileID; //!< ID of next tile to be threaded, different from base class' theCurrentTileNumber TileCache m_tileCache; //!< Saves tiles output by threaded jobs ossim_uint32 m_maxCacheSize; ossim_uint32 m_maxTileCacheFactor; mutable std::mutex m_cacheMutex; mutable std::mutex m_jobMutex; ossim_uint32 m_totalNumberOfTiles; ossim::Block m_getTileBlock; // #include #include #include #if defined(_WIN32) || defined(__WIN32__) #include #else #include #endif class OSSIM_DLL ossimDynamicLibrary : public ossimReferenced { public: ossimDynamicLibrary(); ossimDynamicLibrary(const ossimString& name); virtual ~ossimDynamicLibrary(); // return TRUE if the library was loaded successfully bool isLoaded() const { return theLibrary != 0; } // load the library with the given name (full or not), return TRUE on // success bool load(const ossimString& name); bool load(); // unload the library, also done automatically in dtor void unload(); // load a symbol from the library, return NULL if an error occured or // symbol wasn't found void *getSymbol(const ossimString& name) const; const ossimString& getName()const { return theLibraryName; } protected: // the handle to DLL or NULL #if defined(_WIN32) HINSTANCE theLibrary; #else void* theLibrary; #endif ossimString theLibraryName; }; #endif ossim-Miami-2.9.1/include/ossim/plugin/ossimPluginConstants.h000066400000000000000000000026671352751253100243600ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Constants file for ossim plugins. // // $Id: ossimPluginConstants.h 20616 2012-02-27 13:22:24Z gpotts $ //---------------------------------------------------------------------------- #ifndef ossimPluginConstants_HEADER #define ossimPluginConstants_HEADER /** * DLL IMPORT/EXORT SECTION */ #if defined(OSSIM_STATIC) # define OSSIMPLUGINSEXPORT # define OSSIMPLUGINSIMPORT # define OSSIMPLUGINSDLLEXPORT # define OSSIM_PLUGINS_DLL #elif defined(__MINGW32__) || defined(__CYGWIN__) || defined(_MSC_VER) || defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__) # define OSSIMPLUGINSEXPORT __declspec(dllexport) # define OSSIMPLUGINSIMPORT __declspec(dllimport) # ifdef OSSIMPLUGINSMAKINGDLL # define OSSIMPLUGINSDLLEXPORT OSSIMPLUGINSEXPORT # define OSSIM_PLUGINS_DLL OSSIMPLUGINSEXPORT # else # define OSSIMPLUGINSDLLEXPORT OSSIMPLUGINSIMPORT # define OSSIM_PLUGINS_DLL OSSIMPLUGINSIMPORT # endif #else /* not #if defined(_MSC_VER) */ # define OSSIMPLUGINSEXPORT # define OSSIMPLUGINSIMPORT # define OSSIMPLUGINSDLLEXPORT # define OSSIM_PLUGINS_DLL #endif /* #if defined(_MSC_VER) */ #endif /* #ifndef ossimPluginConstants_HEADER */ ossim-Miami-2.9.1/include/ossim/plugin/ossimPluginLibrary.h000066400000000000000000000017151352751253100240010ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimPluginLibrary.h 20694 2012-03-19 12:22:05Z dburken $ #ifndef ossimPluginLibrary_HEADER #define ossimPluginLibrary_HEADER 1 #include #include class OSSIMDLLEXPORT ossimPluginLibrary : public ossimDynamicLibrary { public: ossimPluginLibrary(); ossimPluginLibrary(const ossimString& name, const ossimString& options=""); virtual ~ossimPluginLibrary(); void initialize(); void finalize(); ossimString getDescription()const; void getClassNames(std::vector& classNames)const; void setOptions(const ossimString& options); protected: ossimString m_options; ossimSharedObjectInfo* m_info; }; #endif ossim-Miami-2.9.1/include/ossim/plugin/ossimSharedObjectBridge.h000066400000000000000000000034071352751253100246700ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimSharedObjectBridge.h 18967 2011-02-25 19:40:48Z gpotts $ #ifndef ossimSharedObjectBridge_HEADER #define ossimSharedObjectBridge_HEADER #include #include #include #include extern "C" { typedef const char* (*ossimSharedLibraryGetDescriptionPtr)(); typedef int (*ossimSharedLibraryGetNumberOfClassNamesPtr)(); typedef const char* (*ossimSharedLibraryGetClassNamesPtr)(int idx); typedef const char* (*ossimSharedLibraryGetIdPtr())(); typedef const char* (*ossimSharedLibraryGetOssimVersionStringPtr())(); typedef void (*ossimSharedLibraryRegisterPluginPtr())(); struct OSSIMDLLEXPORT ossimSharedObjectInfo { ossimSharedLibraryGetDescriptionPtr getDescription; ossimSharedLibraryGetNumberOfClassNamesPtr getNumberOfClassNames; ossimSharedLibraryGetClassNamesPtr getClassName; /* ossimSharedLibraryGetId getId; */ /* ossimSharedLibraryGetOssimVersionString getOssimVersion; */ /* ossimSharedLibraryRegisterPluginPtr registerPlugin; */ }; typedef void (*ossimSharedLibraryInitializePtr)(ossimSharedObjectInfo** info, const char* options); typedef void (*ossimSharedLibraryFinalizePtr)(); /* * these need to define these in your plugin. They are only here for clairity * * extern void ossimSharedLibraryInitialize(ossimSharedObjectInfo** info); * extern void ossimSharedLibraryFinalize(); */ } #endif ossim-Miami-2.9.1/include/ossim/plugin/ossimSharedPluginRegistry.h000066400000000000000000000031361352751253100253330ustar00rootroot00000000000000#ifndef ossimSharedPluginRegistry_HEADER #define ossimSharedPluginRegistry_HEADER #include #include #include #include #include #include class OSSIMDLLEXPORT ossimSharedPluginRegistry { public: virtual ~ossimSharedPluginRegistry(); static ossimSharedPluginRegistry* instance(); bool registerPlugin(const ossimFilename& filename, const ossimString& options="");//, bool insertFrontFlag=false); bool unregisterPlugin(int idx); bool unregisterPlugin(ossimPluginLibrary* plugin); const ossimPluginLibrary* getPlugin(const ossimFilename& filename)const; ossimPluginLibrary* getPlugin(const ossimFilename& filename); ossim_uint32 getIndex(const ossimPluginLibrary* lib)const; ossimPluginLibrary* getPlugin(ossim_uint32 idx); const ossimPluginLibrary* getPlugin(ossim_uint32 idx)const; ossim_uint32 getNumberOfPlugins()const; /** * Checks if filename is already loaded to avoid duplication. * * @param filename The file to check. * * @return true if any of the plugins match file name, false if not. */ bool isLoaded(const ossimFilename& filename) const; void printAllPluginInformation(std::ostream& out); protected: ossimSharedPluginRegistry(); ossimSharedPluginRegistry(const ossimSharedPluginRegistry&){} void operator = (const ossimSharedPluginRegistry&){} //static ossimSharedPluginRegistry* theInstance; std::vector > theLibraryList; }; #endif ossim-Miami-2.9.1/include/ossim/point_cloud/000077500000000000000000000000001352751253100210075ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/point_cloud/ossimGenericPointCloudHandler.h000066400000000000000000000026571352751253100271200ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id: ossimGenericPointCloudHandler.h 23654 2015-12-08 19:04:09Z gpotts $ #ifndef ossimGenericPointCloudHandler_HEADER #define ossimGenericPointCloudHandler_HEADER 1 #include #include #include #include #include class OSSIM_DLL ossimGenericPointCloudHandler : public ossimPointCloudHandler { public: ossimGenericPointCloudHandler(std::vector& ecef_points); ossimGenericPointCloudHandler(std::vector& ground_points); virtual ~ossimGenericPointCloudHandler(); virtual ossim_uint32 getNumPoints() const; virtual void getFileBlock(ossim_uint32 offset, ossimPointBlock& block, ossim_uint32 maxNumPoints=0xFFFFFFFF)const; virtual ossim_uint32 getFieldCode() const; virtual bool open(const ossimFilename& pointsFile); virtual void close(); protected: ossimGenericPointCloudHandler() {} ossimPointBlock m_pointBlock; }; #endif /* #ifndef ossimPdalReader_HEADER */ ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointBlock.h000077500000000000000000000073031352751253100243050ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** #ifndef ossimPointBlock_HEADER #define ossimPointBlock_HEADER 1 #include #include /* for ossim::isnan */ #include #include #include #include #include class ossimSource; /*************************************************************************************************** * Base class for all Point Cloud data sources, including input file handlers and processing nodes. **************************************************************************************************/ class OSSIMDLLEXPORT ossimPointBlock: public ossimDataObject { public: typedef std::vector< ossimRefPtr > PointList; explicit ossimPointBlock(ossimSource* owner=0, ossim_uint32 fields=0); ~ossimPointBlock(); /** Returns allocated size. The pointList may contain only null points if not assigned */ virtual ossim_uint32 size() const { return (ossim_uint32)m_pointList.size(); } bool empty() const { return (size() == 0); } /** * Returns OR'd mash-up of ossimPointRecord field codes being stored (or desired to be stored) */ ossim_uint32 getFieldCode() const; std::vector getFieldCodesAsList() const; /** * Initializes the desired fields to be stored. This will affect future getBlock() calls. If * the point list contains points from prior read, they will be deleted unless the points field * code matches the code argument. */ void setFieldCode(ossim_uint32 code); /** Adds single point to the tail of the list. */ virtual void addPoint(ossimPointRecord* point); virtual const ossimPointRecord* getPoint(ossim_uint32 point_offset) const; virtual ossimPointRecord* getPoint(ossim_uint32 point_offset); const ossimPointRecord* operator[](ossim_uint32 i) const { return getPoint(i); } ossimPointRecord* operator[](ossim_uint32 i) { return getPoint(i); } virtual const PointList& getPoints() const { return m_pointList; } virtual PointList& getPoints() { return m_pointList; } void getFieldMin(ossimPointRecord::FIELD_CODES field, ossim_float32& value) const; void getFieldMax(ossimPointRecord::FIELD_CODES field, ossim_float32& value) const; void getBounds(ossimGrect& block_bounds) const; virtual const ossimPointBlock& operator=(const ossimPointBlock &rhs); virtual ossimObject* dup() const; /** Resets any storage to empty. */ virtual void clear() { m_pointList.clear(); m_isNormalized = false; m_minMaxValid = false;} /** * Fulfills base class pure virtual. TODO: Needs to be correctly implemented */ virtual bool isEqualTo(const ossimDataObject& /*rhs*/, bool /*deep_copy*/) const { return false; } virtual ossim_uint32 getHashId() const { return 0; } virtual ossim_uint64 getDataSizeInBytes() const { return 0; }; virtual void initialize() {}; protected: ossimPointBlock(const ossimPointBlock& /* rhs */) {} void scanForMinMax() const; ossimPointRecord m_nullPCR; mutable ossimPointRecord m_minRecord; mutable ossimPointRecord m_maxRecord; mutable bool m_minMaxValid; PointList m_pointList; mutable ossim_uint32 m_fieldCode; // OR'd mash-up of ossimPointRecord::FIELD_CODES bool m_isNormalized; TYPE_DATA }; #endif /* #ifndef ossimPointBlock_HEADER */ ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointCloudGeometry.h000066400000000000000000000065511352751253100260360ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #ifndef ossimPointCloudGeometry_HEADER #define ossimPointCloudGeometry_HEADER #include #include #include #include #include /*************************************************************************************************** * This class represents the 3D geometry of the point cloud dataset. * NOTE: See below for details on position format. It is the responsibility of the derived * ossimPointCloudHandlers to convert the ray point positions into either geographic or map-meters * before storing a point in ossimPointCloudRecord. **************************************************************************************************/ class OSSIMDLLEXPORT ossimPointCloudGeometry : public ossimObject { public: enum PositionFormat { UNKNOWN, GEOGRAPHIC, // x=lon, y=lat, z=ellipsoid height MAP_PROJECTED, // x=easting, y=northing, z=ellipsoid height ECF_METERS // X, Y, Z (see base/ossimEcef) }; /** * Constructs from WKT specification. Since the projection units are unknown * when the bounds are established, the caller will not know the units of the point coordinates * for establishing the bounds. */ ossimPointCloudGeometry(const ossimString& wkt); /** * If arg left to default GEOGRAPHIC, this geometry is essentially unity transform except for a * possible datum change if requested. */ ossimPointCloudGeometry(PositionFormat f=GEOGRAPHIC) : m_format(f), m_projection(0), m_datum (ossimDatumFactory::instance()->wgs84()) {} ~ossimPointCloudGeometry() {} bool operator==(const ossimPointCloudGeometry& other) const; /** * While the raw point positions may be specified in the data file as either geographic, map * projected (feet or meters), or ECF meters, the point positions are stored in OSSIM as either as * geographic or map (meters) only. This method is used by the Point cloud handler object for * interpreting the input file's raw position format. */ PositionFormat getRawPosFormat() const { return m_format; } /** * This method will return either GEOGRAPHIC or MAP_PROJECTION. For the latter, the stored * coordinates will be in meters. */ PositionFormat getStoredPosFormat() const { return (m_format==ECF_METERS) ? GEOGRAPHIC : m_format; } const ossimMapProjection* getProjection() const { return m_projection.get(); } const ossimDatum* getDatum() const { return m_datum; } /** * Method converts a generic 3D point as stored in the argument ossim3Dpt object, * and converts it to an ossimGpt, using the preset datum provided in the argument gpt. */ void convertPos(const ossimDpt3d& stored_pos, ossimGpt& converted_gpos) const; private: PositionFormat m_format; ossimRefPtr m_projection; const ossimDatum* m_datum; TYPE_DATA }; #endif /* ossimPointCloudGeometry_HEADER */ ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointCloudHandler.h000066400000000000000000000063301352751253100256130ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #ifndef ossimPointCloudHandler_HEADER #define ossimPointCloudHandler_HEADER #include #include #include #include #include #include #include #include /** * Base class for all point-cloud file readers */ class OSSIMDLLEXPORT ossimPointCloudHandler: public ossimPointCloudSource { public: static ossim_uint32 DEFAULT_BLOCK_SIZE; ossimPointCloudHandler(); ossimPointCloudHandler(ossimObject* owner); virtual ~ossimPointCloudHandler(); /** * @brief Method to open input point cloud dataset. * @param imageFile Name of point data file to be opened. (or basename for multi-file sets.) * @return Returns true on success, false on error. */ virtual bool open(const ossimFilename& imageFile) = 0; /** * Closes the point cloud file(s). */ virtual void close() = 0; /** * Fetches up to maxNumPoints points starting at the dataset's in the order they * appear in the data file. Thread-safe implementation accepts an allocated block from the * calling method. caller can check block.size() to see if block is full. */ virtual void getFileBlock(ossim_uint32 offset, ossimPointBlock& block, ossim_uint32 maxNumPoints=0xFFFFFFFF) const = 0; /** * @see getFileBlock. */ virtual void getNextFileBlock(ossimPointBlock& block, ossim_uint32 maxNumPoints=0xFFFFFFFF) const; virtual void rewind() const { m_currentPID = 0; } /** * Fetches the block of points inside the block bounds. If the height components of the bounds * are NaN, then only the horizontal bounds are considered. Thread-safe version accepts data * block object from caller. The block object is cleared before points are pushed on the vector. * The block size will be non-zero if points were found. */ virtual void getBlock(const ossimGrect& bounds, ossimPointBlock& block) const; virtual const ossimPointRecord* getMinPoint() const { return m_minRecord.get(); } virtual const ossimPointRecord* getMaxPoint() const { return m_maxRecord.get(); } virtual void getBounds(ossimGrect& bounds) const; /** * Handler is always on the start of the pipeline */ virtual bool canConnectMyInputTo(ossim_int32, const ossimConnectableObject*) const { return false; } void normalizeBlock(ossimPointBlock& block); protected: ossimFilename m_inputFilename; ossimRefPtr m_geometry; ossimRefPtr m_minRecord; ossimRefPtr m_maxRecord; mutable ossim_uint32 m_currentPID; TYPE_DATA }; #endif /* ossimPointCloudHandler_HEADER */ ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointCloudHandlerFactory.h000066400000000000000000000025151352751253100271440ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #ifndef ossimPointCloudHandlerFactory_HEADER #define ossimPointCloudHandlerFactory_HEADER #include #include #include class ossimPointCloudHandler; class OSSIMDLLEXPORT ossimPointCloudHandlerFactory: public ossimObjectFactory { public: virtual ~ossimPointCloudHandlerFactory() {} virtual ossimPointCloudHandler* open(const ossimFilename& fileName) const = 0; virtual ossimPointCloudHandler* open(const ossimKeywordlist& kwl, const char* prefix = 0) const = 0; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix = 0) const { return (ossimObject*) open(kwl, prefix); } virtual ossimObject* createObject(const ossimString& typeName) const = 0; virtual void getSupportedExtensions(std::vector& extList) const = 0; protected: }; #endif /* ossimPointCloudHandlerFactory_HEADER */ ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointCloudHandlerRegistry.h000066400000000000000000000037441352751253100273520ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #ifndef ossimPointCloudHandlerRegistry_HEADER #define ossimPointCloudHandlerRegistry_HEADER 1 #include #include #include #include #include class OSSIMDLLEXPORT ossimPointCloudHandlerRegistry : public ossimObjectFactory, public ossimFactoryListInterface { public: virtual ~ossimPointCloudHandlerRegistry(); static ossimPointCloudHandlerRegistry* instance(); virtual ossimPointCloudHandler* open(const ossimFilename& fileName) const; virtual ossimPointCloudHandler* open(const ossimKeywordlist& kwl, const char* prefix = 0) const; virtual ossimRefPtr open(std::istream* str, std::streamoff restartPosition, bool youOwnIt) const; /*! * Creates an object given a type name. */ virtual ossimObject* createObject(const ossimString& typeName) const; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix = 0) const; virtual void getTypeNameList(std::vector& typeList)const; protected: ossimPointCloudHandlerRegistry(); const ossimPointCloudHandlerRegistry& operator=(const ossimPointCloudHandlerRegistry& rhs); static ossimPointCloudHandlerRegistry* m_instance; TYPE_DATA }; #endif /* ossimPointCloudHandlerRegistry_HEADER */ ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointCloudImageHandler.h000066400000000000000000000226611352751253100265630ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #ifndef ossimPointCloudImageSource_HEADER #define ossimPointCloudImageSource_HEADER #include #include #include #include #include #include #include class ossimImageData; class ossimTiffOverviewTileSource; class ossimPoinCloudHandler; /** * Class used for rendering point cloud data into a raster tile. It is derived from * ossimImageHandler so that it can be included in the available file formats for reading as * maintained by the ossimImageHandlerRegistry. This base class implementation exposes the data * elements represented by the base-class ossimPointCloudSource and the individual point base-class * ossimPointCloudRecord, namely, intensity, RGB color, elevation, and number of returns. * * For sensor systems providing additional renderable data items, a derived class will be required * to expose those components. */ class OSSIMDLLEXPORT ossimPointCloudImageHandler : public ossimImageHandler { public: enum Components { INTENSITY=0, HIGHEST, LOWEST, RETURNS, RGB, NUM_COMPONENTS /*not a component*/ }; ossimPointCloudImageHandler(); virtual ~ossimPointCloudImageHandler(); /** * @brief open method. * Satisfies ossimImageHandler::open pure virtual. * @return Returns true on success, false on error. * @note This method relies on the data member ossimImageData::theImageFile * being set. Callers should do a "setFilename" prior to calling this * method or use the ossimImageHandler::open that takes a file name and an * entry index. */ virtual bool open() override; /** * @brief is open method. * Satisfies ossimImageHandler::isOpen pure virtual. * @return true if open, false if not. */ virtual bool isOpen() const override { return m_pch.valid(); } /** * @brief Close method. */ virtual void close() override; /** * Returns a pointer to a tile given an origin representing the upper left * corner of the tile to grab from the image. * Satisfies pure virtual from TileSource class. */ ossimRefPtr getTile(const ossimIrect& rect, ossim_uint32 resLevel=0) override; /** * Method to get a tile. * @param result The tile to stuff. Note The requested rectangle in full * image space and bands should be set in the result tile prior to * passing. It will be an error if: * result.getNumberOfBands() != this->getNumberOfOutputBands() * @return true on success false on error. If return is false, result * is undefined so caller should handle appropriately with makeBlank or * whatever. */ bool getTile(ossimImageData* result, ossim_uint32 resLevel=0) override; /** * @brief Gets bands. * Satisfies ossimImageSource::getNumberOfInputBands pure virtual. * @retrun Number of bands. */ ossim_uint32 getNumberOfInputBands() const override; /** * @brief Gets lines. * Satisfies ossimImageHandler::getNumberOfLines pure virtual. * @param resLevel Reduced resolution level to return lines of. * Default = 0 * @return The number of lines for specified reduced resolution level. */ ossim_uint32 getNumberOfLines(ossim_uint32 resLevel = 0) const override; /** * @brief Gets samples. * Satisfies ossimImageHandler::getNumberOfSamples * @param resLevel Reduced resolution level to return samples of. * Default = 0 * @return The number of samples for specified reduced resolution level. */ ossim_uint32 getNumberOfSamples(ossim_uint32 resLevel = 0) const override; /** * @brief Gets tile width. * Satisfies ossimImageHandler::getImageTileWidth pure virtual. * @return The tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ ossim_uint32 getImageTileWidth() const override; /** * @brief Gets tile height. * Satisfies ossimImageHandler::getImageTileHeight pure virtual. * @return The tile width of the image or 0 if the image is not tiled. * Note: this is not the same as the ossimImageSource::getTileWidth which * returns the output tile width which can be different than the internal * image tile width on disk. */ ossim_uint32 getImageTileHeight() const override; /** @return The width of the output tile. */ ossim_uint32 getTileWidth() const override; /** @returns The height of the output tile. */ ossim_uint32 getTileHeight() const override; /** @return The output pixel type of the tile source. */ ossimScalarType getOutputScalarType() const override; /** * @brief Gets entry list. * This list reflects the data component entry list provided by the derived point-cloud handler. * This base class understands the basic (LIDAR-biased) entries: "Intensity", "RGB", * "Elevation", and "Return". If a sensor provides other components, then a derived image handler * will be needed to rasterize that data channel as well. * @param entryList This is the list to initialize with entry indexes. */ void getEntryList(std::vector& entryList) const override; void getEntryNames(std::vector& entryNames) const override; /** @return The current entry number. */ ossim_uint32 getCurrentEntry() const override; /** * @param entryIdx Entry number to select. * @return true if it was able to set the current entry and false otherwise. */ bool setCurrentEntry(ossim_uint32 entryIdx) override; /** @return "point-cloud" */ ossimString getShortName() const override; /** @return "ossim point cloud to image renderer" */ ossimString getLongName() const override; /** * Returns the image geometry object associated with this tile source or * NULL if non defined. The geometry contains full-to-local image * transform as well as projection (image-to-world). */ ossimRefPtr getImageGeometry() override; /** @return Min pixel value. */ double getMinPixelValue(ossim_uint32 band) const override; /** @return Min pixel value. */ double getMaxPixelValue(ossim_uint32 band) const override; /** @return Min pixel value. */ double getNullPixelValue(ossim_uint32 band) const override; /** @return The total number of decimation levels. */ ossim_uint32 getNumberOfDecimationLevels() const override; bool saveState(ossimKeywordlist& kwl, const char* prefix) const override; bool loadState(const ossimKeywordlist& kwl, const char* prefix) override; void getValidImageVertices(std::vector& validVertices, ossimVertexOrdering ordering, ossim_uint32 resLevel) const override; /** * The reader properties are: * -- the GSD ("meters_per_pixel") which overrides computed nominal GSD * -- the GSD factor ("gsd_factor") scales the computed nominal GSD, defaults to 1.0. * -- the active component as entry number ("entry") with possible values [0 - 4] corresponding * to "component" property (listed below) * -- the active component ("component") as string with possible values * "intensity", "highest", "lowest", "returns", or "rgb", respectively (case insensitive) */ void setProperty(ossimRefPtr property) override; ossimRefPtr getProperty(const ossimString& name) const override; /** * Permits backdoor for setting the input point cloud handler object. Useful for debug */ bool setPointCloudHandler(ossimPointCloudHandler* pch); /** @brief Get the GSD for resLevel. */ void getGSD(ossimDpt& gsd, ossim_uint32 resLevel) const; /** @brief Sets m_gsd data member and projection if projection is set. */ void setGSD( const ossim_float64& gsd ); protected: class PcrBucket { public: PcrBucket() : m_bucket(0), m_numSamples(0) {} PcrBucket(const ossim_float32* init_value, ossim_uint32 numBands); PcrBucket(const ossim_float32& R, const ossim_float32& G, const ossim_float32& B); explicit PcrBucket(const ossim_float32& init_value); ~PcrBucket(); ossim_float32* m_bucket; int m_numSamples; }; void initTile(); void addSample(std::map& accumulator, ossim_int32 index, const ossimPointRecord* sample); void normalize(std::map& accumulator); ossim_uint32 componentToFieldCode() const; ossimRefPtr m_pch; ossim_float32 m_maxPixel; ossim_float32 m_minPixel; ossimDpt m_gsd; ossim_float64 m_gsdFactor; ossimRefPtr m_tile; std::mutex m_mutex; Components m_activeComponent; std::vector m_componentNames; }; #endif /* ossimPointCloudRenderer_HEADER */ ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointCloudImageHandlerFactory.h000066400000000000000000000032011352751253100301000ustar00rootroot00000000000000/* * ossimPointCloudImageHandlerFactory.h * * Created on: Dec 8, 2014 * Author: okramer */ #ifndef ossimPointCloudImageHandlerFactory_HEADER #define ossimPointCloudImageHandlerFactory_HEADER #include class ossimPointCloudImageHandlerFactory: public ossimImageHandlerFactoryBase { public: ossimPointCloudImageHandlerFactory() {} virtual ~ossimPointCloudImageHandlerFactory(); static ossimPointCloudImageHandlerFactory* instance(); virtual ossimImageHandler* open(const ossimFilename& fileName, bool openOverview=true) const; virtual ossimImageHandler* open(const ossimKeywordlist& kwl, const char* prefix=0) const; virtual void getSupportedExtensions(ossimImageHandlerFactoryBase::UniqueStringList& extensionList) const; virtual ossimRefPtr openOverview(const ossimFilename& file ) const; virtual ossimObject* createObject(const ossimString& typeName)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; virtual void getTypeNameList(std::vector& typeList)const; virtual void getImageHandlersBySuffix(ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& ext)const; virtual void getImageHandlersByMimeType(ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& mimeType)const; private: static ossimPointCloudImageHandlerFactory* m_instance; TYPE_DATA }; #endif /* OSSIM_PLUGINS_PDAL_ossimPointCloudImageHandlerFactory_H_ */ ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointCloudSource.h000066400000000000000000000063301352751253100254760ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** #ifndef ossimPointCloudSource_HEADER #define ossimPointCloudSource_HEADER 1 #include #include /* for ossim::isnan */ #include #include #include #include #include #include /*************************************************************************************************** * Base class for all Point Cloud data sources, including input file handlers and processing nodes. **************************************************************************************************/ class OSSIMDLLEXPORT ossimPointCloudSource: public ossimSource { public: ossimPointCloudSource(ossimObject* owner = 0); virtual ~ossimPointCloudSource(); /** * Fetches the block of points inside the block bounds. If the height components of the bounds * are NaN, then only the horizontal bounds are considered. Thread-safe version accepts data * block object from caller. */ virtual void getBlock(const ossimGrect& bounds, ossimPointBlock& block) const = 0; /** * Returns the total number of points in the dataset (not just the block returned in getPoints) */ virtual ossim_uint32 getNumPoints() const = 0; /** * Assigns the two points with fields representing the extremes of the dataset. Useful for * normalizing and establishing bounds. */ virtual const ossimPointRecord* getMinPoint() const; virtual const ossimPointRecord* getMaxPoint() const; /** * Fetches the data fields ids available from this source, OR'd together for testing against * specific field (@see ossimPointRecord::FIELD_CODES). e.g. (though should use hasField()), * * bool hasIntensity = getFields() & ossimPointRecord::Intensity; */ virtual ossim_uint32 getFieldCode() const; /** * Sets the data fields ID of interest for this source, and all input sources connected to this. * This is an OR'd mash-up of @see ossimPointRecord::FIELD_CODES */ virtual void setFieldCode (ossim_uint32 fieldCode); /** * Returns true if the data field is available from this source. The argument can be OR'd * together for testing multiple fileds simultaneously. Example: * * bool hasRGB = hasField(ossimPointRecord::Red|ossimPointRecord::Green|ossimPointRecord::Blue); */ virtual bool hasFields(ossim_uint32 id) const { return getFieldCode()&id; } /** Special for convenience */ bool hasRGB() const { return hasFields(ossimPointRecord::Red|ossimPointRecord::Green|ossimPointRecord::Blue); } virtual bool canConnectMyInputTo(ossim_int32, const ossimConnectableObject*) const; protected: ossimPointCloudSource(const ossimPointCloudSource& rhs); ossimPointRecord m_nullPCR; TYPE_DATA }; #endif /* #ifndef ossimPointCloudSource_HEADER */ ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointCloudUtilityFilter.h000066400000000000000000000025661352751253100270560ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #ifndef ossimPointCloudUtilityFilter_HEADER #define ossimPointCloudUtilityFilter_HEADER #include #include #include #include #include #include #include #include class ossimImageData; class ossimPointCloudTool; class OSSIMDLLEXPORT ossimPointCloudUtilityFilter : public ossimImageSourceFilter { public: ossimPointCloudUtilityFilter( ossimPointCloudTool* pc_util); virtual ~ossimPointCloudUtilityFilter() {} virtual bool getTile(ossimImageData* result, ossim_uint32 resLevel); ossimScalarType getOutputScalarType() const { return OSSIM_FLOAT32; } virtual ossim_uint32 getNumberOfOutputBands() const { return 1; } virtual ossimRefPtr getImageGeometry(); protected: ossimRefPtr m_util; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/point_cloud/ossimPointRecord.h000066400000000000000000000066031352751253100244700ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: MIT -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id: ossimPointRecord.h 23352 2015-05-29 17:38:12Z okramer $ #ifndef ossimPointCloudRecord_HEADER #define ossimPointCloudRecord_HEADER #include #include #include #include #include #include /*************************************************************************************************** * This class represents a single sample (point) in a point cloud. **************************************************************************************************/ class OSSIMDLLEXPORT ossimPointRecord : public ossimReferenced { public: // Field codes intended to be OR'd to indicate fields present in point record. All point records // have at least an X, Y, Z position so those fields are implied. enum FIELD_CODES // and associated types { Intensity = 0x0008, // float 32 ReturnNumber = 0x0010, // unsigned int 32 NumberOfReturns = 0x0020, // unsigned int 32 Red = 0x0040, // float 32 Green = 0x0080, // float 32 Blue = 0x0100, // float 32 GpsTime = 0x0200, // unsigned long Unix epoch (microsec from 01/01/1970) Infrared = 0x0400, // float 32 All = 0x0777 }; ossimPointRecord(ossim_uint32 fields_code=0); ossimPointRecord(const ossimPointRecord& pcr); ossimPointRecord(const ossimGpt& pos); /** Creates a point record with fields set to null values */ ~ossimPointRecord(); ossimPointRecord& operator=(const ossimPointRecord& pcr); ossim_uint32 getPointId() const { return m_pointId; } void setPointId(ossim_uint32 id) {m_pointId = id; } /** * Returns the 3D position vector in the dataset's coodinate reference system (available from * the ossimPointCloudSource object. This is either map/meters (x, y, z) or geog (lat, lon, hgt). * Refer to the ossimPointCloudGeometry::getStoredPosFormat() available from the associated * ossimPointCloudSource->getGeometry() */ const ossimGpt& getPosition() const { return m_position; } void setPosition(const ossimGpt& p) { m_position = p; } /** Argument can be mash-up of OR'd codes for check of multiple fields. Returns TRUE if ALL * fields are present. */ virtual bool hasFields(ossim_uint32 code_mashup) const; /** Returns mash-up of OR'd codes of multiple fields being stored*/ virtual ossim_uint32 getFieldCode() const; /** Return the float value of the requested field */ ossim_float32 getField(FIELD_CODES fc) const; const std::map& getFieldMap() const { return m_fieldMap; } void setField(FIELD_CODES fc, ossim_float32 value); friend std::ostream& operator << (std::ostream& ostr, const ossimPointRecord& p); /** * Initializes point to undefined state: */ void clear(); bool isValid() const; protected: ossim_uint32 m_pointId; ossimGpt m_position; std::map m_fieldMap; }; #endif /* ossimPointCloudRecord_HEADER */ ossim-Miami-2.9.1/include/ossim/projection/000077500000000000000000000000001352751253100206445ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/projection/ossimAdjMapModel.h000066400000000000000000000120161352751253100242050ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, Oscar Kramer, all rights reserved. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: // // Special "sensor model" that provides a conventional map projection but // with additional capability for adjusting the map x,y coordinates with // offset, scale, and rotation transform. Funtions to control notifications, // information and error output. // //---------------------------------------------------------------------------- // $Id: ossimAdjMapModel.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimAdjMapModel_HEADER #define ossimAdjMapModel_HEADER #include #include #include #include #include using namespace NEWMAT; class ossimMapProjection; //---------------------------------------------------------------------------- // CLASS DESCRIPTION: ossimAdjMapModel //! Special "sensor model" that provides a conventional map projection but with // additional //! capability for adjusting the map x,y coordinates with offset, scale, and // rotation transform. //---------------------------------------------------------------------------- class OSSIMDLLEXPORT ossimAdjMapModel : public ossimSensorModel { public: //! Constructs to uninitialized state (needed by factory). ossimAdjMapModel(); //! Constructs with map projection and image rectangle size. ossimAdjMapModel(ossimMapProjection* map_proj, const ossimIpt& image_size); //! Copy constructor ossimAdjMapModel(const ossimAdjMapModel& copy_this); //! Constructs given geom KWL. ossimAdjMapModel(const ossimKeywordlist& kwl, const char* prefix); //! Constructs given geom filename. ossimAdjMapModel(const ossimFilename& geom_filename); //! Initializes base class data members after map model established. // Returns TRUE if all's well. bool initializeFromMap(); //! Returns pointer to a new instance, copy of this. virtual ossimObject* dup() const; //! Extends base-class implementation. Dumps contents of object to std::ostream. virtual std::ostream& print(std::ostream& out) const; //! Fulfills ossimObject base-class pure virtuals. Loads and saves geometry //! KWL files. Returns true if successful. virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Writes a template of geom keywords processed by loadState and saveState // to output stream. static void writeGeomTemplate(std::ostream& os); //! Overrides base class pure virtual. virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const; //! Overrides base class virtual. virtual void lineSampleToWorld(const ossimDpt& image_point, ossimGpt& worldPoint) const; //! Rigorous inverse transform implented, overrides base-class' iterative // solution. virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; //! Following a change to the adjustable parameter set, this virtual is // called to permit //! instances to compute derived quantities after parameter change. virtual void updateModel(); //! Initializes adjustable parameters to their default values. //! Overrides ossimAdjustableParameterInterface virtual method. virtual void initAdjustableParameters(); //! Fetches the GSD from the internal map projection. virtual ossimDpt getMetersPerPixel () const; //! Enumeration for adjustable parameter positions in theAdjParams vector enum AdjParamIndex { OFFSET_X = 0, // meters OFFSET_Y, // meters ROTATION, // degrees CCW SCALE_X, // ratio SCALE_Y, // ratio NUM_ADJ_PARAMS // not an index }; /*! * ossimOptimizableProjection */ inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM) private: //! Destructor only deletes the map projection. virtual ~ossimAdjMapModel(); //! This is the vector of UNNORMALIZED, BIASED parameters as used in the //! model. The collection of normalized, 0-biased, parameters used in //! registration are found in the //! ossimAdjustableParameterInterface and related classes. //! The quantities here are computed given the base class quantities. ColumnVector theAdjParams; ossimRefPtr theMapProjection; double theCosTheta; double theSinTheta; TYPE_DATA }; #endif /* End of "#ifndef ossimAdjMapModel_HEADER" */ ossim-Miami-2.9.1/include/ossim/projection/ossimAffineProjection.h000066400000000000000000000071731352751253100253250ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // // DESCRIPTION: // Contains declaration of class ossimAffineProjection. This is an // implementation of a warping interpolation model. // //***************************************************************************** // $Id: ossimAffineProjection.h 17207 2010-04-25 23:21:14Z dburken $ #ifndef ossimAffineProjection_HEADER #define ossimAffineProjection_HEADER #include #include #include #include #include /*!**************************************************************************** * * CLASS: ossimAffineProjection * *****************************************************************************/ class ossimAffineProjection : public ossimProjection { public: /*! * Default Contructor: */ ossimAffineProjection(); /*! * Primary constructor accepting pointer to the underlying client projection. */ ossimAffineProjection(ossimProjection* client); /*! * Constructor accepts OSSIM keywordlist geometry file. */ ossimAffineProjection(const ossimKeywordlist& geom_kwl, const char* prefix=NULL); ~ossimAffineProjection(); /*! * METHOD: worldToLineSample() * Performs the forward projection from ground point to line, sample. */ virtual void worldToLineSample(const ossimGpt& worldPoint, ossimDpt& lineSampPt) const; /*! * METHOD: lineSampleToWorld() * Performs the inverse projection from line, sample to ground (world): */ virtual void lineSampleToWorld(const ossimDpt& lineSampPt, ossimGpt& worldPt) const; /*! * Performs the inverse projection from line, sample to ground, bypassing * reference to elevation surface: */ virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& hgtEllipsoid, ossimGpt& worldPt) const; /*! * Extends base-class implementation. Dumps contents of object to std::ostream. */ virtual std::ostream& print(std::ostream& out) const; friend std::ostream& operator<<(std::ostream& os, const ossimAffineProjection& m); /*! * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry * KWL files. Returns true if successful. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /*! * Returns pointer to a new instance, copy of this. */ virtual ossimObject* dup() const; /*! * Returns projection's ground point origin. That is the GP corresponding * to line=0, sample=0. */ virtual ossimGpt origin() const; /*! * Compares this instance with arg projection. NOT IMPLEMENTED. */ virtual bool operator==(const ossimProjection& /* projection */) const { return false; } virtual ossimDpt getMetersPerPixel() const; /** * @brief Implementation of pure virtual * ossimProjection::isAffectedByElevation method. * @return false. */ virtual bool isAffectedByElevation() const { return false; } protected: /*! * Data Members: */ ossimRefPtr theClientProjection; ossimRefPtr theAffineTransform; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimAlbersProjection.h000066400000000000000000000237061352751253100253450ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Albers projection code. //******************************************************************* // $Id: ossimAlbersProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimAlbersProjection_HEADER #define ossimAlbersProjection_HEADER #include //! Albers Equal Area Conic Projection /*! * A basic conic projection developed by H.C. Albers. Classified as a * conic and equal area. A graphic can be found at: * http://everest.hunter.cuny.edu/mp/pbander/albers.gif */ class OSSIMDLLEXPORT ossimAlbersProjection : public ossimMapProjection { public: ossimAlbersProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(), const ossimGpt& origin = ossimGpt()); /** * @param ellipsoid * @param origin latitude longitude in decimal degrees. * @param stdParallel1 First parallel in DEGREES. * @param stdParallel2 Second parallel in DEGREES. * @param falseEasting False easting in meters. * @param falseNorthing False northing in meters. */ ossimAlbersProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double stdParallel1, double stdParallel2, double falseEasting, double falseNorthing); ossimObject *dup()const; virtual ossimDpt forward(const ossimGpt &worldPoint) const; virtual ossimGpt inverse(const ossimDpt &projectedPoint)const; virtual void update(); /*! * The passed in Argument is in degrees and will convert it to radians * for Geotrans. Update is then called so we can pre-compute paramters. */ void setStandardParallel1(double degree); /*! * The passed in Argument is in degrees and will convert it to radians * for Geotrans. Update is then called so we can pre-compute paramters */ void setStandardParallel2(double degree); /*! * Will allow you to set both parallels. both are passed in degrees. */ void setStandardParallels(double parallel1Degree, double prallel2Degree); /*! * SetFalseEasting. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseEasting(double falseEasting); /*! * SetFalseNorthing. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseNorthing(double falseNorthing); /*! * Sets both false easting and northing values. The values are * expected to be in meters. * Update is then called so we can pre-compute paramters */ void setFalseEastingNorthing(double falseEasting, double falseNorthing); /*! * Allows one to set all parameters for this projections. parallels are in * degrees and easting northings are in meters. * Update is then called so we can pre-compute paramters. */ void setParameters(double parallel1, double parallel2, double falseEasting, double falseNorthing); /** @returns the first standard parallel in decimal degrees. */ virtual double getStandardParallel1() const; /** @returns the second standard parallel in decimal degrees. */ virtual double getStandardParallel2() const; void setDefaults(); /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Returns TRUE if principal parameters are within epsilon tolerance. virtual bool operator==(const ossimProjection& projection) const; protected: virtual ~ossimAlbersProjection(); //________________________GEOTRANS__________________________ // mutable double Albers_a; /* Semi-major axis of ellipsoid in meters */ mutable double Albers_f; /* Flattening of ellipsoid */ mutable double es; /* Eccentricity of ellipsoid */ mutable double es2; /* Eccentricity squared */ mutable double C; /* constant c */ mutable double rho0; /* height above ellipsoid */ mutable double n; /* ratio between meridians */ mutable double Albers_a_OVER_n; /* Albers_a / n */ mutable double one_MINUS_es2; /* 1 - es2 */ mutable double two_es; /* 2 * es */ /* Albers Projection Parameters */ mutable double Albers_Origin_Lat; /* Latitude of origin in radians */ mutable double Albers_Origin_Long; /* Longitude of origin in radians */ mutable double Albers_Std_Parallel_1; mutable double Albers_Std_Parallel_2; mutable double Albers_False_Easting; mutable double Albers_False_Northing; mutable double Albers_Delta_Northing; mutable double Albers_Delta_Easting; /*! * The function Set_Albers_Parameters receives the ellipsoid parameters and * projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise ALBERS_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection (central meridian) * Std_Parallel_1 : First standard parallel (input) * Std_Parallel_2 : Second standard parallel (input) * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ long Set_Albers_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double Std_Parallel_1, double Std_Parallel_2, double False_Easting, double False_Northing); /*! * The function Get_Albers_Parameters returns the current ellipsoid * parameters, and Albers projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * Std_Parallel_1 : First standard parallel (output) * Std_Parallel_2 : Second standard parallel (output) * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ void Get_Albers_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *Std_Parallel_1, double *Std_Parallel_2, double *False_Easting, double *False_Northing)const; /*! * The function Convert_Geodetic_To_Albers converts geodetic (latitude and * longitude) coordinates to Albers projection (easting and northing) * coordinates, according to the current ellipsoid and Albers projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise ALBERS_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ long Convert_Geodetic_To_Albers (double Latitude, double Longitude, double *Easting, double *Northing)const; /*! * The function Convert_Albers_To_Geodetic converts Albers projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Albers projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise ALBERS_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ long Convert_Albers_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const; /* * RTTI information defined in data_types/rtti.h */ TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimAlphaSensor.h000066400000000000000000000064351352751253100243170ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Dave Hicks // // Description: Alpha Sensor Base Class // //******************************************************************* // $Id$ #ifndef ossimAlphaSensor_HEADER #define ossimAlphaSensor_HEADER 1 #include class OSSIM_DLL ossimAlphaSensor : public ossimSensorModel { public: ossimAlphaSensor(); ossimAlphaSensor(const ossimAlphaSensor& src); virtual ossimObject* dup()const; virtual void lineSampToWorld(const ossimDpt& image_point, ossimGpt& worldPoint) const; virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const; virtual void updateModel(); inline virtual bool useForward()const {return true;} virtual void initAdjustableParameters(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; void setFov(const double fov); void setRollBias(const double rollBias); void setPitchBias(const double pitchBias); void setHeadingBias(const double headingBias); void setSlitRot(const double slitRot); void setRollPoly(const std::vector< ossim_float64 > rollPoly); void setPitchPoly(const std::vector< ossim_float64 > pitchPoly); void setHeadingPoly(const std::vector< ossim_float64 > headingPoly); void setLonPoly(const std::vector< ossim_float64 > lonPoly); void setLatPoly(const std::vector< ossim_float64 > latPoly); void setAltPoly(const std::vector< ossim_float64 > altPoly); void setScanPoly(const std::vector< ossim_float64 > scanPoly); void getPositionOrientation(const ossim_float64& line, ossimEcefPoint& pos, NEWMAT::Matrix& cam2EcfRot)const; ossimEcefPoint getCameraPosition(const ossim_float64& line)const; NEWMAT::Matrix getPlatform2LocalRot(const ossim_float64& line)const; ossim_float64 evalPoly(const std::vector& polyCoef, const ossim_float64& line)const; protected: NEWMAT::Matrix formHPRmat(const ossim_float64& roll, const ossim_float64& pitch, const ossim_float64& heading)const; NEWMAT::Matrix formLLAmat(const ossim_float64& lat, const ossim_float64& lon, const ossim_float64& az)const; ossim_float64 m_rollBias; ossim_float64 m_pitchBias; ossim_float64 m_headingBias; ossim_float64 m_fov; ossim_float64 m_slitRot; ossim_float64 m_focalLength; std::vector< ossim_float64 > m_rollPoly; std::vector< ossim_float64 > m_pitchPoly; std::vector< ossim_float64 > m_headingPoly; std::vector< ossim_float64 > m_lonPoly; std::vector< ossim_float64 > m_latPoly; std::vector< ossim_float64 > m_altPoly; std::vector< ossim_float64 > m_scanPoly; // Bias rotation matrix NEWMAT::Matrix m_cam2Platform; ossim_float64 m_adjustedFocalLength; TYPE_DATA }; #endif // #ifndef ossimAlphaSensor_HEADER ossim-Miami-2.9.1/include/ossim/projection/ossimAlphaSensorHRI.h000066400000000000000000000026331352751253100246560ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Dave Hicks // // Description: Alpha HRI Sensor Model // //******************************************************************* // $Id$ #ifndef ossimAlphaSensorHRI_HEADER #define ossimAlphaSensorHRI_HEADER 1 #include class ossimAlphaSensorSupportData; class OSSIM_DLL ossimAlphaSensorHRI : public ossimAlphaSensor { public: ossimAlphaSensorHRI(); ossimAlphaSensorHRI(const ossimAlphaSensorHRI& src); virtual ossimObject* dup()const; virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; virtual void updateModel(); virtual void initAdjustableParameters(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * @brief Initializes model from support data and calls update Model on * success. * @param supData * @return true on success, false on error. */ virtual bool initialize( const ossimAlphaSensorSupportData& supData ); protected: TYPE_DATA }; #endif // #ifndef ossimAlphaSensorHRI_HEADER ossim-Miami-2.9.1/include/ossim/projection/ossimAlphaSensorHSI.h000066400000000000000000000027331352751253100246600ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Dave Hicks // // Description: Alpha HSI Sensor Model // //******************************************************************* // $Id$ #ifndef ossimAlphaSensorHSI_HEADER #define ossimAlphaSensorHSI_HEADER 1 #include class ossimAlphaSensorSupportData; class OSSIM_DLL ossimAlphaSensorHSI : public ossimAlphaSensor { public: ossimAlphaSensorHSI(); ossimAlphaSensorHSI(const ossimAlphaSensorHSI& src); virtual ossimObject* dup()const; virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; virtual void updateModel(); virtual void initAdjustableParameters(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; ossim_float64 getScanAngle(const ossim_float64& line)const; /** * @brief Initializes model from support data and calls update Model on * success. * @param supData * @return true on success, false on error. */ virtual bool initialize( const ossimAlphaSensorSupportData& supData ); protected: TYPE_DATA }; #endif // #ifndef ossimAlphaSensorHSI_HEADER ossim-Miami-2.9.1/include/ossim/projection/ossimApplanixEcefModel.h000066400000000000000000000072461352751253100254210ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // MIT // // Author: Garrett Potts // //******************************************************************* // $Id: ossimApplanixEcefModel.h 20496 2012-01-25 17:15:43Z gpotts $ #ifndef ossimApplanixEcefModel_HEADER #define ossimApplanixEcefModel_HEADER #include #include #include class OSSIM_DLL ossimApplanixEcefModel : public ossimSensorModel { public: ossimApplanixEcefModel(); ossimApplanixEcefModel(const ossimDrect& imageRect, // center in image space const ossimGpt& platformPosition, double roll, double pitch, double heading, const ossimDpt& principalPoint, // in millimeters double focalLength, // in millimeters const ossimDpt& pixelSize); // in millimeters ossimApplanixEcefModel(const ossimApplanixEcefModel& src); virtual ossimObject* dup()const; virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; void lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const; virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const; virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; virtual void updateModel(); void setPrincipalPoint(ossimDpt principalPoint); virtual bool insideImage(const ossimDpt& p) const { /* return( (p.u>=(0.0-FLT_EPSILON)) && */ /* (p.u<=(double)(theImageSize.u-(1-FLT_EPSILON))) && */ /* (p.v>=(0.0-FLT_EPSILON)) && */ /* (p.v<=(double)(theImageSize.v-(1-FLT_EPSILON))) ); */ // if it's close to the edge we will consider it inside the image // return theImageClipRect.pointWithin(p, theImageClipRect.width()); } void setRollPitchHeading(double roll, double pitch, double heading); void setPixelSize(const ossimDpt& pixelSize); void setImageRect(const ossimDrect& rect); void setFocalLength(double focalLength); void setPlatformPosition(const ossimGpt& gpt); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void initAdjustableParameters(); /*! * ossimOptimizableProjection */ // inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM) inline virtual bool useForward()const {return false;} //!ground to image faster (you don't need DEM) virtual bool setupOptimizer(const ossimString& init_file); //!uses file path to init model protected: NEWMAT::Matrix theCompositeMatrix; NEWMAT::Matrix theCompositeMatrixInverse; double theRoll; double thePitch; double theHeading; ossimDpt thePrincipalPoint; ossimDpt thePixelSize; double theFocalLength; ossimEcefPoint theEcefPlatformPosition; ossimRefPtr theLensDistortion; ossimEcefPoint theAdjEcefPlatformPosition; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimApplanixUtmModel.h000066400000000000000000000054761352751253100253270ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // MIT // // Author: Garrett Potts // //******************************************************************* // $Id: ossimApplanixUtmModel.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimApplanixUtmModel_HEADER #define ossimApplanixUtmModel_HEADER #include #include #include class OSSIM_DLL ossimApplanixUtmModel : public ossimSensorModel { public: ossimApplanixUtmModel(); ossimApplanixUtmModel(const ossimApplanixUtmModel& src); virtual ossimObject* dup()const; virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; void lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const; virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const; virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; virtual void updateModel(); void setPrincipalPoint(ossimDpt principalPoint); void setPixelSize(const ossimDpt& pixelSize); void setImageRect(const ossimDrect& rect); void setFocalLength(double focalLength); void setPlatformPosition(const ossimGpt& gpt); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void initAdjustableParameters(); /*! * ossimOptimizableProjection */ // inline virtual bool useForward()const {return false;} inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM) //TBC virtual bool setupOptimizer(const ossimString& init_file); //!uses file path to init model protected: NEWMAT::Matrix theCompositeMatrix; NEWMAT::Matrix theCompositeMatrixInverse; double theOmega; double thePhi; double theKappa; double theBoreSightTx; double theBoreSightTy; double theBoreSightTz; ossimDpt thePrincipalPoint; ossimDpt thePixelSize; double theFocalLength; ossimEcefPoint theEcefPlatformPosition; ossimGpt thePlatformPosition; ossim_int32 theUtmZone; ossim_int8 theUtmHemisphere; ossimDpt3d theUtmPlatformPosition; ossimEcefVector theShiftValues; ossimRefPtr theLensDistortion; ossimEcefPoint theAdjEcefPlatformPosition; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimAzimEquDistProjection.h000066400000000000000000000175271352751253100263400ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Equidistant Cylinder projection code. //******************************************************************* // $Id: ossimAzimEquDistProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimAzimEquDistProjection_HEADER #define ossimAzimEquDistProjection_HEADER #include class OSSIMDLLEXPORT ossimAzimEquDistProjection : public ossimMapProjection { public: ossimAzimEquDistProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(), const ossimGpt& origin = ossimGpt()); ossimAzimEquDistProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing); ossimAzimEquDistProjection(const ossimAzimEquDistProjection& rhs) { *this = rhs; } virtual ossimObject *dup()const { return new ossimAzimEquDistProjection(*this); } virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const; virtual ossimDpt forward(const ossimGpt &latLon)const; virtual void update(); double getFalseEasting()const{return Azeq_False_Easting;} double getFalseNorthing()const{return Azeq_False_Northing;} /*! * SetFalseEasting. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseEasting(double falseEasting); /*! * SetFalseNorthing. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseNorthing(double falseNorthing); /*! * Sets both false easting and northing values. The values are * expected to be in meters. * Update is then called so we can pre-compute paramters */ void setFalseEastingNorthing(double falseEasting, double falseNorthing); /*! * Will initialize all parameters to a default values and then call * update for pre-computations. */ void setDefaults(); /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: virtual ~ossimAzimEquDistProjection(){} mutable double abs_Azeq_Origin_Lat; mutable double Azeq_a; /* Semi-major axis of ellipsoid in meters */ mutable double Azeq_f; /* Flattening of ellipsoid */ mutable double Ra; /* Spherical Radius */ mutable double Sin_Azeq_Origin_Lat; mutable double Cos_Azeq_Origin_Lat; mutable double Azeq_Origin_Lat; /* Latitude of origin in radians */ mutable double Azeq_Origin_Long; /* Longitude of origin in radians */ mutable double Azeq_False_Northing; /* False northing in meters */ mutable double Azeq_False_Easting; /* False easting in meters */ mutable double Azeq_Delta_Northing; mutable double Azeq_Delta_Easting; /*! * The function Set_Azimuthal_Equidistant_Parameters receives the ellipsoid * parameters and projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise AZEQ_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ long Set_Azimuthal_Equidistant_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing); /*! * The function Get_Azimuthal_Equidistant_Parameters returns the current ellipsoid * parameters and Azimuthal Equidistant projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ void Get_Azimuthal_Equidistant_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const; /*! * The function Convert_Geodetic_To_Azimuthal_Equidistant converts geodetic (latitude and * longitude) coordinates to Azimuthal Equidistant projection (easting and northing) * coordinates, according to the current ellipsoid and Azimuthal Equidistant projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise AZEQ_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ long Convert_Geodetic_To_Azimuthal_Equidistant (double Latitude, double Longitude, double *Easting, double *Northing)const; /*! * The function Convert_Azimuthal_Equidistant_To_Geodetic converts Azimuthal Equidistant * projection (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Azimuthal Equidistant projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise AZEQ_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ long Convert_Azimuthal_Equidistant_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimBilinearProjection.h000066400000000000000000000107451352751253100256610ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimBilinearProjection.h 17497 2010-06-02 01:43:43Z gpotts $ #ifndef ossimBilinearProjection_HEADER #define ossimBilinearProjection_HEADER #include #include #include #include #include #include class OSSIM_DLL ossimBilinearProjection : public ossimProjection, public ossimOptimizableProjection { public: ossimBilinearProjection(); ossimBilinearProjection(const ossimBilinearProjection& rhs); ossimBilinearProjection(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll, const ossimGpt& ulg, const ossimGpt& urg, const ossimGpt& lrg, const ossimGpt& llg); virtual ossimObject *dup()const; virtual ossimGpt origin()const; virtual void worldToLineSample(const ossimGpt& worldPoint, ossimDpt& lineSampPt) const; /*! * METHOD: lineSampleToWorld() * Performs the inverse projection from line, sample to ground (world): */ virtual void lineSampleToWorld(const ossimDpt& lineSampPt, ossimGpt& worldPt) const; /*! * METHOD: lineSampleHeightToWorld * This is the pure virtual that projects the image point to the given * elevation above ellipsoid, thereby bypassing reference to a DEM. Useful * for projections that are sensitive to elevation (such as sensor models). */ virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& heightAboveEllipsoid, ossimGpt& worldPt) const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool operator==(const ossimProjection& projection) const; virtual ossimDpt getMetersPerPixel() const; virtual std::ostream& print(std::ostream& out) const; /*! * METHOD: setTiePoints * add any number of tie points and calculate bilinear fit * returns the ground error variance (=RMS^2), in meters^2 */ virtual ossim_float64 setTiePoints(const std::vector& lsPt, const std::vector& geoPt); /* * optimizable interface */ virtual bool setupOptimizer(const ossimString& setup); inline virtual bool useForward()const {return false;} //! better go from image to ground, also means that errors variance are in squared meters virtual ossim_uint32 degreesOfFreedom()const; virtual double optimizeFit(const ossimTieGptSet& tieSet, double* targetVariance=0); /** * @brief Implementation of pure virtual * ossimProjection::isAffectedByElevation method. * @return false. */ virtual bool isAffectedByElevation() const { return false; } //! Access method for tie point information void getTiePoints(std::vector& lsPt, std::vector& geoPt) const; protected: virtual ~ossimBilinearProjection(); void initializeBilinear(); /** * Checks theLineSamplePt for nans. * @return true if any point has a nan. * @note If theLineSamplePt size is 0 this returns false. */ bool dPtsHaveNan() const; /** * Checks theGeographicPt for nans. * @return true if any point has a nan. * @note If theLineSamplePt size is 0 this returns false. */ bool gPtsHaveNan() const; /** * @return The mid point of theLineSamplePts. */ ossimDpt midLineSamplePt() const; std::vector theLineSamplePt; std::vector theGeographicPt; ossimLeastSquaresBilin theLatFit; ossimLeastSquaresBilin theLonFit; ossimLeastSquaresBilin theXFit; ossimLeastSquaresBilin theYFit; bool theInterpolationPointsHaveNanFlag; bool theInverseSupportedFlag; TYPE_DATA }; #endif /* #ifndef ossimBilinearProjection_HEADER */ ossim-Miami-2.9.1/include/ossim/projection/ossimBngProjection.h000066400000000000000000000127151352751253100246410ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimBngProjection.h 9968 2006-11-29 14:01:53Z gpotts $ #include class OSSIMDLLEXPORT ossimBngProjection : public ossimMapProjection { public: ossimBngProjection(); virtual ossimObject* dup()const { return new ossimBngProjection(*this); } virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const; virtual ossimDpt forward(const ossimGpt &latLon)const; virtual void update(); /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: /* Ellipsoid Parameters, must be Airy */ double BNG_a; /* Semi-major axis of ellipsoid, in meters */ double BNG_f; /* Flattening of ellipsoid */ /* BNG projection Parameters */ double BNG_Origin_Lat; /* Latitude of origin, in radians */ double BNG_Origin_Long; /* Longitude of origin, in radians */ double BNG_False_Northing; /* False northing, in meters */ double BNG_False_Easting; /* False easting, in meters */ double BNG_Scale_Factor; /* Scale factor */ mutable long string_Broken; long Find_Index (char letter, const char* letter_Array, long *index)const; long Round_BNG (double value)const; long Make_BNG_String (char ltrnum[4], long Easting, long Northing, char* BNG, long Precision)const; long Break_BNG_String (char* BNG, char Letters[3], double* Easting, double* Northing, long* Precision)const; long Check_Out_Of_Area(char BNG500, char BNG100)const; long Set_BNG_Parameters(char *Ellipsoid_Code); void Get_BNG_Parameters(char *Ellipsoid_Code); /*! * The function Convert_Geodetic_To_BNG converts geodetic (latitude and * longitude) coordinates to a BNG coordinate string, according to the * current ellipsoid parameters. If any errors occur, the error code(s) * are returned by the function, otherwise BNG_NO_ERROR is returned. * * Latitude : Latitude, in radians (input) * Longitude : Longitude, in radians (input) * Precision : Precision level of BNG string (input) * BNG : British National Grid coordinate string (output) * */ long Convert_Geodetic_To_BNG (double Latitude, double Longitude, long Precision, char* BNG)const; /*! * The function Convert_BNG_To_Geodetic converts a BNG coordinate string * to geodetic (latitude and longitude) coordinates, according to the current * ellipsoid parameters. If any errors occur, the error code(s) are returned * by the function, otherwise BNG_NO_ERROR is returned. * * BNG : British National Grid coordinate string (input) * Latitude : Latitude, in radians (output) * Longitude : Longitude, in radians (output) * */ long Convert_BNG_To_Geodetic (char *BNG, double *Latitude, double *Longitude)const; /*! * The function Convert_Transverse_Mercator_To_BNG converts Transverse Mercator * (easting and northing) coordinates to a BNG coordinate string, according * to the current ellipsoid parameters. If any errors occur, the error code(s) * are returned by the function, otherwise BNG_NO_ERROR is returned. * * Easting : Easting (X), in meters (input) * Northing : Northing (Y), in meters (input) * Precision : Precision level of BNG string (input) * BNG : British National Grid coordinate string (output) */ long Convert_Transverse_Mercator_To_BNG(double Easting, double Northing, long Precision, char *BNG)const; /*! * The function Convert_BNG_To_Transverse_Mercator converts a BNG coordinate string * to Transverse Mercator projection (easting and northing) coordinates * according to the current ellipsoid parameters. If any errors occur, * the error code(s) are returned by the function, otherwise BNG_NO_ERROR * is returned. * * BNG : British National Grid coordinate string (input) * Easting : Easting (X), in meters (output) * Northing : Northing (Y), in meters (output) */ long Convert_BNG_To_Transverse_Mercator(char *BNG, double *Easting, double *Northing)const; TYPE_DATA }; ossim-Miami-2.9.1/include/ossim/projection/ossimBonneProjection.h000066400000000000000000000207651352751253100252000ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // Calls Geotrans Bonne projection code. //******************************************************************* // $Id: ossimBonneProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimBonneProjection_HEADER #define ossimBonneProjection_HEADER #include class OSSIMDLLEXPORT ossimBonneProjection : public ossimMapProjection { public: ossimBonneProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(), const ossimGpt& origin = ossimGpt()); ossimBonneProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, const double falseEasting, const double falseNorthing); ~ossimBonneProjection(){} virtual ossimObject *dup()const{return new ossimBonneProjection(*this);} virtual ossimDpt forward(const ossimGpt &worldPoint) const; virtual ossimGpt inverse(const ossimDpt &projectedPoint)const; virtual void update(); /*! * SetFalseEasting. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseEasting(double falseEasting); /*! * SetFalseNorthing. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseNorthing(double falseNorthing); /*! * Sets both false easting and northing values. The values are * expected to be in meters. * Update is then called so we can pre-compute paramters */ void setFalseEastingNorthing(double falseEasting, double falseNorthing); double getFalseEasting()const{return Bonn_False_Easting;} double getFalseNorthing()const{return Bonn_False_Northing;} /*! * Initialize all pramters to default and calls update for * pre-computations. */ void setDefaults(); /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Returns TRUE if principal parameters are within epsilon tolerance. virtual bool operator==(const ossimProjection& projection) const; private: mutable double Bonn_a; /* Semi-major axis of ellipsoid in meters */ mutable double Bonn_f; /* Flattening of ellipsoid */ mutable double es2; /* Eccentricity (0.08181919084262188000) squared */ mutable double es4; /* es2 * es2 */ mutable double es6; /* es4 * es2 */ mutable double M1; /* Bonn_M(Bonna,c0lat,c1s2lat,c2s4lat,c3s6lat) */ mutable double m1; /* Bonn_m(coslat,sinlat,es2) */ mutable double c0; /* 1 - es2 / 4.0 - 3.0 * es4 / 64.0 - 5.0 * es6 / 256.0 */ mutable double c1; /* 3.0 * es2 / 8.0 + 3.0 * es4 / 32.0 + 45.0 * es6 / 1024.0 */ mutable double c2; /* 15.0 * es4 / 256.0 + 45.0 * es6 / 1024.0 */ mutable double c3; /* 35.0 * es6 / 3072.0 */ mutable double a0; /* 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0 */ mutable double a1; /* 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0 */ mutable double a2; /* 151.0 * e3 / 96.0 */ mutable double a3; /* 1097.0 * e4 / 512.0 */ /* Bonne projection Parameters */ mutable double Bonn_Origin_Lat; /* Latitude of origin in radians */ mutable double Bonn_Origin_Long; /* Longitude of origin in radians */ mutable double Bonn_False_Northing; /* False northing in meters */ mutable double Bonn_False_Easting; /* False easting in meters */ mutable double Sin_Bonn_Origin_Lat; /* sin(Bonn_Origin_Lat) */ mutable double Bonn_am1sin; /* Bonn_a * m1 / Sin_Bonn_Origin_Lat */ /* Maximum variance for easting and northing values for WGS 84. */ mutable double Bonn_Max_Easting; mutable double Bonn_Min_Easting; mutable double Bonn_Delta_Northing; /*! * The function Set_Bonne_Parameters receives the ellipsoid parameters and * Bonne projcetion parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the * function, otherwise BONN_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ long Set_Bonne_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing); /*! * The function Get_Bonne_Parameters returns the current ellipsoid * parameters and Bonne projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ void Get_Bonne_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const; /*! * The function Convert_Geodetic_To_Bonne converts geodetic (latitude and * longitude) coordinates to Bonne projection easting, and northing * coordinates, according to the current ellipsoid and Bonne projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise BONN_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ long Convert_Geodetic_To_Bonne (double Latitude, double Longitude, double *Easting, double *Northing)const; /*! * The function Convert_Bonne_To_Geodetic converts Bonne projection * easting and northing coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Bonne projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise BONN_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ long Convert_Bonne_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const; /*! * RTTI found in data_types/rtti.h */ TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimBuckeyeSensor.h000066400000000000000000000117411352751253100246550ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // //******************************************************************* // $Id$ #ifndef ossimBuckeyeSensor_HEADER #define ossimBuckeyeSensor_HEADER /** * The Buckeye sensor has a set of simple orientation parameters. For this model we are using the * orientation parameters found in the MetaData_GSTI.txt file typically found in the directory where the * imagery sits. * * There are 2 forms the class takes for keyword lists. The first allows one to point * to a file containing the frame numbers and all the orientation parameters. You will still * need to define the Camera information and calibration parameters. The pixel_size, * focal_length and principal point are all in millimeters. * *
 * EXAMPLE 1:
 *
 * type: ossimBuckeyeSensor
 * framemeta_gsti: /data/buckeye/01-31@09/01-31@09/10-39-48/FrameMeta_GSTI.txt
 * frame_number: 10001
 * pixel_size: (0.0068,0.0068)
 * focal_length: 211.0211
 * principal_point: (-0.1853,1.2428)
 * smac_radial: -.2165e-3 .4230e-7 -.1652e-11 .2860e-19 .5690e-26
 * smac_decent: -.1483e-6 .1558e-6 -.1464e-18 .1233e-38
 * rect: 0 0 7239 5432
 *
 *
 * EXAMPLE 2:
 * roll: 0.074405
 * pitch: 2.849851
 * yaw: 269.517649
 * platform_position: (34.927014,69.353684,3757.12,WGE)
 * pixel_size: (0.0068,0.0068)
 * focal_length: 211.0211
 * principal_point: (-0.1853,1.2428)
 * smac_radial: -.2165e-3 .4230e-7 -.1652e-11 .2860e-19 .5690e-26
 * smac_decent: -.1483e-6 .1558e-6 -.1464e-18 .1233e-38
 * rect: 0 0 7239 5432
 */
#include 
#include "ossimSmacCallibrationSystem.h"

class OSSIM_DLL ossimBuckeyeSensor : public ossimSensorModel
{
public:
   ossimBuckeyeSensor();
   ossimBuckeyeSensor(const ossimDrect& imageRect, // center in image space
                          const ossimGpt& platformPosition,
                          double roll,
                          double pitch,
                          double heading,
                          const ossimDpt& principalPoint, // in millimeters
                          double focalLength, // in millimeters
                          const ossimDpt& pixelSize); // in millimeters
   ossimBuckeyeSensor(const ossimBuckeyeSensor& src);
   virtual ossimObject* dup()const;
   
   virtual void imagingRay(const ossimDpt& image_point,
                           ossimEcefRay&   image_ray) const;

   void lineSampleToWorld(const ossimDpt& image_point,
                          ossimGpt&       gpt) const;
  
   
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                        const double&   heightEllipsoid,
                                        ossimGpt&       worldPoint) const;
   virtual void worldToLineSample(const ossimGpt& world_point,
                                  ossimDpt&       image_point) const;
   
   virtual void updateModel();

   void setPrincipalPoint(ossimDpt principalPoint);

   virtual bool insideImage(const ossimDpt& p) const
   {
      return theImageClipRect.pointWithin(p, theImageClipRect.width());
   }


   void setRollPitchHeading(double roll,
                            double pitch,
                            double heading);
   
   void setPixelSize(const ossimDpt& pixelSize);
   void setImageRect(const ossimDrect& rect);
   void setFocalLength(double focalLength);
   void setPlatformPosition(const ossimGpt& gpt);

   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;
   
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   virtual void initAdjustableParameters();
   
   void setLensDistortion(ossimSmacCallibrationSystem* lensDistortion);
   /*!
    * ossimOptimizableProjection
    */
//   inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM)
   inline virtual bool useForward()const {return false;} //!ground to image faster (you don't need DEM)
   virtual bool setupOptimizer(const ossimString& init_file); //!uses file path to init model
  
   /**
    * @brief Extracts geometry info from a non-ossim key,value pair 
    * to an ossim keyword list.
    *
    * @param key non-ossim-based input ossimString 
    * @param value non-ossim-based input ossimString
    * @param geomKwl The keyword list to fill in.
    */
   virtual bool getImageGeometry( 
      const ossimString& key, const ossimString& value, 
      ossimKeywordlist& geomKwl ) const;

protected:
   
   NEWMAT::Matrix theCompositeMatrix;
   NEWMAT::Matrix theCompositeMatrixInverse;
   double         theRoll;
   double         thePitch;
   double         theHeading;
   ossimDpt       thePrincipalPoint;
   ossimDpt       thePixelSize;
   double         theFocalLength;
   ossimEcefPoint theEcefPlatformPosition;
   ossimRefPtr theLensDistortion;


   ossimEcefPoint theAdjEcefPlatformPosition;
   
TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimCadrgProjection.h000066400000000000000000000050051352751253100251450ustar00rootroot00000000000000//*******************************************************************
//
// License:  MIT
// 
// See LICENSE.txt file in the top level directory for more details.
//
// Author:  Garrett Potts
//
//*******************************************************************
//  $Id: ossimCadrgProjection.h 17815 2010-08-03 13:23:14Z dburken $
#ifndef ossimCadrgProjection_HEADER
#define ossimCadrgProjection_HEADER
#include 

class OSSIM_DLL ossimCadrgProjection : public ossimMapProjection
{
public:
   ossimCadrgProjection();

                       
   virtual ossimObject *dup()const;
   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   
   virtual ossimDpt worldToLineSample(const ossimGpt &worldPoint)    const;
   virtual ossimGpt lineSampleToWorld(const ossimDpt &projectedPoint)const;
   virtual void worldToLineSample(const ossimGpt &worldPoint,
                                  ossimDpt&       lineSample)const;
   virtual void lineSampleToWorld(const ossimDpt &projectedPoint,
                                  ossimGpt& gpt)const;

   double computeXPixConstant(double scale, long zone)const;
   double computeYPixConstant(double scale)const;
   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   
   ossimString getProjectionName()const
      {
         return getClassName();
      }
      
   //! Returns TRUE if principal parameters are within epsilon tolerance.
   virtual bool operator==(const ossimProjection& projection) const;

protected:
   virtual ~ossimCadrgProjection();
   /*
    * Are from the ADRG Mil spec for 1:1,000,000 and
    * are scales for each zone.
    */
   static double theCadrgArcA[8];
   

   static double theOldZoneExtents[10];

   static double theNorthLimit;
   static double theSouthLimit;

   ossim_int32   theCadrgZone;

   ossimDpt thePixelConstant;
   double   theMapScale;

   double theWidth;
   double theHeight;

   ossimDpt theUlLineSample;

   ossimGpt theUlGpt;
   ossimGpt theLlGpt;
   ossimGpt theLrGpt;
   ossimGpt theUrGpt;
   
   void computeParameters();
TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimCassiniProjection.h000066400000000000000000000203621352751253100255210ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
//
// Author:  Garrett Potts
//
// Description:
//
// Calls Geotrans Cassini projection code.  
//*******************************************************************
//  $Id: ossimCassiniProjection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimCassiniProjection_HEADER
#define ossimCassiniProjection_HEADER

#include 

class OSSIMDLLEXPORT ossimCassiniProjection : public ossimMapProjection
{
public:
   ossimCassiniProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                          const ossimGpt& origin = ossimGpt());
   ossimCassiniProjection(const ossimEllipsoid& ellipsoid,
                          const ossimGpt& origin,
                          const double falseEasting,
                          const double falseNorthing);
   ~ossimCassiniProjection(){}
   virtual ossimObject *dup()const{return new ossimCassiniProjection(*this);}
   
   virtual ossimDpt forward(const ossimGpt &worldPoint)    const;
   virtual ossimGpt inverse(const ossimDpt &projectedPoint)const;
   virtual void update();
   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   double getFalseEasting()const{return Cass_False_Easting;}
   double getFalseNorthing()const{return Cass_False_Northing;}

   /*!
    * Initialize all pramters to default and calls update for
    * pre-computations.
    */
   void setDefaults();

   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
private:
   
   //_____________________GETRANS STUFF_____________________
   
   mutable double Cass_a;                      /* Semi-major axis of ellipsoid in meters */
   mutable double Cass_f;              /* Flattening of ellipsoid */
   mutable double es2;             /* Eccentricity (0.08181919084262188000) squared  */
   mutable double es4;               /* es2 * es2 */
   mutable double es6;              /* es4 * es2 */
   mutable double M0;
   mutable double c0;                    /* 1 - es2 / 4.0 - 3.0 * es4 / 64.0 - 5.0 * es6 / 256.0 */
   mutable double c1;                  /* 3.0 * es2 / 8.0 + 3.0 * es4 / 32.0 + 45.0 * es6 / 1024.0 */
   mutable double c2;               /* 15.0 * es4 / 256.0 + 45.0 * es6 / 1024.0 */
   mutable double c3;               /* 35.0 * es6 / 3072.0 */
   mutable double One_Minus_es2;         /* 1.0 - es2 */
   mutable double a0;                  /* 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0 */
   mutable double a1;               /* 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0 */
   mutable double a2;               /* 151.0 * e3 / 96.0 */
   mutable double a3;               /* 1097.0 * e4 /512.0 */
   
/* Cassini projection Parameters */
   mutable double Cass_Origin_Lat;                   /* Latitude of origin in radians     */
   mutable double Cass_Origin_Long;                  /* Longitude of origin in radians    */
   mutable double Cass_False_Northing;               /* False northing in meters          */
   mutable double Cass_False_Easting;                /* False easting in meters           */
   
 /* Maximum variance for easting and northing values for WGS 84.
  */
   mutable double Cass_Min_Easting;
   mutable double Cass_Max_Easting;
   mutable double Cass_Min_Northing;
   mutable double Cass_Max_Northing;

/*!
 * The function Set_Cassini_Parameters receives the ellipsoid parameters and
 * Cassini projcetion parameters as inputs, and sets the corresponding state
 * variables.  If any errors occur, the error code(s) are returned by the 
 * function, otherwise CASS_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid						        (input)
 *    Origin_Latitude   : Latitude in radians at which the          (input)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)
 */
  long Set_Cassini_Parameters(double a,
                              double f,
                              double Origin_Latitude,
                              double Central_Meridian,
                              double False_Easting,
                              double False_Northing);


/*!
 * The function Get_Cassini_Parameters returns the current ellipsoid
 * parameters, and Cassini projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid						        (output)
 *    Origin_Latitude   : Latitude in radians at which the          (output)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output)
 */
  void Get_Cassini_Parameters(double *a,
                              double *f,
                              double *Origin_Latitude,
                              double *Central_Meridian,
                              double *False_Easting,
                              double *False_Northing)const;


/*!
 * The function Convert_Geodetic_To_Cassini converts geodetic (latitude and
 * longitude) coordinates to Cassini projection easting, and northing
 * coordinates, according to the current ellipsoid and Cassini projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise CASS_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Cassini (double Latitude,
                                    double Longitude,
                                    double *Easting,
                                    double *Northing)const; 


/*!
 * The function Convert_Cassini_To_Geodetic converts Cassini projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Cassini projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise CASS_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Cassini_To_Geodetic(double Easting,
                                   double Northing,
                                   double *Latitude,
                                   double *Longitude)const;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimCoarseGridModel.h000066400000000000000000000132721352751253100251000ustar00rootroot00000000000000//*****************************************************************************
// FILE: ossimCoarseGridModel.h
//
// Copyright (C) 2001 ImageLinks, Inc.
//
// License:  MIT
// 
// See LICENSE.txt file in the top level directory for more details.
//
// AUTHOR: Oscar Kramer
//
// DESCRIPTION:
//   Contains declaration of class ossimCoarseGridModel. This is an
//   implementation of an interpolation sensor model.
//
//*****************************************************************************
//  $Id: ossimCoarseGridModel.h 22825 2014-07-07 23:14:52Z dburken $

#ifndef ossimCoarseGridModel_HEADER
#define ossimCoarseGridModel_HEADER 1

#include 
#include 
#include 
#include 

class ossimImageGeometry;

/******************************************************************************
 *
 * CLASS:  ossimCoarseGridModel
 *
 *****************************************************************************/
class OSSIMDLLEXPORT ossimCoarseGridModel : public ossimSensorModel
{
public:
   ossimCoarseGridModel();
   ossimCoarseGridModel(const ossimCoarseGridModel& copy_this);

   /** Accepts name of geometry file. This can be either MET ECG geom file, or
    * OSSIM keywordlist geometry file.*/
   ossimCoarseGridModel(const ossimFilename& geom_file);

   /** Accepts OSSIM keywordlist geometry file. */
   ossimCoarseGridModel(const ossimKeywordlist& geom_kwl);
   
   ~ossimCoarseGridModel();

   /** This method will build a grid from any projector. The accuracy of the grid can be
    * controlled by the static method setInterpolationError().
    * @param imageBounds Must be the image space bounds for the projection.
    * @param proj The projector that will be used to approximate a bilinear grid over. */
   virtual void buildGrid(const ossimDrect& imageBounds,
                          ossimProjection* proj,
                          double heightDelta=500.0,
                          bool enableHeightFlag=false,
                          bool makeAdjustableFlag=true);
   virtual void buildGrid(const ossimDrect& imageBounds,
                          ossimImageGeometry* geom,
                          double heightDelta=500.0,
                          bool enableHeightFlag=false,
                          bool makeAdjustableFlag=true);
   
   /** This is used when building a grid from a projector. You can set the interpolation error.
    * The default is subpixel accuracy (within .1 of a pixel). */
   static void setInterpolationError(double error=.1);
   static void setMinGridSpacing(ossim_int32 minSpacing = 100);

   /** Extends base-class implementation. Dumps contents of object to std::ostream. */
   virtual std::ostream& print(std::ostream& out) const;
   
   /** Fulfills ossimObject base-class pure virtuals. Saves geometry KWL files.
    * @return Returns true if successful. */
   virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const;

   /** Fulfills ossimObject base-class pure virtuals. Loads geometry KWL files.
    * @return Returns true if successful. */
   virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0);

   /** Writes a template of geometry keywords processed by loadState and
    * saveState to output stream. */
   static void writeGeomTemplate(std::ostream& os);

   /** Returns pointer to a new instance, copy of this. */
   virtual ossimObject* dup() const { return new ossimCoarseGridModel(*this); }
   
   /** Saves the coarse grid to the specified file.
    * @return Returns true if successful. */
   bool saveCoarseGrid(const ossimFilename& cgFileName) const;

   /** Loads the coarse grid from the specified file.
    * @return Returns true if successful. */
   bool loadCoarseGrid(const ossimFilename& cgFileName);

   virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const;

   
   virtual void lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const;

   /** This is the virtual that performs the actual work of projecting the image point
    * to the earth at some specified elevation. */
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                        const double&   heightEllipsoid,
                                        ossimGpt&       world_pt) const;

   virtual void initAdjustableParameters();

   /*!
    * ossimOptimizableProjection
    */
   inline virtual bool useForward()const {return false;} //!image to ground faster

   /** Overrides base ossimSensorModel::isAffectedByElevation method.
    * @return true if height enabled, false if not. */
   virtual bool isAffectedByElevation() const;
   
protected:

   /** Deletes existing allocated memory and reallocates
    * new space. This may happen if a new grid is loaded over an existing one. */
   void reallocateGrid(const ossimIpt& size);
   
   //! Initializes base class data members after grids have been assigned.
   void initializeModelParams(ossimIrect irect);

   //! Implements its own extrapolation since this can be handled by ossimDblGrid.
   virtual ossimGpt extrapolate (const ossimDpt& imgPt, const double& height=ossim::nan()) const;

   mutable ossimFilename theGridFilename;
   ossimDblGrid  theLatGrid;         // degrees
   ossimDblGrid  theLonGrid;         // degrees
   ossimDblGrid  theDlatDhGrid;      // degrees/meter
   ossimDblGrid  theDlonDhGrid;      // degrees/meter
   ossimDblGrid* theDlatDparamGrid;  // degrees/(units-of-param)
   ossimDblGrid* theDlonDparamGrid;  // degrees/(units-of-param)

   static double       theInterpolationError;
   static ossim_int32  theMinGridSpacing;
   ossimAdjustmentInfo theInitialAdjustment;
   bool                theHeightEnabledFlag;
   
   TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimCylEquAreaProjection.h000066400000000000000000000203611352751253100261220ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts
//
// Description:
//
// Calls Geotrans Cylinder Equal Area  projection code.  
//*******************************************************************
//  $Id: ossimCylEquAreaProjection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimCylEquAreaProjection_HEADER
#define ossimCylEquAreaProjection_HEADER

#include 

class OSSIMDLLEXPORT ossimCylEquAreaProjection : public ossimMapProjection
{
public: 
   ossimCylEquAreaProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                             const ossimGpt& origin = ossimGpt());
   ossimCylEquAreaProjection(const ossimEllipsoid& ellipsoid,
                             const ossimGpt& origin,
                             double falseEasting,
                             double falseNorthing);
   ~ossimCylEquAreaProjection(){}
   virtual ossimObject *dup()const
      {
         return new ossimCylEquAreaProjection(*this);
      }

   virtual ossimDpt forward(const ossimGpt &worldPoint)    const;
   virtual ossimGpt inverse(const ossimDpt &projectedPoint)const;
   virtual void update();
   
   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   double getFalseEasting()const{return  Cyeq_False_Easting;}
   double getFalseNorthing()const{return Cyeq_False_Northing;}

   /*!
    * Initialize all pramters to default and calls update for
    * pre-computations.
    */
   void setDefaults();

   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
private:


/* Ellipsoid Parameters, default to WGS 84 */
   mutable double Cyeq_a;                     /* Semi-major axis of ellipsoid in meters */
   mutable double Cyeq_f;             /* Flattening of ellipsoid */
   mutable double es2;            /* Eccentricity (0.08181919084262188000) squared  */
   mutable double es;                  /* Sqrt(es2) */
   mutable double es4;             /* es2 * es2 */
   mutable double es6;             /* es4 * es2 */
   mutable double k0;
   mutable double Cyeq_a_k0;                  /* Cyeq_a * k0 */
   mutable double two_k0;                           /* 2.0 * k0 */
   mutable double c0;                 /* es2 / 3.0 + 31.0 * es4 / 180.0 + 517.0 * es6 / 5040.0 */
   mutable double c1;              /* 23.0 es4 / 360.0 + 251.0 * es6 / 3780.0 */
   mutable double c2;              /* 761.0 * es6 / 45360.0 */
   
/* Cylindrical Equal Area projection Parameters */
   mutable double Cyeq_Origin_Lat;                  /* Latitude of origin in radians     */
   mutable double Cyeq_Origin_Long;                 /* Longitude of origin in radians    */
   mutable double Cyeq_False_Northing;              /* False northing in meters          */
   mutable double Cyeq_False_Easting;               /* False easting in meters           */
   
/* Maximum variance for easting and northing values for WGS 84.
 */
   mutable double Cyeq_Max_Easting;
   mutable double Cyeq_Min_Easting;
   mutable double Cyeq_Delta_Northing;

/*!
 * The function Set_Cyl_Eq_Area_Parameters receives the ellipsoid parameters and
 * Cylindrical Equal Area projcetion parameters as inputs, and sets the corresponding 
 * state variables.  If any errors occur, the error code(s) are returned by the 
 * function, otherwise CYEQ_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid						        (input)
 *    Origin_Latitude   : Latitude in radians at which the          (input)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)
 */
  long Set_Cyl_Eq_Area_Parameters(double a,
                                  double f,
                                  double Origin_Latitude,
                                  double Central_Meridian,
                                  double False_Easting,
                                  double False_Northing);


/*!
 * The function Get_Cyl_Eq_Area_Parameters returns the current ellipsoid
 * parameters and Cylindrical Equal Area projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid						        (output)
 *    Origin_Latitude   : Latitude in radians at which the          (output)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output)
 */  void Get_Cyl_Eq_Area_Parameters(double *a,
                                  double *f,
                                  double *Origin_Latitude,
                                  double *Central_Meridian,
                                  double *False_Easting,
                                  double *False_Northing)const;



/*!
 * The function Convert_Geodetic_To_Cyl_Eq_Area converts geodetic (latitude and
 * longitude) coordinates to Cylindrical Equal Area projection easting, and northing
 * coordinates, according to the current ellipsoid and Cylindrical Equal Area projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise CYEQ_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Cyl_Eq_Area (double Latitude,
                                        double Longitude,
                                        double *Easting,
                                        double *Northing)const; 


/*!
 * The function Convert_Cyl_Eq_Area_To_Geodetic converts Cylindrical Equal Area projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Cylindrical Equal Area projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise CYEQ_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Cyl_Eq_Area_To_Geodetic(double Easting,
                                       double Northing,
                                       double *Latitude,
                                       double *Longitude)const;

/*!
 * RTTI information found in data_types/rtti.h
 */
TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimEckert4Projection.h000066400000000000000000000162501352751253100254320ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts
//
// Description:
//
// Calls Geotrans Eckert4 projection code.  
//*******************************************************************
//  $Id: ossimEckert4Projection.h 17815 2010-08-03 13:23:14Z dburken $
#ifndef ossimEcker4Projection_HEADER
#define ossimEcker4Projection_HEADER
#include 

class OSSIMDLLEXPORT ossimEckert4Projection : public ossimMapProjection
{
public:
    
   ossimEckert4Projection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                          const ossimGpt& origin = ossimGpt());
   ossimEckert4Projection(const ossimEllipsoid& ellipsoid,
                          const ossimGpt& origin,
                          double falseEasting,
                          double falseNorthing);
   ~ossimEckert4Projection(){}
   virtual ossimObject *dup()const
      {
         return new ossimEckert4Projection(*this);
      }
   
   virtual ossimDpt forward(const ossimGpt &worldPoint)     const;
   virtual ossimGpt inverse(const ossimDpt &projectedPoint) const;
   virtual void update();
   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   double getFalseEasting()const{return  Eck4_False_Easting;}
   double getFalseNorthing()const{return Eck4_False_Northing;}

   /*!
    * Initialize all pramters to default and calls update for
    * pre-computations.
    */
   void setDefaults();

   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
private:
/* Ellipsoid Parameters, default to WGS 84 */
   mutable double Eck4_a;                      /* Semi-major axis of ellipsoid in meters */
   mutable double Eck4_f;              /* Flattening of ellipsoid */
   mutable double es2;             /* Eccentricity (0.08181919084262188000) squared         */
   mutable double es4;              /* es2 * es2  */
   mutable double es6;              /* es4 * es2  */
   
   mutable double Ra0;                   /* 0.4222382 * Sperical Radius (6371007.1810824) */
   mutable double Ra1;                   /* 1.3265004 * Sperical Radius (6371007.1810824) */
   
/* Eckert4 projection Parameters */
   mutable double Eck4_Origin_Long;                  /* Longitude of origin in radians    */
   mutable double Eck4_False_Easting;
   mutable double Eck4_False_Northing;
   mutable double Eck4_Delta_Northing;
   mutable double Eck4_Max_Easting;
   mutable double Eck4_Min_Easting;
   
/*!
 * The function Set_Eckert4_Parameters receives the ellipsoid parameters and
 * Eckert IV projection parameters as inputs, and sets the corresponding state
 * variables.  If any errors occur, the error code(s) are returned by the 
 * function, otherwise ECK4_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid						        (input)
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)
 */
  long Set_Eckert4_Parameters(double a,
                              double f,                           
                              double Central_Meridian,
                              double False_Easting,
                              double False_Northing);


/*!
 * The function Get_Eckert4_Parameters returns the current ellipsoid
 * parameters and EckertIV projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid						        (output)
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output)
 */
  void Get_Eckert4_Parameters(double *a,
                              double *f,                            
                              double *Central_Meridian,
                              double *False_Easting,
                              double *False_Northing)const;


/*!
 * The function Convert_Geodetic_To_Eckert4 converts geodetic (latitude and
 * longitude) coordinates to Eckert IV projection easting, and northing
 * coordinates, according to the current ellipsoid and Eckert IV projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise ECK4_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Eckert4 (double Latitude,
                                    double Longitude,
                                    double *Easting,
                                    double *Northing)const;


/*!
 * The function Convert_Eckert4_To_Geodetic converts Eckert IV projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Eckert IV projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise ECK4_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Eckert4_To_Geodetic(double Easting,
                                   double Northing,
                                   double *Latitude,
                                   double *Longitude)const;

/*!
 * RTTI information
 */
TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimEckert6Projection.h000066400000000000000000000161771352751253100254440ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts
//
// Description:
//
// Calls Geotrans Eckert6 projection code.  
//*******************************************************************
//  $Id: ossimEckert6Projection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimEckert6Projection_HEADER
#define ossimEckert6Projection_HEADER

#include 

class OSSIMDLLEXPORT ossimEckert6Projection : public ossimMapProjection
{
public:   
   ossimEckert6Projection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                          const ossimGpt& origin = ossimGpt());
   ossimEckert6Projection(const ossimEllipsoid& ellipsoid,
                          const ossimGpt& origin,
                          double falseEasting,
                          double falseNorthing);
   ~ossimEckert6Projection(){}
   virtual ossimObject *dup()const{return new ossimEckert6Projection(*this);}

   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();
   
   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   double getFalseEasting()const{return  Eck6_False_Easting;}
   double getFalseNorthing()const{return Eck6_False_Northing;}

   /*!
    * Initialize all pramters to default and calls update for
    * pre-computations.
    */
   void setDefaults();

   void setCentralMeridian(double centralMeridian);

   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
private:

   //__________________GEOTRANS STUFF____________________
   
   mutable double Eck6_a;                      /* Semi-major axis of ellipsoid in meters */
   mutable double Eck6_f;              /* Flattening of ellipsoid */
   mutable double es2;             /* Eccentricity (0.08181919084262188000) squared         */
   mutable double es4;              /* es2 * es2	*/
   mutable double es6;              /* es4 * es2  */
   mutable double Ra_Over_Sqrt_Two_Plus_PI;      /* Ra(6371007.1810824)/Sqrt(2.0 + PI) */
   mutable double Inv_Ra_Over_Sqrt_Two_Plus_PI; /* Sqrt(2.0 + PI)/Ra(6371007.1810824) */
   
   
/* Eckert6 projection Parameters */
   mutable double Eck6_Origin_Long;                         /* Longitude of origin in radians    */
   mutable double Eck6_False_Easting;
   mutable double Eck6_False_Northing;
   mutable double Eck6_Delta_Northing;
   mutable double Eck6_Max_Easting;
   mutable double Eck6_Min_Easting;

   
/*!
 * The function Set_Eckert6_Parameters receives the ellipsoid parameters and
 * Eckert VI projection parameters as inputs, and sets the corresponding state
 * variables.  If any errors occur, the error code(s) are returned by the 
 * function, otherwise ECK6_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid						        (input)
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)
 */
  long Set_Eckert6_Parameters(double a,
                              double f,
                              double Central_Meridian,
                              double False_Easting,
                              double False_Northing);


/*!
 * The function Get_Eckert6_Parameters returns the current ellipsoid
 * parameters and Eckert VI projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid						        (output)
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output)
 */
  void Get_Eckert6_Parameters(double *a,
                              double *f,
                              double *Central_Meridian,
                              double *False_Easting,
                              double *False_Northing)const;


/*!
 * The function Convert_Geodetic_To_Eckert6 converts geodetic (latitude and
 * longitude) coordinates to Eckert VI projection easting, and northing
 * coordinates, according to the current ellipsoid and Eckert VI projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise ECK6_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Eckert6 (double Latitude,
                                    double Longitude,
                                    double *Easting,
                                    double *Northing)const;


/*!
 * The function Convert_Eckert6_To_Geodetic converts Eckert VI projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Eckert VI projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise ECK6_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Eckert6_To_Geodetic(double Easting,
                                   double Northing,
                                   double *Latitude,
                                   double *Longitude)const;


TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimEnviCgModel.h000066400000000000000000000013241352751253100242240ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
//*******************************************************************

#ifndef ossimEnviCgModel_HEADER
#define ossimEnviCgModel_HEADER

#include 
#include 

class OSSIMDLLEXPORT ossimEnviCgModel : public ossimCoarseGridModel
{
public:
   ossimEnviCgModel();
   ossimEnviCgModel(const ossimFilename& geoc_file);

   bool loadEnviGeocFile(const ossimFilename& geoc_file);
   bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const;

private:
   double readValue(std::ifstream& s, bool bigEndian) const;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimEpsgProjectionDatabase.h000066400000000000000000000127351352751253100264600ustar00rootroot00000000000000//*************************************************************************************************
//                          OSSIM -- Open Source Software Image Map
//
// License:  See top level LICENSE.txt file.
//
// Author: Oscar Kramer
//
//*************************************************************************************************
//  $Id: ossimEpsgProjectionDatabase.h 22924 2014-10-27 16:32:58Z okramer $

#ifndef ossimEpsgProjectionDatabase_HEADER
#define ossimEpsgProjectionDatabase_HEADER 1

#include 
#include 
#include 
#include 
#include 

class ossimProjection;
class ossimString;
class ossimEpsgProjectionFactory;
class ossimUtmProjection;

//*************************************************************************************************
//! Projection Database for coded projections defined in database files and specified via some 
//! coordinate reference system group:code, such as EPSG:26715.
//*************************************************************************************************
class OSSIMDLLEXPORT ossimEpsgProjectionDatabase : public ossimReferenced
{
   friend class ossimEpsgProjectionFactory;

public:
   //! Instantiates singleton instance of this class:
   static ossimEpsgProjectionDatabase* instance();

   //! Destructor
   virtual ~ossimEpsgProjectionDatabase();

   //! Returns a projection corresponding to the projection specified, or NULL if no entry found.
   //! Normally  takes the form of : (e.g., "EPSG:26715"). Other forms 
   //! accepted are  (assumed EPSG), or  to match a name in the database.
   ossimProjection* findProjection(const ossimString& proj_spec) const;

   //! Returns a projection corresponding to the epsg code specified, or NULL if no entry found.
   ossimProjection* findProjection(ossim_uint32 epsg_code) const;

   //! Given a projection name, assigns the group (e.g., "EPSG") and code of the projection. 
   //! Returns integer EPSG code if match was found or 0 if not found.
   ossim_uint32 findProjectionCode(const ossimString& projection_name) const;

   //! Given a projection instance, this method determines the corresponding EPSG code. Obviously
   //! this is only needed if the projection does not have its PCS code assigned (it is NULL). This
   //! happens when the projection was constructed with full parameters instead of the EPSG code.
   //! Returns integer EPSG code if match was found or 0 if not found.
   ossim_uint32 findProjectionCode(const ossimMapProjection& lost_proj) const;

   //! ### NECESSARY HACK ### (originally implemented by ESH)
   //! ArcMap (9.2 and less) doesn't understand the non-meters HARN codes.  
   //! This method provides acess to the projection name given the EPSG code. The name provides 
   //! enough info for recognizing a non-meters HARN-based projection. 
   ossimString findProjectionName(ossim_uint32 epsg_code) const;

   //! Populates caller's list with all projections currently represented in the database.
   //! The format is: 
   //!    EPSG:  ""
   //! There may be duplicate entries if the projection is duplicated in the various Db files.
   void getProjectionsList(std::vector& typeList) const;

   //! ENGINEERING CODE. Used for testing
   size_t numRecords() const { return m_projDatabase.size(); }

   //! Given UTM projection, derives the associated EPSG code. This is faster than a Db lookup.
   ossim_uint32 getCodeFromUtmProj(const ossimUtmProjection* proj) const;

protected:
   enum RecordFormat
   {  
      NOT_ASSIGNED=0,
      FORMAT_A,
      FORMAT_B,
      FORMAT_C,
      CUSTOM
   };

   //! Type for database record consists of EPSG code and serialized form of corresponding OSSIM 
   //! projection (as a keywordlist)
   class ProjDbRecord : public ossimReferenced
   {
   public:
      ProjDbRecord() : 
            code(0), 
            name(""), 
            datumValid(false), 
            csvFormat(NOT_ASSIGNED), 
            proj(0) {}

      ossim_uint32     code;
      ossimString      name;
      bool             datumValid; //!< FALSE if the datum code was not parsed and WGS84 defaulted
      RecordFormat     csvFormat;
      std::vector        csvRecord;
      ossimRefPtr proj;
   };

   //! Constructor loads all Db files specified in the ossim prefs. Protected as part of
   //! singleton implementation.
   ossimEpsgProjectionDatabase();

   //! Parses the "Spadac EPSG" Db record format and produces a projection (or NULL if invalid)   
   ossimMapProjection* createProjFromFormatARecord(ProjDbRecord* record) const;

   //! Parses the State Plane Db record format and produce a projection (or NULL if invalid)
   ossimMapProjection* createProjFromFormatBRecord(ProjDbRecord* record) const;

   //!  ### HACK ###
   //! UTM projections as specified in the EPSG are indistinguishable from regular TM.
   //! Unfortunately OSSIM does make a distinction. For the time being, parse the code and
   //! programmatically arrives at the UTM projection.
   ossimMapProjection* createProjFromUtmCode(ossim_uint32 code) const;

   //! Populates the database with contents of DB files as specified in ossim_preferences.
   void initialize() const;

   mutable std::multimap > m_projDatabase;
   mutable std::mutex m_mutex;
   //static ossimEpsgProjectionDatabase*  m_instance; //!< Singleton implementation
   
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimEpsgProjectionFactory.h000066400000000000000000000065551352751253100263660ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Oscar Kramer
//
//*******************************************************************
//  $Id: ossimEpsgProjectionFactory.h 12081 2007-11-26 21:44:18Z dburken $

#ifndef ossimEpsgProjectionFactory_HEADER
#define ossimEpsgProjectionFactory_HEADER

#include 
#include 
#include 
#include 

class ossimProjection;
class ossimString;
class ossimMapProjection;

//*************************************************************************************************
//! Projection Factory for coded projections defined in database. These are projections
//! that are fully defined in database files and specified via a projection coordinate system (PCS)
//! code, such as EPSG codes.
//*************************************************************************************************
class OSSIMDLLEXPORT ossimEpsgProjectionFactory : public ossimProjectionFactoryBase
{
public:
   /*!
    * METHOD: instance()
    * Instantiates singleton instance of this class:
    */
   static ossimEpsgProjectionFactory* instance();

   virtual ossimProjection* createProjection(const ossimFilename& filename,
                                             ossim_uint32 entryIdx) const;

   //! This is the principal factory method. It accepts a string in one of three formats:
   //!
   //!   1. :, for example "EPSG:32615"
   //!   2. , for example "32615", this is the CRS code ID for the projerection.
   //!   3. AUTO:, for specifying custom user-defined codes.
   //!
   //! Both projected and geographic (Platte Carre) codes are handled.
   virtual ossimProjection* createProjection(const ossimString& name) const;

   //! Looks for presence of "pcs_code" keyword with the value in the format :,
   //! for example "EPSG:32615" (EPSG and AUTO--see above-- are presently supported).
   //! If only an integer is specified, EPSG code is assumed.
   virtual ossimProjection* createProjection(const ossimKeywordlist& kwl,
                                             const char* prefix = 0)const;

   virtual ossimObject* createObject(const ossimString& typeName)const;
   virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const;
   
    //! This returns the type name of all objects in all factories. This is the name used to 
    //! construct the objects dynamically and this name must be unique.
   virtual void getTypeNameList(std::vector& typeList) const;

protected:
   //! Constructor loads all SRS CSV files specified in the ossim prefs. Protected as part of
   //! singleton implementation.
   ossimEpsgProjectionFactory();

   //! When the CRS is specified with the "AUTO:" code format, this method is invoked to
   //! parse the  and produce a projection (or NULL if spec invalid):
   //! This really shouldn't be in this class but nobody else is parsing for it, so leave it here 
   //! for now.
   ossimMapProjection* createProjFromAutoCode(const std::vector& spec) const;

   //ossimRefPtr    m_projDatabase;
   //static ossimEpsgProjectionFactory*  m_instance; //!< Singleton implementation
 
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimEquDistCylProjection.h000066400000000000000000000224511352751253100261570ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts
//
// Description:
//
// Calls Geotrans Equidistant Cylinder projection code.  
//*******************************************************************
//  $Id: ossimEquDistCylProjection.h 23373 2015-06-13 17:16:38Z okramer $

#ifndef ossimEquDistCylProjection_HEADER
#define ossimEquDistCylProjection_HEADER

#include 

class ossimIpt;

class OSSIMDLLEXPORT ossimEquDistCylProjection : public ossimMapProjection
{
public:
   ossimEquDistCylProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                             const ossimGpt& origin = ossimGpt());
   ossimEquDistCylProjection(const ossimEllipsoid& ellipsoid,
                             const ossimGpt& origin,
                             double falseEasting,
                             double falseNorthing);
   
   ossimEquDistCylProjection(const ossimEquDistCylProjection& rhs)
     :ossimMapProjection(rhs)
     //      :ossimLlxyProjection(rhs)
      {
         *this = rhs;
      }
   
   ~ossimEquDistCylProjection(){}
   virtual ossimObject *dup()const
      {
         return new ossimEquDistCylProjection(*this);
      }
   
   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();

   /*!
    * This method needs to be overridden here because of bug that causes bad projections if the
    * origin is set without reseting the tiepoint. (OLK Jun2015)
    */
   virtual void setOrigin(const ossimGpt& origin);

   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   double getFalseEasting()const{return Eqcy_False_Easting;}
   double getFalseNorthing()const{return Eqcy_False_Northing;}

#if 0
   virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt,
                                        const double&   heightAboveEllipsoid,
                                        ossimGpt&       worldPt) const;
   virtual void     worldToLineSample(const ossimGpt &worldPoint,
                                      ossimDpt&       lineSample)const;

   /**
    * @brief Specialized worldToLineSample.
    * 
    * Takes into consideration the image size and crossing the date line.
    * Also makes local points outside of image negative or positive based on
    * there relative closeness to left or right edge.
    *
    * @param worldPoint Ground point to convert to line sample.
    * @param imageSize Size of image in pixels.
    * @param lineSample Initialized by this.
    */
   void worldToLineSample( const ossimGpt& worldPoint,
                           const ossimIpt& imageSize,
                           ossimDpt&       lineSample ) const;
#endif

   virtual bool isGeographic()const
   {
      return true;
   }
   void setDefaults();

   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
private:   
   //---------------------GEOTRANS-------------------------------
   mutable double Eqcy_a;                  /* Semi-major axis of ellipsoid in meters */
   mutable double Eqcy_f;          /* Flattening of ellipsoid */
   mutable double es2;         /* Eccentricity (0.08181919084262188000) squared         */
   mutable double es4;          /* es2 * es2	 */
   mutable double es6;          /* es4 * es2  */
   mutable double Ra;                /* Spherical Radius  */
   
/* Equidistant Cylindrical projection Parameters */
   mutable double Eqcy_Std_Parallel;             /* Latitude of standard parallel in radians     */
   mutable double Cos_Eqcy_Std_Parallel;         /* cos(Eqcy_Std_Parallel)  */
   mutable double Eqcy_Origin_Long;              /* Longitude of origin in radians    */
   mutable double Eqcy_False_Easting;
   mutable double Eqcy_False_Northing;
   mutable double Eqcy_Delta_Northing;
   mutable double Eqcy_Max_Easting;
   mutable double Eqcy_Min_Easting;
   mutable double Ra_Cos_Eqcy_Std_Parallel; /* Ra * Cos_Eqcy_Std_Parallel */

/*!
 * The function Set_Equidistant_Cyl_Parameters receives the ellipsoid parameters and
 * projection parameters as inputs, and sets the corresponding state
 * variables.  It also calculates the spherical radius of the sphere having 
 * the same area as the ellipsoid.  If any errors occur, the error code(s) 
 * are returned by the function, otherwise EQCY_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid						        (input)
 *    Std_Parallel      : Latitude in radians at which the          (input)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          standard parallel of the projection     (input)
 */
  long Set_Equidistant_Cyl_Parameters(double a,
                                      double f,
                                      double Std_Parallel,
                                      double Central_Meridian,
                                      double False_Easting,
                                      double False_Northing);


/*!
 * The function Get_Equidistant_Cyl_Parameters returns the current ellipsoid
 * parameters and Equidistant Cylindrical projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid						        (output)
 *    Std_Parallel      : Latitude in radians at which the          (output)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          standard parallel of the projection     (output)
 */
  void Get_Equidistant_Cyl_Parameters(double *a,
                                      double *f,
                                      double *Std_Parallel,
                                      double *Central_Meridian,
                                      double *False_Easting,
                                      double *False_Northing)const;


/*!
 * The function Convert_Geodetic_To_Equidistant_Cyl converts geodetic (latitude and
 * longitude) coordinates to Equidistant Cylindrical projection easting, and northing
 * coordinates, according to the current ellipsoid and Equidistant Cylindrical projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise EQCY_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Equidistant_Cyl (double Latitude,
                                            double Longitude,
                                            double *Easting,
                                            double *Northing)const;


/*!
 * The function Convert_Equidistant_Cyl_To_Geodetic converts Equidistant Cylindrical projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Equidistant Cylindrical projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise EQCY_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Equidistant_Cyl_To_Geodetic(double Easting,
                                           double Northing,
                                           double *Latitude,
                                           double *Longitude)const;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimFcsiModel.h000066400000000000000000000213751352751253100237450ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// DESCRIPTION: Contains sensor model class declaration for "Frame Camera
//   Scanned Image" (FCSI, pronounced "foxy"). 
//   
//   This model represents image data that was scanned from film exposed by a
//   conventional aerial frame camera. The data members defined in this class
//   represent the fundamental quantities needed for the transformation.
//   Typically, a different set of parameters will be provided in the metadata.
//   An interface (support data) class will need to be implemented to convert
//   a particular system's format to the quantities needed by this model.
// 
//   Coordinate systems in use are described here:
//
//   Pixel    -- line/sample in the digital image. The origin of this system is
//               the upper left corner of the image, and represents a LEFT-
//               HANDED coordinate system with Y (line) positive down and X
//               (sample) positive to the right.
//
//   Film     -- x, y related to pixel space by affine transform (which includes
//               mirror reflection due to left-handed system above) represented
//               by thePrincipalPoint and the theScanXformMatrix. The latter
//               contains scale, skew, and rotation/reflection. The film
//               coordinates are adjusted for radial and decentering distortion.
//
//   Camera/  -- 3D system containing film plane and optical (Z) axis. Given the
//   Platform    focal length (Z) and the film point (X,Y), a 3D ray direction
//               is established in this space. This space is also termed "LSR"
//               in the code. If there is a rotation between the film/optical
//               axes and the platform (interior orientation), then that
//               transformation must be included as part of the LSR-to-ECF
//               rotation by the metadata reader object.
//
//   ECF      -- Universal earth frame of reference. The imaging ray direction
//               is transformed from Camera space to ECF by theAdjLsrToEcfRot.
//
//   There are two rotations to go from Camera to ECF. First is the initial
//   camera orientation as derived from the metadata, combining the interior
//   orientation (relation between camera and platform) and the exterior
//   orientation dependent on the platform attitude w.r.t. the ECF system.
//   The second rotation is a differential rotation due to the attitude
//   adjustable params. These are arbitrarily taken as rotations about the ECF
//   XYZ axes, not the platform attitude axes of roll/pitch/yaw. The
//   combined rotation is stored in theAdjLsrToEcfRot, which is precomputed
//   in updateModel() once with each adjustment.
//
//   When the time comes to incorporate least-squares parameter adjustment, care
//   must be taken to propagate the a priori sigmas for position and attitude
//   (including both internal and external orientation angles) into the ECF
//   coordinates. This also applies to the affine transform parameters used in
//   transforming pixels to film coordinates. The propagated uncertainties can
//   then be used to assign the adjustable parameter sigmas array (and
//   covariance when we get to that...)
//
// SOFTWARE HISTORY:
//   16JAN2003  Oscar Kramer, ImageLinks
//              Initial coding
//
//*****************************************************************************
//  $Id: ossimFcsiModel.h 15766 2009-10-20 12:37:09Z gpotts $

#ifndef ossimFcsiModel_HEADER
#define ossimFcsiModel_HEADER

#include 
#include 
#include 
#include 
#include 
#include 
#include 

//******************************************************************************
//
// CLASS:  ossimFcsiModel
//
//******************************************************************************
class OSSIM_DLL ossimFcsiModel : public ossimSensorModel
{
public:
   /*!
    * CONSTRUCTORS:
    */
   ossimFcsiModel();
   ossimFcsiModel(const ossimFilename& init_file);
   ossimFcsiModel(const ossimKeywordlist& geom_kwl);
   ossimFcsiModel(const ossimFcsiModel& rhs);
   

   enum AdjustParamIndex
   {
      X_POS = 0,
      Y_POS,
      Z_POS,
      X_ROT,
      Y_ROT,
      Z_ROT,
      FOCAL_LEN,
      SCAN_SKEW,
      NUM_ADJUSTABLE_PARAMS // not an index
   };

   /*!
    * Returns pointer to a new instance, copy of this.
    */
   virtual ossimObject* dup() const { return new ossimFcsiModel(*this); }
   
   /*!
    * Extends base-class implementation. Dumps contents of object to std::ostream.
    */
   virtual std::ostream& print(std::ostream& out) const;
   
   /*!
    * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry
    * KWL files. Returns true if successful.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;
   
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
   /*!
    * Writes a template of geom keywords processed by loadState and saveState
    * to output stream.
    */
   static void writeGeomTemplate(std::ostream& os);
   
   /*!
    * Overrides base class pure virtual.
    */
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                        const double&   heightEllipsoid,
                                        ossimGpt&       worldPoint) const;
   
   /*!
    * Given an image point, returns a ray originating at some arbitrarily high
    * point (ideally at the sensor position) and pointing towards the target.
    */
   virtual void imagingRay(const ossimDpt& image_point,
                           ossimEcefRay&   image_ray) const;

   /*!
    * Rigorous inverse transform implented, overrides base-class' iterative
    * solution.
    */
   virtual void worldToLineSample(const ossimGpt& world_point,
                                  ossimDpt&       image_point) const;
      
   /*!
    * Following a change to the adjustable parameter set, this virtual
    * is called to permit instances to compute derived quantities after
    * parameter change.
    */
   virtual void updateModel();

   /*!
    * Global keywords for use by this model:
    */
   static const char* PRINCIPAL_POINT_X_KW;
   static const char* PRINCIPAL_POINT_Y_KW;
   static const char* SCAN_SCALE_MATRIX_00_KW;
   static const char* SCAN_SCALE_MATRIX_01_KW;
   static const char* SCAN_SCALE_MATRIX_10_KW;
   static const char* SCAN_SCALE_MATRIX_11_KW;
   static const char* SCAN_SKEW_ANGLE_KW;
   static const char* SCAN_ROTATION_ANGLE_KW;
   static const char* FOCAL_LENGTH_KW;
   static const char* PLATFORM_POSITION_X_KW;
   static const char* PLATFORM_POSITION_Y_KW;
   static const char* PLATFORM_POSITION_Z_KW;
   static const char* CAMERA_ORIENTATION_MATRIX_ELEM_KW;

   /*!
    * ossimOptimizableProjection
    */
   inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM)

protected:
   virtual ~ossimFcsiModel() { delete theOpticalDistortion; }

   /*!
    * Assigns initial default values to adjustable parameters and related
    * members.
    */
   void initAdjustableParameters();

   //***
   // Affine transform variables for scanned image to film coordinate
   // transformation, in order of application:
   //***
   ossimDpt       thePrincipalPoint; // principal point location in pixels
   double         theScanScaleMatrix[4];// converts pixel to film X, Y mm
   double         theScanSkew;       // degrees
   double         theScanRotation;   // degrees left rotation of scanned image

   //***
   // Transform variables for film coordinates to platform LSR (interior
   // orientation):
   //***
   double         theFocalLen;     // millimeters
   ossimRadialDecentLensDistortion* theOpticalDistortion;
   
   //***
   // Transform variables for platform LSR to ECF coordinates (interior/exterior
   // orientation and offset):
   //***
   ossimEcefPoint thePlatformPos;
   NEWMAT::Matrix theLsrToEcfRot;
   
   //***
   // Un-normalized adjustable parameters:
   //***
   ossimEcefVector theEcfOffset;      // meters
   double          theXrotCorr;       // degrees
   double          theYrotCorr;       // degrees
   double          theZrotCorr;       // degrees
   double          theFocalOffset;    // millimeters
   double          theScanSkewCorr;   // degrees

   //***
   // Quantities derived from adjustables and assigned in updateModel():
   //***
   ossimEcefPoint theAdjPlatformPos;
   double         theAdjFocalLen;
   NEWMAT::Matrix theAdjLsrToEcfRot;
   NEWMAT::Matrix theAdjEcfToLsrRot;
   double         theScanXformMatrix[4]; 
   double         theInvScanXformMatrix[4];

   TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimGnomonicProjection.h000066400000000000000000000165021352751253100257020ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
//*******************************************************************
//  $Id: ossimGnomonicProjection.h 17815 2010-08-03 13:23:14Z dburken $
#ifndef ossimGnomonicProjection_HEADER
#define ossimGnomonicProjection_HEADER

#include 

class OSSIMDLLEXPORT ossimGnomonicProjection : public ossimMapProjection
{
public:
   ossimGnomonicProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                                const ossimGpt& origin = ossimGpt());
   ossimGnomonicProjection(const ossimEllipsoid& ellipsoid,
                                const ossimGpt& origin,
                                const double falseEasting,
                                const double falseNorthing);
   ~ossimGnomonicProjection(){}
   virtual ossimObject *dup()const
      {
         return new ossimGnomonicProjection(*this);
      }
   
   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();   
   

   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   void setDefaults();

   double getFalseEasting()const{return  Gnom_False_Easting;}
   double getFalseNorthing()const{return Gnom_False_Northing;}
   
   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

protected:

   //__________________________GEOTRANS________________________
   mutable double Gnom_a;               /* Semi-major axis of ellipsoid in meters */
   mutable double Gnom_f;               /* Flattening of ellipsoid */
   mutable double Ra;                   /* Spherical Radius */
   mutable double Sin_Gnom_Origin_Lat;
   mutable double Cos_Gnom_Origin_Lat;
   
/* Gnomonic projection Parameters */
   mutable double Gnom_Origin_Lat;               /* Latitude of origin in radians */
   mutable double Gnom_Origin_Long;              /* Longitude of origin in radians */
   mutable double Gnom_False_Northing;           /* False northing in meters */
   mutable double Gnom_False_Easting;            /* False easting in meters */
   mutable double abs_Gnom_Origin_Lat;
   
   mutable double Gnom_Delta_Northing;
   mutable double Gnom_Delta_Easting;
   
/*
 * The function Set_Gnomonic_Parameters receives the ellipsoid parameters and
 * projection parameters as inputs, and sets the corresponding state
 * variables.  If any errors occur, the error code(s) are returned by the function, 
 * otherwise GNOM_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid						        (input)
 *    Origin_Latitude   : Latitude in radians at which the          (input)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)
 */
  long Set_Gnomonic_Parameters(double a,
                               double f,
                               double Origin_Latitude,
                               double Central_Meridian,
                               double False_Easting,
                               double False_Northing);

/*!
 * The function Get_Gnomonic_Parameters returns the current ellipsoid
 * parameters and Gnomonic projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid						        (output)
 *    Origin_Latitude   : Latitude in radians at which the          (output)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output)
 */
  void Get_Gnomonic_Parameters(double *a,
                               double *f,
                               double *Origin_Latitude,
                               double *Central_Meridian,
                               double *False_Easting,
                               double *False_Northing)const;


/*!
 * The function Convert_Geodetic_To_Gnomonic converts geodetic (latitude and
 * longitude) coordinates to Gnomonic projection (easting and northing)
 * coordinates, according to the current ellipsoid and Gnomonic projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise GNOM_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Gnomonic (double Latitude,
                                     double Longitude,
                                     double *Easting,
                                     double *Northing)const;


/*!
 * The function Convert_Gnomonic_To_Geodetic converts Gnomonic projection
 * (easting and northing) coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Gnomonic projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise GNOM_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Gnomonic_To_Geodetic(double Easting,
                                    double Northing,
                                    double *Latitude,
                                    double *Longitude)const;


TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimGoogleProjection.h000066400000000000000000000022051352751253100253400ustar00rootroot00000000000000//*******************************************************************
//
// License:  MIT
// 
// See LICENSE.txt file in the top level directory for more details.
//
//
//*******************************************************************
#ifndef ossimGoogleProjection_HEADER
#define ossimGoogleProjection_HEADER 1
#include 

class OSSIM_DLL ossimGoogleProjection : public ossimMapProjection
{
public:
   ossimGoogleProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                        const ossimGpt& origin = ossimGpt());
   ossimGoogleProjection(const ossimGoogleProjection&);
   ~ossimGoogleProjection();
   virtual ossimObject *dup()const{return new ossimGoogleProjection(*this);}

   virtual ossimDpt forward(const ossimGpt &worldPoint)    const;
   virtual ossimGpt inverse(const ossimDpt &projectedPoint)const;
   virtual void update();

	virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0);
	virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const;
   virtual bool operator==(const ossimProjection& projection) const;

protected:

	TYPE_DATA;
};
#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimIkonosRpcModel.h000066400000000000000000000043551352751253100247670ustar00rootroot00000000000000//*******************************************************************
//
// License:  MIT
// 
// See LICENSE.txt file in the top level directory for more details.
// 
// AUTHOR: Oscar Kramer
//
// DESCRIPTION: Contains declaration of class ossimIkonosRpcModel. This 
//    derived class implements the capability of reading Ikonos RPC support
//    data.
//
// LIMITATIONS: None.
//
//*****************************************************************************
//  $Id: ossimIkonosRpcModel.h 20606 2012-02-24 12:29:52Z gpotts $

#ifndef ossimIkonosRpcModel_HEADER
#define ossimIkonosRpcModel_HEADER

#include 
#include 
#include 

class ossimFilename;

/*!****************************************************************************
 *
 * CLASS:  ossimIkonosRpcModel
 *
 *****************************************************************************/
class OSSIM_DLL ossimIkonosRpcModel : public ossimRpcModel
{
public:
  ossimIkonosRpcModel();
   ossimIkonosRpcModel(const ossimFilename& geom_file);

   ossimIkonosRpcModel(const ossimFilename& metadata,
                       const ossimFilename& rpcdata);

  virtual bool saveState(ossimKeywordlist& kwl,
			 const char* prefix=0)const;

  /**
    * @brief loadState
    * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry
    * KWL files. Returns true if successful.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
  
   /*!
    * STATIC METHOD: writeGeomTemplate(std::ostream)
    * Writes a template of an ossimIkonosRpcModel geometry file.
    */
   static void writeGeomTemplate(std::ostream& os);

   virtual bool parseFile(const ossimFilename& file);
   
protected:
   virtual ~ossimIkonosRpcModel();
   void finishConstruction();
   void parseMetaData(const ossimFilename& metadata);
   void parseRpcData (const ossimFilename& rpcdata);

   bool isNitf(const ossimFilename& filename);
   bool parseTiffFile(const ossimFilename& filename);
/*    bool parseNitfFile(const ossimFilename& geom_file); */
   bool parseHdrData(const ossimFilename& data_file);

   ossimRefPtr theSupportData;

   TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimImageProjectionModel.h000066400000000000000000000027751352751253100261430ustar00rootroot00000000000000//-----------------------------------------------------------------------------
//
// License:  MIT
// 
// See LICENSE.txt file in the top level directory for more details.
//
// Author:  David Burken
//
// Description: Class declaration of ossimImageProjectionModel.
//
//-----------------------------------------------------------------------------
// $Id$

#ifndef ossimImageProjectionModel_HEADER
#define ossimImageProjectionModel_HEADER 1

#include 
#include 
#include 

class ossimProjection;

/**
 * @brief Class derived from ossimImageModel, this adds an image projection
 * for lineSampleToWorld and worldToLineSample.
 *
 * Note that image points fed to projection methods should be full
 * resolution with any sub image offset applied.
 */
class OSSIM_DLL ossimImageProjectionModel : public ossimImageModel
{
public:
   
   /** @brief default constructor */
   ossimImageProjectionModel();


   /**
    * @brief Method to initialize class from an image handler.
    *
    * @param ih Image handler.
    */
   virtual void initialize(const ossimImageHandler& ih);

   /**
    * @brief Method to get projection.
    *
    * @return Constant pointer to projection or 0 if not initialized.
    */
   const ossimProjection* getProjection() const;

protected:
   /** @brief virtual destructor */
   virtual ~ossimImageProjectionModel();

   ossimProjection* theProjection;

TYPE_DATA
};

#endif /* #ifndef ossimImageProjectionModel_HEADER */
ossim-Miami-2.9.1/include/ossim/projection/ossimImageViewAffineTransform.h000066400000000000000000000140551352751253100267570ustar00rootroot00000000000000//*******************************************************************
// Copyright (C) 2000 ImageLinks Inc.
//
// License:  MIT
// 
// See LICENSE.txt file in the top level directory for more details.
//
// Author:  Garrett Potts
//
//*******************************************************************
//  $Id: ossimImageViewAffineTransform.h 23477 2015-08-26 14:39:12Z gpotts $
#ifndef ossimImageViewAffineTransform_HEADER
#define ossimImageViewAffineTransform_HEADER
#include 
#include 

class OSSIMDLLEXPORT ossimImageViewAffineTransform: public ossimImageViewTransform
{
public:
   /**
    * Initialize transform completely here. The image-to-view transform is a chain of 3x3 matrix
    * multiplies as: [translation] [view scale] [rotation (about pivot pt)] [image scale].
    * The view to image is stored as the inverse transform.
    * @param rotateDegrees
    * @param imageScaleX  Image-side scale, applied before rotation
    * @param imageScaleY  ditto
    * @param scaleXValue  View-side scale
    * @param scaleYValue  ditto
    * @param translateXValue View-side translation
    * @param translateYValue  ditto
    * @param pivotXValue Pivot point in image space
    * @param pivotYValue ditto
    */
   ossimImageViewAffineTransform(double rotateDegrees = 0.0,
                                 double imageScaleX = 1.0,
                                 double imageScaleY = 1.0,
                                 double scaleXValue = 1.0,
                                 double scaleYValue = 1.0,
                                 double translateXValue = 0.0,
                                 double translateYValue = 0.0,
                                 double pivotXValue = 0.0,
                                 double pivotYValue = 0.0 );
   virtual ~ossimImageViewAffineTransform();
   
   ossimImageViewAffineTransform(const ossimImageViewAffineTransform& src)
   :ossimImageViewTransform(src),
   m_transform(src.m_transform),
   m_inverseTransform(src.m_inverseTransform),
   m_rotation(src.m_rotation),
   m_imageSpaceScale(src.m_imageSpaceScale),
   m_scale(src.m_scale),
   m_translate(src.m_translate),
   m_pivot(src.m_pivot)
   {
   }
   virtual ossimObject* dup()const
   {
      return new ossimImageViewAffineTransform(*this);
   }
//   virtual void inverse(const ossimDpt& input,
//                        ossimDpt&       output) const
//   {
//      viewToImage(input, output);
 //  }
   
   virtual void imageToView(const ossimDpt& imagePoint,
                            ossimDpt&       viewPoint)const;
   virtual void viewToImage(const ossimDpt& viewPoint,
                            ossimDpt&       imagePoint)const;
   void setMatrix(NEWMAT::Matrix& matrix);
   const NEWMAT::Matrix& getMatrix()const;
   
   virtual bool isIdentity()const
   {
      return ((m_transform[0][0] == 1.0)&&
              (m_transform[0][1] == 0.0)&&
              (m_transform[0][2] == 0.0)&&
              (m_transform[1][0] == 0.0)&&
              (m_transform[1][1] == 1.0)&&
              (m_transform[1][2] == 0.0)&&
              (m_transform[2][0] == 0.0)&&
              (m_transform[2][1] == 0.0)&&
              (m_transform[2][2] == 1.0));
   }

   virtual bool isValid()const;
   virtual bool setView(ossimObject* obj);
   virtual ossimObject* getView();
   virtual const ossimObject* getView()const;
   
   /** @return (1, 1) ???????(drb) */
   virtual ossimDpt getInputMetersPerPixel()const;

   /** @return (nan, nan) ????????? (drb) */
   virtual ossimDpt getOutputMetersPerPixel()const;
   
   /*!
    * Translate in the x and y direction.
    */ 
   virtual void translate(double deltaX, double deltaY);
   
   /*!
    * Translate in the x direction.
    */
   virtual void translateX(double deltaX);
   
   /*!
    * Translate in the Y direction.
    */
   virtual void translateY(double deltaY);
   
   /*!
    * Translate the origin for rotation in the x and y direction.
    */
   virtual void pivot(double originX, double originY);
   
   /*!
    * Translate the origin for rotation in the x direction.
    */
   virtual void pivotX(double originX);
   
   /*!
    * Translate the origin for rotation in the y direction.
    */
   virtual void pivotY(double originY);

   /*!
    * Will allow you to specify an image scale
    * for both the x and y direction.
    */
   virtual void imageSpaceScale(double x, double y);
   
   /*!
    * Will allow you to specify an image scale along the X direction.
    */
   virtual void imageSpaceScaleX(double x);

   /*!
    * Will allow you to an image scale along the Y direction.
    */
   virtual void imageSpaceScaleY(double y);
    
   /*!
    * will allow you to specify a scale
    * for both the x and y direction.
    */
   virtual void scale(double x, double y);
    
   /*!
    * will alow you to specify a scale
    * along the X direction.
    */
   virtual void scaleX(double x);
   
   /*!
    * Will allow you to scale along the Y
    * direction.
    */
   virtual void scaleY(double y);
   
   /*!
    * Will apply a rotation
    */
   virtual void rotate(double degrees);
   
   ossim_float64 getRotation()const{return m_rotation;}
   const ossimDpt& getScale()const{return m_scale;}
   const ossimDpt& getTranslate()const{return m_translate;}
   const ossimDpt& getPivot()const{return m_pivot;}
   
   
   virtual bool isEqualTo(const ossimObject& obj, ossimCompareType compareType = OSSIM_COMPARE_FULL)const;
   
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix =0);
   
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix =0)const;
   
   
protected:
   void buildCompositeTransform();
   
   /*!
    * This is the transformation from image to
    * viewing coordinates.  If this matrix is
    * changed it will perform an inverse to solve
    * the inverse transform.
    */
   NEWMAT::Matrix m_transform;
   NEWMAT::Matrix m_inverseTransform;
   ossim_float64  m_rotation;
   ossimDpt       m_imageSpaceScale;
   ossimDpt       m_scale;
   ossimDpt       m_translate;
   ossimDpt       m_pivot;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimImageViewProjectionTransform.h000066400000000000000000000127031352751253100277010ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// AUTHOR: Garrett Potts (gpotts@imagelinks.com)  
//         Oscar Kramer (oscar@krameranalytic.com)
//
// DESCRIPTION: Contains declaration of ossimImageViewProjectionTransform.
//    This class provides an image to view transform that utilizes two
//    independent 2D-to-3D projections. Intended for transforming view to
//    geographic "world" space to input image space.
//
// LIMITATIONS: None.
//
//*****************************************************************************
//  $Id: ossimImageViewProjectionTransform.h 20352 2011-12-12 17:24:52Z dburken $

#ifndef ossimImageViewProjectionTransform_HEADER
#define ossimImageViewProjectionTransform_HEADER 1

#include 
#include 
#include 

class OSSIMDLLEXPORT ossimImageViewProjectionTransform : public ossimImageViewTransform
{
public:
   ossimImageViewProjectionTransform(ossimImageGeometry* imageGeometry=0,
                                     ossimImageGeometry* viewGeometry=0);

   //! copy constructor 
   ossimImageViewProjectionTransform(const ossimImageViewProjectionTransform& src);

   virtual ossimObject* dup() const { return new ossimImageViewProjectionTransform(*this); }
   virtual ~ossimImageViewProjectionTransform();

   //! Satisfies base class pure virtual. Returns TRUE if both input and output geoms exist.
   virtual bool isValid() const { return (m_imageGeometry.valid() && m_viewGeometry.valid()); }

   //! Returns TRUE if both input and output geometries are identical. Presently implemented as
   //! limited compare of geometry pointers
   virtual bool isIdentity() const { return (m_imageGeometry == m_viewGeometry); }

   //! Assigns the geometry to use for output view. This object does NOT own the geometry.
   void setViewGeometry(ossimImageGeometry* g);   

   //! Assigns the geometry to use for input image. This object does NOT own the geometry.
   void setImageGeometry(ossimImageGeometry* g);  

   //! Workhorse of the object. Converts image-space to view-space.
   virtual void imageToView(const ossimDpt& imagePoint, ossimDpt& viewPoint) const;

   //! Other workhorse of the object. Converts view-space to image-space.
   virtual void viewToImage(const ossimDpt& viewPoint, ossimDpt& imagePoint) const;

   //! Dumps contents to stream
   virtual std::ostream& print(std::ostream& out) const;
   
   ossimImageGeometry* getImageGeometry()  { return m_imageGeometry.get(); }
   ossimImageGeometry* getViewGeometry()   { return m_viewGeometry.get(); }
   const ossimImageGeometry* getImageGeometry()const  { return m_imageGeometry.get(); }
   const ossimImageGeometry* getViewGeometry()const   { return m_viewGeometry.get(); }
   
   /**
   * Because of the fact we can have dateline crossings there exist on the view
   * plane both positive and negative bounds.  We need a generalized interface that allows
   * us to calculate the valid bounds of an image transformed to the view.
   *
   *
   * @param viewBounds Returns bounds for each segment
   * @param polyArea   Returns the polygons for each segment.
   * @param numberOfEdgePoints If the value is 0 it will do a standard bounds check.  If
   *                           the paramter is greater than 0 this will only be used if the
   *                           input projection is affected by elevation.  If it's not affected
   *                           by elevation then the default bounds will be calculated.
   */
   virtual void getViewSegments(std::vector& viewBounds, 
                                ossimPolyArea2d& polyArea,
                                ossim_uint32 numberOfEdgePoints=25)const; 


   /**
   * This is used a a general access point for setting a view to a chain.  
   * There are multiple locations that need a projector in order to run properly.  
   * When a "Set View" event is sent through the chain.  Typically this is passed
   * down from The renderer.
   */
   virtual bool setView(ossimObject* baseObject);
   
   virtual       ossimObject* getView()       { return m_viewGeometry.get(); }
   virtual const ossimObject* getView() const { return m_viewGeometry.get(); }

   //! Returns the GSD of input image.
   virtual ossimDpt getInputMetersPerPixel()const;

   //! Returns the GSD of the output view.
   virtual ossimDpt getOutputMetersPerPixel() const;

   //! Gets the image bounding rect in view-space coordinates
   virtual ossimDrect getImageToViewBounds(const ossimDrect& imageRect)const;
   
   //! After rewrite for incorporating ossimImageGeometry: No longer needed.  
   virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix =0);
   
   //! After rewrite for incorporating ossimImageGeometry: No longer needed.  
   virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const;

protected:

   /**
    * @brief Initializes the view geometry image size from image geometry
    * bounding rect.
    *
    * This is needed for the ossimImageGeometry::worldToLocal if the underlying
    * projection is geographic to handle images that cross the date line.
    * 
    * @param Input image rectangle.
    * @return true on success, false on error.
    */
   bool initializeViewSize();  
   void initializeDatelineCrossing();

   ossimRefPtr m_imageGeometry;
   ossimRefPtr m_viewGeometry;

   bool m_crossesDateline;
TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimImageViewTransform.h000066400000000000000000000114571352751253100256510ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:  This class hides the image view transformation process.
//               We should be able to open up ay image within the system
//               and be able to map it to the view space.  Classes need to
//               derive and override the methods within this class.  This will
//               mainly be used in the resampling process.
//
//*******************************************************************
//  $Id: ossimImageViewTransform.h 18397 2010-11-09 19:13:46Z gpotts $
#ifndef ossimImageViewTransform_HEADER
#define ossimImageViewTransform_HEADER
#include 
#include 
#include 
#include 
#include 
#include 

class OSSIMDLLEXPORT ossimImageViewTransform : public ossim2dTo2dTransform,
					       public ossimViewInterface
{
public:
   friend OSSIMDLLEXPORT std::ostream& operator<<(std::ostream& out,
					     const ossimImageViewTransform& data);
   
   ossimImageViewTransform();

   virtual void forward(const ossimDpt& input, ossimDpt& output) const;
   virtual void inverse(const ossimDpt& input, ossimDpt& output) const;
  
  /*!
   * derived classes will specify if the imageViewTransform is an
   * identity.  
   */
   virtual bool isIdentity()const=0;


   virtual bool isValid()const=0;
   virtual ossimDpt getInputMetersPerPixel()const=0;
   virtual ossimDpt getOutputMetersPerPixel()const=0;
   /*!
   * If it needs to it will use the information passed in to get the
   * scae factor by transforming the line point.x to point.x+deltaXY and 
   * point.y to point.y + deltaXY.y.  It will comput new delta's and 
   * set the ratio of deltaXY/newDeltaXY to the result scale.  
   *
   * Derived classes can overide this default implementation.  Note:
   * if the scale changes are only subpixel then it will return a scale
   * of one.  We have to see how this works before we actually keep this
   * implementation.
   */
  virtual void getImageToViewScale(ossimDpt& resultScale,
				   const ossimDpt& imagePoint,
				   const ossimDpt& deltaImagePointXY=ossimDpt(1.0,1.0))const;

  /*!
   * If it needs to it will use the information passed in to get the
   * scae factor by transforming the line point.x to point.x+deltaXY and 
   * point.y to point.y + deltaXY.y.  It will comput new delta's and 
   * set the ratio of deltaXY/newDeltaXY to the result scale.  
   *
   * Derived classes can overide this default implementation.  Note:
   * if the scale changes are only subpixel then it will return a scale
   * of one.  We have to see how this works before we actually keep this
   * implementation.
   */
  virtual void getViewToImageScale(ossimDpt &resultScale,
                                   const ossimDpt &imagePoint,
                                   const ossimDpt &deltaImagePointXY = ossimDpt(1.0, 1.0)) const;

  virtual void imageToView(const ossimDpt& imagePoint,
                           ossimDpt&       viewPoint)const;
  
  virtual void viewToImage(const ossimDpt& viewPoint,
                           ossimDpt&       imagePoint)const;
  
  virtual std::ostream& print(std::ostream& out) const;
  
  ossimDpt imageToView(const ossimDpt& imagePoint)const;
  
  ossimDpt viewToImage(const ossimDpt& viewPoint)const;
  
  /*!
   * This should compute output/input.
   */
  virtual void getScaleChangeImageToView(ossimDpt& result,
                                         const ossimDrect& imageRect);
  /*!
   * This should compute output/input.
   */
  virtual void getScaleChangeViewToImage(ossimDpt& result,
                                         const ossimDrect& viewRect);
  
  virtual void getRoundTripErrorView(ossimDpt& result,
				     const ossimDpt& viewPt)const;
  
  virtual ossimDpt getRoundTripErrorView(const ossimDpt& viewPt)const;
  
  virtual void getRoundTripErrorImage(ossimDpt& result,
                                      const ossimDpt& imagePt)const;
  
  virtual ossimDpt getRoundTripErrorImage(const ossimDpt& imagePt)const;

  /** Computes the bounding rect in view space of the quad formed by the transformed image points
   * of the input rect corners. */
  virtual ossimDrect getImageToViewBounds(const ossimDrect& imageRect) const;

  /** Computes the bounding rect in image space of the quad formed by the transformed view points
   * of the input rect corners. */
  virtual ossimDrect getViewToImageBounds(const ossimDrect& viewRect) const;

  virtual bool loadState(const ossimKeywordlist& kwl,
                         const char* prefix =0);
  
  virtual bool saveState(ossimKeywordlist& kwl,
                         const char* prefix = 0)const;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimImageViewTransformFactory.h000066400000000000000000000020661352751253100271750ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
//*******************************************************************
//  $Id: ossimImageViewTransformFactory.h 9968 2006-11-29 14:01:53Z gpotts $
#ifndef ossimImageViewTransformFactory_HEADER
#define ossimImageViewTransformFactory_HEADER
#include 

class ossimImageViewTransform;
class ossimKeywordlist;

class ossimImageViewTransformFactory : public ossimObject
{
public:
   static ossimImageViewTransformFactory* instance();
   virtual ossimImageViewTransform* createTransform(const ossimKeywordlist& kwl,
                                                    const char* prefix = 0);
   
protected:
   ossimImageViewTransformFactory(){}//hide
   ossimImageViewTransformFactory(const ossimImageViewTransformFactory&){}
   void operator =(const ossimImageViewTransformFactory&){}

   static ossimImageViewTransformFactory* theInstance;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimIpodSensor.h000066400000000000000000000063611352751253100241630ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
//
// Author:  Garrett Potts
//
// Description:
//
// SkyBox
//*******************************************************************
//  $Id$
#ifndef ossimIpodSensor_HEADER
#define ossimIpodSensor_HEADER
#include "ossimSensorModel.h"
#include "ossimUtmProjection.h"
#include 
class OSSIM_DLL ossimIpodSensor : public ossimSensorModel
{
public:
   ossimIpodSensor();
   ossimIpodSensor(const ossimIpodSensor& src)
   :ossimSensorModel(src),
   m_air2Ned(src.m_air2Ned),
   m_ecef2Ned(src.m_ecef2Ned),
   m_ecef2NedInverse(src.m_ecef2NedInverse),
   m_roll(src.m_roll),
   m_pitch(src.m_pitch),
   m_yaw(src.m_yaw),
   m_principalPoint(src.m_principalPoint), // in meters
   m_pixelSize(src.m_pixelSize),      // in meters
   m_focalLength(src.m_focalLength),    // in meters
   m_ecefPlatformPosition(src.m_ecefPlatformPosition),
   m_platformPosition(src.m_platformPosition),
   m_platformPositionEllipsoid(src.m_platformPositionEllipsoid),
   m_fovIntrack(src.m_fovIntrack),
   m_fovCrossTrack(src.m_fovCrossTrack),
   m_adjustedPlatformPosition(src.m_adjustedPlatformPosition)
   {
   }
   virtual ossimObject* dup()const
   {
      return new ossimIpodSensor(*this);
   }
   
   virtual void imagingRay(const ossimDpt& image_point,
                           ossimEcefRay&   image_ray) const;
   
   void lineSampleHeightToWorld(const ossimDpt& image_point,
                                const double&   heightEllipsoid,
                                ossimGpt&       worldPoint) const;
      //   virtual void worldToLineSample(const ossimGpt& world_point,
   //                                  ossimDpt&       image_point) const;
   virtual void updateModel();
   
   void setRollPitchYaw(double r, double p, double y)
   {
      m_roll  = r;
      m_pitch = p;
      m_yaw   = y;
   }
   void setFocalLength(double value)
   {
      m_focalLength = value;
   }
   void setPlatformPosition(const ossimGpt& value)
   {
      m_platformPosition     = value;
      m_ecefPlatformPosition = value;
   }
   
   void setPrincipalPoint(const ossimDpt& value)
   {
      m_principalPoint = value;
   }
   void setPixelSize(const ossimDpt& value)
   {
      m_pixelSize = value;
   }
   inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM) //TBC
   
   virtual void initAdjustableParameters();
   virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0);
   virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const;
   
protected:
   NEWMAT::Matrix m_air2Ned;
   NEWMAT::Matrix m_ecef2Ned;
   NEWMAT::Matrix m_ecef2NedInverse;

   NEWMAT::Matrix m_composite;
   NEWMAT::Matrix m_compositeInverse;

   double         m_roll;
   double         m_pitch;
   double         m_yaw;
   ossimDpt       m_principalPoint; // in meters
   ossimDpt       m_pixelSize;      // in meters
   double         m_focalLength;    // in meters
   ossimEcefPoint m_ecefPlatformPosition;
   ossimGpt       m_platformPosition;
   ossimGpt       m_platformPositionEllipsoid;
   double         m_fovIntrack;
   double         m_fovCrossTrack;
   
   ossimGpt       m_adjustedPlatformPosition;
   TYPE_DATA
};

#endif

ossim-Miami-2.9.1/include/ossim/projection/ossimLambertConformalConicProjection.h000066400000000000000000000235051352751253100303350ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
//
// Author:  Garrett Potts
//
// Description:
//
// Calls Lamberts Conformal Conic projection code.  
//*******************************************************************
//  $Id: ossimLambertConformalConicProjection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimLambertConformalConicProjection_HEADER
#define ossimLambertConformalConicProjection_HEADER

#include 
#include 

class OSSIMDLLEXPORT ossimLambertConformalConicProjection : public ossimMapProjection
{
public:
   ossimLambertConformalConicProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                                        const ossimGpt& origin = ossimGpt());

   /**
    * @param ellipsoid
    * @param origin latitude longitude in decimal degrees.
    * @param stdParallel1 First parallel in DEGREES.
    * @param stdParallel2 Second parallel in DEGREES.
    * @param falseEasting False easting in meters.
    * @param falseNorthing False northing in meters.
    */
   ossimLambertConformalConicProjection(const ossimEllipsoid& ellipsoid,
                                        const ossimGpt& origin,
                                        double stdParallel1,
                                        double stdParallel2,
                                        double falseEasting,
                                        double falseNorthing);
   
   virtual ~ossimLambertConformalConicProjection();
   
   virtual ossimObject *dup()const;
   
   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();
   
   /*!
    * The passed in Argument is in degrees and will convert it to radians
    * for Geotrans. Update is then called so we can pre-compute paramters.
    */
   void setStandardParallel1(double degree);

   /*!
    * The passed in Argument is in degrees and will convert it to radians
    * for Geotrans. Update is then called so we can pre-compute paramters
    */
   void setStandardParallel2(double degree);

   /*!
    * Will allow you to set both parallels. both are passed in degrees.
    */
   void setStandardParallels(double parallel1Degree,
                             double prallel2Degree);

   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   /**
    * @brief Allows one to set all parameters for this projections.
    * Update is then called so we can pre-compute paramters.
    * @param stdParallel1 First parallel in decimal degrees.
    * @param stdParallel2 Second parallel in decimal degrees.
    * @param falseEasting False easting in meters.
    * @param falseNorthing False northing in meters.
    */
   void setParameters(double parallel1,
                      double parallel2,
                      double falseEasting,
                      double falseNorthing);

   /** @returns the first standard parallel in decimal degrees. */
   virtual double getStandardParallel1() const;

   /** @returns the second standard parallel in decimal degrees. */
   virtual double getStandardParallel2() const;
   
   void setDefaults();

   /*!
   * Method to save the state of an object to a keyword list.
   * Return true if ok or false on error.
   */
  virtual bool saveState(ossimKeywordlist& kwl,
			 const char* prefix=0)const;
  
  /*!
   * Method to the load (recreate) the state of an object from a keyword
   * list.  Return true if ok or false on error.
   */
  virtual bool loadState(const ossimKeywordlist& kwl,
			 const char* prefix=0);
  
  /**
   * @brief Prints data members to stream.  Returns stream&.
   */
   virtual std::ostream& print(std::ostream& out) const;

   //! Returns TRUE if principal parameters are within epsilon tolerance.
   virtual bool operator==(const ossimProjection& projection) const;

private:

   //_______________GEOTRANS____________________
   mutable double Lambert_a;               /* Semi-major axis of ellipsoid, in meters */
   mutable double Lambert_f;       /* Flattening of ellipsoid */
   mutable double es;         /* Eccentricity of ellipsoid */
   mutable double es2;         /* Eccentricity squared */
   mutable double es_OVER_2;        /* Eccentricity / 2.0 */
   mutable double n;                 /* Ratio of angle between meridians */
   mutable double F;                 /* Flattening of ellipsoid */
   mutable double rho0;              /* Height above ellipsoid */
   mutable double Lambert_aF;        /* Lambert_a * F */
   
/* Lambert_Conformal_Conic projection Parameters */
   mutable double Lambert_Std_Parallel_1; /* Lower std. parallel, in radians */
   mutable double Lambert_Std_Parallel_2; /* Upper std. parallel, in radians */
   mutable double Lambert_Origin_Lat;     /* Latitude of origin, in radians */
   mutable double Lambert_Origin_Long;                /* Longitude of origin, in radians */
   mutable double Lambert_False_Northing;             /* False northing, in meters */
   mutable double Lambert_False_Easting;              /* False easting, in meters */

/*!
 * The function Set_Lambert_Parameters receives the ellipsoid parameters and
 * Lambert Conformal Conic projection parameters as inputs, and sets the
 * corresponding state variables.  If any errors occur, the error code(s)
 * are returned by the function, otherwise LAMBERT_NO_ERROR is returned.
 *
 *   a                   : Semi-major axis of ellipsoid, in meters   (input)
 *   f                   : Flattening of ellipsoid				  	       (input)
 *   Origin_Latitude     : Latitude of origin in radians             (input)
 *   Central_Meridian    : Longitude of origin in radians            (input)
 *   Std_Parallel_1      : First standard parallel                   (input)
 *   Std_Parallel_2      : Second standard parallel                  (input)
 *   False_Easting       : False easting in meters                   (input)
 *   False_Northing      : False northing in meters                  (input)
 */
  long Set_Lambert_Parameters(double a,
                              double f,
                              double Origin_Latitude,
                              double Central_Meridian,
                              double Std_Parallel_1,
                              double Std_Parallel_2,
                              double False_Easting,
                              double False_Northing);




/*!
 * The function Get_Lambert_Parameters returns the current ellipsoid
 * parameters and Lambert Conformal Conic projection parameters.
 *
 *   a                   : Semi-major axis of ellipsoid, in meters   (output)
 *   f                   : Flattening of ellipsoid					         (output)
 *   Origin_Latitude     : Latitude of origin, in radians            (output)
 *   Central_Meridian    : Longitude of origin, in radians           (output)
 *   Std_Parallel_1      : First standard parallel                   (output)
 *   Std_Parallel_2      : Second standard parallel                  (output)
 *   False_Easting       : False easting, in meters                  (output)
 *   False_Northing      : False northing, in meters                 (output) 
 */
  void Get_Lambert_Parameters(double *a,
                              double *f,
                              double *Origin_Latitude,
                              double *Central_Meridian,
                              double *Std_Parallel_1,
                              double *Std_Parallel_2,
                              double *False_Easting,
                              double *False_Northing)const;

/*!
 * The function Convert_Geodetic_To_Lambert converts Geodetic (latitude and
 * longitude) coordinates to Lambert Conformal Conic projection (easting
 * and northing) coordinates, according to the current ellipsoid and
 * Lambert Conformal Conic projection parameters.  If any errors occur, the
 * error code(s) are returned by the function, otherwise LAMBERT_NO_ERROR is
 * returned.
 *
 *    Latitude         : Latitude in radians                         (input)
 *    Longitude        : Longitude in radians                        (input)
 *    Easting          : Easting (X) in meters                       (output)
 *    Northing         : Northing (Y) in meters                      (output)
 */
  long Convert_Geodetic_To_Lambert (double Latitude,
                                    double Longitude,
                                    double *Easting,
                                    double *Northing)const;

/*!
 * The function Convert_Lambert_To_Geodetic converts Lambert Conformal
 * Conic projection (easting and northing) coordinates to Geodetic
 * (latitude and longitude) coordinates, according to the current ellipsoid
 * and Lambert Conformal Conic projection parameters.  If any errors occur,
 * the error code(s) are returned by the function, otherwise LAMBERT_NO_ERROR
 * is returned.
 *
 *    Easting          : Easting (X) in meters                       (input)
 *    Northing         : Northing (Y) in meters                      (input)
 *    Latitude         : Latitude in radians                         (output)
 *    Longitude        : Longitude in radians                        (output)
 */
  long Convert_Lambert_To_Geodetic (double Easting,
                                    double Northing,
                                    double *Latitude,
                                    double *Longitude)const;


TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimLandSatModel.h000066400000000000000000000120621352751253100244000ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// DESCRIPTION: Contains declaration of LandSat sensor model class.
//
// SOFTWARE HISTORY:
//   01AUG2002  Oscar Kramer, ImageLinks
//              Initial coding.
//   21NOV2002  Oscar Kramer, ImageLinks
//              Modified selection of adjustable parameters..
//
//*****************************************************************************
//  $Id: ossimLandSatModel.h 15766 2009-10-20 12:37:09Z gpotts $

#ifndef ossimLandSatModel_HEADER
#define ossimLandSatModel_HEADER

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

class ossimFfL7;
class ossimString;
class ossimMapProjection;

//******************************************************************************
//*
//* CLASS:  ossimLandSatModel
//*
//*******************************************************************************
class OSSIMDLLEXPORT ossimLandSatModel : public ossimSensorModel
{
public:
   /*!
    * CONSTRUCTORS:
    */
   ossimLandSatModel();
   ossimLandSatModel(const ossimFfL7& head);
   ossimLandSatModel(const ossimFilename& init_file);
   ossimLandSatModel(const ossimKeywordlist& geom_kwl);
   ossimLandSatModel(const ossimLandSatModel& rhs);
   virtual ossimObject* dup()const;

   enum ProjectionType
   {
      UNKNOWN_PROJECTION = 0,
      UTM_MAP,
      UTM_ORBIT,
      SOM_MAP,
      SOM_ORBIT
   };
   
   enum AdjustParamIndex
   {
      INTRACK_OFFSET = 0,
      CRTRACK_OFFSET,
      LINE_GSD_CORR,
      SAMP_GSD_CORR,
      ROLL_OFFSET,
      YAW_OFFSET,
      YAW_RATE,
      MAP_ROTATION,
      NUM_ADJUSTABLE_PARAMS // not an index
   };
   
   
   /*!
    * Extends base-class implementation. Dumps contents of object to std::ostream.
    */
   virtual std::ostream& print(std::ostream& out) const;
   
   /*!
    * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry
    * KWL files. Returns true if successful.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;
   
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
   /*!
    * Writes a template of geom keywords processed by loadState and saveState
    * to output stream.
    */
   static void writeGeomTemplate(std::ostream& os);
   
   //***
   // Overrides base class pure virtual.
   //***
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                        const double&   heightEllipsoid,
                                        ossimGpt&       worldPoint) const;
   
   /*!
    * Given an image point, returns a ray originating at some arbitrarily high
    * point (ideally at the sensor position) and pointing towards the target.
    */
   virtual void imagingRay(const ossimDpt& image_point,
                           ossimEcefRay&   image_ray) const;

   /*!
    * Following a change to the adjustable parameter set, this virtual
    * is called to permit instances to compute derived quantities after
    * parameter change.
    */
   virtual void updateModel();

   /*!
    * ossimOptimizableProjection
    */
   inline virtual bool useForward()const {return false;} //!image to ground faster
   virtual bool setupOptimizer(const ossimString& init_file); //!uses file path to init model

protected:

   virtual ~ossimLandSatModel();
   /*!
    * Initializes the model given a fast format header.
    */
   void initFromHeader(const ossimFfL7& head);
   
   virtual void initAdjustableParameters();
   void initMapProjection();

   //***
   // Image constant parameters:
   //***
   double           theIllumAzimuth;  
   double           theIllumElevation;
   double           theOrbitAltitude;
   double           theOrbitInclination;
   int              theMapZone;
   ossimDpt         theMapOffset;
   int              theWrsPathNumber;
   int              theWrsRowNumber;    
   double           theMeridianalAngle;   
   double           thePositionError;

   ProjectionType       theProjectionType;
   ossimRefPtr  theMapProjection;

   double           theMapAzimAngle; 
   double           theMapAzimCos;    
   double           theMapAzimSin;
   double           theMap2IcRotAngle;
   double           theMap2IcRotCos;
   double           theMap2IcRotSin;
   
   //***
   // Adjustable parameters:
   //***
   double           theIntrackOffset;
   double           theCrtrackOffset;
   double           theLineGsdCorr;   
   double           theSampGsdCorr;   
   double           theRollOffset;
   double           theYawOffset; 
   double           theYawRate; 
   double           theMapRotation; 

   //***
   // Quantities derived from the adjustable parameters:
   //***
   NEWMAT::Matrix   theRollRotMat;
   
   TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimLensDistortion.h000066400000000000000000000027171352751253100250570ustar00rootroot00000000000000//*******************************************************************
// Copyright (C) 2000 ImageLinks Inc.
//
// MIT
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
// ossimLensDistortion
//*******************************************************************
//  $Id: ossimLensDistortion.h 15929 2009-11-16 18:20:46Z gpotts $

#ifndef ossimLensDistortion_HEADER
#define ossimLensDistortion_HEADER
#include 
class OSSIM_DLL ossimLensDistortion : public ossim2dTo2dTransform
{
public:
   ossimLensDistortion(const ossimDpt& callibratedCenter=ossimDpt(0,0))
      :theCenter(callibratedCenter)
   {
   }
   void setCenter(const ossimDpt& center)
   {
      theCenter = center;
   }
   const ossimDpt& getCenter()const{return theCenter;}
   virtual void forward(const ossimDpt& input,
                        ossimDpt& output) const
   {
      distort(input, output);
   }
   virtual void inverse(const ossimDpt& input,
                        ossimDpt& output)
   {
      undistort(input, output);
   }
   virtual void distort(const ossimDpt& input, ossimDpt& output)const;
   virtual void undistort(const ossimDpt& input, ossimDpt& output)const=0;

   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix = 0)const;
   
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix = 0);
   
protected:
   ossimDpt theCenter;

TYPE_DATA   
};
#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimLlxyProjection.h000066400000000000000000000101131352751253100250510ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  David Burken
//
// Description:
//
// Contains class declaration for ossimLlxy.  This is a simple "latitude /
// longitude to x / y" projection.  Note that "origin" and "tie_point" are
// synonymous in this projection.
// 
//*******************************************************************
//  $Id: ossimLlxyProjection.h 19651 2011-05-25 18:49:22Z gpotts $

#ifndef ossimLlxyProjection_HEADER
#define ossimLlxyProjection_HEADER

#include 

class OSSIMDLLEXPORT ossimLlxyProjection : public ossimMapProjection
{
public:
   ossimLlxyProjection();
   ossimLlxyProjection(const ossimLlxyProjection& rhs);
   ossimLlxyProjection(const ossimEllipsoid& ellipsoid,
                       const ossimGpt& origin);
   ossimLlxyProjection(const ossimGpt& origin,
                       double latSpacing,  // decimal degrees
                       double lonSpacing);
   
   virtual ~ossimLlxyProjection();
   
   virtual ossimObject *dup()const;
   
   virtual bool isGeographic()const;
   
   virtual ossimDpt forward(const ossimGpt &worldPoint) const;
   virtual ossimGpt inverse(const ossimDpt &projectedPoint) const;
   
   /*!
    *  METHOD:  getLatSpacing() 
    *  Returns the latitude spacing as a double representing decimal degrees.
    */
   virtual double getLatSpacing() const;

   /*!
    *  METHOD:  getLonSpacing() 
    *  Returns the longitude spacing as a double representing decimal degrees.
    */
   virtual double getLonSpacing() const;

   /*!
    *  METHOD:  setLatSpacing(double spacing)
    *  Set the latitude spacing as a double representing decimal degrees.
    */
   virtual void   setLatSpacing(double spacing);

    /*!
    *  METHOD:  setLonSpacing(double spacing)
    *  Set the latitude spacing as a double representing decimal degrees.
    */
   virtual void   setLonSpacing(double spacing);

   /*!
    *  METHOD: worldToLineSample()
    * Performs the forward projection from ground point to line, sample.
    */
   virtual void worldToLineSample(const ossimGpt& worldPoint,
                                  ossimDpt&       lineSampPt) const;

   /*!
    * Performs the inverse projection from line, sample to ground (world):
    */
   virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt,
                                        const double&  hgtEllipsoid,
                                        ossimGpt&       worldPt) const;
   
   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   virtual std::ostream& print(std::ostream& out) const;

   virtual bool operator==(const ossimProjection& projection) const;

  //   virtual ossimDpt getMetersPerPixel() const;
   virtual void setMetersPerPixel(const ossimDpt& pt);
   /*!
    * This will go from the ground point and give
    * you an approximate lat and lon per pixel. the Delta Lat
    * and delta lon will be in degrees.
    */
   virtual void computeDegreesPerPixel(const ossimGpt& ground,
                                       const ossimDpt& metersPerPixel,
                                       double &deltaLat,
                                       double &deltaLon);

   
   /*!
    * This will go from the ground point and give
    * you an approximate meters per pixel. the Delta Lat
    * and delta lon will be in degrees.
    */
   virtual void computeMetersPerPixel(const ossimGpt& center,
                                      double deltaDegreesPerPixelLat,
                                      double deltaDegreesPerPixelLon,
                                      ossimDpt &metersPerPixel);
   
private:
   void updateTransform() override;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimMapProjection.h000066400000000000000000000326321352751253100246500ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
//
// Author:  Garrett Potts
//
// Description:
//
// Base class for all map projections.
// 
//*******************************************************************
//  $Id: ossimMapProjection.h 22938 2014-11-01 11:43:35Z okramer $

#ifndef ossimMapProjection_HEADER
#define ossimMapProjection_HEADER 1

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 

class ossimKeywordlist;

class OSSIMDLLEXPORT ossimMapProjection : public ossimProjection
{
public:
   ossimMapProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                      const ossimGpt& origin=ossimGpt());

   ossimMapProjection(const ossimMapProjection& src);

   virtual ossimGpt origin()const;

   /**
    * This method will convert the world coordinate to  model coordinates (easting,
    * northing in meters). It will be necessary then to transform the map coordinates returned by
    * this method into to line, sample by calling eastingNorthingToLineSample(). Alternatively,
    * just use worldToLineSample() to skip the intermediate model coordinates.
    */
   virtual ossimDpt forward(const ossimGpt &worldPoint) const = 0;

   /**
    * Will take a point in meters and convert it to ground.
    * This methid will convert the model coordinates (easting, northing in meters) to world
    * coordinates. Note that the projectedPoint is not line, sample on the image. It is necessary to
    * first transform the image coordinates into to map easting, northing by calling
    * lineSampleToEastingNorthing(). Alternatively, just use lineSampleToWorld() to skip the
    * intermediate model coordinates.
    */
   virtual ossimGpt inverse(const ossimDpt &projectedPoint)const = 0;

   virtual ossimDpt worldToLineSample(const ossimGpt &worldPoint)const;
   virtual void     worldToLineSample(const ossimGpt &worldPoint,
                                      ossimDpt&       lineSample)const;
   
   virtual ossimGpt lineSampleToWorld(const ossimDpt &projectedPoint)const;
   virtual void     lineSampleToWorld(const ossimDpt &projectedPoint,
                                      ossimGpt& gpt)const;
   /**
    * This is the virtual that projects the image point to the given
    * elevation above ellipsoid, thereby bypassing reference to a DEM. Useful
    * for projections that are sensitive to elevation.
    */
   virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt,
                                        const double&   heightAboveEllipsoid,
                                        ossimGpt&       worldPt) const;

   /** Performs image to model coordinate transformation. */
   virtual void lineSampleToEastingNorthing(const ossimDpt& lineSample,
                                            ossimDpt& eastingNorthing) const;

   /** Performs model to image coordinate transformation. */
   virtual void eastingNorthingToLineSample(const ossimDpt& eastingNorthing,
                                            ossimDpt& lineSample) const;

   virtual void eastingNorthingToWorld(const ossimDpt& eastingNorthing,
                                       ossimGpt&       worldPt)const;

   /** @return The false easting. */
   virtual double getFalseEasting() const;

   /** @return The false northing. */
   virtual double getFalseNorthing() const;
   
   /**
    * Derived classes should implement as needed.
    * This implementation returns 0.0.
    * 
    * @return The first standard parallel.
    */
   virtual double getStandardParallel1() const;

   /**
    * Derived classes should implement as needed.
    * This implementation returns 0.0.
    * 
    * @return The second standard parallel.
    */
   virtual double getStandardParallel2() const;
   
   virtual void update();

   virtual void setPcsCode(ossim_uint32 pcsCode);

   //! Returns the EPSG PCS code or 32767 if the projection is a custom (non-EPSG) projection
   virtual ossim_uint32 getPcsCode()const;

   /**
    *  Returns the projection name.
    */
   virtual ossimString getProjectionName() const;
   
   /**
    * ACCESS METHODS: 
    */
   virtual double getA() const;
   virtual double getB() const;
   virtual double getF() const;
   
   virtual ossimDpt getMetersPerPixel() const;

   /**
    * Returns decimal degrees per pixel as an ossimDpt with
    * "x" representing longitude and "y" representing latitude.
    */
   virtual const ossimDpt& getDecimalDegreesPerPixel() const;
   
   virtual const ossimDpt&   getUlEastingNorthing() const;
   virtual const ossimGpt&   getUlGpt() const;
   virtual const ossimDatum* getDatum() const;
   const ossimEllipsoid&     getEllipsoid() const { return theEllipsoid; }
   const ossimGpt& getOrigin() const;
   virtual bool isGeographic()const;

   /**
    * Applies scale to theDeltaLonPerPixel, theDeltaLatPerPixel and theMetersPerPixel data members
    * (eg: theDeltaLonPerPixel *= scale.x). The image-to-model transform is recomputed.
    *
    * @param scale Multiplier to be applied to theDeltaLonPerPixel,
    * theDeltaLatPerPixel and theMetersPerPixel
    *
    * @param recenterTiePoint If true the will adjust the tie point by
    * shifting the original tie to the upper left corner, applying scale,
    * then shifting back by half of either the new
    * theDeltaLat/lon or theMetersPerPixel depending on if projection
    * isGeographic.
    */
   virtual void applyScale(const ossimDpt& scale, bool recenterTiePoint);

   /**
    * Applies clockwise rotation to the image-to-map coordinates. Scale and offset are preserved.
    */
   virtual void applyRotation(const double& azimuth_degrees);
   bool isRotated() const { return (theImageToModelAzimuth != 0.0); }
   const double& getRotation() const { return theImageToModelAzimuth; }
   /**
    * SET METHODS: 
    */
   virtual void setEllipsoid(const ossimEllipsoid& ellipsoid);
   virtual void setAB(double a, double b);

   /**
    * Sets theDatum to datum.
    * Sets theEllipsiod to datum's ellipsiod.
    * Calls update().
    */
   virtual void setDatum(const ossimDatum* datum);

   /**
    * Sets theOrigin to origin.
    * Sets theDatum to origin's datum.
    * Sets theEllipsiod to datum's ellipsiod.
    * Calls update().
    *
    * @param origin The projection origin.
    */
   virtual void setOrigin(const ossimGpt& origin);
   
   virtual void setMetersPerPixel(const ossimDpt& gsd);
   virtual void setDecimalDegreesPerPixel(const ossimDpt& gsd);
   virtual void setUlTiePoints(const ossimGpt& gpt);
   virtual void setUlTiePoints(const ossimDpt& eastingNorthing);
   virtual void setUlEastingNorthing(const  ossimDpt& ulEastingNorthing);
   virtual void setUlGpt(const  ossimGpt& ulGpt);
   virtual void assign( const  ossimProjection &aProjection);
   
   /**
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;

   /**
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   /**
    * Prints data members to stream.  Returns stream&.
    */
   virtual std::ostream& print(std::ostream& out) const;

   /**
    * Compares this to arg projection and returns TRUE if the same. NOTE: As currently implemented,
    * in OSSIM, map projections also contain image geometry information like tiepoint and scale.
    * This operator is only concerned with the map specification and ignores image geometry
    * differences. I.e., theModelTransform is not compared.
    */
   virtual bool operator==(const ossimProjection& projection) const;

   /**
    * Utility method to snap the tie point to some multiple.
    *
    * This is used to overcome inaccuracies in formats like NITF's rpc tag
    * witch has a four digit decimal degree precision for the lat/lon offset.
    *
    * @param multiple Value to snap tie point to like 1.0.
    *
    * @param unitType OSSIM_METERS or OSSIM_DEGREES.
    *
    * EXAMPLE1:
    * projection:    ossimUtmProjection
    * tie point is:  551634.88, 4492036.16
    * multiple:      1.0
    * unitType:      OSSIM_METERS
    * new tie point: 551635.00, 4492036.00
    *
    * EXAMPLE2:
    * projection:    ossimEquDistCylProjection
    * tie point is:  -90.3246343      42.0297589
    * multiple:      0.0001
    * unitType:      OSSIM_DEGREES
    * new tie point: -90.3246 42.0298
    */
   void snapTiePointTo(ossim_float64 multiple, ossimUnitType unitType);
   void snapTiePointToOrigin();
                      
   void setElevationLookupFlag(bool flag);
   bool getElevationLookupFlag()const;

   const ossimMatrix4x4& getModelTransform() const { return theModelTransform; }

   /**
    * Sets the map-to-image rotation, scale and offset. In other words, converts easting, northing
    * in meters to x, y pixels on the image. 
    * @param transform
    */
   void setModelTransform(const ossimMatrix4x4& transform);

   /**
    * @brief Implementation of pure virtual
    * ossimProjection::isAffectedByElevation method.
    * @return false.
    */
   virtual bool isAffectedByElevation() const { return false; }
   
   void setProjectionUnits(ossimUnitType units) { theProjectionUnits = units; }

   /**
    * OSSIM considers all map projection coordinates (including false eastings and northings) to
    * be in meters. However, some standard projection specifications (cf EPSG spec) indicate
    * coordinates in feet (US and Intl). Since the methods forward() and inverse() always deal in
    * meters, the user of this projection may need to convert their map coordinates to meters prior
    * to calling inverse() (and after calling forward() if the coordinates need to be in the
    * original unit. This class keeps track of the original units so that a user can query and
    * convert the map point coordinates to meters as needed.
    */
   ossimUnitType getProjectionUnits() const { return theProjectionUnits; }
   
   virtual bool isEqualTo(const ossimObject& obj, ossimCompareType compareType = OSSIM_COMPARE_FULL)const;


protected:
   //! Computes the approximate resolution in degrees/pixel
   virtual void computeDegreesPerPixel();

   /**
    * This will go from the ground point and give
    * you an approximate meters per pixel. the Delta Lat
    * and delta lon will be in degrees.
    */
   virtual void computeMetersPerPixel();

   /**
    * Recomputes the image-to-model transform given GSD and UL corner parameters
    */
   virtual void updateTransform();

   /** Extracts tiepoint, scale and rotation info from transform */
   virtual void updateFromTransform();

   virtual ~ossimMapProjection();

   /**
    * This method verifies that the projection parameters match the current
    * pcs code.  If not this will set the pcs code to 0.
    *
    * @return true if match, false if not.
    */
   //bool verifyPcsCodeMatches() const;
   
   ossimEllipsoid   theEllipsoid;
   ossimGpt         theOrigin;

   /**
    * This is only set if we want to have built in datum shifting
    */
   const ossimDatum* theDatum;
   
   /**
    * Holds the number of meters per pixel.
    * x = easting
    * y = northing
    */
   ossimDpt          theMetersPerPixel;

   /**
    * Hold the decimal degrees per pixel.
    * x = longitude
    * y = latitude
    */
   ossimDpt          theDegreesPerPixel;

   /** Hold tie point in decimal degrees. */
   ossimGpt          theUlGpt;

   /**
    * Hold tie point as easting northing.
    * x = easting,
    * y = northing
    */
   ossimDpt          theUlEastingNorthing;

   /**
    * Hold the false easting northing.
    * x = false easting,
    * y = false northing
    */
   ossimDpt          theFalseEastingNorthing;

   //! Projection Coordinate System(PCS) code. Mutable because they may update automatically
   //! after the projection is initialized, even in a const method. Normally set to 0 until the
   //! corresponding EPSG code can be determined. If the projection is NOT represented by any
   //! EPSG code, then the PCS is set to 32767.
   mutable ossim_uint32      thePcsCode;

   bool              theElevationLookupFlag;

   /**
    * Will always be a 4x4 matrix. Provides affine scaling, rotation, and offset to the image line,
    * sample (x, y) to arrive at the map coordinates (easting, northing). The latter are then
    * projected to the ground given specific map projection equations. Note: only the first 2 rows
    * are used as follows.
    *                      [ e, n ]t = M(4-cols x 2-rows) * [ x, y, 0, 1 ]t   (t = transpose)
    * See GeoTIFF tag 34264 specification.
    */
   ossimMatrix4x4 theModelTransform; // goes from image to model
   ossimMatrix4x4 theInverseModelTransform; //goes from model back to image

   //! Linear units of the projection as indicated in the projection's specification. All projections
   //! internal to OSSIM use meters. The EPSG spec may indicate otherwise so users can check if
   //! they need to convert original map coordinates to meters by checking this:
   ossimUnitType theProjectionUnits;

   /** Image azimuth relative to map model coordinates. Applies to image-to-model transform */
   double theImageToModelAzimuth;

TYPE_DATA
};


#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimMapProjectionFactory.h000066400000000000000000000042201352751253100261700ustar00rootroot00000000000000//*******************************************************************
//
// License:  MIT
// 
// See LICENSE.txt file in the top level directory for more details.
// 
// Author:  Garrett Potts
//
// Description:
//
// class ossimProjectionFactory maintains a static list of projection
// makers.  If a user wants to create a projection they can pass in
// a projection name and a datum if desired.  Currently the default
// datum will be WGS84.
//*******************************************************************
//  $Id: ossimMapProjectionFactory.h 15766 2009-10-20 12:37:09Z gpotts $

#ifndef ossimMapProjectionFactory_HEADER
#define ossimMapProjectionFactory_HEADER

#include 

class ossimProjection;
class ossimString;

class OSSIMDLLEXPORT ossimMapProjectionFactory : public ossimProjectionFactoryBase
{
public:
   /*!
    * METHOD: instance()
    * Instantiates singleton instance of this class:
    */
   static ossimMapProjectionFactory* instance();

   virtual ossimProjection* createProjection(const ossimFilename& filename,
                                             ossim_uint32 entryIdx)const;
   /*!
    * METHOD: create()
    * Attempts to create an instance of the projection specified by name.
    * Returns successfully constructed projection or NULL.
    */
   virtual ossimProjection* createProjection(const ossimString& name)const;
   virtual ossimProjection* createProjection(const ossimKeywordlist& kwl,
                                             const char* prefix = 0)const;
   virtual ossimObject* createObject(const ossimString& typeName)const;

   /*!
    * Creates and object given a keyword list.
    */
   virtual ossimObject* createObject(const ossimKeywordlist& kwl,
                                     const char* prefix=0)const;
   
   /*!
    * This should return the type name of all objects in all factories.
    * This is the name used to construct the objects dynamially and this
    * name must be unique.
    */
   virtual void getTypeNameList(std::vector& typeList)const;

protected:
   ossimMapProjectionFactory() {}
   static ossimMapProjectionFactory*  theInstance;
 
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimMapProjectionInfo.h000066400000000000000000000175571352751253100254750ustar00rootroot00000000000000//*******************************************************************
// Copyright (C) 2001 ImageLinks Inc.
//
// License:  MIT
//
// See LICENSE.txt file in the top level directory for more details.
//
// Author:  David Burken
//
// Description:
// Class for encapsulate projection info given a projection, datum, and
// output rectangle.
//
// NOTE:
// - Output rectangle should be relative to the center of pixels.
//   Shifts will be made for "pixel is area" internally.
//
//*******************************************************************
//  $Id: ossimMapProjectionInfo.h 11959 2007-10-31 19:22:56Z gpotts $

#ifndef ossimMapProjectionInfo_HEADER
#define ossimMapProjectionInfo_HEADER

#include 
#include 
#include 
#include 
#include 
#include 

class ossimMapProjection;
class ossimImageChain;

class OSSIMDLLEXPORT ossimMapProjectionInfo : public ossimObject
{
public:

   ossimMapProjectionInfo(const ossimMapProjection* proj,
                          const ossimDrect& output_rect);

   virtual ~ossimMapProjectionInfo();

   /**
    *  Returns true on error false if ok.
    */
   bool errorStatus() const;

   /**
    * Adds tie point to keyword list.  This will be latitude, longitude if
    * projection is geographic; else, easting, northing.
    */
   void getGeom(ossimKeywordlist& kwl, const char* prefix=0)const;

   /**
    *  Returns the pixel size in meters.
    *  x = sample direction
    *  y = line direction
    */
   ossimDpt getMetersPerPixel() const;
   
   /**
    *  Returns the pixel size in U.S. Survey feet.
    *  x = sample direction
    *  y = line direction
    *
    *  NOTE:
    *  The US survey feet per meter converion (0.3048006096 feet per meter)
    *  is NOT the same as the standard feet per meter conversion
    *  (0.3048 feet per meter).
    */
   ossimDpt getUsSurveyFeetPerPixel() const;

   /**
    *  Returns the decimal degrees per pixel.
    *  x = sample direction
    *  y = line direction
    */
   ossimDpt getDecimalDegreesPerPixel() const;
   
   /**
    *  Returns the upper left easting and northing as a ossimDpt.
    *  The easting is "u" and the northing is "v". Units are in meters.
    */
   ossimDpt ulEastingNorthingPt() const;

   /**
    *  Returns the upper right easting and northing as a ossimDpt.
    *  The easting is "u" and the northing is "v". Units are in meters.
    */
   ossimDpt urEastingNorthingPt() const;

   /**
    *  Returns the lower right easting and northing as a ossimDpt.
    *  The easting is "u" and the northing is "v". Units are in meters.
    */
   ossimDpt lrEastingNorthingPt() const;

   /**
    *  Returns the lower left easting and northing as a ossimDpt.
    *  The easting is "u" and the northing is "v". Units are in meters.
    */
   ossimDpt llEastingNorthingPt() const;
   
   /**
    *  Returns the upper left easting and northing as a ossimDpt.
    *  The easting is "u" and the northing is "v".
    *  Units are in U.S. Survey feet.
    */
   ossimDpt ulEastingNorthingPtInFt() const;

   /**
    *  Returns the upper right easting and northing as a ossimDpt.
    *  The easting is "u" and the northing is "v".
    *  Units are in U.S. Survey feet.
    */
   ossimDpt urEastingNorthingPtInFt() const;

   /**
    *  Returns the lower right easting and northing as a ossimDpt.
    *  The easting is "u" and the northing is "v".
    *  Units are in U.S. Survey feet.
    */
   ossimDpt lrEastingNorthingPtInFt() const;

   /**
    *  Returns the lower left easting and northing as a ossimDpt.
    *  The easting is "u" and the northing is "v". 
    *  Units are in U.S. Survey feet.
    */
   ossimDpt llEastingNorthingPtInFt() const;
   
   /**
    * Returns the upper left ground point.
    */
   ossimGpt ulGroundPt() const;

   /**
    * Returns the upper right ground point.
    */
   ossimGpt urGroundPt() const;

   /**
    * Returns the lower right ground point.
    */
   ossimGpt lrGroundPt() const;
 
   /**
    * Returns the lower left ground point.
    */
   ossimGpt llGroundPt() const;

   /**
    * Returns the center ground point.
    */
   ossimGpt centerGroundPt() const;

   /** @return The center ground point. */
   ossimDpt centerEastingNorthingPt() const;

   /** @return The lines per image. */
   ossim_int32 linesPerImage() const;

   /** @return The pixels per line (samples). */
   ossim_int32 pixelsPerLine() const;

   /**
    * Formatted print of data members.  Used by operator <<.
    */
   std::ostream& print(std::ostream& os) const;

   /**
    *  Sets the data member "thePixelType".
    *  NOTE:
    *  PIXEL_IS_POINT (ennumerated to a "0"):
    *  Corner coordinates are relative to the center of pixel.
    *  PIXEL_IS_AREA (ennumerated to a "1"):
    *  Corner coordinates are relative to the outer edge of the pixel.
    */
   void setPixelType (ossimPixelType type);

   /**
    *  Returns data member "thePixelType".
    *  NOTE:
    *  OSSIM_PIXEL_IS_POINT (ennumerated to a "0"):
    *  Corner coordinates are relative to the center of pixel.
    *  OSSIM_PIXEL_IS_AREA (ennumerated to a "1"):
    *  Corner coordinates are relative to the outer of the pixel.
    */
   ossimPixelType  getPixelType () const;

   /**
    * Sets the data member "theOutputInfoInFeetFlag".
    */
   void setOutputFeetFlag (bool flag);

   /**
    *  Returns the data member "theOutputInfoInFeetFlag".
    *  True = feet, false = meters.
    */
   bool unitsInFeet() const;

   /**
    * Returns theImageInfoString.
    */
   ossimString getImageInfoString () const;

   /**
    *  Used to set data member "theImageInfoString".  This will be output
    *  in the "Image: " field of the README file.
    */
   void setImageInfoString (const ossimString& string);

   /**
    * Returns reference to "theProjection".
    */
   const ossimMapProjection* getProjection() const;

   //****
   // Keywords for getStateFrom/saveStateTo.
   //***
   static const char* README_IMAGE_STRING_KW;
   static const char* PIXEL_TYPE_KW;
   static const char* OUTPUT_US_FT_INFO_KW;
   
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix = 0);
   
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix = 0) const;
   
private:

   // Do not permit construction with void args.
   ossimMapProjectionInfo();
   ossimMapProjectionInfo& operator=(const ossimMapProjectionInfo&);
   
   void initializeMembers(const ossimDrect& output_rect);
   
   const ossimMapProjection* theProjection;
   mutable bool              theErrorStatus;
   int                       theLinesPerImage;
   int                       thePixelsPerLine;
   ossimGpt                  theCornerGroundPt[4];
   ossimDpt                  theCornerEastingNorthingPt[4];
   ossimGpt                  theCenterGroundPt;
   ossimDpt                  theCenterEastingNorthingPt;
   ossimDrect                theBoundingRect;
   
   /**
    *   "thePixelType" defines whether the tie point coordinates are
    *   relative to the center of the pixel(which is PIXEL_IS_POINT) or
    *   the upper left corner of the pixel(PIXEL_IS_AREA).  The default
    *   pixle type is PIXEL_IS_POINT.
    */
   ossimPixelType                 thePixelType;

   /**
    *   If "theOutputInfoInFeetFlag" is true the readme file tie point
    *   info will be output in both meters and U.S. feet.
    *   NOTE:
    *   U.S. feet conversion is "meters/0.3048006096" not the standard
    *   "meters/0.3048".
    *   Reference for U.S. feet value:
    *   U.S.G.S. "Map Projections - A Working Manual" USGS Professional
    *   paper 1395 page 51.
    */
   bool                      theOutputInfoInFeetFlag;

   /**
    *   "theImageInfoString" goes in the README file "Image:" field
    *   to identify the image.
    */
   ossimString               theImageInfoString;
};

#endif /* End of #ifndef ossimMapProjectionInfo_HEADER */
ossim-Miami-2.9.1/include/ossim/projection/ossimMapViewController.h000066400000000000000000000033611352751253100255070ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author: Garrett Potts (gpotts@imagelinks)
//
//*************************************************************************
// $Id: ossimMapViewController.h 9968 2006-11-29 14:01:53Z gpotts $
#ifndef ossimMapViewController_HEADER
#define ossimMapViewController_HEADER
#include 
#include 

class ossimMapViewController : public ossimViewController
{
public:
   ossimMapViewController();
   ossimMapViewController(ossimObject* owner,
                          ossim_uint32 inputListSize,
                          ossim_uint32 outputListSize,
                          bool         inputListFixedFlag=true,
                          bool         outputListFixedFlag=false);

   virtual ~ossimMapViewController();
   virtual bool setView(ossimObject* object);
   virtual void changeOwner(ossimObject* owner);
   virtual void setFilename(const ossimFilename& file);
   virtual const ossimFilename& getFilename()const
      {
         return theGeometryFile;
      }
   
   virtual ossimString getShortName()const
      {
         return ossimString("Map View");
      }
   
   virtual ossimString getLongName()const
      {
         return ossimString("Map View controller");
      }
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
protected:

   /*!
    * If the file is not "" (empty) then it will
    * use this filename to load and save the geometry
    * projection.
    */
   ossimFilename theGeometryFile;
   
TYPE_DATA
};
#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimMeanRadialLensDistortion.h000066400000000000000000000074301352751253100267720ustar00rootroot00000000000000//*******************************************************************
// Copyright (C) 2000 ImageLinks Inc.
//
// MIT
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
// MeanRadialLensDistortion
//*******************************************************************
//  $Id: ossimMeanRadialLensDistortion.h 15929 2009-11-16 18:20:46Z gpotts $
#ifndef ossimMeanRadialLensDistortion_HEADER
#define ossimMeanRadialLensDistortion_HEADER
#include 
#include 
#include 
#include 
class ossimMeanRadialLensDistortion : public ossimLensDistortion
{
public:
   ossimMeanRadialLensDistortion()
   {
      theCoefficients.resize(4);
      theCoefficients[0] = 0.0;
      theCoefficients[1] = 0.0;
      theCoefficients[2] = 0.0;
      theCoefficients[3] = 0.0;
   }

  /*!
   * Instantiate a ossimMeanRadialLens with the calibrated data.
   * The data consists of the Principal point,
   * focal distance, radialDistance measures for the distortion
   * deltas, the radial distortion values.
   * 
   * example of construction:
   *
   * lets say we have the following:
   *
   * principal point = (.008 , -.001) mm
   *
   * and
   *
   * field angle       radial distance       deltaR (distortion)
   *_____________________________________________________________
   *  7.5 deg.             .004 mm             .0202 mm
   *  15 deg.              .007 mm             .0411 mm
   *  22.5 deg.            .007 mm             .0635 mm
   *  :
   *  :
   *  :
   *
   * then construct the ossimMeanRadialLensDistortion class to construct the
   * given focal length and principal point and the middle column as
   * the radial distance column vector and the third column as the
   * distortion values.
   */
/*    ossimMeanRadialLensDistortion(ossimDpt    calibratedPrincipalPoint, */
/*                                  const NEWMAT::ColumnVector &radialDistance, */
/*                                  const NEWMAT::ColumnVector &radialDistortion) */
   ossimMeanRadialLensDistortion(ossimDpt    calibratedPrincipalPoint,
                                 const NEWMAT::ColumnVector &radialDistance,
                                 const NEWMAT::ColumnVector &radialDistortion)
      :ossimLensDistortion(calibratedPrincipalPoint)
  {
     theCoefficients.resize(4);
     solveCoefficients(radialDistance, radialDistortion);
  }
      
  /*!
   * Returns the coefficients (k1, k2, k3, k4) for the deltaR polynomial:
   *
   *    deltaR = k1*r + k2*r^3 + k3*r^5 + k4*r^7
   */
  const std::vector& getCoefficients()const{return theCoefficients;}
  std::vector& getCoefficients(){return theCoefficients;}


//  ossimDpt adjustPoint(const ossimDpt &position)const;
  virtual std::ostream& print(std::ostream& out) const
  {return out;}

  /*!
   * dletaR computes how much we should adjust r.  The
   * return value is the adjustment amount.  This method is used
   * by adjustPoint.
   */
  double deltaR(double r)const;

  virtual void undistort(const ossimDpt& input, ossimDpt& output)const;
  
  /*!
   * solves the coefficients given the radial distances and distortion
   * for each distance.
   */
  void solveCoefficients(const NEWMAT::ColumnVector &radialDistance,
			 const NEWMAT::ColumnVector &radialDistortion);
  /*!
   * solves the coefficients given the radial distances and distortion
   * for each distance.
   */
  void solveCoefficients(const std::vector& radialDistance,
			 const std::vector& radialDistortion);
  
  virtual bool saveState(ossimKeywordlist& kwl,
                         const char* prefix = 0)const;
  
  virtual bool loadState(const ossimKeywordlist& kwl,
                         const char* prefix = 0);
  
protected:
  std::vector theCoefficients;
  
TYPE_DATA  
};


#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimMercatorProjection.h000066400000000000000000000215101352751253100257000ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
// Calls Geotrans Mercator projection code.  
//*******************************************************************
//  $Id: ossimMercatorProjection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimMercatorProjection_HEADER
#define ossimMercatorProjection_HEADER

#include 

class OSSIMDLLEXPORT ossimMercatorProjection : public ossimMapProjection
{
public:
   
   ossimMercatorProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                           const ossimGpt& origin = ossimGpt());
   
   ossimMercatorProjection(const ossimEllipsoid& ellipsoid,
                           const ossimGpt& origin,
                           double falseEasting,
                           double falseNorthing,
                           double scaleFactor);
   ~ossimMercatorProjection(){}
   virtual ossimObject *dup()const{return new ossimMercatorProjection(*this);}

   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();   
   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   /*!
    * sets the scale.
    */
   void setScaleFactor(double scaleFactor);

   /*!
    * Allows one to set all parameters for this projections.  parallels are in
    * degrees and easting northings are in meters.
    * Update is then called so we can pre-compute paramters.
    */
   void setParameters(double falseEasting,
                      double falseNorthing,
                      double scaleFactor);  
   void setDefaults();
  
   double getFalseEasting()const{return Merc_False_Easting;}
   double getFalseNorthing()const{return Merc_False_Northing;}
   double getScaleFactor()const{return Merc_Scale_Factor;}
   
   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
   //! Returns TRUE if principal parameters are within epsilon tolerance.
   virtual bool operator==(const ossimProjection& projection) const;

private:
   //_________________GEOTRANS STUFF____________________________

   mutable double Merc_a;    /* Semi-major axis of ellipsoid in meters */
   mutable double Merc_f;      /* Flattening of ellipsoid */
   mutable double Merc_e; /* Eccentricity of ellipsoid    */
   mutable double Merc_es; /* Eccentricity squared         */
   
/* Mercator projection Parameters */
   mutable double Merc_Origin_Lat;      /* Latitude of origin in radians     */
   mutable double Merc_Origin_Long;     /* Longitude of origin in radians    */
   mutable double Merc_False_Northing;  /* False northing in meters          */
   mutable double Merc_False_Easting;   /* False easting in meters           */
   mutable double Merc_Scale_Factor;    /* Scale factor                      */
   
/* Isometric to geodetic latitude parameters, default to WGS 84 */
   mutable double Merc_ab;
   mutable double Merc_bb;
   mutable double Merc_cb;
   mutable double Merc_db;
   
/* Maximum variance for easting and northing values for WGS 84.
 */
   mutable double Merc_Delta_Easting;
   mutable double Merc_Delta_Northing;
   

   bool theSphericalFlag;
/*!
 * The function Set_Mercator_Parameters receives the ellipsoid parameters and
 * Mercator projcetion parameters as inputs, and sets the corresponding state 
 * variables.  It calculates and returns the scale factor.  If any errors
 * occur, the error code(s) are returned by the function, otherwise 
 * MERC_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid						        (input)
 *    Origin_Latitude   : Latitude in radians at which the          (input)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)
 *    Scale_Factor      : Multiplier which reduces distances in the 
 *                          projection to the actual distance on the
 *                          ellipsoid                               (output)
 */
  long Set_Mercator_Parameters(double a,      
                               double f,
                               double Origin_Latitude,
                               double Central_Meridian,
                               double False_Easting,
                               double False_Northing,
                               double *Scale_Factor);


/*!
 * The function Get_Mercator_Parameters returns the current ellipsoid
 * parameters, Mercator projection parameters, and scale factor.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid						        (output)
 *    Origin_Latitude   : Latitude in radians at which the          (output)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output)
 *    Scale_Factor      : Multiplier which reduces distances in the 
 *                          projection to the actual distance on the
 *                          ellipsoid                               (output)
 */
  void Get_Mercator_Parameters(double *a,
                               double *f,
                               double *Origin_Latitude,
                               double *Central_Meridian,
                               double *False_Easting,
                               double *False_Northing,
                               double *Scale_Factor)const;


/*!
 * The function Convert_Geodetic_To_Mercator converts geodetic (latitude and
 * longitude) coordinates to Mercator projection easting, and northing
 * coordinates, according to the current ellipsoid and Mercator projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise MERC_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Mercator (double Latitude,
                                     double Longitude,
                                     double *Easting,
                                     double *Northing)const;


/*!
 * The function Convert_Mercator_To_Geodetic converts Mercator projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Mercator projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise MERC_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Mercator_To_Geodetic(double Easting,
                                    double Northing,
                                    double *Latitude,
                                    double *Longitude)const;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimMgrs.h000066400000000000000000000237221352751253100230060ustar00rootroot00000000000000#ifndef MGRS_H
#define MGRS_H 1

/***************************************************************************/
/* RSC IDENTIFIER:  MGRS
 *
 * ABSTRACT
 *
 *    This component converts between geodetic coordinates (latitude and 
 *    longitude) and Military Grid Reference System (MGRS) coordinates. 
 *
 * ERROR HANDLING
 *
 *    This component checks parameters for valid values.  If an invalid value
 *    is found, the error code is combined with the current error code using 
 *    the bitwise or.  This combining allows multiple error codes to be
 *    returned. The possible error codes are:
 *
 *          MGRS_NO_ERROR          : No errors occurred in function
 *          MGRS_LAT_ERROR         : Latitude outside of valid range 
 *                                    (-90 to 90 degrees)
 *          MGRS_LON_ERROR         : Longitude outside of valid range
 *                                    (-180 to 360 degrees)
 *          MGRS_STR_ERROR         : An MGRS string error: string too long,
 *                                    too short, or badly formed
 *          MGRS_PRECISION_ERROR   : The precision must be between 0 and 5 
 *                                    inclusive.
 *          MGRS_A_ERROR           : Semi-major axis less than or equal to zero
 *          MGRS_INV_F_ERROR       : Inverse flattening outside of valid range
 *									                  (250 to 350)
 *          MGRS_EASTING_ERROR     : Easting outside of valid range
 *                                    (100,000 to 900,000 meters for UTM)
 *                                    (0 to 4,000,000 meters for UPS)
 *          MGRS_NORTHING_ERROR    : Northing outside of valid range
 *                                    (0 to 10,000,000 meters for UTM)
 *                                    (0 to 4,000,000 meters for UPS)
 *          MGRS_ZONE_ERROR        : Zone outside of valid range (1 to 60)
 *          MGRS_HEMISPHERE_ERROR  : Invalid hemisphere ('N' or 'S')
 *
 * REUSE NOTES
 *
 *    MGRS is intended for reuse by any application that does conversions
 *    between geodetic coordinates and MGRS coordinates.
 *
 * REFERENCES
 *
 *    Further information on MGRS can be found in the Reuse Manual.
 *
 *    MGRS originated from : U.S. Army Topographic Engineering Center
 *                           Geospatial Information Division
 *                           7701 Telegraph Road
 *                           Alexandria, VA  22310-3864
 *
 * LICENSES
 *
 *    None apply to this component.
 *
 * RESTRICTIONS
 *
 *
 * ENVIRONMENT
 *
 *    MGRS was tested and certified in the following environments:
 *
 *    1. Solaris 2.5 with GCC version 2.8.1
 *    2. Windows 95 with MS Visual C++ version 6
 *
 * MODIFICATIONS
 *
 *    Date              Description
 *    ----              -----------
 *    16-11-94          Original Code
 *    15-09-99          Reengineered upper layers
 *
 */

#include  /* for OSSIM_DLL */

/***************************************************************************/
/*
 *                              DEFINES
 */

#define OSSIM_MGRS_NO_ERROR                0x0000
#define OSSIM_MGRS_LAT_ERROR               0x0001
#define OSSIM_MGRS_LON_ERROR               0x0002
#define OSSIM_MGRS_STRING_ERROR            0x0004
#define OSSIM_MGRS_PRECISION_ERROR         0x0008
#define OSSIM_MGRS_A_ERROR                 0x0010
#define OSSIM_MGRS_INV_F_ERROR             0x0020
#define OSSIM_MGRS_EASTING_ERROR           0x0040
#define OSSIM_MGRS_NORTHING_ERROR          0x0080
#define OSSIM_MGRS_ZONE_ERROR              0x0100
#define OSSIM_MGRS_HEMISPHERE_ERROR        0x0200


/***************************************************************************/
/*
 *                              FUNCTION PROTOTYPES
 */

/* ensure proper linkage to c++ programs */
  #ifdef __cplusplus
extern "C" {
  #endif


   OSSIM_DLL long Set_OSSIM_MGRS_Parameters(double a,
                                            double f,
                                            const char* Ellipsoid_Code);
/*
 * The function Set_MGRS_Parameters receives the ellipsoid parameters and sets
 * the corresponding state variables. If any errors occur, the error code(s)
 * are returned by the function, otherwise MGRS_NO_ERROR is returned.
 *
 *   a                : Semi-major axis of ellipsoid in meters (input)
 *   f                : Flattening of ellipsoid                (input)
 *   Ellipsoid_Code   : 2-letter code for ellipsoid            (input)
 */


  OSSIM_DLL void Get_OSSIM_MGRS_Parameters(double *a,
                                           double *f,
                                           char   *Ellipsoid_Code);
/*
 * The function Get_MGRS_Parameters returns the current ellipsoid
 * parameters.
 *
 *  a                : Semi-major axis of ellipsoid, in meters (output)
 *  f                : Flattening of ellipsoid					       (output)
 *  Ellipsoid_Code   : 2-letter code for ellipsoid             (output)
 */


   OSSIM_DLL long Convert_Geodetic_To_OSSIM_MGRS (double Latitude,
                                                  double Longitude,
                                                  long   Precision,
                                                  char *MGRS);
/*
 * The function Convert_Geodetic_To_MGRS converts geodetic (latitude and
 * longitude) coordinates to an MGRS coordinate string, according to the 
 * current ellipsoid parameters.  If any errors occur, the error code(s) 
 * are returned by the  function, otherwise MGRS_NO_ERROR is returned.
 *
 *    Latitude   : Latitude in radians              (input)
 *    Longitude  : Longitude in radians             (input)
 *    Precision  : Precision level of MGRS string   (input)
 *    MGRS       : MGRS coordinate string           (output)
 *  
 */


   OSSIM_DLL long Convert_OSSIM_MGRS_To_Geodetic (const char *MGRS,
                                                  double *Latitude,
                                                  double *Longitude);
/*
 * This function converts an MGRS coordinate string to Geodetic (latitude
 * and longitude in radians) coordinates.  If any errors occur, the error 
 * code(s) are returned by the  function, otherwise MGRS_NO_ERROR is returned.  
 *
 *    MGRS       : MGRS coordinate string           (input)
 *    Latitude   : Latitude in radians              (output)
 *    Longitude  : Longitude in radians             (output)
 *  
 */


   OSSIM_DLL long Convert_UTM_To_OSSIM_MGRS (long Zone,
                                             char Hemisphere,
                                             double Easting,
                                             double Northing,
                                             long Precision,
                                             char *MGRS);
/*
 * The function Convert_UTM_To_MGRS converts UTM (zone, easting, and
 * northing) coordinates to an MGRS coordinate string, according to the 
 * current ellipsoid parameters.  If any errors occur, the error code(s) 
 * are returned by the  function, otherwise MGRS_NO_ERROR is returned.
 *
 *    Zone       : UTM zone                         (input)
 *    Hemisphere : North or South hemisphere        (input)
 *    Easting    : Easting (X) in meters            (input)
 *    Northing   : Northing (Y) in meters           (input)
 *    Precision  : Precision level of MGRS string   (input)
 *    MGRS       : MGRS coordinate string           (output)
 */


  OSSIM_DLL long Convert_OSSIM_MGRS_To_UTM (const char   *MGRS,
                                            long   *Zone,
                                            char   *Hemisphere,
                                            double *Easting,
                                            double *Northing); 
/*
 * The function Convert_MGRS_To_UTM converts an MGRS coordinate string
 * to UTM projection (zone, hemisphere, easting and northing) coordinates 
 * according to the current ellipsoid parameters.  If any errors occur, 
 * the error code(s) are returned by the function, otherwise UTM_NO_ERROR 
 * is returned.
 *
 *    MGRS       : MGRS coordinate string           (input)
 *    Zone       : UTM zone                         (output)
 *    Hemisphere : North or South hemisphere        (output)
 *    Easting    : Easting (X) in meters            (output)
 *    Northing   : Northing (Y) in meters           (output)
 */



   OSSIM_DLL long Convert_UPS_To_OSSIM_MGRS ( char   Hemisphere,
                                              double Easting,
                                              double Northing,
                                              long Precision,
                                              char *MGRS);

/*
 *  The function Convert_UPS_To_MGRS converts UPS (hemisphere, easting, 
 *  and northing) coordinates to an MGRS coordinate string according to 
 *  the current ellipsoid parameters.  If any errors occur, the error
 *  code(s) are returned by the function, otherwise UPS_NO_ERROR is 
 *  returned.
 *
 *    Hemisphere    : Hemisphere either 'N' or 'S'     (input)
 *    Easting       : Easting/X in meters              (input)
 *    Northing      : Northing/Y in meters             (input)
 *    Precision     : Precision level of MGRS string   (input)
 *    MGRS          : MGRS coordinate string           (output)
 */


   OSSIM_DLL long Convert_OSSIM_MGRS_To_UPS ( const char   *MGRS,
                                              char   *Hemisphere,
                                              double *Easting,
                                              double *Northing);
/*
 *  The function Convert_MGRS_To_UPS converts an MGRS coordinate string
 *  to UPS (hemisphere, easting, and northing) coordinates, according 
 *  to the current ellipsoid parameters. If any errors occur, the error 
 *  code(s) are returned by the function, otherwide UPS_NO_ERROR is returned.
 *
 *    MGRS          : MGRS coordinate string           (input)
 *    Hemisphere    : Hemisphere either 'N' or 'S'     (output)
 *    Easting       : Easting/X in meters              (output)
 *    Northing      : Northing/Y in meters             (output)
 */
   


  #ifdef __cplusplus
}
  #endif

#endif /* MGRS_H */
ossim-Miami-2.9.1/include/ossim/projection/ossimMillerProjection.h000066400000000000000000000156121352751253100253560ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
// Calls Geotrans Miller projection code.  
//*******************************************************************
//  $Id: ossimMillerProjection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimMillerProjection_HEADER
#define ossimMillerProjection_HEADER

#include 

class OSSIMDLLEXPORT ossimMillerProjection : public ossimMapProjection
{
public:
   ossimMillerProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                         const ossimGpt& origin = ossimGpt());
   ossimMillerProjection(const ossimEllipsoid& ellipsoid,
                         const ossimGpt& origin,
                         const double falseEasting,
                         const double falseNorthing);
   
   ~ossimMillerProjection(){}
   
   virtual ossimObject *dup()const{return new ossimMillerProjection(*this);}

   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();

   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   void setDefaults();

   void setCentralMeridian(double centralMeridian);

   double getFalseEasting()const{return Mill_False_Easting;}
   double getFalseNorthing()const{return Mill_False_Northing;}
   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
private:

   //________________GEOTRANS STUFF___________________

   mutable double Mill_a;   /* Semi-major axis of ellipsoid in meters */
   mutable double Mill_f;   /* Flattening of ellipsoid */
   mutable double es2;      /* Eccentricity (0.08181919084262188000) squared         */
   mutable double es4;      /* es2 * es2	*/
   mutable double es6;      /* es4 * es2   */
   mutable double Ra;       /* Spherical Radius */
   
/* Miller projection Parameters */
   mutable double Mill_Origin_Long;                  /* Longitude of origin in radians    */
   mutable double Mill_False_Easting;
   mutable double Mill_False_Northing;
   mutable double Mill_Delta_Northing;
   mutable double Mill_Max_Easting;
   mutable double Mill_Min_Easting;
   
/*!
 * The function Set_Miller_Parameters receives the ellipsoid parameters and
 * Miller Cylindrical projcetion parameters as inputs, and sets the corresponding
 * state variables.  If any errors occur, the error code(s) are returned by the 
 * function, otherwise MILL_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid						        (input)
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)
 */
  long Set_Miller_Parameters(double a,
                             double f,
                             double Central_Meridian,
                             double False_Easting,
                             double False_Northing);


/*!
 * The function Get_Miller_Parameters returns the current ellipsoid
 * parameters and Miller Cylindrical projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid						        (output)
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output)
 */
  void Get_Miller_Parameters(double *a,
                             double *f,
                             double *Central_Meridian,
                             double *False_Easting,
                             double *False_Northing)const;


/*!
 * The function Convert_Geodetic_To_Miller converts geodetic (latitude and
 * longitude) coordinates to Miller Cylindrical projection easting, and northing
 * coordinates, according to the current ellipsoid and Miller Cylindrical projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise MILL_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Miller (double Latitude,
                                   double Longitude,
                                   double *Easting,
                                   double *Northing)const;


/*!
 * The function Convert_Miller_To_Geodetic converts Miller Cylindrical projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Miller Cylindrical projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise MILL_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Miller_To_Geodetic(double Easting,
                                  double Northing,
                                  double *Latitude,
                                  double *Longitude)const;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimMiscProjectionFactory.h000066400000000000000000000041341352751253100263520ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
//
// Author:  Garrett Potts
//
// Description:
//
// class ossimProjectionFactory maintains a static list of projection
// makers.  If a user wants to create a projection they can pass in
// a projection name and a datum if desired.  Currently the default
// datum will be WGS84.
//*******************************************************************
//  $Id: ossimMiscProjectionFactory.h 12081 2007-11-26 21:44:18Z dburken $

#ifndef ossimMiscProjectionFactory_HEADER
#define ossimMiscProjectionFactory_HEADER

#include 

class ossimProjection;
class ossimString;

class ossimMiscProjectionFactory : public ossimProjectionFactoryBase
{
public:
   /*!
    * METHOD: instance()
    * Instantiates singleton instance of this class:
    */
   static ossimMiscProjectionFactory* instance();

   /*!
    * METHOD: create()
    * Attempts to create an instance of the projection specified by name.
    * Returns successfully constructed projection or NULL.
    */
   virtual ossimProjection* createProjection(const ossimFilename& filename,
                                             ossim_uint32 entryIdx)const;
   virtual ossimProjection* createProjection(const ossimString& name)const;
   virtual ossimProjection* createProjection(const ossimKeywordlist& kwl,
                                             const char* prefix = 0)const;

   virtual ossimObject* createObject(const ossimString& typeName)const;

   /*!
    * Creates and object given a keyword list.
    */
   virtual ossimObject* createObject(const ossimKeywordlist& kwl,
                                     const char* prefix=0)const;
   
   /*!
    * This should return the type name of all objects in all factories.
    * This is the name used to construct the objects dynamially and this
    * name must be unique.
    */
   virtual void getTypeNameList(std::vector& typeList)const;

protected:
   ossimMiscProjectionFactory() {}
   static ossimMiscProjectionFactory*  theInstance;
 
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimMollweidProjection.h000066400000000000000000000163261352751253100257110ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
// Calls Geotrans Mollweid projection code.  
//*******************************************************************
//  $Id: ossimMollweidProjection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimMollweidProojection_HEADER
#define ossimMollweidProojection_HEADER

#include 

class OSSIMDLLEXPORT ossimMollweidProjection : public ossimMapProjection
{
public:   
   ossimMollweidProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                           const ossimGpt& origin = ossimGpt());
   ossimMollweidProjection(const ossimEllipsoid& ellipsoid,
                           const ossimGpt& origin,
                           const double falseEasting,
                           const double falseNorthing);
   
   ~ossimMollweidProjection(){}
   
   virtual ossimObject *dup()const{return new ossimMollweidProjection(*this);}

   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();   

   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   void setDefaults();

   void setCentralMeridian(double centralMeridian);

   double getFalseEasting()const{return Moll_False_Easting;}
   double getFalseNorthing()const{return Moll_False_Northing;}

   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
   //! Returns TRUE if principal parameters are within epsilon tolerance.
   virtual bool operator==(const ossimProjection& projection) const;

private:

   //__________________GEOTRANS______________________
   mutable double Moll_a;                /* Semi-major axis of ellipsoid in meters */
   mutable double Moll_f;        /* Flattening of ellipsoid */
   mutable double es2;       /* Eccentricity (0.08181919084262188000) squared         */
   mutable double es4;        /* es2 * es2	*/
   mutable double es6;        /* es4 * es2  */
   mutable double Sqrt2_Ra;        /* sqrt(2.0) * Spherical Radius(6371007.1810824) */
   mutable double Sqrt8_Ra;        /* sqrt(8.0) * Spherical Radius(6371007.1810824) */
   
/* Mollweide projection Parameters */
   mutable double Moll_Origin_Long;            /* Longitude of origin in radians    */
   mutable double Moll_False_Easting;
   mutable double Moll_False_Northing;
   mutable double Moll_Delta_Northing;
   mutable double Moll_Max_Easting;
   mutable double Moll_Min_Easting;

/*!
 * The function Set_Mollweide_Parameters receives the ellipsoid parameters and
 * Mollweide projcetion parameters as inputs, and sets the corresponding state
 * variables.  If any errors occur, the error code(s) are returned by the 
 * function, otherwise MOLL_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid						        (input)
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)
 */
  long Set_Mollweide_Parameters(double a,
                                double f,
                                double Central_Meridian,
                                double False_Easting,
                                double False_Northing);


/*!
 * The function Get_Mollweide_Parameters returns the current ellipsoid
 * parameters and Mollweide projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid						        (output)
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output)
 */
  void Get_Mollweide_Parameters(double *a,
                                double *f,
                                double *Central_Meridian,
                                double *False_Easting,
                                double *False_Northing)const;


/*!
 * The function Convert_Geodetic_To_Mollweide converts geodetic (latitude and
 * longitude) coordinates to Mollweide projection easting, and northing
 * coordinates, according to the current ellipsoid and Mollweide projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise MOLL_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Mollweide (double Latitude,
                                      double Longitude,
                                      double *Easting,
                                      double *Northing)const;


/*!
 * The function Convert_Mollweide_To_Geodetic converts Mollweide projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Mollweide projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise MOLL_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Mollweide_To_Geodetic(double Easting,
                                     double Northing,
                                     double *Latitude,
                                     double *Longitude)const;
   

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimNewZealandMapGridProjection.h000066400000000000000000000111071352751253100274210ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
//*******************************************************************
//  $Id: ossimNewZealandMapGridProjection.h 17815 2010-08-03 13:23:14Z dburken $
#ifndef ossimNewZealandMapGridProjection_HEADER
#define ossimNewZealandMapGridProjection_HEADER

#include 


class OSSIMDLLEXPORT ossimNewZealandMapGridProjection : public ossimMapProjection
{
public:
   ossimNewZealandMapGridProjection();
   ~ossimNewZealandMapGridProjection();
   virtual ossimObject* dup()const
      {
         return new ossimNewZealandMapGridProjection(*this);
      }
   virtual void update();   

   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);
  
   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   void setDefaults();

   double getFalseEasting()const{return  NZMG_False_Easting;}
   double getFalseNorthing()const{return NZMG_False_Northing;}
   
   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
protected:

   // these should be set to constant values that never change.  The origin
   // will be fixed and the false easting northings will also be fixed.
   //
   mutable double NZMG_Origin_Lat;             /* Latitude of origin, in radians */
   mutable double NZMG_Origin_Long;            /* Longitude of origin, in radians */
   mutable double NZMG_False_Northing;         /* False northing, in meters */
   mutable double NZMG_False_Easting;          /* False easting, in meters */
   mutable double NZMG_a;
/* Maximum variance for easting and northing values for International. */
   mutable double NZMG_Max_Easting;
   mutable double NZMG_Max_Northing;
   mutable double NZMG_Min_Easting;
   mutable double NZMG_Min_Northing;

/*!
 * The function Convert_Geodetic_To_NZMG converts geodetic (latitude and
 * longitude) coordinates to New Zealand Map Grid projection (easting and northing)
 * coordinates, according to the current ellipsoid and New Zealand Map Grid 
 * projection parameters.  If any errors occur, the error code(s) are returned 
 * by the function, otherwise NZMG_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi), in radians           (input)
 *    Longitude         : Longitude (lambda), in radians       (input)
 *    Easting           : Easting (X), in meters               (output)
 *    Northing          : Northing (Y), in meters              (output)
 */
   long Convert_Geodetic_To_NZMG (double Latitude,
                                  double Longitude,
                                  double *Easting,
                                  double *Northing)const;



/*!
 * The function Convert_NZMG_To_Geodetic converts New Zealand Map Grid projection
 * (easting and northing) coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and New Zealand Map Grid projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise NZMG_NO_ERROR is returned.
 *
 *    Easting           : Easting (X), in meters                  (input)
 *    Northing          : Northing (Y), in meters                 (input)
 *    Latitude          : Latitude (phi), in radians              (output)
 *    Longitude         : Longitude (lambda), in radians          (output)
 */
   long Convert_NZMG_To_Geodetic(double Easting,
                                 double Northing,
                                 double *Latitude,
                                 double *Longitude)const;
   
TYPE_DATA   
};
#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimNgaProjectionFactory.h000066400000000000000000000037741352751253100261750ustar00rootroot00000000000000//*******************************************************************
// Copyright (C) 2014 RadiantBlue, Inc.
//
// License:  MIT
//
// See LICENSE.txt file in the top level directory for more details.
//
//*******************************************************************
//  $Id$
#ifndef ossimNgaProjectionFactory_HEADER
#define ossimNgaProjectionFactory_HEADER

#include 

class OSSIM_DLL ossimNgaProjectionFactory : public ossimProjectionFactoryBase
{
public:
   
   static ossimNgaProjectionFactory* instance();

   /**
    * takes a filename. This filename can be an image file or
    * it can also be a ossim .geom file.  It could be other
    * forms of geom files as well.  The factories job will be to
    * determine what parser to use and return a projection if
    * successful.
    */
   virtual ossimProjection* createProjection(const ossimFilename& filename,
                                             ossim_uint32 entryIdx)const;

   /**
    * Take a projection type name.
    */
   virtual ossimProjection* createProjection(const ossimString& name)const;

   /**
    * Take a keywordlist.
    */
   virtual ossimProjection* createProjection(const ossimKeywordlist& kwl,
                                             const char* prefix)const;
   
   virtual ossimObject* createObject(const ossimString& typeName)const;

   /*!
    * Creates and object given a keyword list.
    */
   virtual ossimObject* createObject(const ossimKeywordlist& kwl,
                                     const char* prefix=0) const;

   /*!
     * This should return the type name of all objects in all factories.
     * This is the name used to construct the objects dynamially and this
     * name must be unique.
     */
    virtual void getTypeNameList(std::vector& typeList)const;

protected:
    //! Constructor loads all SRS CSV files specified in the ossim prefs. Protected as part of
    //! singleton implementation.
    ossimNgaProjectionFactory() {}

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimNitfMapModel.h000066400000000000000000000041571352751253100244160ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// AUTHOR: Doug Shibla (dshibla@imagelinks.com)
//
// DESCRIPTION:
//
//*****************************************************************************
//  $Id: ossimNitfMapModel.h 9968 2006-11-29 14:01:53Z gpotts $

#ifndef ossimNitfMapModel_HEADER
#define ossimNitfMapModel_HEADER

#include 
#include 
#include 
#include 
#include 

class ossimString;
class ossimMapProjection;

class OSSIMDLLEXPORT ossimNitfMapModel : public ossimSensorModel
{
public:
   /*!
    * CONSTRUCTORS:
    */
   ossimNitfMapModel();
   ossimNitfMapModel(const ossimFilename& init_file);
   ossimNitfMapModel(const ossimKeywordlist& geom_kwl);
   
   virtual ~ossimNitfMapModel();

   /*!
    * Returns pointer to a new instance, copy of this.
    */
   virtual ossimObject* dup() const { return 0; } // TBR
   
   /*!
    * Extends base-class implementation. Dumps contents of object to std::ostream.
    */
   virtual std::ostream& print(std::ostream& out) const;
   
   /*!
    * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry
    * KWL files. Returns true if successful.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;
   
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
   /*!
    * Writes a template of geom keywords processed by loadState and saveState
    * to output stream.
    */
   static void writeGeomTemplate(std::ostream& os);
   
   //***
   // Overrides base class pure virtual.
   //***
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                        const double&   heightEllipsoid,
                                        ossimGpt&       worldPoint) const;
   /*!
    * ossimOptimizableProjection
    */
   inline virtual bool useForward()const {return false;} //!image to ground faster

protected:
   
TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimNitfProjectionFactory.h000066400000000000000000000211141352751253100263540ustar00rootroot00000000000000//---
// License: MIT
//
// Author:  Matt Revelle
//          David Burken
//
// Description:
//
// Contains class declaration for ossimNitfProjectionFactory.
//---
// $Id$

#ifndef ossimNitfProjectionFactory_HEADER
#define ossimNitfProjectionFactory_HEADER 1

#include 
#include 

class ossimProjection;
class ossimString;
class ossimGpt;
class ossimNitfTileSource;
class ossimNitfImageHeader;
class ossimNitfFileHeader;
class ossimNitfFile;
class ossimDpt;

class OSSIMDLLEXPORT ossimNitfProjectionFactory : public ossimProjectionFactoryBase
{
public:

   /**
    * METHOD: instance()
    *
    * @return  Singleton instance of this class.
    */
   static ossimNitfProjectionFactory* instance();

   /**
    * destructor
    */
   virtual ~ossimNitfProjectionFactory();

   /**
    * @param filename This filename can be an image file or
    * it can also be a ossim .geom file.  It could be other
    * forms of geom files as well.  The factories job will be to
    * determine what parser to use and return a projection if
    * successful.
    *
    * @return ossimProjection* on success or NULL if not handled.
    */
   virtual ossimProjection* createProjection(const ossimFilename& filename,
                                             ossim_uint32 entryIdx)const;
   
   /**
    * @param name This would be a projection name.
    *
    * @return ossimProjection* on success or NULL if not handled.
    */
   virtual ossimProjection* createProjection(const ossimString& name)const;

   
   /**
    * @param kwl  Keyword list to instantiate projection from.
    *
    * @return ossimProjection* on success or NULL if not handled.
    */
   virtual ossimProjection* createProjection(const ossimKeywordlist& kwl,
                                             const char* prefix = 0)const;
   
   virtual ossimProjection* createProjection(ossimImageHandler* handler)const;
   /**
    * Creates an object given a type name.
    *
    * @return ossimObject on success or NULL if not handled.
    */
   virtual ossimObject* createObject(const ossimString& typeName)const;

   /**
    * Creates and object given a keyword list.
    *
    * @return ossimObject on success or NULL if not handled.
    */
   virtual ossimObject* createObject(const ossimKeywordlist& kwl,
                                     const char* prefix=0)const;
   
   /**
    * This should return the type name of all objects in all factories.
    * This is the name used to construct the objects dynamially and this
    * name must be unique.
    *
    * @param typeList List to append names to.
    */
   virtual void getTypeNameList(std::vector& typeList)const;

private:
   
   ossimProjection* createProjectionFromHeaders(ossimNitfFile* nitfFile,
      ossimNitfFileHeader* fileHeader,
      ossimNitfImageHeader* imageHeader)const;
   
   
   /**
    * @param hdr The nitf image header.
    *
    * @param coordianteSystem The coordinate system as a string.
    *
    * @param geographicLocation This should contain the four corner strings.
    *
    * @return Either an  ossimEquDistCylProjection or ossimBilinearProjection
    * depending upon if the corner points line up evenly.
    */
   ossimProjection* makeGeographic(const ossimNitfImageHeader* hdr,
                                   const ossimString& coordinateSysetm)const;//,
                                   //const ossimFilename& filename) const;

   /**
    * @param hdr The nitf image header.
    *
    * @param coordianteSystem The coordinate system as a string.
    *
    * @param geographicLocation This should contain the four corner strings.
    *
    * @return ossimUtmProjection
    */
   ossimProjection* makeUtm(const ossimNitfImageHeader* hdr,
                            const ossimString& coordinateSysetm)const;//,
   
   /**
    * @param hdr The nitf image header.
    *
    * @param gpts Four geographic corner points.
    * 
    * @return ossimEquDistCylProjection* or null if a problem is found.
    */
   ossimProjection* makeEuiDistant(const ossimNitfImageHeader* hdr,
                                   const std::vector& gpts) const;
   
   /**
    * @return ossimBilinearProjection* or null if a problem is found.
    */
   ossimProjection* makeBilinear(const ossimNitfImageHeader* hdr,
                                 const std::vector& gpts) const;

   /**
    * Parses geographic stream.  This will initialize the vector of ossimGpt's
    * with the four corners.  If the string geographicLocation is not the
    * correct size the vector will be cleared.
    *
    * @param geographicLocation String containing corners.
    *
    * @param gpts Vector to initialize.
    */
   void parseGeographicString(const ossimString& geographicLocation,
                              std::vector& gpts) const;

   /**
    * Parses Decimal degree stream.  This will initialize the vector of ossimGpt's
    * with the four corners.  If the string geographicLocation is not the
    * correct size the vector will be cleared.
    *
    * @param geographicLocation String containing corners.
    *
    * @param gpts Vector to initialize.
    */
   void parseDecimalDegreesString(const ossimString& geographicLocation,
                                  std::vector& gpts) const;

   void parseUtmString(const ossimString& utmLocation,
                       ossim_uint32& zone,
                       std::vector& utmPoints)const;

   /**
    * @brief Gets UTM points, zone and hemisphere from IGEOLO field when ICORDS files = U which is
    * UTM expressed in MGRS.
    * @param mgrsLocationString String from IGEOLO field.
    * @param zone Initialized in method.
    * @param hemisphere Initialized in method.
    * @param utmPoints Initialized in method.
    * @return True on success, false on error.
    */
   bool parseMgrsString(const ossimString& mgrsLocationString,
                        ossim_uint32& zone,
                        char& hemisphere,
                        std::vector& utmPoints) const;
   
   /**
    * Computes the scale in decimal degrees with scale.x being longitude,
    * y being latitude.
    *
    * @param hdr The nitf image header from the currently opened nitf file.
    *
    * @param gpts Four geographic corner points.
    *
    * @param scale Scale to initialize.
    *
    * @note scale will be set to nan's on failure.
    */
   void computeScaleInDecimalDegrees(const ossimNitfImageHeader* hdr,
                                     const std::vector& gpts,
                                     ossimDpt& scale) const;

   /**
    * Computes the scale in meters with scale.x being easting,
    * y being northing.
    *
    * @param hdr The nitf image header from the currently opened nitf file.
    *
    * @param dpts Four utm corner points.
    *
    * @param scale Scale to initialize.
    *
    * @note scale will be set to nan's on failure.
    */
   void computeScaleInMeters(const ossimNitfImageHeader* hdr,
                             const std::vector& dpts,
                             ossimDpt& scale) const;
      
   /**
    * @return true if corner points are parallel to each other, else false.
    */
   bool isSkewed(const std::vector& gpts) const;

   /**
    * @return true if corner points are parallel to each other, else false.
    */
   bool isSkewed(const std::vector& gpts) const;

   /**
    * @param hdr The nitf image header from the currently opened nitf file.
    * 
    * @param gpts Ground points to initialize from BLOCKA tag.  This should
    * be an empty vector.
    *
    * @return true if BLOCKA tag was parsed.
    */
   bool getBlockaPoints(const ossimNitfImageHeader* hdr,
                        std::vector& gpts)const;

   /**
    * @param hdr The nitf image header from the currently opened nitf file.
    * 
    * @param gpts Ground points to initialize from GEOLOB tag. This should
    * be an empty vector.
    *
    * @return true if GEOLOB tag was parsed.
    */
   bool getGeolobPoints(const ossimNitfImageHeader* hdr,
                        std::vector& gpts)const;

   /**
    * Private constructor, users must go through instance() method.
    */
   ossimNitfProjectionFactory();

   /**
    * Private copy constructor to hide from use.
    */
   ossimNitfProjectionFactory(const ossimNitfProjectionFactory& obj);

   /**
    * Private operator = to hide from use.
    */
   ossimNitfProjectionFactory& operator=(const ossimNitfProjectionFactory& rhs);
   
   static ossimNitfProjectionFactory*  theInstance;

   bool isNitf(const ossimFilename& filename)const;
};

#endif /* End of "#ifndef ossimNitfProjectionFactory_HEADER" */
ossim-Miami-2.9.1/include/ossim/projection/ossimNitfRpcModel.h000066400000000000000000000070421352751253100244210ustar00rootroot00000000000000//*****************************************************************************
// FILE: ossimNitfRpcModel.h
//
// License:  MIT
// 
// See LICENSE.txt file in the top level directory for more details.
//
// AUTHOR: Oscar Kramer
//
// DESCRIPTION: Contains declaration of class ossimNitfRpcModel. This 
//    derived class implements the capability of reading Nitf RPC support
//    data.
//
// LIMITATIONS: None.
//
//*****************************************************************************
//  $Id: ossimNitfRpcModel.h 15766 2009-10-20 12:37:09Z gpotts $

#ifndef ossimNitfRpcModel_HEADER
#define ossimNitfRpcModel_HEADER

#include 
#include 

class ossimFilename;
class ossimNitfImageHeader;

/*!****************************************************************************
 *
 * CLASS:  ossimNitfRpcModel
 *
 *****************************************************************************/
class OSSIM_DLL ossimNitfRpcModel : public ossimRpcModel
{
public:
   ossimNitfRpcModel();
   ossimNitfRpcModel(const ossimNitfRpcModel& rhs);
   ossimNitfRpcModel(const ossimFilename& nitfFile);
   virtual ossimObject* dup() const;

   /**
    * @brief worldToLineSample()
    * Calls ossimRpcModel::worldToLineSample(), then applies (if needed)
    * decimation.
    * This is a temp work around for decimation RPC NITFs.
    */
   virtual void  worldToLineSample(const ossimGpt& world_point,
                                   ossimDpt&       image_point) const;

   /**
    * @brief lineSampleHeightToWorld()
    * Backs out decimation of image_point (if needed) then calls:
    * ossimRpcModel::lineSampleHeightToWorld
    * This is a temp work around for decimation RPC NITFs.
    */
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                        const double&   heightEllipsoid,
                                        ossimGpt&       worldPoint) const;

   /**
    * @brief Saves "decimation".  Then calls ossimRpcModel::saveState.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;

   /**
    * @brief Looks for decimation. Then calls ossimRpcModel::loadState.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   /**
    * @brief Method to parse an nitf file and initialize model.
    * @param entryIndex The entry to get model for.  Note the nitf's can have
    * multiple entries; each with a different projection.
    * @return true on success, false on error.
    */
   virtual bool parseFile(const ossimFilename& nitfFile,
                          ossim_uint32 entryIndex=0);
   
   virtual bool parseImageHeader(const ossimNitfImageHeader* ih);
private:

   /**
    * Attempts to get gsd from nitf tags and initialize
    * ossimSensorModel::theGsd.
    * 
    * If unsuccessful  theGsd will be initialized to OSSIM_DBL_NAN.
    */
   void getGsd(const ossimNitfImageHeader* ih);

   /**
    * Attempts to get sensor ID from nitf tags and initialize
    * ossimSensorModel::theSensorID.
    * 
    * If unsuccessful  theGsd will be initialized to UNKNOWN.
    */
   void getSensorID(const ossimNitfImageHeader* ih);

   /**
    * Get model information from either the RPC00A or RPC00B tag.
    * @return true on success, false on error.
    */
   bool getRpcData(const ossimNitfImageHeader* ih);

   /**
    * Stored from header field "IMAG".  This is a temp work around to handle
    * decimated rpc nitf's.
    */
   ossim_float64 theDecimation;

   TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimNitfRsmModel.h000066400000000000000000000035201352751253100244330ustar00rootroot00000000000000//---
// File: ossimNitfRsmModel.h
//---
#ifndef ossimNitfRsmModel_HEADER
#define ossimNitfRsmModel_HEADER 1

#include 

class ossimNitfImageHeader;
class ossimNitfRsmecaTag;
class ossimNitfRsmidaTag;
class ossimNitfRsmpcaTag;
class ossimNitfRsmpiaTag;

/**
 * @class ossimNitfRsmModel
 */
class OSSIM_DLL ossimNitfRsmModel : public ossimRsmModel
{
public:

   /** @brief default constructor */
   ossimNitfRsmModel();

   /** @brief copy constructor */
   ossimNitfRsmModel( const ossimNitfRsmModel& obj );

   /** @brief assignment operator */
   const ossimNitfRsmModel& operator=( const ossimNitfRsmModel& rhs );

   virtual bool parseFile(const ossimFilename& nitfFile,
                          ossim_uint32 entryIndex=0);

   virtual bool parseImageHeader(const ossimNitfImageHeader* ih);

   bool getRsmData(const ossimNitfImageHeader* ih);

   /**
    * @brief saveState
    * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry
    * KWL files. Returns true if successful.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;
   
   /**
    * @brief loadState
    * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry
    * KWL files. Returns true if successful.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   /**
    * @brief dup()
    * Returns pointer to a new instance, copy of this.
    */
   virtual ossimObject* dup() const;

   /**
    * @brief Initializes model from RSMECA tag.
    * @param rsmecaTag
    */
   bool initializeModel( const ossimNitfRsmecaTag* rsmecaTag );

protected:
   /** @brief virtual destructor */
   virtual ~ossimNitfRsmModel();

   TYPE_DATA
      
}; // End: class ossimRsmModel

#endif /* #ifndef ossimNitfRsmModel_HEADER */
ossim-Miami-2.9.1/include/ossim/projection/ossimObliqueMercatorProjection.h000066400000000000000000000265201352751253100272270ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
//*******************************************************************
//  $Id: ossimObliqueMercatorProjection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimObliqueMercatorProjection_HEADER
#define ossimObliqueMercatorProjection_HEADER

#include 

class OSSIMDLLEXPORT ossimObliqueMercatorProjection : public ossimMapProjection
{
public:   
   ossimObliqueMercatorProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                                  const ossimGpt& origin = ossimGpt());

   /*!
    * Points 1 and 2 lie along the central line.
    */
   ossimObliqueMercatorProjection(const ossimEllipsoid& ellipsoid,
                                  const ossimGpt& origin,
                                  const ossimGpt& point1,
                                  const ossimGpt& point2,
                                  double falseEasting,
                                  double falseNorthing,
                                  double scaleFactor);
   
   ~ossimObliqueMercatorProjection(){}
   virtual ossimObject *dup()const
      {
         return new ossimObliqueMercatorProjection(*this);
      }
   
   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();

   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);
   
   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);
   
   void setCentralPoint1(const ossimGpt& point);
   void setCentralPoint2(const ossimGpt& point);
   void setScaleFactor(double scaleFactor);
   
   void setParameters(const ossimGpt& point1,
                      const ossimGpt& point2,
                      double falseEasting,
                      double falseNorthing,
                      double scaleFactor);
   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);
   
   void setDefaults();
   
   double getFalseEasting()const{return  OMerc_False_Easting;}
   double getFalseNorthing()const{return OMerc_False_Northing;}
   const ossimGpt& getCentralPoint1()const{return theCentralPoint1;}
   const ossimGpt& getCentralPoint2()const{return theCentralPoint2;}
   double getScaleFactor()const{return OMerc_Scale_Factor;}
   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   //! Returns TRUE if principal parameters are within epsilon tolerance.
   virtual bool operator==(const ossimProjection& projection) const;

protected:

   ossimGpt theCentralPoint1;
   ossimGpt theCentralPoint2;

//________________________GEOTRANS STUFF_____________________________________
   
   mutable double OMerc_a;                   /* Semi-major axis of ellipsoid, in meters */
   mutable double OMerc_f;           /* Flattening of ellipsoid */
   mutable double es;
   mutable double es_OVER_2;
   mutable double OMerc_A;
   mutable double OMerc_B;
   mutable double OMerc_E;
   mutable double OMerc_gamma;
   mutable double OMerc_azimuth;       /* Azimuth of central line as it crosses origin lat */
   mutable double OMerc_Origin_Long;  /* Longitude at center of projection */
   mutable double cos_gamma;
   mutable double sin_gamma;
   mutable double sin_azimuth;  
   mutable double cos_azimuth;
   mutable double A_over_B;
   mutable double B_over_A;
   mutable double OMerc_u;             /* Coordinates for center point (uc , vc), vc = 0 */
                                                 /* at center lat and lon */
/* Oblique Mercator projection Parameters */
   mutable double OMerc_Origin_Lat;/* Latitude of projection center, in radians */
   mutable double OMerc_Lat_1;     /* Latitude of first point lying on central line */
   mutable double OMerc_Lon_1;     /* Longitude of first point lying on central line */
   mutable double OMerc_Lat_2;     /* Latitude of second point lying on central line */
   mutable double OMerc_Lon_2;      /* Longitude of second point lying on central line */
   mutable double OMerc_Scale_Factor;                /* Scale factor at projection center */
   mutable double OMerc_False_Northing;              /* False northing, in meters, at projection center */
   mutable double OMerc_False_Easting;               /* False easting, in meters, at projection center */
   
   mutable double OMerc_Delta_Northing;
   mutable double OMerc_Delta_Easting;
   
/*!
 * The function Set_Oblique_Mercator_Parameters receives the ellipsoid parameters and
 * projection parameters as inputs, and sets the corresponding state
 * variables.  If any errors occur, the error code(s) are returned by the function, 
 * otherwise OMERC_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid                   (input)
 *    Origin_Latitude   : Latitude, in radians, at which the        (input)
 *                          point scale factor is 1.0
 *    Latitude_1        : Latitude, in radians, of first point lying on
 *                           central line                           (input)
 *    Longitude_1       : Longitude, in radians, of first point lying on
 *                           central line                           (input)
 *    Latitude_2        : Latitude, in radians, of second point lying on
 *                           central line                           (input)
 *    Longitude_2       : Longitude, in radians, of second point lying on
 *                           central line                           (input)
 *    False_Easting     : A coordinate value, in meters, assigned to the
 *                          central meridian of the projection      (input)
 *    False_Northing    : A coordinate value, in meters, assigned to the
 *                          origin latitude of the projection       (input)
 *    Scale_Factor      : Multiplier which reduces distances in the
 *                          projection to the actual distance on the
 *                          ellipsoid                               (input)
 */
  long Set_Oblique_Mercator_Parameters(double a,
                                       double f,
                                       double Origin_Latitude,
                                       double Latitude_1,
                                       double Longitude_1,
                                       double Latitude_2,
                                       double Longitude_2,
                                       double False_Easting,
                                       double False_Northing,
                                       double Scale_Factor);


/*!
 * The function Get_Oblique_Mercator_Parameters returns the current ellipsoid
 * parameters and Oblique Mercator projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters  (output)
 *    f                 : Flattening of ellipsoid                  (output)
 *    Origin_Latitude   : Latitude, in radians, at which the       (output)
 *                          point scale factor is 1.0
 *    Latitude_1        : Latitude, in radians, of first point lying on
 *                          central line                           (output)
 *    Longitude_1       : Longitude, in radians, of first point lying on
 *                          central line                           (output)
 *    Latitude_2        : Latitude, in radians, of second point lying on
 *                          central line                           (output)
 *    Longitude_2       : Longitude, in radians, of second point lying on
 *                          central line                           (output)
 *    False_Easting     : A coordinate value, in meters, assigned to the
 *                          central meridian of the projection     (output)
 *    False_Northing    : A coordinate value, in meters, assigned to the
 *                          origin latitude of the projection      (output)
 *    Scale_Factor      : Multiplier which reduces distances in the
 *                          projection to the actual distance on the
 *                          ellipsoid                              (output)
 */
  void Get_Oblique_Mercator_Parameters(double *a,
                                       double *f,
                                       double *Origin_Latitude,
                                       double *Latitude_1,
                                       double *Longitude_1,
                                       double *Latitude_2,
                                       double *Longitude_2,
                                       double *False_Easting,
                                       double *False_Northing,
                                       double *Scale_Factor)const;


/*!
 * The function Convert_Geodetic_To_Oblique_Mercator converts geodetic (latitude and
 * longitude) coordinates to Oblique Mercator projection (easting and
 * northing) coordinates, according to the current ellipsoid and Oblique Mercator 
 * projection parameters.  If any errors occur, the error code(s) are returned 
 * by the function, otherwise OMERC_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi), in radians           (input)
 *    Longitude         : Longitude (lambda), in radians       (input)
 *    Easting           : Easting (X), in meters               (output)
 *    Northing          : Northing (Y), in meters              (output)
 */
  long Convert_Geodetic_To_Oblique_Mercator(double Latitude,
                                            double Longitude,
                                            double *Easting,
                                            double *Northing)const;


/*!
 * The function Convert_Oblique_Mercator_To_Geodetic converts Oblique Mercator projection
 * (easting and northing) coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Oblique Mercator projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise OMERC_NO_ERROR is returned.
 *
 *    Easting           : Easting (X), in meters                  (input)
 *    Northing          : Northing (Y), in meters                 (input)
 *    Latitude          : Latitude (phi), in radians              (output)
 *    Longitude         : Longitude (lambda), in radians          (output)
 */
  long Convert_Oblique_Mercator_To_Geodetic(double Easting,
                                            double Northing,
                                            double *Latitude,
                                            double *Longitude)const;
   
TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimOptimizableProjection.h000066400000000000000000000051641352751253100264120ustar00rootroot00000000000000//*****************************************************************************
// FILE: ossimOptimizableProjection.h
//*****************************************************************************
// $Id: ossimOptimizableProjection.h 11302 2007-07-16 19:37:26Z dburken $
//TODO : forwardRelativeAccuracy should return covariance matrix, and 
//         use an optional ground position as input

#ifndef ossimOptimizableProjection_HEADER
#define ossimOptimizableProjection_HEADER

#include 

//fwd class declaration
class ossimTieGptSet;

/**
 * virtual class enabling projection optimization
 * (can be used for outlier rejection - RANSAC)
 */
class OSSIMDLLEXPORT ossimOptimizableProjection
{
public:
   /*!
    * Construction and init
    */
   ossimOptimizableProjection();
   
   ossimOptimizableProjection(const ossimOptimizableProjection& source);
   
   virtual ~ossimOptimizableProjection();
   
   virtual ossimOptimizableProjection& operator=(
      const ossimOptimizableProjection& source);
   
   /*!
    * @brief setupFromString()  Derived classes should implement as needed.
    * Initialize parameters needed for optimizeFit and degreesOfFreedom
    * 
    * @return This implementation does nothing and returns false.
    */
   virtual bool setupOptimizer(const ossimString& setup);

   /*!
    * useForward()
    * return true when it's better (more accurate / fast) to use forward
    * (from ground to image) than inverse(from image to ground)
    */
   virtual bool useForward()const=0;

   /*!
    * degreesOfFreedom()
    * number of degrees of freedom (eg: 8 for bilinear, 6 for affine,
    * 2 for translation)
    * especially useful when not inheriting from AdjustableParameterInterface
    */
   virtual ossim_uint32 degreesOfFreedom()const=0;

   /*!
    * @brief needsInitialState()
    * 
    * @return This implementation returns false.  Sub classes should true if
    * the projection needs to be initialized to be optimized,
    * eg: sensor models.  
    */
   virtual bool needsInitialState()const;

   /*!
    * optimizeFit()
    * adjusts projection to GLOBALLY fit best to ALL tie points
    * (no outlier rejection)
    * can select an optional threshold for accuracy
    *
    * RETURNS : resulting image error variance of fitted model, or negative
    * value for error
    *
    * IMPORTANT : the unit for *targetVariance and the returned value is :
    *    meters^2 when useForward() is true
    *   OR
    *    pixel^2  if useForward() is false
    */
   virtual double optimizeFit(const ossimTieGptSet& tieSet,
                              double* targetVariance=0)=0;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimOrthoGraphicProjection.h000066400000000000000000000173311352751253100265230ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
// Calls Geotrans OrthoGraphic  projection code.  
//*******************************************************************
//  $Id: ossimOrthoGraphicProjection.h 9968 2006-11-29 14:01:53Z gpotts $

#ifndef ossimOrthoGraphicProjection_HEADER
#define ossimOrthoGraphicProjection_HEADER

#include 

class ossimOrthoGraphicProjection : public ossimMapProjection
{
public:
   
   ossimOrthoGraphicProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                               const ossimGpt& origin = ossimGpt());
   ossimOrthoGraphicProjection(const ossimEllipsoid& ellipsoid,
                               const ossimGpt& origin,
                               const double falseEasting,
                               const double falseNorthing);
   ~ossimOrthoGraphicProjection(){}
   
   virtual ossimObject *dup()const
      {
         return new ossimOrthoGraphicProjection(*this);
      }
   virtual void getGroundClipPoints(ossimGeoPolygon& gpts)const;
   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();
   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   void setDefaults();

   double getFalseEasting()const{return  Orth_False_Easting;}
   double getFalseNorthing()const{return Orth_False_Northing;}

   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
private:
   
   //___________________GEOTRANS_______________________
   mutable double Orth_a;                      /* Semi-major axis of ellipsoid in meters */
   mutable double Orth_f;              /* Flattening of ellipsoid */
   mutable double es2;             /* Eccentricity (0.08181919084262188000) squared         */
   mutable double es4;              /* es2 * es2 */
   mutable double es6;              /* es4 * es2 */
   mutable double Ra;                    /* Spherical Radius */
   
/* Orthographic projection Parameters */
   mutable double Orth_Origin_Lat;                   /* Latitude of origin in radians     */
   mutable double Orth_Origin_Long;                  /* Longitude of origin in radians    */
   mutable double Orth_False_Easting;
   mutable double Orth_False_Northing;
   mutable double Sin_Orth_Origin_Lat;               /* sin(Orth_Origin_Lat) */
   mutable double Cos_Orth_Origin_Lat;               /* cos(Orth_Origin_Lat) */
   
/*!
 * The function Set_Orthographic_Parameters receives the ellipsoid parameters and
 * Orthographic projcetion parameters as inputs, and sets the corresponding state
 * variables.  If any errors occur, the error code(s) are returned by the function, 
 * otherwise ORTH_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid                   (input)
 *    Origin_Latitude   : Latitude in radians at which the          (input)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)                          
 */
  long Set_Orthographic_Parameters(double a,
                                   double f,
                                   double Origin_Latitude,
                                   double Central_Meridian,
                                   double False_Easting,
                                   double False_Northing);



/*!
 * The function Get_Orthographic_Parameters returns the current ellipsoid
 * parameters and Orthographic projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid                   (output)
 *    Origin_Latitude   : Latitude in radians at which the          (output)
 *                          point scale factor is 1.0
 *    Origin_Longitude  : Longitude in radians at the center of     (output)
 *                          the projection (central meridian)
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output) 
 */
  void Get_Orthographic_Parameters(double *a,
                                   double *f,
                                   double *Origin_Latitude,
                                   double *Origin_Longitude,
                                   double *False_Easting,
                                   double *False_Northing)const;



/*!
 * The function Convert_Geodetic_To_Orthographic converts geodetic (latitude and
 * longitude) coordinates to Orthographic projection easting, and northing
 * coordinates, according to the current ellipsoid and Orthographic projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise ORTH_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Orthographic (double Latitude,
                                         double Longitude,
                                         double *Easting,
                                         double *Northing)const;


/*!
 * The function Convert_Orthographic_To_Geodetic converts Orthographic projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Orthographic projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise ORTH_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Orthographic_To_Geodetic(double Easting,
                                        double Northing,
                                        double *Latitude,
                                        double *Longitude)const;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimPolarStereoProjection.h000066400000000000000000000170341352751253100263710ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
// Calls Geotrans Polar Stereographic  projection code.  
//*******************************************************************
//  $Id: ossimPolarStereoProjection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimPolarStereoProjection_HEADER
#define ossimPolarStereoProjection_HEADER

#include 

class OSSIMDLLEXPORT ossimPolarStereoProjection : public ossimMapProjection
{
public:
   ossimPolarStereoProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                              const ossimGpt& origin = ossimGpt());
   ossimPolarStereoProjection(const ossimEllipsoid& ellipsoid,
                              const ossimGpt& origin,
                              const double falseEasting,
                              const double falseNorthing);
   ~ossimPolarStereoProjection(){}
   
   virtual ossimObject *dup()const{return new ossimPolarStereoProjection(*this);}
   
   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();
   
   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   void setDefaults();

   double getFalseEasting()const{return  Polar_False_Easting;}
   double getFalseNorthing()const{return Polar_False_Northing;}

   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
private:

   mutable double Polar_a;                    /* Semi-major axis of ellipsoid in meters  */
   mutable double Polar_f;            /* Flattening of ellipsoid  */
   mutable double es;            /* Eccentricity of ellipsoid    */
   mutable double es_OVER_2;           /* es / 2.0 */
   mutable double Southern_Hemisphere;                /* Flag variable */
   mutable double mc;                    
   mutable double tc;
   mutable double e4;
   mutable double Polar_a_mc;                 /* Polar_a * mc */
   mutable double two_Polar_a;               /* 2.0 * Polar_a */
   
/* Polar Stereographic projection Parameters */
   mutable double Polar_Origin_Lat;   /* Latitude of origin in radians */
   mutable double Polar_Origin_Long;                /* Longitude of origin in radians */
   mutable double Polar_False_Easting;              /* False easting in meters */
   mutable double Polar_False_Northing;             /* False northing in meters */
   
/* Maximum variance for easting and northing values for WGS 84. */
   mutable double Polar_Delta_Easting;
   mutable double Polar_Delta_Northing;
   
/*!
 *  The function Set_Polar_Stereographic_Parameters receives the ellipsoid
 *  parameters and Polar Stereograpic projection parameters as inputs, and
 *  sets the corresponding state variables.  If any errors occur, error
 *  code(s) are returned by the function, otherwise POLAR_NO_ERROR is returned.
 *
 *  a                : Semi-major axis of ellipsoid, in meters         (input)
 *  f                : Flattening of ellipsoid                         (input)
 *  Latitude_of_True_Scale  : Latitude of true scale, in radians       (input)
 *  Longitude_Down_from_Pole : Longitude down from pole, in radians    (input)
 *  False_Easting    : Easting (X) at center of projection, in meters  (input)
 *  False_Northing   : Northing (Y) at center of projection, in meters (input)
 */
  long Set_Polar_Stereographic_Parameters (double a,
                                           double f,
                                           double Latitude_of_True_Scale,
                                           double Longitude_Down_from_Pole,
                                           double False_Easting,
                                           double False_Northing);


/*!
 * The function Get_Polar_Stereographic_Parameters returns the current
 * ellipsoid parameters and Polar projection parameters.
 *
 *  a                : Semi-major axis of ellipsoid, in meters         (output)
 *  f                : Flattening of ellipsoid                         (output)
 *  Latitude_of_True_Scale  : Latitude of true scale, in radians       (output)
 *  Longitude_Down_from_Pole : Longitude down from pole, in radians    (output)
 *  False_Easting    : Easting (X) at center of projection, in meters  (output)
 *  False_Northing   : Northing (Y) at center of projection, in meters (output)
 */
  void Get_Polar_Stereographic_Parameters (double *a,
                                           double *f,
                                           double *Latitude_of_True_Scale,
                                           double *Longitude_Down_from_Pole,
                                           double *False_Easting,
                                           double *False_Northing)const;


/*!
 * The function Convert_Geodetic_To_Polar_Stereographic converts geodetic
 * coordinates (latitude and longitude) to Polar Stereographic coordinates
 * (easting and northing), according to the current ellipsoid
 * and Polar Stereographic projection parameters. If any errors occur, error
 * code(s) are returned by the function, otherwise POLAR_NO_ERROR is returned.
 *
 *    Latitude   :  Latitude, in radians                      (input)
 *    Longitude  :  Longitude, in radians                     (input)
 *    Easting    :  Easting (X), in meters                    (output)
 *    Northing   :  Northing (Y), in meters                   (output)
 */
  long Convert_Geodetic_To_Polar_Stereographic (double Latitude,
                                                double Longitude,
                                                double *Easting,
                                                double *Northing)const;



/*!
 *  The function Convert_Polar_Stereographic_To_Geodetic converts Polar
 *  Stereographic coordinates (easting and northing) to geodetic
 *  coordinates (latitude and longitude) according to the current ellipsoid
 *  and Polar Stereographic projection Parameters. If any errors occur, the
 *  code(s) are returned by the function, otherwise POLAR_NO_ERROR
 *  is returned.
 *
 *  Easting          : Easting (X), in meters                   (input)
 *  Northing         : Northing (Y), in meters                  (input)
 *  Latitude         : Latitude, in radians                     (output)
 *  Longitude        : Longitude, in radians                    (output)
 *
 */
  long Convert_Polar_Stereographic_To_Geodetic (double Easting,
                                                double Northing,
                                                double *Latitude,
                                                double *Longitude)const;


TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimPolarst.h000066400000000000000000000176201352751253100235220ustar00rootroot00000000000000#ifndef POLARST_H
  #define POLARST_H
/***************************************************************************/
/* RSC IDENTIFIER: POLAR STEREOGRAPHIC 
 *
 *
 * ABSTRACT
 *
 *    This component provides conversions between geodetic (latitude and
 *    longitude) coordinates and Polar Stereographic (easting and northing) 
 *    coordinates.
 *
 * ERROR HANDLING
 *
 *    This component checks parameters for valid values.  If an invalid 
 *    value is found the error code is combined with the current error code 
 *    using the bitwise or.  This combining allows multiple error codes to 
 *    be returned. The possible error codes are:
 *
 *          POLAR_NO_ERROR           : No errors occurred in function
 *          POLAR_LAT_ERROR          : Latitude outside of valid range
 *                                      (-90 to 90 degrees)
 *          POLAR_LON_ERROR          : Longitude outside of valid range
 *                                      (-180 to 360 degrees) 
 *          POLAR_ORIGIN_LAT_ERROR   : Latitude of true scale outside of valid
 *                                      range (-90 to 90 degrees)
 *          POLAR_ORIGIN_LON_ERROR   : Longitude down from pole outside of valid
 *                                      range (-180 to 360 degrees)
 *          POLAR_EASTING_ERROR      : Easting outside of valid range,
 *                                      depending on ellipsoid and
 *                                      projection parameters
 *          POLAR_NORTHING_ERROR     : Northing outside of valid range,
 *                                      depending on ellipsoid and
 *                                      projection parameters
 *          POLAR_RADIUS_ERROR       : Coordinates too far from pole,
 *                                      depending on ellipsoid and
 *                                      projection parameters
 *          POLAR_A_ERROR            : Semi-major axis less than or equal to zero
 *          POLAR_INV_F_ERROR        : Inverse flattening outside of valid range
 *								  	                  (250 to 350)
 *
 *
 * REUSE NOTES
 *
 *    POLAR STEREOGRAPHIC is intended for reuse by any application that  
 *    performs a Polar Stereographic projection.
 *
 *
 * REFERENCES
 *
 *    Further information on POLAR STEREOGRAPHIC can be found in the
 *    Reuse Manual.
 *
 *
 *    POLAR STEREOGRAPHIC originated from :
 *                                U.S. Army Topographic Engineering Center
 *                                Geospatial Information Division
 *                                7701 Telegraph Road
 *                                Alexandria, VA  22310-3864
 *
 *
 * LICENSES
 *
 *    None apply to this component.
 *
 *
 * RESTRICTIONS
 *
 *    POLAR STEREOGRAPHIC has no restrictions.
 *
 *
 * ENVIRONMENT
 *
 *    POLAR STEREOGRAPHIC was tested and certified in the following
 *    environments:
 *
 *    1. Solaris 2.5 with GCC, version 2.8.1
 *    2. Window 95 with MS Visual C++, version 6
 *
 *
 * MODIFICATIONS
 *
 *    Date              Description
 *    ----              -----------
 *    06-11-95          Original Code
 *    03-01-97          Original Code
 *
 *
 */


/**********************************************************************/
/*
 *                        DEFINES
 */

  #define POLAR_NO_ERROR                0x0000
  #define POLAR_LAT_ERROR               0x0001
  #define POLAR_LON_ERROR               0x0002
  #define POLAR_ORIGIN_LAT_ERROR        0x0004
  #define POLAR_ORIGIN_LON_ERROR        0x0008
  #define POLAR_EASTING_ERROR			  0x0010
  #define POLAR_NORTHING_ERROR		  0x0020
  #define POLAR_A_ERROR                 0x0040
  #define POLAR_INV_F_ERROR             0x0080
  #define POLAR_RADIUS_ERROR            0x0100

/**********************************************************************/
/*
 *                        FUNCTION PROTOTYPES
 */

/* ensure proper linkage to c++ programs */
  #ifdef __cplusplus
extern "C" {
  #endif

  long Set_Polar_Stereographic_Parameters (double a,
                                           double f,
                                           double Latitude_of_True_Scale,
                                           double Longitude_Down_from_Pole,
                                           double False_Easting,
                                           double False_Northing);
/*  
 *  The function Set_Polar_Stereographic_Parameters receives the ellipsoid
 *  parameters and Polar Stereograpic projection parameters as inputs, and
 *  sets the corresponding state variables.  If any errors occur, error
 *  code(s) are returned by the function, otherwise POLAR_NO_ERROR is returned.
 *
 *  a                : Semi-major axis of ellipsoid, in meters         (input)
 *  f                : Flattening of ellipsoid                         (input)
 *  Latitude_of_True_Scale  : Latitude of true scale, in radians       (input)
 *  Longitude_Down_from_Pole : Longitude down from pole, in radians    (input)
 *  False_Easting    : Easting (X) at center of projection, in meters  (input)
 *  False_Northing   : Northing (Y) at center of projection, in meters (input)
 */


  void Get_Polar_Stereographic_Parameters (double *a,
                                           double *f,
                                           double *Latitude_of_True_Scale,
                                           double *Longitude_Down_from_Pole,
                                           double *False_Easting,
                                           double *False_Northing);
/*
 * The function Get_Polar_Stereographic_Parameters returns the current
 * ellipsoid parameters and Polar projection parameters.
 *
 *  a                : Semi-major axis of ellipsoid, in meters         (output)
 *  f                : Flattening of ellipsoid                         (output)
 *  Latitude_of_True_Scale  : Latitude of true scale, in radians       (output)
 *  Longitude_Down_from_Pole : Longitude down from pole, in radians    (output)
 *  False_Easting    : Easting (X) at center of projection, in meters  (output)
 *  False_Northing   : Northing (Y) at center of projection, in meters (output)
 */


  long Convert_Geodetic_To_Polar_Stereographic (double Latitude,
                                                double Longitude,
                                                double *Easting,
                                                double *Northing);
/*
 * The function Convert_Geodetic_To_Polar_Stereographic converts geodetic
 * coordinates (latitude and longitude) to Polar Stereographic coordinates
 * (easting and northing), according to the current ellipsoid
 * and Polar Stereographic projection parameters. If any errors occur, error
 * code(s) are returned by the function, otherwise POLAR_NO_ERROR is returned.
 *
 *    Latitude   :  Latitude, in radians                      (input)
 *    Longitude  :  Longitude, in radians                     (input)
 *    Easting    :  Easting (X), in meters                    (output)
 *    Northing   :  Northing (Y), in meters                   (output)
 */



  long Convert_Polar_Stereographic_To_Geodetic (double Easting,
                                                double Northing,
                                                double *Latitude,
                                                double *Longitude);

/*
 *  The function Convert_Polar_Stereographic_To_Geodetic converts Polar
 *  Stereographic coordinates (easting and northing) to geodetic
 *  coordinates (latitude and longitude) according to the current ellipsoid
 *  and Polar Stereographic projection Parameters. If any errors occur, the
 *  code(s) are returned by the function, otherwise POLAR_NO_ERROR
 *  is returned.
 *
 *  Easting          : Easting (X), in meters                   (input)
 *  Northing         : Northing (Y), in meters                  (input)
 *  Latitude         : Latitude, in radians                     (output)
 *  Longitude        : Longitude, in radians                    (output)
 *
 */

  #ifdef __cplusplus
}
  #endif

#endif  /* POLARST_H  */

ossim-Miami-2.9.1/include/ossim/projection/ossimPolyconicProjection.h000066400000000000000000000175651352751253100261020ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description:
//
// Calls Geotrans Polyconic  projection code.  
//*******************************************************************
//  $Id: ossimPolyconicProjection.h 17815 2010-08-03 13:23:14Z dburken $

#ifndef ossimPolyconicProjection_HEADER
#define ossimPolyconicProjection_HEADER

#include 

class OSSIMDLLEXPORT ossimPolyconicProjection : public ossimMapProjection
{
public:   
   ossimPolyconicProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(),
                            const ossimGpt& origin = ossimGpt());
   ossimPolyconicProjection(const ossimEllipsoid& ellipsoid,
                            const ossimGpt& origin,
                            const double falseEasting,
                            const double falseNorthing);
   ~ossimPolyconicProjection(){}
   virtual ossimObject *dup()const
      {
         return new ossimPolyconicProjection(*this);
      }
   
   virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const;
   virtual ossimDpt forward(const ossimGpt &latLon)const;
   virtual void update();

   /*!
    * SetFalseEasting.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEasting(double falseEasting);

   /*!
    * SetFalseNorthing.  The value is in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseNorthing(double falseNorthing);

   /*!
    * Sets both false easting and northing values.  The values are
    * expected to be in meters.
    * Update is then called so we can pre-compute paramters
    */
   void setFalseEastingNorthing(double falseEasting, double falseNorthing);

   void setDefaults();

   double getFalseEasting()const{return  Poly_False_Easting;}
   double getFalseNorthing()const{return Poly_False_Northing;}
   
   /*!
    * Method to save the state of an object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   /*!
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
private:
   
   mutable double Poly_a;                      /* Semi-major axis of ellipsoid in meters */
   mutable double Poly_f;              /* Flattening of ellipsoid */
   mutable double es2;             /* Eccentricity (0.08181919084262188000) squared         */
   mutable double es4;              /* es2 * es2 */
   mutable double es6;              /* es4 * es2 */
   mutable double M0;
   mutable double c0;      /* 1 - es2 / 4.0 - 3.0 * es4 / 64.0 - 5.0 * es6 / 256.0 */
   mutable double c1; /* 3.0 * es2 / 8.0 + 3.0 * es4 / 32.0 + 45.0 * es6 / 1024.0 */
   mutable double c2;             /* 15.0 * es4 / 256.0 + 45.0 * es6 / 1024.0 */
   mutable double c3;               /* 35.0 * es6 / 3072.0 */
   
/* Polyconic projection Parameters */
   mutable double Poly_Origin_Lat;                   /* Latitude of origin in radians     */
   mutable double Poly_Origin_Long;                  /* Longitude of origin in radians    */
   mutable double Poly_False_Northing;               /* False northing in meters          */
   mutable double Poly_False_Easting;                /* False easting in meters           */
   
/* Maximum variance for easting and northing values for WGS 84.
 */
   mutable double Poly_Max_Easting;
   mutable double Poly_Max_Northing;
   mutable double Poly_Min_Easting;
   mutable double Poly_Min_Northing;

/*!
 * The function Set_Polyconic_Parameters receives the ellipsoid parameters and
 * Polyconic projcetion parameters as inputs, and sets the corresponding state
 * variables.If any errors
 * occur, the error code(s) are returned by the function, otherwise 
 * POLY_NO_ERROR is returned.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (input)
 *    f                 : Flattening of ellipsoid                   (input)
 *    Origin_Latitude   : Latitude in radians at which the          (input)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (input)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (input)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (input)
 */
  long Set_Polyconic_Parameters(double a,
                                double f,
                                double Origin_Latitude,
                                double Central_Meridian,
                                double False_Easting,
                                double False_Northing);



/*!
 * The function Get_Polyconic_Parameters returns the current ellipsoid
 * parameters, and Polyconic projection parameters.
 *
 *    a                 : Semi-major axis of ellipsoid, in meters   (output)
 *    f                 : Flattening of ellipsoid                   (output)
 *    Origin_Latitude   : Latitude in radians at which the          (output)
 *                          point scale factor is 1.0
 *    Central_Meridian  : Longitude in radians at the center of     (output)
 *                          the projection
 *    False_Easting     : A coordinate value in meters assigned to the
 *                          central meridian of the projection.     (output)
 *    False_Northing    : A coordinate value in meters assigned to the
 *                          origin latitude of the projection       (output)
 */
  void Get_Polyconic_Parameters(double *a,
                                double *f,
                                double *Origin_Latitude,
                                double *Central_Meridian,
                                double *False_Easting,
                                double *False_Northing)const;



/*!
 * The function Convert_Geodetic_To_Polyconic converts geodetic (latitude and
 * longitude) coordinates to Polyconic projection easting, and northing
 * coordinates, according to the current ellipsoid and Polyconic projection
 * parameters.  If any errors occur, the error code(s) are returned by the
 * function, otherwise POLY_NO_ERROR is returned.
 *
 *    Latitude          : Latitude (phi) in radians           (input)
 *    Longitude         : Longitude (lambda) in radians       (input)
 *    Easting           : Easting (X) in meters               (output)
 *    Northing          : Northing (Y) in meters              (output)
 */
  long Convert_Geodetic_To_Polyconic (double Latitude,
                                      double Longitude,
                                      double *Easting,
                                      double *Northing)const; 


/*!
 * The function Convert_Polyconic_To_Geodetic converts Polyconic projection
 * easting and northing coordinates to geodetic (latitude and longitude)
 * coordinates, according to the current ellipsoid and Polyconic projection
 * coordinates.  If any errors occur, the error code(s) are returned by the
 * function, otherwise POLY_NO_ERROR is returned.
 *
 *    Easting           : Easting (X) in meters                  (input)
 *    Northing          : Northing (Y) in meters                 (input)
 *    Latitude          : Latitude (phi) in radians              (output)
 *    Longitude         : Longitude (lambda) in radians          (output)
 */
  long Convert_Polyconic_To_Geodetic(double Easting,
                                     double Northing,
                                     double *Latitude,
                                     double *Longitude)const;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimPolynomProjection.h000066400000000000000000000122311352751253100255610ustar00rootroot00000000000000//*****************************************************************************
// FILE:   ossimPolynomProjection.h
// AUTHOR: Frederic Claudel Meraka/CSIR
//*****************************************************************************

#ifndef ossimPolynomProjection_HEADER
#define ossimPolynomProjection_HEADER

#include 
#include 
#include 
#include 

/**
 * class for ground to image polynomial projection: (x,y,z)|->(x,y)
 * polynom order is configurable
 */
class OSSIM_DLL ossimPolynomProjection : public ossimProjection,
                                         public ossimOptimizableProjection
{
public:
   
   /**
    * Constructors
    */
   ossimPolynomProjection();
   ossimPolynomProjection(const ossimPolynomProjection& copyme);
   ~ossimPolynomProjection();

   /**
    * Basic operations
    */
   virtual bool operator==(const ossimProjection& projection) const;
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   virtual std::ostream& print(std::ostream& out) const;
   virtual ossimObject* dup() const { return new ossimPolynomProjection(*this); }

   /**
    * Projection / localization methods
    */
   virtual void  worldToLineSample(const ossimGpt& world_point,
                                   ossimDpt&       image_point) const;
   virtual void  lineSampleToWorld(const ossimDpt& image_point,
                                   ossimGpt&       world_point) const;
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                        const double&   heightEllipsoid,
                                        ossimGpt&       worldPoint) const;
   virtual ossimGpt origin()const;
   virtual ossimDpt getMetersPerPixel() const;
   
   /**
    * optimizableProjection implementation
    */
   virtual bool setupOptimizer(const ossimString& setup);
   inline virtual bool useForward()const {return true;}
   virtual ossim_uint32 degreesOfFreedom()const;
   virtual double optimizeFit(const ossimTieGptSet& tieSet, double* targetVariance=NULL);
   
   /**
    * accessors (not all of them inline)
    */
   const ossimPolynom< ossim_float64 , 3 >::EXPT_SET& getExpSet()const { return theExpSet; }
   void setExpSet(const ossimPolynom< ossim_float64 , 3 >::EXPT_SET& nset) { theExpSet = nset; }
   void setupDesiredExponents(int horizonal_ord, int vertical_ord); //!added for easy setup
   bool setupDesiredExponents(const ossimString& monoms);//!added for easy setup

   const ossimPolynom< ossim_float64 , 3 >& getPolyLine()const {return thePolyLine;}
   void setPolyLine(const ossimPolynom< ossim_float64 , 3 >& poly);
   const ossimPolynom< ossim_float64 , 3 >& getPolySamp()const {return thePolySamp;}
   void setPolySamp(const ossimPolynom< ossim_float64 , 3 >& poly);

   const ossim_float64& getLonOffset()const { return theLonOffset;}
   void setLonOffset(const ossim_float64& v) { theLonOffset = v; }
   const ossim_float64& getLonScale()const { return theLonScale;}
   void setLonScale(const ossim_float64& v) { theLonScale = v; }

   const ossim_float64& getLatOffset()const { return theLatOffset;}
   void setLatOffset(const ossim_float64& v) { theLatOffset = v; }
   const ossim_float64& getLatScale()const { return theLatScale;}
   void setLatScale(const ossim_float64& v) { theLatScale = v; }

   const ossim_float64& getHgtOffset()const { return theHgtOffset;}
   void setHgtOffset(const ossim_float64& v) { theHgtOffset = v; }
   const ossim_float64& getHgtScale()const { return theHgtScale;}
   void setHgtScale(const ossim_float64& v) { theHgtScale = v; }

   /**
    * @brief Implementation of pure virtual
    * ossimProjection::isAffectedByElevation method.
    * @return true.
    */
   virtual bool isAffectedByElevation() const { return true; }

protected:
   /**
    * desired exponents tuples set (for both line and sample polynoms)
    * used for optimization
    */
   ossimPolynom< ossim_float64 , 3 >::EXPT_SET theExpSet;

   /** 
    * ground (3d) to image(2D) polynoms
    */
   ossimPolynom< ossim_float64 , 3 > thePolyLine;//!xyz polynom
   ossimPolynom< ossim_float64 , 3 > thePolySamp;

   /**
    * polynom partial derivatives
    */
   ossimPolynom< ossim_float64 , 3 > thePolyLine_DLon;
   ossimPolynom< ossim_float64 , 3 > thePolyLine_DLat;
   ossimPolynom< ossim_float64 , 3 > thePolySamp_DLon;
   ossimPolynom< ossim_float64 , 3 > thePolySamp_DLat;

   /**
    * normalization parameters
    */
   ossim_float64 theLonOffset;
   ossim_float64 theLonScale;
   ossim_float64 theLatOffset;
   ossim_float64 theLatScale;
   ossim_float64 theHgtOffset;
   ossim_float64 theHgtScale;

   /**
    * protected methods
    */
   void buildDerivatives();
   void buildLineDerivatives();
   void buildSampDerivatives();
   bool stringToExp(const ossimString& s, ossimPolynom< ossim_float64 , 3 >::EXP_TUPLE& et)const; //!takes string of xyz monoms, x2z3
   int getSymbol(ossimString& ts,const ossimString& symbols)const;
   int getExponent(ossimString& ts)const;

TYPE_DATA
};

#endif

ossim-Miami-2.9.1/include/ossim/projection/ossimPositionQualityEvaluator.h000066400000000000000000000220371352751253100271340ustar00rootroot00000000000000//----------------------------------------------------------------------------
//
// License:  See top level LICENSE.txt file.
//
// Author:  David Hicks
//
// Description: Base class for position quality evaluation operations.
//----------------------------------------------------------------------------
#ifndef ossimPositionQualityEvaluator_HEADER
#define ossimPositionQualityEvaluator_HEADER

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


// Probability level specifiers
enum pqeProbLev_t
{
   ONE_SIGMA = 0,
   P50,
   P90,
   P95,
   NUM_PROB_LEVELS
};

// Ground space ellipse
struct pqeErrorEllipse
{
   double   theSemiMinorAxis;
   double   theSemiMajorAxis;
   double   theAzimAngle;
   ossimGpt theCenter;
};

// RPC model parameters
struct pqeRPCModel
{
   double theLineScale;
   double theSampScale;
   double theLatScale;
   double theLonScale;
   double theHgtScale;
   double theLineOffset;
   double theSampOffset;
   double theLatOffset;
   double theLonOffset;
   double theHgtOffset;
   double theLineNumCoef[20];
   double theLineDenCoef[20];
   double theSampNumCoef[20];
   double theSampDenCoef[20];
   char   theType; // A or B
};

// Image space ellipse point set
typedef std::vector pqeImageErrorEllipse_t;



class OSSIM_DLL ossimPositionQualityEvaluator
{
public:

   /** @brief default constructor */
   ossimPositionQualityEvaluator();
   
   /** @brief covariance matrix-based constructor
    *
    * @param pt     Current ECF ground estimate.
    * @param covMat 3X3 ECF covariance matrix.
    */
   ossimPositionQualityEvaluator(
      const ossimEcefPoint& pt,
      const NEWMAT::Matrix& covMat);
   
   /** @brief LOS error/geometry-based constructor
    *
    * @param pt           Current ECF ground estimate.
    * @param errBiasLOS   0.68p LOS bias component.
    * @param errRandLOS   0.68p LOS random component.
    * @param elevAngleLOS target elevation angle.
    * @param azimAngleLOS target azimuth angle.
    * @param surfN        surface normal unit vector (defaults to unit Z).
    * @param surfCovMat   surface ENU 3X3 covariance matrix (defaults to zero).
    */
   ossimPositionQualityEvaluator(
      const ossimEcefPoint&      pt,
      const ossim_float64&       errBiasLOS,
      const ossim_float64&       errRandLOS,
      const ossim_float64&       elevAngleLOS,
      const ossim_float64&       azimAngleLOS,
      const ossimColumnVector3d& surfN = ossimColumnVector3d(0,0,1),
      const NEWMAT::Matrix&      surfCovMat = ossimMatrix3x3::createZero());
   
   /** @brief LOS error/coefficient-based constructor
    *
    * @param pt         Current ECF ground estimate.
    * @param errBiasLOS 0.68p LOS bias component.
    * @param errRandLOS 0.68p LOS random component.
    * @param rpc        RPC coefficients.
    * @param surfN      surface normal unit vector (defaults to unit Z).
    * @param surfCovMat surface ENU 3X3 covariance matrix (defaults to zero).
    */
   ossimPositionQualityEvaluator(
      const ossimEcefPoint&      pt,
      const ossim_float64&       errBiasLOS,
      const ossim_float64&       errRandLOS,
      const pqeRPCModel&         rpc,
      const ossimColumnVector3d& surfN = ossimColumnVector3d(0,0,1),
      const NEWMAT::Matrix&      surfCovMat = ossimMatrix3x3::createZero());

   /** @brief virtual destructor */
   ~ossimPositionQualityEvaluator();
   
   /**
    * @brief Add contributing covariance matrix
    *
    * @param covMat 3X3 covariance matrix.
    *
    * @return true on success, false on error.
    */
   bool addContributingCovariance(
      NEWMAT::Matrix& covMat);
   
   /**
    * @brief Add contributing CE/LE
    *
    * @param cCE contributing 90% circular error (m).
    * @param cLE contributing 90% linear error (m).
    *
    * @return true on success, false on error.
    */
   bool addContributingCE_LE(
      const ossim_float64& cCE,
      const ossim_float64& cLE);
   
   /**
    * @brief Subtract contributing covariance matrix
    *
    * @param covMat 3X3 covariance matrix.
    *
    * @return true on success, false on error.
    */
   bool subtractContributingCovariance(
      NEWMAT::Matrix& covMat);
   
   /**
    * @brief Subtract contributing CE/LE
    *
    * @param cCE contributing 90% circular error (m).
    * @param cLE contributing 90% linear error (m).
    *
    * @return true on success, false on error.
    */
   bool subtractContributingCE_LE(
      const ossim_float64& cCE,
      const ossim_float64& cLE);
   
   /**
    * @brief Covariance matrix access
    *
    * @param covMat 3X3 covariance matrix.
    *
    * @return true on success, false on error.
    */
   bool getCovMatrix(
      NEWMAT::Matrix& covMat) const;
   
   /**
    * @brief Compute circular/linear error (CE/LE).
    *
    * @param pLev Probability level.
    * @param CE   pLev% circular error (m).
    * @param LE   pLev% linear error (m).
    *
    * @return true on success, false on error.
    */
   bool computeCE_LE(
      const pqeProbLev_t   pLev,
            ossim_float64& CE,
            ossim_float64& LE) const;

   
   /**
    * @brief Extract error ellipse parameters
    *
    * @param pLev    Probability level.
    * @param ellipse pLev% error ellipse.
    *
    * @return true on success, false on error.
    */
   bool extractErrorEllipse(
      const pqeProbLev_t     pLev,
            pqeErrorEllipse& ellipse);

   
   /**
    * @brief Extract error ellipse parameters; valid only with RPC parameters
    *
    * @param pLev             Probability level.
    * @param angularIncrement Angular increment for ellipse point spacing (deg)
    * @param ellipse          pLev% error ellipse.
    * @param ellImage         pLev% image space error ellipse.
    *
    * @return true on success, false on error.
    */
   bool extractErrorEllipse(
      const pqeProbLev_t            pLev,
      const ossim_float64&          angularIncrement,
            pqeErrorEllipse&        ellipse,
            pqeImageErrorEllipse_t& ellImage);
                                  
   
   /**
    * @brief State accessor.
    */
   inline bool isValid() const { return theEvaluatorValid; }
                                  
   
   /**
    * @brief Print method.
    */
   std::ostream& print(std::ostream& out) const;

protected:

private:
   //***
   // Members
   //***
   bool            theEvaluatorValid;
   ossimGpt        thePtG;
   NEWMAT::Matrix  theCovMat;  //local ENU frame
   ossimLsrSpace   theLocalFrame;
   pqeErrorEllipse theEllipse;
   NEWMAT::Matrix  theEigenvectors;
   pqeRPCModel     theRpcModel;
   
   //***
   // Method for eigenvector decomposition of covariance matrix
   //***
   bool decomposeMatrix();
   
   //***
   // Method for covariance matrix formation from 1-sigma LOS
   // error componenents and imaging geometry
   //***
   bool constructMatrix(const ossim_float64&       errBiasLOS,
                        const ossim_float64&       errRandLOS,
                        const ossim_float64&       elevAngleLOS,
                        const ossim_float64&       azimAngleLOS,
                        const ossimColumnVector3d& surfN,
                        const NEWMAT::Matrix&      surfCovMat);

   //***
   // Method for forming 3X3 ENU covariance matrix from CE/LE
   //***
   bool formCovMatrixFromCE_LE(const ossim_float64&  CE,
                               const ossim_float64&  LE,
                                     NEWMAT::Matrix& covMat) const;

   //***
   // Method for computing 90% CE using interpolating function
   //***
   double compute90PCE() const;
   
   //***
   // Method for computing acquisition angles from RPC coefficients
   //***
   bool computeElevAzim(const pqeRPCModel     rpc,
                              ossim_float64&  elevAngleLOS,
                              ossim_float64&  azimAngleLOS) const;
   
   //***
   // Methods for computing RPC polynomial and its derivatives
   //***
   double polynomial(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   double dPoly_dLat(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   double dPoly_dLon(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   double dPoly_dHgt(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
    
    
    
   //***
   // Utility methods
   //***
   ossimColumnVector3d vperp(const ossimColumnVector3d& v1,
                             const ossimColumnVector3d& v2) const;
                             
   double atan3(const ossim_float64 y, const ossim_float64 x) const;

};

#endif /* #ifndef ossimPositionQualityEvaluator_HEADER */
ossim-Miami-2.9.1/include/ossim/projection/ossimPpjFrameSensor.h000066400000000000000000000046071352751253100247750ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
//
// Author:  Dave Hicks
//
// Description:  PPJ Frame Model
//
//*******************************************************************
//  $Id$
#ifndef ossimPpjFrameSensor_HEADER
#define ossimPpjFrameSensor_HEADER 1
#include 

class OSSIM_DLL ossimPpjFrameSensor : public ossimSensorModel
{
public:
   ossimPpjFrameSensor();

   ossimPpjFrameSensor(const ossimPpjFrameSensor& src);

   virtual ossimObject* dup()const;
   
   virtual void imagingRay(const ossimDpt& image_point,
                           ossimEcefRay&   image_ray) const;
   
   virtual void lineSampleToWorld(const ossimDpt& image_point,
                                 ossimGpt&       worldPoint) const;
   
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                const double&   heightEllipsoid,
                                ossimGpt&       worldPoint) const;

   virtual void worldToLineSample(const ossimGpt& world_point,
                                  ossimDpt&       image_point) const;

   virtual void updateModel();
   
   void setFocalLength(double focX, double focY);

   void setCameraPosition(const ossimGpt& value);
   
   void setPrincipalPoint(const ossimDpt& value);

   void setecef2CamMatrix(const NEWMAT::Matrix& value);
   void setAveragePrjectedHeight(double averageProjectedHeight);

   inline virtual bool useForward()const {return true;}
   
   virtual void initAdjustableParameters();
   virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0);
   virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const;
   
protected:
   NEWMAT::Matrix m_ecef2Cam;
   NEWMAT::Matrix m_ecef2CamInverse;
   ossimDpt       m_principalPoint;   // pixels
   double         m_focalLengthX;     // pixels
   double         m_focalLengthY;     // pixels
   double         m_focalLength;      // pixels
   ossimEcefPoint m_ecefCameraPosition;
   ossimGpt       m_cameraPositionEllipsoid;

   // Not used yet
   double         m_radialK1;
   double         m_radialK2;
   double         m_radialP1;
   double         m_radialP2;
   
   ossimGpt       m_adjustedCameraPosition;
   double         m_adjustedFocalLength;
   double         m_averageProjectedHeight;
   TYPE_DATA
};

#endif /* #ifndef ossimPpjFrameSensor_HEADER */
ossim-Miami-2.9.1/include/ossim/projection/ossimProjection.h000066400000000000000000000113131352751253100242030ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description: Base class for all projections (2D-to-3D transform)
//
//*******************************************************************
//  $Id: ossimProjection.h 23297 2015-05-05 20:32:16Z dburken $
#ifndef ossimProjection_HEADER
#define ossimProjection_HEADER 1

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

class OSSIMDLLEXPORT ossimProjection : public ossimObject, public ossimErrorStatusInterface
{
public:
   /*!
    * Constructors, Destructor:
    */
   ossimProjection();
   virtual ~ossimProjection() {}

   virtual ossimObject *dup()const=0;

   /*!
    * METHOD: origin()
    * Returns projection's ground point origin. That is the GP corresponding
    * to line=0, sample=0.
    */
   virtual ossimGpt origin()const=0;

   /*!
    * METHODS: forward(), reverse() 
    * OBSOLETE -- provided for existing GUI code only. Bogus return value.
    */
   virtual ossimDpt forward(const ossimGpt &wp) const;  //inline below
   virtual ossimGpt inverse(const ossimDpt &pp) const;  //inline below

   /*!
    * METHOD: worldToLineSample()
    * Performs the forward projection from ground point to line, sample.
    */
   virtual void worldToLineSample(const ossimGpt& worldPoint,
                                  ossimDpt&       lineSampPt) const = 0;

   /*!
    * METHOD: lineSampleToWorld()
    * Performs the inverse projection from line, sample to ground (world):
    */
   virtual void lineSampleToWorld(const ossimDpt& lineSampPt,
                                  ossimGpt&       worldPt) const = 0;
   
   /*!
    * METHOD: lineSampleHeightToWorld
    * This is the pure virtual that projects the image point to the given
    * elevation above ellipsoid, thereby bypassing reference to a DEM. Useful
    * for projections that are sensitive to elevation (such as sensor models).
    */
   virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt,
                                        const double&   heightAboveEllipsoid,
                                        ossimGpt&       worldPt) const = 0;

   virtual void getRoundTripError(const ossimDpt& imagePoint,
                                  ossimDpt& errorResult)const;

   virtual void getRoundTripError(const ossimGpt& groundPoint,
                                  ossimDpt& errorResult)const;
   
   virtual std::ostream& print(std::ostream& out) const;

   virtual void getGroundClipPoints(ossimGeoPolygon& gpts)const;
   /*!
    * METHODS:  saveState, loadState
    * Fulfills ossimObject base-class pure virtuals.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   virtual bool isEqualTo(const ossimObject& obj, ossimCompareType compareType = OSSIM_COMPARE_FULL)const
   {
      return ossimObject::isEqualTo(obj, compareType);
   }
   
   /*!
    * OPERATOR: ==
    * Compares this instance with arg projection.
    */
   virtual bool operator==(const ossimProjection& projection) const=0;
   virtual bool operator!=(const ossimProjection& projection) const {return !(*this == projection);}

   /*!
    * ACCESS METHODS: 
    */
   virtual ossimDpt getMetersPerPixel() const=0;

   /**
    * @brief Pure virtual method to query if projection is affected by
    * elevation.
    * @return true if affected, false if not.
    */
   virtual bool isAffectedByElevation() const=0;
   
protected:
  

   TYPE_DATA
};

//====================== BEGIN INLINE DEFINITIONS ===========================

//*****************************************************************************
//  INLINE METHOD: ossimProjection::forward()
//  Projects ground point to 2D plane.
//*****************************************************************************
inline ossimDpt ossimProjection::forward(const ossimGpt &wp) const
{
   ossimDpt p;
   worldToLineSample(wp, p);
   return p;
}

//*****************************************************************************
//  INLINE METHOD: ossimProjection::inverse()
//  Inverse projection from 2D plane to ground point.
//*****************************************************************************
inline ossimGpt ossimProjection::inverse(const ossimDpt &pp) const
{
   ossimGpt g;
   lineSampleToWorld(pp, g);
   return g;
}

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimProjectionFactoryBase.h000066400000000000000000000044371352751253100263370ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
//
// Author: Garrett Potts
//*******************************************************************
//  $Id: ossimProjectionFactoryBase.h 15766 2009-10-20 12:37:09Z gpotts $
#ifndef ossimProjectionFactoryBase_HEADER
#define ossimProjectionFactoryBase_HEADER

#include 
#include 
#include 

class ossimProjection;
class ossimImageHandler;
class OSSIM_DLL ossimProjectionFactoryBase : public ossimObjectFactory
{
public:
   
   /**
    * takes a filename. This filename can be an image file or
    * it can also be a ossim .geom file.  It could be other
    * forms of geom files as well.  The factories job will be to
    * determine what parser to use and return a projection if
    * successful.
    */
   virtual ossimProjection* createProjection(const ossimFilename& filename,
                                             ossim_uint32 entryIdx)const=0;

   /**
    * Take a projection type name.
    */
   virtual ossimProjection* createProjection(const ossimString& name)const=0;

   /**
    * Take a keywordlist.
    */
   virtual ossimProjection* createProjection(const ossimKeywordlist& kwl,
                                             const char* prefix)const=0;
   
   virtual ossimProjection* createProjection(ossimImageHandler* handler)const;

protected:

   /**
    * This method takes the filename and tries to find an external ".geom"
    * file.
    *
    * If the "entryIndx" is 0 and the "imageFile" is foo.ntf this will
    * look for "foo.geom".  If that fails it will look for foo_e0.geom.
    *
    * If the "entryIndx" is 5 and the "imageFile" is foo.ntf this will
    * look for foo_e5.geom.
    *
    * @param imageFile Image file that needs a projection.
    *
    * @param entryIdx For image files that support multiple images this is
    * the zero base index to that image.  Images that don't support multiple
    * indexes should just pass 0.
    *
    * @return An ossimProjection* on success or NULL on failure.
    */
   ossimProjection*
   createProjectionFromGeometryFile(const ossimFilename& imageFile,
                                    ossim_uint32 entryIdx)const;
   
TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimProjectionFactoryRegistry.h000066400000000000000000000053001352751253100272630ustar00rootroot00000000000000//*******************************************************************
// Copyright (C) 2000 ImageLinks Inc. 
//
// License:  See top level LICENSE.txt file.
//
// Author: Garrett Potts
//
//*************************************************************************
// $Id: ossimProjectionFactoryRegistry.h 22851 2014-08-05 12:02:55Z gpotts $
#ifndef ossimProjectionFactoryRegistry_HEADER
#define ossimProjectionFactoryRegistry_HEADER
#include 
#include 
#include 
#include 
#include 
#include 

class ossimImageHandler;
class OSSIM_DLL ossimProjectionFactoryRegistry : public ossimObjectFactory,
                                                 public ossimFactoryListInterface
{
public:

   virtual ~ossimProjectionFactoryRegistry();
   
   static ossimProjectionFactoryRegistry* instance();

   
   ossimProjection* createProjection(const ossimFilename& filename,
                                     ossim_uint32 entryIdx)const;
   ossimProjection* createProjection(const ossimString& name)const
   {
      return createNativeObjectFromRegistry(name);
   }
   ossimProjection* createProjection(const ossimKeywordlist& kwl,
                                     const char* prefix=NULL)const;
   
   virtual ossimProjection* createProjection(ossimImageHandler* handler)const;
   /*!
    * Creates an object given a type name.
    */
   virtual ossimObject* createObject(const ossimString& typeName)const
   {
      return createObjectFromRegistry(typeName);
   }
   
   /*!
    * Creates and object given a keyword list.
    */
   virtual ossimObject* createObject(const ossimKeywordlist& kwl,
                                     const char* prefix=0)const
   {
      return createObjectFromRegistry(kwl, prefix);
   }
   
   /**
    * This should return the type name of all objects in all factories.
    * This is the name used to construct the objects dynamially and this
    * name must be unique.
    */
   virtual void getTypeNameList(std::vector& typeList)const
   {
      getAllTypeNamesFromRegistry(typeList);
   }
      
protected:
   ossimProjectionFactoryRegistry();
   ossimProjectionFactoryRegistry(const ossimProjectionFactoryRegistry& rhs);
   void operator = (const ossimProjectionFactoryRegistry&);

   //static ossimProjectionFactoryRegistry* m_instance;
   void initializeDefaults();
};

extern "C"
{
  OSSIMDLLEXPORT void* ossimProjectionFactoryRegistryGetInstance();
}

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimProjectionViewControllerFactory.h000066400000000000000000000026711352751253100304410ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author: Garrett Potts (gpotts@imagelinks)
// Description:
//
//*************************************************************************
// $Id: ossimProjectionViewControllerFactory.h 17108 2010-04-15 21:08:06Z dburken $
#ifndef ossimProjectionViewControllerFactory_HEADER
#define ossimProjectionViewControllerFactory_HEADER
#include 
#include 

class ossimViewController;

class ossimProjectionViewControllerFactory : public ossimObjectFactory
{
public:
   static ossimProjectionViewControllerFactory* instance();

   virtual ossimViewController* createViewController(const ossimString& name)const;
   virtual ossimViewController* createViewController(const ossimKeywordlist& kwl,
                                                     const char* prefix)const;

   virtual ossimObject* createObject(const ossimString& typeName)const;
   virtual ossimObject* createObject(const ossimKeywordlist& kwl,
                                     const char* prefix)const;

   virtual void getTypeNameList(std::vector& typeList)const;
   
protected:
   ossimProjectionViewControllerFactory(){}
   ossimProjectionViewControllerFactory(const ossimProjectionViewControllerFactory& /* rhs */){}

   static ossimProjectionViewControllerFactory* theInstance;
TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimQuadProjection.h000066400000000000000000000053311352751253100250210ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author: Garrett Potts
// 
//********************************************************************
// $Id: ossimQuadProjection.h 15766 2009-10-20 12:37:09Z gpotts $
#ifndef ossimQuadProjection_HEADER
#define ossimQuadProjection_HEADER

#include 
#include 
#include 

class ossimQuadProjection : public ossimProjection
{
 public:
   ossimQuadProjection();
   ossimQuadProjection(const ossimQuadProjection& rhs);
   ossimQuadProjection(const ossimIrect& rect,
                       const ossimGpt& ulg,
                       const ossimGpt& urg,
                       const ossimGpt& lrg,
                       const ossimGpt& llg);
                       
   virtual ossimObject *dup()const;
   virtual ossimGpt origin()const;
   
   virtual void worldToLineSample(const ossimGpt& worldPoint,
                                  ossimDpt&       lineSampPt) const;
   /*!
    * METHOD: lineSampleToWorld()
    * Performs the inverse projection from line, sample to ground (world):
    */
   virtual void lineSampleToWorld(const ossimDpt& lineSampPt,
                                  ossimGpt&       worldPt) const;
   
   /*!
    * METHOD: lineSampleHeightToWorld
    * This is the pure virtual that projects the image point to the given
    * elevation above ellipsoid, thereby bypassing reference to a DEM. Useful
    * for projections that are sensitive to elevation (such as sensor models).
    */
   virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt,
                                        const double&   heightAboveEllipsoid,
                                        ossimGpt&       worldPt) const;
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0)const;

   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);
   
   virtual bool operator==(const ossimProjection& projection) const;
   virtual ossimDpt getMetersPerPixel() const;

   /**
    * @brief Implementation of pure virtual
    * ossimProjection::isAffectedByElevation method.
    * @return false.
    */
   virtual bool isAffectedByElevation() const { return false; }

 protected:
   virtual ~ossimQuadProjection();
   
   ossimIrect theInputRect;
   ossimGpt theUlg;
   ossimGpt theUrg;
   ossimGpt theLrg;
   ossimGpt theLlg;

   ossimDblGrid theLatGrid;   
   ossimDblGrid theLonGrid;

   void initializeGrids();
   ossimGpt extrapolate(const ossimDpt& imagePoint,
                        const double&   height) const;
TYPE_DATA   
};

#endif /* #ifndef ossimQuadProjection_HEADER */
ossim-Miami-2.9.1/include/ossim/projection/ossimQuickbirdRpcModel.h000066400000000000000000000063441352751253100254420ustar00rootroot00000000000000//*****************************************************************************
// FILE: ossimQuickbirdRpcModel.h
//
// Copyright (C) 2001 ImageLinks, Inc.
//
// License:  MIT
//
// See LICENSE.txt file in the top level directory for more details.
//
// DESCRIPTION: Contains declaration of class ossimQuickbirdRpcModel. This
//    derived class implements the capability of reading Quickbird RPC support
//    data.
//
// LIMITATIONS: None.
//
//*****************************************************************************
//  $Id: ossimQuickbirdRpcModel.h 20606 2012-02-24 12:29:52Z gpotts $
#ifndef ossimQuickbirdRpcModel_HEADER
#define ossimQuickbirdRpcModel_HEADER

#include 
#include 
#include 
#include 

class ossimFilename;
class ossimQuickbirdMetaData;
class ossimQbTileFilesHandler;

/*!****************************************************************************
 *
 * CLASS:  ossimQuickbirdRpcModel
 *
 *****************************************************************************/
class ossimQuickbirdRpcModel : public ossimRpcModel
{
public:
   ossimQuickbirdRpcModel();
   ossimQuickbirdRpcModel(const ossimQuickbirdRpcModel &rhs);

   //! Initializes
   ossimQuickbirdRpcModel(const ossimQbTileFilesHandler *handler);
   ~ossimQuickbirdRpcModel();

   virtual ossimObject *dup() const;
   virtual bool saveState(ossimKeywordlist &kwl,
                          const char *prefix = 0) const;

   virtual bool loadState(const ossimKeywordlist &kwl,
                          const char *prefix = 0);

   virtual bool parseFile(const ossimFilename &file);

   void setSupportData(ossimQuickbirdMetaData *supportData)
   {
      theSupportData = supportData;
   }
   ossimQuickbirdMetaData *getSupportData()
   {
      return theSupportData.get();
   }
   const ossimQuickbirdMetaData *getSupportData() const
   {
      return theSupportData.get();
   }

   /** Initializes this with contents of RPC file. IMPORTANT: This is not enough to fully initialize
    * the model. The image size and reference (mid) point need to be set before calling this method
    * so that the GSD is properly computed. A guesstimate of image size is made based
    * on line/samp offset params, but this will probably be wrong. Returns TRUE if successful. */
   bool parseRpcData(const ossimFilename &file);

protected:
   bool parseNitfFile(const ossimFilename &file);
   bool parseTiffFile(const ossimFilename &file);
   bool parseMetaData(const ossimFilename &file);
   bool parseTileData(const ossimFilename &file);

   //! Given an initial filename with case-agnostic extension, this method searches first for an
   //! image-specific instance of that file (i.e., with _R*C* in the filename) before considering
   //! the mosaic-global support file (_R*C* removed). If a file is found, the argument is modified
   //! to match the actual filename and TRUE is returned. Otherwise, argument filename is left
   //! unchanged and FALSE is returned.
   bool findSupportFile(ossimFilename &file) const;

   void finishConstruction();

   ossimRefPtr theSupportData;
   std::shared_ptr m_qbRpcHeader;

TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimRS1SarModel.h000066400000000000000000000117321352751253100241300ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
//
// Author:  Oscar Kramer
//
// Description:
//
// Sensor Model for Radarsat1 SAR sensor.
// 
//*******************************************************************
//  $Id:$

#ifndef ossimRS1SarModel_HEADER
#define ossimRS1SarModel_HEADER 1

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

// Namespace class forward class declaration.
namespace NEWMAT
{
   class Matrix;
}

//*****************************************************************************
// CLASS:  ossimRS1SarModel
//*****************************************************************************
class ossimRS1SarModel : public ossimSensorModel
{
public:
   ossimRS1SarModel();
   ossimRS1SarModel(const ossimFilename& imageDir);

   virtual ~ossimRS1SarModel();
   
   enum ImagingMode
   {
      UNKNOWN_MODE = 0,
      SCN,     // ScanSAR Narrow Beam
      SCW,     // ScanSAR Wide Beam
      SGC,     // SAR Georeferenced Coarse Resolution
      SGF,     // SAR Georeferenced Fine Resolution
      SGX,     // SAR Georeferenced Extra Fine Resolution
      SLC,     // Single Look Complex
      SPG,     // SAR Precision Geocoded
      SSG,     // SAR Systematically Geocoded
      RAW,
      ERS
   };

   enum DirectionFlag
   {
      UNKNOWN_DIRECTION = 0,
      ASCENDING,
      DESCENDING
   };
   
   //! Fulfills ossimObject base-class pure virtuals. Saves modeling info to KWL.
   //! Returns true if successful.
   virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL) const;
   
   //! Fulfills ossimObject base-class pure virtuals. Reads modeling info from KWL.
   //! Returns true if successful.
   virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL);

   //! Establishes geographic 3D point given image line, sample and ellipsoid height.
   virtual void lineSampleHeightToWorld(const ossimDpt& imagePt, 
                                        const double& heightAboveEllipsoid, 
                                        ossimGpt& worldPt) const;

   //! Given an image point, returns a ray originating at some arbitrarily high
   //! point (in this model at the sensor position) and pointing towards the target.
   virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const;

   inline virtual bool useForward() const { return false; } //!image to ground faster 

   //!  Returns pointer to a new instance, copy of this.
   virtual ossimObject* dup() const { return 0; } // TBR

protected:
   void setImagingMode(char* modeStr);
   void initFromCeos(const ossimFilename& dataDir);
   void initAdjParms();
   void establishEphemeris();
   void eciToEcfXform(const double& julianDay, NEWMAT::Matrix& xform) const;
   void establishOrpInterp();
   void establishOrpGrid();
   void establishVehicleSpace();
   void interpolatedScanORP(const ossimDpt& orp, ossimEcefPoint& orp_ecf) const;
   void deallocateMemory();
   
   ossimRefPtr theCeosData;
   ossimRefPtr theArpPosInterp;   // in ECF
   ossimRefPtr theArpVelInterp;   // in ECF
   ossimRefPtr theLocalOrpInterp; // in ECF
   ImagingMode     theImagingMode;
   double          theIllumAzimuth;
   double          theIllumElevation;
   ossimEcefPoint  theORP;
   double          theRefHeight;
   double          theGHA;           // Greenwich Hour Angle of first eph. pt.
   double          theEphFirstSampTime; // in seconds from start of day
   double          theSinOrientation;
   double          theCosOrientation;
   double          theSinSkew;
   ossimLsrSpace   theVehicleSpace;
   ossimEcefVector thePosCorrection;
   int             theFirstLineDay;   // julian day
   double          theFirstLineTime;  // seconds
   double          theTimePerLine;    // seconds
   DirectionFlag   theDirectionFlag;
   double          theSrGrCoeff[6];
   ossimDpt        thePixelSpacing; 
   //***
   // Additional data members used for scan-mode imagery:
   //***
   ossimDblGrid    theLatGrid;
   ossimDblGrid    theLonGrid;
   
   //***
   // Adjustable Parameters:
   //***
   double          theInTrackOffset; // meters
   double          theCrTrackOffset; // meters
   double          theRadialOffset;  // meters
   double          theLineScale;
   double          theSkew;
   double          theOrientation; // degrees
   
   //***
   // Adjustable model parameters array indexes:
   //***
   enum ADJUSTABLE_PARAM_INDEXES
   {
      INTRACK_OFFSET,
      CRTRACK_OFFSET,
      RADIAL_OFFSET,
      LINE_SCALE,
      SKEW,
      ORIENTATION,
      NUM_ADJUSTABLE_PARAMS  // not a parameter
   };

};


#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimRadialDecentLensDistortion.h000066400000000000000000000123771352751253100273220ustar00rootroot00000000000000//*******************************************************************
//
// License:  See top level LICENSE.txt file.
// 
// Author:  Garrett Potts (gpotts@imagelinks.com)
//
// Description: Modeling for lens radial and decentering distortion.
//
//   The default implementation is:
//  
//   Let X and Y be coordinates relative to the center. Let
//   Xc and Yc be the adjusted point so that:
//  
//   Xc = X + delta1X + delta2X
//   Yc = Y + delta1Y + delta2Y
//  
//   
//   delta1X = X*(k0 + k1*r^2 + k2*r^4 + k3*r^6 + k4*r^8)
//   delta1Y = Y*(k0 + k1*r^2 + k2*r^4 + k3*r^6 + k4*r^8)
//   
//   delta2X = (1 + p3*r^2 + p4*r^4)[p1*(r^2 + 2*X^2) + 2*p2*X*Y]
//   delta2Y = (1 + p3*r^2 + p4*r^4)[2*p1*X*Y  + p2*(r^2 + 2*Y^2) ]
//  
//  
//   Note the point that is passed in we will compute:
//         =  position - calibratedPrincipalPoint.
//  
//        so if you compute the delta then make sure that
//        this class is constructed with principal point
//        at 0,0
//  
//   Reference book: Elements of Photogrammetry Paul Wolf
//   
//*******************************************************************
//  $Id: ossimRadialDecentLensDistortion.h 22879 2014-09-03 20:19:42Z dburken $
#ifndef ossimRadialDecentLensDistortion_HEADER
#define ossimRadialDecentLensDistortion_HEADER
#include 
#include 
#include 
#include 

//*****************************************************************************
//  CLASS
//*****************************************************************************
class OSSIMDLLEXPORT ossimRadialDecentLensDistortion
   : public ossim2dTo2dTransform
{
public:
   ossimRadialDecentLensDistortion() {}
   ossimRadialDecentLensDistortion
      (const ossimDpt& calibratedPrincipalPoint,
       const NEWMAT::ColumnVector &radialDistortionParameters,
       const NEWMAT::ColumnVector &decentDistortionParameters)
      : theCalibratedPrincipalPoint(calibratedPrincipalPoint),
        theRadialDistortionParameters(radialDistortionParameters),
        theDecentDistortionParameters(decentDistortionParameters)
      {  }

   ossimRadialDecentLensDistortion(const ossimRadialDecentLensDistortion& copy)
      : theCalibratedPrincipalPoint (copy.theCalibratedPrincipalPoint),
        theRadialDistortionParameters (copy.theRadialDistortionParameters),
        theDecentDistortionParameters (copy.theDecentDistortionParameters) { }

   ossimRadialDecentLensDistortion(const ossimKeywordlist& kwl,
                                   const char* prefix);

   virtual ~ossimRadialDecentLensDistortion(){}
   
   /*!
    * Implementation of base class 2D-to-2D transformation. The "forward"
    * transformation is defined here as going from an undistorted ideal point to
    * a distorted real point, i.e., adding distortion.
    * 
    * Also available (implemented in the base class) are:
    *   inverse(distorted_point_in, undistorted_pt_out)
    *   inverse(undistort_this_pt)
    */
   virtual void forward(const ossimDpt& undistorted_point_in,
                        ossimDpt&       distorted_point_out) const;

   virtual void forward(ossimDpt&  modify_this) const 
      {
         ossimDpt output;
         forward(modify_this, output);
         modify_this = output;
      }
      
   
   /*!
    * Method to save the state of the object to a keyword list.
    * Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;

   /*!
    * Method to the load (recreate) the state of the object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   /*!
    * Set methods provide alternative initialization scheme to loadState:
    */
   void setPrincipalPoint(const ossimDpt pp);
   void setRadialDistortionParams(const NEWMAT::ColumnVector& params);
   void setDecentDistortionParams(const NEWMAT::ColumnVector& params);
   /*!
    * Dumps contents of object to std::ostream.
    */
   virtual std::ostream& print(std::ostream& out) const;
   
   static const char* PRINCIPAL_POINT_X_KW;
   static const char* PRINCIPAL_POINT_Y_KW;
   static const char* RADIAL_DISTORTION_COEFF_KW;
   static const char* DECENT_DISTORTION_COEFF_KW;
   
protected:
   /*!
    * default implementation Will solve the polynomial:
    *
    * k0 + k1*r^2 + k2*r^4 + k3*r^6 + k4*r^8
    */
   virtual double deltaR(double radius)const;
   
   ossimDpt     theCalibratedPrincipalPoint;
   NEWMAT::ColumnVector theRadialDistortionParameters;
   NEWMAT::ColumnVector theDecentDistortionParameters;  

   TYPE_DATA
};

//*****************************************************************************
//  INLINE METHODS
//*****************************************************************************
inline void
ossimRadialDecentLensDistortion::setPrincipalPoint(const ossimDpt pp)
{
   theCalibratedPrincipalPoint = pp;
}

inline void ossimRadialDecentLensDistortion::setRadialDistortionParams
   (const NEWMAT::ColumnVector& params)
{
   theRadialDistortionParameters = params;
}

inline void ossimRadialDecentLensDistortion::setDecentDistortionParams
   (const NEWMAT::ColumnVector& params)
{
   theDecentDistortionParameters = params;
}


#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimRpcModel.h000066400000000000000000000231001352751253100235710ustar00rootroot00000000000000//*****************************************************************************
// FILE: ossimRpcModel.h
//
// License:  See top level LICENSE.txt file.
//
// AUTHOR: Oscar Kramer
//
// DESCRIPTION: Contains declaration of class ossimRpcModel.
//   This is a replacement model utilizing the Rational Polynomial Coefficients
//   (RPC), a.k.a. Rapid Positioning Capability, and Universal Sensor Model
//   (USM).
//
//*****************************************************************************
//  $Id: ossimRpcModel.h 16174 2009-12-23 16:34:06Z dburken $

#ifndef ossimRpcModel_HEADER
#define ossimRpcModel_HEADER

#include 
#include 
#include 
#include 
#include 
#include 

/*!****************************************************************************
 *
 * CLASS:  ossimRpcModel
 *
 *****************************************************************************/
class OSSIMDLLEXPORT ossimRpcModel : public ossimSensorModel
{
public:
   //***
   // Enumeration of supported RPC polynomial formats:
   //***
   enum PolynomialType
   {
      A='A',  // corresponds to "RPC00A"
      B='B'   // corresponds to "RPC00B"
   };

   /** @brief RPC model structure used for access function */
   struct rpcModelStruct
   {
      double lineScale;
      double sampScale;
      double latScale;
      double lonScale;
      double hgtScale;
      double lineOffset;
      double sampOffset;
      double latOffset;
      double lonOffset;
      double hgtOffset;
      double lineNumCoef[20];
      double lineDenCoef[20];
      double sampNumCoef[20];
      double sampDenCoef[20];
      char   type;
   };

   /** @brief default constructor */
   ossimRpcModel();

   /** @brief copy construtor */
   ossimRpcModel(const ossimRpcModel& copy_this);

   void setAttributes(ossim_float64 theSampleOffset,
                      ossim_float64 theLineOffset,
                      ossim_float64 theSampleScale,
                      ossim_float64 theLineScale,
                      ossim_float64 theLatOffset,
                      ossim_float64 theLonOffset,
                      ossim_float64 theHeightOffset,
                      ossim_float64 theLatScale,
                      ossim_float64 theLonScale,
                      ossim_float64 theHeightScale,
                      const std::vector& xNumeratorCoeffs,
                      const std::vector& xDenominatorCoeffs,
                      const std::vector& yNumeratorCoeffs,
                      const std::vector& yDenominatorCoeffs,
                      PolynomialType polyType = B,
                      bool computeGsdFlag=true);

   void setMetersPerPixel(const ossimDpt& metersPerPixel);

   /**
    * @brief Sets data member theBiasError, theRandError.
    *
    * @param biasError Error - Bias 68% non time - varying error estimate
    * assumes correlated images.  Units = meters.
    *
    * @param randError Error - Random 68% time - varying error estimate
    * assumes uncorrelated images. Units = meters.
    *
    * @param initNominalPostionErrorFlag If true the base data member
    * theNominalPosError will be initialized with:
    * sqrt(theBiasError*theBiasError +theRandError*theRandError)
    */
   void setPositionError(const ossim_float64& biasError,
                         const ossim_float64& randomError,
                         bool initNominalPostionErrorFlag);

   /**
    * @brief worldToLineSample()
    * Overrides base class implementation. Directly computes line-sample from
    * the polynomials.
    */
   virtual void  worldToLineSample(const ossimGpt& world_point,
                                   ossimDpt&       image_point) const;
   /**
    * @brief print()
    * Extends base-class implementation. Dumps contents of object to std::ostream.
    */
   virtual std::ostream& print(std::ostream& out) const;

   /**
    * @brief saveState
    * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry
    * KWL files. Returns true if successful.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;
   
   /**
    * @brief loadState
    * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry
    * KWL files. Returns true if successful.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   //***
   // @brief lineSampleToWorld()
   // Overrides base class pure virtual.  Intersects DEM.
   //***
   virtual void  lineSampleToWorld(const ossimDpt& image_point,
                                   ossimGpt&       world_point) const;
   //***
   // @brief lineSampleHeightToWorld()
   // Overrides base class pure virtual. Height understood to be relative to
   // standard ellipsoid.
   //***
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                        const double&   heightEllipsoid,
                                        ossimGpt&       worldPoint) const;
   
   /**
    * @brief imagingRay()
    * Overrides base class pure virtual.
    */
   virtual void imagingRay(const ossimDpt& image_point,
                           ossimEcefRay&   image_ray) const;

   /**
    * @brief STATIC METHOD: writeGeomTemplate(std::ostream)
    * Writes a template of geom keywords processed by loadState and saveState
    * to output stream.
    */
   static void writeGeomTemplate(std::ostream& os);

   virtual void updateModel();
   virtual void initAdjustableParameters();

   /**
    * @brief dup()
    * Returns pointer to a new instance, copy of this.
    */
   virtual ossimObject* dup() const;

   inline virtual bool useForward()const {return false;}

   /** @brief uses file path to init model */
   virtual bool setupOptimizer(const ossimString& init_file);

   /**
    * @brief Compute partials of samp/line WRT ground point
    *
    * @param parmIdx computational mode:
    *        OBS_INIT, EVALUATE, P_WRT_X, P_WRT_X, P_WRT_X.
    *
    * @param gpos Current ground point estimate.
    *
    * @param h Not used.
    *
    * @return OBS_INT: n/a, EVALUATE: residuals, P_WRT_X/Y/Z: partials.
    */
   virtual ossimDpt getForwardDeriv(int parmIdx,
                                    const ossimGpt& gpos,
                                    double h);

   /**
    * @brief Returns Error - Bias.
    * @return Error - Bias
    * @note See NITF field "ERR_BIAS" from RPC00x tag where x = A or B.
    */
   double getBiasError() const;

   /**
    * @brief Returns Error - Random.
    * @return Error - Random
    * @note See NITF field "ERR_RAND" from RPC00x tag where x = A or B.
    */
   double getRandError() const;

   /**
    * @brief Returns RPC parameter set in structure.
    * @param rpcModelStruct structure to initialize.
    */
   void getRpcParameters(ossimRpcModel::rpcModelStruct& model) const;
   
   /** Allows setting an offset to a subimage while using the coefficients of a full-image model.
    * This adds a shift to the line and sample offsets so they corresond to the local subimage
    * image space coordinates. Note thatthe base class' theImageRect will be adjusted to reflect the
    * shift, even though the chip's LR corner will probably be wrong.
    */
   void setImageOffset(const ossimDpt& offset_to_chip_ul);

   /**
    * Serializes RPC to JSON format.
    */
   bool toJSON(std::ostream& json) const;

   /**
    * Serialize to WorldView-style .RPB file to the stream provided.
    * Returns TRUE on successful write.
    * */
   bool toRPB(std::ostream &out) const;

protected:
   enum AdjustParamIndex
   {
      INTRACK_OFFSET = 0,
      CRTRACK_OFFSET,
      INTRACK_SCALE,
      CRTRACK_SCALE,
      MAP_ROTATION,
//      YAW_OFFSET,
      NUM_ADJUSTABLE_PARAMS // not an index
   };

   /** @brief virtual destructor */
   virtual ~ossimRpcModel();
   
   //***
   // Methods for computing RPC polynomial and its derivatives:
   //***
   double polynomial(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   double dPoly_dLat(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   double dPoly_dLon(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   double dPoly_dHgt(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   
   PolynomialType thePolyType;

   //***
   // Quantities for zero-biasing and normalizing the image point and
   // ground point coordinates referenced in the polynomials:
   //***
   double theLineScale;
   double theSampScale;
   double theLatScale;
   double theLonScale;
   double theHgtScale;
   double theLineOffset;
   double theSampOffset;
   double theLatOffset;
   double theLonOffset;
   double theHgtOffset;

   
   //***
   // Quantities derived from the adjustable parameters:
   //***
   double theIntrackOffset;
   double theCrtrackOffset;
   double theIntrackScale;
   double theCrtrackScale;
   double theCosMapRot;
   double theSinMapRot;

   /** error */
   double theBiasError; // meters
   double theRandError; // meters

   //***
   // Coefficients:
   //***
   double theLineNumCoef[20];
   double theLineDenCoef[20];
   double theSampNumCoef[20];
   double theSampDenCoef[20];
 
   friend class ossimRpcSolver;
   friend class ossimNitfRpcBase;

   TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimRpcProjection.h000066400000000000000000000201261352751253100246520ustar00rootroot00000000000000//*****************************************************************************
// FILE: ossimRpcProjection.h
//
// MIT
//
// DESCRIPTION: Contains declaration of class ossimRpcProjection.
//   This is a replacement model utilizing the Rational Polynomial Coefficients
//   (RPC), a.k.a. Rapid Positioning Capability, and Universal Sensor Model
//   (USM).
//
//*****************************************************************************
//  $Id: ossimRpcProjection.h 11805 2007-10-05 14:54:28Z dburken $

#ifndef ossimRpcProjection_HEADER
#define ossimRpcProjection_HEADER

#include 
#include 
#include 
#include 
#include 

/*!****************************************************************************
 *
 * CLASS:  ossimRpcProjection
 *
 *****************************************************************************/
class OSSIM_DLL ossimRpcProjection : public ossimProjection,
                                     public ossimOptimizableProjection,
                                     public ossimAdjustableParameterInterface
{
public:
   //***
   // Enumeration of supported RPC polynomial formats:
   //***
   enum PolynomialType
   {
      A='A',  // corresponds to "RPC00A"
      B='B'   // corresponds to "RPC00B"
   };
   
   /*!
    * CONSTRUCTORS:
    */
   ossimRpcProjection();
   ossimRpcProjection(const ossimRpcProjection& copy_this);
   ~ossimRpcProjection();

   ossimRpcProjection& operator=(const ossimRpcProjection& source);

   void initAdjustableParameters();
   virtual void adjustableParametersChanged();
   
   virtual ossimObject* getBaseObject();
   virtual const ossimObject* getBaseObject()const;
   
   void setAttributes(ossim_float64 theSampleOffset,
                      ossim_float64 theLineOffset,
                      ossim_float64 theSampleScale,
                      ossim_float64 theLineScale,
                      ossim_float64 theLatOffset,
                      ossim_float64 theLonOffset,
                      ossim_float64 theHeightOffset,
                      ossim_float64 theLatScale,
                      ossim_float64 theLonScale,
                      ossim_float64 theHeightScale,
                      const std::vector& xNumeratorCoeffs,
                      const std::vector& xDenominatorCoeffs,
                      const std::vector& yNumeratorCoeffs,
                      const std::vector& yDenominatorCoeffs,
                      PolynomialType polyType = B);
                      
   /*!
    * METHOD: worldToLineSample()
    * Overrides base class implementation. Directly computes line-sample from
    * the polynomials.
    */
   virtual void  worldToLineSample(const ossimGpt& world_point,
                                   ossimDpt&       image_point) const;
   /*!
    * METHOD: print()
    * Extends base-class implementation. Dumps contents of object to std::ostream.
    */
   virtual std::ostream& print(std::ostream& out) const;

   /*!
    * METHODS:  saveState, loadState
    * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry
    * KWL files. Returns true if successful.
    */
   virtual bool saveState(ossimKeywordlist& kwl,
                          const char* prefix=0) const;

   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=0);

   virtual void  lineSampleToWorld(const ossimDpt& image_point,
                                   ossimGpt&       world_point) const;
   //***
   // METHOD: lineSampleHeightToWorld()
   // Overrides base class pure virtual. Height understood to be relative to
   // standard ellipsoid.
   //***
   virtual void lineSampleHeightToWorld(const ossimDpt& image_point,
                                        const double&   heightEllipsoid,
                                        ossimGpt&       worldPoint) const;

   /*!
    * METHOD: dup()
    * Returns pointer to a new instance, copy of this.
    */
   virtual ossimObject* dup() const { return new ossimRpcProjection(*this); }

   virtual ossimGpt origin()const;
   virtual ossimDpt getMetersPerPixel() const;
   virtual bool operator==(const ossimProjection& projection) const;
   
   /*
    * optimizable interface
    */
    virtual bool setupOptimizer(const ossimString& setup);
    inline virtual bool useForward()const {return true;}
    virtual ossim_uint32 degreesOfFreedom()const;
    virtual double optimizeFit(const ossimTieGptSet& tieSet, double* targetVariance=NULL);
   /*!
    * METHOD: getForwardDeriv()
    * gives forward() partial derivative regarding parameter parmIdx (>=0)
    * default implementation is centered finite difference
    * -should be reimplemented with formal derivative in child class
    */
   virtual ossimDpt getForwardDeriv(int parmIdx, const ossimGpt& gpos, double hdelta=1e-11);

   /*!
    * METHOD: getInverseDeriv()
    * gives inverse() partial derivative regarding parameter parmIdx (>=0)
    * default implementation is centered finite difference
    * -should be reimplemented with formal derivative in child class
    */
   virtual ossimGpt getInverseDeriv(int parmIdx, const ossimDpt& ipos, double hdelta=1e-11);

   /**
    * @brief Implementation of pure virtual
    * ossimProjection::isAffectedByElevation method.
    * @return true.
    */
   virtual bool isAffectedByElevation() const { return true; }

protected:
   //***
   // Methods for computing RPC polynomial and its derivatives:
   //***
   double polynomial(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   double dPoly_dLat(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   double dPoly_dLon(const double& nlat,
                     const double& nlon,
                     const double& nhgt,
                     const double* coeffs) const;
   
   /*!
    * METHOD: buildNormalEquation
    * builds linearized system  (LMS equivalent)
    * A*dp = projResidue
    * 
    * A: symetric matrix = tJ*J
    * dp: system parameter shift that we want to estimate
    * projResidue = tJ * residue
    *
    * t: transposition operator
    * J = jacobian of transform relative to parameters p, transform can be forward() or inverse()
    * jacobian is obtained via finite differences
    * residue can be image (2D) or ground residue(3D)
    *
    * TODO: use image/ground points covariance matrices
    */
   void buildNormalEquation(const ossimTieGptSet& tieSet,
                                      NEWMAT::SymmetricMatrix& A,
                                      NEWMAT::ColumnVector& residue,
                                      NEWMAT::ColumnVector& projResidue,
                                      double pstep_scale);

   /*!
    * METHOD: getResidue()
    * returns ground opr image residue
    */
   NEWMAT::ColumnVector getResidue(const ossimTieGptSet& tieSet);

   NEWMAT::ColumnVector solveLeastSquares(NEWMAT::SymmetricMatrix& A,  NEWMAT::ColumnVector& r)const;

   /*!
    * stable invert stolen from ossimRpcSolver
    */
   NEWMAT::Matrix invert(const NEWMAT::Matrix& m)const;

   PolynomialType thePolyType;
   //***
   // Quantities for zero-biasing and normalizing the image point and
   // ground point coordinates referenced in the polynomials:
   //***
   double theLineScale;
   double theSampScale;
   double theLatScale;
   double theLonScale;
   double theHgtScale;
   double theLineOffset;
   double theSampOffset;
   double theLatOffset;
   double theLonOffset;
   double theHgtOffset;

   //***
   // Coefficients:
   //***
   double theLineNumCoef[20];
   double theLineDenCoef[20];
   double theSampNumCoef[20];
   double theSampDenCoef[20];

   //*
   // Quantities derived from the adjustable parameters:
   //*
   double theIntrackOffset;
   double theCrtrackOffset;
   double theIntrackScale;
   double theCrtrackScale;
   double theYawSkew;  // = sin(theYawOffset)
   double theCosMapRot;
   double theSinMapRot;
   
   TYPE_DATA
};

#endif
ossim-Miami-2.9.1/include/ossim/projection/ossimRpcSolver.h000066400000000000000000000203241352751253100240100ustar00rootroot00000000000000//**************************************************************************************************
//
//     OSSIM Open Source Geospatial Data Processing Library
//     See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#ifndef ossimRpcSolver_HEADER
#define ossimRpcSolver_HEADER

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

/**
 * This currently only support Rational poilynomial B format.  This can be
 * found in the NITF registered commercial tag document.
 *
 * @note x=longitude, y=latitude, z=height
 * 
 * 
 * Format is:
 *  coeff[ 0]       + coeff[ 1]*x     + coeff[ 2]*y     + coeff[ 3]*z     +
 *  coeff[ 4]*x*y   + coeff[ 5]*x*z   + coeff[ 6]*y*z   + coeff[ 7]*x*x   +
 *  coeff[ 8]*y*y   + coeff[ 9]*z*z   + coeff[10]*x*y*z + coeff[11]*x*x*x +
 *  coeff[12]*x*y*y + coeff[13]*x*z*z + coeff[14]*x*x*y + coeff[15]*y*y*y +
 *  coeff[16]*y*z*z + coeff[17]*x*x*z + coeff[18]*y*y*z + coeff[19]*z*z*z;
 *
 *       where coeff is one of XNum, XDen, YNum, and YDen.  So there are 80
 *       coefficients all together.
 *
 * Currently we use a linear least squares fit to solve the coefficients.
 * This is the simplest to implement.  We probably relly need a nonlinear
 * minimizer to fit the coefficients but I don't have time to experiment.
 * Levenberg Marquardt might be a solution to look into.
 *
 * HOW TO USE:
 * 
 *        ossimRpcSolver solver;
 *        solver.solveCoefficients(rect,
 *                                 *proj.get());
 *                                 
 * We can also call solve coefficients with a list of ground control points.
 * First is the list of image points followed by the ground points.
 * NOTE: Thes must be equal in size.
 * 
 *        solver.solveCoefficients(imagePoints,
 *                                 groundPoints);
 *                                 
 * Once you call solveCoefficients you can create the projector:
 *                                 
 *        ossimRefPtr rpc = solver.createRpcProjection();
 *
 * Note that a sub-image bounding rect can be passed into the solve methods. This
 * constrains the solution fit to cover only that rectangle in the original image space,
 * but the image coordinates used are still based on the full image. If the intent is to
 * generate an RPC that will work for an image chip in that chip's local image coordinate
 * system (i.e., the UL corner of the chip is 0, 0), then you'll need to call
 * rpcModel->setImageOffset(chip_offset) on the output RPC model.
 *
 * 
* */ class OSSIM_DLL ossimRpcSolver : public ossimReferenced { public: /** * The use elvation flag will deterimne if we force the height t be 0. * If the elevation is enabled then we use the height field of the control * points to determine the coefficients of the RPC00 polynomial. If its * false then we will ignore the height by setting the height field to 0.0. * * Note: even if the elevation is enabled all NAN heights are set to 0.0. */ ossimRpcSolver(bool useElevation=false, bool useHeightAboveMSLFlag=false); virtual ~ossimRpcSolver(){} /** * This will convert any projector to an RPC model */ void solveCoefficients(const ossimDrect& imageBounds, ossimProjection* imageProj, ossim_uint32 xSamples=8, ossim_uint32 ySamples=8); void solveCoefficients(const ossimDrect& imageBounds, ossimImageGeometry* geom, ossim_uint32 xSamples=8, ossim_uint32 ySamples=8); /** * Similar to the other solve methods except that the final grid size is established * iteratively so that the error at the midpoints between grid nodes falls below tolerance. * The RPC is computed for the specified image bounds range only, not the full image. The * expectation here (when the imageBounds is less than the full valid image rect) is to * generate an RPC to accompany a subimage that will be written to disk. * @param imageBounds The AOI in image space for the RPC computation. * @param geom Represents the geometry of the input image * @param pixel_tolerance Maximum error in pixels (typically fraction of a pixel) to achieve. * @return true if solution converged below pixel tolerance. */ bool solve(const ossimDrect& aoiBounds, ossimImageGeometry* geom, const double& pixel_tolerance=0.5); /** * Performs iterative solve using the other solve method, but uses an image filename to * initialize, and computes RPC over entire image rect. */ bool solve(const ossimFilename& imageFilename, const double& pixel_tolerance=0.5); /** * takes associated image points and ground points * and solves the coefficents for the rational polynomial for * line and sample calculations from world points. * * Note: All data will be normalized between -1 and 1 for * numerical robustness. */ void solveCoefficients(const std::vector& imagePoints, const std::vector& groundControlPoints); /** * Fetches the solved-for RPC model. See note in header above on setting the image offset * if this model will be applied to a sub-image chip. */ const ossimRefPtr getRpcModel() const { return theRpcModel; } double getRmsError()const; double getMaxError()const; /** * @return ossimRefPtr * * @note one of the solve methods should have been called prior to this. */ ossimRefPtr getNitfRpcBTag() const; /** * Sets the image rect over which to compute the RPCs. The Resulting RPC will only be valid * over that range of image space. */ void setValidImageRect(const ossimIrect& imageRect); protected: virtual void solveInitialCoefficients(NEWMAT::ColumnVector& coeff, const std::vector& f, const std::vector& x, const std::vector& y, const std::vector& z)const; virtual void solveCoefficients(NEWMAT::ColumnVector& coeff, const std::vector& f, const std::vector& x, const std::vector& y, const std::vector& z)const; double eval(const std::vector& coeff, const double& x, const double& y, const double& z)const; void evalPoint(const ossimGpt& gpt, ossimDpt& ipt) const; /** * Inverts using the SVD method */ NEWMAT::Matrix invert(const NEWMAT::Matrix& m)const; void setupSystemOfEquations(NEWMAT::Matrix& equations, const NEWMAT::ColumnVector& f, const std::vector& x, const std::vector& y, const std::vector& z)const; void setupWeightMatrix(NEWMAT::DiagonalMatrix& result, // holds the resulting weights const NEWMAT::ColumnVector& coefficients, const NEWMAT::ColumnVector& f, const std::vector& x, const std::vector& y, const std::vector& z)const; bool theUseElevationFlag; bool theHeightAboveMSLFlag; ossim_float64 theMeanResidual; ossim_float64 theMaxResidual; ossimRefPtr theRefGeom; ossimRefPtr theRpcModel; }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimRsmModel.h000066400000000000000000000126001352751253100236110ustar00rootroot00000000000000//--- // File: ossimRsmModel.h //--- #ifndef ossimRsmModel_H #define ossimRsmModel_H 1 #include #include #include #include #include #include /** * @class ossimRsmModel */ class OSSIM_DLL ossimRsmModel : public ossimSensorModel { public: /** @brief default constructor */ ossimRsmModel(); /** @brief copy constructor */ ossimRsmModel( const ossimRsmModel& obj ); /** @brief assignment operator */ const ossimRsmModel& operator=( const ossimRsmModel& rhs ); /** * @brief worldToLineSample() * Overrides base class implementation. Directly computes line-sample from * the polynomials. */ virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; /** * @brief lineSampleToWorld() * Overrides base class pure virtual. Intersects DEM. */ virtual void lineSampleToWorld(const ossimDpt& image_point, ossimGpt& world_point) const; /** * @brief lineSampleHeightToWorld() * Overrides base class pure virtual. Height understood to be relative to * standard ellipsoid. */ virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const; /** * @brief imagingRay() * Overrides base class pure virtual. */ virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; virtual void updateModel(); virtual void initAdjustableParameters(); /** * @brief dup() * Returns pointer to a new instance, copy of this. */ virtual ossimObject* dup() const; inline virtual bool useForward()const {return false;} /** * @brief print() * Extends base-class implementation. Dumps contents of object to std::ostream. */ virtual std::ostream& print(std::ostream& out) const; /** * @brief saveState * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry * KWL files. Returns true if successful. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /** * @brief loadState * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry * KWL files. Returns true if successful. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); protected: /** * @brief Gets index into RSM Polynomial Coefficients(rsmpca) container * array for a given ground point. * * @param x Longitude in radians. * @param y Latitude, in radians. * @param z Height in meters. * @return Index into m_pca vector. */ ossim_uint32 getPcaIndex( const double& x, const double& y, const double& z ) const; /** * @brief Gets index into RSM Polynomial Coefficients(rsmpca) container * array for a given image point. * * @note (0,0) in ossim space is (0.5, 0.5) in rsm space. * * @param ipt Image line, sample. * * @param shiftPoint If true ipt is shifted +0.5 to go from ossim * space(0 is center of pixel) to RSM space(0 is upper left of pixel). * If false point is coming from rsm space and does not need to be shifted. * * @return Index into m_pca vector. */ ossim_uint32 getPcaIndex( const ossimDpt& ipt, bool shiftPoint ) const; /** * @brief Gets index into RSM Polynomial Coefficients(rsmpca) container * array for a given ground point. * * @param x Longitude in radians. * @param y Latitude, in radians. * @param z Height in meters. * @parma ipt Initialized by this. */ void lowOrderPolynomial( const double& x, const double& y, const double& z, ossimDpt& ipt ) const; double polynomial( const double& x, const double& y, const double& z, const ossim_uint32& maxx, const ossim_uint32& maxy, const ossim_uint32& maxz, std::vector pcf ) const; double dPoly_dLat( const double& x, const double& y, const double& z, const ossim_uint32& maxx, const ossim_uint32& maxy, const ossim_uint32& maxz, std::vector pcf) const; double dPoly_dLon( const double& x, const double& y, const double& z, const ossim_uint32& maxx, const ossim_uint32& maxy, const ossim_uint32& maxz, std::vector pcf ) const; double dPoly_dHgt( const double& x, const double& y, const double& z, const ossim_uint32& maxx, const ossim_uint32& maxy, const ossim_uint32& maxz, std::vector pcf ) const; /** * @brief Performs sanity check on key/required rsm data. * @return true on success, false on error. */ bool validate() const; /** @brief virtual destructor */ virtual ~ossimRsmModel(); ossimRsmida m_ida; ossimRsmpia m_pia; std::vector m_pca; TYPE_DATA }; // End: class ossimRsmModel #endif /* #ifndef ossimRsmModel_H */ ossim-Miami-2.9.1/include/ossim/projection/ossimSarModel.h000066400000000000000000000240011352751253100235730ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Base class for Synthetic Aperture Radar model. // // This model represents a standard model using relatively // generic support data based on the following references: // [1] Modern Photogrammetry; Mikhail, Bethel, & McGlone; // Sections 11.7-11.9 // [2] The Compendium of Controlled Extensions for NITFS // 21 Mar 2006, paragraph E.3.8, SAR MPDSR // //---------------------------------------------------------------------------- // $Id: ossimSarModel.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimSarModel_HEADER #define ossimSarModel_HEADER #include #include #include #include class ossimHgtRef; class OSSIM_DLL ossimSarModel : public ossimSensorModel { public: enum AcquisitionMode { UNKNOWN = 0, SCAN = 1, SPOT = 2 }; enum AdjustParamIndex { X_POS = 0, Y_POS, Z_POS, NUM_ADJUSTABLE_PARAMS // not an index }; /** @brief default constructor */ ossimSarModel(); /** * @brief Method to load or recreate the state of an ossimSarModel from * a keyword list. * * @param kwl Keyword list to load from. * @param prefix Prefix for keywords, like "image01.". * * @return true on success, false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @brief Method to save the state of this object to a keyword list. * * @param kwl Keyword list to save to. * @param prefix Prefix for keywords, like "image01.". * * @return true on success, false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /*! * Writes a template of geom keywords processed by loadState and saveState * to output stream. */ static void writeGeomTemplate(std::ostream& os); /*! * Returns pointer to a new instance, copy of this. */ virtual ossimObject* dup() const { return 0; } // TBR /** * @brief print method. */ virtual std::ostream& print(std::ostream& out) const; /** * @brief */ virtual void lineSampleToWorld(const ossimDpt& image_point, ossimGpt& world_point) const; virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& heightAboveEllipsoid, ossimGpt& worldPt) const; /** * METHOD: imagingRay(image_point, &ossimEcefRay) * Given an image point, returns a ray originating at the ARP position * and pointing towards the target's position in the Output * Plane. * This DOES NOT provide the conventional definition for an imaging ray * because the imaging locus for SAR is not a ray. * * It DOES provide a radius vector for the range/Doppler circle. */ virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; virtual double sensorAzimuth(const ossimDpt& image_point) const; /** * @brief Compute partials of range/Doppler WRT ground point * * @param parmIdx computational mode: * OBS_INIT, EVALUATE, P_WRT_X, P_WRT_X, P_WRT_X. * @param gpos Current ground point estimate. * @param h Not used. * * @return OBS_INT: n/a, EVALUATE: residuals, P_WRT_X/Y/Z: partials. */ virtual ossimDpt getForwardDeriv(int parmIdx, const ossimGpt& gpos, double h); /** * ossimOptimizableProjection */ inline virtual bool useForward() const { return false; //!image to ground faster } /** * @brief Compute other parameters & update the model. */ virtual void updateModel(); /*! * METHOD: getObsCovMat() * gives 2X2 covariance matrix of observations */ virtual ossimSensorModel::CovMatStatus getObsCovMat( const ossimDpt& ipos, NEWMAT::SymmetricMatrix& Cov); protected: /** @brief virtual destructor */ virtual ~ossimSarModel(); /*! * Assigns initial default values to adjustable parameters and related * members. */ void initAdjustableParameters(); /** * @brief Get ARP time for SPOT mode (constant time). */ virtual ossim_float64 getArpTime() const; /** * @brief Get ARP time for SCAN mode (varying time). * * @param imgPt The image coordinates. */ virtual ossim_float64 getArpTime(const ossimDpt& imgPt) const; /** * @brief Get ARP position for SPOT mode (constant time). */ virtual ossimEcefPoint getArpPos() const; /** * @brief Get ARP position for SCAN mode (varying time). */ virtual ossimEcefPoint getArpPos(const ossim_float64& time) const; /** * @brief Get ARP velocity for SPOT mode (constant time). */ virtual ossimEcefVector getArpVel() const; /** * @brief Get ARP velocity for SPOT mode (constant time). */ virtual ossimEcefVector getArpVel(const ossim_float64& time) const; /** * @brief Method to compute range & Doppler. * * @param pt ECF ground point coordinates. * @param arpPos ECF ARP position. * @param arpVel ECF ARP velocity. * @param range range. * @param arpVel Doppler. * * @return true on success, false on error. */ virtual bool computeRangeDoppler(const ossimEcefPoint& pt, const ossimEcefPoint& arpPos, const ossimEcefVector& arpVel, ossim_float64& range, ossim_float64& doppler) const; /** * @brief Method to compute image coordinates from output plane coordinates. * * @param opPt ECF output plane position of point. * @param imgPt image position of point. * * @return true on success, false on error. */ virtual bool computeImageFromOP(const ossimEcefPoint& opPt, ossimDpt& imgPt) const; /** * @brief Method to compute output plane coordinates from image coordinates. * * @param imgPt image position of point. * @param opPt ECF output plane position of point. * * @return true on success, false on error. */ virtual bool computeOPfromImage(const ossimDpt& imgPt, ossimEcefPoint& opPt) const; /** * @brief Method to project output plane coordinates to surface. * * @param opPt ECF output plane point coordinates. * @param range range. * @param arpVel Doppler. * @param arpPos ECF ARP position. * @param arpVel ECF ARP velocity. * @param hgtRef Height reference defining intersection surface. * @param ellPt ECF point coordinates. * * @return true on success, false on error. */ virtual bool projOPtoSurface(const ossimEcefPoint& opPt, const ossim_float64& range, const ossim_float64& doppler, const ossimEcefPoint& arpPos, const ossimEcefVector& arpVel, const ossimHgtRef* hgtRef, ossimEcefPoint& ellPt) const; /** * @brief Method to project ellipsoid coordinates to output plane. * * @param ellPt ECF ellipsoid position. * @param opPt ECF output plane position of point. * * @return true on success, false on error. */ virtual bool projEllipsoidToOP(const ossimEcefPoint& ellPt, ossimEcefPoint& opPt) const; /** * Returns the acquisition mode as a string. */ ossimString getAcquistionModeString() const; /** * @brief Sets the acquisition mode from string. * * @param mode The string representing mode. */ void setAcquisitionMode(const ossimString& mode); /** acquisition mode */ AcquisitionMode theAcquisitionMode; /** Output/Ground Reference Point (ORP) position */ ossimEcefPoint theOrpPosition; /** sample (x)/line(y) image coordinates of ORP */ ossimDpt theOrpCenter; /** output plane normal */ ossimEcefVector theOutputPlaneNormal; /** output plane x-axis */ ossimEcefVector theOutputPlaneXaxis; /** output impulse response */ ossim_float64 theOipr; /** pixel size */ ossim_float64 thePixelSize; /** Aperture Reference/Center Point (ARP) time in seconds. */ ossim_float64 theArpTime; /** * Aperture Reference Point (ARP) Polynomials. * Note: Size is derived dependent. */ std::vector theArpXPolCoeff; std::vector theArpYPolCoeff; std::vector theArpZPolCoeff; /** Time Coefficients. Note: Size is derived dependent. */ std::vector theTimeCoeff; /** * Other computed parameters */ /** Pixel spacing */ ossim_float64 thePixelSpacing; /** Output/slant plane unit vectors */ ossimEcefVector theOPX; ossimEcefVector theOPY; ossimEcefVector theOPZ; /** * Adjustment-related data used and set by getForwardDeriv */ /** Observations for current point */ ossim_float64 theObsRng; ossim_float64 theObsDop; ossim_float64 theObsTime; ossimEcefPoint theObsPosition; ossimEcefPoint theObsOP; ossimEcefPoint theObsArpPos; ossimEcefVector theObsArpVel; ossimEcefVector theObsArpVel_U; ossim_float64 theObsArpVel_Mag; /** Partials for current point */ ossim_float64 theParDopWRTaz; /** Adjustable parameters */ ossimEcefVector theLsrOffset; // meters TYPE_DATA }; #endif /* #ifndef ossimSarModel_HEADER */ ossim-Miami-2.9.1/include/ossim/projection/ossimSensorModel.h000066400000000000000000000335201352751253100243250ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimSensorModel.h // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // // DESCRIPTION: // Contains declaration of class ossimSensorModel. This is the base class to // all sensor model-related projections including replacement models such as // coarse grids and polynomial models. This base class supports adjustable // parameters for registration adjustment. // // Important note to sensor model implementors: In order to avoid a separate // set of "initial adjustable parameters," this design assumes ALL initial // values are 0. When designing the derived-class model, insure that the // adjustable parameters are 0-based. This applies to theAdjustableParams // array declared in this base class only. The derived classes can declare // their own adjstable params that are more descriptive and that can be // assigned an initial value that is non-zero, but that are linearly related // to the adjustable params of this class. In that case, the updateModel() // method will compute the derived-class's parameters based on // theAdjustableParams array, after an adjustment is made. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimSensorModel.h 23297 2015-05-05 20:32:16Z dburken $ #ifndef ossimSensorModel_HEADER #define ossimSensorModel_HEADER 1 #include #include #include #include #include #include #include #include /* for ossim::nan() */ #include #include #include #include #include class ossimKeywordlist; class ossimTieGptSet; /*!**************************************************************************** * * CLASS: ossimSensorModel * *****************************************************************************/ class OSSIMDLLEXPORT ossimSensorModel : public ossimProjection, public ossimOptimizableProjection, public ossimAdjustableParameterInterface { public: enum CovMatStatus { COV_INVALID = 0, COV_PARTIAL = 1, COV_FULL = 2 }; enum DeriveMode { OBS_INIT =-99, EVALUATE =-98, P_WRT_X = -1, P_WRT_Y = -2, P_WRT_Z = -3 }; /*! * CONSTRUCTORS: */ ossimSensorModel(); ossimSensorModel(const ossimSensorModel& copy_this); ossimSensorModel(const ossimKeywordlist& geom_kwl); /** @brief assignment operator */ const ossimSensorModel& operator=( const ossimSensorModel& rhs ); virtual ossimObject* getBaseObject(); virtual const ossimObject* getBaseObject()const; /*! * ACCESS METHODS: */ virtual ossimGpt origin() const {return theRefGndPt; } virtual ossimDpt getMetersPerPixel() const {return ossimDpt(fabs(theGSD.x), fabs(theGSD.y));} //! Returns the estimated Absolute horizontal position error (CE90) of the sensor model. virtual const double& getNominalPosError() const { return theNominalPosError; } //! Returns the estimated RELATIVE horizontal position error (CE90) of the sensor model. virtual const double& getRelativePosError() const { return theRelPosError; } //! Assigns the absolute image position error uncertainty (abs CE90) virtual void setNominalPosError(const double& ce90) { theNominalPosError = ce90; } //! Assigns the relative image position error uncertainty (rel CE90) virtual void setRelativePosError(const double& ce90) { theRelPosError = ce90; } /*! * Implementation of base-class pure virtual projection methods. These * methods may be overriden by derived classes if those have more efficient * schemes. The implementations here are iterative (relatively slow). Both * depend on calls to the pure virtual lineSampleHeightToWorld() method. */ virtual void lineSampleToWorld(const ossimDpt& image_point, ossimGpt& world_point) const; virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; /*! * METHOD: lineSampleHeightToWorld * This is the pure virtual that performs the actual work of projecting * the image point to the given elevation above Ellipsoid. */ virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& heightEllipsoid, ossimGpt& worldPt) const = 0; /*! * METHOD: imagingRay(image_point, &ossimEcefRay) * Given an image point, returns a ray originating at some arbitrarily high * point (ideally at the sensor position) and pointing towards the target. * Implemented here but should be overriden for more efficient solution. */ virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; /*! * METHOD: print() * Fulfills base-class pure virtual. Dumps contents of object to std::ostream. */ virtual std::ostream& print(std::ostream& out) const; /** * @brief Sets the center line sampe of the image. * * @param pt Image center point (x = sample, y = line). */ void setRefImgPt(const ossimDpt& pt); /** * @brief Sets the center latitude, longitude, height of the image. * * @param pt Image center point. */ void setRefGndPt(const ossimGpt& pt); void setImageRect(const ossimDrect& imageRect); void setGroundRect(const ossimGpt& ul, const ossimGpt& ur, const ossimGpt& lr, const ossimGpt& ll); /*! * METHOD: imageSize() * Returns the maximum line/sample rigorously defined by this model. */ ossimDpt imageSize() const { return theImageSize; } void setImageSize(const ossimDpt& size){theImageSize = size;} /*! * This is from the adjustable parameter interface. It is * called when a paraemter adjustment is made. */ virtual void adjustableParametersChanged() { updateModel(); } /*! * VIRTUAL METHOD: updateModel() * Following a change to the adjustable parameter set, this virtual * is called to permit instances to compute derived quantities after * parameter change. */ virtual void updateModel() {} /*! * METHODS: saveState, loadState * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry * KWL files. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /*! * METHOD: insideImage(image_point) * Returns true if the image_point lies inside the image rectangle. */ virtual bool insideImage(const ossimDpt& p) const { /* return( (p.u>=(0.0-FLT_EPSILON)) && */ /* (p.u<=(double)(theImageSize.u-(1-FLT_EPSILON))) && */ /* (p.v>=(0.0-FLT_EPSILON)) && */ /* (p.v<=(double)(theImageSize.v-(1-FLT_EPSILON))) ); */ // if it's close to the edge we will consider it inside the image // return theImageClipRect.pointWithin(p, 2.0); } /*! * STATIC METHOD: writeGeomTemplate(std::ostream) * Writes a template of keywords processed by loadState and saveState to * output stream. */ static void writeGeomTemplate(std::ostream& os); /*! * OPERATORS: */ virtual bool operator==(const ossimProjection& proj) const; //inline below //! Access methods: const ossimString& getImageID() const { return theImageID; } const ossimDrect& getImageClipRect() const { return theImageClipRect; } /*! * optimizableProjection implementation */ virtual ossim_uint32 degreesOfFreedom()const; inline virtual bool needsInitialState()const {return true;} virtual double optimizeFit(const ossimTieGptSet& tieSet, double* targetVariance=0); /*! * METHOD: getForwardDeriv() * gives forward() partial derivative regarding parameter parmIdx (>=0) * default implementation is centered finite difference * -should be reimplemented with formal derivative in child class */ virtual ossimDpt getForwardDeriv(int parmIdx, const ossimGpt& gpos, double hdelta=1e-11); /*! * METHOD: getInverseDeriv() * gives inverse() partial derivative regarding parameter parmIdx (>=0) * default implementation is centered finite difference * -should be reimplemented with formal derivative in child class */ virtual ossimGpt getInverseDeriv(int parmIdx, const ossimDpt& ipos, double hdelta=1e-11); /*! * METHOD: getObsCovMat() * @brief Gives 2X2 covariance matrix of observations */ virtual ossimSensorModel::CovMatStatus getObsCovMat( const ossimDpt& ipos, NEWMAT::SymmetricMatrix& Cov, const ossim_float64 defPointingSigma = 0.5) const; /** * @brief Implementation of pure virtual * ossimProjection::isAffectedByElevation method. * @return true. */ virtual bool isAffectedByElevation() const { return true; } /** * This method computes the ground sample distance(gsd) and sets class * attributes theGSD and theMeanGSD by doing a lineSampleHeightToWorld on * four points and calculating the distance from them. * * @return Nothing but throws ossimException on error. */ void computeGsd(); /** * @brief Extracts geometry info from a non-ossim key,value pair * to an ossim keyword list. * * @param key non-ossim-based input ossimString * @param value non-ossim-based input ossimString * @param geomKwl The keyword list to fill in. */ virtual bool getImageGeometry( const ossimString& /* key */, const ossimString& /* value */, ossimKeywordlist& /* geomKwl */ ) const { return false; } protected: virtual ~ossimSensorModel(); /*! * METHOD: extrapolate() * Extrapolates solutions for points outside of the image. The second * version accepts a height value -- if left at the default, the elevation * will be looked up via theElevation object. */ virtual ossimDpt extrapolate (const ossimGpt& gp) const; virtual ossimGpt extrapolate (const ossimDpt& ip, const double& height=ossim::nan()) const; /*! * METHOD: buildNormalEquation * builds linearized system (LMS equivalent) * A*dp = projResidue * * A: symetric matrix = tJ*J * dp: system parameter shift that we want to estimate * projResidue = tJ * residue * * t: transposition operator * J = jacobian of transform relative to parameters p, transform can be forward() or inverse() * jacobian is obtained via finite differences * residue can be image (2D) or ground residue(3D) * * TODO: use image/ground points covariance matrices */ void buildNormalEquation(const ossimTieGptSet& tieSet, NEWMAT::SymmetricMatrix& A, NEWMAT::ColumnVector& residue, NEWMAT::ColumnVector& projResidue, double pstep_scale); /*! * METHOD: getResidue() * returns ground opr image residue */ NEWMAT::ColumnVector getResidue(const ossimTieGptSet& tieSet); NEWMAT::ColumnVector solveLeastSquares(NEWMAT::SymmetricMatrix& A, NEWMAT::ColumnVector& r)const; /*! * stable invert stolen from ossimRpcSolver */ NEWMAT::Matrix invert(const NEWMAT::Matrix& m)const; ossimIpt theImageSize; // pixels /*! * Support sub-image of larger full image by maintaining offset to UL corner */ ossimDpt theSubImageOffset; // pixels ossimString theImageID; ossimString theSensorID; ossimDpt theGSD; // meters ossim_float64 theMeanGSD; // meters ossimGpt theRefGndPt; // should be image center ossimDpt theRefImgPt; // should be image center ossimPolygon theBoundGndPolygon; ossimDrect theImageClipRect; ossim_float64 theRelPosError; // meters, relative to other models in the set ossim_float64 theNominalPosError; // meters /** Partials for current point */ ossimDpt theParWRTx; ossimDpt theParWRTy; ossimDpt theParWRTz; /** Observations & residuals for current point */ ossimDpt theObs; ossimDpt theResid; /** * Used as an initial guess for iterative solutions and a guess for points outside the support * bounds. */ ossimRefPtr theSeedFunction; mutable bool theExtrapolateImageFlag; mutable bool theExtrapolateGroundFlag; TYPE_DATA }; //================= BEGIN INLINE DEFINITIONS ================================= //***************************************************************************** // OPERATOR == //***************************************************************************** inline bool ossimSensorModel::operator==(const ossimProjection& proj) const { // const ossimSensorModel* model // = PTR_CAST(ossimSensorModel, (const ossimProjection*) &proj); const ossimSensorModel* model = dynamic_cast( &proj ); if ( (!model) || (theSensorID != model->theSensorID) || (theImageID != model->theImageID) || (theSubImageOffset != model->theSubImageOffset) ) return false; return true; } #endif ossim-Miami-2.9.1/include/ossim/projection/ossimSensorModelFactory.h000066400000000000000000000042221352751253100256520ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // Description: Factory for all ossim sensor models. // //******************************************************************* // $Id: ossimSensorModelFactory.h 22862 2014-08-05 18:54:37Z dburken $ #ifndef ossimSensorModelFactory_HEADER #define ossimSensorModelFactory_HEADER #include class ossimProjection; class ossimString; class ossimFilename; class OSSIM_DLL ossimSensorModelFactory : public ossimProjectionFactoryBase { public: /*! * METHOD: instance() * For accessing static instance of concrete factory. */ static ossimSensorModelFactory* instance(); virtual ossimProjection* createProjection(const ossimFilename& filename, ossim_uint32 entryIdx)const; /*! * METHOD: create() * Attempts to create an instance of the Product given a Specifier or * keywordlist. Returns successfully constructed product or NULL. */ virtual ossimProjection* createProjection(const ossimString& spec) const; virtual ossimProjection* createProjection(const ossimKeywordlist& kwl, const char* prefix = 0) const; virtual ossimObject* createObject(const ossimString& typeName)const; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const; protected: // Hidden from use default constructor: ossimSensorModelFactory(){} bool isNitf(const ossimFilename& filename)const; bool isLandsat(const ossimFilename& filename)const; void findCoarseGrid(ossimFilename& result, const ossimFilename& geomFile)const; }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimSensorModelTuple.h000066400000000000000000000142511352751253100253370ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Base class for tuple-based ossimSensorModel metric operations. //---------------------------------------------------------------------------- // $Id: ossimSensorModelTuple.h 21806 2012-10-05 14:20:45Z dhicks $ #ifndef ossimSensorModelTuple_HEADER #define ossimSensorModelTuple_HEADER #include #include #include #include // Forward class declarations: class ossimEcefPoint; typedef std::vector DptSet_t; /** * Container class to hold computed rpc model inputs to the * ossimPositionQualityEvaluator constructor. These are stored for retrieval * purposes only and will only be initialized if the underlying sensor model * is an rpc. */ class OSSIM_DLL ossimRpcPqeInputs { public: ossimRpcPqeInputs(); ~ossimRpcPqeInputs(); ossim_float64 theRpcElevationAngle; // decimal degrees ossim_float64 theRpcAzimuthAngle; // decimal degrees ossim_float64 theRpcBiasError; ossim_float64 theRpcRandError; ossimColumnVector3d theSurfaceNormalVector; NEWMAT::Matrix theSurfaceCovMatrix; }; class OSSIM_DLL ossimSensorModelTuple { public: enum DeriveMode { OBS_INIT =-99, EVALUATE =-98, P_WRT_X = -1, P_WRT_Y = -2, P_WRT_Z = -3 }; enum IntersectStatus { OP_SUCCESS = 0, ERROR_PROP_FAIL = 1, OP_FAIL = 2 }; /** @brief default constructor */ ossimSensorModelTuple(); /** @brief virtual destructor */ ~ossimSensorModelTuple(); /** * @brief Method to add an image to the tuple. */ void addImage(ossimSensorModel* image); /** * @brief print method. */ std::ostream& print(std::ostream& out) const; /** * @brief Multi-image intersection method. * * @param obs Vector of image point observations. * @param pt Intersected ECF position of point. * @param covMat 3X3 ECF position covariance matrix [m]. * * @return true on success, false on error. */ ossimSensorModelTuple::IntersectStatus intersect( const DptSet_t obs, ossimEcefPoint& pt, NEWMAT::Matrix& covMat) const; /** * @brief Single-image/DEM intersection method. * * @param img Image set index of current image. * @param obs Image point observations. * @param pt Intersected ECF position of point. * @param covMat 3X3 ECF position covariance matrix [m]. * * @return true on success, false on error. */ ossimSensorModelTuple::IntersectStatus intersect( const ossim_int32& img, const ossimDpt& obs, ossimEcefPoint& pt, NEWMAT::Matrix& covMat); /** * @brief Single-image/height intersection method. * * @param img Image set index of current image. * @param obs Image point observations. * @param heightAboveEllipsoid Desired intersection height [m]. * @param pt Intersected ECF position of point. * @param covMat 3X3 ECF position covariance matrix [m]. * * @return true on success, false on error. * * @NOTE: This method's "const" qualifier was removed as it stores rpc * inputs to the pqe constructor for report purposes. */ ossimSensorModelTuple::IntersectStatus intersect( const ossim_int32& img, const ossimDpt& obs, const ossim_float64& heightAboveEllipsoid, ossimEcefPoint& pt, NEWMAT::Matrix& covMat); /** * @brief Set intersection surface accuracy method. * * @param surfCE90 90% CE [m]. * @param surfLE90 90% LE [m]. * * @return true on success, false on exception. * Entry of negative value(s) indicates "no DEM" error prop for RPC */ bool setIntersectionSurfaceAccuracy(const ossim_float64& surfCE90, const ossim_float64& surfLE90); /** @param obj Object to initialize with rpc pqe inputs. */ void getRpcPqeInputs(ossimRpcPqeInputs& obj) const; private: mutable std::vector > theImages; ossim_int32 theNumImages; ossim_float64 theSurfCE90; ossim_float64 theSurfLE90; bool theSurfAccSet; bool theSurfAccRepresentsNoDEM; /** * Rpc model only, container to capture pqe inputs for report purposes only. */ ossimRpcPqeInputs theRpcPqeInputs; /** * @brief Compute single image intersection covariance matrix. * * @param img Image set index of current image. * @param obs Image point observations. * @param ptG Current ground estimate. * @param cRefType Current height reference type. * @param covMat 3X3 ECF position covariance matrix. * * @return true on success, false on error. */ bool computeSingleInterCov(const ossim_int32& img, const ossimDpt& obs, const ossimGpt& ptG, HeightRefType_t cRefType, NEWMAT::Matrix& covMat); /** * @brief Get observation equation components. * * @param img Image set index of current image. * @param iter Current iteration. * @param obs Observations. * @param ptEst Current ground estimate. * @param resid Observation residuals. * @param B Matrix of partials of observations WRT X,Y,Z. * @param W Weight matrix of observations. * * @param img Image set index of current image. */ bool getGroundObsEqComponents(const ossim_int32 img, const ossimDpt& obs, const ossimGpt& ptEst, ossimDpt& resid, NEWMAT::Matrix& B, NEWMAT::SymmetricMatrix& W) const; NEWMAT::Matrix invert(const NEWMAT::Matrix& m) const; }; #endif /* #ifndef ossimSensorModelTuple_HEADER */ ossim-Miami-2.9.1/include/ossim/projection/ossimSinusoid.h000066400000000000000000000162741352751253100236770ustar00rootroot00000000000000#ifndef SINUSOID_H #define SINUSOID_H /***************************************************************************/ /* RSC IDENTIFIER: SINUSOIDAL * * ABSTRACT * * This component provides conversions between Geodetic coordinates * (latitude and longitude in radians) and Sinusoid projection coordinates * (easting and northing in meters). * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid value * is found, the error code is combined with the current error code using * the bitwise or. This combining allows multiple error codes to be * returned. The possible error codes are: * * SINU_NO_ERROR : No errors occurred in function * SINU_LAT_ERROR : Latitude outside of valid range * (-90 to 90 degrees) * SINU_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees) * SINU_EASTING_ERROR : Easting outside of valid range * (False_Easting +/- ~20,000,000 m, * depending on ellipsoid parameters) * SINU_NORTHING_ERROR : Northing outside of valid range * (False_Northing +/- ~10,000,000 m, * depending on ellipsoid parameters) * SINU_CENT_MER_ERROR : Origin longitude outside of valid range * (-180 to 360 degrees) * SINU_A_ERROR : Semi-major axis less than or equal to zero * SINU_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * * REUSE NOTES * * SINUSOIDAL is intended for reuse by any application that performs a * Sinusoid projection or its inverse. * * REFERENCES * * Further information on SINUSOIDAL can be found in the Reuse Manual. * * SINUSOIDAL originated from : U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * SINUSOIDAL has no restrictions. * * ENVIRONMENT * * SINUSOIDAL was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC, version 2.8.1 * 2. Windows 95 with MS Visual C++, version 6 * * MODIFICATIONS * * Date Description * ---- ----------- * 7-15-99 Original Code * */ /***************************************************************************/ /* * DEFINES */ #define SINU_NO_ERROR 0x0000 #define SINU_LAT_ERROR 0x0001 #define SINU_LON_ERROR 0x0002 #define SINU_EASTING_ERROR 0x0004 #define SINU_NORTHING_ERROR 0x0008 #define SINU_CENT_MER_ERROR 0x0020 #define SINU_A_ERROR 0x0040 #define SINU_INV_F_ERROR 0x0080 /***************************************************************************/ /* * FUNCTION PROTOTYPES * for SINUSOID.C */ /* ensure proper linkage to c++ programs */ #ifdef __cplusplus extern "C" { #endif long Set_Sinusoidal_Parameters(double a, double f, double Central_Meridian, double False_Easting, double False_Northing); /* * The function Set_Sinusoidal_Parameters receives the ellipsoid parameters and * Sinusoidal projcetion parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise SINU_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ void Get_Sinusoidal_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing); /* * The function Get_Sinusoidal_Parameters returns the current ellipsoid * parameters and Sinusoidal projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ long Convert_Geodetic_To_Sinusoidal (double Latitude, double Longitude, double *Easting, double *Northing); /* * The function Convert_Geodetic_To_Sinusoidal converts geodetic (latitude and * longitude) coordinates to Sinusoidal projection easting, and northing * coordinates, according to the current ellipsoid and Sinusoidal projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise SINU_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ long Convert_Sinusoidal_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude); /* * The function Convert_Sinusoidal_To_Geodetic converts Sinusoidal projection * easting and northing coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Sinusoida projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise SINU_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ #ifdef __cplusplus } #endif #endif /* SINUSOID_H */ ossim-Miami-2.9.1/include/ossim/projection/ossimSinusoidalProjection.h000066400000000000000000000175731352751253100262540ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // Calls Geotrans Sinusoidal projection code. //******************************************************************* // $Id: ossimSinusoidalProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimSinusoidalProjection_HEADER #define ossimSinusoidalProjection_HEADER #include class OSSIMDLLEXPORT ossimSinusoidalProjection : public ossimMapProjection { public: ossimSinusoidalProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(), const ossimGpt& origin = ossimGpt()); ossimSinusoidalProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, const double falseEasting, const double falseNorthing); ~ossimSinusoidalProjection(){} virtual ossimObject *dup()const{return new ossimSinusoidalProjection(*this);} virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const; virtual ossimDpt forward(const ossimGpt &latLon)const; virtual void update(); /*! * SetFalseEasting. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseEasting(double falseEasting); /*! * SetFalseNorthing. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseNorthing(double falseNorthing); /*! * Sets both false easting and northing values. The values are * expected to be in meters. * Update is then called so we can pre-compute paramters */ void setFalseEastingNorthing(double falseEasting, double falseNorthing); void setDefaults(); void setCentralMeridian(double centralMeridian); double getFalseEasting()const{return Sinu_False_Easting;} double getFalseNorthing()const{return Sinu_False_Northing;} /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Returns TRUE if principal parameters are within epsilon tolerance. virtual bool operator==(const ossimProjection& projection) const; private: //_______________________GEOTRANS________________________ mutable double Sinu_a; /* Semi-major axis of ellipsoid in meters */ mutable double Sinu_f; /* Flattening of ellipsoid */ mutable double es2; /* Eccentricity (0.08181919084262188000) squared */ mutable double es4; /* es2 * es2 */ mutable double es6; /* es4 * es2 */ mutable double c0; /* 1 - es2 / 4.0 - 3.0 * es4 / 64.0 - 5.0 * es6 / 256.0 */ mutable double c1; /* 3.0 * es2 / 8.0 + 3.0 * es4 / 32.0 + 45.0 * es6 / 1024.0 */ mutable double c2; /* 15.0 * es4 / 256.0 + 45.0 * es6 / 1024.0 */ mutable double c3; /* 35.0 * es6 / 3072.0 */ mutable double a0; /* 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0 */ mutable double a1; /* 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0 */ mutable double a2; /* 151.0 * e3 / 96.0 */ mutable double a3; /* 1097.0 * e4 / 512.0 */ /* Sinusoid projection Parameters */ mutable double Sinu_Origin_Long; /* Longitude of origin in radians */ mutable double Sinu_False_Northing; /* False northing in meters */ mutable double Sinu_False_Easting; /* False easting in meters */ /* Maximum variance for easting and northing values for WGS 84. */ mutable double Sinu_Max_Easting; mutable double Sinu_Min_Easting; mutable double Sinu_Delta_Northing; /*! * The function Set_Sinusoidal_Parameters receives the ellipsoid parameters and * Sinusoidal projcetion parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise SINU_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ long Set_Sinusoidal_Parameters(double a, double f, double Central_Meridian, double False_Easting, double False_Northing); /*! * The function Get_Sinusoidal_Parameters returns the current ellipsoid * parameters and Sinusoidal projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ void Get_Sinusoidal_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing)const; /*! * The function Convert_Geodetic_To_Sinusoidal converts geodetic (latitude and * longitude) coordinates to Sinusoidal projection easting, and northing * coordinates, according to the current ellipsoid and Sinusoidal projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise SINU_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ long Convert_Geodetic_To_Sinusoidal (double Latitude, double Longitude, double *Easting, double *Northing)const; /*! * The function Convert_Sinusoidal_To_Geodetic converts Sinusoidal projection * easting and northing coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Sinusoida projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise SINU_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ long Convert_Sinusoidal_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimSkyBoxLearSensor.h000066400000000000000000000065271352751253100253170ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // SkyBox //******************************************************************* // $Id$ #ifndef ossimSkyBoxLearSensor_HEADER #define ossimSkyBoxLearSensor_HEADER #include "ossimSensorModel.h" #include "ossimUtmProjection.h" #include class OSSIM_DLL ossimSkyBoxLearSensor : public ossimSensorModel { public: ossimSkyBoxLearSensor(); ossimSkyBoxLearSensor(const ossimSkyBoxLearSensor& src) :ossimSensorModel(src), m_air2Ned(src.m_air2Ned), m_ecef2Ned(src.m_ecef2Ned), m_ecef2NedInverse(src.m_ecef2NedInverse), m_roll(src.m_roll), m_pitch(src.m_pitch), m_yaw(src.m_yaw), m_principalPoint(src.m_principalPoint), // in meters m_pixelSize(src.m_pixelSize), // in meters m_focalLength(src.m_focalLength), // in meters m_ecefPlatformPosition(src.m_ecefPlatformPosition), m_platformPosition(src.m_platformPosition), m_platformPositionEllipsoid(src.m_platformPositionEllipsoid), m_fovIntrack(src.m_fovIntrack), m_fovCrossTrack(src.m_fovCrossTrack), m_adjustedPlatformPosition(src.m_adjustedPlatformPosition) { } virtual ossimObject* dup()const { return new ossimSkyBoxLearSensor(*this); } virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; virtual void lineSampeToWorld(const ossimDpt& image_point, ossimGpt& worldPoint) const; virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const; // virtual void worldToLineSample(const ossimGpt& world_point, // ossimDpt& image_point) const; virtual void updateModel(); void setRollPitchYaw(double r, double p, double y) { m_roll = r; m_pitch = p; m_yaw = y; } void setFocalLength(double value) { m_focalLength = value; } void setPlatformPosition(const ossimGpt& value) { m_platformPosition = value; m_ecefPlatformPosition = value; } void setPrincipalPoint(const ossimDpt& value) { m_principalPoint = value; } void setPixelSize(const ossimDpt& value) { m_pixelSize = value; } inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM) //TBC virtual void initAdjustableParameters(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: NEWMAT::Matrix m_air2Ned; NEWMAT::Matrix m_ecef2Ned; NEWMAT::Matrix m_ecef2NedInverse; double m_roll; double m_pitch; double m_yaw; ossimDpt m_principalPoint; // in meters ossimDpt m_pixelSize; // in meters double m_focalLength; // in meters ossimEcefPoint m_ecefPlatformPosition; ossimGpt m_platformPosition; ossimGpt m_platformPositionEllipsoid; double m_fovIntrack; double m_fovCrossTrack; ossimGpt m_adjustedPlatformPosition; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimSmacCallibrationSystem.h000066400000000000000000000124211352751253100265040ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Proecedure for compensation of aerial camera lens distortion // as computed by the Simultaneous Multiframe Analytical Calibration // (SMAC) System: // //******************************************************************* // $Id$ #ifndef ossimSmacCallibrationSystem_HEADER #define ossimSmacCallibrationSystem_HEADER #include /** * Proecedure for compensation of aerial camera lens distortion * as computed by the Simultaneous Multiframe Analytical Calibration * (SMAC) System: *
 *
 * TRANSLATION TO POINT OF SYMMETRY:
 *
 * All measured points (x0, y0) requiring a distortion correction must be first referenced to the principal point of
 * autocollimation (PPA) at (0,0) as are the calibrated fiducials. Once the measured points are in the PPA reference frame, they
 * then must be translated to the calibrated point of symmetry (POS), (Xp, Yp).
 *
 *     X = X0 - Xp
 *     Y = Y0 - Yp
 *
 * Once X and Y are found we need to obtain the radial distance R:
 *     R = sqrt(X^2 + Y^2)
 *
 * SYMMETRIC RADIAL DISTORTION: 
 * To compute the correction for the symmetric radial distortion (DXr, DYr)
 * 
 *     DXr = X(K'0 + K'1*R^2 + K'2*R^4 + K'3*R^6 + K'4*R^8);
 *     DXr = Y(K'0 + K'1*R^2 + K'2*R^4 + K'3*R^6 + K'4*R^8);
 *
 * DECENTERING DISTORTION:
 * To compute the correction for decentering distortion (DXd, DYd) of the measured point use
 * the coefficients of the decentering distortion (P1, .. P4) in the following formula
 *
 *     DXd = (1 + P3*R^2 + P4R^4)*(P1*(R^2 + 2*X^2) + 2*P2*X*Y)
 *     DYd = (1 + P3*R^2 + P4R^4)*(2P1*X*Y + P2*(R^2 + 2*Y^2))
 * 
 * FINAL CORRECTED COORDINATES: 
 * Adding the symmetric radial and decentering distortion corrections to the 
 * translation of the measured point results in a corrected final x and y-coordinate 
 * for the measured point (Xc, Yc).
 *
 *     Xc = X + DXr + DXd
 *     Yc = Y + DYr + DYd 
 *
*/ class OSSIM_DLL ossimSmacCallibrationSystem : public ossimLensDistortion { public: ossimSmacCallibrationSystem(const ossimDpt& callibratedCenter = ossimDpt(0.0, 0.0)) :ossimLensDistortion(callibratedCenter) { _symmetricRadialDistortionCoefficients[0] = 0; _symmetricRadialDistortionCoefficients[1] = 0; _symmetricRadialDistortionCoefficients[2] = 0; _symmetricRadialDistortionCoefficients[3] = 0; _symmetricRadialDistortionCoefficients[4] = 0; _decenteringDistortionCoefficients[0] = 0; _decenteringDistortionCoefficients[1] = 0; _decenteringDistortionCoefficients[2] = 0; _decenteringDistortionCoefficients[3] = 0; } ossimSmacCallibrationSystem(double k0, double k1, double k2, double k3, double k4, double p1, double p2, double p3, double p4, const ossimDpt& callibratedCenter = ossimDpt(0.0,0.0)) :ossimLensDistortion(callibratedCenter) { setSymmetricRadialDistortionCoefficients(k0, k1, k2, k3, k4); _decenteringDistortionCoefficients[0] = p1; _decenteringDistortionCoefficients[1] = p2; _decenteringDistortionCoefficients[2] = p3; _decenteringDistortionCoefficients[3] = p4; } ossimSmacCallibrationSystem(const ossimSmacCallibrationSystem& src) { std::copy(src._symmetricRadialDistortionCoefficients, src._symmetricRadialDistortionCoefficients+5, _symmetricRadialDistortionCoefficients); std::copy(src._decenteringDistortionCoefficients, src._decenteringDistortionCoefficients+4, _decenteringDistortionCoefficients); } virtual ossimObject* dup()const { return new ossimSmacCallibrationSystem(*this); } const double* symmetricRadialDistortionCoefficients()const { return _symmetricRadialDistortionCoefficients; } void setSymmetricRadialDistortionCoefficients(double k0, double k1, double k2, double k3, double k4) { _symmetricRadialDistortionCoefficients[0] = k0; _symmetricRadialDistortionCoefficients[1] = k1; _symmetricRadialDistortionCoefficients[2] = k2; _symmetricRadialDistortionCoefficients[3] = k3; _symmetricRadialDistortionCoefficients[4] = k4; } const double* decenteringDistortionCoefficients()const { return _decenteringDistortionCoefficients; } void setDecenteringDistortionCoefficients(double p1, double p2, double p3, double p4) { _decenteringDistortionCoefficients[0] = p1; _decenteringDistortionCoefficients[1] = p2; _decenteringDistortionCoefficients[2] = p3; _decenteringDistortionCoefficients[3] = p4; } const double* radialDistortionCoefficients()const { return _symmetricRadialDistortionCoefficients; } virtual void undistort(const ossimDpt& input, ossimDpt& output)const; static void test(); protected: /** * The coeeficients are arranged index 0..N-1 where 0 refers to * K'0 ... K'(n-1) */ double _symmetricRadialDistortionCoefficients[5]; /** * The coeeficients are arranged index 0..N-1 where 0 refers to * P1 ... PN */ double _decenteringDistortionCoefficients[4]; }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimSonomaSensor.h000066400000000000000000000150521352751253100245210ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Sonoma //******************************************************************* // $Id$ #ifndef ossimSonomaSensor_HEADER #define ossimSonomaSensor_HEADER #include "ossimSensorModel.h" #include "ossimUtmProjection.h" #include /******************************************************************************************* * * The Sonoma system uses an LN200 IMU. The orientation are euler angles of the form * RzRxRz (roll*pitch*heading) where roll and heading are defined about the Rz. The sonoma * software does their own camera callibration and appears to be a mtrix that goes from IMU * to boresite allignment and for the ossim intersections we need to invert * camera mount allignment matrix so we go from camer to IMU boresite allignment. * * Also talking with some contacts it appears that the intersections are done to a affine hyper plane * and the coordinates for the initial ray origin and direction are UTM where the zone and hemishpere * is initialized based on the platfrom position. Their height values are MSL and so I use * the geoid grid to shift to the ellipsoid. We have our own intersectRay that intersects a plane * plane equation. * * * The load state keywords are: * mount: * pitch: * heading: * platform_position: (0,0, 0,WGE) * pixel_size: (1,1) * focal_length: .02 * principal_point: (0,0) * rect: 0 0 4007 2671 * mount: 1.034918 -0.003693 0.309045 0.000000 -0.112617 1.064566 0.362789 0.000000 -0.269597 -0.391096 1.002515 0.000000 * sensor: Sonoma * type: ossimSonomaSensor * * * the mount is a orientation that we invert to go from camera to imu allignment. The roll pitch and heading are euler * angles in degrees. The pixel size and focal lengths were defined as meters and we kept the units here to be meter * units. The platform position is of the form (Lat, Lon, Height). We were not given any lens distortion measurments * and the mount orientation was calculated by the sonoma product and was not part of the IMU information. * *******************************************************************************************/ class OSSIM_DLL ossimSonomaSensor : public ossimSensorModel { public: ossimSonomaSensor(); ossimSonomaSensor(const ossimSonomaSensor& src) :ossimSensorModel(src), m_compositeMatrix(src.m_compositeMatrix), m_compositeMatrixInverse(src.m_compositeMatrixInverse), m_pixelToCamera(src.m_pixelToCamera), m_mount(src.m_mount), m_roll(src.m_roll), m_pitch(src.m_pitch), m_heading(src.m_heading), m_principalPoint(src.m_principalPoint), // in millimeters m_pixelSize(src.m_pixelSize), // in millimeters m_focalLength(src.m_focalLength), // in millimeters m_ecefPlatformPosition(src.m_ecefPlatformPosition), m_platformPosition(src.m_platformPosition), m_platformPositionEllipsoid(src.m_platformPositionEllipsoid) { } virtual ossimObject* dup()const { return new ossimSonomaSensor(*this); } virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const; void lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const; // virtual void worldToLineSample(const ossimGpt& world_point, // ossimDpt& image_point) const; virtual void updateModel(); void setRollPitchHeading(double r, double p, double y) { m_roll = r; m_pitch = p; m_heading = y; } void setFocalLength(double value) { m_focalLength = value; } void setPlatformPosition(const ossimGpt& value) { m_platformPosition = value; m_ecefPlatformPosition = value; } void setPrincipalPoint(const ossimDpt& value) { m_principalPoint = value; } void setPixelSize(const ossimDpt& value) { m_pixelSize = value; } inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM) //TBC virtual void initAdjustableParameters(); virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; protected: class ossimPlane { public: ossimPlane(double nx=0, double ny=0, double nz=1.0, double offset=1.0) :m_nx(nx), m_ny(ny), m_nz(nz), m_offset(offset) { } bool intersect(ossimDpt3d& result, ossimDpt3d& origin, ossimDpt3d& ray) { // P*N + D = 0; // solve for parametric t: // P = P0+t*ray // // (P0 + t*ray)*N + D = 0 // (P0*N + P0*ray*t + D = 0; // t = -(D + P0*N)/(N*ray) // if(t >= 0.0 then intersection double numerator = m_offset + origin.x*m_nx+origin.y*m_ny + origin.z*m_nz; double denominator = ray.z*m_nx + ray.y*m_ny + ray.z*m_nz; if(ossim::almostEqual(denominator, 0.0)) { return false; } double t = -numerator/denominator; result.x = origin.x + t*ray.x; result.y = origin.y + t*ray.y; result.z = origin.z + t*ray.z; return true; } void setOffset(double offset) { m_offset = offset; } protected: double m_nx,m_ny,m_nz; double m_offset; }; bool intersectRay(const ossimMapProjection& proj, ossimDpt3d& result, ossimDpt3d& origin, ossimDpt3d& dir)const; bool intersectRayWithHeight(const ossimMapProjection& proj, ossimDpt3d& result, ossimDpt3d& origin, ossimDpt3d& dir, double h)const; ossimRefPtr m_utmProjection; NEWMAT::Matrix m_compositeMatrix; NEWMAT::Matrix m_compositeMatrixInverse; NEWMAT::Matrix m_pixelToCamera; NEWMAT::Matrix m_mount; NEWMAT::Matrix m_mountInverse; double m_roll; double m_pitch; double m_heading; ossimDpt m_principalPoint; // in meters ossimDpt m_pixelSize; // in meters double m_focalLength; // in meters ossimEcefPoint m_ecefPlatformPosition; ossimGpt m_platformPosition; ossimGpt m_platformPositionEllipsoid; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimSpaceObliqueMercatorProjection.h000066400000000000000000000053421352751253100302020ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimSpaceObliqueMercatorProjection.h 20197 2011-11-03 13:22:02Z dburken $ #ifndef ossimSpaceObliqueMercatorProjection_HEADER #define ossimSpaceObliqueMercatorProjection_HEADER #include /*! * This class implments the formulas for the ellipsoid and * circular orbit. All formulas were directly taken from * proj 4. Proj 4 implementation is from the following * manual reference: * * Map Projections - A Working Manual * by John Snyder * Space Oblique Mercator p. 221. * * */ class OSSIMDLLEXPORT ossimSpaceObliqueMercatorProjection : public ossimMapProjection { public: enum ossimSatelliteType { SOM_TYPE_LANDSAT_1 = 0, SOM_TYPE_LANDSAT_2 = 1, SOM_TYPE_LANDSAT_3 = 2, SOM_TYPE_LANDSAT_4 = 3, SOM_TYPE_LANDSAT_5 = 4, SOM_TYPE_LANDSAT_7 = 5 }; ossimSpaceObliqueMercatorProjection(ossimSatelliteType type=SOM_TYPE_LANDSAT_7, double pathNumber=34, const ossimEllipsoid& ellipsoid = ossimEllipsoid()); virtual ossimObject* dup()const{return new ossimSpaceObliqueMercatorProjection(*this);} virtual ossimDpt forward(const ossimGpt &worldPoint) const; virtual ossimGpt inverse(const ossimDpt &projectedPoint)const; /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void setParameters(ossimSatelliteType type, double path); virtual void update(); //! Returns TRUE if principal parameters are within epsilon tolerance. virtual bool operator==(const ossimProjection& projection) const; protected: // proj 4 parameters that I bridge to. // double a2, a4, b, c1, c3; double q, t, u, w, p22, sa, ca, xj, rlm, rlm2; // proj4 stuff double lam0; double es; double e; double one_es; double rone_es; double a; void seraz0(double lam, double mult); /*! * Is the p variable in Map Projections a Working Manual. */ double thePath; ossimSatelliteType theSatelliteType; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimSpectraboticsRedEdgeModel.h000066400000000000000000000073071352751253100271050ustar00rootroot00000000000000#ifndef ossimSpectraboticsRedEdgeModel_HEADER #define ossimSpectraboticsRedEdgeModel_HEADER 1 #include #include #include #include #include class OSSIM_DLL ossimSpectraboticsRedEdgeModel : public ossimSensorModel { public: ossimSpectraboticsRedEdgeModel(); ossimSpectraboticsRedEdgeModel(const ossimDrect& imageRect, // center in image space const ossimGpt& platformPosition, double roll, double pitch, double heading, const ossimDpt& principalPoint, // in millimeters double focalLength, // in millimeters const ossimDpt& pixelSize); // in millimeters ossimSpectraboticsRedEdgeModel(const ossimSpectraboticsRedEdgeModel& src); virtual ossimObject* dup()const; virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; void lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const; virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const; virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; virtual void updateModel(); void setPrincipalPoint(ossimDpt principalPoint); virtual bool insideImage(const ossimDpt& p) const { /* return( (p.u>=(0.0-FLT_EPSILON)) && */ /* (p.u<=(double)(theImageSize.u-(1-FLT_EPSILON))) && */ /* (p.v>=(0.0-FLT_EPSILON)) && */ /* (p.v<=(double)(theImageSize.v-(1-FLT_EPSILON))) ); */ // if it's close to the edge we will consider it inside the image // return theImageClipRect.pointWithin(p, theImageClipRect.width()); } void setRollPitchHeading(double roll, double pitch, double heading); void setPixelSize(const ossimDpt& pixelSize); void setImageRect(const ossimDrect& rect); void setFocalLength(double focalLength); void setPlatformPosition(const ossimGpt& gpt); virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual void initAdjustableParameters(); /*! * ossimOptimizableProjection */ // inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM) inline virtual bool useForward()const {return false;} //!ground to image faster (you don't need DEM) virtual bool setupOptimizer(const ossimString& init_file); //!uses file path to init model protected: NEWMAT::Matrix m_compositeMatrix; NEWMAT::Matrix m_compositeMatrixInverse; double m_roll; double m_pitch; double m_heading; double m_fov; ossimDpt m_principalPoint; ossimDpt m_calibratedCenter; ossimDpt m_pixelSize; double m_focalLength; double m_norm; // for lens normalization double m_focalX; double m_focalY; ossimEcefPoint m_ecefPlatformPosition; ossimRefPtr m_lensDistortion; ossimEcefPoint m_adjEcefPlatformPosition; TYPE_DATA }; #endifossim-Miami-2.9.1/include/ossim/projection/ossimSpot5Model.h000066400000000000000000000114301352751253100240620ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // ossim port by David Burken // // Description: // // Contains declaration of class ossimSpot5Model. // //***************************************************************************** // $Id: ossimSpot5Model.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimSpot5Model_HEADER #define ossimSpot5Model_HEADER #include #include #include #include #include #include #include #include #include class ossimSpotDimapSupportData; class OSSIMDLLEXPORT ossimSpot5Model : public ossimSensorModel { public: /*! * CONSTRUCTORS: */ ossimSpot5Model(); ossimSpot5Model(ossimSpotDimapSupportData* sd); ossimSpot5Model(const ossimFilename& init_file); ossimSpot5Model(const ossimKeywordlist& geom_kwl); ossimSpot5Model(const ossimSpot5Model& rhs); virtual ~ossimSpot5Model(); enum AdjustParamIndex { ROLL_OFFSET = 0, PITCH_OFFSET, YAW_OFFSET, ROLL_RATE, PITCH_RATE, YAW_RATE, FOCAL_LEN_OFFSET, NUM_ADJUSTABLE_PARAMS // not an index }; /*! * Returns pointer to a new instance, copy of this. * Not implemented yet! Returns NULL... */ virtual ossimObject* dup() const; /*! * Extends base-class implementation. Dumps contents of object to std::ostream. */ virtual std::ostream& print(std::ostream& out) const; /*! * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry * KWL files. Returns true if successful. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=NULL); /*! * Writes a template of geom keywords processed by loadState and saveState * to output stream. */ static void writeGeomTemplate(std::ostream& os); /*! * Given an image point and height, initializes worldPoint. */ virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const ossim_float64& heightEllipsoid, ossimGpt& worldPoint) const; /*! * Given an image point, returns a ray originating at some arbitrarily high * point (ideally at the sensor position) and pointing towards the target. */ virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; /*! * Following a change to the adjustable parameter set, this virtual * is called to permit instances to compute derived quantities after * parameter change. */ virtual void updateModel(); /*! * ossimOptimizableProjection */ inline virtual bool useForward()const {return false;} //!image to ground faster virtual bool setupOptimizer(const ossimString& init_file); //!uses file path to init model bool initFromMetadata(ossimSpotDimapSupportData* sd); protected: /*! * Sets adjustables to default values. */ void initAdjustableParameters(); void loadGeometry(FILE*); void loadSupportData(); //void computeSatToOrbRotation(ossim_float64 t)const; void computeSatToOrbRotation(NEWMAT::Matrix& result, ossim_float64 t)const; /* virtual ossimDpt extrapolate (const ossimGpt& gp) const; */ /* virtual ossimGpt extrapolate (const ossimDpt& ip, */ /* const double& height=ossim::nan()) const; */ ossimRefPtr theSupportData; //--- // Image constant parameters: //--- ossimFilename theMetaDataFile; ossim_float64 theIllumAzimuth; ossim_float64 theIllumElevation; ossim_float64 thePositionError; ossim_float64 theRefImagingTime; /** relative to full image */ ossim_float64 theRefImagingTimeLine; ossim_float64 theLineSamplingPeriod; ossimDpt theSpotSubImageOffset; // mutable NEWMAT::Matrix theSatToOrbRotation; // mutable NEWMAT::Matrix theOrbToEcfRotation; //--- // Adjustable parameters: //--- ossim_float64 theRollOffset; // degrees ossim_float64 thePitchOffset; // degrees ossim_float64 theYawOffset; // degrees ossim_float64 theRollRate; // degrees/sec ossim_float64 thePitchRate; // degrees/sec ossim_float64 theYawRate; // degrees/sec ossim_float64 theFocalLenOffset; // percent deviation from nominal TYPE_DATA }; #endif /* #ifndef ossimSpot5Model_HEADER */ ossim-Miami-2.9.1/include/ossim/projection/ossimStatePlaneProjectionInfo.h000066400000000000000000000072551352751253100270120ustar00rootroot00000000000000//******************************************************************* // // License: See top LICENSE.txt file. // // Author: Garrett Potts //******************************************************************* // $Id: ossimStatePlaneProjectionInfo.h 23353 2015-06-01 19:19:10Z dburken $ #ifndef ossimStatePlaneProjectionInfo_HEADER #define ossimStatePlaneProjectionInfo_HEADER 1 #include /* for OSSIM_DLL macro */ #include #include #include #include class ossimDatum; class ossimMapProjection; class ossimKeywordlist; class OSSIM_DLL ossimStatePlaneProjectionInfo { friend OSSIM_DLL std::ostream& operator<<(std::ostream&, const ossimStatePlaneProjectionInfo&); public: ossimStatePlaneProjectionInfo(const std::string& name, int pcsCode, const std::string& projCode, const std::string& param1, const std::string& param2, const std::string& param3, const std::string& param4, double falseEast, double falseNorth, const std::string& units, const std::string& datumName); int code() const; const ossimString& name() const; const ossimString& projName() const; double originLat() const; double originLon() const; const ossimDatum* datum() const; ossimGpt origin() const; double parallel1() const; double parallel2() const; double falseEasting() const; double falseNorthing() const; double falseEastingInMeters() const; double falseNorthingInMeters() const; double scaleFactor() const; /** Not stored as string; hence, returned by value. */ ossimString units() const; /** * * @return ossimUnitType */ ossimUnitType getUnitType() const; /** * Checks parameters of projection against this. * * @return true if projection parameters match this, false if not. */ bool matchesProjection(const ossimMapProjection* proj) const; bool isSameCode( int Code ) const; void populateProjectionKeywords(ossimKeywordlist& kwl, const char* prefix=0)const; private: int thePcsCode; // The Geotiff code ossimString theName; // Descriptive PCS name /*! * ossimLambertConformalConicProjection or * ossimTransMercatorProjection */ ossimString theProjectionName; const ossimDatum* theDatum; // Either NAD83 or NAD27 based on name ossimDms theOriginLat; ossimDms theOriginLon; ossimGpt theOrigin; double theParameter3; // parallel 1 or Scale factor double theParameter4; // parallel 2 or 0 double theFalseEasting; double theFalseNorthing; double theScaleFactor; ossimUnitType theUnits; // "us_survey_ft" "feet" or "meters" }; #endif /* #ifndef ossimStatePlaneProjectionInfo_HEADER */ ossim-Miami-2.9.1/include/ossim/projection/ossimStereographicProjection.h000066400000000000000000000172231352751253100267310ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimStereographicProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimStereographicProjection_HEADER #define ossimStereographicProjection_HEADER #include class OSSIMDLLEXPORT ossimStereographicProjection : public ossimMapProjection { public: ossimStereographicProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(), const ossimGpt& origin = ossimGpt()); ossimStereographicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, const double falseEasting, const double falseNorthing); ~ossimStereographicProjection(){} virtual ossimObject *dup()const { return new ossimStereographicProjection(*this); } virtual void update(); virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const; virtual ossimDpt forward(const ossimGpt &latLon)const; /*! * SetFalseEasting. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseEasting(double falseEasting); /*! * SetFalseNorthing. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseNorthing(double falseNorthing); /*! * Sets both false easting and northing values. The values are * expected to be in meters. * Update is then called so we can pre-compute paramters */ void setFalseEastingNorthing(double falseEasting, double falseNorthing); void setDefaults(); double getFalseEasting()const{return Stereo_False_Easting;} double getFalseNorthing()const{return Stereo_False_Northing;} /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); private: /************************************************************************/ /* GLOBAL DECLARATIONS * */ /* Ellipsoid Parameters, default to WGS 84 */ mutable double Stereo_a; /* Semi-major axis of ellipsoid, in meters */ mutable double Stereo_f; /* Flattening of ellipsoid */ mutable double Stereo_Ra; /* Spherical Radius */ mutable double Two_Stereo_Ra; /* 2 * Spherical Radius */ mutable long Stereo_At_Pole; /* Flag variable */ /* Stereographic projection Parameters */ mutable double Stereo_Origin_Lat; /* Latitude of origin, in radians */ mutable double Stereo_Origin_Long; /* Longitude of origin, in radians */ mutable double Stereo_False_Easting; /* False easting, in meters */ mutable double Stereo_False_Northing; /* False northing, in meters */ mutable double Sin_Stereo_Origin_Lat; /* sin(Stereo_Origin_Lat) */ mutable double Cos_Stereo_Origin_Lat; /* cos(Stereo_Origin_Lat) */ /* Maximum variance for easting and northing values for WGS 84. */ mutable double Stereo_Delta_Easting; mutable double Stereo_Delta_Northing; /*! * The function Set_Stereographic_Parameters receives the ellipsoid * parameters and Stereograpic projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, error * code(s) are returned by the function, otherwise STEREO_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude, in radians, at the center of (input) * the projection * Central_Meridian : Longitude, in radians, at the center of (input) * the projection * False_Easting : Easting (X) at center of projection, in meters (input) * False_Northing : Northing (Y) at center of projection, in meters (input) */ long Set_Stereographic_Parameters (double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing); /*! * The function Get_Stereographic_Parameters returns the current ellipsoid * parameters and Stereographic projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude, in radians, at the center of (output) * the projection * Central_Meridian : Longitude, in radians, at the center of (output) * the projection * False_Easting : A coordinate value, in meters, assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value, in meters, assigned to the * origin latitude of the projection (output) */ void Get_Stereographic_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const; /*! * The function Convert_Geodetic_To_Stereographic converts geodetic * coordinates (latitude and longitude) to Stereographic coordinates * (easting and northing), according to the current ellipsoid * and Stereographic projection parameters. If any errors occur, error * code(s) are returned by the function, otherwise STEREO_NO_ERROR is returned. * * Latitude : Latitude, in radians (input) * Longitude : Longitude, in radians (input) * Easting : Easting (X), in meters (output) * Northing : Northing (Y), in meters (output) */ long Convert_Geodetic_To_Stereographic (double Latitude, double Longitude, double *Easting, double *Northing)const; /*! * The function Convert_Stereographic_To_Geodetic converts Stereographic projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Stereographic projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise STEREO_NO_ERROR is returned. * * Easting : Easting (X), in meters (input) * Northing : Northing (Y), in meters (input) * Latitude : Latitude (phi), in radians (output) * Longitude : Longitude (lambda), in radians (output) */ long Convert_Stereographic_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimTangentialRadialLensDistortion.h000066400000000000000000000042521352751253100301770ustar00rootroot00000000000000#ifndef ossimTangentialRadialLensDistortion_HEADER #define ossimTangentialRadialLensDistortion_HEADER 1 #include #include #include /*** This is taken from the site: http://www.mathworks.com/products/symbolic/code-examples.html?file=/products/demos/symbolictlbx/Pixel_location/Camera_Lens_Undistortion.html Developing an Algorithm to Undistort Pixel Locations of an Image This example uses Symbolic Math Toolbox to develop an algorithm that undistorts pixel locations of an image. Background When a camera captures an image, it does not precisely capture the real points, but rather a slightly distorted version of the real points that can be denoted (x2, y2). The distorted pixel locations can be described using the following equations: x2 = x1(1 + k1*r^2 + k2*r^4 + k3*r^6) +2*p1*x1*y1 + p2*(r^2 + 2*x1^2) y2 = y1(1 + k1*r^2 + k2*r^4 + k3*r^6) +2*p2*x1*y1 + p1*(r^2 + 2*y1^2) where: x1, y2 = undistorted pixel locations k1, k2, k3 = radial distortion coefficients of the lens p1, p2 = tangential distortion coefficients of the lens r = sqrt(x1^2 + y1^2) ***/ class ossimTangentialRadialLensDistortion : public ossimLensDistortion { public: ossimTangentialRadialLensDistortion(); ossimTangentialRadialLensDistortion(const ossimDpt& calibratedCenter, double k1 = 0.0, double k2 = 0.0, double k3 = 0.0, double p1 = 0.0, double p2 = 0.0); ossimTangentialRadialLensDistortion(const ossimDpt& calibratedCenter, std::vector k, std::vector p); // ossimDpt adjustPoint(const ossimDpt &position)const; virtual std::ostream& print(std::ostream& out) const {return out;} virtual void undistort(const ossimDpt& input, ossimDpt& output)const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); protected: std::vector m_k; std::vector m_p; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimTiffProjectionFactory.h000066400000000000000000000044111352751253100263450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // class ossimProjectionFactory maintains a static list of projection // makers. If a user wants to create a projection they can pass in // a projection name and a datum if desired. Currently the default // datum will be WGS84. //******************************************************************* // $Id: ossimTiffProjectionFactory.h 23440 2015-07-16 19:41:16Z dburken $ #ifndef ossimTiffProjectionFactory_HEADER #define ossimTiffProjectionFactory_HEADER 1 #include #include class ossimProjection; class ossimString; class OSSIM_DLL ossimTiffProjectionFactory : public ossimProjectionFactoryBase { public: /*! * METHOD: instance() * Instantiates singleton instance of this class: */ static ossimTiffProjectionFactory* instance(); virtual ossimProjection* createProjection(const ossimFilename& filename, ossim_uint32 entryIdx)const; /*! * METHOD: create() * Attempts to create an instance of the projection specified by name. * Returns successfully constructed projection or NULL. */ virtual ossimProjection* createProjection(const ossimString& name)const; virtual ossimProjection* createProjection(const ossimKeywordlist& kwl, const char* prefix = 0)const; ossimProjection* createProjection(ossimImageHandler* handler)const; virtual ossimObject* createObject(const ossimString& typeName)const; /*! * Creates and object given a keyword list. */ virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; /*! * This should return the type name of all objects in all factories. * This is the name used to construct the objects dynamially and this * name must be unique. */ virtual void getTypeNameList(std::vector& typeList)const; protected: ossimTiffProjectionFactory() {} static ossimTiffProjectionFactory* theInstance; bool isTiff(const ossimFilename& filename)const; }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimTranmerc.h000066400000000000000000000210611352751253100236430ustar00rootroot00000000000000#ifndef TRANMERC_H #define TRANMERC_H /***************************************************************************/ /* RSC IDENTIFIER: TRANSVERSE MERCATOR * * ABSTRACT * * This component provides conversions between Geodetic coordinates * (latitude and longitude) and Transverse Mercator projection coordinates * (easting and northing). * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid value * is found the error code is combined with the current error code using * the bitwise or. This combining allows multiple error codes to be * returned. The possible error codes are: * * TRANMERC_NO_ERROR : No errors occurred in function * TRANMERC_LAT_ERROR : Latitude outside of valid range * (-90 to 90 degrees) * TRANMERC_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees, and within * +/-90 of Central Meridian) * TRANMERC_EASTING_ERROR : Easting outside of valid range * (depending on ellipsoid and * projection parameters) * TRANMERC_NORTHING_ERROR : Northing outside of valid range * (depending on ellipsoid and * projection parameters) * TRANMERC_ORIGIN_LAT_ERROR : Origin latitude outside of valid range * (-90 to 90 degrees) * TRANMERC_CENT_MER_ERROR : Central meridian outside of valid range * (-180 to 360 degrees) * TRANMERC_A_ERROR : Semi-major axis less than or equal to zero * TRANMERC_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * TRANMERC_SCALE_FACTOR_ERROR : Scale factor outside of valid * range (0.3 to 3.0) * TM_LON_WARNING : Distortion will result if longitude is more * than 9 degrees from the Central Meridian * * REUSE NOTES * * TRANSVERSE MERCATOR is intended for reuse by any application that * performs a Transverse Mercator projection or its inverse. * * REFERENCES * * Further information on TRANSVERSE MERCATOR can be found in the * Reuse Manual. * * TRANSVERSE MERCATOR originated from : * U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * TRANSVERSE MERCATOR has no restrictions. * * ENVIRONMENT * * TRANSVERSE MERCATOR was tested and certified in the following * environments: * * 1. Solaris 2.5 with GCC, version 2.8.1 * 2. Windows 95 with MS Visual C++, version 6 * * MODIFICATIONS * * Date Description * ---- ----------- * 10-02-97 Original Code * 03-02-97 Re-engineered Code * */ /***************************************************************************/ /* * DEFINES */ #define TRANMERC_NO_ERROR 0x0000 #define TRANMERC_LAT_ERROR 0x0001 #define TRANMERC_LON_ERROR 0x0002 #define TRANMERC_EASTING_ERROR 0x0004 #define TRANMERC_NORTHING_ERROR 0x0008 #define TRANMERC_ORIGIN_LAT_ERROR 0x0010 #define TRANMERC_CENT_MER_ERROR 0x0020 #define TRANMERC_A_ERROR 0x0040 #define TRANMERC_INV_F_ERROR 0x0080 #define TRANMERC_SCALE_FACTOR_ERROR 0x0100 #define TRANMERC_LON_WARNING 0x0200 /***************************************************************************/ /* * FUNCTION PROTOTYPES * for TRANMERC.C */ /* ensure proper linkage to c++ programs */ #ifdef __cplusplus extern "C" { #endif long Set_Transverse_Mercator_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing, double Scale_Factor); /* * The function Set_Tranverse_Mercator_Parameters receives the ellipsoid * parameters and Tranverse Mercator projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, the error * code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at the origin of the (input) * projection * Central_Meridian : Longitude in radians at the center of the (input) * projection * False_Easting : Easting/X at the center of the projection (input) * False_Northing : Northing/Y at the center of the projection (input) * Scale_Factor : Projection scale factor (input) */ void Get_Transverse_Mercator_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing, double *Scale_Factor); /* * The function Get_Transverse_Mercator_Parameters returns the current * ellipsoid and Transverse Mercator projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at the origin of the (output) * projection * Central_Meridian : Longitude in radians at the center of the (output) * projection * False_Easting : Easting/X at the center of the projection (output) * False_Northing : Northing/Y at the center of the projection (output) * Scale_Factor : Projection scale factor (output) */ long Convert_Geodetic_To_Transverse_Mercator (double Latitude, double Longitude, double *Easting, double *Northing); /* * The function Convert_Geodetic_To_Transverse_Mercator converts geodetic * (latitude and longitude) coordinates to Transverse Mercator projection * (easting and northing) coordinates, according to the current ellipsoid * and Transverse Mercator projection coordinates. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ long Convert_Transverse_Mercator_To_Geodetic (double Easting, double Northing, double *Latitude, double *Longitude); /* * The function Convert_Transverse_Mercator_To_Geodetic converts Transverse * Mercator projection (easting and northing) coordinates to geodetic * (latitude and longitude) coordinates, according to the current ellipsoid * and Transverse Mercator projection parameters. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ #ifdef __cplusplus } #endif #endif /* TRANMERC_H */ ossim-Miami-2.9.1/include/ossim/projection/ossimTransCylEquAreaProjection.h000066400000000000000000000237631352751253100271430ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // Calls Geotrans Transverse Cylindrical Equal Area // projection code. //******************************************************************* // $Id: ossimTransCylEquAreaProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimTransCylEquAreaProjection_HEADER #define ossimTransCylEquAreaProjection_HEADER #include class OSSIMDLLEXPORT ossimTransCylEquAreaProjection : public ossimMapProjection { public: ossimTransCylEquAreaProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(6378137, 6356752.3142), const ossimGpt& origin = ossimGpt()); ossimTransCylEquAreaProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing, double scaleFactor); ~ossimTransCylEquAreaProjection(){} virtual ossimObject *dup()const{return new ossimTransCylEquAreaProjection(*this);} virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const; virtual ossimDpt forward(const ossimGpt &latLon)const; virtual void update(); /*! * SetFalseEasting. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseEasting(double falseEasting); /*! * SetFalseNorthing. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseNorthing(double falseNorthing); /* * Set's scale and then update. */ void setScaleFactor(double scaleFactor); /*! * Sets both false easting and northing values. The values are * expected to be in meters. * Update is then called so we can pre-compute paramters */ void setFalseEastingNorthing(double falseEasting, double falseNorthing); void setParameters(double falseEasting, double falseNorthing, double scaleFactor); void setDefaults(); double getFalseEasting()const{return Tcea_False_Easting;} double getFalseNorthing()const{return Tcea_False_Northing;} double getScaleFactor()const{return Tcea_Scale_Factor;} /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Returns TRUE if principal parameters are within epsilon tolerance. virtual bool operator==(const ossimProjection& projection) const; private: mutable double Tcea_a; /* Semi-major axis of ellipsoid in meters */ mutable double Tcea_f; /* Flattening of ellipsoid */ mutable double es2; /* Eccentricity (0.08181919084262188000) squared */ mutable double es4; /* es2 * es2 */ mutable double es6; /* es4 * es2 */ mutable double es; /* sqrt(es2) */ mutable double M0; mutable double qp; mutable double One_MINUS_es2; /* 1.0 - es2 */ mutable double One_OVER_2es; /* 1.0 / (2.0 * es) */ mutable double a0; /* es2 / 3.0 + 31.0 * es4 / 180.0 + 517.0 * es6 / 5040.0 */ mutable double a1; /* 23.0 * es4 / 360.0 + 251.0 * es6 / 3780.0 */ mutable double a2; /* 761.0 * es6 / 45360.0 */ mutable double b0; /* 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0 */ mutable double b1; /* 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0 */ mutable double b2; /* 151.0 * e3 / 96.0 */ mutable double b3; /* 1097.0 * e4 / 512.0 */ mutable double c0;/* 1.0 - es2 / 4.0 - 3.0 * es4 / 64.0 - 5.0 * es6 / 256.0 */ mutable double c1;/* 3.0 * es2 / 8.0 + 3.0 * es4 / 32.0 + 45.0 * es6 / 1024.0 */ mutable double c2; /* 15.0 * es4 / 256.0 + 45.0 * es6 / 1024.0 */ mutable double c3; /* 35.0 * es6 / 3072.0 */ /* Transverse Cylindrical Equal Area projection Parameters */ mutable double Tcea_Origin_Lat; /* Latitude of origin in radians */ mutable double Tcea_Origin_Long; /* Longitude of origin in radians */ mutable double Tcea_False_Northing; /* False northing in meters */ mutable double Tcea_False_Easting; /* False easting in meters */ mutable double Tcea_Scale_Factor; /* Scale factor */ /* Maximum variance for easting and northing values for WGS 84. */ mutable double Tcea_Min_Easting; mutable double Tcea_Max_Easting; mutable double Tcea_Min_Northing; mutable double Tcea_Max_Northing; /* * The function Set_Trans_Cyl_Eq_Area_Parameters receives the ellipsoid parameters and * Transverse Cylindrical Equal Area projcetion parameters as inputs, and sets the corresponding * state variables. If any errors occur, the error code(s) are returned by the function, * otherwise TCEA_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) * Scale_Factor : Multiplier which reduces distances in the * projection to the actual distance on the * ellipsoid (input) */ long Set_Trans_Cyl_Eq_Area_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing, double Scale_Factor); /*! * The function Get_Trans_Cyl_Eq_Area_Parameters returns the current ellipsoid * parameters, Transverse Cylindrical Equal Area projection parameters, and scale factor. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) * Scale_Factor : Multiplier which reduces distances in the * projection to the actual distance on the * ellipsoid (output) */ void Get_Trans_Cyl_Eq_Area_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing, double *Scale_Factor)const; /*! * The function Convert_Geodetic_To_Trans_Cyl_Eq_Area converts geodetic (latitude and * longitude) coordinates to Transverse Cylindrical Equal Area projection easting, and northing * coordinates, according to the current ellipsoid and Transverse Cylindrical Equal Area projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise TCEA_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ long Convert_Geodetic_To_Trans_Cyl_Eq_Area (double Latitude, double Longitude, double *Easting, double *Northing)const; /*! * The function Convert_Trans_Cyl_Eq_Area_To_Geodetic converts Transverse Cylindrical Equal Area * projection easting and northing coordinates to geodetic (latitude and longitude) coordinates. * coordinates, according to the current ellipsoid and Transverse Cylindrical Equal Area projection * If any errors occur, the error code(s) are returned by the function, otherwise TCEA_NO_ERROR * is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ long Convert_Trans_Cyl_Eq_Area_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimTransMercatorProjection.h000066400000000000000000000210571352751253100267160ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // Calls Geotrans Transverse Mercator projection code. //******************************************************************* // $Id: ossimTransMercatorProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimTransMercatorProjection_HEADER #define ossimTransMercatorProjection_HEADER #include class OSSIMDLLEXPORT ossimTransMercatorProjection : public ossimMapProjection { public: ossimTransMercatorProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(6378137, 6356752.3142), const ossimGpt& origin = ossimGpt()); ossimTransMercatorProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing, double scaleFactor); ~ossimTransMercatorProjection(){} virtual ossimObject *dup()const{return new ossimTransMercatorProjection(*this);} virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const; virtual ossimDpt forward(const ossimGpt &latLon)const; virtual void update(); /*! * SetFalseEasting. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseEasting(double falseEasting); /*! * SetFalseNorthing. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseNorthing(double falseNorthing); /* * Set's scale and then update. */ void setScaleFactor(double scaleFactor); /*! * Sets both false easting and northing values. The values are * expected to be in meters. * Update is then called so we can pre-compute paramters */ void setFalseEastingNorthing(double falseEasting, double falseNorthing); void setParameters(double falseEasting, double falseNorthing, double scaleFactor); void setDefaults(); double getFalseEasting()const{return TranMerc_False_Easting;} double getFalseNorthing()const{return TranMerc_False_Northing;} double getScaleFactor()const{return TranMerc_Scale_Factor;} /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /*! * Prints data members to stream. Returns stream&. */ virtual std::ostream& print(std::ostream& out) const; //! Returns TRUE if principal parameters are within epsilon tolerance. virtual bool operator==(const ossimProjection& projection) const; protected: //_____________GEOTRANS_______________ double TranMerc_a; /* Semi-major axis of ellipsoid i meters */ double TranMerc_f; /* Flattening of ellipsoid */ double TranMerc_es; /* Eccentricity (0.08181919084262188000) squared */ double TranMerc_ebs; /* Second Eccentricity squared */ /* Transverse_Mercator projection Parameters */ double TranMerc_Origin_Lat; /* Latitude of origin in radians */ double TranMerc_Origin_Long; /* Longitude of origin in radians */ double TranMerc_False_Northing; /* False northing in meters */ double TranMerc_False_Easting; /* False easting in meters */ double TranMerc_Scale_Factor; /* Scale factor */ /* Isometeric to geodetic latitude parameters, default to WGS 84 */ double TranMerc_ap; double TranMerc_bp; double TranMerc_cp; double TranMerc_dp; double TranMerc_ep; /* Maximum variance for easting and northing values for WGS 84. */ double TranMerc_Delta_Easting; double TranMerc_Delta_Northing; /*! * The function Set_Tranverse_Mercator_Parameters receives the ellipsoid * parameters and Tranverse Mercator projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, the error * code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at the origin of the (input) * projection * Central_Meridian : Longitude in radians at the center of the (input) * projection * False_Easting : Easting/X at the center of the projection (input) * False_Northing : Northing/Y at the center of the projection (input) * Scale_Factor : Projection scale factor (input) */ long Set_Transverse_Mercator_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing, double Scale_Factor); /*! * The function Get_Transverse_Mercator_Parameters returns the current * ellipsoid and Transverse Mercator projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at the origin of the (output) * projection * Central_Meridian : Longitude in radians at the center of the (output) * projection * False_Easting : Easting/X at the center of the projection (output) * False_Northing : Northing/Y at the center of the projection (output) * Scale_Factor : Projection scale factor (output) */ void Get_Transverse_Mercator_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing, double *Scale_Factor)const; /*! * The function Convert_Geodetic_To_Transverse_Mercator converts geodetic * (latitude and longitude) coordinates to Transverse Mercator projection * (easting and northing) coordinates, according to the current ellipsoid * and Transverse Mercator projection coordinates. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ long Convert_Geodetic_To_Transverse_Mercator (double Latitude, double Longitude, double *Easting, double *Northing)const; /*! * The function Convert_Transverse_Mercator_To_Geodetic converts Transverse * Mercator projection (easting and northing) coordinates to geodetic * (latitude and longitude) coordinates, according to the current ellipsoid * and Transverse Mercator projection parameters. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ long Convert_Transverse_Mercator_To_Geodetic (double Easting, double Northing, double *Latitude, double *Longitude)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimUps.h000066400000000000000000000134471352751253100226500ustar00rootroot00000000000000#ifndef UPS_H #define UPS_H /********************************************************************/ /* RSC IDENTIFIER: UPS * * * ABSTRACT * * This component provides conversions between geodetic (latitude * and longitude) coordinates and Universal Polar Stereographic (UPS) * projection (hemisphere, easting, and northing) coordinates. * * * ERROR HANDLING * * This component checks parameters for valid values. If an * invalid value is found the error code is combined with the * current error code using the bitwise or. This combining allows * multiple error codes to be returned. The possible error codes * are: * * UPS_NO_ERROR : No errors occurred in function * UPS_LAT_ERROR : Latitude outside of valid range * (North Pole: 83.5 to 90, * South Pole: -79.5 to -90) * UPS_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees) * UPS_HEMISPHERE_ERROR : Invalid hemisphere ('N' or 'S') * UPS_EASTING_ERROR : Easting outside of valid range, * (0 to 4,000,000m) * UPS_NORTHING_ERROR : Northing outside of valid range, * (0 to 4,000,000m) * UPS_A_ERROR : Semi-major axis less than or equal to zero * UPS_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * * * REUSE NOTES * * UPS is intended for reuse by any application that performs a Universal * Polar Stereographic (UPS) projection. * * * REFERENCES * * Further information on UPS can be found in the Reuse Manual. * * UPS originated from : U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * * LICENSES * * None apply to this component. * * * RESTRICTIONS * * UPS has no restrictions. * * * ENVIRONMENT * * UPS was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC version 2.8.1 * 2. Windows 95 with MS Visual C++ version 6 * * * MODIFICATIONS * * Date Description * ---- ----------- * 06-11-95 Original Code * 03-01-97 Original Code * * */ /**********************************************************************/ /* * DEFINES */ #define UPS_NO_ERROR 0x0000 #define UPS_LAT_ERROR 0x0001 #define UPS_LON_ERROR 0x0002 #define UPS_HEMISPHERE_ERROR 0x0004 #define UPS_EASTING_ERROR 0x0008 #define UPS_NORTHING_ERROR 0x0010 #define UPS_A_ERROR 0x0020 #define UPS_INV_F_ERROR 0x0040 /**********************************************************************/ /* * FUNCTION PROTOTYPES * for UPS.C */ /* ensure proper linkage to c++ programs */ #ifdef __cplusplus extern "C" { #endif long Set_UPS_Parameters( double a, double f); /* * The function SET_UPS_PARAMETERS receives the ellipsoid parameters and sets * the corresponding state variables. If any errors occur, the error code(s) * are returned by the function, otherwise UPS_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid in meters (input) * f : Flattening of ellipsoid (input) */ void Get_UPS_Parameters( double *a, double *f); /* * The function Get_UPS_Parameters returns the current ellipsoid parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) */ long Convert_Geodetic_To_UPS ( double Latitude, double Longitude, char *Hemisphere, double *Easting, double *Northing); /* * The function Convert_Geodetic_To_UPS converts geodetic (latitude and * longitude) coordinates to UPS (hemisphere, easting, and northing) * coordinates, according to the current ellipsoid parameters. If any * errors occur, the error code(s) are returned by the function, * otherwide UPS_NO_ERROR is returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Hemisphere : Hemisphere either 'N' or 'S' (output) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ long Convert_UPS_To_Geodetic(char Hemisphere, double Easting, double Northing, double *Latitude, double *Longitude); /* * The function Convert_UPS_To_Geodetic converts UPS (hemisphere, easting, * and northing) coordinates to geodetic (latitude and longitude) coordinates * according to the current ellipsoid parameters. If any errors occur, the * error code(s) are returned by the function, otherwise UPS_NO_ERROR is * returned. * * Hemisphere : Hemisphere either 'N' or 'S' (input) * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ #ifdef __cplusplus } #endif #endif /* UPS_H */ ossim-Miami-2.9.1/include/ossim/projection/ossimUpsProjection.h000066400000000000000000000114411352751253100246750ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimUpsProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimUpsProjection_HEADER #define ossimUpsProjection_HEADER #include class OSSIMDLLEXPORT ossimUpsProjection : public ossimMapProjection { public: ossimUpsProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(), const ossimGpt& origin = ossimGpt()); virtual ossimObject *dup()const{return new ossimUpsProjection(*this);} void setDefaults(); virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const; virtual ossimDpt forward(const ossimGpt &latLon)const; virtual void update(); /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); double getFalseEasting()const{return UPS_False_Easting;} double getFalseNorthing()const{return UPS_False_Northing;} void setHemisphere(char hemisphere); //! Returns TRUE if principal parameters are within epsilon tolerance. virtual bool operator==(const ossimProjection& projection) const; protected: mutable char theHemisphere; //___________________GEOTRANS__________________ // mutable double UPS_a; /* Semi-major axis of ellipsoid in meters */ mutable double UPS_f; /* Flattening of ellipsoid */ mutable double UPS_Origin_Latitude; /*set default = North Hemisphere */ mutable double UPS_Origin_Longitude; mutable double false_easting; mutable double false_northing; mutable double UPS_Easting; mutable double UPS_Northing; double UPS_False_Easting; double UPS_False_Northing; /*! * The function SET_UPS_PARAMETERS receives the ellipsoid parameters and sets * the corresponding state variables. If any errors occur, the error code(s) * are returned by the function, otherwise UPS_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid in meters (input) * f : Flattening of ellipsoid (input) */ long Set_UPS_Parameters( double a, double f); /*! * The function Get_UPS_Parameters returns the current ellipsoid parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) */ void Get_UPS_Parameters( double *a, double *f)const; /*! * The function Convert_Geodetic_To_UPS converts geodetic (latitude and * longitude) coordinates to UPS (hemisphere, easting, and northing) * coordinates, according to the current ellipsoid parameters. If any * errors occur, the error code(s) are returned by the function, * otherwide UPS_NO_ERROR is returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Hemisphere : Hemisphere either 'N' or 'S' (output) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ long Convert_Geodetic_To_UPS ( double Latitude, double Longitude, char *Hemisphere, double *Easting, double *Northing)const; /*! * The function Convert_UPS_To_Geodetic converts UPS (hemisphere, easting, * and northing) coordinates to geodetic (latitude and longitude) coordinates * according to the current ellipsoid parameters. If any errors occur, the * error code(s) are returned by the function, otherwise UPS_NO_ERROR is * returned. * * Hemisphere : Hemisphere either 'N' or 'S' (input) * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ long Convert_UPS_To_Geodetic(char Hemisphere, double Easting, double Northing, double *Latitude, double *Longitude)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimUpspt.h000066400000000000000000000021041352751253100232000ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts(gpotts@imagelinks.com) // // Description: // // This is the Universal Polar Stereographic (UPS) point. Allows // easy onversion between different coordinates. //******************************************************************* // $Id: ossimUpspt.h 23353 2015-06-01 19:19:10Z dburken $ #ifndef ossimUpspt_HEADER #define ossimUpspt_HEADER 1 #include class ossimUtmpt; class ossimGpt; class ossimEcefPoint; class ossimDatum; class OSSIM_DLL ossimUpspt { public: ossimUpspt(const ossimGpt &aPt); ossimUpspt(const ossimEcefPoint &aPt); char hemisphere()const{return theHemisphere;} double easting()const {return theEasting;} double northing()const{return theNorthing;} const ossimDatum* datum()const{return theDatum;} private: char theHemisphere; double theEasting; double theNorthing; ossimDatum *theDatum; void convertFromGeodetic(const ossimGpt &aPt); }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimUtm.h000066400000000000000000000153611352751253100226430ustar00rootroot00000000000000#ifndef UTM_H #define UTM_H 1 /***************************************************************************/ /* RSC IDENTIFIER: UTM * * ABSTRACT * * This component provides conversions between geodetic coordinates * (latitude and longitudes) and Universal Transverse Mercator (UTM) * projection (zone, hemisphere, easting, and northing) coordinates. * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid value * is found, the error code is combined with the current error code using * the bitwise or. This combining allows multiple error codes to be * returned. The possible error codes are: * * UTM_NO_ERROR : No errors occurred in function * UTM_LAT_ERROR : Latitude outside of valid range * (-80.5 to 84.5 degrees) * UTM_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees) * UTM_EASTING_ERROR : Easting outside of valid range * (100,000 to 900,000 meters) * UTM_NORTHING_ERROR : Northing outside of valid range * (0 to 10,000,000 meters) * UTM_ZONE_ERROR : Zone outside of valid range (1 to 60) * UTM_HEMISPHERE_ERROR : Invalid hemisphere ('N' or 'S') * UTM_ZONE_OVERRIDE_ERROR: Zone outside of valid range * (1 to 60) and within 1 of 'natural' zone * UTM_A_ERROR : Semi-major axis less than or equal to zero * UTM_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * * REUSE NOTES * * UTM is intended for reuse by any application that performs a Universal * Transverse Mercator (UTM) projection or its inverse. * * REFERENCES * * Further information on UTM can be found in the Reuse Manual. * * UTM originated from : U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * UTM has no restrictions. * * ENVIRONMENT * * UTM was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC, version 2.8.1 * 2. MSDOS with MS Visual C++, version 6 * * MODIFICATIONS * * Date Description * ---- ----------- * 10-02-97 Original Code * */ /***************************************************************************/ /* * DEFINES */ #include #define UTM_NO_ERROR 0x0000 #define UTM_LAT_ERROR 0x0001 #define UTM_LON_ERROR 0x0002 #define UTM_EASTING_ERROR 0x0004 #define UTM_NORTHING_ERROR 0x0008 #define UTM_ZONE_ERROR 0x0010 #define UTM_HEMISPHERE_ERROR 0x0020 #define UTM_ZONE_OVERRIDE_ERROR 0x0040 #define UTM_A_ERROR 0x0080 #define UTM_INV_F_ERROR 0x0100 /***************************************************************************/ /* * FUNCTION PROTOTYPES * for UTM.C */ /* ensure proper linkage to c++ programs */ #ifdef __cplusplus extern "C" { #endif long OSSIM_DLL Set_UTM_Parameters(double a, double f, long override); /* * The function Set_UTM_Parameters receives the ellipsoid parameters and * UTM zone override parameter as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the * function, otherwise UTM_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * override : UTM override zone, zero indicates no override (input) */ void OSSIM_DLL Get_UTM_Parameters(double *a, double *f, long *override); /* * The function Get_UTM_Parameters returns the current ellipsoid * parameters and UTM zone override parameter. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * override : UTM override zone, zero indicates no override (output) */ long OSSIM_DLL Convert_Geodetic_To_UTM (double Latitude, double Longitude, long *Zone, char *Hemisphere, double *Easting, double *Northing); /* * The function Convert_Geodetic_To_UTM converts geodetic (latitude and * longitude) coordinates to UTM projection (zone, hemisphere, easting and * northing) coordinates according to the current ellipsoid and UTM zone * override parameters. If any errors occur, the error code(s) are returned * by the function, otherwise UTM_NO_ERROR is returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Zone : UTM zone (output) * Hemisphere : North or South hemisphere (output) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ long OSSIM_DLL Convert_UTM_To_Geodetic(long Zone, char Hemisphere, double Easting, double Northing, double *Latitude, double *Longitude); /* * The function Convert_UTM_To_Geodetic converts UTM projection (zone, * hemisphere, easting and northing) coordinates to geodetic(latitude * and longitude) coordinates, according to the current ellipsoid * parameters. If any errors occur, the error code(s) are returned * by the function, otherwise UTM_NO_ERROR is returned. * * Zone : UTM zone (input) * Hemisphere : North or South hemisphere (input) * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ #ifdef __cplusplus } #endif #endif /* UTM_H */ ossim-Miami-2.9.1/include/ossim/projection/ossimUtmProjection.h000066400000000000000000000217211352751253100246750ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Utm projection code. //******************************************************************* // $Id: ossimUtmProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimUtmProjection_HEADER #define ossimUtmProjection_HEADER #include class OSSIMDLLEXPORT ossimUtmProjection : public ossimMapProjection { public: ossimUtmProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(), const ossimGpt& origin = ossimGpt()); ossimUtmProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, ossim_int32 zone, char hemisphere); ossimUtmProjection(ossim_int32 zone); ossimUtmProjection(const ossimUtmProjection& src); virtual ossimObject* dup()const; virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const; virtual ossimDpt forward(const ossimGpt &latLon)const; virtual void update(); /** * This will set the utm zone and utm origin base on origin passed in. * * @note If the origin latitude is not 0.0 it will also set the * hemisphere. If 0.0 hemisphere is unchanged from previous stored value. */ virtual void setOrigin(const ossimGpt& origin); void setZone(const ossimGpt& ground); void setZone(ossim_int32 zone); void setHemisphere(const ossimGpt& ground); void setHemisphere(char hemisphere); static ossim_int32 computeZone(const ossimGpt& gpt); /** * Return in decimal degrees the zone meridian. */ static double computeZoneMeridian(ossim_int32 zone); ossim_int32 getZone()const; char getHemisphere()const; /** * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Prints data members to stream. Returns stream&. */ virtual std::ostream& print(std::ostream& out) const; /** * @return The false easting. */ virtual double getFalseEasting() const; /** * @return The false northing. */ virtual double getFalseNorthing() const; virtual double getScaleFactor() const; //! Returns TRUE if principal parameters are within epsilon tolerance. virtual bool operator==(const ossimProjection& projection) const; /** * @brief Returns the EPSG PCS code based on datum, zone, and hemisphere. * * This overrides ossimMapProjection::getPcsCode(). Sets * ossimMapProjection::thePcsCode on success. * * @return code on success, 0 if datum is not set. */ virtual ossim_uint32 getPcsCode() const; private: /*_____________GEOTRANS_______________*/ /** * The function Set_Tranverse_Mercator_Parameters receives the ellipsoid * parameters and Tranverse Mercator projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, the error * code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at the origin of the (input) * projection * Central_Meridian : Longitude in radians at the center of the (input) * projection * False_Easting : Easting/X at the center of the projection (input) * False_Northing : Northing/Y at the center of the projection (input) * Scale_Factor : Projection scale factor (input) */ ossim_int32 Set_Transverse_Mercator_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing, double Scale_Factor); /** * The function Get_Transverse_Mercator_Parameters returns the current * ellipsoid and Transverse Mercator projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at the origin of the (output) * projection * Central_Meridian : Longitude in radians at the center of the (output) * projection * False_Easting : Easting/X at the center of the projection (output) * False_Northing : Northing/Y at the center of the projection (output) * Scale_Factor : Projection scale factor (output) */ void Get_Transverse_Mercator_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing, double *Scale_Factor)const; /** * The function Convert_Geodetic_To_Transverse_Mercator converts geodetic * (latitude and longitude) coordinates to Transverse Mercator projection * (easting and northing) coordinates, according to the current ellipsoid * and Transverse Mercator projection coordinates. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ ossim_int32 Convert_Geodetic_To_Transverse_Mercator (double Latitude, double Longitude, double *Easting, double *Northing)const; /** * The function Convert_Transverse_Mercator_To_Geodetic converts Transverse * Mercator projection (easting and northing) coordinates to geodetic * (latitude and longitude) coordinates, according to the current ellipsoid * and Transverse Mercator projection parameters. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ ossim_int32 Convert_Transverse_Mercator_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const; double theTranMerc_a; /* Semi-major axis of ellipsoid i meters */ double theTranMerc_f; /* Flattening of ellipsoid */ /* Eccentricity (0.08181919084262188000) squared */ double theTranMerc_es; double theTranMerc_ebs; /* Second Eccentricity squared */ /* Transverse_Mercator projection Parameters */ double theTranMerc_Origin_Lat; /* Latitude of origin in radians */ double theTranMerc_Origin_Long; /* Longitude of origin in radians */ double theTranMerc_False_Northing; /* False northing in meters */ double theTranMerc_False_Easting; /* False easting in meters */ double theTranMerc_Scale_Factor; /* Scale factor */ /* Isometeric to geodetic latitude parameters, default to WGS 84 */ double theTranMerc_ap; double theTranMerc_bp; double theTranMerc_cp; double theTranMerc_dp; double theTranMerc_ep; /* Maximum variance for easting and northing values for WGS 84. */ double theTranMerc_Delta_Easting; double theTranMerc_Delta_Northing; /** * zone can be from 1 through 60 (0 == NOT SET) */ ossim_int32 theZone; /** * can be N or S. */ char theHemisphere; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimUtmpt.h000066400000000000000000000044131352751253100232030ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // // This is the Universal Transverse Mercator (UTM) point. Allows // easy onversion between different coordinates. //******************************************************************* // $Id: ossimUtmpt.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimUtmpt_HEADER #define ossimUtmpt_HEADER #include class ossimGpt; class ossimEcefPoint; class ossimUpspt; class ossimDatum; class OSSIMDLLEXPORT ossimUtmpt { public: ossimUtmpt(const ossimGpt &aPt); ossimUtmpt(const ossimEcefPoint &aPt); ossimUtmpt(long zone, char hemisphere, // N or S double easting, double northing, const ossimDatum* datum); // ossimUtmpt(const ossimUpspt &aPt); /** * Return the zone for this utm point. */ ossim_int32 zone() const { return theZone; } /** * Return the hemisphere ( Northern or Southern). * We store this as a char value N or S. We store it * like this because we are interfacing to geotrans * and geotrans stores their values in this manner. */ char hemisphere() const { return theHemisphere; } /** * return the easting value in meters. */ double easting() const { return theEasting; } /** * return the northing value in meters. */ double northing() const { return theNorthing; } /** * return the reference datum for this point. */ const ossimDatum* datum() const { return theDatum; } /** * Initializes this point to utm coordinates for the ground point. * * @param aPt Ground point to initialize from. */ void convertFromGround(const ossimGpt &aPt); /** * Initializes the ground point from the utm coordinates of this point. * * @param aPt Ground point to initialize. */ void convertToGround(ossimGpt &aPt); private: long theZone; char theHemisphere; double theEasting; double theNorthing; const ossimDatum* theDatum; }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimVanDerGrintenProjection.h000066400000000000000000000164721352751253100266450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // Calls Grinten projection code. //******************************************************************* // $Id: ossimVanDerGrintenProjection.h 17815 2010-08-03 13:23:14Z dburken $ #ifndef ossimVanDerGrintenProjection_HEADER #define ossimVanDerGrintenProjection_HEADER #include class OSSIMDLLEXPORT ossimVanDerGrintenProjection : public ossimMapProjection { public: ossimVanDerGrintenProjection(const ossimEllipsoid& ellipsoid = ossimEllipsoid(), const ossimGpt& origin = ossimGpt()); ossimVanDerGrintenProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, const double falseEasting, const double falseNorthing); ~ossimVanDerGrintenProjection(){} virtual ossimObject *dup()const { return new ossimVanDerGrintenProjection(*this); } virtual ossimGpt inverse(const ossimDpt &eastingNorthing)const; virtual ossimDpt forward(const ossimGpt &latLon)const; virtual void update(); /*! * SetFalseEasting. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseEasting(double falseEasting); /*! * SetFalseNorthing. The value is in meters. * Update is then called so we can pre-compute paramters */ void setFalseNorthing(double falseNorthing); /*! * Sets both false easting and northing values. The values are * expected to be in meters. * Update is then called so we can pre-compute paramters */ void setFalseEastingNorthing(double falseEasting, double falseNorthing); void setDefaults(); void setCentralMeridian(double centralMeridian); double getFalseEasting()const{return Grin_False_Easting;} double getFalseNorthing()const{return Grin_False_Northing;} /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Returns TRUE if principal parameters are within epsilon tolerance. virtual bool operator==(const ossimProjection& projection) const; protected: //________________GEOTRANS_____________ mutable double Grin_a; /* Semi-major axis of ellipsoid in meters */ mutable double Grin_f; /* Flattening of ellipsoid */ mutable double es2; /* Eccentricity (0.08181919084262188000) squared */ mutable double es4; /* es2 * es2 */ mutable double es6; /* es4 * es2 */ mutable double Ra; /* Spherical Radius */ mutable double PI_Ra; mutable double Grin_Origin_Long; /* Longitude of origin in radians */ mutable double Grin_False_Easting; mutable double Grin_False_Northing; /* Van Der Grinten projection Parameters */ /*! * The function Set_Van_der_Grinten_Parameters receives the ellipsoid parameters and * Van Der Grinten projcetion parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, otherwise * GRIN_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ long Set_Van_der_Grinten_Parameters(double a, double f, double Central_Meridian, double False_Easting, double False_Northing); /*! * The function Get_Van_der_Grinten_Parameters returns the current ellipsoid * parameters, and Van Der Grinten projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ void Get_Van_der_Grinten_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing)const; /*! * The function Convert_Geodetic_To_Van_der_Grinten converts geodetic (latitude and * longitude) coordinates to Van Der Grinten projection easting, and northing * coordinates, according to the current ellipsoid and Van Der Grinten projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise GRIN_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ long Convert_Geodetic_To_Van_der_Grinten (double Latitude, double Longitude, double *Easting, double *Northing)const; /*! * The function Convert_Van_der_Grinten_To_Geodetic converts Van Der Grinten projection * easting and northing coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Van Der Grinten projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise GRIN_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ long Convert_Van_der_Grinten_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/projection/ossimWarpProjection.h000066400000000000000000000105251352751253100250410ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // // DESCRIPTION: // Contains declaration of class ossimWarpProjection. This is an // implementation of a warping interpolation model. // //***************************************************************************** // $Id: ossimWarpProjection.h 17207 2010-04-25 23:21:14Z dburken $ #ifndef ossimWarpProjection_HEADER #define ossimWarpProjection_HEADER #include #include class ossim2dTo2dTransform; /*!**************************************************************************** * * CLASS: ossimWarpProjection * *****************************************************************************/ class OSSIMDLLEXPORT ossimWarpProjection : public ossimProjection { public: /*! * Default Contructor: */ ossimWarpProjection(); /*! * Primary constructor accepting pointer to the underlying client projection. */ ossimWarpProjection(ossimProjection* client); /*! * Constructor accepts OSSIM keywordlist geometry file. */ ossimWarpProjection(const ossimKeywordlist& geom_kwl, const char* prefix=0); ~ossimWarpProjection(); /*! * METHOD: worldToLineSample() * Performs the forward projection from ground point to line, sample. */ virtual void worldToLineSample(const ossimGpt& worldPoint, ossimDpt& lineSampPt) const; /*! * METHOD: lineSampleToWorld() * Performs the inverse projection from line, sample to ground (world): */ virtual void lineSampleToWorld(const ossimDpt& lineSampPt, ossimGpt& worldPt) const; /*! * Performs the inverse projection from line, sample to ground, bypassing * reference to elevation surface: */ virtual void lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& hgtEllipsoid, ossimGpt& worldPt) const; /*! * Extends base-class implementation. Dumps contents of object to std::ostream. */ virtual std::ostream& print(std::ostream& out) const; friend std::ostream& operator<<(std::ostream& os, const ossimWarpProjection& m); /*! * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry * KWL files. Returns true if successful. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /*! * Returns pointer to a new instance, copy of this. */ virtual ossimObject* dup() const; /*! * Returns projection's ground point origin. That is the GP corresponding * to line=0, sample=0. */ virtual ossimGpt origin() const; /*! * Compares this instance with arg projection. NOT IMPLEMENTED. */ virtual bool operator==(const ossimProjection& /* projection */) const { return false; } virtual ossimDpt getMetersPerPixel() const; virtual ossim2dTo2dTransform* getWarpTransform() { return theWarpTransform.get(); } virtual ossim2dTo2dTransform* getAffineTransform() { return theAffineTransform.get(); } virtual ossimProjection* getClientProjection() { return theClientProjection.get(); } virtual void setNewWarpTransform(ossim2dTo2dTransform* warp); virtual void setNewAffineTransform(ossim2dTo2dTransform* affine); /** * @brief Implementation of pure virtual * ossimProjection::isAffectedByElevation method. * @return based on theClientProjection->isAffectedByElevation(). * If theClientProjection is null this returns true just to be safe. */ virtual bool isAffectedByElevation() const; protected: /*! * Data Members: */ ossimRefPtr theClientProjection; ossimRefPtr theWarpTransform; ossimRefPtr theAffineTransform; TYPE_DATA }; inline bool ossimWarpProjection::isAffectedByElevation() const { return ( theClientProjection.valid() ? theClientProjection->isAffectedByElevation() : false ); } #endif ossim-Miami-2.9.1/include/ossim/projection/ossimWktProjectionFactory.h000066400000000000000000000061551352751253100262310ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // //******************************************************************* // $Id: ossimWktProjectionFactory.h 22924 2014-10-27 16:32:58Z okramer $ #ifndef ossimWktProjectionFactory_HEADER #define ossimWktProjectionFactory_HEADER #include #include #include class ossimProjection; class ossimString; class ossimMapProjection; class ossimDatum; //************************************************************************************************* //! Projection Factory for coded projections defined in database. These are projections //! that are fully defined in database files and specified via a projection coordinate system (PCS) //! code, such as EPSG codes. //************************************************************************************************* class OSSIMDLLEXPORT ossimWktProjectionFactory : public ossimProjectionFactoryBase { public: /*! * METHOD: instance() * Instantiates singleton instance of this class: */ static ossimWktProjectionFactory* instance(); virtual ossimProjection* createProjection(const ossimFilename& filename, ossim_uint32 entryIdx) const; //! This is the principal factory method. It accepts a WKT string, for example //! "Anguilla_1957_British_West_Indies_Grid" virtual ossimProjection* createProjection(const ossimString& name) const; virtual ossim_uint32 getCode(const ossimString& name); //! Looks for presence of "projection" keyword with the value in WKT format, //! for example "Anguilla_1957_British_West_Indies_Grid" virtual ossimProjection* createProjection(const ossimKeywordlist& kwl, const char* prefix = 0)const; virtual ossimObject* createObject(const ossimString& typeName)const; virtual ossimObject* createObject(const ossimKeywordlist& kwl, const char* prefix=0)const; //! This returns the type name of all objects in all factories. This is the name used to //! construct the objects dynamically and this name must be unique. virtual void getTypeNameList(std::vector& typeList) const; protected: //! Constructor loads the WKT CSV file specified in the ossim prefs with "wkt_database_file" //! keyword. ossimWktProjectionFactory() {} ossimProjection* doTransverseMercator(const ossimKeywordlist& kwl)const; ossimProjection* doMercator(const ossimKeywordlist& kwl)const; ossimProjection* doLambertConformalConic(const ossimKeywordlist& kwl) const; ossimProjection* doEquiDistCylindrical(const ossimKeywordlist& kwl) const; ossimProjection* doEquiAreaCylindrical(const ossimKeywordlist& kwl) const; void loadRecords() const; template void doMapCommon(const ossimKeywordlist& kwl, T proj) const; static ossimWktProjectionFactory* m_instance; //!< Singleton implementation mutable std::map m_wktProjRecords; }; #endif ossim-Miami-2.9.1/include/ossim/reg/000077500000000000000000000000001352751253100172455ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/reg/GroundControlPoint.h000066400000000000000000000054431352751253100232350ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef GroundControlPoint_HEADER #define GroundControlPoint_HEADER 1 #include #include #include #include namespace ossim { /** * Class for representing a ground control point. * TODO: mplement cross-correlation between GCPs */ class GroundControlPoint : public ossim::JsonInterface, public std::enable_shared_from_this { public: /** * Creates new GCP from JSON object. * The ground point (GCP) coordinates are specified in either ECF or geographic. * The associated covariance must be in the same coordinate system. If correlations exist to * other GCPs, those GCPs must share the same coordinate system. TBD: Perhaps the GCP * information, including coordinates, covariances and cross-covariances can be ingested prior * and accessed from the database with only GCP ID. Id so, the remainder of this message is not * needed. * * The JSON Format: * { * "id": , * "ecf": [ , , ], OR * "geo": [ , , ], * "covariance": [ c11, c22, c33, c12, c13, c23 ], * "crossCovariances": [ (Can be excluded if no correlation information available) * { * "id": , The other GCP’s ID * "crossCovariance": [ c11, c22, c33, c12, c13, c23 ] * } * ] * } * */ GroundControlPoint(const Json::Value& image_json_node); virtual ~GroundControlPoint(); const std::string& getId() const { return m_id; } const ossimEcefPoint& getECF() const { return m_gcp; } const NEWMAT::SymmetricMatrix& getCovariance() const {return m_covariance;} /* * Refer to 3DISA API document * for JSON format used. */ virtual void loadJSON(const Json::Value& json); /* * Refer to 3DISA API document * for JSON format used. */ virtual void saveJSON(Json::Value& json) const; private: GroundControlPoint(); std::string m_id; ossimEcefPoint m_gcp; NEWMAT::SymmetricMatrix m_covariance; //> X, Y, Z (ECF) }; typedef std::vector< std::shared_ptr > GcpList; } // end namespace ossimMsp #endif /* #ifndef GroundControlPoint_HEADER */ ossim-Miami-2.9.1/include/ossim/reg/Image.h000066400000000000000000000053641352751253100204500ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef Image_HEADER #define Image_HEADER 1 #include #include #include #include #include #include #include #include #include #include namespace ossim { /** * Class representing an Image as used by ossim-msp services. */ class OSSIM_DLL Image : public ossim::JsonInterface, public std::enable_shared_from_this { public: static unsigned int UNASSIGNED_PHOTOBLOCK_INDEX; Image(const std::string& imageId, const std::string& filename, const std::string& modelName="", unsigned int entryIndex=0, unsigned int band=1); Image(const Json::Value& image_json_node); ~Image(); std::string getImageId() const { return m_imageId; } std::string getFilename() const { return m_filename; } std::string getModelName() const { return m_modelName; } unsigned int getEntryIndex() const { return m_entryIndex; } unsigned int getActiveBand() const { return m_activeBand; } void setImageId(const std::string& id) { m_imageId = id; } void setFilename(const std::string& f) { m_filename = f; } void setEntryIndex(unsigned int i) { m_entryIndex = i; } /** * Returns all available sensor model plugins and model names for this image: * @param availableModels List of pairs. */ virtual void getAvailableModels(std::vector< std::pair >& availableModels) const; /** * Refer to 3DISA API document * for JSON format used. */ virtual void loadJSON(const Json::Value& json); /** * Refer to 3DISA API document * for JSON format used. */ virtual void saveJSON(Json::Value& json) const; protected: std::string m_imageId; ossimFilename m_filename; unsigned int m_entryIndex; unsigned int m_activeBand; std::string m_modelName; std::vector< std::pair > m_availableModel; ossimRefPtr m_sensorModel; }; typedef std::vector< std::shared_ptr > ImageList; } // End namespace ATP #endif ossim-Miami-2.9.1/include/ossim/reg/PhotoBlock.h000066400000000000000000000063641352751253100214730ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef PhotoBlock_HEADER #define PhotoBlock_HEADER 1 #include #include #include #include #include #include #include #include namespace ossim { /** * Class for representing MSP PhotoBlock. */ class PhotoBlock : public JsonInterface, public std::enable_shared_from_this { public: /** * Initialize the photoblock from a prior saved session. If none found, assumes a new, blank * session is being started. */ PhotoBlock(); PhotoBlock(const Json::Value& pb_json_node); PhotoBlock(const PhotoBlock& copyThis); ~PhotoBlock(); PhotoBlock& operator=(const PhotoBlock& copythis); std::shared_ptr getImage(const std::string& imageId); std::shared_ptr getTiePoint(unsigned int tpId); std::shared_ptr getGroundPoint(const std::string& gpId); ImageList& getImageList() { return m_imageList; } TiePointList& getTiePointList() { return m_tiePointList; } std::vector >& getGroundPointList() { return m_gcpList; } // TODO: Add of individual components not valid until proper management of the JCM can be // provided /** * Adds the image to the photoblock at last position. Sets the image's pb index member. * @param images To be added to PB * @return The PB index of the image in the photoblock. */ unsigned int addImage(std::shared_ptr image); /** * Adds the image to the photoblock at last position. Sets the image's pb index member. * @param images To be added to PB * @return The PB index of the image in the photoblock. */ unsigned int addGroundPoint(std::shared_ptr groundPoint); /** * Adds the tiepoint to the PB * @param tiepoint To be added to PB * @return The index of the TP in the photoblock (should be same as TP ID) */ unsigned int addTiePoint(std::shared_ptr tiepoint); /** * Adds the list of tiepoints to the PB * @param tiepointList To be added to PB */ void addTiePoints(TiePointList& tiepointList); /* * Refer to 3DISA API document * for JSON format used. */ virtual void loadJSON(const Json::Value& json); /* * Refer to 3DISA API document * for JSON format used. */ virtual void saveJSON(Json::Value& json) const; protected: std::vector > m_imageList; std::vector > m_tiePointList; std::vector > m_gcpList; }; } // End namespace ISA #endif ossim-Miami-2.9.1/include/ossim/reg/TiePoint.h000066400000000000000000000106741352751253100211610ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef TiePoint_HEADER #define TiePoint_HEADER 1 #include #include #include #include #include #include #include namespace ossim { class TiePoint; typedef std::vector< std::shared_ptr > TiePointList; /** * Class for representing a single tiepoint on two or more images. It also represents image-points * associated with a ground control point. */ class TiePoint : public ossim::JsonInterface, public std::enable_shared_from_this { public: enum Type { UNASSIGNED, MANUAL, //> The point was created or edited manually and contains at least a pair of image points AUTO, //> Result of auto tie point generation and contains at least a pair of image points GCP //> point is associated with a manually-entered ground control. Possibly multiple image points }; TiePoint(); TiePoint(const TiePoint& copy); /** * Creates new tiepoint from JSON object formatted as: * { * "id": , // may be ignored if not valid * "type": "M"|"A"|"G" For “manualâ€, “autoâ€, or “GCP-associated†* "imagePoints: [ * { * "imageId": , * "x": , * "y": , * "covariance": [ cxx, cyy, cxy ], * "gcpId": Only if associated with a GCP * } * ] * } */ TiePoint(const Json::Value& tp_json_node); virtual ~TiePoint(); unsigned int getImageCount() const { return m_images.size(); } const std::string& getTiePointId() const { return m_tiePointId; } void setTiePointId(const std::string& id); /** * Fetches the image point coordinates along with image ID and GCP ID if available. * @param index Inout index into the list of images containing this tiepoint * @param imageId Output image ID for the ccorresponding image point * @param imagePoint image coordinates * @param cov image point measurement covariance in (x, y) coordinates */ void getImagePoint(unsigned int index, std::string& imageId, ossimDpt& imagePoint, NEWMAT::SymmetricMatrix& cov) const; /** * Sets image point value and associated measurement covariance for specified image ID. * If the image ID is not found, it will be added as new observation. */ void setImagePoint(std::shared_ptr image, const ossimDpt& imagePoint, const NEWMAT::SymmetricMatrix& cov); Type getType() const { return m_type; } void setType(Type t) { m_type = t; } const std::string& getGcpId() const { return m_gcpId; } void setGcpId(const std::string& id); /* * Refer to 3DISA API document * for JSON format used. */ virtual void loadJSON(const Json::Value& json); /* * Refer to 3DISA API document * for JSON format used. */ virtual void saveJSON(Json::Value& json) const; virtual std::ostream& print(std::ostream& out) const; friend std::ostream& operator << (std::ostream& out, const TiePoint& tp) { return tp.print(out); } protected: Type m_type; std::string m_tiePointId; std::vector< std::shared_ptr > m_images; //> List of images containing common feature std::vector m_imagePoints; //> List of image point measurements for common feature std::vector m_covariances; //> List of measurement covariances corresponding to image points vector double m_gsd; //> image scale (meters/pixel) at which matching was performed std::string m_gcpId; //> Cross reference to GCP record associated with this TP. static int s_runningId; }; typedef std::vector< std::shared_ptr > TiePointList; } // end namespace ATP #endif /* #ifndef TiePoint_HEADER */ ossim-Miami-2.9.1/include/ossim/sockets/000077500000000000000000000000001352751253100201435ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/sockets/ossimToolClient.h000066400000000000000000000056751352751253100234600ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef ossimToolClient_HEADER #define ossimToolClient_HEADER 1 #include #include /** * Utility class providing an interface to ossimTool-derived functionality via TCP sockets * Results are returned either as streamed text (for non-image responses such as image info) or * streamed binary file representing imagery or vector products. Code interfacing to this class * should know the commands available (or execute the command "help" and view the text response). */ class OSSIM_DLL ossimToolClient { public: ossimToolClient(); /** * Closes any open connections. */ ~ossimToolClient(); /** * Accepts hostname and portname as a string. Returns socket file descriptor or -1 if error. */ int connectToServer(char* hostname, char* portname=NULL); /** * Sets the local destination directory for file product. The product file name used * will match the server-side's file name. This method must be called prior to execute() for * operations generating file products, otherwise the products are written to the client's temp * directory. If the path directory specified does not exist, it will be created. * Returns true if successful. */ bool setProductFilePath(const char* filepath); /** * Returns the filename (including full client-side path) of the local product file waiting * after execute(), or NULL if none. */ const char* getProductFilePath() const { return m_prodFilePath; } /** * Executes OSSIM tool command with options. Examples: * * "info -p " -- Fetches projection info for server side file specified * "shoreline -i , " * * Returns TRUE if product generated and received. setProductFilePath() must be called prior to * execute() for operations generating file products, otherwise the products are written to the * client's temp directory. */ bool execute(const char* command_spec); /** * Returns the server's text response generated by the execute() call, or NULL if no response * available. Some operations generate both text and file products. */ const char* getTextResponse() const { return m_textResponse.chars(); } /** * Closes connection to server and ready to connect again. */ bool disconnect(); protected: void error(const char *msg); bool receiveText(); bool receiveFile(); bool acknowledgeRcv(); int m_svrsockfd; char* m_buffer; ossimFilename m_prodFilePath; ossimString m_textResponse; }; #endif ossim-Miami-2.9.1/include/ossim/sockets/ossimToolServer.h000066400000000000000000000027131352751253100234760ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #ifndef ossimToolServer_HEADER #define ossimToolServer_HEADER 1 #include #include /** * Utility class provides the server interface to ossimTool-derived functionality via TCP sockets * Results are returned either as streamed text (for non-image responses such as image info) or * streamed binary file representing imagery or vector products. Clients interfacing to this class * should know the commands available (or execute the command "help" and view the text response). * @see ossimToolClient for concrete client implementation. */ class OSSIM_DLL ossimToolServer { public: ossimToolServer(); ~ossimToolServer(); void startListening(const char* portid); private: void initSocket(const char* portid); bool processOssimRequest(struct sockaddr_in& cli_addr); bool runCommand(ossimString& command); void writeSocket(const char* buf, int bufsize); bool sendFile(const ossimFilename& fname); void error(const char* msg); bool acknowledgeRcvd(); static void sigchld_handler(int s); int m_svrsockfd; int m_clisockfd; char* m_buffer; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/000077500000000000000000000000001352751253100211755ustar00rootroot00000000000000ossim-Miami-2.9.1/include/ossim/support_data/ImageHandlerState.h000066400000000000000000000124221352751253100246700ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // //***************************************************************************** #ifndef ossimImageHandlerState_HEADER #define ossimImageHandlerState_HEADER 1 #include #include #include #include #include namespace ossim { /** * This is a Image handler state object. This handles caching * state of a ossimImageHandler. The example code provided will * work for any Image handler that supports state caching. Note, * if anything changes on the input image then the state will need * to be recalculated by opening the image without the state and * grabbing it's state again. * * Example code to get a state of an image source: * * @code * #include * #include * #include * #include * * ossimRefPtr h = ossimImageHandlerRegistry::instance()->open(filename); * * if(h) * { * std::shared_ptr state = h->getState(); * if(state) * { * ossimKeywordlist kwl; * state->save(kwl); * std::cout << kwl << "\n"; * } * } * @endCode * * Example code using a state * * @code * #include * #include * #include * #include * * ossimRefPtr h = ossimImageHandlerRegistry::instance()->open(filename); * * if(h) * { * std::shared_ptr state = h->getState(); * if(state) * { * h = ossimImageHandlerRegistry::instance()->open(state); * if(h) * { * std::cout << "Successfully opened with a state\n"; * } * } * } * @endCode */ class OSSIM_DLL ImageHandlerState : public ossim::State { public: ImageHandlerState(); virtual ~ImageHandlerState(); virtual const ossimString& getTypeName()const override; static const ossimString& getStaticTypeName(); /** * Loads the the state object from keywordlist. * * @param kwl keywordlist that olds the state of the object * @param prefix optional prefix value that is used as a prefix * for all keywords. */ virtual bool load(const ossimKeywordlist& kwl, const ossimString& prefix="") override; /** * Saves the state of the object to a keyword list. * * @param kwl keywordlist that the state will be saved to * @param prefix optional prefix value that is used as a prefix * for all keywords. */ virtual bool save(ossimKeywordlist& kwl, const ossimString& prefix="")const override; /** * @return if one exists it will have a valid overview state. */ std::shared_ptr getOverviewState(){return m_overviewState;} /** * @return if one exists it will have a valid overview state. */ std::shared_ptr getOverviewState()const{return m_overviewState;} /** * Allows one to set the overview state object for this handler */ void setOverviewState(std::shared_ptr overviewState){m_overviewState=overviewState;} void setConnectionString(const ossimString& connectionString){m_connectionString = connectionString;} const ossimString& getConnectionString()const{return m_connectionString;} void setImageHandlerType(const ossimString& typeName){m_imageHandlerType = typeName;} const ossimString& getImageHandlerType()const{return m_imageHandlerType;} void setCurrentEntry(ossim_uint32 entry){m_currentEntry = entry;} const ossim_uint32 getCurrentEntry()const{return m_currentEntry;} std::shared_ptr getMetaData()const{return m_omd;} std::shared_ptr getMetaData(){return m_omd;} void setMetaData(std::shared_ptr omd){m_omd=omd;} void setValidVertices(std::shared_ptr kwl){m_validVertices=kwl;} std::shared_ptr getValidVertices(){return m_validVertices;} std::shared_ptr getValidVertices()const{return m_validVertices;} /** * @return true if it has metadata */ bool hasMetaData()const; /** * Overridable and loads the defaults given the main entry. */ bool virtual loadDefaults(const ossimFilename& filename, ossim_uint32 entry=0); private: static const ossimString m_typeName; std::shared_ptr m_overviewState; std::shared_ptr m_omd; std::shared_ptr m_validVertices; ossimString m_connectionString; ossimString m_imageHandlerType; ossim_uint32 m_currentEntry; }; }; #endifossim-Miami-2.9.1/include/ossim/support_data/ImageHandlerStateFactory.h000066400000000000000000000017521352751253100262240ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // //***************************************************************************** #ifndef ossimImageHandlerStateFactory_HEADER #define ossimImageHandlerStateFactory_HEADER 1 #include #include #include namespace ossim { class OSSIM_DLL ImageHandlerStateFactory : public StateFactoryBase< std::shared_ptr > { public: ImageHandlerStateFactory(); static std::shared_ptr instance(); virtual std::shared_ptr createState(const ossimKeywordlist& kwl, const ossimString& prefix="")const override; virtual std::shared_ptr createState(const ossimString& typeName)const override; }; } #endif ossim-Miami-2.9.1/include/ossim/support_data/ImageHandlerStateRegistry.h000066400000000000000000000023361352751253100264240ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // //***************************************************************************** #ifndef ossimImageHandlerStateRegistry_HEADER #define ossimImageHandlerStateRegistry_HEADER 1 #include #include #include #include #include namespace ossim { /** * This is the state registry for all image handler states that * will be supported. */ class OSSIM_DLL ImageHandlerStateRegistry : public ossim::FactoryListBase< std::shared_ptr > > > { public: ImageHandlerStateRegistry(); static std::shared_ptr instance(); std::shared_ptr createState(const ossimKeywordlist& kwl, const ossimString& prefix = "")const; std::shared_ptr createState(const ossimString& typeName)const; }; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/TiffHandlerState.h000066400000000000000000000402211352751253100245340ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // //***************************************************************************** #ifndef ossimTiffHandlerState_HEADER #define ossimTiffHandlerState_HEADER 1 #include #include typedef struct tiff TIFF; class ossimTieGptSet; namespace ossim { /** * This is a Tiff handler state object. This handles caching * state of a ossimTiffTileSource. The example code provided will * work for any Image handler that supports state caching. Note, * if anything changes on the input image then the state will need * to be recalculated by opening the image without the state and * grabbing it's state again. * * Example code to get a state of an image source: * * @code * #include * #include * #include * #include * * ossimRefPtr h = ossimImageHandlerRegistry::instance()->open(filename); * * if(h) * { * std::shared_ptr state = h->getState(); * if(state) * { * ossimKeywordlist kwl; * state->save(kwl); * std::cout << kwl << "\n"; * } * } * @endCode * * Example code using a state * * @code * #include * #include * #include * #include * * ossimRefPtr h = ossimImageHandlerRegistry::instance()->open(filename); * * if(h) * { * std::shared_ptr state = h->getState(); * if(state) * { * h = ossimImageHandlerRegistry::instance()->open(state); * if(h) * { * std::cout << "Successfully opened with a state\n"; * } * } * } * @endCode * * Small Keywordklist example from just the tiff. Typically this is grabbed * from the image handler but here we will just show the tiff tags * * @code * connection_string: /data/sanfran_utm.tif * current_entry: 0 * tiff.image0.is_geotiff: 1 * tiff.image0.is_tiled: true * tiff.image0.tifftag.angular_units: 9108 * tiff.image0.tifftag.bits_per_sample: 8 * tiff.image0.tifftag.compression: 1 * tiff.image0.tifftag.datum_code: 6326 * tiff.image0.tifftag.false_easting: 500000 * tiff.image0.tifftag.false_northing: 0 * tiff.image0.tifftag.gcs_code: 4326 * tiff.image0.tifftag.geo_double_params: (6378137,6356752.3141999999061) * tiff.image0.tifftag.geo_pixel_scale: (5,5,0) * tiff.image0.tifftag.geo_tie_points: (0,0,0,538185,4208785,0) * tiff.image0.tifftag.image_length: 8000 * tiff.image0.tifftag.image_width: 8000 * tiff.image0.tifftag.linear_units: 9001 * tiff.image0.tifftag.max_sample_value: 255 * tiff.image0.tifftag.min_sample_value: 1 * tiff.image0.tifftag.model_type: 1 * tiff.image0.tifftag.origin_lat: 0 * tiff.image0.tifftag.origin_lon: -123 * tiff.image0.tifftag.pcs_code: 32610 * tiff.image0.tifftag.photometric: 2 * tiff.image0.tifftag.planar_config: 1 * tiff.image0.tifftag.raster_type: 2 * tiff.image0.tifftag.sample_format: 1 * tiff.image0.tifftag.samples_per_pixel: 3 * tiff.image0.tifftag.scale_factor: 0.9996 * tiff.image0.tifftag.tile_length: 64 * tiff.image0.tifftag.tile_width: 64 * image_handler_type: * number_of_directories: 1 * type: ossim::TiffHandlerState * @endCode */ class OSSIM_DLL TiffHandlerState : public ossim::ImageHandlerState { public: TiffHandlerState(); virtual ~TiffHandlerState(); virtual const ossimString& getTypeName()const override; static const ossimString& getStaticTypeName(); /** * General access to get the tags of an image * * @return ossimKeywordlist that contains the tags */ ossimKeywordlist& getTags(){return m_tags;} /** * General access to the the tags of an image * * @return ossimKeywordlist that contains the tags */ const ossimKeywordlist& getTags()const{return m_tags;} /** * Is used by this state to add a valud to the tags * * @param key is the identifier for the value * @param value is the value to add to the tags */ void addValue(const ossimString& key, const ossimString& value); /** * Given a key return the value * * @param value returns the value * @param key is the key holding the value * * @return true if the value was found and false otherwise */ bool getValue(ossimString& value, const ossimString& key)const; /** * Convenience method to return the value of a key given the * directory. It will construct a new key from the directory. If * the directory is 0 and the key is sub_file_type then the key that * is actually queried internally is "tiff.image0.sub_file_type" * * @param value returns the value * @param directory is the directory to return the key * @param key is the key holding the value * * @return true if the value was found and false otherwise */ bool getValue(ossimString& value, const ossim_uint32 directory, const ossimString& key)const; /** * Will return true or false if the directory and key is in the * tags. * * @return */ bool exists(ossim_uint32 directory, const ossimString& key)const; /** * Will check if a key exists */ bool exists(const ossimString& key)const; bool checkBool(const ossimString& key)const; bool checkBool(ossim_uint32 directory, const ossimString& key)const; /** * This is overriden from the base and will load the main entry. For Tiff we * do not support multiple pages yet so this value will * be ignored. In the future it will be used to load the state * of individual pages. For now, what is loaded is based on the sub_file_type and * this entry is treated as the main entry point * * @param file file to to open * * @return true if defaults were loaded and false * otheriwse */ virtual bool loadDefaults(const ossimFilename& file, ossim_uint32 entry=0)override; /** * Will load default values * * @param tiffPtr tiff pointer */ void loadDefaults(TIFF* tiffPtr); void loadDefaults(std::shared_ptr &str, const std::string &connectionString); /** * Will load only value for the current directory * * @param tiffPtr tiff pointer */ void loadCurrentDirectory(TIFF *tiffPtr); /** * Will change and load the directory provided * * @param tiffPtr tiff pointer * @param directory the directory to load */ void loadDirectory(TIFF* tiffPtr, ossim_uint32 directory); /** * Convenience method to check if the directory * is a reduced image specification * * @param directory the directory to test */ bool isReduced(ossim_uint32 directory)const; /** * Convenience method to check if the directory * is a image mask specification * * @param directory the directory to test */ bool isMask(ossim_uint32 directory)const; /** * Convenience method to check if the directory * is a paged image specification * * @param directory the directory to test */ bool isPage(ossim_uint32 directory)const; /** * Convenience method to check if a directory * is tiled * * @param directory the directory to test * @return true if tiled and false otherwise */ bool isTiled(ossim_uint32 directory)const; /** * Convenience method to get an Int32 value. * * This does not supply a way to check if a value existed or not. */ ossim_int32 getInt32Value(const ossimString& key, ossim_int32 directory=0)const; /** * Convenience method to get an Double value. * * This does not supply a way to check if a value existed or not. */ ossim_float64 getDoubleValue(const ossimString& key, ossim_int32 directory=0)const; /** * Convenience method to get a pcs code. * * This does not supply a way to check if a value existed or not. */ ossim_int32 getPcsCode(ossim_int32 directory=0)const; /** * Convenience method to get a datum code. * * This does not supply a way to check if a value existed or not. */ ossim_int32 getDatumCode(ossim_int32 directory=0)const; /** * Convenience method to get a gcs code. * * This does not supply a way to check if a value existed or not. */ ossim_int32 getGcsCode(ossim_int32 directory=0)const; /** * Convenience method to get a model type. * * This does not supply a way to check if a value existed or not. */ ossim_int32 getModelType(ossim_int32 directory=0)const; /** * Convenience method to get angular units. * * This does not supply a way to check if a value existed or not. */ ossim_int32 getAngularUnits(ossim_int32 directory=0)const; /** * Convenience method to get linear units. * * This does not supply a way to check if a value existed or not. */ ossim_int32 getLinearUnits(ossim_int32 directory=0)const; /** * Convenience method to get tile height. * * This does not supply a way to check if a value existed or not. */ ossim_int64 getTileLength(ossim_int32 directory = 0) const; /** * Convenience method to get image length. * * This does not supply a way to check if a value existed or not. */ ossim_int64 getImageLength(ossim_int32 directory = 0) const; /** * Convenience method to get tile width. * * This does not supply a way to check if a value existed or not. */ ossim_int64 getTileWidth(ossim_int32 directory = 0) const; /** * Convenience method to get image width. * * This does not supply a way to check if a value existed or not. */ ossim_int64 getImageWidth(ossim_int32 directory=0)const; /** * Convenience method to get origin lat. * * This does not supply a way to check if a value existed or not. */ ossim_float64 getOriginLat(ossim_int32 directory=0)const; /** * Convenience method to get origin lon. * * This does not supply a way to check if a value existed or not. */ ossim_float64 getOriginLon(ossim_int32 directory=0)const; /** * Convenience method to get standard parallel 1. * * This does not supply a way to check if a value existed or not. */ ossim_float64 getStandardParallel1(ossim_int32 directory=0)const; /** * Convenience method to get standard parallel 2. * * This does not supply a way to check if a value existed or not. */ ossim_float64 getStandardParallel2(ossim_int32 directory=0)const; /** * Convenience method to get false easting. * * This does not supply a way to check if a value existed or not. */ ossim_float64 getFalseEasting(ossim_int32 directory=0)const; /** * Convenience method to get false northing. * * This does not supply a way to check if a value existed or not. */ ossim_float64 getFalseNorthing(ossim_int32 directory=0)const; /** * Convenience method to get scale factor. * * This does not supply a way to check if a value existed or not. */ ossim_float64 getScaleFactor(ossim_int32 directory=0)const; /** * Convenience method to get a raster type. * * This does not supply a way to check if a value existed or not. */ ossim_int32 getRasterType(ossim_int32 directory = 0) const; ossim_int32 getPlanarConfig(ossim_int32 directory = 0) const; ossim_int32 getPhotoInterpretation(ossim_int32 directory = 0) const; ossim_int32 getCompressionType(ossim_int32 directory = 0) const; ossim_uint16 getBitsPerSample(ossim_int32 directory = 0) const; ossim_uint16 getSamplesPerPixel(ossim_int32 directory = 0) const; ossim_uint16 getSampleFormat(ossim_int32 directory = 0) const; ossim_uint32 getRowsPerStrip(ossim_int32 directory = 0) const; bool getMinSampleValue(ossim_float64 &minSampleValue, ossim_int32 directory = 0) const; bool getMaxSampleValue(ossim_float64 &maxSampleValue, ossim_int32 directory = 0) const; bool hasColorMap(ossim_int32 dir)const; bool isReduced(ossim_int32 directory = 0) const; bool isPage(ossim_int32 directory = 0) const; bool isMask(ossim_int32 directory = 0) const; bool isDigitalGlobe()const; ossim_int32 getSubFileType(ossim_int32 directory = 0) const; ossim_uint32 getNumberOfDirectories()const; bool getColorMap(std::vector &red, std::vector &green, std::vector &blue, ossim_int32 directory = 0) const; /** * Convenience method to get a double array. * * @param result resulting double array * @param directory to use * @param key to get a double array. */ bool getDoubleArray(std::vector& result, ossim_int32 directory, const ossimString& key)const; /** * Convenience method to get a Geo double params array. * * @param result resulting double array * @param directory to use */ bool getGeoDoubleParams(std::vector& result, ossim_int32 directory=0)const; /** * Convenience method to get a Geo double params array. * * @param result resulting double array * @param directory to use */ bool getGeoPixelScale(std::vector& result, ossim_int32 directory)const; /** * Convenience method to get a Geo Tie points array. * * @param result resulting double array * @param directory to use */ bool getGeoTiePoints(std::vector& result, ossim_int32 directory=0)const; bool getCitation(ossimString& citation, ossim_int32 directory=0)const; bool getCopyright(ossimString ©right, ossim_int32 directory = 0) const; /** * Convenience method to get a Geo trans matrix array. * * @param result resulting double array * @param directory to use */ bool getGeoTransMatrix(std::vector& result, ossim_int32 directory)const; /** * Loads the the state object from keywordlist. * * @param kwl keywordlist that olds the state of the object * @param prefix optional prefix value that is used as a prefix * for all keywords. */ virtual bool load(const ossimKeywordlist& kwl, const ossimString& prefix="") override; /** * Saves the state of the object to a keyword list. * * @param kwl keywordlist that the state will be saved to * @param prefix optional prefix value that is used as a prefix * for all keywords. */ virtual bool save(ossimKeywordlist& kwl, const ossimString& prefix="")const override; private: static const ossimString m_typeName; /** * Used to save a color map. Will save the map into the * tag list as arrays for colormap.red, colormap.blue, colormap.green * Each list is a string of the form "(valu1,valu2, .... valueN)" with * the parenthesis included */ void saveColorMap(const ossimString& dirPrefix, const ossim_uint16* red, const ossim_uint16* green, const ossim_uint16* blue, ossim_uint32 numberOfEntries); /** * loads tags into the keywordlist for a given directory */ void loadGeotiffTags(TIFF* tiffPtr, const ossimString& dirPrefix); /** * converts an array into a string list of the form * * (vale1,value2,...,valueN) */ void convertArrayToStringList(ossimString& result, double* doubleArray, ossim_int32 doubleArraSize)const; ossimKeywordlist m_tags; }; } #endif ossim-Miami-2.9.1/include/ossim/support_data/TiffStreamAdaptor.h000066400000000000000000000060001352751253100247210ustar00rootroot00000000000000#ifndef ossimTiffStreamAdaptor_HEADER #define ossimTiffStreamAdaptor_HEADER #include #include #include #include #include namespace ossim { /** * This is the stream adaptor used by our tiff reader * We use the adaptor so we can support direct S3 access or later be * able to support blocked reads, ... etc * * Code snip for Input stream: * @code * m_streamAdaptor = std::make_shared(str, * connectionString); * * theTiffPtr = XTIFFClientOpen(connectionString.c_str(), "rm", * (thandle_t)m_streamAdaptor.get(), * ossim::TiffIStreamAdaptor::tiffRead, * ossim::TiffIStreamAdaptor::tiffWrite, * ossim::TiffIStreamAdaptor::tiffSeek, * ossim::TiffIStreamAdaptor::tiffClose, * ossim::TiffIStreamAdaptor::tiffSize, * ossim::TiffIStreamAdaptor::tiffMap, * ossim::TiffIStreamAdaptor::tiffUnmap); * @endCode */ class OSSIM_DLL TiffIStreamAdaptor { public: TiffIStreamAdaptor() { } TiffIStreamAdaptor(const ossimString& connectionString) { openStream(connectionString); } TiffIStreamAdaptor(std::shared_ptr inputStream, const ossimString& connectionString="") { setStream(inputStream, connectionString); } ~TiffIStreamAdaptor() { close(); } bool openStream(const ossimString& connectionString) { setStream(ossim::StreamFactoryRegistry::instance()->createIstream(connectionString)); return (m_tiffStream != nullptr); } void setStream(std::shared_ptr inputStream, const ossimString& connectionString="") { m_tiffStream = inputStream; m_connectionString = connectionString; } const ossimString& getConnectionString()const{return m_connectionString;} std::shared_ptr getStream() { return m_tiffStream; } void close() { m_tiffStream.reset(); } static tsize_t tiffRead(thandle_t st,tdata_t buffer,tsize_t size); static tsize_t tiffWrite(thandle_t st,tdata_t buffer,tsize_t size); static int tiffClose(thandle_t st); static toff_t tiffSeek(thandle_t st,toff_t pos, int whence); static toff_t tiffSize(thandle_t st); static int tiffMap(thandle_t, tdata_t*, toff_t*); static void tiffUnmap(thandle_t, tdata_t, toff_t); private: std::shared_ptr m_tiffStream; ossimString m_connectionString; }; } #endifossim-Miami-2.9.1/include/ossim/support_data/ossimAigBounds.h000066400000000000000000000012661352751253100243010ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigBounds.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAigBounds_HEADER #define ossimAigBounds_HEADER #include class ossimAigBounds { public: friend std::ostream& operator <<(std::ostream& out, const ossimAigBounds& data); ossimAigBounds(); void reset(); bool writeStream(std::ostream& out); double ll_x; double ll_y; double ur_x; double ur_y; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimAigDataFileHeader.h000066400000000000000000000161751352751253100256360ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigDataFileHeader.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAigDataFileHeader_HEADER #define ossimAigDataFileHeader_HEADER #include #include #include class ossimAigDataFileHeader { public: ossimAigDataFileHeader() { reset(); } void reset() { theMagicNumber[0] = 0x00; theMagicNumber[1] = 0x00; theMagicNumber[2] = 0x27; theMagicNumber[3] = 0x0A; theMagicNumber[4] = 0xFF; theMagicNumber[5] = 0xFF; theMagicNumber[6] = 0xFC; theMagicNumber[7] = 0x14; memset((char*)theZeroFill1, 0x00, 16); memset((char*)theZeroFill2, 0x00, 72); theFileSize = 50; } bool writeStream(std::ostream& out)const; ossim_uint8 theMagicNumber[8]; ossim_uint8 theZeroFill1[16]; /*! * The size of this file in number of shorts. */ ossim_int32 theFileSize; ossim_uint8 theZeroFill2[72]; // ________________ These fields are replicated for every tile__________ /*! * Size of this tiles data measured in * shorts. This matches the size in * the index file, and does not * include the tile size itself. The * next tile starts 2*n+2 bytes after * the start of this tile, where n is the * value of this field. */ ossim_int16 theTileSize; //____________________These are from Frank's docs on the grid format /*! * Tile type code indicating the * organization of the following data * (integer coverages only). * * theTileType = 0x00 (constant block) * All pixels take the value of the RMin. Data is ignored. * It appears there is sometimes a bit of * meaningless data (up to four bytes) in the block. * * theTileType = 0x01 (raw 1bit data) * * theTileType = 0x04 (raw 4bit data) * One full tiles worth of data pixel values follows the * RMin field, with 4 bits per pixel. The high * order four bits of a byte comes before the * low order four bits. * theTileType = 0x08 (raw byte data) * One full tiles worth of data pixel values * (one byte per pixel) follows the RMin field. * theTileType = 0x10 (raw 16bit data) * One full tiles worth of data pixel values * follows the RMin field, with 16 bits per pixel (MSB). * theTileType = 0xCF (16 bit literal runs/nodata runs) * The data is organized in a series of runs. * Each run starts with a marker which should be * interpreted as: * Marker < 128: The marker is followed by Marker * pixels of literal data with two MSB bytes * per pixel. * Marker > 127: The marker indicates that 256-Marker pixels * of no data pixels should be put into the * output stream. No data * (other than the next marker) follows * this marker. * theTileType = 0xD7 (literal runs/nodata runs) * The data is organized in a series of runs. * Each run starts with a marker which should be * interpreted as: * Marker < 128: The marker is followed by Marker pixels of * literal data with one byte per pixel. * Marker > 127: The marker indicates that 256-Marker pixels * of no data pixels should be put into the * output stream. No data (other than the next * marker) follows this marker. * theTileType = 0xDF (RMin runs/nodata runs) * The data is organized in a series of runs. * Each run starts with a marker which should be * interpreted as: * Marker < 128: The marker is followed by Marker pixels of * literal data with one byte per pixel. * Marker > 127: The marker indicates that 256-Marker pixels * of no data pixels should be put into the * output stream. No data * (other than the next marker) follows this * marker. * This is similar to 0xD7, except that the data size is zero bytes instead of 1, * so only RMin values are inserted into the output stream. * theTileType = 0xE0 (run length encoded 32bit) * The data is organized in a series of runs. * Each run starts with a marker which should be * interpreted as a count. The four bytes following the count * should be interpreted as an MSB * Int32 value. They indicate that count pixels of value * should be inserted into the output stream. * theTileType = 0xF0 (run length encoded 16bit) * The data is organized in a series of runs. Each run * starts with a marker which should be interpreted as a count. * The two bytes following the count should be interpreted as an MSB * Int16 value. They indicate that count pixels of value should be * inserted into the output stream. * theTileType = 0xFC/0xF8 (run length encoded 8bit) * The data is organized in a series of runs. * Each run starts with a marker which should be * interpreted as a count. The following byte is the value. * They indicate that count pixels of value should be inserted * into the output stream. The intepretation is the same for * 0xFC, and 0xF8. I believe that 0xFC has a lower dynamic (2bit) range than 0xF8 (4 or 8 bit). * theTileType = 0xFF (unknown) * I have yet to deduce how this is organized, though it seems to be used for data with one bit of * dynamic range. and presumably uses some sort of run length encoding. But it's operation is not * obvious despite many hours, productions of hundreds of test files, and attempts to develop a * dictionary of binary strings for different run values. */ ossim_uint8 theTileType; /*! * Number of bytes following to * form the minimum value for the * tile (integer coverages only). This describes * the size of the next field */ ossim_uint8 theMinSize; ossim_int32 theMin; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimAigHeader.h000066400000000000000000000056741352751253100242460ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigHeader.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAigHeader_HEADER #define ossimAigHeader_HEADER #include #include #include "string.h" class ossimAigHeader { public: friend std::ostream& operator <<(std::ostream& out, const ossimAigHeader& header) { out << "Magic number: " << header.theMagic << std::endl << "Coverage: " << (header.theCellType==1?"Integer":"float") << std::endl << "Pixel size x: " << header.thePixelSizeX << std::endl << "Pixel size y: " << header.thePixelSizeY << std::endl << "Tiles per row: " << header.theNumberOfTilesPerRow << std::endl << "Tiles per col: " << header.theNumberOfTilesPerColumn << std::endl << "Tile width: " << header.theWidthOfTileInPixels << std::endl << "Tile height: " << header.theHeightOfTileInPixels; return out; } ossimAigHeader() { reset(); } void reset() { memset(theMagic, '\0', 8); strcpy(theMagic, "GRID1.2"); memset(theUnknownData, '\0', 8); setIntCoverage(); memset(theUnknownAssortedData, '\0', 236); thePixelSizeX = 1.0; thePixelSizeY = 1.0; theUnknownGeoReferencingValues[0] = 0.0; theUnknownGeoReferencingValues[1] = 0.0; theNumberOfTilesPerRow = 0; theNumberOfTilesPerColumn = 0; theWidthOfTileInPixels = 0; theUnknownValue = 1; theHeightOfTileInPixels = 0; } bool writeStream(std::ostream& out); void setFloatCoverage() { theCellType = 2; } void setIntCoverage() { theCellType = 1; } char theMagic[8]; char theUnknownData[8]; /*! * 1 means int cover and 2 means float cover */ ossim_int32 theCellType; char theUnknownAssortedData[236]; /*! * Holds the width of the pixel in geo referenced * coordinate. It's 1 otherwise */ double thePixelSizeX; /*! * Holds the height of the pixel in geo referenced * coordinate. It's 1 otherwise */ double thePixelSizeY; double theUnknownGeoReferencingValues[2]; /*! * This is the width of the file in tiles.. */ int theNumberOfTilesPerRow; /*! * This is the height of the file in tiles.. */ int theNumberOfTilesPerColumn; /*! * Numer of pixels wide the tile is. Usually the value is * 256 */ int theWidthOfTileInPixels; int theUnknownValue; /*! * Numer of pixels high the tile is. Usually the value is * 4 */ int theHeightOfTileInPixels; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimAigIndexFileHeader.h000066400000000000000000000040621352751253100260240ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigIndexFileHeader.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAigIndexFileHeader_HEADER #define ossimAigIndexFileHeader_HEADER #include #include #include class ossimAigIndexFileHeader { public: friend std::ostream& operator <<(std::ostream& out, const ossimAigIndexFileHeader& data) { out << "theFileSize: " << data.theFileSize; return out; } ossimAigIndexFileHeader() { reset(); } void reset() { theMagicNumber[0] = 0x00; theMagicNumber[1] = 0x00; theMagicNumber[2] = 0x27; theMagicNumber[3] = 0x0A; theMagicNumber[4] = 0xFF; theMagicNumber[5] = 0xFF; theMagicNumber[6] = 0xFC; theMagicNumber[7] = 0x14; memset((char*)theZeroFill1, 0x00, 16); memset((char*)theZeroFill2, 0x00, 72); theFileSize = 50; } bool writeStream(std::ostream& out); ossim_uint8 theMagicNumber[8]; ossim_uint8 theZeroFill1[16]; /*! * The size of this file in number of shorts. */ ossim_int32 theFileSize; ossim_uint8 theZeroFill2[72]; /*! * The next two fields that follow are replicated the number * of tiles in the file. These two fields holds the offset of the tile * in the data file and the size of the tile in the data file( both are in * shorts and not bytes); */ // 100 + t*8 // 4 // MSB Int32 // Offset to tile t in w001001.adf measured in two byte // shorts. // 104 + t*8 // 4 // MSB Int32 // Size of tile t in 2 byte shorts. }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimAigStatistics.h000066400000000000000000000011421352751253100251720ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigStatistics.h 9968 2006-11-29 14:01:53Z gpotts $ #ifndef ossimAigStatistics_HEADER #define ossimAigStatistics_HEADER #include class ossimAigStatistics { public: ossimAigStatistics(); void reset(); bool writeStream(std::ostream& out); double theMin; double theMax; double theMean; double theStandardDev; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimAlphaSensorSupportData.h000066400000000000000000000055511352751253100270350ustar00rootroot00000000000000#ifndef ossimAlphaSensorSupportData_HEADER #define ossimAlphaSensorSupportData_HEADER 1 #include #include #include #include #include #include class ossimEnviHeader; class OSSIM_DLL ossimAlphaSensorSupportData : public ossimObject { public: enum PolynomialDegrees { MAX_DEGREE = 10, MAX_TERMS = MAX_DEGREE + 1, SCAN_ANGLE_DEG = 2, ROLL_DEG = 7, PITCH_DEG = 5, HEADING_DEG = 4, LON_DEG = 2, LAT_DEG = 2, ALT_DEG = 2 }; ossimAlphaSensorSupportData(); virtual bool readSupportFiles(const ossimFilename& hdrFile); virtual bool readSupportFiles(const ossimEnviHeader& hdr); virtual bool readHdrFile(const ossimFilename& hdrFile); virtual bool readHdrFile(const ossimEnviHeader& hdr); virtual bool readInsGpsFile(const ossimFilename& txtFile); inline bool isHSI()const {return m_isHSI;} const ossimDpt& getImageSize()const; const ossim_float64& getRollBias()const; const ossim_float64& getPitchBias()const; const ossim_float64& getHeadingBias()const; const ossim_float64& getFov()const; const ossim_float64& getSlitRot()const; const std::vector< ossim_float64 >& getRollPoly()const; const std::vector< ossim_float64 >& getPitchPoly()const; const std::vector< ossim_float64 >& getHeadingPoly()const; const std::vector< ossim_float64 >& getLonPoly()const; const std::vector< ossim_float64 >& getLatPoly()const; const std::vector< ossim_float64 >& getAltPoly()const; const std::vector< ossim_float64 >& getScanPoly()const; protected: void reset(); ossimAlphaSensorSupportData(const ossimAlphaSensorSupportData& src); ossimAlphaSensorSupportData& operator =(const ossimAlphaSensorSupportData& src); bool m_isHSI; // hdr data ossimString m_sensorType; ossimDpt m_imageSize; ossim_float64 m_rollBias; ossim_float64 m_pitchBias; ossim_float64 m_headingBias; ossim_float64 m_fov; ossim_float64 m_slitRot; // insgps data std::vector< ossimPolynom::VAR_TUPLE > m_imgLine; std::vector< ossim_float64 > m_roll; std::vector< ossim_float64 > m_pitch; std::vector< ossim_float64 > m_heading; std::vector< ossim_float64 > m_lon; std::vector< ossim_float64 > m_lat; std::vector< ossim_float64 > m_alt; std::vector< ossim_float64 > m_scanAng; // insgps polynomials std::vector< ossim_float64 > m_rollPolyCoef; std::vector< ossim_float64 > m_pitchPolyCoef; std::vector< ossim_float64 > m_headingPolyCoef; std::vector< ossim_float64 > m_lonPolyCoef; std::vector< ossim_float64 > m_latPolyCoef; std::vector< ossim_float64 > m_altPolyCoef; std::vector< ossim_float64 > m_scanAngPolyCoef; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimApplanixEOFile.h000066400000000000000000000147351352751253100252330ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // License: MIT // // Author: Garrett Potts // //******************************************************************* // $Id$ #ifndef ossimApplanixEOFile_HEADER #define ossimApplanixEOFile_HEADER 1 #include #include #include #include #include #include #include class OSSIM_DLL ossimApplanixEORecord : public ossimReferenced { public: OSSIM_DLL friend std::ostream& operator <<(std::ostream& out, const ossimApplanixEORecord& src); ossimApplanixEORecord(const ossimApplanixEORecord& src) :theField(src.theField) { } ossimApplanixEORecord(ossim_uint32 size=0) { setSize(size); } void setSize(ossim_uint32 size) { theField.resize(size); } const ossimString& operator [](ossim_uint32 idx)const { return theField[idx]; } ossimString& operator [](ossim_uint32 idx) { return theField[idx]; } std::vector theField; }; class OSSIM_DLL ossimApplanixEOFile : public ossimReferenced { public: OSSIM_DLL friend std::ostream& operator <<(std::ostream& out, const ossimApplanixEOFile& src); ossimApplanixEOFile(); /** * Will parse the entire Exterior orientation file and then index any record * ID's found. This calls the parseStream method. * * @param file The exterior orientation file */ bool parseFile(const ossimFilename& file); /** * Will parse the stream and set internal queriable parameters. * @param inThe input stream containing the Applanix format exterior orientation file * */ bool parseStream(ossim::istream& in); /** * Utility method that just checks for an APPlanix exterior orientation header. * Will call the isEOFile(std::istream) method. * * @param file theExterior orientation file. */ bool isEOFile(const ossimFilename& file)const; /** * Utility method that just checks for an APPlanix exterior orientation header. */ bool isEOFile(ossim::istream& in)const; /** * Parses the header of the exterior orientation file. * Calls the parseHeader(std::istream, header) method. * * @param file The filename that is an Applanix Exterior orientation file. * @param header The resulting header that was parsed out. */ bool parseHeader(const ossimFilename& file, ossimString& header)const; /** * Parses the header of the exterior orientation file. * Calls the parseHeader(std::istream, header) method. * * @param in The input stream That contains an exterior orientation * @param header The resulting header that was parsed out. */ bool parseHeader(ossim::istream& in, ossimString& header)const; /** * Is a case insensitive parse of the column names for the orientation * record. Note this will check to see if the search key is contained * within any column heading. So if a Heading has something like * "ID MORE TEXT" then you can call this with just "ID" and get a match * * @param searchKey the substring to search for * @return The id of the column or -1 if can't find the column */ ossim_int32 getFieldIdxLike(const ossimString& searchKey)const; /** * Is a case insensitive parse of the column names for the orientation * record. Note this will check to see if the search key exactly matches * a column heading. So if a Heading has something like * "ID MORE TEXT" then you can call this with just "ID MORE TEXT" to have a match * * @param searchKey the substring to search for * * @return The id of the column or -1 if can't find the column */ ossim_int32 getFieldIdx(const ossimString& searchKey)const; /** * Will index all records based on the "ID #" field for fast searching. */ void indexRecordIds(); /** * Given an ID it will search and find an EO record that matches the ID. * * If the records are not indexed it will do a linear search on the record array. * * @param id The id of the record to find. * * @return The exterior orientation for that record. */ const ossimRefPtr getRecordGivenId(const ossimString& id)const; ossim_uint32 getNumberOfRecords()const; const ossimRefPtr getRecord(ossim_uint32 idx)const; bool isHeightAboveMSL()const; bool isEcefModel()const; bool isUtmFrame()const; ossim_int32 getUtmZone()const; ossimString getUtmHemisphere()const; ossimString getSbetField()const; double getBoreSightTx()const; double getBoreSightTy()const; double getBoreSightTz()const; double getLeverArmLx()const; double getLeverArmLy()const; double getLeverArmLz()const; double getKardinalKappa()const; double getShiftValuesX()const; double getShiftValuesY()const; double getShiftValuesZ()const; ossimString getMappingFrameDatum()const; ossimString getMappingFrameProjection()const; double getMappingFrameCentralMeridian()const; double getMappingFrameOriginLatitude()const; double getMappingFrameGridScaleFactor()const; double getMappingFrameFalseEasting()const; double getMappingFrameFalseNorthing()const; ossimString convertToOssimDatumCode(const ossimString& datum)const; protected: ossimString theHeader; ossimString theVersion; ossimString theBoreSightTx; ossimString theBoreSightTy; ossimString theBoreSightTz; ossimString theKappaCardinal; ossimString theLeverArmLx; ossimString theLeverArmLy; ossimString theLeverArmLz; ossimString theShiftValuesX; ossimString theShiftValuesY; ossimString theShiftValuesZ; ossimString theSbetField; ossimString theMappingFrameDatum; ossimString theMappingFrameProjection; ossimString theCentralMeridian; ossimString theOriginLatitude; ossimString theGridScaleFactor; ossimString theFalseEasting; ossimString theFalseNorthing; ossimString theUtmZone; ossimString theUtmHemisphere; ossim_float64 theMinLat; ossim_float64 theMinLon; ossim_float64 theMaxLat; ossim_float64 theMaxLon; std::vector theRecordFormat; std::vector< ossimRefPtr > theApplanixRecordList; std::map, ossimStringLtstr> theRecordIdMap; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimAuxFileHandler.h000066400000000000000000000115501352751253100252560ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: SPADAC Inc // Adaptd from the GDAL package hfa dataset // Description: This class provides some simple utilities for aux file. // //******************************************************************** // $Id: ossimAuxFileHandler.h 2644 2011-05-26 15:20:11Z oscar.kramer $ #ifndef ossimAuxFileHandler_HEADER #define ossimAuxFileHandler_HEADER #include #include #include #include #include #include #include #define EPT_u1 0 #define EPT_u2 1 #define EPT_u4 2 #define EPT_u8 3 #define EPT_s8 4 #define EPT_u16 5 #define EPT_s16 6 #define EPT_u32 7 #define EPT_s32 8 #define EPT_f32 9 #define EPT_f64 10 #define EPT_c64 11 #define EPT_c128 12 class ossimFilename; class ossimAuxEntry; class ossimAuxType; class ossimAuxDictionary; class ossimAuxInfo{ public: ossimAuxInfo(); virtual ~ossimAuxInfo(); FILE *fp; ossim_uint32 nEndOfFile; ossim_uint32 nRootPos; ossim_uint32 nDictionaryPos; ossim_int16 nEntryHeaderLength; ossim_int32 nVersion; ossimAuxEntry* m_Root; ossimAuxDictionary* m_Dictionary; char* dictionaryData; }; class ossimAuxEntry { ossim_uint32 nFilePos; ossimAuxInfo* m_auxInfo; ossimAuxEntry* m_Parent; ossimAuxEntry* m_Prev; ossimAuxEntry* m_Next; ossimAuxEntry* m_Child; ossim_uint32 nNextPos; ossim_uint32 nChildPos; char entryNodeName[64]; char entryType[32]; ossimAuxType* m_Type; ossim_uint32 nDataPos; ossim_uint32 nDataSize; char* entryData; void loadData(); int getFieldValue(const char* auxFieldPath, char chReqType, void *reqReturn); public: ossimAuxEntry( ossimAuxInfo* auxInfoIn, ossim_uint32 nPos, ossimAuxEntry* parentIn, ossimAuxEntry* prevIn); virtual ~ossimAuxEntry(); ossim_uint32 getFilePos() { return nFilePos; } const char* getName() { return entryNodeName; } void setName( const char *nodeName ); const char* getType() { return entryType; } char* getData() { loadData(); return entryData; } ossim_uint32 getDataPos() { return nDataPos; } ossim_uint32 getDataSize() { return nDataSize; } ossimAuxEntry* getChild(); ossimAuxEntry* getNext(); ossimAuxEntry* getNamedChild( const char * name); ossim_int16 getIntField( const char * auxFieldPath); const char* getStringField( const char * auxFieldPath); }; class ossimAuxField { public: int nBytes; int nItemCount; char chPointer; /* '\0', '*' or 'p' */ char chItemType; /* 1|2|4|e|... */ char *itemObjectType; /* if chItemType == 'o' */ ossimAuxType* m_auxItemObjectType; char** enumNames; /* normally NULL if not an enum */ char *fieldName; ossimAuxField(); ~ossimAuxField(); int extractInstValue( const char * auxField, int nIndexValue, char *entryData, ossim_uint32 nDataOffset, int nDataSize, char chReqType, void *reqReturn ); int getInstCount( char * entryData, int nDataSize ); int getInstBytes( char *entryData, int nDataSize ); const char* initialize( const char * fieldInput ); void completeDefn( ossimAuxDictionary * auxDict ); }; class ossimAuxType { public: int nBytes; int nFields; ossimAuxField** m_auxFields; char* auxTypeName; ossimAuxType(); ~ossimAuxType(); const char* initialize( const char * typeInput); void completeDefn( ossimAuxDictionary * auxDict); int getInstBytes(char *entryData, int nDataSize ); int extractInstValue( const char * auxField, char *entryData, ossim_uint32 nDataOffset, int nDataSize, char chReqType, void *reqReturn ); }; class ossimAuxDictionary { public: int nTypes; int nTypesMax; ossimAuxType** m_auxTypes; ossimAuxDictionary(const char *auxDictStr); ~ossimAuxDictionary(); ossimAuxType* findType( const char * name); void addType( ossimAuxType * type); static int getItemSize( char chType); }; class OSSIM_DLL ossimAuxFileHandler { public: ossimAuxFileHandler(); virtual ~ossimAuxFileHandler(); /** * @read .aux file */ bool isAuxFile(const ossimFilename& file); /** * @open the file for reading */ bool open(const ossimFilename& file); /** * Reads a single record from a aux file. * Returns true if succesful. Returns false if EOF or error. */ const ossimString& getProjectionName() const { return m_projName; } const ossimString& getDatumName() const { return m_datumName; } const ossimString& getUnitType() const { return m_unitsType; } private: ossimAuxInfo* m_auxInfo; ossimString m_projName; ossimString m_datumName; ossimString m_unitsType; }; #endif // #ifndef ossimAuxFileHandlerl_HEADER ossim-Miami-2.9.1/include/ossim/support_data/ossimAuxXmlSupportData.h000066400000000000000000000050411352751253100260260ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: See class description below. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimAuxXmlSupportData_HEADER #define ossimAuxXmlSupportData_HEADER 1 #include #include #include // Forward class declarations: class ossimDrect; class ossimFilename; class ossimProjection; class ossimString; class ossimXmlDocument; /** * @class ossimAuxXmlSupportData * * Utility/support data class to extract the projection from a dot aux dot xml * file commonly found with mrsid data. */ class OSSIM_DLL ossimAuxXmlSupportData { public: /** default constructor */ ossimAuxXmlSupportData(); /** virtual destructor */ virtual ~ossimAuxXmlSupportData(); /** * @brief Method to get a projection if possible. * @param file File name to open. * @return Projection pointer wrapped in ref pointer. Can be null if * projection cannot be established. */ ossimRefPtr getProjection(const ossimFilename& file) const; private: /** * @brief Gets path from doc and initializes string. * @param path Xml path to look for. * @param xdoc Xml doc to look in. * @param s String to initialize. * @return true on success and false if path is not found or if there * are more than one of path. */ bool getPath( const ossimString& path, const ossimXmlDocument& xdoc, ossimString& s ) const; /** * @brief Sets tie and scale. * @param xdoc Xml document. * @param wkt Well known tet string. * @return True on success, false on error. */ bool initializeProjection( const ossimXmlDocument xdoc, const std::string& wkt, ossimProjection* proj ) const; /** * @brief Get first parameter from PROJCS[ ... ] string. * @param wkt Well known tet string. * @param name Initialized by this with name if found. * @return true on success, false on error. */ bool getProjcsName( const std::string& wkt, std::string& name ) const; /** * @brief Gets units of Projected Coordinate System. * @param wkt Well known tet string. * @return Units. */ ossimUnitType getUnits( const std::string& wkt ) const; }; #endif /* End of "#ifndef ossimAuxXmlSupportData_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimCcfInfo.h000066400000000000000000000026651352751253100237410ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: CCF Info object. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimCcfInfo_HEADER #define ossimCcfInfo_HEADER #include #include #include #include class ossimNitfFile; /** * @brief NITF info class. * * Encapsulates the dumpnitf functionality. */ class OSSIM_DLL ossimCcfInfo : public ossimInfoBase { public: /** default constructor */ ossimCcfInfo(); /** virtual destructor */ virtual ~ossimCcfInfo(); /** * @brief open method. * * @param file File name to open. * * @return true on success false on error. */ virtual bool open(const ossimFilename& file); virtual bool open(std::shared_ptr& str, const std::string& connectionString); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; private: //ossimFilename theFile; mutable std::shared_ptr m_fileStr; std::string m_connectionString; }; #endif /* End of "#ifndef ossimCcfInfo_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimCeosData.h000066400000000000000000001615311352751253100241130ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // Description: // // Class for reading CEOS-formatted metadata. // //******************************************************************* // $Id:$ #ifndef ossimCeosData_HEADER #define ossimCeosData_HEADER #include #include #include #include struct desc_rec // Record description { ossim_int32 rec_seq; // Record sequence number (B4) ossim_uint8 rec_sub1; // First record sub-type code (B1) ossim_uint8 rec_type; // Record type code (B1) ossim_uint8 rec_sub2; // Second record sub-type code (B1) ossim_uint8 rec_sub3; // Third record sub-type code (B1) ossim_int32 length; // Length of this record, bytes (B4) }; struct vol_desc_rec // Volume descriptor record { struct desc_rec desc; // Record description char ascii_flag[2]; // ASCII flag (A2) char spare1[2]; // Unused (A2) char format_doc[12]; // Format control documentation (A12) char format_ver[2]; // Format doc version (A2) char format_rev[2]; // Format doc revision (A2) char software_id[12]; // Software identifier (A12) char phyvol_id[16]; // Physical volume identifier (A16) char logvol_id[16]; // Logical volume identifier (A16) char volset_id[16]; // Volume set identifier (A16) char phyvol_cnt[2]; // Total physical volume count (I2) char first_phyvol[2]; // Physical vol of first tape (I2) char last_phyvol[2]; // Physical vol of last tape (I2) char curr_phyvol[2]; // Physical vol of current tape (I2) char first_file[4]; // First file number in phyvol (I4) char volset_log[4]; // Logical volume within set (I4) char phyvol_log[4]; // Logical volume within phyvol (I4) char logvol_date[8]; // Logvol creation date (A8) char logvol_time[8]; // Logvol creation time (A8) char logvol_country[12]; // Logvol generation country (A12) char logvol_agency[8]; // Logvol generation agency (A8) char logvol_facility[12]; // Logvol generation facility (A12) char n_filepoint[4]; // Number of file pointer records (I4) char n_voldir[4]; // Number of voldir records (I4) char spare2[92]; // Unused (A92) char product_id[8]; // Product identifier (A8) char spare3[92]; // Local use segment (A92) }; struct file_pntr_rec // File pointer record { struct desc_rec desc; // Record description char ascii_flag[2]; // ASCII flag (A2) char spare1[2]; // Unused (A2) char file_num[4]; // Referenced file number (I4) char file_name[16]; // Referenced file name (A16) char file_class[28]; // Referenced file class (A28) char file_code[4]; // Referenced file class code (A4) char data_type[28]; // Referenced file data type (A28) char data_code[4]; // Referenced file data type code (A4) char nrec[8]; // Referenced file record count (I8) char first_len[8]; // First record length, bytes (I8) char max_len[8]; // Maximum record length, bytes (I8) char len_type[12]; // Record length type (A12) char len_code[4]; // Record length type code (A4) char first_phyvol[2]; // First physical volume (I2) char last_phyvol[2]; // Last physical volume (I2) char first_rec[8]; // First phyvol record (I8) char last_rec[8]; // Last phyvol record (I8) char spare2[100]; // Unused (A100) char spare3[100]; // Unused (A100) }; struct text_rec // Text record { struct desc_rec desc; // Record description char ascii_flag[2]; // ASCII flag (A2) char cont_flag[2]; // Continuation flag (A2) char product_type[40]; // Product type specifier (A40) char product_create[60]; // Product creation info (A60) char phyvol_id[40]; // Physical volume identifier (A40) char scene_id[40]; // Scene identifier (A40) char scene_loc[40]; // Scene location (A40) char copyright_info[20]; // Unused (A20) char spare2[104]; // Unused (A104) }; struct sar_desc_rec // SAR leader/trailer descriptor { struct desc_rec desc; // Record description char ascii_flag[2]; // ASCII flag (A2) char spare1[2]; // Unused (A2) char format_doc[12]; // Format control document (A12) char format_rev[2]; // Format document revision (A2) char design_rev[2]; // File design revision (A2) char software_id[12]; // Software identifier (A12) char file_num[4]; // File number (I4) char file_name[16]; // File name (A16) char rec_seq[4]; // Record sequence/location flag (A4) char seq_loc[8]; // Sequence number location (I8) char seq_len[4]; // Sequence number length (I4) char rec_code[4]; // Record code/location flag (A4) char code_loc[8]; // Record code location (I8) char code_len[4]; // Record code length (I4) char rec_len[4]; // Record length/location flag (A4) char rlen_loc[8]; // Record length location (I8) char rlen_len[4]; // Record length, bytes (I4) char spare2; // Reserved (A1) char spare3; // Reserved (A1) char spare4; // Reserved (A1) char spare5; // Reserved (A1) char spare6[64]; // Reserved segment (A64) char n_dataset[6]; // Number of dataset summary records (I6) char l_dataset[6]; // Data set summary record length, bytes (I6) char n_map_proj[6]; // Number of map proj records (I6) char l_map_proj[6]; // Map proj record length, bytes (I6) char n_plat_pos[6]; // Number of plat pos records (I6) char l_plat_pos[6]; // Plat pos record length, bytes (I6) char n_att_data[6]; // Number of att data records (I6) char l_att_data[6]; // Att data record length, bytes (I6) char n_radi_data[6]; // Number of radiometric data records (I6) char l_radi_data[6]; // Radi data record length, bytes (I6) char n_radi_comp[6]; // Number of radiometric compensation records (I6) char l_radi_comp[6]; // Radiometric compensation record length, bytes (I6) char n_qual_sum[6]; // Number of data qual sum records (I6) char l_qual_sum[6]; // Dat qual sum record length,bytes (I6) char n_data_hist[6]; // Number of data histogram records (I6) char l_data_hist[6]; // Data hist record length, bytes (I6) char n_rang_spec[6]; // Number of range spectra records (I6) char l_rang_spec[6]; // Range spectra record length, bytes (I6) char n_dem_desc[6]; // Number of DEM descriptor records (I6) char l_dem_desc[6]; // DEM desc record length, bytes (I6) char n_radar_par[6]; // Number of RADAR par records (I6) char l_radar_par[6]; // RADAR par record length, bytes (I6) char n_anno_data[6]; // Number of annotation data records (I6) char l_anno_data[6]; // Annotation data record length, bytes (I6) char n_det_proc[6]; // Number of processing parameter records (I6) char l_det_proc[6]; // Processing parameter record length, bytes (I6) char n_cal[6]; // Number of calibration records (I6) char l_cal[6]; // Calibration record length, bytes (I6) char n_gcp[6]; // Number of GCP records (I6) char l_gcp[6]; // GCP record length, bytes (I6) char spare7[10][6]; // Unused (I6) char n_fac_data[6]; // Number of facility data records (I6) char l_fac_data[6]; // Fac data record length, bytes (I6) char spare8[288]; // Unused (A288) }; struct dataset_sum_rec // Data set summary record { struct desc_rec desc; // Record description char seq_num[4]; // Sequence number (I4) char sar_chn[4]; // SAR channel indicator (I4) char scene_id[16]; // Scene identifier (A16) char scene_des[32]; // Scene designator (A32) char inp_sctim[32]; // Input scene centre time (A32) char asc_des[16]; // Ascending/descending (A16) char pro_lat[16]; // Processed scene centre latitude (F16.7) char pro_long[16]; // Processed scene centre longitude (F16.7) char pro_head[16]; // Processed scene centre headng (F16.7) char ellip_des[16]; // Ellipsoid designator (A16) char ellip_maj[16]; // Ellipsoid semi-major axis, km (F16.7) char ellip_min[16]; // Ellipsoid semi_minor axis, km (F16.7) char earth_mass[16]; // Earth's mass (E16.7) char grav_const[16]; // Gravitational constant (E16.7) char ellip_j[3][16]; // Ellipsoid J2-4 parameters (E16.7) char spare1[16]; // Unused (A16) char terrain_h[16]; // Average terrain height, km (F16.7) char sc_lin[8]; // Scene centre line number (I8) char sc_pix[8]; // Scene centre pixel number (I8) char scene_len[16]; // Scene length, km (F16.7) char scene_wid[16]; // Scene width, km (F16.7) char spare2[16]; // Unused (A16) char nchn[4]; // Number of SAR channels (I4) char spare3[4]; // Unused (A4) char mission_id[16]; // Mission identifier (A16) char sensor_id[32]; // Sensor identifier (A32) char orbit_num[8]; // Orbit number (A8) char plat_lat[8]; // Platform geodetic latitude (F8.3) char plat_long[8]; // Platform geodetic longitude (F8.3) char plat_head[8]; // Platform heading (F8.3) char clock_ang[8]; // Sensor clock angle (F8.3) char incident_ang[8]; // Incidence angle (F8.3) char spare4[8]; // Unused (A8) char wave_length[16]; // Radar wave length (F16.7) char motion_comp[2]; // Motion compensation indicator (A2) char pulse_code[16]; // Range pulse code specifier (A16) char ampl_coef[5][16]; // Range chirp coefficients (E16.7) char phas_coef[5][16]; // Range phase coefficients (E16.7) char chirp_ext_ind[8]; // Chirp extraction index (I8) char spare5[8]; // Unused (A8) char fr[16]; // Range sampling rate (F16.7) char rng_gate[16]; // Range gate start time (F16.7) char rng_length[16]; // Range pulse length (F16.7) char baseband_f[4]; // Baseband conversion flag (A4) char rngcmp_f[4]; // Range compressed flag (A4) char gn_polar[16]; // Like polarized gain (F16.7) char gn_cross[16]; // Cross polarized gain (F16.7) char chn_bits[8]; // Number of bits per channel (I8) char quant_desc[12]; // Quantization descriptor (A12) char i_bias[16]; // I channel DC bias (F16.7) char q_bias[16]; // Q channel DC bias (F16.7) char iq_ratio[16]; // I/Q channel ratio (F16.7) char spare6[16]; // Unused (F16.7) char spare7[16]; // Unused (F16.7) char ele_sight[16]; // Electronic boresight (F16.7) char mech_sight[16]; // Mechanical boresight (F16.7) char echo_track[4]; // Echo tracker on/off flag (A4) char fa[16]; // Nominal PRF, Hz (F16.7) char elev_beam[16]; // Elevation beamwidth (F16.7) char azim_beam[16]; // Azimuth beamwidth (F16.7) char sat_bintim[16]; // Satellite binary time (I16) char sat_clktim[32]; // Satellite clock time (I32) char sat_clkinc[8]; // Satellite clock increment (I8) char spare8[8]; // Unused (A8) char fac_id[16]; // Processing facility identifier (A16) char sys_id[8]; // Processing system identifier (A8) char ver_id[8]; // Processing version identifier (A8) char fac_code[16]; // Facility process code (A16) char lev_code[16]; // Product level code (A16) char prod_type[32]; // Product type specifier (A32) char algor_id[32]; // Processing algorithm identifier (A32) char n_azilok[16]; // Number of azimuth looks (F16.7) char n_rnglok[16]; // Number of range looks (F16.7) char bnd_azilok[16]; // Bandwidth per look in azimuth,Hz (F16.7) char bnd_rnglok[16]; // Bandwidth per look in range,Hz (F16.7) char bnd_azi[16]; // Total azimuth look bandwidth (F16.7) char bnd_rng[16]; // Total range look bandwidth (F16.7) char azi_weight[32]; // Azimuth weighting designator (A32) char rng_weight[32]; // Range weighting designator (A32) char data_inpsrc[16]; // Data input source (A16) char rng_res[16]; // Range resolution, meter (F16.7) char azi_res[16]; // Azimuth resolution, meter (F16.7) char radi_stretch[2][16]; // Radiometric stretch terms (F16.7) char alt_dopcen[3][16]; // Along track Doppler frequency terms (E16.7) char spare9[16]; // Unused (A16) char crt_dopcen[3][16]; // Cross track Doppler frequency terms (E16.7) char time_dir_pix[8]; // Pixel time direction indicator (A8) char time_dir_lin[8]; // Line time direction indicator (A8) char alt_rate[3][16]; // Along track Doppler rate term (E16.7) char spare10[16]; // Unused (A16) char crt_rate[3][16]; // Cross track Doppler rate term (E16.7) char spare11[16]; // Unused (A16) char line_cont[8]; // Line content indicator (A8) char clutter_lock[4]; // Clutter lock applied flag (A4) char auto_focus[4]; // Auto-focus applied flag (A4) char line_spacing[16]; // Line spacing, meters (F16.7) char pix_spacing[16]; // Pixel spacing, meters (F16.7) char rngcmp_desg[16]; // Range compression designator (A16) char spare12[2362]; // Unused (A2362) }; struct rad_unc_rec // Radiometric uncertainty record { char db[16]; // Units of db (F16.7) char deg[16]; // Units of deg (F16.7) }; struct misreg_rec // Misregistration record { char alt_m[16]; // Nominal along track misregistration (F16.7) char crt_m[16]; // Nominal cross track misregistration (F16.7) }; struct qual_sum_rec // Data quality summary record { struct desc_rec desc; // Record description char rec_seq[4]; // Record sequence number (I4) char sar_chn[4]; // SAR channel indicator (A4) char cali_date[6]; // Calibration update date (A6) char nchn[4]; // Number of channels (I4) char islr[16]; // Nominal integrated side lobe ratio (F16.7) char pslr[16]; // Nominal peak side lobe ratio (F16.7) char azi_ambig[16]; // Nominal azimuth ambiguity (F16.7) char rng_ambig[16]; // Nominal range ambiguity (F16.7) char snr[16]; // Nominal signal to noise ratio (F16.7) char ber[16]; // Nominal bit error rate (F16.7) char rng_res[16]; // Nominal slant range resolution (F16.7) char azi_res[16]; // Nominal azimuth resolution,meter (F16.7) char rad_res[16]; // Nominal radiometric resolution,dB (F16.7) char dyn_rng[16]; // Instantaneous dynamic range (F16.7) char rad_unc_db[16]; // Nominal radiometric uncertainty,dB (F16.7) char rad_unc_deg[16]; // Nominal Radiometric uncertainty,deg (F16.7) struct rad_unc_rec rad_unc[16]; // Radiometric data quality char alt_locerr[16]; // Nominal along track location error (F16.7) char crt_locerr[16]; // Nominal cross track location error (F16.7) char alt_scale[16]; // Nominal along track distortion scale (F16.7) char crt_scale[16]; // Nominal cross track distortion scale (F16.7) char dis_skew[16]; // Nominal distortion skew (F16.7) char ori_err[16]; // Nominal Scene orientation error (F16.7) struct misreg_rec misreg[16]; // Misregistration error char nesz[16]; // Nominal noise equivalent sigma zero (F16.7) char enl[16]; // Nominal equivalent number of looks (F16.7) char tb_update[8]; // Default parameters table update date (A8) char spare[238]; // Unused (A238) }; struct sdr_htab_rec // Histogram table record { char hist_desc[32]; // Histogram descriptor (A32) char nrec[4]; // Records per table (I4) char tab_seq[4]; // Table sequence number (I4) char nbin[8]; // Total number of table bins (I8) char ns_lin[8]; // Total number of lines (I8) char ns_pix[8]; // Total number of pixels per line (I8) char ngrp_lin[8]; // Group size along line axis (I8) char ngrp_pix[8]; // Group size along pixel axis (I8) char nsamp_lin[8]; // Number of samples used per group along line axis (I8) char nsamp_pix[8]; // Number of samples used per group along pixel (I8) char min_smp[16]; // Minimum first bin (E16.7) char max_smp[16]; // Maximum last bin (E16.7) char mean_smp[16]; // Mean sample value (E16.7) char std_smp[16]; // Sample standard deviation (E16.7) char smp_inc[16]; // Sample value increment (E16.7) char min_hist[16]; // Minimum histogram value (E16.7) char max_hist[16]; // Maximum histogram value (E16.7) char mean_hist[16]; // Histogram mean value (E16.7) char std_hist[16]; // Histogram standard deviation (E16.7) char nhist[8]; // Histogram table size (I8) char hist[256][8]; // 256 histogram table values of 16 bins // I x 16 bins Q (I8) }; struct sdr_hist_rec // Data histogram record { struct desc_rec desc; // Record description char rec_seq[4]; // Record sequence number (I4) char sar_chn[4]; // SAR channel number (I4) char ntab[8]; // Number of histogram table data sets in this record (I8) char ltab[8]; // Histogram table data set size (I8) struct sdr_htab_rec htab; // Histogram tables char spare[14588]; // Unused (A14588) }; struct pdr16_htab_rec // Histogram table record { char hist_desc[32]; // Histogram descriptor (A32) char nrec[4]; // Records per table (I4) char tab_seq[4]; // Table sequence number (I4) char nbin[8]; // Total number of table bins (I8) char ns_lin[8]; // Total number of lines n (I8) char ns_pix[8]; // Total number of pixels per line (I8) char ngrp_lin[8]; // Group size along line axis (I8) char ngrp_pix[8]; // Group size along pixel axis (I8) char nsamp_lin[8]; // Number of samples used per group along line axis (I8) char nsamp_pix[8]; // Number of samples used per group along pixel (I8) char min_smp[16]; // Minimum first bin (E16.7) char max_smp[16]; // Maximum last bin (E16.7) char mean_smp[16]; // Mean sample value (E16.7) char std_smp[16]; // Sample standard deviation (E16.7) char smp_inc[16]; // Sample value increment (E16.7) char min_hist[16]; // Minimum histogram value (E16.7) char max_hist[16]; // Maximum histogram value (E16.7) char mean_hist[16]; // Histogram mean value (E16.7) char std_hist[16]; // Histogram standard deviation (E16.7) char nhist[8]; // Histogram table size (I8) char hist[1024][8]; // 1024 histogram table values for 1024 bins // (I8) }; struct pdr16_hist_rec // Data histogram record { struct desc_rec desc; // Record description char rec_seq[4]; // Record sequence number (I4) char sar_chn[4]; // SAR channel number (I4) char ntab[8]; // Number of histogram table data sets in this record (I8) char ltab[8]; // Histogram table data set size (I8) struct pdr16_htab_rec htab[2];// Histogram tables char spare[3]; // Unused (A3) }; struct pix_count_rec // Beam pixel count record { char pix_update[21]; // Pixel count update date/time (A21) char n_pix[4][8]; // Count of image pixels in beams (4I8) }; struct beam_info_rec // Beam information record { char beam_type[3]; // Beam type (A3) char beam_look_src[9]; // Elevation beam look angle source (A9) char beam_look_ang[16]; // Applied elevation beam look angle (deg) (F16.7) char prf[16]; // Actual PRF (Hz) (F16.7) }; struct temp_rec // Temperature settings record { char temp_set[4][4]; // Temperature settings (4I4) }; struct dopcen_est_rec { char dopcen_conf[16]; // Doppler centroid confidence measure (F16.7) char dopcen_ref_tim[16]; // Doppler centroid reference time (sec) (F16.7) char dopcen_coef[4][16]; // Doppler centroid coefficients (4F16.7) }; struct srgr_coefset_rec { char srgr_update[21]; // SRGR update date/time (A21) char srgr_coef[6][16]; // SRGR coefficients (6F16.7) }; struct proc_parm_rec // Detailed processing parameters record { struct desc_rec desc; // Record description char rec_seq[4]; // Record sequence number (I4) char spare1[4]; // Unused (A4) char inp_media[3]; // Input media (A3) char n_tape_id[4]; // Number of tape input ids (I4) char tape_id[10][8]; // Tape identifiers (10A8) char exp_ing_start[21]; // Expected ingest start time (A21) char exp_ing_stop[21]; // Expected ingest stop time (A21) char act_ing_start[21]; // Actual ingest start time (A21) char act_ing_stop[21]; // Actual ingest stop time (A21) char proc_start[21]; // Processing start time (A21) char proc_stop[21]; // Processing stop time (A21) char mn_sig_lev[10][16]; // Mean signal levels across range (10F16.7) char scr_data_ind[4]; // Source data quality indicator (I4) char miss_ln[8]; // Number of missing lines (I8) char rej_ln[8]; // Number of rejected lines (I8) char large_gap[8]; // Number of time inconsistencies (large gaps) (I8) char bit_err_rate[16]; // Measured bit error rate (E16.7) char fm_crc_err[16]; // Percent of frames with CRC errors (E16.7) char date_incons[8]; // Number of date inconsistencies (I8) char prf_changes[8]; // Number of unexpected PRF changes (I8) char delay_changes[8]; // Number of delay changes (I8) char skipd_frams[8]; // Number of skipped frames (I8) char rej_bf_start[8]; // Range lines rejected before start time (I8) char rej_few_fram[8]; // Range lines rejected due to too few frames (I8) char rej_many_fram[8]; // Range lines rejected due to too many frames (I8) char rej_mchn_err[8]; // Frames rejected due to master channel error (I8) char rej_vchn_err[8]; // Frames rejected due to virtual channel error (I8) char rej_rec_type[8]; // Frames rejected due to incorrect recording type (I8) char sens_config[10]; // Sensor configuration (A10) char sens_orient[9]; // Sensor orientation (A9) char sych_marker[8]; // Frame synch marker (I8) char rng_ref_src[12]; // Range reference function source (A12) char rng_amp_coef[4][16]; // Range reference amplitude coefficients (4E16.7) char rng_phas_coef[4][16]; // Range reference phase coefficients (4E16.7) char err_amp_coef[4][16]; // Error function amplitude coefficients (4E16.7) char err_phas_coef[4][16]; // Error function phase coefficients (4E16.7) char pulse_bandw[4]; // Pulse bandwidth code (I4) char adc_samp_rate[5]; // ADC sampling rate (I5) char rep_agc_attn[16]; // Replica AGC attenuation (F16.7) char gn_corctn_fctr[16]; // Gain correction factor (dB) (F16.7) char rep_energy_gn[16]; // Replica energy gain correction (F16.7) char orb_data_src[11]; // Orbit data source (A11) char pulse_cnt_1[4]; // Pulse count 1 (I4) char pulse_cnt_2[4]; // Pulse count 2 (I4) char beam_edge_rqd[3]; // Beam edge detection requested (A3) char beam_edge_conf[16]; // Beam edge confidence measure (F16.7) char pix_overlap[4]; // Number of pixels in beam overlap (I4) char n_beams[4]; // Number of beams (I4) struct beam_info_rec beam_info[4]; // Beam info char n_pix_updates[4]; // Number of pixel count updates (I4) struct pix_count_rec pix_count[20]; // Beam pixel counts char pwin_start[16]; // Processing window start time (sec) (F16.7) char pwin_end[16]; // Processing window end time (sec) (F16.7) char recd_type[9]; // Recording type (A9) char temp_set_inc[16]; // Time increment between temperature settings (sec) (F16.7) char n_temp_set[4]; // Number of temperature settings (I4) struct temp_rec temp[20]; // Temperature settings char n_image_pix[8]; // Number of image pixels (I8) char prc_zero_pix[16]; // Percent zero pixels (F16.7) char prc_satur_pix[16]; // Percent saturated pixels (F16.7) char img_hist_mean[16]; // Image histogram mean intensity (F16.7) char img_cumu_dist[3][16]; // Image cumulative distribution (3F16.7) char pre_img_gn[16]; // Pre-image calibration gain factor (F16.7) char post_img_gn[16]; // Post-image calibration gain factor (F16.7) char dopcen_inc[16]; // Time increment between Dopcen estimates (sec) (F16.7) char n_dopcen[4]; // Number of Doppler centroid estimates (I4) struct dopcen_est_rec dopcen_est[20]; // Doppler centroid estimates char dop_amb_err[4]; // Doppler ambiguity error (I4) char dopamb_conf[16]; // Doppler ambiguity confidence measure (F16.7) char eph_orb_data[7][16]; // Ephemeris orbit data (7E16.7) char appl_type[12]; // Application type (A12) char slow_time_coef[5][22]; // Slow time coefficients (5D22.15) char n_srgr[4]; // Number of SRGR coefficient sets (I4) struct srgr_coefset_rec srgr_coefset[20]; // SRGR coefficient sets char pixel_spacing[16]; // SGF product pixel spacing (F16.7) char gics_reqd[3]; // GICS product required (A3) char wo_number[8]; // Work order identifier (A8) char wo_date[20]; // Work order entry date (A20) char satellite_id[10]; // Satellite identifier (A10) char user_id[20]; // User id (A20) char complete_msg[3]; // Completion message required flag (A3) char scene_id[15]; // SGF product scene identifier (A15) char density_in[4]; // Density of SGF product media (A4) char media_id[8]; // SGF product identifier (A8) char angle_first[16]; // Incidence angle of first pixel in SGF product line (F16.7) char angle_last[16]; // Incidence angle of last pixel in SGF product line (F16.7) char prod_type[3]; // GICS output product type (A3) char map_system[16]; // Map system identifier (A16) char centre_lat[22]; // GICS output product scene centre latitude (D22.15) char centre_long[22]; // GICS output product scene centre longitude (D22.15) char span_x[22]; // GICS output product size - map eastings (km) (D22.15) char span_y[22]; // GICS output product size - map northings (km) (D22.15) char apply_dtm[3]; // DTM correction to be applied flag (A3) char density_out[4]; // GICS output product density (A4) char state_time[21]; // Time of the first state vector (A21) char num_state_vectors[4]; // Number of state vectors (I4) char state_time_inc[16]; // Time increment between state vectors (F16.7) char spare2[206]; // Unused (A207) }; struct map_proj_rec // Map projection data record { struct desc_rec desc; // Record description char spare1[16]; // Unused (A16) char map_desc[32]; // Map projection descriptor (A32) char n_pixel[16]; // Pixels per line (I16) char n_line[16]; // Lines per processed band (I16) char pixel_spacing[16]; // Inter-pixel distance (F16.7) char line_spacing[16]; // Inter-line distance (F16.7) char osc_orient[16]; // Output scene cntr orientation (F16.7) char orb_incl[16]; // Orbital inclination (F16.7) char asc_node[16]; // Ascending node (F16.7) char isc_dist[16]; // Input scene cntr plat dist (F16.7) char geo_alt[16]; // Geodedic platform altitude (F16.7) char isc_vel[16]; // Ground speed at input scene (F16.7) char plat_head[16]; // Platform heading (F16.7) char ref_ellip[32]; // Reference ellipsoid name (A32) char semi_major[16]; // Ellipsoid semi-major axis (F16.7) char semi_minor[16]; // Ellipsoid semi-minor axis (F16.7) char datum_shift[3][16]; // Datum shift parameters (F16.7) char aux_datum_shift[3][16];// Aux datum shift parameters (F16.7) char scal_ellip[16]; // Ellisoid scale factor (F16.7) char proj_desc[32]; // Map projection description (A32) char utm_desc[32]; // UTM descriptor (A32) char utm_zone_sig[4]; // UTM zone signature (A4) char utm_east_orig[16]; // Map origin, false easting (F16.7) char utm_north_orig[16]; // Map origin, false northing (F16.7) char utm_cent_long[16]; // Projection centre longitude (F16.7) char utm_cent_lat[16]; // Projection centre latitude (F16.7) char utm_stand_par[2][16]; // Standard parallels (F16.7) char utm_scale[16]; // Scale factor (F16.7) char ups_desc[32]; // UPS descriptor (A32) char ups_cent_long[16]; // Projection centre longitude (F16.7) char ups_cent_lat[16]; // Projection centre latitude (F16.7) char ups_scale[16]; // Scale factor (F16.7) char nsp_desc[32]; // NSP descriptor (A32) char nsp_east_orig[16]; // Map origin, false easting (F16.7) char nsp_north_orig[16]; // Map origin, false northing (F16.7) char nsp_cent_long[16]; // Projection centre longitude (F16.7) char nsp_cent_lat[16]; // Projection centre latitude (F16.7) char nsp_stand_par[4][16]; // Standard parallels (F16.7) char nsp_stand_mer[3][16]; // Standard meridians (F16.7) char nsp_spare[4][16]; // Project dependent (4A16) char corner_ne[8][16]; // Corner northing/easting (F16.7) char corner_ll[8][16]; // Corner latitude/longitude (F16.7) char terr_height[4][16]; // Corner terrain height (F16.7) char lp_conv_coef[8][20]; // Line/pixel coefficients (E20.10) char mp_conv_coef[8][20]; // Map proj coefficients (E20.10) char dem_type[4]; // DEM type (A4) char spare3[32]; // Unused (A32) }; struct pos_vect_rec // Position vector record { char pos[3][22]; // Data point position (D22.15) char vel[3][22]; // Data point velocity (D22.15) }; struct pos_data_rec // Platform position data record { struct desc_rec desc; // Record description char orbit_ele_desg[32]; // Orbital elements designator (A32) char orbit_ele[6][16]; // Orbital elements (F16.7) char ndata[4]; // Number of data points (I4) char year[4]; // Year of data point (I4) char month[4]; // Month of data point (I4) char day[4]; // Day of data point (I4) char gmt_day[4]; // Day of year (I4) char gmt_sec[22]; // Seconds of day (D22.15) char data_int[22]; // Data sampling interval (D22.15) char ref_coord[64]; // Reference coordinate system (A64) char hr_angle[22]; // Greenwich mean hour angle (D22.15) char alt_poserr[16]; // Along track position error (F16.7) char crt_poserr[16]; // Cross track position error (F16.7) char rad_poserr[16]; // Radial position error (F16.7) char alt_velerr[16]; // Along track velocity error (F16.7) char crt_velerr[16]; // Cross track velocity error (F16.7) char rad_velerr[16]; // Radial velocity error (F16.7) struct pos_vect_rec pos_vect[64]; // Data point position/velocity char spare[126]; // Unused (A126) }; struct att_vect_rec // Attitude point record { char gmt_day[4]; // Day of the year, GMT (I4) char gmt_sec[8]; // Milliseconds of day, GMT (I8) char pitch_flag[4]; // Pitch data quality flag (I4) char roll_flag[4]; // Roll data quality flag (I4) char yaw_flag[4]; // Yaw data quality flag (I4) char pitch[14]; // Pitch error, degrees (E14.6) char roll[14]; // Roll error, degrees (E14.6) char yaw[14]; // Yaw error, degrees (E14.6) char pitch_rate_flag[4]; // Pitch rate data quality flag (I4) char roll_rate_flag[4]; // Roll rate data quality flag (I4) char yaw_rate_flag[4]; // Yaw rate data quality flag (I4) char pitch_rate[14]; // Pitch rate, degrees/sec (E14.6) char roll_rate[14]; // Roll rate, degrees/sec (E14.6) char yaw_rate[14]; // Yaw rate, degrees/sec (E14.6) }; struct att_data_rec // Attitude data record { struct desc_rec desc; // Record description char npoint[4]; // Number of data points (I4) struct att_vect_rec att_vect[20]; // Data points char pitch_bias[14]; // Pitch bias (degrees) (E14.6) char roll_bias[14]; // Roll bias (degrees) (E14.6) char yaw_bias[14]; // Yaw bias (degrees) (E14.6) char spare[6502]; // Unused (A6502) }; struct radi_dset_rec // Radiometric data set record { char chan_ind[4]; // SAR channel indicator (A4) char spare1[4]; // Unused (A4) char table_desig[24]; // Table designator (A24) char n_samp[8]; // Number of lookup table samples (I8) char samp_type[16]; // Sample type designator (A16) char samp_inc[4]; // Increment between table entries, range samples (I4) char lookup_tab[512][16]; // Output scaling gain table (E16.7) char spare2[4]; // Unused (A4) char noise_scale[16]; // Thermal noise reference level (F16.7) char spare3[16]; // Unused (A16) char offset[16]; // Scaling offset (E16.7) char calib_const[16]; // Calibration constant (E16.7) }; struct radi_data_rec // Radiometric data record { struct desc_rec desc; // Record description char seq_num[4]; // Record sequence number (I4) char n_data[4]; // Number of data fields (I4) char field_size[8]; // Field size in bytes (I8) struct radi_dset_rec dset[1]; // Radiometric data set records char spare1[1512]; // Unused (A1512) }; struct comp_dset_rec // Compensation data set record { char comp_desig[8]; // Compensation data designator (A8) char comp_descr[32]; // Compensation data descriptor (A32) char n_comp_rec[4]; // Number of compensation records (I4) char comp_seq_no[4]; // Compensation record sequence number (I4) char beam_tab_size[8]; // Number of beam table entries (I8) char beam_tab[256][16]; // Elevation gain beam profile (256F16.7) char beam_type[16]; // Beam type (A16) char look_angle[16]; // Look angle of beam table centre (F16.7) char beam_tab_inc[16]; // Increment between beam table entries (F16.7) }; struct radi_comp_rec // Radiometric compensation data record { struct desc_rec desc; // Record description char seq_num[4]; // Record sequence number (I4) char chan_ind[4]; // SAR channel indicator (A4) char n_dset[8]; // Number of data sets in record (I8) char dset_size[8]; // Compensation data set size (I8) struct comp_dset_rec dset[4]; // Compensation data set records }; struct imop_desc_rec // Image options file descriptor { struct desc_rec desc; // Record description char ascii_flag[2]; // ASCII flag (A2) char spare1[2]; // Unused (A2) char format_doc[12]; // Format control document (A12) char format_rev[2]; // Format document revision (A2) char design_rev[2]; // File design revision (A2) char software_id[12]; // Software identifier (A12) char file_num[4]; // File number (I4) char file_name[16]; // File name (A16) char rec_seq[4]; // Record sequence/location flag (A4) char seq_loc[8]; // Sequence number location (I8) char seq_len[4]; // Sequence number length (I4) char rec_code[4]; // Record code/location flag (A4) char code_loc[8]; // Record code location (I8) char code_len[4]; // Record code length (I4) char rec_len[4]; // Record length/location flag (A4) char rlen_loc[8]; // Record length location (I8) char rlen_len[4]; // Record length length (I4) char spare2[4]; // Reserved (4A1) char spare3[64]; // Reserved segment (A64) char n_dataset[6]; // Number of SAR data records (I6) char l_dataset[6]; // SAR data record length (I6) char spare4[24]; // Unused (A24) char nbit[4]; // Number of bits per sample (I4) char nsamp[4]; // Samples per data group (I4) char nbyte[4]; // Bytes per data group (I4) char justify[4]; // Sample justification and order (A4) char nchn[4]; // Number of SAR channels (I4) char nlin[8]; // Lines per data set (I8) char nleft[4]; // Left border pixels per line (I4) char ngrp[8]; // Groups per line per channel (I8) char nright[4]; // Right border pixels per line (I4) char ntop[4]; // Top border lines (I4) char nbott[4]; // Bottom border lines (I4) char intleav[4]; // Interleave indicator (A4) char nrec_lin[2]; // Number of physical records per line (I2) char nrec_chn[2]; // Number of physical records per multi-channel line in this file (I2) char n_prefix[4]; // Number of bytes of prefix data per record (I4) char n_sar[8]; // Number of bytes of SAR data (or pixel data) per record (I8) char n_suffix[4]; // Number of bytes of suffix data per record (I4) char spare5[4]; // Unused (A4) char lin_loc[8]; // Line number locator (A8) char chn_loc[8]; // Channel number locator (A8) char tim_loc[8]; // Time locator (A8) char left_loc[8]; // Left fill locator (A8) char right_loc[8]; // Right fill locator (A8) char pad_ind[4]; // Pad pixel indicator (A4) char spare6[28]; // Unused (A28) char qual_loc[8]; // Quality code locator (A8) char cali_loc[8]; // Calibration info locator (A8) char gain_loc[8]; // Gain value locator (A8) char bias_loc[8]; // Bias value locator (A8) char type_id[28]; // Data type identifier (A28) char type_code[4]; // Data type code (A4) char left_fill[4]; // Number of left fill bits (I4) char right_fill[4]; // Number of right fill bits (I4) char pix_rng[8]; // Maximum data range of pixel (I8) char spare7[15804]; // Unused (A15804) }; struct acq_date_rec // Acquisition date/time { ossim_int32 acq_year; // Acquisition year (B4) ossim_int32 acq_day; // Acquisition day of year (B4) ossim_int32 acq_msec; // Acquisition msecs of day (B4) }; struct sdr_prefix_rec // Signal data prefix data { ossim_int32 line_num; // Image data line number (B4) ossim_int32 rec_num; // Image data record index (B4) ossim_int32 n_left_pixel; // Left fill pixel count (B4) ossim_int32 n_data_pixel; // Data pixel count (B4) ossim_int32 n_right_pixel; // Right fill pixel count. (B4) ossim_int32 sensor_updf; // Sensor parameter update flag (B4) struct acq_date_rec acq_date; // Acquisition date ossim_int16 sar_chan_ind; // SAR channel indicator (B2) ossim_int16 sar_chan_code; // SAR channel code (B2) ossim_int16 tran_polar; // Transmitted polarization (B2) ossim_int16 recv_polar; // Received polarization (B2) ossim_int32 prf; // Pulse repetition frequency, Hz (B4) ossim_uint8 spare1[4]; // Unused (B4) ossim_int16 obrc; // On-board range compressed flag (B2) ossim_int16 pulse_type; // Pulse type designator (B2) ossim_int32 chp_len; // Chirp length, ns (B4) ossim_int32 chp_coef1; // Chirp constant coefficient,Hz (B4) ossim_int32 chp_coef2; // Chirp linear coefficient,Hz/usec (B4) ossim_int32 chp_coef3; // Chirp quadratic coefficient,Hz/usec^2 (B4) ossim_uint8 spare2[2][4]; // Spare (2B4) ossim_int32 recv_gain; // Receiver gain (B4) ossim_int32 nt_line; // Nought line flag (B4) ossim_int32 ele_nadir; // Elec. nadir angle, 10**-6 deg (B4) ossim_int32 mec_nadir; // Mech. nadir angle, 10**-6 deg (B4) ossim_int32 ele_squint; // Elec. squint angle, 10**-6 deg (B4) ossim_int32 mec_squint; // Mech. squint angle, 10**-6 deg (B4) ossim_int32 sr_first; // First sample slant range, m (B4) ossim_int32 dr_window; // Data record window time, ns (B4) ossim_uint8 spare3[4]; // Spare (B4) ossim_int32 plat_updf; // Platform position update flag (B4) ossim_int32 plat_lat; // Platform latitude, 10**-6 deg (B4) ossim_int32 plat_long; // Platform longitude, 10**-6 deg (B4) ossim_int32 plat_alt; // Platform altitude, m (B4) ossim_int32 plat_speed; // Platform speed, cm/s (B4) ossim_int32 plat_vel[3]; // Platform velocity, cm/s (3B4) ossim_int32 plat_acc[3]; // Platform acceleration, cm/s (3B4) ossim_int32 plat_track; // Platform track, 10**-6 deg (B4) ossim_int32 plat_head; // Platform heading, 10**-6 deg (B4) ossim_int32 plat_pitch; // Platform pitch, 10**-6 deg (B4) ossim_int32 plat_roll; // Platform roll, 10**-6 deg (B4) ossim_int32 plat_yaw; // Platform yaw, 10**-6 deg (B4) }; struct sdr_data_rec // Signal data record { struct desc_rec desc; // Record description struct sdr_prefix_rec prefix; // Prefix data ossim_uint8 sdr_data; // SAR signal data (jBk) }; struct pdr_prefix_rec // Processed data prefix data { ossim_int32 line_num; // Image data line number (B4) ossim_int32 rec_num; // Image data record index (B4) ossim_int32 n_left_pixel; // Left fill pixel count (B4) ossim_int32 n_data_pixel; // Data pixel count (B4) ossim_int32 n_right_pixel; // Right fill pixel count (B4) ossim_int32 sensor_updf; // Sensor parameter update flag (B4) struct acq_date_rec acq_date; // Acquisition date ossim_int16 sar_chan_ind; // SAR channel indicator (B2) ossim_int16 sar_chan_code; // SAR channel code (B2) ossim_int16 tran_polar; // Transmitted polarization (B2) ossim_int16 recv_polar; // Received polarization (B2) ossim_int32 prf; // Pulse repetition frequency, Hz (B4) ossim_uint8 spare1[4]; // Unused (B4) ossim_int32 sr_first; // Slant range to first pixel, m (B4) ossim_int32 sr_mid; // Slant range to mid-pixel, m (B4) ossim_int32 sr_last; // Slant range to last pixel, m (B4) ossim_int32 fdc_first; // First pixel Doppler centroid, Hz (B4) ossim_int32 fdc_mid; // Mid-pixel Doppler centroid, Hz (B4) ossim_int32 fdc_last; // Last pixel Doppler centroid, Hz (B4) ossim_int32 ka_first; // First pixel azimuth FM rate, Hz (B4) ossim_int32 ka_mid; // Mid-pixel azimuth FM rate, Hz (B4) ossim_int32 ka_last; // Last pixel azimuth FM rate, Hz (B4) ossim_int32 nadir_ang; // Nadir look angle, 10**-6 deg (B4) ossim_int32 squint_ang; // Azimuth squint angle, 10**-6 deg (B4) ossim_int32 null_f; // Null line flag - 1 for NULL line, 0 for otherwise (B4) ossim_uint8 spare2[4][4]; // Unused (4B4) ossim_int32 geo_updf; // Geographic parameter update flag (B4) ossim_int32 lat_first; // First pixel latitude, millionths of deg (B4) ossim_int32 lat_mid; // Mid-pixel latitude (B4) ossim_int32 lat_last; // Last pixel latitude (B4) ossim_int32 long_first; // First pixel longitude, millionths of deg (B4) ossim_int32 long_mid; // Mid pixel longitue (B4) ossim_int32 long_last; // Last pixel longitude (B4) ossim_int32 north_first; // Northing of first pixel, m (B4) ossim_uint8 spare3[4]; // Unused (B4) ossim_int32 north_last; // Northing of last pixel, m (B4) ossim_int32 east_first; // Easting of first pixel, m (B4) ossim_uint8 spare4[4]; // Spare (B4) ossim_int32 east_last; // Easting of last pixel, m (B4) ossim_int32 heading; // Line heading, millionths of deg (B4) ossim_uint8 spare5[8]; // Unused (B8) }; struct pdr_data_rec // Processed data record { struct desc_rec desc; // Record description struct pdr_prefix_rec prefix; // Prefix data }; struct pdr8_htab_rec // Histogram table record { char hist_desc[32]; // Histogram descriptor (A32) char nrec[4]; // Records per table (I4) char tab_seq[4]; // Table sequence number (I4) char nbin[8]; // Total number of table bins (I8) char ns_lin[8]; // Total number of pixels in line direction (I8) char ns_pix[8]; // Total number of lines (I8) char ngrp_lin[8]; // Group size along pixel axis (I8) char ngrp_pix[8]; // Group size along line axis (I8) char nsamp_lin[8]; // Number of samples used per group along pixel axis (I8) char nsamp_pix[8]; // Number of samples used per group along line (I8) char min_smp[16]; // Minimum first bin (E16.7) char max_smp[16]; // Maximum last bin (E16.7) char mean_smp[16]; // Mean sample value (E16.7) char std_smp[16]; // Sample standard deviation (E16.7) char smp_inc[16]; // Sample value increment (E16.7) char min_hist[16]; // Minimum histogram value (E16.7) char max_hist[16]; // Maximum histogram value (E16.7) char mean_hist[16]; // Histogram mean value (E16.7) char std_hist[16]; // Histogram standard deviation (E16.7) char nhist[8]; // Histogram table size (I8) char hist[256][8]; // 256 histogram table values for 256 bins (I8) }; struct pdr8_hist_rec // Data histogram record { struct desc_rec desc; // Record description char rec_seq[4]; // Record sequence number (I4) char sar_chn[4]; // SAR channel number (I4) char ntab[8]; // Num hist. table data sets in record (I8) char ltab[8]; // Histogram table data set size (I8) struct pdr8_htab_rec htab; // Histogram tables char spare[14588]; // Unused (A14588) }; struct null_vol_rec // Null volume descriptor record { struct desc_rec desc; // Record description char ascii_flag[2]; // ASCII flag (A2) char spare1[2]; // Unused (A2) char format_doc[12]; // Format control doc (A12) char format_ver[2]; // Format doc version (A2) char format_rev[2]; // Format doc revision (A2) char software_id[12]; // Software identifier (A12) char tape_id[16]; // Physical tape id (A16) char logvol_id[16]; // Logical volume id (A16) char phyvol_id[16]; // Physical volume id (A16) char n_phyvol[2]; // Total physical volume count (I2) char first_phyvol[2]; // First physical volume (I2) char last_phyvol[2]; // Last physical volume (I2) char curr_phyvol[2]; // Current physical volume (I2) char first_file[4]; // First file in volume (I4) char volset_log[4]; // Logical volume within set (I4) char logvol_vol[4]; // Logical volume within phyvol (I4) char spare2[248]; // Unused (A248) }; struct VolumeDirectoryFile { vol_desc_rec volDescRec; file_pntr_rec leaderFilePntrRec; file_pntr_rec imageOptionsFilePntrRec; file_pntr_rec trailerFilePntrRec; text_rec textRec; }; struct SarLeaderFile { sar_desc_rec sarDescRec; dataset_sum_rec dataSetSumRec; qual_sum_rec qualSumRec; sdr_hist_rec sdrHistRec; pdr16_hist_rec pdr16HistRec; proc_parm_rec procParmRec; map_proj_rec mapProjRec; pos_data_rec posDataRec; att_data_rec attDataRec; radi_data_rec radiDataRec; radi_comp_rec radiCompRec; }; struct SarTrailerFile { sar_desc_rec sarDescRec; dataset_sum_rec dataSetSumRec; qual_sum_rec qualSumRec; sdr_hist_rec sdrHistRec; pdr8_hist_rec pdr8HistRec; proc_parm_rec procParmRec; att_data_rec attDataRec; radi_data_rec radiDataRec; radi_comp_rec radiCompRec; }; class ossimCeosData : public ossimReferenced { public: enum ErrorStatus { OK = 0, ERROR }; ossimCeosData(const ossimFilename& volDirFile, const ossimFilename& leaderFile, const ossimFilename& imageFile, const ossimFilename& trailerFile); ossimCeosData(const ossimFilename& imageDir); bool errorStatus() const { return theErrorStatus; } const ossimFilename& volDirFile() const { return theVolDirFileName; } const ossimFilename& leaderFile() const { return theLeaderFileName; } const ossimFilename& imageFile() const { return theImageFileName; } const ossimFilename& trailerFile() const { return theTrailerFileName; } const vol_desc_rec* volDescRec() const { return theVolDescRec; } const text_rec* textRec() const { return theTextRec; } const imop_desc_rec* imopDescRec() const { return &theImopDescRec; } const dataset_sum_rec* dataSetSumRec() const { return theDataSetSumRec; } const qual_sum_rec* qualSumRec() const { return theQualSumRec; } const sdr_hist_rec* sdrHistRec() const { return theSdrHistRec; } const pdr16_hist_rec* pdr16HistRec() const { return thePdr16HistRec; } const pdr8_hist_rec* pdr8HistRec() const { return thePdr8HistRec; } const proc_parm_rec* procParmRec() const { return theProcParmRec; } const map_proj_rec* mapProjRec() const { return theMapProjRec; } const pos_data_rec* posDataRec() const { return thePosDataRec; } const att_data_rec* attDataRec() const { return theAttDataRec; } const radi_data_rec* radiDataRec() const { return theRadiDataRec; } const radi_comp_rec* radiCompRec() const { return theRadiCompRec; } void dump(std::ostream& strm = std::clog) const; void dumpVolDescRec (std::ostream&) const; void dumpTextRec (std::ostream&) const; void dumpImopDescRec (std::ostream&) const; void dumpDataSetSumRec(std::ostream&) const; void dumpQualSumRec (std::ostream&) const; void dumpSdrHistRec (std::ostream&) const; void dumpPdr16HistRec (std::ostream&) const; void dumpPdr8HistRec (std::ostream&) const; void dumpProcParmRec (std::ostream&) const; void dumpMapProjRec (std::ostream&) const; void dumpPosDataRec (std::ostream&) const; void dumpAttDataRec (std::ostream&) const; void dumpRadiDataRec (std::ostream&) const; void dumpRadiCompRec (std::ostream&) const; private: void loadCeosRecords(); ossim_int32 sizeOfNextRec(FILE*); VolumeDirectoryFile theVolumeDirectory; SarLeaderFile theSarLeaderFile; imop_desc_rec theImopDescRec; SarTrailerFile theSarTrailerFile; ossimFilename theVolDirFileName; ossimFilename theLeaderFileName; ossimFilename theImageFileName; ossimFilename theTrailerFileName; bool theErrorStatus; vol_desc_rec* theVolDescRec; text_rec* theTextRec; dataset_sum_rec* theDataSetSumRec; qual_sum_rec* theQualSumRec; sdr_hist_rec* theSdrHistRec; pdr16_hist_rec* thePdr16HistRec; pdr8_hist_rec* thePdr8HistRec; proc_parm_rec* theProcParmRec; map_proj_rec* theMapProjRec; pos_data_rec* thePosDataRec; att_data_rec* theAttDataRec; radi_data_rec* theRadiDataRec; radi_comp_rec* theRadiCompRec; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimDemGrid.h000066400000000000000000000061041352751253100237350ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Ken Melero // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class defines a DEM grid. // //******************************************************************** // $Id$ #ifndef ossimDemGrid_HEADER #define ossimDemGrid_HEADER 1 #include #include #include #include #include /*! * class ossimDemGrid * This class uses the DEM library to read a DEM and construct a rectangular * grid of signed 16 bit point values. */ class ossimDemGrid { public: /*! * Missing or void data is replaced with missingDataValue. */ ossimDemGrid(ossim_float32 missingDataValue = -32768.0); ~ossimDemGrid(); /*! * Convertes a DEM to a rectangular grid. * * If incrementalRead is false, the entire DEM will be converted * with just one call to read. 0 (zero) is returned if successful, -1 * if error. * * If incrementalRead is true, multiple calls to read are * required, and the return value is as follows: * >0 -- Number of calls remaining until conversion is complete. * ==0 -- Conversion was successful. No more calls to read required. * -1 -- Error during conversion. */ long read(ossim::istream& dem, bool incrementalRead = false); // Accessors ossimDemHeader const& getHeader() const; /*! * Returns the number of columns in the grid. */ long getWidth() const; /*! * Returns the number of rows in the grid. */ long getHeight() const; /*! * Returns the elevation value at (x,y). (0,0) is in the upper left * corner, x is positive to the right, y is positive down. */ ossim_float32 getElevation(long x, long y) const; /*! * Returns the value used to indicate missing data. */ ossim_float32 getMissingDataValue() const; /*! * (x,y) are the coordinates of a elevation value in the dem. * (ground_x, ground_y) are the coordinates of that value in the * units of the horizontal projection system used by the dem. */ void getGroundCoords(long x, long y, double& ground_x, double& ground_y); private: ossim_float32 _missDataVal; ossimDemHeader _header; long _width; long _height; ossim_float32* _grid; bool _firstTime; // Whether or not we've started reading the DEM. long _curProfile; std::vector _profiles; // Used by fillUTM() double _northwest_x, _northwest_y; void setElevation(long x, long y, ossim_float32 val); long fillGeographic(ossim::istream& dem, bool incrementalRead); long fillUTM(ossim::istream& dem, bool incrementalRead); }; inline void ossimDemGrid::setElevation(long x, long y, ossim_float32 val) { if (_grid == 0) return; _grid[(_width * y) + x] = val; } #endif // #ifndef ossimDemGrid_HEADER ossim-Miami-2.9.1/include/ossim/support_data/ossimDemHeader.h000066400000000000000000000232271352751253100242450ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class parses a DEM header. // //******************************************************************** // $Id$ #ifndef ossimDemHeader_HEADER #define ossimDemHeader_HEADER 1 #include #include #include #include #include #include class ossimFilename; class ossimString; class ossimKeywordlist; class OSSIM_DLL ossimDemHeader { public: ossimDemHeader(); friend OSSIM_DLL std::ostream& operator<<(ossim::ostream& s, const ossimDemHeader& header); friend OSSIM_DLL ossim::istream& operator>>(ossim::istream& s, ossimDemHeader& header); /** * @brief open method that takes a file. * * @param file File name to open. * * @return true on success false on error. */ bool open(const ossimFilename& file); bool open(std::shared_ptr& str, const std::string& connectionString); /** * @brief open method that takes a stream. * * @param is The input stream to read from. * * @return stream */ ossim::istream& open(ossim::istream& is); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ std::ostream& print(std::ostream& out) const; // Accessors /*! Quadrangle name. */ std::string const& getQuadName() const; /*! Free format desciptor field containing process information. */ std::string const& getProcessInfo () const; /*! * SE geographic corner orderd as: * x == Longitude == SDDDMMSS.SSSS * (neg sign (s) right justified, no leading zeros, * plus sign (s) implied */ double getSEGeoCornerX () const; /*! * SE geographic corner orderd as: * y == Latitude == SDDMMSS.SSSS * (neg sign (s) right justified, no leading zeros, * plus sign (s) implied */ double getSEGeoCornerY () const; /*! * 1 == Autocorrelation resample simple bilinear * 2 == Manual profile GRIDEM simple bilinear * 3 == DLG/hypsography CTOG 8-direction bilinear * 4 == Interpolation from photogrammetic system contours DCASS * 4-direction bilinear * 5 == DLG/hypsography LINETRACE, LT4X complex linear * 6 == DLG/hypsography CPS-3, ANUDEM, GRASS complex polynomial * 7 == Electronic imaging (non-photogrammetric), active or passive * sensor systems */ ossim_int32 getProcessCode () const; /*! * Used for 30 minute DEMs - Identifies 1:100,000 scale sections * Formatted as XNN, wher X is "S" == 7.5 min. & "F" == 15 min. * NN is a two digit sequence number */ std::string const& getSectionIndicator() const; /*! * Mapping Center origin code. "EMC","WMC","MCMC","RMMC","FS" and "GPM2" */ std::string const& getMappingCenterCode() const; /*! * 1 == DEM-1 * 2 == DEM-2 * 3 == DEM-3 */ ossim_int32 getLevelCode() const; /*! * 1 == Regular * 2 == Random (reserved for future use). */ ossim_int32 getElevPattern() const; /*! * Code defining ground planimetric reference system. * 0 == Geographic * 1 == UTM * 2 == State Plane */ ossim_int32 getGroundRefSysCode() const; /*! * @return The projection type as a string. */ ossimString getProjectionType() const; /*! * Code defining zone in ground planimetric reference system. */ ossim_int32 getGroundRefSysZone() const; /*! * Code defining unit of measure for ground planimetric coordinates * used throughout the file. * 0 == Radians * 1 == Feet * 2 == Meters * 3 == Arc Seconds */ ossim_int32 getGroundRefSysUnits() const; /*! * Code defining unit of measure for elevation coordinates used * throughout the file. * 1 == Feet * 2 == Meters */ ossim_int32 getElevationUnits() const; /*! * Set n == 4 */ ossim_int32 getNumPolySides() const; /*! * The coordinates of the quadrangle corners are ordered in a clockwise * direction beginning with the southwest corner. */ const ossimDemPointVector& getDEMCorners() const; /*! * In Radians the counterclockwise angle from the primary axis of ground * planimetric reference to the primary axis of the DEM local reference * system. Set to 0 to align with the coordinate system */ double getCounterclockAngle() const; /*! * 0 == unknown accuracy * 1 == accuracy info is given in logical record type C */ ossim_int32 getElevAccuracyCode() const; /*! * Minimum elevation in the DEM. */ double getMinimumElev() const; /*! * Maximum elevation in the DEM. */ double getMaximumElev() const; double getSpatialResX() const; double getSpatialResY() const; double getSpatialResZ() const; /*! * The number of rows and columns in profiles in the DEM. * NOTE: When profile rows == 1, profile columns is the number of profiles * in the DEM. */ ossim_int32 getProfileRows() const; ossim_int32 getProfileColumns() const; /*! * Present only if two or more primary intervals exist (level 2 DEM's only) */ ossim_int32 getLargeContInt() const; /*! * 0 == NA * 1 == feet * 2 == meters * (level two DEM's only) */ ossim_int32 getMaxSourceUnits() const; /*! * Smallest or only primary contour interval (level 2 DEM's only) */ ossim_int32 getSmallContInt() const; /*! * 1 == feet * 2 == meters */ ossim_int32 getMinSourceUnits() const; /*! * YYY */ ossim_int32 getSourceDate() const; /*! * YYY */ ossim_int32 getInspRevDate() const; /*! * "I" indicates all processes of part3, Quality Control have been * performed. */ std::string const& getInspFlag() const; /*! * 0 == No Validation * 1 == RSME computed from test points, no quantative test or interactive * editing/review * 2 == Batch process water body edit and RSME computed from test points * 3 == Review and edit, including water edit. No RSME computed from test * points * 4 == Level 1 DEM's reviewed & edited. RSME computed from test points * 5 == Level 2 & 3 DEM's reviewed & edited. RSME computed from test points */ ossim_int32 getDataValFlag() const; /*! * 0 == none * 1 == suspect areas * 2 == void areas * 3 == suspect & void areas */ ossim_int32 getSuspectVoidFlag() const; /*! * 1 == local mean sea level * 2 == National Geodetic Vertical Datum 1929 * 3 == North American Vertical Datum 1988 */ ossim_int32 getVertDatum() const; /*! * 1 == North Amercian Datum 1927 (NAD 27) * 2 == World Geoditic System 1972 (WGS 72) * 3 == WGS 84 * 4 == NAD 83 * 5 == Old Hawaii Datum * 6 == Puerto Rico Datum */ ossim_int32 getHorizDatum() const; /** * @return The ossim datum code as a string. */ ossimString getHorizDatumCode() const; /*! * 01-99 Primarily a DMA specfic field. (For USGS use set to 01) */ ossim_int32 getDataEdition() const; /*! * Contains the percentage of nodes in the file set to void */ ossim_int32 getPerctVoid() const; /*! * West edge match status flag */ ossim_int32 getWestEdgeFlag() const; /*! * North edge match status flag */ ossim_int32 getNorthEdgeFlag() const; /*! * East edge match staus flag */ ossim_int32 getEastEdgeFlag() const; /*! * South edge match status flag */ ossim_int32 getSouthEdgeFlag() const; /*! * Vertical datum shift - value is in the form of SFFF.DD Value is * the average shift value for the four quadrangle corners obtained * from program VERTCOM. */ double getVertDatumShift() const; /*! * Populates keyword list with geometry info. * * @return true on success, false on error. */ bool getImageGeometry(ossimKeywordlist& kwl, const char* prefix=NULL) const; private: std::string _quadName; std::string _processInfo; double _seGeoCornerX; double _seGeoCornerY; ossim_int32 _processCode; std::string _sectionIndicator; std::string _mapCenterCode; ossim_int32 _levelCode; ossim_int32 _elevPattern; ossim_int32 _groundRefSysCode; ossim_int32 _groundRefSysZone; ossim_int32 _groundRefSysUnits; ossim_int32 _elevUnits; ossim_int32 _numPolySides; ossimDemPointVector _demCorners; double _counterclockAngle; ossim_int32 _elevAccuracyCode; double _minElevation; double _maxElevation; double _spatialResX; double _spatialResY; double _spatialResZ; ossim_int32 _profileRows; ossim_int32 _profileColumns; ossim_int32 _largeContInt; ossim_int32 _maxSourceUnits; ossim_int32 _smallContInt; ossim_int32 _minSourceUnits; ossim_int32 _sourceDate; ossim_int32 _inspRevDate; std::string _inspFlag; ossim_int32 _valFlag; ossim_int32 _suspectVoidFlg; ossim_int32 _vertDatum; ossim_int32 _horizDatum; ossim_int32 _dataEdition; ossim_int32 _perctVoid; ossim_int32 _westEdgeFlag; ossim_int32 _northEdgeFlag; ossim_int32 _eastEdgeFlag; ossim_int32 _southEdgeFlag; double _vertDatumShift; }; #endif // #ifndef ossimDemHeader_HEADER ossim-Miami-2.9.1/include/ossim/support_data/ossimDemInfo.h000066400000000000000000000026521352751253100237470ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: USGS DEM Info object. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimDemInfo_HEADER #define ossimDemInfo_HEADER #include #include #include #include /** * @brief USGS DEM info class. * * Encapsulates the dumpnitf functionality. */ class OSSIM_DLL ossimDemInfo : public ossimInfoBase { public: /** default constructor */ ossimDemInfo(); /** virtual destructor */ virtual ~ossimDemInfo(); /** * @brief open method. * * @param file File name to open. * * @return true on success false on error. */ virtual bool open(const ossimFilename& file); virtual bool open(std::shared_ptr& str, const std::string& connectionString); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; private: //ossimFilename theFile; mutable std::shared_ptr m_fileStr; std::string m_connectionString; }; #endif /* End of "#ifndef ossimDemInfo_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimDemPoint.h000066400000000000000000000031611352751253100241410ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero (kmelero@imagelinks.com) // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class defines a DEM point. // //******************************************************************** // $Id: ossimDemPoint.h 17195 2010-04-23 17:32:18Z dburken $ #ifndef ossimDemPoint_HEADER #define ossimDemPoint_HEADER #include class ossimDemPoint { public: ossimDemPoint(double x = 0.0, double y = 0.0); // Accessors double getX() const; double getY() const; void getXY(double& x, double& y) const; // Modifiers void setX(double x); void setY(double y); void setXY(double x, double y); bool operator<(ossimDemPoint const& /* rhs */) const {return false;} bool operator==(ossimDemPoint const& /* rhs */) const {return false;} private: double _x; double _y; }; // Inline Methods for class ossimDemPoint inline ossimDemPoint::ossimDemPoint(double x, double y) { _x = x; _y = y; } inline double ossimDemPoint::getX() const { return _x; } inline double ossimDemPoint::getY() const { return _y; } inline void ossimDemPoint::getXY(double& x, double& y) const { x = _x; y = _y; } inline void ossimDemPoint::setX(double x) { _x = x; } inline void ossimDemPoint::setY(double y) { _y = y; } inline void ossimDemPoint::setXY(double x, double y) { _x = x; _y = y; } typedef std::vector ossimDemPointVector; #endif // #ifndef ossimDemPoint_HEADER ossim-Miami-2.9.1/include/ossim/support_data/ossimDemProfile.h000066400000000000000000000047661352751253100244640ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class defines a DEM profile. // //******************************************************************** // $Id$ #ifndef ossimDemProfile_HEADER #define ossimDemProfile_HEADER 1 #include #include #include #include typedef std::vector ossimDemElevationVector; class ossimDemProfile { public: ossimDemProfile(); ossimDemProfile(ossimDemProfile const& right); ossimDemProfile const& operator=(ossimDemProfile const& right); friend std::ostream& operator<<(std::ostream& s, ossimDemProfile& demp); friend std::istream& operator>>(std::istream& s, ossimDemProfile& demp); // Accessors /*! * Row identification number. Typically set to 1. */ ossim_int32 getRowNumber() const; /*! * Column identification number. This is the profile sequence number. */ ossim_int32 getColumnNumber() const; /*! * Number of elevations in this profile. */ ossim_int32 getNumberOfElevations() const; /*! * Location (in ground planimetric coordinates) of the first */ ossimDemPoint const& getProfileLocation() const; /*! * Elevation of local datum for the profile. * Value is in units of measure given by the Elevation Units field * found in the DEM header. */ double getLocalDatumElevation() const; /*! * Minimum elevation for this profile. */ double getMinimumElev() const; /*! * Maximum elevation for this profile. */ double getMaximumElev() const; /*! * Elevation values. * From the DEM standard: * "A value in this array would be multiplied by the spatial resolution * value and added to the elevation of the local elevation datum for the * element profile to obtain the elevation for the point." */ ossimDemElevationVector const& getElevations() const; private: ossim_int32 _row; ossim_int32 _column; ossim_int32 _numberElevations; ossimDemPoint _profileLocation; double _locDatumElev; double _minElev; double _maxElev; ossimDemElevationVector _elevations; }; #endif // #ifndef ossimDemProfile_HEADER ossim-Miami-2.9.1/include/ossim/support_data/ossimDemStats.h000066400000000000000000000036571352751253100241600ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class provides some statistics for DEMs. // //******************************************************************** // $Id: ossimDemStats.h 7174 2005-01-11 18:10:38Z dburken $ #ifndef ossimDemStats_HEADER #define ossimDemStats_HEADER #include class ossimDemStats { public: ossimDemStats(); ~ossimDemStats(); friend std::ostream& operator<<(std::ostream& s, ossimDemStats const& stats); friend std::istream& operator>>(std::istream& s, ossimDemStats& stats); //Accessors /*! * 1 = available * 2 = unavailable * The code defines the availability of statics */ long getAvailCodeDE2() const; long getRSMEDE2x () const; long getRSMEDE2y () const; long getRSMEDE2z () const; /*! * This code defines the sample size use * to compute the accuracy, if 0 then the * accuracy is estimated. */ long getSampleSizeDE2() const; /*! * 1 = available * 2 = unavailable * The code defines the availability of statics */ long getAvailCodeDE5() const; long getRSMEDE5x () const; long getRSMEDE5y () const; long getRSMEDE5z () const; /*! * This code defines the sample size use * to compute the accuracy, if 0 then the * accuracy is estimated. */ long getSampleSizeDE5() const; private: long _availCodeDE2; long _rsmeDE2x; long _rsmeDE2y; long _rsmeDE2z; long _sampleSizeDE2; long _availCodeDE5; long _rsmeDE5x; long _rsmeDE5y; long _rsmeDE5z; long _sampleSizeDE5; }; #endif // #ifndef ossimDemStats_HEADER ossim-Miami-2.9.1/include/ossim/support_data/ossimDemUtil.h000066400000000000000000000044511352751253100237700ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class provides some simple utilities for DEMs. // //******************************************************************** // $Id$ #ifndef ossimDemUtil_HEADER #define ossimDemUtil_HEADER 1 #include #include #include class ossimFilename; class ossimDemUtil { public: /** * @brief Does basic sanity checks to see if file is a dem. * * 1) Check extension for .dem * * 2) Look for file.omd (ossim meta data) file containing keyword * "dem_type" with value of "usgs_dem". * * 3) Check 512 bytes and make sure there is no binary data. * * @note * There is a keyword list template stored in the templates directory: * "ossim/etc/templates/usgs_dem_template.kwl" * * @param file The file to check. * * @return true on success, false on error. */ static bool isUsgsDem(const ossimFilename& file); static bool isUsgsDem(std::shared_ptr str, const std::string& connectionString); /** * Reads a single record from a DEM. * Returns true if succesful. Returns false if EOF or error. */ static bool getRecord(ossim::istream& s, std::string& strbuf, long reclength = 1024); /** * Same as getRecord above. buf should be at least reclength+1 in size. */ static bool getRecord(ossim::istream& s, char* buf, long reclength = 1024); static long getLong(char* const strbuf, // string to extract long from long const startpos, // starting position of field long const width); // width of field static bool getDouble(std::string const& strbuf, // string to extract double from long const startpos, // starting position of field long const width, // width of field double& val); // value extracted from field. private: ossimDemUtil(); }; #endif /* #ifndef ossimDemUtil_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimDoqq.h000066400000000000000000000066641352751253100233410ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class parses a Digital Ortho Quarter Quad (DOQQ) // header. // //******************************************************************** // $Id: ossimDoqq.h 19900 2011-08-04 14:19:57Z dburken $ #ifndef ossimDoqq_HEADER #define ossimDoqq_HEADER //#include #include #include #include #include #include #include #include #include #include class OSSIM_DLL ossimDoqq : public ossimInfoBase { public: ossimDoqq(); ossimDoqq(ossimFilename file); ~ossimDoqq(); enum ossimErrorStatus { OSSIM_OK = 0, OSSIM_ERROR = 1 }; enum { GSD_X_OFFSET = 59, GSD_Y_OFFSET = 59, DATA_ORDER_OFFSET = 142, LINE_OFFSET = 145, SAMPLE_OFFSET = 151, PROJECTION_OFFSET = 196, RGB_OFFSET = 157, UL_EASTING_OFFSET = 288, UL_NORTHING_OFFSET = 312, UTM_ZONE_OFFSET = 199, DATUM_OFFSET = 168, DATA_ORDER_SIZE = 3, LINE_SIZE = 8, SAMPLE_SIZE = 8, PROJECTION_SIZE = 3, RGB_SIZE = 3, MARKING_U_SIZE = 5, MARKING_V_SIZE = 5, UL_EASTING_SIZE = 24, UL_NORTHING_SIZE = 24, UTM_ZONE_SIZE = 6, DATUM_SIZE = 2, RADIOMETRY_SIZE = 3, GSD_SIZE = 12 }; /** * @brief open method. * * @param str stream to test. * @param connectionString original string for the stream. * * @return true on success false on error. */ virtual bool open(std::shared_ptr& str, const std::string& connectionString); //! Implementation of ossimInfoBase class pure virtual. virtual std::ostream& print(std::ostream& out) const; ossimString theProjection; ossimString theDatum; ossimString theQuadName; ossimString theQuad; ossimString theNation; ossimString theState; ossimString theDataOrder; ossimString theMarkU; ossimString theMarkV; ossimString theImageSource; ossimString theSourceImageID; ossim_int32 theUtmZone; ossim_int32 theLine; ossim_int32 theSample; ossim_int32 theRgb; ossimString theAcqYear; ossimString theAcqMonth; ossimString theAcqDay; ossimString theAcqYearMonthDay; ossim_float64 theRMSE; ossim_float64 theEasting; ossim_float64 theNorthing; ossim_float64 theUN; ossim_float64 theUE; ossim_float64 theLN; ossim_float64 theLE; ossimDpt theGsd; ossim_int32 theHeaderSize; ossim_int32 theRecordSize; ossim_int32 errorStatus() const { return theErrorStatus; } private: mutable std::shared_ptr m_doqqFileStr; std::string m_connectionString; ossimErrorStatus theErrorStatus; ossim_float64 convertStr(const char* str) const; void ldstr_v1(std::istream& in); void ldstr_v2(std::istream& in); }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimDtedAcc.h000066400000000000000000000076101352751253100237140ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class gives access to the Accuracy Description // (ACC) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedAcc.h 16104 2009-12-17 18:09:59Z gpotts $ #ifndef ossimDtedAcc_H #define ossimDtedAcc_H #include #include #include #include #include #include #include class ossimProperty; class OSSIM_DLL ossimDtedAcc : public ossimErrorStatusInterface { public: ossimDtedAcc(); ossimDtedAcc(std::shared_ptr& str, ossim_int64 offset=0); enum { ACC_LENGTH = 2700, ACC_ABSOLUTE_CE = 4, ACC_ABSOLUTE_LE = 8, ACC_RELATIVE_CE = 12, ACC_RELATIVE_LE = 16, ACC_RESERVED_1 = 20, ACC_RESERVED_2 = 24, ACC_RESERVED_3 = 25, ACC_MULTIPLE_FLAG = 56, ACC_RESERVED = 58, FIELD1_SIZE = 3, FIELD2_SIZE = 4, FIELD3_SIZE = 4, FIELD4_SIZE = 4, FIELD5_SIZE = 4, FIELD6_SIZE = 4, FIELD7_SIZE = 1, FIELD8_SIZE = 31, FIELD9_SIZE = 2, FIELD10_SIZE = 4, FIELD11_SIZE = 4, FIELD12_SIZE = 4, FIELD13_SIZE = 4, FIELD14_SIZE = 2, FIELD15_SIZE = 9, FIELD16_SIZE = 10, FIELD17_SIZE = 18, FIELD18_SIZE = 69 }; // The Recoginition Sentinel signifies if the ACC record exists. ossim_int32 absCE() const; ossim_int32 absLE() const; ossim_int32 relCE() const; ossim_int32 relLE() const; ossim_int32 startOffset() const; ossim_int32 stopOffset() const; friend OSSIM_DLL std::ostream& operator<<( std::ostream& os, const ossimDtedAcc& acc); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix) const; void parse(std::istream& in); void clearFields(); /** * @brief Gets a property for name. * @param name Property name to get. * @return ossimRefPtr Note that this can be empty if * property for name was not found. */ ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Adds this class's properties to list. * @param propertyNames list to append to. */ void getPropertyNames(std::vector& propertyNames)const; private: // Do not allow... ossimDtedAcc(const ossimDtedAcc& source); const ossimDtedAcc& operator=(const ossimDtedAcc& rhs); char theRecSen[FIELD1_SIZE+1]; char theAbsoluteCE[FIELD2_SIZE+1]; char theAbsoluteLE[FIELD3_SIZE+1]; char theRelativeCE[FIELD4_SIZE+1]; char theRelativeLE[FIELD5_SIZE+1]; char theField6[FIELD6_SIZE+1]; char theField7[FIELD7_SIZE+1]; char theField8[FIELD8_SIZE+1]; char theField9[FIELD9_SIZE+1]; char theField10[FIELD10_SIZE+1]; char theField11[FIELD11_SIZE+1]; char theField12[FIELD12_SIZE+1]; char theField13[FIELD13_SIZE+1]; char theField14[FIELD14_SIZE+1]; char theField15[FIELD15_SIZE+1]; char theField16[FIELD16_SIZE+1]; char theField17[FIELD17_SIZE+1]; ossim_int32 theStartOffset; ossim_int32 theStopOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimDtedDsi.h000066400000000000000000000174171352751253100237530ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class gives access to the Data Set Identification // (DSI) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedDsi.h 16104 2009-12-17 18:09:59Z gpotts $ #ifndef ossimDtedDsi_H #define ossimDtedDsi_H #include #include #include #include #include #include #include class ossimProperty; class OSSIM_DLL ossimDtedDsi : public ossimErrorStatusInterface { public: ossimDtedDsi(); ossimDtedDsi(std::shared_ptr& str, ossim_int64 offset=0); enum { DSI_LENGTH = 648, DSI_SECURITY_CODE = 4, DSI_SECURITY_CONTROL = 5, DSI_SECURITY_HANDLING = 7, DSI_RESERVED_1 = 34, DSI_DMA_SERIES = 60, DSI_RESERVED_2 = 65, DSI_RESERVED_3 = 80, DSI_DATA_EDITION = 88, DSI_MATCH_MERGE_VERSION = 90, DSI_MAINTENANCE_DATE = 91, DSI_MATCH_MERGE_DATE = 95, DSI_MAINTENANCE_CODE = 99, DSI_PRODUCER_CODE = 103, DSI_RESERVED_4 = 111, DSI_PRODUCT_SPEC_STOCK_NUMBER = 127, DSI_PRODUCT_SPEC_NUMBER = 136, DSI_PRODUCT_SPEC_DATE = 138, DSI_VERTICAL_DATUM = 142, DSI_HORIZ_DATUM = 145, DSI_DIGITIZING_SYSTEM = 150, DSI_COMPILATION_DATE = 160, DSI_RESERVED_5 = 164, DSI_LAT_ORIGIN = 186, DSI_LON_ORIGIN = 195, DSI_LAT_SW = 205, DSI_LON_SW = 212, DSI_LAT_NW = 220, DSI_LON_NW = 227, DSI_LAT_NE = 235, DSI_LON_NE = 242, DSI_LAT_SE = 250, DSI_LON_SE = 257, DSI_ORIENTATION = 265, DSI_LAT_INTERVAL = 274, DSI_LON_INTERVAL = 278, DSI_NUM_LAT_LINES = 282, DSI_NUM_LON_LINES = 286, DSI_PARTIAL_CELL_INDICATOR = 290, DSI_RESERVED = 292, FIELD1_SIZE = 3, FIELD2_SIZE = 1, FIELD3_SIZE = 2, FIELD4_SIZE = 27, FIELD5_SIZE = 26, FIELD6_SIZE = 5, FIELD7_SIZE = 15, FIELD8_SIZE = 8, FIELD9_SIZE = 2, FIELD10_SIZE = 1, FIELD11_SIZE = 4, FIELD12_SIZE = 4, FIELD13_SIZE = 4, FIELD14_SIZE = 8, FIELD15_SIZE = 16, FIELD16_SIZE = 9, FIELD17_SIZE = 2, FIELD18_SIZE = 4, FIELD19_SIZE = 3, FIELD20_SIZE = 5, FIELD21_SIZE = 10, FIELD22_SIZE = 4, FIELD23_SIZE = 22, FIELD24_SIZE = 9, FIELD25_SIZE = 10, FIELD26_SIZE = 7, FIELD27_SIZE = 8, FIELD28_SIZE = 7, FIELD29_SIZE = 8, FIELD30_SIZE = 7, FIELD31_SIZE = 8, FIELD32_SIZE = 7, FIELD33_SIZE = 8, FIELD34_SIZE = 9, FIELD35_SIZE = 4, FIELD36_SIZE = 4, FIELD37_SIZE = 4, FIELD38_SIZE = 4, FIELD39_SIZE = 2, FIELD40_SIZE = 101, FIELD41_SIZE = 100, FIELD42_SIZE = 156 }; // The Recognition Sentinel signifies if the DSI record exists. ossimString recognitionSentinel() const; ossimString securityCode() const; ossimString productLevel() const; ossimString edition() const; ossimString matchMergeVersion() const; ossimString maintanenceDate() const; ossimString matchMergeDate() const; ossimString maintenanceCode() const; ossimString producerCode() const; ossimString productStockSpecNumber() const; ossimString productSpecNumber() const; ossimString productSpecDate() const; ossimString verticalDatum() const; ossimString horizontalDatum() const; ossimString compilationDate() const; ossimString latOrigin() const; ossimString lonOrigin() const; ossimString latSW() const; ossimString lonSW() const; ossimString latNW() const; ossimString lonNW() const; ossimString latNE() const; ossimString lonNE() const; ossimString latSE() const; ossimString lonSE() const; ossimString orientation() const; ossimString latInterval() const; ossimString lonInterval() const; ossim_int32 numLatPoints() const; ossim_int32 numLonLines() const; ossim_int32 cellIndicator() const; ossim_int32 startOffset() const; ossim_int32 stopOffset() const; friend OSSIM_DLL std::ostream& operator<<( std::ostream& os, const ossimDtedDsi& dsi); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix) const; void parse(std::istream& in); /** * @brief Gets a property for name. * @param name Property name to get. * @return ossimRefPtr Note that this can be empty if * property for name was not found. */ ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Adds this class's properties to list. * @param propertyNames list to append to. */ void getPropertyNames(std::vector& propertyNames)const; private: // Do not allow... ossimDtedDsi(const ossimDtedDsi& source); const ossimDtedDsi& operator=(const ossimDtedDsi& rhs); char theRecSen[FIELD1_SIZE+1]; char theSecurityCode[FIELD2_SIZE+1]; char theField3[FIELD3_SIZE+1]; char theField4[FIELD4_SIZE+1]; char theProductLevel[FIELD6_SIZE+1]; char theField7[FIELD7_SIZE+1]; char theField8[FIELD8_SIZE+1]; char theEdition[FIELD9_SIZE+1]; char theMatchMergeVersion[FIELD10_SIZE+1]; char theMaintenanceDate[FIELD11_SIZE+1]; char theMatchMergeDate[FIELD12_SIZE+1]; char theMaintenanceCode[FIELD13_SIZE+1]; char theProducerCode[FIELD14_SIZE+1]; char theField15[FIELD15_SIZE+1]; char theProductStockSpecNumber[FIELD16_SIZE+1]; char theProductSpecNumber[FIELD17_SIZE+1]; char theProductSpecDate[FIELD18_SIZE+1]; char theVerticalDatum[FIELD19_SIZE+1]; char theHorizontalDatum[FIELD20_SIZE+1]; char theField21[FIELD21_SIZE+1]; char theCompilationDate[FIELD22_SIZE+1]; char theField23[FIELD23_SIZE+1]; char theLatOrigin[FIELD24_SIZE+1]; char theLonOrigin[FIELD25_SIZE+1]; char theLatSW[FIELD26_SIZE+1]; char theLonSW[FIELD27_SIZE+1]; char theLatNW[FIELD28_SIZE+1]; char theLonNW[FIELD29_SIZE+1]; char theLatNE[FIELD30_SIZE+1]; char theLonNE[FIELD31_SIZE+1]; char theLatSE[FIELD32_SIZE+1]; char theLonSE[FIELD33_SIZE+1]; char theOrientation[FIELD34_SIZE+1]; char theLatInterval[FIELD35_SIZE+1]; char theLonInterval[FIELD36_SIZE+1]; char theNumLatPoints[FIELD37_SIZE+1]; char theNumLonLines[FIELD38_SIZE+1]; char theCellIndicator[FIELD39_SIZE+1]; char theField40[FIELD40_SIZE+1]; char theField41[FIELD41_SIZE+1]; char theField42[FIELD42_SIZE+1]; ossim_int32 theStartOffset; ossim_int32 theStopOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimDtedHdr.h000066400000000000000000000075351352751253100237510ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class gives access to the File Header Label // (HDR) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedHdr.h 16104 2009-12-17 18:09:59Z gpotts $ #ifndef ossimDtedHdr_H #define ossimDtedHdr_H #include #include #include #include #include #include #include class ossimProperty; class OSSIM_DLL ossimDtedHdr : public ossimErrorStatusInterface { public: ossimDtedHdr(); ossimDtedHdr(std::shared_ptr& str, ossim_int64 offset=0); enum { HDR_LENGTH = 80, HDR_ONE_LABEL_1 = 4, HDR_FILENAME = 5, HDR_UNIVAC = 22, HDR_REEL = 28, HDR_FILE_NUM = 32, HDR_GENERATION_NUM = 36, HDR_VERSION_NUM = 40, HDR_CREATION_DATE = 42, HDR_EXPIRATION_DATE = 48, HDR_ACCESS = 54, HDR_BLOCK_COUNT = 55, HDR_QUALIFIER = 61, HDR_BLANKS = 74, FIELD1_SIZE = 3, FIELD2_SIZE = 1, FIELD3_SIZE = 17, FIELD4_SIZE = 6, FIELD5_SIZE = 4, FIELD6_SIZE = 4, FIELD7_SIZE = 4, FIELD8_SIZE = 2, FIELD9_SIZE = 6, FIELD10_SIZE = 6, FIELD11_SIZE = 1, FIELD12_SIZE = 6, FIELD13_SIZE = 13, FIELD14_SIZE = 7 }; // The Recognition Sentinel signifies if the HDR record exists. ossimString recognitionSentinel() const; ossimString fileName() const; ossimString version() const; ossimString creationDate() const; ossim_int32 startOffset() const; ossim_int32 stopOffset() const; friend OSSIM_DLL std::ostream& operator<<( std::ostream& os, const ossimDtedHdr& hdr); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix) const; void parse(std::istream& in); /** * @brief Gets a property for name. * @param name Property name to get. * @return ossimRefPtr Note that this can be empty if * property for name was not found. */ ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Adds this class's properties to list. * @param propertyNames list to append to. */ void getPropertyNames(std::vector& propertyNames)const; private: // Do not allow... ossimDtedHdr(const ossimDtedHdr& source); const ossimDtedHdr& operator=(const ossimDtedHdr& rhs); char theRecSen[FIELD1_SIZE+1]; char theField2[FIELD2_SIZE+1]; char theFilename[FIELD3_SIZE+1]; char theField4[FIELD4_SIZE+1]; char theField5[FIELD5_SIZE+1]; char theField6[FIELD6_SIZE+1]; char theVersion[FIELD7_SIZE+1]; char theCreationDate[FIELD8_SIZE+1]; char theField9[FIELD9_SIZE+1]; char theField10[FIELD10_SIZE+1]; char theField11[FIELD11_SIZE+1]; char theField12[FIELD12_SIZE+1]; char theField13[FIELD13_SIZE+1]; char theField14[FIELD14_SIZE+1]; ossim_int32 theStartOffset; ossim_int32 theStopOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimDtedInfo.h000066400000000000000000000044631352751253100241240ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: DTED Info object. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimDtedInfo_HEADER #define ossimDtedInfo_HEADER #include #include #include #include #include #include #include #include #include #include #include class ossimNitfFile; class ossimProperty; /** * @brief DTED Info class. * * Encapsulates the dtedInfo functionality. */ class OSSIM_DLL ossimDtedInfo : public ossimInfoBase { public: /** default constructor */ ossimDtedInfo(); /** virtual destructor */ virtual ~ossimDtedInfo(); /** * @brief open method. * * @param str stream to test. * @param connectionString original string for the stream. * * @return true on success false on error. */ virtual bool open(std::shared_ptr& str, const std::string& connectionString); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; /** * @brief Gets a property for name. * @param name Property name to get. * @return ossimRefPtr Note that this can be empty if * property for name was not found. */ ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Adds this class's properties to list. * @param propertyNames list to append to. */ void getPropertyNames(std::vector& propertyNames)const; private: mutable std::shared_ptr m_dtedFileStr; std::string m_connectionString; ossimDtedVol m_vol; ossimDtedHdr m_hdr; ossimDtedUhl m_uhl; ossimDtedDsi m_dsi; ossimDtedAcc m_acc; //ossimFilename theFile; }; #endif /* End of "#ifndef ossimDtedInfo_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimDtedRecord.h000066400000000000000000000121611352751253100244410ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class gives access to the Data Record Description // of a DTED Level 1 file. // // Notes: Each elevation is a true value referenced to meas sea level // (MSL) datum recorded to the nearest meter. The horizontal // position is referenced to precise longitude-latitiude // locations in terms of the current World Geodetic System // (WGS84) determined for each file by reference to the origin // at the southwest corner. The elevations are evenly spaced // in latitude and longitude at the interval designated in the // User Header Label (UHL) in South to North profile sequence. // //******************************************************************** // $Id: ossimDtedRecord.h 14248 2009-04-08 19:38:11Z dburken $ #ifndef ossimDtedRecord_H #define ossimDtedRecord_H #include #include #include #include class OSSIM_DLL ossimDtedRecord : public ossimErrorStatusInterface { public: ossimDtedRecord(std::istream& in, ossim_int32 offest, ossim_int32 num_points); // NOTE: When using this class be sure that as you cycle through // all the points within a record, that you verify they are // sequential. According to the DTED Specification // (MIL-PRF-89020A) issued in 19 April 1996, page 22 all // records must be sequential. If not, file may be corrupt. // // To verify this, you can do the following: // // int count = 0; // for(int i = 0; i < num_lon_lines; i++) // rec[i] = new ossimDtedRecord(theFileDesc, offset, // num_lat_points); // if(count != (rec[i]->dataBlockCount() + 1)) // ERROR -- Records are not sequential // count = rec[i]->dataBlockCount(); ~ossimDtedRecord(); enum { DATA_LENGTH = 12, DATA_BLOCK_COUNT = 2, DATA_LON_COUNT = 4, DATA_LAT_COUNT = 6, DATA_ELEV_START = 8, DATA_BYTES_PER_POINT = 2, }; // The Recognition Sentinel signifies if the Data Record exists. ossimString recognitionSentinel() const; ossim_int32 dataBlockCount() const; ossim_int32 lonCount() const; ossim_int32 latCount() const; ossim_uint32 checkSum() const; ossim_uint32 computedCheckSum() const; ossim_int32 numPoints() const; // Access methods for the elevation data ossim_int32 getPoint(ossim_int32 i) const; ossim_uint16 getPointData(ossim_int32 i) const; ossim_int32* points() const; ossim_uint16* pointsData() const; ossim_int32 startOffset() const; ossim_int32 stopOffset() const; friend OSSIM_DLL std::ostream& operator<<( std::ostream& os, const ossimDtedRecord& rec); void parse(std::istream& in); private: // prevent use ossimDtedRecord(const ossimDtedRecord& source); ossim_int32 theFile; /*! * 252 (8 bit) */ ossimString theRecSen; /*! * Sequential count of the block within the file. */ ossim_int32 theDataBlockCount; /*! * Count of the meridian. * True longitude = longitude count x data interval + origin * (Offset from the SW corner longitude) */ ossim_int32 theLonCount; /*! * Count of the parallel. * True latitude = latitude count x data interval + origin * (Offset from the SW corner latitude) */ ossim_int32 theLatCount; /*! * Algebraic addition of contents of block. * The checksum is computed algebraically using integer arithmetic by * summing all header and elevation bytes contained int the record as * 8-bit values. Each byte is considered an unsigned, 8-bit value for * checksum calculation. */ ossim_uint32 theCheckSum; /*! * All the elevation points in a Data Record as ints. * (ie. all the latitudal points in a longitudinal line) */ ossim_int32* thePoints; /*! * All the elevation points in a Data Record as unsigned shorts. * (ie. all the latitudal points in a longitudinal line) */ ossim_uint16* thePointsData; /*! * Our computed check sum. This should match the checksum * at the end of the Data Record. */ ossim_uint32 theComputedCheckSum; /*! * The number of points in a longitudinal line. */ ossim_int32 theNumPoints; ossim_int32 theStartOffset; ossim_int32 theStopOffset; /*! * Compute the check sum for the Data Record and compare against * the parsed check sum from the data record. This must be correct * to be a valid data record. If not, there is a chance of a * corrupted elevation cell. * * @return true if check sum validates, false if not. */ bool validateCheckSum(std::istream& in); }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimDtedUhl.h000066400000000000000000000077511352751253100237640ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class gives access to the User Header Label // (UHL) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedUhl.h 16104 2009-12-17 18:09:59Z gpotts $ #ifndef ossimDtedUhl_H #define ossimDtedUhl_H #include #include #include #include #include #include #include class ossimProperty; class OSSIM_DLL ossimDtedUhl : public ossimErrorStatusInterface { public: ossimDtedUhl(); ossimDtedUhl(std::shared_ptr& str, ossim_int64 offset=0); enum { UHL_LENGTH = 80, UHL_LON_ORIGIN = 5, UHL_LAT_ORIGIN = 13, UHL_LON_INTERVAL = 21, UHL_LAT_INTERVAL = 25, UHL_ABSOLUTE_LE = 29, UHL_SECURITY_CODE = 33, UHL_REFERENCE_NUM = 33, UHL_NUM_LON_LINES = 48, UHL_NUM_LAT_LINES = 52, UHL_MULTIPLE_ACC = 56, UHL_RESERVED = 57, FIELD1_SIZE = 3, FIELD2_SIZE = 1, FIELD3_SIZE = 8, FIELD4_SIZE = 8, FIELD5_SIZE = 4, FIELD6_SIZE = 4, FIELD7_SIZE = 4, FIELD8_SIZE = 3, FIELD9_SIZE = 12, FIELD10_SIZE = 4, FIELD11_SIZE = 4, FIELD12_SIZE = 1, FIELD13_SIZE = 24 }; // The Recognition Sentinel signifies if the UHL record exists. ossimString recognitionSentinel() const; double lonOrigin() const; double latOrigin() const; double lonInterval() const; double latInterval() const; double absoluteLE() const; ossimString securityCode() const; ossim_int32 numLonLines() const; ossim_int32 numLatPoints() const; ossim_int32 mulitpleAccuracy() const; ossim_int32 startOffset() const; ossim_int32 stopOffset() const; friend OSSIM_DLL std::ostream& operator<<( std::ostream& out, const ossimDtedUhl& uhl); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix) const; void parse(std::istream& in); /** * @brief Gets a property for name. * @param name Property name to get. * @return ossimRefPtr Note that this can be empty if * property for name was not found. */ ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Adds this class's properties to list. * @param propertyNames list to append to. */ void getPropertyNames(std::vector& propertyNames)const; private: // Do not allow... ossimDtedUhl(const ossimDtedUhl& source); const ossimDtedUhl& operator=(const ossimDtedUhl& rhs); double degreesFromString(const char* str) const; double spacingFromString(const char* str) const; char theRecSen[FIELD1_SIZE+1]; char theField2[FIELD2_SIZE+1]; char theLonOrigin[FIELD3_SIZE+1]; char theLatOrigin[FIELD4_SIZE+1]; char theLonInterval[FIELD5_SIZE+1]; char theLatInterval[FIELD6_SIZE+1]; char theAbsoluteLE[FIELD7_SIZE+1]; char theSecurityCode[FIELD8_SIZE+1]; char theField9[FIELD9_SIZE+1]; char theNumLonLines[FIELD10_SIZE+1]; char theNumLatPoints[FIELD11_SIZE+1]; char theMultipleAccuracy[FIELD12_SIZE+1]; ossim_int32 theStartOffset; ossim_int32 theStopOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimDtedVol.h000066400000000000000000000064051352751253100237670ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class gives access to the Volume Header Label // (VOL) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedVol.h 16104 2009-12-17 18:09:59Z gpotts $ #ifndef ossimDtedVol_H #define ossimDtedVol_H #include #include #include #include #include #include #include class ossimProperty; class OSSIM_DLL ossimDtedVol : public ossimErrorStatusInterface { public: ossimDtedVol(); ossimDtedVol(std::shared_ptr& str, ossim_int64 offset=0); enum { VOL_LENGTH = 80, VOL_ONE_LABEL_1 = 4, VOL_REEL_NUMBER = 5, VOL_REEL_ACCESS = 11, VOL_SPACE = 12, VOL_ACCOUNT_NUMBER = 38, VOL_BLANKS = 52, VOL_ONE_LABEL_2 = 80, FIELD1_SIZE = 3, FIELD2_SIZE = 1, FIELD3_SIZE = 6, FIELD4_SIZE = 1, FIELD5_SIZE = 26, FIELD6_SIZE = 14, FIELD7_SIZE = 28, FIELD8_SIZE = 1 }; // The Recognition Sentinel signifies if the VOL record exists. ossimString getRecognitionSentinel() const; ossimString getReelNumber() const; ossimString getAccountNumber() const; ossim_int32 startOffset() const; ossim_int32 stopOffset() const; friend OSSIM_DLL std::ostream& operator<<( std::ostream& os, const ossimDtedVol& vol); void parse(std::istream& in); /** * @brief Gets a property for name. * @param name Property name to get. * @return ossimRefPtr Note that this can be empty if * property for name was not found. */ ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Adds this class's properties to list. * @param propertyNames list to append to. */ void getPropertyNames(std::vector& propertyNames)const; /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix) const; private: // Do not allow... ossimDtedVol(const ossimDtedVol& source); const ossimDtedVol& operator=(const ossimDtedVol& rhs); char theRecSen[FIELD1_SIZE+1]; char theField2[FIELD2_SIZE+1]; char theReelNumber[FIELD3_SIZE+1]; char theField4[FIELD4_SIZE+1]; char theField5[FIELD5_SIZE+1]; char theAccountNumber[FIELD6_SIZE+1]; char theField7[FIELD7_SIZE+1]; char theField8[FIELD8_SIZE+1]; ossim_int32 theStartOffset; ossim_int32 theStopOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimERS.h000066400000000000000000000046571352751253100230660ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Chong-Ket Chuah // Contributor: Anrew Huang // // Description: // This class parses a ER Mapper raster file format header. // //******************************************************************** // $Id: ossimERS.h 13216 2008-07-23 18:56:53Z dburken $ #ifndef ossimERS_HEADER #define ossimERS_HEADER #include #include #include #include #include #include #include class ossimERS : public ossimErrorStatusInterface { public: ossimERS(); ossimERS(const char* file); virtual ~ossimERS() {}; void clearFields(); // DatasetHeader double theVersion; ossimString theFilename; ossimString theDescription; // tm lastupdated; ossimString theSensorname; // tm sensedate; ossim_int32 theHeaderOffset; // for non-ermapper file ossimString theDatasetType; // ERStorage ossimString theDatatype; // Raster ossimString theByteorder; //MSBFirst or LSBFirst ossimString theComments; // arbitrary comment field // CoordSpace ossimString theDatum; /* geodetic datum */ ossimString theProjection; ossimString theCoordSysType; ossimString theUnits; double theRotation; ossimUnitType theTieUnitType; // RasterInfo ossimScalarType theCelltype; ossim_int32 theCellsizeof; bool theHasNullCells; double theNullCell; double theCellSizeX; double theCellSizeY; ossim_int32 theLine; ossim_int32 theSample; double theOriginX; double theOriginY; ossim_int32 theBands; std::vector theBandID; virtual std::ostream& print(std::ostream& out) const; bool writeFile(const ossimFilename& file); bool toOssimProjectionGeom(ossimKeywordlist& kwl, const char* prefix=NULL)const; ossimString toOssimProjection()const; ossimString toOssimDatum()const; ossim_int32 errorStatus() const { return theErrorStatus; } private: void parseError(const char *msg); std::vector parseLine(std::istream& in); void parseHeader(std::istream& fptr); void parseRasterInfo(std::istream& fptr); void parseCoordinateSpace(std::istream& fptr); }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimEnviHeader.h000066400000000000000000000241021352751253100244320ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Class for reading and writing an ENVI (The Environment for Visualizing // Images) header file. This parses envi header and places in a keyword // list. // //---------------------------------------------------------------------------- // $Id: ossimEnviHeader.h 22349 2013-08-01 21:38:29Z dburken $ #ifndef ossimEnviHeader_HEADER #define ossimEnviHeader_HEADER 1 #include #include #include #include #include #include /** * Class for reading and writing an ENVI (The Environment for Visualizing * Images) header file. */ class OSSIM_DLL ossimEnviHeader : public ossimReferenced { public: /** default construtor */ ossimEnviHeader(); /** virtual destructor */ virtual ~ossimEnviHeader(); virtual void reset(); /** @return Const reference to map. */ const ossimKeywordlist& getMap() const; /** @return Reference to map. */ ossimKeywordlist& getMap(); /** * @brief Gets value for key. * @param key To search for. * @param value Initialized by this. * @return true on success, false on error. This will return true if key is * found, even if value is empty. */ bool getValue( const ossimString& key, ossimString& value ) const; /** * @brief Gets value for key. * @param key * @param value * @return true if key is in map even if value is empty; false, if not. */ bool findCaseInsensitive( const ossimString& key, ossimString& value ) const; /** * @brief Gets value for key. * @param key * @param value * @return true if key is in map even if value is empty; false, if not. */ bool findSubStringCaseInsensitive( const ossimString& key, ossimString& value) const; /** * Opens an envi header. * * @return true on success, false on error. */ bool open(const ossimFilename& file); /** * Writes header to file in a standard envi format. * * @param file File to write to. * * @return true on success, false on error. */ bool writeFile(const ossimFilename& file); /** * Prints header to out in a standard envi format. * * @param out Stream to write to. * * @return Reference to the stream passed. */ std::ostream& print(std::ostream& out) const; /** @brief friend operator<< */ friend OSSIM_DLL std::ostream& operator<<(std::ostream& out, const ossimEnviHeader& obj); /** * @return The description of the file. */ ossimString getDescription() const; /** * @param description The description of the file. */ void setDescription(const ossimString& description); /** * @return The number of samples. */ ossim_uint32 getSamples() const; /** * Sets the number of samples. * * @param samples The number of samples. */ void setSamples(ossim_uint32 samples); /** * @return The number of lines. */ ossim_uint32 getLines() const; /** * Sets the number of lines. * * @param lines The number of lines. */ void setLines(ossim_uint32 lines); /** * @return The number of bands. */ ossim_uint32 getBands() const; /** * Sets the number of bands. * * @param bands The number of bands. */ void setBands(ossim_uint32 bands); /** * @brief Gets default bands if "default bands" keyword is present. * @param bands Initialized by this. * @return true on success, false if keyword not found. "bands" will be * zeroed out on failure. */ bool getDefaultBands( std::vector& bands ) const; /** * @brief Gets rgb bands if "wavelength" keyword is present. * @param bands Initialized by this. * @return true on success, false if keyword not found. "bands" will be * zeroed out on failure. */ bool getRgbBandsFromWaveLength( std::vector& bands ) const; /** * @return The number of header offset in bytes. */ ossim_uint32 getHeaderOffset() const; /** * Sets the header offset in bytes. * * @param headerOffset The number of header offset in bytes. */ void setHeaderOffset(ossim_uint32 headerOffset); /** * @return The file type */ ossimString getFileType() const; /** * Sets the file type. * * @param fileType The sensor type as a string. */ void setFileType(const ossimString& fileType); /** * @return The envi data type.. */ ossim_uint32 getDataType() const; /** * @return The ossimScalarType from the envi data type.. */ ossimScalarType getOssimScalarType() const; /** * Sets the envi data type based on the ossimScalarType. * * @param scalar The ossimScalarType of the image. */ void setDataType(ossimScalarType scalar); /** * @return The envi interleave type. */ ossimString getInterleaveType() const; /** * @return The ossimInterleaveType from the envi interleave.. */ ossimInterleaveType getOssimInterleaveType() const; /** * Sets the envi interleave type string based on the ossimInterleaveType. * * @param interleave The ossimInterleaveType of the image. */ void setInterleaveType(ossimInterleaveType interleave); /** * @return The sensor type.. */ ossimString getSensorType() const; /** * Sets the envi sensor type string. * * @param sensorType The sensor type as a string. */ void setSensorType(const ossimString& sensorType); /** * @return If key "byte order" found returns the envi byte order; else, * system byte order. * * @note (Same as the ossimByteOrder enumeration): * 0 = LITTLE_ENDIAN, * 1 = BIG_ENDIAN */ ossimByteOrder getByteOrder() const; /** * Sets the envi byte order from the ossimByteOrder. * * @param byteorder The ossimByteOrder of the image. */ void setByteorder(ossimByteOrder byteOrder); /** * @return The x start. */ ossim_int32 getXStart() const; /** * Sets the x start. * * @param xStart */ void setXStart(ossim_int32 xstart); /** * @return The x start. */ ossim_int32 getYStart() const; /** * Sets the y start. * * @param ystart */ void setYStart(ossim_int32 ystart); /** * @return The envi map info string. */ ossimString getMapInfo() const; /** * Sets the envi map info string. * * @param mapInfo envi map info string. */ void setMapInfo(const ossimString& mapInfo); /** * Sets the envi map info string from a keyword list containing geometry * information. * * @param kwl Keyword list containing geometry information. */ void setMapInfo(const ossimKeywordlist& kwl, const char* prefix=0); /** * @return The env wavelength units.. */ ossimString getWavelengthUnits() const; /** * Sets the envi wavelength units string. * * @param wavelengthUnits envi wavelength units string. */ void setWavelengthUnits(const ossimString& wavelenghtUnits); /** * @param bandNames Vector of strings to initialize with band names. */ void getBandNames(std::vector& bandNames) const; /** * Sets the band name string vector. * * @param bandNames Vector of band name strings. */ void setBandNames(const std::vector& bandNames); /** * @param wavelengths Vector of strings to initialize with wave lengths. */ void getWavelengths(std::vector& wavelengths) const; /** * Sets the envi band name string. * * @param wavelengths Vector of band name strings. */ void setWavelengths(const std::vector& wavelengths); /** * Method to the load (recreate) the state of the object from a keyword * list. * * @param kwl Keyword list to initialize from. * * @param prefix Usually something like: "object1." * * @return This method will alway return true as it is intended to be * used in conjuction with the set methods. * * Keywords picked up by loadState: * * description: My_file * * number_samples: 1024 * * number_lines: 512 * * number_bands: 3 * * header_offset: 0 * * file_type: ENVI Standard * * data_type: 1 * * interleave_type: bil * * sensor_type: Unknown * * (little_endian or big_endian) * byte_order: little_endian * * map_info: Unknown * * wavelength_units: * * band_name0: Red band * band_name1: Green band * band_name2: Blue band * * wavelength0: 620.25 * wavelength1: 514.5 * wavelength2: 470.0 */ bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * @brief Global method to test first line of file for "ENVI". * @return true on success, false on error. */ static bool isEnviHeader( const ossimFilename& file ); /** * @brief Global method to test first line of stream for "ENVI". * @return true on success, false on error. */ static bool isEnviHeader( std::istream& in ); /** @return Path to envi header file. */ const ossimFilename& getFile() const; private: /** * @brief Check band list to see if any are outside of range of bands. * Bands should be zero base. * @return true if all bands are less than number of bands; false, if * outside range or if "bands" key is not found. */ bool rangeCheckBands( const std::vector& bands ) const; /** * @brief Parses stream. * @return true on success, false on error. */ bool readStream(std::istream& in); ossimFilename m_file; // Name of header file. ossimKeywordlist m_keywords; }; #endif /* #ifndef ossimEnviHeader_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimEnviInfo.h000066400000000000000000000022161352751253100241370ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: ENVI Info object. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimEnviInfo_HEADER #define ossimEnviInfo_HEADER 1 #include #include #include /** @brief ENVI info class. */ class OSSIM_DLL ossimEnviInfo : public ossimInfoBase { public: /** default constructor */ ossimEnviInfo(); /** virtual destructor */ virtual ~ossimEnviInfo(); /** * @brief open method. * * @param file File name to open. * * @return true on success false on error. */ virtual bool open(const ossimFilename& file); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; private: ossimFilename m_file; }; #endif /* End of "#ifndef ossimEnviInfo_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimFfL5.h000066400000000000000000000022541352751253100231600ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Ken Melero (kmelero@imagelinks.com) // Orginally written by Oscar Kramer (SoBe Software) // Description: Container class for LandSat5 Fast Format header files (RevB & C) // // ******************************************************************** // $Id$ #ifndef ossimFfL5_HEADER #define ossimFfL5_HEADER 1 #include #include #include // *************************************************************************** // CLASS: ossimFfL5 // *************************************************************************** class OSSIM_DLL ossimFfL5 : public ossimFfL7 { friend std::ostream& operator<<(std::ostream& os, const ossimFfL5& head); public: ossimFfL5(); ossimFfL5(const char* headerFile); ossimRefPtr revb(); const ossimRefPtr revb()const; protected: virtual ~ossimFfL5(); private: void readHeaderRevB(const ossimString& header_name); int convertGeoPoint(const char* sptr, ossimGpt& geo_point); ossimRefPtr theRevb; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimFfL7.h000066400000000000000000000134301352751253100231600ustar00rootroot00000000000000//******************************************************************* // // License: See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // Orginally written by Oscar Kramer (SoBe Software) // // Description: Container class for LandSat7 Fast Format header files. // //******************************************************************** // $Id: ossimFfL7.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimFfL7_HEADER #define ossimFfL7_HEADER #include #include #include #include #include #include #include #include #include class ossimProperty; class ossimDate; // *************************************************************************** // CLASS: ossimFfL7 // *************************************************************************** class OSSIMDLLEXPORT ossimFfL7 : public ossimReferenced, public ossimErrorStatusInterface, public ossimPropertyInterface { friend std::ostream& operator<<(std::ostream& os, const ossimFfL7& head); public: ossimFfL7 (); ossimFfL7 (const char* headerFile); void dump(std::ostream& os) const; //> Provides a readable dump of this object. //< void writeHeader(std::ostream& os) const; //> Writes the full header to the output stream in proper L7A format. // NOT YET IMPLEMENTED //< int path() const; //> Returns the path as an int. // Currently uses the1stPathRowNumber string. //< int row() const; //> Returns the row as an int from the pathRowString. // Currently uses the1stPathRowNumber string. //< ossimString pathRow() const; //> Returns a string represnting the path and row as a name. // i.e.: PPP/RRFFSS will be returned as pPPPrRRFFSS // This method will remove any spaces. //< /*! * Initializes "bias" with "theBias" from the radiometry record. * Contains eight bands; although, only bands present will be initialized. */ void getBias(std::vector& bias) const; double getBias(long bandIdx)const; /*! * Initializes "bias" with "theBias" from the radiometry record. * Contains eight bands; although, only bands present will be initialized. */ void getGain(std::vector& gain) const; double getGain(long bandIdx)const; double getParam(ossim_uint32 i)const; virtual unsigned int getBandCount()const; long getJulianDay()const; /** @return The acquisition date string. */ ossimString getAcquisitionDate() const; /** * @brief Gets the date as an ossimDate. * @param date to initialize. */ void getAcquisitionDate(ossimDate& date)const; /** @return The satellite name "theSatName". */ ossimString getSatelliteName() const; /** @return The filename for band. */ ossimFilename getBandFilename(ossim_uint32 idx)const; /** @return The number of lines per band. */ int getLinesPerBand() const; /** @return The number of pixels per line (samples). */ int getPixelsPerLine() const; /** * @brief Gets the sun elevation in degrees. * @param elevation The elevation to initialize. */ void getSunElevation(double& elevation) const; /** * @brief Gets the sun azimuth in degrees. * @param azimuth The azimuth to initialize. */ void getSunAzimuth(double& azimuth) const; /** * @brief Gets a property for matching name. * @param name The name of the property to get. * @return Returns property matching "name". */ virtual ossimRefPtr getProperty(const ossimString& name)const; /** * @brief Gets a list of property names available. * @param propertyNames The list to push back names to. */ virtual void getPropertyNames(std::vector& propertyNames)const; // The Admin Record: char theRequestNumber[21]; // NNNYYMMDDSSSSUUUU char theLocationCode[18]; // ppp/rrrffss int thePathNumber; int theRowNumber; char theAcquisitionDate[20]; // yyyymmdd char theSatName[11]; // "LANDSAT7" char theSensorName[11]; // "ETM+" char theSensorMode[7]; // "NORMAL" double theOffNadirAngle; // degrees char theProductType[19]; // "MAPbORIENTED"|"ORBITbORIENTED" char theProductSize[11]; // ("FULLb"|"SUB"|"MULTI")+"SCENE" char theProcessingType[12]; // "SYSTEMATIC" char theResampAlgorithm[3]; // "CC"|"NN"|"MF" int thePixelsPerLine; int theLinesPerBand; int theRecordSize; double theGsd; int theOutputBitsPerPixel; int theAcquiredBitsPerPixel; char theBandsPresentString[33]; char theBandFileNames[8][30]; // The Radiometry Record: std::vector theBias; std::vector theGain; // The Geometry Record: char theMapProjectionName[5]; char theEllipsoid[19]; // "WGS84" char theDatum[7]; // "WGS84" double theProjectionParams[15]; int theUsgsMapZone; ossimGpt theUL_Corner; ossimGpt theUR_Corner; ossimGpt theLR_Corner; ossimGpt theLL_Corner; ossimGpt theCenterGP; ossimIpt theCenterImagePoint; int theHorizontalOffset; // pixels double theOrientationAngle; // degrees double theSunElevation; // degrees double theSunAzimuth; // degrees protected: virtual ~ossimFfL7(); private: void initialize(); void readAdminRecord(FILE* fptr); void readRadiomRecord(FILE* fptr); void readGeomRecord(FILE* fptr); int convertGeoPoint(FILE*, ossimGpt&); }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimFfRevb.h000066400000000000000000000264361352751253100236060ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Ken Melero (kmelero@imagelinks.com) // Orginally written by Dave Burken (dburken@imagelinks.com) // Description: This class parses an EOSAT Fast Format rev b header. // //******************************************************************** // $Id$ #ifndef ossimFfRevb_HEADER #define ossimFfRevb_HEADER 1 #include #include //*************************************************************************** // CLASS: ossimFfRevb.h //*************************************************************************** class ossimFfRevb : public ossimReferenced { public: ossimFfRevb (); ossimFfRevb (const char* headerFile); ~ossimFfRevb (){}; enum ErrorStatus { OSSIM_OK = 0, OSSIM_ERROR = 1 }; //*** // Enumerations for parsing header. Contains size in bytes // for all fields. // // NOTE: Sizes are the actual number of bytes for that field so add // one for trailing '\0' to get the string length for the // data member that are character arrays. //*** enum { NUMBER_OF_PROJECTION_PARAMETERS = 15, NUMBER_OF_BANDS = 7 }; enum { PRODUCT_ORDER_NUMBER_DESC_SIZE = 9, PRODUCT_ORDER_NUMBER_SIZE = 11, WRS_DESC_SIZE = 6, PATH_ROW_NUMBER_SIZE = 9, DATE_DESC_SIZE = 19, DATE_SIZE = 8, SAT_NUMBER_DESC_SIZE = 12, SAT_NUMBER_SIZE = 2, INSTRUMENT_TYPE_DESC_SIZE = 13, INSTRUMENT_TYPE_SIZE = 4, PRODUCT_TYPE_DESC_SIZE = 15, PRODUCT_TYPE_SIZE = 14, PRODUCT_SIZE_DESC_SIZE = 15, PRODUCT_SIZE_SIZE = 10, MAP_SHEET_SIZE = 78, PROCESSING_TYPE_DESC_SIZE = 30, PROCESSING_TYPE_SIZE = 10, RESAMPLING_ALGO_DESC_SIZE = 13, RESAMPLING_ALGO_SIZE = 2, RADIANCE_DESC_SIZE = 20, RADIANCE_SIZE = 16, VOLUME_NUMBER_DESC_SIZE = 20, VOLUME_NUMBER_SIZE = 3, FIRST_LINE_DESC_SIZE = 14, FIRST_LINE_IN_VOLUME_SIZE = 5, LINES_PER_VOLUME_DESC_SIZE = 15, LINES_PER_VOLUME_SIZE = 5, ORIENTATION_ANGLE_DESC_SIZE = 14, ORIENTATION_ANGLE_SIZE = 6, MAP_PROJ_NAME_DESC_SIZE = 13, MAP_PROJ_NAME_SIZE = 4, USGS_PROJ_NUMBER_DESC_SIZE = 20, USGS_PROJ_NUMBER_SIZE = 6, USGS_MAP_ZONE_DESC_SIZE = 16, USGS_MAP_ZONE_SIZE = 6, USGS_PROJ_PARAMS_DESC_SIZE = 29, USGS_PROJ_PARAMS_SIZE = 24, ELLIPSOID_DESC_SIZE = 18, ELLIPSOID_SIZE = 20, MAJOR_AXIS_DESC_SIZE = 18, MAJOR_AXIS_SIZE = 11, MINOR_AXIS_DESC_SIZE = 18, MINOR_AXIS_SIZE = 11, PIXEL_GSD_DESC_SIZE = 13, PIXEL_GSD_SIZE = 5, PIXELS_PER_LINE_DESC_SIZE = 17, PIXELS_PER_LINE_SIZE = 5, LINES_PER_IMAGE_DESC_SIZE = 17, LINES_PER_IMAGE_SIZE = 5, CORNER_DESC_SIZE = 4, LON_SIZE = 13, LAT_SIZE = 12, EASTING_SIZE = 13, NORTHING_SIZE = 13, BANDS_PRESENT_DESC_SIZE = 16, BANDS_PRESENT_SIZE = 7, BLOCKING_FACTOR_DESC_SIZE = 18, BLOCKING_FACTOR_SIZE = 4, RECORD_LENGTH_DESC_SIZE = 16, RECORD_LENGTH_SIZE = 5, SUN_ELEVATION_DESC_SIZE = 16, SUN_ELEVATION_SIZE = 2, SUN_AZIMUTH_DESC_SIZE = 14, SUN_AZIMUTH_SIZE = 3, CENTER_DESC_SIZE = 8, CENTER_SAMPLE_SIZE = 6, CENTER_LINE_SIZE = 6, OFFSET_DESC_SIZE = 8, OFFSET_SIZE = 4, REV_DESC_SIZE = 4, FORMAT_VERSION_SIZE = 1 }; //*** // Enumerations for byte offsets in header. All offsets are relative to // the first byte of the first record which is byte 0. //*** enum { // One record: bytes 0 - 1535 PRODUCT_ORDER_NUMBER_OFFSET = 9, PATH_ROW_NUMBER_OFFSET = 26, DATE_OFFSET = 54, SAT_NUMBER_OFFSET = 74, INSTRUMENT_TYPE_OFFSET = 89, PRODUCT_TYPE_OFFSET = 108, PRODUCT_SIZE_OFFSET = 137, MAP_SHEET_NAME_OFFSET = 147, PROCESSING_TYPE_OFFSET = 255, RESAMPLING_ALGO_OFFSET = 278, VOLUME_NUMBER_OFFSET = 438, FIRST_LINE_IN_VOLUME_OFFSET = 455, LINES_PER_VOLUME_OFFSET = 475, ORIENTATION_ANGLE_OFFSET = 494, MAP_PROJ_NAME_OFFSET = 513, USGS_PROJ_NUMBER_OFFSET = 537, USGS_MAP_ZONE_OFFSET = 559, ELLIPSOID_OFFSET = 972, MAJOR_AXIS_OFFSET = 1010, MINOR_AXIS_OFFSET = 1039, PIXEL_GSD_OFFSET = 1063, PIXELS_PER_LINE_OFFSET = 1085, LINES_PER_IMAGE_OFFSET = 1107, UL_LON_OFFSET = 1116, UL_LAT_OFFSET = 1130, UL_EASTING_OFFSET = 1143, UL_NORTHING_OFFSET = 1157, UR_LON_OFFSET = 1174, UR_LAT_OFFSET = 1188, UR_EASTING_OFFSET = 1201, UR_NORTHING_OFFSET = 1215, LR_LON_OFFSET = 1232, LR_LAT_OFFSET = 1246, LR_EASTING_OFFSET = 1259, LR_NORTHING_OFFSET = 1273, LL_LON_OFFSET = 1290, LL_LAT_OFFSET = 1304, LL_EASTING_OFFSET = 1317, LL_NORTHING_OFFSET = 1331, BANDS_PRESENT_OFFSET = 1360, BLOCKING_FACTOR_OFFSET = 1385, RECORD_LENGTH_OFFSET = 1405, SUN_ELEVATION_OFFSET = 1426, SUN_AZIMUTH_OFFSET = 1442, CENTER_LON_OFFSET = 1453, CENTER_LAT_OFFSET = 1467, CENTER_EASTING_OFFSET = 1480, CENTER_NORTHING_OFFSET = 1494, CENTER_SAMPLE_OFFSET = 1507, CENTER_LINE_OFFSET = 1513, OFFSET_OFFSET = 1527, FORMAT_VERSION_OFFSET = 1535 }; int errorStatus() const { return theErrorStatus; } void print(std::ostream& os) const; void write(std::ostream& os) const; int path() const; //> Returns the path as an int. //< int row() const; //> Returns the row as an int from the pathRowString. //< int fraction() const; //> Returns the fraction as an int from the pathRowString. //< double projParam(int paramNumber) const; //> Converts the USGS Projection Parameter string, which has a // "D" to denote the exponent, to a double. //< friend std::ostream& operator<<(std::ostream& os, const ossimFfRevb& head); char theProductOrderNumber[PRODUCT_ORDER_NUMBER_SIZE + 1]; char thePathRowNumber[PATH_ROW_NUMBER_SIZE + 1]; char theAcquisitionDate[DATE_SIZE + 1]; //> yyyyddmm //< char theSatNumber[SAT_NUMBER_SIZE + 1]; //> L4, L5, 1B, 1C //< char theInstrumentType[INSTRUMENT_TYPE_SIZE + 1]; //> TM, LISS1 LISS2, LISS3, PAN, WIFS //< char theProductType[PRODUCT_TYPE_SIZE + 1]; // MAP or ORBIT oriented char theProductSize[PRODUCT_SIZE_SIZE + 1]; // FULL, SUB, MAP //> SYSTEMATIC, PRECISION, TERRAIN RADIOMETRIC //< char theMapSheetName[MAP_SHEET_SIZE + 1]; char theProcessingType[PROCESSING_TYPE_SIZE + 1]; //> SYSTEMATIC, PRECISION, TERRAIN RADIOMETRIC //< char theResampAlgorithm[RESAMPLING_ALGO_SIZE + 1]; // CC, NN or BL char theBandRadiance[NUMBER_OF_BANDS][RADIANCE_SIZE + 1]; char theVolumeNumber[VOLUME_NUMBER_SIZE + 1]; int the1stLineInVolume; int theLinesPerVolume; double theOrientationAngle; // degrees char theMapProjName[MAP_PROJ_NAME_SIZE + 1]; int theUsgsProjNumber; int theUsgsMapZone; char theUsgsProjParam[NUMBER_OF_PROJECTION_PARAMETERS] [USGS_PROJ_PARAMS_SIZE + 1]; //> USGS Projection Parameters. These are actually a string // representing doubles; however, EOSAT uses a "D" for the // exponent notation, so they are read in as a char*. // To convert to double use the method "projParam". //< char theEllipsoid[ELLIPSOID_SIZE + 1]; double theSemiMajorAxis; double theSemiMinorAxis; double theGsd; // pixel size in meters int thePixelsPerLine; // samples int theLinesPerImage; // lines char theUlLon[LON_SIZE + 1]; // deg, min, sec char theUlLat[LAT_SIZE + 1]; // deg, min, sec double theUlEasting; // meters double theUlNorthing; // meters char theUrLon[LON_SIZE + 1]; // deg, min, sec char theUrLat[LAT_SIZE + 1]; // deg, min, sec double theUrEasting; // meters double theUrNorthing; // meters char theLrLon[LON_SIZE + 1]; // deg, min, sec char theLrLat[LAT_SIZE + 1]; // deg, min, sec double theLrEasting; // meters double theLrNorthing; // meters char theLlLon[LON_SIZE + 1]; // deg, min, sec char theLlLat[LAT_SIZE + 1]; // deg, min, sec double theLlEasting; // meters double theLlNorthing; // meters char theBandsPresentString[BANDS_PRESENT_SIZE + 1]; int theBlockingFactor; int theRecordSize; int theSunElevation; // degrees int theSunAzimuth; // degrees char theCenterLon[LON_SIZE + 1]; // deg, min, sec char theCenterLat[LAT_SIZE + 1]; // deg, min, sec double theCenterEasting; // meters double theCenterNorthing; // meters int theCenterSample; // Nearest whole pixel. int theCenterLine; // Nearest whole pixel. int theOffset; // pixels char theFormatVersion[FORMAT_VERSION_SIZE + 1]; private: void loadFromStream(std::istream& is); int checkStream(std::istream& is); ErrorStatus theErrorStatus; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimFfRevc.h000066400000000000000000000277051352751253100236070ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero (kmelero@imagelinks.com) // Orginally written by Dave Burken (dburken@imagelinks.com) // Description: This class parses an EOSAT Fast Format rev c header. // //******************************************************************** // $Id$ #ifndef ossimFfRevc_HEADER #define ossimFfRevc_HEADER 1 #include // Forward class declarations. class ossimString; //*************************************************************************** // CLASS: ossimFfRevc.h //*************************************************************************** class ossimFfRevc { public: ossimFfRevc (); ossimFfRevc (const char* headerFile); ~ossimFfRevc (){}; enum ErrorStatus { OSSIM_OK = 0, OSSIM_ERROR = 1 }; //> // Enumerations for parsing header. Contains size in bytes // for all fields. // // NOTE: Sizes are the actual number of bytes for that field so add // one for trailing '\0' to get the string length for the // data member that are character arrays. //< enum { NUMBER_OF_BANDS = 8, NUMBER_OF_SCENES = 4, NUMBER_OF_PROJECTION_PARAMETERS = 15 }; enum { // Adminstrative record: PRODUCT_ORDER_NUMBER_DESC_SIZE = 12, PRODUCT_ORDER_NUMBER_SIZE = 11, LOCATION_DESC_SIZE = 11, PATH_ROW_NUMBER_SIZE = 17, DATE_DESC_SIZE = 19, DATE_SIZE = 8, SAT_NAME_DESC_SIZE = 11, SAT_NAME_SIZE = 10, SENSOR_NAME_DESC_SIZE = 9, SENSOR_NAME_SIZE = 10, SENSOR_MODE_DESC_SIZE = 14, SENSOR_MODE_SIZE = 6, LOOK_ANGLE_DESC_SIZE = 13, OFF_NADIR_ANGLE_SIZE = 6, PRODUCT_TYPE_DESC_SIZE = 14, PRODUCT_TYPE_SIZE = 18, PRODUCT_SIZE_DESC_SIZE = 15, PRODUCT_SIZE_SIZE = 10, PROCESSING_TYPE_DESC_SIZE = 20, PROCESSING_TYPE_SIZE = 11, RESAMPLING_ALGO_DESC_SIZE = 13, RESAMPLING_ALGO_SIZE = 2, TAPE_VOLUME_NUMBER_DESC_SIZE = 19, TAPE_VOLUME_NUMBER_SIZE = 2, VOLUMES_PER_TAPE_SIZE = 2, PIXELS_PER_LINE_DESC_SIZE = 18, PIXELS_PER_LINE_SIZE = 5, LINES_PER_IMAGE_DESC_SIZE = 17, LINES_PER_IMAGE_SIZE = 5, FIRST_LINE_DESC_SIZE = 14, FIRST_LINE_IN_VOLUME_SIZE = 5, BLOCKING_FACTOR_DESC_SIZE = 18, BLOCKING_FACTOR_SIZE = 2, RECORD_LENGTH_DESC_SIZE = 16, RECORD_LENGTH_SIZE = 5, PIXEL_GSD_DESC_SIZE = 13, PIXEL_GSD_SIZE = 6, BITS_PER_PIXEL_DESC_SIZE = 23, BITS_PER_PIXEL_SIZE = 2, // Output and Acquired AQUIRED_BITS_PER_PIXEL_DESC_SIZE = 26, BANDS_PRESENT_DESC_SIZE = 15, BANDS_PRESENT_SIZE = 33, REV_DESC_SIZE = 15, FORMAT_VERSION_SIZE = 1, // Radiometric record: BIAS_GAIN_DESC_SIZE = 50, BIAS_SIZE = 24, GAIN_SIZE = 24, // Geometric record: GEO_DESC_SIZE = 14, MAP_PROJECTION_NAME_DESC_SIZE = 17, MAP_PROJECTION_NAME_SIZE = 4, ELLIPSOID_DESC_SIZE = 12, ELLIPSOID_SIZE = 18, DATUM_DESC_SIZE = 8, DATUM_SIZE = 6, PROJECTION_PARAMETER_DESC_SIZE = 28, PROJECTION_PARAMETER_SIZE = 24, CORNER_DESC_SIZE = 4, CENTER_DESC_SIZE = 8, LON_SIZE = 13, LAT_SIZE = 12, EASTING_SIZE = 13, NORTHING_SIZE = 13, CENTER_SAMPLE_SIZE = 5, CENTER_LINE_SIZE = 5, HORIZONTAL_OFFSET_DESC_SIZE = 8, HORIZONTAL_OFFSET_SIZE = 6, ORIENTATION_ANGLE_DESC_SIZE = 20, ORIENTATION_ANGLE_SIZE = 6, SUN_ELEVATION_DESC_SIZE = 21, SUN_ELEVATION_SIZE = 4, SUN_AZIMUTH_DESC_SIZE = 20, SUN_AZIMUTH_SIZE = 5 }; //--- //> // Enumerations for byte offsets in header. All offsets are relative to // the first byte of the first record which is byte 0. //< enum { // Administrative record: bytes 0 - 1535 PRODUCT_ORDER_NUMBER_OFFSET = 12, PRODUCT_TYPE_OFFSET = 654, PRODUCT_SIZE_OFFSET = 687, PROCESSING_TYPE_OFFSET = 740, RESAMPLING_ALGO_OFFSET = 764, TAPE_VOLUME_NUMBER_OFFSET = 819, VOLUMES_PER_TAPE_OFFSET = 822, PIXELS_PER_LINE_OFFSET = 842, LINES_PER_IMAGE_OFFSET = 864, FIRST_LINE_IN_VOLUME_OFFSET = 894, BLOCKING_FACTOR_OFFSET = 917, RECORD_LENGTH_OFFSET = 935, PIXEL_GSD_OFFSET = 954, BITS_PER_PIXEL_OFFSET = 983, ACQUIRED_BITS_PER_PIXEL_OFFSET = 1011, BANDS_PRESENT_OFFSET = 1055, FORMAT_VERSION_OFFSET = 1535, // Radiometric record: bytes 1536 - 3071 // See file scope constants for bias and gain OFFSET positions. // Geometric record: bytes 3072 - 4607 MAP_PROJECTION_NAME_OFFSET = 3103, ELLIPSOID_OFFSET = 3119, DATUM_OFFSET = 3145, UL_LON_OFFSET = 3637, UL_LAT_OFFSET = 3651, UL_EASTING_OFFSET = 3664, UL_NORTHING_OFFSET = 3678, UR_LON_OFFSET = 3717, UR_LAT_OFFSET = 3731, UR_EASTING_OFFSET = 3744, UR_NORTHING_OFFSET = 3758, LR_LON_OFFSET = 3797, LR_LAT_OFFSET = 3811, LR_EASTING_OFFSET = 3824, LR_NORTHING_OFFSET = 3838, LL_LON_OFFSET = 3877, LL_LAT_OFFSET = 3891, LL_EASTING_OFFSET = 3904, LL_NORTHING_OFFSET = 3918, CENTER_LON_OFFSET = 3961, CENTER_LAT_OFFSET = 3975, CENTER_EASTING_OFFSET = 3988, CENTER_NORTHING_OFFSET = 4002, CENTER_SAMPLE_OFFSET = 4016, CENTER_LINE_OFFSET = 4022, HORIZONTAL_OFFSET_OFFSET = 4040, ORIENTATION_ANGLE_OFFSET = 4066, SUN_ELEVATION_OFFSET = 4133, SUN_AZIMUTH_OFFSET = 4157 }; //--- //> // An EOSAT Fast Format Rev C header consists of three // records: administrative, radiometric and geometric // each record has a class defined for it to hold the pertinent // data. //< class AdminRecord { public: AdminRecord(); ~AdminRecord(){} // Data Members for record. char theProductOrderNumber[PRODUCT_ORDER_NUMBER_SIZE + 1]; char thePathRowNumber[NUMBER_OF_SCENES][PATH_ROW_NUMBER_SIZE + 1]; char theAcquisitionDate[NUMBER_OF_SCENES][DATE_SIZE + 1]; //> yyyyddmm //< char theSatName[NUMBER_OF_SCENES][SAT_NAME_SIZE + 1]; //> L4, L5, 1B, 1C //< char theSensorName[NUMBER_OF_SCENES][SENSOR_NAME_SIZE + 1]; //> TM, LISS1 LISS2, LISS3, PAN, WIFS //< char theSensorMode[NUMBER_OF_SCENES][SENSOR_MODE_SIZE + 1]; double theOffNadirAngle[NUMBER_OF_SCENES]; // degrees char theProductType[PRODUCT_TYPE_SIZE + 1]; // MAP or ORBIT oriented char theProductSize[PRODUCT_SIZE_SIZE + 1]; // FULL, SUB, MAP //> SYSTEMATIC, PRECISION, TERRAIN RADIOMETRIC //< char theProcessingType[PROCESSING_TYPE_SIZE + 1]; char theResampAlgorithm[RESAMPLING_ALGO_SIZE + 1]; // CC or NN int theTapeVolumeNumber; int theNumberVolumesPerTape; int thePixelsPerLine; int theLinesPerImage; int the1stLineInVolume; int theTapeBlockingFactor; int theRecordSize; double theGsd; // pixel size in meters int theOutputBitsPerPixel; int theAcquiredBitsPerPixel; char theBandsPresentString[BANDS_PRESENT_SIZE + 1]; char theFormatVersion[FORMAT_VERSION_SIZE + 1]; }; class RadiomRecord { public: RadiomRecord(); ~RadiomRecord(){} double theBias[8]; double theGain[8]; }; class GeoRecord { public: GeoRecord(); ~GeoRecord(){} char theMapProjectionName[MAP_PROJECTION_NAME_SIZE + 1]; char theEllipsoid[ELLIPSOID_SIZE + 1]; char theDatum[DATUM_SIZE + 1]; double theProjectionParams[15]; char theUlLon[LON_SIZE + 1]; // deg, min, sec char theUlLat[LAT_SIZE + 1]; // deg, min, sec double theUlEasting; double theUlNorthing; char theUrLon[LON_SIZE + 1]; // deg, min, sec char theUrLat[LAT_SIZE + 1]; // deg, min, sec double theUrEasting; double theUrNorthing; char theLrLon[LON_SIZE + 1]; // deg, min, sec char theLrLat[LAT_SIZE + 1]; // deg, min, sec double theLrEasting; double theLrNorthing; char theLlLon[LON_SIZE + 1]; // deg, min, sec char theLlLat[LAT_SIZE + 1]; // deg, min, sec double theLlEasting; double theLlNorthing; char theCenterLon[LON_SIZE + 1]; // deg, min, sec char theCenterLat[LAT_SIZE + 1]; // deg, min, sec double theCenterEasting; double theCenterNorthing; int theCenterSample; // Nearest whole pixel. int theCenterLine; // Nearest whole pixel. int theHorizontalOffset; // pixels double theOrientationAngle; // degrees double theSunElevationAngle; // degrees double theSunAzimuth; // degrees }; AdminRecord theAdminRecord; RadiomRecord theRadiomRecord; GeoRecord theGeoRecord; int errorStatus() const { return theErrorStatus; } void print(std::ostream& os) const; void write(std::ostream& os) const; friend std::ostream& operator<<(std::ostream& os, const ossimFfRevc& head); //> // Convenience methods. //< int path(int sceneNbr=0) const; //> Returns the path as an int. // Currently uses the1stPathRowNumber string. //< int row(int sceneNbr=0) const; //> Returns the row as an int from the pathRowString. // Currently uses the1stPathRowNumber string. //< int fraction(int sceneNbr=0) const; //> Returns the fraction as an int from the pathRowString. // Currently uses the1stPathRowNumber string. //< ossimString subScene(int sceneNbr=0) const; //> Returns the sub scene as an string from the pathRowString. // Currently uses the1stPathRowNumber string. //< ossimString pathRow(int sceneNbr=0) const; //> Returns a string represnting the path and row as a name. // i.e.: 287/05100D0 will be returned as p287r05100D0 // This method will remove any spaces. //< private: void loadFromStream(ossim::istream& is); int checkStream(ossim::istream& is); ErrorStatus theErrorStatus; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimFgdcTxtDoc.h000066400000000000000000000071771352751253100244260ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File ossimFgdcTxtDoc.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: ossimFgdcTxtDoc class declaration. // // FGDC = "Federal Geographic Data Committee" // // See: http://www.fgdc.gov/ // //---------------------------------------------------------------------------- // $Id: ossimFgdcTxtDoc.h 2673 2011-06-06 14:57:24Z david.burken $ #ifndef ossimFgdcTxtDoc_HEADER #define ossimFgdcTxtDoc_HEADER 1 #include #include #include #include #include /** * @class ossimFgdcTxtDoc * @brief Support data container for FGDC in text format. * * Has minimum parse support to get Spatial_Reference_Information section to * extract projection information. * * TODO: Make an ossimFgdcBase and consolidate code from * ossimFgdcXmlDoc and this class. (drb - 15 Aug. 2011) */ class OSSIM_DLL ossimFgdcTxtDoc : public ossimReferenced { public: /** default constructor */ ossimFgdcTxtDoc(); /** virtual destructor */ virtual ~ossimFgdcTxtDoc(); /** * @brief open method. * * @param file File name to open. * * @return true on success false on error. */ bool open(const ossimFilename& file); /** * @brief Close method. * * This doesn't really do anything. Here only because I think every open() * should have a matching close(). */ void close(); /** * @brief Gets projection from Spatial_Reference_Information block. * @param proj Intialized by this method. Set to null on projection cannot * be created. */ void getProjection(ossimRefPtr& proj); /** * @brief Gets units from Altitude_Distance_Units. * @return Units if found, OSSIM_UNIT_UNKNOWN if not. */ void getAltitudeDistanceUnits(std::string& units) const; private: /** * @brief Gets projection from Spatial_Reference_Information block for * version FGDC-STD-001-1998. * @param str Stream to read from. * @param proj Intialized by this method. Set to null on projection cannot * be created. */ void getProjectionV1(std::ifstream& str, ossimRefPtr& proj); /** * @brief Finds key and returns true if present. * * Leaves stream at position of last getline. * * @param str Stream to read from. * @param key Key to find. * @return true if present false if not. */ bool findKey( std::ifstream& str, const std::string& key); /** * @brief Finds key and returns and intializes value if present. * * Stream position at end of call is dependent on seekBack flag. * * @param str Stream to read from. * @param seekBack If true the stream will be repositioned to original * position at beginning of the call. * @param key Key to find. * @param value Intialized with value if key is found. * @return true if present false if not. */ bool findKey( std::ifstream& str, bool seekBack, const std::string& key, std::string& value); /** * Gets ossim datum string from fgdc datum string. */ void getOssimDatum( const std::string& fgdcDatumString, std::string& ossimDatumCode ) const; // Container for relevant data from FGDC file. ossimRefPtr m_kwl; }; // End: class ossimFgdcTxtDoc #endif /* #ifndef ossimFgdcTxtDoc_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimFgdcXmlDoc.h000066400000000000000000000117361352751253100244030ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // // Description: Utility class to encapsulate parsing projection info in the xml file. // //---------------------------------------------------------------------------- // $Id: ossimFgdcXmlDoc.h 2063 2011-01-19 19:38:12Z ming.su $ #ifndef ossimFgdcXmlDoc_HEADER #define ossimFgdcXmlDoc_HEADER 1 #include #include #include #include #include #include class ossimDatum; class ossimDrect; /** @brief Class for FGDC XML doc parsing. */ class OSSIMDLLEXPORT ossimFgdcXmlDoc { public: /** @brief default constructor */ ossimFgdcXmlDoc(); /** @brief destructor */ ~ossimFgdcXmlDoc(); /** * @brief Open method. * @return true on success, false on error. */ bool open(const ossimFilename& xmlFileName); /** @return true if m_xmlDocument is open; false if not. */ bool isOpen() const; /** @brief close method. */ void close(); /** @brief Gets projection from document. */ ossimRefPtr getProjection(); /** @return Unit type. Note meters is the default if not found in doc. */ ossimUnitType getUnitType() const; /** * @return text for path "/metadata/spref/horizsys/cordsysn/geogcsn" */ bool getGeoCsn(ossimString& s) const; /** * @return text for path "/metadata/spref/horizsys/cordsysn/projcsn" */ bool getProjCsn(ossimString& s) const; /** * @brief Get the Altitude Distance Units * * Path: "/metadata/spref/vertdef/altsys/altunits" * * Domain: "meters" "feet" * * @return Text for path. */ bool getAltitudeDistantUnits(ossimString& s) const; /** * @brief Get the Grid Coordinate system * * Path: "/metadata/spref/horizsys/planar/gridsys/gridsysn" * * @return Text for path. */ bool getGridCoordinateSystem(ossimString& s) const; /** * @brief Gets projection from Grid Coordinate system node. * * Throws ossimException on error. * * @return Refptr with projection pointer. Underlying pointer may be null. */ ossimRefPtr getGridCoordSysProjection(); /** * @brief Get the Grid Coordinate system * * Path: "/metadata/spref/horizsys/planar/gridsys/gridsysn" * * @return Text for path. */ bool getHorizontalDatum(ossimString& s) const; /** * @brief Get the Planar Distant Units * * Path: "/metadata/spref/horizsys/planar/planci/plandu" * * Domain: "meters" "international feet" "survey feet" * * @return Text for path. */ bool getPlanarDistantUnits(ossimString& s) const; /** * @brief Get UTM false Northing. * * Path: "/metadata/spref/horizsys/planar/gridsys/utm/transmer/fnorth" * * @return Text for path. */ bool getUtmFalseNorthing(ossimString& s) const; /** * @brief Get UTM zone. * * Path: "/metadata/spref/horizsys/planar/gridsys/utm/utmzone" * * Domain: 1 <= UTM Zone Number <= 60 for the northern hemisphere; * -60 <= UTM Zone Number <= -1 for the southern hemisphere * * @return Text for path. */ bool getUtmZone(ossimString& s) const; /** * @brief Get Bands. * * Path: "/metadata/spdoinfo/rastinfo/vrtcount" * * the maximum number of raster objects along the vertical (z) axis. * For use with rectangular volumetric raster objects (voxels). * * @return int for path. */ ossim_uint32 getNumberOfBands(); /** * @brief Gets path from doc and initializes string. * * This method errors if multiple nodes are found for path. * * @param path Xml path to look for. * @param s String to initialize. * @return true on success and false if path is not found or if there * are more than one of path. */ bool getPath(const ossimString& path, ossimString& s) const; bool getImageSize(ossimIpt& size) const; private: bool getXRes(ossim_float64& v) const; bool getYRes(ossim_float64& v) const; void getBoundingBox(ossimDrect& rect) const; /** * @brief Gets path from doc and initializes string. * @param path Xml path to look for. * @param v Value to initialize. * @return true on success and false if path is not found or if there * are more than one of path. */ bool getPath(const ossimString& path, ossim_float64& v) const; /** * Gets the ossimDatum from string. */ const ossimDatum* createOssimDatum(const ossimString& s) const; ossimFilename m_xmlFilename; ossimRefPtr m_xmlDocument; ossimRefPtr m_projection; mutable bool m_boundInDegree; }; #endif /* matches: #ifndef ossimFgdcXmlDoc */ ossim-Miami-2.9.1/include/ossim/support_data/ossimGeoTiff.h000066400000000000000000000254261352751253100237550ustar00rootroot00000000000000//*************************************************************************** // FILE: ossimGeoTiff.h // // License: See top level LICENSE.txt file. // // Description: // // Class declaration for ossimGeoTiff which is designed to read and hold tag // information. // //*************************************************************************** // $Id: ossimGeoTiff.h 21023 2012-05-29 20:32:22Z dburken $ #ifndef ossimGeoTiff_HEADER #define ossimGeoTiff_HEADER 1 #include #include #include #include #include #include #include #include #include #include #include class ossimFilename; class ossimKeywordlist; class ossimPrivateGtifDef; class ossimProjection; class ossimTieGptSet; class OSSIM_DLL ossimGeoTiff : public ossimErrorStatusInterface { public: /** default constructor */ ossimGeoTiff(); ossimGeoTiff(const ossimFilename& file, ossim_uint32 entryIdx=0); ~ossimGeoTiff(); enum { UNDEFINED = 0, PIXEL_IS_AREA = 1, PIXEL_IS_POINT = 2, GT_MODEL_TYPE_GEO_KEY = 1024, GT_RASTER_TYPE_GEO_KEY = 1025, GEOGRAPHIC_TYPE_GEO_KEY = 2048, GEOG_GEODETIC_DATUM_GEO_KEY = 2050, GEOG_ANGULAR_UNITS_GEO_KEY = 2054, PROJECTED_CS_TYPE_GEO_KEY = 3072, PCS_CITATION_GEO_KEY = 3073, PROJECTION_GEO_KEY = 3074, PROJ_COORD_TRANS_GEO_KEY = 3075, LINEAR_UNITS_GEO_KEY = 3076, PROJ_STD_PARALLEL1_GEO_KEY = 3078, PROJ_STD_PARALLEL2_GEO_KEY = 3079, PROJ_NAT_ORIGIN_LONG_GEO_KEY = 3080, PROJ_NAT_ORIGIN_LAT_GEO_KEY = 3081, PROJ_FALSE_EASTING_GEO_KEY = 3082, PROJ_FALSE_NORTHING_GEO_KEY = 3083, PROJ_CENTER_LONG_GEO_KEY = 3088, PROJ_CENTER_LAT_GEO_KEY = 3089, PROJ_SCALE_AT_NAT_ORIGIN_GEO_KEY = 3092, LINEAR_METER = 9001, LINEAR_FOOT = 9002, LINEAR_FOOT_US_SURVEY = 9003, ANGULAR_DEGREE = 9102, ANGULAR_ARC_MINUTE = 9103, ANGULAR_ARC_SECOND = 9104, ANGULAR_GRAD = 9105, ANGULAR_GON = 9106, ANGULAR_DMS = 9107, ANGULAR_DMS_HEMISPHERE = 9108, PCS_BRITISH_NATIONAL_GRID = 27700, USER_DEFINED = 32767 }; /* enum CompressType */ /* { */ /* NOT_COMPRESSED = 0, */ /* COMPRESSED = 1 */ /* }; */ /* enum PhotoInterpretation */ /* { */ /* PHOTO_MINISWHITE = 0, // min value is white */ /* PHOTO_MINISBLACK = 1, // min value is black */ /* PHOTO_RGB = 2, // RGB color model */ /* PHOTO_PALETTE = 3, // color map indexed */ /* PHOTO_MASK = 4, // $holdout mask */ /* PHOTO_SEPARATED = 5, // !color separations */ /* PHOTO_YCBCR = 6, // !CCIR 601 */ /* PHOTO_CIELAB = 8 // !1976 CIE L*a*b* */ /* }; */ enum ModelType { UNKNOWN = 0, MODEL_TYPE_PROJECTED = 1, // Projection Coordinate System MODEL_TYPE_GEOGRAPHIC = 2, // Geographic latitude-longitude System MODEL_TYPE_GEOCENTRIC = 3 }; static int getPcsUnitType(ossim_int32 pcsCode); static bool writeTags(TIFF* tiffOut, const ossimRefPtr projectionInfo, bool imagineNad27Flag=false); /** * @brief Writes a geotiff box to a buffer. * * This will write a degenerate GeoTIFF file to a temp file, copy file to * the buffer and then delete the temp file. * * @param tmpFile The temporary filename. * @param rect The output image rect. * @param proj Pointer to output projection. * @param buf The buffer to stuff with data. * @param pixelType OSSIM_PIXEL_IS_POINT(0) or OSSIM_PIXEL_IS_AREA(1) * @return true on success, false on error. */ static bool writeJp2GeotiffBox(const ossimFilename& tmpFile, const ossimIrect& rect, const ossimProjection* proj, std::vector& buf, ossimPixelType pixelType); /** * Reads tags. * Returns true on success, false on error. */ bool readTags(const ossimFilename& file, ossim_uint32 entryIdx=0); /** * @brief Method to parse the tiff file from an open tiff pointer for a * given index. * * This will initialize this container for a subsequent call to * addImageGeometry. * * @param tiff The opened TIFF* to read from. * * @param entryIdx Entry (tiff directory) to read. * * @param ownTiffPtrFlag If true the tiff pointer will be deleted by this * object; else, it will simply zero out the pointer at the end of method. * This allows for external code to pass in their open tiff pointer * without this object closing it. * * @return true on success, false on error. */ bool readTags(TIFF* tiff, ossim_uint32 entryIdx, bool ownTiffPtrFlag); bool readTags(std::shared_ptr state, ossim_uint32 entryIdx); /** * Returns the map zone as an interger. */ int mapZone() const; /** * Add geometry info from tags to keword list. * Returns true on success, false on error. */ bool addImageGeometry(ossimKeywordlist& kwl, const char* prefix=0) const; /** * Returns an ossimString representing the ossim projection name. * Returns "unknown" if it can't find a match. */ ossimString getOssimProjectionName() const; /** * Attempts to set the ossim projection name from keys read. */ void setOssimProjectionName(); /** * Attempts to set the ossim projection name from keys read. */ void setOssimProjectionName(std::shared_ptr state, ossim_int32 entryIdx=0); /** * Returns an ossimString representing the ossim datum name code. * Returns "unknown" if it can't find a match. */ ossimString getOssimDatumName() const; /** * Attempts to set the ossim datum code. */ void setOssimDatumName(); void setOssimDatumName(std::shared_ptr state, ossim_int32 entryIdx=0); void getScale(std::vector& scale) const; void getTiePoint(std::vector& tie_point) const; void getModelTransformation(std::vector& transform) const; const std::vector& getTiePoint() const; const std::vector& getModelTransformation() const; const std::vector& getScale() const; ossimPixelType getRasterType() const; int getWidth() const; int getLength() const; /* int getSamplesPerPixel() const; */ /** Prints data members. */ virtual std::ostream& print(std::ostream& out) const; private: // Disallow ... ossimGeoTiff& operator=(const ossimGeoTiff& /*rhs*/) { return *this; } //! Initializes data members given a projection code. Returns TRUE if valid PCS code specified. //! Resets the PCS code to 0 if invalid. bool parsePcsCode(); bool parseGcsCode(); //! Initializes data members given a projection. Returns TRUE if successful. bool parseProjection(ossimMapProjection* map_proj); /** * Converts double passed in to meters if needed. The conversion is * base on "theLiniarUnitsCode". */ double convert2meters(double d) const; /** * @return true if conditions are present to use model transform; false * if not. */ bool usingModelTransform() const; /** * Initializes tieSet from theTiePoints. Has logic to shift one based * ties to be zero based like the rest of the code. */ void getTieSet(ossimTieGptSet& tieSet) const; /** * Attempts to detect if tie points are one or zero based. * @return true if one base, false if not. */ bool hasOneBasedTiePoints() const; /** * In the case when tie points are not explicitely provided, this method assigns them given * the image-model transform. * @return true if properly assigned, false if not. */ bool initTiePointsFromImageModelTransform(); TIFF* theTiffPtr; ossim_uint32 theGeoKeyOffset; int theGeoKeyLength; bool theGeoKeysPresentFlag; int theZone; ossimString theHemisphere; int theDoubleParamLength; int theAsciiParamLength; ossimString theProjectionName; ossimString theDatumName; std::vector theScale; // tag 33550 std::vector theTiePoint; // tag 33922 std::vector theModelTransformation; // tag 34264 std::vector theDoubleParam; // tag 34736 ossimString theAsciiParam; // tag 34737 ossim_uint32 theWidth; // tag 256 ossim_uint32 theLength; // tag 257 ossim_uint16 theBitsPerSample; // tag 258 ossim_uint16 theModelType; // key 1024 ossim_uint16 theRasterType; // key 1025 undefined=0, area=1, point=2 ossim_uint16 theGcsCode; // key 2048 ossim_uint16 theDatumCode; // key 2050 ossim_uint16 theAngularUnits; // key 2054 ossim_uint32 thePcsCode; // key 3072 ossimString thePcsCitation; // key 3073 ossim_uint16 theCoorTransGeoCode; // key 3075 ossim_uint16 theLinearUnitsCode; // key 3076 double theStdPar1; // key 3078 double theStdPar2; // key 3079 mutable double theOriginLon; // key 3080 mutable double theOriginLat; // key 3081 double theFalseEasting; // key 3082 double theFalseNorthing; // key 3083 double theScaleFactor; // key 3092 ossimPrivateGtifDef* thePrivateDefinitions; static std::mutex theMutex; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimGmlSupportData.h000066400000000000000000000120331352751253100253260ustar00rootroot00000000000000//--- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: GML support data object. // //--- // $Id$ #ifndef ossimGmlSupportData_HEADER #define ossimGmlSupportData_HEADER 1 #include #include #include #include class ossimImageGeometry; class ossimIpt; class ossimIrect; class ossimKeywordlist; class ossimXmlDocument; class ossimXmlNode; /** @brief GML support data class. */ class OSSIM_DLL ossimGmlSupportData { public: /** default constructor */ ossimGmlSupportData(); /** destructor */ ~ossimGmlSupportData(); /** * @brief Initializes gml block from geometry file. * @param geom * @param rect Output rectangle (view rect). */ bool initialize( const ossimImageGeometry* geom, const ossimIrect& rect ); /** * @brief Initializes from stream assumed to be a gml block. * @param in */ bool initialize( std::istream& in ); /** @brief Write xml doc to stream. */ bool write( std::ostream& os ); /** @return Reference to xml doc. */ ossimRefPtr getXmlDoc() const; /** * @brief Extracts geometry info to keyword list. * * Populates the keyword list with image geometry information. This * method is used to relay projection/model information to users. * * @param geomKwl Keyword list that will be initialized with geometry info. * * @return true if geometry info is present, false if not. */ bool getImageGeometry( ossimKeywordlist& geomKwl ) const; private: ossimRefPtr getGmljp2V1RootNode() const; ossimRefPtr getGmljp2V2RootNode() const; void getGeoOrigin( const ossimImageGeometry* geom, const ossimIpt& ul, ossimString& originString, ossimString& offsetVector1String, ossimString& offsetVector2String ) const; void getMapOrigin( const ossimImageGeometry* geom, const ossimIpt& ul, ossimString& originString, ossimString& offsetVector1String, ossimString& offsetVector2String ) const; void getLimits( const ossimIrect& rect, ossimString& gridHighString, ossimString& gridLowString ) const; void getGeoBounds( const ossimImageGeometry* geom, const ossimIrect& rect, ossimString& upperCornerString, ossimString& lowerCornerString ) const; #if 0 bool configureGmljp2V1( ossimRefPtr node, const ossimImageGeometry* geom, const ossimIrect& rect ); #endif bool configureGmljp2V2( ossimRefPtr node, const ossimImageGeometry* geom, const ossimIrect& rect ); bool configureBounds ( ossimRefPtr node, const ossimImageGeometry* geom, const ossimIrect& rect ); /** * @brief For sensor model data: * @param geomKwl Initialized by this. */ bool getImageGeometryFromSeonsorModel( ossimKeywordlist& geomKwl ) const; /** * @brief For map projected data: * @param geomKwl Initialized by this. */ bool getImageGeometryFromRectifiedGrid( ossimKeywordlist& geomKwl ) const; /** * @brief Adds line and sample to keyword list. * @param xpath0 * @param useGmlPrefix If true tack on "gml:" to paths. * @param geomKwl Initialized by this. */ bool addLineSamps( const ossimString& xpath0, bool useGmlPrefix, ossimKeywordlist& geomKwl ) const; /** * @brief Adds tie point to keyword list. * @param xpath0 * @param useGmlPrefix If true tack on "gml:" to paths. * @param geomKwl Initialized by this. */ bool addTie( const ossimString& xpath0, bool useGmlPrefix, ossim_uint32 pcsCode, ossimKeywordlist& geomKwl ) const; /** * @brief Adds tie and scale to keyword list. * @param xpath0 * @param useGmlPrefix If true tack on "gml:" to paths. * @param geomKwl Initialized by this. */ bool addScale( const ossimString& xpath0, bool useGmlPrefix, ossim_uint32 pcsCode, ossimKeywordlist& geomKwl ) const; ossimRefPtr m_xmlDocument; // bool m_use_gmljp2_version2; ossim_uint32 m_pcsCodeMap; ossim_uint32 m_pcsCodeGeo; ossimString m_srsNameStringMap; ossimString m_srsNameStringGeo; ossimString m_srsDimensionString; ossimString m_axisLabelsStringMap; ossimString m_axisLabelsStringGeo; ossimString m_uomLabelsStringMap; ossimString m_uomLabelsStringGeo; }; #endif /* End of "#ifndef ossimGmlSupportData_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimIkonosMetaData.h000066400000000000000000000062161352751253100252710ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Class declaration for ossimIkonosMetaData. // // This class parses a Space Imaging Ikonos meta data file. // //******************************************************************** // $Id: ossimIkonosMetaData.h 15828 2009-10-28 13:11:31Z dburken $ #ifndef ossimIkonosMetaData_HEADER #define ossimIkonosMetaData_HEADER #include #include #include #include class ossimFilename; class ossimKeywordlist; class OSSIMDLLEXPORT ossimIkonosMetaData : public ossimObject { public: /** @brief default constructor */ ossimIkonosMetaData(); /** * @brief Open method that takes the image file, derives the metadata, * header and rpc files, then calls parse methods parseMetaData, * parseHdrData, and parseRpcData. * * @param imageFile Usually in the form of "po_2619900_pan_0000000.tif". * * @return true on success, false on error. */ bool open(const ossimFilename& imageFile); void clearFields(); ossimString getSensorID() const; //--- // Convenient method to print important image info: //--- virtual std::ostream& print(std::ostream& out) const; /** * Method to save the state of the object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0) const; /** * Method to the load (recreate) the state of the object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); /** * @brief Method to parse Ikonos metadata file. * * @param metadata File name usually in the form of * "po_149875_metadata.txt." * * @return true on success, false on error. */ bool parseMetaData(const ossimFilename& metadata); /** * @brief Method to parse Ikonos header file. * * @param metadata File name usually in the form of * "po_149875_pan_0000000.hdr" * * @return true on success, false on error. */ bool parseHdrData(const ossimFilename& data_file); /** * @brief Method to parse Ikonos rpc file. * * @param metadata File name usually in the form of * "po_149875_pan_0000000_rpc.txt" * * @return true on success, false on error. * * @note Currently NOT implemented. */ bool parseRpcData(const ossimFilename& data_file); protected: /** virtual destructor */ virtual ~ossimIkonosMetaData(); private: ossim_float64 theNominalCollectionAzimuth; ossim_float64 theNominalCollectionElevation; ossim_float64 theSunAzimuth; ossim_float64 theSunElevation; ossim_uint32 theNumBands; ossimString theBandName; ossimString theProductionDate; ossimString theAcquisitionDate; ossimString theAcquisitionTime; ossimString theSensorID; TYPE_DATA }; #endif /* #ifndef ossimIkonosMetaData_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimImageMetaData.h000066400000000000000000000110261352751253100250440ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // // Contains class declaration for ossimImageMetaData. // //******************************************************************* // $Id: ossimImageMetaData.h 21527 2012-08-26 16:50:49Z dburken $ #ifndef ossimImageMetaData_HEADER #define ossimImageMetaData_HEADER 1 #include #include #include #include class ossimKeywordlist; class OSSIM_DLL ossimImageMetaData { public: ossimImageMetaData(); ossimImageMetaData(ossimScalarType aType, ossim_uint32 numberOfBands); ossimImageMetaData(const ossimImageMetaData& rhs); const ossimImageMetaData& operator=(const ossimImageMetaData& rhs); ~ossimImageMetaData(); void clear(); void setDefaultsForArrays(); void setNumberOfBands(ossim_uint32 numberOfBands); ossim_uint32 getNumberOfBands()const; /** * @return string reference containing rgb band order, e.g. "(2,1,0)". * Will be an emptry string if not set. */ const std::string& getRgbBands() const; /** * @brief Convenience method to get the zero based rgb output band list. * * This method returns true on success; false, if rgb_bands key is not set * in dot omd file. * * @note: Current ossimImageMetaData logic requires key "number_bands" to * be set and at least 3. * * @param bandList Initialized by this on success. * * @return false */ bool getRgbBands(std::vector& bandList) const; void setScalarType(ossimScalarType aType); ossimScalarType getScalarType()const; /** @return The bytes per pixel. This is for a single band. */ ossim_uint32 getBytesPerPixel() const; double getMinPix(ossim_uint32 band)const; void setMinPix(ossim_uint32 band, double pix); void setMaxPix(ossim_uint32 band, double pix); void setNullPix(ossim_uint32 band, double pix); double getMaxPix(ossim_uint32 band)const; double getNullPix(ossim_uint32 band)const; const double* getMinPixelArray()const; const double* getMaxPixelArray()const; const double* getNullPixelArray()const; void setMinValuesValid(bool flag); void setMaxValuesValid(bool flag); void setNullValuesValid(bool flag); bool getMinValuesValidFlag()const; bool getMaxValuesValidFlag()const; bool getNullValuesValidFlag()const; bool isValid()const; bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; /** * @brief Method to update band values. * * Assumes a previous initialization and does not error out if band data is * not found. This does NOT clear the object prior to loading like the * loadState(...) method. Can be used to update min/max values from a * "compute min max". * * @param kwl Keyword list to initialize from. * * @param prefix Prefix, e.g. "image0.". */ void updateMetaData( const ossimKeywordlist& kwl, const std::string& prefix ); /** * @brief Print method. * @return std::ostream& */ std::ostream& print(std::ostream& out) const; /** * @note Since the print method is virtual, derived classes only need * to implement that, not an addition operator<<. */ friend OSSIM_DLL std::ostream& operator<<(std::ostream& out, const ossimImageMetaData& obj); private: /** * Looks for ossimKeywordNames::NUMBER_BANDS_KW, if not found looks for. */ ossim_uint32 getBandCount(const ossimKeywordlist& kwl, const std::string& prefix) const; double* theNullPixelArray; double* theMinPixelArray; double* theMaxPixelArray; bool theMinValuesValidFlag; bool theMaxValuesValidFlag; bool theNullValuesValidFlag; ossimScalarType theScalarType; ossim_uint32 theBytesPerPixel; ossim_uint32 theNumberOfBands; //--- // String containing rgb bands, e.g. (2,1,0); // Added to allow tiled tiffs to set band selection correctly by picking // up order from omd file. //--- std::string theRgbBands; }; #endif /* #ifndef ossimImageMetaData_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimInfoBase.h000077500000000000000000000050741352751253100241200ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Base class for Info object. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimInfoBase_HEADER #define ossimInfoBase_HEADER 1 #include #include #include #include #include #include class ossimFilename; class ossimKeywordlist; /** * @brief Info Base. * * This is the base class for all info objects. The purpose of an Info object * is to dump whatever info is available for a given file name to user. */ class OSSIM_DLL ossimInfoBase : public ossimReferenced { public: /** default constructor */ ossimInfoBase(); /** * @brief open method. * * @param file File name to open. * * @return true on success false on error. */ virtual bool open(const ossimFilename& file); /** * @brief open method. * * @param str File name to open. * * @return true on success false on error. */ virtual bool open(std::shared_ptr& str, const std::string& connectionString); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const = 0; /** * @brief Sets the overview flag. * @param flag If true overview info is processed also. */ void setProcessOverviewFlag(bool flag); /** * @brief Method to get the overview flag. * @return The overview flag. */ bool getProcessOverviewFlag() const; /** * @brief Method to dump info to a keyword list. * @param kwl The keyword list to initialize. * @return true on success, false on error. */ virtual bool getKeywordlist(ossimKeywordlist& kwl)const; /** * @brief Method to dump info to a keyword list. * @param kwl The keyword list to initialize. * @param entryIndex Entry to print. Not supported by all info objects * yet. * @return true on success, false on error. */ virtual bool getKeywordlist(ossimKeywordlist& kwl, ossim_uint32 entryIndex)const; protected: /** virtual destructor */ virtual ~ossimInfoBase(); bool theOverviewFlag; // If true overview information should be processed. }; #endif /* End of "#ifndef ossimInfoBase_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimInfoFactory.h000066400000000000000000000027361352751253100246540ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Factory for info objects. // //--- // $Id$ #ifndef ossimInfoFactory_HEADER #define ossimInfoFactory_HEADER 1 #include #include class ossimFilename; class ossimInfoBase; /** * @brief Info factory. */ class OSSIM_DLL ossimInfoFactory : public ossimInfoFactoryInterface { public: /** virtual destructor */ virtual ~ossimInfoFactory(); static ossimInfoFactory* instance(); /** * @brief create method. * * @param file Some file you want info for. * * @return ossimInfoBase* on success 0 on failure. Caller is responsible * for memory. */ // virtual ossimInfoBase* create(const ossimFilename& file) const; virtual std::shared_ptr create(const ossimFilename& file) const; virtual std::shared_ptr create(std::shared_ptr& str, const std::string& connectionString)const; private: /** hidden from use default constructor */ ossimInfoFactory(); /** hidden from use copy constructor */ ossimInfoFactory(const ossimInfoFactory& obj); /** hidden from use operator = */ const ossimInfoFactory& operator=(const ossimInfoFactory& rhs); /** The single instance of this class. */ static ossimInfoFactory* theInstance; }; #endif /* End of "#ifndef ossimInfoFactory_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimInfoFactoryInterface.h000066400000000000000000000027221352751253100264700ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Interface for info factories. // //--- // $Id$ #ifndef ossimInfoFactoryInterface_HEADER #define ossimInfoFactoryInterface_HEADER 1 #include #include class ossimFilename; //--- // Note: Deriving from ossimObjectFactory is being backed out as no // ossimObjectFactory interfaces were ever called and it introduces warning in // the header file so anyone who #includes this gets warnings... // // We can add back if there is a interface from ossimObjectFactory needed; // else, please leave out. // // drb 20120518 //--- /** * @brief Info factory. */ class OSSIM_DLL ossimInfoFactoryInterface { public: /** default constructor */ ossimInfoFactoryInterface(){} /** virtual destructor */ virtual ~ossimInfoFactoryInterface(){} /** * @brief Pure virtual create method. Derived classes must implement to * be concrete. * * @param file Some file you want info for. * * @return ossimInfoBase* on success 0 on failure. Caller is responsible * for memory. */ virtual std::shared_ptr create(const ossimFilename& file) const = 0; virtual std::shared_ptr create(std::shared_ptr& str, const std::string& connectionString) const = 0; }; #endif /* End of "#ifndef ossimInfoFactoryInterface_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimInfoFactoryRegistry.h000066400000000000000000000051161352751253100264000ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Class declaration of Registry (singleton) for info factories. // //--- // $Id$ #ifndef ossimInfoFactoryRegistry_HEADER #define ossimInfoFactoryRegistry_HEADER 1 #include /* for OSSIM_DLL macro */ #include #include #include #include #include // Forward class declarations. class ossimInfoFactoryInterface; class ossimInfoBase; class ossimFilename; class OSSIM_DLL ossimInfoFactoryRegistry { public: /** destructor */ ~ossimInfoFactoryRegistry(); /** * instance method * * @return Pointer to the instance of the registry. */ static ossimInfoFactoryRegistry* instance(); /** * @brief Method to add factory to registry. * @param factory Factory to register. */ void registerFactory(ossimInfoFactoryInterface* factory); /** * @brief Adds factory to the front of the registry. * @param factory Factory to register. */ void registerFactoryToFront( ossimInfoFactoryInterface* factory ); /** * Method to remove a factory from the registry. Used by plugins when they * are unloaded. * @param factory Factory to remove. */ void unregisterFactory(ossimInfoFactoryInterface* factory); /** * @brief Create method. * * @param file Some file you want info for. * * @return ossimInfoBase* on success 0 on failure. Caller is responsible * for memory. */ std::shared_ptr create(const ossimFilename& file) const; /** * @brief Create method. * * @param file Some file you want info for. * * @return ossimInfoBase* on success 0 on failure. Caller is responsible * for memory. */ std::shared_ptr create( std::shared_ptr& str, const std::string& connectionString) const; protected: /** * @brief Hidden from use default constructor. * @note Adds ossimInfoFactory to registry. */ ossimInfoFactoryRegistry(); /** @brief hidden from use copy constructor */ ossimInfoFactoryRegistry(const ossimInfoFactoryRegistry& obj); /** @brief hidden from use assignment operator */ const ossimInfoFactoryRegistry& operator=( const ossimInfoFactoryRegistry& rhs); std::vector m_factoryList; std::mutex m_mutex; static ossimInfoFactoryRegistry* m_instance; }; #endif /* #ifndef ossimInfoFactoryRegistry_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimJ2kCodRecord.h000066400000000000000000000047371352751253100246470ustar00rootroot00000000000000//--- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Container class for J2K Coding style default (COD) record. // // See document BPJ2K01.00 Table 7-7 Image and tile size (15444-1 Annex A5.1) // //--- // $Id$ #ifndef ossimJ2kCodRecord_HEADER #define ossimJ2kCodRecord_HEADER 1 #include #include #include class OSSIM_DLL ossimJ2kCodRecord { public: /** default constructor */ ossimJ2kCodRecord(); /** destructor */ ~ossimJ2kCodRecord(); /** * Parse method. Performs byte swapping as needed. * * @param in Stream to parse. * * @note COD Marker (0xff52) is not read. */ void parseStream(std::istream& in); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "j2k." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; /** * @return LRCP, RLCP, RPCL, PCRL, CPRL or unknown. */ std::string getProgressionOrderAsString( ossim_uint8 progressionOrder ) const; ossim_uint8 getProgressionOrder() const; /** operator<< */ friend OSSIM_DLL std::ostream& operator<<( std::ostream& out, const ossimJ2kCodRecord& obj); /** segmet marker 0xff52 (big endian) */ ossim_uint16 m_marker; /** length of segment minus marker */ ossim_uint16 m_lcod; /** Coding style */ ossim_uint8 m_scod; /** SGcod - Progression order */ ossim_uint8 m_progressionOrder; /** SGcod - Number of layers */ ossim_uint16 m_numberOfLayers; /** SGcod - Multiple component transform */ ossim_uint8 m_multipleComponentTransform; /** SPcod - Number of decomposition levels */ ossim_uint8 m_numberOfDecompositionLevels; /** SPcod - Code-block width */ ossim_uint8 m_codeBlockWidth; /** SPcod - Code-block height */ ossim_uint8 m_codeBlockHeight; /** SPcod - Code-block height */ ossim_uint8 m_codeBlockStyle; /** SPcod - transformation (wavelet filter) */ ossim_uint8 m_transformation; /** SPcod - precinct size (only is defined, Scod = xxxx xxx1) */ ossim_uint8 m_precinctSize; }; #endif /* End of "#ifndef ossimJ2kCodRecord_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimJ2kInfo.h000066400000000000000000000072211352751253100236650ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: J2K Info object. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimJ2kInfo_HEADER #define ossimJ2kInfo_HEADER #include #include #include class ossimEndian; /** * @brief TIFF info class. * * Encapsulates the listgeo functionality. */ class OSSIM_DLL ossimJ2kInfo : public ossimInfoBase { public: /** default constructor */ ossimJ2kInfo(); /** virtual destructor */ virtual ~ossimJ2kInfo(); /** * @brief open method. * * @param file File name to open. * * @return true on success false on error. */ virtual bool open(const ossimFilename& file); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; protected: /** Initializes s reference. Does byte swapping as needed. */ void readUInt16(ossim_uint16& s, std::ifstream& str) const; /** * @brief Prints 0xff52 COD_MARKER (0xff52). * @param out Stream to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "j2k." and key is "file_name" key becomes: * "j2k.file_name:" * @param str Input stream to pass to j2k record for parsing. Should be * just pass the marker. * @return output stream. */ std::ostream& printCodMarker(std::ostream& out, const std::string& prefix, std::ifstream& str) const; /** * @brief Prints 0xff51 SIZ_MARKER (0xff51). * @param out Stream to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "j2k." and key is "file_name" key becomes: * "j2k.file_name:" * @param str Input stream to pass to j2k record for parsing. Should be * just pass the marker. * @return output stream. */ std::ostream& printSizMarker(std::ostream& out, const std::string& prefix, std::ifstream& str) const; /** * @brief Prints 0xff90 SOT_MARKER (0xff90) * @param out Stream to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "j2k." and key is "file_name" key becomes: * "j2k.file_name:" * @param str Input stream to pass to j2k record for parsing. Should be * just pass the marker. * @return output stream. */ std::ostream& printSotMarker(std::ostream& out, const std::string& prefix, std::ifstream& str) const; /** * @brief Prints unhandle segment. This will only print the marker and * record length. * @param out Stream to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "j2k." and key is "file_name" key becomes: * "j2k.file_name:" * @param str Input stream to pass to j2k record for parsing. Should be * just pass the marker. * @param marker. The marker. * @return output stream. */ std::ostream& printUnknownMarker(std::ostream& out, const std::string& prefix, std::ifstream& str, ossim_uint16 marker) const; ossimFilename m_file; ossimEndian* m_endian; }; #endif /* End of "#ifndef ossimJ2kInfo_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimJ2kSizRecord.h000066400000000000000000000065061352751253100247030ustar00rootroot00000000000000//--- // License: MIT // Description: Container class for J2K Image and tile size (SIZ) record. // See document BPJ2K01.00 Table 7-6 Image and tile size (15444-1 Annex A5.1) // $Id$ //--- #ifndef ossimJ2kSizRecord_HEADER #define ossimJ2kSizRecord_HEADER 1 #include #include #include #include class OSSIM_DLL ossimJ2kSizRecord { public: /** default constructor */ ossimJ2kSizRecord(); /** destructor */ ~ossimJ2kSizRecord(); /** * Parse method. Performs byte swapping as needed. * * @param in Stream to parse. * * @note SIZ Marker (0xff51) is not read. */ void parseStream(ossim::istream& in); /** * Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); /** * @brief Gets the scalar type. * * Currently assumes all components are the same scalar type. * I.e., only looks at first component. * * @return scalar type based on bit depth and signed bit from theSsiz. */ ossimScalarType getScalarType() const; /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; /** operator<< */ friend OSSIM_DLL std::ostream& operator<<( std::ostream& out, const ossimJ2kSizRecord& obj); /** segmet marker 0xff51 (big endian) */ ossim_uint16 m_marker; /** length of segment minus marker */ ossim_uint16 m_Lsiz; /** profile */ ossim_uint16 m_Rsiz; /** width of reference grid */ ossim_uint32 m_Xsiz; /** height of reference grid */ ossim_uint32 m_Ysiz; /** * Horizontal offset from the orgin of reference grid to the left side * of image. */ ossim_uint32 m_XOsiz; /** * Vertical offset from the orgin of reference grid to the top * of image. */ ossim_uint32 m_YOsiz; /** width of one reference tile */ ossim_uint32 m_XTsiz; /** height of one reference tile */ ossim_uint32 m_YTsiz; /** * Horizontal offset from the orgin of reference grid to the left edge * of first tile. */ ossim_uint32 m_XTOsiz; /** * Vertical offset from the orgin of reference grid to the top * edge of first tile. */ ossim_uint32 m_YTOsiz; /** number of component in the image */ ossim_uint16 m_Csiz; /** * One for each component: * * sign bit and bit depth of data * unsigned = 0xxx xxxx (msb == 0) * signed = 1xxx xxxx (msb == 1) * bit depth = x000 0000 + 1 (first seven bits plus one) */ std::vector m_Ssiz; /** * One for each component: * * Horizontal separation of a sample of the component with respect to the * reference grid. */ std::vector m_XRsiz; /** * One for each component: * * Vertical separation of a sample of the component with respect to the * reference grid. */ std::vector m_YRsiz; }; #endif /* End of "#ifndef ossimJ2kSizRecord_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimJ2kSotRecord.h000066400000000000000000000041261352751253100246770ustar00rootroot00000000000000//--- // License: MIT // Description: Container class for J2K "Start Of Tile" (SOT) record. // marker: FF90 // See document BPJ2K01.00 Table 7-3 Image and tile size (15444-1 Annex A.4.2) // $Id$ //--- #ifndef ossimJ2kSotRecord_HEADER #define ossimJ2kSotRecord_HEADER 1 #include #include #include class OSSIM_DLL ossimJ2kSotRecord { public: /** default constructor */ ossimJ2kSotRecord(); /** destructor */ ~ossimJ2kSotRecord(); /** * Parse method. Performs byte swapping as needed. * * @param in Stream to parse. * * @note Marker is not read. */ void parseStream(ossim::istream& in); /** * Write method. * * Note: Write includes two marker bytes. * * @param out Stream to write to. */ void writeStream(std::ostream& out); /** * @brief Sets the tile index. * @param isot */ void setIsot( ossim_uint16 isot ); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; /** * operator<<. */ friend OSSIM_DLL std::ostream& operator<<( std::ostream& out, const ossimJ2kSotRecord& obj); /** Length in bytes of the marker segment. */ ossim_uint16 theLsot; /** Tile index. Tiles are in raster order starting at 0. */ ossim_uint16 theIsot; /** The length in bytes of this record including the SOT marker. */ ossim_uint32 thePsot; /** Tile-Part index. */ ossim_uint8 theTpsot; /** * 0 = Number of tile-parts of this tile in the codestream is not defined * in this header. * * 1-255 number of tile-parts of this tile in the codestream. */ ossim_uint8 theTnsot; }; #endif /* End of "#ifndef ossimJ2kSotRecord_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimJ2kTlmRecord.h000066400000000000000000000132441352751253100246670ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Container class declaration for J2K Tile-part lengths record. // See document BPJ2K01.10 Table 7-21 for detailed description. // // $Id$ //--- #ifndef ossimJ2kTlmRecord_HEADER #define ossimJ2kTlmRecord_HEADER 1 #include #include #include class OSSIM_DLL ossimJ2kTlmRecord { public: /** default constructor */ ossimJ2kTlmRecord(); /** destructor */ ~ossimJ2kTlmRecord(); /** * Parse method. Performs byte swapping as needed. * * @param in Stream to parse. * * @note SIZ Marker (0xff51) is not read. */ void parseStream(ossim::istream& in); /** * Write method. * * Note: Write include two marker bytes. * * @param out Stream to write to. */ void writeStream(std::ostream& out); /** * @return Index of this marker segment relative to other marker * segments in the header. */ ossim_uint8 getZtlm() const; /** * @brief Get the ST portion of STLM field( bits 5 and 6). * @return ST bits as an unsigned char. * */ ossim_uint8 getSt() const; /** * @brief Set the ST bits of STLM field. * * @param bits Either 0, 1, or 2. * * 0 = Ttlm parameter is not present. Tiles are in order. * 1 = Ttlm parameter 8 bits. * 2 = Ttlm parameter 16 bits. * * @return true if in range; false, if not. */ bool setSt(ossim_uint8 bits ); /** @return The higher order 4 bits of m_Stlm as an unsigned char. */ ossim_uint8 getSp() const; /** * @brief Set the SP bit of Stlm field. * * @param bit Either 0 or 1. * * 0 = Ptlm parameter 16 bits * 1 = Ptlm parameter 32 bits * * @return true if in range; false, if not. */ bool setSp(ossim_uint8 bit ); /** @return The tile count derived from m_Ltml, sd and sp. */ ossim_uint16 getTileCount() const; /** * @brief Get the tile length for tile at index from ptlm array. * @param index * @param length Initialized by this to of tile legnth or 0 out of array * bounds. * @return true on success, false if out of bounds. */ bool getTileLength( ossim_int32 index, ossim_uint32& length ) const; /** * @brief Sets the tile length for tile at x,y in ptlm array. * @param index * @param length of tile * @return true on success, false if out of bounds. */ bool setTileLength( ossim_int32 index, ossim_uint32 length ); /** * @brief Adds Ptlm array from first to last. * * The range used is [first,last), which contains all the elements between * first and last, including the element pointed by first but not the * element pointed by last. * * @param first array index * @param last array index * @param init Initialized by this. This is added to so whatever it starts * with you get that plus the accumlated indexes. * @return true on success; false, on errors. */ bool accumulate( ossim_int32 first, ossim_int32 last, std::streampos& init ) const; /** * @brief Sets SP bit, initializes ptlm array, and ltlm(size). * * Note: Ptlm array is cleared on this call. * * @param spBit 0 = 16 bit Ptlm parameter, 1 = 32 bit Ptlm parameter. * @param count of ptlm array or tiles. */ bool initPtlmArray( ossim_uint8 spBit, ossim_uint16 count ); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; /** operator<< */ friend OSSIM_DLL std::ostream& operator<<( std::ostream& out, const ossimJ2kTlmRecord& obj); private: /** @brief Deletes m_Ttlm and m_Ptlm arrays. */ void clear(); /** @brief Deletes m_Ttlm array. */ void clearTtlm(); /** @brief Deletes m_Ptlm array. */ void clearPtlm(); /** * @brief Computes length of this segment minus marker itself. * @return Length of this segment. */ ossim_uint16 computeLength( ossim_uint16 tileCount ) const; /** NOTE: tml segmet marker 0xff55 not stored. */ /** Length of segment minus marker. */ ossim_uint16 m_Ltlm; /** * Index of marker segment relative to all other TLM marker segments * present in the current header. 0 - 255 */ ossim_uint8 m_Ztlm; /** * Indicator for Ttlm and Ptlm field sizes. Two variable in one byte. * * ST Ttlm is lower order bytes. * * 0 = Ttlm size = 0 bits, tiles in order. Ttlm size = 0 bits * 1 = Ttlm size = 8 bits, range 0 - 254 * 2 = Ttlm size = 16 bits, range 0 - 65535 * * SP Ptlm is upper order bytes. * * 16 bits if SP = 0, range 14 - 65535 * 32 bits if SP = 1, range 14 - (2^31-1) */ ossim_uint8 m_Stlm; /** * Tile index for tile-parts. Either none or one value for every tile-part. * 0 bits if ST = 0 * 8 bits if ST = 1, range 0 - 254 * 16 bits if ST = 2, range 0 - 65534 */ void* m_Ttlm; /** * The length, in bytes, from the beginning of the SOT marker of the * tile-part to the end of the codestream data for that tile-part. * There should be one Ptlm for every tile-part. * * 16 bits if SP = 0, range 14 - 65535 * 32 bits if SP = 1, range 14 - (2^32-1) * */ void* m_Ptlm; }; #endif /* End of "#ifndef ossimJ2kTlmRecord_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimJp2Info.h000066400000000000000000000103021352751253100236640ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: JP2 Info object. // //---------------------------------------------------------------------------- // $Id: ossimJp2Info.h 23220 2015-04-04 15:39:49Z dburken $ #ifndef ossimJp2Info_HEADER #define ossimJp2Info_HEADER 1 #include /** * @brief JP2 info class. */ class OSSIM_DLL ossimJp2Info : public ossimJ2kInfo { public: /** Anonymous enumerations: */ enum { SIGNATURE_BOX_SIZE = 12, GEOTIFF_UUID_SIZE = 16 }; /** default constructor */ ossimJp2Info(); /** virtual destructor */ virtual ~ossimJp2Info(); /** * @brief open method. * * @param file File name to open. * * @return true on success false on error. */ virtual bool open(const ossimFilename& file); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; /** * @brief This gets a box of type and stuffs in box. * * Code for copying a box to a buffer. Currently used in ossimOpjWriter * to overcome short falls of trying to write in between the uuid box in * between the jp2h and start of jp2c written by opj_start_compress. * * @param type Defines box type. E.g. 0x6A703268 (jp2h) * @param includeAll if true the length fields are copied. If false * just the DBox is copied. * @param box Initialized by this. LBox and XLBox fields * are NOT copied to the box. * @return is the start position of the box. At the LBox. */ std::streamoff getBox( const ossim_uint32 type, bool includeAll, std::vector& box ) const; /** * @brief This gets a box of type and stuffs in box. * * Code for copying a box to a buffer. Note that stream is not rewound or * cleared if it hits EOF. * * @param type Defines box type. E.g. 0x6A703268 (jp2h) * @param includeAll if true the length fields are copied. If false * just the DBox is copied. * @param str Stream to read from. * @param box Initialized by this. LBox and XLBox fields * are NOT copied to the box. * @return The start position of the box (LBox) or zero if not found. */ std::streamoff getBox( const ossim_uint32& type, bool includeAll, std::ifstream& str, std::vector& box ) const; /** * @brief Method to get the embedded JP2 GeoTIFF box. This includes the 16 * GEOTIFF_UUID bytes. * @param str Stream to read from. * @return The start position of the box (LBox) or zero if not found. */ std::streamoff getGeotiffBox( std::ifstream& str, std::vector& box ) const; /** * @brief Method to get the embedded JP2 GML Box. * @param str Stream to read from. * @return The start position of the box (LBox) or zero if not found. */ std::streamoff getGmlBox( std::ifstream& str, std::vector& box ) const; /** * @brief This finds a box of type and returns the location of its data. * * @param type Defines box type. E.g. 0x6A703268 (jp2h) * @param str Stream to read from. * @param length Number of bytes in the data. * @return The start position of the box (LBox) or zero if not found. */ std::streamoff findBoxData( const ossim_uint32& type, std::ifstream& str, ossim_uint32& length ) const; protected: /** @brief Print tbox type as string if known. */ void printTboxType( ossim_uint32 tbox, std::ostream& out) const; /** Initializes i reference. Does byte swapping as needed. */ void readUInt32(ossim_uint32& i, std::ifstream& str) const; /** Initializes i reference. Does byte swapping as needed. */ void readUInt64(ossim_uint64& i, std::ifstream& str) const; }; #endif /* End of "#ifndef ossimJp2Info_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimJpipMessage.h000066400000000000000000000024061352751253100246320ustar00rootroot00000000000000/********************************************************************************************* * * License: MIT Please see the top level LICENSE.txt * * Author: Garrett Potts * *********************************************************************************************/ #ifndef ossimJpipMessage_HEADER #define ossimJpipMessage_HEADER #include #include #include #include #include class OSSIM_DLL ossimJpipMessage : public ossimReferenced { public: typedef std::vector MessageBodyType; ossimJpipMessage(); void reset(); void setHeaderLength(ossim_uint64 length){m_headerLength = length;} ossimJpipMessageHeader* header(){return m_header.get();} const ossimJpipMessageHeader* header()const{return m_header.get();} MessageBodyType& messageBody(){return m_messageBody;} const MessageBodyType& messageBody()const{return m_messageBody;} void dumpBodyAsHex(std::ostream& out)const; void dumpBodyAsText(std::ostream& out)const; protected: ossimRefPtr m_header; ossim_uint64 m_headerLength; MessageBodyType m_messageBody; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimJpipMessageDecoder.h000066400000000000000000000027411352751253100261220ustar00rootroot00000000000000#ifndef ossimJpipMessageDecoder_HEADER #define ossimJpipMessageDecoder_HEADER 1 #include #include #include #include #include class OSSIM_DLL ossimJpipMessageDecoder : public ossimReferenced { public: ossimJpipMessageDecoder(); ossimByteStreamBuffer& inputStreamBuffer(){return m_streamBuffer;} std::istream& inputStream()const{return m_inputStream;} // virtual ossimJpipMessage* readMessage() throw(ossimException); virtual ossimJpipMessage* readMessage(); protected: /** * Reads a Variable-length Byte-Aligned Segment. * * @return the value which has been read from the VBAS. * * @throws ossimException if an I/O error occurs. */ // ossim_int64 readVBAS() throw(ossimException); ossim_int64 readVBAS(); // ossimJpipMessage* readEORMessage() throw(ossimException); ossimJpipMessage* readEORMessage(); ossim_int32 m_lastClass; /** * Contains the last CSn value. It is a state variables used when dependent * form is used. */ ossim_int32 m_lastCSn; /** * Indicates the length of the JPIP message header. This attribute is * useful for statistics. */ ossim_int64 m_headerLength; mutable ossimByteStreamBuffer m_streamBuffer; mutable std::istream m_inputStream; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimJpipMessageHeader.h000066400000000000000000000165611352751253100257520ustar00rootroot00000000000000/********************************************************************************************* * * ossimJpipMessage was modified from the oiginal source found in a JAVA based framework called * * CADI Software - a JPIP Client/Server framework * *********************************************************************************************/ #ifndef ossimJpipMessageHeader_HEADER #define ossimJpipMessageHeader_HEADER #include #include #include class OSSIM_DLL ossimJpipMessageHeader : public ossimReferenced { public: ossimJpipMessageHeader() :m_isLastByte(true), m_inClassIdentifier(-1), m_classIdentifier(-1), m_CSn(-1), m_msgOffset(-1), m_msgLength(-1), m_aux(-1), m_isEOR(false), m_EORCode(-1), m_EORReasonMessage("") { } void reset() { m_isLastByte = true; m_inClassIdentifier = -1; m_classIdentifier = -1; m_CSn = -1; m_msgOffset = -1; m_msgLength = -1; m_aux = -1; m_isEOR = false; m_EORCode = -1; m_EORReasonMessage = ""; } ossimString toString() const { std::ostringstream out; out << "m_isLastByte: " << ossimString::toString(m_isLastByte) << "\n" << "m_inClassIdentifier: " << m_inClassIdentifier << "\n" << "m_classIdentifier: " << m_classIdentifier << "\n" << "m_CSn: " << m_CSn << "\n" << "m_msgOffset: " << m_msgOffset << "\n" << "m_msgLength: " << m_msgLength << "\n" << "m_aux: " << m_aux << "\n" << "m_isEOR: " << m_isEOR << "\n" << "m_EORCode: " << m_EORCode << "\n" << "m_EORReasonMessage: " << m_EORReasonMessage << "\n"; return ossimString(out.str()); } /** * Bin-ID = [BinIdIndicator, completeDataBin, InClassIdentifier] * * Bin-ID format:
* * * MSB LSB * 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 * ----------------- ----------------- ----------------- * |a|b b|c|d d d d| |a|d d d d d d d| |a|d d d d d d d| ..... * ----------------- ----------------- ----------------- * *

* Bits 6 and 5 of the first, BinIDIndicator, byte indicate whether the * Class and CSn VBASs are present in the message header. Next table defines * the bit values and its meaning *

* * * * * * * * * * * * * * * * * * * * * *
Indicator Meaning
0 Prohibited
1 No Class or CSn VBAS is present in message header
2 Class VBAS is present but CSn is no present in message header
3 Class and CSn VBAS are both present in the message header
*

* Bit 4, completeDataBin, of the first byte of the Bin-ID indicates * whether or not this message contains the last byte in the asociated * data-bin: '0' means it is not the last byte in the data-bin; '1' * inidates tat it is the last byte in the data-bin. *

* The remaining 4 bits of the first byte and the 7 low order bits of * any remaining bytes in the Bin-ID VBAS form an "in-class identifier". *

*/ bool m_isLastByte; // completeDataBin better??? ossim_int64 m_inClassIdentifier; /** * If present, provides a message class identifier. The message class * identifier is a non-negative integer, formed by concatenating the * least significant 7 bits of each byte of the VBAS in big-endian order. * If no present, the message class identifier is unchanged form that * associated with the previous message. If the Class VBAS is not present * and there is no previous message, the message class identifier is 0. *

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Class identifier Message class Data-bin class Stream type
0 Precinct data-bin message Precinct data-bin JPP-stream only
1 Extended precinct data-bin message Precinct data-bin JPP-stream only
2 Tile header data-bin message Tile header data-bin JPP-stream only
4 Tile data-bin message Tile data-bin JPT-stream only
5 Extended precinct data-bin message Tile data-bin JPT-stream only
6 Main header data-bin message Main heaer data-bin JPP- and JPT-stream
8 Metadata-bin message Metadata-bin JPP and JPT-stream
* *

* Allowed values, see {@link CADI.Common.Network.JPIP.ClassIdentifiers}. */ ossim_int32 m_classIdentifier; /** * If present, identifies the index (stating from 0) of the codestream to * which the data-bin belongs. The codestream index is formed by concatenating * the leas significant 7 bits of each byte of the VBAS in big-endian order. * If the CSn VBAS is no present, the codestream index is unchanged from the * previous message. If CSn VBAS is no present and there is no previous * message, the codestream index is 0. */ ossim_int32 m_CSn; /** * Identifies the offset of the data in the message from the start of the * data-bin. It is a non-negative integer value, formed by concatenating the * least significant 7 bits of each byte in the VBAS in big-endian order. */ ossim_int64 m_msgOffset; /** * Identifies the total number of bytes in the body of the message. It is a * non-negative integer value, formed by concatenating the least significant * 7 bits of each byte in the VBAS in big-endian order. */ ossim_int64 m_msgLength; /** * If present, it represents a non-negative integer value, formed by * concatenating the least significant 7 bits of each byte in the VBAS in * big-endian order. *

* Its presence and meaning if present, is determined by the message class * identifier found within the Bin-ID VBAS. */ ossim_int64 m_aux; /** * Indicates if this JPIP Message is an End of Response Message. */ bool m_isEOR; /** * Definition in {@link CADI.Common.Network.JPIP.EORCodes}. *

* Further information, see ISO/IEC 15444-9 sect. D.3 */ int m_EORCode; // <<<<<<<<<< NOTICE: the inClassIdentifier could be used as a EORCode >>>>>>>>>> /** * It is and reason message associated with the EORReasonCode. *

* It is an optional attribute. */ ossimString m_EORReasonMessage; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimLasHdr.h000066400000000000000000000132341352751253100236010ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasHdr.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Container class for LAS LIDAR format public header block. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimLasHdr_HEADER #define ossimLasHdr_HEADER 1 #include #include #include class ossimKeywordlist; class OSSIM_DLL ossimLasHdr { public: /* @brief default constructor */ ossimLasHdr(); /* @brief copy constructor */ ossimLasHdr(const ossimLasHdr& hdr); /* @brief assignment operator= */ const ossimLasHdr& operator=(const ossimLasHdr& hdr); /* destructor */ ~ossimLasHdr(); /** * @brief Checks for LASF in first four bytes. * @return true if first four bytes are LASF. */ bool checkSignature(std::istream& in) const; /** * @brief Method to initialize from input stream. * * Input stream should be at beginning of file. * * @param in Stream to read from. */ void readStream(std::istream& in); /** @brief Writes header to stream. */ void writeStream(std::ostream& out); /** * @brief print method. * @return std::ostream& */ std::ostream& print(std::ostream& out) const; /** @brief Convenience operator<< method. */ friend OSSIM_DLL std::ostream& operator<<(std::ostream& out, const ossimLasHdr& hdr); void getKeywordlist(ossimKeywordlist& kwl) const; /** @return True if bit 0 of m_globalEncoding is set, false if not. */ bool getGpsTimeTypeBit() const; /** @return True if bit 1 of m_globalEncoding is set, false if not. */ bool getWaveforDataPacketsInternalBit() const; /** @return True if bit 2 of m_globalEncoding is set, false if not. */ bool getWaveforDataPacketsExternalBit() const; /** @return True if bit 3 of m_globalEncoding is set, false if not. */ bool getReturnsSyntheticallyGeneratedBit() const; /** @return True if bit 4 of m_globalEncoding is set, false if not. */ bool getWktBit() const; /** * @return The project ID GUID data, e.g.: 55b44da7-7c23-4f86-a54ec39e8f1d1ea1 */ std::string getProjectIdGuid() const; /** @return The major and minor version, e.g.: 1.2 */ std::string getVersion() const; /** @return The system identifier string. */ std::string getSystemIndentifier() const; /** @return The generating software string. */ std::string getGeneratingSoftware() const; /** @return Size of this header in bytes. */ ossim_uint16 getHeaderSize() const; /** @return Offset to point data. */ ossim_uint32 getOffsetToPointData() const; /** @return The number fo variable length records. */ ossim_uint32 getNumberOfVlrs() const; /** @return Point data format ID */ ossim_uint8 getPointDataFormatId() const; /** @return The number of total points. */ ossim_uint64 getNumberOfPoints() const; /** * @brief Gets number of points for entry where entry is synonymous returns. * @return The number of points for entries 0 through 4. */ ossim_uint64 getNumberOfPoints(ossim_uint32 entry) const; const ossim_float64& getScaleFactorX() const; const ossim_float64& getScaleFactorY() const; const ossim_float64& getScaleFactorZ() const; const ossim_float64& getOffsetX() const; const ossim_float64& getOffsetY() const; const ossim_float64& getOffsetZ() const; const ossim_float64& getMinX() const; const ossim_float64& getMinY() const; const ossim_float64& getMinZ() const; const ossim_float64& getMaxX() const; const ossim_float64& getMaxY() const; const ossim_float64& getMaxZ() const; private: /** @brief Performs a swap if system byte order is not little endian. */ void swap(); /** * @brief Test version. * @param major * @param minor * @return true if m_versionMajor and m_versionMinor are greater than major and minor * args. */ bool versionGreaterThan( ossim_uint8 major, ossim_uint8 minor ) const; char m_fileSignature[5]; ossim_uint16 m_fileSourceId; ossim_uint16 m_globalEncoding; ossim_uint32 m_projectIdGuidData1; ossim_uint16 m_projectIdGuidData2; ossim_uint16 m_projectIdGuidData3; ossim_uint8 m_projectIdGuidData4[8]; ossim_uint8 m_versionMajor; ossim_uint8 m_versionMinor; char m_systemIndentifier[32]; char m_generatingSoftware[32]; ossim_uint16 m_fileCreationDay; ossim_uint16 m_fileCreateionYear; ossim_uint16 m_headerSize; ossim_uint32 m_offsetToPointData; ossim_uint32 m_numberOfVariableLengthRecords; ossim_uint8 m_pointDataFormatId; ossim_uint16 m_pointDataRecordLength; ossim_uint32 m_legacyNumberOfPointRecords; // deprecated 1_4 ossim_uint32 m_legacyNumberOfPointsByReturn[5]; // deprecated 1_4 ossim_float64 m_xScaleFactor; ossim_float64 m_yScaleFactor; ossim_float64 m_zScaleFactor; ossim_float64 m_xOffset; ossim_float64 m_yOffset; ossim_float64 m_zOffset; ossim_float64 m_maxX; ossim_float64 m_minX; ossim_float64 m_maxY; ossim_float64 m_minY; ossim_float64 m_maxZ; ossim_float64 m_minZ; ossim_uint64 m_startOfWaveformDataPacket; // Added 1_3 ossim_uint64 m_startOfExtendedVariableLengthRecords; // Added 1_4 ossim_uint32 m_numberOfExtendedVariableLengthRecords; // Added 1_4 ossim_uint64 m_numberOfPointRecords; // Added 1_4 ossim_uint64 m_numberOfPointsByReturn[15]; // Added 1_4 }; #endif /* End of "#ifndef ossimLasHdr_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimLasInfo.h000066400000000000000000000023041352751253100237530ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLibLasInfo.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: LAS LIDAR info object. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimLasInfo_HEADER #define ossimLasInfo_HEADER 1 #include #include #include #include /** @brief LAS LIDAR info object. */ class OSSIM_DLL ossimLasInfo : public ossimInfoBase { public: /** default constructor */ ossimLasInfo(); /** virtual destructor */ virtual ~ossimLasInfo(); /** * @brief open method. * * @param file File name to open. * * @return true on success false on error. */ virtual bool open(const ossimFilename& file); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; private: ossimFilename m_file; }; #endif /* End of "#ifndef ossimLasInfo_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimLasPointRecord0.h000066400000000000000000000053241352751253100253750ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord0.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimLasPointRecord0_HEADER #define ossimLasPointRecord0_HEADER 1 #include /** * @class ossimLasPointRecord0 * * Container class for LAS point record type 1. */ class ossimLasPointRecord0 : public ossimLasPointRecordInterface { public: /** @brief default constructor */ ossimLasPointRecord0(); /* @brief copy constructor */ ossimLasPointRecord0(const ossimLasPointRecord0& obj); /* @brief assignment operator= */ const ossimLasPointRecord0& operator=(const ossimLasPointRecord0& copy_this); /** @brief destructor */ virtual ~ossimLasPointRecord0(); /** @brief Initialize record from stream. */ virtual void readStream(std::istream& in); /** @brief Writes record to stream. */ virtual void writeStream(std::ostream& out); /** @return x */ virtual ossim_int32 getX() const; /** @return y */ virtual ossim_int32 getY() const; /** @return z */ virtual ossim_int32 getZ() const; /** @return red */ virtual ossim_uint16 getRed() const; /** @return green */ virtual ossim_uint16 getGreen() const; /** @return blue */ virtual ossim_uint16 getBlue() const; /** @return intensity */ virtual ossim_uint16 getIntensity() const; /** @return return number */ virtual ossim_uint8 getReturnNumber() const; virtual ossim_uint8 getNumberOfReturns() const; virtual ossim_uint8 getEdgeFlag() const; virtual std::ostream& print(std::ostream& out) const; private: /** @brief Performs a swap if system byte order is not little endian. */ void swap(); //--- // Private structure so we can do a single read/write in the readStream // and writeStream methods. This sped the code up 5X when doing an ossim-icp // from a LAS file to a tif. //--- struct ossimLasPointRecord0Data { ossimLasPointRecord0Data(); ossimLasPointRecord0Data(const ossimLasPointRecord0Data& obj); const ossimLasPointRecord0Data& operator=(const ossimLasPointRecord0Data& obj); ossim_int32 m_x; ossim_int32 m_y; ossim_int32 m_z; ossim_uint16 m_intensity; ossim_uint8 m_returnByte; ossim_uint8 m_classification; ossim_int8 m_scanAngleRank; ossim_uint8 m_userData; ossim_uint16 m_pointSourceID; }; ossimLasPointRecord0Data m_record; }; #endif /* #ifndef ossimLasPointRecord0_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimLasPointRecord1.h000066400000000000000000000053631352751253100254010ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord1.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimLasPointRecord1_HEADER #define ossimLasPointRecord1_HEADER 1 #include /** * @class ossimLasPointRecord1 * * Container class for LAS point record type 1. */ class ossimLasPointRecord1 : public ossimLasPointRecordInterface { public: /** @brief default constructor */ ossimLasPointRecord1(); /* @brief copy constructor */ ossimLasPointRecord1(const ossimLasPointRecord1& obj); /* @brief assignment operator= */ const ossimLasPointRecord1& operator=(const ossimLasPointRecord1& copy_this); /** @brief destructor */ virtual ~ossimLasPointRecord1(); /** @brief Initialize record from stream. */ virtual void readStream(std::istream& in); /** @brief Writes record to stream. */ virtual void writeStream(std::ostream& out); /** @return x */ virtual ossim_int32 getX() const; /** @return y */ virtual ossim_int32 getY() const; /** @return z */ virtual ossim_int32 getZ() const; /** @return red */ virtual ossim_uint16 getRed() const; /** @return green */ virtual ossim_uint16 getGreen() const; /** @return blue */ virtual ossim_uint16 getBlue() const; /** @return intensity */ virtual ossim_uint16 getIntensity() const; /** @return return number */ virtual ossim_uint8 getReturnNumber() const; virtual ossim_uint8 getNumberOfReturns() const; virtual ossim_uint8 getEdgeFlag() const; virtual std::ostream& print(std::ostream& out) const; private: /** @brief Performs a swap if system byte order is not little endian. */ void swap(); //--- // Private structure so we can do a single read/write in the readStream // and writeStream methods. This sped the code up 5X when doing an ossim-icp // from a LAS file to a tif. //--- struct ossimLasPointRecord1Data { ossimLasPointRecord1Data(); ossimLasPointRecord1Data(const ossimLasPointRecord1Data& obj); const ossimLasPointRecord1Data& operator=(const ossimLasPointRecord1Data& obj); ossim_int32 m_x; ossim_int32 m_y; ossim_int32 m_z; ossim_uint16 m_intensity; ossim_uint8 m_returnByte; ossim_uint8 m_classification; ossim_int8 m_scanAngleRank; ossim_uint8 m_userData; ossim_uint16 m_pointSourceID; ossim_float64 m_gpsTime; }; ossimLasPointRecord1Data m_record; }; #endif /* #ifndef ossimLasPointRecord1_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimLasPointRecord2.h000066400000000000000000000064021352751253100253750ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord2.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimLasPointRecord2_HEADER #define ossimLasPointRecord2_HEADER 1 #include /** * @class ossimLasPointRecord2 * * Container class for LAS point record type 2. */ class ossimLasPointRecord2 : public ossimLasPointRecordInterface { public: /** @brief default constructor */ ossimLasPointRecord2(); /* @brief copy constructor */ ossimLasPointRecord2(const ossimLasPointRecord2& obj); /* @brief assignment operator= */ const ossimLasPointRecord2& operator=(const ossimLasPointRecord2& copy_this); /** @brief destructor */ virtual ~ossimLasPointRecord2(); /** @brief Initialize record from stream. */ virtual void readStream(std::istream& in); /** @brief Writes record to stream. */ virtual void writeStream(std::ostream& out); /** @return x */ virtual ossim_int32 getX() const; /** @return y */ virtual ossim_int32 getY() const; /** @return z */ virtual ossim_int32 getZ() const; /** @return red */ virtual ossim_uint16 getRed() const; /** @return green */ virtual ossim_uint16 getGreen() const; /** @return blue */ virtual ossim_uint16 getBlue() const; /** @return intensity */ virtual ossim_uint16 getIntensity() const; /** @return return number */ virtual ossim_uint8 getReturnNumber() const; virtual ossim_uint8 getNumberOfReturns() const; virtual ossim_uint8 getEdgeFlag() const; virtual std::ostream& print(std::ostream& out) const; private: /** @brief Performs a swap if system byte order is not little endian. */ void swap(); union BitFlags { BitFlags(const BitFlags& obj):m_bits(obj.m_bits){} BitFlags(ossim_uint8 value):m_bits((ossim_uint8)value){} const BitFlags& operator =(const BitFlags& obj){m_bits = obj.m_bits;return *this;} struct { ossim_uint8 m_returnNumber : 3; ossim_uint8 m_numberOfReturns : 3; ossim_uint8 m_scanDirection : 1; ossim_uint8 m_edgeOfFlightLine : 1; }; ossim_uint8 m_bits; }; //--- // Private structure so we can do a single read/write in the readStream // and writeStream methods. This sped the code up 5X when doing an ossim-icp // from a LAS file to a tif. //--- struct ossimLasPointRecord2Data { ossimLasPointRecord2Data(); ossimLasPointRecord2Data(const ossimLasPointRecord2Data& obj); const ossimLasPointRecord2Data& operator=(const ossimLasPointRecord2Data& obj); ossim_int32 m_x; ossim_int32 m_y; ossim_int32 m_z; ossim_uint16 m_intensity; BitFlags m_bitFlags; ossim_uint8 m_classification; ossim_int8 m_scanAngleRank; ossim_uint8 m_userData; ossim_uint16 m_pointSourceId; ossim_uint16 m_red; ossim_uint16 m_green; ossim_uint16 m_blue; }; ossimLasPointRecord2Data m_record; }; #endif /* #ifndef ossimLasPointRecord2_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimLasPointRecord3.h000066400000000000000000000064411352751253100254010ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord3.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimLasPointRecord3_HEADER #define ossimLasPointRecord3_HEADER 1 #include /** * @class ossimLasPointRecord3 * * Container class for LAS point record type 3. */ class ossimLasPointRecord3 : public ossimLasPointRecordInterface { public: /** @brief default constructor */ ossimLasPointRecord3(); /* @brief copy constructor */ ossimLasPointRecord3(const ossimLasPointRecord3& obj); /* @brief assignment operator= */ const ossimLasPointRecord3& operator=(const ossimLasPointRecord3& copy_this); /** @brief destructor */ virtual ~ossimLasPointRecord3(); /** @brief Initialize record from stream. */ virtual void readStream(std::istream& in); /** @brief Writes record to stream. */ virtual void writeStream(std::ostream& out); /** @return x */ virtual ossim_int32 getX() const; /** @return y */ virtual ossim_int32 getY() const; /** @return z */ virtual ossim_int32 getZ() const; /** @return red */ virtual ossim_uint16 getRed() const; /** @return green */ virtual ossim_uint16 getGreen() const; /** @return blue */ virtual ossim_uint16 getBlue() const; /** @return intensity */ virtual ossim_uint16 getIntensity() const; /** @return return number */ virtual ossim_uint8 getReturnNumber() const; virtual ossim_uint8 getNumberOfReturns() const; virtual ossim_uint8 getEdgeFlag() const; virtual std::ostream& print(std::ostream& out) const; private: /** @brief Performs a swap if system byte order is not little endian. */ void swap(); union BitFlags { BitFlags(const BitFlags& obj):m_bits(obj.m_bits){} BitFlags(ossim_uint8 value):m_bits((ossim_uint8)value){} const BitFlags& operator =(const BitFlags& obj){m_bits = obj.m_bits;return *this;} struct { ossim_uint8 m_returnNumber : 3; ossim_uint8 m_numberOfReturns : 3; ossim_uint8 m_scanDirection : 1; ossim_uint8 m_edgeOfFlightLine : 1; }; ossim_uint8 m_bits; }; //--- // Private structure so we can do a single read/write in the readStream // and writeStream methods. This sped the code up 5X when doing an ossim-icp // from a LAS file to a tif. //--- struct ossimLasPointRecord3Data { ossimLasPointRecord3Data(); ossimLasPointRecord3Data(const ossimLasPointRecord3Data& obj); const ossimLasPointRecord3Data& operator=(const ossimLasPointRecord3Data& obj); ossim_int32 m_x; ossim_int32 m_y; ossim_int32 m_z; ossim_uint16 m_intensity; BitFlags m_bitFlags; ossim_uint8 m_classification; ossim_int8 m_scanAngleRank; ossim_uint8 m_userData; ossim_uint16 m_pointSourceId; ossim_float64 m_gpsTime; ossim_uint16 m_red; ossim_uint16 m_green; ossim_uint16 m_blue; }; ossimLasPointRecord3Data m_record; }; #endif /* #ifndef ossimLasPointRecord3_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimLasPointRecord4.h000066400000000000000000000067441352751253100254100ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord4.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimLasPointRecord4_HEADER #define ossimLasPointRecord4_HEADER 1 #include /** * @class ossimLasPointRecord4 * * Container class for LAS point record type 4. */ class ossimLasPointRecord4 : public ossimLasPointRecordInterface { public: /** @brief default constructor */ ossimLasPointRecord4(); /* @brief copy constructor */ ossimLasPointRecord4(const ossimLasPointRecord4& obj); /* @brief assignment operator= */ const ossimLasPointRecord4& operator=(const ossimLasPointRecord4& copy_this); /** @brief destructor */ virtual ~ossimLasPointRecord4(); /** @brief Initialize record from stream. */ virtual void readStream(std::istream& in); /** @brief Writes record to stream. */ virtual void writeStream(std::ostream& out); /** @return x */ virtual ossim_int32 getX() const; /** @return y */ virtual ossim_int32 getY() const; /** @return z */ virtual ossim_int32 getZ() const; /** @return red */ virtual ossim_uint16 getRed() const; /** @return green */ virtual ossim_uint16 getGreen() const; /** @return blue */ virtual ossim_uint16 getBlue() const; /** @return intensity */ virtual ossim_uint16 getIntensity() const; /** @return return number */ virtual ossim_uint8 getReturnNumber() const; virtual ossim_uint8 getNumberOfReturns() const; virtual ossim_uint8 getEdgeFlag() const; virtual std::ostream& print(std::ostream& out) const; private: /** @brief Performs a swap if system byte order is not little endian. */ void swap(); union BitFlags { BitFlags(const BitFlags& obj):m_bits(obj.m_bits){} BitFlags(ossim_uint8 value):m_bits((ossim_uint8)value){} const BitFlags& operator =(const BitFlags& obj){m_bits = obj.m_bits;return *this;} struct { ossim_uint8 m_returnNumber : 3; ossim_uint8 m_numberOfReturns : 3; ossim_uint8 m_scanDirection : 1; ossim_uint8 m_edgeOfFlightLine : 1; }; ossim_uint8 m_bits; }; //--- // Private structure so we can do a single read/write in the readStream // and writeStream methods. This sped the code up 5X when doing an ossim-icp // from a LAS file to a tif. //--- struct ossimLasPointRecord4Data { ossimLasPointRecord4Data(); ossimLasPointRecord4Data(const ossimLasPointRecord4Data& obj); const ossimLasPointRecord4Data& operator=(const ossimLasPointRecord4Data& obj); ossim_int32 m_x; ossim_int32 m_y; ossim_int32 m_z; ossim_uint16 m_intensity; BitFlags m_bitFlags; ossim_uint8 m_classification; ossim_int8 m_scanAngleRank; ossim_uint8 m_userData; ossim_uint16 m_pointSourceId; ossim_float64 m_gpsTime; ossim_uint8 m_wavePacketDescriptorIndex; ossim_uint64 m_byteOffsetToWaveformData; ossim_uint32 m_waveformPacketSizeInBytes; ossim_float64 m_returnPointWaveformLocation; ossim_uint16 m_red; ossim_uint16 m_green; ossim_uint16 m_blue; }; ossimLasPointRecord4Data m_record; }; #endif /* #ifndef ossimLasPointRecord4_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimLasPointRecordInterface.h000066400000000000000000000026431352751253100271370ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecordInterface.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimLasPointRecordInterface_HEADER #define ossimLasPointRecordInterface_HEADER 1 #include #include /** * @class ossimLasPointRecordInterface * * OSSIM Interface for LAS point record types. */ class ossimLasPointRecordInterface { public: /** @brief Virtual destructor defined to squash compiler errors. */ virtual ~ossimLasPointRecordInterface(){} virtual void readStream(std::istream& in) = 0; virtual void writeStream(std::ostream& out) = 0; virtual ossim_uint16 getRed() const = 0; virtual ossim_uint16 getGreen() const = 0; virtual ossim_uint16 getBlue() const = 0; virtual ossim_uint16 getIntensity() const = 0; virtual ossim_int32 getX() const = 0; virtual ossim_int32 getY() const = 0; virtual ossim_int32 getZ() const = 0; virtual ossim_uint8 getReturnNumber() const = 0; virtual ossim_uint8 getNumberOfReturns() const = 0; virtual ossim_uint8 getEdgeFlag() const = 0; virtual std::ostream& print(std::ostream& out) const = 0; }; #endif /* #ifndef ossimLasPointRecordInterface_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfAcftbTag.h000066400000000000000000000164271352751253100247270ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: ACFTB - Aircraft Infomation Extension Format tag class // declaration. // // See document STDI-0002 (version 3), Appendix E, Table E-6 for more info. // //---------------------------------------------------------------------------- // $Id #ifndef ossimNitfAcftbTag_HEADER #define ossimNitfAcftbTag_HEADER 1 #include class OSSIM_DLL ossimNitfAcftbTag : public ossimNitfRegisteredTag { public: enum { CEL_SIZE = 207, AC_MSN_ID_SIZE = 20, AC_TAIL_NO_SIZE = 10, AC_TO_SIZE = 12, SENSOR_ID_TYPE_SIZE = 4, SENSOR_ID_SIZE = 6, SCENE_SOURCE_SIZE = 1, SCNUM_SIZE = 6, PDATE_SIZE = 8, IMHOSTNO_SIZE = 6, IMREQID_SIZE = 5, MPLAN_SIZE = 3, ENTLOC_SIZE = 25, LOC_ACCY_SIZE = 6, ENTELV_SIZE = 6, ELV_UNIT_SIZE = 1, EXITLOC_SIZE = 25, EXITELV_SIZE = 6, TMAP_SIZE = 7, ROW_SPACING_SIZE = 7, ROW_SPACING_UNITS_SIZE = 1, COL_SPACING_SIZE = 7, COL_SPACING_UINTS_SIZE = 1, FOCAL_LENGTH_SIZE = 6, SENSERIAL_SIZE = 6, ABSWVER_SIZE = 7, CAL_DATE_SIZE = 8, PATCH_TOT_SIZE = 4, MTI_TOT_SIZE = 3 }; /** @brief default constructor */ ossimNitfAcftbTag(); /** @brief destructor */ virtual ~ossimNitfAcftbTag(); /** @brief Method to parse data from stream. */ virtual void parseStream(ossim::istream& in); /** @brief Method to write data to stream. */ virtual void writeStream(ossim::ostream& out); /** @brief Method to clear all fields including null terminating. */ virtual void clearFields(); ossimString getFocalLength()const; ossimString getColumnSpacing()const; ossimString getColumnSpacingUnits()const; ossimString getRowSpacing()const; ossimString getRowSpacingUnits()const; /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; protected: /** Type R = Required Type = BCS spaces allowed for entire field */ /** * FIELD: AC_MSN_ID * * TYPE: R * * 20 byte field * * Aircraft Mission Identification */ char theAcMsnId[AC_MSN_ID_SIZE+1]; /** * FIELD: AC_TAIL_NO * * TYPE: * * 10 byte field * * Aircraft Tail Number */ char theAcTailNo[AC_TAIL_NO_SIZE+1]; /** * FIELD: AC_TO * * TYPE: * * 12 byte field * * Aircraft Take-off, CCYYMMDDhhmm */ char theAcTo[AC_TO_SIZE+1]; /** * FIELD: SENSOR_ID_TYPE * * TYPE: R * * 4 byte field * * Sensor ID Type */ char theSensorIdType[SENSOR_ID_TYPE_SIZE+1]; /** * FIELD: SENSOR_ID * * TYPE: R * * 6 byte field * * Sensor ID */ char theSensorId[SENSOR_ID_SIZE+1]; /** * FIELD: SCENE_SOURCE * * TYPE: * * 1 byte field * * Scene Source, 0 to 9 */ char theSceneSource[SCENE_SOURCE_SIZE+1]; /** * FIELD: SCNUM * * TYPE: R * * 6 byte field * * Scene Number, 000000 to 999999 */ char theScNum[SCNUM_SIZE+1]; /** * FIELD: PDATE * * TYPE: R * * 8 byte field * * Processing Date, CCYYMMDD */ char thePDate[PDATE_SIZE+1]; /** * FIELD: IMHOSTNO * * TYPE: R * * 6 byte field * * Immediate Scene Host */ char theImHostNo[IMHOSTNO_SIZE+1]; /** * FIELD: IMREQID * * TYPE: R * * 5 byte field * * Immediate Scene Request ID, 00000, 00001 to 99999 */ char theImReqID[IMREQID_SIZE+1]; /** * FIELD: MPLAN * * TYPE: R * * 3 byte field * * Mission Plan Mode, 001 to 999 */ char theMPlan[MPLAN_SIZE+1]; /** * FIELD: ENTLOC * * TYPE: * * 25 byte field * * Entry Location */ char theEntLoc[ENTLOC_SIZE+1]; /** * FIELD: LOC_ACCY * * TYPE: R * * 6 byte field * * Location Accuracy, feet, 000.01 to 999.99, 000000, 000.00 */ char theLocAccy[LOC_ACCY_SIZE+1]; /** * FIELD: ENTELV * * TYPE: * * 6 byte field * * Entry Elevation, feet or meters, -01000 to +30000 */ char theEntelv[ENTELV_SIZE+1]; /** * FIELD: ELV_UNIT * * TYPE: * * 1 byte field * * Unit of Elevation, f or m */ char theElvUnit[ELV_UNIT_SIZE+1]; /** * FIELD: EXITLOC * * TYPE: * * 25 byte field * * Exit Location */ char theExitLoc[EXITLOC_SIZE+1]; /** * FIELD: EXITELV * * TYPE: * * 6 byte field * * Exit Elevation */ char theExitElev[EXITELV_SIZE+1]; /** * FIELD: TMAP * * TYPE: * * 7 byte field * * True Map Angle, degrees, 000.000 to 180.000 */ char theTMap[TMAP_SIZE+1]; /** * FIELD: ROW_SPACING * * TYPE: R * * 7 byte field * * Row Spacing, feet, meters, rads. */ char theRowSpacing[ROW_SPACING_SIZE+1]; /** * FIELD: ROW_SPACING_UNITS * * TYPE: R * * 1 byte field * * Unit of Row Spacing, f, m, r or u */ char theRowSpacingUnits[ROW_SPACING_UNITS_SIZE+1]; /** * FIELD: COL_SPACING * * TYPE: R * * 7 byte field * * Column Spacing */ char theColSpacing[COL_SPACING_SIZE+1]; /** * FIELD: COL_SPACING_UINTS * * TYPE: R * * 1 byte field * * Unit of Column Spacing */ char theColSpacingUnits[COL_SPACING_UINTS_SIZE+1]; /** * FIELD: FOCAL_LENGTH * * TYPE: R * * 6 byte field * * Sensor Focal Length, cm, 000.01 to 899.99, 999.99 */ char theFocalLength[FOCAL_LENGTH_SIZE+1]; /** * FIELD: SENSERIAL * * TYPE: * * 6 byte field * * Sensor vendor's serial number, 000001 to 999999 */ char theSenserial[SENSERIAL_SIZE+1]; /** * FIELD: ABSWVER * * TYPE: * * 7byte field * * Airborne Software Version */ char theAbSwVer[ABSWVER_SIZE+1]; /** * FIELD: CAL_DATE * * TYPE: * * 8 byte field * * Calibration Date, CCYYMMDD */ char theCalDate[CAL_DATE_SIZE+1]; /** * FIELD: PATCH_TOT * * TYPE: R * * 4 byte field * * Patch Total */ char thePatchTot[PATCH_TOT_SIZE+1]; /** * FIELD: MTI_TOT * * TYPE: R * * 3 byte field * * MTI Total, SAR: 000 to 999, EO-IR: 000 */ char theMtiTot[MTI_TOT_SIZE+1]; TYPE_DATA }; #endif /* matches #ifndef ossimNitfAcftbTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfAimidbTag.h000066400000000000000000000123721352751253100250700ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: AIMIDB - Additional Image ID Extension Format // tag class declaration. // // See document STDI-0002 (version 3), Appendix E, Table E-3 for more info. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimNitfAimidbTag_HEADER #define ossimNitfAimidbTag_HEADER 1 #include class OSSIM_DLL ossimNitfAimidbTag : public ossimNitfRegisteredTag { public: enum { CEL_SIZE = 89, ACQUISITION_DATE_SIZE = 14, MISSION_NO_SIZE = 4, MISSION_IDENTIFICATION_SIZE = 10, FLIGHT_NO_SIZE = 2, OP_NUM_SIZE = 3, CURRENT_SEGMENT_SIZE = 2, REPRO_NUM_SIZE = 2, REPLAY_SIZE = 3, RESERVED_1_SIZE = 1, START_TILE_COLUMN_SIZE = 3, START_TILE_ROW_SIZE = 5, END_SEGMENT_SIZE = 2, END_TILE_COLUMN_SIZE = 3, END_TILE_ROW_SIZE = 5, COUNTRY_SIZE = 2, RESERVED_2_SIZE = 4, LOCATION_SIZE = 11, RESERVED_3_SIZE = 13 }; /** @brief default constructor */ ossimNitfAimidbTag(); /** @brief destructor */ virtual ~ossimNitfAimidbTag(); /** @brief Method to parse data from stream. */ virtual void parseStream(ossim::istream& in); /** @brief Method to write data to stream. */ virtual void writeStream(ossim::ostream& out); /** @brief Method to clear all fields including null terminating. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; protected: /** Type R = Required Type = BCS spaces allowed for entire field */ /** * FIELD: ACQUISITION_DATE * * TYPE: R * * 14 byte field * * CCYYMMDDhhmmss */ char theAcquisitionDate[ACQUISITION_DATE_SIZE+1]; /** * FIELD: MISSION_NO * * TYPE: R * * 4 byte field * * Mission Number */ char theMissionNumber[MISSION_NO_SIZE+1]; /** * FIELD: MISSION_IDENTIFICATION * * TYPE: R * * 10 byte field * * Name of the Mission. */ char theMissionIdentification[MISSION_IDENTIFICATION_SIZE+1]; /** * FIELD: FLIGHT_NO * * TYPE: R * * 2 byte field * * Flight Number */ char theFlightNo[FLIGHT_NO_SIZE+1]; /** * FIELD: OP_NUM * * TYPE: R * * 3 byte field * * Image Operation Number 000 to 999 */ char theOpNum[OP_NUM_SIZE+1]; /** * FIELD: CURRENT_SEGMENT * * TYPE: R * * 2 byte field * * Current Segment ID, AA to ZZ */ char theCurrentSegment[CURRENT_SEGMENT_SIZE+1]; /** * FIELD: REPRO_NUM * * TYPE: R * * 2 byte field * * Reprocess Number, 00 to 99 */ char theReproNum[REPRO_NUM_SIZE+1]; /** * FIELD: REPLAY * * TYPE: * * 3 byte field * * Replay */ char theReplay[REPLAY_SIZE+1]; /** * FIELD: RESERVED_1 * * TYPE: R * * 1 byte field * * 1 space */ char theReserved1[RESERVED_1_SIZE+1]; /** * FIELD: START_TILE_COLUMN * * TYPE: R * * 3 byte field * * Starting Tile Column Number, 001 to 099 */ char theStartTileColumn[START_TILE_COLUMN_SIZE+1]; /** * FIELD: START_TILE_ROW * * TYPE: R * * 5 byte field * * Starting Tile Row Number, 00001 to 99999 */ char theStartTileRow[START_TILE_ROW_SIZE+1]; /** * FIELD: END_SEGMENT * * TYPE: R * * 2 byte field * * Ending Segment, 00, AA to ZZ */ char theEndSegment[END_SEGMENT_SIZE+1]; /** * FIELD: END_TILE_COLUMN * * TYPE: R * * 3 byte field * * Ending Tile Column Number, 001 to 099 */ char theTileColumn[END_TILE_COLUMN_SIZE+1]; /** * FIELD: END_TILE_ROW * * TYPE: R * * 5 byte field * * Ending Tile Row Number, 00001 to 99999 */ char theTileRow[END_TILE_ROW_SIZE+1]; /** * FIELD: COUNTRY * * TYPE: * * 2 byte field * * Country Code, AA to ZZ */ char theCountry[COUNTRY_SIZE+1]; /** * FIELD: RESERVED_2 * * TYPE: R * * 4 byte field * * 4 spaces */ char theReserved2[RESERVED_2_SIZE+1]; /** * FIELD: LOCATION * * TYPE: * * 11 byte field * * Location, ddmmXdddmmY, spaces */ char theLocation[LOCATION_SIZE+1]; /** * FIELD: RESERVED_3 * * TYPE: R * * 13 byte field * * 13 spaces */ char theReserved3[RESERVED_3_SIZE+1]; TYPE_DATA }; #endif /* matches #ifndef ossimNitfAimidbTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfBlockaTag.h000066400000000000000000000170541352751253100251000ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: BLOCKA tag class declaration. // // See document STDI-0002 Table 8-9 for more info. // // http://164.214.2.51/ntb/baseline/docs/stdi0002/final.pdf // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimNitfBlockaTag_HEADER #define ossimNitfBlockaTag_HEADER 1 #include class ossimDpt; class OSSIM_DLL ossimNitfBlockaTag : public ossimNitfRegisteredTag { public: enum { BLOCK_INSTANCE_SIZE = 2, N_GRAY_SIZE = 5, L_LINES_SIZE = 5, LAYOVER_ANGLE_SIZE = 3, SHADOW_ANGLE_SIZE = 3, FIELD_6_SIZE = 16, // reserved FRLC_LOC_SIZE = 21, LRLC_LOC_SIZE = 21, LRFC_LOC_SIZE = 21, FRFC_LOC_SIZE = 21, FIELD_11_SIZE = 5, // reserved // ----- // 123 }; /** default constructor */ ossimNitfBlockaTag(); /** * Parse method. * * @param in Stream to parse. */ virtual void parseStream(ossim::istream& in); /** * Write method. * * @param out Stream to write to. */ virtual void writeStream(ossim::ostream& out); /** * Clears all string fields within the record to some default nothingness. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; /** @param block number to set block instance to. Valid range 01 to 99. */ void setBlockInstance(ossim_uint32 block); /** @return theBlockInstance as a string. */ ossimString getBlockInstance() const; /** * @param grayCount Count of gray fill. * * Valid range: 0 to 99999 */ void setNGray(ossim_uint32 grayCount); /** @return theNGray as a string. */ ossimString getNGray() const; /** * @param lines Number of rows. * * Valid range: 0 to 99999 */ void setLLines(ossim_uint32 lines); /** @return theLLines as a string. */ ossimString getLLines() const; /** * @param angle Value to set theLayoverAngle to. * * Valid range: 000 to 359 or spaces */ void setLayoverAngle(ossim_uint32 angle); /** @return theLayoverAngle as a string. */ ossimString getLayoverAngle() const; /** * @param angle Value to set theLayoverAngle to. * * Valid range: 000 to 359 or spaces */ void setShadowAngle(ossim_uint32 angle); /** @return theLayoverAngle as a string. */ ossimString getShadowAngle() const; /** * Convert latitude and logitude to theFrlcLoc string. * * @param pt Ground point of first row, last column. * * @param longitude Longitude portion in decimal degrees. */ void setFrlcLoc(const ossimDpt& pt); /** @return theFrlcLoc as a string. */ ossimString getFrlcLoc() const; /** @param pt Ground point to initialize with location. */ void getFrlcLoc(ossimDpt& pt) const; /** * Convert latitude and logitude to theLrlcLoc string. * * @param pt Ground point of last row, last column. * * @param longitude Longitude portion in decimal degrees. */ void setLrlcLoc(const ossimDpt& pt); /** @return theLrlcLoc as a string. */ ossimString getLrlcLoc() const; /** @param pt Ground point to initialize with location. */ void getLrlcLoc(ossimDpt& pt) const; /** * Convert latitude and logitude to theLrfcLoc string. * * @param pt Ground point of last row, first column. * * @param longitude Longitude portion in decimal degrees. */ void setLrfcLoc(const ossimDpt& pt); /** @return theLrfcLoc as a string. */ ossimString getLrfcLoc() const; /** @param pt Ground point to initialize with location. */ void getLrfcLoc(ossimDpt& pt) const; /** * Convert latitude and logitude to theFrfcLoc string. * * @param pt Ground point of first row, first column. * * @param longitude Longitude portion in decimal degrees. */ void setFrfcLoc(const ossimDpt& pt); /** @return theFrfcLoc as a string. */ ossimString getFrfcLoc() const; /** @param pt Ground point to initialize with location. */ void getFrfcLoc(ossimDpt& pt) const; protected: /** * Parses location string and initializes pt with result. * * @param locationString String to parse. * * @param pt Point to initialize. */ void converLocStringToPt(const ossimString& locationString, ossimDpt& pt) const; /** * FIELD: BLOCK_INSTANCE * * required 2 byte field * * 01 to 99 * * Block number of the image. */ char theBlockInstance[BLOCK_INSTANCE_SIZE+1]; /** * FIELD: N_GRAY * * required 5 byte field * * 00000 to 99999 * * SAR The number of gray fill pixels. * * EO-IR: 00000 */ char theNGray[N_GRAY_SIZE+1]; /** * FIELD: L_LINES * * required 5 byte field * * 00000 to 99999 * * Row count. */ char theLLines[L_LINES_SIZE+1]; /** * FIELD: LAYOVER_ANGLE * * required 3 byte field * * 000 to 359 or spaces * * SAR: Angle between the first row of pixels and the layover direction in * the image, measured in a clockwise direction. * * EO-IR: spaces */ char theLayoverAngle[LAYOVER_ANGLE_SIZE+1]; /** * FIELD: SHADOW_ANGLE * * required 3 byte field * * 000 to 359 or spaces * * SAR: Angle between the first row of pixels and the radar shadow in * the image, measured in a clockwase direction. * * EO-IR: spaces */ char theShadowAngle[SHADOW_ANGLE_SIZE+1]; /** * FIELD: FIELD_6 * * Reserved field of 16 spaces. */ char theField6[FIELD_6_SIZE+1]; /** * FIELD: FRLC_LOC * * required 21 byte field * * XDDMMSS.SSYDDDMMSS.SS * OR * +-dd.dddddd+-ddd.dddddd * OR * 21 spaces * * Location of the first row, last column of the image block. */ char theFrlcLoc[FRLC_LOC_SIZE+1]; /** * FIELD: LRLC_LOC * * required 21 byte field * * XDDMMSS.SSYDDDMMSS.SS * OR * +-dd.dddddd+-ddd.dddddd * OR * 21 spaces * * Location of the last row, last column of the image block. */ char theLrlcLoc[LRLC_LOC_SIZE+1]; /** * FIELD: LRFC_LOC * * required 21 byte field * * XDDMMSS.SSYDDDMMSS.SS * OR * +-dd.dddddd+-ddd.dddddd * OR * 21 spaces * * Location of the last row, first column of the image block. */ char theLrfcLoc[LRFC_LOC_SIZE+1]; /** * FIELD: FRFC_LOC * * required 21 byte field * * XDDMMSS.SSYDDDMMSS.SS * OR * +-dd.dddddd+-ddd.dddddd * OR * 21 spaces * * Location of the first row, first column of the image block. */ char theFrfcLoc[FRFC_LOC_SIZE+1]; /** * FIELD: FIELD_11 * * Reserved field of 5 bytes containing: 010.0 */ char theField11[FIELD_11_SIZE+1]; TYPE_DATA }; #endif /* End of "#ifndef ossimNitfBlockaTag_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfCommon.h000066400000000000000000000145531352751253100245020ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Utility class for global nitf methods. // //---------------------------------------------------------------------------- // $Id: ossimNitfCommon.h 15410 2009-09-11 19:45:38Z dburken $ #ifndef ossimNitfCommon_HEADER #define ossimNitfCommon_HEADER #include #include #include class ossimDpt; class ossimIrect; /** class ossimNitfCommon for global utility methods */ class OSSIM_DLL ossimNitfCommon { public: /** default constructor */ ossimNitfCommon(); /** destructor */ ~ossimNitfCommon(); /** * This method takes a value and a size(or width) and converts it to a * scientific notation sting in the format: ±0.999999E±9 * * @note If the value is positive, currently there is no + added to the * front. * * @param aValue Value to convert to string. * * @param size total size of the string. This must be at least 7 if * aValue is positive and at least 8 if aValue is negative; else, * no action is taken and an empty string is returned. */ static ossimString convertToScientificString(const ossim_float64& aValue, ossim_uint32 size); /** * This method takes a value and converts to a string of size with * requested precision with a '0' fill. * * Format example: 00925.00 * * @param aValue Value to convert to string. * * @param precision The floating point precision. * * @param size total size of the string. */ static ossimString convertToDoubleString(const ossim_float64& aValue, ossim_uint32 precision, ossim_uint32 size); /** * This method takes a value and converts to a string of size with * with a '0' fill. * * Format example: 00925 * @param aValue Value to convert to string. * * @param size total size of the string. */ static ossimString convertToUIntString(ossim_uint32 aValue, ossim_uint32 size); /** * Just like convertToUIntString only takes a signed value. * * This method takes a value and converts to a string of size with * with a '0' fill. * * Format example: 00925 * @param aValue Value to convert to string. * * @param size total size of the string. */ static ossimString convertToIntString(ossim_int32 aValue, ossim_uint32 size); /** * Converts pt to a decimal degrees latitude longitude location string. * * Format example: +-dd.dddddd+-ddd.dddddd * * @param pt Point to convert where pt.x = longitude and pt.y = latitude. * * @param precision The floating point precision. This will determine the * size of the string. */ static ossimString convertToDdLatLonLocString(const ossimDpt& pt, ossim_uint32 precision); /** * Sets a field with a given string, width, and IOS flags. * * @param fieldDestination * The member NITF field to set. * @param src * The source string. * @param width * The number of characters in fieldDestination to copy from the * source string. * @param ioflags * Formatting flags for the destination string. * @param fill * If the size of the string is smaller than the field size, * this character specifies what the excess character values are. */ static void setField(void* fieldDestination, const ossimString& src, std::streamsize width, std::ios_base::fmtflags ioflags = std::ios::left, char fill = ' '); /** * This will encode a 60 character IGEOLO field. */ static ossimString encodeUtm( ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); static ossimString encodeGeographicDms( const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); static ossimString encodeGeographicDecimalDegrees( const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); /** * @brief Get the nitf pixel type string from scalar type. * * @param scalarType The scalar type. * * @return Pixel type as string, e.g.: "INT", "SI", "R" */ static ossimString getNitfPixelType(ossimScalarType scalarType); /** * @brief Get compression rate (COMRAT) which is bits perpixel per band. * * This corresponds to the nitf image header COMRAT field. Return is in * the form of Nxyz "N" for numerically lossles, where "xyz" * indicates the expected achieved bit rate (in bits per pixel per band) * for the final layer of each tile. The decimal point is implicit and * assumed to be one digit from the right (i.e. xy.z). * * @param rect Image rectangles. * @param bands * @param scalar * @param lengthInBytes Compressed length of image pixels. * @return Approximate number of bits per pixel for the compressed image as * a string which follows the nitf comrat field convention. This will * return an empty string if comrat is bigger than three digits. */ static ossimString getCompressionRate(const ossimIrect& rect, ossim_uint32 bands, ossimScalarType scalar, ossim_uint64 lengthInBytes); }; // End of class ossimNitfCommon. #endif /* #ifndef ossimNitfCommon_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfCompressionHeader.h000066400000000000000000000017261352751253100266620ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2004 Garrett Potts // // LICENSE: MIT // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfCompressionHeader_HEADER #define ossimNitfCompressionHeader_HEADER 1 #include #include #include #include #include class OSSIM_DLL ossimNitfCompressionHeader : public ossimObject { public: virtual void parseStream(ossim::istream& in) = 0; /** * @brief print method that outputs a key/value type format adding prefix * to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const=0; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; protected: TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfCsccgaTag.h000066400000000000000000000072241352751253100250660ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // Author: Garrett Potts // // Description: CSCCGA tag class definition // //---------------------------------------------------------------------------- // $Id$ #include /** * All comments in this document were taken from the online resource found at: * * http://jitc.fhu.disa.mil/nitf/tag_reg * * The Cloud Cover Grid Data TRE (CSCCGA) provides support data that identifies * which image segment and sensors were used to create the cloud grid. CSCCGA * also geometrically registers the cloud grid to the pixel grid of one of the image segments. * 1. The format and content of the CSCCGA TRE shall be as detailed in Table 3.1-1. * 2. When cloud cover information is included in the dataset (see Section 2.1.4.2 for an exception) * both the CSCCGA TRE and the Cloud Cover Shapefile DES (Section 2.6.2) shall be * included in each dataset even though they both express similar information. */ class OSSIM_DLL ossimNitfCsccgaTag : public ossimNitfRegisteredTag { public: enum { CCG_SOURCE_SIZE = 18, REG_SENSOR_SIZE = 6, ORIGIN_LINE_SIZE = 7, ORIGIN_SAMPLE_SIZE = 5, AS_CELL_SIZE_SIZE = 7, CS_CELL_SIZE_SIZE = 5, CCG_MAX_LINE_SIZE = 7, CCG_MAX_SAMPLE_SIZE= 5, CEL_SIZE = 60 }; ossimNitfCsccgaTag(); virtual void parseStream(ossim::istream& in); virtual void writeStream(ossim::ostream& out); virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void clearFields(); protected: /** * Field: CCG_SOURCE * * BCS-A 18 byte field. * * Values: PAN or MS or PAN, MS * * Source of Grid Concatenation of all sensors used to create * cloud cover grid separated by commas */ char m_ccgSource[CCG_SOURCE_SIZE+1]; /** * Field: REG_SENSOR * * BCS-A 6 bytes. * Values: PAN or MS * * Image Segment Sensor to which Cloud Cover Grid is registered * (CCG is always registered to the synthetic array) */ char m_regSensor[REG_SENSOR_SIZE+1]; /** * Field: ORIGIN_LINE * * BCS-N 7 bytes. * * Values: 0000001 * * Cloud Cover Grid Origin – Line * (Corresponding line in registered image segment) */ char m_originLine[ORIGIN_LINE_SIZE+1]; /** * Field: ORIGIN_SAMPLE * * BCS-N 5 bytes * * Values: 00001 * * Cloud Cover Grid Origin – Sample * (Corresponding sample in registered image segment) */ char m_originSample[ORIGIN_SAMPLE_SIZE+1]; /** * Field: AS_CELL_SIZE * * BCS-N 7 bytes * * Value Range: 0000001 - 9999999 * * Along Scan Cell Size – Lines (Cloud Cover Grid spacing in * registered image segment lines) */ char m_asCellSize[AS_CELL_SIZE_SIZE+1]; /** * Field: CS_CELL_SIZE * * BCS-N 5 bytes * * Value Range: 00001 - 99999 * * Cross Scan Cell Size – Samples * (Cloud Cover Grid spacing in registered image segment samples) */ char m_csCellSize[CS_CELL_SIZE_SIZE+1]; /** * Field: CCG_MAX_LINE * * BCS-N 7 bytes * * Value Range: 0000001 - 9999999 * * Number of Rows in CC Grid (Number of Cells in "lines" direction) */ char m_ccgMaxLine[CCG_MAX_LINE_SIZE+1]; /** * Field: CCG_MAX_SAMPLE * * BCS-N 5 bytes * * Value Range: 00001 - 99999 * * Number of Columns in CC Grid (Number of Cells in "sample" direction) */ char m_ccgMaxSample[CCG_MAX_SAMPLE_SIZE+1]; }; ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfCscrnaTag.h000066400000000000000000000070161352751253100251130ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: CSCRNA tag class declaration. // // Corner Footprint TRE. // // See document STDI-0006-NCDRD Table 3.2-13 for more info. // //---------------------------------------------------------------------------- // $Id #ifndef ossimNitfCscrnaTag_HEADER #define ossimNitfCscrnaTag_HEADER 1 #include class OSSIM_DLL ossimNitfCscrnaTag : public ossimNitfRegisteredTag { public: /** @brief default constructor */ ossimNitfCscrnaTag(); /** @brief destructor */ virtual ~ossimNitfCscrnaTag(); /** @brief Method to parse data from stream. */ virtual void parseStream(std::istream& in); /** @brief Method to write data to stream. */ virtual void writeStream(std::ostream& out); /** @brief Method to clear all fields including null terminating. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; protected: //--- // NOTE: Spec says corner points are project from image plane to // reference ellipsoid NOT ellipsoid + height. //--- /** * FIELD: PREDICT_CORNERS * * 1 byte field BCS-A * * Y = predicted, N = actual */ char thePredictedCornerFlag[2]; /** * FIELD: ULCRN_LAT * * 9 byte field BCS-N Degrees * * -90.000000 ti +90.000000 */ char theUlLat[10]; /** * FIELD: ULCRN_LON * * 10 byte field BCS-N Degrees * * -179.999999 ti +180.000000 */ char theUlLon[11]; /** * FIELD: ULCRN_HT * * 8 byte field BCS-N Meters * * Height referenced to the reference ellipsoid. * * -00610.0 to +10668.0 */ char theUlHt[9]; /** * FIELD: URCRN_LAT * * 9 byte field BCS-N Degrees * * -90.000000 ti +90.000000 */ char theUrLat[10]; /** * FIELD: URCRN_LON * * 10 byte field BCS-N Degrees * * -179.999999 ti +180.000000 */ char theUrLon[11]; /** * FIELD: URCRN_HT * * 8 byte field BCS-N Meters * * Height referenced to the reference ellipsoid. * * -00610.0 to +10668.0 */ char theUrHt[9]; /** * FIELD: LRCRN_LAT * * 9 byte field BCS-N Degrees * * -90.000000 ti +90.000000 */ char theLrLat[10]; /** * FIELD: LRCRN_LON * * 10 byte field BCS-N Degrees * * -179.999999 ti +180.000000 */ char theLrLon[11]; /** * FIELD: LRCRN_HT * * 8 byte field BCS-N Meters * * Height referenced to the reference ellipsoid. * * -00610.0 to +10668.0 */ char theLrHt[9]; /** * FIELD: LLCRN_LAT * * 9 byte field BCS-N Degrees * * -90.000000 ti +90.000000 */ char theLlLat[10]; /** * FIELD: LLCRN_LON * * 10 byte field BCS-N Degrees * * -179.999999 ti +180.000000 */ char theLlLon[11]; /** * FIELD: LLCRN_HT * * 8 byte field BCS-N Meters * * Height referenced to the reference ellipsoid. * * -00610.0 to +10668.0 */ char theLlHt[9]; TYPE_DATA }; #endif /* matches #ifndef ossimNitfCscrnaTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfCsdidaTag.h000066400000000000000000000071641352751253100250750ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: CSDIDA tag class declaration. // // Dataset Indentification TRE. // // See document STDI-0006-NCDRD Table 3.3-14 for more info. // //---------------------------------------------------------------------------- // $Id #ifndef ossimNitfCsdidaTag_HEADER #define ossimNitfCsdidaTag_HEADER 1 #include class OSSIM_DLL ossimNitfCsdidaTag : public ossimNitfRegisteredTag { public: /** @brief default constructor */ ossimNitfCsdidaTag(); /** @brief destructor */ virtual ~ossimNitfCsdidaTag(); /** @brief Method to parse data from stream. */ virtual void parseStream(std::istream& in); /** @brief Method to write data to stream. */ virtual void writeStream(std::ostream& out); /** @brief Method to clear all fields including null terminating. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; protected: /** * FIELD: DAY * * 2 byte field BCS-N * * 01 TO 31 (UTC) */ char theDay[3]; /** * FIELD: MONTH * * 3 byte field BCS-A * * JAN to DEC (UTC) */ char theMonth[4]; /** * FIELD: YEAR * * 4 byte field BCS-N * * 0000 to 9999 (UTC) */ char theYear[5]; /** * FIELD: PLATFORM CODE * * 2 byte field BCS-A * * QB, IK, OV, WV ... */ char thePlatformCode[3]; /** * FIELD: VEHICLE ID * * 2 byte field BCS-N * * 00 TO 99 */ char theVehicleId[3]; /** * FIELD: PASS * * 2 byte field BCS-N * * 01 to 99 */ char thePass[3]; /** * FIELD: OPERATION * * 3 byte field BCS-N * * 001 to 999 */ char theOperation[4]; /** * FIELD: SENSOR_ID * * 2 byte field BCS-A * * AA = pan only, GA = multispectral and pan sharpened only, NA = * panchroomatic & multispectral together. */ char theSensorId[3]; /** * FIELD: PRODUCT_ID * * 2 byte field BCS-A * * See table 2.1-7 */ char theProductId[3]; /** * FIELD: Reserved * * 4 bytes BCS-A * * fill "00 " */ char theReservedField1[5]; /** * FIELD: TIME * * 14 byte field BCS-N * * Image start time (UTC) YYYYMMDDhhmmss Corresponds to ACQUISITION_DATE * in STDI-0002 */ char theTime[15]; /** * FIELD: PROCESS_TIME * * 14 byte field BCS-N * * Image start time (UTC) YYYYMMDDhhmmss */ char theProcessTime[15]; /** FIELD: Reserved * * 2 bytes BCS-N * * Fill "00" */ char theReservedField2[3]; /** * FIELD: Reserved * * 2 bytes BCS-N * * Fill "01" */ char theReservedField3[3]; /** * FIELD: Reserved * * 1 byte BCS-A * * Fill "N" */ char theReservedField4[1]; /** * FIELD: Reserved * * 1 byte BCS-A * * BCS-A "N" */ char theReservedField5[1]; /** * FIELD: SOFTWARE_VERSION_NUMBER * * 10 byte field BCS-A * * Software version used. */ char theSoftwareVersionNumber[11]; TYPE_DATA }; #endif /* matches #ifndef ossimNitfCsdidaTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfCsexraTag.h000066400000000000000000000250301352751253100251230ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: CSEXRA tag class declaration. // // Exploitation Reference Data TRE. // // See document STDI-0006-NCDRD Table 3.5-16 for more info. // //---------------------------------------------------------------------------- // $Id #ifndef ossimNitfCsexraTag_HEADER #define ossimNitfCsexraTag_HEADER 1 #include class OSSIM_DLL ossimNitfCsexraTag : public ossimNitfRegisteredTag { public: /** @brief default constructor */ ossimNitfCsexraTag(); /** @brief destructor */ virtual ~ossimNitfCsexraTag(); /** @brief Method to parse data from stream. */ virtual void parseStream(std::istream& in); /** @brief Method to write data to stream. */ virtual void writeStream(std::ostream& out); /** @brief Method to clear all fields including null terminating. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; /** * @brief Get the SENSOR field. * @return The SENSOR field as a string. */ ossimString getSensor() const; /** * @brief Get the TIME_FIRST_LINE_IMAGE field. * @return The TIME_FIRST_LINE_IMAGE field as a string. */ ossimString getTimeFirstLineImage() const; /** * @brief Get the TIME_IMAGE_DURATION field. * @return The TIME_IMAGE_DURATION field as a string. */ ossimString getTimeImageDuration() const; /** * @brief Get the MAX_GSDfield. * @return The MAX_GSD field as a string. */ ossimString getMaxGsd() const; /** * @brief Get the ALONG_SCAN_GSD field. * @return The ALONG_SCAN_GSD field as a string. */ ossimString getAlongScanGsd() const; /** * @brief Get the CROSS_SCAN_GSD field. * @return TheCROSS_SCAN_GSD field as a string. */ ossimString getCrossScanGsd() const; /** * @brief Get the GEO_MEAN_GSD field. * @return The GEO_MEAN_GSD field as a string. */ ossimString getGeoMeanGsd() const; /** * @brief Get the A_S_VERT_GSD field. * @return The A_S_VERT_GSD field as a string. */ ossimString getAlongScanVerticalGsd() const; /** * @brief Get the C_S_VERT_GSD field. * @return The C_S_VERT_GSD field as a string. */ ossimString getCrossScanVerticalGsd() const; /** * @brief Get the GEO_MEAN_VERT_GSD field. * @return The GEO_MEAN_VERT_GSD field as a string. */ ossimString getGeoMeanVerticalGsd() const; /** * @brief Get the GEO_BETA_ANGLEfield. * @return The GEO_BETA_ANGLE field as a string. */ ossimString getGeoBetaAngle() const; /** * @brief Get the DYNAMIC_RANGE field. * @return The DYNAMIC_RANGE field as a string. */ ossimString getDynamicRange() const; /** * @brief Get the NUM_LINES field. * @return The NUM_LINES field as a string. */ ossimString getNumLines() const; /** * @brief Get the NUM_SAMPLES field. * @return The NUM_SAMPLES field as a string. */ ossimString getNumSamples() const; /** * @brief Get the ANGLE_TO_NORTH field. * @return The ANGLE_TO_NORTH field as a string. */ ossimString getAngleToNorth() const; /** * @brief Get the OBLIQUITY_ANGLE field. * @return The OBLIQUITY_ANGLE field as a string. */ ossimString getObliquityAngle() const; /** * @brief Get the AZ_OF_OBLIQUITY field. * @return The AZ_OF_OBLIQUITY field as a string. */ ossimString getAzimuthOfObliquity() const; /** * @brief Get the GRD_COVER field. * @return The GRD_COVER field as a string. */ ossimString getGroundCover() const; /** * @brief Get the SNOW_DEPTH_CAT field. * @return The SNOW_DEPTH_CAT field as a string. */ ossimString getSnowDepth() const; /** * @brief Get the SUN_AZIMUTH field. * @return The SUN_AZIMUTH field as a string. */ ossimString getSunAzimuth() const; /** * @brief Get the SUN_ELEVATION field. * @return The SUN_ELEVATION field as a string. */ ossimString getSunElevation() const; /** * @brief Get the PREDICTED_NIIRS field. * @return The PREDICTED_NIIRS field as a string. */ ossimString getPredictedNiirs() const; /** * @brief Get the CIRCL_ERR field. * @return The CIRCL_ERR field as a string. */ ossimString getCE90() const; /** * @brief Get the LINEAR_ERR field. * @return The LINEAR_ERR field as a string. */ ossimString getLE90() const; protected: /** * FIELD: SENSOR * * 6 byte field BCS-A * * PAN MS */ char theSensor[7]; /** * FIELD: TIME_FIRST_LINE_IMAGE * * 12 byte field BCS-N Seconds (UTC) * * Time in seconds from midnight for the first line, synthetic array, * of the Dataset collection. * * 00000.000000 to 86400.000000 */ char theTileFirstLine[13]; /** * FIELD: TIME_IMAGE_DURATION * * 12 byte field BCS-N Seconds (UTC) * * Time Difference in seconds between the first line, synthetic array, * and the last line, synthetic array. * * 00000.000000 to 86400.000000 */ char theImageTimeDuration[13]; /** * FIELD: MAX_GSD * * 5 byte field BCS-N inches * * Predicted maximum mean ground sample distance (GSD)for the primary * target. * * 000.0 to 999.9 */ char theMaxGsd[6]; /** * FIELD: ALONG_SCAN_GSD * * 5 byte field BCS-A inches * * Measured along scan GSD for the primary target. * * 000.0 to 999.9 or N/A */ char theAlongScanGsd[6]; /** * FIELD: CROSS_SCAN_GSD * * 5 byte field BCS-A inches * * Measured cross scan GSD for the primary target. * * 000.0 to 999.9 or N/A */ char theCrossScanGsd[6]; /** * FIELD: GEO_MEAN_GSD * * 5 byte field BCS-A inches * * Measured mean GSD for the primary target. * * 000.0 to 999.9 or N/A */ char theGeoMeanGsd[6]; /** * FIELD: A_S_VERT_GSD * * 5 byte field BCS-A inches * * Measured along scan vertical GSD for the primary target. * * 000.0 to 999.9 or N/A */ char theAlongScanVertGsd[6]; /** * FIELD: C_S_VERT_GSD * * 5 byte field BCS-A inches * * Measured cross scan vertical GSD for the primary target. * * 000.0 to 999.9 or N/A */ char theCrossScanVertGsd[6]; /** * FIELD: GEO_MEAN_VERT_GSD * * 5 byte field BCS-A inches * * Measured mean vertical GSD for the primary target. * * 000.0 to 999.9 or N/A */ char theGeoMeanVertGsd[6]; /** * FIELD: GEO_BETA_ANGLE * * 5 byte field BCS-A Degrees * * Angle on ground (Earth tangent plane) between along scan and cross scan * directions. * * 00.0 to 180.0 or N/A */ char theGeoBetaAngle[6]; /** * FIELD: DYNAMIC_RANGE * * 5 byte field BCS-N * * Dynamic range extent of pixel values in the image. * * 00000 to 02047 for PAN and MS. */ char theDynamicRange[6]; /** * FIELD: NUM_LINES * * 7 byte field BCS-N * * 0000101 to 9999999 */ char theLine[8]; /** * FIELD: NUM_SAMPLES * * 5 byte field BCS-N * * 00101 to 99999 */ char theSamples[6]; /** * FIELD: ANGLE_TO_NORTH * * 7 byte field BCS-N Degrees * * Angle in degrees measured clockwise from the first row of the image to * true North at image start time. * * 000.000 to 360.000 */ char theAngleToNorth[8]; /** * FIELD: OBLIQUITY_ANGLE * * 6 byte field BCS-N Degrees * * Obliquity angle measured from target local vertical. I.e., the angle * betweent the local North-Earth-Down (NED) horizontal and the optical * axis of the image at the time of closest approach. * * 00.000 to 90.000 */ char theObliquityAngle[7]; /** * FIELD: AZ_OF_OBLIQUITY * * 7 byte field BCS-N Degrees * * Azimuth of the target-SV line-of-sight vectory projected in the target * local horizontal plane, measured clockwise from True North, computed * at Image Start Time. The Velocity Control Point on the focal plane * is projected to this azimuth projection in the target local * horizontal plane. * * 000.000 to 360.000 */ char theAzOfObliquity[8]; /** * FIELD: GRD_COVER * * 1 byte field BCS-N * * Snow or no snow * * 1 = snow, 0 = no snow, 9 = not available. */ char theGrdCover[2]; /** * FIELD: SNOW_DEPTH_CAT * * 1 byte field BCS-N * * Provides the weighted average of the snow depth values for all of * the grids that overlap the tasked image area. * * 0 = 0 inches, * 1 = 1-8 inches or ice, * 2 = 9-17 inches, * 3 = greater than 17 inches * 9 = Not Available */ char theSnowDepthCategory[2]; /** * FIELD: SUN_AZIMUTH * * 7 byte field BCS-N Degrees * * Azimuth of the target-sun line-of-sight vector projected in the * target local horizontal plane, measured clockwise from True North, * calculated at Image Start Time. * * 000.000 to 360.000 */ char theSunAzimuth[8]; /** * FIELD: SUN_ELEVATION * * 7 byte field BCS-N Degrees * * The sun elevation angle from the local target plane to the sun * calculated at Image_Start_Time, where the local target plane is * referenced by the Target Centered - Earth Fixed, ST coordinate frame. * * -90.000 to +90.000 */ char theSunElevation[8]; /** * FIELD: PREDICTED_NIIRS * * 3 byte field BCS-A * * Imagery NIIRS value. * * 0.0 to 9.0 or N/A */ char thePredictedNiirs[4]; /** * FIELD: CIRCL_ERR * * 3 byte field BCS-N Feet * * Predicted CE/90 in the geolocation in the scene. * * 000 to 999 */ char theCircularError[4]; /** * FIELD: LINEAR_ERR * * 3 byte field BCS-N Feet * * Predicted LE/90 in the geolocation in the scene * * 000 to 999 */ char theLinearError[4]; TYPE_DATA }; #endif /* matches #ifndef ossimNitfCsexraTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfCsproaTag.h000066400000000000000000000025221352751253100251260ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: CSCCGA tag class definition // //---------------------------------------------------------------------------- // $Id$ #include class OSSIM_DLL ossimNitfCsproaTag : public ossimNitfRegisteredTag { public: enum{ RESERVE1_SIZE = 12, RESERVE2_SIZE = 12, RESERVE3_SIZE = 12, RESERVE4_SIZE = 12, RESERVE5_SIZE = 12, RESERVE6_SIZE = 12, RESERVE7_SIZE = 12, RESERVE8_SIZE = 12, RESERVE9_SIZE = 12, BWC_SIZE = 12 }; ossimNitfCsproaTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void clearFields(); protected: char m_reserved1[RESERVE1_SIZE+1]; char m_reserved2[RESERVE1_SIZE+1]; char m_reserved3[RESERVE1_SIZE+1]; char m_reserved4[RESERVE1_SIZE+1]; char m_reserved5[RESERVE1_SIZE+1]; char m_reserved6[RESERVE1_SIZE+1]; char m_reserved7[RESERVE1_SIZE+1]; char m_reserved8[RESERVE1_SIZE+1]; char m_reserved9[RESERVE1_SIZE+1]; char m_bwc[BWC_SIZE+1]; }; ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfDataExtensionSegment.h000066400000000000000000000033321352751253100273340ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDataExtensionSegment.h 22418 2013-09-26 15:01:12Z gpotts $ #ifndef ossimNitfDataExtensionSegment_HEADER #define ossimNitfDataExtensionSegment_HEADER #include #include #include #include #include class ossimNitfTagInformation; class OSSIMDLLEXPORT ossimNitfDataExtensionSegment : public ossimPropertyInterface, public ossimObject { public: friend std::ostream& operator <<(std::ostream &out, const ossimNitfDataExtensionSegment &data); ossimNitfDataExtensionSegment(){} virtual ~ossimNitfDataExtensionSegment(){} virtual void parseStream(std::istream &in, ossim_uint64 dataLength)=0; virtual const std::vector& getTagList()const=0; virtual void getPropertyNames(std::vector& propertyNames)const; static const ossimString DE_KW; static const ossimString DESVER_KW; static const ossimString DESOFLW_KW; static const ossimString DESITEM_KW; static const ossimString DESSHL_KW; static const ossimString DESSHF_KW; static const ossimString DESDATA_KW; static const ossimString DECLAS_KW; static const ossimString DESCODE_KW; static const ossimString DESCTLH_KW; static const ossimString DESREL_KW; static const ossimString DESCAUT_KW; static const ossimString DESCTLN_KW; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfDataExtensionSegmentV2_0.h000066400000000000000000000054331352751253100277670ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDataExtensionSegmentV2_0.h 22418 2013-09-26 15:01:12Z gpotts $ #ifndef ossimNitfDataExtensionSegmentV2_0_HEADER #define ossimNitfDataExtensionSegmentV2_0_HEADER #include #include struct ossimNitfDataExtIdentSecurityChunkV2_0 { friend std::ostream& operator <<(std::ostream& out, const ossimNitfDataExtIdentSecurityChunkV2_0& data); char theFilePartType[3]; // 2 byte alpha char theUniqueDataExtTypeId[26]; // 25 byte alpha numeric char theVersionDataFieldDef[3]; // 2 byte numeric char theDataExtSecurityClass[2]; // 1 byte alpha char theDataExtCodewords[41]; // 40 byte alpha numeric char theDataExtControlAndHand[41]; // 40 byte alpha numeric char theDataExtReleasingInst[41]; // 40 byte alpha numeric char theDataExtClassAuthority[21]; // 20 byte alph num char theDataExtSecurityConNum[21]; // 20 byte alpha num char theDataExtSecurityDowngrade[7]; // 6 byte alpha num char theDataExtDowngradingEvent[41]; // 40 byte alpha num }; class OSSIMDLLEXPORT ossimNitfDataExtensionSegmentV2_0 : public ossimNitfDataExtensionSegment { public: ossimNitfDataExtensionSegmentV2_0(); virtual ~ossimNitfDataExtensionSegmentV2_0(); virtual void parseStream(std::istream &in, ossim_uint64 dataLength); virtual std::ostream& print(std::ostream& out)const; virtual const std::vector& getTagList()const { return theTagList; } ossimRefPtr getProperty(const ossimString& name)const; void getPropertyNames(std::vector& propertyNames)const; static const ossimString DESTAG_KW; static const ossimString DESDWNG_KW; static const ossimString DESDEVT_KW; private: void clearFields(); ossimNitfDataExtIdentSecurityChunkV2_0 theIdentSecurityChunk; /*! * This is a 6 byte field */ char theOverflowedHeaderType[7]; /*! * This is a 3 byte field */ char theDataItemOverflowed[4]; /*! * This is a 4 byte field. */ char theLengthOfUserDefinedSubheaderFields[5]; /*! * This is an n-byte field, where n is theLengthOfUserDefinedSubheaderFields. */ std::vector theUserDefinedSubheaderFields; /*! * This is an n-byte field, where n is found in the file header. */ std::vector theData; std::vector theTagList; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfDataExtensionSegmentV2_1.h000066400000000000000000000074111352751253100277660ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDataExtensionSegmentV2_1.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfDataExtensionSegmentV2_1_HEADER #define ossimNitfDataExtensionSegmentV2_1_HEADER #include #include class ossimNitfFileHeaderV2_1; struct ossimNitfDataExtIdentSecurityChunkV2_1 { friend std::ostream& operator <<(std::ostream& out, const ossimNitfDataExtIdentSecurityChunkV2_1& data); char theFilePartType[3]; // 2 byte alpha char theUniqueDataExtTypeId[26]; // 25 byte alpha numeric char theVersionDataFieldDef[3]; // 2 byte numeric char theDataExtSecurityClass[2]; // 1 byte alpha char theDataExtClassSystem[3]; char theDataExtCodewords[12]; // 11 byte alpha numeric char theDataExtControlAndHand[3]; // 2 byte alpha numeric char theDataExtReleasingInst[21]; // 20 byte alpha numeric char theDataExtDeclassType[3]; char theDataExtDeclassDate[9]; char theDataExtDeclassExempt[5]; char theDataExtSecurityDowngrade[2]; // 1 byte alpha char theDataExtSecurityDowngradeDate[9]; char theDataExtSecurityClassText[44]; char theDataExtClassAuthType[2]; char theDataExtClassAuthority[41]; // 40 byte alph num char theDataExtClassReason[2]; char theDataExtSecuritySourceDate[9]; char theDataExtSecurityConNum[16]; // 20 byte alpha num }; class OSSIMDLLEXPORT ossimNitfDataExtensionSegmentV2_1 : public ossimNitfDataExtensionSegment { public: ossimNitfDataExtensionSegmentV2_1(); virtual ~ossimNitfDataExtensionSegmentV2_1(); virtual void parseStream(std::istream &in, ossim_uint64 dataLength); virtual void writeStream(std::ostream &out); virtual std::ostream& print(std::ostream& out)const; virtual const std::vector& getTagList()const { return theTagList; } virtual void setTagList(const std::vector &tagList); virtual void setSecurityMarkings(const ossimNitfFileHeaderV2_1 &fileHeader); virtual ossim_uint32 getHeaderLength() const; virtual ossim_uint64 getDataLength() const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; static const ossimString DESID_KW; static const ossimString DESCLSY_KW; static const ossimString DESDCTP_KW; static const ossimString DESDCDT_KW; static const ossimString DESDCXM_KW; static const ossimString DESDG_KW; static const ossimString DESDGDT_KW; static const ossimString DESCLTX_KW; static const ossimString DESCATP_KW; static const ossimString DESCRSN_KW; static const ossimString DESSRDT_KW; private: void clearFields(); ossimNitfDataExtIdentSecurityChunkV2_1 theIdentSecurityChunk; /*! * This is a 6 byte field */ char theOverflowedHeaderType[7]; /*! * This is a 3 byte field */ char theDataItemOverflowed[4]; /*! * This is a 4 byte field. */ char theLengthOfUserDefinedSubheaderFields[5]; /*! * This is an n-byte field, where n is theLengthOfUserDefinedSubheaderFields. */ std::vector theUserDefinedSubheaderFields; /*! * This is an n-byte field, where n is found in the file header. */ std::vector theData; std::vector theTagList; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfDesFactory.h000066400000000000000000000017561352751253100253160ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDesFactory.h 17207 2010-04-25 23:21:14Z dburken $ #ifndef ossimNitfDesFactory_HEADER #define ossimNitfDesFactory_HEADER #include #include #include class ossimNitfRegisteredDes; class OSSIM_DLL ossimNitfDesFactory : public ossimObject { public: ossimNitfDesFactory(); virtual ~ossimNitfDesFactory(); virtual ossimRefPtr create(const ossimString &desName)const=0; private: /*! * Hide this. */ ossimNitfDesFactory(const ossimNitfDesFactory & /* rhs */){} /*! * Hide this. */ ossimNitfDesFactory& operator =(const ossimNitfDesFactory & /* rhs */){return *this;} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfDesFactoryRegistry.h000066400000000000000000000025461352751253100270450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDesFactoryRegistry.h 22875 2014-08-27 13:52:03Z dburken $ #ifndef ossimNitfDesFactoryRegistry_HEADER #define ossimNitfDesFactoryRegistry_HEADER 1 #include #include #include class ossimString; class ossimNitfDesFactory; class OSSIM_DLL ossimNitfDesFactoryRegistry { public: virtual ~ossimNitfDesFactoryRegistry(); void registerFactory(ossimNitfDesFactory* aFactory); void unregisterFactory(ossimNitfDesFactory* aFactory); static ossimNitfDesFactoryRegistry* instance(); ossimRefPtr create(const ossimString &desName)const; bool exists(ossimNitfDesFactory* factory)const; protected: ossimNitfDesFactoryRegistry(); private: /** hidden copy constructory */ ossimNitfDesFactoryRegistry(const ossimNitfDesFactoryRegistry& factory); /** hidden operator= */ const ossimNitfDesFactoryRegistry& operator=( const ossimNitfDesFactoryRegistry& factory); void initializeDefaults(); std::vector theFactoryList; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfDesInformation.h000066400000000000000000000075311352751253100261710ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDesInformation.h 22418 2013-09-26 15:01:12Z gpotts $ #ifndef ossimNitfDesInformation_HEADER #define ossimNitfDesInformation_HEADER #include #include class ossimString; class OSSIMDLLEXPORT ossimNitfDesInformation : public ossimObject { public: enum{ DE_SIZE = 2, DESID_SIZE = 25, DESVER_SIZE = 2, DECLAS_SIZE = 1, DESCLSY_SIZE = 2, DESCODE_SIZE = 11, DESCTLH_SIZE = 2, DESREL_SIZE = 20, DESDCTP_SIZE = 2, DESDCDT_SIZE = 8, DESDCXM_SIZE = 4, DESDG_SIZE = 1, DESDGDT_SIZE = 8, DESCLTX_SIZE = 43, DESCATP_SIZE = 1, DESCAUT_SIZE = 40, DESCRSN_SIZE = 1, DESSRDT_SIZE = 8, DESCTLN_SIZE = 15, DESOFLW_SIZE = 6, DESITEM_SIZE = 3, DESSHL_SIZE = 4 }; ossimNitfDesInformation(ossimRefPtr desData = 0); virtual ~ossimNitfDesInformation(); //virtual void parseStream(std::istream& in); virtual void parseStream(std::istream &in, ossim_uint64 dataLength=0); virtual void writeStream(std::ostream& out); void setDesName(const ossimString& desName); void setDesLength(ossim_uint32 desLength); /** * Length of the 5 byte des length the 6 byte des name and * the data length. * So we have Data length + 11 bytes. */ ossim_uint32 getTotalDesLength()const; /** * Should return the value of theDesLength which is the length of * the data in bytes. */ ossim_uint32 getDesLength()const; ossim_uint64 getDesOffset()const; ossim_uint64 getDesDataOffset()const; ossimString getDesId()const; virtual std::ostream& print(std::ostream& out, const std::string& prefix)const; void clearFields(); ossimRefPtr getDesData(); const ossimRefPtr getDesData()const; void setDesData(ossimRefPtr desData); bool operator<(const ossimNitfDesInformation& rhs) const { return getTotalDesLength() < rhs.getTotalDesLength(); } private: char m_de[DE_SIZE+1]; char m_desid[DESID_SIZE+1]; char m_desver[DESVER_SIZE+1]; char m_declas[DECLAS_SIZE+1]; char m_desclsy[DESCLSY_SIZE+1]; char m_descode[DESCODE_SIZE+1]; char m_desctlh[DESCTLH_SIZE+1]; char m_desrel[DESREL_SIZE+1]; char m_desdctp[DESDCTP_SIZE+1]; char m_desdcdt[DESDCDT_SIZE+1]; char m_desdcxm[DESDCXM_SIZE+1]; char m_desdg[DESDG_SIZE+1]; char m_desdgdt[DESDGDT_SIZE+1]; char m_descltx[DESCLTX_SIZE+1]; char m_descatp[DESCATP_SIZE+1]; char m_descaut[DESCAUT_SIZE+1]; char m_descrsn[DESCRSN_SIZE+1]; char m_dessrdt[DESSRDT_SIZE+1]; char m_desctln[DESCTLN_SIZE+1]; char m_desoflw[DESOFLW_SIZE+1]; char m_desitem[DESITEM_SIZE+1]; char m_desshl[DESSHL_SIZE+1]; /** * This will hold the offset to the start of the above information * This is just a work variable. */ ossim_uint64 m_desOffset; ossim_uint64 m_desLength; /** * This will hold the start to the data. This is just the * position in the file just past the des length field. * This is just a work variable */ ossim_uint64 m_desDataOffset; ossim_uint64 m_desDataSize; /** * Used to hold the des data. */ ossimRefPtr m_desData; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfEmbeddedRpfDes.h000066400000000000000000000021621352751253100260400ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfEmbeddedRpfDes.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfEmbeddedRpfDes_HEADER #define ossimNitfEmbeddedRpfDes_HEADER 1 #include #include class ossimNitfFileHeader; class OSSIMDLLEXPORT ossimNitfEmbeddedRpfDes : public ossimNitfRegisteredTag { public: ossimNitfEmbeddedRpfDes(); virtual void parseStream(std::istream &in); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; protected: virtual ~ossimNitfEmbeddedRpfDes(); TYPE_DATA private: }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfEngrdaTag.h000066400000000000000000000113161352751253100251000ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: ENGRDA - Engineering Data tag class declaration. // // See document STDI-0002 (version 4), Appendix N for more info. // //---------------------------------------------------------------------------- // $Id #ifndef ossimNitfEngrdaTag_HEADER #define ossimNitfEngrdaTag_HEADER 1 #include #include #include class OSSIM_DLL ossimNitfEngrdaTag : public ossimNitfRegisteredTag { public: enum { RESRC_SIZE = 20, RECNT_SIZE = 3, ENGLN_SIZE = 2, ENGMTXC_SIZE = 4, ENGMTXR_SIZE = 4, ENGTYP_SIZE = 1, ENGDTS_SIZE = 1, ENGDATU_SIZE = 2, ENGDATC_SIZE = 8, TMP_BUF_SIZE = 128 }; /** @brief default constructor */ ossimNitfEngrdaTag(); /** @brief destructor */ virtual ~ossimNitfEngrdaTag(); /** @brief Method to parse data from stream. */ virtual void parseStream(std::istream& in); /** @brief Method to write data to stream. */ virtual void writeStream(std::ostream& out); /** @brief Method to clear all fields including null terminating. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; protected: /** @brief Container class for an Engineering Data Element Record. */ class ossimEngDataElement { public: /** * FIELD: ENGLN * * TYPE: BCS-N * * 2 byte field * * Engineering Data Label Length 01 - 99 */ char m_engLn[ENGLN_SIZE+1]; /** * FIELD: ENGLBL * * TYPE: BCS-A * * Engineering Label - variable length */ std::string m_engLbl; /** * FIELD: ENGMTXC * * TYPE: BCS-N * * 4 byte field * * Engineering Matrix Data Column Count 0001 - 9999 */ char m_engMtxC[ENGMTXC_SIZE+1]; /** * FIELD: ENGMTXR * * TYPE: BCS-N * * 4 byte field * * Engineering Matrix Data Row Count 0001 - 9999 */ char m_engMtxR[ENGMTXR_SIZE+1]; /** * FIELD: ENGTYP * * TYPE: BCS * * 1 byte field * * Value Type of Engineering Data Element */ char m_engTyp; /** * FIELD: ENGDTS * * TYPE: BCS-N * * 1 byte field * * Engineering Data Element Size */ char m_engDts; /** * FIELD: ENGDATU * * TYPE: BCS-A * * 2 byte field * * Engineering Data Units */ char m_engDatU[ENGDATU_SIZE+1]; /** * FIELD: ENGDATC * * TYPE: BCS-N * * 8 byte field * * Engineering Data Count */ char m_engDatC[ENGDATC_SIZE+1]; /** ENGDATA - data */ std::vector m_engDat; }; /** * @brief Method to print out a ossimEngDataElement object. * @param out Stream to print to. * @param element The element to print. * @param elIndex The index of the element array index. * @param prefix The prefix to add to key. */ std::ostream& printData(std::ostream& out, const ossimEngDataElement& element, ossim_uint32 elIndex, const std::string& prefix) const; /** * @brief Method to convert value to a string, padding with zero's, * left justified. * @param v The value to convert. * @param w The width of the string field. * @param s The string to stuff. */ template void getValueAsString(T v, ossim_uint16 w, std::string& s) const; /** Type R = Required Type = BCS spaces allowed for entire field */ /** * FIELD: RESRC * * TYPE: BCS-A * * 20 byte field * * Unique Source System Name. */ char m_reSrc[RESRC_SIZE+1]; /** * FIELD: RECNT * * TYPE: BCS-N * * 3 byte field * * Record Entry Count 001 - 999 */ char m_reCnt[RECNT_SIZE+1]; std::vector m_data; TYPE_DATA }; #endif /* matches #ifndef ossimNitfEngrdaTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfExoptaTag.h000066400000000000000000000102471352751253100251420ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: EXOPTA tag header definition // //---------------------------------------------------------------------------- // $Id$ #include /** * * EXOPTA - Exploitation Usability Optical Information Extension Format * */ class OSSIM_DLL ossimNitfExoptaTag : public ossimNitfRegisteredTag { public: enum{ ANGLE_TO_NORTH_SIZE = 3, MEAN_GSD_SIZE = 5, EXOPTA_RESERVED1_SIZE = 1, DYNAMIC_RANGE_SIZE = 5, EXOPTA_RESERVED2_SIZE = 7, OBL_ANG_SIZE = 5, ROLL_ANG_SIZE = 6, PRIME_ID_SIZE = 12, PRIME_BE_SIZE = 15, EXOPTA_RESERVED3_SIZE = 5, N_SEC_SIZE = 3, EXOPTA_RESERVED4_SIZE = 2, EXOPTA_RESERVED5_SIZE = 7, N_SEG_SIZE = 3, MAX_LP_SEG_SIZE = 6, EXOPTA_RESERVED6_SIZE = 12, SUN_EL_SIZE = 5, SUN_AZ_SIZE = 5, CEL_SIZE = 107 // total }; ossimNitfExoptaTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void clearFields(); protected: /** * Field: ANGLE_TO_NORTH * * Angle to True North. Angle, * measured clockwise, from the * first-row vector (pointing from * the first column to the last) to * a vector pointing to True * North. */ char m_angleToNorth[ANGLE_TO_NORTH_SIZE+1]; /** * Field: MEAN_GSD * * Mean Ground Sample * Distance. The geometric * mean of the cross and along * scan center-to-center distance * between contiguous ground * samples. Accuracy = ±10% * Note: Systems requiring an * extended range shall insert a * default value of “000.0†for this * field and utilize the PIAMC * tag. */ char m_meanGsd[MEAN_GSD_SIZE+1]; char m_reserved1[EXOPTA_RESERVED1_SIZE+1]; /** * Field: DYNAMIC_RANGE * * Dynamic Range of image pixels. */ char m_dynamicRange[DYNAMIC_RANGE_SIZE+1]; char m_reserved2[EXOPTA_RESERVED2_SIZE+1]; /** * Field: OBL_ANG * * Obliquity Angle. Angle between the local NED * horizontal and the optical axis of the image. */ char m_oblAng[OBL_ANG_SIZE+1]; /** * Field: ROLL_ANG * * Roll Angle of the platform body */ char m_rollAng[ROLL_ANG_SIZE+1]; /** * Field: PRIME_ID * * Primary Target ID */ char m_primeId[PRIME_ID_SIZE+1]; /** * Field: PRIME_BE * * Primary Target BE / OSUFFIX (target designator) */ char m_primeBe[PRIME_BE_SIZE+1]; char m_reserved3[EXOPTA_RESERVED3_SIZE+1]; /** * Field: N_SEC * * Number Of Secondary Targets in Image. Determines the number of SECTG * extension present in the image subheader. */ char m_nSec[N_SEC_SIZE+1]; char m_reserved4[EXOPTA_RESERVED4_SIZE+1]; char m_reserved5[EXOPTA_RESERVED5_SIZE+1]; /** * Field: N_SEG * * * Number of Segments. Segments are separate imagery pieces within an * imaging operation. Range 001 to 999 */ char m_nSeg[N_SEG_SIZE+1]; /** * Field: MAX_LP_SEG * * Maximum Number of Lines Per Segment. Includes overlap lines. * * Range: 000001 to 199999 */ char m_maxLpSeg[MAX_LP_SEG_SIZE+1]; char m_reserved6[EXOPTA_RESERVED6_SIZE+1]; /** * Field: SUN_EL * * Sun Elevation. Angle in degrees, measured from the target plane at intersection of * the optical line of sight with the earth’s surface at the time * of the first image line (NITF row 1). 999.9 indicates data is * not available. * * range: +-90.0, 999.9 */ char m_sunEl[SUN_EL_SIZE+1]; /** * Field: SUN_AZ * * Sun Azimuth. Angle in degrees, from True North * clockwise (as viewed from space) at the time of the first * image line. 999.9 indicates data is not available. * * Range: 000.0 to 359.9, 999.9 */ char m_sunAz[SUN_AZ_SIZE+1]; }; ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfFile.h000066400000000000000000000104071352751253100241230ustar00rootroot00000000000000//--- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //--- // $Id$ #ifndef ossimNitfFile_HEADER #define ossimNitfFile_HEADER 1 #include #include #include #include #include #include #include class ossimNitfImageHeader; class ossimNitfSymbolHeader; class ossimNitfLabelHeader; class ossimNitfTextHeader; class ossimNitfDataExtensionSegment; class OSSIMDLLEXPORT ossimNitfFile : public ossimReferenced { public: friend OSSIMDLLEXPORT std::ostream& operator <<(std::ostream& out, const ossimNitfFile &data); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out Stream to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @param printOverviews If true overview, if present(e.g. rpf's) will be * printed. * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string(), bool printOverviews=true) const; /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out Stream to output to. * @param entryIndex Entry to print. Not supported by all info objects * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @param printOverviews If true overview, if present(e.g. rpf's) will be * printed. * @return output stream. */ std::ostream& print(std::ostream& out, ossim_uint32 entryIndex, const std::string& prefix=std::string(), bool printOverviews=false) const; ossimNitfFile(); virtual ~ossimNitfFile(); /*! * Opens the nitf file and attempts to parse. * Returns true on success, false on error. */ bool parseFile(const ossimFilename& file); /** * @brief Parse stream method. * @param file Filename from opened stream. * @param in Stream to parse. * @return true on success, false on error. */ bool parseStream(const ossimFilename& file, ossim::istream& in); /*! * Will return the header. */ const ossimNitfFileHeader* getHeader()const; ossimNitfFileHeader* getHeader(); ossimIrect getImageRect()const; ossimNitfImageHeader* getNewImageHeader(ossim_uint32 imageNumber)const; ossimNitfImageHeader* getNewImageHeader(ossim::istream& in, ossim_uint32 imageNumber)const; ossimNitfSymbolHeader* getNewSymbolHeader(ossim_uint32 symbolNumber)const; ossimNitfSymbolHeader* getNewSymbolHeader(ossim::istream& in, ossim_uint32 symbolNumber)const; ossimNitfLabelHeader* getNewLabelHeader(ossim_uint32 labelNumber)const; ossimNitfLabelHeader* getNewLabelHeader(ossim::istream& in, ossim_uint32 labelNumber)const; ossimNitfTextHeader* getNewTextHeader(ossim_uint32 textNumber)const; ossimNitfTextHeader* getNewTextHeader(ossim::istream& in, ossim_uint32 textNumber)const; ossimNitfDataExtensionSegment* getNewDataExtensionSegment(ossim_uint32 dataExtNumber)const; ossimNitfDataExtensionSegment* getNewDataExtensionSegment(ossim::istream& in, ossim_uint32 dataExtNumber)const; ossimString getVersion()const; /** @return The filename parsed by this object. */ ossimFilename getFilename() const; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix)const; protected: ossimNitfImageHeader* allocateImageHeader()const; ossimFilename theFilename; ossimRefPtr theNitfFileHeader; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfFileHeader.h000066400000000000000000000173611352751253100252420ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfFileHeader_HEADER #define ossimNitfFileHeader_HEADER 1 #include #include #include #include #include #include #include #include class ossimNitfImageHeader; class ossimNitfSymbolHeader; class ossimNitfTextHeader; class ossimNitfLabelHeader; class ossimNitfRegisteredTag; class ossimNitfDataExtensionSegment; // These structures are just data holders and will // not be used directly by outside users. This is for internal use // class OSSIM_DLL ossimNitfImageOffsetInformation : public ossimObject { public: virtual std::ostream& print(std::ostream& out) const; ossimNitfImageOffsetInformation(ossim_uint64 headerOffset, ossim_uint64 dataOffset) :theImageHeaderOffset(headerOffset), theImageDataOffset(dataOffset) { } ossim_uint64 theImageHeaderOffset; ossim_uint64 theImageDataOffset; }; class OSSIMDLLEXPORT ossimNitfSymbolOffsetInformation : public ossimObject { public: ossimNitfSymbolOffsetInformation(ossim_uint64 headerOffset, ossim_uint64 dataOffset) :theSymbolHeaderOffset(headerOffset), theSymbolDataOffset(dataOffset) { } ossim_uint64 theSymbolHeaderOffset; ossim_uint64 theSymbolDataOffset; }; class OSSIMDLLEXPORT ossimNitfGraphicOffsetInformation : public ossimObject { public: ossimNitfGraphicOffsetInformation(ossim_uint64 headerOffset, ossim_uint64 dataOffset) :theGraphicHeaderOffset(headerOffset), theGraphicDataOffset(dataOffset) { } ossim_uint64 theGraphicHeaderOffset; ossim_uint64 theGraphicDataOffset; }; class OSSIMDLLEXPORT ossimNitfLabelOffsetInformation : public ossimObject { public: ossimNitfLabelOffsetInformation(ossim_uint64 headerOffset, ossim_uint64 dataOffset) :theLabelHeaderOffset(headerOffset), theLabelDataOffset(dataOffset) { } ossim_uint64 theLabelHeaderOffset; ossim_uint64 theLabelDataOffset; }; class OSSIMDLLEXPORT ossimNitfTextOffsetInformation : public ossimObject { public: ossimNitfTextOffsetInformation(ossim_uint64 headerOffset, ossim_uint64 dataOffset) :theTextHeaderOffset(headerOffset), theTextDataOffset(dataOffset) { } ossim_uint64 theTextHeaderOffset; ossim_uint64 theTextDataOffset; }; class OSSIMDLLEXPORT ossimNitfDataExtSegOffsetInformation : public ossimObject { public: ossimNitfDataExtSegOffsetInformation(ossim_uint64 headerOffset, ossim_uint64 dataOffset) :theDataExtSegHeaderOffset(headerOffset), theDataExtSegDataOffset(dataOffset) { } ossim_uint64 theDataExtSegHeaderOffset; ossim_uint64 theDataExtSegDataOffset; }; class OSSIM_DLL ossimNitfFileHeader : public ossimObject, public ossimPropertyInterface { public: friend class ossimNitfFile; ossimNitfFileHeader(); virtual ~ossimNitfFileHeader(); virtual void parseStream(ossim::istream& in)= 0; virtual void writeStream(ossim::ostream& out)=0; virtual bool isEncrypted()const=0; virtual ossim_int32 getNumberOfImages()const=0; virtual ossim_int32 getNumberOfLabels()const=0; virtual ossim_int32 getNumberOfSymbols()const=0; virtual ossim_int32 getNumberOfGraphics()const=0; virtual ossim_int32 getNumberOfTextSegments()const=0; virtual ossim_int32 getNumberOfDataExtSegments()const=0; virtual ossim_int32 getNumberOfReservedExtSegments()const=0; virtual ossim_int32 getHeaderSize()const=0; void addTag(const ossimNitfTagInformation& tag, bool unique=true); virtual void removeTag(const ossimString& tagName); virtual bool getTagInformation(ossimNitfTagInformation& tag, int idx)const; virtual std::vector getAllTags() { return theTagList; } virtual void setAllTags(std::vector tagList) { theTagList = tagList; } virtual int getNumberOfTags()const; virtual bool getTag(ossimNitfTagInformation& tagInfo, const ossimString& tagName)const; virtual bool getDesInformation(ossimNitfDesInformation& desInfo, const ossimString& desId, bool exactMatch=false); virtual ossim_int64 getFileSize()const=0; virtual const char* getVersion()const=0; virtual const char* getDateTime()const=0; virtual ossimDrect getImageRect()const=0; virtual ossimString getSecurityClassification()const=0; /** * isValid will test if the fields are valid and will return true or false. */ virtual bool isValid()const=0; bool hasImages()const; bool hasSymbols()const; bool hasGraphics()const; bool hasText()const; bool hasLabels()const; bool hasDataExtSegments()const; virtual ossimNitfImageHeader* getNewImageHeader(ossim_uint32 imageNumber, ossim::istream& in)const=0; virtual ossimNitfSymbolHeader* getNewSymbolHeader(ossim_uint32 symbolNumber, ossim::istream& in)const=0; virtual ossimNitfLabelHeader* getNewLabelHeader(ossim_uint32 labelNumber, ossim::istream& in)const=0; virtual ossimNitfTextHeader* getNewTextHeader(ossim_uint32 textNumber, ossim::istream& in)const=0; virtual ossimNitfDataExtensionSegment* getNewDataExtensionSegment( ossim_int32 dataExtNumber, ossim::istream& in)const=0; virtual ossimNitfImageHeader* allocateImageHeader()const=0; virtual ossimNitfSymbolHeader* allocateSymbolHeader()const=0; virtual ossimNitfLabelHeader* allocateLabelHeader()const=0; virtual ossimNitfTextHeader* allocateTextHeader()const=0; virtual ossimNitfDataExtensionSegment *allocateDataExtSegment()const=0; virtual const std::vector& getDesInfoList()const; virtual ossim_uint32 getTotalTagLength() const; /** @brief Sets file length (FL) field. */ virtual void setFileLength(ossim_uint64 fileLength) = 0; /** @brief Sets header length (HL) field. */ virtual void setHeaderLength(ossim_uint64 headerLength) = 0; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * @brief Print method that outputs a key/value type format * adding prefix to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; /** * @brief print tags method that outputs a key/value type format adding * prefix to keys. */ virtual std::ostream& printTags( std::ostream& out, const std::string& prefix=std::string()) const; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; protected: std::vector theTagList; std::vector theDesList; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfFileHeaderV2_0.h000066400000000000000000000445221352751253100256700ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfFileHeaderV2_0_HEADER #define ossimNitfFileHeaderV2_0_HEADER 1 #include #include #include #include #include class ossimNitfRegisteredTag; class ossimNitfImageInfoRecordV2_0 { public: friend std::ostream& operator <<(std::ostream& out, const ossimNitfImageInfoRecordV2_0 &data); ossim_uint32 getHeaderLength()const; ossim_uint64 getImageLength()const; ossim_uint64 getTotalLength()const; void setSubheaderLength(ossim_uint32 length); void setImageLength(ossim_uint64 length); /*! * Is a 6 byte numeric 0-999999 */ char theImageSubheaderLength[7]; /*! * Is a 10 byte numeric 0-999999999 */ char theImageLength[11]; }; struct ossimNitfSymbolInfoRecordV2_0 { public: friend std::ostream& operator <<(std::ostream& out, const ossimNitfSymbolInfoRecordV2_0 &data); ossim_int32 getHeaderLength()const; ossim_int32 getImageLength()const; ossim_int32 getTotalLength()const; /*! * Is a 4 byte numeric 0-9999 */ char theSymbolSubheaderLength[5]; /*! * Is a 6 byte numeric 0-999999 */ char theSymbolLength[7]; }; struct ossimNitfLabelInfoRecordV2_0 { public: friend std::ostream& operator <<(std::ostream& out, const ossimNitfLabelInfoRecordV2_0 &data); ossim_int32 getHeaderLength()const; ossim_int32 getImageLength()const; ossim_int32 getTotalLength()const; /*! * Is a 4 byte numeric 0-9999 */ char theLabelSubheaderLength[5]; /*! * Is a 3 byte numeric 0-320 */ char theLabelLength[4]; }; struct ossimNitfTextInfoRecordV2_0 { public: friend std::ostream& operator <<(std::ostream& out, const ossimNitfTextInfoRecordV2_0 &data); ossim_int32 getHeaderLength()const; ossim_int32 getImageLength()const; ossim_int32 getTotalLength()const; /*! * Is a 4 byte numeric 0-9999 */ char theTextSubheaderLength[5]; /*! * Is a 5 byte numeric 0-99999 */ char theTextLength[6]; }; struct ossimNitfDataExtSegInfoRecordV2_0 { public: friend std::ostream& operator <<(std::ostream& out, const ossimNitfDataExtSegInfoRecordV2_0 &data); ossim_int32 getHeaderLength()const; ossim_int32 getImageLength()const; ossim_int32 getTotalLength()const; /*! * Is a 4 byte numeric 0-9999 */ char theDataExtSegSubheaderLength[5]; /*! * Is a 9 byte numeric 0-999999999 */ char theDataExtSegLength[10]; }; struct ossimNitfResExtSegInfoRecordV2_0 { public: friend std::ostream& operator <<(std::ostream& out, const ossimNitfResExtSegInfoRecordV2_0 &data); /*! * Is a 4 byte numeric 0-9999 */ char theResExtSegSubheaderLength[5]; /*! * Is a 7 byte numeric 0-9999999 */ char theResExtSegLength[8]; }; class OSSIMDLLEXPORT ossimNitfFileHeaderV2_0 : public ossimNitfFileHeaderV2_X { public: ossimNitfFileHeaderV2_0(); virtual ~ossimNitfFileHeaderV2_0(); /** * @brief parse method. * @return This method returns void but will throw an std::exception in * certain instances if the stream goes bad on seeks. */ virtual void parseStream(ossim::istream& in); virtual void writeStream(ossim::ostream& out); /** * @brief print method that outputs a key/value type format adding prefix * to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual bool isEncrypted()const; virtual ossim_int32 getNumberOfImages()const; virtual ossim_int32 getNumberOfLabels()const; virtual ossim_int32 getNumberOfSymbols()const; virtual ossim_int32 getNumberOfGraphics()const; virtual ossim_int32 getNumberOfTextSegments()const; virtual ossim_int32 getNumberOfDataExtSegments()const; virtual ossim_int32 getNumberOfReservedExtSegments()const; virtual ossim_int32 getHeaderSize()const; virtual ossim_int64 getFileSize()const; virtual ossimString getSecurityClassification()const; virtual const char* getDateTime()const; virtual const char* getVersion()const; virtual ossimDrect getImageRect()const; virtual void addImageInfoRecord(const ossimNitfImageInfoRecordV2_0& recordInfo); virtual void replaceImageInfoRecord(ossim_uint32 i, const ossimNitfImageInfoRecordV2_0& recordInfo); virtual ossimNitfImageHeader* getNewImageHeader(ossim_uint32 imageNumber, ossim::istream& in)const; virtual ossimNitfSymbolHeader* getNewSymbolHeader(ossim_uint32 symbolNumber, ossim::istream& in)const; virtual ossimNitfLabelHeader* getNewLabelHeader(ossim_uint32 labelNumber, ossim::istream& in)const; virtual ossimNitfTextHeader* getNewTextHeader(ossim_uint32 textNumber, ossim::istream& in)const; virtual ossimNitfDataExtensionSegment* getNewDataExtensionSegment( ossim_int32 dataExtNumber, ossim::istream& in)const; virtual ossimNitfImageHeader* allocateImageHeader()const; virtual ossimNitfSymbolHeader* allocateSymbolHeader()const; virtual ossimNitfLabelHeader* allocateLabelHeader()const; virtual ossimNitfTextHeader* allocateTextHeader()const; virtual ossimNitfDataExtensionSegment *allocateDataExtSegment()const; virtual void setCodeWords(const ossimString& codeWords); virtual void setControlAndHandling(const ossimString& controlAndHandling); virtual void setReleasingInstructions(const ossimString& releasingInstructions); virtual void setClassificationAuthority(const ossimString& classAuth); virtual void setSecurityControlNumber(const ossimString& controlNo); virtual void setOriginatorsName(const ossimString& originatorName); virtual void setOriginatorsPhone(const ossimString& origniatorPhone); virtual ossimString getCodeWords()const; virtual ossimString getControlAndHandling()const; virtual ossimString getReleasingInstructions()const; virtual ossimString getClassificationAuthority()const; virtual ossimString getSecurityControlNumber()const; virtual ossimString getOriginatorsName()const; virtual ossimString getOriginatorsPhone()const; /** * isValid will test if the fields are valid and will return true or false. */ virtual bool isValid()const; ossimString getComplianceLevel()const; ossimString getSecurityDowngrade()const; ossimString getDowngradingEvent()const; void setComplianceLevel(const ossimString& complianceLevel); void setSecurityDowngrade(const ossimString& securityDowngrade); void setDowngradingEvent(const ossimString& downgradeEvent); virtual void setFileLength(ossim_uint64 fileLength); virtual void setHeaderLength(ossim_uint64 headerLength); /** * Properties of a NITF 2.0 Header file. See MIL-STD-2500A for details. * * To access these, pass the constant to getProperty(). */ static const ossimString FSDWNG_KW; static const ossimString FSDEVT_KW; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; TYPE_DATA private: struct ossimNitfDisplayInfo { public: ossimNitfDisplayInfo(const ossimString &filePartType, ossim_int32 displayLevel, ossim_int32 indexIntoList) :theFilePartType(filePartType), theDisplayLevel(displayLevel), theIndex(indexIntoList) { } /*! * Since NITF already has unique ids for the file * part types we will just use them. * * IM indicates image part * LA indicates a label part * SY indicates a symbol part */ ossimString theFilePartType; /*! * This is the display level of the renderable data. Note the * display level is like a painters algorithm. The lowest level * is drawn first followed by the next level. */ ossim_int32 theDisplayLevel; /*! * This is an index into the array that has all the offsets * pre-computed. */ ossim_int32 theIndex; }; void clearFields(); /** * Sets the number of image records in the NITF 2.0 File Header. * * @param num * The number of image records for the entire NITF 2.0 file. * * @throw std::out_of_range */ void setNumberOfImageInfoRecords(ossim_uint64 num); /*! * This method will be used to setup information about the file. * Example: NITF files have display levels where the lowest number is the * back most image and the highes number is the front most image. We * are not guranteed that they will be in order in the file so we must * parse the file and sort the images. The images include image data, * symbols and labels. Each of these are renderable. The lowest * display level should have the larges rect and this will be used * to send back to the user an image rect. During rasterization we must * know the order to draw the data. */ void precomputeValues(); void readImageInfoRecords(ossim::istream& in); void readSymbolInfoRecords(ossim::istream& in); void readLabelInfoRecords(ossim::istream& in); void readTextFileInfoRecords(ossim::istream& in); void readDataExtSegInfoRecords(ossim::istream& in); void readResExtSegInfoRecords(ossim::istream& in); /*! * If the header was parsed this method will initialize the offsets * to whare all data resides within the file. Example: NITF files * have several sections (Image, Symbol, Labels, Text and Extended data) and * each of these sections have subsections. The offsets stored are just offsets * from the start of the file to each major section and eqach subsection. */ void initializeAllOffsets(); /*! * If the header was parsed and the offsets have been initialized, this method will * parse all overflow tags and put them into theTagList. */ void readOverflowTags(ossim::istream& in); /*! * This method will be called after the header is read * in and the offsets have been initialized. It will * sort in order all renderable data based on their * display level. */ void initializeDisplayLevels(ossim::istream& in); void insertIntoDisplayInfoList(const ossimNitfDisplayInfo &displayInformation); /*! * This is the current file we are operating on. */ ossimFilename theFilename; /*! * This will be pre-computed when the header file is opened. This is computed * after we have found the display order. We will use the rectangle of the * smallest display number. */ ossimDrect theImageRect; /*! * This will hold some pre-computed information about the display * order of the images. It will be populated by scanning the * file and sorting display levels. */ std::vector theDisplayInformationList; /*! * This will hold pre-computed offsets to the start of all image headers * and start to their data. */ std::vector theImageOffsetList; /*! * This will hold pre-computed offsets to the start of all symbol headers * and start to their data. */ std::vector theSymbolOffsetList; /*! * This will hold pre-computed offsets to the start of all Label headers * and start to their data. */ std::vector theLabelOffsetList; /*! * This will hold pre-computed offsets to the start of all text headers * and start to their data. */ std::vector theTextOffsetList; /*! * This will hold pre-coputed offsets to the start of all the data * extension segments. */ std::vector theDataExtSegOffsetList; // Note: these are work variables and not part of the // ossimNitf header. These variables will be used to quickly // access various parts of the file. /*! * This is not part of the NITF file header. This will be * computed since somethimes the header size will not be * given in the header field. This value will hold a count of * all the bytes read for the header portion. This can be used * to skip past the header data. */ ossim_int32 theHeaderSize; /*! * FSCODE: This is a 40 byte Alphanumeric field */ char theCodewords[41]; /*! * FSCTLH: This is a 40 byte Alphanumeric field. */ char theControlAndHandling[41]; /*! * FSREL: This is a 40 byte Alphanumeric field. */ char theReleasingInstructions[41]; /*! * FSCAUT: This is a 20 byte alphanumeric field. */ char theClassificationAuthority[21]; /*! * FSCTLN: This is a 20 byte Alphanumeric field. */ char theSecurityControlNumber[21]; /*! * FSDWNG: * * This is a 6 byte Alphanumeric. If this field * is not blank then it will have the form: * * YYMMDD * * Where YY is the last 2 chars of the year and will be * 00 to 59 represents 2000 to 2059 * 60 to 99 represents 1960 to 1999 * * * if the field is 999999 then the Originating agency field * is required. If te field is 999998 then the downgrade event * is required */ char theSecurityDowngrade[7]; /** * FSDEVT: * This is a conditional field and is a 40 byte * Alphanumeric field. This field exists if the * security downgrade is 999998. */ char theDowngradingEvent[41]; /** * ONAME: * * This is a 27 byte Alphanumeric number */ char theOriginatorsName[28]; /*! * OPHONE: * This is an 18 byte Alphanumeric value. */ char theOriginatorsPhone[19]; /*! * FL: * * This is a required field. * * Is a 12 byte number of the form * 000000000388-999999999998 indicates the * file length and a value of 999999999999 * indicates that the file length was not * available. */ char theFileLength[13]; /** * HL: * * This is a reqired field. * * Will hold the header length. The values * range up to 999998 and a value of * 999999 indicates that the length of the * header was not available upon creation. */ char theHeaderLength[7]; /** * NUMI: * * This is a 3 byte field that specifies the number * of images in the file. 0-999 */ char theNumberOfImageInfoRecords[4]; /*! * This information is conditional on the number of image * info records field. If the field is greater than 0 then * the record information is read in up to the indicated number */ std::vector theNitfImageInfoRecords; /*! * This is a 3 byte numeric 0-999. */ char theNumberOfSymbolInfoRecords[4]; /*! * This information is conditional on the number of symbol * info records field. If the field is greater than 0 then * the record information is read in up to the indicated number */ std::vector theNitfSymbolInfoRecords; /** * NUML * * This is a 3 byte numeric 0-999. */ char theNumberOfLabelInfoRecords[4]; /*! * This information is conditional on the number of label * info records field. If the field is greater than 0 then * the record information is read in up to the indicated number */ std::vector theNitfLabelInfoRecords; /** * NUMT: * * This is a 3 byte numeric 0-999. */ char theNumberOfTextFileInfoRecords[4]; /*! * This information is conditional on the number of text file * info records field. If the field is greater than 0 then * the record information is read in up to the indicated number */ std::vector theNitfTextInfoRecords; /** * NUMDES: * * This is a 3 byte numeric 0-999. */ char theNumberOfDataExtSegInfoRecords[4]; /*! * This information is conditional on the number of * info records field. If the field is greater than 0 then * the record information is read in up to the indicated number */ std::vector theNitfDataExtSegInfoRecords; /** * NUMRES: * * This is a 3 byte numeric 0-999. Reserved Extension Segments */ char theNumberOfResExtSegInfoRecords[4]; /*! * This information is conditional on the number of Res Ext Seg * info records field. If the field is greater than 0 then * the record information is read in up to the indicated number */ std::vector theNitfResExtSegInfoRecords; /** * UDHDL: * * This is a required field and is a 5 byte numeric ranging * from 0-99999. This is 0 if there is no data. */ char theUserDefinedHeaderDataLength[6]; /*! * This is a conditional field. It will exist if the * user defined header length is not 0. If it exists * then it may contain an overflow into one of the data * extension segments above and will hold the number of that * segment. */ char theUserDefinedHeaderOverflow[4]; /** * XHDL: * * This is a required field. It is 5 bytes long and * ranges from 0-99999. 0 means there is no data */ char theExtendedHeaderDataLength[6]; /*! * This is a required field. It is 5 bytes long and * ranges from 0-99999. 0 means there is no data */ char theExtendedHeaderOverflow[4]; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfFileHeaderV2_1.h000066400000000000000000000466631352751253100257010ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfFileHeaderV2_1_HEADER #define ossimNitfFileHeaderV2_1_HEADER 1 #include #include #include #include class OSSIMDLLEXPORT ossimNitfImageInfoRecordV2_1 { public: friend std::ostream& operator <<(std::ostream& out, const ossimNitfImageInfoRecordV2_1 &data); ossim_uint64 getHeaderLength()const; ossim_uint64 getImageLength()const; ossim_uint64 getTotalLength()const; void setSubheaderLength(ossim_uint32 length); void setImageLength(ossim_uint64 length); /** * Is a 6 byte numeric 000439-999999 */ char theImageSubheaderLength[7]; /** * Is a 10 byte numeric 0000000001-9999999999 */ char theImageLength[11]; }; struct ossimNitfGraphicInfoRecordV2_1 { public: friend std::ostream& operator <<(std::ostream& out, const ossimNitfGraphicInfoRecordV2_1 &data); ossim_uint64 getHeaderLength()const; ossim_uint64 getGraphicLength()const; ossim_uint64 getTotalLength()const; /** * Is a 4 byte numeric 0258-9999 */ char theGraphicSubheaderLength[5]; /** * Is a 6 byte numeric 0000001-9999999 */ char theGraphicLength[7]; }; class OSSIMDLLEXPORT ossimNitfTextFileInfoRecordV2_1 { public: friend std::ostream& operator<<(std::ostream& out, const ossimNitfTextFileInfoRecordV2_1 &data); ossim_uint64 getHeaderLength()const; ossim_uint64 getTextLength()const; ossim_uint64 getTotalLength()const; void setSubheaderLength(ossim_uint64 length); void setTextLength(ossim_uint64 length); /** * Is a 4 byte numeric 0282-9999 */ char theTextFileSubheaderLength[5]; /** * Is a 5 byte numeric 0-99999 */ char theTextFileLength[6]; }; struct ossimNitfDataExtSegInfoRecordV2_1 { public: friend std::ostream& operator<<(std::ostream& out, const ossimNitfDataExtSegInfoRecordV2_1 &data); ossim_uint64 getHeaderLength()const; ossim_uint64 getDataExtSegLength()const; ossim_uint64 getTotalLength()const; /** * Is a 4 byte numeric 200-9999 */ char theDataExtSegSubheaderLength[5]; /** * Is a 9 byte numeric 0-999999999 */ char theDataExtSegLength[10]; }; struct ossimNitfResExtSegInfoRecordV2_1 { public: friend std::ostream& operator<<(std::ostream& out, const ossimNitfResExtSegInfoRecordV2_1 &data); ossim_uint64 getHeaderLength()const; ossim_uint64 getResExtSegLength()const; ossim_uint64 getTotalLength()const; /** * Is a 4 byte numeric 0-9999 */ char theResExtSegSubheaderLength[5]; /** * Is a 7 byte numeric 0-9999999 */ char theResExtSegLength[8]; }; class OSSIMDLLEXPORT ossimNitfFileHeaderV2_1 : public ossimNitfFileHeaderV2_X { public: ossimNitfFileHeaderV2_1(); virtual ~ossimNitfFileHeaderV2_1(); virtual void parseStream(ossim::istream& in); virtual void writeStream(ossim::ostream& out); virtual bool isEncrypted()const; virtual ossim_int32 getNumberOfImages()const; virtual ossim_int32 getNumberOfLabels()const; virtual ossim_int32 getNumberOfSymbols()const; virtual ossim_int32 getNumberOfGraphics()const; virtual ossim_int32 getNumberOfTextSegments()const; virtual ossim_int32 getNumberOfDataExtSegments()const; virtual ossim_int32 getNumberOfReservedExtSegments()const; virtual ossim_int32 getHeaderSize()const; virtual ossim_int64 getFileSize()const; virtual const char* getVersion()const; virtual const char* getDateTime()const; virtual ossimDrect getImageRect()const; virtual void addImageInfoRecord(const ossimNitfImageInfoRecordV2_1& recordInfo); virtual void deleteLastImageInfoRecord(); virtual void deleteLastDataExtSegInfoRecord(); virtual void addTextInfoRecord(const ossimNitfTextFileInfoRecordV2_1& recordInfo); virtual void addDataExtSegInfoRecord(const ossimNitfDataExtSegInfoRecordV2_1& recordInfo); virtual void replaceImageInfoRecord(int i, const ossimNitfImageInfoRecordV2_1& recordInfo); virtual ossimNitfImageHeader* getNewImageHeader(ossim_uint32 imageNumber, ossim::istream& in)const; virtual ossimNitfSymbolHeader* getNewSymbolHeader(ossim_uint32 symbolNumber, ossim::istream& in)const; virtual ossimNitfLabelHeader* getNewLabelHeader(ossim_uint32 labelNumber, ossim::istream& in)const; virtual ossimNitfTextHeader* getNewTextHeader(ossim_uint32 textNumber, ossim::istream& in)const; virtual ossimNitfDataExtensionSegment* getNewDataExtensionSegment( ossim_int32 dataExtNumber, ossim::istream& in)const; virtual ossimNitfImageHeader* allocateImageHeader()const; virtual ossimNitfSymbolHeader* allocateSymbolHeader()const; virtual ossimNitfLabelHeader* allocateLabelHeader()const; virtual ossimNitfTextHeader* allocateTextHeader()const; virtual ossimNitfDataExtensionSegment *allocateDataExtSegment()const; virtual ossimString getSecurityClassificationSys()const; virtual ossimString getCodeWords()const; virtual ossimString getControlAndHandling()const; virtual ossimString getReleasingInstructions()const; virtual ossimString getDeclassificationType()const; virtual ossimString getDeclassificationDate()const; virtual ossimString getDeclassificationExemption()const; virtual ossimString getDowngrade()const; virtual ossimString getDowngradingDate()const; virtual ossimString getClassificationText()const; virtual ossimString getClassificationAuthorityType()const; virtual ossimString getClassificationAuthority()const; virtual ossimString getClassificationReason()const; virtual ossimString getSecuritySourceDate()const; virtual ossimString getSecurityControlNumber()const; virtual void getBackgroundColor(ossim_uint8& r, ossim_uint8& g, ossim_uint8& b)const; virtual ossimString getOriginatorsName()const; virtual ossimString getOriginatorsPhone()const; virtual void setFileLength(ossim_uint64 fileLength); virtual void setHeaderLength(ossim_uint64 headerLength); virtual void setSecurityClassificationSys(const ossimString& value); virtual void setCodeWords(const ossimString& codeWords); virtual void setControlAndHandling(const ossimString& controlAndHandling); virtual void setReleasingInstructions(const ossimString& releasingInstructions); virtual void setDeclassificationType(const ossimString& declassType); virtual void setDeclassificationDate(const ossimLocalTm& declassDate); virtual void setDeclassificationDate(const ossimString& declassDate); virtual void setDeclassificationExemption(const ossimString& exemption); virtual void setDowngrade(const ossimString& downgrade); virtual void setDowngradingDate(const ossimLocalTm& date); virtual void setDowngradingDate(const ossimString& date); virtual void setClassificationText(const ossimString& classificationText); virtual void setClassificationAuthorityType(const ossimString& authorityType); virtual void setClassificationAuthority(const ossimString& authorityType); virtual void setClassificationReason(const ossimString& reason); virtual void setSecuritySourceDate(const ossimLocalTm& date); virtual void setSecuritySourceDate(const ossimString& date); virtual void setSecurityControlNumber(const ossimString& number); virtual void setFileBackgroundColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b); virtual void setOriginatorsName(const ossimString& name); virtual void setOriginatorsPhone(const ossimString& phone); virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * isValid will test if the fields are valid and will return true or false. */ virtual bool isValid()const; /*! * @brief Method to set fields from a keyword list. * * This is not a true loadState as it does not lookup/initialize all class * members. This was added to allow defaults, e.g OSTAID, to be set via a * site configuration file. * Code does not return false if a field(key) is not found.. * * @return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; /** * Properties of a NITF 2.1 Header file. See MIL-STD-2500B for details. * * To access these, pass the constant to getProperty(). */ static const ossimString FSCLSY_KW; static const ossimString FSDCTP_KW; static const ossimString FSDCDT_KW; static const ossimString FSDCXM_KW; static const ossimString FSDG_KW; static const ossimString FSDGDT_KW; static const ossimString FSCLTX_KW; static const ossimString FSCATP_KW; static const ossimString FSCRSN_KW; static const ossimString FSSRDT_KW; static const ossimString FBKGC_KW; void clearFields(); void addTag(ossimNitfTagInformation tag, bool unique = true); void removeTag(const ossimString& tagName); bool takeOverflowTags(std::vector &overflowTags, ossim_uint32 potentialDesIndex, bool userDefinedTags = false); /** * @brief print method that outputs a key/value type format adding prefix * to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; private: /** * Sets the number of image records in the NITF 2.1 File Header. * * @param num * The number of image records for the entire NITF 2.1 file. * * @throw std::out_of_range */ void setNumberOfImageInfoRecords(ossim_uint64 num); void setNumberOfTextInfoRecords(ossim_uint64 num); void setNumberOfGraphicInfoRecords(ossim_uint64 num); void setNumberOfDataExtSegInfoRecords(ossim_uint64 num); void readImageInfoRecords(ossim::istream& in); void readGraphicInfoRecords(ossim::istream& in); void readTextFileInfoRecords(ossim::istream& in); void readDataExtSegInfoRecords(ossim::istream& in); void readResExtSegInfoRecords(ossim::istream& in); /** * If the header was parsed this method will initialize the offsets * to whare all data resides within the file. Example: NITF files * have several sections (Image, Symbol, Labels, Text and Extended data) and * each of these sections have subsections. The offsets stored are just offsets * from the start of the file to each major section and eqach subsection. */ void initializeAllOffsets(); /** * If the header was parsed and the offsets have been initialized, this method will * parse all overflow tags and put them into theTagList. */ void readOverflowTags(ossim::istream& in); void readDes(std::istream& in); // Note: these are work variables and not part of the // Nitf header. These variables will be used to quickly // access various parts of the file. /** * This is not part of the NITF file header. This will be * computed since somethimes the header size will not be * given in the header field. This value will hold a count of * all the bytes read for the header portion. This can be used * to skip past the header data. */ ossim_uint32 theHeaderSize; /** * This will be pre-computed when the header file is opened. This is * computed after we have found the display order. We will use the * rectangle of the smallest display number. */ ossimDrect theImageRect; /** * This will hold pre-computed offsets to the start of all image headers * and start to their data. */ std::vector theImageOffsetList; std::vector theGraphicOffsetList; std::vector theTextFileOffsetList; std::vector theDataExtSegOffsetList; // START Of header variables /** * Field: FSCLSY * * Is a 2 byte field. Required but can be blank: * */ char theSecurityClassificationSys[3]; /** * Field: FSCODE * * This is a 11 byte Alphanumeric field */ char theCodewords[12]; /** * Field: FSCTLH * * This is a 2 byte Alphanumeric field. */ char theControlAndHandling[3]; /** * Field: FSREL * * This is a 20 byte Alphanumeric field. */ char theReleasingInstructions[21]; /** * Field: FSDCTP * * This is a 2 byte alphanumeric field. * * DD declassify on a specific date * DE declassify upon occurrence of an event * GD downgrade to a specified level on a specific date) * GE downgrade to a specified level upon occurrence of an event) * O OADR * X exempt from automatic declassification * * NOTE: If this field is all BCS spaces (0x20), it shall imply that no * file security declassification or */ char theDeclassificationType[3]; /** * Field: FSDCDT * * This is a 8 byte field and has the form * CCYYMMDD where: * * CC is the firs 2 chars of the year 00-99 * YY is the second 2 chars of the year 00-99 * MM is the month 01-12 * DD is the day 01-31 */ char theDeclassificationDate[9]; /** * Field: FSDCXM * * Is a 4 byte field */ char theDeclassificationExemption[5]; /** * Field: FSDG * * Can be blank. Is a 1 byte field valid * values are: * * S = secret * C = Confidential * R = Restricted * 0x20 or BCS spaces. * * if spaces then security downgrading does not apply. */ char theDowngrade[2]; /** * Field: FSDGDT * * Is an 8 byte field of the form * CCYYMMDD. */ char theDowngradingDate[9]; /** * Field: FSCLTX * * Is a 43 byte field and can contain BCS spaces (0x20). */ char theClassificationText[44]; /** * Field: FSCATP * * Values can be: * * O Original classification authority * D derivative from a single source * M derivative from multiple sources * * Is a 1 byte field and can contain BCS spaces (0x20). */ char theClassificationAuthorityType[2]; /** * Field: FSCAUT * * Is a 40 byte field and can contain BCS spaces (0x20). */ char theClassificationAuthority[41]; /** * Field: FSCRSN * * Is a 1 byte field and can contain BCS spaces (0x20). * * Valid values are A-G */ char theClassificationReason[2]; /** * Field: FSSRDT * * Is a 8 byte field of the form CCYYMMDD and can be * BCS space (0x20). */ char theSecuritySourceDate[9]; /** * Field: FSCTLN * * Is a 15 byte field and can be blank (0x20) */ char theSecurityControlNumber[16]; /** * Field: FBKGC * * Required. Is a 3 byte field and is reuqired. Note: This * field is binary and has range * * (0x00-0xff, 0x00-0xff, 0x00-0xff) * * each byte can range from 0 to 255 binary */ ossim_uint8 theFileBackgroundColor[3]; /** * Field: ONAME * * This is a 24 byte Alphanumeric number */ char theOriginatorsName[25]; /** * Field: OPHONE * * This is an 18 byte Alphanumeric value. */ char theOriginatorsPhone[19]; /** * Field: FL * * This is a required field. * * Is a 12 byte number of the form * 000000000388-999999999998 indicates the * file length and a value of 999999999999 * indicates that the file length was not * available. */ char theFileLength[13]; /** * Field: HL * * This is a reqired field. * * ranges from 000388-999999. */ char theHeaderLength[7]; /** * Field: NUMI * * This is a 3 byte field that specifies the number * of images in the file. 0-999 */ char theNumberOfImageInfoRecords[4]; /** * This information is conditional on the number of image * info records field. If the filed is greater than 0 then * the record information is read in up t the indicated number */ std::vector theNitfImageInfoRecords; /** * Field: NUMS * * This info is required and ranges from 000-999. */ char theNumberOfGraphicInfoRecords[4]; /** * This is an optional field and will depend on * theNumberOfGraphicInfoRecords. If 0 then does not exist. */ std::vector theNitfGraphicInfoRecords; /** * Field: NUMX * * Is a 3 byte field and is reserved for future use. */ char theReservedForFutureUse1[4]; /** * Field: NUMT * * This is a 3 byte numeric 0-999. */ char theNumberOfTextFileInfoRecords[4]; /** * This information is conditional on the number of text file * info records field. If the filed is greater than 0 then * the record information is read in up t the indicated number */ std::vector theNitfTextFileInfoRecords; /** * Field: NUMDES * * This is a 3 byte numeric 0-999. */ char theNumberOfDataExtSegInfoRecords[4]; /** * This information is conditional on the number of * info records field. If the filed is greater than 0 then * the record information is read in up t the indicated number */ std::vector theNitfDataExtSegInfoRecords; /** * Field: NUMRES * * This is a 3 byte numeric 0-999. Reserved Extension Segments */ char theNumberOfResExtSegInfoRecords[4]; /** * This information is conditional on the number of Res Ext Seg * info records field. If the filed is greater than 0 then * the record information is read in up t the indicated number */ std::vector theNitfResExtSegInfoRecords; /** * Field: UDHDL * * This is a required field and is a 5 byte numeric ranging * from 0-99999. This is 0 if there is no data. Valid values * are 00000 or 00003-99999 */ char theUserDefinedHeaderDataLength[6]; /** * Field: UDHOFL * * This exists if theUserDefinedHeaderDataLength is not 0. */ char theUserDefinedHeaderOverflow[4]; /** * Field: XHDL * * This is a required field. It is 5 bytes long and * ranges from 0-99999. 0 means there is no data */ char theExtendedHeaderDataLength[6]; /** * Field: XHDLOFL * * This is conditional on theExtendedHeaderDataLength. If * that field is 0 then this does not exist. This is a 3 * byte field. */ char theExtendedHeaderDataOverflow[4]; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfFileHeaderV2_X.h000066400000000000000000000166521352751253100257430ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimNitfFileHeaderV2_X_HEADER #define ossimNitfFileHeaderV2_X_HEADER 1 #include #include class ossimKeywordlist; class ossimLocalTm; class OSSIM_DLL ossimNitfFileHeaderV2_X : public ossimNitfFileHeader { public: ossimNitfFileHeaderV2_X(); static ossimString formatDate(const ossimString& version, const ossimLocalTm& d); virtual void setCodeWords(const ossimString& codeWords) = 0; virtual void setControlAndHandling(const ossimString& controlAndHandling) = 0; virtual void setReleasingInstructions(const ossimString& releasingInstructions) = 0; virtual void setClassificationAuthority(const ossimString& classAuth) = 0; virtual void setSecurityControlNumber(const ossimString& controlNo) = 0; virtual void setOriginatorsName(const ossimString& originatorName) = 0; virtual void setOriginatorsPhone(const ossimString& origniatorPhone) = 0; virtual ossimString getCodeWords()const = 0; virtual ossimString getControlAndHandling()const = 0; virtual ossimString getReleasingInstructions()const = 0; virtual ossimString getClassificationAuthority()const = 0; virtual ossimString getSecurityControlNumber()const = 0; virtual ossimString getOriginatorsName()const = 0; virtual ossimString getOriginatorsPhone()const = 0; virtual ossimString getSecurityClassification()const; void setComplexityLevel(const ossimString& level); void setSystemType(const ossimString& systemType); void setOriginatingStationId(const ossimString& originationId); /** * @brief Sets field FDT. * * Version 2.0 format: DDHHMMSSZMONYY * Version 2.1 format: CCYYMMDDhhmmss * * @param ossimLocalTm Local time. Note that this will be converted to * GMT(ZULU). */ void setDate(const ossimLocalTm& d); /** * @brief Sets field FDT. * * @param d Date string to copy to FDT field. * * @note No conversions performed. */ void setDate(const ossimString& d); /** * @brief Sets field FDT to current time converted to GMT(ZULU). * * Version 2.0 format: DDHHMMSSZMONYY * Version 2.1 format: CCYYMMDDhhmmss */ virtual void setDate(); void setTitle(const ossimString& title); void setFileSecurityClassification(const ossimString& securityClassification); void setCopyNumber(const ossimString& copyNumber); void setNumberOfCopies(const ossimString& numberOfCopies); void setEncryption(const ossimString& encryption); ossimString getComplexityLevel()const; ossimString getSystemType()const; ossimString getOriginatingStationId()const; ossimString getDate()const; ossimString getTitle()const; ossimString getCopyNumber()const; ossimString getNumberOfCopies()const; ossimString getEncryption()const; /** * isValid will test if the fields are valid and will return true or false. */ virtual bool isValid()const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; /*! * @brief Method to set fields from a keyword list. * * This is not a true loadState as it does not lookup/initialize all class * members. This was added to allow defaults, e.g OSTAID, to be set via a * site configuration file. * Code does not return false if a field(key) is not found.. * * @return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /** * Properties of a NITF 2.x Header file. See MIL-STD-2500A or * MIL-STD-2500B for details. * * To access these, pass the constant to getProperty(). */ static const ossimString FILE_TYPE_KW; static const ossimString FHDR_KW; static const ossimString VERSION_KW; static const ossimString CLEVEL_KW; static const ossimString STYPE_KW; static const ossimString OSTAID_KW; static const ossimString FDT_KW; static const ossimString FTITLE_KW; static const ossimString FSCLAS_KW; static const ossimString FSCODE_KW; static const ossimString FSCTLH_KW; static const ossimString FSREL_KW; static const ossimString FSCAUT_KW; static const ossimString FSCTLN_KW; static const ossimString FSCOP_KW; static const ossimString FSCPYS_KW; static const ossimString ENCRYP_KW; static const ossimString ONAME_KW; static const ossimString OPHONE_KW; protected: /** * Field: FHDR * Required field for NITF and is a 9 byte value * * format is NITFNN.NN where NN.NN is the version * number. The valid version number for this class * is NITF02.10. * * NOTE: This field may contain NSIF01.00 which is also the same as NITF02.10 * */ char theFileTypeVersion[10]; // nine bytes /** * Field: CLEVEL * * Required field. 2 byte field ranges from 01-99 */ char theComplexityLevel[3]; // 2 bytes /** * Field: STYPE * * Required field. 4 bytes */ char theSystemType[5]; // four bytes /** * Field: OSTAID * * Is required 10 byte field and can't be blank * */ char theOriginatingStationId[11]; // ten bytes /** * Field: FDT * * for NITF 2.1 format we have * * Has the form CCYYMMDDhhmmss and is a required field * * where CC is the first two digits of the year 00-99 * YY is the last 2 digits of the year 00-99 * MM is the month 01-12 * DD is the day 01-31 * hh is the hour 00-23 * mm is the minutes 00-59 * ss is the seconds 00-59 * * For NITF 2.0 format we have * * DDHHMMSSZMONYY * * where DD is the day * HH is the hour * MM is the minutes * SS is the seconds * MON is the first 3 characters of the month * YY is the 2 digit year */ char theDateTime[15]; // 14 bytes /** * Field: FTITLE * * Is a required field and is an 80 byte * Alphanumeric value this can be all BCS spaces. */ char theFileTitle[81]; // 80 bytes /** * Field: FSCLAS * * This is a reqired field and is 1 byte long and * can contain one of the following: * * T Top secret * S Secret * C Confidential * R Restricted * U Unclassified */ char theSecurityClassification[2]; /** * Field: FSCOP * * This is the copy number and is a 5 byte * numeric of the form 00000-99999. This field * is required. */ char theCopyNumber[6]; /** * Field: FSCOPYS * * This is the total number of copies that exist. * This is a 5 byte numeric of the form 00000-99999. This * field is required. */ char theNumberOfCopies[6]; /** * Field: ENCRYP * * This is a reqired field and is a 1 byte numeric * where 0 is not encrypted and 1 is encrypted. This field * is reuqired. */ char theEncryption[2]; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfGeoPositioningTag.h000066400000000000000000000143771352751253100266470ustar00rootroot00000000000000//******************************************************************** // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // // Documentation reference: // DIGEST Part 2 Annex D - Appendix 1, Table D1-3 // //******************************************************************** // $Id: ossimNitfGeoPositioningTag.h 22013 2012-12-19 17:37:20Z dburken $ // #ifndef ossimNitfGeoPositioningTag_HEADER #define ossimNitfGeoPositioningTag_HEADER 1 #include class OSSIM_DLL ossimNitfGeoPositioningTag : public ossimNitfRegisteredTag { public: ossimNitfGeoPositioningTag(); virtual ~ossimNitfGeoPositioningTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; protected: /** * FIELD: TYP * * required 3 byte field. * * Coordinate System Type * * This field shall contain the type of coordinate system to which the Image * Segment refers. Valid values are GEO for a geographic coordinate * system (longitude & latitude), MAP for a cartographic (grid) * coordinate system (easting & northing) and DIG for a geographic or * cartographic coordinate system registered through location grids or * registration points. * See clause D1.2.2 for details. * The default value is MAP. * * * Values: MAP, GEO or DIG */ char theType[4]; /** * FIELD: UNI * * required 3 byte field. * * Coordinate Units This field shall contain the units of measure to which * the Image Segment refers. Valid values are SEC (Decimal seconds of arc), * DEG (Decimal degrees) and M (Metres). The value must be consistent with * the coordinate system type. SEC and DEG are not allowed when the * coordinate system type is MAP. M is not allowed when the coordinate system * type is GEO. The PRJPS extension is expected when the value is M. * The default value is M. */ char theCoordinateUnits[4]; /** * FIELD: DAG * * required 80 byte field. * * Geodetic Datum Name * * This field shall contain the name of the geodetic datum to which the * Image Segment refers. * The default value is World Geodetic System 1984. * */ char theGeodeticDatumName[81]; /** * FIELD: DCD * * required 4 byte field. * * Geodetic Datum Code This field shall contain the code of the geodetic * datum to which the Image Segment refers. The default value is WGE. * */ char theGeodeticDatumCode[5]; /** * FIELD: ELL * * required 80 byte field. * * Ellipsoid Name * * This field shall contain the name of the ellipsoid to which the * Image Segment refers. The default value is World Geodetic System 1984. * */ char theEllipsoidName[81]; /** * FIELD: ELC * * required 3 byte field. * * Ellipsoid Code This field shall contain the code of the ellipsoid to * which the Image Segment refers. * The default value is WE. * */ char theEllipsoidCode[4]; /** * FIELD: DVR * * required 80 byte field. * * Vertical Datum Reference This field shall contain the name of the vertical * datum reference to which the Image Segment refers, or BCS Spaces if no elevation value * appears in the Image Segment. The default name is Geodetic. */ char theVerticalDatumReference[81]; /** * FIELD: VDCDVR * * required 4 byte field. * * Code (Category) of Vertical Reference This field shall contain the code * (or category) of the vertical reference to which the Image Segment * refers, or BCS Spaces if no elevation value appears in the Image Segment. * The default code is GEOD. * */ char theVerticalReferenceCode[5]; /** * FIELD: SDA * * required 80 byte field. * * Sounding Datum Name This field shall contain the name of the sounding datum * to which the Image Segment refers, or BCS Spaces i * f no sounding appears in the Image Segment. * The default value is Mean Sea. */ char theSoundingDatumName[81]; /** * FIELD: VDCSDA * * required 4 byte field. * * Code for Sounding Datum This field shall contain the code of the * sounding datum to which the Image Segment refers, or BCS Spaces * if no sounding appears in the Image Segment. * The default valid code is MSL. 4BCS-A See Part 3-6 */ char theSoundingDatumCode[5]; /** * FIELD ZOR * * required 15 byte field * * Z values False Origin * * This field shall contain the elevation and depth false origin for Z values * to which the Image Segment refers. The default value is 000000000000000, * which implies that there is no projection false Z origin. 15 BCS-N positive integer * */ char theZFalseOrigin[16]; /** * FIELD: GRD * * required 3 byte field. * * Grid Code This field shall contain the identification code of the grid system * to which the Image Segment refers, or BCS Spaces. The default value is * BCS Spaces. 3BCS-A See Part 3-6 */ char theGridCode[4]; /** * FIELD: GRN * * required 80 byte field. * * Grid Description If the GRD Field value is not BCS Spaces, this field can * contain a text description of the grid system. * The default value is BCS Spaces. 80 BCS-A */ char theGridDescription[81]; /** * FIELD: ZNA * * required 4 byte field. * * Grid Zone number This field shall contain the zone number when the GRD * Field contains a significant grid code and the corresponding grid system * comprises more than one zone. Defaulted to 0000 otherwise. * 4 BCS-N integer See Part 3-6 R */ char theGridZoneNumber[5]; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfGeolobTag.h000066400000000000000000000112311352751253100251030ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: GEOLOB tag class declaration. // // References: // // 1) DIGEST 2.1 Part 2 - Annex D // Appendix 1 - NSIF Standard Geospatial Support Data Extension // // 2) STDI-0006 //--- // $Id$ #ifndef ossimNitfGeolobTag_HEADER #define ossimNitfGeolobTag_HEADER 1 #include #include #include class OSSIM_DLL ossimNitfGeolobTag : public ossimNitfRegisteredTag { public: enum { ARV_SIZE = 9, BRV_SIZE = 9, LSO_SIZE = 15, PSO_SIZE = 15, TAG_SIZE = 48 // ----- // 48 }; /** default constructor */ ossimNitfGeolobTag(); /** * Parse method. * * @param in Stream to parse. */ virtual void parseStream(ossim::istream& in); /** * Write method. * * @param out Stream to write to. */ virtual void writeStream(ossim::ostream& out); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; /** * @brief Gets the ARV field. * * Longitude density: * This field shall contain the pixel ground spacing in E/W direction that * is the number of pixels or elements intervals in 360° * * Pixel size in decimal degree = 360.0 / AVR * * @return ARV field as a string. */ std::string getArvString() const; /** * @brief Gets the ARV field. * @return ARV field as a positive integer. **/ ossim_uint32 getArv() const; /** * @brief Gets degrees per pixel in lonitude direction from BRV field. * * Pixel size in decimal degree = 360.0 / AVR * * @return Degrees per pixel in lonitude direction. */ ossim_float64 getDegreesPerPixelLon() const; /** * @brief Sets the ARV field. Valid range: 000000002 to 999999999 * @pararm arv */ void setArv(ossim_uint32 arv); /** * @brief Sets the ARV field from decimal degrees per pixel longitude. * @pararm deltaLon */ void setDegreesPerPixelLon(const ossim_float64& deltaLon); /** * @brief Gets the BRV field. * * Latitude density: * This field shall contain the pixel ground spacing in N/S direction that * is the number of pixels or elements intervals in 360°. * * Pixel size in decimal degree = 360.0 / BVR * * @return BRV field as a string. */ std::string getBrvString() const; /** * @brief Gets the BRV field. * @return BRV field as a positive integer. **/ ossim_uint32 getBrv() const; /** * @brief Gets degrees per pixel in latitude direction from BRV field. * * Pixel size in decimal degree = 360.0 / BVR * * @return Degrees per pixel in latitude direction. */ ossim_float64 getDegreesPerPixelLat() const; /** * @brief Sets the BRV field. Valid range: 000000002 to 999999999 * @pararm brv */ void setBrv(ossim_uint32 brv); /** * @brief Sets the BRV field from decimal degrees per pixel latitude. * @pararm deltaLon */ void setDegreesPerPixelLat(const ossim_float64& deltaLat); /** * @brief Gets the LSO field. * * Longitude of Reference Origin: * This field shall contain the longitude of the origin pixel * (row number 0, column number 0) in the absolute coordinate system. * * @return LSO field as a string. */ std::string getLsoString() const; /** * @brief Gets the LSO field(Longitude Origin). * @return LSO field as a positive integer. **/ ossim_float64 getLso() const; /** * @brief Sets the LSO field(Longitude Origin). * Valid range: -180.0 to +180.0 * @pararm lso */ void setLso(const ossim_float64& lso); /** * @brief Gets the PSO field. * * Latitude of Reference Origin: * This field shall contain the latitude of the origin pixel * (row number 0, column number 0) in the absolute coordinate system. * * @return PSO field as a string. */ std::string getPsoString() const; /** * @brief Gets the PSO field(Latitude Origin). * @return PSO field as a positive integer. **/ ossim_float64 getPso() const; /** * @brief Sets the PSO field(Latitude Origin). * Valid range: -90.0 to +90.0 * @pararm pso */ void setPso(const ossim_float64& pso); protected: std::string m_tagData; TYPE_DATA }; #endif /* End of "#ifndef ossimNitfGeolobTag_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfHistoaTag.h000066400000000000000000001043011352751253100251240ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: HISTOA tag class declaration. // //---------------------------------------------------------------------------- // $Id: ossimNitfHistoaTag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfHistoaTag_HEADER #define ossimNitfHistoaTag_HEADER 1 #include #include /** * All comments in this document were taken from the online resource found at: * * http://www.gwg.nga.mil/ntb/baseline/docs/stdi0002/ * * Reference: HISTOA section (currently in Appendix L) * * The purpose of the Softcopy History Tagged Record Extension, HISTOA, is to * provide a history of the softcopy processing functions that have been applied to NSIF * imagery. It is meant to describe previous processing actions and the current state of the * imagery that was distributed within the intelligence and imagery user community. To be * effective, HISTOA needs to be applied to the NSIF product as early as practical and must * be updated each time the image is processed and saved by a softcopy processing system. * This will allow the user to know with confidence the complete history of the imagery. * HISTOA may be created as the NSIF image is created, or when the imagery is first * modified. */ class OSSIM_DLL ossimNitfHistoaProcessingEvent { public: enum { PDATE_SIZE = 14, PSITE_SIZE = 10, PAS_SIZE = 10, NIPCOM_SIZE = 1, IPCOM_SIZE = 80, IBPP_SIZE = 2, IPVTYPE_SIZE = 3, INBWC_SIZE = 10, DISP_FLAG_SIZE = 1, ROT_FLAG_SIZE = 1, ROT_ANGLE_SIZE = 8, ASYM_FLAG_SIZE = 1, ZOOMROW_SIZE = 7, ZOOMCOL_SIZE = 7, PROJ_FLAG_SIZE = 1, SHARP_FLAG_SIZE= 1, SHARPFAM_SIZE = 2, SHARPMEM_SIZE = 2, MAG_FLAG_SIZE = 1, MAG_LEVEL_SIZE = 7, DRA_FLAG_SIZE = 1, DRA_MULT_SIZE = 7, DRA_SUB_SIZE = 5, TTC_FLAG_SIZE = 1, TTCFAM_SIZE = 2, TTCMEM_SIZE = 2, DEVLUT_FLAG_SIZE = 1, OBPP_SIZE = 2, OPVTYPE_SIZE = 3, OUTBWC_SIZE = 10 }; ossimNitfHistoaProcessingEvent(); ossim_uint32 getSizeInBytes()const; void parseStream(std::istream& in); void writeStream(std::ostream& out); std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; void clearFields(); private: /** * Field: PDATE * * This field shall contain the date and time (UTC) on which the processing event occurred. The * valid form of the field is CCYYMMDDhhmmss, where CC is the first two digits of the year (00 * to 99), YY is the last two digits of the year (00 to 99), MM is the month (01 to 12), DD is * the day of the month (01 to 31), hh is the hour (00 to 23), mm is the minute (00 to 59), and * ss is the second (00 to 59). UTC (Zulu) is assumed to be the time zone designator to express * the time of day. This field can be used in conjunction with the FDT field in the NSIF file * header to determine if the History Tag has been updated each time the image was processed and * saved. If the PDATE field and the FDT field are identical, the History Tag has been properly * updated. If the fields are not identical, then the History Tag has not been properly updated * and the data may not be accurate or timely. */ char m_pdate[PDATE_SIZE+1]; /** * Field: PSITE * * This field shall contain the name of the site or segment that performed the processing event. * This 10 character alphanumeric field is free form text. Examples of PSITE entries are FOS, * JWAC, or CENTCOM. */ char m_psite[PSITE_SIZE+1]; /** * Field: PAS * * This field shall contain the processing application software used to perform the processing * steps cited in the event (e.g. IDEX, VITEC, or DIEPS). The version number of the application * would also be helpful to include in this field. */ char m_pas[PAS_SIZE+1]; /** * Field: NIPCOM * * This field shall contain the valid number of image processing comments for this processing * event. The valid field codes are 0 to 9. */ char m_nIpcom[NIPCOM_SIZE+1]; /** * Field IPCOM * * This field shall contain the first line of comment text. The fields IPCOM1 to IPCOMn, if * present shall contain free form alphanumeric text. They are intended for use as a single * comment block and shall be used that way. This field shall be omitted if the value in NIPCOM * field is zero. The comment field shall be used to clarify or indicate special processing not * accounted for in the Processing Event Fields. Reasons for populating this field would be to * vindicate alternate processing for multi-spectral imagery, to indicate the order of S/C * processing steps contained within a single processing event, or to inform downstream users of * potential problems with the image. */ std::vector m_comment; /** * Field: IBPP * * This field shall contain the number of significant bits for each pixel before the processing * functions denoted in the processing event have been performed and before compression. This * type of pixel depth description is consistent with the ABPP field within the NSIF image * subheader. For example, if an 11-bpp word is stored in 16 bits, this field would contain 11 and * the NBPP field in the NSIF image subheader would contain 16. The valid IBPP field codes are * 01 to 64, indicating 1 to 64 bpp. */ char m_ibpp[IBPP_SIZE+1]; /** * Field IPVTYPE * * This field shall contain an indicator of the type of computer representation used for the value * of each pixel before the processing functions denoted in the processing events have been * performed and before compression. Valid entries are INT for integer, SI for 2’s complement * signed integer, R for real, and C for complex. The databits of INT and SI values shall appear in * the file in order of significance, beginning with the most significant bit (MSB) and ending with * the least significant bit (LSB). INT and SI data types shall be limited to 16 bits. R values * shall be represented according to IEEE 32-bit floating-point representation (IEEE754). C values * shall be represented with the Real and Imaginary parts each represented in IEEE 32-bit floating * point representation (IEEE754) and appearing adjacent four-byte blocks, first Real, then * Imaginary. B (bi-level) pixel values shall be represented as single bits with value 1 or 0. */ char m_ipvType[IPVTYPE_SIZE+1]; /** * Field INBWC * * This field shall indicate the type of bandwidth compression or expansion that has been applied * to the image prior to any enhancements denoted in the processing event. The valid field codes to * describe each type of compression are 5 byte character strings. The first two characters * indicate the type of compression such as DCT or DPCM. The next two characters indicate either * the bit rate or the quality level. The last character indicates if the process is compression * or an expansion. Compression is denoted by a C, an E denotes expansion, and 0 indicates that * neither process occurred. The types of compression are indicated by the following codes: * Value Definition * DP43 DPCM (Differential Pulse Coded Modulation) – 4.3 bpp * DC13 DCT (Discrete Cosine Transform – 2.3 bpp * DC23 DCT (Discrete Cosine Transform) – 2.3 bpp * NJNL NSIF JPEG – Lossless * NJQ0 NSIF JPEG – Quality Level 0 * NJQ1 NSIF JPEG – Quality Level 1 * NJQ2 NSIF JPEG – Quality Level 2 * C11D NSIF Bi-level – 1D * C12S NSIF Bi-level – 2DS * C12H NSIF Bi-level – 2DH * M11D NSIF Bi-level – 1D * M12S NSIF Bi-level with masked blocks – 2DS * M12H NSIF Bi-level with masked blocks – 2DH * C207 NITF ARIDPCM – 0.75 bpp * C214 NITF ARIDPCM – 1.40 bpp * C223 NITF ARIDPCM – 2.30 bpp * C245 NITF ARIDPCM – 4.50 bpp * C3Q0 NSIF Lossy JPEG – Q0 Custom Tables * C3Q1 NSIF Lossy JPEG – Q1 Default Tables * C3Q2 NSIF Lossy JPEG – Q2 Default Tables * C3Q3 NSIF Lossy JPEG – Q2 Default Tables * C3Q4 NSIF Lossy JPEG – Q4 Default Tables * C3Q5 NSIF Lossy JPEG – Q5 Default Tables * M3Q0 NSIF Lossy JPEG with masked blocks – Q0 Custom * M3Q1 NSIF Lossy JPEG with masked blocks – Q1 Default * M3Q2 NSIF Lossy JPEG with masked blocks – Q2 Default * M3Q3 NSIF Lossy JPEG with masked blocks – Q3 Default * M3Q4 NSIF Lossy JPEG with masked blocks – Q4 Default * M3Q5 NSIF Lossy JPEG with masked blocks – Q5 Default * C4LO NSIF Vector Quantization – Lossy * M4LO NSIF Vector Quantization with masked blocks * C5NL NSIF Lossless JPEG * M5NL NSIF Lossless JPEG with masked blocks * NC00 NSIF uncompressed * NM00 NSIF with masked blocks uncompressed * I1Q1 NSIF Downsample JPEG – Q1 * I1Q2 NSIF Downsample JPEG – Q2 * I1Q3 NSIF Downsample JPEG – Q3 * I1Q4 NSIF Downsample JPEG – Q4 * I1Q5 NSIF Downsample JPEG – Q5 * WVLO Wavelet Lossy * WVNL Wavelet Lossless * JP20 JPEG 2000 * NONE No Compression * UNKC Unknown Compression * OTLO Unknown lossy compression – requires mandatory IPCOM entry to explain * technique or source * OTNL Unknown lossless compression – requires mandatory IPCOM entry to explain * technique or source * The entire BWC field is 10 bytes long to allow for the concatenation of up to 2 compression * algorithms. Two consecutive 5 byte character strings shall indicate the application of two * compression algorithms in succession. If only one operation is performed, then the remaining 5 * characters are zero. Examples of valid codes for the BWC field are shown below. * The DP43E00000 code indicates that a 4.3 DPCM compressed input image was expanded prior * to NSIF formation. * The DC13E00000 code indicates that 1.3 DCT compressed input image was expanded prior to * NSIF formation. * The NONE000000 code indicates that the input image to the NSIF formation process was * uncompressed. */ char m_inbwc[INBWC_SIZE+1]; /** * Field DISPLAY_FLAG * * This field shall indicate if the image is “Display-Ready.†The DISP_FLAG field applies only to * System B, System D, and certain other systems. Display-Ready data has had a system-specific * transformation applied to it that is described in appendix A. The valid field codes are 0 to 9 * and a blank (BCS 0x20). A value of 0 means that image is not Display-Ready and must be * converted to a displayable format, using the pre-defined mappings for Linlog or PEDF formats. * A value of 1 means that the image is Display-Ready and needs only basic tonal processing and * device compensation for corrects display. Since this field applies to Systems B and D imagery * currently, the field shall be filled with a blank (BCS 0x20) for all other system types. Values * 2 to 9 are reserved for future use and shall not be used at this time. A more detailed * explanation of the Display-Ready transformations is provided in appendix A. */ char m_dispFlag[DISP_FLAG_SIZE + 1]; /** * Field ROT_FLAG * * This field shall indicate if the image has been rotated. The valid field codes are 0 and 1. A * value or 0 means that the image has not been rotated. A value of 1 means that the image has been * rotated. If this field is equal to 1, then the ROT_ANGLE field must be filled with the angle of * rotation. */ char m_rotFlag[ROT_FLAG_SIZE + 1]; /** * Field: ROT_ANGLE * * This field shall contain the angel in degrees that the image has been rotated, where a positive * angle denotes clockwise rotation. The valid field codes are 000.0000 to 359.9999. This field is * conditional on the ROT_FLAG field being equal to 1. If the rotation has included an * interpolation, then the interpolation method shall be described in the comment sections. */ char m_rotAngle[ROT_ANGLE_SIZE + 1]; /** * Field: ASYM_FLAG * * This field shall indicate if asymmetric correction has been applied to the image. This * processing step is only allowed for certain types of EO processing. The valid field codes are * 0 and 1, and a blank (BCS 0x20). A value of 0 means that asymmetric correction has not been * applied to the image. A value of 1 means that asymmetric correction has been applied to the * image. Since this field applies only to certain types of EO imagery, this field shall be filled * with a blank (BCS 0x20) for all other system types. If this field is equal to 1, the ZOOMROW * and ZOOMCOL fields must be filled with the magnification levels in the row (line) and column * (element) directions, respectively. */ char m_asymFlag[ASYM_FLAG_SIZE + 1]; /** * Field: ZOOMROW * * This field shall contain the level of magnification that was applied to the image in the line or * row direction, if asymmetric correction was applied. The valid field codes are 00.0000 to * 99.9999. The level of magnification is relative to the input image at this processing step. This * field is conditional on the ASYM_FLAG field */ char m_zoomRow[ZOOMROW_SIZE + 1]; /** * Field: ZOOMCOL * * This field shall contain the level of magnification that was applied to the image in the element * or column direction, if asymmetric correction was applied. The valid field codes are 00.0000 to * 99.9999. The level of magnification is relative to the input image at this processing step. This * field is conditional on the ASYM_FLAG field. */ char m_zoomCol[ZOOMCOL_SIZE + 1]; /** * Field: PROJ_FLAG * * This field shall indicate if the image has been projected from the collection geometry into * geometry more suitable for display. The valid field codes are 0 and 1. A value of 0 means that * no geometric transformation has been applied to the image, meaning it is probably stilled in the * collection geometry. A value of 1 means that the image has been projected into another * geometry. If this field is equal to 1, then a description of the projection or rectification * shall be given in the comment section. */ char m_projFlag[PROJ_FLAG_SIZE + 1]; /** * Field: SHARP_FLAG * * This field shall indicate if the image has been passed through a sharpening operation. The valid * field codes are 0 and 1. A value of 0 means that no sharpening has been applied to the image. A * value of 1 means that sharpening has been applied to the image. If this field is equal to 1, * then the SHARPFAM and SHARPMEN fields must be filled with the appropriate numbers. Refer to * paragraph 15.5 for a more complete description of the sharpening kernel database. */ char m_sharpFlag[SHARP_FLAG_SIZE+1]; /** * Field: SHARPFAM * * This field shall contain the number of the sharpening family, if a sharpening operation was * applied to the image. The valid field codes are –1, 00 to 99. This field is conditional on the * SHARP_FLAG field. Although the IDEX sharpening family numbers are one-based, many * commercial softcopy systems use a zero-based system for their databases. For example, IDEX * family 5 would be family 4 for many other softcopy systems. If the sharpening kernel is not a * part of the existing group of families and members, a value of – shall be placed in this field * and the nature of the sharpening kernel specified in the comment section. Refer to paragraph * 15-5 for a more complete description of the sharpening kernel database. */ char m_sharpFam[SHARPFAM_SIZE+1]; /** * Field: SHARPMEM * * This field shall contain the number of the sharpening member, if a sharpening operation was * applied to the image. The valid field codes are –1, 00 to 99. This field is conditional on the * SHARP_FLAG field. If the sharpening kernel is not a part of the existing group of families and * members, a value of –1 shall be placed in this field and the nature of the sharpening kernel * shall be specified in the comment section. Refer to 15.5 for a more complete description of the * sharpening database. */ char m_sharpMem[SHARPMEM_SIZE+1]; /** * Field MAG_FLAG * * This field shall indicate if the image has been symmetrically (same amount in each direction) * magnified during this processing step. The valid field codes are 0 and 1. A value of 0 means * that the image was not magnified. A value of 1 means that the image has been magnified. If this * field is equal to 1, then the MAG_LEVEL field shall be filled with the level of magnification. */ char m_magFlag[MAG_FLAG_SIZE+1]; /** * Field MAG_LEVEL * * This field shall contain the level of symmetrical magnification that has been applied to the * image relative to the input image at this processing step. For example, a value of 02.0000 would * indicate a 2X magnification relative to the input image. The valid field codes are 00.0000 to * 99.9999. This field is conditional on the MAG_FLAG field. A value greater than 1 shall * indicate that the image was magnified to a size larger than its previous size and a value less * than 1 shall indicate the image size was decreased. The method of magnification shall be * described in the comment section. */ char m_magLevel[MAG_LEVEL_SIZE +1]; /** * Field: DRA_FLAG * * This field shall indicate if a dynamic Range Adjustment (DRA) has been applied to the image. * DRA is an affine transformation of the image pixel values of the form Y = DRA_MULT*(X – * DRA_SUB), where X is the input pixel value, DRA_SUB is the DRA subtractor, DRA_MULT * is the DRA multiplier, and Y is the output pixel value. The DRA is said to be spatially * invariant when the DRA subtractor and DRA multiplier do not depend on pixel position. If the DRA * subtractor and DRA multiplier do depend on pixel position, the DRA is said to be spatially * variant. The valid field codes are 0, 1, and 2. A value of 0 means that a DRA has not been * applied to the image. A value of 1 means that a spatially invariant DRA has been applied to the * image. In this case, the DRA_SUB and DRA_MULT fields shall be filled with the appropriate * codes. A value of 2 means that a spatially variant DRA has been applied to the image. In cases * where DRA_FLAG equals 0 or 2, the DRA_SUB and DRA_MULT fields shall not be filled. */ char m_draFlag[DRA_FLAG_SIZE+1]; /** * Field: DRA_MULT * * This field shall contain the multiplier value of the DRA. The valid field codes are 000.000 to * 999.999. This field is conditional on the DRA_FLAG field being equal to 1. */ char m_draMult[DRA_MULT_SIZE+1]; /** * Field: DRA_SUB * * This field shall contain the subtractor value of the DRA. The valid field codes are 000.000 to * 999.999. This field is conditional on the DRA_FLAG field being equal to 1. */ char m_draSub[DRA_SUB_SIZE+1]; /** * Field: TTC_FLAG * * This field shall indicate if a TTC (Tonal Transfer Curve) has been applied to the image. The * valid field codes are 0 and 1. A value of 0 means that a TTC has not been applied to the image. * A value of 1 means that a TTC has been applied to the image. If a TTC has been applied, then * the TTCFAM and TTCNUM fields shall be filled with the appropriate codes. Refer to * paragraph 15-5 for more complete description of the TTC database. */ char m_ttcFlag[TTC_FLAG_SIZE+1]; /** * Field: TTCFAM * * This field shall contain the number of the TTC family, if a TTC was applied to the image. The * valid field codes are –1, 00 to 99. This field is conditional on the TTC_FLAG field. Although * the IDEXZ TTC family numbers are one-based, many commercial softcopy systems use a zerobased * system for their databases. For example, IDEX family 5 would be family 4 for many * other softcopy systems. If the TTC is not a part of the existing group of families and members, * a value of –1 shall be placed in this field and the nature of the TTC shall be specified in the * comment section. Refer to paragraph 15-5 for a more complete description of the TTC database. */ char m_ttcFam[TTCFAM_SIZE+1]; /** * Field: TTCMEM * * This field shall contain the number of the TTC member, if a TTC was applied to the image. The * valid field codes are 00 to 99. This field is conditional on the TTC_FLAG field. If the TTC is * not a part of the existing group of families and members, a value of –1 shall be placed in this * field and the nature of the TTC shall be specified in the comment section. Refer to paragraph * 15-5 for a more complete description of the TTC database. */ char m_ttcMem[TTCMEM_SIZE+1]; /** * Field: DEVLUT_FLAG * * This field shall indicate if device compensation LUT has been applied to the image. The valid * field codes are 0 and 1. A value of 0 means that a device LUT has not been applied to the * image. A value of 1 means that t device LUT has been applied to the image. The nature of the * LUT may be specified in the comment section and should include the device for which the LUT * is applied. If the device is not known, an appropriate method for describing the LUT shall be * given. */ char m_devLutFlag[DEVLUT_FLAG_SIZE+1]; /** * Field OBPP * * This field shall contain the number of significant bits for each pixel after the processing * functions denoted in the processing event have been performed, but prior to any output * compression. For example, if an 8 bpp System B image is mapped into Display-Ready space * using the proper 8 to 11 bpp transformation (see appendix A), the IBPP field shall contain the * actual number of data pixels, not the word length. For example, if an 11-bpp word were stored * in 16 bits, this field would contain 11. The valid OBPP field codes are 01 to 64, indicating 1 * to 64 bpp. In many cases, this field will match the IBPP field. */ char m_obpp[OBPP_SIZE+1]; /** * Field: OPVTYPE * * This field shall contain an indicator of the type of computer representation used for the value * of each pixel after the processing functions denoted in the processing event have been * performed, but prior to any output compression. Valid entries are INT for integer, B for * bi-level, SI for 2’s complement signed integer, R for real, and C for complex. The data bits of * INT and SI values shall appear in the file in order of significance, beginning with the MSB and * ending with the LSB. INT and SI data types shall be limited to 16 bits. R values shall be * represented according to IEEE 32-bit floating-point representation (IEEE754). C values shall be * represented with the Real and Imaginary parts each 32-bit floating point representation * (IEEE754) and appearing adjacent four-byte blocks, first Real, then Imaginary. B (bi-level) * pixel values shall be represented as single bits with value 1 or 0. */ char m_opvType[OPVTYPE_SIZE+1]; /** * Field: OUTBWC * * This field shall indicate the type of bandwidth compression or expansion that has been applied * to the image after any enhancements denoted in the processing event. The valid field codes to * describe each type of compression are 5 byte character strings. The first two characters * indicate the type of compression such as DCT or DPCM. The next two characters indicate either * the bit rate or the quality level. The last character indicates if the process is compression * or an expansion. Compression is denoted by a C, an E denotes expansion, and 0 indicates that * neither process occurred. The types of compression are indicated by the same codes used in the * INBWC field and can be found in the field description for INBWC. * The entire BWC field is 10 bytes long to allow for the concatenation of up to 2 compression * algorithms. Two consecutive 5 byte character strings shall indicate the application of two * compression algorithms in succession. If only one operation is performed, then the remaining 5 * characters are zero. Examples of valid codes for the BWC field are shown below. * The NJQ1C00000 code indicates that the processed image was saved as a NSIF JPEG lossless * compressed image. * The NJNLC00000 indicates that the processed image was saved as a NSIF JPEG lossless * compressed image. * The C3Q3C00000 code indicates that the processed image was saved as a NSIF JPEG * compressed image at quality level 3. */ char m_outBwc[OUTBWC_SIZE+1]; }; // Matches: class OSSIM_DLL ossimNitfHistoaProcessingEvent class OSSIM_DLL ossimNitfHistoaTag : public ossimNitfRegisteredTag { public: enum { SYSTYPE_SIZE = 20, PC_SIZE = 12, PE_SIZE = 4, REMAP_FLAG_SIZE = 1, LUTID_SIZE = 2, NEVENTS_SIZE = 2 }; ossimNitfHistoaTag(); /** * * This will allow the user defined data to parse the stream. * */ virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual ossim_uint32 getSizeInBytes()const; // virtual void setProperty(ossimRefPtr property); // virtual ossimRefPtr getProperty(const ossimString& name)const; // virtual void getPropertyNames(std::vector& propertyNames)const; /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void clearFields(); protected: /** * Field: SYSTYPE * * This field shall contain the name of the sensor from which the original image was collected. For * national imagery, the valid field codes are SystemA, SystemB, SystemC, and SystemD. These * codes shall not be used to indicate any other airborne or commercial systems and are reserved * solely for the National systems. The codes in the SYSTYPE field shall be left justified and the * remainder of the field filled with blanks to 20 characters. The NTB has requested that this tag be * able to handle other types of airborne and commercial imagery currently supported by NITF. * Additional valid field codes are listed below: * ASARS-2 ASARS System * GHR Global Hawk Radar * SYERS-EO SYERS Electro-Optical System * SYERS-MSI SYERS Multispectral System * SYERS-IR SYERS Infrared System * DSR Dark Star Radar * TSAR TESAR * TBD Other */ char m_systype[SYSTYPE_SIZE+1]; /** * Field: PC * * This field shall contain an alphanumeric string that indicates if bandwidth * compression/expansion was applied to the image prior to NITF image creation. This field * should be used in conjunction with the PE field to determine the state of the image prior to * NITF formation. The valid field codes for the PC field is 4 byte character strings. The first two * characters indicate the type of compression such as DCT or DPCM. The next two characters * indicate either the bit rate or the quality level. The types of compression are indicated by the * following codes: * Value Definition * DP43 DPCM (Differential Pulse Coded Modulation) – 4.3 bpp * DC13 DCT (Discrete Cosine Transform –1.3 bpp * DC23 DCT (Discrete Cosine Transform) – 2.3 bpp * NJNL NSIF JPEG – Lossless * NJQ0 NSIF JPEG – Quality Level 0 * NJQ1 NSIF JPEG – Quality Level 1 * NJQ2 NSIF JPEG – Quality Level 2 * C11D NSIF Bi-level – 1D * C12S NSIF Bi-level – 2DS * C12H NSIF Bi-level – 2DH * M11D NSIF Bi-level – 1D * M12S NSIF Bi-level with masked blocks – 2DS * M12H NSIF Bi-level with masked blocks – 2DH * C207 NITF ARIDPCM – 0.75 bpp * C214 NITF ARIDPCM – 1.40 bpp * C223 NITF ARIDPCM – 2.30 bpp * C245 NITF ARIDPCM – 4.50 bpp * C3Q0 NSIF Lossy JPEG – Q0 Custom Tables * C3Q1 NSIF Lossy JPEG – Q1 Default Tables * C3Q2 NSIF Lossy JPEG – Q2 Default Tables * C3Q3 NSIF Lossy JPEG – Q2 Default Tables * C3Q4 NSIF Lossy JPEG – Q4 Default Tables * C3Q5 NSIF Lossy JPEG – Q5 Default Tables * M3Q0 NSIF Lossy JPEG with masked blocks – Q0 Custom * M3Q1 NSIF Lossy JPEG with masked blocks – Q1 Default * M3Q2 NSIF Lossy JPEG with masked blocks – Q2 Default * M3Q3 NSIF Lossy JPEG with masked blocks – Q3 Default * M3Q4 NSIF Lossy JPEG with masked blocks – Q4 Default * M3Q5 NSIF Lossy JPEG with masked blocks – Q5 Default * C4LO NSIF Vector Quantization – Lossy * M4LO NSIF Vector Quantization with masked blocks * C5NL NSIF Lossless JPEG * M5NL NSIF Lossless JPEG with masked blocks * NC00 NSIF uncompressed * NM00 NSIF with masked blocks uncompressed * I1Q1 NSIF Downsample JPEG – Q1 * I1Q2 NSIF Downsample JPEG – Q2 * I1Q3 NSIF Downsample JPEG – Q3 * I1Q4 NSIF Downsample JPEG – Q4 * I1Q5 NSIF Downsample JPEG – Q5 * WVLO Wavelet Lossy * WVNL Wavelet Lossless * JP20 JPEG 2000 * NONE No Compression * UNKC Unknown Compression * The entire PC field is 12 bytes long to allow for the concatenation of up to 3 compression * algorithms. Consecutive 4 byte character strings shall indicate the application of two or three * compression algorithms in succession. If only one compression algorithm is applied then the * last eight characters are zero. If the NSIF creator does not know where the image came from or * what processing has been applied to it, then the code for unknown compression (UNKC) shall * be used. * Examples of valid codes for the PC field are shown below. * The DP43DC130000 code indicates that a concatenation of the 4.3 DPCM and the 1.3 DCT * compression and expansion was applied to the image prior to its NSIF formation. * The NONE00000000 code indicates that no compression was applied to the image prior to its * NSIF formation. */ char m_pc[PC_SIZE+1]; /** * Field: PE * * This field shall contain an alphanumeric string that indicates if any enhancements were applied * to the image prior to NSIF image creation. This field should be used in conjunction with the PC * field to determine the state of the image prior to NSIF formation. The valid field codes for the * PC field are given below * EH08 Enhanced 8 bpp from IDEX * EH11 Enhanced 11 bpp from IDEX * UE08 8 bpp data with DRA but no enhancements from IDEX * EU11 Unenhanced 22 bpp from IDEX * DGHC Digitized Hardcopy * UNKP Unknown Processing * NONE No prior processing * The first four codes explicitly define the types of ODS (Output Data Server) products that are * available for NSIF formation. Additional codes may be added for airborne systems. If the NSIF * creator does not know where the image came from or what processing has been applied to it, * then the code for unknown processing (UNKP) shall be used. */ char m_pe[PE_SIZE+1]; /** * Field: REMAP_FLAG * * This field shall indicate whether or not a system specific remap has been applied to the image. * The valid field codes are 0 – 9, and a blank (BCS 0x20), but 2 – 9 are reserved for future use. A * value of 0 means that no systems specific remap has been applied. A value of 1 means that the * System C specific 16 – 12 bit remap has been applied to the System C image. If the image is not * a System C image, this field does not apply at this time and should be filled with a blank. * Values from 2 – 9 are reserved for future use and shall not be used at this time. */ char m_remapFlag[REMAP_FLAG_SIZE+1]; /** * Field: LUTID * * This field shall contain the DMID (Data Mapping ID) for Systems B and D imagery. The * DMID is contained in IMDAT records 97 and 98 in the ESD (Exploitation Support Data). This * information is also referenced in IF200EAA. The valid field codes are 07, 08, and 12 – 64. A * value of 07 and 08 indicates that the image is PEDF (Piecewise Extended Density Format). A * value between 12 and 64 indicates that the image is a Linlog formatted image. Numbers * between 01 and 06, 09, 10, and 11 are reserved and should not be used at this time. There are no * valid DMID values greater than 64. NSIF users to help determine what type of processing * should be applied to the image can use this field. For all other systems, this field should be filled * with 00. */ char m_lutid[LUTID_SIZE+1]; /** * Field: NEVENTS * * This field shall contain the number of processing events associated with the image. The tag is * designed to record up to 99 separate processing events. The valid field codes are 01 to 99. The * processing events are listed in chronological order, starting with the first event and ending with * the most recent processing event. At a minimum, the first processing event shall be the * processing immediately following the generation of the NSIF formatted image; however, if * practical, the originator of the NSIF image can create the HISTOA TRE earlier - with the * creation of the NSIF formatted image. In that instance, the first processing event would be the * creation of the NSIF formatted image. Each successive processing event is to record what * transformations have been applied to the image, once the image has been processed and saved. */ char m_nEvents[NEVENTS_SIZE+1]; std::vector m_eventList; }; // Matches: class OSSIM_DLL ossimNitfHistoaTag #endif /* #ifndef ossimNitfHistoaTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfIchipbTag.h000066400000000000000000000273361352751253100251070ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: ICHIPB tag class declaration. // // See document STDI-0002 Table 5-2 for more info. // // http://164.214.2.51/ntb/baseline/docs/stdi0002/final.pdf // //---------------------------------------------------------------------------- // $Id: ossimNitfIchipbTag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfIchipbTag_HEADER #define ossimNitfIchipbTag_HEADER 1 #include #include class ossimDpt; class ossimDrect; class ossim2dTo2dTransform; class OSSIM_DLL ossimNitfIchipbTag : public ossimNitfRegisteredTag { public: enum { XFRM_FLAG_SIZE = 2, SCALE_FACTOR_SIZE = 10, ANAMRPH_CORR_SIZE = 2, SCANBLK_NUM_SIZE = 2, OP_ROW_11_SIZE = 12, OP_COL_11_SIZE = 12, OP_ROW_12_SIZE = 12, OP_COL_12_SIZE = 12, OP_ROW_21_SIZE = 12, OP_COL_21_SIZE = 12, OP_ROW_22_SIZE = 12, OP_COL_22_SIZE = 12, FI_ROW_11_SIZE = 12, FI_COL_11_SIZE = 12, FI_ROW_12_SIZE = 12, FI_COL_12_SIZE = 12, FI_ROW_21_SIZE = 12, FI_COL_21_SIZE = 12, FI_ROW_22_SIZE = 12, FI_COL_22_SIZE = 12, FI_ROW_SIZE = 8, FI_COL_SIZE = 8 // ------ // 224 }; /** default constructor */ ossimNitfIchipbTag(); /** * Parse method. * * @param in Stream to parse. */ virtual void parseStream(std::istream& in); /** * Write method. * * @param out Stream to write to. */ virtual void writeStream(std::ostream& out); /** * Clears all string fields within the record to some default nothingness. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; /** * @return The Non-linear transformation flag. */ bool getXfrmFlag() const; /** * @return Scale factor relative to R0 (original full res image resolution). */ ossim_float64 getScaleFactor() const; /** * @return Anamophic correction indicator. */ bool getAnamrphCorrFlag() const; /** * @return Scan block number or scan block index. */ ossim_uint32 getScanBlock() const; /** * @return Output product row number component of grid point index (1,1) for * intelligent data, */ ossim_float64 getOpRow11() const; /** * Output product column number component of grid point index (1,1) for * intelligent data. */ ossim_float64 getOpCol11() const; /** * @return Output product row number component of grid point index (1,2) for * intelligent data, */ ossim_float64 getOpRow12() const; /** * Output product column number component of grid point index (1,2) for * intelligent data. */ ossim_float64 getOpCol12() const; /** * @return Output product row number component of grid point index (2,1) for * intelligent data, */ ossim_float64 getOpRow21() const; /** * Output product column number component of grid point index (2,1) for * intelligent data. */ ossim_float64 getOpCol21() const; /** * @return Output product row number component of grid point index (2,2) for * intelligent data, */ ossim_float64 getOpRow22() const; /** * @return Output product row number component of grid point index (2,2) for * intelligent data, */ ossim_float64 getOpCol22() const; /** * @return Grid point (1,1) row number in full image coordinate system. */ ossim_float64 getFiRow11() const; /** * @return Grid point (1,1) column number in full image coordinate system. */ ossim_float64 getFiCol11() const; /** * @return Grid point (1,2) row number in full image coordinate system. */ ossim_float64 getFiRow12() const; /** * @return Grid point (1,2) row number in full image coordinate system. */ ossim_float64 getFiCol12() const; /** * @return Grid point (2,1) row number in full image coordinate system. */ ossim_float64 getFiRow21() const; /** * @return Grid point (2,1) row number in full image coordinate system. */ ossim_float64 getFiCol21() const; /** * @return Grid point (2,2) row number in full image coordinate system. */ ossim_float64 getFiRow22() const; /** * @return Grid point (2,2) row number in full image coordinate system. */ ossim_float64 getFiCol22() const; /** * @return Full image number of rows. */ ossim_uint32 getFullImageRows() const; /** * @return Full image number of cols. */ ossim_uint32 getFullImageCols() const; /** * Initializes rect with the image rectangle without any sub image offset * applied. This is the rectangle of the chip starting at (0,0). * * @param rect The rect to initialize. * * @note Rectangle is shifted by -0.5 since per spec (0,0) is the * considered the upper left corner of the upper left pixel and we use a * point method where (0,0) refers to the center of the pixel. */ void getImageRect(ossimDrect& rect) const; /** * Initializes rect with the image rectangle with sub image offset * applied. This is the rectangle of the chip relative to the full * image or starting at the sub image offset. * * @param rect The rect to initialize. * * @note Rectangle is shifted by -0.5 since per spec (0,0) is the * considered the upper left corner of the upper left pixel and we use a * point method where (0,0) refers to the center of the pixel. */ void getFullImageRect(ossimDrect& rect) const; ossim2dTo2dTransform* newTransform()const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix); protected: /** * FIELD: XFRM_FLAG * * required 2 byte field * * 00 or 01 * * Non-linear transformation flag. * * NOTE: If 01 remaining data zero filled. */ char theXfrmFlag[XFRM_FLAG_SIZE+1]; /** * FIELD: SCALE_FACTOR * * required 10 byte field * * xxxx.xxxxx * * Scale factor relative to R0 (original full res image resolution). */ char theScaleFactor[SCALE_FACTOR_SIZE+1]; /** * FIELD: ANAMRPH_CORR * * required 2 byte field * * 00 or 01 * * Anamophic correction indicator. */ char theAnamrphCorr[ANAMRPH_CORR_SIZE+1]; /** * FIELD: SCANBLK_NUM * * required 2 byte field * * 00-99, 00 if not applicable * * Scan block number or scan block index. */ char theScanBlock[SCANBLK_NUM_SIZE+1]; /** * FIELD: OP_ROW_11 * * required 12 byte field * * xxxxxxxx.yyy typically 00000000.500 * * Output product row number component of grid point index (1,1) for * intelligent data. */ char theOpRow11[OP_ROW_11_SIZE+1]; /** * FIELD: OP_COL_11 * * required 12 byte field * * xxxxxxxx.yyy typically 00000000.500 * * Output product column number component of grid point index (1,1) for * intelligent data. * */ char theOpCol11[OP_COL_11_SIZE+1]; /** * FIELD: OP_ROW_12 * * required 12 byte field * * xxxxxxxx.yyy * * Output product row number component of grid point index (1,2) for * intelligent data. */ char theOpRow12[OP_ROW_12_SIZE+1]; /** * FIELD: OP_COL_12 * * required 12 byte field * * xxxxxxxx.yyy * * Output product column number component of grid point index (1,2) for * intelligent data. */ char theOpCol12[OP_COL_12_SIZE+1]; /** * FIELD: OP_ROW_21 * * required 12 byte field * * xxxxxxxx.yyy * * Output product row number component of grid point index (2,1) for * intelligent data. */ char theOpRow21[OP_ROW_21_SIZE+1]; /** * FIELD: OP_COL_21 * * required 12 byte field * * xxxxxxxx.yyy * * Output product column number component of grid point index (2,1) for * intelligent data. */ char theOpCol21[OP_COL_21_SIZE+1]; /** * FIELD: OP_ROW_22 * * required 12 byte field * * xxxxxxxx.yyy * * Output product row number component of grid point index (2,2) for * intelligent data. */ char theOpRow22[OP_ROW_22_SIZE+1]; /** * FIELD: OP_COL_22 * * required 12 byte field * * xxxxxxxx.yyy * * Output product column number component of grid point index (2,2) for * intelligent data. */ char theOpCol22[OP_COL_22_SIZE+1]; /** * FIELD: FI_ROW_11 * * required 12 byte field * * xxxxxxxx.yyy typically 00000000.500 * * Grid point (1,1) row number in full image coordinate system. */ char theFiRow11[FI_ROW_11_SIZE+1]; /** * FIELD: FI_COL_11 * * required 12 byte field * * xxxxxxxx.yyy typically 00000000.500 * * Grid point (1,1) column number in full image coordinate system. */ char theFiCol11[FI_COL_11_SIZE+1]; /** * FIELD: FI_ROW_12 * * required 12 byte field * * xxxxxxxx.yyy * * Grid point (1,2) row number in full image coordinate system. */ char theFiRow12[FI_ROW_12_SIZE+1]; /** * FIELD: FI_COL_12 * * required 12 byte field * * xxxxxxxx.yyy * * Grid point (1,2) column number in full image coordinate system. */ char theFiCol12[FI_COL_12_SIZE+1]; /** * FIELD: FI_ROW_21 * * required 12 byte field * * xxxxxxxx.yyy * * Grid point (2,1) row number in full image coordinate system. */ char theFiRow21[FI_ROW_21_SIZE+1]; /** * FIELD: FI_COL_21 * * required 12 byte field * * xxxxxxxx.yyy * * Grid point (2,1) column number in full image coordinate system. */ char theFiCol21[FI_COL_21_SIZE+1]; /** * FIELD: FI_ROW_22 * * required 12 byte field * * xxxxxxxx.yyy * * Grid point (2,2) row number in full image coordinate system. */ char theFiRow22[FI_ROW_22_SIZE+1]; /** * FIELD: FI_COL_22 * * required 12 byte field * * xxxxxxxx.yyy * * Grid point (2,2) column number in full image coordinate system. */ char theFiCol22[FI_COL_22_SIZE+1]; /** * FIELD: FI_ROW * * required 8 byte field * * 00000000 and 00000002 to 99999999 * * Full image number of rows. */ char theFullImageRow[FI_ROW_SIZE+1]; /** * FIELD: FI_COL * * required 8 byte field * * 00000000 and 00000002 to 99999999 * * Full image number of cols. */ char theFullImageCol[FI_COL_SIZE+1]; /** * FIELD: * * required byte field * * 01 to 99 * * */ /** * FIELD: * * required byte field * * 01 to 99 * * */ /** * FIELD: * * required byte field * * 01 to 99 * * */ TYPE_DATA }; #endif /* End of "#ifndef ossimNitfIchipbTag_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageBand.h000066400000000000000000000030111352751253100250440ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfImageBand_HEADER #define ossimNitfImageBand_HEADER 1 #include #include #include #include #include class ossimNitfImageBand : public ossimObject { public: ossimNitfImageBand(); virtual ~ossimNitfImageBand(); virtual void parseStream(ossim::istream& in)=0; virtual void writeStream(ossim::ostream& out)=0; /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out Stream to output to. * @param prefix Like "image0." * @param band zero based band. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix, ossim_uint32 band)const=0; virtual ossim_uint32 getNumberOfLuts()const=0; virtual const ossimRefPtr getLut(ossim_uint32 idx)const=0; virtual ossimRefPtr getLut(ossim_uint32 idx)=0; /** @return The band representation as an ossimString. */ virtual ossimString getBandRepresentation() const = 0; TYPE_DATA; }; #endif /* #ifndef ossimNitfImageBand_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageBandV2_0.h000066400000000000000000000057271352751253100255130ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfImageBandV2_0_HEADER #define ossimNitfImageBandV2_0_HEADER 1 #include #include #include #include class OSSIM_DLL ossimNitfImageBandV2_0 : public ossimNitfImageBand { public: /** default constructor */ ossimNitfImageBandV2_0(); /** virtual destructory */ virtual ~ossimNitfImageBandV2_0(); virtual void parseStream(ossim::istream& in); virtual void writeStream(ossim::ostream& out); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out Stream to output to. * @param prefix Like "image0." * @param band zero based band. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string(), ossim_uint32 band=0) const; virtual ossim_uint32 getNumberOfLuts()const; virtual const ossimRefPtr getLut(ossim_uint32 idx)const; virtual ossimRefPtr getLut(ossim_uint32 idx); /** @return The band representation as an ossimString. */ virtual ossimString getBandRepresentation()const; /** * Sets the band representation. * * @param rep The band representation. */ virtual void setBandRepresentation(const ossimString& rep); /** @return The band significance as an ossimString. */ virtual ossimString getBandSignificance()const; /** * Sets the band significance. * * @param rep The band significance. */ virtual void setBandSignificance(const ossimString& rep); bool loadState(const ossimKeywordlist& kwl, const char* prefix, ossim_uint32 index=0); protected: void clearFields(); void printLookupTables(std::ostream& out)const; /*! * FIELD: IREPBAND,, * Is a required 2 byte field. When theNumberOfBands is * 1 this field will contain all spaces. */ char theBandRepresentation[3]; /*! * FIELD: ISUBCATnn * Is a required 6 byte field. */ char theBandSignificance[7]; /*! * FIELD: IFCnn * Is an required 1 byte field. Will be N */ char theBandImageFilterCondition[2]; /*! * FIELD: IMFLTnn * is a required 3 byte field. This is a reserved field */ char theBandStandardImageFilterCode[4]; /*! * FIELD: NLUTSnn * This is a required 1 byte field. Has value 0-4 */ char theBandNumberOfLuts[2]; /*! * NELUTnn * This is a conditional field. */ char theBandNumberOfLutEntries[6]; std::vector > theLookupTables; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageBandV2_1.h000066400000000000000000000011541352751253100255020ustar00rootroot00000000000000//******************************************************************* // // LICENSE: MIT // // Author: David Burken // //******************************************************************** // $Id$ #ifndef ossimNitfImageBandV2_1_HEADER #define ossimNitfImageBandV2_1_HEADER 1 #include #include class OSSIM_DLL ossimNitfImageBandV2_1 : public ossimNitfImageBandV2_0 { public: /** default constructor */ ossimNitfImageBandV2_1(); /** virtual destructory */ virtual ~ossimNitfImageBandV2_1(); }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageDataMaskV2_1.h000066400000000000000000000015711352751253100263260ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2007 Ball Aerspace & Technologies Corp // // LICENSE: See top level LICENSE.txt file. // // Author: Lucas Eckels // // Description: Nitf support class // //******************************************************************** // $Id: $ #ifndef ossimNitfImageDataMaskV2_1_HEADER #define ossimNitfImageDataMaskV2_1_HEADER #include #include #include class OSSIMDLLEXPORT ossimNitfImageDataMaskV2_1 { public: ossimNitfImageDataMaskV2_1(); void setBlockCount(ossim_uint32 blockCount); void setBlockLengthInBytes(ossim_uint32 blockLength); void setIncludeBlock(ossim_uint32 blockNumber, bool included); void writeStream(std::ostream &out); private: std::vector theIncludedBlocks; ossim_uint32 theBlockLength; }; #endifossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageHeader.h000066400000000000000000000164541352751253100254070ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfImageHeader_HEADER #define ossimNitfImageHeader_HEADER 1 #include #include #include #include #include #include #include #include class ossimString; class ossimDpt; class ossimIpt; class ossimIrect; class OSSIMDLLEXPORT ossimNitfImageHeader : public ossimObject, public ossimPropertyInterface { public: ossimNitfImageHeader(); virtual ~ossimNitfImageHeader(); virtual bool getTagInformation(ossimNitfTagInformation& tagInfo, ossim_uint32 idx) const; virtual std::vector getAllTags() { return theTagList; } virtual void setAllTags(std::vector tagList) { theTagList = tagList; } virtual bool getTagInformation(ossimNitfTagInformation& tagInfo, const ossimString& tagName) const; ossimRefPtr getTagData(const ossimString& tagName); const ossimRefPtr getTagData( const ossimString& tagName) const; /** * @brief Returns all tags of type tagName. * * Vector passed in "tags" is cleared, then initialized with all tags * found of "tagName". Size of vector is returned. * * @param tagName E.g. "RSMPCA" * @param tags Initialized by this. */ void getTagData( const ossimString& tagName, std::vector< const ossimNitfRegisteredTag*> &tags ) const; virtual ossim_uint32 getNumberOfTags()const; virtual void addTag(const ossimNitfTagInformation& tag, bool unique=true); virtual void removeTag(const ossimString& tagName); virtual void parseStream(ossim::istream& in)= 0; virtual void writeStream(ossim::ostream& out)= 0; virtual bool isCompressed()const=0; virtual bool isEncrypted()const=0; /** * isValid will test if the fields are valid and will return true or false. */ virtual bool isValid()const=0; virtual ossimString getCompressionCode()const=0; virtual ossimString getCompressionRateCode()const=0; virtual ossim_uint32 getDisplayLevel()const=0; virtual ossim_uint32 getAttachmentLevel()const=0; virtual ossim_int32 getNumberOfRows()const=0; virtual ossim_int32 getNumberOfBands()const=0; virtual ossim_int32 getNumberOfCols()const=0; virtual ossim_int32 getNumberOfBlocksPerRow()const=0; virtual ossim_int32 getNumberOfBlocksPerCol()const=0; virtual ossim_int32 getNumberOfPixelsPerBlockHoriz()const=0; virtual ossim_int32 getNumberOfPixelsPerBlockVert()const=0; virtual ossimString getImageId()const=0; virtual ossimString getTitle()const=0; virtual ossim_int32 getActualBitsPerPixelPerBand()const=0; virtual ossim_int32 getBitsPerPixelPerBand()const=0; virtual ossimIrect getImageRect()const=0; /** * Blocks might not be the same size as the significant rows and cols used * by the getImageRect. */ virtual ossimIrect getBlockImageRect()const=0; virtual ossimString getIMode()const=0; virtual ossim_uint64 getDataLocation()const=0; /** @return The IDATIM field unparsed. */ virtual ossimString getImageDateAndTime() const=0; virtual ossimString getAcquisitionDateMonthDayYear(ossim_uint8 separationChar='-')const=0; virtual ossimString getSecurityClassification()const=0; virtual ossimString getCategory()const=0; virtual ossimString getImageSource()const=0; virtual ossimString getRepresentation()const=0; virtual ossimString getCoordinateSystem()const=0; virtual ossimString getGeographicLocation()const=0; virtual ossimString getPixelValueType()const=0; /** @return IMAG field */ virtual ossimString getImageMagnification()const=0; /** * @brief Gets the ILOC field as an ossimIpt. * @param loc Initialized with the field. * @note: Do not confuse with "data location". */ virtual void getImageLocation(ossimIpt& loc)const=0; /** * @brief Convenience method to get the decimation factor as a double from * the string returned be the getImageMagnification() method. * * @param result Initialized with the decimation factor as a double. * Will return an ossim::nan() if something bad happens like the string is * empty so callers should check result with ossim::isnan(result). */ virtual void getDecimationFactor(ossim_float64& result) const; virtual bool hasBlockMaskRecords()const=0; virtual bool hasPadPixelMaskRecords()const=0; virtual bool hasTransparentCode()const=0; virtual ossim_uint32 getTransparentCode()const=0; virtual ossim_uint32 getBlockMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const=0; virtual ossim_uint32 getPadPixelMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const=0; virtual const ossimRefPtr getCompressionHeader()const=0; virtual const ossimRefPtr getBandInformation(ossim_uint32 idx)const=0; bool hasLut()const; ossimRefPtr createLut(ossim_uint32 bandIdx)const; virtual bool isSameAs(const ossimNitfImageHeader* hdr) const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual ossim_uint32 getTotalTagLength()const; /** * @brief print method that outputs a key/value type format adding prefix * to keys. */ virtual std::ostream& printTags( std::ostream& out, const std::string& prefix=std::string()) const; /** * @brief Populates keyword list with metadata. * expample: country_code: US * * @param kwl Keywordlist to populate with metadata. * * @param prefix Optional prefix to put in front of key, like: "image1.". */ virtual void getMetadata(ossimKeywordlist& kwl, const char* prefix=0) const; /** * @brief pure virtual print method that outputs a key/value type format * adding prefix to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const = 0; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; protected: /** * Method to check tie point to see if it will be truncated in field * IGEOLO which has only arc second resolution. * * Spits out warning if tie does not evenly divide by an arc second. * * @param tie Tie point to check. */ void checkForGeographicTiePointTruncation(const ossimDpt& tie) const; std::vector theTagList; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageHeaderV2_0.h000066400000000000000000000121441352751253100260260ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfImageHeaderV2_0_HEADER #define ossimNitfImageHeaderV2_0_HEADER 1 #include #include #include #include class OSSIMDLLEXPORT ossimNitfImageHeaderV2_0 : public ossimNitfImageHeaderV2_X { public: ossimNitfImageHeaderV2_0(); virtual ~ossimNitfImageHeaderV2_0(); virtual void parseStream(ossim::istream& in); virtual void writeStream(ossim::ostream& out); /** * @brief print method that outputs a key/value type format adding prefix * to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool isCompressed()const; virtual bool isEncrypted()const; virtual ossim_int32 getNumberOfBands()const; virtual ossim_int32 getNumberOfRows()const; virtual ossim_int32 getNumberOfCols()const; virtual ossim_int32 getNumberOfBlocksPerRow()const; virtual ossim_int32 getNumberOfBlocksPerCol()const; virtual ossim_int32 getNumberOfPixelsPerBlockHoriz()const; virtual ossim_int32 getNumberOfPixelsPerBlockVert()const; virtual ossimString getImageId()const; virtual ossim_int32 getBitsPerPixelPerBand()const; virtual ossim_int32 getActualBitsPerPixelPerBand()const; virtual ossimString getIMode()const; virtual ossimString getSecurityClassification()const; /** @return The IDATIM field unparsed. */ virtual ossimString getImageDateAndTime() const; virtual ossimString getAcquisitionDateMonthDayYear( ossim_uint8 separationChar='-')const; virtual ossimString getCategory()const; virtual ossimString getImageSource()const; virtual ossimString getRepresentation()const; virtual ossimString getCoordinateSystem()const; virtual ossimString getPixelValueType()const; virtual bool hasBlockMaskRecords()const; virtual bool hasPadPixelMaskRecords()const; virtual bool hasTransparentCode()const; virtual ossim_uint32 getTransparentCode()const; virtual ossim_uint32 getBlockMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const; virtual ossim_uint32 getPadPixelMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const; virtual const ossimRefPtr getCompressionHeader()const; virtual const ossimRefPtr getBandInformation(ossim_uint32 idx)const; virtual void setNumberOfBands(ossim_uint32 nbands); virtual void setBandInfo(ossim_uint32 idx, const ossimNitfImageBandV2_0& info); virtual void setNumberOfRows(ossim_uint32 rows); virtual void setNumberOfCols(ossim_uint32 cols); virtual bool isValid()const; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; static const ossimString ISCODE_KW; static const ossimString ISCTLH_KW; static const ossimString ISREL_KW; static const ossimString ISCAUT_KW; static const ossimString CTLN_KW; static const ossimString ISDWNG_KW; static const ossimString ISDEVT_KW; TYPE_DATA private: // void clearFields(); /*! * FIELD ISCODE: * is a 40 byte field */ char theCodewords[41]; /*! * FIELD ISCTLH: * is a 40 byte field */ char theControlAndHandling[41]; /*! * FIELD ISREL: * Is a 40 byte field. */ char theReleasingInstructions[41]; /*! * FIELD ISCAUT: * Is a 20 byte field */ char theClassificationAuthority[21]; /*! * FIELD CTLN: */ char theSecurityControlNumber[21]; /*! * FIELD ISDWNG: * Is a 6 byte field with form: * * YYMMDD. Year month day * * 999999 indicates that he Originating * agencies determination is required * (OADR) * 999998 downgrade event will specify at what * point and time the declassification * or downgrading is to take place. */ char theSecurityDowngrade[7]; /*! * FIELD ISDEVT: * This is a conditional field and is present * if the Security downgrade is 999998. */ char theDowngradingEvent[41]; /** * Will contain also the field NBANDS and we will have to recreate the prefix for * * Container for repetitive fields: * IREPBAND * ISUBCAT * IFC * IMFLT * NLUTS * NELUT1 * LUTD */ std::vector > theImageBands; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageHeaderV2_1.h000066400000000000000000000363141352751253100260340ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // LICENSE: MIT // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfImageHeaderV2_1_HEADER #define ossimNitfImageHeaderV2_1_HEADER 1 #include #include class ossimNitfFileHeaderV2_1; class OSSIMDLLEXPORT ossimNitfImageHeaderV2_1 : public ossimNitfImageHeaderV2_X { public: ossimNitfImageHeaderV2_1(); virtual ~ossimNitfImageHeaderV2_1(); virtual void parseStream(std::istream &in, const ossimNitfFileHeaderV2_1 *file); virtual void parseStream(std::istream &in); virtual void writeStream(std::ostream &out); virtual bool isValid()const; /** * @brief print method that outputs a key/value type format adding prefix * to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; virtual ossimIrect getImageRect()const; virtual ossimIrect getBlockImageRect()const; virtual bool isCompressed()const; virtual bool isEncrypted()const; virtual ossim_int32 getNumberOfBands()const; virtual ossim_int32 getNumberOfRows()const; virtual ossim_int32 getNumberOfCols()const; virtual ossim_int32 getNumberOfBlocksPerRow()const; virtual ossim_int32 getNumberOfBlocksPerCol()const; virtual ossim_int32 getNumberOfPixelsPerBlockHoriz()const; virtual ossim_int32 getNumberOfPixelsPerBlockVert()const; virtual ossimString getImageId()const; virtual ossim_int32 getBitsPerPixelPerBand()const; virtual ossim_int32 getActualBitsPerPixelPerBand()const; virtual ossimString getIMode()const; /** @return The IDATIM field unparsed. */ virtual ossimString getImageDateAndTime() const; virtual ossimString getAcquisitionDateMonthDayYear(ossim_uint8 separationChar='-')const; virtual ossimString getSecurityClassification()const; virtual ossimString getCategory()const; virtual ossimString getRepresentation()const; virtual ossimString getCoordinateSystem()const; virtual ossimString getGeographicLocation()const; virtual ossimString getPixelValueType()const; virtual bool takeOverflowTags(std::vector &overflowTags, ossim_uint32 potentialDesIndex, bool userDefinedTags = false); virtual bool hasBlockMaskRecords()const; virtual bool hasPadPixelMaskRecords()const; virtual bool hasTransparentCode()const; virtual ossim_uint32 getTransparentCode()const; virtual ossim_uint32 getBlockMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const; virtual ossim_uint32 getPadPixelMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const; virtual void setNumberOfBands(ossim_uint32 nbands); virtual void setBandInfo(ossim_uint32 idx, const ossimNitfImageBandV2_1& info); virtual void setNumberOfRows(ossim_uint32 rows); virtual void setNumberOfCols(ossim_uint32 cols); virtual void setGeographicLocationDms(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); virtual void setGeographicLocationDecimalDegrees(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); virtual void setUtmNorth(ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); virtual void setUtmSouth(ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); virtual void setSecurityClassificationSystem(const ossimString& value); virtual void setCodewords(const ossimString& value); virtual void setControlAndHandling(const ossimString& value); virtual void setReleasingInstructions(const ossimString& value); virtual void setDeclassificationType(const ossimString& value); virtual void setDeclassificationDate(const ossimString& value); virtual void setDeclassificationExempt(const ossimString& value); virtual void setDowngrade(const ossimString& value); virtual void setDowngradeDate(const ossimString& value); virtual void setClassificationText(const ossimString& value); virtual void setClassificationAuthorityType(const ossimString& value); virtual void setClassificationAuthority(const ossimString& value); virtual void setClassificationReason(const ossimString& value); virtual void setSecuritySourceDate(const ossimString& value); virtual void setSecurityControlNumber(const ossimString& value); virtual void setImageMagnification(const ossimString& value); virtual ossimString getImageSource()const; virtual const ossimRefPtr getCompressionHeader()const; virtual const ossimRefPtr getBandInformation(ossim_uint32 idx)const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; /*! * @brief Method to set fields from a keyword list. * * This is not a true loadState as it does not lookup/initialize all class * members. This was added to allow defaults, e.g ISCLAS, to be set via a * site configuration file. * Code does not return false if a field(key) is not found.. * * @return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); static const ossimString ISCLSY_KW; static const ossimString ISCODE_KW; static const ossimString ISCTLH_KW; static const ossimString ISREL_KW; static const ossimString ISDCTP_KW; static const ossimString ISDCDT_KW; static const ossimString ISDCXM_KW; static const ossimString ISDG_KW; static const ossimString ISDGDT_KW; static const ossimString ISCLTX_KW; static const ossimString ISCATP_KW; static const ossimString ISCAUT_KW; static const ossimString ISCRSN_KW; static const ossimString ISSRDT_KW; static const ossimString ISCTLN_KW; static const ossimString XBANDS_KW; private: void clearFields(); ossimString encodeUtm(ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll)const; /** * FIELD: ISCLSY * * Is a required 2 byte field. * * Image Security Classification System. * * This field shall contain valid values indicating the * national or multinational security system used to classify the image. * Country Codes per FIPS 10-4 shall be used to indicate national security * systems; codes found in DIAM 65-19 * shall be used to indicate multinational security systems. * If this field is all BCS spaces (0x20), it shall imply that no security * classification system applies to the image. */ char theSecurityClassificationSys[3]; /** * FIELD: ISCODE * * is a 11 byte field * * Image Codewords. * * This field shall contain a valid indicator of the security compartments * associated with the image. Values include one or more of the * tri/digraphs found * in DIAM 65-19 and/or Table A-4. Multiple entries shall be separated by * single * BCS spaces (0x20): The selection of a relevant set of codewords is * application * specific. If this field is all BCS spaces (0x20), it shall imply that no * codewords apply to the image. */ char theCodewords[12]; /** * FIELD: ISCTLH * * is a 2 byte field. * * Image Control and Handling. This field shall contain valid additional * security control and/or handling instructions (caveats) associated with * the image. * Values include digraphs found in DIAM 65-19 and/or Table A4. * The digraph may indicate single or multiple caveats. The selection of a * relevant caveat(s) is application specific. If this field is all BCS * spaces (0x20), * it shall imply that no additional control and handling instructions * apply to the image. */ char theControlAndHandling[3]; /** * FIELD: ISREL * * Is a 20 byte field. * * Image Releasing Instructions. This field shall contain a valid list of * country and/or multilateral entity codes to which countries and/or * multilateral entities the image is authorized for release. Valid items * in the list are one or * more country codes as found in FIPS 10-4 and/or codes identifying * multilateral * entities as found in DIAM 65-19. If this field is all BCS spaces (0x20), * it shall imply that no image release instructions apply. */ char theReleasingInstructions[21]; /** * FIELD: ISDCTP * * Is a required 2 byte field. The valid * values are * DD = declassify on a specific date * DE = Declassify upon occurence of an event * GD = downgrade to a specified level upon * occurence of an event * O = OADR * X = exempt from automatic declassification * spaces = no image security declassification or * downgrade instruction apply. */ char theDeclassificationType[3]; /** * FIELD: ISDCDT * * Is a required 8 byte field. * CCYYMMDD * * CC is the first 2 chars of the year 00-99 * YY is the second 2 chars of the year 00-99 * MM is the month 01-12 * DD is the day 00-31 */ char theDeclassificationDate[9]; /** * FIELD: ISDCXM * * is a required 4 byte field. * * Image Declassification Exemption. * * This field shall indicate the reason the image is exempt from automatic * declassification if the value in Image Declassification Type is X. Valid * values are X1 through X8 and X251 through X259. X1 through X8 correspond * to the declassification exemptions found in DOD 5200.1-R, paragraphs * 4-202b(1) through (8) for material exempt from the 10-year rule. * X251 through X259 correspond to the declassification exemptions found in * DOD 5200.1-R, paragraphs 4-301a(1) through (9) for permanently valuable * material exempt from the 25-year declassification system. If this field is * all BCS spaces (0x20), it shall imply that a image declassification exemption * does not apply. */ char theDeclassificationExempt[5]; /** * FIELD: ISDG * * Is a required 1 byte field with form: * * * Image Downgrade. This field shall indicate the classification level * to which a image is to be downgraded if the values in Image Declassification Type * are GD or GE. * * Valid values are * S (=Secret), * C (=Confidential), * R (= Restricted). * * If this field is all BCS spaces (0x20), it shall imply that image security * downgrading does not apply. */ char theDowngrade[2]; /** * FIELD: ISDGDT * * is a required 8 byte field * * CCYYMMDD * * CC is the first 2 chars of the year 00-99 * YY is the second 2 chars of the year 00-99 * MM is the month 01-12 * DD is the day 00-31 */ char theDowngradeDate[9]; /** * FIELD: ISCLTX * * is a required 43 byte field. * * Image Classification Text. * * This field shall be used to provide additional information * about image classification to include identification of a declassification or downgrading * event if the values in Image Declassification Type are DE or GE.. It may also be used * to identify multiple classification sources and/or any other special handling rules. * Values are user defined free text. If this field is all BCS spaces (0x20), it shall * imply that additional information about image classification does not apply. */ char theClassificationText[44]; /** * FIELD: ISCATP * * Is a required 1 byte field. * * O = original classification Authority * D = derivative from a single source * M = derivative from multiple sources * */ char theClassificationAuthType[2]; /** * FIELD: ISCAUT * * Is a required 40 byte field. * * Image Classification Authority. * * This field shall identify the classification authority for the image dependent upon the * value in Image Classification Authority Type. Values are user defined free text which * should contain the following information: original classification authority name and * position or personal identifier if the value in Image Classification Authority Type is O; * title of the document or security classification guide used to classify the image * if the value in Image Classification Authority Type is D; * and Derive-Multiple if the image classification was derived from multiple sources. * In the latter case, the image originator will maintain a record of the sources used * in accordance with existing security directives. One of the multiple sources may also * be identified in Image Classification Text if desired. If this field is all BCS spaces * (0x20), it shall imply that no image classification authority applies. */ char theClassificationAuthority[41]; /** * FIELD: ISCRSN * * This is a required 1 byte field and indicates * the classification reason. * * Image Classification Reason. * * This field shall contain values indicating the reason for classifying the image. * Valid values are A through G. These correspond to the reasons for * original classification per E.O. 12958, Section 1.5.(a) through (g). * If this field is all BCS spaces (0x20), it shall imply that no image classification * reason applies. */ char theClassificationReason[2]; /** * FIELD: ISSRDT * * This is a required 8 byte field. * * CCYYMMDD * * CC is the first 2 chars of the year 00-99 * YY is the second 2 chars of the year 00-99 * MM is the month 01-12 * DD is the day 00-31 * */ char theSecuritySourceDate[9]; /** * FIELD: ISCTLN * * is a required 15 byte field. */ char theSecurityControlNumber[16]; /** * FIELD: XBANDS * * This is a conditional 5 byte field and ranges from * 00010-99999. This exists if theNumberOfBands is 0. */ char theNumberOfMultispectralBands[6]; std::vector > theImageBands; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageHeaderV2_X.h000066400000000000000000000756241352751253100261120ustar00rootroot00000000000000#ifndef ossimNitfImageHeaderV2_X_HEADER #define ossimNitfImageHeaderV2_X_HEADER 1 #include #include #include class OSSIM_DLL ossimNitfImageHeaderV2_X : public ossimNitfImageHeader { public: ossimNitfImageHeaderV2_X(); /** @brief Returns the zero based image rectangle. */ virtual ossimIrect getImageRect()const; /** * @brief Returns the zero based image rectangle expanded out to block boundaries. * @note This may or may not be the same as the rect from getImageRect. */ virtual ossimIrect getBlockImageRect()const; void setImageId(const ossimString& value); void setAquisitionDateTime(const ossimString& value); void setTargetId(const ossimString& value); void setTitle(const ossimString& value); void setSecurityClassification(const ossimString& value); void setEncryption(const ossimString& value); void setImageSource(const ossimString& value); void setJustification(const ossimString& value); void setCoordinateSystem(const ossimString& value); void setGeographicLocation(const ossimString& value); void setNumberOfComments(const ossimString& value); void setCompression(const ossimString& value); void setCompressionRateCode(const ossimString& value); void setDisplayLevel(const ossimString& value); void setAttachmentLevel(const ossimString& value); void setPixelType(const ossimString& pixelType = ossimString("INT")); void setBitsPerPixel(ossim_uint32 bitsPerPixel); void setActualBitsPerPixel(ossim_uint32 bitsPerPixel); void setImageMode(char mode); void setCategory(const ossimString& category); void setRepresentation(const ossimString& rep); void setBlocksPerRow(ossim_uint32 blocks); void setBlocksPerCol(ossim_uint32 blocks); void setNumberOfPixelsPerBlockRow(ossim_uint32 pixels); void setNumberOfPixelsPerBlockCol(ossim_uint32 pixels); ossim_uint64 getDataLocation()const; ossimString getImageId()const; ossimString getAquisitionDateTime()const; ossimString getTargetId()const; ossimString getTitle()const; ossimString getSecurityClassification()const; ossimString getEncryption()const; ossimString getImageSource()const; ossimString getJustification()const; ossimString getCoordinateSystem()const; ossimString getGeographicLocation()const; ossimString getNumberOfComments()const; ossimString getCompressionCode()const; ossimString getCompressionRateCode()const; ossim_uint32 getDisplayLevel()const; ossim_uint32 getAttachmentLevel()const; ossimString getPixelType()const; ossim_uint32 getBitsPerPixel()const; ossim_uint32 getActualBitsPerPixel()const; char getImageMode()const; ossimString getCategory()const; ossimString getRepresentation()const; ossim_uint32 getBlocksPerRow()const; ossim_uint32 getBlocksPerCol()const; ossim_uint32 getNumberOfPixelsPerBlockRow()const; ossim_uint32 getNumberOfPixelsPerBlockCol()const; virtual bool isValid()const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * @brief Gets the IMAG field as a string. Satisfies pure virtual. * @return IMAG field */ virtual ossimString getImageMagnification()const; /** * @brief Gets the ILOC field as an ossimIpt. Satisfies pure virtual. * @param loc Initialized with the field. * @note: Do not confuse with "data location". */ virtual void getImageLocation(ossimIpt& loc)const; virtual void setGeographicLocationDms(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); virtual void setGeographicLocationDecimalDegrees(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); virtual void setUtmNorth(ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); virtual void setUtmSouth(ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll); virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; /*! * @brief Method to set fields from a keyword list. * * This is not a true loadState as it does not lookup/initialize all class * members. This was added to allow defaults, e.g ISCLAS, to be set via a * site configuration file. * Code does not return false if a field(key) is not found.. * * @return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); static const ossimString IM_KW; static const ossimString IID1_KW; static const ossimString IDATIM_KW; static const ossimString TGTID_KW; static const ossimString IID2_KW; static const ossimString ITITLE_KW; // also IID2 in 2.1 spec and ITITLE in 2.0 spec static const ossimString ISCLAS_KW; static const ossimString ENCRYP_KW; static const ossimString ISORCE_KW; static const ossimString NROWS_KW; static const ossimString NCOLS_KW; static const ossimString PVTYPE_KW; static const ossimString IREP_KW; static const ossimString ICAT_KW; static const ossimString ABPP_KW; static const ossimString PJUST_KW; static const ossimString ICORDS_KW; static const ossimString IGEOLO_KW; static const ossimString NICOM_KW; static const ossimString ICOM_KW; static const ossimString IC_KW; static const ossimString COMRAT_KW; static const ossimString NBANDS_KW; static const ossimString ISYNC_KW; static const ossimString IMODE_KW; static const ossimString NBPR_KW; static const ossimString NBPC_KW; static const ossimString NPPBH_KW; static const ossimString NPPBV_KW; static const ossimString NBPP_KW; static const ossimString IDLVL_KW; static const ossimString IALVL_KW; static const ossimString ILOC_KW; static const ossimString IMAG_KW; static const ossimString UDIDL_KW; static const ossimString UDOFL_KW; static const ossimString IXSHDL_KW; static const ossimString IXSOFL_KW; static const ossimString IMDATOFF_KW; static const ossimString BMRLNTH_KW; protected: /*! * FIELD IM: * Is a required 2 byte value and is IM. */ char theType[3]; /** * FIELD: IID1 * Is a required 10 Alphanumeric value. */ char theImageId[11]; /*! * FIELD IDATIM: * Contains the time of acquisition of the image. * this is a 14 byte field and has the format: * * DDHHMMSSZMONYY * * DD is the day of the month * HH is the Hour * MM is the minutes * SS is the seconds * Z is fixed (Zulu time) * MON is the first 3 chars of the month * YY is the year */ char theDateTime[15]; /** * FIELD: TGTID * * is a 17 byte field. Has the form * * BBBBBBBBBBFFFFFCC * * where: * * B is the encyclopedia id * F is the functional category code * C is the country code. */ char theTargetId[18]; /** * FIELD: IID2 * * Is 80 bytes and contains the title */ char theTitle[81]; /** * FIELD: ISCLAS * * Is a required 1 byte field and has value: * * T = Top secret * S = Secrect * C = confidential * R = Restricted * U = Unclassified */ char theSecurityClassification[2]; /*! * FIELD ENCRYP: * Is arequired 1 byte field. * * 0 = no encryption * 1 = encryption */ char theEncryption[2]; /** * FIELD: ISORCE * * Is a 42 byte optional field. */ char theImageSource[43]; /** * FIELD: NROWS * * Required 8 byte number 00000002-99999999 */ char theSignificantRows[9]; /** * FIELD: NCOLS * * Required 8 byte number 00000002-99999999 */ char theSignificantCols[9]; /** * FIELD: PVTYPE * * Required 3 byte value. * Values: * * INT integer 16 bits * B for bi-level represented as single bits 1 or 0 * SI signend 16 bit integer * R 32 bit float * C for complex (32 bit float real part, 32 bit float imag part) * Adjacent 4 byte blocks * U for user defined. */ char thePixelValueType[4]; /** * FIELD: IREP * * This is required 8 byte field. * * Values: * * MONO indicates monnochrome * RGB indicates true color red green blue * RGB/LUT indicates RGB lookup table. * 1D indicates monoband data. * 2D indicates for 2 dimensional data * NM indicates multidimensional data * MULTI indicates multiband imgery * YCbCr601 indicates compressed in CCIR 601 * color space using JPEG (field IC=C3) */ char theRepresentation[9]; /** * FIELD: ABPP * * Is optional and indicates the number of * bits per band 01-96 */ char theActualBitsPerPixelPerBand[3]; /** * FIELD: ICAT * * This is a required 8 byte field. Contains info * about the specific category of the image. * * VIS visible imagery * SL side looking infrared * TI thermal infrared * FL forward looking infrared * RD radar * EO elctro-optical * OP optical * HR high resolution radar * HS hyperspectral * CP color frame photography * BP black/white frame photography * SAR Synthetic Aperture Radar * SARIQ SAR radio hologram * IR infrared. * MS multispectral * FP fingerprints * MRI Magnetic Resonance imagery * XRAY x-rays * CAT cat scans * MAP maps * PAT patch * LEG legends * DTEM elevation models * MATR matrix data * LOCG location grids * VD video * * * default value is VIS */ char theCategory[9]; /** * FIELD: PJUST * * Is 1 byte optional field. Can have * values L (left) or R (right). Any other value * is to interpreted as right justified. * * This indicates how the significant bits are justified * in the field */ char theJustification[2]; /** * FIELD: ICORDS * * Is a 1 byte required field and can have * values * * U indicates UTM MGRS format * G indicates Geodetic (Geographic) * N indicates UTM Northern hemisphere * S indicates UTM SOuthern hemisphere * D Decimal degrees * * spaces means no coordinate system * * Geodetic reference system is WGS84. */ char theCoordinateSystem[2]; /*! * FIELD NICOM: * this is a required 1 byte field and indicates the number of comments. */ char theNumberOfComments[2]; /*! * FIELD ICOMnn: * Dynamic buffer for the comments. Each comment is 80 bytes */ std::vector theImageComments; /** * FIELD: IGEOLO * * This is a conditional field. If theCoordinateSystem * is blank then it does not exist. If it's any other * value then it's given in image coordinate order * * (0, 0) (0, MaxCol) (MaxRow, MaxCol) (MaxRow, 0) * * if its geodetic or geocentric it will have a lat lon coordinate * with each coordinate as: * Lat = ddmmssX * where d is degrees and m is minutes * and s is seconds and X is either N (North) or S (South). * Lon = dddmmssX * where d is degrees and m is minutes * and s is seconds and X is either N (North) or S (South). * * * if its UTM then zzeeeeeennnnnnn where * * z is the zone number * e is the easting * n is the northing * * if its decimal degrees then +-dd.ddd +-dd.ddd four times where * + is northern hemispher and - is souther hemisphere for lat * and longitude + is easting and - is westing. * */ char theGeographicLocation[61]; /** * FIELD: IC * * This is a required 2 byte field and indicates the compression * type of the image. * * NC indicates not compressed * C1 indicates bi-level * C2 indicates ARIDPCM * C3 inidates JPEG * C4 inidcates Vector Quantization * C5 indicates lossless jpeg * I1 indicates a downsampled jpeg * M0 indicates compressed images * M3 indicates compressed images * M4 indicates compressed images * M5 indicates compression * NM indicates uncompressed * * The M's and NM are blocked images that contain * block mask and/or transparent pixel mask. There * will be an Image Data Mask Subheader ath the beginning * of the image data area. * */ char theCompression[3]; /** * FIELD COMRAT * * This is a conditional 4 byte field. if theCompression is * not equal to NC then this field exists. * * Compression Rate Code. * * If the Image Compression (IC) field contains, C1, C4, M1, or M4, * this field shall be present and contain a code indicating the * compression rate for the image. * If the value in IC is C1 or M1, the valid codes are 1D, 2DS, and 2DH, * where: 1D represents One-dimensional Coding * 2DS represents Two-dimensional Coding Standard Vertical * Resolution (K=2) * 2DH represents Two-dimensional Coding High Vertical Resolution * (K=4) * * A BCS zero (0x30) will be used for the Y value when custom Q-Tables are * used. * Explanation of these codes can be found in ITU-T T-4, AMD2 08/95. * * If the value in IC is C3, C5, I1, or M5, the value of this field shall * be 00.0. * The value 00.0 represents embedded tables and is required by JPEG. * Explanation of embedded tables can be found in MIL-STD-188-198A and * NIMA N0105-97. * If the value in IC is C4 or M4, this field shall contain a value given * in the * form nn.n representing the number of bits-per-pixel for the compressed * image. * Explanation of the compression rate for vector quantization can be * found in MIL-STD-188-199. * This field is omitted if the value in IC is NC or NM. If IC = I1, value * = 00.0. * 4 BCS-A See description for constraints C */ char theCompressionRateCode[5]; /** * FIELD: NBANDS * * Is required 1 byte field and will have value 1-9 * * If theRepresentation is MONO this should be 1 * if theRepresentation is RGB this should be 3 * if theRepresentation is RGB/LUT this should be 1 * if theRepresentation YCbCr601 this should be 3 * if theRepresentation is MULTI this should be 2-9 * * if this field is 0 then it's multi spectral data * larger than 9 */ char theNumberOfBands[2]; /** * FIELD: ISYNC * * Required 1 byte field. Has value 0 or 4 */ char theImageSyncCode[2]; /** * FIELD: IMODE * * Required 1 byte field. * * * Image Mode. This field shall contain an indicator of whether the image * bands are stored in the * file sequentially or band interleaved by block or band interleaved by * pixel format or * band interleaved by row. * * Valid values are B, P, R, and S. The significance of the IMODE value * must be interpreted * with the knowledge of whether the image is: * JPEG compressed (IC=C3, C5, M3, or M5), * VQ compressed (IC=C4, or M4), * or uncompressed (IC=NC or NM). * When IC=C1 or M1, the use of IMODE defaults to B. When IC=I1, IMODE is * B. * * For the uncompressed case: The value R represents band interleaved by * row, * where the ordering mechanism stores the pixel values of each band in * row sequential order. * Within each block, all pixel values of the first row of the first band * are followed by * pixel values of the first row of the second band continuing until all * values of the * first row are stored. The remaining rows are stored in a similar * fashion until the last * row of values has been stored. Each block shall be zero filled to the * next octet boundary * when necessary. The value S represents band sequential, where all * blocks for the first band * are followed by all blocks for the second band, and so on: * [(block1, band1), (block2, band1), ... (blockM, band1)], * [(block1, band2), (block2, band 2), ... (blockM, band2)] ... * [(block1, bandN), (block2, bandN), ... (blockM, bandN)]. * * The values B and P indicate variations on block sequential where all * data from all bands * for the first block is followed by all data from all bands for the * second block, and so on. * The variations are based on the way the bands are organized within each * block. * B represents band interleaved by block. * * This means that within each block, the bands follow one 1 BCS-A B, P, * R, S R * * * another: [(block1, band1), (block1, band2), ... * (block1, bandN)], * [(block2, band1), * (block2, band2), ... * (block2, bandN)], ... * [(blockM, band1), * (blockM, band2), ... * (blockM, bandN)]. * * P represents band interleaved by pixel within each block: such as, for * each block, * one after the other, the full pixel vector (all band values) appears * for every pixel in * the block, one pixel after another, the block column index varying * faster than the block * row index. If the NBANDS field is 1, the cases B and S coincide. * In this case, this field shall contain B. If the Number of Blocks is * 1(NBPR = NBPC = 1), * this field shall contain B for non-interleaved by pixel, and P for * interleaved by pixel. * The value S is only valid for images with multiple blocks and multiple * bands. * For the JPEG-compressed case: The presence of B, P, or S implies * specific ordering of * data within the JPEG image data representation. The interpretation of * the values of IMODE * for this case is specified in MIL-STD188-198A. * * For the Vector Quantization compressed case: VQ compressed images are * normally either RGB with a * color look-up table or monochromatic. In either case, the image is * single band, and the IMODE * field defaults to B. However, it is possible to have a multiband VQ * compressed image in band sequential, * band interleaved by block, or band interleaved by pixel format. * */ char theImageMode[2]; /** * FIELD: NBPR * * Required 4 byte value. ranges from * 0001-9999 */ char theNumberOfBlocksPerRow[5]; /** * FIELD: NBPC * * Required 4 byte value. Ranges from * 0001-9999 */ char theNumberOfBlocksPerCol[5]; /** * FIELD: NPPBH * * Reuqired 4 byte field */ char theNumberOfPixelsPerBlockHoriz[5]; /** * FIELD: NPPBV * * Reuqired 4 byte field */ char theNumberOfPixelsPerBlockVert[5]; /** * FIELD: NBPP * * Required 2 byte field. * * Number of Bits Per Pixel Per Band. If IC contains NC, NM, C4, or M4, * this field shall contain the number of storage bits used for the value * from each component of a pixel vector. The value in this field always * shall be greater than or equal to Actual Bits Per Pixel (ABPP). * For example, if 11-bit pixels are stored in 16 bits, * this field shall contain 16 and Actual Bits Per Pixel shall contain 11. * If IC = C3, M3, C5, M5, or I1 this field shall contain the value 8 or * the value 12. * If IC = C1, this field shall contain the value 1. 2 BCS-N 01-96 R */ char theNumberOfBitsPerPixelPerBand[3]; /** * FIELD: IDLVL * * Display Level. * * Required 3 byte field. Ranges from 001-999 * * This field shall contain a valid value that indicates the graphic display * level of the image relative to other displayed file components in a * composite * display. The display level of each displayable file component (image * or graphic) * within a file shall be unique; that is, each number from 001 to 999 is * the display * level of, at most, one item. The meaning of display level is fully * discussed in * paragraph 5.3.3. The image or graphic component in the file having the * minimum * display level shall have attachment level 0. * */ char theDisplayLevel[4]; /** * FIELD: IALVL * * Attachment Level * * Required 3 byte field. Ranges from 000-998 * * This field shall contain a valid value that indicates the attachment * level of the image. * Valid values for this field are 0, and the display level value of any * other image or * graphic in the file. The meaning of attachment level is fully discussed * in * paragraph 5.3.4. The image, graphic, or text component in the file * having the * minimum display level shall have attachment level 0. * */ char theAttachmentLevel[4]; /** * FIELD: ILOC * * Required 10 byte field. * * Image Location. The image location is the location of the first pixel * of the first line of * the image. This field shall contain the image location represented as * rrrrrccccc, where rrrrr and ccccc are the row and column offset from the * ILOC or SLOC value of the item to which the image is attached. A row or * column * value of 00000 indicates no offset. Positive row and column values * indicate offsets down * and to the right and range from 00001 to 99999, while negative row and * column * values indicate offsets up and to the left and must be within the range * -0001 to -9999. * The location in the common coordinate system of all displayable graphic * components can be computed from the offsets given in the ILOC and SLOC * fields. 10 BCS-N -9999 * */ char theImageLocation[11]; /** * FIELD: IMAG * * Required 4 byte field * * Image Magnification. * * This field shall contain the magnification (or reduction) factor of the * image * relative to the original source image. Decimal values are used to * indicate magnification, * and decimal fraction values indicate reduction. * For example, 2.30 indicates the original image has been magnified by a * factor of * Ò2.30,Ó while Ò0.5Ó indicates the original image has been reduced by a * factor of 2. * The default value is 1.0, indicating no magnification or reduction. * In addition, the following values shall be used for reductions that are * reciprocals of * nonnegative powers of 2: /2 (for 1/2), /4 (for 1/4), /8 (for 1/8), /16 * (for 1/16), /32 (for 1/32), * /64 (for 1/64), /128 (for 1/128). 4 BCS-A /2, /4, /8, /16, /32, /64, * /128 or * decimal value (Default is 1.0 followed by BCS space (0x20)) R * */ char theImageMagnification[5]; /** * FIELD: UDIDL * * Required 5 byte field. 00000 or 00003-99999 * * User Defined Image Data Length. A value of 0 shall represent that no * tagged record extensions * are included in the UDID field. If a tagged record extension exists, * the field shall contain * the sum of the length of all the tagged record extensions (see * paragraph 5.7.l.l) appearing in * the UDID field plus 3 bytes (length of UDOFL field). If a tagged * record extension is too long * to fit in the UDID field, it may be put in a data extension segment * (see paragraph 5.8.1.3.1.) * */ char theUserDefinedImageDataLength[6]; /** * FIELD: UDOFL * * conditional 3 byte field. if theUserDefinedImageDataLength * is not 0 * * User Defined Overflow. If present, this field shall contain 000 if the * tagged record extensions * in UDID do not overflow into a DES, or shall contain the sequence number * of the DES into which * they do overflow. This field shall be omitted if the field UDIDL * contains BCS zeros (0x30). * * */ char theUserDefinedOverflow[4]; /** * FIELD: IXSHDL * * Is a required 5 byte field. 00000 or 00003-99999 * * Extended Subheader Data Length. This field shall contain the length in * bytes in * IXSHD plus 3 (length of IXSOFL). The length is 3 plus sum of the * lengths of all the * tagged record extensions (see paragraph 5.7.1.2) appearing in the IXSHD * field. A value of * BCS zeros (0x30) shall represent that no tagged record extensions are * included in the IXSHD field. * If a tagged record extension exists, the field shall contain the sum of * the length of all the tagged * record extensions (see paragraph 5.7.1.2) appearing in the IXSHD field * plus 3 bytes (length of * IXSOFL field). If a tagged record extension is too long to fit in the * IXSHD field, it shall may * be put in a data extension segment (see paragraph 5.7.1.4). */ char theExtendedSubheaderDataLen[6]; /** * FIELD: IXSOFL * * Is a conditional 3 byte field. This depends on * theExtendedSubheaderDataLen not being 0. * * Extended Subheader Data. If present, this field shall contain tagged * record * extensions (see paragraph 5.8.1.2) approved and under configuration * management by the ISMC. * The length of this field shall be the length specified by the field * IXSHDL minus 3. Tagged * record extensions in this field for an image shall contain information * pertaining specifically * to the image. Tagged record extensions shall appear one after the other * in this field with no * intervening bytes. The first byte of this field shall be the first byte * of the first tagged record * extension appearing in the field. The last byte of this field shall be * the last byte of the last * tagged record extension to appear in the field. This field shall be * omitted if the field IXSHDL * contains 0. */ char theExtendedSubheaderOverflow[4]; /************************************************************************** * THIS IS THE MASK TABLE IF PRESENT */ /** * FIELD NAME: IMDATOFF * * Blocked Image Data Offset. * * 4 byte Binary integer: 0x00000000 to 0xFFFFFFFF * * This field is included if the IC value equals NM, M1, M3, M4, or M5. * It identifies the offset from the beginning of the Image Data Mask to * the first byte of the blocked image data. * This offset, when used in combination with the offsets provided in the * BMR fields, * can provide random access to any recorded image block in any image band. * */ ossim_uint32 theBlockedImageDataOffset; /** * FIELD NAME: BMRLNTH * * Block Mask Record Length. * * 2 byte Unsigned binary integer * 0x0000=No Block mask record; 0x0004=Block mask * records (4 bytes each) are present * * This field is included if the IC value equals NM, M1, M3, M4, or M5. * It identifies the length of each Block Mask Record in bytes. * When present, the length of each Block Mask Record is 4 bytes. * The total length of all the block Mask Records is equal to * * For S mode BMRLNTH x NBPR x NBPC x NBANDS (one 4 byte record for each * block of each band in the image). * and for all other modes BMRLNTH x NBPR x NBPC * * If all of the image blocks are recorded, * this value may be set to 0, and the conditional BMR fields are not * recorded/transmitted. * Otherwise, the value may be set to 4, and the conditional BMR fields * are * recorded/transmitted and can be used as an off-set index for each * image block in each band of the image. * If this field is present, but coded as 0, then only a pad pixel mask is * included. */ ossim_uint16 theBlockMaskRecordLength; /** * FIELD: TMRLNTH * * Pad Pixel Mask Record Length. * * 2 byte Unsigned binary integer a value of * 0x0000=No Pad pixel mask records and * 0x0004=Pad pixel mask records (4 bytes each) are present * * This field is included if the IC value equals NM, M1, M3, M4, or M5 * It identifies the length of each Pad Pixel Mask Record in bytes. * When present, the length of each Pad Pixel Mask Record is 4 bytes. * The total length of the Pad Pixel Mask Records is equal to * * For image mode S then TMRLNTH x NBPR x NBPC x NBANDS (one 4 byte record * for each block for each band in the image). * else for all other modes TMRLNTH x NBPR x NBPC * * If none of the image blocks contain pad pixels, this value is set to 0, * and the conditional TMR fields are not recorded/transmitted. * For IC value of M3, the value shall be set to 0. * If this field is present, but coded as 0, then a Block Mask is included. */ ossim_uint16 thePadPixelMaskRecordLength; /** * FIELD: TPXCDLNTH * * Transparent Output Pixel Code Length. * * 2 byte Unsigned binary integer; * 0x0000=No pad pixels; 0x0001 to 0x0010=pad pixel code length in bits * * This field is included if the IC value equals NM, M1, M3, M4, M5. * It identifies the length in bits of the Transparent Output Pixel Code. * If coded as 0, then no transparent pixels are present, * and the TPXCD field is not recorded. For IC value of M3, the * value shall be set to 0.. * */ ossim_uint16 theTransparentOutputPixelCodeLength; /** * FIELD: TPXCD * * Pad Output Pixel Code. * * This field is included if the IC value equals NM, M1, M3, M4, M5, M0 and * TPXCDLNTH is not 0. It contains the output pixel code that represents a * pad pixel in the image. This value is unique within the image, and * allows the user to identify pad pixels. The pad output pixel code * length is determined by TPXCDLNTH, but the value is stored in a maximum * of 2 bytes. If the number of bits used by TPXCD is less than the number * of bits available for storage, * the value shall be justified in accordance with the PJUST field in the * image subheader.   * 3A Binary integer; 0 to 2^n -1 where n=TPXCDLNTH */ ossim_uint16 thePadOutputPixelCode; std::vector theBlockMaskRecords; std::vector thePadPixelMaskRecords; ossimRefPtr theCompressionHeader; ossim_uint64 theDataLocation; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageLut.h000066400000000000000000000017561352751253100247620ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfImageLut_HEADER #define ossimNitfImageLut_HEADER 1 #include #include #include class ossimNitfImageLut : public ossimObject { public: friend std::ostream& operator <<(std::ostream& out, const ossimNitfImageLut &data); ossimNitfImageLut(); virtual ~ossimNitfImageLut(); virtual void parseStream(ossim::istream& in)=0; virtual std::ostream& print(std::ostream& out)const=0; virtual ossim_uint32 getNumberOfEntries()const=0; virtual void setNumberOfEntries(ossim_uint32 numberOfEntries)=0; virtual ossim_uint8 getValue(ossim_uint32 idx)const=0; TYPE_DATA; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageLutV2_0.h000066400000000000000000000017671352751253100254130ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfImageLutV2_0.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfImageLutV2_0_HEADER #define ossimNitfImageLutV2_0_HEADER #include #include class ossimNitfImageLutV2_0 : public ossimNitfImageLut { public: ossimNitfImageLutV2_0(); virtual ~ossimNitfImageLutV2_0(); virtual void parseStream(std::istream &in); virtual std::ostream& print(std::ostream& out)const; virtual ossim_uint32 getNumberOfEntries()const; virtual void setNumberOfEntries(ossim_uint32 numberOfEntries); virtual ossim_uint8 getValue(ossim_uint32 idx)const; protected: std::vector theData; ossim_uint32 theNumberOfEntries; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfImageLutV2_1.h000066400000000000000000000012521352751253100254010ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Nitf support class. Copied from ossimNitfImageLutV2_0. // //******************************************************************** // $Id: ossimNitfImageLutV2_1.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfImageLutV2_1_HEADER #define ossimNitfImageLutV2_1_HEADER #include class ossimNitfImageLutV2_1 : public ossimNitfImageLutV2_0 { public: ossimNitfImageLutV2_1(); virtual ~ossimNitfImageLutV2_1(); }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfInfo.h000066400000000000000000000030541352751253100241370ustar00rootroot00000000000000//--- // // License: MIT // // Description: NITF Info object. // //--- // $Id$ #ifndef ossimNitfInfo_HEADER #define ossimNitfInfo_HEADER 1 #include #include #include #include #include #include /** * @brief NITF info class. * * Encapsulates the dumpnitf functionality. */ class OSSIM_DLL ossimNitfInfo : public ossimInfoBase { public: /** default constructor */ ossimNitfInfo(); /** virtual destructor */ virtual ~ossimNitfInfo(); /** * @brief open method. * * @param file File name to open. * * @return true on success false on error. */ virtual bool open(const ossimFilename& file); virtual bool open(std::shared_ptr& str, const std::string& connectionString); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; /** * @brief Method to dump info to a keyword list. * @param kwl The keyword list to initialize. * @param entryIndex Entry to print. Not supported by all info objects * yet. * @return true on success, false on error. */ virtual bool getKeywordlist( ossimKeywordlist& kwl, ossim_uint32 entryIndex )const; private: std::shared_ptr m_nitfFile; }; #endif /* End of "#ifndef ossimNitfInfo_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfJ2klraTag.h000066400000000000000000000150541352751253100250300ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimNitfJ2klraTag.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: NITF J2KLRA tag. // // See: ISO/IEC BIIF Profile BPJ2K01.00 Table 9-3. // //---------------------------------------------------------------------------- // $Id$ #ifndef ossimNitfJ2klraTag_HEADER #define ossimNitfJ2klraTag_HEADER 1 #include #include #include #include class OSSIM_DLL ossimNitfJ2klraTag : public ossimNitfRegisteredTag { public: enum { ORIG_SIZE = 1, NLEVELS_O_SIZE = 2, NBANDS_O_SIZE = 5, NLAYERS_O_SIZE = 3, LAYER_ID_SIZE = 3, // repeating BITRATE_SIZE = 9, // repeating NLEVELS_I_SIZE = 2, // conditional NBANDS_I_SIZE = 5, // conditional NLAYERS_I_SIZE = 3 // conditional }; /** default constructor */ ossimNitfJ2klraTag(); /** * Parse method. * * @param in Stream to parse. */ virtual void parseStream(std::istream& in); /** * Write method. * * @param out Stream to write to. */ virtual void writeStream(std::ostream& out); /** @return The size of this record in bytes (123) within a nitf file. */ virtual ossim_uint32 getSizeInBytes()const; /** * Clears all string fields within the record to some default nothingness. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; /** @return ORIG field as a number. */ ossim_uint32 getOriginNumber() const; /** @return NLAYERS_O field as a number. */ ossim_uint32 getNumberOfLayersOriginal() const; /** * @brief Sets origin: * * Range is 0 to 9 * * 0 - Original NPJE * 1 – Parsed NPJE * 2 – Original EPJE * 3 – Parsed EPJE* * 4 - Original TPJE * 5 - Parsed TPJE * 6 - Original LPJE * 7 - Parsed LPJE * 8 – Original other * 9 – Parsed other * * @param origin 0 to 9 * @return true on success, false if out of range. */ bool setOrigin( ossim_uint32 origin ); /** * @brief Sets the number of wavelet levels in the original image. * * Range: 00 to 32 * @param levels * @return true on success, false if out of range. */ bool setLevelsO( ossim_uint32 levels ); /** * @brief Sets the number of bands in the original image. * * Range: 00001 to 16384 * * @param levels * @return true on success, false if out of range. */ bool setBandsO( ossim_uint32 bands ); /** * @brief Sets the number of layers in the original image. * * Range: 001 to 999 * * @param levels * @return true on success, false if out of range. */ bool setLayersO( ossim_uint32 layers ); /** * @brief Sets the number of wavelet levels in this image. * * Range: 00 to 32 * @param levels * @return true on success, false if out of range. */ bool setLevelsI( ossim_uint32 levels ); /** * @brief Sets the number of bands in this image. * * Range: 00001 to 16384 * * @param levels * @return true on success, false if out of range. */ bool setBandsI( ossim_uint32 bands ); /** * @brief Sets the number of layers in this image. * * Range: 001 to 999 * * @param levels * @return true on success, false if out of range. */ bool setLayersI( ossim_uint32 layers ); /** * @brief Sets the layer id for index. * * Range: 001 to 999 * * @note Requires call to "setLayersO" prior to this to size the container * m_layer. * * @param index * @param id * @return true on success, false if out of range. */ bool setLayerId( ossim_uint32 index, ossim_uint32 id ); /** * @brief Sets the bitrate from index. * * Range: 00.000000 – 37.000000 * * @note Requires call to "setLayersO" prior to this to size the container * m_layer. * * @param index * @param id * @return true on success, false if out of range. */ bool setLayerBitRate( ossim_uint32 index, ossim_float64 bitRate ); protected: /** * @return true if origin byte is parsed; false if not. */ bool isParsed() const; // Container for repeating fields. class ossimJ2klraLayer { public: /** * FIELD: LAYER_ID * required 3 byte field * 000 - 999 * Layer ID Number. Repeating. */ char m_layer_id[LAYER_ID_SIZE+1]; /** * FIELD: BITRATE * required 9 byte * 00.000000 – 37.000000 * Bitrate */ char m_bitrate[BITRATE_SIZE+1]; }; /** * FIELD: ORIG * * Required 1 byte. * * 0 - Original NPJE * 1 – Parsed NPJE * 2 – Original EPJE * 3 – Parsed EPJE* * 4 - Original TPJE * 5 - Parsed TPJE * 6 - Original LPJE * 7 - Parsed LPJE * 8 – Original other * 9 – Parsed other * * Original compressed data. */ char m_orig[ORIG_SIZE+1]; /** * FIELD: NLEVELS_O * required 2 bytes * 00 - 32 * Number of wavelet levels in original image. */ char m_levels_o[NLEVELS_O_SIZE+1]; /** * FIELD: NBANDS_O * required 5 bytes * 00000 - 16384 * Number of bands in original image. */ char m_bands_o[NBANDS_O_SIZE+1]; /** * FIELD: NLAYERS_O * required 3 bytes * 000 - 999 * Number of layers in original image. */ char m_layers_o[NLAYERS_O_SIZE+1]; /** repeating fields */ std::vector m_layer; /** * FIELD: NLEVELS_I * Conditional 2 bytes if ORIG=1, 3, or 9. * 00 - 32 * Number of wavelet levels in this image. */ char m_nlevels_i[NLEVELS_I_SIZE+1]; /** * FIELD: NBANDS_I * Conditional 5 bytes if ORIG=1, 3,or 9. * 00000 = 16384 * Number of bands in this image. */ char m_nbands_i[NBANDS_I_SIZE+1]; /** * FIELD: NLAYERS_I * Conditional 3 bytes if ORIG=1, 3, or 9. * 000 - 999 * Number of Layers in this image. */ char m_nlayers_i[NLAYERS_I_SIZE+1]; TYPE_DATA }; #endif /* End of "#ifndef ossimNitfJ2klraTag_HEADER_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfLabelHeader.h000066400000000000000000000015241352751253100253740ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfLabelHeader.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfLabelHeader_HEADER #define ossimNitfLabelHeader_HEADER #include #include class ossimDrect; class OSSIMDLLEXPORT ossimNitfLabelHeader : public ossimObject { public: ossimNitfLabelHeader(){} virtual ~ossimNitfLabelHeader(){} virtual void parseStream(std::istream &in)=0; virtual ossim_int32 getDisplayLevel()const=0; virtual ossimDrect getImageRect()const=0; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfLabelHeaderV2_0.h000066400000000000000000000066541352751253100260340ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfLabelHeaderV2_0.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfLabelHeaderV2_0_HEADER #define ossimNitfLabelHeaderV2_0_HEADER #include class OSSIMDLLEXPORT ossimNitfLabelHeaderV2_0 : public ossimNitfLabelHeader { public: ossimNitfLabelHeaderV2_0(); virtual ~ossimNitfLabelHeaderV2_0(){} virtual void parseStream(std::istream &in); virtual std::ostream& print(std::ostream &out)const; virtual ossim_int32 getDisplayLevel()const; virtual ossimDrect getImageRect()const; TYPE_DATA private: void clearFields(); /*! * This is a required 2 byte field and has the value * LA */ char theFilePartType[3]; /*! * This is a required 10 byte field. */ char theLabelId[11]; /*! * This is a required 1 byte field and will have * a value of either: * * T Top secret * S Secret * C Confidential * R Restricted * U Unclassified */ char theLabelSecurityClassification[2]; /*! * optional 40 byte field */ char theLabelCodewords[41]; /*! * optional 40 byte field */ char theLabelControlAndHandling[41]; /*! * optional 40 byte field */ char theLabelReleasingInstructions[41]; /*! * optional 20 byte field */ char theLabelClassificationAuthority[21]; /*! * optional 20 byte field */ char theLabelSecurityControlNumber[21]; /*! * optional 6 byte field */ char theLabelSecurityDowngrade[7]; /*! * conditional 40 byte field. It exists only if * theLabelSecurityDowngrade is = 999998 */ char theLabelDowngradingEvent[41]; /*! * required 1 byte field and can have value * 0 = not encrypted * 1 = encrypted */ char theLabelEncryption[2]; /*! * required 1 byte field. Is reserved for future * use. Will contain 1 blank. */ char theLabelFontStyle[2]; /*! * optional 2 byte field. Ranges from 1-99 */ char theLabelCellWidth[3]; /*! * optional 2 byte field. Ranges from 1-99 */ char theLabelCellHeight[3]; /*! * Required 3 byte field. Ranges from 1-999. */ char theLabelDisplayLevel[4]; /*! * Required 3 byte field. Ranges from 1-998. */ char theLabelAttachmentLevel[4]; /*! * Required 10 byte field. Has format: * * rrrrrccccc the first five chars is the row * location and the second is the * column location. */ char theLabelLocation[11]; /*! * Required 3 byte field. Has format: * * RGB First byte is red, second is blue, and * third is green */ char theLabelTextColor[4]; /*! * Required 3 byte field. Has format: * * RGB First byte is red, second is blue, and * third is green */ char theLabelBackgroundColor[4]; /*! * Required 5 byte field. Ranges from 0-09747 */ char theExtendedHeaderDataLength[6]; /*! * Conditional 3 byte field. Will exist if * theExtendedHeaderDataLength is not 0 */ char theExtendedSubheaderOverflow[4]; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfLocalCartographicTag.h000066400000000000000000000043611352751253100272630ustar00rootroot00000000000000#ifndef ossimNitfLocalCartographicTag_HEADER #define ossimNitfLocalCartographicTag_HEADER #include class ossimNitfLocalCartographicTag : public ossimNitfRegisteredTag { public: ossimNitfLocalCartographicTag(); virtual ~ossimNitfLocalCartographicTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual void clearFields(); void setLengthUnits(const ossimString& units); void setEastingInterval(ossim_uint32 eastingInterval); void setNorthingInterval(ossim_uint32 northingInterval); void setEastingReferenceOrigin(ossim_float64 east); void setNorthingReferenceOrigin(ossim_float64 north); protected: /** * FIELD: UNILOA * * required 3 byte field * * Length units * * This field shall contain the unit of measure used for * easting (LOD) and northing (LAD) intervals. The default value is M. * 3BCS-A See Part 3- 7 R */ char theLengthUnits[4]; /** * FIELD: LOD * * required 5 byte field * * Easting interval * * This field shall contain the data density in E-W direction * that is the column width of an image pixel. * 5 BCS-N positive integer 00001 to 99999 R */ char theEastingInterval[6]; /** * FIELD: LAD * * required 5 byte field * * Northing interval * * This field shall contain the data density in E-W direction * that is the column width of an image pixel. * 5 BCS-N positive integer 00001 to 99999 R */ char theNorthingInterval[6]; /** * FIELD: LSO * * required 15 byte field * * Easting of Reference Origin * * This field shall contain the easting of the * origin pixel (row number 0, column number 0) in the absolute coordinate system. * 15 BCS-N �mmmmmmmmmmmm.m */ char theEastingReferenceOrigin[16]; /** * FIELD: PSO * * required 15 byte field * * Northing of Reference Origin * * This field shall contain the northing of the * origin pixel (row number 0, column number 0) in the absolute coordinate system. * 15 BCS-N �mmmmmmmmmmmm.m */ char theNorthingReferenceOrigin[16]; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfMstgtaTag.h000066400000000000000000000101571352751253100251410ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: MSTGTA Mission Target Information Extension Format // tag class declaration. // // See document STDI-0002 Table 8-16 for more info. // //---------------------------------------------------------------------------- // $Id #ifndef ossimNitfMstgtaTag_HEADER #define ossimNitfMstgtaTag_HEADER 1 #include class OSSIM_DLL ossimNitfMstgtaTag : public ossimNitfRegisteredTag { public: enum { TGT_NUM_SIZE = 5, TGT_ID_SIZE = 12, TGT_BE_SIZE = 15, TGT_PRI_SIZE = 3, TGT_REQ_SIZE = 12, TGT_LTIOV_SIZE = 12, TGT_TYPE_SIZE = 1, TGT_COLL_SIZE = 1, TGT_CAT_SIZE = 5, TGT_UTC_SIZE = 7, TGT_ELEV_SIZE = 6, TGT_ELEV_UNIT_SIZE = 1, TGT_LOC_SIZE = 21 }; /** @brief default constructor */ ossimNitfMstgtaTag(); /** @brief destructor */ virtual ~ossimNitfMstgtaTag(); /** @brief Method to parse data from stream. */ virtual void parseStream(std::istream& in); /** @brief Method to write data to stream. */ virtual void writeStream(std::ostream& out); /** @brief Method to clear all fields including null terminating. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; protected: /** Type R = Required Type = BCS spaces allowed for entire field */ /** * FIELD: TGT_NUM * * TYPE: R * * 5 byte field * * 00001 ti 99999 */ char theTgtNum[TGT_NUM_SIZE+1]; /** * FIELD: TGT_ID * * TYPE: * * 12 byte field * * Disignator of Target, alphnumeric. */ char theTgtId[TGT_ID_SIZE+1]; /** * FIELD: TGT_BE * * TYPE: * * 15 byte field * * alphnumeric */ char theTgtBe[TGT_BE_SIZE+1]; /** * FIELD: TGT_PRI * * TYPE: * * 3 byte field * * Target priority, 1 = top, 2 = 2nd... 001 to 999 */ char theTgtPri[TGT_PRI_SIZE+1]; /** * FIELD: TGT_REQ * * TYPE: * * 12 byte field * * Target requester. alphnumeric */ char theTgtReq[TGT_REQ_SIZE+1]; /** * FIELD: TGT_LTIOV * * TYPE: * * 12 byte field * * Latest Time Information of Value CCYYMMDDhhmm */ char theTgtLtiov[TGT_LTIOV_SIZE+1]; /** * FIELD: TGT_TYPE * * TYPE: * * 1 byte field * * Pre-Planned Target Type: 0 = point, 1 = strip, 2 = area, 0 to 9. */ char theTgtType[TGT_TYPE_SIZE+1]; /** * FIELD: TGT_COLL * * TYPE: R * * 1 byte field * * Pre-Planned Collection Technique: 0 to 9 */ char theTgtColl[TGT_COLL_SIZE+1]; /** * FIELD: TGT_CAT * * TYPE: * * 5 byte field * * Target Functional Category Code 10000 to 99999 */ char theTgtCat[TGT_CAT_SIZE+1]; /** * FIELD: TGT_UTC * * TYPE: * * 7 byte field * * Planned Time at Target hhmmssZ */ char theTgtUtc[TGT_UTC_SIZE+1]; /** * FIELD: TGT_ELEV * * TYPE: * * 6 byte field * * Target Elevation -01000 to +30000 feet or meters */ char theTgtElev[TGT_ELEV_SIZE+1]; /** * FIELD: TGT_ELEV_UNIT * * TYPE: * * 1 byte field * * Unit of Target Elevation, f = feet, m = meters */ char theTgtElevUnit[TGT_ELEV_UNIT_SIZE+1]; /** * FIELD: TGT_LOC * * TYPE: R * * 21 byte field * * Target Location */ char theTgtLoc[TGT_LOC_SIZE+1]; TYPE_DATA }; #endif /* matches #ifndef ossimNitfMstgtaTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfNameConversionTables.h000066400000000000000000000017701352751253100273300ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2004 Garrett Potts. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimNitfNameConversionTables.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfNameConversionTables_HEADER #define ossimNitfNameConversionTables_HEADER #include class ossimString; class OSSIM_DLL ossimNitfNameConversionTables { public: ossimNitfNameConversionTables(); ossimString convertMapProjectionNameToNitfCode(const ossimString& mapProjectionName)const; ossimString convertNitfCodeToOssimProjectionName(const ossimString& nitfProjectionCode)const; ossimString convertNitfCodeToNitfProjectionName(const ossimString& nitfProjectionCode)const; ossimString convertNitfProjectionNameToNitfCode(const ossimString& nitfProjectionName)const; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfPiaimcTag.h000066400000000000000000000222061352751253100251020ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: PIAIMC tag class declaration. // // "Profile for Imagery Access Image Support Extensions" // // See document STDI-0002 Table 6-1 for more info. // // http://164.214.2.51/ntb/baseline/docs/stdi0002/final.pdf // //---------------------------------------------------------------------------- // $Id: ossimNitfPiaimcTag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfPiaimcTag_HEADER #define ossimNitfPiaimcTag_HEADER #include #include class ossimString; class OSSIM_DLL ossimNitfPiaimcTag : public ossimNitfRegisteredTag { public: enum { CLOUDCVR_SIZE = 3, SRP_SIZE = 1, SENSMODE_SIZE = 12, SENSNAME_SIZE = 18, SOURCE_SIZE = 255, COMGEN_SIZE = 2, SUBQUAL_SIZE = 1, PIAMSNNUM_SIZE = 7, CAMSPECS_SIZE = 32, PROJID_SIZE = 2, GENERATION_SIZE = 1, ESD_SIZE = 1, OTHERCOND_SIZE = 2, MEANGSD_SIZE = 7, IDATUM_SIZE = 3, IELLIP_SIZE = 3, PREPROC_SIZE = 2, IPROJ_SIZE = 2, SATTRACK_SIZE = 8 // ------- // 362 }; /** default constructor */ ossimNitfPiaimcTag(); /** * Parse method. * * @param in Stream to parse. */ virtual void parseStream(std::istream& in); /** * Write method. * * @param out Stream to write to. */ virtual void writeStream(std::ostream& out); /** * Clears all string fields within the record to some default nothingness. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; /** * @return CLOUDCVR field as an ossimString. */ ossimString getCloudcvrString() const; /** * @return SRP field as an ossimString. */ ossimString getSrpString() const; /** * @return SENSMODE field as an ossimString. */ ossimString getSensmodeString() const; /** * @return SENSNAME field as an ossimString. */ ossimString getSensnameString() const; /** * @return SOURCE field as an ossimString. */ ossimString getSourceString() const; /** * @return COMGEN field as an ossimString. */ ossimString getComgenString() const; /** * @return SUBQUAL field as an ossimString. */ ossimString getSubqualString() const; /** * @return PIAMSNNUM field as an ossimString. */ ossimString getPiamsnnumString() const; /** * @return field as an ossimString. */ ossimString getString() const; /** * @return CAMSPECS field as an ossimString. */ ossimString getCamspecsString() const; /** * @return PROJID field as an ossimString. */ ossimString getProjidString() const; /** * @return GENERATION field as an ossimString. */ ossimString getGenerationString() const; /** * @return ESD field as an ossimString. */ ossimString getEsdString() const; /** * @return OTHERCONDfield as an ossimString. */ ossimString getOthercondString() const; /** * @return MEANGSD field as an ossimString. */ ossimString getMeadGsdString() const; /** * @return MEANGSD field as a double converted to meters. * * @note Conversion used: gsd_in_meters = gsd / 12.0 * MTRS_PER_FT */ ossim_float64 getMeanGsdInMeters() const; /** * @return IDATUM field as an ossimString. */ ossimString getIdatumString() const; /** * @return IELLIP field as an ossimString. */ ossimString getIellipString() const; /** * @return PREPROC field as an ossimString. */ ossimString getPreprocString() const; /** * @return IPROJ field as an ossimString. */ ossimString getIprojString() const; /** * @return SATTRACK field as an ossimString. */ ossimString getSattrackString() const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; protected: /** * FIELD: CLOUDCVR * * 3 byte field * * Indicates the precentage of the image that is obscured by cloud. A value * os 999 indicates an unknown condition. * * 000 to 100, or 999 */ char theCloudcvr[CLOUDCVR_SIZE+1]; /** * FIELD: SRP * * 1 byte field * * Indicates whether or not standard radiometric product data is available. * * Y,N */ char theSrp[SRP_SIZE+1]; /** * FIELD: SENSMODE * * 12 byte field * * Indentifies the sensor mode used in capturing the image. * * WHISKBROOM, PUSHROOM, FRAMING, SPOT, SWATH, TBD */ char thesSensmode[SENSMODE_SIZE+1]; /** * FIELD: SENSNAME * * 18 byte field * * Indentifies the name of sensor used in capturing the image. * * USIGS DM, SENSORTYPE Name */ char theSensname[SENSNAME_SIZE+1]; /** * FIELD: SOURCE * * 18 byte field * * Indicated where the image came from. * * alphanumeric */ char theSource[SOURCE_SIZE+1]; /** * FIELD: COMGEN * * 2 byte field * * Compression Generation. * * 00 to 99 */ char theComgen[COMGEN_SIZE+1]; /** * FIELD: SUBQUAL * * 1 byte field * * Subjective Quality * * P-Poor, G-Good, E-Excellent, F-Fair */ char theSubqual[SUBQUAL_SIZE+1]; /** * FIELD: PIAMSNNUM * * 7 byte field * * Indicates the mission number assigned to the reconnaissance mission. * * EARS 1.1 page 4-28 */ char thePiamsnnum[PIAMSNNUM_SIZE+1]; /** * FIELD: CAMSPECS * * 32 byte field * * Specifies the brand name of the camera used and the focal length of the * lens. * * alphanumeric */ char theCamspecs[CAMSPECS_SIZE+1]; /** * FIELD: PROJID * * 2 byte field * * Indentifies collection platform project identifier code. * * EARS Appendix 9 */ char theProjid[PROJID_SIZE+1]; /** * FIELD: GENERATION * * 1 byte field * * Specifies the number of image generations of the product. The number(0) * is reserved for the original product. * * 0 to 9 */ char theGeneration[GENERATION_SIZE+1]; /** * FIELD: ESD * * 1 byte field * * Indicates whether or not Exploitation Support Data is available and * contained withing the product data. * * Y,N */ char theEsd[ESD_SIZE+1]; /** * FIELD: OTHERCOND * * 2 byte field * * Indicates other conditions that affect the imagery over the target. * * EARS 1.1 page 4 to 28 */ char theOthercond[OTHERCOND_SIZE+1]; /** * FIELD: MEANGSD * * 7 byte field * * The geometric mean of the across and along scan center-to-center distance * between contiguous ground samples. * * 00000.0 to 99999.9 Expressed in inches, accuracy=10% */ char theMeanGsd[MEANGSD_SIZE+1]; /** * FIELD: IDATUM * * 3 byte field * * Identifies the mathematical representation of the earth used to * geo-correct/or to rectify the image. * (Identifies the Datum assiciated with IGEOLO.) * * Horizontal_Reference_Datum_Code(refer to DDDS element) */ char theIdatum[IDATUM_SIZE+1]; /** * FIELD: IELLIP * * 3 byte field * * Identifies the mathematical representation of the earth used to * geo-correct/or to rectify the image. * (Identifies the Ellipsoid assiciated with IGEOLO.) */ char theIellip[IELLIP_SIZE+1]; /** * FIELD: PREPROC * * 2 byte field * * Identifies the level of radiometric and geometric processing applied to * the product by the commercial vendor. * * USIGS DM, IMAGEDATASET Processing Level Code. */ char thePreproc[PREPROC_SIZE+1]; /** * FIELD: IPROJ * * 2 byte field * * Identifies the 2D-map projection used by commercial vendors to * geo-correct/or to rectify the image. * * DIGEST, Part 3 table 6-1 */ char theIproj[IPROJ_SIZE+1]; /** * FIELD: SATTRACK * * 8 byte field * * Identifies location of an image acquired by LANDSAT or SPOT (only) along * the satellite path. * * Minimum values: * PATH(J)=0001 * ROW(K) =0001 * Maximum values: * PATH(J)=9999 * ROW(K) =9999 * * Recorded as PATH/ROW 00010001 */ char theSattrack[SATTRACK_SIZE+1]; TYPE_DATA }; #endif /* End of "#ifndef ossimNitfPiaimcTag_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfProjectionParameterTag.h000066400000000000000000000262021352751253100276550ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfProjectionParameterTag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfProjectionParameterTag_HEADER #define ossimNitfProjectionParameterTag_HEADER #include #include class OSSIM_DLL ossimNitfProjectionParameterTag : public ossimNitfRegisteredTag { public: ossimNitfProjectionParameterTag(); virtual ~ossimNitfProjectionParameterTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual ossim_uint32 getSizeInBytes()const; virtual void clearFields(); virtual void clearParameters(); virtual void addParameter(const ossimString& param); virtual void addParameter(const ossim_float64& param); void setName(const ossimString& name); void setCode(const ossimString& code); ossimString getName()const; ossimString getCode()const; void setFalseX(double falseX); void setFalseY(double falseY); double getFalseX()const; double getFalseY()const; protected: /** * FIELD: PRN * * required 80 byte field. * * Projection Name * * This field shall contain the name of the projection to which the Image Segment refers. * The default value is Transverse Mercator. */ char theProjectionName[81]; /** * * FIELD: PCO * * required 2 byte field. * * Projection Code * * This field shall contain the code of the projection to which the Image Segment refers. * The default value is TC. * * Code values: * * AC Albers Equal-Area Conic * Parameters: * 1. Longitude of origin * 2. std. parallel nearer to equator * 3. std parallel farther from equator * 4. latitude of origin * * AK (Lambert) Azimuthal Equal-Area * Parameters: * 1. Longitude of origin * 2. Latitude of origin * * AL Azimuthal Equidistant * Parameters: * 1. Longitude of origin * 2. Latitude of origin * * BF Bonne * Parameters: * 1. Longitude of origin * 2. Latitude of origin * 3. Scale factor at projection origin * * CC Equidistant Conic with 1 Standard Parallel * Parameters: * 1. Longitude of origin * 2. Latitude of origin * 3. Latitude of Std. Parallel * * CP Equirectangular * Parameters: * 1. Longitude of central meridian * 2. Latitude of true scale * 3. Radius of sphere * * CS Cassini-Soldner * Parameters: * 1. Longitude of origin * 2. Latitude of origin * * ED Eckert VI * Parameters: * 1. Longitude of origin * 2. Radius of sphere * * EF Eckert IV * Parameters: * 1. Longitude of origin * 2. Radius of sphere * * GN Gnomonic * Parameters: * 1. Longitude of origin * 2. Latitude of origin * * HX Hotine Oblique Mercator based on 2 Points * Parameters: * 1. Scale factor at projection origin * 2. latitude of projection origin * 3. longitude of first point defining center line * 4. latitude of fist point defining center line * * KA Equidistant Conic with 2 Standard Parallels * Parameters: * 1. Longitude of central meridian * 2. Latitude of origin * 3. Latitude of standard parallel Nearer to equator * 4. Latitude of standard parallel farther from equator * * LA Laborde * Parameters: * 1. Longitude of origin * 2. Latitude of origin * 3. Scale factor at proj origin * 4. Azimuth at origin of axis of constant scale * * LE Lambert Conformal Conic * Parameters: * 1. Longitude of origin * 2. std. parallel nearer to equator * 3. std. parallel farther from equator * 4. Latitude of origin * * LI Cylindrical Equal Area * Parameters: * 1. Longitude of central meridian * 2. Latitude of origin * * LJ Lambert Equal-Area Meridional * Parameters: * 1. Longitude of central meridian * 2. Latitude of origin * * MC Mercator * Parameters: * 1. Longitude of origin * 2. Latitude of true scale * 3. Latitude of reference origin * * MH Miller Cylindrical * Parameters: * 1. Longitude of central meridian * 2. Radius of sphere * * MJ French Lambert * Parameters: * 1. Longitude of origin * 2. Latitude of origin * 3. Scale factor at proj origin * * MP Mollweide * Parameters: * 1. Longitude of origin * 2. Radius of sphere * * NT New Zealand Map Grid * Parameters: * 1. Longitude of origin * 2. Latitude of origin * * OC Oblique Mercator * Parameters: * 1. Longitude of origin * 2. Latitude of origin * 3. Azimuth * 4. radius of sphere * * OD Orthographic * Parameters: * 1. Longitude of origin * 2. Latitude of origin * 3. Radius of sphere * * PG Polar Stereographic * Parameters: * 1. Latitude of true scale * * PH Polyconic * Parameters: * 1. Longitude of central meridian * 2. Latitude of origin * * RS or RB Hotine Oblique Mercator (Rectified Skew Orthomorphic) * Parameters: * 1. Longitude of origin * 2. Latitude of origin * 3. Azimuth East of North for Central Line (Skew X-Axis at Proj. origin) * 4. Scale factor at proj origin * * RX Robinson * Parameters: * 1. Longitude of origin * 2. Radius of sphere * * SA Sinusoidal * Parameters: * 1. Longitude of origin * 2. Radius of sphere * * SD Oblique Stereographic * Parameters: * 1. Longitude of origin * 2. Latitude of origin * 3. Scale factor at origin * * SX Space Oblique Mercator * Parameters: * 1. Application code: * 1 = Landsat, USGS equations * 2 = Landsat, EOSAT equations * 2. Vehicle number * 3. Orbital path number * * TC Transverse Mercator * Parameters: * 1. Longitude of central meridian * 2. Central Scale Factor * 3. Latitude of origin * * TX Transverse Cylindrical Equal Area * Parameters: * 1. Longitude of central meridian * 2. Latitude of origin * 3. Scale factor along central meridian * * VA Van der Grinten * Parameters: * 1. Longitude of central meridian * 2. Radius of sphere * * VX General Vertical NearSide Perspective * Parameters: * 1. Longitude of origin * 2. Latitude of origin * 3. Heigh of perspective map above surface * * ZY Other Known Projection */ char theProjectionCode[3]; /** * FIELD: NUM_PRJ * * required 1 byte field ranging from 0-9 * * Number of Projection Parameters * * This field shall contain the number of projection parameters. * The PRJ Field should be repeated as necessary depending on the * projection code (see Part 3-6). If the number of projection parameters * provided is lower than specified in Part 3-6, the * missing parameters value is 0. * */ char theNumberOfParameters[2]; /** * FIELD(S): PRJn * * Conditional 15 byte field each. * * Projection Parameter Each occurrence of this field provides an appropriate * parameter to accurately describe the projection. See Part 3-6 to know the * kind of parameters needed for each projection code. 15 BCS-N C */ std::vector theProjectionParameters; /** * FIELD: XOR * * required 15 byte field. * * Projection False X (Easting) Origin * * This field shall contain the projection false X (easting) origin. * The default value is 000000000000000, which implies that there is no projection false X origin. * */ char theFalseXOrigin[16]; /** * FIELD: YOR * * required 15 byte field. * * Projection False Y (Northing) Origin * * This field shall contain the projection false Y (northing) origin. * The default value is 000000000000000, which implies that there is * no projection false Y origin. * */ char theFalseYOrigin[16]; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRegisteredDes.h000066400000000000000000000072441352751253100260020ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRegisteredDes.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfRegisteredDes_HEADER #define ossimNitfRegisteredDes_HEADER 1 #include #include #include #include class ossimKeywordlist; class ossimString; class OSSIM_DLL ossimNitfRegisteredDes : public ossimObject , public ossimPropertyInterface { public: /** @brief default constructor */ ossimNitfRegisteredDes(); /** @brief Constructor that takes name and size. */ ossimNitfRegisteredDes(const std::string& desName, ossim_uint32 desLength); /** @brief destructor */ virtual ~ossimNitfRegisteredDes(); /** * @brief This will return the name of the registered des for this user * defined header. * * @note Deprecated - Use getDesName() */ virtual std::string getRegisterDesName() const; /** * @brief This will return the name of the registered des for this user * defined header. */ virtual const std::string& getDesName() const; /** * @param desName Name of des. * * @note Users should set des name as this is an unknown des. */ virtual void setDesName(const std::string& desName); /** * @brief Returns the length in bytes of the des from the CEL or REL field. * * @note Depricated use: getDesLength() * * The entire TRE length is 11 plus this(the size of the CEL or REL field). * * @return Length of REDATA or CEDATA. */ virtual ossim_uint32 getSizeInBytes()const; const std::vector& getDesDataBuffer()const; /** * @brief Returns the length in bytes of the des from the CEL or REL field. * * The entire TRE length is 11 plus this(the size of the CEL or REL field). * * @return Length of REDATA or CEDATA. */ virtual ossim_uint32 getDesLength() const; /** * @brief Set the des length. * * @param length Length of des. */ virtual void setDesLength(ossim_uint32 length); /** * This will allow the user defined data to parse the stream. */ virtual void parseStream(std::istream& in)=0; virtual void writeStream(std::ostream& out)=0; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * @brief Default interface to populate keyword list with metadata. * expample: country_code: US * This implementation does nothing. Derived classes should implement as * they see fit. * * @param kwl Keywordlist to populate with metadata. * * @param prefix Optional prefix to put in front of key, like: "image1.". */ virtual void getMetadata(ossimKeywordlist& kwl, const char* prefix=0) const; /** * @brief Pure virtual print method that outputs a key/value type format * adding prefix to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix)const; protected: ossimString m_desName; ossim_uint32 m_desLength; std::vector m_desData; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRegisteredDesFactory.h000066400000000000000000000015261352751253100273270ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // LICENSE: MIT see top level LICENSE.txt // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRegisteredDesFactory.h 22875 2014-08-27 13:52:03Z dburken $ #ifndef ossimNitfRegisteredDesFactory_HEADER #define ossimNitfRegisteredDesFactory_HEADER 1 #include class ossimNitfRegisteredDesFactory : public ossimNitfDesFactory { public: virtual ~ossimNitfRegisteredDesFactory(); static ossimNitfRegisteredDesFactory* instance(); virtual ossimRefPtr create(const ossimString &desName)const; protected: ossimNitfRegisteredDesFactory(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRegisteredTag.h000066400000000000000000000070641352751253100260020ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfRegisteredTag_HEADER #define ossimNitfRegisteredTag_HEADER 1 #include #include #include #include #include class ossimKeywordlist; class ossimString; class OSSIM_DLL ossimNitfRegisteredTag : public ossimObject , public ossimPropertyInterface { public: /** @brief default constructor */ ossimNitfRegisteredTag(); /** @brief Constructor that takes name and size. */ ossimNitfRegisteredTag(const std::string& tagName, ossim_uint32 tagLength); /** @brief destructor */ virtual ~ossimNitfRegisteredTag(); /** * @brief This will return the name of the registered tag for this user * defined header. * * @note Deprecated - Use getTagName() */ virtual std::string getRegisterTagName() const; /** * @brief This will return the name of the registered tag for this user * defined header. */ virtual const std::string& getTagName() const; /** * @param tagName Name of tag. * * @note Users should set tag name as this is an unknown tag. */ virtual void setTagName(const std::string& tagName); /** * @brief Returns the length in bytes of the tag from the CEL or REL field. * * @note Depricated use: getTagLength() * * The entire TRE length is 11 plus this(the size of the CEL or REL field). * * @return Length of REDATA or CEDATA. */ virtual ossim_uint32 getSizeInBytes()const; /** * @brief Returns the length in bytes of the tag from the CEL or REL field. * * The entire TRE length is 11 plus this(the size of the CEL or REL field). * * @return Length of REDATA or CEDATA. */ virtual ossim_uint32 getTagLength()const; /** * @brief Set the tag length. * * @param length Length of tag. */ virtual void setTagLength(ossim_uint32 length); /** * This will allow the user defined data to parse the stream. */ virtual void parseStream(ossim::istream& in)=0; virtual void writeStream(ossim::ostream& out)=0; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; /** * @brief Default interface to populate keyword list with metadata. * expample: country_code: US * This implementation does nothing. Derived classes should implement as * they see fit. * * @param kwl Keywordlist to populate with metadata. * * @param prefix Optional prefix to put in front of key, like: "image1.". */ virtual void getMetadata(ossimKeywordlist& kwl, const char* prefix=0) const; /** * @brief Pure virtual print method that outputs a key/value type format * adding prefix to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix)const; protected: std::string m_tagName; ossim_uint32 m_tagLength; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRegisteredTagFactory.h000066400000000000000000000015261352751253100273270ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // LICENSE: MIT see top level LICENSE.txt // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRegisteredTagFactory.h 22875 2014-08-27 13:52:03Z dburken $ #ifndef ossimNitfRegisteredTagFactory_HEADER #define ossimNitfRegisteredTagFactory_HEADER 1 #include class ossimNitfRegisteredTagFactory : public ossimNitfTagFactory { public: virtual ~ossimNitfRegisteredTagFactory(); static ossimNitfRegisteredTagFactory* instance(); virtual ossimRefPtr create(const ossimString &tagName)const; protected: ossimNitfRegisteredTagFactory(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRpcATag.h000066400000000000000000000015251352751253100245260ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 Intelligence Data Systems. // // LICENSE: MIT // // see top level LICENSE.txt // // Author: Garrett Potts // // Description: Nitf support class for RPC00A - // Rational Polynomial Coefficient extension. // //******************************************************************** // $Id: ossimNitfRpcATag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfRpcATag_HEADER #define ossimNitfRpcATag_HEADER 1 #include /** * The layout of RPC00B is the same as RPC00A. The difference is how the * coefficients are used; hence, all the code is in the ossimNitfRpcBase class. */ class OSSIM_DLL ossimNitfRpcATag : public ossimNitfRpcBase { public: ossimNitfRpcATag(); protected: TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRpcBTag.h000066400000000000000000000014021352751253100245210ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 Intelligence Data Systems. // // LICENSE: MIT // // see top level LICENSE.txt // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRpcBTag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfRpcBTag_HEADER #define ossimNitfRpcBTag_HEADER 1 #include /** * The layout of RPC00B is the same as RPC00A. The difference is how the * coefficients are used; hence, all the code is in the ossimNitfRpcBase class. */ class OSSIM_DLL ossimNitfRpcBTag : public ossimNitfRpcBase { public: ossimNitfRpcBTag(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRpcBase.h000066400000000000000000000360141352751253100245650ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf base support data class for RPC tags. // // Rational Polynomial Coefficient extension. // // See: http://164.214.2.51/ntb/baseline/docs/stdi0002/final.pdf // //******************************************************************** // $Id: ossimNitfRpcBase.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfRpcBase_HEADER #define ossimNitfRpcBase_HEADER 1 #include #include class OSSIM_DLL ossimNitfRpcBase : public ossimNitfRegisteredTag { public: enum { SUCCESS_SIZE = 1, ERROR_BIAS_SIZE = 7, ERR_RAND_SIZE = 7, LINE_OFFSET_SIZE = 6, SAMPLE_OFFSET_SIZE = 5, GEODETIC_LAT_OFFSET_SIZE = 8, GEODETIC_LON_OFFSET_SIZE = 9, GEODETIC_HEIGHT_OFFSET_SIZE = 5, LINE_SCALE_SIZE = 6, SAMPLE_SCALE_SIZE = 5, GEODETIC_LAT_SCALE_SIZE = 8, GEODETIC_LON_SCALE_SIZE = 9, GEODETIC_HEIGHT_SCALE_SIZE = 5, LINE_NUMERATOR_COEFFICIENT_SIZE = 12, LINE_NUMERATOR_COEFFICIENT_COUNT = 20, LINE_DENOMINATOR_COEFFICIENT_SIZE = 12, LINE_DENOMINATOR_COEFFICIENT_COUNT = 20, SAMPLE_NUMERATOR_COEFFICIENT_SIZE = 12, SAMPLE_NUMERATOR_COEFFICIENT_COUNT = 20, SAMPLE_DENOMINATOR_COEFFICIENT_SIZE = 12, SAMPLE_DENOMINATOR_COEFFICIENT_COUNT = 20 // ----- // 1041 }; /** default constructor */ ossimNitfRpcBase(); /** * Parse method. * * @param in Stream to parse. */ virtual void parseStream(std::istream& in); /** * Write method. * * @param out Stream to write to. */ virtual void writeStream(std::ostream& out); /** * Clears all string fields within the record to some default nothingness. */ virtual void clearFields(); /** * For generating the RPC tag from existing RPC Model. */ virtual void setRpcModelParams(ossimRefPtr rpc); /** * @return The success record as a boolean. */ bool getSuccess()const; /** @param success Sets data member theSuccess to success. */ void setSuccess(bool success); /** @return theErrorBias as a string. */ ossimString getErrorBias()const; //--- // The set methods below taking ossimString args will truncate and // pad with spaces, as necessary, to match enumed size. //--- /** * @param errorBias Error bias to set theErrorBias to. This will be * converted to a string with two digit precision. */ void setErrorBias(const ossim_float64& errorBias); /** @param errorBias bias string to set theErrorBias to. */ void setErrorBias(const ossimString& errorBias); /** @return theErrorBias as a string. */ ossimString getErrorRand()const; /** * @param errorRand The random error to set theErrRand to. This will be * converted to a string with two digit precision. */ void setErrorRand(const ossim_float64& errorRand); /** @param errorRand error random string to set theErrorRand to. */ void setErrorRand(const ossimString& errorRand); /** @return The line offset as a string. */ ossimString getLineOffset()const; /** * @param lineOffset Sets the line offset to a string truncated to an int. */ void setLineOffset(ossim_uint32 lineOffset); /** * @param lineOffset Sets theLineOffset to lineOffset string. */ void setLineOffset(const ossimString& lineOffset); /** @return The sample offset as a string. */ ossimString getSampleOffset()const; /** * @param sampleOffset Sets the sample offset to a string truncated to an * int. */ void setSampleOffset(ossim_uint32 sampleOffset); /** @param sampleOffset Sets the sample offset to a string. */ void setSampleOffset(const ossimString& sampleOffset); /** @return Geodetic latitude offset as a string. */ ossimString getGeodeticLatOffset()const; /** * @param geodeticLatOffset Value to Set the geodedic latitude offset to. * Converted to a string with four digit precision. */ void setGeodeticLatOffset(const ossim_float64& geodeticLatOffset); /** * @param geodeticLatOffset geodedic latitude offset string to set * theGeodeticLatOffset to. */ void setGeodeticLatOffset(const ossimString& geodeticLatOffset); /** @return Geodetic longitude offset as a string. */ ossimString getGeodeticLonOffset()const; /** * @param geodeticLonOffset Value to Set the geodedic longitude offset to. * Converted to a string with four digit precision. */ void setGeodeticLonOffset(const ossim_float64& geodeticLonOffset); /** * @param geodeticLonOffset Value to Set the geodedic longitude offset to. */ void setGeodeticLonOffset(const ossimString& geodeticLonOffset); /** @return Geodetic height offset as a string. */ ossimString getGeodeticHeightOffset()const; /** * @param geodeticHeightOffset value to Set the height offset to. * Converted to a string truncated to an int. */ void setGeodeticHeightOffset(ossim_int32 geodeticHeightOffset); /** @param geodeticHeightOffset value to Set the height offset to. */ void setGeodeticHeightOffset(const ossimString& geodeticHeightOffset); /** @return The line scale as a string. */ ossimString getLineScale()const; /** * @param lineScale The value to set the line scale to. * Converted to a string. */ void setLineScale(ossim_uint32 lineScale); /** * @param lineScale The value to set the line scale to. */ void setLineScale(const ossimString& lineScale); /** * @return the sample scale as a string. */ ossimString getSampleScale()const; /** * @param sampleScale The value to set the sample scale to. * Converted to a string truncated to an int. */ void setSampleScale(ossim_uint32 sampleScale); /** * @param sampleScale The value to set the sample scale to. */ void setSampleScale(const ossimString& sampleScale); /** @return The Geodetic latitude scale as a string. */ ossimString getGeodeticLatScale()const; /** * @param geodeticLatScale The value to set the geodedic latitude scale to. * Converted to a string with four digit precision. */ void setGeodeticLatScale(const ossim_float64& geodeticLatScale); /** * @param geodeticLatScale The value to set the geodedic latitude scale to. */ void setGeodeticLatScale(const ossimString& geodeticLatScale); /** @return Geodetic longitude scale as a string. */ ossimString getGeodeticLonScale()const; /** * @param geodeticLonScale The value to set the geodedic longitude scale to. * Converted to a string with four digit precision. */ void setGeodeticLonScale(const ossim_float64& geodeticLonScale); /** * @param geodeticLonScale The value to set the geodedic longitude scale to. */ void setGeodeticLonScale(const ossimString& geodeticLonScale); /** @return The geodetic height scale as a string. */ ossimString getGeodeticHeightScale()const; /** * @param geodeticHeightScale The value to set the height scale to. * Converted to a string truncated to an int. */ void setGeodeticHeightScale(ossim_int32 geodeticHeightScale); /** * @param geodeticHeightScale The value to set the height scale to. */ void setGeodeticHeightScale(const ossimString& geodeticHeightScale); /** * @param idx Index of line numerator coefficient to get. * Range: 0 - 19 * * @return The line numerator coefficient as a string. */ ossimString getLineNumeratorCoeff(ossim_uint32 idx)const; /** * @param coeff This should be an array of 20 line numerator coefficients. * Coefficients will be converted to a scientific string to conform to * specification. * * @note if (coeff.size() != 20) no action is taken. */ void setLineNumeratorCoeff(const std::vector& coeff); /** * @param idx index of line numerator coefficient to set. * Range: 0 - 19 * * @param coeff Value to set line numerator coefficient to for * idx or index. */ void setLineNumeratorCoeff(ossim_uint32 idx, const ossimString& coeff); /** * @param idx index of line denominator coefficient to get. * Range: 0 - 19 * * @return line denominator coefficient as a string. */ ossimString getLineDenominatorCoeff(ossim_uint32 idx)const; /** * @param coeff This should be an array of 20 line denominator coefficients. * Coefficients will be converted to a scientific string to conform to * specification. * * @note if (coeff.size() != 20) no action is taken. */ void setLineDenominatorCoeff(const std::vector& coeff); /** * @param idx index of line denominator coefficient to set. * Range: 0 - 19 * * @param lineDenominatorCoeff Value to set line denominator coefficient * to for idx or index. */ void setLineDenominatorCoeff(ossim_uint32 idx, const ossimString& coeff); /** * @param idx Index of sample numerator coefficient to get. * Range: 0 - 19 * * @return The sample numerator coefficient as a string. */ ossimString getSampleNumeratorCoeff(ossim_uint32 idx)const; /** * @param coeff This should be an array of 20 sample numerator coefficients. * Coefficients will be converted to a scientific string to conform to * specification. * * @note if (coeff.size() != 20) no action is taken. */ void setSampleNumeratorCoeff(const std::vector& coeff); /** * @param idx index of sample numerator coefficient to set. * Range: 0 - 19 * * @param coeff Value to set sample numerator coefficient to for * idx or index. */ void setSampleNumeratorCoeff(ossim_uint32 idx, const ossimString& coeff); /** * @param idx index of sample denominator coefficient to get. * Range: 0 - 19 * * @return sample denominator coefficient as a string. */ ossimString getSampleDenominatorCoeff(ossim_uint32 idx)const; /** * @param coeff This should be an array of 20 sample denominator coefficients. * Coefficients will be converted to a scientific string to conform to * specification. * * @note if (coeff.size() != 20) no action is taken. */ void setSampleDenominatorCoeff(const std::vector& coeff); /** * @param idx index of sample denominator coefficient to set. * Range: 0 - 19 * * @param sampleDenominatorCoeff Value to set sample denominator coefficient * to for idx or index. */ void setSampleDenominatorCoeff(ossim_uint32 idx, const ossimString& coeff); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; bool loadState(const ossimKeywordlist& kwl, const char* prefix); protected: /** * FIELD: SUCCESS * * Required 1 byte field. * * Value is 1 * */ char theSuccess[SUCCESS_SIZE+1]; /** * FIELD: ERR_BIAS * * required 7 byte field * * Error - Bias. 68% non time-varying error estimate assumes * correlated images. * * Values range from 0000.00 to 9999.99 meters */ char theErrorBias[ERROR_BIAS_SIZE+1]; /** * FIELD ERR_RAND * * Required 7 byte field * * Error - Random. 68% time-varying error estimate assumes * correlated images. 0000.00 to 9999.99 meters */ char theErrRand[ERR_RAND_SIZE+1]; /** * FIELD: LINE_OFF * * required 6 byte field. * * value is in pixels and ranges from 000000-999999 */ char theLineOffset[LINE_OFFSET_SIZE+1]; /** * FIELD: SAMP_OFF * * required 5 byte field. * * value is in pixels and ranges from 00000-99999 */ char theSampleOffset[SAMPLE_OFFSET_SIZE+1]; /** * FIELD: LAT_OFF * * required 8 byte field. * * Holds the lat offset in degrees and ranges from +-90.0000 */ char theGeodeticLatOffset[GEODETIC_LAT_OFFSET_SIZE+1]; /** * FIELD: LONG_OFF * * required 9 byte field. * * holds the lon offset in degrees and ranges from +-180.0000 */ char theGeodeticLonOffset[GEODETIC_LON_OFFSET_SIZE+1]; /** * FIELD: HEIGHT_OFF * * required 5 byte field. * * holds the height offset in meters and ranges from +-9999 */ char theGeodeticHeightOffset[GEODETIC_HEIGHT_OFFSET_SIZE+1]; /** * FIELD: LINE_SCALE * * required 6 byte field. * * holds the line scale in pixels and ranges from 000001-999999 * */ char theLineScale[LINE_SCALE_SIZE+1]; /** * FIELD: SAMP_SCALE * * required 5 byte field. * * holds the line scale in pixels and ranges from 00001-99999 * */ char theSampleScale[SAMPLE_SCALE_SIZE+1]; /** * FIELD: LAT_SCALE * * required 8 byte field * * holds the lat scale in degrees and ranges from +-90.0000 degrees */ char theGeodeticLatScale[GEODETIC_LAT_SCALE_SIZE+1]; /** * FIELD: LON_SCALE * * required 9 byte field * * holds the lon scale in degrees and ranges from +-180.0000 degrees */ char theGeodeticLonScale[GEODETIC_LON_SCALE_SIZE+1]; /** * FIELD: HEIGHT_SCALE * * required 5 byte field * * holds the geodetic height scale and ranges from +-9999 meters. */ char theGeodeticHeightScale[GEODETIC_HEIGHT_SCALE_SIZE+1]; /** * FIELD: LINE_NUM_COEFF_1 through LINE_NUM_COEFF_20 * * Line Numerator Coefficients. * * required 12 byte field ranging �0.999999E�9 Twenty coefficients for the * polynomial * */ std::vector theLineNumeratorCoefficient; /** * FIELD: LINE_DEN_COEFF_1 through LINE_DEN_COEFF_20 * * Line Denominato Coefficients. * * required 12 byte field ranging �0.999999E�9 Twenty coefficients for the * polynomial * */ std::vector theLineDenominatorCoefficient; /** * FIELD: SAMP_NUM_COEFF_1 through SAMP_NUM_COEFF_20 * * samp Numerator Coefficients. * * required 12 byte field ranging �0.999999E�9 Twenty coefficients for the * polynomial * */ std::vector theSampleNumeratorCoefficient; /** * FIELD: SAMP_DEN_COEFF_1 through SAMP_DEN_COEFF_20 * * samp Denominator Coefficients. * * required 12 byte field ranging �0.999999E�9 Twenty coefficients for the * polynomial * */ std::vector theSampleDenominatorCoefficient; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRpfTagFactory.h000066400000000000000000000020561352751253100257600ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // LICENSE: MIT see top level LICENSE.txt // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRpfTagFactory.h 22875 2014-08-27 13:52:03Z dburken $ #ifndef ossimNitfRpfTagFactory_HEADER #define ossimNitfRpfTagFactory_HEADER 1 #include class ossimNitfRegisteredTag; class ossimNitfRpfTagFactory : public ossimNitfTagFactory { public: virtual ~ossimNitfRpfTagFactory(); static ossimNitfRpfTagFactory* instance(); virtual ossimRefPtr create(const ossimString &tagName)const; protected: ossimNitfRpfTagFactory(); private: /*! * Hide this. */ ossimNitfRpfTagFactory(const ossimNitfRpfTagFactory & /* rhs */){} /*! * Hide this. */ ossimNitfRpfTagFactory& operator =(const ossimNitfRpfTagFactory & /* rhs */){return *this;} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRsmecaTag.h000066400000000000000000000153251352751253100251160ustar00rootroot00000000000000//--- // File: ossimNitfRsmecaTag.h //--- #ifndef ossimNitfRsmecaTag_HEADER #define ossimNitfRsmecaTag_HEADER 1 #include #include /** * @class ossimNitfRsmecaIsg * RSM Error Covariance: RSM indirect error covariance data. * RFC NTB 055, STDI-0002-1 v4.0, Appendix U: RSM */ class ossimNitfRsmecaIsg { public: enum { NUMOPG_SIZE = 2, FLOAT21_SIZE = 21, TCDF_SIZE = 1, NCSEG_SIZE = 1 }; ossimNitfRsmecaIsg(); /** @brief copy constructor */ ossimNitfRsmecaIsg(const ossimNitfRsmecaIsg& obj); /** @brief assignment operator */ const ossimNitfRsmecaIsg& operator=(const ossimNitfRsmecaIsg& rhs); void parseStream(std::istream& in); void writeStream(std::ostream& out); void clearFields(); std::ostream& print( std::ostream& out, const std::string& prefix=std::string(), ossim_uint32 index=0) const; protected: char m_numopg[NUMOPG_SIZE+1]; std::vector m_errcvg; char m_tcdf[TCDF_SIZE+1]; char m_ncseg[NCSEG_SIZE+1]; std::vector m_corseg; std::vector m_tauseg; ossim_uint32 m_errCovNum; ossim_uint32 m_opgNum; ossim_uint32 m_corSegNum; }; class OSSIM_DLL ossimNitfRsmecaTag : public ossimNitfRegisteredTag { public: enum { IID_SIZE = 80, EDITION_SIZE = 40, TID_SIZE = 40, INCLIC_SIZE = 1, INCLUC_SIZE = 1, NPAR_SIZE = 2, NPARO_SIZE = 2, IGN_SIZE = 2, CVDATE_SIZE = 8, FLOAT21_SIZE = 21, IR_SIZE = 2, IC_SIZE = 2, G_SIZE = 2, NUMOPG_SIZE = 2, TCDF_SIZE = 1, NCSEG_SIZE = 1, UNCSR_SIZE = 1, UNCSC_SIZE = 1 }; ossimNitfRsmecaTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual void clearFields(); virtual std::ostream& print( std::ostream& out, const std::string& prefix=std::string() ) const; ossimString getIid() const; ossimString getEdition() const; ossimString getTid() const; ossimString getInclic() const; ossimString getIncluc() const; ossimString getNpar() const; ossimString getNparo() const; ossimString getIgn() const; ossimString getCvdate() const; ossimString getXuol() const; ossimString getYuol() const; ossimString getZuol() const; ossimString getXuxl() const; ossimString getXuyl() const; ossimString getXuzl() const; ossimString getYuxl() const; ossimString getYuyl() const; ossimString getYuzl() const; ossimString getZuxl() const; ossimString getZuyl() const; ossimString getZuzl() const; ossimString getIro() const; ossimString getIrx() const; ossimString getIry() const; ossimString getIrz() const; ossimString getIrxx() const; ossimString getIrxy() const; ossimString getIrxz() const; ossimString getIryy() const; ossimString getIryz() const; ossimString getIrzz() const; ossimString getIco() const; ossimString getIcx() const; ossimString getIcy() const; ossimString getIcz() const; ossimString getIcxx() const; ossimString getIcxy() const; ossimString getIcxz() const; ossimString getIcyy() const; ossimString getIcyz() const; ossimString getIczz() const; ossimString getGxo() const; ossimString getGyo() const; ossimString getGzo() const; ossimString getGxr() const; ossimString getGyr() const; ossimString getGzr() const; ossimString getGs() const; ossimString getGxx() const; ossimString getGxy() const; ossimString getGxz() const; ossimString getGyx() const; ossimString getGyy() const; ossimString getGyz() const; ossimString getGzx() const; ossimString getGzy() const; ossimString getGzz() const; ossimNitfRsmecaIsg getIsg(ossim_uint32 index) const; ossimString getMap(ossim_uint32 index) const; ossimString getUrr() const; ossimString getUrc() const; ossimString getUcc() const; ossimString getUncsr() const; ossimString getUcorsr(ossim_uint32 index) const; ossimString getUtausr(ossim_uint32 index) const; ossimString getUncsc() const; ossimString getUcorsc(ossim_uint32 index) const; ossimString getUtausc(ossim_uint32 index) const; bool getInclicFlag() const; bool getInclucFlag() const; ossimString getIgnNum() const; ossimString getMapNum() const; ossimString getRowCorSegNum() const; ossimString getColCorSegNum() const; protected: char m_iid[IID_SIZE+1]; char m_edition[EDITION_SIZE+1]; char m_tid[TID_SIZE+1]; char m_inclic[INCLIC_SIZE+1]; char m_incluc[INCLUC_SIZE+1]; char m_npar[NPAR_SIZE+1]; char m_nparo[NPARO_SIZE+1]; char m_ign[IGN_SIZE+1]; char m_cvdate[CVDATE_SIZE+1]; char m_xuol[FLOAT21_SIZE+1]; char m_yuol[FLOAT21_SIZE+1]; char m_zuol[FLOAT21_SIZE+1]; char m_xuxl[FLOAT21_SIZE+1]; char m_xuyl[FLOAT21_SIZE+1]; char m_xuzl[FLOAT21_SIZE+1]; char m_yuxl[FLOAT21_SIZE+1]; char m_yuyl[FLOAT21_SIZE+1]; char m_yuzl[FLOAT21_SIZE+1]; char m_zuxl[FLOAT21_SIZE+1]; char m_zuyl[FLOAT21_SIZE+1]; char m_zuzl[FLOAT21_SIZE+1]; char m_iro[IR_SIZE+1]; char m_irx[IR_SIZE+1]; char m_iry[IR_SIZE+1]; char m_irz[IR_SIZE+1]; char m_irxx[IR_SIZE+1]; char m_irxy[IR_SIZE+1]; char m_irxz[IR_SIZE+1]; char m_iryy[IR_SIZE+1]; char m_iryz[IR_SIZE+1]; char m_irzz[IR_SIZE+1]; char m_ico[IC_SIZE+1]; char m_icx[IC_SIZE+1]; char m_icy[IC_SIZE+1]; char m_icz[IC_SIZE+1]; char m_icxx[IC_SIZE+1]; char m_icxy[IC_SIZE+1]; char m_icxz[IC_SIZE+1]; char m_icyy[IC_SIZE+1]; char m_icyz[IC_SIZE+1]; char m_iczz[IC_SIZE+1]; char m_gxo[G_SIZE+1]; char m_gyo[G_SIZE+1]; char m_gzo[G_SIZE+1]; char m_gxr[G_SIZE+1]; char m_gyr[G_SIZE+1]; char m_gzr[G_SIZE+1]; char m_gs[G_SIZE+1]; char m_gxx[G_SIZE+1]; char m_gxy[G_SIZE+1]; char m_gxz[G_SIZE+1]; char m_gyx[G_SIZE+1]; char m_gyy[G_SIZE+1]; char m_gyz[G_SIZE+1]; char m_gzx[G_SIZE+1]; char m_gzy[G_SIZE+1]; char m_gzz[G_SIZE+1]; std::vector m_isg; std::vector m_map; char m_urr[FLOAT21_SIZE+1]; char m_urc[FLOAT21_SIZE+1]; char m_ucc[FLOAT21_SIZE+1]; char m_uncsr[2]; std::vector m_ucorsr; std::vector m_utausr; char m_uncsc[2]; std::vector m_ucorsc; std::vector m_utausc; bool m_inclicFlag; bool m_inclucFlag; ossim_uint32 m_ignNum; ossim_uint32 m_mapNum; ossim_uint32 m_rowCorSegNum; ossim_uint32 m_colCorSegNum; TYPE_DATA }; // End: class ossimNitfRsmecaTag #endif /* #ifndef ossimNitfRsmecaTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRsmidaTag.h000066400000000000000000000144061352751253100251220ustar00rootroot00000000000000//--- // File: ossimNitfRsmidaTag.h //--- #ifndef ossimNitfRsmidaTag_HEADER #define ossimNitfRsmidaTag_HEADER 1 #include /** * @class ossimNitfRsmidaTag * RSM Identification: Id's, time-of-image model, optional illumination model, * footprint information. */ class OSSIM_DLL ossimNitfRsmidaTag : public ossimNitfRegisteredTag { public: enum { IID_SIZE = 80, EDITION_SIZE = 40, ISID_SIZE = 40, SID_SIZE = 40, STID_SIZE = 40, YEAR_SIZE = 4, MONTH_SIZE = 2, DAY_SIZE = 2, HOUR_SIZE = 2, MINUTE_SIZE = 2, SECOND_SIZE = 9, NRG_SIZE = 8, NCG_SIZE = 8, FLOAT21_SIZE = 21, GRNDD_SIZE = 1, FULL_SIZE = 8, MIN_SIZE = 8, MAX_SIZE = 8, CEL_SIZE = 1628 }; ossimNitfRsmidaTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void clearFields(); ossimString getIid() const; ossimString getEdition() const; ossimString getIsid() const; ossimString getSid() const; ossimString getStid() const; ossimString getYear() const; ossimString getMonth() const; ossimString getDay() const; ossimString getHour() const; ossimString getMinute() const; ossimString getSecond() const; ossimString getNrg() const; ossimString getNcg() const; ossimString getTrg() const; ossimString getTcg() const; ossimString getGrndd() const; ossimString getXuor() const; ossimString getYuor() const; ossimString getZuor() const; ossimString getXuxr() const; ossimString getXuyr() const; ossimString getXuzr() const; ossimString getYuxr() const; ossimString getYuyr() const; ossimString getYuzr() const; ossimString getZuxr() const; ossimString getZuyr() const; ossimString getZuzr() const; ossimString getV1x() const; ossimString getV1y() const; ossimString getV1z() const; ossimString getV2x() const; ossimString getV2y() const; ossimString getV2z() const; ossimString getV3x() const; ossimString getV3y() const; ossimString getV3z() const; ossimString getV4x() const; ossimString getV4y() const; ossimString getV4z() const; ossimString getV5x() const; ossimString getV5y() const; ossimString getV5z() const; ossimString getV6x() const; ossimString getV6y() const; ossimString getV6z() const; ossimString getV7x() const; ossimString getV7y() const; ossimString getV7z() const; ossimString getV8x() const; ossimString getV8y() const; ossimString getV8z() const; ossimString getGrpx() const; ossimString getGrpy() const; ossimString getGrpz() const; ossimString getFullr() const; ossimString getFullc() const; ossimString getMinr() const; ossimString getMaxr() const; ossimString getMinc() const; ossimString getMaxc() const; ossimString getIe0() const; ossimString getIer() const; ossimString getIec() const; ossimString getIerr() const; ossimString getIerc() const; ossimString getIecc() const; ossimString getIa0() const; ossimString getIar() const; ossimString getIac() const; ossimString getIarr() const; ossimString getIarc() const; ossimString getIacc() const; ossimString getSpx() const; ossimString getSvx() const; ossimString getSax() const; ossimString getSpy() const; ossimString getSvy() const; ossimString getSay() const; ossimString getSpz() const; ossimString getSvz() const; ossimString getSaz() const; protected: char m_iid[IID_SIZE+1]; char m_edition[EDITION_SIZE+1]; char m_isid[ISID_SIZE+1]; char m_sid[SID_SIZE+1]; char m_stid[STID_SIZE+1]; char m_year[YEAR_SIZE+1]; char m_month[MONTH_SIZE+1]; char m_day[DAY_SIZE+1]; char m_hour[HOUR_SIZE+1]; char m_minute[MINUTE_SIZE+1]; char m_second[SECOND_SIZE+1]; char m_nrg[NRG_SIZE+1]; char m_ncg[NCG_SIZE+1]; char m_trg[FLOAT21_SIZE+1]; char m_tcg[FLOAT21_SIZE+1]; char m_grndd[GRNDD_SIZE+1]; char m_xuor[FLOAT21_SIZE+1]; char m_yuor[FLOAT21_SIZE+1]; char m_zuor[FLOAT21_SIZE+1]; char m_xuxr[FLOAT21_SIZE+1]; char m_xuyr[FLOAT21_SIZE+1]; char m_xuzr[FLOAT21_SIZE+1]; char m_yuxr[FLOAT21_SIZE+1]; char m_yuyr[FLOAT21_SIZE+1]; char m_yuzr[FLOAT21_SIZE+1]; char m_zuxr[FLOAT21_SIZE+1]; char m_zuyr[FLOAT21_SIZE+1]; char m_zuzr[FLOAT21_SIZE+1]; char m_v1x[FLOAT21_SIZE+1]; char m_v1y[FLOAT21_SIZE+1]; char m_v1z[FLOAT21_SIZE+1]; char m_v2x[FLOAT21_SIZE+1]; char m_v2y[FLOAT21_SIZE+1]; char m_v2z[FLOAT21_SIZE+1]; char m_v3x[FLOAT21_SIZE+1]; char m_v3y[FLOAT21_SIZE+1]; char m_v3z[FLOAT21_SIZE+1]; char m_v4x[FLOAT21_SIZE+1]; char m_v4y[FLOAT21_SIZE+1]; char m_v4z[FLOAT21_SIZE+1]; char m_v5x[FLOAT21_SIZE+1]; char m_v5y[FLOAT21_SIZE+1]; char m_v5z[FLOAT21_SIZE+1]; char m_v6x[FLOAT21_SIZE+1]; char m_v6y[FLOAT21_SIZE+1]; char m_v6z[FLOAT21_SIZE+1]; char m_v7x[FLOAT21_SIZE+1]; char m_v7y[FLOAT21_SIZE+1]; char m_v7z[FLOAT21_SIZE+1]; char m_v8x[FLOAT21_SIZE+1]; char m_v8y[FLOAT21_SIZE+1]; char m_v8z[FLOAT21_SIZE+1]; char m_grpx[FLOAT21_SIZE+1]; char m_grpy[FLOAT21_SIZE+1]; char m_grpz[FLOAT21_SIZE+1]; char m_fullr[FULL_SIZE+1]; char m_fullc[FULL_SIZE+1]; char m_minr[MIN_SIZE+1]; char m_maxr[MAX_SIZE+1]; char m_minc[MIN_SIZE+1]; char m_maxc[MAX_SIZE+1]; char m_ie0[FLOAT21_SIZE+1]; char m_ier[FLOAT21_SIZE+1]; char m_iec[FLOAT21_SIZE+1]; char m_ierr[FLOAT21_SIZE+1]; char m_ierc[FLOAT21_SIZE+1]; char m_iecc[FLOAT21_SIZE+1]; char m_ia0[FLOAT21_SIZE+1]; char m_iar[FLOAT21_SIZE+1]; char m_iac[FLOAT21_SIZE+1]; char m_iarr[FLOAT21_SIZE+1]; char m_iarc[FLOAT21_SIZE+1]; char m_iacc[FLOAT21_SIZE+1]; char m_spx[FLOAT21_SIZE+1]; char m_svx[FLOAT21_SIZE+1]; char m_sax[FLOAT21_SIZE+1]; char m_spy[FLOAT21_SIZE+1]; char m_svy[FLOAT21_SIZE+1]; char m_say[FLOAT21_SIZE+1]; char m_spz[FLOAT21_SIZE+1]; char m_svz[FLOAT21_SIZE+1]; char m_saz[FLOAT21_SIZE+1]; TYPE_DATA }; // End: class ossimNitfRsmidaTag #endif /* #ifndef ossimNitfRsmidaTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRsmpcaTag.h000066400000000000000000000072301352751253100251250ustar00rootroot00000000000000//--- // File: ossimNitfRsmpcaTag.h //--- #ifndef ossimNitfRsmpcaTag_HEADER #define ossimNitfRsmpcaTag_HEADER 1 #include #include #include /** * @class ossimNitfRsmpcaTag * RSM Polynomial Coefficients: Polynomials coefficients for a section. * RFC NTB 055, STDI-0002-1 v4.0, Appendix U: RSM */ class OSSIM_DLL ossimNitfRsmpcaTag : public ossimNitfRegisteredTag { public: enum { IID_SIZE = 80, EDITION_SIZE = 40, RSN_SIZE = 3, CSN_SIZE = 3, FLOAT21_SIZE = 21, MAXPOWER_SIZE = 1, NUMTERMS_SIZE = 3 }; ossimNitfRsmpcaTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual void clearFields(); virtual std::ostream& print( std::ostream& out, const std::string& prefix=std::string() ) const; ossimString getIid() const; ossimString getEdition() const; ossimString getRsn() const; ossimString getCsn() const; ossimString getRfep() const; ossimString getCfep() const; ossimString getRnrmo() const; ossimString getCnrmo() const; ossimString getXnrmo() const; ossimString getYnrmo() const; ossimString getZnrmo() const; ossimString getRnrmsf() const; ossimString getCnrmsf() const; ossimString getXnrmsf() const; ossimString getYnrmsf() const; ossimString getZnrmsf() const; ossimString getRnpwrx() const; ossimString getRnpwry() const; ossimString getRnpwrz() const; ossimString getRntrms() const; ossimString getRnpcf(ossim_uint32 index) const; ossimString getRdpwrx() const; ossimString getRdpwry() const; ossimString getRdpwrz() const; ossimString getRdtrms() const; ossimString getRdpcf(ossim_uint32 index) const; ossimString getCnpwrx() const; ossimString getCnpwry() const; ossimString getCnpwrz() const; ossimString getCntrms() const; ossimString getCnpcf(ossim_uint32 index) const; ossimString getCdpwrx() const; ossimString getCdpwry() const; ossimString getCdpwrz() const; ossimString getCdtrms() const; ossimString getCdpcf(ossim_uint32 index) const; protected: char m_iid[IID_SIZE+1]; char m_edition[EDITION_SIZE+1]; char m_rsn[RSN_SIZE+1]; char m_csn[CSN_SIZE+1]; char m_rfep[FLOAT21_SIZE+1]; char m_cfep[FLOAT21_SIZE+1]; char m_rnrmo[FLOAT21_SIZE+1]; char m_cnrmo[FLOAT21_SIZE+1]; char m_xnrmo[FLOAT21_SIZE+1]; char m_ynrmo[FLOAT21_SIZE+1]; char m_znrmo[FLOAT21_SIZE+1]; char m_rnrmsf[FLOAT21_SIZE+1]; char m_cnrmsf[FLOAT21_SIZE+1]; char m_xnrmsf[FLOAT21_SIZE+1]; char m_ynrmsf[FLOAT21_SIZE+1]; char m_znrmsf[FLOAT21_SIZE+1]; char m_rnpwrx[MAXPOWER_SIZE+1]; char m_rnpwry[MAXPOWER_SIZE+1]; char m_rnpwrz[MAXPOWER_SIZE+1]; char m_rntrms[NUMTERMS_SIZE+1]; std::vector m_rnpcf; char m_rdpwrx[MAXPOWER_SIZE+1]; char m_rdpwry[MAXPOWER_SIZE+1]; char m_rdpwrz[MAXPOWER_SIZE+1]; char m_rdtrms[NUMTERMS_SIZE+1]; std::vector m_rdpcf; char m_cnpwrx[MAXPOWER_SIZE+1]; char m_cnpwry[MAXPOWER_SIZE+1]; char m_cnpwrz[MAXPOWER_SIZE+1]; char m_cntrms[NUMTERMS_SIZE+1]; std::vector m_cnpcf; char m_cdpwrx[MAXPOWER_SIZE+1]; char m_cdpwry[MAXPOWER_SIZE+1]; char m_cdpwrz[MAXPOWER_SIZE+1]; char m_cdtrms[NUMTERMS_SIZE+1]; std::vector m_cdpcf; ossim_uint32 m_rowNumNumTerms; ossim_uint32 m_rowDenNumTerms; ossim_uint32 m_colNumNumTerms; ossim_uint32 m_colDenNumTerms; TYPE_DATA }; // End: class ossimNitfRsmpcaTag #endif /* #ifndef ossimNitfRsmpcaTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfRsmpiaTag.h000066400000000000000000000053471352751253100251420ustar00rootroot00000000000000//--- // File: ossimNitfRsmpiaTag.h //--- #ifndef ossimNitfRsmpiaTag_HEADER #define ossimNitfRsmpiaTag_HEADER 1 #include class OSSIM_DLL ossimNitfRsmpiaTag : public ossimNitfRegisteredTag { public: enum { IID_SIZE = 80, EDITION_SIZE = 40, FLOAT21_SIZE = 21, NIS_SIZE = 3, CEL_SIZE = 591 }; ossimNitfRsmpiaTag(); /** * @brief Reads in tag from stream. * @param in */ virtual void parseStream(std::istream& in); /** * @brief Writes out tag to stream. * @param out */ virtual void writeStream(std::ostream& out); /** * @brief Memsets fields to space. Null terminates fields. */ virtual void clearFields(); /** * @brief prints all fields. * @param out Output stream. * @param prefix e.g. "nitf.image0.". */ virtual std::ostream& print( std::ostream& out, const std::string& prefix=std::string() ) const; ossimString getIid() const; ossimString getEdition() const; ossimString getR0() const; ossimString getRx() const; ossimString getRy() const; ossimString getRz() const; ossimString getRxx() const; ossimString getRxy() const; ossimString getRxz() const; ossimString getRyy() const; ossimString getRyz() const; ossimString getRzz() const; ossimString getC0() const; ossimString getCx() const; ossimString getCy() const; ossimString getCz() const; ossimString getCxx() const; ossimString getCxy() const; ossimString getCxz() const; ossimString getCyy() const; ossimString getCyz() const; ossimString getCzz() const; ossimString getRnis() const; ossimString getCnis() const; ossimString getTnis() const; ossimString getRssiz() const; ossimString getCssiz() const; protected: char m_iid[IID_SIZE+1]; char m_edition[EDITION_SIZE+1]; char m_r0[FLOAT21_SIZE+1]; char m_rx[FLOAT21_SIZE+1]; char m_ry[FLOAT21_SIZE+1]; char m_rz[FLOAT21_SIZE+1]; char m_rxx[FLOAT21_SIZE+1]; char m_rxy[FLOAT21_SIZE+1]; char m_rxz[FLOAT21_SIZE+1]; char m_ryy[FLOAT21_SIZE+1]; char m_ryz[FLOAT21_SIZE+1]; char m_rzz[FLOAT21_SIZE+1]; char m_c0[FLOAT21_SIZE+1]; char m_cx[FLOAT21_SIZE+1]; char m_cy[FLOAT21_SIZE+1]; char m_cz[FLOAT21_SIZE+1]; char m_cxx[FLOAT21_SIZE+1]; char m_cxy[FLOAT21_SIZE+1]; char m_cxz[FLOAT21_SIZE+1]; char m_cyy[FLOAT21_SIZE+1]; char m_cyz[FLOAT21_SIZE+1]; char m_czz[FLOAT21_SIZE+1]; char m_rnis[NIS_SIZE+1]; char m_cnis[NIS_SIZE+1]; char m_tnis[NIS_SIZE+1]; char m_rssiz[FLOAT21_SIZE+1]; char m_cssiz[FLOAT21_SIZE+1]; TYPE_DATA }; // End: class ossimNitfRsmpiaTag #endif /* #ifndef ossimNitfRsmpiaTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfSensraTag.h000066400000000000000000000142351352751253100251360ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Walt Bunch // // Description: Nitf support class for SENSRA - Sensor parameters extension. // //******************************************************************** // $Id: ossimNitfSensraTag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfSensraTag_HEADER #define ossimNitfSensraTag_HEADER #include class OSSIM_DLL ossimNitfSensraTag : public ossimNitfRegisteredTag { public: enum { REF_ROW_SIZE = 8, REF_COL_SIZE = 8, SENSOR_MODEL_SIZE = 6, SENSOR_MOUNT_SIZE = 3, SENSOR_LOC_SIZE = 21, SENSOR_ALT_SRC_SIZE = 1, SENSOR_ALT_SIZE = 6, SENSOR_ALT_UNIT_SIZE = 1, SENSOR_AGL_SIZE = 5, SENSOR_PITCH_SIZE = 7, SENSOR_ROLL_SIZE = 8, SENSOR_YAW_SIZE = 8, PLATFORM_PITCH_SIZE = 7, PLATFORM_ROLL_SIZE = 8, PLATFORM_HDG_SIZE = 5, GROUND_SPD_SRC_SIZE = 1, GROUND_SPEED_SIZE = 6, GROUND_SPD_UNIT_SIZE = 1, GROUND_TRACK_SIZE = 5, VERTICAL_VEL_SIZE = 5, VERT_VEL_UNIT_SIZE = 1, SWATH_FRAMES_SIZE = 4, N_SWATHS_SIZE = 4, SPOT_NUM_SIZE = 3 // ----- // 132 }; ossimNitfSensraTag(); virtual ~ossimNitfSensraTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; // The set methods below taking ossimString args will truncate and // pad with spaces, as necessary, to match enumed size void setRefRow(ossimString refRow); ossimString getRefRow()const; void setRefCol(ossimString refCol); ossimString getRefCol()const; void setSensorModel(ossimString sensorModel); ossimString getSensorModel()const; void setSensorMount(ossimString sensorMount); ossimString getSensorMount()const; void setSensorLoc(ossimString sensorLoc); ossimString getSensorLoc()const; void setSensorAltSrc(ossimString sensorAltSrc); ossimString getSensorAltSrc()const; void setSensorAlt(ossimString sensorAlt); ossimString getSensorAlt()const; void setSensorAltUnit(ossimString sensorAltUnit); ossimString getSensorAltUnit()const; void setSensorAgl(ossimString sensorAgl); ossimString getSensorAgl()const; void setSensorPitch(ossimString sensorPitch); ossimString getSensorPitch()const; void setSensorRoll(ossimString sensorRoll); ossimString getSensorRoll()const; void setSensorYaw(ossimString sensorYaw); ossimString getSensorYaw()const; void setPlatformPitch(ossimString platformPitch); ossimString getPlatformPitch()const; void setPlatformRoll(ossimString platformRoll); ossimString getPlatformRoll()const; void setPlatformHdg(ossimString platformHdg); ossimString getPlatformHdg()const; void setGroundSpdSrc(ossimString groundSpdSrc); ossimString getGroundSpdSrc()const; void setGroundSpeed(ossimString groundSpeed); ossimString getGroundSpeed()const; void setGroundSpdUnit(ossimString groundSpdUnit); ossimString getGroundSpdUnit()const; void setGroundTrack(ossimString groundTrack); ossimString getGroundTrack()const; void setVerticalVel(ossimString verticalVel); ossimString getVerticalVel()const; void setVertVelUnit(ossimString vertVelUnit); ossimString getVertVelUnit()const; void setSwathFrames(ossimString swathFrames); ossimString getSwathFrames()const; void setNSwaths(ossimString nSwaths); ossimString getNSwaths()const; void setSpotNum(ossimString spotNum); ossimString getSpotNum()const; protected: /** * FIELD: REFROW * */ char theRefRow[REF_ROW_SIZE+1]; /** * FIELD: REFCOL * */ char theRefCol[REF_COL_SIZE+1]; /** * FIELD: SENSORMODEL * */ char theSensorModel[SENSOR_MODEL_SIZE+1]; /** * FIELD: SENSORMOUNT * */ char theSensorMount[SENSOR_MOUNT_SIZE+1]; /** * FIELD: SENSORLOC * */ char theSensorLoc[SENSOR_LOC_SIZE+1]; /** * FIELD: SENSORALTSRC * */ char theSensorAltSrc[SENSOR_ALT_SRC_SIZE+1]; /** * FIELD: SENSORALT * */ char theSensorAlt[SENSOR_ALT_SIZE+1]; /** * FIELD: SENSORALTUNIT * */ char theSensorAltUnit[SENSOR_ALT_UNIT_SIZE+1]; /** * FIELD: SENSORAGL * */ char theSensorAgl[SENSOR_AGL_SIZE+1]; /** * FIELD: SENSORPITCH * */ char theSensorPitch[SENSOR_PITCH_SIZE+1]; /** * FIELD: SENSORROLL * */ char theSensorRoll[SENSOR_ROLL_SIZE+1]; /** * FIELD: SENSORYAW * */ char theSensorYaw[SENSOR_YAW_SIZE+1]; /** * FIELD: PLATFORMPITCH * */ char thePlatformPitch[PLATFORM_PITCH_SIZE+1]; /** * FIELD: PLATFORMROLL * */ char thePlatformRoll[PLATFORM_ROLL_SIZE+1]; /** * FIELD: PLATFORMHDG * */ char thePlatformHdg[PLATFORM_HDG_SIZE+1]; /** * FIELD: GROUNDSPDSRC * */ char theGroundSpdSrc[GROUND_SPD_SRC_SIZE+1]; /** * FIELD: GROUNDSPEED * */ char theGroundSpeed[GROUND_SPEED_SIZE+1]; /** * FIELD: GROUNDSPDUNIT * */ char theGroundSpdUnit[GROUND_SPD_UNIT_SIZE+1]; /** * FIELD: GROUNDTRACK * */ char theGroundTrack[GROUND_TRACK_SIZE+1]; /** * FIELD: VERTICALVEL * */ char theVerticalVel[VERTICAL_VEL_SIZE+1]; /** * FIELD: VERTVELUNIT * */ char theVertVelUnit[VERT_VEL_UNIT_SIZE+1]; /** * FIELD: SWATHFRAMES * */ char theSwathFrames[SWATH_FRAMES_SIZE+1]; /** * FIELD: NSWATHS * */ char theNSwaths[N_SWATHS_SIZE+1]; /** * FIELD: SPOTNUM * */ char theSpotNum[SPOT_NUM_SIZE+1]; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfSicdXmlDataContentDes.h000066400000000000000000000040271352751253100273710ustar00rootroot00000000000000#include #include #include class OSSIM_DLL ossimNitfSicdXmlDataContentDes : public ossimNitfRegisteredDes { public: enum { DESSHL_SIZE = 4, DESCRC_SIZE = 5, DESSHFT_SIZE = 8, DESSHDT_SIZE = 20, DESSHRP_SIZE = 40, DESSHSI_SIZE = 60, DESSHSV_SIZE = 10, DESSHSD_SIZE = 20, DESSHTN_SIZE = 120, DESSHLPG_SIZE = 125, DESSHLPT_SIZE = 25, DESSHLI_SIZE = 20, DESSHLIN_SIZE = 120, DESSHABS_SIZE = 200 }; ossimNitfSicdXmlDataContentDes(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void clearFields(); bool loadState(const ossimKeywordlist &kwl, const char *prefix); bool saveState(ossimKeywordlist &kwl, const char *prefix)const; // bool loadValueFromXml(const ossimRefPtr, const ossimString &xpath, ossimString &target) const; ossimString getDesshl() const; ossim_uint32 getDesshlAsUint32() const; ossimString getDescrc() const; ossimString getDesshft() const; ossimString getDesshdt() const; ossimString getDesshrp() const; ossimString getDesshsi() const; ossimString getDesshsv() const; ossimString getDesshsd() const; ossimString getDesshtn() const; void getDesDataAsString(ossimString& result)const; protected: char m_desshl[DESSHL_SIZE+1]; char m_descrc[DESCRC_SIZE+1]; char m_desshft[DESSHFT_SIZE+1]; char m_desshdt[DESSHDT_SIZE+1]; char m_desshrp[DESSHRP_SIZE+1]; char m_desshsi[DESSHSI_SIZE+1]; char m_desshsv[DESSHSV_SIZE+1]; char m_desshsd[DESSHSD_SIZE+1]; char m_desshtn[DESSHTN_SIZE+1]; char m_desshlpg[DESSHLPG_SIZE+1]; char m_desshlpt[DESSHLPT_SIZE+1]; char m_desshli[DESSHLI_SIZE+1]; char m_desshlin[DESSHLIN_SIZE+1]; char m_desshabs[DESSHABS_SIZE+1]; }; ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfStdidcTag.h000066400000000000000000000117171352751253100251170ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Walt Bunch // // Description: NITF support data class for STDIDC - Standard ID extension. // // See: STDI-000_v2.1 Table 7-3 for detailed description. // //******************************************************************** // $Id: ossimNitfStdidcTag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfStdidcTag_HEADER #define ossimNitfStdidcTag_HEADER 1 #include class OSSIM_DLL ossimNitfStdidcTag : public ossimNitfRegisteredTag { public: enum { ACQ_DATE_SIZE = 14, MISSION_SIZE = 14, PASS_SIZE = 2, OP_NUM_SIZE = 3, START_SEGMENT_SIZE = 2, REPRO_NUM_SIZE = 2, REPLAY_REGEN_SIZE = 3, BLANK_FILL_SIZE = 1, START_COLUMN_SIZE = 3, START_ROW_SIZE = 5, END_SEGMENT_SIZE = 2, END_COLUMN_SIZE = 3, END_ROW_SIZE = 5, COUNTRY_SIZE = 2, WAC_SIZE = 4, LOCATION_SIZE = 11, FIELD17_SIZE = 5, FIELD18_SIZE = 8 // ----- // 89 bytes }; ossimNitfStdidcTag(); virtual ~ossimNitfStdidcTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual void clearFields(); // The set methods below taking ossimString args will truncate and // pad with spaces, as necessary, to match enumed size void setAcqDate(ossimString acqDate); ossimString getAcqDate()const; void setMission(ossimString mission); ossimString getMission()const; void setPass(ossimString pass); ossimString getPass()const; void setOpNum(ossimString opNum); ossimString getOpNum()const; void setStartSegment(ossimString startSegment); ossimString getStartSegment()const; void setReproNum(ossimString reproNum); ossimString getReproNum()const; void setReplayRegen(ossimString replayRegen); ossimString getReplayRegen()const; void setBlankFill(ossimString blankFill); ossimString getBlankFill()const; void setStartColumn(ossimString startColumn); ossimString getStartColumn()const; void setStartRow(ossimString startRow); ossimString getStartRow()const; void setEndSegment(ossimString endSegment); ossimString getEndSegment()const; void setEndColumn(ossimString endColumn); ossimString getEndColumn()const; void setEndRow(ossimString endRow); ossimString getEndRow()const; void setCountry(ossimString country); ossimString getCountry()const; void setWac(ossimString wac); ossimString getWac()const; void setLocation(ossimString location); ossimString getLocation()const; void setField17(ossimString field17); ossimString getField17()const; void setField18(ossimString field18); ossimString getField18()const; /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; protected: /** * FIELD: ACQDATE */ char theAcqDate[ACQ_DATE_SIZE+1]; /** * FIELD: MISSION */ char theMission[MISSION_SIZE+1]; /** * FIELD: PASS */ char thePass[PASS_SIZE+1]; /** * FIELD: OPNUM */ char theOpNum[OP_NUM_SIZE+1]; /** * FIELD: STARTSEGMENT */ char theStartSegment[START_SEGMENT_SIZE+1]; /** * FIELD: REPRONUM */ char theReproNum[REPRO_NUM_SIZE+1]; /** * FIELD: REPLAYREGEN */ char theReplayRegen[REPLAY_REGEN_SIZE+1]; /** * FIELD: BLANKFILL */ char theBlankFill[BLANK_FILL_SIZE+1]; /** * FIELD: STARTCOLUMN */ char theStartColumn[START_COLUMN_SIZE+1]; /** * FIELD: STARTROW */ char theStartRow[START_ROW_SIZE+1]; /** * FIELD: ENDSEGMENT */ char theEndSegment[END_SEGMENT_SIZE+1]; /** * FIELD: ENDCOLUMN */ char theEndColumn[END_COLUMN_SIZE+1]; /** * FIELD: ENDROW */ char theEndRow[END_ROW_SIZE+1]; /** * FIELD: COUNTRY */ char theCountry[COUNTRY_SIZE+1]; /** * FIELD: WAC */ char theWac[WAC_SIZE+1]; /** * FIELD: LOCATION */ char theLocation[LOCATION_SIZE+1]; /** * FIELD: FIELD17 */ char theField17[FIELD17_SIZE+1]; /** * FIELD: FIELD18 */ char theField18[FIELD18_SIZE+1]; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfStreobTag.h000066400000000000000000000113231352751253100251340ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // // Description: STREOB tag class declaration. // // Dataset Indentification TRE. // // //---------------------------------------------------------------------------- // $Id #ifndef ossimNitfStreobTag_HEADER #define ossimNitfStreobTag_HEADER 1 #include class OSSIM_DLL ossimNitfStreobTag : public ossimNitfRegisteredTag { public: /** @brief default constructor */ ossimNitfStreobTag(); /** @brief destructor */ virtual ~ossimNitfStreobTag(); /** @brief Method to parse data from stream. */ virtual void parseStream(std::istream& in); /** @brief Method to write data to stream. */ virtual void writeStream(std::ostream& out); /** @brief Method to clear all fields including null terminating. */ virtual void clearFields(); /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; protected: /** * FIELD: ST_ID * * 60 byte field string * * alphanumeric * * The image ID of the first stereo mate. The fields ACQUISITION_DATE * through END_ROW in the STDIDC tag constitute the image ID * */ char m_stdId[61]; /** * FIELD: N_MATES * * 1 byte integer * * values: 1 to 3 * * Number of Stereo Mates. If there are no stereo mates, * there will not be any STREOB (TBR) extensions in the file. * If there is a STREOB (TBR) extension, then there will be at * least 1 stereo mate. */ char n_nMates[2]; /** * FIELD: MATE_INSTANCE * * 1 byte integer * * values: 1 to 3 * * Mate Instance identifies which stereo mate is described in * that extension. For example, this field contains a 2 for * the second stereo mate. */ char m_mateInstance[2]; /** * FIELD: B_CONV * * 5 byte field in degrees * * Value: 00.00 to 90.00 * * Beginning Convergence Angle defined at the first lines of * the fore/left and aft/right images, unless those images are * more than 90 degrees apart. If the images are more than 90 degrees * apart, the first line of the fore and the last line of the * aft shall be used. * */ char m_bConv[6]; /** * FIELD: E_CONV * * 5 byte field in degrees * * Values: 00.00 to 90.00 * * Ending Convergence Angle defined at the last lines of the fore/left * and aft/right images, unless those images are more than 90 degrees apart. * If the images are more than 90 degrees apart, the last line of the fore and * the first line of the aft shall be used. */ char m_eConv[6]; /** * FIELD: B_ASYM * * 5 byte field * * Values: 00.00 to 90.00 * * Beginning Asymmetry Angle defined at the first lines of the fore/left and * aft/right images, unless those images are more than 90 degrees apart. * If the images are more than 90 degrees apart, the first line of * the fore and the last line of the aft shall be used. */ char m_bAsym[6]; /** * FIELD: E_ASYM * * 5 byte field * * Values: 00.00 to 90.00 * * Ending Asymmetry Angle defined at the last lines of the fore/left and aft/right * images, unless those images are more than 90 degrees apart. If the * images are more than 90 degrees apart, the last line of the fore and * the first line of the aft shall be used. */ char m_eAsym[6]; /** * FIELD: B_BIE * * 6 byte field * * Values: +- 90.00 * * Beginning BIE less Convergence Angle of Stereo Mate, defined at the first * lines of the fore/left and aft/right images, unless those images are * more than 90 degrees apart. If the images are more than 90 degrees apart, * the first line of the fore and the last line of the aft shall be used. */ char m_bBie[7]; /** * FIELD: E_BIE * * 6 byte field * * Values: +- 90.00 * * Ending BIE less Convergence Angle of Stereo Mate, * defined at the last lines of the fore/left and aft/right images, * unless those images are more than 90 degrees apart. * If the images are more than 90 degrees apart, the last * line of the fore and the first line of the aft shall be used. */ char m_eBie[7]; TYPE_DATA }; #endif /* matches #ifndef ossimNitfStreobTag_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfSymbolHeader.h000066400000000000000000000014771352751253100256310ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfSymbolHeader.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfSymbolHeader_HEADER #define ossimNitfSymbolHeader_HEADER #include #include class ossimDrect; class OSSIMDLLEXPORT ossimNitfSymbolHeader : public ossimObject { public: ossimNitfSymbolHeader(){} virtual ~ossimNitfSymbolHeader(){} virtual void parseStream(std::istream &in)=0; virtual ossim_int32 getDisplayLevel()const=0; virtual ossimDrect getImageRect()const=0; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfSymbolHeaderV2_0.h000066400000000000000000000122711352751253100262520ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfSymbolHeaderV2_0.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfSymbolHeaderV2_0_HEADER #define ossimNitfSymbolHeaderV2_0_HEADER #include #include class ossimNitfSymbolHeaderV2_0 : public ossimNitfSymbolHeader { public: ossimNitfSymbolHeaderV2_0(); virtual ~ossimNitfSymbolHeaderV2_0(){} virtual void parseStream(std::istream &in); virtual std::ostream& print(std::ostream &out)const; virtual ossim_int32 getDisplayLevel()const; virtual ossimDrect getImageRect()const; TYPE_DATA private: void clearFields(); /*! * Is a required 2 byte field. The expected value * is SY. */ char theFilePartType[3]; /*! * is a 10 byte required alphanumeric field. */ char theSymbolId[11]; /*! * is an optional 20 byte alphanumeric field */ char theSymbolName[21]; /*! * Security classification is a required 1 byte field. * Expected values can * either be: * * T Top secret * S Secret * C Confidential * R Restricted * U UnClassified */ char theSymbolSecurityClass[2]; /*! * 40 byte optional field */ char theSymbolCodewords[41]; /*! * 40 byte optional field. */ char theSymbolControlAndHandling[41]; /*! * 40 byte optional field. */ char theSymbolReleasingInstructions[41]; /*! * optional 20 byte field. */ char theSymbolClassificationAuthority[21]; /*! * optional 20 byte field. */ char theSymbolSecurityControlNum[21]; /*! * optional 6 byte value. */ char theSymbolSecurityDowngrade[7]; /*! * Conditional field. This field exists if * theSymbolSecurityDowngrade has the value of * 999998. If it exists it will be a 40 byte * field. */ char theSymbolDowngradingEvent[41]; /*! * This is a required 1 byte field and can have * a value of: * * 0 Not encrypted * 1 Encrytped * */ char theSymbolEncryption[2]; /*! * This is a required one byte field and can have the value * of either: * * B Bit-mapped * C for CGM * O for object * * * if it's O then theSymbolNumber will hold a number to the symbol * object to draw. See field theSymbolNumber for object * numbers and object types. */ char theSymbolType[2]; /*! * This is a required 4 byte field. Ranges from 0-9999. * * if theSymbolType is B or O this field will contain * the number of rows (lines) in the symbol image. This * field shall contain 0 if theSymbolType is C */ char theNumberLinesPerSymbol[5]; /*! * This is a required 4 byte field. Ranges from 0-9999 * * if theSymbolType is B or O this field will contain * the number of pixels in each row. This * field shall contain 0 if theSymbolType is C */ char theSymbolNumberPixelsPerLine[5]; /*! * This is a required 4 byte field. Ranges from 0-9999 * * if theSymbolType is O this field will contain * the line width for the object symbol in pixels. * * if this field equals theNumberLinesPerSymbol then the * symbol should be drawn solid and filled in. */ char theSymbolLineWidth[5]; /*! * This is a required 1 byte field. Ranges from 0-8 */ char theSymbolNumberBitsPerPixel[2]; /*! * This is a required 3 byte field. Ranges from 1-999 */ char theSymbolDisplayLevel[4]; /*! * This is a required 3 byte field. Ranges from 0-998 */ char theSymbolAttachmentLevel[4]; /*! * This is a required 10 byte field. This indicates the location * in image space. * * rrrrrccccc five characters for r followed by five for the column */ char theSymbolLocation[11]; /*! * This is an optional 10 byte field. Has format * rrrrrccccc where r is row c is column. */ char theSecondSymbolLocation[11]; /*! * This is a required 1 byte field. */ char theSymbolColor[2]; /*! * This is an optional 6 byte field. * * */ char theSymbolNumber[7]; /*! * This is a required 3 byte field. Ranges from 0-359 */ char theSymbolRotation[4]; /*! * This is a required 3 byte field. Ranges from 0-256 */ char theSymbolNumberOfLutEntries[4]; /*! * This will hold the lookup table values for * the pixel data. This is a conditional field and will * exist if theSymbolNumberOfLutEntries is not 0. */ ossimNitfImageLutV2_0 theSymbolLutData; /*! * This is is a required 5 byte field. * Will range from 0-08833. */ char theSymbolExtendedSubheaderDataLength[6]; /*! * This is a conditional 3 byte field that ranges from * 0-999. This field will depend on theSymbolExtendedSubheaderDataLength * not being 0. */ char theSymbolSubheaderOverflow[4]; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfTagFactory.h000066400000000000000000000017561352751253100253160ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfTagFactory.h 17207 2010-04-25 23:21:14Z dburken $ #ifndef ossimNitfTagFactory_HEADER #define ossimNitfTagFactory_HEADER #include #include #include class ossimNitfRegisteredTag; class OSSIM_DLL ossimNitfTagFactory : public ossimObject { public: ossimNitfTagFactory(); virtual ~ossimNitfTagFactory(); virtual ossimRefPtr create(const ossimString &tagName)const=0; private: /*! * Hide this. */ ossimNitfTagFactory(const ossimNitfTagFactory & /* rhs */){} /*! * Hide this. */ ossimNitfTagFactory& operator =(const ossimNitfTagFactory & /* rhs */){return *this;} TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfTagFactoryRegistry.h000066400000000000000000000025461352751253100270450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfTagFactoryRegistry.h 22875 2014-08-27 13:52:03Z dburken $ #ifndef ossimNitfTagFactoryRegistry_HEADER #define ossimNitfTagFactoryRegistry_HEADER 1 #include #include #include class ossimString; class ossimNitfTagFactory; class OSSIM_DLL ossimNitfTagFactoryRegistry { public: virtual ~ossimNitfTagFactoryRegistry(); void registerFactory(ossimNitfTagFactory* aFactory); void unregisterFactory(ossimNitfTagFactory* aFactory); static ossimNitfTagFactoryRegistry* instance(); ossimRefPtr create(const ossimString &tagName)const; bool exists(ossimNitfTagFactory* factory)const; protected: ossimNitfTagFactoryRegistry(); private: /** hidden copy constructory */ ossimNitfTagFactoryRegistry(const ossimNitfTagFactoryRegistry& factory); /** hidden operator= */ const ossimNitfTagFactoryRegistry& operator=( const ossimNitfTagFactoryRegistry& factory); void initializeDefaults(); std::vector theFactoryList; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfTagInformation.h000066400000000000000000000052121352751253100261630ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfTagInformation_HEADER #define ossimNitfTagInformation_HEADER 1 #include #include #include class ossimString; class OSSIMDLLEXPORT ossimNitfTagInformation : public ossimObject { public: ossimNitfTagInformation(ossimRefPtr tagData = 0); virtual ~ossimNitfTagInformation(); virtual void parseStream(ossim::istream& in); virtual void writeStream(ossim::ostream& out); void setTagName(const ossimString& tagName); void setTagLength(ossim_uint32 tagLength); /** * Length of the 5 byte tag length the 6 byte tag name and * the data length. * So we have Data length + 11 bytes. */ ossim_uint32 getTotalTagLength()const; /** * Should return the value of theTagLength which is the length of * the data in bytes. */ ossim_uint32 getTagLength()const; ossim_uint64 getTagOffset()const; ossim_uint64 getTagDataOffset()const; ossimString getTagName()const; virtual std::ostream& print(std::ostream& out)const; void clearFields(); ossimRefPtr getTagData(); const ossimRefPtr getTagData()const; void setTagData(ossimRefPtr tagData); ossimString getTagType() const; void setTagType(const ossimString& tagType) const; bool operator<(const ossimNitfTagInformation& rhs) const { return getTotalTagLength() < rhs.getTotalTagLength(); } private: /** * This is a 6 byte field */ char theTagName[7]; /** * This is a 5 byte field */ char theTagLength[6]; /** * This is a 6 byte field which should be UDHD, UDID, XHD, IXSHD, SXSHD, or TXSHD. * This is declared as mutable since changing the tag type doesn't change the contents of the tag. */ mutable char theTagType[7]; /** * This will hold the offset to the start of the above information * This is just a work variable. */ ossim_uint64 theTagOffset; /** * This will hold the start to the data. This is just the * position in the file just past the tag length field. * This is just a work variable */ ossim_uint64 theTagDataOffset; /** * Used to hold the tag data. */ ossimRefPtr theTagData; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfTextHeader.h000066400000000000000000000012561352751253100253030ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfTextHeader.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfTextHeader_HEADER #define ossimNitfTextHeader_HEADER #include class OSSIMDLLEXPORT ossimNitfTextHeader : public ossimObject { public: ossimNitfTextHeader(){} virtual ~ossimNitfTextHeader(){} virtual void parseStream(std::istream &in)=0; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfTextHeaderV2_0.h000066400000000000000000000060051352751253100257270ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfTextHeaderV2_0.h 9094 2006-06-13 19:12:40Z dburken $ #ifndef ossimNitfTextHeaderV2_0_HEADER #define ossimNitfTextHeaderV2_0_HEADER #include class OSSIMDLLEXPORT ossimNitfTextHeaderV2_0 : public ossimNitfTextHeader { public: ossimNitfTextHeaderV2_0(); virtual ~ossimNitfTextHeaderV2_0(){} virtual void parseStream(std::istream &in); virtual std::ostream& print(std::ostream &out)const; TYPE_DATA private: void clearFields(); /*! * This is a required 2 byte fields and has * a value of TE. */ char theFilePartType[3]; /*! * This is a required 10 byte field. */ char theTextId[11]; /*! * This is a required 14 byte field. It has the * format of: * * DDHHMMSSZMONYY * * DD 2 character day * HH 2 characters for the Hour * MM 2 characters for the minute * SS 2 characters for the seconds * Z required * MON 3 characters of the month * YY 2 characters for the year */ char theDataAndTime[15]; /*! * is an optional 80 byte field */ char theTextTitle[81]; /*! * This is a required 1 byte field. Can have * of either: * * T Top secret * S Secret * C Confidential * R Restricted * U Unclassified */ char theTextSecurityClassification[2]; /*! * This is an optional 40 byte field. */ char theTextCodewords[41]; /*! * This is an optional 40 yte field. */ char theTextControlAndHandling[41]; /*! * This is an optional 40 yte field. */ char theTextReleasingInstructions[41]; /*! * optional 20 byte field */ char theTextClassificationAuthority[21]; /*! * optional 20 byte field */ char theTextSecurityControlNumber[21]; /*! * optional 6 byte field */ char theTextSecurityDowngrade[7]; /* * This is a conditional 40 byte field. if * theSecurityDowngrade = 999998 then this field * exists. */ char theTextSecurityDowngradeEvent[41]; /*! * This is the encription type and is a * required 1 byte field. It can have values * * 0 Not encrypted * 1 Encrypted */ char theTextEncyption[2]; /*! * This is a required 3 byte field and will hold * either: * * MTF indicates USMTF ( refer to JCS PUB 6-04 * for examples * STA indicates NITF ASCII * OTH indicates other or user defined */ char theTextFormat[4]; /*! * is a required 5 byute field. */ char theExtSubheaderDataLength[6]; /*! * is a conditional 3 byte field. It exists if * theExtSubheaderDataLength is not 0 */ char theExtSubheaderOverflow[4]; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfTextHeaderV2_1.h000066400000000000000000000125021352751253100257270ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #ifndef ossimNitfTextHeaderV2_1_HEADER #define ossimNitfTextHeaderV2_1_HEADER #include class OSSIMDLLEXPORT ossimNitfTextHeaderV2_1 : public ossimNitfTextHeader { public: ossimNitfTextHeaderV2_1(); virtual ~ossimNitfTextHeaderV2_1(); virtual void parseStream(std::istream &in); virtual std::ostream& print(std::ostream &out)const; virtual void writeStream(std::ostream &out); void setSecurityClassification(const ossimString& value); void setSecurityClassificationSystem(const ossimString& value); void setCodewords(const ossimString& value); void setControlAndHandling(const ossimString& value); void setReleasingInstructions(const ossimString& value); void setDeclassificationType(const ossimString& value); static const ossimString TE_KW; static const ossimString TEXTID_KW; static const ossimString TXTALVL_KW; static const ossimString TXTDT_KW; static const ossimString TXTITL_KW; static const ossimString TSCLAS_KW; static const ossimString TSCLSY_KW; static const ossimString TSCODE_KW; static const ossimString TSCTLH_KW; static const ossimString TSREL_KW; static const ossimString TSDCTP_KW; static const ossimString TSDCDT_KW; static const ossimString TSDCXM_KW; static const ossimString TSDG_KW; static const ossimString TSDGDT_KW; static const ossimString TSCLTX_KW; static const ossimString TSCATP_KW; static const ossimString TSCAUT_KW; static const ossimString TSCRSN_KW; static const ossimString TSSRDT_KW; static const ossimString TSCTLN_KW; static const ossimString ENCRYP_KW; static const ossimString TXTFMT_KW; static const ossimString TXSHDL_KW; static const ossimString TXSOFL_KW; static const ossimString TXSHD_KW; private: void clearFields(); /*! * This is a required 2 byte fields and has * a value of TE. */ char theFilePartType[3]; /*! * This is a required 7 byte field. Text Identifier */ char theTextId[8]; /*! * This is a required 3 byte field. */ char theTextAttLevel[4]; /*! * This is a required 14 byte field. It has the * format of: * * DDHHMMSSZMONYY * * DD 2 character day * HH 2 characters for the Hour * MM 2 characters for the minute * SS 2 characters for the seconds * Z required * MON 3 characters of the month * YY 2 characters for the year */ char theDataAndTime[15]; /*! * is an optional 80 byte field */ char theTextTitle[81]; /*! * This is a required 1 byte field. Can have * of either: * * T Top secret * S Secret * C Confidential * R Restricted * U Unclassified */ char theTextSecurityClassification[2]; /*! * 2 byte field Security Classification System */ char theTextSecuritySystem[3]; /*! * 11 byte field Text Codewords */ char theTextCodewords[12]; /*! * 2 byte field Text Control and Handling */ char theTextControlAndHandling[3]; /*! * This is an optional 20 byte field. */ char theTextReleasingInstructions[21]; /*! * optional 2 byte field Text Declassification Type */ char theTextDeclassificationType[3]; /*! * optional 8 byte field Text Declassification Date */ char theTextDeclassificationDate[9]; /*! * optional 4 byte field Text Declassification Exemption */ char theTextDeclassificationExemption[5]; /*! * optional 1 byte field Text Declassification Exemption */ char theTextSecurityDowngrade[2]; /*! * optional 8 byte field */ char theTextSecurityDowngradeDate[9]; /*! * 43 byte field providing additional information on text classification */ char theTextClassificationText[44]; /*! * Optional 1 byte flag for type of classification athority */ char theTextClassificationAthorityType[2]; /*! * Optional 40 byte flag for classification athority */ char theTextClassificationAthority[41]; /*! * Optional 1 byte flag for classification athority */ char theTextClassificationReason[2]; /*! * Optional 8 byte entry */ char theTextSecuritySourceDate[9]; /*! * Optional 15 byte entry for security control number */ char theTextSecurityControlNumber[16]; /*! * This is the encription type and is a * required 1 byte field. It can have values * * 0 Not encrypted * 1 Encrypted */ char theTextEncyption[2]; /*! * This is a required 3 byte field and will hold * either: * * MTF indicates USMTF ( refer to JCS PUB 6-04 * for examples * STA indicates NITF ASCII * OTH indicates other or user defined */ char theTextFormat[4]; /*! * is a required 5 byute field. */ char theExtSubheaderDataLength[6]; /*! * is a conditional 3 byte field. It exists if * theExtSubheaderDataLength is not 0 */ char theExtSubheaderOverflow[4]; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfUnknownTag.h000066400000000000000000000042571352751253100253450ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Unknown tag class declaration. // // Note: By "unknown" this means that the tag name was not found in any of // the tag factories. // //---------------------------------------------------------------------------- // $Id: ossimNitfUnknownTag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfUnknownTag_HEADER #define ossimNitfUnknownTag_HEADER 1 #include class OSSIM_DLL ossimNitfUnknownTag : public ossimNitfRegisteredTag { public: /** default constructor */ ossimNitfUnknownTag(); /** destructor */ virtual ~ossimNitfUnknownTag(); /** * Parse method. * * @param in Stream to parse. This will read the entire tag length into * an array. */ virtual void parseStream(std::istream& in); /** * Write method. * * @param out Stream to write to. */ virtual void writeStream(std::ostream& out); /** * Clears all string fields within the record to some default nothingness. */ virtual void clearFields(); /** * @brief print method that outputs a key/value type format adding prefix * to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; /** * @param length Length of tag. * * @note The tag length must be set prior to calling "parseStream". * * @note Since you must have a length to read theTagData, if theTagData * exist it will be deleted by this method. * Subsequent "parseStream" calls will allocate theTagData as needed. */ virtual void setTagLength(ossim_uint32 length); protected: /** * @return true if all characters in theTagData are printable. */ bool tagDataIsAscii() const; bool tagDataIsXml() const; /** * Holds entire tag data(theTagLength) plus one byte for null terminator. */ char* m_tagData; TYPE_DATA }; #endif /* End of "#ifndef ossimNitfUnknownTag_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfUse00aTag.h000066400000000000000000000144371352751253100247440ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Walt Bunch // // Description: Nitf support class for USE00A - // Exploitation Usability extension. // //******************************************************************** // $Id: ossimNitfUse00aTag.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimNitfUse00aTag_HEADER #define ossimNitfUse00aTag_HEADER #include class OSSIM_DLL ossimNitfUse00aTag : public ossimNitfRegisteredTag { public: enum { ANGLE_TO_NORTH_SIZE = 3, MEAN_GSD_SIZE = 5, FIELD3_SIZE = 1, DYNAMIC_RANGE_SIZE = 5, FIELD5_SIZE = 3, FIELD6_SIZE = 1, FIELD7_SIZE = 3, OBL_ANG_SIZE = 5, ROLL_ANG_SIZE = 6, FIELD10_SIZE = 12, FIELD11_SIZE = 15, FIELD12_SIZE = 4, FIELD13_SIZE = 1, FIELD14_SIZE = 3, FIELD15_SIZE = 1, FIELD16_SIZE = 1, N_REF_SIZE = 2, REV_NUM_SIZE = 5, N_SEG_SIZE = 3, MAX_LP_SEG_SIZE = 6, FIELD20_SIZE = 6, FIELD21_SIZE = 6, SUN_EL_SIZE = 5, SUN_AZ_SIZE = 5 // ----- // 107 bytes }; ossimNitfUse00aTag(); virtual ~ossimNitfUse00aTag(); virtual void parseStream(std::istream& in); virtual void writeStream(std::ostream& out); virtual void clearFields(); // The set methods below taking ossimString args will truncate and // pad with spaces, as necessary, to match enumed size void setAngleToNorth(const ossimString& angleToNorth); ossimString getAngleToNorth()const; void setMeanGsd(const ossimString& meanGsd); ossimString getMeanGsd()const; /** * @return MEANGSD field as a double converted to meters. * * @note Conversion used: gsd_in_meters = gsd / 12.0 * MTRS_PER_FT */ ossim_float64 getMeanGsdInMeters() const; void setField3(const ossimString& field3); ossimString getField3()const; void setDynamicRange(const ossimString& dynamicRange); ossimString getDynamicRange()const; void setField5(const ossimString& field5); ossimString getField5()const; void setField6(const ossimString& field6); ossimString getField6()const; void setField7(const ossimString& field7); ossimString getField7()const; void setOblAng(const ossimString& oblAng); ossimString getOblAng()const; void setRollAng(const ossimString& rollAng); ossimString getRollAng()const; void setField10(const ossimString& field10); ossimString getField10()const; void setField11(const ossimString& field11); ossimString getField11()const; void setField12(const ossimString& field12); ossimString getField12()const; void setField13(const ossimString& field13); ossimString getField13()const; void setField14(const ossimString& field14); ossimString getField14()const; void setField15(const ossimString& field15); ossimString getField15()const; void setField16(const ossimString& field16); ossimString getField16()const; void setNRef(const ossimString& nRef); ossimString getNRef()const; void setRevNum(const ossimString& revNum); ossimString getRevNum()const; void setNSeg(const ossimString& nSeg); ossimString getNSeg()const; void setMaxLpSeg(const ossimString& maxLpSeg); ossimString getMaxLpSeg()const; void setField20(const ossimString& field20); ossimString getField20()const; void setField21(const ossimString& field21); ossimString getField21()const; void setSunEl(const ossimString& sunEl); ossimString getSunEl()const; void setSunAz(const ossimString& sunAz); ossimString getSunAz()const; /** * @brief Print method that outputs a key/value type format * adding prefix to keys. * @param out Stream to output to. * @param prefix Prefix added to key like "image0."; */ virtual std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual void setProperty(ossimRefPtr property); virtual ossimRefPtr getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector& propertyNames)const; protected: /** * FIELD: ANGLETONORTH * */ char theAngleToNorth[ANGLE_TO_NORTH_SIZE+1]; /** * FIELD: MEANGSD * */ char theMeanGsd[MEAN_GSD_SIZE+1]; /** * FIELD: FIELD3 * */ char theField3[FIELD3_SIZE+1]; /** * FIELD: DYNAMICRANGE * */ char theDynamicRange[DYNAMIC_RANGE_SIZE+1]; /** * FIELD: FIELD5 * */ char theField5[FIELD5_SIZE+1]; /** * FIELD: FIELD6 * */ char theField6[FIELD6_SIZE+1]; /** * FIELD: FIELD7 * */ char theField7[FIELD7_SIZE+1]; /** * FIELD: OBLANG * */ char theOblAng[OBL_ANG_SIZE+1]; /** * FIELD: ROLLANG * */ char theRollAng[ROLL_ANG_SIZE+1]; /** * FIELD: FIELD10 * */ char theField10[FIELD10_SIZE+1]; /** * FIELD: FIELD11 * */ char theField11[FIELD11_SIZE+1]; /** * FIELD: FIELD12 * */ char theField12[FIELD12_SIZE+1]; /** * FIELD: FIELD13 * */ char theField13[FIELD13_SIZE+1]; /** * FIELD: FIELD14 * */ char theField14[FIELD14_SIZE+1]; /** * FIELD: FIELD15 * */ char theField15[FIELD15_SIZE+1]; /** * FIELD: FIELD16 * */ char theField16[FIELD16_SIZE+1]; /** * FIELD: NREF * */ char theNRef[N_REF_SIZE+1]; /** * FIELD: REVNUM * */ char theRevNum[REV_NUM_SIZE+1]; /** * FIELD: NSEG * */ char theNSeg[N_SEG_SIZE+1]; /** * FIELD: MAXLPSEG * */ char theMaxLpSeg[MAX_LP_SEG_SIZE+1]; /** * FIELD: FIELD20 * */ char theField20[FIELD20_SIZE+1]; /** * FIELD: FIELD21 * */ char theField21[FIELD21_SIZE+1]; /** * FIELD: SUNEL * */ char theSunEl[SUN_EL_SIZE+1]; /** * FIELD: SUNAZ * */ char theSunAz[SUN_AZ_SIZE+1]; TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNitfVqCompressionHeader.h000066400000000000000000000053101352751253100271620ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2004 Garrett Potts // // LICENSE: MIT see top level LICENSE.txt for more details // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfVqCompressionHeader.h 18413 2010-11-11 19:56:22Z gpotts $ #ifndef ossimNitfVqCompressionHeader_HEADER #define ossimNitfVqCompressionHeader_HEADER #include #include class OSSIM_DLL ossimNitfVqCompressionOffsetTableData { public: ossimNitfVqCompressionOffsetTableData(); ossimNitfVqCompressionOffsetTableData(const ossimNitfVqCompressionOffsetTableData& rhs); ~ossimNitfVqCompressionOffsetTableData(); const ossimNitfVqCompressionOffsetTableData& operator =(const ossimNitfVqCompressionOffsetTableData& rhs); ossim_uint32 getDataLengthInBytes()const; void clearFields(); void parseStream(std::istream& in); ossim_uint16 theTableId; ossim_uint32 theNumberOfCompressionLookupRecords; ossim_uint16 theNumberOfValuesPerCompressionLookup; ossim_uint16 theCompressionLookupValueBitLength; ossim_uint32 theCompressionLookupTableOffset; ossim_uint8* theData; }; class OSSIM_DLL ossimNitfVqCompressionHeader : public ossimNitfCompressionHeader { public: ossimNitfVqCompressionHeader(); virtual void parseStream(std::istream &in); virtual std::ostream& print(std::ostream& out) const; /** * @brief print method that outputs a key/value type format adding prefix * to keys. */ virtual std::ostream& print(std::ostream& out, const std::string& prefix) const; virtual bool saveState(ossimKeywordlist& kwl, const ossimString& prefix="")const; virtual ossim_uint32 getBlockSizeInBytes()const; virtual ossim_uint32 getNumberOfImageRows()const; virtual ossim_uint32 getNumberOfImageCodesPerRow()const; virtual ossim_uint32 getCompressionAlgorithmId()const; virtual ossim_uint32 getImageCodeBitLength()const; virtual ossim_uint32 getNumberOfTables()const; const std::vector& getTable()const; protected: ossim_uint32 theNumberOfImageRows; ossim_uint32 theNumberOfImageCodesPerRow; ossim_uint8 theImageCodeBitLength; ossim_uint16 theCompressionAlgorithmId; ossim_uint16 theNumberOfCompressionLookupOffsetRecords; ossim_uint16 theNumberOfCompressionParameterOffsetRecords; ossim_uint32 theCompressionLookupOffsetTableOffset; ossim_uint16 theCompressionLookupTableOffsetRecordLength; std::vector theTable; void clearFields(); TYPE_DATA }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNmeaMessage.h000066400000000000000000000045041352751253100246110ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT See top level LICENSE.txt file. // // File: ossimNmeaMessage.h // // Author: Garrett Potts // // Description: Contains a general parser for NMEA messages. // // // $Id$ //---------------------------------------------------------------------------- #ifndef ossimNmeaMessage_HEADER #define ossimNmeaMessage_HEADER #include #include #include #include #include #include #include class OSSIM_DLL ossimNmeaMessage : public ossimReferenced { public: typedef std::vector FieldListType; ossimNmeaMessage(const std::string& acceptedStartingCharacters="!$"):m_startChars(acceptedStartingCharacters){} /** * Parses a standard formatted NMEA message. No exceptions are created for checksums. The checksum needs * to be checked after parsing by calling validCheckSum(). */ virtual void parseMessage(std::istream& in)throw(ossimException); virtual bool valid()const{return validCheckSum();} bool validCheckSum()const{return m_validCheckSum;} ossim_uint32 numberOfFields()const{return m_fields.size();} const std::string& getField(ossim_uint32 idx) { static ossimString empty=""; if(idx < m_fields.size()) return m_fields[idx]; return empty; } const std::string& operator [](int idx)const { static ossimString empty=""; if ( idx < static_cast( m_fields.size() ) ) return m_fields[idx]; return empty; } void setStartChars(const std::string& acceptedStartingCharacters="!$"){m_startChars = acceptedStartingCharacters;} virtual void reset() { m_fields.clear(); m_message = ""; m_validCheckSum = false; } const std::string& message()const{return m_message;} static ossim_uint32 checksum(std::string::const_iterator start, std::string::const_iterator end); protected: virtual void setFields(std::string::const_iterator start, std::string::const_iterator end); bool isValidStartChar(char c)const; std::string m_message; FieldListType m_fields; bool m_validCheckSum; std::string m_startChars; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimNmeaMessageSequencer.h000066400000000000000000000012701352751253100264610ustar00rootroot00000000000000#ifndef ossimNmeaMessageSequencer_HEADER #define ossimNmeaMessageSequencer_HEADER #include #include #include class OSSIM_DLL ossimNmeaMessageSequencer { public: ossimNmeaMessageSequencer(); ossimNmeaMessageSequencer(const ossimFilename& file); ossimNmeaMessageSequencer(const std::string& str); ~ossimNmeaMessageSequencer(); void initialize(const ossimFilename& file); void initialize(const std::string& str); virtual bool next(ossimNmeaMessage& msg); virtual void reset(); virtual bool valid()const; protected: void destroy(); std::istream* m_inputStream; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimPpjFrameSensorFile.h000066400000000000000000000043661352751253100261300ustar00rootroot00000000000000#ifndef ossimPpjFrameSensorFile_HEADER #define ossimPpjFrameSensorFile_HEADER #include #include #include #include #include #include #include #include #include #include class OSSIM_DLL ossimPpjFrameSensorFile : public ossimObject { public: enum PointType { UNKNOWN_POINT_TYPE = 0, BASIC_POINT_TYPE = 1 }; class OSSIM_DLL PointMap { public: PointType m_type; ossimDpt3d m_point; ossimDpt m_pixelPoint; }; typedef std::vector PointMapList; typedef std::vector DoubleArrayType; ossimPpjFrameSensorFile(); virtual bool readFile(const ossimFilename& file); virtual bool readStream(std::istream& is); const ossimString& getBaseName()const; ossim_int64 getImageNumber()const; const ossimDpt& getPrincipalPoint()const; const ossimGpt& getPlatformPosition()const; const NEWMAT::Matrix& getExtrinsic()const; const NEWMAT::Matrix& getIntrinsic()const; const ossimDpt& getImageSize()const; const DoubleArrayType& getRadialDistortion()const; const DoubleArrayType& getTangentialDistortion()const; double getAverageProjectedHeight()const; protected: void reset(); ossimPpjFrameSensorFile(const ossimPpjFrameSensorFile& src); ossimPpjFrameSensorFile& operator =(const ossimPpjFrameSensorFile& src); ossimGpt m_platformPosition; ossimFilename m_filename; ossimString m_fileBaseName; ossim_int64 m_imageNumber; ossimRefPtr m_ppjXml; ossimDpt m_imageSize; ossimDpt m_principalPoint; NEWMAT::Matrix m_extrinsicMatrix; NEWMAT::Matrix m_intrinsicMatrix; DoubleArrayType m_radialDistortion; DoubleArrayType m_tangentialDistortion; PointMapList m_pointMapList; double m_averageProjectedHeight; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimQuickbirdMetaData.h000066400000000000000000000123261352751253100257430ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Class declaration for ossimQuickbirdMetaData. // // This class parses a Space Imaging Quickbird meta data file. // //******************************************************************** // $Id: ossimQuickbirdMetaData.h 14412 2009-04-27 16:58:46Z dburken $ #ifndef ossimQuickbirdMetaData_HEADER #define ossimQuickbirdMetaData_HEADER 1 #include #include #include #include #include #include #include class ossimFilename; class ossimKeywordlist; class OSSIMDLLEXPORT ossimQuickbirdMetaData : public ossimObject { public: enum QbParseTypes { QB_PARSE_TYPE_NONE = 0, QB_PARSE_TYPE_IMD = 1, QB_PARSE_TYPE_GEO = 2, QB_PARSE_TYPE_RPB = 4, QB_PARSE_TYPE_ATT = 8, QB_PARSE_TYPE_STE = 16, QB_PARSE_TYPE_EPH = 32, QB_PARSE_TYPE_TIL = 64, QB_PARSE_TYPE_ALL = QB_PARSE_TYPE_IMD | QB_PARSE_TYPE_GEO | QB_PARSE_TYPE_RPB | QB_PARSE_TYPE_ATT | QB_PARSE_TYPE_STE | QB_PARSE_TYPE_EPH | QB_PARSE_TYPE_TIL }; /** @brief default constructor */ ossimQuickbirdMetaData(); /** virtual destructor */ virtual ~ossimQuickbirdMetaData(); /** * @brief Open method that takes the image file. By default we just * parse the imd, for this the most common. * * @param imageFile Usually in the form of "po_2619900_pan_0000000.tif". * @param qbParseTypes The types of data to parse. These are bitwise or * together. By default we will only do QB_PARSE_TYPE_IMD. * if you want more just QB_PARSE_TYPE_IMD | QB_PARSE_TYPE_GEO. * * @return true on success, false on error. */ bool open(const ossimFilename &imageFile, ossim_int32 qbParseTypes = QB_PARSE_TYPE_IMD); void clearFields(); //--- // Convenient method to print important image info: //--- virtual std::ostream &print(std::ostream &out) const; /** * Method to save the state of the object to a keyword list. * Return true if ok or false on error. */ virtual bool saveState(ossimKeywordlist &kwl, const char *prefix = 0) const; /** * Method to the load (recreate) the state of the object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist &kwl, const char *prefix = 0); /** * @brief Method to parse Quickbird metadata file. * * @param metadata File name usually in the form of * ".IMD." * * @return true on success, false on error. */ bool parseMetaData(const ossimFilename &metadata); /** * @brief Method to parse Quickbird rpc file. * * @param metadata File name usually in the form of * ".GEO.txt" * * @return true on success, false on error. * * @note Currently NOT implemented. */ bool parseGEOData(const ossimFilename &data_file); bool parseATTData(const ossimFilename &data_file); bool parseEPHData(const ossimFilename &data_file); bool parseRPBData(const ossimFilename &data_file); bool parseSTEData(const ossimFilename &data_file); /** @return theSatID */ ossimString getSatID() const; bool getEndOfLine(char *fileBuf, ossimString lineBeginning, const char *format, ossimString &name); const ossimIpt &getImageSize() const; bool getMapProjectionKwl(const ossimFilename &imd_file, ossimKeywordlist &kwl); const std::shared_ptr getImdKwl() const; const std::shared_ptr getAttKwl() const; const std::shared_ptr getGeoKwl() const; const std::shared_ptr getEphKwl() const; const std::shared_ptr getRpbKwl() const; const std::shared_ptr getSteKwl() const; const std::shared_ptr getTilKwl() const; /***************************************** *parseATTData EPH GEO IMD RPB TIL * ****************************************/ private: ossimString theGenerationDate; ossimString theBandId; int theBitsPerPixel; ossimString theSatID; ossimString theTLCDate; ossim_float64 theSunAzimuth; ossim_float64 theSunElevation; ossim_float64 theSatAzimuth; ossim_float64 theSatElevation; int theTDILevel; std::vector theAbsCalFactors; ossimString theBandNameList; ossimIpt theImageSize; ossim_float64 thePNiirs; ossim_float64 theCloudCoverage; std::shared_ptr m_imdKwl; std::shared_ptr m_attKwl; std::shared_ptr m_geoKwl; std::shared_ptr m_ephKwl; std::shared_ptr m_rpbKwl; std::shared_ptr m_steKwl; std::shared_ptr m_tilKwl; bool parse(std::shared_ptr &kwl, const ossimFilename &file); TYPE_DATA }; #endif /* #ifndef ossimQuickbirdMetaData_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimQuickbirdRpcHeader.h000066400000000000000000000034771352751253100261270ustar00rootroot00000000000000#ifndef ossimQuickbirdRpcHeader_HEADER #define ossimQuickbirdRpcHeader_HEADER #include #include #include class OSSIM_DLL ossimQuickbirdRpcHeader : public ossimErrorStatusInterface { public: friend OSSIM_DLL std::ostream& operator << (std::ostream& out, const ossimQuickbirdRpcHeader& data); ossimQuickbirdRpcHeader(); bool open(const ossimFilename& file); bool isAPolynomial()const { return theSpecId.contains("A"); } bool isBPolynomial()const { return theSpecId.contains("B"); } bool isQuickbird() const { return theSatId.upcase().contains("QB"); } bool isWorldView() const { return theSatId.upcase().contains("WV"); } bool isWorldView1() const { return theSatId.upcase().contains("WV01"); } bool isWorldView2() const { return theSatId.upcase().contains("WV02"); } bool isWorldView3() const { return theSatId.upcase().contains("WV03"); } bool isWorldView4() const { return theSatId.upcase().contains("WV04"); } bool isGlobal()const; bool parseXml(); ossimFilename theFilename; ossimString theSatId; ossimString theBandId; ossimString theSpecId; double theErrBias; double theErrRand; ossim_int32 theLineOffset; ossim_int32 theSampOffset; double theLatOffset; double theLonOffset; double theHeightOffset; double theLineScale; double theSampScale; double theLatScale; double theLonScale; double theHeightScale; std::vector theLineNumCoeff; std::vector theLineDenCoeff; std::vector theSampNumCoeff; std::vector theSampDenCoeff; bool readCoeff(std::istream& in, std::vector& coeff); bool parseNameValue(const ossimString& line); }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimQuickbirdTile.h000066400000000000000000000066361352751253100251670ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id: ossimQuickbirdTile.h 19682 2011-05-31 14:21:20Z dburken $ #ifndef ossimQuickbirdTil_HEADER #define ossimQuickbirdTil_HEADER #include #include #include #include #include #include class ossimQuickbirdTileInfo { public: friend std::ostream& operator << (std::ostream& out, const ossimQuickbirdTileInfo& /* rhs */) { return out; } bool operator ==(const ossimString& rhs)const { return theFilename == rhs; } bool operator <(const ossimString& rhs)const { return theFilename < rhs; } bool operator >(const ossimString& rhs)const { return theFilename > rhs; } bool operator ==(const ossimQuickbirdTileInfo& rhs)const { return theFilename == rhs.theFilename; } bool operator <(const ossimQuickbirdTileInfo& rhs)const { return theFilename < rhs.theFilename; } bool operator >(const ossimQuickbirdTileInfo& rhs)const { return theFilename > rhs.theFilename; } ossimQuickbirdTileInfo() { initialize(); } void initialize() { theTileGroup = ""; theFilename = ""; theUlXOffset = OSSIM_INT_NAN; theUlYOffset = OSSIM_INT_NAN; theUrXOffset = OSSIM_INT_NAN; theUrYOffset = OSSIM_INT_NAN; theLrXOffset = OSSIM_INT_NAN; theLrYOffset = OSSIM_INT_NAN; theLlXOffset = OSSIM_INT_NAN; theLlYOffset = OSSIM_INT_NAN; theUlLon = ossim::nan(); theUlLat = ossim::nan(); theUrLon = ossim::nan(); theUrLat = ossim::nan(); theLrLon = ossim::nan(); theLrLat = ossim::nan(); theLlLon = ossim::nan(); theLlLat = ossim::nan(); } ossimString theTileGroup; ossimFilename theFilename; ossim_int32 theUlXOffset; ossim_int32 theUlYOffset; ossim_int32 theUrXOffset; ossim_int32 theUrYOffset; ossim_int32 theLrXOffset; ossim_int32 theLrYOffset; ossim_int32 theLlXOffset; ossim_int32 theLlYOffset; ossim_float64 theUlLon; ossim_float64 theUlLat; ossim_float64 theUrLon; ossim_float64 theUrLat; ossim_float64 theLrLon; ossim_float64 theLrLat; ossim_float64 theLlLon; ossim_float64 theLlLat; }; class ossimQuickbirdTile : public ossimErrorStatusInterface { public: ossimQuickbirdTile(); bool open(const ossimFilename tileFile); bool getInfo(ossimQuickbirdTileInfo& result, const ossimFilename& filename)const; const std::map& getMap() const { return theTileMap; } typedef std::map TileMap; protected: TileMap theTileMap; ossim_int32 theNumberOfTiles; ossimString theBandId; void parseTileGroup(std::istream& in, const ossimString& tileName); void parseNameValue(ossimString& name, ossimString& value, const ossimString& line)const; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfAttributeOffsetRecord.h000066400000000000000000000261141352751253100273460ustar00rootroot00000000000000#ifndef ossimRpfAttributeOffsetRecord_HEADER #define ossimRpfAttributeOffsetRecord_HEADER 1 #include #include #include class ossimRpfAttributeOffsetRecord { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfAttributeOffsetRecord& data); ossimRpfAttributeOffsetRecord(); virtual ~ossimRpfAttributeOffsetRecord(){} ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); void print(std::ostream& out)const; ossim_uint16 getAttributeId()const{return theAttributeId;} ossim_uint8 getParamterId()const{return theParameterId;} ossim_uint32 getAttributeRecordOffset()const{return theAttributeRecordOffset;} private: void clearFields(); /*! * The attribute Id. The Id and descriptions are taken from * MIL-STD-2411-1 and can have one of the following values: * * ID Description * _________________________________________________________________ * 1 Currency Date, 1 parameter: * 1. Date of most recent revision to the RPF * YYYYMMDD * 8 byte ascii value * * 2 Production Date, 1 parameter: * 1. Date the source data was transformed to RPF format * YYYYMMDD * 8 byte ascii value * * 3 Significant Date, 1 parameter: * 1. Most accurately describes the date of * the source data. * YYYYMMDD * 8 byte ascii value * * 4 Map/Chart source, 4 parameters: * 1. Short title for the id of a group of * products. ex: JOG 1501A ... * 10 byte ascii value * 2. The designation of the hardcopy source * 8 byte ascii value * 3. Old horizontal datum code. Original * horizontal datum of the hardcopy product * 4 byte ascii value * 4. Edition number of the source graphic * 7 byte ascii value. * * 5 Projection Systemd, 5 parameters: p. 38 of MIL-STD-2411-1 * 1. Projection Code. 2 byte ascii value * AC Albers Equal area * Requires Parameters A B C D * AL Azimuthal Equal Dist. * Requires Parameters A B * RB Hotline Oblique Mercator * Requires Parameters A B C * LE Lambert Conformal Conic * Requires Parameters A B C D * MC Mercator * Requires Parameters A B * OC Oblique Mercator * Requires Parameters A B C * OD Orthographic * Requires Parameters A B * PG Polar Stereo-graphic * Requires Parameters A B C D * PH Poly conic * Requires Parameters A B * TC Transverse Mercator * Requires Parameters A B C * UT Universal Transverse Mercator * Requires Parameters A * 2. Projection Param A: real 4 byte value * 3. Projeciton Param B: real 4 byte value * 4. Projection Param C: real 4 byte value * 5. Projection Param D: real 4 byte value * 6 Vertical Datum (1 parameter) p. 37 MIL-STD-2411-1 * 4 byte ascii * * MSL Mean Sea Level. All elevations in th data set * are referenced to the geoid of the specified datum * GEOD Geodetic (All elevations in the data set * are referenced to the ellipsoid of the specified * datum * 7 Horizontal Datum (1 parameter) * 4 byte ascii * * Look on p.33 of MIL-STD-2411-1. Too big to list * we will need a translation table for these * codes * 8 Vertical Absolute Accurracy (2 parameters) * 1. vertical absolute accuracy: 4 byte unsigned int * 2. Accuracy units of measure: 2 byte value * 0 unknown * 1 meters (Length area Volume) * 2 Kilopounds * 3 Seconds (of time) * 4 Meters/Second (speed) * 5 Cubic Meters per second (Flow) * 6 Volt (Electrical potential) * 7 Watt (Ten to 6 electirical power) * 8 Hertz * 9 +- DD MM SS.S (Angular) * 10 +- HH MM SS.S (Time) * 11 International Nautical Mile (1852 meters) * 12 knot * 13 Nautical mile per day * 14 Feet * 15 Fathom * 16 Micrometers (microns) * 17 Mils * 18 Seconds of Arc * 19 Minutes of Arc * 20 Degrees of arc * 999 Other * * 9 Horizontal Absolute Accuracy (2 parameters) * 1. Horizontal absolute accuracy: 4 byte unsigned int * 2. Accuracy units of measure: 2 byte value * 0 unknown * 1 meters (Length area Volume) * 2 Kilopounds * 3 Seconds (of time) * 4 Meters/Second (speed) * 5 Cubic Meters per second (Flow) * 6 Volt (Electrical potential) * 7 Watt (Ten to 6 electirical power) * 8 Hertz * 9 +- DD MM SS.S (Angular) * 10 +- HH MM SS.S (Time) * 11 International Nautical Mile (1852 meters) * 12 knot * 13 Nautical mile per day * 14 Feet * 15 Fathom * 16 Micrometers (microns) * 17 Mils * 18 Seconds of Arc * 19 Minutes of Arc * 20 Degrees of arc * 999 Other * * 10 Vertical Relative Accuracy (2 parameters) * 1. Vertical relative accuracy: 4 byte unsigned int * 2. Accuracy units of measure: 2 byte value * 0 unknown * 1 meters (Length area Volume) * 2 Kilopounds * 3 Seconds (of time) * 4 Meters/Second (speed) * 5 Cubic Meters per second (Flow) * 6 Volt (Electrical potential) * 7 Watt (Ten to 6 electirical power) * 8 Hertz * 9 +- DD MM SS.S (Angular) * 10 +- HH MM SS.S (Time) * 11 International Nautical Mile (1852 meters) * 12 knot * 13 Nautical mile per day * 14 Feet * 15 Fathom * 16 Micrometers (microns) * 17 Mils * 18 Seconds of Arc * 19 Minutes of Arc * 20 Degrees of arc * 999 Other * * 11 Horizontal Relative Accuracy (2 parameters) * 1. Horizontal relative accuracy: 4 byte unsigned int * 2. Accuracy units of measure: 2 byte value * 0 unknown * 1 meters (Length area Volume) * 2 Kilopounds * 3 Seconds (of time) * 4 Meters/Second (speed) * 5 Cubic Meters per second (Flow) * 6 Volt (Electrical potential) * 7 Watt (Ten to 6 electirical power) * 8 Hertz * 9 +- DD MM SS.S (Angular) * 10 +- HH MM SS.S (Time) * 11 International Nautical Mile (1852 meters) * 12 knot * 13 Nautical mile per day * 14 Feet * 15 Fathom * 16 Micrometers (microns) * 17 Mils * 18 Seconds of Arc * 19 Minutes of Arc * 20 Degrees of arc * 999 Other * * 12 Ellipsoid, 1 parameter: * 1. Ellipsoid code. 3 byte ascii * See p. 40 of MIL-STD-2411-1 * 13 Sounding Datumm, 1 parameter: 4 byte ascii * See p. 33 MIL-STD-2411-1 5.3.2.2 * 14 Navigation System, 1 parameter: * 1. Navigation code. 2 byte unsigned int * See MIL-STD-2411-1 5.3.2.4 * 15 Grid, 1 parameter: * 1. Grid code. 2 byte ascii * See MIL-STD-2411-1 5.3.2.7 * 16 Easterly Annual Magnetic Change, 2 parameters: * 1. Easterly annual magnetic change. 4 byte real * 2. Units of the change. See 5.3.2.6 of MIL-STD-2411-1 * 17 Westerly Annual Magnetic Change, 2 parameters: * 1. Westerly annual magnetic change. 4 byte real * 2. Units of the change. See 5.3.2.6 of MIL-STD-2411-1 * 18 Grid North Magnetic North ANgle, 2 paramters: * 1. Grid North - Magnetic North. 4 byte real * 2. Units of angle. 2 byte unsigned int * see 5.3.2.6 * 19 Grid convergence angle, 2 parameters: * 1. Grid convergence angle. 4 byte Real * 2. Units of angle. 2 byte unsigned int 5.3.2.6 * 20 Highest known elevation (4 parameters) * 1. Highest known elevation: 8 byte real * 2. Units of elevation: See 5.3.2.6 of MIL-STD-2411-1 * 3. Lat of elevation: 8 byte real in decimal degrees * 4. Lon of elevation: 8 byte real in decimal degrees * 21 Multiple legend, 1 paraemter: * 1. Name of legend file that applies to this * 12 byte ascii * 22 Image source, 2 parameters: * 1. Source of data from which this * RPF was derived. ex: SPOT. Landsat7, Landsat4. * for CDTED: "imagery, "carto" * 12 byte ascii * 2. GSD. Ground sample or post distance. * 4 byte unsigned int * 23 Data Level, 1 parameter: * 1. The level of the source. For example: * if this is a DTED or CDTED it would * distinguish between level 1 and 2 */ ossim_uint16 theAttributeId; /*! * This defines which parameter number for theAttrributeId */ ossim_uint8 theParameterId; /*! * This is a 1 byte field. If the value is 0 then * the attribute applies to the entire geographic coverage * of this frame. If it's > 0 then the areal coverage * where the given attribute applies is defined in the corresponding * explicit areal coverage record in the explicit areal * coverage table. */ ossim_uint8 theArealCoverageSequenceNumber; /*! * a 4-byte unsigned integer. displacement in bytes measured * from the beginning of the [attribute subsection] and the first * byte of the [attribute record]. */ ossim_uint32 theAttributeRecordOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfAttributeSectionSubheader.h000066400000000000000000000030511352751253100302030ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: Rpf support class // //******************************************************************** // $Id$ #ifndef ossimRpfAttributeSectionSubheader_HEADER #define ossimRpfAttributeSectionSubheader_HEADER 1 #include #include #include class ossimRpfAttributeSectionSubheader { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfAttributeSectionSubheader& data); ossimRpfAttributeSectionSubheader(); virtual ~ossimRpfAttributeSectionSubheader(){} ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); virtual void print(std::ostream& out)const; ossim_uint16 getNumberOfAttributeOffsetRecords()const { return theNumberOfAttributeOffsetRecords; } ossim_uint16 getAttributeOffsetTableOffset()const { return theAttributeOffsetTableOffset; } ossim_uint64 getSubheaderStart()const; ossim_uint64 getSubheaderEnd()const; private: void clearFields(); ossim_uint16 theNumberOfAttributeOffsetRecords; ossim_uint16 theNumberOfExplicitArealCoverageRecords; ossim_uint32 theAttributeOffsetTableOffset; ossim_uint16 theAttribteOffsetRecordLength; mutable ossim_uint64 theAttributeSectionSubheaderStart; mutable ossim_uint64 theAttributeSectionSubheaderEnd; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfAttributes.h000066400000000000000000000310071352751253100252200ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id: ossimRpfAttributes.h 14241 2009-04-07 19:59:23Z dburken $ #ifndef ossimRpfAttributes_HEADER #define ossimRpfAttributes_HEADER #include #include class OSSIM_DLL ossimRpfAttributes { public: friend OSSIM_DLL std::ostream& operator<<(std::ostream& out, const ossimRpfAttributes& data); ossimRpfAttributes(); ~ossimRpfAttributes(); void setAttributeFlag(ossim_uint32 id, bool flag); bool getAttributeFlag(ossim_uint32 id)const; /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; bool isEmpty()const; void clearFields(); /*! * The attribute Id. The Id and descriptions are taken from * MIL-STD-2411-1 and can have one of the following values: * _________________________________________________________________ * 1 Currency Date, 1 parameter: * 1. Date of most recent revision to the RPF * YYYYMMDD * 8 byte ascii value */ ossimString theCurrencyDate; /*! 2 Production Date, 1 parameter: * 1. Date the source data was transformed to RPF format * YYYYMMDD * 8 byte ascii value */ ossimString theProductionDate; /*! 3 Significant Date, 1 parameter: * 1. Most accurately describes the date of * the source data. * YYYYMMDD * 8 byte ascii value */ ossimString theSignificantDate; /*! * 4 Map/Chart source, 4 parameters: * 1. Short title for the id of a group of * products. ex: JOG 1501A ... * 10 byte ascii value * 2. The designation of the hardcopy source * 8 byte ascii value * 3. Old horizontal datum code. Original * horizontal datum of the hardcopy product * 4 byte ascii value * 4. Edition number of the source graphic * 7 byte ascii value. */ ossimString theChartSeriesCode; ossimString theMapDesignationCode; ossimString theOldHorDatum; ossimString theEdition; /*! * 5 Projection Systemd, 5 parameters: p. 38 of MIL-STD-2411-1 * 1. Projection Code. 2 byte ascii value * AC Albers Equal area * Requires Parameters A B C D * AL Azimuthal Equal Dist. * Requires Parameters A B * RB Hotline Oblique Mercator * Requires Parameters A B C * LE Lambert Conformal Conic * Requires Parameters A B C D * MC Mercator * Requires Parameters A B * OC Oblique Mercator * Requires Parameters A B C * OD Orthographic * Requires Parameters A B * PG Polar Stereo-graphic * Requires Parameters A B C D * PH Poly conic * Requires Parameters A B * TC Transverse Mercator * Requires Parameters A B C * UT Universal Transverse Mercator * Requires Parameters A * 2. Projection Param A: real 4 byte value * 3. Projeciton Param B: real 4 byte value * 4. Projection Param C: real 4 byte value * 5. Projection Param D: real 4 byte value */ ossimString theProjectionCode; float theProjectionA; float theProjectionB; float theProjectionC; float theProjectionD; /*! * 6 Vertical Datum (1 parameter) p. 37 MIL-STD-2411-1 * 4 byte ascii * * MSL Mean Sea Level. All elevations in th data set * are referenced to the geoid of the specified datum * GEOD Geodetic (All elevations in the data set * are referenced to the ellipsoid of the specified * datum */ ossimString theVertDatumCode; /*! * 7 Horizontal Datum (1 parameter) * 4 byte ascii * * Look on p.33 of MIL-STD-2411-1. Too big to list * we will need a translation table for these * codes */ ossimString theHorDatumCode; /*! * 8 Vertical Absolute Accurracy (2 parameters) * 1. vertical absolute accuracy: 4 byte unsigned int * 2. Accuracy units of measure: 2 byte value * 0 unknown * 1 meters (Length area Volume) * 2 Kilopounds * 3 Seconds (of time) * 4 Meters/Second (speed) * 5 Cubic Meters per second (Flow) * 6 Volt (Electrical potential) * 7 Watt (Ten to 6 electirical power) * 8 Hertz * 9 +- DD MM SS.S (Angular) * 10 +- HH MM SS.S (Time) * 11 International Nautical Mile (1852 meters) * 12 knot * 13 Nautical mile per day * 14 Feet * 15 Fathom * 16 Micrometers (microns) * 17 Mils * 18 Seconds of Arc * 19 Minutes of Arc * 20 Degrees of arc * 999 Other */ ossim_uint32 theVertAbsAccuracy; ossim_uint16 theVertAbsUnits; /*! * 9 Horizontal Absolute Accuracy (2 parameters) * 1. Horizontal absolute accuracy: 4 byte unsigned int * 2. Accuracy units of measure: 2 byte value * 0 unknown * 1 meters (Length area Volume) * 2 Kilopounds * 3 Seconds (of time) * 4 Meters/Second (speed) * 5 Cubic Meters per second (Flow) * 6 Volt (Electrical potential) * 7 Watt (Ten to 6 electirical power) * 8 Hertz * 9 +- DD MM SS.S (Angular) * 10 +- HH MM SS.S (Time) * 11 International Nautical Mile (1852 meters) * 12 knot * 13 Nautical mile per day * 14 Feet * 15 Fathom * 16 Micrometers (microns) * 17 Mils * 18 Seconds of Arc * 19 Minutes of Arc * 20 Degrees of arc * 999 Other */ ossim_uint32 theHorAbsAccuracy; ossim_uint16 theHorAbsUnits; /*! * 10 Vertical Relative Accuracy (2 parameters) * 1. Vertical relative accuracy: 4 byte unsigned int * 2. Accuracy units of measure: 2 byte value * 0 unknown * 1 meters (Length area Volume) * 2 Kilopounds * 3 Seconds (of time) * 4 Meters/Second (speed) * 5 Cubic Meters per second (Flow) * 6 Volt (Electrical potential) * 7 Watt (Ten to 6 electirical power) * 8 Hertz * 9 +- DD MM SS.S (Angular) * 10 +- HH MM SS.S (Time) * 11 International Nautical Mile (1852 meters) * 12 knot * 13 Nautical mile per day * 14 Feet * 15 Fathom * 16 Micrometers (microns) * 17 Mils * 18 Seconds of Arc * 19 Minutes of Arc * 20 Degrees of arc * 999 Other */ ossim_uint32 theVertRelAccuracy; ossim_uint16 theVertRelUnits; /*! * 11 Horizontal Relative Accuracy (2 parameters) * 1. Horizontal relative accuracy: 4 byte unsigned int * 2. Accuracy units of measure: 2 byte value * 0 unknown * 1 meters (Length area Volume) * 2 Kilopounds * 3 Seconds (of time) * 4 Meters/Second (speed) * 5 Cubic Meters per second (Flow) * 6 Volt (Electrical potential) * 7 Watt (Ten to 6 electirical power) * 8 Hertz * 9 +- DD MM SS.S (Angular) * 10 +- HH MM SS.S (Time) * 11 International Nautical Mile (1852 meters) * 12 knot * 13 Nautical mile per day * 14 Feet * 15 Fathom * 16 Micrometers (microns) * 17 Mils * 18 Seconds of Arc * 19 Minutes of Arc * 20 Degrees of arc * 999 Other */ ossim_uint32 theHorRelAccuracy; ossim_uint16 theHorRelUnits; /*! * 12 Ellipsoid, 1 parameter: * 1. Ellipsoid code. 3 byte ascii * See p. 40 of MIL-STD-2411-1 */ ossimString ellipsoidCode; /*! * 13 Sounding Datumm, 1 parameter: 4 byte ascii * See p. 33 MIL-STD-2411-1 5.3.2.2 */ ossimString theSoundingDatumCode; /*! * 14 Navigation System, 1 parameter: * 1. Navigation code. 2 byte unsigned int * See MIL-STD-2411-1 5.3.2.4 */ ossim_uint16 theNavSystemCode; /*! * 15 Grid, 1 parameter: * 1. Grid code. 2 byte ascii * See MIL-STD-2411-1 5.3.2.7 */ ossimString theGridCode; /*! * 16 Easterly Annual Magnetic Change, 2 parameters: * 1. Easterly annual magnetic change. 4 byte real * 2. Units of the change. See 5.3.2.6 of MIL-STD-2411-1 */ float theEeasterlyMagChange; ossim_uint16 theEasterlyMagChangeUnits; /*! * 17 Westerly Annual Magnetic Change, 2 parameters: * 1. Westerly annual magnetic change. 4 byte real * 2. Units of the change. See 5.3.2.6 of MIL-STD-2411-1 */ float theWesterlyMagChange; ossim_uint16 theWesterlyMagChangeUnits; /*! * 18 Grid North Magnetic North ANgle, 2 paramters: * 1. Grid North - Magnetic North. 4 byte real * 2. Units of angle. 2 byte unsigned int * see 5.3.2.6 */ float theMagAngle; ossim_uint16 theMagAngleUnits; /*! * 19 Grid convergence angle, 2 parameters: * 1. Grid convergence angle. 4 byte Real * 2. Units of angle. 2 byte unsigned int 5.3.2.6 */ float theGridConver; ossim_uint16 theGridConverUnits; /*! * 20 Highest known elevation (4 parameters) * 1. Highest known elevation: 8 byte real * 2. Units of elevation: See 5.3.2.6 of MIL-STD-2411-1 * 3. Lat of elevation: 8 byte real in decimal degrees * 4. Lon of elevation: 8 byte real in decimal degrees */ double theHighElevation; ossim_uint16 theHighElevationUnits; double theHighLat; double theHighLon; /*! 21 Multiple legend, 1 paraemter: * 1. Name of legend file that applies to this * 12 byte ascii */ ossimString theLegendFileName; /*! * 22 Image source, 2 parameters: * 1. Source of data from which this * RPF was derived. ex: SPOT. Landsat7, Landsat4. * for CDTED: "imagery, "carto" * 12 byte ascii * * 2. GSD. Ground sample or post distance. * 4 byte unsigned int */ ossimString theDataSource; // [12]; ossim_uint32 theGsd; // uint /*! * 23 Data Level, 1 parameter: * 1. The level of the source. For example: * if this is a DTED or CDTED it would * distinguish between level 1 and 2 */ ossim_uint16 theDataLevel; // ushort protected: std::map theAttributeIdBoolMap; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfBoundaryRectRecord.h000066400000000000000000000051341352751253100266340ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfBoundaryRectRecord.h 16997 2010-04-12 18:53:48Z dburken $ #ifndef ossimRpfBoundaryRectRecord_HEADER #define ossimRpfBoundaryRectRecord_HEADER #include #include #include #include #include class ossimRpfBoundaryRectRecord { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfBoundaryRectRecord& data); /** default constructor */ ossimRpfBoundaryRectRecord(); /** copy constructor */ ossimRpfBoundaryRectRecord(const ossimRpfBoundaryRectRecord& ojb); /** assignment operator */ const ossimRpfBoundaryRectRecord& operator=(const ossimRpfBoundaryRectRecord& rhs); /** destructor */ ~ossimRpfBoundaryRectRecord(); ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); /** * @brief Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); void clearFields(); ossimString getProductType()const{return ossimString(m_productDataType);} ossimString getScale()const{return ossimString(m_scale);} ossimString getCompressionRatio()const{return ossimString(m_compressionRatio);} ossim_uint32 getNumberOfFramesVertical()const{ return m_numberOfFramesNorthSouth;} ossim_uint32 getNumberOfFramesHorizontal()const{ return m_numberOfFramesEastWest;} const ossimRpfCoverageSection& getCoverage()const{return m_coverage;} void setCoverage(const ossimRpfCoverageSection& coverage); char getZone()const{return m_zone;} /** * @brief prints to out. * @param out Stream to print to. * @param prefix If not empty will be prepended onto the keyword. */ std::ostream& print(std::ostream& out, ossimString prefix) const; private: /*! * a five byte asci field */ char m_productDataType[6]; /*! * five byte asci field */ char m_compressionRatio[6]; /*! * 12 byte asci field. */ char m_scale[13]; /*! * */ char m_zone; /*! * is a 5 byte asci field. */ char m_producer[6]; ossimRpfCoverageSection m_coverage; /*! * Four byte fields. */ ossim_uint32 m_numberOfFramesNorthSouth; /*! * Four byte fields. */ ossim_uint32 m_numberOfFramesEastWest; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfBoundaryRectSectionSubheader.h000066400000000000000000000037331352751253100306500ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfBoundaryRectSectionSubheader.h 16997 2010-04-12 18:53:48Z dburken $ #ifndef ossimRpfBoundaryRectSectionSubheader_HEADER #define ossimRpfBoundaryRectSectionSubheader_HEADER #include #include #include #include class ossimRpfBoundaryRectSectionSubheader : public ossimReferenced { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfBoundaryRectSectionSubheader &data); /** default constructor */ ossimRpfBoundaryRectSectionSubheader(); /** copy constructor */ ossimRpfBoundaryRectSectionSubheader(const ossimRpfBoundaryRectSectionSubheader& obj); /** assignment operator */ const ossimRpfBoundaryRectSectionSubheader& operator=( const ossimRpfBoundaryRectSectionSubheader& rhs); virtual ~ossimRpfBoundaryRectSectionSubheader(); ossimErrorCode parseStream(std::istream& in, ossimByteOrder); /** * @brief Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); /** * @brief print method * @param out String to output to. * @return output stream. */ std::ostream& print(std::ostream& out) const; ossim_uint16 getNumberOfEntries() const; ossim_uint32 getTableOffset() const; ossim_uint16 getLengthOfEachEntry() const; void setNumberOfEntries(ossim_uint16 entries); void setTableOffset(ossim_uint32 offset); void setLengthOfEachEntry(ossim_uint16 length); void clearFields(); private: ossim_uint32 m_rectangleTableOffset; ossim_uint16 m_numberOfEntries; ossim_uint16 m_lengthOfEachEntry; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfBoundaryRectTable.h000066400000000000000000000035011352751253100264410ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfBoundaryRectTable.h 16997 2010-04-12 18:53:48Z dburken $ #ifndef ossimRpfBoundaryRectTable_HEADER #define ossimRpfBoundaryRectTable_HEADER #include #include #include #include #include #include class ossimRpfBoundaryRectTable : public ossimReferenced { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfBoundaryRectTable& data); /** default constructor */ ossimRpfBoundaryRectTable(ossim_uint32 numberOfEntries=0); /** copy constructor */ ossimRpfBoundaryRectTable(const ossimRpfBoundaryRectTable& obj); /** assignment operator */ const ossimRpfBoundaryRectTable& operator=(const ossimRpfBoundaryRectTable& rhs); virtual ~ossimRpfBoundaryRectTable(); ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); /** * @brief Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); void setNumberOfEntries(ossim_uint32 numberOfEntries); ossim_uint32 getNumberOfEntries() const; /** * @brief Gets record for entry. * @param entry Zero base entry to get. * @param record Record to initialize. * @return true on success, false if entry doesn't exist. */ bool getEntry(ossim_uint32 entry, ossimRpfBoundaryRectRecord& record) const; std::ostream& print(std::ostream& out)const; private: std::vector m_table; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfColorConverterOffsetRecord.h000066400000000000000000000031651352751253100303520ustar00rootroot00000000000000#ifndef ossimRpfColorConverterOffsetRecord_HEADER #define ossimRpfColorConverterOffsetRecord_HEADER 1 #include #include #include class ossimRpfColorConverterOffsetRecord { public: friend std::ostream& operator <<( std::ostream& out, const ossimRpfColorConverterOffsetRecord& data); ossimRpfColorConverterOffsetRecord(); ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); void clearFields(); /*! * Is a two byte field as is described in Mil-STD-2411-1. * The id can be one of: * * 1 CCT/1--->1 * 2 CCT/1--->2 * 3 CCT/1--->3 * 4 CCT/1--->4 * 5 CCT/2--->2 * 6 CCT/2--->3 * 7 CCT/2--->4 * 8 CCT/3--->3 * * where CCT stands for Color Converter Table */ ossim_uint16 theColorConverterTableId; /*! * Is a 4 byte field. */ ossim_uint32 theNumberOfColorConverterRecords; /*! * Is a 4 byte field indicating the offset from the start of * the color converter subsection to the color converter table. */ ossim_uint32 theColorConverterTableOffset; /*! * Is a 4 byte field indicating the offset from the colormap * subsection to the source color/grayscale offset table. */ ossim_uint32 theSourceColorGrayscaleOffsetTableOffset; /*! * Is a 4 byte field indicating the offset from the colormap * subsection to the color/graysscale offset table. */ ossim_uint32 theTargetColorGrayscaleOffsetTableOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfColorConverterSubsection.h000066400000000000000000000031761352751253100301050ustar00rootroot00000000000000#ifndef ossimRpfColorConverterSubsection_HEADER #define ossimRpfColorConverterSubsection_HEADER 1 #include #include #include #include #include class ossimRpfColorConverterSubsection { public: friend std::ostream& operator <<( std::ostream& out, const ossimRpfColorConverterSubsection& data); ossimRpfColorConverterSubsection(); virtual ~ossimRpfColorConverterSubsection(){} ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); ossim_uint32 getStartOffset()const{return theStartOffset;} ossim_uint32 getEndOffset()const{return theEndOffset;} const std::vector& getColorConversionTable()const { return theTableList; } const ossimRpfColorConverterTable* getColorConversionTable(ossim_uint32 givenThisNumberOfEntires)const; void setNumberOfColorConverterOffsetRecords(ossim_uint16 numberOfRecords); void print(std::ostream& out)const; void clearFields(); private: ossimRpfColorConverterSubsection(const ossimRpfColorConverterSubsection&){}//hide void operator =(const ossimRpfColorConverterSubsection&){}//hide ossim_uint32 theStartOffset; ossim_uint32 theEndOffset; ossim_uint16 theNumberOfColorConverterOffsetRecords; ossim_uint32 theColorConverterOffsetTableOffset; ossim_uint16 theColorConverterOffsetRecordLength; ossim_uint16 theConverterRecordLength; std::vector theTableList; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfColorConverterTable.h000066400000000000000000000024161352751253100270120ustar00rootroot00000000000000#ifndef ossimRpfColorConverterTable_HEADER #define ossimRpfColorConverterTable_HEADER 1 #include #include #include class ossimRpfColorConverterTable { public: friend std::ostream& operator <<( std::ostream& out, const ossimRpfColorConverterTable& data); ossimRpfColorConverterTable(); virtual ~ossimRpfColorConverterTable(); ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); void print(std::ostream& out)const; ossim_uint32 getEntry(ossim_uint32 entry){return theColorGrayscaleTableEntryList[entry];} void setNumberOfEntries(ossim_uint32 entries); void setTableId(ossim_uint16 id); const ossim_uint32* getEntryList()const{return theColorGrayscaleTableEntryList;} ossim_uint32 getNumberOfEntries()const{return theNumberOfEntries;} private: /*! * This will not be a field read from the stream this is * the value in the color converter offset table. */ ossim_uint16 theTableId; /*! * Holds the number of entries */ ossim_uint32 theNumberOfEntries; /*! * This will hold the lookup table values. */ ossim_uint32* theColorGrayscaleTableEntryList; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfColorGrayscaleOffsetRecord.h000066400000000000000000000023301352751253100303060ustar00rootroot00000000000000#ifndef ossimRpfColorGrayscaleOffsetRecord_HEADER #define ossimRpfColorGrayscaleOffsetRecord_HEADER 1 #include #include #include class ossimRpfColorGrayscaleOffsetRecord { public: friend std::ostream& operator <<( std::ostream& out, const ossimRpfColorGrayscaleOffsetRecord& data); ossimRpfColorGrayscaleOffsetRecord(); ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); void print(std::ostream& out)const; void clearFields(); ossim_uint16 getColorGrayscaleTableId()const { return theColorGrayscaleTableId; } ossim_uint32 getNumberOfColorGrayscaleRecords()const { return theNumberOfColorGrayscaleRecords; } ossim_uint32 getColorGrayscaleTableOffset()const { return theColorGrayscaleTableOffset; } private: ossim_uint16 theColorGrayscaleTableId; ossim_uint32 theNumberOfColorGrayscaleRecords; unsigned char theColorGrayscaleElementLength; ossim_uint16 theHistogramRecordLength; ossim_uint32 theColorGrayscaleTableOffset; ossim_uint32 theHistogramTableOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfColorGrayscaleSubheader.h000066400000000000000000000025171352751253100276320ustar00rootroot00000000000000#ifndef ossimRpfColorGrayscaleSubheader_HEADER #define ossimRpfColorGrayscaleSubheader_HEADER 1 #include #include #include class ossimRpfColorGrayscaleSubheader { public: friend std::ostream& operator <<( std::ostream& out, const ossimRpfColorGrayscaleSubheader& data); ossimRpfColorGrayscaleSubheader(); ~ossimRpfColorGrayscaleSubheader(){} ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); void print(std::ostream& out)const; unsigned long getStartOffset()const { return theStartOffset; } unsigned long getEndOffset()const { return theEndOffset; } unsigned long getNumberOfColorGreyscaleOffsetRecords()const { return theNumberOfColorGreyscaleOffsetRecords; } unsigned long getNumberOfColorConverterOffsetRecords()const { return theNumberOfColorConverterOffsetRecords; } private: void clearFields(); unsigned long theStartOffset; unsigned long theEndOffset; unsigned char theNumberOfColorGreyscaleOffsetRecords; unsigned char theNumberOfColorConverterOffsetRecords; /*! * 12 byte field. */ ossimString theColorGrayscaleFilename; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfColorGrayscaleTable.h000066400000000000000000000031311352751253100267500ustar00rootroot00000000000000#ifndef ossimRpfColorGrayscaleTable_HEADER #define ossimRpfColorGrayscaleTable_HEADER 1 #include #include #include class ossimRpfColorGrayscaleTable { public: friend std::ostream& operator <<( std::ostream& out, const ossimRpfColorGrayscaleTable& data); ossimRpfColorGrayscaleTable(); ossimRpfColorGrayscaleTable(const ossimRpfColorGrayscaleTable& rhs); virtual ~ossimRpfColorGrayscaleTable(); ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); void setTableData(unsigned short id, unsigned long numberOfElements); const ossimRpfColorGrayscaleTable& operator =(const ossimRpfColorGrayscaleTable&); const unsigned char* getData()const{return theData;} const unsigned char* getStartOfData(unsigned long entry)const; unsigned short getTableId()const{return theTableId;} unsigned long getNumberOfElements()const{return theNumberOfElements;} private: unsigned long theNumberOfElements; unsigned long theTotalNumberOfBytes; /*! * This will not be parsed from the stream. This is set when * reading the offset record for this table. The id defines * the format of the data buffer. if the id is : * * 1 then the buffer is in the format of RGB * 2 "" RGBM * 3 "" M * 4 "" CMYK */ unsigned short theTableId; unsigned char* theData; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfComponentIdLut.h000066400000000000000000000031261352751253100257770ustar00rootroot00000000000000//---------------------------------------------------------------------------- // File: ossimRpfComponentIdLut.h // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: See class description. // //---------------------------------------------------------------------------- // $Id: ossimRpfComponentIdLut.h 20324 2011-12-06 22:25:23Z dburken $ #ifndef ossimRpfComponentIdLut_HEADER #define ossimRpfComponentIdLut_HEADER 1 #include #include /** * @class ossimRpfComponentIdLut * * @brief Lookup table for RPF section/component ID's. * * Used to convert from RPF section/component ID's to strings and vice versa. * See MIL-STD-2411-1, section 5.1.1 for detailed information. Defines located * in ossimRpfConstants.h. This class is a singleton, only one of them so all * callers must go through the instance method like: * ossimRpfComponentIdLut::instance()->getEntryString(id); */ class OSSIMDLLEXPORT ossimRpfComponentIdLut : public ossimLookUpTable { public: /** @return The static instance of an ossimRpfComponentIdLut object. */ static ossimRpfComponentIdLut* instance(); /** @brief destructor */ virtual ~ossimRpfComponentIdLut(); /** @return Keyword: ("rpf_component_id", "") */ virtual ossimKeyword getKeyword() const; private: /** @brief Hidden from use constructor. */ ossimRpfComponentIdLut(); /** @brief The single instance of this class. */ static ossimRpfComponentIdLut* theInstance; }; #endif /* #ifndef ossimRpfComponentIdLut_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfCompressionLookupOffsetRecord.h000066400000000000000000000027721352751253100311020ustar00rootroot00000000000000#ifndef ossimRpfCompressionLookupOffsetRecord_HEADER #define ossimRpfCompressionLookupOffsetRecord_HEADER 1 #include #include #include class ossimRpfCompressionLookupOffsetRecord { public: friend std::ostream& operator <<( std::ostream &out, const ossimRpfCompressionLookupOffsetRecord& data); ossimRpfCompressionLookupOffsetRecord(); ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); void print(std::ostream& out)const; ossim_uint16 getCompressionLookupTableId()const { return theCompressionLookupTableId; } ossim_uint32 getNumberOfCompressionLookupRecords()const { return theNumberOfCompressionLookupRecords; } ossim_uint16 getNumberOfValuesPerCompressionLookupRecord()const { return theNumberOfValuesPerCompressionLookupRecord; } ossim_uint16 getCompressionLookupValueBitLength()const { return theCompressionLookupValueBitLength; } ossim_uint32 getCompressionLookupTableOffset()const { return theCompressionLookupTableOffset; } private: void clearFields(); ossim_uint16 theCompressionLookupTableId; ossim_uint32 theNumberOfCompressionLookupRecords; ossim_uint16 theNumberOfValuesPerCompressionLookupRecord; ossim_uint16 theCompressionLookupValueBitLength; ossim_uint32 theCompressionLookupTableOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfCompressionSection.h000066400000000000000000000033411352751253100267200ustar00rootroot00000000000000#ifndef ossimRpfCompressionSection_HEADER #define ossimRpfCompressionSection_HEADER 1 #include #include #include #include class ossimRpfCompressionSectionSubheader; struct ossimRpfCompressionOffsetTableData { friend std::ostream& operator<<( std::ostream& out, const ossimRpfCompressionOffsetTableData& data); ossimRpfCompressionOffsetTableData(); ossimRpfCompressionOffsetTableData(const ossimRpfCompressionOffsetTableData& rhs); ~ossimRpfCompressionOffsetTableData(); const ossimRpfCompressionOffsetTableData& operator =(const ossimRpfCompressionOffsetTableData& rhs); ossim_uint16 theTableId; ossim_uint32 theNumberOfLookupValues; ossim_uint16 theCompressionLookupValueBitLength; ossim_uint16 theNumberOfValuesPerLookup; ossim_uint8* theData; }; class ossimRpfCompressionSection { public: friend std::ostream& operator << ( std::ostream& out, const ossimRpfCompressionSection& data); ossimRpfCompressionSection(); virtual ~ossimRpfCompressionSection(); ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); void print(std::ostream& out)const; const std::vector& getTable()const { return theTable; } const ossimRpfCompressionSectionSubheader* getSubheader()const { return theSubheader; } private: void clearTable(); ossimRpfCompressionSectionSubheader* theSubheader; ossim_uint32 theCompressionLookupOffsetTableOffset; ossim_uint16 theCompressionLookupTableOffsetRecordLength; std::vector theTable; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfCompressionSectionSubheader.h000066400000000000000000000032541352751253100305460ustar00rootroot00000000000000#ifndef ossimRpfCompressionSectionSubheader_HEADER #define ossimRpfCompressionSectionSubheader_HEADER 1 #include #include #include class ossimRpfCompressionSectionSubheader { public: friend std::ostream& operator<<( std::ostream& out, const ossimRpfCompressionSectionSubheader& data); ossimRpfCompressionSectionSubheader(); virtual ~ossimRpfCompressionSectionSubheader(){} ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); unsigned long getStartOffset()const{return theStartOffset;} unsigned long getEndOffset()const{return theEndOffset;} unsigned short getCompressionAlgorithmId()const { return theCompressionAlgorithmId; } unsigned short getNumberOfCompressionLookupOffsetRecords()const { return theNumberOfCompressionLookupOffsetRecords; } unsigned short getNumberOfCompressionParameterOffsetRecords()const { return theNumberOfCompressionParameterOffsetRecords; } void print(std::ostream& out)const; private: void clearFields(); /*! * helper varible that holds the starting absolute * offset to the start of the this data. */ unsigned long theStartOffset; /*! * helper varible that holds the starting absolute * offset to the end of the this data. */ unsigned long theEndOffset; /*! * Current ids are: * * 1 VQ * 2 Jpeg Lossless */ unsigned short theCompressionAlgorithmId; unsigned short theNumberOfCompressionLookupOffsetRecords; unsigned short theNumberOfCompressionParameterOffsetRecords; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfConstants.h000066400000000000000000000032501352751253100250450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************** // $Id: ossimRpfConstants.h 9967 2006-11-29 02:01:23Z gpotts $ // #ifndef ossimRpfComponentId_HEADER #define ossimRpfComponentId_HEADER const unsigned long OSSIM_RPF_ULONG_NULL = 0xFFFFFFFF; enum ossimRpfComponentId { OSSIM_RPF_HEADER_COMPONENT = 128, OSSIM_RPF_LOCATION_COMPONENT = 129, OSSIM_RPF_COVERAGE_SECTION_SUBHEADER = 130, OSSIM_RPF_COMPRESSION_SECTION_SUBHEADER = 131, OSSIM_RPF_COMPRESION_LOOKUP_SUBSECTION = 132, OSSIM_RPF_COMPRESION_PARAMETER_SUBSECTION = 133, OSSIM_RPF_COLOR_GRAYSCALE_SECTION_SUBHEADER = 134, OSSIM_RPF_COLORMAP_SUBSECTION = 135, OSSIM_RPF_IMAGE_DESCRIPTION_SUBHEADER = 136, OSSIM_RPF_IMAGE_DISPLAY_PARAMETERS_SUBHEADER = 137, OSSIM_RPF_MASK_SUBSECTION = 138, OSSIM_RPF_COLOR_CONVERTER_SUBSECTION = 139, OSSIM_RPF_SPATIAL_DATA_SUBSECTION = 140, OSSIM_RPF_ATTRIBUTE_SECTION_SUBHEADER = 141, OSSIM_RPF_ATTRIBUTE_SUBSECTION = 142, OSSIM_RPF_EXPLICIT_AREAL_COVERAGE_TABLE = 143, OSSIM_RPF_RELATED_IMAGES_SECTION_SUBHEADER = 144, OSSIM_RPF_RELATED_IMAGES_SUBSECTION = 145, OSSIM_RPF_REPLACE_UPDATE_SECTION_SUBHEADER = 146, OSSIM_RPF_REPLACE_UPDATE_TABLE = 147, OSSIM_RPF_BOUNDARY_RECT_SECTION_SUBHEADER = 148, OSSIM_RPF_BOUNDARY_RECT_TABLE = 149, OSSIM_RPF_FRAME_FILE_INDEX_SECTION_SUBHEADER = 150, OSSIM_RPF_FRAME_FILE_INDEX_SUBSECTION = 151, OSSIM_RPF_COLOR_TABLE_INDEX_SECTION_SUBHEADER = 152, OSSIM_RPF_COLOR_TABLE_INDEX_RECORD = 153 }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfCoverageSection.h000066400000000000000000000117341352751253100261570ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfCoverageSection.h 16997 2010-04-12 18:53:48Z dburken $ #ifndef ossimRpfCoverageSection_HEADER #define ossimRpfCoverageSection_HEADER #include #include #include #include class ossimRpfCoverageSection { public: friend std::ostream& operator <<(std::ostream &out, const ossimRpfCoverageSection &data); ossimRpfCoverageSection(); ossimRpfCoverageSection(const ossimRpfCoverageSection& obj); const ossimRpfCoverageSection& operator=(const ossimRpfCoverageSection& rhs); ~ossimRpfCoverageSection(){} ossimErrorCode parseStream(std::istream &in, ossimByteOrder byteOrder); /** * @brief Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; void clearFields(); bool isGeographicRectNull()const { return ((theUpperLeftLat == OSSIM_RPF_ULONG_NULL) && (theUpperLeftLon == OSSIM_RPF_ULONG_NULL) && (theLowerLeftLat == OSSIM_RPF_ULONG_NULL) && (theLowerLeftLon == OSSIM_RPF_ULONG_NULL) && (theLowerRightLat == OSSIM_RPF_ULONG_NULL) && (theLowerRightLon == OSSIM_RPF_ULONG_NULL) && (theUpperRightLat == OSSIM_RPF_ULONG_NULL) && (theUpperRightLon == OSSIM_RPF_ULONG_NULL)); } bool isIntervalNull()const { return ((theVerticalInterval == OSSIM_RPF_ULONG_NULL)&& (theHorizontalInterval == OSSIM_RPF_ULONG_NULL)); } ossim_float64 getUlLat()const{return theUpperLeftLat;} ossim_float64 getUlLon()const{return theUpperLeftLon;} ossim_float64 getLlLat()const{return theLowerLeftLat;} ossim_float64 getLlLon()const{return theLowerLeftLon;} ossim_float64 getLrLat()const{return theLowerRightLat;} ossim_float64 getLrLon()const{return theLowerRightLon;} ossim_float64 getUrLat()const{return theUpperRightLat;} ossim_float64 getUrLon()const{return theUpperRightLon;} ossim_float64 getVerticalResolution()const{return theVerticalResolution;} ossim_float64 getHorizontalResolution()const{return theHorizontalResolution;} /*! * This indicates the lat increment per pixel in degrees. */ ossim_float64 getVerticalInterval()const{return theVerticalInterval;} /*! * This indicates the lon increment per pixel in degrees. */ ossim_float64 getHorizontalInterval()const{return theHorizontalInterval;} /** @brief Sets theUpperLeftLat to value. */ void setUlLat(ossim_float64 value); /** @brief Sets theUpperLeftLon to value. */ void setUlLon(ossim_float64 value); /** @brief Sets theLowerLeftLat to value. */ void setLlLat(ossim_float64 value); /** @brief Sets theLowerLeftLon to value. */ void setLlLon(ossim_float64 value); /** @brief Sets theLowerRightLat to value. */ void setLrLat(ossim_float64 value); /** @brief Sets theLowerRightLon to value. */ void setLrLon(ossim_float64 value); /** @brief Sets theUpperRightLat to value. */ void setUrLat(ossim_float64 value); /** @brief Sets theUpperRightLon to value. */ void setUrLon(ossim_float64 value); /** @brief Sets theVerticalResolution to value. */ void setVerticalResolution(ossim_float64 value); /** @brief Sets theHorizontalResolution to value. */ void setHorizontalResolution(ossim_float64 value); /** @brief Sets theVerticalInterval to value. */ void setVerticalInterval(ossim_float64 value); /** @brief Sets theHorizontalInterval to value. */ void setHorizontalInterval(ossim_float64 value); private: /*! * 8 byte ossim_float64 and is the upper left lat or * North West portion of the image. */ ossim_float64 theUpperLeftLat; /*! * 8 byte ossim_float64 and is the upper left lon * (North west) */ ossim_float64 theUpperLeftLon; ossim_float64 theLowerLeftLat; ossim_float64 theLowerLeftLon; ossim_float64 theUpperRightLat; ossim_float64 theUpperRightLon; ossim_float64 theLowerRightLat; ossim_float64 theLowerRightLon; ossim_float64 theVerticalResolution; ossim_float64 theHorizontalResolution; ossim_float64 theVerticalInterval; ossim_float64 theHorizontalInterval; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfFrame.h000066400000000000000000000142771352751253100241360ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This class give the capability to access tiles from an // rpf file. // //******************************************************************** // $Id: ossimRpfFrame.h 20324 2011-12-06 22:25:23Z dburken $ #ifndef ossimRpfFrame_HEADER #define ossimRpfFrame_HEADER 1 #include #include #include #include #include #include #include #include #include class ossimRpfHeader; class ossimRpfAttributes; class ossimRpfCoverageSection; class ossimRpfImageDescriptionSubheader; class ossimRpfImageDisplayParameterSubheader; class ossimRpfMaskSubheader; class ossimRpfCompressionSection; class ossimRpfColorGrayscaleSubheader; class ossimRpfColorConverterSubsection; class OSSIM_DLL ossimRpfFrame : public ossimReferenced { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfFrame& data); ossimRpfFrame(); ~ossimRpfFrame(); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; ossimErrorCode parseFile(const ossimFilename& filename, bool minimalParse = false); const ossimRpfHeader* getRpfHeader()const{return theHeader;} bool hasSubframeMaskTable()const; const std::vector< std::vector >& getSubFrameMask( ossim_uint32 spectralGroup) { return theSubframeMaskTable[spectralGroup]; } bool fillSubFrameBuffer(ossim_uint8* buffer, ossim_uint32 spectralGroup, ossim_uint32 row, ossim_uint32 col)const; const ossimRpfCompressionSection* getCompressionSection()const { return theCompressionSection; } const std::vector& getColorGrayscaleTable()const { return theColorGrayscaleTable; } const ossimRpfColorConverterSubsection* getColorConverterSubsection()const { return theColorConverterSubsection; } const ossimRpfAttributes* getAttributes()const { return theAttributes; } const ossimNitfFile* getNitfFile()const { return theNitfFile.get(); } /** * @return The RPF replace / update table. The ossimRefPtr can have a null * internal pointer if record was not found. Callers should check * ossimRefPtr::valid() before using pointer. */ ossimRefPtr getRpfReplaceUpdateTable() const; private: void clearFields(); void deleteAll(); ossimErrorCode populateCoverageSection(std::istream& in); ossimErrorCode populateCompressionSection(std::istream& in); ossimErrorCode populateImageSection(std::istream& in); ossimErrorCode populateAttributeSection(std::istream& in); ossimErrorCode populateColorGrayscaleSection(std::istream& in); ossimErrorCode populateMasks(std::istream& in); ossimErrorCode populateReplaceUpdateTable(std::istream& in); /*! * The header will be instantiated during the opening of the * frame file. */ ossimRpfHeader *theHeader; /*! * The filename is set if its a successful open. */ ossimFilename theFilename; /*! * This will hold the coverage. */ ossimRpfCoverageSection* theCoverage; /*! * This will hold the attributes of this frame. */ ossimRpfAttributes *theAttributes; /*! * This is the subheader for the image. It will have * some general information about the image. */ ossimRpfImageDescriptionSubheader* theImageDescriptionSubheader; /*! * This is the mask subheader. */ ossimRpfMaskSubheader* theMaskSubheader; /*! * This is the subheader for the display parameters * for this frame. */ ossimRpfImageDisplayParameterSubheader* theImageDisplayParameterSubheader; /*! * Will hold a pointer to the compression information section. */ ossimRpfCompressionSection* theCompressionSection; /*! * If present, it will hold the color grayscale subheader. */ ossimRpfColorGrayscaleSubheader* theColorGrayscaleSubheader; /*! * */ ossimRpfColorConverterSubsection* theColorConverterSubsection; /*! * */ std::vector theColorGrayscaleTable; /*! * */ ossimRefPtr theNitfFile; /*! * We have a 3-D array. For the most part the numberof spectral groups * should be one. The indexes are as follows: * * theSubframeMasKTable[spectralGroup][row][col] * * It will hold RPF_NULL(0xffffffff) if the subframe does not exist * and it will hold an offset value from the start of the * [spatial data section] to the first byte of the subframe table. */ std::vector< std::vector< std::vector< ossim_uint32> > > theSubframeMaskTable; /*! * We have a 3-D array. For the most part the numberof spectral groups * should be one. The indexes are as follows: * * theSubframeTransparencyMaskTable[spectralGroup][row][col] * * It will hold RPF_NULL(0xffffffff) if the subframe does not exist * and it will hold an offset value from the start of the * [spatial data section] to the first byte of the subframe table. */ std::vector< std::vector< std::vector< ossim_uint32> > > theSubframeTransparencyMaskTable; /** Holds table of "replace / update" records if present. */ ossimRefPtr theReplaceUpdateTable; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfFrameEntry.h000066400000000000000000000035761352751253100251600ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfFrameEntry.h 23172 2015-03-02 13:44:54Z dburken $ #ifndef ossimRpfFrameEntry_HEADER #define ossimRpfFrameEntry_HEADER #include #include class OSSIM_DLL ossimRpfFrameEntry { public: friend std::ostream& operator<<(std::ostream& out, const ossimRpfFrameEntry& data); ossimRpfFrameEntry(const ossimFilename& rootDirectory=ossimFilename(""), const ossimFilename& pathToFrameFileFromRoot=ossimFilename("")); /** @brief copy constructor */ ossimRpfFrameEntry(const ossimRpfFrameEntry& obj); /** @brief operator= */ const ossimRpfFrameEntry& operator=(const ossimRpfFrameEntry& rhs); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; bool exists() const; void setEntry(const ossimFilename& rootDirectory, const ossimFilename& pathToFrameFileFromRoot); const ossimFilename& getFullPath() const; const ossimString& getRootDirectory() const; const ossimString getPathToFrameFileFromRoot() const; private: bool m_exists; ossimFilename m_rootDirectory; ossimFilename m_pathToFrameFileFromRoot; ossimFilename m_fullValidPath; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfFrameFileIndexRecord.h000066400000000000000000000043651352751253100270620ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfFrameFileIndexRecord.h 16997 2010-04-12 18:53:48Z dburken $ #ifndef ossimRpfFrameFileIndexRecord_HEADER #define ossimRpfFrameFileIndexRecord_HEADER #include #include #include #include class ossimRpfFrameFileIndexRecord { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfFrameFileIndexRecord& data); /** default constructor */ ossimRpfFrameFileIndexRecord(); /** copy constructor */ ossimRpfFrameFileIndexRecord(const ossimRpfFrameFileIndexRecord& obj); /** assignment operator */ const ossimRpfFrameFileIndexRecord& operator=(const ossimRpfFrameFileIndexRecord& rhs); ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); /** * @brief Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); void clearFields(); std::ostream& print(std::ostream& out)const; ossim_uint16 getBoundaryRecNumber()const; ossim_uint16 getLocationRowNumber()const; ossim_uint16 getLocationColNumber()const; ossim_uint32 getPathnameRecordOffset()const; ossimFilename getFilename()const; /** @brief Sets the zero based entry number. */ void setBoundaryRecNumber(ossim_uint16 entry); void setPathnameRecordOffset(ossim_uint32 offset); private: ossim_uint16 m_boundaryRectRecordNumber; ossim_uint16 m_locationRowNumber; ossim_uint16 m_locationColumnNumber; ossim_uint32 m_pathnameRecordOffset; /*! * This is a 12 byte asci field. */ char m_filename[13]; /*! * this is a 6 byte asci field. */ char m_geographicLocation[7]; char m_securityClassification; /*! * is a 2 byte field. */ char m_fileSecurityCountryCode[3]; /*! * This is a 2 byte field. */ char m_fileSecurityReleaseMarking[3]; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfFrameFileIndexSectionSubheader.h000066400000000000000000000046451352751253100310740ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfFrameFileIndexSectionSubheader.h 16997 2010-04-12 18:53:48Z dburken $ #ifndef ossimRpfFrameFileIndexSectionSubheader_HEADER #define ossimRpfFrameFileIndexSectionSubheader_HEADER #include #include #include #include class ossimRpfFrameFileIndexSectionSubheader : public ossimReferenced { public: friend std::ostream& operator<<(std::ostream& out, const ossimRpfFrameFileIndexSectionSubheader& data); /** default constructor */ ossimRpfFrameFileIndexSectionSubheader(); /** copy constructor */ ossimRpfFrameFileIndexSectionSubheader(const ossimRpfFrameFileIndexSectionSubheader& obj); /** assignment operator */ const ossimRpfFrameFileIndexSectionSubheader& operator=( const ossimRpfFrameFileIndexSectionSubheader& rhs); virtual ~ossimRpfFrameFileIndexSectionSubheader(); ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); /** * @brief Write method. * * Note always writes out in big endian at this point. * * @param out Stream to write to. */ void writeStream(std::ostream& out); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out) const; ossim_uint32 getOffset() const; ossim_uint32 getNumberOfIndexRecords() const; ossim_uint16 getNumberOfPathnameRecords() const; ossim_uint16 getIndexRecordLength() const; void setNumberOfIndexRecords(ossim_uint32 count); void setNumberOfPathnameRecords(ossim_uint16 count); void setIndexRecordLength(ossim_uint16 length); void clearFields(); private: char m_highestSecurityClassification; ossim_uint32 m_indexTableOffset; ossim_uint32 m_numberOfIndexRecords; ossim_uint16 m_numberOfPathnameRecords; ossim_uint16 m_indexRecordLength; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfFrameFileIndexSubsection.h000066400000000000000000000044601352751253100277560ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class. // //******************************************************************** // $Id: ossimRpfFrameFileIndexSubsection.h 16997 2010-04-12 18:53:48Z dburken $ #ifndef ossimRpfFrameFileIndexSubsection_HEADER #define ossimRpfFrameFileIndexSubsection_HEADER #include #include #include #include #include #include class ossimFilename; class ossimRpfFrameFileIndexSubsection : public ossimReferenced { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfFrameFileIndexSubsection& data); /** default constructor */ ossimRpfFrameFileIndexSubsection(); /** copy constructor */ ossimRpfFrameFileIndexSubsection(const ossimRpfFrameFileIndexSubsection& obj); /** assignment operator */ const ossimRpfFrameFileIndexSubsection& operator=(const ossimRpfFrameFileIndexSubsection& rhs); virtual ~ossimRpfFrameFileIndexSubsection(); ossimErrorCode parseStream(std::istream &in, ossimByteOrder byteOrder); /** * @brief Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); void clearFields(); std::ostream& print(std::ostream& out) const; void setNumberOfFileIndexRecords(ossim_uint32 numberOfIndexRecords); void setNumberOfPathnames(ossim_uint32 numberOfPathnames); const std::vector& getIndexTable() const; const std::vector& getPathnameTable() const; /** * @brief Gets the record matching file. * * @param file In the form of: 003H1U1B.I21 * * @param record The record to initialize. * * @return true if matching record found, false if not. */ bool getFrameFileIndexRecordFromFile(const ossimFilename& file, ossimRpfFrameFileIndexRecord& record) const; private: std::vector m_indexTable; std::vector m_pathnameTable; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfFrameFileReader.h000066400000000000000000000013611352751253100260470ustar00rootroot00000000000000#ifndef ossimRpfFrameFileReader_HEADER #define ossimRpfFrameFileReader_HEADER #include #include #include #include #include class ossimRpfFrameFileReader { public: friend std::ostream& operator<<(std::ostream& out, const ossimRpfFrameFileReader& data); ossimRpfFrameFileReader(); ~ossimRpfFrameFileReader(); ossimErrorCode parseFile(const ossimFilename& fileName); std::ostream& print(std::ostream& out) const; const ossimRpfHeader* getRpfHeader()const; private: void clearAll(); ossimRefPtr theRpfHeader; ossimFilename theFilename; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfHeader.h000066400000000000000000000141431352751253100242640ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfHeader.h 22013 2012-12-19 17:37:20Z dburken $ #ifndef ossimRpfHeader_HEADER #define ossimRpfHeader_HEADER 1 #include #include #include #include #include class ossimRpfLocationSection; class ossimRpfCoverageSection; class ossimRpfBoundaryRectTable; class ossimRpfBoundaryRectSectionSubheader; class ossimRpfFrameFileIndexSectionSubheader; class ossimRpfFrameFileIndexSubsection; class ossimRpfColorTableIndexSectionSubheader; class ossimRpfImageDescriptionSubheader; class ossimRpfMaskSubsection; class ossimRpfAttributeSectionSubheader; class ossimRpfImageDisplayParameterSubheader; class ossimRpfCompressionSection; class ossimRpfCompressionSectionSubheader; class ossimRpfColorGrayscaleSubheader; class ossimRpfHeader : public ossimNitfRegisteredTag { public: /** default constructor */ ossimRpfHeader(); /** copy constructor */ ossimRpfHeader(const ossimRpfHeader& obj); /** assignment operator */ const ossimRpfHeader& operator=(const ossimRpfHeader& rhs); virtual ~ossimRpfHeader(); /** * @brief Parse method. * * @param in Stream to parse. */ virtual void parseStream(std::istream& in); /** * @brief Write method. * * @param out Stream to write to. */ virtual void writeStream(std::ostream& out); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; virtual ossimByteOrder getByteOrder()const; const ossimRpfLocationSection* getLocationSection() const; ossimRpfLocationSection* getLocationSection(); bool hasComponent(ossimRpfComponentId componentId)const; ossimString getSecurityClassification()const; /*! * This will return a new coverage section. It will return NULL if * one does not exist. */ ossimRpfCoverageSection* getNewCoverageSection(const ossimFilename& file)const; ossimRpfCoverageSection* getNewCoverageSection(std::istream& in)const; ossimRpfColorGrayscaleSubheader* getNewColorGrayscaleSubheader(std::istream& in)const; ossimRpfCompressionSection* getNewCompressionSection(std::istream& in)const; ossimRpfCompressionSectionSubheader* getNewCompressionSectionSubheader(std::istream& in)const; ossimRpfImageDisplayParameterSubheader* getNewImageDisplayParameterSubheader(std::istream& in)const; ossimRpfAttributeSectionSubheader* getNewAttributeSectionSubheader(std::istream& in)const; ossimRpfImageDescriptionSubheader* getNewImageDescriptionSubheader(std::istream& in)const; ossimRpfMaskSubsection* getNewMaskSubsection(std::istream& in)const; ossimRpfBoundaryRectSectionSubheader* getNewBoundaryRectSectSubheader(std::istream& in)const; ossimRpfBoundaryRectTable* getNewBoundaryRectTable(std::istream& in)const; ossimRpfFrameFileIndexSectionSubheader* getNewFrameFileIndexSectionSubheader(std::istream& in)const; ossimRpfFrameFileIndexSubsection* getNewFileIndexSubsection(std::istream& in)const; ossimRpfColorTableIndexSectionSubheader* getNewColorTableIndexSectionSubheader(std::istream& in)const; ossimRpfCompressionSection* getNewCompressionSection(const ossimFilename& file)const; ossimRpfBoundaryRectSectionSubheader* getNewBoundaryRectSectSubheader(const ossimFilename& file)const; ossimRpfBoundaryRectTable* getNewBoundaryRectTable(const ossimFilename& file)const; ossimRpfFrameFileIndexSectionSubheader* getNewFrameFileIndexSectionSubheader(const ossimFilename& file)const; ossimRpfFrameFileIndexSubsection* getNewFileIndexSubsection(const ossimFilename& file)const; ossimRpfColorTableIndexSectionSubheader* getNewColorTableIndexSectionSubheader(const ossimFilename& file)const; ossimString getDate()const; /** @brief returns the byte position of the location section. */ ossim_uint32 getLocationSectionLocation() const; void setFilename(const ossimString& file); void setNewRepUpIndicator(const ossimString& s); void setGovSpecNumber(const ossimString& s); void setGovSpecDate(const ossimString& s); void setSecurityClassification(const ossimString& s); void setCountryCode(const ossimString& s); void setSecurityReleaseMarking(const ossimString& s); void setLocationSectionPos(std::streamoff off); /*! * Method to the load (recreate) the state of the object from a keyword * list. Return true if ok or false on error. */ virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); private: /** 0x00 = big, 0xff = little */ ossim_uint8 m_littleBigEndianIndicator; // 1 byte bool ossim_uint16 m_headerSectionLength; // 2 bytes uint char m_fileName[13]; // 12 byte ascii ossim_uint8 m_newRepUpIndicator; // 1 byte unsigned int char m_govSpecNumber[16]; // 15 byte ascii char m_govSpecDate[9]; // 8 byte ascii /** * 1 byte field that can have the values * * U Unclassified * R Restricted * C Confidential * S Secret * T Top Secret */ char m_securityClassification[2]; // 1 byte ascii char m_countryCode[3]; // 2 byte ascii char m_securityReleaseMarking[3]; // 2 byte ascii ossim_uint32 m_locSectionLoc; // 4 byte unsigned int ossimRpfLocationSection* m_locationSection; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfImageDescriptionSubheader.h000066400000000000000000000073241352751253100301500ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfImageDescriptionSubheader.h 14241 2009-04-07 19:59:23Z dburken $ #ifndef ossimRpfImageDescriptionSubheader_HEADER #define ossimRpfImageDescriptionSubheader_HEADER #include #include #include #include class ossimRpfImageDescriptionSubheader { public: friend std::ostream& operator <<( std::ostream& out, const ossimRpfImageDescriptionSubheader& data); ossimRpfImageDescriptionSubheader(); ~ossimRpfImageDescriptionSubheader(){} ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); ossim_uint32 getStartOffset()const{return theStartOffset;} ossim_uint32 getEndOffset()const{return theEndOffset;} bool isSubframeMaskTableOffsetNull()const { return (theSubframeMaskTableOffset == OSSIM_RPF_ULONG_NULL); } bool isTransparencyMaskTableOffsetNull()const { return (theTransparencyMaskTableOffset == OSSIM_RPF_ULONG_NULL); } ossim_uint16 getNumberOfSpectralGroups()const { return theNumberOfSpectralGroups; } ossim_uint16 getNumberOfSubframeTables()const { return theNumberOfSubframeTables; } ossim_uint16 getNumberOfSpectralBandTables()const { return theNumberOfSpectralBandTables; } ossim_uint16 getNumberOfSpectralBandLinesPerImageRow()const { return theNumberOfSpectralBandLinesPerImageRow; } ossim_uint16 getNumberOfSubframesHorizontal()const { return theNumberOfSubframesHorizontal; } ossim_uint16 getNumberOfSubframesVertical()const { return theNumberOfSubframesVertical; } ossim_uint32 getNumberOfOutputColumnsPerSubframe()const { return theNumberOfOutputColumnsPerSubframe; } ossim_uint32 getNumberOfOutputRowsPerSubframe()const { return theNumberOfOutputRowsPerSubframe; } ossim_uint32 getSubframeMaskTableOffset()const { return theSubframeMaskTableOffset; } ossim_uint32 getTransparencyMaskTableOffset()const { return theTransparencyMaskTableOffset; } /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; private: void clearFields(); // work variables to store useful information. ossim_uint32 theStartOffset; ossim_uint32 theEndOffset; ossim_uint16 theNumberOfSpectralGroups; ossim_uint16 theNumberOfSubframeTables; ossim_uint16 theNumberOfSpectralBandTables; ossim_uint16 theNumberOfSpectralBandLinesPerImageRow; /*! * Each frame file could be divided into sub frames. * This identifies the number of subframes in the * horizontal direction. */ ossim_uint16 theNumberOfSubframesHorizontal; /*! * Each frame file could be divided into sub frames. * This identifies the number of subframes in the * vertical direction. */ ossim_uint16 theNumberOfSubframesVertical; ossim_uint32 theNumberOfOutputColumnsPerSubframe; ossim_uint32 theNumberOfOutputRowsPerSubframe; ossim_uint32 theSubframeMaskTableOffset; ossim_uint32 theTransparencyMaskTableOffset; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfImageDisplayParameterSubheader.h000066400000000000000000000027771352751253100311420ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: Rpf support class // //******************************************************************** // $Id$ #ifndef ossimRpfImageDisplayParameterSubheader_HEADER #define ossimRpfImageDisplayParameterSubheader_HEADER 1 #include #include #include class ossimRpfImageDisplayParameterSubheader { public: friend std::ostream& operator<<( std::ostream& out, const ossimRpfImageDisplayParameterSubheader& data); ossimRpfImageDisplayParameterSubheader(); ossimErrorCode parseStream(ossim::istream& in, ossimByteOrder byteOrder); void print(std::ostream& out)const; ossim_uint32 getStartOffset()const { return theStartOffset; } ossim_uint32 getEndOffset()const { return theEndOffset; } ossim_uint32 getNumberOfImageRows()const { return theNumberOfImageRows; } ossim_uint32 getNumberOfImageCodesPerRow()const { return theNumberOfImageCodesPerRow; } ossim_uint32 getImageCodeLength()const { return theImageCodeBitLength; } private: void clearFields(); ossim_uint32 theStartOffset; ossim_uint32 theEndOffset; ossim_uint32 theNumberOfImageRows; ossim_uint32 theNumberOfImageCodesPerRow; ossim_uint8 theImageCodeBitLength; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfInfo.h000066400000000000000000000025641352751253100237730ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // // Description: Rpf Info object. // //---------------------------------------------------------------------------- // $Id: ossimRpfInfo.h 1236 2010-08-05 19:45:44Z ming.su $ #ifndef ossimRpfInfo_HEADER #define ossimRpfInfo_HEADER #include #include #include #include class ossimKeywordlist; /** * @brief HDF info class. * * Encapsulates the HDF functionality. */ class ossimRpfInfo : public ossimInfoBase { public: /** default constructor */ ossimRpfInfo(); /** virtual destructor */ virtual ~ossimRpfInfo(); /** * @brief open method. * * @param file File name to open. * @return true on success false on error. */ virtual bool open(const ossimFilename& file); /** * Print method. * * @param out Stream to print to. * * @return std::ostream& */ virtual std::ostream& print(std::ostream& out) const; bool isOpen(); private: ossimFilename theFile; ossimFilename m_infoFile; }; #endif /* End of "#ifndef ossimRpfInfo_HEADER" */ ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfLocationSection.h000066400000000000000000000120511352751253100261650ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfLocationSection.h 16997 2010-04-12 18:53:48Z dburken $ #ifndef ossimRpfLocationSection_HEADER #define ossimRpfLocationSection_HEADER #include #include #include #include #include // 10 byte record class ossimRpfComponentLocationRecord { public: friend std::ostream& operator<<( std::ostream& out, const ossimRpfComponentLocationRecord& data); /** default constructor */ ossimRpfComponentLocationRecord(); /** copy constructor */ ossimRpfComponentLocationRecord(const ossimRpfComponentLocationRecord& record); /** assignment operator */ const ossimRpfComponentLocationRecord& operator=(const ossimRpfComponentLocationRecord& rhs); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; ossimErrorCode parseStream(std::istream& in, ossimByteOrder endianOrder); /** * @brief Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); /*! * The component is a 2-Byte unsigned value which * identitfies a level-2 component. The table can be * found in MIL-STD-2411-1 in section 5.1.1 and in ossimRpfConstants.h. */ ossim_uint16 m_componentId; /*! * Is a 4 byte unsigned integer indicating the length in * bytes of the component. */ ossim_uint32 m_componentLength; /*! * Is a 4 byte value defining the absolute address (byte number) * of the first byte of the component measured * from the beginning of the RPF Frame file. */ ossim_uint32 m_componentLocation; }; class ossimRpfLocationSection { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfLocationSection &data); ossimRpfLocationSection(); virtual ~ossimRpfLocationSection(){} virtual ossimErrorCode parseStream(std::istream& in, ossimByteOrder endianOrder); /** * @brief Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; /*! * Will let you know if a component exists within the location section. * these component Ids' are defined in the MIL-STD-2411-1 standards doc. * the ossimRpfComponentId is in ossimRpfConstants.h */ bool hasComponent(ossimRpfComponentId componentId)const; bool getComponent(ossimRpfComponentId componentId, ossimRpfComponentLocationRecord& result)const; /** * @brief Method to add a component location record. * * This will push the record onto the back of theComponentLocationList array. * * @param record Record to add to array. */ void addComponentRecord(const ossimRpfComponentLocationRecord& record); void setLocationSectionLength(ossim_uint16 length); void setLocationTableOffset(ossim_uint32 offset); void setNumberOfComponentLocationRecords(ossim_uint16 count); void setLocationRecordLength(ossim_uint16 length); void setComponentAggregateLength(ossim_uint32 length); /** @brief Clears records and fields. Public interface to clearFields. */ void clearFields(); /** Brief Direct access to the list of records. */ std::vector& getLocationRecordList(); private: /*! * This is a 2 byte unsigned short >= 34 indicatin * the length in bytes of the entire location section */ ossim_uint16 m_locationSectionLength; ossim_uint32 m_locationTableOffset; ossim_uint16 m_numberOfComponentLocationRecords; ossim_uint16 m_locationRecordLength; ossim_uint32 m_componentAggregateLength; /*! * Since there are not very many components within an Rpf file * it would be overkill to sort these components into an stl * map. We will just use an array (stl vector) and do linear searches * for components when we need to. */ std::vector m_componentLocationList; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfMaskSubheader.h000066400000000000000000000021521352751253100256070ustar00rootroot00000000000000#ifndef ossimRpfMaskSubheader_HEADER #define ossimRpfMaskSubheader_HEADER #include #include #include #include class ossimRpfMaskSubheader { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfMaskSubheader& data); ossimRpfMaskSubheader(); virtual ~ossimRpfMaskSubheader(); ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); void print(std::ostream& out)const; private: void clearFields(); unsigned short theSubframeSequenceRecordLength; unsigned short theTransparencySequenceRecordLength; unsigned short theTransparentOutputPixelCodeLength; unsigned char* theOutputPixelCodeBitString; /*! * This is just a working variable and is not * part of the Rpf fields. this is the number of bytes * of the output pixel code length. It divides by * 8 and then does the ceiling of the * theTransparentOutputPixelCodeLength. */ long theNumberOfBytes; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfMaskSubsection.h000066400000000000000000000020161352751253100260220ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfMaskSubsection.h 11691 2007-09-09 20:02:30Z dburken $ #ifndef ossimRpfMaskSubsection_HEADER #define ossimRpfMaskSubsection_HEADER #include #include #include class ossimRpfMaskSubheader; class ossimRpfImageDescriptionSubheader; class OSSIM_DLL ossimRpfMaskSubsection { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfMaskSubsection& data); ossimRpfMaskSubsection(); virtual ~ossimRpfMaskSubsection(); ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); virtual void print(std::ostream& out)const; private: ossimRpfMaskSubheader *theMaskSubheader; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfPathnameRecord.h000066400000000000000000000027601352751253100257720ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class. // //******************************************************************** // $Id: ossimRpfPathnameRecord.h 16997 2010-04-12 18:53:48Z dburken $ #ifndef ossimRpfPathnameRecord_HEADER #define ossimRpfPathnameRecord_HEADER #include #include #include #include class ossimRpfPathnameRecord { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfPathnameRecord& data); /** default constructor */ ossimRpfPathnameRecord(); /** copy constructor */ ossimRpfPathnameRecord(const ossimRpfPathnameRecord& obj); /** assignment operator */ const ossimRpfPathnameRecord& operator=(const ossimRpfPathnameRecord& rhs); void clearFields(); ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); /** * @brief Write method. * * @param out Stream to write to. */ void writeStream(std::ostream& out); std::ostream& print(std::ostream& out) const; ossimString getPathname()const; /** * @brief Set the pathname and length from string size. * @param path Path like: ./N03E030 */ void setPathName(const ossimString& path); private: ossim_uint16 m_length; ossimString m_pathname; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfReplaceUpdateRecord.h000066400000000000000000000063061352751253100267530ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimRpfReplaceUpdateRecord.h // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: See class description. // //---------------------------------------------------------------------------- // $Id: ossimRpfReplaceUpdateRecord.h 20324 2011-12-06 22:25:23Z dburken $ #ifndef ossimRpfReplaceUpdateRecord_HEADER #define ossimRpfReplaceUpdateRecord_HEADER 1 #include #include #include /** * @class ossimRpfReplaceUpdateRecord * @brief RPF replace/update section subheader record. * See MIL-STD-2411 for detailed information. */ class ossimRpfReplaceUpdateRecord { public: /** @brief Convenience output operator. */ friend std::ostream& operator <<(std::ostream& out, const ossimRpfReplaceUpdateRecord& data); /** @brief default constructor */ ossimRpfReplaceUpdateRecord(); /** @brief copy constructor */ ossimRpfReplaceUpdateRecord(const ossimRpfReplaceUpdateRecord& obj); /** @brief assignment operator */ const ossimRpfReplaceUpdateRecord& operator=(const ossimRpfReplaceUpdateRecord& rhs); /** * @brief Method to parse the record. * Note no byte swapping required for this record. * @param in Stream sitting at record. */ ossimErrorCode parseStream(std::istream& in); /** * @brief Write method. * Note no byte swapping required for this record. * @param out Stream to write to. */ void writeStream(std::ostream& out); /** @brief Clears fields. */ void clearFields(); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out Stream to output to. * @param prefix This will be prepended to key. * @param recordNumber This is added to key. See below. * e.g. Where prefix = "nitf.rpf.", recordNumber = 0 and key is "new_file" * key becomes: "nitf.rpf.replace_update_record0.new_file:" * @return output stream. */ std::ostream& print( std::ostream& out, const std::string& prefix=std::string(), ossim_uint32 recordNumber=0) const; /** * @brief Gets new file field. * @param file Set by this. */ void getNewFilename(std::string& file) const; /** * @brief Gets old file field. * @param file Set by this. */ void getOldFilename(std::string& file) const; /** @return The update status field. */ ossim_uint8 getUpdateStatus() const; /** * @brief Sets old file name 12 byte field. * @param file */ void setNewFilename(const std::string& file); /** * @brief Sets new file name 12 byte field. * @param file */ void setOldFilename(const std::string& file); /** @return Sets the update status field. */ void setUpdateStatus(ossim_uint8 status); private: /** This is a 12 byte asci field. */ char m_newFile[13]; /** This is a 12 byte asci field. */ char m_oldFile[13]; /** This is a 1 byte unsigned integer. */ ossim_uint8 m_updateStatus; }; #endif /* #ifndef ossimRpfReplaceUpdateRecord_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfReplaceUpdateSectionSubheader.h000066400000000000000000000055531352751253100307670ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimRpfReplaceUpdateSectionSubheader.h // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: See class description. // //---------------------------------------------------------------------------- // $Id: ossimRpfReplaceUpdateSectionSubheader.h 20324 2011-12-06 22:25:23Z dburken $ #ifndef ossimRpfReplaceUpdateSubheader_Header #define ossimRpfReplaceUpdateSubheader_Header 1 #include #include #include #include /** * @class ossimRpfReplaceUpdateSectionSubheader * @brief RPF replace/update section subheader record. * See MIL-STD-2411 for detailed information. */ class ossimRpfReplaceUpdateSectionSubheader : public ossimReferenced { public: /** @brief Convenience output operator. */ friend std::ostream& operator<<(std::ostream& out, const ossimRpfReplaceUpdateSectionSubheader& data); /** @brief default constructor */ ossimRpfReplaceUpdateSectionSubheader(); /** @brief copy constructor */ ossimRpfReplaceUpdateSectionSubheader(const ossimRpfReplaceUpdateSectionSubheader& obj); /** @brief assignment operator */ const ossimRpfReplaceUpdateSectionSubheader& operator=( const ossimRpfReplaceUpdateSectionSubheader& rhs); /** @brief virtual destructor */ virtual ~ossimRpfReplaceUpdateSectionSubheader(); /** * @brief Method to parse the record. * @param in Stream sitting at record. * @param byteOrder Byte order of system. */ ossimErrorCode parseStream(std::istream& in, ossimByteOrder byteOrder); /** * @brief Write method. * * Note always writes out in big endian at this point. * * @param out Stream to write to. */ void writeStream(std::ostream& out); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out) const; /** @return Offset to first record. */ ossim_uint32 getOffset() const; /** @return Number of records. */ ossim_uint16 getNumberOfRecords() const; /** @return Length of one record. */ ossim_uint16 getRecordLength() const; /** * @brief Sets number of records. * @param count */ void setNumberOfRecords(ossim_uint16 count); void setRecordLength(ossim_uint16 length); void clearFields(); private: ossim_uint32 m_tableOffset; ossim_uint16 m_numberOfRecords; ossim_uint16 m_recordLength; }; #endif /* #ifndef ossimRpfReplaceUpdateSubheader_Header */ ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfReplaceUpdateTable.h000066400000000000000000000037331352751253100265650ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimRpfReplaceUpdateTable.h // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: See class description. // //---------------------------------------------------------------------------- // $Id: ossimRpfReplaceUpdateTable.h 20328 2011-12-07 17:43:24Z dburken $ #ifndef ossimRpfReplaceUpdateTable_HEADER #define ossimRpfReplaceUpdateTable_HEADER 1 #include #include #include #include #include #include /** * @class ossimRpfReplaceUpdateTable * @brief Holds a table of RPF replace/update section subheader records. * See MIL-STD-2411 for detailed information. */ class OSSIM_DLL ossimRpfReplaceUpdateTable : public ossimReferenced { public: /** @brief default constructor */ ossimRpfReplaceUpdateTable(); /** @brief copy constructor */ ossimRpfReplaceUpdateTable(const ossimRpfReplaceUpdateTable& obj); /** @brief assignment operator */ const ossimRpfReplaceUpdateTable& operator=(const ossimRpfReplaceUpdateTable& rhs); /** * @brief Method to add a record. * @param record to add. */ void addRecord(const ossimRpfReplaceUpdateRecord& record); /** @brief Clears the table. */ void clear(); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out Stream to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf.rpf." and key is "new_file" key becomes: * "nitf.rpf.replace_update_record0.new_file: * @return output stream. */ std::ostream& print( std::ostream& out, const std::string& prefix=std::string() ) const; private: std::vector m_table; }; #endif /* #ifndef ossimRpfReplaceUpdateTable_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfToc.h000066400000000000000000000210471352751253100236220ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRpfToc.h 18044 2010-09-06 14:20:52Z dburken $ #ifndef osimRpfToc_HEADER #define osimRpfToc_HEADER 1 #include #include #include #include #include #include #include #include #include #include class ossimRpfFrameFileIndexSubsection; class ossimRpfTocEntry; class ossimRpfFrameEntry; class OSSIM_DLL ossimRpfToc : public ossimReferenced { public: friend OSSIM_DLL std::ostream& operator <<(std::ostream& out, const ossimRpfToc& data); ossimRpfToc(); virtual ~ossimRpfToc(); /** * @brief Parses a.toc file. * @param fileName File to parse. * @param keepFileHeader If true the ossimNitfFileHeader will be kept. * @return ossimErrorCodes::OSSIM_OK on success, ossimErrorCodes::OSSIM_ERROR on error. */ ossimErrorCode parseFile(const ossimFilename &fileName, bool keepFileHeader = false); /** * @brief Creates a new a.toc file from list of rpf frames in output directory. * * @param dotRpfFile File containing list of rpf frames wanted. * * @param outputDir Directory to write a.toc file and rpf frames to. * * @see ossim-rpf application usage for dotRpfFile format. * * @note Throws ossimException on error. */ void createTocAndCopyFrames( const ossimFilename& dotRpfFile, const ossimFilename& outputDir); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf.rpf." and key is "file_name" key becomes: * "nitf.rpm.file_name:" * @return output stream. */ std::ostream& print( std::ostream& out, const std::string& prefix=std::string(), bool printOverviews=false ) const; /** * @brief print method that outputs a key/value type format adding prefix * to keys. * * This prints the rpf header part only. * * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf.rpf." and key is "file_name" key becomes: * "nitf.rpf.file_name:" * @return output stream. */ std::ostream& printHeader( std::ostream& out, const std::string& prefix=std::string() ) const; /** * @brief print method that outputs a key/value type format adding prefix * to keys. * * This prints the specific rpf toc entry. * * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf.rpf." and key is "file_name" key becomes: * "nitf.rpf.file_name:" * @return output stream. */ std::ostream& printTocEntry( std::ostream& out, ossim_uint32 entryIndex, const std::string& prefix=std::string(), bool printOverviews=false ) const; ossim_uint32 getNumberOfEntries()const; const ossimRpfTocEntry* getTocEntry(ossim_uint32 index)const; /** * Returns -1 if not found. */ ossim_int32 getTocEntryIndex(const ossimRpfTocEntry* entry); /** * @brief Get the nitf file header. * * @return The nitf file header or 0 if not set. */ const ossimNitfFileHeader* getNitfFileHeader()const; const ossimRpfHeader* getRpfHeader() const; /** * For the given entry index, this routine returns the number of * frames that exist in the horizontal direction. If the entry index * is invalid, 0 frames are returned. * * @param idx the entry index. * @return number of frames in the horizontal direction */ ossim_uint32 getNumberOfFramesHorizontal(ossim_uint32 idx)const; /** * For the given entry index, this routine returns the number of * frames that exist in the vertical direction. If the entry index * is invalid, 0 frames are returned. * * @param idx the entry index. * @return number of frames in the vertical direction */ ossim_uint32 getNumberOfFramesVertical(ossim_uint32 idx)const; /** * For the given entry index, frame row, and frame column, this * routine returns the corresponding ossimRpfFrameEntry instance. * * @param entryIdx the entry index. * @param row the frame row. * @param col the frame col. * @return true if successful */ bool getRpfFrameEntry(ossim_uint32 entryIdx, ossim_uint32 row, ossim_uint32 col, ossimRpfFrameEntry& result)const; /** * For the given entry index, frame row, and frame column, this * routine returns the corresponding name of the frame image * with respect to the location of the toc file. * * @param entryIdx the entry index. * @param row the frame row. * @param col the frame col. * @return the name of the frame image */ const ossimString getRelativeFramePath( ossim_uint32 entryIdx, ossim_uint32 row, ossim_uint32 col)const; /** * @brief Method to get the root directory from the a.toc file name. * @param dir This initializes dir. */ void getRootDirectory(ossimFilename& dir) const; private: void deleteAll(); void clearAll(); void deleteTocEntryList(); void buildTocEntryList(ossimRpfHeader* rpfHeader); void allocateTocEntryList(ossim_uint32 numberOfEntries); /** @brief Walks through frames to find the first entry that exists... */ void getFirstEntry(const ossimRpfTocEntry* rpfTocEntry, ossimRpfFrameEntry& frameEntry) const; /** * @brief Writes the frame file sub section of an a.toc. * * This is a utility method for createTocAndCopyFrames method. */ void writeFrameFileIndexSection(ossimRpfFrameFileIndexSubsection* frameFileSubSection, std::ifstream& dotRpfStr, std::ofstream& dotTocStr); /** * @brief Copies frame to output directory. * * This is a utility method for createTocAndCopyFrames method. */ void copyFrames(std::ifstream& dotRpfStr, const ossimFilename& outputDir); /** * @brief Get the number of frames from the dot rpf file. * This is a utility method for createTocAndCopyFrames method. */ ossim_uint32 getNumberOfFrames(std::ifstream& dotRpfStr) const; /** * @brief Get a.toc file from the dot rpf file. * This is a utility method for createTocAndCopyFrames method. */ ossimFilename getSourceTocFile(std::ifstream& dotRpfStr) const; /** * @brief Gets the zero based entry number for the first file in the dot rpf file. * This is a utility method for createTocAndCopyFrames method. */ bool getCorespondingEntry(ossimRpfFrameFileIndexSubsection* frameFileSubSection, std::ifstream& dotRpfStr, ossim_uint32& entry) const; /** * @brief Gets the filename from line in. * * Line format: * * /data/spadac/rpf-frame-test/t1/N03E030/005FNU1B.I21|30.9141787715578,3.03831480449669|30.9889225265623,3.10741371349693 * * @param line Line to extract filename from. * * @param out Filename to initialize. * * This is a utility method for createTocAndCopyFrames method. */ bool getFile(const std::string& line, ossimFilename& file) const; /*! * This will hold a list of table of content entries. There is one entry * per directory. Each entry will have its geographic coverage. * Each directory is then divided into frames. There could be 30 or * more frame images that make up an entire image. */ std::vector m_tocEntryList; /*! * We will remember the file that we opened */ ossimFilename m_filename; ossimRefPtr m_nitfFileHeader; ossimRefPtr m_rpfHeader; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRpfTocEntry.h000066400000000000000000000065621352751253100246510ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfTocEntry.h 19900 2011-08-04 14:19:57Z dburken $ #ifndef ossimRpfTocEntry_HEADER #define ossimRpfTocEntry_HEADER #include #include #include #include #include #include #include class ossimIrect; class OSSIMDLLEXPORT ossimRpfTocEntry { public: friend std::ostream& operator <<(std::ostream& out, const ossimRpfTocEntry& data); ossimRpfTocEntry(); ossimErrorCode parseStream(std::istream &in, ossimByteOrder byteOrder); /** * @brief print method that outputs a key/value type format adding prefix * to keys. * @param out String to output to. * @param prefix This will be prepended to key. * e.g. Where prefix = "nitf." and key is "file_name" key becomes: * "nitf.file_name:" * @return output stream. */ std::ostream& print(std::ostream& out, const std::string& prefix=std::string()) const; void setEntry(const ossimRpfFrameEntry& entry, long row, long col); bool getEntry(long row, long col, ossimRpfFrameEntry& result)const; ossimString getProductType() const; /*! * returns how many subimges or frames exist in the horizontal * direction. */ ossim_uint32 getNumberOfFramesHorizontal()const; /*! * returns how many subimges or frames exist in the vertical * direction. */ ossim_uint32 getNumberOfFramesVertical()const; /** @return The number of lines (frames vertical * 1536). */ ossim_uint32 getNumberOfLines() const; /** @return The number of samples (frames horizontal * 1536). */ ossim_uint32 getNumberOfSamples() const; /** @return Number of bands. */ ossim_uint32 getNumberOfBands() const; /** * @brief Get the bounding rect of entry. * @param rect Gets initialized with rect. */ void getBoundingRect(ossimIrect& rect) const; const ossimRpfBoundaryRectRecord& getBoundaryInformation()const; /*! * If there is an entry and all the files don't exist we will return * true. */ bool isEmpty()const; /** * Returns the image geometry object associated with this tile source or * NULL if non defined. The geometry contains full-to-local image * transform as well as projection (image-to-world). */ ossimRefPtr getImageGeometry() const; /** @brief Get the scale in decimal degrees per pixel. */ void getDecimalDegreesPerPixel(ossimDpt& scale) const; /** @brief Get the scale in meters per pixel. */ void getMetersPerPixel(ossimDpt& scale) const; private: void allocateFrameEntryArray(); ossimRpfBoundaryRectRecord theBoundaryInformation; ossim_uint32 theNumSamples; //!> May be less than actual image width in case of > 360 deg wrap condition. (OLK 10/10) std::vector< std::vector > theFrameEntryArray; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimRsmida.h000066400000000000000000000066351352751253100236520ustar00rootroot00000000000000//--- // File: ossimRsmida.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. //--- #ifndef ossimRsmida_H #define ossimRsmida_H 1 #include #include class ossimKeywordlist; class ossimNitfRsmidaTag; /** * @class Public container RSM Identification(RSMIDA) TRE. * * Reference: * Replacement Sensor Model Tagged Record Extensions Specification for NITF 2.1 * section 7.0(RSMIDA). */ class ossimRsmida { public: /** @brief default constructor */ ossimRsmida(); /** @brief copy constructor */ ossimRsmida( const ossimRsmida& obj ); /** @brief assignment operator */ const ossimRsmida& operator=( const ossimRsmida& rhs ); /** * @brief saveState Saves state to keyword list. * @param kwl * @param prefix */ void saveState( ossimKeywordlist& kwl, const std::string& prefix ) const; /** * @brief loadState Loads state from keyword list. * @param kwl * @param prefix * @return true on success; false, on error. */ bool loadState( const ossimKeywordlist& kwl, const std::string& prefix ); /** * @brief initialize Initializes from nitf rsmida tag. * @param rsmidaTag * @return true on success; false, on error. */ bool initialize( const ossimNitfRsmidaTag* rsmidaTag ); std::string m_iid; std::string m_edition; std::string m_isid; std::string m_sid; std::string m_stid; ossim_uint32 m_year; ossim_uint32 m_month; ossim_uint32 m_day; ossim_uint32 m_hour; ossim_uint32 m_minute; ossim_float64 m_second; ossim_uint32 m_nrg; ossim_uint32 m_ncg; ossim_float64 m_trg; ossim_float64 m_tcg; char m_grndd; ossim_float64 m_xuor; ossim_float64 m_yuor; ossim_float64 m_zuor; ossim_float64 m_xuxr; ossim_float64 m_xuyr; ossim_float64 m_xuzr; ossim_float64 m_yuxr; ossim_float64 m_yuyr; ossim_float64 m_yuzr; ossim_float64 m_zuxr; ossim_float64 m_zuyr; ossim_float64 m_zuzr; ossim_float64 m_v1x; ossim_float64 m_v1y; ossim_float64 m_v1z; ossim_float64 m_v2x; ossim_float64 m_v2y; ossim_float64 m_v2z; ossim_float64 m_v3x; ossim_float64 m_v3y; ossim_float64 m_v3z; ossim_float64 m_v4x; ossim_float64 m_v4y; ossim_float64 m_v4z; ossim_float64 m_v5x; ossim_float64 m_v5y; ossim_float64 m_v5z; ossim_float64 m_v6x; ossim_float64 m_v6y; ossim_float64 m_v6z; ossim_float64 m_v7x; ossim_float64 m_v7y; ossim_float64 m_v7z; ossim_float64 m_v8x; ossim_float64 m_v8y; ossim_float64 m_v8z; ossim_float64 m_grpx; ossim_float64 m_grpy; ossim_float64 m_grpz; ossim_uint32 m_fullr; ossim_uint32 m_fullc; ossim_uint32 m_minr; ossim_uint32 m_maxr; ossim_uint32 m_minc; ossim_uint32 m_maxc; ossim_float64 m_ie0; ossim_float64 m_ier; ossim_float64 m_iec; ossim_float64 m_ierr; ossim_float64 m_ierc; ossim_float64 m_iecc; ossim_float64 m_ia0; ossim_float64 m_iar; ossim_float64 m_iac; ossim_float64 m_iarr; ossim_float64 m_iarc; ossim_float64 m_iacc; ossim_float64 m_spx; ossim_float64 m_svx; ossim_float64 m_sax; ossim_float64 m_spy; ossim_float64 m_svy; ossim_float64 m_say; ossim_float64 m_spz; ossim_float64 m_svz; ossim_float64 m_saz; }; // End: class ossimRsmida() #endif /* #ifndef ossimRsmida!_H */ ossim-Miami-2.9.1/include/ossim/support_data/ossimRsmpca.h000066400000000000000000000050571352751253100236550ustar00rootroot00000000000000//--- // File: ossimRsmpca.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. //--- #ifndef ossimRsmpca_H #define ossimRsmpca_H 1 #include #include #include class ossimKeywordlist; class ossimNitfRsmpcaTag; /** * @class Public container for RSM Polynomial Coefficients(RSMPCA) TRE. * * Reference: * Replacement Sensor Model Tagged Record Extensions Specification for NITF 2.1 * section 9.0(RSMPCA). * */ class ossimRsmpca { public: /** @brief default constructor */ ossimRsmpca(); /** @brief copy constructor */ ossimRsmpca( const ossimRsmpca& obj ); /** @brief assignment operator */ const ossimRsmpca& operator=( const ossimRsmpca& rhs ); /** * @brief saveState Saves state to keyword list. * @param kwl * @param prefix * @param index */ void saveState( ossimKeywordlist& kwl, const std::string& prefix, ossim_uint32 index ) const; /** * @brief loadState Loads state from keyword list. * @param kwl * @param prefix * @param index * @return true on success; false, on error. */ bool loadState( const ossimKeywordlist& kwl, const std::string& prefix, ossim_uint32 index ); /** * @brief initialize Initializes from nitf rsmpia tag. * @param rsmpiaTag * @return true on success; false, on error. */ bool initialize( const ossimNitfRsmpcaTag* rsmpcaTag ); std::string m_iid; std::string m_edition; ossim_uint32 m_rsn; ossim_uint32 m_csn; ossim_float64 m_rfep; ossim_float64 m_cfep; ossim_float64 m_rnrmo; ossim_float64 m_cnrmo; ossim_float64 m_xnrmo; ossim_float64 m_ynrmo; ossim_float64 m_znrmo; ossim_float64 m_rnrmsf; ossim_float64 m_cnrmsf; ossim_float64 m_xnrmsf; ossim_float64 m_ynrmsf; ossim_float64 m_znrmsf; ossim_uint32 m_rnpwrx; ossim_uint32 m_rnpwry; ossim_uint32 m_rnpwrz; ossim_uint32 m_rntrms; std::vector m_rnpcf; ossim_uint32 m_rdpwrx; ossim_uint32 m_rdpwry; ossim_uint32 m_rdpwrz; ossim_uint32 m_rdtrms; std::vector m_rdpcf; ossim_uint32 m_cnpwrx; ossim_uint32 m_cnpwry; ossim_uint32 m_cnpwrz; ossim_uint32 m_cntrms; std::vector m_cnpcf; ossim_uint32 m_cdpwrx; ossim_uint32 m_cdpwry; ossim_uint32 m_cdpwrz; ossim_uint32 m_cdtrms; std::vector m_cdpcf; }; // End: class ossimRsmpca() #endif /* #ifndef ossimRsmpca_H */ ossim-Miami-2.9.1/include/ossim/support_data/ossimRsmpia.h000066400000000000000000000041221352751253100236530ustar00rootroot00000000000000//--- // File: ossimRsmpia.h // // License: MIT // // See LICENSE.txt file in the top level directory for more details. //--- #ifndef ossimRsmpia_H #define ossimRsmpia_H 1 #include #include class ossimKeywordlist; class ossimNitfRsmpiaTag; /** * @class Public container RSM Polynomial Identification(RSMPIA) TRE. * * Reference: * Replacement Sensor Model Tagged Record Extensions Specification for NITF 2.1 * section 8.0(RSMPIA). */ class ossimRsmpia { public: /** @brief default constructor */ ossimRsmpia(); /** @brief copy constructor */ ossimRsmpia( const ossimRsmpia& obj ); /** @brief assignment operator */ const ossimRsmpia& operator=( const ossimRsmpia& rhs ); /** * @brief saveState Saves state to keyword list. * @param kwl * @param prefix */ void saveState( ossimKeywordlist& kwl, const std::string& prefix ) const; /** * @brief loadState Loads state from keyword list. * @param kwl * @param prefix * @return true on success; false, on error. */ bool loadState( const ossimKeywordlist& kwl, const std::string& prefix ); /** * @brief initialize Initializes from nitf rsmpia tag. * @param rsmpiaTag * @return true on success; false, on error. */ bool initialize( const ossimNitfRsmpiaTag* rsmpiaTag ); std::string m_iid; std::string m_edition; ossim_float64 m_r0; ossim_float64 m_rx; ossim_float64 m_ry; ossim_float64 m_rz; ossim_float64 m_rxx; ossim_float64 m_rxy; ossim_float64 m_rxz; ossim_float64 m_ryy; ossim_float64 m_ryz; ossim_float64 m_rzz; ossim_float64 m_c0; ossim_float64 m_cx; ossim_float64 m_cy; ossim_float64 m_cz; ossim_float64 m_cxx; ossim_float64 m_cxy; ossim_float64 m_cxz; ossim_float64 m_cyy; ossim_float64 m_cyz; ossim_float64 m_czz; ossim_uint32 m_rnis; ossim_uint32 m_cnis; ossim_uint32 m_tnis; ossim_uint32 m_rssiz; ossim_uint32 m_cssiz; }; // End: class ossimRsmpia() #endif /* #ifndef ossimRsmpia_H */ ossim-Miami-2.9.1/include/ossim/support_data/ossimSpaceImagingGeom.h000066400000000000000000000040611352751253100255610ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: Converts SpaceImaging geometry file to // OSSIM Geometry file. // //******************************************************************* // $Id: ossimSpaceImagingGeom.h 10251 2007-01-14 17:30:14Z dburken $ #ifndef ossimSpaceImagingGeom_HEADER #define ossimSpaceImagingGeom_HEADER #include #include #include class OSSIM_DLL ossimSpaceImagingGeom { public: ossimSpaceImagingGeom(const ossimFilename& file, const char* prefix = 0); ossimSpaceImagingGeom(); void setGeometry(const ossimFilename& file); void setGeometry(const ossimKeywordlist& kwl); void exportToOssim(ossimKeywordlist& kwl, const char* prefix=0)const; ossimString spaceImagingToOssimKeyword(const ossimString& spaceImagingKeyword)const; ossimString spaceImagingToOssimValue(const ossimString& spaceImagingKeyword, const ossimString& spaceImagingValue)const; ossimString getBandName()const; ossimFilename getFilename()const; ossimString getProducer()const; static const char* SIG_PRODUCER_KW; static const char* SIG_PROJECT_NAME_KW; static const char* SIG_FILENAME_KW; static const char* SIG_BAND_KW; static const char* SIG_BITS_PER_PIXEL_KW; static const char* SIG_NUMBER_OF_BANDS_KW; static const char* SIG_DATUM_KW; static const char* SIG_PROJECTION_KW; static const char* SIG_SELECTED_PROJECTION_KW; static const char* SIG_ZONE_KW; static const char* SIG_UL_EASTING_KW; static const char* SIG_UL_NORTHING_KW; static const char* SIG_PIXEL_SIZE_X_KW; static const char* SIG_PIXEL_SIZE_Y_KW; static const char* SIG_COLUMNS_KW; static const char* SIG_ROWS_KW; protected: ossimKeywordlist theSpaceImagingGeometry; ossimString thePrefix; }; #endif ossim-Miami-2.9.1/include/ossim/support_data/ossimSpotDimapSupportData.h000066400000000000000000000254101352751253100265120ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // // Author: Oscar Kramer (ossim port by D. Burken) // // Description: // // Contains declaration of class ossimSpotDimapSupportData. // //***************************************************************************** // $Id: ossimSpotDimapSupportData.h 17814 2010-08-03 12:44:02Z dburken $ #ifndef ossimSpotDimapSupportData_HEADER #define ossimSpotDimapSupportData_HEADER #include #include #include #include #include #include #include #include #include #include #include #include #include class ossimKeywordlist; // class ossimRefPtr; class ossimXmlDocument; class ossimSpotDimapSupportData : public ossimObject, public ossimErrorStatusInterface { public: /** metadata.dim format version */ enum ossimSpotMetadataVersion { OSSIM_SPOT_METADATA_VERSION_UNKNOWN = 0, OSSIM_SPOT_METADATA_VERSION_1_0 = 1, OSSIM_SPOT_METADATA_VERSION_1_1 = 2 }; ossimSpotDimapSupportData(); ossimSpotDimapSupportData(const ossimSpotDimapSupportData& rhs); ossimSpotDimapSupportData(const ossimFilename& dimapFile, bool processSwir=false); virtual ossimObject* dup()const; void clearFields(); bool loadXmlFile(const ossimFilename& file, bool processSwir=false); ossimString getSensorID() const; ossimString getMetadataVersionString() const; ossimString getAcquisitionDate() const; ossimString getProductionDate() const; ossimString getImageID() const; ossimString getInstrument() const; ossim_uint32 getInstrumentIndex() const; ossimFilename getMetadataFile() const; void getSunAzimuth(ossim_float64& az) const; void getSunElevation(ossim_float64& el) const; void getImageSize(ossimDpt& sz) const; void getLineSamplingPeriod(ossim_float64& pe) const; void getIncidenceAngle(ossim_float64& ia) const; void getViewingAngle(ossim_float64& va) const; void getSceneOrientation(ossim_float64& so) const; ossim_uint32 getNumberOfBands() const; ossim_uint32 getStepCount() const; bool isStarTrackerUsed() const; bool isSwirDataUsed() const; //--- // Image center point: //--- /** Center of frame, sub image if there is one. */ void getRefGroundPoint(ossimGpt& gp) const; /** zero base center point */ void getRefImagePoint(ossimDpt& rp) const; void getRefLineTime(ossim_float64& rt) const; /** relative to full frame. */ void getRefLineTimeLine(ossim_float64& rtl) const; /** Zero based image rectangle, sub image if there is one. */ void getImageRect(ossimDrect& rect)const; //--- // Sub image offset: //--- void getSubImageOffset(ossimDpt& offset) const; //--- // Ephemeris (m & m/s): //--- void getPositionEcf(ossim_uint32 sample, ossimEcefPoint& pe) const; void getPositionEcf(const ossim_float64& time, ossimEcefPoint& pe) const; void getVelocityEcf(ossim_uint32 sample, ossimEcefPoint& ve) const; void getVelocityEcf(const ossim_float64& time, ossimEcefPoint& ve) const; void getEphSampTime(ossim_uint32 sample, ossim_float64& et) const; ossim_uint32 getNumEphSamples() const; //--- // Attitude Angles in RADIANS: //--- void getAttitude(ossim_uint32 sample, ossimDpt3d& at) const; void getAttitude(const ossim_float64& time, ossimDpt3d& at) const; void getAttSampTime(ossim_uint32 sample, ossim_float64& at) const; ossim_uint32 getNumAttSamples() const; //--- // Pixel Pointing/Mirror tilt Angles in RADIANS: //--- void getPixelLookAngleX (ossim_uint32 sample, ossim_float64& pa) const; void getPixelLookAngleX (const ossim_float64& sample, ossim_float64& pa) const; void getPixelLookAngleY (ossim_uint32 sample, ossim_float64& pa) const; void getPixelLookAngleY (const ossim_float64& sample, ossim_float64& pa) const; //--- // Geoposition points provided in the file (most likely just corner points): //--- ossim_uint32 getNumGeoPosPoints() const; void getGeoPosPoint (ossim_uint32 point, ossimDpt& ip, ossimGpt& gp) const; //--- // Corner points: //--- void getUlCorner(ossimGpt& pt) const; void getUrCorner(ossimGpt& pt) const; void getLrCorner(ossimGpt& pt) const; void getLlCorner(ossimGpt& pt) const; //--- // Convenient method to print important image info: //--- void printInfo (std::ostream& os) const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix = 0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix = 0); protected: virtual ~ossimSpotDimapSupportData(); private: void getLagrangeInterpolation(const ossim_float64& t, const std::vector& V, const std::vector& T, ossimDpt3d& li )const; void getBilinearInterpolation(const ossim_float64& t, const std::vector& V, const std::vector& T, ossimDpt3d& li )const; void getInterpolatedLookAngle(const ossim_float64& p, const std::vector& angles, ossim_float64& la) const; ossim_float64 convertTimeStamp(const ossimString& time_stamp) const; void convertTimeStamp(const ossimString& time_stamp, ossim_float64& ti) const; /** * Initializes theMetadataVersion. * @return true on success, false if not found. */ bool initMetadataVersion(ossimRefPtr xmlDocument); /** * Initializes theImageId. * @return true on success, false if not found. */ bool initImageId(ossimRefPtr xmlDocument); /** * From xml section: * /Dimap_Document/Dataset_Sources/Source_Information/Scene_Source * * Initializes: * theSunAzimuth * theSunElevation * theIncidenceAngle * @return true on success, false if not found. */ bool initSceneSource(ossimRefPtr xmlDocument); /** * Frame points: * * From xml section: * /Dimap_Document/Dataset_Frame/ * * Initializes: * theRefGroundPoint * theUlCorner * theUrCorner * theLrCorner * theLlCorner * theViewingAngle * * Note that the theRefImagePoint will be the zero based center of the * frame. * @return true on success, false if not found. */ bool initFramePoints(ossimRefPtr xmlDocument); // Extrapolates the attitude for imaging times outside the defined range: void extrapolateAttitude(const ossim_float64& time, ossimDpt3d& at) const; ossimString theSensorID; ossimSpotMetadataVersion theMetadataVersion; ossimString theImageID; ossimFilename theMetadataFile; ossimString theProductionDate; ossimString theInstrument; ossim_uint32 theInstrumentIndex; /* * From xml section: * /Dimap_Document/Dataset_Sources/Source_Information/ * Scene_Source */ ossim_float64 theSunAzimuth; ossim_float64 theSunElevation; ossim_float64 theIncidenceAngle; ossim_float64 theViewingAngle; ossim_float64 theSceneOrientation; ossimDpt theImageSize; /** Center of frame on ground, if sub image it's the center of that. */ ossimGpt theRefGroundPoint; /** Zero based center of frame. */ ossimDpt theRefImagePoint; ossimDpt theSubImageOffset; /** relative to full image */ ossim_float64 theRefLineTime; /** relative to full image */ ossim_float64 theRefLineTimeLine; ossim_float64 theLineSamplingPeriod; /** holds the size of thePixelLookAngleX/Y */ ossim_uint32 theDetectorCount; std::vector thePixelLookAngleX; std::vector thePixelLookAngleY; std::vector theAttitudeSamples; // x=pitch, y=roll, z=yaw std::vector theAttSampTimes; std::vector thePosEcfSamples; std::vector theVelEcfSamples; std::vector theEphSampTimes; bool theStarTrackerUsed; bool theSwirDataFlag; ossim_uint32 theNumBands; ossimString theAcquisitionDate; ossim_uint32 theStepCount; //--- // Corner points: //--- ossimGpt theUlCorner; ossimGpt theUrCorner; ossimGpt theLrCorner; ossimGpt theLlCorner; //--- // Geoposition Points: //--- std::vector theGeoPosImagePoints; std::vector theGeoPosGroundPoints; ossimGpt createGround(const ossimString& s)const; ossimDpt createDpt(const ossimString& s)const; /** callibration information for radiometric corrections*/ std::vector thePhysicalBias; std::vector thePhysicalGain; std::vector theSolarIrradiance; /** * Private parse methods called by loadXml. * * These "parse" methods were made simply to split the loadXmlMethod * into pieces. This was an attempt to troubleshoot what was thought to * be a compiler issue, which turned out to be changed metadata and bad * error handling within this code. Since there were lots of debug * statements added I am committing this to cvs. * DRB 16 Oct. 2005 */ bool parsePart1(ossimRefPtr xmlDocument); bool parsePart2(ossimRefPtr xmlDocument); bool parsePart3(ossimRefPtr xmlDocument); bool parsePart4(ossimRefPtr xmlDocument); }; #endif /* #ifndef ossimSpotDimapSupportData_HEADER */ ossim-Miami-2.9.1/include/ossim/support_data/ossimSrcRecord.h000066400000000000000000000177131352751253100243200ustar00rootroot00000000000000//************************************************************************************************* // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // AUTHOR: Oscar Kramer // //************************************************************************************************* // $Id: ossimSrcRecord.h 2788 2011-06-29 13:20:37Z oscar.kramer $ #ifndef ossimSrcRecord_HEADER #define ossimSrcRecord_HEADER #include #include #include #include #include #include //************************************************************************************************* // CLASS DESCRIPTION: //! Class used for parsing the command line *.src files. This is a scheme for providing input //! file information to am ossim app such as ossim-orthoigen. //! //! The following keywords with image prefixes as shown are considered: //! //! image0.file: //! image0.entry: (unsigned integer) //! image0.ovr: //! image0.hist: //! image0.hist-op: auto-minmax | std-stretch N (N=1|2|3) //! image0.support: //! image0.rgb: R,G,B (unsigned integers starting with 1) //! image0.mask: //! image0.opacity: //! image0.replacement_mode: //! image0.clamp.min: //! image0.clamp.max: //! image0.clip.min: //! image0.clip.max: //! //! vector0.file: //! vector0.entry: (unsigned integer) //! vector0.query: " << endl << "where output types are: " << endl; printOutputTypes(); } void printOutputTypes() { std::vector outputType; ossimImageWriterFactoryRegistry::instance()->getImageTypeList(outputType); std::copy(outputType.begin(), outputType.end(), std::ostream_iterator(cout, "\n")); } ossim-Miami-2.9.1/src/examples/tutorial/image_copy.cpp000066400000000000000000000102211352751253100227770ustar00rootroot00000000000000/*! * * OVERVIEW: * * this app is a simple image copy. It will use * the image writer factory to instantiate a registered * writer and connect to the input and execute the writer. * * The writers can be instantiatd by class name or by output image * type. * * PURPOSE: * * Learn how to construct a writer from a factory. Connect the * writer to the image loadeer/reader and output the image. * */ // iostream is used for general output // #include #include #include "base/data_types/ossimFilename.h" #include "base/data_types/ossimString.h" // this is for implementing progress output. // #include "base/common/ossimStdOutProgress.h" // This is the majic number factory. All loaders are registered to this factory. // it will lookp through all factories to try to open the passed in image file // #include "imaging/factory/ossimImageHandlerRegistry.h" // Base pointer for the passed back object type // #include "imaging/formats/ossimImageHandler.h" // Base pointer our file writer // #include "imaging/formats/ossimImageFileWriter.h" #include "imaging/factory/ossimImageWriterFactoryRegistry.h" // this is the most important class and is called as the first line of all applications. // without this alll the important factories are not created. // #include "init/ossimInit.h" using namespace std; void usage(); void printOutputTypes(); int main(int argc, char* argv[]) { ossimInit::instance()->initialize(argc, argv); if(argc!=4) { usage(); } else { // try to open up the passed in image // ossimImageHandler *handler = ossimImageHandlerRegistry::instance()->open(ossimFilename(argv[2])); // try to create a writer for the output image type. // ossimImageFileWriter* writer = ossimImageWriterFactoryRegistry::instance()->createWriter(ossimString(argv[1])); if(!handler) { cout << "Unable to open input image: "<< argv[2] << endl; return 1; } if(!writer) { cout << "Unable to create writer of type: " << argv[1] << endl; delete handler; return 1; } // specify the output file name writer->setFilename(ossimFilename(argv[3])); // within OSSIM we have a concept of inputs that can be connected together // writer have only 1 input and we index them starting from 0. If we only // supplied the second argument it would find the first available input and connect // it to that slot. Here, we explicitly say connect the handler to slot 0 of the // writer. // writer->connectMyInputTo(0, handler); // Optionally we can add listeners to listen for certain events. // // all writers should execute event processing and generate a progress event. // we have a default event listener that listens for this event and can be used // to output the progress of the exected process. // // the first argument is to specify the precision of the percent complete // output, here we default to 0 for whole number outputs. The second argument // specifies to flush the stream on each print If you don't want progress // output then don't add this listener // // the defalut standard out listener is found in base/common/ossimStdOutProgress.h" // ossimStdOutProgress progress(0, true); writer->addListener(&progress); // execute the writer. Writer will start sequencing through // all the tiles from the input and output it to disk. // writer->execute(); // now to be on the safe side we will remove any added listeners. writer->removeListener(&progress); delete writer; delete handler; } return 0; } void usage() { cout << "image_copy " << endl << "where output types are: " << endl; printOutputTypes(); } void printOutputTypes() { std::vector outputType; ossimImageWriterFactoryRegistry::instance()->getImageTypeList(outputType); std::copy(outputType.begin(), outputType.end(), ostream_iterator(cout, "\n")); } ossim-Miami-2.9.1/src/examples/tutorial/image_copy_b1.cpp000066400000000000000000000056501352751253100233730ustar00rootroot00000000000000/*! * * OVERVIEW: * * This app extends image_copy and adds an additional filter * to copy the first band from the input. * * PURPOSE: * * Learn how to use your first image filter ossimBandSelector. * */ // iostream is used for general output // #include #include #include "base/data_types/ossimFilename.h" #include "base/data_types/ossimString.h" // This is the majic number factory. All loaders are registered to this factory. // it will lookp through all factories to try to open the passed in image file // #include "imaging/factory/ossimImageHandlerRegistry.h" // Base pointer for the passed back object type // #include "imaging/formats/ossimImageHandler.h" // Base pointer our file writer // #include "imaging/formats/ossimImageFileWriter.h" #include "imaging/factory/ossimImageWriterFactoryRegistry.h" #include "imaging/tile_sources/ossimBandSelector.h" // this is the most important class and is called as the first line of all applications. // without this alll the important factories are not created. // #include "init/ossimInit.h" using namespace std; void usage(); void printOutputTypes(); int main(int argc, char* argv[]) { ossimInit::instance()->initialize(argc, argv); if(argc!=4) { usage(); } else { // try to open up the passed in image // ossimImageHandler *handler = ossimImageHandlerRegistry::instance()->open(ossimFilename(argv[2])); // try to create a writer for the output image type. // ossimImageFileWriter* writer = ossimImageWriterFactoryRegistry::instance()->createWriter(ossimString(argv[1])); if(!handler) { cout << "Unable to open input image: "<< argv[2] << endl; return 1; } if(!writer) { cout << "Unable to create writer of type: " << argv[1] << endl; return 1; } ossimBandSelector* selector = new ossimBandSelector; // specify a lookup table that maps // output band list to each input band // the first output band is mapped to // the first input band 0. // vector outputBandList(1); outputBandList[0] = 0; selector->setOutputBandList(outputBandList); selector->connectMyInputTo(0, handler); // specify the output file name writer->setFilename(ossimFilename(argv[3])); writer->connectMyInputTo(0, selector); writer->execute(); delete writer; delete handler; } return 0; } void usage() { cout << "image_copy " << endl << "where output types are: " << endl; printOutputTypes(); } void printOutputTypes() { std::vector outputType; ossimImageWriterFactoryRegistry::instance()->getImageTypeList(outputType); std::copy(outputType.begin(), outputType.end(), ostream_iterator(cout, "\n")); } ossim-Miami-2.9.1/src/examples/tutorial/image_data.cpp000066400000000000000000000374641352751253100227600ustar00rootroot00000000000000/*! * * OVERVIEW: * * We will retrieve information from the input source and manipulate the data. * All filters will have a data access point called getTile that can take a * rectangle/region of interest and a resolution level. Once we have * retrieved the data we will show documented examples on how to manipulate * the data. * * * PURPOSE: * * 1. Learn how to request data from the connected input and output some basic * information about the requested area of interest * 2. Learn how to use ossimImageData object to manipulate pixel data. * 3. Learn how to query subregions and copy subregions. * 4. Understand what is a NULL, EMPTY, FULL, and PARTIAL data object. * this is very import for mosaicking and other pixel * manipulation filters. * */ // this is the most important class and is called as the first line of all applications. // without this all the important factories are not created. // #include "init/ossimInit.h" #include "base/data_types/ossimFilename.h" #include "base/data_types/ossimString.h" #include "imaging/ossimImageData.h" #include "imaging/formats/ossimImageHandler.h" #include "imaging/factory/ossimImageHandlerRegistry.h" #include "imaging/factory/ossimImageDataFactory.h" // Base pointer for the passed back object type // #include "imaging/formats/ossimImageHandler.h" // used to get the string name of the scalar type for the handler. The scalar // type specifies if its unsigned char, float, double, ...etc // #include "base/misc/lookup_tables/ossimScalarTypeLut.h" #include #include void usage(); void printDataStatus(ossimDataObjectStatus status); void demo1(const ossimFilename& filename); void demo2(const ossimFilename& filename); void demo3(const ossimFilename& filename); int main(int argc, char* argv[]) { ossimInit::instance()->initialize(argc, argv); if(argc != 2) { usage(); } else { // demo 1 we will access some data from the input and print // some basic information about the data dn then access the data // buffers for each band. // demo1(ossimFilename(argv[1])); // Demo 2 just shows ways to allocate the ossimImageData // demo2(ossimFilename(argv[1])); // Demo 3 just show how to load region of a tile // demo3(ossimFilename(argv[1])); } ossimInit::instance()->finalize(); } void usage() { cout <<"image_data "<< endl; } // // The data object status is very useful and is used to determine // if the data is NULL( not initialized), empty (initialized but blank or empty, // partial(contains some null/invalid values), or full (all valid data). // // partial data means you have part of the information with valid data and the // rest of it is set to the null or invalid pixel value for that band. // // full data means that every pixel for each band has valid information. // // empty means that no data is present // // null means no data and the buffer is null. // // For this status to be set on the ossimImageData there is a method // validate that is called. Typically this is called when you implement // a filter that changes the stored data. // void printDataStatus(ossimDataObjectStatus status) { // now lets output some of the information about the tile. The tile // switch(status) { case OSSIM_NULL: { cout << "data status = " << "null" << endl; break; } case OSSIM_EMPTY: { cout << "data status = " << "empty" << endl; break; } case OSSIM_PARTIAL: { cout << "data status = " << "partial" << endl; break; } case OSSIM_FULL: { cout << "data status = " << "full" << endl; break; } default: { cout << "data status = " << "unknown" << endl; } } } // Demo 1 will retrieve a region of interest using the // ossimIrect which is an integer rectangle. // void demo1(const ossimFilename& filename) { cout << "___________________________________DEMO 1_____________________________________\n"; ossimImageHandler* handler = ossimImageHandlerRegistry::instance()->open(filename); if(handler) { } else { cerr <<"Unable to open image " << filename << endl; return; } // we will query the first 100 by 100 pixel of data from the input // and compute the average value of each band. We will only allow // this to happen with unsigned char data. // // Rectangles in ossim take absolute coordinates for upper // left and lower right and does not take an upper left // point and then a width height. So if I want the data // starting at point location 0,0 and ending at 100 pixels along // the x and y direction then we have 0 to 99 along x = 100 and // 0 to 99 along y = 100. // // the second argument to getTile is optional and corresponds // to the resolution level or overview. // ossimIrect regionsOfInterest(0,0, 99, 99); // the data returned from the call getTile is not owned by you and // you should not delete the pointer. // ossimRefPtr data = handler->getTile(regionsOfInterest); if(data.valid()) { // output the rectangle of the tile. cout << "tile rect = " << data->getImageRectangle() << endl; // output the status of the tile. See printDataStatus above for // documentation of status. printDataStatus(data->getDataObjectStatus()); // how many bands are there. // cout << "Number of bands = " << data->getNumberOfBands() << endl; // as in image_open lets use te scalr lut to pint the scalar type as a // string. cout << "Pixel scalar type = " << ossimScalarTypeLut::instance()->getEntryString(data->getScalarType()) << endl; // for each band let's print the min, max and null pixel values // note: the min max values are not for the tile but for the entire // input. Typically these are used for tile normalization // and clamping to data bounds. // cout << "min pix: "; std::copy(data->getMinPix(), data->getMinPix()+data->getNumberOfBands(), ostream_iterator(cout, ", ")); cout << "\nmax pix: "; std::copy(data->getMaxPix(), data->getMaxPix()+data->getNumberOfBands(), ostream_iterator(cout, ", ")); cout << "\nnull pix: "; std::copy(data->getNullPix(), data->getNullPix()+data->getNumberOfBands(), ostream_iterator(cout, " ")); cout << endl; if(data->getScalarType()!=OSSIM_UCHAR) { delete handler; cerr << "Demo 1 only works for uchar data images" << endl; return; } // Now lets compute the average pixel for each band. The data buffer is // internally stored in osismImageData object as a void* buffer. We must cast // to the scalar type or work in normalized space. For this example we will // work the tile in its native type and will not normalize and we will also // only work with unsigned char or uchar data. // // Note: ossimImageData already has a compute mean and sigma. We will re-implement // some code here // // I will implement a more efficient algorithm by only checking for invalid data // if the status is not full. If its full we don't have to check for // null value and all we need to do is compute the sum. Although we can just check for null // all the time and not worry about 2 different loops. // int upperBound = data->getWidth()*data->getHeight(); if(data->getDataObjectStatus() == OSSIM_FULL) { // since te data is full all pixls are used in the avverage double totalNumberOfPixels = upperBound; for(ossim_uint32 bandIndex = 0; bandIndex < data->getNumberOfBands(); ++bandIndex) { double sumOfThePixels = 0; // get access to the raw band data. ossim_uint8* buf = (ossim_uint8*)data->getBuf(bandIndex); for(int offset = 0; offset < upperBound; ++offset) { sumOfThePixels += *buf; ++buf; } if(totalNumberOfPixels > 0) { cout << "band " << bandIndex << " average = " << sumOfThePixels/totalNumberOfPixels << endl; } else { cout << "band " << bandIndex << " average = " << 0.0 << endl; } } } else if(data->getDataObjectStatus() == OSSIM_PARTIAL) { for(ossim_uint32 bandIndex = 0; bandIndex < data->getNumberOfBands(); ++bandIndex) { double totalNumberOfPixels = 0; double sumOfThePixels = 0; ossim_uint8* buf = (ossim_uint8*)data->getBuf(bandIndex); ossim_uint8 np = (ossim_uint8)data->getNullPix(bandIndex); for(int offset = 0; offset < upperBound; ++offset) { if(np != *buf) { sumOfThePixels += *buf; ++totalNumberOfPixels; } ++buf; } if(totalNumberOfPixels > 0) { cout << "band " << bandIndex << " average = " << sumOfThePixels/totalNumberOfPixels << endl; } else { cout << "band " << bandIndex << " average = " << 0.0 << endl; } } } } cout << "___________________________________END DEMO 1_____________________________________\n"; delete handler; } // Demo 2 will show how to create your own data objects // there are several ways to do this. void demo2(const ossimFilename& filename) { cout << "___________________________________DEMO 2_____________________________________\n"; ossimImageHandler* handler = ossimImageHandlerRegistry::instance()->open(filename); if(!handler) { cerr << "Unable to open file " << filename << " for demo 2\n"; return; } // Create image data using the factory technique. // This might be the best way to do it. We might have optimized // implementations for certain input types. For instance you might // want to create an ossimImageData that is optimized for 3 band // ossim_uint8 data. // // there other create methods but this takes as its // first argument a source that owns this data object // and the second argument is the input source to use // to help instantiate the object. Please refer to // ossim_core/imaging/factory/ossimImageDataFactory // for further implementation // ossimRefPtr data = ossimImageDataFactory::instance()->create(NULL, handler); // note: the data is not initialized/allocated. We have // a concept of a NULL or un initialized tile so all the // meta data is carried with it but just don't take up space // by allocating the buffer. The number of bands, the rectangle // of interest, min, max, null are all set. // // We will now initialize the data. The initialize will // allocate the buffer based on the number of bands, width, // height and scalar type and then will set the buffer to // the null pixel value and set the status OSSIM_EMPTY. // data->initialize(); // if you ever want to see if the initialization has been // done then you must call isInitialize. // cout << "data initialized: " << data->isInitialize() << endl; // To make a duplicate copy of the ossimImageData the easiest // way to do this is to call the dup method. // ossimRefPtr dupData = (ossimImageData*)data->dup(); ossimIrect newRect(10,20,200,200); // this particualr method will reallocate the tile // if already initialized and set it to the new // rectangle of interest. // dupData->setImageRectangle(newRect); // allocating without the factory // ossimRefPtr data2 = new ossimImageData(NULL, // owner of the data object OSSIM_UCHAR, // what scalar type 3, // number of bands 128, // width 128); // height data2->initialize(); // delete the allocated data objects. cout << "___________________________________END DEMO 2_____________________________________\n"; } // Demo 3 will show how to create your own data objects // there are several ways to do this. void demo3(const ossimFilename& filename) { cout << "___________________________________DEMO 3_____________________________________\n"; ossimImageHandler* handler = ossimImageHandlerRegistry::instance()->open(filename); if(!handler) { cerr << "Unable to open file " << filename << " for demo 2\n"; return; } // lets just get some data. we will get a 128 by // 128 tile that has upper left origin at 10, 10. // ossimRefPtr data = handler->getTile(ossimIrect(10, 10, 10 + 127, 10 + 127)); if(data.valid()) { cout << "Data rectangle = " << data->getImageRectangle() << endl; ossimRefPtr data2 = ossimImageDataFactory::instance()->create(0, handler); data2->setImageRectangle(ossimIrect(0,0,127,127)); data2->initialize(); cout << "Data 2 rectangle = " << data2->getImageRectangle() << endl; cout << "loading data2 rectangle\n"; // now load the data 2 region with data. Notice the // tile overlaps the data tile and only the // overlapping region is copied. // data2->loadTile(data.get()); // now we can use the raw load tile where you supply the // rectangle. Now if you do this your buffer is assumed // to have the same number of bands. // // Now you must pass in the interleave type of your buffer // The ossimImageData has interleave band sequential, OSSIM_BSQ // which means the bands are sequential in memory where // all of band 1 data followed by all of band 2 ... etc. // The other interleave type are OSSIM_BIP or band // interleaved by pixel. For instance if you had an RGB // data object then it would be RGB, RGB, RGB ... etc. // The final interleave type is by line OSSIM_BIL. This // just says band 1 line1 followed by band2 line2 ... etc until all // lines are stored. // data2->loadTile(data->getBuf(), data->getImageRectangle(), OSSIM_BSQ); // I manipulated the buffer so lets validate it for future // use. I would only validate after you get done doing your // data manipulation. // data2->validate(); cout << "status after load is should be partial \n"; printDataStatus(data2->getDataObjectStatus()); // loadBand has simalar arguments but allows // you to do band loads. // for(ossim_uint32 band = 0; band < data->getNumberOfBands(); ++band) { data2->loadBand(data->getBuf(band), data->getImageRectangle(), band); } data2->validate(); // please refer to ossim_core/imaging/ossimImageData.h for // other load methods // } cout << "___________________________________END DEMO 3_____________________________________\n"; } ossim-Miami-2.9.1/src/examples/tutorial/image_open.cpp000066400000000000000000000113201352751253100227670ustar00rootroot00000000000000/*! * * OVERVIEW: * * this app is a simple image open. * It should open any image supported by the ossim library. * Once the image is open it prints out some general information * about the image. * * PURPOSE: * * Learn how to open an image and query attributes. Also learn which * headers are required to perform these tasks. * */ // iostream is used for general output // #include // within this program ossimCommon is used for ossimGetScalarSizeInBytes. // This header will have some common globabl inline and non-inline functions // #include "base/common/ossimCommon.h" #include "base/data_types/ossimFilename.h" // used to get the string name of the scalar type for the handler. The scalar // type specifies if its unsigned char, float, double, ...etc // #include "base/misc/lookup_tables/ossimScalarTypeLut.h" // This is the majic number factory. All loader are registered to this factory. // it will lookp through all factories to try to open the passed in image file // #include "imaging/factory/ossimImageHandlerRegistry.h" // Base pointer for the passed back object type // #include "imaging/formats/ossimImageHandler.h" // this is the most important class and is called as the first line of all applications. // without this alll the important factories are not created. // #include "init/ossimInit.h" using namespace std; int main(int argc, char* argv[]) { ossimInit::instance()->initialize(argc, argv); if(argc == 2) { // call the registries open and let it traverse through all registered // factories to open up an image. // ossimImageHandler *handler = ossimImageHandlerRegistry::instance()->open(ossimFilename(argv[1])); if(handler) { // includes full resolution so if there are no overviews this value should be // 1. Note: resolution levels or overviews or indexed from 0 being full // resolution to (number of decimations or overviews -1.. // // Overviews are very import for resampling images to different resolutions efficiently. // The overviews are generally power of 2 decimations. Assume we have an image that has // full resolution of 1024x1024 in size. When we are talking about resolution 0 then // we are talking about the full res 1024x1024, but when we are talking // about resolution level 1 then we are looking at the start of the overview and referes to // a decimation of 2^1 which is 512x512 image. So when we ask for resolution level N then // we are talking about a decimation of 2^N // // So again, when we query the number of decimation levels this includes resolution layer 0. // int overviews = handler->getNumberOfDecimationLevels(); // the image bounds can take an argument to specify which resolution I would like to get // the bounding rect of. By default if no argument is given it assumes full resolution or // resolution 0. // ossimIrect bounds = handler->getBoundingRect(0); // scalar type cooresponds to the pixel radiometry type. The pixel can be of precision // float, double, unsigned char, unsigned short, signed short data values. Look at // ossimScalarType enumeration found in base/common/ossimConstants.h for supporting types // ossimScalarType scalarType = handler->getOutputScalarType(); // This is a utility class that maps enumeration values to strings. So we will use this // when we query the scalar type from the image and wish to print the text version of it. // // ossimScalarTypeLut* lut = ossimScalarTypeLut::instance(); cout <<"filename = " << handler->getFilename() << endl << "width = " << bounds.width() << endl << "height = " << bounds.height() << endl << "overview count = " << (overviews-1) << endl << "scalar type = " << lut->getEntryString(handler->getOutputScalarType()) << endl // ossimGetScalarSizeInBytes is a utility functions found in base/common/ossimCommon.h // it will return the byte size of the scalar type. // << "pixel size = " << ossimGetScalarSizeInBytes(scalarType) << " byte(s)" <" << endl; } // call the finalize so the ossim can cleanup if needed. ossimInit::instance()->finalize(); return 0; } ossim-Miami-2.9.1/src/examples/tutorial/kwl.cpp000066400000000000000000000126621352751253100214730ustar00rootroot00000000000000/*! * * OVERVIEW: * * This app uses factory and keywordlist to instatiate objects within OSSIM. Among these * objects are projections, and image processing filters/mosaics and annotations. Basically any * object within OSSIM that must have a state saved or loaded uses a keywordlist to do so. * The main keyword required by all objects is a TYPE_KW which has a value "type". Most * keywords that are used in OSSIM are located in base/common/ossimKeywordNames.h * * We will also demonstrate the use of object factory registry to instantiate objects from * type name. * * A keyword list is basically a name value pair and you want to make sure that the name portion * is unique for all objects being saved to the keywordlist. for example I may want to save 2 objects * to the keyword list and object 1 may have a prefix value of object1. and object 2 may have a * prefix value of object2. and so forth. See sample code for demonstration. * * Note: Since multiple objects may reside within a keywodlist a prefix value is used to prefix all * attributes of an object. * * * PURPOSE: * * Learn how to instantiate different types of objects from a keywordlist * through the ossimObjectFactoryRegistry. * */ #include #include "base/common/ossimCommon.h" #include "base/data_types/ossimFilename.h" #include "base/data_types/ossimKeywordlist.h" #include "base/factory/ossimObjectFactoryRegistry.h" #include "init/ossimInit.h" using namespace std; ossimObject* createObject(const ossimString& objectType); void demo1(); void demo2(); void demo3(); int main(int argc, char* argv[]) { ossimInit::instance()->initialize(argc, argv); cout << "_______________________________DEMO 1__________________________\n"; demo1(); cout << "_______________________________DEMO 2__________________________\n"; demo2(); cout << "_______________________________DEMO 3__________________________\n"; demo3(); ossimInit::instance()->finalize(); return 0; } ossimObject* createObject(const ossimString& objectType) { return ossimObjectFactoryRegistry::instance()->createObject(objectType); } /*! * Demo1 will just instantiate and object of the passed in type and then execute a * save state and print that keywordlist out. */ void demo1() { ossimObject* obj1 = createObject("ossimRgbToGreyFilter"); if(obj1) { ossimKeywordlist kwl; obj1->saveState(kwl); cout << "------------------ object 1 = " << obj1->getClassName() << " keyword list is -----------------" << endl; cout << kwl << endl; kwl.clear(); cout << "------------------ object 1 = " << obj1->getClassName() << " keyword list with prefix -----------------" << endl; obj1->saveState(kwl, "object1."); cout << kwl << endl; } else { cout << "This shouldn't happen" << endl; } } /*! * Save 2 objects to a keywordlist without conflict in values. This will force us to * use a prefix in order to save 2 objects to the same list */ void demo2() { ossimObject* obj1 = createObject("ossimRgbToGreyFilter"); ossimObject* obj2 = createObject("ossimBrightnessContrastSource"); if(obj1&&obj2) { ossimKeywordlist kwl; obj1->saveState(kwl, "object1."); obj2->saveState(kwl, "object2."); cout << "Objects " << obj1->getClassName() << " and " << obj2->getClassName() << " saved to the same keywordlist." << endl; cout << kwl << endl; } else { cout << "This shouldn't happen" << endl; } } /*! * Save object to keywordlist and then pass keyword list to factory and * instantitate an object from keywordlist. We will do it twice, the first time * without a prefix and then the second time with a prefix. * * We will use 2 object types: the first one will be a filter and the second one will * be a projection. * * Note: you should get identical outputs for both outputs. * */ void demo3() { ossimObject* obj = createObject("ossimRgbToGreyFilter"); ossimObject* proj = createObject("ossimUtmProjection"); if(obj&&proj) { ossimKeywordlist kwl; obj->saveState(kwl); ossimObject* objNew = ossimObjectFactoryRegistry::instance()->createObject(kwl); if(objNew) { ossimKeywordlist kwl2; objNew->saveState(kwl2); cout << "____________________ The Original object " << obj->getClassName() << " ___________________" << endl; cout << kwl << endl; cout << "____________________ The New object " << objNew->getClassName() << " ___________________" << endl; cout << kwl2 << endl; delete objNew; } else { cout << "ERROR: This shouldn't happen" << endl; } kwl.clear(); proj->saveState(kwl); objNew = ossimObjectFactoryRegistry::instance()->createObject(kwl); if(objNew) { ossimKeywordlist kwl2; objNew->saveState(kwl2); cout << "____________________ The Original object " << proj->getClassName() << " ___________________" << endl; cout << kwl << endl; cout << "____________________ The New object " << objNew->getClassName() << " ___________________" << endl; cout << kwl2 << endl; delete objNew; } else { cout << "ERROR: This shouldn't happen" << endl; } delete obj; delete proj; } else { cout << "This shouldn't happen" << endl; } } ossim-Miami-2.9.1/src/examples/tutorial/ossim_preferences000066400000000000000000000023611352751253100236230ustar00rootroot00000000000000// ------------------------------------------------------------------------ // $Id: ossim_preferences 4349 2003-03-27 19:52:21Z gpotts $ // // Description: ossim_preferences_template // // This file will be automatically loaded by ossim applications provided the // environment variable "OSSIM_PREFS_FILE" is set to point to some form of // this file. // // Note: c++ comments "//" can be used to comment a line. // // To set the environment variable for automatic preference file loading: // // This assumes a preference file in your home called "ossim_preferences". // Typically this would be put in a dot file read at startup of a shell. // // tcsh and csh users: setenv OSSIM_PREFS_FILE ~/ossim_preferences // // bash and sh users: export OSSIM_PREFS_FILE=~/ossim_preferences // // windoze users: I'll have to look this up... // // You can also use the "-P " option at application startup. // where is full path and filename // // ------------------------------------------------------------------------ // plugin support // plugin.dir1: /work/gpotts/ossim-plugin // You can also list files individually // plugin.file1: plugin.file1: /home/gpotts/ossim/src/examples/tutorial/ossimSharedBandAverageFilter.so ossim-Miami-2.9.1/src/examples/tutorial/reproject.cpp000066400000000000000000000114711352751253100226700ustar00rootroot00000000000000/*! * * OVERVIEW: * * Will reproject the input image to a utm projection. * * PURPOSE: * * Teach you how to create a renderer and set the view and connect it up to an input * */ // iostream is used for general output // #include #include #include "base/data_types/ossimFilename.h" #include "base/data_types/ossimString.h" #include "imaging/factory/ossimImageHandlerRegistry.h" #include "imaging/formats/ossimImageHandler.h" #include "imaging/formats/ossimImageFileWriter.h" #include "imaging/factory/ossimImageWriterFactoryRegistry.h" // this is an ossim ground point and has a lat, lon, and datum // associated with it. #include "base/data_types/ossimGpt.h" // Base class for accessing projection parameters. #include "projections/ossimProjection.h" // the projection used in the reprojection #include "projections/map_projections/ossimUtmProjection.h" // used to instantiate a projector #include "projections/factory/ossimProjectionFactoryRegistry.h" // The heart of the OSSIM resampling process for reprojecting imagery #include "imaging/tile_sources/ossimImageRenderer.h" // this is the most important class and is called as the first line of all applications. // without this alll the important factories are not created. #include "init/ossimInit.h" using namespace std; void usage(); void printOutputTypes(); ossimProjection* newUtmView(const ossimGpt& centerGround, const ossimDpt& metersPerPixel); int main(int argc, char* argv[]) { ossimInit::instance()->initialize(argc, argv); if(argc!=4) { usage(); } else { // try to open up the passed in image // ossimImageHandler *handler = ossimImageHandlerRegistry::instance()->open(ossimFilename(argv[2])); // try to create a writer for the output image type. // ossimImageFileWriter* writer = ossimImageWriterFactoryRegistry::instance()->createWriter(ossimString(argv[1])); if(!handler) { cout << "Unable to open input image: "<< argv[2] << endl; return 1; } if(!writer) { cout << "Unable to create writer of type: " << argv[1] << endl; delete handler; return 1; } ossimKeywordlist geom; handler->getImageGeometry(geom); // grab a projection if it exists // ossimProjection* inputProjection = ossimProjectionFactoryRegistry::instance()->createProjection(geom); if (!inputProjection) { cout << "the input image has no input projection and can't be reprojected" << endl; delete handler; delete writer; return 1; } // --------------------- SETUP The Resampleing process ------------- // // the renderer is the resampler that fits into the chain. // we will set it to a UTM view. We first get the inputs geometry and // then get the scale from its projector. // // now lets set up the renderer ossimImageRenderer* renderer = new ossimImageRenderer; // // get the center ground by running the center pixel // through the handler's projection object ossimIrect bounds = handler->getBoundingRect(); ossimGpt centerGround; inputProjection->lineSampleToWorld(bounds.midPoint(), centerGround); // now set the view to a new UTM view. // I pass true in to tell the renderer that it owns the // projection and will be responsible for deleting // renderer->setView(newUtmView(centerGround, inputProjection->getMetersPerPixel()), true); // connect the renderer to the handler renderer->connectMyInputTo(handler); // specify the output file name writer->setFilename(ossimFilename(argv[3])); // now connect the writer to the renderer writer->connectMyInputTo(0, renderer); // execute the reprojection process. writer->execute(); delete writer; delete handler; } return 0; } void usage() { cout << "repoject " << endl << "where output types are: " << endl; printOutputTypes(); } void printOutputTypes() { std::vector outputType; ossimImageWriterFactoryRegistry::instance()->getImageTypeList(outputType); std::copy(outputType.begin(), outputType.end(), std::ostream_iterator(std::cout, "\n")); } ossimProjection* newUtmView(const ossimGpt& centerGround, const ossimDpt& metersPerPixel) { ossimUtmProjection* utm = new ossimUtmProjection; // we will make it a square pixel in meters double averageGsd = (metersPerPixel.x + metersPerPixel.y)*.5; utm->setZone(centerGround); utm->setMetersPerPixel(ossimDpt(metersPerPixel)); return utm; } ossim-Miami-2.9.1/src/examples/tutorial/writing_your_own_image_processing_filter.html000066400000000000000000000200351352751253100314400ustar00rootroot00000000000000

Writing Your Own Simple Image Processing Filter

Prepared by Garrett Potts

ImageLinks, Inc



We will take you through the steps to writing your first filter and adding it to the factory so it can be saved and loaded through the factory interface. We will show you both 1 ) through the shared library plugin support and 2) through manual editing of the internal OSSIM factories. We will start with a simple filter that takes all bands and performs a weighted average on them and outputs a single band. Our filter should work with any data type such as uchar, sint16, uint16, float(and normalized float), double (and normalized doubles). For this filter we have two ways to do this: 1) normalize the input data, do the weighted average on the normalized data, and unnormalize back to its original type and make sure all values keep to within the min max values, or 2) use a template method to operate within native scalar types. If we choose option 1 we will need to allocate 2 buffers, one for output and one for normalization, but if we choose option 2 we will only have a single tile buffered. For this filter we chose option 2. If you want to see examples of option 1 for normalizing the input just look at src/ossim_core/imaging/ossimScalarRemapper The min max for weighted average should not occure if all weights sum to 1. We will gurantee that all weights sum to 1. For complete code see src/examples/tutorial/ossimBandAverageFilter.h(.cc) and src/examples/tutorial/band_average.cc for example use of the filter.

  1. Choosing a base class for our filter

    Since this is a single input in filter we will derive from ossimImageSourceFilter since it already implements the basic setting up the input connection and copying the pointer to an internal pointer call theInputConnection. It will also pass most of the requests to the input. Based on the description of the filter we will need to override the following: 1) getTile method for getting the data being filtered, 2) load and save state methods for being able to load and save the state of our new object, 3) get number of output bands method since we are going to always output a single band output, 4) general access methods for our internal attributes, and 5) getMinPixelValue, getMaxPixelValue and getNullPixelValue We will use a vector of doubles for the weights of each band. It will be up to us to make sure this array is of the correct size (i.e. Size is equal to the number of input bands). We will use two ossimImageData objects where one is for the outputtile which we will cal theTile and one is the normalized buffer which we will call theNormBufferTile.

  2. getTile method

    This will be the main filtering algorithm. We must perform several checks before we actually execute the filter: 1) We need to see if there is an input to grab data from, 2) we need to see if our filter is actually enabled or not, 3) we need to see if any needed buffer data has been allocated, and 4) finally we need to set the output data rectangle. Please see source for complete implementation

  3. Load and Save State Methods

    These methods are very important to allow your filter to be constructed from a keywordlist ( please see kwl.cc for sample usage of the keywordlist). For a reminder, a keywordlist is no more than unique name value pairs that identify all attributes within the system and your filter is just one of many attributes that might exist in any of the ossim applications. We will store the weights used in the weighted average into a string list of weights. Please see the filter source for detailed implementation.

  4. getNumberOfOutputBands method

    Since our filter can be enabled and disabled this should return 1 if our filter is enabled. If our filter is not enabled we will need to return theInputConnection's getNumberOfOutputBands (Please see the filter source for detailed implementation).

  5. getMinPixelValue, getMaxPixelValue, and getNullPixelValue

    These are important since we are taking multiple bands of data and collapsing it to a single band. Since each band can have a differnet min and max null pix of the first band. Really the NULL pixel value should be the same for al and null we need to keep it consistent. Our min output should be the min of all bands and the max should be the max of all bands and we will use the l bands.

  6. Adding to the factory by Editing the Factory Manually

    Since this is a filter we will add it to the src/ossim_core/imaging/factory/ossimImageSourceFactory.cc file. Add your filter class name in the getTypeNameList and then add your filter to the createObject method. Note, the getTypeNameList uses the RTTI class name of the object. If you look at the bottom of the ossimBandAverageFilter.h file you will see TYPE_DATA and this declares the RTTI support for your class. If you look close to the top of ossimBandAverageFilter.cc file you will see RTTI_DEF1 that defines the RTTI support for your class where the 1 is the number of classes you are deriving from (please see code for implementation). The RTTI is very important since I use it to help uniquely id your new class since no 2 classes can have the same name in ossim. Once this is complete you now can compile OSSIM with the new filter and then access it through the factory.

  7. Adding to the Factory through shared library

    You also have the option of placing your filter into a shared library and using the OSSIM plugin bridge to get access to code that instantiates you filter. It is important to note that this has only been tested under Linux using .so interface. I still need to test this in a .dll file found under windows and .dylib found under macs. The plugin interface is demonstrated in the src/examples/tutorial/ossimSharedBandAverageFilter.h(.cc) file. The shared support code for OSSIM bridge is located at the bottom of the .cc file. It is fully documented to specify what each line is doing. Use the shared_band_average application found in the same directory to demonstrate the loading of the shared library. OSSIM has a concept of a preference file and the current preferences and documentation can be found in the file ossim/etc/templates/ossim_preferences_template. For you convenience I have copied a preference file to the tutorial directory and only have the single plugin file. You wil have to change the path to match your location. The preference file found in the template directory shows you how to setup OSSIM to recognize the template file. Within the template is an explanation on how to add your plugin to be loaded by any OSSIM app that calls the ossimInit initialize code. Once this is done and if it is done correctly you should be able to run the application. To test the plugin to see if it is actually visible through the factory just run: shared_band_average -P<full path and filename of preference> . If it was done correctly then you should see it print out that it was able to construct ossimSharedBandAverageFilter else it will say unable to create it. Try running the application without specifying the preference file. You should see that it was unable to create the object of that type.

ossim-Miami-2.9.1/src/font/000077500000000000000000000000001352751253100154505ustar00rootroot00000000000000ossim-Miami-2.9.1/src/font/ossimFont.cpp000066400000000000000000000030651352751253100201410ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: // //******************************************************************** // $Id: ossimFont.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include "math.h" #include using namespace std; #include RTTI_DEF2(ossimFont, "ossimFont", ossimObject, ossimErrorStatusInterface); void ossimFont::setRotation(double rotationInDegrees) { theRotation = rotationInDegrees; computeMatrix(); } void ossimFont::setScale(double horizontal, double vertical) { theHorizontalScale = horizontal; theVerticalScale = vertical; computeMatrix(); } void ossimFont::computeMatrix() { NEWMAT::Matrix r(2,2); NEWMAT::Matrix s(2,2); double radRotation = theRotation*M_PI/180.0; r << cos(radRotation) << -sin(radRotation) << sin(radRotation) << cos(radRotation); s << theHorizontalScale << theVerticalShear << theHorizontalShear << theVerticalScale; theAffineTransform = s*r; } void ossimFont::getBoundingClipBox(ossimIrect& clippedBox) { getBoundingBox(clippedBox); if(!theClippingBox.hasNans()&& (theClippingBox.width()>1)&&(theClippingBox.height()>1) ) { clippedBox = clippedBox.clipToRect(theClippingBox); } } ossimIrect ossimFont::getBoundingClipBox() { ossimIrect clipBox; getBoundingClipBox(clipBox); return clipBox; } ossim-Miami-2.9.1/src/font/ossimFontFactoryRegistry.cpp000066400000000000000000000122111352751253100232130ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimFontFactoryRegistry.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #if OSSIM_HAS_FREETYPE # include #endif #include //ossimFontFactoryRegistry* ossimFontFactoryRegistry::theInstance = 0; using namespace std; ossimFontFactoryRegistry::ossimFontFactoryRegistry() :theDefaultFont(NULL) { // theInstance = this; #if OSSIM_HAS_FREETYPE registerFactory(ossimFreeTypeFontFactory::instance()); #endif } ossimFontFactoryRegistry* ossimFontFactoryRegistry::instance() { static ossimFontFactoryRegistry sharedInstance; //theInstance = new ossimFontFactoryRegistry; return &sharedInstance; } bool ossimFontFactoryRegistry::registerFactory(ossimFontFactoryBase* factory) { bool result = false; if(factory&&!findFactory(factory)) { theFactoryList.push_back(factory); result = true; } return result; } void ossimFontFactoryRegistry::unregisterFactory(ossimFontFactoryBase* factory) { std::vector::iterator iter = std::find(theFactoryList.begin(), theFactoryList.end(), factory); if(iter != theFactoryList.end()) { theFactoryList.erase(iter); } } bool ossimFontFactoryRegistry::findFactory(ossimFontFactoryBase* factory)const { return (std::find(theFactoryList.begin(), theFactoryList.end(), factory)!=theFactoryList.end()); } ossimFont* ossimFontFactoryRegistry::createFont(const ossimFontInformation& information)const { ossimFont* result = (ossimFont*)NULL; int i = 0; for(i= 0; ( (i < (int)theFactoryList.size()) &&(!result)); ++i) { result = theFactoryList[i]->createFont(information); } return result; } ossimFont* ossimFontFactoryRegistry::createFont(const ossimFilename& file)const { ossimFont* result = (ossimFont*)NULL; int i = 0; for(i= 0; ( (i < (int)theFactoryList.size()) &&(!result)); ++i) { result = theFactoryList[i]->createFont(file); } return result; } void ossimFontFactoryRegistry::getFontInformation(std::vector& informationList)const { int i = 0; for(i= 0; i < (int)theFactoryList.size(); ++i) { theFactoryList[i]->getFontInformation(informationList); } } void ossimFontFactoryRegistry::getFontInformationFamilyName(std::vector& informationList, const ossimString& familyName)const { vector info; getFontInformation(info); ossimString right = familyName; right = right.upcase().trim(); int i = 0; for(i = 0; i < (int)info.size(); ++i) { ossimString left = info[i].theFamilyName; left = left.upcase().trim(); if(left == right) { informationList.push_back(info[i]); } } } void ossimFontFactoryRegistry::getFontInformationContainingFamilyName(std::vector& informationList, const ossimString& familyName)const { vector info; getFontInformation(info); ossimString right = familyName; right = right.upcase().trim(); int i = 0; for(i = 0; i < (int)info.size(); ++i) { ossimString left = info[i].theFamilyName; left = left.upcase().trim(); if(left.contains(right)) { informationList.push_back(info[i]); } } } ossimFont* ossimFontFactoryRegistry::getDefaultFont()const { if(!theDefaultFont) { std::vector infoList; getFontInformationContainingFamilyName(infoList, "Times"); if(infoList.size() < 1) { getFontInformationContainingFamilyName(infoList, "Roman"); } if(infoList.size() < 1) { getFontInformationContainingFamilyName(infoList, "Sanz"); } if(infoList.size() < 1) { getFontInformation(infoList); } if(infoList.size()) { theDefaultFont = createFont(infoList[0]); theDefaultFont->setPixelSize(12, 12); } else { theDefaultFont = new ossimGdBitmapFont("gd sans", "bold", ossimGdSansBold); } } return theDefaultFont.get(); } ossimFontFactoryRegistry::ossimFontFactoryRegistry(const ossimFontFactoryRegistry& /* rhs */ ) { } void ossimFontFactoryRegistry::operator=(const ossimFontFactoryRegistry& /* rhs */ ) { } ossim-Miami-2.9.1/src/font/ossimFreeTypeFont.cpp000066400000000000000000000427641352751253100216160ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimFreeTypeFont.cpp 21518 2012-08-22 21:15:56Z dburken $ // ossimFreeTypeFont.h should be load prior to checking for OSSIM_HAS_FREETYPE. #include #if OSSIM_HAS_FREETYPE # include # include # include # include # include // for memset # ifndef NULL # include # endif static ossimTrace traceDebug ("ossimFreeTypeFont:debug"); RTTI_DEF1(ossimFreeTypeFont, "ossimFreeTypeFont", ossimFont); using namespace std; ossimFreeTypeFont::ossimFreeTypeFont(const ossimFilename& fontFile) :ossimFont(), theFontFace(NULL), theLibrary(NULL), theFontFile(fontFile), theOutputBuffer(NULL), theBufferSize(0), theKerningEnabledFlag(true), theNeedToLayoutGlyphsFlag(true), theBoundingRectIsValid(false) { int error; if(fontFile.exists()) { error = FT_Init_FreeType(&theLibrary); if(error) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimFreeTypeFont::ossimFreeTypeFont: Can't initialize freetype" << std::endl; setErrorStatus(); } if(getErrorStatus() == ossimErrorCodes::OSSIM_OK) { error = FT_New_Face( theLibrary, fontFile.c_str(), 0, &theFontFace ); if (error == FT_Err_Unknown_File_Format) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimFreeTypeFont::ossimFreeTypeFont: Unable to create a font face for file = " << fontFile << std::endl; } FT_Done_Library(theLibrary); theLibrary = NULL; setErrorStatus(); } else { setBaseClassInformation(); } } } else { setErrorStatus(); } } ossimFreeTypeFont::ossimFreeTypeFont(const ossimFreeTypeFont& rhs) :ossimFont(rhs), theMatrix(rhs.theMatrix), theFontFile(rhs.theFontFile), theOutputBuffer(NULL), theBufferSize(0), theKerningEnabledFlag(rhs.theKerningEnabledFlag), theNeedToLayoutGlyphsFlag(rhs.theNeedToLayoutGlyphsFlag), theStringCenter(rhs.theStringCenter), theShift(rhs.theShift), thePrecomputedBoundingRect(rhs.thePrecomputedBoundingRect), theBoundingRectIsValid(rhs.theBoundingRectIsValid) { if(rhs.getErrorStatus()) { setErrorStatus(); } else { int error; error = FT_Init_FreeType(&theLibrary); if(error) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimFreeTypeFoont::ossimFreeTypeFont: Can't initialize freetype in copy constructor" <family_name; if(isFixed()) { vector initialPointList; getFixedSizes(initialPointList); theHorizontalPixelSize = initialPointList[0].x; theVerticalPixelSize = initialPointList[0].y; } else { theHorizontalPixelSize = 8; theVerticalPixelSize = 8; } if((theFontFace->style_flags & FT_STYLE_FLAG_BOLD) && (theFontFace->style_flags&FT_STYLE_FLAG_ITALIC)) { theStyleName = "bold italic"; } else if(theFontFace->style_flags & FT_STYLE_FLAG_BOLD) { theStyleName = "bold"; } else if(theFontFace->style_flags & FT_STYLE_FLAG_ITALIC) { theStyleName = "italic"; } else { theStyleName = "normal"; } } } void ossimFreeTypeFont::setCurrentFace(long index) { int error; if(theFontFace) { if((index >0) && (index < theFontFace->num_faces)) { FT_Done_Face(theFontFace); theFontFace = NULL; error = FT_New_Face( theLibrary, theFontFile.c_str(), index, &theFontFace ); if((error == FT_Err_Unknown_File_Format)||error) { setErrorStatus(); } else { setBaseClassInformation(); } theBoundingRectIsValid = false; } } } void ossimFreeTypeFont::getFixedSizes(vector& sizeArray)const { if(theFontFace) { sizeArray.clear(); int i = 0; for(i = 0; i < theFontFace->num_fixed_sizes; ++i) { sizeArray.push_back(ossimIpt(theFontFace->available_sizes[i].width, theFontFace->available_sizes[i].height)); } } } void ossimFreeTypeFont::allocateBuffer() { ossimIrect box; setupForRasterization(); getBoundingClipBox(box); long bufferSize = box.width()*box.height(); if(bufferSize != theBufferSize) { theBufferSize = bufferSize; if(theOutputBuffer) { delete theOutputBuffer; theOutputBuffer = NULL; } if(!theOutputBuffer&&theBufferSize) { theOutputBuffer = new ossim_uint8[theBufferSize]; } } } void ossimFreeTypeFont::deleteGlyphs(vector& glyphs) { int i = 0; for(i = 0; i < (int)glyphs.size(); ++i) { if(glyphs[i].image) { FT_Done_Glyph(glyphs[i].image); } } glyphs.clear(); } #endif /* #if OSSIM_HAS_FREETYPE */ ossim-Miami-2.9.1/src/font/ossimFreeTypeFontFactory.cpp000066400000000000000000000154511352751253100231370ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimFreeTypeFontFactory.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include /* To pick up OSSIM_HAS_FREETYPE. */ #if OSSIM_HAS_FREETYPE # include # include # include # include # include ossimFreeTypeFontFactory* ossimFreeTypeFontFactory::theInstance=0; using namespace std; ossimFreeTypeFontFactory::ossimFreeTypeFontFactory() { theInstance = this; } ossimFreeTypeFontFactory::~ossimFreeTypeFontFactory() { theInstance = 0; } ossimFreeTypeFontFactory* ossimFreeTypeFontFactory::instance() { if(!theInstance) { theInstance = new ossimFreeTypeFontFactory; theInstance->initializeDefaults(); } return theInstance; } ossimFont* ossimFreeTypeFontFactory::createFont(const ossimFontInformation& information)const { ossimRefPtr result; ossimString rightFamilyName = information.theFamilyName; ossimString rightStyleName = information.theStyleName; rightFamilyName = rightFamilyName.upcase().trim(); rightStyleName = rightStyleName.upcase().trim(); int i = 0; for(i = 0; ( (i < (int)theFontInformationList.size())&&(!result));++i) { ossimString leftFamilyName = theFontInformationList[i].theFontInformation.theFamilyName; ossimString leftStyleName = theFontInformationList[i].theFontInformation.theStyleName; leftFamilyName = leftFamilyName.upcase().trim(); leftStyleName = leftStyleName.upcase().trim(); if( (leftFamilyName == rightFamilyName)&& (leftStyleName == rightStyleName)) { if(theFontInformationList[i].theFontInformation.theFixedFlag) { if(theFontInformationList[i].theFontInformation.thePointSize == information.thePointSize) { result = new ossimFreeTypeFont(theFontInformationList[i].theFilename); if(result.valid()) { if(result->getErrorStatus()) { result = 0; ossimNotify(ossimNotifyLevel_WARN) <<"WARNING ossimFreeTypeFontFactory::createFont: unable to open font file " << theFontInformationList[i].theFilename << std::endl; } } } } else { result = new ossimFreeTypeFont(theFontInformationList[i].theFilename); if(result.valid()) { if(result->getErrorStatus()) { result = 0; ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimFreeTypeFontFactory::createFont: unable to open font file " << theFontInformationList[i].theFilename << std::endl; } else { if(information.thePointSize.x&& information.thePointSize.y) { result->setPixelSize(information.thePointSize.x, information.thePointSize.y); } } } } } } if(result.valid()) { result->setScale(information.theScale.x, information.theScale.y); result->setScale(information.theScale.x, information.theScale.y); result->setHorizontalVerticalShear(information.theShear.x, information.theShear.y); result->setRotation(information.theRotation); } return result.release(); } ossimFont* ossimFreeTypeFontFactory::createFont(const ossimFilename& file)const { ossimRefPtr result = new ossimFreeTypeFont(file); if(result->getErrorStatus()) { result = 0; } return result.release(); } void ossimFreeTypeFontFactory::getFontInformation(std::vector& informationList)const { int i = 0; for(i = 0; i < (int)theFontInformationList.size();++i) { informationList.push_back(theFontInformationList[i].theFontInformation); } } bool ossimFreeTypeFontFactory::addFile(const ossimFilename& file) { ossimRefPtr font = new ossimFreeTypeFont(file); std::vector fontInfoList; bool result = false; int i = 0; if(font->getFontFace()) { if(!font->getErrorStatus()) { font->getFontInformation(fontInfoList); for(i = 0; i < (int)fontInfoList.size();++i) { theFontInformationList.push_back(ossimFreeTypeFontInformation(file, fontInfoList[i])); } result = true; } } // Free memory. font = 0; return result; } void ossimFreeTypeFontFactory::initializeDefaults() { const ossimKeywordlist& kwl = ossimPreferences::instance()->preferencesKWL(); ossimString regExpressionDir = ossimString("^(") + "font.dir[0-9]+)"; ossimString regExpressionFile = ossimString("^(") + "font.file[0-9]+)"; vector dirs = kwl.getSubstringKeyList( regExpressionDir ); vector files = kwl.getSubstringKeyList( regExpressionFile ); int idx = 0; for(idx = 0; idx < (int)dirs.size();++idx) { const char* directoryLocation = kwl.find(dirs[idx]); if(directoryLocation) { ossimDirectory d; if(d.open(ossimFilename(directoryLocation))) { ossimFilename file; if(d.getFirst(file, ossimDirectory::OSSIM_DIR_FILES)) { do { addFile(file); }while(d.getNext(file)); } } } } for(idx = 0; idx < (int)files.size();++idx) { const char* fileName = kwl.find(files[idx]); if(fileName) { addFile(ossimFilename(fileName)); } } #if 0 if(!numberOfDirs&&!numberOfFiles) { #ifdef __UNIX__ ossimFilename file("/usr/X11R6/lib/X11/fonts/Type1"); if(file.exists()) { ossimDirectory d; if(d.open(file)) { if(d.getFirst(file, ossimDirectory::OSSIM_DIR_FILES)) { do { addFile(file); }while(d.getNext(file)); } } } #endif } #endif } #endif /* #if OSSIM_HAS_FREETYPE */ ossim-Miami-2.9.1/src/font/ossimGdBitmapFont.cpp000066400000000000000000000152241352751253100215510ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: // //******************************************************************** // $Id: ossimGdBitmapFont.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include #include "string.h" RTTI_DEF1(ossimGdBitmapFont, "ossimGdBitmapFont", ossimFont); using namespace std; ossimGdBitmapFont::ossimGdBitmapFont(const ossimString& familyName, const ossimString& styleName, const ossimGdFont* gdFontPtr) :ossimFont(familyName, styleName, (int)gdFontPtr->w, (int)gdFontPtr->h), theGdFontPtr(gdFontPtr), theBufferSize(0), theOutputBuffer(NULL) { } ossimGdBitmapFont::ossimGdBitmapFont(const ossimGdBitmapFont& rhs) :ossimFont(rhs), theGdFontPtr(rhs.theGdFontPtr), theBufferSize(rhs.theBufferSize), theOutputBuffer(NULL) { if(theBufferSize) { theOutputBuffer = new ossim_uint8[theBufferSize]; memcpy(theOutputBuffer, rhs.theOutputBuffer, theBufferSize); } } ossimGdBitmapFont::~ossimGdBitmapFont() { if(theOutputBuffer) { delete [] theOutputBuffer; theOutputBuffer = NULL; } } void ossimGdBitmapFont::getBoundingBox(ossimIrect& box) { if(theStringToRasterize.size()) { box = ossimIrect(0,0, (int)ceil(theStringToRasterize.size()*theHorizontalPixelSize*theHorizontalScale)-1, (int)ceil(theVerticalPixelSize*theVerticalScale)-1); } else { box = ossimIrect(0, 0, 0, 0); } // I currently don't support rotations and other affine operations so I will comment this // bounding box test out and use the above. // #if 0 if(theGdFontPtr) { if((theRotation == 0.0)&& (theHorizontalScale == 1.0)&& (theVerticalScale == 1.0)) { box = ossimIrect(0,0, theGdFontPtr->w-1, theGdFontPtr->h-1); } else { ossimIrect localBox(0,0, theGdFontPtr->w-1, theGdFontPtr->h-1); double ulx, uly; double llx, lly; double lrx, lry; double urx, ury; double min_x, min_y, max_x, max_y; ulx = 0.0; uly = 0.0; llx = (theAffineTransform[0][0]*localBox.ll().x + theAffineTransform[0][1]*localBox.ll().y); lly = theAffineTransform[1][0]*localBox.ll().x + theAffineTransform[1][1]*localBox.ll().y; lrx = (theAffineTransform[0][0]*localBox.lr().x + theAffineTransform[0][1]*localBox.lr().y); lry = theAffineTransform[1][0]*localBox.lr().x + theAffineTransform[1][1]*localBox.lr().y; urx = (theAffineTransform[0][0]*localBox.ur().x + theAffineTransform[0][1]*localBox.ur().y); ury = theAffineTransform[1][0]*localBox.ur().x + theAffineTransform[1][1]*localBox.ur().y; min_x = std::min(ulx, std::min(llx, (std::min(lrx, urx)))); max_x = std::max(ulx, std::max(llx, (std::max(lrx, urx)))); min_y = std::min(uly, std::min(lly, (std::min(lry, ury)))); max_y = std::max(uly, std::max(lly, (std::max(lry, ury)))); box = ossimIrect((int)floor(min_x), (int)floor(min_y), (int)ceil(max_x), (int)ceil(max_y)); } } #endif } const ossim_uint8* ossimGdBitmapFont::rasterize() { // make sure the buffer is allocated for the output string allocateBuffer(); if(theOutputBuffer) { memset(theOutputBuffer, 0, theBufferSize); rasterizeNormal(); } return theOutputBuffer; } void ossimGdBitmapFont::rasterizeNormal() { ossimIrect outBox; ossimIrect inBox(0,0, (ossim_int32)theStringToRasterize.length()*theGdFontPtr->w-1, theGdFontPtr->h-1); getBoundingBox(outBox); long charOffset = 0; long bufOffset = 0; long inW = inBox.width(); long inH = inBox.height(); long outW = outBox.width(); long outH = outBox.height(); ossim_uint8* inBuf = new ossim_uint8[inBox.width()*inBox.height()]; for(std::string::size_type character = 0; character < theStringToRasterize.size(); ++character) { charOffset = theStringToRasterize[character]; // we need to shift the offset to a positive value. // if it goes negative we just add 256 to the value. if(charOffset < 0) { charOffset += 256; } // which col do we start on bufOffset = (long)character*theGdFontPtr->w; // get the starting offset to the bitmap charOffset = charOffset*theGdFontPtr->w*theGdFontPtr->h; for(long row = 0; row < (theGdFontPtr->h); ++row) { for(long col = 0; col < theGdFontPtr->w; ++col) { if(theGdFontPtr->data[charOffset]) { inBuf[bufOffset+col] = 255; } ++charOffset; } bufOffset += inW; } } if((inW == outW)&&(inH==outH)) { memcpy(theOutputBuffer, inBuf, inW*inH); } else { // now lets expand or contract the input buf to the output buf. long *xLut = new long[outW]; long *yLut = new long[outH]; long i = 0; for(i = 0; i < outW; ++i) { xLut[i] = (int)(i*((double)inW/(double)outW)); } for(i = 0; i < outH; ++i) { yLut[i] = (int)(i*((double)inH/(double)outH)); } ossim_uint8* outBuf = theOutputBuffer; for(long row= 0; row < outH; ++row) { long inYOffset = yLut[row]*inW; for(long col=0; col < outW; ++col) { *outBuf = inBuf[inYOffset + xLut[col]]; ++outBuf; } } delete [] xLut; delete [] yLut; } delete [] inBuf; } void ossimGdBitmapFont::allocateBuffer() { ossimIrect box; getBoundingBox(box); long bufferSize = box.width()*box.height(); if(bufferSize != theBufferSize) { theBufferSize = bufferSize; if(theOutputBuffer) { delete theOutputBuffer; theOutputBuffer = NULL; } if(!theOutputBuffer&&theBufferSize) { theOutputBuffer = new ossim_uint8[theBufferSize]; } } } void ossimGdBitmapFont::getFixedSizes(vector& sizes)const { sizes.push_back(ossimIpt(theHorizontalPixelSize, theVerticalPixelSize)); } ossim-Miami-2.9.1/src/hdf5/000077500000000000000000000000001352751253100153305ustar00rootroot00000000000000ossim-Miami-2.9.1/src/hdf5/ossimHdf5.cpp000066400000000000000000000452621352751253100177060ustar00rootroot00000000000000//--- // // License: MIT // // Description: OSSIM HDF5 utility class. // //--- // $Id #include #include #include #include #include #include using namespace H5; using namespace std; ossimHdf5::ossimHdf5() : m_h5File (0) { } ossimHdf5::~ossimHdf5() { close(); } bool ossimHdf5::open(const ossimFilename& fullname) { // Check for empty filename. if (fullname.empty()) return false; m_filename = fullname; if (m_h5File && !close()) return false; // H5 lib throws exceptions: bool success = false; try { // Turn off the auto-printing when failure occurs so that we can handle the errors: H5::Exception::dontPrint(); if ( H5File::isHdf5( m_filename.string() ) ) { m_h5File = new H5File(m_filename.string(), H5F_ACC_RDONLY); success = true; } } catch( const H5::Exception& e ) { success = false; ossimNotify(ossimNotifyLevel_WARN) <"<< std::endl; success = false; } if (!success) { delete m_h5File; m_h5File = 0; } return success; } bool ossimHdf5::close() { bool success = true; if (m_h5File) { try { m_h5File->close(); delete m_h5File; m_h5File = 0; } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)<openGroup("/"); } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)<& groupList, bool recursive) { bool success = true; int numObjs = 0; try { numObjs = group.getNumObjs(); } catch( const H5::Exception& e ) { e.getDetailMsg(); success = false; } for (int i=0; (i& datasetList, bool recursive) { datasetList.clear(); vector groupList; if (recursive) { getChildGroups(group, groupList, true); } groupList.insert(groupList.begin(), group); bool success = true; try { vector::iterator group_iter = groupList.begin(); while (group_iter != groupList.end()) { int numObjs = group_iter->getNumObjs(); for (int i=0; igetObjTypeByIdx(i); if (h5type == H5G_DATASET) { string name = group_iter->getObjnameByIdx(i); datasetList.push_back(group_iter->openDataSet(name)); } } ++group_iter; } } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)<& datasetList, bool recursive) { datasetList.clear(); vector groupList; if (recursive) getChildGroups(group, groupList, true); groupList.insert(groupList.begin(), group); bool success = true; try { vector::iterator group_iter = groupList.begin(); while (group_iter != groupList.end()) { int numObjs = group_iter->getNumObjs(); for (int i=0; igetObjTypeByIdx(i); if (h5type == H5G_DATASET) { string name = group_iter->getObjnameByIdx(i); DataSet dataset (group_iter->openDataSet(name)); DataSpace dspace (dataset.getSpace()); if (dspace.getSimpleExtentNdims() > 1) datasetList.push_back(dataset); } } ++group_iter; } } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)<& attrList) { attrList.clear(); // Find the object: bool success = true; try { int numAttr = obj.getNumAttrs(); for (int i=0; i groupList; if (!getChildGroups(baseGroup, groupList, recursive)) return NULL; try { std::vector::iterator group = groupList.begin(); while (group != groupList.end()) { // bool found; ossimString dsName = group->getObjName(); if (dsName.contains(name)) { named_group = new Group(*group); break; } ++group; } } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)< datasetList; if (!getDatasets(baseGroup, datasetList, recursive)) return NULL; try { std::vector::iterator dataset = datasetList.begin(); while (dataset != datasetList.end()) { // bool found; ossimString dsName = dataset->getObjName(); if (dsName.contains(name)) { named_dataset = new H5::DataSet(*dataset); break; } ++dataset; } } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)<getTypeClass(); H5T_order_t order = H5T_ORDER_NONE; if ( typeClass == H5T_INTEGER ) { H5::IntType intype = obj->getIntType(); order = intype.getOrder(); } else if ( typeClass == H5T_FLOAT ) { H5::FloatType floatType = obj->getFloatType(); order = floatType.getOrder(); } if ( order == H5T_ORDER_LE ) { byteOrder = OSSIM_LITTLE_ENDIAN; } else if ( order == H5T_ORDER_BE ) { byteOrder = OSSIM_BIG_ENDIAN; } } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)<& extents ) { extents.clear(); try { // Get dataspace of the dataset. H5::DataSpace dataspace = dataset.getSpace(); // Number of dimensions: int ndims = dataspace.getSimpleExtentNdims(); if ( ndims ) { //hsize_t dims_out[ndims]; std::vector dims_out(ndims); dataspace.getSimpleExtentDims( &dims_out.front(), 0 ); for ( ossim_int32 i = 0; i < ndims; ++i ) { extents.push_back(static_cast(dims_out[i])); } } dataspace.close(); } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)< -1 ) { hid_t native_type = H5Tget_native_type(mem_type_id, H5T_DIR_DEFAULT); if( H5Tequal(H5T_NATIVE_CHAR, native_type) ) scalar = OSSIM_SINT8; else if ( H5Tequal( H5T_NATIVE_UCHAR, native_type) ) scalar = OSSIM_UINT8; else if( H5Tequal( H5T_NATIVE_SHORT, native_type) ) scalar = OSSIM_SINT16; else if(H5Tequal(H5T_NATIVE_USHORT, native_type)) scalar = OSSIM_UINT16; else if(H5Tequal( H5T_NATIVE_INT, native_type)) scalar = OSSIM_SINT32; else if(H5Tequal( H5T_NATIVE_UINT, native_type ) ) scalar = OSSIM_UINT32; else if(H5Tequal( H5T_NATIVE_LONG, native_type)) scalar = OSSIM_SINT32; else if(H5Tequal( H5T_NATIVE_ULONG, native_type)) scalar = OSSIM_UINT32; else if(H5Tequal( H5T_NATIVE_LLONG, native_type)) scalar = OSSIM_SINT64; else if(H5Tequal( H5T_NATIVE_ULLONG, native_type)) scalar = OSSIM_UINT64; else if(H5Tequal( H5T_NATIVE_FLOAT, native_type)) scalar = OSSIM_FLOAT32; else if(H5Tequal( H5T_NATIVE_DOUBLE, native_type)) scalar = OSSIM_FLOAT64; } else if ( typeClass == H5T_INTEGER ) { H5::IntType intType (dataset); bool isSigned = intType.getSign() == H5T_SGN_NONE ? false : true; size = intType.getSize(); switch (size) { case 1: if (isSigned) scalar = OSSIM_SINT8; else scalar = OSSIM_UINT8; break; case 2: if (isSigned) scalar = OSSIM_SINT16; else scalar = OSSIM_UINT16; break; case 4: if (isSigned) scalar = OSSIM_SINT32; else scalar = OSSIM_UINT32; break; case 8: if (isSigned) scalar = OSSIM_SINT64; else scalar = OSSIM_UINT64; break; default: break; } } else // float { size = datatype.getSize(); switch (size) { case 4: scalar = OSSIM_FLOAT32; break; case 8: scalar = OSSIM_FLOAT64; break; default: break; } } } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)<(dataPtr); ossim_uint32 dataSize = dataType.getSize(); ossimByteOrder order = getByteOrder(dataType); ossimEndian endian; bool swapOrder = (order!=ossim::byteOrder()); bool returnValue = true; switch(dataSize) { case 4: { ossim_float32* float_value=0; float_value = reinterpret_cast(buf); if (swapOrder) endian.swap(*float_value); result = ossimString::toString(*float_value).string(); break; } case 8: { ossim_float64* float_value=0; float_value = reinterpret_cast(buf); if (swapOrder) endian.swap(*float_value); result = ossimString::toString(*float_value).string(); break; } default: { returnValue = false; break; } } return returnValue; } bool ossimHdf5::intTypeToString(std::string& result, const H5::IntType& dataType, const char* dataPtr) { char* buf = const_cast(dataPtr); ossim_uint32 signType = H5Tget_sign(dataType.getId()); ossim_uint32 dataSize = dataType.getSize(); ossimByteOrder order = getByteOrder(dataType); ossimEndian endian; bool swapOrder = (order!=ossim::byteOrder()); bool returnValue = true; switch(dataSize) { case 1: // one byte integer { switch(signType) { case H5T_SGN_NONE: { ossim_uint8* intValue=0; intValue = reinterpret_cast(buf); result = ossimString::toString(*intValue).string(); break; } case H5T_SGN_2: { ossim_int8* intValue=0; intValue = reinterpret_cast(buf); result = ossimString::toString(*intValue).string(); break; } default: { returnValue = false; break; } } break; } case 2: // 2 byte integer { switch(signType) { case H5T_SGN_NONE: // unsigned { ossim_uint16* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); result = ossimString::toString(*intValue).string(); break; } case H5T_SGN_2: // Signed { ossim_int16* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); result = ossimString::toString(*intValue).string(); break; } default: { returnValue = false; break; } } break; } case 4: // 4 byte integer { switch(signType) { case H5T_SGN_NONE: { ossim_uint32* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); result = ossimString::toString(*intValue).string(); break; } case H5T_SGN_2: { ossim_int32* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); result = ossimString::toString(*intValue).string(); break; } default: { returnValue = false; break; } } break; } case 8: // 8 byte integer { switch(signType) { case H5T_SGN_NONE: { ossim_uint64* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); result = ossimString::toString(*intValue).string(); break; } case H5T_SGN_2: { ossim_int64* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); result = ossimString::toString(*intValue).string(); break; } default: { returnValue = false; break; } } break; } default: { returnValue = false; } } return returnValue; } bool ossimHdf5::stringTypeToString(std::string& result, const H5::StrType& dataType, const char* dataPtr) { bool returnValue = false; const char* startPtr = dataPtr; const char* endPtr = dataPtr; const char* maxPtr = dataPtr + dataType.getSize(); if(dataPtr) { while((endPtr != maxPtr)&&(*endPtr!='\0')) ++endPtr; result = std::string(startPtr, endPtr); bool returnValue = true; } return returnValue; }ossim-Miami-2.9.1/src/hdf5/ossimHdf5GridModel.cpp000066400000000000000000000344751352751253100215010ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimHdf5GridModel.cc // // License: See LICENSE.txt file in the top level directory. // // AUTHOR: David Burken // // Copied from Mingjie Su's ossimHdfGridModel. // // DESCRIPTION: // Contains implementation of class ossimHdf5GridModel. This is an // implementation of an interpolation sensor model. // // IMPORTANT: The lat/lon grid is for ground points on the ellipsoid. // The dLat/dHgt and dLon/dHgt partials therefore are used against // elevations relative to the ellipsoid. // //***************************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using namespace H5; static const int GRID_SAMPLING_INTERVAL = 32; RTTI_DEF1(ossimHdf5GridModel, "ossimHdf5GridModel", ossimCoarseGridModel); ossimHdf5GridModel::ossimHdf5GridModel() : ossimCoarseGridModel() { theLatGrid.setDomainType(ossimDblGrid::SAWTOOTH_90); } ossimHdf5GridModel::~ossimHdf5GridModel() { } bool ossimHdf5GridModel::initialize(ossimHdf5* hdf5, const ossimString& projDataPath) { if (!hdf5) return false; m_hdf5 = hdf5; m_projDataPath = projDataPath; theHeightEnabledFlag = false; try { initCoarseGrid("Latitude", theLatGrid); initCoarseGrid("Longitude", theLonGrid); } catch (ossimException& x) { ossimNotify(ossimNotifyLevel_FATAL)<findGroupByName(m_projDataPath.chars(), 0, true); DataSet* dataset = m_hdf5->findDatasetByName(datasetName, group, true); if (dataset == NULL) { xmsg << "ossimHdf5GridModel:"<<__LINE__ <<" ERROR: Could not find dataset \""<getSpace(); const ossim_int32 DIM_COUNT = dataSpace.getSimpleExtentNdims(); if ( DIM_COUNT != 2 ) return false; // Get the extents. dimsOut[0] is height, dimsOut[1] is width: std::vector dimsOut(DIM_COUNT); dataSpace.getSimpleExtentDims( &dimsOut.front(), 0 ); m_imageSize.y = dimsOut[0]; m_imageSize.x = dimsOut[1]; // Initialize the ossimDblGrid. Round up if size doesn't fall on end pixel. ossimDpt dspacing (GRID_SAMPLING_INTERVAL, GRID_SAMPLING_INTERVAL); ossim_uint32 gridRows = m_imageSize.y / GRID_SAMPLING_INTERVAL + 1; ossim_uint32 gridCols = m_imageSize.x / GRID_SAMPLING_INTERVAL + 1; if ( m_imageSize.y % GRID_SAMPLING_INTERVAL) ++gridRows; if ( m_imageSize.x % GRID_SAMPLING_INTERVAL) ++gridCols; ossimIpt gridSize (gridCols, gridRows); // The grid as used in base class, has UV-space always at 0,0 origin ossimDpt gridOrigin(0.0,0.0); coarseGrid.setNullValue(ossim::nan()); coarseGrid.initialize(gridSize, gridOrigin, dspacing); std::vector inputCount(DIM_COUNT); std::vector inputOffset(DIM_COUNT); inputOffset[0] = 0; // y_img is set below. inputOffset[1] = 0; inputCount[0] = 1; // y_img inputCount[1] = (hsize_t)m_imageSize.x; // x_img // Output dataspace dimensions. Reading a line at a time. const ossim_int32 OUT_DIM_COUNT = 3; std::vector outputCount(OUT_DIM_COUNT); outputCount[0] = 1; // band outputCount[1] = 1; // y_img outputCount[2] = m_imageSize.x; // x_img // Output dataspace offset. std::vector outputOffset(OUT_DIM_COUNT); outputOffset[0] = 0; outputOffset[1] = 0; outputOffset[2] = 0; ossimScalarType scalar = m_hdf5->getScalarType( *dataset); if ( scalar != OSSIM_FLOAT32 ) return false; // See if we need to swap bytes: ossimEndian endian; bool needSwap = false; if (m_hdf5->getByteOrder(dataset) != ossim::byteOrder()) needSwap = true; DataType dataType = dataset->getDataType(); // Output dataspace always the same, width of one line. DataSpace bufferDataSpace( OUT_DIM_COUNT, &outputCount.front()); bufferDataSpace.selectHyperslab( H5S_SELECT_SET, &outputCount.front(), &outputOffset.front() ); // Arrays to hold a single line of latitude longitude values. vector values(m_imageSize.x); ossim_float32 val = 0; hsize_t y_img = 0; // Line loop: for ( ossim_uint32 y = 0; y < gridRows; ++y ) { // y_img = line in image space y_img = y*GRID_SAMPLING_INTERVAL; if ( y_img < (ossim_uint32) m_imageSize.y ) { inputOffset[0] = y_img; dataSpace.selectHyperslab( H5S_SELECT_SET, &inputCount.front(), &inputOffset.front() ); // Read data from file into the buffer. dataset->read( &(values.front()), dataType, bufferDataSpace, dataSpace ); if ( needSwap ) endian.swap( &(values.front()), m_imageSize.x ); // Sample loop: hsize_t x_img = 0; for ( ossim_uint32 x = 0; x < gridCols; ++x ) { // x_img = sample in image space x_img = x*GRID_SAMPLING_INTERVAL; if ( x_img < (ossim_uint32) m_imageSize.x ) { val = values[x_img]; if (ossim::isnan(val)) // Nulls in grid! { xmsg << "ossimHdf5GridModel:"<<__LINE__<<" encountered nans!"; throw ossimException(xmsg.str()); } } else // Last column is outside of image bounds. { // Delta between last two latitude grid values. ossim_float32 val1 = coarseGrid.getNode( x-2, y ); ossim_float32 val2 = coarseGrid.getNode( x-1, y ); ossim_float32 spacing = val2 - val1; val = val2 + spacing; #if 0 /* Please leave for debug. (drb) */ cout << "val1: " << val1 << " val2 " << val2<getSpace(); if (dataSpace.getSimpleExtentNdims() != 2) { xmsg << "ossimHdf5GridModel:"<<__LINE__<<" ERROR: lat/lon grid dataspace rank != 2."; throw ossimException(xmsg.str()); } // Fetch size of grid in file. Extents are assumed to be the same for both lat and lon grids: hsize_t datExtents[2]; dataSpace.getSimpleExtentDims(datExtents); if ((datExtents[0] < 2) || (datExtents[1] < 2)) { xmsg << "ossimHdf5GridModel:"<<__LINE__<<" ERROR: lat/lon grid size is < 2."; throw ossimException(xmsg.str()); } // Initialize the base class coarse grids: theImageSize = ossimDpt(datExtents[0], datExtents[1]); ossimDrect uvRect(0, 0, theImageSize.u-1, theImageSize.v-1); ossimDpt cgSpacing(GRID_SAMPLING_INTERVAL, GRID_SAMPLING_INTERVAL); coarseGrid.initialize(uvRect, cgSpacing, ossim::nan()); // Declare data of interest in file (the whole thing): hsize_t offset[2] = { 0, 0 }; dataSpace.selectHyperslab( H5S_SELECT_SET, datExtents, offset ); // Initialize dataspace for memory buffer needed by dataset read operation: hsize_t bufExtents[2] = { (hsize_t) theImageSize.u, 1 }; DataSpace bufSpace(2, bufExtents); DataType dataType = dataset->getDataType(); string cname = dataType.fromClass(); cout << cname<(&dataType); if(atomType) { ossimByteOrder ossimByteOrder = ossim::byteOrder(); H5T_order_t h5order = atomType->getOrder(); if( ((h5order == H5T_ORDER_LE) && (ossimByteOrder != OSSIM_LITTLE_ENDIAN)) || ((h5order == H5T_ORDER_BE) && (ossimByteOrder != OSSIM_BIG_ENDIAN))) endian = new ossimEndian(); } // Loop over input grid rows, sampling according to desired interval to fill output // coarse grid, for latitude: ossimIpt cgGridSize (coarseGrid.size()); ossim_uint32 x=0, y=0, u=0, v=0; for ( ; (yread( buffer, dataType, bufSpace, dataSpace ); if ( endian ) endian->swap( buffer, bufExtents[0] ); // Need to subsample the input row and save into coarse grid: for ( x=0, u=0; (x right) crossesDateline = true; #endif for ( ossim_uint32 x = 0; x<(ossim_uint32)size.x; ++x) { longitude = (ossim_int32) theLonGrid.getNode(x, y); // Cast to integer. // look for 179 -> -179... if ( !found179 ) { if ( longitude == 179 ) { found179 = true; continue; } } else // found179 == true { if ( longitude == 178 ) { break; // Going West, 179 -> 178 } else if ( longitude == -179 ) { crossesDateline = true; break; } } // look for -179 -> 179... if ( !found181 ) { if ( longitude == -179 ) { found181 = true; continue; } } else // found181 == true { if ( longitude == -178 ) { break; // Going East -179 -> -178 } else if ( longitude == 179 ) { crossesDateline = true; break; } } } } if ( crossesDateline ) theLonGrid.setDomainType(ossimDblGrid::WRAP_360); else theLonGrid.setDomainType(ossimDblGrid::WRAP_180); return crossesDateline; } bool ossimHdf5GridModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { bool stat = ossimCoarseGridModel::saveState(kwl, prefix); kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimCoarseGridModel", true); return stat; } ossim-Miami-2.9.1/src/hdf5/ossimHdf5ImageDataset.cpp000066400000000000000000000643031352751253100221540ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: OSSIM HDF5 Image DataSet. // //---------------------------------------------------------------------------- // $Id #include #include #include #include #include #include #include #include //--- // This includes everything! Note the H5 includes are order dependent; hence, // the mongo include. //--- #include #include #include ossimHdf5ImageDataset::ossimHdf5ImageDataset(ossimHdf5ImageHandler* owner) : m_handler(owner), m_dataset(0), m_scalar(OSSIM_SCALAR_UNKNOWN), m_bands(1), m_lines(0), m_samples(0), m_endian(0) { if (owner) m_hdf5 = owner->m_hdf5; m_validRect.makeNan(); } ossimHdf5ImageDataset::ossimHdf5ImageDataset( const ossimHdf5ImageDataset& obj ) : m_handler(obj.m_handler), m_hdf5 (obj.m_hdf5), m_dataset(obj.m_dataset), m_scalar(obj.m_scalar), m_bands(obj.m_bands), m_lines(obj.m_lines), m_samples(obj.m_samples), m_endian( obj.m_endian ? new ossimEndian() : 0 ), m_validRect(obj.m_validRect) { } ossimHdf5ImageDataset::~ossimHdf5ImageDataset() { close(); } const ossimHdf5ImageDataset& ossimHdf5ImageDataset::operator=( const ossimHdf5ImageDataset& rhs ) { if ( this != &rhs ) { m_dataset = rhs.m_dataset; m_dataSpace = rhs.m_dataSpace; m_scalar = rhs.m_scalar; m_bands = rhs.m_bands; m_lines = rhs.m_lines; m_samples = rhs.m_samples; m_validRect = rhs.m_validRect; m_endian = ( rhs.m_endian ? new ossimEndian() : 0 ); } return *this; } bool ossimHdf5ImageDataset::initialize( const H5::DataSet& dataset) { close(); m_dataset = dataset; determineScalarType(); // if (!determineExtents() || !scanForValidImageRect() || !scanForMinMax()) if (!determineExtents())// || !scanForMinMax()) return false; return true; } // End: ossimH5ImageDataset::initialize bool ossimHdf5ImageDataset::determineExtents() { try { // Find the valid image rect. dataset may have null padding: H5::DataSpace imageDataspace = m_dataset.getSpace(); int rank = imageDataspace.getSimpleExtentNdims(); if (rank < 2) return false; // Get the extents. Assuming dimensions are same for lat lon dataset. std::vector inputSize(rank); imageDataspace.getSimpleExtentDims( &inputSize.front(), 0 ); m_lines = inputSize[0]; m_samples = inputSize[1]; m_validRect = ossimDrect(ossimDpt(0,0),ossimDpt(m_samples-1,m_lines-1)); if ( rank >= 3 ) m_bands = inputSize[2]; else m_bands = 1; if ( (m_lines == 0) || (m_samples == 0) ) return false; } catch( const H5::Exception& e ) { std::cout << "ERROR:" << e.getDetailMsg()<< " \n"; ossimNotify(ossimNotifyLevel_WARN)< dimsOut(IN_DIM_COUNT); imageDataspace.getSimpleExtentDims( &dimsOut.front(), 0 ); if ( dimsOut[0] && dimsOut[1] ) { //--- // Capture the rectangle: // dimsOut[0] is height, dimsOut[1] is width: //--- m_validRect = ossimIrect( 0, 0, static_cast( dimsOut[1]-1 ), static_cast( dimsOut[0]-1 ) ); const ossim_int32 WIDTH = m_validRect.width(); std::vector inputCount(IN_DIM_COUNT); std::vector inputOffset(IN_DIM_COUNT); inputOffset[0] = 0; inputOffset[1] = 0; inputCount[0] = 1; inputCount[1] = WIDTH; // Output dataspace dimensions. const ossim_int32 OUT_DIM_COUNT = 3; std::vector outputCount(OUT_DIM_COUNT); outputCount[0] = 1; // single band outputCount[1] = 1; // single line outputCount[2] = WIDTH; // whole line // Output dataspace offset. std::vector outputOffset(OUT_DIM_COUNT); outputOffset[0] = 0; outputOffset[1] = 0; outputOffset[2] = 0; ossimScalarType scalar = getScalarType(); if ( scalar == OSSIM_FLOAT32 ) { // Native type: H5::DataType datatype = m_dataset.getDataType(); // Output dataspace always the same one line. H5::DataSpace bufferDataSpace( OUT_DIM_COUNT, &outputCount.front()); bufferDataSpace.selectHyperslab( H5S_SELECT_SET, &outputCount.front(), &outputOffset.front() ); //--- // Dataset sample has NULL lines at the end so scan for valid rect. // Use "<= -999" for test as per NOAA as it seems the NULL value is // fuzzy. e.g. -999.3. //--- const ossim_float32 NULL_VALUE = -999.0; //--- // VIIRS Radiance data has a -1.5e-9 in the first column. // Treat this as a null. //--- ossimString name = m_dataset.getObjName(); const ossim_float32 NULL_VALUE2 = ( name == "/All_Data/VIIRS-DNB-SDR_All/Radiance" ) ? -1.5e-9 : NULL_VALUE; const ossim_float32 TOLERANCE = 0.1e-9; // For ossim::almostEqual() // Hold one line: std::vector values( WIDTH ); // Find the ul pixel: ossimIpt ulIpt = m_validRect.ul(); bool found = false; // Line loop to find upper left pixel: while ( ulIpt.y <= m_validRect.lr().y ) { inputOffset[0] = static_cast(ulIpt.y); imageDataspace.selectHyperslab( H5S_SELECT_SET, &inputCount.front(), &inputOffset.front() ); // Read data from file into the buffer. m_dataset.read( (void*)&values.front(), datatype, bufferDataSpace, imageDataspace ); if ( m_endian ) { // If the endian pointer is initialized(not zero) swap the bytes. m_endian->swap( scalar, (void*)&values.front(), WIDTH ); } // Sample loop: ulIpt.x = m_validRect.ul().x; ossim_int32 index = 0; while ( ulIpt.x <= m_validRect.lr().x ) { if ( !ossim::almostEqual(values[index], NULL_VALUE2, TOLERANCE) && ( values[index] > NULL_VALUE ) ) { found = true; // Found valid pixel. break; } ++ulIpt.x; ++index; } // End: sample loop if ( found ) { break; } ++ulIpt.y; } // End line loop to find ul pixel: // Find the lower right pixel: ossimIpt lrIpt = m_validRect.lr(); found = false; // Line loop to find last pixel: while ( lrIpt.y >= m_validRect.ul().y ) { inputOffset[0] = static_cast(lrIpt.y); imageDataspace.selectHyperslab( H5S_SELECT_SET, &inputCount.front(), &inputOffset.front() ); // Read data from file into the buffer. m_dataset.read( (void*)&values.front(), datatype, bufferDataSpace, imageDataspace ); if ( m_endian ) { // If the endian pointer is initialized(not zero) swap the bytes. m_endian->swap( scalar, (void*)&values.front(), WIDTH ); } // Sample loop: lrIpt.x = m_validRect.lr().x; ossim_int32 index = WIDTH-1; while ( lrIpt.x >= m_validRect.ul().x ) { if ( !ossim::almostEqual(values[index], NULL_VALUE2, TOLERANCE) && ( values[index] > NULL_VALUE ) ) { found = true; // Found valid pixel. break; } --lrIpt.x; --index; } // End: sample loop if ( found ) { break; } --lrIpt.y; } // End line loop to find lower right pixel. m_validRect = ossimIrect( ulIpt, lrIpt ); result = true; } else // Matches: if ( scalar == OSSIM_FLOAT32 ){...} { ossimNotify(ossimNotifyLevel_WARN) << "ossimHdf5ImageDataset:"<<__LINE__<<" WARNING!" << "\nUnhandled scalar type: " << ossimScalarTypeLut::instance()->getEntryString( scalar ) << std::endl; } } // Matches: if ( dimsOut... } // Matches: if ( IN_DIM_COUNT == 2 ) //cout << "ossimHdf5ImageDataset:"<<__LINE__<<" m_validRect = "<ulIpt.y) && !found_valid; lrIpt.y--) { imageOffset[0] = lrIpt.y; imageDataspace.selectHyperslab( H5S_SELECT_SET, rowSize, imageOffset); m_dataset.read(rowBuf, dataType, bufferDataSpace, imageDataspace ); // Scan row for valid pixel: ossim_int64 rowOffset = m_samples*elem_size - 1; for (lrIpt.x=m_samples-1; (lrIpt.x>ulIpt.x) && !found_valid; lrIpt.x-- , rowOffset-=elem_size) found_valid = (memcmp(&rowBuf[rowOffset], fill_value, elem_size) != 0); } if (!found_valid) lrIpt = ossimIpt (m_samples-1, m_lines-1); m_validRect.set_ul(ulIpt); m_validRect.set_lr(lrIpt); imageDataspace.close(); delete [] rowBuf; delete [] fill_value; return true; } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)< dataBuffer(bufSizeInBytes); // Get the extents. Assuming dimensions are same for lat lon dataset. ossimIpt ulIpt (m_validRect.ul()); ossimIpt lrIpt (m_validRect.lr()); const ossim_float32 nullpix = m_handler->getNullPixelValue(); ossim_float32 epsilon = (ossim_float32)0.1e-9; // For ossim::almostEqual() if (nullpix == 0.0) epsilon = 0; m_minValue.clear(); m_maxValue.clear(); ossimIrect clipRect (m_validRect.ul(), m_validRect.ur()); for (ossim_uint32 band=0; band(value, nullpix, epsilon)) continue; if (value > m_maxValue[band]) m_maxValue[band] = value; if (value < m_minValue[band]) m_minValue[band] = value; } } } //cout<<"ossimHdf5ImageDataset:"<<__LINE__<<"\n\tminValue="<= m_bands) return; // Shift rectangle by the sub image offse (if any) from the m_validRect. // NOTE: The rect coming in seems to be alreadyt in image space so no need to offset (OLK 09/2016) ossimIrect irect = rect;// + m_validRect.ul(); try { // Turn off the auto-printing when failure occurs so that we can // handle the errors appropriately // H5::Exception::dontPrint(); // Get dataspace of the dataset. H5::DataSpace imageDataSpace = m_dataset.getSpace(); // Number of dimensions of the input dataspace.: const ossim_int32 IN_DIM_COUNT = imageDataSpace.getSimpleExtentNdims(); // Native type: H5::DataType dataType = m_dataset.getDataType(); std::vector inputCount(IN_DIM_COUNT); std::vector inputOffset(IN_DIM_COUNT); if ( IN_DIM_COUNT == 2 ) { inputOffset[0] = irect.ul().y; inputOffset[1] = irect.ul().x; inputCount[0] = irect.height(); inputCount[1] = irect.width(); } else { inputOffset[0] = band; inputOffset[1] = irect.ul().y; inputOffset[2] = irect.ul().x; inputCount[0] = 1; inputCount[1] = irect.height(); inputCount[2] = irect.width(); } // Define hyperslab in the dataset; implicitly giving strike strike and block NULL. imageDataSpace.selectHyperslab( H5S_SELECT_SET, &inputCount.front(), &inputOffset.front() ); // Output dataspace dimensions. const ossim_int32 OUT_DIM_COUNT = 3; std::vector outputCount(OUT_DIM_COUNT); outputCount[0] = 1; // single band outputCount[1] = irect.height(); // lines outputCount[2] = irect.width(); // samples // Output dataspace offset. std::vector outputOffset(OUT_DIM_COUNT); outputOffset[0] = band; outputOffset[1] = 0; outputOffset[2] = 0; // Output dataspace. H5::DataSpace bufferDataSpace( OUT_DIM_COUNT, &outputCount.front()); bufferDataSpace.selectHyperslab( H5S_SELECT_SET, &outputCount.front(), &outputOffset.front() ); // Read data from file into the buffer. m_dataset.read( buffer, dataType, bufferDataSpace, imageDataSpace ); if ( m_endian ) { // If the m_endian pointer is initialized(not zero) swap the bytes. m_endian->swap( m_scalar, buffer, irect.area() ); } //#define NEVER #ifdef NEVER if (scale) { const ossim_float32 TOLERANCE = 0.1e-9; // For ossim::almostEqual() // Scale the data: #if 1 // Assumes float32 datatype: double gain = 1.0/( m_maxValue[band] - m_minValue[band] ); ossim_float32 null_value = m_handler->getNullPixelValue(band); ossim_float32 value; for (ossim_uint32 i=0; igetNullPixelValue(band); for (ossim_uint32 i=0; igetEntryString( m_scalar ) << "\nbands: " << m_bands << "\nlines: " << m_lines << "\nsamples: " << m_samples << "\nvalid rect: " << m_validRect << "\nswap_flage: " << (m_endian?"true":"false") << std::endl; } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)< #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const ossimTrace traceDebug("ossimHdf5ImageHandler:debug"); RTTI_DEF1(ossimHdf5ImageHandler, "ossimHdf5ImageHandler", ossimImageHandler) using namespace std; using namespace H5; static const string LAYER_KW = "layer"; ossimHdf5ImageHandler::ossimHdf5ImageHandler() : ossimImageHandler(), m_entries(), m_currentEntry(0), m_tile(0), m_mutex() { } ossimHdf5ImageHandler::~ossimHdf5ImageHandler() { if (isOpen()) { close(); } } void ossimHdf5ImageHandler::allocate() { m_mutex.lock(); m_tile = ossimImageDataFactory::instance()->create(this, this); m_tile->initialize(); m_mutex.unlock(); } ossimRefPtr ossimHdf5ImageHandler::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { if ( m_tile.valid() == false ) // First time through. { allocate(); } if (m_tile.valid()) { // Image rectangle must be set prior to calling getTile. m_mutex.lock(); m_tile->setImageRectangle(rect); m_mutex.unlock(); if ( getTile( m_tile.get(), resLevel ) == false ) { m_mutex.lock(); if (m_tile->getDataObjectStatus() != OSSIM_NULL) { m_tile->makeBlank(); } m_mutex.unlock(); } } return m_tile; } bool ossimHdf5ImageHandler::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; m_mutex.lock(); //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) ) { result->ref(); // Increment ref count. //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0. Method returns true on success, false // on error. //--- status = getOverviewTile(resLevel, result); if (!status) // Did not get an overview tile. { status = true; ossimIrect tile_rect = result->getImageRectangle(); if ( ! tile_rect.completely_within(getImageRectangle(0)) ) { // We won't fill totally so make blank first. result->makeBlank(); } if (getImageRectangle(0).intersects(tile_rect)) { // Make a clip rect. ossimIrect clipRect = tile_rect.clipToRect(getImageRectangle(0)); if (tile_rect.completely_within( clipRect) == false) { // Not filling whole tile so blank it out first. result->makeBlank(); } // Create buffer to hold the clip rect for a single band. ossim_uint32 clipRectSizeInBytes = clipRect.area() * ossim::scalarSizeInBytes( m_entries[m_currentEntry]->getScalarType() ); vector dataBuffer(clipRectSizeInBytes); // Get the data. for (ossim_uint32 band = 0; band < getNumberOfInputBands(); ++band) { // Hdf5 file to buffer: m_entries[m_currentEntry]->getTileBuf(&dataBuffer.front(), clipRect, band); #if 0 // Scan and fix non-standard null value: if ( m_entries[m_currentEntry]->getScalarType() == OSSIM_FLOAT32 ) { const ossim_float32 NP = getNullPixelValue(band); const ossim_uint32 COUNT = clipRect.area(); ossim_float32* float_buffer = (ossim_float32*)&dataBuffer.front(); for ( ossim_uint32 i = 0; i < COUNT; ++i ) { if ( float_buffer[i] < -999.0 ) float_buffer[i] = NP; } } #endif // Buffer to tile: result->loadBand((void*)&dataBuffer.front(), clipRect, band); } // Validate the tile, i.e. full, partial, empty. result->validate(); } else // No intersection... { result->makeBlank(); } } result->unref(); // Decrement ref count. } m_mutex.unlock(); return status; } ossimIrect ossimHdf5ImageHandler::getImageRectangle(ossim_uint32 reduced_res_level) const { return ossimIrect(0, 0, getNumberOfSamples(reduced_res_level) - 1, getNumberOfLines(reduced_res_level) - 1); } bool ossimHdf5ImageHandler::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimImageHandler::saveState(kwl, prefix); } bool ossimHdf5ImageHandler::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (ossimImageHandler::loadState(kwl, prefix)) { return open(); } return false; } void ossimHdf5ImageHandler::loadMetaData() { m_tile = 0; ossimImageHandler::loadMetaData(); } bool ossimHdf5ImageHandler::open() { static const char* M = "ossimHdf5ImageHandler::open(filename) -- "; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M <<" Entering..." << std::endl; // Start with a clean slate. if (isOpen()) { close(); } // Check for empty filename. if (theImageFile.empty()) return false; theImageFile = theImageFile.expand(); m_hdf5 = new ossimHdf5; if (!m_hdf5->open(theImageFile)) { if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M <<" Unable to open image Leaving..." << std::endl; m_hdf5 = 0; return false; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M <<" Opened Image..." << std::endl; vector datasetList; H5::Group root; m_hdf5->getRoot(root); m_hdf5->getNdimDatasets(root, datasetList, true); if ( datasetList.empty() ) { return false; m_hdf5->close(); m_hdf5 = 0; } // Filter for specified renderable datasets: if (m_renderableNames.size()) { std::vector::iterator dataset = datasetList.begin(); while (dataset != datasetList.end()) { bool found=false; ossimString dsName = dataset->getObjName(); std::vector::iterator name = m_renderableNames.begin(); while (name != m_renderableNames.end()) { if (dsName.contains(*name)) { found = true; break; } ++name; } if (!found) datasetList.erase(dataset); else ++dataset; } } #if 0 ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimHdf5ImageHandler:"<<__LINE__ << " DEBUG\nDataset names:\n"; for ( ossim_uint32 i = 0; i < datasetList.size(); ++i ) { ossimNotify(ossimNotifyLevel_DEBUG)<< "dataset[" << i << "]: " << datasetList[i].getObjName() << "\n"; } #endif if ( datasetList.empty() ) { m_hdf5 = 0; return false; } // Add the image dataset entries. std::vector::iterator dataset = datasetList.begin(); while (dataset != datasetList.end()) { ossimRefPtr oimgset = new ossimHdf5ImageDataset(this); oimgset->initialize(*dataset); m_entries.push_back(oimgset); ++dataset; } // Initialize the current entry to be 0: m_currentEntry = 999; // Forces init on change of index setCurrentEntry(0); // Establish a common geometry for all entries. TODO: Need to verify if this is a kosher thing // to do. It may be that multiple entries have different geometries associated. getImageGeometry(); if (!theGeometry.valid()) return false; #if 0 /* Please leave for debug. (drb) */ std::vector::const_iterator i = m_entries.begin(); while ( i != m_entries.end() ) { std::cout << (*i) << endl; ++i; } #endif if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M <<" Leaving..." << std::endl; return true; } ossim_uint32 ossimHdf5ImageHandler::getNumberOfLines(ossim_uint32 reduced_res_level) const { ossim_uint32 r = 0; if (reduced_res_level == 0) { if (m_currentEntry < m_entries.size()) r = m_entries[m_currentEntry]->getNumberOfLines(); } else if ( theOverview.valid() ) { r = theOverview->getNumberOfLines(reduced_res_level); } return r; } ossim_uint32 ossimHdf5ImageHandler::getNumberOfSamples(ossim_uint32 reduced_res_level) const { ossim_uint32 r = 0; if (reduced_res_level == 0) { if (m_currentEntry < m_entries.size()) r = m_entries[m_currentEntry]->getNumberOfSamples(); } else if ( theOverview.valid() ) { r = theOverview->getNumberOfSamples(reduced_res_level); } return r; } ossim_uint32 ossimHdf5ImageHandler::getImageTileWidth() const { return 0; // Not tiled format. } ossim_uint32 ossimHdf5ImageHandler::getImageTileHeight() const { return 0; // Not tiled format. } ossimString ossimHdf5ImageHandler::getShortName()const { return ossimString("ossim_hdf5_reader"); } ossimString ossimHdf5ImageHandler::getLongName()const { return ossimString("ossim hdf5 reader"); } ossimString ossimHdf5ImageHandler::getClassName()const { return ossimString("ossimHdf5ImageHandler"); } ossim_uint32 ossimHdf5ImageHandler::getNumberOfInputBands() const { ossim_uint32 result = 1; if ( m_currentEntry < m_entries.size() ) result = m_entries[m_currentEntry]->getNumberOfBands(); return result; } ossim_uint32 ossimHdf5ImageHandler::getNumberOfOutputBands()const { // Currently not band selectable. return getNumberOfInputBands(); } ossimScalarType ossimHdf5ImageHandler::getOutputScalarType() const { ossimScalarType result = OSSIM_SCALAR_UNKNOWN; if ( m_currentEntry < m_entries.size() ) { result = m_entries[m_currentEntry]->getScalarType(); } return result; } bool ossimHdf5ImageHandler::isOpen()const { return ( m_hdf5.valid() && m_entries.size() && (m_currentEntry < m_entries.size())); } void ossimHdf5ImageHandler::close() { // Close the datasets. m_entries.clear(); // Then the file. if ( m_hdf5.valid() ) m_hdf5 = 0; // ossimRefPtr so assign to 0(unreferencing) will handle memory. m_tile = 0; ossimImageHandler::close(); } ossim_uint32 ossimHdf5ImageHandler::getNumberOfEntries() const { return (ossim_uint32)m_entries.size(); } void ossimHdf5ImageHandler::getEntryNames(std::vector& entryNames) const { entryNames.clear(); for (ossim_uint32 i=0; igetName()); } } void ossimHdf5ImageHandler::getEntryList(std::vector& entryList) const { const ossim_uint32 SIZE = m_entries.size(); entryList.resize( SIZE ); for ( ossim_uint32 i = 0; i < SIZE; ++i ) { entryList[i] = i; } } bool ossimHdf5ImageHandler::setCurrentEntry( ossim_uint32 entryIdx) { bool result = true; if (m_currentEntry != entryIdx) { // Entries always start at zero and increment sequentially.. if ( entryIdx < m_entries.size() ) { theOverviewFile.clear(); m_currentEntry = entryIdx; m_tile = 0; ossimIrect validRect = m_entries[entryIdx]->getValidImageRect(); theValidImageVertices.clear(); theValidImageVertices.push_back(validRect.ul()); theValidImageVertices.push_back(validRect.ur()); theValidImageVertices.push_back(validRect.lr()); theValidImageVertices.push_back(validRect.ll()); if ( isOpen() ) completeOpen(); } else { result = false; // Entry index out of range. } } return result; } ossim_uint32 ossimHdf5ImageHandler::getCurrentEntry() const { return m_currentEntry; } ossimRefPtr ossimHdf5ImageHandler::getCurrentDataset() { if ( m_currentEntry >= m_entries.size() ) return 0; return m_entries[m_currentEntry]; } double ossimHdf5ImageHandler::getNullPixelValue( ossim_uint32 band ) const { return ossimImageHandler::getNullPixelValue( band ); } double ossimHdf5ImageHandler::getMaxPixelValue( ossim_uint32 band ) const { if ( m_currentEntry >= m_entries.size() ) { if(m_entries[m_currentEntry]->isMaxPixelSet()) { return m_entries[m_currentEntry]->getMaxPixelValue(band); } } return ossimImageHandler::getMaxPixelValue( band ); } double ossimHdf5ImageHandler::getMinPixelValue( ossim_uint32 band ) const { if ( m_currentEntry >= m_entries.size() ) { if(m_entries[m_currentEntry]->isMinPixelSet()) { return m_entries[m_currentEntry]->getMinPixelValue(band); } } return ossimImageHandler::getMinPixelValue( band ); } void ossimHdf5ImageHandler::setProperty(ossimRefPtr property) { if ( !property.valid() ) return; if ( property->getName().string() == LAYER_KW ) { ossimString s; property->valueToString(s); ossim_uint32 SIZE = (ossim_uint32)m_entries.size(); for ( ossim_uint32 i = 0; i < SIZE; ++i ) { if ( m_entries[i]->getName() == s.string() ) { setCurrentEntry( i ); } } } else { ossimImageHandler::setProperty(property); } } ossimRefPtr ossimHdf5ImageHandler::getProperty(const ossimString& name)const { ossimRefPtr prop = 0; if ( name.string() == LAYER_KW ) { if ( m_currentEntry < m_entries.size() ) { ossimString value = m_entries[m_currentEntry]->getName(); prop = new ossimStringProperty(name, value); } } else { prop = ossimImageHandler::getProperty(name); } return prop; } void ossimHdf5ImageHandler::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back( ossimString("layer") ); ossimImageHandler::getPropertyNames(propertyNames); } ossim-Miami-2.9.1/src/hdf5/ossimHdf5Info.cpp000066400000000000000000001163471352751253100205250ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: HDF5 Info class. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include using namespace std; using namespace H5; ossimHdf5Info::ossimHdf5Info() : ossimInfoBase() { } ossimHdf5Info::ossimHdf5Info(ossimHdf5* hdf5) : ossimInfoBase(), m_hdf5 (hdf5) { } ossimHdf5Info::~ossimHdf5Info() { m_hdf5 = 0; } bool ossimHdf5Info::open(const ossimFilename& file) { m_hdf5 = new ossimHdf5; if (!m_hdf5->open(file)) { m_hdf5 = 0; return false; } return true; } // Top level print from root ostream& ossimHdf5Info::print(ostream& out) const { if (!m_hdf5.valid()) { out<<"ossimHdf5Info: No HDF5 file has been opened! Nothing to print."<getRoot(root)) return out; print(out, root, ""); out< groups; if (!m_hdf5->getChildGroups(group, groups)) return out; if (!groups.empty()) { for (ossim_uint32 i=0; i attributes; if (!m_hdf5->getAttributes(obj, attributes)) return out; if (!attributes.empty()) { for (ossim_uint32 i=0; i datasets; if (!m_hdf5->getDatasets(group, datasets)) return out; if (!datasets.empty()) { for (ossim_uint32 i=0; i 0) out<<" x "; out<getByteOrder(&attr); ossimEndian endian; bool swapOrder = (order!=ossim::byteOrder()); H5T_class_t class_type = attr.getDataType().getClass(); ossim_uint32 dataSize = attr.getDataType().getSize(); switch (class_type) { case H5T_STRING: attr.read(attr.getDataType(), str_value); out <<" = "<(buf); strValue = ossimString::toString(*intValue).string(); break; } case H5T_SGN_2: { ossim_int8* intValue=0; intValue = reinterpret_cast(buf); strValue = ossimString::toString(*intValue).string(); break; } default: { break; } } break; } case 2: // 2 byte integer { switch(signType) { case H5T_SGN_NONE: // unsigned { ossim_uint16* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); strValue = ossimString::toString(*intValue).string(); break; } case H5T_SGN_2: // Signed { ossim_int16* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); strValue = ossimString::toString(*intValue).string(); break; } default: { break; } } break; } case 4: // 4 byte integer { switch(signType) { case H5T_SGN_NONE: { ossim_uint32* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); strValue = ossimString::toString(*intValue).string(); break; } case H5T_SGN_2: { ossim_int32* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); strValue = ossimString::toString(*intValue).string(); break; } default: { break; } } break; } case 8: // 8 byte integer { switch(signType) { case H5T_SGN_NONE: { ossim_uint64* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); strValue = ossimString::toString(*intValue).string(); break; } case H5T_SGN_2: { ossim_int64* intValue=0; intValue = reinterpret_cast(buf); if (swapOrder) endian.swap(*intValue); strValue = ossimString::toString(*intValue).string(); break; } } break; } } out <<" = "<(buf); if (swapOrder) endian.swap(*float_value); strValue = ossimString::toString(*float_value).string(); break; } case 8: { ossim_float64* float_value=0; float_value = reinterpret_cast(buf); if (swapOrder) endian.swap(*float_value); strValue = ossimString::toString(*float_value).string(); break; } } out <<" = "<getRoot(root)) return false; ossim_uint32 recurseCount = 0; dumpGroup(root, prefix, recurseCount); // Dump daset names: vector datasets; vector datasetNames; m_hdf5->getDatasets(root, datasets, true ); ostringstream value; value << "("; for (ossim_uint32 i=0; igetRoot(root)) { H5::DataSet* dataset = m_hdf5->findDatasetByName(datasetName, &root, true); if(dataset) { try{ dumpDataset(*dataset, ""); returnValue = true; kwl = m_kwl; } catch(...) { } delete dataset; } } return returnValue; } bool ossimHdf5Info::getKeywordlistGroup(ossimKeywordlist& kwl, const std::string& groupName) const { bool returnValue = false; m_kwl.clear(); Group root; ossim_uint32 recurseCount = 0; if (m_hdf5->getRoot(root)) { H5::Group* group = m_hdf5->findGroupByName(groupName, &root, true); if(group) { try{ dumpGroup(*group, "", recurseCount); returnValue = true; kwl = m_kwl; } catch(...) { } delete group; } } return returnValue; } void ossimHdf5Info::dumpGroup(const Group& group, const string& prefix, ossim_uint32& recursedCount) const { ++recursedCount; try { ossimString groupPrefix = getObjectPrefix(prefix, group.getObjName()); m_kwl.addPair(groupPrefix, string("type"), string("Group")); // Dump all attributes for this group: dumpAttributes(group, groupPrefix); // Dump all datasets under this group: vector datasets; m_hdf5->getDatasets(group, datasets); for (ossim_uint32 i=0; i childGroups; m_hdf5->getChildGroups(group, childGroups, false); for (ossim_uint32 i=0; i items; fullPathName.split(items, "/"); ossimString objectName (items.back()); ostringstream objectPrefix; if (objectName.empty()) objectPrefix << prefix; else objectPrefix << prefix << objectName<<"."; return objectPrefix.str(); } void ossimHdf5Info::dumpAttributes(const H5Object& obj, const std::string& prefix) const { try { vector attrList; m_hdf5->getAttributes(obj, attrList); for ( ossim_uint32 i = 0; i < attrList.size(); ++i ) { ostringstream attrPrefix; attrPrefix << prefix;//<<"attribute"<getByteOrder(&attr); ossimEndian endian; // bool swapOrder = (order!=ossim::byteOrder()); H5T_class_t class_type = attr.getDataType().getClass(); // ossim_uint32 dataSize = attr.getDataType().getSize(); switch (class_type) { case H5T_STRING: { attr.read(attr.getDataType(), strValue); break; } case H5T_INTEGER: { H5::DataType dataType = attr.getDataType(); H5::IntType* dataTypePtr = (H5::IntType*)(&dataType); attr.read(attr.getDataType(), buf); ossimHdf5::intTypeToString(strValue, *dataTypePtr, buf); break; } case H5T_FLOAT: { H5::DataType dataType = attr.getDataType(); H5::FloatType* dataTypePtr = (H5::FloatType*)(&dataType); attr.read(attr.getDataType(), buf); ossimHdf5::floatTypeToString(strValue, *dataTypePtr, buf); break; } case H5T_COMPOUND: { //H5::DataType dataType = attr.getDataType(); //H5::FloatType* dataTypePtr = (H5::FloatType*)(&dataType); //H5::CompType compType(dataset); //dumpCompoundTypeInfo(compType, datasetPrefix); //dumpCompound(dataset, compType, datasetPrefix); // ostringstream tempOut; // tempOut << "(" <<"H5T_COMPOUND not a handled type)"; // strValue = tempOut.str(); } default: { ostringstream tempOut; tempOut << "(" << ossimHdf5::getDatatypeClassType(class_type) <<" not a handled type)"; strValue = tempOut.str(); } } ossimString attrKey (getObjectPrefix(prefix, attr.getName())); m_kwl.addPair(prefix, attr.getName(), strValue); } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)<getDatatypeClassType(type_class)); // Dump specific datatypes: switch(type_class) { case H5T_COMPOUND: { H5::CompType compType(dataset); dumpCompoundTypeInfo(compType, datasetPrefix); dumpCompound(dataset, compType, datasetPrefix); break; } case H5T_ENUM: { H5::EnumType enumType (dataset); dumpEnumTypeInfo(enumType, datasetPrefix); break; } case H5T_ARRAY: { H5::ArrayType arrayType (dataset.getId()); dumpArrayTypeInfo(arrayType, datasetPrefix); break; } case H5T_INTEGER: case H5T_FLOAT: { ossimByteOrder byteOrder = m_hdf5->getByteOrder( &dataset ); dumpNumericalTypeInfo(dataset, byteOrder, datasetPrefix); break; } default: { m_kwl.addPair(datasetPrefix, string(ossimKeywordNames::SCALAR_TYPE_KW), string("OSSIM_SCALAR_UNKNOWN")); break; } } // Dump Extents: vector extents; m_hdf5->getExtents( dataset, extents ); ostringstream value; if(!extents.empty()) { value < compData(size*nElements); dataset.read((void*)&compData.front(),compType); char* compDataPtr = &compData.front(); if(dimensions!=1) { return; } for(;elementIdx\n"; break; } case H5T_OPAQUE: { // out << newPrefix << ": \n"; break; } case H5T_REFERENCE: { // out << newPrefix << ": \n"; break; } case H5T_ENUM: { H5::EnumType dataType = compound.getMemberEnumType(memberIdx); dumpEnumTypeInfo(dataType, newPrefix); // ossim_hdf5::printEnumType(dataset, dataType, newPrefix, out); break; } case H5T_VLEN: { // out << newPrefix << ": \n"; break; } case H5T_ARRAY: { H5::ArrayType dataType = compound.getMemberArrayType(memberIdx); dumpArrayType(dataType, &compDataPtr[memberOffset], newPrefix); break; } case H5T_NO_CLASS: default: { break; } } } compDataPtr+=size; } } void ossimHdf5Info::dumpCompoundTypeInfo(const H5::CompType& compound, const std::string& prefix) const { #if 0 try { // H5::CompType compound(dataset); ossim_int32 nMembers = compound.getNmembers(); ossim_int32 memberIdx = 0; ostringstream typePrefix; typePrefix << prefix << "compound_type."; m_kwl.addPair(prefix, string("type"), string("compound")); for(memberIdx=0;memberIdx < nMembers;++memberIdx) { H5::DataType dataType (compound.getMemberDataType(memberIdx)); H5std_string memberName (compound.getMemberName(memberIdx)); ostringstream newPrefix; newPrefix<getDatatypeClassType(class_type)); switch(class_type) { case H5T_INTEGER: { H5::IntType dataType = compound.getMemberIntType(memberIdx); //dumpIntType(dataset, dataType, &compDataPtr[memberOffset], newPrefix, out); break; } case H5T_FLOAT: { H5::FloatType dataType = compound.getMemberFloatType(memberIdx); break; } case H5T_ENUM: { H5::EnumType enudataType = compound.getMemberEnumType(memberIdx); dumpEnumTypeInfo(enudataType, newPrefix.str()); break; } case H5T_ARRAY: { H5::ArrayType arrdataType = compound.getMemberArrayType(memberIdx); dumpArrayTypeInfo(arrdataType, newPrefix.str()); break; } default: { break; } } } } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)< dims(arrayNdims); arrayType.getArrayDims(&dims.front()); ostringstream kwl_value; for(ossim_uint32 i=0;igetScalarType(dataset); ossimString sct = ossimScalarTypeLut::instance()->getEntryString(stype); m_kwl.addPair(prefix, string(ossimKeywordNames::SCALAR_TYPE_KW), sct.string()); std::string byteOrderString = "little_endian"; if ( byteOrder == OSSIM_BIG_ENDIAN ) byteOrderString = "big_endian"; m_kwl.addPair(prefix, string(ossimKeywordNames::BYTE_ORDER_KW), byteOrderString); } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)<getByteOrder(dataType); // ossimEndian endian; // bool swapOrder = (order!=ossim::byteOrder()); H5::DataType superType = dataType.getSuper(); //out << prefix<<".class_type: " << ossim_hdf5::getDatatypeClassType( dataType.getClass() ) << "\n"; if(arrayNdims) { std::vector dims(arrayNdims); dataType.getArrayDims(&dims.front()); if(dims.size() > 0) { std::stringstream dimOut; ossimString dimString; ossim_uint32 idx = 1; ossim_uint32 nArrayElements = dims[0]; std::copy(dims.begin(), --dims.end(), std::ostream_iterator(dimOut,",")); for(;idx"; m_kwl.addPair(newPrefix, out.str()); m_kwl.addPair(prefix+".array_type", "H5T_STRING"); break; } case H5T_INTEGER: { ostringstream out; H5::IntType* dataTypePtr = (H5::IntType*)(&superType); ossimByteOrder order = m_hdf5->getByteOrder(*dataTypePtr); ossimEndian endian; bool swapOrder = (order!=ossim::byteOrder()); ossimString newPrefix = prefix+".values"; out<<"("; for(idx=0;idxgetByteOrder(*dataTypePtr); ossimEndian endian; bool swapOrder = (order!=ossim::byteOrder()); //out<getByteOrder(&dataset); ossimEndian endian; bool swapOrder = (order!=ossim::byteOrder()); ossimString valueStr; ossimScalarType scalarType = m_hdf5->getScalarType(dataset); switch(scalarType) { case OSSIM_UINT8: { ossim_uint8 value = *reinterpret_cast(dataPtr); valueStr = ossimString::toString(value).string(); break; } case OSSIM_SINT8: { ossim_int8 value = *reinterpret_cast(dataPtr); valueStr = ossimString::toString(value); break; } case OSSIM_UINT16: { ossim_uint16 value = *reinterpret_cast(dataPtr); if(swapOrder) endian.swap(value); valueStr = ossimString::toString(value); break; } case OSSIM_SINT16: { ossim_int16 value = *reinterpret_cast(dataPtr); if(swapOrder) endian.swap(value); valueStr = ossimString::toString(value); break; } case OSSIM_UINT32: { ossim_uint32 value = *reinterpret_cast(dataPtr); if(swapOrder) endian.swap(value); valueStr = ossimString::toString(value); break; } case OSSIM_SINT32: { ossim_int32 value = *reinterpret_cast(dataPtr); if(swapOrder) endian.swap(value); valueStr = ossimString::toString(value); break; } case OSSIM_UINT64: { ossim_uint64 value = *reinterpret_cast(dataPtr); if(swapOrder) endian.swap(value); valueStr = ossimString::toString(value); break; } case OSSIM_FLOAT32: { ossim_float32 value = *reinterpret_cast(dataPtr); if(swapOrder) endian.swap(value); valueStr = ossimString::toString(value); break; } case OSSIM_FLOAT64: { ossim_float64 value = *reinterpret_cast(dataPtr); if(swapOrder) endian.swap(value); valueStr = ossimString::toString(value); break; } default: { valueStr = ""; break; } } m_kwl.addPair(prefix, string("value"), valueStr.string()); } catch( const H5::Exception& e ) { ossimNotify(ossimNotifyLevel_WARN)< #include #include #include #include #include ossimHdf5ProjectionFactory* ossimHdf5ProjectionFactory::instance() { static ossimHdf5ProjectionFactory* factoryInstance = new ossimHdf5ProjectionFactory(); return factoryInstance; } ossimProjection* ossimHdf5ProjectionFactory::createProjection(const ossimFilename& filename, ossim_uint32 entryIdx)const { // Try external geom file first: ossimRefPtr projection = createProjectionFromGeometryFile(filename, entryIdx); if (!projection.valid()) { // Try internal grid model. This may be specific to VIIRS. In any case, it is not very // robust as this model simply looks for "Latitude" and "Longitude" dataset names, ignoring // multiple entries with potentially different geometries for each. Eventually should // provide for the specification of specific dataset names or at least path to parent group. // This is not trivial with only an entry index available. (OLK 08/16) ossimRefPtr hdf5 = new ossimHdf5; if (hdf5->open(filename)) { ossimRefPtr hdf5_grid = new ossimHdf5GridModel; hdf5_grid->initialize(hdf5.get()); } } // Must release or pointer will self destruct when it goes out of scope. return projection.release(); } ossimProjection* ossimHdf5ProjectionFactory::createProjection(const ossimString& /*name*/) const { return 0; } ossimProjection* ossimHdf5ProjectionFactory::createProjection(const ossimKeywordlist& kwl, const char* prefix) const { ossimRefPtr result; ossimString value = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if ((value != "ossimHdf5GridModel") && (value != "ossimH5GridModel")) return 0; // The HDF5 grid model is just an implementation of the coarse grid model, but the geom file // is purely the latter, so trick the KWL to properly load an OCG model: ossimKeywordlist new_kwl (kwl); new_kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimCoarseGridModel", true); result = new ossimHdf5GridModel; if( !result->loadState(new_kwl, prefix) ) result = 0; return result.release(); } ossimObject* ossimHdf5ProjectionFactory::createObject( const ossimString& typeName)const { return createProjection(typeName); } ossimObject* ossimHdf5ProjectionFactory::createObject( const ossimKeywordlist& kwl, const char* prefix)const { return createProjection(kwl, prefix); } void ossimHdf5ProjectionFactory::getTypeNameList(std::vector& typeList)const { typeList.push_back(ossimString("ossimHdf5GridModel")); } ossimHdf5ProjectionFactory::ossimHdf5ProjectionFactory() { } ossim-Miami-2.9.1/src/hdf5/ossimHdf5Tool.cpp000066400000000000000000000265521352751253100205450ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using namespace H5; const char* ossimHdf5Tool::DESCRIPTION = "Utility for parsing and extracting HDF5 image data."; static const string IMAGE_DATASET_KW = "image_dataset"; static const string GEOM_DATASET_KW = "geom_dataset"; static const string LIST_DATASETS_KW = "list_datasets"; static const string LIST_NDIMS_KW = "list_ndims"; static const string DUMP_INFO_KW = "dump_info"; static const string DUMP_KWL_KW = "dump_kwl"; ossimHdf5Tool::ossimHdf5Tool() : m_dumpInfo (false), m_dumpKwl (false), m_listDatasets (false), m_listNdimDatasets (false) { } ossimHdf5Tool::~ossimHdf5Tool() { } void ossimHdf5Tool::setUsage(ossimArgumentParser& ap) { // Add options. ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " hdf5 [options] [--i ] [-o ]"; au->setCommandLineUsage(usageString); // Set the command line options: au->setDescription(DESCRIPTION); au->addCommandLineOption("--geom-dataset","" "Full HDF5-internal path to geometry dataset to use for image. "); au->addCommandLineOption("--image-dataset","" "Full HDF5-internal path to pixel dataset to extract. "); au->addCommandLineOption("--list-datasets", "Lists all datasets with extents. "); au->addCommandLineOption("--list-ndims", "Lists all datasets with extents that are of rank 2 or higher."); au->addCommandLineOption("--geom", "[]\n" "Dumps the geometry keyword-list to the specified file or the console if no filename specified."); au->addCommandLineOption("--info", "Outputs human-readable dump of all objects in the file"); au->addCommandLineOption("--kwl", "Outputs keywordlist dump of all objects in the file"); // Base class has its own: ossimChipProcTool::setUsage(ap); } bool ossimHdf5Tool::initialize(ossimArgumentParser& ap) { if (!ossimChipProcTool::initialize(ap)) return false; if (m_helpRequested) return true; std::string tempString1; ossimArgumentParser::ossimParameter stringParam1(tempString1); const string TRUE_STR ("true"); if ( ap.read("--geom-dataset", stringParam1) || ap.read("--gdata", stringParam1)) m_kwl.addPair(GEOM_DATASET_KW, tempString1); if ( ap.read("--geom", stringParam1)) m_kwl.addPair(ossimKeywordNames::GEOM_FILE_KW, tempString1); if ( ap.read("--image-dataset", stringParam1) || ap.read("--idata", stringParam1)) m_kwl.addPair(IMAGE_DATASET_KW, tempString1); if ( ap.read("--list-datasets")) m_kwl.addPair(LIST_DATASETS_KW, TRUE_STR); if ( ap.read("--list-ndims") ) m_kwl.addPair(LIST_NDIMS_KW, TRUE_STR); if ( ap.read("--info") ) m_kwl.addPair(DUMP_INFO_KW, TRUE_STR); if ( ap.read("--kwl") ) m_kwl.addPair(DUMP_KWL_KW, TRUE_STR); ap.reportRemainingOptionsAsUnrecognized(); if ( ap.argc() > 1 ) { // If input file already specified, then remaining arg is output file: if (m_kwl.numberOf(ossimKeywordNames::IMAGE_FILE_KW)) m_kwl.add( ossimKeywordNames::OUTPUT_FILE_KW, ap[1]); else { // No input specified, so remaining args contains the input filename: if (ap.argc() == 2) m_kwl.add( ossimKeywordNames::IMAGE_FILE_KW, ap[1]); else { m_kwl.add( ossimKeywordNames::IMAGE_FILE_KW, ap[1]); m_kwl.add( ossimKeywordNames::OUTPUT_FILE_KW, ap[2]); } } } initialize(m_kwl); return true; } void ossimHdf5Tool::initialize(const ossimKeywordlist& kwl) { ostringstream xmsg; // Don't copy KWL if member KWL passed in: if (&kwl != &m_kwl) { // Start with clean options keyword list. m_kwl.clear(); m_kwl.addList( kwl, true ); } m_imageDataPath = m_kwl.findKey(IMAGE_DATASET_KW); m_geomDataPath = m_kwl.findKey(GEOM_DATASET_KW); m_geomFilename = m_kwl.findKey(ossimKeywordNames::GEOM_FILE_KW); m_kwl.getBoolKeywordValue(m_listDatasets, LIST_DATASETS_KW.c_str()); m_kwl.getBoolKeywordValue(m_listNdimDatasets, LIST_NDIMS_KW.c_str()); m_kwl.getBoolKeywordValue(m_dumpInfo, DUMP_INFO_KW.c_str()); m_kwl.getBoolKeywordValue(m_dumpKwl, DUMP_KWL_KW.c_str()); ossimFilename hdfFile = m_kwl.find(ossimKeywordNames::IMAGE_FILE_KW); if (hdfFile.empty() ) { xmsg<<"ERROR: ossimHdf5Tool:"<<__LINE__<<" -- No input filename was specified."; throw ossimException(xmsg.str()); } m_hdf5 = new ossimHdf5; if (!m_hdf5->open(hdfFile)) { xmsg<<"ERROR: ossimHdf5Tool:"<<__LINE__<<" -- Could not open <"< as an HDF5 file."; throw ossimException(xmsg.str()); } if (m_listDatasets || m_listNdimDatasets || m_dumpInfo || m_dumpKwl) return; // Only if an output file is specified, do we need the services of ossimChipProcTool: m_productFilename = m_kwl.findKey( std::string(ossimKeywordNames::OUTPUT_FILE_KW) ); ossimChipProcTool::initialize(kwl); if (m_imgLayers.empty()) { xmsg<<"ERROR: ossimHdf5Tool:"<<__LINE__<<" -- No input chain available. Make sure an HDF5" " input file name is specified"; throw ossimException(xmsg.str()); } // If dataset specified, then expect product filename: if (!m_imageDataPath.empty() && m_productFilename.empty()) { m_productFilename = hdfFile; m_productFilename.setExtension("tif"); } } void ossimHdf5Tool::loadImageFiles() { ostringstream errMsg; // Special handling needed for loading HDF5 file: ossimString value = m_kwl.find(ossimKeywordNames::IMAGE_FILE_KW); if (value.empty()) { errMsg<<"ERROR: ossimHdf5Tool:"<<__LINE__<<" -- No input HDF5 file name specified."; throw ossimException(errMsg.str()); } ossimFilename imageFilename (value); // If explicit image data paths are specified, open the HDF5 handler directly, otherwise assume // there is a plugin factory that will figure it out: ossimRefPtr handler; if (m_imageDataPath.empty()) { // Use the factory system to instantiate handler, then verify it is HDF5: ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(imageFilename); handler = dynamic_cast(ih.get()); if (!handler.valid()) { errMsg<<"ERROR: ossimHdf5Tool:"<<__LINE__<<" -- No HDF5 dataset paths were specified" " and no default HDF5-derived handlers were found. Don't know what dataset to " "extract. Use \"--image-dataset\" option to specify."; throw ossimException(errMsg.str()); } } else { // Use explicitly-provided dataset names: handler = new ossimHdf5ImageHandler; handler->addRenderable(m_imageDataPath); handler->setFilename(ossimFilename(value)); if (!handler->open()) { errMsg<<"ERROR: ossimHdf5Tool:"<<__LINE__<<" -- Could not open <"< as an HDF5 file."; throw ossimException(errMsg.str()); } } // Init chain with handler: ossimRefPtr chain = new ossimSingleImageChain; chain->addLast(handler.get()); // Set up the remapper: if ( ( m_productScalarType != OSSIM_SCALAR_UNKNOWN) && ( m_procChain->getOutputScalarType() != m_productScalarType ) ) { ossimRefPtr remapper = new ossimScalarRemapper(); remapper->setOutputScalarType(m_productScalarType); chain->add(remapper.get()); } // Add geo polygon cutter if specifried: ossimString param = m_kwl.findKey(string("clip_poly_lat_lon")); if (!param.empty()) { std::vector points; ossim::toVector(points, param); if(points.size() >= 3) { ossimGeoPolygon polygon(points); chain->addGeoPolyCutterPolygon(polygon); } } chain->initialize(); m_imgLayers.push_back(chain); } void ossimHdf5Tool::initProcessingChain() { ossimRefPtr input_mosaic = combineLayers(m_imgLayers); m_procChain->add(input_mosaic.get()); ossimRefPtr sf = new ossimShiftFilter(); sf->setNullPixelValue( 0.0 ); sf->setMinPixelValue( 1.0 ); sf->setMaxPixelValue( 65535.0 ); m_procChain->add( sf.get() ); // Cast it to uint16: ossimRefPtr cf = new ossimCastTileSourceFilter(0, OSSIM_UINT16 ); m_procChain->add( cf.get() ); } bool ossimHdf5Tool::execute() { // Need to fix output to tiff ostringstream errMsg; if (!m_hdf5.valid()) return false; if (m_listDatasets || m_listNdimDatasets || m_dumpInfo || m_dumpKwl) { ossimHdf5Info info (m_hdf5.get()); if (m_dumpKwl) { ossimKeywordlist kwl; info.getKeywordlist(kwl); kwl.print(cout); } if (m_dumpInfo) { info.print(cout); } Group root; m_hdf5->getRoot(root); vector datasets; if (m_listDatasets) m_hdf5->getDatasets(root, datasets, true); else if (m_listNdimDatasets) m_hdf5->getNdimDatasets(root, datasets, true); for (ossim_uint32 i=0; i geom = m_imgLayers[0]->getImageGeometry(); if (geom.valid()) { ossimRefPtr proj = geom->getProjection(); if ( proj.valid() ) { ossimFilename geomFile = m_productFilename.noExtension(); geomFile.string() += ".geom"; // Assume it is coarse grid (case for VIIRS): ossimRefPtr cg = dynamic_cast( proj.get() ); if ( cg.valid() ) { // this saves geom file as well cg->saveCoarseGrid( geomFile ); cout << "Wrote file: " << geomFile << endl; } else { // Save the state to keyword list. ossimKeywordlist geomKwl; geom->saveState(geomKwl); // Write to file: geomKwl.write( geomFile.c_str() ); cout << "Wrote file: " << geomFile << endl; } } } return true; } ossim-Miami-2.9.1/src/hdf5/ossimViirsHandler.cpp000066400000000000000000000032601352751253100215020ustar00rootroot00000000000000/***************************************************************************** * * * O S S I M * * Open Source, Geospatial Image Processing Project * * License: MIT, see LICENSE at the top-level directory * * * *****************************************************************************/ #include #include static const ossimString VIIRS_DATASET ("/All_Data/VIIRS-DNB-SDR_All/Radiance"); static const ossimString VIIRS_GEOMETRY ("/All_Data/VIIRS-DNB-GEO_All"); ossimViirsHandler::ossimViirsHandler() { m_renderableNames.push_back(VIIRS_DATASET); } ossimRefPtr ossimViirsHandler::getImageGeometry() { if (theGeometry.valid()) return theGeometry; theGeometry = getExternalImageGeometry(); if (!theGeometry.valid() && isOpen()) { theGeometry = new ossimImageGeometry(); // Attempt to create an OSSIM coarse grid model from HDF5 lat lon grids: ossimRefPtr hdf5GridModel = new ossimHdf5GridModel; if ( hdf5GridModel->initialize(m_hdf5.get(), VIIRS_GEOMETRY) ) { theGeometry->setProjection(hdf5GridModel.get()); initImageParameters( theGeometry.get() ); } else theGeometry = 0; } return theGeometry; } double ossimViirsHandler::getNullPixelValue(ossim_uint32 /*band*/) const { // NPP VIIRS data has null of "-999.3". return -999.3; } ossim-Miami-2.9.1/src/imaging/000077500000000000000000000000001352751253100161155ustar00rootroot00000000000000ossim-Miami-2.9.1/src/imaging/ossim3x3ConvolutionFilter.cpp000066400000000000000000000463261352751253100237320ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossim3x3ConvolutionFilter.cpp 12956 2008-06-02 01:38:50Z dburken $ #include #include #include #include #include RTTI_DEF1(ossim3x3ConvolutionFilter, "ossim3x3ConvolutionFilter", ossimImageSourceFilter); using namespace std; ossim3x3ConvolutionFilter::ossim3x3ConvolutionFilter(ossimObject* owner) :ossimImageSourceFilter(owner), theTile(NULL), theNullPixValue(0), theMinPixValue(0), theMaxPixValue(0) { theKernel[0][0] = 0.0; theKernel[0][1] = 0.0; theKernel[0][2] = 0.0; theKernel[1][0] = 0.0; theKernel[1][1] = 1.0; theKernel[1][2] = 0.0; theKernel[2][0] = 0.0; theKernel[2][1] = 0.0; theKernel[2][2] = 0.0; } ossim3x3ConvolutionFilter::~ossim3x3ConvolutionFilter() { } ossimRefPtr ossim3x3ConvolutionFilter::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return theTile; } if(!isSourceEnabled()) { return theInputConnection->getTile(tileRect, resLevel); } //--- // We have a 3x3 matrix so stretch the rect out to cover // the required pixels. We only need 1 pixel to the left // and right of the center pixel. //--- ossimIrect newRect(ossimIpt(tileRect.ul().x - 1, tileRect.ul().y - 1), ossimIpt(tileRect.lr().x + 1, tileRect.lr().y + 1)); ossimRefPtr data = theInputConnection->getTile(newRect, resLevel); if(!data.valid() || !data->getBuf()) { return data; } // First time through or after an initialize()... if (!theTile.valid()) { allocate(); if (!theTile.valid()) // Should never happen! { return data; } } // First time through, after an initialize() or a setKernel()... if (!theNullPixValue.size()) { computeNullMinMax(); if (!theNullPixValue.size()) // Should never happen! { return data; } } theTile->setImageRectangle(tileRect); theTile->makeBlank(); switch(data->getScalarType()) { case OSSIM_UCHAR: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } case OSSIM_SSHORT16: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossim3x3ConvolutionFilter::getTile WARNING:\n" << "Scalar type = " << theTile->getScalarType() << " Not supported by ossim3x3ConvolutionFilter" << endl; break; } } theTile->validate(); return theTile; } template void ossim3x3ConvolutionFilter::convolvePartial( T, ossimRefPtr inputData, ossimRefPtr outputData) { // let's set up some temporary variables so we don't // have to call the functions in loops. Iknow that compilers // typically optimize this out but if we are in debug mode // with no optimization it will still run fast // double sum = 0.0; ossim_int32 inputW = (ossim_int32)inputData->getWidth(); ossim_int32 outputW = (ossim_int32)outputData->getWidth(); ossim_int32 outputH = (ossim_int32)outputData->getHeight(); ossim_int32 numberOfBands = (ossim_int32)inputData->getNumberOfBands(); ossimIpt outputOrigin = outputData->getOrigin(); ossimIpt inputOrigin = inputData->getOrigin(); ossim_int32 startInputOffset = std::abs(outputOrigin.y - inputOrigin.y)* inputW + std::abs(outputOrigin.x - inputOrigin.x); ossim_int32 ulKernelStart = -inputW - 1; ossim_int32 leftKernelStart = -1; ossim_int32 llKernelStart = inputW - 1; T* ulKernelStartBuf = NULL; T* leftKernelStartBuf = NULL; T* llKernelStartBuf = NULL; for(ossim_int32 band = 0; band < numberOfBands; ++band) { T* inputBuf = static_cast(inputData->getBuf(band))+startInputOffset; T* outputBuf = static_cast(outputData->getBuf(band)); T maxPix = static_cast(getMaxPixelValue(band)); T minPix = static_cast(getMinPixelValue(band)); T nullPix = static_cast(inputData->getNullPix(band)); T oNullPix = static_cast(getNullPixelValue(band)); if(inputBuf&&outputBuf) { for(ossim_int32 row = 0; row < outputW; ++row) { ossim_int32 rowOffset = inputW*row; ulKernelStartBuf = inputBuf + (rowOffset + ulKernelStart); leftKernelStartBuf = inputBuf + (rowOffset + leftKernelStart); llKernelStartBuf = inputBuf + (rowOffset + llKernelStart); for(ossim_int32 col = 0; col < outputH; ++col) { if((ulKernelStartBuf[0] != nullPix)&& (ulKernelStartBuf[1] != nullPix)&& (ulKernelStartBuf[2] != nullPix)&& (leftKernelStartBuf[0] != nullPix)&& (leftKernelStartBuf[1] != nullPix)&& (leftKernelStartBuf[2] != nullPix)&& (llKernelStartBuf[0] != nullPix)&& (llKernelStartBuf[1] != nullPix)&& (llKernelStartBuf[2] != nullPix)) { sum = theKernel[0][0]*(double)ulKernelStartBuf[0] + theKernel[0][1]*(double)ulKernelStartBuf[1] + theKernel[0][2]*(double)ulKernelStartBuf[2] + theKernel[1][0]*(double)leftKernelStartBuf[0] + theKernel[1][1]*(double)leftKernelStartBuf[1] + theKernel[1][2]*(double)leftKernelStartBuf[2] + theKernel[2][0]*(double)llKernelStartBuf[0] + theKernel[2][1]*(double)llKernelStartBuf[1] + theKernel[2][2]*(double)llKernelStartBuf[2]; if(sum > maxPix) { *outputBuf = maxPix; } else if(sum < minPix) { *outputBuf = minPix; } else { *outputBuf = static_cast(sum); } } else { *outputBuf = oNullPix; } // // Need to implement the convolution here // ++ulKernelStartBuf; ++leftKernelStartBuf; ++llKernelStartBuf; ++outputBuf; } } } } } template void ossim3x3ConvolutionFilter::convolveFull( T, ossimRefPtr inputData, ossimRefPtr outputData) { // let's set up some temporary variables so we don't // have to call the functions in loops. Iknow that compilers // typically optimize this out but if we are in debug mode // with no optimization it will still run fast // double sum = 0.0; ossim_int32 inputW = static_cast(inputData->getWidth()); ossim_uint32 outputW = outputData->getWidth(); ossim_uint32 outputH = outputData->getHeight(); ossim_uint32 numberOfBands = inputData->getNumberOfBands(); ossimIpt outputOrigin = outputData->getOrigin(); ossimIpt inputOrigin = inputData->getOrigin(); ossim_int32 startInputOffset = std::abs(outputOrigin.y - inputOrigin.y)* inputW + std::abs(outputOrigin.x - inputOrigin.x); ossim_int32 ulKernelStart = -inputW - 1; ossim_int32 leftKernelStart = -1; ossim_int32 llKernelStart = inputW - 1; T* ulKernelStartBuf = NULL; T* leftKernelStartBuf = NULL; T* llKernelStartBuf = NULL; for(ossim_uint32 band = 0; band < numberOfBands; ++band) { T* inputBuf = static_cast(inputData->getBuf(band))+startInputOffset; T* outputBuf = static_cast(outputData->getBuf(band)); T maxPix = static_cast(getMaxPixelValue(band)); T minPix = static_cast(getMinPixelValue(band)); if(inputBuf&&outputBuf) { for(ossim_uint32 row = 0; row < outputW; ++row) { ossim_int32 rowOffset = inputW*row; ulKernelStartBuf = inputBuf + (rowOffset + ulKernelStart); leftKernelStartBuf = inputBuf + (rowOffset + leftKernelStart); llKernelStartBuf = inputBuf + (rowOffset + llKernelStart); for(ossim_uint32 col = 0; col < outputH; ++col) { sum = theKernel[0][0]*(double)ulKernelStartBuf[0] + theKernel[0][1]*(double)ulKernelStartBuf[1] + theKernel[0][2]*(double)ulKernelStartBuf[2] + theKernel[1][0]*(double)leftKernelStartBuf[0] + theKernel[1][1]*(double)leftKernelStartBuf[1] + theKernel[1][2]*(double)leftKernelStartBuf[2] + theKernel[2][0]*(double)llKernelStartBuf[0] + theKernel[2][1]*(double)llKernelStartBuf[1] + theKernel[2][2]*(double)llKernelStartBuf[2]; if(sum > maxPix) { *outputBuf = maxPix; } else if(sum < minPix) { *outputBuf = minPix; } else { *outputBuf = static_cast(sum); } // // Need to implement the convolution here. // ++ulKernelStartBuf; ++leftKernelStartBuf; ++llKernelStartBuf; ++outputBuf; } } } } } void ossim3x3ConvolutionFilter::initialize() { //--- // NOTE: // Since initialize get called often sequentially we will wipe things slick // but not reallocate to avoid multiple delete/allocates. // // On the first getTile call things will be reallocated/computed. //--- theTile = NULL; clearNullMinMax(); } void ossim3x3ConvolutionFilter::allocate() { if(theInputConnection) { ossimImageDataFactory* idf = ossimImageDataFactory::instance(); theTile = idf->create(this, this); theTile->initialize(); } } void ossim3x3ConvolutionFilter::setProperty(ossimRefPtr property) { if(!property) return; if(property->getName() == "Kernel") { ossimMatrixProperty* matrixProperty = PTR_CAST(ossimMatrixProperty, property.get()); if(matrixProperty) { theKernel[0][0] = (*matrixProperty)(0,0); theKernel[1][0] = (*matrixProperty)(1,0); theKernel[2][0] = (*matrixProperty)(2,0); theKernel[0][1] = (*matrixProperty)(0,1); theKernel[1][1] = (*matrixProperty)(1,1); theKernel[2][1] = (*matrixProperty)(2,1); theKernel[0][2] = (*matrixProperty)(0,2); theKernel[1][2] = (*matrixProperty)(1,2); theKernel[2][2] = (*matrixProperty)(2,2); } else { ossimImageSourceFilter::setProperty(property); } } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossim3x3ConvolutionFilter::getProperty(const ossimString& name)const { if(name == "Kernel") { ossimMatrixProperty* property = new ossimMatrixProperty(name); property->resize(3,3); (*property)(0,0) = theKernel[0][0]; (*property)(1,0) = theKernel[1][0]; (*property)(2,0) = theKernel[2][0]; (*property)(0,1) = theKernel[0][1]; (*property)(1,1) = theKernel[1][1]; (*property)(2,1) = theKernel[2][1]; (*property)(0,2) = theKernel[0][2]; (*property)(1,2) = theKernel[1][2]; (*property)(2,2) = theKernel[2][2]; property->setCacheRefreshBit(); return property; } return ossimImageSourceFilter::getProperty(name); } void ossim3x3ConvolutionFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("Kernel"); } bool ossim3x3ConvolutionFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "rows", 3, true); kwl.add(prefix, "cols", 3, true); for(ossim_int32 row = 0; row < 3; ++row) { for(ossim_int32 col =0; col < 3; ++col) { ossimString newPrefix = "m" + ossimString::toString(row+1) + "_" + ossimString::toString(col+1); kwl.add(prefix, newPrefix, theKernel[row][col], true); } } return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossim3x3ConvolutionFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString newPrefix = prefix; newPrefix += ossimString("m"); for(ossim_int32 r = 0; r < 3; r++) { for(ossim_int32 c = 0; c < 3; c++) { theKernel[r][c] = 0.0; ossimString value = ossimString::toString(r+1); value += "_"; value += ossimString::toString(c+1); const char* v = kwl.find(newPrefix.c_str(), value.c_str()); if(v) { theKernel[r][c] = ossimString(v).toDouble(); } } } return ossimImageSourceFilter::loadState(kwl, prefix); } void ossim3x3ConvolutionFilter::getKernel(double kernel[3][3]) { kernel[0][0] = theKernel[0][0]; kernel[0][1] = theKernel[0][1]; kernel[0][2] = theKernel[0][2]; kernel[1][0] = theKernel[1][0]; kernel[1][1] = theKernel[1][1]; kernel[1][2] = theKernel[1][2]; kernel[2][0] = theKernel[2][0]; kernel[2][1] = theKernel[2][1]; kernel[2][2] = theKernel[2][2]; } void ossim3x3ConvolutionFilter::setKernel(double kernel[3][3]) { theKernel[0][0] = kernel[0][0]; theKernel[0][1] = kernel[0][1]; theKernel[0][2] = kernel[0][2]; theKernel[1][0] = kernel[1][0]; theKernel[1][1] = kernel[1][1]; theKernel[1][2] = kernel[1][2]; theKernel[2][0] = kernel[2][0]; theKernel[2][1] = kernel[2][1]; theKernel[2][2] = kernel[2][2]; // Will be recomputed first getTile call. clearNullMinMax(); } double ossim3x3ConvolutionFilter::getNullPixelValue(ossim_uint32 band)const { if( isSourceEnabled() && (band < theNullPixValue.size()) ) { return theNullPixValue[band]; } return ossim::defaultNull(getOutputScalarType()); } double ossim3x3ConvolutionFilter::getMinPixelValue(ossim_uint32 band)const { if( isSourceEnabled() && (band < theMinPixValue.size()) ) { return theMinPixValue[band]; } return ossimImageSource::getMinPixelValue(band); } double ossim3x3ConvolutionFilter::getMaxPixelValue(ossim_uint32 band)const { if( isSourceEnabled() && (band < theMaxPixValue.size()) ) { return theMaxPixValue[band]; } return ossimImageSource::getMaxPixelValue(band); } void ossim3x3ConvolutionFilter::clearNullMinMax() { theNullPixValue.clear(); theMinPixValue.clear(); theMaxPixValue.clear(); } void ossim3x3ConvolutionFilter::computeNullMinMax() { const ossim_uint32 BANDS = getNumberOfOutputBands(); theNullPixValue.resize(BANDS); theMinPixValue.resize(BANDS); theMaxPixValue.resize(BANDS); ossim_float64 defaultNull = ossim::defaultNull(getOutputScalarType()); ossim_float64 defaultMin = ossim::defaultMin(getOutputScalarType()); ossim_float64 defaultMax = ossim::defaultMax(getOutputScalarType()); for (ossim_uint32 band = 0; band < BANDS; ++band) { if(theInputConnection) { ossim_float64 inputNull = theInputConnection->getNullPixelValue(band); ossim_float64 inputMin = theInputConnection->getMinPixelValue(band); ossim_float64 inputMax = theInputConnection->getMaxPixelValue(band); ossim_float64 tempMin = 0.0; ossim_float64 tempMax = 0.0; ossim_float64 k = 0.0; for(int i=0;i<3;++i) { for(int j=0;j<3;++j) { k=theKernel[i][j]; tempMin += (k<0.0) ? k*inputMax : k*inputMin; tempMax += (k>0.0) ? k*inputMax : k*inputMin; } } if((inputNull < getMinPixelValue(band)) || (inputNull > getMaxPixelValue(band))) { theNullPixValue[band] = inputNull; } else { theNullPixValue[band] = defaultNull; } if((tempMin >= defaultMin) && (tempMin <= defaultMax)) { theMinPixValue[band] = tempMin; } else { theMinPixValue[band] = defaultMin; } if((tempMax >= defaultMin) && (tempMax <= defaultMax)) { theMaxPixValue[band] = tempMax; } else { theMaxPixValue[band] = defaultMax; } } else // No input connection... { theNullPixValue[band] = defaultNull; theMinPixValue[band] = defaultMin; theMaxPixValue[band] = defaultMax; } } // End of band loop. } ossim-Miami-2.9.1/src/imaging/ossimAOD.cpp000066400000000000000000000123631352751253100203040ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Kathy Minear // // Description: // // Class to compute Aerosol Optical Depth (AOD) for with atmospheric // correction. // // //************************************************************************* // $Id: ossimAOD.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include RTTI_DEF1(ossimAOD, "ossimAOD", ossimImageSourceFilter) static ossimTrace traceDebug("ossimAOD:debug"); using namespace std; ossimAOD::ossimAOD(ossimObject* owner) : ossimImageSourceFilter (owner), // base class theTile (NULL) { //*** // Set the base class "theEnableFlag" to off since no adjustments have been // made yet. //*** disableSource(); // Construction not complete. } ossimAOD::ossimAOD(ossimImageSource* inputSource) : ossimImageSourceFilter (NULL, inputSource), // base class theTile (NULL) { //*** // Set the base class "theEnableFlag" to off since no adjustments have been // made yet. //*** disableSource(); if (inputSource == NULL) { setErrorStatus(); cerr << "ossimAOD::ossimAOD ERROR:" << "\nNull input source passed to constructor!" << endl; return; } initialize(); } ossimAOD::ossimAOD(ossimObject* owner, ossimImageSource* inputSource) : ossimImageSourceFilter (owner, inputSource), // base class theTile (NULL) { //*** // Set the base class "theEnableFlag" to off since no adjustments have been // made yet. //*** disableSource(); if (inputSource == NULL) { setErrorStatus(); cerr << "ossimAOD::ossimAOD ERROR:" << "\nNull input source passed to constructor!" << endl; return; } initialize(); } ossimAOD::~ossimAOD() { } ossimRefPtr ossimAOD::getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel) { if (!theInputConnection) { return ossimRefPtr(); } // Fetch tile from pointer from the input source. ossimRefPtr inputTile = theInputConnection->getTile(tile_rect, resLevel); if (!inputTile.valid()) // Just in case... { ossimNotify(ossimNotifyLevel_WARN) << "ossimAOD::getTile ERROR:" << "\nReceived null pointer to tile from input source!" << "\nReturning blank tile." << endl; return inputTile; } ossimDataObjectStatus tile_status = inputTile->getDataObjectStatus(); if ( !theEnableFlag || (tile_status == OSSIM_NULL) || (tile_status == OSSIM_EMPTY) ) { return inputTile; } if (!theTile.valid()) { allocate(); if (!theTile.valid()) { return inputTile; } } ossim_uint32 w = tile_rect.width(); ossim_uint32 h = tile_rect.height(); ossim_uint32 tw = theTile->getWidth(); ossim_uint32 th = theTile->getHeight(); // ossim_uint32 bands = theTile->getNumberOfBands(); // Set the origin of the output tile. theTile->setOrigin(tile_rect.ul()); if(w*h != tw*th) { theTile->setWidthHeight(w, h); theTile->initialize(); } return theTile; } void ossimAOD::initialize() { ossimImageSourceFilter::initialize(); } void ossimAOD::allocate() { if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, theInputConnection); theTile->initialize(); setInitializedFlag(true); clearErrorStatus(); } else { setInitializedFlag(false); setErrorStatus(); cerr << "ossimAOD::initialize ERROR:" << "\nCannot call method when input connection is NULL!" << endl; }; verifyEnabled(); } bool ossimAOD::loadState(const ossimKeywordlist& /* kwl */, const char* /* prefix */) { static const char MODULE[] = "ossimAOD::loadState()"; if (traceDebug()) CLOG << "entering..." << endl; if (!theTile) { cerr << MODULE << " ERROR:" << "Not initialized..." << endl; return false; } if (traceDebug()) { CLOG << "DEBUG:" << *this << "\nreturning..." << endl; } return true; } void ossimAOD::verifyEnabled() { // Check all the pointers... if ( !theInputConnection || !theTile ) { disableSource(); return; } enableSource(); } ostream& ossimAOD::print(ostream& os) const { os << "ossimAOD:" << "\ntheEnableFlag: " << (theEnableFlag?"enabled":"disabled") << endl; return os; } ostream& operator<<(ostream& os, const ossimAOD& hr) { return hr.print(os); } void ossimAOD::writeTemplate(ostream& /* os */) { } ossimString ossimAOD::getShortName() const { return ossimString("Aerosol Optical Depth"); } ossim-Miami-2.9.1/src/imaging/ossimAdrgHeader.cpp000066400000000000000000000373061352751253100216730ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero // Description: This class encapsulates the image parameters and // support data for a ADRG image file(s). // //******************************************************************** // $Id: ossimAdrgHeader.cpp 13766 2008-10-22 19:31:32Z gpotts $ #include #include #include #include #include //************************************************************************** // Constructor //************************************************************************** ossimAdrgHeader::ossimAdrgHeader(const ossimFilename& img_file) : theErrorStatus(OSSIM_OK), theHeaderFile(img_file), theImageFile(img_file), theValidImageRect(0,0,0,0), thePixelType(OSSIM_UCHAR), theInterleaveType(OSSIM_BSQ), theNumberOfBands(3), theLines(0), theSamples(0), theHeaderSize(0), theTim(0) { // Get the extension. ossimString ext = img_file.ext(); if (ext == "IMG") { theHeaderFile.setExtension(ossimString("GEN")); } else if (ext == "img") { theHeaderFile.setExtension(ossimString("gen")); } else { // Required "img" or "IMG" extension. theErrorStatus = OSSIM_ERROR; return; } // Check for header file. if(theHeaderFile.exists() == false) { theErrorStatus = OSSIM_ERROR; return; } // Parse header for all needed support data. parse(); } //************************************************************************** // Destructor //************************************************************************** ossimAdrgHeader::~ossimAdrgHeader() { if(theTim) { delete [] theTim; theTim = 0; } } //************************************************************************** // Parse header //************************************************************************** void ossimAdrgHeader::parse() { // NOTE: By default, ISO8211 library reports errors to stderr, // so we don't bother doing it ourselves. We simply set // the OSSIM_ERROR flag. ossimDDFModule oModule; ossimDDFRecord* oRecord; // Open header file which is ISO8211 encoded. if(!oModule.Open(theHeaderFile.chars()) ) { theErrorStatus = OSSIM_ERROR; return; } oRecord = oModule.ReadRecord(); ossimDDFField* oField = oRecord->FindField("DRF"); int bytesOfData = oField->GetDataSize(); int nBytesConsumed = 0; const char* rawFieldData; ossimDDFFieldDefn* fieldDefn = oField->GetFieldDefn(); ossimDDFSubfieldDefn* nfile = fieldDefn->FindSubfieldDefn("NOZ"); rawFieldData = oField->GetSubfieldData(nfile); ossimString num_img_files = nfile->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed); // Number of ZDR images ossim_uint32 num_ifiles = (ossim_uint32)ossimString::toInt(num_img_files); // Skip overview record. oRecord = oModule.ReadRecord(); // Validate this is the correct record and it is an ADRG image. ossimString img_file = ""; ossimString img_base = theImageFile.fileNoExtension(); img_base.downcase(); // Find the correct geometry record corresponding to the image file. ossim_uint32 count = 0; while(count < num_ifiles) { oField = oRecord->FindField("001"); bytesOfData = oField->GetDataSize(); nBytesConsumed = 0; fieldDefn = oField->GetFieldDefn(); ossimDDFSubfieldDefn* rty = fieldDefn->FindSubfieldDefn("RTY"); rawFieldData = oField->GetSubfieldData(rty); ossimString rtype = rty->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed); // Found general information record if(rtype == "GIN") { // Validate that this is an ADRG header file. oField = oRecord->FindField("DSI"); bytesOfData = oField->GetDataSize(); nBytesConsumed = 0; fieldDefn = oField->GetFieldDefn(); ossimDDFSubfieldDefn* ptype = fieldDefn->FindSubfieldDefn("PRT"); rawFieldData = oField->GetSubfieldData(ptype); ossimString product_type = ptype->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed); if(!(strncmp(product_type.c_str(), "ADRG", 4) == 0)) { ossimNotify(ossimNotifyLevel_NOTICE) << "File does not appear to be an ADRG header file: " << theHeaderFile.chars() << std::endl; theErrorStatus = OSSIM_ERROR; return; } fieldDefn = oField->GetFieldDefn(); ossimDDFSubfieldDefn* ifile = fieldDefn->FindSubfieldDefn("NAM"); rawFieldData = oField->GetSubfieldData(ifile); img_file = ifile->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed); img_file.downcase(); count++; if(img_base == img_file) break; else oRecord = oModule.ReadRecord(); } else oRecord = oModule.ReadRecord(); } // Find Distribution Rectangle name. oField = oRecord->FindField("GEN"); bytesOfData = oField->GetDataSize(); nBytesConsumed = 0; fieldDefn = oField->GetFieldDefn(); // Find Subfield names. ossimDDFSubfieldDefn* min_lon = fieldDefn->FindSubfieldDefn("SWO"); ossimDDFSubfieldDefn* min_lat = fieldDefn->FindSubfieldDefn("SWA"); ossimDDFSubfieldDefn* max_lon = fieldDefn->FindSubfieldDefn("NEO"); ossimDDFSubfieldDefn* max_lat = fieldDefn->FindSubfieldDefn("NEA"); // Extract the min/max lon/lat coordinates. rawFieldData = oField->GetSubfieldData(min_lon); theMinLon = min_lon->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed); rawFieldData = oField->GetSubfieldData(min_lat); theMinLat = min_lat->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed); rawFieldData = oField->GetSubfieldData(max_lon); theMaxLon = max_lon->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed); rawFieldData = oField->GetSubfieldData(max_lat); theMaxLat = max_lat->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed); // Find the DATA_SET_PARAMETERS_FIELD oField = oRecord->FindField("SPR"); bytesOfData = oField->GetDataSize(); nBytesConsumed = 0; fieldDefn = oField->GetFieldDefn(); // Find subfields. ossimDDFSubfieldDefn* start_row = fieldDefn->FindSubfieldDefn("NUL"); ossimDDFSubfieldDefn* stop_col = fieldDefn->FindSubfieldDefn("NUS"); ossimDDFSubfieldDefn* stop_row = fieldDefn->FindSubfieldDefn("NLL"); ossimDDFSubfieldDefn* start_col = fieldDefn->FindSubfieldDefn("NLS"); ossimDDFSubfieldDefn* lines = fieldDefn->FindSubfieldDefn("NFL"); ossimDDFSubfieldDefn* samples = fieldDefn->FindSubfieldDefn("NFC"); ossimDDFSubfieldDefn* tif = fieldDefn->FindSubfieldDefn("TIF"); // Extract the number of lines & samples per tile. rawFieldData = oField->GetSubfieldData(start_row); theStartRow = atoi(start_row->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed)); rawFieldData = oField->GetSubfieldData(start_col); theStartCol = atoi(start_col->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed)); rawFieldData = oField->GetSubfieldData(stop_row); theStopRow = atoi(stop_row->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed)); rawFieldData = oField->GetSubfieldData(stop_col); theStopCol = atoi(stop_col->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed)); rawFieldData = oField->GetSubfieldData(lines); theLinesInTiles = atoi(lines->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed)); rawFieldData = oField->GetSubfieldData(samples); theSamplesInTiles = atoi(samples->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed)); rawFieldData = oField->GetSubfieldData(tif); theTif = tif->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed); theLines = theLinesInTiles * ADRG_TILE_SIZE; theSamples = theSamplesInTiles * ADRG_TILE_SIZE; theValidImageRect = ossimIrect(0, 0, theSamples - 1, theLines - 1); if(theTim) { delete [] theTim; theTim = 0; } // Initialize the TIM (tile index map). theTim = new ossim_uint32[theLinesInTiles * theSamplesInTiles]; // Read in the tile index map (TIM) if it exists. if(strncmp(theTif.c_str(), "Y", 1) == 0) { // Find the TILE_INDEX_MAP_FIELD oField = oRecord->FindField("TIM"); bytesOfData = oField->GetDataSize(); fieldDefn = oField->GetFieldDefn(); rawFieldData = oField->GetData(); nBytesConsumed = 0; for(ossim_uint32 r = 0; r < theLinesInTiles * theSamplesInTiles; r++ ) { ossimDDFSubfieldDefn* tim = fieldDefn->FindSubfieldDefn("TSI"); theTim[r] = atoi(tim->ExtractStringData(rawFieldData, bytesOfData, &nBytesConsumed)); bytesOfData -= nBytesConsumed; rawFieldData += nBytesConsumed; } } else { for(ossim_uint32 m = 0; m < (theLinesInTiles * theSamplesInTiles); m++) theTim[m] = (m+1); } // Close module used for reading encoded header file. oModule.Close(); } //********************************************************************* // tim(int32 row, int32 col) //********************************************************************* ossim_uint32 ossimAdrgHeader::tim(ossim_uint32 row, ossim_uint32 col) const { return ( theTim[(row * theSamplesInTiles) + col] ); } //********************************************************************* // operator << //********************************************************************* std::ostream& operator<<(std::ostream& os, const ossimAdrgHeader& adrg) { os << "\nContents of ADRG Header file (.gen):" << "\nImage File = " << adrg.theImageFile << "\nHeader File = " << adrg.theHeaderFile << "\nPixelType = " << adrg.thePixelType << "\nInterleaveType = " << adrg.theInterleaveType << "\nNumberOfBands = " << adrg.theNumberOfBands << "\nLines = " << adrg.theLines << "\nLines (tiles) = " << adrg.theLinesInTiles << "\nSamples = " << adrg.theSamples << "\nSamples (tiles) = " << adrg.theSamplesInTiles << "\nHeaderSize = " << adrg.theHeaderSize << "\nValidImageRect = " << adrg.theValidImageRect << "\nTIF = " << adrg.theTif << "\nMin Lon = " << adrg.theMinLon << "\nMin Lat = " << adrg.theMinLat << "\nMax Lon = " << adrg.theMaxLon << "\nMax Lat = " << adrg.theMaxLat << "\nStart Row = " << adrg.theStartRow << "\nStart Col = " << adrg.theStartCol << "\nStop Row = " << adrg.theStopRow << "\nStop Col = " << adrg.theStopCol << std::endl; for(ossim_uint32 m = 0; m < (adrg.theLinesInTiles * adrg.theSamplesInTiles); m++) os << "\nTIM[" << m << "] = " << adrg.theTim[m]; os << std::endl; return(os); } //********************************************************************* // Public method: //********************************************************************* double ossimAdrgHeader::minLongitude() const { return parseLongitudeString(theMinLon); } //********************************************************************* // Public method: //********************************************************************* double ossimAdrgHeader::minLatitude() const { return parseLatitudeString(theMinLat); } //********************************************************************* // Public method: //********************************************************************* double ossimAdrgHeader::maxLongitude() const { return parseLongitudeString(theMaxLon); } //********************************************************************* // Public method: //********************************************************************* double ossimAdrgHeader::maxLatitude() const { return parseLatitudeString(theMaxLat); } //********************************************************************* // Private method: //********************************************************************* double ossimAdrgHeader::parseLongitudeString(const ossimString& lon) const { static const char MODULE[] = "ossimAdrgHeader::parseLongitudeString"; // Format = +|-dddmmss.ss if (lon.size() != 11) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Longitude string error!" << "Bad longitude string: " << lon.c_str() << std::endl; } const char* cstr = lon.c_str(); double degrees = 0.0; double sign = 1.0; char tmp_str[6]; // Get the sign. if (cstr[0] == '-') sign = -1.0; // Get the degrees. tmp_str[3] = '\0'; cstr++; // Increment past the sign. strncpy(tmp_str, cstr, 3); degrees = atof(tmp_str); // Get the minutes. tmp_str[2] = '\0'; cstr += 3; // Increment to the minutes. strncpy(tmp_str, cstr, 2); degrees += atof(tmp_str) / 60.0; // Get the seconds. tmp_str[5] = '\0'; cstr += 2; // Increment to seconds. strncpy(tmp_str, cstr, 5); degrees += atof(tmp_str) / 3600.0; // Set the sign. degrees *= sign; return degrees; } //********************************************************************* // Private method: //********************************************************************* double ossimAdrgHeader::parseLatitudeString(const ossimString& lat) const { static const char MODULE[] = "ossimAdrgHeader::parseLatitudeString"; // Format = +|-ddmmss.ss if (lat.size() != 10) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Latitude string error!" << "Bad latitude string: " << lat.c_str() << std::endl; } const char* cstr = lat.c_str(); double degrees = 0.0; double sign = 1.0; char tmp_str[6]; // Get the sign. if (cstr[0] == '-') sign = -1.0; // Get the degrees. tmp_str[2] = '\0'; cstr++; // Increment past the sign. strncpy(tmp_str, cstr, 2); degrees = atof(tmp_str); // Get the minutes. tmp_str[2] = '\0'; cstr += 2; // Increment to the minutes. strncpy(tmp_str, cstr, 2); degrees += atof(tmp_str) / 60.0; // Get the seconds. tmp_str[5] = '\0'; cstr += 2; // Increment to seconds. strncpy(tmp_str, cstr, 5); degrees += atof(tmp_str) / 3600.0; // Set the sign. degrees *= sign; return degrees; } ossim-Miami-2.9.1/src/imaging/ossimAdrgTileSource.cpp000066400000000000000000000520501352751253100225520ustar00rootroot00000000000000//******************************************************************* // // See top level LICENSE.txt file. // // Author: Ken Melero // Contributor: David A. Horner (DAH) - http://dave.thehorners.com // // Description: This class give the capability to access tiles from an // ADRG file. // //******************************************************************** // $Id: ossimAdrgTileSource.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimAdrgTileSource, "ossimAdrgTileSource", ossimImageHandler) //*** // Static trace for debugging //*** static ossimTrace traceDebug("ossimAdrgTileSource:debug"); //*** // NOTE: Currently this tilesource is hard-coded to access tiles // from the ZDR image file. This will change as I wrote support // data classes for all the ADRG image files: ZDR, overview, // and legend support data. Next step in development will // be to put in flags to access overview and legend image files. //*** using namespace std; //******************************************************************* // Public Constructor: //******************************************************************* ossimAdrgTileSource::ossimAdrgTileSource() : ossimImageHandler(), m_Tile(0), m_TileBuffer(0), m_FileStr(), m_AdrgHeader(0) { // Construction not complete. Users should call "open" method. } ossimAdrgTileSource::~ossimAdrgTileSource() { if(m_AdrgHeader) { delete m_AdrgHeader; m_AdrgHeader = 0; } if (m_TileBuffer) { delete [] m_TileBuffer; m_TileBuffer = 0; } close(); } ossimRefPtr ossimAdrgTileSource::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if (m_Tile.valid()) { // Image rectangle must be set prior to calling getTile. m_Tile->setImageRectangle(rect); if ( getTile( m_Tile.get(), resLevel ) == false ) { if (m_Tile->getDataObjectStatus() != OSSIM_NULL) { m_Tile->makeBlank(); } } } return m_Tile; } bool ossimAdrgTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) ) { result->ref(); // Increment ref count. //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0. Method returns true on success, false // on error. //--- status = getOverviewTile(resLevel, result); if (!status) // Did not get an overview tile. { status = true; ossimIrect tile_rect = result->getImageRectangle(); ossimIrect image_rect = getImageRectangle(resLevel); result->makeBlank(); //--- // See if any point of the requested tile is in the image. //--- if ( tile_rect.intersects(image_rect) ) { ossimIrect clip_rect = tile_rect.clipToRect(image_rect); // Load the tile buffer with data from the adrg. status = fillBuffer(tile_rect, clip_rect, result); if (status) { result->validate(); } } } result->unref(); // Decrement ref count. } return status; } //******************************************************************* // Private Method: //******************************************************************* bool ossimAdrgTileSource::fillBuffer(const ossimIrect& /* tile_rect */, const ossimIrect& clip_rect, ossimImageData* tile) { //*** // Shift the upper left corner of the "clip_rect" to the an even chunk // boundry. //*** ossimIpt tileOrigin = clip_rect.ul(); adjustToStartOfTile(tileOrigin); //*** // Calculate the number of tiles needed in the line/sample directions. //*** ossim_int32 size_in_x = clip_rect.lr().x - tileOrigin.x + 1; ossim_int32 size_in_y = clip_rect.lr().y - tileOrigin.y + 1; ossim_int32 tiles_in_x_dir = size_in_x / ADRG_TILE_WIDTH + (size_in_x % ADRG_TILE_WIDTH ? 1 : 0); ossim_int32 tiles_in_y_dir = size_in_y / ADRG_TILE_HEIGHT + (size_in_y % ADRG_TILE_HEIGHT ? 1 : 0); ossimIpt ulTilePt = tileOrigin; // Chunk loop in line direction. for (ossim_int32 y=0; ytim(row, col); if(tileOffset != 0) { // Get the data. int seek_position = (tileOffset - 1) * 49152 + 2048; int band; // seek to start of chip m_FileStr.seekg(seek_position, ios::beg); for (band=0; band<3; band++) { //*** // Read the chip from the ccf file into the chunk buffer. // This will get all the bands. Bands are interleaved by // chip. //*** if (!m_FileStr.read((char*)m_TileBuffer, ADRG_TILE_SIZE)) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return false; } tile->loadBand(m_TileBuffer, adrg_tile_rect, tile_clip_rect, band); } // End of band loop. } // End of if (tileOffset != 0) } // End of if (adrg_tile_rect.intersects(clip_rect)) ulTilePt.x += ADRG_TILE_WIDTH; } // End of tile loop in the sample direction. ulTilePt.y += ADRG_TILE_HEIGHT; } // End of tile loop in the line direction. return true; } ossim_uint32 ossimAdrgTileSource::getNumberOfOutputBands()const { return getNumberOfInputBands(); } //******************************************************************* // Public Method: //******************************************************************* ossimIrect ossimAdrgTileSource::getImageRectangle(ossim_uint32 reduced_res_level) const { return ossimIrect(0, // upper left x 0, // upper left y getNumberOfSamples(reduced_res_level) - 1, // lower right x getNumberOfLines(reduced_res_level) - 1); // lower right y } void ossimAdrgTileSource::close() { if(m_AdrgHeader) { delete m_AdrgHeader; m_AdrgHeader = 0; } if(m_FileStr.is_open()) { m_FileStr.close(); } m_Tile = 0; } //******************************************************************* // Public method: //******************************************************************* bool ossimAdrgTileSource::open() { static const char MODULE[] = "ossimAdrgTileSource::open"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "Entered..."<errorStatus() == ossimErrorCodes::OSSIM_ERROR) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error in ossimAdrg header detected." << std::endl; } close(); return false; } m_FileStr.open(m_AdrgHeader->imageFile().c_str(), ios::in | ios::binary); // Check the file pointer. if(!m_FileStr) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << "\nCannot open: " << m_AdrgHeader->imageFile().c_str() << std::endl; } close(); return false; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "File is opened -> "<< m_AdrgHeader->imageFile()<create(this, this); m_Tile->initialize(); m_TileBuffer = new ossim_uint8[ADRG_TILE_SIZE]; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nminLon: " << m_AdrgHeader->minLon() << "\nminLond: " << m_AdrgHeader->minLongitude() << "\nminLat: " << m_AdrgHeader->minLat() << "\nminLatd: " << m_AdrgHeader->minLatitude() << "\nmaxLon: " << m_AdrgHeader->maxLon() << "\nmaxLond: " << m_AdrgHeader->maxLongitude() << "\nmaxLat: " << m_AdrgHeader->maxLat() << "\nmaxLatd: " << m_AdrgHeader->maxLatitude() << std::endl; } return true; } //******************************************************************* // Public method: //******************************************************************* bool ossimAdrgTileSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Currently nothing to do here. return ossimImageHandler::saveState(kwl, prefix); } //******************************************************************* // Public method: //******************************************************************* bool ossimAdrgTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (ossimImageHandler::loadState(kwl, prefix)) { if (open()) { return true; } } return false; } //******************************************************************* // Public method: //******************************************************************* ossimRefPtr ossimAdrgTileSource::getImageGeometry() { if ( !theGeometry ) { // Check for external geom: theGeometry = getExternalImageGeometry(); if ( !theGeometry ) { // origin of latitude ossim_float64 originLatitude = (m_AdrgHeader->maxLatitude() + m_AdrgHeader->minLatitude()) / 2.0; // central meridian. ossim_float64 centralMeridian = (m_AdrgHeader->maxLongitude() + m_AdrgHeader->minLongitude()) / 2.0; //--- // Compute the pixel size in latitude and longitude direction. This will // be full image extents divided by full image lines and samples. //--- // Samples in full image (used to compute degPerPixelX). ossim_float64 samples = m_AdrgHeader->samples(); // Lines in full image (used to compute degPerPixelX). ossim_float64 lines = m_AdrgHeader->lines(); // Degrees in latitude direction of the full image. ossim_float64 degrees_in_lat_dir = m_AdrgHeader->maxLatitude() - m_AdrgHeader->minLatitude(); // Degrees in longitude direction of the full image. ossim_float64 degrees_in_lon_dir = m_AdrgHeader->maxLongitude() - m_AdrgHeader->minLongitude(); ossim_float64 degPerPixelY = degrees_in_lat_dir / lines; ossim_float64 degPerPixelX = degrees_in_lon_dir / samples; //--- // The tie is determined with the following assumptions that need to be // verified: // 1) Rows and columns start at 1. // 2) The min / max latitudes longitudes go to the edge of the pixel. // 3) Latitude decreases by degPerPixelY with each line. // 4) Longitude increases by degPerPixelX with each sample. //--- ossim_float64 ul_lat = (m_AdrgHeader->maxLatitude() - ( (m_AdrgHeader->startRow() - 1) * degPerPixelY ) - ( degPerPixelY * 0.5 ) ); ossim_float64 ul_lon = (m_AdrgHeader->minLongitude() + ( (m_AdrgHeader->startCol() -1) * degPerPixelX ) + ( degPerPixelX * 0.5 ) ); // projection type ossimKeywordlist kwl; const char* prefix = 0; kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimEquDistCylProjection", true); // datum. kwl.add(prefix, ossimKeywordNames::DATUM_KW, "WGE", true); // origin latitude kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, originLatitude, true); // central meridin kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, centralMeridian, true); // Save the tie point. kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, ossimDpt(ul_lon, ul_lat).toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES), true); // Save the scale. kwl.add(prefix, ossimKeywordNames::TIE_POINT_LAT_KW, ul_lat, true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LON_KW, ul_lon, true); // Save the scale. kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW, ossimDpt(degPerPixelX, degPerPixelY).toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES), true); // lines kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, getNumberOfLines()); // samples kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, getNumberOfSamples()); // res sets kwl.add(prefix, ossimKeywordNames::NUMBER_REDUCED_RES_SETS_KW, getNumberOfDecimationLevels()); // bands kwl.add(prefix, ossimKeywordNames::NUMBER_INPUT_BANDS_KW, getNumberOfInputBands()); // bands kwl.add(prefix, ossimKeywordNames::NUMBER_OUTPUT_BANDS_KW, getNumberOfOutputBands()); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nminLon: " << m_AdrgHeader->minLon() << "\nminLond: " << m_AdrgHeader->minLongitude() << "\nminLat: " << m_AdrgHeader->minLat() << "\nminLatd: " << m_AdrgHeader->minLatitude() << "\nmaxLon: " << m_AdrgHeader->maxLon() << "\nmaxLond: " << m_AdrgHeader->maxLongitude() << "\nmaxLat: " << m_AdrgHeader->maxLat() << "\nmaxLatd: " << m_AdrgHeader->maxLatitude() << "\nstartRow: " << m_AdrgHeader->startRow() << "\nstartCol: " << m_AdrgHeader->startCol() << "\nstopRow: " << m_AdrgHeader->stopRow() << "\nstopCol: " << m_AdrgHeader->stopCol() << "\nfull image lines: " << lines << "\nfull image samples: " << samples << "\nkwl:\n" << kwl << std::endl; } ossimProjection* new_proj = ossimProjectionFactoryRegistry::instance()->createProjection(kwl); theGeometry = new ossimImageGeometry; theGeometry->setProjection(new_proj); // assumes management of projection instance } // matches (after getExternalImageGeometry()): if ( !theGeometry ) // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } // matches: if ( !theGeometry ) return theGeometry; } //******************************************************************* // Public method: //******************************************************************* ossimScalarType ossimAdrgTileSource::getOutputScalarType() const { return OSSIM_UCHAR; } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimAdrgTileSource::getTileWidth() const { return ( m_Tile.valid() ? m_Tile->getWidth() : 0 ); } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimAdrgTileSource::getTileHeight() const { return ( m_Tile.valid() ? m_Tile->getHeight() : 0 ); } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimAdrgTileSource::getNumberOfLines(ossim_uint32 reduced_res_level) const { if ( (reduced_res_level == 0) && m_AdrgHeader ) { return (m_AdrgHeader->stopRow() - m_AdrgHeader->startRow()) + 1; } else if (theOverview.valid()) { return theOverview->getNumberOfLines(reduced_res_level); } return 0; } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimAdrgTileSource::getNumberOfSamples(ossim_uint32 reduced_res_level) const { if ( (reduced_res_level == 0) && m_AdrgHeader ) { return (m_AdrgHeader->stopCol() - m_AdrgHeader->startCol()) + 1; } else if (theOverview.valid()) { return theOverview->getNumberOfSamples(reduced_res_level); } return 0; } ossim_uint32 ossimAdrgTileSource::getImageTileWidth() const { return ADRG_TILE_WIDTH; } ossim_uint32 ossimAdrgTileSource::getImageTileHeight() const { return ADRG_TILE_HEIGHT; } ossimRefPtr ossimAdrgTileSource::getProperty(const ossimString& name)const { if(name == "file_type") { return new ossimStringProperty(name, "ADRG"); } return ossimImageHandler::getProperty(name); } void ossimAdrgTileSource::getPropertyNames(std::vector& propertyNames)const { ossimImageHandler::getPropertyNames(propertyNames); propertyNames.push_back("file_type"); } ossimString ossimAdrgTileSource::getShortName()const { return ossimString("adrg"); } ossimString ossimAdrgTileSource::getLongName()const { return ossimString("adrg reader"); } ossim_uint32 ossimAdrgTileSource::getNumberOfInputBands() const { ossim_uint32 bands = 1; if ( m_AdrgHeader ) { bands = m_AdrgHeader->numberOfBands(); } return bands; } bool ossimAdrgTileSource::isOpen()const { return (m_AdrgHeader!=0); } void ossimAdrgTileSource::adjustToStartOfTile(ossimIpt& pt) const { pt.x &= 0xffffff80; pt.y &= 0xffffff80; } ossim-Miami-2.9.1/src/imaging/ossimAnnotationEllipseObject.cpp000066400000000000000000000126431352751253100244610ustar00rootroot00000000000000//******************************************************************* // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationEllipseObject.cpp 13964 2009-01-14 16:30:07Z gpotts $ #include #include #include RTTI_DEF1(ossimAnnotationEllipseObject, "ossimAnnotationEllipseObject", ossimAnnotationObject) using namespace std; ossimAnnotationEllipseObject::ossimAnnotationEllipseObject( const ossimDpt& center, const ossimDpt& widthHeight, ossim_float64 azimuthInDegrees, bool enableFill, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b, ossim_uint8 thickness) : ossimAnnotationObject(r, g, b, thickness), theCenter(center), theWidthHeight(widthHeight), theAzimuthInDegrees(azimuthInDegrees), theFillEnabled(enableFill), theDrawAxesFlag(false), theBoundingRect(0,0,0,0) { computeBoundingRect(); } ossimAnnotationEllipseObject::ossimAnnotationEllipseObject( const ossimAnnotationEllipseObject& rhs) :ossimAnnotationObject(rhs), theCenter(rhs.theCenter), theWidthHeight(rhs.theWidthHeight), theAzimuthInDegrees(rhs.theAzimuthInDegrees), theFillEnabled(rhs.theFillEnabled), theDrawAxesFlag(rhs.theDrawAxesFlag), theBoundingRect(rhs.theBoundingRect) { } ossimObject* ossimAnnotationEllipseObject::dup()const { return new ossimAnnotationEllipseObject(*this); } ossimAnnotationEllipseObject::~ossimAnnotationEllipseObject() { } void ossimAnnotationEllipseObject::applyScale(double x, double y) { theCenter.x *= x; theCenter.y *= y; theWidthHeight.x *= x; theWidthHeight.y *= y; computeBoundingRect(); } void ossimAnnotationEllipseObject::draw(ossimRgbImage& anImage)const { anImage.setDrawColor(theRed, theGreen, theBlue); anImage.setThickness(theThickness); if(theBoundingRect.intersects(anImage.getImageData()->getImageRectangle())) { if(theFillEnabled) { anImage.drawFilledEllipse((int)(theCenter.x), (int)(theCenter.y), (int)(theWidthHeight.x), (int)(theWidthHeight.y), theAzimuthInDegrees*RAD_PER_DEG); } else { anImage.drawEllipse((int)(theCenter.x), (int)(theCenter.y), (int)(theWidthHeight.x), (int)(theWidthHeight.y), theAzimuthInDegrees*RAD_PER_DEG, theDrawAxesFlag); } } } bool ossimAnnotationEllipseObject::intersects(const ossimDrect& rect)const { return rect.intersects(theBoundingRect); } ossimAnnotationObject* ossimAnnotationEllipseObject::getNewClippedObject( const ossimDrect& rect)const { if(intersects(rect)) { return (ossimAnnotationObject*)dup(); } return (ossimAnnotationEllipseObject*)NULL; } std::ostream& ossimAnnotationEllipseObject::print(std::ostream& out)const { ossimAnnotationObject::print(out); out << endl; out << "ellipse_center: " << theCenter << "\nellipse_height: " << theWidthHeight.y << "\nellipse_width: " << theWidthHeight.x << "\nfill_enabled: " << theFillEnabled << "\ndraw_axes: " << theDrawAxesFlag << "\nellipse_bounding_rect: " << theBoundingRect; return out; } void ossimAnnotationEllipseObject::getBoundingRect(ossimDrect& rect)const { rect = theBoundingRect; } void ossimAnnotationEllipseObject::computeBoundingRect() { ossim_float64 maxDimension = ossim::max(theWidthHeight.x, theWidthHeight.y)/2.0 + 1.0; theBoundingRect = ossimDrect(theCenter.x - maxDimension, theCenter.y - maxDimension, theCenter.x + maxDimension, theCenter.y + maxDimension); } bool ossimAnnotationEllipseObject::isPointWithin(const ossimDpt& point)const { return theBoundingRect.pointWithin(point); } void ossimAnnotationEllipseObject::setCenterWidthHeight(const ossimDpt& center, const ossimDpt& widthHeight) { theCenter = center; theWidthHeight = widthHeight; computeBoundingRect(); } void ossimAnnotationEllipseObject::setAzimuth(ossim_float64 azimuth) { theAzimuthInDegrees = azimuth; } ossim_float64 ossimAnnotationEllipseObject::getAzimuth() const { return theAzimuthInDegrees; } void ossimAnnotationEllipseObject::setFillFlag(bool enabled) { theFillEnabled = enabled; } bool ossimAnnotationEllipseObject::getFillFlag() const { return theFillEnabled; } void ossimAnnotationEllipseObject::setDrawAxesFlag(bool flag) { theDrawAxesFlag = flag; } bool ossimAnnotationEllipseObject::getDrawAxesFlag() const { return theDrawAxesFlag; } bool ossimAnnotationEllipseObject::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimAnnotationObject::saveState(kwl, prefix); } bool ossimAnnotationEllipseObject::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimAnnotationObject::loadState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimAnnotationFontObject.cpp000066400000000000000000000254551352751253100237770ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationFontObject.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include RTTI_DEF1(ossimAnnotationFontObject, "ossimAnnotationFontObject", ossimAnnotationObject); using namespace std; ossimAnnotationFontObject::ossimAnnotationFontObject() :ossimAnnotationObject(), theFont(ossimFontFactoryRegistry::instance()->getDefaultFont()), thePosition(0,0), theString(""), theRotation(0.0), theHorizontalScale(0.0), theVerticalScale(0.0), theHorizontalShear(0.0), theVerticalShear(0.0) { setFontInfo(); theBoundingRect.makeNan(); } ossimAnnotationFontObject::ossimAnnotationFontObject(const ossimIpt& upperLeft, const ossimString& s, const ossimIpt& pixelSize, double rotation, const ossimDpt& scale, const ossimDpt& shear, unsigned char r, unsigned char g, unsigned char b) :ossimAnnotationObject(r,g,b), theFont(ossimFontFactoryRegistry::instance()->getDefaultFont()), theString(s), thePixelSize(pixelSize), theRotation(rotation), theHorizontalScale(scale.x), theVerticalScale(scale.y), theHorizontalShear(shear.x), theVerticalShear(shear.y) { setFontInfo(); thePosition = upperLeft; computeBoundingRect(); #if 0 if (theFont) { theFont->getBoundingBox(theBoundingRect); } theBoundingRect += upperLeft; thePosition = theBoundingRect.ul(); #endif } ossimAnnotationFontObject::ossimAnnotationFontObject(const ossimAnnotationFontObject& rhs) :ossimAnnotationObject(rhs), thePosition(rhs.thePosition), theString(rhs.theString), thePixelSize(rhs.thePixelSize), theRotation(rhs.theRotation), theHorizontalScale(rhs.theHorizontalScale), theVerticalScale(rhs.theVerticalScale), theHorizontalShear(rhs.theHorizontalShear), theVerticalShear(rhs.theVerticalShear), theBoundingRect(rhs.theBoundingRect) { theFont = rhs.theFont; setFontInfo(); } ossimAnnotationFontObject::~ossimAnnotationFontObject() { theFont = 0; } void ossimAnnotationFontObject::draw(ossimRgbImage& anImage)const { if(theBoundingRect.hasNans()) { return; } if (!theFont) { return; } if(!thePixelSize.x || !thePixelSize.y) { return; // (DAH) we have to have some demension to write! } ossimRefPtr destination = anImage.getImageData(); if(destination.valid()) { ossimIrect destRect = anImage.getImageData()->getImageRectangle(); ossimIpt shift(-theBoundingRect.ul().x, -theBoundingRect.ul().y); destRect += shift; ossimIrect boundingRect = theBoundingRect + shift; if(boundingRect.intersects(destRect)) { setFontInfo(); ossimIrect fontBufferRect; ossimIrect boundingFontBox; theFont->setClippingBox(destRect); theFont->getBoundingBox(boundingFontBox); const ossim_uint8* srcBuf = theFont->rasterize(); if (!srcBuf) { return; } theFont->getBufferRect(fontBufferRect); ossimIrect clipRect = boundingRect.clipToRect(fontBufferRect); long clipHeight = clipRect.height(); long clipWidth = clipRect.width(); long destinationOffset = (long)(((clipRect.ul().y - destRect.ul().y)* destRect.width()) + (clipRect.ul().x - destRect.ul().x)); long fontBufferOffset = (long)(((clipRect.ul().y - fontBufferRect.ul().y)*fontBufferRect.width()) + (clipRect.ul().x - fontBufferRect.ul().x)); long destinationIndex = destinationOffset; long srcIndex = fontBufferOffset; long num_bands = destination->getNumberOfBands(); ossim_int32 s_width = (ossim_int32)fontBufferRect.width(); ossim_int32 d_width = (ossim_int32)destRect.width(); num_bands = num_bands > 3? 3:num_bands; unsigned char colorArray[3]; long band = 0; colorArray[0] = theRed; colorArray[1] = theGreen; colorArray[2] = theBlue; ossim_uint8** destBuf = new ossim_uint8*[num_bands]; for(band = 0; band < num_bands;++band) { destBuf[band] = static_cast(destination->getBuf(band)); if (!destBuf[band]) { delete [] destBuf; return; } } for(long line = 0; line < clipHeight; ++line) { for(long col = 0; col < clipWidth; ++col) { if(srcBuf[srcIndex + col]) { for (band=0; bandgetFamilyName() << endl << "Style: " << theFont->getStyleName() << endl; } out << "String: " << theString << endl << "Upper Left Position: " << thePosition << endl << "Rotation: " << theRotation << endl << "Horizontal shear: " << theHorizontalShear << endl << "Vertical shear: " << theVerticalShear << endl << "Vertical scale: " << theVerticalScale << endl << "Horizontal scale: " << theHorizontalScale << endl << "Bounding rect: " << theBoundingRect << endl; return out; } void ossimAnnotationFontObject::getBoundingRect(ossimDrect& rect)const { rect = theBoundingRect; } void ossimAnnotationFontObject::computeBoundingRect() { setFontInfo(); if(theFont.valid()) { ossimIrect textRect; theFont->getBoundingBox(textRect); ossim_int32 w = textRect.width(); ossim_int32 h = textRect.height(); ossim_int32 ulx = thePosition.x; ossim_int32 uly = thePosition.y; theBoundingRect = ossimIrect(ulx, uly, ulx + w - 1, uly + h - 1); } } bool ossimAnnotationFontObject::isPointWithin(const ossimDpt& imagePoint)const { return theBoundingRect.pointWithin(imagePoint); } void ossimAnnotationFontObject::setFont(ossimFont* font) { theFont = font; if(!theFont) { theFont = ossimFontFactoryRegistry::instance()->getDefaultFont(); } } void ossimAnnotationFontObject::setCenterPosition(const ossimIpt& position) { ossimDpt pt = theBoundingRect.midPoint(); ossimIpt delta = position-pt; theBoundingRect += delta; thePosition = theBoundingRect.ul(); } void ossimAnnotationFontObject::setUpperLeftPosition(const ossimIpt& position) { ossimDpt pt = theBoundingRect.ul(); ossimIpt delta = position-pt; theBoundingRect += delta; thePosition = theBoundingRect.ul(); } void ossimAnnotationFontObject::setFontInfo()const { if(theFont.valid()) { theFont->setString(theString); theFont->setRotation(theRotation); theFont->setScale(theHorizontalScale, theVerticalScale); theFont->setHorizontalVerticalShear(theHorizontalShear, theVerticalShear); theFont->setPixelSize(thePixelSize.x, thePixelSize.y); } } void ossimAnnotationFontObject::setString(const ossimString& s) { theString = s; } ossimString ossimAnnotationFontObject::getString()const { return theString; } ossimAnnotationObject* ossimAnnotationFontObject::getNewClippedObject(const ossimDrect& rect)const { if(intersects(rect)) { return (ossimAnnotationObject*)dup(); } return (ossimAnnotationObject*)NULL; } bool ossimAnnotationFontObject::intersects(const ossimDrect& rect)const { return rect.intersects(theBoundingRect); } void ossimAnnotationFontObject::setPointSize(const ossimIpt& size) { thePixelSize = size; setFontInfo(); if (theFont.valid()) { theFont->getBoundingBox(theBoundingRect); } theBoundingRect += (thePosition - theBoundingRect.ul()); thePosition = theBoundingRect.ul(); } void ossimAnnotationFontObject::setRotation(double rotation) { theRotation = rotation; setFontInfo(); if (theFont.valid()) { theFont->getBoundingBox(theBoundingRect); } theBoundingRect += (thePosition - theBoundingRect.ul()); thePosition = theBoundingRect.ul(); } void ossimAnnotationFontObject::setScale(const ossimDpt& scale) { theHorizontalScale = scale.x; theVerticalScale = scale.y; setFontInfo(); if (theFont.valid()) { theFont->getBoundingBox(theBoundingRect); } theBoundingRect += (thePosition - theBoundingRect.ul()); thePosition = theBoundingRect.ul(); } void ossimAnnotationFontObject::setShear(const ossimDpt& shear) { theHorizontalShear = shear.x; theVerticalShear = shear.y; setFontInfo(); if (theFont.valid()) { theFont->getBoundingBox(theBoundingRect); } theBoundingRect += (thePosition - theBoundingRect.ul()); thePosition = theBoundingRect.ul(); } void ossimAnnotationFontObject::setGeometryInformation(const ossimFontInformation& info) { thePixelSize = info.thePointSize; theRotation = info.theRotation; theHorizontalScale = info.theScale.x; theVerticalScale = info.theScale.y; theHorizontalShear = info.theShear.x; theVerticalShear = info.theShear.y; setFontInfo(); if (theFont.valid()) { theFont->getBoundingBox(theBoundingRect); } theBoundingRect += (thePosition - theBoundingRect.ul()); thePosition = theBoundingRect.ul(); } void ossimAnnotationFontObject::applyScale(double x, double y) { thePosition.x = ossim::round(thePosition.x *x); thePosition.y = ossim::round(thePosition.y *y); setFontInfo(); computeBoundingRect(); } ossimObject* ossimAnnotationFontObject::dup()const { return new ossimAnnotationFontObject(*this); } ossim-Miami-2.9.1/src/imaging/ossimAnnotationGdBitmapFont.cpp000066400000000000000000000127061352751253100242530ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimAnnotationGdBitmapFont.cpp 12276 2008-01-07 19:58:43Z dburken $ #include #include #include #include #include #include #include #include using namespace std; ossimAnnotationGdBitmapFont::ossimAnnotationGdBitmapFont(const ossimDpt& position, const ossimString &text, ossimGdFontPtr font, unsigned char r, unsigned char g, unsigned char b, long thickness) :ossimAnnotationObject(r, g, b, thickness), theFontPtr(font), theText(text), thePosition(position) { computeBoundingRect(); } ossimAnnotationGdBitmapFont::ossimAnnotationGdBitmapFont(const ossimAnnotationGdBitmapFont& rhs) : ossimAnnotationObject(rhs), theFontPtr(rhs.theFontPtr), theText(rhs.theText), theBoundingRect(rhs.theBoundingRect), thePosition(rhs.thePosition) { } ossimAnnotationGdBitmapFont::~ossimAnnotationGdBitmapFont() { } void ossimAnnotationGdBitmapFont::getBoundingRect(ossimDrect& rect)const { rect = theBoundingRect; } void ossimAnnotationGdBitmapFont::applyScale(double x, double y) { thePosition.x *= x; thePosition.y *= y; theBoundingRect *= ossimDpt(x, y); } void ossimAnnotationGdBitmapFont::draw(ossimRgbImage& anImage)const { if(!theFontPtr|| !anImage.getImageData()) { return; } ossimDpt origin = anImage.getImageData()->getOrigin(); ossimDrect rect = anImage.getImageData()->getImageRectangle(); if(theBoundingRect.intersects(rect)) { anImage.setDrawColor(theRed, theGreen, theBlue); ossimDpt position(thePosition.x - origin.x, thePosition.y - origin.y); for(std::string::size_type character = 0; character < theText.size(); ++character) { long charOffset = theText[character]; // we need to shift the offset to a positive value. // if it goes negative we just add 256 to the value. if(charOffset < 0) { charOffset += 256; } // get the starting offset to the bitmap long offset = charOffset*theFontPtr->w*theFontPtr->h; for(long row = 0; row < theFontPtr->h; ++row) { for(long col = 0; col < theFontPtr->w; ++col) { if(theFontPtr->data[(int)offset]) { anImage.slowPlotPixel(ossim::round(position.x + col), ossim::round(position.y + row), theRed, theGreen, theBlue); } ++offset; } } position.x += theFontPtr->w; } } } ossimAnnotationObject* ossimAnnotationGdBitmapFont::getNewClippedObject(const ossimDrect& rect)const { ossimAnnotationGdBitmapFont* result = (ossimAnnotationGdBitmapFont*)NULL; if(intersects(rect)) { result = (ossimAnnotationGdBitmapFont*)dup(); } return result; } std::ostream& ossimAnnotationGdBitmapFont::print(std::ostream& out)const { out << "text_value: " << theText << endl << "text_bouding_rect: " << theBoundingRect << endl << "text_position: " << thePosition << endl; return out; } void ossimAnnotationGdBitmapFont::computeBoundingRect() { if(theFontPtr) { theBoundingRect = ossimDrect(thePosition.x, thePosition.y, thePosition.x + theText.size()*theFontPtr->w, thePosition.y + theFontPtr->h); } } void ossimAnnotationGdBitmapFont::setFont(ossimGdFontPtr font) { theFontPtr = font; } void ossimAnnotationGdBitmapFont::setText(const ossimString& text) { theText = text; computeBoundingRect(); } void ossimAnnotationGdBitmapFont::setUpperLeftText(const ossimDpt& upperLeft, const ossimString& text) { setText(text); setUpperLeftTextPosition(upperLeft); } void ossimAnnotationGdBitmapFont::setUpperLeftTextPosition(const ossimDpt& position) { thePosition = position; computeBoundingRect(); } void ossimAnnotationGdBitmapFont::setCenterText(const ossimDpt& upperLeft, const ossimString& text) { setText(text); setCenterTextPosition(upperLeft); } void ossimAnnotationGdBitmapFont::setCenterTextPosition(const ossimDpt& position) { thePosition.x = position.x - theBoundingRect.width()/2.0; thePosition.y = position.y - theBoundingRect.height()/2.0; computeBoundingRect(); } bool ossimAnnotationGdBitmapFont::isPointWithin(const ossimDpt& imagePoint)const { return theBoundingRect.pointWithin(imagePoint); } ossim-Miami-2.9.1/src/imaging/ossimAnnotationLineObject.cpp000066400000000000000000000131341352751253100237470ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationLineObject.cpp 13964 2009-01-14 16:30:07Z gpotts $ #include #include RTTI_DEF1(ossimAnnotationLineObject, "ossimAnnotationLineObject", ossimAnnotationObject) using namespace std; ossimAnnotationLineObject::ossimAnnotationLineObject() :ossimAnnotationObject(), theStart(0,0), theEnd(0,0), theBoundingRect(0,0,0,0) { } ossimAnnotationLineObject::ossimAnnotationLineObject(const ossimIpt& start, const ossimIpt& end, unsigned char r, unsigned char g, unsigned char b, long thickness) :ossimAnnotationObject(r, g, b, thickness), theStart(start), theEnd(end) { computeBoundingRect(); } ossimAnnotationLineObject::ossimAnnotationLineObject(long x1, long y1, long x2, long y2, unsigned char r, unsigned char g, unsigned char b, long thickness) :ossimAnnotationObject(r, g, b, thickness), theStart(x1, y1), theEnd(x2, y2) { computeBoundingRect(); } ossimAnnotationLineObject::ossimAnnotationLineObject(const ossimAnnotationLineObject& rhs) :ossimAnnotationObject(rhs), theStart(rhs.theStart), theEnd(rhs.theEnd), theBoundingRect(rhs.theBoundingRect) { } ossimObject* ossimAnnotationLineObject::dup()const { return new ossimAnnotationLineObject(*this); } void ossimAnnotationLineObject::applyScale(double x, double y) { theStart.x = ossim::round(theStart.x*x); theStart.y = ossim::round(theStart.y*y); theEnd.x = ossim::round(theEnd.x*x); theEnd.y = ossim::round(theEnd.y*y); computeBoundingRect(); } ossimAnnotationObject* ossimAnnotationLineObject::getNewClippedObject(const ossimDrect& rect)const { ossimAnnotationLineObject* result = (ossimAnnotationLineObject*)NULL; ossimDpt start = theStart; ossimDpt end = theEnd; if(rect.clip(start, end)) { result = (ossimAnnotationLineObject*)dup(); result->setLine(start, end); } return result; } bool ossimAnnotationLineObject::intersects(const ossimDrect& rect)const { ossimDpt start = theStart; ossimDpt end = theEnd; return rect.clip(start, end); } void ossimAnnotationLineObject::draw(ossimRgbImage& anImage)const { if(anImage.getImageData().valid()) { anImage.setDrawColor(theRed, theGreen, theBlue); anImage.setThickness(theThickness); ossimDrect imageRect = anImage.getImageData()->getImageRectangle(); ossimDpt start = theStart; ossimDpt end = theEnd; if(anImage.getImageData().valid()) { // we need to extend it by a couple of pixels since // if a pixel lies on the edge and then another pixel is just off // the edge we will get a stair step and so for several pixels // the line might be inside the image rectangle but the clip // algorithm will only draw 1 pixel since it thinks the first // point is inside and the second point is outside and will // execute the clip algorithm keeping only the first // point. ossimDrect clipRect(imageRect.ul().x - 10, imageRect.ul().y - 10, imageRect.lr().x + 10, imageRect.lr().y + 10); // now we can draw. if(clipRect.clip(start, end)) { anImage.drawLine(ossimIpt((int)start.x, (int)start.y), ossimIpt((int)end.x, (int)end.y)); } } } } std::ostream& ossimAnnotationLineObject::print(std::ostream& out)const { out << "line_start: " << theStart << endl << "line_end: " << theEnd << endl << "bounding_rect: " << theBoundingRect << endl; return out; } void ossimAnnotationLineObject::getBoundingRect(ossimDrect& rect)const { rect = theBoundingRect; } void ossimAnnotationLineObject::computeBoundingRect() { vector pts(2); pts[0] = theStart; pts[1] = theEnd; theBoundingRect = ossimDrect(pts); } void ossimAnnotationLineObject::setLine(const ossimDpt& start, const ossimDpt& end) { theStart = start; theEnd = end; computeBoundingRect(); } void ossimAnnotationLineObject::getLine(ossimDpt& start, ossimDpt& end) { start = theStart; end = theEnd; } bool ossimAnnotationLineObject::isPointWithin(const ossimDpt& point)const { if(theBoundingRect.pointWithin(point)) { // we will use the implicit form of a line to determine if the point is // on the line. For now we will just return true if it is within the // bounding rect. return true; } return false; } ossim-Miami-2.9.1/src/imaging/ossimAnnotationMultiEllipseObject.cpp000066400000000000000000000144131352751253100254710ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationMultiEllipseObject.cpp 17195 2010-04-23 17:32:18Z dburken $ #include using namespace std; ossimAnnotationMultiEllipseObject::ossimAnnotationMultiEllipseObject (const std::vector& pointList, const ossimDpt& widthHeight, bool enableFill, unsigned char r, unsigned char g, unsigned char b, long thickness) : ossimAnnotationObject(r, g, b, thickness), thePointList(pointList), theWidthHeight(widthHeight), theFillFlag(enableFill) { computeBoundingRect(); } ossimAnnotationMultiEllipseObject::ossimAnnotationMultiEllipseObject (const ossimDpt& widthHeight, bool enableFill, unsigned char r, unsigned char g, unsigned char b, long thickness) : ossimAnnotationObject(r, g, b, thickness), theWidthHeight(widthHeight), theFillFlag(enableFill) { theBoundingRect.makeNan(); } ossimAnnotationMultiEllipseObject::ossimAnnotationMultiEllipseObject(const ossimAnnotationMultiEllipseObject& rhs) :thePointList(rhs.thePointList), theWidthHeight(rhs.theWidthHeight), theFillFlag(rhs.theFillFlag), theBoundingRect(rhs.theBoundingRect) { } ossimObject* ossimAnnotationMultiEllipseObject::dup()const { return new ossimAnnotationMultiEllipseObject(*this); } ossimAnnotationMultiEllipseObject::~ossimAnnotationMultiEllipseObject() {} ossimAnnotationObject* ossimAnnotationMultiEllipseObject::getNewClippedObject( const ossimDrect& /* rect */)const { ossimNotify(ossimNotifyLevel_WARN) << "ossimAnnotationMultiEllipseObject::getNewClippedObject WARNING: Not implemented" << std::endl; return NULL; } void ossimAnnotationMultiEllipseObject::applyScale(double x, double y) { int i; int upper = (int)thePointList.size(); for(i = 0; i < upper; ++i) { thePointList[i].x *= x; thePointList[i].y *= y; } theWidthHeight.x *= x; theWidthHeight.y *= y; computeBoundingRect(); } void ossimAnnotationMultiEllipseObject::draw(ossimRgbImage& anImage)const { anImage.setDrawColor(theRed, theGreen, theBlue); anImage.setThickness(theThickness); ossimDrect imageRect = anImage.getImageData()->getImageRectangle(); if(theBoundingRect.intersects(imageRect)) { int i; int upper = (int)thePointList.size(); if(theFillFlag) { for(i = 0; i < upper; ++i) { ossimDpt tempPoint = thePointList[i]; ossimDrect tempRect(ossimDpt(tempPoint.x - theWidthHeight.x, tempPoint.y - theWidthHeight.y), ossimDpt(tempPoint.x + theWidthHeight.x, tempPoint.y + theWidthHeight.y)); if(tempRect.intersects(imageRect)) { anImage.drawFilledArc(ossim::round(tempPoint.x), ossim::round(tempPoint.y), ossim::round(theWidthHeight.x), ossim::round(theWidthHeight.y), 0, 360); } } } else { for(i = 0; i < upper; ++i) { ossimDpt tempPoint = thePointList[i]; ossimDrect tempRect(ossimDpt(tempPoint.x - theWidthHeight.x, tempPoint.y - theWidthHeight.y), ossimDpt(tempPoint.x + theWidthHeight.x, tempPoint.y + theWidthHeight.y)); if(tempRect.intersects(imageRect)) { anImage.drawArc(ossim::round(tempPoint.x), ossim::round(tempPoint.y), ossim::round(theWidthHeight.x), ossim::round(theWidthHeight.y), 0, 360); } } } } } bool ossimAnnotationMultiEllipseObject::intersects(const ossimDrect& rect)const { return rect.intersects(theBoundingRect); } std::ostream& ossimAnnotationMultiEllipseObject::print(std::ostream& out)const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimAnnotionMultiEllipseObject::print NOT IMPLEMENTED" << endl; return out; } void ossimAnnotationMultiEllipseObject::getBoundingRect(ossimDrect& rect)const { rect = theBoundingRect; } void ossimAnnotationMultiEllipseObject::computeBoundingRect() { theBoundingRect.makeNan(); int i; int upper = (int)thePointList.size(); for(i = 0; i < upper; ++i) { ossimDpt tempPoint = thePointList[i]; if(!tempPoint.hasNans()) { ossimDrect tempRect(ossimDpt(tempPoint.x - theWidthHeight.x, tempPoint.y - theWidthHeight.y), ossimDpt(tempPoint.x + theWidthHeight.x, tempPoint.y + theWidthHeight.y)); if(!theBoundingRect.hasNans()) { theBoundingRect.combine(tempRect); } else { theBoundingRect = tempRect; } } } } bool ossimAnnotationMultiEllipseObject::isPointWithin(const ossimDpt& imagePoint)const { if(!theBoundingRect.hasNans()) { return theBoundingRect.pointWithin(imagePoint); } return false; } void ossimAnnotationMultiEllipseObject::setFillFlag(bool flag) { theFillFlag = flag; } void ossimAnnotationMultiEllipseObject::resize(ossim_uint32 size) { if(size) { thePointList.resize(size); } else { thePointList.clear(); } } void ossimAnnotationMultiEllipseObject::setWidthHeight(const ossimDpt& widthHeight) { theWidthHeight = widthHeight; computeBoundingRect(); } ossimDpt& ossimAnnotationMultiEllipseObject::operator[](int i) { return thePointList[i]; } const ossimDpt& ossimAnnotationMultiEllipseObject::operator[](int i)const { return thePointList[i]; } ossim-Miami-2.9.1/src/imaging/ossimAnnotationMultiLineObject.cpp000066400000000000000000000131631352751253100247640ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationMultiLineObject.cpp 9094 2006-06-13 19:12:40Z dburken $ #include RTTI_DEF1(ossimAnnotationMultiLineObject, "ossimAnnotationMultiLineObject", ossimAnnotationObject); using namespace std; void ossimAnnotationMultiLineObject::draw(ossimRgbImage& anImage)const { if(anImage.getImageData().valid()) { anImage.setDrawColor(theRed, theGreen, theBlue); anImage.setThickness(theThickness); ossimDrect imageRect = anImage.getImageData()->getImageRectangle(); if(theBoundingRect.intersects(imageRect)) { // we need to extend it by a couple of pixels since // if a pixel lies on the edge and then another pixel is just off // the edge we will get a stair step and so for several pixels // the line might be inside the image rectangle but the clip // algorithm will only draw 1 pixel since it thinks the first // point is inside and the second point is outside and will // execute the clip algorithm keeping only the first // point. ossimDrect clipRect(imageRect.ul().x - 10, imageRect.ul().y - 10, imageRect.lr().x + 10, imageRect.lr().y + 10); for(ossim_uint32 i = 0; i < thePolyLineList.size(); ++i) { const vector& vList = thePolyLineList[i].getVertexList(); if(vList.size() == 1) { anImage.drawLine(ossimIpt(vList[0]), ossimIpt(vList[0])); } else { for(ossim_uint32 i2 = 0; i2 < (vList.size()-1); ++i2) { ossimDpt start = vList[i2]; ossimDpt end = vList[i2+1]; // now we can draw. if(clipRect.clip(start, end)) { anImage.drawLine(ossimIpt((int)start.x, (int)start.y), ossimIpt((int)end.x, (int)end.y)); } } } } } } } bool ossimAnnotationMultiLineObject::intersects(const ossimDrect& rect)const { for(ossim_uint32 i = 0; i < thePolyLineList.size(); ++i) { if(thePolyLineList[i].isWithin(rect)) { return true; } } return false; } void ossimAnnotationMultiLineObject::applyScale(double x, double y) { for(ossim_uint32 i=0; i < thePolyLineList.size(); ++i) { vector& vList = thePolyLineList[i].getVertexList(); for(ossim_uint32 i2 = 0; i2 < vList.size(); ++i2) { vList[i].x *= x; vList[i].y *= y; vList[i].x *= x; vList[i].y *= y; } } theBoundingRect *= ossimDpt(x, y); } ossimAnnotationObject* ossimAnnotationMultiLineObject::getNewClippedObject(const ossimDrect& rect)const { ossimAnnotationMultiLineObject* result = (ossimAnnotationMultiLineObject*)NULL; if(intersects(rect)) { vector lineList; vector tempResult; ossimDrect clipRect(rect.ul().x - 10, rect.ul().y - 10, rect.lr().x + 10, rect.lr().y + 10); for(ossim_uint32 i =0; i< thePolyLineList.size();++i) { if(thePolyLineList[i].clipToRect(tempResult, clipRect)) { lineList.insert(lineList.end(), tempResult.begin(), tempResult.end()); } } if(lineList.size() > 0) { result = new ossimAnnotationMultiLineObject(lineList, theRed, theGreen, theBlue, theThickness); } } return result; } bool ossimAnnotationMultiLineObject::isPointWithin(const ossimDpt& imagePoint)const { for(ossim_uint32 i=0; i < thePolyLineList.size(); ++i) { if(thePolyLineList[i].isPointWithin(imagePoint)) { return true; } } return false; } void ossimAnnotationMultiLineObject::computeBoundingRect() { theBoundingRect.makeNan(); if(thePolyLineList.size() == 1) { theBoundingRect = thePolyLineList[0].getBoundingRect(); } else if(thePolyLineList.size() > 1) { for(ossim_uint32 i = 0; i < thePolyLineList.size(); ++i) { ossimDrect rect = thePolyLineList[i].getBoundingRect(); if(theBoundingRect.hasNans()) { theBoundingRect = rect; } else if(!rect.hasNans()) { theBoundingRect = theBoundingRect.combine(rect); } } } } std::ostream& ossimAnnotationMultiLineObject::print(std::ostream& out)const { ossimAnnotationObject::print(out); for(ossim_uint32 i = 0; i < thePolyLineList.size();++i) { out << thePolyLineList[i] << endl <<"______________________________________"< #include #include #include #include #include RTTI_DEF1(ossimAnnotationMultiPolyLineObject, "ossimAnnotationMultiPolyLineObject", ossimAnnotationObject) using namespace std; ossimAnnotationMultiPolyLineObject::ossimAnnotationMultiPolyLineObject() :ossimAnnotationObject() { computeBoundingRect(); } ossimAnnotationMultiPolyLineObject::ossimAnnotationMultiPolyLineObject(const vector& multiPoly, unsigned char r, unsigned char g, unsigned char b, long thickness) :ossimAnnotationObject(r, g, b, thickness) { theMultiPolyLine = multiPoly; computeBoundingRect(); } ossimAnnotationMultiPolyLineObject::~ossimAnnotationMultiPolyLineObject() { } void ossimAnnotationMultiPolyLineObject::applyScale(double x, double y) { for(ossim_uint32 i =0; i result; if(theMultiPolyLine[i].clipToRect(result, rect)) { return true; } } return false; } ossimAnnotationObject* ossimAnnotationMultiPolyLineObject::getNewClippedObject( const ossimDrect& /* rect */)const { ossimAnnotationObject* result = (ossimAnnotationObject*)NULL; ossimNotify(ossimNotifyLevel_WARN) << "ossimAnnotationMultiPolyLineObject::getNewClippedObject\n" << "Not implemented for " << getClassName() << endl; return result; } void ossimAnnotationMultiPolyLineObject::draw(ossimRgbImage& anImage)const { if(theMultiPolyLine.size()<1) return; if(theBoundingRect.hasNans()) return; anImage.setDrawColor(theRed, theGreen, theBlue); anImage.setThickness(theThickness); ossimDrect imageRect = anImage.getImageData()->getImageRectangle(); if(theBoundingRect.intersects(imageRect)) { // we need to extend it by a couple of pixels since // if a pixel lies on the edge and then another pixel is just off // the edge we will get a stair step and so for several pixels // the line might be inside the image rectangle but the clip // algorithm will only draw 1 pixel since it thinks the first // point is inside and the second point is outside and will // execute the clip algorithm keeping only the first // point. ossimDrect clipRect(imageRect.ul().x - 10, imageRect.ul().y - 10, imageRect.lr().x + 10, imageRect.lr().y + 10); int j = 0; for(ossim_uint32 i = 0; i < theMultiPolyLine.size(); ++i) { const ossimPolyLine& poly = theMultiPolyLine[i]; int vertexCount = poly.getNumberOfVertices(); if(vertexCount > 1) { ossimDpt start, end; start = poly[0]; end = poly[1]; j = 1; do { if(clipRect.clip(start, end)) { anImage.drawLine(ossimIpt(start), ossimIpt(end)); } ++j; start = poly[j-1]; end = poly[j]; }while(j < vertexCount); } else if(vertexCount == 1) { anImage.drawLine(ossimIpt(poly[0]), ossimIpt(poly[0])); } } } } std::ostream& ossimAnnotationMultiPolyLineObject::print(std::ostream& out)const { ossimAnnotationObject::print(out); out << endl; out << setw(15)<& multiPoly) { theMultiPolyLine = multiPoly; computeBoundingRect(); } const std::vector& ossimAnnotationMultiPolyLineObject::getMultiPolyLine()const { return theMultiPolyLine; } std::vector& ossimAnnotationMultiPolyLineObject::getMultiPolyLine() { return theMultiPolyLine; } ossim-Miami-2.9.1/src/imaging/ossimAnnotationMultiPolyObject.cpp000066400000000000000000000236711352751253100250250ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimAnnotationMultiPolyObject.cpp 10867 2007-05-09 19:58:25Z gpotts $ #include #include #include #include #include #include RTTI_DEF1(ossimAnnotationMultiPolyObject, "ossimAnnotationMultiPolyObject", ossimAnnotationObject) using namespace std; ossimAnnotationMultiPolyObject::ossimAnnotationMultiPolyObject() :ossimAnnotationObject(), theFillEnabled(false) { computeBoundingRect(); } ossimAnnotationMultiPolyObject::ossimAnnotationMultiPolyObject(const vector& multiPoly, bool enableFill, unsigned char r, unsigned char g, unsigned char b, long thickness) :ossimAnnotationObject(r, g, b, thickness), theFillEnabled(enableFill) { theMultiPolygon = multiPoly; computeBoundingRect(); } ossimAnnotationMultiPolyObject::~ossimAnnotationMultiPolyObject() { } void ossimAnnotationMultiPolyObject::applyScale(double x, double y) { for(ossim_uint32 i =0; i result; if(theMultiPolygon[i].clipToRect(result, rect)) { return true; } } return false; } ossimAnnotationObject* ossimAnnotationMultiPolyObject::getNewClippedObject(const ossimDrect& rect)const { ossimAnnotationObject* result = (ossimAnnotationObject*)NULL; if(theBoundingRect.intersects(rect)) { ossimDrect clipRect(rect.ul().x - 10, rect.ul().y - 10, rect.lr().x + 10, rect.lr().y + 10); if(theFillEnabled) { vector polyListResult; for(ossim_uint32 i = 0; i < theMultiPolygon.size(); ++i) { vector tempList; if(theMultiPolygon[i].clipToRect(tempList, rect)) { polyListResult.insert(polyListResult.end(), tempList.begin(), tempList.end()); } } if(polyListResult.size()) { result = new ossimAnnotationMultiPolyObject(polyListResult, theFillEnabled, theRed, theGreen, theBlue, theThickness); } } else { vector lineListResult; vector tempResult; for(ossim_uint32 i = 0; i< theMultiPolygon.size();++i) { ossimPolyLine polyLine = theMultiPolygon[i]; if(polyLine.clipToRect(tempResult, clipRect)) { lineListResult.insert(lineListResult.end(), tempResult.begin(), tempResult.end()); } } if(lineListResult.size()) { result = new ossimAnnotationMultiLineObject(lineListResult, theRed, theGreen, theBlue, theThickness); } } } return result; } void ossimAnnotationMultiPolyObject::draw(ossimRgbImage& anImage)const { if(theMultiPolygon.size()<1) return; if(theBoundingRect.hasNans()) return; anImage.setDrawColor(theRed, theGreen, theBlue); anImage.setThickness(theThickness); ossimDrect imageRect = anImage.getImageData()->getImageRectangle(); if(theBoundingRect.intersects(imageRect)) { // we need to extend it by a couple of pixels since // if a pixel lies on the edge and then another pixel is just off // the edge we will get a stair step and so for several pixels // the line might be inside the image rectangle but the clip // algorithm will only draw 1 pixel since it thinks the first // point is inside and the second point is outside and will // execute the clip algorithm keeping only the first // point. ossimDrect clipRect(imageRect.ul().x - 10, imageRect.ul().y - 10, imageRect.lr().x + 10, imageRect.lr().y + 10); int j = 0; for(ossim_uint32 i = 0; i < theMultiPolygon.size(); ++i) { const ossimPolygon& poly = theMultiPolygon[i]; int vertexCount = poly.getVertexCount(); if(!theFillEnabled) { if(poly.getNumberOfVertices() == 1) { ossimDpt start, end; start = poly[0]; end = poly[0]; if(clipRect.clip(start, end)) { anImage.drawLine(ossimIpt(start), ossimIpt(end)); } } else if(poly.getNumberOfVertices() == 2) { ossimDpt start, end; start = poly[0]; end = poly[1]; if(clipRect.clip(start, end)) { anImage.drawLine(ossimIpt(start), ossimIpt(end)); } } else if(vertexCount > 2) { ossimDpt start, end; j = 0; while(j result; if(poly.clipToRect(result, imageRect)) { for(j = 0; j < (int)result.size();++j) { anImage.drawFilledPolygon(result[j].getVertexList()); } } } } } } std::ostream& ossimAnnotationMultiPolyObject::print(std::ostream& out)const { ossimAnnotationObject::print(out); out << endl; out << setw(15)< RTTI_DEF1(ossimAnnotationObject, "ossimAnnotationObject", ossimObject) ossim_uint32 ossimAnnotationObject::theIdCounter = 0; using namespace std; ossimAnnotationObject::~ossimAnnotationObject() {} void ossimAnnotationObject::restIdCounter() { theIdCounter = 0; } ossim_uint32 ossimAnnotationObject::getNextId() { ossim_uint32 id = theIdCounter; ++theIdCounter; return id; } ossimAnnotationObject::ossimAnnotationObject(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b, ossim_uint8 thickness) :theRed(r), theGreen(g), theBlue(b), theThickness(thickness) { theId = getNextId(); } void ossimAnnotationObject::setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { theRed = r; theGreen = g; theBlue = b; } void ossimAnnotationObject::setThickness(ossim_uint8 thickness) { theThickness = thickness; } void ossimAnnotationObject::getColor(ossim_uint8 &r, ossim_uint8 &g, ossim_uint8 &b)const { r = theRed; g = theGreen; b = theBlue; } ossim_uint8 ossimAnnotationObject::getThickness()const { return theThickness; } ossim_uint32 ossimAnnotationObject::getId()const { return theId; } ossim_uint32 ossimAnnotationObject::setId() { theId = getNextId(); return getId(); } bool ossimAnnotationObject::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, "red", theRed); kwl.add(prefix, "green", theGreen); kwl.add(prefix, "blue", theBlue); kwl.add(prefix, "thickness", theThickness); return ossimObject::saveState(kwl, prefix); } bool ossimAnnotationObject::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* red = kwl.find(prefix, "red"); const char* green = kwl.find(prefix, "green"); const char* blue = kwl.find(prefix, "blue"); const char* thickness = kwl.find(prefix, "thickness"); if(red) { theRed = (ossim_uint8)ossimString(red).toLong(); } if(green) { theGreen = (ossim_uint8)ossimString(green).toLong(); } if(blue) { theBlue = (ossim_uint8)ossimString(blue).toLong(); } if(thickness) { theThickness = (ossim_uint8)ossimString(thickness).toLong(); } return ossimObject::loadState(kwl, prefix); } bool ossimAnnotationObject::isPointWithin(const ossimDpt& /* imagePoint */) const { return false; } ossimString ossimAnnotationObject::getName()const { return theName; } void ossimAnnotationObject::setName(const ossimString& name) { theName = name; } ossimDrect ossimAnnotationObject::getBoundingRect()const { ossimDrect rect; getBoundingRect(rect); return rect; } void ossimAnnotationObject::applyScale(const ossimDpt& scale) { applyScale(scale.x, scale.y); } std::ostream& ossimAnnotationObject::print(ostream& out) const { out << setw(15)< #include #include #include #include ossimAnnotationObjectFactory* ossimAnnotationObjectFactory::theInstance=NULL; using namespace std; ossimAnnotationObjectFactory::ossimAnnotationObjectFactory() :ossimFactoryBase() { } ossimAnnotationObject* ossimAnnotationObjectFactory::create( const ossimString& spec) const { if(spec == STATIC_TYPE_NAME(ossimGeoAnnotationEllipseObject)) { return new ossimGeoAnnotationEllipseObject; } if(spec == STATIC_TYPE_NAME(ossimGeoAnnotationFontObject)) { return new ossimGeoAnnotationFontObject; } if(spec == STATIC_TYPE_NAME(ossimGeoAnnotationMultiPolyLineObject)) { return new ossimGeoAnnotationMultiPolyLineObject; } if(spec == STATIC_TYPE_NAME(ossimGeoAnnotationPolyObject)) { return new ossimGeoAnnotationPolyObject; } return NULL; } ossimAnnotationObject* ossimAnnotationObjectFactory::create( const ossimKeywordlist& kwl, const char* prefix) const { ossimAnnotationObject* result = NULL; const char* type = kwl.find(prefix, "type"); if(type) { result = create(ossimString(type)); if(result) { result->loadState(kwl, prefix); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimAnnotationObjectFactory::create WARNING" << "Unable to create object of type: " << type << std::endl; } } return result; } ossimAnnotationObjectFactory* ossimAnnotationObjectFactory::instance() { if(!theInstance) { theInstance = new ossimAnnotationObjectFactory(); } return theInstance; } //***************************************************************************** // METHOD: ossimProjectionFactory::getList() // //***************************************************************************** list ossimAnnotationObjectFactory::getList() const { list rtn_list; list sub_list; list*>::const_iterator factory; factory = theRegistry.begin(); while(factory != theRegistry.end()) { sub_list = (*factory)->getList(); rtn_list.merge(sub_list); ++factory; } return rtn_list; } ossim-Miami-2.9.1/src/imaging/ossimAnnotationPolyObject.cpp000066400000000000000000000227401352751253100240060ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationPolyObject.cpp 13964 2009-01-14 16:30:07Z gpotts $ #include #include #include #include #include RTTI_DEF1(ossimAnnotationPolyObject, "ossimAnnotationPolyObject", ossimAnnotationObject) using namespace std; ossimAnnotationPolyObject::ossimAnnotationPolyObject(bool enableFill, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b, ossim_uint8 thickness) :ossimAnnotationObject(r, g, b, thickness), thePolygon(), theBoundingRect(), theFillEnabled(enableFill) { } ossimAnnotationPolyObject::ossimAnnotationPolyObject( const vector& imagePts, bool enableFill, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b, ossim_uint8 thickness) :ossimAnnotationObject(r, g, b, thickness), theFillEnabled(enableFill) { thePolygon = imagePts; computeBoundingRect(); } ossimAnnotationPolyObject::ossimAnnotationPolyObject( const ossimAnnotationPolyObject& rhs) : ossimAnnotationObject(rhs), thePolygon(rhs.thePolygon), theBoundingRect(rhs.theBoundingRect), theFillEnabled(rhs.theFillEnabled) { } ossimObject* ossimAnnotationPolyObject::dup()const { return new ossimAnnotationPolyObject(*this); } ossimAnnotationPolyObject::~ossimAnnotationPolyObject() { } void ossimAnnotationPolyObject::applyScale(double x, double y) { thePolygon *= ossimDpt(x, y); computeBoundingRect(); } bool ossimAnnotationPolyObject::intersects(const ossimDrect& rect)const { // do the quick checks first // if(rect.hasNans()) return false; if(!rect.intersects(theBoundingRect)) return false; if(!theFillEnabled) { int vertexCount = thePolygon.getVertexCount(); ossimDpt start, end; int j = 0; while(j result; return thePolygon.clipToRect(result, rect); } return false; } ossimAnnotationObject* ossimAnnotationPolyObject::getNewClippedObject(const ossimDrect& rect)const { ossimAnnotationObject* result = (ossimAnnotationObject*)NULL; if(theBoundingRect.intersects(rect)) { if(theFillEnabled) { vector resultPoly; if(thePolygon.clipToRect(resultPoly, rect)) { if(resultPoly.size() == 1) { result = new ossimAnnotationPolyObject(resultPoly[0].getVertexList(), theFillEnabled, theRed, theGreen, theBlue, theThickness); } else { result = new ossimAnnotationMultiPolyObject(resultPoly, theFillEnabled, theRed, theGreen, theBlue, theThickness); } } } else { vector lineListResult; ossimPolyLine polyLine = thePolygon; if(polyLine.clipToRect(lineListResult, rect)) { result = new ossimAnnotationMultiLineObject(lineListResult, theRed, theGreen, theBlue, theThickness); } } } return result; } void ossimAnnotationPolyObject::draw(ossimRgbImage& anImage)const { if(thePolygon.getVertexCount() < 2) return; if(theBoundingRect.hasNans()) return; int vertexCount = thePolygon.getVertexCount(); anImage.setDrawColor(theRed, theGreen, theBlue); anImage.setThickness(theThickness); ossimDrect imageRect = anImage.getImageData()->getImageRectangle(); if(theBoundingRect.intersects(imageRect)) { // we need to extend it by a couple of pixels since // if a pixel lies on the edge and then another pixel is just off // the edge we will get a stair step and so for several pixels // the line might be inside the image rectangle but the clip // algorithm will only draw 1 pixel since it thinks the first // point is inside and the second point is outside and will // execute the clip algorithm keeping only the first // point. ossimDrect clipRect(imageRect.ul().x - 10, imageRect.ul().y - 10, imageRect.lr().x + 10, imageRect.lr().y + 10); if(!theFillEnabled) { ossimDpt start, end; if(thePolygon.getNumberOfVertices() == 1) { start = thePolygon[0]; end = thePolygon[0]; if(clipRect.clip(start, end)) { anImage.drawLine(ossimIpt(start), ossimIpt(end)); } } else if(thePolygon.getNumberOfVertices() == 2) { start = thePolygon[0]; end = thePolygon[1]; if(clipRect.clip(start, end)) { anImage.drawLine(ossimIpt(start), ossimIpt(end)); } } else { int j = 0; while(j result; if(thePolygon.clipToRect(result, imageRect)) { for(int i = 0; i < (int)result.size();++i) { anImage.drawFilledPolygon(result[i].getVertexList()); } } } } } std::ostream& ossimAnnotationPolyObject::print(std::ostream& out)const { out << "number_of_points: " << thePolygon.getVertexCount(); if(thePolygon.getVertexCount() > 0) { for(long index =0; index < (long)(thePolygon.getVertexCount()-1); ++index) { out << thePolygon[index] << endl; } out << thePolygon[thePolygon.getVertexCount()-1] << endl; } out << "fill_enabled: " << theFillEnabled << endl << "bounding_rect: " << theBoundingRect << endl; return out; } void ossimAnnotationPolyObject::getBoundingRect(ossimDrect& rect)const { rect = theBoundingRect; } void ossimAnnotationPolyObject::addPoint(const ossimDpt& pt) { thePolygon.addPoint(pt); } void ossimAnnotationPolyObject::setPolygon(const vector& imagePoints) { thePolygon = imagePoints; } void ossimAnnotationPolyObject::setPolygon(const ossimPolygon& polygon) { thePolygon = polygon; } void ossimAnnotationPolyObject::setPolygon(const ossimIrect& rect) { thePolygon = rect; } void ossimAnnotationPolyObject::setPolygon(const ossimDrect& rect) { thePolygon = rect; } void ossimAnnotationPolyObject::computeBoundingRect() { theBoundingRect = ossimDrect(thePolygon); } bool ossimAnnotationPolyObject::isPointWithin(const ossimDpt& imagePoint)const { return theBoundingRect.pointWithin(imagePoint); } const ossimPolygon& ossimAnnotationPolyObject::getPolygon() const { return thePolygon; } ossimPolygon& ossimAnnotationPolyObject::getPolygon() { return thePolygon; } void ossimAnnotationPolyObject::setFillFlag(bool flag) { theFillEnabled = flag; } ossim-Miami-2.9.1/src/imaging/ossimAnnotationSource.cpp000066400000000000000000000251371352751253100231770ustar00rootroot00000000000000//******************************************************************* // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimAnnotationSource.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include RTTI_DEF1(ossimAnnotationSource, "ossimAnnotationSource", ossimImageSourceFilter) using namespace std; ossimAnnotationSource::ossimAnnotationSource(ossimImageSource* inputSource) : ossimImageSourceFilter(inputSource), theRectangle(0, 0, 0, 0), theNumberOfBands(1), theImage(0), theTile(0), theAnnotationObjectList() { theRectangle.makeNan(); } ossimAnnotationSource::~ossimAnnotationSource() { deleteAll(); destroy(); } void ossimAnnotationSource::destroy() { // theImage is an ossimRefPtr so this is not a leak. theImage = 0; // theTile is an ossimRefPtr so this is not a leak. theTile = 0; } void ossimAnnotationSource::allocate(const ossimIrect& rect) { if (!theImage) { theImage = new ossimRgbImage(); } if (!theTile) { theTile = new ossimU8ImageData( this, theNumberOfBands, rect.width(), rect.height() ); theTile->initialize(); } } ossimScalarType ossimAnnotationSource::getOutputScalarType() const { if(theInputConnection && !isSourceEnabled()) { return theInputConnection->getOutputScalarType(); } return OSSIM_UINT8; } ossim_uint32 ossimAnnotationSource::getNumberOfOutputBands()const { if(theInputConnection && !isSourceEnabled()) { return theInputConnection->getNumberOfOutputBands(); } return theNumberOfBands; } void ossimAnnotationSource::initialize() { //--- // Call the base class initialize. // Note: This will reset "theInputConnection" if it changed... //--- ossimImageSourceFilter::initialize(); if (theInputConnection) { computeBoundingRect(); // This will call destroy on band count change. setNumberOfBands(theInputConnection->getNumberOfOutputBands()); } else { destroy(); } } ossimIrect ossimAnnotationSource::getBoundingRect(ossim_uint32 resLevel)const { ossimIrect result; result.makeNan(); if(theInputConnection) { ossimIrect temp = theInputConnection->getBoundingRect(resLevel); result = temp; } if(result.hasNans()) { result = theRectangle; } else if(!theRectangle.hasNans()) { result.combine(theRectangle); } return result; } void ossimAnnotationSource::setNumberOfBands(ossim_uint32 bands) { theNumberOfBands = bands; if (theTile.get()) { if ( theNumberOfBands != theTile->getNumberOfBands() ) { //--- // This will wide things slick and force an allocate() // call on first getTile(). //--- destroy(); } } } ossimRefPtr ossimAnnotationSource::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { ossimRefPtr inputTile = 0; //--- // NOTE: // This source is written to be used with or without an input connection. // So any call to inputTile should be preceeded by: if (inputTile.valid())" //--- if(theInputConnection) { // Fetch tile from pointer from the input source. inputTile = theInputConnection->getTile(tile_rect, resLevel); } // Check for remap bypass: if ( !theEnableFlag ) { return inputTile; } // Check for first time through or reallocation force by band change. if ( !theTile ) { allocate(tile_rect); } // Allocation failed! if(!theTile) { return inputTile; } //--- // Set the image rectangle and bands. This will set the origin. // // NOTE: We do this before the "theTile->makeBlank()" call for efficiency // since this will force a "ossimImageData::initialize()", which performs // a "makeBlank" if a resize is needed due to tile rectangle or number // of band changes. //--- theTile->setImageRectangleAndBands( tile_rect, theNumberOfBands ); //--- // Start with a blank tile. // // NOTE: This will not do anything if already blank. //--- theTile->makeBlank(); if(inputTile.valid() && inputTile->getBuf()&& (inputTile->getDataObjectStatus()!=OSSIM_EMPTY)) { //--- // Copy the input tile to the output tile performing scalar remap if // needed. //--- theTile->loadTile(inputTile.get()); } // Annotate the output tile. drawAnnotations(theTile); theTile->validate(); return theTile; } bool ossimAnnotationSource::addObject(ossimAnnotationObject* anObject) { if(anObject) { theAnnotationObjectList.push_back(anObject); return true; } return false; } bool ossimAnnotationSource::deleteObject(ossimAnnotationObject* anObject) { if(anObject) { AnnotationObjectListType::iterator current = theAnnotationObjectList.begin(); while(current != theAnnotationObjectList.end()) { if(*current == anObject) { theAnnotationObjectList.erase(current); return true; } ++current; } } return false; } bool ossimAnnotationSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { // Save the state of all annotation objects we have. AnnotationObjectListType::const_iterator obj = theAnnotationObjectList.begin(); ossim_uint32 objIdx = 0; while (obj < theAnnotationObjectList.end()) { ossimString newPrefix = prefix; newPrefix += (ossimString("object") + ossimString::toString(objIdx) + ossimString(".")); (*obj)->saveState(kwl, newPrefix.c_str()); ++objIdx; ++obj; } return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimAnnotationSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossim_uint32 index = 0; ossimString copyPrefix = prefix; ossim_uint32 result = kwl.getNumberOfSubstringKeys(copyPrefix + "object[0-9]+\\."); ossim_uint32 numberOfMatches = 0; const ossim_uint32 MAX_INDEX = result + 100; while(numberOfMatches < result) { ossimString newPrefix = copyPrefix; newPrefix += ossimString("object"); newPrefix += ossimString::toString(index); newPrefix += ossimString("."); const char* lookup = kwl.find(newPrefix.c_str(), "type"); if (lookup) { ++numberOfMatches; ossimRefPtr obj = 0; obj = ossimAnnotationObjectFactory::instance()-> create(kwl, newPrefix.c_str()); if (obj.valid()) { if(!addObject(obj.get())) { ossimNotify(ossimNotifyLevel_WARN) << "ossimGeoAnnotationSource::loadState\n" << "Object " << obj->getClassName() << " is not a geographic object" << endl; obj = 0; } } } ++index; if (index > MAX_INDEX) // Avoid infinite loop... { break; } } return ossimImageSourceFilter::loadState(kwl, prefix); } void ossimAnnotationSource::computeBoundingRect() { theRectangle.makeNan(); if(theAnnotationObjectList.size()>0) { ossimDrect rect; theAnnotationObjectList[0]->computeBoundingRect(); theAnnotationObjectList[0]->getBoundingRect(theRectangle); AnnotationObjectListType::iterator object = (theAnnotationObjectList.begin()+1); while(object != theAnnotationObjectList.end()) { (*object)->computeBoundingRect(); (*object)->getBoundingRect(rect); if(theRectangle.hasNans()) { theRectangle = rect; } else if(!rect.hasNans()) { theRectangle = theRectangle.combine(rect); } ++object; } } } ossimAnnotationSource::AnnotationObjectListType ossimAnnotationSource::pickObjects( const ossimDpt& imagePoint) { AnnotationObjectListType result; AnnotationObjectListType::iterator currentObject; currentObject = theAnnotationObjectList.begin(); while(currentObject != theAnnotationObjectList.end()) { if((*currentObject)->isPointWithin(imagePoint)) { result.push_back(*currentObject); } ++currentObject; } return result; } ossimAnnotationSource::AnnotationObjectListType ossimAnnotationSource::pickObjects( const ossimDrect& imageRect) { AnnotationObjectListType result; AnnotationObjectListType::iterator currentObject; currentObject = theAnnotationObjectList.begin(); while(currentObject != theAnnotationObjectList.end()) { ossimRefPtr current = (*currentObject); if(current->isPointWithin(imageRect.ul())) { result.push_back(*currentObject); } else if(current->isPointWithin(imageRect.ll())) { result.push_back(*currentObject); } else if(current->isPointWithin(imageRect.lr())) { result.push_back(*currentObject); } else if(current->isPointWithin(imageRect.ur())) { result.push_back(*currentObject); } ++currentObject; } return result; } void ossimAnnotationSource::deleteAll() { AnnotationObjectListType::iterator obj; theAnnotationObjectList.clear(); } void ossimAnnotationSource::drawAnnotations(ossimRefPtr tile) { theImage->setCurrentImageData(tile); if(theImage->getImageData().valid()) { AnnotationObjectListType::iterator object = theAnnotationObjectList.begin(); while(object != theAnnotationObjectList.end()) { if((*object).valid()) { (*object)->draw(*theImage); } ++object; } } } const ossimAnnotationSource::AnnotationObjectListType& ossimAnnotationSource::getObjectList()const { return theAnnotationObjectList; } ossimAnnotationSource::AnnotationObjectListType& ossimAnnotationSource::getObjectList() { return theAnnotationObjectList; } ossim-Miami-2.9.1/src/imaging/ossimAppFixedTileCache.cpp000066400000000000000000000274531352751253100231510ustar00rootroot00000000000000//****************************************************************** // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This file contains the Application cache algorithm // //*********************************** // $Id: ossimAppFixedTileCache.cpp 20127 2011-10-12 11:27:10Z gpotts $ #include #include #include #include #include #include #include ossimAppFixedTileCache* ossimAppFixedTileCache::theInstance = 0; ossimAppFixedTileCache::ossimAppFixedCacheId ossimAppFixedTileCache::theUniqueAppIdCounter = 0; const ossim_uint32 ossimAppFixedTileCache::DEFAULT_SIZE = 1024*1024*80; using namespace std; static const ossimTrace traceDebug("ossimAppFixedTileCache:debug"); std::ostream& operator <<(std::ostream& out, const ossimAppFixedTileCache& rhs) { std::map::const_iterator iter = rhs.theAppCacheMap.begin(); if(iter == rhs.theAppCacheMap.end()) { ossimNotify(ossimNotifyLevel_NOTICE) << "***** APP CACHE EMPTY *****" << endl; } else { while(iter != rhs.theAppCacheMap.end()) { out << "Cache id = "<< (*iter).first << " size = " << (*iter).second->getCacheSize() << endl; ++iter; } } return out; } ossimAppFixedTileCache::ossimAppFixedTileCache() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAppFixedTileCache::ossimAppFixedTileCache() DEBUG: entered ..." << std::endl; } theInstance = this; theTileSize = ossimIpt(64, 64); theCurrentCacheSize = 0; // ossim::defaultTileSize(theTileSize); ossim_uint32 cacheSize = ossimString(ossimPreferences::instance()->findPreference("cache_size")).toUInt32()*(1024*1024); const char* tileSize = ossimPreferences::instance()->findPreference("tile_size"); if(tileSize) { ossimString tempString(tileSize); std::vector splitString; tempString = tempString.trim(); tempString.split(splitString, " "); if(splitString.size() > 1) { theTileSize.x = splitString[0].toInt32(); theTileSize.y = splitString[1].toInt32(); } else { theTileSize = ossimIpt(64,64); } } if(cacheSize) { setMaxCacheSize(cacheSize); } else { setMaxCacheSize(DEFAULT_SIZE); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: cache tile size = " << theTileSize << std::endl << "Cache size = " << cacheSize << " bytes" << std::endl; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAppFixedTileCache::ossimAppFixedTileCache() DEBUG: leaving ..." << std::endl; } } ossimAppFixedTileCache::~ossimAppFixedTileCache() { deleteAll(); } ossimAppFixedTileCache *ossimAppFixedTileCache::instance(ossim_uint32 maxSize) { if(!theInstance) { theInstance = new ossimAppFixedTileCache; if(maxSize) { theInstance->setMaxCacheSize(maxSize); } } return theInstance; } void ossimAppFixedTileCache::setMaxCacheSize(ossim_uint32 cacheSize) { std::lock_guard lock(theMutex); theMaxGlobalCacheSize = cacheSize; theMaxCacheSize = cacheSize; // theMaxCacheSize = (ossim_uint32)(theMaxGlobalCacheSize*.2); } void ossimAppFixedTileCache::flush() { std::lock_guard lock(theMutex); std::map::iterator currentIter = theAppCacheMap.begin(); while(currentIter != theAppCacheMap.end()) { (*currentIter).second->flush(); ++currentIter; } theCurrentCacheSize = 0; } void ossimAppFixedTileCache::flush(ossimAppFixedCacheId cacheId) { std::lock_guard lock(theMutex); ossimFixedTileCache* cache = getCache(cacheId); { if(cache) { theCurrentCacheSize -= cache->getCacheSize(); cache->flush(); } } } void ossimAppFixedTileCache::deleteCache(ossimAppFixedCacheId cacheId) { std::lock_guard lock(theMutex); ossimRefPtr cache = getCache(cacheId); { std::map::iterator iter = theAppCacheMap.find(cacheId); if(cache.valid()) { theAppCacheMap.erase(iter); theCurrentCacheSize -= cache->getCacheSize(); } cache = 0; } } ossimAppFixedTileCache::ossimAppFixedCacheId ossimAppFixedTileCache::newTileCache(const ossimIrect& tileBoundaryRect, const ossimIpt& tileSize) { std::lock_guard lock(theMutex); ossimAppFixedCacheId result = -1; ossimFixedTileCache* newCache = new ossimFixedTileCache; if(tileSize.x == 0 || tileSize.y == 0) { // newCache->setRect(tileBoundaryRect, theTileSize); newCache->setRect(tileBoundaryRect, newCache->getTileSize()); } else { newCache->setRect(tileBoundaryRect, tileSize); } result = theUniqueAppIdCounter; theAppCacheMap.insert(std::make_pair(result, newCache)); ++theUniqueAppIdCounter; return result; } ossimAppFixedTileCache::ossimAppFixedCacheId ossimAppFixedTileCache::newTileCache() { std::lock_guard lock(theMutex); ossimAppFixedCacheId result = -1; ossimFixedTileCache* newCache = new ossimFixedTileCache; { result = theUniqueAppIdCounter; theAppCacheMap.insert(std::make_pair(result, newCache)); ++theUniqueAppIdCounter; } return result; } void ossimAppFixedTileCache::setRect(ossimAppFixedCacheId cacheId, const ossimIrect& boundaryTileRect) { std::lock_guard lock(theMutex); ossimFixedTileCache* cache = getCache(cacheId); if(cache) { ossim_uint32 cacheSize = cache->getCacheSize(); // cache->setRect(boundaryTileRect, theTileSize); cache->setRect(boundaryTileRect, cache->getTileSize()); theCurrentCacheSize += (cache->getCacheSize() - cacheSize); } } void ossimAppFixedTileCache::setTileSize(ossimAppFixedCacheId cacheId, const ossimIpt& tileSize) { std::lock_guard lock(theMutex); ossimFixedTileCache* cache = getCache(cacheId); if(cache) { ossim_uint32 cacheSize = cache->getCacheSize(); cache->setRect(cache->getTileBoundaryRect(), tileSize); theCurrentCacheSize += (cache->getCacheSize() - cacheSize); theTileSize = cache->getTileSize(); } } ossimRefPtr ossimAppFixedTileCache::getTile( ossimAppFixedCacheId cacheId, const ossimIpt& origin) { std::lock_guard lock(theMutex); ossimRefPtr result = 0; ossimFixedTileCache* cache = getCache(cacheId); if(cache) { result = cache->getTile(origin); } return result; } ossimRefPtr ossimAppFixedTileCache::addTile( ossimAppFixedCacheId cacheId, ossimRefPtr data, bool duplicateData) { std::lock_guard lock(theMutex); ossimRefPtr result = 0; ossimFixedTileCache *aCache = this->getCache(cacheId); if(!aCache) { return result; } ossim_uint32 dataSize = data->getDataSizeInBytes(); if( (theCurrentCacheSize+dataSize) > theMaxGlobalCacheSize) { shrinkGlobalCacheSize((ossim_int32)(theMaxGlobalCacheSize*0.1)); } ossim_uint32 cacheSize = 0; { cacheSize = aCache->getCacheSize(); } if(cacheSize > theMaxCacheSize) { // shrinkCacheSize(aCache, // (ossim_int32)(aCache->getCacheSize()*.1)); shrinkCacheSize(aCache, (ossim_int32)(1024*1024)); } { cacheSize = aCache->getCacheSize(); result = aCache->addTile(data, duplicateData); theCurrentCacheSize += (aCache->getCacheSize() - cacheSize); } return result; } void ossimAppFixedTileCache::deleteAll() { std::lock_guard lock(theMutex); theCurrentCacheSize = 0; theAppCacheMap.clear(); } ossimRefPtr ossimAppFixedTileCache::removeTile( ossimAppFixedCacheId cacheId, const ossimIpt& origin) { std::lock_guard lock(theMutex); ossimRefPtr result = 0; ossimFixedTileCache* cache = getCache(cacheId); if(cache) { ossim_uint32 cacheSize = cache->getCacheSize(); result = cache->removeTile(origin); theCurrentCacheSize += (cache->getCacheSize() - cacheSize); } return result; } void ossimAppFixedTileCache::deleteTile(ossimAppFixedCacheId cacheId, const ossimIpt& origin) { std::lock_guard lock(theMutex); ossimFixedTileCache* cache = getCache(cacheId); if(cache) { ossim_uint32 cacheSize = cache->getCacheSize(); cache->deleteTile(origin); theCurrentCacheSize += (cache->getCacheSize() - cacheSize); } } ossimFixedTileCache* ossimAppFixedTileCache::getCache( ossimAppFixedCacheId cacheId) { std::map::const_iterator currentIter = theAppCacheMap.find(cacheId); ossimFixedTileCache* result = 0; if(currentIter != theAppCacheMap.end()) { result = (*currentIter).second; } return result; } void ossimAppFixedTileCache::shrinkGlobalCacheSize(ossim_int32 byteCount) { if(static_cast(byteCount) >= theCurrentCacheSize) { flush(); } else { while(byteCount > 0) { std::map::iterator iter = theAppCacheMap.begin(); while( (iter != theAppCacheMap.end())&&(byteCount>0)) { ossimFixedTileCache* cache = getCache((*iter).first); if(cache) { ossim_uint32 before = cache->getCacheSize(); cache->deleteTile(); ossim_uint32 after = cache->getCacheSize(); ossim_uint32 delta = (before - after); byteCount -= delta; theCurrentCacheSize -= (delta); } ++iter; } } } } void ossimAppFixedTileCache::shrinkCacheSize(ossimAppFixedCacheId id, ossim_int32 byteCount) { ossimFixedTileCache* cache = getCache(id); if(cache) { shrinkCacheSize(cache, byteCount); } } void ossimAppFixedTileCache::shrinkCacheSize(ossimFixedTileCache* cache, ossim_int32 byteCount) { if(cache) { ossim_int32 cacheSize = cache->getCacheSize(); if(cacheSize <= byteCount) { cache->flush(); } else { while(byteCount > 0) { ossim_uint32 before = cache->getCacheSize(); cache->deleteTile(); ossim_uint32 after = cache->getCacheSize(); ossim_uint32 delta = std::abs((int)(before - after)); if(delta) { byteCount -= delta; theCurrentCacheSize -= (delta); } else { byteCount = 0; } } } } } const ossimIpt& ossimAppFixedTileCache::getTileSize(ossimAppFixedCacheId cacheId) { std::lock_guard lock(theMutex); ossimFixedTileCache* cache = getCache(cacheId); if(cache) { return cache->getTileSize(); } return theTileSize; } ossim-Miami-2.9.1/src/imaging/ossimAppTileCache.cpp000066400000000000000000000173741352751253100221720ustar00rootroot00000000000000//****************************************************************** // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This file contains the Application cache algorithm // //*********************************** // $Id: ossimAppTileCache.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include ossimAppTileCache* ossimAppTileCache::theInstance = 0; // we will need to grab this from the preferences const ossim_uint32 ossimAppTileCache::DEFAULT_SIZE = 80*1024*1024; const ossim_uint32 ossimAppTileCache::DEFAULT_BUCKET_SIZE = 293; ossimAppTileCache::ossimAppCacheId ossimAppTileCache::theUniqueAppIdCounter = 1; using namespace std; ossimAppTileCache *ossimAppTileCache::instance(ossim_uint32 maxSize) { if(!theInstance) { if(maxSize < 1) { ossimString cacheSize = ossimPreferences::instance()->findPreference("cache_size"); if(cacheSize!="") { maxSize = cacheSize.toUInt32()*1024*1024; } else { maxSize = DEFAULT_SIZE; } ossimNotify(ossimNotifyLevel_NOTICE) << "Setting SIZE----------------------- " << maxSize << std::endl; } theInstance = new ossimAppTileCache(maxSize); } return theInstance; } ossimAppTileCache::~ossimAppTileCache() { deleteAll(); } ossimAppTileCache::ossimAppCacheId ossimAppTileCache::newTileCache(ossim_uint32 bucketSize) { ossimTileCache *aCache = 0; ossimAppCacheId result = 0; aCache = new ossimTileCache(bucketSize); if(aCache) { theAppCache.insert(make_pair(theUniqueAppIdCounter, aCache)); result = theUniqueAppIdCounter; ++theUniqueAppIdCounter; } return result; } /*! * Will retrieve a tile from the cache. */ ossimDataObject *ossimAppTileCache::get(ossimAppCacheId id, const ossimDpt3d &origin, ossim_uint32 resLevel) { ossimDataObject* result = 0; if(id>0) { ossimTileCache *aCache = this->get(id); if(aCache) { result = aCache->get(origin, resLevel); if(result) { adjustQueue(id, origin, resLevel); } } } return result; } ossimRefPtr ossimAppTileCache::removeTile(ossimAppCacheId id, const ossimDpt3d &origin, unsigned long resLevel) { ossimRefPtr result = 0; if(id>0) { ossimTileCache *aCache = this->get(id); if(aCache) { // remove from cache result = aCache->remove(origin, resLevel); // adjust the byte count if(result.valid()) { theCurrentCacheSize -= result->getDataSizeInBytes(); } removeTileFromQueue(id, origin, resLevel); } } return result; } ossimRefPtr ossimAppTileCache::insert(ossimAppCacheId appId, const ossimDpt3d &origin, const ossimDataObject* data, ossim_uint32 resLevel) { static const char MODULE[] = "ossimAppTileCache::insert"; ossimDataObject *result = 0; // find the cache and if it's not there then return NULL ossimTileCache *aCache = this->get(appId); if(!aCache) { return result; } ossimRefPtr tileToInsert = 0; long dataSize = data->getDataSizeInBytes(); if( (theCurrentCacheSize+dataSize) > theMaxCacheSize) { do { ossimRefPtr tile = removeTile(); }while((theCurrentCacheSize+dataSize) > theMaxCacheSize); } if(data) { tileToInsert = (ossimDataObject*)data->dup(); result = aCache->insert(origin, tileToInsert.get(), resLevel); if(!result) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR: can't insert and should not happen" << endl; tileToInsert = 0; } else { theCurrentCacheSize += dataSize; theUsedQueue.push_back(ossimAppCacheTileInfo(appId, origin, resLevel)); } } return result; } ossimTileCache* ossimAppTileCache::get(ossimAppCacheId id) { ossimTileCache *result=0; AppIdIterator anIterator = theAppCache.find(id); if(anIterator != theAppCache.end()) { result = (*anIterator).second; } return result; } void ossimAppTileCache::deleteCache(ossimAppCacheId appId) { // first delete the cache AppIdIterator anIterator = theAppCache.find(appId); if(anIterator != theAppCache.end()) { ossimTileCache *aCache = (*anIterator).second; theCurrentCacheSize -= aCache->sizeInBytes(); delete aCache; theAppCache.erase(anIterator); } // now delete all occurences of the appCacheId in the queue // used for LRU algorithm. deleteAppCacheFromQueue(appId); } void ossimAppTileCache::deleteAll() { AppIdIterator iter = theAppCache.begin(); while(iter != theAppCache.end()) { delete (*iter).second; ++iter; } theAppCache.clear(); } void ossimAppTileCache::removeTileFromQueue(ossimAppCacheId appId, const ossimDpt3d &origin, ossim_uint32 resLevel) { list::iterator anIterator; anIterator = theUsedQueue.begin(); while(anIterator != theUsedQueue.end()) { if( ((*anIterator).theAppCacheId == appId) && ((*anIterator).theOrigin == origin)&& ((*anIterator).theResLevel == resLevel)) { theUsedQueue.erase(anIterator); return; } else { ++anIterator; } } } void ossimAppTileCache::deleteAppCacheFromQueue(ossimAppCacheId appId) { list::iterator anIterator; anIterator = theUsedQueue.begin(); while(anIterator != theUsedQueue.end()) { if( (*anIterator).theAppCacheId == appId) { anIterator = theUsedQueue.erase(anIterator); } else { ++anIterator; } } } ossimRefPtr ossimAppTileCache::removeTile() { ossimRefPtr result; if(!theUsedQueue.empty()) { ossimAppCacheTileInfo &info = *(theUsedQueue.begin()); ossimTileCache *aCache = get(info.theAppCacheId); if(aCache) { result = aCache->remove(info.theOrigin, info.theResLevel); theCurrentCacheSize -= result->getDataSizeInBytes(); } theUsedQueue.erase(theUsedQueue.begin()); } return result; } void ossimAppTileCache::adjustQueue(ossimAppCacheId id, const ossimDpt3d &origin, ossim_uint32 resLevel) { list::iterator anIterator = theUsedQueue.begin(); ossimAppCacheTileInfo info(id, origin, resLevel); while(anIterator != theUsedQueue.end()) { if((*anIterator) == info) { theUsedQueue.erase(anIterator); theUsedQueue.push_back(info); return; } ++anIterator; } } ossim-Miami-2.9.1/src/imaging/ossimArcInfoGridWriter.cpp000066400000000000000000000252021352751253100232210ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimArcInfoGridWriter.cpp 16081 2009-12-10 20:56:36Z eshirschorn $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const ossimTrace traceDebug("ossimArcInfoGridWriter:debug"); using namespace std; RTTI_DEF1(ossimArcInfoGridWriter, "ossimArcInfoGridWriter", ossimImageFileWriter); //******************************************************************* // Constructor: //******************************************************************* ossimArcInfoGridWriter::ossimArcInfoGridWriter() : ossimImageFileWriter(), theOutputTileSize(256, 4) { } ossimArcInfoGridWriter::ossimArcInfoGridWriter(ossimImageSource* inputSource, const ossimFilename& filename) :ossimImageFileWriter(filename, inputSource) { } //******************************************************************* // Destructor //******************************************************************* ossimArcInfoGridWriter::~ossimArcInfoGridWriter() { close(); } bool ossimArcInfoGridWriter::writeFile() { const char* MODULE = "ossimArcInfoGridWriter::writeFile"; if(!theInputConnection) { return false; } ossimRefPtr filter = new ossimCastTileSourceFilter; filter->setOutputScalarType(OSSIM_FLOAT); filter->connectMyInputTo(theInputConnection.get()); filter->initialize(); open(); // make sure we have a region of interest if(theAreaOfInterest.hasNans()) { theInputConnection->initialize(); theAreaOfInterest = theInputConnection->getAreaOfInterest(); } else { theInputConnection->setAreaOfInterest(theAreaOfInterest); } if(theAreaOfInterest.hasNans()) return false; theInputConnection->setTileSize(theOutputTileSize); theInputConnection->setToStartOfSequence(); bool result = writeBinaryAigHeader()&& writeBinaryAigBounds()&& writeBinaryAigStats(); if(result) { ossimFilename indexFile=ossimFilename(theFilename+"/"+"w001001x.adf"); ossimFilename dataFile=ossimFilename(theFilename+"/"+"w001001.adf"); std::ofstream indexFileStream(indexFile.c_str(), ios::out|ios::binary); std::ofstream dataFileStream(dataFile.c_str(), ios::out|ios::binary); ossimEndian endian; if(indexFileStream&&dataFileStream) { ossimAigIndexFileHeader aigIndexHeader; ossimAigDataFileHeader aigDataFileHeader; ossimRefPtr currentTile = theInputConnection->getNextTile(); long tileNumber = 0; long totalNumberOfTiles = theInputConnection->getNumberOfTiles(); ossim_int32 tileOffsetShorts = 0; ossim_int32 tileSizeShorts = 0; ossimNotify(ossimNotifyLevel_NOTICE) << "Tile height = " << theInputConnection->getTileHeight() << std::endl << "Tile width = " << theInputConnection->getTileWidth() << std::endl; ossim_int32 tileSizeInShorts = 2*(theInputConnection->getTileHeight()* theInputConnection->getTileWidth()); // Note: this is in shorts // aigIndexHeader.theFileSize += (4*totalNumberOfTiles); // Note this is in shorts // aigDataFileHeader.theFileSize = 50+ (tileSizeInShorts*totalNumberOfTiles) + totalNumberOfTiles; aigDataFileHeader.theTileSize = tileSizeInShorts; aigIndexHeader.writeStream(indexFileStream); aigDataFileHeader.writeStream(dataFileStream); if(traceDebug()) { CLOG << "AIG INDEX HEADER = \n" << aigIndexHeader << std::endl; CLOG << "AIG DATA FILE HEADER\n" << "file size = " << aigDataFileHeader.theFileSize << std::endl; } while(currentTile.valid()) { currentTile = filter->applyCast(currentTile); if(!currentTile->getBuf()) { currentTile->initialize(); } tileOffsetShorts = dataFileStream.tellp()/2; tileSizeShorts = 2*currentTile->getHeight()*currentTile->getWidth(); ossim_int16 tileSizeShorts16 = 2*currentTile->getHeight()*currentTile->getWidth(); if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(tileOffsetShorts); endian.swap(tileSizeShorts); endian.swap(tileSizeShorts16); endian.swap((ossim_float32*)currentTile->getBuf(), currentTile->getWidth()* currentTile->getHeight()); } indexFileStream.write((char*)(&tileOffsetShorts), 4); indexFileStream.write((char*)(&tileSizeShorts), 4); dataFileStream.write((char*)(&tileSizeShorts16), 2); dataFileStream.write((char*)(currentTile->getBuf()), currentTile->getWidth()*currentTile->getHeight()*4); currentTile = theInputConnection->getNextTile(); ++tileNumber; } } } close(); filter = 0; return result; } bool ossimArcInfoGridWriter::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimImageFileWriter::saveState(kwl, prefix); } bool ossimArcInfoGridWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimImageFileWriter::loadState(kwl, prefix); } bool ossimArcInfoGridWriter::isOpen()const { return (theFilename.isDir() && theFilename.exists()); } bool ossimArcInfoGridWriter::open() { if(theFilename.isDir()&& theFilename.exists()) { return true; } else { theFilename = theFilename.path(); if(theFilename.isDir()&& theFilename.exists()) { return true; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimArcInfoGridWriter::open(): Directory " << theFilename << " doesn't exist" << std::endl; } } return false; } void ossimArcInfoGridWriter::close() { } bool ossimArcInfoGridWriter::writeBinaryAigHeader() { const char* MODULE = "ossimArcInfoGridWriter::writeBinaryAigHeader"; ossimAigHeader aigHeader; ossimFilename file=ossimFilename(theFilename+"/"+"hdr.adf"); if(isOpen()) { switch(theInputConnection->getOutputScalarType()) { case OSSIM_UCHAR: case OSSIM_SSHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: // { // aigHeader.setIntCoverage(); // break; // } case OSSIM_DOUBLE: case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: case OSSIM_NORMALIZED_DOUBLE: { aigHeader.setFloatCoverage(); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimArcInfoGridWriter::writeBinaryAigHeader: " << "unknown scalar type" << std::endl; } } // need to set pixel size // // code goes here // now setting number of tiles per row aigHeader.theNumberOfTilesPerRow = theInputConnection->getNumberOfTilesHorizontal(); aigHeader.theNumberOfTilesPerColumn = theInputConnection->getNumberOfTilesVertical(); aigHeader.theWidthOfTileInPixels = theInputConnection->getTileWidth(); aigHeader.theHeightOfTileInPixels = theInputConnection->getTileHeight(); std::ofstream out; out.open(file.c_str(), ios::out|ios::binary); if(out) { if(traceDebug()) { CLOG << "AIG_HEADER = \n" << aigHeader << std::endl; } return aigHeader.writeStream(out); } } return false; } bool ossimArcInfoGridWriter::writeBinaryAigBounds() { const char* MODULE = "ossimArcInfoGridWriter::writeBinaryAigBounds"; ossimAigBounds aigBounds; // setup bounds ossimIrect bounds = theInputConnection->getBoundingRect(); if(!bounds.hasNans()) { aigBounds.ll_x = -.5; aigBounds.ll_y = -.5; aigBounds.ur_x = bounds.width()-.5; aigBounds.ur_y = bounds.height()-.5; // ossimFilename file=ossimFilename(theFilename+"/"+"dblbnd.adf"); if(isOpen()) { std::ofstream out; out.open(file.c_str(), ios::out|ios::binary); if(out) { if(traceDebug()) { CLOG << "AIG BOUNDS =\n" <getMinPixelValue(); aigStats.theMax = theInputConnection->getMaxPixelValue(); aigStats.theMean = (aigStats.theMax-aigStats.theMin)/2.0; // ossimFilename file=ossimFilename(theFilename+"/"+"sta.adf"); if(isOpen()) { std::ofstream out; out.open(file.c_str(), ios::out|ios::binary); if(out) { return aigStats.writeStream(out); } } return false; } ossimString ossimArcInfoGridWriter::getExtension() const { return ossimString("aig"); } ossim-Miami-2.9.1/src/imaging/ossimAtCorrGridRemapper.cpp000066400000000000000000000240051352751253100233710ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: //******************************************************************* // $Id: ossimAtCorrGridRemapper.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include RTTI_DEF1(ossimAtCorrGridRemapper, "ossimAtCorrGridRemapper", ossimAtCorrRemapper); using namespace std; ossimAtCorrGridRemapper::ossimAtCorrGridRemapper(ossimObject* owner, ossimImageSource* inputSource, const ossimString& sensorType) :ossimAtCorrRemapper(owner, inputSource, sensorType) { theUseInterpolationFlag = true; } ossimAtCorrGridRemapper::~ossimAtCorrGridRemapper() { } void ossimAtCorrGridRemapper::interpolate(const ossimDpt& pt, int band, double& a, double& b, double& c)const { if(theGridBounds.pointWithin(pt)) { double x = (((double)(pt.x - theUlGridBound.x))/theGridBounds.width())*(theGridSize.x-1); double y = (((double)(pt.y - theUlGridBound.y))/theGridBounds.height())*(theGridSize.y-1); int xidx = (int)x; int yidx = (int)y; double xt = x - xidx; double yt = y - yidx; double va00 = theAGrid[band][yidx][xidx]; double va01 = theAGrid[band][yidx][xidx+1]; double va11 = theAGrid[band][yidx+1][xidx+1]; double va10 = theAGrid[band][yidx+1][xidx]; double vb00 = theBGrid[band][yidx][xidx]; double vb01 = theBGrid[band][yidx][xidx+1]; double vb11 = theBGrid[band][yidx+1][xidx+1]; double vb10 = theBGrid[band][yidx+1][xidx]; double vc00 = theCGrid[band][yidx][xidx]; double vc01 = theCGrid[band][yidx][xidx+1]; double vc11 = theCGrid[band][yidx+1][xidx+1]; double vc10 = theCGrid[band][yidx+1][xidx]; double vaInterpH1 = va00 + (va01-va00)*xt; double vaInterpH2 = va10 + (va11-va10)*xt; double vbInterpH1 = vb00 + (vb01-vb00)*xt; double vbInterpH2 = vb10 + (vb11-vb10)*xt; double vcInterpH1 = vc00 + (vc01-vc00)*xt; double vcInterpH2 = vc10 + (vc11-vc10)*xt; a = vaInterpH1 + (vaInterpH2-vaInterpH1)*yt; b = vbInterpH1 + (vbInterpH2-vbInterpH1)*yt; c = vcInterpH1 + (vcInterpH2-vcInterpH1)*yt; } else { ossimAtCorrRemapper::interpolate(pt, band, a, b, c); } } void ossimAtCorrGridRemapper::initialize() { ossimAtCorrRemapper::initialize(); if(theInputConnection) { theGridBounds = theInputConnection->getBoundingRect(); theUlGridBound = theGridBounds.ul(); } else { theGridBounds.makeNan(); } if(!theAGrid.size()|| !theBGrid.size()|| !theCGrid.size()) { theUseInterpolationFlag=false; } setBaseToAverage(); } void ossimAtCorrGridRemapper::setGridSize(ossim_uint32 numberOfBands, const ossimIpt& gridSize) { if((theGridSize!=gridSize)||(numberOfBands != theAGrid.size())) { theAGrid.resize(numberOfBands); theBGrid.resize(numberOfBands); theCGrid.resize(numberOfBands); for(ossim_uint32 b = 0; b < numberOfBands;++b) { theAGrid[b].resize(gridSize.y); theBGrid[b].resize(gridSize.y); theCGrid[b].resize(gridSize.y); for(int r = 0; r < gridSize.y; ++r) { theAGrid[b][r].resize(gridSize.x); theBGrid[b][r].resize(gridSize.x); theCGrid[b][r].resize(gridSize.x); } } theGridSize = gridSize; } } void ossimAtCorrGridRemapper::setBaseToAverage() { ossim_uint32 idxBand; vector xaAverage(theAGrid.size()); vector xcAverage(theBGrid.size()); vector xbAverage(theCGrid.size()); // double aAverage=0.0, bAverage=0.0, cAverag=0.0; if((theAGrid.size() != theBGrid.size())|| (theAGrid.size() != theCGrid.size())|| (theAGrid.size() == 0)) { return; } for(idxBand = 0; idxBand < theAGrid.size(); ++idxBand) { ossim_uint32 idxRow = 0; xaAverage[idxBand] = 0.0; xbAverage[idxBand] = 0.0; xcAverage[idxBand] = 0.0; for(idxRow = 0; idxRow < theAGrid[idxBand].size();++idxRow) { ossim_uint32 idxCol = 0; for(idxCol = 0; idxCol < theAGrid[idxBand][idxRow].size();++idxCol) { xaAverage[idxBand] += theAGrid[idxBand][idxRow][idxCol]; } } for(idxRow = 0; idxRow < theBGrid[idxBand].size();++idxRow) { ossim_uint32 idxCol = 0; for(idxCol = 0; idxCol < theBGrid[idxBand][idxRow].size();++idxCol) { xbAverage[idxBand] += theBGrid[idxBand][idxRow][idxCol]; } } for(idxRow = 0; idxRow < theCGrid[idxBand].size();++idxRow) { ossim_uint32 idxCol = 0; for(idxCol = 0; idxCol < theCGrid[idxBand][idxRow].size();++idxCol) { xaAverage[idxBand] += theCGrid[idxBand][idxRow][idxCol]; xbAverage[idxBand] += theCGrid[idxBand][idxRow][idxCol]; xcAverage[idxBand] += theCGrid[idxBand][idxRow][idxCol]; } } } for(idxBand = 0; idxBand < theAGrid.size(); ++idxBand) { xaAverage[idxBand] /=(double)(theGridSize.x*theGridSize.y); xbAverage[idxBand] /=(double)(theGridSize.x*theGridSize.y); xcAverage[idxBand] /=(double)(theGridSize.x*theGridSize.y); } theXaArray = xaAverage; theXbArray = xbAverage; theXcArray = xcAverage; } /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ bool ossimAtCorrGridRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* MODULE = "ossimAtCorrGridRemapper::loadState"; theAGrid.clear(); theBGrid.clear(); theCGrid.clear(); if (!theTile || !theSurfaceReflectance) { cerr << MODULE << " ERROR:" << "Not initialized..." << endl; return false; } theUseInterpolationFlag=true; ossim_uint32 bands = theTile->getNumberOfBands(); theAGrid.resize(bands); theBGrid.resize(bands); theCGrid.resize(bands); const char* rowsLookup = NULL; const char* colsLookup = NULL; for(ossim_uint32 band = 0; band < bands; ++band) { ossim_uint32 r = 0; ossim_uint32 c = 0; ossimString gridString = "band"; gridString += ossimString::toString(band+1); gridString += ".grid"; rowsLookup = kwl.find(prefix, gridString + ".rows"); colsLookup = kwl.find(prefix, gridString + ".cols"); if(rowsLookup&&colsLookup) { cout << "both keywords needed: " << (gridString+".rows") << endl << (gridString+".cols") << endl; theUseInterpolationFlag=false; return false; } ossim_uint32 rows = ossimString(rowsLookup).toULong(); ossim_uint32 cols = ossimString(colsLookup).toULong(); if(cols&&rows) { cout << "value for cols and rows keyword have 0" << endl; theUseInterpolationFlag=false; return false; } theAGrid[band].resize(rows); theBGrid[band].resize(rows); theCGrid[band].resize(rows); for(r = 0; r < rows; ++r) { theAGrid[band][r].resize(cols); theBGrid[band][r].resize(cols); theCGrid[band][r].resize(cols); } ossim_uint32 idx = 1; const char* aLookup; const char* bLookup; const char* cLookup; for(r = 0; r < rows; ++r) { for(c = 0; c < cols; ++c) { aLookup = kwl.find(prefix, gridString+".a"+ossimString::toString(idx)); bLookup = kwl.find(prefix, gridString+".b"+ossimString::toString(idx)); cLookup = kwl.find(prefix, gridString+".c"+ossimString::toString(idx)); theAGrid[band][r][c] = ossimString(aLookup).toDouble(); theBGrid[band][r][c] = ossimString(bLookup).toDouble(); theCGrid[band][r][c] = ossimString(cLookup).toDouble(); ++idx; } } theGridSize.x = cols; theGridSize.y = rows; setBaseToAverage(); } return true; } bool ossimAtCorrGridRemapper::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossim_uint32 bands = (ossim_uint32)theAGrid.size(); for(ossim_uint32 band = 0; band < bands; ++band) { int idx = 1; int r = 0; int c = 0; ossimString gridString = "band"; gridString += ossimString::toString(band+1); gridString += ".grid"; ossim_uint32 rows = (ossim_uint32)theAGrid[band].size(); kwl.add(prefix, gridString+".rows", rows, true); ossim_uint32 cols = (ossim_uint32)theAGrid[band][0].size(); kwl.add(prefix, gridString+".cols", cols, true); for(r = 0; r < theGridSize.y; ++r) { for(c = 0; c < theGridSize.x; ++c) { kwl.add(prefix, gridString+".a"+ossimString::toString(idx), theAGrid[band][r][c], true); kwl.add(prefix, gridString+".b"+ossimString::toString(idx), theAGrid[band][r][c], true); kwl.add(prefix, gridString+".c"+ossimString::toString(idx), theAGrid[band][r][c], true); ++idx; } } } return ossimAtCorrRemapper::saveState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimAtCorrRemapper.cpp000066400000000000000000000443621352751253100225730ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Kathy Minear // // Description: // Takes in DNs for any number of bands // Converts DNs to Radiance at the satellite values Lsat // Converts Lsat to Surface Reflectance values // //************************************************************************* // $Id: ossimAtCorrRemapper.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimAtCorrRemapper, "ossimAtCorrRemapper", ossimImageSourceFilter); static ossimTrace traceDebug("ossimAtCorrRemapper:debug"); using namespace std; ossimAtCorrRemapper::ossimAtCorrRemapper(ossimObject* owner, ossimImageSource* inputSource, const ossimString& sensorType) : ossimImageSourceFilter (owner, inputSource), // base class theTile (NULL), theSurfaceReflectance (NULL), theUseInterpolationFlag(false), theMinPixelValue (0), theMaxPixelValue (0), theXaArray (0), theXbArray (0), theXcArray (0), theBiasArray (0), theGainArray (0), theCalCoefArray (0), theBandWidthArray (0), theSensorType(sensorType) { //*** // Set the base class "theEnableFlag" to off since no adjustments have been // made yet. //*** disableSource(); initialize(); } ossimAtCorrRemapper::~ossimAtCorrRemapper() { if (theSurfaceReflectance) { delete [] theSurfaceReflectance; theSurfaceReflectance = NULL; } } ossimRefPtr ossimAtCorrRemapper::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { #if 0 if (traceDebug()) { cout << "ossimAtCorrRemapper::getTile DEBUG:" << "\ntile_rect: " << tile_rect << endl; } #endif if (!isInitialized()||!theInputConnection) { cerr << "ossimAtCorrRemapper::getTile ERROR:" << "\nNot initialized!" << endl; return ossimRefPtr(); } if(!theTile.valid()) { initialize(); if(!theTile) { return ossimRefPtr(); } } // Fetch tile from pointer from the input source. ossimRefPtr inputTile = theInputConnection->getTile(tile_rect, resLevel); if (!inputTile.valid()) // Just in case... { return ossimRefPtr(); } // Check for remap bypass or empty / null input tile. ossimDataObjectStatus tile_status = inputTile->getDataObjectStatus(); if (!theEnableFlag || tile_status == OSSIM_NULL || tile_status == OSSIM_EMPTY) { return inputTile; } ossim_uint32 w = tile_rect.width(); ossim_uint32 h = tile_rect.height(); ossim_uint32 tw = theTile->getWidth(); ossim_uint32 th = theTile->getHeight(); ossim_uint32 bands = theTile->getNumberOfBands(); // Set the origin of the output tile. theTile->setOrigin(tile_rect.ul()); if(w*h != tw*th) { theTile->setWidthHeight(w, h); theTile->initialize(); if(theSurfaceReflectance) { delete [] theSurfaceReflectance; theSurfaceReflectance = NULL; } } if(!theSurfaceReflectance) { ossim_uint32 size = tw*th*bands; #if 0 if (traceDebug()) { cout << "ossimAtCorrRemapper::getTile DEBUG:" << "\ntile_rect: " << tile_rect << "\ntile width: " << tw << "\ntile height: " << th << "\nbands: " << bands << "\nBuffer size: " << size << endl; } #endif theSurfaceReflectance = new double[size]; } ossim_uint32 buffer_index = 0; ossimIpt ul = tile_rect.ul(); ossimIpt lr = tile_rect.lr(); const double MP = theTile->getMinNormalizedPix(); // Minimum normalized pix. double a, b, c; buffer_index = 0; cout << setprecision(6); for (ossim_uint32 band=0; band < bands; ++band) { for(ossim_sint32 idxy = ul.y; idxy <= lr.y; ++idxy) { for(ossim_sint32 idxx = ul.x; idxx <= lr.x; ++idxx) { double p = inputTile->getPix(buffer_index); if (p>0.0) { if(!theUseInterpolationFlag) { a = theXaArray[band]; b = theXbArray[band]; c = theXcArray[band]; } else { interpolate(ossimDpt(idxx, idxy), band, a, b, c); } if(theSensorType == "ls7ms") { double radiance_at_satellite = (theGainArray[band] * p) + theBiasArray[band]; double y = (radiance_at_satellite * a) - b; p = (y / (1.0 + (c * y)) ); } else if(theSensorType == "qbms") { double radiance_at_satellite = theCalCoefArray[band] * p / theBandWidthArray[band]; double y = (radiance_at_satellite * a) - b; p = (y / (1.0 + (c * y)) ); } else if(theSensorType == "ikms") { double radiance_at_satellite = p /((theCalCoefArray[band]/1.0)/ theBandWidthArray[band]); double y = (radiance_at_satellite * a) - b; p = (y / (1.0 + (c * y)) ); } // Note that "p" should now be normalized between 0.0 and 1.0; // *** // Since it wasn't null to start with clip / clamp between minimum // normalized pixel and one(max). // *** p = ( p > MP ? ( p < 1.0 ? p : 1.0) : MP ); // Scan the new tile and set the min / max. if (p < theMinPixelValue[band]) { theMinPixelValue[band] = p; } else if (p > theMaxPixelValue[band]) { theMaxPixelValue[band] = p; } theSurfaceReflectance[buffer_index] = p; } else { theSurfaceReflectance[buffer_index] = 0.0; // pixel was null... } ++buffer_index; } // End of sample loop... } // End of line loop... } // End of band loop... // Copy the buffer to the output tile at the same time unnormalizing it. theTile->copyNormalizedBufferToTile(theSurfaceReflectance); // Validate the output to set the tile status. theTile->validate(); return theTile; } void ossimAtCorrRemapper::initialize() { if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, theInputConnection); theTile->initialize(); if(theSurfaceReflectance) { delete []theSurfaceReflectance; theSurfaceReflectance = NULL; } ossim_uint32 tw = theTile->getWidth(); ossim_uint32 th = theTile->getHeight(); ossim_uint32 bands = theTile->getNumberOfBands(); ossim_uint32 size = tw*th*bands; if (traceDebug()) { cout << "ossimAtCorrRemapper::initialize DEBUG:" << "\ntile width: " << tw << "\ntile height: " << th << "\nbands: " << bands << "\nBuffer size: " << size << endl; } theSurfaceReflectance = new double[size]; setInitializedFlag(true); clearErrorStatus(); } else { setInitializedFlag(false); setErrorStatus(); }; verifyEnabled(); if (traceDebug()) { cout << "ossimAtCorrRemapper::initialize DEBUG:" << *this << endl; } } bool ossimAtCorrRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimAtCorrRemapper::loadState()"; if (traceDebug()) CLOG << "entering..." << endl; if (!theTile || !theSurfaceReflectance) { cerr << MODULE << " ERROR:" << "Not initialized..." << endl; return false; } ossim_uint32 bands = theTile->getNumberOfBands(); // Clear out the old values. theMinPixelValue.clear(); theMaxPixelValue.clear(); theXaArray.clear(); theXbArray.clear(); theXcArray.clear(); theBiasArray.clear(); theGainArray.clear(); theCalCoefArray.clear(); theBandWidthArray.clear(); // Now resize them. // Start with arbitrary big number. theMinPixelValue.resize(bands, 1.0); // Start with arbitrary small number. theMaxPixelValue.resize(bands, 0.0); theXaArray.resize(bands, 1.0); theXbArray.resize(bands, 1.0); theXcArray.resize(bands, 1.0); theBiasArray.resize(bands, 0.0); theGainArray.resize(bands, 1.0); theCalCoefArray.resize(bands); theBandWidthArray.resize(bands); for(ossim_uint32 band = 0; band < bands; ++band) { const char* lookup = NULL; ossimString band_string = ".band"; band_string += ossimString::toString(band+1); ossimString kw = AT_CORR_XA_KW; kw += band_string; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { theXaArray[band] = atof(lookup); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nlookup failed for keyword: " << kw.c_str() << endl; } } kw = AT_CORR_XB_KW; kw += band_string; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { theXbArray[band] = atof(lookup); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nlookup failed for keyword: " << kw.c_str() << endl; } } kw = AT_CORR_XC_KW; kw += band_string; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { theXcArray[band] = atof(lookup); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nlookup failed for keyword: " << kw.c_str() << endl; } } if(theSensorType == "ls7ms") { kw = AT_CORR_BIAS_KW; kw += band_string; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { theBiasArray[band] = atof(lookup); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nlookup failed for keyword: " << kw.c_str() << endl; } } kw = AT_CORR_GAIN_KW; kw += band_string; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { theGainArray[band] = atof(lookup); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nlookup failed for keyword: " << kw.c_str() << endl; } } } if(theSensorType == "qbms") { kw = AT_CORR_CALCOEF_KW; kw += band_string; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { theCalCoefArray[band] = atof(lookup); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nlookup failed for keyword: " << kw.c_str() << endl; } } kw = AT_CORR_BANDWIDTH_KW; kw += band_string; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { theBandWidthArray[band] = atof(lookup); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nlookup failed for keyword: " << kw.c_str() << endl; } } } if(theSensorType == "ikms") { kw = AT_CORR_CALCOEF_KW; kw += band_string; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { theCalCoefArray[band] = atof(lookup); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nlookup failed for keyword: " << kw.c_str() << endl; } } kw = AT_CORR_BANDWIDTH_KW; kw += band_string; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { theBandWidthArray[band] = atof(lookup); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nlookup failed for keyword: " << kw.c_str() << endl; } } } } verifyEnabled(); if (theEnableFlag) { //*** // Call the base class to pick up the enable flag. Note that this // can override the state set from verifyEnabled() method. //*** ossimString pref; if (prefix) pref += prefix; pref += "atmospheric_correction."; } if (traceDebug()) { CLOG << "DEBUG:" << *this << "returning..." << endl; } return true; } void ossimAtCorrRemapper::verifyEnabled() { // Check all the pointers... if ( !theInputConnection || !theTile || !theSurfaceReflectance ) { disableSource(); return; } ossim_uint32 bands = theTile->getNumberOfBands(); if ( (theMinPixelValue.size() != bands) || (theMaxPixelValue.size() != bands) || (theXaArray.size() != bands) || (theXbArray.size() != bands) || (theXcArray.size() != bands) || (theBiasArray.size() != bands) || (theGainArray.size() != bands) || (theCalCoefArray.size() != bands) || (theBandWidthArray.size()!= bands)) { disableSource(); return; } enableSource(); } ossimString ossimAtCorrRemapper::getShortName() const { return ossimString("Atmospheric Correction Remapper"); } vector ossimAtCorrRemapper::getNormMinPixelValues() const { return theMinPixelValue; } vector ossimAtCorrRemapper::getNormMaxPixelValues() const { return theMaxPixelValue; } void ossimAtCorrRemapper::getNormMinPixelValues(vector& v) const { v = theMinPixelValue; } void ossimAtCorrRemapper::getNormMaxPixelValues(vector& v) const { v = theMaxPixelValue; } const ossimString& ossimAtCorrRemapper::getSensorType() const { return theSensorType; } void ossimAtCorrRemapper::setSensorType(const ossimString& sensorType) { theSensorType = sensorType; } void ossimAtCorrRemapper::interpolate(const ossimDpt& /* pt */, int band, double& a, double& b, double& c)const { a = theXaArray[band]; b = theXbArray[band]; c = theXcArray[band]; } ostream& ossimAtCorrRemapper::print(ostream& os) const { os << "ossimAtCorrRemapper:" << "\ntheEnableFlag: " << (theEnableFlag?"enabled":"disabled") << endl; os << setprecision(15) << setiosflags(ios::fixed); ossim_uint32 band = 1; vector::const_iterator i = theMinPixelValue.begin(); while (i != theMinPixelValue.end()) { os << "band[" << band << "] min: " << (*i) << endl; ++i; ++band; } band = 1; i = theMaxPixelValue.begin(); while (i != theMaxPixelValue.end()) { os << "band[" << band << "] max: " << (*i) << endl; ++i; ++band; } band = 1; i = theXaArray.begin(); while (i != theXaArray.end()) { os << "band[" << band << "] xa: " << (*i) << endl; ++i; ++band; } band = 1; i = theXbArray.begin(); while (i != theXbArray.end()) { os << "band[" << band << "] xb: " << (*i) << endl; ++i; ++band; } band = 1; i = theXcArray.begin(); while (i != theXcArray.end()) { os << "band[" << band << "] xc: " << (*i) << endl; ++i; ++band; } if(theSensorType == "ls7ms") { band = 1; i = theBiasArray.begin(); while (i != theBiasArray.end()) { os << "band[" << band << "] bias: " << (*i) << endl; ++i; ++band; } band = 1; i = theGainArray.begin(); while (i != theGainArray.end()) { os << "band[" << band << "] gain: " << (*i) << endl; ++i; ++band; } } if(theSensorType == "qbms") { band = 1; i = theCalCoefArray.begin(); while (i != theCalCoefArray.end()) { os << "band[" << band << "] calcoef: " << (*i) << endl; ++i; ++band; } band = 1; i = theBandWidthArray.begin(); while (i != theBandWidthArray.end()) { os << "band[" << band << "] bandwidth: " << (*i) << endl; ++i; ++band; } } if(theSensorType == "ikms") { band = 1; i = theCalCoefArray.begin(); while (i != theCalCoefArray.end()) { os << "band[" << band << "] calcoef: " << (*i) << endl; ++i; ++band; } } return os; } ostream& operator<<(ostream& os, const ossimAtCorrRemapper& hr) { return hr.print(os); } ossim-Miami-2.9.1/src/imaging/ossimAtbController.cpp000066400000000000000000000452731352751253100224610ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains implementation of class ossimAtbController. This is the // controller managing the tonal balancing process. It's product is the // initialization of specialized remappers in each of the mosaic's member // images that results in a tonally balanced mosaic. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimAtbController.cpp 17195 2010-04-23 17:32:18Z dburken $ #include RTTI_DEF2(ossimAtbController, "ossimAtbController", ossimProcessInterface, ossimConnectableObject ); #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimAtbController:exec"); static ossimTrace traceDebug ("ossimAtbController:debug"); static const ossimIpt DEFAULT_GRID_SPACING (64,64); static const char* DEFAULT_ATB_REMAP_ENGINE = "ossimHsvGridRemapEngine"; using namespace std; //***************************************************************************** // CONSTRUCTOR: ossimAtbController() // //***************************************************************************** ossimAtbController::ossimAtbController() : ossimConnectableObject(NULL, 0, 0, false, true), theContainer (0), theGridRemapEngine (0), theGridSpacing (DEFAULT_GRID_SPACING) { static const char MODULE[] = "ossimAtbController Default Constructor"; if (traceExec()) CLOG << "entering..." << endl; //*** // Instantiate a default remap engine: //*** theGridRemapEngine = ossimGridRemapEngineFactory::create(DEFAULT_ATB_REMAP_ENGINE); if (traceExec()) CLOG << "returning..." << endl; } //***************************************************************************** // CONSTRUCTOR: ossimAtbController() // //***************************************************************************** ossimAtbController::ossimAtbController(ossimImageCombiner* combiner, ossimGridRemapEngine* engine) : ossimConnectableObject(NULL, 0, 0, false, true), theContainer (0), theGridRemapEngine (0), theGridSpacing (DEFAULT_GRID_SPACING) { static const char MODULE[] = "ossimAtbController Constructor #1"; if (traceExec()) CLOG << "entering..." << endl; initializeWithCombiner(combiner, engine); if (traceExec()) CLOG << "returning..." << endl; } //***************************************************************************** // CONSTRUCTOR: ossimAtbController() // //***************************************************************************** ossimAtbController::ossimAtbController(ossimGridRemapEngine* engine) : theContainer (0), theGridRemapEngine (0), theGridSpacing (DEFAULT_GRID_SPACING) { static const char MODULE[] = "ossimAtbController Constructor #1"; if (traceExec()) CLOG << "entering..." << endl; //*** // Assign default engine if non provided: //*** if (engine) { theGridRemapEngine = engine; } else { theGridRemapEngine = ossimGridRemapEngineFactory::create(DEFAULT_ATB_REMAP_ENGINE); } if (traceExec()) CLOG << "returning..." << endl; } //***************************************************************************** // DESTRUCTOR: ~ossimAtbController() // // The remappers are left behind, owned by the combiner's container. If the // combiner was owned by something other than a container (see initialize()), // then this controller will assume ownership of the allocated remappers and // delete them here. // //***************************************************************************** ossimAtbController::~ossimAtbController() { theContainer = 0; theGridRemapEngine = 0;; } //***************************************************************************** // METHOD: ossimAtbController::initializeWithCombiner() // //***************************************************************************** void ossimAtbController::initializeWithCombiner(ossimImageCombiner* combiner, ossimGridRemapEngine* engine) { static const char MODULE[] = "ossimAtbController::initializeWithCombiner()"; if (traceExec()) CLOG << "entering..." << endl; //*** // Assign default engine if non provided: //*** if (engine) theGridRemapEngine = (ossimGridRemapEngine*)engine->dup(); else theGridRemapEngine = ossimGridRemapEngineFactory::create(DEFAULT_ATB_REMAP_ENGINE); //*** // This is the first combiner initializing the controller. The combiner // will have all of the input sources connected already. We attach to // these: //*** theContainer = PTR_CAST(ossimConnectableContainer, combiner->getOwner()); //*** // Need to scan the input connections of the combiner and insert a // remapper if there is not one already at the end of the input chain: //*** vector del_list; vector add_list; int numInputs = combiner->getNumberOfInputs(); for(int i=0; igetInput(i)); if (input_image) { ossimGridRemapSource* remapper = PTR_CAST(ossimGridRemapSource, input_image); if (remapper) { //*** // Remapper already present, set its remap engine to this // controller's remap engine: //*** remapper->setRemapEngine(theGridRemapEngine); } else { //*** // Need to instantiate remapper: //*** remapper = new ossimGridRemapSource(input_image, theGridRemapEngine); if (theContainer.valid()) theContainer->addChild(remapper); add_list.push_back(remapper); del_list.push_back(input_image); } connectMyInputTo(remapper); } } //*** // Need to delete the old inputs and add the new remappers to the // combiner's input list: //*** vector::iterator add_iter = add_list.begin(); vector::iterator del_iter = del_list.begin(); while (add_iter != add_list.end()) { (*add_iter)->connectMyInputTo(*del_iter); combiner->disconnect(*del_iter); combiner->connectMyInputTo(*add_iter); add_iter++; del_iter++; } combiner->initialize(); if (traceExec()) CLOG << "returning..." << endl; } //***************************************************************************** // METHOD: ossimAtbController::enableImage() // // Enable an image in the mosaic to be included the tonal balancing process. // //***************************************************************************** bool ossimAtbController::enableImage(unsigned int index) { if (index >= getNumberOfInputs()) return false; ossimSource* remapper = PTR_CAST(ossimSource, getInput(index)); if (remapper) remapper->enableSource(); return true; } //***************************************************************************** // METHOD: ossimAtbController::disableImage() // // Disable an image in the mosaic from the tonal balancing process. // //***************************************************************************** bool ossimAtbController::disableImage(unsigned int index) { if (index >= getNumberOfInputs()) return false; ossimSource* remapper = PTR_CAST(ossimSource, getInput(index)); if (remapper) remapper->disableSource(); return true; } //***************************************************************************** // METHOD: ossimAtbController::lockImage() // // Locks a particular source for adjustment. A locked image // effectively defines the target values for all overlapping imagery. // //***************************************************************************** bool ossimAtbController::lockImage(unsigned int index) { if (index >= getNumberOfInputs()) return false; ossimGridRemapSource* remapper = PTR_CAST(ossimGridRemapSource, getInput(index)); if (remapper) remapper->lock(); return true; } //***************************************************************************** // METHOD: ossimAtbController::unlockImage() // // Unlocks a particular source for allowing its adjustment. // //***************************************************************************** bool ossimAtbController::unlockImage(unsigned int index) { if (index >= getNumberOfInputs()) return false; ossimGridRemapSource* remapper = PTR_CAST(ossimGridRemapSource, getInput(index)); if (remapper) remapper->lock(); return true; } //***************************************************************************** // METHOD: ossimAtbController::execute() // //***************************************************************************** bool ossimAtbController::execute() { static const char MODULE[] = "ossimAtbController::execute()"; if (traceExec()) CLOG << "entering..." << endl; setPercentComplete(0.0); ossimGridRemapSource* source; //*** // First verify that all objects needed are initialized: //*** int num_images = getNumberOfInputs(); if ((!theGridRemapEngine) || (num_images < 2)) { CLOG << "WARNING: execute method was called but the controller has not " << "been properly initialized. Ignoring request..." << endl; if (traceExec()) CLOG << "returning..." << endl; return false; } //*** // establish the remap grids: //*** initializeRemappers(); setPercentComplete(10.0); //*** // Establish grid of matchpoints: //*** int numPoints = 0; ossimDpt mp_view_pt; theMatchPoints.clear(); for (mp_view_pt.line = theBoundingRect.ul().line; mp_view_pt.line <= theBoundingRect.lr().line; mp_view_pt.line += theGridSpacing.line) { for (mp_view_pt.samp = theBoundingRect.ul().samp; mp_view_pt.samp <= theBoundingRect.lr().samp; mp_view_pt.samp += theGridSpacing.samp) { ossimAtbMatchPoint* mp = new ossimAtbMatchPoint(mp_view_pt, theGridRemapEngine); theMatchPoints.push_back(mp); numPoints++; } } //*** // Loop over each matchpoint to determine which images contribute statistics: //*** setPercentComplete(20.0); for (int mp=0; mpviewPoint()); //*** // Loop over each image source to check if point lies inside its bounding // rectangle, and add its contribution to the matchpoint's collection: //*** for (int src=0; srcgetBoundingRect()); if (image_rect.pointWithin(view_point)) theMatchPoints[mp]->addImage(source); } } setPercentComplete(20.0 + 50.0*(mp/numPoints)); } //*** // All contributors have been included in all matchpoints' collections. // Compute the target pixel value for each matchpoint and communicate it // to the corresponding remappers: //*** for (int mp=0; mpassignRemapValues(); } //*** // Finally, enable the remappers: //*** for (int src=0; srcenableSource(); } setPercentComplete(100.0); if (traceExec()) CLOG << "returning..." << endl; return true; } //***************************************************************************** // METHOD: ossimAtbController::abort() // //***************************************************************************** void ossimAtbController::abort() { static const char MODULE[] = "ossimAtbController::abort()"; if (traceExec()) CLOG << "entering..." << endl; CLOG << "NOTICE: this method not yet implemented." << endl; if (traceExec()) CLOG << "returning..." << endl; } //***************************************************************************** // METHOD: ossimAtbController::saveState() // //***************************************************************************** bool ossimAtbController::saveState(ossimKeywordlist& /* kwl */) const { static const char MODULE[] = "ossimAtbController::saveState()"; if (traceExec()) CLOG << "entering..." << endl; CLOG << "NOTICE: this method not yet implemented." << endl; if (traceExec()) CLOG << "returning..." << endl; return true; } //***************************************************************************** // METHOD: ossimAtbController::loadState() // //***************************************************************************** bool ossimAtbController::loadState(const ossimKeywordlist& /* kwl */) { static const char MODULE[] = "ossimAtbController::loadState()"; if (traceExec()) CLOG << "entering..." << endl; CLOG << "NOTICE: this method not yet implemented." << endl; if (traceExec()) CLOG << "returning..." << endl; return true; } //***************************************************************************** // METHOD: ossimAtbController::setKernelSize(N) // // Hook to set the size of the kernel used by all point sources in computing // their mean pixel value. The kernels will be resized to NxN. // //***************************************************************************** void ossimAtbController::setKernelSize(int side_size) { static const char MODULE[] = "ossimAtbController::setKernelSize(N)"; if (traceExec()) CLOG << "entering..." << endl; vector >::iterator mpi = theMatchPoints.begin(); while (mpi != theMatchPoints.end()) (*mpi)->setKernelSize(side_size); if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // PRIVATE METHOD: ossimAtbController::initializeRemappers() // //***************************************************************************** void ossimAtbController::initializeRemappers() { static const char MODULE[] = "ossimAtbController::initializeRemappers()"; if (traceExec()) CLOG << "entering..." << endl; int num_images = getNumberOfInputs(); //*** // Fetch the overall mosaic bounding rect: //*** ossimGridRemapSource* remapper = PTR_CAST(ossimGridRemapSource, getInput(0)); theBoundingRect = remapper->getBoundingRect(); for (int src=1; srcgetBoundingRect()); } //*** // Loop over each contribution image source chain to fetch each image // bounding rect: //*** double dx_ul, dy_ul, dx_lr, dy_lr; double grid_ul_x, grid_ul_y, grid_lr_x, grid_lr_y; for (int src=0; srcgetBoundingRect()); //*** // Arrive at the number of grid posts from mosaic origin to image's grid // UL and LR corners: //*** dx_ul = (image_rect.ul().x - theBoundingRect.ul().x)/theGridSpacing.x; dy_ul = (image_rect.ul().y - theBoundingRect.ul().y)/theGridSpacing.y; dx_lr = (image_rect.lr().x - theBoundingRect.lr().x)/theGridSpacing.x; dy_lr = (image_rect.lr().y - theBoundingRect.lr().y)/theGridSpacing.y; //*** // Establish the view coordinates for the adjusted image grid: //*** grid_ul_x = theBoundingRect.ul().x + ceil(dx_ul)*theGridSpacing.x; grid_ul_y = theBoundingRect.ul().y + ceil(dy_ul)*theGridSpacing.y; grid_lr_x = theBoundingRect.lr().x + floor(dx_lr)*theGridSpacing.x; grid_lr_y = theBoundingRect.lr().y + floor(dy_lr)*theGridSpacing.y; //*** // Have the remapper initialize a new grid with the given rectangle and // spacing: //*** ossimDrect grid_rect (grid_ul_x, grid_ul_y, grid_lr_x, grid_lr_y); remapper->initialize(grid_rect, theGridSpacing); } if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimAtbController::setGridRemapEngine() // //***************************************************************************** void ossimAtbController::setGridRemapEngine(ossimGridRemapEngine* engine) { static const char MODULE[] = "ossimAtbController::setGridRemapEngine()"; if (traceExec()) CLOG << "entering..." << endl; theGridRemapEngine = engine; //*** // Communicate the new engine to all member's interested: //*** ossimGridRemapSource* remapper; ossimConnectableObject::ConnectableObjectList::iterator iter=theInputObjectList.begin(); while (iter != theInputObjectList.end()) { remapper = PTR_CAST(ossimGridRemapSource, (*iter).get()); remapper->setRemapEngine(engine); iter++; } vector >::iterator match_point = theMatchPoints.begin(); while (match_point != theMatchPoints.end()) { (*match_point)->setGridRemapEngine(engine); match_point++; } if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimAtbController::canConnectMyInputTo() // //***************************************************************************** bool ossimAtbController::canConnectMyInputTo(ossim_int32 /* myInputIndex */, const ossimConnectableObject* object) const { return (object&& PTR_CAST(ossimGridRemapSource, object)); } ossim-Miami-2.9.1/src/imaging/ossimAtbMatchPoint.cpp000066400000000000000000000116671352751253100224040ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains implementation of class // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimAtbMatchPoint.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimAtbMatchPoint:exec"); static ossimTrace traceDebug ("ossimAtbMatchPoint:debug"); using namespace std; //***************************************************************************** // DESTRUCTOR: ~ossimAtbMatchPoint() // // Need to delete each instance of an ossimAtbPointSource in thePointSourceList // //***************************************************************************** ossimAtbMatchPoint::~ossimAtbMatchPoint() { thePointSourceList.clear(); } //***************************************************************************** // METHOD: ossimAtbMatchPoint::addImage() // // Adds a new contribution to the sample set. // //***************************************************************************** void ossimAtbMatchPoint::addImage(ossimGridRemapSource* remapper) { static const char MODULE[] = "ossimAtbMatchPoint::addImage()"; if (traceExec()) CLOG << "entering..." << endl; //*** // Assure that this image contains the view point corresponding to this // matchpoint: //*** if (!remapper->getBoundingRect().pointWithin(theViewPoint)) { if (traceExec()) CLOG << "returning..." << endl; return; } //*** // Instantiate a point source for this image at this view point and // save it in the list: //*** ossimAtbPointSource* point_source = new ossimAtbPointSource(remapper, theViewPoint); thePointSourceList.push_back(point_source); if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimAtbMatchPoint::assignRemapValues() // // The target parameter value computed given all contributions. The target // value is then used to establish the remap parameters for each image at this // points location. // //***************************************************************************** bool ossimAtbMatchPoint::assignRemapValues() { static const char MODULE[] = "ossimAtbMatchPoint::assignRemapValues()"; if (traceExec()) CLOG << "entering..." << endl; //*** // Determine the number of contributors. We require minimum of two: //*** ossim_uint32 num_contributors = (ossim_uint32)thePointSourceList.size(); if (num_contributors < 2) return false; //*** // Hand off the computation of the target pixel to the ATB engine being // used. The engine implements the methods for computing targets, as these // will vary according to algorithm being used: //*** theGridRemapEngine->assignRemapValues(thePointSourceList); if (traceExec()) CLOG << "returning..." << endl; return true; } //***************************************************************************** // METHOD: ossimAtbMatchPoint::setKernelSize(N) // // Hook to set the size of the kernel used by all point sources in computing // their mean pixel value. The kernels will be resized to NxN. // //***************************************************************************** void ossimAtbMatchPoint::setKernelSize(int side_size) { static const char MODULE[] = "ossimAtbController::setKernelSize(N)"; if (traceExec()) CLOG << "entering..." << endl; vector::iterator psi = thePointSourceList.begin(); while (psi != thePointSourceList.end()) (*psi)->setKernelSize(side_size); if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimAtbMatchPoint::setAtbRemapEngine // //***************************************************************************** void ossimAtbMatchPoint::setGridRemapEngine(ossimGridRemapEngine* engine) { static const char MODULE[] = "ossimAtbMatchPoint::setAtbRemapEngine"; if (traceExec()) CLOG << "entering..." << endl; theGridRemapEngine = engine; //*** // Need to communicate this change of engine to the point sources that use // it to arrive at a "source value": //*** vector::iterator source = thePointSourceList.begin(); while (source != thePointSourceList.end()) { (*source)->setGridRemapEngine(engine); source++; } if (traceExec()) CLOG << "returning..." << endl; return; } ossim-Miami-2.9.1/src/imaging/ossimAtbPointSource.cpp000066400000000000000000000147221352751253100226030ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains implementation of class ossimAtbPointSource. // This object provides the statistics associated with a given point on a // given image corresponding to a matchpoint. A matchpoint contains a // collection of these point sources, one for each contributing image. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimAtbPointSource.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimImageSource:exec"); static ossimTrace traceDebug ("ossimImageSource:debug"); static const int DEFAULT_KERNEL_SIZE = 18; // recommend odd number using namespace std; //***************************************************************************** // DEFAULT CONSTRUCTOR: ossimAtbPointSource // //***************************************************************************** ossimAtbPointSource::ossimAtbPointSource() : theRemapSource (0), theGridRemapEngine (0), theKernelSize (DEFAULT_KERNEL_SIZE), theViewPointIsValid (false) { static const char MODULE[] = "ossimAtbPointSource Default Constructor"; if (traceExec()) CLOG << "entering..." << endl; if (traceExec()) CLOG << "returning..." << endl; } //***************************************************************************** // CONSTRUCTOR: ossimAtbPointSource(image_source) // //***************************************************************************** ossimAtbPointSource::ossimAtbPointSource(ossimGridRemapSource* source, const ossimDpt& view_point) : theRemapSource (source), theGridRemapEngine (source->getRemapEngine()), theKernelSize (DEFAULT_KERNEL_SIZE), theViewPointIsValid (false) { static const char MODULE[] = "ossimAtbPointSource Default Constructor"; if (traceExec()) CLOG << "entering..." << endl; setViewPoint(view_point); if (traceExec()) CLOG << "returning..." << endl; } //***************************************************************************** // DESTRUCTOR: ~ossimAtbPointSource() // //***************************************************************************** ossimAtbPointSource::~ossimAtbPointSource() { } //***************************************************************************** // METHOD: ossimAtbPointSource::setRemapSource() // // Sets the pointer to the source of pixels used to compute the stats. // //***************************************************************************** void ossimAtbPointSource::setRemapSource(ossimGridRemapSource* source) { static const char MODULE[] = "ossimAtbPointSource::setRemapSource()"; if (traceExec()) CLOG << "entering..." << endl; theRemapSource = source; //*** // Also fetch the remap engine which should be a derived ossimAtbRemapEngine: //*** theGridRemapEngine = theRemapSource->getRemapEngine(); if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimAtbPointSource::setViewPoint() // // Sets the view coordinates corresponding to this point. // //***************************************************************************** void ossimAtbPointSource::setViewPoint(const ossimDpt& view_point) { static const char MODULE[] = "ossimAtbPointSource::setViewPoint()"; if (traceExec()) CLOG << "entering..." << endl; theViewPoint = view_point; if ((theRemapSource.valid()) && (theRemapSource->getBoundingRect().pointWithin(theViewPoint))) theViewPointIsValid = true; else theViewPointIsValid = false; if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimAtbPointSource::getSourceValue() // // Returns the computed value vector corresponding to the region about the // view point. The definition of "value" is implemented by theGridRemapEngine. // //***************************************************************************** void ossimAtbPointSource::getSourceValue(void* value_vector) { static const char MODULE[] = "ossimAtbPointSource::getSourceValue()"; if (traceExec()) CLOG << "entering..." << endl; //*** // Verify that members are initialized before processing: //*** if ((!theViewPointIsValid) || (!theRemapSource) || (!theGridRemapEngine)) { CLOG <<"ERROR: This object was not properly initialized before attempting" <<" to compute target value! Returning usassigned vector..."< kernel_data = theRemapSource->getTile(kernel_rect); //*** // Fetch the value of the data kernel. Note: this is not necessarily in // the same color space as the pixels. It depends on which engine is being // utilized: //*** theGridRemapEngine->computeSourceValue(kernel_data, value_vector); // delete kernel_data; if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimAtbPointSource:: setKernelSize(N) // // Method to set the kernel size used in computing statistics. The kernel // will be resized to NxN. // //***************************************************************************** void ossimAtbPointSource::setKernelSize(int side_size) { static const char MODULE[] = "ossimAtbPointSource::setKernelSize()"; if (traceExec()) CLOG << "entering..." << endl; theKernelSize = side_size; if (traceExec()) CLOG << "returning..." << endl; return; } ossim-Miami-2.9.1/src/imaging/ossimBandAverageFilter.cpp000066400000000000000000000250701352751253100232050ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBandAverageFilter.cpp 17206 2010-04-25 23:20:40Z dburken $ #include // used for constructing and an ossimImageData object #include // used for error reporting and for general info reporting such as warnings #include #include #include static const char* WEIGHTS_KW = "weights"; RTTI_DEF1(ossimBandAverageFilter, "ossimBandAverageFilter", ossimImageSourceFilter); using namespace std; ossimBandAverageFilter::ossimBandAverageFilter() :ossimImageSourceFilter(), theTile(NULL) { } ossimBandAverageFilter::ossimBandAverageFilter(ossimImageSource* input, const std::vector& weights) :ossimImageSourceFilter(input), theTile(NULL), theWeights(weights) { } ossimBandAverageFilter::~ossimBandAverageFilter() { } ossim_uint32 ossimBandAverageFilter::getNumberOfOutputBands()const { if(isSourceEnabled()) { return 1; } return ossimImageSourceFilter::getNumberOfOutputBands(); } ossimRefPtr ossimBandAverageFilter::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { // first we will check to see if we have an input connection // if(!theInputConnection) { // this will probably be null since we aren't initialized. // we really need to creae a default blank tile in OSSIM that is returned return theTile; } ossimRefPtr inputData = theInputConnection->getTile(rect, resLevel); if(!inputData.valid()) { return inputData; } // If we are disabled or if the data object is empty or NULL or // not enough bands we don't need to run our algorithm so return the input // tile. if(!isSourceEnabled() || (inputData->getDataObjectStatus() == OSSIM_NULL)|| (inputData->getDataObjectStatus() == OSSIM_EMPTY)|| (inputData->getNumberOfBands() < 2)) { return inputData; } // check to see if we are initialized if(!theTile.valid()) { initialize(); } theTile->setImageRectangle(rect); // now lets set up the template method to operate in native type and run // the algorithm // switch(inputData->getScalarType()) { case OSSIM_UCHAR: { averageInput((ossim_uint8)0, // setup template variable inputData); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { averageInput((ossim_uint16)0, // setup template variable inputData); break; } case OSSIM_SSHORT16: { averageInput((ossim_sint16)0, // setup template variable inputData); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT: { averageInput((float)0, // setup template variable inputData); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_DOUBLE: { averageInput((double)0, // setup template variable inputData); break; } default: { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "Unsupported scalar type in file %d at line %d", __FILE__, __LINE__); theTile->makeBlank(); break; } } theTile->validate(); return theTile; } void ossimBandAverageFilter::initialize() { ossimImageSourceFilter::initialize(); // theInputConnection is defined in ossimImageSourceFilter // It is automatically set when an input is connected to this // object if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, this); // now initialize the tile theTile->initialize(); checkWeights(); } } double ossimBandAverageFilter::getNullPixelValue(ossim_uint32 band)const { if(!isSourceEnabled()) { return ossimImageSourceFilter::getNullPixelValue(band); } // lets use the first band's null value as our null return ossimImageSourceFilter::getMinPixelValue(0); } double ossimBandAverageFilter::getMinPixelValue(ossim_uint32 band)const { if(!isSourceEnabled()||!theInputConnection) { return ossimImageSourceFilter::getMinPixelValue(band); } // loop through each band and find the min pix value ossim_uint32 bandIndex = 0; ossim_uint32 inputBands = theInputConnection->getNumberOfOutputBands(); double minValue = ossim::defaultMax(OSSIM_DOUBLE); for(bandIndex = 0; bandIndex < inputBands; ++bandIndex) { double minPix = theInputConnection->getMinPixelValue(bandIndex); if(minPix < minValue) { minValue = minPix; } } return minValue; } double ossimBandAverageFilter::getMaxPixelValue(ossim_uint32 band)const { if(!isSourceEnabled()) { return ossimImageSourceFilter::getMaxPixelValue(band); } // loop through each band and find the max pix value ossim_uint32 bandIndex = 0; ossim_uint32 inputBands = theInputConnection->getNumberOfOutputBands(); double maxValue = ossim::defaultMin(OSSIM_DOUBLE); for(bandIndex = 0; bandIndex < inputBands; ++bandIndex) { double maxPix = theInputConnection->getMaxPixelValue(bandIndex); if(maxPix > maxValue) { maxValue = maxPix; } } return maxValue; } void ossimBandAverageFilter::checkWeights() { // we have not been initialzed yet // if(!theTile) { return; } // Check to see if the weights array is the same size as the input // list. If not then resize it and populate them with the same weight // value. It does not matter if they sum to one since we will perform // a weighted average in the execution of the algorithm // if(theWeights.size() != theInputConnection->getNumberOfOutputBands()) { theWeights.resize(theInputConnection->getNumberOfOutputBands()); std::fill(theWeights.begin(), theWeights.end(), 1); } } template void ossimBandAverageFilter::averageInput( T /* dummyVariable */, // used only for template type, value ignored ossimRefPtr inputDataObject) { // since we have already checked the input for empty or // null we will now execute the algorithm. We will make // // std::vector inputBands(inputDataObject->getNumberOfBands()); std::vector nullValues(inputDataObject->getNumberOfBands()); ossim_uint32 i = 0; // for efficiency we will copy the band pointers and // null values so we don't have extra function calls // on a per band basis // for(i = 0; i < inputDataObject->getNumberOfBands(); ++i) { inputBands[i] = static_cast(inputDataObject->getBuf(i)); nullValues[i] = inputDataObject->getNullPix(i); } // store the output buffer pointer T* outputBuf = static_cast(theTile->getBuf(0)); // setup index values and boundary values ossim_uint32 upperBound = theTile->getWidth()*theTile->getHeight(); ossim_uint32 bandIndex = 0; ossim_uint32 numberOfBands = inputDataObject->getNumberOfBands(); double outputNullPix = theTile->getNullPix(0); for(i = 0; i < upperBound; ++i) { double value=0.0; double sumWeights=0.0; // loop over each band only using the valid pixel data // in the weighted average. // for(bandIndex = 0; bandIndex < numberOfBands; ++bandIndex) { // if valid then muliply the value by the weight and add it to // current pixel value if(*inputBands[bandIndex] != nullValues[bandIndex]) { value += theWeights[bandIndex]*((double)*inputBands[bandIndex]); sumWeights += theWeights[bandIndex]; } // increment to the next pixel for the next time around ++inputBands[bandIndex]; } // check to see if we had any valid data. If we did the weight // should be greater than 0 if(sumWeights != 0.0) { value /= sumWeights; } else { // else we set the pixel to the output null value value = outputNullPix; } // store the result in the outputBuffer. *outputBuf = static_cast(value); // advance the output buffer to the next pixel value ++outputBuf; } } bool ossimBandAverageFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { // get the value of the stored keyword ossimString weightString = kwl.find(prefix, WEIGHTS_KW); weightString = weightString.trim(); theWeights.clear(); if(weightString != "") { // split the string list into an array of strings std::vector weightList = weightString.split(" "); // resize the weights to the size of the weight list // theWeights.resize(weightList.size()); ossim_uint32 i = 0; // now store the weights to the array for(i = 0; i < theWeights.size(); ++i) { theWeights[i] = weightList[i].toDouble(); } } // call base class to continue the load state return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimBandAverageFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { std::stringstream out; // copy the weights to a memory stream separated by space std::copy(theWeights.begin(), theWeights.end(), ostream_iterator(out, " ")); ossimString weightString = out.str(); weightString = weightString.trim(); kwl.add(prefix, // prefix to help uniquely id or attributes WEIGHTS_KW, // the keyword to identity our attribute weightString.c_str(), // the value true); // overwrite if already in the keywordlist // call base classes save to allow us to pass the information up return ossimImageSourceFilter::saveState(kwl, prefix); } double ossimBandAverageFilter::getWeight(ossim_uint32 band)const { if(band < theWeights.size()) { return theWeights[band]; } return 0.0; } void ossimBandAverageFilter::setWeight(ossim_uint32 band, double weight) { if(band < theWeights.size()) { theWeights[band] = fabs(weight); } } ossim-Miami-2.9.1/src/imaging/ossimBandClipFilter.cpp000066400000000000000000000476521352751253100225340ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBandClipFilter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include RTTI_DEF1(ossimBandClipFilter, "ossimBandClipFilter", ossimImageSourceFilter); using namespace std; ossimBandClipFilter::ossimBandClipFilter() :ossimImageSourceFilter(), theClipType(ossimBandClipType_NONE), theTile(NULL) { theTile = new ossimImageData(this, // I am the owner, OSSIM_NORMALIZED_FLOAT, 1); theTile->initialize(); } ossimBandClipFilter::ossimBandClipFilter(ossimImageSource* inputSource, const vector& minPix, const vector& maxPix, ossimBandClipType clipType) :ossimImageSourceFilter(inputSource), theClipType(clipType), theTile(NULL) { theTile = new ossimImageData(this, // I am the owner, OSSIM_NORMALIZED_FLOAT, 1); theTile->initialize(); setMinMaxPix(minPix, maxPix); } ossimBandClipFilter::ossimBandClipFilter(ossimImageSource* inputSource, double minPix, double maxPix, ossimBandClipType clipType) :ossimImageSourceFilter(inputSource), theClipType(clipType), theTile(NULL) { theTile = new ossimImageData(this, // I am the owner, OSSIM_NORMALIZED_FLOAT, 1); theTile->initialize(); theMinPix.push_back(minPix); theMaxPix.push_back(maxPix); } ossimBandClipFilter::~ossimBandClipFilter() { } void ossimBandClipFilter::setClipType(ossimBandClipType clipType) { theClipType = clipType; } ossimBandClipFilter::ossimBandClipType ossimBandClipFilter::getClipType()const { return theClipType; } ossim_uint32 ossimBandClipFilter::getNumberOfValues()const { // We make sure that all arrays have the same number // of elements so we can use the size of any of them. return (ossim_uint32)theMinPix.size(); } void ossimBandClipFilter::setNumberOfValues(ossim_uint32 size) { // lets do a non destructive set. That way we can // grow or shrink the list without destroying // the original values. // if(!size) { theMinPix.clear(); theMaxPix.clear(); theMedian.clear(); return; } vector tempMin = theMinPix; vector tempMax = theMaxPix; theMinPix.resize(size); theMaxPix.resize(size); theMedian.resize(size); ossim_uint32 upperBound = (ossim_uint32)min(theMinPix.size(), tempMin.size()); ossim_uint32 index = 0; for(index = 0; index < upperBound; ++index) { theMinPix[index] = tempMin[index]; theMaxPix[index] = tempMax[index]; theMinPix[index] = theMinPix[index]>1?1:theMinPix[index]; theMinPix[index] = theMinPix[index]<0?0:theMinPix[index]; theMaxPix[index] = theMaxPix[index]>1?1:theMaxPix[index]; theMaxPix[index] = theMaxPix[index]<0?0:theMaxPix[index]; theMedian[index] = (theMaxPix[index] + theMinPix[index])/2.0; } for(;index < theMinPix.size();++index) { theMinPix[index] = OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT; theMaxPix[index] = OSSIM_DEFAULT_MAX_PIX_NORM_FLOAT; theMedian[index] = (theMaxPix[index] + theMinPix[index])/2.0; theMedian[index] = (theMaxPix[index] + theMinPix[index])/2.0; } } void ossimBandClipFilter::setMinMaxPix(const vector& minPix, const vector& maxPix) { theMinPix = minPix; theMaxPix = maxPix; setNumberOfValues((ossim_uint32)max(theMinPix.size(), theMaxPix.size())); } const std::vector& ossimBandClipFilter::getMinPixList()const { return theMinPix; } const std::vector ossimBandClipFilter::getMaxPixList()const { return theMaxPix; } double ossimBandClipFilter::getMinPix(ossim_uint32 index)const { return index ossimBandClipFilter::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if(!theInputConnection) { return NULL; } ossimRefPtr data = theInputConnection->getTile(rect, resLevel); if(!data.get()) { return data; } ossimDataObjectStatus status = data->getDataObjectStatus(); if((status != OSSIM_NULL) && (status != OSSIM_EMPTY)) { ossim_uint32 dw = data->getWidth(); ossim_uint32 dh = data->getHeight(); ossim_uint32 db = data->getNumberOfBands(); ossim_uint32 tw = theTile->getWidth(); ossim_uint32 th = theTile->getHeight(); ossim_uint32 tb = theTile->getNumberOfBands(); if(((tw*th)!=(dw*dh))|| (tb != db)) { theTile = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT, db, dw, dh); theTile->initialize(); } if(getNumberOfValues() != theTile->getNumberOfBands()) { // Should this go on??? (drb) ossimNotify(ossimNotifyLevel_WARN) << "ossimBandClipFilter::getTile\n" << "getNumberOfValues() != theTile->getNumberOfBands" << endl; } data->copyTileToNormalizedBuffer(static_cast(theTile->getBuf())); theTile->setDataObjectStatus(data->getDataObjectStatus()); switch(theClipType) { case ossimBandClipType_CLIP: { runClip(); break; } case ossimBandClipType_CLAMP: { runClamp(); break; } case ossimBandClipType_LINEAR_STRETCH: { runLinearStretch(); break; } case ossimBandClipType_MEDIAN_STRETCH: { runMedianStretch(); break; } default: break; } data->copyNormalizedBufferToTile(static_cast(theTile->getBuf())); } return data; } void ossimBandClipFilter::runClip() { ossim_uint32 offset = 0; ossim_uint32 upperBound = theTile->getWidth()*theTile->getHeight(); for(ossim_uint32 band =0; band < theTile->getNumberOfBands(); ++band) { float *buf = static_cast(theTile->getBuf(band)); float minPix = theMinPix[band]; float maxPix = theMaxPix[band]; float nullPix = theTile->getNullPix(band); if(buf) { for(offset = 0; offset < upperBound; ++offset) { if((*buf < minPix)|| (*buf > maxPix)) { *buf = nullPix; } ++buf; } } } theTile->validate(); } void ossimBandClipFilter::runClamp() { ossim_uint32 offset = 0; ossim_uint32 upperBound = theTile->getWidth()*theTile->getHeight(); for(ossim_uint32 band =0; band < theTile->getNumberOfBands(); ++band) { float *buf = static_cast(theTile->getBuf(band)); float minPix = theMinPix[band]; float maxPix = theMaxPix[band]; float nullPix = theTile->getNullPix(band); if(buf) { if(theTile->getDataObjectStatus() == OSSIM_PARTIAL) { for(offset = 0; offset < upperBound; ++offset) { if(*buf != nullPix) { if(*buf < minPix) { *buf = minPix; } else if(*buf > maxPix) { *buf = maxPix; } } ++buf; } } else { for(offset = 0; offset < upperBound; ++offset) { if(*buf < minPix) { *buf = minPix; } else if(*buf > maxPix) { *buf = maxPix; } ++buf; } } } } } void ossimBandClipFilter::runLinearStretch() { ossim_uint32 bands = (ossim_uint32)min(theTile->getNumberOfBands(), (ossim_uint32)theMinPix.size()); ossim_uint32 w = theTile->getWidth(); ossim_uint32 h = theTile->getHeight(); ossim_uint32 upperBound = w*h; const double* minPixArray = theTile->getMinPix(); const double* maxPixArray = theTile->getMaxPix(); float* *bandArray = new float*[bands]; ossim_uint32 band = 0; for(band = 0; band < bands; ++band) { bandArray[band] = static_cast(theTile->getBuf(band)); } if(theTile->getDataObjectStatus() == OSSIM_PARTIAL) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if(!theTile->isNull(offset)) { for(band = 0; band < bands; ++band) { double delta = theMaxPix[band] - theMinPix[band]; double t = (bandArray[band][offset] - theMinPix[band])/delta; if(t < 0) { bandArray[band][offset] = minPixArray[band]; } else if(t > 1) { bandArray[band][offset] = maxPixArray[band]; } else { bandArray[band][offset] = t; } } } } } else if(theTile->getDataObjectStatus() == OSSIM_FULL) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { for(band = 0; band < bands; ++band) { double delta = theMaxPix[band] - theMinPix[band]; double t = (bandArray[band][offset] - theMinPix[band])/delta; if(t < 0) { bandArray[band][offset] = minPixArray[band]; } else if(t > 1) { bandArray[band][offset] = maxPixArray[band]; } else { bandArray[band][offset] = t; } } } } delete [] bandArray; } void ossimBandClipFilter::runMedianStretch() { ossim_uint32 bands = theTile->getNumberOfBands(); float* *bandArray = new float*[bands]; ossim_uint32 band = 0; for(band = 0; band < bands; ++band) { bandArray[band] = static_cast(theTile->getBuf(band)); } ossim_uint32 upperBound = theTile->getWidth()*theTile->getHeight(); if(theTile->getDataObjectStatus() == OSSIM_PARTIAL) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if(!theTile->isNull(offset)) { for(band = 0; band < bands; ++band) { double side = (theMedian[band] - (double)bandArray[band][offset]); if(side > 0) // on the left { double delta = fabs(theMedian[band] - theMinPix[band]); double t = ((double)bandArray[band][offset] - theMinPix[band])/delta; if(t < 0) { bandArray[band][offset] = OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT; } else if(t > 1) { bandArray[band][offset] = theMedian[band]; } else { bandArray[band][offset] = theMedian[band]*t; } } else // on the right { double delta = theMaxPix[band] - theMedian[band]; double t = ((double)bandArray[band][offset] - theMedian[band])/delta; if(t < 0) { bandArray[band][offset] = theMedian[band]; } else if(t > 1) { bandArray[band][offset] = OSSIM_DEFAULT_MAX_PIX_NORM_FLOAT; } else { bandArray[band][offset] = theMedian[band]+delta*t; } } } } } } else if(theTile->getDataObjectStatus() == OSSIM_FULL) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { for(band = 0; band < bands; ++band) { double side = (theMedian[band] - (double)bandArray[band][offset]); if(side > 0) // on the left { double delta = fabs(theMedian[band] - theMinPix[band]); double t = ((double)bandArray[band][offset] - theMinPix[band])/delta; if(t < 0) { bandArray[band][offset] = OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT; } else if(t > 1) { bandArray[band][offset] = theMedian[band]; } else { bandArray[band][offset] = theMedian[band]*t; } } else // on the right { double delta = theMaxPix[band] - theMedian[band]; double t = ((double)bandArray[band][offset] - theMedian[band])/delta; if(t < 0) { bandArray[band][offset] = theMedian[band]; } else if(t > 1) { bandArray[band][offset] = OSSIM_DEFAULT_MAX_PIX_NORM_FLOAT; } else { bandArray[band][offset] = theMedian[band]+delta*t; } } } } } delete [] bandArray; } void ossimBandClipFilter::initialize() { ossimImageSourceFilter::initialize(); if(theInputConnection) { ossim_uint32 bands = theInputConnection->getNumberOfOutputBands(); if(bands) { if(theMinPix.size() != bands) { setNumberOfValues(bands); } } } } bool ossimBandClipFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimImageSourceFilter::loadState(kwl, prefix); if(result) { ossimString minRegExpression = ossimString("^(") + ossimString(prefix) + "min[0-9]+)"; ossimString maxRegExpression = ossimString("^(") + ossimString(prefix) + "max[0-9]+)"; ossimString medianRegExpression = ossimString("^(") + ossimString(prefix) + "median[0-9]+)"; ossim_uint32 numberOfMins = kwl.getNumberOfSubstringKeys(minRegExpression); ossim_uint32 numberOfMaxs = kwl.getNumberOfSubstringKeys(maxRegExpression); ossim_uint32 numberOfMedians = kwl.getNumberOfSubstringKeys(medianRegExpression); theMinPix.clear(); theMaxPix.clear(); theMedian.clear(); if(numberOfMins != numberOfMaxs) { ossim_int32 temp = (ossim_int32)min(numberOfMins, numberOfMaxs); numberOfMins = temp; numberOfMaxs = temp; } if(numberOfMins> 0) { ossimString prefixMin = ossimString(prefix) + "min"; ossimString prefixMax = ossimString(prefix) + "max"; ossimString prefixMedian = ossimString(prefix) + "median"; ossim_uint32 numberOfMatches = 0; ossim_uint32 index = 0; const char* value=(const char*)NULL; while(numberOfMatches < numberOfMins) { value = kwl.find(prefixMin.c_str(), ossimString::toString(index).c_str()); if(value) { theMinPix.push_back(ossimString(value).toDouble()); ++numberOfMatches; } ++index; } index = 0; numberOfMatches = 0; while(numberOfMatches < numberOfMaxs) { value = kwl.find(prefixMax.c_str(), ossimString::toString(index).c_str()); if(value) { theMaxPix.push_back(ossimString(value).toDouble()); ++numberOfMatches; } ++index; } if(numberOfMedians != numberOfMins) { for(index = 0; index < theMaxPix.size(); ++index) { theMedian.push_back((theMinPix[index]+theMaxPix[index])/2.0); } } else { index = 0; numberOfMatches = 0; while(numberOfMatches < numberOfMedians) { value = kwl.find(prefixMedian.c_str(), ossimString::toString(index).c_str()); if(value) { theMedian.push_back(ossimString(value).toDouble()); ++numberOfMatches; } ++index; } } } } const char* clip_type = kwl.find(prefix, "clip_type"); if(clip_type) { ossimString clipType = clip_type; clipType = clipType.upcase().trim(); if(clipType == "NONE") { theClipType = ossimBandClipType_NONE; } else if(clipType == "CLIP") { theClipType = ossimBandClipType_CLIP; } else if(clipType == "LINEAR_STRETCH") { theClipType = ossimBandClipType_LINEAR_STRETCH; } else if(clipType == "MEDIAN_STRETCH") { theClipType = ossimBandClipType_MEDIAN_STRETCH; } } else { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimBandClipFilter::loadState NOTICE:\n" << "Clip type not given defaulting to NONE" << endl; theClipType = ossimBandClipType_NONE; } return result; } bool ossimBandClipFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString minPrefix = ossimString("min"); ossimString maxPrefix = ossimString("max"); ossimString medianPrefix = ossimString("median"); for(ossim_uint32 index = 1; index <= getNumberOfValues(); ++index) { ossimString value = (minPrefix+ossimString::toString(index)); kwl.add(prefix, value.c_str(), theMinPix[index-1], true); value = (maxPrefix+ossimString::toString(index)); kwl.add(prefix, value.c_str(), theMaxPix[index-1], true); value = (medianPrefix+ossimString::toString(index)); kwl.add(prefix, value.c_str(), theMedian[index-1], true); } ossimString clipType; switch(theClipType) { case ossimBandClipType_NONE: { clipType = "NONE"; break; } case ossimBandClipType_CLIP: { clipType = "CLIP"; break; } case ossimBandClipType_LINEAR_STRETCH: { clipType = "LINEAR_STRETCH"; break; } case ossimBandClipType_MEDIAN_STRETCH: { clipType = "MEDIAN_STRETCH"; break; } default: break; } kwl.add(prefix, "clip_type", clipType.c_str(), true); return ossimImageSourceFilter::saveState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimBandLutFilter.cpp000066400000000000000000000306271352751253100224030ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //************************************************************************* // $Id: ossimBandLutFilter.cpp 23242 2015-04-08 17:31:35Z dburken $ #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimBandLutFilter, "ossimBandLutFilter", ossimImageSourceFilter); static const char* MODE_KW = "mode"; static const char* LUT_FILE_KW = "lut_file"; using namespace std; ossimBandLutFilter::ossimBandLutFilter() :ossimImageSourceFilter(), theMode(INTERPOLATED), theTile(0), theLutFile(""), theOutputScalarType(OSSIM_SCALAR_UNKNOWN) { setDescription("Look-up-table remapper for band-independent remapping."); } ossimBandLutFilter::~ossimBandLutFilter() { } ossimRefPtr ossimBandLutFilter::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection || (theLut.size() == 0)) return 0; ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if (!inputTile || !inputTile->getBuf()) return 0; if(!theTile) { allocate(); if (!theTile) return 0; } theTile->setImageRectangle(tileRect); theTile->makeBlank(); // Quick handling special case of empty input tile: if (inputTile->getDataObjectStatus() == OSSIM_EMPTY) return theTile; const double null_index = theInputConnection->getNullPixelValue(); const double null_value = theTile->getNullPix(0); // assuming same null for all bands ossim_uint32 maxLength = inputTile->getWidth()*inputTile->getHeight(); double index, value; double min_value=OSSIM_DEFAULT_MAX_PIX_DOUBLE; double max_value=OSSIM_DEFAULT_MIN_PIX_DOUBLE; ossim_uint32 numBands = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < numBands; ++band) { std::map& bandMap = theLut[band]; std::map::const_iterator lut_entry; for (ossim_uint32 pixel=0; pixelgetPix(pixel, band); if (index == null_index) continue; // Now perform look-up depending on mode: if (theMode == LITERAL) { lut_entry = bandMap.find(index); if (lut_entry == bandMap.end()) value = null_value; else value = lut_entry->second; } else { // Interpolated mode performs interpolation here between the line segments vertices: lut_entry = bandMap.find(index); if (lut_entry != bandMap.end()) { // Got exact match, no interpolation needed: value = lut_entry->second; } else { lut_entry = bandMap.upper_bound(index); if ((lut_entry == bandMap.end()) || (lut_entry == bandMap.begin())) value = null_value; else { // Need to linearly interpolate: double index_hi = lut_entry->first; double value_hi (lut_entry->second); --lut_entry; double index_lo = lut_entry->first; double value_lo (lut_entry->second); double w_lo = (index_hi - index)/(index_hi - index_lo); double w_hi = 1.0 - w_lo; value = value_hi*w_hi + value_lo*w_lo; } } } if (value < min_value) min_value = value; if (value > max_value) max_value = value; // Assign this output pixel according to desired scalar type: switch(theOutputScalarType) { case OSSIM_DOUBLE: theTile->getDoubleBuf(band)[pixel] = value; theTile->setMinPix(min_value); theTile->setMaxPix(max_value); break; case OSSIM_SSHORT16: theTile->getSshortBuf(band)[pixel] = value; break; case OSSIM_FLOAT: theTile->setMinPix(min_value); theTile->setMaxPix(max_value); theTile->getFloatBuf(band)[pixel] = value; break; case OSSIM_NORMALIZED_FLOAT: theTile->getFloatBuf(band)[pixel] = value; break; case OSSIM_UCHAR: theTile->getUcharBuf(band)[pixel] = value; break; case OSSIM_USHORT16: theTile->getUshortBuf(band)[pixel] = value; break; case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: theTile->getUshortBuf(band)[pixel] = value; break; default: break; } } // end loop over band's pixels } // end loop over tile's bands theTile->validate(); return theTile; } void ossimBandLutFilter::allocate() { if(!theInputConnection) return; theTile = ossimImageDataFactory::instance()->create(this, getNumberOfInputBands(), this); if(!theTile.valid()) return; switch(theOutputScalarType) { case OSSIM_SSHORT16: theTile->setMinPix(-32768); theTile->setMaxPix(32767); break; case OSSIM_NORMALIZED_FLOAT: theTile->setMinPix(0.0); theTile->setMaxPix(1.0); break; case OSSIM_UCHAR: theTile->setMinPix(0); theTile->setMaxPix(255); break; case OSSIM_USHORT16: theTile->setMinPix(0); theTile->setMaxPix(65535); break; case OSSIM_USHORT11: theTile->setMinPix(0); theTile->setMaxPix(2047); break; case OSSIM_USHORT12: theTile->setMinPix(0); theTile->setMaxPix(4095); break; case OSSIM_USHORT13: theTile->setMinPix(0); theTile->setMaxPix(8191); break; case OSSIM_USHORT14: theTile->setMinPix(0); theTile->setMaxPix(16383); break; case OSSIM_USHORT15: theTile->setMinPix(0); theTile->setMaxPix(32767); break; default: break; } theTile->initialize(); } void ossimBandLutFilter::initialize() { // This assigns theInputConnection if one is there. ossimImageSourceFilter::initialize(); // theTile will get allocated on first getTile call. theTile = 0; if ( theInputConnection ) { // Initialize the chain on the left hand side of us. theInputConnection->initialize(); } } bool ossimBandLutFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { if (theLut.empty()) return true; ossimString value; switch (theMode) { case LITERAL: value = "literal"; break; case INTERPOLATED: default: value = "interpolated"; break; } kwl.add(prefix, MODE_KW, value.c_str(), true); bool rtn_stat = true; // Save the actual LUT: int numBands = theLut.size(); for (int band=0; band 1) base_keyword << "band" << band << "."; std::map::const_iterator iter = theLut[band].begin(); ossim_uint32 entry = 0; while (iter != theLut[band].end()) { ostringstream inKey, outKey; inKey << base_keyword.str() << "entry" << entry <<".in"; outKey << base_keyword.str() << "entry" << entry <<".out"; ostringstream inVal, outVal; inVal << iter->first; outVal << iter->second; kwl.add(prefix, inKey.str().c_str(), inVal.str().c_str()); kwl.add(prefix, outKey.str().c_str(), outVal.str().c_str()); ++iter; ++entry; } } rtn_stat &= ossimImageSourceFilter::saveState(kwl, prefix); return rtn_stat; } bool ossimBandLutFilter::loadState(const ossimKeywordlist& orig_kwl, const char* prefix) { bool return_state = true; ossimKeywordlist kwl (orig_kwl); // need non-const copy // First look for a LUT filename, and add its contents to the original KWL: theLutFile = kwl.find(prefix, LUT_FILE_KW); if (!theLutFile.empty()) { // Need new (non const) KWL to hold merged contents, maintaining proper prefix if any: ossimKeywordlist lut_kwl; if (lut_kwl.addFile(theLutFile)) kwl.add(prefix, lut_kwl, false); // appends all entries of lut_kwl with prefix before adding } theMode = INTERPOLATED; ossimString lookup = kwl.find(prefix, MODE_KW); if (lookup.contains("literal")) theMode = LITERAL; int scalar = ossimScalarTypeLut::instance()->getEntryNumber(kwl, prefix); if (scalar != ossimLookUpTable::NOT_FOUND) setOutputScalarType(static_cast(scalar)); return_state &= initializeLut(kwl, prefix); return_state &= ossimImageSourceFilter::loadState(orig_kwl, prefix); return return_state; } bool ossimBandLutFilter::initializeLut(const ossimKeywordlist& kwl, const char* prefix) { theLut.clear(); ossim_uint32 numBands = getNumberOfInputBands(); bool usingBandPrefix = true; if (numBands <= 1) { ossim_uint32 numEntries = kwl.numberOf(prefix, "band0.in"); if (numEntries == 0) { usingBandPrefix = false; numBands = 1; } } ossim_uint32 band = 0; while (true) { ossim_uint32 entry = 0; map bandMap; while (true) { ostringstream inKey, outKey; if (usingBandPrefix) { inKey << "band" << band << ".entry" << entry <<".in"; outKey << "band" << band << ".entry" << entry <<".out"; } else { inKey << "entry" << entry <<".in"; outKey << "entry" << entry <<".out"; } ossimString inVal = kwl.find(prefix, inKey.str().c_str()); if (inVal.empty()) break; ossimString outVal = kwl.find(prefix, outKey.str().c_str()); if (outVal.empty()) break; bandMap.insert(std::pair(inVal.toDouble(), outVal.toDouble())); ++entry; } if (bandMap.empty()) break; theLut.push_back(bandMap); ++band; if ((numBands == 1) || !usingBandPrefix) break; } // Band still 0 would indicate a failure reading the first band entry: if (band == 0) return false; // Check that the correct number of bands are represented: if (theInputConnection && (numBands > band)) { if (!usingBandPrefix) { // Use the same map for all bands for (ossim_uint32 i=1; i nullBandMap; for (; bandgetEntryNumber(scalarType.c_str()); if (scalar != ossimLookUpTable::NOT_FOUND) { setOutputScalarType(static_cast(scalar)); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimScalarRemapper ERROR:" << "\nUnknown scalar type: " << scalarType.c_str() << std::endl; } } ossim-Miami-2.9.1/src/imaging/ossimBandMergeSource.cpp000066400000000000000000000161161352751253100227060ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBandMergeSource.cpp 23611 2015-11-06 19:37:12Z gpotts $ #include #include #include #include RTTI_DEF1(ossimBandMergeSource, "ossimBandMergeSource", ossimImageCombiner) ossimBandMergeSource::ossimBandMergeSource() :ossimImageCombiner(), theNumberOfOutputBands(0), theTile(NULL) { } ossimBandMergeSource::ossimBandMergeSource(ossimConnectableObject::ConnectableObjectList& inputSources) :ossimImageCombiner(inputSources), theNumberOfOutputBands(0), theTile(NULL) { initialize(); } ossimBandMergeSource::~ossimBandMergeSource() { theNumberOfOutputBands = 0; } ossimRefPtr ossimBandMergeSource::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { ossim_uint32 layerIdx = 0; if( ( getNumberOfInputs() == 1) || !isSourceEnabled() ) { return getNextTile(layerIdx, 0, tileRect, resLevel); } // test if initialized if(!theTile.get()) { allocate(); } if(!theTile.get()) { return getNextTile(layerIdx, 0, tileRect, resLevel); } long w = tileRect.width(); long h = tileRect.height(); long tileW = theTile->getWidth(); long tileH = theTile->getHeight(); if ((w != tileW) || (h != tileH)) { theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tileW*tileH)) { theTile->initialize(); } else { theTile->makeBlank(); } } else { theTile->makeBlank(); } theTile->setOrigin(tileRect.ul()); getTile(theTile.get(), resLevel); return theTile; } bool ossimBandMergeSource::getTile(ossimImageData* tile, ossim_uint32 resLevel) { if (!tile) return false; ossim_uint32 layerIdx = 0; if( ( getNumberOfInputs() == 1) || !isSourceEnabled() ) { return getNextTile(layerIdx, 0, tile, resLevel); } tile->makeBlank(); ossim_uint32 currentBand = 0; ossim_uint32 maxBands = tile->getNumberOfBands(); ossim_uint32 inputIdx = 0; ossimRefPtr currentTile; for(inputIdx = 0; inputIdx < getNumberOfInputs(); ++inputIdx) { ossimImageSource* input = PTR_CAST(ossimImageSource, getInput(inputIdx)); ossim_uint32 maxInputBands = 1; if(input) { currentTile = input->getTile(tile->getImageRectangle(), resLevel); if(currentTile.valid()) { maxInputBands = currentTile->getNumberOfBands(); //std::cout << "MAX INPUT BANDS === " << maxInputBands << "\n"; if (maxInputBands == 0) maxInputBands = 1; } } else { currentTile = 0; } if(currentTile.valid()&&(currentTile->getBuf())) { for(ossim_uint32 band = 0; (band < maxInputBands) && (currentBand < maxBands); ++band) { //std::cout << "Actual Band, BAND == " << currentBand << ", " << band << "\n"; // clear the band with the actual NULL tile->fill(currentBand, tile->getNullPix(band)); if(currentTile.valid()) { if((currentTile->getDataObjectStatus() != OSSIM_NULL) && (currentTile->getDataObjectStatus() != OSSIM_EMPTY)) { memmove(tile->getBuf(currentBand), currentTile->getBuf(band), currentTile->getSizePerBandInBytes()); } } ++currentBand; } } } tile->validate(); return true; } double ossimBandMergeSource::getNullPixelValue(ossim_uint32 band)const { ossim_uint32 currentBandCount = 0; ossim_uint32 idx = 0; ossim_uint32 maxBands = getNumberOfOutputBands(); if(!maxBands) return 0.0; while((currentBandCount < maxBands)&& (idx < getNumberOfInputs())) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(idx)); if(temp) { ossim_uint32 previousCount = currentBandCount; currentBandCount += temp->getNumberOfOutputBands(); if(band < currentBandCount) { return temp->getNullPixelValue(band - previousCount); } } ++idx; } return ossim::nan(); } double ossimBandMergeSource::getMinPixelValue(ossim_uint32 band)const { ossim_uint32 currentBandCount = 0; ossim_uint32 idx = 0; ossim_uint32 maxBands = getNumberOfOutputBands(); if(!maxBands) return 0.0; while((currentBandCount < maxBands)&& (idx < getNumberOfInputs())) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(idx)); if(temp) { ossim_uint32 previousCount = currentBandCount; currentBandCount += temp->getNumberOfOutputBands(); if(band < currentBandCount) { return temp->getMinPixelValue(band - previousCount); } } ++idx; } return 0.0; } double ossimBandMergeSource::getMaxPixelValue(ossim_uint32 band)const { ossim_uint32 currentBandCount = 0; ossim_uint32 idx = 0; ossim_uint32 maxBands = getNumberOfOutputBands(); if(!maxBands) return 0.0; while((currentBandCount < maxBands)&& (idx < getNumberOfInputs())) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(idx)); if(temp) { ossim_uint32 previousCount = currentBandCount; currentBandCount += temp->getNumberOfOutputBands(); if(band < currentBandCount) { return temp->getMaxPixelValue(band - previousCount); } } ++idx; } return ossim::nan(); } void ossimBandMergeSource::initialize() { ossimImageCombiner::initialize(); if(theTile.get()) { theTile = NULL; } theNumberOfOutputBands = computeNumberOfInputBands(); } void ossimBandMergeSource::allocate() { if(theNumberOfOutputBands) { theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); } } ossim_uint32 ossimBandMergeSource::computeNumberOfInputBands()const { ossim_uint32 result = 0; ossim_uint32 size = getNumberOfInputs(); for(ossim_uint32 index = 0; index < size; ++index) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(index)); if(temp) { if(temp->getNumberOfOutputBands() == 0) { ++result; } else { result += temp->getNumberOfOutputBands(); } } } return result; } ossim_uint32 ossimBandMergeSource::getNumberOfOutputBands() const { if(!theNumberOfOutputBands) { return computeNumberOfInputBands(); } return theNumberOfOutputBands; } ossim-Miami-2.9.1/src/imaging/ossimBandSelector.cpp000066400000000000000000000466671352751253100222640ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts // // Description: // // Contains class declaration for ossimBandSelector. // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimBandSelector:debug"); RTTI_DEF1(ossimBandSelector,"ossimBandSelector", ossimImageSourceFilter) using namespace std; ossimBandSelector::ossimBandSelector() : ossimImageSourceFilter(), m_tile(0), m_outputBandList(0), m_withinRangeFlag(ossimBandSelectorWithinRangeFlagState_NOT_SET), m_passThroughFlag(false), m_delayLoadRgbFlag(false), m_inputIsSelectable(false) { // theEnableFlag = false; // Start off disabled. theEnableFlag = true; } ossimBandSelector::~ossimBandSelector() { m_tile = 0; } ossimRefPtr ossimBandSelector::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if (!theInputConnection) { return ossimRefPtr(); } // Get the tile from the source. ossimRefPtr t = theInputConnection->getTile(tileRect, resLevel); if (!isSourceEnabled()||m_passThroughFlag) { return t; // This tile source bypassed, return the input tile source. } if(!m_tile.valid()) // First time through, might not be initialized... { allocate(); if (!m_tile.valid()) { // Should never happen... return t; // initialize failed. } } m_tile->setImageRectangle(tileRect); if(m_withinRangeFlag == ossimBandSelectorWithinRangeFlagState_NOT_SET) { m_withinRangeFlag = ((outputBandsWithinInputRange() == true) ? ossimBandSelectorWithinRangeFlagState_IN_RANGE: ossimBandSelectorWithinRangeFlagState_OUT_OF_RANGE); } if(m_withinRangeFlag == ossimBandSelectorWithinRangeFlagState_OUT_OF_RANGE) { m_tile->makeBlank(); return m_tile; } if ( !t.valid() || (t->getDataObjectStatus() == OSSIM_EMPTY) || (t->getDataObjectStatus() == OSSIM_NULL)) { //--- // Since we're enabled, we must return our tile not "t" so the // correct number of bands goes through the chain. //--- m_tile->makeBlank(); return m_tile; } // Copy selected bands to our tile. for ( ossim_uint32 i = 0; i < m_outputBandList.size(); ++i) { m_tile->assignBand(t.get(), m_outputBandList[i], i); } m_tile->validate(); return m_tile; } void ossimBandSelector::setThreeBandRgb() { m_outputBandList.clear(); m_delayLoadRgbFlag = true; initialize(); } void ossimBandSelector::setOutputBandList( const vector& outputBandList, bool disablePassThru) { if ( outputBandList.size() ) { m_outputBandList = outputBandList; // Assign the new list. m_passThroughFlag = false; // Assume no pass thru first if ( !disablePassThru ) { bool setBands = false; ossimRefPtr ih = getBandSelectableImageHandler(); if ( ih.valid() ) { // Our input is a single image chain that can do band selection. if ( ih->setOutputBandList( outputBandList ) ) { m_passThroughFlag = true; setBands = true; m_tile = 0; // Don't need. } } if ( setBands == false ) { if ( m_tile.valid() ) { // Check the tile band size and scalar. if ( ( m_tile->getNumberOfBands() != outputBandList.size() ) || ( m_tile->getScalarType() != theInputConnection->getOutputScalarType() ) ) { m_tile = 0; // Force an allocate call next getTile. } } m_withinRangeFlag = ossimBandSelectorWithinRangeFlagState_NOT_SET; checkPassThrough(); //theOrderedCorrectlyFlag = isOrderedCorrectly(); } } } } ossim_uint32 ossimBandSelector::getNumberOfOutputBands() const { ossim_uint32 bands; if(isSourceEnabled()) { bands = static_cast(m_outputBandList.size()); } else { //--- // Note: // This returns theInputConnection->getNumberOfOutputBands() which is our // input. Calling ossimBandSelector::getNumberOfInputBands() will produce // an error if we are bypassed due to a band selectable image handler. //--- bands = ossimImageSourceFilter::getNumberOfInputBands(); } return bands; } ossim_uint32 ossimBandSelector::getNumberOfInputBands() const { ossim_uint32 bands; // See if we have a single image chain with band selectable image handler. ossimRefPtr ih = getBandSelectableImageHandler(); if ( ih.valid() ) { bands = ih->getNumberOfInputBands(); } else { bands = ossimImageSourceFilter::getNumberOfInputBands(); } return bands; } void ossimBandSelector::initialize() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimBandSelector::initialize() entered...\n"; } // Base class will recapture "theInputConnection". ossimImageSourceFilter::initialize(); m_withinRangeFlag = ossimBandSelectorWithinRangeFlagState_NOT_SET; if(theInputConnection) { if ( !m_outputBandList.size() ) { // First time through... if ( m_delayLoadRgbFlag ) { //--- // "bands" key was set to "rgb" or "default" in loadState but there // was not a connection to derive rgb bands from image handler. //--- if ( getRgbBandList( m_outputBandList ) == false ) { //--- // Could not derive from input. Assuming caller wanted three bands. // Call to checkPassThrough()->outputBandsWithinInputRange() // will check the range of output band list. //--- if( theInputConnection->getNumberOfOutputBands() > 2 ) { m_outputBandList.resize(3); m_outputBandList[0] = 0; m_outputBandList[1] = 1; m_outputBandList[2] = 2; } else { m_outputBandList.resize(1); m_outputBandList[0] = 0; } } m_delayLoadRgbFlag = false; // clear flag. } if ( !m_outputBandList.size() ) { // Set the output band list to input if not set above. theInputConnection->getOutputBandList( m_outputBandList ); } if( m_outputBandList.size() ) { // Call to setOutputBandList configures band selector. setOutputBandList(m_outputBandList); } } // if ( !m_outputBandList.size() ) } // if(theInputConnection) if ( !isSourceEnabled() ) { m_tile = 0; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimBandSelector::initialize() exited...\n"; } } void ossimBandSelector::allocate() { //initialize(); // Update the connection. //theOrderedCorrectlyFlag = isOrderedCorrectly(); m_tile = ossimImageDataFactory::instance()->create(this, this); m_tile->initialize(); } bool ossimBandSelector::isSourceEnabled()const { bool result = ossimImageSourceFilter::isSourceEnabled(); if(result) { // if I am not marked to pass information on through then enable me result = !m_passThroughFlag; } return result; } double ossimBandSelector::getMinPixelValue(ossim_uint32 band)const { if(theInputConnection) { if (isSourceEnabled()) { if(band < m_outputBandList.size()) { return theInputConnection-> getMinPixelValue(m_outputBandList[band]); } else { return theInputConnection->getMinPixelValue(band); } } else { return theInputConnection->getMinPixelValue(band); } } return 0; } double ossimBandSelector::getNullPixelValue(ossim_uint32 band)const { if(theInputConnection) { if (isSourceEnabled()) { if(band < m_outputBandList.size()) { return theInputConnection-> getNullPixelValue(m_outputBandList[band]); } else { return theInputConnection->getNullPixelValue(band); } } else { return theInputConnection->getNullPixelValue(band); } } return 0; } double ossimBandSelector::getMaxPixelValue(ossim_uint32 band)const { if(theInputConnection) { if (isSourceEnabled()) { if(band < m_outputBandList.size()) { return theInputConnection-> getMaxPixelValue(m_outputBandList[band]); } else { return theInputConnection->getMaxPixelValue(band); } } else { return theInputConnection->getMaxPixelValue(band); } } return 1.0/DBL_EPSILON; } bool ossimBandSelector::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString temp; kwl.add(prefix, ossimKeywordNames::NUMBER_OUTPUT_BANDS_KW, static_cast(m_outputBandList.size()), true); ossimString bandsString; ossim::toSimpleStringList(bandsString, m_outputBandList); kwl.add(prefix, ossimKeywordNames::BANDS_KW, bandsString, true); /* for(ossim_uint32 counter = 0; counter < m_outputBandList.size();counter++) { temp = ossimKeywordNames::BAND_KW; temp += ossimString::toString(counter+1); kwl.add(prefix, temp.c_str(), ossimString::toString(m_outputBandList[counter]+1).c_str()); } */ return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimBandSelector::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; ossimImageSourceFilter::loadState(kwl, prefix); m_outputBandList.clear(); ossimString copyPrefix = prefix; ossimString bands = kwl.find(prefix, ossimKeywordNames::BANDS_KW); if(!bands.empty()) { ossimString bs = bands; bs.downcase(); if ( (bs == "rgb" ) || (bs == "default")) { // Flag initialize() to set the band list on first connection. m_delayLoadRgbFlag = true; } else { // Load from key:value, e.g. bands:(2,1,0) ossim::toSimpleVector(m_outputBandList, bands); result = true; } } else { ossimString regExpression = ossimString("^(") + copyPrefix + "band[0-9]+)"; vector keys = kwl.getSubstringKeyList( regExpression ); long numberOfBands = (long)keys.size(); ossim_uint32 offset = (ossim_uint32)(copyPrefix+"band").size(); std::vector::size_type idx = 0; std::vector numberList(numberOfBands); for(idx = 0; idx < keys.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); numberList[idx] = numberStr.toInt(); } std::sort(numberList.begin(), numberList.end()); for(idx=0;idx < numberList.size();++idx) { const char* bandValue = kwl.find(copyPrefix, ("band"+ossimString::toString(numberList[idx])).c_str()); m_outputBandList.push_back( ossimString(bandValue).toLong()-1); } result = true; } initialize(); return result; } void ossimBandSelector::checkPassThrough() { m_passThroughFlag = ((theInputConnection == 0)||!outputBandsWithinInputRange()); // check if marked with improper bands if(m_passThroughFlag) return; if(theInputConnection) { std::vector inputList; theInputConnection->getOutputBandList(inputList); if ( inputList.size() == m_outputBandList.size() ) { const std::vector::size_type SIZE = m_outputBandList.size(); std::vector::size_type i = 0; while (i < SIZE) { if ( inputList[i] != m_outputBandList[i] ) { break; } ++i; } if (i == SIZE) { m_passThroughFlag = true; } } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimBandSelector::isOrderedCorrectly() ERROR: " "Method called prior to initialization!\n"; } } } bool ossimBandSelector::outputBandsWithinInputRange() const { bool result = false; if(theInputConnection) { result = true; const ossim_uint32 HIGHEST_BAND = getNumberOfInputBands() - 1; const ossim_uint32 OUTPUT_BANDS = (ossim_uint32)m_outputBandList.size(); for (ossim_uint32 i=0; i HIGHEST_BAND) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimBandSelector::outputBandsWithinInputRange() ERROR:" << "Output band greater than highest input band. " << m_outputBandList[i] << " > " << HIGHEST_BAND << "." << std::endl; } result = false; break; } } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimBandSelector::outputBandsWithinInputRange() ERROR:" << "Method called prior to initialization!" << std::endl; } } return result; } void ossimBandSelector::getOutputBandList(std::vector& bandList) const { if ( isSourceEnabled()&&m_outputBandList.size() ) { bandList = m_outputBandList; } else if (theInputConnection) { theInputConnection->getOutputBandList(bandList); } else { bandList.clear(); } } ossimString ossimBandSelector::getLongName()const { return ossimString("Band Selector, maps an input band to the output band."); } ossimString ossimBandSelector::getShortName()const { return ossimString("Band Selector"); } void ossimBandSelector::setProperty(ossimRefPtr property) { if( property.valid() ) { if(property->getName() == "bands") { std::vector selection; if(ossim::toSimpleVector(selection, property->valueToString())) { m_outputBandList = selection; setOutputBandList( m_outputBandList ); } } else if(property->getName() == "bandSelection") { ossimString str = property->valueToString(); std::vector str_vec; std::vector int_vec; str.split( str_vec, " " ); for ( ossim_uint32 i = 0; i < str_vec.size(); ++i ) { if(!str_vec[i].empty()) { int_vec.push_back( str_vec[i].toUInt32() ); } } setOutputBandList( int_vec ); } else { ossimImageSourceFilter::setProperty(property); } } } ossimRefPtr ossimBandSelector::getProperty(const ossimString& name)const { if( name == "bands" ) { ossimString bandsString; ossim::toSimpleStringList(bandsString, m_outputBandList); ossimStringProperty* stringProp = new ossimStringProperty(name, bandsString); stringProp->clearChangeType(); stringProp->setReadOnlyFlag(false); stringProp->setCacheRefreshBit(); return stringProp; } else if( name == "bandSelection" ) { std::vector bands; getOutputBandList( bands ); std::vector bandNames; for(ossim_uint32 i = 0; i < bands.size(); i++) { bandNames.push_back( ossimString::toString( bands[i] ) ); } ossimString str; str.join( bandNames, " " ); ossimStringProperty* stringProp = new ossimStringProperty(name, str); stringProp->clearChangeType(); stringProp->setReadOnlyFlag(false); stringProp->setCacheRefreshBit(); return stringProp; } return ossimImageSourceFilter::getProperty(name); } void ossimBandSelector::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("bands"); } ossimRefPtr ossimBandSelector::getBandSelectableImageHandler() const { ossimRefPtr ih = 0; if ( theInputConnection ) { /** * GP: We will only allow the immediate input check for an image handler * and if one is present then check if selectable */ ossimTypeNameVisitor visitor(ossimString("ossimImageHandler"), true, ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS); ossimTypeNameVisitor bandSelectorVisitor(ossimString("ossimBandSelector"), true, ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS); theInputConnection->accept(visitor); theInputConnection->accept(bandSelectorVisitor); // if there is a band selector before us then do not // set the image handler if(bandSelectorVisitor.getObjects().size() < 1) { // If there are multiple image handlers, e.g. a mosaic do not uses. if ( visitor.getObjects().size() == 1 ) { ih = visitor.getObjectAs( 0 ); if ( ih.valid() ) { if ( ih->isBandSelector() == false ) { ih = 0; } } } } } // Matches: if ( theInputConnection ) return ih; } // End: ossimBandSelector::getBandSelectableImageHandler() bool ossimBandSelector::getRgbBandList(std::vector& bandList) const { bool result = false; if ( theInputConnection ) { ossimTypeNameVisitor visitor(ossimString("ossimImageHandler"), true, ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS); theInputConnection->accept(visitor); // If there are multiple image handlers, e.g. a mosaic do not uses. if ( visitor.getObjects().size() == 1 ) { ossimRefPtr ih = visitor.getObjectAs( 0 ); if ( ih.valid() ) { result = ih->getRgbBandList( bandList ); } } } // Matches: if ( theInputConnection ) return result; } // End: ossimBandSelector::getRgbBandList( ... ) ossim-Miami-2.9.1/src/imaging/ossimBandSeparateHandler.cpp000066400000000000000000000257721352751253100235400ustar00rootroot00000000000000//************************************************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: // // Image handler used when the multi-band image has each band represented by a different disk file. // This is the case for some Ikonos imagery. // //************************************************************************************************* // $Id: ossimBandSeparateHandler.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $ #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimBandSeparateHandler, "ossimBandSeparateHandler", ossimImageHandler) using namespace std; //************************************************************************************************* //! Constructor (default): //************************************************************************************************* ossimBandSeparateHandler::ossimBandSeparateHandler() { } //************************************************************************************************* //! Destructor: //************************************************************************************************* ossimBandSeparateHandler::~ossimBandSeparateHandler() { close(); } //************************************************************************************************* // Opens multiple band-files based on info in metadata file. //************************************************************************************************* bool ossimBandSeparateHandler::open() { if (isOpen()) close(); // Fetch the list of band filenames: vector file_names; getBandFileNames(file_names); // There should be a list of filenames populated: if (file_names.size() == 0) return false; m_mergeSource = new ossimBandMergeSource; ossimRefPtr handler = 0; for (ossim_uint32 band=0; bandopen(file_names[band], true, false); if (!handler.valid()) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimBandSeparateHandler::open() -- " "Expected to find band file at <"< but could not open file." " Image not opened."<connectMyInputTo(band, handler.get()); } completeOpen(); return true; } //************************************************************************************************* //! Deletes the overview and clears the valid image vertices. Derived //! classes should implement. //************************************************************************************************* void ossimBandSeparateHandler::close() { vector >::iterator iter = m_bandFiles.begin(); while (iter != m_bandFiles.end()) { (*iter)->close(); *iter = 0; ++iter; } m_bandFiles.clear(); m_mergeSource = 0; } //************************************************************************************************* //! Derived classes must implement this method to be concrete. //! @return true if open, false if not. //************************************************************************************************* bool ossimBandSeparateHandler::isOpen()const { if (m_bandFiles.size() > 0) return true; return false; } //************************************************************************************************* //! Fills the requested tile by pulling pixels from multiple file tiles as needed. //************************************************************************************************* ossimRefPtr ossimBandSeparateHandler::getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel) { // First verify that there are band-files available: if ((m_bandFiles.size() == 0) || !m_mergeSource.valid()) return ossimRefPtr(); // Check if res level represents data in the overview: if (theOverview.valid() && (resLevel > 0)) return theOverview->getTile(tile_rect, resLevel); // Just pass getTile call on to contained bandMergeSource: return m_mergeSource->getTile(tile_rect, resLevel); } //************************************************************************************************* //! @param resLevel Reduced resolution level to return lines of. //! Default = 0 //! @return The number of lines for specified reduced resolution level. //************************************************************************************************* ossim_uint32 ossimBandSeparateHandler::getNumberOfLines(ossim_uint32 resLevel) const { if ((m_bandFiles.size() == 0)) return 0; // Using simple decimation by powers of 2: ossim_uint32 numlines = m_bandFiles[0]->getNumberOfLines() >> resLevel; return numlines; } //************************************************************************************************* //! @param resLevel Reduced resolution level to return samples of. //! Default = 0 //! @return The number of samples for specified reduced resolution level. //************************************************************************************************* ossim_uint32 ossimBandSeparateHandler::getNumberOfSamples(ossim_uint32 resLevel) const { if ((m_bandFiles.size() == 0)) return 0; // Using simple decimation by powers of 2: ossim_uint32 numsamps = m_bandFiles[0]->getNumberOfSamples() >> resLevel; return numsamps; } //************************************************************************************************* //! Method to save the state of an object to a keyword list. //! Return true if ok or false on error. //************************************************************************************************* bool ossimBandSeparateHandler::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimImageHandler::saveState(kwl, prefix); } //************************************************************************************************* //! Method to the load (recreate) the state of an object from a keyword //! list. Return true if ok or false on error. //************************************************************************************************* bool ossimBandSeparateHandler::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (!ossimImageHandler::loadState(kwl, prefix)) return false; return open(); } //************************************************************************************************* // Returns the number of bands of the first tile since all tiles need to have the same pixel type. //************************************************************************************************* ossim_uint32 ossimBandSeparateHandler::getNumberOfInputBands() const { return (ossim_uint32) m_bandFiles.size(); } //************************************************************************************************* //! Returns scalar type of first tile (should be the same for all tiles) //************************************************************************************************* ossimScalarType ossimBandSeparateHandler::getOutputScalarType() const { if ((m_bandFiles.size() == 0) || (!m_bandFiles[0].valid())) return OSSIM_SCALAR_UNKNOWN; return m_bandFiles[0]->getOutputScalarType(); } //************************************************************************************************* //! Overrides base connection method to connect output of merge source. // Returns TRUE if connection possible //************************************************************************************************* bool ossimBandSeparateHandler::canConnectMyOutputTo(ossim_int32 index, const ossimConnectableObject* obj) { if (!m_mergeSource.valid()) return false; return m_mergeSource->canConnectMyOutputTo(index, obj); } //************************************************************************************************* //! Fetches the list of band file names from the header file. The header file name is contained //! in ossimImageHandler::theImageFile. //! NOTE TO PROGRAMMER: This class is presently tailored to the Ikonos metadata file specifying //! the individual band files. If other "metadata" formats are to be supported, then this class //! should be derived from. This method would therefore be pure virtual in this base-class and only //! this method would need to be implemented in the derived classes. //************************************************************************************************* void ossimBandSeparateHandler::getBandFileNames(vector& file_names) { file_names.clear(); // Ikonos expects metadata file with text extension: if (theImageFile.ext() != "txt") return; // Attempt to open the metadata file: ifstream is (theImageFile.chars()); if (is.fail()) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimBandSeparateHandler::open() -- " "Cannot open text file at <"<. Image not opened."< fname_list; const ossimString separator (" "); char line_buf[4096]; while (!is.eof()) { is.getline(line_buf, 4096); ossimString line_str (line_buf); // Look for mention of multiple band files. It must indicate "separate files". This comes // before the list of band files: if (line_str.contains("Multispectral Files:")) { if (!line_str.contains("Separate Files")) return; } // Look for list of band files: if (line_str.contains("Tile File Name:")) { ossimString file_list_str = line_str.after(":"); file_list_str.split(fname_list, separator, true); break; } } is.close(); // Set the path of individual band files to match metadata file path: ossimFilename pathName (theImageFile.path()); for (size_t i=0; i ossimBandSeparateHandler::getImageGeometry() { if ((m_bandFiles.size() == 0) || (!m_bandFiles[0].valid())) return 0; return m_bandFiles[0]->getImageGeometry(); } ossim-Miami-2.9.1/src/imaging/ossimBitMaskTileSource.cpp000066400000000000000000000326051352751253100232330ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: // // Contains class definition for ossimBitMaskTileSource. //******************************************************************* // $Id: ossimBitMaskTileSource.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1_INST(ossimBitMaskTileSource, "ossimBitMaskTileSource", ossimImageHandler); using namespace std; //******************************************************************* // Public Constructor: //******************************************************************* ossimBitMaskTileSource::ossimBitMaskTileSource() : ossimImageHandler(), m_tile(NULL) { } //************************************************************************************************* // Destructor must free the buffers for each res level //************************************************************************************************* ossimBitMaskTileSource::~ossimBitMaskTileSource() { close(); } //************************************************************************************************* // Reset //************************************************************************************************* void ossimBitMaskTileSource::close() { ossimImageHandler::close(); // base class // Wipe the mask buffers: vector::iterator iter = m_buffers.begin(); while (iter != m_buffers.end()) { delete [] (*iter); iter++; } m_buffers.clear(); m_bufferSizes.clear(); m_tile = NULL; } //************************************************************************************************* // Opens an OSSIM Bit Mask raster file. This is a custom formatted file with header info //************************************************************************************************** bool ossimBitMaskTileSource::open() { static const char MODULE[] = "ossimBitMaskTileSource::open()"; if (!isSupportedExtension()) { close(); return false; } close(); // Open the mask file and verify magic number, read header info as well and verify good values: std::ifstream fileStream(theImageFile.chars(), ios::in|ios::binary); if (!fileStream.good()) return false; ossimString magic_number; int num_res_levels = 0; char space; fileStream >> magic_number; if (magic_number == ossimBitMaskWriter::MASK_FILE_MAGIC_NUMBER) { // This is a next-generation mask file with header: fileStream >> theStartingResLevel >> num_res_levels; for (int r=0; r> buffer_size.x >> buffer_size.y; m_bufferSizes.push_back(buffer_size); } fileStream >> space; } else { // This is the old headerless "Ming mask" format. Need to query the source image for image size. // This format implies a starting res level of 1: if (!m_handler.valid()) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " ERROR:\nInput file <"< has no header information and " "no valid source image has been provided. Cannot process mask" << std::endl; fileStream.close(); close(); return false; } theStartingResLevel = 1; num_res_levels = m_handler->getNumberOfDecimationLevels() - 1; fileStream.seekg(0); // Need to compute buffer sizes since they are not available in the mask header: ossimIpt image_size = m_handler->getBoundingRect(1).size(); ossimIpt buffer_size ((image_size.x+7)/8, image_size.y); for (int r=0; r is not recognized or has invalid " "header information." << std::endl; fileStream.close(); close(); return false; } // Good to go, Need to now establish sizes for and offsets to each res level: for (int r=0; r"<create(this, this); m_tile->initialize(); // Computes decimation factors for additional reduced res sets: establishDecimationFactors(); return true; } //************************************************************************************************** // "Open" here means only that the mask buffers are valid and ready for access //************************************************************************************************** bool ossimBitMaskTileSource::isOpen() const { return ((m_buffers.size() != 0) || (m_maskWriter.valid())); } //******************************************************************* // Public method: //******************************************************************* bool ossimBitMaskTileSource::isSupportedExtension() { ossimString ext = theImageFile.ext(); if (ext == "mask") return true; return false; } //************************************************************************************************* // Unpacks the mask data into a destination tile //************************************************************************************************* ossimRefPtr ossimBitMaskTileSource::getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel) { static const ossim_uint8 MASK_BITS[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}; // Allocate the mask tile. This will be 8-bits per pixel (i.e., decompressed): if (!m_tile.valid()) { m_tile = ossimImageDataFactory::instance()->create(this, this); m_tile->initialize(); } // Initial screening: if (!(isOpen() && isSourceEnabled() && isValidRLevel(resLevel))) return NULL; // Check if requested rect falls inside valid mask area: if (!getImageRectangle(resLevel).intersects(tile_rect)) return NULL; // Check if tile size matches requested size: if ((m_tile->getWidth() != tile_rect.width()) || (m_tile->getHeight() != tile_rect.height())) { m_tile->setWidthHeight(tile_rect.width(), tile_rect.height()); m_tile->initialize(); } m_tile->setImageRectangle(tile_rect); // Start with blank tile if rect partially intersects defined mask area: ossimIrect image_rect (getImageRectangle(resLevel)); if (!tile_rect.completely_within(image_rect)) m_tile->makeBlank(); //##### START DEBUG CODE ######################### // This else if identifies unassigned mask pixels being returned by this method incorrectly. // See ossimMaskFilter::executeMaskFilterSelection() (OLK 2/11) //m_tile->fill(128.0);//### //##### END DEBUG CODE ######################### ossimIpt image_size (image_rect.size()); ossim_uint32 num_mask_cols = (image_size.x+7)/8; ossim_uint8* tilebuf = (ossim_uint8*) m_tile->getBuf(0); ossim_uint32 tile_index = 0, mask_index = 0, start_bit=0; ossimIpt ul (tile_rect.ul()); ossimIpt lr (tile_rect.lr()); // Decide if we use our own mask buffer (read from file) or borrow tha active mask writer's // buffer: ossim_uint8* maskbuf; if (m_maskWriter.valid()) maskbuf = m_maskWriter->m_buffers[resLevel-theStartingResLevel]; else maskbuf = m_buffers[resLevel-theStartingResLevel]; // Nested loop to fill tile: for (int y=ul.y; (y<=lr.y)&&(y= image_size.x) || (x>lr.x)) break; } ++mask_index; // advance the mask buffer index 1 after processing 8 tile samples start_bit = 0; } else { // Tile buffer extends beyond valid mask rect, so assume it is masked (0): tilebuf[tile_index++] = 0; ++x; } } } m_tile->validate(); return m_tile; } //******************************************************************* // Argument res_Level is relative to the full image //******************************************************************* bool ossimBitMaskTileSource::isValidRLevel(ossim_uint32 res_Level) const { ossim_uint32 num_rlevels; if (m_maskWriter.valid()) num_rlevels = (ossim_uint32) m_maskWriter->m_buffers.size(); else num_rlevels = (ossim_uint32) m_buffers.size(); return ((res_Level >= theStartingResLevel) && ((res_Level-theStartingResLevel) < num_rlevels)); } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimBitMaskTileSource::getNumberOfLines(ossim_uint32 res_Level) const { if (!isValidRLevel(res_Level)) return 0; if (m_maskWriter.valid()) return m_maskWriter->m_bufferSizes[res_Level-theStartingResLevel].y; return m_bufferSizes[res_Level-theStartingResLevel].y; } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimBitMaskTileSource::getNumberOfSamples(ossim_uint32 res_Level) const { if (!isValidRLevel(res_Level)) return 0; ossim_uint32 n = 0; if (m_maskWriter.valid()) n = m_maskWriter->m_bufferSizes[res_Level-theStartingResLevel].x; else n = m_bufferSizes[res_Level-theStartingResLevel].x; return n*8; // 8 pixels represented in one mask byte entry } ossimRefPtr ossimBitMaskTileSource::getImageGeometry() { return 0; } //******************************************************************* //! Overrides base class implementation. //******************************************************************* ossim_uint32 ossimBitMaskTileSource::getNumberOfDecimationLevels() const { return (ossim_uint32) theDecimationFactors.size(); } //******************************************************************* //! Overrides base class implementation. //******************************************************************* void ossimBitMaskTileSource::establishDecimationFactors() { theDecimationFactors.clear(); ossim_uint32 num_res_levels = (ossim_uint32) m_buffers.size(); ossimDpt decimation(1, 1); for (ossim_uint32 r=0; rm_startingResLevel; } //************************************************************************************************* //! For backward compatibility with older mask format ("Ming Mask"), provide for associating //! the mask with an image handler: //************************************************************************************************* void ossimBitMaskTileSource::setAssociatedImageHandler(ossimImageHandler* handler) { m_handler = handler; } ossim-Miami-2.9.1/src/imaging/ossimBitMaskWriter.cpp000066400000000000000000000424211352751253100224260ustar00rootroot00000000000000//************************************************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: Contains implementation of class for computing a mask from an input image. // The mask is stored in a compressed format where one byte represents 8 bit-masks for masking // 8 image pixels. //************************************************************************************************* // $Id: ossimBitMaskWriter.cpp 3081 2011-12-22 16:34:12Z oscar.kramer $ #include #include #include #include #include #include #include const char *ossimBitMaskWriter::MASK_FILE_MAGIC_NUMBER = "OSSIM_BIT_MASK"; const char *ossimBitMaskWriter::BM_STARTING_RLEVEL_KW = "starting_rlevel"; using namespace std; //************************************************************************************************* // Constructor accepts handler to the source imagery being used to compute the mask. //************************************************************************************************* ossimBitMaskWriter::ossimBitMaskWriter() : m_flipper(0), m_memoryImage(0), m_startingResLevel(0) { } //************************************************************************************************* // Destructor //************************************************************************************************* ossimBitMaskWriter::~ossimBitMaskWriter() { // Make sure the mask file was written out before disappearing: if (isOpen()) close(); } //************************************************************************************************* // Returns true if buffers allocated: //************************************************************************************************* bool ossimBitMaskWriter::isOpen() const { return (m_buffers.size() != 0); } //************************************************************************************************* // Returns true if buffers allocated: //************************************************************************************************* bool ossimBitMaskWriter::open() { // Nothing to do yet. Eventually want to open the output stream here and write the buffer after // each R-level is completed, so we don't need to keep vector of buffers in memory. return true; } //************************************************************************************************* // Reset //************************************************************************************************* void ossimBitMaskWriter::reset() { // Wipe the mask buffers: vector::iterator iter = m_buffers.begin(); while (iter != m_buffers.end()) { delete[](*iter); iter++; } m_buffers.clear(); m_bufferSizes.clear(); } //************************************************************************************************* //! Sets the NULL pixel value to consider when computing mask: //************************************************************************************************* void ossimBitMaskWriter::setBogusPixel(double pixel_value) { if (!m_flipper.valid()) initializeFlipper(); m_flipper->setTargetValue(pixel_value); } //************************************************************************************************* //! Sets the range of pixels (inclusive) to be regarded as NULL pixels when computing mask //************************************************************************************************* void ossimBitMaskWriter::setBogusPixelRange(double min, double max) { if (!m_flipper.valid()) initializeFlipper(); m_flipper->setTargetRange(min, max); } //************************************************************************************************* // Given a source's tile, derives the alpha mask and saves it in buffer for later writing to disk. //************************************************************************************************* void ossimBitMaskWriter::generateMask(ossimRefPtr tile, ossim_uint32 rLevel) { static const ossim_uint8 MASK_BITS_0[] = {0x7F, 0xBF, 0xDF, 0xEF, 0xF7, 0xFB, 0xFD, 0xFE}; static const ossim_uint8 MASK_BITS_1[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}; // We don't start doing anything until starting res or higher requested: ossim_uint32 mask_rlevel = rLevel - m_startingResLevel; if (!tile.valid()) return; // We should have had this done by now, but just in case: if (!m_flipper.valid()) initializeFlipper(); ossimRefPtr flipTile; m_memoryImage->setImage(tile); m_flipper->initialize(); flipTile = m_flipper->getTile(tile->getImageRectangle()); ossimIpt image_size = computeImageSize(rLevel, flipTile.get()); ossim_uint32 num_mask_cols = (image_size.x + 7) / 8; // size of mask buffer after compression ossim_uint32 num_mask_rows = image_size.y; ossim_uint8 *maskbuf = 0; // Check if mask buffer for this R-level has already been allocated: if (m_buffers.size() <= mask_rlevel) { ossim_uint32 size_of_maskbuf = num_mask_rows * num_mask_cols; maskbuf = new ossim_uint8[size_of_maskbuf]; memset(maskbuf, 0, size_of_maskbuf); m_buffers.push_back(maskbuf); m_bufferSizes.push_back(ossimIpt(num_mask_cols, num_mask_rows)); } else maskbuf = m_buffers[mask_rlevel]; ossim_uint32 mask_index = 0, tile_index = 0, start_bit = 0; ossimIrect tile_rect(flipTile->getImageRectangle()); ossimIpt ul(tile_rect.ul()); ossimIpt lr(tile_rect.lr()); // Scan each pixel in the source tile and decide on mask value: for (int y = ul.y; (y <= lr.y) && (y < image_size.y); y++) { mask_index = y * num_mask_cols + ul.x / 8; start_bit = ul.x % 8; // may not start on even mask byte boundary for (int x = ul.x; (x <= lr.x); /* incremented in bit loop below */) { if (x < image_size.x) { // Process 8 samples and pack resultant mask into one byte: maskbuf[mask_index] = 0; for (ossim_uint32 mask_bit = start_bit; mask_bit < 8; ++mask_bit) { // Decide whether to mask depending on pixel flipper outputting a NULL pixel. if (flipTile->isNull(tile_index++)) maskbuf[mask_index] &= MASK_BITS_0[mask_bit]; else maskbuf[mask_index] |= MASK_BITS_1[mask_bit]; // Advance the pixel column and check for end of image rect: ++x; if ((x >= image_size.x) || (x > lr.x)) break; } ++mask_index; // advance the mask buffer index 1 after processing 8 tile samples start_bit = 0; } else { ++x; ++tile_index; } } } // Finished looping over all pixels in input tile return; } //************************************************************************************************* //! Writes the mask file to path specified. Returns TRUE if successful. //************************************************************************************************* void ossimBitMaskWriter::close() { static const char *MODULE = "ossimBitMaskWriter::writeMask()"; static const ossimString MASK_EXTENSION("mask"); // Open the output file. Use default name if none provided. if (theOutputName.empty()) // Couldn't figure out the name { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " -- Error encountered trying to create mask file" " for writing because output file name was never initialized."; return; } ofstream maskFileStream(theOutputName.chars(), ios::out | ios::binary); if (!maskFileStream.is_open()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " -- Error encountered trying to create mask file" "<" << theOutputName << "> for writing. Cannot write mask."; return; } // Write the header info: ossim_uint32 num_rlevels = (ossim_uint32)m_buffers.size(); maskFileStream << MASK_FILE_MAGIC_NUMBER << " " << m_startingResLevel << " " << num_rlevels << " "; for (ossim_uint32 r = 0; r < num_rlevels; r++) maskFileStream << m_bufferSizes[r].x << " " << m_bufferSizes[r].y << " "; maskFileStream << ends; // Loop over each res level and write buffers to disk: for (ossim_uint32 rlevel = 0; rlevel < num_rlevels; ++rlevel) { ossim_uint32 bufsize = m_bufferSizes[rlevel].x * m_bufferSizes[rlevel].y; maskFileStream.write((char *)(m_buffers[rlevel]), bufsize); } maskFileStream.close(); reset(); return; } //************************************************************************************************* //! Constructor accepts keywordlist with all info necessary to compute a mask. The caller will //! still need to call writeMask(). //************************************************************************************************* bool ossimBitMaskWriter::loadState(const ossimKeywordlist &kwl, const char *prefix) { // static const char* MODULE = "ossimBitMaskWriter::writeMask(kwl)"; initializeFlipper(); // Fetch optional output filename: theOutputName = kwl.find(prefix, ossimKeywordNames::OUTPUT_FILE_KW); // Initialize the pixel flipper. This filter is used to identify pixels targeted for masking by // remapping them to the null pixel: m_flipper->loadState(kwl, prefix); // Read Starting res level: m_startingResLevel = 0; ossimString kw_value = kwl.find(prefix, BM_STARTING_RLEVEL_KW); if (!kw_value.empty()) m_startingResLevel = kw_value.toUInt32(); return true; } //************************************************************************************************* // //************************************************************************************************* void ossimBitMaskWriter::initializeFlipper() { if (!m_flipper.valid()) { m_flipper = new ossimPixelFlipper(); m_flipper->setReplacementMode(ossimPixelFlipper::REPLACE_ONLY_FULL_TARGETS); m_flipper->setTargetValue(0); m_flipper->setReplacementValue(0); } if (!m_memoryImage) { m_memoryImage = new ossimMemoryImageSource(); m_flipper->connectMyInputTo(m_memoryImage.get()); } // This method gets called when an input connection is made as well as other times, so keep an // eye out for valid input connection: if (theInputObjectList.size() != 0) { m_flipper->connectMyInputTo(theInputObjectList[0].get()); } } //************************************************************************************************* // //************************************************************************************************* bool ossimBitMaskWriter::canConnectMyInputTo(ossim_int32 /*myInputIndex*/, const ossimConnectableObject *object) const { const ossimImageSource *ois = dynamic_cast(object); return (ois != NULL); } //************************************************************************************************* // //************************************************************************************************* ossim_int32 ossimBitMaskWriter::connectMyInputTo(ossimConnectableObject *inputObject, bool makeOutputConnection, bool createEventFlag) { ossimImageSource *input_source = dynamic_cast(inputObject); if (input_source == NULL) return -1; // Base class takes care of connection with this object: ossimConnectableObject::connectMyInputTo(input_source, makeOutputConnection, createEventFlag); // This input should be an image handler, but may need to search the objects inputs in case // it is chained: ossimImageHandler *handler = dynamic_cast(input_source); if (handler == NULL) { // Need to search: ossimTypeNameVisitor visitor(ossimString("ossimImageHandler"), true, ossimVisitor::VISIT_CHILDREN | ossimVisitor::VISIT_INPUTS); input_source->accept(visitor); ossimRefPtr obj = visitor.getObject(); if (obj.valid()) { handler = dynamic_cast(obj.get()); } } // Should have a handler: if (!handler) { disconnectAllInputs(); return -1; } // A handler has been identified. Need the filename: ossimFilename imageFile = handler->getFilename(); if (imageFile.contains("ovr.tmp")) { // The handler is actually an overview, need some massaging to work since the overview may // not have an R0 entry and R1 rect must be requested instead: m_imageSize = handler->getBoundingRect(1).size() * 2; imageFile = imageFile.noExtension(); } else { // This is normal image handler so it is OK to request R0 rect: m_imageSize = handler->getBoundingRect(0).size(); } if (theOutputName.empty()) theOutputName = imageFile.setExtension("mask"); // Check if the pixel flipper was initialized: if (m_flipper.valid()) m_flipper->connectMyInputTo(input_source); else initializeFlipper(); return 0; } //************************************************************************************************* //! Since overviews may not yet exist when the mask is being written, we must compute the //! size of the mask buffer based on the original R0 image size. //************************************************************************************************* ossimIpt ossimBitMaskWriter::computeImageSize(ossim_uint32 rlevel, ossimImageData *tile) const { if (rlevel == 0) return m_imageSize; ossimIpt isize(m_imageSize); for (ossim_uint32 r = 1; r <= rlevel; r++) { isize.x = (isize.x + 1) / 2; isize.y = (isize.y + 1) / 2; } // Adjust size n X direction to even mask boundary: ossimIpt tile_size(tile->getWidth(), tile->getHeight()); isize.x = ((int)(isize.x + 7) / 8) * 8; return isize; } //************************************************************************************************* // For imagery that already has overviews built, but with artifact edge pixels (such as JP2- // compressed data), it is preferred to build the mask overviews directly from the R0 mask. // This method will build the specified number of R-levels (including R0) from the last defined // mask buffer. Returns TRUE if successful. // disk. //************************************************************************************************* bool ossimBitMaskWriter::buildOverviews(ossim_uint32 total_num_rlevels) { // First establish the remaining number of R-levels to generate, and the last valid R-level // currently in memory: if (m_buffers.size() == 0) return false; if (m_buffers.size() == total_num_rlevels) return true; // nothing to do ossim_uint32 ref_rlevel = m_startingResLevel + (ossim_uint32)m_buffers.size() - 1; ossim_uint32 ovr_rlevel = ref_rlevel + 1; ossimIpt ref_size(m_bufferSizes[ref_rlevel - m_startingResLevel]); ossim_uint8 *ref_buf = m_buffers[ref_rlevel - m_startingResLevel]; ossim_uint32 ref_index = 0, ovr_index = 0; ossim_uint8 *ovr_buf = 0; ossim_uint32 size_of_refbuf = ref_size.x * ref_size.y; // Loop over all remaining res levels: while (ovr_rlevel != total_num_rlevels) { // Allocate the buffer at this R-level: ossimIpt ovr_size((ref_size.x + 1) / 2, (ref_size.y + 1) / 2); ossim_uint32 size_of_ovrbuf = ovr_size.x * ovr_size.y; if (size_of_ovrbuf == 0) return false; ovr_buf = new ossim_uint8[size_of_ovrbuf]; memset(ovr_buf, 0, size_of_ovrbuf); m_buffers.push_back(ovr_buf); m_bufferSizes.push_back(ovr_size); // Loop over each output overview pixel, considering the underlying rlevel (equivalent to // nearest-neighbor resampling for overview at 2X decimation): for (int y = 0; y < ovr_size.y; y++) { ref_index = 2 * y * ref_size.x; ovr_index = y * ovr_size.x; for (int x = 0; x < ovr_size.x; x++) { ossim_uint8 a = 0; ossim_uint8 b = 0; if (ref_index < size_of_refbuf) { a = ref_buf[ref_index++]; if ((x < (ovr_size.x - 1)) || !(ref_size.x & 1)) b = ref_buf[ref_index++]; } ovr_buf[ovr_index++] = ((a & 0x80) | ((a & 0x20) << 1) | ((a & 0x08) << 2) | ((a & 0x02) << 3) | ((b & 0x80) >> 4) | ((b & 0x20) >> 3) | ((b & 0x08) >> 2) | ((b & 0x02) >> 1)); } } // Advance to next rlevel: ref_buf = ovr_buf; ref_size = ovr_size; size_of_refbuf = size_of_ovrbuf; ++ovr_rlevel; } return true; } ossim-Miami-2.9.1/src/imaging/ossimBlendMosaic.cpp000066400000000000000000000422631352751253100220630ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBlendMosaic.cpp 20696 2012-03-19 12:36:40Z dburken $ #include #include #include #include RTTI_DEF1(ossimBlendMosaic, "ossimBlendMosaic", ossimImageMosaic) using namespace std; ossimBlendMosaic::ossimBlendMosaic() : ossimImageMosaic(), theNormResult(NULL) { } ossimBlendMosaic::ossimBlendMosaic(ossimConnectableObject::ConnectableObjectList& inputSources) : ossimImageMosaic(inputSources), theNormResult(NULL) { initialize(); } ossimBlendMosaic::~ossimBlendMosaic() { } void ossimBlendMosaic::initialize() { ossimImageMosaic::initialize(); allocate(); // only allocate this space if we have to if(hasDifferentInputs()) { theNormResult = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT, theLargestNumberOfInputBands); theNormResult->initialize(); } if(theWeights.size() < theInputObjectList.size()) { for(ossim_uint32 index =(ossim_uint32)theWeights.size(); index < theInputObjectList.size(); ++index) { theWeights.push_back(1.0); } } } ossimRefPtr ossimBlendMosaic::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { // ossimIpt origin = tileRect.ul(); if(!isSourceEnabled()) { return ossimImageMosaic::getTile(tileRect, resLevel); } ossim_uint32 size = getNumberOfInputs(); if(!theTile.get()) { // try to initialize initialize(); // if we still don't have a buffer // then we will leave if(!theTile.get()) { return theTile; } } if(size == 0) { return ossimRefPtr(); } if(size == 1) { return ossimImageMosaic::getTile(tileRect, resLevel); } theTile->setImageRectangle(tileRect); theTile->makeBlank(); if(theNormResult.valid()) { theNormResult->setImageRectangle(tileRect); theNormResult->makeBlank(); } switch(theTile->getScalarType()) { case OSSIM_UINT8: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SINT8: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SINT16: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SINT32: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_UINT32: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimBlendMosaic::getTile NOTICE:\n" << "Scalar type = " << theTile->getScalarType() << " Not supported by ossimImageMosaic" << endl; } } return ossimRefPtr(); } template ossimRefPtr ossimBlendMosaic::combine( T, const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr currentImageData=NULL; ossim_uint32 band; double currentWeight = 1.0; double previousWeight = 1.0; // double sumOfWeights = 1; long offset = 0; long row = 0; long col = 0; ossim_uint32 layerIdx = 0; currentImageData = getNextTile(layerIdx, 0, tileRect, resLevel); if(!currentImageData.get()) // if we don't have one then return theTile { return theTile; } T** srcBands = new T*[theLargestNumberOfInputBands]; T** destBands = new T*[theLargestNumberOfInputBands]; T* nullPix = new T[theTile->getNumberOfBands()]; previousWeight = theWeights[layerIdx]; // // now get the previous weight and then combine the two into one. // let's assign the bands for(band = 0; band < theLargestNumberOfInputBands; ++band) { destBands[band] = static_cast(theTile->getBuf(band)); nullPix[band] = static_cast(theTile->getNullPix(band)); } while(currentImageData.get()) { ossimDataObjectStatus currentStatus = currentImageData->getDataObjectStatus(); // set the current weight for the current tile. currentWeight = theWeights[layerIdx]; // sumOfWeights = previousWeight+currentWeight; if( (currentStatus != OSSIM_EMPTY) && (currentStatus != OSSIM_NULL)) { long h = (long)currentImageData->getHeight(); long w = (long)currentImageData->getWidth(); offset = 0; ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); // let's assign the bands for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); } for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; } if(currentStatus == OSSIM_PARTIAL) { for(row = 0; row < h; ++row) { for(col = 0; col < w; ++col) { if(!currentImageData->isNull(offset)) { for(band = 0; band < theLargestNumberOfInputBands; ++band) { if(destBands[band][offset] != nullPix[band]) { // destBands[band][offset] = static_cast((destBands[band][offset]*(1.0-currentWeight) + // srcBands[band][offset]*currentWeight)); destBands[band][offset] = static_cast((destBands[band][offset]*previousWeight + srcBands[band][offset]*currentWeight)/(previousWeight+currentWeight)); } else { destBands[band][offset] = srcBands[band][offset]; } } } ++offset; } } } else { for(row = 0; row < h; ++row) { for(col = 0; col < w; ++col) { for(band = 0; band < theLargestNumberOfInputBands; ++band) { if(destBands[band][offset] != nullPix[band]) { destBands[band][offset] = static_cast((destBands[band][offset]*previousWeight+ srcBands[band][offset]*currentWeight)/(previousWeight + currentWeight)); } else { destBands[band][offset] = srcBands[band][offset]; } } ++offset; } } } } currentImageData = getNextTile(layerIdx, tileRect, resLevel); previousWeight = (previousWeight+currentWeight)/2.0; } delete [] srcBands; delete [] destBands; delete [] nullPix; theTile->validate(); return theTile; } template ossimRefPtr ossimBlendMosaic::combineNorm( T, const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr currentImageData=NULL; ossim_uint32 band; double currentWeight = 1.0; double previousWeight = 1.0; // double sumOfWeights = 1; long offset = 0; long row = 0; long col = 0; ossim_uint32 layerIdx = 0; currentImageData = getNextNormTile(layerIdx, 0, tileRect, resLevel); if(!currentImageData.get()) // if we don't have one then return theTile { return theTile; } theNormResult->makeBlank(); float** srcBands = new float*[theLargestNumberOfInputBands]; float** destBands = new float*[theLargestNumberOfInputBands]; float* nullPix = new float[theTile->getNumberOfBands()]; previousWeight = theWeights[layerIdx]; // // now get the previous weight and then combine the two into one. // let's assign the bands for(band = 0; band < theLargestNumberOfInputBands; ++band) { destBands[band] = static_cast(theNormResult->getBuf(band)); nullPix[band] = static_cast(theNormResult->getNullPix(band)); } while(currentImageData.get()) { ossimDataObjectStatus currentStatus = currentImageData->getDataObjectStatus(); // set the current weight for the current tile. currentWeight = theWeights[layerIdx]; // sumOfWeights = previousWeight+currentWeight; if( (currentStatus != OSSIM_EMPTY) && (currentStatus != OSSIM_NULL)) { long h = (long)currentImageData->getHeight(); long w = (long)currentImageData->getWidth(); offset = 0; ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); // let's assign the bands for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); } for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; } if(currentStatus == OSSIM_PARTIAL) { for(row = 0; row < h; ++row) { for(col = 0; col < w; ++col) { if(!currentImageData->isNull(offset)) { for(band = 0; band < theLargestNumberOfInputBands; ++band) { if(destBands[band][offset] != nullPix[band]) { destBands[band][offset] = static_cast((destBands[band][offset]*previousWeight + srcBands[band][offset]*currentWeight)/(previousWeight+currentWeight)); } else { destBands[band][offset] = srcBands[band][offset]; } } } ++offset; } } } else { for(row = 0; row < h; ++row) { for(col = 0; col < w; ++col) { for(band = 0; band < theLargestNumberOfInputBands; ++band) { if(destBands[band][offset] != nullPix[band]) { destBands[band][offset] = static_cast((destBands[band][offset]*previousWeight+ srcBands[band][offset]*currentWeight)/(previousWeight + currentWeight)); } else { destBands[band][offset] = srcBands[band][offset]; } } ++offset; } } } } currentImageData = getNextNormTile(layerIdx, tileRect, resLevel); previousWeight = (previousWeight+currentWeight)/2.0; } theNormResult->validate(); theTile->copyNormalizedBufferToTile((float*)theNormResult->getBuf()); delete [] srcBands; delete [] destBands; delete [] nullPix; theTile->validate(); return theTile; } bool ossimBlendMosaic::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimImageMosaic::saveState(kwl, prefix); ossimString copyPrefix = prefix; for(ossim_uint32 index = 0; index < theWeights.size(); ++index) { ossimString weightStr = ossimString("weight") + ossimString::toString(index); kwl.add(copyPrefix.c_str(), weightStr.c_str(), theWeights[index], true); } return result; } bool ossimBlendMosaic::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimImageMosaic::loadState(kwl, prefix); ossim_uint32 count = 0; theWeights.clear(); if(result) { ossimString copyPrefix = prefix; ossimString regExpression = ossimString("^(") + copyPrefix + "weight[0-9]+)"; ossim_uint32 result = kwl.getNumberOfSubstringKeys(regExpression); ossim_uint32 numberOfMatches = 0; while(numberOfMatches < result) { ossimString value = ossimString("weight") + ossimString::toString(count); const char* lookup = kwl.find(copyPrefix.c_str(), value.c_str()); if(lookup) { ++numberOfMatches; theWeights.push_back(ossimString(lookup).toDouble()); } ++count; } } return result; } void ossimBlendMosaic::setNumberOfWeights(ossim_uint32 numberOfWeights) { if(numberOfWeights > theWeights.size()) { ossim_uint32 length = numberOfWeights - (ossim_uint32) theWeights.size(); for(ossim_uint32 index= 0; index < length; ++ index) { theWeights.push_back(1.0); } } else if(numberOfWeights < theWeights.size()) { // copy the list vector temp(theWeights.begin(), theWeights.begin()+numberOfWeights); // now shrink theWeights = temp; } } void ossimBlendMosaic::setAllWeightsTo(double value) { for(ossim_uint32 index = 0; index < theWeights.size(); ++index) { theWeights[index] = value; } } void ossimBlendMosaic::normalizeWeights() { double sumWeights=0.0; ossim_uint32 index = 0; for(index = 0; index < theWeights.size(); ++index) { sumWeights+=theWeights[index]; } if(sumWeights > 0.0) { for(index = 0; index < theWeights.size(); ++index) { theWeights[index] /= sumWeights; } } } void ossimBlendMosaic::findMinMax(double& minValue, double& maxValue)const { if(theWeights.size() > 0) { minValue = maxValue = theWeights[0]; for(ossim_uint32 index = 1; index < theWeights.size(); ++index) { minValue = minValue < theWeights[index]?minValue:theWeights[index]; maxValue = maxValue > theWeights[index]?maxValue:theWeights[index]; } } } void ossimBlendMosaic::setWeight(ossim_uint32 index, double weight) { if(index < theWeights.size()) { theWeights[index] = weight; } } void ossimBlendMosaic::setWeights(const std::vector& weights) { theWeights = weights; } const vector& ossimBlendMosaic::getWeights()const { return theWeights; } double ossimBlendMosaic::getWeight(ossim_uint32 index) const { if(index < theWeights.size()) { return theWeights[index]; } if(theWeights.size()) { return theWeights[theWeights.size()-1]; } return 0; } ossim-Miami-2.9.1/src/imaging/ossimBrightnessContrastSource.cpp000066400000000000000000000213261352751253100247070ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // // Description: A brief description of the contents of the file. // //************************************************************************* // $Id: ossimBrightnessContrastSource.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimBrightnessContrastSource, "ossimBrightnessContrastSource", ossimImageSourceFilter) ossimBrightnessContrastSource::ossimBrightnessContrastSource() :ossimImageSourceFilter(), theBrightness(0.0), theContrast(1.0) { } ossimBrightnessContrastSource::~ossimBrightnessContrastSource() { } ossimRefPtr ossimBrightnessContrastSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr tile = NULL; if(theInputConnection) { tile = theInputConnection->getTile(tileRect, resLevel); if(!tile.valid()) { return tile; } if(!isSourceEnabled() || (tile->getDataObjectStatus()==OSSIM_NULL)|| (tile->getDataObjectStatus()==OSSIM_EMPTY)|| ( (theBrightness == 0.0) && (theContrast == 1.0) ) ) { return tile; } if(!theTile.valid() || !theNormTile.valid()) { allocate(); } if(!theTile.valid() || !theNormTile.valid()) { return tile; } theTile->setImageRectangle(tileRect); theNormTile->setImageRectangle(tileRect); tile->copyTileToNormalizedBuffer((ossim_float32*)theNormTile->getBuf()); theNormTile->setDataObjectStatus(tile->getDataObjectStatus()); if (theNormTile->getNumberOfBands() == 3) { processRgbTile(); } else { processNBandTile(); } theTile->copyNormalizedBufferToTile((ossim_float32*) theNormTile->getBuf()); theTile->validate(); return theTile; } return tile; } void ossimBrightnessContrastSource::processRgbTile() { ossim_float32* bands[3]; bands[0] = (ossim_float32*)theNormTile->getBuf(0); bands[1] = (ossim_float32*)theNormTile->getBuf(1); bands[2] = (ossim_float32*)theNormTile->getBuf(2); ossim_uint32 offset = 0; ossim_uint32 maxIdx = theNormTile->getWidth()*theNormTile->getHeight(); ossimHsiVector hsi; ossim_float32 i; if(theNormTile->getDataObjectStatus() == OSSIM_FULL) { for(offset = 0; offset < maxIdx; ++offset) { ossimNormRgbVector rgb(bands[0][offset], bands[1][offset], bands[2][offset]); hsi = rgb; i = (hsi.getI()*theContrast + theBrightness); if(i < OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT) i = OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT; if(i > 1.0) i = 1.0; hsi.setI(i); rgb = hsi; bands[0][offset] = rgb.getR(); bands[1][offset] = rgb.getG(); bands[2][offset] = rgb.getB(); } } else { for(offset = 0; offset < maxIdx; ++offset) { if((bands[0][offset] != 0.0)&& (bands[1][offset] != 0.0)&& (bands[2][offset] != 0.0)) { ossimNormRgbVector rgb(bands[0][offset], bands[1][offset], bands[2][offset]); hsi = rgb; i = (hsi.getI()*theContrast + theBrightness); if(i < OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT) i = OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT; if(i > 1.0) i = 1.0; hsi.setI(i); rgb = hsi; bands[0][offset] = rgb.getR(); bands[1][offset] = rgb.getG(); bands[2][offset] = rgb.getB(); } } } } void ossimBrightnessContrastSource::processNBandTile() { const ossim_uint32 BANDS = theNormTile->getNumberOfBands(); const ossim_uint32 PPB = theNormTile->getSizePerBand(); const ossim_float32 MP = theNormTile->getMinNormalizedPix(); for (ossim_uint32 band = 0; band < BANDS; ++band) { ossim_float32* buf = theNormTile->getFloatBuf(band); for (ossim_uint32 i = 0; i < PPB; ++i) { if (buf[i] != 0.0) { ossim_float32 p = buf[i] * theContrast + theBrightness; buf[i] = (p < 1.0) ? ( (p > MP) ? p : 0.0 ) : 1.0; } } } } void ossimBrightnessContrastSource::initialize() { ossimImageSourceFilter::initialize(); theTile = 0; theNormTile = 0; } void ossimBrightnessContrastSource::allocate() { if( isSourceEnabled() && theInputConnection ) { theTile = ossimImageDataFactory::instance()->create(this, this); if(theTile.valid()) { theNormTile = ossimImageDataFactory::instance()->create(this, OSSIM_FLOAT32, theTile->getNumberOfBands()); } if(theTile.valid() && theNormTile.valid()) { theTile->initialize(); theNormTile->initialize(); } else { theTile = 0; theNormTile = 0; } } } void ossimBrightnessContrastSource::setProperty(ossimRefPtr property) { if(!property) { return; } ossimString name = property->getName(); if(name == "brightness") { theBrightness = property->valueToString().toDouble(); } else if(name == "contrast") { theContrast = property->valueToString().toDouble(); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimBrightnessContrastSource::getProperty(const ossimString& name)const { if(name == "brightness") { ossimNumericProperty* numeric = new ossimNumericProperty(name, ossimString::toString(getBrightness()), -1.0, 1.0); numeric->setNumericType(ossimNumericProperty::ossimNumericPropertyType_FLOAT64); numeric->setCacheRefreshBit(); return numeric; } else if(name == "contrast") { ossimNumericProperty* numeric = new ossimNumericProperty(name, ossimString::toString(getContrast()), 0.0, 20.0); numeric->setNumericType(ossimNumericProperty::ossimNumericPropertyType_FLOAT64); numeric->setCacheRefreshBit(); return numeric; } return ossimImageSourceFilter::getProperty(name); } void ossimBrightnessContrastSource::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("brightness"); propertyNames.push_back("contrast"); } bool ossimBrightnessContrastSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* brightness = kwl.find(prefix, "brightness"); const char* contrast = kwl.find(prefix, "contrast"); if(brightness) { theBrightness = ossimString(brightness).toDouble(); } if(contrast) { theContrast = ossimString(contrast).toDouble(); } return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimBrightnessContrastSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "brightness", theBrightness, true); kwl.add(prefix, "contrast", theContrast, true); return ossimImageSourceFilter::saveState(kwl, prefix); } void ossimBrightnessContrastSource::setBrightnessContrast( ossim_float64 brightness, ossim_float64 contrast) { theBrightness = brightness; theContrast = contrast; } void ossimBrightnessContrastSource::setBrightness(ossim_float64 brightness) { setBrightnessContrast(brightness, getContrast()); } void ossimBrightnessContrastSource::setContrast(ossim_float64 contrast) { setBrightnessContrast(getBrightness(), contrast); } ossim_float64 ossimBrightnessContrastSource::getBrightness()const { return theBrightness; } ossim_float64 ossimBrightnessContrastSource::getContrast()const { return theContrast; } ossim-Miami-2.9.1/src/imaging/ossimBrightnessMatch.cpp000066400000000000000000000171341352751253100227670ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: A brief description of the contents of the file. // //************************************************************************* // $Id: ossimBrightnessMatch.cpp 11955 2007-10-31 16:10:22Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimBrightnessMatch, "ossimBrightnessMatch", ossimImageSourceFilter) ossimBrightnessMatch::ossimBrightnessMatch() :ossimImageSourceFilter(), theTargetBrightness(0.5), theInputBrightness(0.5) { theInputBrightness = ossim::nan(); theBrightnessContrastSource = new ossimBrightnessContrastSource; } ossimBrightnessMatch::~ossimBrightnessMatch() { } ossimRefPtr ossimBrightnessMatch::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!isSourceEnabled()) { return ossimImageSourceFilter::getTile(tileRect, resLevel); } if(theInputConnection) { if(ossim::isnan(theInputBrightness)) { computeInputBrightness(); } return theBrightnessContrastSource->getTile(tileRect, resLevel); } return 0; } void ossimBrightnessMatch::initialize() { theBrightnessContrastSource->connectMyInputTo(0, getInput()); theNormTile = 0; } void ossimBrightnessMatch::setProperty(ossimRefPtr property) { if(!property) { return; } ossimString name = property->getName(); if(name == "input_brightness") { theInputBrightness = property->valueToString().toDouble(); theBrightnessContrastSource->setBrightness(theTargetBrightness-theInputBrightness); } else if(name == "target_brightness") { theTargetBrightness = property->valueToString().toDouble(); theBrightnessContrastSource->setBrightness(theTargetBrightness-theInputBrightness); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimBrightnessMatch::getProperty(const ossimString& name)const { if(name == "target_brightness") { ossimNumericProperty* numeric = new ossimNumericProperty(name, ossimString::toString(theTargetBrightness), 0.0, 1.0); numeric->setNumericType(ossimNumericProperty::ossimNumericPropertyType_FLOAT64); numeric->setCacheRefreshBit(); return numeric; } else if(name == "input_brightness") { ossimNumericProperty* numeric = new ossimNumericProperty(name, ossimString::toString(theInputBrightness), 0.0, 1.0); numeric->setNumericType(ossimNumericProperty::ossimNumericPropertyType_FLOAT64); numeric->setCacheRefreshBit(); return numeric; } return ossimImageSourceFilter::getProperty(name); } void ossimBrightnessMatch::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("input_brightness"); propertyNames.push_back("target_brightness"); } bool ossimBrightnessMatch::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* input_brightness = kwl.find(prefix, "input_brightness"); const char* target_brightness = kwl.find(prefix, "target_brightness"); if(input_brightness) { theInputBrightness = ossimString(input_brightness).toDouble(); } if(target_brightness) { theTargetBrightness = ossimString(target_brightness).toDouble(); } return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimBrightnessMatch::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "input_brightness", theInputBrightness, true); kwl.add(prefix, "target_brightness", theTargetBrightness, true); return ossimImageSourceFilter::saveState(kwl, prefix); } void ossimBrightnessMatch::computeInputBrightness() { if(theInputConnection) { ossimIrect inputRect = getBoundingRect(); ossim_uint32 rlevel = 0; ossim_uint32 nlevels = getNumberOfDecimationLevels(); if(nlevels>1) { while((ossim::max(inputRect.width(), inputRect.height()) > 2048)&& (rlevel < nlevels)) { ++rlevel; inputRect = getBoundingRect(rlevel); } } ossimIpt centerPt = inputRect.midPoint(); centerPt.x -= 1024; centerPt.y -= 1024; ossimIrect reqRect(centerPt.x, centerPt.y, centerPt.x + 2047, centerPt.x + 2047); reqRect = reqRect.clipToRect(inputRect); ossimRefPtr inputTile = theInputConnection->getTile(reqRect, rlevel); if(inputTile.valid()) { theNormTile = new ossimImageData(0, OSSIM_FLOAT32, inputTile->getNumberOfBands()); theNormTile->initialize(); theNormTile->setImageRectangle(reqRect); inputTile->copyTileToNormalizedBuffer((ossim_float32*)theNormTile->getBuf()); theNormTile->setDataObjectStatus(inputTile->getDataObjectStatus()); ossim_uint32 maxIdx = theNormTile->getWidth()*theNormTile->getHeight(); ossim_float32* bands[3]; double averageI = 0.0; double count = 0.0; ossim_uint32 offset = 0; bands[0] = (ossim_float32*)theNormTile->getBuf(); if(theNormTile->getNumberOfBands()>2) { bands[1] = (ossim_float32*)theNormTile->getBuf(1); bands[2] = (ossim_float32*)theNormTile->getBuf(2); } else { bands[1] = bands[0]; bands[2] = bands[0]; } ossimHsiVector hsi; if(theNormTile->getDataObjectStatus() == OSSIM_FULL) { count = maxIdx; for(offset = 0; offset < maxIdx; ++offset) { hsi = ossimNormRgbVector(bands[0][offset], bands[1][offset], bands[2][offset]); averageI += hsi.getI(); } } else { for(offset = 0; offset < maxIdx; ++offset) { if((bands[0][offset] != 0.0)&& (bands[1][offset] != 0.0)&& (bands[2][offset] != 0.0)) { hsi = ossimNormRgbVector(bands[0][offset], bands[1][offset], bands[2][offset]); averageI += hsi.getI(); ++count; } } } theInputBrightness = averageI / count; theBrightnessContrastSource->setBrightness(theTargetBrightness-theInputBrightness); } else { theInputBrightness = .5; } } theNormTile = 0; } ossim-Miami-2.9.1/src/imaging/ossimBumpShadeTileSource.cpp000066400000000000000000000372421352751253100235530ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimBumpShadeTileSource.cpp 23165 2015-02-24 18:01:52Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include static const char COLOR_RED_KW[] = "color_red"; static const char COLOR_GREEN_KW[] = "color_green"; static const char COLOR_BLUE_KW[] = "color_blue"; using namespace std; RTTI_DEF1(ossimBumpShadeTileSource, "ossimBumpShadeTileSource", ossimImageCombiner); ossimBumpShadeTileSource::ossimBumpShadeTileSource() :ossimImageCombiner(0, 2, 0, true, false), m_tile(0), m_lightSourceElevationAngle(45.0), m_lightSourceAzimuthAngle(45.0), m_lightDirection(3), m_r(255), m_g(255), m_b(255) { initialize(); } ossimBumpShadeTileSource::~ossimBumpShadeTileSource() { } ossimRefPtr ossimBumpShadeTileSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if (!getInput(0)) return 0; if(!m_tile.get()) { allocate(); } if(!m_tile.valid()) { return m_tile; } m_tile->setImageRectangle(tileRect); m_tile->initialize(); getTile(m_tile.get(), resLevel); return m_tile; } bool ossimBumpShadeTileSource::getTile(ossimImageData* tile, ossim_uint32 resLevel) { if (!getInput(0) || !tile) return false; if(!isSourceEnabled()) return true; tile->makeBlank(); ossimIrect tileRect = tile->getImageRectangle(); ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(1)); ossimRefPtr colorData = 0; if(colorSource) { colorData = new ossimImageData(colorSource, colorSource->getOutputScalarType(), colorSource->getNumberOfOutputBands(), tile->getWidth(), tile->getHeight()); // Caution: Must set rect prior to getTile: colorData->setImageRectangle(tileRect); colorSource->getTile(colorData.get(), resLevel); } ossimImageSource* normalSource = PTR_CAST(ossimImageSource, getInput(0)); ossimRefPtr normalData = new ossimImageData(normalSource, normalSource->getOutputScalarType(), normalSource->getNumberOfOutputBands(), tile->getWidth(), tile->getHeight()); // Caution: Must set rect prior to getTile: normalData->setImageRectangle(tileRect); normalSource->getTile(normalData.get(), resLevel); ossimDataObjectStatus status = normalData->getDataObjectStatus(); if ((status == OSSIM_NULL) || (status == OSSIM_EMPTY) || (normalData->getNumberOfBands() != 3) || (normalData->getScalarType() != OSSIM_DOUBLE)) { return false; } ossim_float64* normalBuf[3]; normalBuf[0] = static_cast(normalData->getBuf(0)); normalBuf[1] = static_cast(normalData->getBuf(1)); normalBuf[2] = static_cast(normalData->getBuf(2)); ossim_float64 normalNp = normalData->getNullPix(0); //--- // If we have some color data then use it for the bump // else we will default to a grey scale bump shade. //--- if ( colorData.get() && (colorData->getDataObjectStatus() != OSSIM_EMPTY) && (colorData->getDataObjectStatus() != OSSIM_NULL) ) { switch(colorData->getScalarType()) { case OSSIM_UCHAR: { ossim_uint8* resultBuf[3]; ossim_uint8* colorBuf[3]; resultBuf[0] = static_cast(tile->getBuf(0)); resultBuf[1] = static_cast(tile->getBuf(1)); resultBuf[2] = static_cast(tile->getBuf(2)); colorBuf[0] = static_cast(colorData->getBuf(0)); if(colorData->getBuf(1)) { colorBuf[1] = static_cast(colorData->getBuf(1)); } else { colorBuf[1] = colorBuf[0]; } if(colorData->getBuf(2)) { colorBuf[2] = static_cast(colorData->getBuf(2)); } else { colorBuf[2] = colorBuf[0]; } long h = m_tile->getHeight(); long w = m_tile->getWidth(); for(long y = 0; y < h; ++y) { for(long x = 0; x < w; ++x) { if((*normalBuf[0] != normalNp) && (*normalBuf[1] != normalNp) && (*normalBuf[2] != normalNp) ) { if((*colorBuf[0])||(*colorBuf[1])||(*colorBuf[2])) { computeColor(*resultBuf[0], *resultBuf[1], *resultBuf[2], *normalBuf[0], *normalBuf[1], *normalBuf[2], *colorBuf[0], *colorBuf[1], *colorBuf[2]); } else { computeColor(*resultBuf[0], *resultBuf[1], *resultBuf[2], *normalBuf[0], *normalBuf[1], *normalBuf[2], m_r, m_g, m_b); } } else { *resultBuf[0] = *colorBuf[0]; *resultBuf[1] = *colorBuf[1]; *resultBuf[2] = *colorBuf[2]; } resultBuf[0]++; resultBuf[1]++; resultBuf[2]++; colorBuf[0]++; colorBuf[1]++; colorBuf[2]++; normalBuf[0]++; normalBuf[1]++; normalBuf[2]++; } } break; } default: { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimBumpShadeTileSource::getTile NOTICE:\n" << "only 8-bit unsigned char is supported." << endl; } } } else { ossim_uint8* resultBuf[3]; resultBuf[0] = static_cast(tile->getBuf(0)); resultBuf[1] = static_cast(tile->getBuf(1)); resultBuf[2] = static_cast(tile->getBuf(2)); long h = tile->getHeight(); long w = tile->getWidth(); for(long y = 0; y < h; ++y) { for(long x = 0; x < w; ++x) { if((*normalBuf[0] != normalNp) && (*normalBuf[1] != normalNp) && (*normalBuf[2] != normalNp) ) { computeColor(*resultBuf[0], *resultBuf[1], *resultBuf[2], *normalBuf[0], *normalBuf[1], *normalBuf[2], m_r, m_g, m_b); } else { *resultBuf[0] = 0; *resultBuf[1] = 0; *resultBuf[2] = 0; } resultBuf[0]++; resultBuf[1]++; resultBuf[2]++; normalBuf[0]++; normalBuf[1]++; normalBuf[2]++; } } } tile->validate(); return true; } void ossimBumpShadeTileSource::computeColor(ossim_uint8& r, ossim_uint8& g, ossim_uint8& b, ossim_float64 normalX, ossim_float64 normalY, ossim_float64 normalZ, ossim_uint8 dr, ossim_uint8 dg, ossim_uint8 db)const { double c = /*fabs*/(normalX*m_lightDirection[0] + normalY*m_lightDirection[1] + normalZ*m_lightDirection[2]); r = ossimRgbVector::clamp(ossim::round(c*dr), 1, 255); g = ossimRgbVector::clamp(ossim::round(c*dg), 1, 255); b = ossimRgbVector::clamp(ossim::round(c*db), 1, 255); } void ossimBumpShadeTileSource::initialize() { ossimImageCombiner::initialize(); ossimImageSource* normalSource = dynamic_cast( getInput(0) ); if ( normalSource ) { normalSource->initialize(); } ossimImageSource* colorSource = dynamic_cast( getInput(1) ); if ( colorSource ) { colorSource->initialize(); } m_tile = 0; computeLightDirection(); } void ossimBumpShadeTileSource::allocate() { m_tile = ossimImageDataFactory::instance()->create(this, this); m_tile->initialize(); } void ossimBumpShadeTileSource::computeLightDirection() { NEWMAT::Matrix m = ossimMatrix3x3::createRotationMatrix(m_lightSourceElevationAngle, 0.0, -m_lightSourceAzimuthAngle); // make positive rotation clockwise for azimuth NEWMAT::ColumnVector v(3); v[0] = 0; v[1] = 1; v[2] = 0; v = m*v; // reflect Z. We need the Z pointing up from the surface and not into it. // ossimColumnVector3d d(v[0], v[1], -v[2]); d = d.unit(); m_lightDirection[0] = d[0]; m_lightDirection[1] = d[1]; m_lightDirection[2] = d[2]; } bool ossimBumpShadeTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* elevationAngle = kwl.find(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW); const char* azimuthAngle = kwl.find(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW); if(elevationAngle) { m_lightSourceElevationAngle = ossimString(elevationAngle).toDouble(); } if(azimuthAngle) { m_lightSourceAzimuthAngle = ossimString(azimuthAngle).toDouble(); } const char* lookup = kwl.find(prefix, COLOR_RED_KW); if (lookup) { m_r = ossimString(lookup).toUInt8(); } lookup = kwl.find(prefix, COLOR_GREEN_KW); if (lookup) { m_g = ossimString(lookup).toUInt8(); } lookup = kwl.find(prefix, COLOR_BLUE_KW); if (lookup) { m_b = ossimString(lookup).toUInt8(); } computeLightDirection(); bool result = ossimImageSource::loadState(kwl, prefix); theInputListIsFixedFlag = true; theOutputListIsFixedFlag = false; if(!getNumberOfInputs()) setNumberOfInputs(2); return result; } bool ossimBumpShadeTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW, m_lightSourceElevationAngle, true); kwl.add(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW, m_lightSourceAzimuthAngle, true); kwl.add(prefix, COLOR_RED_KW, m_r, true); kwl.add(prefix, COLOR_GREEN_KW, m_g, true); kwl.add(prefix, COLOR_BLUE_KW, m_b, true); return ossimImageSource::saveState(kwl, prefix); } ossimString ossimBumpShadeTileSource::getShortName()const { return ossimString("bump shader"); } ossimString ossimBumpShadeTileSource::getLongName()const { return ossimString("Blinn's bump map filter"); } ossim_uint32 ossimBumpShadeTileSource::getNumberOfOutputBands() const { return 3; } ossimScalarType ossimBumpShadeTileSource::getOutputScalarType() const { return OSSIM_UCHAR; } double ossimBumpShadeTileSource::getNullPixelValue()const { return 0.0; } double ossimBumpShadeTileSource::getMinPixelValue(ossim_uint32 /* band */)const { return 1.0; } double ossimBumpShadeTileSource::getMaxPixelValue(ossim_uint32 /* band */)const { return 255.0; } double ossimBumpShadeTileSource::getAzimuthAngle()const { return m_lightSourceAzimuthAngle; } double ossimBumpShadeTileSource::getElevationAngle()const { return m_lightSourceElevationAngle; } void ossimBumpShadeTileSource::setAzimuthAngle(double angle) { m_lightSourceAzimuthAngle = angle; } void ossimBumpShadeTileSource::setElevationAngle(double angle) { m_lightSourceElevationAngle = angle; } bool ossimBumpShadeTileSource::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const { return (object&& ( (inputIndex>=0) && inputIndex < 2)&& PTR_CAST(ossimImageSource, object)); } void ossimBumpShadeTileSource::connectInputEvent(ossimConnectionEvent& /* event */) { initialize(); } void ossimBumpShadeTileSource::disconnectInputEvent(ossimConnectionEvent& /* event */) { initialize(); } void ossimBumpShadeTileSource::propertyEvent(ossimPropertyEvent& /* event */) { initialize(); } void ossimBumpShadeTileSource::refreshEvent(ossimRefreshEvent& /* event */) { initialize(); } void ossimBumpShadeTileSource::setProperty(ossimRefPtr property) { ossimString name = property->getName(); if(name == "lightSourceElevationAngle") { m_lightSourceElevationAngle = property->valueToString().toDouble(); } else if(name == "lightSourceAzimuthAngle") { m_lightSourceAzimuthAngle = property->valueToString().toDouble(); } else { ossimImageCombiner::setProperty(property); } } ossimRefPtr ossimBumpShadeTileSource::getProperty(const ossimString& name)const { if(name == "lightSourceElevationAngle") { ossimProperty* prop = new ossimNumericProperty(name, ossimString::toString(m_lightSourceElevationAngle), 0.0, 90.0); prop->setCacheRefreshBit(); return prop; } else if(name == "lightSourceAzimuthAngle") { ossimProperty* prop = new ossimNumericProperty(name, ossimString::toString(m_lightSourceAzimuthAngle), 0, 360); prop->setCacheRefreshBit(); return prop; } return ossimImageCombiner::getProperty(name); } void ossimBumpShadeTileSource::getPropertyNames(std::vector& propertyNames)const { ossimImageCombiner::getPropertyNames(propertyNames); propertyNames.push_back("lightSourceElevationAngle"); propertyNames.push_back("lightSourceAzimuthAngle"); } void ossimBumpShadeTileSource::setRgbColorSource(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { m_r = r; m_g = g; m_b = b; } void ossimBumpShadeTileSource::getRgbColorSource(ossim_uint8& r, ossim_uint8& g, ossim_uint8& b) const { r = m_r; g = m_g; b = m_b; } ossim-Miami-2.9.1/src/imaging/ossimCacheTileSource.cpp000066400000000000000000000502301352751253100226760ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts // // Description: ossimCacheTileSource // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimCacheTileSource:debug"); static const ossimString TILE_SIZE_XY_KW("tile_size_xy"); static const ossimString USE_INPUT_TILE_SIZE_KW("use_input_tile_size"); RTTI_DEF1(ossimCacheTileSource, "ossimCacheTileSource", ossimImageSourceFilter); ossimCacheTileSource::ossimCacheTileSource() : ossimImageSourceFilter(), //theCacheId(ossimAppFixedTileCache::instance()->newTileCache()), theTile(0), theFixedTileSize(), theCachingEnabled(true), theEventProgressFlag(false), theUseInputTileSizeFlag(false), theTileSizeXY() { ossim::defaultTileSize(theFixedTileSize); ossim::defaultTileSize(theTileSizeXY); } ossimCacheTileSource::~ossimCacheTileSource() { deleteRlevelCache(); //ossimAppFixedTileCache::instance()->deleteCache(theCacheId); //theCacheId = -1; // theBoundingRect.makeNan(); } void ossimCacheTileSource::flush() { //ossimAppFixedTileCache::instance()->flush(theCacheId); ossim_uint32 idx = 0; for(idx = 0; idx < theRLevelCacheList.size();++idx) { ossimAppFixedTileCache::instance()->flush(theRLevelCacheList[idx]); } } void ossimCacheTileSource::initialize() { ossimImageSourceFilter::initialize(); flush(); theTile = 0; } void ossimCacheTileSource::allocate() { theTile = 0; if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); } } ossimRefPtr ossimCacheTileSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "CACHE TILE START: " << tileRect << std::endl; } ossimRefPtr result = 0; if ( theInputConnection ) { if ( isSourceEnabled() ) { if(!theTile.valid()) { allocate(); } if (theTile.valid()) { // theTile->setImageRectangle(tileRect); // theTile->makeBlank(); // see if we can get a valid cache at the given resolution level ossimAppFixedTileCache::ossimAppFixedCacheId cacheId = getCacheId(resLevel); if( cacheId < 0) { return theInputConnection->getTile(tileRect, resLevel); } result = fillTile(tileRect, resLevel, cacheId); } } else // Not enabled... { result = theInputConnection->getTile(tileRect, resLevel); } } // End: if ( theInputConnection ) if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "CACHE TILE END: " << tileRect << std::endl; } return result; } #if 0 ossimRefPtr ossimCacheTileSource::fillTile( ossim_uint32 resLevel) { ossimRefPtr tempTile = 0; fireProgressEvent(0.0); ossimIrect boundingRect = getBoundingRect(resLevel); ossimIrect tileRect = theTile->getImageRectangle(); ossimIrect allignedRect = tileRect.clipToRect(boundingRect); ossimAppFixedTileCache::ossimAppFixedCacheId cacheId = getCacheId(resLevel); ossimIpt cacheTileSize = ossimAppFixedTileCache::instance()->getTileSize(cacheId); if ( !allignedRect.hasNans() ) { allignedRect.stretchToTileBoundary(cacheTileSize); // ossimAppFixedTileCache::ossimAppFixedCacheId cacheId = theCacheId; // check to see if we need to loop if((allignedRect == tileRect)&& (static_cast(tileRect.width()) == cacheTileSize.x)&& (static_cast(tileRect.height()) == cacheTileSize.y)) { ossimIpt origin = tileRect.ul(); if(theCachingEnabled) { tempTile = ossimAppFixedTileCache::instance()->getTile(cacheId, origin); } if(!tempTile.valid()) { tempTile = theInputConnection->getTile(tileRect, resLevel); if(tempTile.valid()) { if((tempTile->getBuf())&& (tempTile->getDataObjectStatus()!=OSSIM_EMPTY)&& theCachingEnabled) { ossimAppFixedTileCache::instance()->addTile(cacheId, tempTile); } } } // else // { // std::cout << "FOUND IN CACHE AT RES " << resLevel << "\n"; // } if(tempTile.valid()) { if((tempTile->getDataObjectStatus() != OSSIM_NULL)&& (tempTile->getDataObjectStatus() != OSSIM_EMPTY)) { theTile->setDataObjectStatus(tempTile->getDataObjectStatus()); theTile->loadTile(tempTile.get()); } } fireProgressEvent(100.0); } else { ossim_int32 boundaryHeight = allignedRect.height(); ossim_int32 boundaryWidth = allignedRect.width(); ossimIpt origin(allignedRect.ul()); ossim_int32 totalTiles = (boundaryHeight/cacheTileSize.y)* (boundaryWidth/theFixedTileSize.x); ossim_int32 currentTile = 0; for(ossim_int32 row = 0; row < boundaryHeight; row+=theFixedTileSize.y) { origin.x = allignedRect.ul().x; for(ossim_int32 col = 0; col < boundaryWidth; col+=theFixedTileSize.x) { ++currentTile; if(theCachingEnabled) { tempTile = ossimAppFixedTileCache::instance()->getTile(cacheId, origin); } else { tempTile = 0; } if(!tempTile.valid()) { ossimIrect rect(origin.x, origin.y, origin.x + cacheTileSize.x-1, origin.y + cacheTileSize.y-1); tempTile = theInputConnection->getTile(rect, resLevel); if(tempTile.valid()) { // drb if(theTile->getBuf()&& if(tempTile->getBuf()&& (tempTile->getDataObjectStatus()!=OSSIM_EMPTY)&& theCachingEnabled) { ossimAppFixedTileCache::instance()-> addTile(cacheId, tempTile); } } } // else // { // std::cout << "FOUND IN CACHE AT RES " << resLevel << "\n"; // } if(tempTile.valid()) { if(tempTile->getBuf()&& (tempTile->getDataObjectStatus()!=OSSIM_EMPTY)) { theTile->loadTile(tempTile.get()); } } double percent = 100.0*((double)currentTile/(double)totalTiles); fireProgressEvent(percent); origin.x += theFixedTileSize.x; } origin.y += theFixedTileSize.y; } theTile->validate(); fireProgressEvent(100); } } // End of: if ( !allignedRect.hasNans() ) return theTile; } #endif ossimRefPtr ossimCacheTileSource::fillTile( const ossimIrect& tileRect, ossim_uint32 resLevel, ossimAppFixedTileCache::ossimAppFixedCacheId cacheId ) { ossimRefPtr result = 0; ossimRefPtr tempTile = 0; fireProgressEvent(0.0); ossimIrect boundingRect = getBoundingRect(resLevel); ossimIrect allignedRect = tileRect.clipToRect(boundingRect); ossimIpt cacheTileSize = ossimAppFixedTileCache::instance()->getTileSize(cacheId); if ( !allignedRect.hasNans() ) { allignedRect.stretchToTileBoundary(cacheTileSize); // ossimAppFixedTileCache::ossimAppFixedCacheId cacheId = theCacheId; // check to see if we need to loop if((allignedRect == tileRect)&& (static_cast(tileRect.width()) == cacheTileSize.x)&& (static_cast(tileRect.height()) == cacheTileSize.y)) { // Grabbing whole tile either from cache or input. ossimIpt origin = tileRect.ul(); if(theCachingEnabled) { result = ossimAppFixedTileCache::instance()->getTile(cacheId, origin); } if(!result.valid()) { result = theInputConnection->getTile(tileRect, resLevel); if(result.valid()) { if((result->getBuf())&& (result->getDataObjectStatus()!=OSSIM_EMPTY)&& theCachingEnabled) { ossimAppFixedTileCache::instance()->addTile(cacheId, result); } } } // else // { // std::cout << "FOUND IN CACHE AT RES " << resLevel << "\n"; // } #if 0 if(tempTile.valid()) { if((tempTile->getDataObjectStatus() != OSSIM_NULL)&& (tempTile->getDataObjectStatus() != OSSIM_EMPTY)) { theTile->setDataObjectStatus(tempTile->getDataObjectStatus()); theTile->loadTile(tempTile.get()); } } #endif fireProgressEvent(100.0); } else { theTile->setImageRectangle(tileRect); theTile->makeBlank(); ossim_int32 boundaryHeight = allignedRect.height(); ossim_int32 boundaryWidth = allignedRect.width(); ossimIpt origin(allignedRect.ul()); ossim_int32 totalTiles = (boundaryHeight/cacheTileSize.y)* (boundaryWidth/theFixedTileSize.x); ossim_int32 currentTile = 0; for(ossim_int32 row = 0; row < boundaryHeight; row+=theFixedTileSize.y) { origin.x = allignedRect.ul().x; for(ossim_int32 col = 0; col < boundaryWidth; col+=theFixedTileSize.x) { ++currentTile; if(theCachingEnabled) { tempTile = ossimAppFixedTileCache::instance()->getTile(cacheId, origin); } else { tempTile = 0; } if(!tempTile.valid()) { ossimIrect rect(origin.x, origin.y, origin.x + cacheTileSize.x-1, origin.y + cacheTileSize.y-1); tempTile = theInputConnection->getTile(rect, resLevel); if(tempTile.valid()) { // drb if(theTile->getBuf()&& if(tempTile->getBuf()&& (tempTile->getDataObjectStatus()!=OSSIM_EMPTY)&& theCachingEnabled) { ossimAppFixedTileCache::instance()-> addTile(cacheId, tempTile); } } } // else // { // std::cout << "FOUND IN CACHE AT RES " << resLevel << "\n"; // } if(tempTile.valid()) { if(tempTile->getBuf()&& (tempTile->getDataObjectStatus()!=OSSIM_EMPTY)) { theTile->loadTile(tempTile.get()); } } double percent = 100.0*((double)currentTile/(double)totalTiles); fireProgressEvent(percent); origin.x += theFixedTileSize.x; } origin.y += theFixedTileSize.y; } theTile->validate(); result = theTile; fireProgressEvent(100); } } // End of: if ( !allignedRect.hasNans() ) else { theTile->setImageRectangle(tileRect); theTile->makeBlank(); result = theTile; } return result; } ossim_uint32 ossimCacheTileSource::getTileWidth() const { return theFixedTileSize.x; } ossim_uint32 ossimCacheTileSource::getTileHeight() const { return theFixedTileSize.y; } bool ossimCacheTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { //ossimAppFixedTileCache::instance()->deleteCache(theCacheId); //theCacheId = ossimAppFixedTileCache::instance()->newTileCache(); deleteRlevelCache(); const char* lookup = kwl.find(prefix, ossimKeywordNames::ENABLE_CACHE_KW); if(lookup) { theCachingEnabled = ossimString(lookup).toBool(); } lookup = kwl.find(prefix, USE_INPUT_TILE_SIZE_KW); if(lookup) { theUseInputTileSizeFlag = ossimString(lookup).toBool(); } lookup = kwl.find(prefix, TILE_SIZE_XY_KW); if (lookup) { ossimIpt pt; pt.toPoint(std::string(lookup)); setTileSize(pt); theTileSizeXY = pt; } bool result = ossimImageSourceFilter::loadState(kwl, prefix); initialize(); return result; } bool ossimCacheTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::ENABLE_CACHE_KW, theCachingEnabled, true); kwl.add(prefix, USE_INPUT_TILE_SIZE_KW, theUseInputTileSizeFlag, true); kwl.add(prefix, TILE_SIZE_XY_KW, theFixedTileSize.toString().c_str()); return ossimImageSourceFilter::saveState(kwl, prefix); } ossimRefPtr ossimCacheTileSource::getProperty( const ossimString& name)const { // Lock for the length of this method. if (name == TILE_SIZE_XY_KW) { ossimRefPtr result = new ossimStringProperty(name, theFixedTileSize.toString()); result->setCacheRefreshBit(); return result; } else if(name == ossimKeywordNames::ENABLE_CACHE_KW) { ossimRefPtr result = new ossimBooleanProperty(name, theCachingEnabled); result->setCacheRefreshBit(); return result; } else if(name == USE_INPUT_TILE_SIZE_KW) { ossimRefPtr result = new ossimBooleanProperty(name, theUseInputTileSizeFlag); result->setCacheRefreshBit(); return result; } return ossimImageSourceFilter::getProperty(name); } void ossimCacheTileSource::setProperty(ossimRefPtr property) { if (!property) return; ossimString name = property->getName(); if (name == TILE_SIZE_XY_KW) { ossimIpt pt; pt.toPoint(property->valueToString()); if ( (pt.x > 7) && (pt.y > 7) ) { setTileSize(pt); } else { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimCacheTileSource::setProperty NOTICE:" << "\nTile dimensions must be at least 8!" << "\nFormat = ( x, y )" << std::endl; } } else if(name == ossimKeywordNames::ENABLE_CACHE_KW) { setCachingEnabledFlag(property->valueToString().toBool()); } else if(name == USE_INPUT_TILE_SIZE_KW) { theUseInputTileSizeFlag = property->valueToString().toBool(); if(theUseInputTileSizeFlag) { deleteRlevelCache(); } // setCachingEnabledFlag(property->valueToString().toBool()); } else { ossimImageSourceFilter::setProperty(property); } } void ossimCacheTileSource::getPropertyNames( std::vector& propertyNames)const { propertyNames.push_back(TILE_SIZE_XY_KW); propertyNames.push_back(ossimKeywordNames::ENABLE_CACHE_KW); propertyNames.push_back(USE_INPUT_TILE_SIZE_KW); ossimImageSourceFilter::getPropertyNames(propertyNames); } ossimString ossimCacheTileSource::getLongName()const { return ossimString("Tile Cache , cache for ossimImageData objects."); } ossimString ossimCacheTileSource::getShortName()const { return ossimString("Tile Cache"); } void ossimCacheTileSource::setCachingEnabledFlag(bool value) { if(!value && theCachingEnabled) { flush(); } theCachingEnabled = value; } void ossimCacheTileSource::setEventProgressFlag(bool value) { theEventProgressFlag = value; } void ossimCacheTileSource::getTileSize(ossimIpt& size) const { size = theFixedTileSize; } void ossimCacheTileSource::setTileSize(const ossimIpt& size) { if (size != theFixedTileSize) { theTile = 0; // Force an allocate of new tile. theFixedTileSize = size; initializeRlevelCache(); // ossimAppFixedTileCache::instance()->setTileSize(theCacheId, size); } } void ossimCacheTileSource::fireProgressEvent(double percentComplete) { if(theEventProgressFlag) { ossimProcessProgressEvent event(this, percentComplete); fireEvent(event); } } ossimAppFixedTileCache::ossimAppFixedCacheId ossimCacheTileSource::getCacheId(ossim_uint32 resLevel) { ossimAppFixedTileCache::ossimAppFixedCacheId result = -1; if(theRLevelCacheList.empty()) { initializeRlevelCache(); } if(resLevel < theRLevelCacheList.size()) { if(theRLevelCacheList[resLevel] <0) { ossimIpt cacheTileSize(theFixedTileSize); if(theUseInputTileSizeFlag) { cacheTileSize = ossimIpt(ossim::min(static_cast(theInputConnection->getTileWidth()), static_cast(1024)), ossim::min(static_cast(theInputConnection->getTileHeight()), static_cast(1024))); } //std::cout << cacheTileSize << std::endl; ossimIrect rect = getBoundingRect(resLevel); if((cacheTileSize.x > static_cast(rect.width()))&& (cacheTileSize.y > static_cast(rect.height()))) { cacheTileSize.x = ossim::max(static_cast(rect.width()), static_cast(theTileSizeXY.x)); cacheTileSize.y = ossim::max(static_cast(rect.height()), static_cast(theTileSizeXY.y)); } rect.stretchToTileBoundary(theFixedTileSize); theRLevelCacheList[resLevel] = ossimAppFixedTileCache::instance()->newTileCache(rect, cacheTileSize); } result = theRLevelCacheList[resLevel]; } return result; } void ossimCacheTileSource::deleteRlevelCache() { ossim_uint32 idx = 0; for(idx = 0; idx < theRLevelCacheList.size();++idx) { ossimAppFixedTileCache::instance()->deleteCache(theRLevelCacheList[idx]); } theRLevelCacheList.clear(); } void ossimCacheTileSource::initializeRlevelCache() { ossim_uint32 nLevels = getNumberOfDecimationLevels(); deleteRlevelCache(); if(nLevels > 0) { ossim_uint32 idx = 0; theRLevelCacheList.resize(nLevels); for(idx= 0; idx < theRLevelCacheList.size(); ++idx) { theRLevelCacheList[idx] = -1; } } } ossim-Miami-2.9.1/src/imaging/ossimCastTileSourceFilter.cpp000066400000000000000000000516371352751253100237470ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimCastTileSourceFilter.cpp 17195 2010-04-23 17:32:18Z dburken $ #include #include #include #include #include #include RTTI_DEF1( ossimCastTileSourceFilter, "ossimCastTileSourceFilter", ossimImageSourceFilter ); using namespace std; ossimCastTileSourceFilter::ossimCastTileSourceFilter(ossimImageSource* input, ossimScalarType scalarType) :ossimImageSourceFilter(NULL,input), theTile(NULL), theOutputScalarType(scalarType) { } ossimCastTileSourceFilter::~ossimCastTileSourceFilter() { } ossimRefPtr ossimCastTileSourceFilter::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr inputTile; if(theInputConnection) { inputTile = theInputConnection->getTile(tileRect, resLevel); } return applyCast(inputTile); } ossimScalarType ossimCastTileSourceFilter::getOutputScalarType() const { if(isSourceEnabled()) { return theOutputScalarType; } else if(theInputConnection) { return theInputConnection->getOutputScalarType(); } return OSSIM_SCALAR_UNKNOWN; } double ossimCastTileSourceFilter::getNullPixelValue(ossim_uint32 band)const { if(!isSourceEnabled()) { if(theInputConnection) { return theInputConnection->getNullPixelValue(band); } } return ossim::defaultNull(getOutputScalarType()); } double ossimCastTileSourceFilter::getMinPixelValue(ossim_uint32 band)const { if(!isSourceEnabled()) { if(theInputConnection) { return theInputConnection->getMinPixelValue(band); } } if(theInputConnection) { double tempMin = theInputConnection->getMinPixelValue(band); double defaultMin = ossim::defaultMin(theOutputScalarType); double defaultMax = ossim::defaultMax(theOutputScalarType); if((tempMin >= defaultMin) && (tempMin <= defaultMax)) { defaultMin = tempMin; } return defaultMin; } return ossimImageSource::getMinPixelValue(band); } double ossimCastTileSourceFilter::getMaxPixelValue(ossim_uint32 band)const { if(!isSourceEnabled()) { if(theInputConnection) { return theInputConnection->getMaxPixelValue(band); } } if(theInputConnection) { double tempMax = theInputConnection->getMaxPixelValue(band); double defaultMax = ossim::defaultMax(theOutputScalarType); double defaultMin = ossim::defaultMin(theOutputScalarType); if((tempMax >= defaultMin) && (tempMax <= defaultMax)) { defaultMax = tempMax; } return defaultMax; } return ossimImageSource::getMaxPixelValue(band); } ossimRefPtr ossimCastTileSourceFilter::applyCast( ossimRefPtr inputTile) { if(!inputTile.valid()) { return inputTile; } if(!theTile.valid() || (theTile->getNumberOfBands() != inputTile->getNumberOfBands())) { allocate(inputTile); } else { ossim_int32 tw =inputTile->getWidth(); ossim_int32 th =inputTile->getHeight(); ossim_int32 w = theTile->getWidth(); ossim_int32 h = theTile->getHeight(); theTile->setWidthHeight(tw, th); if((w*h != tw*th)) { theTile->initialize(); } else { theTile->makeBlank(); } theTile->setOrigin(inputTile->getOrigin()); } if( (inputTile->getDataObjectStatus()==OSSIM_EMPTY) || (inputTile->getDataObjectStatus()==OSSIM_NULL)) { return theTile; } switch(inputTile->getScalarType()) { case OSSIM_UINT8: { ossim_uint8** bands = new ossim_uint8*[inputTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < inputTile->getNumberOfBands(); ++band) { bands[band] = static_cast(inputTile->getBuf(band)); } castInputToOutput(bands, inputTile->getNullPix(), inputTile->getDataObjectStatus()==OSSIM_PARTIAL); delete [] bands; break; } case OSSIM_SINT8: { ossim_sint8** bands = new ossim_sint8*[inputTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < inputTile->getNumberOfBands(); ++band) { bands[band] = static_cast(inputTile->getBuf(band)); } castInputToOutput(bands, inputTile->getNullPix(), inputTile->getDataObjectStatus()==OSSIM_PARTIAL); delete [] bands; break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { ossim_uint16** bands = new ossim_uint16*[inputTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < inputTile->getNumberOfBands(); ++band) { bands[band] = static_cast(inputTile->getBuf(band)); } castInputToOutput(bands, inputTile->getNullPix(), inputTile->getDataObjectStatus()==OSSIM_PARTIAL); delete [] bands; break; } case OSSIM_SINT16: { ossim_sint16** bands = new ossim_sint16*[inputTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < inputTile->getNumberOfBands(); ++band) { bands[band] = static_cast(inputTile->getBuf(band)); } castInputToOutput(bands, inputTile->getNullPix(), inputTile->getDataObjectStatus()==OSSIM_PARTIAL); delete [] bands; break; } case OSSIM_SINT32: { ossim_sint32** bands = new ossim_sint32*[inputTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < inputTile->getNumberOfBands(); ++band) { bands[band] = static_cast(inputTile->getBuf(band)); } castInputToOutput(bands, inputTile->getNullPix(), inputTile->getDataObjectStatus()==OSSIM_PARTIAL); delete [] bands; break; } case OSSIM_UINT32: { ossim_uint32** bands = new ossim_uint32*[inputTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < inputTile->getNumberOfBands(); ++band) { bands[band] = static_cast(inputTile->getBuf(band)); } castInputToOutput(bands, inputTile->getNullPix(), inputTile->getDataObjectStatus()==OSSIM_PARTIAL); delete [] bands; break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { float** bands = new float*[inputTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < inputTile->getNumberOfBands(); ++band) { bands[band] = static_cast(inputTile->getBuf(band)); } castInputToOutput(bands, inputTile->getNullPix(), inputTile->getDataObjectStatus()==OSSIM_PARTIAL); delete [] bands; break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { double** bands = new double*[inputTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < inputTile->getNumberOfBands(); ++band) { bands[band] = static_cast(inputTile->getBuf(band)); } castInputToOutput(bands, inputTile->getNullPix(), inputTile->getDataObjectStatus()==OSSIM_PARTIAL); delete [] bands; break; } case OSSIM_SCALAR_UNKNOWN: default: { break; } } // theTile->setDataObjectStatus(inputTile->getDataObjectStatus()); theTile->validate(); return theTile; } void ossimCastTileSourceFilter::setOutputScalarType(ossimScalarType scalarType) { ossimScalarType old_type = theOutputScalarType; theOutputScalarType = scalarType; if ( (theOutputScalarType != old_type)) { // must reinitialize... theTile = NULL; initialize(); } } void ossimCastTileSourceFilter::setOutputScalarType(ossimString scalarType) { int scalar = ossimScalarTypeLut::instance()->getEntryNumber(scalarType.c_str()); if (scalar != ossimLookUpTable::NOT_FOUND) { setOutputScalarType(static_cast(scalar)); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimCastTileSourceFilter::setOutputScalarType WARN:" << "\nUnknown scalar type: " << scalarType.c_str() << endl; } } ossimString ossimCastTileSourceFilter::getOutputScalarTypeString()const { return ossimScalarTypeLut::instance()->getEntryString(theOutputScalarType); } void ossimCastTileSourceFilter::initialize() { ossimImageSourceFilter::initialize(); if (theOutputScalarType == OSSIM_SCALAR_UNKNOWN) { // default to OSSIM_UCHAR theOutputScalarType = OSSIM_UCHAR; } } bool ossimCastTileSourceFilter::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimImageSourceFilter::saveState(kwl, prefix); kwl.add(prefix, ossimKeywordNames::SCALAR_TYPE_KW, ossimScalarTypeLut::instance()->getEntryString(theOutputScalarType), true); return true; } bool ossimCastTileSourceFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimImageSourceFilter::loadState(kwl, prefix); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN) << "ossimScalarRemapper::loadState WARN:\n" << " ERROR detected in keyword list! State not loaded." << endl; return false; } int scalar = ossimScalarTypeLut::instance()->getEntryNumber(kwl, prefix); if (scalar != ossimLookUpTable::NOT_FOUND) { theOutputScalarType = static_cast(scalar); } return true; } template void ossimCastTileSourceFilter::castInputToOutput(inType **inBuffer, const double *nullPix, bool inPartialFlag) { switch(theTile->getScalarType()) { case OSSIM_UINT8: { ossim_uint8** bands = new ossim_uint8*[theTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < theTile->getNumberOfBands(); ++band) { bands[band] = static_cast(theTile->getBuf(band)); } castInputToOutput(inBuffer, nullPix, inPartialFlag, bands, theTile->getNullPix(), theTile->getNumberOfBands()); delete [] bands; break; } case OSSIM_SINT8: { ossim_sint8** bands = new ossim_sint8*[theTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < theTile->getNumberOfBands(); ++band) { bands[band] = static_cast(theTile->getBuf(band)); } castInputToOutput(inBuffer, nullPix, inPartialFlag, bands, theTile->getNullPix(), theTile->getNumberOfBands()); delete [] bands; break; } case OSSIM_SINT16: { ossim_sint16** bands = new ossim_sint16*[theTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < theTile->getNumberOfBands(); ++band) { bands[band] = static_cast(theTile->getBuf(band)); } castInputToOutput(inBuffer, nullPix, inPartialFlag, bands, theTile->getNullPix(), theTile->getNumberOfBands()); delete [] bands; break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { ossim_uint16** bands = new ossim_uint16*[theTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < theTile->getNumberOfBands(); ++band) { bands[band] = static_cast(theTile->getBuf(band)); } castInputToOutput(inBuffer, nullPix, inPartialFlag, bands, theTile->getNullPix(), theTile->getNumberOfBands()); delete [] bands; break; } case OSSIM_UINT32: { ossim_uint32** bands = new ossim_uint32*[theTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < theTile->getNumberOfBands(); ++band) { bands[band] = static_cast(theTile->getBuf(band)); } castInputToOutput(inBuffer, nullPix, inPartialFlag, bands, theTile->getNullPix(), theTile->getNumberOfBands()); delete [] bands; break; } case OSSIM_SINT32: { ossim_sint32** bands = new ossim_sint32*[theTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < theTile->getNumberOfBands(); ++band) { bands[band] = static_cast(theTile->getBuf(band)); } castInputToOutput(inBuffer, nullPix, inPartialFlag, bands, theTile->getNullPix(), theTile->getNumberOfBands()); delete [] bands; break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { float** bands = new float*[theTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < theTile->getNumberOfBands(); ++band) { bands[band] = static_cast(theTile->getBuf(band)); } castInputToOutput(inBuffer, nullPix, inPartialFlag, bands, theTile->getNullPix(), theTile->getNumberOfBands()); delete [] bands; break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { double** bands = new double*[theTile->getNumberOfBands()]; for(ossim_uint32 band = 0; band < theTile->getNumberOfBands(); ++band) { bands[band] = static_cast(theTile->getBuf(band)); } castInputToOutput(inBuffer, nullPix, inPartialFlag, bands, theTile->getNullPix(), theTile->getNumberOfBands()); delete [] bands; break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimCastTileSourceFilter::castInputToOutput WARN:\n" << "Scalar not set in ossimCastTileSourceFilter" << endl; break; } } } template void ossimCastTileSourceFilter::castInputToOutput(inType *inBuffer[], const double *nullInPix, bool inPartialFlag, outType *outBuffer[], const double *nullOutPix, ossim_uint32 numberOfBands) { ossim_uint32 size = theTile->getWidth()*theTile->getHeight(); if(!inPartialFlag) { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { outType outMin = static_cast(theTile->getMinPix(band)); outType outMax = static_cast(theTile->getMaxPix(band)); for(ossim_uint32 offset = 0; offset < size; ++offset) { double temp = inBuffer[band][offset]; if(temp < outMin) temp = outMin; if(temp > outMax) temp = outMax; outBuffer[band][offset] = static_cast(temp); } } } else { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { inType np = static_cast(nullInPix[band]); outType outNp = static_cast(nullOutPix[band]); outType outMin = static_cast(theTile->getMinPix(band)); outType outMax = static_cast(theTile->getMaxPix(band)); for(ossim_uint32 offset = 0; offset < size; ++offset) { if(inBuffer[band][offset] != np) { double temp = inBuffer[band][offset]; if(temp < outMin) temp = outMin; if(temp > outMax) temp = outMax; outBuffer[band][offset] = static_cast(temp); } else { outBuffer[band][offset] = static_cast(outNp); } } } } } void ossimCastTileSourceFilter::allocate(const ossimRefPtr inputTile) { theTile = ossimImageDataFactory::instance()->create( this, getOutputScalarType(), inputTile->getNumberOfBands(), inputTile->getWidth(), inputTile->getHeight()); theTile->initialize(); theTile->setOrigin(inputTile->getOrigin()); } void ossimCastTileSourceFilter::propertyEvent(ossimPropertyEvent& /* event */) { } void ossimCastTileSourceFilter::refreshEvent(ossimRefreshEvent& /* event */) { } void ossimCastTileSourceFilter::setProperty(ossimRefPtr property) { if(property->getName() == ossimKeywordNames::SCALAR_TYPE_KW) { int scalar = ossimScalarTypeLut::instance()->getEntryNumber(property->valueToString()); if (scalar != ossimLookUpTable::NOT_FOUND) { setOutputScalarType(static_cast(scalar)); } } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimCastTileSourceFilter::getProperty(const ossimString& name)const { ossimRefPtr resultProperty; if(name == ossimKeywordNames::SCALAR_TYPE_KW) { ossimStringProperty* stringProperty = new ossimStringProperty(name, ossimScalarTypeLut::instance()->getEntryString(theOutputScalarType), false); stringProperty->addConstraint(ossimScalarTypeLut::instance()->getEntryString(OSSIM_UINT8)); stringProperty->addConstraint(ossimScalarTypeLut::instance()->getEntryString(OSSIM_SINT8)); stringProperty->addConstraint(ossimScalarTypeLut::instance()->getEntryString(OSSIM_UINT16)); stringProperty->addConstraint(ossimScalarTypeLut::instance()->getEntryString(OSSIM_SINT16)); stringProperty->addConstraint(ossimScalarTypeLut::instance()->getEntryString(OSSIM_UINT32)); stringProperty->addConstraint(ossimScalarTypeLut::instance()->getEntryString(OSSIM_SINT32)); stringProperty->addConstraint(ossimScalarTypeLut::instance()->getEntryString(OSSIM_FLOAT32)); stringProperty->addConstraint(ossimScalarTypeLut::instance()->getEntryString(OSSIM_FLOAT64)); stringProperty->setCacheRefreshBit(); resultProperty = stringProperty; } else { resultProperty = ossimImageSourceFilter::getProperty(name); } return resultProperty; } void ossimCastTileSourceFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back(ossimKeywordNames::SCALAR_TYPE_KW); } ossim-Miami-2.9.1/src/imaging/ossimCcfHead.cpp000066400000000000000000000621121352751253100211530ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: // // Contains class definition for CcfHead. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimCcfHead:debug"); ossimCcfHead::ossimCcfHead() : m_connectionString(), theNumberOfBands(1), thePixelType(OSSIM_UCHAR), theFileType(), theVersionNumber(0), theLinesPerChip(0), theSamplesPerChip(0), theLineChipsPerChunk(0), theSampleChipsPerChunk(0), theRectInFullImageStartLine(0), theRectInFuleImageStartSample(0), theRectInFullImageStopLine(0), theRectInFuleImageStopSample(0), theNumberOfValidImageVertices(0), theValidImageVertices(1), theFirstBandHeaderPointer(0), theRadiometryString(), theBytesPerPixel(0), theBytesPerChip(0), theBytesPerChunk(0), theCompressionType(), theNumberOfRLevels(0), theOccupiedFlag(1), theStartOfData(1), theNumberOfLines(1), theNumberOfSamples(1), theChunksInLineDir(1), theChunksInSampleDir(1) {} //*************************************************************************** // Public Constructor: //*************************************************************************** ossimCcfHead::ossimCcfHead(const char* ccf_file) : m_connectionString(ccf_file), theNumberOfBands(1), thePixelType(OSSIM_UCHAR), theFileType(), theVersionNumber(0), theLinesPerChip(0), theSamplesPerChip(0), theLineChipsPerChunk(0), theSampleChipsPerChunk(0), theRectInFullImageStartLine(0), theRectInFuleImageStartSample(0), theRectInFullImageStopLine(0), theRectInFuleImageStopSample(0), theNumberOfValidImageVertices(0), theValidImageVertices(1), theFirstBandHeaderPointer(0), theRadiometryString(""), theBytesPerPixel(0), theBytesPerChip(0), theBytesPerChunk(0), theCompressionType(), theNumberOfRLevels(0), theOccupiedFlag(1), theStartOfData(1), theNumberOfLines(1), theNumberOfSamples(1), theChunksInLineDir(1), theChunksInSampleDir(1) { static const char MODULE[] = "ossimCcfHead::ossimCcfHead"; if (!parseCcfHeader(ccf_file)) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR!" << "\nError initializing from ccf_file: " << ccf_file << "\nReturning...\n"; } } } ossimCcfHead::ossimCcfHead(std::shared_ptr& str, const std::string& connectionString) { static const char MODULE[] = "ossimCcfHead::ossimCcfHead"; if(!str) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } else if (!parseCcfHeader(str, connectionString)) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR!" << "\nError initializing from ccf_file: " << connectionString << "\nReturning...\n"; } } } //*************************************************************************** // Destructor: //*************************************************************************** ossimCcfHead::~ossimCcfHead() {} //*************************************************************************** // Public Method: //*************************************************************************** bool ossimCcfHead::parseCcfHeader(const char* ccf_file) { static const char MODULE[] = "ossimCcfHead::parseCcfHeader"; bool result = false; std::string connectionString = ccf_file; std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( connectionString, std::ios_base::in|std::ios_base::binary); if ( str ) { result = parseCcfHeader(str, connectionString); } else { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR!" << "\nCannot open file: " << m_connectionString << "\n"; } } return result; } bool ossimCcfHead::parseCcfHeader(std::shared_ptr& str, const std::string& connectionString) { static const char MODULE[] = "ossimCcfHead::parseossimCcfHeader"; bool result = false; if ( str ) { str->clear(); str->seekg(0); const ossim_uint32 MAX_LEN = 256; char tmp[MAX_LEN]; // Check the first string should be "CCF" else get out... // this might hang so I changed it to not use the // >> operator unless it is a ccf file. If it is another // file we might not be guranteed a whitespace or \n character // will exist and therefore the entrie file could have // been read in. // char type[4]; str->read(type, 3); type[3] = '\0'; theFileType = type; if (theFileType == "CCF") { m_ccfStr = str; m_connectionString = connectionString; // Check the version number. (*m_ccfStr) >> tmp >> theVersionNumber; //--- // Call the appropriate method for the version. Currently only version 6 // supported as that was all I had in-house. Feel free to add your own // version reader! //--- switch(theVersionNumber) { case 5: { result = parseV5CcfHeader(*m_ccfStr); break; } case 6: { result = parseV6CcfHeader(*m_ccfStr); break; } default: { m_ccfStr = 0; // Version type not supported... if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR!" << "\nUsupported version: " << theVersionNumber << " Returning...\n"; } } break; } } if ( result ) { //--- // Parse the radiometry string. This will initialize "theNumberOfBands" // and the pixel type. //--- parseRadString(); } else { str->clear(); str->seekg(0); } } return result; } //*************************************************************************** // Private Method: //*************************************************************************** bool ossimCcfHead::parseV5CcfHeader(ossim::istream& is) { static const char MODULE[] = "CcfHead::parseV5CcfHeader"; // Check the stream. if ( !is ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Bad Stream passed to method!" << "\nReturning...\n"; } return false; } const ossim_uint32 MAX_LEN = 256; char tmp[MAX_LEN]; //--- // These are all fixed/not used so just skip... //--- is.read(tmp, 1); // eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip "ccf_maker" is >> tmp // "LinesPerChip" >> theLinesPerChip >> tmp // "SamplesPerChip" >> theSamplesPerChip >> tmp // "LineChipsPerChunk" >> theLineChipsPerChunk >> tmp // "SampleChipsPerChunk" >> theSampleChipsPerChunk; is.read(tmp, 1); // eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip "NumberOfBands" is.getline(tmp, MAX_LEN-1, '\n'); // skip "RectInFullImageSpace" is >> tmp // skip "StartLine" >> theRectInFullImageStartLine >> tmp // skip "StartSample" >> theRectInFuleImageStartSample >> tmp // skip "StopLine" >> theRectInFullImageStopLine >> tmp // skip "StopSample" >> theRectInFuleImageStopSample; // No valid image vertices in this version. theNumberOfValidImageVertices = 0; theValidImageVertices[0] = ossimIpt(0,0); is.read(tmp, 1); // eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip blank line is >> tmp // skip "FirstBandHeaderPointer" >> theFirstBandHeaderPointer; // Offset to band header. // Seek to the band header record. is.seekg(theFirstBandHeaderPointer, std::ios_base::beg); is.getline(tmp, MAX_LEN-1, '\n'); // skip "BAND" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "NextBandHeaderPointer" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "ChunkMapPointer" line is >> tmp; // skip "Radiometry" is.getline(tmp, MAX_LEN-1, '\n'); // Get the radiometry string. const char* rad = tmp; while ( *rad && (*rad == ' ')) rad++; // Eat the whitespaces... theRadiometryString = rad; is >> tmp // skip "BytesPerPixel" >> theBytesPerPixel >> tmp // skip "BytesPerChip" >> theBytesPerChip >> tmp // skip "BytesPerChunk" >> theBytesPerChunk >> tmp // skip "CompressionType" >> theCompressionType >> tmp // skip "NumberOfRLevels" >> theNumberOfRLevels; if ((ossim_uint32)theNumberOfRLevels > theOccupiedFlag.size()) { // Resize all the vectors. theOccupiedFlag.resize(theNumberOfRLevels); theStartOfData.resize(theNumberOfRLevels); theNumberOfLines.resize(theNumberOfRLevels); theNumberOfSamples.resize(theNumberOfRLevels); theChunksInLineDir.resize(theNumberOfRLevels); theChunksInSampleDir.resize(theNumberOfRLevels); } is.read(tmp, 1); // eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip blank line ossim_uint32 i; for (i=0; i> tmp // skip "Occupied" >> tmp_long; theOccupiedFlag[i] = tmp_long; is >> tmp // skip "StartOfData" >> tmp_long; theStartOfData[i] = tmp_long; is >> tmp // skip "NumberOfLines" >> tmp_long; theNumberOfLines[i] = tmp_long; is >> tmp // skip "NumberOfSamples" >> tmp_long; theNumberOfSamples[i] = tmp_long; is >> tmp // skip "ChunksInLineDir" >> tmp_long; theChunksInLineDir[i] = tmp_long; is >> tmp // skip "ChunksInSampleDir" >> tmp_long; theChunksInSampleDir[i] = tmp_long; is.getline(tmp, MAX_LEN-1, '\n'); // skip "LineOffset" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "LineDecimation" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "SampleOffset" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "SampleDecimation" line is.read(tmp, 1); // Eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip blank line is.read(tmp, 1); // Eat the '\n' } // Note: The caller will close the stream. return true; } //*************************************************************************** // Private Method: //*************************************************************************** bool ossimCcfHead::parseV6CcfHeader(std::istream& is) { static const char MODULE[] = "CcfHead::parseV6CcfHeader"; // Check the stream. if (!is) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Bad Stream passed to method!" << "\nReturning...\n"; } return false; } const ossim_uint32 MAX_LEN = 256; char tmp[MAX_LEN]; //*** // These are all fixed/not used so just skip... //*** is.read(tmp, 1); // eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip "ccf_maker" is >> tmp // "LinesPerChip" >> theLinesPerChip >> tmp // "SamplesPerChip" >> theSamplesPerChip >> tmp // "LineChipsPerChunk" >> theLineChipsPerChunk >> tmp // "SampleChipsPerChunk" >> theSampleChipsPerChunk; is.read(tmp, 1); // eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip "NumberOfBands" is.getline(tmp, MAX_LEN-1, '\n'); // skip "RectInFullImageSpace" is >> tmp // skip "StartLine" >> theRectInFullImageStartLine >> tmp // skip "StartSample" >> theRectInFuleImageStartSample >> tmp // skip "StopLine" >> theRectInFullImageStopLine >> tmp // skip "StopSample" >> theRectInFuleImageStopSample >> tmp // skip "ValidImageVertices" >> theNumberOfValidImageVertices; // Get the valid image vertices. ossim_uint32 i; if (theNumberOfValidImageVertices != theValidImageVertices.size()) { theValidImageVertices.resize(theNumberOfValidImageVertices); } for (i=0; i> tmp // skip "Vertex" >> tmp // skip Vertex number >> tmp_dbl; // line theValidImageVertices[i].y = static_cast(tmp_dbl.toDouble()); tmp_dbl = ""; is >> tmp_dbl; // sample theValidImageVertices[i].x = static_cast(tmp_dbl.toDouble()); } is.read(tmp, 1); // eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip blank line is >> tmp // skip "FirstBandHeaderPointer" >> theFirstBandHeaderPointer; // Offset to band header. // Seek to the band header record. is.seekg(theFirstBandHeaderPointer, std::ios_base::beg); is.getline(tmp, MAX_LEN-1, '\n'); // skip "BAND" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "NextBandHeaderPointer" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "ChunkMapPointer" line is >> tmp; // skip "Radiometry" is.getline(tmp, MAX_LEN-1, '\n'); // Get the radiometry string. const char* rad = tmp; while ( *rad && (*rad == ' ')) rad++; // Eat the whitespaces... theRadiometryString = rad; is >> tmp // skip "BytesPerPixel" >> theBytesPerPixel >> tmp // skip "BytesPerChip" >> theBytesPerChip >> tmp // skip "BytesPerChunk" >> theBytesPerChunk >> tmp // skip "CompressionType" >> theCompressionType >> tmp // skip "NumberOfRLevels" >> theNumberOfRLevels; if (theNumberOfRLevels > theOccupiedFlag.size()) { // Resize all the vectors. theOccupiedFlag.resize(theNumberOfRLevels); theStartOfData.resize(theNumberOfRLevels); theNumberOfLines.resize(theNumberOfRLevels); theNumberOfSamples.resize(theNumberOfRLevels); theChunksInLineDir.resize(theNumberOfRLevels); theChunksInSampleDir.resize(theNumberOfRLevels); } is.read(tmp, 1); // eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip blank line for (i=0; i> tmp // skip "Occupied" >> tmp_long; theOccupiedFlag[i] = tmp_long; is >> tmp // skip "StartOfData" >> tmp_long; theStartOfData[i] = tmp_long; is >> tmp // skip "NumberOfLines" >> tmp_long; theNumberOfLines[i] = tmp_long; is >> tmp // skip "NumberOfSamples" >> tmp_long; theNumberOfSamples[i] = tmp_long; is >> tmp // skip "ChunksInLineDir" >> tmp_long; theChunksInLineDir[i] = tmp_long; is >> tmp // skip "ChunksInSampleDir" >> tmp_long; theChunksInSampleDir[i] = tmp_long; is.getline(tmp, MAX_LEN-1, '\n'); // skip "LineOffset" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "LineDecimation" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "SampleOffset" line is.getline(tmp, MAX_LEN-1, '\n'); // skip "SampleDecimation" line is.read(tmp, 1); // Eat the '\n' is.getline(tmp, MAX_LEN-1, '\n'); // skip blank line is.read(tmp, 1); // Eat the '\n' } // Note: The caller will close the stream. return true; } //*************************************************************************** // Public Method: //*************************************************************************** std::ostream& ossimCcfHead::print(std::ostream& out) const { static const char MODULE[] = "ossimCcfHead::print"; out << MODULE << "\ntheErrorStatus: " << theErrorStatus << "\ntheCcfFile: " << m_connectionString << "\ntheNumberOfBands: " << theNumberOfBands << "\nthePixelType: " << (ossimScalarTypeLut::instance()->getEntryString(thePixelType)) << "\ntheFileType: " << theFileType << "\ntheVersionNumber: " << theVersionNumber << "\ntheLinesPerChip: " << theLinesPerChip << "\ntheSamplesPerChip: " << theSamplesPerChip << "\ntheLineChipsPerChunk: " << theLineChipsPerChunk << "\ntheSampleChipsPerChunk: " << theSampleChipsPerChunk << "\ntheRectInFullImageStartLine: " << theRectInFullImageStartLine << "\ntheRectInFuleImageStartSample: " << theRectInFuleImageStartSample << "\ntheRectInFullImageStopLine: " << theRectInFullImageStopLine << "\ntheRectInFuleImageStopSample: " << theRectInFuleImageStopSample << "\ntheNumberOfValidImageVertices: " << theNumberOfValidImageVertices; ossim_uint32 i; for (i=0; i highestReducedResSet() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR!" << "\nInvalid reduced res level: " << reduced_res_level << "\nHighest reduced res level available: " << highestReducedResSet() << std::endl; return 0; } return theNumberOfLines[reduced_res_level]; } //*************************************************************************** // Public Method: //*************************************************************************** ossim_uint32 ossimCcfHead::numberOfSamples(ossim_uint32 reduced_res_level) const { static const char MODULE[] = "ossimCcfHead::numberOfSamples"; if (reduced_res_level > highestReducedResSet() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR!" << "\nInvalid reduced res level: " << reduced_res_level << "\nHighest reduced res level available: " << highestReducedResSet() << std::endl; return 0; } return theNumberOfSamples[reduced_res_level]; } //*************************************************************************** // Public Method: //*************************************************************************** ossim_uint32 ossimCcfHead::chunksInLineDir(ossim_uint32 reduced_res_level) const { static const char MODULE[] = "ossimCcfHead::chunksInLineDir"; if (reduced_res_level > highestReducedResSet() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR!" << "\nInvalid reduced res level: " << reduced_res_level << "\nHighest reduced res level available: " << highestReducedResSet() << std::endl; return 0; } return theChunksInLineDir[reduced_res_level]; } //*************************************************************************** // Public Method: //*************************************************************************** ossim_uint32 ossimCcfHead::chunksInSampleDir(ossim_uint32 reduced_res_level) const { static const char MODULE[] = "ossimCcfHead::chunksInSampleDir"; if (reduced_res_level > highestReducedResSet() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR!" << "\nInvalid reduced res level: " << reduced_res_level << "\nHighest reduced res level available: " << highestReducedResSet() << std::endl; return 0; } return theChunksInSampleDir[reduced_res_level]; } //*************************************************************************** // Public Method: //*************************************************************************** std::streampos ossimCcfHead::startOfData(ossim_uint32 reduced_res_level) const { static const char MODULE[] = "ossimCcfHead::startOfData"; if (reduced_res_level > highestReducedResSet() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR!" << "\nInvalid reduced res level: " << reduced_res_level << "\nHighest reduced res level available: " << highestReducedResSet() << std::endl; return 0; } return theStartOfData[reduced_res_level]; } //*************************************************************************** // Public Method: //*************************************************************************** ossimIrect ossimCcfHead::imageRect(ossim_uint32 reduced_res_level) const { static const char MODULE[] = "ossimCcfHead::imageRect"; if (reduced_res_level > highestReducedResSet() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR!" << "\nInvalid reduced res level: " << reduced_res_level << "\nHighest reduced res level available: " << highestReducedResSet() << std::endl; return ossimIrect(0,0,0,0); } return ossimIrect(0, 0, numberOfSamples(reduced_res_level) - 1, numberOfLines(reduced_res_level) - 1); } //*************************************************************************** // Public Method: //*************************************************************************** void ossimCcfHead::parseRadString() { static const char MODULE[] = "ossimCcfHead::parseRadString"; if (theRadiometryString.contains("RadiomNBand")) { //*** // Complex string, must parse. Should look like: // "RadiomNBand (3 3 Linear8 )" //*** char tmp[80]; std::istringstream is(theRadiometryString); is >> tmp; // Skip the "RadiomNBand" string. is.get(tmp, 3); // Eat the space and the '('. is >> theNumberOfBands; // Get the number of bands. } if (theRadiometryString.contains("8")) { thePixelType = OSSIM_UCHAR; } else if(theRadiometryString.contains("16")) { thePixelType = OSSIM_USHORT16; } else if (theRadiometryString.contains("11")) { thePixelType = OSSIM_USHORT11; } else if (theRadiometryString.contains("12")) { thePixelType = OSSIM_USHORT12; } else if (theRadiometryString.contains("13")) { thePixelType = OSSIM_USHORT13; } else if (theRadiometryString.contains("14")) { thePixelType = OSSIM_USHORT14; } else if (theRadiometryString.contains("15")) { thePixelType = OSSIM_USHORT15; } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Unknown radiometry!" << "\ntheRadiometryString: " << theRadiometryString << std::endl; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "\ntheRadiometryString: " << theRadiometryString << "\ntheNumberOfBands: " << theNumberOfBands << "\nthePixelType: " << (ossimScalarTypeLut::instance()->getEntryString(thePixelType)) << "\n"; } } ossim-Miami-2.9.1/src/imaging/ossimCcfTileSource.cpp000066400000000000000000000732011352751253100223710ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class definition for ossimCcfTileSource. //******************************************************************* // $Id: ossimCcfTileSource.cpp 17195 2010-04-23 17:32:18Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimCcfTileSource, "ossimCcfTileSource", ossimImageHandler); //*** // Define Trace flags for use within this file: //*** static ossimTrace traceExec ("ossimCcfTileSource:exec"); static ossimTrace traceDebug ("ossimCcfTileSource:debug"); // For interleave type enum to string conversions. static const ossimInterleaveTypeLut ILUT; ossimCcfTileSource::ossimCcfTileSource() : ossimImageHandler(), theCcfHead(), theTile(NULL), theChipBuffer(NULL), theFileStr(NULL), theOutputBandList(1), theByteOrder(ossim::byteOrder()) {} ossimCcfTileSource::~ossimCcfTileSource() { close(); } ossimRefPtr ossimCcfTileSource::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if (theTile.valid()) { // Image rectangle must be set prior to calling getTile. theTile->setImageRectangle(rect); if ( getTile( theTile.get(), resLevel ) == false ) { if (theTile->getDataObjectStatus() != OSSIM_NULL) { theTile->makeBlank(); } } } return theTile; } bool ossimCcfTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) ) { result->ref(); // Increment ref count. //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0. Method returns true on success, false // on error. //--- status = getOverviewTile(resLevel, result); if (!status) // Did not get an overview tile. { status = true; ossimIrect tile_rect = result->getImageRectangle(); ossimIrect image_rect = theCcfHead.imageRect(resLevel); //--- // See if any point of the requested tile is in the image. //--- if ( tile_rect.intersects(image_rect) ) { ossimIrect clip_rect = tile_rect.clipToRect(image_rect); if ( !tile_rect.completely_within(clip_rect) ) { // Start with a blank tile. result->makeBlank(); } // Load the tile buffer with data from the ccf. status = fillBuffer(tile_rect, clip_rect, image_rect, resLevel, result); if (status) { result->validate(); } } } result->unref(); // Decrement ref count. } return status; } //******************************************************************* // Private Method: //******************************************************************* bool ossimCcfTileSource::fillBuffer(const ossimIrect& tile_rect, const ossimIrect& clip_rect, const ossimIrect& image_rect, ossim_uint32 reduced_res_level, ossimImageData* tile) { bool status = false; //*** // Determine the pixel type and make the appropriate tiles. //*** switch (theCcfHead.pixelType()) { case OSSIM_UCHAR: status = fillUcharBuffer(tile_rect, clip_rect, image_rect, reduced_res_level, tile); break; case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: status = fillUshortBuffer(tile_rect, clip_rect, image_rect, reduced_res_level, tile); break; default: theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << "ossimCcfTileSource fillBuffer ERROR:" << "\nUnsupported pixel type!" << "\nBuffer not filled. Returning error." << endl; break; } return status; } //******************************************************************* // Private Method: //******************************************************************* bool ossimCcfTileSource::fillUcharBuffer(const ossimIrect& tile_rect, const ossimIrect& clip_rect, const ossimIrect& /* image_rect */, ossim_uint32 reduced_res_level, ossimImageData* tile) { if(!isOpen()) return false; const ossim_uint32 TILE_SIZE_PER_BAND = tile->getSizePerBand(); const ossim_uint32 CHIP_SIZE_PER_BAND = theCcfHead.chipSizePerBand(); const ossim_uint32 SAMPLES_PER_CHIP = theCcfHead.samplesPerChip(); const ossim_uint32 LINES_PER_CHIP = theCcfHead.linesPerChip(); const ossim_uint32 BYTES_PER_CHUNK = theCcfHead.bytesPerChunk(); const ossim_uint32 BYTES_PER_CHIP = theCcfHead.bytesPerChip(); const ossim_uint32 CHIPS_IN_SAMPLE_DIR = theCcfHead.sampleChipsPerChunk(); const ossim_uint32 CHIPS_IN_LINE_DIR = theCcfHead.lineChipsPerChunk(); const ossim_uint32 NUMBER_OF_INPUT_BANDS = theCcfHead.numberOfBands(); const ossim_uint32 CHUNKS_IN_SAMPLE_DIR = theCcfHead.chunksInSampleDir(reduced_res_level); const ossim_uint32 CHUNK_SIDE_SIZE = SAMPLES_PER_CHIP * CHIPS_IN_SAMPLE_DIR; const ossim_uint32 CHIP_OFFSET_TO_END = SAMPLES_PER_CHIP - 1; //*** // Shift the upper left corner of the "clip_rect" to the an even chunk // boundry. //*** ossimIpt chunkOrigin = clip_rect.ul(); adjustToStartOfChunk(chunkOrigin); //*** // Calculate the number of chunks needed in the line/sample directions. //*** ossim_uint32 size_in_x = static_cast(clip_rect.lr().x - chunkOrigin.x + 1); ossim_uint32 size_in_y = static_cast(clip_rect.lr().y - chunkOrigin.y + 1); ossim_uint32 w = (CHIPS_IN_SAMPLE_DIR*SAMPLES_PER_CHIP); ossim_uint32 h = (CHIPS_IN_LINE_DIR*LINES_PER_CHIP); ossim_uint32 chunks_in_x_dir = size_in_x / w + (size_in_x % w ? 1 : 0); ossim_uint32 chunks_in_y_dir = size_in_y / h + (size_in_y % h ? 1 : 0); //*** // Get the start of data for the "reduced_res_level" passed in. //*** streampos startOfData = theCcfHead.startOfData(reduced_res_level); ossimIpt ulChunkPt = chunkOrigin; // Chunk loop in line direction. for (ossim_uint32 y=0; yseekg(seek_position, ios::beg); //*** // Read the chip from the ccf file into the chip buffer. // This will get all the bands. Bands are interleaved by // chip. //*** if (!theFileStr->read((char*)theChipBuffer, BYTES_PER_CHIP)) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; cerr << "ossimCcfTileSource fillUchBuffer READ ERROR!" << "\nReturning from method." << endl; return false; } ossimIrect chip_clip_rect = clip_rect.clipToRect(chip_rect); //*** // Band loop in sample direction. Bands are interleaved by // chip. //*** for (ossim_uint32 band=0; bandgetBuf() + band * TILE_SIZE_PER_BAND + (chip_clip_rect.ul().y - tile_rect.ul().y) * tile->getWidth() + chip_clip_rect.ul().x - tile_rect.ul().x; // Line loop through a chip. for (ossim_int32 chip_line = chip_clip_rect.ul().y; chip_line <= chip_clip_rect.lr().y; chip_line++) { // Sample loop through a chip. ossim_uint32 i=0; for (ossim_int32 chip_sample = chip_clip_rect.ul().x; chip_sample <= chip_clip_rect.lr().x; chip_sample++) { d[i] = s[i]; i++; } // Increment the pointers by one line. s += SAMPLES_PER_CHIP; d += tile->getWidth(); } } // End of band loop. } // End of if (chip_rect.intersects(clip_rect)) chip_pt.x += SAMPLES_PER_CHIP; } // End of chip loop in the sample direction. chip_pt.y += LINES_PER_CHIP; } // End of chip loop in the line direction. ulChunkPt.x += CHUNK_SIDE_SIZE; } // End of chunk loop in the sample direction. ulChunkPt.y += CHUNK_SIDE_SIZE; } // End of chunk loop in the line direction. return true; } //******************************************************************* // Private Method: //******************************************************************* bool ossimCcfTileSource::fillUshortBuffer(const ossimIrect& tile_rect, const ossimIrect& clip_rect, const ossimIrect& /* image_rect */, ossim_uint32 reduced_res_level, ossimImageData* tile) { const ossim_uint32 TILE_SIZE_PER_BAND = tile->getSizePerBand(); const ossim_uint32 CHIP_SIZE_PER_BAND = theCcfHead.chipSizePerBand(); const ossim_uint32 SAMPLES_PER_CHIP = theCcfHead.samplesPerChip(); const ossim_uint32 LINES_PER_CHIP = theCcfHead.linesPerChip(); const ossim_uint32 BYTES_PER_CHUNK = theCcfHead.bytesPerChunk(); const ossim_uint32 BYTES_PER_CHIP = theCcfHead.bytesPerChip(); const ossim_uint32 CHIPS_IN_SAMPLE_DIR = theCcfHead.sampleChipsPerChunk(); const ossim_uint32 CHIPS_IN_LINE_DIR = theCcfHead.lineChipsPerChunk(); const ossim_uint32 NUMBER_OF_INPUT_BANDS = theCcfHead.numberOfBands(); const ossim_uint32 CHUNKS_IN_SAMPLE_DIR = theCcfHead. chunksInSampleDir(reduced_res_level); const ossim_uint32 CHUNK_SIDE_SIZE = SAMPLES_PER_CHIP * CHIPS_IN_SAMPLE_DIR; const ossim_uint32 CHIP_OFFSET_TO_END = SAMPLES_PER_CHIP - 1; //*** // Shift the upper left corner of the "clip_rect" to the an even chunk // boundry. //*** ossimIpt chunkOrigin = clip_rect.ul(); adjustToStartOfChunk(chunkOrigin); //*** // Calculate the number of chunks needed in the line/sample directions. //*** ossim_uint32 size_in_x = clip_rect.lr().x - chunkOrigin.x + 1; ossim_uint32 size_in_y = clip_rect.lr().y - chunkOrigin.y + 1; ossim_uint32 w = (CHIPS_IN_SAMPLE_DIR*SAMPLES_PER_CHIP); ossim_uint32 h = (CHIPS_IN_LINE_DIR*LINES_PER_CHIP); ossim_uint32 chunks_in_x_dir = size_in_x / w + (size_in_x % w ? 1 : 0); ossim_uint32 chunks_in_y_dir = size_in_y / h + (size_in_y % h ? 1 : 0); //*** // Get the start of data for the "reduced_res_level" passed in. //*** streampos startOfData = theCcfHead.startOfData(reduced_res_level); ossimIpt ulChunkPt = chunkOrigin; // Chunk loop in line direction. for (ossim_uint32 y=0; yseekg(seek_position, ios::beg); //*** // Read the chip from the ccf file into the chip buffer. // This will get all the bands. Bands are interleaved by // chip. //*** if (!theFileStr->read((char*)theChipBuffer, BYTES_PER_CHIP)) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; cerr << "ossimCcfTileSource fillUshortBuffer READ ERROR!" << "Returning from method." << endl; return false; } ossimIrect chip_clip_rect = clip_rect.clipToRect(chip_rect); //*** // Band loop in sample direction. Bands are interleaved by // chip. //*** for (ossim_uint32 band=0; bandgetBuf() + band * TILE_SIZE_PER_BAND + (chip_clip_rect.ul().y - tile_rect.ul().y) * tile->getWidth() + chip_clip_rect.ul().x - tile_rect.ul().x; // Line loop through a chip. for (ossim_int32 chip_line = chip_clip_rect.ul().y; chip_line <= chip_clip_rect.lr().y; ++chip_line) { // Sample loop through a chip. ossim_uint32 i=0; for (ossim_int32 chip_sample = chip_clip_rect.ul().x; chip_sample <= chip_clip_rect.lr().x; ++chip_sample) { if (theByteOrder == OSSIM_LITTLE_ENDIAN) { //*** // CCF data alway stored in big endian byte // order so swap the bytes. //*** d[i] = (s[i] << 8) | (s[i] >> 8); } else { d[i] = s[i]; } ++i; } // Increment the pointers by one line. s += SAMPLES_PER_CHIP; d += tile->getWidth(); } } // End of band loop. } // End of if (chip_rect.intersects(clip_rect)) chip_pt.x += SAMPLES_PER_CHIP; } // End of chip loop in the sample direction. chip_pt.y += LINES_PER_CHIP; } // End of chip loop in the line direction. ulChunkPt.x += CHUNK_SIDE_SIZE; } // End of chunk loop in the sample direction. ulChunkPt.y += CHUNK_SIDE_SIZE; } // End of chunk loop in the line direction. return true; } //******************************************************************* // Public Method: //******************************************************************* ossimIrect ossimCcfTileSource::getImageRectangle(ossim_uint32 reduced_res_level) const { return theCcfHead.imageRect(reduced_res_level); } //******************************************************************* // Public Method: //******************************************************************* bool ossimCcfTileSource::setOutputBandList(const vector& outputBandList) { static const char MODULE[] = "ossimCcfTileSource::setOutputBandList"; if (traceExec()) CLOG << "entering..." << endl; if (outputBandList.size() != theOutputBandList.size()) { //*** // Verify that each individual band does not bust the range of input // bands. //*** for (ossim_uint32 i=0; i (getNumberOfInputBands() - 1)) { setErrorStatus(); cerr << MODULE << " ERROR:" << "\nOutput band number in list is greater than the " << "number of bands in the image source!" << "\noutputBandList[" << i << "]: " << "\nHighest available band: " << (getNumberOfInputBands() - 1) << "\nError status has been set! Returning..." << endl; return false; } } // Remove the old tiles and reallocate with the new size. theTile = NULL; } theOutputBandList = outputBandList; // Assign the new list. if (traceExec()) CLOG << "returning..." << endl; return true; } //******************************************************************* // Public method: //******************************************************************* bool ossimCcfTileSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Currently nothing to do here. return ossimImageHandler::saveState(kwl, prefix); } //******************************************************************* // Public method: //******************************************************************* bool ossimCcfTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (ossimImageHandler::loadState(kwl, prefix)) { if (open()) { return true; } } return false; } //******************************************************************* // Public method: //******************************************************************* bool ossimCcfTileSource::open() { static const char MODULE[] = "ossimCcfTileSource::open"; if (traceExec()) CLOG << "entering..." << endl; if(isOpen()) { close(); } if (traceDebug()) { CLOG << "DEBUG -- " << "\n\t theImageFile: " << theImageFile << endl; } if (theCcfHead.parseCcfHeader(theImageFile.c_str()) == false) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; if (traceExec()) CLOG << "returning with error..." << endl; return false; } if (traceDebug()) { CLOG << "DEBUG -- " << "\n\t theImageFile: " << theImageFile << "\n\t theCcfHead: " << theCcfHead << endl; } theFileStr = new std::ifstream; // Open up the file for reading. theFileStr->open(theImageFile.c_str(), ios::in | ios::binary); if (!(*theFileStr)) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; cerr << MODULE << " ERROR!" << "\nCould not open file: " << theImageFile.c_str() << "\nReturning..." << endl; if (traceExec()) CLOG << "returning with error..." << endl; delete theFileStr; theFileStr = NULL; return false; } theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); theChipBuffer = new ossim_uint8[theCcfHead.bytesPerChip()]; // Initialize the output band list. if (getNumberOfInputBands() > theOutputBandList.size()) { theOutputBandList.resize(getNumberOfInputBands()); } for (ossim_uint32 i=0; iclose(); theFileStr->clear(); delete theFileStr; theFileStr = NULL; } } //******************************************************************* // Public method: //******************************************************************* ossimScalarType ossimCcfTileSource::getOutputScalarType() const { return theCcfHead.pixelType(); } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimCcfTileSource::getTileWidth() const { return ( theTile.valid() ? theTile->getWidth() : 0 ); } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimCcfTileSource::getTileHeight() const { return ( theTile.valid() ? theTile->getHeight() : 0 ); } ossim_uint32 ossimCcfTileSource::getImageTileWidth() const { return 32; } ossim_uint32 ossimCcfTileSource::getImageTileHeight() const { return 32; } void ossimCcfTileSource::initVerticesFromHeader() { theValidImageVertices.clear(); const vector& validImageVertices = theCcfHead.getValidImageVertices(); ossim_uint32 upper = (ossim_uint32)validImageVertices.size(); if(!upper) return; for(ossim_uint32 index = 0; index < upper; ++index) { theValidImageVertices.push_back(validImageVertices[index]); } if (traceDebug()) { cout << "ossimCcfTileSource::initVerticesFromHeader DEBUG:" << "\nValid image vertices:" << endl; for (ossim_uint32 i=0; i ossimCcfTileSource::getProperty(const ossimString& name)const { if(name == "file_type") { return new ossimStringProperty(name, "CCF"); } return ossimImageHandler::getProperty(name); } void ossimCcfTileSource::getPropertyNames(std::vector& propertyNames)const { ossimImageHandler::getPropertyNames(propertyNames); propertyNames.push_back("file_type"); } void ossimCcfTileSource::adjustToStartOfChunk(ossimIpt& pt) const { pt.x &= 0xffffff00; pt.y &= 0xffffff00; } void ossimCcfTileSource::adjustToStartOfChip(ossimIpt& pt) const { pt.x &= 0xffffffe0; pt.y &= 0xffffffe0; } ossim-Miami-2.9.1/src/imaging/ossimCibCadrgTileSource.cpp000066400000000000000000001170121352751253100233330ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimCibCadrgTileSource.cpp 23021 2014-12-04 20:57:16Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug = ossimTrace("ossimCibCadrgTileSource:debug"); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimCibCadrgTileSource.cpp 23021 2014-12-04 20:57:16Z dburken $"; #endif RTTI_DEF1(ossimCibCadrgTileSource, "ossimCibCadrgTileSource", ossimImageHandler) const ossim_uint32 ossimCibCadrgTileSource::CIBCADRG_FRAME_WIDTH = 1536; const ossim_uint32 ossimCibCadrgTileSource::CIBCADRG_FRAME_HEIGHT = 1536; using namespace std; ossimCibCadrgTileSource::ossimCibCadrgTileSource() :ossimImageHandler(), theCompressedBuffer(0), theUncompressedBuffer(0), theNumberOfLines(0), theNumberOfSamples(0), theTile(0), theTableOfContents(0), theEntryToRender(0), theEntryNumberToRender(1), theProductType(OSSIM_PRODUCT_TYPE_UNKNOWN), theWorkFrame(0), theSkipEmptyCheck(false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimCibCadrgTileSource::ossimCibCadrgTileSource entered...\n"; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << "\n"; #endif } // Moved memory allocation to happen in first get tile. drb // theWorkFrame = new ossimRpfFrame; // a CADRG and CIBis a 64*64*12 bit buffer and must divide by 8 to // convert to bytes // theCompressedBuffer = new ossim_uint8[(64*64*12)/8]; // whether CIB or CADRG we will alocate the buffer // to the larger of the 2 (CADRG is 3 bands) // theUncompressedBuffer = new ossim_uint8[256*256*3]; } ossimCibCadrgTileSource::~ossimCibCadrgTileSource() { if(theCompressedBuffer) { delete [] theCompressedBuffer; theCompressedBuffer = 0; } if(theUncompressedBuffer) { delete [] theUncompressedBuffer; theUncompressedBuffer = 0; } if(theWorkFrame) { delete theWorkFrame; theWorkFrame = 0; } close(); } ossimString ossimCibCadrgTileSource::getShortName()const { return ossimString("CIB/CADRG"); } ossimString ossimCibCadrgTileSource::getLongName()const { return ossimString("CIB/CADRG reader"); } void ossimCibCadrgTileSource::close() { deleteAll(); ossimImageHandler::close(); } bool ossimCibCadrgTileSource::isOpen()const { return (theTableOfContents!=0); } bool ossimCibCadrgTileSource::open() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimCibCadrgTileSource::open(): Entered....." << "\ntheImageFile: " << theImageFile << std::endl; } bool result = false; if(isOpen()) { close(); } theTableOfContents = new ossimRpfToc; if(theTableOfContents) { if(theTableOfContents->parseFile(theImageFile) == ossimErrorCodes::OSSIM_OK) { if(theTableOfContents->getNumberOfEntries() > 0) { vector scaleList = getProductScaleList(); if(scaleList.size() > 0) { std::vector entryList; getEntryList(entryList); if(entryList.size() > 0) { setCurrentEntry(entryList[0]); if(theEntryToRender) { // a CADRG is 1536x1536 per frame. theNumberOfLines = theEntryToRender->getNumberOfLines(); theNumberOfSamples = theEntryToRender->getNumberOfSamples(); } if(theEntryToRender->getProductType().trim().upcase() == "CADRG") { theProductType = OSSIM_PRODUCT_TYPE_CADRG; result = true; } else if(theEntryToRender->getProductType().trim().upcase() == "CIB") { theProductType = OSSIM_PRODUCT_TYPE_CIB; result = true; } // Moved this code to be called on first get tile. drb // if ( result ) // { // This initializes tiles and buffers. // allocateForProduct(); // } } } } } } if(!result) { theImageFile.clear(); close(); } #if 0 /* 20100414 - drb */ else { //--- // Adjust image rect so not to go over the -180 to 180 and -90 to 90 // bounds. //--- // Note this did not do any boundary checking and was in conflict with setTocEntryToRender // method calculation of lines and samps. // setActualImageRect(); std::ifstream in(theImageFile.c_str(), std::ios::in|std::ios::binary); if(in.good()&&theTableOfContents->getRpfHeader()) { } completeOpen(); theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); } #endif if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimCibCadrgTileSource::open(): Leaving at line " << __LINE__ << " result=" << (result?"true":"false") << std::endl; } return result; } void ossimCibCadrgTileSource::setSkipEmptyCheck( bool bSkipEmptyCheck ) { theSkipEmptyCheck = bSkipEmptyCheck; } ossimRefPtr ossimCibCadrgTileSource::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if ( theTile.valid() == false ) { // First time through. allocateForProduct(); } if (theTile.valid()) { // Image rectangle must be set prior to calling getTile. theTile->setImageRectangle(rect); if ( getTile( theTile.get(), resLevel ) == false ) { if (theTile->getDataObjectStatus() != OSSIM_NULL) { theTile->makeBlank(); } } } return theTile; } bool ossimCibCadrgTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) && (theProductType != OSSIM_PRODUCT_TYPE_UNKNOWN) ) { if ( resLevel > 0 ) { //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0 (if overview is not virtual). Method // returns true on success, false on error. //--- status = getOverviewTile(resLevel, result); } if (!status) // Did not get an overview tile. { if ( !theCompressedBuffer ) { // First time through. allocateForProduct(); } if ( theCompressedBuffer ) { status = true; ossimIrect rect = result->getImageRectangle(); ossimIrect imageRect = getImageRectangle(); if ( rect.intersects(imageRect) ) { //--- // Start with a blank tile in case there is not total coverage // for rect. //--- result->makeBlank(); vector frames = getIntersectingEntries(rect); if(frames.size() > 0) { //--- // Now lets render each frame. Note we will have to find // subframes // that intersect the rectangle of interest for each frame. //--- fillTile(rect, frames, result); // Revalidate tile status. result->validate(); } } else { result->makeBlank(); } } } } return status; } ossim_uint32 ossimCibCadrgTileSource::getNumberOfInputBands()const { switch(theProductType) { case OSSIM_PRODUCT_TYPE_UNKNOWN: { return 0; } case OSSIM_PRODUCT_TYPE_CIB: { return 1; } case OSSIM_PRODUCT_TYPE_CADRG: { return 3; } } return 0; } ossim_uint32 ossimCibCadrgTileSource::getNumberOfOutputBands()const { switch(theProductType) { case OSSIM_PRODUCT_TYPE_UNKNOWN: { return 0; } case OSSIM_PRODUCT_TYPE_CIB: { return 1; } case OSSIM_PRODUCT_TYPE_CADRG: { return 3; } } return 0; } ossim_uint32 ossimCibCadrgTileSource::getNumberOfLines(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return theNumberOfLines; } else if (theOverview.valid()) { return theOverview->getNumberOfLines(reduced_res_level); } return 0; } ossim_uint32 ossimCibCadrgTileSource::getNumberOfSamples(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return theNumberOfSamples; } else if (theOverview.valid()) { return theOverview->getNumberOfSamples(reduced_res_level); } return 0; } ossimIrect ossimCibCadrgTileSource::getImageRectangle(ossim_uint32 reduced_res_level) const { return ossimIrect(0, // upper left x 0, // upper left y getNumberOfSamples(reduced_res_level) - 1, // lower right x getNumberOfLines(reduced_res_level) - 1); // lower right y } ossimRefPtr ossimCibCadrgTileSource::getImageGeometry() { if ( !theGeometry ) { // Check for external geom: theGeometry = getExternalImageGeometry(); if ( !theGeometry && theEntryToRender ) { theGeometry = theEntryToRender->getImageGeometry(); } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } return theGeometry; } ossimScalarType ossimCibCadrgTileSource::getOutputScalarType() const { return OSSIM_UCHAR; } ossim_uint32 ossimCibCadrgTileSource::getTileWidth() const { return getImageTileWidth(); } ossim_uint32 ossimCibCadrgTileSource::getTileHeight() const { return getImageTileHeight(); } ossim_uint32 ossimCibCadrgTileSource::getCurrentEntry()const { return (ossim_uint32)theEntryNumberToRender; } bool ossimCibCadrgTileSource::setCurrentEntry(ossim_uint32 entryIdx) { bool result = false; theDecimationFactors.clear(); // Clear the geometry. theGeometry = 0; // Must clear or openOverview will use last entries. theOverviewFile.clear(); if(setEntryToRender(entryIdx)) { completeOpen(); result = true; } return result; } void ossimCibCadrgTileSource::getEntryList(std::vector& entryList)const { std::vector scaleList = getProductScaleList(); ossim_uint32 scaleIdx = 0; ossim_uint32 entryIdx = 0; for(scaleIdx = 0; scaleIdx < scaleList.size(); ++scaleIdx) { std::vector eList = getProductEntryList(scaleList[scaleIdx]); for(entryIdx = 0; entryIdx < eList.size(); ++entryIdx) { entryList.push_back(eList[entryIdx]); } } } bool ossimCibCadrgTileSource::setEntryToRender(ossim_uint32 index) { if(isOpen()) { const ossimRpfTocEntry *temp = theTableOfContents->getTocEntry(index); if(temp) { if(!(temp->getBoundaryInformation().getCoverage().isGeographicRectNull())) { setTocEntryToRender(temp); theEntryNumberToRender = index; if(theEntryToRender) { if(theEntryToRender->getProductType().trim().upcase() == "CADRG") { theProductType = OSSIM_PRODUCT_TYPE_CADRG; } else if(theEntryToRender->getProductType().trim().upcase() == "CIB") { theProductType = OSSIM_PRODUCT_TYPE_CIB; } else { theProductType = OSSIM_PRODUCT_TYPE_UNKNOWN; } } populateLut(); return true; } } } return false; } void ossimCibCadrgTileSource::setTocEntryToRender(const ossimRpfTocEntry* entry) { if(isOpen()&&entry) { theEntryToRender = entry; theNumberOfLines = theEntryToRender->getNumberOfLines(); theNumberOfSamples = theEntryToRender->getNumberOfSamples(); theEntryNumberToRender = theTableOfContents->getTocEntryIndex(entry); } } ossim_int32 ossimCibCadrgTileSource::getCurrentEntryIndex()const { return theEntryNumberToRender; } const ossimRpfTocEntry* ossimCibCadrgTileSource::getCurrentTocEntry()const { return theEntryToRender; } const ossimRpfToc* ossimCibCadrgTileSource::getToc()const { return theTableOfContents; } bool ossimCibCadrgTileSource::isValidRLevel(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return true; } else if (theOverview.valid()) { return theOverview->isValidRLevel(reduced_res_level); } else { return false; } } vector ossimCibCadrgTileSource::getProductScaleList()const { vector result; if(isOpen()) { ossim_int32 upperBound = theTableOfContents->getNumberOfEntries(); for(ossim_int32 index = 0; index < upperBound; ++index) { const ossimRpfTocEntry* entry = theTableOfContents->getTocEntry(index); ossimString scale = entry->getBoundaryInformation().getScale(); scale = scale.trim().upcase(); if(scale!="") { // CIB will have product scales like 5M or 10M // and CADRG's will have product scales like // 1:50K and 1:250K ... // So if these patterns exist then add it to // the product list. if( ( std::find(scale.begin(), scale.end(), ':') != scale.end() ) || (scale[scale.size()-1]=='M')) { // only add it if it doesn't already exist // on the list. if(find(result.begin(), result.end(), scale) == result.end()) { result.push_back(scale); } } } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimCibCadrgTileSource::getProductScaleList DEBUG:" << endl; std::vector::const_iterator i = result.begin(); ossim_uint32 index = 0; while (i != result.end()) { ossimNotify(ossimNotifyLevel_DEBUG) << "scale[" << index << "]: " << (*i) << endl; ++index; ++i; } } return result; } vector ossimCibCadrgTileSource::getProductEntryList(const ossimString& productScale)const { vector result; if(isOpen()) { ossim_int32 upperBound = theTableOfContents->getNumberOfEntries(); for(ossim_int32 index = 0; index < upperBound; ++index) { const ossimRpfTocEntry* entry = theTableOfContents->getTocEntry(index); if(entry) { // If the "skip empty check" is true, we don't check to see if the // actual frame images exist. Otherwise the check is carried out, // which is the default situation. bool bIsEmpty = (theSkipEmptyCheck==false) ? entry->isEmpty() : false; // if the entry is not empty then add it to the list. if( bIsEmpty == false ) { ossimString scale = entry->getBoundaryInformation().getScale(); scale = scale.trim().upcase(); if(scale==productScale) { result.push_back(index); } } } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimCibCadrgTileSource::getProductEntryList DEBUG:" << endl; std::vector::const_iterator i = result.begin(); ossim_uint32 index = 0; while (i != result.end()) { ossimNotify(ossimNotifyLevel_DEBUG) << "scale[" << index << "]: " << (*i) << endl; ++index; ++i; } } return result; } vector ossimCibCadrgTileSource::getIntersectingEntries(const ossimIrect& rect) { vector result; // make sure we have the Toc entry to render if(!isOpen()) return result; ossimIrect imageRect = getImageRectangle(); if(rect.intersects(imageRect)) { ossimIrect clipRect = rect.clipToRect(imageRect); ossimIrect frameRect(clipRect.ul().x/CIBCADRG_FRAME_WIDTH, clipRect.ul().y/CIBCADRG_FRAME_HEIGHT, clipRect.lr().x/CIBCADRG_FRAME_WIDTH, clipRect.lr().y/CIBCADRG_FRAME_HEIGHT); ossimRpfFrameEntry tempEntry; for(ossim_int32 row = frameRect.ul().y; row <= frameRect.lr().y; ++row) { for(ossim_int32 col = frameRect.ul().x; col <= frameRect.lr().x; ++col) { if(theEntryToRender->getEntry((theEntryToRender->getNumberOfFramesVertical()-1) - row, col, tempEntry)) { if(tempEntry.exists()) { result.push_back(ossimFrameEntryData(row, col, row*CIBCADRG_FRAME_HEIGHT, col*CIBCADRG_FRAME_WIDTH, tempEntry)); } } } } } return result; } void ossimCibCadrgTileSource::fillTile( const ossimIrect& tileRect, const vector& framesInvolved, ossimImageData* tile) { ossim_uint32 idx = 0; for(idx = 0; idx < framesInvolved.size(); ++idx) { if(theWorkFrame->parseFile(framesInvolved[idx].theFrameEntry.getFullPath()) == ossimErrorCodes::OSSIM_OK) { // we will fill a subtile. We pass in which frame it is and the position of the frame. // the actual pixel will be 1536*row and 1536 *col. if(theProductType == OSSIM_PRODUCT_TYPE_CIB) { fillSubTileCib(*theWorkFrame, tileRect, framesInvolved[idx], tile); } else { fillSubTileCadrg(*theWorkFrame, tileRect, framesInvolved[idx], tile); } } } } void ossimCibCadrgTileSource::fillSubTileCadrg( const ossimRpfFrame& aFrame, const ossimIrect& tileRect, const ossimFrameEntryData& frameEntryData, ossimImageData* tile) { // first let's grab the absolute position of the frame rectangle in pixel space ossimIrect frameRect(frameEntryData.thePixelCol, frameEntryData.thePixelRow, frameEntryData.thePixelCol + CIBCADRG_FRAME_WIDTH - 1, frameEntryData.thePixelRow + CIBCADRG_FRAME_HEIGHT - 1); // now clip it to the tile ossimIrect clipRect = tileRect.clipToRect(frameRect); const ossimRpfCompressionSection* compressionSection = aFrame.getCompressionSection(); if(!compressionSection) { return; } const vector& colorTable = aFrame.getColorGrayscaleTable(); // ESH 03/2009 -- Partial fix for ticket #646. // Crash fix on reading RPFs: Make sure the colorTable vector // has entries before trying to make use of them. int numTables = (int)colorTable.size(); if ( numTables <= 0 ) { return; } ossim_uint8 *tempRows[3]; tempRows[0] = theUncompressedBuffer; tempRows[1] = (theUncompressedBuffer + 256*256); tempRows[2] = (tempRows[1] + 256*256); // find the shift to 0,0 ossimIpt tempDelta(clipRect.ul().x - frameEntryData.thePixelCol, clipRect.ul().y - frameEntryData.thePixelRow); // In order to compute the subframe we will need the corner offsets of // the upper left of the frame and the upper left of the clip rect. The // clip rect should be completely within the frame. This just translates the value // to make the upper left of the frame be 0,0. // ossimIrect offsetRect(tempDelta.x, tempDelta.y, tempDelta.x + clipRect.width()-1, tempDelta.y + clipRect.height()-1); // each subframe is 64x64. We will actually use 256x256 since // we will be uncompressing them. Note CADRG is a 256x256 tile // compressed to 64x64x12 bit data // ossimIrect subFrameRect(offsetRect.ul().x/256, offsetRect.ul().y/256, (offsetRect.lr().x)/256, (offsetRect.lr().y)/256); ossim_uint32 readPtr = 0; ossim_int32 row = 0; ossim_int32 col = 0; ossim_uint32 i = 0; ossim_uint32 j = 0; ossim_int32 upperY = subFrameRect.lr().y; ossim_int32 upperX = subFrameRect.lr().x; ossim_int32 lowerY = subFrameRect.ul().y; ossim_int32 lowerX = subFrameRect.ul().x; for(row = lowerY; row <= upperY; ++row) { for(col = lowerX; col <= upperX; ++col) { readPtr = 0; if(aFrame.fillSubFrameBuffer(theCompressedBuffer, 0, row, col)) { for (i = 0; i < 256; i += 4) { for (j = 0; j < 256; j += 8) { ossim_uint16 firstByte = theCompressedBuffer[readPtr++] & 0xff; ossim_uint16 secondByte = theCompressedBuffer[readPtr++] & 0xff; ossim_uint16 thirdByte = theCompressedBuffer[readPtr++] & 0xff; //because dealing with half-bytes is hard, we //uncompress two 4x4 tiles at the same time. (a //4x4 tile compressed is 12 bits ) // this little code was grabbed from openmap software. /* Get first 12-bit value as index into VQ table */ // I think we need to swap ossim_uint16 val1 = (firstByte << 4) | (secondByte >> 4); /* Get second 12-bit value as index into VQ table*/ ossim_uint16 val2 = ((secondByte & 0x000F) << 8) | thirdByte; for (ossim_uint32 t = 0; t < 4; ++t) { for (ossim_uint32 e = 0; e < 4; ++e) { ossim_uint16 tableVal1 = compressionSection->getTable()[t].theData[val1*4 + e] & 0xff; ossim_uint16 tableVal2 = compressionSection->getTable()[t].theData[val2*4 + e] & 0xff; ossim_uint32 pixindex = ((i+t)*256) + (j + e); const ossim_uint8* color1 = colorTable[0].getStartOfData(tableVal1); const ossim_uint8* color2 = colorTable[0].getStartOfData(tableVal2); tempRows[0][pixindex] = color1[0]; tempRows[1][pixindex] = color1[1]; tempRows[2][pixindex] = color1[2]; tempRows[0][pixindex+4] = color2[0]; tempRows[1][pixindex+4] = color2[1]; tempRows[2][pixindex+4] = color2[2]; } //for e } //for t } /* for j */ } //for i } else { memset(theUncompressedBuffer, 0, 256*256*3); } ossim_int32 tempCol = col*256; ossim_int32 tempRow = row*256; ossimIrect subRectToFill(frameRect.ul().x + tempCol, frameRect.ul().y + tempRow, frameRect.ul().x + tempCol + 255, frameRect.ul().y + tempRow + 255); tile->loadTile(theUncompressedBuffer, subRectToFill, OSSIM_BSQ); } } } void ossimCibCadrgTileSource::fillSubTileCib( const ossimRpfFrame& aFrame, const ossimIrect& tileRect, const ossimFrameEntryData& frameEntryData, ossimImageData* tile) { // first let's grab the absolute position of the frame rectangle in pixel // space ossimIrect frameRect(frameEntryData.thePixelCol, frameEntryData.thePixelRow, frameEntryData.thePixelCol + CIBCADRG_FRAME_WIDTH - 1, frameEntryData.thePixelRow + CIBCADRG_FRAME_HEIGHT - 1); // now clip it to the tile ossimIrect clipRect = tileRect.clipToRect(frameRect); const ossimRpfCompressionSection* compressionSection = aFrame.getCompressionSection(); if(!compressionSection) { return; } const vector& colorTable = aFrame.getColorGrayscaleTable(); // ESH 03/2009 -- Partial fix for ticket #646. // Crash fix on reading RPFs: Make sure the colorTable vector // has entries before trying to make use of them. int numTables = (int)colorTable.size(); if ( numTables <= 0 ) { return; } // check to see if it does overlap. If it doesn't then the width and height // will be a single point { ossim_uint8 *tempRow; tempRow = theUncompressedBuffer; // find the shift to 0,0 ossimIpt tempDelta(clipRect.ul().x - frameEntryData.thePixelCol, clipRect.ul().y - frameEntryData.thePixelRow); // In order to compute the subframe we will need the corner offsets of // the upper left of the frame and the upper left of the clip rect. The // clip rect should be completely within the frame. This just translates the value // to make the upper left of the frame be 0,0. // ossimIrect offsetRect(tempDelta.x, tempDelta.y, tempDelta.x + clipRect.width()-1, tempDelta.y + clipRect.height()-1); // each subframe is 64x64. We will actually use 256x256 since // we will be uncompressing them. Note CADRG is a 256x256 tile // compressed to 64x64x12 bit data // ossimIrect subFrameRect(offsetRect.ul().x/256, offsetRect.ul().y/256, (offsetRect.lr().x)/256, (offsetRect.lr().y)/256); ossim_int32 row = 0; ossim_int32 col = 0; ossim_uint32 i = 0; ossim_uint32 j = 0; ossim_uint32 readPtr = 0; for(row = subFrameRect.ul().y; row <= subFrameRect.lr().y; ++row) { for(col = subFrameRect.ul().x; col <= subFrameRect.lr().x; ++col) { readPtr = 0; if(aFrame.fillSubFrameBuffer(theCompressedBuffer, 0, row, col)) { for (i = 0; i < 256; i += 4) { for (j = 0; j < 256; j += 8) { ossim_uint16 firstByte = theCompressedBuffer[readPtr++] & 0xff; ossim_uint16 secondByte = theCompressedBuffer[readPtr++] & 0xff; ossim_uint16 thirdByte = theCompressedBuffer[readPtr++] & 0xff; //because dealing with half-bytes is hard, we //uncompress two 4x4 tiles at the same time. (a //4x4 tile compressed is 12 bits ) // this little code was grabbed from openmap software. /* Get first 12-bit value as index into VQ table */ // I think we need to swap ossim_uint16 val1 = (firstByte << 4) | (secondByte >> 4); /* Get second 12-bit value as index into VQ table*/ ossim_uint16 val2 = ((secondByte & 0x000F) << 8) | thirdByte; for (ossim_uint32 t = 0; t < 4; ++t) { for (ossim_uint32 e = 0; e < 4; ++e) { ossim_uint16 tableVal1 = compressionSection->getTable()[t].theData[val1*4 + e] & 0xff; ossim_uint16 tableVal2 = compressionSection->getTable()[t].theData[val2*4 + e] & 0xff; ossim_uint32 pixindex = ((i+t)*256) + (j + e); const ossim_uint8* color1 = colorTable[0].getStartOfData(tableVal1); const ossim_uint8* color2 = colorTable[0].getStartOfData(tableVal2); tempRow[pixindex] = color1[0]; tempRow[pixindex + 4] = color2[0]; } //for e } //for t } /* for j */ } //for i } else { memset(theUncompressedBuffer, 0, 256*256); } ossim_int32 tCol = col*256; ossim_int32 tRow = row*256; ossimIrect subRectToFill(frameRect.ul().x + tCol, frameRect.ul().y + tRow, frameRect.ul().x + tCol + 255, frameRect.ul().y + tRow + 255); tile->loadTile(theUncompressedBuffer, subRectToFill, OSSIM_BSQ); } } } } void ossimCibCadrgTileSource::allocateForProduct() { if(theProductType == OSSIM_PRODUCT_TYPE_UNKNOWN) { return; } if ( theWorkFrame ) { delete theWorkFrame; } theWorkFrame = new ossimRpfFrame; if(theCompressedBuffer) { delete [] theCompressedBuffer; } //--- // A CADRG and CIBis a 64*64*12 bit buffer and must divide by 8 to convert // to bytes. //--- theCompressedBuffer = new ossim_uint8[(64*64*12)/8]; if(theUncompressedBuffer) { delete [] theUncompressedBuffer; } if(theProductType == OSSIM_PRODUCT_TYPE_CIB) { theUncompressedBuffer = new ossim_uint8[256*256]; } else { theUncompressedBuffer = new ossim_uint8[256*256*3]; } theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); } const ossimRpfTocEntry* ossimCibCadrgTileSource::findFirstFrame() { vector products = getProductScaleList(); vector indexProducts; if(products.size() > 0) { indexProducts = getProductEntryList(products[0]); if(indexProducts.size()>0) { theEntryNumberToRender = indexProducts[0]; return theTableOfContents->getTocEntry(indexProducts[0]); } } return 0; } void ossimCibCadrgTileSource::deleteAll() { theOverview = 0; if(theTableOfContents) { delete theTableOfContents; theTableOfContents = 0; } } bool ossimCibCadrgTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimImageHandler::saveState(kwl, prefix); kwl.add(prefix, "entry", theEntryNumberToRender, true); return result; } bool ossimCibCadrgTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* MODULE = "ossimCibCadrgTileSource::loadState"; if(traceDebug()) { CLOG << "Entering..." << endl; } bool result = ossimImageHandler::loadState(kwl, prefix); if(!result) { if(traceDebug()) { CLOG << "Leaving..." << endl; } return false; } const char* lookup = 0; lookup = kwl.find(ossimString(prefix), "entry"); ossim_int32 entry = ossimString(lookup).toInt32(); // if an entry is specified then // call the open with an entry number if(lookup) { if(traceDebug()) { CLOG << "Leaving..." << endl; } result = ossimImageHandler::open(theImageFile); setCurrentEntry(entry); return result; } result = ossimImageHandler::open(theImageFile); return result; } ossim_uint32 ossimCibCadrgTileSource::getImageTileWidth() const { return 256; // ??? drb } ossim_uint32 ossimCibCadrgTileSource::getImageTileHeight() const { return 256; // ??? drb } bool ossimCibCadrgTileSource::isCib() const { return (theProductType==OSSIM_PRODUCT_TYPE_CIB); } bool ossimCibCadrgTileSource::isCadrg() const { return (theProductType==OSSIM_PRODUCT_TYPE_CADRG); } ossimString ossimCibCadrgTileSource::getProductScale() const { ossimString result; const ossimRpfTocEntry* entry = theTableOfContents->getTocEntry(theEntryNumberToRender); if (entry) { result = entry->getBoundaryInformation().getScale(); } return result; } ossimString ossimCibCadrgTileSource::getSecurityClassification()const { ossimString result; const ossimRpfHeader* header = theTableOfContents->getRpfHeader(); if (header) { result = header->getSecurityClassification(); } return result; } ossimRefPtr ossimCibCadrgTileSource::getProperty(const ossimString& name)const { if(name == "file_type") { if(theProductType == OSSIM_PRODUCT_TYPE_CIB) { return new ossimStringProperty("file_type", "CIB"); } else if(theProductType == OSSIM_PRODUCT_TYPE_CADRG) { return new ossimStringProperty("file_type", "CADRG"); } return 0; } return ossimImageHandler::getProperty(name); } void ossimCibCadrgTileSource::getPropertyNames(std::vector& propertyNames)const { ossimImageHandler::getPropertyNames(propertyNames); propertyNames.push_back("file_type"); /** * This code is crashing and not sure why in here. Looks like a bad GeoEye * baseline merge. */ #if 0 const ossimRpfHeader* header = theTableOfContents->getRpfHeader(); if(header) { std::ifstream in(theImageFile.c_str(), std::ios::in|std::ios::binary); } #endif } void ossimCibCadrgTileSource::populateLut() { theLut = 0; if(theEntryToRender) { ossim_uint32 w = theEntryToRender->getNumberOfFramesHorizontal(); ossim_uint32 h = theEntryToRender->getNumberOfFramesVertical(); ossim_uint32 wi, hi; bool found = false; ossimRpfFrameEntry tempEntry; ossimRpfFrame aFrame; for(wi = 0; ((wi < w)&&(!found)); ++wi) { for(hi = 0; ((hi < h)&&(!found)); ++hi) { theEntryToRender->getEntry(hi, wi, tempEntry); if(tempEntry.getFullPath().exists()) { found = true; } } } if(aFrame.parseFile(tempEntry.getFullPath()) == ossimErrorCodes::OSSIM_OK) { const vector& colorTable = aFrame.getColorGrayscaleTable(); // ESH 03/2009 -- Partial fix for ticket #646. // Crash fix on reading RPFs: Make sure the colorTable vector // has entries before trying to make use of them. int numTables = (int)colorTable.size(); ossim_uint32 numElements = (numTables > 0) ? colorTable[0].getNumberOfElements() : 0; if(numElements > 0) { if((theProductType == OSSIM_PRODUCT_TYPE_CIB)|| (theProductType == OSSIM_PRODUCT_TYPE_CADRG)) { theLut = new ossimNBandLutDataObject(numElements, 3, OSSIM_UINT8); } else { theLut = 0; return; } ossim_uint32 idx = 0; for(idx = 0; idx < numElements;++idx) { const ossim_uint8* startOfData = colorTable[0].getStartOfData(idx); switch(theProductType) { case OSSIM_PRODUCT_TYPE_CIB: { (*theLut)[idx][0] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[0]); (*theLut)[idx][1] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[0]); (*theLut)[idx][2] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[0]); break; } case OSSIM_PRODUCT_TYPE_CADRG: { (*theLut)[idx][0] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[0]); (*theLut)[idx][1] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[1]); (*theLut)[idx][2] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[2]); break; } default: { break; } } } } } } } void ossimCibCadrgTileSource::updatePropertiesToFirstValidFrame() { if(theEntryToRender) { ossim_uint32 w = theEntryToRender->getNumberOfFramesHorizontal(); ossim_uint32 h = theEntryToRender->getNumberOfFramesVertical(); ossim_uint32 wi, hi; bool found = false; ossimRpfFrameEntry tempEntry; ossimRpfFrame aFrame; for(wi = 0; ((wi < w)&&(!found)); ++wi) { for(hi = 0; ((hi < h)&&(!found)); ++hi) { theEntryToRender->getEntry(hi, wi, tempEntry); if(tempEntry.getFullPath().exists()) { found = true; } } } if(found) { if(aFrame.parseFile(tempEntry.getFullPath()) == ossimErrorCodes::OSSIM_OK) { } } } } ossim-Miami-2.9.1/src/imaging/ossimClosestToCenterCombiner.cpp000066400000000000000000000112071352751253100244340ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimClosestToCenterCombiner.cpp 11955 2007-10-31 16:10:22Z gpotts $ #include #include RTTI_DEF1(ossimClosestToCenterCombiner, "ossimClosestToCenterCombiner", ossimImageMosaic); ossimClosestToCenterCombiner::ossimClosestToCenterCombiner() :ossimImageMosaic() { } ossimRefPtr ossimClosestToCenterCombiner::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { ossim_uint32 layerIdx = 0; if(!isSourceEnabled()) { return ossimImageMosaic::getTile(rect, resLevel); } if(!theTile.valid()) { allocate(); if(!theTile.valid()) { return 0; } } theTile->setImageRectangle(rect); theTile->makeBlank(); std::vector normTileList; ossimRefPtr currentTile = getNextNormTile(layerIdx, 0, rect); while(currentTile.valid()) { normTileList.push_back(ossimClosestToCenterCombinerInfo((ossimImageData*)currentTile->dup(), layerIdx)); currentTile = getNextNormTile(layerIdx, rect, resLevel); } if(normTileList.size() == 1) { theTile->copyNormalizedBufferToTile((ossim_float32*)normTileList[0].theTile->getBuf()); } else if(normTileList.size() > 1) { ossimRefPtr copyTile = ossimImageDataFactory::instance()->create(0, OSSIM_NORMALIZED_FLOAT); copyTile->setImageRectangleAndBands(rect, getNumberOfOutputBands()); copyTile->initialize(); ossim_int32 idx = 0; ossim_uint32 w = rect.width(); ossim_uint32 h = rect.height(); ossim_uint32 idxW = 0; ossim_uint32 idxH = 0; ossimIpt origin = rect.ul(); ossimIpt ulPt = rect.ul(); ossim_uint32 band = 0; ossim_uint32 bands = copyTile->getNumberOfBands(); ossim_uint32 srcBandIdx = 0; std::vector bandList(bands); for(band = 0; band < bands; ++band) { bandList[band] = (ossim_float32*)copyTile->getBuf(band); } ossim_uint32 offset = 0; origin.y = ulPt.y; for(idxH = 0; idxH < h; ++idxH) { origin.x = ulPt.x; for(idxW = 0; idxW < w;++idxW) { idx = findIdx(normTileList, origin, offset); if(idx >=0) { ossim_uint32 tileBands = normTileList[idx].theTile->getNumberOfBands(); if (tileBands > 0) { tileBands -= 1; for(band = 0; band < bands; ++band) { srcBandIdx = ossim::min( tileBands, band ); bandList[band][offset] = *(((ossim_float32*)normTileList[idx].theTile->getBuf(srcBandIdx))+offset); } } } ++offset; ++origin.x; } ++origin.y; } theTile->copyNormalizedBufferToTile((ossim_float32*)copyTile->getBuf()); } theTile->validate(); return theTile; } ossim_int32 ossimClosestToCenterCombiner::findIdx(const std::vector& normTileList, const ossimIpt& pt, ossim_uint32 offset)const { ossim_float32 distance = 1000000; ossim_int32 returnIdx = -1; ossim_float32 tempDistance; ossim_int32 idx = 0; ossim_int32 maxIdx = (ossim_int32)normTileList.size(); ossimIpt midPt; ossimIrect rect; for(idx = 0; idx < maxIdx; ++ idx) { rect = theFullResBounds[ normTileList[idx].theIndex ]; midPt = rect.midPoint(); tempDistance = (pt-midPt).length(); if(tempDistance < distance) { if(normTileList[idx].theTile->getDataObjectStatus() == OSSIM_FULL) { distance = tempDistance; returnIdx = idx; } else if(!normTileList[idx].theTile->isNull(offset)) { distance = tempDistance; returnIdx = idx; } } } return returnIdx; } ossim-Miami-2.9.1/src/imaging/ossimCodecBase.cpp000066400000000000000000000000521352751253100215010ustar00rootroot00000000000000#include ossim-Miami-2.9.1/src/imaging/ossimCodecFactory.cpp000066400000000000000000000036041352751253100222440ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Factory class definition for codec(encoder/decoder). // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include ossimCodecFactory* ossimCodecFactory::theInstance = 0; static const std::string TYPE_KW = "type"; ossimCodecFactory::~ossimCodecFactory() {} ossimCodecFactory* ossimCodecFactory::instance() { if ( !theInstance ) { theInstance = new ossimCodecFactory(); } return theInstance; } ossimCodecBase* ossimCodecFactory::createCodec(const ossimString& type)const { ossimRefPtr result; if((type.downcase() == "jpeg") || (type == "ossimJpegCodec")) { result = new ossimJpegCodec(); } return result.release(); } ossimCodecBase* ossimCodecFactory::createCodec(const ossimKeywordlist& kwl, const char* prefix)const { ossimString type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); ossimCodecBase* result = 0; if(!type.empty()) { result = this->createCodec(type); if(result) { result->loadState(kwl, prefix); } } return result; } void ossimCodecFactory::getTypeNameList(std::vector& typeNames)const { typeNames.push_back("jpeg"); } ossimCodecFactory::ossimCodecFactory() {} ossimCodecFactory::ossimCodecFactory(const ossimCodecFactory& /* obj */ ) {} const ossimCodecFactory& ossimCodecFactory::operator=( const ossimCodecFactory& /* rhs */) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimCodecFactoryInterface.cpp000066400000000000000000000006161352751253100240650ustar00rootroot00000000000000#include #include #include ossimObject* ossimCodecFactoryInterface::createObject(const ossimString& type)const { return createCodec(type); } ossimObject* ossimCodecFactoryInterface::createObject(const ossimKeywordlist& kwl, const char* prefix)const { return createCodec(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimCodecFactoryRegistry.cpp000066400000000000000000000026531352751253100240000ustar00rootroot00000000000000#include #include ossimCodecFactoryRegistry* ossimCodecFactoryRegistry::m_instance=0; /** hidden from use default constructor */ ossimCodecFactoryRegistry::ossimCodecFactoryRegistry() { m_instance = this; } /** hidden from use copy constructor */ ossimCodecFactoryRegistry::ossimCodecFactoryRegistry(const ossimCodecFactoryRegistry& /* obj */) { m_instance = this; } /** hidden from use operator = */ const ossimCodecFactoryRegistry& ossimCodecFactoryRegistry::operator=(const ossimCodecFactoryRegistry& /* rhs */) { return *this; } ossimCodecFactoryRegistry* ossimCodecFactoryRegistry::instance() { if(!m_instance) { m_instance = new ossimCodecFactoryRegistry(); m_instance->registerFactory(ossimCodecFactory::instance()); } return m_instance; } ossimCodecFactoryRegistry::~ossimCodecFactoryRegistry() { m_instance = 0; } ossimCodecBase* ossimCodecFactoryRegistry::createCodec(const ossimString& type)const { return createNativeObjectFromRegistry(type); } ossimCodecBase* ossimCodecFactoryRegistry::createCodec(const ossimKeywordlist& kwl, const char* prefix)const { return createNativeObjectFromRegistry(kwl, prefix); } void ossimCodecFactoryRegistry::getTypeNameList(std::vector& typeNames)const { getAllTypeNamesFromRegistry(typeNames); } ossim-Miami-2.9.1/src/imaging/ossimColorNormalizedFusion.cpp000066400000000000000000000104261352751253100241660ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Color normalized fusion // //************************************************************************* // $Id: ossimColorNormalizedFusion.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include RTTI_DEF1(ossimColorNormalizedFusion, "ossimColorNormalizedFusion", ossimFusionCombiner); ossimColorNormalizedFusion::ossimColorNormalizedFusion() : ossimFusionCombiner() { } ossimColorNormalizedFusion::ossimColorNormalizedFusion(ossimObject* owner) : ossimFusionCombiner(owner) { } ossimColorNormalizedFusion::~ossimColorNormalizedFusion() { } ossimRefPtr ossimColorNormalizedFusion::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { ossimRefPtr inputTile = getNormTile(rect, resLevel); if(!inputTile.valid()) { return NULL; } if(!theInputConnection||!theIntensityConnection) { return NULL; } if((inputTile->getDataObjectStatus() == OSSIM_NULL)|| (inputTile->getDataObjectStatus() == OSSIM_EMPTY)) { return NULL; } if(theTile.valid()) { theTile->setImageRectangleAndBands(rect, inputTile->getNumberOfBands()); } ossim_float32* redBuff = (ossim_float32*)inputTile->getBuf(0); ossim_float32* grnBuff = (ossim_float32*)inputTile->getBuf(1); ossim_float32* bluBuff = (ossim_float32*)inputTile->getBuf(2); if(!redBuff||!grnBuff||!bluBuff) { return 0; } ossimRefPtr inputIntensity = getNormIntensity(rect, resLevel); if((!inputIntensity.valid()) || (!inputIntensity->getBuf()) || (inputIntensity->getDataObjectStatus() == OSSIM_EMPTY)) { return 0; } ossim_float32* mono_buff = (ossim_float32*)inputIntensity->getBuf(0); // Since NULL_PIX_VALUE is only used for Pix8 comparisons cast it now. const float NULL_PIX_VALUE = (ossim_float32)inputIntensity->getNullPix(0); const float MIN_PIX_VALUE = (ossim_float32)inputIntensity->getMinPix(0); const float MAX_PIX_VALUE = (ossim_float32)inputIntensity->getMaxPix(0); float rgb_sum; float r_wt; // Weight of red to rgb_sum. float g_wt; // Weight of green to rgb_sum. float b_wt; // Weight of blue to rgb_sum. float iVal; float redVal; float greenVal; float blueVal; int size = theTile->getWidth()*theTile->getHeight(); for (int i = 0; i < size; i++) { //*** // If no intensity source, or, no rgb source make output pixels null. //*** if ( (mono_buff[i] == NULL_PIX_VALUE) || (redBuff[i] == NULL_PIX_VALUE && grnBuff[i] == NULL_PIX_VALUE && bluBuff[i] == NULL_PIX_VALUE) ) { redBuff[i] = NULL_PIX_VALUE; grnBuff[i] = NULL_PIX_VALUE; bluBuff[i] = NULL_PIX_VALUE; } else { redVal = redBuff[i]; greenVal = grnBuff[i]; blueVal = bluBuff[i]; rgb_sum = redVal + greenVal + blueVal + 3; r_wt = 3 * (redVal + 1) / rgb_sum; g_wt = 3 * (greenVal + 1) / rgb_sum; b_wt = 3 * (blueVal + 1) / rgb_sum; iVal = mono_buff[i] + 1; redVal = r_wt * iVal - 1; greenVal = g_wt * iVal - 1; blueVal = b_wt * iVal - 1; // Clip to max pixel value of radiometry. if (redVal > MAX_PIX_VALUE) redVal = MAX_PIX_VALUE; if (greenVal > MAX_PIX_VALUE) greenVal = MAX_PIX_VALUE; if (blueVal > MAX_PIX_VALUE) blueVal = MAX_PIX_VALUE; // Assign chip value, clamp to min pixel value of radiometry if zero. redBuff[i] = (float)(redVal>0.0 ? redVal : MIN_PIX_VALUE); grnBuff[i] = (float)(greenVal>0.0 ? greenVal : MIN_PIX_VALUE); bluBuff[i] = (float)(blueVal>0.0 ? blueVal : MIN_PIX_VALUE); } } // End of loop through pixels in chip. theTile->copyNormalizedBufferToTile((float*)inputTile->getBuf()); theTile->validate(); return theTile; } ossim-Miami-2.9.1/src/imaging/ossimConvolutionFilter1D.cpp000066400000000000000000000505701352751253100235550ustar00rootroot00000000000000//******************************************************************* // License: LGPL // // See LICENSE.txt file in the top level directory for more details. //************************************************************************* // $Id: ossimConvolutionFilter1D.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include #include #include #include #include #include RTTI_DEF1(ossimConvolutionFilter1D, "ossimConvolutionFilter1D", ossimImageSourceFilter); #define PROPNAME_KERNELSIZE "KernelSize" #define PROPNAME_KERNEL "Kernel" #define PROPNAME_ISHZ "Horizontal" #define PROPNAME_CENTEROFFSET "CenterOffset" #define PROPNAME_STRICTNODATA "StrictNoData" using namespace std; ossimConvolutionFilter1D::ossimConvolutionFilter1D(ossimObject* owner) :ossimImageSourceFilter(owner), theCenterOffset(0), theTile(NULL), theIsHz(true), theStrictNoData(true), theNullPixValue(0), theMinPixValue(0), theMaxPixValue(0) { //sets up an identity convolution theKernel.push_back(1.0); } ossimConvolutionFilter1D::~ossimConvolutionFilter1D() { } ossimRefPtr ossimConvolutionFilter1D::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return theTile; } if(!isSourceEnabled()) { return theInputConnection->getTile(tileRect, resLevel); } //--- // We have a 1xn or nx1 matrix, + a center offset // so stretch the input rect out to cover the required pixels //--- ossimIrect newRect; ossim_uint32 kl = (ossim_uint32)theKernel.size(); //kernel length if (theIsHz) { //horizontal kernel (row kernel) newRect = ossimIrect(ossimIpt(tileRect.ul().x - theCenterOffset, tileRect.ul().y), ossimIpt(tileRect.lr().x - theCenterOffset + kl -1, tileRect.lr().y)); } else { //vertical kernel newRect = ossimIrect(ossimIpt(tileRect.ul().x, tileRect.ul().y - theCenterOffset), ossimIpt(tileRect.lr().x, tileRect.lr().y - theCenterOffset + kl -1)); } ossimRefPtr data = theInputConnection->getTile(newRect, resLevel); if(!data.valid() || !data->getBuf()) { return data; } // First time through or after an initialize()... if (!theTile.valid()) { allocate(); if (!theTile.valid()) // Should never happen! { return data; } } // First time through, after an initialize() or a setKernel()... if (!theNullPixValue.size()) { computeNullMinMax(); if (!theNullPixValue.size()) // Should never happen! { return data; } } theTile->setImageRectangle(tileRect); theTile->makeBlank(); switch(data->getScalarType()) { case OSSIM_UCHAR: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } case OSSIM_SSHORT16: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { if(data->getDataObjectStatus() == OSSIM_FULL) { convolveFull(static_cast(0), data, theTile); } else { convolvePartial(static_cast(0), data, theTile); } break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimConvolutionFilter1D::getTile WARNING:\n" << "Scalar type = " << theTile->getScalarType() << " Not supported by ossimConvolutionFilter1D" << endl; break; } } theTile->validate(); return theTile; } template void ossimConvolutionFilter1D::convolvePartial( T, ossimRefPtr inputData, ossimRefPtr outputData) { // there may be NULL pixels in the input ossim_int32 inputW = static_cast(inputData->getWidth()); ossim_uint32 outputW = outputData->getWidth(); ossim_uint32 outputH = outputData->getHeight(); ossim_uint32 numberOfBands = inputData->getNumberOfBands(); ossim_uint32 klength=(ossim_uint32)theKernel.size(),k; ossim_int32 incrK = theIsHz ? 1 : inputW; //kernel increment in input : one col or one row ossim_int32 iRow = inputW - outputW; //jump to go to next row double sum=0.0; T* iKP; //kernel covered input pointer ossim_int32 iCo = incrK*theCenterOffset; //center pixel offset within the input buffer for(ossim_uint32 band = 0; band < numberOfBands; ++band) { T* inputBuf = static_cast(inputData->getBuf(band)); T* outputBuf = static_cast(outputData->getBuf(band)); T maxPix = static_cast(getMaxPixelValue(band)); T minPix = static_cast(getMinPixelValue(band)); T nullPix = static_cast(inputData->getNullPix(band)); T oNullPix = static_cast(getNullPixelValue(band)); if(inputBuf&&outputBuf) { for(ossim_uint32 row = 0; row < outputH; ++row) { for(ossim_uint32 col = 0; col < outputW; ++col) { //center pixel may not be NULL if (inputBuf[iCo] != nullPix) { iKP = inputBuf; sum = 0.0; for(k=0;k maxPix) { *outputBuf = maxPix; } else if(sum < minPix) { *outputBuf = minPix; } else { *outputBuf = static_cast(sum); } } else { //theStrictNoData *outputBuf = oNullPix; } } else { *outputBuf = oNullPix; } // move curent center position inputBuf += 1; outputBuf += 1; } //move current center position inputBuf += iRow; //outputBuf += 0; } } } } template void ossimConvolutionFilter1D::convolveFull( T, ossimRefPtr inputData, ossimRefPtr outputData) { //inputData must be displaced according to the Kernel size and theCenterOffset +isHz ossim_int32 inputW = static_cast(inputData->getWidth()); ossim_uint32 outputW = outputData->getWidth(); ossim_uint32 outputH = outputData->getHeight(); ossim_uint32 numberOfBands = inputData->getNumberOfBands(); ossim_uint32 klength=(ossim_uint32)theKernel.size(), k; ossim_int32 incrK = theIsHz ? 1 : inputW; //kernel increment in input : one col or one row ossim_int32 iRow = inputW - outputW; //jump to go to next row double sum=0.0; T* iKP; //kernel covered input pointer for(ossim_uint32 band = 0; band < numberOfBands; ++band) { T* inputBuf = static_cast(inputData->getBuf(band)); T* outputBuf = static_cast(outputData->getBuf(band)); T maxPix = static_cast(getMaxPixelValue(band)); T minPix = static_cast(getMinPixelValue(band)); if(inputBuf&&outputBuf) { for(ossim_uint32 row = 0; row < outputH; ++row) { for(ossim_uint32 col = 0; col < outputW; ++col) { sum = 0.0; iKP = inputBuf; for(k=0;k maxPix) { *outputBuf = maxPix; } else if(sum < minPix) { *outputBuf = minPix; } else { *outputBuf = static_cast(sum); } // move curent center position inputBuf += 1; outputBuf += 1; } //move current center position inputBuf += iRow; //outputBuf += 0; } } } } void ossimConvolutionFilter1D::initialize() { //--- // NOTE: // Since initialize get called often sequentially we will wipe things slick // but not reallocate to avoid multiple delete/allocates. // // On the first getTile call things will be reallocated/computed. //--- theTile = NULL; clearNullMinMax(); } void ossimConvolutionFilter1D::allocate() { if(theInputConnection) { ossimImageDataFactory* idf = ossimImageDataFactory::instance(); theTile = idf->create(this, this); theTile->initialize(); } } void ossimConvolutionFilter1D::setProperty(ossimRefPtr property) { if(!property) return; if(property->getName() == PROPNAME_KERNEL) { ossimMatrixProperty* matrixProperty = PTR_CAST(ossimMatrixProperty, property.get()); if(matrixProperty) { ossim_uint32 nc=matrixProperty->getNumberOfCols(); theKernel.resize(nc); for(ossim_uint32 i=0;igetName() == PROPNAME_ISHZ) { ossimBooleanProperty* booleanProperty = PTR_CAST(ossimBooleanProperty, property.get()); if(booleanProperty) { theIsHz = booleanProperty->getBoolean(); } } else if (property->getName() == PROPNAME_STRICTNODATA) { ossimBooleanProperty* booleanProperty = PTR_CAST(ossimBooleanProperty, property.get()); if(booleanProperty) { theStrictNoData = booleanProperty->getBoolean(); } } else if (property->getName() == PROPNAME_CENTEROFFSET) { ossimNumericProperty* numProperty = PTR_CAST(ossimNumericProperty, property.get()); if(numProperty) { theCenterOffset = numProperty->asInt32(); } } else if (property->getName() == PROPNAME_KERNELSIZE) { ossimNumericProperty* numProperty = PTR_CAST(ossimNumericProperty, property.get()); if(numProperty) { theKernel.resize(numProperty->asUInt32()); clearNullMinMax(); } } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimConvolutionFilter1D::getProperty(const ossimString& name)const { if(name == PROPNAME_KERNEL) { ossimMatrixProperty* property = new ossimMatrixProperty(name); property->resize(1,(int)theKernel.size()); for(ossim_uint32 i=0;isetCacheRefreshBit(); return property; } else if (name==PROPNAME_ISHZ) { ossimBooleanProperty* property = new ossimBooleanProperty(name,theIsHz); property->setCacheRefreshBit(); return property; } else if (name==PROPNAME_STRICTNODATA) { ossimBooleanProperty* property = new ossimBooleanProperty(name,theStrictNoData); property->setCacheRefreshBit(); return property; } else if (name==PROPNAME_CENTEROFFSET) { ossimNumericProperty* property = new ossimNumericProperty(name,ossimString::toString(theCenterOffset)); property->setNumericType(ossimNumericProperty::ossimNumericPropertyType_INT); //restrict to int type property->setCacheRefreshBit(); return property; } else if (name == PROPNAME_KERNELSIZE) { ossimNumericProperty* property = new ossimNumericProperty(name,ossimString::toString((ossim_uint32)theKernel.size()),1.0,100.0); property->setNumericType(ossimNumericProperty::ossimNumericPropertyType_INT); //restrict to int type property->setCacheRefreshBit(); return property; } return ossimImageSourceFilter::getProperty(name); } void ossimConvolutionFilter1D::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back(PROPNAME_KERNELSIZE); propertyNames.push_back(PROPNAME_KERNEL); propertyNames.push_back(PROPNAME_CENTEROFFSET); propertyNames.push_back(PROPNAME_ISHZ); propertyNames.push_back(PROPNAME_STRICTNODATA); } bool ossimConvolutionFilter1D::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, PROPNAME_KERNELSIZE, static_cast(theKernel.size()), true); kwl.add(prefix, PROPNAME_CENTEROFFSET, theCenterOffset, true); kwl.add(prefix, PROPNAME_ISHZ, theIsHz?"true":"false", //use string instead of boolean true); kwl.add(prefix, PROPNAME_STRICTNODATA, theStrictNoData?"true":"false", //use string instead of boolean true); for(ossim_uint32 row = 0; row < theKernel.size(); ++row) { ossimString newPrefix = "k" + ossimString::toString(row); kwl.add(prefix, newPrefix, theKernel[row], true); } return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimConvolutionFilter1D::loadState(const ossimKeywordlist& kwl, const char* prefix) { //find kernel size ossim_uint32 iks=0; const char* ks = kwl.find(prefix, PROPNAME_KERNELSIZE); if(ks) { iks = ossimString(ks).toUInt32(); if (iks<1) { cerr<<"ossimConvolutionFilter1D : warning bad "<< PROPNAME_KERNELSIZE <<" in state"<& aKernel) { theKernel = aKernel; // Will be recomputed first getTile call. clearNullMinMax(); } double ossimConvolutionFilter1D::getNullPixelValue(ossim_uint32 band)const { if( isSourceEnabled() && (band < theNullPixValue.size()) ) { return theNullPixValue[band]; } return ossim::defaultNull(getOutputScalarType()); } double ossimConvolutionFilter1D::getMinPixelValue(ossim_uint32 band)const { if( isSourceEnabled() && (band < theMinPixValue.size()) ) { return theMinPixValue[band]; } return ossimImageSource::getMinPixelValue(band); } double ossimConvolutionFilter1D::getMaxPixelValue(ossim_uint32 band)const { if( isSourceEnabled() && (band < theMaxPixValue.size()) ) { return theMaxPixValue[band]; } return ossimImageSource::getMaxPixelValue(band); } void ossimConvolutionFilter1D::clearNullMinMax() { theNullPixValue.clear(); theMinPixValue.clear(); theMaxPixValue.clear(); } void ossimConvolutionFilter1D::computeNullMinMax() { const ossim_uint32 BANDS = getNumberOfOutputBands(); theNullPixValue.resize(BANDS); theMinPixValue.resize(BANDS); theMaxPixValue.resize(BANDS); ossim_float64 defaultNull = ossim::defaultNull(getOutputScalarType()); ossim_float64 defaultMin = ossim::defaultMin(getOutputScalarType()); ossim_float64 defaultMax = ossim::defaultMax(getOutputScalarType()); for (ossim_uint32 band = 0; band < BANDS; ++band) { if(theInputConnection) { ossim_float64 inputNull = theInputConnection->getNullPixelValue(band); ossim_float64 inputMin = theInputConnection->getMinPixelValue(band); ossim_float64 inputMax = theInputConnection->getMaxPixelValue(band); ossim_float64 tempMin = 0.0; ossim_float64 tempMax = 0.0; ossim_float64 k = 0.0; for(ossim_uint32 i=0;i0.0) ? k*inputMax : k*inputMin; } if((tempMin >= defaultMin) && (tempMin <= defaultMax)) { theMinPixValue[band] = tempMin; } else { theMinPixValue[band] = defaultMin; } if((tempMax >= defaultMin) && (tempMax <= defaultMax)) { theMaxPixValue[band] = tempMax; } else { theMaxPixValue[band] = defaultMax; } if((inputNull < theMinPixValue[band]) || (inputNull > theMaxPixValue[band])) { theNullPixValue[band] = inputNull; } else { theNullPixValue[band] = defaultNull; } } else // No input connection... { theNullPixValue[band] = defaultNull; theMinPixValue[band] = defaultMin; theMaxPixValue[band] = defaultMax; } } // End of band loop. } ossim-Miami-2.9.1/src/imaging/ossimConvolutionSource.cpp000066400000000000000000000405071352751253100234020ustar00rootroot00000000000000// Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimConvolutionSource.cpp 18602 2010-12-28 05:49:36Z gpotts $ #include #include #include #include #include #include static const ossimKeyword NUMBER_OF_MATRICES = ossimKeyword("number_of_matrices", ""); static const ossimKeyword NUMBER_OF_ROWS = ossimKeyword("rows", ""); static const ossimKeyword NUMBER_OF_COLS = ossimKeyword("cols", ""); RTTI_DEF1(ossimConvolutionSource, "ossimConvolutionSource", ossimImageSourceFilter); using namespace std; ossimConvolutionSource::ossimConvolutionSource() : ossimImageSourceFilter(), theTile(NULL) { } ossimConvolutionSource::ossimConvolutionSource(ossimImageSource* inputSource, const NEWMAT::Matrix& convolutionMatrix) : ossimImageSourceFilter(inputSource), theTile(NULL) { theConvolutionKernelList.push_back(new ossimDiscreteConvolutionKernel(convolutionMatrix)); setKernelInformation(); initialize(); } ossimConvolutionSource::ossimConvolutionSource(ossimImageSource* inputSource, const vector& convolutionList) : ossimImageSourceFilter(inputSource), theTile(NULL) { setConvolutionList(convolutionList); } ossimConvolutionSource::~ossimConvolutionSource() { deleteConvolutionList(); } void ossimConvolutionSource::setConvolution(const double* kernel, int nrows, int ncols, bool doWeightedAverage) { NEWMAT::Matrix m(nrows, ncols); const double* tempPtr = kernel; for(int row = 0; row < nrows; ++row) { for(int col = 0; col < ncols; ++col) { m[row][col] =*tempPtr; ++tempPtr; } } setConvolution(m, doWeightedAverage); } void ossimConvolutionSource::setConvolutionList(const vector& convolutionList, bool doWeightedAverage) { deleteConvolutionList(); ossim_uint32 idx; for(idx = 0; idx < convolutionList.size(); ++idx) { theConvolutionKernelList.push_back(new ossimDiscreteConvolutionKernel(convolutionList[idx], doWeightedAverage)); } setKernelInformation(); } ossimRefPtr ossimConvolutionSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) return ossimRefPtr(); if((!isSourceEnabled())|| (theConvolutionKernelList.size() < 1)) { return theInputConnection->getTile(tileRect, resLevel); } if(!theTile.valid()) { allocate(); if(!theTile.valid()) // Throw exception??? { return theInputConnection->getTile(tileRect, resLevel); } } ossim_uint32 w = tileRect.width(); ossim_uint32 h = tileRect.height(); ossim_uint32 tw = theTile->getWidth(); ossim_uint32 th = theTile->getHeight(); theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tw*th)) { theTile->initialize(); theTile->makeBlank(); } else { theTile->makeBlank(); } theTile->setOrigin(tileRect.ul()); long offsetX = (theMaxKernelWidth)/2; long offsetY = (theMaxKernelHeight)/2; ossimIrect requestRect(tileRect.ul().x - offsetX, tileRect.ul().y - offsetY, tileRect.lr().x + offsetX, tileRect.lr().y + offsetY); ossimRefPtr input = theInputConnection->getTile(requestRect, resLevel); if(!input.valid() || (input->getDataObjectStatus() == OSSIM_NULL)|| (input->getDataObjectStatus() == OSSIM_EMPTY)) { return input; } switch(theTile->getScalarType()) { case OSSIM_UCHAR: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } case OSSIM_SSHORT16: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } default: { theTile->loadTile(input.get()); } } theTile->validate(); return theTile; } template void ossimConvolutionSource::convolve(T /* dummyVariable */, ossimRefPtr inputTile, ossimDiscreteConvolutionKernel* kernel) { ossimIpt startOrigin = theTile->getOrigin(); // Make sure that the patch is not empty or NULL // ossimIpt startDelta(startOrigin.x - inputTile->getOrigin().x, startOrigin.y - inputTile->getOrigin().y); ossimDataObjectStatus status = inputTile->getDataObjectStatus(); // let's setup some variables that we will need to do the // convolution algorithm. // ossimIrect patchRect = inputTile->getImageRectangle(); long tileHeight = theTile->getHeight(); long tileWidth = theTile->getWidth(); long outputBands = theTile->getNumberOfBands(); long convolutionWidth = kernel->getWidth(); long convolutionHeight = kernel->getHeight(); long convolutionOffsetX= convolutionWidth/2; long convolutionOffsetY= convolutionHeight/2; long patchWidth = patchRect.width(); long convolutionTopLeftOffset = 0; long convolutionCenterOffset = 0; long outputOffset = 0; T np = 0; const double minPix = ossim::defaultMin(getOutputScalarType()); const double maxPix = ossim::defaultMax(getOutputScalarType()); // const double* maxPix = inputTile->getMaxPix(); const double* nullPix = inputTile->getNullPix(); double convolveResult = 0; if(status == OSSIM_PARTIAL) // must check for NULLS { for(long y = 0; y isNull(convolutionCenterOffset)) { for(long b = 0; b < outputBands; ++b) { T* buf = (T*)(inputTile->getBuf(b)) + convolutionTopLeftOffset; T* outBuf = (T*)(theTile->getBuf(b)); kernel->convolveSubImage(buf, patchWidth, convolveResult, (T)nullPix[b]); convolveResult = convolveResult < minPix? minPix:convolveResult; convolveResult = convolveResult > maxPix? maxPix:convolveResult; outBuf[outputOffset] = (T)convolveResult; } } else { theTile->setNull(outputOffset); } ++convolutionCenterOffset; ++convolutionTopLeftOffset; ++outputOffset; } } } else // do not need to check for nulls here. { for(long b = 0; b < outputBands; ++b) { double convolveResult = 0; const T* buf = (const T*)inputTile->getBuf(b); T* outBuf = (T*)(theTile->getBuf(b)); np =(T)nullPix[b]; outputOffset = 0; for(long y = 0; y convolveSubImage(&buf[convolutionTopLeftOffset], patchWidth, convolveResult, np); // NOT SURE IF I WANT TO CLAMP IN A CONVOLUTION SOURCE // seems better to clamp to a scalar range instead of an input min max convolveResult = convolveResult < minPix? (T)minPix:convolveResult; convolveResult = convolveResult > maxPix?(T)maxPix:convolveResult; outBuf[outputOffset] = (T)convolveResult; ++outputOffset; ++convolutionTopLeftOffset; } } } } } void ossimConvolutionSource::initialize() { ossimImageSourceFilter::initialize(); theTile = NULL; } void ossimConvolutionSource::allocate() { if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, theInputConnection); theTile->initialize(); } } bool ossimConvolutionSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossim_uint32 numberOfMatrices = 0; for(ossim_uint32 m = 0; m < theConvolutionKernelList.size();++m) { if(theConvolutionKernelList[m]) { ++numberOfMatrices; const NEWMAT::Matrix& kernel = theConvolutionKernelList[m]->getKernel(); ossimString mPrefix = "m" + ossimString::toString(numberOfMatrices) + "."; kwl.add(prefix, (mPrefix + "rows").c_str(), kernel.Nrows(), true); kwl.add(prefix, (mPrefix + "cols").c_str(), kernel.Ncols(), true); for(ossim_int32 row = 0; row < kernel.Nrows(); ++row) { for(ossim_int32 col =0; col < kernel.Ncols(); ++col) { ossimString newPrefix = mPrefix + ossimString::toString(row+1) + "_" + ossimString::toString(col+1); kwl.add(prefix, newPrefix, kernel[row][col], true); } } } } kwl.add(prefix, NUMBER_OF_MATRICES, numberOfMatrices, true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimConvolutionSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { deleteConvolutionList(); const char* numberOfMatrices = kwl.find(prefix, NUMBER_OF_MATRICES); ossim_int32 matrixCount = ossimString(numberOfMatrices).toLong(); ossim_int32 numberOfMatches = 0; ossim_int32 index = 0; while(numberOfMatches < matrixCount) { ossimString newPrefix = prefix; newPrefix += ossimString("m"); newPrefix += ossimString::toString(index); newPrefix += ossimString("."); const char* rows = kwl.find((newPrefix+NUMBER_OF_ROWS.key()).c_str()); const char* cols = kwl.find((newPrefix+NUMBER_OF_COLS.key()).c_str()); if(rows&&cols) { ++numberOfMatches; ossim_int32 numberOfRows = ossimString(rows).toLong(); ossim_int32 numberOfCols = ossimString(cols).toLong(); NEWMAT::Matrix convolutionMatrix(numberOfRows, numberOfCols); for(ossim_int32 r = 1; r <= numberOfRows; r++) { for(ossim_int32 c = 1; c <= numberOfCols; c++) { convolutionMatrix[r-1][c-1] = 0.0; ossimString value = ossimString::toString(r); value += "_"; value += ossimString::toString(c); const char* v = kwl.find(newPrefix.c_str(), value.c_str()); if(v) { convolutionMatrix[r-1][c-1] = ossimString(v).toDouble(); } } } theConvolutionKernelList.push_back(new ossimDiscreteConvolutionKernel(convolutionMatrix)); } ++index; } setKernelInformation(); return ossimImageSourceFilter::loadState(kwl, prefix); } void ossimConvolutionSource::setKernelInformation() { ossim_uint32 index; if(theConvolutionKernelList.size() > 0) { theMaxKernelWidth = theConvolutionKernelList[0]->getWidth(); theMaxKernelHeight = theConvolutionKernelList[0]->getHeight(); for(index = 1; index < theConvolutionKernelList.size(); ++index) { ossim_int32 w = theConvolutionKernelList[index]->getWidth(); ossim_int32 h = theConvolutionKernelList[index]->getHeight(); theMaxKernelWidth = theMaxKernelWidth < w?w:theMaxKernelWidth; theMaxKernelHeight = theMaxKernelHeight < h?h:theMaxKernelHeight; } } } void ossimConvolutionSource::deleteConvolutionList() { for(ossim_int32 index = 0; index < (ossim_int32)theConvolutionKernelList.size(); ++index) { delete theConvolutionKernelList[index]; } theConvolutionKernelList.clear(); } void ossimConvolutionSource::setConvolution(const NEWMAT::Matrix& convolutionMatrix, bool doWeightedAverage) { std::vector m; m.push_back(convolutionMatrix); setConvolutionList(m, doWeightedAverage); } ossim-Miami-2.9.1/src/imaging/ossimDdffield.cpp000066400000000000000000000307531352751253100214050ustar00rootroot00000000000000/****************************************************************************** * Copied from "gdal" project. See licence below. * * Project: ISO 8211 Access * Purpose: Implements the DDFField class. * Author: Frank Warmerdam, warmerda@home.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** * $Id: ossimDdffield.cpp 17170 2010-04-20 13:51:55Z gpotts $ */ #include #include #include // #include "cpl_conv.h" // CPL_CVSID("$Id: ossimDdffield.cpp 17170 2010-04-20 13:51:55Z gpotts $"); // Note, we implement no constructor for this class to make instantiation // cheaper. It is required that the Initialize() be called before anything // else. /************************************************************************/ /* Initialize() */ /************************************************************************/ void ossimDDFField::Initialize( ossimDDFFieldDefn *poDefnIn, const char * pachDataIn, int nDataSizeIn ) { pachData = pachDataIn; nDataSize = nDataSizeIn; poDefn = poDefnIn; } /************************************************************************/ /* Dump() */ /************************************************************************/ /** * Write out field contents to debugging file. * * A variety of information about this field, and all it's * subfields is written to the given debugging file handle. Note that * field definition information (ala DDFFieldDefn) isn't written. * * @param fp The standard io file handle to write to. ie. stderr */ void ossimDDFField::Dump( FILE * fp ) { int nMaxRepeat = 8; if( getenv("DDF_MAXDUMP") != NULL ) nMaxRepeat = atoi(getenv("DDF_MAXDUMP")); fprintf( fp, " DDFField:\n" ); fprintf( fp, " Tag = `%s'\n", poDefn->GetName() ); fprintf( fp, " DataSize = %d\n", nDataSize ); fprintf( fp, " Data = `" ); for( int i = 0; i < std::min(nDataSize,40); i++ ) { if( pachData[i] < 32 || pachData[i] > 126 ) fprintf( fp, "\\%02X", ((unsigned char *) pachData)[i] ); else fprintf( fp, "%c", pachData[i] ); } if( nDataSize > 40 ) fprintf( fp, "..." ); fprintf( fp, "'\n" ); /* -------------------------------------------------------------------- */ /* dump the data of the subfields. */ /* -------------------------------------------------------------------- */ int iOffset = 0, nLoopCount; for( nLoopCount = 0; nLoopCount < GetRepeatCount(); nLoopCount++ ) { if( nLoopCount > nMaxRepeat ) { fprintf( fp, " ...\n" ); break; } for( int i = 0; i < poDefn->GetSubfieldCount(); i++ ) { int nBytesConsumed; poDefn->GetSubfield(i)->DumpData( pachData + iOffset, nDataSize - iOffset, fp ); poDefn->GetSubfield(i)->GetDataLength( pachData + iOffset, nDataSize - iOffset, &nBytesConsumed ); iOffset += nBytesConsumed; } } } /************************************************************************/ /* GetSubfieldData() */ /************************************************************************/ /** * Fetch raw data pointer for a particular subfield of this field. * * The passed DDFSubfieldDefn (poSFDefn) should be acquired from the * DDFFieldDefn corresponding with this field. This is normally done * once before reading any records. This method involves a series of * calls to DDFSubfield::GetDataLength() in order to track through the * DDFField data to that belonging to the requested subfield. This can * be relatively expensive.

* * @param poSFDefn The definition of the subfield for which the raw * data pointer is desired. * @param pnMaxBytes The maximum number of bytes that can be accessed from * the returned data pointer is placed in this int, unless it is NULL. * @param iSubfieldIndex The instance of this subfield to fetch. Use zero * (the default) for the first instance. * * @return A pointer into the DDFField's data that belongs to the subfield. * This returned pointer is invalidated by the next record read * (DDFRecord::ReadRecord()) and the returned pointer should not be freed * by the application. */ const char *ossimDDFField::GetSubfieldData( ossimDDFSubfieldDefn *poSFDefn, int *pnMaxBytes, int iSubfieldIndex ) { int iOffset = 0; if( poSFDefn == NULL ) return NULL; if( iSubfieldIndex > 0 && poDefn->GetFixedWidth() > 0 ) { iOffset = poDefn->GetFixedWidth() * iSubfieldIndex; iSubfieldIndex = 0; } while( iSubfieldIndex >= 0 ) { for( int iSF = 0; iSF < poDefn->GetSubfieldCount(); iSF++ ) { int nBytesConsumed; ossimDDFSubfieldDefn * poThisSFDefn = poDefn->GetSubfield( iSF ); if( poThisSFDefn == poSFDefn && iSubfieldIndex == 0 ) { if( pnMaxBytes != NULL ) *pnMaxBytes = nDataSize - iOffset; return pachData + iOffset; } poThisSFDefn->GetDataLength( pachData+iOffset, nDataSize - iOffset, &nBytesConsumed); iOffset += nBytesConsumed; } iSubfieldIndex--; } // We didn't find our target subfield or instance! return NULL; } /************************************************************************/ /* GetRepeatCount() */ /************************************************************************/ /** * How many times do the subfields of this record repeat? This * will always be one for non-repeating fields. * * @return The number of times that the subfields of this record occur * in this record. This will be one for non-repeating fields. * * @see 8211view example program * for demonstation of handling repeated fields properly. */ int ossimDDFField::GetRepeatCount() { if( !poDefn->IsRepeating() ) return 1; /* -------------------------------------------------------------------- */ /* The occurance count depends on how many copies of this */ /* field's list of subfields can fit into the data space. */ /* -------------------------------------------------------------------- */ if( poDefn->GetFixedWidth() ) { return nDataSize / poDefn->GetFixedWidth(); } /* -------------------------------------------------------------------- */ /* Note that it may be legal to have repeating variable width */ /* subfields, but I don't have any samples, so I ignore it for */ /* now. */ /* */ /* The file data/cape_royal_AZ_DEM/1183XREF.DDF has a repeating */ /* variable length field, but the count is one, so it isn't */ /* much value for testing. */ /* -------------------------------------------------------------------- */ int iOffset = 0, iRepeatCount = 1; while( true ) { for( int iSF = 0; iSF < poDefn->GetSubfieldCount(); iSF++ ) { int nBytesConsumed; ossimDDFSubfieldDefn * poThisSFDefn = poDefn->GetSubfield( iSF ); if( poThisSFDefn->GetWidth() > nDataSize - iOffset ) nBytesConsumed = poThisSFDefn->GetWidth(); else poThisSFDefn->GetDataLength( pachData+iOffset, nDataSize - iOffset, &nBytesConsumed); iOffset += nBytesConsumed; if( iOffset > nDataSize ) return iRepeatCount - 1; } if( iOffset > nDataSize - 2 ) return iRepeatCount; iRepeatCount++; } } /************************************************************************/ /* GetInstanceData() */ /************************************************************************/ /** * Get field instance data and size. * * The returned data pointer and size values are suitable for use with * DDFRecord::SetFieldRaw(). * * @param nInstance a value from 0 to GetRepeatCount()-1. * @param pnInstanceSize a location to put the size (in bytes) of the * field instance data returned. This size will include the unit terminator * (if any), but not the field terminator. This size pointer may be NULL * if not needed. * * @return the data pointer, or NULL on error. */ const char *ossimDDFField::GetInstanceData( int nInstance, int *pnInstanceSize ) { int nRepeatCount = GetRepeatCount(); const char *pachWrkData; if( nInstance < 0 || nInstance >= nRepeatCount ) return NULL; /* -------------------------------------------------------------------- */ /* Special case for fields without subfields (like "0001"). We */ /* don't currently handle repeating simple fields. */ /* -------------------------------------------------------------------- */ if( poDefn->GetSubfieldCount() == 0 ) { pachWrkData = GetData(); if( pnInstanceSize != 0 ) *pnInstanceSize = GetDataSize(); return pachWrkData; } /* -------------------------------------------------------------------- */ /* Get a pointer to the start of the existing data for this */ /* iteration of the field. */ /* -------------------------------------------------------------------- */ int nBytesRemaining1=0, nBytesRemaining2=0; ossimDDFSubfieldDefn *poFirstSubfield; poFirstSubfield = poDefn->GetSubfield(0); pachWrkData = GetSubfieldData(poFirstSubfield, &nBytesRemaining1, nInstance); /* -------------------------------------------------------------------- */ /* Figure out the size of the entire field instance, including */ /* unit terminators, but not any trailing field terminator. */ /* -------------------------------------------------------------------- */ if( pnInstanceSize != NULL ) { ossimDDFSubfieldDefn *poLastSubfield; int nLastSubfieldWidth; const char *pachLastData; poLastSubfield = poDefn->GetSubfield(poDefn->GetSubfieldCount()-1); pachLastData = GetSubfieldData( poLastSubfield, &nBytesRemaining2, nInstance ); poLastSubfield->GetDataLength( pachLastData, nBytesRemaining2, &nLastSubfieldWidth ); *pnInstanceSize = nBytesRemaining1 - (nBytesRemaining2 - nLastSubfieldWidth); } return pachWrkData; } ossim-Miami-2.9.1/src/imaging/ossimDdffielddefn.cpp000066400000000000000000000705551352751253100222460ustar00rootroot00000000000000/****************************************************************************** * Copied from "gdal" project. See licence below. * * Project: ISO 8211 Access * Purpose: Implements the DDFFieldDefn class. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** * $Id: ossimDdffielddefn.cpp 23346 2015-05-29 13:13:12Z dburken $ */ #include #include #include #include #include #include // Static trace for debugging static ossimTrace traceDebug("ossimDDFFieldDefn:debug"); /************************************************************************/ /* DDFFieldDefn() */ /************************************************************************/ ossimDDFFieldDefn::ossimDDFFieldDefn() { poModule = NULL; pszTag = NULL; _fieldName = NULL; _arrayDescr = NULL; _formatControls = NULL; nSubfieldCount = 0; papoSubfields = NULL; bRepeatingSubfields = false; nFixedWidth = 0; } /************************************************************************/ /* ~DDFFieldDefn() */ /************************************************************************/ ossimDDFFieldDefn::~ossimDDFFieldDefn() { int i; free( pszTag ); free( _fieldName ); free( _arrayDescr ); free( _formatControls ); for( i = 0; i < nSubfieldCount; i++ ) delete papoSubfields[i]; free( papoSubfields ); } /************************************************************************/ /* AddSubfield() */ /************************************************************************/ void ossimDDFFieldDefn::AddSubfield( const char *pszName, const char *pszFormat ) { ossimDDFSubfieldDefn *poSFDefn = new ossimDDFSubfieldDefn; poSFDefn->SetName( pszName ); poSFDefn->SetFormat( pszFormat ); AddSubfield( poSFDefn ); } /************************************************************************/ /* AddSubfield() */ /************************************************************************/ void ossimDDFFieldDefn::AddSubfield( ossimDDFSubfieldDefn *poNewSFDefn, int bDontAddToFormat ) { nSubfieldCount++; papoSubfields = (ossimDDFSubfieldDefn ** ) realloc( papoSubfields, sizeof(void*) * nSubfieldCount ); papoSubfields[nSubfieldCount-1] = poNewSFDefn; if( bDontAddToFormat ) return; /* -------------------------------------------------------------------- */ /* Add this format to the format list. We don't bother */ /* aggregating formats here. */ /* -------------------------------------------------------------------- */ if( _formatControls == NULL || strlen(_formatControls) == 0 ) { free( _formatControls ); _formatControls = strdup( "()" ); } int nOldLen = (int)strlen(_formatControls); char *pszNewFormatControls = (char *) malloc(nOldLen+3+strlen(poNewSFDefn->GetFormat())); strcpy( pszNewFormatControls, _formatControls ); pszNewFormatControls[nOldLen-1] = '\0'; if( pszNewFormatControls[nOldLen-2] != '(' ) strcat( pszNewFormatControls, "," ); strcat( pszNewFormatControls, poNewSFDefn->GetFormat() ); strcat( pszNewFormatControls, ")" ); free( _formatControls ); _formatControls = pszNewFormatControls; /* -------------------------------------------------------------------- */ /* Add the subfield name to the list. */ /* -------------------------------------------------------------------- */ if( _arrayDescr == NULL ) _arrayDescr = strdup(""); _arrayDescr = (char *) realloc(_arrayDescr, strlen(_arrayDescr)+strlen(poNewSFDefn->GetName())+2); if( strlen(_arrayDescr) > 0 ) strcat( _arrayDescr, "!" ); strcat( _arrayDescr, poNewSFDefn->GetName() ); } /************************************************************************/ /* Create() */ /* */ /* Initialize a new field defn from application input, instead */ /* of from an existing file. */ /************************************************************************/ int ossimDDFFieldDefn::Create( const char *pszTag, const char *pszFieldName, const char *pszDescription, DDF_data_struct_code eDataStructCode, DDF_data_type_code eDataTypeCode, const char *pszFormat ) { // assert( this->pszTag == NULL ); poModule = NULL; this->pszTag = strdup( pszTag ); _fieldName = strdup( pszFieldName ); _arrayDescr = strdup( pszDescription ); _formatControls = strdup( "" ); _data_struct_code = eDataStructCode; _data_type_code = eDataTypeCode; if( pszFormat != NULL ) _formatControls = strdup( pszFormat ); if( pszDescription != NULL && *pszDescription == '*' ) bRepeatingSubfields = true; return true; } /************************************************************************/ /* GenerateDDREntry() */ /************************************************************************/ int ossimDDFFieldDefn::GenerateDDREntry( char **ppachData, int *pnLength ) { *pnLength = 9 + (int)strlen(_fieldName) + 1 + (int)strlen(_arrayDescr) + 1 + (int)strlen(_formatControls) + 1; if( strlen(_formatControls) == 0 ) *pnLength -= 1; if( ppachData == NULL ) return true; *ppachData = (char *) malloc( *pnLength+1 ); if( _data_struct_code == dsc_elementary ) (*ppachData)[0] = '0'; else if( _data_struct_code == dsc_vector ) (*ppachData)[0] = '1'; else if( _data_struct_code == dsc_array ) (*ppachData)[0] = '2'; else if( _data_struct_code == dsc_concatenated ) (*ppachData)[0] = '3'; if( _data_type_code == dtc_char_string ) (*ppachData)[1] = '0'; else if( _data_type_code == dtc_implicit_point ) (*ppachData)[1] = '1'; else if( _data_type_code == dtc_explicit_point ) (*ppachData)[1] = '2'; else if( _data_type_code == dtc_explicit_point_scaled ) (*ppachData)[1] = '3'; else if( _data_type_code == dtc_char_bit_string ) (*ppachData)[1] = '4'; else if( _data_type_code == dtc_bit_string ) (*ppachData)[1] = '5'; else if( _data_type_code == dtc_mixed_data_type ) (*ppachData)[1] = '6'; (*ppachData)[2] = '0'; (*ppachData)[3] = '0'; (*ppachData)[4] = ';'; (*ppachData)[5] = '&'; (*ppachData)[6] = ' '; (*ppachData)[7] = ' '; (*ppachData)[8] = ' '; sprintf( *ppachData + 9, "%s%c%s", _fieldName, OSSIM_DDF_UNIT_TERMINATOR, _arrayDescr ); if( strlen(_formatControls) > 0 ) sprintf( *ppachData + strlen(*ppachData), "%c%s", OSSIM_DDF_UNIT_TERMINATOR, _formatControls ); sprintf( *ppachData + strlen(*ppachData), "%c", OSSIM_DDF_FIELD_TERMINATOR ); return true; } /************************************************************************/ /* Initialize() */ /* */ /* Initialize the field definition from the information in the */ /* DDR record. This is called by DDFModule::Open(). */ /************************************************************************/ int ossimDDFFieldDefn::Initialize( ossimDDFModule * poModuleIn, const char * pszTagIn, int nFieldEntrySize, const char * pachFieldArea ) { int iFDOffset = poModuleIn->GetFieldControlLength(); int nCharsConsumed; poModule = poModuleIn; pszTag = strdup( pszTagIn ); /* -------------------------------------------------------------------- */ /* Set the data struct and type codes. */ /* -------------------------------------------------------------------- */ switch( pachFieldArea[0] ) { case '0': _data_struct_code = dsc_elementary; break; case '1': _data_struct_code = dsc_vector; break; case '2': _data_struct_code = dsc_array; break; case '3': _data_struct_code = dsc_concatenated; break; default: if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Unrecognised data_struct_code value %c.\n" << "Field %s initialization incorrect.\n" << pachFieldArea[0] << pszTag << std::endl; } _data_struct_code = dsc_elementary; } switch( pachFieldArea[1] ) { case '0': _data_type_code = dtc_char_string; break; case '1': _data_type_code = dtc_implicit_point; break; case '2': _data_type_code = dtc_explicit_point; break; case '3': _data_type_code = dtc_explicit_point_scaled; break; case '4': _data_type_code = dtc_char_bit_string; break; case '5': _data_type_code = dtc_bit_string; break; case '6': _data_type_code = dtc_mixed_data_type; break; default: if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Unrecognised data_type_code value %c.\n" << "Field %s initialization incorrect.\n" << pachFieldArea[1] << pszTag << std::endl; } _data_type_code = dtc_char_string; } /* -------------------------------------------------------------------- */ /* Capture the field name, description (sub field names), and */ /* format statements. */ /* -------------------------------------------------------------------- */ _fieldName = ossimDDFFetchVariable( pachFieldArea + iFDOffset, nFieldEntrySize - iFDOffset, OSSIM_DDF_UNIT_TERMINATOR, OSSIM_DDF_FIELD_TERMINATOR, &nCharsConsumed ); iFDOffset += nCharsConsumed; _arrayDescr = ossimDDFFetchVariable( pachFieldArea + iFDOffset, nFieldEntrySize - iFDOffset, OSSIM_DDF_UNIT_TERMINATOR, OSSIM_DDF_FIELD_TERMINATOR, &nCharsConsumed ); iFDOffset += nCharsConsumed; _formatControls = ossimDDFFetchVariable( pachFieldArea + iFDOffset, nFieldEntrySize - iFDOffset, OSSIM_DDF_UNIT_TERMINATOR, OSSIM_DDF_FIELD_TERMINATOR, &nCharsConsumed ); /* -------------------------------------------------------------------- */ /* Parse the subfield info. */ /* -------------------------------------------------------------------- */ if( _data_struct_code != dsc_elementary ) { if( !BuildSubfields() ) return false; if( !ApplyFormats() ) return false; } return true; } /************************************************************************/ /* Dump() */ /************************************************************************/ /** * Write out field definition info to debugging file. * * A variety of information about this field definition, and all it's * subfields is written to the give debugging file handle. * * @param fp The standard io file handle to write to. ie. stderr */ void ossimDDFFieldDefn::Dump( FILE * fp ) { const char *pszValue = ""; fprintf( fp, " DDFFieldDefn:\n" ); fprintf( fp, " Tag = `%s'\n", pszTag ); fprintf( fp, " _fieldName = `%s'\n", _fieldName ); fprintf( fp, " _arrayDescr = `%s'\n", _arrayDescr ); fprintf( fp, " _formatControls = `%s'\n", _formatControls ); switch( _data_struct_code ) { case dsc_elementary: pszValue = "elementary"; break; case dsc_vector: pszValue = "vector"; break; case dsc_array: pszValue = "array"; break; case dsc_concatenated: pszValue = "concatenated"; break; default: // assert( false ); pszValue = "(unknown)"; } fprintf( fp, " _data_struct_code = %s\n", pszValue ); switch( _data_type_code ) { case dtc_char_string: pszValue = "char_string"; break; case dtc_implicit_point: pszValue = "implicit_point"; break; case dtc_explicit_point: pszValue = "explicit_point"; break; case dtc_explicit_point_scaled: pszValue = "explicit_point_scaled"; break; case dtc_char_bit_string: pszValue = "char_bit_string"; break; case dtc_bit_string: pszValue = "bit_string"; break; case dtc_mixed_data_type: pszValue = "mixed_data_type"; break; default: // assert( false ); pszValue = "(unknown)"; break; } fprintf( fp, " _data_type_code = %s\n", pszValue ); for( int i = 0; i < nSubfieldCount; i++ ) papoSubfields[i]->Dump( fp ); } /************************************************************************/ /* BuildSubfields() */ /* */ /* Based on the _arrayDescr build a set of subfields. */ /************************************************************************/ int ossimDDFFieldDefn::BuildSubfields() { char **papszSubfieldNames; const char *pszSublist = _arrayDescr; if( pszSublist[0] == '*' ) { bRepeatingSubfields = true; pszSublist++; } papszSubfieldNames = ossimCSLTokenizeStringComplex( pszSublist, "!", false, false ); int nSFCount = ossimCSLCount( papszSubfieldNames ); for( int iSF = 0; iSF < nSFCount; iSF++ ) { ossimDDFSubfieldDefn *poSFDefn = new ossimDDFSubfieldDefn; poSFDefn->SetName( papszSubfieldNames[iSF] ); AddSubfield( poSFDefn, true ); } ossimCSLDestroy( papszSubfieldNames ); return true; } /************************************************************************/ /* ExtractSubstring() */ /* */ /* Extract a substring terminated by a comma (or end of */ /* string). Commas in brackets are ignored as terminated with */ /* bracket nesting understood gracefully. If the returned */ /* string would being and end with a bracket then strip off the */ /* brackets. */ /* */ /* Given a string like "(A,3(B,C),D),X,Y)" return "A,3(B,C),D". */ /* Give a string like "3A,2C" return "3A". */ /************************************************************************/ char *ossimDDFFieldDefn::ExtractSubstring( const char * pszSrc ) { int nBracket=0, i; char *pszReturn; for( i = 0; pszSrc[i] != '\0' && (nBracket > 0 || pszSrc[i] != ','); i++ ) { if( pszSrc[i] == '(' ) nBracket++; else if( pszSrc[i] == ')' ) nBracket--; } if( pszSrc[0] == '(' ) { pszReturn = strdup( pszSrc + 1 ); pszReturn[i-2] = '\0'; } else { pszReturn = strdup( pszSrc ); pszReturn[i] = '\0'; } return pszReturn; } /************************************************************************/ /* ExpandFormat() */ /************************************************************************/ char *ossimDDFFieldDefn::ExpandFormat( const char * pszSrc ) { int nDestMax = 32; char *pszDest = (char *) malloc(nDestMax+1); int iSrc, iDst; int nRepeat = 0; iSrc = 0; iDst = 0; pszDest[0] = '\0'; while( pszSrc[iSrc] != '\0' ) { /* This is presumably an extra level of brackets around some binary stuff related to rescaning which we don't care to do (see 6.4.3.3 of the standard. We just strip off the extra layer of brackets */ if( (iSrc == 0 || pszSrc[iSrc-1] == ',') && pszSrc[iSrc] == '(' ) { char *pszContents = ExtractSubstring( pszSrc+iSrc ); char *pszExpandedContents = ExpandFormat( pszContents ); if( (int) (strlen(pszExpandedContents) + strlen(pszDest) + 1) > nDestMax ) { nDestMax = 2 * ((int)strlen(pszExpandedContents) + (int)strlen(pszDest)); pszDest = (char *) realloc(pszDest,nDestMax+1); } strcat( pszDest, pszExpandedContents ); iDst = (int)strlen(pszDest); iSrc = iSrc + (int)strlen(pszContents) + 2; free( pszContents ); free( pszExpandedContents ); } /* this is a repeated subclause */ else if( (iSrc == 0 || pszSrc[iSrc-1] == ',') && isdigit(pszSrc[iSrc]) ) { const char *pszNext; nRepeat = atoi(pszSrc+iSrc); // skip over repeat count. for( pszNext = pszSrc+iSrc; isdigit(*pszNext); pszNext++ ) iSrc++; char *pszContents = ExtractSubstring( pszNext ); char *pszExpandedContents = ExpandFormat( pszContents ); for( int i = 0; i < nRepeat; i++ ) { if( (int) (strlen(pszExpandedContents) + strlen(pszDest) + 1) > nDestMax ) { nDestMax = 2 * ((int)strlen(pszExpandedContents) + (int)strlen(pszDest)); pszDest = (char *) realloc(pszDest,nDestMax+1); } strcat( pszDest, pszExpandedContents ); if( i < nRepeat-1 ) strcat( pszDest, "," ); } iDst = (int)strlen(pszDest); if( pszNext[0] == '(' ) iSrc = iSrc + (int)strlen(pszContents) + 2; else iSrc = iSrc + (int)strlen(pszContents); free( pszContents ); free( pszExpandedContents ); } else { if( iDst+1 >= nDestMax ) { nDestMax = 2 * iDst; pszDest = (char *) realloc(pszDest,nDestMax); } pszDest[iDst++] = pszSrc[iSrc++]; pszDest[iDst] = '\0'; } } return pszDest; } /************************************************************************/ /* ApplyFormats() */ /* */ /* This method parses the format string partially, and then */ /* applies a subfield format string to each subfield object. */ /* It in turn does final parsing of the subfield formats. */ /************************************************************************/ int ossimDDFFieldDefn::ApplyFormats() { char *pszFormatList; char **papszFormatItems; /* -------------------------------------------------------------------- */ /* Verify that the format string is contained within brackets. */ /* -------------------------------------------------------------------- */ if( strlen(_formatControls) < 2 || _formatControls[0] != '(' || _formatControls[strlen(_formatControls)-1] != ')' ) { ossimNotify(ossimNotifyLevel_WARN) << "Format controls for `%s' field missing brackets:%s\n" << pszTag << _formatControls << std::endl; return false; } /* -------------------------------------------------------------------- */ /* Duplicate the string, and strip off the brackets. */ /* -------------------------------------------------------------------- */ pszFormatList = ExpandFormat( _formatControls ); /* -------------------------------------------------------------------- */ /* Tokenize based on commas. */ /* -------------------------------------------------------------------- */ papszFormatItems = ossimCSLTokenizeStringComplex(pszFormatList, ",", false, false ); free( pszFormatList ); /* -------------------------------------------------------------------- */ /* Apply the format items to subfields. */ /* -------------------------------------------------------------------- */ int iFormatItem; for( iFormatItem = 0; papszFormatItems[iFormatItem] != NULL; iFormatItem++ ) { const char *pszPastPrefix; pszPastPrefix = papszFormatItems[iFormatItem]; while( *pszPastPrefix >= '0' && *pszPastPrefix <= '9' ) pszPastPrefix++; /////////////////////////////////////////////////////////////// // Did we get too many formats for the subfields created // by names? This may be legal by the 8211 specification, but // isn't encountered in any formats we care about so we just // blow. if( iFormatItem >= nSubfieldCount ) { ossimNotify(ossimNotifyLevel_WARN) << "Got more formats than subfields for field `%s'.\n" << pszTag << std::endl; break; } if( !papoSubfields[iFormatItem]->SetFormat(pszPastPrefix) ) return false; } /* -------------------------------------------------------------------- */ /* Verify that we got enough formats, cleanup and return. */ /* -------------------------------------------------------------------- */ ossimCSLDestroy( papszFormatItems ); if( iFormatItem < nSubfieldCount ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Got less formats than subfields for field `%s',\n" << pszTag << std::endl; return false; } /* -------------------------------------------------------------------- */ /* If all the fields are fixed width, then we are fixed width */ /* too. This is important for repeating fields. */ /* -------------------------------------------------------------------- */ nFixedWidth = 0; for( int i = 0; i < nSubfieldCount; i++ ) { if( papoSubfields[i]->GetWidth() == 0 ) { nFixedWidth = 0; break; } else nFixedWidth += papoSubfields[i]->GetWidth(); } return true; } /************************************************************************/ /* FindSubfieldDefn() */ /************************************************************************/ /** * Find a subfield definition by it's mnemonic tag. * * @param pszMnemonic The name of the field. * * @return The subfield pointer, or NULL if there isn't any such subfield. */ ossimDDFSubfieldDefn *ossimDDFFieldDefn::FindSubfieldDefn( const char * pszMnemonic ) { for( int i = 0; i < nSubfieldCount; i++ ) { ossimString s = papoSubfields[i]->GetName(); if( s == pszMnemonic ) return papoSubfields[i]; } return NULL; } /************************************************************************/ /* GetSubfield() */ /* */ /* Fetch a subfield by it's index. */ /************************************************************************/ /** * Fetch a subfield by index. * * @param i The index subfield index. (Between 0 and GetSubfieldCount()-1) * * @return The subfield pointer, or NULL if the index is out of range. */ ossimDDFSubfieldDefn *ossimDDFFieldDefn::GetSubfield( int i ) { if( i < 0 || i >= nSubfieldCount ) { // assert( false ); return NULL; } return papoSubfields[i]; } /************************************************************************/ /* GetDefaultValue() */ /************************************************************************/ /** * Return default data for field instance. */ char *ossimDDFFieldDefn::GetDefaultValue( int *pnSize ) { /* -------------------------------------------------------------------- */ /* Loop once collecting the sum of the subfield lengths. */ /* -------------------------------------------------------------------- */ int iSubfield; int nTotalSize = 0; for( iSubfield = 0; iSubfield < nSubfieldCount; iSubfield++ ) { int nSubfieldSize; if( !papoSubfields[iSubfield]->GetDefaultValue( NULL, 0, &nSubfieldSize ) ) return NULL; nTotalSize += nSubfieldSize; } /* -------------------------------------------------------------------- */ /* Allocate buffer. */ /* -------------------------------------------------------------------- */ char *pachData = (char *) malloc( nTotalSize ); if( pnSize != NULL ) *pnSize = nTotalSize; /* -------------------------------------------------------------------- */ /* Loop again, collecting actual default values. */ /* -------------------------------------------------------------------- */ int nOffset = 0; for( iSubfield = 0; iSubfield < nSubfieldCount; iSubfield++ ) { int nSubfieldSize; if( !papoSubfields[iSubfield]->GetDefaultValue( pachData + nOffset, nTotalSize - nOffset, &nSubfieldSize ) ) { // assert( false ); free( pachData ); return NULL; } nOffset += nSubfieldSize; } // assert( nOffset == nTotalSize ); return pachData; } ossim-Miami-2.9.1/src/imaging/ossimDdfmodule.cpp000066400000000000000000000625621352751253100216120ustar00rootroot00000000000000/****************************************************************************** * Copied from "gdal" project. See licence below. * * Project: ISO 8211 Access * Purpose: Implements the DDFModule class. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** * $Id: ossimDdfmodule.cpp 12978 2008-06-04 00:04:14Z dburken $ */ #include #include #include #include /************************************************************************/ /* DDFModule() */ /************************************************************************/ /** * The constructor. */ ossimDDFModule::ossimDDFModule() { nFieldDefnCount = 0; papoFieldDefns = NULL; poRecord = NULL; papoClones = NULL; nCloneCount = nMaxCloneCount = 0; fpDDF = NULL; bReadOnly = true; _interchangeLevel = '\0'; _inlineCodeExtensionIndicator = '\0'; _versionNumber = '\0'; _appIndicator = '\0'; _fieldControlLength = '\0'; strcpy( _extendedCharSet, " ! " ); _recLength = 0; _leaderIden = 'L'; _fieldAreaStart = 0; _sizeFieldLength = 0; _sizeFieldPos = 0; _sizeFieldTag = 0; } /************************************************************************/ /* ~DDFModule() */ /************************************************************************/ /** * The destructor. */ ossimDDFModule::~ossimDDFModule() { Close(); } /************************************************************************/ /* Close() */ /* */ /* Note that closing a file also destroys essentially all other */ /* module datastructures. */ /************************************************************************/ /** * Close an ISO 8211 file. */ void ossimDDFModule::Close() { /* -------------------------------------------------------------------- */ /* Close the file. */ /* -------------------------------------------------------------------- */ if( fpDDF != NULL ) { fclose( fpDDF ); fpDDF = NULL; } /* -------------------------------------------------------------------- */ /* Cleanup the working record. */ /* -------------------------------------------------------------------- */ if( poRecord != NULL ) { delete poRecord; poRecord = NULL; } /* -------------------------------------------------------------------- */ /* Cleanup the clones. Deleting them will cause a callback to */ /* remove them from the list. */ /* -------------------------------------------------------------------- */ while( nCloneCount > 0 ) delete papoClones[0]; nMaxCloneCount = 0; free( papoClones ); papoClones = NULL; /* -------------------------------------------------------------------- */ /* Cleanup the field definitions. */ /* -------------------------------------------------------------------- */ int i; for( i = 0; i < nFieldDefnCount; i++ ) delete papoFieldDefns[i]; free( papoFieldDefns ); papoFieldDefns = NULL; nFieldDefnCount = 0; } /************************************************************************/ /* Open() */ /* */ /* Open an ISO 8211 file, and read the DDR record to build the */ /* field definitions. */ /************************************************************************/ /** * Open a ISO 8211 (DDF) file for reading. * * If the open succeeds the data descriptive record (DDR) will have been * read, and all the field and subfield definitions will be available. * * @param pszFilename The name of the file to open. * @param bFailQuietly If false a CPL Error is issued for non-8211 files, * otherwise quietly return NULL. * * @return false if the open fails or true if it succeeds. Errors messages * are issued internally with CPLError(). */ int ossimDDFModule::Open( const char * pszFilename, int bFailQuietly ) { static const size_t nLeaderSize = 24; /* -------------------------------------------------------------------- */ /* Close the existing file if there is one. */ /* -------------------------------------------------------------------- */ if( fpDDF != NULL ) Close(); // Check for empty filename. if (!pszFilename) { return false; } /* -------------------------------------------------------------------- */ /* Open the file. */ /* -------------------------------------------------------------------- */ fpDDF = fopen( pszFilename, "rb" ); if( fpDDF == NULL ) { if( !bFailQuietly ) ossimNotify(ossimNotifyLevel_WARN) << "Unable to open DDF file `%s'." << pszFilename << std::endl; return false; } /* -------------------------------------------------------------------- */ /* Read the 24 byte leader. */ /* -------------------------------------------------------------------- */ char achLeader[nLeaderSize]; if( fread( achLeader, 1, nLeaderSize, fpDDF ) != nLeaderSize ) { fclose( fpDDF ); fpDDF = NULL; if( !bFailQuietly ) ossimNotify(ossimNotifyLevel_WARN) << "Leader is short on DDF file `%s'." << pszFilename << std::endl; return false; } /* -------------------------------------------------------------------- */ /* Verify that this appears to be a valid DDF file. */ /* -------------------------------------------------------------------- */ int i, bValid = true; for( i = 0; i < (int)nLeaderSize; i++ ) { if( achLeader[i] < 32 || achLeader[i] > 126 ) bValid = false; } if( achLeader[5] != '1' && achLeader[5] != '2' && achLeader[5] != '3' ) bValid = false; if( achLeader[6] != 'L' ) bValid = false; if( achLeader[8] != '1' && achLeader[8] != ' ' ) bValid = false; /* -------------------------------------------------------------------- */ /* Extract information from leader. */ /* -------------------------------------------------------------------- */ if( bValid ) { _recLength = ossimDDFScanInt( achLeader+0, 5 ); _interchangeLevel = achLeader[5]; _leaderIden = achLeader[6]; _inlineCodeExtensionIndicator = achLeader[7]; _versionNumber = achLeader[8]; _appIndicator = achLeader[9]; _fieldControlLength = ossimDDFScanInt(achLeader+10,2); _fieldAreaStart = ossimDDFScanInt(achLeader+12,5); _extendedCharSet[0] = achLeader[17]; _extendedCharSet[1] = achLeader[18]; _extendedCharSet[2] = achLeader[19]; _extendedCharSet[3] = '\0'; _sizeFieldLength = ossimDDFScanInt(achLeader+20,1); _sizeFieldPos = ossimDDFScanInt(achLeader+21,1); _sizeFieldTag = ossimDDFScanInt(achLeader+23,1); if( _recLength < 12 || _fieldControlLength == 0 || _fieldAreaStart < 24 || _sizeFieldLength == 0 || _sizeFieldPos == 0 || _sizeFieldTag == 0 ) { bValid = false; } } /* -------------------------------------------------------------------- */ /* If the header is invalid, then clean up, report the error */ /* and return. */ /* -------------------------------------------------------------------- */ if( !bValid ) { fclose( fpDDF ); fpDDF = NULL; if( !bFailQuietly ) ossimNotify(ossimNotifyLevel_WARN) << "File `%s' does not appear to have\n" << "a valid ISO 8211 header.\n" << pszFilename << std::endl; return false; } /* -------------------------------------------------------------------- */ /* Read the whole record info memory. */ /* -------------------------------------------------------------------- */ char *pachRecord; pachRecord = (char *) malloc(_recLength); memcpy( pachRecord, achLeader, nLeaderSize ); if( fread( pachRecord+nLeaderSize, 1, _recLength-nLeaderSize, fpDDF ) != _recLength - nLeaderSize ) { if( !bFailQuietly ) ossimNotify(ossimNotifyLevel_WARN) << "Header record is short on DDF file `%s'." << pszFilename << std::endl; return false; } /* -------------------------------------------------------------------- */ /* First make a pass counting the directory entries. */ /* -------------------------------------------------------------------- */ int nFieldEntryWidth, nFDCount = 0; nFieldEntryWidth = _sizeFieldLength + _sizeFieldPos + _sizeFieldTag; for( i = nLeaderSize; i < _recLength; i += nFieldEntryWidth ) { if( pachRecord[i] == OSSIM_DDF_FIELD_TERMINATOR ) break; nFDCount++; } /* -------------------------------------------------------------------- */ /* Allocate, and read field definitions. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nFDCount; i++ ) { char szTag[128]; int nEntryOffset = nLeaderSize + i*nFieldEntryWidth; int nFieldLength, nFieldPos; ossimDDFFieldDefn *poFDefn; strncpy( szTag, pachRecord+nEntryOffset, _sizeFieldTag ); szTag[_sizeFieldTag] = '\0'; nEntryOffset += _sizeFieldTag; nFieldLength = ossimDDFScanInt( pachRecord+nEntryOffset, _sizeFieldLength ); nEntryOffset += _sizeFieldLength; nFieldPos = ossimDDFScanInt( pachRecord+nEntryOffset, _sizeFieldPos ); poFDefn = new ossimDDFFieldDefn(); poFDefn->Initialize( this, szTag, nFieldLength, pachRecord+_fieldAreaStart+nFieldPos ); AddField( poFDefn ); } free( pachRecord ); /* -------------------------------------------------------------------- */ /* Record the current file offset, the beginning of the first */ /* data record. */ /* -------------------------------------------------------------------- */ nFirstRecordOffset = ftell( fpDDF ); return true; } /************************************************************************/ /* Initialize() */ /************************************************************************/ int ossimDDFModule::Initialize( char chInterchangeLevel, char chLeaderIden, char chCodeExtensionIndicator, char chVersionNumber, char chAppIndicator, const char *pszExtendedCharSet, int nSizeFieldLength, int nSizeFieldPos, int nSizeFieldTag ) { _interchangeLevel = chInterchangeLevel; _leaderIden = chLeaderIden; _inlineCodeExtensionIndicator = chCodeExtensionIndicator; _versionNumber = chVersionNumber; _appIndicator = chAppIndicator; strcpy( _extendedCharSet, pszExtendedCharSet ); _sizeFieldLength = nSizeFieldLength; _sizeFieldPos = nSizeFieldPos; _sizeFieldTag = nSizeFieldTag; return true; } /************************************************************************/ /* Create() */ /************************************************************************/ int ossimDDFModule::Create( const char *pszFilename ) { // CPLAssert( fpDDF == NULL ); /* -------------------------------------------------------------------- */ /* Create the file on disk. */ /* -------------------------------------------------------------------- */ fpDDF = fopen( pszFilename, "wb+" ); if( fpDDF == NULL ) { ossimNotify(ossimNotifyLevel_WARN) << "Failed to create file %s, check path and permissions." << pszFilename << std::endl; return false; } bReadOnly = false; /* -------------------------------------------------------------------- */ /* Prepare all the field definition information. */ /* -------------------------------------------------------------------- */ int iField; _fieldControlLength = 9; _recLength = 24 + nFieldDefnCount * (_sizeFieldLength+_sizeFieldPos+_sizeFieldTag) + 1; _fieldAreaStart = _recLength; for( iField=0; iField < nFieldDefnCount; iField++ ) { int nLength; papoFieldDefns[iField]->GenerateDDREntry( NULL, &nLength ); _recLength += nLength; } /* -------------------------------------------------------------------- */ /* Setup 24 byte leader. */ /* -------------------------------------------------------------------- */ char achLeader[25]; sprintf( achLeader+0, "%05d", (int) _recLength ); achLeader[5] = _interchangeLevel; achLeader[6] = _leaderIden; achLeader[7] = _inlineCodeExtensionIndicator; achLeader[8] = _versionNumber; achLeader[9] = _appIndicator; sprintf( achLeader+10, "%02d", (int) _fieldControlLength ); sprintf( achLeader+12, "%05d", (int) _fieldAreaStart ); strncpy( achLeader+17, _extendedCharSet, 3 ); sprintf( achLeader+20, "%1d", (int) _sizeFieldLength ); sprintf( achLeader+21, "%1d", (int) _sizeFieldPos ); achLeader[22] = '0'; sprintf( achLeader+23, "%1d", (int) _sizeFieldTag ); fwrite( achLeader, 24, 1, fpDDF ); /* -------------------------------------------------------------------- */ /* Write out directory entries. */ /* -------------------------------------------------------------------- */ int nOffset = 0; for( iField=0; iField < nFieldDefnCount; iField++ ) { char achDirEntry[12]; int nLength; papoFieldDefns[iField]->GenerateDDREntry( NULL, &nLength ); strcpy( achDirEntry, papoFieldDefns[iField]->GetName() ); sprintf( achDirEntry + _sizeFieldTag, "%03d", nLength ); sprintf( achDirEntry + _sizeFieldTag + _sizeFieldLength, "%04d", nOffset ); nOffset += nLength; fwrite( achDirEntry, 11, 1, fpDDF ); } char chUT = OSSIM_DDF_FIELD_TERMINATOR; fwrite( &chUT, 1, 1, fpDDF ); /* -------------------------------------------------------------------- */ /* Write out the field descriptions themselves. */ /* -------------------------------------------------------------------- */ for( iField=0; iField < nFieldDefnCount; iField++ ) { char *pachData; int nLength; papoFieldDefns[iField]->GenerateDDREntry( &pachData, &nLength ); fwrite( pachData, nLength, 1, fpDDF ); free( pachData ); } return true; } /************************************************************************/ /* Dump() */ /************************************************************************/ /** * Write out module info to debugging file. * * A variety of information about the module is written to the debugging * file. This includes all the field and subfield definitions read from * the header. * * @param fp The standard io file handle to write to. ie. stderr. */ void ossimDDFModule::Dump( FILE * fp ) { fprintf( fp, "DDFModule:\n" ); fprintf( fp, " _recLength = %ld\n", _recLength ); fprintf( fp, " _interchangeLevel = %c\n", _interchangeLevel ); fprintf( fp, " _leaderIden = %c\n", _leaderIden ); fprintf( fp, " _inlineCodeExtensionIndicator = %c\n", _inlineCodeExtensionIndicator ); fprintf( fp, " _versionNumber = %c\n", _versionNumber ); fprintf( fp, " _appIndicator = %c\n", _appIndicator ); fprintf( fp, " _extendedCharSet = `%s'\n", _extendedCharSet ); fprintf( fp, " _fieldControlLength = %d\n", _fieldControlLength ); fprintf( fp, " _fieldAreaStart = %ld\n", _fieldAreaStart ); fprintf( fp, " _sizeFieldLength = %ld\n", _sizeFieldLength ); fprintf( fp, " _sizeFieldPos = %ld\n", _sizeFieldPos ); fprintf( fp, " _sizeFieldTag = %ld\n", _sizeFieldTag ); for( int i = 0; i < nFieldDefnCount; i++ ) { papoFieldDefns[i]->Dump( fp ); } } /************************************************************************/ /* FindFieldDefn() */ /************************************************************************/ /** * Fetch the definition of the named field. * * This function will scan the DDFFieldDefn's on this module, to find * one with the indicated field name. * * @param pszFieldName The name of the field to search for. The comparison is * case insensitive. * * @return A pointer to the request DDFFieldDefn object is returned, or NULL * if none matching the name are found. The return object remains owned by * the DDFModule, and should not be deleted by application code. */ ossimDDFFieldDefn *ossimDDFModule::FindFieldDefn( const char *pszFieldName ) { int i; /* -------------------------------------------------------------------- */ /* This pass tries to reduce the cost of comparing strings by */ /* first checking the first character, and by using strcmp() */ /* -------------------------------------------------------------------- */ for( i = 0; i < nFieldDefnCount; i++ ) { const char *pszThisName = papoFieldDefns[i]->GetName(); if( *pszThisName == *pszFieldName && strcmp( pszFieldName+1, pszThisName+1) == 0 ) return papoFieldDefns[i]; } /* -------------------------------------------------------------------- */ /* Now do a more general check. Application code may not */ /* always use the correct name case. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nFieldDefnCount; i++ ) { ossimString s = papoFieldDefns[i]->GetName(); if( s == pszFieldName ) return papoFieldDefns[i]; } return NULL; } /************************************************************************/ /* ReadRecord() */ /* */ /* Read one record from the file, and return to the */ /* application. The returned record is owned by the module, */ /* and is reused from call to call in order to preserve headers */ /* when they aren't being re-read from record to record. */ /************************************************************************/ /** * Read one record from the file. * * @return A pointer to a DDFRecord object is returned, or NULL if a read * error, or end of file occurs. The returned record is owned by the * module, and should not be deleted by the application. The record is * only valid untill the next ReadRecord() at which point it is overwritten. */ ossimDDFRecord *ossimDDFModule::ReadRecord() { if( poRecord == NULL ) poRecord = new ossimDDFRecord( this ); if( poRecord->Read() ) return poRecord; else return NULL; } /************************************************************************/ /* AddField() */ /************************************************************************/ /** * Add new field definition. * * Field definitions may only be added to DDFModules being used for * writing, not those being used for reading. Ownership of the * DDFFieldDefn object is taken by the DDFModule. * * @param poNewFDefn definition to be added to the module. */ void ossimDDFModule::AddField( ossimDDFFieldDefn *poNewFDefn ) { nFieldDefnCount++; papoFieldDefns = (ossimDDFFieldDefn **) ossimCPLRealloc(papoFieldDefns, sizeof(void*)*nFieldDefnCount); papoFieldDefns[nFieldDefnCount-1] = poNewFDefn; } /************************************************************************/ /* GetField() */ /************************************************************************/ /** * Fetch a field definition by index. * * @param i (from 0 to GetFieldCount() - 1. * @return the returned field pointer or NULL if the index is out of range. */ ossimDDFFieldDefn *ossimDDFModule::GetField(int i) { if( i < 0 || i >= nFieldDefnCount ) return NULL; else return papoFieldDefns[i]; } /************************************************************************/ /* AddCloneRecord() */ /* */ /* We want to keep track of cloned records, so we can clean */ /* them up when the module is destroyed. */ /************************************************************************/ void ossimDDFModule::AddCloneRecord( ossimDDFRecord * poRecord ) { /* -------------------------------------------------------------------- */ /* Do we need to grow the container array? */ /* -------------------------------------------------------------------- */ if( nCloneCount == nMaxCloneCount ) { nMaxCloneCount = nCloneCount*2 + 20; papoClones = (ossimDDFRecord **) ossimCPLRealloc(papoClones, nMaxCloneCount * sizeof(void*)); } /* -------------------------------------------------------------------- */ /* Add to the list. */ /* -------------------------------------------------------------------- */ papoClones[nCloneCount++] = poRecord; } /************************************************************************/ /* RemoveCloneRecord() */ /************************************************************************/ void ossimDDFModule::RemoveCloneRecord( ossimDDFRecord * poRecord ) { int i; for( i = 0; i < nCloneCount; i++ ) { if( papoClones[i] == poRecord ) { papoClones[i] = papoClones[nCloneCount-1]; nCloneCount--; return; } } // CPLAssert( false ); } /************************************************************************/ /* Rewind() */ /************************************************************************/ /** * Return to first record. * * The next call to ReadRecord() will read the first data record in the file. * * @param nOffset the offset in the file to return to. By default this is * -1, a special value indicating that reading should return to the first * data record. Otherwise it is an absolute byte offset in the file. */ void ossimDDFModule::Rewind( long nOffset ) { if( nOffset == -1 ) nOffset = nFirstRecordOffset; if( fpDDF == NULL ) return; fseek( fpDDF, nOffset, SEEK_SET ); if( nOffset == nFirstRecordOffset && poRecord != NULL ) poRecord->Clear(); } ossim-Miami-2.9.1/src/imaging/ossimDdfrecord.cpp000066400000000000000000002201121352751253100215660ustar00rootroot00000000000000/****************************************************************************** * Copied from "gdal" project. See licence below. * * Project: ISO 8211 Access * Purpose: Implements the DDFRecord class. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** * $Id: ossimDdfrecord.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ */ #include #include #include #include // CPL_CVSID("$Id: ossimDdfrecord.cpp 15833 2009-10-29 01:41:53Z eshirschorn $"); static const size_t nLeaderSize = 24; /************************************************************************/ /* DDFRecord() */ /************************************************************************/ ossimDDFRecord::ossimDDFRecord( ossimDDFModule * poModuleIn ) { poModule = poModuleIn; nReuseHeader = false; nFieldOffset = 0; nDataSize = 0; pachData = NULL; nFieldCount = 0; paoFields = NULL; bIsClone = false; _sizeFieldTag = 4; _sizeFieldPos = 0; _sizeFieldLength = 0; } /************************************************************************/ /* ~DDFRecord() */ /************************************************************************/ ossimDDFRecord::~ossimDDFRecord() { Clear(); if( bIsClone ) poModule->RemoveCloneRecord( this ); } /************************************************************************/ /* Dump() */ /************************************************************************/ /** * Write out record contents to debugging file. * * A variety of information about this record, and all it's fields and * subfields is written to the given debugging file handle. Note that * field definition information (ala DDFFieldDefn) isn't written. * * @param fp The standard io file handle to write to. ie. stderr */ void ossimDDFRecord::Dump( FILE * fp ) { fprintf( fp, "DDFRecord:\n" ); fprintf( fp, " nReuseHeader = %d\n", nReuseHeader ); fprintf( fp, " nDataSize = %d\n", nDataSize ); fprintf( fp, " _sizeFieldLength=%d, _sizeFieldPos=%d, _sizeFieldTag=%d\n", _sizeFieldLength, _sizeFieldPos, _sizeFieldTag ); for( int i = 0; i < nFieldCount; i++ ) { paoFields[i].Dump( fp ); } } /************************************************************************/ /* Read() */ /* */ /* Read a record of data from the file, and parse the header to */ /* build a field list for the record (or reuse the existing one */ /* if reusing headers). It is expected that the file pointer */ /* will be positioned at the beginning of a data record. It is */ /* the DDFModule's responsibility to do so. */ /* */ /* This method should only be called by the DDFModule class. */ /************************************************************************/ int ossimDDFRecord::Read() { /* -------------------------------------------------------------------- */ /* Redefine the record on the basis of the header if needed. */ /* As a side effect this will read the data for the record as well.*/ /* -------------------------------------------------------------------- */ if( !nReuseHeader ) { return( ReadHeader() ); } /* -------------------------------------------------------------------- */ /* Otherwise we read just the data and carefully overlay it on */ /* the previous records data without disturbing the rest of the */ /* record. */ /* -------------------------------------------------------------------- */ size_t nReadBytes; nReadBytes = fread( pachData + nFieldOffset, 1, nDataSize - nFieldOffset, poModule->GetFP() ); if( nReadBytes != (size_t) (nDataSize - nFieldOffset) && nReadBytes == 0 && feof( poModule->GetFP() ) ) { return false; } else if( nReadBytes != (size_t) (nDataSize - nFieldOffset) ) { ossimNotify(ossimNotifyLevel_WARN) << "Data record is short on DDF file.\n" << std::endl; return false; } // notdef: eventually we may have to do something at this point to // notify the DDFField's that their data values have changed. return true; } /************************************************************************/ /* Write() */ /************************************************************************/ /** * Write record out to module. * * This method writes the current record to the module to which it is * attached. Normally this would be at the end of the file, and only used * for modules newly created with DDFModule::Create(). Rewriting existing * records is not supported at this time. Calling Write() multiple times * on a DDFRecord will result it multiple copies being written at the end of * the module. * * @return true on success or false on failure. */ int ossimDDFRecord::Write() { if( !ResetDirectory() ) return false; /* -------------------------------------------------------------------- */ /* Prepare leader. */ /* -------------------------------------------------------------------- */ char szLeader[nLeaderSize+1]; memset( szLeader, ' ', nLeaderSize ); sprintf( szLeader+0, "%05d", static_cast(nDataSize + nLeaderSize) ); szLeader[5] = ' '; szLeader[6] = 'D'; sprintf( szLeader + 12, "%05d", static_cast(nFieldOffset + nLeaderSize) ); szLeader[17] = ' '; szLeader[20] = (char) ('0' + _sizeFieldLength); szLeader[21] = (char) ('0' + _sizeFieldPos); szLeader[22] = '0'; szLeader[23] = (char) ('0' + _sizeFieldTag); /* notdef: lots of stuff missing */ /* -------------------------------------------------------------------- */ /* Write the leader. */ /* -------------------------------------------------------------------- */ fwrite( szLeader, nLeaderSize, 1, poModule->GetFP() ); /* -------------------------------------------------------------------- */ /* Write the remainder of the record. */ /* -------------------------------------------------------------------- */ fwrite( pachData, nDataSize, 1, poModule->GetFP() ); return true; } /************************************************************************/ /* Clear() */ /* */ /* Clear any information associated with the last header in */ /* preparation for reading a new header. */ /************************************************************************/ void ossimDDFRecord::Clear() { if( paoFields != NULL ) delete[] paoFields; paoFields = NULL; nFieldCount = 0; if( pachData != NULL ) free( pachData ); pachData = NULL; nDataSize = 0; nReuseHeader = false; } /************************************************************************/ /* ReadHeader() */ /* */ /* This perform the header reading and parsing job for the */ /* Read() method. It reads the header, and builds a field */ /* list. */ /************************************************************************/ int ossimDDFRecord::ReadHeader() { /* -------------------------------------------------------------------- */ /* Clear any existing information. */ /* -------------------------------------------------------------------- */ Clear(); /* -------------------------------------------------------------------- */ /* Read the 24 byte leader. */ /* -------------------------------------------------------------------- */ char achLeader[nLeaderSize]; int nReadBytes; nReadBytes = (int)fread(achLeader,1,(int)nLeaderSize,poModule->GetFP()); if( nReadBytes == 0 && feof( poModule->GetFP() ) ) { return false; } else if( nReadBytes != (int) nLeaderSize ) { ossimNotify(ossimNotifyLevel_WARN) << "Leader is short on DDF file." << std::endl; return false; } /* -------------------------------------------------------------------- */ /* Extract information from leader. */ /* -------------------------------------------------------------------- */ int _recLength, _fieldAreaStart; char _leaderIden; _recLength = ossimDDFScanInt( achLeader+0, 5 ); _leaderIden = achLeader[6]; _fieldAreaStart = ossimDDFScanInt(achLeader+12,5); _sizeFieldLength = achLeader[20] - '0'; _sizeFieldPos = achLeader[21] - '0'; _sizeFieldTag = achLeader[23] - '0'; if( _sizeFieldLength < 0 || _sizeFieldLength > 9 || _sizeFieldPos < 0 || _sizeFieldPos > 9 || _sizeFieldTag < 0 || _sizeFieldTag > 9 ) { ossimNotify(ossimNotifyLevel_WARN) << "ISO8211 record leader appears to be corrupt." << std::endl; return false; } if( _leaderIden == 'R' ) nReuseHeader = true; nFieldOffset = _fieldAreaStart - nLeaderSize; /* -------------------------------------------------------------------- */ /* Is there anything seemly screwy about this record? */ /* -------------------------------------------------------------------- */ if(( _recLength < 24 || _recLength > 100000000 || _fieldAreaStart < 24 || _fieldAreaStart > 100000 ) && (_recLength != 0)) { ossimNotify(ossimNotifyLevel_WARN) << "Data record appears to be corrupt on DDF file.\n" << " -- ensure that the files were uncompressed without modifying\n" << "carriage return/linefeeds (by default WINZIP does this)." << std::endl; return false; } /* ==================================================================== */ /* Handle the normal case with the record length available. */ /* ==================================================================== */ if(_recLength != 0) { /* -------------------------------------------------------------------- */ /* Read the remainder of the record. */ /* -------------------------------------------------------------------- */ nDataSize = _recLength - nLeaderSize; pachData = (char *) malloc(nDataSize); if( fread( pachData, 1, nDataSize, poModule->GetFP()) != (size_t) nDataSize ) { ossimNotify(ossimNotifyLevel_WARN) << "Data record is short on DDF file." << std::endl; return false; } /* -------------------------------------------------------------------- */ /* If we don't find a field terminator at the end of the record */ /* we will read extra bytes till we get to it. */ /* -------------------------------------------------------------------- */ while( pachData[nDataSize-1] != OSSIM_DDF_FIELD_TERMINATOR ) { nDataSize++; pachData = (char *) ossimCPLRealloc(pachData,nDataSize); if( fread( pachData + nDataSize - 1, 1, 1, poModule->GetFP() ) != 1 ) { ossimNotify(ossimNotifyLevel_WARN) << "Data record is short on DDF file." << std::endl; return false; } ossimNotify(ossimNotifyLevel_DEBUG) << "Didn't find field terminator, read one more byte." << std::endl; } /* -------------------------------------------------------------------- */ /* Loop over the directory entries, making a pass counting them. */ /* -------------------------------------------------------------------- */ int i; int nFieldEntryWidth; nFieldEntryWidth = _sizeFieldLength + _sizeFieldPos + _sizeFieldTag; nFieldCount = 0; for( i = 0; i < nDataSize; i += nFieldEntryWidth ) { if( pachData[i] == OSSIM_DDF_FIELD_TERMINATOR ) break; nFieldCount++; } /* -------------------------------------------------------------------- */ /* Allocate, and read field definitions. */ /* -------------------------------------------------------------------- */ paoFields = new ossimDDFField[nFieldCount]; for( i = 0; i < nFieldCount; i++ ) { char szTag[128]; int nEntryOffset = i*nFieldEntryWidth; int nFieldLength, nFieldPos; /* -------------------------------------------------------------------- */ /* Read the position information and tag. */ /* -------------------------------------------------------------------- */ strncpy( szTag, pachData+nEntryOffset, _sizeFieldTag ); szTag[_sizeFieldTag] = '\0'; nEntryOffset += _sizeFieldTag; nFieldLength = ossimDDFScanInt( pachData+nEntryOffset, _sizeFieldLength ); nEntryOffset += _sizeFieldLength; nFieldPos = ossimDDFScanInt( pachData+nEntryOffset, _sizeFieldPos ); /* -------------------------------------------------------------------- */ /* Find the corresponding field in the module directory. */ /* -------------------------------------------------------------------- */ ossimDDFFieldDefn *poFieldDefn = poModule->FindFieldDefn( szTag ); if( poFieldDefn == NULL ) { ossimNotify(ossimNotifyLevel_WARN) << "Undefined field `%s' encountered in data record." << szTag << std::endl; return false; } /* -------------------------------------------------------------------- */ /* Assign info the DDFField. */ /* -------------------------------------------------------------------- */ paoFields[i].Initialize( poFieldDefn, pachData + _fieldAreaStart + nFieldPos - nLeaderSize, nFieldLength ); } return true; } /* ==================================================================== */ /* Handle the exceptional case where the record length is */ /* zero. In this case we have to read all the data based on */ /* the size of data items as per ISO8211 spec Annex C, 1.5.1. */ /* */ /* See Bugzilla bug 181 and test with file US4CN21M.000. */ /* ==================================================================== */ else { ossimNotify(ossimNotifyLevel_WARN) << "Record with zero length, use variant (C.1.5.1) logic." << std::endl; /* ----------------------------------------------------------------- */ /* _recLength == 0, handle the large record. */ /* */ /* Read the remainder of the record. */ /* ----------------------------------------------------------------- */ nDataSize = 0; pachData = NULL; /* ----------------------------------------------------------------- */ /* Loop over the directory entries, making a pass counting them. */ /* ----------------------------------------------------------------- */ int nFieldEntryWidth = _sizeFieldLength + _sizeFieldPos + _sizeFieldTag; nFieldCount = 0; int i=0; char *tmpBuf = (char*)malloc(nFieldEntryWidth); // while we're not at the end, store this entry, // and keep on reading... do { // read an Entry: if(nFieldEntryWidth != (int) fread(tmpBuf, 1, nFieldEntryWidth, poModule->GetFP())) { ossimNotify(ossimNotifyLevel_WARN) << "Data record is short on DDF file." << std::endl; return false; } // move this temp buffer into more permanent storage: char *newBuf = (char*)malloc(nDataSize+nFieldEntryWidth); if(pachData!=NULL) { memcpy(newBuf, pachData, nDataSize); free(pachData); } memcpy(&newBuf[nDataSize], tmpBuf, nFieldEntryWidth); pachData = newBuf; nDataSize += nFieldEntryWidth; if(OSSIM_DDF_FIELD_TERMINATOR != tmpBuf[0]) { nFieldCount++; } } while(OSSIM_DDF_FIELD_TERMINATOR != tmpBuf[0]); // Now, rewind a little. Only the TERMINATOR should have been read: int rewindSize = nFieldEntryWidth - 1; FILE *fp = poModule->GetFP(); long pos = ftell(fp) - rewindSize; fseek(fp, pos, SEEK_SET); nDataSize -= rewindSize; // -------------------------------------------------------------------- // Okay, now let's populate the heck out of pachData... // -------------------------------------------------------------------- for(i=0; iGetFP())) { ossimNotify(ossimNotifyLevel_WARN) << "Data record is short on DDF file." << std::endl; return false; } // move this temp buffer into more permanent storage: char *newBuf = (char*)malloc(nDataSize+nFieldLength); memcpy(newBuf, pachData, nDataSize); free(pachData); memcpy(&newBuf[nDataSize], tmpBuf, nFieldLength); free(tmpBuf); pachData = newBuf; nDataSize += nFieldLength; } /* ----------------------------------------------------------------- */ /* Allocate, and read field definitions. */ /* ----------------------------------------------------------------- */ paoFields = new ossimDDFField[nFieldCount]; for( i = 0; i < nFieldCount; i++ ) { char szTag[128]; int nEntryOffset = i*nFieldEntryWidth; int nFieldLength, nFieldPos; /* ------------------------------------------------------------- */ /* Read the position information and tag. */ /* ------------------------------------------------------------- */ strncpy( szTag, pachData+nEntryOffset, _sizeFieldTag ); szTag[_sizeFieldTag] = '\0'; nEntryOffset += _sizeFieldTag; nFieldLength = ossimDDFScanInt( pachData+nEntryOffset, _sizeFieldLength ); nEntryOffset += _sizeFieldLength; nFieldPos = ossimDDFScanInt( pachData+nEntryOffset, _sizeFieldPos ); /* ------------------------------------------------------------- */ /* Find the corresponding field in the module directory. */ /* ------------------------------------------------------------- */ ossimDDFFieldDefn *poFieldDefn = poModule->FindFieldDefn( szTag ); if( poFieldDefn == NULL ) { ossimNotify(ossimNotifyLevel_WARN) << "Undefined field `%s' encountered in data record." << szTag << std::endl; return false; } /* ------------------------------------------------------------- */ /* Assign info the DDFField. */ /* ------------------------------------------------------------- */ paoFields[i].Initialize( poFieldDefn, pachData + _fieldAreaStart + nFieldPos - nLeaderSize, nFieldLength ); } return true; } } /************************************************************************/ /* FindField() */ /************************************************************************/ /** * Find the named field within this record. * * @param pszName The name of the field to fetch. The comparison is * case insensitive. * @param iFieldIndex The instance of this field to fetch. Use zero (the * default) for the first instance. * * @return Pointer to the requested DDFField. This pointer is to an * internal object, and should not be freed. It remains valid until * the next record read. */ ossimDDFField * ossimDDFRecord::FindField( const char * pszName, int iFieldIndex ) { for( int i = 0; i < nFieldCount; i++ ) { ossimString s = paoFields[i].GetFieldDefn()->GetName(); if( s == pszName) { if( iFieldIndex == 0 ) return paoFields + i; else iFieldIndex--; } } return NULL; } /************************************************************************/ /* GetField() */ /************************************************************************/ /** * Fetch field object based on index. * * @param i The index of the field to fetch. Between 0 and GetFieldCount()-1. * * @return A DDFField pointer, or NULL if the index is out of range. */ ossimDDFField *ossimDDFRecord::GetField( int i ) { if( i < 0 || i >= nFieldCount ) return NULL; else return paoFields + i; } /************************************************************************/ /* GetIntSubfield() */ /************************************************************************/ /** * Fetch value of a subfield as an integer. This is a convenience * function for fetching a subfield of a field within this record. * * @param pszField The name of the field containing the subfield. * @param iFieldIndex The instance of this field within the record. Use * zero for the first instance of this field. * @param pszSubfield The name of the subfield within the selected field. * @param iSubfieldIndex The instance of this subfield within the record. * Use zero for the first instance. * @param pnSuccess Pointer to an int which will be set to true if the fetch * succeeds, or false if it fails. Use NULL if you don't want to check * success. * @return The value of the subfield, or zero if it failed for some reason. */ int ossimDDFRecord::GetIntSubfield( const char * pszField, int iFieldIndex, const char * pszSubfield, int iSubfieldIndex, int * pnSuccess ) { ossimDDFField *poField; int nDummyErr; if( pnSuccess == NULL ) pnSuccess = &nDummyErr; *pnSuccess = false; /* -------------------------------------------------------------------- */ /* Fetch the field. If this fails, return zero. */ /* -------------------------------------------------------------------- */ poField = FindField( pszField, iFieldIndex ); if( poField == NULL ) return 0; /* -------------------------------------------------------------------- */ /* Get the subfield definition */ /* -------------------------------------------------------------------- */ ossimDDFSubfieldDefn *poSFDefn; poSFDefn = poField->GetFieldDefn()->FindSubfieldDefn( pszSubfield ); if( poSFDefn == NULL ) return 0; /* -------------------------------------------------------------------- */ /* Get a pointer to the data. */ /* -------------------------------------------------------------------- */ int nBytesRemaining; const char *pachData = poField->GetSubfieldData(poSFDefn, &nBytesRemaining, iSubfieldIndex); /* -------------------------------------------------------------------- */ /* Return the extracted value. */ /* -------------------------------------------------------------------- */ *pnSuccess = true; return( poSFDefn->ExtractIntData( pachData, nBytesRemaining, NULL ) ); } /************************************************************************/ /* GetFloatSubfield() */ /************************************************************************/ /** * Fetch value of a subfield as a float (double). This is a convenience * function for fetching a subfield of a field within this record. * * @param pszField The name of the field containing the subfield. * @param iFieldIndex The instance of this field within the record. Use * zero for the first instance of this field. * @param pszSubfield The name of the subfield within the selected field. * @param iSubfieldIndex The instance of this subfield within the record. * Use zero for the first instance. * @param pnSuccess Pointer to an int which will be set to true if the fetch * succeeds, or false if it fails. Use NULL if you don't want to check * success. * @return The value of the subfield, or zero if it failed for some reason. */ double ossimDDFRecord::GetFloatSubfield( const char * pszField, int iFieldIndex, const char * pszSubfield, int iSubfieldIndex, int * pnSuccess ) { ossimDDFField *poField; int nDummyErr; if( pnSuccess == NULL ) pnSuccess = &nDummyErr; *pnSuccess = false; /* -------------------------------------------------------------------- */ /* Fetch the field. If this fails, return zero. */ /* -------------------------------------------------------------------- */ poField = FindField( pszField, iFieldIndex ); if( poField == NULL ) return 0; /* -------------------------------------------------------------------- */ /* Get the subfield definition */ /* -------------------------------------------------------------------- */ ossimDDFSubfieldDefn *poSFDefn; poSFDefn = poField->GetFieldDefn()->FindSubfieldDefn( pszSubfield ); if( poSFDefn == NULL ) return 0; /* -------------------------------------------------------------------- */ /* Get a pointer to the data. */ /* -------------------------------------------------------------------- */ int nBytesRemaining; const char *pachData = poField->GetSubfieldData(poSFDefn, &nBytesRemaining, iSubfieldIndex); /* -------------------------------------------------------------------- */ /* Return the extracted value. */ /* -------------------------------------------------------------------- */ *pnSuccess = true; return( poSFDefn->ExtractFloatData( pachData, nBytesRemaining, NULL ) ); } /************************************************************************/ /* GetStringSubfield() */ /************************************************************************/ /** * Fetch value of a subfield as a string. This is a convenience * function for fetching a subfield of a field within this record. * * @param pszField The name of the field containing the subfield. * @param iFieldIndex The instance of this field within the record. Use * zero for the first instance of this field. * @param pszSubfield The name of the subfield within the selected field. * @param iSubfieldIndex The instance of this subfield within the record. * Use zero for the first instance. * @param pnSuccess Pointer to an int which will be set to true if the fetch * succeeds, or false if it fails. Use NULL if you don't want to check * success. * @return The value of the subfield, or NULL if it failed for some reason. * The returned pointer is to internal data and should not be modified or * freed by the application. */ const char * ossimDDFRecord::GetStringSubfield( const char * pszField, int iFieldIndex, const char * pszSubfield, int iSubfieldIndex, int * pnSuccess ) { ossimDDFField *poField; int nDummyErr; if( pnSuccess == NULL ) pnSuccess = &nDummyErr; *pnSuccess = false; /* -------------------------------------------------------------------- */ /* Fetch the field. If this fails, return zero. */ /* -------------------------------------------------------------------- */ poField = FindField( pszField, iFieldIndex ); if( poField == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Get the subfield definition */ /* -------------------------------------------------------------------- */ ossimDDFSubfieldDefn *poSFDefn; poSFDefn = poField->GetFieldDefn()->FindSubfieldDefn( pszSubfield ); if( poSFDefn == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Get a pointer to the data. */ /* -------------------------------------------------------------------- */ int nBytesRemaining; const char *pachData = poField->GetSubfieldData(poSFDefn, &nBytesRemaining, iSubfieldIndex); /* -------------------------------------------------------------------- */ /* Return the extracted value. */ /* -------------------------------------------------------------------- */ *pnSuccess = true; return( poSFDefn->ExtractStringData( pachData, nBytesRemaining, NULL ) ); } /************************************************************************/ /* Clone() */ /************************************************************************/ /** * Make a copy of a record. * * This method is used to make a copy of a record that will become (mostly) * the properly of application. However, it is automatically destroyed if * the DDFModule it was created relative to is destroyed, as it's field * and subfield definitions relate to that DDFModule. However, it does * persist even when the record returned by DDFModule::ReadRecord() is * invalidated, such as when reading a new record. This allows an application * to cache whole DDFRecords. * * @return A new copy of the DDFRecord. This can be delete'd by the * application when no longer needed, otherwise it will be cleaned up when * the DDFModule it relates to is destroyed or closed. */ ossimDDFRecord * ossimDDFRecord::Clone() { ossimDDFRecord *poNR; poNR = new ossimDDFRecord( poModule ); poNR->nReuseHeader = false; poNR->nFieldOffset = nFieldOffset; poNR->nDataSize = nDataSize; poNR->pachData = (char *) malloc(nDataSize); memcpy( poNR->pachData, pachData, nDataSize ); poNR->nFieldCount = nFieldCount; poNR->paoFields = new ossimDDFField[nFieldCount]; for( int i = 0; i < nFieldCount; i++ ) { int nOffset; nOffset = (paoFields[i].GetData() - pachData); poNR->paoFields[i].Initialize( paoFields[i].GetFieldDefn(), poNR->pachData + nOffset, paoFields[i].GetDataSize() ); } poNR->bIsClone = true; poModule->AddCloneRecord( poNR ); return poNR; } /************************************************************************/ /* CloneOn() */ /************************************************************************/ /** * Recreate a record referencing another module. * * Works similarly to the DDFRecord::Clone() method, but creates the * new record with reference to a different DDFModule. All DDFFieldDefn * references are transcribed onto the new module based on field names. * If any fields don't have a similarly named field on the target module * the operation will fail. No validation of field types and properties * is done, but this operation is intended only to be used between * modules with matching definitions of all affected fields. * * The new record will be managed as a clone by the target module in * a manner similar to regular clones. * * @param poTargetModule the module on which the record copy should be * created. * * @return NULL on failure or a pointer to the cloned record. */ ossimDDFRecord *ossimDDFRecord::CloneOn( ossimDDFModule *poTargetModule ) { /* -------------------------------------------------------------------- */ /* Verify that all fields have a corresponding field definition */ /* on the target module. */ /* -------------------------------------------------------------------- */ int i; for( i = 0; i < nFieldCount; i++ ) { ossimDDFFieldDefn *poDefn = paoFields[i].GetFieldDefn(); if( poTargetModule->FindFieldDefn( poDefn->GetName() ) == NULL ) return NULL; } /* -------------------------------------------------------------------- */ /* Create a clone. */ /* -------------------------------------------------------------------- */ ossimDDFRecord *poClone; poClone = Clone(); /* -------------------------------------------------------------------- */ /* Update all internal information to reference other module. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nFieldCount; i++ ) { ossimDDFField *poField = poClone->paoFields+i; ossimDDFFieldDefn *poDefn; poDefn = poTargetModule->FindFieldDefn( poField->GetFieldDefn()->GetName() ); poField->Initialize( poDefn, poField->GetData(), poField->GetDataSize() ); } poModule->RemoveCloneRecord( poClone ); poClone->poModule = poTargetModule; poTargetModule->AddCloneRecord( poClone ); return poClone; } /************************************************************************/ /* DeleteField() */ /************************************************************************/ /** * Delete a field instance from a record. * * Remove a field from this record, cleaning up the data * portion and repacking the fields list. We don't try to * reallocate the data area of the record to be smaller. * * NOTE: This method doesn't actually remove the header * information for this field from the record tag list yet. * This should be added if the resulting record is even to be * written back to disk! * * @param poTarget the field instance on this record to delete. * * @return true on success, or false on failure. Failure can occur if * poTarget isn't really a field on this record. */ int ossimDDFRecord::DeleteField( ossimDDFField *poTarget ) { int iTarget, i; /* -------------------------------------------------------------------- */ /* Find which field we are to delete. */ /* -------------------------------------------------------------------- */ for( iTarget = 0; iTarget < nFieldCount; iTarget++ ) { if( paoFields + iTarget == poTarget ) break; } if( iTarget == nFieldCount ) return false; /* -------------------------------------------------------------------- */ /* Change the target fields data size to zero. This takes care */ /* of repacking the data array, and updating all the following */ /* field data pointers. */ /* -------------------------------------------------------------------- */ ResizeField( poTarget, 0 ); /* -------------------------------------------------------------------- */ /* remove the target field, moving down all the other fields */ /* one step in the field list. */ /* -------------------------------------------------------------------- */ for( i = iTarget; i < nFieldCount-1; i++ ) { paoFields[i] = paoFields[i+1]; } nFieldCount--; return true; } /************************************************************************/ /* ResizeField() */ /************************************************************************/ /** * Alter field data size within record. * * This method will rearrange a DDFRecord altering the amount of space * reserved for one of the existing fields. All following fields will * be shifted accordingly. This includes updating the DDFField infos, * and actually moving stuff within the data array after reallocating * to the desired size. * * @param poField the field to alter. * @param nNewDataSize the number of data bytes to be reserved for the field. * * @return true on success or false on failure. */ int ossimDDFRecord::ResizeField( ossimDDFField *poField, int nNewDataSize ) { int iTarget, i; int nBytesToMove; /* -------------------------------------------------------------------- */ /* Find which field we are to resize. */ /* -------------------------------------------------------------------- */ for( iTarget = 0; iTarget < nFieldCount; iTarget++ ) { if( paoFields + iTarget == poField ) break; } if( iTarget == nFieldCount ) { // CPLAssert( false ); return false; } /* -------------------------------------------------------------------- */ /* Reallocate the data buffer accordingly. */ /* -------------------------------------------------------------------- */ int nBytesToAdd = nNewDataSize - poField->GetDataSize(); const char *pachOldData = pachData; // Don't realloc things smaller ... we will cut off some data. if( nBytesToAdd > 0 ) pachData = (char *) ossimCPLRealloc(pachData, nDataSize + nBytesToAdd ); nDataSize += nBytesToAdd; /* -------------------------------------------------------------------- */ /* How much data needs to be shifted up or down after this field? */ /* -------------------------------------------------------------------- */ nBytesToMove = nDataSize - (poField->GetData()+poField->GetDataSize()-pachOldData+nBytesToAdd); /* -------------------------------------------------------------------- */ /* Update fields to point into newly allocated buffer. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nFieldCount; i++ ) { int nOffset; nOffset = paoFields[i].GetData() - pachOldData; paoFields[i].Initialize( paoFields[i].GetFieldDefn(), pachData + nOffset, paoFields[i].GetDataSize() ); } /* -------------------------------------------------------------------- */ /* Shift the data beyond this field up or down as needed. */ /* -------------------------------------------------------------------- */ if( nBytesToMove > 0 ) memmove( (char *)poField->GetData()+poField->GetDataSize()+nBytesToAdd, (char *)poField->GetData()+poField->GetDataSize(), nBytesToMove ); /* -------------------------------------------------------------------- */ /* Update the target fields info. */ /* -------------------------------------------------------------------- */ poField->Initialize( poField->GetFieldDefn(), poField->GetData(), poField->GetDataSize() + nBytesToAdd ); /* -------------------------------------------------------------------- */ /* Shift all following fields down, and update their data */ /* locations. */ /* -------------------------------------------------------------------- */ if( nBytesToAdd < 0 ) { for( i = iTarget+1; i < nFieldCount; i++ ) { char *pszOldDataLocation; pszOldDataLocation = (char *) paoFields[i].GetData(); paoFields[i].Initialize( paoFields[i].GetFieldDefn(), pszOldDataLocation + nBytesToAdd, paoFields[i].GetDataSize() ); } } else { for( i = nFieldCount-1; i > iTarget; i-- ) { char *pszOldDataLocation; pszOldDataLocation = (char *) paoFields[i].GetData(); paoFields[i].Initialize( paoFields[i].GetFieldDefn(), pszOldDataLocation + nBytesToAdd, paoFields[i].GetDataSize() ); } } return true; } /************************************************************************/ /* AddField() */ /************************************************************************/ /** * Add a new field to record. * * Add a new zero sized field to the record. The new field is always * added at the end of the record. * * NOTE: This method doesn't currently update the header information for * the record to include the field information for this field, so the * resulting record image isn't suitable for writing to disk. However, * everything else about the record state should be updated properly to * reflect the new field. * * @param poDefn the definition of the field to be added. * * @return the field object on success, or NULL on failure. */ ossimDDFField *ossimDDFRecord::AddField( ossimDDFFieldDefn *poDefn ) { /* -------------------------------------------------------------------- */ /* Reallocate the fields array larger by one, and initialize */ /* the new field. */ /* -------------------------------------------------------------------- */ ossimDDFField *paoNewFields; paoNewFields = new ossimDDFField[nFieldCount+1]; if( nFieldCount > 0 ) { memcpy( paoNewFields, paoFields, sizeof(ossimDDFField) * nFieldCount ); delete[] paoFields; } paoFields = paoNewFields; nFieldCount++; /* -------------------------------------------------------------------- */ /* Initialize the new field properly. */ /* -------------------------------------------------------------------- */ if( nFieldCount == 1 ) { paoFields[0].Initialize( poDefn, GetData(), 0 ); } else { paoFields[nFieldCount-1].Initialize( poDefn, paoFields[nFieldCount-2].GetData() + paoFields[nFieldCount-2].GetDataSize(), 0 ); } /* -------------------------------------------------------------------- */ /* Initialize field. */ /* -------------------------------------------------------------------- */ CreateDefaultFieldInstance( paoFields + nFieldCount-1, 0 ); return paoFields + (nFieldCount - 1); } /************************************************************************/ /* SetFieldRaw() */ /************************************************************************/ /** * Set the raw contents of a field instance. * * @param poField the field to set data within. * @param iIndexWithinField The instance of this field to replace. Must * be a value between 0 and GetRepeatCount(). If GetRepeatCount() is used, a * new instance of the field is appeneded. * @param pachRawData the raw data to replace this field instance with. * @param nRawDataSize the number of bytes pointed to by pachRawData. * * @return true on success or false on failure. */ int ossimDDFRecord::SetFieldRaw( ossimDDFField *poField, int iIndexWithinField, const char *pachRawData, int nRawDataSize ) { int iTarget, nRepeatCount; /* -------------------------------------------------------------------- */ /* Find which field we are to update. */ /* -------------------------------------------------------------------- */ for( iTarget = 0; iTarget < nFieldCount; iTarget++ ) { if( paoFields + iTarget == poField ) break; } if( iTarget == nFieldCount ) return false; nRepeatCount = poField->GetRepeatCount(); if( iIndexWithinField < 0 || iIndexWithinField > nRepeatCount ) return false; /* -------------------------------------------------------------------- */ /* Are we adding an instance? This is easier and different */ /* than replacing an existing instance. */ /* -------------------------------------------------------------------- */ if( iIndexWithinField == nRepeatCount || !poField->GetFieldDefn()->IsRepeating() ) { char *pachFieldData; int nOldSize; if( !poField->GetFieldDefn()->IsRepeating() && iIndexWithinField != 0 ) return false; nOldSize = poField->GetDataSize(); if( nOldSize == 0 ) nOldSize++; // for added DDF_FIELD_TERMINATOR. if( !ResizeField( poField, nOldSize + nRawDataSize ) ) return false; pachFieldData = (char *) poField->GetData(); memcpy( pachFieldData + nOldSize - 1, pachRawData, nRawDataSize ); pachFieldData[nOldSize+nRawDataSize-1] = OSSIM_DDF_FIELD_TERMINATOR; return true; } /* -------------------------------------------------------------------- */ /* Get a pointer to the start of the existing data for this */ /* iteration of the field. */ /* -------------------------------------------------------------------- */ const char *pachWrkData; int nInstanceSize; // We special case this to avoid alot of warnings when initializing // the field the first time. if( poField->GetDataSize() == 0 ) { pachWrkData = poField->GetData(); nInstanceSize = 0; } else { pachWrkData = poField->GetInstanceData( iIndexWithinField, &nInstanceSize ); } /* -------------------------------------------------------------------- */ /* Create new image of this whole field. */ /* -------------------------------------------------------------------- */ char *pachNewImage; int nPreBytes, nPostBytes, nNewFieldSize; nNewFieldSize = poField->GetDataSize() - nInstanceSize + nRawDataSize; pachNewImage = (char *) malloc(nNewFieldSize); nPreBytes = pachWrkData - poField->GetData(); nPostBytes = poField->GetDataSize() - nPreBytes - nInstanceSize; memcpy( pachNewImage, poField->GetData(), nPreBytes ); memcpy( pachNewImage + nPreBytes + nRawDataSize, poField->GetData() + nPreBytes + nInstanceSize, nPostBytes ); memcpy( pachNewImage + nPreBytes, pachRawData, nRawDataSize ); /* -------------------------------------------------------------------- */ /* Resize the field to the desired new size. */ /* -------------------------------------------------------------------- */ ResizeField( poField, nNewFieldSize ); memcpy( (void *) poField->GetData(), pachNewImage, nNewFieldSize ); free( pachNewImage ); return true; } /************************************************************************/ /* UpdateFieldRaw() */ /************************************************************************/ int ossimDDFRecord::UpdateFieldRaw( ossimDDFField *poField, int iIndexWithinField, int nStartOffset, int nOldSize, const char *pachRawData, int nRawDataSize ) { int iTarget, nRepeatCount; /* -------------------------------------------------------------------- */ /* Find which field we are to update. */ /* -------------------------------------------------------------------- */ for( iTarget = 0; iTarget < nFieldCount; iTarget++ ) { if( paoFields + iTarget == poField ) break; } if( iTarget == nFieldCount ) return false; nRepeatCount = poField->GetRepeatCount(); if( iIndexWithinField < 0 || iIndexWithinField >= nRepeatCount ) return false; /* -------------------------------------------------------------------- */ /* Figure out how much pre and post data there is. */ /* -------------------------------------------------------------------- */ char *pachWrkData; int nInstanceSize, nPostBytes, nPreBytes; pachWrkData = (char *) poField->GetInstanceData( iIndexWithinField, &nInstanceSize ); nPreBytes = pachWrkData - poField->GetData() + nStartOffset; nPostBytes = poField->GetDataSize() - nPreBytes - nOldSize; /* -------------------------------------------------------------------- */ /* If we aren't changing the size, just copy over the existing */ /* data. */ /* -------------------------------------------------------------------- */ if( nOldSize == nRawDataSize ) { memcpy( pachWrkData + nStartOffset, pachRawData, nRawDataSize ); return true; } /* -------------------------------------------------------------------- */ /* If we are shrinking, move in the new data, and shuffle down */ /* the old before resizing. */ /* -------------------------------------------------------------------- */ if( nRawDataSize < nOldSize ) { memcpy( ((char*) poField->GetData()) + nPreBytes, pachRawData, nRawDataSize ); memmove( ((char *) poField->GetData()) + nPreBytes + nRawDataSize, ((char *) poField->GetData()) + nPreBytes + nOldSize, nPostBytes ); } /* -------------------------------------------------------------------- */ /* Resize the whole buffer. */ /* -------------------------------------------------------------------- */ if( !ResizeField( poField, poField->GetDataSize() - nOldSize + nRawDataSize ) ) return false; /* -------------------------------------------------------------------- */ /* If we growing the buffer, shuffle up the post data, and */ /* move in our new values. */ /* -------------------------------------------------------------------- */ if( nRawDataSize >= nOldSize ) { memmove( ((char *) poField->GetData()) + nPreBytes + nRawDataSize, ((char *) poField->GetData()) + nPreBytes + nOldSize, nPostBytes ); memcpy( ((char*) poField->GetData()) + nPreBytes, pachRawData, nRawDataSize ); } return true; } /************************************************************************/ /* ResetDirectory() */ /* */ /* Re-prepares the directory information for the record. */ /************************************************************************/ int ossimDDFRecord::ResetDirectory() { int iField; /* -------------------------------------------------------------------- */ /* Eventually we should try to optimize the size of offset and */ /* field length. For now we will use 5 for each which is */ /* pretty big. */ /* -------------------------------------------------------------------- */ _sizeFieldPos = 5; _sizeFieldLength = 5; /* -------------------------------------------------------------------- */ /* Compute how large the directory needs to be. */ /* -------------------------------------------------------------------- */ int nEntrySize, nDirSize; nEntrySize = _sizeFieldPos + _sizeFieldLength + _sizeFieldTag; nDirSize = nEntrySize * nFieldCount + 1; /* -------------------------------------------------------------------- */ /* If the directory size is different than what is currently */ /* reserved for it, we must resize. */ /* -------------------------------------------------------------------- */ if( nDirSize != nFieldOffset ) { char *pachNewData; int nNewDataSize; nNewDataSize = nDataSize - nFieldOffset + nDirSize; pachNewData = (char *) malloc(nNewDataSize); memcpy( pachNewData + nDirSize, pachData + nFieldOffset, nNewDataSize - nDirSize ); for( iField = 0; iField < nFieldCount; iField++ ) { int nOffset; ossimDDFField *poField = GetField( iField ); nOffset = poField->GetData() - pachData - nFieldOffset + nDirSize; poField->Initialize( poField->GetFieldDefn(), pachNewData + nOffset, poField->GetDataSize() ); } free( pachData ); pachData = pachNewData; nDataSize = nNewDataSize; nFieldOffset = nDirSize; } /* -------------------------------------------------------------------- */ /* Now set each directory entry. */ /* -------------------------------------------------------------------- */ for( iField = 0; iField < nFieldCount; iField++ ) { ossimDDFField *poField = GetField( iField ); ossimDDFFieldDefn *poDefn = poField->GetFieldDefn(); char szFormat[128]; sprintf( szFormat, "%%%ds%%0%dd%%0%dd", _sizeFieldTag, _sizeFieldLength, _sizeFieldPos ); sprintf( pachData + nEntrySize * iField, szFormat, poDefn->GetName(), poField->GetDataSize(), poField->GetData() - pachData - nFieldOffset ); } pachData[nEntrySize * nFieldCount] = OSSIM_DDF_FIELD_TERMINATOR; return true; } /************************************************************************/ /* CreateDefaultFieldInstance() */ /************************************************************************/ /** * Initialize default instance. * * This method is normally only used internally by the AddField() method * to initialize the new field instance with default subfield values. It * installs default data for one instance of the field in the record * using the DDFFieldDefn::GetDefaultValue() method and * DDFRecord::SetFieldRaw(). * * @param poField the field within the record to be assign a default * instance. * @param iIndexWithinField the instance to set (may not have been tested with * values other than 0). * * @return true on success or false on failure. */ int ossimDDFRecord::CreateDefaultFieldInstance( ossimDDFField *poField, int iIndexWithinField ) { int nRawSize, nSuccess; char *pachRawData; pachRawData = poField->GetFieldDefn()->GetDefaultValue( &nRawSize ); if( pachRawData == NULL ) return false; nSuccess = SetFieldRaw( poField, iIndexWithinField, pachRawData, nRawSize); free( pachRawData ); return nSuccess; } /************************************************************************/ /* SetStringSubfield() */ /************************************************************************/ /** * Set a string subfield in record. * * The value of a given subfield is replaced with a new string value * formatted appropriately. * * @param pszField the field name to operate on. * @param iFieldIndex the field index to operate on (zero based). * @param pszSubfield the subfield name to operate on. * @param iSubfieldIndex the subfield index to operate on (zero based). * @param pszValue the new string to place in the subfield. This may be * arbitrary binary bytes if nValueLength is specified. * @param nValueLength the number of valid bytes in pszValue, may be -1 to * internally fetch with strlen(). * * @return true if successful, and false if not. */ int ossimDDFRecord::SetStringSubfield( const char *pszField, int iFieldIndex, const char *pszSubfield, int iSubfieldIndex, const char *pszValue, int nValueLength ) { /* -------------------------------------------------------------------- */ /* Fetch the field. If this fails, return zero. */ /* -------------------------------------------------------------------- */ ossimDDFField *poField; poField = FindField( pszField, iFieldIndex ); if( poField == NULL ) return false; /* -------------------------------------------------------------------- */ /* Get the subfield definition */ /* -------------------------------------------------------------------- */ ossimDDFSubfieldDefn *poSFDefn; poSFDefn = poField->GetFieldDefn()->FindSubfieldDefn( pszSubfield ); if( poSFDefn == NULL ) return false; /* -------------------------------------------------------------------- */ /* How long will the formatted value be? */ /* -------------------------------------------------------------------- */ int nFormattedLen; if( !poSFDefn->FormatStringValue( NULL, 0, &nFormattedLen, pszValue, nValueLength ) ) return false; /* -------------------------------------------------------------------- */ /* Get a pointer to the data. */ /* -------------------------------------------------------------------- */ int nMaxBytes; char *pachSubfieldData = (char *) poField->GetSubfieldData(poSFDefn, &nMaxBytes, iSubfieldIndex); /* -------------------------------------------------------------------- */ /* Add new instance if we have run out of data. */ /* -------------------------------------------------------------------- */ if( nMaxBytes == 0 || (nMaxBytes == 1 && pachSubfieldData[0] == OSSIM_DDF_FIELD_TERMINATOR) ) { CreateDefaultFieldInstance( poField, iSubfieldIndex ); // Refetch. pachSubfieldData = (char *) poField->GetSubfieldData(poSFDefn, &nMaxBytes, iSubfieldIndex); } /* -------------------------------------------------------------------- */ /* If the new length matches the existing length, just overlay */ /* and return. */ /* -------------------------------------------------------------------- */ int nExistingLength; poSFDefn->GetDataLength( pachSubfieldData, nMaxBytes, &nExistingLength ); if( nExistingLength == nFormattedLen ) { return poSFDefn->FormatStringValue( pachSubfieldData, nFormattedLen, NULL, pszValue, nValueLength ); } /* -------------------------------------------------------------------- */ /* We will need to resize the raw data. */ /* -------------------------------------------------------------------- */ const char *pachFieldInstData; int nInstanceSize, nStartOffset, nSuccess; char *pachNewData; pachFieldInstData = poField->GetInstanceData( iFieldIndex, &nInstanceSize ); nStartOffset = pachSubfieldData - pachFieldInstData; pachNewData = (char *) malloc(nFormattedLen); poSFDefn->FormatStringValue( pachNewData, nFormattedLen, NULL, pszValue, nValueLength ); nSuccess = UpdateFieldRaw( poField, iFieldIndex, nStartOffset, nExistingLength, pachNewData, nFormattedLen ); free( pachNewData ); return nSuccess; } /************************************************************************/ /* SetIntSubfield() */ /************************************************************************/ /** * Set an integer subfield in record. * * The value of a given subfield is replaced with a new integer value * formatted appropriately. * * @param pszField the field name to operate on. * @param iFieldIndex the field index to operate on (zero based). * @param pszSubfield the subfield name to operate on. * @param iSubfieldIndex the subfield index to operate on (zero based). * @param nNewValue the new value to place in the subfield. * * @return true if successful, and false if not. */ int ossimDDFRecord::SetIntSubfield( const char *pszField, int iFieldIndex, const char *pszSubfield, int iSubfieldIndex, int nNewValue ) { /* -------------------------------------------------------------------- */ /* Fetch the field. If this fails, return zero. */ /* -------------------------------------------------------------------- */ ossimDDFField *poField; poField = FindField( pszField, iFieldIndex ); if( poField == NULL ) return false; /* -------------------------------------------------------------------- */ /* Get the subfield definition */ /* -------------------------------------------------------------------- */ ossimDDFSubfieldDefn *poSFDefn; poSFDefn = poField->GetFieldDefn()->FindSubfieldDefn( pszSubfield ); if( poSFDefn == NULL ) return false; /* -------------------------------------------------------------------- */ /* How long will the formatted value be? */ /* -------------------------------------------------------------------- */ int nFormattedLen; if( !poSFDefn->FormatIntValue( NULL, 0, &nFormattedLen, nNewValue ) ) return false; /* -------------------------------------------------------------------- */ /* Get a pointer to the data. */ /* -------------------------------------------------------------------- */ int nMaxBytes; char *pachSubfieldData = (char *) poField->GetSubfieldData(poSFDefn, &nMaxBytes, iSubfieldIndex); /* -------------------------------------------------------------------- */ /* Add new instance if we have run out of data. */ /* -------------------------------------------------------------------- */ if( nMaxBytes == 0 || (nMaxBytes == 1 && pachSubfieldData[0] == OSSIM_DDF_FIELD_TERMINATOR) ) { CreateDefaultFieldInstance( poField, iSubfieldIndex ); // Refetch. pachSubfieldData = (char *) poField->GetSubfieldData(poSFDefn, &nMaxBytes, iSubfieldIndex); } /* -------------------------------------------------------------------- */ /* If the new length matches the existing length, just overlay */ /* and return. */ /* -------------------------------------------------------------------- */ int nExistingLength; poSFDefn->GetDataLength( pachSubfieldData, nMaxBytes, &nExistingLength ); if( nExistingLength == nFormattedLen ) { return poSFDefn->FormatIntValue( pachSubfieldData, nFormattedLen, NULL, nNewValue ); } /* -------------------------------------------------------------------- */ /* We will need to resize the raw data. */ /* -------------------------------------------------------------------- */ const char *pachFieldInstData; int nInstanceSize, nStartOffset, nSuccess; char *pachNewData; pachFieldInstData = poField->GetInstanceData( iFieldIndex, &nInstanceSize ); nStartOffset = pachSubfieldData - pachFieldInstData; pachNewData = (char *) malloc(nFormattedLen); poSFDefn->FormatIntValue( pachNewData, nFormattedLen, NULL, nNewValue ); nSuccess = UpdateFieldRaw( poField, iFieldIndex, nStartOffset, nExistingLength, pachNewData, nFormattedLen ); free( pachNewData ); return nSuccess; } /************************************************************************/ /* SetFloatSubfield() */ /************************************************************************/ /** * Set a float subfield in record. * * The value of a given subfield is replaced with a new float value * formatted appropriately. * * @param pszField the field name to operate on. * @param iFieldIndex the field index to operate on (zero based). * @param pszSubfield the subfield name to operate on. * @param iSubfieldIndex the subfield index to operate on (zero based). * @param dfNewValue the new value to place in the subfield. * * @return true if successful, and false if not. */ int ossimDDFRecord::SetFloatSubfield( const char *pszField, int iFieldIndex, const char *pszSubfield, int iSubfieldIndex, double dfNewValue ) { /* -------------------------------------------------------------------- */ /* Fetch the field. If this fails, return zero. */ /* -------------------------------------------------------------------- */ ossimDDFField *poField; poField = FindField( pszField, iFieldIndex ); if( poField == NULL ) return false; /* -------------------------------------------------------------------- */ /* Get the subfield definition */ /* -------------------------------------------------------------------- */ ossimDDFSubfieldDefn *poSFDefn; poSFDefn = poField->GetFieldDefn()->FindSubfieldDefn( pszSubfield ); if( poSFDefn == NULL ) return false; /* -------------------------------------------------------------------- */ /* How long will the formatted value be? */ /* -------------------------------------------------------------------- */ int nFormattedLen; if( !poSFDefn->FormatFloatValue( NULL, 0, &nFormattedLen, dfNewValue ) ) return false; /* -------------------------------------------------------------------- */ /* Get a pointer to the data. */ /* -------------------------------------------------------------------- */ int nMaxBytes; char *pachSubfieldData = (char *) poField->GetSubfieldData(poSFDefn, &nMaxBytes, iSubfieldIndex); /* -------------------------------------------------------------------- */ /* Add new instance if we have run out of data. */ /* -------------------------------------------------------------------- */ if( nMaxBytes == 0 || (nMaxBytes == 1 && pachSubfieldData[0] == OSSIM_DDF_FIELD_TERMINATOR) ) { CreateDefaultFieldInstance( poField, iSubfieldIndex ); // Refetch. pachSubfieldData = (char *) poField->GetSubfieldData(poSFDefn, &nMaxBytes, iSubfieldIndex); } /* -------------------------------------------------------------------- */ /* If the new length matches the existing length, just overlay */ /* and return. */ /* -------------------------------------------------------------------- */ int nExistingLength; poSFDefn->GetDataLength( pachSubfieldData, nMaxBytes, &nExistingLength ); if( nExistingLength == nFormattedLen ) { return poSFDefn->FormatFloatValue( pachSubfieldData, nFormattedLen, NULL, dfNewValue ); } /* -------------------------------------------------------------------- */ /* We will need to resize the raw data. */ /* -------------------------------------------------------------------- */ const char *pachFieldInstData; int nInstanceSize, nStartOffset, nSuccess; char *pachNewData; pachFieldInstData = poField->GetInstanceData( iFieldIndex, &nInstanceSize ); nStartOffset = (int) (pachSubfieldData - pachFieldInstData); pachNewData = (char *) malloc(nFormattedLen); poSFDefn->FormatFloatValue( pachNewData, nFormattedLen, NULL, dfNewValue ); nSuccess = UpdateFieldRaw( poField, iFieldIndex, nStartOffset, nExistingLength, pachNewData, nFormattedLen ); free( pachNewData ); return nSuccess; } ossim-Miami-2.9.1/src/imaging/ossimDdfsubfielddefn.cpp000066400000000000000000000766201352751253100227570ustar00rootroot00000000000000/****************************************************************************** * Copied from "gdal" project. See licence below. * * Project: ISO 8211 Access * Purpose: Implements the DDFSubfieldDefn class. * Author: Frank Warmerdam, warmerda@home.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** * $Id: ossimDdfsubfielddefn.cpp 23245 2015-04-08 20:53:04Z rashadkm $ */ #include #include #include #include /************************************************************************/ /* DDFSubfieldDefn() */ /************************************************************************/ ossimDDFSubfieldDefn::ossimDDFSubfieldDefn() { pszName = NULL; bIsVariable = true; nFormatWidth = 0; chFormatDelimeter = OSSIM_DDF_UNIT_TERMINATOR; eBinaryFormat = NotBinary; eType = DDFString; pszFormatString = strdup(""); nMaxBufChars = 0; pachBuffer = NULL; } /************************************************************************/ /* ~DDFSubfieldDefn() */ /************************************************************************/ ossimDDFSubfieldDefn::~ossimDDFSubfieldDefn() { free( pszName ); free( pszFormatString ); free( pachBuffer ); } /************************************************************************/ /* SetName() */ /************************************************************************/ void ossimDDFSubfieldDefn::SetName( const char * pszNewName ) { int i; free( pszName ); pszName = strdup( pszNewName ); for( i = (int)strlen(pszName)-1; i > 0 && pszName[i] == ' '; i-- ) pszName[i] = '\0'; } /************************************************************************/ /* SetFormat() */ /* */ /* While interpreting the format string we don't support: */ /* */ /* o Passing an explicit terminator for variable length field. */ /* o 'X' for unused data ... this should really be filtered */ /* out by DDFFieldDefn::ApplyFormats(), but isn't. */ /* o 'B' bitstrings that aren't a multiple of eight. */ /************************************************************************/ int ossimDDFSubfieldDefn::SetFormat( const char * pszFormat ) { free( pszFormatString ); pszFormatString = strdup( pszFormat ); /* -------------------------------------------------------------------- */ /* These values will likely be used. */ /* -------------------------------------------------------------------- */ if( pszFormatString[1] == '(' ) { nFormatWidth = atoi(pszFormatString+2); bIsVariable = nFormatWidth == 0; } else bIsVariable = true; /* -------------------------------------------------------------------- */ /* Interpret the format string. */ /* -------------------------------------------------------------------- */ switch( pszFormatString[0] ) { case 'A': case 'C': // It isn't clear to me how this is different than 'A' eType = DDFString; break; case 'R': eType = DDFFloat; break; case 'I': case 'S': eType = DDFInt; break; case 'B': case 'b': // Is the width expressed in bits? (is it a bitstring) bIsVariable = false; if( pszFormatString[1] == '(' ) { // CPLAssert( atoi(pszFormatString+2) % 8 == 0 ); nFormatWidth = atoi(pszFormatString+2) / 8; eBinaryFormat = SInt; // good default, works for SDTS. if( nFormatWidth < 5 ) eType = DDFInt; else eType = DDFBinaryString; } // or do we have a binary type indicator? (is it binary) else { eBinaryFormat = (DDFBinaryFormat) (pszFormatString[1] - '0'); nFormatWidth = atoi(pszFormatString+2); if( eBinaryFormat == SInt || eBinaryFormat == UInt ) eType = DDFInt; else eType = DDFFloat; } break; case 'X': // 'X' is extra space, and shouldn't be directly assigned to a // subfield ... I haven't encountered it in use yet though. ossimNotify(ossimNotifyLevel_WARN) << "Format type of `%c' not supported.\n" << pszFormatString[0] << std::endl; // CPLAssert( false ); return false; default: ossimNotify(ossimNotifyLevel_WARN) << "Format type of `%c' not recognised.\n" << pszFormatString[0] << std::endl; // CPLAssert( false ); return false; } return true; } /************************************************************************/ /* Dump() */ /************************************************************************/ /** * Write out subfield definition info to debugging file. * * A variety of information about this field definition is written to the * give debugging file handle. * * @param fp The standard io file handle to write to. ie. stderr */ void ossimDDFSubfieldDefn::Dump( FILE * fp ) { fprintf( fp, " DDFSubfieldDefn:\n" ); fprintf( fp, " Label = `%s'\n", pszName ); fprintf( fp, " FormatString = `%s'\n", pszFormatString ); } /************************************************************************/ /* GetDataLength() */ /* */ /* This method will scan for the end of a variable field. */ /************************************************************************/ /** * Scan for the end of variable length data. Given a pointer to the data * for this subfield (from within a DDFRecord) this method will return the * number of bytes which are data for this subfield. The number of bytes * consumed as part of this field can also be fetched. This number may * be one longer than the length if there is a terminator character * used.

* * This method is mainly for internal use, or for applications which * want the raw binary data to interpret themselves. Otherwise use one * of ExtractStringData(), ExtractIntData() or ExtractFloatData(). * * @param pachSourceData The pointer to the raw data for this field. This * may have come from DDFRecord::GetData(), taking into account skip factors * over previous subfields data. * @param nMaxBytes The maximum number of bytes that are accessable after * pachSourceData. * @param pnConsumedBytes Pointer to an integer into which the number of * bytes consumed by this field should be written. May be NULL to ignore. * * @return The number of bytes at pachSourceData which are actual data for * this record (not including unit, or field terminator). */ int ossimDDFSubfieldDefn::GetDataLength( const char * pachSourceData, int nMaxBytes, int * pnConsumedBytes ) { if( !bIsVariable ) { if( nFormatWidth > nMaxBytes ) { ossimNotify(ossimNotifyLevel_WARN) << "Only %d bytes available for subfield %s with\n" << "format string %s ... returning shortened data." << nMaxBytes << pszName << pszFormatString << std::endl; if( pnConsumedBytes != NULL ) *pnConsumedBytes = nMaxBytes; return nMaxBytes; } else { if( pnConsumedBytes != NULL ) *pnConsumedBytes = nFormatWidth; return nFormatWidth; } } else { int nLength = 0; int bCheckFieldTerminator = true; /* We only check for the field terminator because of some buggy * datasets with missing format terminators. However, we have found * the field terminator is a legal character within the fields of * some extended datasets (such as JP34NC94.000). So we don't check * for the field terminator if the field appears to be multi-byte * which we established by the first character being out of the * ASCII printable range (32-127). */ if( pachSourceData[0] < 32 || pachSourceData[0] >= 127 ) bCheckFieldTerminator = false; while( nLength < nMaxBytes && pachSourceData[nLength] != chFormatDelimeter ) { if( bCheckFieldTerminator && pachSourceData[nLength] == OSSIM_DDF_FIELD_TERMINATOR ) break; nLength++; } if( pnConsumedBytes != NULL ) { if( nMaxBytes == 0 ) *pnConsumedBytes = nLength; else *pnConsumedBytes = nLength+1; } return nLength; } } /************************************************************************/ /* ExtractStringData() */ /************************************************************************/ /** * Extract a zero terminated string containing the data for this subfield. * Given a pointer to the data * for this subfield (from within a DDFRecord) this method will return the * data for this subfield. The number of bytes * consumed as part of this field can also be fetched. This number may * be one longer than the string length if there is a terminator character * used.

* * This function will return the raw binary data of a subfield for * types other than DDFString, including data past zero chars. This is * the standard way of extracting DDFBinaryString subfields for instance.

* * @param pachSourceData The pointer to the raw data for this field. This * may have come from DDFRecord::GetData(), taking into account skip factors * over previous subfields data. * @param nMaxBytes The maximum number of bytes that are accessable after * pachSourceData. * @param pnConsumedBytes Pointer to an integer into which the number of * bytes consumed by this field should be written. May be NULL to ignore. * This is used as a skip factor to increment pachSourceData to point to the * next subfields data. * * @return A pointer to a buffer containing the data for this field. The * returned pointer is to an internal buffer which is invalidated on the * next ExtractStringData() call on this DDFSubfieldDefn(). It should not * be freed by the application. * * @see ExtractIntData(), ExtractFloatData() */ const char * ossimDDFSubfieldDefn::ExtractStringData( const char * pachSourceData, int nMaxBytes, int * pnConsumedBytes ) { int nLength = GetDataLength( pachSourceData, nMaxBytes, pnConsumedBytes ); /* -------------------------------------------------------------------- */ /* Do we need to grow the buffer. */ /* -------------------------------------------------------------------- */ if( nMaxBufChars < nLength+1 ) { free( pachBuffer ); nMaxBufChars = nLength+1; pachBuffer = (char *) malloc(nMaxBufChars); } /* -------------------------------------------------------------------- */ /* Copy the data to the buffer. We use memcpy() so that it */ /* will work for binary data. */ /* -------------------------------------------------------------------- */ memcpy( pachBuffer, pachSourceData, nLength ); pachBuffer[nLength] = '\0'; return pachBuffer; } /************************************************************************/ /* ExtractFloatData() */ /************************************************************************/ /** * Extract a subfield value as a float. Given a pointer to the data * for this subfield (from within a DDFRecord) this method will return the * floating point data for this subfield. The number of bytes * consumed as part of this field can also be fetched. This method may be * called for any type of subfield, and will return zero if the subfield is * not numeric. * * @param pachSourceData The pointer to the raw data for this field. This * may have come from DDFRecord::GetData(), taking into account skip factors * over previous subfields data. * @param nMaxBytes The maximum number of bytes that are accessable after * pachSourceData. * @param pnConsumedBytes Pointer to an integer into which the number of * bytes consumed by this field should be written. May be NULL to ignore. * This is used as a skip factor to increment pachSourceData to point to the * next subfields data. * * @return The subfield's numeric value (or zero if it isn't numeric). * * @see ExtractIntData(), ExtractStringData() */ double ossimDDFSubfieldDefn::ExtractFloatData( const char * pachSourceData, int nMaxBytes, int * pnConsumedBytes ) { switch( pszFormatString[0] ) { case 'A': case 'I': case 'R': case 'S': case 'C': return atof(ExtractStringData(pachSourceData, nMaxBytes, pnConsumedBytes)); case 'B': case 'b': { unsigned char abyData[8]; // CPLAssert( nFormatWidth <= nMaxBytes ); if( pnConsumedBytes != NULL ) *pnConsumedBytes = nFormatWidth; // Byte swap the data if it isn't in machine native format. // In any event we copy it into our buffer to ensure it is // word aligned. #ifdef CPL_LSB if( pszFormatString[0] == 'B' ) #else if( pszFormatString[0] == 'b' ) #endif { for( int i = 0; i < nFormatWidth; i++ ) abyData[nFormatWidth-i-1] = pachSourceData[i]; } else { memcpy( abyData, pachSourceData, nFormatWidth ); } // Interpret the bytes of data. switch( eBinaryFormat ) { case UInt: if( nFormatWidth == 1 ) { return( abyData[0] ); } else if( nFormatWidth == 2 ) { ossim_uint16* ptr = (ossim_uint16*) abyData; return *ptr; } else if( nFormatWidth == 4 ) { ossim_uint32* ptr = (ossim_uint32*) abyData; return *ptr; } else { // CPLAssert( false ); return 0.0; } case SInt: if( nFormatWidth == 1 ) { signed char* ptr = (signed char*) abyData; return *ptr; } else if( nFormatWidth == 2 ) { ossim_int16* ptr = (ossim_int16*) abyData; return *ptr; } else if( nFormatWidth == 4 ) { ossim_int32* ptr = (ossim_int32*) abyData; return *ptr; } else { // CPLAssert( false ); return 0.0; } case FloatReal: if( nFormatWidth == 4 ) { float* ptr = (float*) abyData; return *ptr; } else if( nFormatWidth == 8 ) { double* ptr = (double*) abyData; return *ptr; } else { // CPLAssert( false ); return 0.0; } case NotBinary: case FPReal: case FloatComplex: // CPLAssert( false ); return 0.0; } break; // end of 'b'/'B' case. } default: // CPLAssert( false ); return 0.0; } // CPLAssert( false ); return 0.0; } /************************************************************************/ /* ExtractIntData() */ /************************************************************************/ /** * Extract a subfield value as an integer. Given a pointer to the data * for this subfield (from within a DDFRecord) this method will return the * int data for this subfield. The number of bytes * consumed as part of this field can also be fetched. This method may be * called for any type of subfield, and will return zero if the subfield is * not numeric. * * @param pachSourceData The pointer to the raw data for this field. This * may have come from DDFRecord::GetData(), taking into account skip factors * over previous subfields data. * @param nMaxBytes The maximum number of bytes that are accessable after * pachSourceData. * @param pnConsumedBytes Pointer to an integer into which the number of * bytes consumed by this field should be written. May be NULL to ignore. * This is used as a skip factor to increment pachSourceData to point to the * next subfields data. * * @return The subfield's numeric value (or zero if it isn't numeric). * * @see ExtractFloatData(), ExtractStringData() */ int ossimDDFSubfieldDefn::ExtractIntData( const char * pachSourceData, int nMaxBytes, int * pnConsumedBytes ) { switch( pszFormatString[0] ) { case 'A': case 'I': case 'R': case 'S': case 'C': return atoi(ExtractStringData(pachSourceData, nMaxBytes, pnConsumedBytes)); case 'B': case 'b': { unsigned char abyData[8]; if( nFormatWidth > nMaxBytes ) { ossimNotify(ossimNotifyLevel_WARN) << "Attempt to extract int subfield %s with format %s\n" << "failed as only %d bytes available. Using zero." << pszName << pszFormatString << nMaxBytes << std::endl; return 0; } if( pnConsumedBytes != NULL ) *pnConsumedBytes = nFormatWidth; // Byte swap the data if it isn't in machine native format. // In any event we copy it into our buffer to ensure it is // word aligned. #ifdef CPL_LSB if( pszFormatString[0] == 'B' ) #else if( pszFormatString[0] == 'b' ) #endif { for( int i = 0; i < nFormatWidth; i++ ) abyData[nFormatWidth-i-1] = pachSourceData[i]; } else { memcpy( abyData, pachSourceData, nFormatWidth ); } // Interpret the bytes of data. switch( eBinaryFormat ) { case UInt: if( nFormatWidth == 4 ) { ossim_uint32* ptr = (ossim_uint32*) abyData; return *ptr; } else if( nFormatWidth == 1 ) { return( abyData[0] ); } else if( nFormatWidth == 2 ) { ossim_uint16* ptr = (ossim_uint16*)abyData; return *ptr; } else { // CPLAssert( false ); return 0; } case SInt: if( nFormatWidth == 4 ) { ossim_int32* ptr = (ossim_int32 *) abyData; return *ptr; } else if( nFormatWidth == 1 ) { signed char* ptr = (signed char *) abyData; return *ptr; } else if( nFormatWidth == 2 ) { ossim_int16* ptr = (ossim_int16 *) abyData; return *ptr; } else { // CPLAssert( false ); return 0; } case FloatReal: if( nFormatWidth == 4 ) { float* ptr = (float *) abyData; return (int) *ptr; } else if( nFormatWidth == 8 ) { double* ptr = (double *) abyData; return (int) *ptr; } else { // CPLAssert( false ); return 0; } case NotBinary: case FPReal: case FloatComplex: // CPLAssert( false ); return 0; } break; // end of 'b'/'B' case. } default: // CPLAssert( false ); return 0; } // CPLAssert( false ); return 0; } /************************************************************************/ /* DumpData() */ /* */ /* Dump the instance data for this subfield from a data */ /* record. This fits into the output dump stream of a DDFField. */ /************************************************************************/ /** * Dump subfield value to debugging file. * * @param pachData Pointer to data for this subfield. * @param nMaxBytes Maximum number of bytes available in pachData. * @param fp File to write report to. */ void ossimDDFSubfieldDefn::DumpData( const char * pachData, int nMaxBytes, FILE * fp ) { if( eType == DDFFloat ) fprintf( fp, " Subfield `%s' = %f\n", pszName, ExtractFloatData( pachData, nMaxBytes, NULL ) ); else if( eType == DDFInt ) fprintf( fp, " Subfield `%s' = %d\n", pszName, ExtractIntData( pachData, nMaxBytes, NULL ) ); else if( eType == DDFBinaryString ) { int nBytes, i; ossim_uint8 *pabyBString = (ossim_uint8 *) ExtractStringData( pachData, nMaxBytes, &nBytes ); fprintf( fp, " Subfield `%s' = 0x", pszName ); for( i = 0; i < std::min(nBytes,24); i++ ) fprintf( fp, "%02X", pabyBString[i] ); if( nBytes > 24 ) fprintf( fp, "%s", "..." ); fprintf( fp, "\n" ); } else fprintf( fp, " Subfield `%s' = `%s'\n", pszName, ExtractStringData( pachData, nMaxBytes, NULL ) ); } /************************************************************************/ /* GetDefaultValue() */ /************************************************************************/ /** * Get default data. * * Returns the default subfield data contents for this subfield definition. * For variable length numbers this will normally be "0". * For variable length strings it will be "". For fixed * length numbers it is zero filled. For fixed length strings it is space * filled. For binary numbers it is binary zero filled. * * @param pachData the buffer into which the returned default will be placed. * May be NULL if just querying default size. * @param nBytesAvailable the size of pachData in bytes. * @param pnBytesUsed will receive the size of the subfield default data in * bytes. * * @return true on success or false on failure or if the passed buffer is too * small to hold the default. */ int ossimDDFSubfieldDefn::GetDefaultValue( char *pachData, int nBytesAvailable, int *pnBytesUsed ) { int nDefaultSize; if( !bIsVariable ) nDefaultSize = nFormatWidth; else nDefaultSize = 1; if( pnBytesUsed != NULL ) *pnBytesUsed = nDefaultSize; if( pachData == NULL ) return true; if( nBytesAvailable < nDefaultSize ) return false; if( bIsVariable ) { pachData[0] = OSSIM_DDF_UNIT_TERMINATOR; } else { if( GetBinaryFormat() == NotBinary ) { if( GetType() == DDFInt || GetType() == DDFFloat ) memset( pachData, 0, nDefaultSize ); else memset( pachData, ' ', nDefaultSize ); } else memset( pachData, 0, nDefaultSize ); } return true; } /************************************************************************/ /* FormatStringValue() */ /************************************************************************/ /** * Format string subfield value. * * Returns a buffer with the passed in string value reformatted in a way * suitable for storage in a DDFField for this subfield. */ int ossimDDFSubfieldDefn::FormatStringValue( char *pachData, int nBytesAvailable, int *pnBytesUsed, const char *pszValue, int nValueLength ) { int nSize; if( nValueLength == -1 ) nValueLength = (int)strlen(pszValue); if( bIsVariable ) { nSize = nValueLength + 1; } else { nSize = nFormatWidth; } if( pnBytesUsed != NULL ) *pnBytesUsed = nSize; if( pachData == NULL ) return true; if( nBytesAvailable < nSize ) return false; if( bIsVariable ) { strncpy( pachData, pszValue, nSize-1 ); pachData[nSize-1] = OSSIM_DDF_UNIT_TERMINATOR; } else { if( GetBinaryFormat() == NotBinary ) { memset( pachData, ' ', nSize ); memcpy( pachData, pszValue, std::min(nValueLength,nSize) ); } else { memset( pachData, 0, nSize ); memcpy( pachData, pszValue, std::min(nValueLength,nSize) ); } } return true; } /************************************************************************/ /* FormatIntValue() */ /************************************************************************/ /** * Format int subfield value. * * Returns a buffer with the passed in int value reformatted in a way * suitable for storage in a DDFField for this subfield. */ int ossimDDFSubfieldDefn::FormatIntValue( char *pachData, int nBytesAvailable, int *pnBytesUsed, int nNewValue ) { int nSize; char szWork[30]; sprintf( szWork, "%d", nNewValue ); if( bIsVariable ) { nSize = (int)strlen(szWork) + 1; } else { nSize = nFormatWidth; if( GetBinaryFormat() == NotBinary && (int) strlen(szWork) > nSize ) return false; } if( pnBytesUsed != NULL ) *pnBytesUsed = nSize; if( pachData == NULL ) return true; if( nBytesAvailable < nSize ) return false; if( bIsVariable ) { strncpy( pachData, szWork, nSize-1 ); pachData[nSize-1] = OSSIM_DDF_UNIT_TERMINATOR; } else { ossim_uint32 nMask = 0xff; int i; switch( GetBinaryFormat() ) { case NotBinary: memset( pachData, '0', nSize ); strncpy( pachData + nSize - strlen(szWork), szWork, strlen(szWork) ); break; case UInt: case SInt: for( i = 0; i < nFormatWidth; i++ ) { int iOut; // big endian required? if( pszFormatString[0] == 'B' ) iOut = nFormatWidth - i - 1; else iOut = i; pachData[iOut] = (nNewValue & nMask) >> (i*8); nMask *= 256; } break; case FloatReal: // CPLAssert( false ); break; default: // CPLAssert( false ); break; } } return true; } /************************************************************************/ /* FormatFloatValue() */ /************************************************************************/ /** * Format float subfield value. * * Returns a buffer with the passed in float value reformatted in a way * suitable for storage in a DDFField for this subfield. */ int ossimDDFSubfieldDefn::FormatFloatValue( char *pachData, int nBytesAvailable, int *pnBytesUsed, double dfNewValue ) { int nSize; char szWork[120]; sprintf( szWork, "%.16g", dfNewValue ); if( bIsVariable ) { nSize = (int)strlen(szWork) + 1; } else { nSize = nFormatWidth; if( GetBinaryFormat() == NotBinary && (int) strlen(szWork) > nSize ) return false; } if( pnBytesUsed != NULL ) *pnBytesUsed = nSize; if( pachData == NULL ) return true; if( nBytesAvailable < nSize ) return false; if( bIsVariable ) { strncpy( pachData, szWork, nSize-1 ); pachData[nSize-1] = OSSIM_DDF_UNIT_TERMINATOR; } else { if( GetBinaryFormat() == NotBinary ) { memset( pachData, '0', nSize ); strncpy( pachData + nSize - strlen(szWork), szWork, strlen(szWork) ); } else { // CPLAssert( false ); /* implement me */ } } return true; } ossim-Miami-2.9.1/src/imaging/ossimDdfutils.cpp000066400000000000000000000100531352751253100214510ustar00rootroot00000000000000/****************************************************************************** * Copied from "gdal" project. See licence below. * * Project: ISO 8211 Access * Purpose: Various utility functions. * Author: Frank Warmerdam, warmerda@home.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************** * $Id: ossimDdfutils.cpp 9094 2006-06-13 19:12:40Z dburken $ */ #include #include /************************************************************************/ /* DDFScanInt() */ /* */ /* Read up to nMaxChars from the passed string, and interpret */ /* as an integer. */ /************************************************************************/ long ossimDDFScanInt( const char * pszString, int nMaxChars ) { char szWorking[33]; if( nMaxChars > 32 || nMaxChars == 0 ) nMaxChars = 32; memcpy( szWorking, pszString, nMaxChars ); szWorking[nMaxChars] = '\0'; return( atoi(szWorking) ); } /************************************************************************/ /* DDFScanVariable() */ /* */ /* Establish the length of a variable length string in a */ /* record. */ /************************************************************************/ int ossimDDFScanVariable( const char *pszRecord, int nMaxChars, int nDelimChar ) { int i; for( i = 0; i < nMaxChars-1 && pszRecord[i] != nDelimChar; i++ ) {} return i; } /************************************************************************/ /* DDFFetchVariable() */ /* */ /* Fetch a variable length string from a record, and allocate */ /* it as a new string (with CPLStrdup()). */ /************************************************************************/ char * ossimDDFFetchVariable( const char *pszRecord, int nMaxChars, int nDelimChar1, int nDelimChar2, int *pnConsumedChars ) { int i; char *pszReturn; for( i = 0; i < nMaxChars-1 && pszRecord[i] != nDelimChar1 && pszRecord[i] != nDelimChar2; i++ ) {} *pnConsumedChars = i; if( i < nMaxChars && (pszRecord[i] == nDelimChar1 || pszRecord[i] == nDelimChar2) ) (*pnConsumedChars)++; pszReturn = (char *) malloc(i+1); pszReturn[i] = '\0'; strncpy( pszReturn, pszRecord, i ); return pszReturn; } ossim-Miami-2.9.1/src/imaging/ossimDespeckleFilter.cpp000066400000000000000000000165041352751253100227470ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //******************************************************************* // $Id: ossimDespeckleFilter.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $ #include #include #include #include #include #include static const ossimKeyword FILTER_RADIUS_KW = ossimKeyword("filter_radius", ""); RTTI_DEF1(ossimDespeckleFilter, "ossimDespeckleFilter", ossimImageSourceFilter); ossimDespeckleFilter::ossimDespeckleFilter() : ossimImageSourceFilter(), theTile(NULL), theFilterRadius(1) { } ossimDespeckleFilter::ossimDespeckleFilter(ossimImageSource* inputSource, ossim_uint32 filter_radius) : ossimImageSourceFilter(inputSource), theTile(NULL), theFilterRadius(filter_radius) { initialize(); } ossimDespeckleFilter::~ossimDespeckleFilter() { theTile = 0; } ossimRefPtr ossimDespeckleFilter::getTile(const ossimIrect& tileRect,ossim_uint32 resLevel) { if (!theInputConnection) return NULL; if (!isSourceEnabled()) return theInputConnection->getTile(tileRect, resLevel); if (!theTile.valid()) { allocate(); if (!theTile.valid()) // Throw exception??? return theInputConnection->getTile(tileRect, resLevel); } // Fetch input tile with kernel margins: ossimIrect requestRect(tileRect.ul().x - theFilterRadius, tileRect.ul().y - theFilterRadius, tileRect.lr().x + theFilterRadius, tileRect.lr().y + theFilterRadius); ossimRefPtr inputTile = theInputConnection->getTile(requestRect, resLevel); if (!inputTile.valid()) return NULL; ossim_uint32 w = tileRect.width(); ossim_uint32 h = tileRect.height(); ossim_uint32 tw = theTile->getWidth(); ossim_uint32 th = theTile->getHeight(); theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tw*th)) theTile->initialize(); theTile->makeBlank(); theTile->setOrigin(tileRect.ul()); ossimDataObjectStatus status = inputTile->getDataObjectStatus(); if ((status == OSSIM_NULL) || (status == OSSIM_EMPTY)) return inputTile; switch(inputTile->getScalarType()) { case OSSIM_UCHAR: despeckle(static_cast(0), inputTile); break; case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: despeckle(static_cast(0), inputTile); break; case OSSIM_SSHORT16: despeckle(static_cast(0), inputTile); break; case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: despeckle(static_cast(0), inputTile); break; case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: despeckle(static_cast(0), inputTile); break; default: theTile->loadTile(inputTile.get()); } theTile->validate(); return theTile; } template void ossimDespeckleFilter::despeckle(T /* dummyVariable */, ossimRefPtr inputTile) { ossimIpt inUL (inputTile->getImageRectangle().ul()); ossimIpt inLR (inputTile->getImageRectangle().lr()); ossimIpt outUL (theTile->getImageRectangle().ul()); ossimIpt outLR (theTile->getImageRectangle().lr()); long inWidth = inputTile->getWidth(); long outWidth = theTile->getWidth(); long num_bands = theTile->getNumberOfBands(); // Loop over all bands first: for(long b = 0; b < num_bands; ++b) { const T* inbuf = (const T*) inputTile->getBuf(b); T* outBuf = (T*) theTile->getBuf(b); T null_pixel = (T) inputTile->getNullPix(b); for (long y=outUL.y; y<=outLR.y; y++) { for (long x=outUL.x; x<=outLR.x; x++) { bool found_valid = false; long idx = (y - inUL.y)*inWidth + x - inUL.x; // index to input buffer long odx = (y-outUL.y)*outWidth + x - outUL.x;// index to output buffer T pixel = inbuf[idx]; if (pixel != null_pixel) { // Inside loop over input "kernel" pixels centered at x, y: for (long iy=-theFilterRadius; (iy<=theFilterRadius) && !found_valid; iy++) { // Compute row number in image space and skip this row if outside input tile: long row = y + iy; if ((row < inUL.y) || (row > inLR.y)) continue; for (long ix=-theFilterRadius; (ix<=theFilterRadius) && !found_valid; ix++) { // Compute column number in image space and skip this col if outside input tile: long col = x + ix; if ((col < inUL.x) || (col > inLR.x)) continue; // Compute offset into input buffer for the neighbor pixel. If we aren't at the // kernel center, consider if valid neighbor was found: idx = (row - inUL.y)*inWidth + col - inUL.x; if ( ((iy != 0) || (ix != 0)) && (inbuf[idx] != null_pixel) ) found_valid = true; } } } // Finished scanning neighborhood. Save output to tile buffer: if (found_valid) outBuf[odx] = pixel; else outBuf[odx] = null_pixel; } } } } void ossimDespeckleFilter::initialize() { ossimImageSourceFilter::initialize(); theTile = NULL; } void ossimDespeckleFilter::allocate() { if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, theInputConnection); theTile->initialize(); } } bool ossimDespeckleFilter::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, FILTER_RADIUS_KW, theFilterRadius, true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimDespeckleFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = kwl.find(prefix, FILTER_RADIUS_KW); if (lookup) theFilterRadius = ossimString(lookup).toInt32(); return ossimImageSourceFilter::loadState(kwl, prefix); } void ossimDespeckleFilter::setProperty(ossimRefPtr property) { ossimString name = property->getName(); if(name == "Filter Radius") theFilterRadius = property->valueToString().toInt32(); else ossimImageSourceFilter::setProperty(property); } ossimRefPtr ossimDespeckleFilter::getProperty(const ossimString& name)const { if(name == "Filter Radius") { ossimProperty* prop = new ossimNumericProperty(name, ossimString::toString(theFilterRadius), 1, 16.0); prop->setCacheRefreshBit(); return prop; } return ossimImageSourceFilter::getProperty(name); } void ossimDespeckleFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("Filter Radius"); } ossim-Miami-2.9.1/src/imaging/ossimDilationFilter.cpp000066400000000000000000000226311352751253100226110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimDilationFilter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimDilationFilter, "ossimDilationFilter", ossimImageSourceFilter); // Keywords used throughout. static const ossimString WINDOW_SIZE_KW = "window_size"; static const ossimString RECURSIVE_DILATION_KW = "recursive_dilation"; ossimDilationFilter::ossimDilationFilter(ossimObject* owner) :ossimImageSourceFilter(owner), theTile(0), theTempTile(0), theWindowSize(15), theRecursiveFlag(false), theNullFoundFlag(false) { setDescription(ossimString("Dilation Filter")); } ossimDilationFilter::~ossimDilationFilter() { } void ossimDilationFilter::initialize() { ossimImageSourceFilter::initialize(); theTile = NULL; } ossimRefPtr ossimDilationFilter::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { if(!isSourceEnabled()) return ossimImageSourceFilter::getTile(rect, resLevel); ossimRefPtr inputData; if (theRecursiveFlag) inputData = ossimImageSourceFilter::getTile(rect, resLevel); else { ossim_uint32 halfSize = getWindowSize()>>1; ossimIrect requestRect(rect.ul().x - halfSize, rect.ul().y - halfSize, rect.lr().x + halfSize, rect.lr().y + halfSize); inputData = ossimImageSourceFilter::getTile(requestRect, resLevel); } if(!inputData.valid() || !inputData->getBuf()) return inputData; vector viv; ossimImageSourceFilter::getValidImageVertices(viv, OSSIM_CLOCKWISE_ORDER, resLevel); theValidImagePoly = ossimPolygon(viv); if(!theTile.valid()) { theTile = (ossimImageData*)inputData->dup(); theTile->setImageRectangle(rect); } else { theTile->setImageRectangleAndBands(rect, inputData->getNumberOfBands()); } theNullFoundFlag = false; switch(inputData->getScalarType()) { case OSSIM_UINT8: doDilation(ossim_uint8(0), inputData); break; case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: doDilation(ossim_uint16(0), inputData); break; case OSSIM_SINT16: doDilation(ossim_sint16(0), inputData); break; case OSSIM_UINT32: doDilation(ossim_uint32(0), inputData); break; case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: doDilation(ossim_float32(0), inputData); break; case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: doDilation(ossim_float64(0), inputData); break; default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimDilationFilter::applyFilter WARNING:\n" << "Unhandled scalar type!" << endl; } } return theTile; } template void ossimDilationFilter::doDilation(T scalarType , ossimRefPtr& inputData) { ossimDataObjectStatus status = inputData->getDataObjectStatus(); if ((status == OSSIM_FULL) || (status == OSSIM_EMPTY)) { // Nothing to do just copy the tile. theTile->loadTile(inputData.get()); return; } ossim_int32 halfWindow = (ossim_int32)(theWindowSize >> 1); ossim_int32 x, y, kernelX, kernelY; ossim_int32 iw = (ossim_int32)inputData->getWidth(); ossim_int32 ih = (ossim_int32)inputData->getHeight(); ossim_int32 ow = (ossim_int32)theTile->getWidth(); ossim_int32 oh = (ossim_int32)theTile->getHeight(); ossim_uint32 numBands = ossim::min(theTile->getNumberOfBands(), inputData->getNumberOfBands()); // It may be that the input rect is the same size as the output (i.e., the tile bounds aren't // expanded in the input's request to permit full kernels for output edge pixels: ossim_uint32 i_offset = 0; ossim_int32 delta = (ossim_int32)((iw - ow) >> 1); ossim_int32 xi, yi; if (delta > 0) i_offset = (ossim_uint32) halfWindow*(iw + 1); ossimIpt tile_ul (theTile->getImageRectangle().ul()); vector values; for(ossim_uint32 bandIdx = 0; bandIdx < numBands; ++bandIdx) { T* inputBuf = (T*)inputData->getBuf(bandIdx); T* outputBuf = (T*)theTile->getBuf(bandIdx); if (!inputBuf || !outputBuf) { return; // Shouldn't happen... } const T NP = (T)inputData->getNullPix(bandIdx); for(y = 0; y < oh; ++y) { for(x = 0; x < ow; ++x) { // Get the center input pixel. Only process those points inside the valid image // (to avoid dilation beyond valid image) const T CP = *(inputBuf+i_offset); ossimDpt ipt (tile_ul.x+x, tile_ul.y+y); if ((CP == NP) && theValidImagePoly.isPointWithin(ipt)) { theNullFoundFlag = true; // Needed for recursion values.clear(); for(kernelY = -halfWindow; kernelY <= halfWindow; ++kernelY) { yi = y + kernelY + delta; if ((yi < 0) || (y > ih)) continue; for(kernelX = -halfWindow; kernelX <= halfWindow; ++kernelX) { xi = x + kernelX + delta; if ((xi < 0) || (x > iw)) continue; T tempValue = *(inputBuf+kernelX+delta + (kernelY+delta)*iw); if(tempValue != NP) values.push_back((double)tempValue); } } if(values.size() > 0) { double accum = accumulate(values.begin(), values.end(), 0.0); double average = accum/(double)values.size(); (*outputBuf) = (T)average; } else { (*outputBuf) = NP; } } else // Center pixel (CP) not null. { (*outputBuf) = CP; } // Move over... ++inputBuf; ++outputBuf; } // End of loop in x direction. // Move down... inputBuf += iw - ow; } // End of loop in y direction. } // End of band loop. theTile->validate(); // Set up recursion for "dilation fill mode", we'll keep calling this getTile until all pixels // are filled with non-null values: if (theRecursiveFlag) { //cout << "Percent Full: "<percentFull()<write("filtered.ras"); //### status = theTile->getDataObjectStatus(); if (theNullFoundFlag) { theNullFoundFlag = false; // assume will fill, set true in next recursion if null found theTempTile = new ossimImageData(*theTile.get()); doDilation(scalarType, theTempTile); } } } void ossimDilationFilter::setProperty(ossimRefPtr property) { if (!property.valid()) return; ossimString name = property->getName(); if (name == WINDOW_SIZE_KW) { theWindowSize = property->valueToString().toUInt32(); } else if (name == RECURSIVE_DILATION_KW) { ossimString value; property->valueToString(value); setRecursiveFlag(value.toBool()); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimDilationFilter::getProperty(const ossimString& name)const { ossimRefPtr prop = 0; if (name == WINDOW_SIZE_KW) { prop = new ossimNumericProperty(WINDOW_SIZE_KW, ossimString::toString(theWindowSize), 3, 25); prop->setCacheRefreshBit(); return prop; } else if (name == RECURSIVE_DILATION_KW) { prop = new ossimBooleanProperty(RECURSIVE_DILATION_KW, getRecursiveFlag()); prop->setFullRefreshBit(); return prop; } return ossimImageSourceFilter::getProperty(name); } void ossimDilationFilter::getPropertyNames(vector& propertyNames) const { propertyNames.push_back(WINDOW_SIZE_KW); propertyNames.push_back(RECURSIVE_DILATION_KW); ossimImageSourceFilter::getPropertyNames(propertyNames); } bool ossimDilationFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, WINDOW_SIZE_KW.c_str(), theWindowSize, true); kwl.add(prefix, RECURSIVE_DILATION_KW.c_str(), (theRecursiveFlag?"true":"false"), true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimDilationFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = kwl.find(prefix, WINDOW_SIZE_KW.c_str()); if (lookup) theWindowSize = ossimString(lookup).toUInt32(); lookup = kwl.find(prefix, RECURSIVE_DILATION_KW.c_str()); if (lookup) setRecursiveFlag(ossimString(lookup).toBool()); return ossimImageSourceFilter::loadState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimDiscrete3x3HatFilter.cpp000066400000000000000000000154711352751253100236070ustar00rootroot00000000000000//******************************************************************* // // LICENSE: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimDiscrete3x3HatFilter.cpp 11419 2007-07-27 16:24:57Z dburken $ #include #include ossimDiscrete3x3HatFilter::ossimDiscrete3x3HatFilter() :ossimDiscreteConvolutionKernel(3,3) { // make the default be the nearest neighbor (*theKernel)[0][0] = 0; (*theKernel)[0][1] = 0; (*theKernel)[0][2] = 0; (*theKernel)[1][0] = 0; (*theKernel)[1][1] = 1; (*theKernel)[1][2] = 0; (*theKernel)[2][0] = 0; (*theKernel)[2][1] = 0; (*theKernel)[2][2] = 0; } void ossimDiscrete3x3HatFilter::convolve(const float* data, double& result, float nullPixel)const { double divisor = 0; result = 0; if(data[0] != nullPixel) { divisor += (*theKernel)[0][0]; result += (*theKernel)[0][0] * data[0]; } if(data[1] != nullPixel) { divisor += (*theKernel)[0][1]; result += (*theKernel)[0][1] * data[1]; } if(data[2] != nullPixel) { divisor += (*theKernel)[0][2]; result += (*theKernel)[0][2] * data[2]; } if(data[3] != nullPixel) { divisor += (*theKernel)[1][0]; result += (*theKernel)[1][0] * data[3]; } if(data[4] != nullPixel) { divisor += (*theKernel)[1][1]; result += (*theKernel)[1][1] * data[4]; } if(data[5] != nullPixel) { divisor += (*theKernel)[1][2]; result += (*theKernel)[1][2] * data[5]; } if(data[6] != nullPixel) { divisor += (*theKernel)[2][0]; result += (*theKernel)[2][0] * data[6]; } if(data[7] != nullPixel) { divisor += (*theKernel)[2][1]; result += (*theKernel)[2][1] * data[7]; } if(data[8] != nullPixel) { divisor += (*theKernel)[2][2]; result += (*theKernel)[2][2] * data[8]; } if(divisor > 0) result /= divisor; } void ossimDiscrete3x3HatFilter::convolveSubImage(const float* data, long dataWidth, double& result, float nullPixel)const { double divisor = 0.0; result = 0; if(data[0] != nullPixel) { divisor += (*theKernel)[0][0]; result += (*theKernel)[0][0]*data[0]; } if(data[1] != nullPixel) { divisor += (*theKernel)[0][1]; result += (*theKernel)[0][1]*data[1]; } if(data[2] != nullPixel) { divisor += (*theKernel)[0][2]; result += (*theKernel)[0][2]*data[2]; } data +=dataWidth; if(data[0] != nullPixel) { divisor += (*theKernel)[1][0]; result += (*theKernel)[1][0]*data[0]; } if(data[1] != nullPixel) { divisor += (*theKernel)[1][1]; result += (*theKernel)[1][1]*data[1]; } if(data[2] != nullPixel) { divisor += (*theKernel)[1][2]; result += (*theKernel)[1][2]*data[2]; } data +=dataWidth; if(data[0] != nullPixel) { divisor += (*theKernel)[2][0]; result += (*theKernel)[2][0]*data[0]; } if(data[1] != nullPixel) { divisor += (*theKernel)[2][1]; result += (*theKernel)[2][1]*data[1]; } if(data[2] != nullPixel) { divisor += (*theKernel)[2][2]; result += (*theKernel)[2][2]*data[2]; } if(divisor > 0) { result /= divisor; } } void ossimDiscrete3x3HatFilter::convolve(const unsigned char* data, double& result, ossim_uint8 nullPixel)const { double divisor = 0; result = 0; if(data[0] != nullPixel) { divisor += (*theKernel)[0][0]; result += (*theKernel)[0][0] * data[0]; } if(data[1] != nullPixel) { divisor += (*theKernel)[0][1]; result += (*theKernel)[0][1] * data[1]; } if(data[2] != nullPixel) { divisor += (*theKernel)[0][2]; result += (*theKernel)[0][2] * data[2]; } if(data[3] != nullPixel) { divisor += (*theKernel)[1][0]; result += (*theKernel)[1][0] * data[3]; } if(data[4] != nullPixel) { divisor += (*theKernel)[1][1]; result += (*theKernel)[1][1] * data[4]; } if(data[5] != nullPixel) { divisor += (*theKernel)[1][2]; result += (*theKernel)[1][2] * data[5]; } if(data[6] != nullPixel) { divisor += (*theKernel)[2][0]; result += (*theKernel)[2][0] * data[6]; } if(data[7] != nullPixel) { divisor += (*theKernel)[2][1]; result += (*theKernel)[2][1] * data[7]; } if(data[8] != nullPixel) { divisor += (*theKernel)[2][2]; result += (*theKernel)[2][2] * data[8]; } if(divisor > 0) result /= divisor; } void ossimDiscrete3x3HatFilter::convolveSubImage(const unsigned char* data, long dataWidth, double& result, ossim_uint8 nullPixel)const { double divisor = 0.0; result = 0; if(data[0] != nullPixel) { divisor += (*theKernel)[0][0]; result += (*theKernel)[0][0]*data[0]; } if(data[1] != nullPixel) { divisor += (*theKernel)[0][1]; result += (*theKernel)[0][1]*data[1]; } if(data[2] != nullPixel) { divisor += (*theKernel)[0][2]; result += (*theKernel)[0][2]*data[2]; } data +=dataWidth; if(data[0] != nullPixel) { divisor += (*theKernel)[1][0]; result += (*theKernel)[1][0]*data[0]; } if(data[1] != nullPixel) { divisor += (*theKernel)[1][1]; result += (*theKernel)[1][1]*data[1]; } if(data[2] != nullPixel) { divisor += (*theKernel)[1][2]; result += (*theKernel)[1][2]*data[2]; } data +=dataWidth; if(data[0] != nullPixel) { divisor += (*theKernel)[2][0]; result += (*theKernel)[2][0]*data[0]; } if(data[1] != nullPixel) { divisor += (*theKernel)[2][1]; result += (*theKernel)[2][1]*data[1]; } if(data[2] != nullPixel) { divisor += (*theKernel)[2][2]; result += (*theKernel)[2][2]*data[2]; } if(divisor > 0) { result /= divisor; } } void ossimDiscrete3x3HatFilter::buildConvolution(double xLocation, double yLocation) { NEWMAT::RowVector row(3); NEWMAT::ColumnVector col(3); row[0] = std::abs(xLocation); row[1] = 1; row[2] = std::abs(xLocation); col[0] = std::abs(yLocation); col[1] = 1; col[2] = std::abs(yLocation); (*theKernel) = col*row; } ossim-Miami-2.9.1/src/imaging/ossimDiscreteConvolutionKernel.cpp000066400000000000000000000330231352751253100250400ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimDiscreteConvolutionKernel.cpp 12912 2008-05-28 15:05:54Z gpotts $ #include ossimDiscreteConvolutionKernel::ossimDiscreteConvolutionKernel(long width, long height, bool doWeightedAverage) : theKernel(0), theWidth(width), theHeight(height), theComputeWeightedAverageFlag(doWeightedAverage) { theWidth = theWidth <0?1:theWidth; theHeight = theHeight <0?1:theHeight; theKernel = new NEWMAT::Matrix(theHeight, theWidth); *theKernel = (1.0/(theHeight*theWidth)); } ossimDiscreteConvolutionKernel::ossimDiscreteConvolutionKernel(const NEWMAT::Matrix& kernel, bool doWeightedAverage) :theKernel(new NEWMAT::Matrix(kernel)), theComputeWeightedAverageFlag(doWeightedAverage) { theWidth = theKernel->Ncols(); theHeight = theKernel->Nrows(); } ossimDiscreteConvolutionKernel::~ossimDiscreteConvolutionKernel() { if(theKernel) { delete theKernel; theKernel = 0; } } void ossimDiscreteConvolutionKernel::buildSymmetric(const std::vector& coefficients, NEWMAT::Matrix& result) { ossim_uint32 size = (ossim_uint32)coefficients.size(); if(size > 0) { NEWMAT::RowVector row(size); NEWMAT::ColumnVector col(size); for(ossim_uint32 index = 0; index < size; ++index) { row[index] = coefficients[index]; col[index] = coefficients[index]; } result = col*row; } } void ossimDiscreteConvolutionKernel::buildSymmetric(float *coefficients, long size, NEWMAT::Matrix& result) { if(size > 0) { NEWMAT::RowVector row(size); NEWMAT::ColumnVector col(size); for(long index = 0; index < size; ++index) { row[index] = coefficients[index]; col[index] = coefficients[index]; } result = col*row; } } void ossimDiscreteConvolutionKernel::setKernel(const NEWMAT::Matrix& kernel) { if(theKernel) { theKernel = new NEWMAT::Matrix; } *theKernel = kernel; theWidth = theKernel->Ncols(); theHeight = theKernel->Nrows(); } void ossimDiscreteConvolutionKernel::convolve(const float* data, double& result, float nullPixel)const { result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*data)); } ++data; } } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { result += ((*theKernel)[row][col] * (*data)); } ++data; } } } } void ossimDiscreteConvolutionKernel::convolveSubImage(const float* data, long dataWidth, double& result, float nullPixel)const { const float* dataStart = 0; result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } } } void ossimDiscreteConvolutionKernel::convolve(const unsigned char* data, double& result, ossim_uint8 nullPixel)const { result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*data)); } ++data; } } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { result += ((*theKernel)[row][col] * (*data)); } ++data; } } } } void ossimDiscreteConvolutionKernel::convolveSubImage(const unsigned char* data, long dataWidth, double& result, ossim_uint8 nullPixel)const { const ossim_uint8* dataStart = 0; result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } } } void ossimDiscreteConvolutionKernel::convolve(const unsigned short* data, double& result, ossim_uint16 nullPixel)const { result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*data)); } ++data; } } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { result += ((*theKernel)[row][col] * (*data)); } ++data; } } } } void ossimDiscreteConvolutionKernel::convolveSubImage(const unsigned short* data, long dataWidth, double& result, ossim_uint16 nullPixel)const { const ossim_uint16* dataStart = 0; result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } } } void ossimDiscreteConvolutionKernel::convolve(const short* data, double& result, ossim_sint16 nullPixel)const { result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*data)); } ++data; } } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { result += ((*theKernel)[row][col] * (*data)); } ++data; } } } } void ossimDiscreteConvolutionKernel::convolveSubImage(const short* data, long dataWidth, double& result, ossim_sint16 nullPixel)const { const ossim_sint16* dataStart = 0; result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } } } void ossimDiscreteConvolutionKernel::convolve(const double* data, double& result, double nullPixel)const { result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*data)); } ++data; } } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { for(long col=0; col < theWidth; ++col) { if(*data != nullPixel) { result += ((*theKernel)[row][col] * (*data)); } ++data; } } } } void ossimDiscreteConvolutionKernel::convolveSubImage(const double* data, long dataWidth, double& result, double nullPixel)const { const double* dataStart = 0; result = 0; if(theComputeWeightedAverageFlag) { double divisor = 0.0; for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { divisor += (*theKernel)[row][col]; result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } if(divisor > 0) { result /= divisor; } } else { for(long row=0; row < theHeight; ++row) { dataStart=data; for(long col=0; col < theWidth; ++col) { if(*dataStart != nullPixel) { result += ((*theKernel)[row][col] * (*dataStart)); } ++dataStart; } data+=dataWidth; } } } ossim-Miami-2.9.1/src/imaging/ossimDoqqTileSource.cpp000066400000000000000000000172241352751253100226050ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimDoqqTileSource.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include RTTI_DEF1(ossimDoqqTileSource, "ossimDoqqTileSource", ossimGeneralRasterTileSource); using namespace std; ossimDoqqTileSource::ossimDoqqTileSource() :theHeaderInformation(0) { } ossimDoqqTileSource::~ossimDoqqTileSource() { theHeaderInformation = 0; } bool ossimDoqqTileSource::open(const ossimFilename& filename) { bool result = false; theHeaderInformation = new ossimDoqq(filename); if(theHeaderInformation->errorStatus() == ossimDoqq::OSSIM_ERROR) { theHeaderInformation = 0; return result; } else { // Set the Acquisition Date theAcqDate = theHeaderInformation->theAcqYear; theAcqDate += "-"; theAcqDate += theHeaderInformation->theAcqMonth; theAcqDate += "-"; theAcqDate += theHeaderInformation->theAcqDay; vector f; f.push_back(filename); ossimGeneralRasterInfo genRasterInfo(f, OSSIM_UCHAR, OSSIM_BIP, theHeaderInformation->theRgb, theHeaderInformation->theLine, theHeaderInformation->theSample, theHeaderInformation->theHeaderSize, ossimGeneralRasterInfo::NONE, 0); result = ossimGeneralRasterTileSource::open(genRasterInfo); } return result; } //************************************************************************************************** //! Returns the image geometry object associated with this tile source or NULL if non defined. //! The geometry contains full-to-local image transform as well as projection (image-to-world) //************************************************************************************************** ossimRefPtr ossimDoqqTileSource::getImageGeometry() { if (theGeometry.valid()) return theGeometry; if(theHeaderInformation.valid()) { ossimKeywordlist kwl; const char* prefix = 0; // legacy ossimString proj = theHeaderInformation->theProjection.trim().upcase(); ossimString datum = theHeaderInformation->theDatum.trim().upcase(); if(proj == ossimString("UTM") || proj == ossimString("1")) { kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimUtmProjection", true); kwl.add(prefix, ossimKeywordNames::ZONE_KW, theHeaderInformation->theUtmZone, true); } else { return ossimRefPtr(); } if(datum == ossimString("NAR") || datum == ossimString("4")) { kwl.add(prefix, ossimKeywordNames::DATUM_KW, "NAR-C", // North American Conus 1983 true); } else if(datum == ossimString("NAS") || datum == ossimString("1")) { kwl.add(prefix, ossimKeywordNames::DATUM_KW, "NAS-C", // North American Conus 1927 true); } else if(datum == ossimString("2")) { kwl.add(prefix, ossimKeywordNames::DATUM_KW, "WGD", // WGS 72 true); } else if(datum == ossimString("3")) { kwl.add(prefix, ossimKeywordNames::DATUM_KW, "WGE", // WGS 84 true); } else { return ossimRefPtr(); } kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_X_KW, theHeaderInformation->theGsd.x, true); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW, theHeaderInformation->theGsd.y, true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_EASTING_KW, // theHeaderInformation->theUE + (theHeaderInformation->theGsd/2.0), theHeaderInformation->theEasting, true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_NORTHING_KW, // theHeaderInformation->theUN - (theHeaderInformation->theGsd/2.0), theHeaderInformation->theNorthing, true); // Capture this for next time. theGeometry = new ossimImageGeometry; theGeometry->loadState(kwl, prefix); // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); return theGeometry; } return ossimRefPtr(); } ossimRefPtr ossimDoqqTileSource::getProperty(const ossimString& name)const { if(name == "acquisition_date") { if(theHeaderInformation.valid()) { std::stringstream out; out << std::setw(4) << std::setfill(' ') << theHeaderInformation->theAcqYear.c_str() << std::setw(2) << setfill('0') << theHeaderInformation->theAcqMonth.c_str() << std::setw(2) << setfill('0') << theHeaderInformation->theAcqDay.c_str(); return new ossimStringProperty("acquisition_date", out.str()); } return 0; } else if(name == "file_type") { return new ossimStringProperty("file_type", "DOQQ"); } return ossimImageHandler::getProperty(name); } void ossimDoqqTileSource::getPropertyNames(std::vector& propertyNames)const { ossimImageHandler::getPropertyNames(propertyNames); propertyNames.push_back("acquisition_date"); propertyNames.push_back("file_type"); } bool ossimDoqqTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if(!ossimImageHandler::loadState(kwl, prefix)) { return false; } if(lookup) { theHeaderInformation = new ossimDoqq(ossimFilename(lookup)); if(theHeaderInformation->errorStatus() != ossimDoqq::OSSIM_OK) { theHeaderInformation = 0; return false; } else { ossimFilename filename(lookup); vector f; f.push_back(filename); ossimGeneralRasterInfo genRasterInfo(f, OSSIM_UCHAR, OSSIM_BIP, theHeaderInformation->theRgb, theHeaderInformation->theLine, theHeaderInformation->theSample, theHeaderInformation->theHeaderSize, ossimGeneralRasterInfo::NONE, 0); return open(genRasterInfo); } } else { return false; } return true; } ossimString ossimDoqqTileSource::getShortName()const { return ossimString("doqq"); } ossimString ossimDoqqTileSource::getLongName()const { return ossimString("doqq handler"); } bool ossimDoqqTileSource::open(const ossimGeneralRasterInfo& info) { return ossimGeneralRasterTileSource::open(info); } ossimString ossimDoqqTileSource::acqdate() const { return theAcqDate; } ossim-Miami-2.9.1/src/imaging/ossimDtedTileSource.cpp000066400000000000000000000452031352751253100225570ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: // // Contains class declaration for ossimDtedTileSource. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimDtedTileSource, "ossimDtedTileSource", ossimImageHandler) // Static trace for debugging static ossimTrace traceDebug("ossimDtedTileSource:debug"); ossimDtedTileSource::ossimDtedTileSource() : ossimImageHandler(), theTile(0), m_fileStr(0), m_dtedInfo(0), theTileWidth(0), theTileHeight(0), theNumberOfLines(0), theNumberOfSamps(0), theOffsetToFirstDataRecord(0), theDataRecordSize(0), theMinHeight(0), theMaxHeight(0), thePostSpacing(0.0, 0.0), theSwapBytesFlag(false) { if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) { theSwapBytesFlag = true; } // Set the tile size to the default. ossimIpt defaultTileSize; ossim::defaultTileSize(defaultTileSize); theTileWidth = static_cast(defaultTileSize.x); theTileHeight = static_cast(defaultTileSize.y); // Construction not complete. Users should call "open" method. } ossimDtedTileSource::~ossimDtedTileSource() { close(); } ossimString ossimDtedTileSource::getShortName()const { return ossimString("dted"); } ossimString ossimDtedTileSource::getLongName()const { return ossimString("dted reader"); } ossimRefPtr ossimDtedTileSource::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { if (!theTile.valid()) { allocate(); // First getTile call or after changeTileSize. if (!theTile.valid()) { return ossimRefPtr(); // Throw exception??? } } // Image rectangle must be set prior to calling getTile. theTile->setImageRectangle(tile_rect); if ( getTile( theTile.get(), resLevel ) == false ) { if (theTile->getDataObjectStatus() != OSSIM_NULL) { theTile->makeBlank(); } } return theTile; } bool ossimDtedTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) ) { result->ref(); // Increment ref count. //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0. Method returns true on success, false // on error. //--- status = getOverviewTile(resLevel, result); if ( !status ) // Did not get an overview tile. { ossimIrect image_rect = getImageRectangle(resLevel); ossimIrect tile_rect = result->getImageRectangle(); //--- // See if any point of the requested tile is in the image. //--- if ( tile_rect.intersects(image_rect) ) { ossimIrect clip_rect = tile_rect.clipToRect(image_rect); if ( !tile_rect.completely_within(clip_rect) ) { // Start with a blank tile. result->makeBlank(); } // Load the tile buffer with data from the dted cell. status = fillBuffer(tile_rect, clip_rect, result); } // End of if ( tile_rect.intersects(image_rect) ) } result->unref(); // Decrement ref count. } return status; } //******************************************************************* // Private Method: //******************************************************************* bool ossimDtedTileSource::fillBuffer(const ossimIrect& tile_rect, const ossimIrect& clip_rect, ossimImageData* tile) { //*** // NOTE: // Elevation posts are organized positive line up. // The "tile_rect" and "clip_rect" is organized positive line down. //*** const ossim_int32 TILE_WIDTH = tile->getWidth(); //*** // Position the file pointer to the first record needed. // Posts are organized positive line up so we're going to start at // the lower left side of the cell so all reads are going forward in // the file. //*** ossim_int32 seek_position = theOffsetToFirstDataRecord + (clip_rect.ul().x * theDataRecordSize); seek_position += DATA_RECORD_OFFSET_TO_POST + (theNumberOfLines - 1 - clip_rect.lr().y) * 2; //*** // Get a pointer positioned at the first valid pixel in // the tile. Tiles are organized positive line down. //*** ossim_sint16* d = static_cast(tile->getBuf()); // Loop in the longitude or sample direction. for (ossim_int32 samp = clip_rect.ul().x; samp <= clip_rect.lr().x; samp++) { ossim_int32 d_offset = (clip_rect.lr().y - tile_rect.ul().y) * TILE_WIDTH + (samp - tile_rect.ul().x); m_fileStr->seekg(seek_position, ios::beg); // Seek to the first post. for (ossim_int32 line = clip_rect.lr().y; line >= clip_rect.ul().y; line--) { // Grab all the post needed from the column. ossim_uint16 temp; ossim_sint16 s; m_fileStr->read((char*)&temp, POST_SIZE); s = convertSignedMagnitude(temp); d[d_offset] = s; d_offset -= TILE_WIDTH; } seek_position += theDataRecordSize; } tile->validate(); return true; } ossim_uint32 ossimDtedTileSource::getNumberOfOutputBands()const { return getNumberOfInputBands(); } ossimIrect ossimDtedTileSource::getImageRectangle(ossim_uint32 reduced_res_level) const { return ossimIrect(0, 0, getNumberOfSamples(reduced_res_level) - 1, getNumberOfLines(reduced_res_level) - 1); } bool ossimDtedTileSource::isOpen()const { return (m_fileStr!=0); } void ossimDtedTileSource::close() { m_fileStr.reset(); } bool ossimDtedTileSource::open() { static const char MODULE[] = "ossimDtedTileSource::open"; if (traceDebug()) { CLOG << "DEBUG:" << "\nAttempting to parse file: " << theImageFile.c_str() << endl; } std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( theImageFile.c_str(), std::ios_base::in|std::ios_base::binary); // Open up the file for reading. if (!str) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR!" << "\nCould not open file: " << theImageFile.c_str() << "\nReturning..." << endl; CLOG << "returning with error..." << endl; } return false; } if(!str) { if (traceDebug()) { CLOG << "DEBUG:" << "\nCannot open: " << theImageFile.c_str() << endl; } str.reset(); return false; } std::string connectionString = theImageFile.c_str(); m_dtedInfo = std::make_shared(); if(!m_dtedInfo->open(str, connectionString)) { close(); return false; } m_fileStr = str; m_fileStr->clear(); m_fileStr->seekg(0); m_vol.parse(*str); m_hdr.parse(*str); m_uhl.parse(*str); m_dsi.parse(*str); m_acc.parse(*str); //*** // Check for errors. Must have uhl, dsi and acc records. vol and hdr // are for magnetic tape only; hence, may or may not be there. //*** if (m_uhl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR || m_dsi.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR || m_acc.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { if (traceDebug()) { CLOG << "DEBUG:" << "\nError parsing file: " << theImageFile.c_str() << "\nPossibly not a dted file.\n"; } str.reset(); return false; } m_fileStr = str; // Get the cell specific info needed for later. theNumberOfLines = m_uhl.numLatPoints(); theNumberOfSamps = m_uhl.numLonLines(); thePostSpacing.x = m_uhl.lonInterval(); thePostSpacing.y = m_uhl.latInterval(); theOffsetToFirstDataRecord = m_acc.stopOffset(); theDataRecordSize = DATA_RECORD_OFFSET_TO_POST + (theNumberOfLines * sizeof(ossim_sint16)) + DATA_RECORD_CHECKSUM_SIZE; //--- // Note: // Complete open calls loadMetaData which we have overriden to check for // dot omd or dot statistics file. If not there it will call // gatherStatistics which will scan the file for min/max values. //--- completeOpen(); if (traceDebug()) { CLOG << "DEBUG:" << "\nNull pix: " << getNullPixelValue(0) << "\nMin pix: " << getMinPixelValue(0) << "\nMax pix: " << getMaxPixelValue(0) << "\ntheNumberOfLines: " << theNumberOfLines << "\ntheNumberOfSamps: " << theNumberOfSamps << "\ntheOffsetToFirstDataRecord: " << theOffsetToFirstDataRecord << "\ntheDataRecordSize: " << theDataRecordSize << "\n"; } return true; } void ossimDtedTileSource::allocate() { //--- // Set up the tiles. Note the blank tile will not get initialized to save // memory. This includes setting the min and max pixel value gathered // from the statistics. //--- theTile = ossimImageDataFactory::instance()->create(this, this); if(theTile.valid()) { theTile->initialize(); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:" << "\ntheTile:\n" << *theTile << "\n"; } } bool ossimDtedTileSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Currently nothing to do here. return ossimImageHandler::saveState(kwl, prefix); } bool ossimDtedTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (ossimImageHandler::loadState(kwl, prefix)) { if (ossimImageHandler::open(theImageFile)) { return true; } } return false; } //************************************************************************************************** // Returns the image geometry object associated with this tile source or NULL if not defined. // The geometry contains full-to-local image transform as well as projection (image-to-world) //************************************************************************************************** ossimRefPtr ossimDtedTileSource::getImageGeometry() { if ( theGeometry.valid() ) return theGeometry; // Compute the projection tie point (UL corner of dted cell). The UHL supplies the SW (LL) corner // coordinates, so need to compute the UL lat from the cell spacing: const ossimDatum* datum = ossimDatumFactory::instance()->wgs84(); ossim_float64 ul_lat = m_uhl.latOrigin() + (m_uhl.latInterval() * (m_uhl.numLatPoints()-1.0)); ossim_float64 ul_lon = m_uhl.lonOrigin(); ossimGpt tie(ul_lat, ul_lon, 0.0, datum); //--- // This code is backed out as it affects the corner. // E.g.: image0.ur_lon: -88.999999999995 // Should be -89.0 // Used ossimImageGeometry::::getMetersPerPixel for a center of the image gsd. (drb) // // We also need to define an origin for the projection as the center of the cell for proper GSD // calculation (OLK 01/11: Used to set origin at 0,0 causing incorrect meters GSD to be // computed) // ossim_float64 mid_lat = m_uhl.latOrigin() + (m_uhl.latInterval()*m_uhl.numLatPoints()/2.0); // ossim_float64 mid_lon = m_uhl.lonOrigin() + (m_uhl.lonInterval()*m_uhl.numLonLines()/2.0); // ossimGpt origin (mid_lat, mid_lon, 0.0, datum); //--- ossimGpt origin (0.0, 0.0, 0.0, datum); // Make an Equidistant Cylindrical projection. ossimRefPtr eq = new ossimEquDistCylProjection(*(datum->ellipsoid())); // Set the scale: eq->setOrigin(origin); eq->setUlTiePoints(tie); ossimDpt gsd(m_uhl.lonInterval(), m_uhl.latInterval()); eq->setDecimalDegreesPerPixel(gsd); // Give it to the geometry object. ossimRefPtr proj = eq.get(); // Make the geometry: theGeometry = new ossimImageGeometry; // Set the projection. theGeometry->setProjection( proj.get() ); // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); return theGeometry; } ossimScalarType ossimDtedTileSource::getOutputScalarType() const { return OSSIM_SSHORT16; // Always signed 16 bit. } ossim_uint32 ossimDtedTileSource::getTileWidth() const { return theTileWidth; } ossim_uint32 ossimDtedTileSource::getTileHeight() const { return theTileHeight; } ossim_uint32 ossimDtedTileSource::getNumberOfLines(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return theNumberOfLines; } else if (theOverview.valid()) { return theOverview->getNumberOfLines(reduced_res_level); } return 0; } ossim_uint32 ossimDtedTileSource::getNumberOfSamples(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return theNumberOfSamps; } else if (theOverview.valid()) { return theOverview->getNumberOfSamples(reduced_res_level); } return 0; } void ossimDtedTileSource::loadMetaData() { ossimKeywordlist kwl; const char* min_str = 0; const char* max_str = 0; ossimFilename f = theImageFile.fileNoExtension(); // Check for omd file. f.setExtension("omd"); if ( f.exists() ) { kwl.addFile(f); min_str = kwl.find("band1.min_value"); max_str = kwl.find("band1.max_value"); } if ( !min_str || !max_str ) { f.setExtension("statistics"); if ( f.exists() ) { kwl.addFile(f); min_str = kwl.find(ossimKeywordNames::MIN_VALUE_KW); max_str = kwl.find(ossimKeywordNames::MAX_VALUE_KW); } } if ( min_str || max_str ) { theMinHeight = atoi(min_str); theMaxHeight = atoi(max_str); } else { gatherStatistics(false); } } void ossimDtedTileSource::gatherStatistics(bool writeStatsFile) { // Scan the cell and gather the statistics... if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedTileSource::gatherStatistics() scanning for min/max" << "\nThis may take a while...\n"; } // Start off with the min and max pegged. theMinHeight = 32767; theMaxHeight = -32767; // Put the file pointer at the start of the first elevation post. m_fileStr->seekg(theOffsetToFirstDataRecord, ios::beg); //--- // Loop through all records and scan for lowest min and highest max. // Each record contains a row of latitude points for a given longitude. // There are eight bytes in front of the post and four checksum bytes at // the end so ignore them. //--- for (ossim_uint32 i=0; iseekg(DATA_RECORD_OFFSET_TO_POST, ios::cur); for (ossim_uint32 j=0; jread((char*)&temp, POST_SIZE); s = convertSignedMagnitude(temp); if (s < theMinHeight && s != NULL_PIXEL) theMinHeight = s; if (s > theMaxHeight) theMaxHeight = s; } m_fileStr->seekg(DATA_RECORD_CHECKSUM_SIZE, ios::cur); } if ( writeStatsFile ) { // Add the stats to the keyword list. ossimKeywordlist kwl; kwl.add(ossimKeywordNames::MIN_VALUE_KW, theMinHeight); kwl.add(ossimKeywordNames::MAX_VALUE_KW, theMaxHeight); // Write out the statistics file. ossimFilename f = theImageFile.fileNoExtension(); f.setExtension("statistics"); kwl.write( f.c_str() ); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedTileSource::gatherStatistics DEBUG:" << "\ntheMinHeight: " << theMinHeight << "\ntheMaxHeight: " << theMaxHeight << "\n"; } } ossim_uint32 ossimDtedTileSource::getImageTileWidth() const { return 0; } ossim_uint32 ossimDtedTileSource::getImageTileHeight() const { return 0; } ossim_uint32 ossimDtedTileSource::getNumberOfInputBands() const { return 1; } double ossimDtedTileSource::getNullPixelValue(ossim_uint32 /* band */)const { if(theMetaData.getNumberOfBands()) { return theMetaData.getNullPix(0); } return -32767.0; } double ossimDtedTileSource::getMinPixelValue(ossim_uint32 band)const { if(theMetaData.getNumberOfBands()) { return theMetaData.getMinPix(band); } return theMinHeight; } double ossimDtedTileSource::getMaxPixelValue(ossim_uint32 band)const { if(theMetaData.getNumberOfBands()) { return theMetaData.getMaxPix(band); } return theMaxHeight; } void ossimDtedTileSource::getPostSpacing(ossimDpt& postSpacing) const { postSpacing.x = thePostSpacing.x; postSpacing.y = thePostSpacing.y; } ossimRefPtr ossimDtedTileSource::getProperty( const ossimString& name)const { // look in base class. ossimRefPtr result = ossimImageHandler::getProperty(name); if (result.valid() == false) { // ossimDtedInfo info; // std::string connectionString = theImageFile.c_str(); if (m_dtedInfo) { result = m_dtedInfo->getProperty(name); } } return result; } void ossimDtedTileSource::getPropertyNames( std::vector& propertyNames) const { ossimImageHandler::getPropertyNames(propertyNames); if (m_dtedInfo) { m_dtedInfo->getPropertyNames(propertyNames); } // ossimDtedInfo info; // if (info.open(theImageFile)) // { // info.getPropertyNames(propertyNames); // } } const ossimDtedTileSource& ossimDtedTileSource::operator=(const ossimDtedTileSource& rhs) { return rhs; } ossimDtedTileSource::ossimDtedTileSource(const ossimDtedTileSource&) { } ossim-Miami-2.9.1/src/imaging/ossimERSFileWriter.cpp000066400000000000000000000143021352751253100223220ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Andrew Huang // // Description: // // Class declaration for ossimERSFileWriter. Meta data class for // writing an ERS header file. // //---------------------------------------------------------------------------- // $Id: ossimERSFileWriter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimERSFileWriter, "ossimERSFileWriter", ossimMetadataFileWriter) ossimERSFileWriter::ossimERSFileWriter() : ossimMetadataFileWriter(), theHdr() { } ossimERSFileWriter::~ossimERSFileWriter() { } bool ossimERSFileWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { // To pick up output filename. return ossimMetadataFileWriter::loadState(kwl, prefix); } bool ossimERSFileWriter::writeFile() { ossimString tmp; theHdr.theDatasetType = "ERStorage"; theHdr.theDatatype = "Raster"; theHdr.theBands = theInputConnection->getNumberOfOutputBands(); theHdr.theSample = theAreaOfInterest.width(); theHdr.theLine = theAreaOfInterest.height(); ossimByteOrder byteorder = ossim::byteOrder(); if (byteorder == OSSIM_BIG_ENDIAN) { theHdr.theByteorder = "MSBFirst"; } else { theHdr.theByteorder = "LSBFirst"; } theHdr.theCelltype = theInputConnection->getOutputScalarType(); // Get the geometry from the input. ossimMapProjection* mapProj = 0; ossimRefPtr inputGeom = theInputConnection->getImageGeometry(); if ( inputGeom.valid() ) mapProj = PTR_CAST(ossimMapProjection, inputGeom->getProjection()); if (mapProj) { // Create the projection info. ossimRefPtr projectionInfo = new ossimMapProjectionInfo(mapProj, theAreaOfInterest); // Set the tie points in the keyword list. ossimKeywordlist kwl; projectionInfo->getGeom(kwl); // Get the projection type. const char* lookup; ossimString projection; lookup = kwl.find(ossimKeywordNames::TYPE_KW); if (lookup) { projection = lookup; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimERSFileWriter::writeFile WARNING:" << "\nNo projection type found!\nReturning..." << std::endl; return false; // Have to have the projection type! } if (projection == "ossimUtmProjection") { ossimString utm; lookup = kwl.find(ossimKeywordNames::HEMISPHERE_KW); if (lookup) { utm = lookup; utm += "UTM"; } else return false; lookup = kwl.find(ossimKeywordNames::ZONE_KW); if (lookup) utm += lookup; else return false; theHdr.theProjection = utm; theHdr.theCoordSysType = "EN"; //we get tie points lookup = kwl.find(ossimKeywordNames::TIE_POINT_XY_KW); tmp = lookup; if (lookup) { tmp = tmp.trim("("); tmp = tmp.trim(")"); ossimString a = tmp.before(",", 0); ossimString b = tmp.after(",", 0); theHdr.theOriginX = a.toDouble(); theHdr.theOriginY = b.toDouble(); } //set the tie point unit type to meters theHdr.theTieUnitType = OSSIM_METERS; } else if (projection == "ossimEquDistCylProjection") { theHdr.theProjection = "GEODETIC"; theHdr.theCoordSysType = "LL"; //we get tie points lookup = kwl.find(ossimKeywordNames::TIE_POINT_XY_KW); tmp = lookup; if (lookup) { tmp = tmp.trim("("); tmp = tmp.trim(")"); ossimString a = tmp.before(",", 0); ossimString b = tmp.after(",", 0); theHdr.theOriginX = a.toDouble(); theHdr.theOriginY = b.toDouble(); } //set the tie point unit type to degrees theHdr.theTieUnitType = OSSIM_DEGREES; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimERSFileWriter::writeFile WARNING:" << "\nOnly LatLon and UTM supported!\nReturning..." << std::endl; return false; } // Get the datum. ossimString datum = "WGS-84"; lookup = kwl.find(ossimKeywordNames::DATUM_KW); if (lookup) { ossimString os = lookup; if (os == "WGE") { theHdr.theDatum = "WGS84"; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimERSFileWriter::writeFile WARNING:" << "\nOnly WGS84 supported!\nReturning..." << std::endl; return false; // Datum has to be WGS84 for now... } } //get cell size lookup = kwl.find(ossimKeywordNames::PIXEL_SCALE_XY_KW); tmp = lookup; if (lookup) { tmp = tmp.trim("("); tmp = tmp.trim(")"); ossimString a = tmp.before(",", 0); ossimString b = tmp.after(",", 0); theHdr.theCellSizeX = a.toDouble(); theHdr.theCellSizeY = b.toDouble(); } //get pixel is area or point if(thePixelType == OSSIM_PIXEL_IS_POINT) { theHdr.theOriginX -= theHdr.theCellSizeX/2.0; theHdr.theOriginY += theHdr.theCellSizeY/2.0; } } return theHdr.writeFile(theFilename); } void ossimERSFileWriter::getMetadatatypeList( std::vector& metadatatypeList) const { metadatatypeList.push_back(ossimString("ers_header")); } bool ossimERSFileWriter::hasMetadataType( const ossimString& metadataType)const { return (metadataType == "ers_header"); } ossim-Miami-2.9.1/src/imaging/ossimERSTileSource.cpp000066400000000000000000000146111352751253100223270ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Chong-Ket Chuah // // Description: // // Implementation for the class "ossimERSTileSource". ossimERSTileSource // is used for reading ER Mapper raster file format. The format consists // of a raster file with no extension and a header file with the same name // as the raster file but with an .ers extension. // //******************************************************************* // $Id: ossimERSTileSource.cpp 21512 2012-08-22 11:53:57Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimERSTileSource, "ossimERSTileSource", ossimGeneralRasterTileSource); using namespace std; //******************************************************************* // Public Constructor: //******************************************************************* ossimERSTileSource::ossimERSTileSource() : ossimGeneralRasterTileSource(), theHdr(NULL) { } //******************************************************************* // Public Constructor: //******************************************************************* ossimERSTileSource::ossimERSTileSource(const ossimKeywordlist& kwl, const char* prefix) : ossimGeneralRasterTileSource(), theHdr(NULL) { if (loadState(kwl, prefix) == false) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } } //******************************************************************* // Destructor: //******************************************************************* ossimERSTileSource::~ossimERSTileSource() { if (theHdr) { delete theHdr; theHdr = NULL; } } bool ossimERSTileSource::open(const ossimFilename& fileName) { // Open and parse the header file theHdr = new ossimERS(fileName); // theHdr->dump(cout); if(theHdr->errorStatus() == ossimErrorCodes::OSSIM_ERROR) { delete theHdr; theHdr = NULL; return false; } else { vector f; ossimFilename fne; ossimFilename fpath = fileName.path(); if (fpath.empty()) fne = fileName.fileNoExtension(); else fne = fpath+"/"+fileName.fileNoExtension(); f.push_back(fne); ossimGeneralRasterInfo genRasterInfo(f, theHdr->theCelltype, OSSIM_BIL, theHdr->theBands, theHdr->theLine, theHdr->theSample, 0, ossimGeneralRasterInfo::NONE, 0); if(theHdr->theHasNullCells) { ossim_uint32 i = 0; ossim_uint32 bands = static_cast(theHdr->theBands); for(i = 0; i < bands; ++i) { genRasterInfo.getImageMetaData().setNullPix(i, theHdr->theNullCell); } } ossimFilename metadataFile = fne; metadataFile = metadataFile + ".omd"; if(metadataFile.exists()) { ossimKeywordlist kwl; kwl.addFile(metadataFile.c_str()); theMetaData.loadState(kwl); ossim_uint32 i = 0; ossim_uint32 bands = static_cast(theHdr->theBands); for(i = 0; i < bands; ++i) { if(theMetaData.getMinValuesValidFlag()) { genRasterInfo.getImageMetaData().setMinPix(i, theMetaData.getMinPix(i)); } if(theMetaData.getMaxValuesValidFlag()) { genRasterInfo.getImageMetaData().setMaxPix(i, theMetaData.getMaxPix(i)); } if(theMetaData.getNullValuesValidFlag()) { genRasterInfo.getImageMetaData().setNullPix(i, theMetaData.getNullPix(i)); } } } ossimNotify(ossimNotifyLevel_INFO) << "general raster info is\n"; genRasterInfo.print(ossimNotify(ossimNotifyLevel_INFO)); ossimGeneralRasterTileSource::open(genRasterInfo); } return true; } ossimRefPtr ossimERSTileSource::getImageGeometry() { if ( !theGeometry ) { // Check for external geom: theGeometry = getExternalImageGeometry(); if ( !theGeometry ) { theGeometry = new ossimImageGeometry; if(theHdr) { ossimKeywordlist kwl; if ( theHdr->toOssimProjectionGeom(kwl) ) { theGeometry->loadState(kwl); } } // At this point it is assured theGeometry is set. //--- // WARNING: // Must create/set the geometry at this point or the next call to // ossimImageGeometryRegistry::extendGeometry will put us in an infinite loop // as it does a recursive call back to ossimImageHandler::getImageGeometry(). //--- // Check for set projection. if ( !theGeometry->getProjection() ) { // Try factories for projection. ossimImageGeometryRegistry::instance()->extendGeometry(this); } } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } return theGeometry; } bool ossimERSTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if (lookup) { ossimFilename fileName = lookup; bool result = open(fileName); ossimImageSource::loadState(kwl, prefix); return result; } return ossimGeneralRasterTileSource::loadState(kwl, prefix); } ossimString ossimERSTileSource::getShortName() const { return ossimString("ERS"); } ossimString ossimERSTileSource::getLongName() const { return ossimString("ER Mapper Raster"); } ossimString ossimERSTileSource::className() const { return ossimString("ossimERSTileSource"); } ossim-Miami-2.9.1/src/imaging/ossimEastingNorthingCutter.cpp000066400000000000000000000122241352751253100241670ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // $Id: ossimEastingNorthingCutter.cpp 15766 2009-10-20 12:37:09Z gpotts $ //---------------------------------------------------------------------------- #include #include #include #include #include RTTI_DEF2(ossimEastingNorthingCutter, "ossimEastingNorthingCutter", ossimRectangleCutFilter, ossimViewInterface); static ossimTrace traceDebug(ossimString("ossimEastingNorthingCutter:debug")); using namespace std; ossimEastingNorthingCutter::ossimEastingNorthingCutter(ossimObject* owner, ossimImageSource* inputSource) :ossimRectangleCutFilter(owner, inputSource), ossimViewInterface(0), theViewProjection(0) { theUlEastingNorthing.makeNan(); theLrEastingNorthing.makeNan(); theCutType = OSSIM_RECTANGLE_NULL_OUTSIDE; } ossimEastingNorthingCutter::ossimEastingNorthingCutter(ossimImageSource* inputSource) :ossimRectangleCutFilter(inputSource), ossimViewInterface(0), theViewProjection(0) { theUlEastingNorthing.makeNan(); theLrEastingNorthing.makeNan(); theCutType = OSSIM_RECTANGLE_NULL_OUTSIDE; } ossimEastingNorthingCutter::~ossimEastingNorthingCutter() { } void ossimEastingNorthingCutter::setEastingNorthingRectangle(const ossimDpt& ul, const ossimDpt& lr) { theUlEastingNorthing = ul; theLrEastingNorthing = lr; transformVertices(); } ossimDpt ossimEastingNorthingCutter::getUlEastingNorthing()const { return theUlEastingNorthing; } ossimDpt ossimEastingNorthingCutter::getLrEastingNorthing()const { return theLrEastingNorthing; } void ossimEastingNorthingCutter::initialize() { ossimRectangleCutFilter::initialize(); transformVertices(); } bool ossimEastingNorthingCutter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "ul_en", ossimString::toString(theUlEastingNorthing.x) + " " + ossimString::toString(theUlEastingNorthing.y), true); kwl.add(prefix, "lr_en", ossimString::toString(theLrEastingNorthing.x) + " " + ossimString::toString(theLrEastingNorthing.y), true); return ossimRectangleCutFilter::saveState(kwl, prefix); } bool ossimEastingNorthingCutter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char *ul = kwl.find(prefix, "ul_en"); const char *lr = kwl.find(prefix, "lr_en"); theUlEastingNorthing.makeNan(); theLrEastingNorthing.makeNan(); if(ul) { istringstream in(ul); ossimString x; ossimString y; in >> x >> y; theUlEastingNorthing.x = x.toDouble(); theUlEastingNorthing.y = y.toDouble(); } if(lr) { istringstream in(lr); ossimString x; ossimString y; in >> x >> y; theLrEastingNorthing.x = x.toDouble(); theLrEastingNorthing.y = y.toDouble(); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimEastingNorthingCutter::loadState DEBUG:" << "\ntheUlEastingNorthing: " << theUlEastingNorthing << "\ntheLrEastingNorthing: " << theLrEastingNorthing << endl; } return ossimRectangleCutFilter::loadState(kwl, prefix); } bool ossimEastingNorthingCutter::setView(ossimObject* baseObject) { ossimProjection* tempProj = PTR_CAST(ossimProjection, baseObject); if(!tempProj) { return false; } theViewProjection = tempProj; transformVertices(); return true; } ossimObject* ossimEastingNorthingCutter::getView() { return theViewProjection.get(); } const ossimObject* ossimEastingNorthingCutter::getView()const { return theViewProjection.get(); } void ossimEastingNorthingCutter::transformVertices() { theRectangle.makeNan(); if(theUlEastingNorthing.hasNans()|| theLrEastingNorthing.hasNans()|| (!theViewProjection)) { return; } ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, theViewProjection.get()); ossimDpt ul; ossimDpt lr; ossimDpt easting; ossimDpt northing; if(mapProj) { mapProj->eastingNorthingToLineSample(theUlEastingNorthing, ul); mapProj->eastingNorthingToLineSample(theLrEastingNorthing, lr); ossimDrect drect(ul.x, ul.y, lr.x, lr.y); theRectangle = drect; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimEastingNorthingCutter::transformVertices DEBUG:" << "original drect: " << drect << "\ntheRectangle: " << theRectangle << endl; } } } ossim-Miami-2.9.1/src/imaging/ossimEdgeFilter.cpp000066400000000000000000000520131352751253100217070ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimEdgeFilter.cpp 19956 2011-08-16 00:36:25Z gpotts $ #include #include #include #include RTTI_DEF1(ossimEdgeFilter, "ossimEdgeFilter", ossimImageSourceFilter); #define PROP_EDGE_FILTER "Edge type" using namespace std; ossimEdgeFilter::ossimEdgeFilter(ossimObject* owner) :ossimImageSourceFilter(owner), theTile(NULL), theFilterType("Sobel") { } ossimEdgeFilter::ossimEdgeFilter(ossimImageSource* inputSource) :ossimImageSourceFilter(inputSource), theTile(NULL), theFilterType("Sobel") { } ossimEdgeFilter::ossimEdgeFilter(ossimObject* owner, ossimImageSource* inputSource) :ossimImageSourceFilter(owner, inputSource), theTile(NULL), theFilterType("Sobel") { } ossimRefPtr ossimEdgeFilter::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { if(!isSourceEnabled()) { return ossimImageSourceFilter::getTile(rect, resLevel); } // expand the rect out to cver the 3x3 horizontal and vertical // kernel. // ossimIrect requestRect = rect; adjustRequestRect(requestRect); ossimRefPtr inputData = ossimImageSourceFilter::getTile(requestRect, resLevel); if(!inputData.valid() || (!inputData->getBuf())) { return inputData; } if(!theTile.valid()) initialize(); if(!theTile.valid()) return theTile; theTile->setImageRectangleAndBands(rect, inputData->getNumberOfBands()); switch(theTile->getScalarType()) { case OSSIM_UCHAR: { runFilter((ossim_uint8)0, inputData); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { runFilter((ossim_float32)0, inputData); break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { runFilter((ossim_uint16)0, inputData); break; } case OSSIM_SSHORT16: { runFilter((ossim_sint16)0, inputData); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { runFilter((ossim_float64)0, inputData); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimEdgeFilter::getTile WARN: Scalar type = " << theTile->getScalarType() << " Not supported by ossimEdgeFilter" << std::endl; break; } } return theTile; } void ossimEdgeFilter::initialize() { ossimImageSourceFilter::initialize(); theTile = NULL; if(!isSourceEnabled()) { return; } theTile = ossimImageDataFactory::instance()->create(this, this); if(theTile.valid()) { theTile->initialize(); } } void ossimEdgeFilter::getFilterTypeNames( std::vector& filterNames)const { filterNames.push_back("Laplacian"); filterNames.push_back("Prewitt"); filterNames.push_back("Roberts"); filterNames.push_back("Simple"); filterNames.push_back("Sobel"); filterNames.push_back("LocalMax8"); } ossimString ossimEdgeFilter::getFilterType()const { return theFilterType; } void ossimEdgeFilter::setFilterType(const ossimString& filterType) { ossimString tempFilterType = filterType; tempFilterType = tempFilterType.downcase(); if(tempFilterType.contains("sob")) { theFilterType = "Sobel"; } else if(tempFilterType.contains("lap")) { theFilterType = "Laplacian"; } else if(tempFilterType.contains("prew")) { theFilterType = "Prewitt"; } else if(tempFilterType.contains("rob")) { theFilterType = "Roberts"; } else if(tempFilterType.contains("sim")) { theFilterType = "Simple"; } else if(tempFilterType.contains("localmax")) { theFilterType = "LocalMax8"; } else { theFilterType = "Sobel"; } } void ossimEdgeFilter::setProperty(ossimRefPtr property) { if(!property) return; if(property->getName() == PROP_EDGE_FILTER) { theFilterType = property->valueToString(); } else { ossimImageSourceFilter::setProperty(property.get()); } } ossimRefPtr ossimEdgeFilter::getProperty(const ossimString& name)const { if(name == PROP_EDGE_FILTER) { std::vector filterNames; getFilterTypeNames(filterNames); ossimStringProperty* stringProp = new ossimStringProperty(PROP_EDGE_FILTER, theFilterType, false, filterNames); stringProp->clearChangeType(); stringProp->setReadOnlyFlag(false); stringProp->setCacheRefreshBit(); return stringProp; } return ossimImageSourceFilter::getProperty(name); } void ossimEdgeFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back(PROP_EDGE_FILTER); } void ossimEdgeFilter::adjustRequestRect(ossimIrect& requestRect)const { ossimString filterType = theFilterType; filterType = filterType.downcase(); ossimIrect rect = requestRect; if(filterType.contains("sob")|| filterType.contains("lap")|| filterType.contains("pre")|| filterType.contains("localmax")) { requestRect = ossimIrect(rect.ul().x - 1, rect.ul().y - 1, rect.lr().x + 1, rect.lr().y + 1); } else if (filterType.contains("rob") || filterType.contains("sim")) { requestRect = ossimIrect(rect.ul().x, rect.ul().y, rect.lr().x + 1, rect.lr().y + 1); } else { requestRect = ossimIrect(rect.ul().x - 1, rect.ul().y - 1, rect.lr().x + 1, rect.lr().y + 1); } } template void ossimEdgeFilter::runFilter(T dummyVariable, ossimRefPtr inputData) { ossimString filterType = theFilterType; filterType = filterType.downcase(); if(filterType.contains("sobel")) { runSobelFilter(dummyVariable, inputData); } else if(filterType.contains("lap")) { runLaplacianFilter(dummyVariable, inputData); } else if(filterType.contains("pre")) { runPrewittFilter(dummyVariable, inputData); } else if(filterType.contains("rob")) { runRobertsFilter(dummyVariable, inputData); } else if(filterType.contains("sim")) { runSimpleFilter(dummyVariable, inputData); } else if(filterType.contains("localmax")) { runLocalMax8Filter(dummyVariable, inputData); } else { theTile->makeBlank(); } } template void ossimEdgeFilter::runSobelFilter(T /* dummyVariable */, ossimRefPtr inputData) { ossim_uint32 bandIdx = 0; ossim_uint32 numberOfBands = inputData->getNumberOfBands(); double horizontalValue = 0.0; double verticalValue = 0.0; double value = 0.0; // ossim_uint32 valueIdx = 0; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 width = theTile->getWidth(); ossim_uint32 height = theTile->getHeight(); ossim_int32 rowIncrement = inputData->getWidth(); ossim_int32 rowIncrement2 = 2*inputData->getWidth(); for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = static_cast(inputData->getBuf(bandIdx)); T* outputBuf = static_cast(theTile->getBuf(bandIdx)); T np = static_cast(inputData->getNullPix(bandIdx)); T minP = static_cast(inputData->getMinPix(bandIdx)); T maxP = static_cast(inputData->getMaxPix(bandIdx)); if(inputBuf&&outputBuf) { for(y = 0; y < height; ++y) { for(x = 0; x < width; ++x) { if( (*(inputBuf + rowIncrement + 1) != np)) { horizontalValue = ((double)inputBuf[0] - (double)inputBuf[rowIncrement2]) + ((double)(inputBuf[1]*2.0) - (double)( inputBuf[rowIncrement2+1]*2.0)) + ((double)(inputBuf[2]) - (double)(inputBuf[rowIncrement2+2])); verticalValue = ((double)(inputBuf[2]) + (double)inputBuf[rowIncrement+2]*2.0 + (double)inputBuf[rowIncrement2+2]) - (double)(inputBuf[0] + 2.0*(double)inputBuf[rowIncrement] + (double)inputBuf[rowIncrement2]); value = sqrt(horizontalValue*horizontalValue + verticalValue*verticalValue); if((value == np) || (value < minP)) { *outputBuf = (static_cast(minP)); } else if(value > maxP) { *outputBuf = (static_cast(maxP)); } else { *outputBuf = (static_cast(value)); } } else { *outputBuf = np; } ++outputBuf; ++inputBuf; } inputBuf+=2; } } } theTile->validate(); } template void ossimEdgeFilter::runPrewittFilter(T /* dummyVariable */, ossimRefPtr inputData) { ossim_uint32 bandIdx = 0; ossim_uint32 numberOfBands = inputData->getNumberOfBands(); double horizontalValue = 0.0; double verticalValue = 0.0; double value = 0.0; // ossim_uint32 valueIdx = 0; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 width = theTile->getWidth(); ossim_uint32 height = theTile->getHeight(); ossim_int32 rowIncrement = inputData->getWidth(); ossim_int32 rowIncrement2 = 2*inputData->getWidth(); for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = static_cast(inputData->getBuf(bandIdx)); T* outputBuf = static_cast(theTile->getBuf(bandIdx)); T np = static_cast(inputData->getNullPix(bandIdx)); T minP = static_cast(inputData->getMinPix(bandIdx)); T maxP = static_cast(inputData->getMaxPix(bandIdx)); if(inputBuf&&outputBuf) { for(y = 0; y < height; ++y) { for(x = 0; x < width; ++x) { if( (*(inputBuf + rowIncrement + 1) != np)) { horizontalValue = ((double)inputBuf[0] - (double)inputBuf[rowIncrement2]) + ((double)(inputBuf[1]) - (double)( inputBuf[rowIncrement2+1])) + ((double)(inputBuf[2]) - (double)(inputBuf[rowIncrement2+2])); verticalValue = ((double)(inputBuf[2]) + (double)inputBuf[rowIncrement+2] + (double)inputBuf[rowIncrement2+2]) - ((double)inputBuf[0] + (double)inputBuf[rowIncrement] + (double)inputBuf[rowIncrement2]); value = sqrt(horizontalValue*horizontalValue + verticalValue*verticalValue); if((value == np) || (value < minP)) { *outputBuf = (static_cast(minP)); } else if(value > maxP) { *outputBuf = (static_cast(maxP)); } else { *outputBuf = (static_cast(value)); } } else { *outputBuf = np; } ++outputBuf; ++inputBuf; } inputBuf+=2; } } } theTile->validate(); } template void ossimEdgeFilter::runRobertsFilter(T /* dummyVariable */, ossimRefPtr inputData) { ossim_uint32 bandIdx = 0; ossim_uint32 numberOfBands = inputData->getNumberOfBands(); double v1 = 0.0; double v2 = 0.0; double value = 0.0; // ossim_uint32 valueIdx = 0; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 width = theTile->getWidth(); ossim_uint32 height = theTile->getHeight(); ossim_int32 rowIncrement = inputData->getWidth(); for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = static_cast(inputData->getBuf(bandIdx)); T* outputBuf = static_cast(theTile->getBuf(bandIdx)); T np = static_cast(inputData->getNullPix(bandIdx)); T minP = static_cast(inputData->getMinPix(bandIdx)); T maxP = static_cast(inputData->getMaxPix(bandIdx)); if(inputBuf&&outputBuf) { for(y = 0; y < height; ++y) { for(x = 0; x < width; ++x) { if( (*inputBuf) != np) { v1 = (double)inputBuf[0] - (double)(inputBuf[rowIncrement+1]); v1 = (double)inputBuf[0] - (double)(inputBuf[1]); v2 = (double)inputBuf[1] - (double)inputBuf[rowIncrement]; v2 = (double)inputBuf[0] - (double)inputBuf[rowIncrement]; value = sqrt(v1*v1 + v2*v2); if((value == np) || (value < minP)) { *outputBuf = (static_cast(minP)); } else if(value > maxP) { *outputBuf = (static_cast(maxP)); } else { *outputBuf = (static_cast(value)); } } else { *outputBuf = np; } ++outputBuf; ++inputBuf; } ++inputBuf; } } } theTile->validate(); } template void ossimEdgeFilter::runSimpleFilter(T /* dummyVariable */, ossimRefPtr inputData) { ossim_uint32 bandIdx = 0; ossim_uint32 numberOfBands = inputData->getNumberOfBands(); double v1 = 0.0; double v2 = 0.0; double value = 0.0; // ossim_uint32 valueIdx = 0; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 width = theTile->getWidth(); ossim_uint32 height = theTile->getHeight(); ossim_int32 rowIncrement = inputData->getWidth(); for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = static_cast(inputData->getBuf(bandIdx)); T* outputBuf = static_cast(theTile->getBuf(bandIdx)); T np = static_cast(inputData->getNullPix(bandIdx)); T minP = static_cast(inputData->getMinPix(bandIdx)); T maxP = static_cast(inputData->getMaxPix(bandIdx)); if(inputBuf&&outputBuf) { for(y = 0; y < height; ++y) { for(x = 0; x < width; ++x) { if( (*inputBuf) != np) { v1 = (double)inputBuf[0] - (double)(inputBuf[1]); v2 = (double)inputBuf[0] - (double)inputBuf[rowIncrement]; value = sqrt(v1*v1 + v2*v2); if((value == np) || (value < minP)) *outputBuf = (static_cast(minP)); else if(value > maxP) *outputBuf = (static_cast(maxP)); else *outputBuf = (static_cast(value)); } else { *outputBuf = np; } ++outputBuf; ++inputBuf; } ++inputBuf; } } } theTile->validate(); } template void ossimEdgeFilter::runLaplacianFilter(T /* dummyVariable */, ossimRefPtr inputData) { ossim_uint32 bandIdx = 0; ossim_uint32 numberOfBands = inputData->getNumberOfBands(); // double horizontalValue = 0.0; // double verticalValue = 0.0; double value = 0.0; // ossim_uint32 valueIdx = 0; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 width = theTile->getWidth(); ossim_uint32 height = theTile->getHeight(); ossim_int32 rowIncrement = inputData->getWidth(); ossim_int32 rowIncrement2 = 2*inputData->getWidth(); for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = static_cast(inputData->getBuf(bandIdx)); T* outputBuf = static_cast(theTile->getBuf(bandIdx)); T np = static_cast(inputData->getNullPix(bandIdx)); T minP = static_cast(inputData->getMinPix(bandIdx)); T maxP = static_cast(inputData->getMaxPix(bandIdx)); if(inputBuf&&outputBuf) { for(y = 0; y < height; ++y) { for(x = 0; x < width; ++x) { if( (*(inputBuf + rowIncrement + 1) != np)) { value = fabs(((double)inputBuf[rowIncrement + 1]*4.0) - ((double)inputBuf[1] + (double)inputBuf[rowIncrement] + (double)inputBuf[rowIncrement + 2] + (double)inputBuf[rowIncrement2+1])); if((value == np) || (value < minP)) { *outputBuf = (static_cast(minP)); } else if(value > maxP) { *outputBuf = (static_cast(maxP)); } else { *outputBuf = (static_cast(value)); } } else { *outputBuf = np; } ++outputBuf; ++inputBuf; } inputBuf+=2; } } } theTile->validate(); } template void ossimEdgeFilter::runLocalMax8Filter(T /* dummyVariable */, ossimRefPtr inputData) { ossim_uint32 bandIdx = 0; ossim_uint32 numberOfBands = inputData->getNumberOfBands(); ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 width = theTile->getWidth(); ossim_uint32 height = theTile->getHeight(); ossim_int32 rowIncrement = inputData->getWidth(); ossim_int32 rowIncrement2 = 2*inputData->getWidth(); for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { //inputBuf has a 1 pixel edge compared to outputBuf T* inputBuf = static_cast(inputData->getBuf(bandIdx)); T* outputBuf = static_cast(theTile->getBuf(bandIdx)); T np = static_cast(inputData->getNullPix(bandIdx)); //changed to input Null if(inputBuf&&outputBuf) { //one pass: maybe faster if changed to two passes T* outB; T* inB; outB = outputBuf; inB = inputBuf; for(y = 0; y < height; ++y) { for(x = 0; x < width; ++x) { if (inB[1+rowIncrement] != np) { *outB = max( max( max(inB[0],inB[1]), max(inB[2],inB[rowIncrement])), max( max(inB[rowIncrement+2],inB[rowIncrement2]), max(inB[rowIncrement2+1],inB[rowIncrement2+2]) )); } else { *outB = np; } ++outB; ++inB; } inB+=2; //go to next line, jump due to edge } } } theTile->validate(); } bool ossimEdgeFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, PROP_EDGE_FILTER, getFilterType(), true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimEdgeFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* value = kwl.find(prefix, PROP_EDGE_FILTER ); if(value) { setFilterType(ossimString(value)); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimEdgeFilter::loadState WARN: no filter type found" << std::endl; } return ossimImageSourceFilter::loadState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimElevImageSource.cpp000066400000000000000000000525531352751253100227250ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class provides an elevation image source from the elevation // manager. // //******************************************************************* // $Id: ossimElevImageSource.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include RTTI_DEF1(ossimElevImageSource, "ossimElevImageSource", ossimImageSource) // Static trace for debugging static ossimTrace traceDebug("ossimElevImage:debug"); using namespace std; ossimElevImageSource::ossimElevImageSource() : ossimImageSource(NULL, 0, 0, true, false),// output list is not fixed theElevManager(NULL), theTile(NULL), theTiePoint(), theLatSpacing(0.0), theLonSpacing(0.0), theNumberOfLines(0), theNumberOfSamps(0) {} ossimElevImageSource::ossimElevImageSource(ossimObject* owner) : ossimImageSource(owner, 0, 0, true, false),// output list is not fixed theElevManager(NULL), theTile(NULL), theTiePoint(), theLatSpacing(0.0), theLonSpacing(0.0), theNumberOfLines(0), theNumberOfSamps(0) {} ossimElevImageSource::ossimElevImageSource(ossimObject* owner, const ossimGpt& tie, double latSpacing, double lonSpacing, ossim_uint32 numberLines, ossim_uint32 numberSamples) : ossimImageSource(owner, 0, 0, true, false),// output list is not fixed theElevManager(NULL), theTile(NULL), theTiePoint(tie), theLatSpacing(latSpacing), theLonSpacing(lonSpacing), theNumberOfLines(numberLines), theNumberOfSamps(numberSamples) { initialize(); } ossimElevImageSource::ossimElevImageSource(ossimObject* owner, const ossimKeywordlist& kwl, const char* prefix) : ossimImageSource(owner, 0, 0, true, false), theElevManager(NULL), theTile(NULL), theTiePoint(), theLatSpacing(0), theLonSpacing(0), theNumberOfLines(0), theNumberOfSamps(0) { if (loadState(kwl, prefix) == false) { setErrorStatus(); } } ossimElevImageSource::~ossimElevImageSource() { } ossimRefPtr ossimElevImageSource::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { if (!theTile.get()) { return theTile; } // First make sure our tile is the right size. ossim_int32 w = tile_rect.width(); ossim_int32 h = tile_rect.height(); ossim_int32 tileW = theTile->getWidth(); ossim_int32 tileH = theTile->getHeight(); if( (w != tileW) || (h != tileH) ) { theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tileW*tileH)) { theTile->initialize(); //*** // Initialize can reset the min max to defaults if the min happens // to be "0" so reset it just in case. // NOTE: We need to fix initialize! //*** theTile->setMinPix(theElevManager->getMinHeightAboveMSL(), 0); theTile->setMaxPix(theElevManager->getMaxHeightAboveMSL(), 0); } } // Set the origin. theTile->setOrigin(tile_rect.ul()); if(!isSourceEnabled()) { // This tile source bypassed. theTile->makeBlank(); return theTile; } //*** // No overview support yet... //*** if (resLevel) { // NOTE: Need to add overview support. cerr << "ossimElevImageSource::getTile ERROR:\nOverviews not supported!" << endl; theTile->makeBlank(); return theTile; } ossimIrect image_rect = getImageRectangle(0); if ( !tile_rect.intersects(image_rect) ) { // No point in the tile falls within the set boundaries of this source. theTile->makeBlank(); return theTile; } // Ok fill the tile with the data from the post... ossimIrect clip_rect = tile_rect.clipToRect(image_rect); if ( !tile_rect.completely_within(clip_rect) ) { // Start with a blank tile since it won't be filled all the way. theTile->makeBlank(); } // Move the buffer pointer to the first valid pixel. ossim_uint32 tile_width = theTile->getWidth(); ossim_int32 start_offset = (clip_rect.lr().y - tile_rect.ul().y) * tile_width + clip_rect.ul().x - tile_rect.ul().x; //*** // Since most elevation formats have posts organized positive line up, // start at the lower left side of the cell so all reads are going // forward in the file. //*** double start_lat = theTiePoint.latd() - theLatSpacing * (clip_rect.lr().y - image_rect.ul().y); if (start_lat < -90.0) { start_lat = -(start_lat + 180.0); // Wrapped around the south poll. } double lon = theTiePoint.lond() + theLonSpacing * (clip_rect.ul().x - image_rect.ul().x); if (lon > 180.0) { lon -= 360.0; // Went across the central meridian. } // Copy the data. ossim_uint32 clipHeight = clip_rect.height(); ossim_uint32 clipWidth = clip_rect.width(); // Get a pointer to the tile buffer. ossim_float32* buf = static_cast(theTile->getBuf()); for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { double lat = start_lat; ossim_int32 offset = start_offset; for (ossim_uint32 line = 0; line < clipHeight; ++line) { ossimGpt gpt(lat, lon); buf[offset+sample] = theElevManager->getHeightAboveMSL(gpt); lat += theLatSpacing; if (lat > 90) lat = 180.0 - lat; offset -= tile_width; } lon += theLonSpacing; if (lon > 180.0) lon = lon - 360.0; // Went across the central meridian. } #if 0 for (ossim_uint32 line = 0; line < clipHeight; ++line) { double lon = start_lon; for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { ossimGpt gpt(lat, lon); buf[sample] = theElevManager->getHeightAboveMSL(gpt); lon += theLonSpacing; if (start_lon > 180.0) { start_lon -= 360.0; // Went across the central meridian. } } buf += tile_width; lat -= theLatSpacing; if (lat < -90.0) lat = -(lat + 180.0);// Wrapped around the south poll. } #endif theTile->validate(); return theTile; } bool ossimElevImageSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { static const char MODULE[] = "ossimElevImageSource::saveState"; if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { cerr << MODULE << " ERROR detected in keyword list! State not saved." << endl; return false; } // Save the state of the base class. ossimImageSource::saveState(kwl, prefix); // Save the tie point. kwl.add(prefix, ossimKeywordNames::TIE_POINT_LAT_KW, theTiePoint.latd(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LON_KW, theTiePoint.lond(), true); // Save the post spacing. kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, theLatSpacing, true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, theLonSpacing, true); // Save the image size kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, theNumberOfLines, true); kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, theNumberOfSamps, true); // Save the min / max pixel values. kwl.add(prefix, ossimKeywordNames::MIN_VALUE_KW, getMinPixelValue(0), true); kwl.add(prefix, ossimKeywordNames::MAX_VALUE_KW, getMaxPixelValue(0), true); return true; } //******************************************************************* // Public method: //******************************************************************* bool ossimElevImageSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimElevImageSource::loadState"; if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { cerr << MODULE << " ERROR detected in keyword list! State not load." << endl; return false; } // Base class... ossimImageSource::loadState(kwl, prefix); const char* lookup; // Get the tie point. lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LAT_KW); if (lookup) { theTiePoint.latd(ossimString(lookup).toDouble()); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nRequired keyword not found: " << ossimKeywordNames::TIE_POINT_LAT_KW << "\nReturning false" << endl; } return false; } lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LON_KW); if (lookup) { theTiePoint.lond(ossimString(lookup).toDouble()); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nRequired keyword not found: " << ossimKeywordNames::TIE_POINT_LON_KW << "\nReturning false" << endl; } return false; } // Get the post spacing. lookup = kwl.find(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT); if (lookup) { theLatSpacing = ossimString(lookup).toDouble(); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nRequired keyword not found: " << ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT << "\nReturning false" << endl; } return false; } lookup = kwl.find(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON); if (lookup) { theLonSpacing = ossimString(lookup).toDouble(); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nRequired keyword not found: " << ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON << "\nReturning false" << endl; } return false; } // Get the image size. lookup = kwl.find(prefix, ossimKeywordNames::NUMBER_LINES_KW); if (lookup) { theNumberOfLines = ossimString(lookup).toULong(); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nRequired keyword not found: " << ossimKeywordNames::NUMBER_LINES_KW << "\nReturning false" << endl; } return false; } lookup = kwl.find(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW); if (lookup) { theNumberOfSamps = ossimString(lookup).toULong(); } else { if (traceDebug()) { CLOG << "DEBUG:" << "\nRequired keyword not found: " << ossimKeywordNames::NUMBER_SAMPLES_KW << "\nReturning false" << endl; } return false; } initialize(); //*** // See if the min / max keyword was set and reset it. // Note this must be done after initialize since it sets the min / max from // the elevation manager. //*** lookup = kwl.find(prefix, ossimKeywordNames::MIN_VALUE_KW); if (lookup) { setMinPixelValue(ossimString(lookup).toDouble()); } lookup = kwl.find(prefix, ossimKeywordNames::MAX_VALUE_KW); if (lookup) { setMaxPixelValue(ossimString(lookup).toDouble()); } if (getErrorStatus() != ossimErrorCodes::OSSIM_OK) { return false; } //*** // Reset the base class to have a fixed input list of "0" size. // Note: To not do this will result in a core dump destroying objects // connected to this output. //*** theInputObjectList.clear(); theInputListIsFixedFlag = true; theOutputListIsFixedFlag = false; return true; } void ossimElevImageSource::initialize() { static const char MODULE[] = "ossimElevImageSource::initialize"; if (traceDebug()) CLOG << " Entered..." << endl; //*** // First see if the manager pointer has been captured. //*** if (!theElevManager) theElevManager = ossimElevManager::instance(); if (!theElevManager) { setErrorStatus(); cerr << MODULE << "ERROR:\nNULL elevation manager pointer!" << "\nObject not initialized!" << endl; return; } // Basic sanity checks. if (!theLatSpacing || !theLonSpacing || !theNumberOfLines || !theNumberOfSamps) { setErrorStatus(); cerr << MODULE << "ERROR:" << "\nMust set latitude/longitude spacing and number of line and" << " samples." << "Object not initialized!" << endl; return; } // Check the ground point. if ( theTiePoint.latd() > 90.0 || theTiePoint.latd() < -90.0 || theTiePoint.lond() > 180.0 || theTiePoint.lond() < -180.0 ) { setErrorStatus(); cerr << MODULE << "ERROR:\nBogus tie point." << "\nObject not initialized!" << endl; return; } if (traceDebug()) { CLOG << "DEBUG:" << "\nTie point: " << theTiePoint << "\nLatitude spacing: " << theLatSpacing << "\nLongitude spacing: " << theLonSpacing << "\nLines: " << theNumberOfLines << "\nSamples: " << theNumberOfSamps << endl; } //*** // Since this will return float data we need to set the min / max values // of the data so that anybody who remaps it to eight bit will do it // properly. So scan the entire image rectangle using the manager. // This will do two things, force the elevation manager to load all the // cells, and at the same time the min / max elevation value will be set. // NOTE: // ??? Should the elevation manager clear the list of sources prior to // the code segment so that the min / max is only from the cells we // need! //*** cout << "Initializing elevation manager..." << endl; #if 0 // Loop in the longitude or sample direction. time_t start_t = time(NULL); double lon = theTiePoint.lond(); for (ossim_uint32 samp = 0; samp < theNumberOfSamps; ++samp) { double lat = theTiePoint.latd() - theLatSpacing * (theNumberOfLines - 1); if (lat < -90.0) lat = -(lat + 180.0); // Wrapped around the south poll. for (ossim_uint32 line = 0; line < theNumberOfLines; ++line) { ossimGpt gpt(lat, lon); theElevManager->getHeightAboveMSL(gpt); lat += theLatSpacing; if (lat > 90) lat = 180 - lat; // Went across poll. } lon += theLonSpacing; if (lon > 180.0) lon -= 360.0; // Went across the central meridian. } time_t stop_t = time(NULL); cout << "Finished loop two..." << endl; cout << "Elapsed time for loop two: " << (stop_t - start_t) << endl; #endif theTile = new ossimImageData(this, OSSIM_FLOAT); theTile->initialize(); // Set the min / max for any normalization down the chain... theTile->setMinPix(theElevManager->getMinHeightAboveMSL(), 0); theTile->setMaxPix(theElevManager->getMaxHeightAboveMSL(), 0); if (traceDebug()) { CLOG << "DEBUG:" << "\nMin pix: " << theTile->getMinPix(0) << "\nMax pix: " << theTile->getMaxPix(0) << endl; } } ossimIrect ossimElevImageSource::getImageRectangle(ossim_uint32 reduced_res_level) const { ossimIrect result(0, 0, theNumberOfSamps-1, theNumberOfLines-1); if (reduced_res_level != 0) { cerr << "ossimElevImageSource::getImageRectangle ERROR:" << "\nOnly R0 is supported." << endl; } return result; } bool ossimElevImageSource::getImageGeometry(ossimKeywordlist& kwl, const char* prefix) { // Save off the image dimensions. kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, theNumberOfLines, true); kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, theNumberOfLines, true); // Save off the projection info (tie and post spacing). ossimLlxyProjection proj(theTiePoint, theLatSpacing, theLonSpacing); return proj.saveState(kwl, prefix); } void ossimElevImageSource::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { if (resLevel) { cerr << "ossimElevImageSource::getDecimationFactor ERROR:" << "\nReduced res sets currently not supported!" << endl; } result.line = 1.0; result.samp = 1.0; } void ossimElevImageSource::getDecimationFactors(vector& decimations) const { ossimDpt pt(1.0, 1.0); decimations.clear(); decimations.push_back(pt); } ossim_uint32 ossimElevImageSource::getNumberOfDecimationLevels()const { return 1; } ossim_uint32 ossimElevImageSource::getNumberOfInputBands() const { return 1; } ossimScalarType ossimElevImageSource::getOutputScalarType() const { return OSSIM_FLOAT; } ossim_uint32 ossimElevImageSource::getTileWidth() const { if (theTile.get()) return theTile->getWidth(); return 0; } ossim_uint32 ossimElevImageSource::getTileHeight() const { if (theTile.get()) return theTile->getHeight(); return 0; } void ossimElevImageSource::changeTileSize(const ossimIpt& size) { if (traceDebug()) { cout << "ossimElevImageSource::changeTileSize DEBUG:" << "\nx size: " << size.x << "\ny size: " << size.y << endl; } if (!theTile) { cerr << "ossimElevImageSource::changeTileSize ERROR:" << "\nObject not initialized! Returning..." << endl; return; } theTile = new ossimImageData(this, OSSIM_FLOAT, 1, size.x, size.y); theTile->initialize(); // Set the min / max for any normalization down the chain... theTile->setMinPix(theElevManager->getMinHeightAboveMSL(), 0); theTile->setMaxPix(theElevManager->getMaxHeightAboveMSL(), 0); } ossim_uint32 ossimElevImageSource::getNumberOfLines(ossim_uint32 reduced_res_level) const { if (reduced_res_level) { cerr << "ossimElevImageSource::getNumberOfLines ERROR:" << "\nReduced res sets currently not supported!" << endl; return 0; } return theNumberOfLines; } ossim_uint32 ossimElevImageSource::getNumberOfSamples(ossim_uint32 reduced_res_level) const { if (reduced_res_level) { cerr << "ossimElevImageSource::getNumberOfSamples ERROR:" << "\nReduced res sets currently not supported!" << endl; return 0; } return theNumberOfSamps; } double ossimElevImageSource::getMinPixelValue(ossim_uint32 band) const { if (band) { cerr << "ossimElevImageSource::getMinPixelValue ERROR:" << "\nReduced res sets currently not supported!" << endl; return 0.0; } if (theTile.get()) { return theTile->getMinPix(0); } else if (theElevManager) { return theElevManager->getMinHeightAboveMSL(); } return 0.0; } double ossimElevImageSource::getMaxPixelValue(ossim_uint32 band) const { if (band) { cerr << "ossimElevImageSource::getMaxPixelValue ERROR:" << "\nReduced res sets currently not supported!" << endl; return 0.0; } if (theTile.get()) { return theTile->getMaxPix(0); } else if (theElevManager) { return theElevManager->getMaxHeightAboveMSL(); } return 0.0; } void ossimElevImageSource::setMinPixelValue(ossim_float64 min_pix) { if (theTile.get()) { theTile->setMinPix(min_pix, 0); if (traceDebug()) { cout << "ossimElevImageSource::setMinPixelValue DEBUG:" << "\nMin pixel value: " << min_pix << endl; } } else { cerr << "ossimElevImageSource::setMinPixelValue ERROR:" << "\nObject not initialized!" << endl; } } void ossimElevImageSource::setMaxPixelValue(ossim_float64 max_pix) { if (theTile.get()) { theTile->setMaxPix(max_pix, 0); if (traceDebug()) { cout << "ossimElevImageSource::setMaxPixelValue DEBUG:" << "\nMax pixel value: " << max_pix << endl; } } else { cerr << "ossimElevImageSource::setMinPixelValue ERROR:" << "\nObject not initialized!" << endl; } } ossim-Miami-2.9.1/src/imaging/ossimElevRemapper.cpp000066400000000000000000000205371352751253100222720ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: RP // // Description: // // //******************************************************************* // $Id$ #include #include #include #include RTTI_DEF1(ossimElevRemapper, "ossimElevRemapper", ossimImageSourceFilter); static ossimTrace traceDebug("ossimElevRemapper::debug"); const char ossimElevRemapper::REMAP_MODE_KW[] = "remap_mode"; using namespace std; ossimElevRemapper::ossimElevRemapper() :m_replacementType(ReplacementType_ELLIPSOID) { } ossimElevRemapper::~ossimElevRemapper() { m_imageGeometry = 0; } void ossimElevRemapper::initialize() { if (theInputConnection && (!m_imageGeometry.valid() || !m_imageGeometry->getProjection())) { m_imageGeometry = theInputConnection->getImageGeometry(); } } ossimRefPtr ossimElevRemapper::getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimElevRemapper::getTile entered..." << endl; } ossimRefPtr result = ossimImageSourceFilter::getTile(tile_rect, resLevel); if(!isSourceEnabled()||!result.valid()) { return result.get(); } ossimDataObjectStatus status = result->getDataObjectStatus(); if(status == OSSIM_NULL) { return result.get(); } // Call the appropriate load method. switch (result->getScalarType()) { case OSSIM_UCHAR: { elevRemap(ossim_uint8(0), result.get(), resLevel); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { elevRemap(ossim_uint16(0), result.get(), resLevel); break; } case OSSIM_SSHORT16: { elevRemap(ossim_sint16(0), result.get(), resLevel); break; } case OSSIM_UINT32: { elevRemap(ossim_uint32(0), result.get(), resLevel); break; } case OSSIM_SINT32: { elevRemap(ossim_sint32(0), result.get(), resLevel); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { elevRemap(ossim_float32(0), result.get(), resLevel); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { elevRemap(ossim_float64(0), result.get(), resLevel); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimElevRemapper::getTile Unsupported scalar type!" << endl; break; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimElevRemapper::getTile leaving..." << endl; } return result; } template void ossimElevRemapper::elevRemap(T /* dummy */, ossimImageData* inputTile, ossim_uint32 resLevel) { if (!inputTile) return; ossimIrect rect = inputTile->getImageRectangle(); ossimIrect imageBounds = getBoundingRect(resLevel); ossimIrect clipRect; if(!rect.intersects(imageBounds)) { return; } clipRect = rect.clipToRect(imageBounds); if (m_imageGeometry.valid() && m_imageGeometry->getProjection()) { ossimGpt ul, ll, lr, ur; ossim_float32 hul, hll, hlr, hur; ossim_float32 height = 0.0, xpercent, ypercent, uppery, lowery; m_imageGeometry->rnToWorld(clipRect.ul(), resLevel, ul); m_imageGeometry->rnToWorld(clipRect.ur(), resLevel, ur); m_imageGeometry->rnToWorld(clipRect.ll(), resLevel, ll); m_imageGeometry->rnToWorld(clipRect.lr(), resLevel, lr); //std::cout << "UL: " << clipRect.ul() << " RES: " << ossimString::toString(resLevel) << " ULGROUND: " << ul << "\n"; hul = ossimGeoidManager::instance()->offsetFromEllipsoid(ul); hll = ossimGeoidManager::instance()->offsetFromEllipsoid(ll); hlr = ossimGeoidManager::instance()->offsetFromEllipsoid(lr); hur = ossimGeoidManager::instance()->offsetFromEllipsoid(ur); // std::cout << "HUL: " << ossimString::toString(hul) << " HUR: " << ossimString::toString(hur) << " HLR: " << ossimString::toString(hlr) << " HUR: " << ossimString::toString(hur) << "\n"; if(!rect.completely_within(imageBounds)) { ossim_uint32 bands = inputTile->getNumberOfBands(); ossimIpt origin = clipRect.ul() - rect.ul(); ossim_uint32 bandIdx = 0; ossim_uint32 inputW = inputTile->getWidth(); ossim_uint32 originOffset = origin.y*inputW + origin.x; ossim_uint32 w = clipRect.width(); ossim_uint32 h = clipRect.height(); ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_float32 height = 0.0, xpercent, ypercent, uppery, lowery; for(bandIdx = 0; bandIdx < bands; ++bandIdx) { T* bandPtr = static_cast(inputTile->getBuf(bandIdx)) + originOffset; for(y = 0; y < h; ++y) { for(x = 0; x < w; ++x) { xpercent = x / clipRect.width(); ypercent = y / clipRect.height(); uppery = hul + xpercent * ( hur - hul); lowery = hll + xpercent * ( hlr - hll); height = uppery + ypercent * ( lowery - uppery ); if (m_replacementType==ReplacementType_GEOID) height*=-1.0; bandPtr[x] += height; } bandPtr += inputW; } } } else { ossim_uint32 bands = inputTile->getNumberOfBands(); ossim_uint32 bandIdx = 0; ossim_uint32 size = inputTile->getWidth()*inputTile->getHeight(); ossim_float32 height = 0.0; for(bandIdx = 0; bandIdx < bands; ++bandIdx) { T* bandPtr = static_cast(inputTile->getBuf(bandIdx)); ossim_uint32 idx = 0; for(idx = 0; idx < size;++idx) { ossim_uint32 y = idx / rect.width(); ossim_uint32 x = idx % rect.width(); xpercent = x / clipRect.width(); ypercent = y / clipRect.height(); uppery = hul + xpercent * ( hur - hul); lowery = hll + xpercent * ( hlr - hll); height = uppery + ypercent * ( lowery - uppery ); if (m_replacementType==ReplacementType_GEOID) height*=-1.0; (*bandPtr) += height; ++bandPtr; } } } } } bool ossimElevRemapper::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimImageSourceFilter::saveState(kwl, prefix); ossimString remapMode = ""; switch(m_replacementType) { case ReplacementType_ELLIPSOID: remapMode = "ellipsoid"; break; case ReplacementType_GEOID: remapMode = "geoid"; break; default: remapMode = "ellipsoid"; break; } kwl.add(prefix, REMAP_MODE_KW, remapMode.c_str()); ossimString imagePrefix = ossimString(prefix)+"image_geometry."; if(m_imageGeometry.valid()) { m_imageGeometry->saveState(kwl, imagePrefix.c_str()); } //std::cout << kwl << " SAVESTATE\n"; return result; } bool ossimElevRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { //std::cout << kwl << " LOADSTATE\n"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimElevRemapper::loadState entered..." << endl; } bool result = ossimImageSourceFilter::loadState(kwl, prefix); const char* lookup; lookup = kwl.find(prefix, REMAP_MODE_KW); if(lookup) { ossimString mode = lookup; mode.upcase(); if (mode == "ELLIPSOID") { m_replacementType = ReplacementType_ELLIPSOID; } else if (mode == "GEOID") { m_replacementType = ReplacementType_GEOID; } } ossimString imagePrefix = ossimString(prefix)+"image_geometry."; if(kwl.numberOf(imagePrefix.c_str())>0) { m_imageGeometry = new ossimImageGeometry(); m_imageGeometry->loadState(kwl, imagePrefix.c_str()); //setImageGeometry(m_igeometry.get()); } return result; } ossim-Miami-2.9.1/src/imaging/ossimElevationMosaic.cpp000066400000000000000000000417101352751253100227610ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: // // Description: implementation for image mosaic // //************************************************************************* // $Id: ossimElevationMosaic.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include static const ossimTrace traceDebug("ossimElevationMosaic:debug"); static const ossim_float32 MIN_ELEVATION = -500.0; static const ossim_float32 MAX_ELEVATION = 32000.0; using namespace std; RTTI_DEF1(ossimElevationMosaic, "ossimElevationMosaic", ossimImageCombiner) ossimElevationMosaic::ossimElevationMosaic() :ossimImageCombiner(), theTile(NULL) { } ossimElevationMosaic::ossimElevationMosaic(ossimConnectableObject::ConnectableObjectList& inputSources) : ossimImageCombiner(inputSources), theTile(NULL) { } ossimElevationMosaic::~ossimElevationMosaic() { } ossimRefPtr ossimElevationMosaic::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { long size = getNumberOfInputs(); ossim_uint32 layerIdx = 0; // If there is only one in the mosaic then just return it. if(size == 1) { return getNextTile(layerIdx, 0, tileRect, resLevel); } ossimIpt origin = tileRect.ul(); ossim_uint32 w = tileRect.width(); ossim_uint32 h = tileRect.height(); if(!theTile.valid()) { // try to initialize allocate(); // if we still don't have a buffer // then we will leave if(!theTile.valid()) { return ossimRefPtr(); } } ossim_uint32 tileW = theTile->getWidth(); ossim_uint32 tileH = theTile->getHeight(); if((w != tileW)|| (h != tileH)) { theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tileW*tileH)) { theTile->initialize(); } } theTile->setOrigin(origin); //--- // General Note: // // Note: I will not check for disabled or enabled since we have // no clear way to handle this within a mosaic. The default will be // to do a simple a A over B type mosaic. Derived classes should // check for the enabled and disabled and always // use this default implementation if they are disabled. //--- theTile->setOrigin(origin); theTile->makeBlank(); switch(theTile->getScalarType()) { case OSSIM_UCHAR: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SINT8: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SSHORT16: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SINT32: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_UINT32: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "Scalar type = " << theTile->getScalarType() << " Not supported by ossimElevationMosaic" << endl; } } return ossimRefPtr(); } void ossimElevationMosaic::initialize() { ossimImageCombiner::initialize(); theTile = NULL; } void ossimElevationMosaic::allocate() { theTile = NULL; if( (getNumberOfInputs() > 0) && getInput(0) ) { theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); } } bool ossimElevationMosaic::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimImageCombiner::saveState(kwl, prefix); } bool ossimElevationMosaic::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimImageCombiner::loadState(kwl, prefix); } template ossimRefPtr ossimElevationMosaic::combineNorm( T,// dummy template variable const ossimIrect& tileRect, ossim_uint32 resLevel) { ossim_uint32 layerIdx = 0; //--- // Get the first tile from the input sources. If this(index 0) is blank // that means there are no layers so go no further. //--- ossimRefPtr currentImageData = getNextNormTile(layerIdx, 0, tileRect, resLevel); if(!currentImageData) { return theTile; } ossimRefPtr destination = theTile; ossimDataObjectStatus destinationStatus = theTile->getDataObjectStatus(); float** srcBands = new float*[theLargestNumberOfInputBands]; float* srcBandsNullPix = new float[theLargestNumberOfInputBands]; T** destBands = new T*[theLargestNumberOfInputBands]; T* destBandsNullPix = new T[theLargestNumberOfInputBands]; T* destBandsMinPix = new T[theLargestNumberOfInputBands]; T* destBandsMaxPix = new T[theLargestNumberOfInputBands]; ossim_uint32 band; ossim_uint32 upperBound = destination->getWidth()*destination->getHeight(); ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); destBands[band] = static_cast(theTile->getBuf(band)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); destBandsMinPix[band] = static_cast(theTile->getMinPix(band)); destBandsMaxPix[band] = static_cast(theTile->getMaxPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = static_cast(srcBands[minNumberOfBands - 1]); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); destBands[band] = static_cast(theTile->getBuf(band)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); destBandsMinPix[band] = static_cast(theTile->getMinPix(band)); destBandsMaxPix[band] = static_cast(theTile->getMaxPix(band)); } // Loop to copy from layers to output tile. while(currentImageData.valid()) { //--- // Check the status of the source tile. If empty get the next source // tile and loop back. //--- ossimDataObjectStatus currentStatus = currentImageData->getDataObjectStatus(); if ( (currentStatus == OSSIM_EMPTY) || (currentStatus == OSSIM_NULL) ) { currentImageData = getNextNormTile(layerIdx, tileRect, resLevel); continue; } ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); } if ( (currentStatus == OSSIM_FULL) && (destinationStatus == OSSIM_EMPTY) ) { // Copy full tile to empty tile. for(band=0; band < theLargestNumberOfInputBands; ++band) { float delta = destBandsMaxPix[band] - destBandsMinPix[band]; float minP = destBandsMinPix[band]; for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { destBands[band][offset] = (T)( minP + delta*srcBands[band][offset]); } } } else // Copy tile checking all the pixels... { for(band = 0; band < theLargestNumberOfInputBands; ++band) { float delta = destBandsMaxPix[band] - destBandsMinPix[band]; float minP = destBandsMinPix[band]; for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (destBands[band][offset] < MIN_ELEVATION || destBands[band][offset] > MAX_ELEVATION) //== destBandsNullPix[band]) { if (srcBands[band][offset] > MIN_ELEVATION && srcBands[band][offset] < MAX_ELEVATION) //!= srcBandsNullPix[band]) { destBands[band][offset] = (T)(minP + delta*srcBands[band][offset]); } } } } } // Validate output tile and return if full. destinationStatus = destination->validate(); if (destinationStatus == OSSIM_FULL) { break;//return destination; } // If we get here we're are still not full. Get a tile from next layer. currentImageData = getNextNormTile(layerIdx, tileRect, resLevel); } // Cleanup... delete [] srcBands; delete [] destBands; delete [] srcBandsNullPix; delete [] destBandsNullPix; delete [] destBandsMinPix; delete [] destBandsMaxPix; return destination; } template ossimRefPtr ossimElevationMosaic::combine( T,// dummy template variable const ossimIrect& tileRect, ossim_uint32 resLevel) { ossim_uint32 layerIdx = 0; bool hasInvalidElevations = false; //--- // Get the first tile from the input sources. If this(index 0) is blank // that means there are no layers so go no further. //--- ossimRefPtr currentImageData = getNextTile(layerIdx, 0, tileRect, resLevel); if (!currentImageData) { return theTile; } ossimRefPtr destination = theTile; ossimDataObjectStatus destinationStatus = theTile->getDataObjectStatus(); T** srcBands = new T*[theLargestNumberOfInputBands]; T* srcBandsNullPix = new T[theLargestNumberOfInputBands]; T** destBands = new T*[theLargestNumberOfInputBands]; T* destBandsNullPix = new T[theLargestNumberOfInputBands]; ossim_uint32 band; ossim_uint32 upperBound = destination->getWidth()*destination->getHeight(); ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); destBands[band] = static_cast(theTile->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = static_cast(srcBands[minNumberOfBands - 1]); destBands[band] = static_cast(theTile->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); } // Loop to copy from layers to output tile. while(currentImageData.valid()) { //--- // Check the status of the source tile. If empty get the next source // tile and loop back. //--- ossimDataObjectStatus currentStatus = currentImageData->getDataObjectStatus(); if ( (currentStatus == OSSIM_EMPTY) || (currentStatus == OSSIM_NULL) ) { currentImageData = getNextNormTile(layerIdx, tileRect, resLevel); continue; } ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); } if ( (currentStatus == OSSIM_FULL) && (destinationStatus == OSSIM_EMPTY) ) { // Copy full tile to empty tile. for(ossim_uint32 band=0; band < theLargestNumberOfInputBands; ++band) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { destBands[band][offset] = srcBands[band][offset]; if(destBands[band][offset] < MIN_ELEVATION || destBands[band][offset] > MAX_ELEVATION) { hasInvalidElevations = true; } } } } else // Copy tile checking all the pixels... { for(band = 0; band < theLargestNumberOfInputBands; ++band) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if(destBands[band][offset] < MIN_ELEVATION || destBands[band][offset] > MAX_ELEVATION) //== destBandsNullPix[band]) { hasInvalidElevations = true; destBands[band][offset] = srcBands[band][offset]; } } } } // Validate output tile and return if full. destinationStatus = destination->validate(); if (!hasInvalidElevations) { break; } //if (destinationStatus == OSSIM_FULL) //{ // break;//return destination; //} // If we get here we're are still not full. Get a tile from next layer. currentImageData = getNextTile(layerIdx, tileRect, resLevel); } // Cleanup... delete [] srcBands; delete [] destBands; delete [] srcBandsNullPix; delete [] destBandsNullPix; return destination; } ossim-Miami-2.9.1/src/imaging/ossimEnviHeaderFileWriter.cpp000066400000000000000000000055051352751253100237100ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Class definition for ossimEnviHeaderFileWriter. Meta data class for // writing an ENVI (The Environment for Visualizing Images) header file. // //---------------------------------------------------------------------------- // $Id: ossimEnviHeaderFileWriter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include RTTI_DEF1(ossimEnviHeaderFileWriter, "ossimEnviHeaderFileWriter", ossimMetadataFileWriter) ossimEnviHeaderFileWriter::ossimEnviHeaderFileWriter() : ossimMetadataFileWriter(), theHdr() { } ossimEnviHeaderFileWriter::~ossimEnviHeaderFileWriter() { } bool ossimEnviHeaderFileWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; if (ossimMetadataFileWriter::loadState(kwl, prefix)) { result = theHdr.loadState(kwl, prefix); } return result; } bool writeFile() { bool result = true; return result; } bool ossimEnviHeaderFileWriter::writeFile() { theHdr.setLines(theAreaOfInterest.height()); theHdr.setSamples(theAreaOfInterest.width()); theHdr.setBands(theInputConnection->getNumberOfOutputBands()); // Get the geometry from the input. // Get the geometry from the input. ossimMapProjection* mapProj = 0; ossimRefPtr inputGeom = theInputConnection->getImageGeometry(); if ( inputGeom.valid() ) mapProj = PTR_CAST(ossimMapProjection, inputGeom->getProjection()); if (mapProj) { // Create the projection info. ossimRefPtr projectionInfo = new ossimMapProjectionInfo(mapProj, theAreaOfInterest); // Set the tie points in the keyword list. ossimKeywordlist kwl; projectionInfo->getGeom(kwl); // Pass it on to envi header to set the map info string from geometry. theHdr.setMapInfo(kwl); } return theHdr.writeFile(theFilename); } void ossimEnviHeaderFileWriter::getMetadatatypeList( std::vector& metadatatypeList) const { metadatatypeList.push_back(ossimString("envi_header")); } bool ossimEnviHeaderFileWriter::hasMetadataType( const ossimString& metadataType)const { return (metadataType == "envi_header"); } ossim-Miami-2.9.1/src/imaging/ossimEnviTileSource.cpp000066400000000000000000000176331352751253100226060ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: // // Image handler class for a raster files with an ENVI header file. // //--- // $Id$ #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimEnviTileSource, "ossimEnviTileSource", ossimGeneralRasterTileSource) static ossimTrace traceDebug("ossimEnviTileSource:debug"); ossimEnviTileSource::ossimEnviTileSource() : ossimGeneralRasterTileSource(), m_enviHdr() { } ossimEnviTileSource::~ossimEnviTileSource() { } bool ossimEnviTileSource::open() { static const char MODULE[] = "ossimEnviTileSource::open"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << "\nimage file: " << theImageFile << std::endl; } bool result = false; if(isOpen()) { close(); } // Look for a header file: ossimFilename hdr = theImageFile; hdr.setExtension("hdr"); // image.hdr if ( !hdr.exists() ) { hdr = theImageFile; hdr.string() += ".hdr"; // image.ras.hdr } if ( hdr.exists() ) { if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "header file: " << hdr << std::endl; } if ( m_enviHdr.open( hdr ) ) { if ( m_rasterInfo.initializeFromEnviHdr( m_enviHdr ) ) { // Set image file for initializeHandler method. m_rasterInfo.setImageFile( theImageFile ); // Look for an omd file: ossimFilename omd = theImageFile; omd.setExtension("omd"); // image.omd if ( !omd.exists() ) { omd.setExtension("kwl"); // image.kwl } if ( omd.exists() ) { if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "omd file: " << omd << std::endl; } // Pick up adjusted min / max values if present. ossimKeywordlist kwl( omd ); m_rasterInfo.getImageMetaData().updateMetaData( kwl, std::string("") ); } theMetaData = m_rasterInfo.getImageMetaData(); result = initializeHandler(); if ( result ) { completeOpen(); //--- // This will set default output band list if we are a band selector and // "default bands" key is found in the envi header. If "default bands" // is not found it will set to identity(input = output). //--- setDefaultBandList(); } } } } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Exit status: " << (result?"true":"false") << std::endl; } return result; } //************************************************************************************************ //! Returns the image geometry object associated with this tile source or NULL if non defined. //! The geometry contains full-to-local image transform as well as projection (image-to-world) //************************************************************************************************ ossimRefPtr ossimEnviTileSource::getImageGeometry() { if ( !theGeometry ) { // Check for external geom: theGeometry = getExternalImageGeometry(); if ( !theGeometry ) { // Check the internal geometry first to avoid a factory call. theGeometry = getInternalImageGeometry(); // At this point it is assured theGeometry is set. //--- // WARNING: // Must create/set theGeometry at this point or the next call to // ossimImageGeometryRegistry::extendGeometry will put us in an infinite loop // as it does a recursive call back to ossimImageHandler::getImageGeometry(). //--- // Check for set projection. if ( theGeometry.valid()&&!theGeometry->getProjection() ) { // Try factories for projection. ossimImageGeometryRegistry::instance()->extendGeometry(this); } } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } return theGeometry; } ossimRefPtr ossimEnviTileSource::getInternalImageGeometry() const { static const char MODULE[] = "ossimEnviTileSource::getInternalImageGeometry"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr geom; // debugging to turn off model load // return geom; geom = new ossimImageGeometry(); ossimRefPtr supData = new ossimAlphaSensorSupportData(); if ( supData->readSupportFiles( m_enviHdr ) ) { if (supData->isHSI()) { ossimRefPtr sensor = new ossimAlphaSensorHSI(); if ( sensor->initialize( *(supData.get()) ) ) { geom->setProjection( sensor.get() ); } } else { ossimRefPtr sensor = new ossimAlphaSensorHRI(); if ( sensor->initialize( *(supData.get()) ) ) { geom->setProjection( sensor.get() ); } } } // Matches: if ( supData->readSupportFiles( m_enviHdr ) ) else { geom = 0; } return geom; } bool ossimEnviTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimGeneralRasterTileSource::saveState(kwl,prefix); } bool ossimEnviTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimGeneralRasterTileSource::loadState(kwl, prefix); } ossimRefPtr ossimEnviTileSource::getProperty( const ossimString& name)const { if(name == "file_type") { return new ossimStringProperty(name, getShortName()); } return ossimImageHandler::getProperty(name); } void ossimEnviTileSource::getPropertyNames( std::vector& propertyNames)const { ossimImageHandler::getPropertyNames(propertyNames); propertyNames.push_back("file_type"); } ossimString ossimEnviTileSource::getShortName() const { return ossimString("ENVI"); } ossimString ossimEnviTileSource::getLongName() const { return ossimString("ENVI reader"); } bool ossimEnviTileSource::getRgbBandList(std::vector& bandList) const { bool result = false; bandList.clear(); // Look in ENVI header for "default bands": result = m_enviHdr.getDefaultBands( bandList ); if ( !result && ( getNumberOfInputBands() > 2 ) ) { // Try to derive RGB from wavelengths if found in ENVI header. ossimWavelength wl; if ( wl.initialize( m_enviHdr ) ) { result = wl.getRgbBands( bandList ); } } if ( bandList.size() != 3 ) { result = false; } return result; } void ossimEnviTileSource::setDefaultBandList() { if ( isBandSelector() ) { std::vector bandList; if ( getRgbBandList( bandList ) ) { if ( bandList.size() ) { ossimImageHandler::setOutputBandList(bandList, m_outputBandList); } } } if ( m_outputBandList.empty() ) { // Initialized to identity (input = output): ossimImageSource::getOutputBandList( m_outputBandList ); } } ossim-Miami-2.9.1/src/imaging/ossimEquationCombiner.cpp000066400000000000000000002567571352751253100231660ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimEquationCombiner.cpp 23407 2015-07-06 15:59:23Z okramer $ #include #include using namespace std; #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimEquationCombiner, "ossimEquationCombiner", ossimImageCombiner); static const char* EQUATION_KW = "equation"; class ossimBinaryOpAdd : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return v1 + v2; } }; class ossimBinaryOpAnd : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (double)(((ossim_uint32)v1) & ((ossim_uint32)v2)); } }; class ossimBinaryOpOr : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (double)(((ossim_uint32)v1) | ((ossim_uint32)v2)); } }; class ossimBinaryOpXor : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (double)(((ossim_uint32)v1) ^ ((ossim_uint32)v2)); } }; class ossimBinaryOpSub : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return v1 - v2; } }; class ossimBinaryOpMax : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return std::max(v1, v2); } }; class ossimBinaryOpMin : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return std::min(v1, v2); } }; class ossimBinaryOpMul : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return v1 * v2; } }; class ossimBinaryOpDiv : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { if(fabs(v2)>FLT_EPSILON) return v1 / v2; return 1.0/FLT_EPSILON; } }; class ossimBinaryOpMod : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { if(fabs(v2)>FLT_EPSILON) return fmod(v1,v2); return 1.0/FLT_EPSILON; } }; class ossimBinaryOpPow : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return pow(v1, v2); } }; // boolean operators class ossimBinaryOpEqual : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1==v2)?1.0:0.0; } }; class ossimBinaryOpGreater : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1>v2)?1.0:0.0; } }; class ossimBinaryOpGreaterOrEqual : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1>=v2)?1.0:0.0; } }; class ossimBinaryOpLess : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1= 0) { return sqrt(v); } return -1; } }; class ossimUnaryOpExp : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return exp(v); } }; class ossimUnaryOpSin : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return sin(v); } }; class ossimUnaryOpSind : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return sin(v*M_PI/180.0); } }; class ossimUnaryOpASin : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { if(v > 1) v = 1; if(v < -1) v = -1; return asin(v); } }; class ossimUnaryOpASind : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { if(v > 1) v = 1; if(v < -1) v = -1; return (180/M_PI)*asin(v); } }; class ossimUnaryOpACos : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { if(v > 1) v = 1; if(v < -1) v = -1; return acos(v); } }; class ossimUnaryOpACosd : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { if(v > 1) v = 1; if(v < -1) v = -1; return (180/M_PI)*acos(v); } }; class ossimUnaryOpCos : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return cos(v); } }; class ossimUnaryOpCosd : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return cos(v*M_PI/180.0); } }; class ossimUnaryOpTan : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return tan(v); } }; class ossimUnaryOpTand : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return tan(v*M_PI/180.0); } }; class ossimUnaryOpATan : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return atan(v); } }; class ossimUnaryOpATand : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return (180/M_PI)*atan(v); } }; ossimEquationCombiner::ossimEquationCombiner() :ossimImageCombiner(), theOutputScalarType(OSSIM_FLOAT64), theEquation(""), theLexer(NULL), theTile(NULL), theCastFilter(NULL), theCastOutputFilter(NULL), theCurrentId(0), theCurrentResLevel(0) { theLexer = new ossimEquTokenizer; theCastFilter = new ossimCastTileSourceFilter; theCastFilter->setOutputScalarType(OSSIM_FLOAT64); } ossimEquationCombiner::ossimEquationCombiner(ossimConnectableObject::ConnectableObjectList& inputs) :ossimImageCombiner(inputs), theOutputScalarType(OSSIM_FLOAT64), theEquation(""), theLexer(NULL), theTile(NULL), theCastFilter(NULL), theCastOutputFilter(NULL), theCurrentId(0), theCurrentResLevel(0) { theLexer = new ossimEquTokenizer; theCastFilter = new ossimCastTileSourceFilter; theCastFilter->setOutputScalarType(OSSIM_FLOAT64); } ossimEquationCombiner::~ossimEquationCombiner() { if(theLexer) { delete theLexer; theLexer = NULL; } if(theCastFilter.valid()) { theCastFilter->disconnect(); theCastFilter = 0; } if(theCastOutputFilter.valid()) { theCastOutputFilter->disconnect(); theCastOutputFilter = 0; } // make sure they are cleared clearStacks(); } double ossimEquationCombiner::getNullPixelValue(ossim_uint32 band)const { if(theEquation == "") { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getNullPixelValue(band); } } } return ossim::defaultNull(getOutputScalarType()); } double ossimEquationCombiner::getMinPixelValue(ossim_uint32 band)const { if(theEquation == "") { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getMinPixelValue(band); } } } return ossim::defaultMin(getOutputScalarType()); } double ossimEquationCombiner::getMaxPixelValue(ossim_uint32 band)const { if(theEquation == "") { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getMaxPixelValue(band); } } } return ossim::defaultMax(getOutputScalarType()); } ossimScalarType ossimEquationCombiner::getOutputScalarType() const { if(theEquation == "") { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getOutputScalarType(); } } } return theOutputScalarType; } ossimRefPtr ossimEquationCombiner::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theTile) { initialize(); } long w = tileRect.width(); long h = tileRect.height(); long tw = theTile->getWidth(); long th = theTile->getHeight(); if(theEquation != "") { theTile->setImageRectangle(tileRect); if(w*h != tw*th) { theTile->initialize(); } else { theTile->makeBlank(); } theCurrentResLevel = resLevel; ossimRefPtr outputTile = parseEquation(); if(theCastOutputFilter.valid()) { outputTile = theCastOutputFilter->applyCast(outputTile); } return outputTile; } else { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getTile(tileRect, resLevel); } } } return ossimRefPtr(); } void ossimEquationCombiner::setOutputScalarType(ossimScalarType scalarType) { if(theOutputScalarType != scalarType) { theOutputScalarType = scalarType; if(theOutputScalarType == OSSIM_SCALAR_UNKNOWN) { theOutputScalarType = OSSIM_FLOAT64; } if(theCastOutputFilter.valid()) { theCastOutputFilter = 0; } if(theOutputScalarType != OSSIM_FLOAT64) { theCastOutputFilter = new ossimCastTileSourceFilter; theCastOutputFilter->setOutputScalarType(theOutputScalarType); theCastOutputFilter->connectMyInputTo(0, this); theCastOutputFilter->initialize(); } } } void ossimEquationCombiner::setProperty(ossimRefPtr property) { if(!property) return; if(property->getName() == "Equation") { theEquation = property->valueToString(); } else if(property->getName() == "Output scalar type") { setOutputScalarType(ossimScalarTypeLut::instance()-> getScalarTypeFromString(property->valueToString())); } else { ossimImageCombiner::setProperty(property); } } ossimRefPtr ossimEquationCombiner::getProperty(const ossimString& name)const { if(name == "Equation") { ossimStringProperty* stringProp = new ossimStringProperty("Equation", theEquation, false); stringProp->clearChangeType(); stringProp->setReadOnlyFlag(false); stringProp->setCacheRefreshBit(); return stringProp; } else if(name == "Output scalar type") { ossimScalarTypeLut* sl = ossimScalarTypeLut::instance(); std::vector scalarNames; ossim_int32 tableSize = (ossim_int32)sl->getTableSize(); ossim_int32 idx; for(idx = 0; idx < tableSize; ++idx) { scalarNames.push_back(sl->getEntryString(idx)); } ossimStringProperty* stringProp = new ossimStringProperty("Output scalar type", sl->getEntryString((ossim_int32)theOutputScalarType), false, scalarNames); stringProp->clearChangeType(); stringProp->setReadOnlyFlag(false); stringProp->setCacheRefreshBit(); return stringProp; } return ossimImageCombiner::getProperty(name); } void ossimEquationCombiner::getPropertyNames(std::vector& propertyNames)const { ossimImageCombiner::getPropertyNames(propertyNames); propertyNames.push_back("Equation"); propertyNames.push_back("Output scalar type"); } void ossimEquationCombiner::initialize() { ossimImageCombiner::initialize(); theTile = ossimImageDataFactory::instance()->create(this, OSSIM_FLOAT64, getNumberOfOutputBands(), getTileWidth(), getTileHeight()); theTile->initialize(); if(theCastOutputFilter.valid()) { theCastOutputFilter->initialize(); } } void ossimEquationCombiner::assignValue() { if(!theValueStack.empty()) { if(theValueStack.top().type == OSSIM_EQU_IMAGE_DATA_TYPE) { ossimImageData* topData = theValueStack.top().d.imageDataValue; ossim_uint32 minBands = std::min(theTile->getNumberOfBands(), topData->getNumberOfBands()); ossim_uint32 maxBands = theTile->getNumberOfBands(); ossim_uint32 band = 0; ossim_uint32 offset = 0; ossim_uint32 size = theTile->getWidth()*theTile->getHeight(); if(topData->getDataObjectStatus() == OSSIM_PARTIAL) { for(band = 0; band < minBands; ++band) { double* inBuf = (double*)topData->getBuf(band); double* outBuf = (double*)theTile->getBuf(band); double np = topData->getNullPix(band); if(outBuf && inBuf) { for(offset = 0; offset < size; ++offset) { if(*inBuf != np) { *outBuf = *inBuf; } ++outBuf; ++inBuf; } } } for(;band < maxBands; ++band) { double* inBuf = (double*)topData->getBuf(minBands-1); double* outBuf = (double*)theTile->getBuf(band); double np = topData->getNullPix(band); if(outBuf && inBuf) { for(offset = 0; offset < size; ++offset) { if(*inBuf != np) { *outBuf = *inBuf; } ++outBuf; ++inBuf; } } } } else if(topData->getDataObjectStatus() == OSSIM_FULL) { for(band = 0; band < minBands; ++band) { double* inBuf = (double*)theValueStack.top().d.imageDataValue->getBuf(band); double* outBuf = (double*)theTile->getBuf(band); if(outBuf && inBuf) { for(offset = 0; offset < size; ++offset) { *outBuf = *inBuf; ++outBuf; ++inBuf; } } } for(;band < maxBands; ++band) { double* inBuf = (double*)theValueStack.top().d.imageDataValue->getBuf(minBands-1); double* outBuf = (double*)theTile->getBuf(band); if(outBuf && inBuf) { for(offset = 0; offset < size; ++offset) { *outBuf = *inBuf; ++outBuf; ++inBuf; } } } } // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = theValueStack.top().d.imageDataValue; id = NULL; } else { double* buf = static_cast(theTile->getBuf()); ossim_uint32 size = theTile->getSize(); double value = (double)theValueStack.top().d.doubleValue; for(ossim_uint32 offset = 0; offset < size; ++offset) { *buf = value; ++buf; } } theValueStack.pop(); } } void ossimEquationCombiner::clearStacks() { while(!theValueStack.empty()) { if(theValueStack.top().type == OSSIM_EQU_IMAGE_DATA_TYPE) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = theValueStack.top().d.imageDataValue; id = NULL; } theValueStack.pop(); } } void ossimEquationCombiner::clearArgList(vector& argList) { for(ossim_uint32 i = 0; i < argList.size(); ++i) { if(argList[i].type == OSSIM_EQU_IMAGE_DATA_TYPE) { if(argList[i].d.imageDataValue) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = argList[i].d.imageDataValue; id = NULL; argList[i].d.imageDataValue = (ossimImageData*)NULL; } } } argList.clear(); } void ossimEquationCombiner::deleteArgList(vector& args) { int i = 0; for(i = 0; i < (int)args.size(); ++i) { if(args[i].type == OSSIM_EQU_IMAGE_DATA_TYPE) { if(args[i].d.imageDataValue) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = args[i].d.imageDataValue; id = NULL; args[i].d.imageDataValue = NULL; } } } args.clear(); } bool ossimEquationCombiner::parseArgList(vector& args, bool popValueStack) { bool result = true; if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); do { if(parseExpression()) { if(!theValueStack.empty()) { args.push_back(theValueStack.top()); if(popValueStack) { theValueStack.pop(); } } else { ossimNotify(ossimNotifyLevel_WARN) << "The expression at arg " << (args.size()+1) << " is empty" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) <<"Unable to parse expression" << endl; result = false; } if(theCurrentId == OSSIM_EQU_TOKEN_COMMA) { theCurrentId = theLexer->yylex(); } else if(theCurrentId != OSSIM_EQU_TOKEN_RIGHT_PAREN) { ossimNotify(ossimNotifyLevel_WARN) <<"Missing comma in argument list" << endl; result = false; } }while(result&&(theCurrentId != OSSIM_EQU_TOKEN_RIGHT_PAREN)); } else { ossimNotify(ossimNotifyLevel_WARN) << "Starting left parenthesis missing from arg list" << endl; result = false; } if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { theCurrentId = theLexer->yylex(); // skip past right parenthesis } else { ossimNotify(ossimNotifyLevel_WARN) <<"No matching right parenthesis for arg list" << endl; result = false; } if(!result && popValueStack) { clearArgList(args); } return result; } bool ossimEquationCombiner::parseAssignBand() { bool result = true; vector argList; if(parseArgList(argList)) { if((argList.size() == 3) || (argList.size() == 4)) { ossimEquValue v3 = argList[2]; ossimEquValue v2 = argList[1]; ossimEquValue v1 = argList[0]; if(argList.size() == 3) { if((v1.type == OSSIM_EQU_IMAGE_DATA_TYPE) && (v2.type == OSSIM_EQU_DOUBLE_TYPE)) { ossimImageData *data = (ossimImageData*)v1.d.imageDataValue->dup(); ossimEquValue v; if(v3.type == OSSIM_EQU_IMAGE_DATA_TYPE) { if(data->getBuf()&& v3.d.imageDataValue->getBuf()) { if((ossim_uint32)(v2.d.doubleValue) < data->getNumberOfBands()) { data->assignBand(v3.d.imageDataValue, 0, (ossim_uint32)v2.d.doubleValue); } } } else { if(data->getBuf()&& (ossim_uint32)v2.d.doubleValue < data->getNumberOfBands()) { ossim_uint32 upper = data->getWidth()*data->getHeight(); double* buf = (double*)data->getBuf((ossim_uint32)v2.d.doubleValue); double value = v3.d.doubleValue; if(buf) { for(ossim_uint32 i = 0; i < upper; ++i) { *buf = value; ++buf; } } else { result = false; } } } if(result) { data->validate(); v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = data; theValueStack.push(v); } } else { result = false; } } else { ossimEquValue v4 = argList[3]; if((v1.type == OSSIM_EQU_IMAGE_DATA_TYPE) && (v2.type == OSSIM_EQU_DOUBLE_TYPE)&& (v3.type == OSSIM_EQU_IMAGE_DATA_TYPE)&& (v4.type == OSSIM_EQU_DOUBLE_TYPE)) { ossimImageData *data = (ossimImageData*)v1.d.imageDataValue->dup(); ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = data; if(data->getBuf()&&v3.d.imageDataValue->getBuf()) { ossim_uint32 index1 = (ossim_uint32)v4.d.doubleValue; ossim_uint32 index2 = (ossim_uint32)v2.d.doubleValue; if((index1 > data->getNumberOfBands()) || (index1 > v3.d.imageDataValue->getNumberOfBands())) { result = false; } else { data->assignBand(v3.d.imageDataValue, index1, index2); data->validate(); } } theValueStack.push(v); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "Invalid number of arguments to assign_band" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) << "unable to parse arguments for assign band" << endl; result = false; } clearArgList(argList); return result; } bool ossimEquationCombiner::parseStdFuncs() { bool result = true; switch(theCurrentId) { case OSSIM_EQU_TOKEN_ASSIGN_BAND: { theCurrentId = theLexer->yylex(); if(!parseAssignBand()) { result = false; } break; } case OSSIM_EQU_TOKEN_CONV: { theCurrentId = theLexer->yylex(); vector args; if(parseArgList(args)) { ossimImageData* resultImage = (ossimImageData*)NULL; if(applyConvolution(resultImage, args)) { if(resultImage) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = resultImage; theValueStack.push(v); } else { ossimNotify(ossimNotifyLevel_WARN) << "function conv error: resulting image is NULL" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Unable to apply convolution" << endl; result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_CLAMP: { theCurrentId = theLexer->yylex(); vector args; if(parseArgList(args)) { ossimImageData* resultImage = (ossimImageData*)NULL; if(applyClamp(resultImage, args)) { if(resultImage) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = resultImage; theValueStack.push(v); } else { ossimNotify(ossimNotifyLevel_WARN) << "function clamp error: resulting image is NULL" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Unable to apply clamp" << endl; result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BAND: { // need to parse the following rule for blurr function // // band(image data, number) theCurrentId = theLexer->yylex(); vector argList; if(parseArgList(argList)) { if(argList.size() == 2) { ossimEquValue v1 = argList[0]; ossimEquValue v2 = argList[1]; ossimImageData* tempData = NULL; ossim_uint32 bandNumber = 0; if(v1.type == OSSIM_EQU_IMAGE_DATA_TYPE) { tempData = v1.d.imageDataValue; } else { result = false; } if(v2.type == OSSIM_EQU_DOUBLE_TYPE) { bandNumber = (ossim_uint32)(v2.d.doubleValue); } else { result = false; } if(bandNumber > tempData->getNumberOfBands()) { result = false; } if(result) { ossimImageData* data = new ossimImageData(this, OSSIM_FLOAT64, 1); data->setWidthHeight(tempData->getWidth(), tempData->getHeight()); data->setOrigin(tempData->getOrigin()); data->setNullPix(tempData->getNullPix(bandNumber), 0); data->setMinPix(tempData->getMinPix(bandNumber), 0); data->setMaxPix(tempData->getMaxPix(bandNumber), 0); data->initialize(); if((tempData->getBuf())&& (bandNumber < tempData->getNumberOfBands())) { data->assignBand(tempData, bandNumber, 0); data->validate(); } ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = data; theValueStack.push(v); } if(tempData) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = tempData; tempData = NULL; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Invalid number of args in function band" << endl; result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BLURR: { theCurrentId = theLexer->yylex(); vector args; if(parseArgList(args)) { ossimImageData* resultImage = (ossimImageData*)NULL; if(applyBlurr(resultImage, args)) { if(resultImage) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = resultImage; theValueStack.push(v); } else { result = false; } } else { result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_SHIFT: { theCurrentId = theLexer->yylex(); vector args; if(parseArgList(args)) { ossimImageData* resultImage = (ossimImageData*)NULL; if(applyShift(resultImage, args)) { if(resultImage) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = resultImage; theValueStack.push(v); } else { result = false; } } else { result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_MAX: case OSSIM_EQU_TOKEN_MIN: { ossimBinaryOp* op = NULL; if(theCurrentId == OSSIM_EQU_TOKEN_MIN) op = new ossimBinaryOpMin; else op = new ossimBinaryOpMax; int argCount = 0; theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); bool done = false; while(!done) { if(parseExpression()) { ++argCount; if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { theCurrentId = theLexer->yylex(); done = true; } else if(theCurrentId == OSSIM_EQU_TOKEN_COMMA) { theCurrentId = theLexer->yylex(); } else { result = false; done = true; } } else { done = true; result = false; } } if((argCount > 1)&&result) { result = true; ossimEquValue v; ossimEquValue v1; ossimEquValue v2; v2 = theValueStack.top(); theValueStack.pop(); v1 = theValueStack.top(); theValueStack.pop(); argCount -=2; do { if(applyOp(*op, v, v1, v2)) { theValueStack.push(v); } else { result = false; argCount = 0; } --argCount; if((argCount>0)&&result) { v2 = theValueStack.top(); theValueStack.pop(); v1 = theValueStack.top(); theValueStack.pop(); } }while((argCount > 0)&&(result)); } else { result = false; } } else { result = false; } if(op) { delete op; op = NULL; } break; } case OSSIM_EQU_TOKEN_ABS: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpAbs(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_SIN: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpSin(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_SIND: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpSind(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ASIN: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpASin(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ASIND: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpASind(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_COS: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpCos(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_COSD: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpCosd(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ACOS: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpACos(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ACOSD: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpACosd(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_TAN: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpTan(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_TAND: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpTand(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ATAN: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpATan(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ATAND: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpATand(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_LOG: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpLog(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_LOG10: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpLog10(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_SQRT: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpSqrt(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_EXP: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpExp(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } default: { result = false; } } return result; } bool ossimEquationCombiner::parseUnaryFactor() { bool result = false; if(theCurrentId == OSSIM_EQU_TOKEN_MINUS) { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 0) { ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpNeg(), v, v1); theValueStack.push(v); } else { result = false; } result = true; } else { result = false; } } else if(theCurrentId == OSSIM_EQU_TOKEN_TILDE) { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 0) { ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpOnesComplement(), v, v1); theValueStack.push(v); } else { result = false; } result = true; } else { result = false; } } return result; } bool ossimEquationCombiner::parseFactor() { bool result = false; switch(theCurrentId) { case OSSIM_EQU_TOKEN_CONSTANT: { ossimEquValue v; v.type = OSSIM_EQU_DOUBLE_TYPE; v.d.doubleValue = atof(theLexer->YYText()); theValueStack.push(v); theCurrentId = theLexer->yylex(); result = true; break; } case OSSIM_EQU_TOKEN_PI: { ossimEquValue v; v.type = OSSIM_EQU_DOUBLE_TYPE; v.d.doubleValue = M_PI; theValueStack.push(v); theCurrentId = theLexer->yylex(); result = true; break; } case OSSIM_EQU_TOKEN_IMAGE_VARIABLE: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_ARRAY_BRACKET) { theCurrentId = theLexer->yylex(); if(parseExpression()) { if(!theValueStack.empty()) { if(theValueStack.top().type == OSSIM_EQU_DOUBLE_TYPE) { if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_ARRAY_BRACKET) { theCurrentId = theLexer->yylex(); ossim_uint32 index = (ossim_uint32)theValueStack.top().d.doubleValue; theValueStack.pop(); ossimRefPtr data = getNewImageData(index); result = true; if(data.valid()) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = data.release(); theValueStack.push(v); } else { ossimNotify(ossimNotifyLevel_WARN) <<"Data is NULL for array operation" << endl; } result = true; } else { ossimNotify(ossimNotifyLevel_WARN) << "Mismatched Right array bracket" << endl; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Expression between array brackets is not a number" << endl; } } else { ossimNotify(ossimNotifyLevel_WARN) << "no expression within array brackets" << endl; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Unabel to parse expression"<yylex(); if(parseExpression()) { if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { result = true; theCurrentId = theLexer->yylex(); } else { ossimNotify(ossimNotifyLevel_WARN) << "Right parenthesis missing" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Unable to parse expression within parenthesis" << endl; result = false; } break; } } if(!result) result = parseUnaryFactor(); if(!result) result = parseStdFuncs(); return result; } bool ossimEquationCombiner::parseRestOfTerm() { //--- // Parse the following rule: // RestOfTerm: * Factor RestOfTerm | / Factor RestOfTerm | // ^ Factor RestOfTerm //--- bool result = true; switch(theCurrentId) { case OSSIM_EQU_TOKEN_MULT: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpMul(), v, v1, v2); theValueStack.push(v); } else { ossimNotify(ossimNotifyLevel_WARN) << "Multiplication requires two arguments" << endl; result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_DIV: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpDiv(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_XOR: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpXor(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_AMPERSAND: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpAnd(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_OR_BAR: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpOr(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_MOD: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpMod(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_POWER: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpPow(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BEQUAL: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpEqual(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BGREATER: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpGreater(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BGREATEROREQUAL: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpGreaterOrEqual(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BLESS: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpLess(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BLESSOREQUAL: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpLessOrEqual(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BDIFFERENT: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpDifferent(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } } return result; } bool ossimEquationCombiner::parseTerm() { // parse the following rule: // // Term : Factor RestOfTerm bool result = false; result = parseFactor(); if(result) { result = parseRestOfTerm(); } return result; } bool ossimEquationCombiner::parseRestOfExp() { // parse the following rule: // RestOfExpression : + Term RestOfExpression | - Term RestOfExpression | epsilon // bool result = true; if(theCurrentId == OSSIM_EQU_TOKEN_PLUS) { theCurrentId = theLexer->yylex(); if(parseTerm()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpAdd(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfExp(); } } else { result = false; } } else if(theCurrentId == OSSIM_EQU_TOKEN_MINUS) { theCurrentId = theLexer->yylex(); if(parseTerm()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpSub(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfExp(); } } else { result = false; } } return result; } ossimRefPtr ossimEquationCombiner::getImageData(ossim_uint32 index) { ossimRefPtr result; ossimConnectableObject* obj = getInput(index); if(obj) { theCastFilter->connectMyInputTo(0, obj); result= (theCastFilter->getTile(theTile->getImageRectangle(), theCurrentResLevel)); if(result.valid()) { result->setMinPix(theTile->getMinPix(), theTile->getNumberOfBands()); result->setMaxPix(theTile->getMaxPix(), theTile->getNumberOfBands()); } } return result; } ossimRefPtr ossimEquationCombiner::getNewImageData( ossim_uint32 index) { ossimRefPtr result = getImageData(index); if(result.valid()) { if(result->getBuf()) { result = (ossimImageData*)result->dup(); } } return result; } bool ossimEquationCombiner::parseExpression() { // parse the following rule: // expression : Term ResOfExpression // bool result = false; if(parseTerm()) { result = parseRestOfExp(); } return result; } ossimRefPtr ossimEquationCombiner::parseEquation() { ostringstream s; s << theEquation; istringstream inS(s.str()); theLexer->switch_streams(&inS, &ossimNotify(ossimNotifyLevel_WARN)); theCurrentId = theLexer->yylex(); while(theCurrentId) { if(!parseExpression()) { break; } } if(!theValueStack.empty()) { assignValue(); theTile->validate(); clearStacks(); } return theTile; } bool ossimEquationCombiner::applyClamp(ossimImageData* &result, const vector& argList) { if(result) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = result; id = NULL; result = (ossimImageData*) NULL; } if(argList.size() <3) { return false; } if(argList[0].type == OSSIM_EQU_DOUBLE_TYPE) { return false; } else if( (argList[1].type == OSSIM_EQU_DOUBLE_TYPE)&& (argList[2].type == OSSIM_EQU_DOUBLE_TYPE)) { result = argList[0].d.imageDataValue; if(argList[0].d.imageDataValue) { ossimDataObjectStatus status = result->getDataObjectStatus(); if((status != OSSIM_NULL) && (status != OSSIM_EMPTY)) { double minValue = argList[1].d.doubleValue; double maxValue = argList[2].d.doubleValue; if(minValue > maxValue) { std::swap(minValue, maxValue); } int band = 0; int offset = 0; int upperBoundBand = result->getNumberOfBands(); int offsetUpperBound = result->getWidth()*result->getHeight(); if(status == OSSIM_PARTIAL) { for(band = 0; band < upperBoundBand; ++band) { double np = static_cast(result->getNullPix(band)); double *buf = static_cast(result->getBuf(band)); for(offset = 0; offset < offsetUpperBound; ++ offset) { if( *buf != np ) { if( (*buf) < minValue) *buf = minValue; else if( (*buf) >maxValue) *buf = maxValue; } ++buf; } } } else { for(band = 0; band < upperBoundBand; ++band) { double *buf = static_cast(result->getBuf(band)); for(offset = 0; offset < offsetUpperBound; ++ offset) { if( (*buf) < minValue) *buf = minValue; else if( (*buf) >maxValue) *buf = maxValue; ++buf; } } } } } return true; } return false; } bool ossimEquationCombiner::applyConvolution(ossimImageData* &result, const vector& argList) { if(result) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = result; id = NULL; result = (ossimImageData*) NULL; } if(argList.size() <4) return false; for(ossim_uint32 i = 0; i < argList.size(); ++i) { if(argList[i].type != OSSIM_EQU_DOUBLE_TYPE) { return false; } } ossim_uint32 index = (ossim_uint32)argList[0].d.doubleValue; int rows = (int)argList[1].d.doubleValue; int cols = (int)argList[2].d.doubleValue; if((rows*cols) != (int)(argList.size()-3)) { return false; } NEWMAT::Matrix m(rows,cols); int count = 3; for(int r = 0; r< rows;++r) { for(int c=0;c conv = new ossimConvolutionSource(NULL, m); conv->connectMyInputTo(0, obj); theCastFilter->connectMyInputTo(0, conv.get()); ossimRefPtr tempData = theCastFilter->getTile(theTile->getImageRectangle(), theCurrentResLevel); if(tempData.valid()) { result = (ossimImageData*)tempData->dup(); } else { result = (ossimImageData*)theTile->dup(); } conv->disconnect(); conv = 0; } if(result) { return true; } return false; } bool ossimEquationCombiner::applyBlurr(ossimImageData* &result, const vector& argList) { if(result) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = result; id = NULL; result = (ossimImageData*) NULL; } if(argList.size() !=3) return false; for(ossim_uint32 i = 0; i < argList.size(); ++i) { if(argList[i].type != OSSIM_EQU_DOUBLE_TYPE) { return false; } } ossim_uint32 index = (ossim_uint32)argList[0].d.doubleValue; int rows = (int)argList[1].d.doubleValue; int cols = (int)argList[2].d.doubleValue; NEWMAT::Matrix m(rows, cols); m = 1.0/(rows*cols); ossimConnectableObject* obj = getInput(index); if(obj) { ossimRefPtr conv = new ossimConvolutionSource(NULL, m); conv->connectMyInputTo(0, obj); theCastFilter->connectMyInputTo(0, conv.get()); theCastFilter->initialize(); ossimRefPtr tempData = theCastFilter->getTile(theTile->getImageRectangle(), theCurrentResLevel); if(tempData.valid()) { result = (ossimImageData*)tempData->dup(); } conv->disconnect(); conv = 0; } if(result) { return true; } return false; } bool ossimEquationCombiner::applyShift(ossimImageData* &result, const vector& argList) { if(result) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = result; id = NULL; result = (ossimImageData*) NULL; } if(argList.size() !=3) return false; for(ossim_uint32 i = 0; i < argList.size(); ++i) { if(argList[i].type != OSSIM_EQU_DOUBLE_TYPE) { return false; } } ossim_uint32 index = (ossim_uint32)argList[0].d.doubleValue; int x = (int)argList[1].d.doubleValue; int y = (int)argList[2].d.doubleValue; ossimConnectableObject* obj = getInput(index); if(obj) { ossimRefPtr shiftSource = new ossimSubImageTileSource(NULL, ossimIpt(x, y)); shiftSource->connectMyInputTo(0, obj); theCastFilter->connectMyInputTo(0, shiftSource.get()); ossimRefPtr tempData = theCastFilter->getTile(theTile->getImageRectangle(), theCurrentResLevel); if(tempData.valid()) { result = (ossimImageData*)tempData->dup(); } shiftSource->disconnect(); shiftSource = 0; } if(result) { return true; } return false; } bool ossimEquationCombiner::applyOp(const ossimBinaryOp& op, ossimEquValue& result, ossimEquValue& v1, ossimEquValue& v2) { bool returnValue = true; if(v1.type == OSSIM_EQU_DOUBLE_TYPE) { if(v2.type == OSSIM_EQU_DOUBLE_TYPE) { result.type = OSSIM_EQU_DOUBLE_TYPE; result.d.doubleValue = op.apply(v1.d.doubleValue, v2.d.doubleValue); } else if(v2.type == OSSIM_EQU_IMAGE_DATA_TYPE) { returnValue = applyOp(op, v1.d.doubleValue, v2.d.imageDataValue); result.type = OSSIM_EQU_IMAGE_DATA_TYPE; result.d.imageDataValue = v2.d.imageDataValue; } else { returnValue = false; } } else if(v1.type == OSSIM_EQU_IMAGE_DATA_TYPE) { if(v2.type == OSSIM_EQU_DOUBLE_TYPE) { returnValue = applyOp(op, v1.d.imageDataValue, v2.d.doubleValue); result.type = OSSIM_EQU_IMAGE_DATA_TYPE; result.d.imageDataValue = v1.d.imageDataValue; returnValue = true; } else if(v2.type == OSSIM_EQU_IMAGE_DATA_TYPE) { returnValue = applyOp(op, v1.d.imageDataValue, v2.d.imageDataValue); result.type = OSSIM_EQU_IMAGE_DATA_TYPE; result.d.imageDataValue = v1.d.imageDataValue; // Delete the object indirectly through an ossimRefPtr. ossimRefPtr id = v2.d.imageDataValue; id = NULL; v2.d.imageDataValue = (ossimImageData*)NULL; returnValue = true; } else { returnValue = false; } } else { returnValue = false; } return returnValue; } bool ossimEquationCombiner::applyOp(const ossimBinaryOp& op, ossimImageData* v1, double v2) { double* buf = static_cast(v1->getBuf()); if(!buf) return true; ossimDataObjectStatus status = v1->getDataObjectStatus(); if(status == OSSIM_EMPTY || status == OSSIM_NULL) { return true; } if(status == OSSIM_FULL ) { ossim_uint32 size = v1->getSize(); double value = (static_cast(v2)); for(ossim_uint32 i = 0; i < size; ++i) { *buf = (double)op.apply(*buf, value); ++buf; } } else { ossim_uint32 sizePerBand = v1->getSizePerBand(); ossim_uint32 numberOfBands = v1->getNumberOfBands(); if(numberOfBands) { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { double* buf = static_cast(v1->getBuf(band)); if(buf) { double np = static_cast(v1->getNullPix()[band]); for(ossim_uint32 offset = 0; offset < sizePerBand;++offset) { if(*buf != np) { *buf = (double)op.apply(*buf, v2); } ++buf; } } } } } return true; } bool ossimEquationCombiner::applyOp(const ossimBinaryOp& op, double v1, ossimImageData* v2) { double* buf = static_cast(v2->getBuf()); if(!buf) return true; ossimDataObjectStatus status = v2->getDataObjectStatus(); if(status == OSSIM_EMPTY || status == OSSIM_NULL) { return true; } if(status == OSSIM_FULL ) { ossim_uint32 size = v2->getSize(); double value = (static_cast(v1)); for(ossim_uint32 i = 0; i < size; ++i) { *buf = (double)op.apply(value, *buf); ++buf; } } else { ossim_uint32 sizePerBand = v2->getSizePerBand(); ossim_uint32 numberOfBands = v2->getNumberOfBands(); if(numberOfBands) { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { double* buf = static_cast(v2->getBuf(band)); if(buf) { double np = static_cast(v2->getNullPix()[band]); for(ossim_uint32 offset = 0; offset < sizePerBand; ++offset) { if(*buf != np) { *buf = (double)op.apply((double)v1, *buf); } ++buf; } } } } } return true; } bool ossimEquationCombiner::applyOp(const ossimBinaryOp& op, ossimImageData* v1, ossimImageData* v2) { ossim_uint32 minNumberOfBands = std::min(v1->getNumberOfBands(), v2->getNumberOfBands()); ossim_uint32 maxNumberOfBands = std::max(v1->getNumberOfBands(), v2->getNumberOfBands()); ossim_uint32 size = v1->getWidth()*v1->getHeight(); ossimDataObjectStatus status1 = v1->getDataObjectStatus(); ossimDataObjectStatus status2 = v2->getDataObjectStatus(); double** bandV1 = new double*[maxNumberOfBands]; double** bandV2 = new double*[maxNumberOfBands]; double* bandV1Np = new double[maxNumberOfBands]; double* bandV2Np = new double[maxNumberOfBands]; ossim_uint32 band = 0; for(band = 0; band < minNumberOfBands; ++band) { bandV1[band] = (double*)v1->getBuf(band); bandV2[band] = (double*)v2->getBuf(band); bandV1Np[band] = (double)v1->getNullPix(band); bandV2Np[band] = (double)v2->getNullPix(band); } if(v1->getNumberOfBands() < v2->getNumberOfBands()) { for(band = 0; band < maxNumberOfBands; ++band) { bandV1[band] = (double*)v1->getBuf(minNumberOfBands-1); bandV2[band] = (double*)v2->getBuf(band); bandV1Np[band] = (double)v1->getNullPix(minNumberOfBands-1); bandV2Np[band] = (double)v2->getNullPix(band); } } else if(v2->getNumberOfBands() < v1->getNumberOfBands()) { for(band = 0; band < maxNumberOfBands; ++band) { bandV1[band] = (double*)v1->getBuf(band); bandV2[band] = (double*)v2->getBuf(minNumberOfBands-1); bandV1Np[band] = (double)v1->getNullPix(band); bandV2Np[band] = (double)v2->getNullPix(minNumberOfBands-1); } } if(status1 == OSSIM_EMPTY) { if(status2 == OSSIM_FULL) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; for(ossim_uint32 i = 0; i < size; ++i) { *buf1 = *buf2; ++buf1; ++buf2; } } } else if(status2 == OSSIM_PARTIAL) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; double nullPix2 = bandV2Np[band]; for(ossim_uint32 i = 0; i < size; ++i) { if(*buf2 != nullPix2) { *buf1 = *buf2; } ++buf1; ++buf2; } } } v1->setDataObjectStatus(status2); } else if((status1 == OSSIM_FULL)&& (status2 == OSSIM_FULL)) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; for(ossim_uint32 i = 0; i < size; ++i) { *buf1 = op.apply(*buf1, *buf2); ++buf1; ++buf2; } } } else if((status1 == OSSIM_FULL)&& (status2 == OSSIM_PARTIAL)) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; double nullPix2 = bandV2Np[band]; for(ossim_uint32 i = 0; i < size; ++i) { if(*buf2 != nullPix2) { *buf1 = op.apply(*buf1, *buf2); } ++buf1; ++buf2; } } } else if((status1 == OSSIM_PARTIAL)&& (status2 == OSSIM_FULL)) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; double nullPix1 = bandV1Np[band]; for(ossim_uint32 i = 0; i < size; ++i) { if(*buf1 != nullPix1) { *buf1 = op.apply(*buf1, *buf2); } ++buf1; ++buf2; } } } else if((status1 == OSSIM_PARTIAL)&& (status2 == OSSIM_PARTIAL)) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; double nullPix1 = bandV1Np[band]; double nullPix2 = bandV2Np[band]; for(ossim_uint32 i = 0; i < size; ++i) { if((*buf1 != nullPix1)&& (*buf2 != nullPix2)) { *buf1 = op.apply(*buf1, *buf2); } ++buf1; ++buf2; } } } delete [] bandV1; delete [] bandV2; delete [] bandV1Np; delete [] bandV2Np; return true; } bool ossimEquationCombiner::applyOp(const ossimUnaryOp& op, ossimEquValue& result, ossimEquValue& v) { bool returnValue = true; if(v.type == OSSIM_EQU_DOUBLE_TYPE) { result.type = OSSIM_EQU_DOUBLE_TYPE; result.d.doubleValue = op.apply(v.d.doubleValue); } else if(v.type == OSSIM_EQU_IMAGE_DATA_TYPE) { returnValue = applyOp(op, v.d.imageDataValue); result.type = OSSIM_EQU_IMAGE_DATA_TYPE; result.d.imageDataValue = v.d.imageDataValue; returnValue = true; } else { returnValue = false; } return returnValue; } bool ossimEquationCombiner::applyOp(const ossimUnaryOp& op, ossimImageData* v) { double* buf = static_cast(v->getBuf()); if(!buf) return true; ossimDataObjectStatus status = v->getDataObjectStatus(); if(status == OSSIM_EMPTY || status == OSSIM_NULL) { return true; } if(status == OSSIM_FULL ) { ossim_uint32 size = v->getSize(); for(ossim_uint32 i = 0; i < size; ++i) { *buf = (double)op.apply(*buf); ++buf; } } else { ossim_uint32 sizePerBand = v->getSizePerBand(); ossim_uint32 numberOfBands = v->getNumberOfBands(); if(numberOfBands) { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { double* buf = static_cast(v->getBuf(band)); if(buf) { double np = static_cast(v->getNullPix()[band]); for(ossim_uint32 offset = 0; offset < sizePerBand;++offset) { if(*buf != np) { *buf = (double)op.apply(*buf); } ++buf; } } } } } return true; } bool ossimEquationCombiner::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString outputScalarType = ossimScalarTypeLut::instance()->getEntryString(theOutputScalarType); kwl.add(prefix, EQUATION_KW, theEquation.c_str(), true); kwl.add(prefix, "output_scalar_type", outputScalarType.c_str(), true); return ossimImageCombiner::saveState(kwl, prefix); } bool ossimEquationCombiner::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* equ = kwl.find(prefix, EQUATION_KW); const char* scalar = kwl.find(prefix, "output_scalar_type"); bool result = ossimImageCombiner::loadState(kwl, prefix); if(equ) { theEquation = equ; } if(scalar) { setOutputScalarType(ossimScalarTypeLut::instance()-> getScalarTypeFromString(scalar)); } return result; } ossim-Miami-2.9.1/src/imaging/ossimErosionFilter.cpp000066400000000000000000000172071352751253100224670ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimErosionFilter, "ossimErosionFilter", ossimImageSourceFilter); // Keywords used throughout. static const ossimString WINDOW_SIZE_KW = "window_size"; ossimErosionFilter::ossimErosionFilter(ossimObject* owner) :ossimImageSourceFilter(owner), theTile(0), theTempTile(0), theWindowSize(3) { setDescription(ossimString("Dilation Filter")); } ossimErosionFilter::~ossimErosionFilter() { } void ossimErosionFilter::initialize() { ossimImageSourceFilter::initialize(); theTile = NULL; } ossimRefPtr ossimErosionFilter::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { if(!isSourceEnabled()) return ossimImageSourceFilter::getTile(rect, resLevel); ossimRefPtr inputData; ossim_uint32 halfSize = getWindowSize()>>1; ossimIrect requestRect(rect.ul().x - halfSize, rect.ul().y - halfSize, rect.lr().x + halfSize, rect.lr().y + halfSize); inputData = ossimImageSourceFilter::getTile(requestRect, resLevel); if(!inputData.valid() || !inputData->getBuf()) return inputData; vector viv; ossimImageSourceFilter::getValidImageVertices(viv, OSSIM_CLOCKWISE_ORDER, resLevel); theValidImagePoly = ossimPolygon(viv); if(!theTile.valid()) { theTile = (ossimImageData*)inputData->dup(); theTile->setImageRectangle(rect); } else { theTile->setImageRectangleAndBands(rect, inputData->getNumberOfBands()); } switch(inputData->getScalarType()) { case OSSIM_UINT8: doErosion(ossim_uint8(0), inputData); break; case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: doErosion(ossim_uint16(0), inputData); break; case OSSIM_SINT16: doErosion(ossim_sint16(0), inputData); break; case OSSIM_UINT32: doErosion(ossim_uint32(0), inputData); break; case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: doErosion(ossim_float32(0), inputData); break; case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: doErosion(ossim_float64(0), inputData); break; default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimErosionFilter::applyFilter WARNING:\n" << "Unhandled scalar type!" << endl; } } return theTile; } template void ossimErosionFilter::doErosion(T /* scalarType */, ossimRefPtr& inputData) { ossimDataObjectStatus status = inputData->getDataObjectStatus(); if ((status == OSSIM_FULL) || (status == OSSIM_EMPTY)) { // Nothing to do just copy the tile. theTile->loadTile(inputData.get()); return; } ossim_int32 halfWindow = (ossim_int32)(theWindowSize >> 1); ossim_int32 x, y, kernelX, kernelY; ossim_int32 iw = (ossim_int32)inputData->getWidth(); ossim_int32 ih = (ossim_int32)inputData->getHeight(); ossim_int32 ow = (ossim_int32)theTile->getWidth(); ossim_int32 oh = (ossim_int32)theTile->getHeight(); ossim_uint32 numBands = ossim::min(theTile->getNumberOfBands(), inputData->getNumberOfBands()); // It may be that the input rect is the same size as the output (i.e., the tile bounds aren't // expanded in the input's request to permit full kernels for output edge pixels: ossim_uint32 i_offset = 0; ossim_int32 delta = (ossim_int32)((iw - ow) >> 1); ossim_int32 xi, yi; if (delta > 0) i_offset = (ossim_uint32) halfWindow*(iw + 1); ossimIpt tile_ul (theTile->getImageRectangle().ul()); vector values; for(ossim_uint32 bandIdx = 0; bandIdx < numBands; ++bandIdx) { T* inputBuf = (T*)inputData->getBuf(bandIdx); T* outputBuf = (T*)theTile->getBuf(bandIdx); if (!inputBuf || !outputBuf) { return; // Shouldn't happen... } const T NP = (T)inputData->getNullPix(bandIdx); for(y = 0; y < oh; ++y) { for(x = 0; x < ow; ++x) { bool null_found = true; const T CP = *(inputBuf+i_offset); ossimDpt ipt (tile_ul.x+x, tile_ul.y+y); if ((CP != NP) && theValidImagePoly.isPointWithin(ipt)) { // Valid pixel found, need to check neighbors for null: null_found = false; values.clear(); for(kernelY = -halfWindow; (kernelY<=halfWindow) && !null_found; ++kernelY) { yi = y + kernelY + delta; if ((yi < 0) || (y > ih)) continue; for(kernelX = -halfWindow; (kernelX<=halfWindow) && !null_found; ++kernelX) { xi = x + kernelX + delta; if ((xi < 0) || (x > iw)) continue; T neighborPixel = *(inputBuf+kernelX+delta + (kernelY+delta)*iw); if(neighborPixel == NP) { // Found a NULL pixel: (*outputBuf) = NP; null_found = true; } } } } if (null_found) (*outputBuf) = NP; else (*outputBuf) = CP; // Move over... ++inputBuf; ++outputBuf; } // End of loop in x direction. // Move down... inputBuf += iw - ow; } // End of loop in y direction. } // End of band loop. theTile->validate(); } void ossimErosionFilter::setProperty(ossimRefPtr property) { if (!property.valid()) return; ossimString name = property->getName(); if (name == WINDOW_SIZE_KW) { theWindowSize = property->valueToString().toUInt32(); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimErosionFilter::getProperty(const ossimString& name)const { ossimRefPtr prop = 0; if (name == WINDOW_SIZE_KW) { prop = new ossimNumericProperty(WINDOW_SIZE_KW, ossimString::toString(theWindowSize), 3, 25); prop->setCacheRefreshBit(); return prop; } return ossimImageSourceFilter::getProperty(name); } void ossimErosionFilter::getPropertyNames(vector& propertyNames) const { propertyNames.push_back(WINDOW_SIZE_KW); ossimImageSourceFilter::getPropertyNames(propertyNames); } bool ossimErosionFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, WINDOW_SIZE_KW.c_str(), theWindowSize, true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimErosionFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = kwl.find(prefix, WINDOW_SIZE_KW.c_str()); if (lookup) theWindowSize = ossimString(lookup).toUInt32(); return ossimImageSourceFilter::loadState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimEsriShapeFileInterface.cpp000066400000000000000000000001751352751253100242030ustar00rootroot00000000000000#include RTTI_DEF(ossimEsriShapeFileInterface, "ossimEsriShapeFileInterface");ossim-Miami-2.9.1/src/imaging/ossimFeatherMosaic.cpp000066400000000000000000000355141352751253100224160ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimFeatherMosaic.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include #include static ossimTrace traceDebug("ossimFeatherMosaic:debug"); RTTI_DEF1(ossimFeatherMosaic, "ossimFeatherMosaic", ossimImageMosaic); using namespace std; ossimFeatherMosaic::ossimFeatherMosaic() :ossimImageMosaic(), theInputFeatherInformation(NULL), theAlphaSum(NULL), theResult(NULL), theFeatherInfoSize(0) { } ossimFeatherMosaic::ossimFeatherMosaic(ossimConnectableObject::ConnectableObjectList& inputSources) :ossimImageMosaic(inputSources), theInputFeatherInformation(NULL), theAlphaSum(NULL), theResult(NULL), theFeatherInfoSize(0) { initialize(); } ossimFeatherMosaic::~ossimFeatherMosaic() { if(theInputFeatherInformation) { delete [] theInputFeatherInformation; theInputFeatherInformation = NULL; } theFeatherInfoSize = 0; } ossimRefPtr ossimFeatherMosaic::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { long w = tileRect.width(); long h = tileRect.height(); ossimIpt origin = tileRect.ul(); if(!isSourceEnabled()) { return ossimImageMosaic::getTile(tileRect, resLevel); } if(!theTile||!theAlphaSum||!theResult||!theInputFeatherInformation) { initialize(); if(!theTile||!theAlphaSum||!theResult||!theInputFeatherInformation) { return ossimImageMosaic::getTile(tileRect, resLevel); } } ossim_uint32 size = getNumberOfInputs(); theAlphaSum->setImageRectangle(tileRect); theResult->setImageRectangle(tileRect); if(size == 0) { return ossimRefPtr(); } if(size == 1) { return ossimImageMosaic::getTile(tileRect, resLevel); } long tileW = theTile->getWidth(); long tileH = theTile->getHeight(); if((w != tileW)|| (h != tileH)) { theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tileW*tileH)) { theTile->initialize(); } } theTile->setOrigin(origin); theTile->makeBlank(); switch(theTile->getScalarType()) { case OSSIM_UCHAR: { return combine(static_cast(0), tileRect, resLevel); } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { return combine(static_cast(0), tileRect, resLevel); } case OSSIM_SSHORT16: { return combine(static_cast(0), tileRect, resLevel); } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { return combine(static_cast(0), tileRect, resLevel); } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { return combine(static_cast(0), tileRect, resLevel); } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimFeatherMosaic::getTile: error, unknown scalar type!!!" << std::endl; } } return ossimRefPtr(); } template ossimRefPtr ossimFeatherMosaic::combine( T, const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr currentImageData; ossim_uint32 band; long upperBound = theTile->getWidth()*theTile->getHeight(); long offset = 0; long row = 0; long col = 0; long numberOfTilesProcessed = 0; float *sumBand = static_cast(theAlphaSum->getBuf()); float *bandRes = NULL; ossimIpt point; theAlphaSum->fill(0.0); theResult->fill(0.0); T** srcBands = new T*[theLargestNumberOfInputBands]; T** destBands = new T*[theLargestNumberOfInputBands]; ossim_uint32 layerIdx = 0; currentImageData = getNextTile(layerIdx, 0, tileRect, resLevel); if(!currentImageData.valid()) { delete [] srcBands; delete [] destBands; return currentImageData; } ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); destBands[band] = static_cast(theTile->getBuf(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; destBands[band] = static_cast(theTile->getBuf(band)); } // most of the time we will not overlap so let's // copy the first tile into destination and check later. // for(band = 0; band < theTile->getNumberOfBands();++band) { T* destBand = destBands[band]; T* srcBand = srcBands[band]; if(destBand&&srcBand) { for(offset = 0; offset < upperBound;++offset) { *destBand = *srcBand; ++srcBand; ++destBand; } } } theTile->setDataObjectStatus(currentImageData->getDataObjectStatus()); while(currentImageData.valid()) { ossimDataObjectStatus currentStatus = currentImageData->getDataObjectStatus(); point = currentImageData->getOrigin(); long h = (long)currentImageData->getHeight(); long w = (long)currentImageData->getWidth(); if( (currentStatus != OSSIM_EMPTY) && (currentStatus != OSSIM_NULL)) { ++numberOfTilesProcessed; offset = 0; minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; } if(currentStatus == OSSIM_PARTIAL) { for(row = 0; row < h; ++row) { for(col = 0; col < w; ++col) { if(!currentImageData->isNull(offset)) { double weight = computeWeight(layerIdx, ossimDpt(point.x+col, point.y+row)); for(band = 0; band < theLargestNumberOfInputBands; ++band) { bandRes = static_cast(theResult->getBuf(band)); bandRes[offset] += (srcBands[band][offset]*weight); } sumBand[offset] += weight; } ++offset; } } } else { offset = 0; for(row = 0; row < h; ++row) { for(col = 0; col < w; ++col) { double weight = computeWeight(layerIdx, ossimDpt(point.x+col, point.y+row)); for(band = 0; band < theLargestNumberOfInputBands; ++band) { bandRes = static_cast(theResult->getBuf(band)); bandRes[offset] += (srcBands[band][offset]*weight); } sumBand[offset] += weight; ++offset; } } } } currentImageData = getNextTile(layerIdx, tileRect, resLevel); } upperBound = theTile->getWidth()*theTile->getHeight(); if(numberOfTilesProcessed > 1) { const double* minPix = theTile->getMinPix(); const double* maxPix = theTile->getMaxPix(); const double* nullPix= theTile->getNullPix(); for(offset = 0; offset < upperBound;++offset) { for(band = 0; band < theTile->getNumberOfBands();++band) { T* destBand = static_cast(theTile->getBuf(band)); float* weightedBand = static_cast(theResult->getBuf(band)); // this should be ok to test 0.0 instead of // FLT_EPSILON range for 0 since we set it. if(sumBand[offset] != 0.0) { weightedBand[offset] = (weightedBand[offset])/sumBand[offset]; if(weightedBand[offset] maxPix[band]) { weightedBand[offset] = maxPix[band]; } } else { weightedBand[offset] = nullPix[band]; } destBand[offset] = static_cast(weightedBand[offset]); } } theTile->validate(); } delete [] srcBands; delete [] destBands; return theTile; } double ossimFeatherMosaic::computeWeight(long index, const ossimDpt& point)const { ossimFeatherInputInformation& info = theInputFeatherInformation[index]; double result = 0.0; ossimDpt delta = point-info.theCenter; double length1 = fabs(delta.x*info.theAxis1.x + delta.y*info.theAxis1.y)/info.theAxis1Length; double length2 = fabs(delta.x*info.theAxis2.x + delta.y*info.theAxis2.y)/info.theAxis2Length; if(length1 > length2) { result = (1.0 - length1); } else { result = (1.0 - length2); } if(result < 0) result = 0; return result; } void ossimFeatherMosaic::initialize() { ossimImageMosaic::initialize(); allocate(); if(theTile.valid()) { theAlphaSum = new ossimImageData(this, OSSIM_FLOAT, 1, theTile->getWidth(), theTile->getHeight()); theResult = new ossimImageData(this, OSSIM_FLOAT, theLargestNumberOfInputBands, theTile->getWidth(), theTile->getHeight()); theAlphaSum->initialize(); theResult->initialize(); } std::vector validVertices; if(!getNumberOfInputs()) return; if(theInputFeatherInformation) { delete [] theInputFeatherInformation; theInputFeatherInformation = NULL; } theFeatherInfoSize = getNumberOfInputs(); theInputFeatherInformation = new ossimFeatherInputInformation[theFeatherInfoSize]; for(long index = 0; index < theFeatherInfoSize; ++ index) { validVertices.clear(); ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(index)); if(temp) { temp->getValidImageVertices(validVertices, OSSIM_CLOCKWISE_ORDER); theInputFeatherInformation[index].setVertexList(validVertices); } } } ossimFeatherMosaic::ossimFeatherInputInformation::ossimFeatherInputInformation(const std::vector& validVertices) { setVertexList(validVertices); } void ossimFeatherMosaic::ossimFeatherInputInformation::setVertexList(const std::vector& validVertices) { const char* MODULE = "ossimFeatherMosaic::ossimFeatherInputInformation::setVertexList()"; theValidVertices = validVertices; theCenter = ossimDpt(0,0); theAxis1 = ossimDpt(1, 0); theAxis2 = ossimDpt(0, 1); theAxis1Length = 1; theAxis2Length = 1; double xSum=0.0, ySum=0.0; ossim_uint32 upperBound = (ossim_uint32)validVertices.size(); if(upperBound) { for(ossim_uint32 index = 0; index < upperBound; ++index) { xSum += validVertices[index].x; ySum += validVertices[index].y; } theCenter.x = xSum/upperBound; theCenter.y = ySum/upperBound; // for now we just want a quick implementation of something // and we know that we have 4 vertices for the bounding valid // vertices. // if(upperBound == 4) { ossimDpt edgeDirection1 = validVertices[1] - validVertices[0]; ossimDpt edgeDirection2 = validVertices[2] - validVertices[1]; theAxis1 = ossimDpt(-edgeDirection1.y, edgeDirection1.x); theAxis2 = ossimDpt(-edgeDirection2.y, edgeDirection2.x); theAxis1 = theAxis1/theAxis1.length(); theAxis2 = theAxis2/theAxis2.length(); ossimLine line1(theCenter, theCenter + theAxis1*2); ossimLine line2(validVertices[1], validVertices[0]); ossimLine line3(theCenter, theCenter + theAxis2*2); ossimLine line4(validVertices[2], validVertices[1]); ossimDpt intersectionPoint1 = line1.intersectInfinite(line2); ossimDpt intersectionPoint2 = line3.intersectInfinite(line4); theAxis1Length = ossim::round((theCenter-intersectionPoint1).length()); theAxis2Length = ossim::round((theCenter-intersectionPoint2).length()); if(traceDebug()) { CLOG << "theAxis1Length: " << theAxis1Length << endl << "theAxis2Length: " << theAxis2Length << endl << "center: " << theCenter << endl; } } } } ostream& operator<<(ostream& out, const ossimFeatherMosaic::ossimFeatherInputInformation& data) { out << "center: " << data.theCenter << endl << "axis1: " << data.theAxis1 << endl << "axis2: " << data.theAxis2 << endl << "axis1_length: " << data.theAxis1Length << endl << "axis2_length: " << data.theAxis2Length << endl << "valid vertices: " << endl; std::copy(data.theValidVertices.begin(), data.theValidVertices.end(), std::ostream_iterator(out, "\n")); return out; } ossim-Miami-2.9.1/src/imaging/ossimFftFilter.cpp000066400000000000000000000263541352751253100215730ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimFftFilter.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimFftFilter, "ossimFftFilter", ossimImageSourceFilter); ossimFftFilter::ossimFftFilter(ossimObject* owner) :ossimImageSourceFilter(owner), theTile(0), theDirectionType(FORWARD), theScalarRemapper(new ossimScalarRemapper()) { theScalarRemapper->setOutputScalarType(OSSIM_NORMALIZED_DOUBLE); } ossimFftFilter::ossimFftFilter(ossimImageSource* inputSource) :ossimImageSourceFilter(inputSource), theTile(0), theDirectionType(FORWARD), theScalarRemapper(new ossimScalarRemapper()) { theScalarRemapper->setOutputScalarType(OSSIM_NORMALIZED_DOUBLE); } ossimFftFilter::ossimFftFilter(ossimObject* owner, ossimImageSource* inputSource) :ossimImageSourceFilter(owner, inputSource), theTile(0), theDirectionType(FORWARD), theScalarRemapper(new ossimScalarRemapper()) { theScalarRemapper->setOutputScalarType(OSSIM_NORMALIZED_DOUBLE); } ossimFftFilter::~ossimFftFilter() { if(theScalarRemapper.valid()) { theScalarRemapper->disconnect(); theScalarRemapper = 0; } } ossimRefPtr ossimFftFilter::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { if(!isSourceEnabled()) return ossimImageSourceFilter::getTile(rect, resLevel); ossimIrect tempRequest = rect; ossim_uint32 w = rect.width(); ossim_uint32 h = rect.height(); if(w & 1) ++w; if(h&1) ++h; tempRequest = ossimIrect(rect.ul().x, rect.ul().y, rect.ul().x + (w-1), rect.ul().y + (h-1)); ossimRefPtr inTile = theScalarRemapper->getTile(tempRequest, resLevel); if(!inTile.valid()) return inTile; if(!theTile.valid()) initialize(); if(!theTile.valid() || !inTile->getBuf()) return theTile; theTile->setImageRectangle(rect); ossimRefPtr tempTile = theTile; if(rect != tempRequest) { tempTile = (ossimImageData*)theTile->dup(); tempTile->setImageRectangle(tempRequest); } runFft(inTile, tempTile); if(tempTile != theTile) { theTile->loadTile(tempTile.get()); } theTile->validate(); return theTile; } void ossimFftFilter::initialize() { ossimImageSourceFilter::initialize(); theTile = ossimImageDataFactory::instance()->create(this, this); if(theTile.valid()) { theTile->initialize(); } if(theDirectionType == FORWARD) { theScalarRemapper->setOutputScalarType(OSSIM_NORMALIZED_DOUBLE); } else { theScalarRemapper->setOutputScalarType(OSSIM_NORMALIZED_DOUBLE); } theScalarRemapper->connectMyInputTo(0, getInput()); } ossimScalarType ossimFftFilter::getOutputScalarType() const { if(!isSourceEnabled()) { return ossimImageSourceFilter::getOutputScalarType(); } if(theDirectionType == FORWARD) { return OSSIM_NORMALIZED_DOUBLE; } return OSSIM_NORMALIZED_DOUBLE; } double ossimFftFilter::getNullPixelValue(ossim_uint32 band)const { if(!isSourceEnabled()) { return ossimImageSourceFilter::getNullPixelValue(band); } if(theDirectionType == FORWARD) { return ossim::nan(); } // it will invert to a normalized float output return 0.0; } double ossimFftFilter::getMinPixelValue(ossim_uint32 band)const { if(!isSourceEnabled()) { return ossimImageSourceFilter::getMinPixelValue(band); } return 0.0; } double ossimFftFilter::getMaxPixelValue(ossim_uint32 band)const { if(!isSourceEnabled()) { return ossimImageSourceFilter::getMaxPixelValue(band); } return 1.0; } ossim_uint32 ossimFftFilter::getNumberOfOutputBands() const { if(!isSourceEnabled()) { return ossimImageSourceFilter::getNumberOfOutputBands(); } ossim_uint32 bands = ossimImageSourceFilter::getNumberOfOutputBands(); if(theDirectionType == FORWARD) { bands *=2; } else { bands /=2; } return bands; } void ossimFftFilter::setForward() { theDirectionType = FORWARD; } void ossimFftFilter::setInverse() { theDirectionType = INVERSE; } ossimString ossimFftFilter::getDirectionTypeAsString()const { if(theDirectionType == FORWARD) { return "Forward"; } return "Inverse"; } void ossimFftFilter::setDirectionType(const ossimString& directionType) { ossimString tempDirectionType = directionType; tempDirectionType = tempDirectionType.downcase(); if(tempDirectionType.contains("forward")) { setDirectionType(FORWARD); } else { setDirectionType(INVERSE); } } void ossimFftFilter::setDirectionType(ossimFftFilterDirectionType directionType) { theDirectionType = directionType; if(theTile.valid()) { theTile = NULL; } } ossimRefPtr ossimFftFilter::getProperty(const ossimString& name)const { if(name == "FFT Direction") { std::vector filterNames; filterNames.push_back("Forward"); filterNames.push_back("Inverse"); ossimStringProperty* stringProp = new ossimStringProperty("FFT Direction", getDirectionTypeAsString(), false, filterNames); stringProp->setCacheRefreshBit(); return stringProp; } return ossimImageSourceFilter::getProperty(name); } void ossimFftFilter::setProperty(ossimRefPtr property) { if(!property) return; if(property->getName() == "FFT Direction") { if(theTile.valid()) { theTile = NULL; } setDirectionType(property->valueToString()); } else { ossimImageSourceFilter::setProperty(property); } } void ossimFftFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("FFT Direction"); } void ossimFftFilter::runFft(ossimRefPtr& input, ossimRefPtr& output) { NEWMAT::Matrix* realIn = new NEWMAT::Matrix(input->getHeight(), input->getWidth()); NEWMAT::Matrix* imgIn = new NEWMAT::Matrix(input->getHeight(), input->getWidth()); NEWMAT::Matrix* realOut = new NEWMAT::Matrix(input->getHeight(), input->getWidth()); NEWMAT::Matrix* imgOut = new NEWMAT::Matrix(input->getHeight(), input->getWidth()); ossim_uint32 bandIdx = 0; ossim_uint32 w = input->getWidth(); ossim_uint32 h = input->getHeight(); ossim_uint32 x = 0; ossim_uint32 y = 0; if(theDirectionType == FORWARD) { ossim_uint32 bands = input->getNumberOfBands(); for(bandIdx = 0; bandIdx < bands; ++bandIdx) { ossim_float64* bandReal = 0; ossim_float64* bandImg = 0; fillMatrixForward((ossim_float64*)input->getBuf(bandIdx), (ossim_float64)input->getNullPix(bandIdx), *realIn, *imgIn); NEWMAT::FFT2(*realIn, *imgIn, *realOut, *imgOut); bandReal = (ossim_float64*)output->getBuf(2*bandIdx); bandImg = (ossim_float64*)output->getBuf(2*bandIdx + 1); if(bandReal&&bandImg) { for(y = 0; y < h; ++y) { for(x = 0; x < w; ++x) { *bandReal = (ossim_float64)((*realOut)[y][x]); *bandImg = (ossim_float64)((*imgOut)[y][x]); ++bandReal; ++bandImg; } } } } } else { ossim_float64* bandReal = 0; ossim_uint32 bands = input->getNumberOfBands(); for(bandIdx = 0; bandIdx < bands; bandIdx+=2) { bandReal = (ossim_float64*)output->getBuf(bandIdx/2); if(input->getBuf(bandIdx)&& input->getBuf(bandIdx+1)) { fillMatrixInverse((double*)input->getBuf(bandIdx), (double*)input->getBuf(bandIdx+1), *realIn, *imgIn); NEWMAT::FFT2I(*realIn, *imgIn, *realOut, *imgOut); for(y = 0; y < h; ++y) { for(x = 0; x < w; ++x) { *bandReal = (ossim_float64)((*realOut)[y][x]); // if(*bandReal > 1.0) // { // *bandReal = 1.0; // } // if(*bandReal < 0.0) // { // *bandReal = 0.0; // } ++bandReal; } } } } } delete realIn; delete imgIn; delete realOut; delete imgOut; } template void ossimFftFilter::fillMatrixForward(T *realPart, T nullPix, NEWMAT::Matrix& real, NEWMAT::Matrix& img)const { ossim_uint32 w = real.Ncols(); ossim_uint32 h = real.Nrows(); ossim_uint32 yIdx = 0; ossim_uint32 xIdx = 0; for(yIdx = 0; yIdx < h; ++yIdx) { for(xIdx = 0; xIdx < w; ++xIdx) { if((double)(*realPart) != nullPix) { real[yIdx][xIdx] = (double)(*realPart); } else { real[yIdx][xIdx] = 0.0; } img[yIdx][xIdx] = 0.0; ++realPart; } } } template void ossimFftFilter::fillMatrixInverse(T *realPart, T *imgPart, NEWMAT::Matrix& real, NEWMAT::Matrix& img)const { ossim_uint32 w = real.Ncols(); ossim_uint32 h = real.Nrows(); ossim_uint32 yIdx = 0; ossim_uint32 xIdx = 0; for(yIdx = 0; yIdx < h; ++yIdx) { for(xIdx = 0; xIdx < w; ++xIdx) { real[yIdx][xIdx] = (double)(*realPart); img[yIdx][xIdx] = (double)(*imgPart); ++realPart; ++imgPart; } } } bool ossimFftFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* direction = kwl.find(prefix, "fft_direction"); if(direction) { setDirectionType(ossimString(direction)); } return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimFftFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "fft_direction", getDirectionTypeAsString(), true); return ossimImageSourceFilter::saveState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimFgdcFileWriter.cpp000066400000000000000000000752751352751253100225540ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class to write out meta data in a Federal Geographic Data // Committe (FGDC) format. // //---------------------------------------------------------------------------- // $Id: ossimFgdcFileWriter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimFgdcFileWriter, "ossimFgdcFileWriter", ossimMetadataFileWriter) static ossimTrace traceDebug("ossimFgdcFileWriter:debug"); ossimFgdcFileWriter::ossimFgdcFileWriter() : theIndentionLevel(0), theTabString("\t"), theTemplate(), theSourceImageFilename() { } ossimFgdcFileWriter::~ossimFgdcFileWriter() { } bool ossimFgdcFileWriter::writeFile() { if(theFilename == ossimFilename::NIL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimFgdcFileWriter::writeFile no filename set!" << endl; return false; } if( !theInputConnection ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimFgdcFileWriter::writeFile no input connection!" << endl; return false; } ofstream os(theFilename.c_str()); if (!os) { ossimNotify(ossimNotifyLevel_WARN) << "ossimFgdcFileWriter::writeFile no input connection!" << endl; return false; } // Get the geometry from the input. ossimMapProjection* mapProj = 0; ossimRefPtr inputGeom = theInputConnection->getImageGeometry(); if ( inputGeom.valid() ) mapProj = PTR_CAST(ossimMapProjection, inputGeom->getProjection()); if (!mapProj) { ossimNotify(ossimNotifyLevel_WARN) << "ossimFgdcFileWriter::writeFile Not map projected." << endl; return false; } ossimMapProjectionInfo mpi(mapProj, theInputConnection->getBoundingRect()); os << "\n" << "\n"; openTag(os, ossimString("metadata"), true); openTag(os, ossimString("idinfo"), true); openTag(os, ossimString("citation"), true); openTag(os, ossimString("citeinfo"), true); openTag(os, ossimString("origin"), false); os << find(ossimString("/metadata/idinfo/citation/citeinfo/origin")); closeTag(os, ossimString("origin"), false); openTag(os, ossimString("pubdate"), false); os << find(ossimString("/metadata/idinfo/citation/citeinfo/pubdate")); closeTag(os, ossimString("pubdate"), false); openTag(os, ossimString("title"), false); // os << find(ossimString("/metadata/idinfo/citation/citeinfo/title")); os << theSourceImageFilename.c_str(); closeTag(os, ossimString("title"), false); openTag(os, ossimString("edition"), false); os << find(ossimString("/metadata/idinfo/citation/citeinfo/edition")); closeTag(os, ossimString("edition"), false); openTag(os, ossimString("geoform"), false); os << find(ossimString("/metadata/idinfo/citation/citeinfo/geoform")); closeTag(os, ossimString("geoform"), false); openTag(os, ossimString("serinfo"), true); openTag(os, ossimString("sername"), false); os << find(ossimString("/metadata/idinfo/citation/citeinfo/serinfo/sername")); closeTag(os, ossimString("sername"), false); openTag(os, ossimString("issue"), false); os << theSourceImageFilename.c_str(); closeTag(os, ossimString("issue"), false); closeTag(os, ossimString("serinfo"), true); openTag(os, ossimString("pubinfo"), true); openTag(os, ossimString("pubplace"), false); os << find(ossimString("/metadata/idinfo/citation/citeinfo/pubinfo/pubplace")); closeTag(os, ossimString("pubplace"), false); openTag(os, ossimString("publish"), false); os << find(ossimString("/metadata/idinfo/citation/citeinfo/pubinfo/publish")); closeTag(os, ossimString("publish"), false); closeTag(os, ossimString("pubinfo"), true); closeTag(os, ossimString("citeinfo"), true); closeTag(os, ossimString("citation"), true); openTag(os, ossimString("descript"), true); openTag(os, ossimString("abstract"), false); os << find(ossimString("/metadata/idinfo/descript/abstract")); closeTag(os, ossimString("abstract"), false); openTag(os, ossimString("purpose"), false); os << find(ossimString("/metadata/idinfo/descript/purpose")); closeTag(os, ossimString("purpose"), false); openTag(os, ossimString("supplinf"), false); os << find(ossimString("/metadata/idinfo/descript/supplinf")); closeTag(os, ossimString("supplinf"), false); closeTag(os, ossimString("descript"), true); openTag(os, ossimString("timeperd"), true); openTag(os, ossimString("timeinfo"), true); openTag(os, ossimString("sngdate"), true); openTag(os, ossimString("caldate"), false); os << find(ossimString("/metadata/idinfo/timeperd/timeinfo/sngdate/caldate")); closeTag(os, ossimString("caldate"), false); closeTag(os, ossimString("sngdate"), true); closeTag(os, ossimString("timeinfo"), true); openTag(os, ossimString("current"), false); os << find(ossimString("/metadata/idinfo/timeperd/current")); closeTag(os, ossimString("current"), false); closeTag(os, ossimString("timeperd"), true); openTag(os, ossimString("status"), true); openTag(os, ossimString("progress"), false); os << find(ossimString("/metadata/idinfo/status/progress")); closeTag(os, ossimString("progress"), false); openTag(os, ossimString("update"), false); os << find(ossimString("/metadata/idinfo/status/update")); closeTag(os, ossimString("update"), false); closeTag(os, ossimString("status"), true); openTag(os, ossimString("spdom"), true); openTag(os, ossimString("bounding"), true); if (mapProj->isGeographic()) { openTag(os, ossimString("westbc"), false); os << ossimString::toString(mpi.ulGroundPt().lon); closeTag(os, ossimString("westbc"), false); openTag(os, ossimString("eastbc"), false); os << ossimString::toString(mpi.lrGroundPt().lon); closeTag(os, ossimString("eastbc"), false); openTag(os, ossimString("northbc"), false); os << ossimString::toString(mpi.ulGroundPt().lat); closeTag(os, ossimString("northbc"), false); openTag(os, ossimString("southbc"), false); os << ossimString::toString(mpi.lrGroundPt().lat); closeTag(os, ossimString("southbc"), false); } else { openTag(os, ossimString("westbc"), false); os << ossimString::toString(mpi.ulEastingNorthingPt().x); closeTag(os, ossimString("westbc"), false); openTag(os, ossimString("eastbc"), false); os << ossimString::toString(mpi.lrEastingNorthingPt().x); closeTag(os, ossimString("eastbc"), false); openTag(os, ossimString("northbc"), false); os << ossimString::toString(mpi.ulEastingNorthingPt().y); closeTag(os, ossimString("northbc"), false); openTag(os, ossimString("southbc"), false); os << ossimString::toString(mpi.ulEastingNorthingPt().y); closeTag(os, ossimString("southbc"), false); } closeTag(os, ossimString("bounding"), true); closeTag(os, ossimString("spdom"), true); openTag(os, ossimString("keywords"), true); openTag(os, ossimString("theme"), true); openTag(os, ossimString("themekt"), false); os << find(ossimString("/metadata/idinfo/keywords/theme/themekt")); closeTag(os, ossimString("themekt"), false); openTag(os, ossimString("themekey"), false); os << find(ossimString("/metadata/idinfo/keywords/theme/themekey")); closeTag(os, ossimString("themekey"), false); closeTag(os, ossimString("theme"), true); closeTag(os, ossimString("keywords"), true); openTag(os, ossimString("accconst"), false); os << find(ossimString("/metadata/idinfo/accconst")); closeTag(os, ossimString("accconst"), false); openTag(os, ossimString("useconst"), false); os << find(ossimString("/metadata/idinfo/useconst")); closeTag(os, ossimString("useconst"), false); openTag(os, ossimString("ptcontac"), true); openTag(os, ossimString("cntinfo"), true); openTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntper"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntperp/cntper")); closeTag(os, ossimString("cntper"), false); closeTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("addrtype"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntaddr/addrtype")); closeTag(os, ossimString("addrtype"), false); openTag(os, ossimString("address"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntaddr/address")); closeTag(os, ossimString("address"), false); openTag(os, ossimString("city"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntaddr/city")); closeTag(os, ossimString("city"), false); openTag(os, ossimString("state"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntaddr/state")); closeTag(os, ossimString("state"), false); openTag(os, ossimString("postal"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntaddr/postal")); closeTag(os, ossimString("postal"), false); openTag(os, ossimString("country"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntaddr/country")); closeTag(os, ossimString("country"), false); closeTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("cntvoice"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntvoice")); closeTag(os, ossimString("cntvoice"), false); openTag(os, ossimString("cntfax"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntfax")); closeTag(os, ossimString("cntfax"), false); openTag(os, ossimString("cntemail"), false); os << find(ossimString("/metadata/idinfo/ptcontac/cntinfo/cntemail")); closeTag(os, ossimString("cntemail"), false); closeTag(os, ossimString("cntinfo"), true); closeTag(os, ossimString("ptcontac"), true); openTag(os, ossimString("secinfo"), true); openTag(os, ossimString("secclass"), false); os << find(ossimString("/metadata/idinfo/secinfo/secclass")); closeTag(os, ossimString("secclass"), false); openTag(os, ossimString("secsys"), false); os << find(ossimString("/metadata/idinfo/secinfo/secsys")); closeTag(os, ossimString("secsys"), false); openTag(os, ossimString("sechandl"), false); os << find(ossimString("/metadata/idinfo/secinfo/sechandl")); closeTag(os, ossimString("sechandl"), false); closeTag(os, ossimString("secinfo"), true); closeTag(os, ossimString("idinfo"), true); openTag(os, ossimString("distinfo"), true); openTag(os, ossimString("distrib"), true); openTag(os, ossimString("cntinfo"), true); openTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntper"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntperp/cntper")); closeTag(os, ossimString("cntper"), false); closeTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("addrtype"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntaddr/addrtype")); closeTag(os, ossimString("addrtype"), false); openTag(os, ossimString("address"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntaddr/address")); closeTag(os, ossimString("address"), false); openTag(os, ossimString("city"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntaddr/city")); closeTag(os, ossimString("city"), false); openTag(os, ossimString("state"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntaddr/state")); closeTag(os, ossimString("state"), false); openTag(os, ossimString("postal"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntaddr/postal")); closeTag(os, ossimString("postal"), false); openTag(os, ossimString("country"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntaddr/country")); closeTag(os, ossimString("country"), false); closeTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("cntvoice"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntvoice")); closeTag(os, ossimString("cntvoice"), false); openTag(os, ossimString("cntfax"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntfax")); closeTag(os, ossimString("cntfax"), false); openTag(os, ossimString("cntemail"), false); os << find(ossimString("/metadata/distinfo/distrib/cntinfo/cntemail")); closeTag(os, ossimString("cntemail"), false); closeTag(os, ossimString("cntinfo"), true); closeTag(os, ossimString("distrib"), true); openTag(os, ossimString("resdesc"), false); os << find(ossimString("/metadata/distinfo/resdesc")); closeTag(os, ossimString("resdesc"), false); openTag(os, ossimString("distliab"), false); os << find(ossimString("/metadata/distinfo/distliab")); closeTag(os, ossimString("distliab"), false); openTag(os, ossimString("stdorder"), true); openTag(os, ossimString("digform"), true); openTag(os, ossimString("digtinfo"), true); openTag(os, ossimString("formname"), false); os << find(ossimString("/metadata/distinfo/stdorder/digform/digtinfo/formname")); closeTag(os, ossimString("formname"), false); closeTag(os, ossimString("digtinfo"), true); openTag(os, ossimString("digtopt"), true); openTag(os, ossimString("onlinopt"), true); openTag(os, ossimString("computer"), true); openTag(os, ossimString("networka"), true); openTag(os, ossimString("networkr"), false); os << find(ossimString("/metadata/distinfo/stdorder/digform/digtopt/onlinopt/computer/networka/networkr")); closeTag(os, ossimString("networkr"), false); closeTag(os, ossimString("networka"), true); closeTag(os, ossimString("computer"), true); closeTag(os, ossimString("onlinopt"), true); closeTag(os, ossimString("digtopt"), true); closeTag(os, ossimString("digform"), true); openTag(os, ossimString("fees"), false); os << find(ossimString("/metadata/distinfo/stdorder/fees")); closeTag(os, ossimString("fees"), false); closeTag(os, ossimString("stdorder"), true); closeTag(os, ossimString("distinfo"), true); openTag(os, ossimString("metainfo"), true); openTag(os, ossimString("metd"), false); os << find(ossimString("/metadata/metainfo/metd")); closeTag(os, ossimString("metd"), false); openTag(os, ossimString("metc"), true); openTag(os, ossimString("cntinfo"), true); openTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntper"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntperp/cntper")); closeTag(os, ossimString("cntper"), false); closeTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("addrtype"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntaddr/addrtype")); closeTag(os, ossimString("addrtype"), false); openTag(os, ossimString("address"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntaddr/address")); closeTag(os, ossimString("address"), false); openTag(os, ossimString("city"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntaddr/city")); closeTag(os, ossimString("city"), false); openTag(os, ossimString("state"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntaddr/state")); closeTag(os, ossimString("state"), false); openTag(os, ossimString("postal"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntaddr/postal")); closeTag(os, ossimString("postal"), false); openTag(os, ossimString("country"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntaddr/country")); closeTag(os, ossimString("country"), false); closeTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("cntvoice"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntvoice")); closeTag(os, ossimString("cntvoice"), false); openTag(os, ossimString("cntfax"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntfax")); closeTag(os, ossimString("cntfax"), false); openTag(os, ossimString("cntemail"), false); os << find(ossimString("/metadata/metainfo/metc/cntinfo/cntemail")); closeTag(os, ossimString("cntemail"), false); closeTag(os, ossimString("cntinfo"), true); closeTag(os, ossimString("metc"), true); openTag(os, ossimString("metstdn"), false); os << find(ossimString("/metadata/metainfo/metstdn")); closeTag(os, ossimString("metstdn"), false); openTag(os, ossimString("metstdv"), false); os << find(ossimString("/metadata/metainfo/metstdv")); closeTag(os, ossimString("metstdv"), false); closeTag(os, ossimString("metainfo"), true); closeTag(os, ossimString("metadata"), true); os.close(); return true; } bool ossimFgdcFileWriter::writeTemplate(const ossimFilename& file) const { ofstream os(file.c_str()); if (!os) { ossimNotify(ossimNotifyLevel_WARN) << "ossimFgdcFileWriter::writeTemplate Could not open: " << file << endl; return false; } os << "\n" << "\n"; openTag(os, ossimString("metadata"), true); openTag(os, ossimString("idinfo"), true); openTag(os, ossimString("citation"), true); openTag(os, ossimString("citeinfo"), true); openTag(os, ossimString("origin"), false); closeTag(os, ossimString("origin"), false); openTag(os, ossimString("pubdate"), false); closeTag(os, ossimString("pubdate"), false); openTag(os, ossimString("title"), false); closeTag(os, ossimString("title"), false); openTag(os, ossimString("edition"), false); closeTag(os, ossimString("edition"), false); openTag(os, ossimString("geoform"), false); closeTag(os, ossimString("geoform"), false); openTag(os, ossimString("serinfo"), true); openTag(os, ossimString("sername"), false); closeTag(os, ossimString("sername"), false); openTag(os, ossimString("issue"), false); closeTag(os, ossimString("issue"), false); closeTag(os, ossimString("serinfo"), true); openTag(os, ossimString("pubinfo"), true); openTag(os, ossimString("pubplace"), false); closeTag(os, ossimString("pubplace"), false); openTag(os, ossimString("publish"), false); closeTag(os, ossimString("publish"), false); closeTag(os, ossimString("pubinfo"), true); closeTag(os, ossimString("citeinfo"), true); closeTag(os, ossimString("citation"), true); openTag(os, ossimString("descript"), true); openTag(os, ossimString("abstract"), false); closeTag(os, ossimString("abstract"), false); openTag(os, ossimString("purpose"), false); closeTag(os, ossimString("purpose"), false); openTag(os, ossimString("supplinf"), false); closeTag(os, ossimString("supplinf"), false); closeTag(os, ossimString("descript"), true); openTag(os, ossimString("timeperd"), true); openTag(os, ossimString("timeinfo"), true); openTag(os, ossimString("sngdate"), true); openTag(os, ossimString("caldate"), false); closeTag(os, ossimString("caldate"), false); closeTag(os, ossimString("sngdate"), true); closeTag(os, ossimString("timeinfo"), true); openTag(os, ossimString("current"), false); closeTag(os, ossimString("current"), false); closeTag(os, ossimString("timeperd"), true); openTag(os, ossimString("status"), true); openTag(os, ossimString("progress"), false); closeTag(os, ossimString("progress"), false); openTag(os, ossimString("update"), false); closeTag(os, ossimString("update"), false); closeTag(os, ossimString("status"), true); openTag(os, ossimString("spdom"), true); openTag(os, ossimString("bounding"), true); openTag(os, ossimString("westbc"), false); closeTag(os, ossimString("westbc"), false); openTag(os, ossimString("eastbc"), false); closeTag(os, ossimString("eastbc"), false); openTag(os, ossimString("northbc"), false); closeTag(os, ossimString("northbc"), false); openTag(os, ossimString("southbc"), false); closeTag(os, ossimString("southbc"), false); closeTag(os, ossimString("bounding"), true); closeTag(os, ossimString("spdom"), true); openTag(os, ossimString("keywords"), true); openTag(os, ossimString("theme"), true); openTag(os, ossimString("themekt"), false); closeTag(os, ossimString("themekt"), false); openTag(os, ossimString("themekey"), false); closeTag(os, ossimString("themekey"), false); closeTag(os, ossimString("theme"), true); closeTag(os, ossimString("keywords"), true); openTag(os, ossimString("accconst"), false); closeTag(os, ossimString("accconst"), false); openTag(os, ossimString("useconst"), false); closeTag(os, ossimString("useconst"), false); openTag(os, ossimString("ptcontac"), true); openTag(os, ossimString("cntinfo"), true); openTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntper"), false); closeTag(os, ossimString("cntper"), false); closeTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("addrtype"), false); closeTag(os, ossimString("addrtype"), false); openTag(os, ossimString("address"), false); closeTag(os, ossimString("address"), false); openTag(os, ossimString("city"), false); closeTag(os, ossimString("city"), false); openTag(os, ossimString("state"), false); closeTag(os, ossimString("state"), false); openTag(os, ossimString("postal"), false); closeTag(os, ossimString("postal"), false); openTag(os, ossimString("country"), false); closeTag(os, ossimString("country"), false); closeTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("cntvoice"), false); closeTag(os, ossimString("cntvoice"), false); openTag(os, ossimString("cntfax"), false); closeTag(os, ossimString("cntfax"), false); openTag(os, ossimString("cntemail"), false); closeTag(os, ossimString("cntemail"), false); closeTag(os, ossimString("cntinfo"), true); closeTag(os, ossimString("ptcontac"), true); openTag(os, ossimString("secinfo"), true); openTag(os, ossimString("secclass"), false); closeTag(os, ossimString("secclass"), false); openTag(os, ossimString("secsys"), false); closeTag(os, ossimString("secsys"), false); openTag(os, ossimString("sechandl"), false); closeTag(os, ossimString("sechandl"), false); closeTag(os, ossimString("secinfo"), true); closeTag(os, ossimString("idinfo"), true); openTag(os, ossimString("distinfo"), true); openTag(os, ossimString("distrib"), true); openTag(os, ossimString("cntinfo"), true); openTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntper"), false); closeTag(os, ossimString("cntper"), false); closeTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("addrtype"), false); closeTag(os, ossimString("addrtype"), false); openTag(os, ossimString("address"), false); closeTag(os, ossimString("address"), false); openTag(os, ossimString("city"), false); closeTag(os, ossimString("city"), false); openTag(os, ossimString("state"), false); closeTag(os, ossimString("state"), false); openTag(os, ossimString("postal"), false); closeTag(os, ossimString("postal"), false); openTag(os, ossimString("country"), false); closeTag(os, ossimString("country"), false); closeTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("cntvoice"), false); closeTag(os, ossimString("cntvoice"), false); openTag(os, ossimString("cntfax"), false); closeTag(os, ossimString("cntfax"), false); openTag(os, ossimString("cntemail"), false); closeTag(os, ossimString("cntemail"), false); closeTag(os, ossimString("cntinfo"), true); closeTag(os, ossimString("distrib"), true); openTag(os, ossimString("resdesc"), false); closeTag(os, ossimString("resdesc"), false); openTag(os, ossimString("distliab"), false); closeTag(os, ossimString("distliab"), false); openTag(os, ossimString("stdorder"), true); openTag(os, ossimString("digform"), true); openTag(os, ossimString("digtinfo"), true); openTag(os, ossimString("formname"), false); closeTag(os, ossimString("formname"), false); closeTag(os, ossimString("digtinfo"), true); openTag(os, ossimString("digtopt"), true); openTag(os, ossimString("onlinopt"), true); openTag(os, ossimString("computer"), true); openTag(os, ossimString("networka"), true); openTag(os, ossimString("networkr"), false); closeTag(os, ossimString("networkr"), false); closeTag(os, ossimString("networka"), true); closeTag(os, ossimString("computer"), true); closeTag(os, ossimString("onlinopt"), true); closeTag(os, ossimString("digtopt"), true); closeTag(os, ossimString("digform"), true); openTag(os, ossimString("fees"), false); closeTag(os, ossimString("fees"), false); closeTag(os, ossimString("stdorder"), true); closeTag(os, ossimString("distinfo"), true); openTag(os, ossimString("metainfo"), true); openTag(os, ossimString("metd"), false); closeTag(os, ossimString("metd"), false); openTag(os, ossimString("metc"), true); openTag(os, ossimString("cntinfo"), true); openTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntper"), false); closeTag(os, ossimString("cntper"), false); closeTag(os, ossimString("cntperp"), true); openTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("addrtype"), false); closeTag(os, ossimString("addrtype"), false); openTag(os, ossimString("address"), false); closeTag(os, ossimString("address"), false); openTag(os, ossimString("city"), false); closeTag(os, ossimString("city"), false); openTag(os, ossimString("state"), false); closeTag(os, ossimString("state"), false); openTag(os, ossimString("postal"), false); closeTag(os, ossimString("postal"), false); openTag(os, ossimString("country"), false); closeTag(os, ossimString("country"), false); closeTag(os, ossimString("cntaddr"), true); openTag(os, ossimString("cntvoice"), false); closeTag(os, ossimString("cntvoice"), false); openTag(os, ossimString("cntfax"), false); closeTag(os, ossimString("cntfax"), false); openTag(os, ossimString("cntemail"), false); closeTag(os, ossimString("cntemail"), false); closeTag(os, ossimString("cntinfo"), true); closeTag(os, ossimString("metc"), true); openTag(os, ossimString("metstdn"), false); closeTag(os, ossimString("metstdn"), false); openTag(os, ossimString("metstdv"), false); closeTag(os, ossimString("metstdv"), false); closeTag(os, ossimString("metainfo"), true); closeTag(os, ossimString("metadata"), true); os.close(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_NOTICE) << "Wrote file: " << file.c_str() << endl; } return true; } bool ossimFgdcFileWriter::loadState (const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = kwl.find(prefix, "template"); if (lookup) { setTemplate(ossimFilename(lookup)); } lookup = kwl.find(prefix, "source_image_filename"); if (lookup) { theSourceImageFilename = lookup; } lookup = kwl.find(prefix, "tab_string"); if (lookup) { theTabString = lookup; } lookup = kwl.find(prefix, "fgdc_template_doc"); if (lookup) { setTemplate(ossimFilename(lookup)); } return ossimMetadataFileWriter::loadState(kwl, prefix); } ossim_uint32 ossimFgdcFileWriter::getIndentionLevel() const { return theIndentionLevel; } void ossimFgdcFileWriter::setIndentionLevel(ossim_uint32 level) { theIndentionLevel = level; } ossimString ossimFgdcFileWriter::getTabString() const { return theTabString; } void ossimFgdcFileWriter::setTabString(const ossimString& tabString) { theTabString = tabString; } void ossimFgdcFileWriter::openTag(std::ostream& os, const ossimString& tag, bool newLine) const { if ( theIndentionLevel && theTabString.size() ) { ossimString tab; for (ossim_uint32 i = 0; i < theIndentionLevel; ++i) { tab += theTabString; } os << tab.c_str(); } os << "<" << tag.c_str() << ">"; if (newLine) { os << "\n"; ++theIndentionLevel; } } void ossimFgdcFileWriter::closeTag(std::ostream& os, const ossimString& tag, bool decrementLevel) const { if ( decrementLevel && (theIndentionLevel > 1) && theTabString.size() ) { ossimString tab; for (ossim_uint32 i = 0; i < theIndentionLevel-1; ++i) { tab += theTabString; } os << tab.c_str(); } os << "\n"; if (theIndentionLevel && decrementLevel) { --theIndentionLevel; } } void ossimFgdcFileWriter::setTemplate(const ossimFilename& xmlTemplateFile) { theTemplate.openFile(xmlTemplateFile); } ossimString ossimFgdcFileWriter::find(const ossimString& xpath) const { ossimString result; if (theTemplate.getErrorStatus()) { return result; } vector< ossimRefPtr > xml_nodes; theTemplate.findNodes(xpath, xml_nodes); if (xml_nodes.size()) { if (xml_nodes[0].valid()) { result = xml_nodes[0]->getText(); } } return result; } void ossimFgdcFileWriter::getMetadatatypeList( std::vector& metadatatypeList) const { metadatatypeList.push_back(ossimString("ossim_fgdc")); } bool ossimFgdcFileWriter::hasMetadataType( const ossimString& metadataType)const { return (metadataType == "ossim_fgdc"); } ossim-Miami-2.9.1/src/imaging/ossimFilter.cpp000066400000000000000000000261161352751253100211270ustar00rootroot00000000000000/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % ZZZZZ OOO OOO M M % % ZZ O O O O MM MM % % ZZZ O O O O M M M % % ZZ O O O O M M % % ZZZZZ OOO OOO M M % % % % % % ImageMagick Image Zoom Methods % % % % % % Software Design % % John Cristy % % July 1992 % % % % % % Copyright (C) 2000 ImageMagick Studio, a non-profit organization dedicated % % to making software imaging solutions freely available. % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % ImageMagick Studio be liable for any claim, damages or other liability, % % whether in an action of contract, tort or otherwise, arising from, out of % % or in connection with ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ #include #include #include #include RTTI_DEF(ossimFilter, "ossimFilter"); RTTI_DEF1(ossimBoxFilter, "ossimBoxFilter",ossimFilter); RTTI_DEF1(ossimSincFilter, "ossimSincFilter",ossimFilter); RTTI_DEF1(ossimBellFilter, "ossimBellFilter",ossimFilter); RTTI_DEF1(ossimNearestNeighborFilter, "ossimNearestNeighborFilter",ossimFilter); RTTI_DEF1(ossimBesselFilter, "ossimBesselFilter",ossimFilter); RTTI_DEF1(ossimBesselOrderOneFilter, "ossimBesselOrderOneFilter",ossimFilter); RTTI_DEF1(ossimBlackmanFilter, "ossimBlackmanFilter",ossimFilter); RTTI_DEF1(ossimBlackmanSincFilter, "ossimBlackmanSincFilter",ossimFilter); RTTI_DEF1(ossimBlackmanBesselFilter, "ossimBlackmanBesselFilter",ossimFilter); RTTI_DEF1(ossimCatromFilter, "ossimCatromFilter",ossimFilter); RTTI_DEF1(ossimCubicFilter, "ossimCubicFilter",ossimFilter); RTTI_DEF1(ossimBSplineFilter, "ossimBSplineFilter",ossimFilter); RTTI_DEF1(ossimGaussianFilter, "ossimGaussianFilter",ossimFilter); RTTI_DEF1(ossimHanningFilter, "ossimHanningFilter",ossimFilter); RTTI_DEF1(ossimHammingFilter, "ossimHammingFilter",ossimFilter); RTTI_DEF1(ossimHermiteFilter, "ossimHermiteFilter",ossimFilter); RTTI_DEF1(ossimLanczosFilter, "ossimLanczosFilter",ossimFilter); RTTI_DEF1(ossimMitchellFilter, "ossimMitchellFilter",ossimFilter); RTTI_DEF1(ossimQuadraticFilter, "ossimQuadraticFilter",ossimFilter); RTTI_DEF1(ossimTriangleFilter, "ossimTriangleFilter",ossimFilter); RTTI_DEF1(ossimMagicFilter, "ossimMagicFilter",ossimFilter); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + B e s s e l O r d e r O n e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method BesselOrderOne computes the Bessel function of x of the first kind % of order 0: % % Reduce x to |x| since j1(x)= -j1(-x), and for x in (0,8] % % j1(x) = x*j1(x); % % For x in (8,inf) % % j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1)) % % where x1 = x-3*pi/4. Compute sin(x1) and cos(x1) as follow: % % cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4) % = 1/sqrt(2) * (sin(x) - cos(x)) % sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) % = -1/sqrt(2) * (sin(x) + cos(x)) % % The format of the BesselOrderOne method is: % % double BesselOrderOne(double x) % % A description of each parameter follows: % % o value: Method BesselOrderOne returns the Bessel function of x of the % first kind of orders 1. % % o x: double value. % % */ static double J1(double x) { double p, q; int i; static const double Pone[] = { 0.581199354001606143928050809e+21, -0.6672106568924916298020941484e+20, 0.2316433580634002297931815435e+19, -0.3588817569910106050743641413e+17, 0.2908795263834775409737601689e+15, -0.1322983480332126453125473247e+13, 0.3413234182301700539091292655e+10, -0.4695753530642995859767162166e+7, 0.270112271089232341485679099e+4 }, Qone[] = { 0.11623987080032122878585294e+22, 0.1185770712190320999837113348e+20, 0.6092061398917521746105196863e+17, 0.2081661221307607351240184229e+15, 0.5243710262167649715406728642e+12, 0.1013863514358673989967045588e+10, 0.1501793594998585505921097578e+7, 0.1606931573481487801970916749e+4, 0.1e+1 }; p=Pone[8]; q=Qone[8]; for (i=7; i >= 0; i--) { p=p*x*x+Pone[i]; q=q*x*x+Qone[i]; } return(p/q); } static double P1(double x) { double p, q; int i; static const double Pone[] = { 0.352246649133679798341724373e+5, 0.62758845247161281269005675e+5, 0.313539631109159574238669888e+5, 0.49854832060594338434500455e+4, 0.2111529182853962382105718e+3, 0.12571716929145341558495e+1 }, Qone[] = { 0.352246649133679798068390431e+5, 0.626943469593560511888833731e+5, 0.312404063819041039923015703e+5, 0.4930396490181088979386097e+4, 0.2030775189134759322293574e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } static double Q1(double x) { double p, q; int i; static const double Pone[] = { 0.3511751914303552822533318e+3, 0.7210391804904475039280863e+3, 0.4259873011654442389886993e+3, 0.831898957673850827325226e+2, 0.45681716295512267064405e+1, 0.3532840052740123642735e-1 }, Qone[] = { 0.74917374171809127714519505e+4, 0.154141773392650970499848051e+5, 0.91522317015169922705904727e+4, 0.18111867005523513506724158e+4, 0.1038187585462133728776636e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } double ossimBesselOrderOneFilter::filter(double x, double /* support */)const { double p, q; if (x == 0.0) return(0.0); p=x; if (x < 0.0) x=(-x); if (x < 8.0) return(p*J1(x)); q=sqrt(2.0/(M_PI*x))*(P1(x)*(1.0/sqrt(2.0)*(sin(x)-cos(x)))-8.0/x*Q1(x)* (-1.0/sqrt(2.0)*(sin(x)+cos(x)))); if (p < 0.0) q=(-q); return(q); } void ossimFilter::createMatrix(NEWMAT::Matrix& m, long width, double middle, double scale)const { NEWMAT::ColumnVector colVec(width); NEWMAT::RowVector rowVec(width); double t = 0.0; double val = 0.0; if(width == 1) { t = 0; val = filter(t, getSupport()); colVec[0] = val; rowVec[0] = val; } else { for(long index = 0; index < width; index++) { t = (double)index/(double)(width-1); t = middle + (t - .5)*scale; val = filter(t, getSupport()); colVec[index] = val; rowVec[index] = val; } } // do the outer product to construct the // filter matrix m = colVec * rowVec; } NEWMAT::Matrix *ossimFilter::newMatrix(long width, double middle, double scale)const { NEWMAT::Matrix *result = new NEWMAT::Matrix(width, width); createMatrix(*result, width, middle, scale); return result; } NEWMAT::RowVector *ossimFilter::newVector(long width, double middle, double scale)const { NEWMAT::RowVector *result = new NEWMAT::RowVector(width); double t = 0.0; double val = 0.0; for(long index = 0; index < width; index++) { t = (double)index/(double)(width-1); t = middle + (t- .5)*scale; val = filter(t, getSupport()); (*result)[index] = val; } return result; } ossim-Miami-2.9.1/src/imaging/ossimFilterResampler.cpp000066400000000000000000000630641352751253100230050ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // Contributor: // David A. Horner (DAH) http://dave.thehorners.com // //************************************************************************* // $Id: ossimFilterResampler.cpp 23586 2015-10-19 10:45:22Z gpotts $ #include #include #include #include #include #include #include #include #include using namespace std; ossimFilterResampler::ossimFilterResampler() :theMinifyFilter(new ossimNearestNeighborFilter()), theMagnifyFilter(new ossimNearestNeighborFilter()), theMinifyFilterType(ossimFilterResampler_NEAREST_NEIGHBOR), theMagnifyFilterType(ossimFilterResampler_NEAREST_NEIGHBOR), theScaleFactor(1.0, 1.0), theInverseScaleFactor(1.0, 1.0), theBlurFactor(1.0) { setScaleFactor(ossimDpt(1.0, 1.0)); loadState(ossimPreferences::instance()->preferencesKWL(),"resampler."); } ossimFilterResampler::~ossimFilterResampler() { if(theMinifyFilter) { delete theMinifyFilter; theMinifyFilter = NULL; } if(theMagnifyFilter) { delete theMagnifyFilter; theMagnifyFilter = NULL; } } void ossimFilterResampler::resample(const ossimRefPtr& input, ossimRefPtr& output, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length) { resample(input, output, output->getImageRectangle(), ul, ur, deltaUl, deltaUr, length); } void ossimFilterResampler::resample(const ossimRefPtr& input, ossimRefPtr& output, const ossimIrect& outputSubRect, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length) { if(!input.valid() || !output.valid() || !input->getBuf() || !output->getBuf()) { return; } ossimScalarType scalarType = input->getScalarType(); switch(scalarType) { case OSSIM_UINT8: { resampleBilinearTile(ossim_uint8(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_SINT8: { resampleBilinearTile(ossim_sint8(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { resampleBilinearTile(ossim_uint16(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_SINT16: { resampleBilinearTile(ossim_sint16(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_UINT32: { resampleBilinearTile(ossim_uint32(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_SINT32: { resampleBilinearTile(ossim_sint32(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { resampleBilinearTile(ossim_float32(0.0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { resampleBilinearTile(ossim_float64(0.0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimFilterResampler::resample error: unknown scalar type: " << scalarType << endl; } } } ossimFilter* ossimFilterResampler::createNewFilter( ossimFilterResamplerType filterType, ossimFilterResamplerType& result) { switch(filterType) { case ossimFilterResampler_NEAREST_NEIGHBOR: { return new ossimNearestNeighborFilter(); } case ossimFilterResampler_BOX: { return new ossimBoxFilter(); } case ossimFilterResampler_GAUSSIAN: { return new ossimGaussianFilter(); } case ossimFilterResampler_CUBIC: { return new ossimCubicFilter(); } case ossimFilterResampler_HANNING: { return new ossimHanningFilter(); } case ossimFilterResampler_HAMMING: { return new ossimHammingFilter(); } case ossimFilterResampler_LANCZOS: { return new ossimLanczosFilter(); } case ossimFilterResampler_CATROM: { return new ossimCatromFilter(); } case ossimFilterResampler_MITCHELL: { return new ossimMitchellFilter(); } case ossimFilterResampler_BLACKMAN: { return new ossimBlackmanFilter(); } case ossimFilterResampler_BLACKMAN_SINC: { return new ossimBlackmanSincFilter(); } case ossimFilterResampler_BLACKMAN_BESSEL: { return new ossimBlackmanBesselFilter(); } case ossimFilterResampler_QUADRATIC: { return new ossimQuadraticFilter(); } case ossimFilterResampler_TRIANGLE: { return new ossimTriangleFilter(); } case ossimFilterResampler_HERMITE: { return new ossimHermiteFilter(); } case ossimFilterResampler_BELL: { return new ossimGaussianFilter(); } case ossimFilterResampler_BSPLINE: { return new ossimBSplineFilter(); } case ossimFilterResampler_MAGIC: { return new ossimBSplineFilter(); } } result = ossimFilterResampler_NEAREST_NEIGHBOR; return new ossimNearestNeighborFilter(); } void ossimFilterResampler::setScaleFactor(const ossimDpt& scale) { theScaleFactor = scale; if(fabs(theScaleFactor.x) <= FLT_EPSILON) { theScaleFactor.x = 1.0; } if(fabs(theScaleFactor.y) <= FLT_EPSILON) { theScaleFactor.y = 1.0; } theInverseScaleFactor.x = 1.0/theScaleFactor.x; theInverseScaleFactor.y = 1.0/theScaleFactor.y; } template void ossimFilterResampler::resampleBilinearTile( T /* dummy */, const ossimRefPtr& input, ossimRefPtr& output, const ossimIrect& outputSubRect, const ossimDpt& inputUl, const ossimDpt& inputUr, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& outLength) { #if 0 /* Please leave for debug. */ std::cout << "INPUT = \n" << *input << std::endl << "OUTPUT = \n" << *output << std::endl << "inputUL= " << inputUl << std::endl << "inputUR= " << inputUr << std::endl << "deltaUL= " << deltaUl << std::endl << "deltaUr= " << deltaUr << std::endl << "outlength= " << outLength << std::endl; #endif ossim_uint32 band, centerOffset; ossim_float64 tmpFlt64, stepSizeWidth; if(outLength.x>1) { stepSizeWidth = 1.0/(outLength.x-1.0); } else { stepSizeWidth = 1.0; } // INPUT INFORMATION ossim_uint32 inWidth = input->getWidth(); ossim_uint32 inBandSize = input->getSizePerBand(); // fix for out-of-bounds check OLK 06/2005 ossim_uint32 BANDS = input->getNumberOfBands(); ossimIrect inputRect = input->getImageRectangle(); // OUTPUT INFORMATION const ossim_float64* NULL_PIX = output->getNullPix(); const ossim_float64* MIN_PIX = output->getMinPix(); const ossim_float64* MAX_PIX = output->getMaxPix(); ossimIrect outputRect = output->getImageRectangle(); ossim_uint32 resultRectH = outputSubRect.height(); ossim_uint32 resultRectW = outputSubRect.width(); ossim_uint32 outputRectW = outputRect.width(); // calculate the offset into the data so we can refer to it at 0 index. ossim_uint32 resultOffset=(outputSubRect.ul().y - outputRect.ul().y)*outputRectW + (outputSubRect.ul().x - outputRect.ul().x); // make a local copy of the band pointers (at resultOffset) ossim_float64 *densityvals=new ossim_float64[BANDS]; ossim_float64 *pixelvals=new ossim_float64[BANDS]; const T* *inputBuf = new const T*[BANDS]; T* *resultBuf = new T*[BANDS]; if(!pixelvals||!inputBuf||!resultBuf) { return; } for(band = 0; band < BANDS; ++band) { inputBuf[band] = static_cast(input->getBuf(band)); resultBuf[band] = static_cast(output->getBuf(band))+resultOffset; } // FILTER INFORMAION ossim_uint32 xkernel_width = theFilterTable.getWidth();; ossim_uint32 ykernel_height = theFilterTable.getHeight(); double xkernel_half_width = theFilterTable.getXSupport(); double ykernel_half_height = theFilterTable.getYSupport(); double initialx = inputUl.x-inputRect.ul().x; double initialy = inputUl.y-inputRect.ul().y; double terminalx = inputUr.x-inputRect.ul().x; double terminaly = inputUr.y-inputRect.ul().y; double pointx,pointy,deltaX,deltaY; ossim_int32 starty,startx; if(xkernel_width==0 || ykernel_height==0) { // USING NEAREST NEIGHBOR for(ossim_uint32 resultY = 0; resultY < resultRectH; ++resultY) { // deltaX = (terminalx-initialx) * stepSizeWidth; // deltaY = (terminaly-initialy) * stepSizeHeight; // this should be stepsize width for both since we are traversing horizontal deltaX = (terminalx-initialx) * stepSizeWidth; deltaY = (terminaly-initialy) * stepSizeWidth; pointx = initialx; pointy = initialy; for(ossim_uint32 resultX = 0; resultX < resultRectW; ++resultX) { // just sample center in input space. centerOffset = ossim::round(pointy)*inWidth + ossim::round(pointx); for(band=0;band(pointy - ykernel_half_height + .5); startx = ossim::round(pointx - xkernel_half_width + .5); centerOffset = ossim::round(pointy)*inWidth + ossim::round(pointx); sourceIndex = starty*inWidth+startx; // look at center pixel, make sure they aren't all null. nullCount=0; if(centerOffset(NULL_PIX[band])) { ++nullCount; } } // the center of the kernel is outside the input space, just set null. } else { nullCount=BANDS; } // make sure we have non-null data and we fit within the inputBuf. if ( nullCount==BANDS || (sourceIndex>=inBandSize)) { // we don't need to continue, just assign null! for (band=0;band(NULL_PIX[band]); } } else { kernel = theFilterTable.getClosestWeights(pointx,pointy); if(kernel) { // reset the pixel/density sums for each band to zero. memset(densityvals,'\0',sizeof(ossim_float64)*BANDS); memset(pixelvals,'\0',sizeof(ossim_float64)*BANDS); // apply kernel to input space. for (iy=0;((iy=inBandSize) { break; } } sourceIndex+=(inWidth-xkernel_width); } // actually assign the value to the output for (band = 0; band < BANDS; ++band) { if(densityvals[band]<=FLT_EPSILON) { //--- // Setting tempFlt64 to pixelvals[band] causing 0's where -32768 // should be when null check was skipped above. // tmpFlt64 = pixelvals[band]; //--- tmpFlt64 = NULL_PIX[band]; } else { // normalize tmpFlt64 = pixelvals[band]/densityvals[band]; } // clamp tmpFlt64 = (tmpFlt64>=MIN_PIX[band]?(tmpFlt64(tmpFlt64); } // we didn't get a filter kernel, just set NULL in this disaster. } else { for (band=0;band(NULL_PIX[band]); } } } pointy += deltaY; pointx += deltaX; } // End of loop in x direction. // increment pointers to where we are now. for(band=0;band& filterTypes)const { filterTypes.push_back("nearest neighbor"); filterTypes.push_back("bilinear"); filterTypes.push_back("cubic"); // filterTypes.push_back("bell"); filterTypes.push_back("bessel"); filterTypes.push_back("blackman"); filterTypes.push_back("box"); filterTypes.push_back("bspline"); filterTypes.push_back("catrom"); filterTypes.push_back("gaussian"); filterTypes.push_back("hanning"); filterTypes.push_back("hamming"); filterTypes.push_back("hermite"); filterTypes.push_back("lanczos"); filterTypes.push_back("mitchell"); filterTypes.push_back("quadratic"); filterTypes.push_back("sinc"); filterTypes.push_back("magic"); } ossimFilterResampler::ossimFilterResamplerType ossimFilterResampler::getFilterType(const ossimString& type)const { ossimString typeUpper = type; typeUpper = typeUpper.upcase(); if(typeUpper.contains("BOX")) { return ossimFilterResampler_BOX; } else if(typeUpper.contains("NEAREST")) { return ossimFilterResampler_NEAREST_NEIGHBOR; } else if(typeUpper.contains("GAUSSIAN")) { return ossimFilterResampler_GAUSSIAN; } else if(typeUpper.contains("HANNING")) { return ossimFilterResampler_HANNING; } else if(typeUpper.contains("HAMMING")) { return ossimFilterResampler_HAMMING; } else if(typeUpper.contains("LANCZOS")) { return ossimFilterResampler_LANCZOS; } else if(typeUpper.contains("MITCHELL")) { return ossimFilterResampler_MITCHELL; } else if(typeUpper.contains("CATROM")) { return ossimFilterResampler_CATROM; } else if(typeUpper.contains("CUBIC")) { return ossimFilterResampler_CUBIC; } else if(typeUpper.contains("BESSEL")) { return ossimFilterResampler_BLACKMAN_BESSEL; } else if(typeUpper.contains("SINC")) { return ossimFilterResampler_BLACKMAN_SINC; } else if(typeUpper.contains("BLACKMAN")) { return ossimFilterResampler_BLACKMAN; } else if(typeUpper.contains("QUADRATIC")) { return ossimFilterResampler_QUADRATIC; } else if(typeUpper.contains("TRIANGLE")) { return ossimFilterResampler_TRIANGLE; } else if(typeUpper.contains("BILINEAR")) { return ossimFilterResampler_TRIANGLE; } else if(typeUpper.contains("HERMITE")) { return ossimFilterResampler_HERMITE; } // else if(typeUpper.contains("BELL")) // { // return ossimFilterResampler_BELL; // } else if(typeUpper.contains("BSPLINE")) { return ossimFilterResampler_BSPLINE; } else if(typeUpper.contains("MAGIC")) { return ossimFilterResampler_MAGIC; } return ossimFilterResampler_NEAREST_NEIGHBOR; } void ossimFilterResampler::getKernelSupport(double& x, double& y)const { const ossimFilter* horizontalFilter = getHorizontalFilter(); const ossimFilter* verticalFilter = getVerticalFilter(); if(!horizontalFilter) { x = 0.0; } else { // x = theBlurFactor*ossim::max(1.0/theScaleFactor.x, 1.0)* // horizontalFilter->getSupport(); x = horizontalFilter->getSupport(); } if(!verticalFilter) { y = 0.0; } else { // y = theBlurFactor*ossim::max(1.0/theScaleFactor.y, 1.0)* // verticalFilter->getSupport(); y = verticalFilter->getSupport(); } } const ossimFilter* ossimFilterResampler::getHorizontalFilter()const { if(theScaleFactor.x < 1) { return theMinifyFilter; } return theMagnifyFilter; } const ossimFilter* ossimFilterResampler::getVerticalFilter()const { if(theScaleFactor.y < 1) { return theMinifyFilter; } return theMagnifyFilter; } void ossimFilterResampler::setFilterType(const ossimString& type) { setFilterType(type, type); } void ossimFilterResampler::setFilterType(ossimFilterResamplerType filterType) { setFilterType(filterType, filterType); } void ossimFilterResampler::setFilterType(const ossimString& minifyType, const ossimString& magnifyType) { setFilterType(getFilterType(minifyType), getFilterType(magnifyType)); } void ossimFilterResampler::setMinifyFilterType(const ossimString& minifyType) { setMinifyFilterType(getFilterType(minifyType)); } void ossimFilterResampler::setMagnifyFilterType(const ossimString& magnifyType) { setMagnifyFilterType(getFilterType(magnifyType)); } void ossimFilterResampler::setMinifyFilterType(ossimFilterResamplerType filterType) { setFilterType(filterType, theMagnifyFilterType); } void ossimFilterResampler::setMagnifyFilterType(ossimFilterResamplerType filterType) { setFilterType(theMinifyFilterType,filterType); } ossimString ossimFilterResampler::getMinifyFilterTypeAsString()const { return getFilterTypeAsString(theMinifyFilterType); } ossimString ossimFilterResampler::getMagnifyFilterTypeAsString()const { return getFilterTypeAsString(theMagnifyFilterType); } void ossimFilterResampler::setFilterType( ossimFilterResamplerType minifyFilterType, ossimFilterResamplerType magnifyFilterType) { if(theMinifyFilter) { delete theMinifyFilter; theMinifyFilter = NULL; } if(theMagnifyFilter) { delete theMagnifyFilter; theMagnifyFilter = NULL; } theMinifyFilterType = minifyFilterType; theMagnifyFilterType = magnifyFilterType; theMinifyFilter = createNewFilter(minifyFilterType, theMinifyFilterType); theMagnifyFilter = createNewFilter(magnifyFilterType, theMagnifyFilterType); computeTable(); } ossim_float64 ossimFilterResampler::getBlurFactor()const { return theBlurFactor; } void ossimFilterResampler::setBlurFactor(ossim_float64 blur) { theBlurFactor = blur; } bool ossimFilterResampler::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::SCALE_X_KW, theScaleFactor.x, true); kwl.add(prefix, ossimKeywordNames::SCALE_Y_KW, theScaleFactor.y, true); kwl.add(prefix, "minify_type", getFilterTypeAsString(theMinifyFilterType), true); kwl.add(prefix, "magnify_type", getFilterTypeAsString(theMagnifyFilterType), true); return true; } bool ossimFilterResampler::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = 0; lookup = kwl.find(prefix, ossimKeywordNames::SCALE_X_KW); if (lookup) { theScaleFactor.x = ossimString(lookup).toDouble(); } lookup = kwl.find(prefix, ossimKeywordNames::SCALE_Y_KW); if (lookup) { theScaleFactor.y = ossimString(lookup).toDouble(); } lookup = kwl.find(prefix, "minify_type"); if (lookup) { setMinifyFilterType(lookup); } lookup = kwl.find(prefix, "magnify_type"); if (lookup) { setMagnifyFilterType(lookup); } if(fabs(theScaleFactor.x) <= FLT_EPSILON) { theScaleFactor.x = 1.0; } if(fabs(theScaleFactor.y) <= FLT_EPSILON) { theScaleFactor.y = 1.0; } theInverseScaleFactor.x = 1.0/theScaleFactor.x; theInverseScaleFactor.y = 1.0/theScaleFactor.y; return true; } void ossimFilterResampler::computeTable() { theFilterTable.buildTable(32, *theMagnifyFilter); } ossim-Miami-2.9.1/src/imaging/ossimFilterTable.cpp000066400000000000000000000070111352751253100220700ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //---------------------------------------------------------------------------- // $Id: ossimFilterTable.cpp 23604 2015-10-28 13:40:09Z gpotts $ #include #include #include ossimFilterTable::ossimFilterTable() :theWeights(0), theWidth(0), theHeight(0), theWidthHeight(0), theXSupport(0), theYSupport(0), theFilterSteps(0) { } ossimFilterTable::~ossimFilterTable() { if(theWeights) { delete [] theWeights; theWeights = 0; } } void ossimFilterTable::buildTable(ossim_uint32 filterSteps, const ossimFilter& filter) { buildTable(filterSteps, filter, filter); } void ossimFilterTable::buildTable(ossim_uint32 filterSteps, const ossimFilter& xFilter, const ossimFilter& yFilter) { ossim_int32 subpixelSample=0; ossim_int32 subpixelLine=0; double dx = 0.0; double dy = 0.0; double kernelH = 0.0; double kernelV = 0.0; double x = 0; double y = 0; double xsupport = ceil(xFilter.getSupport()); double ysupport = ceil(yFilter.getSupport()); double left = 0; double right = 0; double top = 0; double bottom = 0; theXSupport = (ossim_uint32)xsupport; theYSupport = (ossim_uint32)ysupport; theFilterSteps = filterSteps; theWidth = (2*theXSupport); theHeight = (2*theYSupport); theWidthHeight = theWidth*theHeight; allocateWeights(); left = -(xsupport-1); right = xsupport; top = -(ysupport-1); bottom = ysupport; ossim_uint32 idx = 0; for (subpixelLine = 0; subpixelLine < (int)filterSteps; subpixelLine++) { // Calculate subpixel sample step. // ---------------------------------- dy = subpixelLine / (double)(filterSteps); for (subpixelSample = 0; subpixelSample < (int)filterSteps; subpixelSample++) { // Calculate subpixel sample step. // ---------------------------------- dx = subpixelSample / (double)(filterSteps); for (kernelV=top; kernelV<=bottom; kernelV++) { y = kernelV - dy; double tempWeight = yFilter.filter(y, yFilter.getSupport()); for(kernelH=left; kernelH<=right;++kernelH) { x = kernelH - dx; // Get the weight for the current pixel. // ---------------------------------------- theWeights[idx] = tempWeight*xFilter.filter(x, xFilter.getSupport()); ++idx; } } } } } ossim_uint32 ossimFilterTable::getWidthByHeight()const { return theWidthHeight; } ossim_uint32 ossimFilterTable::getXSupport()const { return theXSupport; } ossim_uint32 ossimFilterTable::getYSupport()const { return theYSupport; } ossim_uint32 ossimFilterTable::getWidth()const { return theWidth; } ossim_uint32 ossimFilterTable::getHeight()const { return theHeight; } void ossimFilterTable::allocateWeights() { if(theWeights) { delete [] theWeights; theWeights = 0; } ossim_uint32 size = (theWidthHeight*(theFilterSteps*theFilterSteps)); if(size) { theWeights = new double[size]; } }ossim-Miami-2.9.1/src/imaging/ossimFixedTileCache.cpp000066400000000000000000000172701352751253100225040ustar00rootroot00000000000000//****************************************************************** // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This file contains the Application cache algorithm // //*********************************** // $Id: ossimFixedTileCache.cpp 16276 2010-01-06 01:54:47Z gpotts $ #include #include using namespace std; ossimFixedTileCache::ossimFixedTileCache() : theTileBoundaryRect(), theTileSize(), theBoundaryWidthHeight(), theTilesHorizontal(0), theTilesVertical(0), theCacheSize(0), theMaxCacheSize(0), theTileMap(), theLruQueue(), theUseLruFlag(true) { ossim::defaultTileSize(theTileSize); ossimIrect tempRect; tempRect.makeNan(); setRect(tempRect); // theCacheSize = 0; // theMaxCacheSize = 0; // theUseLruFlag = true; } ossimFixedTileCache::~ossimFixedTileCache() { flush(); } void ossimFixedTileCache::setRect(const ossimIrect& rect) { { std::lock_guard lock(theMutex); ossim::defaultTileSize(theTileSize); theTileBoundaryRect = rect; theTileBoundaryRect.stretchToTileBoundary(theTileSize); theBoundaryWidthHeight.x = theTileBoundaryRect.width(); theBoundaryWidthHeight.y = theTileBoundaryRect.height(); theTilesHorizontal = theBoundaryWidthHeight.x/theTileSize.x; theTilesVertical = theBoundaryWidthHeight.y/theTileSize.y; } flush(); } void ossimFixedTileCache::setRect(const ossimIrect& rect, const ossimIpt& tileSize) { { std::lock_guard lock(theMutex); theTileBoundaryRect = rect; theTileSize = tileSize; theTileBoundaryRect.stretchToTileBoundary(theTileSize); theBoundaryWidthHeight.x = theTileBoundaryRect.width(); theBoundaryWidthHeight.y = theTileBoundaryRect.height(); theTilesHorizontal = theBoundaryWidthHeight.x/theTileSize.x; theTilesVertical = theBoundaryWidthHeight.y/theTileSize.y; } flush(); } void ossimFixedTileCache::keepTilesWithinRect(const ossimIrect& rect) { std::lock_guard lock(theMutex); std::map::iterator tileIter = theTileMap.begin(); while(tileIter != theTileMap.end()) { ossimIrect tileRect = (*tileIter).second.theTile->getImageRectangle(); if(!tileRect.intersects(rect)) { eraseFromLru(computeId((*tileIter).second.theTile->getOrigin())); theCacheSize -= (*tileIter).second.theTile->getDataSizeInBytes(); (*tileIter).second.theTile = NULL; theTileMap.erase(tileIter); } ++tileIter; } } ossimRefPtr ossimFixedTileCache::addTile(ossimRefPtr imageData, bool duplicateData) { std::lock_guard lock(theMutex); ossimRefPtr result = NULL; if(!imageData.valid()) { return result; } if(!imageData->getBuf()) { return result; } ossim_int32 id = computeId(imageData->getOrigin()); if(id < 0) { return result; } std::map::iterator tileIter = theTileMap.find(id); if(tileIter==theTileMap.end()) { if(duplicateData) { result = (ossimImageData*)imageData->dup(); } else { result = imageData; } ossimFixedTileCacheInfo cacheInfo(result, id); theCacheSize += imageData->getDataSizeInBytes(); theTileMap.insert(make_pair(id, cacheInfo)); if(theUseLruFlag) { theLruQueue.push_back(id); } } return result; } ossimRefPtr ossimFixedTileCache::getTile(ossim_int32 id) { std::lock_guard lock(theMutex); ossimRefPtr result = NULL; std::map::iterator tileIter = theTileMap.find(id); if(tileIter!=theTileMap.end()) { result = (*tileIter).second.theTile; adjustLru(id); } return result; } ossimIpt ossimFixedTileCache::getTileOrigin(ossim_int32 tileId) { std::lock_guard lock(theMutex); ossimIpt result; result.makeNan(); if(tileId < 0) { return result; } ossim_int32 ty = (tileId/theTilesHorizontal); ossim_int32 tx = (tileId%theTilesVertical); ossimIpt ul = theTileBoundaryRect.ul(); result = ossimIpt(ul.x + tx*theTileSize.x, ul.y + ty*theTileSize.y); return result; } ossim_int32 ossimFixedTileCache::computeId(const ossimIpt& tileOrigin)const { ossimIpt idDiff = tileOrigin - theTileBoundaryRect.ul(); if((idDiff.x < 0)|| (idDiff.y < 0)|| (idDiff.x >= theBoundaryWidthHeight.x)|| (idDiff.y >= theBoundaryWidthHeight.y)) { return -1; } ossim_uint32 y = idDiff.y/theTileSize.y; y*=theTilesHorizontal; ossim_uint32 x = idDiff.x/theTileSize.x; return (y + x); } void ossimFixedTileCache::deleteTile(ossim_int32 tileId) { std::map::iterator tileIter = theTileMap.find(tileId); if(tileIter != theTileMap.end()) { if((*tileIter).second.theTile.valid()) { theCacheSize -= (*tileIter).second.theTile->getDataSizeInBytes(); (*tileIter).second.theTile = NULL; } theTileMap.erase(tileIter); eraseFromLru(tileId); } } ossimRefPtr ossimFixedTileCache::removeTile(ossim_int32 tileId) { std::lock_guard lock(theMutex); ossimRefPtr result = NULL; std::map::iterator tileIter = theTileMap.find(tileId); if(tileIter != theTileMap.end()) { theCacheSize -= (*tileIter).second.theTile->getDataSizeInBytes(); if((*tileIter).second.theTile.valid()) { result = (*tileIter).second.theTile; } theTileMap.erase(tileIter); eraseFromLru(tileId); } return result; } void ossimFixedTileCache::flush() { std::lock_guard lock(theMutex); std::map::iterator tileIter = theTileMap.begin(); while(tileIter != theTileMap.end()) { if( (*tileIter).second.theTile.valid()) { (*tileIter).second.theTile = 0; } ++tileIter; } theLruQueue.clear(); theTileMap.clear(); theCacheSize = 0; } void ossimFixedTileCache::deleteTile() { std::lock_guard lock(theMutex); if(theUseLruFlag) { if(theLruQueue.begin() != theLruQueue.end()) { deleteTile(*(theLruQueue.begin())); } } } ossimRefPtr ossimFixedTileCache::removeTile() { std::lock_guard lock(theMutex); if(theUseLruFlag) { if(theLruQueue.begin() != theLruQueue.end()) { return removeTile(*(theLruQueue.begin())); } } return NULL; } void ossimFixedTileCache::adjustLru(ossim_int32 id) { if(theUseLruFlag) { std::list::iterator iter = std::find(theLruQueue.begin(), theLruQueue.end(), id); if(iter != theLruQueue.end()) { ossim_int32 value = *iter; theLruQueue.erase(iter); theLruQueue.push_back(value); } } } void ossimFixedTileCache::eraseFromLru(ossim_int32 id) { if(theUseLruFlag) { std::list::iterator iter = std::find(theLruQueue.begin(), theLruQueue.end(), id); if(iter != theLruQueue.end()) { theLruQueue.erase(iter); } } } void ossimFixedTileCache::setTileSize(const ossimIpt& tileSize) { setRect(theTileBoundaryRect, tileSize); } ossim-Miami-2.9.1/src/imaging/ossimFusionCombiner.cpp000066400000000000000000000143211352751253100226170ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: implementation for base fusion // //************************************************************************* // $Id: ossimFusionCombiner.cpp 13312 2008-07-27 01:26:52Z gpotts $ #include #include RTTI_DEF1(ossimFusionCombiner, "ossimFusionCombiner", ossimImageCombiner); ossimFusionCombiner::ossimFusionCombiner() :ossimImageCombiner(NULL, 2, 0, true, false), theTile(NULL), theNormTile(NULL), theNormIntensity(NULL), theInputConnection(NULL), theIntensityConnection(NULL) { } ossimFusionCombiner::ossimFusionCombiner(ossimObject* owner) :ossimImageCombiner(owner, 2, 0, true, false), theTile(NULL), theNormTile(NULL), theNormIntensity(NULL), theInputConnection(NULL), theIntensityConnection(NULL) {} ossimFusionCombiner::~ossimFusionCombiner() { theInputConnection = NULL; theIntensityConnection = NULL; } ossimIrect ossimFusionCombiner::getBoundingRect(ossim_uint32 resLevel) const { ossimIrect result; ossimIrect colorRect; result.makeNan(); if(theIntensityConnection) { result = theIntensityConnection->getBoundingRect(resLevel); } if(theInputConnection) { colorRect = theInputConnection->getBoundingRect(resLevel); if(theIntensityConnection) { result = result.clipToRect(colorRect); } else { result = colorRect; } } return result; } bool ossimFusionCombiner::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const { return ((inputIndex<2)&& (PTR_CAST(ossimImageSource, object)||!object)); } ossimScalarType ossimFusionCombiner::getOutputScalarType() const { if(theInputConnection) { return theInputConnection->getOutputScalarType(); } return ossimImageCombiner::getOutputScalarType(); } ossimRefPtr ossimFusionCombiner::getNormIntensity( const ossimIrect& rect, ossim_uint32 resLevel) { if(theIntensityConnection) { ossimRefPtr data = theIntensityConnection->getTile(rect, resLevel); if(data.valid() && data->getBuf()) { if(!theNormIntensity.valid()) { theNormIntensity = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT, data->getNumberOfBands(), rect.width(), rect.height()); theNormIntensity->initialize(); } theNormIntensity->setImageRectangleAndBands(rect, data->getNumberOfBands()); data->copyTileToNormalizedBuffer((float*)theNormIntensity->getBuf()); theNormIntensity->setDataObjectStatus(data->getDataObjectStatus()); return theNormIntensity; } } return ossimRefPtr(); } ossimRefPtr ossimFusionCombiner::getNormTile( const ossimIrect& rect, ossim_uint32 resLevel) { if(theInputConnection) { ossimRefPtr data = theInputConnection->getTile(rect, resLevel); if(data.valid() && data->getBuf()) { // make sure the tile result is updated if changed. // if((data->getNumberOfBands() != theTile->getNumberOfBands())|| (data->getScalarType() != theTile->getScalarType())) { theTile = ossimImageDataFactory::instance()->create(this, theInputConnection); theTile->initialize(); } if(!theNormTile.valid()) { theNormTile = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT, data->getNumberOfBands(), rect.width(), rect.height()); theNormTile->initialize(); } else if(theNormTile->getNumberOfBands() != data->getNumberOfBands()) { theNormTile = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT, data->getNumberOfBands(), rect.width(), rect.height()); theNormTile->initialize(); } theNormTile->setImageRectangleAndBands(rect, data->getNumberOfBands()); data->copyTileToNormalizedBuffer((float*)theNormTile->getBuf()); theNormTile->setDataObjectStatus(data->getDataObjectStatus()); return theNormTile; } } return ossimRefPtr(); } void ossimFusionCombiner::initialize() { ossimImageCombiner::initialize(); theInputConnection = PTR_CAST(ossimImageSource, getInput(0)); theIntensityConnection = PTR_CAST(ossimImageSource, getInput(1)); if(getInput(0)&&getInput(1)) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(0)); ossimImageSource* temp2 = PTR_CAST(ossimImageSource, getInput(1)); if(temp&&temp2) { if((temp->getNumberOfOutputBands()==1)&& (temp2->getNumberOfOutputBands()!=1)) { theIntensityConnection = PTR_CAST(ossimImageSource, getInput(0)); theInputConnection = PTR_CAST(ossimImageSource, getInput(1)); } } } if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, theInputConnection); theTile->initialize(); } } ossim-Miami-2.9.1/src/imaging/ossimGammaRemapper.cpp000066400000000000000000000167121352751253100224210ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // //************************************************************************* // $Id: ossimGammaRemapper.cpp 12980 2008-06-04 00:50:33Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimGammaRemapper, "ossimGammaRemapper", ossimImageSourceFilter) static const char GAMMA_KW[] = "gamma"; const ossim_float64 ossimGammaRemapper::MIN_GAMMA=0.0001; const ossim_float64 ossimGammaRemapper::MAX_GAMMA=10.0; const ossim_float64 ossimGammaRemapper::DEFAULT_GAMMA = 1.0; static ossimTrace traceDebug("ossimGammaRemapper:debug"); ossimGammaRemapper::ossimGammaRemapper() : m_gamma(DEFAULT_GAMMA), m_dirtyFlag(true) { } ossimGammaRemapper::ossimGammaRemapper(const double &gamma) : m_gamma(gamma), m_dirtyFlag(true) { } ossimGammaRemapper::~ossimGammaRemapper() { } ossimRefPtr ossimGammaRemapper::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr result = 0; if ( theInputConnection ) { ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if(!m_tile||!m_tile->getBuf()) { allocate(); } if (!m_tile || ossim::almostEqual(m_gamma, 0.0)) return inputTile; m_tile->setImageRectangle(tileRect); m_tile->makeBlank(); if ( !inputTile.valid() || (inputTile->getDataObjectStatus() == OSSIM_NULL) || (inputTile->getDataObjectStatus() == OSSIM_EMPTY) ) { //--- // Since the filter is enabled, return theTile which is of the // correct scalar type. //--- return m_tile; } if (m_dirtyFlag) { computeLookup(); } if(!m_lookupTable.empty()) { calculateGammaWithLookup(inputTile); } else { calculateGamma(inputTile); } m_tile->validate(); result = m_tile; } return result; } void ossimGammaRemapper::calculateGammaWithLookup(ossimRefPtr inputTile) { switch(inputTile->getScalarType()) { case OSSIM_UINT8: { calculateGammaWithLookupTemplate(inputTile, (ossim_uint8)0); break; } case OSSIM_UINT9: case OSSIM_UINT11: case OSSIM_UINT12: case OSSIM_UINT13: case OSSIM_UINT14: case OSSIM_UINT15: case OSSIM_UINT16: { calculateGammaWithLookupTemplate(inputTile, (ossim_uint16)0); break; } default: { break; } } } template void ossimGammaRemapper::calculateGammaWithLookupTemplate(ossimRefPtr inputTile, T /*dummy*/) { T* input = reinterpret_cast(inputTile->getBuf()); T* output = reinterpret_cast(m_tile->getBuf()); T nullPix = static_cast(inputTile->getNullPix(0)); ossim_uint32 nValues = inputTile->getNumberOfBands()*inputTile->getImageRectangle().area(); ossim_uint32 idx = 0; ossim_float32* table = &m_lookupTable.front(); if(inputTile->getDataObjectStatus() == OSSIM_PARTIAL) { for(idx = 0; idx < nValues; ++idx,++input,++output) { if(*input != nullPix) { *output = table[*input]; } } } else { for(idx = 0; idx < nValues; ++idx,++input,++output) { *output = table[*input]; } } } void ossimGammaRemapper::calculateGamma(ossimRefPtr inputTile) { m_normalizedTile->setImageRectangle(inputTile->getImageRectangle()); m_normalizedTile->makeBlank(); ossim_float64 minPix = ossim::defaultMin(OSSIM_NORMALIZED_FLOAT); ossim_float64 maxPix = ossim::defaultMax(OSSIM_NORMALIZED_FLOAT); ossim_float64 delta = maxPix; inputTile->copyTileToNormalizedBuffer(reinterpret_cast(m_normalizedTile->getBuf())); ossim_float32* input = reinterpret_cast(m_normalizedTile->getBuf()); ossim_uint32 idx = 0; ossim_float64 v = 0.0; ossim_uint32 nValues = m_normalizedTile->getNumberOfBands()*inputTile->getImageRectangle().area(); if(inputTile->getDataObjectStatus() == OSSIM_PARTIAL) { for(idx = 0; idx < nValues; ++idx,++input) { if(*input != 0.0) { v = std::pow(*input, m_gamma)*delta; if(v > maxPix) v = maxPix; if(v < minPix) v = minPix; *input = v; } } } else { for(idx = 0; idx < nValues; ++idx,++input) { v = std::pow(*input, m_gamma)*delta; if(v > maxPix) v = maxPix; if(v < minPix) v = minPix; *input = v; } } m_tile->copyNormalizedBufferToTile(reinterpret_cast(m_normalizedTile->getBuf())); m_tile->validate(); } void ossimGammaRemapper::initialize() { ossimImageSourceFilter::initialize(); m_tile = 0; m_dirtyFlag = true; m_lookupTable.clear(); } void ossimGammaRemapper::allocate() { m_tile = ossimImageDataFactory::instance()->create(this,this); if(m_tile.valid()) { m_tile->initialize(); m_normalizedTile = new ossimImageData(0, OSSIM_NORMALIZED_FLOAT, m_tile->getNumberOfBands(), m_tile->getWidth(), m_tile->getHeight()); m_normalizedTile->initialize(); } } void ossimGammaRemapper::computeLookup() { ossim_uint32 nValues=0; ossimScalarType scalarType = getOutputScalarType(); switch(scalarType) { case OSSIM_UINT8: case OSSIM_UINT9: case OSSIM_UINT11: case OSSIM_UINT12: case OSSIM_UINT13: case OSSIM_UINT14: case OSSIM_UINT15: case OSSIM_UINT16: { nValues = ossim::defaultMax(scalarType)+1; } default: { break; } } if(nValues) { ossim_uint32 idx = 0; ossim_float64 maxPix = nValues-1; ossim_float64 outputMaxPix = getMaxPixelValue(); ossim_float64 outputMinPix = getMinPixelValue(); ossim_float64 v = 0.0; m_lookupTable.resize(nValues); for(idx = 0; idx < m_lookupTable.size();++idx) { ossim_float64 input = static_cast(idx)/maxPix; v = std::pow(input, m_gamma)*maxPix; if(v > outputMaxPix) v = outputMaxPix; if(v < outputMinPix) v = outputMinPix; m_lookupTable[idx] = v; } } m_dirtyFlag = false; } bool ossimGammaRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimImageSourceFilter::loadState(kwl, prefix); ossimString lookup = kwl.find(prefix, GAMMA_KW); if(!lookup.empty()) { setGamma(lookup.toFloat64()); } return result; } bool ossimGammaRemapper::saveState(ossimKeywordlist& kwl, const char* prefix) { bool result = ossimImageSourceFilter::saveState(kwl, prefix); kwl.add(prefix, GAMMA_KW, getGamma(), true); return result; } void ossimGammaRemapper::setGamma(const double& gamma) { m_gamma = gamma; if(m_gamma < MIN_GAMMA) m_gamma = MIN_GAMMA; if(m_gamma > MAX_GAMMA) m_gamma = MAX_GAMMA; m_dirtyFlag = true; } ossimString ossimGammaRemapper::getShortName() const { return ossimString("Gamma Remapper"); } ossim-Miami-2.9.1/src/imaging/ossimGeneralRasterInfo.cpp000066400000000000000000001064221352751253100232530ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // Contains class definition for ossimGeneralRasterInfo //******************************************************************* // $Id: ossimGeneralRasterInfo.cpp 23645 2015-12-04 13:17:34Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include #include #include static const ossimKeyword NUMBER_LINES("number_lines", "Number of lines in the raster image."); static const ossimKeyword NUMBER_SAMPLES("number_samples", "Number of samples in the raster image."); static const ossimKeyword VALID_START_LINE("valid_start_line", "First valid line of raster image(zero based)."); static const ossimKeyword VALID_STOP_LINE("valid_stop_line", "Last valid line of raster image(zero based)."); static const ossimKeyword VALID_START_SAMPLE("valid_start_sample", "First valid sample of raster image(zero based)."); static const ossimKeyword VALID_STOP_SAMPLE("valid_stop_sample", "Last valid sample of raster image(zero based)."); static const ossimKeyword SUB_IMAGE_OFFSET_LINE( "sub_image_offset_line", "Pixel line offset of sub-image in the full-image pixel space."); static const ossimKeyword SUB_IMAGE_OFFSET_SAMP( "sub_image_offset_samp", "Pixel sample offset of sub-image in the full-image pixel space."); static const ossimKeyword HEADER_SIZE("header_size", "Header size in bytes."); static const ossimKeyword SET_NULLS("set_fill_to_nulls_mode", "0 = do nothing to pixels,\n1 = all zeroes to min values,\ \n2 = zeroes to null on edges only."); static const ossimKeyword PIXELS_TO_CHOP("pixels_to_chop", "Amount of pixels to chop from edge."); static const ossimInterleaveTypeLut INTERLEAVE_TYPE_LUT; static ossimTrace traceDebug("ossimGeneralRasterInfo:debug"); ossimGeneralRasterInfo::ossimGeneralRasterInfo() : theMetaData(), theImageFileList(), theInterleaveType(OSSIM_BIL), theRawImageRect(), theValidImageRect(), theImageRect(), theSubImageOffset(0,0), theHeaderSize(0), theSetNullsMode(NONE), thePixelsToChop(0), theImageDataByteOrder(OSSIM_LITTLE_ENDIAN) { theRawImageRect.makeNan(); theValidImageRect.makeNan(); theImageRect.makeNan(); } ossimGeneralRasterInfo::ossimGeneralRasterInfo(const std::vector& imageFileList, ossimScalarType pixelType, ossimInterleaveType il_type, ossim_int32 numberOfBands, ossim_int32 lines, ossim_int32 samples, ossim_int32 headerSize, ossimFillMode nullsMode, ossim_int32 pixelsToChop) : theMetaData(pixelType, numberOfBands), theImageFileList(imageFileList), theInterleaveType(il_type), theRawImageRect(0,0,0,0), theValidImageRect(0,0,0,0), theImageRect(0,0,0,0), theSubImageOffset(0,0), theHeaderSize(headerSize), theSetNullsMode(nullsMode), thePixelsToChop(pixelsToChop), theImageDataByteOrder(OSSIM_LITTLE_ENDIAN) { theRawImageRect.set_lry(lines - 1); theRawImageRect.set_lrx(samples - 1); theValidImageRect = theRawImageRect; theImageRect = theRawImageRect; } ossimGeneralRasterInfo::ossimGeneralRasterInfo(const ossimKeywordlist& kwl, const char* prefix) : theImageFileList(), theInterleaveType(OSSIM_BIL), theRawImageRect(0,0,0,0), theValidImageRect(0,0,0,0), theImageRect(0,0,0,0), theSubImageOffset(0,0), theHeaderSize(0), theSetNullsMode(NONE), thePixelsToChop(0), theImageDataByteOrder(OSSIM_LITTLE_ENDIAN) { theRawImageRect.makeNan(); theValidImageRect.makeNan(); theImageRect.makeNan(); loadState(kwl, prefix); } ossimGeneralRasterInfo::ossimGeneralRasterInfo( const ossimGeneralRasterInfo& obj ) : theMetaData ( obj.theMetaData ), theImageFileList ( obj.theImageFileList ), theInterleaveType ( obj.theInterleaveType ), theRawImageRect ( obj.theRawImageRect ), theValidImageRect ( obj.theValidImageRect ), theImageRect ( obj.theImageRect ), theSubImageOffset ( obj.theSubImageOffset ), theHeaderSize ( obj.theHeaderSize ), theSetNullsMode ( obj.theSetNullsMode ), thePixelsToChop ( obj.thePixelsToChop ), theImageDataByteOrder ( obj.theImageDataByteOrder ) { } const ossimGeneralRasterInfo& ossimGeneralRasterInfo::operator=( const ossimGeneralRasterInfo& rhs ) { if ( this != &rhs ) { theMetaData = rhs.theMetaData; theImageFileList = rhs.theImageFileList; theInterleaveType = rhs.theInterleaveType; theRawImageRect = rhs.theRawImageRect; theValidImageRect = rhs.theValidImageRect; theImageRect = rhs.theImageRect; theSubImageOffset = rhs.theSubImageOffset; theHeaderSize = rhs.theHeaderSize; theSetNullsMode = rhs.theSetNullsMode; thePixelsToChop = rhs.thePixelsToChop; theImageDataByteOrder = rhs.theImageDataByteOrder; } return *this; } ossimGeneralRasterInfo::~ossimGeneralRasterInfo() { } void ossimGeneralRasterInfo::clear() { theMetaData.clear(); theImageFileList.clear(); theInterleaveType = OSSIM_BIL; theRawImageRect.makeNan(); theValidImageRect.makeNan(); theImageRect.makeNan(); theSubImageOffset.x = 0; theSubImageOffset.y = 0; theHeaderSize = 0; theSetNullsMode = NONE; thePixelsToChop = 0; theImageDataByteOrder = OSSIM_LITTLE_ENDIAN; } const ossimIrect& ossimGeneralRasterInfo::imageRect() const { return theImageRect; } const ossimIrect& ossimGeneralRasterInfo::validImageRect() const { return theValidImageRect; } const ossimIrect& ossimGeneralRasterInfo::rawImageRect() const { return theRawImageRect; } const ossimIpt& ossimGeneralRasterInfo::subImageOffset() const { return theSubImageOffset; } ossim_int32 ossimGeneralRasterInfo::headerSize() const { return theHeaderSize; } ossim_uint32 ossimGeneralRasterInfo::fillToNullsMode() const { return theSetNullsMode; } std::ostream& ossimGeneralRasterInfo::print(std::ostream& out) const { //--- // This will print in a keyword format that can be read by the constructor. // that takes a keyword list. //--- ossimKeywordlist kwl; saveState( kwl, 0 ); out << kwl << std::endl; return out; } void ossimGeneralRasterInfo::setFillToNullsMode(ossim_uint32 mode) { static const char MODULE[] = "ossimGeneralRasterInfo::setFillToNullMode"; if(mode < 3) { theSetNullsMode = (ossimFillMode)mode; } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nmode out of bounds(0 - 2): " << mode << std::endl << "\nmode has not been changed." << std::endl; } } ossim_int32 ossimGeneralRasterInfo::pixelsToChop() const { return thePixelsToChop; } ossimInterleaveType ossimGeneralRasterInfo::interleaveType() const { return theInterleaveType; } const std::vector& ossimGeneralRasterInfo::getImageFileList() const { return theImageFileList; } void ossimGeneralRasterInfo::setImageFileList(const std::vector& list) { theImageFileList = list; } void ossimGeneralRasterInfo::setImageFile(const ossimFilename& file) { theImageFileList.clear(); theImageFileList.push_back( file ); } void ossimGeneralRasterInfo::setImageDataByteOrder(ossimByteOrder byteOrder) { theImageDataByteOrder = byteOrder; } void ossimGeneralRasterInfo::setHeaderSize(ossim_int32 headerSize) { theHeaderSize = headerSize; } void ossimGeneralRasterInfo::setInterleaveType(ossimInterleaveType il_type) { theInterleaveType = il_type; } void ossimGeneralRasterInfo::setImageRect(const ossimIrect& imageRect) { theImageRect = imageRect; } void ossimGeneralRasterInfo::setValidImageRect(const ossimIrect &imageRect) { theValidImageRect = imageRect; } void ossimGeneralRasterInfo::setRawImageRect(const ossimIrect &imageRect) { theRawImageRect = imageRect; } void ossimGeneralRasterInfo::setSubImageOffset(const ossimIpt& d) { theSubImageOffset = d; } ossimByteOrder ossimGeneralRasterInfo::getImageDataByteOrder() const { return theImageDataByteOrder; } bool ossimGeneralRasterInfo::saveState(ossimKeywordlist& kwl, const char* prefix) const { for (ossim_uint32 i=0; i 1) { kwl.add(prefix, ossimKeywordNames::BYTE_ORDER_KW, (theImageDataByteOrder == OSSIM_LITTLE_ENDIAN ? "little_endian" : "big_endian"), true); } return true; } bool ossimGeneralRasterInfo::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimGeneralRasterInfo::loadState"; if ( traceDebug() ) { CLOG << "DEBUG: entered..." << "\nprefix: " << (prefix ? prefix : "") << "\nInput keyword list:\n" << kwl << std::endl; } bool result = false; //--- // Look for required and option keyword. Break from loop if required // keyword is not found. //--- while( 1 ) { // Check for errors in the ossimKeywordlist. if(kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << "Detected an error in the keywordlist: " << kwl << std::endl; } break; } std::string key; ossimString value; // Use for keyword list lookups. ossim_int32 lines = 0; ossim_int32 samples = 0; // Lines (required): key = NUMBER_LINES; value.string() = kwl.findKey( key ); // Required to have this. if ( value.size() ) { lines = value.toInt32(); if ( !lines ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << " ERROR:\n" << "Required number of lines is 0!" << std::endl; } break; } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << " ERROR:\n" << "Required keyword not found: " << key << std::endl; } break; } // Samples (required): key = NUMBER_SAMPLES; value.string() = kwl.findKey( key ); // Required to have this. if ( value.size() ) { samples = value.toInt32(); if ( !samples ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << " ERROR:\n" << "Required number of samples is 0!" << std::endl; } break; } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << " ERROR:\n" << "Required keyword not found: " << key << std::endl; } break; } // Bands ossimImageMetaData::loadState checks for required bands: if(!theMetaData.loadState(kwl, prefix)) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << " Error loading meta data!\n" << std::endl; } break; } // If we get here assign the rectangles: theRawImageRect = ossimIrect( 0, 0, samples - 1, lines - 1 ); theValidImageRect = theRawImageRect; theImageRect = theRawImageRect; int tmp = INTERLEAVE_TYPE_LUT.getEntryNumber(kwl); if (tmp == ossimLookUpTable::NOT_FOUND) { theInterleaveType = OSSIM_BIL; } else { theInterleaveType = static_cast(tmp); } // Get the image files. if (theInterleaveType != OSSIM_BSQ_MULTI_FILE) { // Look for "filename" first, then deprecated "image_file". key = ossimKeywordNames::FILENAME_KW; value.string() = kwl.findKey( key ); if ( value.empty() ) { // deprecated keyword... key = ossimKeywordNames::IMAGE_FILE_KW; value.string() = kwl.findKey( key ); } if ( value.size() ) { //--- // omd (ossim metadata) files can have just the base filename, e.g. image.ras, // in which case open will fail if not in the image dir. So only put it in // the list if it doesn't exits. //--- ossimFilename f = value; if ( f.exists() ) { theImageFileList.clear(); theImageFileList.push_back(ossimFilename(value)); } } if ( theImageFileList.empty() ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ERROR:\n" << "Required keyword not found: " << ossimKeywordNames::FILENAME_KW << std::endl; } break; } } else { // multiple file names. ossim_int32 count = 0; // look for image file key word with no number. // Required to have this. key = ossimKeywordNames::FILENAME_KW; value.string() = kwl.findKey( key ); if ( value.empty() ) { // deprecated keyword... key = ossimKeywordNames::IMAGE_FILE_KW; value.string() = kwl.findKey( key ); } if ( value.size() ) { theImageFileList.push_back(ossimFilename(value)); ++count; } ossim_int32 i = 0; while ( (count < numberOfBands()) && (i < 1000) ) { key = ossimKeywordNames::FILENAME_KW; key += ossimString::toString(i).string(); value.string() = kwl.findKey( key ); if ( value.empty() ) { // Lookup for deprecated keyword. key = ossimKeywordNames::IMAGE_FILE_KW; key += ossimString::toString(i).string(); value.string() = kwl.findKey( key ); } if ( value.size() ) { theImageFileList.push_back(ossimFilename(value)); ++count; } ++i; } if (count != numberOfBands()) // Error, count should equal bands! { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << " ERROR:\n" << "Required keyword not found: " << ossimKeywordNames::FILENAME_KW << "\nInterleave type is multi file; however," << " not enough were pick up!" << std::endl; } break; } } key = VALID_START_LINE; value.string() = kwl.findKey( key ); // Default is zero. if ( value.size() ) { theValidImageRect.set_uly( value.toInt32() ); } key = VALID_STOP_LINE; value.string() = kwl.findKey( key ); // Default is last line. if ( value.size() ) { theValidImageRect.set_lry( value.toInt32() ); } if (theValidImageRect.lr().y < theValidImageRect.ul().y) { ossimNotify(ossimNotifyLevel_WARN) << " ERROR:" << "\nValid stop line < start line." << "\nValid start line: " << theValidImageRect.ul().y << "\nValid stop line: " << theValidImageRect.lr().y << "\nError status has been set. Returning." << std::endl; break; } key = VALID_START_SAMPLE; value.string() = kwl.findKey( key ); // Default is zero. if ( value.size() ) { theValidImageRect.set_ulx( value.toInt32() ); } key = VALID_STOP_SAMPLE; value.string() = kwl.findKey( key ); // Default is last sample. if ( value.size() ) { theValidImageRect.set_lrx( value.toInt32() ); } if (theValidImageRect.lr().x < theValidImageRect.ul().x) { ossimNotify(ossimNotifyLevel_WARN) << " ERROR:" << "\nValid stop samp < start samp." << "\nValid start samp: " << theValidImageRect.ul().x << "\nValid stop samp: " << theValidImageRect.lr().x << "\nError status has been set. Returning." << std::endl; break; } theImageRect.set_lry(theValidImageRect.lr().y - theValidImageRect.ul().y); theImageRect.set_lrx(theValidImageRect.lr().x - theValidImageRect.ul().x); key = SUB_IMAGE_OFFSET_LINE; value.string() = kwl.findKey( key ); // Default is zero. if ( value.size() ) { theSubImageOffset.line = value.toInt32(); } key = SUB_IMAGE_OFFSET_SAMP; value.string() = kwl.findKey( key ); // Default is zero. if ( value.size() ) { theSubImageOffset.samp = atoi(value); } key = HEADER_SIZE; value.string() = kwl.findKey( key ); // Default is zero. if ( value.size() ) { theHeaderSize = value.toInt32(); } key = SET_NULLS; value.string() = kwl.findKey( key ); // Default is 2. if ( value.size() ) { int tmp; tmp = atoi(value); if ((tmp < 3) && (tmp > -1)) { theSetNullsMode = (ossimFillMode)tmp; } else { theSetNullsMode = ZEROES_TO_NULL_EDGES_ONLY; // 2 ossimNotify(ossimNotifyLevel_WARN) << " WARNING:" << "\nset_fill_to_nulls_mode value out of range." << "\nDefaulted to 2" << std::endl; } } key = PIXELS_TO_CHOP; value.string() = kwl.findKey( key ); // Default is zero. if ( value.size() ) { thePixelsToChop = value.toInt32(); } if (bytesPerPixel() > 1) { // get the byte order of the data. key = ossimKeywordNames::BYTE_ORDER_KW; value.string() = kwl.findKey( key ); if ( value.size() ) { ossimString s(value); if (s.trim() != "") // Check for empty string. { s.downcase(); if (s.contains("big")) { theImageDataByteOrder = OSSIM_BIG_ENDIAN; } else if(s.contains("little")) { theImageDataByteOrder = OSSIM_LITTLE_ENDIAN; } } } } // End of while forever loop. result = true; break; } // Matches: while (1) if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Exit status: " << (result?"true":"false") << std::endl; } return result; } // End: bool ossimGeneralRasterInfo::loadState bool ossimGeneralRasterInfo::open( const ossimFilename& imageFile ) { static const char MODULE[] = "ossimGeneralRasterInfo::open"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << "\nimageFile: " << imageFile << std::endl; } bool result = false; // Wipe any previous state slick. clear(); ossimFilename copyFile = imageFile; if ( !imageFile.exists() ) { copyFile = imageFile.expand(); } // Look for the headrer of omd file as they are written out by img2rr. ossimFilename hdr = copyFile; hdr.setExtension("hdr"); // image.hdr if ( !hdr.exists() ) { hdr = imageFile; hdr.string() += ".hdr"; // image.ras.hdr if ( ! hdr.exists() ) { hdr = imageFile; hdr.setExtension("xml"); // image.xml } } if ( hdr.exists() ) { if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "header file: " << hdr << std::endl; } ossimString ext = hdr.ext().downcase(); if ( ext == "hdr" ) { if ( ossimEnviHeader::isEnviHeader( hdr ) ) { result = initializeFromEnviHdr( hdr ); } else { result = initializeFromHdr( imageFile, hdr ); } if ( !result ) { // Could be an ossim meta data file: ossimKeywordlist kwl( hdr ); result = loadState( kwl, 0 ); } } else if ( ext == "xml" ) { result = initializeFromXml( imageFile, hdr ); } } //--- // Set the file name. Needed for ossimGeneralRasterTileSource::open. // Note set here above loadState call to stop loadState from returning // false if no image file found. //--- if ( theImageFileList.empty() ) { setImageFile( imageFile ); } ossimFilename omd = imageFile; omd.setExtension("omd"); // image.omd if ( !omd.exists() ) { omd.setExtension("kwl"); // image.kwl } if ( omd.exists() ) { if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "omd file: " << omd << std::endl; } ossimKeywordlist kwl( omd ); if ( result && theMetaData.getNumberOfBands() ) { //--- // Just update the band info in case it has min/max values from // a compute min/max scan. //--- theMetaData.updateMetaData( kwl, std::string("") ); } else { // We're not initialized yet so do a loadState: result = loadState( kwl, 0 ); } } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Exit status: " << (result?"true":"false") << std::endl; } return result; } bool ossimGeneralRasterInfo::initializeFromHdr( const ossimFilename& imageFile, const ossimFilename& headerFile ) { bool result = false; ossimKeywordlist kwl; char delimeter = ' '; kwl.change_delimiter(delimeter); if ( kwl.addFile(headerFile) ) { kwl.downcaseKeywords(); ossimString value; while( 1 ) { //--- // Go through the data members in order. // If a required item is not found break from loop. //-- theMetaData.clear(); // scalar ( default ) - adjusted below : theMetaData.setScalarType( OSSIM_UINT8 ); // Image file name: theImageFileList.clear(); theImageFileList.push_back( imageFile ); // interleave ( not required - default=BIL) theInterleaveType = OSSIM_BIL; value.string() = kwl.findKey( std::string("layout") ); if ( value.size() ) { ossimInterleaveTypeLut lut; ossim_int32 intrlv = lut.getEntryNumber( value.string().c_str(), true ); if ( intrlv != ossimLookUpTable::NOT_FOUND ) { theInterleaveType = static_cast(intrlv); } } // bands ( required ): ossim_uint32 bands = 0; value.string() = kwl.findKey( std::string("nbands") ); if ( value.size() ) { bands = value.toUInt32(); } if ( !bands ) { break; } theMetaData.setNumberOfBands( bands ); // lines ( required ): ossim_int32 lines = 0; value.string() = kwl.findKey( std::string("nrows") ); if ( value.size() ) { lines = value.toInt32(); } if ( !lines ) { break; } // samples ( required ): ossim_int32 samples = 0; value.string() = kwl.findKey( std::string("ncols") ); if ( value.size() ) { samples = value.toInt32(); } if ( !samples ) { break; } // nodata or null value ( not required ) value.string() = kwl.findKey( std::string("nodata") ); if ( value.empty() ) { value.string() = kwl.findKey( std::string("nodata_value") ); } if ( value.size() ) { ossim_float64 nullValue = value.toUInt32(); for ( ossim_uint32 band = 0; band < theMetaData.getNumberOfBands(); ++band ) { theMetaData.setNullPix( band, nullValue ); } theMetaData.setNullValuesValid(true); } // Set the rectangles: theRawImageRect = ossimIrect( 0, 0, samples - 1, lines - 1 ); theValidImageRect = theRawImageRect; theImageRect = theRawImageRect; // sample start ( not required ): theSubImageOffset.x = 0; // line start ( not required ): theSubImageOffset.y = 0; // header offset ( not required ): theHeaderSize = 0; // null mode: theSetNullsMode = ossimGeneralRasterInfo::NONE; // pixels to chop: thePixelsToChop = 0; // Byte order, ( not required - defaulted to system if not found. theImageDataByteOrder = ossim::byteOrder(); value.string() = kwl.findKey( std::string("byteorder") ); if ( value.size() ) { ossim_uint32 i = value.toUInt32(); if ( i == 0 ) { theImageDataByteOrder = OSSIM_LITTLE_ENDIAN; } else { theImageDataByteOrder = OSSIM_BIG_ENDIAN; } } // Pixel type used for scalar below: std::string pixelType = "N"; // not defined value.string() = kwl.findKey( std::string("pixeltype") ); if ( value.size() ) { pixelType = value.string(); } ossim_int32 nbits = -1; value.string() = kwl.findKey( std::string("nbits") ); if ( value.size() ) { nbits = value.toInt32(); } else { nbits = getBitsPerPixel( imageFile ); } switch( nbits ) { case 8: { theMetaData.setScalarType( OSSIM_UINT8 ); break; } case 16: { if (pixelType == "S") { theMetaData.setScalarType( OSSIM_SINT16 ); } else { theMetaData.setScalarType( OSSIM_UINT16 ); } break; } case 32: { if( pixelType == "S") { theMetaData.setScalarType( OSSIM_SINT32 ); } else if( pixelType == "F") { theMetaData.setScalarType( OSSIM_FLOAT32 ); } else { theMetaData.setScalarType( OSSIM_UINT32 ); } break; } default: { if( (nbits < 8) && (nbits >= 1 ) ) { theMetaData.setScalarType( OSSIM_UINT8 ); } break; } } result = true; break; // Trailing break to get out. } } return result; } // End: ossimGeneralRasterInfo::initializeFromHdr bool ossimGeneralRasterInfo::initializeFromEnviHdr( const ossimFilename& headerFile ) { bool result = false; ossimEnviHeader hdr; if( hdr.open( headerFile ) ) { result = initializeFromEnviHdr( hdr ); } return result; } bool ossimGeneralRasterInfo::initializeFromEnviHdr( const ossimEnviHeader& enviHdr ) { bool result = false; while( 1 ) { //--- // Go through the data members in order. // If a required item is not found break from loop. //-- theMetaData.clear(); // scalar ( required ) : if( enviHdr.getOssimScalarType() != OSSIM_SCALAR_UNKNOWN ) { theMetaData.setScalarType( enviHdr.getOssimScalarType() ); } else { break; } theImageFileList.clear(); // interleave ( required ): theInterleaveType = enviHdr.getOssimInterleaveType(); if ( theInterleaveType == OSSIM_INTERLEAVE_UNKNOWN ) { break; } // bands ( required ): if ( !enviHdr.getBands() ) { break; } theMetaData.setNumberOfBands( enviHdr.getBands() ); // lines ( required ): ossim_uint32 lines = enviHdr.getLines(); if ( !lines ) { break; } // samples ( required ): ossim_uint32 samples = enviHdr.getSamples(); if ( !samples ) { break; } // Set the rectangles: theRawImageRect = ossimIrect( 0, 0, samples - 1, lines - 1 ); theValidImageRect = theRawImageRect; theImageRect = theRawImageRect; // sample start ( not required ): theSubImageOffset.x = enviHdr.getXStart(); // line start ( not required ): theSubImageOffset.y = enviHdr.getYStart(); // header offset ( not required ): theHeaderSize = enviHdr.getHeaderOffset(); // null mode: theSetNullsMode = ossimGeneralRasterInfo::NONE; // pixels to chop: thePixelsToChop = 0; // Byte order, this will be system if not found. theImageDataByteOrder = enviHdr.getByteOrder(); result = true; break; // Trailing break to get out. } return result; } // End: ossimGeneralRasterInfo::initializeFromEnviHdr( const ossimEnviHeader& ) bool ossimGeneralRasterInfo::initializeFromXml( const ossimFilename& imageFile, const ossimFilename& headerFile ) { bool result = false; ossimFgdcXmlDoc file; if (file.open( headerFile )) { while( 1 ) { //--- // Go through the data members in order. // If a required item is not found break from loop. //-- theMetaData.clear(); // scalar ( default ) - adjusted below : theMetaData.setScalarType( OSSIM_UINT8 ); // Image file name: theImageFileList.clear(); theImageFileList.push_back( imageFile ); // interleave ( defaulted ): theInterleaveType = OSSIM_BIL; // bands ( required ): if ( !file.getNumberOfBands() ) { break; } theMetaData.setNumberOfBands( file.getNumberOfBands() ); ossimIpt size; if ( file.getImageSize(size) ) // Lines, samples not image file size. { // lines, samples ( required ): if ( !size.x || !size.y ) { break; } } else { break; } // Set the rectangles: theRawImageRect = ossimIrect( 0, 0, size.x - 1, size.y - 1 ); theValidImageRect = theRawImageRect; theImageRect = theRawImageRect; // sample start ( not required ): theSubImageOffset.x = 0; // line start ( not required ): theSubImageOffset.y = 0; // header offset ( not required ): theHeaderSize = 0; // null mode: theSetNullsMode = ossimGeneralRasterInfo::NONE; // pixels to chop: thePixelsToChop = 0; // Byte order *** need this ***, defaulting to system for now: theImageDataByteOrder = ossim::byteOrder(); // Adjust scalar if needed, note defaulted to 8 bit above: ossimString eainfo; file.getPath("/metadata/eainfo/detailed/enttyp/enttypd", eainfo); ossim_int32 numBits = 0; ossim_int64 fileSize = imageFile.fileSize(); // Image file size. ossim_int32 numBytes = fileSize / size.x / size.y / numberOfBands(); if( numBytes > 0 && numBytes != 3 ) { numBits = numBytes*8; } if( numBits == 16 ) { theMetaData.setScalarType( OSSIM_UINT16 ); } else if( numBits == 32 ) { if(eainfo.contains("float")) { theMetaData.setScalarType( OSSIM_FLOAT32 ); } else { theMetaData.setScalarType( OSSIM_UINT32 ); } } result = true; break; // Trailing break to get out. } } return result; } // End: ossimGeneralRasterInfo::initializeFromXml ossim_int32 ossimGeneralRasterInfo::getBitsPerPixel( const ossimFilename& imageFile ) const { // Note currently does not consider header size. ossim_int32 result = 0; ossim_int64 fileSize = imageFile.size(); ossimIpt rectSize = theRawImageRect.size(); if ( fileSize && rectSize.x && rectSize.y && numberOfBands() ) { result = ( fileSize / rectSize.x / rectSize.y / numberOfBands() ) * 8; } return result; } ossim-Miami-2.9.1/src/imaging/ossimGeneralRasterTileSource.cpp000066400000000000000000001351631352751253100244420ustar00rootroot00000000000000//******************************************************************* // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class definition for ossimGeneralRasterTileSource. //******************************************************************* #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1_INST(ossimGeneralRasterTileSource, "ossimGeneralRasterTileSource", ossimImageHandler) static ossimTrace traceDebug("ossimGeneralRasterTileSource:debug"); // For interleave type enum to string conversions. static const ossimInterleaveTypeLut ILUT; using namespace std; //******************************************************************* // Public Constructor: //******************************************************************* ossimGeneralRasterTileSource::ossimGeneralRasterTileSource() : ossimImageHandler(), m_tile(0), m_buffer(0), m_lineBuffer(0), m_bufferInterleave(OSSIM_BIL), m_fileStrList(0), m_rasterInfo(), m_bufferRect(0, 0, 0, 0), m_swapBytesFlag(false), m_bufferSizeInPixels(0), m_outputBandList(0) {} ossimGeneralRasterTileSource::~ossimGeneralRasterTileSource() { close(); } ossimRefPtr ossimGeneralRasterTileSource::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { if ( m_tile.valid() == false ) { allocateTile(); // First time through... } if (m_tile.valid()) { // Image rectangle must be set prior to calling getTile. m_tile->setImageRectangle(tile_rect); if ( getTile( m_tile.get(), resLevel ) == false ) { if (m_tile->getDataObjectStatus() != OSSIM_NULL) { m_tile->makeBlank(); } } } return m_tile; } bool ossimGeneralRasterTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) ) { //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0. Method returns true on success, false // on error. //--- status = getOverviewTile(resLevel, result); if (status) { if(getOutputScalarType() == OSSIM_USHORT11) { //--- // Temp fix: // The overview handler could return a tile of OSSIM_UINT16 if // the max sample value was not set to 2047. //--- result->setScalarType(OSSIM_USHORT11); } else if(getOutputScalarType() == OSSIM_USHORT12) { result->setScalarType(OSSIM_USHORT12); } else if(getOutputScalarType() == OSSIM_USHORT13) { result->setScalarType(OSSIM_USHORT13); } else if(getOutputScalarType() == OSSIM_USHORT14) { result->setScalarType(OSSIM_USHORT14); } else if(getOutputScalarType() == OSSIM_USHORT15) { result->setScalarType(OSSIM_USHORT15); } } if (!status) // Did not get an overview tile. { status = true; //--- // Subtract any sub image offset to get the zero based image space // rectangle. //--- ossimIrect tile_rect = result->getImageRectangle(); // This should be the zero base image rectangle for this res level. ossimIrect image_rect = getImageRectangle(resLevel); //--- // See if any point of the requested tile is in the image. //--- if ( tile_rect.intersects(image_rect) ) { // Make the tile rectangle zero base. result->setImageRectangle(tile_rect); // Initialize the tile if needed as we're going to stuff it. if (result->getDataObjectStatus() == OSSIM_NULL) { result->initialize(); } ossimIrect clip_rect = tile_rect.clipToRect(image_rect); if ( ! tile_rect.completely_within(m_bufferRect) ) { // A new buffer must be loaded. if ( !tile_rect.completely_within(clip_rect) ) { //--- // Start with a blank tile since the whole tile buffer will // not be // filled. //--- result->makeBlank(); } // Reallocate the buffer if needed. if ( m_bufferSizeInPixels != result->getSize() ) { allocateBuffer( result ); } ossimIpt size(static_cast(result->getWidth()), static_cast(result->getHeight())); if( !fillBuffer(clip_rect.ul(), size) ) { ossimNotify(ossimNotifyLevel_WARN) << "Error from fill buffer..." << std::endl; //--- // Error in filling buffer. //--- setErrorStatus(); status = false; } } result->loadTile(m_buffer, m_bufferRect, clip_rect, m_bufferInterleave); result->validate(); // Set the rectangle back. result->setImageRectangle(tile_rect); } else // No intersection. { result->makeBlank(); } } } return status; } bool ossimGeneralRasterTileSource::fillBuffer(const ossimIpt& origin, const ossimIpt& size) { static const char MODULE[] = "ossimGeneralRasterTileSource::fillBuffer"; // Note: InterleaveType enumerations in "constants.h" file. bool status = false; switch ( m_rasterInfo.interleaveType() ) { case OSSIM_BIP: { status = fillBIP(origin, size); break; } case OSSIM_BIL: { status = fillBIL(origin, size); break; } case OSSIM_BSQ: { status = fillBSQ(origin, size); break; } case OSSIM_BSQ_MULTI_FILE: { status = fillBsqMultiFile(origin, size); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << " Unsupported interleave type: " << ILUT.getEntryString(m_rasterInfo.interleaveType()) << std::endl; } } if (status && m_swapBytesFlag) { ossimEndian oe; oe.swap(m_rasterInfo.getImageMetaData().getScalarType(), m_buffer, m_bufferSizeInPixels); } return status; } bool ossimGeneralRasterTileSource::fillBIP(const ossimIpt& origin, const ossimIpt& size ) { static const char MODULE[] = "ossimGeneralRasterTileSource::fillBIP "; m_bufferRect.set_ul(origin); m_bufferRect.set_lry(min( (origin.y + size.y -1), m_rasterInfo.imageRect().lr().y)); m_bufferRect.set_lrx(min( (origin.x + size.x -1), m_rasterInfo.imageRect().lr().x)); const ossim_int32 WIDTH = static_cast( m_bufferRect.width() ); const ossim_int32 HEIGHT = static_cast( m_bufferRect.height() ); const ossim_int32 INPUT_BANDS = m_rasterInfo.numberOfBands(); const ossim_int32 OUTPUT_BANDS = static_cast( m_outputBandList.size() ); const ossim_int32 BYTES_PER_PIXEL = m_rasterInfo.bytesPerPixel(); const ossim_int32 INPUT_BYTES_PER_SAMPLE = BYTES_PER_PIXEL * INPUT_BANDS; const ossim_int32 OUTPUT_BYTES_PER_SAMPLE = BYTES_PER_PIXEL * OUTPUT_BANDS; // Seek position. std::streamoff rasterOffset = m_rasterInfo.offsetToFirstValidSample() + origin.y * m_rasterInfo.bytesPerRawLine() + origin.x * INPUT_BYTES_PER_SAMPLE; // Input line buffer, all bands. std::streamsize inputLineBufferWidth = WIDTH * INPUT_BYTES_PER_SAMPLE; // Output buffer width: std::streamsize outputLineBufferWidth = WIDTH * OUTPUT_BYTES_PER_SAMPLE; #if 0 /* Please keep for debug. (drb) */ ossimNotify(ossimNotifyLevel_DEBUG) << "\nDEBUG:" << "\norigin: " << origin << "\nSeek position: " << rasterOffset << "\ninputLineBufferWidth: " << inputLineBufferWidth << "\noutputLineBufferWidth: " << outputLineBufferWidth << "\nINPUT_BANDS: " << INPUT_BANDS << "\nOUTPUT_BANDS: " << OUTPUT_BANDS << std::endl; #endif ossim_int32 bufferOffset = 0; // Line loop: ossim_int32 currentLine = 0; while ( currentLine < HEIGHT ) { // Seek to line. m_fileStrList[0]->seekg(rasterOffset, ios::beg); if (!(*m_fileStrList[0])) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << " Seek error! Returning with error..." << std::endl; return false; } // Read image data from line for all bands into line buffer. m_fileStrList[0]->read( (char*)m_lineBuffer, inputLineBufferWidth ); if ( m_fileStrList[0]->gcount() != inputLineBufferWidth ) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << "\nERROR: Reading image line." << std::endl; return false; } // Sample loop: for ( ossim_int32 sample = 0; sample < WIDTH; ++sample ) { // Band loop: for ( ossim_int32 band = 0; band < OUTPUT_BANDS; ++band ) { ossim_int32 selectedBand = static_cast(m_outputBandList[band]); memcpy( (void*)(m_buffer + bufferOffset + sample * OUTPUT_BYTES_PER_SAMPLE + band * BYTES_PER_PIXEL), (void*)(m_lineBuffer + sample * INPUT_BYTES_PER_SAMPLE + selectedBand * BYTES_PER_PIXEL), BYTES_PER_PIXEL ); } } ++currentLine; bufferOffset += outputLineBufferWidth; rasterOffset += m_rasterInfo.bytesPerRawLine(); } return true; } // End: bool ossimGeneralRasterTileSource::fillBipBandSelect(... bool ossimGeneralRasterTileSource::fillBIL(const ossimIpt& origin, const ossimIpt& size) { static const char MODULE[] = "ossimGeneralRasterTileSource::fillBIL"; //*** // This will fill a buffer the full width of valid samples * tileHeight(). //*** m_bufferRect.set_ul(origin); m_bufferRect.set_lry(min((origin.y + size.y - 1), m_rasterInfo.imageRect().lr().y)); m_bufferRect.set_lrx(min((origin.x + size.x - 1), m_rasterInfo.imageRect().lr().x)); ossim_sint64 currentLine = origin.y; // Bytes in one line all bands. const std::streamoff LINE_OFFSET = m_rasterInfo.bytesPerRawLine() * m_rasterInfo.numberOfBands(); // Start seek position. std::streamoff offset = ( m_rasterInfo.offsetToFirstValidSample() + currentLine * LINE_OFFSET + origin.x * m_rasterInfo.bytesPerPixel() ); //--- // Loop through and process lines. //--- ossim_int32 linesProcessed = 0; std::streamsize buffer_width = m_bufferRect.width() * m_rasterInfo.bytesPerPixel(); ossim_uint8* buf = m_buffer; #if 0 /* Please leave for debug. (drb) */ ossimNotify(ossimNotifyLevel_DEBUG) << "\nDEBUG:" << "\norigin: " << origin << "\nSeek position: " << offset << "\nStarting line number: " << currentLine << "\nbuffer_width: " << buffer_width << std::endl; #endif // Line loop: while ((currentLine <= static_cast(m_rasterInfo.imageRect().lr().y)) && linesProcessed < size.y) { // Band loop: std::vector::const_iterator i = m_outputBandList.begin(); while ( i != m_outputBandList.end() ) { ossim_int64 band = static_cast( (*i) ); const std::streamoff bandOffset = band * m_rasterInfo.bytesPerRawLine(); // Seek to line. m_fileStrList[0]->seekg(offset + bandOffset, ios::beg); if (!m_fileStrList[0]) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << " Seek error! Returning with error..." << std::endl; return false; } // Read the line of image data. m_fileStrList[0]->read( (char*)buf, buffer_width ); if ( m_fileStrList[0]->gcount() != buffer_width ) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << "\nERROR: Reading image line." << "\ncurrentLine: " << currentLine << std::endl; return false; } buf += buffer_width; ++i; } // End of band loop. ++linesProcessed; ++currentLine; offset += LINE_OFFSET; } // End: line loop return true; } //******************************************************************* // Private Method: //******************************************************************* bool ossimGeneralRasterTileSource::fillBSQ(const ossimIpt& origin, const ossimIpt& size) { static const char MODULE[] = "ossimGeneralRasterTileSource::fillBSQ"; // This will fill a buffer the full width of valid samples * tileHeight(). m_bufferRect.set_ul(origin); m_bufferRect.set_lry(min((origin.y + size.y -1), m_rasterInfo.imageRect().lr().y)); m_bufferRect.set_lrx(min((origin.x + size.x - 1), m_rasterInfo.imageRect().lr().x)); // Start seek position. std::streamoff startSeekPosition = m_rasterInfo.offsetToFirstValidSample() + origin.y * m_rasterInfo.bytesPerRawLine() + origin.x * m_rasterInfo.bytesPerPixel(); std::streamsize buffer_width = m_bufferRect.width() * m_rasterInfo.bytesPerPixel(); ossim_uint8* buf = (ossim_uint8*)m_buffer; std::streamoff bandOffset = m_rasterInfo.bytesPerRawLine() * m_rasterInfo.rawLines(); #if 0 /* Please leave for debug. (drb) */ ossimNotify(ossimNotifyLevel_DEBUG) << "\nDEBUG:" << "\norigin: " << origin << "\nSeek position: " << startSeekPosition << "\nStarting line number: " << origin.y << "\nbuffer_width: " << buffer_width << "\nbytesPerRawLine(): " << m_rasterInfo.bytesPerRawLine() << "\nm_rasterInfo.offsetToFirstValidSample(): " << m_rasterInfo.offsetToFirstValidSample() << "\nbandOffset: " << bandOffset << std::endl; #endif ossim_int32 num_bands = m_rasterInfo.numberOfBands(); ossim_int32 height = size.y; // Band loop: for (ossim_int32 band = 0; band < num_bands; ++band) { ossim_sint64 currentLine = origin.y; ossim_sint64 linesProcessed = 0; std::streamoff offset = startSeekPosition + (band * bandOffset); // Line loop: while (currentLine <= m_rasterInfo.imageRect().lr().y && linesProcessed < height) { // Seek to line. m_fileStrList[0]->seekg(offset, ios::beg); if (!m_fileStrList[0]) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << " Seek error! Returning with error..." << std::endl; return false; } // Read the line of image data. m_fileStrList[0]->read( (char*)buf, buffer_width ); if ( m_fileStrList[0]->gcount() != buffer_width ) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << "\nERROR: Reading image line." << "\ncurrentLine: " << currentLine << std::endl; return false; } // Increment everybody accordingly. buf += buffer_width; offset += m_rasterInfo.bytesPerRawLine(); ++linesProcessed; ++currentLine; } // End of line loop. } // End of band loop. return true; } //******************************************************************* // Private Method: //******************************************************************* bool ossimGeneralRasterTileSource::fillBsqMultiFile(const ossimIpt& origin, const ossimIpt& size) { static const char MODULE[] = "ossimGeneralRasterTileSource::fillBsqMultiFile"; if (traceDebug()) CLOG << " Entered..." << std::endl; // This will fill a buffer the full width of valid samples * tileHeight(). m_bufferRect.set_ul(origin); m_bufferRect.set_lry(min((origin.y + size.y -1), m_rasterInfo.imageRect().lr().y)); m_bufferRect.set_lrx(min((origin.x + size.x - 1), m_rasterInfo.imageRect().lr().x)); //--- // Start seek position. //--- std::streamoff startSeekPosition = m_rasterInfo.offsetToFirstValidSample() + origin.y * m_rasterInfo.bytesPerRawLine() + origin.x * m_rasterInfo.bytesPerPixel(); //--- // Loop through and process lines. //--- std::streamsize buffer_width = m_bufferRect.width() * m_rasterInfo.bytesPerPixel(); ossim_uint8* buf = (ossim_uint8*)m_buffer; #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nDEBUG:" << "\norigin: " << origin << "\nSeek position: " << startSeekPosition << "\nStarting line number: " << origin.y << "\nbuffer_width: " << buffer_width << "\nbuffer_rect: " << m_bufferRect << "\nbytesPerRawLine(): " << m_rasterInfo.bytesPerRawLine() << "\nm_rasterInfo.offsetToFirstValidSample(): " << m_rasterInfo.offsetToFirstValidSample() << std::endl; } #endif // ossim_int32 num_bands = m_rasterInfo.numberOfBands(); std::vector::const_iterator bandIter = m_outputBandList.begin(); while ( bandIter != m_outputBandList.end() ) { ossim_int32 currentLine = origin.y; ossim_int32 linesProcessed = 0; ossim_int64 offset = startSeekPosition; while (currentLine <= m_rasterInfo.imageRect().lr().y && linesProcessed < size.y) { //--- // Seek to line. //--- m_fileStrList[ *bandIter ]->seekg(offset, ios::beg); if ( !m_fileStrList[ *bandIter ] ) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << " Seek error! Returning with error..." << std::endl; return false; } //--- // Read the line of image data. //--- m_fileStrList[ *bandIter ]->read((char*)buf, buffer_width); if ( m_fileStrList[ *bandIter ]->gcount() != buffer_width) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << "\nERROR: Reading image line." << "\ncurrentLine: " << currentLine << std::endl; return false; } // Increment everybody accordingly. buf += buffer_width; offset += m_rasterInfo.bytesPerRawLine(); ++linesProcessed; ++currentLine; } // End of line loop. ++bandIter; // Next band... } // End: while ( bandIter ! = m_outputBandList.end() ) return true; } //******************************************************************* // Public method: //******************************************************************* bool ossimGeneralRasterTileSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Our stuff: m_rasterInfo.saveState(kwl, prefix); // Base class: bool result = ossimImageHandler::saveState(kwl, prefix); if ( result && isBandSelector() && m_outputBandList.size() ) { if ( isIdentityBandList( m_outputBandList ) == false ) { // If we're not identity output the bands. ossimString bandsString; ossim::toSimpleStringList(bandsString, m_outputBandList); kwl.add(prefix, ossimKeywordNames::BANDS_KW, bandsString, true); } } return result; } //******************************************************************* // Public method: //******************************************************************* bool ossimGeneralRasterTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; m_outputBandList.clear(); if ( ossimImageHandler::loadState(kwl, prefix) ) { // Set the band list if key is present. std::string pfx = ( prefix ? prefix : "" ); std::string key = ossimKeywordNames::BANDS_KW; ossimString value; value.string() = kwl.findKey( pfx, key ); if ( value.size() ) { ossim::toSimpleVector( m_outputBandList, value ); } result = open(); } return result; } //******************************************************************* // Public method: //******************************************************************* ossimScalarType ossimGeneralRasterTileSource::getOutputScalarType() const { return m_rasterInfo.getImageMetaData().getScalarType(); } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimGeneralRasterTileSource::getTileWidth() const { ossim_uint32 result = 0; if ( m_tile.valid() ) { m_tile->getWidth(); } else { ossimIpt tileSize; ossim::defaultTileSize(tileSize); result = tileSize.x; } return result; } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimGeneralRasterTileSource::getTileHeight() const { ossim_uint32 result = 0; if ( m_tile.valid() ) { m_tile->getHeight(); } else { ossimIpt tileSize; ossim::defaultTileSize(tileSize); result = tileSize.y; } return result; } //******************************************************************* // Public method: //******************************************************************* bool ossimGeneralRasterTileSource::isValidRLevel(ossim_uint32 reduced_res_level) const { static const char MODULE[] = "ossimGeneralRasterTileSource::isValidRLevel"; if (reduced_res_level == 0) { return true; } else if (theOverview.valid()) { return theOverview->isValidRLevel(reduced_res_level); } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Invalid reduced_res_level: " << reduced_res_level << "\nHighest available: " << (getNumberOfDecimationLevels() - 1) << std::endl; return false; } } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimGeneralRasterTileSource::getNumberOfLines(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return m_rasterInfo.validLines(); } else if (theOverview.valid()) { return theOverview->getNumberOfLines(reduced_res_level); } return 0; } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimGeneralRasterTileSource::getNumberOfSamples( ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return m_rasterInfo.validSamples(); } else if (theOverview.valid()) { return theOverview->getNumberOfSamples(reduced_res_level); } return 0; } double ossimGeneralRasterTileSource::getNullPixelValue(ossim_uint32 band) const { return m_rasterInfo.getImageMetaData().getNullPix(band); } double ossimGeneralRasterTileSource::getMinPixelValue(ossim_uint32 band)const { return m_rasterInfo.getImageMetaData().getMinPix(band); } double ossimGeneralRasterTileSource::getMaxPixelValue(ossim_uint32 band)const { return m_rasterInfo.getImageMetaData().getMaxPix(band); } bool ossimGeneralRasterTileSource::open() { static const char MODULE[] = "ossimGeneralRasterTileSource::open"; if (traceDebug()) CLOG << " Entered..." << std::endl; bool result = false; if(isOpen()) { close(); } //--- // Find the header file: // // We need lines, samples, bands, scalar and interleave at a minimum: // // A general raster image requires a keyword list to get essential image // information or meta data as its sometimes called. The meta data file // can have four types of extensions: ".omd", ".hdr", ".kwl" and xml. // Look for them in that order. // Note that the ".omd" extension is for "Ossim Meta Data" and was made // up to avoid conflicting with other software packages ".hdr" files. //--- if ( m_rasterInfo.open( theImageFile ) ) { theMetaData = m_rasterInfo.getImageMetaData(); result = initializeHandler(); if ( result ) { completeOpen(); if ( isBandSelector() && m_outputBandList.size() && ( isIdentityBandList( m_outputBandList ) == false ) ) { // This does range checking and will pass to overview if open. setOutputBandList( m_outputBandList ); } } } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Exit status: " << (result?"true":"false") << std::endl; } return result; } bool ossimGeneralRasterTileSource::open( const ossimGeneralRasterInfo& info ) { if( isOpen() ) { close(); } m_rasterInfo = info; bool result = initializeHandler(); if ( result ) { completeOpen(); if ( isBandSelector() && m_outputBandList.size() && ( isIdentityBandList( m_outputBandList ) == false ) ) { // This does range checking and will pass to overview if open. setOutputBandList( m_outputBandList ); } } return result; } bool ossimGeneralRasterTileSource::initializeHandler() { //--- // This private method assumes that "m_rasterInfo" object has been // initialized. Note that "close() should have already been called if // there was an open file prior to this. //--- std::vector aList = m_rasterInfo.getImageFileList(); for (ossim_uint32 i=0; i is = ossim::StreamFactoryRegistry::instance()-> createIstream(f); // check the stream... if( is ) { // Check the file stream. if ( is->fail() ) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << "ossimGeneralRasterTileSource::open" << " ERROR:\n" << "Cannot open: " << f.c_str() << std::endl; is = 0; return false; } } // Check the file size (removed). m_fileStrList.push_back(is); // Add it to the list... } if ((aList.size()==1) && theImageFile.empty()) { theImageFile = aList[0]; } // Set the buffer interleave type. m_bufferInterleave = m_rasterInfo.interleaveType(); if (m_bufferInterleave == OSSIM_BSQ_MULTI_FILE) { m_bufferInterleave = OSSIM_BSQ; } if ( m_outputBandList.empty() ) { // Set starting output band list to identity. ossimImageSource::getOutputBandList( m_outputBandList ); } //--- // Get the byte order of the image data and host machine. If different, // set the swap bytes flag... //--- if (m_rasterInfo.getImageDataByteOrder() != ossim::byteOrder()) { m_swapBytesFlag = true; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeneralRasterTileSource::initializeHandler()" << " DEBUG:" << "\nScalar type: " << ossimScalarTypeLut::instance()-> getEntryString(m_rasterInfo.getImageMetaData().getScalarType()) << "\nByte swapping is " << (m_swapBytesFlag?"enabled.":"not enabled.") // << "\nm_bufferSizeInPixels: " << m_bufferSizeInPixels // << "\nbuffer size: " << buffer_size << "\nRasterInfo:\n"; m_rasterInfo.print(ossimNotify(ossimNotifyLevel_DEBUG)); } return true; } bool ossimGeneralRasterTileSource::isOpen() const { bool result = false; if (m_fileStrList.size() > 0) { if( m_fileStrList[0] ) { result = !(m_fileStrList[0]->fail()); } } return result; } void ossimGeneralRasterTileSource::close() { ossimImageHandler::close(); // base class m_tile = 0; // Not a leak, ref ptr. if ( m_buffer ) { delete [] m_buffer; m_buffer = 0; m_bufferSizeInPixels = 0; // Must zero out for check in getTile method. } if ( m_lineBuffer ) { delete [] m_lineBuffer; m_lineBuffer = 0; } std::vector< shared_ptr >::iterator is = m_fileStrList.begin(); while (is != m_fileStrList.end()) { (*is) = 0; ++is; } m_fileStrList.clear(); } ossim_uint32 ossimGeneralRasterTileSource::getImageTileWidth() const { return 0; } ossim_uint32 ossimGeneralRasterTileSource::getImageTileHeight() const { return 0; } ossimString ossimGeneralRasterTileSource::getShortName()const { return ossimString("ossim_raster"); } ossimString ossimGeneralRasterTileSource::getLongName()const { return ossimString("general raster reader"); } ossim_uint32 ossimGeneralRasterTileSource::getNumberOfInputBands() const { return m_rasterInfo.getImageMetaData().getNumberOfBands(); } ossim_uint32 ossimGeneralRasterTileSource::getNumberOfOutputBands() const { ossim_uint32 result = 0; if ( isBandSelector() && m_outputBandList.size() ) { result = (ossim_uint32)m_outputBandList.size(); } else { result = m_rasterInfo.getImageMetaData().getNumberOfBands(); } return result; } ossimKeywordlist ossimGeneralRasterTileSource::getHdrInfo(ossimFilename hdrFile) { ossimKeywordlist kwl; char delimeter = ' '; kwl.change_delimiter(delimeter); kwl.addFile(hdrFile); kwl.downcaseKeywords(); ossimKeywordlist geoKwl; ossim_uint32 lines = 0; ossim_uint32 samples = 0; ossim_float32 noData = -9999; ossimString scalarType = "ossim_uint8"; ossim_int32 numBands = 1; // ossim_int32 skipBytes = 0; ossim_int32 numBits = -1; ossimString chPixelType = "N"; // not defined ossimString interleaveType = "BIL"; ossimString byteOrder; bool noDataFound = false; const char* lookup = kwl.find("ncols"); if (lookup) { samples = ossimString(lookup).toUInt32(); geoKwl.add(ossimKeywordNames::NUMBER_SAMPLES_KW, samples); } lookup = kwl.find("nrows"); if (lookup) { lines = ossimString(lookup).toUInt32(); geoKwl.add(ossimKeywordNames::NUMBER_LINES_KW, lines); } // lookup = kwl.find("skipbytes"); // if (lookup) // { // skipBytes = ossimString(lookup).toInt(); // } lookup = kwl.find("nbands"); if (lookup) { numBands = ossimString(lookup).toInt(); } lookup = kwl.find("nodata"); if (lookup) { noData = ossimString(lookup).toFloat32(); noDataFound = true; } lookup = kwl.find("nodata_value"); if (lookup) { noData = ossimString(lookup).toFloat32(); noDataFound = true; } lookup = kwl.find("nbits"); if (lookup) { numBits = ossimString(lookup).toInt(); } lookup = kwl.find("pixeltype"); if (lookup) { chPixelType = ossimString(lookup); } lookup = kwl.find("layout"); if (lookup) { interleaveType = ossimString(lookup); } lookup = kwl.find("byteorder"); if (lookup) { byteOrder = ossimString(lookup); } if (numBits == -1) { FILE* fp; ossim_int64 size = 0; fp = fopen(theImageFile.c_str(), "r"); if (fp != 0) { fseek(fp, 0, SEEK_END); size = ftell(fp); } fclose(fp); if (lines > 0 && samples > 0) { ossim_int32 numBytes = size/samples/lines/numBands; if( numBytes > 0 && numBytes != 3 ) { numBits = numBytes*8; if( numBytes == 4 ) { chPixelType = "F"; } } } } if( numBits == 16 ) { if (chPixelType == "S") { scalarType = "ossim_sint16"; } else { scalarType = "ossim_uint16"; // default } } else if( numBits == 32 ) { if( chPixelType == "S") { scalarType = "ossim_sint32"; } else if( chPixelType == "F") { scalarType = "ossim_float32"; } else { scalarType = "ossim_uint32"; // default } } else if( numBits == 8 ) { scalarType = "ossim_uint8"; numBits = 8; } else if( numBits < 8 && numBits >= 1 ) { scalarType = "ossim_uint8"; } else if(numBits == -1) { if( chPixelType == "F") { scalarType = "ossim_float32"; numBits = 32; } else { scalarType = "ossim_uint8"; numBits = 8; } } if (noDataFound) { for (ossim_int32 i = 0; i < numBands; i++) { ossimString prefix = "band" + ossimString::toString(i+1) + ": "; geoKwl.add(prefix, ossimKeywordNames::NULL_VALUE_KW, noData); } } geoKwl.add(ossimKeywordNames::NUMBER_BANDS_KW, numBands); geoKwl.add(ossimKeywordNames::SCALAR_TYPE_KW, scalarType); geoKwl.add(ossimKeywordNames::INTERLEAVE_TYPE_KW, interleaveType); return geoKwl; } ossimKeywordlist ossimGeneralRasterTileSource::getXmlInfo(ossimFilename xmlFile) { ossimKeywordlist kwl; ossimFgdcXmlDoc file; if (file.open(xmlFile)) { ossimString scalarType = "ossim_uint8"; ossim_int32 numBits = -1; ossimString interleaveType = "BIL"; ossimIpt size; ossim_int32 samples = 0; ossim_int32 lines = 0; if (file.getImageSize(size)) { samples = size.x; lines = size.y; } if (samples > 0) { kwl.add(ossimKeywordNames::NUMBER_SAMPLES_KW, samples); } if (lines > 0) { kwl.add(ossimKeywordNames::NUMBER_LINES_KW, lines); } ossim_int32 bands = file.getNumberOfBands(); if (bands > 0) { kwl.add(ossimKeywordNames::NUMBER_BANDS_KW, bands); } else { if (samples > 0 && lines > 0)//if there is no bands info but samples and lines info, default number of bands to 1 { bands = 1; kwl.add(ossimKeywordNames::NUMBER_BANDS_KW, bands); } } ossimString eainfo; file.getPath("/metadata/eainfo/detailed/enttyp/enttypd", eainfo); if (numBits == -1) { if ( (lines > 0) && (samples > 0) && (bands > 0) ) { ossim_int64 size = theImageFile.fileSize(); ossim_int32 numBytes = size/samples/lines/bands; if( numBytes > 0 && numBytes != 3 ) { numBits = numBytes*8; } } } if( numBits == 16 ) { scalarType = "ossim_uint16"; // default } else if( numBits == 32 ) { if(eainfo.contains("float")) { scalarType = "ossim_float32"; } else { scalarType = "ossim_uint32"; // default } } else if( numBits == 8 ) { scalarType = "ossim_uint8"; numBits = 8; } else if( numBits < 8 && numBits >= 1 ) { scalarType = "ossim_uint8"; } kwl.add(ossimKeywordNames::SCALAR_TYPE_KW, scalarType); kwl.add(ossimKeywordNames::INTERLEAVE_TYPE_KW, interleaveType); } return kwl; } ossimRefPtr ossimGeneralRasterTileSource::getImageGeometry() { if ( !theGeometry.valid() ) { // Check for external geom: theGeometry = getExternalImageGeometry(); if ( !theGeometry.valid() ) { theGeometry = new ossimImageGeometry(); ossimString ext = theImageFile.ext(); ossimFilename hdrFile = theImageFile; ossimFilename xmlFile = theImageFile; hdrFile = hdrFile.setExtension("hdr"); xmlFile = xmlFile.setExtension("xml"); if (hdrFile.exists()) { ossimKeywordlist geoKwl; ossimKeywordlist kwl(hdrFile, ' '); kwl.downcaseKeywords(); ossim_uint32 lines = 0; ossim_uint32 samples = 0; ossim_float32 ll_lon = 0.0; ossim_float32 ll_lat = 0.0; ossim_float32 xCellSize = 1.0; ossim_float32 yCellSize = 1.0; const char* lookup = kwl.find("ncols"); if (lookup) { samples = ossimString(lookup).toUInt32(); geoKwl.add(ossimKeywordNames::NUMBER_SAMPLES_KW, samples); } lookup = kwl.find("nrows"); if (lookup) { lines = ossimString(lookup).toUInt32(); geoKwl.add(ossimKeywordNames::NUMBER_LINES_KW, lines); } lookup = kwl.find("cellsize"); if (lookup) { xCellSize = ossimString(lookup).toFloat32(); yCellSize = xCellSize; geoKwl.add(ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, yCellSize); geoKwl.add(ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, xCellSize); } lookup = kwl.find("xdim"); if (lookup) { xCellSize = ossimString(lookup).toFloat32(); geoKwl.add(ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, xCellSize); } lookup = kwl.find("ydim"); if (lookup) { yCellSize = ossimString(lookup).toFloat32(); geoKwl.add(ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, yCellSize); } lookup = kwl.find("xllcenter"); if (lookup) { ossim_float32 centerX = ossimString(lookup).toFloat32(); ll_lon = centerX + xCellSize * 0.5; geoKwl.add(ossimKeywordNames::TIE_POINT_LON_KW, ll_lon); } lookup = kwl.find("yllcenter"); if (lookup) { ossim_float32 centerY = ossimString(lookup).toFloat32(); ll_lat = (centerY + (lines - 1) * yCellSize) + yCellSize * 0.5; geoKwl.add(ossimKeywordNames::TIE_POINT_LAT_KW, ll_lat); } lookup = kwl.find("xllcorner"); if (lookup) { ll_lon = ossimString(lookup).toFloat32(); geoKwl.add(ossimKeywordNames::TIE_POINT_LON_KW, ll_lon); } lookup = kwl.find("yllcorner"); if (lookup) { ossim_uint32 centerY = ossimString(lookup).toFloat32(); ll_lat = centerY + lines * yCellSize; geoKwl.add(ossimKeywordNames::TIE_POINT_LAT_KW, ll_lat); } lookup = kwl.find("ulxmap"); if (lookup) { ll_lon = ossimString(lookup).toFloat32(); geoKwl.add(ossimKeywordNames::TIE_POINT_LON_KW, ll_lon); } lookup = kwl.find("ulymap"); if (lookup) { ossim_uint32 centerY = ossimString(lookup).toFloat32(); ll_lat = centerY + lines * yCellSize; geoKwl.add(ossimKeywordNames::TIE_POINT_LAT_KW, ll_lat); } kwl.add(ossimKeywordNames::ORIGIN_LATITUDE_KW, ll_lat); geoKwl.add(ossimKeywordNames::TYPE_KW, "ossimEquDistCylProjection"); geoKwl.add(ossimKeywordNames::DATUM_KW, ossimDatumFactory::instance()->wgs84()-> code()); ossimRefPtr proj = ossimMapProjectionFactory::instance()-> createProjection(geoKwl); if ( proj.valid() ) { theGeometry->setProjection(proj.get()); } } else if (xmlFile.exists()) { ossimFgdcXmlDoc file; if ( file.open(xmlFile) ) { ossimRefPtr proj = file.getProjection(); if ( !proj.valid() ) { proj = file.getGridCoordSysProjection(); } if ( proj.valid() ) { theGeometry->setProjection(proj.get()); } } } // xml file exist... } // Matches second if ( !theGeometry.valid() ) //--- // WARNING: // Must have theGeometry at this point or the next call to // ossimImageGeometryRegistry::extendGeometry will put us in an infinite loop // as it does a recursive call back to ossimImageHandler::getImageGeometry(). //--- // Check for set projection. if ( !theGeometry->getProjection() ) { // Try factories for projection. ossimImageGeometryRegistry::instance()->extendGeometry(this); } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } // Matches first if ( !theGeometry.valid() ) return theGeometry; } bool ossimGeneralRasterTileSource::isBandSelector() const { bool result = false; if ( ( m_rasterInfo.interleaveType() == OSSIM_BSQ_MULTI_FILE ) || ( m_rasterInfo.interleaveType() == OSSIM_BIP ) || ( m_rasterInfo.interleaveType() == OSSIM_BIL ) ) { result = true; } if ( result && theOverview.valid() ) { result = theOverview->isBandSelector(); } return result; } bool ossimGeneralRasterTileSource::setOutputBandList(const std::vector& band_list) { bool result = false; if ( isBandSelector() ) { // Making a copy as passed in list could be our m_outputBandList. std::vector inputList = band_list; result = ossimImageHandler::setOutputBandList( inputList, m_outputBandList ); if ( result && m_tile.valid() ) { if ( m_tile->getNumberOfBands() != m_outputBandList.size() ) { m_tile = 0; // Force a reinitialize on next getTile. } } } return result; } void ossimGeneralRasterTileSource::getOutputBandList(std::vector& bandList) const { bandList = m_outputBandList; } void ossimGeneralRasterTileSource::allocateTile() { m_tile = 0; ossim_uint32 bands = 0; if ( m_outputBandList.empty() ) { bands = m_rasterInfo.numberOfBands(); } else { bands = (ossim_uint32)m_outputBandList.size(); } if ( bands ) { m_tile = ossimImageDataFactory::instance()->create( this, m_rasterInfo.getImageMetaData().getScalarType(), bands ); if ( m_tile.valid() ) { // These values can be overridden by loadState... for(ossim_uint32 band = 0; band < bands; ++ band) { m_tile->setNullPix(m_rasterInfo.getImageMetaData().getNullPix(band), band); m_tile->setMinPix(m_rasterInfo.getImageMetaData().getMinPix(band), band); m_tile->setMaxPix(m_rasterInfo.getImageMetaData().getMaxPix(band), band); } m_tile->initialize(); // This does a makeBlank(). } } } void ossimGeneralRasterTileSource::allocateBuffer( const ossimImageData* tile ) { if( m_buffer ) { delete [] m_buffer; m_buffer = 0; m_bufferSizeInPixels = 0; // Must zero out for check in getTile method. } if ( m_lineBuffer ) { delete [] m_lineBuffer; m_lineBuffer = 0; } if ( tile ) { // Store the size of the buffer in pixels for swapping bytes. m_bufferSizeInPixels = tile->getSize(); if ( m_bufferSizeInPixels ) { // Initialize buffer. This is bytes, not pixels. m_buffer = new ossim_uint8[ tile->getSizeInBytes() ]; // Zero out the buffer rect. m_bufferRect = ossimIrect(0, 0, 0, 0); } if ( m_rasterInfo.interleaveType() == OSSIM_BIP ) { // Big enough to hold a whole line all bands. ossim_uint32 widthInBytes = tile->getWidth() * m_rasterInfo.getImageMetaData().getNumberOfBands() * m_rasterInfo.getImageMetaData().getBytesPerPixel(); m_lineBuffer = new ossim_uint8[ widthInBytes ]; } } } ossim-Miami-2.9.1/src/imaging/ossimGeneralRasterWriter.cpp000066400000000000000000000650231352751253100236350ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: David Burken // //******************************************************************* // $Id: ossimGeneralRasterWriter.cpp 21962 2012-11-30 15:44:32Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimGeneralRasterWriter:debug"); RTTI_DEF1(ossimGeneralRasterWriter, "ossimGeneralRasterWriter", ossimImageFileWriter) static const char DEFAULT_FILE_NAME[] = "output.ras"; using namespace std; ossimGeneralRasterWriter::ossimGeneralRasterWriter() : ossimImageFileWriter(), theOutputStream(0), theOwnsStreamFlag(false), theRlevel(0), theOutputByteOrder(OSSIM_LITTLE_ENDIAN), theMinPerBand(0), theMaxPerBand(0) { setOutputImageType(OSSIM_GENERAL_RASTER_BSQ); // Since there is no internal geometry set the flag to write out one. setWriteExternalGeometryFlag(true); theOutputByteOrder = ossimEndian().getSystemEndianType(); } ossimGeneralRasterWriter::~ossimGeneralRasterWriter() { if(isOpen()) { close(); } } bool ossimGeneralRasterWriter::isOpen()const { return ( theOutputStream ? true : false ); } bool ossimGeneralRasterWriter::open() { bool result = false; close(); // Check for empty filenames. if ( theFilename.size() ) { std::ofstream* os = new std::ofstream(); os->open(theFilename.c_str(), ios::out | ios::binary); if(os->is_open()) { theOutputStream = os; theOwnsStreamFlag = true; result = true; } else { delete os; os = 0; } } return result; } void ossimGeneralRasterWriter::close() { if (theOutputStream) { theOutputStream->flush(); if (theOwnsStreamFlag) { delete theOutputStream; theOwnsStreamFlag = false; } theOutputStream = 0; } } bool ossimGeneralRasterWriter::writeFile() { bool result = false; if( theInputConnection.valid() && ( getErrorStatus() == ossimErrorCodes::OSSIM_OK ) ) { //--- // Make sure we can open the file. Note only the master process is used for // writing... //--- if(theInputConnection->isMaster()) { if (!isOpen()) { open(); } } result = writeStream(); if ( result ) { // Do this only on the master process. Note left to right precedence! if (getSequencer() && getSequencer()->isMaster()) { //--- // Write the header out. We do this last since we must // compute min max pixel while we are writting the image. // since the header is an external text file this is Ok // to do. //--- writeHeader(); if (theOutputImageType.contains("envi")) { writeEnviHeader(); } } } close(); } return result; } // End: ossimGeneralRasterWriter::writeFile() bool ossimGeneralRasterWriter::writeStream() { static const char MODULE[] = "ossimGeneralRasterWriter::writeStream"; bool result = false; if( theInputConnection.valid() && theOutputStream && ( getErrorStatus() == ossimErrorCodes::OSSIM_OK ) ) { if ( theInputConnection->isMaster() ) { // Write the file with the image data. if ( (theOutputImageType == "general_raster_bip") || (theOutputImageType == "general_raster_bip_envi") ) { result = writeToBip(); } else if ( (theOutputImageType == "general_raster_bil") || (theOutputImageType == "general_raster_bil_envi") ) { result = writeToBil(); } else if ( (theOutputImageType == "general_raster_bsq") || (theOutputImageType == "general_raster_bsq_envi") ) { result = writeToBsq(); } else { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " ERROR:" << "\nUnsupported output type: " << theOutputImageType << std::endl; result = false; } if ( result ) { // Flush the stream to disk... theOutputStream->flush(); } } else // Matching else: if ( theInputConnection->isMaster() ) { // Slave process: theInputConnection->slaveProcessTiles(); result = true; } } return result; } // End: ossimGeneralRasterWriter::writeStream() bool ossimGeneralRasterWriter::writeToBip() { ossimEndian endian; static const char* const MODULE = "ossimGeneralRasterWriter::writeToBip"; if (traceDebug()) CLOG << " Entered." << std::endl; //--- // Get an arbitrary tile just to get the size in bytes! // This should be changed later... An ossimImageSource should know // this. //--- ossimRefPtr id; // Start the sequence at the first tile. theInputConnection->setToStartOfSequence(); ossim_uint64 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint64 tilesWide = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint64 tilesHigh = theInputConnection->getNumberOfTilesVertical(); ossim_uint64 tileHeight = theInputConnection->getTileHeight(); ossim_uint64 numberOfTiles = theInputConnection->getNumberOfTiles(); ossim_uint64 width = theAreaOfInterest.width(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimGeneralRasterWriter::writeToBip DEBUG:" << "\nbands: " << bands << "\ntilesWide: " << tilesWide << "\ntilesHigh: " << tilesHigh << "\ntileHeight: " << tileHeight << "\nnumberOfTiles: " << numberOfTiles << "\nwidth: " << width << std::endl; } //--- // Buffer to hold one line x tileHeight //--- ossim_uint64 bufferSizeInBytes = 0; ossim_uint64 bytesInLine = 0; unsigned char* buffer = NULL; theMinPerBand.clear(); theMaxPerBand.clear(); ossim_uint64 tileNumber = 0; bool wroteSomethingOut = false; ossimScalarType scalarType = theInputConnection->getOutputScalarType(); for(ossim_uint64 i = 0; ((i < tilesHigh)&&(!needsAborting())); ++i) { // Clear the buffer. if(buffer) { memset(buffer, 0, bufferSizeInBytes); } ossimIrect bufferRect(theAreaOfInterest.ul().x, theAreaOfInterest.ul().y + i*tileHeight, theAreaOfInterest.ul().x + (width - 1), theAreaOfInterest.ul().y + i*tileHeight + (tileHeight - 1)); // Tile loop in the sample (width) direction. for(ossim_uint64 j = 0; ((j < tilesWide)&&(!needsAborting())); ++j) { // Get the tile and copy it to the buffer. id = theInputConnection->getNextTile(); if(id.valid()) { id->computeMinMaxPix(theMinPerBand, theMaxPerBand); if(!buffer) { bytesInLine = id->getScalarSizeInBytes() * width * bands; //--- // Buffer to hold one line x tileHeight //--- bufferSizeInBytes = bytesInLine * tileHeight; buffer = new unsigned char[bufferSizeInBytes]; memset(buffer, 0, bufferSizeInBytes); } id->unloadTile(buffer, bufferRect, OSSIM_BIP); } ++tileNumber; } // Get the number of lines to write from the buffer. ossim_uint64 linesToWrite = min(tileHeight, static_cast(theAreaOfInterest.lr().y - bufferRect.ul().y + 1)); // Write the buffer out to disk. ossim_uint8* buf = buffer; if(buf) { for (ossim_uint64 ii=0; ((iiwrite((char*)buf, lineBytes); if (theOutputStream->fail()) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " ERROR:" << "Error returned writing line!" << std::endl; setErrorStatus(); if(buffer) { // Free the memory. delete [] buffer; } return false; } buf += bytesInLine; } // End of loop to write lines from buffer to tiff file. } double tile = tileNumber; double numTiles = numberOfTiles; setPercentComplete(tile / numTiles * 100); if(needsAborting()) { setPercentComplete(100.0); } } // End of loop in the line (height) direction. if(buffer) { // Free the memory. delete [] buffer; } if (traceDebug()) CLOG << " Exited." << std::endl; return wroteSomethingOut; } bool ossimGeneralRasterWriter::writeToBil() { ossimEndian endian; static const char* const MODULE = "ossimGeneralRasterWriter::writeToBil"; if (traceDebug()) CLOG << " Entered." << std::endl; //*** // Get an arbitrary tile just to get the size in bytes! // This should be changed later... An ossimImageSource should know // this. //*** ossimRefPtr id; theInputConnection->setToStartOfSequence(); ossim_uint64 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint64 tilesWide = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint64 tilesHigh = theInputConnection->getNumberOfTilesVertical(); ossim_uint64 tileHeight = theInputConnection->getTileHeight(); ossim_uint64 numberOfTiles = theInputConnection->getNumberOfTiles(); ossim_uint64 width = theAreaOfInterest.width(); ossim_uint64 bufferSizeInBytes = 0; ossim_uint64 bytesInLine = 0; unsigned char* buffer = NULL; // Start with a clean min/max. theMinPerBand.clear(); theMaxPerBand.clear(); ossim_uint64 tileNumber = 0; bool wroteSomethingOut = false; ossimScalarType scalarType = theInputConnection->getOutputScalarType(); for(ossim_uint64 i = 0; ((i < tilesHigh)&&(!needsAborting())); ++i) { // Clear the buffer. // Clear the buffer. if(buffer) { memset(buffer, 0, bufferSizeInBytes); } ossimIrect bufferRect(theAreaOfInterest.ul().x, theAreaOfInterest.ul().y + i*tileHeight, theAreaOfInterest.ul().x + (width - 1), theAreaOfInterest.ul().y + i * tileHeight + (tileHeight - 1)); // Tile loop in the sample (width) direction. for(ossim_uint64 j = 0; ((j < tilesWide)&&(!needsAborting())); ++j) { // Get the tile and copy it to the buffer. id = theInputConnection->getNextTile(); if(id.valid()) { id->computeMinMaxPix(theMinPerBand, theMaxPerBand); if(!buffer) { bytesInLine = id->getScalarSizeInBytes() * width; // Buffer to hold one line x tileHeight bufferSizeInBytes = bytesInLine * tileHeight * bands; buffer = new unsigned char[bufferSizeInBytes]; memset(buffer, 0, bufferSizeInBytes); } id->unloadTile(buffer, bufferRect, OSSIM_BIL); } ++tileNumber; } // Get the number of lines to write from the buffer. ossim_uint64 linesToWrite = min(tileHeight, static_cast(theAreaOfInterest.lr().y - bufferRect.ul().y + 1)); // Write the buffer out to disk. ossim_uint8* buf = buffer; for (ossim_uint64 ii=0; ((iiwrite((char*)buf, bytesInLine); if (theOutputStream->fail()) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " ERROR:" << "Error returned writing line!" << std::endl; setErrorStatus(); if(buffer) { // Free the memory. delete [] buffer; } return false; } buf += bytesInLine; } } // End of loop to write lines from buffer to tiff file. double tile = tileNumber; double numTiles = numberOfTiles; setPercentComplete(tile / numTiles * 100); if(needsAborting()) { setPercentComplete(100.0); } } // End of loop in the line (height) direction. if(buffer) { // Free the memory. delete [] buffer; } if (traceDebug()) CLOG << " Exited." << std::endl; return wroteSomethingOut; } bool ossimGeneralRasterWriter::writeToBsq() { ossimEndian endian; static const char* const MODULE = "ossimGeneralRasterWriter::writeToBsq"; if (traceDebug()) CLOG << " Entered." << std::endl; //*** // Get an arbitrary tile just to get the size in bytes! // This should be changed later... An ossimImageSource should know // this. //*** ossimRefPtr id; // Start the sequence at the first tile. theInputConnection->setToStartOfSequence(); ossim_uint64 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint64 tilesWide = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint64 tilesHigh = theInputConnection->getNumberOfTilesVertical(); ossim_uint64 tileHeight = theInputConnection->getTileHeight(); ossim_uint64 numberOfTiles = theInputConnection->getNumberOfTiles(); ossim_uint64 width = theAreaOfInterest.width(); ossim_uint64 height = theAreaOfInterest.height(); ossim_uint64 bytesInLine = 0; ossim_uint64 buf_band_offset = 0; // Use the system "streampos" typedef for future 64 bit seeks (long long). streampos file_band_offset = 0; //*** // Buffer to hold one line x tileHeight //*** ossim_uint64 bufferSizeInBytes = 0; unsigned char* buffer = NULL; theMinPerBand.clear(); theMaxPerBand.clear(); ossim_uint64 tileNumber = 0; bool wroteSomethingOut = false; ossimScalarType scalarType = theInputConnection->getOutputScalarType(); for(ossim_uint64 i = 0; ((i < tilesHigh)&&(!needsAborting())); ++i) { if(buffer) { // Clear the buffer. memset(buffer, 0, bufferSizeInBytes); } ossimIrect bufferRect(theAreaOfInterest.ul().x, theAreaOfInterest.ul().y + i*tileHeight, theAreaOfInterest.ul().x + (width - 1), theAreaOfInterest.ul().y + i * tileHeight + (tileHeight - 1)); // Tile loop in the sample (width) direction. for(ossim_uint64 j = 0; ((j < tilesWide)&&(!needsAborting())); ++j) { // Get the tile and copy it to the buffer. id = theInputConnection->getNextTile(); if(id.valid()) { id->computeMinMaxPix(theMinPerBand, theMaxPerBand); if(!buffer) { bytesInLine = id->getScalarSizeInBytes() * width; buf_band_offset = bytesInLine * tileHeight; file_band_offset = height * bytesInLine; bufferSizeInBytes = bytesInLine * tileHeight * bands; buffer = new unsigned char[bufferSizeInBytes]; memset(buffer, 0, bufferSizeInBytes); } id->unloadTile(buffer, bufferRect, OSSIM_BSQ); } ++tileNumber; } // Get the number of lines to write from the buffer. ossim_uint64 linesToWrite = min(tileHeight, static_cast(theAreaOfInterest.lr().y - bufferRect.ul().y + 1)); // Write the buffer out to disk. ossim_uint64 start_line = static_cast(bufferRect.ul().y - theAreaOfInterest.ul().y); for (ossim_uint64 band = 0; ((band < bands)&&(!needsAborting())); ++band) { ossim_uint8* buf = buffer; buf += buf_band_offset * band; // Put the file pointer in the right spot. streampos pos = file_band_offset * band + start_line * bytesInLine; theOutputStream->seekp(pos, ios::beg); if (theOutputStream->fail()) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " ERROR:" << "Error returned seeking to image data position!" << std::endl; setErrorStatus(); return false; } for (ossim_uint64 ii=0; ((iiwrite((char*)buf, bytesInLine); if (theOutputStream->fail()) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " ERROR:" << "Error returned writing line!" << std::endl; setErrorStatus(); return false; } buf += bytesInLine; } } // End of loop to write lines from buffer to tiff file. double tile = tileNumber; double numTiles = numberOfTiles; setPercentComplete(tile / numTiles * 100); if(needsAborting()) { setPercentComplete(100.0); } } // End of loop in the line (height) direction. // Free the memory. delete [] buffer; if (traceDebug()) CLOG << " Exited." << std::endl; return wroteSomethingOut; } bool ossimGeneralRasterWriter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::BYTE_ORDER_KW, ((theOutputByteOrder==OSSIM_LITTLE_ENDIAN)?"little_endian":"big_endian"), true); return ossimImageFileWriter::saveState(kwl, prefix); } bool ossimGeneralRasterWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* value; value = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if(value) { setFilename(ossimFilename(value)); } value = kwl.find(prefix, ossimKeywordNames::INPUT_RR_LEVEL_KW); if(value) { theRlevel = atoi(value); } if(ossimImageFileWriter::loadState(kwl, prefix)) { if( (theOutputImageType!="general_raster_bip") && (theOutputImageType!="general_raster_bil") && (theOutputImageType!="general_raster_bsq") && (theOutputImageType!="general_raster_bip_envi") && (theOutputImageType!="general_raster_bil_envi") && (theOutputImageType!="general_raster_bsq_envi") ) { theOutputImageType = "general_raster_bsq"; } } else { return false; } const char* outputByteOrder = kwl.find(prefix, ossimKeywordNames::BYTE_ORDER_KW); theOutputByteOrder = ossimEndian().getSystemEndianType(); if(outputByteOrder) { ossimString byteOrder = outputByteOrder; byteOrder = byteOrder.downcase(); if(byteOrder.contains("little")) { theOutputByteOrder = OSSIM_LITTLE_ENDIAN; } else if(byteOrder.contains("big")) { theOutputByteOrder = OSSIM_BIG_ENDIAN; } } return true; } void ossimGeneralRasterWriter::writeHeader() const { static const char MODULE[] = "ossimGeneralRasterWriter::writeHeader"; if (traceDebug()) CLOG << " Entered..." << std::endl; // Make a header file name from the image file. ossimFilename headerFile = theFilename; headerFile.setExtension(".omd"); // ossim meta data std::ofstream os; os.open(headerFile.c_str(), ios::out); if (!os) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " Error:\n" << "Could not open: " << headerFile << std::endl; return; } ossimString interleaveType = getInterleaveString(); ossimString scalar = ossimScalarTypeLut::instance()->getEntryString(theInputConnection-> getOutputScalarType()); os << "// *** ossim meta data general raster header file ***\n" << ossimKeywordNames::FILENAME_KW << ": " << theFilename.file().c_str() << "\n" << ossimKeywordNames::IMAGE_TYPE_KW << ": " << getOutputImageTypeString() << "\n" << ossimKeywordNames::INTERLEAVE_TYPE_KW << ": " << interleaveType.c_str() << "\n" << ossimKeywordNames::NUMBER_BANDS_KW << ": " << theInputConnection->getNumberOfOutputBands() << "\n" << ossimKeywordNames::NUMBER_LINES_KW << ": " << (theAreaOfInterest.lr().y - theAreaOfInterest.ul().y + 1) << "\n" << ossimKeywordNames::NUMBER_SAMPLES_KW << ": " << (theAreaOfInterest.lr().x - theAreaOfInterest.ul().x + 1) << "\n" << ossimKeywordNames::SCALAR_TYPE_KW << ": " << scalar.c_str() << "\n" << ossimKeywordNames::BYTE_ORDER_KW <<": " << ((theOutputByteOrder==OSSIM_BIG_ENDIAN)?"big_endian":"little_endian") << "\n" << std::endl; // Output the null/min/max for each band. os << "\n// NOTE: Bands are one based, band1 is the first band." << std::endl; for (ossim_uint32 i=0; igetNumberOfOutputBands(); ++i) { ossimString prefix = ossimKeywordNames::BAND_KW + ossimString::toString(i+1) + "."; ossimString null_pix = ossimString::toString(theInputConnection-> getNullPixelValue(i)); ossimString min_pix; ossimString max_pix; if(!theMinPerBand.size()||!theMaxPerBand.size()) { min_pix = ossimString::toString(theInputConnection-> getMinPixelValue(i)); max_pix = ossimString::toString(theInputConnection-> getMaxPixelValue(i)); } else { min_pix = ossimString::toString(theMinPerBand[i]); max_pix = ossimString::toString(theMaxPerBand[i]); } os << prefix.c_str() << ossimKeywordNames::NULL_VALUE_KW << ": " << null_pix.c_str() << "\n" << prefix << ossimKeywordNames::MIN_VALUE_KW << ": " << min_pix.c_str() << "\n" << prefix << ossimKeywordNames::MAX_VALUE_KW << ": " << max_pix.c_str() << std::endl; } os.close(); if (traceDebug()) CLOG << " Exited..." << endl; } void ossimGeneralRasterWriter::writeEnviHeader() const { static const char MODULE[] = "ossimGeneralRasterWriter::writeEnviHeader"; if (traceDebug()) CLOG << " Entered..." << endl; if (!theInputConnection) { return; } // Make a header file name from the image file. ossimFilename headerFile = theFilename; headerFile.setExtension(".hdr"); // ossim meta data ossimString interleaveType = getInterleaveString(); ossimKeywordlist kwl; kwl.add(ossimKeywordNames::INTERLEAVE_TYPE_KW, interleaveType.c_str()); ossimRefPtr hdr = new ossimEnviHeaderFileWriter; hdr->connectMyInputTo(0, theInputConnection.get()); hdr->initialize(); hdr->setFilename(headerFile); hdr->loadState(kwl); hdr->setAreaOfInterest(theAreaOfInterest); hdr->execute(); if (traceDebug()) CLOG << " Exited..." << endl; } ossimString ossimGeneralRasterWriter::getExtension() const { return "ras"; //return getInterleaveString(); } void ossimGeneralRasterWriter::getImageTypeList(std::vector& imageTypeList)const { imageTypeList.push_back(ossimString("general_raster_bip")); imageTypeList.push_back(ossimString("general_raster_bil")); imageTypeList.push_back(ossimString("general_raster_bsq")); imageTypeList.push_back(ossimString("general_raster_bip_envi")); imageTypeList.push_back(ossimString("general_raster_bil_envi")); imageTypeList.push_back(ossimString("general_raster_bsq_envi")); } ossimString ossimGeneralRasterWriter::getInterleaveString() const { ossimString interleaveType = "unknown"; if ( (theOutputImageType == "general_raster_bip") || (theOutputImageType == "general_raster_bip_envi") ) { interleaveType = "bip"; } else if ( (theOutputImageType == "general_raster_bil") || (theOutputImageType == "general_raster_bil_envi") ) { interleaveType = "bil"; } else if ( (theOutputImageType == "general_raster_bsq") || (theOutputImageType == "general_raster_bsq_envi") ) { interleaveType = "bsq"; } return interleaveType; } bool ossimGeneralRasterWriter::setOutputStream(std::ostream& stream) { if (theOwnsStreamFlag && theOutputStream) { delete theOutputStream; } theOutputStream = &stream; theOwnsStreamFlag = false; return true; } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationBitmap.cpp000066400000000000000000000136041352751253100236020ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationBitmap.cpp 22519 2013-12-16 15:18:29Z dburken $ #include #include #include #include #include RTTI_DEF1(ossimGeoAnnotationBitmap, "ossimGeoAnnotationBitmap", ossimGeoAnnotationObject) using namespace std; ossimGeoAnnotationBitmap::ossimGeoAnnotationBitmap( const ossimGpt& center, ossimRefPtr imageData, unsigned char r, unsigned char g, unsigned char b) :ossimGeoAnnotationObject(r, g, b), theCenterPoint(center), theProjectedPoint(0,0), theImageData(NULL) { if(imageData.valid() && (imageData->getScalarType()==OSSIM_UCHAR)) { theImageData = imageData; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimGeoAnnotationBitmap::ossimGeoAnnotationBitmap\n" << "Invalid image data passed to ossimGeoAnnotationBitmap " << "constructor" << endl; } } ossimGeoAnnotationBitmap::ossimGeoAnnotationBitmap( const ossimGeoAnnotationBitmap& rhs) : ossimGeoAnnotationObject(rhs), theCenterPoint(rhs.theCenterPoint), theProjectedPoint(rhs.theProjectedPoint), theImageData(rhs.theImageData) { } ossimGeoAnnotationBitmap::~ossimGeoAnnotationBitmap() { } ossimObject* ossimGeoAnnotationBitmap::dup()const { return new ossimGeoAnnotationBitmap(*this); } bool ossimGeoAnnotationBitmap::intersects(const ossimDrect& rect) const { if(theImageData.valid()) { return theImageData->getImageRectangle().intersects(rect); } return false; } ossimGeoAnnotationBitmap* ossimGeoAnnotationBitmap::getNewClippedObject( const ossimDrect& /* rect */)const { ossimGeoAnnotationBitmap* result = (ossimGeoAnnotationBitmap*)dup(); ossimNotify(ossimNotifyLevel_WARN) << "ossimGeoAnnotationBitmap::getNewClippedObject WRNING: " << "not implemented" << std::endl; return result; } void ossimGeoAnnotationBitmap::applyScale(double /* x */, double /* y */) { ossimNotify(ossimNotifyLevel_WARN) << "ossimGeoAnnotationBitmap::applyScale WRNING: not implemented" << std::endl; } std::ostream& ossimGeoAnnotationBitmap::print(std::ostream& out)const { out << "center: " << theCenterPoint << endl; return out; } void ossimGeoAnnotationBitmap::draw(ossimRgbImage& anImage)const { ossimRefPtr destination = anImage.getImageData(); if(!destination) { ossimNotify(ossimNotifyLevel_WARN) << "ossimGeoAnnotationBitmap::draw\n" << "ERROR: can't draw annotation bitmap to NULL buffer" << endl; return; } ossimIrect destinationRect = destination->getImageRectangle(); ossimIrect srcRect = theImageData->getImageRectangle(); if(!srcRect.intersects(destinationRect)) { return; } ossimIrect clipRect = srcRect.clipToRect(destinationRect); long clipHeight = (long)clipRect.height(); long clipWidth = (long)clipRect.width(); if(clipRect.width() != 1.0 && clipRect.height() != 1.0) { long destinationOffset = (long)(((clipRect.ul().y - destinationRect.ul().y)* destinationRect.width()) + (clipRect.ul().x - destinationRect.ul().x)); long srcOffset = (long)(((clipRect.ul().y - srcRect.ul().y)*srcRect.width()) + (clipRect.ul().x - srcRect.ul().x)); long destinationIndex = destinationOffset; long srcIndex = srcOffset; long num_bands = destination->getNumberOfBands(); ossim_int32 s_width = (ossim_int32)srcRect.width(); ossim_int32 d_width = (ossim_int32)destinationRect.width(); num_bands = num_bands > 3? 3:num_bands; const ossim_uint8* imageDataBuf = static_cast(theImageData->getBuf()); unsigned char colorArray[3]; colorArray[0] = theRed; colorArray[1] = theGreen; colorArray[2] = theBlue; for (long band=0; band(destination->getBuf(band)); destinationIndex = destinationOffset; srcIndex = srcOffset; for(long line = 0; line < clipHeight; ++line) { for(long col = 0; col < clipWidth; ++col) { if(imageDataBuf[srcIndex + col]) { destinationBand[destinationIndex + col] = colorArray[band]; } } srcIndex += s_width; destinationIndex += d_width; } } } } void ossimGeoAnnotationBitmap::getBoundingRect(ossimDrect& rect)const { rect = ossimDrect(0,0,0,0); if(theImageData.valid()) { rect = theImageData->getImageRectangle(); } } void ossimGeoAnnotationBitmap::transform(ossimImageGeometry* projection) { if(projection) { projection->worldToLocal(theCenterPoint, theProjectedPoint); theProjectedPoint = ossimIpt(theProjectedPoint); if(theImageData.valid()) { ossimDpt origin(theProjectedPoint.x - theImageData->getWidth()/2.0, theProjectedPoint.y - theImageData->getHeight()/2.0); theImageData->setOrigin(origin); } } } void ossimGeoAnnotationBitmap::setImageData( ossimRefPtr& imageData) { theImageData = imageData; } void ossimGeoAnnotationBitmap::computeBoundingRect() { // nothing to be done since we don't support // rotated bitmaps yet. } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationEllipseObject.cpp000066400000000000000000000244501352751253100251130ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationEllipseObject.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include #include #include RTTI_DEF1(ossimGeoAnnotationEllipseObject, "ossimGeoAnnotationEllipseObject", ossimGeoAnnotationObject); using namespace std; ossimGeoAnnotationEllipseObject::ossimGeoAnnotationEllipseObject( const ossimGpt& center, const ossimDpt& widthHeight, bool enableFill, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b, ossim_uint8 thickness) :ossimGeoAnnotationObject(r, g, b, thickness), theProjectedEllipse(0), theCenter(center), theWidthHeight(widthHeight), theEllipseWidthHeightUnitType(OSSIM_PIXEL) // default to image space { theProjectedEllipse = new ossimAnnotationEllipseObject(ossimDpt(0,0), ossimDpt(0,0), enableFill, r, g, b, thickness); } ossimGeoAnnotationEllipseObject::ossimGeoAnnotationEllipseObject( const ossimGeoAnnotationEllipseObject& rhs) :ossimGeoAnnotationObject(rhs), theProjectedEllipse(rhs.theProjectedEllipse.valid()?(ossimAnnotationEllipseObject*)rhs.theProjectedEllipse->dup():(ossimAnnotationEllipseObject*)0), theCenter(rhs.theCenter), theWidthHeight(rhs.theWidthHeight), theEllipseWidthHeightUnitType(rhs.theEllipseWidthHeightUnitType) { } ossimGeoAnnotationEllipseObject::~ossimGeoAnnotationEllipseObject() { if(theProjectedEllipse.valid()) { theProjectedEllipse = 0; } } ossimObject* ossimGeoAnnotationEllipseObject::dup()const { return new ossimGeoAnnotationEllipseObject(*this); } void ossimGeoAnnotationEllipseObject::applyScale(double x, double y) { if(theProjectedEllipse.valid()) theProjectedEllipse->applyScale(x, y); theCenter.lond(theCenter.lond()*x); theCenter.latd(theCenter.latd()*y); theWidthHeight .x *= x; theWidthHeight .y *= y; } std::ostream& ossimGeoAnnotationEllipseObject::print(std::ostream& out)const { out << "center ground: " << theCenter << endl << "width height image space flag = " << theEllipseWidthHeightUnitType << endl << *theProjectedEllipse; return out; } void ossimGeoAnnotationEllipseObject::draw(ossimRgbImage& anImage)const { if(theProjectedEllipse.valid()) { theProjectedEllipse->draw(anImage); } } bool ossimGeoAnnotationEllipseObject::intersects(const ossimDrect& rect)const { if(theProjectedEllipse.valid()) { theProjectedEllipse->intersects(rect); } return false; } ossimAnnotationObject* ossimGeoAnnotationEllipseObject::getNewClippedObject(const ossimDrect& rect)const { if(intersects(rect)) { if(theProjectedEllipse.valid()) { return theProjectedEllipse->getNewClippedObject(rect); } } return (ossimAnnotationObject*)0; } void ossimGeoAnnotationEllipseObject::getBoundingRect(ossimDrect& rect)const { if(theProjectedEllipse.valid()) { theProjectedEllipse->getBoundingRect(rect); } else { rect.makeNan(); } } void ossimGeoAnnotationEllipseObject::computeBoundingRect() { if(theProjectedEllipse.valid()) { theProjectedEllipse->computeBoundingRect(); } } void ossimGeoAnnotationEllipseObject::transform(ossimImageGeometry* projection) { if(!projection) { return; } // Ellipse center, height and width in image space. ossimDpt projectedCenter; ossimDpt projectedWidthHeight; // first get the center projected projection->worldToLocal(theCenter, projectedCenter); getWidthHeightInPixels(projectedWidthHeight, projection); theProjectedEllipse->setCenterWidthHeight(projectedCenter, projectedWidthHeight); } bool ossimGeoAnnotationEllipseObject::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, "center", theCenter.toString().c_str()); kwl.add(prefix, "ellipse_width", theWidthHeight.x); kwl.add(prefix, "ellipse_height", theWidthHeight.y); kwl.add(prefix, "azimuth", getAzimuth()); kwl.add(prefix, "fill", ossimString::toString(getFillFlag())); kwl.add(prefix, "draw_axes", ossimString::toString(getDrawAxesFlag())); kwl.add(prefix, "units", ossimUnitTypeLut::instance()->getEntryString(theEllipseWidthHeightUnitType).c_str()); return ossimGeoAnnotationObject::saveState(kwl, prefix); } bool ossimGeoAnnotationEllipseObject::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (!theProjectedEllipse) { return false; } //--- // Base class state must be called first to pick up colors... //--- bool status = ossimGeoAnnotationObject::loadState(kwl, prefix); if (status == true) { theProjectedEllipse->setColor(theRed, theGreen, theBlue); theProjectedEllipse->setThickness(theThickness); } const char* center = kwl.find(prefix, "center"); const char* ellipse_width = kwl.find(prefix, "ellipse_width"); const char* ellipse_height = kwl.find(prefix, "ellipse_height"); const char* azimuth = kwl.find(prefix, "azimuth"); const char* fill = kwl.find(prefix, "fill"); const char* draw_axes = kwl.find(prefix, "draw_axes"); const char* units = kwl.find(prefix, "units"); if(units) { theEllipseWidthHeightUnitType = static_cast(ossimUnitTypeLut::instance()->getEntryNumber(units)); if (theEllipseWidthHeightUnitType == OSSIM_UNIT_UNKNOWN) { theEllipseWidthHeightUnitType = OSSIM_PIXEL; } } if (center) { std::istringstream is(center); is >> theCenter; } if(ellipse_width) { theWidthHeight.x = ossimString(ellipse_width).toDouble(); } if(ellipse_height) { theWidthHeight.y = ossimString(ellipse_height).toDouble(); } if (azimuth) { setAzimuth(ossimString(azimuth).toFloat64()); } if (fill) { setFillFlag(ossimString(fill).toBool()); } if (draw_axes) { setDrawAxesFlag(ossimString(draw_axes).toBool()); } return status; } void ossimGeoAnnotationEllipseObject::setEllipseWidthHeightUnitType( ossimUnitType type) { theEllipseWidthHeightUnitType = type; } void ossimGeoAnnotationEllipseObject::setWidthHeight(const ossimDpt& pt) { theWidthHeight = pt; } void ossimGeoAnnotationEllipseObject::setAzimuth(ossim_float64 azimuth) { if (theProjectedEllipse.valid()) { theProjectedEllipse->setAzimuth(azimuth); } } ossim_float64 ossimGeoAnnotationEllipseObject::getAzimuth() const { if (theProjectedEllipse.valid()) { return theProjectedEllipse->getAzimuth(); } return 0.0; } void ossimGeoAnnotationEllipseObject::getWidthHeightInPixels( ossimDpt& widthHeight, const ossimImageGeometry* projection) const { switch (theEllipseWidthHeightUnitType) { case OSSIM_PIXEL: { widthHeight = theWidthHeight; break; } case OSSIM_DEGREES: case OSSIM_MINUTES: case OSSIM_SECONDS: { ossimGpt origin = projection->hasProjection()?projection->getProjection()->origin():ossimGpt(); ossimDpt gsd = projection->getMetersPerPixel(); ossimUnitConversionTool uct(origin, theWidthHeight.x, theEllipseWidthHeightUnitType); double x = uct.getValue(OSSIM_METERS); uct.setValue(theWidthHeight.y, theEllipseWidthHeightUnitType); double y = uct.getValue(OSSIM_METERS); widthHeight.x = ceil(x/gsd.x); widthHeight.y = ceil(y/gsd.y); break; } case OSSIM_METERS: { ossimDpt gsd = projection->getMetersPerPixel(); widthHeight.x = static_cast(theWidthHeight.x/gsd.x+0.5); widthHeight.y = static_cast(theWidthHeight.y/gsd.y+0.5); break; } default: { ossimDpt gsd = projection->getMetersPerPixel(); ossimUnitConversionTool uct(theWidthHeight.x, theEllipseWidthHeightUnitType); double x = uct.getValue(OSSIM_METERS); uct.setValue(theWidthHeight.y, theEllipseWidthHeightUnitType); double y = uct.getValue(OSSIM_METERS); widthHeight.x = ceil(x/gsd.x); widthHeight.y = ceil(y/gsd.y); break; } } } void ossimGeoAnnotationEllipseObject::setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { if(theProjectedEllipse.valid()) { theProjectedEllipse->setColor(r, g, b); } ossimGeoAnnotationObject::setColor(r, g, b); } void ossimGeoAnnotationEllipseObject::setThickness(ossim_uint8 thickness) { if(theProjectedEllipse.valid()) { theProjectedEllipse->setThickness(thickness); } } void ossimGeoAnnotationEllipseObject::setFillFlag(bool flag) { if(theProjectedEllipse.valid()) { theProjectedEllipse->setFillFlag(flag); } } bool ossimGeoAnnotationEllipseObject::getFillFlag() const { if (theProjectedEllipse.valid()) { return theProjectedEllipse->getFillFlag(); } return false; } void ossimGeoAnnotationEllipseObject::setDrawAxesFlag(bool flag) { if (theProjectedEllipse.valid()) { theProjectedEllipse->setDrawAxesFlag(flag); } } bool ossimGeoAnnotationEllipseObject::getDrawAxesFlag() const { if (theProjectedEllipse.valid()) { return theProjectedEllipse->getDrawAxesFlag(); } return false; } void ossimGeoAnnotationEllipseObject::setCenter(const ossimGpt& gpt) { theCenter = gpt; } void ossimGeoAnnotationEllipseObject::getCenter(ossimGpt& gpt) const { gpt = theCenter; } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationFontObject.cpp000066400000000000000000000161311352751253100244210ustar00rootroot00000000000000//************************************************************************* // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* //$Id: ossimGeoAnnotationFontObject.cpp 17108 2010-04-15 21:08:06Z dburken $ #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimGeoAnnotationFontObject, "ossimGeoAnnotationFontObject", ossimGeoAnnotationObject); using namespace std; ossimGeoAnnotationFontObject::ossimGeoAnnotationFontObject() : ossimGeoAnnotationObject(), theCenterGround(), theFont(0), theFontInfo(), theAnnotationFontObject(0) { theFont = (ossimFont*)ossimFontFactoryRegistry::instance()-> getDefaultFont()->dup(); if (!theFont) { ossimNotify(ossimNotifyLevel_WARN) << "ossimGeoAnnotationFontObject::ossimGeoAnnotationFontObject" << " WARNING: No font support..." << endl; } theAnnotationFontObject = new ossimAnnotationFontObject(ossimIpt(0,0), ossimString("")); theAnnotationFontObject->setFont(theFont.get()); } ossimGeoAnnotationFontObject::ossimGeoAnnotationFontObject( const ossimGpt& location, const ossimString& s, const ossimIpt& pixelSize, double rotation, const ossimDpt& scale, const ossimDpt& shear, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) : ossimGeoAnnotationObject(r, g, b), theCenterGround(location), theFont(0), theFontInfo(), theAnnotationFontObject(0) { ossimDpt pt; pt.makeNan(); theAnnotationFontObject = new ossimAnnotationFontObject(pt, s, pixelSize, rotation, scale, shear, r, g, b); } ossimGeoAnnotationFontObject::ossimGeoAnnotationFontObject( const ossimGeoAnnotationFontObject& rhs) : ossimGeoAnnotationObject(rhs), theCenterGround(rhs.theCenterGround), theFont(rhs.theFont.valid()?(ossimFont*)rhs.theFont->dup():(ossimFont*)0), theFontInfo(), theAnnotationFontObject( new ossimAnnotationFontObject( ossimDpt(ossim::nan(), ossim::nan()), rhs.theAnnotationFontObject->theString, rhs.theAnnotationFontObject->thePixelSize, rhs.theAnnotationFontObject->theRotation, ossimDpt(rhs.theAnnotationFontObject->theHorizontalScale, rhs.theAnnotationFontObject->theVerticalScale), ossimDpt(rhs.theAnnotationFontObject->theHorizontalShear, rhs.theAnnotationFontObject->theVerticalShear), rhs.theRed, rhs.theGreen, rhs.theBlue)) { theAnnotationFontObject->setFont(theFont.get()); } ossimGeoAnnotationFontObject::~ossimGeoAnnotationFontObject() { theAnnotationFontObject = 0; theFont = 0; } ossimObject* ossimGeoAnnotationFontObject::dup()const { return new ossimGeoAnnotationFontObject(*this); } void ossimGeoAnnotationFontObject::setFont(ossimFont* font) { theFont = font; theAnnotationFontObject->setFont(theFont.get()); } ossimFont* ossimGeoAnnotationFontObject::getFont() { return theFont.get(); } void ossimGeoAnnotationFontObject::setPointSize(const ossimIpt& size) { if(theAnnotationFontObject.valid()) { theAnnotationFontObject->setPointSize(size); } } void ossimGeoAnnotationFontObject::setRotation(double rotation) { if(theAnnotationFontObject.valid()) { theAnnotationFontObject->setRotation(rotation); } } void ossimGeoAnnotationFontObject::setScale(const ossimDpt& scale) { if(theAnnotationFontObject.valid()) { theAnnotationFontObject->setScale(scale); } } void ossimGeoAnnotationFontObject::setShear(const ossimDpt& shear) { if(theAnnotationFontObject.valid()) { theAnnotationFontObject->setShear(shear); } } void ossimGeoAnnotationFontObject::setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { if(theAnnotationFontObject.valid()) { theAnnotationFontObject->setColor(r, g, b); } } void ossimGeoAnnotationFontObject::transform(ossimImageGeometry* projection) { if(projection) { ossimDpt ipt; projection->worldToLocal(theCenterGround, ipt); theAnnotationFontObject->setCenterPosition(ipt); theAnnotationFontObject->computeBoundingRect(); } } void ossimGeoAnnotationFontObject::setCenterGround(const ossimGpt& gpt) { theCenterGround = gpt; } ossimAnnotationFontObject* ossimGeoAnnotationFontObject::getFontObject() { return theAnnotationFontObject.get(); } void ossimGeoAnnotationFontObject::draw(ossimRgbImage& anImage)const { theAnnotationFontObject->draw(anImage); } void ossimGeoAnnotationFontObject::computeBoundingRect() { theAnnotationFontObject->computeBoundingRect(); } void ossimGeoAnnotationFontObject::getBoundingRect(ossimDrect& rect)const { theAnnotationFontObject->getBoundingRect(rect); } ossimAnnotationObject* ossimGeoAnnotationFontObject::getNewClippedObject( const ossimDrect& /* rect */)const { return (ossimAnnotationObject*)0; } bool ossimGeoAnnotationFontObject::intersects(const ossimDrect& rect)const { return theAnnotationFontObject->intersects(rect); } void ossimGeoAnnotationFontObject::applyScale(double x, double y) { theAnnotationFontObject->applyScale(x,y); } bool ossimGeoAnnotationFontObject::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, "center", theCenterGround.toString().c_str()); kwl.add(prefix, "text", theAnnotationFontObject->getString().c_str()); theFontInfo.saveState(kwl, prefix); return ossimGeoAnnotationObject::saveState(kwl, prefix); } bool ossimGeoAnnotationFontObject::loadState(const ossimKeywordlist& kwl, const char* prefix) { //--- // Base class state must be called first to pick up colors... //--- bool status = ossimGeoAnnotationObject::loadState(kwl, prefix); theAnnotationFontObject->setColor(theRed, theGreen, theBlue); theAnnotationFontObject->setThickness(theThickness); const char* lookup; lookup = kwl.find(prefix, "text"); if (lookup) { theAnnotationFontObject->setString(ossimString(lookup)); } lookup = kwl.find(prefix, "center"); if (lookup) { std::istringstream is(lookup); is >> theCenterGround; } // Get the font information. theFontInfo.loadState(kwl, prefix); // See if we can make a font. ossimRefPtr f = ossimFontFactoryRegistry::instance()-> createFont(theFontInfo); if (f.valid()) { theFont = f; theAnnotationFontObject->setFont(theFont.get()); } theAnnotationFontObject->setGeometryInformation(theFontInfo); return status; } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationGdBitmapFont.cpp000066400000000000000000000076551352751253100247150ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimGeoAnnotationGdBitmapFont.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include RTTI_DEF1(ossimGeoAnnotationGdBitmapFont, "ossimGeoAnnotationGdBitmapFont", ossimGeoAnnotationObject) ossimGeoAnnotationGdBitmapFont::ossimGeoAnnotationGdBitmapFont(const ossimGpt& position, const ossimString &text, ossimGdFontPtr font, unsigned char r, unsigned char g, unsigned char b, long thickness) : ossimGeoAnnotationObject(r, g, b, thickness), thePosition(position) { theProjectedFont = new ossimAnnotationGdBitmapFont(ossimDpt(0,0), text, font, r, g, b, thickness); } ossimGeoAnnotationGdBitmapFont::ossimGeoAnnotationGdBitmapFont(const ossimGeoAnnotationGdBitmapFont& rhs) :ossimGeoAnnotationObject(rhs), theProjectedFont(rhs.theProjectedFont.valid()?(ossimAnnotationGdBitmapFont*)theProjectedFont->dup():(ossimAnnotationGdBitmapFont*)0), thePosition(rhs.thePosition) { } ossimGeoAnnotationGdBitmapFont::~ossimGeoAnnotationGdBitmapFont() { theProjectedFont=0; } ossimObject* ossimGeoAnnotationGdBitmapFont::dup()const { return new ossimGeoAnnotationGdBitmapFont(*this); } void ossimGeoAnnotationGdBitmapFont::applyScale(double x, double y) { thePosition.lond(thePosition.lond()*x); thePosition.latd(thePosition.latd()*y); if(theProjectedFont.valid()) { theProjectedFont->applyScale(x, y); } } std::ostream& ossimGeoAnnotationGdBitmapFont::print(std::ostream& out)const { out << "position: " << thePosition; theProjectedFont->print(out); return out; } void ossimGeoAnnotationGdBitmapFont::draw(ossimRgbImage& anImage)const { theProjectedFont->draw(anImage); } void ossimGeoAnnotationGdBitmapFont::getBoundingRect(ossimDrect& rect)const { theProjectedFont->getBoundingRect(rect); } bool ossimGeoAnnotationGdBitmapFont::intersects(const ossimDrect& rect)const { if(theProjectedFont.valid()) { return theProjectedFont->intersects(rect); } return false; } ossimAnnotationObject* ossimGeoAnnotationGdBitmapFont::getNewClippedObject(const ossimDrect& rect)const { if(intersects(rect)) { if(theProjectedFont.valid()) { return theProjectedFont->getNewClippedObject(rect); } } return (ossimAnnotationObject*)0; } void ossimGeoAnnotationGdBitmapFont::computeBoundingRect() { theProjectedFont->computeBoundingRect(); } void ossimGeoAnnotationGdBitmapFont::transform(ossimImageGeometry* projection) { ossimDpt position; projection->worldToLocal(thePosition, position); theProjectedFont->setUpperLeftTextPosition(position); } void ossimGeoAnnotationGdBitmapFont::setText(const ossimString& text) { theProjectedFont->setText(text); } void ossimGeoAnnotationGdBitmapFont::setFont(ossimGdFontPtr font) { theProjectedFont->setFont(font); } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationLineObject.cpp000066400000000000000000000077331352751253100244120ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimGeoAnnotationLineObject.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include using namespace std; RTTI_DEF1(ossimGeoAnnotationLineObject, "ossimGeoAnnotationLineObject", ossimGeoAnnotationObject) ossimGeoAnnotationLineObject::ossimGeoAnnotationLineObject(const ossimGpt& start, const ossimGpt& end, unsigned char r, unsigned char g, unsigned char b, long thickness) :ossimGeoAnnotationObject(r, g, b, thickness), theProjectedLineObject(0), theStart(start), theEnd(end) { theProjectedLineObject = new ossimAnnotationLineObject(ossimDpt(0,0), ossimDpt(0,0), r, g, b, thickness); } ossimGeoAnnotationLineObject::ossimGeoAnnotationLineObject(const ossimGeoAnnotationLineObject& rhs) :ossimGeoAnnotationObject(rhs), theProjectedLineObject(rhs.theProjectedLineObject?(ossimAnnotationLineObject*)rhs.theProjectedLineObject->dup():(ossimAnnotationLineObject*)0), theStart(rhs.theStart), theEnd(rhs.theEnd) { } ossimGeoAnnotationLineObject::~ossimGeoAnnotationLineObject() { if(theProjectedLineObject) { delete theProjectedLineObject; theProjectedLineObject = 0; } } ossimObject* ossimGeoAnnotationLineObject::dup()const { return new ossimGeoAnnotationLineObject(*this); } void ossimGeoAnnotationLineObject::applyScale(double x, double y) { theStart.lond(theStart.lond()*x); theStart.latd(theStart.latd()*y); theEnd.lond(theEnd.lond()*x); theEnd.latd(theEnd.latd()*y); if(theProjectedLineObject) { theProjectedLineObject->applyScale(x, y); } } void ossimGeoAnnotationLineObject::transform(ossimImageGeometry* projection) { if(projection) { ossimDpt projectedStart; ossimDpt projectedEnd; projection->worldToLocal(theStart, projectedStart); projection->worldToLocal(theEnd, projectedEnd); theProjectedLineObject->setLine(projectedStart, projectedEnd); } } std::ostream& ossimGeoAnnotationLineObject::print(std::ostream& out)const { out << "start ground: " << theStart << endl; out << "end ground: " << theEnd << endl; return out; } void ossimGeoAnnotationLineObject::draw(ossimRgbImage& anImage)const { theProjectedLineObject->draw(anImage); } bool ossimGeoAnnotationLineObject::intersects(const ossimDrect& rect)const { if(theProjectedLineObject) { return theProjectedLineObject->intersects(rect); } return false; } ossimAnnotationObject* ossimGeoAnnotationLineObject::getNewClippedObject(const ossimDrect& rect)const { if(intersects(rect)) { if(theProjectedLineObject) { return theProjectedLineObject->getNewClippedObject(rect); } } return (ossimAnnotationObject*)0; } void ossimGeoAnnotationLineObject::getBoundingRect(ossimDrect& rect)const { theProjectedLineObject->getBoundingRect(rect); } void ossimGeoAnnotationLineObject::computeBoundingRect() { theProjectedLineObject->computeBoundingRect(); } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationMultiEllipseObject.cpp000066400000000000000000000140701352751253100261230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationMultiEllipseObject.cpp 23239 2015-04-08 01:02:44Z gpotts $ #include #include #include #include #include using namespace std; ossimGeoAnnotationMultiEllipseObject::ossimGeoAnnotationMultiEllipseObject() :ossimGeoAnnotationObject(), theProjectedObject(new ossimAnnotationMultiEllipseObject()), theWidthHeight(1,1), theFillFlag(false) { theProjectedObject->setFillFlag(false); } ossimGeoAnnotationMultiEllipseObject::~ossimGeoAnnotationMultiEllipseObject() { if(theProjectedObject) { delete theProjectedObject; theProjectedObject = 0; } } ossimGeoAnnotationMultiEllipseObject::ossimGeoAnnotationMultiEllipseObject(const std::vector& pointList, const ossimDpt& widthHeight, bool enableFill, unsigned char r, unsigned char g, unsigned char b, long thickness) :ossimGeoAnnotationObject(r, g, b, thickness), theProjectedObject(new ossimAnnotationMultiEllipseObject(widthHeight,enableFill, r, g, b, thickness )), thePointList(pointList), theWidthHeight(widthHeight), theFillFlag(enableFill) { } ossimGeoAnnotationMultiEllipseObject::ossimGeoAnnotationMultiEllipseObject(const ossimDpt& widthHeight, bool enableFill, unsigned char r, unsigned char g, unsigned char b, long thickness) :ossimGeoAnnotationObject(r, g, b,thickness), theProjectedObject(new ossimAnnotationMultiEllipseObject(widthHeight,enableFill, r, g, b, thickness )), theWidthHeight(widthHeight), theFillFlag(enableFill) { } ossimGeoAnnotationMultiEllipseObject::ossimGeoAnnotationMultiEllipseObject(const ossimGeoAnnotationMultiEllipseObject& rhs) :ossimGeoAnnotationObject(rhs), theProjectedObject((ossimAnnotationMultiEllipseObject*)rhs.theProjectedObject->dup()), thePointList(rhs.thePointList), theWidthHeight(rhs.theWidthHeight), theFillFlag(rhs.theFillFlag) { } void ossimGeoAnnotationMultiEllipseObject::transform( ossimImageGeometry* projection) { const std::vector::size_type BOUNDS = thePointList.size(); theProjectedObject->resize((ossim_uint32)BOUNDS); for(std::vector::size_type i = 0; i < BOUNDS; ++i) { projection->worldToLocal(thePointList[(int)i], (*theProjectedObject)[(int)i]); } computeBoundingRect(); } void ossimGeoAnnotationMultiEllipseObject::setFillFlag(bool fillFlag) { theProjectedObject->setFillFlag(fillFlag); theFillFlag = fillFlag; } void ossimGeoAnnotationMultiEllipseObject::setColor(unsigned char r, unsigned char g, unsigned char b) { ossimAnnotationObject::setColor(r,g,b); if(theProjectedObject) { theProjectedObject->setColor(r,g,b); } } void ossimGeoAnnotationMultiEllipseObject::setThickness(ossim_uint8 thickness) { ossimAnnotationObject::setThickness(thickness); if(theProjectedObject) { theProjectedObject->setThickness(thickness); } } void ossimGeoAnnotationMultiEllipseObject::applyScale(double /* x */, double /* y */) { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimGeoAnnotationMultiEllipseObject::applyScale NOT IMPLEMENTED" << endl; } void ossimGeoAnnotationMultiEllipseObject::draw(ossimRgbImage& anImage)const { theProjectedObject->draw(anImage); } bool ossimGeoAnnotationMultiEllipseObject::intersects(const ossimDrect& rect)const { return theProjectedObject->intersects(rect); } void ossimGeoAnnotationMultiEllipseObject::setWidthHeight(const ossimDpt& widthHeight) { theWidthHeight = widthHeight; theProjectedObject->setWidthHeight(widthHeight); } std::ostream& ossimGeoAnnotationMultiEllipseObject::print(std::ostream& out)const { theProjectedObject->print(out); return out; } void ossimGeoAnnotationMultiEllipseObject::getBoundingRect(ossimDrect& rect)const { theProjectedObject->getBoundingRect(rect); } void ossimGeoAnnotationMultiEllipseObject::computeBoundingRect() { theProjectedObject->computeBoundingRect(); } ossimObject* ossimGeoAnnotationMultiEllipseObject::dup()const { return new ossimGeoAnnotationMultiEllipseObject(*this); } ossimAnnotationObject* ossimGeoAnnotationMultiEllipseObject::getNewClippedObject( const ossimDrect& /* rect */)const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimGeoAnnotationMultiEllipseObject::getNewClippedObject " << "NOT IMPLEMENTED" << endl; return (ossimAnnotationObject*)dup(); } void ossimGeoAnnotationMultiEllipseObject::addPoint(const ossimGpt& point) { thePointList.push_back(point); } void ossimGeoAnnotationMultiEllipseObject::setPoint(int i, const ossimGpt& point) { thePointList[i] = point; } void ossimGeoAnnotationMultiEllipseObject::resize(ossim_uint32 newSize) { if(newSize) { thePointList.resize(newSize); } } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationMultiPolyLineObject.cpp000066400000000000000000000224421352751253100262630ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationMultiPolyLineObject.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimGeoAnnotationMultiPolyLineObject, "ossimGeoAnnotationMultiPolyLineObject", ossimGeoAnnotationObject); ossimGeoAnnotationMultiPolyLineObject::ossimGeoAnnotationMultiPolyLineObject() : ossimGeoAnnotationObject(), theMultiPolyLine(), theBoundingRect(), theDatum(ossimDatumFactory::instance()->wgs84()), theProjectedPolyLineObject(0) { allocateProjectedPolyLine(); theBoundingRect.makeNan(); } ossimGeoAnnotationMultiPolyLineObject::ossimGeoAnnotationMultiPolyLineObject( const vector& multiPoly, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b, ossim_uint8 thickness) : ossimGeoAnnotationObject(r, g, b, thickness), theMultiPolyLine(multiPoly), theBoundingRect(), theDatum(ossimDatumFactory::instance()->wgs84()), theProjectedPolyLineObject(0) { allocateProjectedPolyLine(); theBoundingRect.makeNan(); } ossimGeoAnnotationMultiPolyLineObject::ossimGeoAnnotationMultiPolyLineObject( const ossimGeoAnnotationMultiPolyLineObject& rhs) :ossimGeoAnnotationObject(rhs), theMultiPolyLine(rhs.theMultiPolyLine), theBoundingRect(rhs.theBoundingRect), theDatum(rhs.theDatum), theProjectedPolyLineObject(rhs.theProjectedPolyLineObject.valid()?(ossimAnnotationMultiPolyLineObject*)rhs.theProjectedPolyLineObject->dup():0) { } ossimObject* ossimGeoAnnotationMultiPolyLineObject::dup()const { return new ossimGeoAnnotationMultiPolyLineObject(*this); } ossimGeoAnnotationMultiPolyLineObject::~ossimGeoAnnotationMultiPolyLineObject() { theProjectedPolyLineObject = 0; } void ossimGeoAnnotationMultiPolyLineObject::applyScale(double /* x */, double /* y */) { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimGeoAnnotationPolyLineObject::applyScale NOT IMPLEMENTED!!!!" << endl; } void ossimGeoAnnotationMultiPolyLineObject::transform(ossimImageGeometry* projection) { if(!projection) { return; } allocateProjectedPolyLine(); //--- // NOTE: // allocateProjectedPolygon() will set theProjectedPolyLineObject to 0 if // theMultiPolyLine is empty (theMultiPolyLine.size() == 0). So check // before accessing pointer to avoid a core dump. //--- if(!theProjectedPolyLineObject) { return; } std::vector& multiPolyLine = theProjectedPolyLineObject->getMultiPolyLine(); ossimGpt tempPoint(0,0, ossim::nan(), theDatum); for(std::vector::size_type polyI = 0; polyI < theMultiPolyLine.size(); ++polyI) { ossimPolyLine polyLine; ossim_uint32 numberOfVertices = theMultiPolyLine[polyI].getNumberOfVertices(); for(ossim_uint32 pointI = 0; pointI < numberOfVertices; ++pointI) { tempPoint.latd(theMultiPolyLine[polyI][pointI].lat); tempPoint.lond(theMultiPolyLine[polyI][pointI].lon); ossimDpt temp; projection->worldToLocal(tempPoint, temp); if(!temp.hasNans()) { multiPolyLine[polyI].addPoint(temp); } } multiPolyLine[polyI].roundToIntegerBounds(true); } } std::ostream& ossimGeoAnnotationMultiPolyLineObject::print(std::ostream& out)const { ossimNotify(ossimNotifyLevel_INFO) << "ossimGeoAnnotationMultiPolyLineObject::print\n" << "Poly line size: " << theMultiPolyLine.size() << endl; return out; } bool ossimGeoAnnotationMultiPolyLineObject::intersects(const ossimDrect& /* rect */)const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimGeoAnnotationMultiPolyObject::intersects NOT IMPLEMENTED" << endl; return false; } ossimAnnotationObject* ossimGeoAnnotationMultiPolyLineObject::getNewClippedObject( const ossimDrect& /* rect */)const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimGeoAnnotationMultiPolyObject::getNewClippedObject " << "NOT IMPLEMENTED" << endl; return (ossimAnnotationObject*)(dup()); } void ossimGeoAnnotationMultiPolyLineObject::draw(ossimRgbImage& anImage)const { if(theProjectedPolyLineObject.valid()) { theProjectedPolyLineObject->draw(anImage); } } void ossimGeoAnnotationMultiPolyLineObject::getBoundingRect(ossimDrect& rect)const { rect = theBoundingRect; } void ossimGeoAnnotationMultiPolyLineObject::addPoint(ossim_uint32 polygonIndex, const ossimGpt& pt) { if(polygonIndex < theMultiPolyLine.size()) { theMultiPolyLine[polygonIndex].addPoint(pt); // we will have to reset the projected polygon theProjectedPolyLineObject = 0; } } void ossimGeoAnnotationMultiPolyLineObject::setMultiPolyLine( const vector& multiPoly) { theMultiPolyLine = multiPoly; theProjectedPolyLineObject = 0; } void ossimGeoAnnotationMultiPolyLineObject::computeBoundingRect() { theBoundingRect.makeNan(); if(theProjectedPolyLineObject.valid()) { theProjectedPolyLineObject->computeBoundingRect(); theProjectedPolyLineObject->getBoundingRect(theBoundingRect); } } bool ossimGeoAnnotationMultiPolyLineObject::isPointWithin(const ossimDpt& imagePoint)const { if(theProjectedPolyLineObject.valid()) { return theProjectedPolyLineObject->isPointWithin(imagePoint); } return false; } void ossimGeoAnnotationMultiPolyLineObject::setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { ossimAnnotationObject::setColor(r, g, b); if(theProjectedPolyLineObject.valid()) { theProjectedPolyLineObject->setColor(r, g, b); } } void ossimGeoAnnotationMultiPolyLineObject::setThickness(ossim_uint8 thickness) { ossimAnnotationObject::setThickness(thickness); if(theProjectedPolyLineObject.valid()) { theProjectedPolyLineObject->setThickness(thickness); } } void ossimGeoAnnotationMultiPolyLineObject::setDatum(const ossimDatum* datum) { theDatum = datum; } const ossimDatum* ossimGeoAnnotationMultiPolyLineObject::getDatum()const { return theDatum; } const std::vector& ossimGeoAnnotationMultiPolyLineObject::getMultiPolyLine() const { return theMultiPolyLine; } std::vector& ossimGeoAnnotationMultiPolyLineObject::getMultiPolyLine() { return theMultiPolyLine; } bool ossimGeoAnnotationMultiPolyLineObject::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossim_uint32 vIdx = 0; for(ossim_uint32 i = 0; i < theMultiPolyLine.size(); ++i) { ossimPolyLine pl = theMultiPolyLine[i]; for(ossim_uint32 j = 0; j < pl.getNumberOfVertices(); ++j) { ossimDpt dpt = pl[j]; std::ostringstream os; os << setprecision(15) << dpt.x << " " << dpt.y << endl; ossimString key = "v"; key += ossimString::toString(vIdx); kwl.add(prefix, key.c_str(), os.str().c_str()); ++vIdx; } } return ossimGeoAnnotationObject::saveState(kwl, prefix); } bool ossimGeoAnnotationMultiPolyLineObject::loadState( const ossimKeywordlist& kwl, const char* prefix) { //--- // Base class state must be called first to pick up colors... //--- bool status = ossimGeoAnnotationObject::loadState(kwl, prefix); ossim_uint32 index = 0; ossimString copyPrefix = prefix; ossim_uint32 count = kwl.getNumberOfSubstringKeys(copyPrefix+ "v[0-9]"); ossim_uint32 numberOfMatches = 0; const ossim_uint32 MAX_INDEX = count + 100; ossimPolyLine pl; while(numberOfMatches < count) { ossimString key = "v"; key += ossimString::toString(index); const char* lookup = kwl.find(prefix, key.c_str()); if (lookup) { ++numberOfMatches; ossimDpt dpt; ossimString x,y; std::istringstream is(lookup); is >> x >> y; pl.addPoint(ossimDpt(x.toDouble(), y.toDouble())); } if (pl.size() == 2) { theMultiPolyLine.push_back(pl); pl.clear(); } ++index; if (index > MAX_INDEX) // Avoid infinite loop... { break; } } return status; } void ossimGeoAnnotationMultiPolyLineObject::allocateProjectedPolyLine() { theProjectedPolyLineObject = 0; if(theMultiPolyLine.size()) { vector polyList(theMultiPolyLine.size()); theProjectedPolyLineObject = new ossimAnnotationMultiPolyLineObject(polyList, theRed, theGreen, theBlue, theThickness); } } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationMultiPolyObject.cpp000066400000000000000000000165211352751253100254540ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationMultiPolyObject.cpp 18435 2010-11-17 19:41:13Z gpotts $ #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimGeoAnnotationMultiPolyObject, "ossimGeoAnnotationMultiPolyObject", ossimGeoAnnotationObject); ossimGeoAnnotationMultiPolyObject::ossimGeoAnnotationMultiPolyObject() : ossimGeoAnnotationObject(), theMultiPolygon(), theBoundingRect(), theFillEnabled(false), theProjectedPolyObject(0) { allocateProjectedPolygon(); theBoundingRect.makeNan(); } ossimGeoAnnotationMultiPolyObject::ossimGeoAnnotationMultiPolyObject(const vector& multiPoly, bool enableFill, unsigned char r, unsigned char g, unsigned char b, long thickness) : ossimGeoAnnotationObject(r, g, b, thickness), theMultiPolygon(multiPoly), theBoundingRect(), theFillEnabled(enableFill), theProjectedPolyObject(0) { allocateProjectedPolygon(); theBoundingRect.makeNan(); } ossimGeoAnnotationMultiPolyObject::ossimGeoAnnotationMultiPolyObject(const ossimGeoAnnotationMultiPolyObject& rhs) : ossimGeoAnnotationObject(rhs), theMultiPolygon(rhs.theMultiPolygon), theBoundingRect(rhs.theBoundingRect), theFillEnabled(rhs.theFillEnabled), theProjectedPolyObject(rhs.theProjectedPolyObject.valid()?(ossimAnnotationMultiPolyObject*)rhs.theProjectedPolyObject->dup():0) { } ossimObject* ossimGeoAnnotationMultiPolyObject::dup()const { return new ossimGeoAnnotationMultiPolyObject(*this); } ossimGeoAnnotationMultiPolyObject::~ossimGeoAnnotationMultiPolyObject() { theProjectedPolyObject = 0; } void ossimGeoAnnotationMultiPolyObject::applyScale(double /* x */, double /* y */) { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimGeoAnnotationPolyObject::applyScale NOT IMPLEMENTED!!!!" << endl; } void ossimGeoAnnotationMultiPolyObject::transform(ossimImageGeometry* projection) { if(!projection) { return; } allocateProjectedPolygon(); //--- // NOTE: // allocateProjectedPolygon() will set theProjectedPolyObject to 0 if // theMultiPolygon is empty (theMultiPolygon.size() == 0). So check before // accessing pointer to avoid a core dump. //--- if (!theProjectedPolyObject) { return; } ossimDpt temp; std::vector visiblePolygons; ossimPolygon polygon; for(ossim_uint32 polyI = 0; polyI < theMultiPolygon.size(); ++polyI) { polygon.clear(); for(ossim_uint32 pointI = 0; pointI < theMultiPolygon[polyI].size(); ++pointI) { projection->worldToLocal(theMultiPolygon[polyI][pointI], temp); if(!temp.hasNans()) { polygon.addPoint(temp); } } theProjectedPolyObject->addPolygon(polyI, polygon); } //--- // Update the bounding rect. //--- theProjectedPolyObject->computeBoundingRect(); } std::ostream& ossimGeoAnnotationMultiPolyObject::print(std::ostream& out)const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimGeoAnnotationMultiPolyObject::print NOT IMPLEMENTED" << endl; return out; } bool ossimGeoAnnotationMultiPolyObject::intersects(const ossimDrect& /* rect */)const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimGeoAnnotationMultiPolyObject::intersects NOT IMPLEMENTED" << endl; return false; } ossimAnnotationObject* ossimGeoAnnotationMultiPolyObject::getNewClippedObject( const ossimDrect& /* rect */)const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimGeoAnnotationMultiPolyObject::getNewClippedObject " << "NOT IMPLEMENTED" << endl; return (ossimAnnotationObject*)(dup()); } void ossimGeoAnnotationMultiPolyObject::draw(ossimRgbImage& anImage)const { if(theProjectedPolyObject.valid()) { theProjectedPolyObject->draw(anImage); } } void ossimGeoAnnotationMultiPolyObject::getBoundingRect(ossimDrect& rect)const { //--- // Should we make non const and call computeBoundingRect if theBoundingRect // is nan? (drb - 20100728) //--- rect = theBoundingRect; if (rect.isNan()&&theProjectedPolyObject.valid()) { theProjectedPolyObject->getBoundingRect(rect); } } void ossimGeoAnnotationMultiPolyObject::addPoint(ossim_uint32 polygonIndex, const ossimGpt& pt) { if(polygonIndex < theMultiPolygon.size()) { theMultiPolygon[polygonIndex].addPoint(pt); // we will have to reset the projected polygon theProjectedPolyObject = 0; } } void ossimGeoAnnotationMultiPolyObject::setMultiPolygon( const vector& multiPoly) { theMultiPolygon = multiPoly; theProjectedPolyObject = 0; } void ossimGeoAnnotationMultiPolyObject::setColor(unsigned char r, unsigned char g, unsigned char b) { ossimAnnotationObject::setColor(r, g, b); if(theProjectedPolyObject.valid()) { theProjectedPolyObject->setColor(r, g, b); } } void ossimGeoAnnotationMultiPolyObject::setThickness(ossim_uint8 thickness) { ossimAnnotationObject::setThickness(thickness); if(theProjectedPolyObject.valid()) { theProjectedPolyObject->setThickness(thickness); } } void ossimGeoAnnotationMultiPolyObject::computeBoundingRect() { theBoundingRect.makeNan(); if(theProjectedPolyObject.valid()) { theProjectedPolyObject->computeBoundingRect(); theProjectedPolyObject->getBoundingRect(theBoundingRect); } } bool ossimGeoAnnotationMultiPolyObject::isPointWithin(const ossimDpt& imagePoint)const { if(theProjectedPolyObject.valid()) { return theProjectedPolyObject->isPointWithin(imagePoint); } return false; } void ossimGeoAnnotationMultiPolyObject::setFillFlag(bool flag) { theFillEnabled = flag; if(theProjectedPolyObject.valid()) { theProjectedPolyObject->setFillFlag(flag); } } void ossimGeoAnnotationMultiPolyObject::allocateProjectedPolygon() { theProjectedPolyObject = 0; if(theMultiPolygon.size()) { vector polyList( theMultiPolygon.size() ); theProjectedPolyObject = new ossimAnnotationMultiPolyObject(polyList, theFillEnabled, theRed, theGreen, theBlue, theThickness); } } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationObject.cpp000066400000000000000000000026061352751253100235740ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationObject.cpp 9094 2006-06-13 19:12:40Z dburken $ #include RTTI_DEF1(ossimGeoAnnotationObject, "ossimGeoAnnotationObject", ossimAnnotationObject) ossimGeoAnnotationObject::ossimGeoAnnotationObject(unsigned char r, unsigned char g, unsigned char b, long thickness) :ossimAnnotationObject(r, g, b, thickness) { } ossimGeoAnnotationObject::ossimGeoAnnotationObject( const ossimGeoAnnotationObject& rhs) : ossimAnnotationObject(rhs) { } ossimGeoAnnotationObject::~ossimGeoAnnotationObject() { } bool ossimGeoAnnotationObject::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimAnnotationObject::saveState(kwl, prefix); } bool ossimGeoAnnotationObject::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimAnnotationObject::loadState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationPolyLineObject.cpp000066400000000000000000000121371352751253100252500ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationPolyLineObject.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include using namespace std; RTTI_DEF1(ossimGeoAnnotationPolyLineObject, "ossimGeoAnnotationPolyLineObject", ossimGeoAnnotationObject) ossimGeoAnnotationPolyLineObject::ossimGeoAnnotationPolyLineObject( const vector& groundPts, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b, ossim_uint8 thickness) :ossimGeoAnnotationObject(r, g, b, thickness), theProjectedMultiLineObject(0) { thePolygon = groundPts; // we will initialize the projected polygon's size // so we don't have to reset it every time we do a // projection // vector projectedPoints(thePolygon.size()); theProjectedMultiLineObject = new ossimAnnotationMultiLineObject(ossimPolyLine(projectedPoints), r, g, b, thickness); } ossimGeoAnnotationPolyLineObject::ossimGeoAnnotationPolyLineObject(const ossimGeoAnnotationPolyLineObject& rhs) :ossimGeoAnnotationObject(rhs), thePolygon(rhs.thePolygon), theProjectedMultiLineObject(rhs.theProjectedMultiLineObject?(ossimAnnotationMultiLineObject*)rhs.theProjectedMultiLineObject->dup():(ossimAnnotationMultiLineObject*)NULL) { } ossimGeoAnnotationPolyLineObject::~ossimGeoAnnotationPolyLineObject() { if(theProjectedMultiLineObject) { delete theProjectedMultiLineObject; theProjectedMultiLineObject = 0; } } ossimObject* ossimGeoAnnotationPolyLineObject::dup()const { return new ossimGeoAnnotationPolyLineObject(*this); } void ossimGeoAnnotationPolyLineObject::applyScale(double x, double y) { for(int i = 0; i < (int)thePolygon.size(); ++i) { thePolygon[i].lond(thePolygon[i].lond()*x); thePolygon[i].latd(thePolygon[i].latd()*y); } if(theProjectedMultiLineObject) { theProjectedMultiLineObject->applyScale(x, y); } } void ossimGeoAnnotationPolyLineObject::transform(ossimImageGeometry* projection) { // make sure it's not null if(!projection) { return; } vector& polyList = theProjectedMultiLineObject->getPolyLineList(); if(polyList.size()) { vector& poly = polyList[0].getVertexList(); const std::vector::size_type BOUNDS = thePolygon.size(); for(std::vector::size_type index=0; index < BOUNDS; ++index) { projection->worldToLocal(thePolygon[index], poly[index]); } // update the bounding rect theProjectedMultiLineObject->computeBoundingRect(); } } std::ostream& ossimGeoAnnotationPolyLineObject::print(std::ostream& out)const { out << "number_of_points: " << thePolygon.size() << endl; if(thePolygon.size() > 0) { for(long index =0; index < (long)(thePolygon.size()-1); ++index) { out << thePolygon[index] << endl; } out << thePolygon[thePolygon.size()-1] << endl; } out << "Projected Polygon" << endl; theProjectedMultiLineObject->print(out); return out; } void ossimGeoAnnotationPolyLineObject::draw(ossimRgbImage& anImage)const { theProjectedMultiLineObject->draw(anImage); } bool ossimGeoAnnotationPolyLineObject::intersects(const ossimDrect& rect)const { if(theProjectedMultiLineObject) { return theProjectedMultiLineObject->intersects(rect); } return false; } ossimAnnotationObject* ossimGeoAnnotationPolyLineObject::getNewClippedObject(const ossimDrect& rect)const { if(theProjectedMultiLineObject) { return theProjectedMultiLineObject->getNewClippedObject(rect); } return (ossimAnnotationObject*)NULL;; } void ossimGeoAnnotationPolyLineObject::getBoundingRect(ossimDrect& rect)const { theProjectedMultiLineObject->getBoundingRect(rect); } void ossimGeoAnnotationPolyLineObject::computeBoundingRect() { theProjectedMultiLineObject->computeBoundingRect(); } void ossimGeoAnnotationPolyLineObject::setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { if(theProjectedMultiLineObject) { theProjectedMultiLineObject->setColor(r, g, b); } } void ossimGeoAnnotationPolyLineObject::setThickness(ossim_uint8 thickness) { if(theProjectedMultiLineObject) { theProjectedMultiLineObject->setThickness(thickness); } } ossim-Miami-2.9.1/src/imaging/ossimGeoAnnotationPolyObject.cpp000066400000000000000000000212131352751253100244330ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimGeoAnnotationPolyObject.cpp 19734 2011-06-06 23:45:36Z dburken $ #include #include #include #include #include #include static const ossimTrace traceDebug(ossimString("ossimGeoAnnotationPolyObject:debug")); RTTI_DEF1(ossimGeoAnnotationPolyObject, "ossimGeoAnnotationPolyObject", ossimGeoAnnotationObject) ossimGeoAnnotationPolyObject::ossimGeoAnnotationPolyObject(bool enableFill, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b, ossim_uint8 thickness) :ossimGeoAnnotationObject(r, g, b, thickness), thePolygon(), theProjectedPolyObject(0), m_PolyType(OSSIM_POLY_EXTERIOR_RING) { theProjectedPolyObject = new ossimAnnotationPolyObject(enableFill, r, g, b, thickness); } ossimGeoAnnotationPolyObject::ossimGeoAnnotationPolyObject( const std::vector& groundPts, bool enableFill, ossim_uint8 r, ossim_uint8 g, ossim_uint8 b, ossim_uint8 thickness) :ossimGeoAnnotationObject(r, g, b, thickness), thePolygon(), theProjectedPolyObject(0), m_PolyType(OSSIM_POLY_EXTERIOR_RING) { thePolygon = groundPts; // we will initialize the projected polygon's size // so we don't have to reset it every time we do a // projection // std::vector projectedPoints(thePolygon.size()); theProjectedPolyObject = new ossimAnnotationPolyObject(projectedPoints, enableFill, r, g, b, thickness); } ossimGeoAnnotationPolyObject::ossimGeoAnnotationPolyObject( const ossimGeoAnnotationPolyObject& rhs) :ossimGeoAnnotationObject(rhs), thePolygon(rhs.thePolygon), theProjectedPolyObject(rhs.theProjectedPolyObject.valid()?(ossimAnnotationPolyObject*)rhs.theProjectedPolyObject->dup():(ossimAnnotationPolyObject*)0), m_PolyType(rhs.m_PolyType) { } ossimGeoAnnotationPolyObject::~ossimGeoAnnotationPolyObject() { theProjectedPolyObject = 0; } ossimObject* ossimGeoAnnotationPolyObject::dup()const { return new ossimGeoAnnotationPolyObject(*this); } void ossimGeoAnnotationPolyObject::applyScale(double x, double y) { for(int i = 0; i < (int)thePolygon.size(); ++i) { thePolygon[i].lond(thePolygon[i].lond()*x); thePolygon[i].latd(thePolygon[i].latd()*y); } if(theProjectedPolyObject.valid()) { theProjectedPolyObject->applyScale(x, y); } } void ossimGeoAnnotationPolyObject::transform(ossimImageGeometry* projection) { // make sure it's not null if(!projection) { return; } ossimPolygon& poly = theProjectedPolyObject->getPolygon(); const std::vector::size_type BOUNDS = thePolygon.size(); for(std::vector::size_type index=0; index < BOUNDS; ++index) { projection->worldToLocal(thePolygon[(int)index], poly[(int)index]); } // update the bounding rect // theProjectedPolyObject->computeBoundingRect(); } std::ostream& ossimGeoAnnotationPolyObject::print(std::ostream& out)const { out << "number_of_points: " << thePolygon.size() << std::endl; if(thePolygon.size() > 0) { for(long index =0; index < (long)(thePolygon.size()-1); ++index) { out << thePolygon[index] << std::endl; } out << thePolygon[thePolygon.size()-1] << std::endl; } out << "Projected Polygon" << std::endl; theProjectedPolyObject->print(out); return out; } void ossimGeoAnnotationPolyObject::draw(ossimRgbImage& anImage)const { if(theProjectedPolyObject.valid()) { theProjectedPolyObject->draw(anImage); } } ossimAnnotationObject* ossimGeoAnnotationPolyObject::getNewClippedObject( const ossimDrect& rect)const { if(theProjectedPolyObject.valid()) { return theProjectedPolyObject->getNewClippedObject(rect); } return (ossimAnnotationObject*)0; } bool ossimGeoAnnotationPolyObject::intersects(const ossimDrect& rect)const { if(theProjectedPolyObject.valid()) { return theProjectedPolyObject->intersects(rect); } return false; } void ossimGeoAnnotationPolyObject::getBoundingRect(ossimDrect& rect)const { rect.makeNan(); if(theProjectedPolyObject.valid()) { theProjectedPolyObject->getBoundingRect(rect); } } void ossimGeoAnnotationPolyObject::computeBoundingRect() { if(theProjectedPolyObject.valid()) { theProjectedPolyObject->computeBoundingRect(); } } const std::vector& ossimGeoAnnotationPolyObject::getPolygon()const { return thePolygon; } void ossimGeoAnnotationPolyObject::setPolygon(const std::vector& poly) { thePolygon = poly; std::vector projectedPoints(thePolygon.size()); if(theProjectedPolyObject.valid()) { theProjectedPolyObject->setPolygon(projectedPoints); } } void ossimGeoAnnotationPolyObject::setFillFlag(bool flag) { if(theProjectedPolyObject.valid()) { theProjectedPolyObject->setFillFlag(flag); } } void ossimGeoAnnotationPolyObject::setColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { ossimAnnotationObject::setColor(r, g, b); if(theProjectedPolyObject.valid()) { theProjectedPolyObject->setColor(r, g, b); } } void ossimGeoAnnotationPolyObject::setThickness(ossim_uint8 thickness) { ossimAnnotationObject::setThickness(thickness); if(theProjectedPolyObject.valid()) { theProjectedPolyObject->setThickness(thickness); } } bool ossimGeoAnnotationPolyObject::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossim_uint32 vIdx = 0; for(ossim_uint32 i = 0; i < thePolygon.size(); ++i) { ossimString key = "v"; key += ossimString::toString(vIdx); kwl.add(prefix, key.c_str(), thePolygon[i].toString().c_str()); ++vIdx; } return ossimGeoAnnotationObject::saveState(kwl, prefix); } bool ossimGeoAnnotationPolyObject::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (!theProjectedPolyObject) { return false; } //--- // Base class state must be called first to pick up colors... //--- bool status = ossimGeoAnnotationObject::loadState(kwl, prefix); ossim_uint32 index = 0; ossimString copyPrefix = prefix; ossim_uint32 count = kwl.getNumberOfSubstringKeys(copyPrefix+"v[0-9]*"); ossim_uint32 numberOfMatches = 0; const ossim_uint32 MAX_INDEX = count + 100; while(numberOfMatches < count) { ossimString key = "v"; key += ossimString::toString(index); const char* lookup = kwl.find(prefix, key.c_str()); if (lookup) { ++numberOfMatches; ossimGpt gpt; std::istringstream is(lookup); is >> gpt; thePolygon.push_back(gpt); } ++index; if (index > MAX_INDEX) // Avoid infinite loop... { break; } } // Set up the annotator. theProjectedPolyObject->setColor(theRed, theGreen, theBlue); theProjectedPolyObject->setThickness(theThickness); std::vector projectedPoints(thePolygon.size()); theProjectedPolyObject->setPolygon(projectedPoints); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeoAnnotationPolyObject::loadState DEBUG:" << std::endl; for (ossim_uint32 i=0; i #include #include #include using namespace std; RTTI_DEF2(ossimGeoAnnotationSource, "ossimGeoAnnotationSource", ossimAnnotationSource, ossimViewInterface); ostream& operator <<(ostream& out, const ossimGeoAnnotationSource& rhs) { const ossimAnnotationSource::AnnotationObjectListType &tempList = rhs.getObjectList(); for(ossim_uint32 index = 0; index < tempList.size(); ++index) { out << "output " << index << endl; tempList[index]->print(out); } return out; } ossimGeoAnnotationSource::ossimGeoAnnotationSource(ossimImageGeometry* geom, bool /* ownsProjectionFlag */ ) :ossimAnnotationSource(), ossimViewInterface(), m_geometry(geom) { ossimViewInterface::theObject = this; } ossimGeoAnnotationSource::ossimGeoAnnotationSource(ossimImageSource* inputSource, ossimImageGeometry* geom, bool /* ownsProjectionFlag */) :ossimAnnotationSource(inputSource), ossimViewInterface(), m_geometry(geom) { ossimViewInterface::theObject = this; } ossimGeoAnnotationSource::~ossimGeoAnnotationSource() { } bool ossimGeoAnnotationSource::addObject(ossimAnnotationObject* anObject) { ossimGeoAnnotationObject *objectToAdd = PTR_CAST(ossimGeoAnnotationObject, anObject); if(objectToAdd) { ossimAnnotationSource::addObject(objectToAdd); if(m_geometry.valid()) { objectToAdd->transform(m_geometry.get()); computeBoundingRect(); } return true; } return false; } void ossimGeoAnnotationSource::setGeometry(ossimImageGeometry* geom) { m_geometry = geom; transformObjects(m_geometry.get()); } bool ossimGeoAnnotationSource::setView(ossimObject* baseObject) { bool result = false; ossimProjection* proj = PTR_CAST(ossimProjection, baseObject); if(proj) { if(m_geometry.valid()) { m_geometry->setProjection(proj); } else { m_geometry = new ossimImageGeometry(0, proj); } setGeometry(m_geometry.get()); result = true; } else { m_geometry = dynamic_cast(baseObject); if ( m_geometry.valid() ) { result = true; } } return result; } ossimObject* ossimGeoAnnotationSource::getView() { return m_geometry.get(); } const ossimObject* ossimGeoAnnotationSource::getView()const { return m_geometry.get(); } void ossimGeoAnnotationSource::computeBoundingRect() { // static const char *MODULE = "ossimAnnotationSource::computeBoundingRect"; theRectangle.makeNan(); if(theAnnotationObjectList.size()>0) { ossimDrect rect; theAnnotationObjectList[0]->getBoundingRect(theRectangle); AnnotationObjectListType::iterator object = (theAnnotationObjectList.begin()+1); while(object != theAnnotationObjectList.end()) { (*object)->getBoundingRect(rect); theRectangle = theRectangle.combine(rect); ++object; } } } void ossimGeoAnnotationSource::transformObjects(ossimImageGeometry* geom) { ossimRefPtr tempGeom = geom; if(!tempGeom) { tempGeom = m_geometry.get(); } if(!tempGeom) return; AnnotationObjectListType::iterator currentObject; currentObject = theAnnotationObjectList.begin(); while(currentObject != theAnnotationObjectList.end()) { // this is safe since we trapped all adds to make // sure that each object added to the list is // geographic. ossimGeoAnnotationObject* object = static_cast((*currentObject).get()); // transform the object to image space. object->transform(m_geometry.get()); ++currentObject; } computeBoundingRect(); } ossimRefPtr ossimGeoAnnotationSource::getImageGeometry() { if(!m_geometry.valid()) { return ossimImageSource::getImageGeometry(); } return m_geometry; } bool ossimGeoAnnotationSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimAnnotationSource::saveState(kwl, prefix); } bool ossimGeoAnnotationSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { m_geometry = new ossimImageGeometry; ossimString newPrefix = ossimString(prefix)+"view_proj."; if(!m_geometry->loadState(kwl, newPrefix.c_str())) { m_geometry = 0; } else { if(!m_geometry->hasProjection()) { m_geometry = 0; } } return ossimAnnotationSource::loadState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimGeoPolyCutter.cpp000066400000000000000000000233501352751253100224440ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimGeoPolyCutter.cpp 22303 2013-07-04 18:15:52Z dburken $ #include #include #include #include #include #include #include using namespace std; static const char* NUMBER_POLYGONS_KW = "number_polygons"; RTTI_DEF2(ossimGeoPolyCutter, "ossimGeoPolyCutter", ossimPolyCutter, ossimViewInterface) ossimGeoPolyCutter::ossimGeoPolyCutter() : ossimPolyCutter(), ossimViewInterface(0), m_viewGeometry(0), m_geoPolygonList(0) { ossimViewInterface::theObject = this; m_geoPolygonList.push_back(ossimGeoPolygon()); } ossimGeoPolyCutter::~ossimGeoPolyCutter() { } bool ossimGeoPolyCutter::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString newPrefix = prefix; for(int i = 0; i < (int)thePolygonList.size();++i) { newPrefix = ossimString(prefix) + "geo_polygon" + ossimString::toString(i)+"."; m_geoPolygonList[i].saveState(kwl, newPrefix.c_str()); } kwl.add(prefix, NUMBER_POLYGONS_KW, static_cast(m_geoPolygonList.size()), true); ossimString fillType = "null_inside"; if(theCutType == OSSIM_POLY_NULL_OUTSIDE) { fillType = "null_outside"; } kwl.add(prefix, "cut_type", fillType.c_str(), true); if(m_viewGeometry.valid()) { ossimString viewPrefix = prefix; viewPrefix += "view."; m_viewGeometry->saveState(kwl, viewPrefix.c_str()); } return ossimImageSourceFilter::saveState(kwl, prefix);; } bool ossimGeoPolyCutter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString copyPrefix(prefix); ossimString polygons = ossimString("^(") + copyPrefix + "geo_polygon[0-9]+.)"; vector keys = kwl.getSubstringKeyList( polygons ); int offset = (int)(copyPrefix+"geo_polygon").size(); std::vector numberList(keys.size()); for(int idx = 0; idx < (int)numberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); numberList[idx] = numberStr.toInt(); } std::sort(numberList.begin(), numberList.end()); ossimString newPrefix; thePolygonList.clear(); for(int i = 0; i < (int)numberList.size();++i) { m_geoPolygonList.push_back(ossimGeoPolygon()); newPrefix = copyPrefix+"geo_polygon"+ossimString::toString(numberList[i])+"."; m_geoPolygonList[i].loadState(kwl, newPrefix.c_str()); } const char* lookup = kwl.find(prefix, "cut_type"); if(lookup) { theCutType = OSSIM_POLY_NULL_INSIDE; ossimString test = lookup; if(test == "null_outside") { theCutType = OSSIM_POLY_NULL_OUTSIDE; } } else { theCutType = OSSIM_POLY_NULL_OUTSIDE; } ossimString viewPrefix = prefix; viewPrefix += "view."; m_viewGeometry = new ossimImageGeometry(); if(m_viewGeometry->loadState(kwl, viewPrefix)) { transformVertices(); } return ossimImageSourceFilter::loadState(kwl, prefix); } void ossimGeoPolyCutter::setPolygon(const vector& polygon, ossim_uint32 index) { if(m_viewGeometry.valid()) { ossimPolyCutter::setPolygon(polygon); invertPolygon(index); } } void ossimGeoPolyCutter::setPolygon(const vector& polygon, ossim_uint32 index) { if(m_viewGeometry.valid()) { ossimPolyCutter::setPolygon(polygon); invertPolygon(index); } } void ossimGeoPolyCutter::setPolygon(const vector& polygon, ossim_uint32 i) { if(i < m_geoPolygonList.size()) { m_geoPolygonList[i] = polygon; transformVertices(i); } } void ossimGeoPolyCutter::setPolygon(const ossimGeoPolygon& polygon, ossim_uint32 i) { if(i < m_geoPolygonList.size()) { m_geoPolygonList[i] = polygon.getVertexList(); transformVertices(i); } } void ossimGeoPolyCutter::addPolygon(const vector& polygon) { m_geoPolygonList.push_back(polygon); thePolygonList.push_back(ossimPolygon()); if(m_viewGeometry.valid()) { transformVertices(((int)m_geoPolygonList.size())-1); } } void ossimGeoPolyCutter::addPolygon(const vector& polygon) { if(m_viewGeometry.valid()) { ossimPolyCutter::addPolygon(polygon); m_geoPolygonList.push_back(ossimGeoPolygon()); invertPolygon((int)thePolygonList.size()-1); } } void ossimGeoPolyCutter::addPolygon(const vector& polygon) { if(m_viewGeometry.valid()) { ossimPolyCutter::addPolygon(polygon); m_geoPolygonList.push_back(ossimGeoPolygon()); invertPolygon((int)thePolygonList.size()-1); } } void ossimGeoPolyCutter::addPolygon(const ossimPolygon& polygon) { if(m_viewGeometry.valid()) { ossimPolyCutter::addPolygon(polygon); m_geoPolygonList.push_back(ossimGeoPolygon()); invertPolygon((int)thePolygonList.size()-1); } } void ossimGeoPolyCutter::addPolygon(const ossimGeoPolygon& polygon) { ossimPolyCutter::addPolygon(ossimPolygon()); m_geoPolygonList.push_back(polygon); if(m_viewGeometry.valid()) { transformVertices(((int)m_geoPolygonList.size())-1); } } void ossimGeoPolyCutter::setNumberOfPolygons(ossim_uint32 count) { if(!count) { m_geoPolygonList.clear(); } else { m_geoPolygonList.resize(count); } ossimPolyCutter::setNumberOfPolygons(count); } std::vector& ossimGeoPolyCutter::getGeoPolygonList() { return m_geoPolygonList; } const std::vector& ossimGeoPolyCutter::getGeoPolygonList() const { return m_geoPolygonList; } void ossimGeoPolyCutter::invertPolygon(int polygonNumber) { if(!m_viewGeometry) return; ossimPolygon& poly = thePolygonList[polygonNumber]; ossimGeoPolygon& gpoly = m_geoPolygonList[polygonNumber]; gpoly.clear(); gpoly.resize(poly.getVertexCount()); int j = 0; for(j = 0; j < (int)poly.getVertexCount(); ++j) { m_viewGeometry->localToWorld(poly[j], gpoly[j]); } } bool ossimGeoPolyCutter::setView(ossimObject* baseObject) { if ( baseObject ) { ossimRefPtr origGeom = m_viewGeometry; ossimRefPtr geom = dynamic_cast(baseObject); if ( geom.valid() ) { m_viewGeometry = geom; } else { ossimRefPtr proj = dynamic_cast(baseObject); if( proj.valid() ) { m_viewGeometry = new ossimImageGeometry( 0, proj.get() ); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimGeoPolyCutter::setView WARNING: Invalid class type!" << std::endl; } } if ( m_viewGeometry.valid() ) { // If view changed transform points... if ( !origGeom || ( m_viewGeometry->isEqualTo( *( (ossimObject*)(origGeom.get()) ) ) == false ) ) { transformVertices(); } } } return m_viewGeometry.valid(); } // End: ossimGeoPolyCutter::setView(ossimObject* baseObject) ossimObject* ossimGeoPolyCutter::getView() { return m_viewGeometry.get(); } const ossimObject* ossimGeoPolyCutter::getView()const { return m_viewGeometry.get(); } void ossimGeoPolyCutter::transformVertices() { if( m_viewGeometry.valid() ) { if( m_geoPolygonList.size() ) { if(m_geoPolygonList.size() != thePolygonList.size()) { thePolygonList.resize(m_geoPolygonList.size()); } int i = 0; int j = 0; for(i = 0; i < (int)m_geoPolygonList.size(); ++i) { ossimGeoPolygon& gpoly = m_geoPolygonList[i]; ossimPolygon& poly = thePolygonList[i]; int nvert = (int)gpoly.size(); if((int)poly.getVertexCount() != nvert) { poly.resize(nvert); } for(j = 0; j < nvert; ++j) { // ossimDpt error; m_viewGeometry->worldToLocal(gpoly[j], poly[j]); // m_viewGeometry->getRoundTripError(ossimIpt(poly[j]), error); // poly[j] = poly[j] + error; poly[j] = ossimDpt(ossim::round(poly[j].x), ossim::round(poly[j].y)); } } computeBoundingRect(); } } } void ossimGeoPolyCutter::transformVertices(int i) { if( m_viewGeometry.valid() ) { ossimGeoPolygon& gpoly = m_geoPolygonList[i]; ossimPolygon& poly = thePolygonList[i]; int nvert = (int)gpoly.size(); if((int)poly.getVertexCount() != nvert) { poly.resize(nvert); } int j = 0; for(j = 0; j < nvert; ++j) { // ossimDpt error; m_viewGeometry->worldToLocal(gpoly[j], poly[j]); // m_viewGeometry->getRoundTripError(poly[j], error); // poly[j] = poly[j] + error; poly[j] = ossimDpt(ossim::round(poly[j].x), ossim::round(poly[j].y)); } computeBoundingRect(); } } ossim-Miami-2.9.1/src/imaging/ossimGeographicAnnotationGrid.cpp000066400000000000000000000230141352751253100246050ustar00rootroot00000000000000#include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimGeographicAnnotationGrid:debug"); ossimGeographicAnnotationGrid::ossimGeographicAnnotationGrid() : ossimAnnotationObject(), theViewProjection(NULL), theGroundRect(0,0,0,0), theDeltaLatSpacing(1.0/60.0), // every minute theDeltaLonSpacing(1.0/60.0) { } void ossimGeographicAnnotationGrid::draw(ossimRgbImage& anImage)const { if(!anImage.getImageData()) { return; } anImage.setDrawColor(theRed, theGreen,theBlue); if((fabs(theDeltaLatSpacing) <= DBL_EPSILON)|| (fabs(theDeltaLonSpacing) <= DBL_EPSILON)) { return; } // ossimDrect imageRect = anImage.getImageData()->getImageRectangle(); // If the view projection exists we will use it to // compute the bounding ground rect and find all lines // that overlap that area in the lat and lon direction // and draw them. // // I the projection doesn't exist we will assume that // the geographic grid to generate will be 0,0 is origin // -180lon and 90lat. // if(theViewProjection.valid()) { ossimRefPtr line=NULL; ossimRefPtr font; line = new ossimAnnotationLineObject(); font = new ossimAnnotationGdBitmapFont(); ossimDpt start; ossimDpt end; ossimGpt groundUpper(0,0,0,theGroundRect.ul().datum()); ossimGpt groundLower(0,0,0,theGroundRect.ul().datum()); double height = theGroundRect.height(); double width = theGroundRect.width(); double lat = theGroundRect.ul().latd(); // ossimDrect imageRect = anImage.getImageData()->getImageRectangle(); double lon; // used for the font spacing ossimDrect boundingRect; // we will go across the longitudinal direction first for(lon = theGroundRect.ul().lond()+theDeltaLonSpacing; lon <= theGroundRect.ur().lond(); lon += theDeltaLonSpacing) { groundUpper.lond(lon); groundUpper.latd(lat); groundLower.lond(lon); groundLower.latd(lat-height); theViewProjection->worldToLineSample(groundUpper, start); theViewProjection->worldToLineSample(groundLower, end); line->setLine(start, end); line->draw(anImage); } lon = theGroundRect.ul().lond(); // now go accross longitude and place the // text in. for(lon = theGroundRect.ul().lond()+theDeltaLonSpacing; lon <= theGroundRect.ur().lond(); lon += theDeltaLonSpacing) { groundUpper.lond(lon); groundUpper.latd(lat); groundLower.lond(lon); groundLower.latd(lat-height); theViewProjection->worldToLineSample(groundUpper, start); theViewProjection->worldToLineSample(groundLower, end); font->setText(ossimDms(groundUpper.lond(), false).toString("ddd@mm'ss.ssss\"C")); font->getBoundingRect(boundingRect); start.y -= boundingRect.height(); font->setCenterTextPosition(start); font->draw(anImage); end.y += boundingRect.height(); font->setCenterText(end, ossimDms(groundLower.lond(), false).toString("ddd@mm'ss.ssssC")); font->draw(anImage); } lon = theGroundRect.ul().lond(); ossimGpt groundLeft; ossimGpt groundRight; // Now go down lat direction for(lat = theGroundRect.ul().latd()-theDeltaLatSpacing; lat >= theGroundRect.lr().latd(); lat -= theDeltaLatSpacing) { groundLeft.lond(lon); groundLeft.latd(lat); groundRight.lond(lon+width); groundRight.latd(lat); theViewProjection->worldToLineSample(groundLeft, start); theViewProjection->worldToLineSample(groundRight, end); line->setLine(start, end); line->draw(anImage); } // now go down lat direction font for(lat = theGroundRect.ul().latd()-theDeltaLatSpacing; lat >= theGroundRect.lr().latd(); lat -= theDeltaLatSpacing) { groundLeft.lond(lon); groundLeft.latd(lat); groundRight.lond(lon+width); groundRight.latd(lat); theViewProjection->worldToLineSample(groundLeft, start); theViewProjection->worldToLineSample(groundRight, end); font->setText(ossimDms(groundLeft.latd()).toString("ddd@mm'ss.ssss\"C")); font->getBoundingRect(boundingRect); start.x -= boundingRect.width()/2.0-1; font->setCenterTextPosition(start); font->draw(anImage); end.x += boundingRect.width()/2.0+1; font->setCenterText(end, ossimDms(groundRight.latd()).toString("ddd@mm'ss.ssssC")); font->draw(anImage); } line = 0; font = 0; } } void ossimGeographicAnnotationGrid::setViewProjectionInformation(ossimMapProjection* projection, const ossimGrect& boundingGroundRect) { static const char* MODULE = "ossimGeographicAnnotationGrid::setViewProjectionInformation"; theViewProjection = projection; // set the ground and then stretch it // to cover which even degree grid we are currently // in. theGroundRect = boundingGroundRect; // find the even degree grid. ossimGrect rect(ossimGpt(90, -180), ossimGpt(-90, 180)); // make sure that it is within the range of the // geographic grid. ossimGrect clipRect = rect.clipToRect(boundingGroundRect); // for easier math we will shift the points so they // are between 0..360Lon and 0..180Lat. This way // we are working with just positive numbers double upperLeftLonShift = clipRect.ul().lond() + 180; double upperLeftLatShift = clipRect.ul().latd() + 90; double lowerRightLonShift = clipRect.lr().lond() + 180; double lowerRightLatShift = clipRect.lr().latd() + 90; // now find the even boundaries double upperLeftLonCell = floor(upperLeftLonShift/theDeltaLonSpacing)* theDeltaLonSpacing; double upperLeftLatCell = floor(upperLeftLatShift/theDeltaLatSpacing)* theDeltaLatSpacing; double lowerRightLonCell = floor(lowerRightLonShift/theDeltaLonSpacing)* theDeltaLonSpacing; double lowerRightLatCell = floor(lowerRightLatShift/theDeltaLatSpacing)* theDeltaLatSpacing; // now adjust them by 1 boundary distance. upperLeftLonCell -= theDeltaLonSpacing; upperLeftLatCell += theDeltaLatSpacing; lowerRightLonCell += theDeltaLonSpacing; lowerRightLatCell -= theDeltaLatSpacing; // now clamp to the range of the lat and lon upperLeftLonCell = (upperLeftLonCell<0?0:upperLeftLonCell); upperLeftLatCell = (upperLeftLatCell>180?180:upperLeftLatCell); lowerRightLonCell = (lowerRightLonCell>360?360:lowerRightLonCell); lowerRightLatCell = (lowerRightLatCell<0?0:lowerRightLatCell); // now shift them back into range upperLeftLonCell -= 180; upperLeftLatCell -= 90; lowerRightLonCell -= 180; lowerRightLatCell -= 90; const ossimDatum* datum = theGroundRect.ul().datum(); theGroundRect = ossimGrect(upperLeftLatCell, upperLeftLonCell, lowerRightLatCell, lowerRightLonCell, datum); if(traceDebug()) { CLOG << "Ground Rect: " << theGroundRect << endl; } computeBoundingRect(); } void ossimGeographicAnnotationGrid::getBoundingRect(ossimDrect& rect)const { rect = theBoundingRect; } void ossimGeographicAnnotationGrid::computeBoundingRect() { static const char* MODULE = "ossimGeographicAnnotationGrid::computeBoundingRect"; if(theViewProjection.valid()) { vector points(4); theViewProjection->worldToLineSample(theGroundRect.ul(), points[0]); theViewProjection->worldToLineSample(theGroundRect.ll(), points[1]); theViewProjection->worldToLineSample(theGroundRect.lr(), points[2]); theViewProjection->worldToLineSample(theGroundRect.ur(), points[3]); // now solve the bounding rect in view space. theBoundingRect = ossimDrect(points); // for now we will add a border for the labelling // of lat lon readouts. We need a better border // computation that checks exactly what we need // based on font sizes. // ossimDpt ul = theBoundingRect.ul(); ossimDpt lr = theBoundingRect.lr(); ossimRefPtr font = new ossimAnnotationGdBitmapFont();; font->setCenterText(ossimDpt(0,0),"ddd@mm'ss.ssssC"); ossimDrect boundingRect; font->getBoundingRect(boundingRect); font = 0; theBoundingRect = ossimDrect(ul.x - boundingRect.width(), ul.y - boundingRect.height(), lr.x + boundingRect.width(), lr.y + boundingRect.height()); if(traceDebug()) { CLOG << " bounding rect: " << theBoundingRect << endl; } } } std::ostream& ossimGeographicAnnotationGrid::print(std::ostream& out)const { return out; } ossim-Miami-2.9.1/src/imaging/ossimGeomFileWriter.cpp000066400000000000000000000104131352751253100225570ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Kenneth Melero // //******************************************************************* // $Id: ossimGeomFileWriter.cpp 20506 2012-01-27 17:02:30Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimGeomFileWriter, "ossimGeomFileWriter", ossimMetadataFileWriter) static const char DEFAULT_FILE_NAME[] = "output.geom"; static ossimTrace traceDebug("ossimGeomFileWriter:debug"); ossimGeomFileWriter::ossimGeomFileWriter() : ossimMetadataFileWriter() {} ossimGeomFileWriter::~ossimGeomFileWriter() {} bool ossimGeomFileWriter::writeFile() { bool status = false; if(theInputConnection) { ossimRefPtr geom = theInputConnection->getImageGeometry(); if(geom.valid()) { //--- // First check the ossimImageGeometry image size and adjust to area of interest if // necessary. The ossimImageGeometry::applyScale method sometimes has rounding // issues so fix it here... //--- if ( geom->getImageSize().hasNans() || ( geom->getImageSize() != theAreaOfInterest.size() ) ) { if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeomFileWriter::writeFile DEBUG:" << "\nAdjusting ossimImageGeometry size to reflect the area of interest." << "\narea of interest size: " << theAreaOfInterest.size() << "\nossimImageGeometry size: " << geom->getImageSize() << std::endl; } geom->setImageSize( theAreaOfInterest.size() ); } // Save the state to keyword list. ossimKeywordlist kwl; geom->saveState(kwl); const ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, geom->getProjection()); if (mapProj) { const char* prefix = "projection."; ossimDpt tiePoint; if (mapProj->isGeographic()) { // Get the ground tie point. ossimGpt gpt; mapProj->lineSampleToWorld(theAreaOfInterest.ul(), gpt); tiePoint = gpt; // Set the units to degrees. kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES), true); } else { // Get the easting northing tie point. mapProj->lineSampleToEastingNorthing(theAreaOfInterest.ul(), tiePoint); // Set the units to meters. kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true); } // Write the tie to keyword list. kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, ossimDpt(tiePoint).toString().c_str(), true); } // matches: if (mapProj) status = kwl.write(theFilename.c_str()); } // matches: if(geom.valid()) } // matches: if(theInputConnection) return status; } void ossimGeomFileWriter::getMetadatatypeList(std::vector& metadatatypeList) const { metadatatypeList.push_back(ossimString("ossim_geometry")); } bool ossimGeomFileWriter::hasMetadataType( const ossimString& metadataType)const { return (metadataType == "ossim_geometry"); } ossim-Miami-2.9.1/src/imaging/ossimGpkgWriterInterface.cpp000066400000000000000000000010721352751253100236020ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Interface for GeoPackage(gpkg) writers. // //---------------------------------------------------------------------------- // $Id$ #include //--- // Explicit constructor. Fix for undefine in sqlite plugin, windows vs14 debug // configuration. //--- ossimGpkgWriterInterface::ossimGpkgWriterInterface() { } ossim-Miami-2.9.1/src/imaging/ossimGridRemapEngine.cpp000066400000000000000000000010061352751253100226710ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains declaration of class // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimGridRemapEngine.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include RTTI_DEF1(ossimGridRemapEngine, "ossimGridRemapEngine", ossimObject); ossim-Miami-2.9.1/src/imaging/ossimGridRemapEngineFactory.cpp000066400000000000000000000025641352751253100242330ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimGridRemapEngineFactory.cc // // Copyright (C) 2001 ImageLinks, Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains implementation of class ossimGridRemapEngineFactory // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimGridRemapEngineFactory.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include //***************************************************************************** // STATIC METHOD: ossimGridRemapEngineFactory::create() // //***************************************************************************** ossimGridRemapEngine* ossimGridRemapEngineFactory::create(const char* s) { if (!s) return 0; if (strcmp(s, "ossimHsvGridRemapEngine") == 0) return new ossimHsvGridRemapEngine; else if (strcmp(s, "ossimRgbGridRemapEngine") == 0) return new ossimRgbGridRemapEngine; else if (strcmp(s, "ossimMonoGridRemapEngine") == 0) return new ossimMonoGridRemapEngine; return 0; } ossim-Miami-2.9.1/src/imaging/ossimGridRemapSource.cpp000066400000000000000000000256711352751253100227420ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimGridRemapper.cc // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains implementation of class ossimGridRemapper. This is // a spacially variant remapper that utilizes a grid for interpolating the // remap value given an image x, y. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimGridRemapSource.cpp 19682 2011-05-31 14:21:20Z dburken $ #include RTTI_DEF1(ossimGridRemapSource, "ossimGridRemapSource", ossimImageSourceFilter); #include #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include using namespace std; static ossimTrace traceExec ("ossimGridRemapSource:exec"); static ossimTrace traceDebug ("ossimGridRemapSource:debug"); static const char* GRID_FILENAME_KW = "grid_remap_file"; static const char* REMAP_ENGINE_KW = "remap_engine"; //***************************************************************************** // DEFAULT CONSTRUCTOR #1: ossimGridRemapper() // //***************************************************************************** ossimGridRemapSource::ossimGridRemapSource() : ossimImageSourceFilter(), theGridFilename (0), theRemapEngine (0), theRemapIsLockedFlag(true), theGridIsFilled(false) { disableSource(); } //***************************************************************************** // CONSTRUCTOR #2: ossimGridRemapper(inputSource) // //***************************************************************************** ossimGridRemapSource::ossimGridRemapSource(ossimImageSource* inputSource, ossimGridRemapEngine* engine) : ossimImageSourceFilter(inputSource), theGridFilename (0), theRemapEngine ((ossimGridRemapEngine*)engine->dup()), theRemapIsLockedFlag(true), theGridIsFilled(false) { disableSource(); } //***************************************************************************** // DESTRUCTOR: ~ossimGridRemapSource // //***************************************************************************** ossimGridRemapSource::~ossimGridRemapSource() { deallocateGrids(); theRemapEngine = 0; } //***************************************************************************** // METHOD: ossimGridRemapSource::initialize // //***************************************************************************** void ossimGridRemapSource::initialize(const ossimDrect& uv_rect, const ossimDpt& grid_spacing) { deallocateGrids(); int num_params; if (theRemapEngine) { num_params = theRemapEngine->getNumberOfParams(); for (int p=0; p(this)); theGridFilename += ".org"; theGridIsFilled = false; } } //***************************************************************************** // METHOD: ossimGridRemapSource::getTile() // // Implementation of virtual method to return remapped tile. // //***************************************************************************** ossimRefPtr ossimGridRemapSource::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if(!theInputConnection) return NULL; //*** // Fetch tile from input source: //*** ossimRefPtr tile = theInputConnection->getTile(rect, resLevel); //--- // Bypass this filter if it is not initialized, or if input tile is bogus: //--- if ((!isSourceEnabled()) || (!tile.valid()) || (!theRemapEngine) || (tile->getDataObjectStatus()==OSSIM_NULL) || (tile->getDataObjectStatus()==OSSIM_EMPTY)) { return tile; } //*** // Insure that the grid has been filled in case nodes were being randomly set //*** if (!theGridIsFilled) { vector::iterator grid = theGrids.begin(); while (grid != theGrids.end()) { // (*grid)->setInterpolationType(ossimDblGrid::BILINEAR); (*grid)->interpolateNullValuedNodes(); grid++; } theGridIsFilled = true; } //*** // hand off the actual remap to the ATB engine. This object knows how to // interpret the grids for the particular remap algorithm selected: //*** theRemapEngine->remapTile(rect.ul(), this, tile); tile->validate(); return tile; } //***************************************************************************** // METHOD: ossimGridRemapSource::loadState() // //***************************************************************************** bool ossimGridRemapSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimGridRemapSource::loadState()"; if (traceExec()) CLOG << "entering..." << endl; bool successful = false; const char* value; //*** // Reset object in preparation for reassignment: //*** deallocateGrids(); theRemapEngine = 0; //*** // Read the remap engine type: //*** value = kwl.find(prefix, REMAP_ENGINE_KW); theRemapEngine = ossimGridRemapEngineFactory::create(value); if (!theRemapEngine) { // CLOG << "ERROR: could not instantiate remap engine. Aborting..." << endl; // if (traceExec()) CLOG << "returning..." << endl; // return false; } //*** // Read the grid filename and open input stream: //*** theGridIsFilled = false; value = kwl.find(prefix, GRID_FILENAME_KW); if (value) { theGridFilename = value; ifstream is (theGridFilename.chars()); //*** // Create an input stream from the grid file to pass to the // corresponding grid: //*** int num_grids = theRemapEngine->getNumberOfParams(); for (int i=0; (iload(is); if (successful) theGrids.push_back(grid); } if (!successful) { CLOG << "ERROR: Encountered errorloading remap grids at file: " << theGridFilename << ". Remapper disabled." << endl; if (traceExec()) CLOG << "returning..." << endl; return false; } theGridIsFilled = true; } //*** // Allow base class to parse list: //*** bool rtn_stat = ossimImageSourceFilter::loadState(kwl, prefix); //*** // Enable source only if KWL read was successful: //*** if (theRemapEngine && successful && rtn_stat) enableSource(); if (traceExec()) CLOG << "returning..." << endl; return rtn_stat; } //***************************************************************************** // METHOD: ossimGridRemapSource::saveState() // //***************************************************************************** bool ossimGridRemapSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { static const char MODULE[] = "ossimGridRemapSource::saveState()"; //*** // No filename indicates that this remapper has not been initialized: //*** if (!theGridFilename) return false; //*** // Write the remap engine type: //*** if (theRemapEngine) kwl.add(prefix, REMAP_ENGINE_KW, theRemapEngine->getClassName()); //*** // Write the filename to the KWL: //*** if (!theGridFilename.empty()) { kwl.add(prefix, GRID_FILENAME_KW, theGridFilename); //*** // Loop over each remap component to write out the grid: //*** ofstream os (theGridFilename.c_str()); bool successful = true; int num_components = theRemapEngine->getNumberOfParams(); for (int p=0; (psave(os, "Remap-Grid"); if (!successful) { CLOG << "ERROR: Encountered saving remap grids to file: " << theGridFilename << ". State not properly saved." << endl; return false; } } return ossimImageSourceFilter::saveState(kwl, prefix); } //***************************************************************************** // METHOD: ossimGridRemapSource::setGridNode() // // Sets a node of the member grid to the value specified. // //***************************************************************************** void ossimGridRemapSource::setGridNode(const ossimDpt& view_pt, const double* value) { int numGrids = (int)theGrids.size(); for (int i=0; isetNearestNode(view_pt, value[i]); theGridIsFilled = false; return; } //***************************************************************************** // METHOD: ossimGridRemapSource::getGrid() // //***************************************************************************** ossimDblGrid* ossimGridRemapSource::getGrid(unsigned int index) { if (index >= theGrids.size()) return 0; return theGrids[index]; } //***************************************************************************** // METHOD: ossimGridRemapSource::deallocateGrids() // //***************************************************************************** void ossimGridRemapSource::deallocateGrids() { static const char MODULE[] = "ossimGridRemapSource::deallocateMemory()"; if (traceExec()) CLOG << "entering..." << endl; vector::iterator grid = theGrids.begin(); while (grid != theGrids.end()) { delete *grid; grid++; } theGrids.clear(); if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimGridRemapSource::setRemapEngine() // //***************************************************************************** void ossimGridRemapSource::setRemapEngine(ossimGridRemapEngine* engine) { theRemapEngine = engine; theGridIsFilled = false; } //***************************************************************************** // METHOD: ossimGridRemapSource::setGridFilename() // //***************************************************************************** void ossimGridRemapSource::setGridFilename(const ossimFilename& grid_filename) { theGridFilename = grid_filename; //*** // NOT COMPLETE### //*** } ossim-Miami-2.9.1/src/imaging/ossimHistoMatchRemapper.cpp000066400000000000000000000250761352751253100234450ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimHistoMatchRemapper.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include #include #include #include #include using namespace std; ossimHistoMatchRemapper::ossimHistoMatchRemapper() : ossimImageSourceFilter() { theBlankTile = NULL; } ossimHistoMatchRemapper::ossimHistoMatchRemapper(ossimImageSource* inputSource, const vector& targetMeanPerBand, const vector& targetSigmaPerBand, const vector& inputMeanPerBand, const vector& inputSigmaPerBand) : ossimImageSourceFilter(inputSource), theTargetMeanPerBand(targetMeanPerBand), theTargetSigmaPerBand(targetSigmaPerBand), theInputMeanPerBand(inputMeanPerBand), theInputSigmaPerBand(inputSigmaPerBand) { theBlankTile = NULL; } ossimHistoMatchRemapper::~ossimHistoMatchRemapper() { } ossimRefPtr ossimHistoMatchRemapper::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr tile; if(theInputConnection) { tile = theInputConnection->getTile(tileRect, resLevel); } if(!tile.valid()) { return NULL; } if((tile.valid() && ((tile->getDataObjectStatus()==OSSIM_NULL) || (tile->getDataObjectStatus()==OSSIM_EMPTY)))) { return tile; } theBlankTile->setOrigin(tileRect.ul()); ossim_uint32 numberOfBands = (ossim_uint32)theInputMeanPerBand.size(); numberOfBands = numberOfBands>tile->getNumberOfBands()?tile->getNumberOfBands():numberOfBands; double result = 0; if(isSourceEnabled()) { long offsetBound = (long)(tile->getWidth()*tile->getHeight()); if(tile->getScalarType() == OSSIM_UCHAR) { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { unsigned char* buf = static_cast(tile->getBuf(band)); for(long offset=0; offset < offsetBound;++offset) { // if the input has no deviation we will just // do a shift to the target mean if(fabs(theInputSigmaPerBand[band]) < FLT_EPSILON) { result = transLean(buf[offset], theInputMeanPerBand[band], theTargetMeanPerBand[band], 0, 255); } else { result = transLeanStretch(buf[offset], theInputMeanPerBand[band], theInputSigmaPerBand[band], theTargetMeanPerBand[band], theTargetSigmaPerBand[band], 0, 255); } result = ((result>255)?255:result); result = ((result<0)?0:result); buf[offset] = (unsigned char)result; } } } } return tile; } void ossimHistoMatchRemapper::initialize() { if(!theInputConnection) { return; } theBlankTile = new ossimImageData(this, theInputConnection->getOutputScalarType(), theInputConnection->getNumberOfOutputBands()); } const vector& ossimHistoMatchRemapper::getInputMeanValues()const { return theInputMeanPerBand; } const vector& ossimHistoMatchRemapper::getInputSigmaValues()const { return theInputSigmaPerBand; } const vector& ossimHistoMatchRemapper::getTargetMeanValues()const { return theTargetMeanPerBand; } const vector& ossimHistoMatchRemapper::getTargetSigmaValues()const { return theTargetSigmaPerBand; } void ossimHistoMatchRemapper::setInputMeanValues(const vector& newValues) { theInputMeanPerBand = newValues; } void ossimHistoMatchRemapper::setInputSigmaValues(const vector& newValues) { theInputSigmaPerBand = newValues; } void ossimHistoMatchRemapper::setTargetMeanValues(const vector& newValues) { theTargetMeanPerBand = newValues; } void ossimHistoMatchRemapper::setTargetSigmaValues(const vector& newValues) { theTargetSigmaPerBand = newValues; } double ossimHistoMatchRemapper::transLean // returns vOut ( double vIn //!< input value to be transformed , double vBias //!< bias value to be removed , double vTarget //!< value that will replace bias , double vMin //!< minimum valid value of vIn (inclusive) , double vMax //!< maximum valid value of vIn (inclusive) ) { // max change const double vDelta = vTarget - vBias; double weight=0.0; // weight max change dependend on proximity to end points if (vIn <= vBias) { weight = fabs((vIn - vMin) / (vBias - vMin)); } else { weight = fabs((vMax - vIn) / (vMax - vBias)); } return (vIn + (vDelta * weight)); }; double ossimHistoMatchRemapper::transLeanStretch // returns vOut ( double vIn //!< input value to be transformed , double vBias //!< bias value to be removed , double vBiasStretch //!< dispersion (+/-) about vBias , double vTarget //!< value that will replace bias , double vTargetStretch //!< dispersion (+/-) about vTarget , double vMin //!< minimum valid value of vIn (inclusive) , double vMax //!< maximum valid value of vIn (inclusive) ) { // line segment end points const double x1 = vMin; const double x2 = vBias - vBiasStretch; const double x3 = vBias + vBiasStretch; const double x4 = vMax; const double y1 = 0.0; const double y2 = (vTarget + vTargetStretch) - (vBias + vBiasStretch); const double y3 = (vTarget - vTargetStretch) - (vBias - vBiasStretch); const double y4 = 0.0; // perform appropriate linear lookup operation based on input value double vOut = vIn; if (vIn <= x2) { vOut = (vIn - x1) * (y2-y1)/(x2-x1) + y1 + vIn; } else if (vIn <= x3) { vOut = (vIn - x2) * (y3-y2)/(x3-x2) + y2 + vIn; } else { vOut = (vIn - x3) * (y4-y3)/(x4-x3) + y3 + vIn; } return vOut; } bool ossimHistoMatchRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { theTargetMeanPerBand.clear(); theTargetSigmaPerBand.clear(); theInputMeanPerBand.clear(); theInputSigmaPerBand.clear(); ossim_uint32 result = kwl.getNumberOfSubstringKeys(ossimString(prefix) + "target_mean[0-9]"); ossim_uint32 numberOfMatches=0; ossim_uint32 index=0; // load target mean while(numberOfMatches < result) { ossimString key = prefix; key += ossimString("target_mean"); key += ossimString::toString(index); const char* lookup = kwl.find(key.c_str()); if(lookup) { theTargetMeanPerBand.push_back(ossimString(lookup).toDouble()); ++numberOfMatches; } ++index; } numberOfMatches = 0; index = 0; result = kwl.getNumberOfSubstringKeys(ossimString(prefix) + "target_sigma[0-9]"); // load target sigma while(numberOfMatches < result) { ossimString key = prefix; key += ossimString("target_sigma"); key += ossimString::toString(index); const char* lookup = kwl.find(key.c_str()); if(lookup) { theTargetSigmaPerBand.push_back(ossimString(lookup).toDouble()); ++numberOfMatches; } ++index; } numberOfMatches = 0; index = 0; result = kwl.getNumberOfSubstringKeys(ossimString(prefix) + "input_mean[0-9]"); // load input mean while(numberOfMatches < result) { ossimString key = prefix; key += ossimString("input_mean"); key += ossimString::toString(index); const char* lookup = kwl.find(key.c_str()); if(lookup) { theInputMeanPerBand.push_back(ossimString(lookup).toDouble()); ++numberOfMatches; } ++index; } numberOfMatches = 0; index = 0; result = kwl.getNumberOfSubstringKeys(ossimString(prefix) + "input_sigma[0-9]"); // load input sigma while(numberOfMatches < result) { ossimString key = prefix; key += ossimString("input_sigma"); key += ossimString::toString(index); const char* lookup = kwl.find(key.c_str()); if(lookup) { theInputSigmaPerBand.push_back(ossimString(lookup).toDouble()); ++numberOfMatches; } ++index; } return true; } bool ossimHistoMatchRemapper::saveState(ossimKeywordlist& kwl, const char* prefix) { ossim_uint32 index = 1; for(index=1;index <= theTargetMeanPerBand.size();++index) { ossimString key = ossimString("target_mean") + ossimString::toString(index); kwl.add(prefix, key.c_str(), theTargetMeanPerBand[index-1], true); } for(index=1;index <= theTargetSigmaPerBand.size();++index) { ossimString key = ossimString("target_sigma") + ossimString::toString(index); kwl.add(prefix, key.c_str(), theTargetSigmaPerBand[index-1], true); } for(index=1;index <= theInputMeanPerBand.size();++index) { ossimString key = ossimString("input_mean") + ossimString::toString(index); kwl.add(prefix, key.c_str(), theInputMeanPerBand[index-1], true); } for(index=1;index <= theInputSigmaPerBand.size();++index) { ossimString key = ossimString("input_sigma") + ossimString::toString(index); kwl.add(prefix, key.c_str(), theInputSigmaPerBand[index-1], true); } return true; } ossim-Miami-2.9.1/src/imaging/ossimHistogramEqualization.cpp000066400000000000000000000405551352751253100242300ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHistogramEqualization.cpp 14110 2009-03-14 15:46:40Z dburken $ #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimHistogramEqualization, "ossimHistogramEqualization", ossimImageSourceHistogramFilter) static const ossimKeyword HISTOGRAM_INVERSE_FLAG_KW("inverse_flag", "specifies whether the inverse should be done for the getTile"); static ossimTrace traceDebug("ossimHistogramEqualization:debug"); ossimHistogramEqualization::ossimHistogramEqualization() : ossimImageSourceHistogramFilter(), theTile(NULL), theAccumulationHistogram(NULL), theInverseFlag(false) { } ossimHistogramEqualization::ossimHistogramEqualization(ossimImageSource* inputSource, ossimRefPtr histogram) : ossimImageSourceHistogramFilter(inputSource, histogram), theTile(0), theAccumulationHistogram(0), theInverseFlag(false) { if(getHistogram().valid()) { theAccumulationHistogram = getHistogram()->createAccumulationLessThanEqual(); initializeLuts(); } } ossimHistogramEqualization::ossimHistogramEqualization(ossimImageSource* inputSource, ossimRefPtr histogram, bool inverseFlag) : ossimImageSourceHistogramFilter(inputSource, histogram), theTile(NULL), theAccumulationHistogram(0), theInverseFlag(inverseFlag) { if(getHistogram().valid()) { theAccumulationHistogram = getHistogram()->createAccumulationLessThanEqual(); initializeLuts(); } } ossimHistogramEqualization::~ossimHistogramEqualization() { deleteLuts(); } ossimRefPtr ossimHistogramEqualization::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return NULL; } ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if(!inputTile.valid()) return inputTile; if (!isSourceEnabled()) { return inputTile; } if(!theTile.valid()) { allocate(); // First time through... } // if (!theTile) throw exception! // Set the origin, resize if needed of the output tile. theTile->setImageRectangleAndBands(inputTile->getImageRectangle(), inputTile->getNumberOfBands()); if( !inputTile.valid() || inputTile->getDataObjectStatus() == OSSIM_NULL || inputTile->getDataObjectStatus() == OSSIM_EMPTY ) { return theTile; } if(!theAccumulationHistogram) { computeAccumulationHistogram(); } if(theForwardLut.size() == 0 || theInverseLut.size() == 0) { initializeLuts(); } if((theForwardLut.size() == 0) || (theInverseLut.size() == 0)) { return inputTile; } switch(inputTile->getScalarType()) { case OSSIM_UCHAR: { return runEqualizationAlgorithm(static_cast(0), inputTile); } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { return runEqualizationAlgorithm(static_cast(0), inputTile); } case OSSIM_SINT16: { return runEqualizationAlgorithm(static_cast(0), inputTile); } case OSSIM_UINT32: { return runEqualizationAlgorithm(static_cast(0), inputTile); } case OSSIM_SINT32: { return runEqualizationAlgorithm(static_cast(0), inputTile); } case OSSIM_FLOAT32: { return runEqualizationAlgorithm(static_cast(0), inputTile); } case OSSIM_FLOAT64: { return runEqualizationAlgorithm(static_cast(0), inputTile); } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramEqualization::getTile WARNING: Unsupported scalar type." << endl; break; } } return inputTile; } void ossimHistogramEqualization::setHistogram(ossimRefPtr histogram) { ossimImageSourceHistogramFilter::setHistogram(histogram); computeAccumulationHistogram(); initializeLuts(); } bool ossimHistogramEqualization::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimImageSourceHistogramFilter::saveState(kwl, prefix); kwl.add(prefix, HISTOGRAM_INVERSE_FLAG_KW, theInverseFlag, true); return result; } bool ossimHistogramEqualization::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimHistogramEqualization::loadState"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << " Entered..." << "\nprefix: " << prefix << endl; } const char* lookup = kwl.find(prefix, HISTOGRAM_INVERSE_FLAG_KW); if(lookup) { theInverseFlag = ossimString(lookup).toBool(); } if(ossimImageSourceHistogramFilter::loadState(kwl, prefix)) { // computeAccumulationHistogram(); // initializeLuts(); } else { return false; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:" << MODULE; this->print(ossimNotify(ossimNotifyLevel_DEBUG)); ossimNotify(ossimNotifyLevel_DEBUG) << "\nExited..." << endl; } return true; } void ossimHistogramEqualization::computeAccumulationHistogram() { if(getHistogram().valid()) { theAccumulationHistogram = getHistogram()->createAccumulationLessThanEqual(); } } template ossimRefPtr ossimHistogramEqualization::runEqualizationAlgorithm(T, ossimRefPtr tile) { if(!theAccumulationHistogram || !getHistogram()) { return tile; } // for now we will always pull from res 0 information ossimRefPtr histo = getHistogram()->getMultiBandHistogram(0); if(histo.valid()) { ossim_uint32 maxBands = ( (histo->getNumberOfBands() > tile->getNumberOfBands())? tile->getNumberOfBands(): histo->getNumberOfBands()); long offsetUpperBound = tile->getHeight()*tile->getWidth(); for(ossim_uint32 band = 0; band < maxBands; ++band) { ossimRefPtr bandHisto = histo->getHistogram(band); T* buf = static_cast(tile->getBuf(band)); double *histoLut = bandgetNumberOfBands())) { if(theInverseFlag) { histoLut = theInverseLut[actualBand]; } if(histoLut) { if(tile->getDataObjectStatus() == OSSIM_FULL) { T minPix = (T)tile->getMinPix(actualBand); T maxPix = (T)tile->getMaxPix(actualBand); for(long offset = 0; offset < offsetUpperBound; ++offset) { ossim_int32 idx = bandHisto->GetIndex(buf[offset]); if(idx>=0) { T value = (T)(histoLut[idx]); //--- // Assign clamping to min max. // // ESH 03/2009 -- Clamping to within min-max fixed //--- buf[offset] = value < minPix ? minPix : (value > maxPix ? maxPix : value); } } } else { T minPix = (T)tile->getMinPix(actualBand); T maxPix = (T)tile->getMaxPix(actualBand); T nullPix = (T)tile->getNullPix(actualBand); for(long offset = 0; offset < offsetUpperBound; ++offset) { ossim_int32 idx = bandHisto->GetIndex(buf[offset]); if((buf[offset]!=nullPix)&&(idx>=0)) { T value = (T)(histoLut[idx]); //--- // Assign clamping to min max. // // ESH 03/2009 -- Clamping to within min-max fixed //--- buf[offset] = value < minPix ? minPix : (value > maxPix ? maxPix : value); } else { buf[offset] = nullPix; } } } } } } } tile->validate(); } return tile; } void ossimHistogramEqualization::initialize() { // Base class will recapture "theInputConnection". ossimImageSourceHistogramFilter::initialize(); if(theTile.valid()) { theTile = NULL; } } void ossimHistogramEqualization::allocate() { theBandList.clear(); if(theTile.valid()) { theTile = NULL; } if(theInputConnection) { theInputConnection->getOutputBandList(theBandList); theTile = ossimImageDataFactory::instance()->create(this, this); if(theTile.valid()) { theTile->initialize(); } } } void ossimHistogramEqualization::initializeLuts() { if(theForwardLut.size() != 0 || theInverseLut.size() != 0) { deleteLuts(); } if(!theAccumulationHistogram||!getHistogram()) { return; } ossimRefPtr accumHisto = theAccumulationHistogram->getMultiBandHistogram(0); ossimRefPtr histogram = getHistogram()->getMultiBandHistogram(0); ossimKeywordlist kwl; theAccumulationHistogram->saveState(kwl); if(accumHisto.valid()&&histogram.valid()) { long maxBands = accumHisto->getNumberOfBands(); for(long band = 0; band < maxBands; ++band) { // first we grab pointers to the histogram and the accumulation // histogram ossimRefPtr h = accumHisto->getHistogram(band); ossimRefPtr h2 = histogram->getHistogram(band); if(h.valid()&&h2.valid()) { // lets get the number of indices. ossim_uint32 numberOfIndices = (ossim_uint32)h2->GetRes(); vector countForInverse(numberOfIndices); theForwardLut.push_back(new double[numberOfIndices]); theInverseLut.push_back(new double[numberOfIndices]); // let's grab the counts array const ossim_int64* histoCounts = h->GetCounts(); // double maxIntensity = h2->GetMaxVal(); double maxIntensity = h2->GetRangeMax(); double maxCount = h->GetMaxCount(); // now pre compute the transforms double *forwardLut = theForwardLut[band]; double *inverseLut = theInverseLut[band]; // double minIntensity = h2->GetMinVal(); double minIntensity = h2->GetRangeMin(); double delta = maxIntensity-minIntensity; ossim_uint32 idx = 0; // clear out the inverse // for(idx = 0; idx < numberOfIndices; ++ idx) { inverseLut[idx] = ossim::nan(); } for(idx = 0; idx < numberOfIndices; ++ idx) { forwardLut[idx] = minIntensity + (histoCounts[idx]/maxCount)*delta; ossim_int32 inverseIdx = h2->GetIndex(forwardLut[idx]); if(inverseIdx >= 0) { inverseLut[inverseIdx] = minIntensity + delta*(idx/(ossim_float32)numberOfIndices); } } // now solve the inverse lut // ossim_uint32 idxStart = 0; ossim_uint32 idxEnd = 0; while((ossim::isnan(inverseLut[idxEnd]))&&(idxEnd 0)){ --idxStart;} if(idxStart !=0) { std::fill(inverseLut+idxStart, inverseLut+numberOfIndices, inverseLut[idxStart]); } idxStart = 0; idxEnd = 0; ossim_float32 valueStart = 0.0; ossim_float32 valueEnd = 0.0; while(idxStart < numberOfIndices) { idxEnd = idxStart; if(ossim::isnan(inverseLut[idxStart])) { while(ossim::isnan(inverseLut[idxEnd])&&(idxEnd < (numberOfIndices-1))) ++idxEnd; double length = (idxEnd-idxStart)+1; valueEnd = inverseLut[idxEnd]; double deltaVal = (valueEnd-valueStart); ossim_uint32 tempIdx = idxStart; ossim_float32 count = 1.0; double t = 0.0; while(tempIdx < idxEnd) { t = (count/length); t = t>1.0?1.0:t; inverseLut[tempIdx] = valueStart + deltaVal*t; ++count; ++tempIdx; } idxStart = idxEnd; valueStart = valueEnd; } else { valueStart = inverseLut[idxStart]; ++idxStart; } } } } } } bool ossimHistogramEqualization::setHistogram(const ossimFilename& filename) { return ossimImageSourceHistogramFilter::setHistogram(filename); } bool ossimHistogramEqualization::getInverseFlag()const { return theInverseFlag; } void ossimHistogramEqualization::setInverseFlag(bool inverseFlag) { theInverseFlag = inverseFlag; } void ossimHistogramEqualization::deleteLuts() { long band = 0; for(band = 0; band < (long)theForwardLut.size(); ++band) { delete [] theForwardLut[band]; } theForwardLut.clear(); for(band = 0; band < (long)theInverseLut.size(); ++band) { delete [] theInverseLut[band]; } theInverseLut.clear(); } const ossimFilename& ossimImageSourceHistogramFilter::getHistogramFilename() const { return theFilename; } std::ostream& ossimHistogramEqualization::print(std::ostream& out) const { // Base class... return ossimImageSourceHistogramFilter::print(out); } ossim-Miami-2.9.1/src/imaging/ossimHistogramMatchFilter.cpp000066400000000000000000000171461352751253100237650ustar00rootroot00000000000000#include #include #include #include #include #include RTTI_DEF1(ossimHistogramMatchFilter, "ossimHistogramMatchFilter", ossimImageSourceFilter); ossimHistogramMatchFilter::ossimHistogramMatchFilter() :ossimImageSourceFilter(), theAutoLoadInputHistogramFlag(false) { theInputHistogramEqualizer = new ossimHistogramEqualization; theTargetHistogramEqualizer = new ossimHistogramEqualization; theInputHistogramEqualizer->setInverseFlag(false); theTargetHistogramEqualizer->setInverseFlag(true); theTargetHistogramEqualizer->connectMyInputTo(0, theInputHistogramEqualizer.get()); } ossimRefPtr ossimHistogramMatchFilter::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { if(isSourceEnabled()) { return theTargetHistogramEqualizer->getTile(tileRect, resLevel); } if(theAutoLoadInputHistogramFlag&& (theInputHistogramFilename=="")) { autoLoadInputHistogram(); } if(theInputConnection) { return theInputConnection->getTile(tileRect, resLevel); } return 0; } void ossimHistogramMatchFilter::setInputHistogram(const ossimFilename& inputHistogram) { theInputHistogramFilename = inputHistogram; theInputHistogramEqualizer->setHistogram(inputHistogram); theInputHistogramEqualizer->initialize(); } void ossimHistogramMatchFilter::setTargetHistogram(const ossimFilename& targetHistogram) { theTargetHistogramFilename = targetHistogram; theTargetHistogramEqualizer->setHistogram(targetHistogram); theTargetHistogramEqualizer->initialize(); } void ossimHistogramMatchFilter::connectInputEvent(ossimConnectionEvent& event) { ossimImageSourceFilter::connectInputEvent(event); if(getInput()) { theInputHistogramEqualizer->connectMyInputTo(0, getInput()); theInputHistogramEqualizer->initialize(); theTargetHistogramEqualizer->initialize(); } else { theInputHistogramEqualizer->disconnectMyInput(0, false, false); theInputHistogramEqualizer->initialize(); theTargetHistogramEqualizer->initialize(); } } void ossimHistogramMatchFilter::disconnectInputEvent(ossimConnectionEvent& event) { ossimImageSourceFilter::disconnectInputEvent(event); if(getInput()) { theInputHistogramEqualizer->connectMyInputTo(0, getInput()); theInputHistogramEqualizer->initialize(); theTargetHistogramEqualizer->initialize(); } else { theInputHistogramEqualizer->disconnectMyInput(0, false, false); theInputHistogramEqualizer->initialize(); theTargetHistogramEqualizer->initialize(); } } void ossimHistogramMatchFilter::initialize() { ossimImageSourceFilter::initialize(); if(theAutoLoadInputHistogramFlag) { if(theInputHistogramFilename == "") { autoLoadInputHistogram(); } } theInputHistogramEqualizer->initialize(); theTargetHistogramEqualizer->initialize(); } void ossimHistogramMatchFilter::setProperty(ossimRefPtr property) { if(!property.valid()) return; ossimString name = property->getName(); if(name == "input_histogram_filename") { setInputHistogram(ossimFilename(property->valueToString())); return; } else if(name == "target_histogram_filename") { setTargetHistogram(ossimFilename(property->valueToString())); return; } else if(name == "auto_load_input_histogram_flag") { theAutoLoadInputHistogramFlag = property->valueToString().toBool(); if(theAutoLoadInputHistogramFlag) { initialize(); } return; } ossimImageSourceFilter::setProperty(property); } ossimRefPtr ossimHistogramMatchFilter::getProperty(const ossimString& name)const { if(name == "input_histogram_filename") { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, theInputHistogramFilename); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); filenameProp->setCacheRefreshBit(); return filenameProp; } else if(name == "target_histogram_filename") { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, theTargetHistogramFilename); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); filenameProp->setCacheRefreshBit(); return filenameProp; } if(name == "auto_load_input_histogram_flag") { ossimBooleanProperty* boolProp = new ossimBooleanProperty(name, theAutoLoadInputHistogramFlag); boolProp->setCacheRefreshBit(); return boolProp; } return ossimImageSourceFilter::getProperty(name); } void ossimHistogramMatchFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("auto_load_input_histogram_flag"); propertyNames.push_back("input_histogram_filename"); propertyNames.push_back("target_histogram_filename"); } bool ossimHistogramMatchFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* inputFilename = kwl.find(prefix, "input_histogram_filename"); const char* targetFilename = kwl.find(prefix, "target_histogram_filename"); const char* autoLoadInputFlag = kwl.find(prefix, "auto_load_input_histogram_flag"); if(autoLoadInputFlag) { theAutoLoadInputHistogramFlag = ossimString(autoLoadInputFlag).toBool(); } if(inputFilename&&!theAutoLoadInputHistogramFlag) { setInputHistogram(ossimFilename(inputFilename)); } else { setInputHistogram(ossimFilename("")); } if(targetFilename) { setTargetHistogram(ossimFilename(targetFilename)); } else { setTargetHistogram(ossimFilename("")); } return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimHistogramMatchFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { if(theAutoLoadInputHistogramFlag) { kwl.add(prefix, "input_histogram_filename", "", true); } else { kwl.add(prefix, "input_histogram_filename", theInputHistogramFilename.c_str(), true); } kwl.add(prefix, "target_histogram_filename", theTargetHistogramFilename.c_str(), true); kwl.add(prefix, "auto_load_input_histogram_flag", theAutoLoadInputHistogramFlag, true); return ossimImageSourceFilter::saveState(kwl, prefix); } void ossimHistogramMatchFilter::autoLoadInputHistogram() { ossimTypeNameVisitor visitor(ossimString("ossimImageHandler"), true, ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS); accept(visitor); if ( visitor.getObjects().size() ) { ossimRefPtr ih = visitor.getObjectAs( 0 ); if ( ih.valid() ) { ossimRefPtr prop = ih->getProperty("histogram_filename"); if( prop.valid() ) { ossimFilename inputHisto = ossimFilename(prop->valueToString()); if( inputHisto.exists() ) { setInputHistogram(inputHisto); } } } } } ossim-Miami-2.9.1/src/imaging/ossimHistogramRemapper.cpp000066400000000000000000001746661352751253100233510ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: // // Histogram remapper class declaration. Derived from ossimTableRemapper. // // Remaps a tile based on mode and histogram clip points. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimHistogramRemapper, "ossimHistogramRemapper", ossimTableRemapper) static ossimTrace traceDebug("ossimHistogramRemapper:debug"); static const char* STRETCH_MODE[] = { "linear_one_piece", "linear_1std_from_mean", "linear_2std_from_mean", "linear_3std_from_mean", "linear_auto_min_max", "linear_auto_percentile", "stretch_unknown" }; static const char NORMALIZED_LOW_CLIP_POINT_KW[] = "normalized_low_clip_point"; static const char NORMALIZED_HIGH_CLIP_POINT_KW[]="normalized_high_clip_point"; static const char MID_POINT_KW[] = "mid_point"; static const char MIN_OUTPUT_VALUE_KW[] = "min_output_value"; static const char MAX_OUTPUT_VALUE_KW[] = "max_output_value"; static const char STRETCH_MODE_KW[] = "stretch_mode"; static const char HISTOGRAM_FILENAME_KW[] = "histogram_filename"; static const char AUTO_MINMAX_BIAS_KW[] = "auto_minmax_bias"; static const char BIAS_FACTOR_KW[] = "bias_factor"; static const char PERCENT_PENETRATION_KW[] = "percent_penetration"; #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimHistogramRemapper.cpp 23182 2015-03-09 14:30:52Z okramer $"; #endif ossimHistogramRemapper::ossimHistogramRemapper() : ossimTableRemapper(), // base class theStretchMode(ossimHistogramRemapper::LINEAR_ONE_PIECE), theDirtyFlag(false), theHistogram(0), theNormalizedLowClipPoint(), theNormalizedHighClipPoint(), theMinOutputValue(), theMaxOutputValue(), theBandList(), theBypassFlag(true), theResetBandIndicesFlag(false), m_percentPenetration(0.05), m_autoMinMaxBias(.006), m_biasFactor(1.0) { setNumberOfInputs(2); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimHistogramRemapper::ossimHistogramRemapper entered...\n"; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << "\n"; #endif } } ossimHistogramRemapper::~ossimHistogramRemapper() { } void ossimHistogramRemapper::initialize() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimHistogramRemapper::initialize entered..." << endl; } theResetBandIndicesFlag = (dynamic_cast(getInput(1))!=0); //--- // Call the base class initialize. // Note: This will reset "theInputConnection" if it changed... //--- ossimTableRemapper::initialize(); //--- // Look for an image histogram source in second input: // This could have been added in the load state before we were connected // to anything. //--- ossimImageHistogramSource* histogramSource = dynamic_cast(getInput(1)); if ( histogramSource && theInputConnection ) { ossimConnectableObject* obj = histogramSource->getInput(0); if ( obj == 0 ) { histogramSource->connectMyInputTo( theInputConnection ); } } // Check the band list to see if it's changes. vector bandList; getOutputBandList(bandList); ossim_uint32 idx = 0; if(theResetBandIndicesFlag) { for(idx = 0; idx < bandList.size();++idx) { bandList[idx] = idx; } } if (theBandList.size() != 0 && bandList.size()) { if (theBandList.size() != bandList.size()) { // Somethings changed. Set everthing back. initializeClips(); setNullCount(); theTable.clear(); } } else { initializeMinMaxOutput(); } // Update the band list with the latest. theBandList = bandList; // Mark dirty to force a table rebuild first get tile. theDirtyFlag = true; verifyEnabled(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimHistogramRemapper::initialize exited..." << endl; } } void ossimHistogramRemapper::reset() { setStretchMode(LINEAR_ONE_PIECE); initializeClips(); theDirtyFlag = true; verifyEnabled(); } void ossimHistogramRemapper::setHistogram(ossimRefPtr histogram) { theHistogram = histogram; setNullCount(); // Note: initializeClips before setNullCount since it relies on clips. initializeClips(); theTable.clear(); theDirtyFlag = true; } bool ossimHistogramRemapper::openHistogram(const ossimFilename& histogram_file) { ossimRefPtr h = new ossimMultiResLevelHistogram(); if (h->importHistogram(histogram_file)) { setHistogram(h); return true; } // Import failed if here! return false; } bool ossimHistogramRemapper::computeHistogram(const ossimIrect& roi) { bool result = false; if ( theInputConnection ) { ossimRefPtr tile = theInputConnection->getTile(roi, 0); if ( tile.valid() ) { ossimDataObjectStatus tile_status = tile->getDataObjectStatus(); if ( (tile_status != OSSIM_NULL) && (tile_status != OSSIM_EMPTY) ) { ossimRefPtr h = new ossimMultiBandHistogram; h->create( theInputConnection ); tile->populateHistogram(h, roi); ossimRefPtr histo = new ossimMultiResLevelHistogram(); histo->addHistogram( h.get() ); setHistogram( histo ); result = true; } } } return result; } ossimRefPtr ossimHistogramRemapper::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr result = 0; if ( theInputConnection ) { if ( theDirtyFlag ) { // Rebuild the table if dirty flag set: makeClean(); } if ( theEnableFlag && !theBypassFlag && theTable.size() ) { //--- // Not bypassed and has a table... // Base handles the rest... //--- result = ossimTableRemapper::getTile(tileRect, resLevel); } else { // Fetch tile from pointer from the input source. result = theInputConnection->getTile(tileRect, resLevel); } } return result; } void ossimHistogramRemapper::setLowNormalizedClipPoint(const ossim_float64& clip) { const ossim_uint32 BANDS = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { setLowNormalizedClipPoint(clip, band); } } void ossimHistogramRemapper::makeClean() { if (theEnableFlag && theDirtyFlag) // Enabled and dirty. { // Always rebuild table if dirty. buildTable(); // Check for internal bypass. verifyEnabled(); // Always clear the dirty flag. theDirtyFlag = false; } } void ossimHistogramRemapper::setLowNormalizedClipPoint(const ossim_float64& clip, ossim_uint32 zero_based_band) { const ossim_uint32 BANDS = getNumberOfInputBands(); if (zero_based_band >= BANDS) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::setLowNormalizedClipPoint ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (BANDS-1) << endl; } if (theNormalizedLowClipPoint.size() != BANDS) { initializeClips(); } if ( clip != theNormalizedLowClipPoint[zero_based_band] && clip < theNormalizedHighClipPoint[zero_based_band] ) { theDirtyFlag = true; theNormalizedLowClipPoint[zero_based_band] = clip; } } void ossimHistogramRemapper::setHighNormalizedClipPoint(const ossim_float64& clip) { const ossim_uint32 BANDS = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { setHighNormalizedClipPoint(clip, band); } } void ossimHistogramRemapper::setHighNormalizedClipPoint( const ossim_float64& clip, ossim_uint32 zero_based_band) { const ossim_uint32 BANDS = getNumberOfInputBands(); if (zero_based_band >= BANDS) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::setHighNormalizedClipPoint ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (BANDS-1) << endl; } if (theNormalizedHighClipPoint.size() != BANDS) { initializeClips(); } if ( clip != theNormalizedHighClipPoint[zero_based_band] && clip > theNormalizedLowClipPoint[zero_based_band] ) { theDirtyFlag = true; theNormalizedHighClipPoint[zero_based_band] = clip; } } void ossimHistogramRemapper::setLowClipPoint(const ossim_float64& clip) { const ossim_uint32 BANDS = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { setLowClipPoint(clip, band); } } void ossimHistogramRemapper::setLowClipPoint(const ossim_float64& clip, ossim_uint32 zero_based_band) { // allow the call to getHistogram to happen this way we can calculate a histogram if // a histosource is connected to this object // // if (!theHistogram) return; ossimRefPtr h = getHistogram(zero_based_band); if (h.valid()) { ossim_float64 d = h->getLowFractionFromValue(clip); if (ossim::isnan(d) == false) { setLowNormalizedClipPoint(d, zero_based_band); } } } void ossimHistogramRemapper::setHighClipPoint(const ossim_float64& clip) { const ossim_uint32 BANDS = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { setHighClipPoint(clip, band); } } void ossimHistogramRemapper::setHighClipPoint(const ossim_float64& clip, ossim_uint32 zero_based_band) { // allow the call to getHistogram to happen this way we can calculate a histogram if // a histosource is connected to this object // // if (!theHistogram) return; ossimRefPtr h = getHistogram(zero_based_band); if (h.valid()) { ossim_float64 d = h->getHighFractionFromValue(clip); if (ossim::isnan(d) == false) { d = 1.0-d; setHighNormalizedClipPoint(d, zero_based_band); } } } void ossimHistogramRemapper::setMidPoint(const ossim_float64& value) { const ossim_uint32 BANDS = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { setMidPoint(value, band); } } void ossimHistogramRemapper::setMidPoint(const ossim_float64& value, ossim_uint32 zero_based_band) { const ossim_uint32 BANDS = getNumberOfInputBands(); if (zero_based_band >= BANDS) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::setMidPoint ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (BANDS-1) << endl; } if (theMidPoint.size() != BANDS) { initializeClips(); } if (theMidPoint[zero_based_band] != value) { theDirtyFlag = true; theMidPoint[zero_based_band] = value; } } void ossimHistogramRemapper::setMinOutputValue(const ossim_float64& value) { const ossim_uint32 BANDS = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { setMinOutputValue(value, band); } } void ossimHistogramRemapper::setMinOutputValue(const ossim_float64& value, ossim_uint32 zero_based_band) { if (theInputConnection) { const ossim_uint32 BANDS = getNumberOfInputBands(); if (zero_based_band >= BANDS) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::setMinOutputValue ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (BANDS-1) << endl; } if (theMinOutputValue.size() != BANDS) { initializeClips(); } if ( value != theMinOutputValue[zero_based_band] && value >= theInputConnection->getMinPixelValue(zero_based_band) && value < theMaxOutputValue[zero_based_band] ) { theDirtyFlag = true; theMinOutputValue[zero_based_band] = value; } } } void ossimHistogramRemapper::setMaxOutputValue(const ossim_float64& value) { const ossim_uint32 BANDS = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { setMaxOutputValue(value, band); } } void ossimHistogramRemapper::setMaxOutputValue(const ossim_float64& value, ossim_uint32 zero_based_band) { if (theInputConnection) { const ossim_uint32 BANDS = getNumberOfInputBands(); if (zero_based_band >= BANDS) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::setMaxOutputValue ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (BANDS-1) << endl; } if (theMaxOutputValue.size() != BANDS) { initializeClips(); } if ( value != theMaxOutputValue[zero_based_band] && value <= theInputConnection->getMaxPixelValue(zero_based_band) && value > theMinOutputValue[zero_based_band] ) { theDirtyFlag = true; theMaxOutputValue[zero_based_band] = value; } } } ossim_float64 ossimHistogramRemapper::getLowNormalizedClipPoint(ossim_uint32 zero_based_band) const { if (theNormalizedLowClipPoint.size() == 0 || zero_based_band >= getNumberOfInputBands()) { return ossim::nan(); } if (zero_based_band >= theNormalizedLowClipPoint.size()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::getLowNormalizedClipPoint ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (theNormalizedLowClipPoint.size()-1) << endl; return ossim::nan(); } return theNormalizedLowClipPoint[zero_based_band]; } ossim_float64 ossimHistogramRemapper::getLowNormalizedClipPoint() const { if (theNormalizedLowClipPoint.size() == 0) { return ossim::nan(); } ossim_float64 d = 0.0; const ossim_uint32 BANDS = (ossim_uint32)theNormalizedLowClipPoint.size(); for (ossim_uint32 band = 0; band < BANDS; ++band) { d += getLowNormalizedClipPoint(band); } return (d / BANDS); } ossim_float64 ossimHistogramRemapper::getHighNormalizedClipPoint(ossim_uint32 zero_based_band) const { if (theNormalizedHighClipPoint.size() == 0 || zero_based_band >= getNumberOfInputBands()) { return ossim::nan(); } if (zero_based_band >= theNormalizedHighClipPoint.size()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::getHighNormalizedClipPoint ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (theNormalizedHighClipPoint.size()-1) << endl; return ossim::nan(); } return theNormalizedHighClipPoint[zero_based_band]; } ossim_float64 ossimHistogramRemapper::getHighNormalizedClipPoint() const { if (theNormalizedHighClipPoint.size() == 0) { return ossim::nan(); } ossim_float64 d = 0.0; const ossim_uint32 BANDS = (ossim_uint32)theNormalizedHighClipPoint.size(); for (ossim_uint32 band = 0; band < BANDS; ++band) { d += getHighNormalizedClipPoint(band); } return (d / BANDS); } ossim_float64 ossimHistogramRemapper::getLowClipPoint(ossim_uint32 zero_based_band) const { if(zero_based_band >= getNumberOfInputBands() || !theHistogram || zero_based_band >= theNormalizedLowClipPoint.size()) { return ossim::nan(); } if (theNormalizedLowClipPoint[zero_based_band] == 0.0) { return getMinPixelValue(zero_based_band); } ossimRefPtr h = getHistogram(zero_based_band); if (h.valid()) { ossim_float64 d = h->LowClipVal(theNormalizedLowClipPoint[zero_based_band]); return d;//floor(d); } return ossim::nan(); } ossim_float64 ossimHistogramRemapper::getLowClipPoint() const { if (theNormalizedLowClipPoint.size() == 0 || !theHistogram) { return ossim::nan(); } ossim_float64 d = 0.0; const ossim_uint32 BANDS = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { d += getLowClipPoint(band); } return (d / BANDS); } ossim_float64 ossimHistogramRemapper::getHighClipPoint(ossim_uint32 zero_based_band) const { if(zero_based_band >= getNumberOfInputBands() || !theHistogram || zero_based_band >= theNormalizedHighClipPoint.size()) { return ossim::nan(); } if (theNormalizedHighClipPoint[zero_based_band] == 1.0) { return getMaxPixelValue(zero_based_band); } ossimRefPtr h = getHistogram(zero_based_band); if (h.valid()) { ossim_float64 d = h->HighClipVal(1.0-theNormalizedHighClipPoint[zero_based_band]); return (d);//ceil(d); } return ossim::nan(); } ossim_float64 ossimHistogramRemapper::getHighClipPoint() const { if (theNormalizedHighClipPoint.size() == 0 || !theHistogram) { return ossim::nan(); } ossim_float64 d = 0.0; const ossim_uint32 BANDS = getNumberOfInputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { d += getHighClipPoint(band); } return (d / BANDS); } ossim_float64 ossimHistogramRemapper::getMidPoint(ossim_uint32 zero_based_band) const { if (theMidPoint.size() == 0 || zero_based_band >= getNumberOfInputBands()) { return ossim::nan(); } if (zero_based_band >= theMidPoint.size()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::getMidPoint ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (theMidPoint.size()-1) << endl; return ossim::nan(); } return theMidPoint[zero_based_band]; } ossim_float64 ossimHistogramRemapper::getMidPoint() const { if (theMidPoint.size() == 0) { return ossim::nan(); } ossim_float64 d = 0.0; const ossim_uint32 BANDS = (ossim_uint32)theMidPoint.size(); for (ossim_uint32 band = 0; band < BANDS; ++band) { d += getMidPoint(band); } return (d / BANDS); } ossim_float64 ossimHistogramRemapper::getMinOutputValue(ossim_uint32 zero_based_band) const { if (theMinOutputValue.size() == 0 || zero_based_band >= getNumberOfInputBands()) { return ossim::nan(); } if (zero_based_band >= theMinOutputValue.size()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::getMinOutputValue ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (theMinOutputValue.size()-1) << endl; return ossim::nan(); } return theMinOutputValue[zero_based_band]; } ossim_float64 ossimHistogramRemapper::getMinOutputValue() const { if (theMinOutputValue.size() == 0) { return ossim::nan(); } ossim_float64 d = 0.0; const ossim_uint32 BANDS = (ossim_uint32)theMinOutputValue.size(); for (ossim_uint32 band = 0; band < BANDS; ++band) { d += getMinOutputValue(band); } return (d / BANDS); } ossim_float64 ossimHistogramRemapper::getMaxOutputValue(ossim_uint32 zero_based_band) const { if (theMaxOutputValue.size() == 0 || zero_based_band >= getNumberOfInputBands()) { return ossim::nan(); } if (zero_based_band >= theMaxOutputValue.size()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::getMaxOutputValue ERROR:" << "\nband " << zero_based_band << " is out of range!" << "\nhighest band: " << (theMaxOutputValue.size()-1) << endl; return ossim::nan(); } return theMaxOutputValue[zero_based_band]; } ossim_float64 ossimHistogramRemapper::getMaxOutputValue() const { if (theMaxOutputValue.size() == 0) { return ossim::nan(); } ossim_float64 d = 0.0; const ossim_uint32 BANDS = (ossim_uint32)theMaxOutputValue.size(); for (ossim_uint32 band = 0; band < BANDS; ++band) { d += getMaxOutputValue(band); } return (d / BANDS); } bool ossimHistogramRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimHistogramRemapper::loadState"; if (traceDebug()) { CLOG << " Entered..." << "\nprefix: " << prefix << endl; } // Load the base class states... bool status = ossimTableRemapper::loadState(kwl, prefix); if (status) { const char* lookup = 0; ossimString keyword; lookup = kwl.find(prefix, HISTOGRAM_FILENAME_KW); if (lookup) { if ( !openHistogram(ossimFilename(lookup)) ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::loadState ERROR!" << "\nCould not open file: " << lookup << "\nReturning..." << endl; return false; } } lookup = kwl.find(prefix, AUTO_MINMAX_BIAS_KW); if(lookup) { m_autoMinMaxBias = ossimString(lookup).toFloat64(); } lookup = kwl.find(prefix, BIAS_FACTOR_KW); if(lookup) { m_biasFactor = ossimString(lookup).toFloat64(); } lookup = kwl.find(prefix, PERCENT_PENETRATION_KW); if(lookup) { m_percentPenetration = ossimString(lookup).toFloat64(); } //--- // Get the band specific keywords. // NOTES: // - This loadState assumes the all keywords will have the same number // of bands. // - The set methods cannot be used here as there may not be a connection // yet that they need. //--- ossim_uint32 bands = 0; lookup = kwl.find(prefix, ossimKeywordNames::NUMBER_BANDS_KW); if (lookup) { bands = ossimString::toUInt32(lookup); } else // For backwards compatibility. { // Use the low clip to find number of bands... keyword = NORMALIZED_LOW_CLIP_POINT_KW; bands = kwl.numberOf(prefix, keyword); } //if(!bands&&theHistogram.valid()) // { // bands = theHistogram->getNumberOfBands(); // } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimHistogramRemapper::loadState DEBUG:" << "\nBands: " << bands << endl; } if (bands) { // Start with fresh clips. initializeClips(bands); for (ossim_uint32 band = 0; band < bands; ++band) { // Get the low clip. keyword = NORMALIZED_LOW_CLIP_POINT_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); lookup = kwl.find(prefix, keyword); if(lookup) { theNormalizedLowClipPoint[band] = atof(lookup); } // Get the high clip. keyword = NORMALIZED_HIGH_CLIP_POINT_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); lookup = kwl.find(prefix, keyword); if(lookup) { theNormalizedHighClipPoint[band] = atof(lookup); } // Get the mid point. keyword = MID_POINT_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); lookup = kwl.find(prefix, keyword); if(lookup) { theMidPoint[band] = atof(lookup); } // Get the min output value. keyword = MIN_OUTPUT_VALUE_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); lookup = kwl.find(prefix, keyword); if(lookup) { theMinOutputValue[band] = atof(lookup); } // Get the max output value. keyword = MAX_OUTPUT_VALUE_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); lookup = kwl.find(prefix, keyword); if(lookup) { theMaxOutputValue[band] = atof(lookup); } } } lookup = kwl.find(prefix, STRETCH_MODE_KW); if (lookup) { ossimString s = lookup; s.downcase(); if (s == STRETCH_MODE[ossimHistogramRemapper::LINEAR_ONE_PIECE]) { theStretchMode = ossimHistogramRemapper::LINEAR_ONE_PIECE; } else if (s == STRETCH_MODE[ossimHistogramRemapper::LINEAR_1STD_FROM_MEAN]) { theStretchMode = ossimHistogramRemapper::LINEAR_1STD_FROM_MEAN; } else if (s == STRETCH_MODE[ossimHistogramRemapper::LINEAR_2STD_FROM_MEAN]) { theStretchMode = ossimHistogramRemapper::LINEAR_2STD_FROM_MEAN; } else if (s == STRETCH_MODE[ossimHistogramRemapper::LINEAR_3STD_FROM_MEAN]) { theStretchMode = ossimHistogramRemapper::LINEAR_3STD_FROM_MEAN; } else if (s == STRETCH_MODE[ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX]) { theStretchMode = ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX; } else if (s == STRETCH_MODE[ossimHistogramRemapper::LINEAR_AUTO_PERCENTILE]) { theStretchMode = ossimHistogramRemapper::LINEAR_AUTO_PERCENTILE; } else { theStretchMode = ossimHistogramRemapper::STRETCH_UNKNOWN; } } // Look for input on second connection: std::string tmpPrefix = ( prefix?prefix:""); tmpPrefix += "input1."; lookup = kwl.find( tmpPrefix.c_str(), ossimKeywordNames::TYPE_KW ); if ( lookup ) { if ( std::string(lookup) == "ossimImageHistogramSource" ) { //--- // NOTE: The ossimImageHistogramSource's input will be connected in // this->initialize() //--- ossimRefPtr ihist = new ossimImageHistogramSource(); if ( ihist->loadState( kwl, tmpPrefix.c_str() ) ) { connectMyInputTo( ihist.get() ); } } } // Always set the dirty flag. theDirtyFlag = true; } verifyEnabled(); if (traceDebug()) { CLOG << "ossimHistogramRemapper::loadState DEBUG:" << *this << "\nExited..." << endl; } return status; } bool ossimHistogramRemapper::saveState(ossimKeywordlist& kwl, const char* prefix) const { if (theHistogram.valid()) { kwl.add(prefix, HISTOGRAM_FILENAME_KW, theHistogram->getHistogramFile().c_str(), true); } kwl.add(prefix, STRETCH_MODE_KW, getStretchModeString().c_str(), true); const ossim_uint32 BANDS = (ossim_uint32)theNormalizedLowClipPoint.size(); kwl.add(prefix, ossimKeywordNames::NUMBER_BANDS_KW, BANDS, true); static const char AUTO_MINMAX_BIAS_KW[] = "auto_minmax_bias"; static const char AUTO_MINMAX_BIAS_FACTOR_KW[] = "auto_minmax_bias_factor"; static const char PERCENT_PENETRATION_KW[] = "percent_penetration"; kwl.add(prefix, AUTO_MINMAX_BIAS_KW, m_autoMinMaxBias, true); kwl.add(prefix, BIAS_FACTOR_KW, m_biasFactor, true); kwl.add(prefix, PERCENT_PENETRATION_KW, m_percentPenetration, true); for (ossim_uint32 band = 0; band < BANDS; ++band) { ossimString keyword; // Save the low clip. keyword = NORMALIZED_LOW_CLIP_POINT_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); kwl.add(prefix, keyword, theNormalizedLowClipPoint[band], true); // Save the high clip. keyword = NORMALIZED_HIGH_CLIP_POINT_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); kwl.add(prefix, keyword, theNormalizedHighClipPoint[band], true); // Save the mid point. keyword = MID_POINT_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); kwl.add(prefix, keyword, theMidPoint[band], true); // Save the min output value. keyword = MIN_OUTPUT_VALUE_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); kwl.add(prefix, keyword, theMinOutputValue[band], true); // Save the max output value. keyword = MAX_OUTPUT_VALUE_KW; keyword += "."; keyword += ossimKeywordNames::BAND_KW; keyword += ossimString::toString(band+1); kwl.add(prefix, keyword, theMaxOutputValue[band], true); } const ossimHistogramSource* obj = dynamic_cast(getInput(1)); if ( obj ) { std::string tmpPrefix = (prefix?prefix:""); tmpPrefix += "input1."; obj->saveState( kwl, tmpPrefix.c_str() ); } return ossimTableRemapper::saveState(kwl, prefix); } void ossimHistogramRemapper::setStretchMode(StretchMode mode) { if (theStretchMode != mode) { theStretchMode = mode; theDirtyFlag = true; } } // Only here for backwards compatibility... void ossimHistogramRemapper::setStretchMode(StretchMode mode, bool rebuildTableFlag) { setStretchMode(mode); if ( rebuildTableFlag ) { makeClean(); } } void ossimHistogramRemapper::setStretchModeAsString(const ossimString& mode, bool rebuildTableFlag ) { setStretchModeAsString(mode); if ( rebuildTableFlag ) { makeClean(); } } void ossimHistogramRemapper::setStretchModeAsString(const ossimString& mode) { if( mode == "linear_one_piece") { setStretchMode(LINEAR_ONE_PIECE); } else if(mode == "linear_1std_from_mean") { setStretchMode(LINEAR_1STD_FROM_MEAN); } else if(mode == "linear_2std_from_mean") { setStretchMode(LINEAR_2STD_FROM_MEAN); } else if(mode == "linear_3std_from_mean") { setStretchMode(LINEAR_3STD_FROM_MEAN); } else if(mode == "linear_auto_min_max") { setStretchMode(LINEAR_AUTO_MIN_MAX); } else if(mode == "linear_auto_percentile") { setStretchMode(LINEAR_AUTO_PERCENTILE); } else { setStretchMode(STRETCH_UNKNOWN); } } void ossimHistogramRemapper::buildTable() { setupTable(); switch(theStretchMode) { case ossimHistogramRemapper::LINEAR_ONE_PIECE: { buildLinearTable(); break; } case ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX: { buildAutoLinearMinMaxTable(); break; } case ossimHistogramRemapper::LINEAR_AUTO_PERCENTILE: { buildAutoLinearPercentileTable(); break; } case ossimHistogramRemapper::LINEAR_1STD_FROM_MEAN: case ossimHistogramRemapper::LINEAR_2STD_FROM_MEAN: case ossimHistogramRemapper::LINEAR_3STD_FROM_MEAN: buildLinearTableStdFromMean(); break; default: if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::buildTable ERROR!" << "\nUnknown stretch type!" << endl; } break; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimHistogramRemapper::buildTable DEBUG:\n" << endl; print(ossimNotify(ossimNotifyLevel_DEBUG)); } } void ossimHistogramRemapper::buildLinearTable() { switch (getOutputScalarType()) { case OSSIM_UINT8: { buildLinearTable(ossim_uint8(0)); break; } case OSSIM_UINT9: case OSSIM_UINT10: case OSSIM_UINT11: case OSSIM_UINT12: case OSSIM_UINT13: case OSSIM_UINT14: case OSSIM_UINT15: case OSSIM_UINT16: { buildLinearTable(ossim_uint16(0)); break; } case OSSIM_SINT16: { buildLinearTable(ossim_sint16(0)); break; } case OSSIM_UINT32: { buildLinearTable(ossim_uint32(0)); break; } case OSSIM_SINT32: { buildLinearTable(ossim_sint32(0)); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT: { buildLinearTable(ossim_float32(0)); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_DOUBLE: { buildLinearTable(ossim_float64(0)); break; } case OSSIM_SCALAR_UNKNOWN: default: { if(traceDebug()) { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::buildLinearTable OSSIM_SCALAR_UNKNOWN!" << endl; } break; } } // End of "switch (theTableType)" } void ossimHistogramRemapper::buildAutoLinearMinMaxTable() { switch (getOutputScalarType()) { case OSSIM_UINT8: { buildAutoLinearMinMaxTableTemplate(ossim_uint8(0)); break; } case OSSIM_UINT9: case OSSIM_UINT10: case OSSIM_UINT11: case OSSIM_UINT12: case OSSIM_UINT13: case OSSIM_UINT14: case OSSIM_UINT15: case OSSIM_UINT16: { buildAutoLinearMinMaxTableTemplate(ossim_uint16(0)); break; } case OSSIM_SINT16: { buildAutoLinearMinMaxTableTemplate(ossim_sint16(0)); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT: { buildAutoLinearMinMaxTableTemplate(ossim_float32(0)); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_DOUBLE: { buildAutoLinearMinMaxTableTemplate(ossim_float64(0)); break; } case OSSIM_SCALAR_UNKNOWN: default: { if(traceDebug()) { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimTableRemapper::buildTable OSSIM_SCALAR_UNKNOWN!" << endl; } break; } } // End of "switch (theTableType)" } void ossimHistogramRemapper::buildAutoLinearPercentileTable() { switch (getOutputScalarType()) { case OSSIM_UINT8: { buildAutoLinearPercentileTableTemplate(ossim_uint8(0)); break; } case OSSIM_UINT9: case OSSIM_UINT10: case OSSIM_UINT11: case OSSIM_UINT12: case OSSIM_UINT13: case OSSIM_UINT14: case OSSIM_UINT15: case OSSIM_UINT16: { buildAutoLinearPercentileTableTemplate(ossim_uint16(0)); break; } case OSSIM_SINT16: { buildAutoLinearPercentileTableTemplate(ossim_sint16(0)); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT: { buildAutoLinearPercentileTableTemplate(ossim_float32(0)); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_DOUBLE: { buildAutoLinearPercentileTableTemplate(ossim_float64(0)); break; } case OSSIM_SCALAR_UNKNOWN: default: { if(traceDebug()) { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::buildAutoLinearPercentileTableTemplate OSSIM_SCALAR_UNKNOWN!" << endl; } break; } } // End of "switch (theTableType)" } template void ossimHistogramRemapper::buildLinearTable(T /* dummy */) { // This builds a native table. theTableType = ossimTableRemapper::NATIVE; const ossim_uint32 BANDS = getNumberOfInputBands(); // Sanity check. if (theNormalizedLowClipPoint.size() != BANDS || !getHistogram(0).valid()) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::buildTable ERROR!" << " Line: " << __LINE__ << endl; } return; } T* table = reinterpret_cast(&theTable.front()); // Finally, build the table... ossim_uint32 index = 0; for (ossim_uint32 band = 0; band < BANDS; ++band) { ossimRefPtr h = getHistogram(band); if (h.get()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimHistogramRemapper::buildLinearTable DEBUG:" << "\nband: " << band << "\nmean: " << h->GetMean() << "\nstddev: " << h->GetStandardDev() << endl; } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::buildTable ERROR!" << " Line: " << __LINE__ << endl; } return; } const T NULL_PIX = static_cast(getNullPixelValue(band)); const T MIN_PIX = static_cast(theMinOutputValue[band]); const T MAX_PIX = static_cast(theMaxOutputValue[band]); const ossim_float64 TARGET_CENTER_PIX = static_cast((MAX_PIX - MIN_PIX) * 0.5); ossim_float64 min_clip_value = h->LowClipVal(theNormalizedLowClipPoint[band]); ossim_float64 max_clip_value = h->HighClipVal(1.0-theNormalizedHighClipPoint[band]); ossim_float64 centerClipValue = min_clip_value * (1.0 - theMidPoint[band]) + (max_clip_value * theMidPoint[band]); ossim_float64 gain = 1.0; ossim_float64 gainLeft = 1.0; ossim_float64 gainRight = 1.0; if (theTableType == ossimTableRemapper::NATIVE) { min_clip_value = floor(min_clip_value); max_clip_value = ceil(max_clip_value); gain = (MAX_PIX-MIN_PIX+1)/(max_clip_value-min_clip_value); gainLeft = (TARGET_CENTER_PIX - MIN_PIX + 1) / (centerClipValue - min_clip_value); gainRight = (MAX_PIX - TARGET_CENTER_PIX + 1) / (max_clip_value - centerClipValue); } else { gain = (MAX_PIX-MIN_PIX)/(max_clip_value-min_clip_value); gainLeft = (TARGET_CENTER_PIX - MIN_PIX) / (centerClipValue - min_clip_value); gainRight = (MAX_PIX - TARGET_CENTER_PIX) / (max_clip_value - centerClipValue); } table[index] = NULL_PIX; ++index; #if 0 /* Please leave for debug. */ std::cout << "table count: " << theTableBinCount << "\nmin_clip_value: " << min_clip_value << "\nmax_clip_value: " << max_clip_value << "\nMIN_PIX: " << MIN_PIX << "\nMAX_PIX: " << MAX_PIX << "\nGAIN: " << gain << "\n"; #endif T pix = MIN_PIX; bool needSkewCheck = std::fabs(theMidPoint[band] - 0.5) > FLT_EPSILON; for (ossim_uint32 pixIndex = 1; pixIndex < theTableBinCount; ++pixIndex) { ossim_float64 p = pix; if (p <= min_clip_value) { p = MIN_PIX; } else if (p >= max_clip_value) { p = MAX_PIX; } else { if (!needSkewCheck) { p = (((p - min_clip_value) * gain) + MIN_PIX); } else if (p < centerClipValue) { p = (((p - min_clip_value) * gainLeft) + MIN_PIX); } else if (p > centerClipValue) { p = (((p - centerClipValue) * gainRight) + TARGET_CENTER_PIX); } else { p = TARGET_CENTER_PIX; } p = (p >= MIN_PIX) ? ((p <= MAX_PIX) ? p : MAX_PIX) : MIN_PIX; } table[index] = static_cast(p); // cout << "table[" << index << "]: " << table[index] << endl; ++pix; ++index; } } // End of band loop. // Clear the dirty flag so the table's not rebuilt on the next getTile. theDirtyFlag = false; } template void ossimHistogramRemapper::buildAutoLinearMinMaxTableTemplate(T /* dummy */) { const ossim_uint32 BANDS = getNumberOfInputBands(); // Sanity check. if (theNormalizedLowClipPoint.size() != BANDS || !getHistogram(0).valid()) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::buildAutoLinearMinMaxTableTemplate ERROR!" << " Line: " << __LINE__ << endl; } return; } ossim_float64 bias = m_autoMinMaxBias*m_biasFactor; for (ossim_uint32 band = 0; band < BANDS; ++band) { ossimRefPtr h = getHistogram(band); T nullPix = static_cast(getNullPixelValue(band)); if(h) { ossim_uint32 n = h->GetRes(); ossim_float64 low = h->GetIndex(h->GetMinVal()); ossim_float64 high = h->GetIndex(h->GetMaxVal()); if(n > 0) { double newCount = 0.0; double nextPercentage = 0.0; double percentage = 0.0; int idx = 0; const ossim_int64* counts = h->GetCounts(); double count = h->ComputeArea(); for(idx = 0; idx < (ossim_int32)(n-1); ++idx) { bool hasValue = (counts[idx] > 0)&&(counts[idx+1]); if(nullPix != idx) { newCount += counts[idx]; } percentage = newCount / count; nextPercentage = (newCount + counts[idx+1]) / count; if (hasValue &&((std::fabs(percentage - bias) < std::fabs(nextPercentage - bias)))) { low = idx+1; break; } } newCount = 0.0; for (idx = n-1; idx > 0; idx--) { bool hasValue = (counts[idx] > 0)&&(counts[idx-1]); newCount += counts[idx]; percentage = newCount / count; nextPercentage = (newCount + counts[idx-1]) / count; if (hasValue && ((std::fabs(percentage - bias) < std::fabs(nextPercentage - bias)))) { high=idx-1; break; } } if(low > high) { low = 0; high = n - 1; } if(theTableType == ossimTableRemapper::NATIVE) { setLowClipPoint(low, band); setHighClipPoint(high, band); } else { setLowClipPoint(h->GetMinValFromIndex(low), band); setHighClipPoint(h->GetMaxValFromIndex(high), band); } } } } buildLinearTable(); } void ossimHistogramRemapper::buildLinearTableStdFromMean() { const ossim_uint32 BANDS = getNumberOfInputBands(); // Sanity check. if (theNormalizedLowClipPoint.size() != BANDS || !getHistogram(0).valid()) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::buildTable ERROR!" << " Line: " << __LINE__ << endl; } return; } ossim_float64 multiplier = 1.0; if (theStretchMode == LINEAR_2STD_FROM_MEAN) { multiplier = 2.0; } else if (theStretchMode == LINEAR_3STD_FROM_MEAN) { multiplier = 3.0; } // Finally, build the table... for (ossim_uint32 band = 0; band < BANDS; ++band) { ossimRefPtr h = getHistogram(band); ossim_float64 mean = 0.0; ossim_float64 stdDev = 0.0; if(h.valid()) { mean = h->GetMean(); stdDev = h->GetStandardDev(); } ossim_float64 lowClip = mean - (stdDev * multiplier); ossim_float64 highClip = mean + (stdDev * multiplier); // Clamp to min/max. if (lowClip < theMinOutputValue[band]) { lowClip = theMinOutputValue[band]; } if (highClip > theMaxOutputValue[band]) { highClip = theMaxOutputValue[band]; } setLowClipPoint(lowClip, band); setHighClipPoint(highClip, band); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimHistogramRemapper::buildLinearStdFromMean DEBUG:" << "\nband: " << band << "\nmean: " << mean << "\nstddev: " << stdDev << "\nlow clip: " << lowClip << "\nhigh clip: " << highClip << endl; } } buildLinearTable(); } template void ossimHistogramRemapper::buildAutoLinearPercentileTableTemplate(T /* dummy */) { const ossim_uint32 BANDS = getNumberOfInputBands(); // Sanity check. if (theNormalizedLowClipPoint.size() != BANDS || !getHistogram(0).valid()) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::buildAutoLinearMinMaxTableTemplate ERROR!" << " Line: " << __LINE__ << endl; } return; } for (ossim_uint32 band = 0; band < BANDS; ++band) { ossimRefPtr h = getHistogram(band); // T nullPix = static_cast(getNullPixelValue(band)); // h->fillInteriorEmptyBins(); if(h.valid()) { ossim_uint32 n = h->GetRes(); ossim_float64 low = h->GetIndex(h->LowClipVal((float)m_percentPenetration)); ossim_float64 high = h->GetIndex(h->HighClipVal((float)m_percentPenetration)); if(low > high) { low = 0; high = n - 1; } if(low < 0) low = 0; if(high < 0) high = n-1; if(theTableType == ossimTableRemapper::NATIVE) { setLowClipPoint(low, band); setHighClipPoint(high, band); } else { setLowClipPoint(h->GetValFromIndex(static_cast(low)), band); setHighClipPoint(h->GetValFromIndex(static_cast(high)), band); } } } buildLinearTable(); } void ossimHistogramRemapper::initializeClips() { initializeClips(getNumberOfInputBands()); } void ossimHistogramRemapper::initializeClips(ossim_uint32 bands) { //--- // NOTE: This method deoes not set theDirtyFlag by design. //--- if (bands) { theNormalizedLowClipPoint.resize(bands); theNormalizedHighClipPoint.resize(bands); theMidPoint.resize(bands); theMinOutputValue.resize(bands); theMaxOutputValue.resize(bands); for (ossim_uint32 band = 0; band < bands; ++band) { theNormalizedLowClipPoint[band] = 0.0; theNormalizedHighClipPoint[band] = 1.0; theMidPoint[band] = 0.5; switch(theOutputScalarType) { case OSSIM_FLOAT32: case OSSIM_FLOAT64: { theMinOutputValue[band] = getMinPixelValue(band); theMaxOutputValue[band] = getMaxPixelValue(band); break; } case OSSIM_SCALAR_UNKNOWN: { theMinOutputValue[band] = 0.0; theMaxOutputValue[band] = 0.0; } default: { theMinOutputValue[band] = ossim::defaultMin(theOutputScalarType);//getMinPixelValue(band); theMaxOutputValue[band] = ossim::defaultMax(theOutputScalarType);//getMaxPixelValue(band); break; } } } } } void ossimHistogramRemapper::initializeMinMaxOutput() { ossim_uint32 nBands = getNumberOfInputBands(); theMinOutputValue.resize(nBands); theMaxOutputValue.resize(nBands); for (ossim_uint32 band = 0; band < nBands; ++band) { // Must have an output scalar type for getMin/Max call. if (theOutputScalarType != OSSIM_SCALAR_UNKNOWN) { theMinOutputValue[band] = ossim::defaultMin(theOutputScalarType);//getMinPixelValue(band); theMaxOutputValue[band] = ossim::defaultMax(theOutputScalarType);//getMaxPixelValue(band); } else { theMinOutputValue[band] = 0.0; theMaxOutputValue[band] = 0.0; } } } void ossimHistogramRemapper::setNullCount() { // This will set the null bucket for all res zero bands to zero! if (getHistogram(0).valid()) { const ossim_uint32 BANDS = theHistogram->getNumberOfBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { ossimRefPtr h = theHistogram->getHistogram(band); if (h.valid()) { h->SetCount(0, 0); } } } } ossimHistogramRemapper::StretchMode ossimHistogramRemapper::getStretchMode() const { return theStretchMode; } ossimString ossimHistogramRemapper::getStretchModeString() const { return ossimString(STRETCH_MODE[theStretchMode]); } ossim_uint32 ossimHistogramRemapper::getNumberOfStretchModes() const { return ossimHistogramRemapper::STRETCH_UNKNOWN; // last index } ossimString ossimHistogramRemapper::getStretchModeString(ossim_uint32 index) const { if (index < ossimHistogramRemapper::STRETCH_UNKNOWN) { return ossimString(STRETCH_MODE[index]); } return ossimString(STRETCH_MODE[ossimHistogramRemapper::STRETCH_UNKNOWN]); } ostream& ossimHistogramRemapper::print(ostream& os) const { os << setiosflags(ios::fixed) << setprecision(15) << "\nossimHistogramRemapper::print:" << "\ntheStretchMode: " << getStretchModeString().c_str() << "\ntheDirtyFlag: " << (theDirtyFlag?"true":"false") << "\ntheBypassFlag: " << (theBypassFlag?"true":"false") << "\ntheHistogram: " << (theHistogram.valid()?"initialized":"null") << "\ntheTableSizeInBytes: " << theTable.size() << endl; const ossim_uint32 BANDS = (ossim_uint32)theNormalizedLowClipPoint.size(); for (ossim_uint32 band = 0; band < BANDS; ++band) { os << "\ntheNormalizedLowClipPoint[" << band << "]: " << theNormalizedLowClipPoint[band] << "\ntheNormalizedHighClipPoint[" << band << "]: " << theNormalizedHighClipPoint[band] << "\ntheMidPoint[" << band << "]: " << theMidPoint[band] << "\ntheMinOutputValue[" << band << "]: " << theMinOutputValue[band] << "\ntheMaxOutputValue[" << band << "]: " << theMaxOutputValue[band] << endl; } for (ossim_uint32 i = 0; i < theBandList.size(); ++i) { os << "theBandList[" << i << "]: " << theBandList[i] << endl; } // Note: To set table call ossimTableRemapper::print or turn trace on // for "ossimTableRemapper:debug" // ossimTableRemapper::print(os); return os; } void ossimHistogramRemapper::setupTable() { const ossim_uint32 BANDS = getNumberOfInputBands(); ossim_uint32 values_per_band = 0; ossim_uint32 bytes_per_pixel = 0; switch (theOutputScalarType) { case OSSIM_UINT8: values_per_band = 256; // 2 ^ 8 bytes_per_pixel = 1; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT9: values_per_band = 512; // 2 ^ 9 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT10: values_per_band = 1024; // 2 ^ 10 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT11: values_per_band = 2048; // 2 ^ 11 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT12: values_per_band = 4096; // 2 ^ 12 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT13: values_per_band = 8192; // 2 ^ 13 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT14: values_per_band = 16384; // 2 ^ 14 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT15: values_per_band = 32768; // 2 ^ 15 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT16: case OSSIM_SINT16: values_per_band = 65536; // 2 ^ 16 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT32: case OSSIM_SINT32: values_per_band = 65536; // 2 ^ 16 bytes_per_pixel = 4; theTableType = ossimTableRemapper::MIN_MAX; break; case OSSIM_NORMALIZED_FLOAT: { bytes_per_pixel = 4; theTableType = ossimTableRemapper::NORMALIZED; break; } case OSSIM_FLOAT: bytes_per_pixel = 4; values_per_band = 65536; // 2 ^ 16 theTableType = ossimTableRemapper::MIN_MAX; break; case OSSIM_NORMALIZED_DOUBLE: { bytes_per_pixel = 8; values_per_band = 65536; // 2 ^ 16 theTableType = ossimTableRemapper::NORMALIZED; break; } case OSSIM_DOUBLE: bytes_per_pixel = 8; values_per_band = 65536; // 2 ^ 16 theTableType = ossimTableRemapper::MIN_MAX; break; default: break; } if (theNormalizedLowClipPoint.size() == 0) { initializeClips(BANDS); } if ( theOutputScalarType == OSSIM_FLOAT || theOutputScalarType == OSSIM_DOUBLE || theOutputScalarType == OSSIM_NORMALIZED_FLOAT || theOutputScalarType == OSSIM_NORMALIZED_DOUBLE ) { for (ossim_uint32 band = 0; band < BANDS; ++band) { ossimRefPtr h = getHistogram(band); if (h.valid()) { if (h->GetRes() > static_cast(values_per_band)) { values_per_band = h->GetRes(); } } } } theTableBinCount = values_per_band; theTableBandCount = BANDS; ossim_uint32 size_in_bytes = values_per_band * BANDS * bytes_per_pixel; theTable.resize(size_in_bytes); ossimImageSource* input = dynamic_cast(getInput()); double minPix = ossim::defaultMin(getOutputScalarType()); double maxPix = ossim::defaultMax(getOutputScalarType()); if(input) { //--- // Last check for NaNs in key data members and set to some default if so. // This could occur if someone stripped a keyword list down to a minimal // set of keywords. //--- for (ossim_uint32 band = 0; band < BANDS; ++band) { minPix = input->getMinPixelValue(band); maxPix = input->getMaxPixelValue(band); if ( ossim::isnan(theMinOutputValue[band]) ) { theMinOutputValue[band] = minPix; } if ( ossim::isnan(theMaxOutputValue[band]) ) { theMaxOutputValue[band] = maxPix; } } } else { //--- // Last check for NaNs in key data members and set to some default if so. // This could occur if someone stripped a keyword list down to a minimal // set of keywords. //--- for (ossim_uint32 band = 0; band < BANDS; ++band) { if ( ossim::isnan(theMinOutputValue[band]) ) { theMinOutputValue[band] = minPix; } if ( ossim::isnan(theMaxOutputValue[band]) ) { theMaxOutputValue[band] = maxPix; } } } } void ossimHistogramRemapper::verifyEnabled() { //--- // Since this filter can be constructed with no input connection do not // output and error, simply return. //--- setBypassFlag(true); //if (theInputConnection) { #if 1 // Start off bypassed. if (theStretchMode != STRETCH_UNKNOWN) { if(theHistogram.valid()) { setBypassFlag(false); } /* const ossim_uint32 BANDS = (ossim_uint32)theNormalizedLowClipPoint.size(); for (ossim_uint32 band = 0; band < BANDS; ++band) { //const double MIN = ossimTableRemapper::getMinPixelValue(band); //const double MAX = ossimTableRemapper::getMaxPixelValue(band); if ( theNormalizedLowClipPoint[band] != 0.0 || theNormalizedHighClipPoint[band] != 1.0 ) // theMinOutputValue[band] != MIN || //theMaxOutputValue[band] != MAX ) { // Need to turn filter on. setBypassFlag(false); break; } } */ } #endif } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimHistogramRemapper::verifyEnabled theBypassFlag: " << (theBypassFlag ? "true" : "false") << endl; } } ossimRefPtr ossimHistogramRemapper::getHistogram() { return ossimRefPtr(theHistogram.get()); } ossimRefPtr ossimHistogramRemapper::getHistogram()const { return ossimRefPtr(theHistogram.get()); } ossimRefPtr ossimHistogramRemapper::getHistogram(ossim_uint32 zero_based_band, ossim_uint32 res_level) const { ossim_uint32 histogram_band = getHistogramBand(zero_based_band); if(!theHistogram.valid()) { const ossimHistogramSource* source = dynamic_cast(getInput(1)); if(source) { theHistogram = const_cast(source)->getHistogram(); } } if (theHistogram.valid()) { if (histogram_band < theHistogram->getNumberOfBands()) { return theHistogram->getHistogram(histogram_band, res_level); } } return 0; } ossimFilename ossimHistogramRemapper::getHistogramFile() const { if (theHistogram.valid()) { return theHistogram->getHistogramFile(); } return ossimFilename::NIL; } ossim_uint32 ossimHistogramRemapper::getHistogramBand(ossim_uint32 input_band) const { if(theResetBandIndicesFlag) return input_band; vector bandList; getOutputBandList(bandList); const ossim_uint32 BANDS = (ossim_uint32)bandList.size(); if (BANDS == 0) { return 0; } return bandList[input_band]; } ossimString ossimHistogramRemapper::getLongName()const { return ossimString("Histogram Remapper, filter with controls for histogram stretching."); } ossimString ossimHistogramRemapper::getShortName()const { return ossimString("Histogram Remapper"); } // Private to disallow use... ossimHistogramRemapper::ossimHistogramRemapper(const ossimHistogramRemapper&) { } // Private to disallow use... ossimHistogramRemapper& ossimHistogramRemapper::operator=(const ossimHistogramRemapper&) { return *this; } void ossimHistogramRemapper::setBypassFlag(bool flag) { if (theBypassFlag != flag) { //--- // If switching from bypassed to enabled set // the dirty flag. We don't care about going the other way. //--- if ( theBypassFlag && !flag ) { theDirtyFlag = true; } theBypassFlag = flag; } } double ossimHistogramRemapper::getMinPixelValue(ossim_uint32 band)const { double result = ossimTableRemapper::getMinPixelValue(band); if(theEnableFlag&&!theBypassFlag &&(band < theMinOutputValue.size())) { result = theMinOutputValue[band]; } // if(theOutputScalarType != OSSIM_SCALAR_UNKNOWN) // { // return ossim::defaultMin(theOutputScalarType); // } return result; } void ossimHistogramRemapper::setBiasFactor(ossim_float64 factor) { m_biasFactor = factor; } ossim_float64 ossimHistogramRemapper::getBiasFactor()const { return m_biasFactor; } void ossimHistogramRemapper::setAutoMinMaxBias(ossim_float64 bias) { m_autoMinMaxBias = bias; } ossim_float64 ossimHistogramRemapper::getAutoMinMaxBias()const { return m_autoMinMaxBias; } void ossimHistogramRemapper::setPercentPenetration(ossim_float64 percent) { m_percentPenetration = percent; } ossim_float64 ossimHistogramRemapper::getPercentPenetration()const { return m_percentPenetration; } double ossimHistogramRemapper::getMaxPixelValue(ossim_uint32 band)const { double result = ossimTableRemapper::getMaxPixelValue(band); if(theEnableFlag&&!theBypassFlag &&(band < theMaxOutputValue.size())) { result = theMaxOutputValue[band]; } //if(theOutputScalarType != OSSIM_SCALAR_UNKNOWN) // { // result = ossim::defaultMax(theOutputScalarType); // } return result; } bool ossimHistogramRemapper::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const { // we will alloe the histogram source only to be connected to input slot 2 and // the first slot will be reserved for the ossimImageSource. // bool result = false; if(inputIndex == 0) result = dynamic_cast(object)!=0; if(inputIndex == 1) result = dynamic_cast(object)!=0; return result; } ossim-Miami-2.9.1/src/imaging/ossimHistogramThreshholdFilter.cpp000066400000000000000000000174321352751253100250330ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHistogramThreshholdFilter.cpp 17195 2010-04-23 17:32:18Z dburken $ #include #include #include #include #include #include #include #include #include static const ossimKeyword MIN_VALUE_PERCENT_KW("min_percent", "min percentage clip"); static const ossimKeyword MAX_VALUE_PERCENT_KW("max_percent", "max percentage value"); RTTI_DEF1(ossimHistogramThreshholdFilter, "ossimHistogramThreshholdFilter", ossimImageSourceHistogramFilter) ossimHistogramThreshholdFilter::ossimHistogramThreshholdFilter() : ossimImageSourceHistogramFilter(), theMinValuePercent(0.0), theMaxValuePercent(0.0) { } ossimHistogramThreshholdFilter::ossimHistogramThreshholdFilter(double minValuePercent, double maxValuePercent, ossimImageSource* inputSource, ossimMultiResLevelHistogram* histogram) : ossimImageSourceHistogramFilter(inputSource, histogram), theMinValuePercent(minValuePercent), theMaxValuePercent(maxValuePercent) { } ossimHistogramThreshholdFilter::~ossimHistogramThreshholdFilter() { } ossimRefPtr ossimHistogramThreshholdFilter::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) return NULL; ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if(!isSourceEnabled()) { return inputTile; } if(inputTile.valid() && inputTile->getBuf() && (inputTile->getDataObjectStatus()!=OSSIM_EMPTY)) { switch(inputTile->getScalarType()) { case OSSIM_UCHAR: { return runThreshholdStretchAlgorithm((ossim_uint8)0, inputTile); } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { return runThreshholdStretchAlgorithm((ossim_uint16)0, inputTile); } case OSSIM_SSHORT16: { return runThreshholdStretchAlgorithm(static_cast(0), inputTile); } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { return runThreshholdStretchAlgorithm(static_cast(0), inputTile); } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { return runThreshholdStretchAlgorithm(static_cast(0), inputTile); } case OSSIM_SCALAR_UNKNOWN: default: { ossimSetError("ossimHistogramThreshholdFilter", ossimErrorCodes::OSSIM_ERROR, "Unknown scalar type"); break; } } } return inputTile; } bool ossimHistogramThreshholdFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { if(ossimImageSourceHistogramFilter::loadState(kwl, prefix)) { const char* minPercent = kwl.find(prefix, MIN_VALUE_PERCENT_KW); const char* maxPercent = kwl.find(prefix, MAX_VALUE_PERCENT_KW); if(minPercent) { theMinValuePercent = ossimString(minPercent).toDouble(); } else { theMinValuePercent = 0.0; } if(maxPercent) { theMaxValuePercent = ossimString(maxPercent).toDouble(); } else { theMaxValuePercent = 0.0; } } else { return false; } return true; } bool ossimHistogramThreshholdFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { if(ossimImageSourceHistogramFilter::saveState(kwl, prefix)) { kwl.add(prefix, MIN_VALUE_PERCENT_KW, theMinValuePercent, true); kwl.add(prefix, MAX_VALUE_PERCENT_KW, theMaxValuePercent, true); } else { return false; } return true; } void ossimHistogramThreshholdFilter::initialize() { ossimImageSourceHistogramFilter::initialize(); } template ossimRefPtr ossimHistogramThreshholdFilter::runThreshholdStretchAlgorithm( T /* dummyVariable */, ossimRefPtr& tile) { if(!getHistogram()) { return tile; } ossimRefPtr histo = getHistogram()->getMultiBandHistogram(0); if(histo.valid()) { ossim_uint32 maxBands = ( (histo->getNumberOfBands() > tile->getNumberOfBands())? tile->getNumberOfBands(): histo->getNumberOfBands()); long offsetUpperBound = tile->getHeight()*tile->getWidth(); for(ossim_uint32 band = 0; band < maxBands; ++band) { ossimRefPtr h = histo->getHistogram(band); T* buf = static_cast(tile->getBuf(band)); if(h.valid()&&buf) { T np = static_cast(tile->getNullPix(band)); T minPix = static_cast(tile->getMinPix(band)); T maxPix = static_cast(tile->getMaxPix(band)); double range = (maxPix - minPix); double res = h->GetRes(); double maxClip = (h->HighClipVal(theMaxValuePercent/100.0)/res); double minClip = (h->LowClipVal(theMinValuePercent/100.0)/res); ossim_float64 normPix; double delta = fabs(maxClip - minClip); if(delta > 0.0) { for(long offset = 0; offset < offsetUpperBound; ++offset) { if(buf[offset] != np) { normPix = ((double)buf[offset]-minPix)/range; if(normPix <= minClip) { buf[offset] = minPix; } else if(normPix >= maxClip) { buf[offset] = maxPix; } else { double t = (normPix - minClip)/delta; T value = static_cast(minPix + range*t); buf[offset] = value; } } } } } } tile->validate(); } return tile; } void ossimHistogramThreshholdFilter::setMinValuePercent(double minValue) { theMinValuePercent = minValue; } void ossimHistogramThreshholdFilter::setMaxValuePercent(double maxValue) { theMaxValuePercent = maxValue; } double ossimHistogramThreshholdFilter::getMinValuePercent()const { return theMinValuePercent; } double ossimHistogramThreshholdFilter::getMaxValuePercent()const { return theMaxValuePercent; } ossim-Miami-2.9.1/src/imaging/ossimHistogramWriter.cpp000066400000000000000000000166631352751253100230420ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHistogramWriter.cpp 20118 2011-10-05 13:50:55Z dburken $ #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimHistogramWriter:debug"); class ossimHistogramWriterProcessListener : public ossimProcessListener { public: ossimHistogramWriterProcessListener(ossimConnectableObject* passon) :thePassonTo(passon) { } virtual void processProgressEvent(ossimProcessProgressEvent& event) { if(thePassonTo) { event.setObject(thePassonTo); thePassonTo->fireEvent(event); } } ossimConnectableObject* thePassonTo; }; RTTI_DEF3(ossimHistogramWriter, "ossimHistogramWriter", ossimOutputSource, ossimProcessInterface, ossimConnectableObjectListener); ossimHistogramWriter::ossimHistogramWriter(ossimImageSource* inputSource, ossimObject* owner) : ossimOutputSource(owner, 1, 0, true, false), theAreaOfInterest(), theFilename(), theFileStream(0), theProcessListener(0), theHistogramSource(0) { theProcessListener = new ossimHistogramWriterProcessListener(this); theAreaOfInterest.makeNan(); connectMyInputTo(0, inputSource); } ossimHistogramWriter::~ossimHistogramWriter() { if(isOpen()) { close(); } if(theProcessListener) { delete theProcessListener; theProcessListener = 0; } // This does not need to be deleted here. Simply stored for abort. if (theHistogramSource) { theHistogramSource = 0; } } void ossimHistogramWriter::setAreaOfInterest(const ossimIrect& rect) { theAreaOfInterest = rect; } ossimObject* ossimHistogramWriter::getObject() { return this; } bool ossimHistogramWriter::isOpen()const { return (theFileStream != 0); } bool ossimHistogramWriter::open() { if(isOpen()) { close(); } theFileStream = new std::ofstream(theFilename.c_str()); return theFileStream->good(); } bool ossimHistogramWriter::open(const ossimFilename& filename) { return ossimOutputSource::open(filename); } void ossimHistogramWriter::close() { delete theFileStream; theFileStream = 0; } void ossimHistogramWriter::setOutputName(const ossimString& outputName) { ossimOutputSource::setOutputName(outputName); setFilename(outputName); } void ossimHistogramWriter::setFilename(const ossimFilename& filename) { theFilename = filename; } bool ossimHistogramWriter::canConnectMyInputTo( ossim_int32 inputIndex, const ossimConnectableObject* object)const { return (object&&(inputIndex == 0)&& (PTR_CAST(ossimHistogramSource, object)|| PTR_CAST(ossimImageSource, object))); } const ossimObject* ossimHistogramWriter::getObject()const { return this; } void ossimHistogramWriter::processProgressEvent( ossimProcessProgressEvent& event) { // we will raise the event if its coming from our // input. This means that we are connected to a // ossimHistogramSource. // if(event.getObject() != this) { ossimProcessInterface::setCurrentMessage(event.getMessage()); setPercentComplete(event.getPercentComplete()); } } void ossimHistogramWriter::connectInputEvent( ossimConnectionEvent& event) { if(event.getObject() == this) { if(event.getOldObject()) { event.getOldObject()->removeListener((ossimProcessListener*)this); } if(getInput(0)&& PTR_CAST(ossimHistogramSource, getInput(0))) { getInput(0)->addListener( (ossimProcessListener*)this); } } } void ossimHistogramWriter::disconnectInputEvent( ossimConnectionEvent& event) { if(event.getOldObject()&& PTR_CAST(ossimHistogramSource, getInput(0))) { event.getOldObject()->removeListener((ossimProcessListener*)this); } } bool ossimHistogramWriter::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimOutputSource::saveState(kwl, prefix); return result; } bool ossimHistogramWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimOutputSource::loadState(kwl, prefix); if(result) { if(!getNumberOfInputs()) { setNumberOfInputs(1); } } return result; } bool ossimHistogramWriter::execute() { writeHistogram(); return true; } void ossimHistogramWriter::writeHistogram() { if(!getInput(0)) { cerr << "ossimHistogramWriter::writeHistogram is not connected" << endl; return; } ossimHistogramSource* histoSource = PTR_CAST(ossimHistogramSource, getInput(0)); bool deleteHistoSource = false; if(!histoSource) { histoSource = new ossimImageHistogramSource; histoSource->connectMyInputTo(0, getInput(0)); histoSource->enableSource(); deleteHistoSource = true; //--- // Capture the pointer for abort call. Note a ossimHistogramSource has // no abort so the abort will only work through the // ossimImageHistogramSource pointer. //--- theHistogramSource = (ossimImageHistogramSource*)histoSource; } // Capture the pointer for abort call. theHistogramSource = histoSource; histoSource->addListener( theProcessListener); ossimRefPtr histo = histoSource->getHistogram(); // Don't write histogram if abort flag was set... if(histo.valid() && !isAborted() ) { ossimKeywordlist kwl; histo->saveState(kwl); if(!isOpen()) { open(); if(!isOpen()) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "unable to open file " << theFilename << endl; } } } if( isOpen() ) { kwl.writeToStream(*theFileStream); } } histoSource->removeListener(theProcessListener); if(deleteHistoSource) { delete histoSource; histoSource = 0; } theHistogramSource = 0; close(); } void ossimHistogramWriter::abort() { //--- // Call base abort. This sets the status to PROCESS_STATUS_ABORT_REQUEST so the processor // knows to abort. //--- ossimProcessInterface::abort(); // Propagate to histo source. if (theHistogramSource) { ossimImageHistogramSource* histoSource = PTR_CAST(ossimImageHistogramSource, theHistogramSource); if (histoSource) { histoSource->abort(); } } //--- // Now set status to "ABORTED" so ossimProcessInterface::isAborted returns true so the // writeHistogram method doesn't write the file if the process was aborted. //--- setProcessStatus(PROCESS_STATUS_ABORTED); } ossim-Miami-2.9.1/src/imaging/ossimHsiRemapper.cpp000066400000000000000000002630431352751253100221230ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Remapper to adjust hue, saturation and intensity. // //************************************************************************* // $Id: ossimHsiRemapper.cpp 19714 2011-06-03 17:23:45Z gpotts $ #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimHsiRemapper, "ossimHsiRemapper", ossimImageSourceFilter) static ossimTrace traceDebug("ossimHsiRemapper:debug"); //*** // State keywords: //*** static const char MASTER_HUE_OFFSET_KW[] = "hsi_master_hue_offset"; static const char MASTER_SATURATION_OFFSET_KW[] = "hsi_master_saturation_offset"; static const char MASTER_INTENSITY_OFFSET_KW[] = "hsi_master_intensity_offset"; static const char MASTER_INTENSITY_LOW_CLIP_KW[] = "hsi_master_intensity_low_clip"; static const char MASTER_INTENSITY_HIGH_CLIP_KW[] = "hsi_master_intensity_high_clip"; static const char RED_HUE_OFFSET_KW[] = "hsi_red_hue_offset"; static const char RED_HUE_LOW_RANGE_KW[] = "hsi_red_hue_low_range"; static const char RED_HUE_HIGH_RANGE_KW[] = "hsi_red_hue_high_range"; static const char RED_HUE_BLEND_RANGE_KW[] = "hsi_red_hue_blend_range"; static const char RED_SATURATION_OFFSET_KW[] = "hsi_red_saturation_offset"; static const char RED_INTENSITY_OFFSET_KW[] = "hsi_red_intensity_offset"; static const char YELLOW_HUE_OFFSET_KW[] = "hsi_yellow_hue_offset"; static const char YELLOW_HUE_LOW_RANGE_KW[] = "hsi_yellow_hue_low_range"; static const char YELLOW_HUE_HIGH_RANGE_KW[] = "hsi_yellow_hue_high_range"; static const char YELLOW_HUE_BLEND_RANGE_KW[] = "hsi_yellow_hue_blend_range"; static const char YELLOW_SATURATION_OFFSET_KW[] = "hsi_yellow_saturation_offset"; static const char YELLOW_INTENSITY_OFFSET_KW[] = "hsi_yellow_intensity_offset"; static const char GREEN_HUE_OFFSET_KW[] = "hsi_green_hue_offset"; static const char GREEN_HUE_LOW_RANGE_KW[] = "hsi_green_hue_low_range"; static const char GREEN_HUE_HIGH_RANGE_KW[] = "hsi_green_hue_high_range"; static const char GREEN_HUE_BLEND_RANGE_KW[] = "hsi_green_hue_blend_range"; static const char GREEN_SATURATION_OFFSET_KW[] = "hsi_green_saturation_offset"; static const char GREEN_INTENSITY_OFFSET_KW[] = "hsi_green_intensity_offset"; static const char CYAN_HUE_OFFSET_KW[] = "hsi_cyan_hue_offset"; static const char CYAN_HUE_LOW_RANGE_KW[] = "hsi_cyan_hue_low_range"; static const char CYAN_HUE_HIGH_RANGE_KW[] = "hsi_cyan_hue_high_range"; static const char CYAN_HUE_BLEND_RANGE_KW[] = "hsi_cyan_hue_blend_range"; static const char CYAN_SATURATION_OFFSET_KW[] = "hsi_cyan_saturation_offset"; static const char CYAN_INTENSITY_OFFSET_KW[] = "hsi_cyan_intensity_offset"; static const char BLUE_HUE_OFFSET_KW[] = "hsi_blue_hue_offset"; static const char BLUE_HUE_LOW_RANGE_KW[] = "hsi_blue_hue_low_range"; static const char BLUE_HUE_HIGH_RANGE_KW[] = "hsi_blue_hue_high_range"; static const char BLUE_HUE_BLEND_RANGE_KW[] = "hsi_blue_hue_blend_range"; static const char BLUE_SATURATION_OFFSET_KW[] = "hsi_blue_saturation_offset"; static const char BLUE_INTENSITY_OFFSET_KW[] = "hsi_blue_intensity_offset"; static const char MAGENTA_HUE_OFFSET_KW[] = "hsi_magenta_hue_offset"; static const char MAGENTA_HUE_LOW_RANGE_KW[] = "hsi_magenta_hue_low_range"; static const char MAGENTA_HUE_HIGH_RANGE_KW[] = "hsi_magenta_hue_high_range"; static const char MAGENTA_HUE_BLEND_RANGE_KW[] = "hsi_magenta_hue_blend_range"; static const char MAGENTA_SATURATION_OFFSET_KW[] = "hsi_magenta_saturation_offset"; static const char MAGENTA_INTENSITY_OFFSET_KW[] = "hsi_magenta_intensity_offset"; static const char WHITE_OBJECT_CLIP_KW[] = "hsi_white_object_clip"; static const double DEFAULT_BLEND = 15.0; static const double MAX_BLEND = 30.0; ossimHsiRemapper::ossimHsiRemapper() : ossimImageSourceFilter (), // base class theTile (NULL), theBuffer (NULL), theNormalizedMinPix (0.0), theMasterHueOffset (0.0), theMasterSaturationOffset (0.0), theMasterIntensityOffset (0.0), theMasterIntensityLowClip (0.0), theMasterIntensityHighClip (1.0), theRedHueOffset (0.0), theRedHueLowRange (-30.0), theRedHueHighRange (30.0), theRedHueBlendRange (DEFAULT_BLEND), theRedSaturationOffset (0.0), theRedIntensityOffset (0.0), theYellowHueOffset (0.0), theYellowHueLowRange (30.0), theYellowHueHighRange (90.0), theYellowHueBlendRange (DEFAULT_BLEND), theYellowSaturationOffset (0.0), theYellowIntensityOffset (0.0), theGreenHueOffset (0.0), theGreenHueLowRange (90.0), theGreenHueHighRange (150.0), theGreenHueBlendRange (DEFAULT_BLEND), theGreenSaturationOffset (0.0), theGreenIntensityOffset (0.0), theCyanHueOffset (0.0), theCyanHueLowRange (150.0), theCyanHueHighRange (210.0), theCyanHueBlendRange (DEFAULT_BLEND), theCyanSaturationOffset (0.0), theCyanIntensityOffset (0.0), theBlueHueOffset (0.0), theBlueHueLowRange (210.0), theBlueHueHighRange (270.0), theBlueHueBlendRange (DEFAULT_BLEND), theBlueSaturationOffset (0.0), theBlueIntensityOffset (0.0), theMagentaHueOffset (0.0), theMagentaHueLowRange (270.0), theMagentaHueHighRange (330.0), theMagentaHueBlendRange (DEFAULT_BLEND), theMagentaSaturationOffset (0.0), theMagentaIntensityOffset (0.0), theWhiteObjectClip (1.0) { //*** // Set the base class "theEnableFlag" to off since no adjustments have been // made yet. //*** //disableSource(); theValidFlag = false; // Construction not complete. } ossimHsiRemapper::~ossimHsiRemapper() { theTile = NULL; if (theBuffer) { delete [] theBuffer; theBuffer = NULL; } } ossimRefPtr ossimHsiRemapper::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { if(!theInputConnection) { return ossimRefPtr(); } // Fetch tile from pointer from the input source. ossimRefPtr inputTile = theInputConnection->getTile( tile_rect, resLevel); // Check for remap bypass or a null tile return from input: if (!isSourceEnabled() || !inputTile||!theValidFlag) { return inputTile; } // Check for first time through or size change. if ( !theTile.valid() || tile_rect.height() != theTile->getHeight() || tile_rect.width() != theTile->getWidth() ) { allocate(tile_rect); } //--- // Set the image rectangle of the tile. // Note that this will resize the tiles buffers if theTile->setImageRectangle(tile_rect); // Get its status. ossimDataObjectStatus tile_status = inputTile->getDataObjectStatus(); if ( (tile_status == OSSIM_NULL) || (tile_status == OSSIM_EMPTY) ) { theTile->makeBlank(); return theTile; } double* rgbBuf[3]; const ossim_uint32 PPT = theTile->getSizePerBand(); // Pixels Per Tile rgbBuf[0] = theBuffer; rgbBuf[1] = &(theBuffer[PPT]); rgbBuf[2] = &(rgbBuf[1][PPT]); switch(inputTile->getNumberOfBands()) { case 1: case 2: { // Copy the first band only. inputTile->copyTileBandToNormalizedBuffer(0, rgbBuf[0]); memcpy(rgbBuf[1], rgbBuf[0], PPT*sizeof(double)); memcpy(rgbBuf[2], rgbBuf[0], PPT*sizeof(double)); break; } case 3: { inputTile->copyTileToNormalizedBuffer(theBuffer); break; } default: { inputTile->copyTileBandToNormalizedBuffer(0, rgbBuf[0]); inputTile->copyTileBandToNormalizedBuffer(1, rgbBuf[1]); inputTile->copyTileBandToNormalizedBuffer(2, rgbBuf[2]); break; } } ossimNormRgbVector rgb; ossimHsiVector hsi; double r = 0.0; double g = 0.0; double b = 0.0; double h = 0.0; double s = 0.0; double i = 0.0; ossim_uint32 idx; // Convert the rgb value to hsi and adjust values. for (idx=0; idx FLT_EPSILON) { double h_offset = theMasterHueOffset; double s_offset = theMasterSaturationOffset; double i_offset = theMasterIntensityOffset; //*** // Note: For the purpose of checking to see if in the red range, // make the hue negative if it's >= 315.0 and < 360.0. // The red low and high ranges are stored in the same manner. //*** double red_hue = h; if (red_hue >= 315.0 && red_hue < 360.0) red_hue = red_hue - 360.0; if ( red_hue >= theRedHueLowRange && red_hue <= theRedHueHighRange) { // Adjust the reds. double bf = 1.0; // blend factor if ( red_hue < (theRedHueLowRange + theRedHueBlendRange) ) { bf = (red_hue - theRedHueLowRange) / theRedHueBlendRange; } else if ( red_hue > (theRedHueHighRange - theRedHueBlendRange) ) { bf = (theRedHueHighRange - red_hue) / theRedHueBlendRange; } h_offset += (theRedHueOffset * bf); s_offset += (theRedSaturationOffset * bf); i_offset += (theRedIntensityOffset * bf); } if (h >= theYellowHueLowRange && h <= theYellowHueHighRange) { // Adjust the yellows. double bf = 1.0; // blend factor if ( h < (theYellowHueLowRange + theYellowHueBlendRange) ) { bf = (h - theYellowHueLowRange) / theYellowHueBlendRange; } else if ( h > (theYellowHueHighRange - theYellowHueBlendRange) ) { bf = (theYellowHueHighRange - h) / theYellowHueBlendRange; } h_offset += (theYellowHueOffset * bf); s_offset += (theYellowSaturationOffset * bf); i_offset += (theYellowIntensityOffset * bf); } if (h >= theGreenHueLowRange && h <= theGreenHueHighRange) { // Adjust the greens. double bf = 1.0; // blend factor if ( h < (theGreenHueLowRange + theGreenHueBlendRange) ) { bf = (h - theGreenHueLowRange) / theGreenHueBlendRange; } else if ( h > (theGreenHueHighRange - theGreenHueBlendRange) ) { bf = (theGreenHueHighRange - h) / theGreenHueBlendRange; } h_offset += (theGreenHueOffset * bf); s_offset += (theGreenSaturationOffset * bf); i_offset += (theGreenIntensityOffset * bf); } if (h >= theCyanHueLowRange && h <= theCyanHueHighRange) { // Adjust the cyans. double bf = 1.0; // blend factor if ( h < (theCyanHueLowRange + theCyanHueBlendRange) ) { bf = (h - theCyanHueLowRange) / theCyanHueBlendRange; } else if ( h > (theCyanHueHighRange - theCyanHueBlendRange) ) { bf = (theCyanHueHighRange - h) / theCyanHueBlendRange; } h_offset += (theCyanHueOffset * bf); s_offset += (theCyanSaturationOffset * bf); i_offset += (theCyanIntensityOffset * bf); } if (h >= theBlueHueLowRange && h <= theBlueHueHighRange) { // Adjust the blues. double bf = 1.0; // blend factor if ( h < (theBlueHueLowRange + theBlueHueBlendRange) ) { bf = (h - theBlueHueLowRange) / theBlueHueBlendRange; } else if ( h > (theBlueHueHighRange - theBlueHueBlendRange) ) { bf = (theBlueHueHighRange - h) / theBlueHueBlendRange; } h_offset += (theBlueHueOffset * bf); s_offset += (theBlueSaturationOffset * bf); i_offset += (theBlueIntensityOffset * bf); } if (h >= theMagentaHueLowRange && h <= theMagentaHueHighRange) { // Adjust the magentas. double bf = 1.0; // blend factor if ( h < (theMagentaHueLowRange + theMagentaHueBlendRange) ) { bf = (h - theMagentaHueLowRange) / theMagentaHueBlendRange; } else if ( h > (theMagentaHueHighRange - theMagentaHueBlendRange) ) { bf = (theMagentaHueHighRange - h) / theMagentaHueBlendRange; } h_offset += (theMagentaHueOffset * bf); s_offset += (theMagentaSaturationOffset * bf); i_offset += (theMagentaIntensityOffset * bf); } // Apply the hue offset. h += h_offset; // Make sure the hue is between 0 and 360... if (h < 0.0) h += 360.0; else if (h >= 360) h -= 360.0; // Apply the saturation offset clamping/clipping to 0.0/1.0. s += s_offset; s = (s > 0.0 ? (s < 1.0 ? s : 1.0) : 0.0); // Apply the intensity offset clamping/clipping to 0.0/1.0. i += i_offset; i = (i > 0.0 ? (i < 1.0 ? i : 1.0) : 0.0); // Stretch the intensity channel. // i = (i - theMasterIntensityLowClip) * // ( 1.0 / (theMasterIntensityHighClip - // theMasterIntensityLowClip) ); i = (i - theMasterIntensityLowClip)/(theMasterIntensityHighClip - theMasterIntensityLowClip); hsi.setH(h); hsi.setS(s); hsi.setI(i); rgb = hsi; r = rgb.getR(); g = rgb.getG(); b = rgb.getB(); if ( (theWhiteObjectClip < 1.0) && (r > theWhiteObjectClip) && (g > theWhiteObjectClip) && (b > theWhiteObjectClip) ) { r = theWhiteObjectClip; g = theWhiteObjectClip; b = theWhiteObjectClip; } // Do min/max range check and assign back to buffer. rgbBuf[0][idx] = r > theNormalizedMinPix ? (r < 1.0 ? r : 1.0) : theNormalizedMinPix; rgbBuf[1][idx] = g > theNormalizedMinPix ? (g < 1.0 ? g : 1.0) : theNormalizedMinPix; rgbBuf[2][idx] = b > theNormalizedMinPix ? (b < 1.0 ? b : 1.0) : theNormalizedMinPix; } // End of "if(i > FLT_EPSILON)" else { rgbBuf[0][idx] = 0.0; rgbBuf[1][idx] = 0.0; rgbBuf[2][idx] = 0.0; } } // End of loop through pixels in a tile. // Copy the buffer to the output tile. theTile->copyNormalizedBufferToTile(theBuffer); // Update the tile status. theTile->validate(); return theTile; } void ossimHsiRemapper::initialize() { ossimImageSourceFilter::initialize(); if (theTile.valid()) { theTile = NULL; if(theBuffer) { delete []theBuffer; theBuffer = NULL; } } } void ossimHsiRemapper::setProperty(ossimRefPtr property) { if(!property.valid()) return; ossimString name = property->getName(); if(name == MASTER_HUE_OFFSET_KW) { setMasterHueOffset(property->valueToString().toDouble()); } else if(name == MASTER_SATURATION_OFFSET_KW) { setMasterSaturationOffset(property->valueToString().toDouble()); } else if(name == MASTER_INTENSITY_OFFSET_KW) { setMasterIntensityOffset(property->valueToString().toDouble()); } else if(name == MASTER_INTENSITY_LOW_CLIP_KW) { setMasterIntensityLowClip(property->valueToString().toDouble()); } else if(name == MASTER_INTENSITY_HIGH_CLIP_KW) { setMasterIntensityHighClip(property->valueToString().toDouble()); } else if(name == RED_HUE_OFFSET_KW) { setRedHueOffset(property->valueToString().toDouble()); } else if(name == RED_HUE_LOW_RANGE_KW) { setRedHueLowRange(property->valueToString().toDouble()); } else if(name == RED_HUE_HIGH_RANGE_KW) { setRedHueHighRange(property->valueToString().toDouble()); } else if(name == RED_HUE_BLEND_RANGE_KW) { setRedHueBlendRange(property->valueToString().toDouble()); } else if(name == RED_SATURATION_OFFSET_KW) { setRedSaturationOffset(property->valueToString().toDouble()); } else if(name == RED_INTENSITY_OFFSET_KW) { setRedIntensityOffset(property->valueToString().toDouble()); } else if(name == YELLOW_HUE_OFFSET_KW) { setYellowHueOffset(property->valueToString().toDouble()); } else if(name == YELLOW_HUE_LOW_RANGE_KW) { setYellowHueLowRange(property->valueToString().toDouble()); } else if(name == YELLOW_HUE_HIGH_RANGE_KW) { setYellowHueHighRange(property->valueToString().toDouble()); } else if(name == YELLOW_HUE_BLEND_RANGE_KW) { setYellowHueBlendRange(property->valueToString().toDouble()); } else if(name == YELLOW_SATURATION_OFFSET_KW) { setYellowSaturationOffset(property->valueToString().toDouble()); } else if(name == YELLOW_INTENSITY_OFFSET_KW) { setYellowIntensityOffset(property->valueToString().toDouble()); } else if(name == GREEN_HUE_OFFSET_KW) { setGreenHueOffset(property->valueToString().toDouble()); } else if(name == GREEN_HUE_LOW_RANGE_KW) { setGreenHueLowRange(property->valueToString().toDouble()); } else if(name == GREEN_HUE_HIGH_RANGE_KW) { setGreenHueHighRange(property->valueToString().toDouble()); } else if(name == GREEN_HUE_BLEND_RANGE_KW) { setGreenHueBlendRange(property->valueToString().toDouble()); } else if(name == GREEN_SATURATION_OFFSET_KW) { setGreenSaturationOffset(property->valueToString().toDouble()); } else if(name == GREEN_INTENSITY_OFFSET_KW) { setGreenIntensityOffset(property->valueToString().toDouble()); } else if(name == CYAN_HUE_OFFSET_KW) { setCyanHueOffset(property->valueToString().toDouble()); } else if(name == CYAN_HUE_LOW_RANGE_KW) { setCyanHueLowRange(property->valueToString().toDouble()); } else if(name == CYAN_HUE_HIGH_RANGE_KW) { setCyanHueHighRange(property->valueToString().toDouble()); } else if(name == CYAN_HUE_BLEND_RANGE_KW) { setCyanHueBlendRange(property->valueToString().toDouble()); } else if(name == CYAN_SATURATION_OFFSET_KW) { setCyanSaturationOffset(property->valueToString().toDouble()); } else if(name == CYAN_INTENSITY_OFFSET_KW) { setCyanIntensityOffset(property->valueToString().toDouble()); } else if(name == BLUE_HUE_OFFSET_KW) { setBlueHueOffset(property->valueToString().toDouble()); } else if(name == BLUE_HUE_LOW_RANGE_KW) { setBlueHueLowRange(property->valueToString().toDouble()); } else if(name == BLUE_HUE_HIGH_RANGE_KW) { setBlueHueHighRange(property->valueToString().toDouble()); } else if(name == BLUE_HUE_BLEND_RANGE_KW) { setBlueHueBlendRange(property->valueToString().toDouble()); } else if(name == BLUE_SATURATION_OFFSET_KW) { setBlueSaturationOffset(property->valueToString().toDouble()); } else if(name == BLUE_INTENSITY_OFFSET_KW) { setBlueIntensityOffset(property->valueToString().toDouble()); } else if(name == MAGENTA_HUE_OFFSET_KW) { setMagentaHueOffset(property->valueToString().toDouble()); } else if(name == MAGENTA_HUE_LOW_RANGE_KW) { setMagentaHueLowRange(property->valueToString().toDouble()); } else if(name == MAGENTA_HUE_HIGH_RANGE_KW) { setMagentaHueHighRange(property->valueToString().toDouble()); } else if(name == MAGENTA_HUE_BLEND_RANGE_KW) { setMagentaHueBlendRange(property->valueToString().toDouble()); } else if(name == MAGENTA_SATURATION_OFFSET_KW) { setMagentaSaturationOffset(property->valueToString().toDouble()); } else if(name == MAGENTA_INTENSITY_OFFSET_KW) { setMagentaIntensityOffset(property->valueToString().toDouble()); } else if(name == WHITE_OBJECT_CLIP_KW) { setWhiteObjectClip(property->valueToString().toDouble()); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimHsiRemapper::getProperty(const ossimString& name)const { ossimRefPtr result; if(name == MASTER_HUE_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMasterHueOffset), -180, 180); result->setCacheRefreshBit(); } else if(name == MASTER_SATURATION_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMasterSaturationOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == MASTER_INTENSITY_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMasterIntensityOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == MASTER_INTENSITY_LOW_CLIP_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMasterIntensityLowClip), 0, 1); result->setCacheRefreshBit(); } else if(name == MASTER_INTENSITY_HIGH_CLIP_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMasterIntensityHighClip), 0, 1); result->setCacheRefreshBit(); } else if(name == RED_HUE_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theRedHueOffset), -180, 180); result->setCacheRefreshBit(); } else if(name == RED_HUE_LOW_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theRedHueLowRange), -30, 30); result->setCacheRefreshBit(); } else if(name == RED_HUE_HIGH_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theRedHueHighRange), -30, 30); result->setCacheRefreshBit(); } else if(name == RED_HUE_BLEND_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theRedHueBlendRange), 0, 30); result->setCacheRefreshBit(); } else if(name == RED_SATURATION_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theRedSaturationOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == RED_INTENSITY_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theRedIntensityOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == YELLOW_HUE_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theYellowHueOffset), -180, 180); result->setCacheRefreshBit(); } else if(name == YELLOW_HUE_LOW_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theYellowHueLowRange), 30, 90); result->setCacheRefreshBit(); } else if(name == YELLOW_HUE_HIGH_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theYellowHueHighRange), 30, 90); result->setCacheRefreshBit(); } else if(name == YELLOW_HUE_BLEND_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theYellowHueBlendRange), 0, 30); result->setCacheRefreshBit(); } else if(name == YELLOW_SATURATION_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theYellowSaturationOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == YELLOW_INTENSITY_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theYellowIntensityOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == GREEN_HUE_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theGreenHueOffset), -180, 180); result->setCacheRefreshBit(); } else if(name == GREEN_HUE_LOW_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theGreenHueLowRange), 90, 150); result->setCacheRefreshBit(); } else if(name == GREEN_HUE_HIGH_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theGreenHueHighRange), 90, 150); result->setCacheRefreshBit(); } else if(name == GREEN_HUE_BLEND_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theGreenHueBlendRange), 0, 30); result->setCacheRefreshBit(); } else if(name == GREEN_SATURATION_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theGreenSaturationOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == GREEN_INTENSITY_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theGreenIntensityOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == CYAN_HUE_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theCyanHueOffset), -180, 180); result->setCacheRefreshBit(); } else if(name == CYAN_HUE_LOW_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theCyanHueLowRange), 150, 210); result->setCacheRefreshBit(); } else if(name == CYAN_HUE_HIGH_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theCyanHueHighRange), 150, 210); result->setCacheRefreshBit(); } else if(name == CYAN_HUE_BLEND_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theCyanHueBlendRange), 0, 30); result->setCacheRefreshBit(); } else if(name == CYAN_SATURATION_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theCyanSaturationOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == CYAN_INTENSITY_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theCyanIntensityOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == BLUE_HUE_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theBlueHueOffset), -180, 180); result->setCacheRefreshBit(); } else if(name == BLUE_HUE_LOW_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theBlueHueLowRange), 210, 270); result->setCacheRefreshBit(); } else if(name == BLUE_HUE_HIGH_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theBlueHueHighRange), 210, 270); result->setCacheRefreshBit(); } else if(name == BLUE_HUE_BLEND_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theBlueHueBlendRange), 0, 30); result->setCacheRefreshBit(); } else if(name == BLUE_SATURATION_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theBlueSaturationOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == BLUE_INTENSITY_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theBlueIntensityOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == MAGENTA_HUE_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMagentaHueOffset), -180, 180); result->setCacheRefreshBit(); } else if(name == MAGENTA_HUE_LOW_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMagentaHueLowRange), 270, 330); result->setCacheRefreshBit(); } else if(name == MAGENTA_HUE_HIGH_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMagentaHueHighRange), 270, 330); result->setCacheRefreshBit(); } else if(name == MAGENTA_HUE_BLEND_RANGE_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMagentaHueBlendRange), 0, 30); result->setCacheRefreshBit(); } else if(name == MAGENTA_SATURATION_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMagentaSaturationOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == MAGENTA_INTENSITY_OFFSET_KW) { result = new ossimNumericProperty(name, ossimString::toString(theMagentaIntensityOffset), -1, 1); result->setCacheRefreshBit(); } else if(name == WHITE_OBJECT_CLIP_KW) { result = new ossimNumericProperty(name, ossimString::toString(theWhiteObjectClip), 0.8, 1.0); result->setCacheRefreshBit(); } else { result = ossimImageSourceFilter::getProperty(name); } return result; } void ossimHsiRemapper::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back(MASTER_HUE_OFFSET_KW); propertyNames.push_back(MASTER_SATURATION_OFFSET_KW); propertyNames.push_back(MASTER_INTENSITY_OFFSET_KW); propertyNames.push_back(MASTER_INTENSITY_LOW_CLIP_KW); propertyNames.push_back(MASTER_INTENSITY_HIGH_CLIP_KW); propertyNames.push_back(RED_HUE_OFFSET_KW); propertyNames.push_back(RED_HUE_LOW_RANGE_KW); propertyNames.push_back(RED_HUE_HIGH_RANGE_KW); propertyNames.push_back(RED_HUE_BLEND_RANGE_KW); propertyNames.push_back(RED_SATURATION_OFFSET_KW); propertyNames.push_back(RED_INTENSITY_OFFSET_KW); propertyNames.push_back(YELLOW_HUE_OFFSET_KW); propertyNames.push_back(YELLOW_HUE_LOW_RANGE_KW); propertyNames.push_back(YELLOW_HUE_HIGH_RANGE_KW); propertyNames.push_back(YELLOW_HUE_BLEND_RANGE_KW); propertyNames.push_back(YELLOW_SATURATION_OFFSET_KW); propertyNames.push_back(YELLOW_INTENSITY_OFFSET_KW); propertyNames.push_back(GREEN_HUE_OFFSET_KW); propertyNames.push_back(GREEN_HUE_LOW_RANGE_KW); propertyNames.push_back(GREEN_HUE_HIGH_RANGE_KW); propertyNames.push_back(GREEN_HUE_BLEND_RANGE_KW); propertyNames.push_back(GREEN_SATURATION_OFFSET_KW); propertyNames.push_back(GREEN_INTENSITY_OFFSET_KW); propertyNames.push_back(CYAN_HUE_OFFSET_KW); propertyNames.push_back(CYAN_HUE_LOW_RANGE_KW); propertyNames.push_back(CYAN_HUE_HIGH_RANGE_KW); propertyNames.push_back(CYAN_HUE_BLEND_RANGE_KW); propertyNames.push_back(CYAN_SATURATION_OFFSET_KW); propertyNames.push_back(CYAN_INTENSITY_OFFSET_KW); propertyNames.push_back(BLUE_HUE_OFFSET_KW); propertyNames.push_back(BLUE_HUE_LOW_RANGE_KW); propertyNames.push_back(BLUE_HUE_HIGH_RANGE_KW); propertyNames.push_back(BLUE_HUE_BLEND_RANGE_KW); propertyNames.push_back(BLUE_SATURATION_OFFSET_KW); propertyNames.push_back(BLUE_INTENSITY_OFFSET_KW); propertyNames.push_back(MAGENTA_HUE_OFFSET_KW); propertyNames.push_back(MAGENTA_HUE_LOW_RANGE_KW); propertyNames.push_back(MAGENTA_HUE_HIGH_RANGE_KW); propertyNames.push_back(MAGENTA_HUE_BLEND_RANGE_KW); propertyNames.push_back(MAGENTA_SATURATION_OFFSET_KW); propertyNames.push_back(MAGENTA_INTENSITY_OFFSET_KW); propertyNames.push_back(WHITE_OBJECT_CLIP_KW); } void ossimHsiRemapper::allocate(const ossimIrect& rect) { if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this,this); theTile->initialize(); ossim_uint32 width = rect.width(); ossim_uint32 height = rect.height(); if(theBuffer) { delete [] theBuffer; theBuffer = 0; } ossim_uint32 size = width * height * 3; // Buffer always 3 bands. theBuffer = new double[size]; memset(theBuffer, '\0', sizeof(double) * size); // Get the minimum normalized pixel value. theNormalizedMinPix = calculateMinNormValue(); } } bool ossimHsiRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimHsiRemapper::loadState()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entering..." << endl; } // Make a prefix. ossimString tmpPrefix; if (prefix) tmpPrefix += prefix; const char* lookupReturn; lookupReturn = kwl.find(tmpPrefix.c_str(), MASTER_HUE_OFFSET_KW); if(lookupReturn) { setMasterHueOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MASTER_SATURATION_OFFSET_KW); if(lookupReturn) { setMasterSaturationOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MASTER_INTENSITY_OFFSET_KW); if(lookupReturn) { setMasterIntensityOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MASTER_INTENSITY_LOW_CLIP_KW); if(lookupReturn) { setMasterIntensityLowClip(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MASTER_INTENSITY_HIGH_CLIP_KW); if(lookupReturn) { setMasterIntensityHighClip(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), RED_HUE_OFFSET_KW); if(lookupReturn) { setRedHueOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), RED_HUE_LOW_RANGE_KW); if(lookupReturn) { setRedHueLowRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), RED_HUE_HIGH_RANGE_KW); if(lookupReturn) { setRedHueHighRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), RED_HUE_BLEND_RANGE_KW); if(lookupReturn) { setRedHueBlendRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), RED_SATURATION_OFFSET_KW); if(lookupReturn) { setRedSaturationOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), RED_INTENSITY_OFFSET_KW); if(lookupReturn) { setRedIntensityOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), YELLOW_HUE_OFFSET_KW); if(lookupReturn) { setYellowHueOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), YELLOW_HUE_LOW_RANGE_KW); if(lookupReturn) { setYellowHueLowRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), YELLOW_HUE_HIGH_RANGE_KW); if(lookupReturn) { setYellowHueHighRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), YELLOW_HUE_BLEND_RANGE_KW); if(lookupReturn) { setYellowHueBlendRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), YELLOW_SATURATION_OFFSET_KW); if(lookupReturn) { setYellowSaturationOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), YELLOW_INTENSITY_OFFSET_KW); if(lookupReturn) { setYellowIntensityOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), GREEN_HUE_OFFSET_KW); if(lookupReturn) { setGreenHueOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), GREEN_HUE_LOW_RANGE_KW); if(lookupReturn) { setGreenHueLowRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), GREEN_HUE_HIGH_RANGE_KW); if(lookupReturn) { setGreenHueHighRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), GREEN_HUE_BLEND_RANGE_KW); if(lookupReturn) { setGreenHueBlendRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), GREEN_SATURATION_OFFSET_KW); if(lookupReturn) { setGreenSaturationOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), GREEN_INTENSITY_OFFSET_KW); if(lookupReturn) { setGreenIntensityOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), CYAN_HUE_OFFSET_KW); if(lookupReturn) { setCyanHueOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), CYAN_HUE_LOW_RANGE_KW); if(lookupReturn) { setCyanHueLowRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), CYAN_HUE_HIGH_RANGE_KW); if(lookupReturn) { setCyanHueHighRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), CYAN_HUE_BLEND_RANGE_KW); if(lookupReturn) { setCyanHueBlendRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), CYAN_SATURATION_OFFSET_KW); if(lookupReturn) { setCyanSaturationOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), CYAN_INTENSITY_OFFSET_KW); if(lookupReturn) { setCyanIntensityOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), BLUE_HUE_OFFSET_KW); if(lookupReturn) { setBlueHueOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), BLUE_HUE_LOW_RANGE_KW); if(lookupReturn) { setBlueHueLowRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), BLUE_HUE_HIGH_RANGE_KW); if(lookupReturn) { setBlueHueHighRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), BLUE_HUE_BLEND_RANGE_KW); if(lookupReturn) { setBlueHueBlendRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), BLUE_SATURATION_OFFSET_KW); if(lookupReturn) { setBlueSaturationOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), BLUE_INTENSITY_OFFSET_KW); if(lookupReturn) { setBlueIntensityOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MAGENTA_HUE_OFFSET_KW); if(lookupReturn) { setMagentaHueOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MAGENTA_HUE_LOW_RANGE_KW); if(lookupReturn) { setMagentaHueLowRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MAGENTA_HUE_HIGH_RANGE_KW); if(lookupReturn) { setMagentaHueHighRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MAGENTA_HUE_BLEND_RANGE_KW); if(lookupReturn) { setMagentaHueBlendRange(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MAGENTA_SATURATION_OFFSET_KW); if(lookupReturn) { setMagentaSaturationOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), MAGENTA_INTENSITY_OFFSET_KW); if(lookupReturn) { setMagentaIntensityOffset(atof(lookupReturn)); } lookupReturn = kwl.find(tmpPrefix.c_str(), WHITE_OBJECT_CLIP_KW); if(lookupReturn) { setWhiteObjectClip(atof(lookupReturn)); } //*** // Initialize the base class. Do this last so that the enable/disable // doesn't get overridden by the "set*" methods. //*** ossimImageSourceFilter::loadState(kwl, tmpPrefix.c_str()); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "" << *this << "\nreturning..." << endl; } return true; } bool ossimHsiRemapper::saveState(ossimKeywordlist& kwl, const char* prefix) const { static const char MODULE[] = "ossimHsiRemapper::saveStateTo()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "entering..." << endl; } // Call the base class getStateFrom. ossimImageSourceFilter::saveState(kwl, prefix); kwl.add(prefix, MASTER_HUE_OFFSET_KW, theMasterHueOffset); kwl.add(prefix, MASTER_SATURATION_OFFSET_KW, theMasterSaturationOffset); kwl.add(prefix, MASTER_INTENSITY_OFFSET_KW, theMasterIntensityOffset); kwl.add(prefix, MASTER_INTENSITY_LOW_CLIP_KW, theMasterIntensityLowClip); kwl.add(prefix, MASTER_INTENSITY_HIGH_CLIP_KW, theMasterIntensityHighClip); kwl.add(prefix, RED_HUE_OFFSET_KW, theRedHueOffset); kwl.add(prefix, RED_HUE_LOW_RANGE_KW, theRedHueLowRange); kwl.add(prefix, RED_HUE_HIGH_RANGE_KW, theRedHueHighRange); kwl.add(prefix, RED_HUE_BLEND_RANGE_KW, theRedHueBlendRange); kwl.add(prefix, RED_SATURATION_OFFSET_KW, theRedSaturationOffset); kwl.add(prefix, RED_INTENSITY_OFFSET_KW, theRedIntensityOffset); kwl.add(prefix, YELLOW_HUE_OFFSET_KW, theYellowHueOffset); kwl.add(prefix, YELLOW_HUE_LOW_RANGE_KW, theYellowHueLowRange); kwl.add(prefix, YELLOW_HUE_HIGH_RANGE_KW, theYellowHueHighRange); kwl.add(prefix, YELLOW_HUE_BLEND_RANGE_KW, theYellowHueBlendRange); kwl.add(prefix, YELLOW_SATURATION_OFFSET_KW, theYellowSaturationOffset); kwl.add(prefix, YELLOW_INTENSITY_OFFSET_KW, theYellowIntensityOffset); kwl.add(prefix, GREEN_HUE_OFFSET_KW, theGreenHueOffset); kwl.add(prefix, GREEN_HUE_LOW_RANGE_KW, theGreenHueLowRange); kwl.add(prefix, GREEN_HUE_HIGH_RANGE_KW, theGreenHueHighRange); kwl.add(prefix, GREEN_HUE_BLEND_RANGE_KW, theGreenHueBlendRange); kwl.add(prefix, GREEN_SATURATION_OFFSET_KW, theGreenSaturationOffset); kwl.add(prefix, GREEN_INTENSITY_OFFSET_KW, theGreenIntensityOffset); kwl.add(prefix, CYAN_HUE_OFFSET_KW, theCyanHueOffset); kwl.add(prefix, CYAN_HUE_LOW_RANGE_KW, theCyanHueLowRange); kwl.add(prefix, CYAN_HUE_HIGH_RANGE_KW, theCyanHueHighRange); kwl.add(prefix, CYAN_HUE_BLEND_RANGE_KW, theCyanHueBlendRange); kwl.add(prefix, CYAN_SATURATION_OFFSET_KW, theCyanSaturationOffset); kwl.add(prefix, CYAN_INTENSITY_OFFSET_KW, theCyanIntensityOffset); kwl.add(prefix, BLUE_HUE_OFFSET_KW, theBlueHueOffset); kwl.add(prefix, BLUE_HUE_LOW_RANGE_KW, theBlueHueLowRange); kwl.add(prefix, BLUE_HUE_HIGH_RANGE_KW, theBlueHueHighRange); kwl.add(prefix, BLUE_HUE_BLEND_RANGE_KW, theBlueHueBlendRange); kwl.add(prefix, BLUE_SATURATION_OFFSET_KW, theBlueSaturationOffset); kwl.add(prefix, BLUE_INTENSITY_OFFSET_KW, theBlueIntensityOffset); kwl.add(prefix, MAGENTA_HUE_OFFSET_KW, theMagentaHueOffset); kwl.add(prefix, MAGENTA_HUE_LOW_RANGE_KW, theMagentaHueLowRange); kwl.add(prefix, MAGENTA_HUE_HIGH_RANGE_KW, theMagentaHueHighRange); kwl.add(prefix, MAGENTA_HUE_BLEND_RANGE_KW, theMagentaHueBlendRange); kwl.add(prefix, MAGENTA_SATURATION_OFFSET_KW, theMagentaSaturationOffset); kwl.add(prefix, MAGENTA_INTENSITY_OFFSET_KW, theMagentaIntensityOffset); kwl.add(prefix, WHITE_OBJECT_CLIP_KW, theWhiteObjectClip); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "returning..." << endl; } return true; } void ossimHsiRemapper::resetGroup(int color_group) { switch (color_group) { case RED: resetRed(); break; case YELLOW: resetYellow(); break; case GREEN: resetGreen(); break; case CYAN: resetCyan(); break; case BLUE: resetBlue(); break; case MAGENTA: resetMagenta(); break; case ALL: resetMaster(); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::setSaturationOffset NOTICE: Range error!" << endl; break; } verifyEnabled(); } void ossimHsiRemapper::resetAll() { theMasterHueOffset = 0.0; theMasterSaturationOffset = 0.0; theMasterIntensityOffset = 0.0; theMasterIntensityLowClip = 0.0; theMasterIntensityHighClip = 1.0; theRedHueOffset = 0.0; theRedHueLowRange = -30.0; theRedHueHighRange = 30.0; theRedHueBlendRange = DEFAULT_BLEND; theRedSaturationOffset = 0.0; theRedIntensityOffset = 0.0; theYellowHueOffset = 0.0; theYellowHueLowRange = 30.0; theYellowHueHighRange = 90.0; theYellowHueBlendRange = DEFAULT_BLEND; theYellowSaturationOffset = 0.0; theYellowIntensityOffset = 0.0; theGreenHueOffset = 0.0; theGreenHueLowRange = 90.0; theGreenHueHighRange = 150.0; theGreenHueBlendRange = DEFAULT_BLEND; theGreenSaturationOffset = 0.0; theGreenIntensityOffset = 0.0; theCyanHueOffset = 0.0; theCyanHueLowRange = 150.0; theCyanHueHighRange = 210.0; theCyanHueBlendRange = DEFAULT_BLEND; theCyanSaturationOffset = 0.0; theCyanIntensityOffset = 0.0; theBlueHueOffset = 0.0; theBlueHueLowRange = 210.0; theBlueHueHighRange = 270.0; theBlueHueBlendRange = DEFAULT_BLEND; theBlueSaturationOffset = 0.0; theBlueIntensityOffset = 0.0; theMagentaHueOffset = 0.0; theMagentaHueLowRange = 270.0; theMagentaHueHighRange = 330.0; theMagentaHueBlendRange = DEFAULT_BLEND; theMagentaSaturationOffset = 0.0; theMagentaIntensityOffset = 0.0; theWhiteObjectClip = 1.0; theValidFlag = false; //disableSource(); } void ossimHsiRemapper::resetMaster() { theMasterHueOffset = 0.0; theMasterSaturationOffset = 0.0; theMasterIntensityOffset = 0.0; theMasterIntensityLowClip = 0.0; theMasterIntensityHighClip = 1.0; verifyEnabled(); } void ossimHsiRemapper::resetRed() { theRedHueOffset = 0.0; theRedHueLowRange = -30.0; theRedHueHighRange = 30.0; theRedHueBlendRange = DEFAULT_BLEND; theRedSaturationOffset = 0.0; theRedIntensityOffset = 0.0; verifyEnabled(); } void ossimHsiRemapper::resetYellow() { theYellowHueOffset = 0.0; theYellowHueLowRange = 30.0; theYellowHueHighRange = 90.0; theYellowHueBlendRange = DEFAULT_BLEND; theYellowSaturationOffset = 0.0; theYellowIntensityOffset = 0.0; verifyEnabled(); } void ossimHsiRemapper::resetGreen() { theGreenHueOffset = 0.0; theGreenHueLowRange = 90.0; theGreenHueHighRange = 150.0; theGreenHueBlendRange = DEFAULT_BLEND; theGreenSaturationOffset = 0.0; theGreenIntensityOffset = 0.0; verifyEnabled(); } void ossimHsiRemapper::resetCyan() { theCyanHueOffset = 0.0; theCyanHueLowRange = 150.0; theCyanHueHighRange = 210.0; theCyanHueBlendRange = DEFAULT_BLEND; theCyanSaturationOffset = 0.0; theCyanIntensityOffset = 0.0; verifyEnabled(); } void ossimHsiRemapper::resetBlue() { theBlueHueOffset = 0.0; theBlueHueLowRange = 210.0; theBlueHueHighRange = 270.0; theBlueHueBlendRange = DEFAULT_BLEND; theBlueSaturationOffset = 0.0; theBlueIntensityOffset = 0.0; verifyEnabled(); } void ossimHsiRemapper::resetMagenta() { theMagentaHueOffset = 0.0; theMagentaHueLowRange = 270.0; theMagentaHueHighRange = 330.0; theMagentaHueBlendRange = DEFAULT_BLEND; theMagentaSaturationOffset = 0.0; theMagentaIntensityOffset = 0.0; verifyEnabled(); } void ossimHsiRemapper::verifyEnabled() { // Start off disabled... //disableSource(); theValidFlag = false; if (!theInputConnection) { //*** // Since this filter can be constructed with no input connection do not // output and error, simply return. //*** return; } //*** // Add all the offsets and the low clips. // If greater than zero enable getTile method. //*** double d = theMasterHueOffset + theMasterSaturationOffset + theMasterIntensityOffset + theMasterIntensityLowClip + theRedHueOffset + theRedSaturationOffset + theRedIntensityOffset + theYellowHueOffset + theYellowSaturationOffset + theYellowIntensityOffset + theGreenHueOffset + theGreenSaturationOffset + theGreenIntensityOffset + theCyanHueOffset + theCyanSaturationOffset + theCyanIntensityOffset + theBlueHueOffset + theBlueSaturationOffset + theBlueIntensityOffset + theMagentaHueOffset + theMagentaSaturationOffset + theMagentaIntensityOffset; if ( d != 0.0 || theMasterIntensityHighClip != 1.0 || theWhiteObjectClip != 1.0 ) { theValidFlag = true; // enableSource(); } } void ossimHsiRemapper::setMasterHueOffset(double offset) { if (offset >= -180.0 && offset <= 180.0) { theMasterHueOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMasterHueOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -180.0 and less than" << "\nor equal to 180.0" << endl; } } void ossimHsiRemapper::setMasterSaturationOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theMasterSaturationOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMasterSaturationOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setMasterIntensityOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theMasterIntensityOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMasterIntensityOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setMasterIntensityLowClip(double clip) { if (clip >= 0.0 && clip < theMasterIntensityHighClip) { theMasterIntensityLowClip = clip; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMasterIntensityClip range error:" << "\nLow clip of " << clip << " is out of range!" << "\nMust be equal to or greater than 0.0 and less than" << "\nthe high clip of " << theMasterIntensityHighClip << endl; } } void ossimHsiRemapper::setMasterIntensityHighClip(double clip) { if (clip <= 1.0 && clip > theMasterIntensityLowClip) { theMasterIntensityHighClip = clip; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMasterIntensityHighClip range error:" << "\nHigh clip of " << clip << " is out of range!" << "\nMust be greater than low clip of " << theMasterIntensityLowClip << " and less than 1.0" << endl; } } void ossimHsiRemapper::setRedHueOffset(double offset) { if (offset >= -180.0 && offset <= 180.0) { theRedHueOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setRedHueOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -180.0 and less than" << "\nor equal to 180.0" << endl; } } void ossimHsiRemapper::setRedHueLowRange(double range) { //*** // Default red range: 330 - 30 // Allow 315 to 15 as long as it's less than the high range. // Note: Store the range as a negative if it's between 315 and 360. //*** double r = range; double h = theRedHueHighRange; if (r >= 315.0 && r < 360.0) r = r - 360.0; if (h >= 315.0 && h < 360.0) h = h - 360.0; if (r >= -45.0 && r <= 15.0 && r < h) { theRedHueLowRange = r; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setRedHueLow range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setRedHueHighRange(double range) { if (range == 360.0) range = 0.0; //*** // Default red range: 330 - 30 // Allow 345 to 45 as long as it's greater than the low range. // Note: Store the range as a negative if it's between 345 and 360. //*** double r = range; double l = theRedHueLowRange; if (r >= 315.0 && r < 360.0) r = r - 360.0; if (l >= 315.0 && l < 360.0) l = l - 360.0; if (r >= -15.0 && r <= 45 && l < r) { theRedHueHighRange = r; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setRedHueHigh range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setRedHueBlendRange(double range) { //*** // Allowable range: 0.0 to 30.0 as long as it's not greater than the // half range. If so snap it to half range. //*** if ( range >= 0.0 && range <= MAX_BLEND ) { double half_range = (theRedHueHighRange - theRedHueLowRange) / 2.0; if (range <= half_range) { theRedHueBlendRange = range; } else { // Put it in the middle of the range. ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setRedHueBlendRange range error:" << "\nRange of " << range << " is greater than the full range" << "\ndivided by 2!" << endl; theRedHueBlendRange = half_range; } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setRedHueBlendRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setRedSaturationOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theRedSaturationOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setRedSaturationOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setRedIntensityOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theRedIntensityOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setRedIntensityOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setYellowHueOffset(double offset) { if (offset >= -180.0 && offset <= 180.0) { theYellowHueOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setYellowHueOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -180.0 and less than" << "\nor equal to 180.0" << endl; } } void ossimHsiRemapper::setYellowHueLowRange(double range) { //*** // Default yellow range: 30 - 90 // Allow 15 to 75 as long as it's less than the high range. //*** if ( range >= 15.0 && range <= 75.0 && range < theYellowHueHighRange ) { theYellowHueLowRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setYellowHueLowRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setYellowHueHighRange(double range) { //*** // Default yellow range: 30 - 90 // Allow 45 to 105 as long as it's greater than the low range. //*** if ( range >= 45.0 && range <= 105.0 && range > theYellowHueLowRange ) { theYellowHueHighRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setYellowHueHighRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setYellowHueBlendRange(double range) { //*** // Allowable range: 0.0 to 30.0 as long as it's not greater than the // half range. If so snap it to half range. //*** if ( range >= 0.0 && range <= MAX_BLEND ) { double half_range = (theYellowHueHighRange - theYellowHueLowRange) / 2.0; if (range <= half_range) { theYellowHueBlendRange = range; } else { // Put it in the middle of the range. ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setYellowHueBlendRange range error:" << "\nRange of " << range << " is greater than the full range" << "\ndivided by 2!" << endl; theYellowHueBlendRange = half_range; } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setYellowHueBlendRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setYellowSaturationOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theYellowSaturationOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setYellowSaturationOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setYellowIntensityOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theYellowIntensityOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setYellowIntensityOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setGreenHueOffset(double offset) { if (offset >= -180.0 && offset <= 180.0) { theGreenHueOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setGreenHueOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -180.0 and less than" << "\nor equal to 180.0" << endl; } } void ossimHsiRemapper::setGreenHueLowRange(double range) { //*** // Default green range: 90 - 150 // Allow 75 to 135 as long as it's less than the high range. //*** if ( range >= 75.0 && range <= 135.0 && range < theGreenHueHighRange ) { theGreenHueLowRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setGreenHueLowRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setGreenHueHighRange(double range) { //*** // Default green range: 90 - 150 // Allow 105 to 165 as long as it's greater than the low range. //*** if ( range >= 105.0 && range <= 165.0 && range > theGreenHueLowRange ) { theGreenHueHighRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setGreenHueHighRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setGreenHueBlendRange(double range) { //*** // Allowable range: 0.0 to 30.0 as long as it's not greater than the // half range. If so snap it to half range. //*** if ( range >= 0.0 && range <= MAX_BLEND ) { double half_range = (theGreenHueHighRange - theGreenHueLowRange) / 2.0; if (range <= half_range) { theGreenHueBlendRange = range; } else { // Put it in the middle of the range. ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setGreenHueBlendRange range error:" << "\nRange of " << range << " is greater than the full range" << "\ndivided by 2!" << endl; theGreenHueBlendRange = half_range; } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setGreenHueBlendRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setGreenSaturationOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theGreenSaturationOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setGreenSaturationOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setGreenIntensityOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theGreenIntensityOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setGreenIntensityOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setCyanHueOffset(double offset) { if (offset >= -180.0 && offset <= 180.0) { theCyanHueOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setCyanHueOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -180.0 and less than" << "\nor equal to 180.0" << endl; } } void ossimHsiRemapper::setCyanHueLowRange(double range) { //*** // Default cyan range: 150 - 210 // Allow 135 to 195 as long as it's less than the high range. //*** if ( range >= 135.0 && range <= 195.0 && range < theCyanHueHighRange ) { theCyanHueLowRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setCyanHueLowRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setCyanHueHighRange(double range) { //*** // Default cyan range: 150 - 210 // Allow 165 to 225 as long as it's greater than the low range. //*** if ( range >= 165.0 && range <= 225.0 && range > theCyanHueLowRange ) { theCyanHueHighRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setCyanHueHighRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setCyanHueBlendRange(double range) { //*** // Allowable range: 0.0 to 30.0 as long as it's not greater than the // half range. If so snap it to half range. //*** if ( range >= 0.0 && range <= MAX_BLEND ) { double half_range = (theCyanHueHighRange - theCyanHueLowRange) / 2.0; if (range <= half_range) { theCyanHueBlendRange = range; } else { // Put it in the middle of the range. ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setCyanHueBlendRange range error:" << "\nRange of " << range << " is greater than the full range" << "\ndivided by 2!" << endl; theCyanHueBlendRange = half_range; } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setCyanHueBlendRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setCyanSaturationOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theCyanSaturationOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setCyanSaturationOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setCyanIntensityOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theCyanIntensityOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setCyanIntensityOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setBlueHueOffset(double offset) { if (offset >= -180.0 && offset <= 180.0) { theBlueHueOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setBlueHueOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -180.0 and less than" << "\nor equal to 180.0" << endl; } } void ossimHsiRemapper::setBlueHueLowRange(double range) { //*** // Default blue range: 210 - 270 // Allow 195 to 255 as long as it's less than the high range. //*** if ( range >= 195.0 && range <= 255.0 && range < theBlueHueHighRange ) { theBlueHueLowRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setBlueHueLowRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setBlueHueHighRange(double range) { //*** // Default blue range: 210 - 270 // Allow 225 to 285 as long as it's greater than the low range. //*** if ( range >= 225.0 && range <= 285.0 && range > theBlueHueLowRange ) { theBlueHueHighRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setBlueHueHighRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setBlueHueBlendRange(double range) { //*** // Allowable range: 0.0 to 30.0 as long as it's not greater than the // half range. If so snap it to half range. //*** if ( range >= 0.0 && range <= MAX_BLEND ) { double half_range = (theBlueHueHighRange - theBlueHueLowRange) / 2.0; if (range <= half_range) { theBlueHueBlendRange = range; } else { // Put it in the middle of the range. ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setBlueHueBlendRange range error:" << "\nRange of " << range << " is greater than the full range" << "\ndivided by 2!" << endl; theBlueHueBlendRange = half_range; } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setBlueHueBlendRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setBlueSaturationOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theBlueSaturationOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setBlueSaturationOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setBlueIntensityOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theBlueIntensityOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setBlueIntensityOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setMagentaHueOffset(double offset) { if (offset >= -180.0 && offset <= 180.0) { theMagentaHueOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMagentaHueOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -180.0 and less than" << "\nor equal to 180.0" << endl; } } void ossimHsiRemapper::setMagentaHueLowRange(double range) { //*** // Default magenta range: 270 - 330 // Allow 255 to 315 as long as it's less than the high range. //*** if ( range >= 255.0 && range <= 315.0 && range < theMagentaHueHighRange ) { theMagentaHueLowRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMagentaHueLowRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setMagentaHueHighRange(double range) { //*** // Default magenta range: 270 - 330 // Allow 285 to 345 as long as it's greater than the low range. //*** if ( range >= 285.0 && range <= 345.0 && range > theMagentaHueLowRange ) { theMagentaHueHighRange = range; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMagentaHueHighRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setMagentaHueBlendRange(double range) { //*** // Allowable range: 0.0 to 30.0 as long as it's not greater than the // half range. If so snap it to half range. //*** if ( range >= 0.0 && range <= MAX_BLEND ) { double half_range = (theMagentaHueHighRange-theMagentaHueLowRange)/2.0; if (range <= half_range) { theMagentaHueBlendRange = range; } else { // Put it in the middle of the range. ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMagentaHueBlendRange range error:" << "\nRange of " << range << " is greater than the full range" << "\ndivided by 2!" << endl; theMagentaHueBlendRange = half_range; } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMagentaHueBlendRange range error:" << "\nRange of " << range << " is out of range!" << endl; } } void ossimHsiRemapper::setMagentaSaturationOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theMagentaSaturationOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMagentaSaturationOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } void ossimHsiRemapper::setMagentaIntensityOffset(double offset) { if (offset >= -1.0 && offset <= 1.0) { theMagentaIntensityOffset = offset; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHsiRemapper::setMagentaIntensityOffset range error:" << "\nOffset of " << offset << " is out of range!" << "\nMust be equal to or greater than -1.0 and less than" << "\nor equal to 1.0" << endl; } } double ossimHsiRemapper::calculateMinNormValue() { static const char MODULE[] = "ossimHsiRemapper::calculateMinNormValue"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Entered..." << endl; } if (!theTile) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nClass not initialized!" << endl; return 0.0; } double min_pix = theTile->getMinPix(0); double max_pix = theTile->getMaxPix(0); for (ossim_uint32 band=1; bandgetNumberOfBands(); ++band) { if (min_pix != theTile->getMinPix(band)) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Warning:" << "\nMixed minimum values for bands..." << endl; } if (max_pix != theTile->getMaxPix(band)) { ossimNotify(ossimNotifyLevel_WARN) << " Warning:" << "\nMixed maximum values for bands..." << endl; } } if (min_pix < 0.0) { // // Assigning some arbituary number for float data. // This should really come from the normalizer (ossimImageData) of // the data. // return OSSIM_DEFAULT_MIN_PIX_NORM_DOUBLE; } return (min_pix / max_pix); } ossim_uint32 ossimHsiRemapper::getNumberOfOutputBands() const { if (isSourceEnabled()&&theValidFlag) // Always rgb tile out... { return 3; } // Filter bypassed so getTile will return input tile. return ossimImageSourceFilter::getNumberOfInputBands(); } double ossimHsiRemapper::getMasterHueOffset () const { return theMasterHueOffset; } double ossimHsiRemapper::getMasterSaturationOffset() const { return theMasterSaturationOffset; } double ossimHsiRemapper::getMasterIntensityOffset() const { return theMasterIntensityOffset; } double ossimHsiRemapper::getMasterIntensityLowClip() const { return theMasterIntensityLowClip; } double ossimHsiRemapper::getMasterIntensityHighClip() const { return theMasterIntensityHighClip; } double ossimHsiRemapper::getRedHueOffset() const { return theRedHueOffset; } double ossimHsiRemapper::getRedHueLowRange() const { return theRedHueLowRange; } double ossimHsiRemapper::getRedHueHighRange() const { return theRedHueHighRange; } double ossimHsiRemapper::getRedHueBlendRange() const { return theRedHueBlendRange; } double ossimHsiRemapper::getRedSaturationOffset() const { return theRedSaturationOffset; } double ossimHsiRemapper::getRedIntensityOffset() const { return theRedIntensityOffset; } double ossimHsiRemapper::getYellowHueOffset () const { return theYellowHueOffset; } double ossimHsiRemapper::getYellowHueLowRange() const { return theYellowHueLowRange; } double ossimHsiRemapper::getYellowHueHighRange() const { return theYellowHueHighRange; } double ossimHsiRemapper::getYellowHueBlendRange() const { return theYellowHueBlendRange; } double ossimHsiRemapper::getYellowSaturationOffset() const { return theYellowSaturationOffset; } double ossimHsiRemapper::getYellowIntensityOffset() const { return theYellowIntensityOffset; } double ossimHsiRemapper::getGreenHueOffset () const { return theGreenHueOffset; } double ossimHsiRemapper::getGreenHueLowRange() const { return theGreenHueLowRange; } double ossimHsiRemapper::getGreenHueHighRange() const { return theGreenHueHighRange; } double ossimHsiRemapper::getGreenHueBlendRange() const { return theGreenHueBlendRange; } double ossimHsiRemapper::getGreenSaturationOffset() const { return theGreenSaturationOffset; } double ossimHsiRemapper::getGreenIntensityOffset() const { return theGreenIntensityOffset; } double ossimHsiRemapper::getCyanHueOffset () const { return theCyanHueOffset; } double ossimHsiRemapper::getCyanHueLowRange() const { return theCyanHueLowRange; } double ossimHsiRemapper::getCyanHueHighRange() const { return theCyanHueHighRange; } double ossimHsiRemapper::getCyanHueBlendRange() const { return theCyanHueBlendRange; } double ossimHsiRemapper::getCyanSaturationOffset() const { return theCyanSaturationOffset; } double ossimHsiRemapper::getCyanIntensityOffset() const { return theCyanIntensityOffset; } double ossimHsiRemapper::getBlueHueOffset () const { return theBlueHueOffset; } double ossimHsiRemapper::getBlueHueLowRange() const { return theBlueHueLowRange; } double ossimHsiRemapper::getBlueHueHighRange() const { return theBlueHueHighRange; } double ossimHsiRemapper::getBlueHueBlendRange() const { return theBlueHueBlendRange; } double ossimHsiRemapper::getBlueSaturationOffset() const { return theBlueSaturationOffset; } double ossimHsiRemapper::getBlueIntensityOffset() const { return theBlueIntensityOffset; } double ossimHsiRemapper::getMagentaHueOffset () const { return theMagentaHueOffset; } double ossimHsiRemapper::getMagentaHueLowRange() const { return theMagentaHueLowRange; } double ossimHsiRemapper::getMagentaHueHighRange() const { return theMagentaHueHighRange; } double ossimHsiRemapper::getMagentaHueBlendRange() const { return theMagentaHueBlendRange; } double ossimHsiRemapper::getMagentaSaturationOffset() const { return theMagentaSaturationOffset; } double ossimHsiRemapper::getMagentaIntensityOffset() const { return theMagentaIntensityOffset; } void ossimHsiRemapper::setHueOffset(int color_group, double offset) { switch (color_group) { case RED: setRedHueOffset(offset); break; case YELLOW: setYellowHueOffset(offset); break; case GREEN: setGreenHueOffset(offset); break; case CYAN: setCyanHueOffset(offset); break; case BLUE: setBlueHueOffset(offset); break; case MAGENTA: setMagentaHueOffset(offset); break; case ALL: setMasterHueOffset(offset); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::setHueOffset NOTICE: Range error!" << endl; } } void ossimHsiRemapper::setHueLowRange(int color_group, double range) { switch (color_group) { case RED: setRedHueLowRange(range); break; case YELLOW: setYellowHueLowRange(range); break; case GREEN: setGreenHueLowRange(range); break; case CYAN: setCyanHueLowRange(range); break; case BLUE: setBlueHueLowRange(range); break; case MAGENTA: setMagentaHueLowRange(range); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::setHueLowRange NOTICE: Range error!" << endl; } } void ossimHsiRemapper::setHueHighRange(int color_group, double range) { switch (color_group) { case RED: setRedHueHighRange(range); break; case YELLOW: setYellowHueHighRange(range); break; case GREEN: setGreenHueHighRange(range); break; case CYAN: setCyanHueHighRange(range); break; case BLUE: setBlueHueHighRange(range); break; case MAGENTA: setMagentaHueHighRange(range); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::setHueHighRange NOTICE: Range error!" << endl; } } void ossimHsiRemapper::setHueBlendRange(int color_group, double range) { switch (color_group) { case RED: setRedHueBlendRange(range); break; case YELLOW: setYellowHueBlendRange(range); break; case GREEN: setGreenHueBlendRange(range); break; case CYAN: setCyanHueBlendRange(range); break; case BLUE: setBlueHueBlendRange(range); break; case MAGENTA: setMagentaHueBlendRange(range); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::setHueBlendRange NOTICE: Range error!" << endl; } } void ossimHsiRemapper::setSaturationOffset(int color_group, double offset) { switch (color_group) { case RED: setRedSaturationOffset(offset); break; case YELLOW: setYellowSaturationOffset(offset); break; case GREEN: setGreenSaturationOffset(offset); break; case CYAN: setCyanSaturationOffset(offset); break; case BLUE: setBlueSaturationOffset(offset); break; case MAGENTA: setMagentaSaturationOffset(offset); break; case ALL: setMasterSaturationOffset(offset); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::setSaturationOffset NOTICE: Range error!" << endl; break; } } void ossimHsiRemapper::setIntensityOffset(int color_group, double offset) { switch (color_group) { case RED: setRedIntensityOffset(offset); break; case YELLOW: setYellowIntensityOffset(offset); break; case GREEN: setGreenIntensityOffset(offset); break; case CYAN: setCyanIntensityOffset(offset); break; case BLUE: setBlueIntensityOffset(offset); break; case MAGENTA: setMagentaIntensityOffset(offset); break; case ALL: setMasterIntensityOffset(offset); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::setIntensityOffset NOTICE: Range error!" << endl; break; } } double ossimHsiRemapper::getHueOffset(int color_group) const { switch (color_group) { case RED: return getRedHueOffset(); break; case YELLOW: return getYellowHueOffset(); break; case GREEN: return getGreenHueOffset(); break; case CYAN: return getCyanHueOffset(); break; case BLUE: return getBlueHueOffset(); break; case MAGENTA: return getMagentaHueOffset(); break; case ALL: return getMasterHueOffset(); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::getHueOffset NOTICE: Range error!" << endl; break; } return 0.0; } double ossimHsiRemapper::getHueLowRange(int color_group) const { switch (color_group) { case RED: return getRedHueLowRange(); break; case YELLOW: return getYellowHueLowRange(); break; case GREEN: return getGreenHueLowRange(); break; case CYAN: return getCyanHueLowRange(); break; case BLUE: return getBlueHueLowRange(); break; case MAGENTA: return getMagentaHueLowRange(); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::getHueLowRange NOTICE: Range error!" << endl; break; } return 0.0; } double ossimHsiRemapper::getHueHighRange(int color_group) const { switch (color_group) { case RED: return getRedHueHighRange(); break; case YELLOW: return getYellowHueHighRange(); break; case GREEN: return getGreenHueHighRange(); break; case CYAN: return getCyanHueHighRange(); break; case BLUE: return getBlueHueHighRange(); break; case MAGENTA: return getMagentaHueHighRange(); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::getHueHighRange NOTICE: Range error!" << endl; break; } return 0.0; } double ossimHsiRemapper::getHueBlendRange(int color_group) const { switch (color_group) { case RED: return getRedHueBlendRange(); break; case YELLOW: return getYellowHueBlendRange(); break; case GREEN: return getGreenHueBlendRange(); break; case CYAN: return getCyanHueBlendRange(); break; case BLUE: return getBlueHueBlendRange(); break; case MAGENTA: return getMagentaHueBlendRange(); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::getHueBlendRange NOTICE: Range error!" << endl; break; } return 0.0; } double ossimHsiRemapper::getSaturationOffset(int color_group) const { switch (color_group) { case RED: return getRedSaturationOffset(); break; case YELLOW: return getYellowSaturationOffset(); break; case GREEN: return getGreenSaturationOffset(); break; case CYAN: return getCyanSaturationOffset(); break; case BLUE: return getBlueSaturationOffset(); break; case MAGENTA: return getMagentaSaturationOffset(); break; case ALL: return getMasterSaturationOffset(); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::getSaturationOffset NOTICE: Range error!" << endl; break; } return 0.0; } double ossimHsiRemapper::getIntensityOffset(int color_group) const { switch (color_group) { case RED: return getRedIntensityOffset(); break; case YELLOW: return getYellowIntensityOffset(); break; case GREEN: return getGreenIntensityOffset(); break; case CYAN: return getCyanIntensityOffset(); break; case BLUE: return getBlueIntensityOffset(); break; case MAGENTA: return getMagentaIntensityOffset(); break; case ALL: return getMasterIntensityOffset(); break; default: ossimNotify(ossimNotifyLevel_NOTICE) << "ossimHsiRemapper::getIntensityOffset NOTICE: Range error!" << endl; break; } return 0.0; } void ossimHsiRemapper::setWhiteObjectClip(double clip) { if ( (clip >= .8) && (clip <= 1.0) ) { theWhiteObjectClip = clip; verifyEnabled(); } else { ossimNotify(ossimNotifyLevel_WARN) << "HsiRemapper::setWhiteObjectClip range error:" << "\nClip of " << clip << " is out of range!" << "\nMust be between .8 and 1.0" << endl; } } double ossimHsiRemapper::getWhiteObjectClip() const { return theWhiteObjectClip; } void ossimHsiRemapper::resetWhiteObjectClip() { theWhiteObjectClip = 1.0; verifyEnabled(); } ossimString ossimHsiRemapper::getLongName()const { return ossimString("HSI Remapper, filter with controls for all HSI(Hue, Saturation, and Intensity) adjustments."); } ossimString ossimHsiRemapper::getShortName()const { return ossimString("HSI Remapper"); } ostream& ossimHsiRemapper::print(ostream& os) const { os << setiosflags(ios::fixed) << setprecision(2) << "\nossimHsiRemapper:" << "\ntheEnableFlag: " << theEnableFlag << "\ntheMasterHueOffset: " << theMasterHueOffset << "\ntheMasterSaturationOffset: " << theMasterSaturationOffset << "\ntheMasterIntensityOffset: " << theMasterIntensityOffset << "\ntheMasterIntensityLowClip: " << theMasterIntensityLowClip << "\ntheMasterIntensityHighClip: " << theMasterIntensityHighClip << "\ntheRedHueOffset: " << theRedHueOffset << "\ntheRedHueLowRange: " << theRedHueLowRange << "\ntheRedHueHighRange: " << theRedHueHighRange << "\ntheRedSaturationOffset: " << theRedSaturationOffset << "\ntheRedIntensityOffset: " << theRedIntensityOffset << "\ntheYellowHueOffset: " << theYellowHueOffset << "\ntheYellowHueLowRange: " << theYellowHueLowRange << "\ntheYellowHueHighRange: " << theYellowHueHighRange << "\ntheYellowSaturationOffset: " << theYellowSaturationOffset << "\ntheYellowIntensityOffset: " << theYellowIntensityOffset << "\ntheGreenHueOffset: " << theGreenHueOffset << "\ntheGreenHueLowRange: " << theGreenHueLowRange << "\ntheGreenHueHighRange: " << theGreenHueHighRange << "\ntheGreenSaturationOffset: " << theGreenSaturationOffset << "\ntheGreenIntensityOffset: " << theGreenIntensityOffset << "\ntheCyanHueOffset: " << theCyanHueOffset << "\ntheCyanHueLowRange: " << theCyanHueLowRange << "\ntheCyanHueHighRange: " << theCyanHueHighRange << "\ntheCyanSaturationOffset: " << theCyanSaturationOffset << "\ntheCyanIntensityOffset: " << theCyanIntensityOffset << "\ntheBlueHueOffset: " << theBlueHueOffset << "\ntheBlueHueLowRange: " << theBlueHueLowRange << "\ntheBlueHueHighRange: " << theBlueHueHighRange << "\ntheBlueSaturationOffset: " << theBlueSaturationOffset << "\ntheBlueIntensityOffset: " << theBlueIntensityOffset << "\ntheMagentaHueOffset: " << theMagentaHueOffset << "\ntheMagentaHueLowRange: " << theMagentaHueLowRange << "\ntheMagentaHueHighRange: " << theMagentaHueHighRange << "\ntheMagentaSaturationOffset: " << theMagentaSaturationOffset << "\ntheMagentaIntensityOffset: " << theMagentaIntensityOffset << "\ntheWhiteObjectClip: " << theWhiteObjectClip << endl; return os; } ostream& operator<<(ostream& os, const ossimHsiRemapper& hr) { return hr.print(os); } ossim-Miami-2.9.1/src/imaging/ossimHsiToRgbSource.cpp000066400000000000000000000075631352751253100225510ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHsiToRgbSource.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include #include RTTI_DEF1(ossimHsiToRgbSource, "ossimHsiToRgbSource", ossimImageSourceFilter) ossimHsiToRgbSource::ossimHsiToRgbSource() :ossimImageSourceFilter(), theBlankTile(NULL), theTile(NULL) { } ossimHsiToRgbSource::ossimHsiToRgbSource(ossimImageSource* inputSource) : ossimImageSourceFilter(inputSource), theBlankTile(NULL), theTile(NULL) { } ossimHsiToRgbSource::~ossimHsiToRgbSource() { } ossimRefPtr ossimHsiToRgbSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return NULL; // This filter requires an input. } ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if(!isSourceEnabled()) { return inputTile; } if(!theTile.valid()) { allocate(); // First time through... } if( !inputTile.valid() || inputTile->getDataObjectStatus() == OSSIM_NULL || inputTile->getDataObjectStatus() == OSSIM_EMPTY ) { theBlankTile->setImageRectangle(tileRect); return theBlankTile; } if((inputTile->getNumberOfBands()==3)&& (inputTile->getScalarType()==OSSIM_NORMALIZED_FLOAT)&& (inputTile->getDataObjectStatus()!=OSSIM_NULL)) { // Set the origin, resize if needed of the output tile. theTile->setImageRectangle(tileRect); ossim_uint8* outputBands[3]; float* inputBands[3]; outputBands[0] = static_cast(theTile->getBuf(0)); outputBands[1] = static_cast(theTile->getBuf(1)); outputBands[2] = static_cast(theTile->getBuf(2)); inputBands[0] = static_cast(inputTile->getBuf(0)); inputBands[1] = static_cast(inputTile->getBuf(1)); inputBands[2] = static_cast(inputTile->getBuf(2)); long height = inputTile->getHeight(); long width = inputTile->getWidth(); long offset = 0; for(long row = 0; row < height; ++row) { for(long col = 0; col < width; ++col) { ossimHsiVector hsi(inputBands[0][offset], inputBands[1][offset], inputBands[2][offset]); ossimRgbVector rgb(hsi); outputBands[0][offset] = rgb.getR(); outputBands[1][offset] = rgb.getG(); outputBands[2][offset] = rgb.getB(); ++offset; } } } else { return inputTile; } theTile->validate(); return theTile; } void ossimHsiToRgbSource::initialize() { ossimImageSourceFilter::initialize(); } void ossimHsiToRgbSource::allocate() { theBlankTile = ossimImageDataFactory::instance()->create(this, this); theTile = (ossimImageData*)theBlankTile->dup(); theTile->initialize(); } ossimScalarType ossimHsiToRgbSource::getOutputScalarType() const { return OSSIM_UCHAR; } double ossimHsiToRgbSource::getNullPixelValue()const { return 0.0; } double ossimHsiToRgbSource::getMinPixelValue(ossim_uint32 /* band */)const { return OSSIM_DEFAULT_MIN_PIX_UCHAR; } double ossimHsiToRgbSource::getMaxPixelValue(ossim_uint32 /* band */)const { return OSSIM_DEFAULT_MAX_PIX_UCHAR; } ossim-Miami-2.9.1/src/imaging/ossimHsvGridRemapEngine.cpp000066400000000000000000000222231352751253100233560ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimHsvGridRemapEngine.cc // // Copyright (C) 2001 ImageLinks, Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains implementation of class // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimHsvGridRemapEngine.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include RTTI_DEF1(ossimHsvGridRemapEngine, "ossimHsvGridRemapEngine", ossimGridRemapEngine); #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimHsvGridRemapEngine:exec"); static ossimTrace traceDebug ("ossimHsvGridRemapEngine:debug"); using namespace std; //***************************************************************************** // METHOD: ossimHsvGridRemapEngine::remapTile // //***************************************************************************** ossimObject* ossimHsvGridRemapEngine::dup() const { return new ossimHsvGridRemapEngine; } //***************************************************************************** // METHOD: ossimHsvGridRemapEngine::remapTile // //***************************************************************************** void ossimHsvGridRemapEngine::remapTile(const ossimDpt& origin, ossimGridRemapSource* remapper, ossimRefPtr& tile) { static const char MODULE[] = "ossimHsvGridRemapEngine::remapTile"; if (traceExec()) CLOG << "entering..." << endl; //*** // Fetch tile size and NULL pixel value: //*** int width = tile->getWidth(); int height = tile->getHeight(); int offset = 0; void* red_buf = tile->getBuf(0); void* grn_buf = tile->getBuf(1); void* blu_buf = tile->getBuf(2); ossimDblGrid& gridH = *(remapper->getGrid(0)); ossimDblGrid& gridS = *(remapper->getGrid(1)); ossimDblGrid& gridV = *(remapper->getGrid(2)); //--- // Remap according to pixel type: //--- switch(tile->getScalarType()) { case OSSIM_UINT8: { for (double line=origin.line; line& sources_list) { static const char MODULE[] = "ossimHsvGridRemapEngine::assignRemapValues"; if (traceExec()) CLOG << "entering..." << endl; int i; // index to individual sources //*** // Declare a 2D array that will contain all of the contributing sources' // HSV mean values. Also declare the accumulator target vector. //*** int num_contributors = (int)sources_list.size(); double** contributor_pixel = new double* [num_contributors]; for (i=0; i::iterator source; i = 0; for(source = sources_list.begin(); source != sources_list.end(); source++) { (*source)->getSourceValue(contributor_pixel[i]); target_pixel[0] += contributor_pixel[i][0]/(double)num_contributors; target_pixel[1] += contributor_pixel[i][1]/(double)num_contributors; target_pixel[2] += contributor_pixel[i][2]/(double)num_contributors; i++; } //*** // The target pixel has been established. Now need to compute the actual // remap quantities that will be written to the appropriate remap grids: //*** i = 0; for(source = sources_list.begin(); source != sources_list.end(); source++) { computeRemapNode(*source, contributor_pixel[i], target_pixel); i++; } //*** // Delete locally allocated memory: //*** for (i=0; i& source, void* result) { static const char MODULE[]="ossimHsvGridRemapEngine::computeSourceValue"; if (traceExec()) CLOG << "entering..." << endl; //*** // This engine defines "value" as the HSV vector corresponding to the mean // RGB pixel value of the source data: //*** ossimRgbVector rgb_vector; rgb_vector.setR((unsigned char) source->computeAverageBandValue(0)); rgb_vector.setG((unsigned char) source->computeAverageBandValue(1)); rgb_vector.setB((unsigned char) source->computeAverageBandValue(2)); //*** // Assign the HSV components to the result vector: //*** ossimHsvVector hsv_vector (rgb_vector); ((double*)result)[0] = (double) hsv_vector.getH(); ((double*)result)[1] = (double) hsv_vector.getS(); ((double*)result)[2] = (double) hsv_vector.getV(); if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimHsvGridRemapEngine::computeRemapNode // // This engine defines the remap value as the difference between the target // HSV vector and the individual point source's value vector. // //***************************************************************************** void ossimHsvGridRemapEngine::computeRemapNode(ossimAtbPointSource* ps, void* source_value, void* target_value) { static const char MODULE[] = "ossimHsvGridRemapEngine::computeRemapNode"; if (traceExec()) CLOG << "entering..." << endl; //*** // Compute the remap grid node value specific to this HSV implementation: //*** double node[3]; node[0] = ((double*)target_value)[0] - ((double*)source_value)[0]; node[1] = ((double*)target_value)[1] - ((double*)source_value)[1]; node[2] = ((double*)target_value)[2] - ((double*)source_value)[2]; //*** // Fetch a pointer to the remapper feeding this point source in order to // pass it the node value: //*** ossimGridRemapSource* remapper = ps->getRemapSource(); remapper->setGridNode(ps->getViewPoint(), node); if (traceExec()) CLOG << "returning..." << endl; return; } ossim-Miami-2.9.1/src/imaging/ossimHsvToRgbSource.cpp000066400000000000000000000104441352751253100225560ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimHsvToRgbSource.cpp 17195 2010-04-23 17:32:18Z dburken $ #include #include #include #include #include #include #include RTTI_DEF1(ossimHsvToRgbSource, "ossimHsvToRgbSource", ossimImageSourceFilter) ossimHsvToRgbSource::ossimHsvToRgbSource() :ossimImageSourceFilter(), theBlankTile(NULL), theTile(NULL) { } ossimHsvToRgbSource::ossimHsvToRgbSource(ossimImageSource* inputSource) : ossimImageSourceFilter(inputSource), theBlankTile(NULL), theTile(NULL) { } ossimHsvToRgbSource::~ossimHsvToRgbSource() { } ossimRefPtr ossimHsvToRgbSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(theInputConnection) { ossimRefPtr imageData = theInputConnection->getTile(tileRect, resLevel); if(!imageData.valid()) return theBlankTile; if(!isSourceEnabled()) { return imageData; } if(!theTile.valid()) allocate(); if(!theTile.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "Unable to initialize ossimHsvToRgbSource in getTile" << std::endl; return ossimRefPtr(); } long w = tileRect.width(); long h = tileRect.height(); long tw = theTile->getWidth(); long th = theTile->getHeight(); theBlankTile->setOrigin(tileRect.ul()); theBlankTile->setWidthHeight(w, h); theTile->setWidthHeight(w, h); theTile->setOrigin(tileRect.ul()); if( (tw*th) != (w*h)) { theTile->initialize(); } else { theTile->makeBlank(); } if((imageData->getNumberOfBands()==3)&& (imageData->getScalarType()==OSSIM_NORMALIZED_FLOAT)&& (imageData->getDataObjectStatus()!=OSSIM_NULL)) { ossim_uint8* outputBands[3]; float* inputBands[3]; outputBands[0] = static_cast(theTile->getBuf(0)); outputBands[1] = static_cast(theTile->getBuf(1)); outputBands[2] = static_cast(theTile->getBuf(2)); inputBands[0] = static_cast(imageData->getBuf(0)); inputBands[1] = static_cast(imageData->getBuf(1)); inputBands[2] = static_cast(imageData->getBuf(2)); long height = imageData->getHeight(); long width = imageData->getWidth(); long offset = 0; for(long row = 0; row < height; ++row) { for(long col = 0; col < width; ++col) { ossimHsvVector hsv(inputBands[0][offset], inputBands[1][offset], inputBands[2][offset]); ossimRgbVector rgb(hsv); outputBands[0][offset] = rgb.getR(); outputBands[1][offset] = rgb.getG(); outputBands[2][offset] = rgb.getB(); ++offset; } } } else { return imageData; } theTile->validate(); return theTile; } return theBlankTile; } void ossimHsvToRgbSource::initialize() { theBlankTile = NULL; theTile = NULL; } void ossimHsvToRgbSource::allocate() { theBlankTile = ossimImageDataFactory::instance()->create(this, this); theTile = (ossimImageData*)theBlankTile->dup(); theTile->initialize(); } ossimScalarType ossimHsvToRgbSource::getOutputScalarType() const { return OSSIM_UINT8; } double ossimHsvToRgbSource::getNullPixelValue()const { return 0; } double ossimHsvToRgbSource::getMinPixelValue(ossim_uint32 /* band */)const { return OSSIM_DEFAULT_MIN_PIX_UCHAR; } double ossimHsvToRgbSource::getMaxPixelValue(ossim_uint32 /* band */)const { return OSSIM_DEFAULT_MAX_PIX_UCHAR; } ossim-Miami-2.9.1/src/imaging/ossimIgenGenerator.cpp000066400000000000000000000455151352751253100224370ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimIgenGenerator.cpp 20206 2011-11-04 15:16:31Z dburken $ #include #include #include #include #include #include #include #include #include using namespace std; void ossimIgenGenerator::generateSpecList(bool outputToFileFlag) { if(theTilingFlag&& (theTileSpacingUnits!=OSSIM_UNIT_UNKNOWN)&& (!theTileSpacing.hasNans())) { generateTiledSpecList(outputToFileFlag); } else { generateNoTiledSpecList(outputToFileFlag); } } void ossimIgenGenerator::getImageFilenamesFromSpecList(std::vector& filenameList) { if(!theSpecList.size()) { generateSpecList(); } if(theSpecList.size()) { filenameList.clear(); for(ossim_uint32 i = 0; i < theSpecList.size(); ++i) { const char* filename = theSpecList[i].find("object2.", ossimKeywordNames::FILENAME_KW); if(filename) { filenameList.push_back(ossimFilename(filename)); } else { filenameList.clear(); return; } } } } ossimGrect ossimIgenGenerator::getBoundingGround()const { return ossimGrect(theOutputGeoPolygon[0], theOutputGeoPolygon[1], theOutputGeoPolygon[2], theOutputGeoPolygon[3]); } void ossimIgenGenerator::executeSpecList() { } void ossimIgenGenerator::setInput(ossimConnectableObject* input) { theSpecList.clear(); generateInputKwl(input); ossimImageSource* inputInterface = PTR_CAST(ossimImageSource, input); if(inputInterface) { theInputBoundingRect = inputInterface->getBoundingRect(); } } void ossimIgenGenerator::generateChainForMultiInput(ossimConnectableObject* connectable) { std::stack aStack; generateChainForMultiInputRecurse(aStack, connectable); ossim_int32 objectIndex = 1; while(!aStack.empty()) { ossimConnectableObject* current = aStack.top(); aStack.pop(); ossimString prefix = ossimString("object") + ossimString::toString(objectIndex) + "."; current->saveState(theInputKwl, prefix.c_str()); ++objectIndex; } theInputKwl.add("type", "ossimImageChain", true); } void ossimIgenGenerator::generateChainForMultiInputRecurse(std::stack& aStack, ossimConnectableObject* connectable) { if(connectable) { aStack.push(connectable); for(ossim_uint32 i = 0; i < connectable->getNumberOfInputs(); ++i) { generateChainForMultiInputRecurse(aStack, connectable->getInput(i)); } } } ossimProjection* ossimIgenGenerator::createProductProjection()const { return ossimProjectionFactoryRegistry::instance()->createProjection(theViewKwl); } ossimObject* ossimIgenGenerator::createOutput()const { return ossimObjectFactoryRegistry::instance()->createObject(theOutputKwl); } ossimObject* ossimIgenGenerator::createInput()const { return ossimObjectFactoryRegistry::instance()->createObject(theInputKwl); } void ossimIgenGenerator::generateInputKwl(ossimConnectableObject* connectable) { theInputKwl.clear(); if(connectable) { // if it has at least one non null input // then we must build a chain and save it out if(connectable->getInput()) { generateChainForMultiInput(connectable); } else // it is a single input { connectable->saveState(theInputKwl); } } } void ossimIgenGenerator::generateOutputKwl(ossimConnectableObject* connectable) { theOutputKwl.clear(); if(connectable) { connectable->saveState(theOutputKwl); } } void ossimIgenGenerator::generateViewKwl(ossimObject* view) { theViewKwl.clear(); if(view) { view->saveState(theViewKwl); } } void ossimIgenGenerator::setDefaultOutput() { } void ossimIgenGenerator::generateTiledSpecList(bool outputToFileFlag) { theSpecList.clear(); theSpecFileList.clear(); ossimDpt spacing = theTileSpacing; switch(theTileSpacingUnits) { case OSSIM_MINUTES: { spacing.x /= 60; spacing.y /= 60; generateGeoTiledSpecList(spacing, outputToFileFlag); break; } case OSSIM_SECONDS: { spacing.x /= 3600; spacing.y /= 3600; generateGeoTiledSpecList(spacing, outputToFileFlag); break; } case OSSIM_DEGREES: { generateGeoTiledSpecList(spacing, outputToFileFlag); break; } case OSSIM_PIXEL: { generatePixelTiledSpecList(outputToFileFlag); break; } default: break; } } void ossimIgenGenerator::generatePixelTiledSpecList(bool outputToFileFlag) { ossimRefPtr proj = createProductProjection(); if((!proj)||(theOutputGeoPolygon.size() != 4)) { return; } ossimIrect inputRect = getInputBoundingRect(); inputRect.stretchToTileBoundary(theTileSpacing); ossimGeoPolygon tempPoly; ossimObject* obj = createInput(); ossimImageChain* chain = PTR_CAST(ossimImageChain, obj); ossimGeoPolyCutter* cutter = new ossimGeoPolyCutter; chain->add(cutter); ossimKeywordlist kwl; ossimFilename outfile = theOutputKwl.find(ossimKeywordNames::FILENAME_KW); if(outfile == "") { cerr << "Valid filename not given, returning!" << endl; } kwl.add("object2.", theOutputKwl, true); kwl.add("product.projection.",theViewKwl, true); addPixelType(kwl, "product."); ossimDpt p1; ossimDpt p2; ossimDpt p3; ossimDpt p4; proj->worldToLineSample(theOutputGeoPolygon[0], p1); proj->worldToLineSample(theOutputGeoPolygon[1], p2); proj->worldToLineSample(theOutputGeoPolygon[2], p3); proj->worldToLineSample(theOutputGeoPolygon[3], p4); ossimIrect bounds(p1, p2, p3, p4); if(inputRect.completely_within(bounds)) { inputRect = bounds; } bounds.stretchToTileBoundary(theTileSpacing); ossim_sint32 i = 1; for(ossim_sint32 ulY = bounds.ul().y; ulY < bounds.lr().y; ulY+=(ossim_sint32)theTileSpacing.y) { for(ossim_sint32 ulX = bounds.ul().x; ulX < bounds.lr().x; ulX+=(ossim_sint32)theTileSpacing.x) { ossimDrect rect(ulX, ulY, ulX + (theTileSpacing.x - 1), ulY + (theTileSpacing.y - 1)); ossimGpt gpt1; ossimGpt gpt2; ossimGpt gpt3; ossimGpt gpt4; proj->lineSampleToWorld(rect.ul(), gpt1); proj->lineSampleToWorld(rect.ur(), gpt2); proj->lineSampleToWorld(rect.lr(), gpt3); proj->lineSampleToWorld(rect.ll(), gpt4); tempPoly.clear(); tempPoly.addPoint(gpt1); tempPoly.addPoint(gpt2); tempPoly.addPoint(gpt3); tempPoly.addPoint(gpt4); addPadding(tempPoly, tempPoly); cutter->setPolygon(tempPoly); chain->saveState(kwl, "object1."); ossimFilename specName(theSpecFileLocation); specName = specName.dirCat(ossimFilename("igen" + ossimString::toString(i) + ".spec")); ossimFilename tilename = outfile.path(); if(theTileNamingConvention == "id") { int tileId = getTileId(inputRect, ossimDpt(ulX+theTileSpacing.x/2, ulY+theTileSpacing.y/2), theTileSpacing); tilename = tilename.dirCat(ossimFilename(outfile.fileNoExtension() + "_" + ossimString::toString(tileId))); tilename.setExtension(outfile.ext()); } kwl.add("object2.", ossimKeywordNames::FILENAME_KW, tilename, true); kwl.add("object2.input_connection1", kwl.find("object1.id"), true); theSpecFileList.push_back(specName); if(outputToFileFlag) { kwl.write(specName.c_str()); } else { theSpecList.push_back(kwl); } i++; } } } void ossimIgenGenerator::generateGeoTiledSpecList(const ossimDpt& spacing, bool outputToFileFlag) { ossimRefPtr proj = createProductProjection(); if((proj.valid())&&(theOutputGeoPolygon.size() == 4)) { ossimDrect rect; ossimIrect inputRect = getInputBoundingRect(); ossimGpt gpt1; ossimGpt gpt2; ossimGpt gpt3; ossimGpt gpt4; proj->lineSampleToWorld(inputRect.ul(), gpt1); proj->lineSampleToWorld(inputRect.ur(), gpt2); proj->lineSampleToWorld(inputRect.lr(), gpt3); proj->lineSampleToWorld(inputRect.ll(), gpt4); ossimDrect inputGroundRect(gpt1, gpt2, gpt3, gpt4, OSSIM_RIGHT_HANDED); rect = ossimDrect(theOutputGeoPolygon[0], theOutputGeoPolygon[1], theOutputGeoPolygon[2], theOutputGeoPolygon[3], OSSIM_RIGHT_HANDED); rect.stretchToTileBoundary(spacing); inputGroundRect.stretchToTileBoundary(spacing); double ulLat = rect.ul().lat; double ulLon = rect.ul().lon; ossimGeoPolygon tempPoly; ossimObject* obj = createInput(); ossimImageChain* chain = PTR_CAST(ossimImageChain, obj); ossimGeoPolyCutter* cutter = new ossimGeoPolyCutter; chain->add(cutter); ossimKeywordlist kwl; ossimFilename outfile = theOutputKwl.find(ossimKeywordNames::FILENAME_KW); if(outfile == "") { cerr << "Valid filename not given, returning!" << endl; } kwl.add("object2.", theOutputKwl, true); kwl.add("object2.input_connection1", kwl.find("object1.id"), true); kwl.add("product.projection.",theViewKwl, true); addPixelType(kwl, "product."); int i = 1; int row = 0; int col = 0; // int tileId = 0; while(ulLat > rect.ll().lat) { ulLon = rect.ul().lon; col = 0; while(ulLon < rect.ur().lon) { tempPoly.clear(); tempPoly.addPoint(ulLat, ulLon, ossim::nan(), theOutputGeoPolygon[0].datum()); tempPoly.addPoint(ulLat, ulLon+spacing.lon, ossim::nan(), theOutputGeoPolygon[0].datum()); tempPoly.addPoint(ulLat-spacing.lat, ulLon+spacing.lon, ossim::nan(), theOutputGeoPolygon[0].datum()); tempPoly.addPoint(ulLat-spacing.lat, ulLon, ossim::nan(), theOutputGeoPolygon[0].datum()); addPadding(tempPoly, tempPoly); cutter->setPolygon(tempPoly); chain->saveState(kwl, "object1."); ossimFilename specName(theSpecFileLocation); specName = specName.dirCat(ossimFilename("igen" + ossimString::toString(i) + ".spec")); ossimFilename tilename = outfile.path(); if(theTileNamingConvention == "id") { int tileId = getTileId(inputGroundRect, ossimDpt(ulLon, ulLat), spacing); tilename = tilename.dirCat(ossimFilename(outfile.fileNoExtension() + "_" + ossimString::toString(tileId))); tilename.setExtension(outfile.ext()); } else { ossimUsgsQuad quad(ossimGpt(ulLat - (spacing.x), ulLon+(spacing.x), 0.0)); if(spacing.x == 7.5/60.0) { tilename = tilename.dirCat(ossimFilename(quad.quarterQuadName().downcase().trim())); } else { tilename = tilename.dirCat(ossimFilename(quad.quarterQuadSegName().downcase().trim())); } tilename.setExtension(outfile.ext()); } kwl.add("object2.", ossimKeywordNames::FILENAME_KW, tilename, true); kwl.add("object2.input_connection1", kwl.find("object1.id"), true); theSpecFileList.push_back(specName); if(outputToFileFlag) { kwl.write(specName.c_str()); } else { theSpecList.push_back(kwl); } ulLon += spacing.lon; ++i; ++col; } ++row; ulLat -= spacing.lat; } } } void ossimIgenGenerator::generateNoTiledSpecList(bool outputToFileFlag) { theSpecList.clear(); theSpecFileList.clear(); if(theViewKwl.getSize()&& theInputKwl.getSize()&& theOutputKwl.getSize()) { ossimKeywordlist kwl; if(theOutputGeoPolygon.size()) { ossimRefPtr obj = createInput(); ossimRefPtr chain = PTR_CAST(ossimImageChain, obj.get()); if(chain.valid()) { ossimGeoPolyCutter* cutter = new ossimGeoPolyCutter; cutter->setPolygon(theOutputGeoPolygon); chain->add(cutter); chain->saveState(kwl, "object1."); } else { kwl.add("object1.",theInputKwl, true); } obj = 0; } else { kwl.add("object1.",theInputKwl, true); } kwl.add("object2.", theOutputKwl, true); kwl.add("object2.input_connection1", kwl.find("object1.id"), true); kwl.add("product.projection.",theViewKwl, true); addPixelType(kwl, "product."); ossimFilename specName(theSpecFileLocation + "/"+ "igen1.spec"); theSpecFileList.push_back(specName); if(outputToFileFlag) { kwl.write(specName.c_str()); } else { theSpecList.push_back(kwl); } kwl.clear(); } } int ossimIgenGenerator::getTileId(const ossimDrect& rect, const ossimDpt& currentPt, const ossimDpt& spacing)const { ossimDpt ul(rect.ul()); double relY = fabs(ul.y - currentPt.y); double relX = fabs(ul.x - currentPt.x); ossim_int32 spacingY = (ossim_int32)(relY/spacing.y); ossim_int32 spacingX = (ossim_int32)(relX/spacing.x); ossim_int32 maxHorizontalTiles = (ossim_int32)( (rect.width()-1)/spacing.x); return spacingY*maxHorizontalTiles + spacingX; } ossimIrect ossimIgenGenerator::getInputBoundingRect()const { ossimRefPtr obj = createInput(); ossimImageSource* inter = PTR_CAST(ossimImageSource, obj.get()); ossimIrect result; result.makeNan(); if(inter) { result = inter->getBoundingRect(); } return result; } void ossimIgenGenerator::addPadding(ossimGeoPolygon& output, const ossimGeoPolygon& input)const { output = input; switch(theTilePaddingUnits) { case OSSIM_PIXEL: { ossimRefPtr proj = createProductProjection(); if(proj.valid()) { ossimDpt ul; ossimDpt ur; ossimDpt lr; ossimDpt ll; if(input.getOrdering() == OSSIM_CLOCKWISE_ORDER) { proj->worldToLineSample(input[0], ul); proj->worldToLineSample(input[1], ur); proj->worldToLineSample(input[2], lr); proj->worldToLineSample(input[3], ll); } else { proj->worldToLineSample(input[0], ul); proj->worldToLineSample(input[1], ll); proj->worldToLineSample(input[2], lr); proj->worldToLineSample(input[3], ur); } ul -= theTilePadding; ur += ossimDpt(theTilePadding.x, -theTilePadding.y); lr += theTilePadding; ll += ossimDpt(-theTilePadding.x, theTilePadding.y); proj->lineSampleToWorld(ul, output[0]); proj->lineSampleToWorld(ur, output[1]); proj->lineSampleToWorld(lr, output[2]); proj->lineSampleToWorld(ll, output[3]); output.setOrdering(OSSIM_CLOCKWISE_ORDER); } break; } case OSSIM_DEGREES: case OSSIM_MINUTES: case OSSIM_SECONDS: { ossimGpt ul; ossimGpt ur; ossimGpt lr; ossimGpt ll; ossimDpt spacing = theTilePadding; if(theTilePaddingUnits==OSSIM_MINUTES) { spacing.x /= 60; spacing.y /= 60; } else if(theTilePaddingUnits==OSSIM_MINUTES) { spacing.x /= 3600; spacing.y /= 3600; } if(input.getOrdering() == OSSIM_CLOCKWISE_ORDER) { ul = input[0]; ur = input[1]; lr = input[2]; ll = input[3]; } else { ul = input[0]; ll = input[1]; lr = input[2]; ur = input[3]; } ul.lat += spacing.lat; ul.lon -= spacing.lon; ur.lat += spacing.lat; ur.lon += spacing.lon; lr.lat -= spacing.lat; lr.lon += spacing.lon; ll.lat -= spacing.lat; ll.lon -= spacing.lon; output[0] = ul; output[1] = ur; output[2] = lr; output[3] = ll; output.setOrdering(OSSIM_CLOCKWISE_ORDER); break; } case OSSIM_METERS: { break; } default: break; } } void ossimIgenGenerator::addPixelType(ossimKeywordlist& kwl, const char* prefix) { if(thePixelType == OSSIM_PIXEL_IS_POINT) { kwl.add(prefix, ossimKeywordNames::PIXEL_TYPE_KW, "PIXEL_IS_POINT", true); } else { kwl.add(prefix, ossimKeywordNames::PIXEL_TYPE_KW, "PIXEL_IS_AREA", true); } } void ossimIgenGenerator::setOutput(const ossimKeywordlist& kwl) { theOutputKwl.clear(); theOutputKwl = kwl; } ossim-Miami-2.9.1/src/imaging/ossimImageCacheBase.cpp000066400000000000000000000442171352751253100224450ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // //******************************************************************** // $Id: ossimImageCacheBase.cpp 2685 2011-06-07 16:24:41Z david.burken $ #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug = ossimTrace("ossimImageCacheBase:debug"); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimImageCacheBase.cpp 2685 2011-06-07 16:24:41Z david.burken $"; #endif RTTI_DEF1(ossimImageCacheBase, "ossimImageCacheBase", ossimImageHandler) ossimImageCacheBase::ossimImageCacheBase() : ossimImageHandler(), m_actualImageRect(), m_numberOfLines(0), m_numberOfSamples(0), m_numberOfBands(0), m_fileNames(), m_tileSize(128, 128), m_workFrame(new ossimRpfFrame), m_bBox_LL_Lon(0.0), m_bBox_LL_Lat(0.0), m_bBox_UR_Lon(0.0), m_bBox_UR_Lat(0.0), m_numOfFramesVertical(0), m_numOfFramesHorizontal(0), m_frame_width(0), m_frame_height(0), m_frameEntryArray() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageCacheBase::ossimImageCacheBase entered...\n"; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << "\n"; #endif } m_actualImageRect.makeNan(); } ossimImageCacheBase::~ossimImageCacheBase() { if(m_workFrame) { delete m_workFrame; m_workFrame = 0; } close(); } void ossimImageCacheBase::close() { deleteAll(); } bool ossimImageCacheBase::isOpen()const { //return (theTableOfContents!=0); ossimString ext = theImageFile.ext().downcase(); if(ext == "rpf") { return true; } else { return false; } } bool ossimImageCacheBase::buildFrameEntryArray(ossimFilename imageFile, ossim_uint32 frameWidth, ossim_uint32 frameHeight) { static const char MODULE[] = "ossimImageCacheBase::buildFrameEntryArray"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << endl; } // use to check if tiles have overlap pixels ossim_float64 avgLat = 0.0; ossim_float64 avgLon = 0.0; m_frame_width = frameWidth; m_frame_height = frameHeight; std::ifstream in((imageFile).c_str() ); std::string line; ossim_uint32 index = 0; // used throughout while( in.good() ) { // Read in a line. std::getline(in, line); ossimString tmpStr = ossimString(line); if (!tmpStr.empty()) { if (index == 0) { std::vector box_lat_lon; tmpStr.split(box_lat_lon, "|"); if (box_lat_lon.size() > 2) { std::vector ll; std::vector ur; box_lat_lon[0].split(ll, ","); box_lat_lon[1].split(ur, ","); ossimString bandStr = box_lat_lon[2]; m_bBox_LL_Lon = ll[0].toFloat64(); m_bBox_LL_Lat = ll[1].toFloat64(); m_bBox_UR_Lon = ur[0].toFloat64(); m_bBox_UR_Lat = ur[1].toFloat64(); checkLongitude(m_bBox_LL_Lon, m_bBox_UR_Lon); m_numberOfBands = ossimString(bandStr).toInt32(); } else { return false; } } else if (index == 1) { m_fileNames.push_back(tmpStr); std::vector frame_lat_lon = tmpStr.split("|"); if (frame_lat_lon.size() > 2) { ossimString ll_lon_lat = frame_lat_lon[1]; ossimString ur_lon_lat = frame_lat_lon[2]; ossim_float64 ll_lon = ossimString(ll_lon_lat.split(",")[0]).toDouble(); ossim_float64 ll_lat = ossimString(ll_lon_lat.split(",")[1]).toDouble(); ossim_float64 ur_lon = ossimString(ur_lon_lat.split(",")[0]).toDouble(); ossim_float64 ur_lat = ossimString(ur_lon_lat.split(",")[1]).toDouble(); checkLongitude(ll_lon, ur_lon); ossim_float64 bBox_lat_diff = std::fabs(m_bBox_UR_Lat - m_bBox_LL_Lat); ossim_float64 bBox_lon_diff = std::fabs(m_bBox_UR_Lon - m_bBox_LL_Lon); ossim_float64 lat_diff = std::fabs(ur_lat - ll_lat); ossim_float64 lon_diff = std::fabs(ur_lon - ll_lon); m_numOfFramesVertical = static_cast(bBox_lat_diff/lat_diff + 0.5); m_numOfFramesHorizontal = static_cast(bBox_lon_diff/lon_diff + 0.5); avgLon = std::fabs(bBox_lon_diff/m_numOfFramesHorizontal); avgLat = std::fabs(bBox_lat_diff/m_numOfFramesVertical); m_numberOfLines = m_numOfFramesVertical*m_frame_height; m_numberOfSamples = m_numOfFramesHorizontal*m_frame_width; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nscene height in degrees: " << bBox_lat_diff << "\nscene width in degrees: " << bBox_lon_diff << "\nframe height in degrees: " << lat_diff << "\nframe width in degrees: " << lon_diff << "\nframes vertical: " << m_numOfFramesVertical << "\nframes horizontal: " << m_numOfFramesHorizontal << "\nlines: " << m_numberOfLines << "\nsamples: " << m_numberOfSamples << "\n"; } } else { return false; } } else { m_fileNames.push_back(tmpStr); } } // matches: if (!tmpStr.empty()) ++index; } // matches: while( in.good() ) in.close(); m_frameEntryArray.resize(m_numOfFramesVertical); for(index = 0; index < m_frameEntryArray.size(); ++index) { m_frameEntryArray[index].resize(m_numOfFramesHorizontal); } for(index = 0; index < m_fileNames.size(); ++index) { ossimString tmpStr = m_fileNames[index]; std::vector frameInfos = tmpStr.split("|"); if (frameInfos.size() > 1) { ossimString fileName = frameInfos[0]; ossimString ll_lon_lat = frameInfos[1]; ossimString ur_lon_lat = frameInfos[2]; double ll_lon = ossimString(ll_lon_lat.split(",")[0]).toDouble(); double ll_lat = ossimString(ll_lon_lat.split(",")[1]).toDouble(); double ur_lon = ossimString(ur_lon_lat.split(",")[0]).toDouble(); double ur_lat = ossimString(ur_lon_lat.split(",")[1]).toDouble(); checkLongitude(ll_lon, ur_lon); ossim_float64 tmpColPostion = std::fabs(ll_lon - m_bBox_LL_Lon); ossim_float64 tmpFrameLon = std::fabs(ur_lon - ll_lon); if (std::fabs(tmpFrameLon - avgLon) > 0.002) { ossimNotify(ossimNotifyLevel_WARN) << fileName << " has overlap pixels with other image." << std::endl; return false; } ossim_float64 tmpRowPostion = std::fabs(m_bBox_UR_Lat - ur_lat); ossim_float64 tmpFrameLat = std::fabs(ur_lat - ll_lat); if (std::fabs(tmpFrameLat - avgLat) > 0.002) { ossimNotify(ossimNotifyLevel_WARN) << fileName << " has overlap pixels with other image." << std::endl; return false; } ossim_uint32 colNum = static_cast(tmpColPostion/tmpFrameLon + 0.5); ossim_uint32 rowNum = static_cast(tmpRowPostion/tmpFrameLat + 0.5); if (colNum >= m_numOfFramesHorizontal) { colNum = m_numOfFramesHorizontal-1; // Clamp to last column. } if (rowNum >= m_numOfFramesVertical) { rowNum = m_numOfFramesVertical-1; // Clamp to last row. } ossimRpfFrameEntry tempEntry; tempEntry.setEntry(ossimFilename(""), fileName); m_frameEntryArray[rowNum][colNum] = tempEntry; } else { return false; } } return true; } void ossimImageCacheBase::checkLongitude(ossim_float64& leftLon, const ossim_float64& rightLon) const { //--- // Test for scene coordinates being 180 to 180 and adjust leftLon to -180 // if so. // // NOTE: // Setting tolerance to 1/7200 about 15 meters. // Not sure if this is too loose or not. (drb) //--- const ossim_float64 TOLERANCE = 0.000138889; // 1/7200 about 15 meters. if ( ossim::almostEqual(leftLon, 180.0, TOLERANCE) ) { if ( ossim::almostEqual(rightLon, 180.0, TOLERANCE) ) { leftLon = -180.0; } } } ossim_uint32 ossimImageCacheBase::getNumberOfInputBands()const { return m_numberOfBands; } ossim_uint32 ossimImageCacheBase::getNumberOfOutputBands()const { return m_numberOfBands; } ossim_uint32 ossimImageCacheBase::getNumberOfLines(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return m_numberOfLines; } else if (theOverview.valid()) { return theOverview->getNumberOfLines(reduced_res_level); } return 0; } ossim_uint32 ossimImageCacheBase::getNumberOfSamples(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return m_numberOfSamples; } else if (theOverview.valid()) { return theOverview->getNumberOfSamples(reduced_res_level); } return 0; } void ossimImageCacheBase::setActualImageRect() { m_actualImageRect = ossimIrect(0,0,m_numberOfLines, m_numberOfSamples); } ossimIrect ossimImageCacheBase::getImageRectangle(ossim_uint32 reduced_res_level) const { return ossimIrect(0, // upper left x 0, // upper left y getNumberOfSamples(reduced_res_level) - 1, // lower right x getNumberOfLines(reduced_res_level) - 1); // lower right y } ossim_uint32 ossimImageCacheBase::getTileWidth() const { return m_tileSize.x; } ossim_uint32 ossimImageCacheBase::getTileHeight() const { return m_tileSize.y; } void ossimImageCacheBase::getEntryList(std::vector& entryList)const { entryList.push_back(0); } bool ossimImageCacheBase::isValidRLevel(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return true; } else if (theOverview.valid()) { return theOverview->isValidRLevel(reduced_res_level); } else { return false; } } vector ossimImageCacheBase::getIntersectingEntries(const ossimIrect& rect) { vector result; // make sure we have the Toc entry to render if(!isOpen()) return result; ossimIrect imageRect = getImageRectangle(); if(rect.intersects(imageRect)) { ossimIrect clipRect = rect.clipToRect(imageRect); ossimIrect frameRect(clipRect.ul().x/m_frame_width, clipRect.ul().y/m_frame_height, clipRect.lr().x/m_frame_width, clipRect.lr().y/m_frame_height); for(ossim_int32 row = frameRect.ul().y; row <= frameRect.lr().y; ++row) { for(ossim_int32 col = frameRect.ul().x; col <= frameRect.lr().x; ++col) { ossimRpfFrameEntry tempEntry = m_frameEntryArray[row][col]; if(tempEntry.exists()) { result.push_back(ossimFrameEntryData(row, col, row*m_frame_height, col*m_frame_width, tempEntry)); } } } } return result; } void ossimImageCacheBase::deleteAll() { theOverview = 0; } bool ossimImageCacheBase::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimImageHandler::saveState(kwl, prefix); return result; } bool ossimImageCacheBase::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* MODULE = "ossimImageCacheBase::loadState"; if(traceDebug()) { CLOG << "Entering..." << endl; } bool result = ossimImageHandler::loadState(kwl, prefix); if(!result) { if(traceDebug()) { CLOG << "Leaving..." << endl; } return false; } const char* lookup = 0; lookup = kwl.find(ossimString(prefix), "entry"); ossim_int32 entry = ossimString(lookup).toInt32(); // if an entry is specified then // call the open with an entry number if(lookup) { if(traceDebug()) { CLOG << "Leaving..." << endl; } result = ossimImageHandler::open(theImageFile); setCurrentEntry(entry); return result; } result = ossimImageHandler::open(theImageFile); return result; } ossim_uint32 ossimImageCacheBase::getImageTileWidth() const { return 256; } ossim_uint32 ossimImageCacheBase::getImageTileHeight() const { return 256; } void ossimImageCacheBase::establishDecimationFactors() { theDecimationFactors.clear(); // Just needed to set the first R level here, the base class can do the rest: ossimImageHandler::establishDecimationFactors(); } ossimRefPtr ossimImageCacheBase::getImageGeometry() { if (theGeometry.valid()) return theGeometry; // datum // WGS 84 ossimKeywordlist kwl; const char* prefix = 0; // legacy kwl.add(prefix, ossimKeywordNames::DATUM_KW, "WGE", true); ossimGpt ul(m_bBox_UR_Lat,m_bBox_LL_Lon); ossimGpt ll(m_bBox_LL_Lat,m_bBox_LL_Lon); ossimGpt ur(m_bBox_UR_Lat,m_bBox_UR_Lon); ossimGpt lr(m_bBox_LL_Lat,m_bBox_UR_Lon); double latInterval = fabs(ul.latd() - lr.latd())/ getNumberOfLines(); double lonInterval = fabs(ul.lond() - ur.lond())/ getNumberOfSamples(); kwl.add(prefix, ossimKeywordNames::UL_LAT_KW, ul.latd(),//-(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::UL_LON_KW, ul.lond(),//+(lonInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::LL_LAT_KW, ll.latd(),//+(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::LL_LON_KW, ll.lond(),//+(lonInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::LR_LAT_KW, lr.latd(),//+(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::LR_LON_KW, lr.lond(),//-(lonInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::UR_LAT_KW, ur.latd(),//-(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::UR_LON_KW, ur.lond(),//-(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::NUMBER_INPUT_BANDS_KW, getNumberOfInputBands(), true); kwl.add(prefix, ossimKeywordNames::NUMBER_OUTPUT_BANDS_KW, getNumberOfOutputBands(), true); kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, getNumberOfLines(), true); kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, getNumberOfSamples(), true); //--- // Make a projection to get the easting / northing of the tie point and // the scale in meters. This will only be used by the CIB. //--- kwl.add(prefix, ossimKeywordNames::DATUM_KW, "WGE", true); ossimGpt origin((ul.latd()+lr.latd())*.5, (ul.lond()+lr.lond())*.5, 0.0); double deltaLatPerPixel = latInterval; double deltaLonPerPixel = lonInterval; ossimDpt tie; tie.lat = ul.latd() - deltaLatPerPixel/2.0; tie.lon = ul.lond() + deltaLonPerPixel/2.0; kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, tie.toString(), true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, deltaLatPerPixel, true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, deltaLonPerPixel, true); kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, origin.latd(), true); kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, origin.lond(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LAT_KW, ul.latd()-(deltaLatPerPixel/2.0), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LON_KW, ul.lond()+(deltaLonPerPixel/2.0), true); kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimEquDistCylProjection", true); // Capture this for next time. theGeometry = new ossimImageGeometry; theGeometry->loadState(kwl, prefix); // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); return theGeometry; } ossim-Miami-2.9.1/src/imaging/ossimImageCacheTileSource.cpp000066400000000000000000000324641352751253100236520ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // //******************************************************************** // $Id: ossimImageCacheTileSource.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $ #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug = ossimTrace("ossimImageCacheTileSource:debug"); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimImageCacheTileSource.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $"; #endif RTTI_DEF1(ossimImageCacheTileSource, "ossimImageCacheTileSource", ossimImageCacheBase) ossimImageCacheTileSource::ossimImageCacheTileSource() : ossimImageCacheBase(), m_tile(0), m_imageHandler(0), m_minPixelValue(ossim::nan()), m_maxPixelValue(ossim::nan()), m_nullPixelValue(ossim::nan()) { } ossimImageCacheTileSource::~ossimImageCacheTileSource() { if(m_imageHandler.valid()) { m_imageHandler = 0; } close(); } ossimString ossimImageCacheTileSource::getShortName()const { return ossimString("ImageCache"); } ossimString ossimImageCacheTileSource::getLongName()const { return ossimString("ImageCache reader"); } void ossimImageCacheTileSource::close() { deleteAll(); } bool ossimImageCacheTileSource::open() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageCacheTileSource::open(): Entered....." << std::endl; } ossimFilename imageFile = theImageFile; bool result = true; if(isOpen() == false) { close(); result = false; } if(result) { if (m_fileNames.size() == 0 && m_frameEntryArray.size() == 0) { if (buildFrameEntryArray(imageFile) == false) { return false; } } //--- // Adjust image rect so not to go over the -180 to 180 and -90 to 90 // bounds. //--- setActualImageRect(); // Set the base class image file name. theImageFile = imageFile; m_tile = ossimImageDataFactory::instance()->create(this, this); m_tile->initialize(); completeOpen(); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageCacheTileSource::open(): Leaving at line" << __LINE__ << std::endl; } return result; } bool ossimImageCacheTileSource::buildFrameEntryArray(ossimFilename imageFile) { static const char MODULE[] = "ossimImageCacheTileSource::buildFrameEntryArray"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << endl; } std::ifstream in((imageFile).c_str() ); std::string line; ossim_uint32 index = 0; // used throughout ossim_uint32 frameWidth = 0; ossim_uint32 frameHeight = 0; while( in.good() ) { // Read in a line. std::getline(in, line); ossimString tmpStr = ossimString(line); if (index == 0) { std::vector box_lat_lon; tmpStr.split(box_lat_lon, "|"); if (box_lat_lon.size() == 4) { std::vector pixelInfos = box_lat_lon[3].split(","); if (pixelInfos.size() == 3) { m_minPixelValue = ossimString::toFloat64(pixelInfos[0]); m_maxPixelValue = ossimString::toFloat64(pixelInfos[1]); m_nullPixelValue = ossimString::toFloat64(pixelInfos[2]); } } } else if (index == 1) { std::vector frame_lat_lon = tmpStr.split("|"); ossimFilename firstFile = frame_lat_lon[0]; if(m_workFrame->parseFile(firstFile) == ossimErrorCodes::OSSIM_ERROR) { m_imageHandler = ossimImageHandlerRegistry::instance()->open(firstFile); if (m_imageHandler.valid()) { frameWidth = m_imageHandler->getBoundingRect().width(); frameHeight = m_imageHandler->getBoundingRect().height(); break; } } else { return false; } } ++index; } in.close(); return ossimImageCacheBase::buildFrameEntryArray(imageFile, frameWidth, frameHeight); } ossimRefPtr ossimImageCacheTileSource::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if (m_tile.valid()) { // Image rectangle must be set prior to calling getTile. m_tile->setImageRectangle(rect); if ( getTile( m_tile.get(), resLevel ) == false ) { if (m_tile->getDataObjectStatus() != OSSIM_NULL) { m_tile->makeBlank(); } } } return m_tile; } bool ossimImageCacheTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands())) { if ( resLevel > 0 ) { status = getOverviewTile(resLevel, result); } if (!status) // Did not get an overview tile. { status = true; ossimIrect rect = result->getImageRectangle(); ossimIrect imageRect = getImageRectangle(); if ( rect.intersects(imageRect) ) { //--- // Start with a blank tile in case there is not total coverage // for rect. //--- result->makeBlank(); vector frames = getIntersectingEntries(rect); if(frames.size() > 0) { //--- // Now lets render each frame. Note we will have to find // subframes // that intersect the rectangle of interest for each frame. //--- fillTile(rect, frames, result); // Revalidate tile status. result->validate(); } } else { result->makeBlank(); } } } return status; } void ossimImageCacheTileSource::fillTile( const ossimIrect& tileRect, const vector& framesInvolved, ossimImageData* tile) { ossim_uint32 idx = 0; for(idx = 0; idx < framesInvolved.size(); ++idx) { if (m_imageHandler.valid()) { if (m_imageHandler->getFilename() != framesInvolved[idx].theFrameEntry.getFullPath()) { m_imageHandler = 0; m_imageHandler = ossimImageHandlerRegistry::instance()->open(framesInvolved[idx].theFrameEntry.getFullPath()); } } else { m_imageHandler = ossimImageHandlerRegistry::instance()->open(framesInvolved[idx].theFrameEntry.getFullPath()); } if (m_imageHandler.valid()) { if (m_imageHandler->isOpen() == false) { m_imageHandler->open(framesInvolved[idx].theFrameEntry.getFullPath()); } ossimIrect frameRect(framesInvolved[idx].thePixelCol, framesInvolved[idx].thePixelRow, framesInvolved[idx].thePixelCol + m_frame_width - 1, framesInvolved[idx].thePixelRow + m_frame_height - 1); ossimIrect clipRect = tileRect.clipToRect(frameRect); ossimIpt tempDelta(clipRect.ul().x - framesInvolved[idx].thePixelCol, clipRect.ul().y - framesInvolved[idx].thePixelRow); ossimIrect offsetRect(tempDelta.x, tempDelta.y, tempDelta.x + clipRect.width()-1, tempDelta.y + clipRect.height()-1); //if the current image size is different from the default size, resample the image data if ( ( m_imageHandler->getBoundingRect().width() != m_frame_width ) || ( m_imageHandler->getBoundingRect().height() != m_frame_height ) ) { //calculate the ratio ossim_float64 widthRatio = static_cast(m_imageHandler->getBoundingRect().width())/static_cast(m_frame_width); ossim_float64 heightRatio = static_cast(m_imageHandler->getBoundingRect().height())/static_cast(m_frame_height); //initialize the rect bounding for getting image data from image handler ossimDpt ul(offsetRect.ul().x*widthRatio, offsetRect.ul().y*heightRatio); ossimDpt lr(offsetRect.lr().x*widthRatio, offsetRect.lr().y*heightRatio); //--- // Floor, ceil to avoid rect size of zero from ul, lr, delta being only fractional // resulting in size of 0 if cast to an int or passed to ossim::round(). //--- ossimIrect actualOffsetRect(static_cast(std::floor(ul.x)), static_cast(std::floor(ul.y)), static_cast(std::ceil(lr.x)), static_cast(std::ceil(lr.y))); //get accurate rect in case the actual rect is larger than the rect of image actualOffsetRect = actualOffsetRect.clipToRect(m_imageHandler->getBoundingRect()); ossimRefPtr imageData = m_imageHandler->getTile(actualOffsetRect); if (imageData.valid()) { ossimFilterResampler* resampler = new ossimFilterResampler(); double denominatorY = 1.0; double denominatorX = 1.0; if(clipRect.height() > 2) // Cannot be zero. { denominatorY = clipRect.height()-1.0; } if(clipRect.width() > 2) // Cannot be zero. { denominatorX = clipRect.width()-1.0; } //create a tile and set the rect size ossimRefPtr tmpTile = (ossimImageData*)imageData->dup(); tmpTile->setImageRectangle(offsetRect); tmpTile->makeBlank(); ossimDpt deltaUl(((actualOffsetRect.ll().x - actualOffsetRect.ul().x)/denominatorX), ((actualOffsetRect.ll().y - actualOffsetRect.ul().y)/denominatorY)); ossimDpt deltaUr(((actualOffsetRect.lr().x - actualOffsetRect.ur().x)/denominatorX), ((actualOffsetRect.lr().y - actualOffsetRect.ur().y)/denominatorY)); ossimDpt length(offsetRect.width(),offsetRect.height()); //resample the image data resampler->resample(imageData, tmpTile, actualOffsetRect.ul(), actualOffsetRect.ur(), deltaUl, deltaUr, length); tile->loadTile(tmpTile->getBuf(), clipRect, OSSIM_BSQ); tmpTile = 0; delete resampler; resampler = 0; } } else { ossimRefPtr imageData = m_imageHandler->getTile(offsetRect); if (imageData.valid()) { tile->loadTile(imageData->getBuf(), clipRect, OSSIM_BSQ); } } } } } ossimScalarType ossimImageCacheTileSource::getOutputScalarType() const { if (m_imageHandler.valid()) { return m_imageHandler->getOutputScalarType(); } return OSSIM_UCHAR; } double ossimImageCacheTileSource::getMinPixelValue(ossim_uint32 band)const { if (ossim::isnan(m_minPixelValue)) { return ossimImageHandler::getMinPixelValue(band); } return m_minPixelValue; } double ossimImageCacheTileSource::getMaxPixelValue(ossim_uint32 band)const { if (ossim::isnan(m_maxPixelValue)) { return ossimImageHandler::getMaxPixelValue(band); } return m_maxPixelValue; } double ossimImageCacheTileSource::getNullPixelValue(ossim_uint32 band)const { if (ossim::isnan(m_nullPixelValue)) { return ossimImageHandler::getNullPixelValue(band); } return m_nullPixelValue; } ossim_uint32 ossimImageCacheTileSource::getNumberOfInputBands()const { if (m_imageHandler.valid()) { return m_imageHandler->getNumberOfInputBands(); } return m_numberOfBands; } ossim_uint32 ossimImageCacheTileSource::getNumberOfOutputBands()const { if (m_imageHandler.valid()) { return m_imageHandler->getNumberOfInputBands(); } return m_numberOfBands; } ossim-Miami-2.9.1/src/imaging/ossimImageChain.cpp000066400000000000000000001514201352751253100216640ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageChain.cpp 21850 2012-10-21 20:09:55Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimImageChain"); RTTI_DEF3(ossimImageChain, "ossimImageChain", ossimImageSource, ossimConnectableObjectListener, ossimConnectableContainerInterface); void ossimImageChain::processEvent(ossimEvent& event) { ossimConnectableObjectListener::processEvent(event); ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, event.getCurrentObject()); if((ossimConnectableObject*)getFirstSource() == obj) { if(event.isPropagatingToOutputs()) { ossimConnectableObject::ConnectableObjectList& outputList = getOutputList(); ossim_uint32 idx = 0; for(idx = 0; idx < outputList.size();++idx) { if(outputList[idx].valid()) { outputList[idx]->fireEvent(event); outputList[idx]->propagateEventToOutputs(event); } } } } } ossimImageChain::ossimImageChain() :ossimImageSource(0, 0, // number of inputs 0, // number of outputs false, // input's fixed false), // outputs are not fixed ossimConnectableContainerInterface((ossimObject*)NULL), theBlankTile(NULL), theLoadStateFlag(false) { ossimConnectableContainerInterface::theBaseObject = this; //thePropagateEventFlag = false; addListener((ossimConnectableObjectListener*)this); } ossimImageChain::~ossimImageChain() { removeListener((ossimConnectableObjectListener*)this); deleteList(); } bool ossimImageChain::addFirst(ossimConnectableObject* obj) { ossimConnectableObject* rightOfThisObj = (ossimConnectableObject*)getFirstObject(); return insertRight(obj, rightOfThisObj); } bool ossimImageChain::addLast(ossimConnectableObject* obj) { if(imageChainList().size() > 0) { ossimConnectableObject* lastSource = imageChainList()[ imageChainList().size() -1].get(); // if(dynamic_cast(obj)&&lastSource) if(lastSource) { // obj->disconnect(); ossimConnectableObject::ConnectableObjectList tempIn = getInputList(); lastSource->disconnectAllInputs(); lastSource->connectMyInputTo(obj); obj->changeOwner(this); obj->connectInputList(tempIn); tempIn = obj->getInputList(); theInputListIsFixedFlag = obj->getInputListIsFixedFlag(); setNumberOfInputs(obj->getNumberOfInputs()); imageChainList().push_back(obj); obj->addListener((ossimConnectableObjectListener*)this); // Send an event to any listeners. ossimContainerEvent event((ossimObject*)this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(obj); fireEvent(event); return true; } } else { return add(obj); } return false;; } ossimImageSource* ossimImageChain::getFirstSource() { if(imageChainList().size()>0) { return dynamic_cast(imageChainList()[0].get()); } return 0; } const ossimImageSource* ossimImageChain::getFirstSource() const { if(imageChainList().size()>0) return dynamic_cast(imageChainList()[0].get()); return 0; } ossimObject* ossimImageChain::getFirstObject() { if(imageChainList().size()>0) { return dynamic_cast(imageChainList()[0].get()); } return 0; } ossimImageSource* ossimImageChain::getLastSource() { if(imageChainList().size()>0) { return dynamic_cast((*(imageChainList().end()-1)).get()); } return NULL; } const ossimImageSource* ossimImageChain::getLastSource() const { if(imageChainList().size()>0) return dynamic_cast((*(imageChainList().end()-1)).get()); return NULL; } ossimObject* ossimImageChain::getLastObject() { if(imageChainList().size()>0) { return dynamic_cast((*(imageChainList().end()-1)).get()); } return 0; } ossimConnectableObject* ossimImageChain::findObject(const ossimId& id, bool /* recurse */) { std::vector >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).get()) { if(id == (*current)->getId()) { return (*current).get(); } } ++current; } current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* object = child->findObject(id, true); if(object) return object; } ++current; } return NULL; } ossimConnectableObject* ossimImageChain::findObject(const ossimConnectableObject* obj, bool /* recurse */) { std::vector >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()) { if(obj == (*current).get()) { return (*current).get(); } } ++current; } current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* object = child->findObject(obj, true); if(object) return object; } ++current; } return 0; } ossimConnectableObject* ossimImageChain::findFirstObjectOfType(const RTTItypeid& typeInfo, bool recurse) { vector >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(typeInfo)) { return (*current).get(); } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* temp = child->findFirstObjectOfType(typeInfo, recurse); if(temp) { return temp; } } ++current; } } return (ossimConnectableObject*)NULL; } ossimConnectableObject* ossimImageChain::findFirstObjectOfType(const ossimString& className, bool recurse) { vector >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(className) ) { return (*current).get(); } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* temp = child->findFirstObjectOfType(className, recurse); if(temp) { return temp; } } ++current; } } return (ossimConnectableObject*)0; } ossimConnectableObject::ConnectableObjectList ossimImageChain::findAllObjectsOfType(const RTTItypeid& typeInfo, bool recurse) { ossimConnectableObject::ConnectableObjectList result; ossimConnectableObject::ConnectableObjectList::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(typeInfo)) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), (*current).get()); if(iter == result.end()) { result.push_back((*current).get()); } } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject::ConnectableObjectList temp; temp = child->findAllObjectsOfType(typeInfo, recurse); for(long index=0; index < (long)temp.size();++index) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), temp[index]); if(iter == result.end()) { result.push_back(temp[index]); } } } ++current; } } return result; } ossimConnectableObject::ConnectableObjectList ossimImageChain::findAllObjectsOfType(const ossimString& className, bool recurse) { ossimConnectableObject::ConnectableObjectList result; ossimConnectableObject::ConnectableObjectList::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(className)) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), (*current).get()); if(iter == result.end()) { result.push_back((*current).get()); } } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject::ConnectableObjectList temp; temp = child->findAllObjectsOfType(className, recurse); for(long index=0; index < (long)temp.size();++index) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), temp[index]); if(iter == result.end()) { result.push_back(temp[index]); } } } ++current; } } return result; } void ossimImageChain::makeUniqueIds() { setId(ossimIdManager::instance()->generateId()); for(long index = 0; index < (long)imageChainList().size(); ++index) { ossimConnectableContainerInterface* container = PTR_CAST(ossimConnectableContainerInterface, imageChainList()[index].get()); if(container) { container->makeUniqueIds(); } else { if(imageChainList()[index].valid()) { imageChainList()[index]->setId(ossimIdManager::instance()->generateId()); } } } } ossim_uint32 ossimImageChain::getNumberOfObjects(bool recurse)const { ossim_uint32 result = (ossim_uint32)imageChainList().size(); if(recurse) { for(ossim_uint32 i = 0; i < imageChainList().size(); ++i) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, imageChainList()[i].get()); if(child) { result += child->getNumberOfObjects(true); } } } return result; } ossim_uint32 ossimImageChain::getNumberOfSources() const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimImageChain::getNumberOfSources is deprecated!" << "\nUse: ossimImageChain::getNumberOfObjects(false)" << std::endl; return getNumberOfObjects(false); } bool ossimImageChain::addChild(ossimConnectableObject* object) { return add(object); } bool ossimImageChain::removeChild(ossimConnectableObject* object) { bool result = false; vector >::iterator current = std::find(imageChainList().begin(), imageChainList().end(), object); if(current!=imageChainList().end()) { result = true; object->removeListener((ossimConnectableObjectListener*)this); if(current == imageChainList().begin()) { object->removeListener((ossimConnectableObjectListener*)this); } if(imageChainList().size() == 1) { object->changeOwner(0); current = imageChainList().erase(current); } else { ossimConnectableObject::ConnectableObjectList input = object->getInputList(); ossimConnectableObject::ConnectableObjectList output = object->getOutputList(); object->changeOwner(0);// set the owner to 0 bool erasingBeginning = (current == imageChainList().begin()); // bool erasingEnd = (current+1) == imageChainList().end(); current = imageChainList().erase(current); object->disconnect(); if(!imageChainList().empty()) { if(erasingBeginning) // the one that receives the first getTile { (*imageChainList().begin())->addListener(this); } else if(current==imageChainList().end()) // one that receives the last getTIle { current = imageChainList().begin()+(imageChainList().size()-1); (*current)->connectInputList(input); theInputObjectList = (*current)->getInputList(); theInputListIsFixedFlag = (*current)->getInputListIsFixedFlag(); } else { // prepare interior setup and removal and connect surrounding nodes // take the outputs of the node we are removing and connect them to the old inputs ossim_uint32 outIndex = 0; for(outIndex = 0; outIndex < output.size();++outIndex) { output[outIndex]->connectInputList(input); } } } } // Send an event to any listeners. ossimContainerEvent event((ossimObject*)this, OSSIM_EVENT_REMOVE_OBJECT_ID); event.setObjectList(object); fireEvent(event); } return result; } ossimConnectableObject* ossimImageChain::removeChild(const ossimId& id) { ossimIdVisitor visitor( id, (ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS ) ); accept( visitor ); ossimConnectableObject* obj = visitor.getObject(); if ( obj ) { removeChild(obj); } return obj; } void ossimImageChain::getChildren(vector& children, bool immediateChildrenOnlyFlag) { ossim_uint32 i = 0; vector temp; for(i = 0; i < imageChainList().size();++i) { temp.push_back(imageChainList()[i].get()); } for(i = 0; i < temp.size();++i) { ossimConnectableContainerInterface* interface = PTR_CAST(ossimConnectableContainerInterface, temp[i]); if(immediateChildrenOnlyFlag) { children.push_back(temp[i]); } else if(!interface) { children.push_back(temp[i]); } } if(!immediateChildrenOnlyFlag) { for(i = 0; i < temp.size();++i) { ossimConnectableContainerInterface* interface = PTR_CAST(ossimConnectableContainerInterface, temp[i]); if(interface) { interface->getChildren(children, false); } } } } bool ossimImageChain::add(ossimConnectableObject* source) { bool result = false; // if(PTR_CAST(ossimImageSource, source)) { source->changeOwner(this); if(imageChainList().size() > 0) { source->disconnectAllOutputs(); theOutputListIsFixedFlag = source->getOutputListIsFixedFlag(); imageChainList()[0]->removeListener(this); imageChainList().insert(imageChainList().begin(), source); imageChainList()[0]->addListener(this); source->addListener((ossimConnectableObjectListener*)this); imageChainList()[0]->connectMyInputTo(imageChainList()[1].get()); result = true; } else { theInputListIsFixedFlag = false; theOutputListIsFixedFlag = false; if(!theInputObjectList.empty()) { source->connectInputList(getInputList()); } theInputObjectList = source->getInputList(); theInputListIsFixedFlag = source->getInputListIsFixedFlag(); // theOutputObjectList = source->getOutputList(); // theOutputListIsFixedFlag= source->getOutputListIsFixedFlag(); imageChainList().push_back(source); source->addListener((ossimConnectableObjectListener*)this); source->addListener(this); result = true; } } if (result && source) { ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(source); fireEvent(event); } return result; } bool ossimImageChain::insertRight(ossimConnectableObject* newObj, ossimConnectableObject* rightOfThisObj) { if(!newObj&&!rightOfThisObj) return false; if(!imageChainList().size()) { return add(newObj); } std::vector >::iterator iter = std::find(imageChainList().begin(), imageChainList().end(), rightOfThisObj); if(iter!=imageChainList().end()) { if(iter == imageChainList().begin()) { return add(newObj); } else //if(PTR_CAST(ossimImageSource, newObj)) { ossimConnectableObject::ConnectableObjectList outputList = rightOfThisObj->getOutputList(); rightOfThisObj->disconnectAllOutputs(); // Core dump fix. Connect input prior to outputs. (drb) newObj->connectMyInputTo(rightOfThisObj); newObj->connectOutputList(outputList); newObj->changeOwner(this); newObj->addListener((ossimConnectableObjectListener*)this); imageChainList().insert(iter, newObj); // Send event to any listeners. ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(newObj); fireEvent(event); return true; } } return false; } bool ossimImageChain::insertRight(ossimConnectableObject* newObj, const ossimId& id) { #if 1 ossimIdVisitor visitor( id, ossimVisitor::VISIT_CHILDREN ); accept( visitor ); ossimConnectableObject* obj = visitor.getObject(); if ( obj ) { return insertRight(newObj, obj); } return false; #else ossimConnectableObject* obj = findObject(id, false); if(obj) { return insertRight(newObj, obj); } return false; #endif } bool ossimImageChain::insertLeft(ossimConnectableObject* newObj, ossimConnectableObject* leftOfThisObj) { if(!newObj&&!leftOfThisObj) return false; if(!imageChainList().size()) { return add(newObj); } std::vector >::iterator iter = std::find(imageChainList().begin(), imageChainList().end(), leftOfThisObj); if(iter!=imageChainList().end()) { if((iter+1)==imageChainList().end()) { return addLast(newObj); } else { ossimConnectableObject::ConnectableObjectList inputList = leftOfThisObj->getInputList(); newObj->connectInputList(inputList); leftOfThisObj->disconnectAllInputs(); leftOfThisObj->connectMyInputTo(newObj); newObj->changeOwner(this); newObj->addListener((ossimConnectableObjectListener*)this); imageChainList().insert(iter+1, newObj); // Send an event to any listeners. ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(newObj); fireEvent(event); return true; } } return false; } bool ossimImageChain::insertLeft(ossimConnectableObject* newObj, const ossimId& id) { #if 1 ossimIdVisitor visitor( id, ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS); accept( visitor ); ossimConnectableObject* obj = visitor.getObject(); if ( obj ) { return insertLeft(newObj, obj); } return false; #else ossimConnectableObject* obj = findObject(id, false); if(obj) { return insertLeft(newObj, obj); } return false; #endif } bool ossimImageChain::replace(ossimConnectableObject* newObj, ossimConnectableObject* oldObj) { ossim_int32 idx = indexOf(oldObj); if(idx >= 0) { ossimConnectableObject::ConnectableObjectList& inputList = oldObj->getInputList(); ossimConnectableObject::ConnectableObjectList& outputList = oldObj->getOutputList(); oldObj->removeListener((ossimConnectableObjectListener*)this); oldObj->removeListener(this); oldObj->changeOwner(0); imageChainList()[idx] = newObj; newObj->connectInputList(inputList); newObj->connectOutputList(outputList); newObj->changeOwner(this); newObj->addListener((ossimConnectableObjectListener*)this); if(idx == 0) { newObj->addListener(this); } } return (idx >= 0); } ossimRefPtr ossimImageChain::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* inputSource = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(inputSource) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs return inputSource->getTile(tileRect, resLevel); } } else { if(getInput(0)) { ossimImageSource* inputSource = PTR_CAST(ossimImageSource, getInput(0)); if(inputSource) { ossimRefPtr inputTile = inputSource->getTile(tileRect, resLevel); // if(inputTile.valid()) // { // std::cout << *(inputTile.get()) << std::endl; // } return inputTile.get(); } } } // std::cout << "RETURNING A BLANK TILE!!!!" << std::endl; /* if(theBlankTile.get()) { theBlankTile->setImageRectangle(tileRect); } return theBlankTile; */ return 0; } ossim_uint32 ossimImageChain::getNumberOfInputBands() const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getNumberOfOutputBands(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getNumberOfOutputBands(); } } } return 0; } double ossimImageChain::getNullPixelValue(ossim_uint32 band)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getNullPixelValue(band); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getNullPixelValue(band); } } } return ossim::defaultNull(getOutputScalarType()); } double ossimImageChain::getMinPixelValue(ossim_uint32 band)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getMinPixelValue(band); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getMinPixelValue(band); } } } return ossim::defaultMin(getOutputScalarType()); } double ossimImageChain::getMaxPixelValue(ossim_uint32 band)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* inter = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(inter) { return inter->getMaxPixelValue(band); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getMaxPixelValue(band); } } } return ossim::defaultMax(getOutputScalarType()); } void ossimImageChain::getOutputBandList(std::vector& bandList) const { if( (imageChainList().size() > 0) && isSourceEnabled() ) { ossimRefPtr inter = dynamic_cast( imageChainList()[0].get() ); if( inter.valid() ) { // cout << "cn: " << inter->getClassName() << endl; inter->getOutputBandList(bandList); } } } ossimScalarType ossimImageChain::getOutputScalarType() const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getOutputScalarType(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getOutputScalarType(); } } } return OSSIM_SCALAR_UNKNOWN; } ossim_uint32 ossimImageChain::getTileWidth()const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getTileWidth();; } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getTileWidth(); } } } return 0; } ossim_uint32 ossimImageChain::getTileHeight()const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getTileHeight(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getTileHeight(); } } } return 0; } ossimIrect ossimImageChain::getBoundingRect(ossim_uint32 resLevel)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getBoundingRect(resLevel); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getBoundingRect(); } } } ossimDrect rect; rect.makeNan(); return rect; } void ossimImageChain::getValidImageVertices(vector& validVertices, ossimVertexOrdering ordering, ossim_uint32 resLevel)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface =PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { interface->getValidImageVertices(validVertices, ordering, resLevel); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getValidImageVertices(validVertices, ordering, resLevel); } } } } ossimRefPtr ossimImageChain::getImageGeometry() { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if( interface ) { return interface->getImageGeometry(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getImageGeometry(); } } } return ossimRefPtr(); } void ossimImageChain::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { interface->getDecimationFactor(resLevel, result); return; } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getDecimationFactor(resLevel, result); return; } } } result.makeNan(); } void ossimImageChain::getDecimationFactors(vector& decimations) const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { interface->getDecimationFactors(decimations); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getDecimationFactors(decimations); return; } } } } ossim_uint32 ossimImageChain::getNumberOfDecimationLevels()const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getNumberOfDecimationLevels(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getNumberOfDecimationLevels(); } } } return 1; } bool ossimImageChain::addAllSources(map >& idMapping, const ossimKeywordlist& kwl, const char* prefix) { static const char* MODULE = "ossimImageChain::addAllSources"; ossimString copyPrefix = prefix; bool result = ossimImageSource::loadState(kwl, copyPrefix.c_str()); if(!result) { return result; } long index = 0; // ossimSource* source = NULL; vector inputConnectionIds; ossimString regExpression = ossimString("^(") + copyPrefix + "object[0-9]+.)"; vector keys = kwl.getSubstringKeyList( regExpression ); long numberOfSources = (long)keys.size();//kwl.getNumberOfSubstringKeys(regExpression); int offset = (int)(copyPrefix+"object").size(); int idx = 0; std::vector theNumberList(numberOfSources); for(idx = 0; idx < (int)theNumberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); theNumberList[idx] = numberStr.toInt(); } std::sort(theNumberList.begin(), theNumberList.end()); for(idx=0;idx < (int)theNumberList.size();++idx) { ossimString newPrefix = copyPrefix; newPrefix += ossimString("object"); newPrefix += ossimString::toString(theNumberList[idx]); newPrefix += ossimString("."); if(traceDebug()) { CLOG << "trying to create source with prefix: " << newPrefix << std::endl; } ossimRefPtr object = ossimObjectFactoryRegistry::instance()->createObject(kwl, newPrefix.c_str()); ossimConnectableObject* source = PTR_CAST(ossimConnectableObject, object.get()); if(source) { // we did find a source so include it in the count if(traceDebug()) { CLOG << "Created source with prefix: " << newPrefix << std::endl; } //if(PTR_CAST(ossimImageSource, source)) { ossimId id = source->getId(); inputConnectionIds.clear(); findInputConnectionIds(inputConnectionIds, kwl, newPrefix); if(inputConnectionIds.size() == 0) { // we will try to do a default connection // if(imageChainList().size()) { if(traceDebug()) { CLOG << "connecting " << source->getClassName() << " to " << imageChainList()[0]->getClassName() << std::endl; } source->connectMyInputTo(0, imageChainList()[0].get()); } } else { // we remember the connection id's so we can connect this later. // this way we make sure all sources were actually // allocated. // idMapping.insert(std::make_pair(id, inputConnectionIds)); } add(source); } // else // { source = 0; // } } else { object = 0; source = 0; } ++index; } if(imageChainList().size()) { ossimConnectableObject* obj = imageChainList()[(ossim_int32)imageChainList().size()-1].get(); if(obj) { setNumberOfInputs(obj->getNumberOfInputs()); } } return result; } void ossimImageChain::findInputConnectionIds(vector& result, const ossimKeywordlist& kwl, const char* prefix) { ossimString copyPrefix = prefix; ossim_uint32 idx = 0; ossimString regExpression = ossimString("^") + ossimString(prefix) + "input_connection[0-9]+"; vector keys = kwl.getSubstringKeyList( regExpression ); ossim_int32 offset = (ossim_int32)(copyPrefix+"input_connection").size(); ossim_uint32 numberOfKeys = (ossim_uint32)keys.size(); std::vector theNumberList(numberOfKeys); for(idx = 0; idx < theNumberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); theNumberList[idx] = numberStr.toInt(); } std::sort(theNumberList.begin(), theNumberList.end()); copyPrefix += ossimString("input_connection"); for(idx=0;idx < theNumberList.size();++idx) { const char* lookup = kwl.find(copyPrefix,ossimString::toString(theNumberList[idx])); if(lookup) { long id = ossimString(lookup).toLong(); result.push_back(ossimId(id)); } } } bool ossimImageChain::connectAllSources(const map >& idMapping) { // cout << "this->getId(): " << this->getId() << endl; if(idMapping.size()) { map >::const_iterator iter = idMapping.begin(); while(iter != idMapping.end()) { // cout << "(*iter).first): " << (*iter).first << endl; #if 0 ossimConnectableObject* currentSource = findObject((*iter).first); #else ossimIdVisitor visitor( (*iter).first, (ossimVisitor::VISIT_CHILDREN ) ); // ossimVisitor::VISIT_INPUTS ) ); accept( visitor ); ossimConnectableObject* currentSource = visitor.getObject(); #endif if(currentSource) { // cout << "currentSource->getClassName: " << currentSource->getClassName() << endl; long upperBound = (long)(*iter).second.size(); for(long index = 0; index < upperBound; ++index) { //cout << "(*iter).second[index]: " << (*iter).second[index] << endl; if((*iter).second[index].getId() > -1) { #if 0 ossimConnectableObject* inputSource = PTR_CAST(ossimConnectableObject, findObject((*iter).second[index])); #else visitor.reset(); visitor.setId( (*iter).second[index] ); accept( visitor ); ossimConnectableObject* inputSource = visitor.getObject(); #endif // cout << "inputSource is " << (inputSource?"good...":"null...") << endl; if ( inputSource ) { // cout << "inputSource->getClassName(): " << inputSource->getClassName() << endl; // Check for connection to self. if ( this != inputSource ) { currentSource->connectMyInputTo(index, inputSource); } // else warning??? } } else // -1 id { currentSource->disconnectMyInput((ossim_int32)index); } } } else { cerr << "Could not find " << (*iter).first << " for source: "; return false; } ++iter; } } // abort(); return true; } bool ossimImageChain::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = true; result = ossimImageSource::saveState(kwl, prefix); if(!result) { return result; } ossim_uint32 upper = (ossim_uint32)imageChainList().size(); ossim_uint32 counter = 1; if (upper) { ossim_int32 idx = upper-1; // start with the tail and go to the head fo the list. for(;((idx >= 0)&&result);--idx, ++counter) { ossimString newPrefix = prefix; newPrefix += (ossimString("object") + ossimString::toString(counter) + ossimString(".")); result = imageChainList()[idx]->saveState(kwl, newPrefix.c_str()); } } return result; } bool ossimImageChain::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char* MODULE = "ossimImageChain::loadState(kwl, prefix)"; deleteList(); ossimImageSource::loadState(kwl, prefix); theLoadStateFlag = true; bool result = true; map > idMapping; result = addAllSources(idMapping, kwl, prefix); if(!result) { CLOG << "problems adding sources" << std::endl; } result = connectAllSources(idMapping); if(!result) { CLOG << "problems connecting sources" << std::endl; } theLoadStateFlag = false; return result; } void ossimImageChain::initialize() { static const char* MODULE = "ossimImageChain::initialize()"; if (traceDebug()) CLOG << " Entered..." << std::endl; long upper = (ossim_uint32)imageChainList().size(); for(long index = upper - 1; index >= 0; --index) { if(traceDebug()) { CLOG << "initializing source: " << imageChainList()[index]->getClassName() << std::endl; } if(imageChainList()[index].valid()) { ossimSource* interface = PTR_CAST(ossimSource, imageChainList()[index].get()); if(interface) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs interface->initialize(); } } } if (traceDebug()) CLOG << " Exited..." << std::endl; } void ossimImageChain::enableSource() { ossim_int32 upper = static_cast(imageChainList().size()); ossim_int32 index = 0; for(index = upper - 1; index >= 0; --index) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs ossimSource* source = PTR_CAST(ossimSource, imageChainList()[index].get()); if(source) { source->enableSource(); } } theEnableFlag = true; } void ossimImageChain::disableSource() { long upper = (ossim_uint32)imageChainList().size(); for(long index = upper - 1; index >= 0; --index) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs ossimSource* source = PTR_CAST(ossimSource, imageChainList()[index].get()); if(source) { source->disableSource(); } } theEnableFlag = false; } void ossimImageChain::prepareForRemoval(ossimConnectableObject* connectableObject) { if(connectableObject) { connectableObject->removeListener((ossimConnectableObjectListener*)this); connectableObject->changeOwner(0); connectableObject->disconnect(); } } bool ossimImageChain::deleteFirst() { if (imageChainList().size() == 0) return false; ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID); prepareForRemoval(imageChainList()[0].get()); // Clear any listeners, memory. event.setObjectList(imageChainList()[0].get()); imageChainList()[0] = 0; // Remove from the vector. std::vector >::iterator i = imageChainList().begin(); imageChainList().erase(i); fireEvent(event); return true; } bool ossimImageChain::deleteLast() { if (imageChainList().size() == 0) return false; ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID); // Clear any listeners, memory. ossim_uint32 idx = (ossim_uint32)imageChainList().size() - 1; prepareForRemoval(imageChainList()[idx].get()); event.setObjectList(imageChainList()[idx].get()); imageChainList()[idx] = 0; // Remove from the vector. imageChainList().pop_back(); fireEvent(event); return true; } void ossimImageChain::deleteList() { ossim_uint32 upper = (ossim_uint32) imageChainList().size(); ossim_uint32 idx = 0; ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID); for(; idx < upper; ++idx) { if(imageChainList()[idx].valid()) { event.getObjectList().push_back(imageChainList()[idx].get()); prepareForRemoval(imageChainList()[idx].get()); imageChainList()[idx] = 0; } } imageChainList().clear(); fireEvent(event); } void ossimImageChain::disconnectInputEvent(ossimConnectionEvent& event) { if(imageChainList().size()) { if(event.getObject()==this) { if(imageChainList()[imageChainList().size()-1].valid()) { for(ossim_uint32 i = 0; i < event.getNumberOfOldObjects(); ++i) { imageChainList()[imageChainList().size()-1]->disconnectMyInput(event.getOldObject(i)); } } } } } void ossimImageChain::disconnectOutputEvent(ossimConnectionEvent& /* event */) { } void ossimImageChain::connectInputEvent(ossimConnectionEvent& event) { if(imageChainList().size()) { if(event.getObject()==this) { if(imageChainList()[imageChainList().size()-1].valid()) { for(ossim_uint32 i = 0; i < event.getNumberOfNewObjects(); ++i) { ossimConnectableObject* obj = event.getNewObject(i); imageChainList()[imageChainList().size()-1]->connectMyInputTo(findInputIndex(obj), obj, false); } } } else if(event.getObject() == imageChainList()[0].get()) { if(!theLoadStateFlag) { // theInputObjectList = imageChainList()[0]->getInputList(); } } initialize(); } } void ossimImageChain::connectOutputEvent(ossimConnectionEvent& /* event */) { } // void ossimImageChain::propertyEvent(ossimPropertyEvent& event) // { // if(imageChainList().size()) // { // ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, // event.getObject()); // if(obj) // { // ossimImageSource* interface = findSource(obj->getId()); // if(interface) // { // ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, // interface.getObject()); // if(obj) // { // } // } // } // } // } void ossimImageChain::objectDestructingEvent(ossimObjectDestructingEvent& event) { if(!event.getObject()) return; if(imageChainList().size()&&(event.getObject()!=this)) { removeChild(PTR_CAST(ossimConnectableObject, event.getObject())); } } void ossimImageChain::propagateEventToOutputs(ossimEvent& event) { //if(thePropagateEventFlag) return; //thePropagateEventFlag = true; if(imageChainList().size()) { if(imageChainList()[imageChainList().size()-1].valid()) { imageChainList()[imageChainList().size()-1]->fireEvent(event); imageChainList()[imageChainList().size()-1]->propagateEventToOutputs(event); } } //ossimConnectableObject::propagateEventToOutputs(event); // thePropagateEventFlag = false; } void ossimImageChain::propagateEventToInputs(ossimEvent& event) { // if(thePropagateEventFlag) return; // thePropagateEventFlag = true; if(imageChainList().size()) { if(imageChainList()[0].valid()) { imageChainList()[0]->fireEvent(event); imageChainList()[0]->propagateEventToInputs(event); } } // thePropagateEventFlag = false; } ossimConnectableObject* ossimImageChain::operator[](ossim_uint32 index) { return getConnectableObject(index); } ossimConnectableObject* ossimImageChain::getConnectableObject( ossim_uint32 index) { if(imageChainList().size() && (index < imageChainList().size())) { return imageChainList()[index].get(); } return 0; } ossim_int32 ossimImageChain::indexOf(ossimConnectableObject* obj)const { ossim_uint32 idx = 0; for(idx = 0; idx < imageChainList().size();++idx) { if(imageChainList()[idx] == obj) { return (ossim_int32)idx; } } return -1; } void ossimImageChain::accept(ossimVisitor& visitor) { if(!visitor.hasVisited(this)) { visitor.visit(this); ossimVisitor::VisitorType currentType = visitor.getVisitorType(); //--- // Lets make sure inputs and outputs are turned off for we are traversing all children // and we should not have to have that enabled. //--- visitor.turnOffVisitorType(ossimVisitor::VISIT_INPUTS|ossimVisitor::VISIT_OUTPUTS); if(visitor.getVisitorType() & ossimVisitor::VISIT_CHILDREN) { ConnectableObjectList::reverse_iterator current = imageChainList().rbegin(); while((current != imageChainList().rend())&&!visitor.stopTraversal()) { ossimRefPtr currentObject = (*current); if(currentObject.get() && !visitor.hasVisited(currentObject.get())) currentObject->accept(visitor); ++current; } } visitor.setVisitorType(currentType); ossimConnectableObject::accept(visitor); } } //************************************************************************************************** // Inserts all of its children and inputs into the container provided. Since ossimImageChain is // itself a form of container, this method will consolidate this chain with the argument // container. Therefore this chain object will not be represented in the container (but its // children will be, with correct input and output connections to external objects). // Returns TRUE if successful. //************************************************************************************************** #if 0 bool ossimImageChain::fillContainer(ossimConnectableContainer& container) { // Grab the first source in the chain and let it fill the container with itself and inputs. This // will traverse down the chain and will even pick up external sources that feed this chain: ossimRefPtr first_source = getFirstSource(); if (!first_source.valid()) return false; first_source->fillContainer(container); // Instead of adding ourselves, make sure my first source is properly connected to my output, // thus obviating the need for this image chain (my chain items become part of 'container': ConnectableObjectList& obj_list = getOutputList(); ossimRefPtr output_connection = 0; while (!obj_list.empty()) { // Always pick off the beginning of the list since it is shrinking with each disconnect: output_connection = obj_list[0]; disconnectMyOutput(output_connection.get(), true, false); first_source->connectMyOutputTo(output_connection.get()); } return true; } #endif ossim-Miami-2.9.1/src/imaging/ossimImageCombiner.cpp000066400000000000000000000464331352751253100224070ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageCombiner.cpp 23108 2015-01-27 17:00:20Z okramer $ #include #include #include #include #include using namespace std; RTTI_DEF2(ossimImageCombiner, "ossimImageCombiner", ossimImageSource, ossimConnectableObjectListener) static ossimTrace traceDebug ("ossimImageCombiner:debug"); ossimImageCombiner::ossimImageCombiner() :ossimImageSource(NULL, 0, 0, false, false), theLargestNumberOfInputBands(0), theInputToPassThrough(0), theHasDifferentInputs(false), theNormTile(NULL), theCurrentIndex(0) { theComputeFullResBoundsFlag = true; // until something is set we will just set the blank tile // to a 1 band unsigned char type addListener((ossimConnectableObjectListener*)this); } ossimImageCombiner::ossimImageCombiner(ossimObject* owner, int numberOfInputs, int numberOfOutputs, bool inputListIsFixedFlag, bool outputListIsFixedFlag) :ossimImageSource(owner, numberOfInputs, numberOfOutputs, inputListIsFixedFlag, outputListIsFixedFlag), theLargestNumberOfInputBands(0), theInputToPassThrough(0), theHasDifferentInputs(false), theNormTile(NULL), theCurrentIndex(0) { addListener((ossimConnectableObjectListener*)this); theComputeFullResBoundsFlag = true; } ossimImageCombiner::ossimImageCombiner(ossimConnectableObject::ConnectableObjectList& inputSources) :ossimImageSource(NULL, (ossim_uint32)inputSources.size(), 0, false, false), theLargestNumberOfInputBands(0), theInputToPassThrough(0), theHasDifferentInputs(false), theNormTile(NULL), theCurrentIndex(0) { theComputeFullResBoundsFlag = true; for(ossim_uint32 index = 0; index < inputSources.size(); ++index) { connectMyInputTo(index, inputSources[index].get()); } addListener((ossimConnectableObjectListener*)this); initialize(); } ossimImageCombiner::~ossimImageCombiner() { removeListener((ossimConnectableObjectListener*)this); } ossimIrect ossimImageCombiner::getBoundingRect(ossim_uint32 resLevel)const { static const char* MODULE = "ossimImageCombiner::getBoundingRect"; ossimIrect result; if(theComputeFullResBoundsFlag) { precomputeBounds(); } double scale = 1.0/std::pow(2.0, (double)resLevel); ossimDpt scalar(scale, scale); result.makeNan(); ossim_uint32 inputIndex = 0; ossimImageSource* interface; for(inputIndex = 0;inputIndex < getNumberOfInputs(); ++inputIndex) { interface = PTR_CAST(ossimImageSource, getInput(inputIndex)); if(interface) { ossimIrect rect = theFullResBounds[inputIndex]; if(result.hasNans()) { result = rect; } else if(!rect.hasNans()) { if(traceDebug()) { CLOG << "rect " << inputIndex << " = " << result << endl; } rect = rect*scale; result = result.combine(rect); } } } if(traceDebug()) { CLOG << "resulting bounding rect = " << result << endl; } return result; } ossim_uint32 ossimImageCombiner::getNumberOfInputBands() const { return theLargestNumberOfInputBands; } ossimScalarType ossimImageCombiner::getOutputScalarType() const { if(getInput(theInputToPassThrough)) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(theInputToPassThrough)); if(temp) { return temp->getOutputScalarType(); } } return OSSIM_SCALAR_UNKNOWN; } ossim_uint32 ossimImageCombiner::getTileWidth()const { if(getInput(theInputToPassThrough)) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(theInputToPassThrough)); if(temp) { return temp->getTileWidth(); } } return 1; } ossim_uint32 ossimImageCombiner::getTileHeight()const { if(getInput(theInputToPassThrough)) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(theInputToPassThrough)); if(temp) { return temp->getTileHeight(); } } return 1; } double ossimImageCombiner::getNullPixelValue(ossim_uint32 band)const { if(getInput(theInputToPassThrough)) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(theInputToPassThrough)); if(temp) { ossim_uint32 bands = temp->getNumberOfOutputBands(); if(band < bands) { return temp->getNullPixelValue(band); } else { return temp->getNullPixelValue(bands-1); } } } return 0.0; } double ossimImageCombiner::getMinPixelValue(ossim_uint32 band)const { const char* MODULE = "ossimImageCombiner::getMinPixelValue"; if(!getNumberOfInputs()) { return ossim::nan(); } double result = 1.0/DBL_EPSILON; for(ossim_uint32 index = 0; index < getNumberOfInputs();++index) { ossimImageSource* input = PTR_CAST(ossimImageSource, getInput(index)); if(input) { ossim_uint32 bands = input->getNumberOfOutputBands(); double temp = 0; if(band < bands) { temp = input->getMinPixelValue(band); } else { temp = input->getMinPixelValue(0); } if(temp < result) { result = temp; } } } if(traceDebug()) { CLOG << "min pixel returned is = " << result; } return result; } double ossimImageCombiner::getMaxPixelValue(ossim_uint32 band)const { const char* MODULE = "ossimImageCombiner::getMaxPixelValue"; if(!getNumberOfInputs()) { return ossim::nan(); } double result = -1.0/DBL_EPSILON; for(ossim_uint32 idx = 0; idx < getNumberOfInputs();++idx) { ossimImageSource* input = PTR_CAST(ossimImageSource, getInput(idx)); if(input) { ossim_uint32 bands = input->getNumberOfOutputBands(); double temp = 0; if(band < bands) { temp = input->getMaxPixelValue(band); } else { temp = input->getMaxPixelValue(0); } if(temp > result) { result = temp; } } } if(traceDebug()) { CLOG << "max pixel returned is = " << result; } return result; } void ossimImageCombiner::initialize() { theLargestNumberOfInputBands = 0; theComputeFullResBoundsFlag = true; // now find the largest number of bands // ossim_uint32 size = getNumberOfInputs(); ossimScalarType scalarType = OSSIM_SCALAR_UNKNOWN; ossim_uint32 scalarSizeInBytes = 0; theInputToPassThrough = 0; theHasDifferentInputs= false; if(size > 0) { for(ossim_uint32 idx = 0; idx < size; ++idx) { ossimImageSource* temp = PTR_CAST(ossimImageSource, getInput(idx)); if(temp) { ossim_uint32 numberOfBands = temp->getNumberOfOutputBands(); if(numberOfBands > theLargestNumberOfInputBands) { theLargestNumberOfInputBands = numberOfBands; } ossimScalarType current = temp->getOutputScalarType(); if(current != scalarType) { if(scalarType == OSSIM_SCALAR_UNKNOWN) { scalarType = current; scalarSizeInBytes = ossim::scalarSizeInBytes(scalarType); theInputToPassThrough = idx; } else { theHasDifferentInputs = true; if(scalarSizeInBytes < ossim::scalarSizeInBytes(current)) { scalarType = current; scalarSizeInBytes = ossim::scalarSizeInBytes(current); theInputToPassThrough = idx; } } } } } } } bool ossimImageCombiner::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimImageSource::loadState(kwl, prefix); return result; } void ossimImageCombiner::updateRects() { theComputeFullResBoundsFlag = true; } // ossimRefPtr ossimImageCombiner::getNextTile(ossim_uint32& returnedIdx, // ossim_uint32 idx, // const ossimIpt& tileRect, // ossim_uint32 resLevel) // { // theCurrentIndex = idx; // return getNextTile(returnedIdx, origin, resLevel); // } // ossimRefPtr ossimImageCombiner::getNextTile(ossim_uint32& returnedIdx, // ossim_uint32 idx, // const ossimIpt& origin, // ossim_uint32 resLevel) // { // theCurrentIndex = idx; // return getNextTile(returnedIdx, origin, resLevel); // } ossimRefPtr ossimImageCombiner::getNextTile(ossim_uint32& returnedIdx, const ossim_uint32 startIdx, const ossimIrect& tileRect, ossim_uint32 resLevel) { theCurrentIndex = startIdx; return getNextTile(returnedIdx, tileRect, resLevel); } // ossimRefPtr ossimImageCombiner::getNextTile(ossim_uint32& returnedIdx, // const ossimIpt& origin, // ossim_uint32 resLevel) // { // ossim_int32 w = getTileWidth(); // ossim_int32 h = getTileHeight(); // return getNextTile(returnedIndex, // ossimIrect(origin.x, // origin.y, // origin.x + w-1, // origin.y + h-1), // resLevel); // } ossimRefPtr ossimImageCombiner::getNextTile(ossim_uint32& returnedIdx, const ossimIrect& tileRect, ossim_uint32 resLevel) { ossim_uint32 size = getNumberOfInputs(); if ( theCurrentIndex >= size) { return 0; } if(theComputeFullResBoundsFlag) { precomputeBounds(); } ossimImageSource* temp = 0; ossimRefPtr result = 0; ossimDataObjectStatus status = OSSIM_NULL; double scale = 1.0/std::pow(2.0, (double)resLevel); ossimDpt scalar(scale, scale); while( (theCurrentIndexgetTile(tileRect, resLevel); status = (result.valid() ? result->getDataObjectStatus():OSSIM_NULL); if((status == OSSIM_NULL)|| (status == OSSIM_EMPTY)) { result = 0; } } else { status = OSSIM_NULL; result = 0; } } else { status = OSSIM_NULL; result = NULL; } // Go to next source. ++theCurrentIndex; } returnedIdx = theCurrentIndex; if(result.valid()) { --returnedIdx; } return result; } bool ossimImageCombiner::getNextTile(ossim_uint32& returnedIdx, const ossim_uint32 startIdx, ossimImageData* tile, ossim_uint32 resLevel) { if (!tile) return false; ossim_uint32 size = getNumberOfInputs(); theCurrentIndex = startIdx; if(theComputeFullResBoundsFlag) precomputeBounds(); ossimImageSource* temp = 0; ossimDataObjectStatus status = OSSIM_NULL; double scale = 1.0/std::pow(2.0, (double)resLevel); ossimDpt scalar(scale, scale); while( (theCurrentIndexgetImageRectangle()) && temp) { temp->getTile(tile, resLevel); status = tile->getDataObjectStatus(); if((status != OSSIM_NULL) && (status != OSSIM_EMPTY)) { break; } } } // Go to next source. ++theCurrentIndex; } returnedIdx = theCurrentIndex; if((status == OSSIM_NULL) || (status == OSSIM_EMPTY)) { --returnedIdx; return false; } return true; } // ossimRefPtr ossimImageCombiner::getNextNormTile(ossim_uint32& returnedIdx, // ossim_uint32 index, // const ossimIpt& origin, // ossim_uint32 resLevel) // { // theCurrentIndex = index; // return getNextNormTile(returnedIdx, origin, resLevel); // } ossimRefPtr ossimImageCombiner::getNextNormTile(ossim_uint32& returnedIdx, const ossim_uint32 startIdx, const ossimIrect& tileRect, ossim_uint32 resLevel) { theCurrentIndex = startIdx; return getNextNormTile(returnedIdx, tileRect, resLevel); } // ossimRefPtr ossimImageCombiner::getNextNormTile(ossim_uint32& returnedIdx, // const ossimIpt& origin, // ossim_uint32 resLevel) // { // ossim_int32 w = getTileWidth(); // ossim_int32 h = getTileHeight(); // return getNextNormTile(returnedIdx, // ossimIrect(origin.x, // origin.y, // origin.x + w-1, // origin.y + h-1), // resLevel); // } ossimRefPtr ossimImageCombiner::getNextNormTile(ossim_uint32& returnedIdx, const ossimIrect& tileRect, ossim_uint32 resLevel) { ossim_uint32 size = getNumberOfInputs(); if(theCurrentIndex >= size) { return 0; } if(!theNormTile) { theNormTile = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT); theNormTile->initialize(); } ossimRefPtr result = getNextTile(returnedIdx, tileRect, resLevel); if(result.valid()) { theNormTile->setImageRectangleAndBands(result->getImageRectangle(), result->getNumberOfBands()); result->copyTileToNormalizedBuffer((float*)theNormTile->getBuf()); theNormTile->setDataObjectStatus(result->getDataObjectStatus()); result = theNormTile; } return result; } ossim_uint32 ossimImageCombiner::getNumberOfOverlappingImages(const ossimIrect& rect, ossim_uint32 resLevel)const { if(theComputeFullResBoundsFlag) { precomputeBounds(); } double scale = 1.0/std::pow(2.0, (double)resLevel); ossimDpt scalar(scale, scale); ossim_uint32 result = 0; ossim_uint32 maxIndex = getNumberOfInputs(); for(ossim_uint32 inputIndex = 0; inputIndex < maxIndex; ++inputIndex) { if(!theFullResBounds[inputIndex].hasNans()) { ossimIrect boundingRect = theFullResBounds[inputIndex] * scalar; if(rect.intersects(boundingRect)) { ++result; } } } return result; } void ossimImageCombiner::getOverlappingImages(std::vector& result, const ossimIrect& rect, ossim_uint32 resLevel)const { if(theComputeFullResBoundsFlag) { precomputeBounds(); } double scale = 1.0/std::pow(2.0, (double)resLevel); ossimDpt scalar(scale, scale); ossim_uint32 inputIndex; ossimIrect boundingRect; for(inputIndex = 0; inputIndex < getNumberOfInputs(); ++inputIndex) { if(!theFullResBounds[inputIndex].hasNans()) { boundingRect = theFullResBounds[inputIndex]*scalar; if(rect.intersects(boundingRect)) { result.push_back(inputIndex); } } } } void ossimImageCombiner::connectInputEvent(ossimConnectionEvent& /* event */) { initialize(); } void ossimImageCombiner::disconnectInputEvent(ossimConnectionEvent& /* event */) { initialize(); } void ossimImageCombiner::propertyEvent(ossimPropertyEvent& /* event */) { initialize(); } void ossimImageCombiner::refreshEvent(ossimRefreshEvent& /* event */) { initialize(); } bool ossimImageCombiner::hasDifferentInputs()const { return theHasDifferentInputs; } bool ossimImageCombiner::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimImageSource::saveState(kwl, prefix); } bool ossimImageCombiner::canConnectMyInputTo(ossim_int32 /* inputIndex */, const ossimConnectableObject* object)const { return (object&& PTR_CAST(ossimImageSource, object)); } void ossimImageCombiner::precomputeBounds()const { ossim_uint32 inputSize = getNumberOfInputs(); if(inputSize) { ossimImageSource* tempInterface=0; if(theFullResBounds.size() != inputSize) { theFullResBounds.resize(inputSize); } for(ossim_uint32 inputIndex = 0; inputIndex < inputSize; ++inputIndex) { tempInterface = PTR_CAST(ossimImageSource, getInput(inputIndex)); if(tempInterface) { theFullResBounds[inputIndex] = tempInterface->getBoundingRect(); } else { theFullResBounds[inputIndex].makeNan(); } } theComputeFullResBoundsFlag = false; } else { theFullResBounds.clear(); } } ossim-Miami-2.9.1/src/imaging/ossimImageData.cpp000066400000000000000000006720071352751253100215240ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id$ #include #include //#include #include #include //#include #include #include #include #include #include //#include #include #include #include #include #include #include #include //#include using namespace std; RTTI_DEF1(ossimImageData, "ossimImageData", ossimRectilinearDataObject) ossimImageData::ossimImageData() : ossimRectilinearDataObject(2, // 2d 0, // owner 1, // bands OSSIM_UINT8), // scalar m_nullPixelValue(0), m_minPixelValue(0), m_maxPixelValue(0), m_alpha(0), m_origin(0, 0), m_indexedFlag(false), m_histogram(NULL) { ossimIpt tileSize; ossim::defaultTileSize(tileSize); m_spatialExtents[0] = tileSize.x; m_spatialExtents[1] = tileSize.y; initializeDefaults(); } ossimImageData::ossimImageData(ossimSource* owner, ossimScalarType scalar, ossim_uint32 bands) : ossimRectilinearDataObject(2, owner, bands, scalar), m_nullPixelValue(0), m_minPixelValue(0), m_maxPixelValue(0), m_alpha(0), m_origin(0, 0), m_indexedFlag(false), m_histogram(NULL) { ossimIpt tileSize; ossim::defaultTileSize(tileSize); m_spatialExtents[0] = tileSize.x; m_spatialExtents[1] = tileSize.y; initializeDefaults(); } ossimImageData::ossimImageData(ossimSource* owner, ossimScalarType scalar, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height) : ossimRectilinearDataObject(owner, bands, width, // 2-D array height, scalar), m_nullPixelValue(0), m_minPixelValue(0), m_maxPixelValue(0), m_alpha(0), m_origin(0, 0), m_indexedFlag(false), m_histogram(NULL), m_percentFull(0) { m_spatialExtents[0] = width; m_spatialExtents[1] = height; initializeDefaults(); } ossimImageData::ossimImageData(const ossimImageData &rhs) : ossimRectilinearDataObject(rhs), m_nullPixelValue(rhs.m_nullPixelValue), m_minPixelValue(rhs.m_minPixelValue), m_maxPixelValue(rhs.m_maxPixelValue), m_alpha(rhs.m_alpha), m_origin(rhs.m_origin), m_indexedFlag(rhs.m_indexedFlag), m_percentFull(0) { } const ossimImageData& ossimImageData::operator=(const ossimImageData& rhs) { if (this != &rhs) { // ossimRectilinearDataObject initialization: ossimRectilinearDataObject::operator=(rhs); // ossimImageData (this) members: m_nullPixelValue = rhs.m_nullPixelValue; m_minPixelValue = rhs.m_minPixelValue; m_maxPixelValue = rhs.m_maxPixelValue; m_alpha = rhs.m_alpha; m_origin = rhs.m_origin; m_indexedFlag = rhs.m_indexedFlag; } return *this; } ossimImageData::~ossimImageData() { } bool ossimImageData::isValidBand(ossim_uint32 band) const { return (band 0) { return &m_alpha.front(); } return 0; } ossim_uint8* ossimImageData::getAlphaBuf() { if (m_alpha.size() > 0) { return &m_alpha.front(); } return 0; } const void* ossimImageData::getBuf() const { if (m_dataBuffer.size() > 0) { return static_cast(&m_dataBuffer.front()); } return 0; } void* ossimImageData::getBuf() { if (m_dataBuffer.size() > 0) { return static_cast(&m_dataBuffer.front()); } return 0; } const void* ossimImageData::getBuf(ossim_uint32 band) const { const ossim_uint8* b = static_cast(getBuf()); if (isValidBand(band) && b != 0) { b += (band * getSizePerBandInBytes()); return static_cast(b); } return 0; } void* ossimImageData::getBuf(ossim_uint32 band) { ossim_uint8* b = static_cast(getBuf()); if (isValidBand(band) && b != 0) { b += (band * getSizePerBandInBytes()); return static_cast(b); } return 0; } const ossim_uint8* ossimImageData::getUcharBuf() const { if (m_scalarType == OSSIM_UINT8) { return static_cast(getBuf()); } return 0; } const ossim_uint16* ossimImageData::getUshortBuf() const { if (m_scalarType == OSSIM_UINT16 || m_scalarType == OSSIM_USHORT11 || m_scalarType == OSSIM_USHORT12 || m_scalarType == OSSIM_USHORT13 || m_scalarType == OSSIM_USHORT14 || m_scalarType == OSSIM_USHORT15) { return static_cast(getBuf()); } return 0; } const ossim_sint16* ossimImageData::getSshortBuf() const { if (m_scalarType == OSSIM_SINT16) { return static_cast(getBuf()); } return 0; } const ossim_float32* ossimImageData::getFloatBuf() const { if (m_scalarType == OSSIM_FLOAT32 || m_scalarType == OSSIM_NORMALIZED_FLOAT) { return static_cast(getBuf()); } return 0; } const ossim_float64* ossimImageData::getDoubleBuf() const { if (m_scalarType == OSSIM_FLOAT64 || m_scalarType == OSSIM_NORMALIZED_DOUBLE) { return static_cast(getBuf()); } return 0; } ossim_uint8* ossimImageData::getUcharBuf() { if (m_scalarType == OSSIM_UINT8) { return static_cast(getBuf()); } return 0; } ossim_uint16* ossimImageData::getUshortBuf() { if (m_scalarType == OSSIM_UINT16 || m_scalarType == OSSIM_USHORT11 || m_scalarType == OSSIM_USHORT12 || m_scalarType == OSSIM_USHORT13 || m_scalarType == OSSIM_USHORT14 || m_scalarType == OSSIM_USHORT15) { return static_cast(getBuf()); } return 0; } ossim_sint16* ossimImageData::getSshortBuf() { if (m_scalarType == OSSIM_SINT16) { return static_cast(getBuf()); } return 0; } ossim_float32* ossimImageData::getFloatBuf() { if (m_scalarType == OSSIM_FLOAT32 || m_scalarType == OSSIM_NORMALIZED_FLOAT) { return static_cast(getBuf()); } return 0; } ossim_float64* ossimImageData::getDoubleBuf() { if (m_scalarType == OSSIM_FLOAT64 || m_scalarType == OSSIM_NORMALIZED_DOUBLE) { return static_cast(getBuf()); } return 0; } const ossim_uint8* ossimImageData::getUcharBuf(ossim_uint32 band) const { if (m_scalarType == OSSIM_UINT8) { return static_cast(getBuf(band)); } return 0; } const ossim_uint16* ossimImageData::getUshortBuf(ossim_uint32 band) const { if (m_scalarType == OSSIM_UINT16 || m_scalarType == OSSIM_USHORT11 || m_scalarType == OSSIM_USHORT12 || m_scalarType == OSSIM_USHORT13 || m_scalarType == OSSIM_USHORT14 || m_scalarType == OSSIM_USHORT15) { return static_cast(getBuf(band)); } return 0; } const ossim_sint16* ossimImageData::getSshortBuf(ossim_uint32 band) const { if (m_scalarType == OSSIM_SINT16) { return static_cast(getBuf(band)); } return 0; } const ossim_float32* ossimImageData::getFloatBuf(ossim_uint32 band) const { if (m_scalarType == OSSIM_FLOAT32 || m_scalarType == OSSIM_NORMALIZED_FLOAT) { return static_cast(getBuf(band)); } return 0; } const ossim_float64* ossimImageData::getDoubleBuf(ossim_uint32 band) const { if (m_scalarType == OSSIM_FLOAT64 || m_scalarType == OSSIM_NORMALIZED_DOUBLE) { return static_cast(getBuf(band)); } return 0; } ossim_uint8* ossimImageData::getUcharBuf(ossim_uint32 band) { if (m_scalarType == OSSIM_UINT8) { return static_cast(getBuf(band)); } return 0; } ossim_uint16* ossimImageData::getUshortBuf(ossim_uint32 band) { if (m_scalarType == OSSIM_UINT16 || m_scalarType == OSSIM_USHORT11 || m_scalarType == OSSIM_USHORT12 || m_scalarType == OSSIM_USHORT13 || m_scalarType == OSSIM_USHORT14 || m_scalarType == OSSIM_USHORT15) { return static_cast(getBuf(band)); } return 0; } ossim_sint16* ossimImageData::getSshortBuf(ossim_uint32 band) { if (m_scalarType == OSSIM_SINT16) { return static_cast(getBuf(band)); } return 0; } ossim_float32* ossimImageData::getFloatBuf(ossim_uint32 band) { if (m_scalarType == OSSIM_FLOAT32 || m_scalarType == OSSIM_NORMALIZED_FLOAT) { return static_cast(getBuf(band)); } return 0; } ossim_float64* ossimImageData::getDoubleBuf(ossim_uint32 band) { if (m_scalarType == OSSIM_FLOAT64 || m_scalarType == OSSIM_NORMALIZED_DOUBLE) { return static_cast(getBuf(band)); } return 0; } void ossimImageData::getNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, ossim_float32& result)const { // Make sure that the types and width and height are good. if( (getDataObjectStatus() != OSSIM_NULL) && (bandNumber < getNumberOfDataComponents()) ) { ossim_float32 p = 0.0; switch (getScalarType()) { case OSSIM_UINT8: { const unsigned char* sourceBuf = getUcharBuf(bandNumber); p = sourceBuf[offset]; break; } case OSSIM_SINT8: { const ossim_sint8* sourceBuf = static_cast(getBuf(bandNumber)); p = sourceBuf[offset]; break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { const ossim_uint16* sourceBuf = getUshortBuf(bandNumber); p = sourceBuf[offset]; break; } case OSSIM_SINT16: { const ossim_sint16* sourceBuf = getSshortBuf(bandNumber); p = sourceBuf[offset]; break; } case OSSIM_UINT32: { const ossim_uint32* sourceBuf = static_cast(getBuf(bandNumber)); p = sourceBuf[offset]; break; } case OSSIM_SINT32: { const ossim_sint32* sourceBuf = static_cast(getBuf(bandNumber)); p = sourceBuf[offset]; break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { const ossim_float32* sourceBuf = getFloatBuf(bandNumber); p = sourceBuf[offset]; break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { const ossim_float64* sourceBuf = getDoubleBuf(bandNumber); p = sourceBuf[offset]; break; } case OSSIM_SCALAR_UNKNOWN: default: { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::setNormalizedFloat Unsupported scalar type!" << std::endl; } } // Matches: switch (getScalarType()) if ( p != m_nullPixelValue[bandNumber] ) { const ossim_float32 DELTA = m_maxPixelValue[bandNumber] - m_minPixelValue[bandNumber] - 1; const ossim_float32 OFFSET_TO_ONE = 1 - m_minPixelValue[bandNumber]; result = ( p <= m_maxPixelValue[bandNumber] ) ? ( ( p >= m_minPixelValue[bandNumber] ) ? ( p + OFFSET_TO_ONE ) / DELTA : 0.0 ) : 1.0; } else { result = 0.0; } } // Matches: if( (getDataObjectStatus() ... } // End: ossimImageData::getNormalizedFloat void ossimImageData::setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, ossim_float32 inputValue) { // Make sure that the types and width and height are good. if( (getDataObjectStatus() != OSSIM_NULL) && (bandNumber < getNumberOfDataComponents()) ) { ossim_float32 p = 0.0; if ( inputValue ) { const ossim_float32 DELTA = m_maxPixelValue[bandNumber] - m_minPixelValue[bandNumber] - 1; const ossim_float32 OFFSET_TO_MIN = m_minPixelValue[bandNumber] - 1; p = inputValue * DELTA + OFFSET_TO_MIN + 0.5; if ( p > m_maxPixelValue[bandNumber] ) { p = m_maxPixelValue[bandNumber]; } } else { p = m_nullPixelValue[bandNumber]; } switch (getScalarType()) { case OSSIM_UINT8: { unsigned char* sourceBuf = getUcharBuf(bandNumber); sourceBuf[offset] = static_cast( p ); break; } case OSSIM_SINT8: { ossim_sint8* sourceBuf = static_cast(getBuf(bandNumber)); sourceBuf[offset] = static_cast( p ); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { ossim_uint16* sourceBuf = getUshortBuf(bandNumber); sourceBuf[offset] = static_cast( p ); break; } case OSSIM_SINT16: { ossim_sint16* sourceBuf = getSshortBuf(bandNumber); sourceBuf[offset] = static_cast( p ); break; } case OSSIM_UINT32: { ossim_uint32* sourceBuf = static_cast(getBuf(bandNumber)); sourceBuf[offset] = static_cast( p ); break; } case OSSIM_SINT32: { ossim_sint32* sourceBuf = static_cast(getBuf(bandNumber)); sourceBuf[offset] = static_cast( p ); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { ossim_float32* sourceBuf = getFloatBuf(bandNumber); sourceBuf[offset] = p; break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { ossim_float64* sourceBuf = getDoubleBuf(bandNumber); sourceBuf[offset] = p; break; } case OSSIM_SCALAR_UNKNOWN: default: // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::setNormalizedFloat Unsupported scalar type!" << std::endl; } // Matches: switch (getScalarType()) } // Matches: if( (getDataObjectStatus() ... } // End: ossimImageData::setNormalizedFloat void ossimImageData::convertToNormalizedFloat(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } copyTileToNormalizedBuffer((ossim_float32*)result->getBuf()); result->setDataObjectStatus(getDataObjectStatus()); } ossimRefPtr ossimImageData::newNormalizedFloat()const { ossimRefPtr result = new ossimImageData(0, OSSIM_NORMALIZED_FLOAT, this->getNumberOfBands(), this->getWidth(), this->getHeight()); result->initialize(); convertToNormalizedFloat(result.get()); return result; } void ossimImageData::convertToNormalizedDouble(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_DOUBLE) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } copyTileToNormalizedBuffer((ossim_float64*)result->getBuf()); result->setDataObjectStatus(getDataObjectStatus()); } ossimImageData* ossimImageData::newNormalizedDouble()const { ossimImageData* result = new ossimImageData(0, OSSIM_NORMALIZED_DOUBLE, this->getNumberOfBands(), this->getWidth(), this->getHeight()); result->initialize(); convertToNormalizedDouble(result); return result; } void ossimImageData::unnormalizeInput(ossimImageData* normalizedInput) { if((normalizedInput->getScalarType() != OSSIM_NORMALIZED_FLOAT) && (normalizedInput->getScalarType() != OSSIM_NORMALIZED_DOUBLE) ) { //ERROR return; } if(normalizedInput->getScalarType() == OSSIM_NORMALIZED_DOUBLE) { copyNormalizedBufferToTile((ossim_float64*)normalizedInput->getBuf()); } else { copyNormalizedBufferToTile((ossim_float32*)normalizedInput->getBuf()); } } ossim_float64 ossimImageData::computeMeanSquaredError( ossim_float64 meanValue, ossim_uint32 bandNumber) const { ossim_float64 result = -1; // invalid MSE switch (getScalarType()) { case OSSIM_UINT8: { result = computeMeanSquaredError(ossim_uint8(0), meanValue, bandNumber); break; } case OSSIM_SINT8: { result = computeMeanSquaredError(ossim_sint8(0), meanValue, bandNumber); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { result = computeMeanSquaredError(ossim_uint16(0), meanValue, bandNumber); break; } case OSSIM_SINT16: { result = computeMeanSquaredError(ossim_sint16(0), meanValue, bandNumber); break; } case OSSIM_UINT32: { result = computeMeanSquaredError(ossim_uint32(0), meanValue, bandNumber); break; } case OSSIM_SINT32: { result = computeMeanSquaredError(ossim_sint32(0), meanValue, bandNumber); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { result = computeMeanSquaredError(ossim_float32(0.0), meanValue, bandNumber); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { result = computeMeanSquaredError(ossim_float64(0.0), meanValue, bandNumber); break; } case OSSIM_SCALAR_UNKNOWN: default: { setDataObjectStatus(OSSIM_STATUS_UNKNOWN); ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::computeMeanSquaredError File %s line %d\n\ Invalid scalar type: %d", __FILE__, __LINE__, getScalarType()); break; } } return result; } template ossim_float64 ossimImageData::computeMeanSquaredError( T, /* dummyTemplate */ ossim_float64 meanValue, ossim_uint32 bandNumber) const { ossim_float64 result = -1.0; // invalid MSE if ( (getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_EMPTY) ) { return result; } ossim_uint32 index = 0; ossim_float64 delta = 0.0; ossim_uint32 validPixelCount = 0; const T* BUFFER = static_cast(getBuf(bandNumber)); if(BUFFER) { const ossim_uint32 BOUNDS = getSizePerBand(); for(index = 0; index < BOUNDS; ++index) { if(!isNull(index)) { delta = BUFFER[index] - meanValue; result += (delta*delta); ++validPixelCount; } } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } //****************************************************************** // // NOTE: I was checking for null and not adding it to the histogram. // this was messing up the equalization algorithms since the // accumulation histogram did not represent the area of the // image. For now I will leave out the check for "is null" and // add this to the count so that the total accumulation is the // area of the image. // //****************************************************************** /* Method repalace by populateHistogram(...) that takes a clip rect. * drb - 20190218 */ #if 0 void ossimImageData::populateHistogram(ossimRefPtr histo) { if ( (getDataObjectStatus() != OSSIM_NULL) && histo.valid() ) { ossim_uint32 numberOfBands = getNumberOfBands(); ossim_uint32 upperBound = getWidth()*getHeight(); if (getDataObjectStatus() != OSSIM_EMPTY) { switch(getScalarType()) { case OSSIM_UINT8: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_uint8 nullpix = (ossim_uint8)getNullPix(band); float* histoBins = currentHisto->GetCounts(); int binCount = currentHisto->GetRes(); ossim_uint8* buffer = (ossim_uint8*)getBuf(band); ossim_uint32 upperBound = getWidth()*getHeight(); if ( binCount == 256 ) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (buffer[offset] != nullpix) { ++histoBins[ buffer[offset] ]; } else { currentHisto->upNullCount(); } } } else { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (buffer[offset] != nullpix) { currentHisto->UpCount((float)buffer[offset]); } else { currentHisto->upNullCount(); } } } } } break; } case OSSIM_UINT9: case OSSIM_UINT10: case OSSIM_UINT11: case OSSIM_UINT12: case OSSIM_UINT13: case OSSIM_UINT14: case OSSIM_UINT15: case OSSIM_UINT16: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_uint16 nullpix = (ossim_uint16)getNullPix(band); ossim_uint16* buffer = (ossim_uint16*)getBuf(band); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (buffer[offset] != nullpix) { currentHisto->UpCount((float)buffer[offset]); } else { currentHisto->upNullCount(); } } } } break; } case OSSIM_SINT16: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_sint16 nullpix = (ossim_sint16)getNullPix(band); ossim_sint16* buffer = (ossim_sint16*)getBuf(band); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (buffer[offset] != nullpix) { currentHisto->UpCount((float)buffer[offset]); } else { currentHisto->upNullCount(); } } } } break; } case OSSIM_SINT32: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_sint32 nullpix = (ossim_sint32)getNullPix(band); ossim_sint32* buffer = (ossim_sint32*)getBuf(band); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (buffer[offset] != nullpix) { currentHisto->UpCount((float)buffer[offset]); } else { currentHisto->upNullCount(); } } } } break; } case OSSIM_UINT32: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_uint32 nullpix = (ossim_uint32)getNullPix(band); ossim_uint32* buffer = (ossim_uint32*)getBuf(band); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (buffer[offset] != nullpix) { currentHisto->UpCount((float)buffer[offset]); } else { currentHisto->upNullCount(); } } } } break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { ossim_float64 epsilon = 2*DBL_EPSILON; for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_float64 nullpix = (ossim_float64)getNullPix(band); if (nullpix == 0.0) epsilon = 0; ossim_float64* buffer = (ossim_float64*)getBuf(band); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (!ossim::almostEqual(buffer[offset], nullpix, epsilon)) { currentHisto->UpCount((float)buffer[offset]); } else { currentHisto->upNullCount(); } } } } break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { ossim_float32 epsilon = 2*FLT_EPSILON; for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_float32 nullpix = (ossim_float32)getNullPix(band); if (nullpix == 0.0) epsilon = 0; ossim_float32* buffer = (ossim_float32*)getBuf(band); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (!ossim::almostEqual(buffer[offset], nullpix, epsilon)) { currentHisto->UpCount((float)buffer[offset]); } else { currentHisto->upNullCount(); } } } } break; } case OSSIM_SCALAR_UNKNOWN: default: { //ERROR ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::populateHistogram\n" << "Unknown scalar type." << std::endl; } } // end of switch } else // Tile is empty. { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { currentHisto->upNullCount( upperBound ); } } } } } #endif void ossimImageData::populateHistogram(ossimRefPtr histo, const ossimIrect& clip_rect) { if ( (getDataObjectStatus() != OSSIM_NULL) && histo.valid() ) { const ossimIrect img_rect = getImageRectangle(); ossimIrect tile_clip_rect = img_rect.clipToRect( clip_rect ); // Check the clip rect. if ( tile_clip_rect.completely_within(img_rect) ) { ossim_uint32 numberOfBands = getNumberOfBands(); ossim_uint32 imgWidth = getWidth(); ossim_uint32 clipHeight = tile_clip_rect.height(); ossim_uint32 clipWidth = tile_clip_rect.width(); if (getDataObjectStatus() != OSSIM_EMPTY) { switch(getScalarType()) { case OSSIM_UINT8: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_uint8 nullpix = (ossim_uint8)getNullPix(band); ossim_uint8* buffer = (ossim_uint8*)getBuf(band); // Move the pointer to the first valid pixel. buffer += (tile_clip_rect.ul().y - img_rect.ul().y) * imgWidth + tile_clip_rect.ul().x - img_rect.ul().x; for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { if ( buffer[sample] != nullpix ) { currentHisto->UpCount((float)buffer[sample]); } else { currentHisto->upNullCount(); } } buffer += imgWidth; } } } break; } case OSSIM_UINT9: case OSSIM_UINT10: case OSSIM_UINT11: case OSSIM_UINT12: case OSSIM_UINT13: case OSSIM_UINT14: case OSSIM_UINT15: case OSSIM_UINT16: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_uint16 nullpix = (ossim_uint16)getNullPix(band); ossim_uint16* buffer = (ossim_uint16*)getBuf(band); // Move the pointer to the first valid pixel. buffer += (tile_clip_rect.ul().y - img_rect.ul().y) * imgWidth + tile_clip_rect.ul().x - img_rect.ul().x; for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { if ( buffer[sample] != nullpix ) { currentHisto->UpCount((float)buffer[sample]); } else { currentHisto->upNullCount(); } } buffer += imgWidth; } } } break; } case OSSIM_SINT16: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_sint16 nullpix = (ossim_sint16)getNullPix(band); ossim_sint16* buffer = (ossim_sint16*)getBuf(band); // Move the pointer to the first valid pixel. buffer += (tile_clip_rect.ul().y - img_rect.ul().y) * imgWidth + tile_clip_rect.ul().x - img_rect.ul().x; for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { if ( buffer[sample] != nullpix ) { currentHisto->UpCount((float)buffer[sample]); } else { currentHisto->upNullCount(); } } buffer += imgWidth; } } } break; } case OSSIM_SINT32: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_sint32 nullpix = (ossim_sint32)getNullPix(band); ossim_sint32* buffer = (ossim_sint32*)getBuf(band); // Move the pointer to the first valid pixel. buffer += (tile_clip_rect.ul().y - img_rect.ul().y) * imgWidth + tile_clip_rect.ul().x - img_rect.ul().x; for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { if ( buffer[sample] != nullpix ) { currentHisto->UpCount((float)buffer[sample]); } else { currentHisto->upNullCount(); } } buffer += imgWidth; } } } break; } case OSSIM_UINT32: { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_uint32 nullpix = (ossim_uint32)getNullPix(band); ossim_uint32* buffer = (ossim_uint32*)getBuf(band); // Move the pointer to the first valid pixel. buffer += (tile_clip_rect.ul().y - img_rect.ul().y) * imgWidth + tile_clip_rect.ul().x - img_rect.ul().x; for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { if ( buffer[sample] != nullpix ) { currentHisto->UpCount((float)buffer[sample]); } else { currentHisto->upNullCount(); } } buffer += imgWidth; } } } break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { ossim_float32 epsilon = 2*FLT_EPSILON; for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_float32 nullpix = (ossim_float32)getNullPix(band); if (nullpix == 0.0) epsilon = 0; ossim_float32* buffer = (ossim_float32*)getBuf(band); // Move the pointer to the first valid pixel. buffer += (tile_clip_rect.ul().y - img_rect.ul().y) * imgWidth + tile_clip_rect.ul().x - img_rect.ul().x; for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { if ( !ossim::almostEqual( buffer[sample], nullpix, epsilon) ) { currentHisto->UpCount((float)buffer[sample]); } else { currentHisto->upNullCount(); } } } } } break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { ossim_float64 epsilon = 2*DBL_EPSILON; for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { ossim_float64 nullpix = (ossim_float64)getNullPix(band); if (nullpix == 0.0) epsilon = 0; ossim_float64* buffer = (ossim_float64*)getBuf(band); // Move the pointer to the first valid pixel. buffer += (tile_clip_rect.ul().y - img_rect.ul().y) * imgWidth + tile_clip_rect.ul().x - img_rect.ul().x; for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { if ( !ossim::almostEqual( buffer[sample], nullpix, epsilon) ) { currentHisto->UpCount((float)buffer[sample]); } else { currentHisto->upNullCount(); } } } } } break; } case OSSIM_SCALAR_UNKNOWN: default: { //ERROR ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::populateHistogram\n" << "Unknown scalar type." << std::endl; } } // end of switch } else // Tile is empty. { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { ossimRefPtr currentHisto = histo->getHistogram(band); if(currentHisto.valid()) { currentHisto->upNullCount( tile_clip_rect.area() ); } } } } } } ossim_float64 ossimImageData::computeAverageBandValue(ossim_uint32 bandNumber) const { ossim_float64 result = 0.0; switch (getScalarType()) { case OSSIM_UINT8: { result = computeAverageBandValue(ossim_uint8(0), bandNumber); break; } case OSSIM_SINT8: { result = computeAverageBandValue(ossim_sint8(0), bandNumber); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { result = computeAverageBandValue(ossim_uint16(0), bandNumber); break; } case OSSIM_SINT16: { result = computeAverageBandValue(ossim_sint16(0), bandNumber); break; } case OSSIM_UINT32: { result = computeAverageBandValue(ossim_uint32(0), bandNumber); break; } case OSSIM_SINT32: { result = computeAverageBandValue(ossim_sint32(0), bandNumber); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { result = computeAverageBandValue(ossim_float32(0.0), bandNumber); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { result = computeAverageBandValue(ossim_float64(0.0), bandNumber); break; } case OSSIM_SCALAR_UNKNOWN: default: { setDataObjectStatus(OSSIM_STATUS_UNKNOWN); ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::computeAverageBandValue File %s line %d\n\ Invalid scalar type: %d", __FILE__, __LINE__, getScalarType()); break; } } return result; } template ossim_float64 ossimImageData::computeAverageBandValue( T, /* dummy */ ossim_uint32 bandNumber) const { ossim_float64 result = 0.0; if ( (getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_EMPTY) ) { return result; } ossim_uint32 index = 0; ossim_uint32 validPixelCount = 0; const T* BUFFER = static_cast(getBuf(bandNumber)); if(BUFFER) { const ossim_uint32 BOUNDS = getSizePerBand(); for(index = 0; index < BOUNDS; ++index) { if(!isNull(index)) { result += BUFFER[index]; ++validPixelCount; } } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } ossimDataObjectStatus ossimImageData::validate() const { switch (getScalarType()) { case OSSIM_UINT8: { return validate(ossim_uint8(0)); } case OSSIM_SINT8: { return validate(ossim_sint8(0)); } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { return validate(ossim_uint16(0)); } case OSSIM_SINT16: { return validate(ossim_sint16(0)); } case OSSIM_UINT32: { return validate(ossim_uint32(0)); } case OSSIM_SINT32: { return validate(ossim_sint32(0)); } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { return validate(ossim_float32(0.0)); } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { return validate(ossim_float64(0.0)); } case OSSIM_SCALAR_UNKNOWN: default: { setDataObjectStatus(OSSIM_STATUS_UNKNOWN); break; } } return OSSIM_STATUS_UNKNOWN; } template ossimDataObjectStatus ossimImageData::validate(T /* dummyTemplate */ ) const { if (m_dataBuffer.size() == 0) { setDataObjectStatus(OSSIM_NULL); m_percentFull = 0; return OSSIM_NULL; } ossim_uint32 count = 0; const ossim_uint32 SIZE = getSize(); const ossim_uint32 BOUNDS = getSizePerBand(); const ossim_uint32 NUMBER_OF_BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < NUMBER_OF_BANDS; ++band) { const T NP = static_cast(m_nullPixelValue[band]); const T* p = static_cast(getBuf(band)); for (ossim_uint32 i = 0; i < BOUNDS; ++i) { // check if the band is null if (p[i] != NP) ++count; } } if (!count) { setDataObjectStatus(OSSIM_EMPTY); m_percentFull = 0; } else if (count == SIZE) { setDataObjectStatus(OSSIM_FULL); m_percentFull = 100; } else { setDataObjectStatus(OSSIM_PARTIAL); m_percentFull = 100.0 * count / SIZE; } return getDataObjectStatus(); } void ossimImageData::makeBlank() { if ( (m_dataBuffer.size() == 0) || (getDataObjectStatus() == OSSIM_EMPTY) ) { return; // nothing to do... } switch (getScalarType()) { case OSSIM_UINT8: { makeBlank(ossim_uint8(0)); return; } case OSSIM_SINT8: { makeBlank(ossim_sint8(0)); return; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { makeBlank(ossim_uint16(0)); return; } case OSSIM_SINT16: { makeBlank(ossim_sint16(0)); return; } case OSSIM_UINT32: { makeBlank(ossim_uint32(0)); return; } case OSSIM_SINT32: { makeBlank(ossim_sint32(0)); return; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { makeBlank(ossim_float32(0.0)); return; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { makeBlank(ossim_float64(0.0)); return; } case OSSIM_SCALAR_UNKNOWN: default: { setDataObjectStatus(OSSIM_STATUS_UNKNOWN); ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::makeBlank File %s line %d\n\ Invalid scalar type: %d", __FILE__, __LINE__, getScalarType()); break; } } } template void ossimImageData::makeBlank(T /* dummyTemplate */ ) { // Note: Empty buffer or already OSSIM_EMPTY checked in public method. const ossim_uint32 BANDS = getNumberOfBands(); const ossim_uint32 SPB = getSizePerBand(); ossim_uint32 sizePerBandInBytes = getSizePerBandInBytes(); for(ossim_uint32 band = 0; band < BANDS; ++band) { const T NP = static_cast(m_nullPixelValue[band]); if(NP == 0.0) { // do an optimize byte fill memset(getBuf(band), '\0', sizePerBandInBytes); } else { // slower assign call T* p = static_cast(getBuf(band)); for (ossim_uint32 i = 0; i < SPB; ++i) { p[i] = NP; } } } setDataObjectStatus(OSSIM_EMPTY); } void ossimImageData::initialize() { // let the base class allocate a buffer ossimRectilinearDataObject::initialize(); if (m_dataBuffer.size() > 0) { makeBlank(); // Make blank will set the status. } } // Write the tile out to disk with a general raster header file. bool ossimImageData::write(const ossimFilename& f) const { bool result = false; std::ofstream os; os.open(f.c_str(), ios::out | ios::binary); if (os.good()) { // Write the tile out. os.write(static_cast(getBuf()), static_cast(getSizeInBytes())); result = os.good(); if (result) { // Write a header file that we can use to read the tile. os.close(); ossimFilename hdrFile = f; hdrFile.setExtension("hdr"); os.open(hdrFile.c_str(), ios::out); result = os.good(); if (result) { os << "filename: " << f.c_str() << "\nimage_type: general_raster_bsq" << "\nindexed: " << m_indexedFlag << "\ninterleave_type: bsq" << "\norigin: " << m_origin << "\nnumber_bands: " << ossimString::toString(getNumberOfBands()) << "\nnumber_lines: " << ossimString::toString(getHeight()) << "\nnumber_samples: " << ossimString::toString(getWidth()) << "\nscalar_type: " << ossimScalarTypeLut::instance()->getEntryString(getScalarType()) << "\n"; for(ossim_uint32 band=0; band < getNumberOfBands(); ++band) { ossimString bs = "band"; bs += ossimString::toString(band+1); os << bs.c_str() << ".min_value: " << m_minPixelValue[band] << "\n" << bs.c_str() << ".max_value: " << m_maxPixelValue[band] << "\n" << bs.c_str() << ".null_value: " << m_nullPixelValue[band] << std::endl; } } } } os.close(); return result; } bool ossimImageData::isWithin(ossim_int32 x, ossim_int32 y) { return ((x >= m_origin.x) && (x < m_origin.x + static_cast(m_spatialExtents[0])) && (y >= m_origin.y) && (y < m_origin.y + static_cast(m_spatialExtents[1]))); } void ossimImageData::setValue(ossim_int32 x, ossim_int32 y, ossim_float64 color) { for (ossim_uint32 band = 0; band < m_numberOfDataComponents; band++) setValue(x, y, color, band); } void ossimImageData::setValue(ossim_int32 x, ossim_int32 y, ossim_float64 color, ossim_uint32 band) { if(m_dataBuffer.size() > 0 && isWithin(x, y)) { //*** // Compute the offset into the buffer for (x,y). This should always // come out positive. //*** ossim_uint32 ux = static_cast(x - m_origin.x); ossim_uint32 uy = static_cast(y - m_origin.y); ossim_uint32 offset = uy * m_spatialExtents[0] + ux; switch (getScalarType()) { case OSSIM_UINT8: { unsigned char* buf = static_cast(getBuf(band))+offset; *buf = (unsigned char)color; break; } case OSSIM_SINT8: { ossim_sint8* buf = static_cast(getBuf(band))+offset; *buf = (ossim_sint8)color; break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { ossim_uint16* buf = static_cast(getBuf(band))+offset; *buf = (ossim_uint16)color; break; } case OSSIM_SINT16: { signed short* buf = static_cast(getBuf(band))+offset; *buf = (signed short)color; break; } case OSSIM_UINT32: { ossim_uint32* buf = static_cast(getBuf(band))+offset; *buf = (ossim_uint32)color; break; } case OSSIM_SINT32: { ossim_sint32* buf = static_cast(getBuf(band))+offset; *buf = (ossim_sint32)color; break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { ossim_float32* buf = static_cast(getBuf(band))+offset; *buf = (ossim_float32)color; break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { ossim_float64* buf = static_cast(getBuf(band))+offset; *buf = color; break; } case OSSIM_SCALAR_UNKNOWN: default: { //ERROR ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::setValue Unsupported scalar type!" << std::endl; } } // End of: switch (getScalarType()) } } void ossimImageData::initializeDefaults() { initializeMinDefault(); initializeMaxDefault(); initializeNullDefault(); } void ossimImageData::initializeMinDefault() { if(!m_numberOfDataComponents) { return; } m_minPixelValue.resize(m_numberOfDataComponents); ossim_float64 value = ossim::defaultMin( getScalarType() ); for(ossim_uint32 band = 0; band < m_numberOfDataComponents; ++band) { m_minPixelValue[band] = value; } } void ossimImageData::initializeMaxDefault() { if(!m_numberOfDataComponents) { return; } m_maxPixelValue.resize(m_numberOfDataComponents); ossim_float64 value = ossim::defaultMax( getScalarType() ); for(ossim_uint32 band = 0; band < m_numberOfDataComponents; ++band) { m_maxPixelValue[band] = value; } } void ossimImageData::initializeNullDefault() { if(!m_numberOfDataComponents) { return; } m_nullPixelValue.resize(m_numberOfDataComponents); ossim_float64 value = ossim::defaultNull( getScalarType() ); for(ossim_uint32 band = 0; band < m_numberOfDataComponents; ++band) { m_nullPixelValue[band] = value; } } bool ossimImageData::isEqualTo(const ossimDataObject& rhs, bool deepTest)const { const ossimImageData* rhsPtr = dynamic_cast(&rhs); if(!rhsPtr) return false; bool result = ( (m_scalarType == rhsPtr->m_scalarType)&& (m_numberOfDataComponents == rhsPtr->m_numberOfDataComponents)&& (m_origin == rhsPtr->m_origin)&& (getWidth() == rhsPtr->getWidth())&& (getHeight() == rhsPtr->getHeight())); if(result) { bool test=true; for(ossim_uint32 index = 0; index < m_numberOfDataComponents; ++index) { if(m_minPixelValue[index] != rhsPtr->m_minPixelValue[index]) { test = false; break; } if(m_maxPixelValue[index] != rhsPtr->m_maxPixelValue[index]) { test = false; break; } if(m_nullPixelValue[index] != rhsPtr->m_nullPixelValue[index]) { test = false; break; } } result = test; } if(deepTest&&result) { if(getBuf() != 0 && rhsPtr->getBuf() != 0) { if(memcmp(getBuf(), rhsPtr->getBuf(), getSizeInBytes()) != 0) { result = false; } } else if(getBuf() == 0 && rhsPtr->getBuf() == 0) { // nothing both are null so don't change the result. } else // one is null so not equal. { result = false; } } return result; } ossimString ossimImageData::getScalarTypeAsString() const { return ossimScalarTypeLut::instance()->getEntryString(getScalarType()); } ossim_uint32 ossimImageData::getNumberOfBands() const { return getNumberOfDataComponents(); } ossim_float64 ossimImageData::getPix(const ossimIpt& position, ossim_uint32 band) const { ossimIpt relative( position.x - m_origin.x, position.y - m_origin.y); if((relative.x < 0) || (relative.x >= (ossim_int32)m_spatialExtents[0])) return 0.0; if((relative.y < 0) || (relative.y >= (ossim_int32)m_spatialExtents[1])) return 0.0; return getPix((m_spatialExtents[0])*relative.y + relative.x, band); } ossim_float64 ossimImageData::getPix(ossim_uint32 offset, ossim_uint32 band) const { switch(m_scalarType) { case OSSIM_UINT8: { const ossim_uint8* buf = getUcharBuf(band); if(buf) { return (ossim_float64)buf[offset]; } break; } case OSSIM_SINT8: { const ossim_sint8* buf = static_cast(getBuf(band)); if(buf) { return (ossim_float64)buf[offset]; } break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { const ossim_uint16* buf = getUshortBuf(band); if(buf) { return (ossim_float64)buf[offset]; } break; } case OSSIM_SINT16: { const ossim_sint16* buf = getSshortBuf(band); if(buf) { return (ossim_float64)buf[offset]; } break; } case OSSIM_SINT32: { const ossim_sint32* buf = static_cast(getBuf(band)); if(buf) { return (ossim_float64)buf[offset]; } break; } case OSSIM_UINT32: { const ossim_uint32* buf = static_cast(getBuf(band)); if(buf) { return (ossim_float64)buf[offset]; } break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { const ossim_float64* buf = getDoubleBuf(band); if(buf) { return (ossim_float64)buf[offset]; } break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { const ossim_float32* buf = getFloatBuf(band); if(buf) { return (ossim_float64)buf[offset]; } break; } case OSSIM_SCALAR_UNKNOWN: default: // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::fill Unsupported scalar type!" << std::endl; } return 0.0; } void ossimImageData::fill(ossim_uint32 band, ossim_float64 value) { void* s = getBuf(band); if (s == 0) return; // nothing to do... ossim_uint32 size_in_pixels = getWidth()*getHeight(); switch (getScalarType()) { case OSSIM_UINT8: { ossim_uint8* p = getUcharBuf(band); ossim_uint8 np = static_cast(value); for (ossim_uint32 i=0; i(getBuf(band)); ossim_sint8 np = static_cast(value); for (ossim_uint32 i=0; i(value); for (ossim_uint32 i=0; i(value); for (ossim_uint32 i=0; i(getBuf(band)); ossim_uint32 np = static_cast(value); for (ossim_uint32 i=0; i(getBuf(band)); ossim_sint32 np = static_cast(value); for (ossim_uint32 i=0; i(value); for (ossim_uint32 i=0; i(value); for (ossim_uint32 i=0; i void ossimImageData::createTestTile(T) { if (getDataObjectStatus() != OSSIM_NULL) { const ossim_uint32 BANDS = getNumberOfBands(); const ossim_uint32 LINES = getHeight(); const ossim_uint32 SAMPS = getWidth(); const ossim_float64 NP = getNullPix(0); const ossim_float64 MAX_PIX = getMaxPix(0); const T STEP = static_cast( (MAX_PIX-NP) / (LINES-1) ); for(ossim_uint32 band = 0; band < BANDS; ++band) { T* s = (T*)getBuf(band); T p = (T)NP; for ( ossim_uint32 line = 0; line < LINES; ++line ) { for ( ossim_uint32 samp = 0; samp < SAMPS; ++samp ) { s[samp] = p; } p += STEP; s += SAMPS; } } validate(); } } // End: ossimImageData::createTestTile() template implementation. bool ossimImageData::isNull(ossim_uint32 offset)const { ossim_uint32 numberOfBands = getNumberOfBands(); ossim_uint32 band=0; if(!getBuf()) { return true; } switch(getScalarType()) { case OSSIM_UINT8: { for(band = 0; band < numberOfBands; ++band) { const ossim_uint8* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_uint8)getNullPix(band)) { return false; } } break; } case OSSIM_SINT8: { for(band = 0; band < numberOfBands; ++band) { const ossim_sint8* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_uint8)getNullPix(band)) { return false; } } break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { for(band = 0; band < numberOfBands; band++) { const ossim_uint16* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_uint16)getNullPix(band)) { return false; } } break; } case OSSIM_SINT16: { for(band = 0; band < numberOfBands; band++) { const ossim_sint16* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_sint16)getNullPix(band)) { return false; } } break; } case OSSIM_UINT32: { for(band = 0; band < numberOfBands; band++) { const ossim_uint32* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_uint32)getNullPix(band)) { return false; } } break; } case OSSIM_SINT32: { for(band = 0; band < numberOfBands; band++) { const ossim_sint32* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_sint32)getNullPix(band)) { return false; } } break; } case OSSIM_NORMALIZED_FLOAT: { for(band = 0; band < numberOfBands; band++) { const ossim_float32* buf = static_cast(getBuf(band))+offset; if((*buf) != 0.0) { return false; } } break; } case OSSIM_FLOAT32: { for(band = 0; band < numberOfBands; band++) { const ossim_float32* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_float32)getNullPix(band)) { return false; } } break; } case OSSIM_NORMALIZED_DOUBLE: { for(band = 0; band < numberOfBands; band++) { const ossim_float64* buf = static_cast(getBuf(band))+offset; if((*buf) != 0.0) { return false; } } break; } case OSSIM_FLOAT64: { for(band = 0; band < numberOfBands; band++) { const ossim_float64* buf = static_cast(getBuf(band))+offset; if((*buf) != getNullPix(band)) { return false; } } break; } case OSSIM_SCALAR_UNKNOWN: default: { //ERROR ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::isNull Unsupported scalar type!" << std::endl; } } return true; } bool ossimImageData::isNull(ossim_uint32 offset, ossim_uint32 band)const { switch(getScalarType()) { case OSSIM_UINT8: { const ossim_uint8* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_uint8)getNullPix(band)) { return false; } break; } case OSSIM_SINT8: { const ossim_sint8* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_sint8)getNullPix(band)) { return false; } break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { const ossim_uint16* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_uint16)getNullPix(band)) { return false; } break; } case OSSIM_SINT16: { const ossim_sint16* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_sint16)getNullPix(band)) { return false; } break; } case OSSIM_UINT32: { const ossim_uint32* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_uint32)getNullPix(band)) { return false; } break; } case OSSIM_SINT32: { const ossim_sint32* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_sint32)getNullPix(band)) { return false; } break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { const ossim_float32* buf = static_cast(getBuf(band))+offset; if((*buf) != (ossim_float32)getNullPix(band)) { return false; } break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { const ossim_float64* buf = static_cast(getBuf(band))+offset; if((*buf) != getNullPix(band)) { return false; } break; } case OSSIM_SCALAR_UNKNOWN: default: { //ERROR ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::isNull Unsupported scalar type!" << std::endl; } } return true; } bool ossimImageData::isNull(const ossimIpt& pt)const { ossim_int32 xNew = (pt.x - m_origin.x); ossim_int32 yNew = (pt.y - m_origin.y); if(xNew < 0 || xNew >= static_cast(m_spatialExtents[0]) || yNew < 0 || yNew >= static_cast(m_spatialExtents[1]) ) { return true; } ossim_uint32 offset = getWidth()*yNew + xNew; return isNull(offset); } bool ossimImageData::isNull(const ossimIpt& pt, ossim_uint32 band)const { ossim_int32 xNew = (pt.x - m_origin.x); ossim_int32 yNew = (pt.y - m_origin.y); if(xNew < 0 || xNew >= static_cast(m_spatialExtents[0]) || yNew < 0 || yNew >= static_cast(m_spatialExtents[1]) ) { return true; } ossim_uint32 offset = getWidth()*yNew + xNew; return isNull(offset, band); } void ossimImageData::setNull(ossim_uint32 offset) { ossim_uint32 numberOfBands = getNumberOfBands(); ossim_uint32 band=0; switch(getScalarType()) { case OSSIM_UINT8: { for(band = 0; band < numberOfBands; ++band) { ossim_uint8* buf = static_cast(getBuf(band))+offset; *buf = (ossim_uint8)getNullPix(band); } break; } case OSSIM_SINT8: { for(band = 0; band < numberOfBands; ++band) { ossim_sint8* buf = static_cast(getBuf(band))+offset; *buf = (ossim_sint8)getNullPix(band); } break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { for(band = 0; band < numberOfBands; band++) { ossim_uint16* buf = static_cast(getBuf(band))+ offset; *buf = (ossim_uint16)getNullPix(band); } break; } case OSSIM_SINT16: { for(band = 0; band < numberOfBands; band++) { ossim_sint16* buf = static_cast(getBuf(band))+ offset; *buf = (ossim_sint16)getNullPix(band); } break; } case OSSIM_UINT32: { for(band = 0; band < numberOfBands; band++) { ossim_uint32* buf = static_cast(getBuf(band))+ offset; *buf = (ossim_uint32)getNullPix(band); } break; } case OSSIM_SINT32: { for(band = 0; band < numberOfBands; band++) { ossim_sint32* buf = static_cast(getBuf(band))+ offset; *buf = (ossim_sint32)getNullPix(band); } break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { for(band = 0; band < numberOfBands; band++) { ossim_float32* buf = static_cast(getBuf(band))+offset; *buf = (ossim_float32)getNullPix(band); } break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { for(band = 0; band < numberOfBands; band++) { ossim_float64* buf = static_cast(getBuf(band))+offset; *buf = getNullPix(band); } break; } case OSSIM_SCALAR_UNKNOWN: default: { //ERROR ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::isNull Unsupported scalar type!" << std::endl; } } } void ossimImageData::setNull(ossim_uint32 offset, ossim_uint32 band) { switch(getScalarType()) { case OSSIM_UINT8: { ossim_uint8* buf = static_cast(getBuf(band))+offset; *buf = (ossim_uint8)getNullPix(band); break; } case OSSIM_SINT8: { ossim_sint8* buf = static_cast(getBuf(band))+offset; *buf = (ossim_sint8)getNullPix(band); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { ossim_uint16* buf = static_cast(getBuf(band))+offset; *buf = (ossim_uint16)getNullPix(band); break; } case OSSIM_SINT16: { ossim_sint16* buf = static_cast(getBuf(band))+offset; *buf = (ossim_sint16)getNullPix(band); break; } case OSSIM_UINT32: { ossim_uint32* buf = static_cast(getBuf(band))+offset; *buf = (ossim_uint32)getNullPix(band); break; } case OSSIM_SINT32: { ossim_sint32* buf = static_cast(getBuf(band))+offset; *buf = (ossim_sint32)getNullPix(band); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { ossim_float32* buf = static_cast(getBuf(band))+offset; *buf = (ossim_float32)getNullPix(band); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { ossim_float64* buf = static_cast(getBuf(band))+offset; *buf = getNullPix(band); break; } case OSSIM_SCALAR_UNKNOWN: default: { //ERROR ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::isNull Unsupported scalar type!" << std::endl; } } } void ossimImageData::setNull(const ossimIpt& pt) { ossim_int32 xNew = (pt.x - m_origin.x); ossim_int32 yNew = (pt.y - m_origin.y); if(xNew < 0 || xNew >= (int)m_spatialExtents[0] || yNew < 0 || yNew >= (int)m_spatialExtents[1]) { return; } ossim_uint32 offset = ((int)getWidth())*yNew + xNew; setNull(offset); } void ossimImageData::setNull(const ossimIpt& pt, ossim_uint32 band) { ossim_int32 xNew = (pt.x - m_origin.x); ossim_int32 yNew = (pt.y - m_origin.y); if(xNew < 0 || xNew >= (int)m_spatialExtents[0] || yNew < 0 || yNew >= (int)m_spatialExtents[1]) { return; } ossim_uint32 offset = ((int)getWidth())*yNew + xNew; setNull(offset, band); } void ossimImageData::setNullPix(ossim_float64 null_pix) { if(!m_numberOfDataComponents) { return; } m_nullPixelValue.resize(m_numberOfDataComponents); for(ossim_uint32 band = 0; band < m_numberOfDataComponents; ++band) { m_nullPixelValue[band] = null_pix; } } void ossimImageData::setNullPix(ossim_float64 null_pix, ossim_uint32 band) { if( !m_numberOfDataComponents || (band >= m_numberOfDataComponents) ) { return; } if (m_nullPixelValue.size() != m_numberOfDataComponents) { initializeNullDefault(); } m_nullPixelValue[band] = null_pix; } void ossimImageData::setNullPix(const ossim_float64* nullPixArray, ossim_uint32 numberOfValues) { if(!nullPixArray || !m_numberOfDataComponents) { return; } if (m_nullPixelValue.size() != m_numberOfDataComponents) { initializeNullDefault(); } for(ossim_uint32 band = 0; (band < numberOfValues) && (band < m_numberOfDataComponents); ++band) { m_nullPixelValue[band] = nullPixArray[band]; } } void ossimImageData::setMinPix(ossim_float64 min_pix) { if(!m_numberOfDataComponents) { return; } m_minPixelValue.resize(m_numberOfDataComponents); for(ossim_uint32 band = 0; band < m_minPixelValue.size(); ++band) { m_minPixelValue[band] = min_pix; } } void ossimImageData::setMinPix(ossim_float64 min_pix, ossim_uint32 band) { if( !m_numberOfDataComponents || (band >= m_numberOfDataComponents) ) { return; } if (m_minPixelValue.size() != m_numberOfDataComponents) { initializeMinDefault(); } m_minPixelValue[band] = min_pix; } void ossimImageData::setMinPix(const ossim_float64* minPixArray, ossim_uint32 numberOfValues) { if( !minPixArray || !m_numberOfDataComponents ) { return; } if (m_minPixelValue.size() != m_numberOfDataComponents) { initializeMinDefault(); } for(ossim_uint32 band = 0; (band < numberOfValues) && (band < m_numberOfDataComponents); ++band) { m_minPixelValue[band] = minPixArray[band]; } } void ossimImageData::setMaxPix(ossim_float64 max_pix) { if(!m_numberOfDataComponents) { return; } m_maxPixelValue.resize(m_numberOfDataComponents); for(ossim_uint32 band = 0; band < m_numberOfDataComponents; ++band) { m_maxPixelValue[band] = max_pix; } } void ossimImageData::setMaxPix(ossim_float64 max_pix, ossim_uint32 band) { if( !m_numberOfDataComponents || (band >= m_numberOfDataComponents) ) { return; } if (m_maxPixelValue.size() != m_numberOfDataComponents) { initializeMaxDefault(); } m_maxPixelValue[band] = max_pix; } void ossimImageData::setMaxPix(const ossim_float64* maxPixArray, ossim_uint32 /* numberOfValues */) { if(!maxPixArray || !m_numberOfDataComponents ) { return; } if (m_maxPixelValue.size() != m_numberOfDataComponents) { initializeMaxDefault(); } for(ossim_uint32 band = 0; (band < m_numberOfDataComponents) && (band < m_numberOfDataComponents); ++band) { m_maxPixelValue[band] = maxPixArray[band]; } } void ossimImageData::setNumberOfBands(ossim_uint32 bands, bool reallocate) { ossim_uint32 b = getNumberOfBands(); if(bands && (b != bands)) { setNumberOfDataComponents(bands); if(reallocate) { ossimRectilinearDataObject::initialize(); } ossim_uint32 minBands = ossim::min(b, bands); vector newNull(bands); vector newMin(bands); vector newMax(bands); ossim_uint32 i = 0; while (i < minBands) { newNull[i] = m_nullPixelValue[i]; newMin[i] = m_minPixelValue[i]; newMax[i] = m_maxPixelValue[i]; ++i; } if(b) { while (i < bands) { newNull[i] = m_nullPixelValue[b-1]; newMin[i] = m_minPixelValue[b-1]; newMax[i] = m_maxPixelValue[b-1]; ++i; } } m_nullPixelValue = newNull; m_minPixelValue = newMin; m_maxPixelValue = newMax; } } void ossimImageData::setImageRectangleAndBands(const ossimIrect& rect, ossim_uint32 numberOfBands) { if(rect.hasNans()) { return; } ossim_uint32 bands = getNumberOfBands(); ossim_uint32 w = getWidth(); ossim_uint32 h = getHeight(); ossim_uint32 nw = rect.width(); ossim_uint32 nh = rect.height(); setOrigin(rect.ul()); setWidthHeight(nw, nh); setNumberOfBands(numberOfBands, false); // we will try to be non destructive on the resize of the number of bands if( ( (w*h != nw*nh) || ( bands != numberOfBands) ) && (theDataObjectStatus != OSSIM_NULL) ) { initialize(); } } void ossimImageData::setImageRectangle(const ossimIrect& rect) { if(rect.hasNans()) { return; } ossim_uint32 w = getWidth(); ossim_uint32 h = getHeight(); ossim_uint32 nw = rect.width(); ossim_uint32 nh = rect.height(); setOrigin(rect.ul()); setWidthHeight(nw, nh); // we will try to be non destructive on the resize of the number of bands if ( (w*h != nw*nh) && (theDataObjectStatus != OSSIM_NULL) ) { initialize(); } } void ossimImageData::assign(const ossimDataObject* data) { if(data) { const ossimImageData* d = dynamic_cast(data); if(d) { assign(d); } } } void ossimImageData::assign(const ossimImageData* data) { ossimSource* tmp_owner = getOwner(); ossimRectilinearDataObject::assign(data); //*** // The data member "theSource" will be overwritten so capture it and then // set it back. //*** setOwner(tmp_owner); if(this != data) { ossim_uint32 numberOfBands = getNumberOfBands(); if(!numberOfBands) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::assign\n" << "Number of components is 0, can't assign" << std::endl; return; } m_origin = data->m_origin; m_minPixelValue = data->m_minPixelValue; m_maxPixelValue = data->m_maxPixelValue; m_nullPixelValue = data->m_nullPixelValue; if (m_minPixelValue.size() == 0 || m_maxPixelValue.size() == 0 || m_nullPixelValue.size() == 0) { initializeDefaults(); } ossim_uint32 source_size = data->getSizeInBytes(); const void* s = data->getBuf(); void* d = getBuf(); if (s && d) memcpy(d, s, source_size); } } void ossimImageData::assignBand(const ossimImageData* data, ossim_uint32 source_band, ossim_uint32 output_band) { //*** // This method requires this image data to be initialized to the same // size as the source data being copied. //*** // Some basic error checking... if ( !data->isValidBand(source_band) ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::assignBand ERROR:" << "\nInvalid source band!" << std::endl; return; } if ( !isValidBand(output_band) ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::assignBand ERROR:" << "\nInvalid output band!" << std::endl; return; } if (data->getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::assignBand ERROR:" << "\nSource data status is null!" << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::assignBand ERROR:" << "\nThis status is null!" << std::endl; return; } //*** // Make sure this buffer is the same size; if not, return. //*** ossim_uint32 source_size = data->getSizePerBandInBytes(); if ( source_size != getSizePerBandInBytes() ) { return; } // Get the pointers to the bands. const void* s = data->getBuf(source_band); void* d = getBuf(output_band); // One last check. if (s == 0 || d == 0) { return; } // Ok copy the image data... memcpy(d, s, source_size); } void ossimImageData::loadBand(const void* src, const ossimIrect& src_rect, ossim_uint32 band) { // Call the appropriate load method. switch (getScalarType()) { case OSSIM_UINT8: loadBandTemplate(ossim_uint8(0), src, src_rect, band); return; case OSSIM_SINT8: loadBandTemplate(ossim_sint8(0), src, src_rect, band); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: loadBandTemplate(ossim_uint16(0), src, src_rect, band); return; case OSSIM_SINT16: loadBandTemplate(ossim_sint16(0), src, src_rect, band); return; case OSSIM_UINT32: loadBandTemplate(ossim_uint32(0), src, src_rect, band); return; case OSSIM_SINT32: loadBandTemplate(ossim_sint32(0), src, src_rect, band); return; case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: loadBandTemplate(ossim_float32(0), src, src_rect, band); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: loadBandTemplate(ossim_float64(0), src, src_rect, band); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadBand\n\ File %s line %d\nUnknown scalar type!", __FILE__, __LINE__); return; } } void ossimImageData::loadBand(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, ossim_uint32 band) { // Call the appropriate load method. switch (getScalarType()) { case OSSIM_UINT8: loadBandTemplate(ossim_uint8(0), src, src_rect, clip_rect, band); return; case OSSIM_SINT8: loadBandTemplate(ossim_sint8(0), src, src_rect, clip_rect, band); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: loadBandTemplate(ossim_uint16(0), src, src_rect, clip_rect, band); return; case OSSIM_SINT16: loadBandTemplate(ossim_sint16(0), src, src_rect, clip_rect, band); return; case OSSIM_UINT32: loadBandTemplate(ossim_uint32(0), src, src_rect, clip_rect, band); return; case OSSIM_SINT32: loadBandTemplate(ossim_sint32(0), src, src_rect, clip_rect, band); return; case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: loadBandTemplate(ossim_float32(0), src, src_rect, clip_rect, band); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: loadBandTemplate(ossim_float64(0), src, src_rect, clip_rect, band); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadBand\n\ File %s line %d\nUnknown scalar type!", __FILE__, __LINE__); return; } } template void ossimImageData::loadBandTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, ossim_uint32 band) { const ossimIrect img_rect = getImageRectangle(); // Get the clip rect. const ossimIrect clip_rect = img_rect.clipToRect(src_rect); loadBandTemplate(T(0), src, src_rect, clip_rect, band); } template void ossimImageData::loadBandTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, ossim_uint32 band) { static const char MODULE[] = "ossimImageData::loadBand"; // Check the pointer. if (!src) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nNULL pointer passed to method!", MODULE, __FILE__, __LINE__); return; } // Check the band. if (!isValidBand(band)) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nInvalid band: %d", MODULE, __FILE__, __LINE__, band); return; } const ossimIrect img_rect = getImageRectangle(); // Check for intersect. if ( ! img_rect.intersects(src_rect) ) { return; // Nothing to do here. } // Check the clip rect. if (!clip_rect.completely_within(img_rect)) { return; } // Check the status and allocate memory if needed. if (getDataObjectStatus() == OSSIM_NULL) initialize(); // Get the width of the buffers. ossim_uint32 s_width = src_rect.width(); ossim_uint32 d_width = getWidth(); const T* s = static_cast(src); T* d = static_cast(getBuf(band)); // Move the pointers to the first valid pixel. s += (clip_rect.ul().y - src_rect.ul().y) * s_width + clip_rect.ul().x - src_rect.ul().x; d += (clip_rect.ul().y - img_rect.ul().y) * d_width + clip_rect.ul().x - img_rect.ul().x; // Copy the data. ossim_uint32 clipHeight = clip_rect.height(); ossim_uint32 clipWidth = clip_rect.width(); for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { d[sample] = s[sample]; } s += s_width; d += d_width; } } void ossimImageData::loadTile(const ossimImageData* src) { if (!src) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::loadTile ERROR:" << "Null tile passed to method!" << std::endl; return; } if (!src->getBuf()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::loadTile ERROR:" << "Source tile buff is null!" << std::endl; return; } if (!this->getBuf()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::loadTile ERROR:" << "This tile not initialized!" << std::endl; return; } if (src->getNumberOfBands() != this->getNumberOfBands()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::loadTile ERROR:" << "Tiles do not have same number of bands!" << std::endl; return; } //*** // Set the status of this tile to the status of the source tile. // Do this in place of validate. //*** setDataObjectStatus(src->getDataObjectStatus()); if(getScalarType() == src->getScalarType()) { loadTile((void*)(src->getBuf()), src->getImageRectangle(), OSSIM_BSQ); setNullPix(src->getNullPix(), src->getNumberOfBands()); } else // do a slow generic normalize to unnormalize copy { // Check the pointer. ossimIrect src_rect = src->getImageRectangle(); const ossimIrect img_rect = getImageRectangle(); // Check for intersect. if ( !img_rect.intersects(src_rect) ) { return; // Nothing to do here. } // Get the clip rect. const ossimIrect clip_rect = img_rect.clipToRect(src_rect); // Check the status and allocate memory if needed. if (getDataObjectStatus() == OSSIM_NULL) initialize(); // Get the width of the buffers. ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 s_width = src_rect.width(); ossim_uint32 d_width = getWidth(); ossim_uint32 band; ossim_uint32 sourceOffset = (clip_rect.ul().y - src_rect.ul().y) * s_width + (clip_rect.ul().x - src_rect.ul().x); ossim_uint32 destinationOffset = (clip_rect.ul().y - img_rect.ul().y) * d_width + (clip_rect.ul().x - img_rect.ul().x); ossim_uint32 clipHeight = clip_rect.height(); ossim_uint32 clipWidth = clip_rect.width(); // Copy the data. for (band=0; bandgetNormalizedFloat(sourceIndex + sample, band, tempResult); this->setNormalizedFloat(destinationIndex + sample, band, tempResult); } sourceIndex += s_width; destinationIndex += d_width; } } } } void ossimImageData::loadTile(const void* src, const ossimIrect& src_rect, ossimInterleaveType il_type) { switch (il_type) { case OSSIM_BIP: loadTileFromBip(src, src_rect); return; case OSSIM_BIL: loadTileFromBil(src, src_rect); return; case OSSIM_BSQ: loadTileFromBsq(src, src_rect); return; default: ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::loadTile ERROR: unsupported interleave type!" << std::endl; ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTile\n\ File %s line %d\nUnknown interleave type!", __FILE__, __LINE__); return; } // End of "switch (type)" } void ossimImageData::loadTileWithAlpha(const void* src, const ossimIrect& src_rect, ossimInterleaveType il_type) { switch (il_type) { case OSSIM_BIP: loadTileFromBipAlpha(src, src_rect); return; /* case OSSIM_BIL: loadTileFromBil(src, src_rect); return; case OSSIM_BSQ: loadTileFromBsq(src, src_rect); return; */ default: ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::loadTileWithAlpha ERROR: unsupported interleave type!" << std::endl; ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTile\n\ File %s line %d\nUnknown interleave type!", __FILE__, __LINE__); return; } // End of "switch (type)" } void ossimImageData::loadTile(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, ossimInterleaveType il_type) { switch (il_type) { case OSSIM_BIP: loadTileFromBip(src, src_rect, clip_rect); return; case OSSIM_BIL: loadTileFromBil(src, src_rect, clip_rect); return; case OSSIM_BSQ: loadTileFromBsq(src, src_rect, clip_rect); return; default: ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::loadTile ERROR: unsupported interleave type!" << std::endl; ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTile\n\ File %s line %d\nUnknown interleave type!", __FILE__, __LINE__); return; } // End of "switch (type)" } void ossimImageData::nullTileAlpha(const ossim_uint8* src, const ossimIrect& src_rect, bool multiplyAlphaFlag) { const ossimIrect img_rect = getImageRectangle(); // Get the clip rect. const ossimIrect clip_rect = img_rect.clipToRect(src_rect); nullTileAlpha(src, src_rect, clip_rect, multiplyAlphaFlag); } void ossimImageData::nullTileAlpha(const ossim_uint8* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, bool multiplyAlphaFlag) { switch (getScalarType()) { case OSSIM_UINT8: nullTileAlphaTemplate(ossim_uint8(0), src, src_rect, clip_rect, multiplyAlphaFlag); return; case OSSIM_SINT8: nullTileAlphaTemplate(ossim_sint8(0), src, src_rect, clip_rect, multiplyAlphaFlag); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: nullTileAlphaTemplate(ossim_uint16(0), src, src_rect, clip_rect, multiplyAlphaFlag); return; case OSSIM_SINT16: nullTileAlphaTemplate(ossim_sint16(0), src, src_rect, clip_rect, multiplyAlphaFlag); return; case OSSIM_UINT32: nullTileAlphaTemplate(ossim_uint32(0), src, src_rect, clip_rect, multiplyAlphaFlag); return; case OSSIM_SINT32: nullTileAlphaTemplate(ossim_sint32(0), src, src_rect, clip_rect, multiplyAlphaFlag); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: nullTileAlphaTemplate(ossim_float32(0), src, src_rect, clip_rect, multiplyAlphaFlag); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: nullTileAlphaTemplate(ossim_float64(0), src, src_rect, clip_rect, multiplyAlphaFlag); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::nullTileAlpha\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::loadTileFromBip(const void* src, const ossimIrect& src_rect) { switch (getScalarType()) { case OSSIM_UINT8: loadTileFromBipTemplate(ossim_uint8(0), src, src_rect); return; case OSSIM_SINT8: loadTileFromBipTemplate(ossim_sint8(0), src, src_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: loadTileFromBipTemplate(ossim_uint16(0), src, src_rect); return; case OSSIM_SINT16: loadTileFromBipTemplate(ossim_sint16(0), src, src_rect); return; case OSSIM_UINT32: loadTileFromBipTemplate(ossim_uint32(0), src, src_rect); return; case OSSIM_SINT32: loadTileFromBipTemplate(ossim_sint32(0), src, src_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: loadTileFromBipTemplate(ossim_float32(0), src, src_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: loadTileFromBipTemplate(ossim_float64(0), src, src_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTileFromBip\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::loadTileFromBipAlpha(const void* src, const ossimIrect& src_rect) { switch (getScalarType()) { case OSSIM_UINT8: loadTileFromBipAlphaTemplate(ossim_uint8(0), src, src_rect); return; case OSSIM_SINT8: loadTileFromBipAlphaTemplate(ossim_sint8(0), src, src_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: loadTileFromBipAlphaTemplate(ossim_uint16(0), src, src_rect); return; case OSSIM_SINT16: loadTileFromBipAlphaTemplate(ossim_sint16(0), src, src_rect); return; case OSSIM_UINT32: loadTileFromBipAlphaTemplate(ossim_uint32(0), src, src_rect); return; case OSSIM_SINT32: loadTileFromBipAlphaTemplate(ossim_sint32(0), src, src_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: loadTileFromBipAlphaTemplate(ossim_float32(0), src, src_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: loadTileFromBipAlphaTemplate(ossim_float64(0), src, src_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTileFromBip\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::loadTileFromBip(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect) { switch (getScalarType()) { case OSSIM_UINT8: loadTileFromBipTemplate(ossim_uint8(0), src, src_rect, clip_rect); return; case OSSIM_SINT8: loadTileFromBipTemplate(ossim_sint8(0), src, src_rect, clip_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: loadTileFromBipTemplate(ossim_uint16(0), src, src_rect, clip_rect); return; case OSSIM_SINT16: loadTileFromBipTemplate(ossim_sint16(0), src, src_rect, clip_rect); return; case OSSIM_UINT32: loadTileFromBipTemplate(ossim_uint32(0), src, src_rect, clip_rect); return; case OSSIM_SINT32: loadTileFromBipTemplate(ossim_sint32(0), src, src_rect, clip_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: loadTileFromBipTemplate(ossim_float32(0), src, src_rect, clip_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: loadTileFromBipTemplate(ossim_float64(0), src, src_rect, clip_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTileFromBip\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::loadTileFromBil(const void* src, const ossimIrect& src_rect) { switch (getScalarType()) { case OSSIM_UINT8: loadTileFromBilTemplate(ossim_uint8(0), src, src_rect); return; case OSSIM_SINT8: loadTileFromBilTemplate(ossim_sint8(0), src, src_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: loadTileFromBilTemplate(ossim_uint16(0), src, src_rect); return; case OSSIM_SINT16: loadTileFromBilTemplate(ossim_sint16(0), src, src_rect); return; case OSSIM_UINT32: loadTileFromBilTemplate(ossim_uint32(0), src, src_rect); return; case OSSIM_SINT32: loadTileFromBilTemplate(ossim_sint32(0), src, src_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: loadTileFromBilTemplate(ossim_float32(0), src, src_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: loadTileFromBilTemplate(ossim_float64(0), src, src_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTileFromBil\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::loadTileFromBil(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect) { switch (getScalarType()) { case OSSIM_UINT8: loadTileFromBilTemplate(ossim_uint8(0), src, src_rect, clip_rect); return; case OSSIM_SINT8: loadTileFromBilTemplate(ossim_sint8(0), src, src_rect, clip_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: loadTileFromBilTemplate(ossim_uint16(0), src, src_rect, clip_rect); return; case OSSIM_SINT16: loadTileFromBilTemplate(ossim_sint16(0), src, src_rect, clip_rect); return; case OSSIM_UINT32: loadTileFromBilTemplate(ossim_uint32(0), src, src_rect, clip_rect); return; case OSSIM_SINT32: loadTileFromBilTemplate(ossim_sint32(0), src, src_rect, clip_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: loadTileFromBilTemplate(ossim_float32(0), src, src_rect, clip_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: loadTileFromBilTemplate(ossim_float64(0), src, src_rect, clip_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTileFromBil\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::loadTileFromBsq(const void* src, const ossimIrect& src_rect) { switch (getScalarType()) { case OSSIM_UINT8: loadTileFromBsqTemplate(ossim_uint8(0), src, src_rect); return; case OSSIM_SINT8: loadTileFromBsqTemplate(ossim_sint8(0), src, src_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: loadTileFromBsqTemplate(ossim_uint16(0), src, src_rect); return; case OSSIM_SINT16: loadTileFromBsqTemplate(ossim_sint16(0), src, src_rect); return; case OSSIM_UINT32: loadTileFromBsqTemplate(ossim_uint32(0), src, src_rect); return; case OSSIM_SINT32: loadTileFromBsqTemplate(ossim_sint32(0), src, src_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: loadTileFromBsqTemplate(ossim_float32(0), src, src_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: loadTileFromBsqTemplate(ossim_float64(0), src, src_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTileFromBsq\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::loadTileFromBsq(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect) { switch (getScalarType()) { case OSSIM_UINT8: loadTileFromBsqTemplate(ossim_uint8(0), src, src_rect, clip_rect); return; case OSSIM_SINT8: loadTileFromBsqTemplate(ossim_sint8(0), src, src_rect, clip_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: loadTileFromBsqTemplate(ossim_uint16(0), src, src_rect, clip_rect); return; case OSSIM_SINT16: loadTileFromBsqTemplate(ossim_sint16(0), src, src_rect, clip_rect); return; case OSSIM_UINT32: loadTileFromBsqTemplate(ossim_uint32(0), src, src_rect, clip_rect); return; case OSSIM_SINT32: loadTileFromBsqTemplate(ossim_sint32(0), src, src_rect, clip_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: loadTileFromBsqTemplate(ossim_float32(0), src, src_rect, clip_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: loadTileFromBsqTemplate(ossim_float64(0), src, src_rect, clip_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTileFromBsq\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::loadTileFromBsqAlpha(const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect) { switch ( getScalarType() ) { case OSSIM_UINT8: { loadTileFromBsqAlphaTemplate(ossim_uint8(0), src, src_rect, clip_rect); return; } case OSSIM_SINT8: { loadTileFromBsqAlphaTemplate(ossim_sint8(0), src, src_rect, clip_rect); return; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { loadTileFromBsqAlphaTemplate(ossim_uint16(0), src, src_rect, clip_rect); return; } case OSSIM_SINT16: { loadTileFromBsqAlphaTemplate(ossim_sint16(0), src, src_rect, clip_rect); return; } case OSSIM_UINT32: { loadTileFromBsqAlphaTemplate(ossim_uint32(0), src, src_rect, clip_rect); return; } case OSSIM_SINT32: { loadTileFromBsqAlphaTemplate(ossim_sint32(0), src, src_rect, clip_rect); return; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { loadTileFromBsqAlphaTemplate(ossim_float32(0), src, src_rect, clip_rect); return; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { loadTileFromBsqAlphaTemplate(ossim_float64(0), src, src_rect, clip_rect); return; } case OSSIM_SCALAR_UNKNOWN: default: { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::loadTileFromBsqAlpha\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } } void ossimImageData::computeMinMaxPix(vector& minBands, vector& maxBands) const { if ( (getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_EMPTY) ) { return; } switch(m_scalarType) { case OSSIM_UINT8: { computeMinMaxPix((ossim_uint8)0, minBands, maxBands); break; } case OSSIM_SINT8: { computeMinMaxPix((ossim_sint8)0, minBands, maxBands); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { computeMinMaxPix((ossim_uint16)0, minBands, maxBands); break; } case OSSIM_SINT16: { computeMinMaxPix((ossim_sint16)0, minBands, maxBands); break; } case OSSIM_UINT32: { computeMinMaxPix((ossim_uint32)0, minBands, maxBands); break; } case OSSIM_SINT32: { computeMinMaxPix((ossim_sint32)0, minBands, maxBands); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { computeMinMaxPix((ossim_float32)0.0, minBands, maxBands); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { computeMinMaxPix((ossim_float64)0.0, minBands, maxBands); break; } case OSSIM_SCALAR_UNKNOWN: default: { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::computeMinPix Unsupported scalar type!" << std::endl; break; } } } template void ossimImageData::computeMinMaxPix(T /* dummyValue */, vector& minBands, vector& maxBands) const { const ossim_uint32 BANDS = getNumberOfBands(); const ossim_uint32 SPB = getSizePerBand(); if( minBands.size() != BANDS || maxBands.size() != BANDS ) { minBands.resize(BANDS); maxBands.resize(BANDS); for (ossim_uint32 band = 0; band < BANDS; ++band) { // Set min to max and max to min for starters. minBands[band] = getMaxPix(band); maxBands[band] = getMinPix(band); } } for(ossim_uint32 band = 0; band < BANDS; ++band) { const T* bandBuffer = (const T*)getBuf(band); if(bandBuffer) { const T NP = static_cast(getNullPix(band)); ossim_float64 currentMin = minBands[band]; ossim_float64 currentMax = maxBands[band]; for(ossim_uint32 offset = 0; offset < SPB; ++offset) { T p = bandBuffer[offset]; if(p != NP) { if(p < currentMin) { currentMin = p; } else if(p > currentMax) { currentMax = p; } } } minBands[band] = currentMin; maxBands[band] = currentMax; } } } void ossimImageData::computeMinMaxNulPix(vector& minBands, vector& maxBands, vector& nulBands) const { if ( getDataObjectStatus() == OSSIM_NULL ) { return; } switch(m_scalarType) { case OSSIM_UINT8: { computeMinMaxNulPix((ossim_uint8)0, minBands, maxBands, nulBands); break; } case OSSIM_SINT8: { computeMinMaxNulPix((ossim_sint8)0, minBands, maxBands, nulBands); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { computeMinMaxNulPix((ossim_uint16)0, minBands, maxBands, nulBands); break; } case OSSIM_SINT16: { computeMinMaxNulPix((ossim_sint16)0, minBands, maxBands, nulBands); break; } case OSSIM_UINT32: { computeMinMaxNulPix((ossim_uint32)0, minBands, maxBands, nulBands); break; } case OSSIM_SINT32: { computeMinMaxNulPix((ossim_sint32)0, minBands, maxBands, nulBands); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { computeMinMaxNulPix((ossim_float32)0.0, minBands, maxBands, nulBands); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { computeMinMaxNulPix((ossim_float64)0.0, minBands, maxBands, nulBands); break; } case OSSIM_SCALAR_UNKNOWN: default: { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::computeMinNulPix Unsupported scalar type!" << std::endl; break; } } } template void ossimImageData::computeMinMaxNulPix(T /* dummyValue */, vector& minBands, vector& maxBands, vector& nulBands) const { const ossim_uint32 BANDS = getNumberOfBands(); const ossim_uint32 SPB = getSizePerBand(); T DEFAULT_NULL = static_cast(ossim::defaultNull(getScalarType())); if( minBands.size() != BANDS || maxBands.size() != BANDS || nulBands.size() != BANDS ) { // First time through. minBands.resize(BANDS); maxBands.resize(BANDS); nulBands.resize(BANDS); for (ossim_uint32 band = 0; band < BANDS; ++band) { // Set min to max and max to min for starters. minBands[band] = getMaxPix(band); maxBands[band] = getMinPix(band); nulBands[band] = getMaxPix(band); } } for(ossim_uint32 band = 0; band < BANDS; ++band) { const T* bandBuffer = (const T*)getBuf(band); if(bandBuffer) { ossim_float64 currentMin = minBands[band]; ossim_float64 currentMax = maxBands[band]; ossim_float64 currentNul = nulBands[band]; for(ossim_uint32 offset = 0; offset < SPB; ++offset) { T p = bandBuffer[offset]; // Since we are scanning for nulls this is making an assumption that the default // null is incorrect and should be ignored in this scan as it could have been // introduced by a make blank on a partial tile so ignore it. // NOTE (OLK 03/2015): It is a bad idea to ignore pixels with default nulls, as it may // be the actual null value being used. By ignoring it, a new null will be latched // corresponding to actual, non-null, minimum value. Unfortunately, when tiles are // initialized, they are filled with default nulls since (with float-data), the // null (if any exists) is not yet known -- effectively creating two null pixel values. // The recommendation (if you're looking at this code, then you're probably having the // problem that your nulls aren't being recognized), is to turn off the flag in your // ossim prefs file with: overview_builder.scan_for_min_max_null_if_float: false // (or just delete that line) if ( p != DEFAULT_NULL ) { // Must do null first as min depends on null. if ( p < currentNul ) { currentNul = p; } if( ( p < currentMin ) && ( p > currentNul ) ) { currentMin = p; } else if( p > currentMax ) { currentMax = p; } } } minBands[band] = currentMin; maxBands[band] = currentMax; nulBands[band] = currentNul; } } } template void ossimImageData::loadTileFromBipTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect) { const ossimIrect img_rect = getImageRectangle(); // Get the clip rect. const ossimIrect clip_rect = img_rect.clipToRect(src_rect); loadTileFromBipTemplate(T(0), src, src_rect, clip_rect); } template void ossimImageData::loadTileFromBipAlphaTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect) { const ossimIrect img_rect = getImageRectangle(); // Get the clip rect. const ossimIrect clip_rect = img_rect.clipToRect(src_rect); loadTileFromBipAlphaTemplate(T(0), src, src_rect, clip_rect); } template void ossimImageData::loadTileFromBipTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect) { static const char MODULE[] = "ossimImageData::loadTileFromBip"; // Check the pointer. if (!src) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nNULL pointer passed to method!", MODULE, __FILE__, __LINE__); return; } const ossimIrect img_rect = getImageRectangle(); // Check for intersect. if ( ! img_rect.intersects(src_rect) ) { return; // Nothing to do here. } // Check the clip rect. if (!clip_rect.completely_within(img_rect)) { return; } // Check the status and allocate memory if needed. if (getDataObjectStatus() == OSSIM_NULL) initialize(); // Get the width of the buffers. ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 s_width = (src_rect.width()) * num_bands; ossim_uint32 d_width = getWidth(); ossim_uint32 band = 0; const T* s = static_cast(src); T** d = new T*[num_bands]; // Make destination pointers to each one. for (band=0; band(getBuf(band)); // Move the pointers to the first valid pixel. d[band] += (clip_rect.ul().y - img_rect.ul().y) * d_width + clip_rect.ul().x - img_rect.ul().x; } // Move the source pointer to the first valid pixel. s += (clip_rect.ul().y - src_rect.ul().y) * s_width + (clip_rect.ul().x - src_rect.ul().x) * num_bands; // Copy the data. ossim_uint32 clipHeight = clip_rect.height(); ossim_uint32 clipWidth = clip_rect.width(); for (ossim_uint32 line = 0; line < clipHeight; ++line) { ossim_uint32 j = 0; for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { for (band=0; band void ossimImageData::loadTileFromBipAlphaTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect) { static const char MODULE[] = "ossimImageData::loadTileFromBip"; // Check the pointer. if (!src) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nNULL pointer passed to method!", MODULE, __FILE__, __LINE__); return; } const ossimIrect img_rect = getImageRectangle(); // Check for intersect. if ( ! img_rect.intersects(src_rect) ) { return; // Nothing to do here. } // Check the clip rect. if (!clip_rect.completely_within(img_rect)) { return; } // Check the status and allocate memory if needed. if (getDataObjectStatus() == OSSIM_NULL) initialize(); // Get the width of the buffers. ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 s_width = (src_rect.width()) * (num_bands+1); ossim_uint32 d_width = getWidth(); ossim_uint32 band = 0; const T* s = static_cast(src); T** d = new T*[num_bands]; // Make destination pointers to each one. for (band=0; band(getBuf(band)); // Move the pointers to the first valid pixel. d[band] += (clip_rect.ul().y - img_rect.ul().y) * d_width + clip_rect.ul().x - img_rect.ul().x; } // Move the source pointer to the first valid pixel. s += (clip_rect.ul().y - src_rect.ul().y) * s_width + (clip_rect.ul().x - src_rect.ul().x) * (num_bands+1); // +1 for the alpha // Copy the data. ossim_uint32 clipHeight = clip_rect.height(); ossim_uint32 clipWidth = clip_rect.width(); for (ossim_uint32 line = 0; line < clipHeight; ++line) { ossim_uint32 j = 0; for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { for (band=0; band void ossimImageData::loadTileFromBilTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect) { const ossimIrect img_rect = getImageRectangle(); // Get the clip rect. const ossimIrect clip_rect = img_rect.clipToRect(src_rect); loadTileFromBilTemplate(T(0), src, src_rect, clip_rect); } template void ossimImageData::loadTileFromBilTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect) { static const char MODULE[] = "ossimImageData::loadTileFromBil"; // Check the pointer. if (!src) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nNULL pointer passed to method!", MODULE, __FILE__, __LINE__); return; } const ossimIrect img_rect = getImageRectangle(); // Check for intersect. if ( ! img_rect.intersects(src_rect) ) { return; // Nothing to do here. } // Check the clip rect. if (!clip_rect.completely_within(img_rect)) { return; } // Check the status and allocate memory if needed. if (getDataObjectStatus() == OSSIM_NULL) initialize(); // Get the width of the buffers. ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 s_width = (src_rect.lr().x - src_rect.ul().x + 1); ossim_uint32 d_width = getWidth(); ossim_uint32 band = 0; ossim_uint32 d_offset = (clip_rect.ul().y - img_rect.ul().y) * d_width + clip_rect.ul().x - img_rect.ul().x; const T* s = static_cast(src); // Get the number of bands and make destination pointers to each one. T** d = new T*[num_bands]; for (band=0; band(getBuf(band)); // Move the pointers to the first valid pixel. d[band] += d_offset; } // Move the source pointer to the first valid pixel. s += (clip_rect.ul().y - src_rect.ul().y) * s_width * num_bands + clip_rect.ul().x - src_rect.ul().x; // Copy the data. ossim_uint32 clipHeight = clip_rect.height(); ossim_uint32 clipWidth = clip_rect.width(); for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (band = 0; band < num_bands; ++band) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { d[band][sample] = s[sample]; } s += s_width; d[band] += d_width; } } delete [] d; } template void ossimImageData::loadTileFromBsqTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect) { const ossimIrect img_rect = getImageRectangle(); // Get the clip rect. const ossimIrect clip_rect = img_rect.clipToRect(src_rect); loadTileFromBsqTemplate(T(0), src, src_rect, clip_rect); } template void ossimImageData::loadTileFromBsqTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect) { static const char MODULE[] = "ossimImageData::loadTileFromBsq"; // Check the pointer. if (!src) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nNULL pointer passed to method!", MODULE, __FILE__, __LINE__); return; } const ossimIrect img_rect = getImageRectangle(); // Check for intersect. if ( ! img_rect.intersects(src_rect) ) { return; // Nothing to do here. } // Check the clip rect. if (!clip_rect.completely_within(img_rect)) { return; } // Check the status and allocate memory if needed. if (getDataObjectStatus() == OSSIM_NULL) initialize(); // Get the width of the buffers. ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 s_width = src_rect.width(); ossim_uint32 d_width = getWidth(); ossim_uint32 s_band_offset = s_width * src_rect.height(); const T* s = static_cast(src); ossim_uint32 band; ossim_uint32 destinationOffset = (clip_rect.ul().y - img_rect.ul().y) * d_width + (clip_rect.ul().x - img_rect.ul().x); ossim_uint32 destinationIndex = destinationOffset; ossim_uint32 sourceOffset = (clip_rect.ul().y - src_rect.ul().y) * s_width + (clip_rect.ul().x - src_rect.ul().x); ossim_uint32 sourceIndex = sourceOffset; ossim_uint32 clipHeight = clip_rect.height(); ossim_uint32 clipWidth = clip_rect.width(); // Copy the data. for (band=0; band(getBuf(band)); destinationIndex = destinationOffset; sourceIndex = sourceOffset + s_band_offset*band; for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { destinationBand[destinationIndex + sample] = s[sourceIndex+sample]; } sourceIndex += s_width; destinationIndex += d_width; } } } template void ossimImageData::loadTileFromBsqAlphaTemplate(T, // dummy template variable const void* src, const ossimIrect& src_rect, const ossimIrect& clip_rect) { static const char MODULE[] = "ossimImageData::loadTileFromBsqAlphaTemplate"; // Check the pointer. if (!src) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nNULL pointer passed to method!", MODULE, __FILE__, __LINE__); return; } const ossimIrect img_rect = getImageRectangle(); // Check for intersect. if ( ! img_rect.intersects(src_rect) ) { return; // Nothing to do here. } // Check the clip rect. if (!clip_rect.completely_within(img_rect)) { return; } // Check the status and allocate memory if needed. if (getDataObjectStatus() == OSSIM_NULL) initialize(); // Get the width of the buffers. ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 s_width = src_rect.width(); ossim_uint32 d_width = getWidth(); ossim_uint32 s_band_offset = s_width * src_rect.height(); const T* s = static_cast(src); // Pointer to the alpha band: const T* a = s + (s_band_offset*num_bands); ossim_uint32 band; ossim_uint32 destinationOffset = (clip_rect.ul().y - img_rect.ul().y) * d_width + (clip_rect.ul().x - img_rect.ul().x); ossim_uint32 destinationIndex = destinationOffset; ossim_uint32 sourceOffset = (clip_rect.ul().y - src_rect.ul().y) * s_width + (clip_rect.ul().x - src_rect.ul().x); ossim_uint32 sourceIndex = sourceOffset; ossim_uint32 clipHeight = clip_rect.height(); ossim_uint32 clipWidth = clip_rect.width(); // Copy the data. for (band=0; band(getBuf(band)); destinationIndex = destinationOffset; sourceIndex = sourceOffset + s_band_offset*band; ossim_uint32 alphaIndex = sourceOffset; for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { T pix = s[sourceIndex+sample]; destinationBand[destinationIndex + sample] = (a[alphaIndex+sample] >= AC) ? ( (pix > MP) ? pix : MP ) : NP; } sourceIndex += s_width; alphaIndex += s_width; destinationIndex += d_width; } } } void ossimImageData::loadTileFrom1Band(const void* src, const ossimIrect& src_rect) { ossim_uint32 bands = getNumberOfBands(); for(ossim_uint32 band = 0; band < bands; ++band) { loadBand(src, src_rect, band); } } void ossimImageData::loadTileFrom1Band(const ossimImageData* src) { if(!src) return; loadTileFrom1Band((const void*)src->getBuf(), src->getImageRectangle()); } void ossimImageData::loadShortBand(const void* src, const ossimIrect& src_rect, ossim_uint32 band, bool swap_bytes) { static const char MODULE[] = "ossimImageData::loadShortBand"; // Check the pointer. if (!src) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nNULL pointer passed to method!", MODULE, __FILE__, __LINE__); return; } // Check the band. if (!isValidBand(band)) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nInvalid band: %d", MODULE, __FILE__, __LINE__, band); return; } const ossimIrect img_rect = getImageRectangle(); // Check for intersect. if ( ! img_rect.intersects(src_rect) ) { return; // Nothing to do here. } // Get the clip rect. const ossimIrect clip_rect = img_rect.clipToRect(src_rect); // Check the status and allocate memory if needed. if (getDataObjectStatus() == OSSIM_NULL) initialize(); // Get the width of the buffers. ossim_uint32 s_width = src_rect.width(); ossim_uint32 d_width = getWidth(); const ossim_uint16* s = static_cast(src); ossim_uint16* d = getUshortBuf(band); // Move the pointers to the first valid pixel. s += (clip_rect.ul().y - src_rect.ul().y) * s_width + clip_rect.ul().x - src_rect.ul().x; d += (clip_rect.ul().y - img_rect.ul().y) * d_width + clip_rect.ul().x - img_rect.ul().x; // Copy the data. for (ossim_int32 line=clip_rect.ul().y; line<=clip_rect.lr().y; line++) { ossim_uint32 i = 0; for (ossim_int32 sample=clip_rect.ul().x; sample<=clip_rect.lr().x; sample++) { d[i] = (swap_bytes ? ( (s[i] << 8) | (s[i] >> 8) ) : s[i]); ++i; } s += s_width; d += d_width; } validate(); } bool ossimImageData::isPointWithin(const ossimIpt& point)const { return ((point.x >= m_origin.x)&& (point.y >= m_origin.y)&& ((point.x - m_origin.x)(m_spatialExtents[0]))&& ((point.y - m_origin.y)(m_spatialExtents[1]))); } bool ossimImageData::isPointWithin(ossim_int32 x, ossim_int32 y)const { return ((x >= m_origin.x)&& (y >= m_origin.y)&& ((x - m_origin.x) < static_cast(m_spatialExtents[0]))&& ((y - m_origin.y) < static_cast(m_spatialExtents[1]))); } void ossimImageData::unloadTile(void* dest, const ossimIrect& dest_rect, ossimInterleaveType type) const { unloadTile(dest, dest_rect, getImageRectangle(), type); } void ossimImageData::unloadTile(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect, ossimInterleaveType type) const { switch (type) { case OSSIM_BIP: unloadTileToBip(dest, dest_rect, clip_rect); return; case OSSIM_BIL: unloadTileToBil(dest, dest_rect, clip_rect); return; case OSSIM_BSQ: unloadTileToBsq(dest, dest_rect, clip_rect); return; default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::unloadTile\n\ File %s line %d\nUnknown scalar type!", __FILE__, __LINE__); return; } } void ossimImageData::unloadTileToBip(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const { switch (getScalarType()) { case OSSIM_UINT8: unloadTileToBipTemplate(ossim_uint8(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT8: unloadTileToBipTemplate(ossim_sint8(0), dest, dest_rect, clip_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: unloadTileToBipTemplate(ossim_uint16(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT16: unloadTileToBipTemplate(ossim_sint16(0), dest, dest_rect, clip_rect); return; case OSSIM_UINT32: unloadTileToBipTemplate(ossim_uint32(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT32: unloadTileToBipTemplate(ossim_sint32(0), dest, dest_rect, clip_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: unloadTileToBipTemplate(ossim_float32(0), dest, dest_rect, clip_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: unloadTileToBipTemplate(ossim_float64(0), dest, dest_rect, clip_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::unloadTileToBip\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::unloadTileToBipAlpha(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const { switch (getScalarType()) { case OSSIM_UINT8: unloadTileToBipAlphaTemplate(ossim_uint8(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT8: unloadTileToBipAlphaTemplate(ossim_sint8(0), dest, dest_rect, clip_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: unloadTileToBipAlphaTemplate(ossim_uint16(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT16: unloadTileToBipAlphaTemplate(ossim_sint16(0), dest, dest_rect, clip_rect); return; case OSSIM_UINT32: unloadTileToBipAlphaTemplate(ossim_uint32(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT32: unloadTileToBipAlphaTemplate(ossim_sint32(0), dest, dest_rect, clip_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: unloadTileToBipAlphaTemplate(ossim_float32(0), dest, dest_rect, clip_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: unloadTileToBipAlphaTemplate(ossim_float64(0), dest, dest_rect, clip_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::unloadTileToBipAlpha\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::unloadTileToBil(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const { switch (getScalarType()) { case OSSIM_UINT8: unloadTileToBilTemplate(ossim_uint8(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT8: unloadTileToBilTemplate(ossim_sint8(0), dest, dest_rect, clip_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: unloadTileToBilTemplate(ossim_uint16(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT16: unloadTileToBilTemplate(ossim_sint16(0), dest, dest_rect, clip_rect); return; case OSSIM_UINT32: unloadTileToBilTemplate(ossim_uint32(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT32: unloadTileToBilTemplate(ossim_sint32(0), dest, dest_rect, clip_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: unloadTileToBilTemplate(ossim_float32(0), dest, dest_rect, clip_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: unloadTileToBilTemplate(ossim_float64(0), dest, dest_rect, clip_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::unloadTileToBil\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::unloadTileToBsq(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const { switch (getScalarType()) { case OSSIM_UINT8: unloadTileToBsqTemplate(ossim_uint8(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT8: unloadTileToBsqTemplate(ossim_sint8(0), dest, dest_rect, clip_rect); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: unloadTileToBsqTemplate(ossim_uint16(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT16: unloadTileToBsqTemplate(ossim_sint16(0), dest, dest_rect, clip_rect); return; case OSSIM_UINT32: unloadTileToBsqTemplate(ossim_uint32(0), dest, dest_rect, clip_rect); return; case OSSIM_SINT32: unloadTileToBsqTemplate(ossim_sint32(0), dest, dest_rect, clip_rect); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: unloadTileToBsqTemplate(ossim_float32(0), dest, dest_rect, clip_rect); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: unloadTileToBsqTemplate(ossim_float64(0), dest, dest_rect, clip_rect); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::unloadTileToBsq\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::unloadBand(void* dest, const ossimIrect& dest_rect, ossim_uint32 band) const { unloadBand(dest, dest_rect, getImageRectangle(), band); } void ossimImageData::unloadBand(void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect, ossim_uint32 band) const { // Call the appropriate load method. switch (getScalarType()) { case OSSIM_UINT8: unloadBandTemplate(ossim_uint8(0), dest, dest_rect, clip_rect, band); return; case OSSIM_SINT8: unloadBandTemplate(ossim_sint8(0), dest, dest_rect, clip_rect, band); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: unloadBandTemplate(ossim_uint16(0), dest, dest_rect, clip_rect, band); return; case OSSIM_SINT16: unloadBandTemplate(ossim_sint16(0), dest, dest_rect, clip_rect, band); return; case OSSIM_UINT32: unloadBandTemplate(ossim_uint32(0), dest, dest_rect, clip_rect, band); return; case OSSIM_SINT32: unloadBandTemplate(ossim_sint32(0), dest, dest_rect, clip_rect, band); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: unloadBandTemplate(ossim_float32(0), dest, dest_rect, clip_rect, band); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: unloadBandTemplate(ossim_float64(0), dest, dest_rect, clip_rect, band); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::unloadBand\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } void ossimImageData::unloadBand( void* dest, ossim_uint32 src_band, ossim_uint32 dest_band, const ossimIrect& dest_rect, ossimInterleaveType il_type, OverwriteBandRule ow_type ) const { unloadBand( dest, src_band, dest_band, dest_rect, getImageRectangle(), il_type, ow_type ); } void ossimImageData::unloadBand( void* dest, ossim_uint32 src_band, ossim_uint32 dest_band, const ossimIrect& dest_rect, const ossimIrect& clip_rect, ossimInterleaveType il_type, OverwriteBandRule ow_type ) const { static const char MODULE[] = "ossimImageData::unloadBand"; if ( il_type == OSSIM_BSQ ) { unloadBandToBsq( dest, src_band, dest_band, dest_rect, clip_rect, ow_type ); } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " NOTICE:" << "\nUnsupported interleave type: " << il_type << " Returning..." << std::endl; } } void ossimImageData::unloadBandToBsq( void* dest, ossim_uint32 src_band, ossim_uint32 dest_band, const ossimIrect& dest_rect, const ossimIrect& clip_rect, OverwriteBandRule ow_type ) const { switch (getScalarType()) { case OSSIM_UINT8: unloadBandToBsqTemplate(ossim_uint8(0), dest, src_band, dest_band, dest_rect, clip_rect, ow_type ); return; case OSSIM_SINT8: unloadBandToBsqTemplate(ossim_sint8(0), dest, src_band, dest_band, dest_rect, clip_rect, ow_type ); return; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: unloadBandToBsqTemplate(ossim_uint16(0), dest, src_band, dest_band, dest_rect, clip_rect, ow_type ); return; case OSSIM_SINT16: unloadBandToBsqTemplate(ossim_sint16(0), dest, src_band, dest_band, dest_rect, clip_rect, ow_type ); return; case OSSIM_UINT32: unloadBandToBsqTemplate(ossim_uint32(0), dest, src_band, dest_band, dest_rect, clip_rect, ow_type ); return; case OSSIM_SINT32: unloadBandToBsqTemplate(ossim_sint32(0), dest, src_band, dest_band, dest_rect, clip_rect, ow_type ); return; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: unloadBandToBsqTemplate(ossim_float32(0), dest, src_band, dest_band, dest_rect, clip_rect, ow_type ); return; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: unloadBandToBsqTemplate(ossim_float64(0), dest, src_band, dest_band, dest_rect, clip_rect, ow_type ); return; case OSSIM_SCALAR_UNKNOWN: default: ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::unloadBandToBsq\n\ File %s line %d\nUnsupported scalar type for method!", __FILE__, __LINE__); return; } } template void ossimImageData::unloadBandTemplate(T, // dummy template variable void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect, ossim_uint32 band) const { static const char MODULE[] = "ossimImageData::unloadBand"; // Check the pointers. if (!dest) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nNULL pointer passed to method! Returning..." << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nThis object is null! Returning..." << std::endl; return; } ossimIrect img_rect = getImageRectangle(); // Clip the clip_rect to the tile rect. ossimIrect output_clip_rect = clip_rect.clipToRect(img_rect); // Clip it again to the destination rect. output_clip_rect = dest_rect.clipToRect(output_clip_rect); // Check the output clip rect for intersection. if (!output_clip_rect.intersects(img_rect)) { return; } if ( !(output_clip_rect.intersects(dest_rect)) ) { return; } // Check for valid band. if (!isValidBand(band)) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " NOTICE:" << "\nInvalid band: " << band << " Returning..." << std::endl; return; } ossim_uint32 buf_width = dest_rect.lr().x - dest_rect.ul().x + 1; // Get a pointer to the source band buffer. const T* s = reinterpret_cast(getBuf(band)); // Get the offset for each source band. ossim_uint32 src_offset = (output_clip_rect.ul().y - img_rect.ul().y) * getWidth() + output_clip_rect.ul().x - img_rect.ul().x; // Move the pointers to the start. T* d = reinterpret_cast(dest); ossim_uint32 dest_offset = (output_clip_rect.ul().y - dest_rect.ul().y) * buf_width + output_clip_rect.ul().x - dest_rect.ul().x; d += dest_offset; s += src_offset; for (ossim_int32 line=output_clip_rect.ul().y; line<=output_clip_rect.lr().y; ++line) { ossim_uint32 i=0; for (ossim_int32 samp=clip_rect.ul().x; samp<=output_clip_rect.lr().x; ++samp) { d[i] = s[i]; ++i; } d += buf_width; s += getWidth(); } } template void ossimImageData::unloadTileToBipTemplate(T, // dummy template variable void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const { static const char MODULE[] = "ossimImageData::unloadTileToBip"; // Check the pointer. if (!dest) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nNULL pointer passed to method! Returning..." << std::endl; return; } bool dataIsNull = false; if (getDataObjectStatus() == OSSIM_NULL) { dataIsNull = true; } ossimIrect img_rect = getImageRectangle(); // Clip the clip_rect to the tile rect. ossimIrect output_clip_rect = clip_rect.clipToRect(img_rect); // Clip it again to the destination rect. output_clip_rect = dest_rect.clipToRect(output_clip_rect); // Check the output clip rect for intersection. if (output_clip_rect.hasNans()) { return; } if ( !(output_clip_rect.intersects(dest_rect)) ) { return; } ossim_int32 num_bands = getNumberOfBands(); ossim_int32 buf_width = dest_rect.width() * num_bands; if(!dataIsNull) { // Get the number of bands and grab a pointers to each one. const T** s = new const T*[num_bands]; ossim_int32 band; ossim_int32 s_width = getWidth(); for (band=0; band(getBuf(band)); } // Move the pointers to the start. T* d = reinterpret_cast(dest); d += (output_clip_rect.ul().y - dest_rect.ul().y) * buf_width + (output_clip_rect.ul().x - dest_rect.ul().x) * num_bands; // Get the offset for each source band. ossim_int32 src_offset = (output_clip_rect.ul().y - img_rect.ul().y) * s_width + (output_clip_rect.ul().x - img_rect.ul().x); ossim_int32 output_clip_width = output_clip_rect.width(); ossim_int32 output_clip_height = output_clip_rect.height(); for (band=0; band<(ossim_int32)getNumberOfBands(); band++) { s[band] += src_offset; } ossim_int32 j; for (ossim_int32 line=0; line(m_nullPixelValue[band]); } // Move the pointers to the start. T* d = reinterpret_cast(dest); d += (output_clip_rect.ul().y - dest_rect.ul().y) * buf_width + (output_clip_rect.ul().x - dest_rect.ul().x) * num_bands; for (ossim_int32 line=output_clip_rect.ul().y; line<=output_clip_rect.lr().y; ++line) { ossim_int32 i=0; ossim_int32 j=0; for (ossim_int32 samp=output_clip_rect.ul().x; samp<=output_clip_rect.lr().x; ++samp) { for (band=0; band void ossimImageData::unloadTileToBipAlphaTemplate(T, // dummy template variable void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const { static const char M[] = "ossimImageData::unloadTileToBipAlphaTemplate"; // Sanity checks: // Are we null: if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << M << " ERROR:" << "\nAttempting to copy null tile! Returning..." << std::endl; return; } // Check the pointer. if (!dest) { ossimNotify(ossimNotifyLevel_WARN) << M << " ERROR:" << "\nNULL pointer passed to method! Returning..." << std::endl; return; } if ( !hasAlpha() ) { ossimNotify(ossimNotifyLevel_WARN) << M << " ERROR:" << "\nTile has no alpha! Returning..." << std::endl; return; } ossimIrect img_rect = getImageRectangle(); // Clip the clip_rect to the tile rect. ossimIrect output_clip_rect = clip_rect.clipToRect(img_rect); // Clip it again to the destination rect. output_clip_rect = dest_rect.clipToRect(output_clip_rect); // Check the output clip rect for intersection. if (output_clip_rect.hasNans()) { return; } if ( !(output_clip_rect.intersects(dest_rect)) ) { return; } const ossim_int32 NUM_DATA_BANDS = getNumberOfBands(); const ossim_int32 BANDS = NUM_DATA_BANDS + 1; // Has data plus alpha. const ossim_float64 MAX_PIX = static_cast(getMaxPix(0)); const ossim_float64 ALPHA_MAX_PIX = 255.00; const ossim_int32 S_WIDTH = getWidth(); const ossim_int32 D_WIDTH = dest_rect.width() * BANDS; const ossim_int32 OUTPUT_CLIP_WIDTH = output_clip_rect.width(); const ossim_int32 OUTPUT_CLIP_HEIGHT = output_clip_rect.height(); bool uint8Flag = ( getScalarType() == OSSIM_UINT8 ); // Get the offset for each source band relative to start of clip rect. const ossim_int32 SRC_OFFSET = (output_clip_rect.ul().y - img_rect.ul().y) * S_WIDTH + (output_clip_rect.ul().x - img_rect.ul().x); // Get pointers to each one band of image data. std::vector s(NUM_DATA_BANDS); ossim_int32 band; for (band = 0; band < NUM_DATA_BANDS; ++band) { s[band] = reinterpret_cast(getBuf(band)); // Move to start of clip rect. s[band] += SRC_OFFSET; } // Get pointer to the alpha channel: const ossim_uint8* a = getAlphaBuf(); // Move to start of clip rect. a += SRC_OFFSET; // Pointer to the destination buffer. T* d = reinterpret_cast(dest); // Move to start of clip rect. d += (output_clip_rect.ul().y - dest_rect.ul().y) * D_WIDTH + (output_clip_rect.ul().x - dest_rect.ul().x) * BANDS; // Loop to copy data: for (ossim_int32 line = 0; line < OUTPUT_CLIP_HEIGHT; ++line) { ossim_int32 j = 0; ossim_int32 alphaIdx = 0; for (ossim_int32 samp = 0; samp < OUTPUT_CLIP_WIDTH; ++samp, j +=BANDS) { // Copy the pixels: for (band = 0; band < NUM_DATA_BANDS; ++band) { d[j+band] = s[band][samp]; } // Copy alpha channel converting to scalar type. if ( uint8Flag ) { d[j+NUM_DATA_BANDS] = a[alphaIdx++]; } else { d[j+NUM_DATA_BANDS] = static_cast( (a[alphaIdx++]/ALPHA_MAX_PIX) * MAX_PIX ); } } // Increment pointers to next line... d += D_WIDTH; for (band = 0; band < NUM_DATA_BANDS; ++band) { s[band] += S_WIDTH; } a += S_WIDTH; } } template void ossimImageData::unloadTileToBilTemplate(T, // dummy template arg... void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const { static const char MODULE[] = "ossimImageData::unloadTileToBil"; // Check the pointers. if (!dest) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nNULL pointer passed to method! Returning..." << std::endl; return; } bool dataIsNull = false; if (getDataObjectStatus() == OSSIM_NULL) { dataIsNull = true; } ossimIrect img_rect = getImageRectangle(); // Clip the clip_rect to the tile rect. ossimIrect output_clip_rect = clip_rect.clipToRect(img_rect); // Clip it again to the destination rect. output_clip_rect = dest_rect.clipToRect(output_clip_rect); // Check the output clip rect for intersection. if (output_clip_rect.hasNans()) { return; } if ( !(output_clip_rect.intersects(dest_rect)) ) { return; } ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 buf_width = dest_rect.width(); if(!dataIsNull) { // Get the number of bands and grab a pointers to each one. const T** s = new const T*[num_bands]; ossim_uint32 band; for (band=0; band(getBuf(band)); } // Get the offset for each source band. ossim_uint32 src_offset = (output_clip_rect.ul().y - img_rect.ul().y) * getWidth() + (output_clip_rect.ul().x - img_rect.ul().x); // Move the pointers to the start. T* d = reinterpret_cast(dest); d += (output_clip_rect.ul().y - dest_rect.ul().y) * buf_width * num_bands + (output_clip_rect.ul().x-dest_rect.ul().x); for (band=0; band(m_nullPixelValue[band]); } // Move the pointers to the start. T* d = reinterpret_cast(dest); d += (output_clip_rect.ul().y - dest_rect.ul().y) * buf_width * num_bands + (output_clip_rect.ul().x - dest_rect.ul().x); for (ossim_int32 line=output_clip_rect.ul().y; line<=output_clip_rect.lr().y; ++line) { for (band=0; band void ossimImageData::nullTileAlphaTemplate( T, const ossim_uint8* src, const ossimIrect& src_rect, const ossimIrect& clip_rect, bool multiplyAlphaFlag) { static const char MODULE[] = "ossimImageData::nullTileAlphaTemplate"; // Check the pointer. if (!src) { // Set the error... ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "%s File %s line %d\nNULL pointer passed to method!", MODULE, __FILE__, __LINE__); return; } const ossimIrect img_rect = getImageRectangle(); // Check for intersect. if ( ! img_rect.intersects(src_rect) ) { return; // Nothing to do here. } // Check the clip rect. if (!clip_rect.completely_within(img_rect)) { return; } // Check the status and allocate memory if needed. if (getDataObjectStatus() == OSSIM_NULL) initialize(); // Get the width of the buffers. ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 s_width = src_rect.width(); ossim_uint32 d_width = getWidth(); ossim_uint32 band; ossim_uint32 destinationOffset = (clip_rect.ul().y - img_rect.ul().y) * d_width + (clip_rect.ul().x - img_rect.ul().x); ossim_uint32 destinationIndex = destinationOffset; ossim_uint32 sourceOffset = (clip_rect.ul().y - src_rect.ul().y) * s_width + (clip_rect.ul().x - src_rect.ul().x); ossim_uint32 sourceIndex = sourceOffset; ossim_uint32 clipHeight = clip_rect.height(); ossim_uint32 clipWidth = clip_rect.width(); if(!multiplyAlphaFlag) { // Copy the data. for (band=0; band(getBuf(band)); destinationIndex = destinationOffset; sourceIndex = sourceOffset; T nullPix = (T)getNullPix(band); T minPix = (T)getMinPix(band); for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { if(src[sourceIndex+sample] == 0) { destinationBand[destinationIndex + sample] = nullPix; } else if(destinationBand[destinationIndex + sample] == nullPix) { destinationBand[destinationIndex + sample] = minPix; } } sourceIndex += s_width; destinationIndex += d_width; } } } else { ossim_float64 normalizer = 1.0/255.0; // Copy the data. for (band=0; band(getBuf(band)); destinationIndex = destinationOffset; sourceIndex = sourceOffset; T nullPix = (T)getNullPix(band); T minPix = (T)getMinPix(band); for (ossim_uint32 line = 0; line < clipHeight; ++line) { for (ossim_uint32 sample = 0; sample < clipWidth; ++sample) { if(src[sourceIndex+sample] != 255) { if(src[sourceIndex+sample] != 0) { destinationBand[destinationIndex + sample] = (T)(destinationBand[destinationIndex + sample]* (src[sourceIndex+sample]*normalizer)); if(destinationBand[destinationIndex + sample] == nullPix) { destinationBand[destinationIndex + sample] = minPix; } } else { destinationBand[destinationIndex + sample] = nullPix; } } else if(destinationBand[destinationIndex + sample] == nullPix) { destinationBand[destinationIndex + sample] = minPix; } } sourceIndex += s_width; destinationIndex += d_width; } } } } template void ossimImageData::unloadTileToBsqTemplate(T, // dummy template arg... void* dest, const ossimIrect& dest_rect, const ossimIrect& clip_rect) const { static const char MODULE[] = "ossimImageData::unloadTileToBsq"; // Check the pointers. if (!dest) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nNULL pointer passed to method! Returning..." << std::endl; return; } bool dataIsNull = false; if (getDataObjectStatus() == OSSIM_NULL) { dataIsNull = true; } ossimIrect img_rect = getImageRectangle(); // Clip the clip_rect to the tile rect. ossimIrect output_clip_rect = clip_rect.clipToRect(img_rect); // Clip it again to the destination rect. output_clip_rect = dest_rect.clipToRect(output_clip_rect); // Check the output clip rect for intersection. if (output_clip_rect.hasNans()) { return; } if ( !(output_clip_rect.intersects(dest_rect)) ) { return; } ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 band = 0; if(!dataIsNull) { ossim_uint32 d_width = dest_rect.lr().x - dest_rect.ul().x + 1; ossim_uint32 d_band_offset = d_width * (dest_rect.lr().y-dest_rect.ul().y+1); ossim_uint32 s_width = getWidth(); ossim_uint32 s_offset = (output_clip_rect.ul().y - img_rect.ul().y) * s_width + (output_clip_rect.ul().x - img_rect.ul().x); T* d = static_cast(dest); const T** s = new const T*[num_bands]; // Grab a pointers to each one. for (band=0; band(getBuf(band)); // Move to first valid pixel. s[band] += s_offset; } // Move to first valid pixel. d += (output_clip_rect.ul().y - dest_rect.ul().y) * d_width + (output_clip_rect.ul().x - dest_rect.ul().x); for (band=0; band(dest); // Move to first valid pixel. d += (output_clip_rect.ul().y - dest_rect.ul().y) * d_width + (output_clip_rect.ul().x - dest_rect.ul().x); for (band=0; band(m_nullPixelValue[band]); ossim_uint32 d_buf_offset = 0; for (ossim_int32 line=output_clip_rect.ul().y; line<=output_clip_rect.lr().y; ++line) { ossim_int32 i=0; for (ossim_int32 samp=output_clip_rect.ul().x; samp<=output_clip_rect.lr().x; ++samp) { d[d_buf_offset+i] = np; ++i; } d_buf_offset += d_width; } d += d_band_offset; } } } template void ossimImageData::unloadBandToBsqTemplate(T, // dummy template arg... void* dest, ossim_uint32 src_band, ossim_uint32 dest_band, const ossimIrect& dest_rect, const ossimIrect& clip_rect, OverwriteBandRule ow_type) const { static const char MODULE[] = "ossimImageData::unloadBandToBsq"; // Check the pointers. if (!dest) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nNULL pointer passed to method! Returning..." << std::endl; return; } bool dataIsNull = false; if (getDataObjectStatus() == OSSIM_NULL) { dataIsNull = true; } ossimIrect img_rect = getImageRectangle(); // Clip the clip_rect to the tile rect. ossimIrect output_clip_rect = clip_rect.clipToRect(img_rect); // Clip it again to the destination rect. output_clip_rect = dest_rect.clipToRect(output_clip_rect); // Check the output clip rect for intersection. if (output_clip_rect.hasNans()) { return; } if ( !(output_clip_rect.intersects(dest_rect)) ) { return; } ossim_uint32 num_bands = getNumberOfBands(); ossim_uint32 band = 0; if(!dataIsNull) { ossim_uint32 d_width = dest_rect.lr().x - dest_rect.ul().x + 1; ossim_uint32 d_band_offset = d_width * (dest_rect.lr().y-dest_rect.ul().y+1); ossim_uint32 s_width = getWidth(); ossim_uint32 s_offset = (output_clip_rect.ul().y - img_rect.ul().y) * s_width + (output_clip_rect.ul().x - img_rect.ul().x); T* d = static_cast(dest); const T** s = new const T*[num_bands]; // Grab a pointers to each one. for (band=0; band(getBuf(band)); // Move to first valid pixel. s[band] += s_offset; } // Move to first valid pixel. d += (output_clip_rect.ul().y - dest_rect.ul().y) * d_width + (output_clip_rect.ul().x - dest_rect.ul().x); ossim_uint32 d_dest_band_offset = dest_band * d_band_offset; ossim_uint32 d_buf_offset = 0; for (ossim_int32 line=output_clip_rect.ul().y; line<=output_clip_rect.lr().y; ++line) { ossim_int32 i=0; for (ossim_int32 samp=output_clip_rect.ul().x; samp<=output_clip_rect.lr().x; ++samp) { ossim_uint32 d_pixel_offset = d_buf_offset+i; ossim_uint32 d_dest_band_pixel_offset = d_pixel_offset + d_dest_band_offset; switch( ow_type ) { case COLOR_DISCREPANCY: case COLOR_DISCREPANCY_OF_ANY_FROM_DEST: { T d_dest_band = d[d_dest_band_pixel_offset]; for ( band=0; band(dest); // Move to first valid pixel. d += (output_clip_rect.ul().y - dest_rect.ul().y) * d_width + (output_clip_rect.ul().x - dest_rect.ul().x); for (band=0; band(m_nullPixelValue[band]); ossim_uint32 d_buf_offset = 0; for (ossim_int32 line=output_clip_rect.ul().y; line<=output_clip_rect.lr().y; ++line) { ossim_int32 i=0; for (ossim_int32 samp=output_clip_rect.ul().x; samp<=output_clip_rect.lr().x; ++samp) { d[d_buf_offset+i] = np; ++i; } d_buf_offset += d_width; } d += d_band_offset; } } } ossimObject* ossimImageData::dup() const { return new ossimImageData(*this); } void ossimImageData::copyTileToNormalizedBuffer(ossim_float64* buf)const { if (!buf) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileToNormalizedBuffer ERROR:" << "\nNull buffer passed to method! Returning..." << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileToNormalizedBuffer ERROR:" << "\nThis object is null! Returning..." << std::endl; return; } switch(getScalarType()) { case OSSIM_NORMALIZED_DOUBLE: { memmove(buf, getBuf(), getDataSizeInBytes()); break; } case OSSIM_NORMALIZED_FLOAT: { ossim_uint32 upperBound = getWidth()*getHeight()*getNumberOfBands(); const ossim_float32* inputBuf = static_cast(getBuf()); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { buf[offset] = inputBuf[offset]; } break; } case OSSIM_FLOAT32: { copyTileToNormalizedBuffer((ossim_float32)0, buf); break; } case OSSIM_FLOAT64: { copyTileToNormalizedBuffer((ossim_float64)0, buf); break; } case OSSIM_UINT8: { copyTileToNormalizedBuffer((ossim_uint8)0, buf); break; } case OSSIM_SINT8: { copyTileToNormalizedBuffer((ossim_sint8)0, buf); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { copyTileToNormalizedBuffer((ossim_uint16)0, buf); break; } case OSSIM_SINT16: { copyTileToNormalizedBuffer((ossim_sint16)0, buf); break; } case OSSIM_UINT32: { copyTileToNormalizedBuffer((ossim_uint32)0, buf); break; } case OSSIM_SINT32: { copyTileToNormalizedBuffer((ossim_sint32)0, buf); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "NOTICE: copyTileToNormalizedBuffer not implemented yet" << std::endl; } } // End of "switch(getScalarType())" } template void ossimImageData::copyTileToNormalizedBuffer(T /* dummyTemplate */, ossim_float64* buf) const { const ossim_uint32 SIZE = getSizePerBand(); const ossim_uint32 BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < BANDS; ++band) { const ossim_float64 MIN_PIX = getMinPix(band); const ossim_float64 MAX_PIX = getMaxPix(band); const ossim_float64 RANGE = (MAX_PIX-MIN_PIX); const ossim_float64 NP = getNullPix(band); const T* s = (T*)getBuf(band); // source ossim_float64* d = (ossim_float64*)(buf + (band*SIZE)); // destination for(ossim_uint32 offset = 0; offset < SIZE; ++offset) { ossim_float64 p = s[offset]; if(p != NP) { if( p == MIN_PIX) { d[offset] = OSSIM_DEFAULT_MIN_PIX_NORM_DOUBLE; } else { d[offset] = (p-MIN_PIX)/RANGE; } } else { d[offset] = 0.0; } } } } template void ossimImageData::copyTileToNormalizedBuffer(T /* dummyTemplate */, ossim_float32* buf) const { const ossim_uint32 SIZE = getSizePerBand(); const ossim_uint32 BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < BANDS; ++band) { const ossim_float64 MIN_PIX = getMinPix(band); const ossim_float64 MAX_PIX = getMaxPix(band); const ossim_float64 RANGE = (MAX_PIX-MIN_PIX); const ossim_float64 NP = getNullPix(band); const T* s = (T*)getBuf(band); // source ossim_float32* d = (ossim_float32*)(buf + (band*SIZE)); // destination for(ossim_uint32 offset = 0; offset < SIZE; ++offset) { ossim_float64 p = s[offset]; if(p != NP) { if( p == MIN_PIX) { d[offset] = OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT; } else { d[offset] = (p-MIN_PIX)/RANGE; } } else { d[offset] = 0.0; } } } } template void ossimImageData::copyTileToNormalizedBuffer(T /* dummyTemplate */, ossim_uint32 band, ossim_float64* buf) const { const ossim_uint32 SIZE = getSizePerBand(); const ossim_float64 MIN_PIX = getMinPix(band); const ossim_float64 MAX_PIX = getMaxPix(band); const ossim_float64 RANGE = (MAX_PIX-MIN_PIX); const ossim_float64 NP = getNullPix(band); const T* s = (T*)getBuf(band); // source ossim_float64* d = (ossim_float64*)(buf); // destination for(ossim_uint32 offset = 0; offset < SIZE; ++offset) { ossim_float64 p = s[offset]; if(p != NP) { if( p == MIN_PIX) { d[offset] = OSSIM_DEFAULT_MIN_PIX_NORM_DOUBLE; } else { d[offset] = (p-MIN_PIX)/RANGE; } } else { d[offset] = 0.0; } } } template void ossimImageData::copyTileToNormalizedBuffer(T /* dummyTemplate */, ossim_uint32 band, ossim_float32* buf) const { const ossim_uint32 SIZE = getSizePerBand(); const ossim_float64 MIN_PIX = getMinPix(band); const ossim_float64 MAX_PIX = getMaxPix(band); const ossim_float64 RANGE = (MAX_PIX-MIN_PIX); const ossim_float64 NP = getNullPix(band); const T* s = (T*)getBuf(band); // source ossim_float32* d = (ossim_float32*)(buf); // destination for(ossim_uint32 offset = 0; offset < SIZE; ++offset) { ossim_float64 p = s[offset]; if(p != NP) { if( p == MIN_PIX) { d[offset] = OSSIM_DEFAULT_MIN_PIX_NORM_FLOAT; } else { d[offset] = (p-MIN_PIX)/RANGE; } } else { d[offset] = 0.0; } } } template void ossimImageData::copyNormalizedBufferToTile(T /* dummyTemplate */, ossim_float64* buf) { const ossim_uint32 SIZE = getSizePerBand(); const ossim_uint32 BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < BANDS; ++band) { const ossim_float64 MIN_PIX = getMinPix(band); const ossim_float64 MAX_PIX = getMaxPix(band); const ossim_float64 RANGE = (MAX_PIX-MIN_PIX); const T NP = (T)getNullPix(band); ossim_float64* s = buf + (band*SIZE); // source T* d = (T*)getBuf(band); // destination for(ossim_uint32 offset = 0; offset < SIZE; ++offset) { const ossim_float64 P = s[offset]; if(P != 0.0) { d[offset] = (T)(MIN_PIX + RANGE*P); } else { d[offset] = NP; } } } } template void ossimImageData::copyNormalizedBufferToTile(T /* dummyTemplate */, ossim_float32* buf) { const ossim_uint32 SIZE = getSizePerBand(); const ossim_uint32 BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < BANDS; ++band) { const ossim_float64 MIN_PIX = getMinPix(band); const ossim_float64 MAX_PIX = getMaxPix(band); const ossim_float64 RANGE = (MAX_PIX-MIN_PIX); const T NP = (T)getNullPix(band); ossim_float32* s = buf + (band*SIZE); // source T* d = (T*)getBuf(band); // destination for(ossim_uint32 offset = 0; offset < SIZE; ++offset) { const ossim_float64 P = s[offset]; if(P != 0.0) { ossim_float64 test = MIN_PIX + RANGE*P; if(test > MAX_PIX) test = MAX_PIX; d[offset] = (T)test; } else { d[offset] = NP; } } } } template void ossimImageData::copyNormalizedBufferToTile(T /* dummyTemplate */, ossim_uint32 band, ossim_float64* buf) { const ossim_uint32 SIZE = getSizePerBand(); const ossim_float64 MIN_PIX = getMinPix(band); const ossim_float64 MAX_PIX = getMaxPix(band); const ossim_float64 RANGE = (MAX_PIX-MIN_PIX); const T NP = (T)getNullPix(band); ossim_float64* s = buf; // source T* d = (T*)getBuf(band); // destination for(ossim_uint32 offset = 0; offset < SIZE; ++offset) { const ossim_float64 P = s[offset]; if(P != 0.0) { ossim_float64 test = MIN_PIX + RANGE*P; if(test > MAX_PIX) test = MAX_PIX; d[offset] = (T)test; } else { d[offset] = NP; } } } template void ossimImageData::copyNormalizedBufferToTile(T /* dummyTemplate */, ossim_uint32 band, ossim_float32* buf) { const ossim_uint32 SIZE = getSizePerBand(); const ossim_float64 MIN_PIX = getMinPix(band); const ossim_float64 MAX_PIX = getMaxPix(band); const ossim_float64 RANGE = (MAX_PIX-MIN_PIX); const T NP = (T)getNullPix(band); ossim_float32* s = buf; // source T* d = (T*)getBuf(band); // destination for(ossim_uint32 offset = 0; offset < SIZE; ++offset) { const ossim_float64 P = s[offset]; if(P != 0.0) { ossim_float64 test = MIN_PIX + RANGE*P; if(test > MAX_PIX) test = MAX_PIX; d[offset] = (T)test; } else { d[offset] = NP; } } } void ossimImageData::copyTileBandToNormalizedBuffer(ossim_uint32 band, ossim_float64* buf) const { if (!buf) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileBandToNormalizedBuffer ERROR:" << "\nNull buffer passed to method! Returning..." << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileBandToNormalizedBuffer ERROR:" << "\nThis object is null! Returning..." << std::endl; return; } if(!getBuf(band)) return; switch(getScalarType()) { case OSSIM_NORMALIZED_DOUBLE: { memmove(buf, getBuf(band), getDataSizeInBytes()); break; } case OSSIM_NORMALIZED_FLOAT: { ossim_uint32 upperBound = getWidth()*getHeight(); const ossim_float32* inputBuf = static_cast(getBuf(band)); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { buf[offset] = inputBuf[offset]; } break; } case OSSIM_FLOAT32: { copyTileToNormalizedBuffer((ossim_float32)0, band, buf); break; } case OSSIM_FLOAT64: { copyTileToNormalizedBuffer((ossim_float64)0, band, buf); break; } case OSSIM_UINT8: { copyTileToNormalizedBuffer((ossim_uint8)0, band, buf); break; } case OSSIM_SINT8: { copyTileToNormalizedBuffer((ossim_sint8)0, band, buf); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { copyTileToNormalizedBuffer((ossim_uint16)0, band, buf); break; } case OSSIM_SINT16: { copyTileToNormalizedBuffer((ossim_sint16)0, band, buf); break; } case OSSIM_UINT32: { copyTileToNormalizedBuffer((ossim_uint32)0, band, buf); break; } case OSSIM_SINT32: { copyTileToNormalizedBuffer((ossim_sint32)0, band, buf); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileBandToNormalizedBuffer ERROR:" << " Unknown scalar type!" << std::endl; } } // End of "switch(getScalarType())" } void ossimImageData::copyTileToNormalizedBuffer(ossim_float32* buf)const { if (!buf) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileToNormalizedBuffer ERROR:" << "\nNull buffer passed to method! Returning..." << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileToNormalizedBuffer ERROR:" << "\nThis object is null! Returning..." << std::endl; return; } switch(getScalarType()) { case OSSIM_NORMALIZED_DOUBLE: { ossim_uint32 upperBound = getWidth()*getHeight()*getNumberOfBands(); const ossim_float32* inputBuf = static_cast(getBuf()); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { buf[offset] = inputBuf[offset]; } break; } case OSSIM_NORMALIZED_FLOAT: { memmove(buf, getBuf(), getDataSizeInBytes()); break; } case OSSIM_FLOAT32: { copyTileToNormalizedBuffer((ossim_float32)0, buf); break; } case OSSIM_FLOAT64: { copyTileToNormalizedBuffer((ossim_float64)0, buf); break; } case OSSIM_UINT8: { copyTileToNormalizedBuffer((ossim_uint8)0, buf); break; } case OSSIM_SINT8: { copyTileToNormalizedBuffer((ossim_sint8)0, buf); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { copyTileToNormalizedBuffer((ossim_uint16)0, buf); break; } case OSSIM_SINT16: { copyTileToNormalizedBuffer((ossim_sint16)0, buf); break; } case OSSIM_UINT32: { copyTileToNormalizedBuffer((ossim_uint32)0, buf); break; } case OSSIM_SINT32: { copyTileToNormalizedBuffer((ossim_sint32)0, buf); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "NOTICE: copyTileToNormalizedBuffer not implemented yet" << std::endl; } } // End of "switch(getScalarType())" } void ossimImageData::copyTileBandToNormalizedBuffer(ossim_uint32 band, ossim_float32* buf)const { if (!buf) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileBandToNormalizedBuffer ERROR:" << "\nNull buffer passed to method! Returning..." << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileBandToNormalizedBuffer ERROR:" << "\nThis object is null! Returning..." << std::endl; return; } switch(getScalarType()) { case OSSIM_NORMALIZED_DOUBLE: { ossim_uint32 upperBound = getWidth()*getHeight(); const ossim_float32* inputBuf = static_cast(getBuf(band)); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { buf[offset] = inputBuf[offset]; } break; } case OSSIM_NORMALIZED_FLOAT: { memmove(buf, getBuf(band), getSizePerBandInBytes()); break; } case OSSIM_FLOAT32: { copyTileToNormalizedBuffer((ossim_float32)0, band, buf); break; } case OSSIM_FLOAT64: { copyTileToNormalizedBuffer((ossim_float64)0, band, buf); break; } case OSSIM_UINT8: { copyTileToNormalizedBuffer((ossim_uint8)0, band, buf); break; } case OSSIM_SINT8: { copyTileToNormalizedBuffer((ossim_sint8)0, band, buf); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { copyTileToNormalizedBuffer((ossim_uint16)0, band, buf); break; } case OSSIM_SINT16: { copyTileToNormalizedBuffer((ossim_sint16)0, band, buf); break; } case OSSIM_UINT32: { copyTileToNormalizedBuffer((ossim_uint32)0, band, buf); break; } case OSSIM_SINT32: { copyTileToNormalizedBuffer((ossim_sint32)0, band, buf); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyTileBandToNormalizedBuffer ERROR:" << " Unknown scalar type" << std::endl; } } // End of "switch(getScalarType())" } void ossimImageData::copyNormalizedBufferToTile(ossim_float64* buf) { if (!buf) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile ERROR:" << "\nNull buffer passed to method! Returning..." << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile ERROR:" << "\nThis object is null! Returning..." << std::endl; return; } switch(getScalarType()) { case OSSIM_NORMALIZED_DOUBLE: { memmove(getBuf(), buf, getDataSizeInBytes()); break; } case OSSIM_NORMALIZED_FLOAT: { ossim_uint32 upperBound = getWidth()*getHeight()*getNumberOfBands(); ossim_float32* inputBuf = static_cast(getBuf()); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { inputBuf[offset] = static_cast(buf[offset]); } break; } case OSSIM_FLOAT32: { copyNormalizedBufferToTile((ossim_float32)0, buf); break; } case OSSIM_FLOAT64: { copyNormalizedBufferToTile((ossim_float64)0, buf); break; } case OSSIM_UINT8: { copyNormalizedBufferToTile((ossim_uint8)0, buf); break; } case OSSIM_SINT8: { copyNormalizedBufferToTile((ossim_sint8)0, buf); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { copyNormalizedBufferToTile((ossim_uint16)0, buf); break; } case OSSIM_SINT16: { copyNormalizedBufferToTile((ossim_sint16)0, buf); break; } case OSSIM_UINT32: { copyNormalizedBufferToTile((ossim_uint32)0, buf); break; } case OSSIM_SINT32: { copyNormalizedBufferToTile((ossim_sint32)0, buf); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile\n" << "Unknown scalar type!" << std::endl; } } // End of "switch(getScalarType())". } void ossimImageData::copyNormalizedBufferToTile(ossim_uint32 band, ossim_float64* buf) { if (!buf) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile ERROR:" << "\nNull buffer passed to method! Returning..." << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile ERROR:" << "\nThis object is null! Returning..." << std::endl; return; } if(band < getNumberOfBands()) { switch(getScalarType()) { case OSSIM_NORMALIZED_DOUBLE: { memmove(getBuf(band), buf, getSizePerBandInBytes()); break; } case OSSIM_NORMALIZED_FLOAT: { ossim_uint32 upperBound = getWidth()*getHeight(); ossim_float32* inputBuf = static_cast(getBuf(band)); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { inputBuf[offset] = static_cast(buf[offset]); } break; } case OSSIM_FLOAT32: { copyNormalizedBufferToTile((ossim_float32)0, band, buf); break; } case OSSIM_FLOAT64: { copyNormalizedBufferToTile((ossim_float64)0, band, buf); break; } case OSSIM_UINT8: { copyNormalizedBufferToTile((ossim_uint8)0, band, buf); break; } case OSSIM_SINT8: { copyNormalizedBufferToTile((ossim_sint8)0, band, buf); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { copyNormalizedBufferToTile((ossim_uint16)0, band, buf); break; } case OSSIM_SINT16: { copyNormalizedBufferToTile((ossim_sint16)0, band, buf); break; } case OSSIM_UINT32: { copyNormalizedBufferToTile((ossim_uint32)0, band, buf); break; } case OSSIM_SINT32: { copyNormalizedBufferToTile((ossim_sint32)0, band, buf); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile\n" << "Unknown scalar type." << std::endl; } } // End of "switch(getScalarType())". } } void ossimImageData::copyNormalizedBufferToTile(ossim_float32* buf) { if (!buf) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile ERROR:" << "\nNull buffer passed to method! Returning..." << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile ERROR:" << "\nThis object is null! Returning..." << std::endl; return; } switch(getScalarType()) { case OSSIM_NORMALIZED_DOUBLE: { ossim_uint32 upperBound = getWidth()*getHeight()*getNumberOfBands(); ossim_float64* inputBuf = static_cast(getBuf()); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { inputBuf[offset] = buf[offset]; } break; } case OSSIM_NORMALIZED_FLOAT: { memmove(getBuf(), buf, getDataSizeInBytes()); break; } case OSSIM_FLOAT32: { copyNormalizedBufferToTile((ossim_float32)0, buf); break; } case OSSIM_FLOAT64: { copyNormalizedBufferToTile((ossim_float64)0, buf); break; } case OSSIM_UINT8: { copyNormalizedBufferToTile((ossim_uint8)0, buf); break; } case OSSIM_SINT8: { copyNormalizedBufferToTile((ossim_sint8)0, buf); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { copyNormalizedBufferToTile((ossim_uint16)0, buf); break; } case OSSIM_SINT16: { copyNormalizedBufferToTile((ossim_sint16)0, buf); break; } case OSSIM_UINT32: { copyNormalizedBufferToTile((ossim_uint32)0, buf); break; } case OSSIM_SINT32: { copyNormalizedBufferToTile((ossim_sint32)0, buf); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageDatacopyNormalizedBufferToTile\n" << "Unknown scalar type!" << std::endl; } } // End of "switch(getScalarType())". } void ossimImageData::copyNormalizedBufferToTile(ossim_uint32 band, ossim_float32* buf) { if (!buf) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile ERROR:" << "\nNull buffer passed to method! Returning..." << std::endl; return; } if (getDataObjectStatus() == OSSIM_NULL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile ERROR:" << "\nThis object is null! Returning..." << std::endl; return; } switch(getScalarType()) { case OSSIM_NORMALIZED_DOUBLE: { ossim_uint32 upperBound = getWidth()*getHeight(); ossim_float64* inputBuf = static_cast(getBuf(band)); for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { inputBuf[offset] = buf[offset]; } break; } case OSSIM_NORMALIZED_FLOAT: { memmove(getBuf(band), buf, getSizePerBandInBytes()); break; } case OSSIM_FLOAT32: { copyNormalizedBufferToTile((ossim_float32)0, band, buf); break; } case OSSIM_FLOAT64: { copyNormalizedBufferToTile((ossim_float64)0, band, buf); break; } case OSSIM_UINT8: { copyNormalizedBufferToTile((ossim_uint8)0, band, buf); break; } case OSSIM_SINT8: { copyNormalizedBufferToTile((ossim_sint8)0, band, buf); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { copyNormalizedBufferToTile((ossim_uint16)0, band, buf); break; } case OSSIM_SINT16: { copyNormalizedBufferToTile((ossim_sint16)0, band, buf); break; } case OSSIM_UINT32: { copyNormalizedBufferToTile((ossim_uint32)0, band, buf); break; } case OSSIM_SINT32: { copyNormalizedBufferToTile((ossim_sint32)0, band, buf); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyNormalizedBufferToTile\n" << "Unknown scalar type!" << std::endl; } } // End of "switch(getScalarType())". } ossim_float64 ossimImageData::getMinNormalizedPix() const { if (m_scalarType == OSSIM_NORMALIZED_DOUBLE || m_scalarType == OSSIM_NORMALIZED_FLOAT) { return m_minPixelValue[0]; // Already normalized. } return (1.0 / (m_maxPixelValue[0] - m_minPixelValue[0] + 1.0)); } std::ostream& ossimImageData::print(std::ostream& out) const { out << getClassName() << "::print:" << "\nm_origin: " << m_origin << "\n"; if(m_nullPixelValue.size()) { out << "Null values: "; copy(m_nullPixelValue.begin(), m_nullPixelValue.begin() + getNumberOfBands(), std::ostream_iterator(out, " ")); out << "\n"; } if(m_minPixelValue.size()) { out << "Min values: "; copy(m_minPixelValue.begin(), m_minPixelValue.begin() + getNumberOfBands(), std::ostream_iterator(out, " ")); out << "\n"; } if(m_maxPixelValue.size()) { out << "Max values: "; copy(m_maxPixelValue.begin(), m_maxPixelValue.begin() + getNumberOfBands(), std::ostream_iterator(out, " ")); out << "\n"; } out << "width: " << getWidth() << "\nheight: " << getHeight() << "\nimage rectangle: " << getImageRectangle() << "\nindexed: " << m_indexedFlag << "\nalpha size: " << m_alpha.size() << std::endl; return ossimRectilinearDataObject::print(out); } void ossimImageData::stretchMinMax() { if ( (getDataObjectStatus() != OSSIM_NULL) && (getDataObjectStatus() != OSSIM_EMPTY) ) { switch (getScalarType()) { case OSSIM_UINT8: { stretchMinMax(ossim_uint8(0)); return; } case OSSIM_SINT8: { stretchMinMax(ossim_sint8(0)); return; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { stretchMinMax(ossim_uint16(0)); return; } case OSSIM_SINT16: { stretchMinMax(ossim_sint16(0)); return; } case OSSIM_UINT32: { stretchMinMax(ossim_uint32(0)); return; } case OSSIM_SINT32: { stretchMinMax(ossim_sint32(0)); return; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { stretchMinMax(ossim_float32(0.0)); return; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { stretchMinMax(ossim_float64(0.0)); return; } case OSSIM_SCALAR_UNKNOWN: default: { setDataObjectStatus(OSSIM_STATUS_UNKNOWN); ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::stretchMinMax File %s line %d\n\ Invalid scalar type: %d", __FILE__, __LINE__, getScalarType()); break; } } } } template void ossimImageData::stretchMinMax(T /* dummyTemplate */) { const ossim_uint32 BANDS = getNumberOfBands(); const ossim_uint32 SPB = getSizePerBand(); // scalar min const ossim_float64 S_MIN = ossim::defaultMin(getScalarType()); // scalar max const ossim_float64 S_MAX = ossim::defaultMax(getScalarType()); // scalar null const ossim_float64 S_NUL = ossim::defaultNull(getScalarType()); // scalar range const ossim_float64 S_RNG = S_MAX-S_MIN+1.0; for(ossim_uint32 band = 0; band < BANDS; ++band) { T* s = static_cast(getBuf(band)); if (s) { const ossim_float64 T_NUL = m_nullPixelValue[band]; // tile null const ossim_float64 T_MIN = m_minPixelValue[band]; // tile min const ossim_float64 T_MAX = m_maxPixelValue[band]; // tile max const ossim_float64 T_RNG = (T_MAX-T_MIN)+1; // tile range const ossim_float64 SPP = S_RNG / T_RNG; // stretch per pixel for(ossim_uint32 i = 0; i < SPB; ++i) { ossim_float64 p = s[i]; if ( p == T_NUL ) { p = S_NUL; } else if (p <= T_MIN) { p = S_MIN; } else if (p >= T_MAX) { p = S_MAX; } else { // Stretch... p = (p - T_MIN + 1.0) * SPP + S_MIN - 1.0; } s[i] = ossim::round(p); } // Set the min, max, null: m_minPixelValue[band] = S_MIN; m_maxPixelValue[band] = S_MAX; m_nullPixelValue[band] = S_NUL; } } } void ossimImageData::computeAlphaChannel() { if ( getDataObjectStatus() != OSSIM_NULL ) { switch (getScalarType()) { case OSSIM_UINT8: { computeAlphaChannel(ossim_uint8(0)); return; } case OSSIM_SINT8: { computeAlphaChannel(ossim_sint8(0)); return; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { computeAlphaChannel(ossim_uint16(0)); return; } case OSSIM_SINT16: { computeAlphaChannel(ossim_sint16(0)); return; } case OSSIM_UINT32: { computeAlphaChannel(ossim_uint32(0)); return; } case OSSIM_SINT32: { computeAlphaChannel(ossim_sint32(0)); return; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { computeAlphaChannel(ossim_float32(0.0)); return; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { computeAlphaChannel(ossim_float64(0.0)); return; } case OSSIM_SCALAR_UNKNOWN: default: { setDataObjectStatus(OSSIM_STATUS_UNKNOWN); ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimImageData::computeAlphaChannel File %s line %d\n\ Invalid scalar type: %d", __FILE__, __LINE__, getScalarType()); break; } } } } template void ossimImageData::computeAlphaChannel(T /* dummyTemplate */) { const ossim_uint32 SPB = getSizePerBand(); const ossim_uint8 ANP = 0; // Alpha Null Pixel const ossim_uint8 AVP = 255; // Alpha Valid Pixel // Allocate the alpha channel if not already. if (m_alpha.size() != SPB) { m_alpha.resize(SPB); } if (getDataObjectStatus() == OSSIM_FULL) { memset( static_cast(&m_alpha.front()), static_cast(AVP), static_cast(SPB) ); } else if (getDataObjectStatus() == OSSIM_EMPTY) { // Start with alpha being set to 0. memset( static_cast(&m_alpha.front()), static_cast(ANP), static_cast(SPB) ); } else // Partial must check each pixel. { const ossim_uint32 BANDS = getNumberOfBands(); std::vector null_pix(BANDS); std::vector buf(BANDS); // Pointer to pixel data. ossim_uint32 band; for(band = 0; band < BANDS; ++band) { buf[band] = static_cast(getBuf(band)); null_pix[band] = static_cast(m_nullPixelValue[band]); } for(ossim_uint32 i = 0; i < SPB; ++i) { //--- // Start with alpha being set to 0. If any band has a valid pixel set // to 255 and break from band loop. //--- m_alpha[i] = ANP; for(band = 0; band < BANDS; ++band) { if (buf[band][i] != null_pix[band]) { m_alpha[i] = AVP; break; } } } } } // End: template void ossimImageData::computeAlphaChannel ossim_uint64 ossimImageData::getWidth() const { return m_spatialExtents[0]; } ossim_uint64 ossimImageData::getHeight() const { return m_spatialExtents[1]; } void ossimImageData::getWidthHeight(ossim_uint32& w, ossim_uint32& h) { w = m_spatialExtents[0]; h = m_spatialExtents[1]; } void ossimImageData::setWidth(ossim_uint32 width) { m_spatialExtents[0] = width; } void ossimImageData::setHeight(ossim_uint32 height) { m_spatialExtents[1] = height; } void ossimImageData::setWidthHeight(ossim_uint32 w, ossim_uint32 h) { m_spatialExtents[0] = w; m_spatialExtents[1] = h; } void ossimImageData::setOrigin(const ossimIpt& origin) { m_origin = origin; } ossim_uint64 ossimImageData::getDataSizeInBytes()const { return getSizeInBytes(); } void ossimImageData::copyLine(const void *src, ossim_int64 lineNumber, ossim_int64 lineStartSample, ossim_int64 lineStopSample, ossimInterleaveType lineInterleave) { switch(m_scalarType) { case OSSIM_UINT8: { copyLineTemplate((ossim_uint8)0, src, lineNumber, lineStartSample, lineStopSample, lineInterleave); break; } case OSSIM_SINT8: { copyLineTemplate((ossim_sint8)0, src, lineNumber, lineStartSample, lineStopSample, lineInterleave); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { copyLineTemplate((ossim_uint16)0, src, lineNumber, lineStartSample, lineStopSample, lineInterleave); break; } case OSSIM_SINT16: { copyLineTemplate((ossim_sint16)0, src, lineNumber, lineStartSample, lineStopSample, lineInterleave); break; } case OSSIM_UINT32: { copyLineTemplate((ossim_uint32)0, src, lineNumber, lineStartSample, lineStopSample, lineInterleave); break; } case OSSIM_SINT32: { copyLineTemplate((ossim_sint32)0, src, lineNumber, lineStartSample, lineStopSample, lineInterleave); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT32: { copyLineTemplate((ossim_float32)0.0, src, lineNumber, lineStartSample, lineStopSample, lineInterleave); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { copyLineTemplate((ossim_float64)0.0, src, lineNumber, lineStartSample, lineStopSample, lineInterleave); break; } case OSSIM_SCALAR_UNKNOWN: default: { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimImageData::copyLine Unsupported scalar type!" << std::endl; break; } } } // End: void ossimImageData::copyLine template void ossimImageData::copyLineTemplate(T /* dummyTemplate */, const void *src, ossim_int64 lineNumber, ossim_int64 lineStartSample, ossim_int64 lineStopSample, ossimInterleaveType lineInterleave) { if (src) { const ossimIrect RECT = getImageRectangle(); // Check for intersect: if ( ( lineNumber >= RECT.ul().y) && ( lineNumber <= RECT.lr().y) && ( lineStartSample < lineStopSample) && ( lineStartSample <= RECT.lr().x) && ( lineStopSample >= RECT.ul().x) ) { const ossim_int64 BANDS = static_cast(m_numberOfDataComponents); const ossim_int64 START_SAMP = (lineStartSample > RECT.ul().x) ? lineStartSample : RECT.ul().x; const ossim_int64 STOP_SAMP = (lineStopSample < RECT.lr().x) ? lineStopSample : RECT.lr().x; const ossim_int64 SAMPS = STOP_SAMP - START_SAMP + 1; std::vector d(BANDS); ossim_int64 band; for (band = 0; band < BANDS; ++band) { d[band] = static_cast(getBuf(band)); // Position at start sample. d[band] += (lineNumber - RECT.ul().y) * RECT.width() + (START_SAMP - RECT.ul().x); } if (lineInterleave == OSSIM_BIP) { const T* S = static_cast(src); // Source buffer: // Position at start sample. S += (START_SAMP - lineStartSample) * BANDS; ossim_int32 srcOffset = 0; for (ossim_int32 samp = 0; samp < SAMPS; ++samp) { for (band = 0; band < BANDS; ++band) { d[band][samp] = S[srcOffset++]; } } } else { const ossim_int64 W = lineStopSample - lineStartSample + 1; std::vector S(BANDS); for (band = 0; band < BANDS; ++band) { S[band] = static_cast(src) + (START_SAMP - lineStartSample); if (band) { S[band] += band * W; // Move to line. } } for (band = 0; band < BANDS; ++band) { for (ossim_int32 samp = 0; samp < SAMPS; ++samp) { d[band][samp] = S[band][samp]; } } } } // intersect check } // if (src) } // End: template void ossimImageData::copyLineTemplate void ossimImageData::setIndexedFlag(bool flag) { m_indexedFlag = flag; } bool ossimImageData::getIndexedFlag() const { return m_indexedFlag; } bool ossimImageData::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimRectilinearDataObject::saveState(kwl, prefix); ossimString null_pixels; ossimString min_pixels; ossimString max_pixels; ossim::toSimpleStringList(null_pixels, m_nullPixelValue); ossim::toSimpleStringList(min_pixels, m_minPixelValue); ossim::toSimpleStringList(max_pixels, m_maxPixelValue); kwl.add(prefix, "null_pixels", null_pixels, true); kwl.add(prefix, "min_pixels", min_pixels, true); kwl.add(prefix, "max_pixels", max_pixels, true); ossimString alpha; ossim::toSimpleStringList(alpha, m_alpha); kwl.add(prefix, "alpha", alpha, true); kwl.add(prefix, "indexed", m_indexedFlag, true); kwl.add(prefix, "origin", m_origin.toString(), true); return result; } bool ossimImageData::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimRectilinearDataObject::loadState(kwl, prefix); m_spatialExtents.resize(2); if(result) { const char* null_pixels = kwl.find(prefix, "null_pixels"); const char* min_pixels = kwl.find(prefix, "min_pixels"); const char* max_pixels = kwl.find(prefix, "max_pixels"); const char* alpha = kwl.find(prefix, "alpha"); const char* origin = kwl.find(prefix, "origin"); const char* indexed = kwl.find(prefix, "indexed"); ossimString rectString = kwl.find(prefix, "rect"); const char* numberOfBands = kwl.find(prefix, "number_bands"); m_nullPixelValue.clear(); m_minPixelValue.clear(); m_maxPixelValue.clear(); m_alpha.clear(); if(null_pixels) { if(!ossim::toSimpleVector(m_nullPixelValue, ossimString(null_pixels))) { return false; } } if(min_pixels) { if(!ossim::toSimpleVector(m_minPixelValue, ossimString(min_pixels))) { return false; } } if(max_pixels) { if(!ossim::toSimpleVector(m_maxPixelValue, ossimString(max_pixels))) { return false; } } if(alpha) { if(!ossim::toSimpleVector(m_alpha, ossimString(alpha))) { return false; } } if(origin) { m_origin.toPoint(origin); } m_indexedFlag = false; if(indexed) { m_indexedFlag = ossimString(indexed).toBool(); } if(!rectString.empty()) { ossimIrect rect; if(rect.toRect(rectString)) { setImageRectangle(rect); } } if(numberOfBands) { ossim_uint32 nBands = ossimString(numberOfBands).toUInt32(); setNumberOfDataComponents(nBands); if(m_nullPixelValue.empty()|| m_minPixelValue.empty()|| m_maxPixelValue.empty()) { initializeDefaults(); } } } return result; } void ossimImageData::setHistogram(ossimRefPtr histo) { m_histogram = histo; } ossimRefPtr ossimImageData::getHistogram() { return m_histogram; } ossim_float64 ossimImageData::percentFull() const { return m_percentFull; } void ossimImageData::setPercentFull( const ossim_float64& percentFull ) { m_percentFull = percentFull; } ossim-Miami-2.9.1/src/imaging/ossimImageDataFactory.cpp000066400000000000000000000206561352751253100230510ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // Contributor: David A. Horner (DAH) - http://dave.thehorners.com // //************************************************************************* // $Id: ossimImageDataFactory.cpp 22135 2013-02-02 16:27:24Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Static trace for debugging static ossimTrace traceDebug("ossimImageDataFactory:debug"); ossimImageDataFactory* ossimImageDataFactory::theInstance = 0; std::mutex ossimImageDataFactory::theInstanceMutex; ossimImageDataFactory::ossimImageDataFactory() { theInstance = 0; } ossimImageDataFactory::~ossimImageDataFactory() { if(theInstance) { //delete theInstance; theInstance = 0; } } ossimImageDataFactory* ossimImageDataFactory::instance() { theInstanceMutex.lock(); if(!theInstance) { theInstance = new ossimImageDataFactory; } theInstanceMutex.unlock(); return theInstance; } ossimRefPtr ossimImageDataFactory::create( ossimSource* owner, ossimScalarType scalar, ossim_uint32 bands)const { ossimIpt tileSize; ossim::defaultTileSize(tileSize); ossim_uint32 width = tileSize.x; ossim_uint32 height = tileSize.y; // do some bounds checking and initialize to a default bands = (bands>0)?bands:1; scalar = scalar != OSSIM_SCALAR_UNKNOWN?scalar:OSSIM_UINT8; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageDataFactory::create DEBUG:" << "\nCaller: " << (owner ? owner->getClassName().c_str() : "unknown") << "\nbands: " << bands << "\nwidth: " << width << "\nheight: " << height << "\nScalar type: " << (ossimScalarTypeLut::instance()->getEntryString(scalar)) << std::endl; } ossimRefPtr result = 0; switch(scalar) { case OSSIM_UINT8: { result = new ossimU8ImageData(owner, bands, width, height); break; } case OSSIM_USHORT11: { result = new ossimU11ImageData(owner, bands, width, height); break; } case OSSIM_USHORT12: { result = new ossimU12ImageData(owner, bands, width, height); break; } case OSSIM_USHORT13: { result = new ossimU13ImageData(owner, bands, width, height); break; } case OSSIM_USHORT14: { result = new ossimU14ImageData(owner, bands, width, height); break; } case OSSIM_USHORT15: { result = new ossimU15ImageData(owner, bands, width, height); break; } case OSSIM_UINT16: { result = new ossimU16ImageData(owner, bands, width, height); break; } case OSSIM_SINT16: { result = new ossimS16ImageData(owner, bands, width, height); break; } default: { // create a generic image data implementation. result = new ossimImageData(owner, scalar, bands, width, height); // Set the scalar type for stretching. ossimImageSource* inputSource = dynamic_cast(owner); if( inputSource ) { for(ossim_uint32 band = 0; band < bands; ++band) { result->setMinPix(inputSource->getMinPixelValue(band), band); result->setMaxPix(inputSource->getMaxPixelValue(band), band); result->setNullPix(inputSource->getNullPixelValue(band), band); } } break; } } return result; } ossimRefPtr ossimImageDataFactory::create( ossimSource* owner, ossimScalarType scalar, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height)const { ossimIpt tileSize; ossim::defaultTileSize(tileSize); // do some bounds checking and initialize to a default bands = bands > 0?bands:1; width = width > 0?width:tileSize.x; height = height > 0?height:tileSize.y; scalar = scalar != OSSIM_SCALAR_UNKNOWN?scalar:OSSIM_UINT8; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageDataFactory::create DEBUG:" << "\nCaller: " << (owner ? owner->getClassName().c_str() : "unknown") << "\nbands: " << bands << "\nwidth: " << width << "\nheight: " << height << "\nScalar type: " << (ossimScalarTypeLut::instance()->getEntryString(scalar)) << std::endl; } ossimRefPtr result = 0; switch(scalar) { case OSSIM_UINT8: { result = new ossimU8ImageData(owner, bands, width, height); break; } case OSSIM_USHORT11: { result = new ossimU11ImageData(owner, bands, width, height); break; } case OSSIM_USHORT12: { result = new ossimU12ImageData(owner, bands, width, height); break; } case OSSIM_USHORT13: { result = new ossimU13ImageData(owner, bands, width, height); break; } case OSSIM_USHORT14: { result = new ossimU14ImageData(owner, bands, width, height); break; } case OSSIM_USHORT15: { result = new ossimU15ImageData(owner, bands, width, height); break; } case OSSIM_UINT16: { result = new ossimU16ImageData(owner, bands, width, height); break; } case OSSIM_SINT16: { result = new ossimS16ImageData(owner, bands, width, height); break; } default: { // create a generic image data implementation. result = new ossimImageData(owner, scalar, bands, width, height); break; } } return result; } ossimRefPtr ossimImageDataFactory::create( ossimSource* owner, ossim_uint32 bands, ossimImageSource* inputSource)const { ossimRefPtr result = 0; if(inputSource) { ossimScalarType scalar = inputSource->getOutputScalarType(); ossim_uint32 width = inputSource->getTileWidth(); ossim_uint32 height = inputSource->getTileHeight(); result = create(owner, scalar, bands, width, height); if ( result.valid() ) { for(ossim_uint32 band = 0; band < bands; ++band) { result->setMinPix(inputSource->getMinPixelValue(band), band); result->setMaxPix(inputSource->getMaxPixelValue(band), band); result->setNullPix(inputSource->getNullPixelValue(band), band); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageDataFactory::create ERROR:" << "\nNULL input source!" << std::endl; } return result; } ossimRefPtr ossimImageDataFactory::create( ossimSource* owner, ossimImageSource* inputSource)const { ossimRefPtr result = 0; if(inputSource) { ossimScalarType scalar = inputSource->getOutputScalarType(); ossim_uint32 bands = inputSource->getNumberOfOutputBands(); ossim_uint32 width = inputSource->getTileWidth(); ossim_uint32 height = inputSource->getTileHeight(); result = create(owner, scalar, bands, width, height); if ( result.valid() ) { for(ossim_uint32 band = 0; band < bands; ++band) { result->setMinPix(inputSource->getMinPixelValue(band), band); result->setMaxPix(inputSource->getMaxPixelValue(band), band); result->setNullPix(inputSource->getNullPixelValue(band), band); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageDataFactory::create ERROR:" << "\nNULL input source!" << std::endl; } return result; } ossim-Miami-2.9.1/src/imaging/ossimImageDataHelper.cpp000066400000000000000000000377201352751253100226610ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageDataHelper.cpp 23162 2015-02-21 14:46:31Z dburken $ #include #include #include #include #include using namespace std; ossimImageDataHelper::ossimImageDataHelper(ossimImageData* imageData) { setImageData(imageData); } void ossimImageDataHelper::setImageData(ossimImageData* imageData) { theImageData = imageData; if(theImageData) { theImageRectangle = theImageData->getImageRectangle(); thePolyImageRectangle = theImageRectangle; // thePolyImageRectangle = ossimPolyArea2d(theImageRectangle.ul(), // theImageRectangle.ur(), // theImageRectangle.lr(), // theImageRectangle.ll()); theOrigin = theImageRectangle.ul(); } } void ossimImageDataHelper::copyInputToThis(const void* input, const ossimPolygon& region, bool clipPoly) { if(!theImageData) return; switch(theImageData->getScalarType()) { case OSSIM_UCHAR: { copyInputToThis(reinterpret_cast(input), region, clipPoly); break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { copyInputToThis(reinterpret_cast(input), region, clipPoly); break; } case OSSIM_SSHORT16: { copyInputToThis(reinterpret_cast(input), region, clipPoly); break; } case OSSIM_SINT32: { copyInputToThis(reinterpret_cast(input), region, clipPoly); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { copyInputToThis(reinterpret_cast(input), region, clipPoly); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { copyInputToThis(reinterpret_cast(input), region, clipPoly); break; } case OSSIM_SCALAR_UNKNOWN: default: { break; } } } void ossimImageDataHelper::fill(const ossimRgbVector& color, std::vector& regionList, bool clipPoly) { int i = 0; for(i = 0; i < (int)regionList.size();++i) { fill(color, regionList[i], clipPoly); } } void ossimImageDataHelper::fill(const double* values, std::vector& regionList, bool clipPoly) { int i = 0; for(i = 0; i < (int)regionList.size();++i) { fill(values, regionList[i], clipPoly); } } void ossimImageDataHelper::fill(const ossimRgbVector& color, const ossimPolygon& region, bool clipPoly) { double colorArray[3]; colorArray[0] = color.getR(); colorArray[1] = color.getG(); colorArray[2] = color.getB(); switch(theImageData->getScalarType()) { case OSSIM_UCHAR: { if(theImageData->getNumberOfBands() <= 3) { fill(static_cast(0), (const double*)colorArray, region, clipPoly); } break; } case OSSIM_SCALAR_UNKNOWN: case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_SSHORT16: case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: default: { break; } } } void ossimImageDataHelper::fill(const ossimRgbVector& color, const ossimIrect& region, bool clipPoly) { double colorArray[3]; colorArray[0] = color.getR(); colorArray[1] = color.getG(); colorArray[2] = color.getB(); switch(theImageData->getScalarType()) { case OSSIM_UCHAR: { if(theImageData->getNumberOfBands() <= 3) { fill(static_cast(0), colorArray, region, clipPoly); } break; } case OSSIM_SCALAR_UNKNOWN: case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_SSHORT16: case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { break; } default: break; } } void ossimImageDataHelper::fill(const double* values, const ossimPolygon& region, bool clipPoly) { switch(theImageData->getScalarType()) { case OSSIM_UCHAR: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_SSHORT16: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_SCALAR_UNKNOWN: default: { break; } } } void ossimImageDataHelper::fill(const double* values, const ossimIrect& region, bool clipPoly) { switch(theImageData->getScalarType()) { case OSSIM_UCHAR: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_SSHORT16: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { fill(static_cast(0), values, region, clipPoly); break; } case OSSIM_SCALAR_UNKNOWN: default: { break; } } } template void ossimImageDataHelper::copyInputToThis(const T* inputBuf, const ossimPolygon& region, bool clipPoly) { if(clipPoly) { ossimPolyArea2d polyArea(region); ossimPolyArea2d clipArea = polyArea&thePolyImageRectangle; vector clipList; // clipArea.getAllVisiblePolygons(clipList); clipArea.getVisiblePolygons(clipList); for(ossim_uint32 i = 0; i < clipList.size();++i) { copyInputToThis( inputBuf, clipList[i] ); } } else { copyInputToThis( inputBuf, region ); } } template void ossimImageDataHelper::copyInputToThis(const T* inputBuf, const ossimPolygon& region) { int n; int i; int y; ossim_int32 miny, maxy, minx, maxx; int x1, y1; int x2, y2; int ind1, ind2; // int ints; vector polyInts; T* buf = reinterpret_cast(theImageData->getBuf()); ossim_int32 blockLength=theImageData->getWidth()*theImageData->getHeight(); ossim_int32 bandOffset = 0; region.getIntegerBounds(minx, miny, maxx, maxy); ossim_int32 rowOffset = (miny-theOrigin.y)*theImageData->getWidth(); n = region.getVertexCount(); /* Fix in 1.3: count a vertex only once */ for (y = miny; (y <= maxy); y++) { polyInts.clear(); // ints = 0; for (i = 0; (i < n); i++) { if (!i) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } y1 = ossim::round(region[ind1].y); y2 = ossim::round(region[ind2].y); if (y1 < y2) { x1 = ossim::round(region[ind1].x); x2 = ossim::round(region[ind2].x); } else if (y1 > y2) { y2 = ossim::round(region[ind1].y); y1 = ossim::round(region[ind2].y); x2 = ossim::round(region[ind1].x); x1 = ossim::round(region[ind2].x); } else { continue; } if ((y >= y1) && (y < y2)) { polyInts.push_back((y - y1) * (x2 - x1) / (y2 - y1) + x1); } else if ((y == maxy) && (y > y1) && (y <= y2)) { polyInts.push_back((y - y1) * (x2 - x1) / (y2 - y1) + x1); } } std::sort(polyInts.begin(), polyInts.end()); for (i = 0; (i < (int)polyInts.size()); i += 2) { ossim_int32 startX = polyInts[i]-theOrigin.x; ossim_int32 endX = polyInts[i+1]-theOrigin.x; while(startX <= endX) { bandOffset = 0; int band; for(band = 0; band < (ossim_int32)theImageData->getNumberOfBands();++band) { buf[rowOffset+bandOffset+startX] = (inputBuf[rowOffset+bandOffset+startX]); bandOffset += blockLength; } ++startX; } } rowOffset += theImageData->getWidth(); } } template void ossimImageDataHelper::fill(T dummyVariable, const double* values, const ossimPolygon& region, bool clipPoly) { if(clipPoly) { ossimPolyArea2d polyArea(region); ossimPolyArea2d clipArea = polyArea&thePolyImageRectangle; vector clipList; clipArea.getVisiblePolygons(clipList); for(ossim_uint32 i = 0; i < clipList.size();++i) { fill( dummyVariable, values, clipList[i] ); } } else { fill( dummyVariable, values, region ); } } template void ossimImageDataHelper::fill(T dummyVariable, const double* values, const ossimIrect& region, bool clipPoly) { if(clipPoly) { fill(dummyVariable, values, region.clipToRect(theImageData->getImageRectangle())); } else { fill(dummyVariable, values, region); } } template void ossimImageDataHelper::fill(T /* dummyVariable */, const double* values, const ossimPolygon& region) { int n; int i; int y; ossim_int32 miny, maxy, minx, maxx; int x1, y1; int x2, y2; int ind1, ind2; // int ints; vector polyInts; T* buf = reinterpret_cast(theImageData->getBuf()); ossim_int32 blockLength=theImageData->getWidth()*theImageData->getHeight(); ossim_int32 bandOffset = 0; region.getIntegerBounds(minx, miny, maxx, maxy); ossim_int32 rowOffset = (miny-theOrigin.y)*theImageData->getWidth(); n = region.getVertexCount(); /* Fix in 1.3: count a vertex only once */ for (y = miny; (y <= maxy); y++) { polyInts.clear(); // ints = 0; for (i = 0; (i < n); i++) { if (!i) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } y1 = ossim::round(region[ind1].y); y2 = ossim::round(region[ind2].y); if (y1 < y2) { x1 = ossim::round(region[ind1].x); x2 = ossim::round(region[ind2].x); } else if (y1 > y2) { y2 = ossim::round(region[ind1].y); y1 = ossim::round(region[ind2].y); x2 = ossim::round(region[ind1].x); x1 = ossim::round(region[ind2].x); } else { continue; } if ((y >= y1) && (y < y2)) { polyInts.push_back((y - y1) * (x2 - x1) / (y2 - y1) + x1); } else if ((y == maxy) && (y > y1) && (y <= y2)) { polyInts.push_back((y - y1) * (x2 - x1) / (y2 - y1) + x1); } } std::sort(polyInts.begin(), polyInts.end()); for (i = 0; (i < (int)polyInts.size()); i += 2) { ossim_int32 startX = std::abs(polyInts[i]-theOrigin.x); ossim_int32 endX = std::abs(polyInts[i+1]-theOrigin.x); while(startX <= endX) { bandOffset = 0; int band; for(band = 0; band < (int)theImageData->getNumberOfBands();++band) { buf[rowOffset+bandOffset+startX] = (T)(values[band]); bandOffset += blockLength; } ++startX; } } rowOffset += theImageData->getWidth(); } } template void ossimImageDataHelper::fill(T /* dummyVariable */, const double* values, const ossimIrect& region) { T* buf = reinterpret_cast(theImageData->getBuf()); ossim_int32 blockLength=theImageData->getWidth()*theImageData->getHeight(); ossim_int32 bandOffset = 0; ossim_int32 miny,maxy; ossim_int32 minx, maxx; ossim_int32 y = 0; miny = region.ul().y-theOrigin.y; maxy = region.lr().y-theOrigin.y; minx = region.ul().x-theOrigin.x; maxx = region.lr().x-theOrigin.x; ossim_int32 rowOffset = (miny)*theImageData->getWidth(); ossim_int32 startX = minx; ossim_int32 endX = maxx; ossim_int32 bands = (ossim_int32)theImageData->getNumberOfBands(); for (y = miny; (y <= maxy); ++y) { startX=minx; while(startX <= endX) { bandOffset = 0; int band = 0; for(band = 0; band < bands;++band) { buf[rowOffset+bandOffset+startX] = (T)(values[band]); bandOffset += blockLength; } ++startX; } rowOffset += theImageData->getWidth(); } } ossim-Miami-2.9.1/src/imaging/ossimImageDisplayWriter.cpp000066400000000000000000000026131352751253100234430ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Frank Warmerdam (warmerdam@pobox.com) // // Description: // // Contains class declaration for ossimImageWriter //******************************************************************* // $Id: ossimImageDisplayWriter.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include RTTI_DEF3(ossimImageDisplayWriter, "ossimImageDisplayWriter", ossimImageWriter, ossimDisplayInterface, ossimConnectableObjectListener); ossimImageDisplayWriter::ossimImageDisplayWriter(ossimObject* owner) :ossimImageWriter(owner, 1, 0, true, true), ossimConnectableObjectListener() { } ossimImageDisplayWriter::ossimImageDisplayWriter(ossimObject* owner, ossim_uint32 numberOfInputs, ossim_uint32 numberOfOutputs, bool inputListIsFixed, bool outputListIsFixed) : ossimImageWriter(owner, numberOfInputs, numberOfOutputs, inputListIsFixed, outputListIsFixed), ossimConnectableObjectListener() { } ossim-Miami-2.9.1/src/imaging/ossimImageFileWriter.cpp000066400000000000000000001260771352751253100227300ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Frank Warmerdam (warmerdam@pobox.com) // // Description: // // Contains class declaration for ossimImageFileWriter. //******************************************************************* // $Id: ossimImageFileWriter.cpp 23068 2015-01-07 23:08:29Z okramer $ #include /* for tiff compression defines */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimImageFileWriter:debug"); static const ossimString AUTO_CREATE_DIRECTORY_KW("auto_create_directory"); #if OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimImageFileWriter.cpp 23068 2015-01-07 23:08:29Z okramer $"; #endif RTTI_DEF3(ossimImageFileWriter, "ossimImageFileWriter", ossimImageWriter, ossimProcessInterface, ossimConnectableObjectListener) static const char SCALE_TO_EIGHT_BIT_KW[] = "scale_to_eight_bit"; ossimImageFileWriter::ossimImageFileWriter(const ossimFilename& file, ossimImageSource* inputSource, ossimObject* owner) : ossimImageWriter(owner, 1, 0, true, false), ossimProcessInterface(), ossimConnectableObjectListener(), theViewController(NULL), theProgressListener(NULL), theFilename(file), theOutputImageType(ossimImageTypeLut().getEntryString(OSSIM_IMAGE_TYPE_UNKNOWN)), theWriteImageFlag(true), theWriteOverviewFlag(false), theWriteHistogramFlag(false), theScaleToEightBitFlag(false), theOverviewCompressType(COMPRESSION_NONE), theOverviewJpegCompressQuality(75), theWriteEnviHeaderFlag(false), theWriteErsHeaderFlag(false), theWriteExternalGeometryFlag(false), theWriteFgdcFlag(false), theWriteJpegWorldFileFlag(false), theWriteReadmeFlag(false), theWriteTiffWorldFileFlag(false), theWriteWorldFileFlag(false), theAutoCreateDirectoryFlag(true), theLinearUnits(OSSIM_UNIT_UNKNOWN), thePixelType(OSSIM_PIXEL_IS_POINT) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageFileWriter::ossimImageFileWriter entered..." << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } theInputConnection = new ossimImageSourceSequencer(inputSource); // now map the sequencer to the same input connectMyInputTo(0, inputSource); initialize(); // make sure we listen to our input changes so we can change // it for the sequencer as well. ossimImageWriter::addListener((ossimConnectableObjectListener*)this); theInputConnection->connectMyInputTo(0, inputSource, false); theAreaOfInterest.makeNan(); } ossimImageFileWriter::~ossimImageFileWriter() { theInputConnection = 0; theProgressListener = NULL; removeListener((ossimConnectableObjectListener*)this); } void ossimImageFileWriter::initialize() { if(theInputConnection.valid()) { theInputConnection->initialize(); //--- // Area Of Interest(AOI): // There are two AOIs to keep in sync. // One owned by this base: ossimImageWriter::theAreaOfInterest // One owned by the theInputConntion: ossimImageSourceSequencer::theAreaOfInterest //--- if ( theAreaOfInterest.hasNans() == false ) { //--- // ossimImageSourceSequencer::setAreaOfInterest does more than just set the // variable, so only call if out of sync to avoid wasted cycles. //--- if ( theAreaOfInterest != theInputConnection->getBoundingRect() ) { theInputConnection->setAreaOfInterest( theAreaOfInterest ); } } else { // Set this AOI to bounding rect of input. theAreaOfInterest = theInputConnection->getBoundingRect(); } } } void ossimImageFileWriter::changeSequencer(ossimImageSourceSequencer* sequencer) { if( sequencer ) { theInputConnection = sequencer; theInputConnection->connectMyInputTo(0, getInput(0)); } } bool ossimImageFileWriter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::TYPE_KW, getClassName(), true); kwl.add(prefix, ossimKeywordNames::FILENAME_KW, theFilename.c_str(), true); kwl.add(prefix, "create_envi_hdr", (ossim_uint32)theWriteEnviHeaderFlag, true); kwl.add(prefix, "create_ers_hdr", (ossim_uint32)theWriteErsHeaderFlag, true); kwl.add(prefix, ossimKeywordNames::CREATE_EXTERNAL_GEOMETRY_KW, (ossim_uint32)theWriteExternalGeometryFlag, true); kwl.add(prefix, "create_fgdc", (ossim_uint32)theWriteFgdcFlag, true); kwl.add(prefix, "create_jpeg_world_file", (ossim_uint32)theWriteJpegWorldFileFlag, true); kwl.add(prefix, "create_readme", (ossim_uint32)theWriteReadmeFlag, true); kwl.add(prefix, "create_tiff_world_file", (ossim_uint32)theWriteTiffWorldFileFlag, true); kwl.add(prefix, "create_world_file", (ossim_uint32)theWriteWorldFileFlag, true); kwl.add(prefix, ossimKeywordNames::CREATE_IMAGE_KW, (ossim_uint32)theWriteImageFlag, true); kwl.add(prefix, ossimKeywordNames::CREATE_OVERVIEW_KW, (ossim_uint32)theWriteOverviewFlag, true); kwl.add(prefix, ossimKeywordNames::CREATE_HISTOGRAM_KW, (ossim_uint32)theWriteHistogramFlag, true); kwl.add(prefix, SCALE_TO_EIGHT_BIT_KW, (ossim_uint32)theScaleToEightBitFlag, true); kwl.add(prefix, AUTO_CREATE_DIRECTORY_KW, theAutoCreateDirectoryFlag, true); kwl.add(prefix, ossimKeywordNames::OVERVIEW_COMPRESSION_TYPE_KW, theOverviewCompressType, true); kwl.add(prefix, ossimKeywordNames::OVERVIEW_COMPRESSION_QUALITY_KW, theOverviewJpegCompressQuality, true); ossimImageTypeLut lut; kwl.add(prefix, ossimKeywordNames::IMAGE_TYPE_KW, theOutputImageType, true); //--- // When "theLinearUnits" == "unknown" that is a key to the writer to just // use whatever units makes sense for the projection. Since "unknown" // doesn't look good to the average user in a spec file, change to // "default" if "unknown". When read back in by the lookup table since // "default" is not a valid "string" theLinearUnits will remain "unknown". // Kind of a hack but it works:) (drb) //--- ossimString os = ossimUnitTypeLut::instance()-> getEntryString(theLinearUnits); if (os == "unknown") { os = "default"; // Avoid saving as unknown for user readability. } kwl.add(prefix, "linear_units", os, true); // Set the pixel type. ossimString pixelType; getPixelTypeString(pixelType); kwl.add(prefix, ossimKeywordNames::PIXEL_TYPE_KW, pixelType.c_str(), true); return ossimSource::saveState(kwl, prefix); } bool ossimImageFileWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Load the state of the base class. bool result = ossimSource::loadState(kwl, prefix); // Get the filename... const char* lookup = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if(lookup) { ossimString filename = lookup; lookup = kwl.find(prefix, ossimKeywordNames::FILEPATH_KW); if(lookup) { filename = ossimString(lookup) + filename; } setFilename(filename); } lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_TYPE_KW); if(lookup) { if(ossimString(lookup).downcase().contains("area")) { thePixelType = OSSIM_PIXEL_IS_AREA; } else { thePixelType = OSSIM_PIXEL_IS_POINT; } } lookup = kwl.find(prefix, "linear_units"); if(lookup) { ossimUnitType units = (ossimUnitType)ossimUnitTypeLut::instance()-> getEntryNumber(lookup, true); if ( (units == OSSIM_METERS) || (units == OSSIM_FEET) || (units == OSSIM_US_SURVEY_FEET) ) { theLinearUnits = units; } } lookup = kwl.find(prefix, ossimKeywordNames::CREATE_EXTERNAL_GEOMETRY_KW); if(lookup) { ossimString s = lookup; theWriteExternalGeometryFlag = s.toBool(); } lookup = kwl.find(prefix, "create_envi_hdr"); if(lookup) { ossimString s = lookup; theWriteEnviHeaderFlag = s.toBool(); } lookup = kwl.find(prefix, "create_ers_hdr"); if(lookup) { ossimString s = lookup; theWriteErsHeaderFlag = s.toBool(); } lookup = kwl.find(prefix, "create_fgdc"); if(lookup) { ossimString s = lookup; theWriteFgdcFlag = s.toBool(); } lookup = kwl.find(prefix, "create_jpeg_world_file"); if(lookup) { ossimString s = lookup; theWriteJpegWorldFileFlag = s.toBool(); } lookup = kwl.find(prefix, "create_readme"); if(lookup) { ossimString s = lookup; theWriteReadmeFlag = s.toBool(); } lookup = kwl.find(prefix, "create_tiff_world_file"); if(lookup) { ossimString s = lookup; theWriteTiffWorldFileFlag = s.toBool(); } lookup = kwl.find(prefix, "create_world_file"); if(lookup) { ossimString s = lookup; theWriteWorldFileFlag = s.toBool(); } lookup = kwl.find(prefix, ossimKeywordNames::CREATE_IMAGE_KW); if(lookup) { ossimString s = lookup; theWriteImageFlag = s.toBool(); } lookup = kwl.find(prefix, ossimKeywordNames::CREATE_OVERVIEW_KW); if(lookup) { ossimString s = lookup; theWriteOverviewFlag = s.toBool(); } lookup = kwl.find(prefix, ossimKeywordNames::CREATE_HISTOGRAM_KW); if(lookup) { ossimString s = lookup; theWriteHistogramFlag = s.toBool(); } lookup = kwl.find(prefix, SCALE_TO_EIGHT_BIT_KW); if(lookup) { ossimString s = lookup; theScaleToEightBitFlag = s.toBool(); } lookup = kwl.find(prefix, AUTO_CREATE_DIRECTORY_KW); if(lookup) { theAutoCreateDirectoryFlag = ossimString(lookup).toBool(); } lookup = kwl.find(prefix, ossimKeywordNames::OVERVIEW_COMPRESSION_TYPE_KW); if(lookup) { ossimString s = lookup; theOverviewCompressType = static_cast(s.toUInt32()); } lookup = kwl.find(prefix, ossimKeywordNames::OVERVIEW_COMPRESSION_QUALITY_KW); if(lookup) { ossimString s = lookup; theOverviewJpegCompressQuality = s.toInt32(); } const char* outputImageType = kwl.find(prefix, ossimKeywordNames::IMAGE_TYPE_KW); if(outputImageType) { theOutputImageType = outputImageType; } if(theInputObjectList.size() != 2) { theInputObjectList.resize(2); theInputListIsFixedFlag = true; } theOutputListIsFixedFlag = false; return result; } bool ossimImageFileWriter::writeOverviewFile(ossim_uint16 tiff_compress_type, ossim_int32 jpeg_compress_quality, bool includeR0) { if(theFilename == "") return false; // Get an image handler for the source file. ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(theFilename); if (ih.valid() == false) { // Set the error... return false; } ossimRefPtr ob = new ossimTiffOverviewBuilder(); if ( ob->setInputSource(ih.get()) ) { // Give the listener to the overview builder if set. if (theProgressListener) { ob->addListener(theProgressListener); } // Build a new file name for the overview. ossimFilename overview_file = theFilename; overview_file.setExtension(ossimString("ovr")); ob->setCompressionType(tiff_compress_type); ob->setJpegCompressionQuality(jpeg_compress_quality); ob->setOutputFile(overview_file); ob->setCopyAllFlag(includeR0); ob->execute(); // Remove the listener from the overview builder. if (theProgressListener) { ob->removeListener(theProgressListener); } } return true; } bool ossimImageFileWriter::writeEnviHeaderFile() { if( (theFilename == "") || !theInputConnection || theAreaOfInterest.hasNans()) { return false; } // Make the file name. ossimFilename outputFile = theFilename; outputFile.setExtension(ossimString("hdr")); // Make the writer. ossimRefPtr writer = new ossimEnviHeaderFileWriter(); // Set things up. writer->connectMyInputTo(0, theInputConnection.get()); writer->initialize(); writer->setFilename(outputFile); writer->setPixelType(thePixelType); writer->setAreaOfInterest(theAreaOfInterest); // Write it to disk. return writer->execute(); } bool ossimImageFileWriter::writeErsHeaderFile() { if( (theFilename == "") || !theInputConnection || theAreaOfInterest.hasNans()) { return false; } // Make the file name. ossimFilename outputFile = theFilename; outputFile.setExtension(ossimString("ers")); // Make the writer. ossimRefPtr writer = new ossimERSFileWriter(); // Set things up. writer->connectMyInputTo(0, theInputConnection.get()); writer->initialize(); writer->setFilename(outputFile); writer->setPixelType(thePixelType); writer->setAreaOfInterest(theAreaOfInterest); // Write it to disk. return writer->execute(); } bool ossimImageFileWriter::writeExternalGeometryFile() { if( (theFilename == "") || !theInputConnection || theAreaOfInterest.hasNans()) { return false; } // Make the file name. ossimFilename geomFile = theFilename; geomFile.setExtension(ossimString("geom")); // Make the writer. ossimRefPtr writer = new ossimGeomFileWriter(); // Set things up. // writer->connectMyInputTo(0, theInputConnection.get()); writer->connectMyInputTo(0, theInputConnection.get()); writer->setFilename(geomFile); writer->initialize(); writer->setPixelType(thePixelType); writer->setAreaOfInterest(theAreaOfInterest); // Write it to disk. return writer->execute(); } bool ossimImageFileWriter::writeFgdcFile() { if( (theFilename == "") || !theInputConnection || theAreaOfInterest.hasNans()) { return false; } // Make the file name. ossimFilename outputFile = theFilename; outputFile.setExtension(ossimString("xml")); // Make the writer. ossimRefPtr writer = new ossimFgdcFileWriter(); // Set things up. writer->connectMyInputTo(0, theInputConnection.get()); writer->initialize(); writer->setFilename(outputFile); writer->setPixelType(thePixelType); writer->setAreaOfInterest(theAreaOfInterest); // Write it to disk. return writer->execute(); } bool ossimImageFileWriter::writeJpegWorldFile() { if(theFilename == "") { return false; } // Make the file name. ossimFilename file = theFilename; file.setExtension(ossimString("jpw")); // jpw??? return writeWorldFile(file); } bool ossimImageFileWriter::writeReadmeFile() { if( (theFilename == "") || !theInputConnection || theAreaOfInterest.hasNans()) { return false; } // Make the file name. ossimFilename outputFile = theFilename.noExtension(); outputFile += "_readme.txt"; // Make the writer. ossimRefPtr writer = new ossimReadmeFileWriter(); // Set things up. writer->connectMyInputTo(0, theInputConnection.get()); writer->initialize(); writer->setFilename(outputFile); writer->setPixelType(thePixelType); writer->setAreaOfInterest(theAreaOfInterest); // Write it to disk. return writer->execute(); } bool ossimImageFileWriter::writeTiffWorldFile() { if(theFilename == "") { return false; } // Make the file name. ossimFilename file = theFilename; file.setExtension(ossimString("tfw")); return writeWorldFile(file); } bool ossimImageFileWriter::writeMetaDataFiles() { bool status = true; if(theWriteEnviHeaderFlag&&!needsAborting()) { if(writeEnviHeaderFile() == false) { status = false; ossimNotify(ossimNotifyLevel_WARN) << "Write of envi header file failed!" << endl; } } if(theWriteErsHeaderFlag&&!needsAborting()) { if(writeErsHeaderFile() == false) { status = false; ossimNotify(ossimNotifyLevel_WARN) << "Write of ers header file failed!" << endl; } } if (theWriteExternalGeometryFlag&&!needsAborting()) { if( writeExternalGeometryFile() == false) { status = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Write of geometry file failed!" << endl; } } } if(theWriteFgdcFlag&&!needsAborting()) { if(writeFgdcFile() == false) { status = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Write of fgdc file failed!" << endl; } } } if(theWriteJpegWorldFileFlag&&!needsAborting()) { if(writeJpegWorldFile() == false) { status = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Write of jpeg world file failed!" << endl; } } } if(theWriteReadmeFlag&&!needsAborting()) { if(writeReadmeFile() == false) { status = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Write of readme file failed!" << endl; } } } if(theWriteTiffWorldFileFlag&&!needsAborting()) { if(writeTiffWorldFile() == false) { status = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Write of tiff world file failed!" << endl; } } } if(theWriteWorldFileFlag&&!needsAborting()) { if(writeWorldFile() == false) { status = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Write of world file failed!" << endl; } } } if (theWriteHistogramFlag&&!needsAborting()) { if (!writeHistogramFile()) { status = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Write of histogram file failed!" << endl; } } } return status; } bool ossimImageFileWriter::writeHistogramFile() { if(needsAborting()) return false; if(theFilename == "") return false; ossimFilename histogram_file = theFilename; histogram_file.setExtension(ossimString("his")); ossimRefPtr handler = ossimImageHandlerRegistry::instance()-> open(theFilename); if (!handler) { return false; } ossimRefPtr histoSource = new ossimImageHistogramSource; ossimRefPtr writer = new ossimHistogramWriter; histoSource->setMaxNumberOfRLevels(1); // Only compute for r0. histoSource->connectMyInputTo(0, handler.get()); histoSource->enableSource(); writer->connectMyInputTo(0, histoSource.get()); writer->setFilename(histogram_file); writer->addListener(&theStdOutProgress); writer->execute(); writer->disconnect(); histoSource->disconnect(); handler->disconnect(); writer = 0; histoSource = 0; handler = 0; return true; } void ossimImageFileWriter::disconnectInputEvent(ossimConnectionEvent& /* event */) { if(!getInput(0)) { theInputConnection->disconnectMyInput((ossim_int32)0, false); } theViewController = PTR_CAST(ossimViewController, getInput(1)); initialize(); } void ossimImageFileWriter::connectInputEvent(ossimConnectionEvent& /* event */) { theInputConnection->connectMyInputTo((ossim_int32)0, getInput(0), false); theViewController = PTR_CAST(ossimViewController, getInput(1)); initialize(); } void ossimImageFileWriter::propertyEvent(ossimPropertyEvent& /* event */) { initialize(); } void ossimImageFileWriter::setOutputImageType(const ossimString& type) { theOutputImageType = type; } void ossimImageFileWriter::setOutputImageType(ossim_int32 type) { ossimImageTypeLut lut; theOutputImageType = lut.getEntryString(type); } ossimString ossimImageFileWriter::getOutputImageTypeString() const { return theOutputImageType; } ossim_int32 ossimImageFileWriter::getOutputImageType() const { ossimImageTypeLut lut; return lut.getEntryNumber(theOutputImageType); } bool ossimImageFileWriter::getWriteImageFlag() const { return theWriteImageFlag; } bool ossimImageFileWriter::getWriteHistogramFlag() const { return theWriteHistogramFlag; } bool ossimImageFileWriter::getWriteOverviewFlag() const { return theWriteOverviewFlag; } bool ossimImageFileWriter::getScaleToEightBitFlag() const { return theScaleToEightBitFlag; } bool ossimImageFileWriter::getWriteEnviHeaderFlag() const { return theWriteEnviHeaderFlag; } bool ossimImageFileWriter::getWriteErsHeaderFlag() const { return theWriteErsHeaderFlag; } bool ossimImageFileWriter::getWriteExternalGeometryFlag() const { return theWriteExternalGeometryFlag; } bool ossimImageFileWriter::getWriteFgdcFlag() const { return theWriteFgdcFlag; } bool ossimImageFileWriter::getWriteJpegWorldFileFlag() const { return theWriteJpegWorldFileFlag; } bool ossimImageFileWriter::getWriteReadmeFlag() const { return theWriteReadmeFlag; } bool ossimImageFileWriter::getWriteTiffWorldFileFlag() const { return theWriteTiffWorldFileFlag; } bool ossimImageFileWriter::getWriteWorldFileFlag() const { return theWriteWorldFileFlag; } void ossimImageFileWriter::setWriteOverviewFlag(bool flag) { theWriteOverviewFlag = flag; } void ossimImageFileWriter::setWriteImageFlag(bool flag) { theWriteImageFlag = flag; } void ossimImageFileWriter::setWriteHistogramFlag(bool flag) { theWriteHistogramFlag = flag; } void ossimImageFileWriter::setScaleToEightBitFlag(bool flag) { theScaleToEightBitFlag = flag; } void ossimImageFileWriter::setWriteEnviHeaderFlag(bool flag) { theWriteEnviHeaderFlag = flag; } void ossimImageFileWriter::setWriteErsHeaderFlag(bool flag) { theWriteErsHeaderFlag = flag; } void ossimImageFileWriter::setWriteExternalGeometryFlag(bool flag) { theWriteExternalGeometryFlag = flag; } void ossimImageFileWriter::setWriteFgdcFlag(bool flag) { theWriteFgdcFlag = flag; } void ossimImageFileWriter::setWriteJpegWorldFile(bool flag) { theWriteJpegWorldFileFlag = flag; } void ossimImageFileWriter::setWriteReadme(bool flag) { theWriteReadmeFlag = flag; } void ossimImageFileWriter::setWriteTiffWorldFile(bool flag) { theWriteTiffWorldFileFlag = flag; } void ossimImageFileWriter::setWriteWorldFile(bool flag) { theWriteWorldFileFlag = flag; } ossimObject* ossimImageFileWriter::getObject() { return this; } const ossimObject* ossimImageFileWriter::getObject() const { return this; } void ossimImageFileWriter::setAreaOfInterest(const ossimIrect& inputRect) { // This sets "theAreaOfInterest". ossimImageWriter::setAreaOfInterest(inputRect); if( theInputConnection.valid() ) { //--- // ossimImageSourceSequencer::setAreaOfInterest does more than just set the // variable, so only call if out of sync to avoid wasted cycles. //--- if ( theAreaOfInterest != theInputConnection->getBoundingRect() ) { // Set the sequencer area of interest. theInputConnection->setAreaOfInterest(inputRect); } } } ossimImageSourceSequencer* ossimImageFileWriter::getSequencer() { return theInputConnection.get(); } bool ossimImageFileWriter::execute() { static const char MODULE[] = "ossimImageFileWriter::execute"; if (!theInputConnection) // Must have a sequencer... { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:\ntheInputConnection is NULL!" << endl; } return false; } if (theFilename == "") // Must have a filename... { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:\ntheFilename is empty!" << endl; } return false; } // make sure we have a region of interest if(theAreaOfInterest.hasNans()) { theInputConnection->initialize(); theAreaOfInterest = theInputConnection->getAreaOfInterest(); } else { theInputConnection->setAreaOfInterest(theAreaOfInterest); } if(theAreaOfInterest.hasNans()) // Must have an area of interest... { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR: Area of interest has nans!" << "Area of interest: " << theAreaOfInterest << "\nReturning..." << endl; } return false; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:\n" << "Area of interest: " << theAreaOfInterest << endl; } ossimRefPtr savedInput; if (theScaleToEightBitFlag) { if(theInputConnection->getOutputScalarType() != OSSIM_UINT8) { savedInput = new ossimScalarRemapper; savedInput->connectMyInputTo(0, theInputConnection->getInput(0)); theInputConnection->connectMyInputTo(0, savedInput.get()); theInputConnection->initialize(); } } ossimFilename path = theFilename.path(); if (!path.empty() && !path.exists() ) { path.createDirectory(true); } setProcessStatus(ossimProcessInterface::PROCESS_STATUS_EXECUTING); //setPercentComplete(0.0); let writeFile set the precent complete bool wroteFile = true; bool result = true; if (theWriteImageFlag) { wroteFile = writeFile(); } /* if(needsAborting()) { setProcessStatus(ossimProcessInterface::PROCESS_STATUS_ABORTED); } else { setProcessStatus(ossimProcessInterface::PROCESS_STATUS_NOT_EXECUTING); } */ if (theWriteOverviewFlag&&!needsAborting()) { // Writing overviews has been mpi'd so do on all processes. if (!writeOverviewFile(theOverviewCompressType, theOverviewJpegCompressQuality)) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Write of overview file failed!" << endl; } } } if(!needsAborting()) { // Do these only on the master process. Note left to right precedence! if (getSequencer() && getSequencer()->isMaster()) { if (wroteFile) { if (writeMetaDataFiles() == false) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Write of metadata file failed!" << endl; } result = false; } } } // End of "if (getSequencer() && getSequencer()->isMaster())) } if(savedInput.valid()) { ossimConnectableObject* obj = theInputConnection->getInput(0); if(obj) { theInputConnection->connectMyInputTo(0, obj->getInput(0)); } } if(!needsAborting()) { setProcessStatus(ossimProcessInterface::PROCESS_STATUS_NOT_EXECUTING); } else { setProcessStatus(ossimProcessInterface::PROCESS_STATUS_ABORTED); } savedInput = 0; return result; } bool ossimImageFileWriter::writeStream() { //--- // Not implemented in this class. Derived classed should implement if // they can write to a stream. //--- return false; } ossimRefPtr ossimImageFileWriter::getOutputStream() const { //--- // Not implemented in this class. Derived classed should implement if // they can write to a stream. //--- return ossimRefPtr(); } bool ossimImageFileWriter::setOutputStream( ossimRefPtr /* stream */ ) { //--- // Not implemented in this class. Derived classed should implement if // they can write to a stream. //--- return false; } bool ossimImageFileWriter::setOutputStream(std::ostream& /* str */) { //--- // Not implemented in this class. Derived classed should implement if // they can write to a stream. //--- return false; } void ossimImageFileWriter::setPercentComplete(double percentComplete) { ossimProcessInterface::setPercentComplete(percentComplete); ossimProcessProgressEvent event(this, percentComplete); fireEvent(event); } void ossimImageFileWriter::setOutputName(const ossimString& outputName) { ossimImageWriter::setOutputName(outputName); setFilename(ossimFilename(outputName)); } void ossimImageFileWriter::setFilename(const ossimFilename& file) { theFilename = file; } const ossimFilename& ossimImageFileWriter::getFilename()const { return theFilename; } bool ossimImageFileWriter::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const { return (object&& ( (PTR_CAST(ossimImageSource, object)&&inputIndex == 0)|| (PTR_CAST(ossimViewController, object)&&inputIndex == 1)) ); } ossim_uint16 ossimImageFileWriter::getOverviewCompressType() const { return theOverviewCompressType; } ossim_int32 ossimImageFileWriter::getOverviewJpegCompressQuality() const { return theOverviewJpegCompressQuality; } void ossimImageFileWriter::setOverviewCompressType(ossim_uint16 type) { theOverviewCompressType = type; } void ossimImageFileWriter::setOverviewJpegCompressQuality(ossim_int32 quality) { theOverviewJpegCompressQuality = quality; } void ossimImageFileWriter::setProperty(ossimRefPtr property) { if(!property) return; if(property->getName() == ossimKeywordNames::FILENAME_KW) { theFilename = property->valueToString(); } else if (property->getName() == "create_envi_hdr") { theWriteEnviHeaderFlag = property->valueToString().toBool(); } else if (property->getName() == "create_ers_hdr") { theWriteErsHeaderFlag = property->valueToString().toBool(); } else if (property->getName() == ossimKeywordNames::CREATE_EXTERNAL_GEOMETRY_KW) { theWriteExternalGeometryFlag = property->valueToString().toBool(); } else if (property->getName() == "create_fgdc") { theWriteFgdcFlag = property->valueToString().toBool(); } else if (property->getName() == "create_jpeg_world_file") { theWriteJpegWorldFileFlag = property->valueToString().toBool(); } else if (property->getName() == "create_readme") { theWriteReadmeFlag = property->valueToString().toBool(); } else if (property->getName() == "create_tiff_world_file") { theWriteTiffWorldFileFlag = property->valueToString().toBool(); } else if (property->getName() == "create_world_file") { theWriteWorldFileFlag = property->valueToString().toBool(); } else if (property->getName() == ossimKeywordNames::CREATE_IMAGE_KW) { theWriteImageFlag = property->valueToString().toBool(); } else if (property->getName() == ossimKeywordNames::CREATE_OVERVIEW_KW) { theWriteOverviewFlag = property->valueToString().toBool(); } else if (property->getName() == ossimKeywordNames::CREATE_HISTOGRAM_KW) { theWriteHistogramFlag = property->valueToString().toBool(); } else if (property->getName() == SCALE_TO_EIGHT_BIT_KW) { theScaleToEightBitFlag = property->valueToString().toBool(); } else if(property->getName() == AUTO_CREATE_DIRECTORY_KW) { theAutoCreateDirectoryFlag = property->valueToString().toBool(); } else if (property->getName() == "linear_units") { theLinearUnits = (ossimUnitType) (ossimUnitTypeLut::instance()-> getEntryNumber(property->valueToString())); } else if(property->getName() == ossimKeywordNames::IMAGE_TYPE_KW) { setOutputImageType(property->valueToString()); } else if(property->getName() == ossimKeywordNames::PIXEL_TYPE_KW) { ossimStringProperty* stringProperty = PTR_CAST(ossimStringProperty, property.get()); if (stringProperty) { ossimString s; stringProperty->valueToString(s); setPixelType(s); } } else { ossimImageWriter::setProperty(property); } } ossimRefPtr ossimImageFileWriter::getProperty(const ossimString& name)const { if(name == ossimKeywordNames::FILENAME_KW) { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, theFilename); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_OUTPUT); return filenameProp; } else if(name == ossimKeywordNames::IMAGE_TYPE_KW) { ossimStringProperty* prop = new ossimStringProperty(name, theOutputImageType, false); std::vector typeList; getImageTypeList(typeList); if(typeList.size() > 1) { prop->setReadOnlyFlag(false); prop->setConstraints(typeList); prop->setChangeType(ossimProperty::ossimPropertyChangeType_AFFECTS_OTHERS); } else { prop->setReadOnlyFlag(true); } return prop; } else if(name == AUTO_CREATE_DIRECTORY_KW) { return new ossimBooleanProperty(name, theAutoCreateDirectoryFlag); } else if (name == "create_envi_hdr") { return new ossimBooleanProperty(name, theWriteEnviHeaderFlag); } else if (name == "create_ers_hdr") { return new ossimBooleanProperty(name, theWriteErsHeaderFlag); } else if (name == ossimKeywordNames::CREATE_EXTERNAL_GEOMETRY_KW) { return new ossimBooleanProperty(name, theWriteExternalGeometryFlag); } else if (name == "create_fgdc") { return new ossimBooleanProperty(name, theWriteFgdcFlag); } else if (name == "create_jpeg_world_file") { return new ossimBooleanProperty(name, theWriteJpegWorldFileFlag); } else if (name == "create_readme") { return new ossimBooleanProperty(name, theWriteReadmeFlag); } else if (name == "create_tiff_world_file") { return new ossimBooleanProperty(name, theWriteTiffWorldFileFlag); } else if (name == "create_world_file") { return new ossimBooleanProperty(name, theWriteWorldFileFlag); } else if (name == ossimKeywordNames::CREATE_IMAGE_KW) { return new ossimBooleanProperty(name, theWriteImageFlag); } else if (name == ossimKeywordNames::CREATE_OVERVIEW_KW) { return new ossimBooleanProperty(name, theWriteOverviewFlag); } else if (name == ossimKeywordNames::CREATE_HISTOGRAM_KW) { return new ossimBooleanProperty(name, theWriteHistogramFlag); } else if (name == SCALE_TO_EIGHT_BIT_KW) { return new ossimBooleanProperty(name, theScaleToEightBitFlag); } else if (name == "linear_units") { // property value ossimString value = ossimUnitTypeLut::instance()-> getEntryString(theLinearUnits); //--- // theLinearUnits is set to unknown as a default. This keys the // writer to use whatever makes sense for the given output. // Since "unknown" is a bad name to present to users, we will // use "default" if theLinearUnits is == "unknown". //--- if (value == "unknown") { value = "default"; } // constraint list vector constraintList; constraintList.push_back(ossimString("default")); constraintList.push_back(ossimString("meters")); constraintList.push_back(ossimString("feet")); constraintList.push_back(ossimString("us_survey_feet")); return new ossimStringProperty(name, value, false, // not editable constraintList); } else if (name == ossimKeywordNames::PIXEL_TYPE_KW) { ossimString value; getPixelTypeString(value); ossimStringProperty* stringProp = new ossimStringProperty(name, value, false); // editable flag stringProp->addConstraint(ossimString("point")); stringProp->addConstraint(ossimString("area")); return stringProp; } return ossimImageWriter::getProperty(name); } void ossimImageFileWriter::getPropertyNames(std::vector& propertyNames)const { ossimImageWriter::getPropertyNames(propertyNames); propertyNames.push_back(ossimString(ossimKeywordNames::FILENAME_KW)); propertyNames.push_back(ossimString("create_envi_hdr")); propertyNames.push_back(ossimString(ossimKeywordNames::CREATE_EXTERNAL_GEOMETRY_KW)); propertyNames.push_back(ossimString("create_fgdc")); propertyNames.push_back(ossimString("create_jpeg_world_file")); propertyNames.push_back(ossimString("create_readme")); propertyNames.push_back(ossimString("create_tiff_world_file")); propertyNames.push_back(ossimString("create_world_file")); propertyNames.push_back(ossimString(ossimKeywordNames::CREATE_IMAGE_KW)); propertyNames.push_back(ossimString(ossimKeywordNames::CREATE_OVERVIEW_KW)); propertyNames.push_back(ossimString(ossimKeywordNames::CREATE_HISTOGRAM_KW)); propertyNames.push_back(ossimString(AUTO_CREATE_DIRECTORY_KW)); propertyNames.push_back(ossimString(SCALE_TO_EIGHT_BIT_KW)); propertyNames.push_back(ossimString("linear_units")); propertyNames.push_back(ossimString(ossimKeywordNames::PIXEL_TYPE_KW)); propertyNames.push_back(ossimString(ossimKeywordNames::IMAGE_TYPE_KW)); } ossimString ossimImageFileWriter::getExtension() const { // default unknown file extension return ossimString("ext"); } bool ossimImageFileWriter::getOutputHasInternalOverviews( void ) const { // default value: don't assume internal overviews will // be generated by image writers. return false; } bool ossimImageFileWriter::hasImageType(const ossimString& imageType) const { std::vector imageTypeList; getImageTypeList(imageTypeList); std::vector::const_iterator i = imageTypeList.begin(); while (i != imageTypeList.end()) { if ( (*i) == imageType ) { return true; } ++i; } return false; // not found... } bool ossimImageFileWriter::addListener(ossimListener* listener) { theProgressListener = listener; return ossimImageWriter::addListener(listener); } bool ossimImageFileWriter::removeListener(ossimListener* listener) { if (listener == theProgressListener) { theProgressListener = NULL; } return ossimImageWriter::removeListener(listener); } void ossimImageFileWriter::setPixelType(ossimPixelType type) { thePixelType = type; } void ossimImageFileWriter::setPixelType(const ossimString& type) { ossimString s = type; s.downcase(); if (s == "point") { setPixelType(OSSIM_PIXEL_IS_POINT); } else if (s == "area") { setPixelType(OSSIM_PIXEL_IS_AREA); } } ossimPixelType ossimImageFileWriter::getPixelType() const { return thePixelType; } void ossimImageFileWriter::getPixelTypeString(ossimString& type) const { if (thePixelType == OSSIM_PIXEL_IS_POINT) { type = "point"; } else { type = "area"; } } void ossimImageFileWriter::setTileSize(const ossimIpt& tileSize) { if (theInputConnection.valid()) { theInputConnection->setTileSize(tileSize); } } bool ossimImageFileWriter::writeWorldFile() { bool result = false; if( theFilename.size() ) { // Make the file name. ossimFilename file = theFilename; ossimString ext = file.ext().downcase(); ossimString wfExt = ""; // World file extension. if ( ( ext == "tif" ) || ( ext == "tiff" ) ) { wfExt = "tfw"; } else if ( ( ext == "jpg" ) || ( ext == "jpeg" ) ) { wfExt = "jpw"; } else if ( ext == "png" ) { wfExt = "pgw"; } else if ( ext == "sid" ) { wfExt = "sdw"; } if ( ext.size() ) { file.setExtension(wfExt); result = writeWorldFile(file); } else { ossimNotify(ossimNotifyLevel_WARN) << "Could not derive world file extension for: " << theFilename << "\n"; } } if ( !result ) { ossimNotify(ossimNotifyLevel_WARN) << "Write of world file failed!\n"; } return result; } bool ossimImageFileWriter::writeWorldFile(const ossimFilename& file) { if( !theInputConnection || theAreaOfInterest.hasNans()) { return false; } // Make the writer. ossimRefPtr writer = new ossimWorldFileWriter(); // Set things up. writer->connectMyInputTo(0, theInputConnection.get()); writer->initialize(); writer->setFilename(file); writer->setAreaOfInterest(theAreaOfInterest); writer->setLinearUnits(theLinearUnits); writer->setPixelType(thePixelType); // Write it to disk. return writer->execute(); } ossim-Miami-2.9.1/src/imaging/ossimImageGaussianFilter.cpp000066400000000000000000000152031352751253100235600ustar00rootroot00000000000000//******************************************************************* // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // class ossimImageGaussianFilter : tile source //******************************************************************* // $Id: ossimImageGaussianFilter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include using namespace std; RTTI_DEF1(ossimImageGaussianFilter, "ossimImageGaussianFilter", ossimImageSourceFilter); /** * property names */ static const char* PROPERTYNAME_GAUSSSTD = "GaussStd"; static const char* PROPERTYNAME_STRICTNODATA = "StrictNoData"; ossimImageGaussianFilter::ossimImageGaussianFilter() : ossimImageSourceFilter(), theGaussStd(0.5), theStrictNoData(true) { // ingredients: // 2x ConvolutionFilter1D theHF=new ossimConvolutionFilter1D(); theVF=new ossimConvolutionFilter1D(); theHF->setIsHorizontal(true); theVF->setIsHorizontal(false); updateKernels(); theHF->setStrictNoData(theStrictNoData); theVF->setStrictNoData(theStrictNoData); //tie them up theVF->connectMyInputTo(0,theHF.get()); } ossimImageGaussianFilter::~ossimImageGaussianFilter() { if(theHF.valid()) { theHF->disconnect(); theHF = 0; } if(theVF.valid()) { theVF->disconnect(); theVF = 0; } } void ossimImageGaussianFilter::setProperty(ossimRefPtr property) { if(!property) return; if (property->getName() == PROPERTYNAME_GAUSSSTD) { ossimNumericProperty* sProperty = PTR_CAST(ossimNumericProperty, property.get()); if(sProperty) { setGaussStd(sProperty->asFloat64()); } } else if (property->getName() == PROPERTYNAME_STRICTNODATA) { ossimBooleanProperty* booleanProperty = PTR_CAST(ossimBooleanProperty, property.get()); if(booleanProperty) { setStrictNoData(booleanProperty->getBoolean()); } } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimImageGaussianFilter::getProperty(const ossimString& name)const { if (name == PROPERTYNAME_GAUSSSTD) { ossimNumericProperty* property = new ossimNumericProperty(name,ossimString::toString(getGaussStd()),1e-13,100.0); property->setCacheRefreshBit(); return property; } else if (name == PROPERTYNAME_STRICTNODATA) { ossimBooleanProperty* property = new ossimBooleanProperty(name,isStrictNoData()); property->setCacheRefreshBit(); return property; } return ossimImageSourceFilter::getProperty(name); } void ossimImageGaussianFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back(PROPERTYNAME_GAUSSSTD); propertyNames.push_back(PROPERTYNAME_STRICTNODATA); } bool ossimImageGaussianFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, PROPERTYNAME_GAUSSSTD, theGaussStd, true); kwl.add(prefix, PROPERTYNAME_STRICTNODATA, isStrictNoData()?"true":"false", //use string instead of boolean true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimImageGaussianFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* gs = kwl.find(prefix, PROPERTYNAME_GAUSSSTD); if(gs) { setGaussStd(ossimString(gs).toDouble()); } else { cerr<<"ossimImageGaussianFilter : warning no "<< PROPERTYNAME_GAUSSSTD<<" in loadState"<setStrictNoData(aStrict); theVF->setStrictNoData(aStrict); } void ossimImageGaussianFilter::initialize() { ossimImageSourceFilter::initialize(); initializeProcesses(); } ossimRefPtr ossimImageGaussianFilter::getTile(const ossimIrect &tileRect,ossim_uint32 resLevel) { if(isSourceEnabled()) { return theVF->getTile(tileRect, resLevel); } if(theInputConnection) { return theInputConnection->getTile(tileRect, resLevel); } return 0; } void ossimImageGaussianFilter::initializeProcesses() { theHF->initialize(); theVF->initialize(); } void ossimImageGaussianFilter::connectInputEvent(ossimConnectionEvent &event) { ossimImageSourceFilter::connectInputEvent(event); if(getInput()) { theHF->connectMyInputTo(0, getInput()); initializeProcesses(); } else { theHF->disconnectMyInput(0, false, false); initializeProcesses(); } } void ossimImageGaussianFilter::disconnectInputEvent(ossimConnectionEvent &event) { ossimImageSourceFilter::disconnectInputEvent(event); if(getInput()) { theHF->connectMyInputTo(0, getInput()); initializeProcesses(); } else { theHF->disconnectMyInput(0, false, false); initializeProcesses(); } } void ossimImageGaussianFilter::updateKernels() { //update kernels based on GaussStd value :2.5 sigma on each side // symetric kernel static const ossim_float64 sigmaN = 2.5; ossim_float64 sig22 = getGaussStd()*getGaussStd()*2.0; ossim_uint32 halfw = (ossim_uint32)(std::floor(getGaussStd() * sigmaN + 0.5)); ossim_uint32 supsize = 2*halfw + 1; //fill with sym. gaussian (unnormalized) vector newk(supsize); ossim_float64 sum=1.0; ossim_float64 v; newk[halfw] = 1.0; for(ossim_int32 i=(ossim_int32)halfw; i>0 ;--i) //reverse for summing { newk[halfw + i] = newk[halfw - i] = v = std::exp(-i*i/sig22); sum += 2.0 * v; } //normalize ossim_float64 invsum=1.0/sum; for(ossim_uint32 i=0; isetKernel(newk); theVF->setKernel(newk); theHF->setCenterOffset(halfw); theVF->setCenterOffset(halfw); } ossim-Miami-2.9.1/src/imaging/ossimImageGeometry.cpp000066400000000000000000001570111352751253100224370ustar00rootroot00000000000000//************************************************************************************************** // // License: MIT // // Author: Oscar Kramer // // Description: Class implementation of ossimImageGeometry. See .h file for class documentation. // //************************************************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimImageGeometry, "ossimImageGeometry", ossimObject); //************************************************************************************************** // Default constructor defaults to unity transform with no projection //************************************************************************************************** ossimImageGeometry::ossimImageGeometry() : m_transform (0), m_projection(0), m_decimationFactors(0), m_imageSize(), m_targetRrds(0) { m_imageSize.makeNan(); } //************************************************************************************************** // Copy constructor -- performs a deep copy. This is needed when an imageSource in the chain // needs to modify the image geometry at that point in the chain. The image geometry to the left // of that imageSource must remain unchanged. This constructor permits that imageSource to // maintain its own geometry based on the input geometry. All objects in the chain and to the right // would see this alternate geometry. See ossimScaleFilter for an example of this case. //************************************************************************************************** ossimImageGeometry::ossimImageGeometry(const ossimImageGeometry& copy_this) : ossimObject(copy_this), m_transform(copy_this.m_transform.valid()?(ossim2dTo2dTransform*)copy_this.m_transform->dup():((ossim2dTo2dTransform*)0)), m_projection(copy_this.m_projection.valid()?(ossimProjection*)copy_this.m_projection->dup():(ossimProjection*)0), m_decimationFactors(copy_this.m_decimationFactors), m_imageSize(copy_this.m_imageSize), m_targetRrds(copy_this.m_targetRrds) { } //************************************************************************************************** //! Constructs with projection and transform objects available for referencing. Either pointer //! can be NULL -- the associated mapping would be identity. //************************************************************************************************** ossimImageGeometry::ossimImageGeometry(ossim2dTo2dTransform* transform, ossimProjection* proj) : ossimObject(), m_transform(transform), m_projection(proj), m_decimationFactors(0), m_imageSize(), m_targetRrds(0) { m_imageSize.makeNan(); } //************************************************************************************************** // Destructor is hidden. Only accessible via ossimRefPtr centrally managed //************************************************************************************************** ossimImageGeometry::~ossimImageGeometry() { // Nothing to do } bool ossimImageGeometry::open(const ossimFilename& image) { ossimRefPtr handler = ossimImageHandlerRegistry::instance()->open(image); if (!handler.valid()) return false; ossimRefPtr geom = handler->getImageGeometry(); if (!geom.valid()) return false; *this = *geom; return true; } void ossimImageGeometry::rnToRn(const ossimDpt& inRnPt, ossim_uint32 inResolutionLevel, ossim_uint32 outResolutionLevel, ossimDpt& outRnPt) const { if (inResolutionLevel != outResolutionLevel) { // Back out the decimation. ossimDpt pt; undecimatePoint(inRnPt, inResolutionLevel, pt); // Decimate to new level. decimatePoint(pt, outResolutionLevel, outRnPt); } else { outRnPt = inRnPt; // No transform required. } } void ossimImageGeometry::rnToFull(const ossimDpt& rnPt, ossim_uint32 resolutionLevel, ossimDpt& fullPt) const { // Back out the decimation. ossimDpt localPt; undecimatePoint(rnPt, resolutionLevel, localPt); // Remove any shift/rotation. if ( m_transform.valid() && !localPt.hasNans() ) { m_transform->forward(localPt, fullPt); } else { fullPt = localPt; // No transform (shift/rotation) } } void ossimImageGeometry::fullToRn(const ossimDpt& fullPt, ossim_uint32 resolutionLevel, ossimDpt& rnPt) const { // Apply shift/rotation. ossimDpt localPt; if (m_transform.valid()) { m_transform->inverse(fullPt, localPt); } else { localPt = fullPt; // No transform (shift/rotation) } // Apply the decimation. decimatePoint(localPt, resolutionLevel, rnPt); } void ossimImageGeometry::rnToWorld(const ossimDpt& rnPt, ossim_uint32 resolutionLevel, ossimGpt& wpt) const { ossimDpt localPt; rnToRn(rnPt, resolutionLevel, m_targetRrds, localPt); localToWorld(localPt, wpt); } void ossimImageGeometry::worldToRn(const ossimGpt& wpt, ossim_uint32 resolutionLevel, ossimDpt& rnPt) const { ossimDpt localPt; worldToLocal(wpt, localPt); rnToRn(localPt, m_targetRrds, resolutionLevel, rnPt); } //************************************************************************************************** //! Exposes the 3D projection from image to world coordinates. The caller should verify that //! a valid projection exists before calling this method. Returns TRUE if a valid ground point //! is available in the ground_pt argument. This method depends on the existence of elevation //! information. If no DEM is available, the results will be incorrect or inaccurate. //************************************************************************************************** bool ossimImageGeometry::localToWorld(const ossimDpt& local_pt, ossimGpt& world_pt) const { //! Return a NAN point of no projection is defined: if (!m_projection.valid()) { world_pt.makeNan(); return false; } // First transform local pixel to full-image pixel: ossimDpt full_image_pt; rnToFull(local_pt, m_targetRrds, full_image_pt); // Perform projection to world coordinates: m_projection->lineSampleToWorld(full_image_pt, world_pt); // Put longitude between -180 and +180 and latitude between -90 and +90 if not so. // world_pt.wrap(); return true; } bool ossimImageGeometry::localToWorld(const ossimDrect& local_rect, ossimGrect& world_rect) const { ossimGpt gp1, gp2, gp3, gp4; if ( localToWorld(local_rect.ul(), gp1) && localToWorld(local_rect.ur(), gp2) && localToWorld(local_rect.lr(), gp3) && localToWorld(local_rect.ll(), gp4)) { world_rect = ossimGrect(gp1, gp2, gp3, gp4); return true; } return false; } //************************************************************************************************** //! Exposes the 3D projection from image to world coordinates given a constant height above //! ellipsoid. The caller should verify that a valid projection exists before calling this //! method. Returns TRUE if a valid ground point is available in the ground_pt argument. //************************************************************************************************** bool ossimImageGeometry::localToWorld(const ossimDpt& local_pt, const double& h_ellipsoid, ossimGpt& world_pt) const { //! Return a NAN point of no projection is defined: if (!m_projection.valid()) { world_pt.makeNan(); return false; } // First transform local pixel to full-image pixel: ossimDpt full_image_pt; rnToFull(local_pt, m_targetRrds, full_image_pt); // Perform projection to world coordinates: m_projection->lineSampleHeightToWorld(full_image_pt, h_ellipsoid, world_pt); // Put longitude between -180 and +180 and latitude between -90 and +90 if not so. world_pt.wrap(); return true; } //************************************************************************************************** //! Exposes the 3D world-to-local image coordinate reverse projection. The caller should verify //! that a valid projection exists before calling this method. Returns TRUE if a valid image //! point is available in the local_pt argument. //************************************************************************************************** bool ossimImageGeometry::worldToLocal(const ossimGpt& world_pt, ossimDpt& local_pt) const { bool result = true; if ( m_projection.valid() ) { //const ossimEquDistCylProjection* eqProj = // dynamic_cast( m_projection.get() ); ossimDpt full_image_pt; //***** GCP // I am having major problems with the call and is messing up on Image that are edge to edge -180 to 180. // It appears to wrap and think that the image is onl 1 pixel wide. I am commenting out for now // until a better solution can be done for points that wrap. We need a general implementation that will work // with any projector // //if ( eqProj && (m_imageSize.hasNans() == false) ) // { // Call specialized method to handle wrapping... // eqProj->worldToLineSample( world_pt, m_imageSize, full_image_pt ); // } // else if( isAffectedByElevation() ) if( isAffectedByElevation() ) { ossimGpt copyPt( world_pt ); if(world_pt.isHgtNan()) { copyPt.hgt = ossimElevManager::instance()->getHeightAboveEllipsoid(copyPt); } // Perform projection from world coordinates to full-image space: m_projection->worldToLineSample(copyPt, full_image_pt); } else { // Perform projection from world coordinates to full-image space: m_projection->worldToLineSample(world_pt, full_image_pt); } // Transform to local space: fullToRn(full_image_pt, m_targetRrds, local_pt); } else // No projection set: { local_pt.makeNan(); result = false; } return result; } // End: ossimImageGeometry::worldToLocal(const ossimGpt&, ossimDpt&) bool ossimImageGeometry::worldToLocal(const ossimGrect& world_rect, ossimDrect& local_rect) const { ossimDpt dp1, dp2, dp3, dp4; if ( worldToLocal(world_rect.ul(), dp1) && worldToLocal(world_rect.ur(), dp2) && worldToLocal(world_rect.lr(), dp3) && worldToLocal(world_rect.ll(), dp4)) { local_rect = ossimDrect(dp1, dp2, dp3, dp4); return true; } return false; } //************************************************************************************************** //! Sets the transform to be used for local-to-full-image coordinate transformation //************************************************************************************************** void ossimImageGeometry::setTransform(ossim2dTo2dTransform* transform) { m_transform = transform; } //************************************************************************************************** //! Sets the projection to be used for local-to-world coordinate transformation //************************************************************************************************** void ossimImageGeometry::setProjection(ossimProjection* projection) { m_projection = projection; } //************************************************************************************************** //! Returns TRUE if this geometry is sensitive to elevation //************************************************************************************************** bool ossimImageGeometry::isAffectedByElevation() const { if (m_projection.valid()) return m_projection->isAffectedByElevation(); return false; } //************************************************************************************************* //! Returns GSD in meters in x- and y-directions. This may not be the same as the member //! projection's stated resolution since a transform may be involved. //************************************************************************************************* ossimDpt ossimImageGeometry::getMetersPerPixel() const { ossimDpt gsd; getMetersPerPixel(gsd); return gsd; } //************************************************************************************************* //! Computes GSD in meters in x- and y-directions. This may not be the same as the member //! projection's stated resolution since a transform may be involved. //************************************************************************************************* void ossimImageGeometry::getMetersPerPixel( ossimDpt& gsd ) const { if (m_projection.valid() && !m_transform.valid()) { // No transform present, so simply query the projection for GSD: gsd = m_projection->getMetersPerPixel(); } else if (m_projection.valid() && (m_imageSize.hasNans() == false)) { // A transform is involved, so need to use localToWorld call below: ossimDpt pL0 (m_imageSize/2); ossimDpt pLx (pL0.x+1, pL0.y); ossimDpt pLy (pL0.x, pL0.y+1); ossimGpt g0, gx, gy; localToWorld(pL0, g0); localToWorld(pLx, g0.height(), gx); localToWorld(pLy, g0.height(), gy); // Compute horizontal distance for one pixel: gsd.x = g0.distanceTo(gx); gsd.y = g0.distanceTo(gy); } else { // This object is not fully initialized: gsd.makeNan(); } } //************************************************************************************************* // Returns the resolution of this image in degrees/pixel. Note that this only // makes sense if there is a projection associated with the image. Returns NaNs if no // projection defined. //************************************************************************************************* ossimDpt ossimImageGeometry::getDegreesPerPixel() const { ossimDpt dpp; getDegreesPerPixel(dpp); return dpp; } //************************************************************************************************* // Computes the resolution of this image in degrees/pixel. Note that this only // makes sense if there is a projection associated with the image. Returns NaNs if no // projection defined. //************************************************************************************************* void ossimImageGeometry::getDegreesPerPixel( ossimDpt& dpp ) const { const ossimMapProjection *map_proj = dynamic_cast(m_projection.get()); if (map_proj && !m_transform.valid()) { // No transform present, so simply query the projection for resolution: dpp = map_proj->getDecimalDegreesPerPixel(); } else if (m_projection.valid() && (m_imageSize.hasNans() == false)) { // A transform is involved, so need to use localToWorld call below: ossimDpt pL0 (m_imageSize/2); ossimDpt pLx (pL0.x+1, pL0.y); ossimDpt pLy (pL0.x, pL0.y+1); ossimGpt g0, gx, gy; localToWorld(pL0, g0); localToWorld(pLx, g0.height(), gx); localToWorld(pLy, g0.height(), gy); // Compute horizontal distance for one pixel: double dlatx = std::fabs(g0.lat - gx.lat); double dlaty = std::fabs(g0.lat - gy.lat); double dlonx = std::fabs(g0.lon - gx.lon); double dlony = std::fabs(g0.lon - gy.lon); dpp.lat = sqrt(dlatx*dlatx + dlaty*dlaty); dpp.lon = sqrt(dlonx*dlonx + dlony*dlony); } else { // This object is not fully initialized: dpp.makeNan(); } } //************************************************************************************************** //! Prints contents to output stream. //************************************************************************************************** std::ostream& ossimImageGeometry::print(std::ostream& out) const { out << "type: ossimImageGeometry" << std::endl; if(m_transform.valid()) { out << " m_transform: "; m_transform->print(out); } else { out << " No transform defined. Using identity transform.\n"; } if(m_projection.valid()) { out << " m_projection: "; m_projection->print(out); } else { out << " No projection defined. "; } for ( std::vector::size_type i = 0; i < m_decimationFactors.size(); ++i ) { cout << "m_decimationFactors[" << i << "]: " << m_decimationFactors[i] << "\n"; } out << "m_imageSize: " << m_imageSize << "\nm_targetRrds: " << m_targetRrds << "\n"; return out; } //************************************************************************************************** //! Returns TRUE if argument geometry has exactly the same instances for transform and //! m_projection. This may need to be expanded to permit different instances of same transforms //************************************************************************************************** bool ossimImageGeometry::operator==(const ossimImageGeometry& other) const { return ((m_transform == other.m_transform) && (m_projection == other.m_projection) && (decimationFactor(0) == other.decimationFactor(0)) ); } //************************************************************************************************** //! Returns the decimation factor from R0 for the resolution level specified. For r_index=0, the //! decimation factor is by definition 1.0. For the non-discrete case, r_index=1 returns a //! decimation of 0.5. If the vector of discrete decimation factors (m_decimationFactors) is //! empty, the factor will be computed as f=1/2^n //************************************************************************************************** ossimDpt ossimImageGeometry::decimationFactor(ossim_uint32 r_index) const { ossim_uint32 size = (ossim_uint32)m_decimationFactors.size(); if (size) { if (r_index < size) { return m_decimationFactors[r_index]; } // Return the last defined decimation if the index requested exceeds list size: return m_decimationFactors[size-1]; } // Compute the decimation factor: ossim_float64 factor = 1.0/(ossim_float64)(1 << r_index); return ossimDpt(factor, factor); } void ossimImageGeometry::decimationFactor(ossim_uint32 r_index, ossimDpt& result) const { const ossim_uint32 SIZE = (ossim_uint32)m_decimationFactors.size(); if (SIZE) { if (r_index < SIZE) { result = m_decimationFactors[r_index]; } else { //--- // Return the last defined decimation if the index requested // exceeds list size: //--- result = m_decimationFactors[SIZE-1]; } } else { // Compute the decimation factor: ossim_float64 factor = 1.0/(ossim_float64)(1 << r_index); result.x = factor; result.y = factor; } } void ossimImageGeometry::decimationFactors( std::vector& decimations) const { decimations = m_decimationFactors; } //***************************************************************************** //! Attempts to initialize a transform and a projection given the KWL. //! Returns TRUE if no error encountered. //***************************************************************************** bool ossimImageGeometry::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if (lookup) { if ( ossimString(lookup) == STATIC_TYPE_NAME(ossimImageGeometry) ) { ossimObject::loadState(kwl, prefix); // m_transform ossimString transformPrefix = ossimString(prefix) + "transform."; ossimRefPtr transform = ossim2dTo2dTransformRegistry::instance()-> createNativeObjectFromRegistry(kwl, transformPrefix.c_str()); if( transform.valid() ) { m_transform = transform; } // m_projection: ossimString projectionPrefix = ossimString(prefix) + "projection."; ossimRefPtr projection = ossimProjectionFactoryRegistry::instance()-> createProjection(kwl, projectionPrefix.c_str()); if( projection.valid() ) { m_projection = projection; } // m_decimationFactors: ossimString decimations = kwl.find(prefix, "decimations"); if( decimations.size() ) { m_decimationFactors.clear(); ossim::toVector(m_decimationFactors, decimations); } // m_imageSize: ossimString imageSize = kwl.find(prefix, "image_size"); if( imageSize.size() ) { m_imageSize.toPoint(imageSize); } // m_targetRrds: ossimString targetRrds = kwl.find(prefix, "target_rrds"); if ( targetRrds.size() ) { m_targetRrds = ossimString(targetRrds).toUInt32(); } } else { // Now look for projection spec (for backwards compatibility): ossimProjection* projection = ossimProjectionFactoryRegistry::instance()-> createProjection(kwl, prefix); if (projection) { setProjection(projection); } } } else { //--- // Old geometry file with no type keyword: //--- ossimProjection* projection = ossimProjectionFactoryRegistry::instance()-> createProjection(kwl, prefix); if (projection) { setProjection(projection); } } return true; } //************************************************************************************************** //! Saves the transform (if any) and projection (if any) states to the KWL. //************************************************************************************************** bool ossimImageGeometry::saveState(ossimKeywordlist& kwl, const char* prefix) const { bool good_save = true; // m_transform: if (m_transform.valid()) { ossimString transformPrefix = ossimString(prefix) + "transform."; good_save = m_transform->saveState(kwl, transformPrefix.c_str()); } // m_projection: if (m_projection.valid()) { ossimString projectionPrefix = ossimString(prefix) + "projection."; good_save &= m_projection->saveState(kwl, projectionPrefix.c_str()); } // m_gsd: ossimDpt gsd; getMetersPerPixel(gsd); kwl.add(prefix, "gsd", gsd.toString(), true); // m_decimationFactors: if(m_decimationFactors.size()) { ossimString resultPoints; ossim::toStringList(resultPoints, m_decimationFactors); kwl.add(prefix, "decimations", resultPoints, true); } else { kwl.add(prefix, "decimations", "", true); } // m_imageSize: kwl.add(prefix, "image_size", m_imageSize.toString(), true); // m_targetRrds; kwl.add(prefix, "target_rrds", m_targetRrds, true); // Base class: good_save &= ossimObject::saveState(kwl, prefix); return good_save; } void ossimImageGeometry::setTargetRrds(ossim_uint32 rrds) { m_targetRrds = rrds; } ossim_uint32 ossimImageGeometry::getTargetRrds() const { return m_targetRrds; } //************************************************************************************************** //! Replaces any existing transform and projection with those in the copy_this object //************************************************************************************************** const ossimImageGeometry& ossimImageGeometry::operator=(const ossimImageGeometry& copy_this) { if (this != ©_this) { // Get deep copy of 2D transform if one exists: if (copy_this.m_transform.valid()) { m_transform = (ossim2dTo2dTransform*) copy_this.m_transform->dup(); } // Now establish a deep copy of the projection, if any: if (copy_this.m_projection.valid()) { m_projection = (ossimProjection*) copy_this.m_projection->dup(); } // the Gsd should already be solved from the source we are copying from m_imageSize = copy_this.m_imageSize; m_decimationFactors = copy_this.m_decimationFactors; m_targetRrds = copy_this.m_targetRrds; } return *this; } //************************************************************************************************** //! Returns the ossimGpts for the four image corner points //************************************************************************************************** bool ossimImageGeometry::getCornerGpts(ossimGpt& gul, ossimGpt& gur, ossimGpt& glr, ossimGpt& gll) const { ossimDpt iul (0,0); ossimDpt iur (m_imageSize.x-1, 0); ossimDpt ilr (m_imageSize.x-1, m_imageSize.y-1); ossimDpt ill (0, m_imageSize.y-1); bool status = true; status &= localToWorld(iul, gul); status &= localToWorld(iur, gur); status &= localToWorld(ilr, glr); status &= localToWorld(ill, gll); return status; } void ossimImageGeometry::getTiePoint(ossimGpt& tie, bool edge) const { ossimGrect grect; getBoundingGroundRect(grect); if ( m_projection.valid() && (m_imageSize.hasNans() == false) ) { // Use the easting/northing version of this method if underlying projection is meters: const ossimMapProjection* map_proj = dynamic_cast(m_projection.get()); if (map_proj) { if(!map_proj->isGeographic()) { ossimDpt enTie; getTiePoint(enTie, edge); if (!enTie.hasNans()) tie = m_projection->inverse(enTie); else tie.makeNan(); } else { tie = grect.ul(); if(edge) { ossimDpt half_pixel_shift = map_proj->getDecimalDegreesPerPixel() * 0.5; tie.lat += half_pixel_shift.y; tie.lon -= half_pixel_shift.x; } } } else { // must be a sensor model so we will set to the upper left bounds of the image tie = grect.ul(); // std::cout << "GRECT ======= " << grect << "\n"; // std::cout << m_projection->getClassName() << std::endl; // ossimDpt pt = m_projection->forward( tie ); // std::cout << "FORWARD:" <(m_projection.get()); if (map_proj && !map_proj->isGeographic()) { ossimDpt enTie; getTiePoint(enTie, edge); if (!enTie.hasNans()) tie = m_projection->inverse(enTie); else tie.makeNan(); return; // return here only because it bugs Dave } // Use projection to ground to establish UL extreme of image: ossimDpt iul (0,0); ossimDpt iur (m_imageSize.x-1, 0); ossimDpt ilr (m_imageSize.x-1, m_imageSize.y-1); ossimDpt ill (0, m_imageSize.y-1); ossimDpt iRight(1, 0); ossimDpt iDown(0, 1); ossimGpt gul; ossimGpt gur; ossimGpt glr; ossimGpt gll; ossimGpt gRight; ossimGpt gDown; localToWorld(iul, gul); localToWorld(iur, gur); localToWorld(ilr, glr); localToWorld(ill, gll); localToWorld(iRight, gRight); localToWorld(iDown, gDown); std::cout << "gul: " << gul << "\n" << "gur: " << gur << "\n" << "glr: " << glr << "\n" << "gll: " << gll << "\n" << "gRight: " << gRight << "\n" << "gDown: " << gDown << "\n"; // Determine the direction of the image: if ( gul.lat > gDown.lat ) // oriented north up { if ( gul.lat >= gRight.lat ) // straight up or leaning right { std::cout << "ONE\n"; tie.lat = gul.lat; tie.lon = gll.lon; } else // leaning left { std::cout << "TWO\n"; tie.lat = gur.lat; tie.lon = gul.lon; } } else // south or on side { if ( gRight.lat >= gul.lat ) // straight down or leaning right { std::cout << "THREE\n"; tie.lat = glr.lat; tie.lon = gur.lon; } else // leaning left { std::cout << "FOUR\n"; tie.lat = gll.lat; tie.lon = glr.lon; } } std::cout << "TIE BEFORE ==== " << tie << "\n"; if ( edge ) { ossimDpt pt = m_projection->forward( tie ); ossimDpt half_pixel_shift = m_projection->getMetersPerPixel() * 0.5; pt.y += half_pixel_shift.y; pt.x -= half_pixel_shift.x; tie = m_projection->inverse( pt ); } std::cout << "TIE ==== " << tie << "\n"; } // if ( (m_imageSize.hasNans() == false) && m_projection.valid() ) else { tie.lat = ossim::nan(); tie.lon = ossim::nan(); } #endif } //************************************************************************************************** // Assigns tie to the UL easting northing of the image. If edge is true, the E/N will be for the // pixel-is-area representation //************************************************************************************************** void ossimImageGeometry::getTiePoint(ossimDpt& tie, bool edge) const { if (!m_projection.valid() || m_imageSize.hasNans()) { tie.makeNan(); return; // return here only because it bugs Dave } // Use the geographic version of this method if underlying projection is NOT map in meters: const ossimMapProjection* map_proj = dynamic_cast(m_projection.get()); if (!map_proj || map_proj->isGeographic()) { // Use the geographic version of this method to establish UL: ossimGpt gTie; gTie.hgt = 0.0; getTiePoint(gTie, edge); if (!gTie.hasNans()) tie = m_projection->forward( gTie ); else tie.makeNan(); return; // return here only because it bugs Dave } // The underlying projection is a proper map projection in meters. Use easting northing // directly to avoid shifting the UL tiepoint because of skewed edge in geographic. Note: // assume the image is North up: ossimDpt iul (0,0); ossimDpt ful; rnToFull(iul, 0, ful); map_proj->lineSampleToEastingNorthing(ful, tie); if (edge && !tie.hasNans()) { // Shift from pixel-is-point to pixel-is-area ossimDpt half_pixel_shift = map_proj->getMetersPerPixel() * 0.5; tie.y += half_pixel_shift.y; tie.x -= half_pixel_shift.x; } } //************************************************************************************************** void ossimImageGeometry::undecimatePoint(const ossimDpt& rnPt, ossim_uint32 resolutionLevel, ossimDpt& outPt) const { // Back out the decimation. ossimDpt decimation = decimationFactor(resolutionLevel); //--- // If no nans and one or both of the factors is not 1.0 decimation should // be applied. //--- if ( (decimation.x != 1.0) || (decimation.y != 1.0) ) { if ( !decimation.hasNans() && !rnPt.hasNans() ) { outPt.x = rnPt.x * (1.0/decimation.x); outPt.y = rnPt.y * (1.0/decimation.y); } else { outPt.makeNan(); } } else { outPt = rnPt; // No decimation. } } //************************************************************************************************** void ossimImageGeometry::decimatePoint(const ossimDpt& inPt, ossim_uint32 resolutionLevel, ossimDpt& rnPt) const { // Apply the decimation. ossimDpt decimation = decimationFactor(resolutionLevel); //--- // If no nans and one or both of the factors is not 1.0 decimation should // be applied. //--- if ( (decimation.x != 1.0) || (decimation.y != 1.0) ) { if ( !decimation.hasNans() && !inPt.hasNans() ) { rnPt.x = inPt.x * decimation.x; rnPt.y = inPt.y * decimation.y; } else { rnPt.makeNan(); } } else { rnPt = inPt; // No decimation. } } bool ossimImageGeometry::isEqualTo(const ossimObject& obj, ossimCompareType compareType)const { bool result = ossimObject::isEqualTo(obj, compareType); const ossimImageGeometry* rhs = dynamic_cast (&obj); if(rhs&&result) // we know the types are the same { result = ((m_decimationFactors.size() == rhs->m_decimationFactors.size())&& m_imageSize.isEqualTo(rhs->m_imageSize)&& (m_targetRrds == rhs->m_targetRrds)); if(result) { ossim_uint32 decimationIdx = 0; for(decimationIdx = 0; result&&(decimationIdx < m_decimationFactors.size());++decimationIdx) { result = m_decimationFactors[decimationIdx].isEqualTo(rhs->m_decimationFactors[decimationIdx]); } } if(result && compareType==OSSIM_COMPARE_IMMEDIATE) { result = ((m_transform.get() == rhs->m_transform.get())&& (m_projection.get() == rhs->m_projection.get())); //!< Maintains full_image-to-world_space transformation } else { if(m_transform.valid()&&rhs->m_transform.valid()) { result = m_transform->isEqualTo(*rhs->m_transform.get()); } else if(reinterpret_cast(m_transform.get()) | reinterpret_cast(rhs->m_transform.get())) // one is null { result = false; } if(m_projection.valid()&&rhs->m_projection.valid()) { result = m_projection->isEqualTo(*rhs->m_projection.get()); } else if(reinterpret_cast(m_projection.get()) | reinterpret_cast(rhs->m_projection.get())) // one is null { result = false; } } } return result; } bool ossimImageGeometry::getCrossesDateline()const { bool result = false; ossimIrect rect; ossimGpt ul; ossimGpt ur; ossimGpt lr; ossimGpt ll; ossimGpt center; ossimGpt wgs84; getBoundingRect(rect); localToWorld(rect.ul(), ul); localToWorld(rect.ur(), ur); localToWorld(rect.lr(), lr); localToWorld(rect.ll(), ll); localToWorld(rect.midPoint(), center); if(ul.isLonNan()||ur.isLonNan()||lr.isLonNan()||ll.isLonNan()||center.isLonNan()) { return result; } else { ul.changeDatum(wgs84.datum()); ur.changeDatum(wgs84.datum()); lr.changeDatum(wgs84.datum()); ll.changeDatum(wgs84.datum()); center.changeDatum(wgs84.datum()); result = ( (fabs(center.lond()-ul.lond()) > 180.0) || (fabs(center.lond()-ur.lond()) > 180.0) || (fabs(center.lond()-lr.lond()) > 180.0) || (fabs(center.lond()-ll.lond()) > 180.0) || (fabs(ul.lond()) > 180.0) || (fabs(ur.lond()) > 180.0) || (fabs(lr.lond()) > 180.0) || (fabs(ll.lond()) > 180.0) ); } return result; } void ossimImageGeometry::getImageEdgePoints(std::vector& result, ossim_uint32 partitions)const { ossimDrect imageRect; getBoundingRect(imageRect); if(imageRect.hasNans()) { // error out return; } // Make edge to edge. //imageRect.expand( ossimDpt(0.5, 0.5) ); result.clear(); // First get the image points we will be transforming if(partitions > 2) { ossimDpt uli = imageRect.ul(); ossimDpt uri = imageRect.ur(); ossimDpt lri = imageRect.lr(); ossimDpt lli = imageRect.ll(); ossim_float32 stepSize = partitions; ossimDpt deltaUpper = (uri-uli)*(1.0/stepSize); ossimDpt deltaRight = (lri-uri)*(1.0/stepSize); ossimDpt deltaLower = (lli-lri)*(1.0/stepSize); ossimDpt deltaLeft = (uli-lli)*(1.0/stepSize); ossimDpt p; ossim_int32 idx = 0; ossimDpt initialPoint= uli; for(idx = 0; idx < stepSize;++idx) { result.push_back(initialPoint); initialPoint.x+=deltaUpper.x; initialPoint.y+=deltaUpper.y; } initialPoint= uri; for(idx = 0; idx < stepSize;++idx) { result.push_back(initialPoint); initialPoint.x+=deltaRight.x; initialPoint.y+=deltaRight.y; } initialPoint= lri; for(idx = 0; idx < stepSize;++idx) { result.push_back(initialPoint); initialPoint.x+=deltaLower.x; initialPoint.y+=deltaLower.y; } initialPoint= lli; for(idx = 0; idx < stepSize;++idx) { result.push_back(initialPoint); initialPoint.x+=deltaLeft.x; initialPoint.y+=deltaLeft.y; } } else // If not enough partitions then we will just use the corners { result.resize(4); result[0] = imageRect.ul(); result[1] = imageRect.ur(); result[2] = imageRect.lr(); result[3] = imageRect.ll(); } } void ossimImageGeometry::calculatePolyBounds(ossimPolyArea2d& result, ossim_uint32 partitions)const { std::vector points; std::vector gPoints; std::vector polyList; ossimDrect imageRect; ossimGpt cg; ossimDrect worldRect(ossimDpt(-180,-90), ossimDpt(-180,90), ossimDpt(180,90), ossimDpt(180,-90)); getBoundingRect(imageRect); // bool affectedByElevation = isAffectedByElevation(); bool crossesDateline = getCrossesDateline(); result.clear(); if(imageRect.hasNans()) { // error out return; } localToWorld(imageRect.midPoint(), cg); if(cg.isLatNan() || cg.isLonNan()) { return; } ossim_int32 sgn = static_cast( ossim::sgn(cg.lond())); getImageEdgePoints(points, partitions); if(points.empty()) { return; } if(crossesDateline) { for(std::vector::const_iterator iter=points.begin(); iter != points.end(); ++iter) { ossimGpt testGpt; localToWorld(*iter, testGpt); if(!testGpt.isLatNan()&&!testGpt.isLonNan()) { bool needToShift =( (std::fabs(testGpt.lond()-cg.lond()) > 180.0)|| (std::fabs(testGpt.lond()>180.0)) ); if(needToShift) { testGpt.lond(testGpt.lond()+sgn*360); } gPoints.push_back(testGpt); } } // now clip the ground list to the full ground rect // ossimPolygon tempPoly(gPoints); tempPoly.clipToRect(polyList, worldRect); for(std::vector::const_iterator iter = polyList.begin(); iter!=polyList.end();++iter) { result.add(ossimPolyArea2d(*iter)); } // now shift gpoints to the other side // for(std::vector::iterator iter = gPoints.begin(); iter != gPoints.end(); ++iter) { (*iter).lond((*iter).lond()+(-sgn*360)); } tempPoly = gPoints; polyList.clear(); tempPoly.clipToRect(polyList, worldRect); for(std::vector::const_iterator iter = polyList.begin(); iter!=polyList.end();++iter) { result.add(ossimPolyArea2d(*iter)); } } else { for(std::vector::const_iterator iter=points.begin(); iter != points.end();++iter) { ossimGpt testGpt; localToWorld(*iter, testGpt); if(!testGpt.isLatNan()&&!testGpt.isLonNan()) { gPoints.push_back(testGpt); } } result.add(ossimPolygon(gPoints)); } if(!result.isValid()) result.setToBufferedShape(); } void ossimImageGeometry::getBoundingRect(ossimIrect& bounding_rect) const { if (m_imageSize.hasNans()) { bounding_rect.makeNan(); } else { bounding_rect.set_ulx(0); bounding_rect.set_uly(0); bounding_rect.set_lrx(m_imageSize.x-1); bounding_rect.set_lry(m_imageSize.y-1); } } void ossimImageGeometry::getBoundingRect(ossimDrect& bounding_rect) const { if (m_imageSize.hasNans()) { bounding_rect.makeNan(); } else { bounding_rect.set_ulx(0); bounding_rect.set_uly(0); bounding_rect.set_lrx(m_imageSize.x-1); bounding_rect.set_lry(m_imageSize.y-1); } } void ossimImageGeometry::getBoundingGroundRect(ossimGrect& bounding_grect) const { ossimGpt ul, ur, lr, ll; getCornerGpts(ul, ur, lr, ll); bounding_grect.ul().lat = ul.lat > ur.lat ? ul.lat : ur.lat; bounding_grect.ul().lon = ul.lon < ll.lon ? ul.lon : ll.lon; bounding_grect.lr().lat = ll.lat < lr.lat ? ll.lat : lr.lat; bounding_grect.lr().lon = ur.lon > lr.lon ? ur.lon : lr.lon; } void ossimImageGeometry::applyScale(const ossimDpt& scale, bool recenterTiePoint) { if ((scale.x != 0.0) && (scale.y != 0.0)) { ossimMapProjection* map_Proj = dynamic_cast(m_projection.get()); if ( map_Proj ) { m_imageSize.x = ossim::round(m_imageSize.x / scale.x); m_imageSize.y = ossim::round(m_imageSize.y / scale.y); map_Proj->applyScale(scale, recenterTiePoint); } } } ossimAdjustableParameterInterface* ossimImageGeometry::getAdjustableParameterInterface() { return PTR_CAST(ossimAdjustableParameterInterface, getProjection()); } const ossimAdjustableParameterInterface* ossimImageGeometry::getAdjustableParameterInterface()const { return dynamic_cast(getProjection()); } bool ossimImageGeometry::computeImageToGroundPartialsWRTAdjParam(ossimDpt& result, const ossimGpt& gpt, ossim_uint32 idx, ossim_float64 paramDelta) { double den = 0.5/paramDelta; // this is the same as dividing by 2*delta result = ossimDpt(0.0,0.0); ossimAdjustableParameterInterface* adjustableParamInterface = getAdjustableParameterInterface(); if(!adjustableParamInterface) return false; if(idx >= adjustableParamInterface->getNumberOfAdjustableParameters()) return false; ossimDpt p1, p2; // double middle = adjustableParamInterface->getAdjustableParameter(idx); double middle = adjustableParamInterface->getParameterCenter(idx); //set parm to high value // adjustableParamInterface->setAdjustableParameter(idx, middle + paramDelta, true); adjustableParamInterface->setParameterCenter(idx, middle + paramDelta, true); worldToLocal(gpt, p1); //set parm to low value and gte difference // adjustableParamInterface->setAdjustableParameter(idx, middle - paramDelta, true); adjustableParamInterface->setParameterCenter(idx, middle - paramDelta, true); worldToLocal(gpt, p2); //get partial derivative result = (p2-p1)*den; //reset param // adjustableParamInterface->setAdjustableParameter(idx, middle, true); adjustableParamInterface->setParameterCenter(idx, middle, true); return !result.hasNans(); } bool ossimImageGeometry::computeImageToGroundPartialsWRTAdjParams(NEWMAT::Matrix& result, const ossimGpt& gpt, ossim_float64 paramDelta) { ossimAdjustableParameterInterface* adjustableParamInterface = getAdjustableParameterInterface(); ossim_uint32 nAdjustables = adjustableParamInterface->getNumberOfAdjustableParameters(); ossim_uint32 idx = 0; result = NEWMAT::Matrix(nAdjustables, 2); for(;idx < nAdjustables; ++idx) { ossimDpt paramResResult; computeImageToGroundPartialsWRTAdjParam(paramResResult, gpt, idx, paramDelta); result[idx][0] = paramResResult.x; result[idx][1] = paramResResult.y; } return true; } bool ossimImageGeometry::computeImageToGroundPartialsWRTAdjParams(NEWMAT::Matrix& result, const ossimGpt& gpt, const DeltaParamList& deltas) { ossimAdjustableParameterInterface* adjustableParamInterface = getAdjustableParameterInterface(); ossim_uint32 nAdjustables = adjustableParamInterface->getNumberOfAdjustableParameters(); if(nAdjustables != deltas.size()) return false; ossim_uint32 idx = 0; result = NEWMAT::Matrix(nAdjustables, 2); for(;idx < nAdjustables; ++idx) { ossimDpt paramResResult; computeImageToGroundPartialsWRTAdjParam(paramResResult, gpt, idx, deltas[idx]); // ROWxCOL result[idx][0] = paramResResult.x; result[idx][1] = paramResResult.y; } return true; } bool ossimImageGeometry::computeGroundToImagePartials(NEWMAT::Matrix& result, const ossimGpt& gpt, const ossimDpt3d& deltaLlh) { if(!getProjection()) return false; ossimDpt p1; ossimDpt p2; ossimDpt deltaWithRespectToLon; ossimDpt deltaWithRespectToLat; ossimDpt deltaWithRespectToH; ossim_float64 h = ossim::isnan(gpt.height())?0.0:gpt.height(); // do the change in lon first for the dx, dy // worldToLocal(ossimGpt(gpt.latd(), gpt.lond()+deltaLlh.x, h, gpt.datum()), p1); worldToLocal(ossimGpt(gpt.latd(), gpt.lond()-deltaLlh.x, h, gpt.datum()), p2); double den = 0.5/deltaLlh.x; // this is the same as dividing by 2*delta deltaWithRespectToLon = (p2-p1)*den; // do the change in lat for the dx, dy // worldToLocal(ossimGpt(gpt.latd()+deltaLlh.y, gpt.lond(), h, gpt.datum()), p1); worldToLocal(ossimGpt(gpt.latd()-deltaLlh.y, gpt.lond(), h, gpt.datum()), p2); den = 0.5/deltaLlh.y; // this is the same as dividing by 2*delta deltaWithRespectToLat = (p2-p1)*den; // do the change in height first for the dx, dy // worldToLocal(ossimGpt(gpt.latd(), gpt.lond(), h+deltaLlh.z, gpt.datum()), p1); worldToLocal(ossimGpt(gpt.latd(), gpt.lond(), h-deltaLlh.z, gpt.datum()), p2); den = 0.5/deltaLlh.z; // this is the same as dividing by 2*delta deltaWithRespectToH = (p2-p1)*den; result = NEWMAT::Matrix(3,2); // set the matrix // result[1][0] = deltaWithRespectToLon.x*DEG_PER_RAD; result[1][1] = deltaWithRespectToLon.y*DEG_PER_RAD; result[0][0] = deltaWithRespectToLat.x*DEG_PER_RAD; result[0][1] = deltaWithRespectToLat.y*DEG_PER_RAD; result[2][0] = deltaWithRespectToH.x; result[2][1] = deltaWithRespectToH.y; return true; } bool ossimImageGeometry::computeGroundToImagePartials(NEWMAT::Matrix& result, const ossimGpt& gpt) { ossimDpt mpp = getMetersPerPixel(); ossimGpt originPoint; ossim_float64 len = mpp.length(); if(len > FLT_EPSILON) { ossim_float64 delta = originPoint.metersPerDegree().length(); delta = len/delta; return computeGroundToImagePartials(result, gpt, ossimDpt3d(delta, delta, len)); } return false; } ossim_float64 ossimImageGeometry::upIsUpAngle(const ossimDpt& pt) const { ossim_float64 result = ossim::nan(); if ( m_projection.valid() ) { if ( m_projection->isAffectedByElevation() ) { const int NUMBER_OF_SAMPLES = 9; // In meters. This is about a height of a 6 to 7 story building. const double ELEVATION_DISPLACEMENT = 20; ossimDrect bounds; getBoundingRect( bounds ); if( !bounds.hasNans() ) { // only need an average // so will keep the test close to the pixel location // we are sampling // let's get rid of the scale ossim_float64 widthPercent = 1;//bounds.width()*.1; ossim_float64 heightPercent = 1;//bounds.height()*.1; //--- // Sanity check to make sure that taking 10 percent out on the image // gets us to at least 1 pixel away. //--- // if(widthPercent < 1.0) widthPercent = 1.0; // if(heightPercent < 1.0) heightPercent = 1.0; // set up some work variables to help calculate the average partial // std::vector ipts(NUMBER_OF_SAMPLES); std::vector gpts(NUMBER_OF_SAMPLES); std::vector iptsDisplacement(NUMBER_OF_SAMPLES); std::vector partials(NUMBER_OF_SAMPLES); ossimDpt averageDelta(0.0,0.0); ossimDpt centerIpt = pt; if(centerIpt.hasNans()) { centerIpt = bounds.midPoint(); } //--- // Lets take an average displacement about the center point (3x3 grid) // we will go 10 percent out of the width and height of the image and // look at the displacement at those points and average them we will // use the average displacement to compute the up is up rotation. //--- // top row: // 45 degree left quadrant // RP - FIX POINTS IN FIRST ROW ipts[0] = centerIpt + ossimDpt(-widthPercent, -heightPercent); // 45 degree middle top ipts[1] = centerIpt + ossimDpt(0.0,heightPercent); // 45 degree right quadrant ipts[2] = centerIpt + ossimDpt(widthPercent, -heightPercent); // middle row ipts[3] = centerIpt + ossimDpt(-widthPercent, 0.0); // left middle ipts[4] = centerIpt; ipts[5] = centerIpt + ossimDpt(widthPercent, 0.0); // bottom row ipts[6] = centerIpt + ossimDpt(-widthPercent, heightPercent); ipts[7] = centerIpt + ossimDpt(0.0, heightPercent); ipts[8] = centerIpt + ossimDpt(widthPercent, heightPercent); ossim_uint32 idx = 0; for(idx = 0; idx < ipts.size(); ++idx) { double h = 0.0; localToWorld(ipts[idx], gpts[idx]); h = gpts[idx].height(); if(ossim::isnan(h)) h = 0.0; gpts[idx].height(h + ELEVATION_DISPLACEMENT); worldToLocal(gpts[idx], iptsDisplacement[idx]); averageDelta = averageDelta + (iptsDisplacement[idx] - ipts[idx]); } ossim_float64 averageLength = averageDelta.length(); if(averageLength < 1) return false; if(!ossim::almostEqual((double)0.0, (double)averageLength)) { averageDelta = averageDelta/averageLength; } // RP - the rest of this calculation seems to be leading to less accurate results. // We already have the average image space displacement from raising the height for 9 points in the image // Just rotate based on this displacement, // scaling based on the image size distorts the direction of the up vector, leading to inaccurate results for non-square images // //ossimDpt averageLocation = (ossimDpt(averageDelta.x*bounds.width(), // averageDelta.y*bounds.height())+centerIpt) ; //ossimGpt averageLocationGpt; //ossimGpt centerGpt; //localToWorld(averageLocation, averageLocationGpt); //localToWorld(ipts[0], centerGpt); ossimDpt deltaPt = averageDelta; //averageLocation - centerIpt; ossimDpt deltaUnitPt = deltaPt; double len = deltaPt.length(); if(len > FLT_EPSILON) { deltaUnitPt = deltaUnitPt/len; } // Image space model positive y is down. Let's reflect to positve y up. deltaUnitPt.y *= -1.0; // Reflect y to be right handed. result = ossim::atan2d(deltaUnitPt.x, deltaUnitPt.y); //--- // We are essentially simulating camera rotation so negate the rotation // value. //--- result *= -1; if(result < 0) result += 360.0; } // Matches: if( bounds.hasNans() == false ) } else { result = 0; } } // Matches: if ( m_projection.valid() && m_projection->isAffectedByElevation() ) return result; } ossim_float64 ossimImageGeometry::upIsUpAngle() const { ossim_float64 result = ossim::nan(); if ( m_projection.valid() ) { if ( m_projection->isAffectedByElevation() ) { ossimDrect bounds; getBoundingRect( bounds ); if( !bounds.hasNans() ) { return upIsUpAngle(bounds.midPoint()); } } else { result = 0; } } // Matches: if ( m_projection.valid() && m_projection->isAffectedByElevation() ) return result; } // End: ossimImageGeometry::upIsUpAngle() ossim_float64 ossimImageGeometry::northUpAngle()const { ossim_float64 result = ossim::nan(); if ( m_projection.valid() ) { ossimDrect bounds; getBoundingRect( bounds ); if( !bounds.hasNans() ) { ossimDpt centerIpt = bounds.midPoint(); ossimDpt midBottomIpt( centerIpt.x, bounds.lr().y ); ossimDpt midTopIpt( centerIpt.x, bounds.ul().y ); ossimGpt midBottomGpt; ossimGpt midTopGpt; localToWorld( midBottomIpt, midBottomGpt ); localToWorld( midTopIpt, midTopGpt ); if ( !midBottomGpt.hasNans() && !midTopGpt.hasNans() ) { result = midBottomGpt.azimuthTo( midTopGpt ); if(result < 0) result += 360.0; } } } // Matches: if ( m_projection.valid() ) return result; } // End: ossimImageGeometry::northUpAngle() bool ossimImageGeometry::isMapProjected() const { return dynamic_cast( m_projection.get() ) != 0; } ossim-Miami-2.9.1/src/imaging/ossimImageGeometryFactory.cpp000066400000000000000000000146371352751253100237750ustar00rootroot00000000000000//***************************************************************************** // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: Class implementation of ossimImageGeometryFactory. // See .h file for class documentation. // //***************************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include #include #include ossimImageGeometryFactory* ossimImageGeometryFactory::m_instance = 0; ossimImageGeometryFactory::ossimImageGeometryFactory() { m_instance = this; } ossimImageGeometryFactory* ossimImageGeometryFactory::instance() { if(!m_instance) { m_instance = new ossimImageGeometryFactory(); } return m_instance; } ossimImageGeometry* ossimImageGeometryFactory::createGeometry( const ossimString& typeName)const { if(typeName == "ossimImageGeometry") { return new ossimImageGeometry(); } return 0; } ossimImageGeometry* ossimImageGeometryFactory::createGeometry( const ossimKeywordlist& kwl, const char* prefix)const { ossimRefPtr result = 0; ossimString type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if(!type.empty()) { result = createGeometry(type); if(result.valid()&&!result->loadState(kwl, prefix)) { result = 0; } } return result.release(); } ossimImageGeometry* ossimImageGeometryFactory::createGeometry( const ossimFilename& /* filename */, ossim_uint32 /* entryIdx */)const { // currently don't support this option just yet by this factory return 0; } bool ossimImageGeometryFactory::extendGeometry(ossimImageHandler* handler)const { bool result = false; if (handler) { bool add2D = true; ossimRefPtr geom = handler->getImageGeometry(); if(geom.valid()) { if(!geom->getProjection()) { geom->setProjection(createProjection(handler)); result = geom->hasProjection(); } if(geom->getProjection()) { if( !(dynamic_cast(geom->getProjection()))) { add2D = false; } } if(!geom->getTransform()&&add2D) { geom->setTransform(createTransform(handler)); result |= geom->hasTransform(); } } } return result; } void ossimImageGeometryFactory::getTypeNameList( std::vector& typeList)const { typeList.push_back("ossimImageGeometry"); } ossim2dTo2dTransform* ossimImageGeometryFactory::createTransform( ossimImageHandler* handler)const { // Currently nothing to do... ossimRefPtr result = 0; ossimNitfTileSource* nitf = dynamic_cast (handler); if(nitf) { result = createTransformFromNitf(nitf); } return result.release(); } ossimProjection* ossimImageGeometryFactory::createProjection( ossimImageHandler* handler) const { ossimRefPtr result = ossimProjectionFactoryRegistry::instance()->createProjection(handler); return result.release(); } ossim2dTo2dTransform* ossimImageGeometryFactory::createTransformFromNitf(ossimNitfTileSource* nitf)const { ossim2dTo2dTransform* result = 0; ossimRefPtr hdr = nitf->getCurrentImageHeader(); if (!hdr) { return result; } //--- // Test for the ichipb tag and set the sub image if needed. // // NOTE # 1: // // There are nitf writers that set the ichipb offsets and only have // IGEOLO field present. For these it has been determined // (but still in question) that we should not apply the sub image offset. // // See trac # 1578 // http://trac.osgeo.org/ossim/ticket/1578 // // NOTE # 2: // // Let the ICHIPB have precedence over the STDIDC tag as we could have a // chip of a segment. //--- ossimRefPtr tag = hdr->getTagData(ossimString("ICHIPB")); if (tag.valid()) { ossimNitfIchipbTag* ichipb = PTR_CAST(ossimNitfIchipbTag, tag.get()); if (ichipb) { // const ossimRefPtr blocka = // hdr->getTagData(ossimString("BLOCKA")); // const ossimRefPtr rpc00a = // hdr->getTagData(ossimString("RPC00A")); // const ossimRefPtr rpc00b = // hdr->getTagData(ossimString("RPC00B")); //--- // If any of these tags are present we will use the sub image from // the ichipb tag. //--- // if ( blocka.get() || rpc00a.get() || rpc00b.get() ) // ************************* THERE ARE PROBLEMS NOT SETTING THIS AT SITE. GO AHEAD AND ALWAYS INIT THE SHIFT { result = ichipb->newTransform(); } } } if ( !result) { //--- // Look for the STDIDC tag for a sub image (segment) offset. // // See: STDI-002 Table 7.3 for documentation. //--- tag = hdr->getTagData(ossimString("STDIDC")); if (tag.valid() && (hdr->getIMode() == "B") ) { ossimDpt shift; ossimNitfStdidcTag* stdidc = PTR_CAST(ossimNitfStdidcTag, tag.get()); if (stdidc) { ossim_int32 startCol = stdidc->getStartColumn().toInt32(); ossim_int32 startRow = stdidc->getStartRow().toInt32(); if ( (startCol > 0) && (startRow > 0) ) { // field are one based; hence, the - 1. shift.x = (startCol-1) * hdr->getNumberOfPixelsPerBlockHoriz(); shift.y = (startRow-1) * hdr->getNumberOfPixelsPerBlockVert(); } if(shift.x > 0 || shift.y > 0) { result = new ossim2dTo2dShiftTransform(shift); } } } } return result; } ossim-Miami-2.9.1/src/imaging/ossimImageGeometryRegistry.cpp000066400000000000000000000047071352751253100241730ustar00rootroot00000000000000//************************************************************************************************** // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: Class implementation of ossimImageGeometryRegistry. See .h file for class documentation. // //************************************************************************************************** // $Id$ #include #include #include ossimImageGeometryRegistry* ossimImageGeometryRegistry::m_instance = 0; RTTI_DEF1(ossimImageGeometryRegistry, "ossimImageGeometryRegistry", ossimImageGeometryFactoryBase); ossimImageGeometryRegistry* ossimImageGeometryRegistry::instance() { if(!m_instance) { m_instance = new ossimImageGeometryRegistry(); m_instance->registerFactory(ossimImageGeometryFactory::instance()); ossimObjectFactoryRegistry::instance()->registerFactory(m_instance); } return m_instance; } bool ossimImageGeometryRegistry::extendGeometry(ossimImageHandler* handler)const { bool result = false; ossim_uint32 idx = 0; for(;((idx < m_factoryList.size())&&!result); ++idx) { result = m_factoryList[idx]->extendGeometry(handler); } return result; } ossimImageGeometry* ossimImageGeometryRegistry::createGeometry(const ossimString& typeName)const { ossimRefPtr obj = createObjectFromRegistry(typeName); ossimRefPtr geomResult = dynamic_cast(obj.get()); obj = 0; return geomResult.release(); } ossimImageGeometry* ossimImageGeometryRegistry::createGeometry(const ossimKeywordlist& kwl, const char* prefix)const { ossimRefPtr obj = createObjectFromRegistry(kwl, prefix); ossimRefPtr geomResult = dynamic_cast(obj.get()); obj = 0; return geomResult.release(); } ossimImageGeometry* ossimImageGeometryRegistry::createGeometry(const ossimFilename& filename, ossim_uint32 entryIdx)const { ossimImageGeometry* result = 0; ossim_uint32 idx = 0; for(;((idx < m_factoryList.size())&&!result); ++idx) { result = m_factoryList[idx]->createGeometry(filename, entryIdx); } return result; } ossim-Miami-2.9.1/src/imaging/ossimImageHandler.cpp000077500000000000000000001544741352751253100222360ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // This class defines an abstract image handler which all loaders should // derive from. // //******************************************************************* // $Id: ossimImageHandler.cpp 23013 2014-12-02 19:21:56Z okramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimImageHandler, "ossimImageHandler", ossimImageSource) // Static trace for debugging static ossimTrace traceDebug("ossimImageHandler:debug"); // Property keywords. static const char HAS_LUT_KW[] = "has_lut"; static const char OPEN_OVERVIEW_FLAG_KW[] = "open_overview_flag"; static const char START_RES_LEVEL_KW[] = "start_res_level"; static const char SUPPLEMENTARY_DIRECTORY_KW[] = "supplementary_directory"; static const char VALID_VERTICES_FILE_KW[] = "valid_vertices_file"; #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimImageHandler.cpp 23013 2014-12-02 19:21:56Z okramer $"; #endif // GARRETT! All of the decimation factors are scattered throughout. We want to fold that into // the image geometry object. The code is ready in ossimImageGeometry for this (more or less), but // the ossimImageGeometry::m_decimationFactors is not being set nor referenced. Can you do this? // I'm a little foggy on how we want to incorporate R-level scaling into the geometry object. ossimImageHandler::ossimImageHandler() : ossimImageSource(0, 0, 0, true, false /* output list is not fixed */ ), theImageFile(ossimFilename::NIL), theOverviewFile(ossimFilename::NIL), theSupplementaryDirectory(ossimFilename::NIL), theOverview(0), theValidImageVertices(0), theMetaData(), theGeometry(), theLut(0), theDecimationFactors(0), theImageID(""), theStartingResLevel(0), theOpenOverviewFlag(true), thePixelType(OSSIM_PIXEL_IS_POINT) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageHandler::ossimImageHandler() DEBUG:" << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } // Check for global preference supplementary dir. theSupplementaryDirectory.string() = ossimPreferences::instance()-> preferencesKWL().findKey( std::string("ossim_supplementary_directory") ); } ossimImageHandler::~ossimImageHandler() { theOverview = 0; } void ossimImageHandler::initialize() { } //******************************************************************* // Public method: //******************************************************************* bool ossimImageHandler::saveState(ossimKeywordlist& kwl, const char* prefix) const { static const char MODULE[] = "ossimImageHandler::saveState"; ossimImageSource::saveState(kwl, prefix); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR detected in keyword list! State not saved." << std::endl; return false; } kwl.add(prefix, ossimKeywordNames::FILENAME_KW, theImageFile.c_str(), true); kwl.add(prefix, HAS_LUT_KW, (theLut.valid()?"true":"false"), true); kwl.add(prefix, ossimKeywordNames::IMAGE_ID_KW, theImageID, true); kwl.add(prefix, ossimKeywordNames::OVERVIEW_FILE_KW, theOverviewFile.c_str(), true); kwl.add(prefix, SUPPLEMENTARY_DIRECTORY_KW, theSupplementaryDirectory.c_str(), true); kwl.add(prefix, START_RES_LEVEL_KW, theStartingResLevel, true); kwl.add(prefix, OPEN_OVERVIEW_FLAG_KW, (theOpenOverviewFlag?"1":"0"), true); kwl.add(prefix, ossimKeywordNames::PIXEL_TYPE_KW, (ossim_uint16) thePixelType, true); return true; } //******************************************************************* // Public method: //******************************************************************* bool ossimImageHandler::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimImageHandler::loadState(kwl, prefix)"; theDecimationFactors.clear(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG: entered ..." << std::endl; } ossimImageSource::loadState(kwl, prefix); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << "WARNING: error detected in keyword list! State not load." << std::endl; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG: " << "leaving with error in kwl ..." << std::endl; } return false; } const char* lookup = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if (!lookup) { // Deprecated... lookup = kwl.find(prefix, ossimKeywordNames::IMAGE_FILE_KW); } if (lookup) { theImageFile = lookup; } lookup = kwl.find(prefix, ossimKeywordNames::OVERVIEW_FILE_KW); if(lookup) { theOverviewFile = ossimFilename(lookup); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:\n" << "filename = " << theImageFile << std::endl; } // Check for an external geometry file to initialize our image geometry object: lookup = kwl.find(prefix, ossimKeywordNames::GEOM_FILE_KW); if (lookup) { ossimKeywordlist geomKwl; if (geomKwl.addFile(lookup) == true) { theGeometry = new ossimImageGeometry; theGeometry->loadState(geomKwl); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "Loaded external geometry file: " << lookup << "\n" << geomKwl << std::endl; } } } // Check for an valid image vetices file. lookup = kwl.find(prefix, VALID_VERTICES_FILE_KW); if (lookup) { initVertices(lookup); } // Starting resolution level. lookup = kwl.find(prefix, START_RES_LEVEL_KW); if (lookup) { theStartingResLevel = ossimString(lookup).toUInt32(); } // Open overview flag. lookup = kwl.find(prefix, OPEN_OVERVIEW_FLAG_KW); if (lookup) { setOpenOverviewFlag( ossimString(lookup).toBool() ); } // The supplementary directory for finding the overview lookup = kwl.find(prefix, SUPPLEMENTARY_DIRECTORY_KW); if (lookup) { theSupplementaryDirectory = ossimFilename(lookup); } if(getNumberOfInputs()) { theInputObjectList.clear(); } theInputListIsFixedFlag = true; // Read image id if present: theImageID = kwl.find(prefix, ossimKeywordNames::IMAGE_ID_KW); lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_TYPE_KW); if (lookup) { thePixelType = (ossimPixelType) atoi(lookup); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG: Leaving Ok ..." << std::endl; } return true; } bool ossimImageHandler::initVertices(const char* file) { static const char MODULE[] = "ossimImageHandler::initVertices"; bool loadFromFileFlag = true; std::shared_ptr kwl; if(m_state) { bool validVerticesFlag = false; if(m_state->getValidVertices()) { loadFromFileFlag = false; kwl = m_state->getValidVertices(); if(kwl) { ossimString connectionString = kwl->find("connection_string"); if(connectionString != file) { loadFromFileFlag = true; } else if(kwl->getSize()<=0) { return false; } } } else { loadFromFileFlag = true; } } if(!kwl) kwl = std::make_shared(); if(loadFromFileFlag) { kwl = std::make_shared(); std::shared_ptr instream = ossim::StreamFactoryRegistry::instance()->createIstream(file); kwl->add("connection_string", file, true); if (!instream) { //if(m_state) // m_state->setValidVertices(kwl); return false; } kwl->parseStream(*instream); if(m_state && kwl->getSize()) m_state->setValidVertices(kwl); } if (kwl->getErrorStatus() != ossimErrorCodes::OSSIM_OK) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageHandler::initVertices NOTICE:" << "\nError reading valid vertice file: " << file << std::endl; } return false; } // Clean out any old vertices... theValidImageVertices.clear(); std::vector indexedPrefixes; kwl->getSortedList(indexedPrefixes, "point"); ossim_uint32 number_of_points = indexedPrefixes.size(); for (ossim_uint32 i=0; ifind(indexedPrefixes[i], ".x"); if (lookup) { pt.x = atoi(lookup); lookup = kwl->find(indexedPrefixes[i], ".y"); if (lookup) pt.y = atoi(lookup); } if (!lookup) { if (traceDebug()) CLOG << " ERROR: lookup failed for: " << indexedPrefixes[i] << std::endl; return false; } theValidImageVertices.push_back(pt); } if (traceDebug()) { CLOG << " DEBUG:" << "\nVertices file: " << file << "\nValid image vertices:" << std::endl; for (ossim_uint32 i=0; igetNumberOfDecimationLevels(); } return result; } ossim_uint32 ossimImageHandler::getNumberOfReducedResSets() const { return getNumberOfDecimationLevels(); } ossimIrect ossimImageHandler::getImageRectangle(ossim_uint32 resLevel) const { ossimIrect result; if( isOpen() && isValidRLevel(resLevel) ) { ossim_int32 lines = getNumberOfLines(resLevel); ossim_int32 samples = getNumberOfSamples(resLevel); if( !lines || !samples ) { result.makeNan(); } else { result = ossimIrect(0, 0, samples-1, lines-1); } } else { result.makeNan(); } return result; } ossimIrect ossimImageHandler::getBoundingRect(ossim_uint32 resLevel) const { return getImageRectangle(resLevel); } void ossimImageHandler::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { if (resLevel < theDecimationFactors.size()) result = theDecimationFactors[resLevel]; else result.makeNan(); } void ossimImageHandler::getDecimationFactors(vector& decimations) const { decimations = theDecimationFactors; } //************************************************************************************************* // Method determines the decimation factors at each resolution level. This // base class implementation computes the decimation by considering the ratios in image size // between resolution levels, with fuzzy logic for rounding ratios to the nearest power of 2 // if possible. Derived classes need to override this method if the decimations are provided // as part of the image metadata. In some cases (cf. ossimNitfTileSource), the derived class can // set the first R-level (R0) decimation in the case that it is not unity, and then invoke this // base class implementation to compute remaining R-levels, respecting the R0 decimation previously // set by derived class. //************************************************************************************************* void ossimImageHandler::establishDecimationFactors() { double line_decimation, samp_decimation, decimation, ratio; ossim_uint32 num_lines, num_samps; // The error margin here is effectively the percent error tolerated between ideal number of // pixels for given power-of-2 decimation, and the actual number of pixels found at this // decimation level. Typically, the last level will have fewer pixels than expected, hence the // need for this logic... static const double ERROR_MARGIN = 1.1; // 10% allowance // NOTE -- Until the end of this method, all decimation values are actually inverse quantities, // i.e., a decimation of 0.5 typical for rlevel 1 is represented here as 2. This facilitates the // fuzzy logic for recognizing powers of 2 (as integers) // Default implementation assumes R0 is not decimated. Check for R0 defined by derived class // however, in case this is not the case: ossimDpt decimation_r0 (1.0, 1.0); if (theDecimationFactors.size() > 0) { decimation_r0.x = 1.0/theDecimationFactors[0].x; // note use of inverse decimation decimation_r0.y = 1.0/theDecimationFactors[0].y; } else theDecimationFactors.push_back(decimation_r0); // Variables used in loop below: ossim_uint32 num_lines_r0 = getNumberOfLines(0); ossim_uint32 num_samps_r0 = getNumberOfSamples(0); ossim_uint32 power_of_2_decimation = (ossim_uint32) decimation_r0.x; // Remaining res levels are computed as a ratio of image size at R0 to image size at Rn: ossim_uint32 nRlevels = getNumberOfDecimationLevels(); for(ossim_uint32 res_level = 1; res_level < nRlevels; ++res_level) { num_lines = getNumberOfLines(res_level); num_samps = getNumberOfSamples(res_level); if ((num_lines < 2) || (num_samps < 2)) break; line_decimation = decimation_r0.y * num_lines_r0 / (double)num_lines; samp_decimation = decimation_r0.x * num_samps_r0 / (double)num_samps; decimation = line_decimation histoSource = new ossimImageHistogramSource; ossimRefPtr writer = new ossimHistogramWriter; if(numberOfRLevels) { histoSource->setMaxNumberOfRLevels(numberOfRLevels); } else { histoSource->setMaxNumberOfRLevels(getNumberOfDecimationLevels()); } //--- // Note if mode==OSSIM_HISTO_MODE_UNKNOWN the histoSource defaults to // normal mode. //--- histoSource->setComputationMode( mode ); histoSource->connectMyInputTo(0, this); histoSource->enableSource(); writer->connectMyInputTo(0, histoSource.get()); writer->setFilename(file); writer->addListener(&theStdOutProgress); writer->execute(); histoSource->disconnect(); writer->disconnect(); histoSource = 0; writer = 0; } else { return false; } return true; } bool ossimImageHandler::buildAllHistograms( int numberOfRLevels, ossimHistogramMode mode ) { ossim_uint32 currentEntry = getCurrentEntry(); std::vector entryList; getEntryList(entryList); ossim_uint32 idx = 0; for(idx = 0; idx < entryList.size(); ++idx) { setCurrentEntry(entryList[idx]); if(!buildHistogram( numberOfRLevels, mode )) { setCurrentEntry(currentEntry); return false; } } setCurrentEntry(currentEntry); return true; } bool ossimImageHandler::buildOverview(ossimImageHandlerOverviewCompressionType compressionType, ossim_uint32 quality, ossimFilterResampler::ossimFilterResamplerType resampleType, bool includeFullResFlag) { ossimFilename file = getFilenameWithThisExtension(ossimString(".ovr")); theOverviewFile = file; if(buildOverview(file, compressionType, quality, resampleType, includeFullResFlag)) { openOverview(); } return true; } bool ossimImageHandler::buildAllOverviews(ossimImageHandlerOverviewCompressionType compressionType, ossim_uint32 quality, ossimFilterResampler::ossimFilterResamplerType resampleType, bool includeFullResFlag) { ossim_uint32 currentEntry = getCurrentEntry(); std::vector entryList; getEntryList(entryList); ossim_uint32 idx = 0; for(idx = 0; idx < entryList.size(); ++idx) { setCurrentEntry(entryList[idx]); if(!buildOverview(compressionType, quality, resampleType, includeFullResFlag)) { setCurrentEntry(currentEntry); return false; } } setCurrentEntry(currentEntry); return true; } bool ossimImageHandler::buildOverview(const ossimFilename& filename, ossimImageHandlerOverviewCompressionType compressionType, ossim_uint32 quality, ossimFilterResampler::ossimFilterResamplerType resampleType, bool includeFullResFlag) { closeOverview(); if(!isOpen()) { return false; } theOverviewFile = filename; ossimTiffOverviewBuilder tiffBuilder; if ( tiffBuilder.setInputSource(this) == false ) { return false; } ossim_uint16 cType = COMPRESSION_NONE; switch(compressionType) { case OSSIM_OVERVIEW_COMPRESSION_NONE: { cType = COMPRESSION_NONE; break; } case OSSIM_OVERVIEW_COMPRESSION_JPEG: { cType = COMPRESSION_JPEG; break; } case OSSIM_OVERVIEW_COMPRESSION_LZW: { cType = COMPRESSION_LZW; break; } case OSSIM_OVERVIEW_COMPRESSION_DEFLATE: { cType = COMPRESSION_DEFLATE; break; } case OSSIM_OVERVIEW_COMPRESSION_PACKBITS: { cType = COMPRESSION_PACKBITS; break; } } tiffBuilder.setJpegCompressionQuality(quality); tiffBuilder.setCompressionType(cType); tiffBuilder.setResampleType(resampleType); tiffBuilder.buildOverview(filename, includeFullResFlag); return true; } ossimRefPtr ossimImageHandler::getImageHistogram() const { ossimRefPtr histogram = 0; if ( isOpen() ) { ossimFilename histoFile = getFilenameWithThisExtension(ossimString(".his")); histogram = new ossimMultiResLevelHistogram(); if ( histogram->importHistogram(histoFile) == false ) { histogram = 0; } } return histogram; } ossimRefPtr ossimImageHandler::getImageGeometry() { if ( !theGeometry ) { //--- // Check factory for external geom: //--- theGeometry = getExternalImageGeometry(); if ( !theGeometry ) { //--- // WARNING: // Must create/set the geometry at this point or the next call to // ossimImageGeometryRegistry::extendGeometry will put us in an infinite loop // as it does a recursive call back to ossimImageHandler::getImageGeometry(). //--- theGeometry = new ossimImageGeometry(); initImageParameters( theGeometry.get() ); //--- // And finally allow factories to extend the internal geometry. // This allows plugins for tagged formats with tags not know in the base // to extend the internal geometry. // // Plugins can do handler->getImageGeometry() then modify/extend. //--- if(!ossimImageGeometryRegistry::instance()->extendGeometry( this )) { //--- // Check for internal, for geotiff, nitf and so on as last resort for getting some // kind of geometry loaded //--- theGeometry = getInternalImageGeometry(); initImageParameters( theGeometry.get() ); } } } return theGeometry; } ossimRefPtr ossimImageHandler::getExternalImageGeometry() const { ossimRefPtr geom = 0; // No geometry object has been set up yet. Check for external geometry file. // Try "foo.geom" if image is "foo.tif": ossimFilename filename; getFilenameWithThisExt( ossimString(".geom"), filename ); if(!filename.exists()) { // Try "foo_e0.tif" if image is "foo.tif" where "e0" is entry index. filename = getFilenameWithThisExtension(ossimString(".geom"), true); } #if 0 /* getgetFilenameWithThisExt... methods tack on sup dir if set. drb */ if(!filename.exists()) { // Try supplementary data directory for remote geometry: filename = getFilenameWithThisExtension(ossimString(".geom"), false); filename = theSupplementaryDirectory.dirCat(filename.file()); } if(!filename.exists()) { // Try supplementary data directory for remote geometry with entry index: filename = getFilenameWithThisExtension(ossimString(".geom"), true); filename = theSupplementaryDirectory.dirCat(filename.file()); } #endif if(filename.exists()) { // Open the geom file as a KWL and initialize our geometry object: filename = filename.expand(); ossimKeywordlist geomKwl(filename); // Try loadState with no prefix. std::string prefix = ""; std::string key = ossimKeywordNames::TYPE_KW; std::string value = geomKwl.findKey(prefix, key); if ( value.empty() || (value != "ossimImageGeometry") ) { // Try with "image0." type prefix. prefix += std::string("image") + ossimString::toString(getCurrentEntry()).string() + std::string("."); value = geomKwl.findKey(prefix, key); if ( value.empty() || (value != "ossimImageGeometry") ) { // Try with "image0.geometry." prefix. prefix += std::string( "geometry." ); value = geomKwl.findKey(prefix, key); if ( value.empty() || (value != "ossimImageGeometry") ) { // Try with "geometry." prefix. prefix = std::string( "geometry." ); value = geomKwl.findKey(prefix, key); } } } if ( value == "ossimImageGeometry" ) { geom = new ossimImageGeometry; if( !geom->loadState(geomKwl, prefix.c_str()) ) { geom = 0; } } } return geom; } ossimRefPtr ossimImageHandler::getInternalImageGeometry() const { // Default, derived classes should override. ossimRefPtr geom = new ossimImageGeometry(); return geom; } void ossimImageHandler::setImageGeometry( ossimImageGeometry* geom) { theGeometry = geom; } void ossimImageHandler::saveImageGeometry() const { ossimFilename geometryFile = getFilenameWithThisExtension(ossimString(".geom")); saveImageGeometry(geometryFile); } void ossimImageHandler::saveImageGeometry(const ossimFilename& geometry_file) const { if (theGeometry.valid()) { ossimKeywordlist kwl; theGeometry->saveState(kwl); kwl.write(geometry_file.chars()); } } void ossimImageHandler::closeOverview() { theOverview = 0; } const ossimImageHandler* ossimImageHandler::getOverview() const { return theOverview.get(); } bool ossimImageHandler::hasOverviews() const { return (getNumberOfDecimationLevels() > 1); } bool ossimImageHandler::openOverview(const ossimFilename& overview_file) { bool result = false; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageHandler::openOverview(overview_file): ...entered!"; } closeOverview(); if (overview_file != theImageFile) // Make sure we don't open ourselves. { //--- // Get the number of level before the call to opening the overview so // the overview can be told what it's starting res level is. //--- ossim_uint32 overviewStartingResLevel = getNumberOfDecimationLevels(); // Try to open: theOverview = ossimImageHandlerRegistry::instance()->openOverview( overview_file ); if (theOverview.valid()) { result = true; //--- // Set the owner in case the overview reader needs to get something // from the it like min/max/null. //--- theOverview->changeOwner(this); // Set the starting res level of the overview. theOverview->setStartingResLevel(overviewStartingResLevel); // Capture the file name. theOverviewFile = overview_file; //--- // Some overview handlers cannot store what the null is. Like dted // null is -32767 not default -32768 so this allows passing this to the // overview reader provided it overrides setMin/Max/NullPixel value // methods. (drb) //--- const ossim_uint32 BANDS = getNumberOfOutputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { theOverview->setMinPixelValue(band, getMinPixelValue(band)); theOverview->setMaxPixelValue(band, getMaxPixelValue(band)); theOverview->setNullPixelValue(band, getNullPixelValue(band)); } if(m_state) { m_state->setOverviewState(theOverview->getState()); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "overview starting res level: " << overviewStartingResLevel << "\noverview levels: " << theOverview->getNumberOfDecimationLevels() << "\nlevels: " << getNumberOfDecimationLevels() << endl; } //--- // This is not really a container event; however, using for now. //--- ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(theOverview.get()); fireEvent(event); } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageHandler::openOverview(overview_file): ...leaving!"; } return result; } bool ossimImageHandler::openOverview() { static const char MODULE[] = "ossimImageHandler::openOverview()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool result = false; closeOverview(); if(m_state) { // check if we have an overview state std::shared_ptr overviewState = m_state->getOverviewState(); if(overviewState) { // check to see if the overvies state was cached // to mark has checked but no overview if(overviewState->getConnectionString().empty()) { return false; } ossim_uint32 overviewStartingResLevel = getNumberOfDecimationLevels(); theOverview = ossimImageHandlerRegistry::instance()->open( overviewState ); if(theOverview) { result = true; //--- // Set the owner in case the overview reader needs to get something // from the it like min/max/null. //--- theOverview->changeOwner(this); // Set the starting res level of the overview. theOverview->setStartingResLevel(overviewStartingResLevel); // Capture the file name. theOverviewFile = overviewState->getConnectionString(); //--- // Some overview handlers cannot store what the null is. Like dted // null is -32767 not default -32768 so this allows passing this to the // overview reader provided it overrides setMin/Max/NullPixel value // methods. (drb) //--- const ossim_uint32 BANDS = getNumberOfOutputBands(); for (ossim_uint32 band = 0; band < BANDS; ++band) { theOverview->setMinPixelValue(band, getMinPixelValue(band)); theOverview->setMaxPixelValue(band, getMaxPixelValue(band)); theOverview->setNullPixelValue(band, getNullPixelValue(band)); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "overview starting res level: " << overviewStartingResLevel << "\noverview levels: " << theOverview->getNumberOfDecimationLevels() << "\nlevels: " << getNumberOfDecimationLevels() << endl; } //--- // This is not really a container event; however, using for now. //--- ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(theOverview.get()); fireEvent(event); return result; } } } // 1) ESH 03/2009 -- Use the overview file set e.g. using a .spec file. ossimFilename overviewFilename = getOverviewFile(); // ossimFilename::exists() currently does not work with s3 url's. if ( overviewFilename.empty() ) // || (overviewFilename.exists() == false) ) { // 2) Generate the name from image name. overviewFilename = createDefaultOverviewFilename(); } // ossimFilename::exists() currently does not work with s3 url's. if ( overviewFilename.size() ) { result = openOverview( overviewFilename ); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << (result?"Opened ":"Could not open ") << "overview: " << overviewFilename << "\n"; } } if ( !result ) { if (overviewFilename.empty() || (overviewFilename.exists() == false) ) { // 3) For backward compatibility check if single entry and _e0.ovr overviewFilename = getFilenameWithThisExtension(ossimString(".ovr"), true); if (overviewFilename.empty() || (overviewFilename.exists() == false) ) { //--- // 4) For overviews built with gdal. // Examples: // Single entry: foo.tif.ovr // Multi-entry: foo.tif.x.ovr where "x" == one based entry number. // // Note: Take into account a supplementary dir if any. //--- if ( theSupplementaryDirectory.empty() ) { overviewFilename = getFilename(); } else { overviewFilename = theSupplementaryDirectory; overviewFilename = overviewFilename.dirCat( getFilename().file() ); } if ( getNumberOfEntries() > 1 ) { overviewFilename += "."; // Sample multi-entry data "one" based; hence, the + 1. overviewFilename += ossimString::toString( getCurrentEntry()+1 ); } overviewFilename += ".ovr"; } } if ( overviewFilename.exists() ) { result = openOverview( overviewFilename ); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << (result?"Opened ":"Could not open ") << "overview: " << overviewFilename << "\n"; } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit result: " << (result?"true":"false") << "\n"; } return result; } bool ossimImageHandler::writeValidImageVertices(const std::vector& vertices, const ossimFilename& file) { ossimFilename tempFile = file; if(tempFile == "") { tempFile = createDefaultValidVerticesFilename(); } ossim_uint32 i = 0; ossimKeywordlist tempKwl; ossimPolygon poly(vertices); poly.checkOrdering(); // Capture the vertices. theValidImageVertices = vertices; if(poly.getOrdering() == OSSIM_COUNTERCLOCKWISE_ORDER) { std::reverse(theValidImageVertices.begin(), theValidImageVertices.end()); } if(theValidImageVertices.size()) { for(i = 0; i < theValidImageVertices.size(); ++i) { ossimString prefix = ossimString("point") + ossimString::toString(i) + "."; tempKwl.add(prefix.c_str(), "x", theValidImageVertices[i].x, true); tempKwl.add(prefix.c_str(), "y", theValidImageVertices[i].y, true); } tempKwl.write(tempFile.c_str()); } if ( tempFile.exists() ) { return true; } return false; // Write of file failed. } bool ossimImageHandler::openValidVertices(const ossimFilename& vertices_file) { return initVertices(vertices_file); } bool ossimImageHandler::openValidVertices() { ossimFilename vertices_file; vertices_file = theImageFile.path(); vertices_file = vertices_file.dirCat(theImageFile.fileNoExtension()); if(getNumberOfEntries() > 1) { vertices_file += ossimString("_vertices") + "_e" + ossimString::toString(getCurrentEntry()) + ".kwl"; } else { vertices_file += "_vertices.kwl"; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Looking for " << vertices_file << " vertices file..." << std::endl; } return openValidVertices(vertices_file); } bool ossimImageHandler::open(const ossimFilename& imageFile) { if(isOpen()) { close(); } setFilename(imageFile); return open(); } bool ossimImageHandler::open(const ossimFilename& imageFile, ossim_uint32 entryIndex) { if(isOpen()) { close(); } setFilename(imageFile); bool result = open(); if(result) { return setCurrentEntry(entryIndex); } return result; } bool ossimImageHandler::open(std::shared_ptr state) { bool result = false; if(isOpen()) { close(); } setFilename(state->getConnectionString()); setState(state); result = open(); return result; } bool ossimImageHandler::isValidRLevel(ossim_uint32 resLevel) const { bool result = false; const ossim_uint32 LEVELS = getNumberOfDecimationLevels(); if ( !theStartingResLevel) // Not an overview. { result = (resLevel < LEVELS); } else // Used as overview. { if (resLevel >= theStartingResLevel) { //--- // Adjust the res level to be zero based for this overview before // checking. //--- result = ( (resLevel - theStartingResLevel) < LEVELS); } } return result; } void ossimImageHandler::getValidImageVertices(vector& validVertices, ossimVertexOrdering ordering, ossim_uint32 resLevel) const { ossimDpt decimation; getDecimationFactor(resLevel, decimation); if(decimation.hasNans()) { return; } if (theValidImageVertices.size() != 0) { validVertices.clear(); for (ossim_uint32 i=0; i(theValidImageVertices[i].x*decimation.x), ossim::round(theValidImageVertices[i].y*decimation.y)); validVertices.push_back(pt); } if(ordering == OSSIM_COUNTERCLOCKWISE_ORDER) { std::reverse(validVertices.begin()+1, validVertices.end()); } } else { // Call the base class method which will set to bounding rectangle. ossimImageSource::getValidImageVertices(validVertices, ordering, resLevel); } } void ossimImageHandler::close() { theOverview = 0; theGeometry = 0; theValidImageVertices.clear(); theDecimationFactors.clear(); setState(0); } bool ossimImageHandler::isBandSelector() const { return false; } bool ossimImageHandler::setOutputBandList(const std::vector& /* band_list */) { return false; } bool ossimImageHandler::getRgbBandList( std::vector& bandList ) const { // Looks for "rgb_bands" key in dot omd file. E.g. "rgb_bands: (2,1,0)" return theMetaData.getRgbBands( bandList ); } bool ossimImageHandler::setOutputToInputBandList() { bool result = false; if ( isBandSelector() ) { std::vector bandList; ossimImageSource::getOutputBandList( bandList ); result = setOutputBandList( bandList ); } return result; } bool ossimImageHandler::isIdentityBandList( const std::vector& bandList ) const { bool result = false; const ossim_uint32 BANDS = (ossim_uint32)bandList.size(); if ( BANDS ) { std::vector inputList; ossimImageSource::getOutputBandList( inputList ); // This populates an identity band list. if ( inputList.size() == BANDS ) { ossim_uint32 band = 0; while ( band < BANDS ) { if ( inputList[band] != bandList[band] ) { break; } ++band; } if ( band == BANDS ) { result = true; } } } return result; } // Protected convenience method: bool ossimImageHandler::setOutputBandList(const std::vector& inBandList, std::vector& outBandList) { bool result = false; const ossim_uint32 INPUT_BANDS = getNumberOfInputBands(); const ossim_uint32 OUTPUT_BANDS = (ossim_uint32)inBandList.size(); if ( INPUT_BANDS && OUTPUT_BANDS ) { result = true; outBandList.resize( OUTPUT_BANDS ); for ( ossim_uint32 band = 0; band < OUTPUT_BANDS; ++band ) { if ( inBandList[band] < INPUT_BANDS ) { outBandList[band] = inBandList[band]; } else // Out of range... { result = false; break; } } if ( result && theOverview.valid() ) { result = theOverview->setOutputBandList( inBandList ); } } if ( result == false ) { ossimImageSource::getOutputBandList( outBandList ); // Set to identity. } return result; } bool ossimImageHandler::isImageTiled() const { return (getImageTileWidth() && getImageTileHeight()); } void ossimImageHandler::loadMetaData() { if(m_state&&m_state->getMetaData()) { theMetaData = *m_state->getMetaData(); } else { ossimFilename filename = getFilenameWithThisExtension(ossimString(".omd"), false); theMetaData.clear(); std::shared_ptr instream = ossim::StreamFactoryRegistry::instance()->createIstream(filename.c_str()); if(!instream) { filename = getFilenameWithThisExtension(ossimString(".omd"), true); instream = ossim::StreamFactoryRegistry::instance()->createIstream(filename.c_str()); } if(instream) { ossimKeywordlist kwl; kwl.parseStream(*instream); theMetaData.loadState(kwl); } else { theMetaData.setScalarType(getOutputScalarType()); } if(m_state) { m_state->setMetaData(std::make_shared(theMetaData)); } } } double ossimImageHandler::getMinPixelValue(ossim_uint32 band)const { if(theMetaData.getNumberOfBands()) { return theMetaData.getMinPix(band); } return ossim::defaultMin(getOutputScalarType()); } double ossimImageHandler::getMaxPixelValue(ossim_uint32 band)const { if(theMetaData.getNumberOfBands()) { return theMetaData.getMaxPix(band); } return ossim::defaultMax(getOutputScalarType()); } double ossimImageHandler::getNullPixelValue(ossim_uint32 band)const { if(theMetaData.getNumberOfBands()) { return theMetaData.getNullPix(band); } return ossim::defaultNull(getOutputScalarType()); } void ossimImageHandler::setMinPixelValue(ossim_uint32 band, const ossim_float64& pix) { theMetaData.setMinPix(band, pix); } void ossimImageHandler::setMaxPixelValue(ossim_uint32 band, const ossim_float64& pix) { theMetaData.setMaxPix(band, pix); } void ossimImageHandler::setNullPixelValue(ossim_uint32 band, const ossim_float64& pix) { theMetaData.setNullPix(band, pix); } ossim_uint32 ossimImageHandler::getCurrentEntry()const { return 0; } bool ossimImageHandler::setCurrentEntry(ossim_uint32 entryIdx ) { return true; } ossimFilename ossimImageHandler::getOverviewFile()const { return theOverviewFile; } void ossimImageHandler::getEntryList(std::vector& entryList)const { entryList.push_back(0); } bool ossimImageHandler::useEntryIndex() const { bool result = false; if ( isOpen() ) { std::vector entryList; getEntryList(entryList); if ( entryList.size() ) { if ( (entryList.size() > 1) || (entryList[0] != 0) ) result = true; } } return result; } ossim_uint32 ossimImageHandler::getNumberOfEntries()const { std::vector tempList; getEntryList(tempList); return (ossim_uint32)tempList.size(); } void ossimImageHandler::getEntryNames(std::vector& entryStringList) const { entryStringList.clear(); } void ossimImageHandler::getEntryName( ossim_uint32 entryIdx, std::string& name ) const { name = ""; std::vector entryNames; getEntryNames(entryNames); if (entryIdx < entryNames.size()) name = entryNames[entryIdx].string(); } void ossimImageHandler::completeOpen() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageHandler::completeOpen(): Entered........" << std::endl; } loadMetaData(); if ( theOpenOverviewFlag ) { openOverview(); } establishDecimationFactors(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageHandler::completeOpen(): Leaving......." << std::endl; } openValidVertices(); } bool ossimImageHandler::canConnectMyInputTo(ossim_int32 /* inputIndex */, const ossimConnectableObject* /* object */)const { return false; } bool ossimImageHandler::hasMetaData()const { return theMetaData.isValid(); } void ossimImageHandler::setFilename(const ossimFilename& filename) { theImageFile = filename; } const ossimFilename& ossimImageHandler::getFilename()const { return theImageFile; } void ossimImageHandler::setSupplementaryDirectory(const ossimFilename& dir) { if (dir.isDir()) theSupplementaryDirectory = dir; else theSupplementaryDirectory = dir.path(); // A change in supplementary directory presents an opportunity to find the OVR that could not be // opened previously, as well as other support data items: if (!theOverview.valid()) { if (theDecimationFactors.size() > 0) { theDecimationFactors.clear(); } completeOpen(); } } const ossimFilename& ossimImageHandler::getSupplementaryDirectory()const { return theSupplementaryDirectory; } void ossimImageHandler::setProperty(ossimRefPtr property) { if ( property.valid() ) { if(property->getName() == ossimKeywordNames::ENTRY_KW) { setCurrentEntry(property->valueToString().toUInt32()); } else if ( property->getName() == OPEN_OVERVIEW_FLAG_KW ) { setOpenOverviewFlag( property->valueToString().toBool() ); } else { ossimImageSource::setProperty(property); } } } ossimRefPtr ossimImageHandler::getProperty(const ossimString& name)const { if(name == ossimKeywordNames::ENTRY_KW) { std::vector entryList; getEntryList(entryList); ossimStringProperty* stringProperty = new ossimStringProperty(name, ossimString::toString(getCurrentEntry())); ossim_uint32 idx = 0; for(idx = 0; idx < entryList.size(); ++idx) { stringProperty->addConstraint(ossimString::toString(entryList[idx])); } stringProperty->setFullRefreshBit(); stringProperty->setEditableFlag(false); return stringProperty; } else if(name == ossimKeywordNames::NUMBER_SAMPLES_KW) { ossimNumericProperty* prop = new ossimNumericProperty(name, ossimString::toString(getNumberOfSamples())); prop->setReadOnlyFlag(true); return prop; } else if(name == ossimKeywordNames::NUMBER_LINES_KW) { ossimNumericProperty* prop = new ossimNumericProperty(name, ossimString::toString(getNumberOfLines())); prop->setReadOnlyFlag(true); return prop; } else if(name == ossimKeywordNames::NUMBER_BANDS_KW) { ossimNumericProperty* prop = new ossimNumericProperty(name, ossimString::toString(getNumberOfInputBands())); prop->setReadOnlyFlag(true); return prop; } else if(name == ossimKeywordNames::NUMBER_REDUCED_RES_SETS_KW) { ossimNumericProperty* prop = new ossimNumericProperty(name, ossimString::toString(getNumberOfDecimationLevels())); prop->setReadOnlyFlag(true); return prop; } else if(name == ossimKeywordNames::SCALAR_TYPE_KW) { ossimStringProperty* prop = new ossimStringProperty(name, ossimScalarTypeLut::instance()->getEntryString(getOutputScalarType())); prop->setReadOnlyFlag(true); return prop; } else if(name == "histogram_filename") { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, createDefaultHistogramFilename()); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); filenameProp->setCacheRefreshBit(); return filenameProp; } else if(name == "geometry_filename") { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, createDefaultGeometryFilename()); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); filenameProp->setCacheRefreshBit(); return filenameProp; } else if(name == "valid_vertices_filename") { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, createDefaultValidVerticesFilename()); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); filenameProp->setCacheRefreshBit(); return filenameProp; } else if(name == "metadata_filename") { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, createDefaultMetadataFilename()); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); filenameProp->setCacheRefreshBit(); return filenameProp; } else if(name == "overview_filename") { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, createDefaultOverviewFilename()); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); filenameProp->setCacheRefreshBit(); return filenameProp; } else if(name == "filename") { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, getFilename()); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); filenameProp->setFullRefreshBit(); return filenameProp; } else if ( name == OPEN_OVERVIEW_FLAG_KW) { ossimRefPtr result = new ossimBooleanProperty(ossimString(OPEN_OVERVIEW_FLAG_KW), theOpenOverviewFlag); return result; } return ossimImageSource::getProperty(name); } void ossimImageHandler::getPropertyNames(std::vector& propertyNames)const { ossimImageSource::getPropertyNames(propertyNames); propertyNames.push_back(ossimKeywordNames::ENTRY_KW); propertyNames.push_back(ossimKeywordNames::NUMBER_SAMPLES_KW); propertyNames.push_back(ossimKeywordNames::NUMBER_LINES_KW); propertyNames.push_back(ossimKeywordNames::NUMBER_BANDS_KW); propertyNames.push_back(ossimKeywordNames::NUMBER_REDUCED_RES_SETS_KW); propertyNames.push_back(ossimKeywordNames::SCALAR_TYPE_KW); propertyNames.push_back(OPEN_OVERVIEW_FLAG_KW); } ossimFilename ossimImageHandler::getFilenameWithThisExtension( const ossimString& ext, bool set_e0_prefix) const { // Get the image file. ossimFilename f = getFilename(); getFilenameWithNoExtension( f ); if (set_e0_prefix || (getNumberOfEntries() > 1)) { f += "_e"; f += ossimString::toString(getCurrentEntry()); } if (ext.size()) { if (ext.string()[0] != '.') { f += "."; } f += ext; } return f; } void ossimImageHandler::getFilenameWithThisExt( const ossimString& ext, ossimFilename& f ) const { // Get the image file. f = getFilename(); getFilenameWithNoExtension( f ); if (ext.size()) { if (ext.string()[0] != '.') { f += "."; } f += ext; } } void ossimImageHandler::getFilenameWithNoExtension( ossimFilename& f ) const { //--- // If the supplementary directory is set, find the extension at that // location instead of at the default. //--- if ( theSupplementaryDirectory.size() ) { ossimString drivePart; ossimString pathPart; ossimString filePart; ossimString extPart; f.split(drivePart, pathPart, filePart, extPart); ossimFilename newDrivePart = theSupplementaryDirectory.drive(); ossimFilename newPathPart = theSupplementaryDirectory.after(newDrivePart); f.merge( newDrivePart, newPathPart, filePart, extPart ); } // Wipe out the extension. f.setExtension(""); } bool ossimImageHandler::getOverviewTile(ossim_uint32 resLevel, ossimImageData* result) { bool status = false; if (theOverview.valid()) { if (theOverview->isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) ) { status = theOverview->getTile(result, resLevel); } } return status; } ossimRefPtr ossimImageHandler::getLut()const { return theLut; } bool ossimImageHandler::hasLut() const { return theLut.valid(); } ossimFilename ossimImageHandler::createDefaultOverviewFilename() const { return getFilenameWithThisExtension("ovr"); } ossimFilename ossimImageHandler::createDefaultGeometryFilename() const { return getFilenameWithThisExtension("geom"); } ossimFilename ossimImageHandler::createDefaultMetadataFilename() const { return getFilenameWithThisExtension("omd"); } ossimFilename ossimImageHandler::createDefaultHistogramFilename() const { return getFilenameWithThisExtension("his"); } ossimFilename ossimImageHandler::createDefaultValidVerticesFilename() const { ossimFilename result; result = theImageFile.path(); result = result.dirCat(theImageFile.fileNoExtension()); result += "_vertices"; if(getNumberOfEntries() > 1) { result += "_e"; result += ossimString::toString(getCurrentEntry()); } result += ".kwl"; return result; } ossim_uint32 ossimImageHandler::getStartingResLevel() const { return theStartingResLevel; } void ossimImageHandler::setStartingResLevel(ossim_uint32 level) { theStartingResLevel = level; } bool ossimImageHandler::getOpenOverviewFlag() const { return theOpenOverviewFlag; } void ossimImageHandler::setOpenOverviewFlag(bool flag) { theOpenOverviewFlag = flag; // If false close overview if open??? (drb) } void ossimImageHandler::initImageParameters(ossimImageGeometry* geom) const { if ( geom ) { // Set decimation levels ossim_uint32 num_levels = getNumberOfDecimationLevels(); if ((num_levels > 0) && (num_levels != geom->getNumberOfDecimations())) { geom->setDiscreteDecimation(theDecimationFactors); } // Set image size. if(geom->getImageSize().hasNans()) { ossimIrect rect = getBoundingRect(); geom->setImageSize(ossimIpt(rect.width(), rect.height())); } } } ossim-Miami-2.9.1/src/imaging/ossimImageHandlerFactory.cpp000066400000000000000000001152161352751253100235520ustar00rootroot00000000000000//--- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include // #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if OSSIM_HAS_HDF5 #include #endif static const ossimTrace traceDebug("ossimImageHandlerFactory:debug"); RTTI_DEF1(ossimImageHandlerFactory, "ossimImageHandlerFactory", ossimImageHandlerFactoryBase); ossimImageHandlerFactory* ossimImageHandlerFactory::theInstance = 0; ossimImageHandlerFactory::~ossimImageHandlerFactory() { theInstance = (ossimImageHandlerFactory*)0; } ossimImageHandlerFactory* ossimImageHandlerFactory::instance() { if(!theInstance) { theInstance = new ossimImageHandlerFactory; // let's turn off tiff error reporting TIFFSetErrorHandler(0); TIFFSetWarningHandler(0); } return theInstance; } ossimRefPtr ossimImageHandlerFactory::open( std::shared_ptr& str, const std::string& connectionString, bool openOverview ) const { ossimRefPtr result(0); // NITF: ossimRefPtr ih = new ossimNitfTileSource(); ih->setOpenOverviewFlag(openOverview); if ( ih->open( str, connectionString ) ) { result = ih.get(); } if( !result ) { // Reset the stream for downstream code. str->seekg(0, std::ios_base::beg); str->clear(); // TIFF: ossimRefPtr ihTiff = new ossimTiffTileSource(); ihTiff->setOpenOverviewFlag(openOverview); if ( ihTiff->open( str, connectionString ) ) { result = ihTiff.get(); } if(!result) { // Reset the stream for downstream code. str->seekg(0, std::ios_base::beg); str->clear(); // ossim dot.src file: result = openSrcRecord( str, connectionString, openOverview ); if ( !result ) { // Reset the stream for downstream code. str->seekg(0, std::ios_base::beg); str->clear(); } } } return result; } ossimImageHandler* ossimImageHandlerFactory::open(const ossimFilename& fileName, bool openOverview) const { static const char* M = "ossimImageHandlerFactory::open(filename) -- "; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M <<" Entering..." << std::endl; ossimFilename copyFilename = fileName; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Attempting to open file: " << fileName.c_str() << "\nopen overview flag: " << (openOverview?"true":"false") << "\n"; } ossimRefPtr result = 0; while (true) { // Check for empty file. copyFilename.trim(); if (copyFilename.empty()) break; // for all of our imagehandlers the filename must exist. // if we have any imagehandlers that require an encoded string and is contrlled in this factory then // we need to move this. if (!copyFilename.exists()) break; ossimString ext = copyFilename.ext().downcase(); if(ext == "gz") copyFilename = copyFilename.setExtension(""); // Try opening from extension logic first (this is faster than instantiating each type). // if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); //if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; // this must be checked first before the TIFF handler if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; //--- // The srtm and general raser readers were picking up j2k overviews because the // matching base file has an "omd" file that the raster reader can load // so added extension check. (drb - 20100709) //--- if (copyFilename.ext() != "ovr") { // Note: ENVI should be in front of general raster.. if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; // Note: SRTM should be in front of general raster.. if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; } if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); result = new ossimLasReader(); if (result->open(copyFilename)) break; #if OSSIM_HAS_HDF5 if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setOpenOverviewFlag(openOverview); if (result->open(copyFilename)) break; #endif result = 0; break; } if (traceDebug()) { if (result.valid()) ossimNotify(ossimNotifyLevel_DEBUG)< result = 0; while (true) { if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying adrg...\n"; result = new ossimAdrgTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying ccf...\n"; result = new ossimCcfTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M << "trying CIB/CADRG...\n"; result = new ossimCibCadrgTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M << "trying DOQQ...\n"; result = new ossimDoqqTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying DTED...\n"; result = new ossimDtedTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying jpeg...\n"; result = new ossimJpegTileSource(); if (result->loadState(kwl, prefix)) break; //if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying Quickbird NITF...\n"; //result = new ossimQuickbirdNitfTileSource; //if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M << "trying Nitf...\n"; result = new ossimNitfTileSource(); if (result->loadState(kwl, prefix)) break; // Must be before tiff... if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying Quickbird TIFF...\n"; result = new ossimQuickbirdTiffTileSource; if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying tiff...\n"; result = new ossimTiffTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying USGS Dem...\n"; result = new ossimUsgsDemTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying Landsat...\n"; result = new ossimLandsatTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying VPF...\n"; result = new ossimVpfTileSource; if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying ERS...\n"; result = new ossimERSTileSource; if (result->loadState(kwl, prefix)) break; // Note: ENVI should be in front of general raster... if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying ENVI...\n"<< std::endl; result = new ossimEnviTileSource(); if (result->loadState(kwl, prefix)) break; // Note: SRTM should be in front of general raster... if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M<< "trying SRTM...\n"<< std::endl; result = new ossimSrtmTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M << "trying General Raster...\n"<< std::endl; result = new ossimGeneralRasterTileSource(); if (result->loadState(kwl, prefix)) break; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<loadState(kwl, prefix)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<loadState(kwl, prefix)) break; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<loadState(kwl, prefix)) break; #if OSSIM_HAS_HDF5 if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<loadState(kwl, prefix)) break; #endif #ifdef ENABLE_POINT_CLOUD_HANDLER if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<loadState(kwl, prefix)) break; #endif result = 0; break; } if (traceDebug()) { if (result.valid()) ossimNotify(ossimNotifyLevel_DEBUG)< ossimImageHandlerFactory::open(std::shared_ptr state)const { ossimRefPtr result = 0; if(state) { ossimRefPtr obj = createObject(state->getImageHandlerType()); if(obj) { result = dynamic_cast(obj.get()); if(result) { if(!result->open(state)) { result = 0; } } obj = 0; } } return result; } ossimRefPtr ossimImageHandlerFactory::openOverview( const ossimFilename& file ) const { ossimRefPtr result = 0; if ( file.size() ) { result = new ossimTiffTileSource; result->setOpenOverviewFlag( false ); // Always false. if ( result->open( file ) == false ) { result = 0; } } return result; } #if 0 ossimImageHandler* ossimImageHandlerFactory::openFromExtension(const ossimFilename& fileName) const { static const char* M = "ossimImageHandlerFactory::openFromExtension() -- "; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<"< result = 0; while (true) { // OVR can be combined with "tif" once we get rid of ossimQuickbirdTiffTileSource if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; result = new ossimTiffTileSource; if(result->open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; result = new ossimNitfTileSource; if(result->open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; result = new ossimImagefCacheTileSource; if(result->open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<open(fileName)) break; } result = 0; break; } if (traceDebug()) { if (result.valid()) ossimNotify(ossimNotifyLevel_DEBUG)<open(kwl, prefix);//ossimFilename(lookup)); } } else { result = createObject(ossimString(type)); if(result) { result->loadState(kwl, prefix); } } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageHandlerFactory::createObject(kwl, prefix) DEBUG: returning result ..." << std::endl; } return result; } void ossimImageHandlerFactory::getTypeNameList(std::vector& typeList)const { typeList.push_back(STATIC_TYPE_NAME(ossimAdrgTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimCcfTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimCibCadrgTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimEnviTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimRpfCacheTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimImageCacheTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimDoqqTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimDtedTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimJpegTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimNitfTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimTiffTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimUsgsDemTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimLandsatTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimERSTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimSrtmTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimGeneralRasterTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimQuickbirdNitfTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimQuickbirdTiffTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimQbTileFilesHandler)); typeList.push_back(STATIC_TYPE_NAME(ossimBitMaskTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimRangeDomeTileSource)); #if OSSIM_HAS_HDF5 typeList.push_back(STATIC_TYPE_NAME(ossimViirsHandler)); #endif #ifdef ENABLE_POINT_CLOUD_HANDLER typeList.push_back(STATIC_TYPE_NAME(ossimPointCloudImageHandler)); #endif typeList.push_back(STATIC_TYPE_NAME(ossimImageHandlerMtAdaptor)); } ossimRefPtr ossimImageHandlerFactory::openSrcRecord( std::shared_ptr& str, const std::string& connectionString, bool openOverview ) const { ossimRefPtr result = 0; if(!str) return result; // Check the extension for ".src" before going any further: std::size_t found = connectionString.find( std::string(".src") ); if ( found != std::string::npos && ( found == (connectionString.size() - 4) ) ) { ossimKeywordlist kwl; if ( kwl.parseStream( *str ) ) { // Right now only concidering one image, i.e. "image0": std::string prefix = "image0."; ossimSrcRecord src; if ( src.loadState(kwl, prefix.c_str() ) ) { if ( src.getFilename().string().size() ) { // Avoid recursive loop: if (src.getFilename().string() != connectionString ) { result = ossimImageHandlerRegistry::instance()-> openConnection( src.getFilename(), false ); if ( result.valid() ) { ossimFilename supportDir = src.getSupportDir(); if ( supportDir.empty() ) { if ( src.getOverviewPath().size() ) { if ( src.getOverviewPath().isDir() ) { supportDir = src.getOverviewPath(); } else { supportDir = src.getOverviewPath().path(); } } else if ( src.getHistogramPath().size() ) { if ( src.getHistogramPath().isDir() ) { supportDir = src.getHistogramPath(); } else { supportDir = src.getHistogramPath().path(); } } } if ( supportDir.size() && (src.getFilename().path() != supportDir) ) { result->setSupplementaryDirectory( supportDir ); } if ( src.getEntryIndex() > 0 ) // defaulted to -1. { result->setCurrentEntry( static_cast( src.getEntryIndex() ) ); } if ( openOverview && ( result->getOverview() == 0 ) ) { if ( src.getOverviewPath().size() ) { result->openOverview( src.getOverviewPath() ); } else { ossimFilename ovrFile = result-> getFilenameWithThisExtension(ossimString(".ovr")); result->openOverview( ovrFile ); } } } } } } } // Matches: if ( kwl.parseStream( str ) ) if ( !result ) { // Reset the stream for downstream code. str->seekg(0, std::ios_base::beg); str->clear(); } } return result; } ossim-Miami-2.9.1/src/imaging/ossimImageHandlerFactoryBase.cpp000066400000000000000000000034471352751253100243470ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id$ #include RTTI_DEF1(ossimImageHandlerFactoryBase, "ossimImageHandlerFactoryBase", ossimObjectFactory); void ossimImageHandlerFactoryBase::getImageHandlersBySuffix(ImageHandlerList& /*result*/, const ossimString& /*ext*/)const { } void ossimImageHandlerFactoryBase::getImageHandlersByMimeType(ImageHandlerList& /*result*/, const ossimString& /*mimeType*/)const { } ossimRefPtr ossimImageHandlerFactoryBase::openOverview( const ossimFilename& /* file */ ) const { return ossimRefPtr(0); } #if 0 ossimRefPtr ossimImageHandlerFactoryBase::open( ossim::istream* /* str */, std::streamoff /* restartPosition */, bool /* youOwnIt */ ) const { return ossimRefPtr(0); } #endif ossimRefPtr ossimImageHandlerFactoryBase::open( std::shared_ptr& /*str */, const std::string& /* connectionString */, bool /* openOverview */ ) const { return ossimRefPtr(0); } ossimRefPtr ossimImageHandlerFactoryBase::open(std::shared_ptr state)const { return ossimRefPtr(0); } ossimRefPtr ossimImageHandlerFactoryBase::openOverview( std::shared_ptr& /* str */, const ossimString& /* connectionString */ ) const { return ossimRefPtr(0); } ossim-Miami-2.9.1/src/imaging/ossimImageHandlerRegistry.cpp000066400000000000000000000435711352751253100237570ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts // // Description: // // Contains class definition for ImageHandlerRegistry. // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimImageHandlerRegistry:debug"); RTTI_DEF1(ossimImageHandlerRegistry, "ossimImageHandlerRegistry", ossimObjectFactory); //ossimImageHandlerRegistry* ossimImageHandlerRegistry::theInstance = 0; ossimImageHandlerRegistry::ossimImageHandlerRegistry() { ossimObjectFactoryRegistry::instance()->registerFactory(this); registerFactory(ossimImageHandlerFactory::instance()); initializeStateCache(); } ossimImageHandlerRegistry* ossimImageHandlerRegistry::instance() { static ossimImageHandlerRegistry sharedInstance; return &sharedInstance; } ossimImageHandlerRegistry::~ossimImageHandlerRegistry() { unregisterAllFactories(); } ossimObject* ossimImageHandlerRegistry::createObject(const ossimKeywordlist& kwl, const char* prefix)const { ossimObject* result = createObjectFromRegistry(kwl, prefix); if(!result) { result = open(kwl, prefix); } return result; } ossimRefPtr ossimImageHandlerRegistry::openBySuffix(const ossimFilename& file, bool openOverview)const { std::vector > handlers; getImageHandlersBySuffix(handlers, file.ext()); ossim_uint32 idx = 0; ossim_uint32 size = (ossim_uint32) handlers.size(); for(idx = 0; idx < size; ++idx) { handlers[idx]->setOpenOverviewFlag(openOverview); if(handlers[idx]->open(file)) { return handlers[idx]; } } return ossimRefPtr(0); } void ossimImageHandlerRegistry::getImageHandlersBySuffix(ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& ext)const { vector::const_iterator iter = m_factoryList.begin(); ossimImageHandlerFactoryBase::ImageHandlerList temp; while(iter != m_factoryList.end()) { temp.clear(); (*iter)->getImageHandlersBySuffix(temp, ext); if(!temp.empty()) { // now append to the end of the typeList. result.insert(result.end(), temp.begin(), temp.end()); } ++iter; } } void ossimImageHandlerRegistry::getImageHandlersByMimeType( ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& mimeType)const { vector::const_iterator iter = m_factoryList.begin(); ossimImageHandlerFactoryBase::ImageHandlerList temp; while(iter != m_factoryList.end()) { temp.clear(); (*iter)->getImageHandlersByMimeType(temp, mimeType); if(!temp.empty()) { // now append to the end of the typeList. result.insert(result.end(), temp.begin(), temp.end()); } ++iter; } } void ossimImageHandlerRegistry::getTypeNameList( std::vector& typeList ) const { getAllTypeNamesFromRegistry(typeList); } void ossimImageHandlerRegistry::getSupportedExtensions( ossimImageHandlerFactoryBase::UniqueStringList& extensionList)const { vector result; vector::const_iterator iter = m_factoryList.begin(); while(iter != m_factoryList.end()) { (*iter)->getSupportedExtensions(extensionList); ++iter; } } std::shared_ptr ossimImageHandlerRegistry::getState(const ossimString& connectionString, ossim_uint32 entry)const { return getState(connectionString + "_e" + ossimString::toString(entry)); } std::shared_ptr ossimImageHandlerRegistry::getState(const ossimString& id)const { std::shared_ptr result; if(m_stateCache) { result = m_stateCache->getItem(id); } return result; } ossimRefPtr ossimImageHandlerRegistry::openConnection( const ossimString& connectionString, bool openOverview )const { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::openConnection: entered.........." << std::endl; } ossimRefPtr result(0); std::string myConnectionString = connectionString.downcase().string(); std::string fileStr = "file://"; std::size_t found = myConnectionString.find( fileStr ); if ( found == 0 ) { myConnectionString = connectionString.string().substr( fileStr.size() ); } else { myConnectionString = connectionString.string(); } // add entry 0 std::shared_ptr state = getState(myConnectionString, 0); if(state) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::openConnection: leaving with open(state).........." << std::endl;; } return open(state); } std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( myConnectionString, std::ios_base::in|std::ios_base::binary); if ( str ) { result = open( str, myConnectionString, openOverview ); } if ( !result.valid() ) { ossimFilename f = myConnectionString; if ( f.exists() ) { result = open( f, true, openOverview ); } } if(result) { addToStateCache(result.get()); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::openConnection: leaving.........." << std::endl; } return result; } ossimImageHandler* ossimImageHandlerRegistry::open(const ossimFilename& filename, bool trySuffixFirst, bool openOverview)const { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::open(file, trySuffix,openOverview): entered.........." << std::endl; } std::shared_ptr state = getState(filename, 0); if(state) { ossimRefPtr h = open(state); if(h) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::open(file, trySuffix,openOverview): returning with state open.........." << std::endl;; } return h.release(); } } if(trySuffixFirst) { ossimRefPtr h = openBySuffix(filename, openOverview); if(h.valid()) { addToStateCache(h.get()); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::open(file, trySuffix,openOverview): leaving.........." << std::endl; } return h.release(); } } // now try magic number opens // ossimImageHandler* result = NULL; vector::const_iterator factory = m_factoryList.begin(); while((factory != m_factoryList.end()) && !result) { result = (*factory)->open(filename, openOverview); ++factory; } if(result) { addToStateCache(result); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::open(file, trySuffix,openOverview): leaving.........." << std::endl; } return result; } ossimImageHandler* ossimImageHandlerRegistry::open(const ossimKeywordlist& kwl, const char* prefix)const { ossimImageHandler* result = NULL; vector::const_iterator factory; factory = m_factoryList.begin(); while((factory != m_factoryList.end()) && !result) { result = (*factory)->open(kwl, prefix); ++factory; } if(result) { addToStateCache(result); } return result; } ossimRefPtr ossimImageHandlerRegistry::open( std::shared_ptr& str, const std::string& connectionString, bool openOverview ) const { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::open(stream,connectionString,openOverview): entered.........." << std::endl; } ossimRefPtr result = 0; std::shared_ptr state = getState(connectionString, 0); if(state) { result = open(state); if(result) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::open(stream,connectionString,openOverview): leaving with state open..........Valid? " << result.valid() <::const_iterator factory = m_factoryList.begin(); while( factory != m_factoryList.end() ) { result = (*factory)->open( str, connectionString, openOverview ); if ( result.valid() ) { break; } ++factory; } } if(result) { addToStateCache(result.get()); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::open(stream,connectionString,openOverview): leaving..........Valid? " << result.valid()< ossimImageHandlerRegistry::open(std::shared_ptr state)const { ossimRefPtr result = 0; vector::const_iterator factory = m_factoryList.begin(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::open(state): Entered......." << std::endl; } while( (!result)&&(factory != m_factoryList.end()) ) { result = (*factory)->open( state ); if ( result ) { break; } ++factory; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::open(state): Leaving.......valid?" << result.valid()< ossimImageHandlerRegistry::open( ossim::istream* str, std::streamoff restartPosition, bool youOwnIt ) const { ossimRefPtr result = 0; vector::const_iterator factory = m_factoryList.begin(); while( factory != m_factoryList.end() ) { result = (*factory)->open( str, restartPosition, youOwnIt ); if ( result.valid() ) { break; } ++factory; } return result; } #endif ossimRefPtr ossimImageHandlerRegistry::openOverview( const ossimFilename& file ) const { ossimRefPtr result = 0; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::openOverview: Entered......." << std::endl; } std::shared_ptr state = getState(file, 0); if(state) { result = open(state); } if(!result) { // See if we can open via the stream interface: std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( file, std::ios_base::in|std::ios_base::binary); if ( str ) { std::vector::const_iterator factory = m_factoryList.begin(); while( factory != m_factoryList.end() ) { result = (*factory)->openOverview( str, file ); if ( result.valid() ) { break; } ++factory; } str = 0; } if ( (result.valid() == false) && file.exists() ) { vector::const_iterator factory = m_factoryList.begin(); while( factory != m_factoryList.end() ) { result = (*factory)->openOverview( file ); if ( result.valid() ) { break; } ++factory; } } if(result) { addToStateCache(result.get()); } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::openOverview: Leaving.......Valid? " << result.valid() << std::endl; } return result; } ossimObject* ossimImageHandlerRegistry::createObject(const ossimString& typeName) const { return createObjectFromRegistry(typeName); } std::ostream& ossimImageHandlerRegistry::printReaderProps(std::ostream& out) const { // Loop through factories: vector::const_iterator factory = m_factoryList.begin(); while( factory != m_factoryList.end() ) { out << "factory: " << (*factory)->getClassName() << "\n"; // Loop through factory image handlers: std::vector readerList; (*factory)->getTypeNameList(readerList); std::vector::const_iterator i = readerList.begin(); while ( i != readerList.end() ) { ossimRefPtr ih = dynamic_cast( (*factory)->createObject( (*i) ) ); if ( ih.valid() ) { out << "reader: " << ih->getClassName() << "\n"; // Loop through image handler properties: std::vector propNames; ih->getPropertyNames(propNames); if ( propNames.size() ) { out << "\nproperties:\n"; ossimRefPtr prop = 0; std::vector::const_iterator p = propNames.begin(); while ( p != propNames.end() ) { out << " " << (*p) << "\n"; prop = ih->getProperty( *p ); if ( prop.valid() ) { ossimStringProperty* stringProp = dynamic_cast(prop.get()); if ( stringProp ) { if ( stringProp->getConstraints().size() ) { out << " constraints:\n"; std::vector::const_iterator strPropIter = stringProp->getConstraints().begin(); while( strPropIter != stringProp->getConstraints().end() ) { out << " " << (*strPropIter) << "\n"; ++strPropIter; } } } } ++p; } out << "\n"; } } ++i; } ++factory; } out << std::endl; return out; } ossimImageHandlerRegistry::ossimImageHandlerRegistry(const ossimImageHandlerRegistry& /* rhs */) : ossimObjectFactory() {} void ossimImageHandlerRegistry::initializeStateCache()const { m_stateCache = 0; ossimString enabledString = ossimPreferences::instance()->findPreference("ossim.imaging.handler.registry.state_cache.enabled"); ossimString minSizeString = ossimPreferences::instance()->findPreference("ossim.imaging.handler.registry.state_cache.min_size"); ossimString maxSizeString = ossimPreferences::instance()->findPreference("ossim.imaging.handler.registry.state_cache.max_size"); ossim_uint32 maxSize = 0; ossim_uint32 minSize = 0; if(!enabledString.empty()) { if(enabledString.toBool()) { m_stateCache = std::make_shared >(); if(!maxSizeString.empty()) { maxSize = maxSizeString.toUInt32(); } if(!minSizeString.empty()) { minSize = minSizeString.toUInt32(); } else if(maxSize) { minSize = ossim::round(maxSize*.8); } if(minSize < maxSize) { m_stateCache->setMinAndMaxItemsToCache(minSize, maxSize); } } } } void ossimImageHandlerRegistry::addToStateCache(ossimImageHandler* handler)const { if(handler) { std::shared_ptr state = handler->getState(); if(state&&m_stateCache) { ossimString id = handler->getFilename()+"_e"+ossimString::toString(state->getCurrentEntry()); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimImageHandlerRegistry::addToStateCache: " << id << std::endl; } m_stateCache->addItem(id, state); } } } const ossimImageHandlerRegistry& ossimImageHandlerRegistry::operator=(const ossimImageHandlerRegistry& rhs) { return rhs; } extern "C" { void* ossimImageHandlerRegistryGetInstance() { return ossimImageHandlerRegistry::instance(); } } ossim-Miami-2.9.1/src/imaging/ossimImageHistogramSource.cpp000066400000000000000000000403451352751253100237630ustar00rootroot00000000000000//******************************************************************* // // License: See LICENSE.txt file in the top level directory. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageHistogramSource.cpp 22737 2014-04-16 18:53:57Z gpotts $ #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimImageHistogramSource:debug"); RTTI_DEF3(ossimImageHistogramSource, "ossimImageHistogramSource", ossimHistogramSource, ossimConnectableObjectListener, ossimProcessInterface); ossimImageHistogramSource::ossimImageHistogramSource(ossimObject* owner) :ossimHistogramSource(owner, 1, // one input 0, // no outputs true, // input list is fixed false),// output can still grow though theHistogramRecomputeFlag(true), theMaxNumberOfResLevels(1), theComputationMode(OSSIM_HISTO_MODE_NORMAL) // theNumberOfTilesToUseInFastMode(100) { theAreaOfInterest.makeNan(); addListener((ossimConnectableObjectListener*)this); theMinValueOverride = ossim::nan(); theMaxValueOverride = ossim::nan(); theNumberOfBinsOverride = -1; } ossimImageHistogramSource::~ossimImageHistogramSource() { removeListener((ossimConnectableObjectListener*)this); } ossimObject* ossimImageHistogramSource::getObject() { return this; } const ossimObject* ossimImageHistogramSource::getObject()const { return this; } void ossimImageHistogramSource::setAreaOfInterest(const ossimIrect& rect) { if(rect != theAreaOfInterest) { theHistogramRecomputeFlag = true; } theAreaOfInterest = rect; } ossimIrect ossimImageHistogramSource::getAreaOfInterest()const { return theAreaOfInterest; } void ossimImageHistogramSource::getAreaOfInterest(ossimIrect& rect)const { rect = theAreaOfInterest; } ossim_uint32 ossimImageHistogramSource::getMaxNumberOfRLevels()const { return theMaxNumberOfResLevels; } void ossimImageHistogramSource::setMaxNumberOfRLevels(ossim_uint32 number) { if(number != theMaxNumberOfResLevels) { theHistogramRecomputeFlag = true; } theMaxNumberOfResLevels = number; } ossimRefPtr ossimImageHistogramSource::getHistogram(const ossimIrect& rect) { if((theAreaOfInterest != rect)|| (theAreaOfInterest.hasNans())) { theAreaOfInterest = rect; theHistogramRecomputeFlag = true; } return getHistogram(); } bool ossimImageHistogramSource::execute() { if(!isSourceEnabled()) { return theHistogram.valid(); } setProcessStatus(ossimProcessInterface::PROCESS_STATUS_EXECUTING); if(theHistogramRecomputeFlag) { if(theAreaOfInterest.hasNans()) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { theAreaOfInterest = interface->getBoundingRect(); } } switch(theComputationMode) { case OSSIM_HISTO_MODE_FAST: { computeFastModeHistogram(); break; } case OSSIM_HISTO_MODE_NORMAL: default: { computeNormalModeHistogram(); break; } } } if (needsAborting()) { setProcessStatus(ossimProcessInterface::PROCESS_STATUS_ABORTED); theHistogramRecomputeFlag = false; } else { setProcessStatus(ossimProcessInterface::PROCESS_STATUS_NOT_EXECUTING); } return true; } bool ossimImageHistogramSource::canConnectMyInputTo(ossim_int32 myInputIndex, const ossimConnectableObject* object)const { return ((myInputIndex==0)&&PTR_CAST(ossimImageSource, object)); } void ossimImageHistogramSource::setNumberOfBinsOverride(ossim_int32 numberOfBinsOverride) { theNumberOfBinsOverride = numberOfBinsOverride; } void ossimImageHistogramSource::setMinValueOverride(ossim_float32 minValueOverride) { theMinValueOverride = minValueOverride; } void ossimImageHistogramSource::setMaxValueOverride(ossim_float32 maxValueOverride) { theMaxValueOverride = maxValueOverride; } ossimHistogramMode ossimImageHistogramSource::getComputationMode()const { return theComputationMode; } void ossimImageHistogramSource::setComputationMode(ossimHistogramMode mode) { theComputationMode = mode; } void ossimImageHistogramSource::propertyEvent(ossimPropertyEvent& /* event */) { theHistogramRecomputeFlag = true; } void ossimImageHistogramSource::connectInputEvent(ossimConnectionEvent& /* event */) { theHistogramRecomputeFlag = true; } ossimRefPtr ossimImageHistogramSource::getHistogram() { execute(); return theHistogram; } bool ossimImageHistogramSource::getBinInformation(ossim_uint32& numberOfBins, ossim_float32& minValue, ossim_float32& maxValue, ossim_float32& nullValue, ossim_uint32 band)const { bool result = false; ossimImageSource* input = PTR_CAST(ossimImageSource, getInput(0)); if(input) { result = ossim::getBinInformation( input, band, numberOfBins, minValue, maxValue, nullValue ); if ( result ) { if(ossim::isnan(theMinValueOverride) == false) { minValue = (float)theMinValueOverride; } if(ossim::isnan(theMaxValueOverride) == false) { maxValue = (float)theMaxValueOverride; } if(theNumberOfBinsOverride > 0) { numberOfBins = theNumberOfBinsOverride; } } } return result; } void ossimImageHistogramSource::computeNormalModeHistogram() { // ref ptr, not a leak. theHistogram = new ossimMultiResLevelHistogram; ossimImageSource *input = PTR_CAST(ossimImageSource, getInput(0)); if ( input ) { // sum up all tiles needing processing. We will use the sequencer. // ossim_uint32 numberOfResLevels = input->getNumberOfDecimationLevels(); ossim_uint32 index = 0; double tileCount = 0.0; double totalTiles = 0.0; ossim_uint32 numberOfBands = input->getNumberOfOutputBands(); ossim_uint32 numberOfBins = 0; ossim_float32 minValue = 0; ossim_float32 maxValue = 0; ossim_float32 nullValue = 0; if ( getBinInformation(numberOfBins, minValue, maxValue, nullValue, 0) ) { ossimRefPtr sequencer = new ossimImageSourceSequencer(); // If the input is tiled use that tile size: ossimIpt inputTileSize; inputTileSize.x = input->getTileWidth(); inputTileSize.y = input->getTileHeight(); if ( (inputTileSize.x != 0) && (inputTileSize.y != 0) ) { sequencer->setTileSize( inputTileSize ); } sequencer->connectMyInputTo(0, getInput(0)); sequencer->initialize(); vector decimationFactors; input->getDecimationFactors(decimationFactors); if ( !decimationFactors.size() ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageHistogramSource::computeNormalModeHistogram WARNING:" << "\nNo decimation factors from input. returning..." << std::endl; return; } ossim_uint32 resLevelsToCompute = ossim::min((ossim_uint32)theMaxNumberOfResLevels, (ossim_uint32)decimationFactors.size()); if( decimationFactors.size() < theMaxNumberOfResLevels) { ossimNotify(ossimNotifyLevel_WARN) << "Number Decimations is smaller than the request number of r-levels defaulting to the smallest of the 2 numbers" << endl; } theHistogram->create(resLevelsToCompute); for(index = 0; index < resLevelsToCompute; ++index) { sequencer->setAreaOfInterest(theAreaOfInterest*decimationFactors[index]); totalTiles += sequencer->getNumberOfTiles(); } if(numberOfBins > 0) { setPercentComplete(0.0); for(index = 0; (index < resLevelsToCompute); ++index) { // Check for abort request. if (needsAborting()) { setPercentComplete(100); break; } //sequencer->setAreaOfInterest(input->getBoundingRect(index)); sequencer->setAreaOfInterest(theAreaOfInterest*decimationFactors[index]); sequencer->setToStartOfSequence(); theHistogram->getMultiBandHistogram(index)->create( numberOfBands, numberOfBins, minValue, maxValue, nullValue, input->getOutputScalarType() ); ossimRefPtr data = sequencer->getNextTile(index); ++tileCount; setPercentComplete((100.0*(tileCount/totalTiles))); ossim_uint32 resLevelTotalTiles = sequencer->getNumberOfTiles(); for (ossim_uint32 resLevelTileCount = 0; resLevelTileCount < resLevelTotalTiles; ++resLevelTileCount) { //--- // Counting nulls now so the check for OSSIM_EMPTY status // removed. drb - 20190227 //--- if( data.valid() ) { data->populateHistogram( theHistogram->getMultiBandHistogram(index), theAreaOfInterest ); } // Check for abort request. if (needsAborting()) { setPercentComplete(100); break; } data = sequencer->getNextTile(index); ++tileCount; setPercentComplete((100.0*(tileCount/totalTiles))); } } } sequencer->disconnect(); sequencer = 0; } } else { setPercentComplete(100.0); } } void ossimImageHistogramSource::computeFastModeHistogram() { // Compute at most 9 x 9 tiles of 16 x 16 tile size. ossim_uint32 resLevelsToCompute = 1; // ref ptr, not a leak. theHistogram = new ossimMultiResLevelHistogram; theHistogram->create(resLevelsToCompute); ossimImageSource* input = PTR_CAST(ossimImageSource, getInput(0)); if(!input) { setPercentComplete(100.0); return; } // sum up all tiles needing processing. We will use the sequencer. // ossim_uint32 numberOfResLevels = input->getNumberOfDecimationLevels(); double tileCount = 0.0; double totalTiles = 0.0; ossim_uint32 numberOfBands = input->getNumberOfOutputBands(); ossim_uint32 numberOfBins = 0; ossim_float32 minValue = 0; ossim_float32 maxValue = 0; ossim_float32 nullValue = 0; // Assuming all bands have the same min, max, null as band 0: if ( getBinInformation(numberOfBins, minValue, maxValue, nullValue, 0) ) { // Fixed 32 x 32 tile size: ossimIpt tileSize( 32, 32 ); ossimIrect tileBoundary = theAreaOfInterest; tileBoundary.stretchToTileBoundary(tileSize); // Max of 11 x 11 tiles accross the image. const ossim_uint32 MAX_TILES_WIDE = 11; ossim_uint32 tilesWide = ossim::min( (ossim_uint32)(tileBoundary.width()/tileSize.x), MAX_TILES_WIDE); ossim_uint32 tilesHigh = ossim::min( (ossim_uint32)(tileBoundary.height()/tileSize.y), MAX_TILES_WIDE); totalTiles = tilesWide*tilesHigh; if(numberOfBins > 0) { ossimIpt origin = theAreaOfInterest.ul(); ossim_uint32 xTileOffset = tileBoundary.width() / tilesWide; ossim_uint32 yTileOffset = tileBoundary.height() / tilesHigh; theHistogram->getMultiBandHistogram(0)->create( numberOfBands, numberOfBins, minValue, maxValue, nullValue, input->getOutputScalarType() ); ossim_uint32 x = 0; ossim_uint32 y = 0; tileCount = 0; totalTiles = tilesWide*tilesHigh; for(y = 0; y < tilesHigh; ++y) { for(x = 0; x < tilesWide; ++x) { ossimIpt ul( origin.x + (x*xTileOffset), origin.y + (y*yTileOffset) ); ossimIrect tileRect(ul.x, ul.y, ul.x + tileSize.x-1, ul.y + tileSize.y-1); ossimRefPtr data = input->getTile(tileRect); if(data.valid()&&data->getBuf()&&(data->getDataObjectStatus() != OSSIM_EMPTY)) { data->populateHistogram( theHistogram->getMultiBandHistogram(0), theAreaOfInterest ); } // Check for abort request. if (needsAborting()) { break; } ++tileCount; } // Check for abort request. if (needsAborting()) { setPercentComplete(100); break; } setPercentComplete((100.0*(tileCount/totalTiles))); } } } } bool ossimImageHistogramSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimHistogramSource::loadState(kwl, prefix); if ( result ) { std::string myPrefix = (prefix?prefix:""); std::string key = "area_of_interest"; ossimString value; value.string() = kwl.findKey( myPrefix, key); if ( value.size() ) { theAreaOfInterest.toRect( value ); } key = "mode"; value.string() = kwl.findKey( myPrefix, key); if ( value.size() ) { if(value == "normal") { theComputationMode = OSSIM_HISTO_MODE_NORMAL; } else if(value == "fast") { theComputationMode = OSSIM_HISTO_MODE_FAST; } } } #if 0 /* old loadState drb - 20181114 */ // setNumberOfInputs(2); // ossimString rect = kwl.find(prefix, "rect"); if(!rect.empty()) { loadState(kwl, prefix); } else { ossimString newPrefix = ossimString(prefix) + "area_of_interest."; theAreaOfInterest.loadState(kwl, newPrefix); } ossimString mode = kwl.find(prefix, "mode"); mode = mode.downcase(); if(mode == "normal") { theComputationMode = OSSIM_HISTO_MODE_NORMAL; } else if(mode == "fast") { theComputationMode = OSSIM_HISTO_MODE_FAST; } if(getNumberOfInputs()!=1) { setNumberOfInputs(1); } // ossimString numberOfTiles = kwl.find(prefix, "number_of_tiles"); // if(!numberOfTiles.empty()) // { // theNumberOfTilesToUseInFastMode = numberOfTiles.toUInt32(); // } theInputListIsFixedFlag = true; theOutputListIsFixedFlag = false; #endif return result; } bool ossimImageHistogramSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimHistogramSource::saveState(kwl, prefix); if(result) { std::string myPrefix = (prefix?prefix:""); std::string key = "area_of_interest"; ossimString value = theAreaOfInterest.toString(); kwl.addPair( myPrefix, key, value.string() ); key = "mode"; if ( theComputationMode == OSSIM_HISTO_MODE_NORMAL ) { value = "normal"; } else if ( theComputationMode == OSSIM_HISTO_MODE_FAST ) { value = "fast"; } else { value = "unknown"; } kwl.addPair( myPrefix, key, value.string() ); } return result; } ossim-Miami-2.9.1/src/imaging/ossimImageMetaDataWriterFactory.cpp000066400000000000000000000136041352751253100250500ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Kenneth Melero // //******************************************************************* // $Id: ossimImageMetaDataWriterFactory.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include #include #include RTTI_DEF1(ossimImageMetaDataWriterFactory, "ossimImageMetaDataWriterFactory", ossimImageMetaDataWriterFactoryBase); ossimImageMetaDataWriterFactory* ossimImageMetaDataWriterFactory::theInstance = NULL; ossimImageMetaDataWriterFactory::ossimImageMetaDataWriterFactory() { theInstance = this; } ossimImageMetaDataWriterFactory::~ossimImageMetaDataWriterFactory() { theInstance = NULL; } ossimImageMetaDataWriterFactory* ossimImageMetaDataWriterFactory::instance() { if(!theInstance) { theInstance = new ossimImageMetaDataWriterFactory; } return theInstance; } ossimObject* ossimImageMetaDataWriterFactory::createObject( const ossimString& typeName) const { // Use the type name to instantiate the class. ossimObject* result = (ossimObject*)NULL; if(STATIC_TYPE_NAME(ossimEnviHeaderFileWriter) == typeName) { result = new ossimEnviHeaderFileWriter; } if(STATIC_TYPE_NAME(ossimERSFileWriter) == typeName) { result = new ossimERSFileWriter; } else if(STATIC_TYPE_NAME(ossimFgdcFileWriter) == typeName) { result = new ossimFgdcFileWriter; } else if(STATIC_TYPE_NAME(ossimGeomFileWriter) == typeName) { result = new ossimGeomFileWriter; } else if(STATIC_TYPE_NAME(ossimReadmeFileWriter) == typeName) { result = new ossimReadmeFileWriter; } //--- // Special case for backwards compatibility. ossimJpegWorldFileWriter and // ossimTiffWorldFileWriter same; hence, moved to ossimWorldFileWriter. //--- else if( (STATIC_TYPE_NAME(ossimWorldFileWriter) == typeName) || (ossimString("ossimJpegWorldFileWriter") == typeName) || (ossimString("ossimTiffWorldFileWriter") == typeName) ) { result = new ossimWorldFileWriter; } return result; } ossimObject* ossimImageMetaDataWriterFactory::createObject( const ossimKeywordlist& kwl, const char* prefix)const { //--- // Check the type keyword found in kwl. Use the create by class name // above and then call load state. //--- ossimObject* result = (ossimObject*)NULL; const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if(type) { result = createObject(ossimString(type)); if(result) { result->loadState(kwl, prefix); } } return result; } ossimRefPtr ossimImageMetaDataWriterFactory::createWriter(const ossimString& type)const { ossimRefPtr writer; writer = new ossimEnviHeaderFileWriter; if ( (writer->getClassName() == type) || (writer->hasMetadataType(type)) ) { return writer; } writer = new ossimERSFileWriter; if ( (writer->getClassName() == type) || (writer->hasMetadataType(type)) ) { return writer; } writer = new ossimFgdcFileWriter; if ( (writer->getClassName() == type) || (writer->hasMetadataType(type)) ) { return writer; } writer = new ossimGeomFileWriter; if ( (writer->getClassName() == type) || (writer->hasMetadataType(type)) ) { return writer; } writer = new ossimReadmeFileWriter; if ( (writer->getClassName() == type) || (writer->hasMetadataType(type)) ) { return writer; } //--- // Special case for backwards compatibility. ossimJpegWorldFileWriter and // ossimTiffWorldFileWriter same; hence, moved to ossimWorldFileWriter. //--- writer = new ossimWorldFileWriter; if ( (writer->getClassName() == type) || (writer->hasMetadataType(type)) || (ossimString("ossimJpegWorldFileWriter") == type) || (ossimString("ossimTiffWorldFileWriter") == type) ) { return writer; } // Not in factory. writer = NULL; return writer; } void ossimImageMetaDataWriterFactory::getTypeNameList( std::vector& typeList) const { // add each object's RTTI name here typeList.push_back(STATIC_TYPE_NAME(ossimEnviHeaderFileWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimERSFileWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimFgdcFileWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimGeomFileWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimReadmeFileWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimWorldFileWriter)); } void ossimImageMetaDataWriterFactory::getMetadatatypeList( std::vector& metadatatypeList) const { ossimRefPtr writer; writer = new ossimEnviHeaderFileWriter; writer->getMetadatatypeList(metadatatypeList); writer = new ossimERSFileWriter; writer->getMetadatatypeList(metadatatypeList); writer = new ossimFgdcFileWriter; writer->getMetadatatypeList(metadatatypeList); writer = new ossimGeomFileWriter; writer->getMetadatatypeList(metadatatypeList); writer = new ossimReadmeFileWriter; writer->getMetadatatypeList(metadatatypeList); writer = new ossimWorldFileWriter; writer->getMetadatatypeList(metadatatypeList); } ossimImageMetaDataWriterFactory::ossimImageMetaDataWriterFactory( const ossimImageMetaDataWriterFactory& /* rhs */) { } const ossimImageMetaDataWriterFactory& ossimImageMetaDataWriterFactory::operator=( const ossimImageMetaDataWriterFactory& /* rhs */) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimImageMetaDataWriterFactoryBase.cpp000066400000000000000000000015731352751253100256450ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: LGPL // // See LICENSE.txt file in the top level directory for more details. //---------------------------------------------------------------------------- // $Id: ossimImageMetaDataWriterFactoryBase.cpp 9094 2006-06-13 19:12:40Z dburken $ #include RTTI_DEF1(ossimImageMetaDataWriterFactoryBase, "ossimImageMetaDataWriterFactoryBase", ossimObjectFactory); ossimImageMetaDataWriterFactoryBase::ossimImageMetaDataWriterFactoryBase() { } ossimImageMetaDataWriterFactoryBase::ossimImageMetaDataWriterFactoryBase( const ossimImageMetaDataWriterFactoryBase&) { } const ossimImageMetaDataWriterFactoryBase& ossimImageMetaDataWriterFactoryBase::operator=( const ossimImageMetaDataWriterFactoryBase&) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimImageMetaDataWriterRegistry.cpp000066400000000000000000000112241352751253100252450ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: LGPL // // See LICENSE.txt file in the top level directory for more details. //---------------------------------------------------------------------------- // $Id: ossimImageMetaDataWriterRegistry.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include //ossimImageMetaDataWriterRegistry* //ossimImageMetaDataWriterRegistry::theInstance= NULL; ossimImageMetaDataWriterRegistry::ossimImageMetaDataWriterRegistry() { registerFactory(ossimImageMetaDataWriterFactory::instance()); ossimObjectFactoryRegistry::instance()->registerFactory(this); } ossimImageMetaDataWriterRegistry::~ossimImageMetaDataWriterRegistry() { ossimObjectFactoryRegistry::instance()->unregisterFactory(this); } ossimImageMetaDataWriterRegistry* ossimImageMetaDataWriterRegistry::instance() { static ossimImageMetaDataWriterRegistry sharedInstance; return &sharedInstance; } void ossimImageMetaDataWriterRegistry::registerFactory( ossimImageMetaDataWriterFactoryBase* factory) { if(factory&&!findFactory(factory)) { theFactoryList.push_back(factory); } } void ossimImageMetaDataWriterRegistry::unregisterFactory( ossimImageMetaDataWriterFactoryBase* factory) { std::vector::iterator iter = std::find(theFactoryList.begin(), theFactoryList.end(), factory); if(iter != theFactoryList.end()) { theFactoryList.erase(iter); } } bool ossimImageMetaDataWriterRegistry::findFactory( ossimImageMetaDataWriterFactoryBase* factory)const { return (std::find(theFactoryList.begin(), theFactoryList.end(), factory)!=theFactoryList.end()); } ossimObject* ossimImageMetaDataWriterRegistry::createObject( const ossimString& typeName) const { ossimObject* result = NULL; std::vector::const_iterator factory; factory = theFactoryList.begin(); while((factory != theFactoryList.end()) && !result) { result = (*factory)->createObject(typeName); ++factory; } return result; } ossimObject* ossimImageMetaDataWriterRegistry::createObject( const ossimKeywordlist& kwl, const char* prefix) const { ossimObject* result = NULL; std::vector::const_iterator factory; factory = theFactoryList.begin(); while((factory != theFactoryList.end()) && !result) { result = (*factory)->createObject(kwl, prefix); ++factory; } return result; } ossimRefPtr ossimImageMetaDataWriterRegistry::createWriter(const ossimString& type) const { ossimRefPtr result = NULL; std::vector::const_iterator factory; factory = theFactoryList.begin(); while((factory != theFactoryList.end()) && !result) { result = (*factory)->createWriter(type); ++factory; } return result; } void ossimImageMetaDataWriterRegistry::getTypeNameList( std::vector& typeList) const { std::vector result; std::vector::const_iterator iter = theFactoryList.begin(); while(iter != theFactoryList.end()) { result.clear(); (*iter)->getTypeNameList(result); // now append to the end of the typeList. typeList.insert(typeList.end(), result.begin(), result.end()); ++iter; } } void ossimImageMetaDataWriterRegistry::getMetadatatypeList( std::vector& metadatatypeList) const { //--- // Since this is the master registry for all meta data writer factories // we will start with a cleared list. //--- metadatatypeList.clear(); std::vector::const_iterator iter = theFactoryList.begin(); while(iter != theFactoryList.end()) { (*iter)->getMetadatatypeList(metadatatypeList); ++iter; } } ossimImageMetaDataWriterRegistry::ossimImageMetaDataWriterRegistry( const ossimImageMetaDataWriterRegistry& /* rhs */) { } const ossimImageMetaDataWriterRegistry& ossimImageMetaDataWriterRegistry::operator=( const ossimImageMetaDataWriterRegistry& /* rhs */) { return *this; } extern "C" { void* ossimImageMetaDataWriterRegistryGetInstance() { return ossimImageMetaDataWriterRegistry::instance(); } } ossim-Miami-2.9.1/src/imaging/ossimImageModel.cpp000066400000000000000000000100371352751253100217000ustar00rootroot00000000000000//----------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class definition of ossimImageModel. // //----------------------------------------------------------------------------- // $Id$ #include #include #include #include #include RTTI_DEF1(ossimImageModel, "ossimImageModel", ossimObject); ossimImageModel::ossimImageModel() : ossimObject(), theSubImageOffset(), theDecimationFactors(), theLines(0), theSamples(0), theTargetRrds(0) { } ossimImageModel::~ossimImageModel() { } void ossimImageModel::initialize(const ossimImageHandler& ih) { theSubImageOffset = ossimDpt(); theLines = ih.getNumberOfLines(0); theSamples = ih.getNumberOfSamples(0); ih.getDecimationFactors(theDecimationFactors); } void ossimImageModel::rnToR0(ossim_uint32 rrds, const ossimDpt& rnPt, ossimDpt& r0Pt) const { if ( rrds < theDecimationFactors.size() ) { r0Pt.x = rnPt.x / theDecimationFactors[rrds].x; r0Pt.y = rnPt.y / theDecimationFactors[rrds].y; } else { std::string e = "ossimImageModel::rnToR0 rrds out of range!"; throw ossimException(e); } } void ossimImageModel::rnToR0(const ossimDpt& rnPt, ossimDpt& r0Pt) const { rnToR0(theTargetRrds, rnPt, r0Pt); } void ossimImageModel::r0ToRn(ossim_uint32 rrds, const ossimDpt& r0Pt, ossimDpt& rnPt) const { if ( rrds < theDecimationFactors.size() ) { rnPt.x = r0Pt.x * theDecimationFactors[rrds].x; rnPt.y = r0Pt.y * theDecimationFactors[rrds].y; } else { std::string e = "ossimImageModel::r0ToRn rrds out of range!"; throw ossimException(e); } } void ossimImageModel::r0ToRn(const ossimDpt& r0Pt, ossimDpt& rnPt) const { r0ToRn(theTargetRrds, r0Pt, rnPt); } void ossimImageModel::getSubImageOffset(ossim_uint32 rrds, ossimDpt& offset) const { if ( rrds < theDecimationFactors.size() ) { offset.x = theSubImageOffset.x * theDecimationFactors[rrds].x; offset.y = theSubImageOffset.y * theDecimationFactors[rrds].y; } else { std::string e = "ossimImageModel::getSubImageOffset rrds out of range!"; throw ossimException(e); } } void ossimImageModel::getImageRectangle(ossim_uint32 rrds, ossimDrect& rect) const { if ( rrds < theDecimationFactors.size() ) { ossim_float64 lrX = theSamples * theDecimationFactors[rrds].x - 1.0; ossim_float64 lrY = theLines * theDecimationFactors[rrds].y - 1.0; ossimDrect r(0.0, 0.0, lrX, lrY); rect = r; } else { std::string e = "ossimImageModel::getImageRectangle rrds out of range!"; throw ossimException(e); } } void ossimImageModel::getBoundingRectangle(ossim_uint32 rrds, ossimDrect& rect) const { if ( rrds < theDecimationFactors.size() ) { ossim_float64 urX = theSubImageOffset.x * theDecimationFactors[rrds].x; ossim_float64 urY = theSubImageOffset.y * theDecimationFactors[rrds].y; ossim_float64 lrX = urX + theSamples*theDecimationFactors[rrds].x - 1.0; ossim_float64 lrY = urY + theLines *theDecimationFactors[rrds].y - 1.0; ossimDrect r(0, 0, lrX, lrY); rect = r; } else { std::string e = "ossimImageModel::getBoundingRectangle rrds out of range!"; throw ossimException(e); } } ossim_uint32 ossimImageModel::getNumberOfDecimationLevels()const { return (ossim_uint32)theDecimationFactors.size(); } void ossimImageModel::setTargetRrds(ossim_uint32 rrds) { theTargetRrds = rrds; } ossim_uint32 ossimImageModel::getTargetRrds() const { return theTargetRrds; } ossim-Miami-2.9.1/src/imaging/ossimImageMosaic.cpp000066400000000000000000000405151352751253100220570ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: implementation for image mosaic // //************************************************************************* // $Id: ossimImageMosaic.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include static const ossimTrace traceDebug("ossimImageMosaic:debug"); using namespace std; RTTI_DEF1(ossimImageMosaic, "ossimImageMosaic", ossimImageCombiner) ossimImageMosaic::ossimImageMosaic() :ossimImageCombiner(), theTile(NULL) { } ossimImageMosaic::ossimImageMosaic(ossimConnectableObject::ConnectableObjectList& inputSources) : ossimImageCombiner(inputSources), theTile(NULL) { } ossimImageMosaic::~ossimImageMosaic() { } ossimRefPtr ossimImageMosaic::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { long size = getNumberOfInputs(); ossim_uint32 layerIdx = 0; // If there is only one in the mosaic then just return it. if(size == 1) { return getNextTile(layerIdx, 0, tileRect, resLevel); } ossimIpt origin = tileRect.ul(); ossim_uint32 w = tileRect.width(); ossim_uint32 h = tileRect.height(); if(!theTile.valid()) { // try to initialize allocate(); // if we still don't have a buffer // then we will leave if(!theTile.valid()) { return ossimRefPtr(); } } ossim_uint32 tileW = theTile->getWidth(); ossim_uint32 tileH = theTile->getHeight(); if((w != tileW)|| (h != tileH)) { theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tileW*tileH)) { theTile->initialize(); } } theTile->setOrigin(origin); //--- // General Note: // // Note: I will not check for disabled or enabled since we have // no clear way to handle this within a mosaic. The default will be // to do a simple a A over B type mosaic. Derived classes should // check for the enabled and disabled and always // use this default implementation if they are disabled. //--- theTile->setOrigin(origin); theTile->makeBlank(); switch(theTile->getScalarType()) { case OSSIM_UCHAR: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SINT8: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SSHORT16: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SINT32: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_UINT32: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "Scalar type = " << theTile->getScalarType() << " Not supported by ossimImageMosaic" << endl; } } return ossimRefPtr(); } void ossimImageMosaic::initialize() { ossimImageCombiner::initialize(); theTile = NULL; } void ossimImageMosaic::allocate() { theTile = NULL; if( (getNumberOfInputs() > 0) && getInput(0) ) { theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); } } bool ossimImageMosaic::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimImageCombiner::saveState(kwl, prefix); } bool ossimImageMosaic::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimImageCombiner::loadState(kwl, prefix); } template ossimRefPtr ossimImageMosaic::combineNorm( T,// dummy template variable const ossimIrect& tileRect, ossim_uint32 resLevel) { ossim_uint32 layerIdx = 0; //--- // Get the first tile from the input sources. If this(index 0) is blank // that means there are no layers so go no further. //--- ossimRefPtr currentImageData = getNextNormTile(layerIdx, 0, tileRect, resLevel); if(!currentImageData) { return theTile; } ossimRefPtr destination = theTile; ossimDataObjectStatus destinationStatus = theTile->getDataObjectStatus(); float** srcBands = new float*[theLargestNumberOfInputBands]; float* srcBandsNullPix = new float[theLargestNumberOfInputBands]; T** destBands = new T*[theLargestNumberOfInputBands]; T* destBandsNullPix = new T[theLargestNumberOfInputBands]; T* destBandsMinPix = new T[theLargestNumberOfInputBands]; T* destBandsMaxPix = new T[theLargestNumberOfInputBands]; ossim_uint32 band; ossim_uint32 upperBound = destination->getWidth()*destination->getHeight(); ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); destBands[band] = static_cast(theTile->getBuf(band)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); destBandsMinPix[band] = static_cast(theTile->getMinPix(band)); destBandsMaxPix[band] = static_cast(theTile->getMaxPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = static_cast(srcBands[minNumberOfBands - 1]); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); destBands[band] = static_cast(theTile->getBuf(band)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); destBandsMinPix[band] = static_cast(theTile->getMinPix(band)); destBandsMaxPix[band] = static_cast(theTile->getMaxPix(band)); } // Loop to copy from layers to output tile. while(currentImageData.valid()) { //--- // Check the status of the source tile. If empty get the next source // tile and loop back. //--- ossimDataObjectStatus currentStatus = currentImageData->getDataObjectStatus(); if ( (currentStatus == OSSIM_EMPTY) || (currentStatus == OSSIM_NULL) ) { currentImageData = getNextNormTile(layerIdx, tileRect, resLevel); continue; } ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); } if ( (currentStatus == OSSIM_FULL) && (destinationStatus == OSSIM_EMPTY) ) { // Copy full tile to empty tile. for(band=0; band < theLargestNumberOfInputBands; ++band) { float delta = destBandsMaxPix[band] - destBandsMinPix[band]; float minP = destBandsMinPix[band]; for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { destBands[band][offset] = (T)( minP + delta*srcBands[band][offset]); } } } else // Copy tile checking all the pixels... { for(band = 0; band < theLargestNumberOfInputBands; ++band) { float delta = destBandsMaxPix[band] - destBandsMinPix[band]; float minP = destBandsMinPix[band]; for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if (destBands[band][offset] == destBandsNullPix[band]) { if (srcBands[band][offset] != srcBandsNullPix[band]) { destBands[band][offset] = (T)(minP + delta*srcBands[band][offset]); } } } } } // Validate output tile and return if full. destinationStatus = destination->validate(); if (destinationStatus == OSSIM_FULL) { break;//return destination; } // If we get here we're are still not full. Get a tile from next layer. currentImageData = getNextNormTile(layerIdx, tileRect, resLevel); } // Cleanup... delete [] srcBands; delete [] destBands; delete [] srcBandsNullPix; delete [] destBandsNullPix; delete [] destBandsMinPix; delete [] destBandsMaxPix; return destination; } template ossimRefPtr ossimImageMosaic::combine( T,// dummy template variable const ossimIrect& tileRect, ossim_uint32 resLevel) { ossim_uint32 layerIdx = 0; //--- // Get the first tile from the input sources. If this(index 0) is blank // that means there are no layers so go no further. //--- ossimRefPtr currentImageData = getNextTile(layerIdx, 0, tileRect, resLevel); if (!currentImageData) { return theTile; } ossimRefPtr destination = theTile; ossimDataObjectStatus destinationStatus = theTile->getDataObjectStatus(); T** srcBands = new T*[theLargestNumberOfInputBands]; T* srcBandsNullPix = new T[theLargestNumberOfInputBands]; T** destBands = new T*[theLargestNumberOfInputBands]; T* destBandsNullPix = new T[theLargestNumberOfInputBands]; ossim_uint32 band; ossim_uint32 upperBound = destination->getWidth()*destination->getHeight(); ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); destBands[band] = static_cast(theTile->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = static_cast(srcBands[minNumberOfBands - 1]); destBands[band] = static_cast(theTile->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); } // Loop to copy from layers to output tile. while(currentImageData.valid()) { //--- // Check the status of the source tile. If empty get the next source // tile and loop back. //--- ossimDataObjectStatus currentStatus = currentImageData->getDataObjectStatus(); if ( (currentStatus == OSSIM_EMPTY) || (currentStatus == OSSIM_NULL) ) { currentImageData = getNextNormTile(layerIdx, tileRect, resLevel); continue; } ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); } if ( (currentStatus == OSSIM_FULL) && (destinationStatus == OSSIM_EMPTY) ) { // Copy full tile to empty tile. for(ossim_uint32 band=0; band < theLargestNumberOfInputBands; ++band) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { destBands[band][offset] = srcBands[band][offset]; } } } else // Copy tile checking all the pixels... { for(band = 0; band < theLargestNumberOfInputBands; ++band) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if(destBands[band][offset] == destBandsNullPix[band]) { destBands[band][offset] = srcBands[band][offset]; } } } } // Validate output tile and return if full. destinationStatus = destination->validate(); if (destinationStatus == OSSIM_FULL) { break;//return destination; } // If we get here we're are still not full. Get a tile from next layer. currentImageData = getNextTile(layerIdx, tileRect, resLevel); } // Cleanup... delete [] srcBands; delete [] destBands; delete [] srcBandsNullPix; delete [] destBandsNullPix; return destination; } ossim-Miami-2.9.1/src/imaging/ossimImageReconstructionFilterFactory.cpp000066400000000000000000000040031352751253100263530ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimImageReconstructionFilterFactory.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include #include #include RTTI_DEF1(ossimImageReconstructionFilterFactory, "ossimImageReconstructionFilterFactory", ossimImageSourceFactoryBase); ossimImageReconstructionFilterFactory* ossimImageReconstructionFilterFactory::theInstance = 0; ossimImageReconstructionFilterFactory::~ossimImageReconstructionFilterFactory() { theInstance = NULL; } ossimImageReconstructionFilterFactory* ossimImageReconstructionFilterFactory::instance() { if(!theInstance) { theInstance = new ossimImageReconstructionFilterFactory; } return theInstance; } ossimImageReconstructionFilterFactory::ossimImageReconstructionFilterFactory() { theInstance = this; } ossimObject* ossimImageReconstructionFilterFactory::createObject(const ossimString& name)const { if(STATIC_TYPE_NAME(ossimMeanMedianFilter) == name) { return new ossimMeanMedianFilter; } return 0; } ossimObject* ossimImageReconstructionFilterFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { const char* typeKw = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if(typeKw) { ossimObject* obj = createObject(ossimString(typeKw).trim()); if(obj) { obj->loadState(kwl, prefix); return obj; } } return 0; } void ossimImageReconstructionFilterFactory::getTypeNameList(std::vector& typeList)const { typeList.push_back(STATIC_TYPE_NAME(ossimMeanMedianFilter)); } ossim-Miami-2.9.1/src/imaging/ossimImageReconstructionFilterRegistry.cpp000066400000000000000000000067561352751253100265750ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimImageReconstructionFilterRegistry.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include #include #include #include ossimImageReconstructionFilterRegistry* ossimImageReconstructionFilterRegistry::theInstance = 0; RTTI_DEF1(ossimImageReconstructionFilterRegistry, "ossimImageReconstructionFilterRegistry", ossimImageSourceFactoryBase); ossimImageReconstructionFilterRegistry::ossimImageReconstructionFilterRegistry() { theInstance = this; } ossimImageReconstructionFilterRegistry::~ossimImageReconstructionFilterRegistry() { theInstance = NULL; } ossimImageReconstructionFilterRegistry* ossimImageReconstructionFilterRegistry::instance() { if(theInstance == NULL) { theInstance = new ossimImageReconstructionFilterRegistry; theInstance->registerFactory(ossimImageReconstructionFilterFactory::instance()); } return theInstance; } ossimObject* ossimImageReconstructionFilterRegistry::createObject(const ossimString& name)const { ossimObject* result = NULL; std::vector::const_iterator factory; factory = theFactoryList.begin(); while((factory != theFactoryList.end()) && !result) { result = (*factory)->createObject(name); ++factory; } return result; } ossimObject* ossimImageReconstructionFilterRegistry::createObject(const ossimKeywordlist& kwl, const char* prefix)const { ossimObject* result = NULL; std::vector::const_iterator factory; factory = theFactoryList.begin(); while((factory != theFactoryList.end()) && !result) { result = (*factory)->createObject(kwl, prefix); ++factory; } return result; } void ossimImageReconstructionFilterRegistry::getTypeNameList(std::vector& typeList)const { std::vector result; std::vector::const_iterator iter = theFactoryList.begin(); while(iter != theFactoryList.end()) { result.clear(); (*iter)->getTypeNameList(result); // now append to the end of the typeList. typeList.insert(typeList.end(), result.begin(), result.end()); ++iter; } } void ossimImageReconstructionFilterRegistry::registerFactory(ossimImageSourceFactoryBase* factory) { if(factory&&!findFactory(factory)) { theFactoryList.push_back(factory); } } void ossimImageReconstructionFilterRegistry::unregisterFactory(ossimImageSourceFactoryBase* factory) { std::vector::iterator iter = std::find(theFactoryList.begin(), theFactoryList.end(), factory); if(iter != theFactoryList.end()) { theFactoryList.erase(iter); } } bool ossimImageReconstructionFilterRegistry::findFactory(ossimImageSourceFactoryBase* factory)const { return (std::find(theFactoryList.begin(), theFactoryList.end(), factory)!=theFactoryList.end()); } ossim-Miami-2.9.1/src/imaging/ossimImageRenderer.cpp000066400000000000000000002406071352751253100224160ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts // //******************************************************************* // $Id: ossimImageRenderer.cpp 23663 2015-12-11 21:10:54Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // using namespace std; using namespace std; #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimImageRenderer.cpp 23663 2015-12-11 21:10:54Z dburken $"; #endif static ossimTrace traceDebug("ossimImageRenderer:debug"); RTTI_DEF2(ossimImageRenderer, "ossimImageRenderer", ossimImageSourceFilter, ossimViewInterface); double ossimImageRenderer::m_interpErrorThreshold = 1.0; void ossimImageRenderer::ossimRendererSubRectInfo::splitHorizontal(std::vector& result)const { ossimIrect vrect(m_Vul, m_Vur, m_Vlr, m_Vll); ossim_int32 w = vrect.width(); // ossim_int32 h = vrect.height(); ossim_int32 w2 = w>>1; ossimIrect tempLeftRect(m_Vul.x, m_Vul.y, m_Vul.x+w2-1, m_Vlr.y); ossimIrect tempRightRect(tempLeftRect.ur().x+1, m_Vul.y, m_Vur.x, m_Vlr.y); ossimRendererSubRectInfo left(m_transform.get()); ossimRendererSubRectInfo right(m_transform.get()); left.m_viewBounds = m_viewBounds; right.m_viewBounds = m_viewBounds; left.m_Vul = tempLeftRect.ul(); left.m_Vur = tempLeftRect.ur(); left.m_Vlr = tempLeftRect.lr(); left.m_Vll = tempLeftRect.ll(); right.m_Vul = tempRightRect.ul(); right.m_Vur = tempRightRect.ur(); right.m_Vlr = tempRightRect.lr(); right.m_Vll = tempRightRect.ll(); left.transformViewToImage(); right.transformViewToImage(); if(left.imageIsNan()) { if(left.m_viewBounds->intersects(left.getViewRect())) { result.push_back(left); } } else { result.push_back(left); } if(right.imageIsNan()) { if(right.m_viewBounds->intersects(right.getViewRect())) { result.push_back(right); } } else { result.push_back(right); } } void ossimImageRenderer::ossimRendererSubRectInfo::splitVertical(std::vector& result)const { ossimIrect vrect(m_Vul, m_Vur, m_Vlr, m_Vll); // ossim_int32 w = vrect.width(); ossim_int32 h = vrect.height(); ossim_int32 h2 = h>>1; ossimIrect tempTopRect(m_Vul.x, m_Vul.y, m_Vlr.x, m_Vul.y+h2-1); ossimIrect tempBottomRect(m_Vul.x, tempTopRect.lr().y+1, m_Vlr.x, m_Vlr.y); ossimRendererSubRectInfo top(m_transform.get()); ossimRendererSubRectInfo bottom(m_transform.get()); top.m_viewBounds = m_viewBounds; bottom.m_viewBounds = m_viewBounds; top.m_Vul = tempTopRect.ul(); top.m_Vur = tempTopRect.ur(); top.m_Vlr = tempTopRect.lr(); top.m_Vll = tempTopRect.ll(); bottom.m_Vul = tempBottomRect.ul(); bottom.m_Vur = tempBottomRect.ur(); bottom.m_Vlr = tempBottomRect.lr(); bottom.m_Vll = tempBottomRect.ll(); top.transformViewToImage(); bottom.transformViewToImage(); if(top.imageIsNan()) { if(top.m_viewBounds->intersects(top.getViewRect())) { result.push_back(top); } } else { result.push_back(top); } if(bottom.imageIsNan()) { if(bottom.m_viewBounds->intersects(bottom.getViewRect())) { result.push_back(bottom); } } else { result.push_back(bottom); } } void ossimImageRenderer::ossimRendererSubRectInfo::splitAll(std::vector& result)const { //std::cout << "FULL Split\n" << std::endl; // let splitAll for now. We can still optimize but will do that later ossimIrect tempUlRect; ossimIrect tempUrRect; ossimIrect tempLrRect; ossimIrect tempLlRect; ossimIrect vrect(m_Vul, m_Vur, m_Vlr, m_Vll); ossim_int32 w = vrect.width(); ossim_int32 h = vrect.height(); ossim_int32 w2 = w>>1; ossim_int32 h2 = h>>1; tempUlRect = ossimIrect(m_Vul.x, m_Vul.y, m_Vul.x + (w2 - 1), m_Vul.y + (h2 - 1)); tempUrRect = ossimIrect(tempUlRect.ur().x+1, m_Vul.y, m_Vur.x, m_Vul.y + (h2 - 1)); tempLrRect = ossimIrect(tempUlRect.lr().x, tempUlRect.lr().y+1, m_Vlr.x, m_Vlr.y); tempLlRect = ossimIrect(m_Vul.x, tempUlRect.ll().y+1, tempLrRect.ul().x, tempLrRect.ll().y); // std::cout << "VR: " << vrect.width() << ", " << vrect.height() << "\n" // << "UL: " << tempUlRect.width() << ", " << tempUlRect.height() << "\n" // << "UR: " << tempUrRect.width() << ", " << tempUrRect.height() << "\n" // << "LR: " << tempLrRect.width() << ", " << tempLrRect.height() << "\n" // << "LL: " << tempLlRect.width() << ", " << tempLlRect.height() << "\n"; ossimRendererSubRectInfo ul(m_transform.get(),tempUlRect.ul(), tempUlRect.ur(),tempUlRect.lr(), tempUlRect.ll()); ossimRendererSubRectInfo ur(m_transform.get(),tempUrRect.ul(), tempUrRect.ur(),tempUrRect.lr(), tempUrRect.ll()); ossimRendererSubRectInfo lr(m_transform.get(),tempLrRect.ul(), tempLrRect.ur(),tempLrRect.lr(), tempLrRect.ll()); ossimRendererSubRectInfo ll(m_transform.get(),tempLlRect.ul(), tempLlRect.ur(),tempLlRect.lr(), tempLlRect.ll()); ul.m_viewBounds = m_viewBounds; ur.m_viewBounds = m_viewBounds; lr.m_viewBounds = m_viewBounds; ll.m_viewBounds = m_viewBounds; ul.transformViewToImage(); ur.transformViewToImage(); lr.transformViewToImage(); ll.transformViewToImage(); if(ul.imageIsNan()) { if(ul.m_viewBounds->intersects(ul.getViewRect())) { result.push_back(ul); } } else { result.push_back(ul); } if(ur.imageIsNan()) { if(ur.m_viewBounds->intersects(ur.getViewRect())) { result.push_back(ur); } } else { result.push_back(ur); } if(lr.imageIsNan()) { if(lr.m_viewBounds->intersects(lr.getViewRect())) { result.push_back(lr); } } else { result.push_back(lr); } if(ll.imageIsNan()) { if(ll.m_viewBounds->intersects(ll.getViewRect())) { result.push_back(ll); } } else { result.push_back(ll); } } void ossimImageRenderer::ossimRendererSubRectInfo::splitView(std::vector& result)const { ossim_uint16 splitFlags = getSplitFlags(); if(!splitFlags) { return; } // just do horizontal split for test ossimIrect vrect(m_Vul, m_Vur, m_Vlr, m_Vll); ossim_int32 w = vrect.width(); ossim_int32 h = vrect.height(); ossim_int32 w2 = w>>1; ossim_int32 h2 = h>>1; if((w2 <2)&&(h2<2)) { ossimRendererSubRectInfo rect(m_transform.get(),m_Vul, m_Vul, m_Vul, m_Vul); rect.m_viewBounds = m_viewBounds; rect.transformViewToImage(); if(rect.imageHasNans()) { if(rect.m_viewBounds->intersects(rect.getViewRect())) { result.push_back(rect); } } } // horizontal split if only the upper left and lower left // vertices need splitting else if((splitFlags==(UPPER_LEFT_SPLIT_FLAG|LOWER_LEFT_SPLIT_FLAG))|| (splitFlags==(UPPER_RIGHT_SPLIT_FLAG|LOWER_RIGHT_SPLIT_FLAG))) { // std::cout << "Horizontal Split\n" << std::endl; if(w > 1) { splitHorizontal(result); } } // check vertical only split else if((splitFlags==(UPPER_LEFT_SPLIT_FLAG|UPPER_RIGHT_SPLIT_FLAG))|| (splitFlags==(LOWER_RIGHT_SPLIT_FLAG|LOWER_LEFT_SPLIT_FLAG))) { //std::cout << "Vertical Split\n" << std::endl; if(h>1) { splitVertical(result); } } else//if((w>1)&&(h>1)&&(splitFlags)) { if((w<2)&&(h>1)) { splitVertical(result); } else if((w>1)&&(h<2)) { splitHorizontal(result); } else { splitAll(result); } } } void ossimImageRenderer::ossimRendererSubRectInfo::transformImageToView() { ossimDpt vul; ossimDpt vur; ossimDpt vlr; ossimDpt vll; m_transform->imageToView(m_Iul, vul); m_transform->imageToView(m_Iur, vur); m_transform->imageToView(m_Ilr, vlr); m_transform->imageToView(m_Ill, vll); m_Vul = vul; m_Vur = vur; m_Vlr = vlr; m_Vll = vll; } bool ossimImageRenderer::ossimRendererSubRectInfo::tooBig()const { ossimDrect vRect = getViewRect(); return ((vRect.width() > 32) || (vRect.height() > 32)); } ossim_uint16 ossimImageRenderer::ossimRendererSubRectInfo::getSplitFlags()const { #if 1 ossim_uint16 result = SPLIT_NONE; ossimDrect vRect = getViewRect(); //--- // Don't allow splits beyond 8x8 pixel. ossim2dBilinearTransform was core dumping with // very small rectangles in canBilinearInterpolate(...) method. // DRB 05 Dec. 2017 //--- if ( imageIsNan()||(vRect.width() < 8 && vRect.height() < 8) ) { return result; } if(imageHasNans()) { if(m_viewBounds->intersects(vRect)) { result = SPLIT_ALL; } else { return result; } } /* if(result != SPLIT_ALL) { if(m_ulRoundTripError.hasNans()&&m_urRoundTripError.hasNans()&& m_lrRoundTripError.hasNans()&&m_llRoundTripError.hasNans()) { if(m_viewBounds->intersects(getViewRect())) { result = SPLIT_ALL; } return result; } else if(tooBig()) { result = SPLIT_ALL; } } if(result != SPLIT_ALL) { if(m_ulRoundTripError.hasNans()) result |= UPPER_LEFT_SPLIT_FLAG; if(m_urRoundTripError.hasNans()) result |= UPPER_RIGHT_SPLIT_FLAG; if(m_lrRoundTripError.hasNans()) result |= LOWER_RIGHT_SPLIT_FLAG; if(m_llRoundTripError.hasNans()) result |= LOWER_LEFT_SPLIT_FLAG; } */ if(result != SPLIT_ALL) { // ossim_float64 bias = m_ImageToViewScale.length(); //ossim_float64 bias = (m_ImageToViewScale.x+m_ImageToViewScale.y)/2.0; //std::cout << "SCALE BIAS = " << bias << "\n"; // if (bias < 1.0) // bias = 1.0 / bias; // bias = std::sqrt(bias); // if(bias < 1) bias = 1.0; // if((m_ulRoundTripError.length() > bias)|| // (m_urRoundTripError.length() > bias)|| // (m_lrRoundTripError.length() > bias)|| // (m_llRoundTripError.length() > bias)) // { // std::cout << "________________\n"; // std::cout << "Bias: " << bias << "\n" // << "View: " << getViewRect() << "\n" // << "UL: " << m_ulRoundTripError.length() << "\n" // << "UR: " << m_urRoundTripError.length() << "\n" // << "LR: " << m_lrRoundTripError.length() << "\n" // << "LL: " << m_llRoundTripError.length() << "\n"; // } // if(m_ulRoundTripError.length() > sensitivityScale) result |= UPPER_LEFT_SPLIT_FLAG; // if(m_urRoundTripError.length() > sensitivityScale) result |= UPPER_RIGHT_SPLIT_FLAG; // if(m_lrRoundTripError.length() > sensitivityScale) result |= LOWER_RIGHT_SPLIT_FLAG; // if(m_llRoundTripError.length() > sensitivityScale) result |= LOWER_LEFT_SPLIT_FLAG; // std::cout << result << " == " << SPLIT_ALL << "\n"; if(!canBilinearInterpolate()) { // std::cout << "SPLITTING\n"; result = SPLIT_ALL; } else { // std::cout << "CAN BILINEAR!!!!\n"; } } return result; #else ossim_uint16 result = SPLIT_NONE; ossimDrect vRect = getViewRect(); if(imageHasNans()||tooBig()) { if(m_viewBounds->intersects(getViewRect())) { result = SPLIT_ALL; } else { return result; } } /* if(result != SPLIT_ALL) { if(m_ulRoundTripError.hasNans()&&m_urRoundTripError.hasNans()&& m_lrRoundTripError.hasNans()&&m_llRoundTripError.hasNans()) { if(m_viewBounds->intersects(getViewRect())) { result = SPLIT_ALL; } return result; } else if(tooBig()) { result = SPLIT_ALL; } } if(result != SPLIT_ALL) { if(m_ulRoundTripError.hasNans()) result |= UPPER_LEFT_SPLIT_FLAG; if(m_urRoundTripError.hasNans()) result |= UPPER_RIGHT_SPLIT_FLAG; if(m_lrRoundTripError.hasNans()) result |= LOWER_RIGHT_SPLIT_FLAG; if(m_llRoundTripError.hasNans()) result |= LOWER_LEFT_SPLIT_FLAG; } */ if(result != SPLIT_ALL) { ossim_float64 sensitivityScale = m_ImageToViewScale.length(); //std::cout << sensitivityScale << std::endl; if(sensitivityScale < 1.0) sensitivityScale = 1.0/sensitivityScale; // if((m_ulRoundTripError.length() > sensitivityScale)|| // (m_urRoundTripError.length() > sensitivityScale)|| // (m_lrRoundTripError.length() > sensitivityScale)|| // (m_llRoundTripError.length() > sensitivityScale)) // { // std::cout << "________________\n"; // std::cout << "Sens: " << sensitivityScale << "\n" // << "View: " << getViewRect() << "\n" // << "UL: " << m_ulRoundTripError.length() << "\n" // << "UR: " << m_urRoundTripError.length() << "\n" // << "LR: " << m_lrRoundTripError.length() << "\n" // << "LL: " << m_llRoundTripError.length() << "\n"; // } // if(m_ulRoundTripError.length() > sensitivityScale) result |= UPPER_LEFT_SPLIT_FLAG; // if(m_urRoundTripError.length() > sensitivityScale) result |= UPPER_RIGHT_SPLIT_FLAG; // if(m_lrRoundTripError.length() > sensitivityScale) result |= LOWER_RIGHT_SPLIT_FLAG; // if(m_llRoundTripError.length() > sensitivityScale) result |= LOWER_LEFT_SPLIT_FLAG; // std::cout << result << " == " << SPLIT_ALL << "\n"; if((result!=SPLIT_ALL)&&!canBilinearInterpolate(sensitivityScale)) { // std::cout << "TESTING BILINEAR!!!!\n"; result = SPLIT_ALL; } else { // std::cout << "CAN BILINEAR!!!!\n"; } } return result; #endif } void ossimImageRenderer::ossimRendererSubRectInfo::transformViewToImage() { // std::cout << "TRANSFORM VIEW TO IMAGE!!!!!!!!!!!!!!\n"; ossimDrect vrect = getViewRect(); ossim_float64 w = vrect.width() - 1; // subtract 1 to prevent core dump in full-earth view rect ossim_float64 h = vrect.height(); m_transform->viewToImage(m_Vul, m_Iul); m_transform->viewToImage(m_Vur, m_Iur); m_transform->viewToImage(m_Vlr, m_Ilr); m_transform->viewToImage(m_Vll, m_Ill); // m_ulRoundTripError = m_transform->getRoundTripErrorView(m_Vul); // m_urRoundTripError = m_transform->getRoundTripErrorView(m_Vur); // m_lrRoundTripError = m_transform->getRoundTripErrorView(m_Vlr); // m_llRoundTripError = m_transform->getRoundTripErrorView(m_Vll); #if 1 m_transform->getViewToImageScale(m_VulScale, m_Vul); m_transform->getViewToImageScale(m_VurScale, m_Vur); m_transform->getViewToImageScale(m_VlrScale, m_Vlr); m_transform->getViewToImageScale(m_VllScale, m_Vll); // m_VulScale = computeViewToImageScale(m_Vul, ossimDpt( w, h)); // m_VurScale = computeViewToImageScale(m_Vur, ossimDpt(-w, h)); // m_VlrScale = computeViewToImageScale(m_Vlr, ossimDpt(-w,-h)); // m_VllScale = computeViewToImageScale(m_Vll, ossimDpt( w,-h)); ossim_int32 n = 0; m_ViewToImageScale.x = 0.0; m_ViewToImageScale.y = 0.0; if (!m_VulScale.hasNans()) { m_ViewToImageScale += m_VulScale; ++n; } if(!m_VurScale.hasNans()) { m_ViewToImageScale += m_VurScale; ++n; } if(!m_VlrScale.hasNans()) { m_ViewToImageScale += m_VlrScale; ++n; } if(!m_VllScale.hasNans()) { m_ViewToImageScale += m_VllScale; ++n; } if(!n) { m_ViewToImageScale.makeNan(); } else { m_ViewToImageScale.x/=n; m_ViewToImageScale.y/=n; } #else { m_ViewToImageScale = ossimDpt(1.0, 1.0); ossimDpt topDelta = m_Iur - m_Iul; ossimDpt rightDelta = m_Ilr - m_Iur; ossimDpt bottomDelta = m_Ill - m_Ilr; ossimDpt leftDelta = m_Iul - m_Ill; double topLen = topDelta.length(); double bottomLen = bottomDelta.length(); double rightLen = rightDelta.length(); double leftLen = leftDelta.length(); double averageHoriz = ((topLen) + (bottomLen))*.5; double averageVert = ((leftLen) + (rightLen))*.5; ossimDpt deltaViewP1P2 = m_Vul - m_Vur; ossimDpt deltaViewP1P3 = m_Vul - m_Vll; double lengthViewP1P2 = deltaViewP1P2.length();//+1; double lengthViewP1P3 = deltaViewP1P3.length();//+1; if(lengthViewP1P2 > FLT_EPSILON) m_ViewToImageScale.x = averageHoriz/lengthViewP1P2; else m_ViewToImageScale.makeNan(); if(lengthViewP1P3 > FLT_EPSILON) m_ViewToImageScale.y = averageVert/lengthViewP1P3; else m_ViewToImageScale.makeNan(); } #endif //std::cout << m_ViewToImageScale << std::endl; if(!m_ViewToImageScale.hasNans()) { m_ImageToViewScale.x = 1.0/m_ViewToImageScale.x; m_ImageToViewScale.y = 1.0/m_ViewToImageScale.y; } else { m_ImageToViewScale.makeNan(); } } ossimDpt ossimImageRenderer::ossimRendererSubRectInfo::computeViewToImageScale(const ossimDpt& viewPt, const ossimDpt& delta)const { ossimDpt result; result.makeNan(); if(viewPt.hasNans()) return result; ossimDpt ipt; m_transform->viewToImage(viewPt, ipt); if(!ipt.isNan()) { // ossimDpt delta; // transform->viewToImage(viewPt+ossimDpt(0.5,0.5), delta); // delta = delta-ipt; // result.x = delta.length()/std::sqrt(2); // result.y = result.x; ossimDpt dx; ossimDpt dy; m_transform->viewToImage(viewPt + ossimDpt(delta.x,0.0), dx); m_transform->viewToImage(viewPt + ossimDpt(0.0,delta.y), dy); dx = dx-ipt; dy = dy-ipt; result.x = dx.length()/fabs(delta.x); result.y = dy.length()/fabs(delta.y); } return result; } void ossimImageRenderer::ossimRendererSubRectInfo::stretchImageOut(bool enableRound) { ossimDpt topDelta = m_Iur - m_Iul; ossimDpt rightDelta = m_Ilr - m_Iur; ossimDpt bottomDelta = m_Ill - m_Ilr; ossimDpt leftDelta = m_Iul - m_Ill; topDelta = topDelta*(1.0/topDelta.length()); rightDelta = rightDelta*(1.0/rightDelta.length()); bottomDelta = bottomDelta*(1.0/bottomDelta.length()); leftDelta = leftDelta*(1.0/leftDelta.length()); m_Iul = m_Iul + ((leftDelta - topDelta)*.5); m_Iur = m_Iur + ((topDelta - rightDelta)*.5); m_Ilr = m_Ilr + ((rightDelta - bottomDelta)*.5); m_Ill = m_Ill + ((bottomDelta - leftDelta)*.5); if(enableRound) { m_Iul = ossimIpt(ossim::round(m_Iul.x), ossim::round(m_Iul.y)); m_Iur = ossimIpt(ossim::round(m_Iur.x), ossim::round(m_Iur.y)); m_Ilr = ossimIpt(ossim::round(m_Ilr.x), ossim::round(m_Ilr.y)); m_Ill = ossimIpt(ossim::round(m_Ill.x), ossim::round(m_Ill.y)); } } bool ossimImageRenderer::ossimRendererSubRectInfo::isIdentity()const { // ossimDpt deltaP1P2 = m_Iul - m_Iur; // ossimDpt deltaP1P3 = m_Iul - m_Ill; // ossimDpt deltaViewP1P2 = m_Vul - m_Vur; // ossimDpt deltaViewP1P3 = m_Vul - m_Vll; // bool horizontalSigns = ossimGetSign(deltaP1P2.x)==ossimGetSign(deltaViewP1P2.x); // bool verticalSigns = ossimGetSign(deltaP1P3.y)==ossimGetSign(deltaViewP1P3.y); // // check first to see if any horizontal or vertical flipping // // // if(horizontalSigns && verticalSigns) // { // // check scales to see if they are 1 // if(fabs(1-m_ViewToImageScale.x) <= FLT_EPSILON && // fabs(1-m_ViewToImageScale.y) <= FLT_EPSILON) // { // return true; // } // } double iulDelta = (m_Iul-m_Vul).length(); double iurDelta = (m_Iur-m_Vur).length(); double ilrDelta = (m_Ilr-m_Vlr).length(); double illDelta = (m_Ill-m_Vll).length(); return ((iulDelta <= FLT_EPSILON)&& (iurDelta <= FLT_EPSILON)&& (ilrDelta <= FLT_EPSILON)&& (illDelta <= FLT_EPSILON)); } bool ossimImageRenderer::ossimRendererSubRectInfo::canBilinearInterpolate() const //bool ossimImageRenderer::ossimRendererSubRectInfo::canBilinearInterpolate(double error) const { bool result = false; // now check point placement ossimDpt imageToViewScale = getAbsValueImageToViewScales(); if(imageToViewScale.hasNans()) return true; ossim_float64 bias = imageToViewScale.length(); // root average of 1x1 = sqrt(2) const double ROOT_AVERAGE = 1.41421356237309504880; double testScale = imageToViewScale.length()/ROOT_AVERAGE; // if there is a large shrink or expansion then just return true. // You are probably not worried about error in bilinear interpolation // if ((testScale > 256) || (testScale < 1.0 / 256.0)) { return true; } if (m_VulScale.hasNans() || m_VurScale.hasNans() || m_VlrScale.hasNans() || m_VllScale.hasNans()) { return result; } // std::cout << "ulScale: " << m_VulScale << "\n" // << "urScale: " << m_VurScale << "\n" // << "lrScale: " << m_VlrScale << "\n" // << "llScale: " << m_VllScale << "\n"; // check overage power of 2 variance // If there is a variance of 1 resolution level // then we must split further // ossim_float64 averageUlScale = m_VulScale.length(); ossim_float64 averageUrScale = m_VurScale.length(); ossim_float64 averageLrScale = m_VlrScale.length(); ossim_float64 averageLlScale = m_VllScale.length(); // std::cout << "_________________________\n"; // std::cout << log(averageUlScale)/(log(2)) << "\n"; // std::cout << log(averageUrScale)/(log(2)) << "\n"; // std::cout << log(averageLrScale)/(log(2)) << "\n"; // std::cout << log(averageLlScale)/(log(2)) << "\n"; ossim_float64 ratio1 = averageUlScale / averageUrScale; ossim_float64 ratio2 = averageUlScale / averageLrScale; ossim_float64 ratio3 = averageUlScale / averageLlScale; // std::cout << "_________________________\n"; // std::cout << "ratio1: " << ratio1 << "\n"; // std::cout << "ratio2: " << ratio2 << "\n"; // std::cout << "ratio3: " << ratio3 << "\n"; // make sure all are within a power of 2 shrink or expand // which means the range of each ratio should be // between .5 and 2 result = (((ratio1 < 2) && (ratio1 > 0.5)) && ((ratio2 < 2) && (ratio2 > 0.5)) && ((ratio3 < 2) && (ratio3 > 0.5))); //result = ((diff1<=2)&&(diff2<=2)&&(diff3<=2)); //std::cout << "DIFF1: " << diff1 << std::endl; //std::cout << "DIFF2: " << diff2 << std::endl; //std::cout << "DIFF3: " << diff3 << std::endl; if (result) { #if 1 ossimDpt vUpper, vRight, vBottom, vLeft, vCenter; ossimDpt iUpper, iRight, iBottom, iLeft, iCenter; ossimDpt testUpper, testRight, testBottom, testLeft, testCenter; getViewMids(vUpper, vRight, vBottom, vLeft, vCenter); getImageMids(iUpper, iRight, iBottom, iLeft, iCenter); // get the model centers for the mid upper left right bottom m_transform->viewToImage(vCenter, testCenter); if (testCenter.hasNans()) { return false; } m_transform->viewToImage(vUpper, testUpper); if (testUpper.hasNans()) { return false; } m_transform->viewToImage(vRight, testRight); if (testRight.hasNans()) { return false; } m_transform->viewToImage(vBottom, testBottom); if (testBottom.hasNans()) { return false; } m_transform->viewToImage(vLeft, testLeft); if (testLeft.hasNans()) { return false; } // now get the model error to bilinear estimate of those points double errorCheck1 = (testCenter - iCenter).length(); double errorCheck2 = (testUpper - iUpper).length(); double errorCheck3 = (testRight - iRight).length(); double errorCheck4 = (testBottom - iBottom).length(); double errorCheck5 = (testLeft - iLeft).length(); // This is crude but we will do a simple scale to find the R0 delta. // If the R0 delta is within a pixel then we will return true // for canBilinear if (testScale <= FLT_EPSILON) { errorCheck1 = 0.0; errorCheck2 = 0.0; errorCheck3 = 0.0; errorCheck4 = 0.0; errorCheck5 = 0.0; } else if(testScale > 1.0) { // errorCheck1 *= testScale; // errorCheck2 *= testScale; // errorCheck3 *= testScale; // errorCheck4 *= testScale; // errorCheck5 *= testScale; } else if(testScale > FLT_EPSILON) { // errorCheck1 /= testScale; // errorCheck2 /= testScale; // errorCheck3 /= testScale; // errorCheck4 /= testScale; // errorCheck5 /= testScale; } // errorCheck1 = sqrt(errorCheck1); // errorCheck2 = sqrt(errorCheck2); // errorCheck3 = sqrt(errorCheck3); // errorCheck4 = sqrt(errorCheck4); // errorCheck5 = sqrt(errorCheck5); // std::cout << "SCALE BIAS: " << testScale << "\n"; // std::cout << "errorCheck1:" << errorCheck1 << "\n"; result = ((errorCheck1 < ossimImageRenderer::m_interpErrorThreshold) && (errorCheck2 < ossimImageRenderer::m_interpErrorThreshold) && (errorCheck3 < ossimImageRenderer::m_interpErrorThreshold) && (errorCheck4 < ossimImageRenderer::m_interpErrorThreshold) && (errorCheck5 < ossimImageRenderer::m_interpErrorThreshold)); // std::cout <<"__________________________\n" // << "ERROR1:" <viewToImage(vCenter, testCenter); if (testCenter.hasNans()) { return false; } ossimDpt testFullRes(testCenter.x * imageToViewScale.x, testCenter.y * imageToViewScale.y); double errorCheck1 = (testFullRes - iFullRes).length(); iFullRes = ossimDpt(iUpper.x * imageToViewScale.x, iUpper.y * imageToViewScale.y); m_transform->viewToImage(vUpper, testCenter); if (testCenter.hasNans()) { return false; } testFullRes = ossimDpt(testCenter.x * imageToViewScale.x, testCenter.y * imageToViewScale.y); double errorCheck2 = (testFullRes - iFullRes).length(); iFullRes = ossimDpt(iRight.x * imageToViewScale.x, iRight.y * imageToViewScale.y); m_transform->viewToImage(vRight, testCenter); if (testCenter.hasNans()) { return false; } testFullRes = ossimDpt(testCenter.x * imageToViewScale.x, testCenter.y * imageToViewScale.y); double errorCheck3 = (testFullRes - iFullRes).length(); iFullRes = ossimDpt(iBottom.x * imageToViewScale.x, iBottom.y * imageToViewScale.y); m_transform->viewToImage(vBottom, testCenter); if (testCenter.hasNans()) { return false; } testFullRes = ossimDpt(testCenter.x * imageToViewScale.x, testCenter.y * imageToViewScale.y); double errorCheck4 = (testFullRes - iFullRes).length(); iFullRes = ossimDpt(iLeft.x * imageToViewScale.x, iLeft.y * imageToViewScale.y); m_transform->viewToImage(vLeft, testCenter); testFullRes = ossimDpt(testCenter.x * imageToViewScale.x, testCenter.y * imageToViewScale.y); double errorCheck5 = (testFullRes - iFullRes).length(); std::cout << "__________________________\n" << "ERROR1:" << errorCheck1 << "\n" << "ERROR2:" << errorCheck2 << "\n" << "ERROR3:" << errorCheck3 << "\n" << "ERROR4:" << errorCheck4 << "\n" << "ERROR5:" << errorCheck5 << "\n" << "SENS: " << error << "\n"; result = ((errorCheck1 < error) && (errorCheck2 < error) && (errorCheck3 < error) && (errorCheck4 < error) && (errorCheck5 < error)); // std::cout << "CAN INTERPOLATE? " << result <<"\n"; #endif } return result; } void ossimImageRenderer::ossimRendererSubRectInfo::getViewMids(ossimDpt& upperMid, ossimDpt& rightMid, ossimDpt& bottomMid, ossimDpt& leftMid, ossimDpt& center)const { upperMid = (m_Vul + m_Vur)*.5; rightMid = (m_Vur + m_Vlr)*.5; bottomMid = (m_Vlr + m_Vll)*.5; leftMid = (m_Vul + m_Vll)*.5; center = (m_Vul + m_Vur + m_Vlr + m_Vll)*.25; } void ossimImageRenderer::ossimRendererSubRectInfo::getImageMids(ossimDpt& upperMid, ossimDpt& rightMid, ossimDpt& bottomMid, ossimDpt& leftMid, ossimDpt& center)const { if(imageHasNans()) { upperMid.makeNan(); rightMid.makeNan(); bottomMid.makeNan(); leftMid.makeNan(); center.makeNan(); } else { upperMid = (m_Iul + m_Iur)*.5; rightMid = (m_Iur + m_Ilr)*.5; bottomMid = (m_Ilr + m_Ill)*.5; leftMid = (m_Iul + m_Ill)*.5; center = (m_Iul + m_Iur + m_Ilr + m_Ill)*.25; } } ossimDpt ossimImageRenderer::ossimRendererSubRectInfo::getParametricCenter(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll)const { ossimDpt top = ur - ul; ossimDpt bottom = lr - ll; ossimDpt centerTop = ul + top * .5; ossimDpt centerBottom = ll + bottom * .5; return centerBottom + (centerBottom - centerTop)*.5; } ossimImageRenderer::ossimImageRenderer() : ossimImageSourceFilter(), ossimViewInterface(0), m_Resampler(0), m_BlankTile(0), m_Tile(0), m_TemporaryBuffer(0), m_StartingResLevel(0), m_ImageViewTransform(0), m_inputR0Rect(), m_viewRect(), m_rectsDirty(true), m_MaxRecursionLevel(5), m_AutoUpdateInputTransform(true), m_MaxLevelsToCompute(999999), // something large so it will always compute m_averageViewToImageScale(1.0), m_averageViewToImageRLevelScale(0.0) { ossimViewInterface::theObject = this; m_Resampler = new ossimFilterResampler(); m_ImageViewTransform = new ossimImageViewProjectionTransform; loadState(ossimPreferences::instance()->preferencesKWL(), "renderer."); } ossimImageRenderer::ossimImageRenderer(ossimImageSource *inputSource, ossimImageViewTransform *imageViewTrans) : ossimImageSourceFilter(inputSource), ossimViewInterface(0), m_Resampler(0), m_BlankTile(0), m_Tile(0), m_TemporaryBuffer(0), m_StartingResLevel(0), m_inputR0Rect(), m_viewRect(), m_rectsDirty(true), m_MaxRecursionLevel(5), m_AutoUpdateInputTransform(true), m_MaxLevelsToCompute(999999), // something large so it will always compute m_averageViewToImageScale(1.0), m_averageViewToImageRLevelScale(0.0) { ossimViewInterface::theObject = this; m_Resampler = new ossimFilterResampler(); loadState(ossimPreferences::instance()->preferencesKWL(), "renderer."); if (imageViewTrans) m_ImageViewTransform = imageViewTrans; } ossimImageRenderer::~ossimImageRenderer() { m_ImageViewTransform = 0; if(m_Resampler) { delete m_Resampler; m_Resampler = 0; } } ossimRefPtr ossimImageRenderer::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { // std::cout << "_________________________\n"; static const char MODULE[] = "ossimImageRenderer::getTile"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Requesting view rect = " << tileRect << endl; } // long w = tileRect.width(); // long h = tileRect.height(); // ossimIpt origin = tileRect.ul(); if( !m_BlankTile.valid() || !m_Tile.valid() ) { allocate(); if ( !m_BlankTile.valid() || !m_Tile.valid() ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimImageRenderer::getTile tile allocation failure!\n" << endl; } return ossimImageSourceFilter::getTile(tileRect, resLevel); } } m_BlankTile->setImageRectangle(tileRect); if(!theInputConnection) { return m_BlankTile; } if ( !isSourceEnabled()||(!m_ImageViewTransform.valid())|| (!m_ImageViewTransform->isValid()) ) { // This tile source bypassed, return the input tile source. return theInputConnection->getTile(tileRect, resLevel); } if( m_rectsDirty ) { initializeBoundingRects(); // We can't go on without these... if ( m_rectsDirty ) { return m_BlankTile; } } if(m_viewRect.width() < 4 && m_viewRect.height() < 4) { return m_BlankTile; } if( !theInputConnection || !m_viewRect.intersects(tileRect) || !m_viewArea.intersects(tileRect) ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "No intersection, Returning...." << endl; } return m_BlankTile; } // drb - handled above... // if(!m_Tile) // { // return theInputConnection->getTile(tileRect, resLevel); // } // Check for identity transform: if( m_ImageViewTransform->isIdentity() == true ) { return theInputConnection->getTile(tileRect, resLevel); } // long tw = m_Tile->getWidth(); // long th = m_Tile->getHeight(); m_Tile->setImageRectangle(tileRect); m_Tile->makeBlank(); //if(!(m_viewArea.intersects(ossimPolyArea2d(tileRect)))) //{ // return m_BlankTile; //} #if 1 ossimIrect tempRect = tileRect; ossim_uint32 levels = theInputConnection->getNumberOfDecimationLevels(); ossim_float64 length = ossim::max(m_inputR0Rect.width(), m_inputR0Rect.height()); // if we are zoomed out or we are completely within the requesting tile rect bool canClip = (m_viewRect.completely_within(tileRect)); if(!canClip) { if(m_averageViewToImageScale > 1.0) { if ((length / m_averageViewToImageScale) <= 256) { // we are very small so we can clip canClip = true; } } } // gpotts: Until I can fix the entire resampling process we will add a sanity // if we are zoomed out or the rect completely fits within the tile // then we will clip to the view rect if (canClip) { ossimPolyArea2d tileRectArea(tileRect); if (!(m_viewArea.intersects(tileRectArea))) { return m_BlankTile; } else { ossimDrect rect; tileRectArea &= m_viewArea; tileRectArea.getBoundingRect(rect); tempRect = rect; } } // tempRect = tileRect.clipToRect(m_viewRect); // expand a small patch just to alleviate errors in the size of the rect when resampling // ossimIrect viewRectClip = tileRect.clipToRect(ossimIrect(m_viewRect.ul() + ossimIpt(-8,-8), // m_viewRect.lr() + ossimIpt(8,8))); //ossimIrect viewRectClip = tileRect.clipToRect(m_viewRect); // std::cout << "_____________________" << std::endl; // std::cout << "viewRectClip = " << viewRectClip << std::endl; // std::cout << "tileRect = " << tileRect << std::endl; // std::cout << "m_viewRect = " << m_viewRect << std::endl; ossimRendererSubRectInfo subRectInfo(m_ImageViewTransform.get(), tempRect.ul(), tempRect.ur(), tempRect.lr(), tempRect.ll()); #else ossimRendererSubRectInfo subRectInfo(m_ImageViewTransform.get(), tileRect.ul(), tileRect.ur(), tileRect.lr(), tileRect.ll()); #endif subRectInfo.m_viewBounds = &m_viewArea; subRectInfo.transformViewToImage(); if((!m_viewArea.intersects(subRectInfo.getViewRect()))) // if((!m_viewRect.intersects(subRectInfo.getViewRect()))) { return m_BlankTile; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " image rect = " << subRectInfo.getImageRect() << std::endl; } // If the image rect is completely outside of the valid image, there is no need to resample: // (OLK 11/18) // if ((!subRectInfo.imageHasNans())&&!m_inputR0Rect.intersects(subRectInfo.getImageRect())) // { // return m_Tile; // } recursiveResample(m_Tile, subRectInfo, 1); if(m_Tile.valid()) { m_Tile->validate(); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "Returning...." << endl; } return m_Tile; } void ossimImageRenderer::recursiveResample(ossimRefPtr outputData, const ossimRendererSubRectInfo& rectInfo, ossim_uint32 /* level */) { // Removed recursion and just use the std::stack. // std::stack rectStack; rectStack.push(rectInfo); while(!rectStack.empty()) { ossimRendererSubRectInfo currentRectInfo = rectStack.top(); ossimIrect tempViewRect = currentRectInfo.getViewRect(); rectStack.pop(); if(m_viewArea.intersects(tempViewRect)) { if(tempViewRect.width() <2 || tempViewRect.height() <2) { if(!currentRectInfo.imageHasNans()) { fillTile(outputData, currentRectInfo); } } else { ossim_uint32 idx = 0; std::vector splitRects; currentRectInfo.splitView(splitRects); if(!splitRects.empty()) { for(idx = 0; idx < splitRects.size();++idx) { if(m_viewArea.intersects(splitRects[idx].getViewRect())) { rectStack.push(splitRects[idx]); } // recursiveResample(outputData, // splitRects[idx], // level + 1); } } else { if(!currentRectInfo.imageHasNans()) { fillTile(outputData, currentRectInfo); } } } } } #if 0 ossimIrect tempViewRect = rectInfo.getViewRect(); if(rectInfo.imageIsNan()) { return; } if(tempViewRect.width() <2 || tempViewRect.height() <2) { if(!rectInfo.imageHasNans()) { fillTile(outputData, rectInfo); } return; } // std::vector splitRects; rectInfo.splitView(splitRects); //std::cout << "SHOULD BE SPLITTING: " << splitRects.size() <<"\n"; ossim_uint32 idx = 0; if(!splitRects.empty()) { // std::cout << "SPLITTING " << level << ", " << tempViewRect << "\n"; for(idx = 0; idx < splitRects.size();++idx) { recursiveResample(outputData, splitRects[idx], level + 1); } } else if(!rectInfo.imageHasNans()) { fillTile(outputData, rectInfo); } #endif } #define RSET_SEARCH_THRESHHOLD 0.1 void ossimImageRenderer::fillTile(ossimRefPtr outputData, const ossimRendererSubRectInfo& rectInfo) { if(!outputData.valid() || !outputData->getBuf() || rectInfo.imageHasNans()) { return; } ossimDrect vrect = rectInfo.getViewRect(); ossimDpt imageToViewScale = rectInfo.getAbsValueImageToViewScales(); if(imageToViewScale.hasNans()) return; ossimDpt tile_size = ossimDpt(vrect.width(), vrect.height()); double kernelSupportX, kernelSupportY; double resLevelX = log( 1.0 / imageToViewScale.x )/ log( 2.0 ); double resLevelY = log( 1.0 / imageToViewScale.y )/ log( 2.0 ); double resLevel0 = resLevelX < resLevelY ? resLevelX : resLevelY; long closestFitResLevel = (long)floor( resLevel0 ); //double averageScale = (imageToViewScale.x + imageToViewScale.y) / 2.0; //long closestFitResLevel = (long)floor( log( 1.0 / averageScale )/ log( 2.0 ) ); ossim_uint32 resLevel = closestFitResLevel<0 ? 0:closestFitResLevel; resLevel += m_StartingResLevel; //--- // ESH 02/2009: If requested resLevel is too high, let's lower it to one // that is ok. //--- #if 0 const ossim_uint32 NUM_LEVELS = theInputConnection->getNumberOfDecimationLevels(); if ( (NUM_LEVELS > 0) && (resLevel >= NUM_LEVELS) ) { resLevel = NUM_LEVELS - 1; } #endif //--- // ESH 11/2008: Check the rset at the calculated resLevel to see // if it has the expected decimation factor. It it does, we can // use this rset and assume it is at resLevel. //--- ossimDpt decimation; decimation.makeNan(); // initialize to nan. theInputConnection->getDecimationFactor(resLevel, decimation); double requestScale = 1.0 / (1< RSET_SEARCH_THRESHHOLD) || ((fabs(differenceTest) < RSET_SEARCH_THRESHHOLD) && (differenceTest < 0.0) ) ) { //--- // ESH 11/2008: We test for the best rset. We assume // that decimation level always decreases as resLevel increases, so // the search can end before testing all rsets. //--- ossim_uint32 savedResLevel = resLevel; closestScale = 1.0; // resLevel 0 resLevel = 0; ossim_uint32 i; for( i=1; igetDecimationFactor(i, decimation); if(decimation.hasNans() == false ) { double testDiscrepancy = decimation.x - requestScale; if ( testDiscrepancy < 0.0 ) // we're done { break; } else { closestScale = decimation.x; resLevel = i; } } else // use the default value { closestScale = requestScale; resLevel = savedResLevel; break; } } } #endif ossimDpt nul(rectInfo.m_Iul.x*closestScale, rectInfo.m_Iul.y*closestScale); ossimDpt nll(rectInfo.m_Ill.x*closestScale, rectInfo.m_Ill.y*closestScale); ossimDpt nlr(rectInfo.m_Ilr.x*closestScale, rectInfo.m_Ilr.y*closestScale); ossimDpt nur(rectInfo.m_Iur.x*closestScale, rectInfo.m_Iur.y*closestScale); m_Resampler->getKernelSupport( kernelSupportX, kernelSupportY ); ossimDrect boundingRect = ossimDrect( nul, nll, nlr, nur ); boundingRect = ossimIrect((ossim_int32)floor(boundingRect.ul().x - (kernelSupportX)-.5), (ossim_int32)floor(boundingRect.ul().y - (kernelSupportY)-.5), (ossim_int32)ceil (boundingRect.lr().x + (kernelSupportX)+.5), (ossim_int32)ceil (boundingRect.lr().y + (kernelSupportY)+.5)); ossimDrect requestRect = boundingRect; ossimRefPtr data = getTileAtResLevel(requestRect, resLevel); ossimDataObjectStatus status = OSSIM_NULL; if( data.valid() ) { status = data->getDataObjectStatus(); } if( (status == OSSIM_NULL) || (status == OSSIM_EMPTY) ) { return; } if((boundingRect.width() <2)&&(boundingRect.height()<2)) { // return; }// std::cout << "SMALL RECT!!!!!!\n"; else { ossimDrect inputRect = m_inputR0Rect; inputRect = inputRect*ossimDpt(closestScale, closestScale); m_Resampler->setBoundingInputRect(inputRect); double denominatorY = 1.0; if(tile_size.y > 2) { denominatorY = tile_size.y-1.0; } ossimDpt newScale( imageToViewScale.x / closestScale, imageToViewScale.y / closestScale ); m_Resampler->setScaleFactor(newScale); //std::cout << "SPLIT VIEW RECT: " << vrect << std::endl; //std::cout << "VIEW RECT: " << outputData->getImageRectangle() << std::endl; m_Resampler->resample(data, outputData, vrect, nul, nur, ossimDpt( ( (nll.x - nul.x)/denominatorY ), ( (nll.y - nul.y)/denominatorY ) ), ossimDpt( ( (nlr.x - nur.x)/denominatorY ), ( (nlr.y - nur.y)/denominatorY ) ), tile_size); } } long ossimImageRenderer::computeClosestResLevel(const std::vector& decimationFactors, double scale)const { long result = 0; long upper = (long)decimationFactors.size(); bool done = false; if(upper > 1) { while((result < upper)&&!done) { if(scale < decimationFactors[result].x) { ++result; } else { done = true; } } // now use the higher res level and resample down // if(result) { --result; } } return result; } ossimIrect ossimImageRenderer::getBoundingRect(ossim_uint32 resLevel)const { //--- // 01 November 2011: // Backed out expand code as the ossimImageViewProjectionTransform::getImageToViewBounds // does not handle image on the edge of international date line. D. Burken //--- // The input bounding rect as returned here corresponds to "pixel-is-point", i.e., the center // of the pixel area for the corners and not the edges which extend 1/2 pixel in all // directions. Because the view is probably a different GSD, first expand the input // bounding rect to the edge before transforming to a view rect. Then shrink the view rect by // 1/2 pixel to get it to the pixel center (OSSIM convention for bounding rect -- this may // need to be revisited in light of the need to match edges, not pixel centers, OLK 09/11). // Code functionality moved to below method. (drb - 08 Nov. 2011) ossimIrect result; getBoundingRect( result, resLevel ); return result; } void ossimImageRenderer::getBoundingRect(ossimIrect& rect, ossim_uint32 resLevel) const { if ( isSourceEnabled() ) { rect = m_viewRect; } else if ( theInputConnection ) { rect = theInputConnection->getBoundingRect(resLevel); } else { rect.makeNan(); } #if 0 /* Please leave for debug. */ if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageRenderer::getBoundingRect(rect, resLevel) debug:\nbounds = " << rect << "\n"; } #endif } void ossimImageRenderer::initializeBoundingRects() { m_averageViewToImageScale = 1.0; m_rectsDirty = true; ossimImageViewProjectionTransform *ivpt = dynamic_cast(m_ImageViewTransform.get()); if (!theInputConnection || !m_ImageViewTransform.valid()) return; m_inputR0Rect = theInputConnection->getBoundingRect(0); if (!m_inputR0Rect.hasNans()) { if (ivpt && ivpt->getImageGeometry() && ivpt->getViewGeometry()) { // Little complicated but instead of always setting the edge walk // to a high number like 50 points per edge // we will look at the image to view scale change // and use that as a factor. So as the image zooms out we // need fewer points to estimate the edge. // // ossim_uint32 idx; std::vector boundList; ossimImageGeometry *igeom = ivpt->getImageGeometry(); // look at projected meters ossimImageGeometry *vgeom = ivpt->getViewGeometry(); // look at projected meters ossimDrect testRect; igeom->getBoundingRect(testRect); ossimDpt mpp = igeom->getMetersPerPixel(); ossimDpt vmpp = vgeom->getMetersPerPixel(); ossim_float64 scale = 1.0; ossim_uint32 maxLen = ossim::max(testRect.width(), testRect.height()); // (GP March 2, 2017) determine goodMatch : test if we have either enough samples to closely match the post spacing // or if we have at least half the number of pixels along the edge of an image // // This is hopefully to help avoid when using the polygon for intersection to not have // bad intersection tests when zooming. We might have to rethink it and implement // this as a windowed edge walker. So when zooming we create a polygon that // is denser for only what the view can see and not the entire image. Basically interatively // tesselate the input image model based on bounding volumes and then create a dense edge walker // for what lies in the view at the given scale. Too much to implement right now so we will cheet // and take an easy way out for now. // if (!mpp.hasNans() && !vmpp.hasNans()) { scale = mpp.y / vmpp.y; if (scale > 1.0) scale = 1.0; } ossim_float64 mppTest = mpp.y; ossim_float64 divisor = mppTest; // default to 30 meter elevation if (mppTest < 500) { if (mppTest >= 45) { divisor = 90; // 90 meters } } else { divisor = 1000; // 1 kilometer } if (divisor < 30) divisor = 30.0; // now test to see if our edge walk is close to matching enough // points for a good match. // ossim_uint32 maxEdgeSample = ossim::min(static_cast(50), maxLen); if (maxEdgeSample < 1) maxEdgeSample = 1; ossim_uint32 testEdgeSample = ossim::round((maxLen * scale * mpp.y) / divisor); bool goodMatch = (testEdgeSample <= maxEdgeSample) || (testEdgeSample >= (maxLen >> 1)); ossim_float64 steps = ossim::min(testEdgeSample, maxEdgeSample); ossim_uint32 finalSteps = ossim::round(steps); if (finalSteps < 1) finalSteps = 1; if (igeom->getCrossesDateline()) { if (finalSteps < maxEdgeSample) finalSteps = maxEdgeSample; } ivpt->getViewSegments(boundList, m_viewArea, finalSteps); if (boundList.size()) { m_viewRect = boundList[0]; ossim_uint32 idx = 0; if (goodMatch) { m_viewArea = boundList[idx]; } else { m_viewArea = m_viewRect; } for (idx = 1; idx < boundList.size(); ++idx) { ossimIrect rectBounds = ossimIrect(boundList[idx]); m_viewRect = m_viewRect.combine(rectBounds); if (goodMatch) { m_viewArea.add(ossimPolygon(boundList[idx])); } else { m_viewArea.add(rectBounds); } } // if (!m_viewRect.hasNans()) { m_rectsDirty = false; } } //END if boundList.size() } else if (m_ImageViewTransform.valid()) { m_viewRect = m_ImageViewTransform->getImageToViewBounds(m_inputR0Rect); if (!m_viewRect.hasNans()) { m_rectsDirty = false; } m_viewArea = m_viewRect; } } if(!m_viewRect.hasNans()&&m_ImageViewTransform) { ossimDpt result; m_ImageViewTransform->getViewToImageScale(result, m_viewRect.midPoint()); m_averageViewToImageScale = (result.x+result.y)/2.0; m_averageViewToImageRLevelScale = log(m_averageViewToImageScale) / log(2); } if ( m_rectsDirty ) { m_viewRect.makeNan(); } #if 0 /* Please leave for debug. */ ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageRenderer::initializeBoundingRects() debug:\n" << "\ninput rect: " << m_inputR0Rect << "\nview rect: " << m_viewRect << endl; #endif } void ossimImageRenderer::initialize() { // Call the base class initialize. // Note: This will reset "theInputConnection" if it changed... ossimImageSourceFilter::initialize(); deallocate(); m_rectsDirty = true; // we will only do this if we are enabled for this could be expensive if (m_ImageViewTransform.valid() && !m_ImageViewTransform->isValid() && isSourceEnabled()) { checkIVT(); // This can initialize bounding rects and clear dirty flag. } if ( m_rectsDirty ) { initializeBoundingRects(); } } void ossimImageRenderer::deallocate() { m_Tile = 0; m_BlankTile = 0; m_TemporaryBuffer = 0; } void ossimImageRenderer::allocate() { deallocate(); if(theInputConnection) { m_Tile = ossimImageDataFactory::instance()->create(this, this); m_BlankTile = ossimImageDataFactory::instance()->create(this, this); m_Tile->initialize(); } } bool ossimImageRenderer::saveState(ossimKeywordlist& kwl, const char* prefix)const { if(m_ImageViewTransform.valid()) { ossimString newPrefix = ossimString(prefix) + ossimString("image_view_trans."); m_ImageViewTransform->saveState(kwl, newPrefix.c_str()); } if(m_Resampler) { m_Resampler->saveState(kwl, (ossimString(prefix)+"resampler.").c_str()); } kwl.add(prefix, "max_levels_to_compute", m_MaxLevelsToCompute); kwl.add(prefix, "interpolation_error_threshold", m_interpErrorThreshold); return ossimImageSource::saveState(kwl, prefix); } bool ossimImageRenderer::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageRenderer::loadState entered..." << endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << endl; #endif } ossimString newPrefix = ossimString(prefix) + ossimString("image_view_trans."); bool result = ossimImageSourceFilter::loadState(kwl, prefix); if(m_Resampler) { m_Resampler->loadState(kwl, (ossimString(prefix)+"resampler.").c_str()); } m_ImageViewTransform = 0; m_ImageViewTransform = ossimImageViewTransformFactory::instance()->createTransform(kwl, newPrefix.c_str()); if(!m_ImageViewTransform) { m_ImageViewTransform = new ossimImageViewProjectionTransform; } const char* maxLevelsToCompute = kwl.find(prefix, "max_levels_to_compute"); if(maxLevelsToCompute) { m_MaxLevelsToCompute = ossimString(maxLevelsToCompute).toUInt32(); } const ossimString threshold = kwl.find(prefix, "interpolation_error_threshold"); if(!threshold.empty()) { m_interpErrorThreshold = threshold.toDouble(); } return result; } void ossimImageRenderer::setImageViewTransform(ossimImageViewTransform* ivt) { m_ImageViewTransform = ivt; m_rectsDirty = true; // Want to recompute bounding rects. if ( m_ImageViewTransform.valid() && !m_ImageViewTransform->isValid() && isSourceEnabled() ) { checkIVT(); // This can initialize bounding rects and clear dirty flag. } if ( m_rectsDirty ) { initializeBoundingRects(); } } bool ossimImageRenderer::setView(ossimObject* baseObject) { bool new_view_set = false; if(m_ImageViewTransform.valid()) { new_view_set = m_ImageViewTransform->setView(baseObject); // If view changes reset the bounding rects. initializeBoundingRects(); } return new_view_set; } ossimObject* ossimImageRenderer::getView() { if(m_ImageViewTransform.valid()) { return m_ImageViewTransform->getView(); } return 0; } const ossimObject* ossimImageRenderer::getView()const { if(m_ImageViewTransform.valid()) { return m_ImageViewTransform->getView(); } return 0; } void ossimImageRenderer::getValidImageVertices(vector& validVertices, ossimVertexOrdering ordering, ossim_uint32 resLevel)const { if(theInputConnection&&m_ImageViewTransform.valid()&&m_ImageViewTransform->isValid()) { theInputConnection->getValidImageVertices(validVertices, ordering, resLevel); if(isSourceEnabled()) { ossim_uint32 inputSize = (ossim_uint32)validVertices.size(); if(inputSize) { ossimDpt viewPt; ossim_uint32 idx = 0; // transform each point to the view for(idx = 0; idx < inputSize; ++idx) { m_ImageViewTransform->imageToView(validVertices[idx], viewPt); // round it to the nearest pixel // validVertices[idx] = ossimIpt(viewPt); } } } } } //************************************************************************************************* // Returns the geometry associated with the image being served out of the renderer. This // corresponds to the view geometry defined in theIVT. //************************************************************************************************* ossimRefPtr ossimImageRenderer::getImageGeometry() { ossimRefPtr geom = 0; if (isSourceEnabled()) { // Make sure the IVT was properly initialized if (m_ImageViewTransform.valid() && !m_ImageViewTransform->isValid()) checkIVT(); ossimImageViewProjectionTransform* ivpt = dynamic_cast(m_ImageViewTransform.get()); if (ivpt) { // we need to return the right side since the geometry changed to a view geometry geom = ivpt->getViewGeometry(); } } else if (theInputConnection) { geom = theInputConnection->getImageGeometry(); } return geom; } void ossimImageRenderer::connectInputEvent(ossimConnectionEvent& /* event */) { theInputConnection = PTR_CAST(ossimImageSource, getInput(0)); if(!m_ImageViewTransform.valid()) m_ImageViewTransform = new ossimImageViewProjectionTransform; checkIVT(); initialize(); } void ossimImageRenderer::disconnectInputEvent(ossimConnectionEvent& /* event */) { ossimImageViewProjectionTransform* ivpt = dynamic_cast(m_ImageViewTransform.get()); if(ivpt) ivpt->setImageGeometry(0); theInputConnection = 0; } void ossimImageRenderer::propertyEvent(ossimPropertyEvent& /* event */) { checkIVT(); initialize(); } void ossimImageRenderer::setProperty(ossimRefPtr property) { ossimString tempName = property->getName(); if((tempName == "Filter type")|| (tempName == "filter_type")) { if(m_Resampler) { m_Resampler->setFilterType(property->valueToString()); } } // else if(tempName == "Blur factor") // { // if(m_Resampler) // { // m_Resampler->setBlurFactor(property->valueToString().toDouble()); // } // } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimImageRenderer::getProperty(const ossimString& name)const { ossimString tempName = name; if((tempName == "Filter type")|| (tempName == "filter_type")) { std::vector filterNames; m_Resampler->getFilterTypes(filterNames); ossimStringProperty* stringProp = new ossimStringProperty("filter_type", m_Resampler->getMinifyFilterTypeAsString(), false, filterNames); stringProp->clearChangeType(); stringProp->setReadOnlyFlag(false); stringProp->setCacheRefreshBit(); return stringProp; } // else if(tempName == "Blur factor") // { // ossimNumericProperty* numericProperty = new ossimNumericProperty("Blur factor", // ossimString::toString((double)m_Resampler->getBlurFactor())); // numericProperty->setConstraints(0.0, 50.0); // numericProperty->setNumericType(ossimNumericProperty::ossimNumericPropertyType_FLOAT64); // numericProperty->setCacheRefreshBit(); // return numericProperty; // } return ossimImageSourceFilter::getProperty(name); } void ossimImageRenderer::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("Filter type"); // propertyNames.push_back("Blur factor"); } //************************************************************************************************* // Insures that a proper IVT is established. //************************************************************************************************* void ossimImageRenderer::checkIVT() { if(!isSourceEnabled()) return; // Check validity of the IVT: if (m_ImageViewTransform->isValid()) return; // Detected uninitialized IVT. We are only concerned with projection IVTs (IVPTs) so // make sure that's what we're working with: ossimImageViewProjectionTransform* ivpt = dynamic_cast(m_ImageViewTransform.get()); ossimImageSource* inputSrc = PTR_CAST(ossimImageSource, getInput(0)); if(!ivpt || !inputSrc) return; // nothing to do here yet. // Fetch the input image geometry from the IVPT to see if one needs to be established: ossimRefPtr inputGeom = ivpt->getImageGeometry(); if ( !inputGeom ) { // Ask the input source for a geometry: inputGeom = inputSrc->getImageGeometry(); if ( !inputGeom ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimImageRenderer::checkTransform() -- " "No input image geometry could be established for this renderer."<setImageGeometry( inputGeom.get() ); m_rectsDirty = true; } // Now check the output view geometry: ossimRefPtr outputGeom = ivpt->getViewGeometry(); if (!outputGeom) { ossimRefPtr myOutGeom = new ossimImageGeometry; //--- // If the input geometry sports a map projection instead of a 3D // projector, use the same map projection for the view. // // Note: Don't use map projections with model transforms as they don't // allow for changing resolution. //--- const ossimProjection* inputProj = inputGeom->getProjection(); const ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, inputProj); if (mapProj) { ossimProjection* my_proj = PTR_CAST(ossimProjection, mapProj->dup()); myOutGeom->setProjection(my_proj); } else { // The input geometry uses a 3D projection, so let's default here to a // ossimEquDistCylProjection for the view: ossimMapProjection* myMapProj = new ossimEquDistCylProjection; ossimDpt meters = inputGeom->getMetersPerPixel(); double GSD = (meters.x + meters.y)/2.0; meters.x = GSD; meters.y = GSD; if(inputProj) { //--- // Update the map projection. Since ossimMapProjection::setOrigin calls // ossimMapProjection::update we do that before setUlTiePoints as it in // turn calls setUlEastingNorthing(forward(gpt)) which depends on the orgin. //--- myMapProj->setOrigin(inputProj->origin()); myMapProj->setUlTiePoints( inputProj->origin() ); } myMapProj->setMetersPerPixel(meters); myOutGeom->setProjection(myMapProj); } // Set up our IVT with the new output geometry: ivpt->setViewGeometry(myOutGeom.get()); // Must reinitialize bounding rects before calling ossimImageGeometry::setImageSize(). initializeBoundingRects(); // Set the size on the ossimImageGeometry. ossimIrect rect; getBoundingRect(rect, 0); myOutGeom->setImageSize( rect.size() ); } if ( m_rectsDirty ) { initializeBoundingRects(); } } void ossimImageRenderer::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result)const { if(isSourceEnabled()) { result = ossimDpt(1,1); } else { ossimImageSourceFilter::getDecimationFactor(resLevel, result); } } void ossimImageRenderer::getDecimationFactors(vector& decimations)const { if(isSourceEnabled()) { decimations.push_back(ossimDpt(1,1)); } else { ossimImageSourceFilter::getDecimationFactors(decimations); } } ossim_uint32 ossimImageRenderer::getNumberOfDecimationLevels()const { if(isSourceEnabled()) { return 1; } return ossimImageSourceFilter::getNumberOfDecimationLevels(); } void ossimImageRenderer::stretchQuadOut(const ossimDpt& amount, ossimDpt& ul, ossimDpt& ur, ossimDpt& lr, ossimDpt& ll) { ossimDpt upper = ur - ul; ossimDpt right = lr - ur; ossimDpt bottom = ll - lr; ossimDpt left = ul - ll; upper = (upper*(1.0 / upper.length())); upper.x *= amount.x; upper.y *= amount.y; right = (right*(1.0 / right.length())); right.x *= amount.x; right.y *= amount.y; bottom = (bottom*(1.0 / bottom.length())); bottom.x *= amount.x; bottom.y *= amount.y; left = (left*(1.0 / left.length())); left.x *= amount.x; left.y *= amount.y; ul = ul - upper + left; ur = ur + upper - right; lr = lr + left - bottom; ll = ll - left + bottom; } ossimRefPtr ossimImageRenderer::getTileAtResLevel(const ossimIrect& boundingRect, ossim_uint32 resLevel) { if(!theInputConnection) { m_BlankTile->setImageRectangle(boundingRect); return m_BlankTile; } ossim_uint32 levels = theInputConnection->getNumberOfDecimationLevels(); // ossim_uint32 maxValue = (ossim_uint32)ossim::max((ossim_uint32)m_BoundingRect.width(), // (ossim_uint32)m_BoundingRect.height()); if(resLevel == 0) { return theInputConnection->getTile(boundingRect); } if(resLevel < levels) { if(theInputConnection) { return theInputConnection->getTile(boundingRect, resLevel); } else { return m_BlankTile; } } else if((resLevel - levels) < m_MaxLevelsToCompute) { // check to see how many decimations we must achiev for the // request // int decimations = (resLevel - (levels-1)); ossimIpt tileSize(theInputConnection->getTileWidth(), theInputConnection->getTileHeight()); ossim_int32 multiplier = (1 << decimations); ossim_int32 xIndex = 0; ossim_int32 yIndex = 0; // adjust the tilesize so it at least will cover the multiplier // We will probably come up with something better later but for now // this will do. if(multiplier > tileSize.x) { tileSize.x = multiplier; } if(multiplier > tileSize.y) { tileSize.y = multiplier; } // set the rect that covers the requested RLevel to the valid RLevel. // the valid RLevel is what is available on the input side. // ossimIrect requestedRectAtValidRLevel = boundingRect; requestedRectAtValidRLevel.stretchToTileBoundary(tileSize); ossimIrect mappedRequestedRect = requestedRectAtValidRLevel; requestedRectAtValidRLevel = requestedRectAtValidRLevel*((double)multiplier); if(!m_TemporaryBuffer) { m_TemporaryBuffer = (ossimImageData*)m_BlankTile->dup(); m_TemporaryBuffer->setImageRectangle(mappedRequestedRect); m_TemporaryBuffer->initialize(); } else { m_TemporaryBuffer->setImageRectangle(mappedRequestedRect); m_TemporaryBuffer->makeBlank(); } // ossim_uint32 totalCount = ((requestedRectAtValidRLevel.lr().y-requestedRectAtValidRLevel.ul().y)* // (requestedRectAtValidRLevel.lr().x-requestedRectAtValidRLevel.ul().x)); ossim_uint32 currentCount = 0; ossimIrect boundingRect = theInputConnection->getBoundingRect(levels-1); for(yIndex = requestedRectAtValidRLevel.ul().y;yIndex < requestedRectAtValidRLevel.lr().y; yIndex += tileSize.y) { for(xIndex = requestedRectAtValidRLevel.ul().x; xIndex < requestedRectAtValidRLevel.lr().x; xIndex+=tileSize.x) { ossimIrect request(xIndex, yIndex, xIndex + (tileSize.x-1), yIndex + (tileSize.y-1)); ossimRefPtr data = theInputConnection->getTile(request, levels-1); if(data.valid() && (data->getDataObjectStatus()!=OSSIM_EMPTY)&& data->getBuf()&& boundingRect.intersects(request)) { switch(data->getScalarType()) { case OSSIM_UINT8: { resampleTileToDecimation((ossim_uint8)0, m_TemporaryBuffer, data, multiplier); break; } case OSSIM_SINT16: { resampleTileToDecimation((ossim_sint16)0, m_TemporaryBuffer, data, multiplier); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { resampleTileToDecimation((ossim_uint16)0, m_TemporaryBuffer, data, multiplier); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { resampleTileToDecimation((ossim_float32)0, m_TemporaryBuffer, data, multiplier); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { resampleTileToDecimation((ossim_float64)0, m_TemporaryBuffer, data, multiplier); break; } case OSSIM_SCALAR_UNKNOWN: default: { break; } } } ++currentCount; } } m_TemporaryBuffer->validate(); return m_TemporaryBuffer; } return 0; } void ossimImageRenderer::setMaxLevelsToCompute(ossim_uint32 maxLevels) { m_MaxLevelsToCompute = maxLevels; } ossim_uint32 ossimImageRenderer::getMaxLevelsToCompute()const { return m_MaxLevelsToCompute; } template void ossimImageRenderer::resampleTileToDecimation(T /* dummyVariable */, ossimRefPtr result, ossimRefPtr tile, ossim_uint32 multiplier) { if(tile->getDataObjectStatus() == OSSIM_EMPTY || !tile->getBuf()) { return; } ossim_int32 maxX = (ossim_int32)tile->getWidth(); ossim_int32 maxY = (ossim_int32)tile->getHeight(); ossim_int32 resultHeight = result->getHeight(); ossim_int32* offsetX = new ossim_int32[maxX]; ossim_int32* offsetY = new ossim_int32[maxY]; ossim_int32 i = 0; ossim_int32 resultWidth = (ossim_int32)result->getWidth(); ossimIpt tileOrigin = tile->getOrigin(); ossimIpt resultOrigin = result->getOrigin(); // create a lookup table. that maps the tile to the result for(i = 0; i < maxX; ++i) { offsetX[i] = (i+tileOrigin.x)/(ossim_int32)multiplier - resultOrigin.x; if(offsetX[i] < 0 ) { offsetX[i] = 0; } else if(offsetX[i] >= resultWidth) { offsetX[i] = resultWidth-1; } } for(i = 0; i < maxY; ++i) { offsetY[i] = ( ((i+tileOrigin.y)/(ossim_int32)multiplier) - resultOrigin.y); if(offsetY[i] < 0 ) { offsetY[i] = 0; } else if(offsetY[i] >= resultHeight) { offsetY[i] = resultHeight-1; } offsetY[i] *= resultWidth; } if(tile->getDataObjectStatus() == OSSIM_FULL) { ossim_int32 numberOfBands = (ossim_int32)std::min(result->getNumberOfBands(), tile->getNumberOfBands()); ossim_int32 band = 0; for(band = 0; band < numberOfBands; ++band) { T* tileBuf = static_cast(tile->getBuf(band)); T* resultBuf = static_cast(result->getBuf(band)); ossim_int32 dx = 0; ossim_int32 dy = 0; ossim_int32 boxAverageX = 0; ossim_int32 boxAverageY = 0; for(dy = 0; dy < maxY; dy+=multiplier) { for(dx = 0; dx < maxX; dx+=multiplier) { double sum = 0.0; for(boxAverageY = 0; ((boxAverageY < (ossim_int32)multiplier)&& ((boxAverageY+dy)getNumberOfBands(), tile->getNumberOfBands()); ossim_int32 band = 0; for(band = 0; band < numberOfBands; ++band) { T* tileBuf = static_cast(tile->getBuf(band)); T* resultBuf = static_cast(result->getBuf(band)); T tileBufNp = static_cast(tile->getNullPix(band)); ossim_int32 dx = 0; ossim_int32 dy = 0; ossim_int32 boxAverageX = 0; ossim_int32 boxAverageY = 0; for(dy = 0; dy < maxY; dy+=multiplier) { for(dx = 0; dx < maxX; dx+=multiplier) { double sum = 0.0; if(tileBuf[((dy+(multiplier>>1))*maxX + dx+(multiplier>>1))] != tileBufNp) { ossim_uint32 nullCount = 0; for(boxAverageY = 0; ((boxAverageY < (ossim_int32)multiplier)&& ((boxAverageY+dy) inputGeom = theInputConnection?theInputConnection->getImageGeometry().get():0; if(inputGeom) { ossimImageViewProjectionTransform* ivpt = dynamic_cast(m_ImageViewTransform.get()); if(ivpt) { ivpt->setImageGeometry(inputGeom.get()); } } } initialize(); } void ossimImageRenderer::enableSource() { if ( isSourceEnabled() == false ) { setEnableFlag( true ); } } void ossimImageRenderer::disableSource() { if ( isSourceEnabled() ) { setEnableFlag( false ); } } void ossimImageRenderer::setEnableFlag(bool flag) { if ( getEnableFlag() != flag ) { ossimImageSourceFilter::setEnableFlag( flag ); checkIVT(); initialize(); } } ossim-Miami-2.9.1/src/imaging/ossimImageSharpenFilter.cpp000066400000000000000000000524031352751253100234110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageSharpenFilter.cpp 18021 2010-09-01 12:11:05Z gpotts $ #include /* for abs() */ #include #include #include #include RTTI_DEF1(ossimImageSharpenFilter, "ossimImageSharpenFilter", ossimImageSourceFilter); // static const char* KERNEL_WIDTH_KW = "kernel_width"; // static const char* KERNEL_SIGMA_KW = "kernel_sigma"; static const char* SHARPEN_PERCENT_KW = "sharpen_percent"; ossimImageSharpenFilter::ossimImageSharpenFilter(ossimObject *owner) : ossimImageSourceFilter(owner), // theWidth(3), // theSigma(.5), m_sharpenPercent(0.0) { // theConvolutionSource = new ossimConvolutionSource; } ossimImageSharpenFilter::~ossimImageSharpenFilter() { } // void ossimImageSharpenFilter::setWidthAndSigma(ossim_uint32 w, ossim_float64 sigma) // { // theWidth = w; // theWidth |= 1; // if(theWidth < 3) theWidth = 3; // theSigma = sigma; // buildConvolutionMatrix(); // } void ossimImageSharpenFilter::setSharpenPercent(ossim_float64 percent) { m_sharpenPercent = percent; buildConvolutionLuts(); } ossimRefPtr ossimImageSharpenFilter::getTile( const ossimIrect &tileRect, ossim_uint32 resLevel) { if (!theInputConnection) { return NULL; } if (!isSourceEnabled() || (std::fabs(m_sharpenPercent) < FLT_EPSILON)) { return theInputConnection->getTile(tileRect, resLevel); } if (!m_tile.valid()) { allocate(); if (!m_tile.valid()) // Throw exception??? { return theInputConnection->getTile(tileRect, resLevel); } } ossimIrect requestRect(tileRect); requestRect.expand(ossimIpt(1, 1)); m_tile->makeBlank(); m_tile->setImageRectangle(tileRect); ossimRefPtr input = theInputConnection->getTile(requestRect, resLevel); if(input.valid()) { switch(input->getScalarType()) { case OSSIM_UINT8: { sharpenLut(static_cast(0), input, m_tile); break; } case OSSIM_UINT9: case OSSIM_UINT10: case OSSIM_UINT11: case OSSIM_UINT12: case OSSIM_UINT16: { sharpenLut(static_cast(0), input, m_tile); break; } case OSSIM_SINT16: { sharpenLutRemap(static_cast(0), input, m_tile); break; } default: { m_tile->loadTile(input.get()); break; } } } return m_tile; // return theConvolutionSource->getTile(tileRect, resLevel); } void ossimImageSharpenFilter::allocate() { if (theInputConnection) { m_tile = ossimImageDataFactory::instance()->create(this, theInputConnection); m_tile->initialize(); } } void ossimImageSharpenFilter::initialize() { ossimImageSourceFilter::initialize(); // if(theConvolutionSource->getInput()!=getInput()) // { // theConvolutionSource->disconnectAllInputs(); // theConvolutionSource->connectMyInputTo(0, getInput()); // } // buildConvolutionMatrix(); buildConvolutionLuts(); } void ossimImageSharpenFilter::buildConvolutionLuts() { // Gimp port of the sharpen kernel. I will describe what appears to be happening in the Gimp code // and then port to work with any bit depths. // // the Laplacian kernel is a 3x3 matrix kernel where the center is 8 and the surrounding kernel weights are -1 // by multiplying through the positive coefficient by 100/100 ( essentially 1) giving you // // 100*8*/(100 - m_sharpenPercent*100) // giving you // 800*/(100 - m_sharpenPercent*100) // // If you didn't multiply by 1 then we would need to have a floating buffer and this would have the same // affect as // // 8*/(1 - m_sharpenPercent) // ossim_float64 fact = 100 - m_sharpenPercent*100.0; ossim_int32 size = 0; if( fact < FLT_EPSILON ) fact = 1.0; // precompute luts for 8, 11, 12 and 16 bit data // m_remapValue = false; if (theInputConnection && fact >= 1) { ossimScalarType outputScalarType = theInputConnection->getOutputScalarType(); switch (outputScalarType) { case OSSIM_UINT8: /**< 8 bit unsigned integer */ { size = 256; break; } case OSSIM_UINT9: /**< 9 bit unsigned integer */ { size = 512; break; } case OSSIM_UINT10: /**< 10 bit unsigned integer */ { size = 1024; break; } case OSSIM_UINT11: /**< 16 bit unsigned integer (9 bits used) */ { size = 2048; break; } case OSSIM_UINT12: { size = 4096; break; } case OSSIM_UINT16: { size = 65536; break; } default: { // for remapping we will just a set of sample // values and then do a normalization // we will enable remap and do a 256 samples // for the laplacian. m_remapValue = true; size = 256; } } } else { m_posLut.clear(); m_posNegLut.clear(); } if(size) { m_posLut.resize(size); m_posNegLut.resize(size); } for (ossim_int32 i = 0; i < (ossim_int32)m_posLut.size(); i++) { m_posLut[i] = 800 * i / fact; m_posNegLut[i] = (4 + m_posLut[i] - (i << 3))/ 8.0; } } void ossimImageSharpenFilter::connectInputEvent(ossimConnectionEvent &event) { ossimImageSourceFilter::connectInputEvent(event); buildConvolutionLuts(); } void ossimImageSharpenFilter::disconnectInputEvent(ossimConnectionEvent &event) { ossimImageSourceFilter::disconnectInputEvent(event); } ossimString ossimImageSharpenFilter::getShortName() const { return ossimString("Sharpen"); } ossimString ossimImageSharpenFilter::getLongName() const { return ossimString("Sharpens the input"); } template void ossimImageSharpenFilter::sharpenLut(T, const ossimRefPtr &inputTile, ossimRefPtr &outputTile) { ossimDataObjectStatus status = inputTile->getDataObjectStatus(); ossim_int64 tileHeight = outputTile->getHeight(); ossim_int64 tileWidth = outputTile->getWidth(); // ossim_int64 inputTileHeight= inputTile->getHeight(); ossim_int64 inputTileWidth = inputTile->getWidth(); ossim_int64 outputBands = outputTile->getNumberOfBands(); // ossim_int64 convolutionTopLeftOffset = 0; // ossim_int64 convolutionMiddleLeftOffset = 0; // ossim_int64 convolutionBottomLeftOffset = 0; // ossim_int64 convolutionCenterOffset = inputTileWidth + 1; // kernel is a 3x3 so move it over by 1 // ossim_int64 outputOffset = 0; std::vector inputBandBuf(outputBands); std::vector outputBandBuf(outputBands); for (ossim_int64 b = 0; b < outputBands; ++b) { inputBandBuf[b] = (T *)(inputTile->getBuf(b)); outputBandBuf[b] = (T *)(outputTile->getBuf(b)); } if (status == OSSIM_NULL || status == OSSIM_EMPTY) { outputTile->makeBlank(); } else if(status == OSSIM_FULL) { for (ossim_int64 b = 0; b < outputBands; ++b) { ossim_float64 minPix = outputTile->getMinPix(b); ossim_float64 maxPix = outputTile->getMaxPix(b); // convolutionTopLeftOffset = 0; // convolutionCenterOffset = convolutionTopLeftOffset + inputTileWidth + 1; // convolutionMiddleLeftOffset = convolutionTopLeftOffset + inputTileWidth; // convolutionBottomLeftOffset = convolutionMiddleLeftOffset + inputTileWidth; T *inBuf = (T *)(inputBandBuf[b]); T *outBuf = (T *)(outputBandBuf[b]); for (ossim_int64 y = 0; y < tileHeight; y++) { for (ossim_int64 x = 0; x < tileWidth; ++x, ++inBuf, ++outBuf) { ossim_float64 convolveResult = 0.0; ossim_float64 pos = m_posLut[*(inBuf + inputTileWidth + 1)]; ossim_float64 neg = m_posNegLut[*(inBuf)] + m_posNegLut[*(inBuf + 1)] + m_posNegLut[*(inBuf + 2)]; // top neg += (m_posNegLut[*(inBuf + inputTileWidth)] + m_posNegLut[*(inBuf + inputTileWidth + 2)]); // middle without positive neg += (m_posNegLut[*(inBuf + (inputTileWidth << 1))] + m_posNegLut[*(inBuf + (inputTileWidth << 1) + 1)] + m_posNegLut[*(inBuf + (inputTileWidth << 1) + 2)]); // bottom convolveResult = ((pos - neg) + 4)/ 8.0; convolveResult = convolveResult < minPix ? minPix : convolveResult; convolveResult = convolveResult > maxPix ? maxPix : convolveResult; *outBuf = (T)convolveResult; } inBuf +=2; } } } else { ossim_float64 inputValues[9]; for (ossim_int64 b = 0; b < outputBands; ++b) { ossim_float64 minPix = inputTile->getMinPix(b); ossim_float64 maxPix = inputTile->getMaxPix(b); ossim_float64 nullPix = inputTile->getNullPix(b); // convolutionTopLeftOffset = 0; // convolutionCenterOffset = convolutionTopLeftOffset + inputTileWidth + 1; // convolutionMiddleLeftOffset = convolutionTopLeftOffset + inputTileWidth; // convolutionBottomLeftOffset = convolutionMiddleLeftOffset + inputTileWidth; T *inBuf = (T *)(inputBandBuf[b]); T *outBuf = (T *)(outputBandBuf[b]); for (ossim_int64 y = 0; y < tileHeight; y++) { for (ossim_int64 x = 0; x < tileWidth; ++x, ++inBuf, ++outBuf) { ossim_float64 convolveResult = 0.0; inputValues[0] = *(inBuf); inputValues[1] = *(inBuf + 1); inputValues[2] = *(inBuf + 2); inputValues[3] = *(inBuf + inputTileWidth); inputValues[4] = *(inBuf + inputTileWidth + 1); inputValues[5] = *(inBuf + inputTileWidth + 2); inputValues[6] = *(inBuf + (inputTileWidth<<1) ); inputValues[7] = *(inBuf + (inputTileWidth<<1)+1); inputValues[8] = *(inBuf + (inputTileWidth<<1)+2); if((inputValues[0]==nullPix)|| (inputValues[1]==nullPix)|| (inputValues[2]==nullPix)|| (inputValues[3]==nullPix)|| (inputValues[4]==nullPix)|| (inputValues[5]==nullPix)|| (inputValues[6]==nullPix)|| (inputValues[7]==nullPix)|| (inputValues[8]==nullPix)) { *outBuf = static_cast(inputValues[4]); } else { ossim_float64 pos = m_posLut[inputValues[4]]; ossim_float64 neg = m_posNegLut[inputValues[0]] + m_posNegLut[inputValues[1]] + m_posNegLut[inputValues[2]] + m_posNegLut[inputValues[3]] + m_posNegLut[inputValues[5]] + m_posNegLut[inputValues[6]] + m_posNegLut[inputValues[7]] + m_posNegLut[inputValues[8]]; convolveResult = ((pos - neg) + 4) / 8.0; convolveResult = convolveResult < minPix ? minPix : convolveResult; convolveResult = convolveResult > maxPix ? maxPix : convolveResult; *outBuf = static_cast(convolveResult); /* code */ } } inBuf += 2; } } } outputTile->validate(); } template void ossimImageSharpenFilter::sharpenLutRemap(T, const ossimRefPtr &inputTile, ossimRefPtr &outputTile) { ossim_float64 inputValues[9]; ossimDataObjectStatus status = inputTile->getDataObjectStatus(); ossim_int64 tileHeight = outputTile->getHeight(); ossim_int64 tileWidth = outputTile->getWidth(); // ossim_int64 inputTileHeight = inputTile->getHeight(); ossim_int64 inputTileWidth = inputTile->getWidth(); ossim_int64 outputBands = outputTile->getNumberOfBands(); // ossim_int64 convolutionTopLeftOffset = 0; // ossim_int64 convolutionMiddleLeftOffset = 0; // ossim_int64 convolutionBottomLeftOffset = 0; // kernel is a 3x3 so move it over by 1 // ossim_int64 convolutionCenterOffset = inputTileWidth + 1; // ossim_int64 outputOffset = 0; ossim_float64 convolveResult = 0.0; std::vector inputBandBuf(outputBands); std::vector outputBandBuf(outputBands); for (ossim_int64 b = 0; b < outputBands; ++b) { inputBandBuf[b] = (T *)(inputTile->getBuf(b)); outputBandBuf[b] = (T *)(outputTile->getBuf(b)); } if (status == OSSIM_NULL || status == OSSIM_EMPTY) { outputTile->makeBlank(); } else if (status == OSSIM_FULL) // whether partial or null we must check nulls over entire matrix { for (ossim_int64 b = 0; b < outputBands; ++b) { ossim_float64 minPix = outputTile->getMinPix(b); ossim_float64 maxPix = outputTile->getMaxPix(b); // convolutionTopLeftOffset = 0; // convolutionCenterOffset = convolutionTopLeftOffset + inputTileWidth + 1; // convolutionMiddleLeftOffset = convolutionTopLeftOffset + inputTileWidth; // convolutionBottomLeftOffset = convolutionMiddleLeftOffset + inputTileWidth; T *inBuf = (T *)(inputBandBuf[b]); T *outBuf = (T *)(outputBandBuf[b]); ossim_float64 deltaMinMax = (maxPix-minPix); // ossimScalarType inputScalar = inputTile->getScalarType(); for (ossim_int64 y = 0; y < tileHeight; y++) { for (ossim_int64 x = 0; x < tileWidth; ++x, ++inBuf, ++outBuf) { inputValues[0] = *(inBuf); inputValues[1] = *(inBuf + 1); inputValues[2] = *(inBuf + 2); inputValues[3] = *(inBuf + inputTileWidth); inputValues[4] = *(inBuf + inputTileWidth + 1); inputValues[5] = *(inBuf + inputTileWidth + 2); inputValues[6] = *(inBuf + (inputTileWidth << 1)); inputValues[7] = *(inBuf + (inputTileWidth << 1) + 1); inputValues[8] = *(inBuf + (inputTileWidth << 1) + 2); for (ossim_uint32 idx = 0; idx < 9; ++idx) { inputValues[idx] = ((inputValues[idx] - minPix) / deltaMinMax) * m_posLut.size(); if (inputValues[idx] < 0) inputValues[idx] = 0; if (inputValues[idx] >= m_posLut.size()) inputValues[idx] = m_posLut.size() - 1; } ossim_float64 pos = m_posLut[inputValues[4]]; ossim_float64 neg = m_posNegLut[inputValues[0]] + m_posNegLut[inputValues[1]] + m_posNegLut[inputValues[2]] + m_posNegLut[inputValues[3]] + m_posNegLut[inputValues[5]] + m_posNegLut[inputValues[6]] + m_posNegLut[inputValues[7]] + m_posNegLut[inputValues[8]]; convolveResult = ((pos - neg) + 4) / 8.0; convolveResult = convolveResult < 0 ? 0 : convolveResult; convolveResult = convolveResult > (m_posLut.size() - 1) ? m_posLut.size() - 1 : convolveResult; ossim_float64 t = convolveResult / (m_posLut.size() - 1); *outBuf = static_cast(minPix * (1 - t) + deltaMinMax * t); } inBuf += 2; } } } else { for (ossim_int64 b = 0; b < outputBands; ++b) { ossim_float64 minPix = outputTile->getMinPix(b); ossim_float64 maxPix = outputTile->getMaxPix(b); ossim_float64 nullPix = inputTile->getNullPix(b); // convolutionTopLeftOffset = 0; // convolutionCenterOffset = convolutionTopLeftOffset + inputTileWidth + 1; // convolutionMiddleLeftOffset = convolutionTopLeftOffset + inputTileWidth; // convolutionBottomLeftOffset = convolutionMiddleLeftOffset + inputTileWidth; T *inBuf = (T *)(inputBandBuf[b]); T *outBuf = (T *)(outputBandBuf[b]); ossim_float64 deltaMinMax = (maxPix - minPix); for (ossim_int64 y = 0; y < tileHeight; y++) { for (ossim_int64 x = 0; x < tileWidth; ++x, ++inBuf, ++outBuf) { inputValues[0] = *(inBuf); inputValues[1] = *(inBuf + 1); inputValues[2] = *(inBuf + 2); inputValues[3] = *(inBuf + inputTileWidth); inputValues[4] = *(inBuf + inputTileWidth + 1); inputValues[5] = *(inBuf + inputTileWidth + 2); inputValues[6] = *(inBuf + (inputTileWidth << 1)); inputValues[7] = *(inBuf + (inputTileWidth << 1) + 1); inputValues[8] = *(inBuf + (inputTileWidth << 1) + 2); if ((inputValues[0] == nullPix) && (inputValues[1] == nullPix) && (inputValues[2] == nullPix) && (inputValues[3] == nullPix) && (inputValues[4] == nullPix) && (inputValues[5] == nullPix) && (inputValues[6] == nullPix) && (inputValues[7] == nullPix) && (inputValues[8] == nullPix)) { *outBuf = static_cast(inputValues[4]); } else { for (ossim_uint32 idx = 0; idx < 9; ++idx) { inputValues[idx] = ((inputValues[idx] - minPix) / deltaMinMax) * m_posLut.size(); if (inputValues[idx] < 0) inputValues[idx] = 0; if (inputValues[idx] >= m_posLut.size()) inputValues[idx] = m_posLut.size() - 1; } ossim_float64 pos = m_posLut[inputValues[4]]; ossim_float64 neg = m_posNegLut[inputValues[0]] + m_posNegLut[inputValues[1]] + m_posNegLut[inputValues[2]] + m_posNegLut[inputValues[3]] + m_posNegLut[inputValues[5]] + m_posNegLut[inputValues[6]] + m_posNegLut[inputValues[7]] + m_posNegLut[inputValues[8]]; convolveResult = ((pos - neg) + 4.0) / 8.0; convolveResult = convolveResult < 0 ? 0 : convolveResult; convolveResult = convolveResult > (m_posLut.size() - 1) ? m_posLut.size() - 1 : convolveResult; ossim_float64 t = convolveResult / (m_posLut.size() - 1); *outBuf = static_cast(minPix * (1 - t) + deltaMinMax * t); } } inBuf += 2; } } } outputTile->validate(); } void ossimImageSharpenFilter::setProperty(ossimRefPtr property) { if(!property) return; if(property->getName() == SHARPEN_PERCENT_KW) { m_sharpenPercent = property->valueToString().toDouble(); initialize(); } else { ossimImageSourceFilter::setProperty(property.get()); } } ossimRefPtr ossimImageSharpenFilter::getProperty(const ossimString& name)const { ossimRefPtr property = 0; if (name == SHARPEN_PERCENT_KW) { property = new ossimNumericProperty(name, ossimString::toString(m_sharpenPercent), 0.0, 1.0); property->setCacheRefreshBit(); } else { property = ossimImageSourceFilter::getProperty(name); } return property.get(); } void ossimImageSharpenFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back(SHARPEN_PERCENT_KW); } bool ossimImageSharpenFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimImageSourceFilter::loadState(kwl, prefix); ossimString sharpenPercent = kwl.find(prefix, SHARPEN_PERCENT_KW); if(!sharpenPercent.empty()) { m_sharpenPercent = sharpenPercent.toDouble(); } buildConvolutionLuts(); return result; } bool ossimImageSharpenFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, SHARPEN_PERCENT_KW, m_sharpenPercent, true); return ossimImageSourceFilter::saveState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimImageSource.cpp000066400000000000000000000243471352751253100221110ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageSource.cpp 23100 2015-01-26 19:43:08Z okramer $ #include #include #include RTTI_DEF1(ossimImageSource, "ossimImageSource" , ossimSource) ossimImageSource::ossimImageSource(ossimObject* owner) :ossimSource(owner, 0,0,false,false) { } ossimImageSource::ossimImageSource(ossimObject* owner, ossim_uint32 inputListSize, ossim_uint32 outputListSize, bool inputListIsFixedFlag, bool outputListIsFixedFlag) : ossimSource(owner, inputListSize, outputListSize, inputListIsFixedFlag, outputListIsFixedFlag) { } ossimImageSource::~ossimImageSource() { } ossimRefPtr ossimImageSource::getTile(const ossimIpt& origin, ossim_uint32 resLevel) { ossimIrect tileRect(origin.x, origin.y, origin.x + getTileWidth() - 1, origin.y + getTileHeight() - 1); return getTile(tileRect, resLevel); } ossimRefPtr ossimImageSource::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getTile(rect, resLevel); } return NULL; } bool ossimImageSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { // This is the default implementation that is not thread-friendly as it uses the object's tile // then simply assigns its buffer to the provided tile. Eventually, all image sources should // override this method. bool status = true; if (result) { ossimIrect tileRect = result->getImageRectangle(); ossimRefPtr id = getTile(tileRect, resLevel); if (id.valid()) { *result = *(id.get()); result->loadTile(id.get()); // Deep copy } else { status = false; } } return status; } void ossimImageSource::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result)const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { inter->getDecimationFactor(resLevel, result); } } void ossimImageSource::getDecimationFactors(std::vector& decimations)const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { inter->getDecimationFactors(decimations); } } ossim_uint32 ossimImageSource::getNumberOfDecimationLevels() const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getNumberOfDecimationLevels(); } return 0; } ossimScalarType ossimImageSource::getOutputScalarType() const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getOutputScalarType(); } return OSSIM_SCALAR_UNKNOWN; } ossim_uint32 ossimImageSource::getTileWidth() const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getTileWidth(); } ossimIpt tileSize; ossim::defaultTileSize(tileSize); return tileSize.x; } ossim_uint32 ossimImageSource::getTileHeight() const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getTileHeight(); } ossimIpt tileSize; ossim::defaultTileSize(tileSize); return tileSize.y; } ossimIrect ossimImageSource::getBoundingRect(ossim_uint32 resLevel)const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getBoundingRect(resLevel); } ossimIrect rect; rect.makeNan(); return rect; } void ossimImageSource::getBoundingRect(ossimIrect& rect, ossim_uint32 resLevel) const { rect = getBoundingRect( resLevel ); } bool ossimImageSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimSource::saveState(kwl, prefix); } bool ossimImageSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimSource::loadState(kwl, prefix); } //***************************************************************************** // METHOD: ossimImageSource::getValidImageVertices() //***************************************************************************** void ossimImageSource::getValidImageVertices(std::vector& validVertices, ossimVertexOrdering ordering, ossim_uint32 resLevel)const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getValidImageVertices(validVertices, ordering, resLevel); } ossimIrect boundingRect = getBoundingRect(resLevel); validVertices.clear(); if(ordering == OSSIM_CLOCKWISE_ORDER) { validVertices.push_back(boundingRect.ul()); validVertices.push_back(boundingRect.ur()); validVertices.push_back(boundingRect.lr()); validVertices.push_back(boundingRect.ll()); } else { validVertices.push_back(boundingRect.ul()); validVertices.push_back(boundingRect.ll()); validVertices.push_back(boundingRect.lr()); validVertices.push_back(boundingRect.ur()); } } double ossimImageSource::getNullPixelValue(ossim_uint32 band)const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getNullPixelValue(band); } return ossim::defaultNull(getOutputScalarType()); } double ossimImageSource::getMinPixelValue(ossim_uint32 band)const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getMinPixelValue(band); } return ossim::defaultMin(getOutputScalarType()); } double ossimImageSource::getMaxPixelValue(ossim_uint32 band)const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if(inter) { return inter->getMaxPixelValue(band); } return ossim::defaultMax(getOutputScalarType()); } //************************************************************************************************** // Default implementation returns the image geometry object associated with the first input source // (if any) connected to this source, or NULL. //************************************************************************************************** ossimRefPtr ossimImageSource::getImageGeometry() { ossimRefPtr result = 0; if ( getInput(0) ) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if( inter ) { result = inter->getImageGeometry(); } } return result; } //************************************************************************************************** //! Default implementation sets geometry of the first input to the geometry specified. //************************************************************************************************** void ossimImageSource::setImageGeometry(const ossimImageGeometry* geom) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if (inter) { inter->setImageGeometry(geom); } } void ossimImageSource::saveImageGeometry() const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if (inter) { inter->saveImageGeometry(); } } void ossimImageSource::saveImageGeometry(const ossimFilename& geometry_file) const { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if (inter) { inter->saveImageGeometry(geometry_file); } } void ossimImageSource::getOutputBandList(std::vector& bandList) const { const ossim_uint32 INPUT_BANDS = getNumberOfInputBands(); if ( INPUT_BANDS ) { bandList.resize( INPUT_BANDS ); for ( ossim_uint32 band = 0; band < INPUT_BANDS; ++band ) { bandList[band] = band; } } else { bandList.clear(); } } ossim_uint32 ossimImageSource::getNumberOfOutputBands() const { return getNumberOfInputBands(); } ossimRefPtr ossimImageSource::getProperty(const ossimString& name)const { ossimRefPtr result = ossimSource::getProperty(name); ossimString tempName = name; if(result.valid()) { if(tempName.downcase() == ossimKeywordNames::ENABLED_KW) { result->clearChangeType(); // we will at least say its a radiometric change // result->setFullRefreshBit(); } } return result; } void ossimImageSource::setProperty(ossimRefPtr property) { ossimSource::setProperty(property); } void ossimImageSource::getPropertyNames(std::vector& propertyNames)const { ossimSource::getPropertyNames(propertyNames); } bool ossimImageSource::isIndexedData() const { bool result = false; ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput(0)); if (inter) { result = inter->isIndexedData(); } return result; } // Protected to hide from use... ossimImageSource::ossimImageSource (const ossimImageSource& /* rhs */) :ossimSource() {} // Protected to hide from use... const ossimImageSource& ossimImageSource::operator=(const ossimImageSource&) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimImageSourceFactory.cpp000066400000000000000000000533371352751253100234420ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This is the image source factory. // It will try to create image filters // first then it will try the image writers // and image handlers (image readers) // //************************************************************************* // $Id: ossimImageSourceFactory.cpp 22981 2014-11-13 22:08:39Z okramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Not sure if we want to keep this here #include #include using namespace std; RTTI_DEF1(ossimImageSourceFactory, "ossimImageSourceFactory", ossimImageSourceFactoryBase); static ossimTrace traceDebug("ossimImageSourceFactory:debug"); ossimImageSourceFactory* ossimImageSourceFactory::theInstance=NULL; ossimImageSourceFactory::~ossimImageSourceFactory() { theInstance = NULL; ossimObjectFactoryRegistry::instance()->unregisterFactory(this); } ossimImageSourceFactory* ossimImageSourceFactory::instance() { if(!theInstance) { theInstance = new ossimImageSourceFactory; } return theInstance; } ossimObject* ossimImageSourceFactory::createObject(const ossimString& name)const { // lets do the filters first if( name == STATIC_TYPE_NAME(ossimBandSelector) || name == "ossimNativeBandSelectorTileSource" ) { //--- // For backwards compatibility check old name: // "ossimNativeBandSelectorTileSource" //--- return new ossimBandSelector; } else if(name == STATIC_TYPE_NAME(ossimMultiThreadSequencer) || name == "ossimMultiThreadSequencer") { return new ossimMultiThreadSequencer; } else if(name == STATIC_TYPE_NAME(ossimNullPixelFlip)) { return new ossimNullPixelFlip; } else if(name == STATIC_TYPE_NAME(ossimElevRemapper)) { return new ossimElevRemapper; } else if(name == STATIC_TYPE_NAME(ossimImageRenderer)) { return new ossimImageRenderer; } else if(name == STATIC_TYPE_NAME(ossimCacheTileSource)) { return new ossimCacheTileSource; } else if(name == STATIC_TYPE_NAME(ossimColorNormalizedFusion)) { return new ossimColorNormalizedFusion; } else if(name == STATIC_TYPE_NAME(ossimLocalCorrelationFusion)) { return new ossimLocalCorrelationFusion; } else if(name == STATIC_TYPE_NAME(ossimSFIMFusion)) { return new ossimSFIMFusion; } else if(name == STATIC_TYPE_NAME(ossimBlendMosaic)) { return new ossimBlendMosaic; } else if(name == STATIC_TYPE_NAME(ossimMaxMosaic)) { return new ossimMaxMosaic; } else if(name == STATIC_TYPE_NAME(ossimHistogramRemapper)) { return new ossimHistogramRemapper; } else if(name == STATIC_TYPE_NAME(ossimImageMosaic)) { return new ossimImageMosaic; } else if(name == STATIC_TYPE_NAME(ossimElevationMosaic)) { return new ossimElevationMosaic; } else if(name == STATIC_TYPE_NAME(ossimPiecewiseRemapper)) { return new ossimPiecewiseRemapper; } else if(name == STATIC_TYPE_NAME(ossimImageSourceSequencer)) { return new ossimImageSourceSequencer; } else if(name == STATIC_TYPE_NAME(ossimClosestToCenterCombiner)) { return new ossimClosestToCenterCombiner; } else if(name == STATIC_TYPE_NAME(ossimRgbToGreyFilter)) { return new ossimRgbToGreyFilter; } else if(name == STATIC_TYPE_NAME(ossimNBandToIndexFilter)) { return new ossimNBandToIndexFilter; } else if(name == STATIC_TYPE_NAME(ossimImageChain)) { return new ossimImageChain; } else if(name == STATIC_TYPE_NAME(ossimPolyCutter)) { return new ossimPolyCutter; } else if(name == STATIC_TYPE_NAME(ossimGeoPolyCutter)) { return new ossimGeoPolyCutter; } else if(name == STATIC_TYPE_NAME(ossimJpegYCbCrToRgbSource)) { return new ossimJpegYCbCrToRgbSource; } else if(name == STATIC_TYPE_NAME(ossimRgbToJpegYCbCrSource)) { return new ossimRgbToJpegYCbCrSource; } else if(name == STATIC_TYPE_NAME(ossimHsiToRgbSource)) { return new ossimHsiToRgbSource; } else if(name == STATIC_TYPE_NAME(ossimRgbToHsiSource)) { return new ossimRgbToHsiSource; } else if(name == STATIC_TYPE_NAME(ossimHsvToRgbSource)) { return new ossimHsvToRgbSource; } else if(name == STATIC_TYPE_NAME(ossimRgbToHsvSource)) { return new ossimRgbToHsvSource; } else if(name == STATIC_TYPE_NAME(ossimHistogramEqualization)) { return new ossimHistogramEqualization; } else if(name == STATIC_TYPE_NAME(ossimHistogramMatchFilter)) { return new ossimHistogramMatchFilter; } else if(name == STATIC_TYPE_NAME(ossimHistogramThreshholdFilter)) { return new ossimHistogramThreshholdFilter; } else if(name == STATIC_TYPE_NAME(ossimGeoAnnotationSource)) { return new ossimGeoAnnotationSource; } else if(name == STATIC_TYPE_NAME(ossimConvolutionSource)) { return new ossimConvolutionSource; } else if(name == STATIC_TYPE_NAME(ossimSICDToDetectedImage)) { return new ossimSICDToDetectedImage; } else if(name == STATIC_TYPE_NAME(ossimBrightnessContrastSource)) { return new ossimBrightnessContrastSource; } else if(name == STATIC_TYPE_NAME(ossimBrightnessMatch)) { return new ossimBrightnessMatch; } else if(name == STATIC_TYPE_NAME(ossimScalarRemapper)) { return new ossimScalarRemapper; } else if(name == STATIC_TYPE_NAME(ossimBandMergeSource)) { return new ossimBandMergeSource; } else if(name == STATIC_TYPE_NAME(ossimFeatherMosaic)) { return new ossimFeatherMosaic; } else if(name == STATIC_TYPE_NAME(ossimGridRemapSource)) { return new ossimGridRemapSource; } else if(name == STATIC_TYPE_NAME(ossimEquationCombiner)) { return new ossimEquationCombiner; } else if(name == STATIC_TYPE_NAME(ossimConvolutionFilter1D)) { return new ossimConvolutionFilter1D; } else if(name == STATIC_TYPE_NAME(ossimImageGaussianFilter)) { return new ossimImageGaussianFilter; } // Not sure if we want to keep this here else if(name == STATIC_TYPE_NAME(ossimAtbController)) { return new ossimAtbController; } else if(name == STATIC_TYPE_NAME(ossimIndexToRgbLutFilter)) { return new ossimIndexToRgbLutFilter; } else if(name == STATIC_TYPE_NAME(ossimBumpShadeTileSource)) { return new ossimBumpShadeTileSource; } else if(name == STATIC_TYPE_NAME(ossimSubImageTileSource)) { return new ossimSubImageTileSource; } else if(name == STATIC_TYPE_NAME(ossimRLevelFilter)) { return new ossimRLevelFilter; } else if(name == STATIC_TYPE_NAME(ossimBandClipFilter)) { return new ossimBandClipFilter; } else if(name == STATIC_TYPE_NAME(ossimHsiRemapper)) { return new ossimHsiRemapper; } else if(name == STATIC_TYPE_NAME(ossimHistogramWriter)) { return new ossimHistogramWriter; } else if(name == STATIC_TYPE_NAME(ossimImageHistogramSource)) { return new ossimImageHistogramSource; } else if(name == STATIC_TYPE_NAME(ossimRectangleCutFilter)) { return new ossimRectangleCutFilter; } else if(name == STATIC_TYPE_NAME(ossimCastTileSourceFilter)) { return new ossimCastTileSourceFilter; } // all the image handlers else if(name == STATIC_TYPE_NAME(ossimValueAssignImageSourceFilter)) { return new ossimValueAssignImageSourceFilter; } else if(name == STATIC_TYPE_NAME(ossimImageSharpenFilter)) { return new ossimImageSharpenFilter; } else if(name == STATIC_TYPE_NAME(ossim3x3ConvolutionFilter)) { return new ossim3x3ConvolutionFilter; } else if(name == STATIC_TYPE_NAME(ossimOrthoImageMosaic)) { return new ossimOrthoImageMosaic; } else if(name == STATIC_TYPE_NAME(ossimPiecewiseRemapper)) { return new ossimPiecewiseRemapper; } else if(name == STATIC_TYPE_NAME(ossimMapCompositionSource)) { return new ossimMapCompositionSource; } else if(name == STATIC_TYPE_NAME(ossimElevImageSource)) { return new ossimElevImageSource; } else if(name == STATIC_TYPE_NAME(ossimMaskFilter)) { return new ossimMaskFilter; } else if(name == STATIC_TYPE_NAME(ossimMultiBandHistogramTileSource)) { return new ossimMultiBandHistogramTileSource; } else if(name == STATIC_TYPE_NAME(ossimBandAverageFilter)) { return new ossimBandAverageFilter; } else if(name == STATIC_TYPE_NAME(ossimPixelFlipper)) { return new ossimPixelFlipper(); } else if(name == STATIC_TYPE_NAME(ossimScaleFilter)) { return new ossimScaleFilter(); } else if(name == STATIC_TYPE_NAME(ossimImageToPlaneNormalFilter)) { return new ossimImageToPlaneNormalFilter(); } else if(name == STATIC_TYPE_NAME(ossimTopographicCorrectionFilter)) { return new ossimTopographicCorrectionFilter(); } else if(name == STATIC_TYPE_NAME(ossimLandsatTopoCorrectionFilter)) { return new ossimLandsatTopoCorrectionFilter(); } else if(name == STATIC_TYPE_NAME(ossimAtCorrRemapper)) { return new ossimAtCorrRemapper(); } else if(name == STATIC_TYPE_NAME(ossimAtCorrGridRemapper)) { return new ossimAtCorrGridRemapper(); } else if(name == STATIC_TYPE_NAME(ossimEastingNorthingCutter)) { return new ossimEastingNorthingCutter(); } else if(name == STATIC_TYPE_NAME(ossimEdgeFilter)) { return new ossimEdgeFilter(); } else if(name == STATIC_TYPE_NAME(ossimFftFilter)) { return new ossimFftFilter(); } else if(name == STATIC_TYPE_NAME(ossimWatermarkFilter)) { return new ossimWatermarkFilter(); } else if(name == STATIC_TYPE_NAME(ossimImageGaussianFilter)) { return new ossimImageGaussianFilter(); } else if(name == STATIC_TYPE_NAME(ossimTrimFilter)) { return new ossimTrimFilter(); } else if(name == STATIC_TYPE_NAME(ossimTwoColorView)) { return new ossimTwoColorView; } else if(name == STATIC_TYPE_NAME(ossimImageHistogramSource)) { return new ossimImageHistogramSource(); } else if(name == STATIC_TYPE_NAME(ossimImageSourceFilter)) { // this is just a pass through source return new ossimImageSourceFilter; } else if(name == STATIC_TYPE_NAME(ossimMemoryImageSource)) { // this is just a pass through source return new ossimMemoryImageSource; } else if(name == STATIC_TYPE_NAME(ossimDilationFilter)) { return new ossimDilationFilter(); } else if(name == STATIC_TYPE_NAME(ossimErosionFilter)) { return new ossimErosionFilter(); } else if(name == STATIC_TYPE_NAME(ossimGammaRemapper)) { return new ossimGammaRemapper(); } return NULL; } ossimObject* ossimImageSourceFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { static const char* MODULE = "ossimImageSourceFactory::createSource"; ossimString copyPrefix; if (prefix) { copyPrefix = prefix; } ossimObject* result = NULL; if(traceDebug()) { CLOG << "looking up type keyword for prefix = " << copyPrefix << endl; } const char* lookup = kwl.find(copyPrefix, "type"); if(lookup) { ossimString name = lookup; result = createObject(name); if(result) { if(traceDebug()) { CLOG << "found source " << result->getClassName() << " now loading state" << endl; } result->loadState(kwl, copyPrefix.c_str()); } else { if(traceDebug()) { CLOG << "type not found " << lookup << endl; } } } else { if(traceDebug()) { CLOG << "type keyword not found" << endl; } } return result; } void ossimImageSourceFactory::getTypeNameList(std::vector& typeList)const { typeList.push_back(STATIC_TYPE_NAME(ossimBandSelector)); typeList.push_back(STATIC_TYPE_NAME(ossimMultiThreadSequencer)); typeList.push_back(STATIC_TYPE_NAME(ossimImageRenderer)); typeList.push_back(STATIC_TYPE_NAME(ossimCacheTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimBlendMosaic)); typeList.push_back(STATIC_TYPE_NAME(ossimMaxMosaic)); typeList.push_back(STATIC_TYPE_NAME(ossimNullPixelFlip)); typeList.push_back(STATIC_TYPE_NAME(ossimElevRemapper)); typeList.push_back(STATIC_TYPE_NAME(ossimColorNormalizedFusion)); typeList.push_back(STATIC_TYPE_NAME(ossimLocalCorrelationFusion)); typeList.push_back(STATIC_TYPE_NAME(ossimSFIMFusion)); typeList.push_back(STATIC_TYPE_NAME(ossimHistogramRemapper)); typeList.push_back(STATIC_TYPE_NAME(ossimImageMosaic)); typeList.push_back(STATIC_TYPE_NAME(ossimElevationMosaic)); typeList.push_back(STATIC_TYPE_NAME(ossimClosestToCenterCombiner)); typeList.push_back(STATIC_TYPE_NAME(ossimRgbToGreyFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimNBandToIndexFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimImageChain)); typeList.push_back(STATIC_TYPE_NAME(ossimPolyCutter)); typeList.push_back(STATIC_TYPE_NAME(ossimGeoPolyCutter)); typeList.push_back(STATIC_TYPE_NAME(ossimJpegYCbCrToRgbSource)); typeList.push_back(STATIC_TYPE_NAME(ossimRgbToJpegYCbCrSource)); typeList.push_back(STATIC_TYPE_NAME(ossimHsiToRgbSource)); typeList.push_back(STATIC_TYPE_NAME(ossimRgbToHsiSource)); typeList.push_back(STATIC_TYPE_NAME(ossimHsvToRgbSource)); typeList.push_back(STATIC_TYPE_NAME(ossimRgbToHsvSource)); typeList.push_back(STATIC_TYPE_NAME(ossimHistogramEqualization)); typeList.push_back(STATIC_TYPE_NAME(ossimHistogramMatchFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimHistogramThreshholdFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimGeoAnnotationSource)); typeList.push_back(STATIC_TYPE_NAME(ossimConvolutionSource)); typeList.push_back(STATIC_TYPE_NAME(ossimSICDToDetectedImage)); typeList.push_back(STATIC_TYPE_NAME(ossimBrightnessContrastSource)); typeList.push_back(STATIC_TYPE_NAME(ossimBrightnessMatch)); typeList.push_back(STATIC_TYPE_NAME(ossimScalarRemapper)); typeList.push_back(STATIC_TYPE_NAME(ossimBandMergeSource)); typeList.push_back(STATIC_TYPE_NAME(ossimFeatherMosaic)); typeList.push_back(STATIC_TYPE_NAME(ossimGridRemapSource)); // Not sure if we want to keep this here typeList.push_back(STATIC_TYPE_NAME(ossimAtbController)); typeList.push_back(STATIC_TYPE_NAME(ossimIndexToRgbLutFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimBumpShadeTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimSubImageTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimRLevelFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimBandClipFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimHsiRemapper)); typeList.push_back(STATIC_TYPE_NAME(ossimHistogramWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimImageHistogramSource)); typeList.push_back(STATIC_TYPE_NAME(ossimRectangleCutFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimElevImageSource)); typeList.push_back(STATIC_TYPE_NAME(ossimValueAssignImageSourceFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimImageSharpenFilter)); typeList.push_back(STATIC_TYPE_NAME(ossim3x3ConvolutionFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimOrthoImageMosaic)); typeList.push_back(STATIC_TYPE_NAME(ossimPiecewiseRemapper)); typeList.push_back(STATIC_TYPE_NAME(ossimMapCompositionSource)); typeList.push_back(STATIC_TYPE_NAME(ossimCastTileSourceFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimEquationCombiner)); typeList.push_back(STATIC_TYPE_NAME(ossimConvolutionFilter1D)); typeList.push_back(STATIC_TYPE_NAME(ossimImageGaussianFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimMaskFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimMultiBandHistogramTileSource)); typeList.push_back(STATIC_TYPE_NAME(ossimBandAverageFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimPixelFlipper)); typeList.push_back(STATIC_TYPE_NAME(ossimScaleFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimImageToPlaneNormalFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimTopographicCorrectionFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimLandsatTopoCorrectionFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimAtCorrRemapper)); typeList.push_back(STATIC_TYPE_NAME(ossimAtCorrGridRemapper)); typeList.push_back(STATIC_TYPE_NAME(ossimEastingNorthingCutter)); typeList.push_back(STATIC_TYPE_NAME(ossimEdgeFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimFftFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimWatermarkFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimImageGaussianFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimTrimFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimTwoColorView)); typeList.push_back(STATIC_TYPE_NAME(ossimImageHistogramSource)); typeList.push_back(STATIC_TYPE_NAME(ossimImageSourceFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimMemoryImageSource)); typeList.push_back(STATIC_TYPE_NAME(ossimPiecewiseRemapper)); typeList.push_back(STATIC_TYPE_NAME(ossimImageSourceSequencer)); typeList.push_back(STATIC_TYPE_NAME(ossimDilationFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimErosionFilter)); typeList.push_back(STATIC_TYPE_NAME(ossimGammaRemapper)); } // Hide from use... ossimImageSourceFactory::ossimImageSourceFactory() :ossimImageSourceFactoryBase() {} ossimImageSourceFactory::ossimImageSourceFactory(const ossimImageSourceFactory&) :ossimImageSourceFactoryBase() {} const ossimImageSourceFactory& ossimImageSourceFactory::operator=(ossimImageSourceFactory&) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimImageSourceFactoryBase.cpp000066400000000000000000000027111352751253100242230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // //************************************************************************* // $Id: ossimImageSourceFactoryBase.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include ossimImageSourceFactoryBase::ossimImageSourceFactoryBase() : ossimObjectFactory() {} ossimImageSourceFactoryBase::ossimImageSourceFactoryBase(const ossimImageSourceFactoryBase&) : ossimObjectFactory() {} const ossimImageSourceFactoryBase& ossimImageSourceFactoryBase::operator=(const ossimImageSourceFactoryBase&) { return *this; } ossimImageSource* ossimImageSourceFactoryBase::createImageSource(const ossimString& name)const { ossimRefPtr result =createObject(name); if(PTR_CAST(ossimImageSource, result.get())) { return (ossimImageSource*)result.release(); } result = 0; return 0; } ossimImageSource* ossimImageSourceFactoryBase::createImageSource(const ossimKeywordlist& kwl, const char* prefix)const { ossimRefPtr result =createObject(kwl, prefix); if(PTR_CAST(ossimImageSource, result.get())) { return (ossimImageSource*)result.release(); } result = 0; return (ossimImageSource*)0; } ossim-Miami-2.9.1/src/imaging/ossimImageSourceFactoryRegistry.cpp000066400000000000000000000076071352751253100251720ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //************************************************************************* // $Id: ossimImageSourceFactoryRegistry.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include #include #include #include ossimImageSourceFactoryRegistry* ossimImageSourceFactoryRegistry::theInstance = NULL; RTTI_DEF1(ossimImageSourceFactoryRegistry, "ossimImageSourceFactoryRegistry", ossimImageSourceFactoryBase); ossimImageSourceFactoryRegistry::ossimImageSourceFactoryRegistry() { theInstance = this; } ossimImageSourceFactoryRegistry::~ossimImageSourceFactoryRegistry() { theInstance->unregisterFactory(ossimImageSourceFactory::instance()); theInstance = NULL; } ossimImageSourceFactoryRegistry* ossimImageSourceFactoryRegistry::instance() { if(theInstance == NULL) { theInstance = new ossimImageSourceFactoryRegistry; theInstance->registerFactory(ossimImageSourceFactory::instance()); theInstance->registerFactory(ossimImageReconstructionFilterRegistry::instance()); } return theInstance; } ossimObject* ossimImageSourceFactoryRegistry::createObject(const ossimString& name)const { ossimObject* result = NULL; std::vector::const_iterator factory; factory = theFactoryList.begin(); while((factory != theFactoryList.end()) && !result) { result = (*factory)->createObject(name); ++factory; } return result; } ossimObject* ossimImageSourceFactoryRegistry::createObject(const ossimKeywordlist& kwl, const char* prefix)const { ossimObject* result = NULL; std::vector::const_iterator factory; factory = theFactoryList.begin(); while((factory != theFactoryList.end()) && !result) { result = (*factory)->createObject(kwl, prefix); ++factory; } return result; } void ossimImageSourceFactoryRegistry::getTypeNameList(std::vector& typeList)const { std::vector result; std::vector::const_iterator iter = theFactoryList.begin(); while(iter != theFactoryList.end()) { result.clear(); (*iter)->getTypeNameList(result); // now append to the end of the typeList. typeList.insert(typeList.end(), result.begin(), result.end()); ++iter; } } void ossimImageSourceFactoryRegistry::registerFactory(ossimImageSourceFactoryBase* factory) { if(factory&&!findFactory(factory)) { theFactoryList.push_back(factory); } } void ossimImageSourceFactoryRegistry::unregisterFactory(ossimImageSourceFactoryBase* factory) { std::vector::iterator iter = std::find(theFactoryList.begin(), theFactoryList.end(), factory); if(iter != theFactoryList.end()) { theFactoryList.erase(iter); } } bool ossimImageSourceFactoryRegistry::findFactory(ossimImageSourceFactoryBase* factory)const { return (std::find(theFactoryList.begin(), theFactoryList.end(), factory)!=theFactoryList.end()); } void* ossimImageSourceFactoryRegistryGetInstance() { return ossimImageSourceFactoryRegistry::instance(); } // Hidden ossimImageSourceFactoryRegistry::ossimImageSourceFactoryRegistry(const ossimImageSourceFactoryRegistry&) : ossimImageSourceFactoryBase() {} // Hidden void ossimImageSourceFactoryRegistry::operator=(ossimImageSourceFactoryRegistry&) {} ossim-Miami-2.9.1/src/imaging/ossimImageSourceFilter.cpp000066400000000000000000000135711352751253100232540ustar00rootroot00000000000000 //******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id: ossimImageSourceFilter.cpp 18920 2011-02-18 20:06:11Z gpotts $ #include #include #include static ossimTrace traceDebug("ossimImageSourceFilter:debug"); RTTI_DEF2(ossimImageSourceFilter, "ossimImageSourceFilter", ossimImageSource, ossimConnectableObjectListener) ossimImageSourceFilter::ossimImageSourceFilter(ossimObject* owner) : ossimImageSource(owner, 1, // number of inputs 0, // number of outputs true, // input's fixed false), // outputs ar not fixed theInputConnection(NULL) { addListener((ossimConnectableObjectListener*)this); } ossimImageSourceFilter::ossimImageSourceFilter(ossimImageSource* inputSource) : ossimImageSource(NULL, 1, 0, true, false), theInputConnection(inputSource) { if(inputSource) { connectMyInputTo(0, inputSource); } addListener((ossimConnectableObjectListener*)this); } ossimImageSourceFilter::ossimImageSourceFilter(ossimObject* owner, ossimImageSource* inputSource) : ossimImageSource(owner, 1, 0, true, false), theInputConnection(inputSource) { if(inputSource) { theInputObjectList[0] = inputSource; inputSource->connectMyOutputTo(this, false); } addListener((ossimConnectableObjectListener*)this); } ossimImageSourceFilter::~ossimImageSourceFilter() { removeListener((ossimConnectableObjectListener*)this); theInputConnection = NULL; } ossim_uint32 ossimImageSourceFilter::getNumberOfInputBands()const { if(theInputConnection) { return theInputConnection->getNumberOfOutputBands(); } return 0; } void ossimImageSourceFilter::initialize() { theInputConnection = PTR_CAST(ossimImageSource, getInput(0)); } bool ossimImageSourceFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimImageSource::loadState(kwl, prefix); // make sure we have 1 input. //setNumberOfInputs(1); // we will fix the input //if(!theInputListIsFixedFlag) // { // theInputListIsFixedFlag = true; // } return result; } bool ossimImageSourceFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimImageSource::saveState(kwl, prefix); } bool ossimImageSourceFilter::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const { return ((PTR_CAST(ossimImageSource, object)||!object) && ( inputIndex == 0 ) ); } void ossimImageSourceFilter::connectInputEvent(ossimConnectionEvent& /* event */) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageSourceFilter::connectInputEvent: "; if(getInput()) { ossimNotify(ossimNotifyLevel_DEBUG) << "to" << getInput()->getClassName() << std::endl; } else { ossimNotify(ossimNotifyLevel_DEBUG) << "to NULL" << std::endl; } } theInputConnection = PTR_CAST(ossimImageSource, getInput(0)); initialize(); if(traceDebug()) { if(theInputConnection) { ossimNotify(ossimNotifyLevel_DEBUG) << "theInputConnection was set to " << getInput()->getClassName() << std::endl; } else { ossimNotify(ossimNotifyLevel_DEBUG) << "theInputConnection was set to NULL" << std::endl; } ossimNotify(ossimNotifyLevel_DEBUG) << "Leaving ossimImageSourceFilter::connectInput" << std::endl; } } void ossimImageSourceFilter::disconnectInputEvent(ossimConnectionEvent& /* event */) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageSourceFilter::disconnectInputEvent" << std::endl; } theInputConnection = PTR_CAST(ossimImageSource, getInput(0)); initialize(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Leaving ossimImageSourceFilter::disconnectInput" << std::endl; } } void ossimImageSourceFilter::propertyEvent(ossimPropertyEvent& /* event */) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageSourceFilter::propertyEvent DEBUG: Entering..." << std::endl; } initialize(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageSourceFilter::propertyEvent DEBUG: Leaving..." << std::endl; } } void ossimImageSourceFilter::refreshEvent(ossimRefreshEvent& /* event */) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageSourceFilter::refreshEvent " << std::endl; } initialize(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageSourceFilter::refreshEvent " << std::endl; } } void ossimImageSourceFilter::getOutputBandList(std::vector& bandList) const { if(theInputConnection) { return theInputConnection->getOutputBandList(bandList); } return ossimImageSource::getOutputBandList(bandList); } void ossimImageSourceFilter::setProperty(ossimRefPtr property) { ossimImageSource::setProperty(property); } ossimRefPtr ossimImageSourceFilter::getProperty(const ossimString& name)const { return ossimImageSource::getProperty(name); } void ossimImageSourceFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSource::getPropertyNames(propertyNames); } ossim-Miami-2.9.1/src/imaging/ossimImageSourceHistogramFilter.cpp000066400000000000000000000127001352751253100251230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimImageSourceHistogramFilter.cpp 13312 2008-07-27 01:26:52Z gpotts $ #include #include #include #include #include #include #include #include #include using namespace std; static const ossimKeyword PROPRIETARY_FILENAME_KW("proprietary_filename", "imports a proprietary file"); static const ossimKeyword HISTOGRAM_FILENAME_KW("histogram_filename", "read an OSSIM histogram file"); RTTI_DEF1(ossimImageSourceHistogramFilter, "ossimImageSourceHistogramFilter", ossimImageSourceFilter) ossimImageSourceHistogramFilter::ossimImageSourceHistogramFilter() :ossimImageSourceFilter(), theCurrentResLevel(0), theHistogram(NULL), theFilename("") { setNumberOfInputs(2); theInputListIsFixedFlag = true; } ossimImageSourceHistogramFilter::ossimImageSourceHistogramFilter(ossimImageSource* inputSource, ossimRefPtr histogram) : ossimImageSourceFilter(inputSource), theCurrentResLevel(0), theHistogram(histogram), theFilename("") { setNumberOfInputs(2); theInputListIsFixedFlag = true; } ossimImageSourceHistogramFilter::~ossimImageSourceHistogramFilter() { } void ossimImageSourceHistogramFilter::setHistogram(ossimRefPtr histogram) { theHistogram = histogram; if(theHistogram.valid()) { theHistogram->setBinCount(0, 0); } } bool ossimImageSourceHistogramFilter::setHistogram(const ossimFilename& filename) { ossimRefPtr histogram = new ossimMultiResLevelHistogram; bool result = histogram->importHistogram(filename); if(result) { theFilename = filename; setHistogram(histogram); } return result; } ossimRefPtr ossimImageSourceHistogramFilter::getHistogram() { if(!getInput(1)) { return theHistogram; } else { ossimHistogramSource* histoSource = PTR_CAST(ossimHistogramSource, getInput(1)); if(histoSource) { return histoSource->getHistogram(); } } return (ossimMultiResLevelHistogram*)0; } const ossimRefPtr ossimImageSourceHistogramFilter::getHistogram()const { if(!getInput(1)) { return theHistogram; } else { ossimHistogramSource* histoSource = PTR_CAST(ossimHistogramSource, getInput(1)); if(histoSource) { return histoSource->getHistogram(); } } return (ossimMultiResLevelHistogram*)0; } bool ossimImageSourceHistogramFilter::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const { if(object) { if(PTR_CAST(ossimImageSource, object) && ( inputIndex == 0 )) { return true; } else if(PTR_CAST(ossimHistogramSource, object) && ( inputIndex == 1 )) { return true; } } return false; } void ossimImageSourceHistogramFilter::connectInputEvent(ossimConnectionEvent& event) { theInputConnection = PTR_CAST(ossimImageSource, getInput(0)); if(PTR_CAST(ossimHistogramSource, event.getNewObject())) { // only initialize if it's a new object initialize(); } } bool ossimImageSourceHistogramFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimImageSourceFilter::saveState(kwl, prefix); kwl.add(prefix, HISTOGRAM_FILENAME_KW, theFilename, true); return result; } bool ossimImageSourceHistogramFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* proprietaryName = kwl.find(prefix, PROPRIETARY_FILENAME_KW); const char* ossimName = kwl.find(prefix, HISTOGRAM_FILENAME_KW); bool result = true; ossimFilename file; if(proprietaryName) { theFilename = ossimFilename(proprietaryName); } else if(ossimName) { if(!theHistogram) { theHistogram = new ossimMultiResLevelHistogram; } theFilename = ossimFilename(ossimName); } if(theFilename.exists()&&(theFilename!="")) { if(!theHistogram) { theHistogram = new ossimMultiResLevelHistogram; } result = theHistogram->importHistogram(theFilename); } if(theHistogram.valid()) { theHistogram->setBinCount(0, 0); } result = ossimImageSourceFilter::loadState(kwl, prefix); setNumberOfInputs(2); theInputListIsFixedFlag = true; return result; } std::ostream& ossimImageSourceHistogramFilter::print(std::ostream& out) const { out << "ossimImageSourceHistogramFilter::print:\n" << "theFilename: " << endl; return ossimImageSourceFilter::print(out); } ossim-Miami-2.9.1/src/imaging/ossimImageSourceSequencer.cpp000066400000000000000000000413641352751253100237620ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF2(ossimImageSourceSequencer, "ossimImageSourceSequencer", ossimImageSource, ossimConnectableObjectListener); static ossimTrace traceDebug("ossimImageSourceSequencer:debug"); ossimImageSourceSequencer::ossimImageSourceSequencer(ossimImageSource* inputSource, ossimObject* owner) :ossimImageSource(owner, 1, 1, true, false), theBlankTile(NULL), theAreaOfInterest(0,0,0,0), theTileSize(OSSIM_DEFAULT_TILE_WIDTH, OSSIM_DEFAULT_TILE_HEIGHT), theNumberOfTilesHorizontal(0), theNumberOfTilesVertical(0), theCurrentTileNumber(0), theCreateHistogram(false) { ossim::defaultTileSize(theTileSize); theAreaOfInterest.makeNan(); theInputConnection = inputSource; if(inputSource) { connectMyInputTo(0, inputSource); initialize(); // Derived class depends on this initialization to happen now. DO NOT MOVE. } addListener( (ossimConnectableObjectListener*)this); } ossimImageSourceSequencer::~ossimImageSourceSequencer() { removeListener((ossimConnectableObjectListener*)this); } ossim_int64 ossimImageSourceSequencer::getNumberOfTiles()const { return (theNumberOfTilesHorizontal*theNumberOfTilesVertical); } ossim_int64 ossimImageSourceSequencer::getNumberOfTilesHorizontal()const { return theNumberOfTilesHorizontal; } ossim_int64 ossimImageSourceSequencer::getNumberOfTilesVertical()const { return theNumberOfTilesVertical; } ossimScalarType ossimImageSourceSequencer::getOutputScalarType() const { if(theInputConnection) { return theInputConnection->getOutputScalarType(); } return OSSIM_SCALAR_UNKNOWN; } ossimIpt ossimImageSourceSequencer::getTileSize()const { return theTileSize; } void ossimImageSourceSequencer::setTileSize(const ossimIpt& tileSize) { theTileSize = tileSize; updateTileDimensions(); // initialize(); } void ossimImageSourceSequencer::setTileSize(ossim_int32 width, ossim_int32 height) { setTileSize(ossimIpt(width, height)); } void ossimImageSourceSequencer::updateTileDimensions() { bool status = false; if( !theAreaOfInterest.hasNans() && !theTileSize.hasNans() ) { ossim_float64 aoiWidth = theAreaOfInterest.width(); ossim_float64 aoiHeight = theAreaOfInterest.height(); ossim_float64 tileWidth = theTileSize.x; ossim_float64 tileHeight = theTileSize.y; if ( (aoiWidth > 0.0) && (aoiHeight > 0.0) && (tileWidth > 0.0) && (tileHeight > 0.0) ) { theNumberOfTilesHorizontal = static_cast(std::ceil(aoiWidth/tileWidth)); theNumberOfTilesVertical = static_cast(std::ceil(aoiHeight/tileHeight)); status = true; } } if ( !status ) { theNumberOfTilesHorizontal = 0; theNumberOfTilesVertical = 0; } } void ossimImageSourceSequencer::initialize() { theInputConnection = PTR_CAST(ossimImageSource, getInput(0)); if(theInputConnection) { if(theTileSize.hasNans()) { theTileSize.x = theInputConnection->getTileWidth(); theTileSize.y = theInputConnection->getTileHeight(); } ossimDrect rect = theInputConnection->getBoundingRect(); if(rect.hasNans()) { theAreaOfInterest.makeNan(); } else { rect.stretchOut(); setAreaOfInterest(rect); } updateTileDimensions(); theBlankTile = ossimImageDataFactory::instance()->create(this, this); if(theBlankTile.valid()) { theBlankTile->initialize(); } } } bool ossimImageSourceSequencer::canConnectMyInputTo(ossim_int32 /* inputIndex */, const ossimConnectableObject* object)const { return (object&& PTR_CAST(ossimImageSource, object)); } void ossimImageSourceSequencer::connectInputEvent(ossimConnectionEvent& /* event */) { initialize(); } void ossimImageSourceSequencer::disconnectInputEvent(ossimConnectionEvent& /* event */) { theInputConnection = PTR_CAST(ossimImageSource, getInput(0)); } ossimIrect ossimImageSourceSequencer::getBoundingRect(ossim_uint32 resLevel)const { ossimDrect temp; temp.makeNan(); if(!theInputConnection) return temp; if(theAreaOfInterest.hasNans()) { return theInputConnection->getBoundingRect(resLevel); } return theAreaOfInterest; } void ossimImageSourceSequencer::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { if(theInputConnection) { theInputConnection->getDecimationFactor(resLevel, result); } result.makeNan(); } void ossimImageSourceSequencer::getDecimationFactors(vector& decimations) const { if(theInputConnection) { theInputConnection->getDecimationFactors(decimations); } } ossim_uint32 ossimImageSourceSequencer::getNumberOfDecimationLevels()const { ossim_uint32 result = 0; if(theInputConnection) { result = theInputConnection->getNumberOfDecimationLevels(); } return result; } void ossimImageSourceSequencer::setAreaOfInterest(const ossimIrect& areaOfInterest) { if(areaOfInterest.hasNans()) { theAreaOfInterest.makeNan(); theNumberOfTilesHorizontal = 0; theNumberOfTilesVertical = 0; } // let's round it to the nearest pixel value before setting it. theAreaOfInterest = areaOfInterest; updateTileDimensions(); } const ossimIrect& ossimImageSourceSequencer::getAreaOfInterest()const { return theAreaOfInterest; } void ossimImageSourceSequencer::setToStartOfSequence() { theCurrentTileNumber = 0; } ossimRefPtr ossimImageSourceSequencer::getTile( const ossimIrect& rect, ossim_uint32 /* resLevel */ ) { if(theInputConnection) { /* ossimRefPtr tile = theInputConnection->getTile(rect, resLevel); if (tile.valid()&&tile->getBuf()) { return tile; } else { // We should return a valid tile for the writers. theBlankTile->setImageRectangle(rect); return theBlankTile; } */ // For Use with multithreaded sequencer ossimRefPtr tile = ossimImageDataFactory::instance()->create(this, this); tile->setImageRectangle(rect); tile->initialize(); tile->makeBlank(); setToStartOfSequence(); ossim_uint32 num_tiles = getNumberOfTiles(); // bool hasHistoOutput = true; ossim_uint32 numberOfBands = 1; ossim_uint32 numberOfBins = 0; ossim_float32 minValue = 0; ossim_float32 maxValue = 0; ossim_float32 nullValue = 0; ossimRefPtr histogram = 0; if (theCreateHistogram) { // ossimScalarType stype = tile->getScalarType(); histogram = new ossimMultiResLevelHistogram; histogram->create(1); numberOfBands = tile->getNumberOfBands(); if ( ossim::getBinInformation(theInputConnection, 0, numberOfBins, minValue, maxValue, nullValue) ) { histogram->getMultiBandHistogram(0)->create( numberOfBands, numberOfBins, minValue, maxValue, nullValue, theInputConnection->getOutputScalarType() ); } } for (ossim_uint32 tile_idx=0; tile_idx imagedata = getNextTile(); //tile->setDataObjectStatus(imagedata->getDataObjectStatus()); if(imagedata->getBuf() && (imagedata->getDataObjectStatus()!=OSSIM_EMPTY)) { tile->loadTile(imagedata.get()); if (theCreateHistogram) { ossimIrect tileRect = tile->getImageRectangle(); ossimIrect clipRect = tileRect.clipToRect( theAreaOfInterest ); imagedata->populateHistogram( histogram->getMultiBandHistogram(0), clipRect); } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN)<< "BASE SEQUENCER TILE " << tile_idx << " RECT: " << rect << std::endl;; } } tile->validate(); if (theCreateHistogram) tile->setHistogram(histogram); return tile; } return 0; } ossimRefPtr ossimImageSourceSequencer::getNextTile( ossim_uint32 resLevel ) { ossimRefPtr result = 0; if ( theInputConnection ) { ossimIrect tileRect; if ( getTileRect( theCurrentTileNumber, tileRect ) ) { ++theCurrentTileNumber; result = theInputConnection->getTile(tileRect, resLevel); if( !result.valid() || !result->getBuf() ) { theBlankTile->setImageRectangle(tileRect); result = theBlankTile; } } } return result; } bool ossimImageSourceSequencer::getNextTileStream(std::ostream& /* bos */) { return false; } ossimRefPtr ossimImageSourceSequencer::getTile( ossim_int64 id, ossim_uint32 resLevel) { static const char* MODULE= "ossimImageSourceSequencer::getTile(id, resLevel)"; if(traceDebug()) { CLOG << "entering.."< result = 0; if(theInputConnection) { // if we have no tiles try to initialize. if(getNumberOfTiles() == 0) { initialize(); } ossimIrect tileRect; if ( getTileRect( id, tileRect ) ) { result = theInputConnection->getTile(tileRect, resLevel); if( !result.valid() || !result->getBuf() ) { theBlankTile->setImageRectangle(tileRect); result = theBlankTile; } } else // getTileRect failed... { if(traceDebug()) { CLOG << "was not able to get an origin for id = " << id << endl; } } } else // no connection... { if(traceDebug()) { CLOG << "No input connection so returning NULL" << endl; } } if(traceDebug()) { CLOG << "leaving.."<= 0 ) { if( (theNumberOfTilesHorizontal > 0) && (theCurrentTileNumber < getNumberOfTiles()) ) { ossim_int64 y = id / theNumberOfTilesHorizontal; ossim_int64 x = id % theNumberOfTilesHorizontal; if( (x < theNumberOfTilesHorizontal) && (y < theNumberOfTilesVertical) ) { ossim_int64 ulx = theAreaOfInterest.ul().x; ossim_int64 uly = theAreaOfInterest.ul().y; ossim_int64 tx = theTileSize.x; ossim_int64 ty = theTileSize.y; x = ulx + x * tx; y = uly + y * ty; //--- // ossimIpt currently signed 32 bit so make sure we didn't bust the // bounds. //--- if ( (x <= OSSIM_DEFAULT_MAX_PIX_SINT32) && ( y <= OSSIM_DEFAULT_MAX_PIX_SINT32) ) { origin.x = (ossim_int32)x; origin.y = (ossim_int32)y; result = true; } } } } return result; } bool ossimImageSourceSequencer::getTileRect(ossim_int64 tile_id, ossimIrect& tileRect) const { // Fetch tile origin for this tile: ossimIpt origin; bool result = getTileOrigin(tile_id, origin); if ( result ) { // Establish the tile rect of interest for this tile: tileRect.set_ul (origin); tileRect.set_lrx(origin.x + theTileSize.x - 1); tileRect.set_lry(origin.y + theTileSize.y - 1); } return result; } double ossimImageSourceSequencer::getNullPixelValue(ossim_uint32 band)const { if (theInputConnection) { return theInputConnection->getNullPixelValue(band); } return ossimImageSource::getNullPixelValue(band); } double ossimImageSourceSequencer::getMinPixelValue(ossim_uint32 band)const { if (theInputConnection) { return theInputConnection->getMinPixelValue(band); } return ossimImageSource::getMinPixelValue(band); } double ossimImageSourceSequencer::getMaxPixelValue(ossim_uint32 band)const { if (theInputConnection) { return theInputConnection->getMaxPixelValue(band); } return ossimImageSource::getMaxPixelValue(band); } ossim_uint32 ossimImageSourceSequencer::getNumberOfInputBands()const { if(theInputConnection) { return theInputConnection->getNumberOfOutputBands(); } return 0; } ossim_uint32 ossimImageSourceSequencer::getTileWidth() const { return theTileSize.x; } ossim_uint32 ossimImageSourceSequencer::getTileHeight()const { return theTileSize.y; } void ossimImageSourceSequencer::slaveProcessTiles() { } bool ossimImageSourceSequencer::isMaster() const { return true; } void ossimImageSourceSequencer::getBinInformation(ossim_uint32& numberOfBins, ossim_float64& minValue, ossim_float64& maxValue, ossimScalarType stype)const { numberOfBins = 0; minValue = 0; maxValue = 0; switch(stype) { case OSSIM_UINT8: { minValue = 0; maxValue = OSSIM_DEFAULT_MAX_PIX_UCHAR; numberOfBins = 256; break; } case OSSIM_USHORT11: { minValue = 0; maxValue = OSSIM_DEFAULT_MAX_PIX_UINT11; numberOfBins = OSSIM_DEFAULT_MAX_PIX_UINT11 + 1; break; } case OSSIM_USHORT12: { minValue = 0; maxValue = OSSIM_DEFAULT_MAX_PIX_UINT12; numberOfBins = OSSIM_DEFAULT_MAX_PIX_UINT12 + 1; break; } case OSSIM_USHORT13: { minValue = 0; maxValue = OSSIM_DEFAULT_MAX_PIX_UINT13; numberOfBins = OSSIM_DEFAULT_MAX_PIX_UINT13 + 1; break; } case OSSIM_USHORT14: { minValue = 0; maxValue = OSSIM_DEFAULT_MAX_PIX_UINT14; numberOfBins = OSSIM_DEFAULT_MAX_PIX_UINT14 + 1; break; } case OSSIM_USHORT15: { minValue = 0; maxValue = OSSIM_DEFAULT_MAX_PIX_UINT15; numberOfBins = OSSIM_DEFAULT_MAX_PIX_UINT15 + 1; break; } case OSSIM_UINT16: case OSSIM_UINT32: { minValue = 0; maxValue = OSSIM_DEFAULT_MAX_PIX_UINT16; numberOfBins = OSSIM_DEFAULT_MAX_PIX_UINT16 + 1; break; } case OSSIM_SINT16: case OSSIM_SINT32: case OSSIM_FLOAT32: case OSSIM_FLOAT64: { minValue = OSSIM_DEFAULT_MIN_PIX_SINT16; maxValue = OSSIM_DEFAULT_MAX_PIX_SINT16; numberOfBins = (OSSIM_DEFAULT_MAX_PIX_SINT16-OSSIM_DEFAULT_MIN_PIX_SINT16) + 1; break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_NORMALIZED_DOUBLE: { minValue = 0; maxValue = 1.0; numberOfBins = OSSIM_DEFAULT_MAX_PIX_UINT16+1; break; } default: { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Unsupported scalar type in ossimImageHistogramSource::computeHistogram()" << endl; } return; } } } bool ossimImageSourceSequencer::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup; lookup = kwl.find(prefix, "create_histogram"); if(lookup) { bool create_histogram = ossimString(lookup).toBool(); setCreateHistogram(create_histogram); } bool status = ossimImageSource::loadState(kwl, prefix); return status; } void ossimImageSourceSequencer::setCreateHistogram(bool create_histogram) { theCreateHistogram = create_histogram; } ossim-Miami-2.9.1/src/imaging/ossimImageStatisticsSource.cpp000066400000000000000000000116671352751253100241650ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* #include #include #include #include ossimImageStatisticsSource::ossimImageStatisticsSource() :ossimSource(0, 1, 0, true, false) { } ossimImageStatisticsSource::~ossimImageStatisticsSource() { } void ossimImageStatisticsSource::computeStatistics() { ossimImageSource* anInterface = PTR_CAST(ossimImageSource, getInput()); if(anInterface&&isSourceEnabled()) { clearStatistics(); ossimScalarType outputScalarType = anInterface->getOutputScalarType(); switch(outputScalarType) { case OSSIM_UCHAR: { computeStatisticsTemplate((ossim_uint8)0); break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { computeStatisticsTemplate((ossim_uint16)0); break; } case OSSIM_SSHORT16: { computeStatisticsTemplate((ossim_sint16)0); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { computeStatisticsTemplate((ossim_float64)0); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { computeStatisticsTemplate((ossim_float32)0); break; } default : { break; } } } } bool ossimImageStatisticsSource::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const { return (PTR_CAST(ossimImageSource, object)&&(inputIndex < 1)); } template void ossimImageStatisticsSource::computeStatisticsTemplate(T /* dummyVariable */) { ossimRefPtr sequencer = new ossimImageSourceSequencer; sequencer->connectMyInputTo(getInput()); sequencer->setToStartOfSequence(); ossim_uint32 bands = sequencer->getNumberOfOutputBands(); if(bands) { setStatsSize(bands); ossimRefPtr dataObject; while( (dataObject=sequencer->getNextTile()).valid() ) { ossim_uint32 bandIdx = 0; bands = dataObject->getNumberOfBands(); ossimDataObjectStatus status = dataObject->getDataObjectStatus(); if((status != OSSIM_EMPTY)&& (dataObject->getBuf())) { ossim_uint32 offsetMax = dataObject->getWidth()*dataObject->getHeight(); for(bandIdx = 0; bandIdx < bands; ++bandIdx) { ossim_float64 pixelCount = 0.0; ossim_uint32 offset = 0; T* dataPtr = static_cast(dataObject->getBuf(bandIdx)); T nullPixel = static_cast(dataObject->getNullPix(bandIdx)); for(offset = 0; offset < offsetMax; ++offset) { if((*dataPtr) != nullPixel) { theMean[bandIdx] += *dataPtr; if((*dataPtr) < theMin[bandIdx]) { theMin[bandIdx] = (*dataPtr); } if((*dataPtr) > theMax[bandIdx]) { theMax[bandIdx] = (*dataPtr); } ++pixelCount; } ++dataPtr; } if(pixelCount > 0) { theMean[bandIdx] /= pixelCount; } } } } } sequencer->disconnect(); sequencer = 0; } const std::vector& ossimImageStatisticsSource::getMean()const { return theMean; } const std::vector& ossimImageStatisticsSource::getMin()const { return theMin; } const std::vector& ossimImageStatisticsSource::getMax()const { return theMax; } void ossimImageStatisticsSource::clearStatistics() { theMean.clear(); theMin.clear(); theMax.clear(); } void ossimImageStatisticsSource::setStatsSize(ossim_uint32 size) { theMean.resize(size); theMin.resize(size); theMax.resize(size); std::fill(theMean.begin(), theMean.end(), (ossim_float64)0.0); std::fill(theMin.begin(), theMin.end(), OSSIM_DEFAULT_MAX_PIX_DOUBLE); std::fill(theMax.begin(), theMax.end(), (ossim_float64)OSSIM_DEFAULT_MIN_PIX_DOUBLE); } ossim-Miami-2.9.1/src/imaging/ossimImageToPlaneNormalFilter.cpp000066400000000000000000000325331352751253100245260ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageToPlaneNormalFilter.cpp 23451 2015-07-27 15:42:17Z okramer $ #include #include #include #include #include #include #include #include static const char* SMOOTHNESS_FACTOR_KW="smoothness_factor"; RTTI_DEF1(ossimImageToPlaneNormalFilter, "ossimImageToPlaneNormalFilter", ossimImageSourceFilter); ossimImageToPlaneNormalFilter::ossimImageToPlaneNormalFilter() :ossimImageSourceFilter(), theTile(NULL), theBlankTile(NULL), theTrackScaleFlag(true), theXScale(1.0), theYScale(1.0), theSmoothnessFactor(1.0) { } ossimImageToPlaneNormalFilter::ossimImageToPlaneNormalFilter(ossimImageSource* inputSource) :ossimImageSourceFilter(inputSource), theTile(NULL), theBlankTile(NULL), theTrackScaleFlag(true), theXScale(1.0), theYScale(1.0), theSmoothnessFactor(1.0) { } ossimRefPtr ossimImageToPlaneNormalFilter::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!isSourceEnabled()||!theInputConnection) { return ossimImageSourceFilter::getTile(tileRect, resLevel); } if(!theTile.valid()) { initialize(); } if(!theTile.valid()) { return ossimImageSourceFilter::getTile(tileRect, resLevel); } theTile->setImageRectangle(tileRect); ossimIrect requestRect(tileRect.ul().x - 1, tileRect.ul().y - 1, tileRect.lr().x + 1, tileRect.lr().y + 1); ossimRefPtr input = theInputConnection->getTile(requestRect, resLevel); if(!input||(input->getDataObjectStatus()==OSSIM_EMPTY)||!input->getBuf()) { if(tileRect.completely_within(theInputBounds)) { initializeTile(); theTile->validate(); return theTile.get(); } theBlankTile->setImageRectangle(tileRect); return theBlankTile; } double oldScaleX = theXScale; double oldScaleY = theYScale; if(resLevel > 0) { ossimDpt scaleFactor; theInputConnection->getDecimationFactor(resLevel, scaleFactor); if(!scaleFactor.hasNans()) { theXScale *= scaleFactor.x; theYScale *= scaleFactor.y; } } computeNormals(input, theTile); theXScale = oldScaleX; theYScale = oldScaleY; theTile->validate(); return theTile; } void ossimImageToPlaneNormalFilter::initializeTile() { double* x = static_cast(theTile->getBuf(0)); double* y = static_cast(theTile->getBuf(1)); double* z = static_cast(theTile->getBuf(2)); if(x) std::fill(x, x+theTile->getSizePerBand(), 0.0); if(y) std::fill(y, y+theTile->getSizePerBand(), 0.0); if(z) std::fill(z, z+theTile->getSizePerBand(), 1.0); } void ossimImageToPlaneNormalFilter::initialize() { if(theInputConnection) { theInputConnection->initialize(); theInputBounds = theInputConnection->getBoundingRect(); theTile = ossimImageDataFactory::instance()->create(this, this); theBlankTile = (ossimImageData*)(theTile->dup()); theTile->initialize(); if(theTrackScaleFlag) { ossimRefPtr geom = theInputConnection->getImageGeometry(); if( geom.valid() ) { ossimDpt pt = geom->getMetersPerPixel(); if(!pt.hasNans()) { theXScale = 1.0/pt.x; theYScale = 1.0/pt.y; } } } } } void ossimImageToPlaneNormalFilter::computeNormals( ossimRefPtr& inputTile, ossimRefPtr& outputTile) { switch(inputTile->getScalarType()) { case OSSIM_SSHORT16: { computeNormalsTemplate((ossim_sint16)0, inputTile, outputTile); break; } case OSSIM_UCHAR: { computeNormalsTemplate((ossim_uint8)0, inputTile, outputTile); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { computeNormalsTemplate((ossim_uint16)0, inputTile, outputTile); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_DOUBLE: { computeNormalsTemplate((ossim_float64)0, inputTile, outputTile); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT: { computeNormalsTemplate((ossim_float32)0, inputTile, outputTile); break; } default: break; } } template void ossimImageToPlaneNormalFilter::computeNormalsTemplate( T /* inputScalarTypeDummy */, ossimRefPtr& inputTile, ossimRefPtr& outputTile) { T inputNull = (T) inputTile->getNullPix(0); T* inbuf = (T*) inputTile->getBuf(); T outputNull = (T) outputTile->getNullPix(0); double* normX = (double*)outputTile->getBuf(0); double* normY = (double*)outputTile->getBuf(1); double* normZ = (double*)outputTile->getBuf(2); ossim_int32 inbuf_width = inputTile->getWidth(); ossim_int32 normbuf_width = outputTile->getWidth(); ossim_int32 normbuf_height = outputTile->getHeight(); ossimColumnVector3d normal; bool valid_component = true; for (ossim_int32 y=0; y property) { ossimString name = property->getName(); if((name == "smoothnessFactor")|| (name == "gain")) { theSmoothnessFactor = property->valueToString().toDouble(); initialize(); } else if(name == "xscale") { theXScale = property->valueToString().toDouble(); initialize(); } else if(name == "yscale") { theYScale = property->valueToString().toDouble(); initialize(); } else if(name == "autoTrackScaleFlag") { theTrackScaleFlag = property->valueToString().toDouble(); initialize(); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimImageToPlaneNormalFilter::getProperty(const ossimString& name)const { if((name == "smoothnessFactor")|| (name == "gain")) { ossimNumericProperty* prop = new ossimNumericProperty("gain", ossimString::toString(theSmoothnessFactor), .0001, 40); prop->setCacheRefreshBit(); return prop; } else if(name == "xscale") { ossimNumericProperty* prop = new ossimNumericProperty(name, ossimString::toString(theXScale), .0001, 50000); prop->setCacheRefreshBit(); return prop; } else if(name == "yscale") { ossimNumericProperty* prop = new ossimNumericProperty(name, ossimString::toString(theYScale), .0001, 50000); prop->setCacheRefreshBit(); return prop; } else if(name == "autoTrackScaleFlag") { ossimBooleanProperty* prop = new ossimBooleanProperty(name, theTrackScaleFlag); prop->setCacheRefreshBit(); return prop; } return ossimImageSourceFilter::getProperty(name); } void ossimImageToPlaneNormalFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("gain"); propertyNames.push_back("xscale"); propertyNames.push_back("yscale"); propertyNames.push_back("autoTrackScaleFlag"); } ossim-Miami-2.9.1/src/imaging/ossimImageWriter.cpp000066400000000000000000000043371352751253100221220ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Frank Warmerdam (warmerdam@pobox.com) // // Description: // // Contains class declaration for ossimImageWriter. //******************************************************************* // $Id: ossimImageWriter.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include #include #include #include #include RTTI_DEF1(ossimImageWriter, "ossimImageWriter", ossimOutputSource); ossimImageWriter::ossimImageWriter(ossimObject* owner) : ossimOutputSource(owner, 1, 0, true, true) { theAreaOfInterest.makeNan(); } ossimImageWriter::ossimImageWriter(ossimObject* owner, ossim_uint32 numberOfInputs, ossim_uint32 numberOfOutputs, bool inputListIsFixed, bool outputListIsFixed) :ossimOutputSource(owner, numberOfInputs, numberOfOutputs, inputListIsFixed, outputListIsFixed) { theAreaOfInterest.makeNan(); } ossimImageWriter::~ossimImageWriter() { } bool ossimImageWriter::setViewingRect(const ossimIrect &aRect) { setAreaOfInterest(aRect); return true; } ossimIrect ossimImageWriter::getAreaOfInterest() const { return theAreaOfInterest; } void ossimImageWriter::setAreaOfInterest(const ossimIrect& inputAreaOfInterest) { theAreaOfInterest = inputAreaOfInterest; } bool ossimImageWriter::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimOutputSource::saveState(kwl, prefix); } bool ossimImageWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimOutputSource::loadState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimImageWriterFactory.cpp000066400000000000000000000244041352751253100234470ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include ossimImageWriterFactory* ossimImageWriterFactory::theInstance = (ossimImageWriterFactory*)NULL; ossimImageWriterFactory* ossimImageWriterFactory::instance() { if(!theInstance) { theInstance = new ossimImageWriterFactory; ossimImageWriterFactoryRegistry::instance()->registerFactory(theInstance); } return theInstance; } ossimImageWriterFactory::~ossimImageWriterFactory() { theInstance = (ossimImageWriterFactory*)NULL; } ossimImageFileWriter *ossimImageWriterFactory::createWriterFromExtension( const ossimString& fileExtension)const { ossimImageFileWriter* result = 0; ossimString ext = fileExtension; ext.downcase(); if( (ext == "tif")|| (ext == "tiff") ) { result = new ossimTiffWriter; } else if( (ext == "jpg")|| (ext == "jpeg") ) { result = new ossimJpegWriter; } else if( (ext == "ras") || (ext == "bsq") ) { // Default is OSSIM_GENERAL_RASTER_BSQ result = new ossimGeneralRasterWriter; } else if(ext == "bil") { result = new ossimGeneralRasterWriter; result->setOutputImageType(OSSIM_GENERAL_RASTER_BIL); } else if(ext == "bip") { result = new ossimGeneralRasterWriter; result->setOutputImageType(OSSIM_GENERAL_RASTER_BIP); } else if((ext == "ntf")|| (ext == "nitf")) { result = new ossimNitfWriter; } else if( ext == "pdf" ) { result = new ossimPdfWriter; } return result; } ossimImageFileWriter* ossimImageWriterFactory::createWriter(const ossimKeywordlist& kwl, const char *prefix)const { ossimString type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); ossimImageFileWriter* result = (ossimImageFileWriter*)NULL; if(type != "") { result = createWriter(type); if (result) { if (result->hasImageType(type)) { ossimKeywordlist kwl2(kwl); kwl2.add(prefix, ossimKeywordNames::IMAGE_TYPE_KW, type, true); result->loadState(kwl2, prefix); } else { result->loadState(kwl, prefix); } } } return result; } ossimImageFileWriter* ossimImageWriterFactory::createWriter(const ossimString& typeName)const { ossimString mimeType = typeName; mimeType = mimeType.downcase(); // Check for tiff writer. ossimRefPtr writer = createFromMimeType(mimeType); if(writer.valid()) { return writer.release(); } // Check for generic ossim writer. writer = new ossimWriter; if ( writer->getClassName() == typeName ) { return writer.release(); } else { // See if the type name is supported by the writer. if ( writer->hasImageType(typeName) ) { writer->setOutputImageType(typeName); return writer.release(); } } writer = new ossimTiffWriter; if (STATIC_TYPE_NAME(ossimTiffWriter) == typeName ) { return writer.release(); } else { // See if the type name is supported by the writer. if ( writer->hasImageType(typeName) ) { writer->setOutputImageType(typeName); return writer.release(); } } // Check for jpeg writer. writer = new ossimJpegWriter; if ( writer->getClassName() == typeName ) { return writer.release(); } else { // See if the type name is supported by the writer. if ( writer->hasImageType(typeName) ) { writer->setOutputImageType(typeName); return writer.release(); } } // Check for general raster writer. writer = new ossimGeneralRasterWriter; if ( writer->getClassName() == typeName ) { return writer.release(); } else { // See if the type name is supported by the writer. if ( writer->hasImageType(typeName) ) { writer->setOutputImageType(typeName); return writer.release(); } } // Check for nitf writer. writer = new ossimNitfWriter; if ( writer->getClassName() == typeName ) { return writer.release(); } else { // See if the type name is supported by the writer. if ( writer->hasImageType(typeName) ) { writer->setOutputImageType(typeName); return writer.release(); } } // Check for nitf writer. writer = new ossimNitf20Writer; if ( writer->getClassName() == typeName ) { return writer.release(); } else { // See if the type name is supported by the writer. if ( writer->hasImageType(typeName) ) { writer->setOutputImageType(typeName); return writer.release(); } } // Check for pdf writer. writer = new ossimPdfWriter; if ( writer->getClassName() == typeName ) { return writer.release(); } else { // See if the type name is supported by the writer. if ( writer->hasImageType(typeName) ) { writer->setOutputImageType(typeName); return writer.release(); } } writer = 0; // Not a nitf writer. return writer.release(); // Return a null writer. } ossimImageFileWriter* ossimImageWriterFactory::createFromMimeType( const ossimString& mimeType)const { if((mimeType == "image/jpeg")|| (mimeType == "image/jpg")) { ossimJpegWriter* writer = new ossimJpegWriter; writer->setOutputImageType("jpeg"); return writer; } else if((mimeType == "image/tiff")|| (mimeType == "image/tif")|| (mimeType == "image/gtif")|| (mimeType == "image/gtiff")) { ossimTiffWriter* writer = new ossimTiffWriter; writer->setOutputImageType("tiff_tiled_band_separate"); return writer; } else if((mimeType == "image/nitf") || (mimeType == "image/ntf")) { ossimNitfWriter* writer = new ossimNitfWriter; writer->setOutputImageType("nitf_block_band_separate"); return writer; } else if((mimeType == "image/ras")) { ossimGeneralRasterWriter* writer = new ossimGeneralRasterWriter; writer->setOutputImageType("general_raster_bsq"); return writer; } else if((mimeType == "application/pdf")|| (mimeType == "image/pdf")) { ossimPdfWriter* writer = new ossimPdfWriter; writer->setOutputImageType("ossim_pdf"); return writer; } return 0; } ossimObject* ossimImageWriterFactory::createObject(const ossimKeywordlist& kwl, const char *prefix)const { return createWriter(kwl, prefix); } ossimObject* ossimImageWriterFactory::createObject(const ossimString& typeName)const { return createWriter(typeName); } void ossimImageWriterFactory::getExtensions(std::vector& result)const { result.push_back("ras"); result.push_back("bsq"); result.push_back("bil"); result.push_back("bip"); result.push_back("tif"); result.push_back("jpg"); result.push_back("ntf"); result.push_back("pdf"); } void ossimImageWriterFactory::getTypeNameList(std::vector& typeList)const { typeList.push_back(STATIC_TYPE_NAME(ossimTiffWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimJpegWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimGeneralRasterWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimNitfWriter)); typeList.push_back(STATIC_TYPE_NAME(ossimNitf20Writer)); typeList.push_back(STATIC_TYPE_NAME(ossimPdfWriter)); typeList.push_back(ossimString("ossimWriter")); } void ossimImageWriterFactory::getImageFileWritersBySuffix( ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& ext)const { ossimString testExt = ext.downcase(); if(testExt == "tiff" || testExt == "tif") { result.push_back(new ossimTiffWriter); } else if(testExt == "ntf" || testExt == "nitf") { result.push_back(new ossimNitfWriter); } else if(testExt == "jpg" || testExt == "jpeg") { result.push_back(new ossimJpegWriter); } else if(testExt == "ras" || testExt == "bsq" || testExt == "bil" || testExt == "bip") { result.push_back(new ossimGeneralRasterWriter); } else if( testExt == "pdf" ) { result.push_back( new ossimPdfWriter ); } } void ossimImageWriterFactory::getImageFileWritersByMimeType( ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& mimeType ) const { ossimString testExt = mimeType.downcase(); testExt = ossimString(testExt.begin()+6, testExt.end()); getImageFileWritersBySuffix(result, testExt); } void ossimImageWriterFactory::getImageTypeList( std::vector& imageTypeList ) const { // Add the tiff writer types. ossimRefPtr writer = new ossimTiffWriter; writer->getImageTypeList(imageTypeList); // Add the jpeg writer types. writer = new ossimJpegWriter; writer->getImageTypeList(imageTypeList); // Add the general raster writer types. writer = new ossimGeneralRasterWriter; writer->getImageTypeList(imageTypeList); // Add the nitf writer types. writer = new ossimNitfWriter; writer->getImageTypeList(imageTypeList); // Add the nitf writer types. writer = new ossimNitf20Writer; writer->getImageTypeList(imageTypeList); // Add the pdf writer types. writer = new ossimPdfWriter; writer->getImageTypeList(imageTypeList); // Add the generic ossim writer types. writer = new ossimWriter; writer->getImageTypeList(imageTypeList); writer = 0; } ossim-Miami-2.9.1/src/imaging/ossimImageWriterFactoryBase.cpp000066400000000000000000000014571352751253100242450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimImageWriterFactoryBase.cpp 18011 2010-08-31 12:48:56Z dburken $ #include RTTI_DEF1(ossimImageWriterFactoryBase, "ossimImageWriterFactoryBase", ossimObjectFactory); void ossimImageWriterFactoryBase::getImageFileWritersBySuffix( ossimImageWriterFactoryBase::ImageFileWriterList& /*result*/, const ossimString& /*ext*/)const { } void ossimImageWriterFactoryBase::getImageFileWritersByMimeType( ossimImageWriterFactoryBase::ImageFileWriterList& /*result*/, const ossimString& /*mimeType*/)const { } ossim-Miami-2.9.1/src/imaging/ossimImageWriterFactoryRegistry.cpp000066400000000000000000000232241352751253100251770ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Frank Warmerdam (warmerda@home.com) // //******************************************************************* // $Id: ossimImageWriterFactoryRegistry.cpp 22865 2014-08-06 11:17:03Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //ossimImageWriterFactoryRegistry* ossimImageWriterFactoryRegistry::theInstance = NULL; ossimImageWriterFactoryRegistry::ossimImageWriterFactoryRegistry() { } ossimImageWriterFactoryRegistry* ossimImageWriterFactoryRegistry::instance() { static ossimImageWriterFactoryRegistry inst; static bool initInst = false; if(!initInst) { ossimObjectFactoryRegistry::instance()->registerFactory(&inst); ossimImageWriterFactory::instance(); initInst = true; } return &inst; // if(!theInstance) // { // theInstance = new ossimImageWriterFactoryRegistry; // } // return theInstance; } ossimImageFileWriter* ossimImageWriterFactoryRegistry::createWriter(const ossimFilename& filename)const { ossimImageFileWriter * writer = createWriterFromExtension(filename.ext().downcase()); if(writer) { writer->setFilename(filename); } return writer; } ossimObject* ossimImageWriterFactoryRegistry::createObject(const ossimKeywordlist &kwl, const char *prefix)const { return createObjectFromRegistry(kwl, prefix); } ossimObject* ossimImageWriterFactoryRegistry::createObject(const ossimString& typeName)const { return createObjectFromRegistry(typeName); } void ossimImageWriterFactoryRegistry::getTypeNameList(std::vector& typeList)const { getAllTypeNamesFromRegistry(typeList); } ossimImageFileWriter *ossimImageWriterFactoryRegistry::createWriterFromExtension(const ossimString& fileExtension)const { ossimImageFileWriter *writer = NULL; ossimImageWriterFactoryBase::ImageFileWriterList result; getImageFileWritersBySuffix(result, fileExtension); if(!result.empty()) { writer = result[0].release(); result.clear(); } return writer; } ossimImageFileWriter *ossimImageWriterFactoryRegistry::createWriter(const ossimKeywordlist &kwl, const char *prefix)const { // let's see if we ned to return an object based on extension. // this is specified by the type to be a generic // ossimImageFileWriter // ossimString type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if(type == "ossimImageFileWriter") { ossimFilename filename = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if((filename != "")&& (filename.ext() != "")) { ossimImageFileWriter* writer = createWriterFromExtension(filename.ext()); if(writer) { writer->setFilename(filename); } return writer; } } vector::const_iterator factories; ossimImageFileWriter *result = NULL; factories = m_factoryList.begin(); while(factories != m_factoryList.end()) { result = (*factories)->createWriter(kwl, prefix); if(result) { return result; } ++factories; } return result; } ossimImageFileWriter *ossimImageWriterFactoryRegistry::createWriter(const ossimString& typeName)const { vector::const_iterator factories; ossimImageFileWriter *result = NULL; factories = m_factoryList.begin(); while(factories != m_factoryList.end()) { result = (*factories)->createWriter(typeName); if(result) { return result; } ++factories; } return result; } void ossimImageWriterFactoryRegistry::getImageTypeList(std::vector& typeList)const { vector result; vector::const_iterator iter = m_factoryList.begin(); while(iter != m_factoryList.end()) { result.clear(); (*iter)->getImageTypeList(result); // now append to the end of the typeList. typeList.insert(typeList.end(), result.begin(), result.end()); ++iter; } } void ossimImageWriterFactoryRegistry::getImageFileWritersBySuffix(ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& ext)const { ossimImageWriterFactoryBase::ImageFileWriterList tempResult; vector::const_iterator iter = m_factoryList.begin(); while(iter != m_factoryList.end()) { result.clear(); (*iter)->getImageFileWritersBySuffix(tempResult, ext); // now append to the end of the typeList. result.insert(result.end(), tempResult.begin(), tempResult.end()); ++iter; } } void ossimImageWriterFactoryRegistry::getImageFileWritersByMimeType(ossimImageWriterFactoryBase::ImageFileWriterList& result, const ossimString& mimeType)const { ossimImageWriterFactoryBase::ImageFileWriterList tempResult; vector::const_iterator iter = m_factoryList.begin(); while(iter != m_factoryList.end()) { result.clear(); (*iter)->getImageFileWritersByMimeType(tempResult, mimeType); // now append to the end of the typeList. result.insert(result.end(), tempResult.begin(), tempResult.end()); ++iter; } } std::ostream& ossimImageWriterFactoryRegistry::printImageTypeList( std::ostream& out)const { std::vector outputType; this->getImageTypeList(outputType); std::copy(outputType.begin(), outputType.end(), std::ostream_iterator(out, "\n")); out << std::endl; return out; } std::ostream& ossimImageWriterFactoryRegistry::printWriterProps(std::ostream& out)const { // Loop through factories: vector::const_iterator factoryIter = m_factoryList.begin(); while( factoryIter != m_factoryList.end() ) { out << "factory: " << (*factoryIter)->getClassName() << "\n\n"; // Loop through writer classes in factory. std::vector typeNames; (*factoryIter)->getTypeNameList(typeNames); std::vector::const_iterator typeNamesIter = typeNames.begin(); while (typeNamesIter != typeNames.end()) { ossimRefPtr writer = (*factoryIter)->createWriter(*typeNamesIter); if ( writer.valid() ) { out << "writer:\n" << writer->getClassName() << "\n"; // Loop through writer types, e.g. tiff_tiled_band_separate std::vector imageTypeList; writer->getImageTypeList(imageTypeList); std::vector::const_iterator imageTypeListIter = imageTypeList.begin(); out << "\ntypes:\n"; while ( imageTypeListIter != imageTypeList.end() ) { out << (*imageTypeListIter) << "\n"; ++imageTypeListIter; } // Loop through writer properties: std::vector propNames; writer->getPropertyNames(propNames); if ( propNames.size() ) { out << "\nproperties:\n"; ossimRefPtr prop = 0; std::vector::const_iterator p = propNames.begin(); while ( p != propNames.end() ) { out << " " << (*p) << "\n"; prop = writer->getProperty( *p ); if ( prop.valid() ) { ossimStringProperty* stringProp = dynamic_cast(prop.get()); if ( stringProp ) { if ( stringProp->getConstraints().size() ) { out << " constraints:\n"; std::vector::const_iterator strPropIter = stringProp->getConstraints().begin(); while( strPropIter != stringProp->getConstraints().end() ) { out << " " << (*strPropIter) << "\n"; ++strPropIter; } } } } ++p; } out << "\n"; } } ++typeNamesIter; } ++factoryIter; } return out; } extern "C" { void* ossimImageWriterFactoryRegistryGetInstance() { return ossimImageWriterFactoryRegistry::instance(); } } ossimImageWriterFactoryRegistry::ossimImageWriterFactoryRegistry(const ossimImageWriterFactoryRegistry&) : ossimObjectFactory() { } void ossimImageWriterFactoryRegistry::operator=(const ossimImageWriterFactoryRegistry&) { } ossim-Miami-2.9.1/src/imaging/ossimIndexToRgbLutFilter.cpp000066400000000000000000000334171352751253100235440ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //************************************************************************* // $Id: ossimIndexToRgbLutFilter.cpp 23242 2015-04-08 17:31:35Z dburken $ #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimIndexToRgbLutFilter, "ossimIndexToRgbLutFilter", ossimImageSourceFilter); static const char* MIN_VALUE_KW = "min_value"; static const char* MAX_VALUE_KW = "max_value"; static const char* MODE_KW = "mode"; static const char* LUT_FILE_KW = "lut_file"; ossimIndexToRgbLutFilter::ossimIndexToRgbLutFilter() :ossimImageSourceFilter(), theMinValue(ossim::nan()), theMaxValue(ossim::nan()), theMinValueOverride(false), theMaxValueOverride(false), theMode(REGULAR), theTile(0), theLutFile("") { setDescription("Look-up-table remapper from single-band index image to 24-bit RGB."); } ossimIndexToRgbLutFilter::~ossimIndexToRgbLutFilter() { } ossimRefPtr ossimIndexToRgbLutFilter::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection || (theLut.size() == 0)) return 0; ossimRefPtr tile = theInputConnection->getTile(tileRect, resLevel); if (!tile || !tile->getBuf()) return 0; if(!theTile) { allocate(); if (!theTile) return 0; } theTile->setImageRectangle(tileRect); theTile->makeBlank(); // Quick handling special case of empty input tile: if (tile->getDataObjectStatus() == OSSIM_EMPTY) return theTile; ossim_uint8* outBuf[3]; outBuf[0] = (ossim_uint8*)(theTile->getBuf(0)); outBuf[1] = (ossim_uint8*)(theTile->getBuf(1)); outBuf[2] = (ossim_uint8*)(theTile->getBuf(2)); ossim_uint32 maxLength = tile->getWidth()*tile->getHeight(); ossimRgbVector color; const ossimRgbVector null_color (theTile->getNullPix(0), theTile->getNullPix(1), theTile->getNullPix(2)); double index; std::map::const_iterator lut_entry; double null_index = theInputConnection->getNullPixelValue(); for (ossim_uint32 pixel=0; pixelgetScalarType()) { case OSSIM_DOUBLE: index = ((double*) tile->getBuf())[pixel]; break; case OSSIM_SSHORT16: index = (double)(((ossim_sint16*) tile->getBuf())[pixel]); break; case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: index = (double)(((float*) tile->getBuf())[pixel]); break; case OSSIM_UCHAR: index = (double)(((ossim_uint8*) tile->getBuf())[pixel]); break; case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: index = (double)(((ossim_uint16*) tile->getBuf())[pixel]); break; default: break; } // Do not remap null pixels, leave the output pixel "blank" which is null-pixel value: if (index == null_index) continue; // REGULAR mode needs to clamp the indices to min max for non-null pixels: if (theMode == REGULAR) { if (index < theMinValue) index = theMinValue; else if (index > theMaxValue) index = theMaxValue; } // Now perform look-up depending on mode: if (theMode == LITERAL) { lut_entry = theLut.find(index); if (lut_entry == theLut.end()) color = null_color; else color = lut_entry->second; } else { // Vertices and Regular mode perform same interpolation here between the line segments // vertices: lut_entry = theLut.find(index); if (lut_entry != theLut.end()) { // Got exact match, no interpolation needed: color = lut_entry->second; } else { lut_entry = theLut.upper_bound(index); if ((lut_entry == theLut.end()) || (lut_entry == theLut.begin())) color = null_color; else { // Need to linearly interpolate: double index_hi = lut_entry->first; ossimRgbVector color_hi (lut_entry->second); --lut_entry; double index_lo = lut_entry->first; ossimRgbVector color_lo (lut_entry->second); double w_lo = (index_hi - index)/(index_hi - index_lo); double w_hi = 1.0 - w_lo; color.setR(ossim::round( color_hi.getR()*w_hi + color_lo.getR()*w_lo )); color.setG(ossim::round( color_hi.getG()*w_hi + color_lo.getG()*w_lo )); color.setB(ossim::round( color_hi.getB()*w_hi + color_lo.getB()*w_lo )); } } } // Assign this output pixel: outBuf[0][pixel] = color.getR(); outBuf[1][pixel] = color.getG(); outBuf[2][pixel] = color.getB(); } // end loop over tile's pixels theTile->validate(); return theTile; } void ossimIndexToRgbLutFilter::allocate() { if(!theInputConnection) return; theTile = ossimImageDataFactory::instance()->create(this, 3, this); if(theTile.valid()) { theTile->initialize(); } } void ossimIndexToRgbLutFilter::initialize() { // This assigns theInputConnection if one is there. ossimImageSourceFilter::initialize(); // theTile will get allocated on first getTile call. theTile = 0; if ( theInputConnection ) { // Initialize the chain on the left hand side of us. theInputConnection->initialize(); if(!theMinValueOverride) theMinValue = theInputConnection->getMinPixelValue(0); if(!theMaxValueOverride) theMaxValue = theInputConnection->getMaxPixelValue(0); if(theMinValue > theMaxValue) swap(theMinValue, theMaxValue); } } bool ossimIndexToRgbLutFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { if (theMinValueOverride) kwl.add(prefix, MIN_VALUE_KW, theMinValue, true); if (theMaxValueOverride) kwl.add(prefix, MAX_VALUE_KW, theMaxValue, true); ossimString value; switch (theMode) { case LITERAL: value = "literal"; break; case VERTICES: value = "vertices"; break; default: value = "regular"; } kwl.add(prefix, MODE_KW, value.c_str(), true); bool rtn_stat = true; // Save the actual LUT: const ossimString entry_kw ("entry"); ossimString color_keyword, base_keyword; ossimRgbVector rgbVector; ossimString blank(" "); ossim_uint32 entry = 0; std::map::const_iterator iter = theLut.begin(); while (iter != theLut.end()) { base_keyword = entry_kw + ossimString::toString(entry); if ((theMode == LITERAL) || (theMode == VERTICES)) { // Index and color are sub-entries for these modes: kwl.add(prefix, (base_keyword+".index").chars(), iter->first); color_keyword = base_keyword + ".color"; } else { color_keyword = base_keyword; } rgbVector = iter->second; value = ossimString::toString((int)rgbVector.getR()) + blank + ossimString::toString((int)rgbVector.getG()) + blank + ossimString::toString((int)rgbVector.getB()); kwl.add(prefix, color_keyword.chars(), value.chars()); ++iter; ++entry; } rtn_stat &= ossimImageSourceFilter::saveState(kwl, prefix); return rtn_stat; } bool ossimIndexToRgbLutFilter::loadState(const ossimKeywordlist& orig_kwl, const char* prefix) { bool return_state = true; ossimKeywordlist* kwl = new ossimKeywordlist(orig_kwl); // need non-const copy // First look for a LUT filename, and add its contents to the original KWL: theLutFile = kwl->find(prefix, LUT_FILE_KW); if (!theLutFile.empty()) { // Need new (non const) KWL to hold merged contents, maintaining proper prefix if any: ossimKeywordlist lut_kwl; if (lut_kwl.addFile(theLutFile)) kwl->add(prefix, lut_kwl, false); // appends all entries of lut_kwl with prefix before adding } theMinValueOverride = false; ossimString lookup = kwl->find(prefix, MIN_VALUE_KW); if(!lookup.empty()) { theMinValue =lookup.toDouble(); theMinValueOverride = true; } theMaxValueOverride = false; lookup = kwl->find(prefix, MAX_VALUE_KW); if(!lookup.empty()) { theMaxValue = lookup.toDouble(); theMaxValueOverride = true; } lookup = kwl->find(prefix, MODE_KW); if (lookup.contains("literal")) theMode = LITERAL; else if (lookup.contains("vertices")) theMode = VERTICES; else theMode = REGULAR; return_state &= initializeLut(kwl, prefix); return_state &= ossimImageSourceFilter::loadState(orig_kwl, prefix); delete kwl; return return_state; } bool ossimIndexToRgbLutFilter::initializeLut(const ossimKeywordlist* kwl, const char* prefix) { theLut.clear(); const ossimString entry_kw ("entry"); ossimString keyword, base_keyword; ossimString indexStr, rgbStr; ossimString blank(" "); std::vector rgbList; double index; ossimRgbVector rgbVector (0,0,0); bool rtn_state = true; ossim_uint32 numEntries=0; while (true) { base_keyword = entry_kw + ossimString::toString(numEntries); if ((theMode == LITERAL) || (theMode == VERTICES)) { // Index and color are subentries for this mode: keyword = base_keyword + ".index"; indexStr = kwl->find(prefix, keyword.chars()); if (indexStr.empty()) break; index = indexStr.toDouble(); keyword = base_keyword + ".color"; rgbStr = kwl->find(prefix, keyword.chars()); } else { // REGULAR mode: index is computed later to arrive at equally-spaced vertices. For now, // just store entry number as index: index = (double) numEntries; keyword = base_keyword; rgbStr = kwl->find(prefix, keyword.chars()); if (rgbStr.empty()) { // Perhaps old bloated form with separate keywords for R, G, B rgbStr = kwl->find(prefix, (keyword + ".r").chars()); rgbStr += " "; rgbStr += kwl->find(prefix, (keyword + ".g").chars()); rgbStr += " "; rgbStr += kwl->find(prefix, (keyword + ".b").chars()); if (rgbStr.length() < 5) break; } } rgbStr.split(rgbList, blank, true); if (rgbList.size() != 3) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimIndexToRgbLutFilter::initializeLut() -- " "Bad color specification in LUT KWL. LUT is not properly initialized."<(index, rgbVector)); rgbList.clear(); ++numEntries; } // For REGULAR mode, need to adjust the indices to reflect a piecewise linear LUT with equally // spaced vertices: if (theMode == REGULAR) { std::map orig_lut = theLut; std::map::iterator iter = orig_lut.begin(); theLut.clear(); if (numEntries == 1) { // Insert the implied start index at black and endpoint at specified color: theLut.insert(std::pair(theMinValue, ossimRgbVector (1, 1, 1))); theLut.insert(std::pair(theMaxValue, iter->second)); } else { // Loop to create equally-spaced vertices between min and max index values: double interval = (theMaxValue - theMinValue) / (numEntries - 1); while (iter != orig_lut.end()) { index = theMinValue + iter->first*interval; theLut.insert(std::pair(index, iter->second)); ++iter; } } } return rtn_state; } ossim_uint32 ossimIndexToRgbLutFilter::getNumberOfOutputBands() const { if(isSourceEnabled()) { return 3; } return ossimImageSourceFilter::getNumberOfOutputBands(); } ossimScalarType ossimIndexToRgbLutFilter::getOutputScalarType() const { if(isSourceEnabled()) { return OSSIM_UCHAR; } return ossimImageSourceFilter::getOutputScalarType(); } void ossimIndexToRgbLutFilter::setLut(const ossimFilename& file) { theLutFile = file; if(file.exists()) { ossimKeywordlist kwl(theLutFile); loadState(kwl); } } double ossimIndexToRgbLutFilter::getMinValue()const { return theMinValue; } double ossimIndexToRgbLutFilter::getMaxValue()const { return theMaxValue; } void ossimIndexToRgbLutFilter::setMinValue(double value) { theMinValue = value; } void ossimIndexToRgbLutFilter::setMaxValue(double value) { theMaxValue = value; } double ossimIndexToRgbLutFilter::getNullPixelValue(ossim_uint32 /* band */ )const { return 0.0; } double ossimIndexToRgbLutFilter::getMinPixelValue(ossim_uint32 /* band */)const { return 1.0; } double ossimIndexToRgbLutFilter::getMaxPixelValue(ossim_uint32 /* band */)const { return 255.0; } ossim-Miami-2.9.1/src/imaging/ossimIntensityAdjustmentFilter.cpp000066400000000000000000000204731352751253100250750ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimIntensityAdjustmentFilter.cpp 13330 2008-07-28 18:04:40Z dburken $ #include #include #include #include #include RTTI_DEF1(ossimIntensityAdjustmentFilter, "ossimIntensityAdjustmentFilter", ossimImageSourceFilter); ossimIntensityAdjustmentFilter::ossimIntensityAdjustmentFilter() :ossimImageSourceFilter(), theMeanIntensityTarget(ossim::nan()), theNormTile(NULL), theTile(NULL), theBlankTile(NULL) { theGridBounds.makeNan(); } ossimIntensityAdjustmentFilter::~ossimIntensityAdjustmentFilter() { } ossimRefPtr ossimIntensityAdjustmentFilter::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if (!theTile.valid()) { allocate(); // first time through. } if(theBlankTile.valid()) { theBlankTile->setImageRectangle(rect); } if(!theInputConnection) { return theBlankTile; } ossimRefPtr data = theInputConnection->getTile(rect, resLevel); if(!isSourceEnabled()) { return data; } theTile->setImageRectangle(rect); theNormTile->setImageRectangle(rect); loadNormTile(data); if(ossim::isnan(theMeanIntensityTarget)) { theMeanIntensityTarget = theMeanIntensityGrid.meanValue(); } loadNormTile(data); if((theNormTile->getDataObjectStatus()!=OSSIM_NULL)&& (theNormTile->getDataObjectStatus()!=OSSIM_EMPTY)) { float* buf[3]; if(data->getNumberOfBands() == 3) { buf[0] = (float*)theNormTile->getBuf(0); buf[1] = (float*)theNormTile->getBuf(1); buf[2] = (float*)theNormTile->getBuf(2); } else { buf[0] = (float*)theNormTile->getBuf(0); buf[1] = (float*)theNormTile->getBuf(0); buf[2] = (float*)theNormTile->getBuf(0); } ossim_int32 y = 0; ossim_int32 x = 0; ossim_int32 upperY = theNormTile->getHeight(); ossim_int32 upperX = theNormTile->getWidth(); ossimIpt origin = rect.ul(); for(y = 0; y < upperY; ++y) { for(x = 0; x < upperX; ++x) { ossimIpt pt = ossimIpt(origin.x + x, origin.y + y) - theGridBounds.ul(); if((buf[0] != 0) && (buf[1] != 0) && (buf[2] != 0)) { ossimRgbVector rgb((ossim_uint8)(*(buf[0])*255.0), (ossim_uint8)(*(buf[1])*255.0), (ossim_uint8)(*(buf[2])*255.0)); ossimHsvVector hsv(rgb); hsv.setV(matchTargetMean(hsv.getV(), theMeanIntensityGrid(pt.x, pt.y), theMeanIntensityTarget, theNormTile->getMinPix(0), theNormTile->getMaxPix(0))); ossimRgbVector result(hsv); *buf[0] = result.getR()/255.0; *buf[1] = result.getG()/255.0; *buf[2] = result.getB()/255.0; } ++buf[0]; ++buf[1]; ++buf[2]; } } } theTile->copyNormalizedBufferToTile((float*)theNormTile->getBuf()); theTile->validate(); return theTile; } void ossimIntensityAdjustmentFilter::initialize() { ossimImageSourceFilter::initialize(); theNormTile = NULL; theBlankTile = NULL; if(theInputConnection) { theGridBounds = theInputConnection->getBoundingRect(); } else { theGridBounds.makeNan(); } } void ossimIntensityAdjustmentFilter::allocate() { theBlankTile = ossimImageDataFactory::instance()->create(this, this); theTile = (ossimImageData*)theBlankTile->dup(); theTile->initialize(); } void ossimIntensityAdjustmentFilter::createAndPopulateGrid(const ossimIpt& spacing, double targetMean) { if(theInputConnection) { ossim_uint32 x = 0; ossim_uint32 y = 0; theGridBounds = theInputConnection->getBoundingRect(); ossimDrect rect(0, 0, theGridBounds.width()-1, theGridBounds.height()-1); theMeanIntensityGrid = ossimDblGrid(rect, ossimDpt(spacing), 0); for(y = 0; y <= theGridBounds.height(); y+=spacing.y) { for(x = 0; x <= theGridBounds.width(); x+=spacing.x) { ossimIpt ul(x - 16, y - 16); ossimIrect sampleRect(ul.x, ul.y, ul.x + 31, ul.y + 31); ossimRefPtr data = theInputConnection->getTile(sampleRect); double mean = computeMeanIntensity(data); theMeanIntensityGrid.setNearestNode(ossimDpt(x, y), mean); } } // theMeanIntensityGrid.interpolateNullValuedNodes(); } theMeanIntensityTarget = targetMean; } double ossimIntensityAdjustmentFilter::computeMeanIntensity( ossimRefPtr& data) { double result = 0; double divisor = 0; if(data.valid() && (data->getDataObjectStatus()!=OSSIM_NULL)&& (data->getDataObjectStatus()!=OSSIM_EMPTY)) { loadNormTile(data); int i = 0; int upper = data->getWidth()*data->getHeight(); float* buf[3]; if(data->getNumberOfBands() == 3) { buf[0] = (float*)theNormTile->getBuf(0); buf[1] = (float*)theNormTile->getBuf(1); buf[2] = (float*)theNormTile->getBuf(2); } else { buf[0] = (float*)theNormTile->getBuf(); buf[1] = (float*)theNormTile->getBuf(); buf[2] = (float*)theNormTile->getBuf(); } for(i = 0; i < upper; ++i) { ossimRgbVector rgb((ossim_uint8)(*(buf[0])*255.0), (ossim_uint8)(*(buf[1])*255.0), (ossim_uint8)(*(buf[2])*255.0)); ossimHsvVector hsv(rgb); if(hsv.getV() > 0.0) { result += hsv.getV(); divisor += 1.0; } ++buf[0]; ++buf[1]; ++buf[2]; } } if(divisor > 0.0) { result /= divisor; } return result; } void ossimIntensityAdjustmentFilter::loadNormTile(ossimRefPtr& data) { if(!theNormTile) { theNormTile = ossimImageDataFactory::instance()->create(this, OSSIM_NORMALIZED_FLOAT, data->getNumberOfBands(), data->getWidth(), data->getHeight()); theNormTile->initialize(); } else { theNormTile->setImageRectangle(data->getImageRectangle()); } data->copyTileToNormalizedBuffer((float*)theNormTile->getBuf()); theNormTile->validate(); } double ossimIntensityAdjustmentFilter::matchTargetMean(double inputValue, double meanValue, double targetMean, double minValue, double maxValue) { // max change const double delta = targetMean - meanValue; double weight=0.0; // weight max change dependend on proximity to end points if (inputValue <= meanValue) { weight = fabs((inputValue - minValue) / (meanValue - minValue)); } else { weight = fabs((maxValue - inputValue) / (maxValue - meanValue)); } return (inputValue + (delta * weight)); } ossim-Miami-2.9.1/src/imaging/ossimJpegCodec.cpp000066400000000000000000000417531352751253100215310ustar00rootroot00000000000000//--- // // License: MIT // // Description: class declaration for base codec(encoder/decoder). // //--- // $Id$ #include // we need to get rid of the jpedlib include in this header #include // same for here #include #include #include #include #include /** for jmp_buf */ #include /** for jpeg stuff */ /** @brief Extended error handler struct. */ struct ossimJpegErrorMgr { struct jpeg_error_mgr pub; /* "public" fields */ jmp_buf setjmp_buffer; /* for return to caller */ }; typedef struct ossimJpegErrorMgr* ossimJpegErrorPtr; void ossimJpegErrorExit (jpeg_common_struct* cinfo) { /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */ ossimJpegErrorPtr myerr = (ossimJpegErrorPtr) cinfo->err; /* Always display the message. */ /* We could postpone this until after returning, if we chose. */ (*cinfo->err->output_message) (cinfo); /* Return control to the setjmp point */ longjmp(myerr->setjmp_buffer, 1); } ossimJpegCodec::ossimJpegCodec() :m_quality(100), m_ext("jpg") { } ossimJpegCodec::~ossimJpegCodec() { } ossimString ossimJpegCodec::getCodecType()const { return ossimString("jpeg"); } const std::string& ossimJpegCodec::getExtension() const { return m_ext; // "jpg" } bool ossimJpegCodec::encode( const ossimRefPtr& in, std::vector& out )const { bool result = false; if ( in.valid() && (in->getDataObjectStatus() != OSSIM_NULL) ) { if ( in->getScalarType() == OSSIM_UINT8 ) { // Open a memory stream up to put the jpeg image in memory: std::stringstream jpegStreamBuf; //--- // Initialize JPEG compression library: // NOTE: JDIMENSION is an "unsigned int" //--- struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error( &jerr ); jpeg_create_compress(&cinfo); // Define a custom stream destination manager for jpeglib to write compressed block: jpeg_cpp_stream_dest(&cinfo, jpegStreamBuf); /* Setting the parameters of the output file here */ cinfo.image_width = in->getWidth(); cinfo.image_height = in->getHeight(); // Bands must be one or three for this writer. const ossim_uint32 INPUT_BANDS = in->getNumberOfBands(); if ( (INPUT_BANDS == 1) || (INPUT_BANDS == 3) ) { cinfo.input_components = INPUT_BANDS; } else { if ( INPUT_BANDS < 3 ) { cinfo.input_components = 1; // Use first band. } else { cinfo.input_components = 3; // Use the first 3 bands. } } // colorspace of input image if ( cinfo.input_components == 3) { cinfo.in_color_space = JCS_RGB; } else { cinfo.in_color_space = JCS_GRAYSCALE; } // Default compression parameters, we shouldn't be worried about these. jpeg_set_defaults( &cinfo ); jpeg_set_quality(&cinfo, m_quality, TRUE); //limit to baseline-JPEG values // Now do the compression... jpeg_start_compress( &cinfo, TRUE ); // Line buffer: ossim_uint32 buf_size = cinfo.input_components*cinfo.image_width; std::vector buf(buf_size); // Compress the tile on line at a time: JSAMPROW row_pointer[1]; // Pointer to a single row. row_pointer[0] = (JSAMPLE*)&buf.front(); // Get pointers to the input data: std::vector inBuf(cinfo.input_components); for ( ossim_int32 band = 0; band < cinfo.input_components; ++band ) { inBuf[band] = in->getUcharBuf(band); } ossim_uint32 inIdx = 0; for (ossim_uint32 line=0; line< cinfo.image_height; ++line) { // Convert from band sequential to band interleaved by pixel. ossim_uint32 outIdx = 0; for ( ossim_uint32 p = 0; p < cinfo.image_width; ++p ) { for ( ossim_int32 band = 0; band < cinfo.input_components; ++band ) { buf[outIdx++] = inBuf[band][inIdx]; } ++inIdx; } // Write it... jpeg_write_scanlines( &cinfo, row_pointer, 1 ); } // Similar to read file, clean up after we're done compressing. jpeg_finish_compress( &cinfo ); jpeg_destroy_compress( &cinfo ); // Copy the memory stream to output vector. out.resize(jpegStreamBuf.str().size()); jpegStreamBuf.seekg(0, std::ios_base::beg); jpegStreamBuf.read((char*)&out.front(), jpegStreamBuf.str().size()); result = true; } else // Scalar type check... { ossimNotify(ossimNotifyLevel_WARN) << "ossimCodecFactory::encodeJpeg ERROR:" << "\nPassing non-eight bit data to eight bit encoder!" << std::endl; } } // Matches: if ( in.valid() ... ) return result; } bool ossimJpegCodec::decode( const std::vector& in, ossimRefPtr& out ) const { bool result = false; // Check for jpeg signature: if ( in.size() > 3 ) { if ( (in[0] == 0xff) && (in[1] == 0xd8) && (in[2] == 0xff) ) { if (in[3] == 0xe0) { result = decodeJpeg( in, out ); } else if (in[3] == 0xdb) { result = decodeJpegToRgb( in, out ); } } } return result; } bool ossimJpegCodec::decodeJpeg( const std::vector& in, ossimRefPtr& out ) const { bool result = false; /* This struct contains the JPEG decompression parameters and pointers * to working space (which is allocated as needed by the JPEG library). */ jpeg_decompress_struct cinfo; /* We use our private extension JPEG error handler. * Note that this struct must live as long as the main JPEG parameter * struct, to avoid dangling-pointer problems. */ ossimJpegErrorMgr jerr; /* Step 1: allocate and initialize JPEG decompression object */ /* We set up the normal JPEG error routines, then override error_exit. */ cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = ossimJpegErrorExit; /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp(jerr.setjmp_buffer) == 0) { result = true; /* Now we can initialize the JPEG decompression object. */ jpeg_CreateDecompress(&cinfo, JPEG_LIB_VERSION, sizeof(cinfo)); //--- // Step 2: specify data source. In this case we will uncompress from // memory so we will use "ossimJpegMemorySrc" in place of " jpeg_stdio_src". //--- ossimJpegMemorySrc ( &cinfo, &(in.front()), (size_t)(in.size()) ); /* Step 3: read file parameters with jpeg_read_header() */ jpeg_read_header(&cinfo, TRUE); /* Step 4: set parameters for decompression */ /* Step 5: Start decompressor */ jpeg_start_decompress(&cinfo); const ossim_uint32 SAMPLES = cinfo.output_width; const ossim_uint32 LINES = cinfo.output_height; const ossim_uint32 BANDS = cinfo.output_components; #if 0 /* Please leave for debug. (drb) */ if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "jpeg cinfo.output_width: " << cinfo.output_width << "\njpeg cinfo.output_height: " << cinfo.output_height << "\njpeg cinfo.out_color_space: " << cinfo.out_color_space << "\n"; } #endif if ( out.valid() ) { // This will resize tile if not correct. out->setImageRectangleAndBands( ossimIrect(0,0,(ossim_int32)SAMPLES-1,(ossim_int32)LINES-1), BANDS ); } else { out = new ossimU8ImageData( 0, BANDS, SAMPLES, LINES ); out->initialize(); } // Get pointers to the cache tile buffers. std::vector destinationBuffer(BANDS); for (ossim_uint32 band = 0; band < BANDS; ++band) { destinationBuffer[band] = out->getUcharBuf(band); } std::vector lineBuffer(SAMPLES * cinfo.output_components); JSAMPROW jbuf[1]; jbuf[0] = (JSAMPROW) &(lineBuffer.front()); while (cinfo.output_scanline < LINES) { // Read a line from the jpeg file. jpeg_read_scanlines(&cinfo, jbuf, 1); //--- // Copy the line which if band interleaved by pixel the the band // separate buffers. //--- ossim_uint32 index = 0; for (ossim_uint32 sample = 0; sample < SAMPLES; ++sample) { for (ossim_uint32 band = 0; band < BANDS; ++band) { destinationBuffer[band][sample] = lineBuffer[index]; ++index; } } for (ossim_uint32 band = 0; band < BANDS; ++band) { destinationBuffer[band] += SAMPLES; } } // Set the tile status: out->validate(); // clean up... jpeg_finish_decompress(&cinfo); } // Matches: if (setjmp(jerr.setjmp_buffer) == 0) jpeg_destroy_decompress(&cinfo); return result; } bool ossimJpegCodec::decodeJpegToRgb(const std::vector& in, ossimRefPtr& out ) const { bool result = false; ossim_int32 jpegColorSpace = getColorSpace( in ); if ( jpegColorSpace == JCS_CMYK ) { ossimRefPtr cmykTile = 0; result = decodeJpeg( in, cmykTile ); // Decode to CMYK tile. if ( result ) { if ( cmykTile.valid() ) { const ossim_uint32 INPUT_BANDS = cmykTile->getNumberOfBands(); if ( INPUT_BANDS == 4 ) { const ossim_uint32 OUTPUT_BANDS = 3; const ossimIrect RECT = cmykTile->getImageRectangle(); const ossim_uint32 LINES = RECT.height(); const ossim_uint32 SAMPLES = RECT.width(); ossim_uint32 band = 0; // Set or create output tile: if ( out.valid() ) { // This will resize tile if not correct. out->setImageRectangleAndBands( RECT, OUTPUT_BANDS ); } else { out = new ossimU8ImageData( 0, OUTPUT_BANDS, SAMPLES, LINES ); out->initialize(); } // Assign pointers to bands. std::vector inBands(INPUT_BANDS); for ( band = 0; band < INPUT_BANDS; ++band ) { inBands[band] = cmykTile->getUcharBuf( band ); } std::vector outBands(INPUT_BANDS); for ( band = 0; band < OUTPUT_BANDS; ++band ) { outBands[band] = out->getUcharBuf( band ); } const ossim_uint8 NP = 0; // null pixel const ossim_uint8 MAXP = 255; // max pixel std::vector cmyk(INPUT_BANDS, 0.0); std::vector rgb(OUTPUT_BANDS, 0.0); for ( ossim_uint32 line = 0; line < LINES; ++line ) { for (ossim_uint32 sample = 0; sample < SAMPLES; ++sample) { //--- // NOTE: // This current does NOT work, colors come out wrong, with // the one dataset that I have: // "2015_05_05_Whitehorse_3857.gpkg" // (drb - 03 June 2015) //--- cmyk[0] = inBands[0][sample]; // C cmyk[1] = inBands[1][sample]; // M cmyk[2] = inBands[2][sample]; // Y cmyk[3] = inBands[3][sample]; // K //--- // The red (R) color is calculated from the cyan (C) and black (K) colors. // The green color (G) is calculated from the magenta (M) and black (K) colors. // The blue color (B) is calculated from the yellow (Y) and black (K) colors. //--- // rgb[0] = (255.0-cmyk[0]) * 255.0-cmyk[3]; // rgb[1] = (255.0-cmyk[1]) * 255.0-cmyk[3]; // rgb[2] = (255.0-cmyk[2]) * 255.0-cmyk[3]; rgb[0] = (cmyk[0]) * cmyk[3]/255.0; rgb[1] = (cmyk[1]) * cmyk[3]/255.0; rgb[2] = (cmyk[2]) * cmyk[3]/255.0; outBands[0][sample] = ( (rgb[0] >= 0.0) ? ( (rgb[0] <= 255.0) ? (ossim_uint8)rgb[0] : MAXP ) : NP ); outBands[1][sample] = ( (rgb[1] >= 0.0) ? ( (rgb[1] <= 255.0) ? (ossim_uint8)rgb[1] : MAXP ) : NP ); outBands[2][sample] = ( (rgb[2] >= 0.0) ? ( (rgb[2] <= 255.0) ? (ossim_uint8)rgb[2] : MAXP ) : NP ); } // End sample loop. // Increment pointers. for (ossim_uint32 band = 0; band < OUTPUT_BANDS; ++band) { inBands[band] += SAMPLES; outBands[band] += SAMPLES; } inBands[3] += SAMPLES; // Last band of input. } // End of line loop. // Set the tile status: out->validate(); } // Matches sanity check: if ( INPUT_BANDS == 4 ) } // Matches: if ( cmykTile.valid() ) } // Matches: if ( decodeJpeg( in, cmykTile ) ) } // Matches: if ( jpegColorSpace == JCS_CMYK ) else { ossimNotify(ossimNotifyLevel_WARN) << "ossimJpegCodec::decodeJpegRgb: WARNING: " << "Unhandled jpeg output color space!" << std::endl; } return result; } // End: ossimJpegCodec::decodeJpegRgb( ... ) ossim_int32 ossimJpegCodec::getColorSpace( const std::vector& in ) const { J_COLOR_SPACE result = JCS_UNKNOWN; if ( in.size() ) { jpeg_decompress_struct cinfo; ossimJpegErrorMgr jerr; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = ossimJpegErrorExit; /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp(jerr.setjmp_buffer) == 0) { jpeg_CreateDecompress(&cinfo, JPEG_LIB_VERSION, sizeof(cinfo)); ossimJpegMemorySrc ( &cinfo, &(in.front()), (size_t)(in.size()) ); jpeg_read_header(&cinfo, TRUE); result = cinfo.out_color_space; jpeg_destroy_decompress(&cinfo); } } return result; } void ossimJpegCodec::setProperty(ossimRefPtr property) { if(property->getName() == ossimKeywordNames::QUALITY_KW) { m_quality = property->valueToString().toUInt32(); } } ossimRefPtr ossimJpegCodec::getProperty(const ossimString& name)const { ossimRefPtr result; if(name == ossimKeywordNames::QUALITY_KW) { result = new ossimNumericProperty(ossimKeywordNames::QUALITY_KW, ossimString::toString(m_quality), 0, 100); } else { result = ossimCodecBase::getProperty(name); } return result; } void ossimJpegCodec::getPropertyNames(std::vector& propertyNames)const { ossimCodecBase::getPropertyNames(propertyNames); propertyNames.push_back(ossimKeywordNames::QUALITY_KW); } bool ossimJpegCodec::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* quality = kwl.find(prefix, ossimKeywordNames::QUALITY_KW); if(quality) { m_quality = ossimString(quality).toUInt32(); } return ossimCodecBase::loadState(kwl, prefix); } bool ossimJpegCodec::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::QUALITY_KW, m_quality); return ossimCodecBase::saveState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimJpegMemDest.cpp000066400000000000000000000050011352751253100220340ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file // // Most of code and comments below are from jpeg-6b "example.c" file. See // http://www4.cs.fau.de/Services/Doc/graphics/doc/jpeg/libjpeg.html // // Author: Oscar Kramer (From example by Thomas Lane) //---------------------------------------------------------------------------- // $Id$ #include #include /* free, malloc, size_t */ #include /* FILE* */ #include /** for jmp_buf */ #include #include /** for jpeg stuff */ /* *** Custom destination manager for JPEG writer *** */ typedef struct { struct jpeg_destination_mgr pub; /* public fields */ std::ostream* stream; /* target stream */ JOCTET* buffer; /* start of buffer */ } cpp_dest_mgr; #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */ void init_destination (j_compress_ptr cinfo) { cpp_dest_mgr* dest = (cpp_dest_mgr*) cinfo->dest; /* Allocate the output buffer --- it will be released when done with image */ dest->buffer = (JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, OUTPUT_BUF_SIZE * sizeof(JOCTET)); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; } boolean empty_output_buffer (j_compress_ptr cinfo) { cpp_dest_mgr* dest = (cpp_dest_mgr*) cinfo->dest; dest->stream->write ((char*)dest->buffer, OUTPUT_BUF_SIZE); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; return TRUE; } void term_destination (j_compress_ptr cinfo) { cpp_dest_mgr* dest = (cpp_dest_mgr*) cinfo->dest; size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer; /* Write any data remaining in the buffer */ if (datacount > 0) dest->stream->write ((char*)dest->buffer, datacount); dest->stream->flush(); free (cinfo->dest); } // void jpeg_cpp_stream_dest (j_compress_ptr cinfo, std::ostream& stream) void jpeg_cpp_stream_dest(jpeg_compress_struct* cinfo, std::ostream& stream) { cpp_dest_mgr* dest; /* first time for this JPEG object? */ if (cinfo->dest == NULL) cinfo->dest = (struct jpeg_destination_mgr *) malloc (sizeof(cpp_dest_mgr)); dest = (cpp_dest_mgr*) cinfo->dest; dest->pub.init_destination = init_destination; dest->pub.empty_output_buffer = empty_output_buffer; dest->pub.term_destination = term_destination; dest->stream = &stream; } ossim-Miami-2.9.1/src/imaging/ossimJpegMemSrc.cpp000066400000000000000000000130231352751253100216670ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: See top level LICENSE.txt file. // // Author: David Burken, original code from Thomas G. Lane (memsrc.c) // // Description: // Code to use jpeg-6b library to read jpeg image from memory. //---------------------------------------------------------------------------- // $Id$ //--- // Original code from Thomas G. Lane, header comment follows. //--- /* * memsrc.c * * Copyright (C) 1994-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains decompression data source routines for the case of * reading JPEG data from a memory buffer that is preloaded with the entire * JPEG file. This would not seem especially useful at first sight, but * a number of people have asked for it. * This is really just a stripped-down version of jdatasrc.c. Comparison * of this code with jdatasrc.c may be helpful in seeing how to make * custom source managers for other purposes. */ /* this is not a core library module, so it doesn't define JPEG_INTERNALS */ /* #include */ #include #include /* FILE* */ #include /** for jmp_buf */ #include /** for jpeg stuff */ #include extern "C" { /* Expanded data source object for memory input */ struct ossimJpegSourceMgr { struct jpeg_source_mgr pub; /* public fields */ JOCTET eoi_buffer[2]; /* a place to put a dummy EOI */ }; typedef ossimJpegSourceMgr* ossimJpegSourceMgrPtr; /* * Initialize source --- called by jpeg_read_header * before any data is actually read. */ void init_source (j_decompress_ptr /* cinfo */) { /* No work, since jpeg_memory_src set up the buffer pointer and count. * Indeed, if we want to read multiple JPEG images from one buffer, * this *must* not do anything to the pointer. */ } /* * Fill the input buffer --- called whenever buffer is emptied. * * In this application, this routine should never be called; if it is called, * the decompressor has overrun the end of the input buffer, implying we * supplied an incomplete or corrupt JPEG datastream. A simple error exit * might be the most appropriate response. * * But what we choose to do in this code is to supply dummy EOI markers * in order to force the decompressor to finish processing and supply * some sort of output image, no matter how corrupted. */ boolean fill_input_buffer (j_decompress_ptr cinfo) { ossimJpegSourceMgrPtr src = (ossimJpegSourceMgrPtr) cinfo->src; WARNMS(cinfo, JWRN_JPEG_EOF); /* Create a fake EOI marker */ src->eoi_buffer[0] = (JOCTET) 0xFF; src->eoi_buffer[1] = (JOCTET) JPEG_EOI; src->pub.next_input_byte = src->eoi_buffer; src->pub.bytes_in_buffer = 2; return TRUE; } /* * Skip data --- used to skip over a potentially large amount of * uninteresting data (such as an APPn marker). * * If we overrun the end of the buffer, we let fill_input_buffer deal with * it. An extremely large skip could cause some time-wasting here, but * it really isn't supposed to happen ... and the decompressor will never * skip more than 64K anyway. */ void skip_input_data (j_decompress_ptr cinfo, long num_bytes) { ossimJpegSourceMgrPtr src = (ossimJpegSourceMgrPtr) cinfo->src; if (num_bytes > 0) { while (num_bytes > (long) src->pub.bytes_in_buffer) { num_bytes -= (long) src->pub.bytes_in_buffer; (void) fill_input_buffer(cinfo); /* note we assume that fill_input_buffer will never return FALSE, * so suspension need not be handled. */ } src->pub.next_input_byte += (size_t) num_bytes; src->pub.bytes_in_buffer -= (size_t) num_bytes; } } /* * An additional method that can be provided by data source modules is the * resync_to_restart method for error recovery in the presence of RST markers. * For the moment, this source module just uses the default resync method * provided by the JPEG library. That method assumes that no backtracking * is possible. */ /* * Terminate source --- called by jpeg_finish_decompress * after all data has been read. Often a no-op. * * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding * application must deal with any cleanup that should happen even * for error exit. */ void term_source (j_decompress_ptr /* cinfo */) { /* no work necessary here */ } /* * Prepare for input from a memory buffer. */ void ossimJpegMemorySrc (jpeg_decompress_struct* cinfo, const ossim_uint8* buffer, std::size_t bufsize) { ossimJpegSourceMgrPtr src; /* The source object is made permanent so that a series of JPEG images * can be read from a single buffer by calling jpeg_memory_src * only before the first one. * This makes it unsafe to use this manager and a different source * manager serially with the same JPEG object. Caveat programmer. */ if (cinfo->src == NULL) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(ossimJpegSourceMgr)); } src = (ossimJpegSourceMgrPtr) cinfo->src; src->pub.init_source = init_source; src->pub.fill_input_buffer = fill_input_buffer; src->pub.skip_input_data = skip_input_data; src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ src->pub.term_source = term_source; src->pub.next_input_byte = buffer; src->pub.bytes_in_buffer = bufsize; } } ossim-Miami-2.9.1/src/imaging/ossimJpegStdIOSrc.cpp000066400000000000000000000234161352751253100221420ustar00rootroot00000000000000/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ /* * jdatasrc.c * * Copyright (C) 1994-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains decompression data source routines for the case of * reading JPEG data from a file (or any stdio stream). While these routines * are sufficient for most applications, some will want to use a different * source manager. * IMPORTANT: we assume that fread() will correctly transcribe an array of * JOCTETs from 8-bit-wide elements on external storage. If char is wider * than 8 bits on your machine, you may need to do some tweaking. */ /* this is not a core library module, so it doesn't define JPEG_INTERNALS */ #include #include /** for jmp_buf */ #include /** for jpeg stuff */ #include #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */ #define JFREAD(file,buf,sizeofbuf) \ ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file))) /* * In ANSI C, and indeed any rational implementation, size_t is also the * type returned by sizeof(). However, it seems there are some irrational * implementations out there, in which sizeof() returns an int even though * size_t is defined as long or unsigned long. To ensure consistent results * we always use this SIZEOF() macro in place of using sizeof() directly. */ #define SIZEOF(object) ((size_t) sizeof(object)) extern "C" { /* Expanded data source object for stdio input */ typedef struct { struct jpeg_source_mgr pub; /* public fields */ FILE * infile; /* source stream */ JOCTET * buffer; /* start of buffer */ boolean start_of_file; /* have we gotten any data yet? */ } ossimJpegStdIOSourceMgr; typedef ossimJpegStdIOSourceMgr * ossimJpegStdIOSourceMgrPtr; /* * Initialize source --- called by jpeg_read_header * before any data is actually read. */ void ossimJpegStdIOSrc_init_source (j_decompress_ptr cinfo) { ossimJpegStdIOSourceMgrPtr src = (ossimJpegStdIOSourceMgrPtr) cinfo->src; /* We reset the empty-input-file flag for each image, * but we don't clear the input buffer. * This is correct behavior for reading a series of images from one source. */ src->start_of_file = TRUE; } /* * Fill the input buffer --- called whenever buffer is emptied. * * In typical applications, this should read fresh data into the buffer * (ignoring the current state of next_input_byte & bytes_in_buffer), * reset the pointer & count to the start of the buffer, and return TRUE * indicating that the buffer has been reloaded. It is not necessary to * fill the buffer entirely, only to obtain at least one more byte. * * There is no such thing as an EOF return. If the end of the file has been * reached, the routine has a choice of ERREXIT() or inserting fake data into * the buffer. In most cases, generating a warning message and inserting a * fake EOI marker is the best course of action --- this will allow the * decompressor to output however much of the image is there. However, * the resulting error message is misleading if the real problem is an empty * input file, so we handle that case specially. * * In applications that need to be able to suspend compression due to input * not being available yet, a FALSE return indicates that no more data can be * obtained right now, but more may be forthcoming later. In this situation, * the decompressor will return to its caller (with an indication of the * number of scanlines it has read, if any). The application should resume * decompression after it has loaded more data into the input buffer. Note * that there are substantial restrictions on the use of suspension --- see * the documentation. * * When suspending, the decompressor will back up to a convenient restart point * (typically the start of the current MCU). next_input_byte & bytes_in_buffer * indicate where the restart point will be if the current call returns FALSE. * Data beyond this point must be rescanned after resumption, so move it to * the front of the buffer rather than discarding it. */ boolean ossimJpegStdIOSrc_fill_input_buffer (j_decompress_ptr cinfo) { ossimJpegStdIOSourceMgrPtr src = (ossimJpegStdIOSourceMgrPtr) cinfo->src; size_t nbytes; nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE); if (nbytes <= 0) { if (src->start_of_file) /* Treat empty input file as fatal error */ ERREXIT(cinfo, JERR_INPUT_EMPTY); WARNMS(cinfo, JWRN_JPEG_EOF); /* Insert a fake EOI marker */ src->buffer[0] = (JOCTET) 0xFF; src->buffer[1] = (JOCTET) JPEG_EOI; nbytes = 2; } src->pub.next_input_byte = src->buffer; src->pub.bytes_in_buffer = nbytes; src->start_of_file = FALSE; return TRUE; } /* * Skip data --- used to skip over a potentially large amount of * uninteresting data (such as an APPn marker). * * Writers of suspendable-input applications must note that skip_input_data * is not granted the right to give a suspension return. If the skip extends * beyond the data currently in the buffer, the buffer can be marked empty so * that the next read will cause a fill_input_buffer call that can suspend. * Arranging for additional bytes to be discarded before reloading the input * buffer is the application writer's problem. */ void ossimJpegStdIOSrc_skip_input_data (j_decompress_ptr cinfo, long num_bytes) { ossimJpegStdIOSourceMgrPtr src = (ossimJpegStdIOSourceMgrPtr) cinfo->src; /* Just a dumb implementation for now. Could use fseek() except * it doesn't work on pipes. Not clear that being smart is worth * any trouble anyway --- large skips are infrequent. */ if (num_bytes > 0) { while (num_bytes > (long) src->pub.bytes_in_buffer) { num_bytes -= (long) src->pub.bytes_in_buffer; (void) ossimJpegStdIOSrc_fill_input_buffer(cinfo); /* note we assume that fill_input_buffer will never return FALSE, * so suspension need not be handled. */ } src->pub.next_input_byte += (size_t) num_bytes; src->pub.bytes_in_buffer -= (size_t) num_bytes; } } /* * An additional method that can be provided by data source modules is the * resync_to_restart method for error recovery in the presence of RST markers. * For the moment, this source module just uses the default resync method * provided by the JPEG library. That method assumes that no backtracking * is possible. */ /* * Terminate source --- called by jpeg_finish_decompress * after all data has been read. Often a no-op. * * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding * application must deal with any cleanup that should happen even * for error exit. */ void ossimJpegStdIOSrc_term_source (j_decompress_ptr cinfo) { (void)cinfo; /* no work necessary here */ } /* * Prepare for input from a stdio stream. * The caller must have already opened the stream, and is responsible * for closing it after finishing decompression. */ /* void ossimJpegStdIOSrc (j_decompress_ptr cinfo, FILE * infile) */ void ossimJpegStdIOSrc (jpeg_decompress_struct* cinfo, FILE * infile) { ossimJpegStdIOSourceMgrPtr src; /* The source object and input buffer are made permanent so that a series * of JPEG images can be read from the same file by calling jpeg_stdio_src * only before the first one. (If we discarded the buffer at the end of * one image, we'd likely lose the start of the next one.) * This makes it unsafe to use this manager and a different source * manager serially with the same JPEG object. Caveat programmer. */ if (cinfo->src == NULL) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(ossimJpegStdIOSourceMgr)); src = (ossimJpegStdIOSourceMgrPtr) cinfo->src; src->buffer = (JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, INPUT_BUF_SIZE * SIZEOF(JOCTET)); } src = (ossimJpegStdIOSourceMgrPtr) cinfo->src; src->pub.init_source = ossimJpegStdIOSrc_init_source; src->pub.fill_input_buffer = ossimJpegStdIOSrc_fill_input_buffer; src->pub.skip_input_data = ossimJpegStdIOSrc_skip_input_data; src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ src->pub.term_source = ossimJpegStdIOSrc_term_source; src->infile = infile; src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ src->pub.next_input_byte = NULL; /* until buffer loaded */ } } ossim-Miami-2.9.1/src/imaging/ossimJpegTileSource.cpp000066400000000000000000000511261352751253100225650ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class definition for JpegTileSource. //******************************************************************* // $Id: ossimJpegTileSource.cpp 22117 2013-01-18 21:04:23Z dburken $ #if defined(__BORLANDC__) # include using std::size_t; # include # include #endif extern "C" { #include #include #include } #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //--- // Using windows .NET compiler there is a conflict in the libjpeg with INT32 // in the file jmorecfg.h. Defining XMD_H fixes this. //--- RTTI_DEF1_INST(ossimJpegTileSource, "ossimJpegTileSource", ossimImageHandler) static ossimTrace traceDebug("ossimJpegTileSource:debug"); class ossimJpegTileSource::PrivateData { public: PrivateData() :theCinfo(), theJerr() { } virtual ~PrivateData() { clear(); } void clear() { jpeg_destroy_decompress( &theCinfo ); } struct jpeg_decompress_struct theCinfo; struct jpeg_error_mgr theJerr; }; //******************************************************************* // Public Constructor: //******************************************************************* ossimJpegTileSource::ossimJpegTileSource() : ossimImageHandler(), theTile(0), theCacheTile(0), theLineBuffer(0), theFilePtr(0), theBufferRect(0, 0, 0, 0), theImageRect(0, 0, 0, 0), theNumberOfBands(0), theCacheSize (0), thePrivateData(0), theCacheId(-1) { } //******************************************************************* // Public Constructor: //******************************************************************* ossimJpegTileSource::ossimJpegTileSource(const ossimKeywordlist& kwl, const char* prefix) : ossimImageHandler(), theTile(0), theCacheTile(0), theLineBuffer(0), theFilePtr(0), theBufferRect(0, 0, 0, 0), theImageRect(0, 0, 0, 0), theNumberOfBands(0), theCacheSize (0), thePrivateData(0), theCacheId(-1) { if (loadState(kwl, prefix) == false) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } } //******************************************************************* // Public Constructor: //******************************************************************* ossimJpegTileSource::ossimJpegTileSource(const char* jpeg_file) : ossimImageHandler(), theTile(0), theCacheTile(0), theLineBuffer(0), theFilePtr(0), theBufferRect(0, 0, 0, 0), theImageRect(0, 0, 0, 0), theNumberOfBands(0), theCacheSize(0), thePrivateData(0), theCacheId(-1) { static const char MODULE[] = "ossimJpegTileSource::ossimJpegTileSource"; if (!open()) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << "\nCannot open: " << jpeg_file << endl; } } //******************************************************************* // Destructor: //******************************************************************* ossimJpegTileSource::~ossimJpegTileSource() { destroy(); } void ossimJpegTileSource::destroy() { ossimAppFixedTileCache::instance()->deleteCache(theCacheId); theTile = 0; theCacheTile = 0; if (theLineBuffer) { delete [] theLineBuffer; theLineBuffer = 0; } if (theFilePtr) { fclose(theFilePtr); theFilePtr = NULL; } if(thePrivateData) { delete thePrivateData; thePrivateData = 0; } } void ossimJpegTileSource::allocate() { if(theLineBuffer) { delete [] theLineBuffer; theLineBuffer = 0; } // Make the cache tile the height of one tile by the image width. ossim::defaultTileSize(theCacheSize); theCacheSize.x = theImageRect.width(); ossimAppFixedTileCache::instance()->deleteCache(theCacheId); theCacheId = ossimAppFixedTileCache::instance()->newTileCache(theImageRect, theCacheSize); theTile = ossimImageDataFactory::instance()->create(this, this); theCacheTile = (ossimImageData*)theTile->dup(); theTile->initialize(); ossimIrect cache_rect(theImageRect.ul().x, theImageRect.ul().y, theImageRect.ul().x + (theCacheSize.x-1), theImageRect.ul().y + (theCacheSize.y-1)); theCacheTile->setImageRectangle(cache_rect); theCacheTile->initialize(); theLineBuffer = new ossim_uint8[theImageRect.width() * theNumberOfBands]; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimJpegTileSource::allocate DEBUG:" << "\ncache tile size: " << theCacheSize << "\nimage width: " << theImageRect.width() << "\nimage height: " << theImageRect.height() << "\nnumber of bands: " << theNumberOfBands << endl; } } ossimRefPtr ossimJpegTileSource::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if (theTile.valid()) { // Image rectangle must be set prior to calling getTile. theTile->setImageRectangle(rect); if ( getTile( theTile.get(), resLevel ) == false ) { if (theTile->getDataObjectStatus() != OSSIM_NULL) { theTile->makeBlank(); } } } return theTile; } bool ossimJpegTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) ) { result->ref(); // Increment ref count. //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0. Method returns true on success, false // on error. //--- status = getOverviewTile(resLevel, result); if (!status) // Did not get an overview tile. { status = true; ossimIrect tile_rect = result->getImageRectangle(); if (getImageRectangle(0).intersects(tile_rect)) { // Make a clip rect. ossimIrect clip_rect = tile_rect.clipToRect(getImageRectangle(0)); fillTile(clip_rect, result); } else // No intersection... { result->makeBlank(); } } result->unref(); // Decrement ref count. } return status; } void ossimJpegTileSource::fillTile(const ossimIrect& clip_rect, ossimImageData* tile) { if (!theFilePtr) return; ossimIrect buffer_rect = clip_rect; buffer_rect.stretchToTileBoundary(theCacheSize); buffer_rect.set_ulx(0); buffer_rect.set_lrx(getImageRectangle(0).lr().x); // Check for a partial tile. if ( ! tile->getImageRectangle().completely_within(buffer_rect) ) { tile->makeBlank(); } ossim_int32 number_of_cache_tiles = buffer_rect.height()/theCacheSize.y; #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "tiles high: " << number_of_cache_tiles << endl; } #endif ossimIpt origin = buffer_rect.ul(); for (int tileIdx = 0; tileIdx < number_of_cache_tiles; ++tileIdx) { // See if it's in the cache already. ossimRefPtr tempTile; tempTile = ossimAppFixedTileCache::instance()-> getTile(theCacheId, origin); if (tempTile.valid()) { tile->loadTile(tempTile.get()); } else { // Have to read from the jpeg file. ossim_uint32 start_line = static_cast(origin.y); ossim_uint32 stop_line = static_cast( min(origin.y+theCacheSize.y-1, getImageRectangle().lr().y) ); ossimIrect cache_rect(origin.x, origin.y, origin.x+theCacheSize.x-1, origin.y+theCacheSize.y-1); theCacheTile->setImageRectangle(cache_rect); if ( !theCacheTile->getImageRectangle(). completely_within(getImageRectangle()) ) { theCacheTile->makeBlank(); } if (start_line < thePrivateData->theCinfo.output_scanline) { // Must restart the compression process again. restart(); } // Get pointers to the cache tile buffers. JSAMPROW jbuf[1]; std::vector buf(theNumberOfBands); ossim_uint32 band = 0; for (band = 0; band < theNumberOfBands; ++band) { buf[band] = theCacheTile->getUcharBuf(band); } const ossim_uint32 SAMPLES = getNumberOfSamples(); jbuf[0] = (JSAMPROW) theLineBuffer; // Gobble any not needed lines. while (thePrivateData->theCinfo.output_scanline < start_line) { jpeg_read_scanlines(&thePrivateData->theCinfo, jbuf, 1); } while (thePrivateData->theCinfo.output_scanline <= stop_line) { // Read a line from the jpeg file. jpeg_read_scanlines(&thePrivateData->theCinfo, jbuf, 1); //--- // Copy the line which if band interleaved by pixel the the band // separate buffers. //--- ossim_uint32 index = 0; for (ossim_uint32 sample = 0; sample < SAMPLES; ++sample) { for (band = 0; band < theNumberOfBands; ++band) { buf[band][sample] = theLineBuffer[index]; ++index; } } for (band = 0; band < theNumberOfBands; ++band) { buf[band] += SAMPLES; } } theCacheTile->validate(); tile->loadTile(theCacheTile.get()); // Add it to the cache for the next time. ossimAppFixedTileCache::instance()->addTile(theCacheId, theCacheTile); } // End of reading for jpeg file. origin.y += theCacheSize.y; } // for (int tile = 0; tile < number_of_cache_tiles; ++tile) tile->validate(); } //******************************************************************* // Public Method: //******************************************************************* ossimIrect ossimJpegTileSource::getImageRectangle(ossim_uint32 reduced_res_level) const { return ossimIrect(0, 0, getNumberOfSamples(reduced_res_level) - 1, getNumberOfLines(reduced_res_level) - 1); } //******************************************************************* // Public method: //******************************************************************* bool ossimJpegTileSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimImageHandler::saveState(kwl, prefix); } //******************************************************************* // Public method: //******************************************************************* bool ossimJpegTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (ossimImageHandler::loadState(kwl, prefix)) { return open(); } return false; } void ossimJpegTileSource::close() { destroy(); } //******************************************************************* // Public method: //******************************************************************* bool ossimJpegTileSource::open(const ossimFilename& jpeg_file) { theImageFile = jpeg_file; return open(); } //******************************************************************* // Private method:I have problems //******************************************************************* bool ossimJpegTileSource::open() { static const char MODULE[] = "ossimJpegTileSource::open"; // Start with a clean slate. destroy(); // Check for empty filename. if (theImageFile.empty()) { return false; } // Open Jpeg file. if((theFilePtr = fopen(theImageFile.c_str(), "rb")) == NULL) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "\nERROR:\n" << "Could not open: " << theImageFile.c_str() << endl; } return false; } //*** // Verify the file is a jpeg by checking the first two bytes. //*** ossim_uint8 c[2]; fread(c, 2, 1, theFilePtr); if( c[0] != 0xFF || c[1] != 0xD8 ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " NOTICE:\n" << "Not a jpeg file..." << endl; } fclose(theFilePtr); theFilePtr = NULL; return false; } thePrivateData = new PrivateData(); rewind(theFilePtr); //--- // Step 1: allocate and initialize JPEG decompression object // We set up the normal JPEG error routines, then override error_exit. //--- thePrivateData->theCinfo.err = jpeg_std_error(&thePrivateData->theJerr); // Initialize the JPEG decompression object. jpeg_create_decompress(&thePrivateData->theCinfo); // Specify data source. //jpeg_stdio_src(&thePrivateData->theCinfo, theFilePtr); ossimJpegStdIOSrc(&thePrivateData->theCinfo, theFilePtr); // Read the file parameters with jpeg_read_header. jpeg_read_header(&thePrivateData->theCinfo, TRUE); jpeg_start_decompress(&thePrivateData->theCinfo); theNumberOfBands = thePrivateData->theCinfo.output_components; theImageRect = ossimIrect(0, 0, thePrivateData->theCinfo.output_width - 1, thePrivateData->theCinfo.output_height - 1); theBufferRect.set_lrx(thePrivateData->theCinfo.output_width - 1); completeOpen(); // Allocate memory... allocate(); return true; } ossimRefPtr ossimJpegTileSource::getProperty(const ossimString& name)const { if(name == "file_type") { return new ossimStringProperty("file_type", "JPEG"); } return ossimImageHandler::getProperty(name); } void ossimJpegTileSource::getPropertyNames(std::vector& propertyNames)const { ossimImageHandler::getPropertyNames(propertyNames); propertyNames.push_back("file_type"); } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimJpegTileSource::getTileWidth() const { return ( theTile.valid() ? theTile->getWidth() : 0 ); } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimJpegTileSource::getTileHeight() const { return ( theTile.valid() ? theTile->getHeight() : 0 ); } //******************************************************************* // Public method: //******************************************************************* bool ossimJpegTileSource::isValidRLevel(ossim_uint32 reduced_res_level) const { static const char MODULE[] = "ossimJpegTileSource::isValidRLevel"; if (reduced_res_level == 0) { return true; } else if (theOverview.valid()) { return theOverview->isValidRLevel(reduced_res_level); } else { cerr << MODULE << " Invalid reduced_res_level: " << reduced_res_level << "\nHighest available: " << (getNumberOfDecimationLevels() - 1) << endl; } return false; } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimJpegTileSource::getNumberOfLines(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return theImageRect.lr().y - theImageRect.ul().y + 1; } else if (theOverview.valid()) { return theOverview->getNumberOfLines(reduced_res_level); } return 0; } //******************************************************************* // Public method: //******************************************************************* ossim_uint32 ossimJpegTileSource::getNumberOfSamples(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return theImageRect.lr().x - theImageRect.ul().x + 1;; } else if (theOverview.valid()) { return theOverview->getNumberOfSamples(reduced_res_level); } return 0; } ossim_uint32 ossimJpegTileSource::getImageTileWidth() const { return 0; } ossim_uint32 ossimJpegTileSource::getImageTileHeight() const { return 0; } ossimString ossimJpegTileSource::getShortName()const { return ossimString("jpg"); } ossimString ossimJpegTileSource::getLongName()const { return ossimString("jpg reader"); } ossim_uint32 ossimJpegTileSource::getNumberOfInputBands() const { return theNumberOfBands; } ossim_uint32 ossimJpegTileSource::getNumberOfOutputBands()const { return getNumberOfInputBands(); } ossimScalarType ossimJpegTileSource::getOutputScalarType() const { return OSSIM_UCHAR; } bool ossimJpegTileSource::isOpen()const { return (theFilePtr != NULL); } void ossimJpegTileSource::restart() { jpeg_abort_decompress( &thePrivateData->theCinfo ); jpeg_destroy_decompress( &thePrivateData->theCinfo ); // Put the theFilePtr back to the start... rewind(theFilePtr); // Initialize the JPEG decompression object. jpeg_create_decompress(&thePrivateData->theCinfo); // Specify data source. ossimJpegStdIOSrc(&thePrivateData->theCinfo, theFilePtr); // Read the file parameters with jpeg_read_header. jpeg_read_header(&thePrivateData->theCinfo, TRUE); jpeg_start_decompress(&thePrivateData->theCinfo); } ossimRefPtr ossimJpegTileSource::getImageGeometry() { if ( !theGeometry ) { // Check for external geom: theGeometry = getExternalImageGeometry(); if ( !theGeometry ) { // Check the internal geometry first to avoid a factory call. theGeometry = getInternalImageGeometry(); // At this point it is assured theGeometry is set. //--- // WARNING: // Must create/set theGeometry at this point or the next call to // ossimImageGeometryRegistry::extendGeometry will put us in an infinite loop // as it does a recursive call back to ossimImageHandler::getImageGeometry(). //--- // Check for set projection. if ( !theGeometry->getProjection() ) { // Try factories for projection. ossimImageGeometryRegistry::instance()->extendGeometry(this); } } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } return theGeometry; } ossimRefPtr ossimJpegTileSource::getInternalImageGeometry() const { ossimRefPtr geom = new ossimImageGeometry(); // See if we can pull a projection from the XMP APP1 XML block if present: ossimXmpInfo info; if ( info.open( getFilename() ) ) { ossimDrect imageRect = getImageRectangle( 0 ); ossimRefPtr proj = info.getProjection( imageRect ); if ( proj.valid() ) { geom->setProjection( proj.get() ); } } return geom; } ossim-Miami-2.9.1/src/imaging/ossimJpegWriter.cpp000066400000000000000000000325141352751253100217630ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // //******************************************************************* // $Id: ossimJpegWriter.cpp 22673 2014-03-13 21:42:34Z dburken $ #include #include //--- // Using windows .NET compiler there is a conflict in the libjpeg with INT32 // in the file jmorecfg.h. Defining XMD_H fixes this. extern "C" { #if defined(_MSC_VER) || defined(__MINGW32__) # ifndef XMD_H # define XMD_H # endif #endif #include } #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1_INST(ossimJpegWriter, "ossimJpegWriter", ossimImageFileWriter) static const char DEFAULT_FILE_NAME[] = "output.jpg"; static const ossim_int32 DEFAULT_JPEG_QUALITY = 100; static ossimTrace traceDebug("ossimJpegWriter:debug"); ossimJpegWriter::ossimJpegWriter() : ossimImageFileWriter(), theQuality(DEFAULT_JPEG_QUALITY), theOutputFilePtr(NULL) { // Since there is no internal geometry set the flag to write out one. setWriteExternalGeometryFlag(true); } ossimJpegWriter::~ossimJpegWriter() { close(); } bool ossimJpegWriter::writeFile() { static const char MODULE[] = "ossimJpegWriter::writeFile"; if( !theInputConnection || (getErrorStatus() != ossimErrorCodes::OSSIM_OK)) { return false; } bool bandsDontMatch = false; // Get the number of bands. Must be one or three for this writer. ossim_int32 components = theInputConnection->getNumberOfOutputBands(); ossim_int32 outputComponents = components; if (components != 1 && components != 3) { bandsDontMatch = true; if(components < 3) { outputComponents = 1; } else if(components > 3) { outputComponents = 3; } } if(theInputConnection->isMaster()) { if (!isOpen()) { open(); } if (!theOutputFilePtr) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nCannot open: " << theFilename.c_str() << "\nReturning from method." << endl; return false; } } ossimRefPtr savedInput = 0; if(theInputConnection->getOutputScalarType() != OSSIM_UINT8) { savedInput = new ossimScalarRemapper(); // Connect scalar remapper to sequencer input. savedInput->connectMyInputTo(0, theInputConnection->getInput(0)); // Connect sequencer to the scalar remapper. theInputConnection->connectMyInputTo(0, savedInput.get()); theInputConnection->initialize(); } if(theInputConnection->isMaster()) { if (traceDebug()) { CLOG << " DEBUG:" << "\nOutput Rect: " << theAreaOfInterest << endl; } ossim_int32 image_height = theAreaOfInterest.lr().y - theAreaOfInterest.ul().y + 1; ossim_int32 image_width = theAreaOfInterest.lr().x - theAreaOfInterest.ul().x + 1; ossim_int32 tileWidth = theInputConnection->getTileWidth(); ossim_int32 tileHeight = theInputConnection->getTileHeight(); // Allocate a buffer to hold a row of tiles. ossim_uint32 buf_size = tileHeight*image_width*outputComponents; if (traceDebug()) { CLOG << "DEBUG:" << "\nbuf_size: " << buf_size << endl; } std::vector buf(buf_size); ossimRefPtr blankTile = new ossimImageData(NULL, OSSIM_UINT8, outputComponents, tileWidth, tileHeight); ossimRefPtr tempTile; std::vector tempBuf; if(bandsDontMatch) { tempTile = new ossimImageData(NULL, OSSIM_UINT8, outputComponents, tileWidth, tileHeight); tempTile->initialize(); } blankTile->initialize(); // // Stuff needed for the jpeg library. // Taken from "example.c" file of the "jpeg-6b" package. // struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPROW row_pointer[1]; // pointer to JSAMPLE row[s] // physical row width in image buffer int row_stride = image_width * outputComponents; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_stdio_dest(&cinfo, theOutputFilePtr); cinfo.image_width = image_width; // image width and height, in pixels cinfo.image_height = image_height; cinfo.input_components = outputComponents; // # of color components per pixel // colorspace of input image if (outputComponents == 3) { cinfo.in_color_space = JCS_RGB; } else { cinfo.in_color_space = JCS_GRAYSCALE; } jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, theQuality, TRUE); //limit to baseline-JPEG values jpeg_start_compress(&cinfo, TRUE); theInputConnection->setAreaOfInterest(theAreaOfInterest); theInputConnection->setToStartOfSequence(); ossim_uint32 maxY = theInputConnection->getNumberOfTilesVertical(); ossim_uint32 maxX = theInputConnection->getNumberOfTilesHorizontal(); double tileCount = 0.0; double totalTiles = theInputConnection->getNumberOfTiles(); // // Ok the jpeg stuff should be set. Loop through and grab a row of tiles // and copy to the buffer. Then write the buffer to the jpeg file. // Get the next row... until finished. // for (ossim_uint32 i=0; ((i t = theInputConnection->getNextTile(); if ( t.valid() ) { if (t->getDataObjectStatus() != OSSIM_NULL) { if(bandsDontMatch) { tempTile->setImageRectangle(t->getImageRectangle()); tempTile->setDataObjectStatus(t->getDataObjectStatus()); memcpy(tempTile->getBuf(), t->getBuf(), t->getSizePerBandInBytes()*outputComponents); tempTile->unloadTile(&buf.front(), buf_rect, OSSIM_BIP); } else { // Copy the tile to the buffer. t->unloadTile(&buf.front(), buf_rect, OSSIM_BIP); } } else { blankTile->setOrigin(t->getOrigin()); if(bandsDontMatch) { tempTile->setImageRectangle(blankTile->getImageRectangle()); tempTile->setDataObjectStatus(t->getDataObjectStatus()); memcpy(tempTile->getBuf(), t->getBuf(), t->getSizePerBandInBytes()*outputComponents); blankTile->unloadTile(&buf.front(), buf_rect, OSSIM_BIP); } else { // Copy the tile to the buffer. blankTile->unloadTile(&buf.front(), buf_rect, OSSIM_BIP); } } } ++tileCount; setPercentComplete((100.0*(tileCount/totalTiles))); } // End of loop through tiles in the x direction. // Copy the buffer to the jpeg file. ossim_int32 lines_to_copy = min( (buf_rect.lr().y-buf_rect.ul().y+1), (theAreaOfInterest.lr().y-buf_rect.ul().y+1) ); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "buf_rect: " << buf_rect << "lines_to_copy: " << lines_to_copy << endl; } if(!needsAborting()) { // Now copy the buffer that should be full to the jpeg file. ossim_int32 buf_offset = 0; for (ossim_int32 line=0; lineslaveProcessTiles(); } // Reset the connection if needed. if(savedInput.valid()) { ossimConnectableObject* obj = theInputConnection->getInput(0); if(obj) { theInputConnection->connectMyInputTo(0, obj->getInput(0)); } savedInput = 0; } return true; } bool ossimJpegWriter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add( prefix, ossimKeywordNames::COMPRESSION_QUALITY_KW, theQuality, true ); return ossimImageFileWriter::saveState(kwl, prefix); } bool ossimJpegWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* value = kwl.find(prefix, ossimKeywordNames::COMPRESSION_QUALITY_KW); if(value) { setQuality(atoi(value)); } theOutputImageType = "jpeg"; return ossimImageFileWriter::loadState(kwl, prefix); } void ossimJpegWriter::setQuality(ossim_int32 quality) { static const char MODULE[] = "ossimJpegWriter::setQuality"; // Range 1 to 100 with 100 being best. if (quality > 0 && quality < 101) { theQuality = quality; } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nquality out of range: " << quality << "\nquality has been set to default: " << DEFAULT_JPEG_QUALITY << "\nvalid range: 1 to 100 with 100 being best." << endl; } theQuality = DEFAULT_JPEG_QUALITY; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nQuality set to: " << theQuality << endl; } } bool ossimJpegWriter::isOpen() const { return (theOutputFilePtr!=NULL); } bool ossimJpegWriter::open() { close(); // Check for empty filenames. if (theFilename.empty()) { return false; } theOutputFilePtr = fopen(theFilename.c_str(), "wb"); if(theOutputFilePtr) { return true; } return false; } void ossimJpegWriter::close() { if(theOutputFilePtr) { fclose(theOutputFilePtr); theOutputFilePtr = NULL; } } void ossimJpegWriter::getImageTypeList(std::vector& imageTypeList)const { imageTypeList.push_back(ossimString("jpeg")); } ossimString ossimJpegWriter::getExtension() const { return ossimString("jpg"); } bool ossimJpegWriter::hasImageType(const ossimString& imageType) const { if((imageType == "image/jpeg")|| (imageType == "image/jpg")) { return true; } return ossimImageFileWriter::hasImageType(imageType); } void ossimJpegWriter::setProperty(ossimRefPtr property) { if ( property.valid() ) { if(property->getName() == ossimKeywordNames::COMPRESSION_QUALITY_KW) { ossimString stringValue; property->valueToString(stringValue); setQuality( stringValue.toInt32() ); } else { ossimImageFileWriter::setProperty(property); } } } ossimRefPtr ossimJpegWriter::getProperty(const ossimString& name)const { if (name == ossimKeywordNames::COMPRESSION_QUALITY_KW) { ossimNumericProperty* prop = new ossimNumericProperty(name, ossimString::toString(theQuality), 1.0, 100.0); prop->setNumericType(ossimNumericProperty::ossimNumericPropertyType_INT); return prop; } return ossimImageFileWriter::getProperty(name); } void ossimJpegWriter::getPropertyNames(std::vector& propertyNames)const { ossimString name = ossimKeywordNames::COMPRESSION_QUALITY_KW; propertyNames.push_back(name); ossimImageFileWriter::getPropertyNames(propertyNames); } ossim-Miami-2.9.1/src/imaging/ossimJpegYCbCrToRgbSource.cpp000066400000000000000000000062701352751253100235700ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimJpegYCbCrToRgbSource.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimJpegYCbCrToRgbSource, "ossimJpegYCbCrToRgbSource" , ossimImageSourceFilter) ossimJpegYCbCrToRgbSource::ossimJpegYCbCrToRgbSource() :ossimImageSourceFilter(), theBlankTile() { } ossimJpegYCbCrToRgbSource::ossimJpegYCbCrToRgbSource(ossimImageSource* inputSource) : ossimImageSourceFilter(inputSource), theBlankTile() { } ossimJpegYCbCrToRgbSource::~ossimJpegYCbCrToRgbSource() { } void ossimJpegYCbCrToRgbSource::initialize() { ossimImageSourceFilter::initialize(); } void ossimJpegYCbCrToRgbSource::allocate() { theBlankTile = new ossimImageData(this, OSSIM_UCHAR, 3); } ossimRefPtr ossimJpegYCbCrToRgbSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if (!theBlankTile.valid()) { allocate(); // first time through. } if(theBlankTile.valid()) { theBlankTile->setOrigin(tileRect.ul()); theBlankTile->setWidthHeight(tileRect.width(), tileRect.height()); } if(theInputConnection) { ossimRefPtr imageData = theInputConnection->getTile(tileRect, resLevel); if(!imageData.valid()) { return theBlankTile; } if((isSourceEnabled())&& (imageData->getNumberOfBands()==3)&& (imageData->getScalarType()==OSSIM_UCHAR)&& (imageData->getDataObjectStatus()!=OSSIM_NULL)&& (imageData->getDataObjectStatus()!=OSSIM_EMPTY)) { ossim_uint8* bands[3]; bands[0] = static_cast(imageData->getBuf(0)); bands[1] = static_cast(imageData->getBuf(1)); bands[2] = static_cast(imageData->getBuf(2)); long height = imageData->getHeight(); long width = imageData->getWidth(); long offset = 0; for(long row = 0; row < height; ++row) { for(long col = 0; col < width; ++col) { ossimJpegYCbCrVector ycbcr(bands[0][offset], bands[1][offset], bands[2][offset]); ossimRgbVector rgb(ycbcr); bands[0][offset] = rgb.getR(); bands[1][offset] = rgb.getG(); bands[2][offset] = rgb.getB(); ++offset; } } imageData->validate(); } return imageData; } return theBlankTile; } ossim-Miami-2.9.1/src/imaging/ossimKMeansFilter.cpp000066400000000000000000000311011352751253100222140ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimKMeansFilter, "ossimKMeansFilter", ossimImageSourceFilter); ossimKMeansFilter::ossimKMeansFilter() : ossimImageSourceFilter(), m_numClusters(0), m_tile(0), m_outputScalarType(OSSIM_SCALAR_UNKNOWN), m_initialized(false), m_thresholdMode(NONE) { setDescription("K-Means pixel classification filter."); } ossimKMeansFilter::ossimKMeansFilter(ossimImageSource* input_source, ossimMultiBandHistogram* histogram) : ossimImageSourceFilter(input_source), m_histogram (histogram), m_numClusters(0), m_tile(0), m_outputScalarType(OSSIM_SCALAR_UNKNOWN), m_initialized(false), m_thresholdMode(NONE) { setDescription("K-Means pixel classification filter."); } ossimKMeansFilter::~ossimKMeansFilter() { } void ossimKMeansFilter::setInputHistogram(ossimMultiBandHistogram* histo) { m_histogram = histo; m_initialized = 0; m_thresholds.clear(); } ossimRefPtr ossimKMeansFilter::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection || (m_numClusters == 0)) return 0; if (!m_initialized) { initialize(); if (!m_initialized) return 0; } if (m_classifiers.empty() && !computeKMeans()) return 0; ossimRefPtr inTile = theInputConnection->getTile(tileRect, resLevel); if (!inTile || !inTile->getBuf()) return 0; if(!m_tile) { allocate(); if (!m_tile) return 0; } m_tile->setImageRectangle(tileRect); m_tile->makeBlank(); // Quick handling special case of empty input tile: if (inTile->getDataObjectStatus() == OSSIM_EMPTY) return m_tile; // Since a histogram is being used, the bin value reflects a range: ossimKMeansClustering* bandClusters = 0; const ossimKMeansClustering::Cluster* cluster = 0; ossim_uint8* outBuf; // TODO: Only K < 256 is currently supported double null_pixel = theInputConnection->getNullPixelValue(); double pixel; ossimIpt ipt; ossim_uint32 offset = 0; ossim_uint32 numBands = getNumberOfInputBands(); for (ossim_uint32 band=0; bandgetHistogram(band)->GetBucketSize() / 2.0; bandClusters = m_classifiers[band].get(); outBuf = (ossim_uint8*)(m_tile->getBuf(band)); for (ipt.y=tileRect.ul().y; ipt.y<=tileRect.lr().y; ++ipt.y) { for (ipt.x=tileRect.ul().x; ipt.x<=tileRect.lr().x; ++ipt.x) { pixel = inTile->getPix(ipt, band); if (pixel != null_pixel) { // if thresholding, only interested in the threshold point, not the cluster: if (m_thresholds.size() > band) { if (pixel <= m_thresholds[band]) outBuf[offset] = (ossim_uint8) m_pixelValues[0]; else outBuf[offset] = (ossim_uint8) m_pixelValues[1]; } else { // Determine its group and remap it using the group's DN: for (ossim_uint32 gid=0; gidgetCluster(gid); if (!cluster) continue; if ((pixel >= (cluster->min-delta)) && (pixel <= (cluster->max+delta))) { outBuf[offset] = (ossim_uint8) m_pixelValues[gid]; break; } } } } ++offset; } } } // end loop over bands m_tile->validate(); return m_tile; } void ossimKMeansFilter::allocate() { if (!m_initialized) { initialize(); if (!m_initialized) return; } m_tile = ossimImageDataFactory::instance()->create(this, getNumberOfInputBands(), this); if(!m_tile.valid()) return; ossim_uint32 numBands = getNumberOfInputBands(); if (m_numClusters && (m_classifiers.size() == numBands)) { for (ossim_uint32 band=0; bandgetCluster(0)->min; double max = m_classifiers[band]->getCluster(0)->max; for (ossim_uint32 gid=1; gidgetCluster(gid)->min < min) min = m_classifiers[band]->getCluster(gid)->min; if (m_classifiers[band]->getCluster(gid)->max > max) max = m_classifiers[band]->getCluster(gid)->max; } m_tile->setMinPix(min, band); m_tile->setMaxPix(max, band); } } m_tile->initialize(); } void ossimKMeansFilter::initialize() { // This assigns theInputConnection if one is there. m_initialized = false; ossimImageSourceFilter::initialize(); m_tile = 0; if ( !theInputConnection ) return; // If an input histogram was provided, use it. Otherwise compute one: if (!m_histogram.valid()) { ossimRefPtr histoSource = new ossimImageHistogramSource; histoSource->connectMyInputTo(theInputConnection); histoSource->setComputationMode(OSSIM_HISTO_MODE_FAST); histoSource->setMaxNumberOfRLevels(1); histoSource->execute(); m_histogram = histoSource->getHistogram()->getMultiBandHistogram(0); } if (!m_histogram.valid()) { ostringstream xmsg; xmsg<<"ossimKMeansFilter:"<<__LINE__<<" Could not establish a histogram. Cannot " "initialize filter"; throw ossimException(xmsg.str()); } ossim_uint32 numBands = getNumberOfInputBands(); for (ossim_uint32 band=0; band h = m_histogram->getHistogram(band); m_minPixelValue.push_back(h->GetRangeMin()); m_maxPixelValue.push_back(h->GetRangeMax()); } m_initialized = true; } bool ossimKMeansFilter::computeKMeans() { m_classifiers.clear(); m_thresholds.clear(); ostringstream xmsg; if (m_numClusters == 0) { xmsg<<"ossimKMeansFilter:"<<__LINE__<<" Number of groups has not been initialized!"; throw ossimException(xmsg.str()); } if (!m_initialized) initialize(); ossim_uint32 numBands = getNumberOfInputBands(); for (ossim_uint32 band=0; band band_histo = m_histogram->getHistogram(band); if (!band_histo.valid()) { xmsg<<"ossimKMeansFilter:"<<__LINE__<<" Null band histogram returned!"; throw ossimException(xmsg.str()); } ossimRefPtr classifier = new ossimKMeansClustering; classifier->setVerbose(); classifier->setNumClusters(m_numClusters); classifier->setSamples(band_histo->GetVals(), band_histo->GetRes()); classifier->setPopulations(band_histo->GetCounts(), band_histo->GetRes()); if (!classifier->computeKmeans()) { cout<<"ossimKMeansFilter:"<<__LINE__<<" No K-means clustering data available."<getNumClusters() == 2)) { double mean0 = classifier->getMean(0); double mean1 = classifier->getMean(1); double sigma0 = classifier->getSigma(0); double sigma1 = classifier->getSigma(1); double threshold = 0; switch (m_thresholdMode) { case MEAN: threshold = (mean0 + mean1)/2.0; break; case SIGMA_WEIGHTED: threshold = (sigma1*mean0 + sigma0*mean1)/(sigma0 + sigma1); break; case VARIANCE_WEIGHTED: threshold = (sigma1*sigma1*mean0 + sigma0*sigma0*mean1)/(sigma0*sigma0 + sigma1*sigma1); break; default: break; } m_thresholds.push_back(threshold); cout<<"ossimKMeansFilter:"<<__LINE__<<" Using threshold = "< 255) { ostringstream xmsg; xmsg << "ossimKMeansFilter:"<<__LINE__<<" Requested K="< 1) { keybase1 = "band"; keybase1 += ossimString::toString(band) + "."; } // Need bin size of histogram since only center values were used in clustering: bandClusters = m_classifiers[band].get(); for (ossim_uint32 gid=0; gid < m_numClusters; ++gid) { keybase2 = keybase1; keybase2 += "cluster"; keybase2 += ossimString::toString(gid); cluster = bandClusters->getCluster(gid); key = keybase2 + ".mean"; kwl.add(prefix, key.chars(), cluster->mean); key = keybase2 + ".sigma"; kwl.add(prefix, key.chars(), cluster->sigma); key = keybase2 + ".min"; kwl.add(prefix, key.chars(), cluster->min); key = keybase2 + ".max"; kwl.add(prefix, key.chars(), cluster->max); } } bool rtn_stat = ossimImageSourceFilter::saveState(kwl, prefix); return rtn_stat; } bool ossimKMeansFilter::loadState(const ossimKeywordlist& orig_kwl, const char* prefix) { bool return_state = true; //ossimKeywordlist kwl (orig_kwl); // need non-const copy // TODO: Need to implement return_state &= ossimImageSourceFilter::loadState(orig_kwl, prefix); return return_state; } ossimScalarType ossimKMeansFilter::getOutputScalarType() const { ossimScalarType myType = OSSIM_SCALAR_UNKNOWN; if (m_numClusters > 255) myType = OSSIM_UINT16; // Can't have more than 65535 groups! NOT YET SUPPORTED else if (m_numClusters > 0) myType = OSSIM_UINT8; return myType; } double ossimKMeansFilter::getMinPixelValue(ossim_uint32 band)const { if (band < m_minPixelValue.size()) return m_minPixelValue[band]; return 1; } double ossimKMeansFilter::getMaxPixelValue(ossim_uint32 band)const { if (band < m_maxPixelValue.size()) return m_maxPixelValue[band]; return 255.0; } ossim-Miami-2.9.1/src/imaging/ossimKakaduCompressorInterface.cpp000066400000000000000000000005531352751253100247750ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Interface for Kakadu compressor. // //--- // $Id$ #include //--- // Explicit constructor. Fix for undefine in kakadu plugin, windows vs14 debug // configuration. //--- ossimKakaduCompressorInterface::ossimKakaduCompressorInterface() { } ossim-Miami-2.9.1/src/imaging/ossimLandsatTileSource.cpp000066400000000000000000000321401352751253100232610ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class implementaiton for the class "ossim LandsatTileSource". // //******************************************************************* // $Id: ossimLandsatTileSource.cpp 21512 2012-08-22 11:53:57Z dburken $ #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1_INST(ossimLandsatTileSource, "ossimLandsatTileSource", ossimGeneralRasterTileSource) static ossimTrace traceDebug("ossimLandsatTileSource:debug"); //******************************************************************* // Public Constructor: //******************************************************************* ossimLandsatTileSource::ossimLandsatTileSource() : ossimGeneralRasterTileSource(), theFfHdr(NULL) { } //******************************************************************* // Public Constructor: //******************************************************************* ossimLandsatTileSource::ossimLandsatTileSource(const ossimKeywordlist& kwl, const char* prefix) : ossimGeneralRasterTileSource(), theFfHdr(NULL) { if (loadState(kwl, prefix) == false) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } } //******************************************************************* // Destructor: //******************************************************************* ossimLandsatTileSource::~ossimLandsatTileSource() { theFfHdr = NULL; } bool ossimLandsatTileSource::open() { static const char MODULE[] = "ossimLandsatTileSource::open"; if (traceDebug()) { CLOG << " Entered..." << std::endl << " trying to open file " << theImageFile << std::endl; } ossimFilename tempFilename = theImageFile; // See if the file passed in is a header file. openHeader(theImageFile); if (!theFfHdr) return false; // Start building the keyword list for the general raster base class. ossimKeywordlist kwl; //*** // There can be up to seven (six for L7) files that belong to the header. // Note that it seems the file names in the header are always upper case. // So test the file given to us to see if they should be downcased. This // is assuming that all files in the directory have the same case. //*** vector fileList; for (ossim_uint32 i=0; igetBandCount(); ++i) { bool addFile = false; ossimFilename f1 = theFfHdr->getBandFilename(i); if (f1.trim() != "") { // Make the file name. ossimFilename f2 = theImageFile.path(); f2 = f2.dirCat(f1); if (f2.exists()) { addFile = true; } else { // Try it downcased... f2 = theImageFile.path(); f1.downcase(); f2 = f2.dirCat(f1); if (f2.exists()) { addFile = true; } else { // Try is upcased... f2 = theImageFile.path(); f1.upcase(); f2 = f2.dirCat(f1); if (f2.exists()) { addFile = true; } } } if (addFile) { if (traceDebug()) { CLOG << "\nAdding file: " << f2 << std::endl; } fileList.push_back(f2); } else { if (traceDebug()) { f2 = theImageFile.path(); f1 = theFfHdr->getBandFilename(i); f1.trim(); f2 = f2.dirCat(f1); CLOG << "\nCould not find: " << f2 << std::endl; } } } } if(fileList.size() == 0) { close(); return false; } ossimGeneralRasterInfo generalRasterInfo(fileList, OSSIM_UINT8, OSSIM_BSQ_MULTI_FILE, (ossim_uint32)fileList.size(), theFfHdr->getLinesPerBand(), theFfHdr->getPixelsPerLine(), 0, ossimGeneralRasterInfo::NONE, 0); if(fileList.size() == 1) { generalRasterInfo = ossimGeneralRasterInfo(fileList, OSSIM_UINT8, OSSIM_BSQ, (ossim_uint32)fileList.size(), theFfHdr->getLinesPerBand(), theFfHdr->getPixelsPerLine(), 0, ossimGeneralRasterInfo::NONE, 0); } theMetaData.clear(); theMetaData.setScalarType(OSSIM_UINT8); theMetaData.setNumberOfBands((ossim_uint32)fileList.size()); m_rasterInfo = generalRasterInfo; if(initializeHandler()) { theImageFile = tempFilename; completeOpen(); } else { if (traceDebug()) CLOG << " Exited..." << std::endl; return false; } if (traceDebug()) CLOG << " Exited..." << std::endl; return true; } void ossimLandsatTileSource::openHeader(const ossimFilename& file) { //*** // Landsat file name example: l71024031_03119990929_hpn.fst // Three header header file type substrings: // HPN = Pan // HRF = VNIR/SWIR (visible near infrared/shortwave infrared) // HTM = Thermal //*** ossimFilename hdr = file.file(); hdr.downcase(); theFfHdr = 0; if ( hdr.contains("hpn") || hdr.contains("hrf") || hdr.contains("htm") ) { theFfHdr = new ossimFfL7(file.c_str()); } else if (hdr.contains("header.dat")) { theFfHdr = new ossimFfL5(file.c_str()); } else { theFfHdr = 0; return; } if (theFfHdr->getErrorStatus() != ossimErrorCodes::OSSIM_OK) { theFfHdr = 0; } return; // I had to force the open to go with a header since there are duplicate entries when scanning // landsat directories. // For now I am commenting this code out. // #if 0 //*** // User may have passed in an image file name in which case the header file // must be derived from it. //*** if (hdr.size() < 25) { // file name not long enough... if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimLandsatTileSource::openHeader DEBUG:" << "\nNot a standard landsat 7 file name: " << hdr << std::endl; return; } } char substr[4]; const char* f = hdr.c_str(); strncpy(substr, (f+22), 3); substr[3] = '\0'; ossimString s1 = substr; ossimString s2; s1.downcase(); if (s1 == "b80") { s2 = "hpn"; } else if (s1 == "b61" || s1 == "b62") { s2 = "htm"; } else if (s1 == "b10" || s1 == "b20" || s1 == "b30" || s1 == "b40" || s1 == "b50" || s1 == "b70") { s2 = "hrf"; } else { // Not of any format we know of... if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimLandsatTileSource::openHeader DEBUG:" << "\nCould not derive header name from: " << file << std::endl; } return; } // Set the case to be the same as the file passed in. if (substr[0] == 0x42) // ascii "B" { s1.upcase(); s2.upcase(); hdr.upcase(); // Header files alway start with "L71" hdr = hdr.substitute(ossimString("L72"), ossimString("L71")); } else { // Header files alway start with "l71" hdr = hdr.substitute(ossimString("l72"), ossimString("l71")); } // Make the hdr file name. hdr = hdr.substitute(s1, s2); ossimFilename f1 = file.drive(); f1 += file.path(); hdr = f1.dirCat(hdr); theFfHdr = new ossimFfL7(hdr.c_str()); if (theFfHdr->getErrorStatus() != ossimErrorCodes::OSSIM_OK) { delete theFfHdr; theFfHdr = NULL; } #endif } ossimRefPtr ossimLandsatTileSource::getImageGeometry() { if ( !theGeometry ) { // Check for external geom: theGeometry = getExternalImageGeometry(); if ( !theGeometry ) { theGeometry = new ossimImageGeometry(); if ( theFfHdr.valid() ) { // Make a model ossimLandSatModel* model = new ossimLandSatModel (*theFfHdr); if (model->getErrorStatus() == ossimErrorCodes::OSSIM_OK) { //initialize the image geometry object with the model theGeometry->setProjection(model); } } //--- // WARNING: // Must create/set the geometry at this point or the next call to // ossimImageGeometryRegistry::extendGeometry will put us in an infinite loop // as it does a recursive call back to ossimImageHandler::getImageGeometry(). //--- // Check for set projection. if ( !theGeometry->getProjection() ) { // Try factories for projection. ossimImageGeometryRegistry::instance()->extendGeometry(this); } } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } return theGeometry; } bool ossimLandsatTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if (lookup) { ossimFilename fileName = lookup; ossimString ext = fileName.ext(); if((ext.upcase() == "FST") || (ext.upcase() == "DAT")) { //--- // This will call: // ossimImageHandler::loadState() the open() //--- if (ossimGeneralRasterTileSource::loadState(kwl, prefix)) { return true; } } } return false; } ossimRefPtr ossimLandsatTileSource::getProperty( const ossimString& name)const { ossimRefPtr result = 0; if(name == "file_type") { if(ossimString(getFilename()).downcase().contains("header")) { return (new ossimStringProperty(name, "landsat5")); } else { return (new ossimStringProperty(name, "landsat7")); } } else if (theFfHdr.valid()) { result = theFfHdr->getProperty(name); } if ( result.valid() == false ) { result = ossimGeneralRasterTileSource::getProperty(name); } return result; } void ossimLandsatTileSource::getPropertyNames( std::vector& propertyNames)const { propertyNames.push_back("file_type"); if (theFfHdr.valid()) { theFfHdr->getPropertyNames(propertyNames); } ossimGeneralRasterTileSource::getPropertyNames(propertyNames); } ossimString ossimLandsatTileSource::getShortName() const { return ossimString("Landsat"); } ossimString ossimLandsatTileSource::getLongName() const { return ossimString("Landsat reader"); } double ossimLandsatTileSource::getNullPixelValue(ossim_uint32)const { return 0.0; } double ossimLandsatTileSource::getMinPixelValue(ossim_uint32)const { return 1.0; } double ossimLandsatTileSource::getMaxPixelValue(ossim_uint32)const { return 255.0; } ossimScalarType ossimLandsatTileSource::getOutputScalarType() const { return OSSIM_UINT8; } bool ossimLandsatTileSource::getAcquisitionDate(ossimDate& date)const { if(!theFfHdr) return false; theFfHdr->getAcquisitionDate(date); return true; } ossimString ossimLandsatTileSource::getSatelliteName()const { if(!theFfHdr) return ""; return theFfHdr->getSatelliteName(); } ossimFilename ossimLandsatTileSource::getBandFilename(ossim_uint32 idx)const { ossim_uint32 maxIdx = getNumberOfInputBands(); if(!theFfHdr||(idx > maxIdx)) { return ""; } ossimFilename path = getFilename().path(); ossimString filename = theFfHdr->getBandFilename(idx); filename = filename.trim(); ossimFilename file = path.dirCat(filename); if (file.exists()) { return file; } // Try downcased name. file = path.dirCat(filename.downcase()); if (file.exists()) { return file; } // Try upcase name. file = path.dirCat(filename.upcase()); if (file.exists()) { return file; } return ossimFilename(); } bool ossimLandsatTileSource::isPan()const { return (getNumberOfInputBands() == 1); } bool ossimLandsatTileSource::isVir()const { return (getNumberOfInputBands() == 6); } bool ossimLandsatTileSource::isTm()const { return (getNumberOfInputBands() == 2); } ossim-Miami-2.9.1/src/imaging/ossimLandsatTopoCorrectionFilter.cpp000066400000000000000000000335211352751253100253260ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimLandsatTopoCorrectionFilter.cpp 21850 2012-10-21 20:09:55Z dburken $ #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimLandsatTopoCorrectionFilter, "ossimLandsatTopoCorrectionFilter",ossimTopographicCorrectionFilter); ossimLandsatTopoCorrectionFilter::ossimLandsatTopoCorrectionFilter() :ossimTopographicCorrectionFilter(), theLandsatHeader("") { } ossimLandsatTopoCorrectionFilter::~ossimLandsatTopoCorrectionFilter() { } ossimLandsatTopoCorrectionFilter::ossimLandsatTopoCorrectionFilter(ossimImageSource* colorSource, ossimImageSource* elevSource, const ossimFilename& landsatFileName) :ossimTopographicCorrectionFilter(colorSource, elevSource), theLandsatHeader(landsatFileName) { } void ossimLandsatTopoCorrectionFilter::initialize() { ossimTopographicCorrectionFilter::initialize(); if(theLandsatHeader == "") { setLandsatHeader(findLandsatHeader()); } else { setLandsatHeader(theLandsatHeader); } } void ossimLandsatTopoCorrectionFilter::setLandsatHeader(const ossimFilename& header) { if(header != "") { theLandsatHeader = header; ossimRefPtr headerL7 = new ossimFfL7(header.c_str()); headerL7->getGain(theGain); headerL7->getBias(theBias); headerL7->getSunElevation(theLightSourceElevationAngle); headerL7->getSunAzimuth(theLightSourceAzimuthAngle); computeLightDirection(); theJulianDay = headerL7->getJulianDay(); } } ossimFilename ossimLandsatTopoCorrectionFilter::findLandsatHeader() { ossimFilename result; if(!getInput(0)) { return result; } ossimTypeNameVisitor visitor(ossimString("ossimImageHandler"), true, ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS); getInput(0)->accept(visitor); // If there are multiple image handlers, e.g. a mosaic do not uses. ossimRefPtr handler = 0; if ( visitor.getObjects().size() == 1 ) { handler = visitor.getObjectAs( 0 ); } if( handler.valid() ) { ossimFilename imageFile = handler->getFilename(); imageFile.setExtension("fst"); if(imageFile.exists()) { result = imageFile; } else { imageFile.setExtension("FST"); if(imageFile.exists()) { result = imageFile; } else { ossimDirectory dir; if(dir.open(imageFile.path())) { vector fileList; dir.findAllFilesThatMatch(fileList, ".*.fst"); if(fileList.size() <1) { dir.findAllFilesThatMatch(fileList, ".*.FST"); } for(int i = 0; i < (int)fileList.size(); ++i) { if(fileList[i].contains("_hpn")|| fileList[i].contains("_hrf")|| fileList[i].contains("_htm")) { result = fileList[i]; break; } } } } } } return result; } // void ossimLandsatTopoCorrectionFilter::addRegressionPoints(std::vector& regressionPoints, // ossimImageData* colorData, // ossimImageData* normalData) // { // ossim_uint32 b = 0; // for(b = 0; b < colorData->getNumberOfBands(); ++b) // { // ossim_float64* normalBands[3]; // normalBands[0] = normalData->getBuf(0); // normalBands[1] = normalData->getBuf(1); // normalBands[2] = normalData->getBuf(2); // ossim_float64* colorData = // } #if 0 void ossimLandsatTopoCorrectionFilter::computeC() { theCComputedFlag = false; ossim_uint32 totalNumberOfPixelsUsed = 0; if(getInput(0)&&getInput(1)) { std::vector linearRegression(6); ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); ossimImageSource* normalSource = PTR_CAST(ossimImageSource, getInput(1)); ossimFfL7 headerL7(theLandsatHeader.c_str()); if(theLandsatHeader == "") { ossimNotify(ossimNotifyLevel_WARN) << "No landsat header found " << std::endl; return; } if(colorSource->getNumberOfOutputBands() < 6) { ossimNotify(ossimNotifyLevel_WARN) << "The color source needs all the vir bands from the landsat" << std::endl << "Not enough bands to process the request" << std::endl; return; } ossimIrect normalRect = normalSource->getBoundingRect(); ossimIrect colorRect = colorSource->getBoundingRect(); ossimIrect clipRect = normalRect.clipToRect(colorRect); ossimIpt ul = clipRect.ul(); ossimIpt lr = clipRect.lr(); long julianDay = headerL7.getJulianDay(); double d2 =pow( (double)(1 - 0.01674 * ossim::cosd(0.9856*(julianDay-4)) ), 2.0); ossim_uint32 numberOfPixelsUsedForTile = 0; for(int y = ul.y; ((y < lr.y)&&(totalNumberOfPixelsUsed<1000));++y) { for(int x = ul.x; ((x < lr.x)&&(totalNumberOfPixelsUsed<1000)); ++x) { ossimIrect reqRect(x, y, x + 127, y + 127); ossimIrect reqClip = reqRect.clipToRect(clipRect); ossimImageData* colorData = colorSource->getTile(reqClip, 0); ossimImageData* normalData = normalSource->getTile(reqClip, 0); ossim_uint8* colorBands[6]; double* normalBands[3]; double normalBandsNp[3]; ossim_uint8 colorBandsNp[6]; colorBands[0] = (ossim_uint8*)colorData->getBuf(0); colorBands[1] = (ossim_uint8*)colorData->getBuf(1); colorBands[2] = (ossim_uint8*)colorData->getBuf(2); colorBands[3] = (ossim_uint8*)colorData->getBuf(3); colorBands[4] = (ossim_uint8*)colorData->getBuf(4); colorBands[5] = (ossim_uint8*)colorData->getBuf(5); colorBandsNp[0] = (ossim_uint8)colorData->getNullPix(0); colorBandsNp[1] = (ossim_uint8)colorData->getNullPix(1); colorBandsNp[2] = (ossim_uint8)colorData->getNullPix(2); colorBandsNp[3] = (ossim_uint8)colorData->getNullPix(3); colorBandsNp[4] = (ossim_uint8)colorData->getNullPix(4); colorBandsNp[5] = (ossim_uint8)colorData->getNullPix(5); normalBands[0] = (double*)normalData->getBuf(0); normalBands[1] = (double*)normalData->getBuf(1); normalBands[2] = (double*)normalData->getBuf(2); normalBandsNp[0] = normalData->getNullPix(0); normalBandsNp[1] = normalData->getNullPix(1); normalBandsNp[2] = normalData->getNullPix(2); ossim_uint32 offset = 0; ossim_uint32 numberOfPixels = reqClip.width()*reqClip.height(); numberOfPixelsUsedForTile = 0; for(offset = 0; ((offset < numberOfPixels)&&(numberOfPixelsUsedForTile < 10)); ++offset) { if((*colorBands[0] != colorBandsNp[0])&& (*colorBands[1] != colorBandsNp[1])&& (*colorBands[2] != colorBandsNp[2])&& (*colorBands[3] != colorBandsNp[3])&& (*colorBands[4] != colorBandsNp[4])&& (*colorBands[5] != colorBandsNp[5])&& (*normalBands[0] != normalBandsNp[0])&& (*normalBands[1] != normalBandsNp[1])&& (*normalBands[2] != normalBandsNp[2])) { double ndviTest = (((double)*colorBands[3] - (double)*colorBands[2])/ ((double)*colorBands[3] + (double)*colorBands[2])); if(ndviTest > 0.0) { double radiance5 = theBias[5]+(*colorBands[5]*theGain[5]); // double p = (M_PI*radiance5*d2)/(esun[5]*cosd(90-theLightSourceAzimuthAngle)); // if(p < .05) { double cosineI = ((*normalBands[0])*theLightDirection[0] + (*normalBands[1])*theLightDirection[1] + (*normalBands[2])*theLightDirection[2]); double radiance0 = theBias[0]+(*colorBands[0]*theGain[0]); double radiance1 = theBias[1]+(*colorBands[1]*theGain[1]); double radiance2 = theBias[2]+(*colorBands[2]*theGain[2]); double radiance3 = theBias[3]+(*colorBands[3]*theGain[3]); double radiance4 = theBias[4]+(*colorBands[4]*theGain[4]); cosineI = fabs(cosineI); if(cosineI > 1.0) cosineI = 1.0; if(cosineI < 0.0) cosineI = 0.0; cosineI = acos(cosineI); // // linearRegression[0].addPoint(ossimDpt( cosineI,(double)(*colorBands[0]))); // // linearRegression[1].addPoint(ossimDpt( cosineI,(double)(*colorBands[1]))); // // linearRegression[2].addPoint(ossimDpt( cosineI,(double)(*colorBands[2]))); // // linearRegression[3].addPoint(ossimDpt( cosineI,(double)(*colorBands[3]))); // // linearRegression[4].addPoint(ossimDpt( cosineI,(double)(*colorBands[4]))); // // linearRegression[5].addPoint(ossimDpt( cosineI,(double)(*colorBands[5]))); linearRegression[0].addPoint(ossimDpt( cosineI,radiance0)); linearRegression[1].addPoint(ossimDpt( cosineI,radiance1)); linearRegression[2].addPoint(ossimDpt( cosineI,radiance2)); linearRegression[3].addPoint(ossimDpt( cosineI,radiance3)); linearRegression[4].addPoint(ossimDpt( cosineI,radiance4)); linearRegression[5].addPoint(ossimDpt( cosineI,radiance5)); ++numberOfPixelsUsedForTile; ++totalNumberOfPixelsUsed; } } } ++colorBands[0]; ++colorBands[1]; ++colorBands[2]; ++colorBands[3]; ++colorBands[4]; ++colorBands[5]; ++normalBands[0]; ++normalBands[1]; ++normalBands[2]; } } } if(totalNumberOfPixelsUsed > 2) { linearRegression[0].solve(); linearRegression[1].solve(); linearRegression[2].solve(); linearRegression[3].solve(); linearRegression[4].solve(); linearRegression[5].solve(); ossimNotify(ossimNotifyLevel_INFO) << "linear regression results = " << endl << linearRegression[0] << endl << linearRegression[1] << endl << linearRegression[2] << endl << linearRegression[3] << endl << linearRegression[4] << endl << linearRegression[5] << endl; double b,m; linearRegression[0].getEquation(m, b); theC[0] = b/m; linearRegression[1].getEquation(m, b); theC[1] = b/m; linearRegression[2].getEquation(m, b); theC[2] = b/m; linearRegression[3].getEquation(m, b); theC[3] = b/m; linearRegression[4].getEquation(m, b); theC[4] = b/m; linearRegression[5].getEquation(m, b); theC[5] = b/m; } else { ossimNotify(ossimNotifyLevel_INFO) << "No points found in regression test" << endl; } } else { ossimNotify(ossimNotifyLevel_WARN) << "No input connected to the ossimLandsatTopoCorrectionFilter" << std::endl; return; } theCComputedFlag = true; } #endif bool ossimLandsatTopoCorrectionFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimTopographicCorrectionFilter::loadState(kwl, prefix); const char* filename = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if(filename) { setLandsatHeader(filename); } return true; } bool ossimLandsatTopoCorrectionFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimTopographicCorrectionFilter::saveState(kwl, prefix); kwl.add(prefix, ossimKeywordNames::FILENAME_KW, theLandsatHeader.c_str(), true); return true; } ossim-Miami-2.9.1/src/imaging/ossimLasReader.cpp000066400000000000000000001062441352751253100215450ustar00rootroot00000000000000//--- // // File: ossimLasReader.cpp // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: OSSIM LAS LIDAR reader. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimLasReader, "ossimLasReader", ossimImageHandler) static ossimTrace traceDebug("ossimLasReader:debug"); static const char GSD_KW[] = "gsd"; static const char SCAN_KW[] = "scan"; // boolean ossimLasReader::ossimLasReader() : ossimImageHandler(), m_str(), m_hdr(0), m_proj(0), m_ul(), m_lr(), m_maxZ(0.0), m_minZ(0.0), m_gsd(), m_tile(0), m_entry(0), m_mutex(), m_scan(false), // ??? m_units(OSSIM_METERS), m_unitConverter(0) { //--- // Nan out as can be set in several places, i.e. setProperty, // loadState and initProjection. //--- m_gsd.makeNan(); } ossimLasReader::~ossimLasReader() { close(); } bool ossimLasReader::open() { static const char M[] = "ossimLasReader::open"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\nfile: " << theImageFile << "\n"; } bool result = false; close(); m_str.open(theImageFile.c_str(), std::ios_base::in | std::ios_base::binary); if ( m_str.good() ) { m_hdr = new ossimLasHdr(); if ( m_hdr->checkSignature( m_str ) ) { m_str.seekg(0, std::ios_base::beg); m_hdr->readStream(m_str); ossim_uint32 dataFormatId = m_hdr->getPointDataFormatId(); if ( (dataFormatId == 0) || (dataFormatId == 1) || (dataFormatId == 2) || (dataFormatId == 3) || (dataFormatId == 4) ) { result = init(); if ( result ) { establishDecimationFactors(); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << *m_hdr << "\n"; } } } else { if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Unhandled point type: " << int(m_hdr->getPointDataFormatId()) << "\n"; } } if ( traceDebug() && result ) { ossimNotify(ossimNotifyLevel_DEBUG) << *m_hdr << "\n"; } } // if ( m_hdr->checkSignature( m_str ) ) } // if ( m_str.good() ) if ( !result ) close(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exit status = " << (result?"true\n":"false\n"); } return result; } void ossimLasReader::completeOpen() { establishDecimationFactors(); } void ossimLasReader::close() { if ( isOpen() ) { m_str.close(); delete m_hdr; m_hdr = 0; m_entry = 0; m_tile = 0; m_proj = 0; ossimImageHandler::close(); } } ossimRefPtr ossimLasReader::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { if ( m_tile.valid() == false ) { initTile(); // First time through. } if ( m_tile.valid() ) { // Image rectangle must be set prior to calling getTile. m_tile->setImageRectangle(tile_rect); if ( getTile( m_tile.get(), resLevel ) == false ) { if (m_tile->getDataObjectStatus() != OSSIM_NULL) { m_tile->makeBlank(); } } } return m_tile; } bool ossimLasReader::getTile(ossimImageData* result, ossim_uint32 resLevel) { // static const char MODULE[] = "ossimLibLasReader::getTile(ossimImageData*, level)"; bool status = false; if ( m_hdr && result && (result->getScalarType() == OSSIM_FLOAT32||result->getScalarType() == OSSIM_UINT16) && (result->getDataObjectStatus() != OSSIM_NULL) && !m_ul.hasNans() && !m_gsd.hasNans() ) { status = true; const ossimIrect TILE_RECT = result->getImageRectangle(); const ossim_int32 TILE_HEIGHT = static_cast(TILE_RECT.height()); const ossim_int32 TILE_WIDTH = static_cast(TILE_RECT.width()); const ossim_int32 TILE_SIZE = static_cast(TILE_RECT.area()); // Get the scale for this resLevel: ossimDpt scale; getScale(scale, resLevel); // Set the starting upper left of upper left pixel for this tile. const ossimDpt UL_PROG_PT( m_ul.x - scale.x / 2.0 + TILE_RECT.ul().x * scale.x, m_ul.y + scale.y / 2.0 - TILE_RECT.ul().y * scale.y); //const ossimDpt UL_PROG_PT( m_ul.x + TILE_RECT.ul().x * scale.x, // m_ul.y + scale.y / 2.0 - TILE_RECT.ul().y * scale.y); //--- // Set the lower right to the edge of the tile boundary. This looks like an // "off by one" error but it's not. We want the ossimDrect::pointWithin to // catch any points in the last line sample. //--- const ossimDpt LR_PROG_PT( UL_PROG_PT.x + TILE_WIDTH * scale.x, UL_PROG_PT.y - TILE_HEIGHT * scale.y); const ossimDrect PROJ_RECT(UL_PROG_PT, LR_PROG_PT, OSSIM_RIGHT_HANDED); #if 0 /* Please leave for debug. (drb) */ cout << "m_ul: " << m_ul << "\nm_gsd: " << m_gsd << "\nscale: " << scale << "\nresult->getScalarType(): " << result->getScalarType() << "\nresult->getDataObjectStatus(): " << result->getDataObjectStatus() << "\nPROJ_RECT: " << PROJ_RECT << "\nTILE_RECT: " << TILE_RECT << "\nUL_PROG_PT: " << UL_PROG_PT << endl; #endif const ossim_float64 SCALE_X = m_hdr->getScaleFactorX(); const ossim_float64 SCALE_Y = m_hdr->getScaleFactorY(); const ossim_float64 SCALE_Z = m_hdr->getScaleFactorZ(); const ossim_float64 OFFSET_X = m_hdr->getOffsetX(); const ossim_float64 OFFSET_Y = m_hdr->getOffsetY(); const ossim_float64 OFFSET_Z = m_hdr->getOffsetZ(); // Create array of buckets. std::vector bucket( TILE_SIZE ); // Loop through the point data. ossimLasPointRecordInterface* lasPtRec = getNewPointRecord(); ossimDpt lasPt; m_str.clear(); m_str.seekg(m_hdr->getOffsetToPointData()); while ( m_str.good() ) { // m_str.read((char*)lasPtRec, 28); lasPtRec->readStream( m_str ); //if ( lasPtRec->getReturnNumber() == ENTRY ) //{ lasPt.x = lasPtRec->getX() * SCALE_X + OFFSET_X; lasPt.y = lasPtRec->getY() * SCALE_Y + OFFSET_Y; if ( m_unitConverter ) { convertToMeters(lasPt.x); convertToMeters(lasPt.y); } if ( PROJ_RECT.pointWithin( lasPt ) ) { // Compute the bucket index: ossim_int32 line = static_cast((UL_PROG_PT.y - lasPt.y) / scale.y); ossim_int32 samp = static_cast((lasPt.x - UL_PROG_PT.x) / scale.x ); ossim_int32 bucketIndex = line * TILE_WIDTH + samp; // Range check and add if in there. if ( ( bucketIndex >= 0 ) && ( bucketIndex < TILE_SIZE ) ) { ossim_float64 z = lasPtRec->getZ() * SCALE_Z + OFFSET_Z; if ( m_unitConverter ) convertToMeters(z); bucket[bucketIndex].add( z ); bucket[bucketIndex].setRed(lasPtRec->getRed()); bucket[bucketIndex].setGreen(lasPtRec->getGreen()); bucket[bucketIndex].setBlue(lasPtRec->getBlue()); bucket[bucketIndex].setIntensity(lasPtRec->getIntensity()); } } //} if ( m_str.eof() ) break; } delete lasPtRec; lasPtRec = 0; //--- // We must always blank out the tile as we may not have a point for every // point. //--- result->makeBlank(); //ossim_float32* buf = result->getFloatBuf(); // Tile buffer to fill. if(m_entry == 1) { const ossim_uint32 BANDS = getNumberOfOutputBands(); std::vector tempBuf(TILE_SIZE * BANDS); ossim_uint16* buffer = &tempBuf.front(); for (ossim_uint32 band = 0; band < BANDS; ++band) { for (ossim_int32 i = 0; i < TILE_SIZE; ++i) { if(band == 0) buffer[i] = bucket[i].getRed(); if(band == 1) buffer[i] = bucket[i].getGreen(); if(band == 2) buffer[i] = bucket[i].getBlue(); } } result->loadTile(buffer, TILE_RECT, TILE_RECT, OSSIM_BIP); } else if (m_entry == 2) { ossim_uint16* buf = result->getUshortBuf(); for (ossim_int32 i = 0; i < TILE_SIZE; ++i) { buf[i] = bucket[i].getIntensity(); } } else { ossim_float32* buf = result->getFloatBuf(); // Fill the tile. Currently no band loop: for (ossim_int32 i = 0; i < TILE_SIZE; ++i) { buf[i] = bucket[i].getValue(); } } // Revalidate. result->validate(); } return status; } // End: bool ossimLibLasReader::getTile(ossimImageData* result, ossim_uint32 resLevel) ossim_uint32 ossimLasReader::getNumberOfInputBands() const { return 1; // tmp } ossim_uint32 ossimLasReader::getNumberOfOutputBands() const { if(m_entry == 1) return 3; return 1; } ossim_uint32 ossimLasReader::getNumberOfLines(ossim_uint32 resLevel) const { ossim_uint32 result = 0; if ( isOpen() ) { result = static_cast(ceil((m_ul.y - m_lr.y) / m_gsd.y)); if (resLevel) result = (result>>resLevel); } return result; } ossim_uint32 ossimLasReader::getNumberOfSamples(ossim_uint32 resLevel) const { ossim_uint32 result = 0; if ( isOpen() ) { result = static_cast(ceil((m_lr.x - m_ul.x) / m_gsd.x)); if (resLevel) result = (result>>resLevel); } return result; } ossim_uint32 ossimLasReader::getImageTileWidth() const { return 0; } ossim_uint32 ossimLasReader::getImageTileHeight() const { return 0; } ossim_uint32 ossimLasReader::getTileWidth() const { ossimIpt ipt; ossim::defaultTileSize(ipt); return ipt.x; } ossim_uint32 ossimLasReader::getTileHeight() const { ossimIpt ipt; ossim::defaultTileSize(ipt); return ipt.y; } ossimScalarType ossimLasReader::getOutputScalarType() const { //return OSSIM_FLOAT32; ossimScalarType stype = OSSIM_FLOAT32; if(m_entry == 1 || m_entry == 2) stype = OSSIM_UINT16; return stype; } void ossimLasReader::getEntryList(std::vector& entryList)const { if ( isOpen() ) { entryList.push_back(0); entryList.push_back(1); entryList.push_back(2); //for ( ossim_uint32 entry = 0; entry < 15; ++entry ) //{ // if ( m_hdr->getNumberOfPoints(entry) ) entryList.push_back(entry); //} } else { entryList.clear(); } } ossim_uint32 ossimLasReader::getCurrentEntry() const { return static_cast(m_entry); } bool ossimLasReader::setCurrentEntry(ossim_uint32 entryIdx) { bool result = false; if ( isOpen() ) { std::vector entryList; getEntryList( entryList ); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { if ( (*i) == entryIdx ) { m_entry = entryIdx; result = true; } ++i; } } if(result) initTile(); return result; } ossimString ossimLasReader::getShortName() const { return ossimString("las"); } ossimString ossimLasReader::getLongName() const { return ossimString("ossim las reader"); } ossimRefPtr ossimLasReader::getImageGeometry() { if ( !theGeometry ) { // Check for external geom: theGeometry = getExternalImageGeometry(); if ( theGeometry.valid() == true ) { // Picked up an external geometry file(dot.geom). m_proj = theGeometry->getProjection(); ossimRefPtr proj = dynamic_cast( m_proj.get() ); if ( proj.valid() == true ) { // Set the units: if ( proj->isGeographic() ) { m_units = OSSIM_DEGREES; } else { // Currently hard coding to meters. May need to add property to override this. m_units = OSSIM_METERS; } // Call initValues to set the tie point / bounds: initValues(); // Set the tie and gsd: if ( proj->isGeographic() ) { m_units = OSSIM_DEGREES; ossimGpt gpt(m_ul.y, m_ul.x, 0.0, proj->getDatum() ); proj->setUlTiePoints( gpt ); theGeometry->getDegreesPerPixel( m_gsd ); } else { // Currently hard coding to meters. May need to add property to override this. m_units = OSSIM_METERS; proj->setUlTiePoints(m_ul); theGeometry->getMetersPerPixel( m_gsd ); } ossimIpt imgSize; imgSize.x = (ossim_int32)getNumberOfSamples(0); imgSize.y = (ossim_int32)getNumberOfLines(0); theGeometry->setImageSize( imgSize ); } } if ( !theGeometry ) { theGeometry = new ossimImageGeometry(); if ( m_proj.valid() ) { theGeometry->setProjection( m_proj.get() ); } else { //--- // WARNING: // Must create/set theGeometry at this point or the next call to // ossimImageGeometryRegistry::extendGeometry will put us in an infinite loop // as it does a recursive call back to ossimImageHandler::getImageGeometry(). //--- // Try factories for projection. ossimImageGeometryRegistry::instance()->extendGeometry(this); } } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } return theGeometry; } double ossimLasReader::getMinPixelValue(ossim_uint32 /* band */) const { return m_minZ; } double ossimLasReader::getMaxPixelValue(ossim_uint32 /* band */) const { return m_maxZ; } double ossimLasReader::getNullPixelValue(ossim_uint32 /* band */) const { return -99999.0; } ossim_uint32 ossimLasReader::getNumberOfDecimationLevels() const { // Can support any number of rlevels. ossim_uint32 result = 1; const ossim_uint32 STOP_DIMENSION = 16; ossim_uint32 largestImageDimension = getNumberOfSamples(0) > getNumberOfLines(0) ? getNumberOfSamples(0) : getNumberOfLines(0); while(largestImageDimension > STOP_DIMENSION) { largestImageDimension /= 2; ++result; } return result; } bool ossimLasReader::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add( prefix, GSD_KW, m_gsd.toString().c_str(), true ); kwl.add( prefix, SCAN_KW, ossimString::toString(m_scan).c_str(), true ); return ossimImageHandler::saveState(kwl, prefix); } bool ossimLasReader::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; if ( ossimImageHandler::loadState(kwl, prefix) ) { result = open(); if ( result ) { // Get our keywords: const char* lookup = kwl.find(prefix, GSD_KW); if ( lookup ) { m_gsd.toPoint( ossimString(lookup) ); } lookup = kwl.find(prefix, SCAN_KW); if ( lookup ) { ossimString s = lookup; m_scan = s.toBool(); } } } return result; } void ossimLasReader::setProperty(ossimRefPtr property) { if ( property.valid() ) { if ( property->getName() == GSD_KW ) { ossimString s; property->valueToString(s); ossim_float64 d = s.toFloat64(); if ( ossim::isnan(d) == false ) { setGsd( d ); } } else if ( property->getName() == SCAN_KW ) { ossimString s; property->valueToString(s); m_scan = s.toBool(); } else { ossimImageHandler::setProperty(property); } } } ossimRefPtr ossimLasReader::getProperty(const ossimString& name)const { ossimRefPtr prop = 0; if ( name == GSD_KW ) { ossimString value = ossimString::toString(m_gsd.x); prop = new ossimStringProperty(name, value); } else if ( name == SCAN_KW ) { prop = new ossimBooleanProperty(name, m_scan); } else { prop = ossimImageHandler::getProperty(name); } return prop; } void ossimLasReader::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back( ossimString(GSD_KW) ); propertyNames.push_back( ossimString(SCAN_KW) ); ossimImageHandler::getPropertyNames(propertyNames); } bool ossimLasReader::init() { bool result = false; if ( isOpen() ) { // Check for external geometry file for projection stuff. ossimFilename geomFile; getFilenameWithThisExt( ossimString(".geom" ), geomFile ); if ( geomFile.exists() == true ) { // Call get image geometry to initialize ourself. ossimRefPtr geom = getImageGeometry(); if ( geom.valid() == true ) { // Check for map projection. ossimRefPtr proj = geom->getProjection(); if ( proj.valid() == true ) { if ( dynamic_cast( proj.get() ) ) { result = true; } } } } if ( !result ) { // Check for option var record. result = parseVarRecords(); if ( !result ) { // Checks for external FGDC text file. result = initFromExternalMetadata(); } } } return result; } bool ossimLasReader::initProjection() { bool result = true; ossimMapProjection* proj = dynamic_cast( m_proj.get() ); if ( proj ) { //--- // Set the tie and scale: // Note the scale can be set in other places so only set here if it // has nans. //--- if ( proj->isGeographic() ) { ossimGpt gpt(m_ul.y, m_ul.x, 0.0, proj->getDatum() ); proj->setUlTiePoints( gpt ); if ( m_gsd.hasNans() ) { m_gsd = proj->getDecimalDegreesPerPixel(); if ( m_gsd.hasNans() || !m_gsd.x || !m_gsd.y ) { // Set to some default: m_gsd.x = 0.000008983; // About 1 meter at the Equator. m_gsd.y = m_gsd.x; proj->setDecimalDegreesPerPixel( m_gsd ); } } } else { proj->setUlTiePoints(m_ul); if ( m_gsd.hasNans() ) { m_gsd = proj->getMetersPerPixel(); if ( m_gsd.hasNans() || !m_gsd.x || !m_gsd.y ) { // Set to some default: m_gsd.x = 1.0; m_gsd.y = 1.0; proj->setMetersPerPixel( m_gsd ); } } } } else { result = false; m_ul.makeNan(); m_lr.makeNan(); m_gsd.makeNan(); ossimNotify(ossimNotifyLevel_WARN) << "ossimLasReader::initProjection WARN Could not cast to map projection!" << std::endl; } return result; } // bool ossimLasReader::initProjection() void ossimLasReader::initTile() { ossim_uint32 BANDS = getNumberOfOutputBands(); m_tile = new ossimImageData(this, getOutputScalarType(), BANDS, getTileWidth(), getTileHeight()); for(ossim_uint32 band = 0; band < BANDS; ++band) { if (m_entry == 0 || m_entry == 1) { m_tile->setMinPix(getMinPixelValue(band), band); m_tile->setMaxPix(getMaxPixelValue(band), band); m_tile->setNullPix(getNullPixelValue(band), band); } } m_tile->initialize(); } void ossimLasReader::initUnits(const ossimKeywordlist& geomKwl) { ossimMapProjection* proj = dynamic_cast( m_proj.get() ); if ( proj ) { if ( proj->isGeographic() ) { m_units = OSSIM_DEGREES; } else { const char* lookup = geomKwl.find("image0.linear_units"); if ( lookup ) { std::string units = lookup; if ( units == "meters" ) { m_units = OSSIM_METERS; } else if ( units == "feet" ) { m_units = OSSIM_FEET; } else if ( units == "us_survey_feet" ) { m_units = OSSIM_US_SURVEY_FEET; } else { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimLibLasReader::initUnits WARN:\n" << "Unhandled linear units code: " << units << std::endl; } } } } // Don't make a unit converter for decimal degrees... if ( (m_units != OSSIM_DEGREES) && (m_units != OSSIM_METERS) && !m_unitConverter ) { m_unitConverter = new ossimUnitConversionTool(); } } void ossimLasReader::initValues() { static const char M[] = "ossimLasReader::initValues"; if ( m_scan ) { // Set to bogus values to start. m_ul.x = numeric_limits::max(); m_ul.y = numeric_limits::min(); m_lr.x = numeric_limits::min(); m_lr.y = numeric_limits::max(); m_maxZ = numeric_limits::min(); m_minZ = numeric_limits::max(); const ossim_float64 SCALE_X = m_hdr->getScaleFactorX(); const ossim_float64 SCALE_Y = m_hdr->getScaleFactorY(); const ossim_float64 SCALE_Z = m_hdr->getScaleFactorZ(); const ossim_float64 OFFSET_X = m_hdr->getOffsetX(); const ossim_float64 OFFSET_Y = m_hdr->getOffsetY(); const ossim_float64 OFFSET_Z = m_hdr->getOffsetZ(); ossimLasPointRecordInterface* lasPtRec = getNewPointRecord(); m_str.clear(); m_str.seekg(m_hdr->getOffsetToPointData()); ossim_float64 x; ossim_float64 y; ossim_float64 z; while ( m_str.good() ) { lasPtRec->readStream( m_str ); #if 0 /* Please leave for debug. (drb) */ lasPtRec->print( ossimNotify(ossimNotifyLevel_DEBUG) ); #endif x = lasPtRec->getX() * SCALE_X + OFFSET_X; y = lasPtRec->getY() * SCALE_Y + OFFSET_Y; z = lasPtRec->getZ() * SCALE_Z + OFFSET_Z; //std::cout << "X: " << lasPtRec->getX() << " SCALE: " << SCALE_X << " OFFSET: " << OFFSET_X << " XNORM: " << x << std::endl; //std::cout << "Y: " << lasPtRec->getY() << " SCALE: " << SCALE_Y << " OFFSET: " << OFFSET_Y << " YNORM: " << y << std::endl; //std::cout << "Z: " << lasPtRec->getZ() << " SCALE: " << SCALE_Z << " OFFSET: " << OFFSET_Z << " ZNORM: " << z << std::endl; if ( x < m_ul.x ) m_ul.x = x; if ( x > m_lr.x ) m_lr.x = x; if ( y > m_ul.y ) m_ul.y = y; if ( y < m_lr.y ) m_lr.y = y; if ( z > m_maxZ ) m_maxZ = z; if ( z < m_minZ ) m_minZ = z; if ( m_str.eof() ) break; } delete lasPtRec; lasPtRec = 0; } else { // Set the upper left (tie). m_ul.x = m_hdr->getMinX(); m_ul.y = m_hdr->getMaxY(); // Set the lower right. m_lr.x = m_hdr->getMaxX(); m_lr.y = m_hdr->getMinY(); // Set the min/max: m_minZ = m_hdr->getMinZ(); m_maxZ = m_hdr->getMaxZ(); } if ( m_unitConverter ) // Need to convert to meters. { convertToMeters(m_ul.x); convertToMeters(m_ul.y); convertToMeters(m_lr.x); convertToMeters(m_lr.y); convertToMeters(m_maxZ); convertToMeters(m_minZ); } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " DEBUG:\nBounds from header:"; ossimDpt pt; pt.x = m_hdr->getMinX(); pt.y = m_hdr->getMaxY(); if ( m_unitConverter ) { convertToMeters(pt.x); convertToMeters(pt.y); } ossimNotify(ossimNotifyLevel_DEBUG) << "\nul: " << pt; pt.x = m_hdr->getMaxX(); pt.y = m_hdr->getMinY(); if ( m_unitConverter ) { convertToMeters(pt.x); convertToMeters(pt.y); } ossimNotify(ossimNotifyLevel_DEBUG) << "\nlr: " << pt; pt.x = m_hdr->getMinZ(); pt.y = m_hdr->getMaxZ(); if ( m_unitConverter ) { convertToMeters(pt.x); convertToMeters(pt.y); } ossimNotify(ossimNotifyLevel_DEBUG) << "\nminZ: " << pt.x << "\nmaxZ: " << pt.y << "\n"; if ( m_scan ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Bounds from scan:" << "\nul: " << m_ul << "\nlr: " << m_lr << "\nminZ: " << m_minZ << "\nmaxZ: " << m_maxZ << "\n"; } } } bool ossimLasReader::parseVarRecords() { static const char M[] = "ossimLasReader::parseVarRecords"; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; bool result = false; if ( isOpen() ) { std::streampos origPos = m_str.tellg(); std::streamoff pos = static_cast(m_hdr->getHeaderSize()); m_str.clear(); m_str.seekg(pos, std::ios_base::beg); ossim_uint32 vlrCount = m_hdr->getNumberOfVlrs(); ossim_uint16 reserved; char uid[17]; uid[16]='\n'; ossim_uint16 recordId; ossim_uint16 length; char des[33]; des[32] = '\n'; //--- // Things we need to save for printGeoKeys: //--- ossim_uint16* geoKeyBlock = 0; ossim_uint64 geoKeyLength = 0; ossim_float64* geoDoubleBlock = 0; ossim_uint64 geoDoubleLength = 0; ossim_int8* geoAsciiBlock = 0; ossim_uint64 geoAsciiLength = 0; ossimEndian* endian = 0; // LAS LITTLE ENDIAN: if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { endian = new ossimEndian; } for ( ossim_uint32 i = 0; i < vlrCount; ++i ) { m_str.read((char*)&reserved, 2); m_str.read(uid, 16); m_str.read((char*)&recordId, 2); m_str.read((char*)&length, 2); m_str.read(des, 32); // LAS LITTLE ENDIAN: if ( endian ) { endian->swap(recordId); endian->swap(length); } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "uid: " << uid << "\nrecordId: " << recordId << "\nlength: " << length << "\ndes: " << des << std::endl; } if (recordId == 34735) // GeoTiff projection keys. { geoKeyLength = length/2; if ( geoKeyBlock ) { delete [] geoKeyBlock; } geoKeyBlock = new ossim_uint16[geoKeyLength]; m_str.read((char*)geoKeyBlock, length); if ( endian ) { endian->swap(geoKeyBlock, geoKeyLength); } } else if (recordId == 34736) // GeoTiff double parameters. { geoDoubleLength = length/8; if ( geoDoubleBlock ) { delete [] geoDoubleBlock; } geoDoubleBlock = new ossim_float64[geoDoubleLength]; m_str.read((char*)geoDoubleBlock, length); if ( endian ) { endian->swap(geoDoubleBlock, geoDoubleLength); } } else if (recordId == 34737) // GeoTiff ascii block. { geoAsciiLength = length; if (geoAsciiBlock) { delete [] geoAsciiBlock; } geoAsciiBlock = new ossim_int8[length]; m_str.read((char*)geoAsciiBlock, length); } else { m_str.seekg(length, ios_base::cur); } } //--- // Must have at mimimum the geoKeyBlock for a projection. // Note the geoDoubleBlock is needed for some. // Note the geoAsciiBlock is not needed, i.e. only informational. //--- if ( geoKeyBlock ) { //--- // Give the geokeys to ossimTiffInfo to get back a keyword list that can be fed to // ossimProjectionFactoryRegistry::createProjection //--- ossimTiffInfo info; ossimKeywordlist geomKwl; info.getImageGeometry(geoKeyLength, geoKeyBlock, geoDoubleLength,geoDoubleBlock, geoAsciiLength,geoAsciiBlock, geomKwl); // Create the projection. m_proj = ossimProjectionFactoryRegistry::instance()->createProjection(geomKwl); if (m_proj.valid()) { // Units must be set before initValues and initProjection. initUnits(geomKwl); // Must be called before initProjection. initValues(); result = initProjection(); // Sets the ties and scale... if (traceDebug()) { m_proj->print(ossimNotify(ossimNotifyLevel_DEBUG)); } } } else { /* Current data samples appear to be UTM but not sure where to find the zone const char* prefix = "image0."; // Build a default projection ossimKeywordlist geomKwl; geomKwl.add(prefix, "datum", "WGE", true); geomKwl.add(prefix, "pixel_type", "pixel_is_area", true); geomKwl.add(prefix, "type", "ossimEquDistCylProjection", true); m_proj = ossimProjectionFactoryRegistry::instance()->createProjection(geomKwl); if(m_proj.valid()) { initUnits(geomKwl); initValues(); result = initProjection(); // Sets the ties and scale... if (traceDebug()) { m_proj->print(ossimNotify(ossimNotifyLevel_DEBUG)); } } */ } if ( geoKeyBlock ) { delete [] geoKeyBlock; geoKeyBlock = 0; } if (geoDoubleBlock) { delete [] geoDoubleBlock; geoDoubleBlock = 0; } if (geoAsciiBlock) { delete [] geoAsciiBlock; geoAsciiBlock = 0; } m_str.seekg(origPos); if ( endian ) { delete endian; endian = 0; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exit status = " << (result?"true\n":"false\n"); } return result; } bool ossimLasReader::initFromExternalMetadata() { static const char M[] = "ossimLasReader::initFromExternalMetadata"; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; bool result = false; ossimFilename fgdcFile = theImageFile; fgdcFile.setExtension("txt"); if ( fgdcFile.exists() == false ) { fgdcFile.setExtension("TXT"); } if ( fgdcFile.exists() ) { ossimRefPtr fgdcDoc = new ossimFgdcTxtDoc(); if ( fgdcDoc->open( fgdcFile ) ) { fgdcDoc->getProjection( m_proj ); if ( m_proj.valid() ) { // Units must be set before initValues and initProjection. std::string units; fgdcDoc->getAltitudeDistanceUnits(units); if ( ( units == "feet" ) || ( units == "international feet" ) ) { m_units = OSSIM_FEET; } else if ( units == "survey feet" ) { m_units = OSSIM_US_SURVEY_FEET; } else { m_units = OSSIM_METERS; } // Must be called before initProjection. initValues(); result = initProjection(); // Sets the ties and scale... if (traceDebug()) { m_proj->print(ossimNotify(ossimNotifyLevel_DEBUG)); } } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exit status = " << (result?"true\n":"false\n"); } return result; } ossimLasPointRecordInterface* ossimLasReader::getNewPointRecord() const { ossimLasPointRecordInterface* result = 0; switch(m_hdr->getPointDataFormatId()) { case 0: { result = new ossimLasPointRecord0(); break; } case 1: { result = new ossimLasPointRecord1(); break; } case 2: { result = new ossimLasPointRecord2(); break; } case 3: { result = new ossimLasPointRecord3(); break; } case 4: { result = new ossimLasPointRecord4(); break; } default: { break; } } return result; } void ossimLasReader::getScale(ossimDpt& scale, ossim_uint32 resLevel) const { // std::pow(2.0, 0) returns 1. ossim_float64 d = std::pow(2.0, static_cast(resLevel)); scale.x = m_gsd.x * d; scale.y = m_gsd.y * d; } void ossimLasReader::setGsd( const ossim_float64& gsd ) { m_gsd.x = gsd; m_gsd.y = m_gsd.x; if ( m_proj.valid() && ( m_gsd.hasNans() == false ) ) { ossimMapProjection* proj = dynamic_cast( m_proj.get() ); if ( proj && ( m_gsd.hasNans() == false ) ) { if ( proj->isGeographic() ) { proj->setDecimalDegreesPerPixel( m_gsd ); } else { proj->setMetersPerPixel( m_gsd ); } } } } ossim-Miami-2.9.1/src/imaging/ossimLinearStretchRemapper.cpp000066400000000000000000000155541352751253100241510ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //************************************************************************* #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimLinearStretchRemapper, "ossimLinearRemapper", ossimImageSourceFilter); static const char* MIN_VALUE_KW = "min_value"; static const char* MAX_VALUE_KW = "max_value"; ossimLinearStretchRemapper::ossimLinearStretchRemapper() { setDescription("Remaps input from min-max to full range (0-1) of normalized float.."); } ossimLinearStretchRemapper::~ossimLinearStretchRemapper() { } ossimRefPtr ossimLinearStretchRemapper::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) return 0; ossimRefPtr tile = theInputConnection->getTile(tileRect, resLevel); if ( !theEnableFlag ) return tile; if (!tile || !tile->getBuf()) return 0; if(!m_tile) { initialize(); if (!m_tile) return 0; } m_tile->setImageRectangle(tileRect); m_tile->makeBlank(); // Quick handling special case of empty input tile: if (tile->getDataObjectStatus() == OSSIM_EMPTY) return m_tile; ossim_uint32 maxLength = tile->getWidth()*tile->getHeight(); double pixel; double null_pixel = theInputConnection->getNullPixelValue(); ossim_uint32 numBands = theInputConnection->getNumberOfOutputBands(); for (int i=0; igetDoubleBuf(i); for (ossim_uint32 offset=0; offsetgetScalarType()) { case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: pixel = tile->getDoubleBuf(i)[offset]; break; case OSSIM_SSHORT16: pixel = (double)(tile->getSshortBuf(i)[offset]); break; case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: pixel = (double)(tile->getFloatBuf(i)[offset]); break; case OSSIM_UCHAR: pixel = (double)(tile->getUcharBuf(i)[offset]); break; case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: pixel = (double)(tile->getUshortBuf(i)[offset]); break; default: break; } // Do not remap null pixels, leave the output pixel "blank" which is null-pixel value: if (pixel == null_pixel) continue; // Do linear remap: pixel = (pixel-m_minValues[i])/delta; if (pixel < 0.0) pixel = 0.0; if (pixel > 1.0) pixel = 1.0; outBuf[offset] = pixel; } } m_tile->validate(); return m_tile; } void ossimLinearStretchRemapper::allocate() { if(!theInputConnection) return; m_tile = ossimImageDataFactory::instance()->create(this, OSSIM_NORMALIZED_DOUBLE, theInputConnection->getNumberOfOutputBands(), theInputConnection->getTileWidth(), theInputConnection->getTileHeight()); if(m_tile.valid()) { m_tile->initialize(); } } void ossimLinearStretchRemapper::initialize() { // This assigns theInputConnection if one is there. ossimImageSourceFilter::initialize(); m_tile = 0; if ( theInputConnection ) { // Initialize the chain on the left hand side of us. //theInputConnection->initialize(); This is done by base class int numBands = theInputConnection->getNumberOfOutputBands(); if ((m_minValues.size() != numBands) && (m_maxValues.size() != numBands)) { m_minValues.resize(numBands); m_maxValues.resize(numBands); for (int i=0; igetMinPixelValue(i); m_maxValues[i] = theInputConnection->getMaxPixelValue(i); } } allocate(); } } bool ossimLinearStretchRemapper::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool rtn_stat = true; ostringstream minstr, maxstr; int numBands = m_minValues.size(); if ((numBands == 0) || (numBands != m_maxValues.size())) rtn_stat = false; for (int i=0; i minimums; vector maximums; ossimString minVals = kwl.find(prefix, MIN_VALUE_KW); ossimString maxVals = kwl.find(prefix, MAX_VALUE_KW); if(!minVals.empty() && !maxVals.empty()) { minimums = minVals.split(" "); maximums = maxVals.split(" "); if (minimums.size() != maximums.size()) return false; for (int i=0; i #include #include #include #include #include #include RTTI_DEF2(ossimLocalCorrelationFusion, "ossimLocalCorrelationFusion", ossimFusionCombiner, ossimAdjustableParameterInterface); static const ossim_uint32 REGRESSION_COEFFICIENT_ATTENUATOR_OFFSET = 0; static const ossim_uint32 REGRESSION_COEFFICIENT_CLAMP_OFFSET = 1; static const ossim_uint32 HIGH_PASS_GAIN_OFFSET = 2; static const ossim_uint32 PAN_BLURR_WIDTH_OFFSET = 3; static const ossim_uint32 NUMBER_OF_ADJUSTABLE_PARAMETERS = 4; ossimLocalCorrelationFusion::ossimLocalCorrelationFusion() :theBlurrKernelWidth(1.5), theHighPassKernelWidth(3), theRegressionWidth(5) { theLowPassFilter = new ossimImageGaussianFilter; theHighPassFilter = new ossimConvolutionSource; setFilters(); initAdjustableParameters(); } ossimLocalCorrelationFusion::~ossimLocalCorrelationFusion() { } ossimRefPtr ossimLocalCorrelationFusion::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { if(!theInputConnection) { return ossimRefPtr(); } if (!theIntensityConnection) { return theInputConnection->getTile(rect, resLevel); } ossim_int32 regressionW2 = (ossim_int32)ceil(theRegressionWidth/2.0); ossimIrect expandedRegressionRect(rect.ul().x - regressionW2, rect.ul().y - regressionW2, rect.lr().x + regressionW2, rect.lr().y + regressionW2); if(!theNormLowPassTile.valid()) { theNormLowPassTile = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT, 1, expandedRegressionRect.width(), expandedRegressionRect.height()); theNormHighPassTile = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT, 1, expandedRegressionRect.width(), expandedRegressionRect.height()); theNormLowPassTile->initialize(); theNormHighPassTile->initialize(); theNormLowPassTile->makeBlank(); theNormHighPassTile->makeBlank(); } theNormLowPassTile->setImageRectangle(expandedRegressionRect); theNormHighPassTile->setImageRectangle(expandedRegressionRect); theNormLowPassTile->makeBlank(); theNormHighPassTile->makeBlank(); if(!theLowPassFilter->getInput() && getInput()) { initialize(); } ossimRefPtr lowTile = theLowPassFilter->getTile(expandedRegressionRect, resLevel); ossimRefPtr highTile = theHighPassFilter->getTile(expandedRegressionRect, resLevel); // ossimRefPtr highTile = getNormIntensity(expandedRegressionRect, resLevel); ossimIpt ul = rect.ul(); ossimIpt origin; // if we don't have valid low and high pass then return the input color tile // in its original format // if(!lowTile.valid()||!highTile.valid()) { return theInputConnection->getTile(rect, resLevel); } if((lowTile->getDataObjectStatus() == OSSIM_EMPTY)|| (!lowTile->getBuf()) || (highTile->getDataObjectStatus() == OSSIM_EMPTY)|| (!highTile->getBuf())) { return theInputConnection->getTile(rect, resLevel); } ossimRefPtr normColorData = getNormTile(expandedRegressionRect, resLevel); ossim_uint32 y = 0; ossim_uint32 x = 0; ossim_uint32 w = theTile->getWidth(); ossim_uint32 h = theTile->getHeight(); theTile->makeBlank(); theTile->setImageRectangle(rect); if(!normColorData.valid()) { return 0; // return theTile; } if((normColorData->getDataObjectStatus() == OSSIM_EMPTY)|| !normColorData->getBuf()) { return theTile; } ossimRefPtr normColorOutputData = (ossimImageData*)normColorData->dup(); normColorOutputData->setImageRectangle(rect); normColorOutputData->loadTile(normColorData.get()); ossim_float64 slopeResult = 0.0; ossim_uint32 idx = 0; std::vector bands(normColorData->getNumberOfBands()); lowTile->copyTileToNormalizedBuffer((ossim_float32*)theNormLowPassTile->getBuf()); highTile->copyTileToNormalizedBuffer((ossim_float32*)theNormHighPassTile->getBuf()); theNormLowPassTile->validate(); theNormHighPassTile->validate(); ossimRefPtr lowPan = (ossimImageData*)theNormLowPassTile->dup(); lowPan->setImageRectangle(rect); lowPan->loadTile(theNormLowPassTile.get()); ossimRefPtr highPan = (ossimImageData*)theNormHighPassTile->dup(); highPan->setImageRectangle(rect); highPan->loadTile(theNormHighPassTile.get()); ossim_float32* panHigh = (ossim_float32*)highPan->getBuf(); ossim_float32* panLow = (ossim_float32*)lowPan->getBuf(); for(idx = 0; idx < bands.size(); ++idx) { bands[idx] = (ossim_float32*)normColorOutputData->getBuf(idx); } double panAttenuator = computeParameterOffset(REGRESSION_COEFFICIENT_ATTENUATOR_OFFSET); double delta = 0.0; ossim_uint32 bandsSize = (ossim_uint32)bands.size(); ossim_float64 slopeClamp = computeParameterOffset(REGRESSION_COEFFICIENT_CLAMP_OFFSET); ossim_float64 minSlope = -slopeClamp; ossim_float64 maxSlope = slopeClamp; for(y = 0; y < h; ++y) { origin.y = ul.y + y; for(x = 0; x < w; ++x) { origin.x = ul.x + x; // if(computeRegression(slopeResult, // origin, // theNormLowPassTile, // normColorData, // 0)) // { // delta = panAttenuator*slopeResult*(*panHigh - *panLow); for(idx = 0; idx < bandsSize; ++idx) { if(*bands[idx] != 0.0) // if band is not null { if(computeRegression(slopeResult, origin, theNormLowPassTile, normColorData, idx)) { if(slopeResult < minSlope) slopeResult = minSlope; if(slopeResult > maxSlope) slopeResult = maxSlope; delta = panAttenuator*slopeResult*(*panHigh - *panLow); ossim_float32 normMinPix = (ossim_float32)normColorOutputData->getMinPix(idx); *bands[idx] += delta; if(*bands[idx] > 1.0) *bands[idx] = 1.0; if(*bands[idx] < normMinPix) *bands[idx] = normMinPix; } } ++bands[idx]; } ++panHigh; ++panLow; } } theTile->copyNormalizedBufferToTile((ossim_float32*)normColorOutputData->getBuf()); theTile->validate(); return theTile; } void ossimLocalCorrelationFusion::initialize() { ossimFusionCombiner::initialize(); if(!theIntensityConnection) { theLowPassFilter->disconnect(); theHighPassFilter->disconnect(); } else { theLowPassFilter->connectMyInputTo(0, PTR_CAST(ossimConnectableObject, theIntensityConnection->getObject())); theHighPassFilter->connectMyInputTo(0, PTR_CAST(ossimConnectableObject, theIntensityConnection->getObject())); setFilters(); theLowPassFilter->initialize(); theHighPassFilter->initialize(); } } void ossimLocalCorrelationFusion::setFilters() { theLowPassFilter->setGaussStd(theBlurrKernelWidth); theHighPassMatrix = NEWMAT::Matrix(theHighPassKernelWidth, theHighPassKernelWidth); theHighPassMatrix = 0; theHighPassMatrix[theHighPassKernelWidth>>1][theHighPassKernelWidth>>1] = 1; // adjust the gain for the high pass filter // NEWMAT::Matrix high = theHighPassMatrix; ossim_float64 kernelW2 = theHighPassKernelWidth*theHighPassKernelWidth; double gain = computeParameterOffset(HIGH_PASS_GAIN_OFFSET)*(kernelW2); double multiplier = gain/(kernelW2); high = -multiplier; ossim_int32 cx = theHighPassKernelWidth>>1; ossim_int32 cy = theHighPassKernelWidth>>1; if(gain > FLT_EPSILON) { high[cy][cx] = multiplier* ( (kernelW2-1)+kernelW2/gain); } else { high = 0.0; high[cy][cx] = 1.0; } theHighPassFilter->setConvolution(high); } bool ossimLocalCorrelationFusion::computeRegression(ossim_float64& slopeResult, const ossimIpt& origin, const ossimRefPtr panData, const ossimRefPtr colorData, ossim_uint32 colorBandIdx) { bool result = false; slopeResult = 0.0; if(panData.valid()&&colorData.valid()) { ossim_int32 regW2 = (ossim_int32)(theRegressionWidth>>1); ossimIrect rect = panData->getImageRectangle(); const ossim_float32* colorDataPtr = (const ossim_float32*)colorData->getBuf(colorBandIdx); const ossim_float32* colorDataPtr2 = (const ossim_float32*)colorData->getBuf(colorBandIdx); // const ossim_float32* colorDataPtrBands[3]={0}; // if(colorData->getNumberOfBands() <2) // { // colorDataPtrBands[0] = (ossim_float32*)colorData->getBuf(0); // } // else if(colorData->getNumberOfBands() <3) // { // colorDataPtrBands[0] = (ossim_float32*)colorData->getBuf(0); // colorDataPtrBands[1] = (ossim_float32*)colorData->getBuf(1); // } // else // { // colorDataPtrBands[0] = (ossim_float32*)colorData->getBuf(0); // colorDataPtrBands[1] = (ossim_float32*)colorData->getBuf(1); // colorDataPtrBands[2] = (ossim_float32*)colorData->getBuf(2); // } const ossim_float32* panDataPtr = (const ossim_float32*)panData->getBuf(); const ossim_float32* panDataPtr2 = (const ossim_float32*)panData->getBuf(); // if(!panDataPtr || !colorDataPtrBands[0]) return result; if(!panDataPtr || !colorDataPtr) return result; ossim_float64 panNp = panData->getNullPix(0); ossim_float64 colorNp = colorData->getNullPix(0); ossim_int32 w = (ossim_int32)rect.width(); ossim_int32 offset = (ossim_int32)( ((origin.y-rect.ul().y) - regW2)*w + ((origin.x-rect.ul().x) - regW2)); ossim_uint32 y = 0; ossim_uint32 x = 0; ossim_uint32 idx = 0; ossim2dLinearRegression regression; ossim_uint32 offsetColorBand; for(y = 0; y < theRegressionWidth; ++y) { offsetColorBand = (offset + y*w); panDataPtr = panDataPtr2 + offsetColorBand; colorDataPtr = colorDataPtr2 + offsetColorBand; for(x = 0; x < theRegressionWidth; ++x) { // if((*panDataPtr != panNp)&& // (colorDataPtrBands[0][offsetColorBand] != colorNp)&& // (colorDataPtrBands[1][offsetColorBand] != colorNp)&& // (colorDataPtrBands[2][offsetColorBand] != colorNp)) // { if((*panDataPtr != panNp)&& (*colorDataPtr != colorNp)) { // ossimNormRgbVector rgbV(colorDataPtrBands[0][offsetColorBand], // colorDataPtrBands[1][offsetColorBand], // colorDataPtrBands[2][offsetColorBand]); // ossimHsiVector hsi(rgbV); regression.addPoint(ossimDpt(*panDataPtr, *colorDataPtr)); // regression.addPoint(ossimDpt(*panDataPtr, hsi.getI())); ++idx; } ++panDataPtr; // ++offsetColorBand; ++colorDataPtr; } } if(idx > 2) { double slope, intercept; result = true; regression.solve(); regression.getEquation(slope, intercept); slopeResult = slope; } } return result; } void ossimLocalCorrelationFusion::initAdjustableParameters() { resizeAdjustableParameterArray(NUMBER_OF_ADJUSTABLE_PARAMETERS); setAdjustableParameter(REGRESSION_COEFFICIENT_ATTENUATOR_OFFSET, 0.0); setParameterDescription(REGRESSION_COEFFICIENT_ATTENUATOR_OFFSET, "Attenuator"); setParameterSigma(REGRESSION_COEFFICIENT_ATTENUATOR_OFFSET, 2.0); setParameterCenter(REGRESSION_COEFFICIENT_ATTENUATOR_OFFSET, 1.0); setAdjustableParameter(REGRESSION_COEFFICIENT_CLAMP_OFFSET, 0.0); setParameterDescription(REGRESSION_COEFFICIENT_CLAMP_OFFSET, "Regression clamp"); setParameterSigma(REGRESSION_COEFFICIENT_CLAMP_OFFSET, 10.0); setParameterCenter(REGRESSION_COEFFICIENT_CLAMP_OFFSET, 10.0); setAdjustableParameter(HIGH_PASS_GAIN_OFFSET, -1.0); setParameterDescription(HIGH_PASS_GAIN_OFFSET, "High pass gain"); setParameterSigma(HIGH_PASS_GAIN_OFFSET, 1); setParameterCenter(HIGH_PASS_GAIN_OFFSET, 1.0); setAdjustableParameter(PAN_BLURR_WIDTH_OFFSET, -1); setParameterDescription(PAN_BLURR_WIDTH_OFFSET, "Blurring kernel width"); setParameterSigma(PAN_BLURR_WIDTH_OFFSET, 7); setParameterCenter(PAN_BLURR_WIDTH_OFFSET, 7.5); setParameterOffset(PAN_BLURR_WIDTH_OFFSET, 1.5); setParameterOffset(REGRESSION_COEFFICIENT_CLAMP_OFFSET, 4.0); } void ossimLocalCorrelationFusion::adjustableParametersChanged() { // std::cout << "Parameter offset = " << computeParameterOffset(2) << std::endl; theBlurrKernelWidth = (ossim_uint32)(ossim::round(computeParameterOffset(PAN_BLURR_WIDTH_OFFSET))); } bool ossimLocalCorrelationFusion::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimFusionCombiner::saveState(kwl, prefix); saveAdjustments(kwl, prefix); return true; } bool ossimLocalCorrelationFusion::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimFusionCombiner::loadState(kwl, prefix); loadAdjustments(kwl, prefix); adjustableParametersChanged(); return true; } ossim-Miami-2.9.1/src/imaging/ossimMapCompositionSource.cpp000066400000000000000000004043431352751253100240260ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimMapCompositionSource.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static const char* GRID_TYPE_ENUM_NAMES[] = {"none", "line", "reseaux"}; static const char* VIEW_WIDTH_KW = "view_width"; static const char* VIEW_HEIGHT_KW = "view_height"; static const char* METER_GRID_SPACING_X_KW = "meter_grid_spacing_x"; static const char* METER_GRID_SPACING_Y_KW = "meter_grid_spacing_y"; static const char* GEO_GRID_SPACING_LON_KW = "geo_grid_spacing_lon"; static const char* GEO_GRID_SPACING_LAT_KW = "geo_grid_spacing_lat"; static const char* METER_GRID_TYPE_KW = "meter_grid_type"; static const char* GEO_GRID_TYPE_KW = "geo_grid_type"; static const char* TOP_BORDER_LENGTH_KW = "top_border_length"; static const char* BOTTOM_BORDER_LENGTH_KW = "bottom_border_length"; static const char* LEFT_BORDER_LENGTH_KW = "top_border_length"; static const char* RIGHT_BORDER_LENGTH_KW = "right_border_length"; static const char* BORDER_COLOR_KW = "border_color"; static const char* GEO_GRID_COLOR_KW = "geo_grid_color"; static const char* METER_GRID_COLOR_KW = "meter_grid_color"; static const char* TITLE_STRING_KW = "title_string"; static const char* TITLE_COLOR_KW = "title_color"; static const char* TOP_GEO_LABEL_COLOR_KW = "top_geo_label_color"; static const char* BOTTOM_GEO_LABEL_COLOR_KW = "bottom_geo_label_color"; static const char* LEFT_GEO_LABEL_COLOR_KW = "left_geo_label_color"; static const char* RIGHT_GEO_LABEL_COLOR_KW = "right_geo_label_color"; static const char* TOP_METER_LABEL_COLOR_KW = "top_meter_label_color"; static const char* BOTTOM_METER_LABEL_COLOR_KW = "bottom_meter_label_color"; static const char* LEFT_METER_LABEL_COLOR_KW = "left_meter_label_color"; static const char* RIGHT_METER_LABEL_COLOR_KW = "right_meter_label_color"; static const char* TOP_GEO_LABEL_FORMAT_KW = "top_geo_label_format"; static const char* BOTTOM_GEO_LABEL_FORMAT_KW = "bottom_geo_label_format"; static const char* LEFT_GEO_LABEL_FORMAT_KW = "left_geo_label_format"; static const char* RIGHT_GEO_LABEL_FORMAT_KW = "right_geo_label_format"; static const char* TOP_GEO_LABEL_FLAG_KW = "top_geo_label_flag"; static const char* BOTTOM_GEO_LABEL_FLAG_KW = "bottom_geo_label_flag"; static const char* LEFT_GEO_LABEL_FLAG_KW = "left_geo_label_flag"; static const char* RIGHT_GEO_LABEL_FLAG_KW = "right_geo_label_flag"; static const char* TOP_METER_LABEL_FLAG_KW = "top_meter_label_flag"; static const char* BOTTOM_METER_LABEL_FLAG_KW = "bottom_meter_label_flag"; static const char* LEFT_METER_LABEL_FLAG_KW = "left_meter_label_flag"; static const char* RIGHT_METER_LABEL_FLAG_KW = "right_meter_label_flag"; static const char* TOP_GEO_LABEL_FONT_KW = "top_geo_label_font"; static const char* BOTTOM_GEO_LABEL_FONT_KW = "bottom_geo_label_font"; static const char* LEFT_GEO_LABEL_FONT_KW = "left_geo_label_font"; static const char* RIGHT_GEO_LABEL_FONT_KW = "right_geo_label_font"; static const char* TOP_METER_LABEL_FONT_KW = "top_meter_label_font"; static const char* BOTTOM_METER_LABEL_FONT_KW = "bottom_meter_label_font"; static const char* LEFT_METER_LABEL_FONT_KW = "left_meter_label_font"; static const char* RIGHT_METER_LABEL_FONT_KW = "right_meter_label_font"; static const char* TITLE_FONT_KW = "title_font"; static ossimTrace traceDebug("ossimMapCompositionSource:debug"); RTTI_DEF1(ossimMapCompositionSource, "ossimMapCompositionSource", ossimAnnotationSource); ossimMapCompositionSource::ossimMapCompositionSource() :ossimAnnotationSource(), theMeterGridType(OSSIM_GRID_NONE), theGeographicGridType(OSSIM_GRID_LINE), theTopBorderLength(200), theBottomBorderLength(200), theLeftBorderLength(300), theRightBorderLength(300), theBorderColor(255,255,255), theGeographicGridColor(255,255,255), theMeterGridColor(255,255,255), theTitleString(""), theTitleFont(NULL), theTitleColor(1, 1, 1), theTopGeographicLabelColor(1, 1, 1), theBottomGeographicLabelColor(1, 1, 1), theLeftGeographicLabelColor(1, 1, 1), theRightGeographicLabelColor(1, 1, 1), theTopMeterLabelColor(1, 1, 1), theBottomMeterLabelColor(1, 1, 1), theLeftMeterLabelColor(1, 1, 1), theRightMeterLabelColor(1, 1, 1), theGeographicTopLabelFont(NULL), theGeographicBottomLabelFont(NULL), theGeographicLeftLabelFont(NULL), theGeographicRightLabelFont(NULL), theMeterTopLabelFont(NULL), theMeterBottomLabelFont(NULL), theMeterLeftLabelFont(NULL), theMeterRightLabelFont(NULL), theTopGeographicFormat("dd@mm'ss\".ssssC"), theBottomGeographicFormat("dd@mm'ss\".ssssC"), theLeftGeographicFormat("dd@mm'ss\".ssssC"), theRightGeographicFormat("dd@mm'ss\".ssssC"), theTopGeographicLabelFlag(true), theBottomGeographicLabelFlag(true), theLeftGeographicLabelFlag(true), theRightGeographicLabelFlag(true), theTopGeographicTickFlag(true), theBottomGeographicTickFlag(true), theLeftGeographicTickFlag(true), theRightGeographicTickFlag(true), theTopMeterLabelFlag(false), theBottomMeterLabelFlag(false), theLeftMeterLabelFlag(false), theRightMeterLabelFlag(false), theTopMeterTickFlag(false), theBottomMeterTickFlag(false), theLeftMeterTickFlag(false), theRightMeterTickFlag(false), theGeographicSpacing(1.0, 1.0), theMeterSpacing(3600*30, 3600*30) { theViewWidthHeight = ossimIpt(-1,-1); vector info; ossimFontFactoryRegistry::instance()->getFontInformation(info); if(info.size()) { theGeographicTopLabelFont = ossimFontFactoryRegistry::instance()->createFont(info[0]); theGeographicTopLabelFontInfo = info[0]; theGeographicTopLabelFontInfo.thePointSize = ossimIpt(12,12); if(theGeographicTopLabelFont.valid()) { theGeographicBottomLabelFont = (ossimFont*)theGeographicTopLabelFont->dup(); theGeographicBottomLabelFontInfo = theGeographicTopLabelFontInfo; theGeographicLeftLabelFont = (ossimFont*)theGeographicTopLabelFont->dup(); theGeographicLeftLabelFontInfo = theGeographicTopLabelFontInfo; theGeographicRightLabelFont = (ossimFont*)theGeographicTopLabelFont->dup(); theGeographicRightLabelFontInfo = theGeographicTopLabelFontInfo; theMeterTopLabelFont = (ossimFont*)theGeographicTopLabelFont->dup(); theMeterTopLabelFontInfo = theGeographicTopLabelFontInfo; theMeterBottomLabelFont = (ossimFont*)theGeographicTopLabelFont->dup(); theMeterBottomLabelFontInfo = theGeographicTopLabelFontInfo; theMeterLeftLabelFont = (ossimFont*)theGeographicTopLabelFont->dup(); theMeterLeftLabelFontInfo = theGeographicTopLabelFontInfo; theMeterRightLabelFont = (ossimFont*)theGeographicTopLabelFont->dup(); theMeterRightLabelFontInfo = theGeographicTopLabelFontInfo; theTitleFont = (ossimFont*)theGeographicTopLabelFont->dup(); theTitleFontInfo = theGeographicTopLabelFontInfo; theTitleFontInfo.thePointSize = ossimIpt(48, 48); } } } ossimMapCompositionSource::~ossimMapCompositionSource() { theGeographicTopLabelFont = 0; theGeographicBottomLabelFont = 0; theGeographicLeftLabelFont = 0; theGeographicRightLabelFont = 0; theMeterTopLabelFont = 0; theMeterBottomLabelFont = 0; theMeterLeftLabelFont = 0; theMeterRightLabelFont = 0; theTitleFont = 0; deleteFixedAnnotations(); } ossimRefPtr ossimMapCompositionSource::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theTile) { allocate(tileRect); if(!theTile) { if(theInputConnection) { return theInputConnection->getTile(tileRect, resLevel); } } } theTile->setImageRectangle(tileRect); theTile->makeBlank(); if(theInputConnection) { ossimRefPtr tile = theInputConnection->getTile(tileRect, resLevel); if(tile.valid()) { if(tile->getScalarType() != OSSIM_UCHAR) { ossimNotify(ossimNotifyLevel_WARN) << "ossimMapCompositionSource::getTile\n" << "Error input is not uchar" << endl; return tile; } else { if(tile->getBuf()&&(tile->getDataObjectStatus() != OSSIM_EMPTY)) { int band = 0; int outBands = theTile->getNumberOfBands(); int minBand = std::min((long)theTile->getNumberOfBands(), (long)tile->getNumberOfBands()); for(band = 0; band < minBand; ++band) { theTile->loadBand(tile->getBuf(band), tile->getImageRectangle(), band); } // copy last band of input tile to all output // bands if the input tile did not have enough bands. // for(;band < outBands;++band) { theTile->loadBand(tile->getBuf(minBand-1), tile->getImageRectangle(), band); } } drawBorders(); drawAnnotations(theTile); } } } theTile->validate(); return theTile; } void ossimMapCompositionSource::setGeographicLabelFormat(const ossimString format) { if( (format == theTopGeographicFormat)&& (format == theBottomGeographicFormat)&& (format == theLeftGeographicFormat)&& (format == theRightGeographicFormat)) { return; } theTopGeographicFormat = format; theBottomGeographicFormat = format; theLeftGeographicFormat = format; theRightGeographicFormat = format; } void ossimMapCompositionSource::setTopGeographicLabelFormat(const ossimString& format) { if(format == theTopGeographicFormat) { return; } theTopGeographicFormat = format; } void ossimMapCompositionSource::setBottomGeographicLabelFormat(const ossimString& format) { if(format == theBottomGeographicFormat) { return; } theBottomGeographicFormat = format; // need to reset the fonts // layoutAnnotations(); } void ossimMapCompositionSource::setLeftGeographicLabelFormat(const ossimString& format) { if(format == theLeftGeographicFormat) { return; } theLeftGeographicFormat = format; // need to reset the fonts // layoutAnnotations(); } void ossimMapCompositionSource::setRightGeographicLabelFormat(const ossimString& format) { if(format == theRightGeographicFormat) { return; } theRightGeographicFormat = format; } void ossimMapCompositionSource::setTitleFont(const ossimFontInformation& fontInfo) { if(theTitleFontInfo == fontInfo) { return; } ossimFont* font = ossimFontFactoryRegistry::instance()->createFont(fontInfo); if(font) { theTitleFont = font; theTitleFontInfo = fontInfo; } } void ossimMapCompositionSource::setGeographicTopLabelFont(const ossimFontInformation& fontInfo) { const char* MODULE = "ossimMapCompositionSource::setGeographicTopLabelFont"; if(traceDebug()) { CLOG << "Entering...." <createFont(fontInfo); if(font) { if(traceDebug()) { CLOG << "Previous font info " <createFont(fontInfo); if(font) { theGeographicBottomLabelFont = font; theGeographicBottomLabelFontInfo = fontInfo; } } void ossimMapCompositionSource::setGeographicLeftLabelFont(const ossimFontInformation& fontInfo) { if(theGeographicRightLabelFontInfo == fontInfo) { return; } ossimFont* font = ossimFontFactoryRegistry::instance()->createFont(fontInfo); if(font) { theGeographicLeftLabelFont = font; theGeographicLeftLabelFontInfo = fontInfo; } } void ossimMapCompositionSource::setGeographicRightLabelFont(const ossimFontInformation& fontInfo) { if(theGeographicRightLabelFontInfo == fontInfo) { return; } ossimFont* font = ossimFontFactoryRegistry::instance()->createFont(fontInfo); if(font) { theGeographicRightLabelFont = font; theGeographicRightLabelFontInfo = fontInfo; } } void ossimMapCompositionSource::setMeterTopLabelFont(const ossimFontInformation& fontInfo) { if(theMeterTopLabelFontInfo == fontInfo) { return; } ossimFont* font = ossimFontFactoryRegistry::instance()->createFont(fontInfo); if(font) { theMeterTopLabelFont = font; theMeterTopLabelFontInfo = fontInfo; } } void ossimMapCompositionSource::setMeterBottomLabelFont(const ossimFontInformation& fontInfo) { if(theMeterBottomLabelFontInfo == fontInfo) { return; } ossimFont* font = ossimFontFactoryRegistry::instance()->createFont(fontInfo); if(font) { theMeterBottomLabelFont = font; theMeterBottomLabelFontInfo = fontInfo; } } void ossimMapCompositionSource::setMeterLeftLabelFont(const ossimFontInformation& fontInfo) { if(theMeterLeftLabelFontInfo == fontInfo) { return; } ossimFont* font = ossimFontFactoryRegistry::instance()->createFont(fontInfo); if(font) { theMeterLeftLabelFont = font; theMeterLeftLabelFontInfo = fontInfo; } } void ossimMapCompositionSource::setMeterRightLabelFont(const ossimFontInformation& fontInfo) { if(theMeterRightLabelFontInfo == fontInfo) { return; } ossimFont* font = ossimFontFactoryRegistry::instance()->createFont(fontInfo); if(font) { theMeterRightLabelFont = font; theMeterRightLabelFontInfo = fontInfo; } } ossimIrect ossimMapCompositionSource::getBoundingRect(ossim_uint32 resLevel)const { ossimIrect result; result.makeNan(); if(theInputConnection) { ossimIrect inputRect = getViewingRect(); if(!inputRect.hasNans()) { ossimDpt decimation; getDecimationFactor(resLevel, decimation); int leftBorderLength = theLeftBorderLength; int rightBorderLength = theRightBorderLength; int topBorderLength = theTopBorderLength; int bottomBorderLength = theBottomBorderLength; ossimIpt p1(inputRect.ul().x - leftBorderLength, inputRect.ul().y - topBorderLength); ossimIpt p2(inputRect.ur().x + rightBorderLength, inputRect.ur().y - topBorderLength); ossimIpt p3(inputRect.lr().x + rightBorderLength, inputRect.lr().y + bottomBorderLength); ossimIpt p4(inputRect.ll().x - leftBorderLength, inputRect.ll().y + bottomBorderLength); result = ossimIrect(p1, p2, p3, p4); if(!decimation.hasNans()) { result*=decimation; } } } return result; } void ossimMapCompositionSource::layoutAnnotations() { deleteFixedAnnotations(); addTitle(); addGridLabels(); if(theGeographicGridType == OSSIM_GRID_LINE) { addGeographicGridLines(); } else if(theGeographicGridType == OSSIM_GRID_RESEAUX) { addGeographicGridReseaux(); } if(theMeterGridType == OSSIM_GRID_LINE) { addMeterGridLines(); } else if(theMeterGridType == OSSIM_GRID_RESEAUX) { addMeterGridReseaux(); } } void ossimMapCompositionSource::initialize() { ossimAnnotationSource::initialize(); theTile = 0; if(theInputConnection) { computeBorderRects(); layoutAnnotations(); } else { deleteFixedAnnotations(); } } void ossimMapCompositionSource::computeBorderRects() { if(theInputConnection) { ossimIrect inputRect = getViewingRect();; theTopBorder = ossimIrect(inputRect.ul().x - theLeftBorderLength, inputRect.ul().y - theTopBorderLength, inputRect.ur().x + theRightBorderLength, inputRect.ur().y); theBottomBorder = ossimIrect(inputRect.ll().x - theLeftBorderLength, inputRect.ll().y, inputRect.lr().x + theRightBorderLength, inputRect.lr().y + theBottomBorderLength); theLeftBorder = ossimIrect(theTopBorder.ul().x, theTopBorder.ll().y, inputRect.ll().x, inputRect.ll().y); theRightBorder = ossimIrect(inputRect.ur().x, inputRect.ur().y, theBottomBorder.lr().x, inputRect.lr().y); } else { theTopBorder.makeNan(); theBottomBorder.makeNan(); theLeftBorder.makeNan(); theRightBorder.makeNan(); } } void ossimMapCompositionSource::drawBorders() { if(theTile.valid()) { ossimIrect top = theTopBorder; ossimIrect bottom = theBottomBorder; ossimIrect left = theLeftBorder; ossimIrect right = theRightBorder; // if(resLevel) // { // ossimDpt decimation; // getDecimationFactor(resLevel, // decimation); // if(!decimation.hasNans()) // { // top*=decimation; // bottom*=decimation; // left*=decimation; // right*=decimation; // } // } ossimIrect tileRect = theTile->getImageRectangle(); ossimImageDataHelper helper(theTile.get()); if(top.intersects(tileRect)) { helper.fill(theBorderColor, top.clipToRect(tileRect),false); } if(bottom.intersects(tileRect)) { helper.fill(theBorderColor, bottom.clipToRect(tileRect),false); } if(left.intersects(tileRect)) { helper.fill(theBorderColor, left.clipToRect(tileRect),false); } if(right.intersects(tileRect)) { helper.fill(theBorderColor, right.clipToRect(tileRect),false); } } } void ossimMapCompositionSource::addGridLabels() { addGeographicTopGridLabels(); addGeographicBottomGridLabels(); addGeographicLeftGridLabels(); addGeographicRightGridLabels(); addMeterGridLabels(); } void ossimMapCompositionSource::addGeographicTopGridLabels() { const char* MODULE = "ossimMapCompositionSource::addGeographicTopGridLabels"; if(traceDebug()) { CLOG << "Entering...." << endl; } if((!theTopGeographicLabelFlag)&&(!theTopGeographicTickFlag)) { if(traceDebug()) { CLOG << "Exiting, flags are false...." << endl; } return; } if(theInputConnection) { const ossimMapProjection* mapProj = inputMapProjection(); ossimGpt gpt[4]; ossimDrect rect = getViewingRect(); if(rect.hasNans()) return; mapProj->lineSampleToWorld(rect.ul(), gpt[0]); mapProj->lineSampleToWorld(rect.ur(), gpt[1]); mapProj->lineSampleToWorld(rect.lr(), gpt[2]); mapProj->lineSampleToWorld(rect.ll(), gpt[3]); ossimDrect grect(gpt[0], gpt[1], gpt[2], gpt[3], OSSIM_RIGHT_HANDED); if(grect.hasNans()) return; ossimDpt ulLatLon(((int)((grect.ul().x-theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.ul().y+theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); ossimDpt lrLatLon(((int)((grect.lr().x+theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.lr().y-theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); while(ulLatLon.lat > 90) { ulLatLon.lat -= theGeographicSpacing.lat; } while(ulLatLon.lon < -180) { ulLatLon.lon += theGeographicSpacing.lon; } while(lrLatLon.lat < -90) { ulLatLon.lat += theGeographicSpacing.lat; } while(lrLatLon.lon > 180) { ulLatLon.lon -= theGeographicSpacing.lon; } ossimDrect latLonSpacing(ulLatLon, lrLatLon, OSSIM_RIGHT_HANDED); if(traceDebug()) { CLOG << "labeling bounding geo rect = " << latLonSpacing << endl; } // do the top side labels. for(double lon = latLonSpacing.ul().x; lon <= latLonSpacing.lr().x; lon+=theGeographicSpacing.x) { ossimDpt tipt; // top ossimDpt bipt; // bottom ossimGpt tgpt(latLonSpacing.ul().y, lon, 0.0, gpt[0].datum()); ossimGpt bgpt(latLonSpacing.lr().y, lon, 0.0, gpt[0].datum()); mapProj->worldToLineSample(tgpt, tipt); mapProj->worldToLineSample(bgpt, bipt); if((!tipt.hasNans()&& !bipt.hasNans()) && rect.clip(tipt, bipt)) { ossimIpt rounded(tipt); if( (rounded.x >= rect.ul().x)&& (rounded.x <= rect.lr().x)) { if(theTopGeographicLabelFlag) { ossimDms dms(tgpt.lond(), false); ossimString dmsString = dms.toString(theTopGeographicFormat.c_str()); ossimAnnotationFontObject* lonLabel = new ossimAnnotationFontObject(ossimIpt(0,0), dmsString); lonLabel->setFont(theGeographicTopLabelFont.get()); lonLabel->setGeometryInformation(theGeographicTopLabelFontInfo); lonLabel->computeBoundingRect(); ossimDrect boundsD; lonLabel->getBoundingRect(boundsD); ossimIpt center( rounded.x, ossim::round(rect.ul().y-(boundsD.height()/2))); lonLabel->setColor(theTopGeographicLabelColor.getR(), theTopGeographicLabelColor.getG(), theTopGeographicLabelColor.getB()); lonLabel->setCenterPosition(center); lonLabel->computeBoundingRect(); ossimDrect labelRect; lonLabel->getBoundingRect(labelRect); if(rect.intersects(labelRect)) { ossimIrect intersection = rect.clipToRect(labelRect); center.y -= ossim::round(rect.ul().y - intersection.lr().y); } center.y -= 24; // this will need to be the tick height later; lonLabel->setCenterPosition(center); lonLabel->computeBoundingRect(); addFixedAnnotation(lonLabel); } if(theTopGeographicTickFlag) { ossimAnnotationLineObject* lineLabel = new ossimAnnotationLineObject (ossimIpt(rounded.x,ossim::round(rect.ul().y-24)), ossimIpt(rounded.x, ossim::round(rect.ul().y))); lineLabel->setColor(theTopGeographicLabelColor.getR(), theTopGeographicLabelColor.getG(), theTopGeographicLabelColor.getB()); addFixedAnnotation(lineLabel); } } } } } if(traceDebug()) { CLOG << "Exiting...." << endl; } } void ossimMapCompositionSource::addGeographicBottomGridLabels() { if((!theBottomGeographicLabelFlag)&&(!theBottomGeographicTickFlag)) { return; } const ossimMapProjection* mapProj = inputMapProjection(); if(mapProj) { ossimGpt gpt[4]; ossimDrect rect = getViewingRect(); if(rect.hasNans()) return; mapProj->lineSampleToWorld(rect.ul(), gpt[0]); mapProj->lineSampleToWorld(rect.ur(), gpt[1]); mapProj->lineSampleToWorld(rect.lr(), gpt[2]); mapProj->lineSampleToWorld(rect.ll(), gpt[3]); ossimDrect grect(gpt[0], gpt[1], gpt[2], gpt[3], OSSIM_RIGHT_HANDED); if(grect.hasNans()) return; ossimDpt ulLatLon(((int)((grect.ul().x-theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.ul().y+theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); ossimDpt lrLatLon(((int)((grect.lr().x+theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.lr().y-theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); while(ulLatLon.lat > 90) { ulLatLon.lat -= theGeographicSpacing.lat; } while(ulLatLon.lon < -180) { ulLatLon.lon += theGeographicSpacing.lon; } while(lrLatLon.lat < -90) { ulLatLon.lat += theGeographicSpacing.lat; } while(lrLatLon.lon > 180) { ulLatLon.lon -= theGeographicSpacing.lon; } ossimDrect latLonSpacing(ulLatLon, lrLatLon, OSSIM_RIGHT_HANDED); // do the top side labels. for(double lon = latLonSpacing.ul().x; lon <= latLonSpacing.lr().x; lon+=theGeographicSpacing.x) { ossimDpt tipt; // top ossimDpt bipt; // bottom ossimGpt tgpt(latLonSpacing.ul().y, lon, 0.0, gpt[0].datum()); ossimGpt bgpt(latLonSpacing.lr().y, lon, 0.0, gpt[0].datum()); mapProj->worldToLineSample(tgpt, tipt); mapProj->worldToLineSample(bgpt, bipt); if(rect.clip(tipt, bipt)) { ossimIpt rounded(bipt); if( (rounded.x >= rect.ul().x)&& (rounded.x <= rect.lr().x)) { if(theBottomGeographicLabelFlag) { ossimDms dms(bgpt.lond(), false); ossimString dmsString = dms.toString(theBottomGeographicFormat.c_str()); ossimAnnotationFontObject* lonLabel = new ossimAnnotationFontObject(ossimIpt(0,0), dmsString); lonLabel->setGeometryInformation(theGeographicBottomLabelFontInfo); lonLabel->setFont(theGeographicBottomLabelFont.get()); // lonLabel->setFont(theGeographicBottomLabelFont->dup()); lonLabel->computeBoundingRect(); ossimDrect boundsD; lonLabel->getBoundingRect(boundsD); ossimIrect bounds = boundsD; ossimIpt center( rounded.x, ossim::round(rect.lr().y+(bounds.height()/2))); lonLabel->setColor(theBottomGeographicLabelColor.getR(), theBottomGeographicLabelColor.getG(), theBottomGeographicLabelColor.getB()); lonLabel->setCenterPosition(center); lonLabel->computeBoundingRect(); lonLabel->getBoundingRect(boundsD); bounds = boundsD; ossimDrect labelRect; lonLabel->getBoundingRect(labelRect); if(rect.intersects(labelRect)) { ossimIrect intersection = rect.clipToRect(labelRect); center.y += ossim::round(rect.lr().y - intersection.ul().y); } center.y += 24; // this will need to be the tick height later; lonLabel->setCenterPosition(center); lonLabel->computeBoundingRect(); addFixedAnnotation(lonLabel); } if(theBottomGeographicTickFlag) { ossimAnnotationLineObject* lineLabel = new ossimAnnotationLineObject(ossimIpt(rounded.x, ossim::round(rect.lr().y+24)), ossimIpt(rounded.x, ossim::round(rect.lr().y))); lineLabel->setColor(theBottomGeographicLabelColor.getR(), theBottomGeographicLabelColor.getG(), theBottomGeographicLabelColor.getB()); addFixedAnnotation(lineLabel); } } } } } } void ossimMapCompositionSource::addGeographicLeftGridLabels() { if((!theLeftGeographicLabelFlag)&&(!theLeftGeographicTickFlag)) { return; } const ossimMapProjection* mapProj = inputMapProjection(); if(mapProj) { ossimGpt gpt[4]; ossimDrect rect = getViewingRect(); if(rect.hasNans()) return; mapProj->lineSampleToWorld(rect.ul(), gpt[0]); mapProj->lineSampleToWorld(rect.ur(), gpt[1]); mapProj->lineSampleToWorld(rect.lr(), gpt[2]); mapProj->lineSampleToWorld(rect.ll(), gpt[3]); ossimDrect grect(gpt[0], gpt[1], gpt[2], gpt[3], OSSIM_RIGHT_HANDED); if(grect.hasNans()) return; ossimDpt ulLatLon(((int)((grect.ul().x-theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.ul().y+theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); ossimDpt lrLatLon(((int)((grect.lr().x+theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.lr().y-theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); while(ulLatLon.lat > 90) { ulLatLon.lat -= theGeographicSpacing.lat; } while(ulLatLon.lon < -180) { ulLatLon.lon += theGeographicSpacing.lon; } while(lrLatLon.lat < -90) { ulLatLon.lat += theGeographicSpacing.lat; } while(lrLatLon.lon > 180) { ulLatLon.lon -= theGeographicSpacing.lon; } ossimDrect latLonSpacing(ulLatLon, lrLatLon, OSSIM_RIGHT_HANDED); // do the left side labels for(double lat = latLonSpacing.ul().y; lat >= latLonSpacing.lr().y; lat-=theGeographicSpacing.y) { ossimDpt lipt; ossimDpt ript; ossimGpt lgpt(lat, latLonSpacing.ul().x, 0.0, gpt[0].datum()); ossimGpt rgpt(lat, latLonSpacing.ur().x, 0.0, gpt[0].datum()); mapProj->worldToLineSample(lgpt, lipt); mapProj->worldToLineSample(rgpt, ript); if(rect.clip(lipt, ript)) { ossimIpt rounded(lipt); if( (rounded.y >= rect.ul().y)&& (rounded.y <= rect.lr().y)) { if(theLeftGeographicLabelFlag) { ossimDms dms(lgpt.latd()); ossimString dmsString = dms.toString(theLeftGeographicFormat.c_str()); ossimAnnotationFontObject* latLabel = new ossimAnnotationFontObject(ossimIpt(0,0), dmsString); latLabel->setGeometryInformation(theGeographicLeftLabelFontInfo); latLabel->setFont(theGeographicLeftLabelFont.get()); // latLabel->setFont(theGeographicLeftLabelFont->dup()); latLabel->computeBoundingRect(); ossimDrect boundsD; latLabel->getBoundingRect(boundsD); ossimIrect bounds = boundsD; ossimIpt center( ossim::round((rect.ul().x - (bounds.width()/2))), rounded.y); latLabel->setColor(theLeftGeographicLabelColor.getR(), theLeftGeographicLabelColor.getG(), theLeftGeographicLabelColor.getB()); latLabel->setCenterPosition(center); latLabel->computeBoundingRect(); latLabel->getBoundingRect(boundsD); bounds = boundsD; ossimDrect labelRect; latLabel->getBoundingRect(labelRect); if(rect.intersects(labelRect)) { ossimIrect intersection = rect.clipToRect(labelRect); center.x -= ossim::round(rect.ul().x - intersection.ur().x); } center.x -= 24; // this will need to be the tick height later; latLabel->setCenterPosition(center); latLabel->computeBoundingRect(); addFixedAnnotation(latLabel); } if(theLeftGeographicTickFlag) { ossimAnnotationLineObject* lineLabel = new ossimAnnotationLineObject(ossimIpt(ossim::round(rect.ul().x), rounded.y), ossimIpt(ossim::round(rect.ul().x-23), rounded.y)); lineLabel->setColor(theLeftGeographicLabelColor.getR(), theLeftGeographicLabelColor.getG(), theLeftGeographicLabelColor.getB()); addFixedAnnotation(lineLabel); } } } } } } void ossimMapCompositionSource::addGeographicRightGridLabels() { if((!theRightGeographicLabelFlag)&&(!theRightGeographicTickFlag)) { return; } const ossimMapProjection* mapProj = inputMapProjection(); if(mapProj) { ossimGpt gpt[4]; ossimDrect rect = getViewingRect(); if(rect.hasNans()) return; mapProj->lineSampleToWorld(rect.ul(), gpt[0]); mapProj->lineSampleToWorld(rect.ur(), gpt[1]); mapProj->lineSampleToWorld(rect.lr(), gpt[2]); mapProj->lineSampleToWorld(rect.ll(), gpt[3]); ossimDrect grect(gpt[0], gpt[1], gpt[2], gpt[3], OSSIM_RIGHT_HANDED); if(grect.hasNans()) return; ossimDpt ulLatLon(((int)((grect.ul().x-theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.ul().y+theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); ossimDpt lrLatLon(((int)((grect.lr().x+theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.lr().y-theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); while(ulLatLon.lat > 90) { ulLatLon.lat -= theGeographicSpacing.lat; } while(ulLatLon.lon < -180) { ulLatLon.lon += theGeographicSpacing.lon; } while(lrLatLon.lat < -90) { ulLatLon.lat += theGeographicSpacing.lat; } while(lrLatLon.lon > 180) { ulLatLon.lon -= theGeographicSpacing.lon; } ossimDrect latLonSpacing(ulLatLon, lrLatLon, OSSIM_RIGHT_HANDED); // do the left side labels for(double lat = latLonSpacing.ul().y; lat >= latLonSpacing.lr().y; lat-=theGeographicSpacing.y) { ossimDpt lipt; ossimDpt ript; ossimGpt lgpt(lat, latLonSpacing.ul().x, 0.0, gpt[0].datum()); ossimGpt rgpt(lat, latLonSpacing.ur().x, 0.0, gpt[0].datum()); mapProj->worldToLineSample(lgpt, lipt); mapProj->worldToLineSample(rgpt, ript); if(rect.clip(lipt, ript)) { ossimIpt rounded(ript); if( (rounded.y >= rect.ul().y)&& (rounded.y <= rect.lr().y)) { if(theRightGeographicLabelFlag) { ossimDms dms(rgpt.latd()); ossimString dmsString = dms.toString(theRightGeographicFormat.c_str()); ossimAnnotationFontObject* latLabel = new ossimAnnotationFontObject(ossimIpt(0,0), dmsString); latLabel->setGeometryInformation(theGeographicRightLabelFontInfo); latLabel->setFont(theGeographicRightLabelFont.get()); // latLabel->setFont(theGeographicRightLabelFont->dup()); latLabel->computeBoundingRect(); ossimDrect boundsD; latLabel->getBoundingRect(boundsD); ossimIrect bounds = boundsD; ossimIpt center( ossim::round((rect.ur().x + (bounds.width()/2))), rounded.y); latLabel->setColor(theRightGeographicLabelColor.getR(), theRightGeographicLabelColor.getG(), theRightGeographicLabelColor.getB()); latLabel->setCenterPosition(center); latLabel->computeBoundingRect(); latLabel->getBoundingRect(boundsD); bounds = boundsD; ossimDrect labelRect; latLabel->getBoundingRect(labelRect); if(rect.intersects(labelRect)) { ossimIrect intersection = rect.clipToRect(labelRect); center.x -= ossim::round(rect.ur().x - intersection.ul().x); } center.x += 24; // this will need to be the tick height later; latLabel->setCenterPosition(center); latLabel->computeBoundingRect(); addFixedAnnotation(latLabel); } if(theRightGeographicTickFlag) { ossimAnnotationLineObject* lineLabel = new ossimAnnotationLineObject(ossimIpt(ossim::round(rect.lr().x), rounded.y), ossimIpt(ossim::round(rect.lr().x+23), rounded.y)); lineLabel->setColor(theRightGeographicLabelColor.getR(), theRightGeographicLabelColor.getG(), theRightGeographicLabelColor.getB()); addFixedAnnotation(lineLabel); } } } } } } void ossimMapCompositionSource::addGeographicGridLines() { const ossimMapProjection* mapProj = inputMapProjection(); if(mapProj) { ossimGpt gpt[4]; ossimDrect rect = getViewingRect(); if(rect.hasNans()) return; mapProj->lineSampleToWorld(rect.ul(), gpt[0]); mapProj->lineSampleToWorld(rect.ur(), gpt[1]); mapProj->lineSampleToWorld(rect.lr(), gpt[2]); mapProj->lineSampleToWorld(rect.ll(), gpt[3]); ossimDrect grect(gpt[0], gpt[1], gpt[2], gpt[3], OSSIM_RIGHT_HANDED); if(grect.hasNans()) return; ossimDpt ulLatLon(((int)((grect.ul().x-theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.ul().y+theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); ossimDpt lrLatLon(((int)((grect.lr().x+theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.lr().y-theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); while(ulLatLon.lat > 90) { ulLatLon.lat -= theGeographicSpacing.lat; } while(ulLatLon.lon < -180) { ulLatLon.lon += theGeographicSpacing.lon; } while(lrLatLon.lat < -90) { ulLatLon.lat += theGeographicSpacing.lat; } while(lrLatLon.lon > 180) { ulLatLon.lon -= theGeographicSpacing.lon; } ossimDrect latLonSpacing(ulLatLon, lrLatLon, OSSIM_RIGHT_HANDED); for(double lon = latLonSpacing.ul().x; lon <= latLonSpacing.lr().x; lon+=theGeographicSpacing.x) { ossimDpt tipt; // top ossimDpt bipt; // bottom ossimGpt tgpt(latLonSpacing.ul().y, lon, 0.0, gpt[0].datum()); ossimGpt bgpt(latLonSpacing.lr().y, lon, 0.0, gpt[0].datum()); mapProj->worldToLineSample(tgpt, tipt); mapProj->worldToLineSample(bgpt, bipt); if(rect.clip(tipt, bipt)) { ossimAnnotationLineObject* line = new ossimAnnotationLineObject(tipt, bipt); line->setColor(theGeographicGridColor.getR(), theGeographicGridColor.getG(), theGeographicGridColor.getB()); addFixedAnnotation(line); } } // do the left side labels for(double lat = latLonSpacing.ul().y; lat >= latLonSpacing.lr().y; lat-=theGeographicSpacing.y) { ossimDpt lipt; ossimDpt ript; ossimGpt lgpt(lat, latLonSpacing.ul().x, 0.0, gpt[0].datum()); ossimGpt rgpt(lat, latLonSpacing.ur().x, 0.0, gpt[0].datum()); mapProj->worldToLineSample(lgpt, lipt); mapProj->worldToLineSample(rgpt, ript); if(rect.clip(lipt, ript)) { ossimAnnotationLineObject* line = new ossimAnnotationLineObject(lipt, ript); line->setColor(theGeographicGridColor.getR(), theGeographicGridColor.getG(), theGeographicGridColor.getB()); addFixedAnnotation(line); } } } } void ossimMapCompositionSource::addGeographicGridReseaux() { const ossimMapProjection* mapProj = inputMapProjection(); if(mapProj) { ossimGpt gptArray[4]; ossimDrect rect = getViewingRect(); mapProj->lineSampleToWorld(rect.ul(), gptArray[0]); mapProj->lineSampleToWorld(rect.ur(), gptArray[1]); mapProj->lineSampleToWorld(rect.lr(), gptArray[2]); mapProj->lineSampleToWorld(rect.ll(), gptArray[3]); ossimDrect grect(gptArray[0], gptArray[1], gptArray[2], gptArray[3], OSSIM_RIGHT_HANDED); ossimDpt ulLatLon(((int)((grect.ul().x-theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.ul().y+theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); ossimDpt lrLatLon(((int)((grect.lr().x+theGeographicSpacing.x)/theGeographicSpacing.x))*theGeographicSpacing.x, ((int)((grect.lr().y-theGeographicSpacing.y)/theGeographicSpacing.y))*theGeographicSpacing.y); ossimDrect latLonSpacing(ulLatLon, lrLatLon, OSSIM_RIGHT_HANDED); ossimDpt ipt; // top for(double lat = latLonSpacing.ul().y; lat >= latLonSpacing.lr().y; lat-=theGeographicSpacing.y) { for(double lon = latLonSpacing.ul().x; lon <= latLonSpacing.lr().x; lon+=theGeographicSpacing.x) { ossimGpt gpt(lat, lon, 0.0, gptArray[0].datum()); mapProj->worldToLineSample(gpt, ipt); ossimIpt rounded(ipt); if(rect.pointWithin(ossimDpt(rounded))) { ossimIpt horizontalStart(rounded.x-10, rounded.y); ossimIpt horizontalEnd(rounded.x+10, rounded.y); ossimIpt verticalStart(rounded.x, rounded.y-10); ossimIpt verticalEnd(rounded.x, rounded.y+10); ossimAnnotationLineObject* line1 = new ossimAnnotationLineObject(horizontalStart, horizontalEnd); ossimAnnotationLineObject* line2 = new ossimAnnotationLineObject(verticalStart,verticalEnd); line1->setColor(theGeographicGridColor.getR(), theGeographicGridColor.getG(), theGeographicGridColor.getB()); line2->setColor(theGeographicGridColor.getR(), theGeographicGridColor.getG(), theGeographicGridColor.getB()); addFixedAnnotation(line1); addFixedAnnotation(line2); } } } } } void ossimMapCompositionSource::addMeterGridLines() { const ossimMapProjection* mapProj = inputMapProjection(); if(mapProj) { ossimDpt dptArray[4]; ossimDrect rect = getViewingRect(); mapProj->lineSampleToEastingNorthing(rect.ul(), dptArray[0]); mapProj->lineSampleToEastingNorthing(rect.ur(), dptArray[1]); mapProj->lineSampleToEastingNorthing(rect.lr(), dptArray[2]); mapProj->lineSampleToEastingNorthing(rect.ll(), dptArray[3]); ossimDrect drect(dptArray[0], dptArray[1], dptArray[2], dptArray[3], OSSIM_RIGHT_HANDED); ossimDpt ulMeter(((int)((drect.ul().x-theMeterSpacing.x)/theMeterSpacing.x))*theMeterSpacing.x, ((int)((drect.ul().y+theMeterSpacing.y)/theMeterSpacing.y))*theMeterSpacing.y); ossimDpt lrMeter(((int)((drect.lr().x+theMeterSpacing.x)/theMeterSpacing.x))*theMeterSpacing.x, ((int)((drect.lr().y-theMeterSpacing.y)/theMeterSpacing.y))*theMeterSpacing.y); ossimDrect meterSpacing(ulMeter, lrMeter, OSSIM_RIGHT_HANDED); for(double horizontal = meterSpacing.ul().x; horizontal <= meterSpacing.lr().x; horizontal+=theMeterSpacing.x) { ossimDpt tipt; // top ossimDpt bipt; // bottom ossimDpt tdpt(horizontal, meterSpacing.ul().y); ossimDpt bdpt(horizontal, meterSpacing.lr().y); mapProj->eastingNorthingToLineSample(tdpt, tipt); mapProj->eastingNorthingToLineSample(bdpt, bipt); if(rect.clip(tipt, bipt)) { ossimAnnotationLineObject* line = new ossimAnnotationLineObject(tipt, bipt); line->setColor(theMeterGridColor.getR(), theMeterGridColor.getG(), theMeterGridColor.getB()); addFixedAnnotation(line); } } // do the left side labels for(double vertical = meterSpacing.ul().y; vertical >= meterSpacing.lr().y; vertical-=theMeterSpacing.y) { ossimDpt lipt; ossimDpt ript; ossimDpt ldpt(meterSpacing.ul().x, vertical); ossimDpt rdpt(meterSpacing.ur().x, vertical); mapProj->eastingNorthingToLineSample(ldpt, lipt); mapProj->eastingNorthingToLineSample(rdpt, ript); if(rect.clip(lipt, ript)) { ossimAnnotationLineObject* line = new ossimAnnotationLineObject(lipt, ript); line->setColor(theMeterGridColor.getR(), theMeterGridColor.getG(), theMeterGridColor.getB()); addFixedAnnotation(line); } } } } void ossimMapCompositionSource::addMeterGridLabels() { const ossimMapProjection* mapProj = inputMapProjection(); if(mapProj) { ossimDpt dptArray[4]; ossimDrect rect = getViewingRect(); mapProj->lineSampleToEastingNorthing(rect.ul(), dptArray[0]); mapProj->lineSampleToEastingNorthing(rect.ur(), dptArray[1]); mapProj->lineSampleToEastingNorthing(rect.lr(), dptArray[2]); mapProj->lineSampleToEastingNorthing(rect.ll(), dptArray[3]); ossimDrect drect(dptArray[0], dptArray[1], dptArray[2], dptArray[3], OSSIM_RIGHT_HANDED); ossimDpt ulMeter(((int)((drect.ul().x-theMeterSpacing.x)/theMeterSpacing.x))*theMeterSpacing.x, ((int)((drect.ul().y+theMeterSpacing.y)/theMeterSpacing.y))*theMeterSpacing.y); ossimDpt lrMeter(((int)((drect.lr().x+theMeterSpacing.x)/theMeterSpacing.x))*theMeterSpacing.x, ((int)((drect.lr().y-theMeterSpacing.y)/theMeterSpacing.y))*theMeterSpacing.y); ossimDrect meterSpacing(ulMeter, lrMeter, OSSIM_RIGHT_HANDED); ossimDrect labelRect; // Since we support overlapping grid lables. We will shift // the meter label if there exists a gegraphic label. To // do this we need to compute an extra shift length based // on the font type on each of the sides. We could actually make this // shift adjustable later???? // long extraTopDelta = 0; long extraBottomDelta = 0; long extraLeftDelta = 0; long extraRightDelta = 0; if(theTopGeographicLabelFlag&&theGeographicTopLabelFont.valid()) { ossimDms dms(180, false); ossimString dmsString = dms.toString(theTopGeographicFormat.c_str()); theGeographicTopLabelFont->setString(dmsString); ossimIrect box; theGeographicTopLabelFont->getBoundingBox(box); extraTopDelta = box.height(); } if(theBottomGeographicLabelFlag&&theGeographicBottomLabelFont.valid()) { ossimDms dms(180, false); ossimString dmsString = dms.toString(theBottomGeographicFormat.c_str()); theGeographicBottomLabelFont->setString(dmsString); ossimIrect box; theGeographicBottomLabelFont->getBoundingBox(box); extraBottomDelta = box.height(); } if(theLeftGeographicLabelFlag&&theGeographicLeftLabelFont.valid()) { ossimDms dms(90.0, true); ossimString dmsString = dms.toString(theLeftGeographicFormat.c_str()); theGeographicLeftLabelFont->setString(dmsString); ossimIrect box; theGeographicLeftLabelFont->getBoundingBox(box); extraLeftDelta = box.width(); } if(theRightGeographicLabelFlag&&theGeographicRightLabelFont.valid()) { ossimDms dms(90.0, true); ossimString dmsString = dms.toString(theRightGeographicFormat.c_str()); theGeographicRightLabelFont->setString(dmsString); ossimIrect box; theGeographicRightLabelFont->getBoundingBox(box); extraRightDelta = box.width(); } if(theTopMeterLabelFlag || theBottomMeterLabelFlag) { for(double horizontal = meterSpacing.ul().x; horizontal <= meterSpacing.lr().x; horizontal+=theMeterSpacing.x) { ossimDpt tipt; // top ossimDpt bipt; // bottom ossimDpt tdpt(horizontal, meterSpacing.ul().y); ossimDpt bdpt(horizontal, meterSpacing.lr().y); mapProj->eastingNorthingToLineSample(tdpt, tipt); mapProj->eastingNorthingToLineSample(bdpt, bipt); rect.clip(tipt, bipt); tipt = ossimIpt(tipt); bipt = ossimIpt(bipt); if(theTopMeterLabelFlag&&rect.clip(tipt, bipt)) { ossimAnnotationFontObject* topLabel = new ossimAnnotationFontObject(ossimIpt(0,0), ossimString::toString(horizontal).c_str()); topLabel->setFont(theMeterTopLabelFont.get()); topLabel->setGeometryInformation(theMeterTopLabelFontInfo); topLabel->computeBoundingRect(); ossimDrect boundsTop; topLabel->getBoundingRect(boundsTop); ossimIpt centerTop(ossim::round(tipt.x), ossim::round(rect.ul().y-(boundsTop.height()/2))); topLabel->setColor(theTopMeterLabelColor.getR(), theTopMeterLabelColor.getG(), theTopMeterLabelColor.getB()); topLabel->setCenterPosition(centerTop); topLabel->computeBoundingRect(); topLabel->getBoundingRect(labelRect); if(rect.intersects(labelRect)) { ossimIrect intersection = rect.clipToRect(labelRect); centerTop.y -= ossim::round(rect.ul().y - intersection.lr().y); } centerTop.y -= (24+extraTopDelta); // this will need to be the tick height later; topLabel->setCenterPosition(centerTop); topLabel->computeBoundingRect(); addFixedAnnotation(topLabel); if(theTopMeterTickFlag) { ossimAnnotationLineObject* lineLabel = new ossimAnnotationLineObject(ossimIpt(ossim::round(tipt.x), ossim::round(tipt.y-24)), ossimIpt(ossim::round(tipt.x), ossim::round(tipt.y))); lineLabel->setColor(theTopMeterLabelColor.getR(), theTopMeterLabelColor.getG(), theTopMeterLabelColor.getB()); addFixedAnnotation(lineLabel); } } // ------------------------- BOTTOM ---------------------------- if(theBottomMeterLabelFlag&&rect.pointWithin(bipt)) { ossimAnnotationFontObject* bottomLabel = new ossimAnnotationFontObject(ossimIpt(0,0), ossimString::toString(horizontal).c_str()); bottomLabel->setFont(theMeterBottomLabelFont.get()); bottomLabel->setGeometryInformation(theMeterBottomLabelFontInfo); bottomLabel->computeBoundingRect(); ossimDrect boundsBottom; bottomLabel->getBoundingRect(boundsBottom); ossimIpt centerBottom(ossim::round(bipt.x), ossim::round(rect.lr().y+(boundsBottom.height()/2))); bottomLabel->setColor(theBottomMeterLabelColor.getR(), theBottomMeterLabelColor.getG(), theBottomMeterLabelColor.getB()); bottomLabel->setCenterPosition(centerBottom); bottomLabel->computeBoundingRect(); bottomLabel->getBoundingRect(labelRect); if(rect.intersects(labelRect)) { ossimIrect intersection = rect.clipToRect(labelRect); centerBottom.y += ossim::round(rect.lr().y - intersection.ul().y); } centerBottom.y += (24+extraBottomDelta); // this will need to be the tick height later; bottomLabel->setCenterPosition(centerBottom); bottomLabel->computeBoundingRect(); addFixedAnnotation(bottomLabel); if(theBottomMeterTickFlag) { ossimAnnotationLineObject* lineLabel = new ossimAnnotationLineObject(ossimIpt(ossim::round(bipt.x), ossim::round(bipt.y+24)), ossimIpt(ossim::round(bipt.x), ossim::round(bipt.y))); lineLabel->setColor(theBottomMeterLabelColor.getR(), theBottomMeterLabelColor.getG(), theBottomMeterLabelColor.getB()); addFixedAnnotation(lineLabel); } } } } if(theLeftMeterLabelFlag || theRightMeterLabelFlag) { for(double vertical = meterSpacing.ul().y; vertical >= meterSpacing.lr().y; vertical-=theMeterSpacing.y) { ossimDpt lipt; ossimDpt ript; ossimDpt ldpt(meterSpacing.ul().x, vertical); ossimDpt rdpt(meterSpacing.ur().x, vertical); mapProj->eastingNorthingToLineSample(ldpt, lipt); mapProj->eastingNorthingToLineSample(rdpt, ript); if(rect.clip(lipt, ript)) { //------------------------------------------------ Left label ---------------------------------------------- ossimAnnotationFontObject* leftLabel = new ossimAnnotationFontObject(ossimIpt(0,0), ossimString::toString(vertical).c_str()); leftLabel->setFont(theMeterLeftLabelFont.get()); leftLabel->setGeometryInformation(theMeterLeftLabelFontInfo); leftLabel->computeBoundingRect(); ossimDrect boundsLeft; leftLabel->getBoundingRect(boundsLeft); ossimIpt centerLeft(ossim::round(rect.ul().x-(boundsLeft.width()/2)), ossim::round(lipt.y)); leftLabel->setColor(theLeftMeterLabelColor.getR(), theLeftMeterLabelColor.getG(), theLeftMeterLabelColor.getB()); leftLabel->setCenterPosition(centerLeft); leftLabel->computeBoundingRect(); leftLabel->getBoundingRect(labelRect); if(rect.intersects(labelRect)) { ossimIrect intersection = rect.clipToRect(labelRect); centerLeft.x -= ossim::round(intersection.lr().x - rect.ul().x); } centerLeft.x -= (24+extraLeftDelta); // this will need to be the tick height later; leftLabel->setCenterPosition(centerLeft); leftLabel->computeBoundingRect(); addFixedAnnotation(leftLabel); if(theLeftMeterTickFlag) { ossimAnnotationLineObject* lineLabel = new ossimAnnotationLineObject(ossimIpt(ossim::round(lipt.x-24), ossim::round(lipt.y)), ossimIpt(ossim::round(lipt.x), ossim::round(lipt.y))); lineLabel->setColor(theLeftMeterLabelColor.getR(), theLeftMeterLabelColor.getG(), theLeftMeterLabelColor.getB()); addFixedAnnotation(lineLabel); } //--------------------------------RIGHT----------------------------------------------------------- ossimAnnotationFontObject* rightLabel = new ossimAnnotationFontObject(ossimIpt(0,0), ossimString::toString(vertical).c_str()); rightLabel->setFont(theMeterRightLabelFont.get()); rightLabel->setGeometryInformation(theMeterRightLabelFontInfo); rightLabel->computeBoundingRect(); ossimDrect boundsRight; rightLabel->getBoundingRect(boundsRight); ossimIpt centerRight(ossim::round(rect.ur().x+(boundsRight.width()/2)), ossim::round(ript.y)); rightLabel->setColor(theRightMeterLabelColor.getR(), theRightMeterLabelColor.getG(), theRightMeterLabelColor.getB()); rightLabel->setCenterPosition(centerRight); rightLabel->computeBoundingRect(); rightLabel->getBoundingRect(labelRect); if(rect.intersects(labelRect)) { ossimIrect intersection = rect.clipToRect(labelRect); centerRight.x += ossim::round(intersection.ul().x - rect.ur().x); } centerRight.x += (24+extraRightDelta); // this will need to be the tick height later; rightLabel->setCenterPosition(centerRight); rightLabel->computeBoundingRect(); addFixedAnnotation(rightLabel); if(theRightMeterTickFlag) { ossimAnnotationLineObject* lineLabel = new ossimAnnotationLineObject(ossimIpt(ossim::round(ript.x+24), ossim::round(ript.y)), ossimIpt(ossim::round(ript.x), ossim::round(ript.y))); lineLabel->setColor(theRightMeterLabelColor.getR(), theRightMeterLabelColor.getG(), theRightMeterLabelColor.getB()); addFixedAnnotation(lineLabel); } } } } } } void ossimMapCompositionSource::addMeterGridReseaux() { const ossimMapProjection* mapProj = inputMapProjection(); if(mapProj) { ossimDpt dpt[4]; ossimDrect rect = getViewingRect(); mapProj->lineSampleToEastingNorthing(rect.ul(), dpt[0]); mapProj->lineSampleToEastingNorthing(rect.ur(), dpt[1]); mapProj->lineSampleToEastingNorthing(rect.lr(), dpt[2]); mapProj->lineSampleToEastingNorthing(rect.ll(), dpt[3]); ossimDrect drect(dpt[0], dpt[1], dpt[2], dpt[3], OSSIM_RIGHT_HANDED); ossimDpt ulMeter(((int)((drect.ul().x-theMeterSpacing.x)/theMeterSpacing.x))*theMeterSpacing.x, ((int)((drect.ul().y+theMeterSpacing.y)/theMeterSpacing.y))*theMeterSpacing.y); ossimDpt lrMeter(((int)((drect.lr().x+theMeterSpacing.x)/theMeterSpacing.x))*theMeterSpacing.x, ((int)((drect.lr().y-theMeterSpacing.y)/theMeterSpacing.y))*theMeterSpacing.y); ossimDrect meterSpacing(ulMeter, lrMeter, OSSIM_RIGHT_HANDED); ossimDpt ipt; // top for(double vertical = meterSpacing.ul().y; vertical >= meterSpacing.lr().y; vertical-=theMeterSpacing.y) { for(double horizontal = meterSpacing.ul().x; horizontal <= meterSpacing.lr().x; horizontal+=theMeterSpacing.x) { ossimDpt dpt(horizontal, vertical); mapProj->eastingNorthingToLineSample(dpt, ipt); ossimIpt rounded(ipt); if(rect.pointWithin(ossimDpt(rounded))) { ossimIpt horizontalStart(rounded.x-10, rounded.y); ossimIpt horizontalEnd(rounded.x+10, rounded.y); ossimIpt verticalStart(rounded.x, rounded.y-10); ossimIpt verticalEnd(rounded.x, rounded.y+10); ossimAnnotationLineObject* line1 = new ossimAnnotationLineObject(horizontalStart, horizontalEnd); ossimAnnotationLineObject* line2 = new ossimAnnotationLineObject(verticalStart,verticalEnd); line1->setColor(theMeterGridColor.getR(), theMeterGridColor.getG(), theMeterGridColor.getB()); line2->setColor(theMeterGridColor.getR(), theMeterGridColor.getG(), theMeterGridColor.getB()); addFixedAnnotation(line1); addFixedAnnotation(line2); } } } } } void ossimMapCompositionSource::addTitle() { ossimAnnotationFontObject* title = new ossimAnnotationFontObject(ossimIpt(0,0), theTitleString); title->setGeometryInformation(theTitleFontInfo); title->setFont(theTitleFont.get()); title->setColor(theTitleColor.getR(), theTitleColor.getG(), theTitleColor.getB()); title->setCenterPosition(theTopBorder.midPoint()); title->computeBoundingRect(); addFixedAnnotation(title); } ossimIrect ossimMapCompositionSource::getViewingRect()const { ossimIrect result; result.makeNan(); if(theInputConnection) { result = theInputConnection->getBoundingRect(); if(!result.hasNans()) { ossimIpt mid = result.midPoint(); ossim_int32 w = result.width(); ossim_int32 h = result.width(); if(theViewWidthHeight.x >-1) { w = theViewWidthHeight.x; } if(theViewWidthHeight.y >-1) { h = theViewWidthHeight.y; } ossimIpt ul(mid.x - w/2, mid.y - h/2); result = ossimIrect(ul.x, ul.y, ul.x + w-1, ul.y + h -1); } } return result; } void ossimMapCompositionSource::drawAnnotations( ossimRefPtr tile) { if (!theImage) { return; } theImage->setCurrentImageData(theTile); if(theImage->getImageData().valid()) { ossimAnnotationSource::AnnotationObjectListType::iterator object = theFixedAnnotationList.begin(); while(object != theFixedAnnotationList.end()) { if((*object).valid()) { (*object)->draw(*theImage); } ++object; } } ossimAnnotationSource::drawAnnotations(tile); } void ossimMapCompositionSource::deleteFixedAnnotations() { theFixedAnnotationList.clear(); } void ossimMapCompositionSource::setProperty(ossimRefPtr property) { if(!property.valid()) return; ossimRefPtr tempProp = 0; ossimFontProperty* fontProp = 0; ossimColorProperty* colorProp = 0; ossimBooleanProperty* booleanProp = 0; if(property->getName() == "Geographic label properties") { ossimContainerProperty* containerProp = PTR_CAST(ossimContainerProperty, property.get()); if(containerProp) { // first set the font format // tempProp = containerProp->getProperty("Top font"); fontProp = PTR_CAST(ossimFontProperty, tempProp.get()); if(fontProp) { setGeographicTopLabelFont(fontProp->getFontInformation()); } tempProp = containerProp->getProperty("Bottom font"); fontProp = PTR_CAST(ossimFontProperty, tempProp.get()); if(fontProp) { setGeographicBottomLabelFont(fontProp->getFontInformation()); } tempProp = containerProp->getProperty("Left font"); fontProp = PTR_CAST(ossimFontProperty, tempProp.get()); if(fontProp) { setGeographicLeftLabelFont(fontProp->getFontInformation()); } tempProp = containerProp->getProperty("Right font"); fontProp = PTR_CAST(ossimFontProperty, tempProp.get()); if(fontProp) { setGeographicRightLabelFont(fontProp->getFontInformation()); } // set color property tempProp = containerProp->getProperty("Top color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(colorProp) { setTopGeographicLabelColor(colorProp->getColor()); } tempProp = containerProp->getProperty("Bottom color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(colorProp) { setBottomGeographicLabelColor(colorProp->getColor()); } tempProp = containerProp->getProperty("Left color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(colorProp) { setLeftGeographicLabelColor(colorProp->getColor()); } tempProp = containerProp->getProperty("Right color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(colorProp) { setRightGeographicLabelColor(colorProp->getColor()); } // set enable flags tempProp = containerProp->getProperty("Top enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setTopGeographicLabelFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Bottom enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setBottomGeographicLabelFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Left enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setLeftGeographicLabelFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Right enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setRightGeographicLabelFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Top tick enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setTopGeographicTickMarkFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Bottom tick enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setBottomGeographicTickMarkFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Left tick enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setLeftGeographicTickMarkFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Right tick enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setRightGeographicTickMarkFlag(booleanProp->getBoolean()); } } } else if(property->getName() == "Geographic grid properties") { ossimContainerProperty* containerProp = PTR_CAST(ossimContainerProperty, property.get()); if(containerProp) { tempProp = containerProp->getProperty("Grid type"); if(tempProp.valid()) { ossimString value = tempProp->valueToString(); if(value == "none") { setGeographicGridType(OSSIM_GRID_NONE); } else if(value == "line") { setGeographicGridType(OSSIM_GRID_LINE); } else if(value == "reseaux") { setGeographicGridType(OSSIM_GRID_RESEAUX); } } tempProp = containerProp->getProperty("Horizontal spacing"); if(tempProp.valid()) { setGeographicSpacingLon(tempProp->valueToString().toDouble()); } tempProp = containerProp->getProperty("Vertical spacing"); if(tempProp.valid()) { setGeographicSpacingLat(tempProp->valueToString().toDouble()); } tempProp = containerProp->getProperty("Color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(tempProp.valid()) { setGeographicGridColor(colorProp->getColor()); } } } else if(property->getName() == "Meter label properties") { ossimContainerProperty* containerProp = PTR_CAST(ossimContainerProperty, property.get()); if(containerProp) { // first set the font format // tempProp = containerProp->getProperty("Top font"); fontProp = PTR_CAST(ossimFontProperty, tempProp.get()); if(fontProp) { setMeterTopLabelFont(fontProp->getFontInformation()); } tempProp = containerProp->getProperty("Bottom font"); fontProp = PTR_CAST(ossimFontProperty, tempProp.get()); if(fontProp) { setMeterBottomLabelFont(fontProp->getFontInformation()); } tempProp = containerProp->getProperty("Left font"); fontProp = PTR_CAST(ossimFontProperty, tempProp.get()); if(fontProp) { setMeterLeftLabelFont(fontProp->getFontInformation()); } tempProp = containerProp->getProperty("Right font"); fontProp = PTR_CAST(ossimFontProperty, tempProp.get()); if(fontProp) { setMeterRightLabelFont(fontProp->getFontInformation()); } // set color property tempProp = containerProp->getProperty("Top color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(colorProp) { setTopMeterLabelColor(colorProp->getColor()); } tempProp = containerProp->getProperty("Bottom color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(colorProp) { setBottomMeterLabelColor(colorProp->getColor()); } tempProp = containerProp->getProperty("Left color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(colorProp) { setLeftMeterLabelColor(colorProp->getColor()); } tempProp = containerProp->getProperty("Right color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(colorProp) { setRightMeterLabelColor(colorProp->getColor()); } // set enable flags tempProp = containerProp->getProperty("Top enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setTopMeterLabelFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Bottom enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setBottomMeterLabelFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Left enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setLeftMeterLabelFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Right enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setRightMeterLabelFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Top tick enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setTopMeterTickMarkFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Bottom tick enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setBottomMeterTickMarkFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Left tick enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setLeftMeterTickMarkFlag(booleanProp->getBoolean()); } tempProp = containerProp->getProperty("Right tick enabled"); booleanProp = PTR_CAST(ossimBooleanProperty, tempProp.get()); if(booleanProp) { setRightMeterTickMarkFlag(booleanProp->getBoolean()); } } } else if(property->getName() == "Meter grid properties") { ossimContainerProperty* containerProp = PTR_CAST(ossimContainerProperty, property.get()); if(containerProp) { tempProp = containerProp->getProperty("Grid type"); if(tempProp.valid()) { ossimString value = tempProp->valueToString(); if(value == "none") { setMeterGridType(OSSIM_GRID_NONE); } else if(value == "line") { setMeterGridType(OSSIM_GRID_LINE); } else if(value == "reseaux") { setMeterGridType(OSSIM_GRID_RESEAUX); } } tempProp = containerProp->getProperty("Horizontal spacing"); if(tempProp.valid()) { setMeterSpacingX(tempProp->valueToString().toDouble()); } tempProp = containerProp->getProperty("Vertical spacing"); if(tempProp.valid()) { setMeterSpacingY(tempProp->valueToString().toDouble()); } tempProp = containerProp->getProperty("Color"); colorProp = PTR_CAST(ossimColorProperty, tempProp.get()); if(tempProp.valid()) { setMeterGridColor(colorProp->getColor()); } } } else if(property->getName() == "Title properties") { ossimContainerProperty* container = PTR_CAST(ossimContainerProperty, property.get()); if(container) { ossimProperty* titleProp = container->getProperty("Title").get(); if(titleProp) { setTitle(titleProp->valueToString()); } ossimFontProperty* fontProp = PTR_CAST(ossimFontProperty, container->getProperty("Font").get()); ossimColorProperty* colorProp = PTR_CAST(ossimColorProperty, container->getProperty("Color").get()); if(fontProp) { setTitleFont(fontProp->getFontInformation()); } if(colorProp) { setTitleColor(colorProp->getColor()); } } } else if(property->getName() == "Viewport properties") { ossimContainerProperty* container = PTR_CAST(ossimContainerProperty, property.get()); if(container) { int w = -1; int h = -1; tempProp = container->getProperty("Width"); if(tempProp.valid()) { w = tempProp->valueToString().toInt32(); } tempProp = container->getProperty("Height"); if(tempProp.valid()) { h = tempProp->valueToString().toInt32(); } setViewWidthHeight(ossimIpt(w, h)); } } else if(property->getName() == "Border color") { colorProp = PTR_CAST(ossimColorProperty, property.get()); if(colorProp) { setBorderColor(colorProp->getColor()); } } else if(property->getName() == "Border size") { ossimContainerProperty* container = PTR_CAST(ossimContainerProperty, property.get()); if(container) { tempProp = container->getProperty("Top"); if(tempProp.valid()) { setTopBorderLength(tempProp->valueToString().toInt32()); } tempProp = container->getProperty("Bottom"); if(tempProp.valid()) { setBottomBorderLength(tempProp->valueToString().toInt32()); } tempProp = container->getProperty("Left"); if(tempProp.valid()) { setLeftBorderLength(tempProp->valueToString().toInt32()); } tempProp = container->getProperty("Right"); if(tempProp.valid()) { setRightBorderLength(tempProp->valueToString().toInt32()); } } } else { ossimAnnotationSource::setProperty(property); } } ossimRefPtr ossimMapCompositionSource::getProperty(const ossimString& name)const { if(name == "Viewport properties") { ossimContainerProperty* container = new ossimContainerProperty(name); container->addChild(new ossimNumericProperty("Width", ossimString::toString(theViewWidthHeight.x), -1,1.0/DBL_EPSILON)); container->addChild(new ossimNumericProperty("Height", ossimString::toString(theViewWidthHeight.y), -1,1.0/DBL_EPSILON)); container->setCacheRefreshBit(); return container; } else if(name == "Geographic label properties") { ossimContainerProperty* container = new ossimContainerProperty(name); container->addChild(new ossimFontProperty("Top font", theGeographicTopLabelFontInfo)); container->addChild(new ossimColorProperty("Top color", theTopGeographicLabelColor)); container->addChild(new ossimBooleanProperty("Top enabled", theTopGeographicLabelFlag)); container->addChild(new ossimBooleanProperty("Top tick enabled", theTopGeographicTickFlag)); container->addChild(new ossimFontProperty("Bottom font", theGeographicBottomLabelFontInfo)); container->addChild(new ossimColorProperty("Bottom color", theBottomGeographicLabelColor)); container->addChild(new ossimBooleanProperty("Bottom enabled", theBottomGeographicLabelFlag)); container->addChild(new ossimBooleanProperty("Bottom tick enabled", theBottomGeographicTickFlag)); container->addChild(new ossimFontProperty("Left font", theGeographicLeftLabelFontInfo)); container->addChild(new ossimColorProperty("Left color", theLeftGeographicLabelColor)); container->addChild(new ossimBooleanProperty("Left enabled", theLeftGeographicLabelFlag)); container->addChild(new ossimBooleanProperty("Left tick enabled", theLeftGeographicTickFlag)); container->addChild(new ossimFontProperty("Right font", theGeographicRightLabelFontInfo)); container->addChild(new ossimColorProperty("Right color", theRightGeographicLabelColor)); container->addChild(new ossimBooleanProperty("Right enabled", theRightGeographicLabelFlag)); container->addChild(new ossimBooleanProperty("Right tick enabled", theRightGeographicTickFlag)); container->setCacheRefreshBit(); return container; } else if(name == "Geographic grid properties") { ossimContainerProperty* container = new ossimContainerProperty(name); std::vector gridTypeConstraints; ossimString value = GRID_TYPE_ENUM_NAMES[(int)theGeographicGridType]; gridTypeConstraints.push_back("none"); gridTypeConstraints.push_back("line"); gridTypeConstraints.push_back("reseaux"); container->addChild(new ossimStringProperty("Grid type", value, false, gridTypeConstraints)); container->addChild(new ossimColorProperty("Color", theGeographicGridColor)); container->addChild(new ossimNumericProperty("Horizontal spacing", ossimString::toString(theGeographicSpacing.x), 0.0, 180.0)); container->addChild(new ossimNumericProperty("Vertical spacing", ossimString::toString(theGeographicSpacing.y), 0.0, 180.0)); container->setCacheRefreshBit(); return container; } else if(name == "Meter label properties") { ossimContainerProperty* container = new ossimContainerProperty(name); container->addChild(new ossimFontProperty("Top font", theMeterTopLabelFontInfo)); container->addChild(new ossimColorProperty("Top color", theTopMeterLabelColor)); container->addChild(new ossimBooleanProperty("Top enabled", theTopMeterLabelFlag)); container->addChild(new ossimBooleanProperty("Top tick enabled", theTopMeterTickFlag)); container->addChild(new ossimFontProperty("Bottom font", theMeterBottomLabelFontInfo)); container->addChild(new ossimColorProperty("Bottom color", theBottomMeterLabelColor)); container->addChild(new ossimBooleanProperty("Bottom enabled", theBottomMeterLabelFlag)); container->addChild(new ossimBooleanProperty("Bottom tick enabled", theBottomMeterTickFlag)); container->addChild(new ossimFontProperty("Left font", theMeterLeftLabelFontInfo)); container->addChild(new ossimColorProperty("Left color", theLeftMeterLabelColor)); container->addChild(new ossimBooleanProperty("Left enabled", theLeftMeterLabelFlag)); container->addChild(new ossimBooleanProperty("Left tick enabled", theLeftMeterTickFlag)); container->addChild(new ossimFontProperty("Right font", theMeterRightLabelFontInfo)); container->addChild(new ossimColorProperty("Right color", theRightMeterLabelColor)); container->addChild(new ossimBooleanProperty("Right enabled", theRightMeterLabelFlag)); container->addChild(new ossimBooleanProperty("Right tick enabled", theRightMeterTickFlag)); container->setCacheRefreshBit(); return container; } else if(name == "Meter grid properties") { ossimContainerProperty* container = new ossimContainerProperty(name); std::vector gridTypeConstraints; ossimString value = GRID_TYPE_ENUM_NAMES[(int)theMeterGridType]; gridTypeConstraints.push_back("none"); gridTypeConstraints.push_back("line"); gridTypeConstraints.push_back("reseaux"); container->addChild(new ossimStringProperty("Grid type", value, false, gridTypeConstraints)); container->addChild(new ossimColorProperty("Color", theMeterGridColor)); container->addChild(new ossimNumericProperty("Horizontal spacing", ossimString::toString(theMeterSpacing.x), 0.0, 1.0/DBL_EPSILON)); container->addChild(new ossimNumericProperty("Vertical spacing", ossimString::toString(theMeterSpacing.y), 0.0, 1.0/DBL_EPSILON)); container->setCacheRefreshBit(); return container; } else if(name == "Title properties") { ossimContainerProperty* container = new ossimContainerProperty(name); container->addChild(new ossimTextProperty("Title", theTitleString)); container->addChild(new ossimFontProperty("Font", theTitleFontInfo)); container->addChild(new ossimColorProperty("Color", theTitleColor)); container->setCacheRefreshBit(); return container; } else if(name == "Border size") { ossimContainerProperty* container = new ossimContainerProperty(name); container->addChild(new ossimNumericProperty("Top", ossimString::toString(theTopBorderLength), 0,10000)); container->addChild(new ossimNumericProperty("Bottom", ossimString::toString(theBottomBorderLength), 0,10000)); container->addChild(new ossimNumericProperty("Left", ossimString::toString(theLeftBorderLength), 0,10000)); container->addChild(new ossimNumericProperty("Right", ossimString::toString(theRightBorderLength), 0,10000)); container->setCacheRefreshBit(); return container; } else if(name == "Border color") { ossimColorProperty* colorProp = new ossimColorProperty(name, theBorderColor); colorProp->setCacheRefreshBit(); return colorProp; } else if(name == "Viewport properties") { } return ossimAnnotationSource::getProperty(name); } void ossimMapCompositionSource::getPropertyNames(std::vector& propertyNames)const { ossimAnnotationSource::getPropertyNames(propertyNames); propertyNames.push_back("Title properties"); propertyNames.push_back("Border size"); propertyNames.push_back("Border color"); propertyNames.push_back("Viewport properties"); propertyNames.push_back("Geographic label properties"); propertyNames.push_back("Geographic grid properties"); propertyNames.push_back("Meter label properties"); propertyNames.push_back("Meter grid properties"); } bool ossimMapCompositionSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, VIEW_WIDTH_KW, theViewWidthHeight.x, true); kwl.add(prefix, VIEW_HEIGHT_KW, theViewWidthHeight.x, true); kwl.add(prefix, METER_GRID_SPACING_X_KW, theMeterSpacing.x, true); kwl.add(prefix, METER_GRID_SPACING_Y_KW, theMeterSpacing.y, true); kwl.add(prefix, GEO_GRID_SPACING_LON_KW, theGeographicSpacing.lon, true); kwl.add(prefix, GEO_GRID_SPACING_LAT_KW, theGeographicSpacing.lat, true); ossimString meterGridType = "line"; if(theMeterGridType == OSSIM_GRID_NONE) { meterGridType = "none"; } else if(theMeterGridType == OSSIM_GRID_RESEAUX) { meterGridType = "reseaux"; } kwl.add(prefix, METER_GRID_TYPE_KW, meterGridType.c_str(), true); ossimString geoGridType = "line"; if(theGeographicGridType == OSSIM_GRID_NONE) { geoGridType = "none"; } else if(theGeographicGridType == OSSIM_GRID_RESEAUX) { geoGridType = "reseaux"; } kwl.add(prefix, GEO_GRID_TYPE_KW, geoGridType.c_str(), true); kwl.add(prefix, TOP_BORDER_LENGTH_KW, theTopBorderLength, true); kwl.add(prefix, BOTTOM_BORDER_LENGTH_KW, theBottomBorderLength, true); kwl.add(prefix, LEFT_BORDER_LENGTH_KW, theLeftBorderLength, true); kwl.add(prefix, RIGHT_BORDER_LENGTH_KW, theRightBorderLength, true); kwl.add(prefix, BORDER_COLOR_KW, (ossimString::toString(theBorderColor.getR()) +" "+ ossimString::toString(theBorderColor.getG()) +" "+ ossimString::toString(theBorderColor.getB())).c_str(), true); kwl.add(prefix, GEO_GRID_COLOR_KW, (ossimString::toString(theGeographicGridColor.getR()) +" "+ ossimString::toString(theGeographicGridColor.getG()) +" "+ ossimString::toString(theGeographicGridColor.getB())).c_str(), true); kwl.add(prefix, METER_GRID_COLOR_KW, (ossimString::toString(theMeterGridColor.getR()) +" "+ ossimString::toString(theMeterGridColor.getG()) +" "+ ossimString::toString(theMeterGridColor.getB())).c_str(), true); kwl.add(prefix, TITLE_STRING_KW, theTitleString.c_str(), true); kwl.add(prefix, TITLE_COLOR_KW, (ossimString::toString(theTitleColor.getR()) +" "+ ossimString::toString(theTitleColor.getG()) +" "+ ossimString::toString(theTitleColor.getB())).c_str(), true); kwl.add(prefix, TOP_GEO_LABEL_COLOR_KW, (ossimString::toString(theTopGeographicLabelColor.getR()) +" "+ ossimString::toString(theTopGeographicLabelColor.getG()) +" "+ ossimString::toString(theTopGeographicLabelColor.getB())).c_str(), true); kwl.add(prefix, BOTTOM_GEO_LABEL_COLOR_KW, (ossimString::toString(theBottomGeographicLabelColor.getR()) +" "+ ossimString::toString(theBottomGeographicLabelColor.getG()) +" "+ ossimString::toString(theBottomGeographicLabelColor.getB())).c_str(), true); kwl.add(prefix, LEFT_GEO_LABEL_COLOR_KW, (ossimString::toString(theLeftGeographicLabelColor.getR()) +" "+ ossimString::toString(theLeftGeographicLabelColor.getG()) +" "+ ossimString::toString(theLeftGeographicLabelColor.getB())).c_str(), true); kwl.add(prefix, RIGHT_GEO_LABEL_COLOR_KW, (ossimString::toString(theRightGeographicLabelColor.getR()) +" "+ ossimString::toString(theRightGeographicLabelColor.getG()) +" "+ ossimString::toString(theRightGeographicLabelColor.getB())).c_str(), true); kwl.add(prefix, TOP_GEO_LABEL_FORMAT_KW, theTopGeographicFormat, true); kwl.add(prefix, BOTTOM_GEO_LABEL_FORMAT_KW, theBottomGeographicFormat, true); kwl.add(prefix, LEFT_GEO_LABEL_FORMAT_KW, theLeftGeographicFormat, true); kwl.add(prefix, RIGHT_GEO_LABEL_FORMAT_KW, theRightGeographicFormat, true); kwl.add(prefix, TOP_GEO_LABEL_FLAG_KW, (int)theTopGeographicLabelFlag, true); kwl.add(prefix, BOTTOM_GEO_LABEL_FLAG_KW, (int)theBottomGeographicLabelFlag, true); kwl.add(prefix, LEFT_GEO_LABEL_FLAG_KW, (int)theLeftGeographicLabelFlag, true); kwl.add(prefix, RIGHT_GEO_LABEL_FLAG_KW, (int)theRightGeographicLabelFlag, true); kwl.add(prefix, TOP_METER_LABEL_COLOR_KW, (ossimString::toString(theTopMeterLabelColor.getR()) +" "+ ossimString::toString(theTopMeterLabelColor.getG()) +" "+ ossimString::toString(theTopMeterLabelColor.getB())).c_str(), true); kwl.add(prefix, BOTTOM_METER_LABEL_COLOR_KW, (ossimString::toString(theBottomMeterLabelColor.getR()) +" "+ ossimString::toString(theBottomMeterLabelColor.getG()) +" "+ ossimString::toString(theBottomMeterLabelColor.getB())).c_str(), true); kwl.add(prefix, LEFT_METER_LABEL_COLOR_KW, (ossimString::toString(theLeftMeterLabelColor.getR()) +" "+ ossimString::toString(theLeftMeterLabelColor.getG()) +" "+ ossimString::toString(theLeftMeterLabelColor.getB())).c_str(), true); kwl.add(prefix, RIGHT_METER_LABEL_COLOR_KW, (ossimString::toString(theRightMeterLabelColor.getR()) +" "+ ossimString::toString(theRightMeterLabelColor.getG()) +" "+ ossimString::toString(theRightMeterLabelColor.getB())).c_str(), true); kwl.add(prefix, TOP_METER_LABEL_FLAG_KW, (int)theTopMeterLabelFlag, true); kwl.add(prefix, BOTTOM_METER_LABEL_FLAG_KW, (int)theBottomMeterLabelFlag, true); kwl.add(prefix, LEFT_METER_LABEL_FLAG_KW, (int)theLeftMeterLabelFlag, true); kwl.add(prefix, RIGHT_METER_LABEL_FLAG_KW, (int)theRightMeterLabelFlag, true); theGeographicTopLabelFontInfo.saveState(kwl, (ossimString(prefix) + ossimString(TOP_GEO_LABEL_FONT_KW) + ".").c_str()); theGeographicBottomLabelFontInfo.saveState(kwl, (ossimString(prefix) + ossimString(BOTTOM_GEO_LABEL_FONT_KW) + ".").c_str()); theGeographicLeftLabelFontInfo.saveState(kwl, (ossimString(prefix) + ossimString(LEFT_GEO_LABEL_FONT_KW) + ".").c_str()); theGeographicRightLabelFontInfo.saveState(kwl, (ossimString(prefix) + ossimString(RIGHT_GEO_LABEL_FONT_KW) + ".").c_str()); theMeterTopLabelFontInfo.saveState(kwl, (ossimString(prefix) + ossimString(TOP_METER_LABEL_FONT_KW) + ".").c_str()); theMeterBottomLabelFontInfo.saveState(kwl, (ossimString(prefix) + ossimString(BOTTOM_METER_LABEL_FONT_KW) + ".").c_str()); theMeterLeftLabelFontInfo.saveState(kwl, (ossimString(prefix) + ossimString(LEFT_METER_LABEL_FONT_KW) + ".").c_str()); theMeterRightLabelFontInfo.saveState(kwl, (ossimString(prefix) + ossimString(RIGHT_METER_LABEL_FONT_KW) + ".").c_str()); theTitleFontInfo.saveState(kwl, (ossimString(prefix) + ossimString(TITLE_FONT_KW) + ".").c_str()); return ossimImageSource::saveState(kwl, prefix); } bool ossimMapCompositionSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* viewWidth = kwl.find(prefix, VIEW_WIDTH_KW); const char* viewHeight = kwl.find(prefix, VIEW_HEIGHT_KW); const char* meterGridSpacingX = kwl.find(prefix, METER_GRID_SPACING_X_KW); const char* meterGridSpacingY = kwl.find(prefix, METER_GRID_SPACING_Y_KW); const char* geoGridSpacingLon = kwl.find(prefix, GEO_GRID_SPACING_LON_KW); const char* geoGridSpacingLat = kwl.find(prefix, GEO_GRID_SPACING_LAT_KW); const char* meterGridType = kwl.find(prefix, METER_GRID_TYPE_KW); const char* geoGridType = kwl.find(prefix, GEO_GRID_TYPE_KW); const char* topBorderLength = kwl.find(prefix, TOP_BORDER_LENGTH_KW); const char* bottomBorderLength = kwl.find(prefix, BOTTOM_BORDER_LENGTH_KW); const char* leftBorderLength = kwl.find(prefix, LEFT_BORDER_LENGTH_KW); const char* rightBorderLength = kwl.find(prefix, RIGHT_BORDER_LENGTH_KW); const char* borderColor = kwl.find(prefix, BORDER_COLOR_KW); const char* geoGridColor = kwl.find(prefix, GEO_GRID_COLOR_KW); const char* meterGridColor = kwl.find(prefix, METER_GRID_COLOR_KW); const char* titleString = kwl.find(prefix, TITLE_STRING_KW); const char* titleColor = kwl.find(prefix, TITLE_COLOR_KW); const char* topGeoLabelColor = kwl.find(prefix, TOP_GEO_LABEL_COLOR_KW); const char* bottomGeoLabelColor = kwl.find(prefix, BOTTOM_GEO_LABEL_COLOR_KW); const char* leftGeoLabelColor = kwl.find(prefix, LEFT_GEO_LABEL_COLOR_KW); const char* rightGeoLabelColor = kwl.find(prefix, RIGHT_GEO_LABEL_COLOR_KW); const char* topMeterLabelColor = kwl.find(prefix, TOP_METER_LABEL_COLOR_KW); const char* bottomMeterLabelColor = kwl.find(prefix, BOTTOM_METER_LABEL_COLOR_KW); const char* leftMeterLabelColor = kwl.find(prefix, LEFT_METER_LABEL_COLOR_KW); const char* rightMeterLabelColor = kwl.find(prefix, RIGHT_METER_LABEL_COLOR_KW); const char* topGeoLabelFormat = kwl.find(prefix, TOP_GEO_LABEL_FORMAT_KW); const char* bottomGeoLabelFormat = kwl.find(prefix, BOTTOM_GEO_LABEL_FORMAT_KW); const char* leftGeoLabelFormat = kwl.find(prefix, LEFT_GEO_LABEL_FORMAT_KW); const char* rightGeoLabelFormat = kwl.find(prefix, RIGHT_GEO_LABEL_FORMAT_KW); const char* topGeoLabelFlag = kwl.find(prefix, TOP_GEO_LABEL_FLAG_KW); const char* bottomGeoLabelFlag = kwl.find(prefix, BOTTOM_GEO_LABEL_FLAG_KW); const char* leftGeoLabelFlag = kwl.find(prefix, LEFT_GEO_LABEL_FLAG_KW); const char* rightGeoLabelFlag = kwl.find(prefix, RIGHT_GEO_LABEL_FLAG_KW); const char* topMeterLabelFlag = kwl.find(prefix, TOP_METER_LABEL_FLAG_KW); const char* bottomMeterLabelFlag = kwl.find(prefix, BOTTOM_METER_LABEL_FLAG_KW); const char* leftMeterLabelFlag = kwl.find(prefix, LEFT_METER_LABEL_FLAG_KW); const char* rightMeterLabelFlag = kwl.find(prefix, RIGHT_METER_LABEL_FLAG_KW); deleteFixedAnnotations(); theViewWidthHeight.makeNan(); if(viewWidth) { theViewWidthHeight.x = ossimString(viewWidth).toLong(); } if(viewHeight) { theViewWidthHeight.y = ossimString(viewHeight).toLong(); } if(meterGridSpacingX) { theMeterSpacing.x = ossimString(meterGridSpacingX).toDouble(); } if(meterGridSpacingY) { theMeterSpacing.y = ossimString(meterGridSpacingY).toDouble(); } if(geoGridSpacingLon) { theGeographicSpacing.lon = ossimString(geoGridSpacingLon).toDouble(); } if(geoGridSpacingLat) { theGeographicSpacing.lat = ossimString(geoGridSpacingLat).toDouble(); } if(meterGridType) { ossimString type = ossimString(meterGridType).trim().downcase(); if(type == "reseaux") { theMeterGridType = OSSIM_GRID_RESEAUX; } else if(type == "line") { theMeterGridType = OSSIM_GRID_LINE; } else { theMeterGridType = OSSIM_GRID_NONE; } } if(geoGridType) { ossimString type = ossimString(geoGridType).trim().downcase(); if(type == "reseaux") { theGeographicGridType = OSSIM_GRID_RESEAUX; } else if(type == "line") { theGeographicGridType = OSSIM_GRID_LINE; } else { theGeographicGridType = OSSIM_GRID_NONE; } } if(topBorderLength) { theTopBorderLength = ossimString(topBorderLength).toULong(); } if(bottomBorderLength) { theBottomBorderLength = ossimString(bottomBorderLength).toULong(); } if(leftBorderLength) { theLeftBorderLength = ossimString(leftBorderLength).toULong(); } if(rightBorderLength) { theRightBorderLength = ossimString(rightBorderLength).toULong(); } if(borderColor) { istringstream in(borderColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theBorderColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(geoGridColor) { istringstream in(geoGridColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theGeographicGridColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(meterGridColor) { istringstream in(meterGridColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theMeterGridColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(titleString) { theTitleString = titleString; } if(titleColor) { istringstream in(titleColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theTitleColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(topGeoLabelColor) { istringstream in(topGeoLabelColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theTopGeographicLabelColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(bottomGeoLabelColor) { istringstream in(bottomGeoLabelColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theBottomGeographicLabelColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(leftGeoLabelColor) { istringstream in(leftGeoLabelColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theLeftGeographicLabelColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(rightGeoLabelColor) { istringstream in(rightGeoLabelColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theRightGeographicLabelColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } ///// if(topMeterLabelColor) { istringstream in(topMeterLabelColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theTopMeterLabelColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(bottomMeterLabelColor) { istringstream in(bottomMeterLabelColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theBottomMeterLabelColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(leftMeterLabelColor) { istringstream in(leftMeterLabelColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theLeftMeterLabelColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(rightMeterLabelColor) { istringstream in(rightMeterLabelColor); ossimString r; ossimString g; ossimString b; in >> r >> g >> b; theRightMeterLabelColor = ossimRgbVector((ossim_uint8)r.toUInt32(), (ossim_uint8)g.toUInt32(), (ossim_uint8)b.toUInt32()); } if(topGeoLabelFormat) { theTopGeographicFormat = topGeoLabelFormat; } if(bottomGeoLabelFormat) { theBottomGeographicFormat = bottomGeoLabelFormat; } if(leftGeoLabelFormat) { theLeftGeographicFormat = leftGeoLabelFormat; } if(rightGeoLabelFormat) { theRightGeographicFormat = rightGeoLabelFormat; } if(topGeoLabelFlag) { theTopGeographicLabelFlag = ossimString(topGeoLabelFlag).toBool(); } if(bottomGeoLabelFlag) { theBottomGeographicLabelFlag = ossimString(bottomGeoLabelFlag).toBool(); } if(leftGeoLabelFlag) { theLeftGeographicLabelFlag = ossimString(leftGeoLabelFlag).toBool(); } if(rightGeoLabelFlag) { theRightGeographicLabelFlag = ossimString(rightGeoLabelFlag).toBool(); } if(topMeterLabelFlag) { theTopMeterLabelFlag = ossimString(topMeterLabelFlag).toBool(); } if(bottomMeterLabelFlag) { theBottomMeterLabelFlag = ossimString(bottomMeterLabelFlag).toBool(); } if(leftMeterLabelFlag) { theLeftMeterLabelFlag = ossimString(leftMeterLabelFlag).toBool(); } if(rightMeterLabelFlag) { theRightMeterLabelFlag = ossimString(rightMeterLabelFlag).toBool(); } theGeographicTopLabelFontInfo.loadState(kwl, (ossimString(prefix) + ossimString(TOP_GEO_LABEL_FONT_KW) + ".").c_str()); theGeographicBottomLabelFontInfo.loadState(kwl, (ossimString(prefix) + ossimString(BOTTOM_GEO_LABEL_FONT_KW) + ".").c_str()); theGeographicLeftLabelFontInfo.loadState(kwl, (ossimString(prefix) + ossimString(LEFT_GEO_LABEL_FONT_KW) + ".").c_str()); theGeographicRightLabelFontInfo.loadState(kwl, (ossimString(prefix) + ossimString(RIGHT_GEO_LABEL_FONT_KW) + ".").c_str()); theMeterTopLabelFontInfo.loadState(kwl, (ossimString(prefix) + ossimString(TOP_METER_LABEL_FONT_KW) + ".").c_str()); theMeterBottomLabelFontInfo.loadState(kwl, (ossimString(prefix) + ossimString(BOTTOM_METER_LABEL_FONT_KW) + ".").c_str()); theMeterLeftLabelFontInfo.loadState(kwl, (ossimString(prefix) + ossimString(LEFT_METER_LABEL_FONT_KW) + ".").c_str()); theMeterRightLabelFontInfo.loadState(kwl, (ossimString(prefix) + ossimString(RIGHT_METER_LABEL_FONT_KW) + ".").c_str()); theTitleFontInfo.loadState(kwl, (ossimString(prefix) + ossimString(TITLE_FONT_KW) + ".").c_str()); theTitleFont = ossimFontFactoryRegistry::instance()->createFont(theTitleFontInfo); theGeographicTopLabelFont = ossimFontFactoryRegistry::instance()->createFont(theGeographicTopLabelFontInfo); theGeographicBottomLabelFont = ossimFontFactoryRegistry::instance()->createFont(theGeographicBottomLabelFontInfo); theGeographicLeftLabelFont = ossimFontFactoryRegistry::instance()->createFont(theGeographicLeftLabelFontInfo); theGeographicRightLabelFont = ossimFontFactoryRegistry::instance()->createFont(theGeographicRightLabelFontInfo); theMeterTopLabelFont = ossimFontFactoryRegistry::instance()->createFont(theMeterTopLabelFontInfo); theMeterBottomLabelFont = ossimFontFactoryRegistry::instance()->createFont(theMeterBottomLabelFontInfo); theMeterLeftLabelFont = ossimFontFactoryRegistry::instance()->createFont(theMeterLeftLabelFontInfo); theMeterRightLabelFont = ossimFontFactoryRegistry::instance()->createFont(theMeterRightLabelFontInfo); vector info; if(!theTitleFont) { theTitleFont = (ossimFont*)ossimFontFactoryRegistry::instance()->getDefaultFont()->dup(); theTitleFont->getFontInformation(info); theTitleFontInfo = info[0]; } if(!theGeographicTopLabelFont) { info.clear(); theGeographicTopLabelFont = (ossimFont*)ossimFontFactoryRegistry::instance()->getDefaultFont()->dup(); theGeographicTopLabelFont->getFontInformation(info); theGeographicTopLabelFontInfo = info[0]; } if(!theGeographicBottomLabelFont) { info.clear(); theGeographicBottomLabelFont = (ossimFont*)ossimFontFactoryRegistry::instance()->getDefaultFont()->dup(); theGeographicBottomLabelFont->getFontInformation(info); theGeographicBottomLabelFontInfo = info[0]; } if(!theGeographicLeftLabelFont) { info.clear(); theGeographicLeftLabelFont = (ossimFont*)ossimFontFactoryRegistry::instance()->getDefaultFont()->dup(); theGeographicLeftLabelFont->getFontInformation(info); theGeographicLeftLabelFontInfo = info[0]; } if(!theGeographicRightLabelFont) { info.clear(); theGeographicRightLabelFont = (ossimFont*)ossimFontFactoryRegistry::instance()->getDefaultFont()->dup(); theGeographicRightLabelFont->getFontInformation(info); theGeographicRightLabelFontInfo = info[0]; } if(!theMeterTopLabelFont) { info.clear(); theMeterTopLabelFont = (ossimFont*)ossimFontFactoryRegistry::instance()->getDefaultFont()->dup(); theMeterTopLabelFont->getFontInformation(info); theMeterTopLabelFontInfo = info[0]; } if(!theMeterBottomLabelFont) { info.clear(); theMeterBottomLabelFont = (ossimFont*)ossimFontFactoryRegistry::instance()->getDefaultFont()->dup(); theMeterBottomLabelFont->getFontInformation(info); theMeterBottomLabelFontInfo = info[0]; } if(!theMeterLeftLabelFont) { info.clear(); theMeterLeftLabelFont = (ossimFont*)ossimFontFactoryRegistry::instance()->getDefaultFont()->dup(); theMeterLeftLabelFont->getFontInformation(info); theMeterLeftLabelFontInfo = info[0]; } if(!theMeterRightLabelFont) { info.clear(); theMeterRightLabelFont = (ossimFont*)ossimFontFactoryRegistry::instance()->getDefaultFont()->dup(); theMeterRightLabelFont->getFontInformation(info); theMeterRightLabelFontInfo = info[0]; } bool result = ossimAnnotationSource::loadState(kwl, prefix); layoutAnnotations(); return result; } ossimScalarType ossimMapCompositionSource::getOutputScalarType() const { return OSSIM_UCHAR; } ossim_uint32 ossimMapCompositionSource::getNumberOfOutputBands() const { return 3; } ossimIpt ossimMapCompositionSource::getViewWidthHeight()const { return theViewWidthHeight; } void ossimMapCompositionSource::getViewWidthHeight(ossimIpt& widthHeight)const { widthHeight = theViewWidthHeight; } void ossimMapCompositionSource::setViewWidthHeight(const ossimIpt& widthHeight) { theViewWidthHeight = widthHeight; } ossim_int32 ossimMapCompositionSource::getTopBorderLength()const { return theTopBorderLength; } ossim_int32 ossimMapCompositionSource::getBottomBorderLength()const { return theBottomBorderLength; } ossim_int32 ossimMapCompositionSource::getLeftBorderLength()const { return theLeftBorderLength; } ossim_int32 ossimMapCompositionSource::getRightBorderLength()const { return theRightBorderLength; } void ossimMapCompositionSource::setTopBorderLength(ossim_int32 length) { theTopBorderLength = length; } void ossimMapCompositionSource::setBottomBorderLength(ossim_int32 length) { theBottomBorderLength = length; } void ossimMapCompositionSource::setLeftBorderLength(ossim_int32 length) { theLeftBorderLength = length; } void ossimMapCompositionSource::setRightBorderLength(ossim_int32 length) { theRightBorderLength = length; } void ossimMapCompositionSource::setGeographicSpacingLat(double value) { theGeographicSpacing.lat = value; } void ossimMapCompositionSource::setGeographicSpacingLon(double value) { theGeographicSpacing.lon = value; } void ossimMapCompositionSource::setMeterSpacingX(double value) { theMeterSpacing.x = value; } void ossimMapCompositionSource::setMeterSpacingY(double value) { theMeterSpacing.y = value; } void ossimMapCompositionSource::setMeterSpacing(double x, double y) { theMeterSpacing.x = x; theMeterSpacing.y = y; } void ossimMapCompositionSource::setGeographicSpacing(double lat, double lon) { theGeographicSpacing.lat = lat; theGeographicSpacing.lon = lon; } ossimDpt ossimMapCompositionSource::getGeographicSpacing()const { return theGeographicSpacing; } ossimDpt ossimMapCompositionSource::getMeterSpacing()const { return theMeterSpacing; } ossimString ossimMapCompositionSource::getTopGeographicLabelFormat()const { return theTopGeographicFormat; } ossimString ossimMapCompositionSource::getBottomGeographicLabelFormat()const { return theBottomGeographicFormat; } ossimString ossimMapCompositionSource::getLeftGeographicLabelFormat()const { return theLeftGeographicFormat; } ossimString ossimMapCompositionSource::getRightGeographicLabelFormat()const { return theRightGeographicFormat; } ossimString ossimMapCompositionSource::getTitle()const { return theTitleString; } ossimRgbVector ossimMapCompositionSource::getTitleColor()const { return theTitleColor; } void ossimMapCompositionSource::setTitleColor(const ossimRgbVector& color) { if(theTitleColor != color) { theTitleColor = color; } } void ossimMapCompositionSource::setTitle(const ossimString& s) { if(theTitleString != s) { theTitleString = s; } } ossimFontInformation ossimMapCompositionSource::getTitleFont()const { return theTitleFontInfo; } ossimFontInformation ossimMapCompositionSource::getGeographicTopLabelFontInfo()const { return theGeographicTopLabelFontInfo; } ossimFontInformation ossimMapCompositionSource::getGeographicBottomLabelFontInfo()const { return theGeographicBottomLabelFontInfo; } ossimFontInformation ossimMapCompositionSource::getGeographicLeftLabelFontInfo()const { return theGeographicLeftLabelFontInfo; } ossimFontInformation ossimMapCompositionSource::getGeographicRightLabelFontInfo()const { return theGeographicRightLabelFontInfo; } ossimFontInformation ossimMapCompositionSource::getMeterTopLabelFontInfo()const { return theMeterTopLabelFontInfo; } ossimFontInformation ossimMapCompositionSource::getMeterBottomLabelFontInfo()const { return theMeterBottomLabelFontInfo; } ossimFontInformation ossimMapCompositionSource::getMeterLeftLabelFontInfo()const { return theMeterLeftLabelFontInfo; } ossimFontInformation ossimMapCompositionSource::getMeterRightLabelFontInfo()const { return theMeterRightLabelFontInfo; } ossimRgbVector ossimMapCompositionSource::getBorderColor()const { return theBorderColor; } void ossimMapCompositionSource::setBorderColor(const ossimRgbVector& color) { theBorderColor=color; } ossimRgbVector ossimMapCompositionSource::getGeographicGridColor()const { return theGeographicGridColor; } ossimRgbVector ossimMapCompositionSource::getMeterGridColor()const { return theMeterGridColor; } ossimRgbVector ossimMapCompositionSource::getTopGeographicLabelColor()const { return theTopGeographicLabelColor; } ossimRgbVector ossimMapCompositionSource::getBottomGeographicLabelColor()const { return theBottomGeographicLabelColor; } ossimRgbVector ossimMapCompositionSource::getLeftGeographicLabelColor()const { return theLeftGeographicLabelColor; } ossimRgbVector ossimMapCompositionSource::getRightGeographicLabelColor()const { return theRightGeographicLabelColor; } void ossimMapCompositionSource::setGeographicGridColor(const ossimRgbVector& color) { theGeographicGridColor = color; } void ossimMapCompositionSource::setTopGeographicLabelColor(const ossimRgbVector& color) { theTopGeographicLabelColor = color; } void ossimMapCompositionSource::setBottomGeographicLabelColor(const ossimRgbVector& color) { theBottomGeographicLabelColor = color; } void ossimMapCompositionSource::setLeftGeographicLabelColor(const ossimRgbVector& color) { theLeftGeographicLabelColor = color; } void ossimMapCompositionSource::setRightGeographicLabelColor(const ossimRgbVector& color) { theRightGeographicLabelColor = color; } void ossimMapCompositionSource::setGeographicLabelColor(const ossimRgbVector& color) { setTopGeographicLabelColor(color); setBottomGeographicLabelColor(color); setLeftGeographicLabelColor(color); setRightGeographicLabelColor(color); } ossimRgbVector ossimMapCompositionSource::getTopMeterLabelColor()const { return theTopMeterLabelColor; } ossimRgbVector ossimMapCompositionSource::getBottomMeterLabelColor()const { return theBottomMeterLabelColor; } ossimRgbVector ossimMapCompositionSource::getLeftMeterLabelColor()const { return theLeftMeterLabelColor; } ossimRgbVector ossimMapCompositionSource::getRightMeterLabelColor()const { return theRightMeterLabelColor; } void ossimMapCompositionSource::setTopMeterLabelColor(const ossimRgbVector& color) { theTopMeterLabelColor = color; } void ossimMapCompositionSource::setBottomMeterLabelColor(const ossimRgbVector& color) { theBottomMeterLabelColor = color; } void ossimMapCompositionSource::setLeftMeterLabelColor(const ossimRgbVector& color) { theLeftMeterLabelColor = color; } void ossimMapCompositionSource::setRightMeterLabelColor(const ossimRgbVector& color) { theRightMeterLabelColor = color; } void ossimMapCompositionSource::setMeterLabelColor(const ossimRgbVector& color) { setTopMeterLabelColor(color); setBottomMeterLabelColor(color); setLeftMeterLabelColor(color); setRightMeterLabelColor(color); } void ossimMapCompositionSource::setMeterGridColor(const ossimRgbVector& color) { theMeterGridColor = color; } void ossimMapCompositionSource::setMeterGridType(ossimGridLineType gridType) { theMeterGridType = gridType; } void ossimMapCompositionSource::setGeographicGridType(ossimGridLineType gridType) { theGeographicGridType = gridType; } void ossimMapCompositionSource::setBorderColor(ossimRgbVector& color) { theBorderColor = color; } ossimMapCompositionSource::ossimGridLineType ossimMapCompositionSource::getGeographicGridType()const { return theGeographicGridType; } ossimMapCompositionSource::ossimGridLineType ossimMapCompositionSource::getMeterGridType()const { return theMeterGridType; } void ossimMapCompositionSource::setGeographicTickMarkFlag(bool flag) { setTopGeographicTickMarkFlag(flag); setBottomGeographicTickMarkFlag(flag); setLeftGeographicTickMarkFlag(flag); setRightGeographicTickMarkFlag(flag); } void ossimMapCompositionSource::setTopGeographicTickMarkFlag(bool flag) { theTopGeographicTickFlag = flag; } void ossimMapCompositionSource::setBottomGeographicTickMarkFlag(bool flag) { theBottomGeographicTickFlag = flag; } void ossimMapCompositionSource::setLeftGeographicTickMarkFlag(bool flag) { theLeftGeographicTickFlag = flag; } void ossimMapCompositionSource::setRightGeographicTickMarkFlag(bool flag) { theRightGeographicTickFlag = flag; } void ossimMapCompositionSource::setTopGeographicLabelFlag(bool flag) { theTopGeographicLabelFlag = flag; } void ossimMapCompositionSource::setBottomGeographicLabelFlag(bool flag) { theBottomGeographicLabelFlag = flag; } void ossimMapCompositionSource::setLeftGeographicLabelFlag(bool flag) { theLeftGeographicLabelFlag = flag; } void ossimMapCompositionSource::setRightGeographicLabelFlag(bool flag) { theRightGeographicLabelFlag = flag; } bool ossimMapCompositionSource::getTopGeographicTickMarkFlag()const { return theTopGeographicTickFlag; } bool ossimMapCompositionSource::getBottomGeographicTickMarkFlag()const { return theBottomGeographicTickFlag; } bool ossimMapCompositionSource::getLeftGeographicTickMarkFlag()const { return theLeftGeographicTickFlag; } bool ossimMapCompositionSource::getRightGeographicTickMarkFlag()const { return theRightGeographicTickFlag; } bool ossimMapCompositionSource::getTopGeographicLabelFlag()const { return theTopGeographicLabelFlag; } bool ossimMapCompositionSource::getBottomGeographicLabelFlag()const { return theBottomGeographicLabelFlag; } bool ossimMapCompositionSource::getLeftGeographicLabelFlag()const { return theLeftGeographicLabelFlag; } bool ossimMapCompositionSource::getRightGeographicLabelFlag()const { return theRightGeographicLabelFlag; } void ossimMapCompositionSource::setMeterTickMarkFlag(bool flag) { setTopMeterTickMarkFlag(flag); setBottomMeterTickMarkFlag(flag); setLeftMeterTickMarkFlag(flag); setRightMeterTickMarkFlag(flag); } void ossimMapCompositionSource::setTopMeterTickMarkFlag(bool flag) { theTopMeterTickFlag = flag; } void ossimMapCompositionSource::setBottomMeterTickMarkFlag(bool flag) { theBottomMeterTickFlag = flag; } void ossimMapCompositionSource::setLeftMeterTickMarkFlag(bool flag) { theLeftMeterTickFlag = flag; } void ossimMapCompositionSource::setRightMeterTickMarkFlag(bool flag) { theRightMeterTickFlag = flag; } void ossimMapCompositionSource::setTopMeterLabelFlag(bool flag) { theTopMeterLabelFlag = flag; } void ossimMapCompositionSource::setBottomMeterLabelFlag(bool flag) { theBottomMeterLabelFlag = flag; } void ossimMapCompositionSource::setLeftMeterLabelFlag(bool flag) { theLeftMeterLabelFlag = flag; } void ossimMapCompositionSource::setRightMeterLabelFlag(bool flag) { theRightMeterLabelFlag = flag; } bool ossimMapCompositionSource::getTopMeterTickMarkFlag()const { return theTopMeterTickFlag; } bool ossimMapCompositionSource::getBottomMeterTickMarkFlag()const { return theBottomMeterTickFlag; } bool ossimMapCompositionSource::getLeftMeterTickMarkFlag()const { return theLeftMeterTickFlag; } bool ossimMapCompositionSource::getRightMeterTickMarkFlag()const { return theRightMeterTickFlag; } bool ossimMapCompositionSource::getTopMeterLabelFlag()const { return theTopMeterLabelFlag; } bool ossimMapCompositionSource::getBottomMeterLabelFlag()const { return theBottomMeterLabelFlag; } bool ossimMapCompositionSource::getLeftMeterLabelFlag()const { return theLeftMeterLabelFlag; } bool ossimMapCompositionSource::getRightMeterLabelFlag()const { return theRightMeterLabelFlag; } void ossimMapCompositionSource::addFixedAnnotation(ossimAnnotationObject* obj) { if(obj) { theFixedAnnotationList.push_back(obj); } } //************************************************************************************************** //! Fetches the input connection's image geometry and verifies that it is a map projection. //! Returns NULL if no valid projection found. //************************************************************************************************** const ossimMapProjection* ossimMapCompositionSource::inputMapProjection() const { if (!theInputConnection) return 0; ossimRefPtr inputGeom = theInputConnection->getImageGeometry(); if (!inputGeom) return 0; return PTR_CAST(ossimMapProjection, inputGeom->getProjection()); } ossim-Miami-2.9.1/src/imaging/ossimMaskFilter.cpp000066400000000000000000000623231352751253100217430ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // Modified by: Elan Sharghi (1/20/2009) // Description: Class definition for ossimMaskFilter. // //************************************************************************* // $Id: ossimMaskFilter.cpp 20409 2011-12-22 16:57:05Z dburken $ #include #include #include #include #include #include #include using namespace std; static const char * MASK_FILTER_MASK_TYPE_KW = "mask_type"; RTTI_DEF1(ossimMaskFilter, "ossimMaskFilter", ossimImageSource); ossimMaskFilter::ossimMaskFilter(ossimObject* owner) : ossimImageSource(owner, 1, 1, true, false), theMaskType(OSSIM_MASK_TYPE_SELECT), theTile(0) { } ossimMaskFilter::~ossimMaskFilter() { } //************************************************************************************************* void ossimMaskFilter::setMaskSource(ossimImageSource* maskSource) { theMaskSource = maskSource; } ossimRefPtr ossimMaskFilter::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { ossimImageSource* imageSource = PTR_CAST(ossimImageSource, getInput(0)); if (!imageSource || !theMaskSource.valid()) { ossimRefPtr(); return theTile; } ossimRefPtr imageSourceData; ossimRefPtr maskSourceData; imageSourceData = imageSource->getTile(rect, resLevel); if(!isSourceEnabled()) return imageSourceData; if (!theTile.valid()) allocate(); maskSourceData = theMaskSource->getTile(rect, resLevel); if(!imageSourceData.valid() || !theTile.valid()) { return ossimRefPtr(); } theTile->setOrigin(rect.ul()); if(theTile->getImageRectangle() != rect) { theTile->setImageRectangle(rect); theTile->initialize(); } if(!imageSourceData.valid()) { return theTile; } if(!maskSourceData.valid()) { return imageSourceData; } if(imageSourceData->getDataObjectStatus() != OSSIM_NULL) { return executeMaskFilter(imageSourceData, maskSourceData); } return theTile; } bool ossimMaskFilter::canConnectMyInputTo(ossim_int32 /* index */, const ossimConnectableObject* object)const { return (PTR_CAST(ossimImageSource, object)!= 0); } void ossimMaskFilter::initialize() { if(getInput(0)) { // Force an allocate on the next getTile. theTile = 0; } } void ossimMaskFilter::allocate() { if(getInput()) { theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); } } ossimRefPtr ossimMaskFilter::executeMaskFilter( ossimRefPtr imageSourceData, ossimRefPtr maskSourceData) { if(!theTile) { theTile = (ossimImageData*)imageSourceData->dup(); if(!theTile->getBuf()) { theTile->initialize(); } } else { ossim_uint32 tw = theTile->getWidth(); ossim_uint32 th = theTile->getHeight(); ossim_uint32 dw = imageSourceData->getWidth(); ossim_uint32 dh = imageSourceData->getHeight(); theTile->setWidthHeight(imageSourceData->getWidth(), imageSourceData->getHeight()); theTile->setOrigin(imageSourceData->getOrigin()); if((tw*th) != (dw*dh)) { theTile->initialize(); } theTile->setDataObjectStatus(imageSourceData->getDataObjectStatus()); } theTile->loadTile(imageSourceData.get()); theTile->setDataObjectStatus(imageSourceData->getDataObjectStatus()); switch(theMaskType) { case OSSIM_MASK_TYPE_SELECT: case OSSIM_MASK_TYPE_SELECT_CLAMP_MIN: { return executeMaskFilterSelect(theTile, maskSourceData); } case OSSIM_MASK_TYPE_INVERT: { return executeMaskFilterInvertSelect(theTile, maskSourceData); } case OSSIM_MASK_TYPE_WEIGHTED: { return executeMaskFilterWeighted(theTile, maskSourceData); } case OSSIM_MASK_TYPE_BINARY: case OSSIM_MASK_TYPE_BINARY_INVERSE: { return executeMaskFilterBinary(theTile, maskSourceData); } } return imageSourceData; } ossimRefPtr ossimMaskFilter::executeMaskFilterSelect( ossimRefPtr imageSourceData, ossimRefPtr maskSourceData) { if(maskSourceData->getScalarType() != OSSIM_UCHAR) { ossimNotify(ossimNotifyLevel_WARN) << "ossimMaskFilter::executeMaskFilterSelect WARNING: Only uchar masks are supported" << endl; return imageSourceData; } switch(imageSourceData->getScalarType()) { case OSSIM_UCHAR: { executeMaskFilterSelection((ossim_uint8)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { executeMaskFilterSelection((ossim_uint16)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_SSHORT16: { executeMaskFilterSelection((ossim_sint16)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { executeMaskFilterSelection((float)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { executeMaskFilterSelection((double)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimMaskFilter::executeMaskFilterSelect WARNING: Unknown scalar type" << endl; break; } } return theTile; } ossimRefPtr ossimMaskFilter::executeMaskFilterInvertSelect(ossimRefPtr imageSourceData, ossimRefPtr maskSourceData) { if(maskSourceData->getScalarType() != OSSIM_UCHAR) { ossimNotify(ossimNotifyLevel_WARN) << "ossimMaskFilter::executeMaskFilterSelect WARNING: Only uchar masks are supported" << endl; return imageSourceData; } switch(imageSourceData->getScalarType()) { case OSSIM_UCHAR: { executeMaskFilterInvertSelection((ossim_uint8)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { executeMaskFilterInvertSelection((ossim_uint16)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_SSHORT16: { executeMaskFilterInvertSelection((ossim_sint16)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { executeMaskFilterInvertSelection((float)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { executeMaskFilterInvertSelection((double)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimMaskFilter::executeMaskFilterSelect WARNING: Unknown scalar type" << endl; break; } } return theTile; } ossimRefPtr ossimMaskFilter::executeMaskFilterWeighted(ossimRefPtr imageSourceData, ossimRefPtr maskSourceData) { if(maskSourceData->getScalarType() != OSSIM_UCHAR) { ossimNotify(ossimNotifyLevel_WARN) << "ossimMaskFilter::executeMaskFilterSelect WARNING: Only uchar masks are supported" << endl; return imageSourceData; } switch(imageSourceData->getScalarType()) { case OSSIM_UCHAR: { executeMaskFilterWeighted((ossim_uint8)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { executeMaskFilterWeighted((ossim_uint16)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_SSHORT16: { executeMaskFilterWeighted((ossim_sint16)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { executeMaskFilterWeighted((float)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { executeMaskFilterWeighted((double)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimMaskFilter::executeMaskFilterSelect WARNING: Unknown scalar type" << endl; break; } } return theTile; } ossimRefPtr ossimMaskFilter::executeMaskFilterBinary( ossimRefPtr imageSourceData, ossimRefPtr maskSourceData) { if(maskSourceData->getScalarType() != OSSIM_UCHAR) { ossimNotify(ossimNotifyLevel_WARN) << "ossimMaskFilter::executeMaskFilterBinary WARNING: Only uchar masks are supported" << endl; return imageSourceData; } switch(imageSourceData->getScalarType()) { case OSSIM_UCHAR: { executeMaskFilterBinarySelection((ossim_uint8)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { executeMaskFilterBinarySelection((ossim_uint16)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_SSHORT16: { executeMaskFilterBinarySelection((ossim_sint16)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { executeMaskFilterBinarySelection((float)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { executeMaskFilterBinarySelection((double)0, (ossim_uint8)0, imageSourceData, maskSourceData); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimMaskFilter::executeMaskFilterBinary WARNING: Unknown scalar type" << endl; break; } } return theTile; } template ossimRefPtr ossimMaskFilter::executeMaskFilterSelection( inputT /* dummyInput */, maskT /* dummyMask */, ossimRefPtr imageSourceData, ossimRefPtr maskSourceData) { ossimDataObjectStatus maskDataStatus = maskSourceData->getDataObjectStatus(); ossimDataObjectStatus inputDataStatus = imageSourceData->getDataObjectStatus(); // First just check if mask is full, which means pass the image source along untouched: if (maskDataStatus == OSSIM_FULL) { theTile = imageSourceData; return theTile; } // Then check for a total mask (all mask values are 0) and return empty tile if so: if( (maskDataStatus == OSSIM_NULL) || (maskDataStatus == OSSIM_EMPTY)) { theTile->makeBlank(); return theTile; } // Finally check for blank source tile and return it if so: if( (inputDataStatus == OSSIM_NULL) || (inputDataStatus == OSSIM_EMPTY)) { theTile->makeBlank(); return theTile; } ossim_uint32 maskBands = maskSourceData->getNumberOfBands(); ossim_uint32 inputBands = imageSourceData->getNumberOfBands(); if(maskBands&&inputBands) { ossim_uint32 maxOffset = theTile->getWidth()*theTile->getHeight(); for(ossim_uint32 band = 0; band < inputBands; ++band) { maskT* bufMask = static_cast ( maskSourceData->getBuf() ); inputT* bufIn = static_cast( imageSourceData->getBuf(band) ); inputT* bufOut = static_cast( theTile->getBuf(band) ); inputT nullPix = static_cast ( theTile->getNullPix(band) ); inputT minPix = static_cast ( theTile->getMinPix(band) ); ossim_uint32 offset = 0; for(offset = 0; offset < maxOffset; ++offset) { if(*bufMask) { if ( theMaskType == OSSIM_MASK_TYPE_SELECT ) { *bufOut = *bufIn; } else { //--- // OSSIM_MASK_TYPE_SELECT_CLAMP_MIN // Use input pixel clamping any nulls to min. //--- *bufOut = *bufIn != nullPix ? *bufIn : minPix; } } else { *bufOut = nullPix; } ++bufOut; ++bufIn; ++bufMask; } } theTile->validate(); } return theTile; } template ossimRefPtr ossimMaskFilter::executeMaskFilterInvertSelection( inputT /* dummyInput */, maskT /* dummyMask */, ossimRefPtr imageSourceData, ossimRefPtr maskSourceData) { ossimDataObjectStatus maskDataStatus = maskSourceData->getDataObjectStatus(); ossimDataObjectStatus inputDataStatus = imageSourceData->getDataObjectStatus(); // First just check if mask is empty, which means pass the image source along untouched: if( (maskDataStatus == OSSIM_NULL) || (maskDataStatus == OSSIM_EMPTY)) { theTile = imageSourceData; return theTile; } // Then check for a total mask (all mask values are 1) and return empty tile if so: if (maskDataStatus == OSSIM_FULL) { theTile->makeBlank(); return theTile; } // Finally check for blank source tile and return it if so: if( (inputDataStatus == OSSIM_NULL) || (inputDataStatus == OSSIM_EMPTY)) { theTile->makeBlank(); return theTile; } ossim_uint32 maskBands = maskSourceData->getNumberOfBands(); ossim_uint32 inputBands = imageSourceData->getNumberOfBands(); if(maskBands&&inputBands) { ossim_uint32 maxOffset = theTile->getWidth()*theTile->getHeight(); for(ossim_uint32 band = 0; band < inputBands; ++band) { maskT* bufMask = (maskT*)maskSourceData->getBuf(); inputT* bufIn = (inputT*)imageSourceData->getBuf(band); inputT* bufOut = (inputT*)theTile->getBuf(band); inputT np = (inputT)theTile->getNullPix(band); ossim_uint32 offset = 0; for(offset = 0; offset < maxOffset; ++offset) { if(!*bufMask) { *bufOut = *bufIn; } else { *bufOut = np; } ++bufOut; ++bufIn; ++bufMask; } } theTile->validate(); } return theTile; } template ossimRefPtr ossimMaskFilter::executeMaskFilterWeighted( inputT /* dummyInput */, maskT /* dummyMask */, ossimRefPtr imageSourceData, ossimRefPtr maskSourceData) { ossimDataObjectStatus maskDataStatus = maskSourceData->getDataObjectStatus(); ossimDataObjectStatus inputDataStatus = imageSourceData->getDataObjectStatus(); if( (maskDataStatus == OSSIM_NULL)|| (maskDataStatus == OSSIM_EMPTY)) { theTile->makeBlank(); return theTile; } if( (inputDataStatus == OSSIM_NULL)|| (inputDataStatus == OSSIM_EMPTY)) { return theTile; } ossim_uint32 maskBands = maskSourceData->getNumberOfBands(); ossim_uint32 inputBands = imageSourceData->getNumberOfBands(); if(maskBands&&inputBands) { ossim_uint32 maxOffset = theTile->getWidth()*theTile->getHeight(); for(ossim_uint32 band = 0; band < inputBands; ++band) { maskT* bufMask = (maskT*)maskSourceData->getBuf(); inputT* bufIn = (inputT*)imageSourceData->getBuf(band); inputT* bufOut = (inputT*)theTile->getBuf(band); inputT np = (inputT)theTile->getNullPix(band); inputT minp = (inputT)theTile->getMinPix(band); ossim_uint32 offset = 0; if(inputDataStatus == OSSIM_PARTIAL) { for(offset = 0; offset < maxOffset; ++offset) { if(*bufIn != np) { *bufOut = (inputT)((*bufIn)*((double)(*bufMask)/255.0)); if((*bufOut != np)&& (*bufOut < minp)) { *bufOut = minp; } } else { *bufOut = np; } ++bufOut; ++bufIn; ++bufMask; } } else { for(offset = 0; offset < maxOffset; ++offset) { *bufOut = (inputT)((*bufIn)*((double)(*bufMask)/255.0)); if((*bufOut != np)&& (*bufOut < minp)) { *bufOut = minp; } ++bufOut; ++bufIn; ++bufMask; } } } theTile->validate(); } return theTile; } template ossimRefPtr ossimMaskFilter::executeMaskFilterBinarySelection( inputT /* dummyInput */, maskT /* dummyMask */ , ossimRefPtr imageSourceData, ossimRefPtr maskSourceData) { ossim_uint32 maskBands = maskSourceData->getNumberOfBands(); ossim_uint32 inputBands = imageSourceData->getNumberOfBands(); if(maskBands&&inputBands) { ossim_uint32 maxOffset = theTile->getWidth()*theTile->getHeight(); for(ossim_uint32 band = 0; band < inputBands; ++band) { maskT* bufMask = (maskT*)maskSourceData->getBuf(); inputT* bufOut = (inputT*)theTile->getBuf(band); const inputT NP = (inputT)theTile->getNullPix(band); const inputT MP = (inputT)theTile->getMaxPix(band); ossim_uint32 offset = 0; for(offset = 0; offset < maxOffset; ++offset) { if (theMaskType == OSSIM_MASK_TYPE_BINARY_INVERSE) { if(*bufMask) // if mask == 1 *bufOut = MP; // set to max pix else // if mask == 0 *bufOut = NP; // set to null pix } else { if(*bufMask) // if mask == 1 *bufOut = NP; // set to null pix else // if mask == 0 *bufOut = MP; // set to max pix } ++bufOut; ++bufMask; } } theTile->validate(); } return theTile; } void ossimMaskFilter::setMaskType(ossimFileSelectionMaskType type) { theMaskType = type; } void ossimMaskFilter::setMaskType(const ossimString& type) { if(type != "") { ossimString maskType = type; maskType.downcase(); if(maskType == "select") { theMaskType = OSSIM_MASK_TYPE_SELECT; } else if(maskType == "invert") { theMaskType = OSSIM_MASK_TYPE_INVERT; } else if(maskType == "weighted") { theMaskType = OSSIM_MASK_TYPE_WEIGHTED; } else if(maskType == "binary") { theMaskType = OSSIM_MASK_TYPE_BINARY; } else if(maskType == "binary_inverse") { theMaskType = OSSIM_MASK_TYPE_BINARY_INVERSE; } else if(maskType == "select_clamp_min") { theMaskType = OSSIM_MASK_TYPE_SELECT_CLAMP_MIN; } } } ossimMaskFilter::ossimFileSelectionMaskType ossimMaskFilter::getMaskType()const { return theMaskType; } ossimString ossimMaskFilter::getMaskTypeString() const { ossimString maskType; switch(theMaskType) { case OSSIM_MASK_TYPE_SELECT: { maskType = "select"; break; } case OSSIM_MASK_TYPE_INVERT: { maskType = "invert"; break; } case OSSIM_MASK_TYPE_WEIGHTED: { maskType = "weighted"; break; } case OSSIM_MASK_TYPE_BINARY: { maskType = "binary"; break; } case OSSIM_MASK_TYPE_BINARY_INVERSE: { maskType = "binary_inverse"; break; } case OSSIM_MASK_TYPE_SELECT_CLAMP_MIN: { maskType = "select_clamp_min"; break; } } return maskType; } bool ossimMaskFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimImageSource::loadState(kwl, prefix); theInputListIsFixedFlag = true; theOutputListIsFixedFlag = false; setNumberOfInputs(2); const char* lookup = kwl.find(prefix, MASK_FILTER_MASK_TYPE_KW); if (lookup) { setMaskType(ossimString(lookup)); } return result; } bool ossimMaskFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, MASK_FILTER_MASK_TYPE_KW, getMaskTypeString().c_str(), true); return ossimImageSource::saveState(kwl, prefix); } void ossimMaskFilter::setProperty(ossimRefPtr property) { if( property.valid() ) { if(property->getName() == MASK_FILTER_MASK_TYPE_KW) { setMaskType(property->valueToString()); } else { ossimImageSource::setProperty(property); } } } ossimRefPtr ossimMaskFilter::getProperty( const ossimString& name)const { ossimRefPtr result = 0; if(name == MASK_FILTER_MASK_TYPE_KW) { std::vector constraintList; constraintList.push_back(ossimString("select")); constraintList.push_back(ossimString("invert")); constraintList.push_back(ossimString("weighted")); result = new ossimStringProperty(MASK_FILTER_MASK_TYPE_KW, getMaskTypeString(), false, constraintList); } else { result = ossimImageSource::getProperty(name); } return result; } void ossimMaskFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSource::getPropertyNames(propertyNames); propertyNames.push_back(MASK_FILTER_MASK_TYPE_KW); } ossim_uint32 ossimMaskFilter::getNumberOfInputBands() const { ossimImageSource* img_source = PTR_CAST(ossimImageSource, getInput()); if (img_source) return img_source->getNumberOfInputBands(); return 0; } ossim-Miami-2.9.1/src/imaging/ossimMaxMosaic.cpp000066400000000000000000000430321352751253100215570ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 SANZ Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Kenneth Melero (kmelero@sanz.com) // // Description: This combiner is designed to "float" the maximum pixel value // of all inputs to top of the mosaic output. // //************************************************************************* // $Id: ossimMaxMosaic.cpp 23257 2015-04-13 16:57:14Z dburken $ #include #include #include #include static const ossimTrace traceDebug("ossimMaxMosaic:debug"); using namespace std; RTTI_DEF1(ossimMaxMosaic, "ossimMaxMosaic", ossimImageCombiner) ossimMaxMosaic::ossimMaxMosaic() :ossimImageCombiner(), theTile(NULL) { } ossimMaxMosaic::ossimMaxMosaic(ossimConnectableObject::ConnectableObjectList& inputSources) : ossimImageCombiner(inputSources), theTile(NULL) { } ossimMaxMosaic::~ossimMaxMosaic() { } ossimRefPtr ossimMaxMosaic::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { long size = getNumberOfInputs(); ossim_uint32 layerIdx = 0; // If there is only one in the mosaic then just return it. if(size == 1) { return getNextTile(layerIdx, 0, tileRect, resLevel); } ossimIpt origin = tileRect.ul(); ossim_uint32 w = tileRect.width(); ossim_uint32 h = tileRect.height(); if(!theTile.valid()) { // First time through... allocate(); // If we still don't have a buffer then we will leave. if(!theTile.valid()) { return ossimRefPtr(); } } ossim_uint32 tileW = theTile->getWidth(); ossim_uint32 tileH = theTile->getHeight(); if((w != tileW)|| (h != tileH)) { theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tileW*tileH)) { theTile->initialize(); } } theTile->setOrigin(origin); //--- // General Note: // // Note: I will not check for disabled or enabled since we have // no clear way to handle this within a mosaic. The default will be // to do a simple a A over B type mosaic. Derived classes should // check for the enabled and disabled and always // use this default implementation if they are disabled. //--- theTile->setOrigin(origin); theTile->makeBlank(); switch(theTile->getScalarType()) { case OSSIM_UCHAR: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SINT8: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SSHORT16: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SINT32: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_UINT32: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { if(!hasDifferentInputs()) { return combine(static_cast(0), tileRect, resLevel); } else { return combineNorm(static_cast(0), tileRect, resLevel); } } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "Scalar type = " << theTile->getScalarType() << " Not supported by ossimMaxMosaic" << endl; } } return ossimRefPtr(); } void ossimMaxMosaic::initialize() { ossimImageCombiner::initialize(); theTile = NULL; } void ossimMaxMosaic::allocate() { theTile = NULL; if( (getNumberOfInputs() > 0) && getInput(0) ) { theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); } } bool ossimMaxMosaic::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimImageCombiner::saveState(kwl, prefix); } bool ossimMaxMosaic::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimImageCombiner::loadState(kwl, prefix); } template ossimRefPtr ossimMaxMosaic::combineNorm( T,// dummy template variable const ossimIrect& tileRect, ossim_uint32 resLevel) { ossim_uint32 layerIdx = 0; ossimRefPtr destination = theTile; ossimRefPtr currentImageData = getNextNormTile(layerIdx, 0, tileRect, resLevel); if(!currentImageData) { return currentImageData; } std::vector srcBands(theLargestNumberOfInputBands); std::vector srcBandsNullPix(theLargestNumberOfInputBands); std::vector destBands(theLargestNumberOfInputBands); std::vector destBandsNullPix(theLargestNumberOfInputBands); std::vector destBandsMinPix(theLargestNumberOfInputBands); std::vector destBandsMaxPix(theLargestNumberOfInputBands); //float** srcBands = new float*[theLargestNumberOfInputBands]; //float* srcBandsNullPix = new float[theLargestNumberOfInputBands]; //T** destBands = new T*[theLargestNumberOfInputBands]; //T* destBandsNullPix = new T[theLargestNumberOfInputBands]; //T* destBandsMinPix = new T[theLargestNumberOfInputBands]; //T* destBandsMaxPix = new T[theLargestNumberOfInputBands]; ossim_uint32 band; ossim_uint32 upperBound = destination->getWidth()*destination->getHeight(); ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); destBands[band] = static_cast(theTile->getBuf(band)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); destBandsMinPix[band] = static_cast(theTile->getMinPix(band)); destBandsMaxPix[band] = static_cast(theTile->getMaxPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = static_cast(srcBands[minNumberOfBands - 1]); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); destBands[band] = static_cast(theTile->getBuf(band)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); destBandsMinPix[band] = static_cast(theTile->getMinPix(band)); destBandsMaxPix[band] = static_cast(theTile->getMaxPix(band)); } // most of the time we will not overlap so let's // copy the first tile into destination and check later. // ossim_uint32 tempBandIdx = 0; for(band = 0; band < theTile->getNumberOfBands();++band) { if(band < currentImageData->getNumberOfBands()) { theTile->copyNormalizedBufferToTile(band, (float*)currentImageData->getBuf(band)); ++tempBandIdx; } else { if(tempBandIdx) { theTile->copyNormalizedBufferToTile(band, (float*)currentImageData->getBuf(tempBandIdx-1)); } } } destination->validate(); currentImageData = getNextNormTile(layerIdx, tileRect, resLevel); while(currentImageData.valid()) { ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); ossimDataObjectStatus currentStatus = currentImageData->getDataObjectStatus(); ossimDataObjectStatus destinationStatus = destination->getDataObjectStatus(); if(destinationStatus == OSSIM_FULL) { return destination; } for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); } if((destinationStatus == OSSIM_EMPTY)&& (currentStatus != OSSIM_EMPTY)&& (currentStatus != OSSIM_NULL)) { ossim_uint32 upperBound = destination->getWidth()*destination->getHeight(); for(band=0; band < theLargestNumberOfInputBands; ++band) { float delta = destBandsMaxPix[band] - destBandsMinPix[band]; float minP = destBandsMinPix[band]; for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { destBands[band][offset] = (T)( minP + delta*srcBands[band][offset]); } } } else if((destinationStatus == OSSIM_PARTIAL)&& (currentStatus != OSSIM_EMPTY)&& (currentStatus != OSSIM_NULL)) { for(band = 0; band < theLargestNumberOfInputBands; ++band) { float delta = destBandsMaxPix[band] - destBandsMinPix[band]; float minP = destBandsMinPix[band]; for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if(destBands[band][offset] == destBandsNullPix[band]) { destBands[band][offset] = (T)(minP + delta*srcBands[band][offset]); } } } } destination->validate(); currentImageData = getNextNormTile(layerIdx, tileRect, resLevel); } // Cleanup... // delete [] srcBands; // delete [] srcBandsNullPix; // delete [] destBands; // delete [] destBandsNullPix; // delete [] destBandsMinPix; // delete [] destBandsMaxPix; return destination; } template ossimRefPtr ossimMaxMosaic::combine( T,// dummy template variable const ossimIrect& tileRect, ossim_uint32 resLevel) { ossim_uint32 layerIdx = 0; ossimRefPtr destination = theTile; ossimRefPtr currentImageData = getNextTile(layerIdx, 0, tileRect, resLevel); if(!currentImageData) { return currentImageData; } T** srcBands = new T*[theLargestNumberOfInputBands]; T* srcBandsNullPix = new T[theLargestNumberOfInputBands]; T** destBands = new T*[theLargestNumberOfInputBands]; T* destBandsNullPix = new T[theLargestNumberOfInputBands]; ossim_uint32 band; ossim_uint32 upperBound = destination->getWidth()*destination->getHeight(); ossim_uint32 bandIndex = 0; ossim_uint32 offset=0; ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); destBands[band] = static_cast(theTile->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = static_cast(srcBands[minNumberOfBands - 1]); destBands[band] = static_cast(theTile->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); destBandsNullPix[band] = static_cast(theTile->getNullPix(band)); } // most of the time we will not overlap so let's // copy the first tile into destination and check later. // for(band = 0; band < theTile->getNumberOfBands();++band) { T* destBand = destBands[band]; T* srcBand = srcBands[band]; if(destBand&&srcBand) { for(offset = 0; offset < upperBound;++offset) { *destBand = *srcBand; ++srcBand; ++destBand; } } } destination->setDataObjectStatus(currentImageData->getDataObjectStatus()); currentImageData = getNextTile(layerIdx, tileRect, resLevel); while(currentImageData.valid()) { ossim_uint32 minNumberOfBands = currentImageData->getNumberOfBands(); ossimDataObjectStatus currentStatus = currentImageData->getDataObjectStatus(); ossimDataObjectStatus destinationStatus = destination->getDataObjectStatus(); for(band = 0; band < minNumberOfBands; ++band) { srcBands[band] = static_cast(currentImageData->getBuf(band)); srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(band)); } // if the src is smaller than the destination in number // of bands we will just duplicate the last band. for(;band < theLargestNumberOfInputBands; ++band) { srcBands[band] = srcBands[minNumberOfBands - 1]; srcBandsNullPix[band] = static_cast(currentImageData->getNullPix(minNumberOfBands - 1)); } if((destinationStatus == OSSIM_PARTIAL)&& (currentStatus != OSSIM_EMPTY)&& (currentStatus != OSSIM_NULL)) { for(bandIndex = 0; bandIndex < theLargestNumberOfInputBands; ++bandIndex) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if(srcBands[bandIndex][offset] > destBands[bandIndex][offset]) { destBands[bandIndex][offset] = srcBands[bandIndex][offset]; } } } } else { ossim_uint32 upperBound = destination->getWidth()*destination->getHeight(); for(ossim_uint32 band=0; band < theLargestNumberOfInputBands; ++band) { for(ossim_uint32 offset = 0; offset < upperBound; ++offset) { if(srcBands[band][offset] > destBands[band][offset]) { destBands[band][offset] = srcBands[band][offset]; } } } } destination->validate(); currentImageData = getNextTile(layerIdx,tileRect, resLevel); } // Cleanup... delete [] srcBands; delete [] srcBandsNullPix; delete [] destBands; delete [] destBandsNullPix; return destination; } ossimString ossimMaxMosaic::getShortName()const { return ossimString("ossimMaxMosaic"); } ossimString ossimMaxMosaic::getLongName()const { return ossimString("Max Mosaic"); } ossimString ossimMaxMosaic::getDescription()const { return ossimString("Combiner which puts maximum dn value on image."); } ossim-Miami-2.9.1/src/imaging/ossimMeanMedianFilter.cpp000066400000000000000000000650571352751253100230550ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimMeanMedianFilter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimMeanMedianFilter, "ossimMeanMedianFilter", ossimImageSourceFilter); // Keywords used throughout. static const ossimString WINDOW_SIZE_KW = "window_size"; static const ossimString FILTER_TYPE_KW = "filter_type"; static const ossimString AUTO_GROW_KW = "auto_grow_rectangle_flag"; ossimMeanMedianFilter::ossimMeanMedianFilter(ossimObject* owner) :ossimImageSourceFilter(owner), theTile(0), theFilterType(OSSIM_MEDIAN), theWindowSize(3), theEnableFillNullFlag(false), theAutoGrowRectFlag(false) { setDescription(ossimString("Mean Median Filter")); } ossimMeanMedianFilter::~ossimMeanMedianFilter() { } ossimRefPtr ossimMeanMedianFilter::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if(!isSourceEnabled()) { return ossimImageSourceFilter::getTile(rect, resLevel); } ossim_uint32 halfSize = getWindowSize()>>1; ossimIrect requestRect(rect.ul().x - halfSize, rect.ul().y - halfSize, rect.lr().x + halfSize, rect.lr().y + halfSize); ossimRefPtr inputData = ossimImageSourceFilter::getTile(requestRect, resLevel); if(!inputData.valid() || !inputData->getBuf()) { return inputData; } if(!theTile.valid()) { theTile = (ossimImageData*)inputData->dup(); theTile->setImageRectangle(rect); } else { theTile->setImageRectangleAndBands(rect, inputData->getNumberOfBands()); } applyFilter(inputData); theTile->setDataObjectStatus(inputData->getDataObjectStatus()); if(theEnableFillNullFlag) { theTile->validate(); } return theTile; } void ossimMeanMedianFilter::setWindowSize(ossim_uint32 windowSize) { theWindowSize = windowSize; } ossim_uint32 ossimMeanMedianFilter::getWindowSize()const { return theWindowSize; } void ossimMeanMedianFilter::initialize() { ossimImageSourceFilter::initialize(); theTile = NULL; } void ossimMeanMedianFilter::applyFilter(ossimRefPtr& input) { switch(input->getScalarType()) { case OSSIM_UINT8: { switch (theFilterType) { case OSSIM_MEDIAN: case OSSIM_MEDIAN_FILL_NULLS: applyMedian(ossim_uint8(0), input); break; case OSSIM_MEDIAN_NULL_CENTER_ONLY: applyMedianNullCenterOnly(ossim_uint8(0), input); break; case OSSIM_MEAN: case OSSIM_MEAN_FILL_NULLS: applyMean(ossim_uint8(0), input); break; case OSSIM_MEAN_NULL_CENTER_ONLY: applyMeanNullCenterOnly(ossim_uint8(0), input); default: break; } break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { switch (theFilterType) { case OSSIM_MEDIAN: case OSSIM_MEDIAN_FILL_NULLS: applyMedian(ossim_uint16(0), input); break; case OSSIM_MEDIAN_NULL_CENTER_ONLY: applyMedianNullCenterOnly(ossim_uint16(0), input); break; case OSSIM_MEAN: case OSSIM_MEAN_FILL_NULLS: applyMean(ossim_uint16(0), input); break; case OSSIM_MEAN_NULL_CENTER_ONLY: applyMeanNullCenterOnly(ossim_uint16(0), input); break; default: break; } break; } case OSSIM_SINT16: { switch (theFilterType) { case OSSIM_MEDIAN: case OSSIM_MEDIAN_FILL_NULLS: applyMedian(ossim_sint16(0), input); break; case OSSIM_MEDIAN_NULL_CENTER_ONLY: applyMedianNullCenterOnly(ossim_sint16(0), input); break; case OSSIM_MEAN: case OSSIM_MEAN_FILL_NULLS: applyMean(ossim_sint16(0), input); break; case OSSIM_MEAN_NULL_CENTER_ONLY: applyMeanNullCenterOnly(ossim_sint16(0), input); break; default: break; } break; } case OSSIM_UINT32: { switch (theFilterType) { case OSSIM_MEDIAN: case OSSIM_MEDIAN_FILL_NULLS: applyMedian(ossim_uint32(0), input); break; case OSSIM_MEDIAN_NULL_CENTER_ONLY: applyMedianNullCenterOnly(ossim_uint32(0), input); break; case OSSIM_MEAN: case OSSIM_MEAN_FILL_NULLS: applyMean(ossim_uint32(0), input); break; case OSSIM_MEAN_NULL_CENTER_ONLY: applyMeanNullCenterOnly(ossim_uint32(0), input); break; default: break; } } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { switch (theFilterType) { case OSSIM_MEDIAN: case OSSIM_MEDIAN_FILL_NULLS: applyMedian(ossim_float32(0.0), input); break; case OSSIM_MEDIAN_NULL_CENTER_ONLY: applyMedianNullCenterOnly(ossim_float32(0.0), input); break; case OSSIM_MEAN: case OSSIM_MEAN_FILL_NULLS: applyMean(ossim_float32(0.0), input); break; case OSSIM_MEAN_NULL_CENTER_ONLY: applyMeanNullCenterOnly(ossim_float32(0.0), input); break; default: break; } break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { switch (theFilterType) { case OSSIM_MEDIAN: case OSSIM_MEDIAN_FILL_NULLS: applyMedian(ossim_float64(0.0), input); break; case OSSIM_MEDIAN_NULL_CENTER_ONLY: applyMedianNullCenterOnly(ossim_float64(0.0), input); break; case OSSIM_MEAN: case OSSIM_MEAN_FILL_NULLS: applyMean(ossim_float64(0.0), input); break; case OSSIM_MEAN_NULL_CENTER_ONLY: applyMeanNullCenterOnly(ossim_float64(0.0), input); break; default: break; } break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimMeanMedianFilter::applyFilter WARNING:\n" << "Unhandled scalar type!" << endl; } } } template void ossimMeanMedianFilter::applyMean(T /* dummyVariable */, ossimRefPtr& inputData) { ossim_uint32 halfWindow = (theWindowSize >> 1); ossim_uint32 bandIdx = 0; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 kernelX = 0; ossim_uint32 kernelY = 0; ossim_uint32 kernelIdx = 0; ossim_uint32 iw = inputData->getWidth(); ossim_uint32 ow = theTile->getWidth(); ossim_uint32 oh = theTile->getHeight(); ossim_uint32 numberOfBands = ossim::min(theTile->getNumberOfBands(), inputData->getNumberOfBands()); ossimDataObjectStatus status = inputData->getDataObjectStatus(); std::vector values(theWindowSize*theWindowSize); if(status == OSSIM_FULL) { for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = (T*)inputData->getBuf(bandIdx); T* outputBuf = (T*)theTile->getBuf(bandIdx); if(inputBuf&&outputBuf) { for(y = 0; y < oh; ++y) { for(x = 0; x < ow; ++x) { kernelIdx = 0; for(kernelY = 0; kernelY < theWindowSize; ++kernelY) { for(kernelX = 0; kernelX < theWindowSize;++kernelX) { values[kernelIdx] = *(inputBuf+kernelX + kernelY*iw); ++kernelIdx; } } if(values.size() > 0) { double sum = std::accumulate(values.begin(), values.end(), 0.0); double average = sum/(double)values.size(); (*outputBuf) = (T)average; } ++inputBuf; ++outputBuf; } inputBuf+=(halfWindow<<1); } } } } else { for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = (T*)inputData->getBuf(bandIdx); T* outputBuf = (T*)theTile->getBuf(bandIdx); T np = (T)inputData->getNullPix(bandIdx); if(inputBuf&&outputBuf) { for(y = 0; y < oh; ++y) { for(x = 0; x < ow; ++x) { values.clear(); for(kernelY = 0; kernelY < theWindowSize; ++kernelY) { for(kernelX = 0; kernelX < theWindowSize;++kernelX) { T tempValue = *(inputBuf+kernelX + kernelY*iw); if(tempValue != np) { values.push_back((double)tempValue); } } } if(values.size() > 0) { double accumulate = std::accumulate(values.begin(), values.end(), 0.0); double average = accumulate/(double)values.size(); if(*(inputBuf+halfWindow + halfWindow*iw) == np) { if(theEnableFillNullFlag) { (*outputBuf) = (T)average; } else { (*outputBuf) = np; } } else { (*outputBuf) = (T)average; } } else { *outputBuf = np; } ++inputBuf; ++outputBuf; } inputBuf+=(halfWindow<<1); } } } } } template void ossimMeanMedianFilter::applyMeanNullCenterOnly( T /* dummyVariable */, ossimRefPtr& inputData) { ossim_uint32 halfWindow = (theWindowSize >> 1); ossim_uint32 bandIdx = 0; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 kernelX = 0; ossim_uint32 kernelY = 0; ossim_uint32 iw = inputData->getWidth(); ossim_uint32 ow = theTile->getWidth(); ossim_uint32 oh = theTile->getHeight(); ossim_uint32 numberOfBands = ossim::min(theTile->getNumberOfBands(), inputData->getNumberOfBands()); ossimDataObjectStatus status = inputData->getDataObjectStatus(); std::vector values; if(status == OSSIM_FULL) { // Nothing to do just copy the tile. theTile->loadTile(inputData.get()); } else { // Partial tile with nulls in it. for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = (T*)inputData->getBuf(bandIdx); T* outputBuf = (T*)theTile->getBuf(bandIdx); if (!inputBuf || !outputBuf) { return; // Shouldn't happen... } const T NP = (T)inputData->getNullPix(bandIdx); for(y = 0; y < oh; ++y) { for(x = 0; x < ow; ++x) { // Get the center input pixel. const T CP = *(inputBuf+halfWindow + halfWindow*iw); if (CP == NP) { values.clear(); for(kernelY = 0; kernelY < theWindowSize; ++kernelY) { for(kernelX = 0; kernelX < theWindowSize;++kernelX) { T tempValue = *(inputBuf+kernelX + kernelY*iw); if(tempValue != NP) { values.push_back((double)tempValue); } } } if(values.size() > 0) { double accumulate = std::accumulate(values.begin(), values.end(), 0.0); double average = accumulate/(double)values.size(); (*outputBuf) = (T)average; } else { (*outputBuf) = NP; } } else // Center pixel (CP) not null. { (*outputBuf) = CP; } // Move over... ++inputBuf; ++outputBuf; } // End of loop in x direction. // Move down... inputBuf+=(halfWindow<<1); } // End of loop in y direction. } // End of band loop. } // End of else "partial tile" block. } template void ossimMeanMedianFilter::applyMedian(T /* dummyVariable */, ossimRefPtr& inputData) { ossim_uint32 halfWindow = (theWindowSize >> 1); ossim_uint32 bandIdx = 0; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 kernelX = 0; ossim_uint32 kernelY = 0; ossim_uint32 kernelIdx = 0; ossim_uint32 iw = inputData->getWidth(); ossim_uint32 ow = theTile->getWidth(); ossim_uint32 oh = theTile->getHeight(); ossim_uint32 numberOfBands = ossim::min(theTile->getNumberOfBands(), inputData->getNumberOfBands()); ossimDataObjectStatus status = inputData->getDataObjectStatus(); std::vector values(theWindowSize*theWindowSize); if(status == OSSIM_FULL) { for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = (T*)inputData->getBuf(bandIdx); T* outputBuf = (T*)theTile->getBuf(bandIdx); if(inputBuf&&outputBuf) { for(y = 0; y < oh; ++y) { for(x = 0; x < ow; ++x) { kernelIdx = 0; for(kernelY = 0; kernelY < theWindowSize; ++kernelY) { for(kernelX = 0; kernelX < theWindowSize;++kernelX) { values[kernelIdx] = *(inputBuf+kernelX + kernelY*iw); ++kernelIdx; } } std::sort(values.begin(), values.end()); if(values.size() > 0) { (*outputBuf) = values[values.size()>>1]; } ++inputBuf; ++outputBuf; } inputBuf+=(halfWindow<<1); } } } } else { for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = (T*)inputData->getBuf(bandIdx); T* outputBuf = (T*)theTile->getBuf(bandIdx); T np = (T)inputData->getNullPix(bandIdx); if(inputBuf&&outputBuf) { for(y = 0; y < oh; ++y) { for(x = 0; x < ow; ++x) { values.clear(); for(kernelY = 0; kernelY < theWindowSize; ++kernelY) { for(kernelX = 0; kernelX < theWindowSize;++kernelX) { T tempValue = *(inputBuf+kernelX + kernelY*iw); if(tempValue != np) { values.push_back(tempValue); } } } std::sort(values.begin(), values.end()); if(values.size() > 0) { if(*(inputBuf+halfWindow + halfWindow*iw) == np) { if(theEnableFillNullFlag) { (*outputBuf) = values[values.size()>>1]; } else { (*outputBuf) = np; } } else { (*outputBuf) = values[values.size()>>1]; } } else { *outputBuf = np; } ++inputBuf; ++outputBuf; } inputBuf+=(halfWindow<<1); } } } } } template void ossimMeanMedianFilter::applyMedianNullCenterOnly ( T /* dummyVariable */, ossimRefPtr& inputData) { ossim_uint32 halfWindow = (theWindowSize >> 1); ossim_uint32 bandIdx = 0; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 kernelX = 0; ossim_uint32 kernelY = 0; ossim_uint32 iw = inputData->getWidth(); ossim_uint32 ow = theTile->getWidth(); ossim_uint32 oh = theTile->getHeight(); ossim_uint32 numberOfBands = ossim::min(theTile->getNumberOfBands(), inputData->getNumberOfBands()); ossimDataObjectStatus status = inputData->getDataObjectStatus(); std::vector values; if(status == OSSIM_FULL) { // Nothing to do just copy the tile. theTile->loadTile(inputData.get()); } else { // Partial tile with nulls in it. for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* inputBuf = (T*)inputData->getBuf(bandIdx); T* outputBuf = (T*)theTile->getBuf(bandIdx); if (!inputBuf || !outputBuf) { return; // Shouldn't happen... } const T NP = (T)inputData->getNullPix(bandIdx); for(y = 0; y < oh; ++y) { for(x = 0; x < ow; ++x) { // Get the center input pixel. const T CP = *(inputBuf+halfWindow + halfWindow*iw); if (CP == NP) { values.clear(); for(kernelY = 0; kernelY < theWindowSize; ++kernelY) { for(kernelX = 0; kernelX < theWindowSize;++kernelX) { T tempValue = *(inputBuf+kernelX + kernelY*iw); if(tempValue != NP) { values.push_back(tempValue); } } } std::sort(values.begin(), values.end()); if(values.size() > 0) { (*outputBuf) = values[values.size()>>1]; } else { (*outputBuf) = NP; } } else // Center pixel (CP) not null. { (*outputBuf) = CP; } // Move over... ++inputBuf; ++outputBuf; } // End of loop in x direction. // Move down... inputBuf+=(halfWindow<<1); } // End of loop in y direction. } // End of band loop. } // End of else "partial tile" block. } void ossimMeanMedianFilter::setProperty(ossimRefPtr property) { if(!property.valid()) { return; } ossimString name = property->getName(); if (name == WINDOW_SIZE_KW) { theWindowSize = property->valueToString().toUInt32(); } else if (name == FILTER_TYPE_KW) { ossimString value = property->valueToString(); setFilterType(value); } else if (name == AUTO_GROW_KW) { ossimString value; property->valueToString(value); setAutoGrowRectFlag(value.toBool()); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimMeanMedianFilter::getProperty(const ossimString& name)const { if (name == WINDOW_SIZE_KW) { ossimProperty* prop = new ossimNumericProperty(WINDOW_SIZE_KW, ossimString::toString(theWindowSize), 3, 25); prop->setCacheRefreshBit(); return prop; } else if (name == FILTER_TYPE_KW) { std::vector constraintList; getFilterTypeList(constraintList); ossimString value = getFilterTypeString(); ossimProperty* prop = new ossimStringProperty(FILTER_TYPE_KW, value, false, constraintList); prop->setCacheRefreshBit(); return prop; } else if (name == AUTO_GROW_KW) { ossimRefPtr p = new ossimBooleanProperty( AUTO_GROW_KW, getAutoGrowRectFlag()); p->setFullRefreshBit(); return p; } return ossimImageSourceFilter::getProperty(name); } void ossimMeanMedianFilter::getPropertyNames( std::vector& propertyNames)const { propertyNames.push_back(WINDOW_SIZE_KW); propertyNames.push_back(FILTER_TYPE_KW); propertyNames.push_back(AUTO_GROW_KW); ossimImageSourceFilter::getPropertyNames(propertyNames); } bool ossimMeanMedianFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, WINDOW_SIZE_KW.c_str(), theWindowSize, true); kwl.add(prefix, FILTER_TYPE_KW.c_str(), getFilterTypeString(), true); kwl.add(prefix, AUTO_GROW_KW.c_str(), (theAutoGrowRectFlag?"true":"false"), true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimMeanMedianFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = NULL; lookup = kwl.find(prefix, WINDOW_SIZE_KW.c_str()); if(lookup) { theWindowSize = ossimString(lookup).toUInt32(); } lookup = kwl.find(prefix, FILTER_TYPE_KW.c_str()); if(lookup) { ossimString type = lookup; setFilterType(type); } lookup = kwl.find(prefix, AUTO_GROW_KW.c_str()); if(lookup) { ossimString flag = lookup; setAutoGrowRectFlag(flag.toBool()); } return ossimImageSourceFilter::loadState(kwl, prefix); } void ossimMeanMedianFilter::setFilterType(ossimMeanMedianFilterType type) { theFilterType = type; } void ossimMeanMedianFilter::setFilterType(const ossimString& type) { ossimString s = type; s.downcase(); std::vector list; getFilterTypeList(list); for (ossim_uint32 i = 0; i < list.size(); ++i) { if (s == list[i]) { theFilterType = static_cast(i); } } if ( (theFilterType == OSSIM_MEDIAN_FILL_NULLS) || (theFilterType == OSSIM_MEAN_FILL_NULLS) ) { theEnableFillNullFlag = true; } else { theEnableFillNullFlag = false; } } void ossimMeanMedianFilter::setAutoGrowRectFlag(bool flag) { theAutoGrowRectFlag = flag; } bool ossimMeanMedianFilter::getAutoGrowRectFlag() const { return theAutoGrowRectFlag; } ossimString ossimMeanMedianFilter::getFilterTypeString() const { std::vector list; getFilterTypeList(list); return list[theFilterType]; } void ossimMeanMedianFilter::getFilterTypeList( std::vector& list) const { list.resize(OSSIM_MEAN_NULL_CENTER_ONLY+1); list[0] = ossimString("median"); list[1] = ossimString("median_fill_nulls"); list[2] = ossimString("median_null_center_only"); list[3] = ossimString("mean"); list[4] = ossimString("mean_fill_nulls"); list[5] = ossimString("mean_null_center_only"); } ossimIrect ossimMeanMedianFilter::getBoundingRect(ossim_uint32 resLevel)const { // Get the input rectangle. ossimIrect rect = ossimImageSourceFilter::getBoundingRect(resLevel); if (!theAutoGrowRectFlag || rect.hasNans()) { return rect; // Not in autogrow mode or no input connection yet... } if ( (theFilterType == OSSIM_MEDIAN_FILL_NULLS) || (theFilterType == OSSIM_MEDIAN_NULL_CENTER_ONLY) || (theFilterType == OSSIM_MEAN_FILL_NULLS) || (theFilterType == OSSIM_MEAN_NULL_CENTER_ONLY) ) { ossimIpt pt = rect.ul(); const ossim_int32 HW = (theWindowSize >> 1); // half window size. // Adjust the upper left. pt.x = pt.x-HW; pt.y = pt.y-HW; rect.set_ul(pt); // Adjust the lower right. pt = rect.lr(); pt.x = pt.x+HW; pt.y = pt.y+HW; rect.set_lr(pt); } return rect; } ossim-Miami-2.9.1/src/imaging/ossimMemoryImageSource.cpp000066400000000000000000000143001352751253100232660ustar00rootroot00000000000000//*******************************************************************. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // #include #include #include RTTI_DEF1(ossimMemoryImageSource, "ossimMemoryImageSource", ossimImageSource); ossimMemoryImageSource::ossimMemoryImageSource() :ossimImageSource(0, 0, 1, true, false) { m_boundingRect.makeNan(); } void ossimMemoryImageSource::setImage(ossimRefPtr image) { m_image = image.get(); if(m_image.valid()) { m_boundingRect = m_image->getImageRectangle(); } else { m_boundingRect.makeNan(); } m_result = 0; } void ossimMemoryImageSource::setImage(ossimScalarType scalarType, ossim_uint32 numberOfBands, ossim_uint32 width, ossim_uint32 height) { m_image = new ossimImageData(0, scalarType, numberOfBands, width, height); m_image->initialize(); m_boundingRect = m_image->getImageRectangle(); m_result = 0; } void ossimMemoryImageSource::setRect(ossim_uint32 ulx, ossim_uint32 uly, ossim_uint32 width, ossim_uint32 height) { if(m_image.valid()) { m_image->setImageRectangle(ossimIrect(ulx, uly, ulx + (width-1), uly + (height-1))); m_boundingRect = m_image->getImageRectangle(); } } ossim_uint32 ossimMemoryImageSource::getNumberOfInputBands() const { if(m_image.valid()) { return m_image->getNumberOfBands(); } return 0;; } ossim_uint32 ossimMemoryImageSource::getNumberOfOutputBands() const { return getNumberOfInputBands(); } ossimScalarType ossimMemoryImageSource::getOutputScalarType() const { if(m_image.valid()) { return m_image->getScalarType(); } return ossimImageSource::getOutputScalarType(); } double ossimMemoryImageSource::getNullPixelValue(ossim_uint32 band)const { if(m_image.valid()) { if(band < getNumberOfInputBands()) { return m_image->getNullPix(band); } } return ossimImageSource::getNullPixelValue(band); } double ossimMemoryImageSource::getMinPixelValue(ossim_uint32 band)const { if(m_image.valid()) { if(band < getNumberOfInputBands()) { return m_image->getMinPix(band); } } return ossimImageSource::getMinPixelValue(band); } double ossimMemoryImageSource::getMaxPixelValue(ossim_uint32 band)const { if(m_image.valid()) { if(band < getNumberOfInputBands()) { return m_image->getMaxPix(band); } } return ossimImageSource::getMaxPixelValue(band); } ossimIrect ossimMemoryImageSource::getBoundingRect(ossim_uint32 resLevel)const { if(resLevel == 0) { if(m_image.valid()) { return m_boundingRect; } } return ossimImageSource::getBoundingRect(resLevel); } ossimRefPtr ossimMemoryImageSource::getTile(const ossimIrect& rect, ossim_uint32 /* resLevel */) { if(!isSourceEnabled()||!m_image.valid()||m_boundingRect.hasNans()) return 0; if(!m_result.valid()) { m_result = new ossimImageData(0, getOutputScalarType(), getNumberOfOutputBands(), rect.width(), rect.height()); m_result->initialize(); } m_result->setImageRectangle(rect); m_result->makeBlank(); ossimIrect clampRect = m_image->getImageRectangle().clipToRect(rect); m_result->loadTile(m_image->getBuf(), m_boundingRect, OSSIM_BSQ); m_result->validate(); return m_result; } bool ossimMemoryImageSource::canConnectMyInputTo(ossim_int32 /* myInputIndex */, const ossimConnectableObject* /* object */)const { return false; } void ossimMemoryImageSource::initialize() { m_result = 0; } ossim_uint32 ossimMemoryImageSource::getNumberOfDecimationLevels() const { return 1; } void ossimMemoryImageSource::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { if (resLevel == 0) { result.x = 1.0; result.y = 1.0; } else { result.x = 1.0 / (1<& decimations)const { decimations.push_back(ossimDpt(1.0,1.0)); } bool ossimMemoryImageSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString imagePrefix = ossimString(prefix) + "image."; ossimString geomPrefix = ossimString(prefix) + "geom."; if(m_image.valid()) { m_image->saveState(kwl, imagePrefix); } if(m_geometry.valid()) { m_geometry->saveState(kwl, geomPrefix); } return ossimImageSource::saveState(kwl, prefix); } bool ossimMemoryImageSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool returnResult = ossimImageSource::loadState(kwl, prefix); m_geometry = 0; if(returnResult) { ossimString imagePrefix = ossimString(prefix) + "image."; ossimString geomPrefix = ossimString(prefix) + "geom."; ossimString type = kwl.find(imagePrefix, "type"); if(!type.empty()) { m_image = new ossimImageData(); returnResult = m_image->loadState(kwl, imagePrefix.c_str()); m_image->initialize(); m_boundingRect = m_image->getImageRectangle(); } if(returnResult) { type = kwl.find(geomPrefix, "type"); if(!type.empty()) { m_geometry = new ossimImageGeometry(); returnResult = m_geometry->loadState(kwl, geomPrefix.c_str()); } } } m_result = 0; return returnResult; } ossim-Miami-2.9.1/src/imaging/ossimMetadataFileWriter.cpp000066400000000000000000000157171352751253100234240ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2003 Stroage Area Networks, Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Kenneth Melero (kmelero@sanz.com) // //******************************************************************* // $Id: ossimMetadataFileWriter.cpp 17195 2010-04-23 17:32:18Z dburken $ #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF3(ossimMetadataFileWriter, "ossimMetadataFileWriter", ossimConnectableObject, ossimProcessInterface, ossimConnectableObjectListener); static ossimTrace traceDebug("ossimMetadataFileWriter:debug"); ossimMetadataFileWriter::ossimMetadataFileWriter() :ossimConnectableObject(0), ossimProcessInterface(), ossimConnectableObjectListener(), theInputConnection(NULL), theFilename(), thePixelType(OSSIM_PIXEL_IS_POINT), theAreaOfInterest() { addListener((ossimConnectableObjectListener*)this); theAreaOfInterest.makeNan(); } ossimMetadataFileWriter::~ossimMetadataFileWriter() { removeListener((ossimConnectableObjectListener*)this); } void ossimMetadataFileWriter::initialize() { theInputConnection = dynamic_cast (getInput(0)); } bool ossimMetadataFileWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimConnectableObject::loadState(kwl, prefix); // Get the filename... const char* lookup = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if(lookup) { ossimString filename = lookup; setFilename(filename); } // Note: Defaulted to point in constructor. lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_TYPE_KW); if (lookup) { ossimString s = lookup; s.downcase(); if (s.contains("area")) { thePixelType = OSSIM_PIXEL_IS_AREA; } else if (s.contains("point")) { thePixelType = OSSIM_PIXEL_IS_POINT; } } if(theInputObjectList.size() != 1) { theInputObjectList.resize(1); theInputListIsFixedFlag = true; } theOutputListIsFixedFlag = false; return result; } void ossimMetadataFileWriter::disconnectInputEvent(ossimConnectionEvent& /* event */) { initialize(); } void ossimMetadataFileWriter::connectInputEvent(ossimConnectionEvent& /* event */) { initialize(); } void ossimMetadataFileWriter::propertyEvent(ossimPropertyEvent& /* event */) { initialize(); } void ossimMetadataFileWriter::setPixelType(ossimPixelType pixelType) { thePixelType = pixelType; } ossimPixelType ossimMetadataFileWriter::getPixelType()const { return thePixelType; } ossimObject* ossimMetadataFileWriter::getObject() { return this; } const ossimObject* ossimMetadataFileWriter::getObject() const { return this; } bool ossimMetadataFileWriter::execute() { bool result = false; if (!theInputConnection) { initialize(); if (!theInputConnection) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimMetadataFileWriter::execute DEBUG:\n" << "theInputConnection is null!" << endl; } return result; } } if(theFilename == ossimFilename::NIL) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimMetadataFileWriter::execute DEBUG:\n" << "theFilename is not set!" << endl; } return result; } //--- // If theAreaOfInterest hasNans then it was probably not set so use // the bounding rectangle of the input source. //--- if (theAreaOfInterest.hasNans()) { theAreaOfInterest = theInputConnection->getBoundingRect(); if (theAreaOfInterest.hasNans()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimMetadataFileWriter::execute DEBUG:\n" << "theAreaOfInterest is not set!" << endl; } return result; } } setProcessStatus(ossimProcessInterface::PROCESS_STATUS_EXECUTING); setPercentComplete(0.0); result = writeFile(); setProcessStatus(ossimProcessInterface::PROCESS_STATUS_NOT_EXECUTING); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimMetadataFileWriter::execute DEBUG:\n" << (result?"successful":"unsuccessful") << " write of file: " << theFilename << endl; } return result; } void ossimMetadataFileWriter::setPercentComplete(double percentComplete) { ossimProcessInterface::setPercentComplete(percentComplete); ossimProcessProgressEvent event(this, percentComplete); fireEvent(event); } void ossimMetadataFileWriter::setFilename(const ossimFilename& file) { theFilename = file; } const ossimFilename& ossimMetadataFileWriter::getFilename() const { return theFilename; } bool ossimMetadataFileWriter::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object) const { return (object && ((PTR_CAST(ossimImageSource, object) && inputIndex == 0)|| (PTR_CAST(ossimViewController, object) && inputIndex == 1))); } void ossimMetadataFileWriter::setAreaOfInterest( const ossimIrect& areaOfInterest) { theAreaOfInterest = areaOfInterest; } ossimIrect ossimMetadataFileWriter::getAreaOfInterest() const { return theAreaOfInterest; } void ossimMetadataFileWriter::setProperty(ossimRefPtr property) { if(!property.valid())return; ossimString name = property->getName(); if(name == ossimKeywordNames::FILENAME_KW) { setFilename(property->valueToString()); } else { ossimConnectableObject::setProperty(property); } } ossimRefPtr ossimMetadataFileWriter::getProperty(const ossimString& name)const { if(name == ossimKeywordNames::FILENAME_KW) { ossimFilenameProperty* filenameProp = new ossimFilenameProperty(name, theFilename); filenameProp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_OUTPUT); return filenameProp; } return ossimConnectableObject::getProperty(name); } void ossimMetadataFileWriter::getPropertyNames(std::vector& propertyNames)const { ossimConnectableObject::getPropertyNames(propertyNames); propertyNames.push_back(ossimKeywordNames::FILENAME_KW); } ossim-Miami-2.9.1/src/imaging/ossimMonoGridRemapEngine.cpp000066400000000000000000000373161352751253100235370ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimMonoGridRemapEngine.cc // // Copyright (C) 2001 ImageLinks, Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // See the GPL in the COPYING.GPL file for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains implementation of class // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimMonoGridRemapEngine.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include RTTI_DEF1(ossimMonoGridRemapEngine, "ossimMonoGridRemapEngine", ossimGridRemapEngine); #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimMonoGridRemapEngine:exec"); static ossimTrace traceDebug ("ossimMonoGridRemapEngine:debug"); static bool TRACE_FLAG = true; using namespace std; //***************************************************************************** // METHOD: ossimMonoGridRemapEngine::dup // //***************************************************************************** ossimObject* ossimMonoGridRemapEngine::dup() const { return new ossimMonoGridRemapEngine; } //***************************************************************************** // METHOD: ossimMonoGridRemapEngine::remapTile // //***************************************************************************** void ossimMonoGridRemapEngine::remapTile(const ossimDpt& origin, ossimGridRemapSource* remapper, ossimRefPtr& tile) { static const char MODULE[] = "ossimMonoGridRemapEngine::remapTile"; if (traceExec()) CLOG << "entering..." << endl; //*** // Fetch tile size and NULL pixel value: //*** int width = tile->getWidth(); int height = tile->getHeight(); int offset = 0; double null; //*** // Determine null pixel values so that we can recognize a null coming in and // not remap it: //*** null = tile->getNullPix(0); ossimDblGrid& grid = *(remapper->getGrid(0)); //*** // Remap according to pixel type: //*** switch(tile->getScalarType()) { case OSSIM_UCHAR: { ossim_uint8* tile_buf = (ossim_uint8*)tile->getBuf(0); short pixel; for (double line=origin.line; line255) tile_buf[offset] = 255; else tile_buf[offset] = pixel; //*** // Avoid NULLS: //*** if (tile_buf[offset] == (ossim_uint8) null) tile_buf[offset]++; } offset++; } } break; } case OSSIM_USHORT11: { ossim_uint16* tile_buf = (ossim_uint16*)tile->getBuf(0); int pixel; for (double line=origin.line; line2047) tile_buf[offset] = 2047; else tile_buf[offset] = pixel; //*** // Avoid NULLS: //*** if (tile_buf[offset] == (ossim_uint16) null) tile_buf[offset]++; } offset++; } } break; } case OSSIM_USHORT12: { ossim_uint16* tile_buf = (ossim_uint16*)tile->getBuf(0); int pixel; for (double line=origin.line; line4095) tile_buf[offset] = 4095; else tile_buf[offset] = pixel; //*** // Avoid NULLS: //*** if (tile_buf[offset] == (ossim_uint16) null) tile_buf[offset]++; } offset++; } } break; } case OSSIM_USHORT13: { ossim_uint16* tile_buf = (ossim_uint16*)tile->getBuf(0); int pixel; for (double line=origin.line; line8191) tile_buf[offset] = 8191; else tile_buf[offset] = pixel; //*** // Avoid NULLS: //*** if (tile_buf[offset] == (ossim_uint16) null) tile_buf[offset]++; } offset++; } } break; } case OSSIM_USHORT14: { ossim_uint16* tile_buf = (ossim_uint16*)tile->getBuf(0); int pixel; for (double line=origin.line; line16383) tile_buf[offset] = 16383; else tile_buf[offset] = pixel; //*** // Avoid NULLS: //*** if (tile_buf[offset] == (ossim_uint16) null) tile_buf[offset]++; } offset++; } } break; } case OSSIM_USHORT15: { ossim_uint16* tile_buf = (ossim_uint16*)tile->getBuf(0); int pixel; for (double line=origin.line; line32767) tile_buf[offset] = 32767; else tile_buf[offset] = pixel; //*** // Avoid NULLS: //*** if (tile_buf[offset] == (ossim_uint16) null) tile_buf[offset]++; } offset++; } } break; } case OSSIM_USHORT16: { ossim_uint16* tile_buf = (ossim_uint16*)tile->getBuf(0); int pixel; for (double line=origin.line; line65535) tile_buf[offset] = 65535; else tile_buf[offset] = pixel; //*** // Avoid NULLS: //*** if (tile_buf[offset] == (ossim_uint16) null) tile_buf[offset]++; } offset++; } } break; } case OSSIM_SSHORT16: { short* tile_buf = (short*)tile->getBuf(0); int pixel; for (double line=origin.line; line 32767) tile_buf[offset] = 32767; else tile_buf[offset] = pixel; //*** // Avoid NULLS: //*** if (tile_buf[offset] == (short) null) tile_buf[offset]++; } offset++; } } break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimMonoGridRemapEngine::remapTile: Scalar type not handled" << std::endl; break; } } // end switch statement if (traceExec()) CLOG << "returning..." << endl; return; }; //***************************************************************************** // METHOD: ossimMonoGridRemapEngine::assignRemapValues // // This engine defines the target value as an MONO vector of doubles, computed // as the mean of all contributor MONO values. // //***************************************************************************** void ossimMonoGridRemapEngine::assignRemapValues ( vector& sources_list) { static const char MODULE[] = "ossimMonoGridRemapEngine::assignRemapValues"; if (traceExec()) CLOG << "entering..." << endl; int i; // index to individual sources //*** // Declare a 2D array that will contain all of the contributing sources' // MONO mean values. Also declare the accumulator target vector. //*** int num_contributors = (int)sources_list.size(); double** contributor_pixel = new double* [num_contributors]; for (i=0; i::iterator source; i = 0; for(source=sources_list.begin(); source!=sources_list.end(); source++) { (*source)->getSourceValue(contributor_pixel[i]); target_pixel += contributor_pixel[i][0]/(double)num_contributors; ++i; } //*** // The target pixel has been established. Now need to compute the actual // remap quantities that will be written to the appropriate remap grids: //*** i = 0; for(source=sources_list.begin(); source!=sources_list.end(); source++) { computeRemapNode(*source, contributor_pixel[i], &target_pixel); ++i; } // *** // Delete locally allocated memory: // *** for (i=0; i& source, void* result) { static const char MODULE[]="ossimMonoGridRemapEngine::computeSourceValue"; if (traceExec()) CLOG << "entering..." << endl; //*** // This engine defines "value" as the MONO vector corresponding to the mean // MONO pixel value of the source data: //*** ((double*)result)[0] = source->computeAverageBandValue(0); if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimMonoGridRemapEngine::computeRemapNode // // This engine defines the remap value as the difference between the target // MONO vector and the individual point source's value vector. // //***************************************************************************** void ossimMonoGridRemapEngine::computeRemapNode(ossimAtbPointSource* ps, void* source_value, void* target_value) { static const char MODULE[] = "ossimMonoGridRemapEngine::computeRemapNode"; if (traceExec()) CLOG << "entering..." << endl; //*** // Compute the remap grid node value specific to this MONO implementation: //*** double node; node = ((double*)target_value)[0] - ((double*)source_value)[0]; //*** // Fetch a pointer to the remapper feeding this point source in order to // pass it the node value: //*** ossimGridRemapSource* remapper = ps->getRemapSource(); remapper->setGridNode(ps->getViewPoint(), &node); if (traceDebug() || TRACE_FLAG) { CLOG << "DEBUG -- " << "\n\t ps->getViewPoint() = "<getViewPoint() << "\n\t source_value = "<<((double*)source_value)[0] << "\n\t target_value = "<<((double*)target_value)[0] << "\n\t node = "< #include #include #include #include #include #include #include #include #include #include static const char* MIN_VALUE_PERCENT_KW = "min_percent"; static const char* MAX_VALUE_PERCENT_KW = "max_percent"; static const char* ALGORITHM_KW = "algorithm"; RTTI_DEF1(ossimMultiBandHistogramTileSource, "ossimMultiBandHistogramTileSource", ossimImageSourceHistogramFilter) ossimMultiBandHistogramTileSource::ossimMultiBandHistogramTileSource() : ossimImageSourceHistogramFilter(), theTile(0), theAlgorithm(OSSIM_HISTOGRAM_LINEAR_STRETCH_ALGORITHM) { disableSource(); } ossimMultiBandHistogramTileSource::ossimMultiBandHistogramTileSource( double /* minValuePercent */, double /* maxValuePercent */, ossimImageSource* inputSource, ossimMultiResLevelHistogram* histogram) : ossimImageSourceHistogramFilter(inputSource, histogram), theTile(0), theAlgorithm(OSSIM_HISTOGRAM_LINEAR_STRETCH_ALGORITHM) { disableSource(); } ossimMultiBandHistogramTileSource::~ossimMultiBandHistogramTileSource() { } ossimRefPtr ossimMultiBandHistogramTileSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) return 0; ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if(!isSourceEnabled() || !inputTile.valid()) { return inputTile; } if(!theTile.valid()) { allocate(); // First time through... } if( !theTile.valid() || !theMinValuePercentArray.size() || !theMaxValuePercentArray.size() ) { return inputTile; } theTile->setImageRectangle(tileRect); if(inputTile->getBuf()&& (inputTile->getDataObjectStatus()!=OSSIM_EMPTY)) { theTile->loadTile(inputTile.get()); switch(inputTile->getScalarType()) { case OSSIM_UCHAR: { return runLinearStretchAlgorithm((ossim_uint8)0, theTile); } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { return runLinearStretchAlgorithm((ossim_uint16)0, theTile); } case OSSIM_SSHORT16: { return runLinearStretchAlgorithm(static_cast(0), theTile); } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { return runLinearStretchAlgorithm(static_cast(0), theTile); } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { return runLinearStretchAlgorithm(static_cast(0), theTile); } case OSSIM_SCALAR_UNKNOWN: default: { ossimSetError("ossimMultiBandHistogramTileSource", ossimErrorCodes::OSSIM_ERROR, "Unknown scalar type"); break; } } theTile->validate(); return theTile; } return inputTile; } void ossimMultiBandHistogramTileSource::initialize() { ossimImageSourceHistogramFilter::initialize(); // Force an allocate on the next getTile. theTile = 0; } void ossimMultiBandHistogramTileSource::allocate() { theTile = ossimImageDataFactory::instance()->create(this, this); if(theTile.valid()) { theTile->initialize(); ossim_uint32 numberOfBands = theTile->getNumberOfBands(); ossim_uint32 i = 0; if(numberOfBands) { std::vector copyArray; if(numberOfBands > theMinValuePercentArray.size()) { copyArray = theMinValuePercentArray; theMinValuePercentArray.resize(numberOfBands); if(numberOfBands < copyArray.size()) { std::copy(copyArray.begin(), copyArray.end(), theMinValuePercentArray.begin()); } else { std::copy(copyArray.begin(), copyArray.begin() + copyArray.size(), theMinValuePercentArray.begin()); } } if(numberOfBands != theMaxValuePercentArray.size()) { copyArray = theMaxValuePercentArray; theMaxValuePercentArray.resize(numberOfBands); if(numberOfBands < copyArray.size()) { std::copy(copyArray.begin(), copyArray.end(), theMaxValuePercentArray.begin()); } else { std::copy(copyArray.begin(), copyArray.begin() + copyArray.size(), theMaxValuePercentArray.begin()); } } if(numberOfBands > theMinValuePercentArray.size()) { for(i = (ossim_uint32)theMinValuePercentArray.size(); i < numberOfBands; ++i) { theMinValuePercentArray[i] = 0.0; theMaxValuePercentArray[i] = 0.0; } } } } } bool ossimMultiBandHistogramTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { theMinValuePercentArray.clear(); theMaxValuePercentArray.clear(); if(ossimImageSourceHistogramFilter::loadState(kwl, prefix)) { ossimNotify(ossimNotifyLevel_INFO) << "ossimMultiBandHistogramTileSource::loadState INFO: histogram filter was loaded" << std::endl; ossimString regExpression = ossimString("^(") + ossimString(prefix) + ossimString(MIN_VALUE_PERCENT_KW) + ossimString("[0-9]+)"); long numberOfSources = kwl.getNumberOfSubstringKeys(regExpression); unsigned long numberOfMatches = 0; ossim_uint32 i = 0; while(numberOfMatches < static_cast(numberOfSources)) { ossimString key = ossimString(MIN_VALUE_PERCENT_KW) + ossimString::toString(i); const char* value = kwl.find(prefix, key); if(value) { theMinValuePercentArray.push_back(ossimString(value).toDouble()); ++numberOfMatches; } ++i; } numberOfMatches = 0; i = 0; regExpression = ossimString("^(") + ossimString(prefix) + ossimString(MAX_VALUE_PERCENT_KW) + ossimString("[0-9]+)"); numberOfSources = kwl.getNumberOfSubstringKeys(regExpression); while(numberOfMatches < static_cast(numberOfSources)) { ossimString key = ossimString(MAX_VALUE_PERCENT_KW) + ossimString::toString(i); const char* value = kwl.find(prefix, key); if(value) { theMaxValuePercentArray.push_back(ossimString(value).toDouble()); ++numberOfMatches; } ++i; } ossimString algorithm = kwl.find(prefix, ALGORITHM_KW); algorithm = algorithm.downcase(); theAlgorithm = OSSIM_HISTOGRAM_LINEAR_STRETCH_ALGORITHM; if(algorithm != "") { if(algorithm.contains("linear")) { theAlgorithm = OSSIM_HISTOGRAM_LINEAR_STRETCH_ALGORITHM; } } } return true; } bool ossimMultiBandHistogramTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimImageSourceHistogramFilter::saveState(kwl, prefix); ossim_int32 i = 0; for(i = 0; i< (ossim_int32)theMinValuePercentArray.size();++i) { kwl.add(prefix, ossimString(MIN_VALUE_PERCENT_KW) + ossimString::toString(i), theMinValuePercentArray[i], true); } for(i = 0; i< (ossim_int32)theMaxValuePercentArray.size();++i) { kwl.add(prefix, ossimString(MAX_VALUE_PERCENT_KW) + ossimString::toString(i), theMaxValuePercentArray[i], true); } ossimString algorithmString; switch(theAlgorithm) { case OSSIM_HISTOGRAM_LINEAR_STRETCH_ALGORITHM: { algorithmString = "linear_stretch"; break; } case OSSIM_HISTOGRAM_NO_ALGORITHM: { algorithmString = "none"; break; } default: { algorithmString = "none"; break; } } kwl.add(prefix, ALGORITHM_KW, algorithmString.c_str(), true); return true; } template ossimRefPtr ossimMultiBandHistogramTileSource::runLinearStretchAlgorithm( T /* dummyVariable */, ossimRefPtr& tile) { if(!getHistogram()) { return tile; } ossimRefPtr histo = getHistogram()->getMultiBandHistogram(theCurrentResLevel); if(histo.valid()) { ossim_uint32 maxBands = ( (histo->getNumberOfBands() > tile->getNumberOfBands())? tile->getNumberOfBands(): histo->getNumberOfBands()); long offsetUpperBound = tile->getHeight()*tile->getWidth(); for(ossim_uint32 band = 0; band < maxBands; ++band) { ossimRefPtr h = histo->getHistogram(band); T* buf = static_cast(tile->getBuf(band)); T np = static_cast(tile->getNullPix(band)); T minPix = static_cast(tile->getMinPix(band)); T maxPix = static_cast(tile->getMaxPix(band)); T range = (maxPix - minPix); if(h.valid()&&buf) { double maxClip = minPix + (h->HighClipVal(theMaxValuePercentArray[band])/(double)h->GetRes())*range; double minClip = minPix + (h->LowClipVal(theMinValuePercentArray[band])/(double)h->GetRes())*range; double delta = (maxClip - minClip); if(fabs(delta) > 0.0) { for(long offset = 0; offset < offsetUpperBound; ++offset) { if(buf[offset] != np) { if(buf[offset] < minClip) { buf[offset] = minPix; } else if(buf[offset] > maxClip) { buf[offset] = maxPix; } else { T value = static_cast(minPix + ((buf[offset] - minClip)/delta)*range); buf[offset] = value>maxPix?maxPix:value; } } } } } } tile->validate(); } return tile; } ossim-Miami-2.9.1/src/imaging/ossimNBandToIndexFilter.cpp000066400000000000000000000360701352751253100233250ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimNBandToIndexFilter.cpp 23325 2015-05-27 13:03:38Z gpotts $ #include #include #include #include #include #include #include static const char* KEEP_QUANTIZED_VALUE_FLAG_KW = "keep_quantized_value_flag"; RTTI_DEF1(ossimNBandToIndexFilter, "ossimNBandToIndexFilter", ossimImageSourceFilter); ossimNBandToIndexFilter::ossimNBandToIndexFilter() :ossimImageSourceFilter(), theLut(0), theTile(0), theKeepQuantizedValueFlag(false) { } ossimNBandToIndexFilter::~ossimNBandToIndexFilter() { } void ossimNBandToIndexFilter::initialize() { ossimImageSourceFilter::initialize(); // Force allocate on next getTile. theTile = 0; if(theLut.valid()) { if(theKeepQuantizedValueFlag) { ossimNBandLutDataObject::LUT_ENTRY_TYPE minValue; ossimNBandLutDataObject::LUT_ENTRY_TYPE maxValue; ossim_uint32 bands = theLut->getNumberOfBands(); ossim_uint32 idx = 0; if(theMinValues.size() != bands) { theMinValues.resize(bands); theMaxValues.resize(bands); theNullValues.resize(bands); } std::fill(theNullValues.begin(), theNullValues.end(), 0); for(idx = 0; idx < bands; ++idx) { theLut->getMinMax(idx, minValue, maxValue); theMinValues[idx] = minValue; theMaxValues[idx] = maxValue; theNullValues[idx] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(ossimImageSourceFilter::getNullPixelValue(idx)); } } else { if(theMinValues.size() != 1) { theMinValues.resize(1); theMaxValues.resize(1); theNullValues.resize(1); } theMinValues[0] = 0; theMaxValues[0] = theLut->getNumberOfEntries()-1; theNullValues[0] = theLut->getNullPixelIndex(); } } } void ossimNBandToIndexFilter::allocate() { theTile = 0; if(isSourceEnabled()&&theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, this); if(theTile.valid()) { theTile->initialize(); } } } void ossimNBandToIndexFilter::disableSource() { ossimImageSourceFilter::disableSource(); theTile = 0; } ossimRefPtr ossimNBandToIndexFilter::getTile(const ossimIrect& origin, ossim_uint32 resLevel) { if(!isSourceEnabled()) { return ossimImageSourceFilter::getTile(origin, resLevel); } if(!theInputConnection) { return ossimRefPtr(); } if(!theTile.valid()) { allocate(); } ossimRefPtr input = theInputConnection->getTile(origin, resLevel); if(!theTile.valid() || !input.valid()) { return input; } theTile->setImageRectangle(origin); theTile->setDataObjectStatus(OSSIM_FULL); theTile->makeBlank(); return convertInputTile(input.get()); } ossimRefPtr ossimNBandToIndexFilter::convertInputTile(ossimImageData* tile) { switch(getOutputScalarType()) { case OSSIM_UINT8: { return convertOutputTileTemplate((ossim_uint8)0, tile); break; } case OSSIM_UINT16: { return convertOutputTileTemplate((ossim_uint16)0, tile); break; } case OSSIM_UINT32: { return convertOutputTileTemplate((ossim_uint32)0, tile); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimNBandToIndexFilter::convertInputTile: Unsupported scalar type for conversion" << std::endl; } } return theTile; } template ossimRefPtr ossimNBandToIndexFilter::convertOutputTileTemplate(T outputDummy, ossimImageData* inputTile) { switch(inputTile->getScalarType()) { case OSSIM_UINT8: { return convertInputTileToOutputTemplate((ossim_uint8)0, outputDummy, inputTile); break; } case OSSIM_SINT8: { return convertInputTileToOutputTemplate((ossim_sint8)0, outputDummy, inputTile); } case OSSIM_UINT16: { return convertInputTileToOutputTemplate((ossim_uint16)0, outputDummy, inputTile); } case OSSIM_SINT32: { return convertInputTileToOutputTemplate((ossim_sint32)0, outputDummy, inputTile); } case OSSIM_UINT32: { return convertInputTileToOutputTemplate((ossim_uint32)0, outputDummy, inputTile); } default: { ossimNotify(ossimNotifyLevel_WARN) << "convertInputTileToOutputTemplate::convertOutputTileTemplate: Unsupported scalar type for conversion." << std::endl; } } return theTile; } template ossimRefPtr ossimNBandToIndexFilter::convertInputTileToOutputTemplate( T1 /* inputDummy */, T2 /* outputDummy */, ossimImageData* inputTile) { if (!inputTile) { return theTile; } const ossim_uint32 BANDS = inputTile->getNumberOfBands(); if (!BANDS) { return theTile; } // T2** outBand = (T2*)theTile->getBuf(); ossim_uint32 numberOfBands = theLut->getNumberOfBands(); std::vector bandValuesTemplate(numberOfBands); ossimNBandLutDataObject::LUT_ENTRY_TYPE* bandValues = &bandValuesTemplate.front();//new ossimNBandLutDataObject::LUT_ENTRY_TYPE[numberOfBands]; std::fill(bandValuesTemplate.begin(), bandValuesTemplate.end(), 0); numberOfBands = ossim::min(BANDS, numberOfBands); if(!numberOfBands) return theTile; std::vector band(numberOfBands); std::vector outBand(numberOfBands); // T1** band = new T1*[numberOfBands]; //T2** outBand = new T2*[numberOfBands]; ossim_int32 idx = 0; for(idx = 0; idx < (ossim_int32)numberOfBands; ++idx) { band[idx] = (T1*)inputTile->getBuf(idx); outBand[idx] = (T2*)theTile->getBuf(idx); } if(band[0]) { if(inputTile->getDataObjectStatus() == OSSIM_FULL) { ossim_uint32 upper = inputTile->getWidth()*inputTile->getHeight(); ossim_uint32 idx2=0; for(ossim_uint32 offset = 0; offset < upper; ++offset) { for(idx2 = 0; idx2 < numberOfBands; ++idx2) { bandValues[idx2] = *band[idx2]; ++band[idx2]; } //--- // Note call the ossimNBandLutDataObject::findIndex that takes a size as the input // data may have dropped the alpha channel. //--- idx = theLut->findIndex(bandValues, numberOfBands); if(!theKeepQuantizedValueFlag) { *outBand[0] = (T2)idx; ++outBand[0]; } else { for(idx2 = 0; idx2 < numberOfBands; ++idx2) { if(idx >=0) { *outBand[idx2] = (T2)(*theLut)[idx][idx2]; ++outBand[idx2]; } } } } } else if(inputTile->getDataObjectStatus() == OSSIM_PARTIAL) { ossim_uint32 upper = inputTile->getWidth()*inputTile->getHeight(); ossim_uint32 idx2=0; for(ossim_uint32 offset = 0; offset < upper; ++offset) { for(idx2 = 0; idx2 < numberOfBands; ++idx2) { bandValues[idx2] = *band[idx2]; ++band[idx2]; } idx = -1; if(!inputTile->isNull(offset)) { //--- // Note call the ossimNBandLutDataObject::findIndex that takes a size as the input // data may have dropped the alpha channel. //--- idx = theLut->findIndex(bandValues, numberOfBands); } if(!theKeepQuantizedValueFlag) { if(idx>=0) { *outBand[0] = (T2)idx; } ++outBand[0]; } else { for(idx2 = 0; idx2 < numberOfBands; ++idx2) { if(idx >=0) { if(idx>=0) { *outBand[idx2] = (T2)(*theLut)[idx][idx2]; } } ++outBand[idx2]; } } } } } if(theKeepQuantizedValueFlag) { theTile->validate(); } else { theTile->setDataObjectStatus(OSSIM_FULL); } return theTile; } bool ossimNBandToIndexFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString newPrefix = prefix; newPrefix = newPrefix + "lut."; if(theLut.valid()) { theLut->saveState(kwl, newPrefix.c_str()); } kwl.add(prefix, KEEP_QUANTIZED_VALUE_FLAG_KW, theKeepQuantizedValueFlag?"true":"false", true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimNBandToIndexFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString newPrefix = prefix; newPrefix = newPrefix + "lut."; if(!theLut.valid()) { theLut = new ossimNBandLutDataObject; } theLut->loadState(kwl, newPrefix.c_str()); const char* flag = kwl.find(prefix, KEEP_QUANTIZED_VALUE_FLAG_KW); if(flag) { theKeepQuantizedValueFlag = ossimString(flag).toBool(); } return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimNBandToIndexFilter::isSourceEnabled()const { bool result = ossimSource::isSourceEnabled()&&theInputConnection; // only support 3 band integral values, no floating point for now. // if(result) { ossimScalarType inputScalarType = theInputConnection->getOutputScalarType(); if(!theLut.valid() || (theLut->getNumberOfEntries()<1)|| (inputScalarType==OSSIM_FLOAT32)|| (inputScalarType==OSSIM_FLOAT64)|| (theInputConnection->getNumberOfOutputBands()!=3)) { result = false; } } return result; } ossim_uint32 ossimNBandToIndexFilter::getNumberOfOutputBands() const { if(isSourceEnabled()) { if(theKeepQuantizedValueFlag) { if(theLut.valid()) { return theLut->getNumberOfBands(); } } else { return 1; } } return ossimImageSourceFilter::getNumberOfOutputBands(); } ossimScalarType ossimNBandToIndexFilter::getOutputScalarType() const { if(isSourceEnabled()) { ossim_uint32 numberOfEntries = theLut->getNumberOfEntries(); if(numberOfEntries < 257) { return OSSIM_UCHAR; } else if(numberOfEntries < 65537) { return OSSIM_UINT16; } else { return OSSIM_UINT32; } } return ossimImageSourceFilter::getOutputScalarType(); } void ossimNBandToIndexFilter::setLut(ossimNBandLutDataObject& lut) { theLut = new ossimNBandLutDataObject(lut); } double ossimNBandToIndexFilter::getNullPixelValue(ossim_uint32 band)const { if(isSourceEnabled()) { if(theLut->getNullPixelIndex() >= 0) { return theLut->getNullPixelIndex(); } } return ossimImageSourceFilter::getNullPixelValue(band); } double ossimNBandToIndexFilter::getMinPixelValue(ossim_uint32 band)const { if(isSourceEnabled()) { if(band < theMinValues.size()) { return (double)theMinValues[band]; } } // if(isSourceEnabled()) // { // if(getNullPixelValue() != 0) // { // return 0; // } // else // { // return 1; // } // return 0; // } return ossimImageSourceFilter::getMinPixelValue(); } double ossimNBandToIndexFilter::getMaxPixelValue(ossim_uint32 band)const { if(isSourceEnabled()) { if(band < theMaxValues.size()) { return (double)theMaxValues[band]; } // if(theLut->getNullPixelIndex() != ((ossim_int32)(theLut->getNumberOfEntries())-1)) // { // return theLut->getNumberOfEntries(); // } // else // { // return (theLut->getNumberOfEntries()-1); // } } return ossimImageSourceFilter::getMaxPixelValue(); } void ossimNBandToIndexFilter::setProperty(ossimRefPtr property) { if(property->getName() == ossimKeywordNames::FILENAME_KW) { ossimKeywordlist kwl; if(kwl.addFile(ossimFilename(property->valueToString()))) { theLut = new ossimNBandLutDataObject; theLut->loadState(kwl); } } else if(property->getName() == KEEP_QUANTIZED_VALUE_FLAG_KW) { theKeepQuantizedValueFlag = property->valueToString().toBool(); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimNBandToIndexFilter::getProperty(const ossimString& name)const { if(name == ossimKeywordNames::FILENAME_KW) { ossimFilenameProperty* property = new ossimFilenameProperty(name, theLutFilename); property->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); property->setCacheRefreshBit(); return property; } else if(name == KEEP_QUANTIZED_VALUE_FLAG_KW) { ossimBooleanProperty* property = new ossimBooleanProperty(name, theKeepQuantizedValueFlag); property->setCacheRefreshBit(); return property; } return ossimImageSourceFilter::getProperty(name); } void ossimNBandToIndexFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back(ossimKeywordNames::FILENAME_KW); propertyNames.push_back(KEEP_QUANTIZED_VALUE_FLAG_KW); } ossim-Miami-2.9.1/src/imaging/ossimNitf20Writer.cpp000066400000000000000000000677201352751253100221470ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimNitf20Writer.cpp 2982 2011-10-10 21:28:55Z david.burken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // #include // #include // #include // #include // #include // #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitf20Writer, "ossimNitf20Writer", ossimNitfWriterBase); static ossimTrace traceDebug(ossimString("ossimNitfWriter:debug")); static ossimString monthConversionTable[] = {" ", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}; ossimNitf20Writer::ossimNitf20Writer(const ossimFilename& filename, ossimImageSource* inputSource) : ossimNitfWriterBase(filename, inputSource), theOutputStream(0), theFileHeader(), theImageHeader(), theEnableRpcbTagFlag(false), theEnableBlockaTagFlag(true), theCopyFieldsFlag(false) { //--- // Since the internal nitf tags are not very accurate, write an external // geometry out as default behavior. Users can disable this via the // property interface or keyword list. //--- setWriteExternalGeometryFlag(true); theFileHeader = new ossimNitfFileHeaderV2_0; theImageHeader = new ossimNitfImageHeaderV2_0; theOutputImageType = "nitf20_block_band_separate"; // These are always set: theFileHeader->setEncryption( ossimString("0") ); theImageHeader->setJustification( ossimString("R") ); // Set any site defaults. initializeDefaultsFromConfigFile( dynamic_cast(theFileHeader.get()), dynamic_cast(theImageHeader.get()) ); } ossimNitf20Writer::~ossimNitf20Writer() { //--- // This looks like a leak but it's not as both of these are ossimRefPtr's. //--- theFileHeader=0; theImageHeader=0; close(); } bool ossimNitf20Writer::isOpen()const { return (theOutputStream != 0); } bool ossimNitf20Writer::open() { if(isOpen()) { close(); } theOutputStream = new std::ofstream; theOutputStream->open(theFilename.c_str(), ios::out|ios::binary); return theOutputStream->good(); } void ossimNitf20Writer::close() { if(theOutputStream) { theOutputStream->close(); delete theOutputStream; theOutputStream = (std::ofstream*)0; } } bool ossimNitf20Writer::writeFile() { if(!theInputConnection->isMaster()) { theInputConnection->slaveProcessTiles(); return true; } open(); if (!isOpen()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitf20Writer::writeFile ERROR:" << " Could not open! Returning..." << std::endl; } return false; } // Write out the geometry info. writeGeometry(theImageHeader.get(), theInputConnection.get()); addTags(); bool result = false; if((theOutputImageType == "nitf20_block_band_separate")|| (theOutputImageType == "image/nitf20")) { result = writeBlockBandSeparate(); } else if(theOutputImageType == "nitf20_block_band_sequential") { result = writeBlockBandSequential(); } close(); return result; } void ossimNitf20Writer::getImageTypeList(std::vector& imageTypeList)const { imageTypeList.push_back(ossimString("nitf20_block_band_separate")); imageTypeList.push_back(ossimString("nitf20_block_band_sequential")); } void ossimNitf20Writer::setProperty(ossimRefPtr property) { if(!property) return; ossimString name = property->getName(); if(name == "file_header") { ossimContainerProperty* containerProperty = PTR_CAST(ossimContainerProperty, property.get()); if(containerProperty) { std::vector > propertyList; containerProperty->getPropertyList(propertyList); theFileHeader->setProperties(propertyList); } } else if(name == "image_header") { ossimContainerProperty* containerProperty = PTR_CAST(ossimContainerProperty, property.get()); if(containerProperty) { std::vector > propertyList; containerProperty->getPropertyList(propertyList); theImageHeader->setProperties(propertyList); } } else if (name == "enable_rpcb_tag") { theEnableRpcbTagFlag = property->valueToString().toBool(); } else if (name == "enable_blocka_tag") { theEnableBlockaTagFlag = property->valueToString().toBool(); } else if(name == "copy_fields_flag") { theCopyFieldsFlag = property->valueToString().toBool(); } else { // just in case it was an nitf specific tag we can pass it safely like this theFileHeader->setProperty(property); theImageHeader->setProperty(property); ossimImageFileWriter::setProperty(property); } } ossimRefPtr ossimNitf20Writer::getProperty(const ossimString& name)const { ossimRefPtr result = 0; if(name == "file_header") { ossimContainerProperty* container = new ossimContainerProperty(name); std::vector > propertyList; theFileHeader->getPropertyList(propertyList); container->addChildren(propertyList); result = container; } else if(name == "image_header") { ossimContainerProperty* container = new ossimContainerProperty(name); std::vector > propertyList; theImageHeader->getPropertyList(propertyList); container->addChildren(propertyList); result = container; } else if(name == "enable_rpcb_tag") { ossimBooleanProperty* boolProperty = new ossimBooleanProperty(name, theEnableRpcbTagFlag); result = boolProperty; } else if(name == "enable_blocka_tag") { ossimBooleanProperty* boolProperty = new ossimBooleanProperty(name, theEnableBlockaTagFlag); result = boolProperty; } else if(name == "copy_fields_flag") { ossimBooleanProperty* boolProperty = new ossimBooleanProperty(name, theCopyFieldsFlag); result = boolProperty; } else { return ossimImageFileWriter::getProperty(name); } return result; } void ossimNitf20Writer::getPropertyNames(std::vector& propertyNames)const { ossimImageFileWriter::getPropertyNames(propertyNames); propertyNames.push_back("file_header"); propertyNames.push_back("image_header"); propertyNames.push_back("enable_rpcb_tag"); propertyNames.push_back("enable_blocka_tag"); propertyNames.push_back("copy_fields_flag"); } bool ossimNitf20Writer::writeBlockBandSeparate() { ossimScalarType scalarType = theInputConnection->getOutputScalarType(); ossim_uint64 byteSize = ossim::scalarSizeInBytes(scalarType); ossimIrect rect = theInputConnection->getBoundingRect(); ossim_uint64 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint64 idx = 0; ossim_uint64 headerStart = (ossim_uint64)theOutputStream->tellp(); ossimIpt blockSize(64, 64); ossim_uint64 blocksHorizontal = (ossim_uint32)ceil(((double)rect.width()/(double)blockSize.x)); ossim_uint64 blocksVertical = (ossim_uint32)ceil(((double)rect.height()/(double)blockSize.y)); ossimNitfImageInfoRecordV2_0 imageInfoRecord; //imageInfoRecord.setSubheaderLength(439); // ok if no tags imageInfoRecord.setImageLength(bands*byteSize*blocksVertical*blockSize.y*blocksHorizontal*blockSize.x); theFileHeader->addImageInfoRecord(imageInfoRecord); //--- // This makes space for the file header; it is written again at the end of // this method with updated values // need a better way to get the length. This should be queried on the // header before writing //--- theFileHeader->writeStream(*theOutputStream); ossim_uint64 headerLength = ((ossim_uint64)theOutputStream->tellp() - headerStart) /* + 1 */; ossimString representation; theImageHeader->setActualBitsPerPixel( ossim::getActualBitsPerPixel(scalarType)); theImageHeader->setBitsPerPixel(ossim::getBitsPerPixel(scalarType)); theImageHeader->setPixelType(ossimNitfCommon::getNitfPixelType(scalarType)); theImageHeader->setNumberOfBands(bands); theImageHeader->setImageMode('B');// blocked if((bands == 3)&& (scalarType == OSSIM_UCHAR)) { theImageHeader->setRepresentation("RGB"); theImageHeader->setCategory("VIS"); } else if(bands == 1) { theImageHeader->setRepresentation("MONO"); theImageHeader->setCategory("MS"); } else { theImageHeader->setRepresentation("MULTI"); theImageHeader->setCategory("MS"); } theImageHeader->setBlocksPerRow(blocksHorizontal); theImageHeader->setBlocksPerCol(blocksVertical); theImageHeader->setNumberOfPixelsPerBlockRow(blockSize.x); theImageHeader->setNumberOfPixelsPerBlockCol(blockSize.y); theImageHeader->setNumberOfRows(rect.height()); theImageHeader->setNumberOfCols(rect.width()); ossimNitfImageBandV2_0 bandInfo; for(idx = 0; idx < bands; ++idx) { std::ostringstream out; out << std::setfill('0') << std::setw(2) << idx; bandInfo.setBandRepresentation(out.str().c_str()); theImageHeader->setBandInfo(idx, bandInfo); } ossim_uint64 imageHeaderStart = theOutputStream->tellp(); theImageHeader->writeStream(*theOutputStream); ossim_uint64 imageHeaderEnd = theOutputStream->tellp(); ossim_uint64 imageHeaderSize = imageHeaderEnd - imageHeaderStart; theInputConnection->setTileSize(blockSize); ossim_uint64 numberOfTiles = theInputConnection->getNumberOfTiles(); theInputConnection->setToStartOfSequence(); ossimRefPtr data = theInputConnection->getNextTile(); ossim_uint64 tileNumber = 1; ossimEndian endian; while( data.valid() && !needsAborting()) { if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { switch(data->getScalarType()) { case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { endian.swap((ossim_uint16*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_SSHORT16: { endian.swap((ossim_sint16*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { endian.swap((ossim_float32*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { endian.swap((ossim_float64*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } default: break; } } theOutputStream->write((char*)(data->getBuf()), data->getSizeInBytes()); setPercentComplete(((double)tileNumber / (double)numberOfTiles) * 100); if(!needsAborting()) { data = theInputConnection->getNextTile(); } ++tileNumber; } std::streamoff pos = theOutputStream->tellp(); setComplexityLevel(pos, theFileHeader.get()); /* * Need to change the way I compute file length and header length later * We need to figure out a better way to compute. */ theFileHeader->setFileLength(static_cast(pos)); theFileHeader->setHeaderLength(headerLength); theOutputStream->seekp(0, ios::beg); imageInfoRecord.setSubheaderLength(imageHeaderSize); theFileHeader->replaceImageInfoRecord(0, imageInfoRecord); theFileHeader->writeStream(*theOutputStream); return true; } bool ossimNitf20Writer::writeBlockBandSequential() { ossimScalarType scalarType = theInputConnection->getOutputScalarType(); ossim_uint64 byteSize = ossim::scalarSizeInBytes(scalarType); ossimIrect rect = theInputConnection->getBoundingRect(); ossim_uint64 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint64 idx = 0; ossim_uint64 headerStart = (ossim_uint64)theOutputStream->tellp(); ossimIpt blockSize(64, 64); ossim_uint64 blocksHorizontal = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint64 blocksVertical = theInputConnection->getNumberOfTilesVertical(); theInputConnection->setTileSize(blockSize); ossim_uint64 numberOfTiles = theInputConnection->getNumberOfTiles(); theInputConnection->setToStartOfSequence(); ossimNitfImageInfoRecordV2_0 imageInfoRecord; // imageInfoRecord.setSubheaderLength(439); imageInfoRecord.setImageLength(bands*byteSize*blocksHorizontal*blocksVertical*blockSize.x*blockSize.y); ossimDate currentDate; theFileHeader->setDate(currentDate); theFileHeader->addImageInfoRecord(imageInfoRecord); //--- // This makes space for the file header; it is written again at the end of // this method with updated values // need a better way to get the length. This should be queried on the // header before writing //--- theFileHeader->writeStream(*theOutputStream); ossim_uint64 headerLength = ((ossim_uint64)theOutputStream->tellp() - headerStart) /* + 1 */; ossimString representation; theImageHeader->setActualBitsPerPixel( ossim::getActualBitsPerPixel(scalarType)); theImageHeader->setBitsPerPixel(ossim::getBitsPerPixel(scalarType)); theImageHeader->setPixelType(ossimNitfCommon::getNitfPixelType(scalarType)); theImageHeader->setNumberOfBands(bands); theImageHeader->setImageMode('S');// blocked if((bands == 3)&& (scalarType == OSSIM_UCHAR)) { theImageHeader->setRepresentation("RGB"); theImageHeader->setCategory("VIS"); } else if(bands == 1) { theImageHeader->setRepresentation("MONO"); theImageHeader->setCategory("MS"); } else { theImageHeader->setRepresentation("MULTI"); theImageHeader->setCategory("MS"); } theImageHeader->setBlocksPerRow(blocksHorizontal); theImageHeader->setBlocksPerCol(blocksVertical); theImageHeader->setNumberOfPixelsPerBlockRow(blockSize.x); theImageHeader->setNumberOfPixelsPerBlockCol(blockSize.y); theImageHeader->setNumberOfRows(rect.height()); theImageHeader->setNumberOfCols(rect.width()); ossimNitfImageBandV2_0 bandInfo; for(idx = 0; idx < bands; ++idx) { std::ostringstream out; out << std::setfill('0') << std::setw(2) << idx; bandInfo.setBandRepresentation(out.str().c_str()); theImageHeader->setBandInfo(idx, bandInfo); } int imageHeaderStart = theOutputStream->tellp(); theImageHeader->writeStream(*theOutputStream); int imageHeaderEnd = theOutputStream->tellp(); int imageHeaderSize = imageHeaderEnd - imageHeaderStart; // ossimIpt ul = rect.ul(); ossimRefPtr data = theInputConnection->getNextTile(); ossim_uint64 tileNumber = 0; ossimEndian endian; // get the start to the first band of data block // ossim_uint64 streamOffset = theOutputStream->tellp(); // holds the total pixels to the next band ossim_uint64 blockSizeInBytes = blockSize.x*blockSize.y*ossim::scalarSizeInBytes(data->getScalarType()); ossim_uint64 bandOffsetInBytes = (blockSizeInBytes*blocksHorizontal*blocksVertical); bool needSwapping = endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN; while(data.valid() && !needsAborting()) { if(needSwapping) { switch(data->getScalarType()) { case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { endian.swap((ossim_uint16*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_SSHORT16: { endian.swap((ossim_sint16*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { endian.swap((ossim_float32*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { endian.swap((ossim_float64*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } default: break; } } for(idx = 0; idx < bands; ++idx) { theOutputStream->seekp(streamOffset+ // start of image stream tileNumber*blockSizeInBytes + // start of block for band separate output bandOffsetInBytes*idx, // which band offset is it ios::beg); theOutputStream->write((char*)(data->getBuf(idx)), blockSizeInBytes); } ++tileNumber; setPercentComplete(((double)tileNumber / (double)numberOfTiles) * 100); if(!needsAborting()) { data = theInputConnection->getNextTile(); } } std::streamoff pos = theOutputStream->tellp(); setComplexityLevel(pos, theFileHeader.get()); /* * Need to change the way I compute file length and header length later * We need to figure out a better way to compute. */ theFileHeader->setFileLength(static_cast(pos)); theFileHeader->setHeaderLength(headerLength); theOutputStream->seekp(0, ios::beg); imageInfoRecord.setSubheaderLength(imageHeaderSize); theFileHeader->replaceImageInfoRecord(0, imageInfoRecord); theFileHeader->writeStream(*theOutputStream); return true; } void ossimNitf20Writer::addRegisteredTag( ossimRefPtr registeredTag) { ossimNitfTagInformation tagInfo; tagInfo.setTagData(registeredTag.get()); theImageHeader->addTag(tagInfo); } void ossimNitf20Writer::addTags() { ossimDate currentDate; theFileHeader->setDate(currentDate); if(theCopyFieldsFlag) { ossimTypeNameVisitor visitor(ossimString("ossimNitfTileSource"), true, (ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS)); accept(visitor); // If there are multiple image handlers, e.g. a mosaic do not uses. ossimRefPtr nitf = 0; if ( visitor.getObjects().size() == 1 ) { nitf = visitor.getObjectAs( 0 ); } if( nitf.valid() ) { ossimString value; ossimPropertyInterface* fileHeaderProperties = dynamic_cast(theFileHeader.get()); ossimPropertyInterface* imageHeaderProperties = dynamic_cast(theImageHeader.get()); bool nitf21Flag = false; const ossimNitfFileHeader* header = nitf->getFileHeader(); const ossimNitfImageHeader* imageHeader = nitf->getCurrentImageHeader(); if(header) { ossimString version = header->getPropertyValueAsString("fhdr"); nitf21Flag = version.contains("2.1"); value = header->getPropertyValueAsString("stype"); if(value.size()) { fileHeaderProperties->setProperty("stype", value); } value = header->getPropertyValueAsString("ostaid"); if(value.size()) { fileHeaderProperties->setProperty("ostaid", value); } value = header->getPropertyValueAsString("ftitle"); if(value.size()) { fileHeaderProperties->setProperty("ftitle", value); } value = header->getPropertyValueAsString("fsclas"); if(value.size()) { fileHeaderProperties->setProperty("fsclas", value); } value = header->getPropertyValueAsString("oname"); if(value.size()) { fileHeaderProperties->setProperty("oname", value); } value = header->getPropertyValueAsString("ophone"); if(value.size()) { fileHeaderProperties->setProperty("ophone", value); } int idx = 0; for(idx = 0; idx < header->getNumberOfTags(); ++idx) { ossimNitfTagInformation info; header->getTagInformation(info, idx); theFileHeader->addTag(info); } value = header->getPropertyValueAsString(""); if(value.size()) { fileHeaderProperties->setProperty("", value); } value = header->getPropertyValueAsString("fdt"); if(value.size()==14) { if(nitf21Flag) { ossimString year(value.begin()+2, value.begin()+4); ossimString mon(value.begin()+4, value.begin()+6); ossimString day(value.begin()+6, value.begin()+8); ossimString hour(value.begin()+8, value.begin()+10); ossimString min(value.begin()+10, value.begin()+12); ossimString sec(value.begin()+12, value.begin()+14); if(mon.toUInt32() < 13) { mon = monthConversionTable[mon.toUInt32()]; } fileHeaderProperties->setProperty("fdt", day+hour+min+sec+"Z"+mon+year); } else { fileHeaderProperties->setProperty("fdt", value); } } } if(imageHeader) { ossim_uint32 idx = 0; for(idx = 0; idx < imageHeader->getNumberOfTags(); ++idx) { ossimNitfTagInformation info; imageHeader->getTagInformation(info, idx); theImageHeader->addTag(info); } value = imageHeader->getPropertyValueAsString("tgtid"); if(value.size()) { imageHeaderProperties->setProperty("tgtid", value); } value = imageHeader->getPropertyValueAsString("isclas"); if(value.size()) { imageHeaderProperties->setProperty("isclas", value); } value = imageHeader->getPropertyValueAsString("igeolo"); if(value.size()) { imageHeaderProperties->setProperty("igeolo", value); } value = imageHeader->getPropertyValueAsString("ititle"); if(nitf21Flag) { value = imageHeader->getPropertyValueAsString("iid2"); } if(value.size()) { imageHeaderProperties->setProperty("ititle", value); } if(!nitf21Flag) { value = imageHeader->getPropertyValueAsString("iscaut"); if(value.size()) { imageHeaderProperties->setProperty("iscaut", value); } value = imageHeader->getPropertyValueAsString("iscode"); if(value.size()) { imageHeaderProperties->setProperty("iscode", value); } value = imageHeader->getPropertyValueAsString("isctlh"); if(value.size()) { imageHeaderProperties->setProperty("isctlh", value); } value = imageHeader->getPropertyValueAsString("isrel"); if(value.size()) { imageHeaderProperties->setProperty("isrel", value); } value = imageHeader->getPropertyValueAsString("isctln"); if(value.size()) { imageHeaderProperties->setProperty("isctln", value); } value = imageHeader->getPropertyValueAsString("isdwng"); if(value.size()) { imageHeaderProperties->setProperty("isdevt", value); } value = imageHeader->getPropertyValueAsString("isorce"); if(value.size()) { imageHeaderProperties->setProperty("isorce", value); } } value = imageHeader->getPropertyValueAsString("idatim"); if(value.size()==14) { if(nitf21Flag) { ossimString year(value.begin()+2, value.begin()+4); ossimString mon(value.begin()+4, value.begin()+6); ossimString day(value.begin()+6, value.begin()+8); ossimString hour(value.begin()+8, value.begin()+10); ossimString min(value.begin()+10, value.begin()+12); ossimString sec(value.begin()+12, value.begin()+14); if(mon.toUInt32() < 13) { mon = monthConversionTable[mon.toUInt32()]; } imageHeaderProperties->setProperty("idatim", day+hour+min+sec+"Z"+mon+year); } else { imageHeaderProperties->setProperty("idatim", value); } } } // we will port over only a selected few } } } bool ossimNitf20Writer::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimNitfWriterBase::saveState(kwl, prefix); } bool ossimNitf20Writer::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimNitfWriterBase::loadState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimNitfCodecFactory.cpp000066400000000000000000000026671352751253100230750ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Description: Factory class declaration for codec(encoder/decoder). // //---------------------------------------------------------------------------- // $Id$ #include #include ossimNitfCodecFactory* ossimNitfCodecFactory::m_instance=0; std::mutex ossimNitfCodecFactory::m_mutex; ossimNitfCodecFactory::ossimNitfCodecFactory() { m_instance = this; } ossimNitfCodecFactory::~ossimNitfCodecFactory() { std::lock_guard lock(m_mutex); m_instance = 0; } ossimNitfCodecFactory* ossimNitfCodecFactory::instance() { std::lock_guard lock(m_mutex); if(!m_instance) { m_instance = new ossimNitfCodecFactory(); } return m_instance; } ossimCodecBase* ossimNitfCodecFactory::createCodec(ossimRefPtr imageHeader) { ossimCodecBase* result=0; if(imageHeader.valid()&&imageHeader->isCompressed()) { ossimKeywordlist kwl; imageHeader->saveState(kwl); // rename the type to be a NITF IC compression type // J2K should be C8 // kwl.add("type", imageHeader->getCompressionCode().c_str(), true); result = ossimCodecFactoryRegistry::instance()->createCodec(kwl); } return result; } ossim-Miami-2.9.1/src/imaging/ossimNitfTileSource.cpp000066400000000000000000003120711352751253100225770ustar00rootroot00000000000000//--- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Contains class definition for ossimNitfTileSource. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* free, malloc, size_t (jpeglib.h) */ #include /* FILE* (jpeglib.h) */ #include /** for jmp_buf (jpeglib.h) */ #include #include #include #include /* for std::fill */ using namespace std; RTTI_DEF1_INST(ossimNitfTileSource, "ossimNitfTileSource", ossimImageHandler) #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimNitfTileSource.cpp 22925 2014-10-28 22:01:09Z dburken $"; #endif //--- // NOTE: This should match the enumerations for ReadMode. //--- static const char* READ_MODE[] = { "READ_MODE_UNKNOWN", "READ_BIB_BLOCK", "READ_BIP_BLOCK", "READ_BIR_BLOCK", "READ_BSQ_BLOCK", "READ_BIB", "READ_BIP", "READ_BIR", "READ_JPEG_BLOCK" }; //*** // Static trace for debugging //*** static ossimTrace traceDebug("ossimNitfTileSource:debug"); // 64x64*12bits // divide by 8 bits to get bytes gives you 6144 bytes static const ossim_uint32 OSSIM_NITF_VQ_BLOCKSIZE = 6144; /** @brief Extended error handler struct for jpeg code. */ struct ossimJpegErrorMgr { struct jpeg_error_mgr pub; /* "public" fields */ jmp_buf setjmp_buffer; /* for return to caller */ }; ossimNitfTileSource::ossimNitfTileSource() : ossimImageHandler(), theTile(0), theCacheTile(0), theNitfFile(0), theNitfImageHeader(0), theReadMode(READ_MODE_UNKNOWN), theScalarType(OSSIM_SCALAR_UNKNOWN), theSwapBytesFlag(false), theNumberOfInputBands(0), theNumberOfOutputBands(0), theBlockSizeInBytes(0), theReadBlockSizeInBytes(0), theNumberOfImages(0), theCurrentEntry(0), theImageRect(0,0,0,0), theFileStr(0), theOutputBandList(), theCacheSize(0, 0), theCacheTileInterLeaveType(OSSIM_INTERLEAVE_UNKNOWN), theCacheEnabledFlag(false), theEntryList(0), theCacheId(-1), thePackedBitsFlag(false), theCompressedBuf(0), theNitfBlockOffset(0), theNitfBlockSize(0), m_jpegOffsetsDirty(false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::ossimNitfTileSource entered..." << endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG)<< "OSSIM_ID: " << OSSIM_ID << endl; #endif } } ossimNitfTileSource::~ossimNitfTileSource() { destroy(); } void ossimNitfTileSource::destroy() { if (theCacheId != -1) { ossimAppFixedTileCache::instance()->deleteCache(theCacheId); theCacheId = -1; } // Delete the list of image headers. theNitfImageHeader.clear(); theNitfFile = 0; shared_ptr str = std::dynamic_pointer_cast( theFileStr ); if ( str ) { if(str->is_open()) { str->close(); } } theCacheTile = 0; theTile = 0; theOverview = 0; } bool ossimNitfTileSource::isOpen()const { return (theNitfImageHeader.size() > 0); } bool ossimNitfTileSource::open() { bool result = false; if(isOpen()) { close(); } theErrorStatus = ossimErrorCodes::OSSIM_OK; std::shared_ptr nitfStream= ossim::StreamFactoryRegistry::instance()->createIstream(getFilename().c_str()); result = open(nitfStream, getFilename().c_str()); // if ( parseFile() ) // { // result = allocate(); // } // if (result) // { // completeOpen(); // } return result; } bool ossimNitfTileSource::open( std::shared_ptr& str, const std::string& connectionString ) { static const char MODULE[] = "ossimNitfTileSource::open( stream, ...)"; bool result = false; if(!str) return result; ossimFilename file = connectionString; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\nFile = " << file << "\n"; } if( isOpen() ) { close(); } theErrorStatus = ossimErrorCodes::OSSIM_OK; theNitfFile = new ossimNitfFile(); result = theNitfFile->parseStream( file, *str); if ( result ) { // Get the number of images within the file. theNumberOfImages = theNitfFile->getHeader()->getNumberOfImages(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nNumber of images " << theNumberOfImages << "\n"; } theEntryList.clear(); //--- // Get image header pointers. Note there can be multiple images in one // image file. //--- for (ossim_uint32 i = 0; i < theNumberOfImages; ++i) { ossimRefPtr hdr = theNitfFile->getNewImageHeader(*str, i); if (!hdr) { result = false; setErrorStatus(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:\nNull image header!" << endl; } break; } if (traceDebug()) { if(hdr.valid()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "DEBUG:" << "\nImage header[" << i << "]:\n" << *(hdr.get()) << "\n"; } } if(hdr->isValid()) { if( !hdr->isCompressed() ) { // GP: I will remove the NODISPLY check for if there is // any kind of data OSSIM should allow it through. // filterting for this data should be at a higher level. // SICD data is labeled as NODISPLY but we need to process // it in order for it to be used in other algorithms // Skip entries tagged NODISPLAY, e.g. cloud mask entries. // if (hdr->getRepresentation() != "NODISPLY") // { theEntryList.push_back(i); theNitfImageHeader.push_back(hdr); // } // else // { // ossimString cat = hdr->getCategory().trim().downcase(); // // this is an NGA Highr Resoluion Digital Terrain Model NITF format // if(cat == "dtem") // { // theEntryList.push_back(i); // theNitfImageHeader.push_back(hdr); // } // } } else if ( canUncompress(hdr.get()) ) { theEntryList.push_back(i); theCacheEnabledFlag = true; theNitfImageHeader.push_back(hdr); } else { //std::cout << "COMPRESSION CODE: "<< hdr->getCompressionCode() << "\n"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Entry " << i <<" has an unsupported compression code = " << hdr->getCompressionCode() << std::endl; } theNitfImageHeader.clear(); theEntryList.clear(); // break out break; } } } // End: image header loop // Reset the number of images in case we skipped some, e.g. tagged "NODISPLAY" if ( theNitfImageHeader.size() ) { theNumberOfImages = (ossim_uint32)theNitfImageHeader.size(); } else { result = false; } if ( result ) { // Save the stream and connection/file name. theFileStr = str; theImageFile = file; // Initialize the lut to the current entry if the current entry has a lut. initializeLut(); result = allocate(); if (result) { completeOpen(); } } else { setErrorStatus(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "DEBUG:\nNo images in file!" << endl; } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status: " << (result?"true":"false") << "\n"; } return result; } void ossimNitfTileSource::close() { destroy(); } bool ossimNitfTileSource::parseFile() { static const char MODULE[] = "ossimNitfTileSource::parseFile"; ossimFilename file = getFilename(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG: Nitf file = " << file << endl; } if (file.empty()) { setErrorStatus(); return false; } if ( !theNitfFile ) // A close deletes "theNitfFile". { theNitfFile = new ossimNitfFile(); } if ( !theNitfFile->parseFile(file) ) { setErrorStatus(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "DEBUG:" << "\nError parsing file!" << endl; } return false; } // Get the number of images within the file. theNumberOfImages = theNitfFile->getHeader()->getNumberOfImages(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "DEBUG:\nNumber of images " < hdr = theNitfFile->getNewImageHeader(i); if (!hdr) { setErrorStatus(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:\nNull image header!" << endl; } return false; } if (traceDebug()) { if(hdr.valid()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "DEBUG:" << "\nImage header[" << i << "]:\n" << *hdr << endl; } } if(hdr->isValid()) { if( !hdr->isCompressed() ) { // GP: I will remove the NODISPLYU check for if there is // any kind of data OSSIM should allow it through. // filterting for this data should be at a higher level. // SICD data is labeled as NODISPLY but we need to process // it in order for it to be used in other algorithms // // Skip entries tagged NODISPLAY, e.g. cloud mask entries. // if (hdr->getRepresentation() != "NODISPLY") // { theEntryList.push_back(i); theNitfImageHeader.push_back(hdr); // } // else // { // ossimString cat = hdr->getCategory().trim().downcase(); // // this is an NGA Highr Resoluion Digital Terrain Model NITF format // if(cat == "dtem") // { // theEntryList.push_back(i); // theNitfImageHeader.push_back(hdr); // } // } } else if ( canUncompress(hdr.get()) ) { theEntryList.push_back(i); theCacheEnabledFlag = true; theNitfImageHeader.push_back(hdr); } else { theEntryList.clear(); theNitfImageHeader.clear(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Entry " << i <<" has an unsupported compression code = " << hdr->getCompressionCode() << std::endl; } break; } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Entry " << i <<" has an invalid image header\n"; } } } if(theEntryList.size()<1) { return false; } //### WHY IS THIS HERE? THIS CAUSED A BUG BECAUSE theCurrentEntry was previously initialized //### in loadState() according to a KWL. Any entry index in the KWL was being ignored. //if(theEntryList.size()>0) //{ // theCurrentEntry = theEntryList[0]; //} theNumberOfImages = (ossim_uint32)theNitfImageHeader.size(); if (theNitfImageHeader.size() != theNumberOfImages) { setErrorStatus(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "DEBUG:\nNumber of header not equal number of images!" << endl; } return false; } // Check the current entry range. if ( theCurrentEntry >= theNumberOfImages ) { if(theEntryList.size()) { theCurrentEntry = theEntryList[0]; } } // Initialize the lut to the current entry if the current entry has a lut. initializeLut(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCurrent entry: " << theCurrentEntry << endl; } // Open up a stream to the file. theFileStr = ossim::StreamFactoryRegistry::instance()->createIstream( file, ios::in | ios::binary); if (!theFileStr) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:" << "\nCannot open: " << file.c_str() << endl; } return false; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " leaving with true..." << endl; } return true; } bool ossimNitfTileSource::allocate() { // Clear out the cache if there was any. if (theCacheId != -1) { ossimAppFixedTileCache::instance()->deleteCache(theCacheId); theCacheId = -1; } // Clear buffers: theTile = 0; theCacheTile = 0; theCompressedBuf.clear(); // Set the scalar type. initializeScalarType(); if (theScalarType == OSSIM_SCALAR_UNKNOWN) { return false; } // Set the swap bytes flag. initializeSwapBytesFlag(); // Set the read mode. initializeReadMode(); if (theReadMode == READ_MODE_UNKNOWN) { return false; } // Set the number of bands. initializeBandCount(); if (theNumberOfInputBands == 0) { return false; } // Initialize the image rectangle. before the cache size is done if (initializeImageRect() == false) { return false; } // Initialize the cache size. Must be done before // setting the blocksize. Since bit encoded data may very // and we need to know if the nitf file needs to be accessed // like a general raster. // initializeCacheSize(); if ( (theCacheSize.x == 0) || (theCacheSize.y == 0) ) { return false; } // Initialize the block size. if (initializeBlockSize() == false) { return false; } // Initialize the cache tile interleave type. initializeCacheTileInterLeaveType(); if (theCacheTileInterLeaveType == OSSIM_INTERLEAVE_UNKNOWN) { return false; } return true; } bool ossimNitfTileSource::allocateBuffers() { //--- // Initialize the cache tile. This will be used for a block buffer even // if the cache is disabled. //--- initializeCacheTile(); if (!theCacheTile.valid()) { return false; } // Initialize the cache if enabled. if (theCacheEnabledFlag) { theCacheId = ossimAppFixedTileCache::instance()-> newTileCache(theBlockImageRect, theCacheSize); } //--- // Initialize the compressed buffer if needed. //--- initializeCompressedBuf(); //--- // Make the output tile. //--- initializeOutputTile(); return true; } bool ossimNitfTileSource::canUncompress(const ossimNitfImageHeader* hdr) const { bool result = false; if (hdr) { ossimString code = hdr->getCompressionCode(); if (code == "C3") // jpeg { if (hdr->getBitsPerPixelPerBand() == 8) { result = true; } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Entry with jpeg compression (C3) has an unsupported " << "JPEG data precision: " << hdr->getBitsPerPixelPerBand() << std::endl; } } } else if(isVqCompressed( code ) && (hdr->getCompressionHeader().valid()) ) { // we will only support single band vq compressed NITFS // basically CIB and CADRG products are single band code words. // if(hdr->getNumberOfBands() == 1) { result = true; } } } return result; } void ossimNitfTileSource::initializeReadMode() { // Initialize the read mode. theReadMode = READ_MODE_UNKNOWN; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return; } ossim_uint32 numberOfBlocks = getNumberOfBlocks(); ossimString imode = hdr->getIMode(); ossimString compressionCode = hdr->getCompressionCode(); if ( (compressionCode == "C3") && ((imode == "B")||(imode == "P")) ) { theReadMode = READ_JPEG_BLOCK; } else if (numberOfBlocks > 1) { if (imode == "B") { theReadMode = READ_BIB_BLOCK; } else if (imode == "P") { theReadMode = READ_BIP_BLOCK; } else if (imode == "R") { theReadMode = READ_BIR_BLOCK; } else if (imode == "S") { theReadMode = READ_BSQ_BLOCK; } } else // The entire image comprises one block. { if (imode == "B") { theReadMode = READ_BIB; } else if (imode == "P") { theReadMode = READ_BIP; } else if (imode == "R") { theReadMode = READ_BIR; } else if (imode == "S") { theReadMode = READ_BSQ_BLOCK; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::initializeReadMode DEBUG:" << "\nnumberOfBlocks: " << numberOfBlocks << "\nIMODE: " << imode << "\nRead Mode: " << READ_MODE[theReadMode] << endl; } } void ossimNitfTileSource::initializeScalarType() { thePackedBitsFlag = false; // Initialize the read mode. theScalarType = OSSIM_SCALAR_UNKNOWN; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return; } ossim_int32 bitsPerPixel = hdr->getActualBitsPerPixelPerBand(); if (bitsPerPixel < 1) { bitsPerPixel = hdr->getBitsPerPixelPerBand(); } ossimString pixelValueType = hdr->getPixelValueType().upcase(); switch (bitsPerPixel) { case 8: { theScalarType = OSSIM_UINT8; break; } case 11: { if(pixelValueType == "SI") { theScalarType = OSSIM_SINT16; } else { theScalarType = OSSIM_USHORT11; } break; } case 12: { if(pixelValueType == "SI") { theScalarType = OSSIM_SINT16; } else { theScalarType = OSSIM_USHORT12; } break; } case 13: { if(pixelValueType == "SI") { theScalarType = OSSIM_SINT16; } else { theScalarType = OSSIM_USHORT13; } break; } case 14: { if(pixelValueType == "SI") { theScalarType = OSSIM_SINT16; } else { theScalarType = OSSIM_USHORT14; } break; } case 15: { if(pixelValueType == "SI") { theScalarType = OSSIM_SINT16; } else { theScalarType = OSSIM_USHORT15; } break; } case 9: case 10: case 16: { if(pixelValueType == "SI") { theScalarType = OSSIM_SINT16; } else { theScalarType = OSSIM_UINT16; } break; } case 32: { if(pixelValueType == "SI") { theScalarType = OSSIM_SINT32; } else if(pixelValueType == "R") { theScalarType = OSSIM_FLOAT32; } break; } case 64: { if(pixelValueType == "R") { theScalarType = OSSIM_FLOAT64; } break; } default: { if(hdr->isCompressed()) { thePackedBitsFlag = true; if(bitsPerPixel < 8) { theScalarType = OSSIM_UINT8; } else if(bitsPerPixel < 16) { theScalarType = OSSIM_UINT16; } else if(bitsPerPixel < 32) { theScalarType = OSSIM_FLOAT32; } } else { if(bitsPerPixel<8) { theScalarType = OSSIM_UINT8; } } break; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::initializeScalarType DEBUG:" << "\nScalar type: " << (ossimScalarTypeLut::instance()->getEntryString(theScalarType)) << "\nPacked bits: " << (thePackedBitsFlag?"true":"false") << endl; } } void ossimNitfTileSource::initializeSwapBytesFlag() { if ( (theScalarType != OSSIM_UINT8) && (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) ) { theSwapBytesFlag = true; } else { theSwapBytesFlag = false; } } void ossimNitfTileSource::initializeBandCount() { // Initialize the read mode. theNumberOfInputBands = 0; theNumberOfOutputBands = 0; //theOutputBandList.clear(); const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return; } if(!isVqCompressed(hdr->getCompressionCode())) { theNumberOfInputBands = hdr->getNumberOfBands(); theNumberOfOutputBands = hdr->getNumberOfBands(); if(hdr->getRepresentation().contains("LUT")&&(theNumberOfInputBands == 1)) { theNumberOfOutputBands = 3; } } else { ossimRefPtr bandInfo = hdr->getBandInformation(0); if ( bandInfo.valid() ) { theNumberOfInputBands = 1; theNumberOfOutputBands = bandInfo->getNumberOfLuts(); } } //for (ossim_uint32 i=0; i < theNumberOfOutputBands; ++i) // Need to take bands from loadState to pass to Kakadu to avoid decompressing all bands if (theOutputBandList.size() > 0) theNumberOfOutputBands = theOutputBandList.size(); else { theOutputBandList.resize(theNumberOfOutputBands); for (ossim_uint32 i=0; i < theNumberOfOutputBands; ++i) { theOutputBandList[i] = i; // One to one for initial setup. } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::initializeBandCount DEBUG:" << "\nInput Band count: " << theNumberOfInputBands << "\nOutput Band count: " << theNumberOfOutputBands << endl; } } bool ossimNitfTileSource::initializeBlockSize() { theBlockSizeInBytes = 0; theReadBlockSizeInBytes = 0; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return false; } ossim_uint32 bytesRowCol = 0; ossim_uint32 bytesRowColCacheTile = 0; if(isVqCompressed(hdr->getCompressionCode())) { bytesRowCol = OSSIM_NITF_VQ_BLOCKSIZE; } else { //--- // Busting int32 limit on single block data. // Need a new read method to handle this. (drb - 09 May 2016) //--- ossim_uint64 x = hdr->getNumberOfPixelsPerBlockHoriz(); ossim_uint64 y = hdr->getNumberOfPixelsPerBlockVert(); ossim_uint64 bpp = hdr->getBitsPerPixelPerBand(); ossim_uint64 bytes = x * y * bpp / 8; if ( bytes > 2147483647 ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfTileSource::initializeBlockSize WARNING!" << "\nBusting 2 GIG block size: " << bytes << std::endl; } return false; } bytesRowCol = (ossim_uint32)bytes; } if ( !bytesRowColCacheTile ) { //--- // Busting int32 limit on single block data. // Need a new read method to handle this. (drb - 09 May 2016) //--- ossim_uint64 x = theCacheSize.x; ossim_uint64 y = theCacheSize.y; ossim_uint64 bpp = hdr->getBitsPerPixelPerBand(); ossim_uint64 bytes = x * y * bpp / 8; if ( bytes > 2147483647 ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfTileSource::initializeBlockSize WARNING!" << "\nBusting 2 GIG cache bytes: " << bytes << std::endl; } return false; } bytesRowColCacheTile = bytes; } #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:" // << "\ncompressionHeader: " << compressionHeader << "\ngetNumberOfPixelsPerBlockHoriz(): " << hdr->getNumberOfPixelsPerBlockHoriz() << "\ngetNumberOfPixelsPerBlockVert(): " << hdr->getNumberOfPixelsPerBlockVert() << "\ngetBitsPerPixelPerBand(): " << hdr->getBitsPerPixelPerBand() << "\nbytesRowCol: " << bytesRowCol << "\nbytesRowColCacheTile: " << bytesRowColCacheTile << endl; } #endif theBlockSizeInBytes = bytesRowCol; theReadBlockSizeInBytes = theBlockSizeInBytes; switch (theReadMode) { case READ_BSQ_BLOCK: case READ_BIB_BLOCK: { break; } case READ_BIB: { theReadBlockSizeInBytes = bytesRowColCacheTile; break; } case READ_BIP_BLOCK: case READ_BIR_BLOCK: { theBlockSizeInBytes *= theNumberOfInputBands; theReadBlockSizeInBytes *= theNumberOfInputBands; break; } case READ_BIP: case READ_BIR: { theBlockSizeInBytes *= theNumberOfInputBands; theReadBlockSizeInBytes = bytesRowColCacheTile*theNumberOfInputBands; break; } case READ_JPEG_BLOCK: { theBlockSizeInBytes *= theNumberOfInputBands; ossimString code = hdr->getCompressionCode(); if (code == "C3") // jpeg { m_jpegOffsetsDirty = true; } break; } default: { return false; } } #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::initializeBlockSize DEBUG:" << "\nNumber of input bands: " << theNumberOfInputBands << "\nNumber of output bands: " << theNumberOfOutputBands << "\nBlock size in bytes: " << theBlockSizeInBytes << "\nRead block size in bytes: " << theReadBlockSizeInBytes << endl; } #endif return true; } //************************************************************************************************* // Virtual method determines the decimation factors at each resolution level. // This implementation derives the R0 decimation from the image metadata if available, then hands // off the computation of remaining R-levels to the base class implementation. //************************************************************************************************* void ossimNitfTileSource::establishDecimationFactors() { theDecimationFactors.clear(); const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (hdr) { double decimation; hdr->getDecimationFactor(decimation); if ((decimation != 0.0) && !ossim::isnan(decimation)) { //--- // Note: Commented out as other code is picking up the resolution and then we're applying // a decimation on top of that. (drb Aug. 2011) // ossimDpt dec_2d (decimation, decimation); //--- ossimDpt dec_2d (1.0, 1.0); theDecimationFactors.push_back(dec_2d); } } // Just needed to set the first R level here, the base class can do the rest: ossimImageHandler::establishDecimationFactors(); } #if 0 ossimImageGeometry* ossimNitfTileSource::getImageGeometry() { //--- // Call base class getImageGeometry which will check for external geometry // or an already set geometry. //--- ossimImageGeometry* result = ossimImageHandler::getImageGeometry(); if (result) { if ( !result->getTransform() ) { ossimRefPtr transform = 0; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (hdr) { //--- // Test for the ichipb tag and set the sub image if needed. // // NOTE # 1: // // There are nitf writers that set the ichipb offsets and only have // IGEOLO field present. For these it has been determined // (but still in question) that we should not apply the sub image // offset. // // See trac # 1578 // http://trac.osgeo.org/ossim/ticket/1578 // // NOTE # 2: // // Let the ICHIPB have precedence over the STDIDC tag as we could // have a chip of a segment. //--- ossimRefPtr tag = hdr->getTagData(ossimString("ICHIPB")); if (tag.valid()) { ossimNitfIchipbTag* ichipb = PTR_CAST(ossimNitfIchipbTag, tag.get()); if (ichipb) { // const ossimRefPtr blocka = // hdr->getTagData(ossimString("BLOCKA")); // const ossimRefPtr rpc00a = // hdr->getTagData(ossimString("RPC00A")); // const ossimRefPtr rpc00b = // hdr->getTagData(ossimString("RPC00B")); //--- // If any of these tags are present we will use the sub // image from the ichipb tag. //--- // if ( blocka.get() || rpc00a.get() || rpc00b.get() ) // ************************* THERE ARE PROBLEMS NOT SETTING THIS AT SITE. GO AHEAD AND ALWAYS INIT THE SHIFT { transform = ichipb->newTransform(); } } } if ( !transform) { //--- // Look for the STDIDC tag for a sub image (segment) offset. // // See: STDI-002 Table 7.3 for documentation. //--- tag = hdr->getTagData(ossimString("STDIDC")); if (tag.valid() && (hdr->getIMode() == "B") ) { ossimDpt shift; ossimNitfStdidcTag* stdidc = PTR_CAST(ossimNitfStdidcTag, tag.get()); if (stdidc) { ossim_int32 startCol = stdidc->getStartColumn().toInt32(); ossim_int32 startRow = stdidc->getStartRow().toInt32(); if ( (startCol > 0) && (startRow > 0) ) { // field are one based; hence, the - 1. shift.x = (startCol-1) * hdr->getNumberOfPixelsPerBlockHoriz(); shift.y = (startRow-1) * hdr->getNumberOfPixelsPerBlockVert(); } if(shift.x > 0 || shift.y > 0) { transform = new ossim2dTo2dShiftTransform(shift); } } } } } // matches: if (hdr) if ( transform.valid() ) { result->setTransform( transform.get() ); } //else //{ // ossimImageGeometryRegistry::instance()->createTransform(this); //} } // matches: if ( !result->getTransform() ) if ( !result->getProjection() ) { ossimRefPtr proj = ossimProjectionFactoryRegistry::instance()-> createProjection(this); if ( proj.valid() ) { result->setProjection( proj.get() ); } //else //{ // ossimImageGeometryRegistry::instance()->createProjection(this); //} } } // matches: if (result) if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::createImageGeometry DEBUG:\n"; if (result) { result->print(ossimNotify(ossimNotifyLevel_DEBUG)) << "\n"; } } return result; } #endif bool ossimNitfTileSource::initializeImageRect() { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { theImageRect.makeNan(); return false; } theBlockImageRect = hdr->getBlockImageRect(); theImageRect = hdr->getImageRect(); if (traceDebug()) { ossimIpt iloc; hdr->getImageLocation(iloc); // for temp debug (drb) ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::initializeImageRect DEBUG:" << "\noffset from ILOC field: " << iloc << "\nImage Rect: " << theImageRect << "\nBlock rect: " << theBlockImageRect << endl; } return true; } void ossimNitfTileSource::initializeCacheSize() { theCacheSize.x = 0; theCacheSize.y = 0; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return; } switch (theReadMode) { case READ_BIB_BLOCK: case READ_BIP_BLOCK: case READ_BIR_BLOCK: case READ_BSQ_BLOCK: case READ_JPEG_BLOCK: theCacheSize.x = hdr->getNumberOfPixelsPerBlockHoriz(); theCacheSize.y = hdr->getNumberOfPixelsPerBlockVert(); break; case READ_BIB: case READ_BIP: case READ_BIR: theCacheSize.x = hdr->getNumberOfPixelsPerBlockHoriz(); theCacheSize.y = hdr->getNumberOfPixelsPerBlockVert(); if(getNumberOfBlocks() == 1) { // is it larger than 4kx4k then we will for now error out so // we can't continue if((theCacheSize.x*theCacheSize.y) > 16777216) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "We currently do not support single blocks with block sizes larger than 4kx4k"; ossimNotify(ossimNotifyLevel_WARN) << "Current size is: " << theCacheSize << std::endl; } theCacheSize.x = 0; theCacheSize.y = 0; } } // theCacheSize.x = getNumberOfSamples(0); // theCacheSize.y = getTileHeight(); // if(theCacheSize.y > hdr->getNumberOfPixelsPerBlockVert()) // { // theCacheSize.y = hdr->getNumberOfPixelsPerBlockVert(); // } break; default: break; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::initializeCacheSize DEBUG:" << "\nCache size: " << theCacheSize << endl; } } void ossimNitfTileSource::initializeCacheTileInterLeaveType() { theCacheTileInterLeaveType = OSSIM_INTERLEAVE_UNKNOWN; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return; } switch (theReadMode) { case READ_BIB_BLOCK: case READ_BSQ_BLOCK: case READ_BIB: case READ_JPEG_BLOCK: theCacheTileInterLeaveType = OSSIM_BSQ; break; case READ_BIP_BLOCK: case READ_BIP: theCacheTileInterLeaveType = OSSIM_BIP; break; case READ_BIR_BLOCK: case READ_BIR: theCacheTileInterLeaveType = OSSIM_BIL; break; default: break; } if (traceDebug()) { ossimInterleaveTypeLut lut; ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::initializeCacheTileInterLeaveType DEBUG:" << "\nCache tile interleave type: " << lut.getEntryString(theCacheTileInterLeaveType) << endl; } } void ossimNitfTileSource::initializeCacheTile() { theCacheTile = ossimImageDataFactory::instance()->create( this, theScalarType, theNumberOfOutputBands, theCacheSize.x, theCacheSize.y); theCacheTile->initialize(); } void ossimNitfTileSource::initializeCompressedBuf() { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return; } if( (hdr->getRepresentation().upcase().contains("LUT")) || ( isVqCompressed(hdr->getCompressionCode()) ) ) { theCompressedBuf.resize(theReadBlockSizeInBytes); std::fill(theCompressedBuf.begin(), theCompressedBuf.end(), '\0'); } } void ossimNitfTileSource::initializeOutputTile() { //--- // Make the output tile. This implementation will use default tile size. ossimImageDataFactory* idf = ossimImageDataFactory::instance(); theTile = idf->create(this, this); theTile->initialize(); } void ossimNitfTileSource::initializeLut() { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (hdr) { if ( hdr->hasLut() ) { //--- // NOTE: Only band 0 ??? (drb) //--- theLut = theNitfImageHeader[theCurrentEntry]->createLut(0); } } } ossimRefPtr ossimNitfTileSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { // This tile source bypassed, or invalid res level, return a blank tile. if(!isSourceEnabled() || !isOpen() || !isValidRLevel(resLevel)) { return ossimRefPtr(); } if ( !theTile.valid() ) { // First call to getTile: allocateBuffers(); if ( !theTile.valid() ) { return theTile; } } // Rectangle must be set prior to getOverviewTile call. theTile->setImageRectangle(tileRect); if (resLevel) { if ( getOverviewTile(resLevel, theTile.get() ) ) { return theTile; } } ossim_uint32 level = resLevel; if (theStartingResLevel) // Used as overview. { if (theStartingResLevel <= resLevel) { //--- // Adjust the level to be relative to the reader using this as // overview. //--- level -= theStartingResLevel; } } //--- // See if the whole tile is going to be filled, if not, start out with // a blank tile so data from a previous load gets wiped out. //--- if ( !tileRect.completely_within(theImageRect) ) { // Start with a blank tile. theTile->makeBlank(); } //--- // See if any point of the requested tile is in the image. //--- if ( tileRect.intersects(theBlockImageRect) ) { ossimIrect clipRect = tileRect.clipToRect(theImageRect); // See if the requested clip rect is already in the cache tile. if ( (clipRect.completely_within(theCacheTile->getImageRectangle()))&& (theCacheTile->getDataObjectStatus() != OSSIM_EMPTY)&& (theCacheTile->getBuf())) { //--- // Note: Clip the cache tile(nitf block) to the image clipRect since // there are nitf blocks that go beyond the image dimensions, i.e., // edge blocks. //--- ossimIrect cr = theCacheTile->getImageRectangle().clipToRect(clipRect); theTile->loadTile(theCacheTile->getBuf(), theCacheTile->getImageRectangle(), cr, theCacheTileInterLeaveType); //--- // Validate the tile. This will set the status to full, partial // or empty. Must be performed if any type of combining is to be // performed down the chain. //--- theTile->validate(); } else { if ( loadTile(clipRect) == true ) { //--- // Validate the tile. This will set the status to full, partial // or empty. Must be performed if any type of combining is to be // performed down the chain. //--- theTile->validate(); } else { //--- // Commented setting error status out for jpeg data that had several bad // blocks but the rest of the image was good. If the error status is // set the overview builder stops! (drb) 10 May 2013 // Flag an error for callers: // setErrorStatus(); ossimNotify(ossimNotifyLevel_WARN) << __FILE__ << " " << __LINE__ << " loadTile failed!" << std::endl; theTile->makeBlank(); // loadTile failed... } } } // End of if ( tileRect.intersects(image_rect) ) return theTile; } bool ossimNitfTileSource::loadTile(const ossimIrect& clipRect) { ossimIrect zbClipRect = clipRect; const ossim_uint32 BLOCK_HEIGHT = theCacheSize.y; const ossim_uint32 BLOCK_WIDTH = theCacheSize.x; zbClipRect.stretchToTileBoundary(ossimIpt(BLOCK_WIDTH, BLOCK_HEIGHT)); //--- // Shift the upper left corner of the "clip_rect" to the an even nitf // block boundry. //--- ossimIpt nitfBlockOrigin = zbClipRect.ul(); // Vertical block loop. ossim_int32 y = nitfBlockOrigin.y; while (y < zbClipRect.lr().y) { // Horizontal block loop. ossim_int32 x = nitfBlockOrigin.x; while (x < zbClipRect.lr().x) { if ( loadBlockFromCache(x, y, clipRect) == false ) { if ( loadBlock(x, y) ) { //--- // Note: Clip the cache tile(nitf block) to the image clipRect // since there are nitf blocks that go beyond the image // dimensions, i.e., edge blocks. //--- ossimIrect cr = theCacheTile->getImageRectangle().clipToRect(clipRect); theTile->loadTile(theCacheTile->getBuf(), theCacheTile->getImageRectangle(), cr, theCacheTileInterLeaveType); } else { // Error loading... return false; } } x += BLOCK_WIDTH; // Go to next block. } y += BLOCK_HEIGHT; // Go to next row of blocks. } return true; } bool ossimNitfTileSource::loadBlockFromCache(ossim_uint32 x, ossim_uint32 y, const ossimIrect& clipRect) { bool result = false; if (theCacheEnabledFlag) { //--- // The origin set in the cache tile must have the sub image offset in it // since "theTile" is relative to any sub image offset. This is so that // "theTile->loadTile(theCacheTile)" will work. //--- ossimIpt origin(x, y); ossimRefPtr tempTile = ossimAppFixedTileCache::instance()->getTile(theCacheId, origin); if (tempTile.valid()) { //--- // Note: Clip the cache tile(nitf block) to the image clipRect since // there are nitf blocks that go beyond the image dimensions, i.e., // edge blocks. //--- ossimIrect cr = tempTile->getImageRectangle().clipToRect(clipRect); theTile->loadTile(tempTile.get()->getBuf(), tempTile->getImageRectangle(), cr, theCacheTileInterLeaveType); result = true; } } return result; } bool ossimNitfTileSource::loadBlock(ossim_uint32 x, ossim_uint32 y) { #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::loadBlock DEBUG:" << " x: " << x << " y: " << y << endl; } #endif //--- // The origin set in the cache tile must have the sub image offset in it // since "theTile" is relative to any sub image offset. This is so that // "theTile->loadTile(theCacheTile)" will work. //--- ossimIpt origin(x, y); const ossimNitfImageHeader* hdr = getCurrentImageHeader(); theCacheTile->setOrigin(origin); ossim_uint32 readSize = theReadBlockSizeInBytes; if(!theCacheTile->getImageRectangle().completely_within(theBlockImageRect)) { readSize = getPartialReadSize(origin); } if((hdr->hasBlockMaskRecords())|| (readSize != theReadBlockSizeInBytes)) { theCacheTile->makeBlank(); } switch (theReadMode) { case READ_BIR: case READ_BIR_BLOCK: case READ_BIP: case READ_BIP_BLOCK: { std::streamoff p; if(getPosition(p, x, y, 0)) { theFileStr->seekg(p, ios::beg); char* buf = (char*)(theCacheTile->getBuf()); if (!theFileStr->read(buf, readSize)) { theFileStr->clear(); ossimNotify(ossimNotifyLevel_FATAL) << "ossimNitfTileSource::loadBlock BIP Read Error!" << "\nReturning error..." << endl; theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return false; } } break; } case READ_BSQ_BLOCK: case READ_BIB_BLOCK: case READ_BIB: { //--- // NOTE: // With some of these types we could do one read and get all bands. // The reads are done per for future enabling on band selection // at the image handler level. //--- for (ossim_uint32 band = 0; band < theNumberOfInputBands; ++band) { ossim_uint8* buf =0; if(isVqCompressed(hdr->getCompressionCode())|| hdr->getRepresentation().upcase().contains("LUT")) { buf = (ossim_uint8*)&(theCompressedBuf.front()); } else { buf = (ossim_uint8*)(theCacheTile->getBuf(band)); } std::streamoff p; if(getPosition(p, x, y, band)) { theFileStr->seekg(p, ios::beg); if (!theFileStr->read((char*)buf, readSize)) { theFileStr->clear(); ossimNotify(ossimNotifyLevel_FATAL) << "ossimNitfTileSource::loadBlock Read Error!" << "\nReturning error..." << endl; theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return false; } else if(hdr->getCompressionCode() == "C4") { vqUncompressC4(theCacheTile, (ossim_uint8*)&(theCompressedBuf.front())); } else if(hdr->getCompressionCode() == "M4") { vqUncompressM4(theCacheTile, (ossim_uint8*)&(theCompressedBuf.front())); } else if(hdr->getRepresentation().upcase().contains("LUT")) { lutUncompress(theCacheTile, (ossim_uint8*)&(theCompressedBuf.front())); } } } break; } case READ_JPEG_BLOCK: { if (uncompressJpegBlock(x, y) == false) { theCacheTile->makeBlank(); theFileStr->clear(); ossimNotify(ossimNotifyLevel_FATAL) << "ossimNitfTileSource::loadBlock Read Error!" << "\nReturning error..." << endl; return false; } break; } default: break; } if(thePackedBitsFlag) { explodePackedBits(theCacheTile); } // Check for swap bytes. if (theSwapBytesFlag) { ossimEndian swapper; swapper.swap(theScalarType, theCacheTile->getBuf(), theCacheTile->getSize()); } if ( !isVqCompressed(hdr->getCompressionCode()) ) { convertTransparentToNull(theCacheTile); } // Set the origin of the cache tile. theCacheTile->validate(); if (theCacheEnabledFlag) { // Add it to the cache for the next time. ossimAppFixedTileCache::instance()->addTile(theCacheId, theCacheTile); } return true; } void ossimNitfTileSource::explodePackedBits(ossimRefPtr packedBuffer)const { ossim_uint8* tempBuf = new ossim_uint8[packedBuffer->getSizePerBandInBytes()]; ossim_uint32 idx = 0; ossim_uint32 bandIdx = 0; ossim_uint32 h = packedBuffer->getHeight(); ossim_uint32 w = packedBuffer->getWidth(); ossim_uint32 maxIdx = w*h; ossim_uint32 bandCount = packedBuffer->getNumberOfBands(); switch(packedBuffer->getScalarType()) { case OSSIM_UINT8: { ossim_uint8* outputBuf = (ossim_uint8*)tempBuf; for(bandIdx = 0; bandIdx < bandCount; ++bandIdx) { ossimPackedBits packedBits((ossim_uint8*)packedBuffer->getBuf(bandIdx), getCurrentImageHeader()->getBitsPerPixelPerBand()); for(idx = 0; idx < maxIdx; ++idx) { *outputBuf = (ossim_uint8)packedBits.getValueAsUint32(idx); ++outputBuf; } memcpy((char*)packedBuffer->getBuf(bandIdx), (char*)tempBuf, theCacheTile->getSizePerBandInBytes()*bandCount); } break; } case OSSIM_UINT16: { ossim_uint16* outputBuf = (ossim_uint16*)tempBuf; for(bandIdx = 0; bandIdx < bandCount; ++bandIdx) { ossimPackedBits packedBits((ossim_uint8*)packedBuffer->getBuf(bandIdx), getCurrentImageHeader()->getBitsPerPixelPerBand()); for(idx = 0; idx < maxIdx; ++idx) { *outputBuf = (ossim_uint16)packedBits.getValueAsUint32(idx); ++outputBuf; } memcpy((char*)packedBuffer->getBuf(bandIdx), (char*)tempBuf, theCacheTile->getSizePerBandInBytes()*bandCount); } break; } case OSSIM_FLOAT: { ossim_float32* outputBuf = (ossim_float32*)tempBuf; for(bandIdx = 0; bandIdx < bandCount; ++bandIdx) { ossimPackedBits packedBits((ossim_uint8*)packedBuffer->getBuf(bandIdx), getCurrentImageHeader()->getBitsPerPixelPerBand()); for(idx = 0; idx < maxIdx; ++idx) { *outputBuf = (ossim_float32)packedBits.getValueAsUint32(idx); ++outputBuf; } memcpy((char*)packedBuffer->getBuf(bandIdx), (char*)tempBuf, theCacheTile->getSizePerBandInBytes()*bandCount); } break; } default: { break; } } delete [] tempBuf; } void ossimNitfTileSource::convertTransparentToNull(ossimRefPtr tile)const { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if(!hdr||!tile) return; if(!tile->getBuf()) return; ossimIpt tempOrigin = tile->getOrigin(); ossim_uint32 blockNumber = getBlockNumber(tempOrigin); ossim_uint32 numberOfBands = tile->getNumberOfBands(); ossim_uint32 band = 0; if(hdr->hasPadPixelMaskRecords()) { if(hdr->hasTransparentCode()) { ossim_uint32 idx = 0; ossim_uint32 maxIdx = tile->getWidth()*tile->getHeight(); for (band = 0; band < numberOfBands; ++band) { if(hdr->getPadPixelMaskRecordOffset(blockNumber, band)!=0xffffffff) { switch(tile->getScalarType()) { case OSSIM_UINT8: { ossim_uint8 transparentValue = hdr->getTransparentCode(); ossim_uint8* buf = (ossim_uint8*)tile->getBuf(band); ossim_uint8 nullPix = (ossim_uint8)tile->getNullPix(band); for(idx = 0; idx < maxIdx; ++idx) { if(*buf == transparentValue) { *buf = nullPix; } ++buf; } break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { ossim_uint16 transparentValue = hdr->getTransparentCode(); ossim_uint16* buf = (ossim_uint16*)tile->getBuf(band); ossim_uint16 nullPix = (ossim_uint16)tile->getNullPix(band); for(idx = 0; idx < maxIdx; ++idx) { if(*buf == transparentValue) { *buf = nullPix; } ++buf; } break; } case OSSIM_SINT16: { ossim_sint16 transparentValue = hdr->getTransparentCode(); ossim_sint16* buf = (ossim_sint16*)tile->getBuf(band); ossim_sint16 nullPix = (ossim_sint16)tile->getNullPix(band); for(idx = 0; idx < maxIdx; ++idx) { if(*buf == transparentValue) { *buf = nullPix; } ++buf; } break; } default: { break; } } } } } } } double ossimNitfTileSource::getMinPixelValue(ossim_uint32 band)const { double result = ossimImageHandler::getMinPixelValue(band); if(thePackedBitsFlag) { if(result < 1.0) result = 1.0; } return result; } double ossimNitfTileSource::getMaxPixelValue(ossim_uint32 band)const { double result = ossimImageHandler::getMaxPixelValue(band); const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if(hdr) { if(thePackedBitsFlag) { double test = 1<<(hdr->getBitsPerPixelPerBand()); if(result > test) result = test; } else { ossim_int32 bitsPerPixel = hdr->getActualBitsPerPixelPerBand(); switch (bitsPerPixel) { case 11: { if (result > 2047.0) { result = 2047.0; } break; } case 12: { if (result > 4095.0) { result = 4095.0; } break; } default: break; } } } return result; } double ossimNitfTileSource::getNullPixelValue(ossim_uint32 band)const { double result = ossimImageHandler::getNullPixelValue(band); if(thePackedBitsFlag) { if((result < 0) || (result > getMaxPixelValue(band))) { result = 0.0; } } return result; } bool ossimNitfTileSource::getPosition(std::streamoff& streamPosition, ossim_uint32 x, ossim_uint32 y, ossim_uint32 band) const { // // NOTE: "theCacheSize is always relative to a block size except in // the case where a block is the entire image. // streamPosition = 0; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return streamPosition; } ossim_uint64 blockNumber = getBlockNumber(ossimIpt(x,y)); #if 0 cout << "ossimNitfTileSource::getPosition blockNumber: " << blockNumber << endl; #endif streamPosition = (std::streamoff)hdr->getDataLocation(); // Position to first block. if(hdr->hasBlockMaskRecords()) { ossim_uint64 blockOffset = hdr->getBlockMaskRecordOffset(blockNumber, band); if(blockOffset == 0xffffffff) { return false; } streamPosition += blockOffset; } switch (theReadMode) { case READ_BIB_BLOCK: { if(!hdr->hasBlockMaskRecords()) { streamPosition += (std::streamoff)((ossim_uint64)blockNumber * (ossim_uint64)getBlockOffset()) + ((ossim_uint64)getBandOffset() * band); } else { streamPosition += (std::streamoff)((ossim_uint64)getBandOffset() * (ossim_uint64)band); } break; } case READ_BIB: { streamPosition += (std::streamoff) ((ossim_uint64)blockNumber * (ossim_uint64)theReadBlockSizeInBytes)+ ((ossim_uint64)getBandOffset() * (ossim_uint64)band); break; } case READ_BSQ_BLOCK: { if(!hdr->hasBlockMaskRecords()) { streamPosition += (std::streamoff)((ossim_uint64)blockNumber * (ossim_uint64)getBlockOffset()) + ((ossim_uint64)getBandOffset() * (ossim_uint64)band); } break; } case READ_JPEG_BLOCK: { streamPosition += (std::streamoff)((ossim_uint64)blockNumber * (ossim_uint64)theReadBlockSizeInBytes); break; } default: { if(!hdr->hasBlockMaskRecords()) { streamPosition += (std::streamoff)((ossim_uint64)blockNumber*(ossim_uint64)getBlockOffset()); } break; } } return true; } std::streampos ossimNitfTileSource::getBandOffset() const { std::streampos bandOffset = 0; switch (theReadMode) { case READ_BIB_BLOCK: case READ_BIP_BLOCK: case READ_BIR_BLOCK: case READ_BIB: case READ_BIP: case READ_BIR: bandOffset = theBlockSizeInBytes; break; case READ_BSQ_BLOCK: bandOffset = getNumberOfBlocks() * theBlockSizeInBytes; break; default: break; } return bandOffset; } std::streampos ossimNitfTileSource::getBlockOffset() const { std::streampos blockOffset = 0; std::streampos blockSizeInBytes = 0; if (getNumberOfBlocks() == 1) { blockSizeInBytes = theReadBlockSizeInBytes; } else { blockSizeInBytes = theBlockSizeInBytes; } switch (theReadMode) { case READ_BIB_BLOCK: case READ_BIB: // Band interleaved by block. blockOffset = blockSizeInBytes * theNumberOfInputBands; break; case READ_BIR_BLOCK: case READ_BSQ_BLOCK: case READ_BIP_BLOCK: case READ_BIP: case READ_BIR: // Blocks side by side. blockOffset = blockSizeInBytes; break; case READ_JPEG_BLOCK: blockSizeInBytes = theReadBlockSizeInBytes; break; default: break; } return blockOffset; } ossim_uint32 ossimNitfTileSource::getNumberOfBlocks() const { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return 0; } return static_cast( hdr->getNumberOfBlocksPerRow() * hdr->getNumberOfBlocksPerCol() ); } bool ossimNitfTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { if ( !ossimImageHandler::loadState(kwl, prefix) ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::loadState(kwl, prefix) DEBUG:" << "\nUnable to load, exiting..." << std::endl; } return false; } const char* lookup = kwl.find(prefix, "entry"); if (lookup) { ossimString s(lookup); theCurrentEntry = s.toUInt32(); } theOutputBandList.clear(); ossimString bands = kwl.find(prefix, ossimKeywordNames::BANDS_KW); if (!bands.empty()) { ossim::toSimpleVector(theOutputBandList, bands); } lookup = kwl.find(prefix,ossimKeywordNames::ENABLE_CACHE_KW); if (lookup) { ossimString s(lookup); theCacheEnabledFlag = s.toBool(); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::loadState(kwl, prefix) DEBUG:" << "\nCurrent entry: " << theCurrentEntry << "\nCache enable flag: " << theCacheEnabledFlag << std::endl; } return open(); } bool ossimNitfTileSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Add the entry number. kwl.add(prefix, "entry", theCurrentEntry, true); // Add the cache_enable flag. kwl.add(prefix, ossimKeywordNames::ENABLE_CACHE_KW, theCacheEnabledFlag, true); // Call the base class save state. return ossimImageHandler::saveState(kwl, prefix); } ossimScalarType ossimNitfTileSource::getOutputScalarType() const { return theScalarType; } ossim_uint32 ossimNitfTileSource::getTileWidth() const { ossim_uint32 result = 0; bool needDefault = false; if(!theCacheSize.hasNans()&& theCacheSize.x > 0) { result = theCacheSize.x; if(result >= getBoundingRect().width()) { needDefault = true; } } else { needDefault = true; } if(needDefault) { ossimIpt tileSize; ossim::defaultTileSize(tileSize); result = static_cast(tileSize.x); } return result; } ossim_uint32 ossimNitfTileSource::getTileHeight() const { ossim_uint32 result = 0; bool needDefault = false; if(!theCacheSize.hasNans()&& theCacheSize.y > 0) { result = theCacheSize.y; if(result >= getBoundingRect().height()) { needDefault = true; } } else { needDefault = true; } if(needDefault) { ossimIpt tileSize; ossim::defaultTileSize(tileSize); result = static_cast(tileSize.y); } return result; } ossim_uint32 ossimNitfTileSource::getNumberOfInputBands() const { return theNumberOfInputBands; } ossim_uint32 ossimNitfTileSource::getNumberOfOutputBands() const { return theNumberOfOutputBands; } ossim_uint32 ossimNitfTileSource::getNumberOfLines(ossim_uint32 resLevel) const { ossim_uint32 result = 0; if (resLevel == 0) { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (hdr) { result = hdr->getNumberOfRows(); } } else if (theOverview.valid()) { result = theOverview->getNumberOfLines(resLevel); } return result; } ossim_uint32 ossimNitfTileSource::getNumberOfSamples(ossim_uint32 resLevel) const { ossim_uint32 result = 0; if (resLevel == 0) { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (hdr) { result = hdr->getNumberOfCols(); } } else if (theOverview.valid()) { result = theOverview->getNumberOfSamples(resLevel); } return result; } ossim_uint32 ossimNitfTileSource::getBlockNumber(const ossimIpt& block_origin) const { ossim_uint32 blockNumber = 0; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return blockNumber; } ossim_uint32 blockY; ossim_uint32 blockX; blockX = (block_origin.x / theCacheSize.x); blockY= (block_origin.y / theCacheSize.y); switch (theReadMode) { case READ_BIB_BLOCK: case READ_BIP_BLOCK: case READ_BIR_BLOCK: case READ_BSQ_BLOCK: case READ_JPEG_BLOCK: { blockNumber = ((blockY*hdr->getNumberOfBlocksPerRow()) + blockX); break; } case READ_BIB: case READ_BIP: case READ_BIR: //--- // These read modes are for a single block image. The cache size will // be set to the width of the image (block) by the height of one tile. // // This is to avoid reading an entire large image with a single block // into memory. //--- blockNumber = blockY; break; default: break; } return blockNumber; } ossim_uint32 ossimNitfTileSource::getPartialReadSize(const ossimIpt& /* blockOrigin */)const { ossim_uint32 result = 0; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return result; } if(theCacheTile->getImageRectangle().completely_within(theBlockImageRect)) { return theReadBlockSizeInBytes; } ossimIrect clipRect = theCacheTile->getImageRectangle().clipToRect(theBlockImageRect); result = (theCacheSize.x* clipRect.height()* hdr->getBitsPerPixelPerBand())/8; switch (theReadMode) { case READ_BSQ_BLOCK: case READ_BIB_BLOCK: case READ_BIB: { // purposely left blank. only hear for clarity. break; } case READ_BIP_BLOCK: case READ_BIR_BLOCK: case READ_BIP: case READ_BIR: { result *= theNumberOfInputBands; break; } default: { break; } } return result; } bool ossimNitfTileSource::isVqCompressed(const ossimString& compressionCode)const { return((compressionCode == "C4")|| (compressionCode == "M4")); } ossim_uint32 ossimNitfTileSource::getImageTileWidth() const { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); ossim_uint32 tileSize = 0; if (!hdr) { return tileSize; } tileSize = hdr->getNumberOfPixelsPerBlockHoriz(); if(tileSize >= getBoundingRect().width()) tileSize = 0; return tileSize; } ossim_uint32 ossimNitfTileSource::getImageTileHeight() const { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); ossim_uint32 tileSize = 0; if (!hdr) { return tileSize; } tileSize = hdr->getNumberOfPixelsPerBlockVert(); if(tileSize >= getBoundingRect().height()) tileSize = 0; return tileSize; } ossimString ossimNitfTileSource::getShortName()const { return ossimString("ossim_nitf"); } ossimString ossimNitfTileSource::getLongName()const { return ossimString("ossim nitf reader"); } ossim_uint32 ossimNitfTileSource::getCurrentEntry() const { return theCurrentEntry; } ossim_uint32 ossimNitfTileSource::getNumberOfEntries() const { return (ossim_uint32)theEntryList.size(); } void ossimNitfTileSource::getEntryList(std::vector& entryList)const { entryList = theEntryList; // entryList.resize(theNumberOfImages); // for (ossim_uint32 i = 0; i < theNumberOfImages; ++i) // { // entryList[i] = i; // } } bool ossimNitfTileSource::setCurrentEntry(ossim_uint32 entryIdx) { bool result = true; if (theCurrentEntry != entryIdx) { if ( isOpen() ) { if ( entryIdx < theNumberOfImages ) { // Clear the geometry. theGeometry = 0; // Must clear or openOverview will use last entries. theOverviewFile.clear(); theCurrentEntry = entryIdx; theOutputBandList.clear(); //--- // Since we were previously open and the the entry has changed we // need to reinitialize some things. //--- result = allocate(); if (result) { completeOpen(); } } else { result = false; // Entry index out of range. } } else { //--- // Not open. // Allow this knowing that the parseFile will check for out of range. //--- theCurrentEntry = entryIdx; } } if(result) { if(theNitfImageHeader[theCurrentEntry]->getRepresentation().contains("LUT")) { theLut = theNitfImageHeader[theCurrentEntry]->createLut(0); } } return result; } bool ossimNitfTileSource::getCacheEnabledFlag() const { return theCacheEnabledFlag; } void ossimNitfTileSource::setCacheEnabledFlag(bool flag) { if (flag != theCacheEnabledFlag) { // State of caching has changed... theCacheEnabledFlag = flag; if ( theCacheEnabledFlag) // Cache enabled. { theCacheId = ossimAppFixedTileCache::instance()-> newTileCache(theBlockImageRect, theCacheSize); } else // Cache disabled... { // Clean out the cache if there was one. if (theCacheId != -1) { ossimAppFixedTileCache::instance()->deleteCache(theCacheId); theCacheId = -1; } } } } const ossimNitfFileHeader* ossimNitfTileSource::getFileHeader()const { if(theNitfFile.valid()) { return theNitfFile->getHeader(); } return 0; } ossimNitfFileHeader* ossimNitfTileSource::getFileHeader() { if(theNitfFile.valid()) { return theNitfFile->getHeader(); } return 0; } ossimNitfFile* ossimNitfTileSource::getNitfFile() { return theNitfFile.get(); } const ossimNitfFile *ossimNitfTileSource::getNitfFile() const { return theNitfFile.get(); } const ossimNitfImageHeader* ossimNitfTileSource::getCurrentImageHeader() const { if(theNitfImageHeader.size()) { return theNitfImageHeader[theCurrentEntry].get(); } return 0; } ossimNitfImageHeader* ossimNitfTileSource::getCurrentImageHeader() { if(theNitfImageHeader.size()) { return theNitfImageHeader[theCurrentEntry].get(); } return 0; } bool ossimNitfTileSource::getRgbBandList(std::vector& bandList) const { bool result = false; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); const ossim_uint32 BANDS = getNumberOfOutputBands(); const ossim_uint32 BOGUS = 99999; if ( hdr && (BANDS > 2) ) { ossim_uint32 r = BOGUS; ossim_uint32 g = BOGUS; ossim_uint32 b = BOGUS; for ( ossim_uint32 i = 0; i < BANDS; ++i ) { const ossimRefPtr imageBand = hdr->getBandInformation( i ); if ( imageBand.valid() ) { ossimString os = imageBand->getBandRepresentation(); os.trim(); // Remove trailing spaces. os.upcase(); if ( os == "R" ) { r = i; } else if ( os == "G" ) { g = i; } else if ( os == "B" ) { b = i; } if ( ( i > 1 ) && ( r != BOGUS ) && ( g != BOGUS ) && ( b != BOGUS ) ) { result = true; bandList.resize(3); bandList[0] = r; bandList[1] = g; bandList[2] = b; break; // done... } } } // TODO: Derive rgb from ISUBCAT wavelength or other nitf tags. } return result; } // End: ossimNitfTileSource::getRgbBandList( ... ) void ossimNitfTileSource::setBoundingRectangle(const ossimIrect& imageRect) { theImageRect = imageRect; // now shift the internal block rect as well theBlockImageRect = (theBlockImageRect - theBlockImageRect.ul()); } ossimRefPtr ossimNitfTileSource::getProperty(const ossimString& name)const { if (name == ossimKeywordNames::ENABLE_CACHE_KW) { ossimProperty* p = new ossimBooleanProperty(name, theCacheEnabledFlag); return ossimRefPtr(p); } else { if(theNitfFile.valid()) { if(getFileHeader()) { ossimRefPtr p = theNitfFile->getHeader()->getProperty(name); if(p.valid()) { p->setReadOnlyFlag(true); return p; } } } const ossimNitfImageHeader* imageHeader = getCurrentImageHeader(); if(imageHeader) { ossimRefPtr p = imageHeader->getProperty(name); if(p.valid()) { p->setReadOnlyFlag(true); return p; } } } return ossimImageHandler::getProperty(name); } void ossimNitfTileSource::setProperty(ossimRefPtr property) { if (!property) return; ossimString name = property->getName(); if (name == ossimKeywordNames::ENABLE_CACHE_KW) { ossimBooleanProperty* obj = PTR_CAST(ossimBooleanProperty, property.get()); if (obj) { setCacheEnabledFlag(obj->getBoolean()); } } else { ossimImageHandler::setProperty(property); } } void ossimNitfTileSource::getPropertyNames(std::vector& propertyNames)const { ossimImageHandler::getPropertyNames(propertyNames); propertyNames.push_back(ossimKeywordNames::ENABLE_CACHE_KW); if(getFileHeader()) { getFileHeader()->getPropertyNames(propertyNames); } const ossimNitfImageHeader* imageHeader = getCurrentImageHeader(); if(imageHeader) { imageHeader->getPropertyNames(propertyNames); } } ossimString ossimNitfTileSource::getSecurityClassification() const { if(getCurrentImageHeader()) { return getCurrentImageHeader()->getSecurityClassification(); } return "U"; } void ossimNitfTileSource::lutUncompress(ossimRefPtr destination, ossim_uint8* source) { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr||!destination) { return; } if((destination->getNumberOfBands()<3)|| (!destination->getBuf())|| (destination->getScalarType()!=OSSIM_UINT8)|| (!theLut.valid())) { return; } if(destination->getNumberOfBands()!=theLut->getNumberOfBands()) { return; } ossim_uint8* tempRows[3]; tempRows[0] = (ossim_uint8*)destination->getBuf(0); tempRows[1] = (ossim_uint8*)destination->getBuf(1); tempRows[2] = (ossim_uint8*)destination->getBuf(2); ossim_uint8* srcPtr = source; ossim_uint32 compressionYidx = 0; ossim_uint32 compressionXidx = 0; ossim_uint32 uncompressIdx = 0; ossim_uint32 h = destination->getHeight(); ossim_uint32 w = destination->getWidth(); for(compressionYidx = 0; compressionYidx < h; ++compressionYidx) { for(compressionXidx = 0; compressionXidx < w; ++compressionXidx) { tempRows[0][uncompressIdx] = (*theLut)[*srcPtr][0]; tempRows[1][uncompressIdx] = (*theLut)[*srcPtr][1]; tempRows[2][uncompressIdx] = (*theLut)[*srcPtr][2]; ++srcPtr; ++uncompressIdx; } } } void ossimNitfTileSource::vqUncompressC4( ossimRefPtr destination, ossim_uint8* source) { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr||!destination) { return; } const ossim_uint32 BANDS = destination->getNumberOfBands(); if( ( (BANDS != 1) && (BANDS!=3) ) || (!destination->getBuf()) || (destination->getScalarType()!=OSSIM_UINT8) || !theLut.valid() || (theLut->getNumberOfBands() != BANDS) ) { return; } ossimNitfVqCompressionHeader* compressionHeader = PTR_CAST(ossimNitfVqCompressionHeader, hdr->getCompressionHeader().get()); if(!compressionHeader) { return; } const std::vector& table = compressionHeader->getTable(); ossimRefPtr bandInfo = hdr->getBandInformation(0); if(!bandInfo.valid()) return; std::vector > luts(BANDS); std::vector tempRows(BANDS); ossim_uint32 band; for (band =0; bandgetLut(band); if ( luts[band].valid() ) { tempRows[band] = (ossim_uint8*)destination->getBuf(band); } else { return; } } ossimPackedBits bits(source, compressionHeader->getImageCodeBitLength()); const ossim_uint32 ROWS = static_cast(table.size()); const ossim_uint32 COLS = static_cast(table[0]. theNumberOfValuesPerCompressionLookup); const ossim_uint32 COMPRESSION_HEIGHT = compressionHeader->getNumberOfImageRows(); const ossim_uint32 COMPRESSION_WIDTH = compressionHeader->getNumberOfImageCodesPerRow(); ossim_uint32 DEST_WIDTH = destination->getWidth(); ossim_uint32 compressionIdx = 0; ossim_uint32 uncompressIdx = 0; ossim_uint32 uncompressYidx = 0; ossim_uint8 lutValue = 0; ossim_uint8* data = 0; ossim_uint32 codeWord = 0; for(ossim_uint32 compressionYidx = 0; compressionYidx < COMPRESSION_HEIGHT; ++compressionYidx) { uncompressYidx = compressionYidx * ROWS * DEST_WIDTH; for(ossim_uint32 compressionXidx = 0; compressionXidx < COMPRESSION_WIDTH; ++compressionXidx) { uncompressIdx = uncompressYidx + COLS * compressionXidx; codeWord = bits.getValueAsUint32(compressionIdx++); codeWord *= COLS; for(ossim_uint32 rowIdx = 0; rowIdx < ROWS; ++rowIdx) { data = &(table[rowIdx].theData[codeWord]); for(ossim_uint32 colIdx = 0; colIdx < COLS; ++colIdx) { lutValue = (*data)&0xff; for (band = 0; band < BANDS; ++band) { ossim_uint8 p = (*theLut.get())[lutValue][band]; tempRows[band][uncompressIdx+colIdx] = p; } ++data; } // column loop uncompressIdx += DEST_WIDTH; } // row loop } // x compression loop } // y compression loop } void ossimNitfTileSource::vqUncompressM4( ossimRefPtr destination, ossim_uint8* source) { const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr||!destination) { return; } const ossim_uint32 BANDS = destination->getNumberOfBands(); if(( (BANDS != 1)&&(BANDS!=3) ) || (!destination->getBuf())|| (destination->getScalarType()!=OSSIM_UINT8)) { return; } ossimNitfVqCompressionHeader* compressionHeader = PTR_CAST(ossimNitfVqCompressionHeader, hdr->getCompressionHeader().get()); if(!compressionHeader) { return; } const std::vector& table = compressionHeader->getTable(); ossimRefPtr bandInfo = hdr->getBandInformation(0); if(!bandInfo.valid()) return; std::vector > luts(BANDS); std::vector tempRows(BANDS); ossim_uint32 band; for (band =0; bandgetLut(band); if ( luts[band].valid() ) { tempRows[band] = (ossim_uint8*)destination->getBuf(band); } else { return; } } const ossim_uint8 NI = 216; // null index (transparency index). const ossim_uint8 NP = 0; // null pixel ossim_uint32 destWidth = destination->getWidth(); ossimPackedBits bits(source, compressionHeader->getImageCodeBitLength()); ossim_uint32 compressionYidx = 0; ossim_uint32 compressionXidx = 0; ossim_uint32 compressionIdx = 0; ossim_uint32 uncompressIdx = 0; ossim_uint32 uncompressYidx = 0; ossim_uint32 rows = (ossim_uint32)table.size(); ossim_uint32 cols = 0; ossim_uint32 rowIdx = 0; ossim_uint32 colIdx = 0; if(rows) { cols = table[0].theNumberOfValuesPerCompressionLookup; } ossim_uint32 compressionHeight = compressionHeader->getNumberOfImageRows(); ossim_uint32 compressionWidth = compressionHeader->getNumberOfImageCodesPerRow(); ossim_uint8 lutValue = 0; ossim_uint8* data=0; for(compressionYidx = 0; compressionYidx < compressionHeight; ++compressionYidx) { uncompressYidx = compressionYidx*rows*destWidth; for(compressionXidx = 0; compressionXidx < compressionWidth; ++compressionXidx) { uncompressIdx = uncompressYidx + cols*compressionXidx; ossim_uint32 codeWord = bits.getValueAsUint32(compressionIdx); bool transparent = false; if (codeWord == 4095) { //--- // Check to see if the whole kernel is transparent. If no, the // null index '216' could be used for valid pixels. // // For more see docs: // MIL-PRF-89041A 3.13.1.2 Transparent pixels // MIL-STD-2411 //--- codeWord *= cols; transparent = true; for(rowIdx = 0; rowIdx < rows; ++rowIdx) { data = &table[rowIdx].theData[codeWord]; for(colIdx = 0; colIdx < cols; ++colIdx) { lutValue = (*data)&0xff; if (lutValue != NI) { // Not a kernel full of transparent pixels. transparent = false; break; } ++data; } if (!transparent) { break; } uncompressIdx += destWidth; } } // Reset everyone for loop to copy pixel data from lut. uncompressIdx = uncompressYidx + cols*compressionXidx; codeWord = bits.getValueAsUint32(compressionIdx); codeWord *= cols; for(rowIdx = 0; rowIdx < rows; ++rowIdx) { data = &table[rowIdx].theData[codeWord]; for(colIdx = 0; colIdx < cols; ++colIdx) { lutValue = (*data)&0xff; for (band = 0; band < BANDS; ++band) { ossim_uint8 p = luts[band]->getValue(lutValue); tempRows[band][uncompressIdx+colIdx] = (!transparent?p:NP); } ++data; } uncompressIdx += destWidth; } ++compressionIdx; } // x loop } // y loop } bool ossimNitfTileSource::scanForJpegBlockOffsets() { // Find, capture all jpeg block offsets and sizes for an entry. bool allBlocksFound = false; const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if ( !hdr || (theReadMode != READ_JPEG_BLOCK) || !theFileStr ) { return allBlocksFound; // Get out... } theNitfBlockOffset.clear(); theNitfBlockSize.clear(); //--- // Get the totol blocks. // Note: There can be more than one jpeg image in the nitf. So after blocks // found equals total_blocks get out. //--- ossim_uint32 total_blocks = hdr->getNumberOfBlocksPerRow()*hdr->getNumberOfBlocksPerCol(); //--- // NOTE: // SOI = 0xffd8 Start of image // EOI = 0xffd9 End of image // DHT = 0xffc4 Define Huffman Table(s) // DQT = 0xffdb Define Quantization Table(s) //--- // Seek to the first block. theFileStr->seekg(hdr->getDataLocation(), ios::beg); if ( theFileStr->good() ) { const ossim_uint8 AP6 = 0xe6; const ossim_uint8 AP7 = 0xe7; const ossim_uint8 DHT = 0xc4; const ossim_uint8 DQT = 0xdb; const ossim_uint8 EOI = 0xd9; const ossim_uint8 FF = 0xff; const ossim_uint8 SOI = 0xd8; const ossim_uint8 SOS = 0xda; union { char c; ossim_uint8 uc; } ct; std::streamoff soiOffset = 0; std::streamoff eoiOffset = 0; ossim_uint16 length = 0; ossimEndian* swapper = 0; if ( ossim::byteOrder() == OSSIM_LITTLE_ENDIAN ) { swapper = new ossimEndian(); } // Find all the SOI markers. while ( theFileStr->get( ct.c ) && !allBlocksFound ) { if ( ct.uc == FF ) // Found FF byte. { // Loop to skip multiple 0xff's in cases like FF FF D8 while ( theFileStr->get( ct.c ) ) { if ( ct.uc != FF) { break; } } if ( ct.uc == SOI ) { // At SOI 0xFFD8 marker... SOI marker offset is two bytes back. soiOffset = ((std::streamoff)theFileStr->tellg()) - 2; // Now look for matching EOI. while ( theFileStr->get( ct.c ) ) { if ( ct.uc == FF ) // Found FF byte. { // Loop to skip multiple 0xff's in cases like FF FF D8 while ( theFileStr->get( ct.c ) ) { if ( ct.uc != FF ) { break; } } if ( ct.uc == EOI ) { // At EOI 0xD9marker... eoiOffset = theFileStr->tellg(); // Capture offset: theNitfBlockOffset.push_back( soiOffset ); // Capture block size: theNitfBlockSize.push_back( eoiOffset - soiOffset ); //--- // Since there can be more than one jpeg entry in a file, breeak out of // loop when we hit block size. //--- if ( theNitfBlockOffset.size() == total_blocks ) { allBlocksFound = true; } break; // From "find EOI" while loop. } //--- // These are things to skip to avoid hitting random sequence of FFD9 // and picking up a false EOI. // Not a complete set of markers but all test data works. // drb - 14 May 2013. //--- else if ( ( ct.uc == AP6 ) || ( ct.uc == AP7 ) || ( ct.uc == DHT ) || ( ct.uc == DQT ) || ( ct.uc == SOS ) || ( ( ct.uc >= 0xc0 ) && ( ct.uc <= 0xcF ) ) ) { // Length two byte big endian. theFileStr->read( (char*)&length, 2 ); if ( swapper ) { swapper->swap( length ); } // Length includes two length bytes. // Seek to the end of the record. theFileStr->seekg( length - 2, std::ios_base::cur ); } } // Matches: if ( ct.uc == FF ) } // Matches: while ( theFileStr->get( ut.c ) ) "find EOI loop" } // Matches: if ( ut.uc == SOI ) "SOI marker found" } // Matches: if ( ut.uc == FF ) } // Matches: while ( theFileStr->get( ut.c ) && !allBlocksFound ) if ( swapper ) { delete swapper; swapper = 0; } } // Matches: if ( theFileStr->good() ) theFileStr->seekg(0, ios::beg); theFileStr->clear(); #if 0 /* Please leave for debug. (drb) */ std::streamoff startOfData = hdr->getDataLocation(); ossimNotify(ossimNotifyLevel_WARN) << "current entry: " << theCurrentEntry << "\n"; for (ossim_uint32 i = 0; i < total_blocks; ++i) { cout << "theNitfBlockOffset[" << i << "]: " << theNitfBlockOffset[i] << "\nrealative_offset[" << i << "]: " << (theNitfBlockOffset[i] - startOfData) << "\ntheNitfBlockSize[" << i << "]: " << theNitfBlockSize[i] << "\n"; } #endif if ( !allBlocksFound ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "DEBUG:" << "\nBlock offset count wrong!" << "\nexpected blocks: " << total_blocks << "\noffset array count: " << theNitfBlockOffset.size() << "\nblock size array count: " << theNitfBlockSize.size() << std::endl; } theNitfBlockOffset.clear(); theNitfBlockSize.clear(); } return allBlocksFound; } bool ossimNitfTileSource::uncompressJpegBlock(ossim_uint32 x, ossim_uint32 y) { ossim_uint32 blockNumber = getBlockNumber( ossimIpt(x,y) ); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfTileSource::uncompressJpegBlock DEBUG:" << "\nblockNumber: " << blockNumber << std::endl; } //--- // Logic to hold off on scanning for offsets until a block is actually needed // to speed up loads for things like ossim-info that don't actually read // pixel data. //--- if ( m_jpegOffsetsDirty ) { if ( scanForJpegBlockOffsets() ) { m_jpegOffsetsDirty = false; } else { ossimNotify(ossimNotifyLevel_FATAL) << "ossimNitfTileSource::uncompressJpegBlock scan for offsets error!" << "\nReturning error..." << endl; theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return false; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\noffset to block: " << theNitfBlockOffset[blockNumber] << "\nblock size: " << theNitfBlockSize[blockNumber] << std::endl; } // Seek to the block. theFileStr->seekg(theNitfBlockOffset[blockNumber], ios::beg); // Read the block into memory. std::vector compressedBuf(theNitfBlockSize[blockNumber]); if (!theFileStr->read((char*)&(compressedBuf.front()), theNitfBlockSize[blockNumber])) { theFileStr->clear(); ossimNotify(ossimNotifyLevel_FATAL) << "ossimNitfTileSource::uncompressJpegBlock Read Error!" << "\nReturning error..." << endl; return false; } //--- // Most of comments below from jpeg-6b "example.c" file. //--- /* This struct contains the JPEG decompression parameters and pointers * to working space (which is allocated as needed by the JPEG library). */ jpeg_decompress_struct cinfo; /* We use our private extension JPEG error handler. * Note that this struct must live as long as the main JPEG parameter * struct, to avoid dangling-pointer problems. */ ossimJpegErrorMgr jerr; /* Step 1: allocate and initialize JPEG decompression object */ /* We set up the normal JPEG error routines, then override error_exit. */ cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = ossimJpegErrorExit; /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp(jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. * We need to clean up the JPEG object, close the input file, and return. */ jpeg_destroy_decompress(&cinfo); return false; } /* Now we can initialize the JPEG decompression object. */ jpeg_CreateDecompress(&cinfo, JPEG_LIB_VERSION, sizeof(cinfo)); //--- // Step 2: specify data source. In this case we will uncompress from // memory so we will use "ossimJpegMemorySrc" in place of " jpeg_stdio_src". //--- ossimJpegMemorySrc (&cinfo, &(compressedBuf.front()), static_cast(theReadBlockSizeInBytes)); /* Step 3: read file parameters with jpeg_read_header() */ jpeg_read_header(&cinfo, TRUE); // Check for Quantization tables. if (cinfo.quant_tbl_ptrs[0] == NULL) { // This will load table specified in COMRAT field. if (loadJpegQuantizationTables(cinfo) == false) { jpeg_destroy_decompress(&cinfo); return false; } } // Check for huffman tables. if (cinfo.ac_huff_tbl_ptrs[0] == NULL) { // This will load default huffman tables into . if (loadJpegHuffmanTables(cinfo) == false) { jpeg_destroy_decompress(&cinfo); return false; } } /* Step 4: set parameters for decompression */ /* In this example, we don't need to change any of the defaults set by * jpeg_read_header(), so we do nothing here. */ /* Step 5: Start decompressor */ jpeg_start_decompress(&cinfo); #if 0 /* Please leave for debug. (drb) */ if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "jpeg cinfo.output_width: " << cinfo.output_width << "\njpeg cinfo.output_height: " << cinfo.output_height << "\n"; } #endif const ossim_uint32 SAMPLES = cinfo.output_width; //--- // Note: Some nitf will be tagged with a given number of lines but the last // jpeg block may go beyond that to a complete block. So it you clamp to // last line of the nitf you will get a libjpeg error: // // "Application transferred too few scanlines" // // So here we will always read the full jpeg block even if it is beyond the // last line of the nitf. //--- const ossim_uint32 LINES_TO_READ = min(static_cast(theCacheSize.y), cinfo.output_height); /* JSAMPLEs per row in output buffer */ const ossim_uint32 ROW_STRIDE = SAMPLES * cinfo.output_components; if ( (SAMPLES < theCacheTile->getWidth() ) || (LINES_TO_READ < theCacheTile->getHeight()) ) { theCacheTile->makeBlank(); } if ( (SAMPLES > theCacheTile->getWidth()) || (LINES_TO_READ > theCacheTile->getHeight()) ) { // Error... jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); return false; } // Get pointers to the cache tile buffers. std::vector destinationBuffer(theNumberOfInputBands); for (ossim_uint32 band = 0; band < theNumberOfInputBands; ++band) { destinationBuffer[band] = theCacheTile->getUcharBuf(band); } std::vector lineBuffer(ROW_STRIDE); JSAMPROW jbuf[1]; jbuf[0] = (JSAMPROW) &(lineBuffer.front()); while (cinfo.output_scanline < LINES_TO_READ) { // Read a line from the jpeg file. jpeg_read_scanlines(&cinfo, jbuf, 1); //--- // Copy the line which if band interleaved by pixel the the band // separate buffers. // // Note: // Not sure if IMODE of 'B' is interleaved the same as image with // IMODE of 'P'. // // This works with all samples with IMODE of B and P but I only have // one band 'B' and three band 'P'. So if we ever get a three band // 'B' it could be wrong here. (drb - 20090615) //--- ossim_uint32 index = 0; for (ossim_uint32 sample = 0; sample < SAMPLES; ++sample) { for (ossim_uint32 band = 0; band < theNumberOfInputBands; ++band) { destinationBuffer[band][sample] = lineBuffer[index]; ++index; } } for (ossim_uint32 band = 0; band < theNumberOfInputBands; ++band) { destinationBuffer[band] += theCacheSize.x; } } // clean up... jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); return true; } //--- // Default JPEG quantization tables // Values from: MIL-STD-188-198, APPENDIX A //--- bool ossimNitfTileSource::loadJpegQuantizationTables( jpeg_decompress_struct& cinfo) const { //--- // Check to see if table is present. We will only look at the first table // in the array of arrays. // // NOTE: There are four tables in the array "cinfo.quant_tbl_ptrs". It // looks like the standard is to use the first table. (not sure though) //--- if (cinfo.quant_tbl_ptrs[0] != NULL) { return false; } // Get the COMRAT (compression rate code) from the header: const ossimNitfImageHeader* hdr = getCurrentImageHeader(); if (!hdr) { return false; } ossimString comrat = hdr->getCompressionRateCode(); ossim_uint32 tableIndex = 0; if (comrat.size() >= 4) { // COMRAT string like: "00.2" = use table 2. (between 1 and 5). ossimString s; s.push_back(comrat[static_cast(3)]); ossim_int32 comTbl = s.toInt32(); if ( (comTbl > 0) && (comTbl < 6) ) { tableIndex = comTbl-1; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfTileSource::loadJpegQuantizationTables WARNING\n" << "\nNo quantization tables specified!" << endl; return false; } } cinfo.quant_tbl_ptrs[0] = jpeg_alloc_quant_table((j_common_ptr) &cinfo); JQUANT_TBL* quant_ptr = cinfo.quant_tbl_ptrs[0]; // quant_ptr is JQUANT_TBL* for (ossim_int32 i = 0; i < 64; ++i) { /* Qtable[] is desired quantization table, in natural array order */ quant_ptr->quantval[i] = QTABLE_ARRAY[tableIndex][i]; } return true; } //--- // Default JPEG Huffman tables // Values from: MIL-STD-188-198, APPENDIX B //--- bool ossimNitfTileSource::loadJpegHuffmanTables( jpeg_decompress_struct& cinfo) const { if ( (cinfo.ac_huff_tbl_ptrs[0] != NULL) && (cinfo.dc_huff_tbl_ptrs[0] != NULL) ) { return false; } cinfo.ac_huff_tbl_ptrs[0] = jpeg_alloc_huff_table((j_common_ptr)&cinfo); cinfo.dc_huff_tbl_ptrs[0] = jpeg_alloc_huff_table((j_common_ptr)&cinfo); ossim_int32 i; JHUFF_TBL* huff_ptr; // Copy the ac tables. huff_ptr = cinfo.ac_huff_tbl_ptrs[0]; /* huff_ptr is JHUFF_TBL* */ for (i = 0; i < 16; ++i) { // huff_ptr->bits is array of 17 bits[0] is unused; hence, the i+1 huff_ptr->bits[i+1] = AC_BITS[i]; } for (i = 0; i < 256; ++i) { huff_ptr->huffval[i] = AC_HUFFVAL[i]; } // Copy the dc tables. huff_ptr = cinfo.dc_huff_tbl_ptrs[0]; /* huff_ptr is JHUFF_TBL* */ for (i = 0; i < 16; ++i) { // huff_ptr->bits is array of 17 bits[0] is unused; hence, the i+1 huff_ptr->bits[i+1] = DC_BITS[i]; } for (i = 0; i < 256; i++) { /* symbols[] is the list of Huffman symbols, in code-length order */ huff_ptr->huffval[i] = DC_HUFFVAL[i]; } return true; } // Protected to disallow use... ossimNitfTileSource::ossimNitfTileSource(const ossimNitfTileSource& /* obj */) { } // Protected to disallow use... ossimNitfTileSource& ossimNitfTileSource::operator=( const ossimNitfTileSource& /* rhs */) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimNitfWriter.cpp000066400000000000000000000721751352751253100220050ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimNitfWriter.cpp 22814 2014-06-05 15:13:28Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfWriter, "ossimNitfWriter", ossimNitfWriterBase); static ossimTrace traceDebug(ossimString("ossimNitfWriter:debug")); // Maximum file size static const ossim_uint64 KB = 1024; static const ossim_uint64 MB = KB * KB; static const ossim_uint64 MB50 = 50 * MB; static const ossim_uint64 GB = KB * MB; static const ossim_uint64 GB2 = 2 * GB; static const ossim_uint64 GB10 = 10 * GB; ossimNitfWriter::ossimNitfWriter(const ossimFilename& filename, ossimImageSource* inputSource) : ossimNitfWriterBase(filename, inputSource), m_str(0), m_fileHeader(0), m_imageHeader(0), m_textHeader(0), m_textEntry(), m_blockSize(OSSIM_DEFAULT_TILE_WIDTH, OSSIM_DEFAULT_TILE_HEIGHT) { //--- // Since the internal nitf tags are not very accurate, write an external // geometry out as default behavior. Users can disable this via the // property interface or keyword list. //--- // Added GEOLOB tag for geographic output. UTM is good with BLOCKA. // No longer needed. (drb - 30 March 2018) // setWriteExternalGeometryFlag(true); m_fileHeader = new ossimNitfFileHeaderV2_1; m_imageHeader = new ossimNitfImageHeaderV2_1; // m_textHeader is conditional so we will not new here. theOutputImageType = "nitf_block_band_separate"; //--- // The tile size can be set in the preferences via "tile_size" keyword. // This will get it if set; else, set to default. //--- ossim::defaultTileSize(m_blockSize); // These are always set: m_fileHeader->setEncryption( ossimString("0") ); m_imageHeader->setJustification( ossimString("R") ); // Set any site defaults. initializeDefaultsFromConfigFile( dynamic_cast(m_fileHeader.get()), dynamic_cast(m_imageHeader.get()) ); } ossimNitfWriter::~ossimNitfWriter() { //--- // This looks like a leak but it's not as both of these are ossimRefPtr's. //--- m_fileHeader=0; m_imageHeader=0; m_textHeader=0; close(); } bool ossimNitfWriter::isOpen()const { return (m_str ? m_str->is_open() : false); } bool ossimNitfWriter::open() { bool result = true; if(isOpen()) { close(); } // there is a bug in gcc < 5.0 and we can't use constructors in the // C++11 build. Will refactor to do a new ifstream then use open // m_str = std::make_shared(); m_str->open(theFilename.c_str(), ios::out|ios::binary); if(!m_str->is_open()) { m_str.reset(); result = false; } //new std::ofstream; //m_str->open(theFilename.c_str(), ios::out|ios::binary); return result; } void ossimNitfWriter::close() { if(m_str) { m_str->close(); m_str.reset(); } } bool ossimNitfWriter::writeFile() { if(!theInputConnection->isMaster()) { theInputConnection->slaveProcessTiles(); return true; } open(); if (!isOpen()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfWriter::writeFile ERROR:" << " Could not open! Returning..." << std::endl; } return false; } // Write out the geometry info. writeGeometry(m_imageHeader.get(), theInputConnection.get()); // addStandardTags(); bool result = false; if((theOutputImageType == "nitf_block_band_separate")|| (theOutputImageType == "image/nitf")) { result = writeBlockBandSeparate(); } else if(theOutputImageType == "nitf_block_band_sequential") { result = writeBlockBandSequential(); } close(); return result; } void ossimNitfWriter::getImageTypeList(std::vector& imageTypeList)const { imageTypeList.push_back(ossimString("nitf_block_band_separate")); imageTypeList.push_back(ossimString("nitf_block_band_sequential")); } void ossimNitfWriter::setProperty(ossimRefPtr property) { if(!property) return; ossimString name = property->getName(); if(name == "file_header") { ossimContainerProperty* containerProperty = PTR_CAST(ossimContainerProperty, property.get()); if(containerProperty) { std::vector > propertyList; containerProperty->getPropertyList(propertyList); m_fileHeader->setProperties(propertyList); } } else if(name == "image_header") { ossimContainerProperty* containerProperty = PTR_CAST(ossimContainerProperty, property.get()); if(containerProperty) { std::vector > propertyList; containerProperty->getPropertyList(propertyList); m_imageHeader->setProperties(propertyList); } } else if(name == "block_size") { ossimIpt blockSize; blockSize.x = property->valueToString().toInt32(); blockSize.y = blockSize.x; setTileSize(blockSize); } else { ossimNitfWriterBase::setProperty(property); } } ossimRefPtr ossimNitfWriter::getProperty(const ossimString& name)const { ossimRefPtr result = 0; if(name == "file_header") { ossimContainerProperty* container = new ossimContainerProperty(name); std::vector > propertyList; m_fileHeader->getPropertyList(propertyList); container->addChildren(propertyList); result = container; } else if(name == "image_header") { ossimContainerProperty* container = new ossimContainerProperty(name); std::vector > propertyList; m_imageHeader->getPropertyList(propertyList); container->addChildren(propertyList); result = container; } else if(name == "des_header") { ossimContainerProperty* container = new ossimContainerProperty(name); std::vector > propertyList; // Create a temporary DES in order to populate propertyList. ossimNitfDataExtensionSegmentV2_1 des; des.getPropertyList(propertyList); container->addChildren(propertyList); result = container; } else if(name == "block_size") { ossimStringProperty* stringProp = new ossimStringProperty(name, ossimString::toString(m_blockSize.x), false); // editable flag stringProp->addConstraint(ossimString("64")); stringProp->addConstraint(ossimString("128")); stringProp->addConstraint(ossimString("256")); stringProp->addConstraint(ossimString("512")); stringProp->addConstraint(ossimString("1024")); stringProp->addConstraint(ossimString("2048")); return stringProp; } else { return ossimNitfWriterBase::getProperty(name); } return result; } void ossimNitfWriter::getPropertyNames( std::vector& propertyNames)const { ossimNitfWriterBase::getPropertyNames(propertyNames); propertyNames.push_back("file_header"); propertyNames.push_back("image_header"); propertyNames.push_back("des_header"); propertyNames.push_back("block_size"); } bool ossimNitfWriter::writeBlockBandSeparate() { ossimScalarType scalarType = theInputConnection->getOutputScalarType(); ossim_uint64 byteSize = ossim::scalarSizeInBytes(scalarType); ossimIrect rect = theInputConnection->getBoundingRect(); ossim_uint64 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint64 idx = 0; ossim_uint64 headerStart = (ossim_uint64)m_str->tellp(); // Set the sequencer block size to be the same as output. theInputConnection->setTileSize(m_blockSize); ossim_uint64 blocksHorizontal = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint64 blocksVertical = theInputConnection->getNumberOfTilesVertical(); ossim_uint64 numberOfTiles = theInputConnection->getNumberOfTiles(); ossimNitfImageInfoRecordV2_1 imageInfoRecord; imageInfoRecord.setSubheaderLength(439); // ok if no tags imageInfoRecord.setImageLength(bands*byteSize*blocksVertical*m_blockSize.y*blocksHorizontal*m_blockSize.x); m_fileHeader->setDate(); m_fileHeader->addImageInfoRecord(imageInfoRecord); if ( m_textHeader.valid() ) { // Add any text headers ossimNitfTextFileInfoRecordV2_1 textInfoRecord; textInfoRecord.setSubheaderLength(285); //default // Set length of text to be that of input text textInfoRecord.setTextLength(m_textEntry.length()); m_fileHeader->addTextInfoRecord(textInfoRecord); } // Get the overflow tags from the file header and the image subheader takeOverflowTags(true, true); takeOverflowTags(true, false); takeOverflowTags(false, true); takeOverflowTags(false, false); for (vector::iterator iter = m_dataExtensionSegments.begin(); iter != m_dataExtensionSegments.end(); iter++) { ossimNitfDataExtSegInfoRecordV2_1 desInfoRecord; iter->setSecurityMarkings(*m_fileHeader); std::ostringstream headerOut; headerOut << std::setw(4) << std::setfill('0') << std::setiosflags(ios::right) << iter->getHeaderLength(); strcpy(desInfoRecord.theDataExtSegSubheaderLength, headerOut.str().c_str()); std::ostringstream dataOut; dataOut << std::setw(9) << std::setfill('0') << std::setiosflags(ios::right) << iter->getDataLength(); strcpy(desInfoRecord.theDataExtSegLength, dataOut.str().c_str()); m_fileHeader->addDataExtSegInfoRecord(desInfoRecord); } //--- // This makes space for the file header; it is written again at the end of // this method with updated values // need a better way to get the length. This should be queried on the // header before writing //--- m_fileHeader->writeStream( *m_str ); ossim_uint64 headerLength = ((ossim_uint64)m_str->tellp() - headerStart) /* + 1 */; ossimString representation; m_imageHeader->setActualBitsPerPixel(ossim::getActualBitsPerPixel(scalarType)); m_imageHeader->setBitsPerPixel(ossim::getBitsPerPixel(scalarType)); m_imageHeader->setPixelType(ossimNitfCommon::getNitfPixelType(scalarType)); m_imageHeader->setNumberOfBands(bands); m_imageHeader->setImageMode('B');// blocked bool masked = (m_imageHeader->getCompressionCode() == "NM"); ossimNitfImageDataMaskV2_1 datamask; datamask.setBlockCount(blocksVertical * blocksHorizontal); ossim_uint64 blockLength = bands * byteSize * m_blockSize.x * m_blockSize.y; datamask.setBlockLengthInBytes(blockLength); std::vector blockZeros; if((bands == 3)&& (scalarType == OSSIM_UCHAR)) { m_imageHeader->setRepresentation("RGB"); m_imageHeader->setCategory("VIS"); } else if(bands == 1) { m_imageHeader->setRepresentation("MONO"); m_imageHeader->setCategory("VIS"); } else { m_imageHeader->setRepresentation("MULTI"); m_imageHeader->setCategory("MS"); } m_imageHeader->setBlocksPerRow(blocksHorizontal); m_imageHeader->setBlocksPerCol(blocksVertical); m_imageHeader->setNumberOfPixelsPerBlockRow(m_blockSize.x); m_imageHeader->setNumberOfPixelsPerBlockCol(m_blockSize.y); m_imageHeader->setNumberOfRows(rect.height()); m_imageHeader->setNumberOfCols(rect.width()); ossimNitfImageBandV2_1 bandInfo; for(idx = 0; idx < bands; ++idx) { std::ostringstream out; out << std::setfill('0') << std::setw(2) << idx; bandInfo.setBandRepresentation(out.str().c_str()); m_imageHeader->setBandInfo(idx, bandInfo); } ossim_uint64 imageHeaderStart = m_str->tellp(); m_imageHeader->writeStream( *m_str ); ossim_uint64 imageHeaderEnd = m_str->tellp(); ossim_uint64 imageHeaderSize = imageHeaderEnd - imageHeaderStart; // Start the sequence through tiles: theInputConnection->setToStartOfSequence(); ossimRefPtr data = theInputConnection->getNextTile(); ossim_uint64 tileNumber = 1; ossimEndian endian; // write out mask if needed if(masked) { blockZeros.resize(blockLength); memset(&blockZeros.front(), '\0', blockLength); datamask.writeStream( *m_str ); } while( data.valid() && !needsAborting()) { bool write = true; if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { switch(data->getScalarType()) { case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { endian.swap((ossim_uint16*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_SSHORT16: { endian.swap((ossim_sint16*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { endian.swap((ossim_float32*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { endian.swap((ossim_float64*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } default: break; } } if (masked) { if (memcmp(data->getBuf(), &blockZeros.front(), blockLength) == 0) { write = false; datamask.setIncludeBlock(tileNumber-1, false); } } if(write) { m_str->write((char*)(data->getBuf()), data->getSizeInBytes()); } setPercentComplete(((double)tileNumber / (double)numberOfTiles) * 100); if(!needsAborting()) { data = theInputConnection->getNextTile(); } ++tileNumber; } // ossim_uint64 imageSegmentEnd = m_str->tellp(); // Let's write our text header if ( m_textHeader.valid() ) { m_textHeader->writeStream( *m_str ); //Now write the text m_str->write((char*)(m_textEntry.c_str()), m_textEntry.length()); } for (vector::iterator iter = m_dataExtensionSegments.begin(); iter != m_dataExtensionSegments.end(); iter++) { iter->writeStream( *m_str ); } if (masked) { m_str->seekp(imageHeaderEnd); datamask.writeStream( *m_str ); //delete [] blockZeros; } std::streamoff pos = m_str->tellp(); setComplexityLevel(pos, m_fileHeader.get()); /* * Need to change the way I compute file length and header length later * We need to figure out a better way to compute. */ m_fileHeader->setFileLength(static_cast(pos)); m_fileHeader->setHeaderLength(headerLength); m_str->seekp(0, ios::beg); imageInfoRecord.setSubheaderLength(imageHeaderSize); m_fileHeader->replaceImageInfoRecord(0, imageInfoRecord); m_fileHeader->writeStream( *m_str ); return true; } bool ossimNitfWriter::writeBlockBandSequential() { ossimScalarType scalarType = theInputConnection->getOutputScalarType(); ossim_uint64 byteSize = ossim::scalarSizeInBytes(scalarType); ossimIrect rect = theInputConnection->getBoundingRect(); ossim_uint64 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint64 idx = 0; ossim_uint64 headerStart = (ossim_uint64)m_str->tellp(); // Set the sequencer block size to be the same as output. theInputConnection->setTileSize(m_blockSize); ossim_uint64 blocksHorizontal = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint64 blocksVertical = theInputConnection->getNumberOfTilesVertical(); ossim_uint64 numberOfTiles = theInputConnection->getNumberOfTiles(); ossimNitfImageInfoRecordV2_1 imageInfoRecord; imageInfoRecord.setSubheaderLength(439); imageInfoRecord.setImageLength(bands*byteSize*blocksHorizontal*blocksVertical*m_blockSize.x*m_blockSize.y); m_fileHeader->setDate(); m_fileHeader->addImageInfoRecord(imageInfoRecord); if ( m_textHeader.valid() ) { // Add any text headers ossimNitfTextFileInfoRecordV2_1 textInfoRecord; textInfoRecord.setSubheaderLength(285); //default // Set length of text to be that of input text textInfoRecord.setTextLength(m_textEntry.length()); m_fileHeader->addTextInfoRecord(textInfoRecord); } //--- // This makes space for the file header; it is written again at the end of // this method with updated values // need a better way to get the length. This should be queried on the // header before writing //--- m_fileHeader->writeStream( *m_str ); ossim_uint64 headerLength = ((ossim_uint64)m_str->tellp() - headerStart) /* + 1 */; ossimString representation; m_imageHeader->setActualBitsPerPixel(ossim::getActualBitsPerPixel(scalarType)); m_imageHeader->setBitsPerPixel(ossim::getBitsPerPixel(scalarType)); m_imageHeader->setPixelType(ossimNitfCommon::getNitfPixelType(scalarType)); m_imageHeader->setNumberOfBands(bands); m_imageHeader->setImageMode('S');// blocked if((bands == 3)&& (scalarType == OSSIM_UCHAR)) { m_imageHeader->setRepresentation("RGB"); m_imageHeader->setCategory("VIS"); } else if(bands == 1) { m_imageHeader->setRepresentation("MONO"); m_imageHeader->setCategory("VIS"); } else { m_imageHeader->setRepresentation("MULTI"); m_imageHeader->setCategory("MS"); } m_imageHeader->setBlocksPerRow(blocksHorizontal); m_imageHeader->setBlocksPerCol(blocksVertical); m_imageHeader->setNumberOfPixelsPerBlockRow(m_blockSize.x); m_imageHeader->setNumberOfPixelsPerBlockCol(m_blockSize.y); m_imageHeader->setNumberOfRows(rect.height()); m_imageHeader->setNumberOfCols(rect.width()); ossimNitfImageBandV2_1 bandInfo; for(idx = 0; idx < bands; ++idx) { std::ostringstream out; out << std::setfill('0') << std::setw(2) << idx; bandInfo.setBandRepresentation(out.str().c_str()); m_imageHeader->setBandInfo(idx, bandInfo); } ossim_uint64 imageHeaderStart = m_str->tellp(); m_imageHeader->writeStream( *m_str ); ossim_uint64 imageHeaderEnd = m_str->tellp(); ossim_uint64 imageHeaderSize = imageHeaderEnd - imageHeaderStart; // ossimIpt ul = rect.ul(); // Start the sequence through tiles: theInputConnection->setToStartOfSequence(); ossimRefPtr data = theInputConnection->getNextTile(); ossim_uint64 tileNumber = 0; ossimEndian endian; // get the start to the first band of data block // ossim_uint64 streamOffset = m_str->tellp(); // holds the total pixels to the next band ossim_uint64 blockSizeInBytes = m_blockSize.x*m_blockSize.y*ossim::scalarSizeInBytes(data->getScalarType()); ossim_uint64 bandOffsetInBytes = (blockSizeInBytes*blocksHorizontal*blocksVertical); bool needSwapping = endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN; while(data.valid() && !needsAborting()) { if(needSwapping) { switch(data->getScalarType()) { case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { endian.swap((ossim_uint16*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_SSHORT16: { endian.swap((ossim_sint16*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { endian.swap((ossim_float32*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { endian.swap((ossim_float64*)data->getBuf(), data->getWidth()*data->getHeight()*data->getNumberOfBands()); break; } default: break; } } for(idx = 0; idx < bands; ++idx) { m_str->seekp(streamOffset+ // start of image stream tileNumber*blockSizeInBytes + // start of block for band separate output bandOffsetInBytes*idx, // which band offset is it ios::beg); m_str->write((char*)(data->getBuf(idx)), blockSizeInBytes); } ++tileNumber; setPercentComplete(((double)tileNumber / (double)numberOfTiles) * 100); if(!needsAborting()) { data = theInputConnection->getNextTile(); } } // Let's write our text header if ( m_textHeader.valid() ) { m_textHeader->writeStream( *m_str ); //Now write the text m_str->write((char*)(m_textEntry.c_str()), m_textEntry.length()); } ossim_uint64 pos = m_str->tellp(); setComplexityLevel(pos, m_fileHeader.get()); /* * Need to change the way I compute file length and header length later * We need to figure out a better way to compute. */ m_fileHeader->setFileLength(static_cast(pos)); m_fileHeader->setHeaderLength(headerLength); m_str->seekp(0, ios::beg); imageInfoRecord.setSubheaderLength(imageHeaderSize); m_fileHeader->replaceImageInfoRecord(0, imageInfoRecord); m_fileHeader->writeStream( *m_str ); return true; } void ossimNitfWriter::addRegisteredTag(ossimRefPtr registeredTag, bool unique) { addRegisteredTag(registeredTag, unique, 1, ossimString("IXSHD")); } void ossimNitfWriter::addRegisteredTag(ossimRefPtr registeredTag, bool unique, const ossim_uint32& ownerIndex, const ossimString& tagType) { ossimNitfTagInformation tagInfo; tagInfo.setTagData(registeredTag.get()); tagInfo.setTagType(tagType); switch (ownerIndex) { case 0: { m_fileHeader->addTag(tagInfo, unique); break; } case 1: { m_imageHeader->addTag(tagInfo, unique); break; } default: { // Do nothing } } } bool ossimNitfWriter::addTextToNitf(std::string &inputText) { // Initialize the m_textHeader m_textEntry = inputText; if ( m_textHeader.valid() == false ) { // Only created if we need it. m_textHeader = new ossimNitfTextHeaderV2_1; } return true; } void ossimNitfWriter::getTileSize(ossimIpt& size) const { size = m_blockSize; } void ossimNitfWriter::setTileSize(const ossimIpt& tileSize) { const ossim_int32 MIN_BLOCK_SIZE = 64; if ( (tileSize.x % MIN_BLOCK_SIZE) || (tileSize.y % MIN_BLOCK_SIZE) ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfWriter::setTileSize ERROR:" << "\nBlock size must be a multiple of " << MIN_BLOCK_SIZE << "\nSize remains: " << m_blockSize << std::endl; } } else { m_blockSize = tileSize; } } #if 0 void ossimNitfWriter::addStandardTags() { if(!theInputConnection) { return; } // commenting this out for now. For some reason the pixels // are off when I add this tag. I checked the parsing and it // appears to be the correct length??? So, I am not sure // why we are off when reading the output back in. // // first lets do the projection tag. I REALLY need to add // parameter support soon or this tag is useless. // ossimKeywordlist kwl; theInputConnection->getImageGeometry(kwl); ossimRefPtr proj = ossimProjectionFactoryRegistry::instance()->createProjection(kwl); ossimNitfNameConversionTables table; ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, proj.get()); ossimNitfTagInformation tagInfo; if(mapProj) { if(!PTR_CAST(ossimUtmProjection, mapProj)) { ossimRefPtr parameterTag = new ossimNitfProjectionParameterTag; ossimString nitfCode = table.convertMapProjectionNameToNitfCode(proj->getClassName()); ossimString nitfName = table.convertNitfCodeToNitfProjectionName(nitfCode); parameterTag->setName(nitfName); parameterTag->setCode(nitfCode); parameterTag->setFalseX(mapProj->getFalseEasting()); parameterTag->setFalseY(mapProj->getFalseNorthing()); tagInfo.setTagData(parameterTag.get()); m_imageHeader->addTag(tagInfo); } } } #endif bool ossimNitfWriter::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimNitfWriterBase::saveState(kwl, prefix); } bool ossimNitfWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimNitfWriterBase::loadState(kwl, prefix); } ossimNitfImageHeaderV2_1 *ossimNitfWriter::getImageHeader() { return m_imageHeader.get(); } ossimNitfFileHeaderV2_1 *ossimNitfWriter::getFileHeader() { return m_fileHeader.get(); } void ossimNitfWriter::addDataExtensionSegment(const ossimNitfDataExtensionSegmentV2_1& des, bool allowTreOverflow) { if (allowTreOverflow == false) { ossimRefPtr pId = des.getProperty(ossimNitfDataExtensionSegmentV2_1::DESID_KW); if ( !pId.valid() || pId->valueToString() == "TRE_OVERFLOW" || pId->valueToString() == "REGISTERED EXTENSIONS" || pId->valueToString() == "CONTROLLED EXTENSIONS") { return; } } m_dataExtensionSegments.push_back(des); } void ossimNitfWriter::takeOverflowTags(bool useFileHeader, bool userDefinedTags) { ossimString itemIndex; std::vector overflowTags; const ossim_uint32 potentialDesIndex = m_dataExtensionSegments.size() + 1; if (useFileHeader) { m_fileHeader->takeOverflowTags(overflowTags, potentialDesIndex, userDefinedTags); itemIndex = "0"; } else { m_imageHeader->takeOverflowTags(overflowTags, potentialDesIndex, userDefinedTags); itemIndex = "1"; } if (overflowTags.empty() == false) { ossimNitfDataExtensionSegmentV2_1 des; ossimRefPtr pDe = new ossimStringProperty(ossimNitfDataExtensionSegmentV2_1::DE_KW, "DE"); des.setProperty(pDe); ossimRefPtr pId = new ossimStringProperty(ossimNitfDataExtensionSegmentV2_1::DESID_KW, "TRE_OVERFLOW"); des.setProperty(pId); ossimRefPtr pVersion = new ossimStringProperty(ossimNitfDataExtensionSegmentV2_1::DESVER_KW, "1"); des.setProperty(pVersion); ossimRefPtr pOverflow = new ossimStringProperty(ossimNitfDataExtensionSegmentV2_1::DESOFLW_KW, overflowTags[0].getTagType()); des.setProperty(pOverflow); ossimRefPtr pItem = new ossimStringProperty(ossimNitfDataExtensionSegmentV2_1::DESITEM_KW, itemIndex); des.setProperty(pItem); des.setTagList(overflowTags); addDataExtensionSegment(des, true); } } ossim-Miami-2.9.1/src/imaging/ossimNitfWriterBase.cpp000066400000000000000000000347021352751253100225720ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: OSSIM nitf writer base class to hold methods common to // all nitf writers. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const char ENABLE_BLOCKA_KW[] = "enable_blocka_tag"; static const char ENABLE_RPCB_KW[] = "enable_rpcb_tag"; static const char ENABLE_GEOLOB_KW[] = "enable_geolob_tag"; RTTI_DEF1(ossimNitfWriterBase, "ossimNitfWriterBase", ossimImageFileWriter) static ossimTrace traceDebug(ossimString("ossimNitfWriterBase:debug")); ossimNitfWriterBase::ossimNitfWriterBase() : ossimImageFileWriter(), theEnableRpcbTagFlag(false), theEnableBlockaTagFlag(true), theEnableGeolobTagFlag(true) { } ossimNitfWriterBase::ossimNitfWriterBase(const ossimFilename& filename, ossimImageSource* inputSource) : ossimImageFileWriter(filename, inputSource, 0), theEnableRpcbTagFlag(false), theEnableBlockaTagFlag(true), theEnableGeolobTagFlag(true) { } ossimNitfWriterBase::~ossimNitfWriterBase() { } void ossimNitfWriterBase::setProperty(ossimRefPtr property) { if(property.valid()) { ossimString name = property->getName(); if (name == ENABLE_RPCB_KW) { theEnableRpcbTagFlag = property->valueToString().toBool(); } else if (name == ENABLE_BLOCKA_KW) { theEnableBlockaTagFlag = property->valueToString().toBool(); } else if (name == ENABLE_GEOLOB_KW) { theEnableGeolobTagFlag = property->valueToString().toBool(); } else { ossimImageFileWriter::setProperty(property); } } } ossimRefPtr ossimNitfWriterBase::getProperty( const ossimString& name)const { ossimRefPtr result = 0; if(name == ENABLE_BLOCKA_KW) { result = new ossimBooleanProperty(name, theEnableBlockaTagFlag); } else if (name == ENABLE_GEOLOB_KW) { result = new ossimBooleanProperty(name, theEnableGeolobTagFlag); } else if(name == ENABLE_RPCB_KW) { result = new ossimBooleanProperty(name, theEnableRpcbTagFlag); } else { result = ossimImageFileWriter::getProperty(name); } return result; } void ossimNitfWriterBase::getPropertyNames( std::vector& propertyNames)const { ossimImageFileWriter::getPropertyNames(propertyNames); propertyNames.push_back(ENABLE_BLOCKA_KW); propertyNames.push_back(ENABLE_GEOLOB_KW); propertyNames.push_back(ENABLE_RPCB_KW); } bool ossimNitfWriterBase::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, ENABLE_BLOCKA_KW, theEnableBlockaTagFlag, true); kwl.add(prefix, ENABLE_GEOLOB_KW, theEnableGeolobTagFlag, true); kwl.add(prefix, ENABLE_RPCB_KW, theEnableRpcbTagFlag, true); return ossimImageFileWriter::saveState(kwl, prefix); } bool ossimNitfWriterBase::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Look for the rpcb enable flag keyword. // Look for the blocka enable flag keyword. const char* lookup = kwl.find(prefix, ENABLE_BLOCKA_KW); if(lookup) { ossimString os = lookup; theEnableBlockaTagFlag = os.toBool(); } // Look for the geolob enable flag keyword. lookup = kwl.find(prefix, ENABLE_GEOLOB_KW); if(lookup) { ossimString os = lookup; theEnableGeolobTagFlag = os.toBool(); } lookup = kwl.find(prefix, ENABLE_RPCB_KW); if(lookup) { ossimString os = lookup; theEnableRpcbTagFlag = os.toBool(); } return ossimImageFileWriter::loadState(kwl, prefix); } void ossimNitfWriterBase::writeGeometry(ossimNitfImageHeaderV2_X* hdr, ossimImageSourceSequencer* seq) { if (hdr && seq) { ossimRefPtr geom = theInputConnection->getImageGeometry(); ossimKeywordlist kwl; if (geom.valid()&&geom->hasProjection()) { // Get the requested bounding rectangles. ossimIrect rect = seq->getBoundingRect(); // See if it's a map projection; else, a sensor model. ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, geom->getProjection()); if (mapProj) { // Use map info to get the corners. ossimMapProjectionInfo mapInfo(mapProj, rect); mapInfo.setPixelType(OSSIM_PIXEL_IS_AREA); // See if it's utm. ossimUtmProjection* utmProj = PTR_CAST(ossimUtmProjection, mapProj); if(utmProj) { ossimDpt ul = mapInfo.ulEastingNorthingPt(); ossimDpt ur = mapInfo.urEastingNorthingPt(); ossimDpt lr = mapInfo.lrEastingNorthingPt(); ossimDpt ll = mapInfo.llEastingNorthingPt(); if(utmProj->getHemisphere() == 'N') { hdr->setUtmNorth(utmProj->getZone(), ul, ur, lr, ll); } else { hdr->setUtmSouth(utmProj->getZone(), ul, ur, lr, ll); } } else { ossimGpt ul = mapInfo.ulGroundPt(); ossimGpt ur = mapInfo.urGroundPt(); ossimGpt lr = mapInfo.lrGroundPt(); ossimGpt ll = mapInfo.llGroundPt(); hdr->setGeographicLocationDms(ul, ur, lr, ll); } if (theEnableBlockaTagFlag) { addBlockaTag(mapInfo, hdr); } if ( theEnableGeolobTagFlag ) { addGeolobTag( mapInfo, hdr ); } } else { ossimGpt ul, ur, lr, ll; bool status = geom->getCornerGpts(ul, ur, lr, ll); if (status) { hdr->setGeographicLocationDms(ul, ur, lr, ll); } } if (theEnableRpcbTagFlag) { addRpcbTag(rect, geom->getProjection(), hdr); } } // matches: if (proj.valid()) } // matches: if (hdr && seq) } void ossimNitfWriterBase::addBlockaTag(ossimMapProjectionInfo& mapInfo, ossimNitfImageHeaderV2_X* hdr) { if (hdr) { // Capture the current pixel type. ossimPixelType originalPixelType = mapInfo.getPixelType(); // This tag wants corners as area: mapInfo.setPixelType(OSSIM_PIXEL_IS_AREA); // Stuff the blocka tag which has six digit precision. ossimRefPtr blockaTag = new ossimNitfBlockaTag(); // Set the block number. blockaTag->setBlockInstance(1); // Set the number of lines. blockaTag->setLLines(mapInfo.linesPerImage()); // Set first row, first column. blockaTag->setFrfcLoc(ossimDpt(mapInfo.ulGroundPt())); // Set first row, last column. blockaTag->setFrlcLoc(ossimDpt(mapInfo.urGroundPt())); // Set last row, last column. blockaTag->setLrlcLoc(ossimDpt(mapInfo.lrGroundPt())); // Set last row, first column. blockaTag->setLrfcLoc(ossimDpt(mapInfo.llGroundPt())); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfWriterBase::addBlockaTag DEBUG:" << "\nBLOCKA Tag:" << *((ossimObject*)(blockaTag.get())) << std::endl; } // Add the tag to the header. ossimRefPtr blockaTagRp = blockaTag.get(); ossimNitfTagInformation blockaTagInfo(blockaTagRp); hdr->addTag(blockaTagInfo); // Reset the pixel type to original value mapInfo.setPixelType(originalPixelType); } // matches: if (hdr) } void ossimNitfWriterBase::addGeolobTag(ossimMapProjectionInfo& mapInfo, ossimNitfImageHeaderV2_X* hdr) { if ( hdr && mapInfo.getProjection() ) { if ( mapInfo.getProjection()->isGeographic() == true ) { // This tag wants corners as area: mapInfo.setPixelType(OSSIM_PIXEL_IS_AREA); // Get the scale: ossimDpt gsd = mapInfo.getDecimalDegreesPerPixel(); if ( (gsd.hasNans() == false) && (gsd.x > 0.0) && (gsd.y > 0.0) ) { ossimGpt tie = mapInfo.ulGroundPt(); if ( tie.hasNans() == false ) { if ( (tie.lat <= 90.0) && (tie.lon >= -180.0) ) { ossimRefPtr geolobTag = new ossimNitfGeolobTag(); geolobTag->setDegreesPerPixelLon( gsd.x ); geolobTag->setDegreesPerPixelLat( gsd.y ); geolobTag->setLso( tie.lon ); // Origin Longitude geolobTag->setPso( tie.lat ); // Origin Latitude // Add the tag to the header. ossimRefPtr geolobTagRp = geolobTag.get(); ossimNitfTagInformation geolobTagInfo(geolobTagRp); hdr->addTag(geolobTagInfo); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfWriterBase::addGeolobTag DEBUG:" << "\nAdded GEOLOB Tag:\n" << *(geolobTag.get()) << "\n"; } } } } } } } void ossimNitfWriterBase::addRpcbTag(const ossimIrect& rect, ossimProjection* proj, ossimNitfImageHeaderV2_X* hdr) { if (proj && hdr) { bool useElevation = false; if (PTR_CAST(ossimMapProjection, proj)) { // If we're already map projected turn the elevation off. useElevation = false; } // Make an rpc solver. ossimRefPtr rs = new ossimRpcSolver(useElevation); // Compute the coefficients. rs->solveCoefficients(ossimDrect(rect), proj, 64, 64); // Add the tag. ossimRefPtr tag = rs->getNitfRpcBTag(); ossimNitfTagInformation tagInfo(tag); hdr->addTag(tagInfo); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfWriterBase::addRpcbTag DEBUG:" << "\nRPCB Tag:" << *((ossimObject*)(tag.get())) << "\nProjection:\n"; proj->print(ossimNotify(ossimNotifyLevel_DEBUG)); ossimNotify(ossimNotifyLevel_DEBUG) << "\nRect: " << rect << std::endl; } } // matches: if (proj && hdr) } void ossimNitfWriterBase::setComplexityLevel(std::streamoff endPosition, ossimNitfFileHeaderV2_X* hdr) { if (hdr) { //--- // See MIL-STD-2500C, Table A-10: // // Lots of rules here, but for now we will key off of file size. //--- const std::streamoff MB = 1024 * 1024; const std::streamoff MB50 = 50 * MB; const std::streamoff GIG = 1000 * MB; const std::streamoff GIG2 = 2 * GIG; ossimString complexity = "03"; // Less than 50 mb. if ( (endPosition >= MB50) && (endPosition < GIG) ) { complexity = "05"; } else if ( (endPosition >= GIG) && (endPosition < GIG2) ) { complexity = "06"; } else if (endPosition >= GIG2) { complexity = "07"; } hdr->setComplexityLevel(complexity); } } // Alternate calculation option for complexity. This seems to match more test data. void ossimNitfWriterBase::setComplexityLevel(ossimNitfFileHeaderV2_X* hdr, ossim_uint64 width, ossim_uint64 height) { if (hdr) { ossim_uint64 max = (width > height) ? width : height; ossimString complexity = "03"; if (max > 65536) complexity = "07"; else if (max > 8192) complexity = "06"; else if (max > 2048) complexity = "05"; hdr->setComplexityLevel(complexity); } } ossimString ossimNitfWriterBase::getExtension() const { return ossimString("ntf"); } void ossimNitfWriterBase::addRegisteredTag(ossimRefPtr /* registeredTag */) { } void ossimNitfWriterBase::addRegisteredTag(ossimRefPtr /* registeredTag */, bool /* unique */) { } void ossimNitfWriterBase::addRegisteredTag(ossimRefPtr /* registeredTag */, bool /* unique */, const ossim_uint32& /* ownerIndex */, const ossimString& /* tagType */) { } void ossimNitfWriterBase::setFileHeaderV2_1(ossimRefPtr, bool /* preferSource */) { } void ossimNitfWriterBase::setImageHeaderV2_1(ossimRefPtr, bool /* preferSource */) { } void ossimNitfWriterBase::initializeDefaultsFromConfigFile( ossimNitfFileHeaderV2_X* fileHdr, ossimNitfImageHeaderV2_X* imgHdr ) { // Look in prefs for site configuration file: const char* lookup = ossimPreferences::instance()-> findPreference("nitf_writer.site_configuration_file"); if ( lookup && fileHdr && imgHdr ) { ossimKeywordlist kwl; if ( kwl.addFile( lookup ) ) { fileHdr->loadState( kwl, "nitf.file." ); imgHdr->loadState( kwl, "nitf.image." ); } } } ossim-Miami-2.9.1/src/imaging/ossimNormalizedRemapTable.cpp000066400000000000000000000015531352751253100237410ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class definition for NormalizedRemapTable. // //******************************************************************* // $Id: ossimNormalizedRemapTable.cpp 15496 2009-09-29 11:36:56Z dburken $ #include ossimNormalizedRemapTable::ossimNormalizedRemapTable() { } ossimNormalizedRemapTable::~ossimNormalizedRemapTable() { } // Private copy constructor. ossimNormalizedRemapTable::ossimNormalizedRemapTable( const ossimNormalizedRemapTable&) {} // Private assignment operator. ossimNormalizedRemapTable& ossimNormalizedRemapTable::operator=( const ossimNormalizedRemapTable&) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimNormalizedS16RemapTable.cpp000066400000000000000000000027671352751253100242430ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class definition for ossimNormalizedS16RemapTable. // //******************************************************************* // $Id: ossimNormalizedS16RemapTable.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include ossim_float64 ossimNormalizedS16RemapTable::theTable[TABLE_ENTRIES]; bool ossimNormalizedS16RemapTable::theTableIsInitialized = false; ossimNormalizedS16RemapTable::ossimNormalizedS16RemapTable() : ossimNormalizedRemapTable() { if (!theTableIsInitialized) { const ossim_int32 ENTRIES = getEntries(); const ossim_float64 DENOMINATOR = getNormalizer(); //--- // Initialize the remap table. // // Specialized for elevation, make -32768 and -32767 map to 0 since // DTED NULL is -32767. // // NOTE: Zero will always remap back to -32768 with this hack. This // could cause issues on writers that use pixFromNorm(). (drb) //--- theTable[0] = 0.0; // Index zero always for null. theTable[1] = 0.0; // Specialized for DTED. for (ossim_int32 i = 2; i < ENTRIES; ++i) { theTable[i] = static_cast(i)/DENOMINATOR; } theTableIsInitialized = true; } } ossimNormalizedS16RemapTable::~ossimNormalizedS16RemapTable() {} ossim-Miami-2.9.1/src/imaging/ossimNormalizedU11RemapTable.cpp000066400000000000000000000022751352751253100242320ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class definition for ossimNormalizedU11RemapTable. // //******************************************************************* // $Id: ossimNormalizedU11RemapTable.cpp 15743 2009-10-17 13:00:45Z dburken $ #include ossim_float64 ossimNormalizedU11RemapTable::theTable[TABLE_ENTRIES]; bool ossimNormalizedU11RemapTable::theTableIsInitialized = false; ossimNormalizedU11RemapTable::ossimNormalizedU11RemapTable() : ossimNormalizedRemapTable() { if (!theTableIsInitialized) { const ossim_int32 ENTRIES = getEntries(); const ossim_float64 DENOMINATOR = getNormalizer(); //--- // Initialize the remap table. //--- theTable[0] = 0.0; // Index zero always for null. for (ossim_int32 i = 1; i < ENTRIES; ++i) { theTable[i] = static_cast(i)/DENOMINATOR; } theTableIsInitialized = true; } } ossimNormalizedU11RemapTable::~ossimNormalizedU11RemapTable() {} ossim-Miami-2.9.1/src/imaging/ossimNormalizedU12RemapTable.cpp000066400000000000000000000022751352751253100242330ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class definition for ossimNormalizedU12RemapTable. // //******************************************************************* // $Id: ossimNormalizedU12RemapTable.cpp 15743 2009-10-17 13:00:45Z dburken $ #include ossim_float64 ossimNormalizedU12RemapTable::theTable[TABLE_ENTRIES]; bool ossimNormalizedU12RemapTable::theTableIsInitialized = false; ossimNormalizedU12RemapTable::ossimNormalizedU12RemapTable() : ossimNormalizedRemapTable() { if (!theTableIsInitialized) { const ossim_int32 ENTRIES = getEntries(); const ossim_float64 DENOMINATOR = getNormalizer(); //--- // Initialize the remap table. //--- theTable[0] = 0.0; // Index zero always for null. for (ossim_int32 i = 1; i < ENTRIES; ++i) { theTable[i] = static_cast(i)/DENOMINATOR; } theTableIsInitialized = true; } } ossimNormalizedU12RemapTable::~ossimNormalizedU12RemapTable() {} ossim-Miami-2.9.1/src/imaging/ossimNormalizedU13RemapTable.cpp000066400000000000000000000022751352751253100242340ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class definition for ossimNormalizedU13RemapTable. // //******************************************************************* // $Id: ossimNormalizedU13RemapTable.cpp 15743 2009-10-17 13:00:45Z dburken $ #include ossim_float64 ossimNormalizedU13RemapTable::theTable[TABLE_ENTRIES]; bool ossimNormalizedU13RemapTable::theTableIsInitialized = false; ossimNormalizedU13RemapTable::ossimNormalizedU13RemapTable() : ossimNormalizedRemapTable() { if (!theTableIsInitialized) { const ossim_int32 ENTRIES = getEntries(); const ossim_float64 DENOMINATOR = getNormalizer(); //--- // Initialize the remap table. //--- theTable[0] = 0.0; // Index zero always for null. for (ossim_int32 i = 1; i < ENTRIES; ++i) { theTable[i] = static_cast(i)/DENOMINATOR; } theTableIsInitialized = true; } } ossimNormalizedU13RemapTable::~ossimNormalizedU13RemapTable() {} ossim-Miami-2.9.1/src/imaging/ossimNormalizedU14RemapTable.cpp000066400000000000000000000022751352751253100242350ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class definition for ossimNormalizedU14RemapTable. // //******************************************************************* // $Id: ossimNormalizedU14RemapTable.cpp 15743 2009-10-17 13:00:45Z dburken $ #include ossim_float64 ossimNormalizedU14RemapTable::theTable[TABLE_ENTRIES]; bool ossimNormalizedU14RemapTable::theTableIsInitialized = false; ossimNormalizedU14RemapTable::ossimNormalizedU14RemapTable() : ossimNormalizedRemapTable() { if (!theTableIsInitialized) { const ossim_int32 ENTRIES = getEntries(); const ossim_float64 DENOMINATOR = getNormalizer(); //--- // Initialize the remap table. //--- theTable[0] = 0.0; // Index zero always for null. for (ossim_int32 i = 1; i < ENTRIES; ++i) { theTable[i] = static_cast(i)/DENOMINATOR; } theTableIsInitialized = true; } } ossimNormalizedU14RemapTable::~ossimNormalizedU14RemapTable() {} ossim-Miami-2.9.1/src/imaging/ossimNormalizedU15RemapTable.cpp000066400000000000000000000022751352751253100242360ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class definition for ossimNormalizedU15RemapTable. // //******************************************************************* // $Id: ossimNormalizedU15RemapTable.cpp 15743 2009-10-17 13:00:45Z dburken $ #include ossim_float64 ossimNormalizedU15RemapTable::theTable[TABLE_ENTRIES]; bool ossimNormalizedU15RemapTable::theTableIsInitialized = false; ossimNormalizedU15RemapTable::ossimNormalizedU15RemapTable() : ossimNormalizedRemapTable() { if (!theTableIsInitialized) { const ossim_int32 ENTRIES = getEntries(); const ossim_float64 DENOMINATOR = getNormalizer(); //--- // Initialize the remap table. //--- theTable[0] = 0.0; // Index zero always for null. for (ossim_int32 i = 1; i < ENTRIES; ++i) { theTable[i] = static_cast(i)/DENOMINATOR; } theTableIsInitialized = true; } } ossimNormalizedU15RemapTable::~ossimNormalizedU15RemapTable() {} ossim-Miami-2.9.1/src/imaging/ossimNormalizedU16RemapTable.cpp000066400000000000000000000023001352751253100242240ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class definition for ossimNormalizedU16RemapTable. // //******************************************************************* // $Id: ossimNormalizedU16RemapTable.cpp 15743 2009-10-17 13:00:45Z dburken $ #include ossim_float64 ossimNormalizedU16RemapTable::theTable[TABLE_ENTRIES]; bool ossimNormalizedU16RemapTable::theTableIsInitialized = false; ossimNormalizedU16RemapTable::ossimNormalizedU16RemapTable() : ossimNormalizedRemapTable() { if (!theTableIsInitialized) { const ossim_int32 ENTRIES = getEntries(); const ossim_float64 DENOMINATOR = getNormalizer(); //--- // Initialize the remap table. //--- theTable[0] = 0.0; // Index zero always for null. for (ossim_int32 i = 1; i < ENTRIES; ++i) { theTable[i] = static_cast(i)/DENOMINATOR; } theTableIsInitialized = true; } } ossimNormalizedU16RemapTable::~ossimNormalizedU16RemapTable() {} ossim-Miami-2.9.1/src/imaging/ossimNormalizedU8RemapTable.cpp000066400000000000000000000022651352751253100241570ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class definition for ossimNormalizedU8RemapTable. // //******************************************************************* // $Id: ossimNormalizedU8RemapTable.cpp 15743 2009-10-17 13:00:45Z dburken $ #include ossim_float64 ossimNormalizedU8RemapTable::theTable[TABLE_ENTRIES]; bool ossimNormalizedU8RemapTable::theTableIsInitialized = false; ossimNormalizedU8RemapTable::ossimNormalizedU8RemapTable() : ossimNormalizedRemapTable() { if (!theTableIsInitialized) { const ossim_int32 ENTRIES = getEntries(); const ossim_float64 DENOMINATOR = getNormalizer(); //--- // Initialize the remap table. //--- theTable[0] = 0.0; // Index zero always for null. for (ossim_int32 i = 1; i < ENTRIES; ++i) { theTable[i] = static_cast(i)/DENOMINATOR; } theTableIsInitialized = true; } } ossimNormalizedU8RemapTable::~ossimNormalizedU8RemapTable() {} ossim-Miami-2.9.1/src/imaging/ossimNullPixelFlip.cpp000066400000000000000000000123301352751253100224220ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // //******************************************************************* // $Id$ #include #include RTTI_DEF1(ossimNullPixelFlip, "ossimNullPixelFlip", ossimImageSourceFilter); ossimNullPixelFlip::ossimNullPixelFlip(ClipMode clipMode, ReplacementType replacementType) :m_clipMode(clipMode), m_replacementType(replacementType) { } void ossimNullPixelFlip::initialize() { } ossimRefPtr ossimNullPixelFlip::getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel) { ossimRefPtr result = ossimImageSourceFilter::getTile(tile_rect, resLevel); if(!isSourceEnabled()||!result.valid()) { return result.get(); } ossimDataObjectStatus status = result->getDataObjectStatus(); if((status == OSSIM_FULL)|| (status == OSSIM_NULL)) { return result.get(); } // Call the appropriate load method. switch (result->getScalarType()) { case OSSIM_UCHAR: { flipPixels(ossim_uint8(0), result.get(), resLevel); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { flipPixels(ossim_uint16(0), result.get(), resLevel); break; } case OSSIM_SSHORT16: { flipPixels(ossim_sint16(0), result.get(), resLevel); break; } case OSSIM_UINT32: { flipPixels(ossim_uint32(0), result.get(), resLevel); break; } case OSSIM_SINT32: { flipPixels(ossim_sint32(0), result.get(), resLevel); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { flipPixels(ossim_float32(0), result.get(), resLevel); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { flipPixels(ossim_float64(0), result.get(), resLevel); break; } case OSSIM_SCALAR_UNKNOWN: default: { // ossimNotify(ossimNotifyLevel_WARN) // << "ossimPixelFlipper::getTile Unsupported scalar type!" << endl; break; } } return result; } template void ossimNullPixelFlip::flipPixels(T /* dummy */, ossimImageData* inputTile, ossim_uint32 resLevel) { if (!inputTile) return; ossimDataObjectStatus status = inputTile->getDataObjectStatus(); ossimIrect rect = inputTile->getImageRectangle(); ossimIrect imageBounds = getBoundingRect(resLevel); ossimIrect clipRect; if(!rect.intersects(imageBounds)) { return; } clipRect = rect.clipToRect(imageBounds); if((status == OSSIM_EMPTY)|| (status == OSSIM_PARTIAL)) { if(!rect.completely_within(imageBounds)) { ossim_uint32 bands = inputTile->getNumberOfBands(); ossimIpt origin = clipRect.ul() - rect.ul(); ossim_uint32 bandIdx = 0; ossim_uint32 inputW = inputTile->getWidth(); ossim_uint32 originOffset = origin.y*inputW + origin.x; ossim_uint32 w = clipRect.width(); ossim_uint32 h = clipRect.height(); ossim_uint32 x = 0; ossim_uint32 y = 0; for(bandIdx = 0; bandIdx < bands; ++bandIdx) { T* bandPtr = static_cast(inputTile->getBuf(bandIdx)) + originOffset; T nullValue = static_cast(inputTile->getNullPix(bandIdx)); T replaceValue = (m_replacementType==ReplacementType_MINPIX?static_cast(inputTile->getMinPix(bandIdx)): static_cast(inputTile->getMaxPix(bandIdx))); for(y = 0; y < h; ++y) { for(x = 0; x < w; ++x) { if(bandPtr[x] == nullValue) { bandPtr[x] = replaceValue; } } bandPtr += inputW; } } } else { ossim_uint32 bands = inputTile->getNumberOfBands(); ossim_uint32 bandIdx = 0; ossim_uint32 size = inputTile->getWidth()*inputTile->getHeight(); for(bandIdx = 0; bandIdx < bands; ++bandIdx) { T* bandPtr = static_cast(inputTile->getBuf(bandIdx)); T nullValue = static_cast(inputTile->getNullPix(bandIdx)); T replaceValue = (m_replacementType==ReplacementType_MINPIX?static_cast(inputTile->getMinPix(bandIdx)): static_cast(inputTile->getMaxPix(bandIdx))); ossim_uint32 idx = 0; for(idx = 0; idx < size;++idx) { if((*bandPtr) == nullValue) { (*bandPtr) = replaceValue; } ++bandPtr; } } inputTile->setDataObjectStatus(OSSIM_FULL); } } } ossim-Miami-2.9.1/src/imaging/ossimOrthoImageMosaic.cpp000066400000000000000000000343401352751253100230720ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimOrthoImageMosaic.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug ("ossimOrthoImageMosaic:debug"); RTTI_DEF1(ossimOrthoImageMosaic, "ossimOrthoImageMosaic", ossimImageMosaic); //************************************************************************************************** // //************************************************************************************************** ossimOrthoImageMosaic::ossimOrthoImageMosaic() :ossimImageMosaic() { m_Delta.makeNan(); m_UpperLeftTie.makeNan(); } //************************************************************************************************** // //************************************************************************************************** ossimOrthoImageMosaic::ossimOrthoImageMosaic(ossimConnectableObject::ConnectableObjectList& inputSources) :ossimImageMosaic(inputSources) { m_Delta.makeNan(); m_UpperLeftTie.makeNan(); } //************************************************************************************************** // //************************************************************************************************** ossimOrthoImageMosaic::~ossimOrthoImageMosaic() { } //************************************************************************************************** // //************************************************************************************************** ossim_uint32 ossimOrthoImageMosaic::getNumberOfOverlappingImages(const ossimIrect& rect, ossim_uint32 resLevel)const { ossim_uint32 result = 0; for(ossim_uint32 i = 0; i < m_InputTiePoints.size(); ++i) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(i)); if(interface&& !m_InputTiePoints[i].hasNans()) { ossimIrect tempRect = getRelativeRect(i, resLevel); if(!tempRect.hasNans()) { if(tempRect.intersects(rect)) { ++result; } } } } return 0; } //************************************************************************************************** // //************************************************************************************************** void ossimOrthoImageMosaic::getOverlappingImages(std::vector& result, const ossimIrect& rect, ossim_uint32 resLevel)const { result.clear(); for(ossim_uint32 i = 0; i < m_InputTiePoints.size(); ++i) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(i)); if(interface&& !m_InputTiePoints[i].hasNans()) { ossimIrect tempRect = getRelativeRect(i, resLevel); if(!tempRect.hasNans()) { if(tempRect.intersects(rect)) { result.push_back(i); } } } } } //************************************************************************************************** // Returns the image geometry for the complete mosaic //************************************************************************************************** ossimRefPtr ossimOrthoImageMosaic::getImageGeometry() { if ( !m_Geometry.valid() ) { // The geometry (projection) associated with this mosaic is necessarily the same for all // single-image objects feeding into this combiner, So we will copy the first image source's // geometry, and modify our copy to reflect the mosaic-specific items. ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { ossimRefPtr inputGeom = interface->getImageGeometry(); if ( inputGeom.valid() ) { m_Geometry = new ossimImageGeometry(*inputGeom); updateGeometry(); } } } return m_Geometry; } //************************************************************************************************** //! If this object is maintaining an ossimImageGeometry, this method needs to be called after //! each time the contents of the mosaic changes. //************************************************************************************************** void ossimOrthoImageMosaic::updateGeometry() { if (!m_Geometry.valid()) return; ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, m_Geometry->getProjection()); if (mapProj) { if(m_Units == "degrees") { mapProj->setDecimalDegreesPerPixel(m_Delta); mapProj->setUlGpt(ossimGpt(m_UpperLeftTie.y, m_UpperLeftTie.x, 0.0, mapProj->origin().datum())); } else if(m_Units == "meters") { mapProj->setMetersPerPixel(m_Delta); mapProj->setUlEastingNorthing(m_UpperLeftTie); } } } //************************************************************************************************** // //************************************************************************************************** ossimIrect ossimOrthoImageMosaic::getBoundingRect(ossim_uint32 resLevel) const { ossimDpt decimation; decimation.makeNan(); ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getDecimationFactor(resLevel, decimation); } if(decimation.hasNans()) { return m_BoundingRect; } return m_BoundingRect*decimation; } //************************************************************************************************** // //************************************************************************************************** void ossimOrthoImageMosaic::initialize() { m_InputTiePoints.clear(); m_Delta.makeNan(); m_UpperLeftTie.makeNan(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoImageMosaic::initialize() DEBUG: Entered..." << "Number of inputs = " << getNumberOfInputs() << std::endl; } if(getNumberOfInputs()) { m_InputTiePoints.resize(getNumberOfInputs()); for(ossim_uint32 i = 0; i < getNumberOfInputs(); ++i) { ossimImageSource *interface = PTR_CAST(ossimImageSource, getInput(i)); m_InputTiePoints[i].makeNan(); if(interface) { ossimRefPtr geom = interface->getImageGeometry(); if( geom.valid() ) { const ossimMapProjection* mapPrj = PTR_CAST(ossimMapProjection, geom->getProjection()); if(mapPrj) { if(!mapPrj->isGeographic()) { m_Units = "meters"; m_Delta = mapPrj->getMetersPerPixel(); } else { m_Units = "degrees"; m_Delta = mapPrj->getDecimalDegreesPerPixel(); } if(m_Units == "degrees") { m_InputTiePoints[i].x = mapPrj->getUlGpt().lond(); m_InputTiePoints[i].y = mapPrj->getUlGpt().latd(); } else if(m_Units == "meters") { m_InputTiePoints[i].x = mapPrj->getUlEastingNorthing().x;; m_InputTiePoints[i].y = mapPrj->getUlEastingNorthing().y; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "tie points for input " << i << " = " << m_InputTiePoints[i] << std::endl; } } } if(!m_InputTiePoints[i].hasNans()) { if(m_UpperLeftTie.hasNans()) { m_UpperLeftTie = m_InputTiePoints[i]; } else if(!m_InputTiePoints[i].hasNans()) { if(m_Units == "meters") { m_UpperLeftTie.x = std::min(m_UpperLeftTie.x, m_InputTiePoints[i].x); m_UpperLeftTie.y = std::max(m_UpperLeftTie.y, m_InputTiePoints[i].y); } else { m_UpperLeftTie.lon = std::min(m_UpperLeftTie.lon, m_InputTiePoints[i].lon); m_UpperLeftTie.lat = std::max(m_UpperLeftTie.lat, m_InputTiePoints[i].lat); } } } } else { m_InputTiePoints[i].makeNan(); // CLOG << "Input " << i << " will not be used since no ortho information exists" << endl; } } } computeBoundingRect(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "m_UpperLeftTie = " << m_UpperLeftTie << std::endl << "delta per pixel = " << m_Delta << std::endl << "bounding rect = " << m_BoundingRect << std::endl; } ossimImageMosaic::initialize(); // Finally, update the geometry (if there was one already defined), to reflect the change in input updateGeometry(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoImageMosaic::initialize() DEBUG: Leaving..." << std::endl; } } //************************************************************************************************** // //************************************************************************************************** ossimRefPtr ossimOrthoImageMosaic::getNextTile(ossim_uint32& returnedIdx, const ossimIrect& origin, ossim_uint32 resLevel) { const char *MODULE="ossimOrthoImageMosaic::getNextTile"; ossim_uint32 size = getNumberOfInputs(); if(theCurrentIndex >= size) { return ossimRefPtr(); } ossimImageSource* temp = NULL; ossimRefPtr result; ossimDataObjectStatus status = OSSIM_NULL; do { temp = PTR_CAST(ossimImageSource, getInput(theCurrentIndex)); if(temp) { ossimIrect relRect = getRelativeRect(theCurrentIndex, resLevel); if(traceDebug()) { CLOG << "Rel rect for input " << theCurrentIndex << " = " << relRect << "\nRes level: " << resLevel << endl; } if(origin.intersects(relRect)) { // get the rect relative to the input rect // ossimIrect shiftedRect = origin + (ossimIpt(-relRect.ul().x, -relRect.ul().y)); // request that tile from the input space. result = temp->getTile(shiftedRect, resLevel); // now change the origin to the output origin. if (result.valid()) { result->setOrigin(origin.ul()); status = result->getDataObjectStatus(); if((status == OSSIM_NULL)||(status == OSSIM_EMPTY)) { result = NULL; } } } else { result = NULL; } } // Go to next source. ++theCurrentIndex; } while(!result.valid() && (theCurrentIndexgetBoundingRect(); result = inputRect; if(!inputRect.hasNans()) { ossimDpt shift = (m_InputTiePoints[index] - m_UpperLeftTie); shift.x/= m_Delta.x; shift.y/=-m_Delta.y; result = result + shift; if(!resLevel) { return result; } ossimDpt decimation; interface->getDecimationFactor(resLevel, decimation); if(!decimation.hasNans()) { result = result * decimation; } } } return result; } ossim-Miami-2.9.1/src/imaging/ossimOverviewBuilderBase.cpp000066400000000000000000000125171352751253100236120ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Interface class for overview builders. // //---------------------------------------------------------------------------- // $Id: ossimOverviewBuilderBase.cpp 21745 2012-09-16 15:21:53Z dburken $ #include #include #include #include #include RTTI_DEF3(ossimOverviewBuilderBase, "ossimOverviewBuilderBase", ossimSource, ossimProcessInterface, ossimConnectableObjectListener) static const std::string SCAN_FLOAT_DATA_KW = "overview_builder.scan_for_min_max_null_if_float"; ossimOverviewBuilderBase::ossimOverviewBuilderBase() : m_overviewStopDimension(0), m_histoMode(OSSIM_HISTO_MODE_UNKNOWN), m_bitMaskSpec(), m_imageHandler(0), m_originalBandList(0), m_maskWriter(0), m_maskFilter(0), m_outputFile(ossimFilename::NIL), m_scanForMinMax(false), m_scanForMinMaxNull(false), m_scanFloatData(false) { initializePreferenceSettings(); } ossimOverviewBuilderBase::~ossimOverviewBuilderBase() { m_imageHandler = 0; m_maskWriter = 0; m_maskFilter = 0; } bool ossimOverviewBuilderBase::setOutputWriter(ossimImageFileWriter* /* outputWriter */) { return false; } bool ossimOverviewBuilderBase::setInputSource(ossimImageHandler* imageSource) { bool result = false; if ( imageSource ) { if ( imageSource->getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { m_imageHandler = imageSource; // Check handler to see if it's filtering bands. if ( m_imageHandler->isBandSelector() ) { // Capture for finalize method. m_imageHandler->getOutputBandList( m_originalBandList ); // Set output list to input. m_imageHandler->setOutputToInputBandList(); } // This will set the flag to scan for min, max, nulls if needed. initializeScanOptions(); result = true; } } return result; } bool ossimOverviewBuilderBase::hasOverviewType(const ossimString& type) const { std::vector typeList; getTypeNameList(typeList); std::vector::const_iterator i = typeList.begin(); while ( i != typeList.end() ) { if ( (*i) == type ) { return true; } ++i; } return false; } ossim_uint32 ossimOverviewBuilderBase::getRequiredResLevels( const ossimImageHandler* ih) const { ossim_uint32 result = 0; if (ih) { // Note we always have one rset result = 1; ossim_uint32 largestImageDimension = ih->getNumberOfSamples(0) > ih->getNumberOfLines(0) ? ih->getNumberOfSamples(0) : ih->getNumberOfLines(0); while(largestImageDimension > m_overviewStopDimension) { largestImageDimension /= 2; ++result; } } return result; } ossim_uint32 ossimOverviewBuilderBase::getOverviewStopDimension() const { return m_overviewStopDimension; } void ossimOverviewBuilderBase::setOverviewStopDimension(ossim_uint32 dim) { m_overviewStopDimension = dim; } ossimHistogramMode ossimOverviewBuilderBase::getHistogramMode() const { return m_histoMode; } void ossimOverviewBuilderBase::setHistogramMode(ossimHistogramMode mode) { m_histoMode = mode; } void ossimOverviewBuilderBase::finalize() { if ( m_imageHandler.valid() && m_imageHandler->isBandSelector() && m_originalBandList.size() ) { m_imageHandler->setOutputBandList( m_originalBandList ); } } void ossimOverviewBuilderBase::setBitMaskSpec(const ossimKeywordlist& bit_mask_spec) { m_bitMaskSpec = bit_mask_spec; } void ossimOverviewBuilderBase::setScanForMinMax(bool flag) { m_scanForMinMax = flag; } bool ossimOverviewBuilderBase::getScanForMinMax() const { return m_scanForMinMax; } void ossimOverviewBuilderBase::setScanForMinMaxNull(bool flag) { m_scanForMinMaxNull = flag; } bool ossimOverviewBuilderBase::getScanForMinMaxNull() const { return m_scanForMinMaxNull; } void ossimOverviewBuilderBase::initializePreferenceSettings() { // Get the stop dimension from ossim preferences. const char* lookup = ossimPreferences::instance()-> findPreference(ossimKeywordNames::OVERVIEW_STOP_DIMENSION_KW); if (lookup) { m_overviewStopDimension = ossimString(lookup).toUInt32(); } if ( m_overviewStopDimension == 0 ) { // Use the smallest default tile size. ossimIpt tileSize; ossim::defaultTileSize(tileSize); m_overviewStopDimension = tileSize.x < tileSize.y ? tileSize.x : tileSize.y; } // Look for overview_builder.scan_for_min_max_null_if_float: lookup = ossimPreferences::instance()->findPreference(SCAN_FLOAT_DATA_KW.c_str()); if ( lookup ) { m_scanFloatData = ossimString(lookup).toBool(); } } void ossimOverviewBuilderBase::initializeScanOptions() { if ( m_scanFloatData && m_imageHandler.valid()) { ossimScalarType scalar = m_imageHandler->getOutputScalarType(); if ( ( scalar == OSSIM_FLOAT32 ) || ( scalar == OSSIM_FLOAT64 ) ) { setScanForMinMaxNull(true); } } } ossim-Miami-2.9.1/src/imaging/ossimOverviewBuilderFactory.cpp000066400000000000000000000032271352751253100243450ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // See top level LICENSE.txt file. // // Author: David Burken // // Description: Factory for overview builders. // //---------------------------------------------------------------------------- // $Id: ossimOverviewBuilderFactory.cpp 17709 2010-07-08 20:21:14Z dburken $ #include #include ossimOverviewBuilderFactory* ossimOverviewBuilderFactory::theInstance = 0; ossimOverviewBuilderFactory* ossimOverviewBuilderFactory::instance() { if ( !theInstance ) { theInstance = new ossimOverviewBuilderFactory(); } return theInstance; } ossimOverviewBuilderFactory::~ossimOverviewBuilderFactory() { theInstance = 0; } ossimOverviewBuilderBase* ossimOverviewBuilderFactory::createBuilder( const ossimString& typeName) const { ossimRefPtr result = new ossimTiffOverviewBuilder(); if ( result->hasOverviewType(typeName) == false ) { result = 0; } if ( result.get() ) { result->setOverviewType(typeName); } return result.release(); } void ossimOverviewBuilderFactory::getTypeNameList( std::vector& typeList) const { ossimRefPtr builder = new ossimTiffOverviewBuilder(); builder->getTypeNameList(typeList); } ossimOverviewBuilderFactory::ossimOverviewBuilderFactory() { } ossimOverviewBuilderFactory::ossimOverviewBuilderFactory( const ossimOverviewBuilderFactory& /* obj */) { } void ossimOverviewBuilderFactory::operator=( const ossimOverviewBuilderFactory& /* rhs */) { } ossim-Miami-2.9.1/src/imaging/ossimOverviewBuilderFactoryBase.cpp000066400000000000000000000022751352751253100251420ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // See top level LICENSE.txt file. // // Author: David Burken // // Description: The base for overview builder factories. // //---------------------------------------------------------------------------- // $Id: ossimOverviewBuilderFactoryBase.cpp 19187 2011-03-23 12:21:58Z gpotts $ #include #include ossimObject* ossimOverviewBuilderFactoryBase::createObject(const ossimString& typeName) const { return createBuilder(typeName); } ossimObject* ossimOverviewBuilderFactoryBase::createObject(const ossimKeywordlist& kwl, const char* prefix) const { ossimObject* result = 0; ossimString typeValue = kwl.find(prefix, "type"); if(!typeValue.empty()) { result = createObject(typeValue); if(result) { if(!result->loadState(kwl, prefix)) { delete result; result = 0; } } } return result; } ossimOverviewBuilderFactoryBase::ossimOverviewBuilderFactoryBase() { } ossimOverviewBuilderFactoryBase::~ossimOverviewBuilderFactoryBase() { } ossim-Miami-2.9.1/src/imaging/ossimOverviewBuilderFactoryRegistry.cpp000066400000000000000000000047761352751253100261100ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // See top level LICENSE.txt file. // // Author: David Burken // // Description: The factory registry for overview builders. // //---------------------------------------------------------------------------- // $Id: ossimOverviewBuilderFactoryRegistry.cpp 19907 2011-08-05 19:55:46Z dburken $ #include #include #include #include /* for std::find */ ossimOverviewBuilderFactoryRegistry* ossimOverviewBuilderFactoryRegistry::m_instance = 0; ossimOverviewBuilderFactoryRegistry* ossimOverviewBuilderFactoryRegistry::instance() { if ( m_instance == 0 ) { m_instance = new ossimOverviewBuilderFactoryRegistry(); ossimObjectFactoryRegistry::instance()->registerFactory(m_instance); } return m_instance; } ossimObject* ossimOverviewBuilderFactoryRegistry::createObject(const ossimString& typeName)const { return createObjectFromRegistry(typeName); } ossimObject* ossimOverviewBuilderFactoryRegistry::createObject(const ossimKeywordlist& kwl, const char* prefix)const { ossimRefPtr result = 0; ossimString type = kwl.find(prefix, "type"); if(!type.empty()) { result = createBuilder(type); if(result.valid()) { if(!result->loadState(kwl, prefix)) { result = 0; } } } return result.release(); } ossimOverviewBuilderBase* ossimOverviewBuilderFactoryRegistry::createBuilder( const ossimString& typeName) const { FactoryListType::const_iterator iter = m_factoryList.begin(); NativeReturnType* result = 0; while(iter != m_factoryList.end()) { result = (*iter)->createBuilder(typeName); if (result) { break; } ++iter; } return result; } void ossimOverviewBuilderFactoryRegistry::getTypeNameList(std::vector& typeList)const { getAllTypeNamesFromRegistry(typeList); } ossimOverviewBuilderFactoryRegistry::ossimOverviewBuilderFactoryRegistry() { m_instance = this; } ossimOverviewBuilderFactoryRegistry::ossimOverviewBuilderFactoryRegistry( const ossimOverviewBuilderFactoryRegistry& /* obj */ ) { m_instance = this; } void ossimOverviewBuilderFactoryRegistry::operator=( const ossimOverviewBuilderFactoryRegistry& /* rhs */ ) { } ossim-Miami-2.9.1/src/imaging/ossimOverviewSequencer.cpp000066400000000000000000000755261352751253100233740ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: Sequencer for building overview files. // //---------------------------------------------------------------------------- // $Id: ossimOverviewSequencer.cpp 23377 2015-06-17 18:03:05Z okramer $ #include #include #include #include #include #include #include #include #include #include #include using namespace std; #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimOverviewSequencer.cpp 23377 2015-06-17 18:03:05Z okramer $"; #endif static ossimTrace traceDebug("ossimOverviewSequencer:debug"); ossimOverviewSequencer::ossimOverviewSequencer() : ossimReferenced(), ossimErrorStatusInterface(), m_imageHandler(0), m_maskWriter(0), m_maskFilter(0), m_tile(0), m_areaOfInterest(), m_tileSize(OSSIM_DEFAULT_TILE_WIDTH, OSSIM_DEFAULT_TILE_HEIGHT), m_numberOfTilesHorizontal(0), m_numberOfTilesVertical(0), m_currentTileNumber(0), m_sourceResLevel(0), m_dirtyFlag(true), m_decimationFactor(2), m_resampleType(ossimFilterResampler::ossimFilterResampler_BOX), m_histogram(0), m_histoMode(OSSIM_HISTO_MODE_UNKNOWN), m_histoTileIndex(1), m_scanForMinMax(false), m_scanForMinMaxNull(false), m_minValues(0), m_maxValues(0), m_nulValues(0) { m_areaOfInterest.makeNan(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOverviewSequencer::ossimOverviewSequencer entered..." << "\nmpi rank: "<< ossimMpi::instance()->getRank() << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG)<< "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } } ossimOverviewSequencer::~ossimOverviewSequencer() { m_imageHandler = 0; m_maskFilter = 0; m_maskWriter = 0; m_tile = 0; m_histogram = 0; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOverviewSequencer::~ossimOverviewSequencer entered..." << "\nmpi rank: " << ossimMpi::instance()->getRank() << std::endl; } } ossim_uint32 ossimOverviewSequencer::getNumberOfTiles() const { return (m_numberOfTilesHorizontal*m_numberOfTilesVertical); } ossim_uint32 ossimOverviewSequencer::getNumberOfTilesHorizontal()const { return m_numberOfTilesHorizontal; } ossim_uint32 ossimOverviewSequencer::getNumberOfTilesVertical()const { return m_numberOfTilesVertical; } void ossimOverviewSequencer::getOutputImageRectangle(ossimIrect& rect) const { if (m_areaOfInterest.hasNans()) { rect.makeNan(); // not initialized... } else { ossim_int32 width = m_areaOfInterest.width() / m_decimationFactor; ossim_int32 height = m_areaOfInterest.height() / m_decimationFactor; //--- // NOTE: // This will add a sample or line if there is a remainder like: // 1025 / 2 = 512 will then become 513. It will be up to the resample // tile method to fill the extra sample correctly. //--- if (m_areaOfInterest.width() % m_decimationFactor) { ++width; } if (m_areaOfInterest.height() % m_decimationFactor) { ++height; } rect = ossimIrect(0, 0, width-1, height-1); } } void ossimOverviewSequencer::setImageHandler(ossimImageHandler* input) { m_imageHandler = input; m_areaOfInterest.makeNan(); m_dirtyFlag = true; if (m_maskWriter.valid()) m_maskWriter->connectMyInputTo(m_imageHandler.get()); } void ossimOverviewSequencer::setSourceLevel(ossim_uint32 level) { m_sourceResLevel = level; m_areaOfInterest.makeNan(); m_dirtyFlag = true; } ossimHistogramMode ossimOverviewSequencer::getHistogramMode() const { return m_histoMode; } void ossimOverviewSequencer::setHistogramMode(ossimHistogramMode mode) { m_histoMode = mode; m_dirtyFlag = true; } void ossimOverviewSequencer::writeHistogram() { if ( m_histogram.valid() && m_imageHandler.valid() ) { writeHistogram( m_imageHandler->getFilenameWithThisExtension("his") ); } } void ossimOverviewSequencer::writeHistogram(const ossimFilename& file) { if ( m_histogram.valid() ) { ossimRefPtr histo = new ossimMultiResLevelHistogram; histo->addHistogram( m_histogram.get() ); ossimKeywordlist kwl; histo->saveState(kwl); kwl.write(file.c_str()); } } void ossimOverviewSequencer::initialize() { if ( m_dirtyFlag == false ) { return; // Already initialized. } if ( !m_imageHandler ) { return; } ossimImageSource* imageSource = m_imageHandler.get(); if (m_maskFilter.valid()) imageSource = m_maskFilter.get(); // Check the area of interest and set from image if needed. if ( m_areaOfInterest.hasNans() ) { m_areaOfInterest = m_imageHandler->getImageRectangle(m_sourceResLevel); } // Check the tile size and set from image if needed. if ( m_tileSize.hasNans() ) { m_tileSize.x = imageSource->getTileWidth(); m_tileSize.y = imageSource->getTileHeight(); } // Update m_numberOfTilesHorizontal and m_numberOfTilesVertical. updateTileDimensions(); // Start on first tile. m_currentTileNumber = 0; // Use this factory constructor as it copies the min/max/nulls from the image handler. m_tile = ossimImageDataFactory::instance()-> create( 0, imageSource->getNumberOfOutputBands(), imageSource); if(m_tile.valid()) { // Set the width and height. m_tile->setWidthHeight(static_cast(m_tileSize.x), static_cast(m_tileSize.y) ); // Initialize tile buffer. m_tile->initialize(); } if (m_histoMode != OSSIM_HISTO_MODE_UNKNOWN) { m_histogram = new ossimMultiBandHistogram; m_histogram->create(imageSource); if (m_histoMode == OSSIM_HISTO_MODE_NORMAL) { m_histoTileIndex = 1; // Sample every tile. } else { const ossim_float64 PIXEL_TO_SAMPLE = 100.0 * 256.0 * 256.0; // 100 256x256 tiles. ossim_float64 pixels = m_tileSize.x * m_tileSize.y * getNumberOfTiles(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "pixels: " << pixels << "\n" << "PIXEL_TO_SAMPLE: " << PIXEL_TO_SAMPLE << "\n"; } if (pixels > PIXEL_TO_SAMPLE) { m_histoTileIndex = ossim::round(pixels/PIXEL_TO_SAMPLE); } else { m_histoTileIndex = 1; // Sample every tile. } } } else { m_histogram = 0; } if ( m_scanForMinMax || m_scanForMinMaxNull ) { //--- // The methods ossimImageData::computeMinMaxNullPix and computeMinMaxPix // will resize and set min to max, max to min and null to max if the arrays passed in // are empty. //--- clearMinMaxNullArrays(); } m_dirtyFlag = false; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "aoi: " << m_areaOfInterest << "\ntile size: " << m_tileSize << "\ntiles wide: " << m_numberOfTilesHorizontal << "\ntiles high: " << m_numberOfTilesVertical << "\nsource rlevel: " << m_sourceResLevel << "\ndecimation factor: " << m_decimationFactor << "\nresamp type: " << m_resampleType << "\nscan for min max: " << (m_scanForMinMax?"true\n":"false\n") << "\nscan for min, max null: " << (m_scanForMinMaxNull?"true\n":"false\n") << "\nhisto mode: " << m_histoMode << "\n"; if (m_histoMode != OSSIM_HISTO_MODE_UNKNOWN) { ossimNotify(ossimNotifyLevel_DEBUG) << "Sampling every " << m_histoTileIndex << " tile(s) for histogram.\n"; } } } void ossimOverviewSequencer::setToStartOfSequence() { m_currentTileNumber = 0; } ossimRefPtr ossimOverviewSequencer::getNextTile() { if ( m_dirtyFlag ) { return ossimRefPtr(); } // Get the rectangle to grab from the image. ossimIrect inputRect; getInputTileRectangle(inputRect); // Get the output rectangle. ossimIrect outputRect; getOutputTileRectangle(outputRect); // Capture the output rectangle. m_tile->setImageRectangle(outputRect); // Start with a blank tile. m_tile->makeBlank(); // Grab the input tile. ossimRefPtr inputTile; if (m_maskFilter.valid()) { inputTile = m_maskFilter->getTile(inputRect, m_sourceResLevel); // Check for errors reading tile and set our error status for callers. if ( m_maskFilter->hasError() ) { setErrorStatus(); } } else { inputTile = m_imageHandler->getTile(inputRect, m_sourceResLevel); // Check for errors reading tile and set our error status for callers. if ( m_imageHandler->hasError() ) { setErrorStatus(); } } if ( hasError() ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimOverviewSequencer::getNextTile ERROR:" << "\nError set reading tile: " << m_currentTileNumber << std::endl; if ( inputTile.valid() ) { inputTile->makeBlank(); } } else if ( inputTile.valid() ) { if ( m_scanForMinMaxNull ) { inputTile->computeMinMaxNulPix(m_minValues, m_maxValues, m_nulValues); } else if ( m_scanForMinMax ) { inputTile->computeMinMaxPix(m_minValues, m_maxValues); } if ( ( m_histoMode != OSSIM_HISTO_MODE_UNKNOWN ) && ( (m_currentTileNumber % m_histoTileIndex) == 0 ) ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOverviewSequencer::getNextTile DEBUG:" << "\npopulating histogram for tile: " << m_currentTileNumber << "\n"; } ossimIrect tileRect = inputTile->getImageRectangle(); ossimIrect clipRect = tileRect.clipToRect( m_areaOfInterest ); inputTile->populateHistogram(m_histogram, clipRect); } if ( (inputTile->getDataObjectStatus() == OSSIM_PARTIAL) || (inputTile->getDataObjectStatus() == OSSIM_FULL ) ) { // Resample the tile. resampleTile(inputTile.get()); m_tile->validate(); // Scan the resampled pixels for bogus values to be masked out (if masking enabled) if (m_maskWriter.valid()) m_maskWriter->generateMask(m_tile, m_sourceResLevel+1); } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimOverviewSequencer::getNextTile DEBUG:" << "\nRequest failed for input rect: " << inputRect << "\nRes level: " << m_sourceResLevel << std::endl; } // Increment the tile index. ++m_currentTileNumber; return m_tile; } void ossimOverviewSequencer::slaveProcessTiles() { } bool ossimOverviewSequencer::isMaster() const { return true; } ossimIpt ossimOverviewSequencer::getTileSize() const { return m_tileSize; } void ossimOverviewSequencer::setTileSize(const ossimIpt& tileSize) { m_tileSize = tileSize; updateTileDimensions(); m_dirtyFlag = true; } void ossimOverviewSequencer::setResampleType( ossimFilterResampler::ossimFilterResamplerType resampleType) { m_resampleType = resampleType; } void ossimOverviewSequencer::setScanForMinMax(bool flag) { m_scanForMinMax = flag; } bool ossimOverviewSequencer::getScanForMinMax() const { return m_scanForMinMax; } void ossimOverviewSequencer::setScanForMinMaxNull(bool flag) { m_scanForMinMaxNull = flag; } bool ossimOverviewSequencer::getScanForMinMaxNull() const { return m_scanForMinMaxNull; } void ossimOverviewSequencer::clearMinMaxNullArrays() { m_minValues.clear(); m_maxValues.clear(); m_nulValues.clear(); } bool ossimOverviewSequencer::writeOmdFile(const std::string& file) { static const char M[] = "ossimOverviewSequencer::writeOmdFile"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\nfile: " << file << endl; } //--- // This method writes an omd file to disk. Typically called after sequencing trough tile that // were scanned for min, max, and potentially null values. // Since this can be called without a scan there is extra logic in here to initialize values // if so. Also there are sanity checks for cases where there is no null value, i.e. a // full tile, in which case assumptions have to be made... //--- bool result = false; if ( file.size() && m_imageHandler.valid() ) { const ossim_uint32 BANDS = m_imageHandler->getNumberOfInputBands(); const ossimScalarType SCALAR = m_imageHandler->getOutputScalarType(); const ossim_float64 DEFAULT_NULL = ossim::defaultNull(SCALAR); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Original array values:\n"; std::vector::const_iterator i = m_minValues.begin(); ossim_int32 band = 0; while ( i < m_minValues.end() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "min[" << band++ << "]: " << *i << "\n"; ++i; } i = m_maxValues.begin(); band = 0; while ( i < m_maxValues.end() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "max[" << band++ << "]: " << *i << "\n"; ++i; } i = m_nulValues.begin(); band = 0; while ( i < m_nulValues.end() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "nul[" << band++ << "]: " << *i << "\n"; ++i; } } if ( (m_scanForMinMax == true) || (m_nulValues.size() != BANDS) ) { // Only scanned for min and max so set the null. if (m_nulValues.size() != BANDS) { m_nulValues.resize(BANDS); } for (ossim_uint32 band = 0; band < BANDS; ++band) { m_nulValues[band] = m_imageHandler->getNullPixelValue(band); } } else if ( m_scanForMinMaxNull == true ) { //--- // The arrays (sizes) should be set if we did the scan. // Note that scanning for null only works if there IS a null in the image; hence, the // extra sanity checks as if there are no null then the null gets set to the real min. // // This is very dangerous code as it makes assumptions (drb)... //--- if ( (m_minValues.size() == BANDS) && (m_maxValues.size() == BANDS) && (m_nulValues.size() == BANDS) ) { switch(SCALAR) { case OSSIM_UINT8: case OSSIM_SINT8: case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT32: { // All of these should have a null of 0. for (ossim_uint32 band = 0; band < BANDS; ++band) { if ( m_nulValues[band] > DEFAULT_NULL ) { if ( m_nulValues[band] < m_minValues[band] ) { m_minValues[band] = m_nulValues[band]; } m_nulValues[band] = DEFAULT_NULL; } } break; } case OSSIM_SINT16: { for (ossim_uint32 band = 0; band < BANDS; ++band) { if ( ( m_nulValues[band] != DEFAULT_NULL ) && // -32768 ( m_nulValues[band] != -32767.0 ) && ( m_nulValues[band] != -32766.0 ) && ( m_nulValues[band] != -9999.0 ) ) { if ( ( m_nulValues[band] > -9999.0 ) && ( m_nulValues[band] < m_minValues[band] ) ) { m_minValues[band] = m_nulValues[band]; } m_nulValues[band] = DEFAULT_NULL; } } break; } case OSSIM_SINT32: { for (ossim_uint32 band = 0; band < BANDS; ++band) { if ( ( m_nulValues[band] != DEFAULT_NULL ) && ( m_nulValues[band] != -32768.0 ) && // Common null ( m_nulValues[band] != -32767.0 ) && // The other common null. ( m_nulValues[band] != -32766.0 ) && ( m_nulValues[band] != -9999.0 ) && ( m_nulValues[band] != -99999.0 ) ) { if ( ( m_nulValues[band] > -9999.0 ) && ( m_nulValues[band] < m_minValues[band] ) ) { m_minValues[band] = m_nulValues[band]; } m_nulValues[band] = DEFAULT_NULL; } } break; } case OSSIM_FLOAT32: case OSSIM_FLOAT64: { for (ossim_uint32 band = 0; band < BANDS; ++band) { if ( ( m_nulValues[band] != DEFAULT_NULL ) && ( m_nulValues[band] != -32768.0 ) && ( m_nulValues[band] != -32767.0 ) && ( m_nulValues[band] != -32766.0 ) && ( m_nulValues[band] != -9999.0 ) && ( m_nulValues[band] != -99999.0 ) ) { if ( ( m_nulValues[band] > -9999 ) && ( m_nulValues[band] < m_minValues[band] ) ) { m_minValues[band] = m_nulValues[band]; } m_nulValues[band] = DEFAULT_NULL; } } break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_NORMALIZED_DOUBLE: { for (ossim_uint32 band = 0; band < BANDS; ++band) { if ( ( m_nulValues[band] != DEFAULT_NULL ) && ( m_nulValues[band] > 0.0) ) { if ( m_nulValues[band] < m_minValues[band] ) { m_minValues[band] = m_nulValues[band]; } m_nulValues[band] = 0.0; } } break; } case OSSIM_SCALAR_UNKNOWN: default: { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << __FILE__ << ":" << __LINE__ << " " << M << "\nUnhandled scalar type: " << SCALAR << std::endl; } break; } } // End: switch(SCALAR) } // Matches: if ( (m_minValues.size() == BANDS) &&... else { // ERROR! ossimNotify(ossimNotifyLevel_WARN) << M << "ERROR:\nMin, max and null array sizes bad! No omd file will be written." << std::endl; } } // Matches: else if ( m_scanForMinMaxNull == true ) else { // Get the values from the image handler. if (m_minValues.size() != BANDS) { m_minValues.resize(BANDS); for (ossim_uint32 band = 0; band < BANDS; ++band) { m_minValues[band] = m_imageHandler->getMinPixelValue(band); } } if (m_maxValues.size() != BANDS) { m_maxValues.resize(BANDS); for (ossim_uint32 band = 0; band < BANDS; ++band) { m_maxValues[band] = m_imageHandler->getMaxPixelValue(band); } } if (m_nulValues.size() != BANDS) { m_nulValues.resize(BANDS); for (ossim_uint32 band = 0; band < BANDS; ++band) { m_nulValues[band] = m_imageHandler->getNullPixelValue(band); } } } // Last size check as the m_scanForMinMaxNull block could have failed. if ( ( m_minValues.size() == BANDS ) && ( m_maxValues.size() == BANDS ) && ( m_nulValues.size() == BANDS ) ) { // Write the omd file: ossimKeywordlist kwl; if( ossimFilename(file).exists()) { // Pick up existing omd file. kwl.addFile(file.c_str()); } ossimImageMetaData metaData(SCALAR, BANDS); for(ossim_uint32 band = 0; band < BANDS; ++band) { metaData.setMinPix(band, m_minValues[band]); metaData.setMaxPix(band, m_maxValues[band]); metaData.setNullPix(band, m_nulValues[band]); } // Save to keyword list. metaData.saveState(kwl); // Write to disk. result = kwl.write(file.c_str()); if ( result ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Wrote file: " << file << "\n"; } else { ossimNotify(ossimNotifyLevel_WARN) << "ERROR writing file: " << file << "\n"; } } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Final array values:\n"; std::vector::const_iterator i = m_minValues.begin(); ossim_int32 band = 0; while ( i < m_minValues.end() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "min[" << band++ << "]: " << *i << "\n"; ++i; } i = m_maxValues.begin(); band = 0; while ( i < m_maxValues.end() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "max[" << band++ << "]: " << *i << "\n"; ++i; } i = m_nulValues.begin(); band = 0; while ( i < m_nulValues.end() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "nul[" << band++ << "]: " << *i << "\n"; ++i; } } } // Matches: if ( file && m_imageHandler.valid() ) if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exit status" << (result?"true\n":"false\n"); } return result; } void ossimOverviewSequencer::getInputTileRectangle(ossimIrect& inputRect) const { if (!m_imageHandler) return; getOutputTileRectangle(inputRect); inputRect = inputRect * m_decimationFactor; #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOverviewSequencer::getInputTileRectangle DEBUG:" << "input rect: " << inputRect << std::endl; } #endif } void ossimOverviewSequencer::getOutputTileRectangle( ossimIrect& outputRect) const { // Get the row and column. ossim_int32 row = m_currentTileNumber / m_numberOfTilesHorizontal; ossim_int32 col = m_currentTileNumber % m_numberOfTilesHorizontal; ossimIpt pt; // Set the upper left. pt.y = row * m_tileSize.y; pt.x = col * m_tileSize.x; outputRect.set_ul(pt); // Set the lower right. pt.y = pt.y + m_tileSize.y - 1; pt.x = pt.x + m_tileSize.x - 1; outputRect.set_lr(pt); #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOverviewSequencer::getOutputTileRectangle DEBUG:" << "output rect: " << outputRect << std::endl; } #endif } void ossimOverviewSequencer::updateTileDimensions() { if( m_areaOfInterest.hasNans() || m_tileSize.hasNans() ) { m_numberOfTilesHorizontal = 0; m_numberOfTilesVertical = 0; m_dirtyFlag = true; } else { // Get the output rectangle. ossimIrect rect; getOutputImageRectangle(rect); m_numberOfTilesHorizontal = static_cast( rect.width() / m_tileSize.x ); m_numberOfTilesVertical = static_cast( rect.height() / m_tileSize.y ); if (rect.width() % m_tileSize.x) { ++m_numberOfTilesHorizontal; } if (rect.height() % m_tileSize.y) { ++m_numberOfTilesVertical; } } } void ossimOverviewSequencer::resampleTile(const ossimImageData* inputTile) { switch(m_imageHandler->getOutputScalarType()) { case OSSIM_UINT8: { resampleTile(inputTile, ossim_uint8(0)); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { resampleTile(inputTile, ossim_uint16(0)); break; } case OSSIM_SINT16: { resampleTile(inputTile, ossim_sint16(0)); break; } case OSSIM_UINT32: { resampleTile(inputTile, ossim_uint32(0)); break; } case OSSIM_SINT32: { resampleTile(inputTile, ossim_sint32(0)); break; } case OSSIM_FLOAT32: { resampleTile(inputTile, ossim_float32(0.0)); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { resampleTile(inputTile, ossim_float64(0.0)); break; } default: ossimNotify(ossimNotifyLevel_WARN) << "ossimOverviewSequencer::resampleTile Unknown pixel type!" << std::endl; return; } // End of "switch(m_imageHandler->getOutputScalarType())" } template void ossimOverviewSequencer::resampleTile(const ossimImageData* inputTile, T /* dummy */ ) { #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOverviewSequencer::resampleTile DEBUG: " << "\ncurrent tile: " << m_currentTileNumber << "\ninput tile:\n" << *inputTile << "output tile:\n" << *(m_tile.get()) << endl; } #endif const ossim_uint32 BANDS = m_tile->getNumberOfBands(); const ossim_uint32 LINES = m_tile->getHeight(); const ossim_uint32 SAMPS = m_tile->getWidth(); const ossim_uint32 INPUT_WIDTH = m_decimationFactor*m_tileSize.x; T nullPixel = 0; ossim_float64 weight = 0.0; ossim_float64 value = 0.0; ossim_uint32 sampOffset = 0; if (m_resampleType == ossimFilterResampler::ossimFilterResampler_NEAREST_NEIGHBOR) { for (ossim_uint32 band=0; band(inputTile->getBuf(band)); // source T* d = static_cast(m_tile->getBuf(band)); // destination nullPixel = static_cast(inputTile->getNullPix(band)); weight = 0.0; value = 0.0; for (ossim_uint32 i=0; i( value/weight ); } else { d[j] = nullPixel; } } // End of sample loop. d += m_tileSize.x; } // End of line loop. } // End of band loop. } else // ossimFilterResampler::ossimFilterResampler_BOX { ossim_uint32 lineOffset1 = 0; ossim_uint32 lineOffset2 = 0; ossim_float64 ul = 0.0; ossim_float64 ur = 0.0; ossim_float64 ll = 0.0; ossim_float64 lr = 0.0; for (ossim_uint32 band=0; band(inputTile->getBuf(band)); // source T* d = static_cast(m_tile->getBuf(band)); // destination nullPixel = static_cast(inputTile->getNullPix(band)); weight = 0.0; value = 0.0; for (ossim_uint32 i=0; i( value/weight ); } else { d[j] = nullPixel; } } // End of sample loop. d += m_tileSize.x; } // End of line loop. } // End of band loop. } } void ossimOverviewSequencer::setBitMaskObjects(ossimBitMaskWriter* mask_writer, ossimMaskFilter* mask_filter) { m_maskWriter = mask_writer; m_maskFilter = mask_filter; } ossim-Miami-2.9.1/src/imaging/ossimPdfWriter.cpp000066400000000000000000001472451352751253100216170ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file // // Author: David Burken // // Description: OSSIM Portable Document Format (PDF) writer. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimPdfWriter, "ossimPdfWriter", ossimImageFileWriter) //--- // For trace debugging (to enable at runtime do: // your_app -T "ossimPdfWriter:debug" your_app_args //--- static ossimTrace traceDebug("ossimPdfWriter:debug"); static ossimTrace traceLog("ossimPdfWriter:log"); // Property keywords: static const std::string AUTHOR_KW = "Author"; static const std::string CREATOR_KW = "Creator"; static const std::string CREATION_DATE_KW = "CreationDate"; static const std::string KEYWORDS_KW = "Keywords"; static const std::string MOD_DATE_KW = "ModDate"; static const std::string PRODUCER_KW = "Producer"; static const std::string SUBJECT_KW = "Subject"; static const std::string TITLE_KW = "Title"; //--- // For the "ident" program which will find all exanded $Id$ macros and print them. //--- #if OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id$"; #endif ossimPdfWriter::ossimPdfWriter() : ossimImageFileWriter(), m_str(0), m_ownsStream(false), m_savedInput(0), m_kwl( new ossimKeywordlist() ), m_mutex() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPdfWriter::ossimPdfWriter entered" << std::endl; #if OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } // Since there is no internal geometry set the flag to write out one. setWriteExternalGeometryFlag(true); theOutputImageType = "ossim_pdf"; } ossimPdfWriter::~ossimPdfWriter() { // This will flush stream and delete it if we own it. close(); m_kwl = 0; // Not a leak, ossimRefPtr } ossimString ossimPdfWriter::getShortName() const { return ossimString("ossim_pdf_writer"); } ossimString ossimPdfWriter::getLongName() const { return ossimString("ossim pdf writer"); } ossimString ossimPdfWriter::getClassName() const { return ossimString("ossimPdfWriter"); } bool ossimPdfWriter::writeFile() { bool result = false; if( theInputConnection.valid() && ( getErrorStatus() == ossimErrorCodes::OSSIM_OK ) ) { //--- // Make sure we can open the file. Note only the master process is used for // writing... //--- if(theInputConnection->isMaster()) { if (!isOpen()) { open(); } } result = writeStream(); } return result; } bool ossimPdfWriter::writeStream() { static const char MODULE[] = "ossimPdfWriter::writeStream"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << "\nCurrent options:\n" << *(m_kwl.get()) << std::endl; } bool result = false; if ( isOpen() ) { // Make sure we have a region of interest. if( theAreaOfInterest.hasNans() ) { theInputConnection->initialize(); theAreaOfInterest = theInputConnection->getAreaOfInterest(); } else { theInputConnection->setAreaOfInterest( theAreaOfInterest ); } ossim_uint32 bands = theInputConnection->getNumberOfOutputBands(); ossimScalarType scalarType = theInputConnection->getOutputScalarType(); // std::cout <<"BANDS ======== " << bands << " scalarType = " << scalarType << std::endl; if(((bands == 3) || (bands == 1))&&(scalarType == OSSIM_UINT8)) { // Write the image: result = writeImage( m_str ); } else { ossimNotify(ossimNotifyLevel_INFO) << MODULE << " result = false" << std::endl; // need some kind of error result = false; } close(); // Reset the input to the image source sequence if it was modified. if ( m_savedInput.get() != theInputConnection->getInput( 0 ) ) { theInputConnection->connectMyInputTo( 0, m_savedInput.get() ); } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status = " << (result?"true":"false") << std::endl; } return result; } // bool ossimPdfWriter::writeStream() void ossimPdfWriter::writeHeader( std::ostream* str ) { // Header: if ( str ) { // Open in binary mode: std::ostringstream os( std::ios_base::out|std::ios_base::binary ); os << "%PDF-1.7\n"; //--- // Add comment with four characters greater than 127 to flag "binary pdf". // Standard/norm from spec is "0xE2E3CFD3": //--- std::vector binData(4); binData[0] = 0xE2; binData[1] = 0xE3; binData[2] = 0xCF; binData[3] = 0xD3; os << "%"; os.write( (char*)&binData.front(), binData.size() ); os << "\n"; // Write it: str->write( os.str().data(), os.str().size() ); if ( traceLog() ) { // Has binary data in it??? ossimNotify(ossimNotifyLevel_DEBUG) << os.str() << "\n"; } } } void ossimPdfWriter::writeCatalog( std::ostream* str, std::vector& xref ) { // Write the Catalog object. This assumes an order of: if ( str ) { // Capture position: xref.push_back( (std::streamoff)m_str->tellp() ); std::ostringstream os; // tmp stream... os << xref.size() << " 0 obj\n" << " << /Type /Catalog\n" << " /Pages " << xref.size()+1 << " 0 R\n" // Reference to Pages. << " >>\n" << "endobj\n"; // Write it: str->write( os.str().data(), os.str().size() ); if ( traceLog() ) { // Has binary data in it??? ossimNotify(ossimNotifyLevel_DEBUG) << os.str() << "\n"; } } } #if 0 void ossimPdfWriter::writeOutlines( std::ostream* str, std::vector& xref ) { // Write the Outlines object: if ( str ) { // Capture position: xref.push_back( (std::streamoff)m_str->tellp() ); std::ostringstream os; // tmp stream... os << xref.size() << " 0 obj\n" << " << /Type /Outlines\n" << " /Count 0\n" << " >>\n" << "endobj\n"; str->write( os.str().data(), os.str().size() ); if ( traceLog() ) { // Has binary data in it??? ossimNotify(ossimNotifyLevel_DEBUG) << os.str() << "\n"; } } } #endif void ossimPdfWriter::writePages( std::ostream* str, std::vector& xref ) { // Write Pages object. if ( str ) { // Capture position: xref.push_back( (std::streamoff)str->tellp() ); std::ostringstream os; os << xref.size() << " 0 obj\n" << " << /Type /Pages\n" << " /Kids [ " << xref.size()+1 << " 0 R ]\n" // Reference to Page. << " /Count 1\n" << " >>\n" << "endobj\n"; str->write( os.str().data(), os.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os.str() << "\n"; } } } void ossimPdfWriter::writeInfo( std::ostream* str, std::vector& xref ) { // Write Pages object. if ( str ) { // Capture position: xref.push_back( (std::streamoff)str->tellp() ); std::ostringstream os; os << xref.size() << " 0 obj % Document Information Dictionary\n"; // Tile: std::string s; getTitle( s ); if ( s.size() ) { os << " << /Title (" << s << ")\n"; } // Author: getAuthor( s ); if ( s.size() ) { os << " /Author (" << s << ")\n"; } // Creator: getCreator( s ); if ( s.size() ) { os << " /Creator (" << s << ")\n"; } // Producer: getProducer( s ); if ( s.size() ) { os << " /Producer (" << s << ")\n"; } // Creation date ( D : YYYYMMDDHHmmSSOHH ' mm ' ): getCreationDate( s ); if ( s.size() ) { os << " /CreationDate " << s << "\n"; } // Modification date ( D : YYYYMMDDHHmmSSOHH ' mm ' ): getModDate( s ); if ( s.size() ) { os << " /ModDate " << s << "\n"; } os << " >>\n" << "endobj\n"; str->write( os.str().data(), os.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os.str() << "\n"; } } } // End: ossimPdfWriter::writeInfo bool ossimPdfWriter::writeImage( std::ostream* str ) { bool status = false; if ( str ) { //--- // This will remap input to eight bit if not already and make input one or // three band depending on number of bands. //--- setupInputChain(); // Set the sequence tile size: ossimIpt tileSize; getTileSize( tileSize ); theInputConnection->setTileSize( tileSize ); // Start the sequence at the first tile. theInputConnection->setToStartOfSequence(); const ossim_uint32 WIDTH = theAreaOfInterest.width(); const ossim_uint32 HEIGHT = theAreaOfInterest.height(); const ossim_uint32 TW = theInputConnection->getNumberOfTilesHorizontal(); const ossim_uint32 TH = theInputConnection->getNumberOfTilesVertical(); const ossim_uint32 TILES = theInputConnection->getNumberOfTiles(); #if 0 /* Please save for debug. (drb) */ ossimIrect boundingRect = theInputConnection->getBoundingRect(); ossimNotify(ossimNotifyLevel_NOTICE) << "\nBounding rect: " << theInputConnection->getBoundingRect() << "\nAOI: " << theAreaOfInterest << "\nBands: " << theInputConnection->getNumberOfOutputBands() << "\ntilesWide: " << TW << "\ntilesHigh: " << TH << "\ntileWidth: " << tileWidth << "\ntileHeight " << tileHeight << std::endl; #endif if ( traceLog() ) { ossimKeywordlist logKwl; theInputConnection->saveStateOfAllInputs(logKwl); ossimFilename logFile = getFilename(); logFile.setExtension("log"); ossimKeywordlist kwl; theInputConnection->saveStateOfAllInputs(kwl); kwl.write(logFile.c_str() ); } // Cross reference(xref) table. Holds the offset of each object. Written at the end. std::vector xref; //--- // Header: //--- writeHeader( str ); //--- // Catalog object: //--- writeCatalog( str, xref ); //--- // Outlines object: //--- // writeOutlines( m_str, xref ); //--- // Pages object: //--- writePages( str, xref ); //--- // Page object: //--- // Capture position: xref.push_back( (std::streamoff)str->tellp() ); std::ostringstream os1; os1 << xref.size() << " 0 obj\n" << " << /Type /Page\n" << " /Parent " << xref.size()-1 << " 0 R\n" // Parent always one back. << " /Resources " << xref.size()+1 << " 0 R\n" // Next object. << " /MediaBox[0.0 0.0 " << WIDTH << " " << HEIGHT << "]\n" // Contents = Resources_dictionary + tiles + base_form + 1): << " /Contents[" << (xref.size()+TILES+3) << " 0 R]\n"; ossimRefPtr geom = theInputConnection->getImageGeometry(); if ( geom.valid() ) { // Coordinate Transformation Matrix (CTM) std::string lgiDictString; getLgiDict( geom.get(), theAreaOfInterest, lgiDictString ); if ( lgiDictString.size() ) { os1 << lgiDictString; } } os1 << " >>\n" << "endobj\n"; // Matches: <write( os1.str().data(), os1.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os1.str() << "\n"; } // End /Page object //--- // Resource dictionary for page: //--- // Capture position: xref.push_back( (std::streamoff)str->tellp() ); std::ostringstream os2; os2 << xref.size() << " 0 obj % Resource dictionary for page.\n" << " << /ProcSet[/PDF/ImageB/ImageC]\n" << " /XObject << /Basemap_Form " << (xref.size()+TILES+1) << " 0 R "; // Write in the tiles: ossim_uint32 objIndex = static_cast(xref.size()+1); ossim_uint32 x; ossim_uint32 y; for ( x = 0; x < TW; ++x ) { for ( y = 0; y < TH; ++y ) { os2 << getTileString( x, y ) << " " << objIndex << " 0 R "; ++objIndex; } } os2 << ">>\n" // Matches: /XObject<< << " >>\nendobj\n"; // Matches: % Resources..."; str->write( os2.str().data(), os2.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os2.str() << "\n"; } // End Resources dictionary. //--- // Now write the XObjects jpeg tiles: //--- ossim_uint32 tileNumber = 0; std::vector outputTileRects; while ( tileNumber < TILES ) { ossimRefPtr id = theInputConnection->getNextTile(); if( id.valid() ) { // To hold output tile rect clamped to AOI. ossimIrect outputTileRect; switch ( getImageType() ) { case ossimPdfWriter::RAW: { writeRawTile( str, xref, id.get(), theAreaOfInterest, outputTileRect ); break; } case ossimPdfWriter::JPEG: default: { writeJpegTile( str, xref, id.get(), theAreaOfInterest, outputTileRect ); break; } } // Capture tile rect: outputTileRects.push_back( outputTileRect ); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimPdfWriter::writeImage ERROR:" << "\nNULL Tile encountered, tile number=" << tileNumber << std::endl; status = false; break; } ++tileNumber; setPercentComplete( tileNumber / TILES * 100.0 ); } if ( tileNumber == TILES ) { status = true; } if ( status ) { //--- // XObect Form for image tiles: //--- // Capture position: xref.push_back( (std::streamoff)str->tellp() ); ossimIpt llPageOffset; getLowerLeftPageOffset( theAreaOfInterest, llPageOffset ); std::ostringstream os3; // Tile loop - ontents for each ile: tileNumber = 0; ossim_uint32 x; ossim_uint32 y; for ( x = 0; x < TW; ++x ) { for ( y = 0; y < TH; ++y ) { //--- // PDF space is positive y = up, positive x = right. // ossim image space is positive y down. // 0, 0 is lower left corner in pdf space so "y of 0" in pdf space is // theAreaOfInterest.ll().y in image space. //--- ossim_int32 width = outputTileRects[tileNumber].width(); ossim_int32 height = outputTileRects[tileNumber].height(); ossim_int32 llOffsetX = llPageOffset.x + outputTileRects[tileNumber].ll().x - theAreaOfInterest.ll().x; ossim_int32 llOffsetY = llPageOffset.y + theAreaOfInterest.lr().y - outputTileRects[tileNumber].ll().y; os3 << " q\n" // Save graphics state << " " << width << " 0 0 " << height << " " << llOffsetX << " " << llOffsetY << " cm\n" << " " << getTileString( x, y ) << " Do\n" << " Q\n"; // Restore graphics state. ++tileNumber; } } std::ostringstream os4; os4 << xref.size() << " 0 obj % /XObject/Form dictionary for image tiles.\n" << " << /Type /XObject\n" << " /Subtype /Form\n" << " /Length " << os3.str().size() << "\n" << " /BBox[" << llPageOffset.x << " " << llPageOffset.y << " " << WIDTH << " " << HEIGHT << "]\n" << " >>\n" << "stream\n"; // Write the content stream to tmp stream. os4.write( os3.str().data(), os3.str().size() ); os4 << "\n" << "endstream\n" << "endobj\n"; // Write the tmp stream to output stream. str->write( os4.str().data(), os4.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os4.str() << "\n"; } //--- // Contents of page: //--- // Capture position: xref.push_back( (std::streamoff)str->tellp() ); std::ostringstream os5; os5 << "/Basemap_Form Do"; std::ostringstream os6; os6 << xref.size() << " 0 obj % Contents of page.\n" << " << /Length " << os5.str().size() << " >>\n" << "stream\n"; os6.write( os5.str().data(), os5.str().size() ); os6 << "\n" << "endstream\n" << "endobj\n"; str->write( os6.str().data(), os6.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os6.str() << "\n"; } m_mutex.lock(); // Code not thread safe. // Document Information dictionary: writeInfo( str, xref ); m_mutex.unlock(); //--- // Cross reference tables: //--- // Capture start of xref for the second to last line: std::streamoff xrefOffset = (std::streamoff)m_str->tellp(); writeXref( m_str, xref ); //--- // Trailer: //--- writeTrailer( m_str, static_cast(xref.size()+1), xrefOffset ); } } // Matches: if ( str ... return status; } // End: ossimPdfWriter::writeImage void ossimPdfWriter::writeJpegTile( std::ostream* str, std::vector& xref, ossimImageData* id, const ossimIrect& aoi, ossimIrect& outputTileRect ) { //--- // Most of code and comments below are from jpeg-6b "example.c" file. See // http://www4.cs.fau.de/Services/Doc/graphics/doc/jpeg/libjpeg.html //--- //--- // Initialize JPEG compression library: // Note: JDIMENSION is typedefed to an unsigned int. //--- struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error( &jerr ); jpeg_create_compress(&cinfo); //--- // Need to define a custom ostream destination manager for jpeglib to write compressed block: // Note: Write the tile to a temp memory stream to get the size up front. //--- std::ostringstream tileStream; jpeg_cpp_stream_dest(&cinfo, tileStream); // Setting the parameters of the output file here. const ossim_uint32 BANDS = id->getNumberOfBands(); const ossim_uint32 TW = id->getWidth(); const ossim_uint32 TH = id->getHeight(); // Assign width, height clamping to the aoi. cinfo.image_width = ossim::min( TW, aoi.lr().x - id->getOrigin().x + 1 ); cinfo.image_height = ossim::min( TH, aoi.lr().y - id->getOrigin().y + 1 ); cinfo.input_components = BANDS; // Capture the output tile rect: outputTileRect = ossimIrect( id->getOrigin(), ossimIpt( id->getOrigin().x + cinfo.image_width - 1, id->getOrigin().y + cinfo.image_height - 1 ) ); // colorspace of input image if ( BANDS == 3 ) { cinfo.in_color_space = JCS_RGB; } else { cinfo.in_color_space = JCS_GRAYSCALE; } // Default compression parameters... jpeg_set_defaults( &cinfo ); /* Now do the compression .. */ jpeg_start_compress( &cinfo, TRUE ); // Compress the tile on line at a time: JSAMPLE** samp_array = new JSAMPLE* [cinfo.image_height]; //--- // Get a pointer to the source data. // Needs to be band interleaved by pixel(BIP), so convert if needed. //--- ossimRefPtr tempTile = 0; ossim_uint8* tile = 0; if ( ( BANDS == 1 ) && ( cinfo.image_width == id->getWidth() ) && ( cinfo.image_height == id->getHeight() ) ) { tile = id->getUcharBuf(); } else { // Convert from OSSIM's native BSQ interleave to BIP. tempTile = new ossimImageData( 0, OSSIM_UINT8, BANDS, cinfo.image_width, cinfo.image_height ); tempTile->setOrigin( id->getOrigin() ); tempTile->initialize(); tile = tempTile->getUcharBuf(); id->unloadTile( tile, tempTile->getImageRectangle(), OSSIM_BIP ); } for ( ossim_uint32 row=0; rowtellp() ); std::ostringstream os1; os1 << xref.size() << " 0 obj\n" << " << /Type /XObject\n" << " /Subtype /Image\n" << " /Length " << tileStream.str().size() << "\n" << " /Filter[/DCTDecode]\n" << " /BitsPerComponent 8" << " /ColorSpace " << (BANDS==1?"/DeviceGray\n":"/DeviceRGB\n") << " /Width " << cinfo.image_width << " /Height " << cinfo.image_height << " >>\n" << "stream\n"; str->write( os1.str().data(), os1.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os1.str() << "*** image stream not displayed ***\n" << "endstream\n" << "endobj\n\n"; } // Write the image tile from memory to output stream. str->write( tileStream.str().data(), tileStream.str().size() ); // Close out stream object. *str << "\n" << "endstream\n" << "endobj\n"; } // End: ossimPdfWriter::writeJpegTile( ... ) void ossimPdfWriter::writeRawTile( std::ostream* str, std::vector& xref, ossimImageData* id, const ossimIrect& aoi, ossimIrect& outputTileRect ) { const ossim_uint32 BANDS = id->getNumberOfBands(); const ossim_uint32 TW = id->getWidth(); const ossim_uint32 TH = id->getHeight(); // Assign width, height clamping to the aoi. ossim_uint32 width = ossim::min( TW, aoi.lr().x - id->getOrigin().x + 1 ); ossim_uint32 height = ossim::min( TH, aoi.lr().y - id->getOrigin().y + 1 ); // Capture the output tile rect: outputTileRect = ossimIrect( id->getOrigin(), ossimIpt( id->getOrigin().x + width - 1, id->getOrigin().y + height - 1 ) ); //--- // Get a pointer to the source data. // Needs to be band interleaved by pixel(BIP), so convert if needed. //--- ossimRefPtr tempTile = 0; ossim_uint8* tile = 0; ossim_uint32 length = 0; if ( ( BANDS == 1 ) && ( width == id->getWidth() ) && ( height == id->getHeight() ) ) { tile = id->getUcharBuf(); length = id->getSizeInBytes(); } else { // Convert from OSSIM's native BSQ interleave to BIP. tempTile = new ossimImageData( 0, OSSIM_UINT8, BANDS, width, height ); tempTile->setOrigin( id->getOrigin() ); tempTile->initialize(); tile = tempTile->getUcharBuf(); id->unloadTile( tile, tempTile->getImageRectangle(), OSSIM_BIP ); length = tempTile->getSizeInBytes(); } // Capture position: xref.push_back( (std::streamoff)str->tellp() ); std::ostringstream os1; os1 << xref.size() << " 0 obj\n" << " << /Type /XObject\n" << " /Subtype /Image\n" << " /Length " << length << "\n" << " /BitsPerComponent 8" << " /ColorSpace " << (BANDS==1?"/DeviceGray\n":"/DeviceRGB\n") << " /Width " << width << " /Height " << height << " >>\n" << "stream\n"; str->write( os1.str().data(), os1.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os1.str() << "*** image stream not displayed ***\n" << "endstream\n" << "endobj\n\n"; } // Write the image tile from memory to output stream. str->write( (char*)tile, length ); // Close out stream object. *str << "\n" << "endstream\n" << "endobj\n"; } // End ossimPdfWriter::writeRawTile( ... ) void ossimPdfWriter::writeXref( std::ostream* str, const std::vector& xref ) { if ( str ) { std::ostringstream os; os << "xref\n" << "0 " << (xref.size()+1) << "\n" << "0000000000 65535 f \n"; std::vector::const_iterator i = xref.begin(); while ( i != xref.end() ) { os << std::setiosflags(std::ios_base::fixed|std::ios_base::right) << std::setfill('0') << std::setw(10) << (*i) << " 00000 n \n"; ++i; } // os << "\n"; str->write( os.str().data(), os.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os.str() << "\n"; } } } void ossimPdfWriter::writeTrailer( std::ostream* str, ossim_uint32 entrySize, std::streamoff xrefOffset ) { if ( str ) { std::ostringstream os; os << "trailer\n" << " << /Size " << entrySize << "\n" << " /Root 1 0 R\n" << " /Info " << entrySize-1 << " 0 R\n" << " >>\n" << "startxref\n" << xrefOffset << "\n" << "%%EOF\n"; // << "%%EOF"; str->write( os.str().data(), os.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os.str() << "\n"; } } } #if 0 void ossimPdfWriter::writeDummy( std::ostream* str, std::vector& xref ) { // Write a blank object. if ( str ) { // Capture position: xref.push_back( (std::streamoff)str->tellp() ); std::ostringstream os; os << xref.size() << " 0 obj % dummy\n" << "endobj\n"; str->write( os.str().data(), os.str().size() ); if ( traceLog() ) { ossimNotify(ossimNotifyLevel_DEBUG) << os.str() << "\n"; } } } #endif bool ossimPdfWriter::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimImageFileWriter::saveState(kwl, prefix); } bool ossimPdfWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimImageFileWriter::loadState(kwl, prefix); } bool ossimPdfWriter::isOpen() const { bool result = false; if (m_str) { const std::ofstream* fs = dynamic_cast(m_str); if ( fs ) { result = fs->is_open(); } else { // Pointer good enough... result = true; } } return result; } bool ossimPdfWriter::open() { bool result = false; close(); // Check for empty filenames. if (theFilename.size()) { std::ofstream* os = new std::ofstream(); os->open(theFilename.c_str(), ios::out | ios::binary); if(os->is_open()) { m_str = os; m_ownsStream = true; result = true; } else { delete os; os = 0; } } return result; } void ossimPdfWriter::close() { if (m_str) { m_str->flush(); if (m_ownsStream) { delete m_str; m_str = 0; m_ownsStream = false; } } } void ossimPdfWriter::getImageTypeList(std::vector& imageTypeList)const { imageTypeList.push_back(ossimString("ossim_pdf")); } ossimString ossimPdfWriter::getExtension() const { return ossimString("pdf"); } bool ossimPdfWriter::hasImageType(const ossimString& imageType) const { bool result = false; if ( (imageType == "ossim_pdf") || (imageType == "image/pdf")||(imageType == "application/pdf") ) { result = true; } return result; } void ossimPdfWriter::setProperty( ossimRefPtr property ) { if ( property.valid() ) { std::string name = property->getName().string(); if ( name.size() ) { if ( ( name == ossimKeywordNames::IMAGE_TYPE_KW ) || ( name == AUTHOR_KW ) || ( name == CREATOR_KW ) || ( name == CREATION_DATE_KW ) || ( name == KEYWORDS_KW ) || ( name == MOD_DATE_KW ) || ( name == ossimKeywordNames::OUTPUT_TILE_SIZE_KW ) || ( name == PRODUCER_KW ) || ( name == SUBJECT_KW ) || ( name == TITLE_KW ) ) { addOption( name, property->valueToString().string() ); } else { ossimImageFileWriter::setProperty(property); } } } } // ossimPdfWriter::setProperty ossimRefPtr ossimPdfWriter::getProperty(const ossimString& name)const { ossimRefPtr prop = 0; if ( name.size() ) { if ( name == AUTHOR_KW ) { ossimString value; getAuthor( value.string() ); ossimRefPtr stringProp = new ossimStringProperty( name, value, true); prop = stringProp.get(); } else if ( name == CREATOR_KW ) { ossimString value; getCreator( value.string() ); ossimRefPtr stringProp = new ossimStringProperty( name, value, true); prop = stringProp.get(); } else if ( name == CREATION_DATE_KW ) { ossimString value; getCreationDate( value.string() ); ossimRefPtr stringProp = new ossimStringProperty( name, value, true); prop = stringProp.get(); } else if ( name == ossimKeywordNames::IMAGE_TYPE_KW ) { ossimString value; getImageType( value.string() ); ossimRefPtr stringProp = new ossimStringProperty( name, value, false); // editable flag = false // Alway support jpeg. stringProp->addConstraint( ossimString("jpeg") ); // Alway support raw (general raster). stringProp->addConstraint( ossimString("raw") ); prop = stringProp.get(); } else if ( name == KEYWORDS_KW ) { ossimString value; getKeywords( value.string() ); ossimRefPtr stringProp = new ossimStringProperty( name, value, true); prop = stringProp.get(); } else if ( name == MOD_DATE_KW ) { ossimString value; getModDate( value.string() ); ossimRefPtr stringProp = new ossimStringProperty( name, value, true); prop = stringProp.get(); } else if( name == ossimKeywordNames::OUTPUT_TILE_SIZE_KW ) { ossimString value; getTileSize( value.string() ); ossimRefPtr stringProp = new ossimStringProperty( name, value, false); stringProp->addConstraint(ossimString("16")); stringProp->addConstraint(ossimString("32")); stringProp->addConstraint(ossimString("64")); stringProp->addConstraint(ossimString("128")); stringProp->addConstraint(ossimString("256")); stringProp->addConstraint(ossimString("512")); stringProp->addConstraint(ossimString("1024")); stringProp->addConstraint(ossimString("2048")); prop = stringProp.get(); } else if ( name == SUBJECT_KW ) { ossimString value; getSubject( value.string() ); ossimRefPtr stringProp = new ossimStringProperty( name, value, true); prop = stringProp.get(); } else if ( name == TITLE_KW ) { ossimString value; getSubject( value.string() ); ossimRefPtr stringProp = new ossimStringProperty( name, value, true); prop = stringProp.get(); } else { prop = ossimImageFileWriter::getProperty(name); } } return prop; } // End: ossimPdfWriter::getProperty void ossimPdfWriter::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back( ossimString( AUTHOR_KW ) ); propertyNames.push_back( ossimString( CREATOR_KW ) ); propertyNames.push_back( ossimString( CREATION_DATE_KW ) ); propertyNames.push_back( ossimString( ossimKeywordNames::IMAGE_TYPE_KW ) ); propertyNames.push_back( ossimString( KEYWORDS_KW ) ); propertyNames.push_back( ossimString( MOD_DATE_KW ) ); propertyNames.push_back( ossimString( ossimKeywordNames::OUTPUT_TILE_SIZE_KW ) ); propertyNames.push_back( ossimString( PRODUCER_KW ) ); propertyNames.push_back( ossimString( SUBJECT_KW ) ); propertyNames.push_back( ossimString( TITLE_KW ) ); ossimImageFileWriter::getPropertyNames(propertyNames); } bool ossimPdfWriter::setOutputStream(std::ostream& stream) { if (m_ownsStream && m_str) { delete m_str; } m_str = &stream; m_ownsStream = false; return true; } void ossimPdfWriter::setupInputChain() { if ( theInputConnection.get() ) { // Capture the input to the image source sequencer(theInputConnection). m_savedInput = theInputConnection->getInput( 0 ); ossimScalarType inputScalar = theInputConnection->getOutputScalarType(); ossim_uint32 bands = theInputConnection->getNumberOfOutputBands(); if( inputScalar != OSSIM_UINT8 ) { // Make eight bit. if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimPdfWriter::setupInputChain WARNING:" << "\nData is being scaled to 8 bit!" << "\nOriginal scalar type: " << ossimScalarTypeLut::instance()-> getEntryString(inputScalar).c_str() << std::endl; } //--- // Attach a scalar remapper to the end of the input chain. This will // need to be unattached and deleted at the end of this. //--- ossimRefPtr sr = new ossimScalarRemapper; // Connect remapper's input to sequencer input. sr->connectMyInputTo( 0, theInputConnection->getInput(0) ); // Connet sequencer to remapper. theInputConnection->connectMyInputTo(0, sr.get() ); // Initialize connections. theInputConnection->initialize(); } // Must be one or three band. Note bands are zero based... if ( ( bands != 1 ) && ( bands != 3 ) ) { std::vector bandList; // Always have one band. bandList.push_back( 0 ); if ( bands > 3 ) { // Use the first three bands. bandList.push_back( 1 ); bandList.push_back( 2 ); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimPdfWriter::setupInputChain WARNING:" << "\nOutput bands must be 1 or 3 and are being filterd!" << "\nOriginal band count: " << bands << "\nNew band count: " << bandList.size() << std::endl; } ossimRefPtr bs = new ossimBandSelector(); // Set the the band selector list. bs->setOutputBandList( bandList ); // Connect band selector's input to sequencer input. bs->connectMyInputTo( 0, theInputConnection->getInput(0) ); // Connet sequencer to band selector. theInputConnection->connectMyInputTo(0, bs.get() ); // Initialize connections. theInputConnection->initialize(); } if ( m_savedInput != theInputConnection->getInput( 0 ) ) { //--- // If the input to the image source sequencer change the AOI // MUST be reset as it gets wiped. //--- theInputConnection->setAreaOfInterest( theAreaOfInterest ); } } // Matches: if ( theInputConnection ) } // End: void ossimPdfWriter::setupInputChain() ossimPdfWriter::ossimPdfImageType ossimPdfWriter::getImageType() const { ossimPdfWriter::ossimPdfImageType result = ossimPdfWriter::UNKNOWN; // Get the type and downcase. ossimString os; getImageType( os.string() ); os.downcase(); if ( os == "jpeg" ) { result = ossimPdfWriter::JPEG; } else if ( os == "raw" ) { result = ossimPdfWriter::RAW; } else { // Unknown value: ossimNotify(ossimNotifyLevel_WARN) << "ossimPdfWriter::getImageCompression WARN\n" << "Unhandled image compression type: " << os << std::endl; } return result; } void ossimPdfWriter::getImageType( std::string& type ) const { type = m_kwl->findKey( std::string(ossimKeywordNames::IMAGE_TYPE_KW) ); if ( type.empty() ) { type = "jpeg"; // default } } void ossimPdfWriter::addOption( const std::string& key, const std::string& value ) { m_mutex.lock(); if ( m_kwl.valid() ) { if ( key.size() && value.size() ) { m_kwl->addPair( key, value ); } } m_mutex.unlock(); } #if 0 void ossimPdfWriter::getMediaBoxSize( ossim_uint32 imageWidth, ossim_uint32 imageHeight, ossimIpt& size ) const { //--- // This could be an option / property. // 612 x 792 = 8.5 x 11 inches at 72 dots per inch (612/72 x 792/72) //--- size.x = static_cast(imageWidth); size.y = static_cast(imageHeight); } #endif void ossimPdfWriter::getLowerLeftPageOffset( const ossimIrect& aoi, ossimIpt& offset ) const { if ( aoi.hasNans() == false ) { // Get the page size. // ossimIpt mediaBoxSize; // getMediaBoxSize( mediaBoxSize ); // Temp hard coded. (drb) offset.x = 0; offset.y = 0; } else { offset.x = 0; offset.y = 0; } } void ossimPdfWriter::getLgiDict( ossimImageGeometry* geom, const ossimIrect& aoi, std::string& s ) const { s.clear(); // Empty string indicates error. if ( geom && !aoi.hasNans() ) { // Coordinate Transformation Matrix (CTM) std::string ctmString; getLgiDictCtm( geom, aoi, ctmString ); if ( ctmString.size() ) { // ProjectionType std::string projectionString; getLgiDictProjection( geom, projectionString ); if ( projectionString.size() ) { //--- // Neatline: Not required for single frame. // std::string neatLineString; // getLgiDictNeatline( geom, neatLineString ); //--- // if ( neatLineString.size() ) // { // cout << "d..." << endl; // Description std::string descriptionString; getLgiDictDescription( geom, descriptionString ); if ( descriptionString.size() ) { std::ostringstream os; os << "/LGIDict" << "[<<" << ctmString << "/Version(2.1)" << projectionString // << neatLineString << descriptionString << "/Type/LGIDict>>]"; s = os.str(); // } } } } } } // End: ossimPdfWriter::getLgiDictString void ossimPdfWriter::getLgiDictDatum( ossimImageGeometry* geom, std::string& s ) const { s.clear(); if ( geom ) { ossimRefPtr mapProj = geom->getAsMapProjection(); if ( mapProj.valid() ) { const ossimDatum* datum = mapProj->getDatum(); if ( datum ) { s = "/Datum("; s += datum->code().string(); s += ")"; } } } } // End: ossimPdfWriter::getLgiDictDatum void ossimPdfWriter::getLgiDictDescription( ossimImageGeometry* geom, std::string& s ) const { s.clear(); if ( geom ) { ossimRefPtr mapProj = geom->getAsMapProjection(); if ( mapProj.valid() ) { const ossimDatum* datum = mapProj->getDatum(); if ( datum ) { std::string code = datum->code().string(); if ( code == "WGE" ) { s = "/Description(WGS 84)"; } } } } } // End: ossimPdfWriter::getLgiDictDescription #if 0 void ossimPdfWriter::getLgiDictNeatline( ossimImageGeometry* geom, std::string& s ) const { s.clear(); if ( geom ) { std::ostringstream os; // Tmp drb... os << "/Neatline[(0.0000000000)(0.0000000000)(0.0000000000)(718.0800000000)(609.8400000000)(718.0800000000)(609.8400000000)(0.0000000000)]"; s = os.str(); } } // End: ossimPdfWriter::getLgiDictNeatline #endif void ossimPdfWriter::getLgiDictProjection( ossimImageGeometry* geom, std::string& s ) const { s.clear(); // Empty string indicates error. // Projection: std::string projType; getLgiDictProjectionType( geom, projType ); // Datum: std::string datumString; getLgiDictDatum( geom, datumString ); // Description std::string descriptionString; getLgiDictDescription( geom, descriptionString ); if ( projType.size() && datumString.size() ) { std::ostringstream os; os << "/Projection<<" << projType << descriptionString << datumString << "/Type/Projection>>" << "/Display<<" << projType << descriptionString << datumString << "/Type/Projection>>"; s = os.str(); } } // End: ossimPdfWriter::getLgiDictProjection void ossimPdfWriter::getLgiDictCtm( ossimImageGeometry* geom, const ossimIrect& aoi, std::string& s ) const { s.clear(); // Empty string indicates error. ossimDpt scale; scale.makeNan(); ossimDpt dTie; dTie.makeNan(); ossimRefPtr proj = geom->getProjection(); if ( proj.valid() ) { ossimRefPtr mapProj = dynamic_cast( proj.get() ); if ( mapProj.valid() ) { if ( mapProj->isGeographic() ) { // Degrees per pixel. geom->getDegreesPerPixel( scale ); if ( !scale.hasNans() ) { // Tie point: Lat, lon of lower left corner. ossimGpt gTie; geom->localToWorld( ossimDpt( aoi.ll() ), gTie ); // Check just lat and lon disregard height. if ( !ossim::isnan(gTie.lon) && !ossim::isnan(gTie.lon) ) { dTie.x = gTie.lon; dTie.y = gTie.lat; } } } } } if ( !scale.hasNans() && !dTie.hasNans() ) { //--- // Example string: // (0.0000381944)(0.0000000000)(0.0000000000)(0.0000381944)(-77.0558525000)(38.8388091667) // NOTE: (0,0) is lower left corner in pdf space. ossim_float64 d = 0.0; std::ostringstream os; os << setprecision(15) // Not sure if this should be 10??? (drb) << std::setiosflags(std::ios_base::fixed|std::ios_base::right) << std::setfill('0') << "/CTM[(" << scale.x << ")(" << d << ")(" << d << ")(" << scale.y << ")(" << dTie.x << ")(" << dTie.y << ")]"; s = os.str(); } } // End: ossimPdfWriter::getCtmString void ossimPdfWriter::getLgiDictProjectionType( ossimImageGeometry* geom, std::string& s ) const { //--- // Initialize the projection string from geometry: // Currently only coded for geographic and UTM projection. //--- s.clear(); // Empty string indicates error. if ( geom ) { ossimRefPtr mapProj = geom->getAsMapProjection(); if ( mapProj.valid() ) { if ( mapProj->isGeographic() ) { s = "/ProjectionType(GEOGRAPHIC)"; } else { // Check for UTM: ossimRefPtr utmProj = dynamic_cast( mapProj.get() ); if ( utmProj.valid() ) { ossim_int32 zone = utmProj->getZone(); char hemisphere = utmProj->getHemisphere(); std::ostringstream os; os << "/ProjectionType(UT)" << "/Zone(" << zone << ")" << "/Hemisphere(" << hemisphere << ")"; s = os.str(); } } } } // Matches if ( geom ) } // End: ossimPdfWriter::getProjectionType ossim_uint32 ossimPdfWriter::getEpsgCode( const ossimImageGeometry* geom ) const { ossim_uint32 code = 32767; if ( geom ) { ossimRefPtr proj = geom->getProjection(); if ( proj.valid() ) { // Map projection: ossimRefPtr mapProj = dynamic_cast( proj.get() ); if ( mapProj.valid() ) { code = mapProj->getPcsCode(); } } } return code; } #if 0 void ossimPdfWriter::getNumberOfTiles( ossim_uint32 imageWidth, ossim_uint32 imageHeight, ossimIpt size ) const { const ossim_int32 DEFAULT_TILE_DIMENSION = 1024; size.x = imageWidth / DEFAULT_TILE_DIMENSION; size.y = imageHeight / DEFAULT_TILE_DIMENSION; if ( imageWidth % DEFAULT_TILE_DIMENSION ) { ++size.x; } if ( imageHeight % DEFAULT_TILE_DIMENSION ) { ++size.y; } } // End: getNumberOfTiles( ... ) #endif void ossimPdfWriter::getTitle( std::string& s ) const { // Check if in keyword list. s = m_kwl->findKey( TITLE_KW ); if ( s.empty() ) { if ( theFilename.size() ) { // Set to basename of file. s = theFilename.file().string(); } } } void ossimPdfWriter::getAuthor( std::string& s ) const { // Check if in keyword list. s = m_kwl->findKey( AUTHOR_KW ); if ( s.empty() ) { s = "ossim"; // Default: ??? } } void ossimPdfWriter::getSubject( std::string& s ) const { // Check if in keyword list. s = m_kwl->findKey( SUBJECT_KW ); } void ossimPdfWriter::getKeywords( std::string& s ) const { // Check if in keyword list. s = m_kwl->findKey( KEYWORDS_KW ); } void ossimPdfWriter::getCreator( std::string& s ) const { // Check if in keyword list. s = m_kwl->findKey( CREATOR_KW ); if ( s.empty() ) { s = "ossim"; // Default: ??? } } void ossimPdfWriter::getProducer( std::string& s ) const { // Check if in keyword list. s = m_kwl->findKey( PRODUCER_KW ); if ( s.empty() ) { s = "ossim"; // Default: ??? } } void ossimPdfWriter::getCreationDate( std::string& s ) const { // Check if in keyword list. s = m_kwl->findKey( CREATION_DATE_KW ); if ( s.empty() ) { getGmtDate( s ); } } void ossimPdfWriter::getModDate( std::string& s ) const { // Check if in keyword list. s = m_kwl->findKey( MOD_DATE_KW ); if ( s.empty() ) { getGmtDate( s ); } } void ossimPdfWriter::getGmtDate( std::string& s ) const { // Get the time: time_t now; time(&now); // Convert to UTC: tm* gt = gmtime(&now); if ( gt ) { //--- // Format(26 charactors including trailing null): // (D:YYYYMMDDHHmmSSZ00'00') char dateChars[26]; dateChars[25] = '\0'; strftime(dateChars, 26, "(D:%Y%m%d%H%M%SZ00'00')", gt); s = dateChars; } } // End: ossimPdfWriter::getGmtDate void ossimPdfWriter::getTileSize( std::string& s ) const { // Check if in keyword list. s = m_kwl->findKey( std::string( ossimKeywordNames::OUTPUT_TILE_SIZE_KW ) ); if ( s.empty() ) { ossimIpt tileSize; ossim::defaultTileSize( tileSize ); s = ossimString::toString( tileSize.x ).string(); } } void ossimPdfWriter::getTileSize( ossimIpt& tileSize ) const { std::string s; getTileSize( s ); if ( s.size() ) { tileSize.x = ossimString(s).toInt32(); } else { tileSize.x = 1024; // default } tileSize.y = tileSize.x; } std::string ossimPdfWriter::getTileString( ossim_uint32 x, ossim_uint32 y ) const { // Format like: /Tile_0001_0002 std::ostringstream os; os << std::setiosflags(std::ios_base::fixed|std::ios_base::right) << std::setfill('0') << "/Tile_" << std::setw(4) << x << "_" << std::setw(4) << y; return os.str(); } ossim-Miami-2.9.1/src/imaging/ossimPiecewiseRemapper.cpp000066400000000000000000000635531352751253100233210ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Piecewise remapper class definition. Derived from ossimTableRemapper. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimPiecewiseRemapper, "ossimPiecewiseRemapper", ossimTableRemapper) static const std::string REMAP_KW = "remap"; static const std::string REMAP_TYPE_KW = "remap_type"; static ossimTrace traceDebug("ossimPiecewiseRemapper:debug"); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id$"; #endif // Private container class for points. ossimPiecewiseRemapper::ossimRemapSet::ossimRemapSet() : m_set(0) { } ossimPiecewiseRemapper::ossimRemapSet::ossimRemapSet(const ossimRemapSet& obj) : m_set(obj.m_set) { } const ossimPiecewiseRemapper::ossimRemapSet& ossimPiecewiseRemapper::ossimRemapSet::operator=( const ossimRemapSet& rhs ) { if ( this != &rhs ) { m_set = rhs.m_set; } return *this; } // Private container class for points. ossimPiecewiseRemapper::ossimBandRemap::ossimBandRemap() : m_remap(0) { } ossimPiecewiseRemapper::ossimBandRemap::ossimBandRemap(const ossimBandRemap& obj) : m_remap(obj.m_remap) { } const ossimPiecewiseRemapper::ossimBandRemap& ossimPiecewiseRemapper::ossimBandRemap::operator=( const ossimBandRemap& rhs ) { if ( this != &rhs ) { m_remap = rhs.m_remap; } return *this; } void ossimPiecewiseRemapper::ossimBandRemap::loadState( const ossimKeywordlist& kwl, const std::string& prefix, ossim_uint32 band ) { //--- // Band Remap set example: // band0.remap0:((0, 127, 0, 127), (128, 255, 128, 382)) // band0.remap1:((0, 382, 0, 255)) //--- // Clear the sets: m_remap.clear(); // Get the number of remaps for this band. std::string keyBase = "band"; keyBase += ossimString::toString(band).string(); keyBase += "."; keyBase += REMAP_KW; ossim_uint32 NUMBER_REMAPS = kwl.numberOf(prefix.c_str(), keyBase.c_str()); ossim_uint32 found = 0; ossim_uint32 index = 0; // Loop to find band remaps. This allows for skipping indexes. while ( found < NUMBER_REMAPS ) { std::string key = keyBase + ossimString::toString(index).string(); std::string value = kwl.findKey( prefix, key ); if ( value.size() ) { ossimPiecewiseRemapper::ossimRemapSet set; if ( initRemapSetFromString( value, set ) ) { m_remap.push_back( set ); } ++found; } ++index; if ( index > (NUMBER_REMAPS+100) ) { break; } } } // End: ossimPiecewiseRemapper::ossimBandRemap::loadState void ossimPiecewiseRemapper::ossimBandRemap::saveState( ossimKeywordlist& kwl, const std::string& prefix, ossimPiecewiseRemapper::PiecewiseRemapType remapType, ossim_uint32 band ) const { //--- // Remap set: // Remap set: "band0.remap0": // band0.remap0:((0, 127, 0, 127), (128, 255, 128, 382)) // band0.remap1:((0, 382, 0, 255)) //--- ossim_uint32 remapIndex = 0; std::vector::const_iterator i = m_remap.begin(); while ( i != m_remap.end() ) { std::string key = "band"; key += ossimString::toString(band).string(); key += "."; key += REMAP_KW; key += ossimString::toString(remapIndex).string(); std::string value; getRemapSetString( remapType, (*i), value ); kwl.addPair( prefix, key, value ); ++i; ++remapIndex; } } // End: ossimPiecewiseRemapper::ossimBandRemap::saveState bool ossimPiecewiseRemapper::ossimBandRemap::initRemapSetFromString( const std::string& s, ossimPiecewiseRemapper::ossimRemapSet& set ) const { //--- // Example: // ((0, 127, 0, 127), (128, 255, 128, 382)) //--- bool result = false; if ( s.size() ) { std::istringstream in( s ); char c; ossim_float64 d; // Gobble the open '(' while ( !in.bad() && !in.eof() ) { c = in.get(); if ( c == '(' ) break; } // Main loop: while( !in.bad() && !in.eof() ) { c = in.get(); if ( c == ')' ) // Possible end of quadruple... { // Gobble next comma: while( !in.bad() && !in.eof() ) { c = in.get(); if ( c == ',' ) { break; } } c = in.get(); } if ( (c == '(') || (c == ',') ) { // Next string should be a number: in >> d; if ( in.good() ) { set.m_set.push_back(d); } else { break; } } } if ( set.m_set.size() ) { result = true; } } if ( !result ) { set.m_set.clear(); } return result; } // End: ossimPiecewiseRemapper::ossimBandRemap::initRemapSetFromString( ... ) void ossimPiecewiseRemapper::ossimBandRemap::getRemapSetString( ossimPiecewiseRemapper::PiecewiseRemapType remapType, const ossimPiecewiseRemapper::ossimRemapSet& set, std::string& s ) const { if ( remapType == ossimPiecewiseRemapper::LINEAR_NATIVE ) { getLinearRemapSetString( set, s ); } } void ossimPiecewiseRemapper::ossimBandRemap::getLinearRemapSetString( const ossimPiecewiseRemapper::ossimRemapSet& set, std::string& s ) const { //--- // Save in the form of: // ((0, 127, 0, 127), (128, 255, 128, 382)) //--- s.clear(); if ( set.m_set.size() ) { const ossim_uint32 TUPLES = set.m_set.size() / 4; if ( TUPLES ) { std::ostringstream os; os << std::setprecision(15) << "("; for ( ossim_uint32 i = 0; i < TUPLES; ++i ) { ossim_uint32 setIdx = i*4; os << "(" << set.m_set[ setIdx ] << "," << set.m_set[ setIdx + 1 ] << "," << set.m_set[ setIdx + 2 ] << "," << set.m_set[ setIdx + 3 ] << ")"; if ( i < (TUPLES-1) ) { os << ","; // Comma between quadruples. } } os << ")"; s = os.str(); } } } // End: ossimPiecewiseRemapper::ossimBandRemap::getLinearRemapSetString( ... ) ossimPiecewiseRemapper::ossimPiecewiseRemapper() : ossimTableRemapper(), // base class m_dirty(false), m_remapType(ossimPiecewiseRemapper::UNKNOWN), m_bandRemap(0), m_min(0), m_max(0) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPiecewiseRemapper::ossimPiecewiseRemapper entered...\n"; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << "\n"; #endif } } ossimPiecewiseRemapper::~ossimPiecewiseRemapper() { } void ossimPiecewiseRemapper::initialize() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPiecewiseRemapper::initialize entered..." << endl; } //--- // Call the base class initialize. // Note: This will reset "theInputConnection" if it changed... //--- ossimTableRemapper::initialize(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPiecewiseRemapper::initialize exited..." << endl; } } void ossimPiecewiseRemapper::setRemapType( const std::string& type ) { if ( (type == "linear_native") || (ossimString(type).downcase() == "linear_native") ) { m_remapType = ossimPiecewiseRemapper::LINEAR_NATIVE; } else { m_remapType = ossimPiecewiseRemapper::UNKNOWN; } } ossimRefPtr ossimPiecewiseRemapper::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr result = 0; if ( theInputConnection ) { if ( m_dirty ) { // Rebuild the table if dirty flag set: buildTable(); } if ( theEnableFlag && theTable.size() ) { //--- // Not bypassed and has a table... // Base handles the rest... //--- result = ossimTableRemapper::getTile(tileRect, resLevel); } else { // Fetch tile from pointer from the input source. result = theInputConnection->getTile(tileRect, resLevel); } } return result; } void ossimPiecewiseRemapper::getRemapTypeString( ossimPiecewiseRemapper::PiecewiseRemapType remapType, std::string& s ) const { if ( remapType == ossimPiecewiseRemapper::LINEAR_NATIVE ) { s = "linear_native"; } else { s = "unknown"; } } bool ossimPiecewiseRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimPiecewiseRemapper::loadState"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Entered..." << "\nprefix: " << (prefix?prefix:"null") << endl; } bool status = false; std::string p = ( prefix ? prefix : "" ); // Check type first before going on: std::string key = ossimKeywordNames::TYPE_KW; std::string value; value = kwl.findKey( p, key ); if ( value == "ossimPiecewiseRemapper" ) { // Load the base class states... status = ossimTableRemapper::loadState(kwl, prefix); if (status) { // Look for scalar type keyword. // ossim_int32 st = ossimScalarTypeLut::instance()->getEntryNumber(kwl, p.c_str(), true); // Lookup table returns -1 if not found so check return... // if ( (st != -1) && (st != OSSIM_SCALAR_UNKNOWN) ) // { // m_outputScalarType = static_cast(st); //} // Remap type "remap_type": value = kwl.findKey( p, REMAP_TYPE_KW ); if ( value.size() ) { setRemapType( value ); if ( m_remapType != ossimPiecewiseRemapper::UNKNOWN ) { // Get the number of bands "number_bands": ossim_uint32 bands = 0; key = ossimKeywordNames::NUMBER_BANDS_KW; value = kwl.findKey( p, key ); if ( value.size() ) { bands = ossimString(value).toUInt32(); } if ( bands ) { // Start with clean remap set: m_bandRemap.clear(); m_bandRemap.resize( bands ); m_min.clear(); m_max.clear(); // Loop through bands: for ( ossim_uint32 band = 0; band < bands; ++band ) { // Band remap: m_bandRemap[band].loadState( kwl, p, band ); // Min: std::string keyBase = ossimKeywordNames::MIN_VALUE_KW; keyBase += ".band"; key = keyBase + ossimString::toString(band).string(); value = kwl.findKey( p, key ); if ( value.size() ) { m_min.push_back( ossimString(value).toFloat64() ); } // Max: keyBase = ossimKeywordNames::MAX_VALUE_KW; keyBase += ".band"; key = keyBase + ossimString::toString(band).string(); value = kwl.findKey( p, key ); if ( value.size() ) { m_max.push_back( ossimString(value).toFloat64() ); } } // End: Band loop if ( m_bandRemap.size() && ( !m_min.size() || !m_max.size() ) ) { initMinMax(); // Initialize from the m_reampSet tuples. } } } } if ( m_bandRemap.size() ) { m_dirty = true; } } // Matches: status = ossimTableRemapper::loadState(kwl, prefix); if (status){... else { // Sets base: ossimSource::theEnableFlag setEnableFlag(false); } // Tmp drb: // initMinMax(); } // Matches: if ( value == "ossimPiecewiseRemapper" ) if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:\n"; this->print( ossimNotify(ossimNotifyLevel_DEBUG) ); ossimNotify(ossimNotifyLevel_DEBUG) << "\nExited..." << endl; } return status; } // End: ossimPiecewiseRemapper::loadState bool ossimPiecewiseRemapper::saveState( ossimKeywordlist& kwl, const char* prefix) const { bool result = false; const ossim_uint32 BANDS = getNumberOfOutputBands(); if ( ( m_remapType != ossimPiecewiseRemapper::UNKNOWN ) && ( m_bandRemap.size() == BANDS ) ) { std::string p = ( prefix ? prefix : "" ); // Bands: std::string value = ossimString::toString(BANDS).string(); kwl.addPair( p, std::string(ossimKeywordNames::NUMBER_BANDS_KW), value ); // Remap type: getRemapTypeString( m_remapType, value ); kwl.addPair( p, REMAP_TYPE_KW, value ); // Save the band remaps. if ( m_bandRemap.size() == BANDS ) { for ( ossim_uint32 band = 0; band < BANDS; ++band ) { m_bandRemap[band].saveState( kwl, p, m_remapType, band ); } } // Min/max values: if ( ( m_min.size() == BANDS ) && ( m_max.size() == BANDS ) ) { std::string minBase = ossimKeywordNames::MIN_VALUE_KW; minBase += ".band"; std::string maxBase = ossimKeywordNames::MAX_VALUE_KW; maxBase += ".band"; for ( ossim_uint32 band = 0; band < BANDS; ++band ) { // Min: std::string key = minBase + ossimString::toString(band).string(); kwl.add( p.c_str(), key.c_str(), m_min[band] ); // Max: key = maxBase + ossimString::toString(band).string(); kwl.add( p.c_str(), key.c_str(), m_max[band] ); } } // Base class: result = ossimTableRemapper::saveState(kwl, prefix); } return result; } ostream& ossimPiecewiseRemapper::print(ostream& os) const { ossimKeywordlist kwl; saveState( kwl, 0 ); os << setiosflags(ios::fixed) << setprecision(15) << "\nossimPiecewiseRemapper::print:\n" << kwl << "\n"; return os; } ossimString ossimPiecewiseRemapper::getClassName() const { return ossimString("ossimPiecewiseRemapper"); } ossimString ossimPiecewiseRemapper::getLongName()const { return ossimString("OSSIM Piecewise Remapper"); } ossimString ossimPiecewiseRemapper::getShortName()const { return ossimString("Piecewise Remapper"); } double ossimPiecewiseRemapper::getMinPixelValue(ossim_uint32 band)const { ossim_float64 result = ossimTableRemapper::getMinPixelValue(band); if ( theEnableFlag && (band < m_min.size()) ) { result = m_min[band]; } return result; } ossim_float64 ossimPiecewiseRemapper::getMaxPixelValue(ossim_uint32 band) const { ossim_float64 result = ossimTableRemapper::getMaxPixelValue(band); if ( theEnableFlag && (band < m_max.size()) ) { result = m_max[band]; } return result; } void ossimPiecewiseRemapper::initMinMax() { #if 0 if ( m_remapType == ossimPiecewiseRemapper::LINEAR_NATIVE ) { //--- // Each remap set holds a group of tuples for the band. // Tuple format example: //--- const ossim_uint32 BANDS = getNumberOfOutputBands(); if ( m_bandRemap.size() == BANDS ) { m_min.resize( BANDS ); m_max.resize( BANDS ); // First time through: for( ossim_uint32 band = 0; band < BANDS; ++band ) { const ossim_uint32 TUPLES = m_bandRemap[band].m_set.size() / 4; for ( ossim_uint32 tuple = 0; tuple < TUPLES; ++tuple ) { //--- // Min: get min of "min_out" from sets. // Max: get max of "max_out" from sets. //--- if ( tuple == 0 ) { m_min[band] = m_bandRemap[band].m_set[tuple*4+2]; m_max[band] = m_bandRemap[band].m_set[tuple*4+3]; } else { if ( m_bandRemap[band].m_set[tuple*4+2] < m_min[band] ) { m_min[band] = m_bandRemap[band].m_set[tuple*4+2]; } if ( m_bandRemap[band].m_set[tuple*4+3] > m_max[band] ) { m_max[band] = m_bandRemap[band].m_set[tuple*4+3]; } } } //--- // Clamp min to scalar min as this is used for getMinPixelValue. // This will keep a remap of: // ((0, 127, 0, 127), (128, 255, 128, 382)) // From having a min and null of 0... //--- if ( m_outputScalarType != OSSIM_SCALAR_UNKNOWN ) { if ( m_min[band] < ossim::defaultMin( m_outputScalarType ) ) { m_min[band] = ossim::defaultMin( m_outputScalarType ); } } } // End: band loop... } } else { m_min.clear(); m_max.clear(); } #endif // Disabled for now (drb) m_min.clear(); m_max.clear(); } // End: ossimPiecewiseRemapper::initMinMax() void ossimPiecewiseRemapper::buildTable() { const ossim_uint32 BANDS = getNumberOfOutputBands(); if ( BANDS && (m_bandRemap.size() == BANDS) && ( m_remapType == ossimPiecewiseRemapper::LINEAR_NATIVE ) ) { setupTable(); if ( theTable.size() ) { if ( m_remapType == ossimPiecewiseRemapper::LINEAR_NATIVE ) { buildLinearNativeTable(); } } } else { // No remaps: theTable.clear(); } // Clear the dirty flag. m_dirty = false; } // End: ossimPiecewiseRemapper::buildTable() void ossimPiecewiseRemapper::buildLinearNativeTable() { switch ( getOutputScalarType() ) { case OSSIM_UINT8: { buildLinearNativeTable(ossim_uint8(0)); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { buildLinearNativeTable(ossim_uint16(0)); break; } case OSSIM_SINT16: { buildLinearNativeTable(ossim_sint16(0)); break; } case OSSIM_UINT32: { buildLinearNativeTable(ossim_uint32(0)); break; } case OSSIM_SINT32: { buildLinearNativeTable(ossim_sint32(0)); break; } case OSSIM_SCALAR_UNKNOWN: default: { if(traceDebug()) { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimHistogramRemapper::buildLinearNativeTable OSSIM_SCALAR_UNKNOWN!" << endl; } break; } } // End of "switch (theTableType)" } // End: void ossimPiecewiseRemapper::buildLinearNativeTable() template void ossimPiecewiseRemapper::buildLinearNativeTable(T /* dummy */) { const ossim_uint32 BANDS = getNumberOfOutputBands(); if ( BANDS && (m_bandRemap.size() == BANDS) && theTable.size() ) { T* table = reinterpret_cast(&theTable.front()); ossim_uint32 index = 0; bool isInteger = std::numeric_limits::is_integer; // Flag to round or not. // Band loop: for(ossim_uint32 band = 0; band < BANDS; ++band) { // First bin is always for null. table[index++] = (T)getNullPixelValue(band); const ossim_float64 MIN_PIX = getMinPixelValue(band); const ossim_float64 MAX_PIX = getMaxPixelValue(band); for( ossim_uint32 bin = 1; bin < theTableBinCount; ++bin ) { ossim_float64 p = MIN_PIX + bin - 1; #if 0 /* Please keep for debug. (drb) */ cout << "\ninput pix[" << bin << "]: " << p << endl; #endif // Loop through remaps: std::vector::const_iterator i = m_bandRemap[band].m_remap.begin(); while ( i != m_bandRemap[band].m_remap.end() ) { //--- // Each remap set holds a group of tuples for the band. // Tuple format example: //--- const ossim_uint32 TUPLES = (*i).m_set.size() / 4; for ( ossim_uint32 set = 0; set < TUPLES; ++set ) { // Range check it: if ( ( p >= (*i).m_set[set*4] ) && // input min ( p <= (*i).m_set[set*4+1] ) ) // input max { //--- // p = (p - output_min) * (output_max-output_min)/(input_max-input_min) // + output_min; //--- p = (p - (*i).m_set[set*4]) * ((*i).m_set[set*4+3]-(*i).m_set[set*4+2]) / ((*i).m_set[set*4+1]-(*i).m_set[set*4]) + (*i).m_set[set*4]; #if 0 /* Please keep for debug. (drb) */ cout << "remapp_pix[" << bin << "][" << set << "]: " << p << endl; #endif } } // End: TUPLE loop ++i; // Next remap. } // End: remap loop: if ( isInteger ) { p = ossim::round(p); // Round to integer correctly. } #if 0 /* Please keep for debug. (drb) */ cout << "output_pix[" << bin << "]: " << p << endl; #endif // Assign to table with min/max clip: table[bin] = (T)( ( p >= MIN_PIX ) ? ( ( p <= MAX_PIX ) ? p : MAX_PIX ) : MIN_PIX); } // End: bin loop } // End: band loop } // Matches: if ( theTable.size() ) #if 0 /* Please leave for debug. (drb) */ ossimTableRemapper::print( cout ); #endif } // End: template void ossimPiecewiseRemapper::buildLinearNativeTable(T dummy) void ossimPiecewiseRemapper::setupTable() { const ossim_uint32 BANDS = getNumberOfOutputBands(); if ( BANDS ) { ossim_uint32 values_per_band = 0; ossim_uint32 bytes_per_pixel = 0; switch (theOutputScalarType) { case OSSIM_UINT8: values_per_band = 256; // 2 ^ 8 bytes_per_pixel = 1; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_USHORT11: values_per_band = 2048; // 2 ^ 11 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_USHORT12: values_per_band = 4096; // 2 ^ 12 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_USHORT13: values_per_band = 8192; // 2 ^ 13 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_USHORT14: values_per_band = 16384; // 2 ^ 14 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_USHORT15: values_per_band = 32768; // 2 ^ 15 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT16: case OSSIM_SINT16: values_per_band = 65536; // 2 ^ 16 bytes_per_pixel = 2; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_UINT32: case OSSIM_SINT32: values_per_band = 65536; // 2 ^ 16 bytes_per_pixel = 4; theTableType = ossimTableRemapper::NATIVE; break; case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT: bytes_per_pixel = 4; break; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_DOUBLE: bytes_per_pixel = 8; theTableType = ossimTableRemapper::NORMALIZED; break; default: break; } theTableBinCount = values_per_band; theTableBandCount = BANDS; ossim_uint32 size_in_bytes = values_per_band * BANDS * bytes_per_pixel; theTable.resize(size_in_bytes); } } // End: ossimPiecwiseRemapper::getTableSize() // Private to disallow use... ossimPiecewiseRemapper::ossimPiecewiseRemapper(const ossimPiecewiseRemapper&) : m_dirty(true), m_remapType(UNKNOWN) { } // Private to disallow use... ossimPiecewiseRemapper& ossimPiecewiseRemapper::operator=(const ossimPiecewiseRemapper&) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimPixelFlipper.cpp000066400000000000000000001101051352751253100222750ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Filter to toggle pixel values. // //************************************************************************* // $Id: ossimPixelFlipper.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimPixelFlipper, "ossimPixelFlipper", ossimImageSourceFilter) static ossimTrace traceDebug("ossimPixelFlipper:debug"); const char ossimPixelFlipper::PF_TARGET_VALUE_KW[] = "target_value"; const char ossimPixelFlipper::PF_TARGET_RANGE_KW[] = "target_range"; const char ossimPixelFlipper::PF_REPLACEMENT_VALUE_KW[] = "replacement_value"; const char ossimPixelFlipper::PF_REPLACEMENT_MODE_KW[] = "replacement_mode"; const char ossimPixelFlipper::PF_CLAMP_VALUE_KW[] = "clamp_value"; // deprecated by clamp_value_hi const char ossimPixelFlipper::PF_CLAMP_VALUE_LO_KW[] = "clamp_value_lo"; const char ossimPixelFlipper::PF_CLAMP_VALUE_HI_KW[] = "clamp_value_hi"; const char ossimPixelFlipper::PF_CLIP_MODE_KW[] = "border_clip_mode"; static const char TARGET_LOWER_LIMIT_PROP_NAME[] = "target_range_lower_limit"; static const char TARGET_UPPER_LIMIT_PROP_NAME[] = "target_range_upper_limit"; #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimPixelFlipper.cpp 21631 2012-09-06 18:10:55Z dburken $"; #endif ossimPixelFlipper::ossimPixelFlipper(ossimObject *owner) : ossimImageSourceFilter(owner), theTargetValueLo(0.0), theTargetValueHi(0.0), theReplacementValue(1.0), theReplacementMode(ossimPixelFlipper::REPLACE_BAND_IF_TARGET), theClampValueLo(ossim::nan()), theClampValueHi(ossim::nan()), theClampingMode(DISABLED), theClipMode(NONE) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPixelFlipper::ossimPixelFlipper entered...\n"; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << "\n"; #endif } setDescription(ossimString("Pixel Flipper")); enableSource(); } ossimPixelFlipper::~ossimPixelFlipper() { } ossimRefPtr ossimPixelFlipper::getTile( const ossimIrect &tile_rect, ossim_uint32 resLevel) { if (!theInputConnection) { return 0; } // Fetch tile from pointer from the input source. ossimRefPtr inputTile = theInputConnection->getTile(tile_rect, resLevel); if (!inputTile.valid() || !isSourceEnabled()) return inputTile; if (!inputTile->getBuf()) return inputTile; // Lock for the length of this method. std::lock_guard scopeLock(theMutex); // Call the appropriate load method. switch (inputTile->getScalarType()) { case OSSIM_UCHAR: { flipPixels(ossim_uint8(0), inputTile.get(), resLevel); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { flipPixels(ossim_uint16(0), inputTile.get(), resLevel); break; } case OSSIM_SSHORT16: { flipPixels(ossim_sint16(0), inputTile.get(), resLevel); break; } case OSSIM_UINT32: { flipPixels(ossim_uint32(0), inputTile.get(), resLevel); break; } case OSSIM_SINT32: { flipPixels(ossim_sint32(0), inputTile.get(), resLevel); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { flipPixels(ossim_float32(0), inputTile.get(), resLevel); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: { flipPixels(ossim_float64(0), inputTile.get(), resLevel); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimPixelFlipper::getTile Unsupported scalar type!" << endl; break; } } inputTile->validate(); return inputTile; } template void ossimPixelFlipper::flipPixels(T /* dummy */, ossimImageData *inputTile, ossim_uint32 resLevel) { if (!inputTile) return; T targetLo = static_cast(theTargetValueLo); T targetHi = static_cast(theTargetValueHi); T replacement = static_cast(theReplacementValue); T clampLo = static_cast(theClampValueLo); T clampHi = static_cast(theClampValueHi); // Get pointers to data for each band. ossim_uint32 bands = inputTile->getNumberOfBands(); ossim_uint32 band; T **buf = new T *[bands]; for (band = 0; band < bands; ++band) buf[band] = static_cast(inputTile->getBuf(band)); ossimIrect rect = inputTile->getImageRectangle(); ossimIpt ul = rect.ul(); ossimIpt lr = rect.lr(); // Check the relation between tile rect and the area of interest (either bounding rect or // valid vertices polygons). If completely outside, we can return with empty buffer.get If // partially inside, we'll need to test individual pixels. bool is_outside_aoi = false; bool needsTesting = false; if ((theClipMode == BOUNDING_RECT) && (resLevel < theBoundingRects.size())) { if (!rect.intersects(theBoundingRects[resLevel])) is_outside_aoi = true; else needsTesting = !rect.completely_within(theBoundingRects[resLevel]); } else if ((theClipMode == VALID_VERTICES) && (resLevel < theValidVertices.size())) { bool ulFlag = theValidVertices[resLevel].isPointWithin(rect.ul()); bool urFlag = theValidVertices[resLevel].isPointWithin(rect.ur()); bool lrFlag = theValidVertices[resLevel].isPointWithin(rect.lr()); bool llFlag = theValidVertices[resLevel].isPointWithin(rect.ll()); if ((!ulFlag) && (!urFlag) && (!lrFlag) && (!llFlag)) is_outside_aoi = true; else needsTesting = !(ulFlag && urFlag && lrFlag && llFlag); } if (is_outside_aoi) { // none of the tile is inside so just return with empty tile: delete[] buf; return; } ossim_uint32 i = 0; // index into band buffers; ossimIpt pixel_loc; bool can_replace, found_candidate; // Begin loop over each pixel in the tile. The individual bands are handled inside this loop: for (pixel_loc.y = ul.y; pixel_loc.y <= lr.y; ++pixel_loc.y) { for (pixel_loc.x = ul.x; pixel_loc.x <= lr.x; ++pixel_loc.x) { // First consider if we need to test the pixel for border clipping: if (needsTesting) { bool is_inside = true; // Assume it will pass the border test if (theClipMode == BOUNDING_RECT) is_inside = theBoundingRects[resLevel].pointWithin(pixel_loc); else if (theClipMode == VALID_VERTICES) is_inside = theValidVertices[resLevel].isPointWithin(pixel_loc); if (!is_inside) { // Remap this pixel to the replacement value (all bands) for (band = 0; band < bands; ++band) buf[band][i] = replacement; // Proceed to next pixel location: ++i; continue; } } // If clamping specified, the target replacement function is disabled: if (theClampingMode) { switch (theReplacementMode) { case REPLACE_BAND_IF_TARGET: case REPLACE_ALL_BANDS_IF_ANY_TARGET: for (band = 0; band < bands; ++band) { if (!ossim::isnan(theClampValueLo) && (buf[band][i] < clampLo)) buf[band][i] = clampLo; else if (!ossim::isnan(theClampValueHi) && (buf[band][i] > clampHi)) buf[band][i] = clampHi; } break; case REPLACE_BAND_IF_PARTIAL_TARGET: case REPLACE_ALL_BANDS_IF_PARTIAL_TARGET: // First band loop to establish if pixel qualifies for replacement (at least one // band must be valid): can_replace = false; found_candidate = false; for (band = 0; (band < bands) && !(can_replace && found_candidate); ++band) { if ((!ossim::isnan(theClampValueLo) && (buf[band][i] < clampLo)) || (!ossim::isnan(theClampValueHi) && (buf[band][i] > clampHi))) found_candidate = true; else can_replace = true; } if (can_replace && found_candidate) { // This pixel has at least one band with normal value, so need to rescan bands // to find pixels that need replacing (are within the target range): for (band = 0; band < bands; ++band) { if (!ossim::isnan(theClampValueLo) && (buf[band][i] < clampLo)) buf[band][i] = clampLo; else if (!ossim::isnan(theClampValueHi) && buf[band][i] > clampHi) buf[band][i] = clampHi; } } break; case REPLACE_ONLY_FULL_TARGETS: // First band loop to establish if pixel qualifies for replacement (all // bands must be in target range): can_replace = true; for (band = 0; (band < bands) && can_replace; ++band) { if ((ossim::isnan(theClampValueLo) || (buf[band][i] >= clampLo)) && (ossim::isnan(theClampValueHi) || (buf[band][i] <= clampHi))) can_replace = false; } if (can_replace) { // Map all pixels to replacement value: for (band = 0; band < bands; ++band) { if (!ossim::isnan(theClampValueLo) && (buf[band][i] < clampLo)) buf[band][i] = clampLo; else if (!ossim::isnan(theClampValueHi) && buf[band][i] > clampHi) buf[band][i] = clampHi; } } break; } // close switch // Proceed to next pixel location: ++i; continue; } // If we got here (the continue statement was not reached) then // the pixel value now needs to be checked for possible target replacement: switch (theReplacementMode) { case REPLACE_BAND_IF_TARGET: for (band = 0; band < bands; ++band) { if ((buf[band][i] >= targetLo) && (buf[band][i] <= targetHi)) buf[band][i] = theReplacementValue; } break; case REPLACE_BAND_IF_PARTIAL_TARGET: // First band loop to establish if pixel qualifies for replacement (at least one // band must be valid): can_replace = false; found_candidate = false; for (band = 0; (band < bands) && !(can_replace && found_candidate); ++band) { // check for target range replacement qualification: if ((buf[band][i] < targetLo) || (buf[band][i] > targetHi)) can_replace = true; // Has valid band else found_candidate = true; // found band within target range } if (can_replace && found_candidate) { // This pixel has at least one band with normal value, so need to rescan bands // to find pixels that need replacing (are within the target range): for (band = 0; band < bands; ++band) { if ((buf[band][i] >= targetLo) && (buf[band][i] <= targetHi)) buf[band][i] = theReplacementValue; } } break; case REPLACE_ALL_BANDS_IF_PARTIAL_TARGET: // First band loop to establish if pixel qualifies for replacement (at least one // band must be valid): can_replace = false; found_candidate = false; for (band = 0; (band < bands) && !(can_replace && found_candidate); ++band) { // check for target range replacement qualification: if ((buf[band][i] < targetLo) || (buf[band][i] > targetHi)) can_replace = true; else found_candidate = true; } if (can_replace && found_candidate) { // This pixel has at least one band with normal value and one with target, so // map all bands to target: for (band = 0; band < bands; ++band) buf[band][i] = theReplacementValue; } break; case REPLACE_ONLY_FULL_TARGETS: // First band loop to establish if pixel qualifies for replacement (all // bands must be in target range): can_replace = true; for (band = 0; (band < bands) && can_replace; ++band) { // check for target range replacement qualification: if ((buf[band][i] < targetLo) || (buf[band][i] > targetHi)) can_replace = false; } if (can_replace) { // Map all pixels to replacement value: for (band = 0; band < bands; ++band) buf[band][i] = theReplacementValue; } break; case REPLACE_ALL_BANDS_IF_ANY_TARGET: // First band loop to establish if pixel qualifies for replacement (all // bands must be in target range): can_replace = false; for (band = 0; (band < bands) && !can_replace; ++band) { // check for target range replacement qualification: if ((buf[band][i] >= targetLo) && (buf[band][i] <= targetHi)) can_replace = true; } if (can_replace) { // Map all pixels to replacement value: for (band = 0; band < bands; ++band) buf[band][i] = theReplacementValue; } break; } // close switch // Reached end of processing for one pixel location. Increment the band buffers index: ++i; } // end of loop over pixel_loc.x } // end of loop over pixel_loc.y delete[] buf; inputTile->validate(); } template void ossimPixelFlipper::clipTile(T /* dummy */, ossimImageData *inputTile, ossim_uint32 resLevel) { if (theClipMode == NONE) { theClipTileBuffer = 0; return; } if (!inputTile) return; if (!inputTile->getBuf() || (inputTile->getDataObjectStatus() == OSSIM_EMPTY)) { return; } allocateClipTileBuffer(inputTile); if (theClipTileBuffer.valid()) { ossimIrect tileRect = inputTile->getImageRectangle(); // force to all nulls theClipTileBuffer->setDataObjectStatus(OSSIM_FULL); theClipTileBuffer->makeBlank(); switch (theClipMode) { case NONE: { break; } case BOUNDING_RECT: { if (resLevel < theBoundingRects.size()) { if (tileRect.completely_within(theBoundingRects[resLevel]) || theBoundingRects[resLevel].hasNans()) { return; } else { if (tileRect.intersects(theBoundingRects[resLevel])) { ossimIrect clipRect = tileRect.clipToRect(theBoundingRects[resLevel]); theClipTileBuffer->setImageRectangle(clipRect); theClipTileBuffer->loadTile(inputTile); inputTile->makeBlank(); inputTile->loadTile(theClipTileBuffer.get()); inputTile->validate(); } else { inputTile->makeBlank(); } } } break; } case VALID_VERTICES: { if (resLevel < theValidVertices.size()) { const ossimPolygon &p = theValidVertices[resLevel]; bool ulWithin = p.isPointWithin(tileRect.ul()); bool urWithin = p.isPointWithin(tileRect.ur()); bool lrWithin = p.isPointWithin(tileRect.lr()); bool llWithin = p.isPointWithin(tileRect.ll()); if (ulWithin && urWithin && lrWithin && llWithin) { return; } else if (!(ulWithin || // if none are in urWithin || lrWithin || llWithin)) { inputTile->makeBlank(); return; } else { ossimIpt ul = tileRect.ul(); ossimIpt origin; ossim_uint32 x = 0; ossim_uint32 y = 0; ossim_uint32 w = inputTile->getWidth(); ossim_uint32 h = inputTile->getHeight(); ossim_uint32 offset = 0; origin.y = ul.y; for (y = 0; y < h; ++y) { origin.x = ul.x; for (x = 0; x < w; ++x) { if (!p.isPointWithin(origin)) { inputTile->setNull(offset); } ++offset; ++origin.x; } ++origin.y; } } } break; } } } } void ossimPixelFlipper::allocateClipTileBuffer(ossimRefPtr inputImage) { if (inputImage.valid()) { bool needDupFlag = false; if (theClipTileBuffer.valid()) { if ((theClipTileBuffer->getScalarType() != inputImage->getScalarType()) || theClipTileBuffer->getNumberOfBands() != theClipTileBuffer->getNumberOfBands()) { needDupFlag = true; } else { theClipTileBuffer->setImageRectangle(inputImage->getImageRectangle()); } } else { needDupFlag = true; } if (needDupFlag) { theClipTileBuffer = (ossimImageData *)inputImage->dup(); } } } void ossimPixelFlipper::initialize() { std::lock_guard scopeLock(theMutex); ossimImageSourceFilter::initialize(); theValidVertices.clear(); theBoundingRects.clear(); ossim_uint32 rlevels = getNumberOfDecimationLevels(); ossim_uint32 idx = 0; if (rlevels) { if (theValidVertices.size() != rlevels) { theValidVertices.resize(rlevels); } if (theBoundingRects.size() != rlevels) { theBoundingRects.resize(rlevels); } for (idx = 0; idx < rlevels; ++idx) { std::vector validVertices; getValidImageVertices(validVertices, OSSIM_CLOCKWISE_ORDER, idx); theValidVertices[idx] = ossimPolygon(validVertices); theBoundingRects[idx] = getBoundingRect(idx); } } } ossimScalarType ossimPixelFlipper::getOutputScalarType() const { if (theInputConnection) { ossimScalarType scalar = theInputConnection->getOutputScalarType(); { if (scalar == OSSIM_USHORT16 && theClampValueHi == 2047.0) { //--- // Special case: // We have an unsigned 16 bit type but we want to call it // USHORT11 ( (2^11- 1) = 2047 ). //--- return OSSIM_USHORT11; } else if (scalar == OSSIM_USHORT16 && theClampValueHi == 4095.0) { //--- // Special case: // We have an unsigned 16 bit type but we want to call it // USHORT12 ( (2^12- 1) = 4095 ). //--- return OSSIM_USHORT12; } else if (scalar == OSSIM_USHORT16 && theClampValueHi == 8191.0) { //--- // Special case: // We have an unsigned 16 bit type but we want to call it // USHORT13 ( (2^13- 1) = 8191 ). //--- return OSSIM_USHORT13; } else if (scalar == OSSIM_USHORT16 && theClampValueHi == 16383.0) { //--- // Special case: // We have an unsigned 16 bit type but we want to call it // USHORT14 ( (2^14- 1) = 16383 ). //--- return OSSIM_USHORT14; } else if (scalar == OSSIM_USHORT16 && theClampValueHi == 32767.0) { //--- // Special case: // We have an unsigned 16 bit type but we want to call it // USHORT15 ( (2^15- 1) = 32767 ). //--- return OSSIM_USHORT15; } return scalar; } } return OSSIM_SCALAR_UNKNOWN; } ossim_float64 ossimPixelFlipper::getMaxPixelValue(ossim_uint32 band) const { const ossim_float64 MIN = ossimImageSourceFilter::getMinPixelValue(band); const ossim_float64 MAX = ossimImageSourceFilter::getMaxPixelValue(band); if ((theClampValueHi > MIN) && (theClampValueHi < MAX)) return theClampValueHi; return MAX; } ossim_float64 ossimPixelFlipper::getMinPixelValue(ossim_uint32 band) const { const ossim_float64 MIN = ossimImageSourceFilter::getMinPixelValue(band); const ossim_float64 MAX = ossimImageSourceFilter::getMaxPixelValue(band); if ((theClampValueLo > MIN) && (theClampValueLo < MAX)) return theClampValueLo; return MIN; } bool ossimPixelFlipper::loadState(const ossimKeywordlist &kwl, const char *prefix) { const char *lookupReturn; lookupReturn = kwl.find(prefix, PF_TARGET_VALUE_KW); if (lookupReturn) { setTargetValue(atof(lookupReturn)); } lookupReturn = kwl.find(prefix, PF_TARGET_RANGE_KW); if (lookupReturn) { ossimString min_max_string(lookupReturn); ossimString separator(" "); ossim_float64 min_target = min_max_string.before(separator).toFloat64(); ossim_float64 max_target = min_max_string.after(separator).toFloat64(); setTargetRange(min_target, max_target); } lookupReturn = kwl.find(prefix, PF_REPLACEMENT_VALUE_KW); if (lookupReturn) { setReplacementValue(atof(lookupReturn)); } lookupReturn = kwl.find(prefix, PF_REPLACEMENT_MODE_KW); if (lookupReturn) { ossimString modeString = lookupReturn; setReplacementMode(modeString); } lookupReturn = kwl.find(prefix, PF_CLAMP_VALUE_KW); if (lookupReturn) { setClampValue(atof(lookupReturn), true); } lookupReturn = kwl.find(prefix, PF_CLAMP_VALUE_LO_KW); if (lookupReturn) { setClampValue(atof(lookupReturn), false); } lookupReturn = kwl.find(prefix, PF_CLAMP_VALUE_HI_KW); if (lookupReturn) { setClampValue(atof(lookupReturn), true); } lookupReturn = kwl.find(prefix, PF_CLIP_MODE_KW); if (lookupReturn) { ossimString modeString = lookupReturn; setClipMode(modeString); } bool status = ossimImageSourceFilter::loadState(kwl, prefix); if (traceDebug()) { print(ossimNotify(ossimNotifyLevel_DEBUG)); } return status; } bool ossimPixelFlipper::saveState(ossimKeywordlist &kwl, const char *prefix) const { // Call the base class saveState. ossimImageSourceFilter::saveState(kwl, prefix); if (theTargetValueHi != theTargetValueLo) { ossimString s(ossimString::toString(theTargetValueLo) + " " + ossimString::toString(theTargetValueHi)); kwl.add(prefix, PF_TARGET_RANGE_KW, s); } else { kwl.add(prefix, PF_TARGET_VALUE_KW, theTargetValueLo); } kwl.add(prefix, PF_REPLACEMENT_VALUE_KW, theReplacementValue); kwl.add(prefix, PF_REPLACEMENT_MODE_KW, getReplacementModeString().c_str()); if (theClampingMode) { kwl.add(prefix, PF_CLAMP_VALUE_LO_KW, theClampValueLo); kwl.add(prefix, PF_CLAMP_VALUE_HI_KW, theClampValueHi); } kwl.add(prefix, PF_CLIP_MODE_KW, getClipModeString().c_str()); return true; } void ossimPixelFlipper::setTargetValue(ossim_float64 target_value) { //--- // Since this is the value to replace we will allow for any value as it // won't affect the output null, min and max ranges. This will fix a // tiled nitf with max of 2047(11bit) with edge tile fill values of 2048. //--- std::lock_guard scopeLock(theMutex); theTargetValueLo = target_value; theTargetValueHi = target_value; } void ossimPixelFlipper::setTargetRange(ossim_float64 target_min, ossim_float64 target_max) { //--- // Since this is the value to replace we will allow for any value as it // won't affect the output null, min and max ranges. This will fix a // tiled nitf with max of 2047(11bit) with edge tile fill values of 2048. //--- std::lock_guard scopeLock(theMutex); theTargetValueLo = target_min; theTargetValueHi = target_max; } void ossimPixelFlipper::setReplacementValue(ossim_float64 replacement_value) { std::lock_guard scopeLock(theMutex); // Range check to ensure within null, min and max of output radiometry. if (inRange(replacement_value)) { theReplacementValue = replacement_value; } } void ossimPixelFlipper::setClampValue(ossim_float64 clamp_value, bool clamp_max_value) { std::lock_guard scopeLock(theMutex); if (inRange(clamp_value)) { // Stupid MS compiler complains if we do an |= on enum type. (OLK 1/11) int temp_int = (int)theClampingMode; if (clamp_max_value) { theClampValueHi = clamp_value; temp_int |= (int)CLAMPING_HI; } else { theClampValueLo = clamp_value; temp_int |= (int)CLAMPING_LO; } theClampingMode = (ClampingMode)temp_int; } } void ossimPixelFlipper::setClampValues(ossim_float64 clamp_value_lo, ossim_float64 clamp_value_hi) { theClampingMode = DISABLED; // reset and let next calls set accordingly setClampValue(clamp_value_lo, false); setClampValue(clamp_value_hi, true); } void ossimPixelFlipper::setReplacementMode(ossimPixelFlipper::ReplacementMode mode) { std::lock_guard scopeLock(theMutex); theReplacementMode = mode; } bool ossimPixelFlipper::setReplacementMode(const ossimString &modeString) { std::lock_guard scopeLock(theMutex); ossimString mode = modeString; mode.upcase(); if (mode == "REPLACE_BAND_IF_TARGET") { theReplacementMode = REPLACE_BAND_IF_TARGET; } else if (mode == "REPLACE_BAND_IF_PARTIAL_TARGET") { theReplacementMode = REPLACE_BAND_IF_PARTIAL_TARGET; } else if (mode == "REPLACE_ALL_BANDS_IF_PARTIAL_TARGET") { theReplacementMode = REPLACE_ALL_BANDS_IF_PARTIAL_TARGET; } else if (mode == "REPLACE_ONLY_FULL_TARGETS") { theReplacementMode = REPLACE_ONLY_FULL_TARGETS; } else if (mode == "REPLACE_ALL_BANDS_IF_ANY_TARGET") { theReplacementMode = REPLACE_ALL_BANDS_IF_ANY_TARGET; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimPixelFlipper::setReplacementMode warning:\n" << "Invalid mode: " << modeString << endl; return false; } return true; } void ossimPixelFlipper::setClipMode(ossimPixelFlipper::ClipMode mode) { std::lock_guard scopeLock(theMutex); theClipMode = mode; } void ossimPixelFlipper::setClipMode(const ossimString &modeString) { ossimString mode = modeString; mode.downcase(); if (mode == "none") { setClipMode(NONE); } else if (mode == "bounding_rect") { setClipMode(BOUNDING_RECT); } else if (mode == "valid_vertices") { setClipMode(VALID_VERTICES); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimPixelFlipper::setClipMode warning:\n" << "Invalid mode: " << modeString << endl; } } //ossim_float64 ossimPixelFlipper::getTargetValue() const //{ // return theTargetValueLo; //} ossim_float64 ossimPixelFlipper::getReplacementValue() const { return theReplacementValue; } ossimPixelFlipper::ReplacementMode ossimPixelFlipper::getReplacementMode() const { return theReplacementMode; } ossimString ossimPixelFlipper::getReplacementModeString() const { switch (theReplacementMode) { case REPLACE_BAND_IF_TARGET: return ossimString("REPLACE_BAND_IF_TARGET"); case REPLACE_BAND_IF_PARTIAL_TARGET: return ossimString("REPLACE_BAND_IF_PARTIAL_TARGET"); case REPLACE_ALL_BANDS_IF_PARTIAL_TARGET: return ossimString("REPLACE_ALL_BANDS_IF_PARTIAL_TARGET"); case REPLACE_ONLY_FULL_TARGETS: return ossimString("REPLACE_ONLY_FULL_TARGETS"); case REPLACE_ALL_BANDS_IF_ANY_TARGET: return ossimString("REPLACE_ALL_BANDS_IF_ANY_TARGET"); default: break; } return ossimString("UNKNOWN_MODE"); } ossimString ossimPixelFlipper::getClipModeString() const { if (theClipMode == BOUNDING_RECT) return ossimString("bounding_rect"); if (theClipMode == VALID_VERTICES) return ossimString("valid_vertices"); return ossimString("none"); } ossimPixelFlipper::ClipMode ossimPixelFlipper::getClipMode() const { return theClipMode; } std::ostream &ossimPixelFlipper::print(std::ostream &out) const { out << "ossimPixelFlipper::print:" << "\ntarget value Lo: " << theTargetValueLo << "\ntarget value Hi: " << theTargetValueHi << "\nreplacement value: " << theReplacementValue << "\nclamp value Lo: " << theClampValueLo << "\nclamp value Hi: " << theClampValueHi << "\nreplacement mode: " << getReplacementModeString().c_str() << "\nclip_mode: " << getClipModeString().c_str() << endl; return out; } ossimRefPtr ossimPixelFlipper::getProperty( const ossimString &name) const { // Lock for the length of this method. std::lock_guard scopeLock(theMutex); if (name == PF_TARGET_VALUE_KW) { ossimProperty *p = new ossimNumericProperty(name, ossimString::toString(theTargetValueLo)); p->setCacheRefreshBit(); return ossimRefPtr(p); } if (name == PF_TARGET_RANGE_KW) { ossimProperty *p = new ossimNumericProperty(name, ossimString::toString(theTargetValueLo)); p->setCacheRefreshBit(); return ossimRefPtr(p); } if (name == TARGET_UPPER_LIMIT_PROP_NAME) { ossimProperty *p = new ossimNumericProperty(name, ossimString::toString(theTargetValueHi)); p->setCacheRefreshBit(); return ossimRefPtr(p); } else if (name == PF_REPLACEMENT_VALUE_KW) { ossimProperty *p = new ossimNumericProperty(name, ossimString::toString(theReplacementValue)); p->setCacheRefreshBit(); return ossimRefPtr(p); } else if (name == PF_CLAMP_VALUE_LO_KW) { ossimProperty *p = new ossimNumericProperty(name, ossimString::toString(theClampValueLo)); p->setCacheRefreshBit(); return ossimRefPtr(p); } else if (name == PF_CLAMP_VALUE_HI_KW) { ossimProperty *p = new ossimNumericProperty(name, ossimString::toString(theClampValueHi)); p->setCacheRefreshBit(); return ossimRefPtr(p); } else if (name == PF_REPLACEMENT_MODE_KW) { vector constraintList(5); constraintList[0] = "REPLACE_BAND_IF_TARGET"; constraintList[1] = "REPLACE_BAND_IF_PARTIAL_TARGET"; constraintList[2] = "REPLACE_ALL_BANDS_IF_PARTIAL_TARGET"; constraintList[3] = "REPLACE_ONLY_FULL_TARGETS"; constraintList[4] = "REPLACE_ALL_BANDS_IF_ANY_TARGET"; ossimStringProperty *p = new ossimStringProperty(name, getReplacementModeString(), false, constraintList); p->setCacheRefreshBit(); return ossimRefPtr(p); } else if (name == PF_CLIP_MODE_KW) { vector constraintList(3); constraintList[0] = "none"; constraintList[1] = "bounding_rect"; constraintList[2] = "valid_vertices"; ossimStringProperty *p = new ossimStringProperty(name, getClipModeString(), false, constraintList); p->setCacheRefreshBit(); return ossimRefPtr(p); } ossimRefPtr result = ossimSource::getProperty(name); if (result.valid()) { if (result->getName() == ossimKeywordNames::ENABLED_KW) { result->clearChangeType(); // we will at least say its a radiometric change // result->setCacheRefreshBit(); } } return result; } void ossimPixelFlipper::setProperty(ossimRefPtr property) { if (!property) return; ossimString os = property->valueToString(); ossimString name = property->getName(); if (name == PF_TARGET_VALUE_KW) { setTargetValue(os.toDouble()); } if (name == TARGET_LOWER_LIMIT_PROP_NAME) { setTargetRange(os.toDouble(), theTargetValueHi); } if (name == TARGET_UPPER_LIMIT_PROP_NAME) { setTargetRange(theTargetValueLo, os.toDouble()); } else if (name == PF_REPLACEMENT_VALUE_KW) { setReplacementValue(os.toDouble()); } else if (name == PF_REPLACEMENT_MODE_KW) { setReplacementMode(os); } else if (name == PF_CLAMP_VALUE_LO_KW) { setClampValue(os.toDouble(), false); } else if (name == PF_CLAMP_VALUE_HI_KW) { setClampValue(os.toDouble(), true); } else if (name == PF_CLIP_MODE_KW) { setClipMode(os); } else { ossimImageSourceFilter::setProperty(property); } } void ossimPixelFlipper::getPropertyNames( std::vector &propertyNames) const { propertyNames.push_back(PF_TARGET_VALUE_KW); propertyNames.push_back(TARGET_LOWER_LIMIT_PROP_NAME); propertyNames.push_back(TARGET_UPPER_LIMIT_PROP_NAME); propertyNames.push_back(PF_REPLACEMENT_VALUE_KW); propertyNames.push_back(PF_REPLACEMENT_MODE_KW); propertyNames.push_back(PF_CLAMP_VALUE_LO_KW); propertyNames.push_back(PF_CLAMP_VALUE_HI_KW); propertyNames.push_back(PF_CLIP_MODE_KW); ossimImageSourceFilter::getPropertyNames(propertyNames); } ossimString ossimPixelFlipper::getShortName() const { return ossimString("Pixel flipper"); } bool ossimPixelFlipper::inRange(ossim_float64 value) const { if (!theInputConnection) { //--- // Not initialized yet... We're going to return true so that things // like loadState work with the assumption that the caller know's // the correct range. This check is really intended for an uncheck // range on the gui side. //--- return true; } const ossim_float64 NULL_PIX = ossimImageSourceFilter::getNullPixelValue(); const ossim_float64 MIN_PIX = ossimImageSourceFilter::getMinPixelValue(); const ossim_float64 MAX_PIX = ossimImageSourceFilter::getMaxPixelValue(); if ((value == NULL_PIX) || ((value >= MIN_PIX) && (value <= MAX_PIX))) { return true; } ossimNotify(ossimNotifyLevel_WARN) << "\nossimPixelFlipper::inRange WARNING:" << "\nvalue \"" << value << "\" is out of range!" << "\nInput source null = " << NULL_PIX << "\nInput source min = " << MIN_PIX << "\nInput source max = " << MAX_PIX << endl; return false; } ossim-Miami-2.9.1/src/imaging/ossimPolyCutter.cpp000066400000000000000000000233011352751253100220050ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimPolyCutter.cpp 21518 2012-08-22 21:15:56Z dburken $ #include #include #include #include #include #include #include static const char* NUMBER_POLYGONS_KW = "number_polygons"; using namespace std; RTTI_DEF1(ossimPolyCutter, "ossimPolyCutter", ossimImageSourceFilter) ossimPolyCutter::ossimPolyCutter() : ossimImageSourceFilter(), theTile(NULL), theCutType(OSSIM_POLY_NULL_OUTSIDE), m_boundingOverwrite(false) { thePolygonList.push_back(ossimPolygon()); theBoundingRect.makeNan(); } // ossimPolyCutter::ossimPolyCutter(ossimImageSource* inputSource, // ossimPolyArea2d* polygon) ossimPolyCutter::ossimPolyCutter(ossimImageSource* inputSource, const ossimPolygon& polygon) : ossimImageSourceFilter(inputSource), theTile(NULL), theCutType(OSSIM_POLY_NULL_INSIDE), m_boundingOverwrite(false) { thePolygonList.push_back(polygon); computeBoundingRect(); initialize(); } ossimPolyCutter::~ossimPolyCutter() { } ossimRefPtr ossimPolyCutter::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return theTile; } ossimRefPtr input = theInputConnection->getTile(tileRect, resLevel); if(!isSourceEnabled() || theBoundingRect.hasNans() || !input.valid()) { return input; } if((input->getDataObjectStatus() == OSSIM_EMPTY) || (input->getDataObjectStatus() == OSSIM_NULL)) { return input; } if(!theTile.valid()) { allocate(); // First time through... } if(!theTile.valid()) { return input; } theTile->setImageRectangle(tileRect); theTile->loadTile(input.get()); theTile->setDataObjectStatus(input->getDataObjectStatus()); vector* polyList = &thePolygonList; vector scaledPoly; ossimIrect boundingRect = getBoundingRect(resLevel); if(resLevel) { ossimDpt decimation; getDecimationFactor(resLevel, decimation); if(!decimation.hasNans()) { for(int polyIndex = 0; polyIndex < (int)thePolygonList.size(); ++polyIndex) { scaledPoly.push_back(thePolygonList[polyIndex]*decimation); } polyList = &scaledPoly; } } if(polyList->size()&& theTile->getDataObjectStatus()!=OSSIM_NULL) { // ossimActiveEdgeTable aet; if(theCutType == OSSIM_POLY_NULL_OUTSIDE) { if(boundingRect.intersects(tileRect)) { theTile->makeBlank(); theHelper.setImageData(theTile.get()); for(int polyIndex = 0; polyIndex < (int)polyList->size(); ++polyIndex) { theHelper.copyInputToThis(input->getBuf(), (*polyList)[polyIndex]); } theTile->validate(); } else { theTile->makeBlank(); } } else if(theCutType == OSSIM_POLY_NULL_INSIDE) { if(boundingRect.intersects(tileRect)) { theHelper.setImageData(theTile.get()); for(int polyIndex = 0; polyIndex < (int)polyList->size(); ++polyIndex) { theHelper.fill(theTile->getNullPix(), (*polyList)[polyIndex]); } } theTile->validate(); } } return theTile; } ossimIrect ossimPolyCutter::getBoundingRect(ossim_uint32 resLevel)const { ossimIrect result; result.makeNan(); if(!theInputConnection) { return result; } if(!isSourceEnabled()) { return ossimImageSourceFilter::getBoundingRect(resLevel); } result = theInputConnection->getBoundingRect(resLevel); if(isSourceEnabled()&&(!theBoundingRect.hasNans())) { if(theCutType == OSSIM_POLY_NULL_OUTSIDE) { ossimDpt decimation; getDecimationFactor(resLevel, decimation); if(decimation.hasNans()) { result = theBoundingRect; } else { result = theBoundingRect*decimation; } } } else if(isSourceEnabled()) { return theBoundingRect; } return result; } void ossimPolyCutter::initialize() { // Capture the input connection. ossimImageSourceFilter::initialize(); // Force an allocate on next getTile. theTile = NULL; } void ossimPolyCutter::allocate() { theTile=NULL; if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, theInputConnection); theTile->initialize(); } } bool ossimPolyCutter::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString newPrefix = prefix; for(int i = 0; i < (int)thePolygonList.size();++i) { newPrefix = ossimString(prefix) + "polygon" + ossimString::toString(i)+"."; thePolygonList[i].saveState(kwl, newPrefix.c_str()); } kwl.add(prefix, NUMBER_POLYGONS_KW, (int)thePolygonList.size(), true); ossimString fillType = "null_inside"; if(theCutType == OSSIM_POLY_NULL_OUTSIDE) { fillType = "null_outside"; } kwl.add(prefix, "cut_type", fillType.c_str(), true); return ossimImageSourceFilter::saveState(kwl, prefix);; } bool ossimPolyCutter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* numberPolygons = kwl.find(prefix, NUMBER_POLYGONS_KW); ossimString newPrefix; if(numberPolygons) { thePolygonList.clear(); int npolys = ossimString(numberPolygons).toLong(); for(int i = 0; i < npolys;++i) { thePolygonList.push_back(ossimPolygon()); newPrefix = ossimString(prefix) + "polygon" + ossimString::toString(i)+"."; thePolygonList[i].loadState(kwl, newPrefix.c_str()); } } const char* lookup = kwl.find(prefix, "cut_type"); if(lookup) { theCutType = OSSIM_POLY_NULL_INSIDE; ossimString test = lookup; if(test == "null_outside") { theCutType = OSSIM_POLY_NULL_OUTSIDE; } } else { theCutType = OSSIM_POLY_NULL_OUTSIDE; } computeBoundingRect(); return ossimImageSourceFilter::loadState(kwl, prefix); } void ossimPolyCutter::setPolygon(const vector& polygon, ossim_uint32 index) { if(index < polygon.size()) { thePolygonList[index] = polygon; computeBoundingRect(); } } void ossimPolyCutter::setPolygon(const vector& polygon, ossim_uint32 index) { if(polygon.size()) { thePolygonList[index] = polygon; computeBoundingRect(); } } void ossimPolyCutter::addPolygon(const vector& polygon) { thePolygonList.push_back(ossimPolygon(polygon)); computeBoundingRect(); } void ossimPolyCutter::addPolygon(const vector& polygon) { thePolygonList.push_back(ossimPolygon(polygon)); computeBoundingRect(); } void ossimPolyCutter::addPolygon(const ossimPolygon& polygon) { thePolygonList.push_back(ossimPolygon(polygon)); computeBoundingRect(); } void ossimPolyCutter::setCutType(ossimPolyCutterCutType cutType) { theCutType = cutType; } ossimPolyCutter::ossimPolyCutterCutType ossimPolyCutter::getCutType()const { return theCutType; } void ossimPolyCutter::clear() { setNumberOfPolygons(0); } void ossimPolyCutter::setProperty(ossimRefPtr property) { ossimImageSourceFilter::setProperty(property); } ossimRefPtr ossimPolyCutter::getProperty(const ossimString& name)const { return ossimImageSourceFilter::getProperty(name); } void ossimPolyCutter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); } void ossimPolyCutter::computeBoundingRect() { ossimIrect bounds; theBoundingRect.makeNan(); for(int i = 0; i < (int)thePolygonList.size(); ++i) { thePolygonList[i].getBoundingRect(bounds); if(!bounds.hasNans()) { if(theBoundingRect.hasNans()) { theBoundingRect = bounds; } else { theBoundingRect = theBoundingRect.combine(bounds); } } } } const ossimIrect& ossimPolyCutter::getRectangle() const { return theBoundingRect; } void ossimPolyCutter::setRectangle(const ossimIrect& rect) { theBoundingRect = rect; m_boundingOverwrite = true; } void ossimPolyCutter::setNumberOfPolygons(ossim_uint32 count) { if(!count) { thePolygonList.clear(); thePolygonList.clear(); } else { thePolygonList.resize(count); } } std::vector& ossimPolyCutter::getPolygonList() { return thePolygonList; } const std::vector& ossimPolyCutter::getPolygonList()const { return thePolygonList; } ossim-Miami-2.9.1/src/imaging/ossimQbTileFilesHandler.cpp000066400000000000000000000270251352751253100233430ustar00rootroot00000000000000//************************************************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: Image handler used for tiled Quickbird imagery. // //************************************************************************************************* // $Id: ossimQbTileFilesHandler.cpp 2814 2011-07-05 13:40:16Z oscar.kramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimQbTileFilesHandler, "ossimQbTileFilesHandler", ossimTiledImageHandler) // Static trace for debugging static ossimTrace traceDebug("ossimQbTileFilesHandler:debug"); //************************************************************************************************* //! Constructor (default): //************************************************************************************************* ossimQbTileFilesHandler::ossimQbTileFilesHandler() { } //************************************************************************************************* //! Destructor: //************************************************************************************************* ossimQbTileFilesHandler::~ossimQbTileFilesHandler() { } //************************************************************************************************* //! Opens the image file given entry index. This class does not support multiple entries. //! @param imageFile File to open. //! @param entryIndex //! @return false if entry index other than 0 specified. //************************************************************************************************* bool ossimQbTileFilesHandler::open() { static const char* MODULE = "ossimQbTileFilesHandler::open() -- "; if (traceDebug()) { ossimNotify(ossimNotifyLevel_INFO) <"<open(tilefile.tileFilename); if (tilefile.imageHandler.valid()) { // Valid handler, populate remaining items of interest and push it on our list... // Fetch image coordinates in full-view: subImageRect.set_ulx((*qbt_iter).second.theUlXOffset); subImageRect.set_uly((*qbt_iter).second.theUlYOffset); subImageRect.set_lrx((*qbt_iter).second.theLrXOffset); subImageRect.set_lry((*qbt_iter).second.theLrYOffset); tilefile.subImageRects.push_back(subImageRect); // Update bounding image rectangle: m_fullImgRect = m_fullImgRect.combine(subImageRect); m_tileFiles.push_back(tilefile); if (traceDebug()) { ossimNotify(ossimNotifyLevel_INFO)< on" "to tile-files list."< as one of the tiles, but the file could not be opened. " <<"This is being ignored but may cause a problem downstream."<"< ossimQbTileFilesHandler::getImageGeometry() { if ( !theGeometry ) { // Try external geom first: theGeometry = getExternalImageGeometry(); if ( !theGeometry ) { theGeometry = new ossimImageGeometry; // The dataset is expected to have an RPC model associated with it: ossimRefPtr model = new ossimQuickbirdRpcModel(this); if (!model->getErrorStatus()) { theGeometry->setProjection(model.get()); } else { // Check for map projected data: ossimFilename imd_file = theImageFile; imd_file.setExtension("IMD"); if ( imd_file.exists() == false ) { imd_file.setExtension("imd"); } if ( imd_file.exists() ) { ossimQuickbirdMetaData md; ossimKeywordlist kwl; if ( md.getMapProjectionKwl( imd_file, kwl ) == true ) { ossimRefPtr proj = ossimProjectionFactoryRegistry::instance()-> createProjection( kwl, 0 ); if ( proj.valid() == true ) { theGeometry->setProjection( proj.get() ); } } } } if ( (m_fullImgRect.ul().x != 0) || (m_fullImgRect.ul().y != 0) ) { // Set sub image offset. ossimRefPtr xfrm = new ossim2dTo2dShiftTransform( m_fullImgRect.ul() ); theGeometry->setTransform( xfrm.get() ); } } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } return theGeometry; } //************************************************************************************************* //! Initializes tile image rects by considering adjacent row/col offsets. Called when TIL //! doesn't contain the info. Returns true if successful. //************************************************************************************************* bool ossimQbTileFilesHandler::computeImageRects() { try { ossimQuickbirdMetaData oqmd; if (!oqmd.open(theImageFile)) throw 1; ossimIpt image_size (oqmd.getImageSize()); if (image_size.hasNans()) throw 2; ossimIpt full_image_lr (image_size.x-1, image_size.y-1); m_fullImgRect.set_ulx(0); m_fullImgRect.set_uly(0); m_fullImgRect.set_lr(full_image_lr); // Now consider the subrects for each tile. It is assumed that all tiles (except right // and bottom) will be of uniform size. The TIL file should have at least provided the row // and column offsets for each tile into the full image. This is equivalent to the UL corner. // It is presumed that the TIL failed to provide the LR corner since this method was called. int dx=0, dy=0, i=0; int num_tiles = (int) m_tileFiles.size(); while (((dx == 0) || (dy == 0)) && (i < num_tiles-1)) { if (dx == 0) dx = m_tileFiles[i+1].subImageRects[0].ul().x - m_tileFiles[i].subImageRects[0].ul().x; if (dy == 0) dy = m_tileFiles[i+1].subImageRects[0].ul().y - m_tileFiles[i].subImageRects[0].ul().y; ++i; } // We should have the nominal tile size now. Check this is so: if ((dx == 0) || (dy == 0)) { // Prior scheme failed for establishing the tile dimensions. Final resort is to open the first // available tile file and query its dimensions: if (num_tiles == 0) throw 3; if (m_tileFiles[0].imageHandler.valid()) { // we have an open handler, so just query it: dy = m_tileFiles[0].imageHandler->getNumberOfLines(); dx = m_tileFiles[0].imageHandler->getNumberOfSamples(); } else { // Struck out, just assume the tile is square: if ((dx == 0) && (dy == 0)) throw 4; if (dy == 0) dy = dx; else dx = dy; } } // Loop over all tiles to properly assign their image rectangles: for (i=0; i full_image_lr.x) lr.x = full_image_lr.x; if (lr.y > full_image_lr.y) lr.y = full_image_lr.y; m_tileFiles[i].subImageRects[0].set_lr(lr); } } catch (...) { // Could not establish the rectangles: return false; } return true; } ossim-Miami-2.9.1/src/imaging/ossimQuickbirdNitfTileSource.cpp000066400000000000000000000106651352751253100244410ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // //******************************************************************* // $Id: ossimQuickbirdNitfTileSource.cpp 22836 2014-07-25 15:13:47Z dburken $ #include #include #include #include #include #include #include RTTI_DEF1(ossimQuickbirdNitfTileSource, "ossimQuickbirdNitfTileSource", ossimNitfTileSource); static const ossimTrace traceDebug("ossimQuickbirdNitfTileSource:debug"); bool ossimQuickbirdNitfTileSource::open() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdNitfTileSource::open(file) DEBUG: entered ..." << std::endl; } ossimFilename file = theImageFile; file = file.replaceAllThatMatch("_R[0-9]+C[0-9]+"); ossimQuickbirdTile tileFile; bool openedTileFile = false; file.setExtension("TIL"); if(!tileFile.open(file)) { file.setExtension("TIL"); if(tileFile.open(file)) { openedTileFile = true; } else { file.setExtension("til"); if(tileFile.open(file)) { openedTileFile = true; } } } else { openedTileFile = true; } if(openedTileFile) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdNitfTileSource::open(file) DEBUG:" << "\nOpened tile file" << std::endl; } // Call the base class open... if(!ossimNitfTileSource::open()) { return false; } ossimQuickbirdTileInfo info; ossimIrect tempBounds = getCurrentImageHeader()->getImageRect(); tempBounds = ossimIrect(0, 0, tempBounds.width() - 1, tempBounds.height() - 1); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdNitfTileSource::open(file) DEBUG:" << "\nheader rectangle = " << tempBounds << std::endl; } ossimIpt ulPt; ossimIpt urPt; ossimIpt lrPt; ossimIpt llPt; ossimDpt shift; if(tileFile.getInfo(info, theImageFile.file().upcase())) { ulPt.makeNan(); urPt.makeNan(); lrPt.makeNan(); llPt.makeNan(); if((info.theUlXOffset != OSSIM_INT_NAN) && (info.theUlYOffset != OSSIM_INT_NAN)) { shift = ossimIpt(info.theUlXOffset, info.theUlYOffset); } else { shift = ossimIpt(0,0); } m_transform = new ossim2dTo2dShiftTransform(shift); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdNitfTileSource::open(file) DEBUG:" << "\nUl = " << ulPt << "\nUr = " << urPt << "\nLr = " << lrPt << "\nLl = " << llPt << "\ntheImageRect: " << getImageRectangle(0) << "\nExiting..." << std::endl; } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdNitfTileSource::open(file) DEBUG" << "Not opened..." << std::endl; } } return openedTileFile; } ossimRefPtr ossimQuickbirdNitfTileSource::getImageGeometry() { ossimRefPtr result = ossimImageHandler::getImageGeometry(); if( result.valid() ) { if(!result->getTransform()) { result->setTransform(m_transform.get()); } } return result; } bool ossimQuickbirdNitfTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimNitfTileSource::saveState( kwl, prefix ); } bool ossimQuickbirdNitfTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossimNitfTileSource::loadState( kwl, prefix ); } ossim-Miami-2.9.1/src/imaging/ossimQuickbirdTiffTileSource.cpp000066400000000000000000000134651352751253100244320ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: See top level LICENSE.txt file. // // Author: David Burken // // Copied from ossimQuickbirdTiffTileSource written by Garrett Potts. // // Description: // // Class definition for specialized image handler to pick up offsets from // Quick Bird ".TIL" files. // //---------------------------------------------------------------------------- // $Id: ossimQuickbirdTiffTileSource.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimQuickbirdTiffTileSource, "ossimQuickbirdTiffTileSource", ossimTiffTileSource); static const ossimTrace traceDebug("ossimQuickbirdTiffTileSource:debug"); //************************************************************************************************* // Checks for presence of required info before flagging successful open //************************************************************************************************* bool ossimQuickbirdTiffTileSource::open() { static const char M[] = "ossimQuickbirdTiffTileSource::open()"; bool result = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " ENTERED ..." << std::endl; } m_tileInfoFilename = theImageFile.noExtension().replaceAllThatMatch("_R[0-9]+C[0-9]+"); // QB is recognized by the presence of a tile info file. Fail if not present: m_tileInfoFilename.setExtension("TIL"); if ( !m_tileInfoFilename.exists() ) { m_tileInfoFilename.setExtension("til"); } if ( m_tileInfoFilename.exists() ) { // Call the base class open... result = ossimTiffTileSource::open(); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " result=" << (result?"true\n":"false\n"); } return result; } //************************************************************************************************* // I know what I am. I am a Quickbird TIFF image. I may be standalone or tiled with row-column // designation in the file name. My projection information is available (possibly) in an // accompanying RPC file and/or internal TIF tag, and my transform info (sub-image offset) is // available in a TILE info file (*.til) or internal TIF tag. Therefore, I (and not some outside // factory) am best qualified for establishing my image geometry. //************************************************************************************************* ossimRefPtr ossimQuickbirdTiffTileSource::getImageGeometry() { if ( !theGeometry ) { //--- // Check factory for external geom: //--- theGeometry = getExternalImageGeometry(); if ( !theGeometry ) { theGeometry = new ossimImageGeometry(); // Fetch the tile info for this particular image: if ( m_tileInfoFilename.size() ) { ossimQuickbirdTile tileFile; if ( tileFile.open(m_tileInfoFilename) ) { ossimQuickbirdTileInfo info; bool infoStatus = tileFile.getInfo(info, theImageFile.file().upcase()); if ( !infoStatus ) { infoStatus = tileFile.getInfo(info, theImageFile.file().downcase()); } if ( infoStatus ) { // Next is the projection part of the image geometry. This should be available // as an external RPC file or internal RPC's in the tiff file. Otherwise use // the map projection specified in the // tiff file: theGeometry->setProjection(0); ossimRefPtr model = new ossimQuickbirdRpcModel; if (model->parseFile(theImageFile)) { //--- // If RPC projection set the sub-image offset: // Establish sub-image offset (shift) for this tile: //--- ossimDpt shift(0,0); if ((info.theUlXOffset != OSSIM_INT_NAN) && (info.theUlYOffset != OSSIM_INT_NAN)) shift = ossimIpt(info.theUlXOffset, info.theUlYOffset); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdTiffTileSource::open() DEBUG:" << "\nSub image offset = " << shift << std::endl; } // Create the transform and set it in the geometry object: ossimRefPtr transform = new ossim2dTo2dShiftTransform(shift); theGeometry->setTransform(transform.get()); theGeometry->setProjection(model.get()); } else { // Last resort to a projection factory: ossimRefPtr proj = ossimProjectionFactoryRegistry::instance()->createProjection(this); if (proj.valid()) theGeometry->setProjection(proj.get()); } } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } } } } return theGeometry; } ossim-Miami-2.9.1/src/imaging/ossimRLevelFilter.cpp000066400000000000000000000173101352751253100222350ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRLevelFilter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include static const char* CURRENT_RLEVEL_KW = "current_rlevel"; static const char* OVERRIDE_GEOMETRY_KW = "override_geometry"; static ossimTrace traceDebug("ossimRLevelFilter:debug"); RTTI_DEF1(ossimRLevelFilter, "ossimRLevelFilter", ossimImageSourceFilter); //************************************************************************************************** ossimRLevelFilter::ossimRLevelFilter() : ossimImageSourceFilter(), theCurrentRLevel(0), theOverrideGeometryFlag(false) { } //************************************************************************************************** ossimRLevelFilter::~ossimRLevelFilter() { } //************************************************************************************************** void ossimRLevelFilter::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { if(!theInputConnection) { result.makeNan(); } theInputConnection->getDecimationFactor(resLevel, result); } //************************************************************************************************** bool ossimRLevelFilter::getOverrideGeometryFlag() const { return theOverrideGeometryFlag; } //************************************************************************************************** void ossimRLevelFilter::setOverrideGeometryFlag(bool override) { theOverrideGeometryFlag = override; } //************************************************************************************************** void ossimRLevelFilter::setCurrentRLevel(ossim_uint32 rlevel) { theCurrentRLevel = rlevel; updateGeometry(); } //************************************************************************************************** ossim_uint32 ossimRLevelFilter::getCurrentRLevel()const { return theCurrentRLevel; } //************************************************************************************************** // Returns a pointer reference to the active image geometry at this filter. The input source // geometry is modified, so we need to maintain our own geometry object as a data member. //************************************************************************************************** ossimRefPtr ossimRLevelFilter::getImageGeometry() { // Have we already defined our own geometry? Return it if so: if (m_ScaledGeometry.valid()) return m_ScaledGeometry; if (!theInputConnection) return ossimRefPtr(); ossim_uint32 rlevel = getCurrentRLevel(); ossimRefPtr inputGeom = theInputConnection->getImageGeometry(); // If no scaling is happening, just return the input image geometry: if ((!inputGeom) || (rlevel == 0) || (getEnableFlag() == false)) return inputGeom; // Need to create a copy of the input geom and modify it as our own, then pass that: m_ScaledGeometry = new ossimImageGeometry(*inputGeom); updateGeometry(); // Return our version of the image geometry: return m_ScaledGeometry; } //************************************************************************************************** //! If this object is maintaining an ossimImageGeometry, this method needs to be called after //! a scale change so that the geometry's projection is modified accordingly. //************************************************************************************************** void ossimRLevelFilter::updateGeometry() { if (m_ScaledGeometry.valid()) { // Modify the image geometry's projection with the scale factor before returning geom: ossimProjection* proj = m_ScaledGeometry->getProjection(); ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, proj);; if(mapProj) { ossimDpt decimation; getDecimationFactor(theCurrentRLevel, decimation); decimation.x = 1.0/decimation.x; decimation.y = 1.0/decimation.y; // This will adjust both the scale and the tie point to account for decimation. mapProj->applyScale(decimation, true); // recenter tie point flag } } } //************************************************************************************************** void ossimRLevelFilter::getSummedDecimation(ossimDpt& result) const { // Start with fresh values. result.x = 0.0; result.y = 0.0; ossim_uint32 rlevel = getCurrentRLevel(); if (rlevel == 0) { return; // no decimation. } // Sum the decimations from rlevel one to the current rlevel. for (ossim_uint32 i = 1; i <= rlevel; ++i) { ossimDpt dpt; getDecimationFactor(i, dpt); if (dpt.hasNans()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimRLevelFilter::getSummedDecimation WARNING:" << "\nNans returned from getDecimationFactor!" << std::endl; result.makeNan(); return; } result.x += dpt.x; result.y += dpt.y; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRLevelFilter::getSummedDecimation result: " << result << std::endl; } } //************************************************************************************************** ossimIrect ossimRLevelFilter::getBoundingRect(ossim_uint32 resLevel)const { ossimIrect rect; rect.makeNan(); if(!theInputConnection) return rect; if (isSourceEnabled()) { return theInputConnection->getBoundingRect(theCurrentRLevel); } return theInputConnection->getBoundingRect(resLevel); } //************************************************************************************************** ossimRefPtr ossimRLevelFilter::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return 0; } if(!isSourceEnabled()) { return theInputConnection->getTile(tileRect, resLevel); } // Ignoring resLevel as we're in charge of it here! return theInputConnection->getTile(tileRect, theCurrentRLevel); } //************************************************************************************************** bool ossimRLevelFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* current = kwl.find(prefix, CURRENT_RLEVEL_KW); const char* override = kwl.find(prefix, OVERRIDE_GEOMETRY_KW); if(current) theCurrentRLevel = ossimString(current).toULong(); if(override) theOverrideGeometryFlag = ossimString(override).toBool(); return ossimImageSourceFilter::loadState(kwl, prefix); // An existing image geometry object here will need to be updated: updateGeometry(); } //************************************************************************************************** bool ossimRLevelFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, CURRENT_RLEVEL_KW, theCurrentRLevel, true); kwl.add(prefix, OVERRIDE_GEOMETRY_KW, (ossim_uint32)theOverrideGeometryFlag, true); return ossimImageSourceFilter::saveState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimRangeDomeTileSource.cpp000066400000000000000000000245441352751253100235450ustar00rootroot00000000000000/* * ossimRangeDomeTileSource.cpp * * Created on: Aug 3, 2015 * Author: okramer */ #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimRangeDomeTileSource, "ossimRangeDomeTileSource", ossimImageHandler); const ossimString ossimRangeDomeTileSource::OSSIM_RANGE_DOME_SPEC_MAGIC_NUMBER ("OSSIM_RANGE_DOMES"); ossimRangeDome::ossimRangeDome(vector& tokens) : valid (false), id (0), radiusMeters (0), radiusPixelsSq (0), classification (UNASSIGNED), startAz (0), endAz (0) { if ((tokens.size() < 6) || (tokens[0].size() && (tokens[0].chars()[0] == '#'))) return; ossim_uint32 i = 0; id = tokens[i++].toUInt32(); centerGpt.lat = tokens[i++].toDouble(); centerGpt.lon = tokens[i++].toDouble(); centerGpt.hgt = tokens[i++].toDouble(); radiusMeters = tokens[i++].toDouble(); classification = (Classification) tokens[i++].toInt32(); valid = true; if (tokens.size() >= 8) { startAz = tokens[i++].toDouble(); endAz = tokens[i++].toDouble(); if (endAz == 360.0) endAz = 0.0; } if ( tokens.size()-i ) { description = tokens[i]; description.trim(); } } ossimGrect ossimRangeDome::boundingRect() const { ossimDpt scale = centerGpt.metersPerDegree(); double dlat = radiusMeters/scale.y; double dlon = radiusMeters/scale.x; return ossimGrect(centerGpt.lat+dlat, centerGpt.lon-dlon, centerGpt.lat-dlat, centerGpt.lon+dlon); } ossimRangeDomeTileSource::ossimRangeDomeTileSource() : m_gsd(1.0, 1.0) // default GSD { } ossimRangeDomeTileSource::~ossimRangeDomeTileSource() { close(); } bool ossimRangeDomeTileSource::open() { #if 0 /* Please wrap with traceDebug(). drb */ if (!theImageFile.isReadable()) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimRangeDomeTileSource::open() -- Error. Coould not" " open CSV file at <"<" << endl; return false; } #endif ossimString dome_spec; ossim_uint32 sizeOfMagic = (ossim_uint32)OSSIM_RANGE_DOME_SPEC_MAGIC_NUMBER.size(); char* magic_number = new char [ sizeOfMagic ]; // Open the CSV and check proper file type: ifstream indata (theImageFile.chars()); if (indata.fail()) return false; indata.read(magic_number, sizeOfMagic); if (indata.eof() || indata.fail() || (OSSIM_RANGE_DOME_SPEC_MAGIC_NUMBER != magic_number)) return false; // loop over each record/dome spec: vector tokens; while (indata.good()) { tokens.clear(); getline(indata, dome_spec); dome_spec.split(tokens, ",", true); ossimRangeDome dome (tokens); if (dome.valid) m_rangeDomes.push_back(dome); } // The GSD may be incorrect, but init anyway then redo whe GSD is set: initialize(); return isOpen(); } void ossimRangeDomeTileSource::initialize() { if (!isOpen()) return; // Establish bounding rect: ossimGrect boundingRect; boundingRect.makeNan(); vector::iterator dome = m_rangeDomes.begin(); while (dome != m_rangeDomes.end()) { boundingRect.expandToInclude(dome->boundingRect()); ++dome; } // Set up the geometry: ossimRefPtr mapProj = new ossimEquDistCylProjection(); mapProj->setOrigin(boundingRect.midPoint()); mapProj->setMetersPerPixel(m_gsd); ossimDpt degPerPixel (mapProj->getDecimalDegreesPerPixel()); mapProj->setElevationLookupFlag(false); mapProj->setUlTiePoints(boundingRect.ul()); ossimIpt image_size(boundingRect.width()/degPerPixel.x, boundingRect.height()/degPerPixel.y); theGeometry = new ossimImageGeometry(0, mapProj.get()); theGeometry->setImageSize(image_size); // Transform the domes to image space coordinates: dome = m_rangeDomes.begin(); double r; while (dome != m_rangeDomes.end()) { theGeometry->worldToLocal(dome->centerGpt, dome->centerIpt); r = dome->radiusMeters/m_gsd.x; dome->radiusPixelsSq = r*r; ++dome; } } bool ossimRangeDomeTileSource::isOpen() const { return (!m_rangeDomes.empty()); } void ossimRangeDomeTileSource::close() { m_rangeDomes.clear(); theGeometry = 0; } ossimRefPtr ossimRangeDomeTileSource::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { ossimRefPtr tile = ossimImageDataFactory::instance()->create(this, this); tile->setImageRectangle(rect); tile->initialize(); getTile(tile.get(), resLevel); return tile; } bool ossimRangeDomeTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { if (!result || !theGeometry.valid()) return false; // Start with null fill: result->fill(getNullPixelValue()); // Verify intersection with dataset. Everything done in R0 space: ossimIrect tile_rect (result->getImageRectangle()); ossim_uint32 coord_scale = resLevel + 1; ossimIrect tile_rect_r0 (coord_scale*tile_rect); ossimIrect boundingImgRect; theGeometry->getBoundingRect(boundingImgRect); if (!tile_rect_r0.intersects(boundingImgRect)) { result->setDataObjectStatus(OSSIM_EMPTY); return true; } vector::iterator dome; double d2, x0, y0, dx, dy, az; // Nested loop over all pixels in tile: for (ossim_int32 yn=tile_rect.ul().y; yn<=tile_rect.lr().y; ++yn) { y0 = yn * coord_scale; for (ossim_int32 xn=tile_rect.ul().x; xn<=tile_rect.lr().x; ++xn) { x0 = xn * coord_scale; // Loop over each dome in the list to see if this pixel is affected: dome = m_rangeDomes.begin(); while (dome != m_rangeDomes.end()) { // Check distance to center: dx = x0 - dome->centerIpt.x; dy = y0 - dome->centerIpt.y; d2 = dx*dx + dy*dy; if (d2 > dome->radiusPixelsSq) { ++dome; continue; } // Passed range test, do azimuth test. First check for simple 360 dome: if (dome->startAz == dome->endAz) { result->setValue(xn, yn, (ossim_uint8) dome->classification); ++dome; continue; } // Need full azimuth test: az = ossim::atan2d(dx, -dy); if (az < 0) az += 360; if (((dome->startAz < dome->endAz) && (az >= dome->startAz) && (az <= dome->endAz)) || ((dome->startAz > dome->endAz) && ( ((az >= dome->startAz) && (az > dome->endAz)) || ((az < dome->startAz) && (az <= dome->endAz))))) { result->setValue(xn, yn, (ossim_uint8) dome->classification); } ++dome; } } } result->validate(); return true; } ossim_uint32 ossimRangeDomeTileSource::getNumberOfInputBands() const { return 1; } ossim_uint32 ossimRangeDomeTileSource::getNumberOfLines(ossim_uint32 resLevel) const { if (theGeometry.valid()) return ( theGeometry->getImageSize().y / (resLevel+1) ); return 0; } ossim_uint32 ossimRangeDomeTileSource::getNumberOfSamples(ossim_uint32 resLevel) const { if (theGeometry.valid()) return ( theGeometry->getImageSize().x / (resLevel+1) ); return 0; } bool ossimRangeDomeTileSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { static const char MODULE[] = "ossimRangeDomeTileSource::saveState()"; ossimImageHandler::saveState(kwl, prefix); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR detected in keyword list! State not saved." << std::endl; return false; } kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_KW, m_gsd.x, true); return true; } bool ossimRangeDomeTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimRangeDomeTileSource::loadState()"; theDecimationFactors.clear(); ossimImageHandler::loadState(kwl, prefix); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN)<< MODULE << "WARNING: error detected in keyword list! State not load." << std::endl; return false; } ossimDpt gsd; ossimString value = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_KW); if (!value.empty()) gsd.x = value.toDouble(); value = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW); if (!value.empty()) setGSD(value.toDouble()); // The rest of the state is established by opening the file: bool good_open = open(); return good_open; } void ossimRangeDomeTileSource::setProperty(ossimRefPtr property) { if (!property.valid()) return; ossimString s; property->valueToString(s); if (s.empty()) return; // The user should select either explicit GSD or relative GSD factor, never both: if ( property->getName() == ossimKeywordNames::METERS_PER_PIXEL_KW ) { ossim_float64 gsd = s.toFloat64(); if (!ossim::isnan(gsd)) setGSD(gsd); } else { ossimImageHandler::setProperty(property); } } ossimRefPtr ossimRangeDomeTileSource::getProperty(const ossimString& name) const { ossimRefPtr prop = 0; if ( name == ossimKeywordNames::METERS_PER_PIXEL_KW ) { ossimString value = ossimString::toString(m_gsd.x); prop = new ossimStringProperty(name, value); } else { prop = ossimImageHandler::getProperty(name); } return prop; } void ossimRangeDomeTileSource::getGSD(ossimDpt& gsd, ossim_uint32 resLevel) const { gsd.x =(1.0/(resLevel+1)) * m_gsd.x; gsd.y =(1.0/(resLevel+1)) * m_gsd.y; } void ossimRangeDomeTileSource::setGSD( const ossim_float64& gsd ) { if (gsd == m_gsd.x) return; m_gsd.x = gsd; m_gsd.y = gsd; initialize(); } ossim-Miami-2.9.1/src/imaging/ossimReadmeFileWriter.cpp000066400000000000000000000370501352751253100230730ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2003 Storage Area Networks, Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Kenneth Melero (kmelero@sanz.com) // //******************************************************************* // $Id: ossimReadmeFileWriter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimReadmeFileWriter, "ossimReadmeFileWriter", ossimMetadataFileWriter) static const char DEFAULT_FILE_NAME[] = "output_readme.txt"; static ossimTrace traceDebug("ossimReadmeFileWriter:debug"); //************************************************************************************************** // //************************************************************************************************** ossimReadmeFileWriter::ossimReadmeFileWriter() : ossimMetadataFileWriter() { } //************************************************************************************************** // //************************************************************************************************** ossimReadmeFileWriter::~ossimReadmeFileWriter() { } //************************************************************************************************** // //************************************************************************************************** bool ossimReadmeFileWriter::writeFile() { static const char MODULE[] = "ossimReadmeFileWriter::writeFile"; if(!theInputConnection) { if (traceDebug()) { CLOG << "DEBUG:" << "\nNo input connection! Returning..." << endl; } return false; } std::ofstream out(theFilename.c_str(), ios_base::out); if (!out) return false; // Fetch the map projection of the input image if it exists: const ossimMapProjection* mapProj = 0; ossimRefPtr imgGeom = theInputConnection->getImageGeometry(); if ( imgGeom.valid() ) { const ossimProjection* proj = imgGeom->getProjection(); mapProj = PTR_CAST(ossimMapProjection, proj); } if (!mapProj) { out.close(); return false; } ossimMapProjectionInfo* projectionInfo = new ossimMapProjectionInfo(mapProj, theAreaOfInterest); if(projectionInfo) { out << setiosflags(ios::fixed) << setiosflags(ios::left) << setw(16) << "Image: " << projectionInfo->getImageInfoString(); out << setw(17) << "\nLines:" << projectionInfo->linesPerImage() << setw(17) << "\nSamples:" << projectionInfo->pixelsPerLine() << setw(17) << "\nPixel Size x:" << setprecision(8) << projectionInfo->getMetersPerPixel().x << " meters"; out << ", " << setprecision(8) << projectionInfo->getUsSurveyFeetPerPixel().x << " U.S. feet"; out << setw(17) << "\nPixel Size y:" << setprecision(8) << projectionInfo->getMetersPerPixel().y << " meters"; out << ", " << setprecision(8) << projectionInfo->getUsSurveyFeetPerPixel().y << " U.S. feet"; const ossimString type = TYPE_NAME(mapProj); const ossimString datum = mapProj->getDatum()->code(); const ossimString ellipsoid = mapProj->getEllipsoid().code(); if(type) out << setw(17) << "\nProjection:" << type; const ossimUtmProjection* utmProj = PTR_CAST(ossimUtmProjection, mapProj); if (utmProj) out << setw(17) << "\nUTM map zone:" << utmProj->getZone(); if(datum && ellipsoid) out << setw(17) << "\nDatum:" << datum << setw(17) << "\nEllipsoid:" << ellipsoid; out << resetiosflags(ios::left) << endl; const ossimString NORTH = "N"; const ossimString SOUTH = "S"; const ossimString EAST = "E"; const ossimString WEST = "W"; ossimString tmpString; double tmpDouble; // HACK: Easiest way to get projection info for optional params is via the old keywordlist: ossimKeywordlist kwl; mapProj->saveState(kwl); const char* parallel1 = kwl.find(ossimKeywordNames::STD_PARALLEL_1_KW); const char* parallel2 = kwl.find(ossimKeywordNames::STD_PARALLEL_2_KW); const char* scaleFactor = kwl.find(ossimKeywordNames::SCALE_FACTOR_KW); ossimString proj_name = mapProj->getClassName(); if ( ( proj_name.contains("Lambert") ) || ( proj_name.contains("Albers") ) || ( proj_name.contains("TransverseMercator" ) ) ) { double falseEasting = mapProj->getFalseEasting(); double falseNorthing = mapProj->getFalseNorthing(); double origin_lat = mapProj->origin().latd(); tmpDouble = fabs(origin_lat); tmpString = (origin_lat < 0.0) ? SOUTH : NORTH; out << setiosflags(ios::left) << "\n" << setw(18) << "Origin Latitude:" << resetiosflags(ios::left) << setw(21) << setprecision(12) << tmpDouble << tmpString << endl; double origin_lon = mapProj->origin().lond(); tmpDouble = fabs(origin_lon); tmpString = (origin_lon < 0.0) ? WEST : EAST; out << setiosflags(ios::left) << setw(18) << "Origin Longitude:" << resetiosflags(ios::left) << setw(21) << tmpDouble << tmpString << setiosflags(ios::left) << "\n" << setw(23) << "False Easting:" << resetiosflags(ios::left) << setw(17) << setprecision(4) << falseEasting; out << " meters, " << setprecision(4) << ossim::mtrs2usft(falseEasting) << " U.S. feet"; out << endl; out << setiosflags(ios::left) << setw(23) << "False Northing:" << resetiosflags(ios::left) << setw(17) << setprecision(4) << falseNorthing; out << " meters, " << setprecision(4) << ossim::mtrs2usft(falseNorthing) << " U.S. feet"; out << endl; } // End of if "Alber Lambert or TM. if (proj_name.contains("TransverseMercator")) { out << setiosflags(ios::left) << "\n" << setw(18) << "Scale Factor:" << resetiosflags(ios::left) << setw(21) << setprecision(10) << ossimString(scaleFactor).toDouble() << "\n" << endl; } if ( (proj_name.contains("Lambert") ) || (proj_name.contains("Albers") ) ) { double stdpar1 = ossimString(parallel1).toDouble(); tmpDouble = fabs(stdpar1); tmpString = (stdpar1 < 0.0) ? SOUTH : NORTH; out << setiosflags(ios::left) << setw(23) << "Standard Parallel #1:" << resetiosflags(ios::left) << setw(16) << setprecision(12) << tmpDouble << tmpString << endl; double stdpar2 = ossimString(parallel2).toDouble(); tmpDouble = fabs(stdpar2); tmpString = (stdpar2 < 0.0) ? SOUTH : NORTH; out << setiosflags(ios::left) << setw(23) << "Standard Parallel #2:" << resetiosflags(ios::left) << setw(16) << setprecision(12) << tmpDouble << tmpString << "\n" << endl; } ossimString cornerString[4] = { "Upper Left", "Upper Right", "Lower Right", "Lower Left" }; //--- // Add a note to the readme file stating what the corner coordinates // are relative to. //--- if (projectionInfo->getPixelType() == OSSIM_PIXEL_IS_AREA) { out << "\nCorner coordinates relative to outer edge of pixel.\n\n"; } else { out << "\nCorner coordinates relative to center of pixel.\n\n"; } out << "Corner Coordinates:\n\n"; //--- // Upper Left Corner Points //--- tmpDouble = fabs(projectionInfo->ulGroundPt().latd()); tmpString = (projectionInfo->ulGroundPt().latd() < 0.0) ? SOUTH : NORTH; out << cornerString[0] << endl; out << setw(14) << "Latitude: " << setw(16) << setprecision(12) << tmpDouble << tmpString << endl; tmpDouble = fabs(projectionInfo->ulGroundPt().lond()); tmpString = (projectionInfo->ulGroundPt().lond() < 0.0) ? WEST : EAST; out << setw(14) << "Longitude: " << setw(16) << tmpDouble << tmpString << endl; out << setw(14) << "Easting: " << setw(17) << setprecision(4) << projectionInfo->ulEastingNorthingPt().x; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->ulEastingNorthingPt().x) << " U.S. feet"; out << endl << setw(14) << "Northing: " << setw(17) << projectionInfo->ulEastingNorthingPt().y; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->ulEastingNorthingPt().y) << " U.S. feet"; out << endl << endl; //--- // Upper Right Corner Points //--- tmpDouble = fabs(projectionInfo->urGroundPt().latd()); tmpString = (projectionInfo->urGroundPt().latd() < 0.0) ? SOUTH : NORTH; out << cornerString[1] << endl; out << setw(14) << "Latitude: " << setw(16) << setprecision(12) << tmpDouble << tmpString << endl; tmpDouble = fabs(projectionInfo->urGroundPt().lond()); tmpString = (projectionInfo->urGroundPt().lond() < 0.0) ? WEST : EAST; out << setw(14) << "Longitude: " << setw(16) << tmpDouble << tmpString << endl; out << setw(14) << "Easting: " << setw(17) << setprecision(4) << projectionInfo->urEastingNorthingPt().x; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->urEastingNorthingPt().x) << " U.S. feet"; out << endl << setw(14) << "Northing: " << setw(17) << projectionInfo->urEastingNorthingPt().y; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->urEastingNorthingPt().y) << " U.S. feet"; out << endl << endl; //--- // Lower Right Corner Points //--- tmpDouble = fabs(projectionInfo->lrGroundPt().latd()); tmpString = (projectionInfo->lrGroundPt().latd() < 0.0) ? SOUTH : NORTH; out << cornerString[2] << endl; out << setw(14) << "Latitude: " << setw(16) << setprecision(12) << tmpDouble << tmpString << endl; tmpDouble = fabs(projectionInfo->lrGroundPt().lond()); tmpString = (projectionInfo->lrGroundPt().lond() < 0.0) ? WEST : EAST; out << setw(14) << "Longitude: " << setw(16) << tmpDouble << tmpString << endl; out << setw(14) << "Easting: " << setw(17) << setprecision(4) << projectionInfo->lrEastingNorthingPt().x; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->lrEastingNorthingPt().x) << " U.S. feet"; out << endl << setw(14) << "Northing: " << setw(17) << projectionInfo->lrEastingNorthingPt().y; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->lrEastingNorthingPt().y) << " U.S. feet"; out << endl << endl; //--- // Lower Left Corner Points //--- tmpDouble = fabs(projectionInfo->llGroundPt().latd()); tmpString = (projectionInfo->llGroundPt().latd() < 0.0) ? SOUTH : NORTH; out << cornerString[3] << endl; out << setw(14) << "Latitude: " << setw(16) << setprecision(12) << tmpDouble << tmpString << endl; tmpDouble = fabs(projectionInfo->llGroundPt().lond()); tmpString = (projectionInfo->llGroundPt().lond() < 0.0) ? WEST : EAST; out << setw(14) << "Longitude: " << setw(16) << tmpDouble << tmpString << endl; out << setw(14) << "Easting: " << setw(17) << setprecision(4) << projectionInfo->llEastingNorthingPt().x; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->llEastingNorthingPt().x) << " U.S. feet"; out << endl << setw(14) << "Northing: " << setw(17) << projectionInfo->llEastingNorthingPt().y; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->llEastingNorthingPt().y) << " U.S. feet"; out << endl << endl; out << "Center Coordinates:\n\n"; tmpDouble = fabs(projectionInfo->centerGroundPt().latd()); tmpString = (projectionInfo->centerGroundPt().latd() < 0.0) ? SOUTH : NORTH; out << setw(14) << "Latitude: " << setw(16) << setprecision(12) << tmpDouble << tmpString << endl; tmpDouble = fabs(projectionInfo->centerGroundPt().lond()); tmpString = (projectionInfo->centerGroundPt().lond() < 0.0) ? WEST : EAST; out << setw(14) << "Longitude: " << setw(16) << tmpDouble << tmpString << endl; out << setw(14) << "Easting: " << setw(17) << setprecision(4) << projectionInfo->centerEastingNorthingPt().x; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->centerEastingNorthingPt().x) << " U.S. feet"; out << endl << setw(14) << "Northing: " << setw(17) << projectionInfo->centerEastingNorthingPt().y; out << " meters, " << setprecision(4) << ossim::mtrs2usft(projectionInfo->centerEastingNorthingPt().y) << " U.S. feet"; out << endl << endl; out << "\nNOTE: Lat/Lon values are in decimal degrees."; out << "\n Eastings/Northings are in meters."; out << endl; delete projectionInfo; } out.close(); return true; } //************************************************************************************************** // //************************************************************************************************** void ossimReadmeFileWriter::getMetadatatypeList(std::vector& metadatatypeList) const { metadatatypeList.push_back(ossimString("ossim_readme")); } //************************************************************************************************** // //************************************************************************************************** bool ossimReadmeFileWriter::hasMetadataType(const ossimString& metadataType) const { return (metadataType == "ossim_readme"); } ossim-Miami-2.9.1/src/imaging/ossimRectangleCutFilter.cpp000066400000000000000000000217111352751253100234240ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRectangleCutFilter.cpp 22953 2014-11-05 19:19:28Z dburken $ #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimRectangleCutFilter:debug"); RTTI_DEF1(ossimRectangleCutFilter, "ossimRectangleCutFilter", ossimImageSourceFilter); ossimRectangleCutFilter::ossimRectangleCutFilter(ossimObject* owner, ossimImageSource* inputSource) :ossimImageSourceFilter(owner, inputSource), theCutType(OSSIM_RECTANGLE_NULL_OUTSIDE) { theRectangle.makeNan(); } ossimRectangleCutFilter::ossimRectangleCutFilter(ossimImageSource* inputSource) :ossimImageSourceFilter(NULL, inputSource), theCutType(OSSIM_RECTANGLE_NULL_OUTSIDE) { theRectangle.makeNan(); } ossimRefPtr ossimRectangleCutFilter::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { ossimRefPtr tile = 0; if ( theInputConnection && isSourceEnabled() && ( theRectangle.hasNans() == false ) ) { ossim_int32 decimationIndex = min((ossim_int32)resLevel, (ossim_int32)theDecimationList.size()-1); // Compute cut rect for resLevel: ossimIrect cutRect = theRectangle*theDecimationList[decimationIndex]; // Check intersection of our cut rect: bool requestIntersects = rect.intersects( cutRect ); bool requestCompletelyWithin = rect.completely_within(cutRect); if ( ( ( theCutType == OSSIM_RECTANGLE_NULL_OUTSIDE ) && requestIntersects ) || ( ( theCutType == OSSIM_RECTANGLE_NULL_INSIDE ) && !requestCompletelyWithin ) ) { // Grab tile from the input. tile = theInputConnection->getTile(rect, resLevel); if ( tile.valid() ) { if ( tile->getDataObjectStatus() != OSSIM_NULL && tile->getDataObjectStatus() != OSSIM_EMPTY ) { ossimIrect inputRectangle = tile->getImageRectangle(); if( theCutType == OSSIM_RECTANGLE_NULL_OUTSIDE ) // Typical case... { if ( !requestCompletelyWithin ) { // Clip the tile: ossim_int32 ulx = inputRectangle.ul().x; ossim_int32 uly = inputRectangle.ul().y; ossim_int32 w = tile->getWidth(); ossim_int32 h = tile->getHeight(); ossim_int32 offset = 0; ossimIpt tempPoint(ulx, uly); for(ossim_int32 y = 0; y < h; ++tempPoint.y,++y) { tempPoint.x = ulx; for(ossim_int32 x = 0; x < w; ++tempPoint.x,++x) { if(!cutRect.pointWithin(tempPoint)) { tile->setNull(offset); } ++offset; } } tile->validate(); } } else // Null inside... { // Note if complete within requested rect this block was bypassed entirely. ossim_int32 ulx = inputRectangle.ul().x; ossim_int32 uly = inputRectangle.ul().y; ossim_int32 w = tile->getWidth(); ossim_int32 h = tile->getHeight(); ossim_int32 offset = 0; ossimIpt tempPoint(ulx, uly); for(ossim_int32 y = 0; y < h; ++tempPoint.y,++y) { tempPoint.x = ulx; for(ossim_int32 x = 0; x < w; ++tempPoint.x,++x) { if(cutRect.pointWithin(tempPoint)) { tile->setNull(offset); } ++offset; } } tile->validate(); } } // Matches: if ( tile->getDataObjectStatus() ... } // Matches: if ( tile.valid() ) } // Matches: if ( ( ( theCutType == OSSI ... } // Matches: if ( theInputConnection && enabled && ... return tile; } // End: ossimRectangleCutFilter::getTile( ... ) void ossimRectangleCutFilter::setRectangle(const ossimIrect& rect) { theRectangle = rect; if(theRectangle.hasNans()) { if(theInputConnection) { theRectangle = theInputConnection->getBoundingRect(); } } } void ossimRectangleCutFilter::getValidImageVertices( vector& validVertices, ossimVertexOrdering ordering, ossim_uint32 /* resLevel */)const { ossimIrect rect = getBoundingRect(); if(ordering == OSSIM_CLOCKWISE_ORDER) { validVertices.push_back(rect.ul()); validVertices.push_back(rect.ur()); validVertices.push_back(rect.lr()); validVertices.push_back(rect.ll()); } else { validVertices.push_back(rect.ul()); validVertices.push_back(rect.ll()); validVertices.push_back(rect.lr()); validVertices.push_back(rect.ur()); } } ossimIrect ossimRectangleCutFilter::getBoundingRect(ossim_uint32 resLevel)const { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRectangleCutFilter::getBoundingRect DEBUG: entered..." << std::endl; } ossimIrect result; result.makeNan(); if(!theInputConnection) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRectangleCutFilter::getBoundingRect DEBUG: Input connection was not valid so leaving" << std::endl; } return result; } result = theInputConnection->getBoundingRect(resLevel); if(isSourceEnabled()) { if(theCutType == OSSIM_RECTANGLE_NULL_OUTSIDE) { ossimDpt decimation; getDecimationFactor(resLevel, decimation); ossimIrect cutRect = theRectangle; if(!decimation.hasNans()) { cutRect = theRectangle*decimation; } result = cutRect; } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRectangleCutFilter::getBoundingRect DEBUG: cut rect = " << result << std::endl; } return result; } void ossimRectangleCutFilter::initialize() { theDecimationList.clear(); if(theInputConnection) { getDecimationFactors(theDecimationList); } if(theDecimationList.empty()) { theDecimationList.push_back(ossimDpt(1,1)); } if(theRectangle.hasNans()) { setRectangle(theRectangle); } } bool ossimRectangleCutFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString newPrefix = prefix; newPrefix+="clip_rect."; theRectangle.saveState(kwl, newPrefix); if(theCutType == OSSIM_RECTANGLE_NULL_INSIDE) { kwl.add(prefix, "cut_type", "null_inside", true); } else if(theCutType == OSSIM_RECTANGLE_NULL_OUTSIDE) { kwl.add(prefix, "cut_type", "null_outside", true); } return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimRectangleCutFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString newPrefix = prefix; ossimString rect = kwl.find(prefix, "rect"); if(!rect.empty()) { theRectangle.toRect(rect); } else { newPrefix+="clip_rect."; theRectangle.loadState(kwl, newPrefix.c_str()); } const char* cutType = kwl.find(prefix, "cut_type"); if(cutType) { ossimString c = cutType; if(c == "null_inside") { theCutType = OSSIM_RECTANGLE_NULL_INSIDE; } else if(c == "null_outside") { theCutType = OSSIM_RECTANGLE_NULL_OUTSIDE; } else { theCutType = static_cast(ossimString(cutType).toLong()); } } return ossimImageSourceFilter::loadState(kwl, prefix); } const ossimIrect& ossimRectangleCutFilter::getRectangle()const { return theRectangle; } ossimRectangleCutFilter::ossimRectangleCutType ossimRectangleCutFilter::getCutType()const { return theCutType; } void ossimRectangleCutFilter::setCutType(ossimRectangleCutType cutType) { theCutType = cutType; } ossim-Miami-2.9.1/src/imaging/ossimResampler.cpp000066400000000000000000001176541352751253100216440ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // // Description: // // Contains class definition for ossimResampler. // //******************************************************************* // $Id: ossimResampler.cpp 20204 2011-11-04 15:12:28Z dburken $ #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimResampler, "ossimResampler", ossimConnectableObject) static const char* RESAMPLER_CONVOLUTION_TYPE_KW = "convolution_type"; static const char* RESAMPLER_SCALE_X_KW = "scale_x"; static const char* RESAMPLER_SCALE_Y_KW = "scale_y"; static const char* RESAMPLER_CUBIC_PARAMETER_KW = "cubic_parameter"; ossimResampler::ossimResampler() :ossimConnectableObject(NULL,0,0,true, false), theOutputToInputRatio(1,1), theResamplerType(ossimResampler_NONE), theTableWidthX(0), theTableWidthY(0), theTableHeight(0), theKernelWidth(0), theKernelHeight(0), theWeightTableX(NULL), theWeightTableY(NULL), theCubicAdjustableParameter(-.5) { } ossimResampler::~ossimResampler() { deleteWeightTable(); } void ossimResampler::resample(ossimImageData* input, ossimImageData* output) { if(!input|| !output || !input->getBuf() || !output->getBuf()) { return; } if(theWeightTableX&&theWeightTableY) { ossimScalarType scalarType = input->getScalarType(); switch(scalarType) { case OSSIM_UINT8: { resampleTile(ossim_uint8(0), // dummy template variable input, output); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { resampleTile(ossim_uint16(0), // dummy template variable input, output); break; } case OSSIM_SSHORT16: { resampleTile(ossim_sint16(0), // dummy template variable input, output); break; } case OSSIM_UINT32: { resampleTile(ossim_uint32(0), // dummy template variable input, output); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { resampleTile(ossim_float32(0.0), // dummy template variable input, output); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { resampleTile(ossim_float64(0.0), // dummy template variable input, output); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimResampler::resample error: unknown scalar type: " << scalarType << endl; } } } // convolve the input and copy to output. } void ossimResampler::resample(ossimImageData* input, ossimImageData* output, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length) { resample(input, output, output->getImageRectangle(), ul, ur, deltaUl, deltaUr, length); } void ossimResampler::resample(ossimImageData* input, ossimImageData* output, const ossimIrect& outputSubRect, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length) { if(!input|| !output || !input->getBuf() || !output->getBuf()) { return; } if(theWeightTableX&&theWeightTableY) { ossimScalarType scalarType = input->getScalarType(); switch(scalarType) { case OSSIM_UINT8: { resampleTile(ossim_uint8(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { resampleTile(ossim_uint16(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_SINT16: { resampleTile(ossim_sint16(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_UINT32: { resampleTile(ossim_uint32(0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { resampleTile(ossim_float32(0.0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { resampleTile(ossim_float64(0.0), // dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimResampler::resample error: unknown scalar type: " << scalarType << endl; } } } } void ossimResampler::resampleNearestNeighbor(ossimImageData* input, ossimImageData* output, const ossimIrect& outputSubRect, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length) { if(!input|| !output || !input->getBuf() || !output->getBuf()) { return; } ossimScalarType scalarType = input->getScalarType(); switch(scalarType) { case OSSIM_UINT8: { resampleTileNearestNeighbor(ossim_uint8(0),// dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { resampleTileNearestNeighbor(ossim_uint16(0),// dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_SINT16: { resampleTileNearestNeighbor(ossim_sint16(0),// dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_UINT32: { resampleTileNearestNeighbor(ossim_uint32(0),// dummy template variable input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { resampleTileNearestNeighbor(ossim_float32(0.0), input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { resampleTileNearestNeighbor(ossim_float64(0.0), input, output, outputSubRect, ul, ur, deltaUl, deltaUr, length); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimResampler::resample error: unknown scalar type: " << scalarType << endl; } } } void ossimResampler::resampleNearestNeighbor(ossimImageData* input, ossimImageData* output, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length) { resampleNearestNeighbor(input, output, output->getImageRectangle(), ul, ur, deltaUl, deltaUr, length); } template void ossimResampler::resampleTile(T,// not used ossimImageData* input, ossimImageData* output) { switch(input->getDataObjectStatus()) { case OSSIM_FULL: { resampleFullTile((T)0, input, output); break; } case OSSIM_PARTIAL: { resamplePartialTile((T)0, input, output); break; } default: { break; } } } template void ossimResampler::resamplePartialTile(T,// not used ossimImageData* input, ossimImageData* output) { ossim_int32 maxInputSize = std::max(input->getWidth(), input->getHeight()); ossim_int32 maxOutputSize = std::max(output->getWidth(), output->getHeight()); ossim_int32 k; double *h = new double[maxInputSize]; int *Lx = new int[maxOutputSize]; int *Ly = new int[maxOutputSize]; ossim_int32 out_height = output->getHeight(); ossim_int32 out_width = output->getWidth(); ossim_int32 in_width = input->getWidth(); ossim_int32 in_height = input->getHeight(); ossim_int32 j; ossim_int32 l; ossimIpt origin=output->getOrigin(); ossimIpt scaledOriginShift(input->getOrigin()*-1); ossim_int32 evenKernelW = (ossim_int32)(!(theKernelWidth%2)); ossim_int32 evenKernelH = (ossim_int32)(!(theKernelHeight%2)); ossim_int32 kernelHorizontalShift = (ossim_int32)(-theKernelWidth/2.0+evenKernelW); ossim_int32 kernelVerticalShift = (ossim_int32)(-theKernelHeight/2.0+evenKernelH); for (k = 0; k < maxOutputSize; ++k) { Lx[k] = (ossim_int32)(scaledOriginShift.x+((k+origin.x)/ theOutputToInputRatio.x)); } for (k = 0; k < maxOutputSize; ++k) { Ly[k] = (ossim_int32)(scaledOriginShift.y+((k+origin.y)/ theOutputToInputRatio.y)); } for(ossim_int32 band = 0; band < (ossim_int32)input->getNumberOfBands();++band) { const T* inputBuf = static_cast(input->getBuf(band)); T* outputBuf = static_cast(output->getBuf(band)); T minPix = static_cast(input->getMinPix(band)); T maxPix = static_cast(input->getMaxPix(band)); T np = static_cast(input->getNullPix(band)); for (k = 0; k < out_height; ++k) { ossim_int32 indexMod = (ossim_int32)fmod((k+origin.y), theOutputToInputRatio.y); if(indexMod >= theTableWidthY) indexMod = theTableWidthY - 1; if(indexMod <0) indexMod = 0; for (j = 0; j < in_width; ++j) { h[j] = 0.0; ossim_int32 count = 0; double lastValue = ossim::nan(); for (l = 0; l < theKernelHeight; ++l) { ossim_int32 index = Ly[k] + l + kernelVerticalShift; if ((index >= 0) && (index < in_height)) { ossim_int32 offset = index*in_width +j; if(!input->isNull(offset)) { lastValue = (double)inputBuf[offset]; h[j] += lastValue * theWeightTableY[theKernelHeight - l-1][indexMod]; ++count; } // I think instead of skipping to next value I'll just assume 0 // this was code to skip to next non-null value and use it // // else // { // for(ossim_int32 templ = l; templ < theKernelHeight; ++templ) // { // index = Ly[k] + templ + kernelVerticalShift; // offset = index*in_width +j; // if(!input->isNull(offset)) // { // lastValue = (double)inputBuf[offset]; // break; // } // } // if(ossim::isnan(lastValue) == false) // { // h[j] += lastValue * // theWeightTableY[theKernelHeight - l-1][indexMod]; // ++count; // } // else // { // break; // } // } } } if(!count) { h[j] = ossim::nan(); } } for (ossim_int32 m = 0; m < out_width; ++m) { double x = 0.0; ossim_int32 indexMod = (ossim_int32)fmod((m+origin.x), theOutputToInputRatio.x); if(indexMod >= theTableWidthX) indexMod = theTableWidthX-1; if(indexMod <0) indexMod = 0; if(input->isNull(ossimIpt(Lx[m]-scaledOriginShift.x, Ly[k]-scaledOriginShift.y))) { outputBuf[k*out_width +m] = np; } else { for (l = 0; l < theKernelWidth; ++l) { ossim_int32 index = Lx[m] + l + kernelHorizontalShift; if ((index >= 0) && (index < in_width)) { if(ossim::isnan(h[index]) == false) { x += h[index] * theWeightTableX[theKernelWidth - l-1][indexMod]; } // I am commenting out the code that searches for the next // non null value with the kernel range. This will have the // same effect as multiplying by 0.0 for the NULL value. // // else // { // for(ossim_int32 templ = l; templ < l; ++templ) // { // ossim_int32 index = Lx[m] + templ + kernelHorizontalShift; // if(ossim::isnan(h[index]) == false)) // { // lastValue = h[index]; // break; // } // } // if(ossim::isnan(lastValue) == false) // { // x += lastValue * theWeightTableX[theKernelWidth - l-1][indexMod]; // } // } } } if (x < minPix) { outputBuf[k*out_width +m] = static_cast(minPix); } else if (x > maxPix) { outputBuf[k*out_width +m] = static_cast(maxPix); } else { outputBuf[k*out_width +m] = static_cast(x); } } } } } delete [] h; delete [] Lx; delete [] Ly; } template void ossimResampler::resampleFullTile(T,// not used ossimImageData* input, ossimImageData* output) { ossim_int32 maxInputSize = std::max(input->getWidth(), input->getHeight()); ossim_int32 maxOutputSize = std::max(output->getWidth(), output->getHeight()); ossim_int32 k; double *h = new double[maxInputSize]; ossim_int32 *Lx = new ossim_int32[maxOutputSize]; ossim_int32 *Ly = new ossim_int32[maxOutputSize]; ossim_int32 out_height = output->getHeight(); ossim_int32 out_width = output->getWidth(); ossim_int32 in_width = input->getWidth(); ossim_int32 in_height = input->getHeight(); ossim_int32 j; ossim_int32 l; ossimIpt origin=output->getOrigin(); ossimIpt scaledOriginShift(input->getOrigin()*-1); ossim_int32 evenKernelW = (ossim_int32)(!(theKernelWidth%2)); ossim_int32 evenKernelH = (ossim_int32)(!(theKernelHeight%2)); ossim_int32 kernelHorizontalShift = (ossim_int32)(-theKernelWidth/2.0+evenKernelW); ossim_int32 kernelVerticalShift = (ossim_int32)(-theKernelHeight/2.0+evenKernelH); for (k = 0; k < maxOutputSize; ++k) { Lx[k] = (ossim_int32)(scaledOriginShift.x+((k+origin.x)/ theOutputToInputRatio.x)); } for (k = 0; k < maxOutputSize; ++k) { Ly[k] = (ossim_int32)(scaledOriginShift.y+((k+origin.y)/ theOutputToInputRatio.y)); } for(ossim_int32 band = 0; band < (ossim_int32)input->getNumberOfBands();++band) { const T* inputBuf = (const T*)(input->getBuf(band)); T* outputBuf = (T*)(output->getBuf(band)); double minPix = static_cast(input->getMinPix()[band]); double maxPix = static_cast(input->getMaxPix()[band]); for (k = 0; k < out_height; ++k) { int indexMod = (int)fmod((k+origin.y), theOutputToInputRatio.y); if(indexMod >= theTableWidthY) indexMod = theTableWidthY - 1; if(indexMod <0) indexMod = 0; for (j = 0; j < in_width; ++j) { h[j] = 0.0; for (l = 0; l < theKernelHeight; ++l) { ossim_int32 index = Ly[k] + l + kernelVerticalShift; if ((index >= 0) && (index < in_height)) { h[j] += ((double)inputBuf[index*in_width +j]) * theWeightTableY[theKernelHeight - l-1][indexMod]; } } } for (ossim_int32 m = 0; m < out_width; ++m) { double x = 0.0; int indexMod = (int)fmod((m+origin.x), theOutputToInputRatio.x); if(indexMod >= theTableWidthX) indexMod = theTableWidthX-1; if(indexMod <0) indexMod = 0; for (l = 0; l < theKernelWidth; ++l) { ossim_int32 index = Lx[m] + l + kernelHorizontalShift; if ((index >= 0) && (index < in_width)) { x += h[index] * theWeightTableX[theKernelWidth - l-1][indexMod]; } } if (x < minPix) { outputBuf[k*out_width +m] = static_cast(minPix); } else if (x > maxPix) { outputBuf[k*out_width +m] = static_cast(maxPix); } else { outputBuf[k*out_width +m] = static_cast(x); } } } } delete [] h; delete [] Lx; delete [] Ly; } template void ossimResampler::resampleTile(T,// not used ossimImageData* input, ossimImageData* output, const ossimIrect& outputSubRect, const ossimDpt& inputUl, const ossimDpt& inputUr, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& outLength) { ossimRefPtr dupIn = input; ossimDpt origin = input->getOrigin(); ossimDpt newInputUl = inputUl; ossimDpt newInputUr = inputUr; ossimDpt newDeltaUl = deltaUl; ossimDpt newDeltaUr = deltaUr; if(theResamplerType != ossimResampler_NEAREST_NEIGHBOR) { newInputUl = ossimDpt(inputUl.x * theOutputToInputRatio.x, inputUl.y * theOutputToInputRatio.y); newInputUr = ossimDpt(inputUr.x * theOutputToInputRatio.x, inputUr.y * theOutputToInputRatio.y); newDeltaUl = ossimDpt(deltaUl.x * theOutputToInputRatio.x, deltaUl.y * theOutputToInputRatio.y); newDeltaUr = ossimDpt(deltaUr.x * theOutputToInputRatio.x, deltaUr.y * theOutputToInputRatio.y); ossimDpt newLl = newInputUl + newDeltaUl*outLength.y; ossimDpt newLr = newInputUr + newDeltaUr*outLength.y; ossimDrect newBoundingRect(newInputUl, newInputUr, newLl, newLr); newBoundingRect = ossimDrect(newBoundingRect.ul() - ossimDpt(theKernelWidth, theKernelHeight), newBoundingRect.lr() + ossimDpt(theKernelWidth, theKernelHeight)); ossimIrect roundedRect = newBoundingRect; origin = roundedRect.ul(); dupIn = new ossimImageData(NULL, input->getScalarType(), input->getNumberOfBands(), roundedRect.width(), roundedRect.height()); dupIn->setOrigin(roundedRect.ul()); dupIn->initialize(); resampleTile(static_cast(0), input, dupIn.get()); } long inWidth = dupIn->getWidth(); long inHeight = dupIn->getHeight(); double stepSizeWidth = 1.0/outLength.x; double stepSizeHeight = 1.0/outLength.y; ossimIrect rect = dupIn->getImageRectangle(); ossimDpt startSave(newInputUl.x - rect.ul().x, newInputUl.y - rect.ul().y ); ossimDpt endSave(newInputUr.x - rect.ul().x, newInputUr.y - rect.ul().y); ossimIrect outputRect = output->getImageRectangle(); ossimIpt subRectUl = outputSubRect.ul(); long subRectH = outputSubRect.height(); long subRectW = outputSubRect.width(); ossimIpt outputRectUl = outputRect.ul(); long outputRectW = outputRect.width(); long resultOffset = (subRectUl.y - outputRectUl.y)*outputRectW + (subRectUl.x - outputRectUl.x); for(ossim_uint32 band = 0; band < input->getNumberOfBands(); ++band) { T* resultBuf = static_cast(output->getBuf(band))+resultOffset; const T *sourceBuf = static_cast(dupIn->getBuf(band)); ossimDpt start = startSave; ossimDpt end = endSave; T np = (T)output->getNullPix(band); for(long y = 0; y < subRectH; ++y) { double deltaX = (end.x - start.x)*stepSizeWidth; double deltaY = (end.y - start.y)*stepSizeHeight; ossimDpt pointXY = start; for(long x = 0; x < subRectW; ++x) { int xPixel = pointXY.x<0?(int)floor(pointXY.x):(int)pointXY.x; int yPixel = pointXY.y<0?(int)floor(pointXY.y):(int)pointXY.y; if( (xPixel >=0) && (xPixel < inWidth) && (yPixel >=0) && (yPixel < inHeight)) { resultBuf[x] = sourceBuf[yPixel*inWidth + xPixel]; } else { resultBuf[x] = np; } pointXY.y += deltaY; pointXY.x += deltaX; } resultBuf += outputRectW; start.x += newDeltaUl.x; start.y += newDeltaUl.y; end.x += newDeltaUr.x; end.y += newDeltaUr.y; } } dupIn = 0; } template void ossimResampler::resampleTileNearestNeighbor(T, // dummy template variable ossimImageData* input, ossimImageData* output, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length) { resampleTileNearestNeighbor((T)0, input, output, output->getImageRectangle(), ul, ur, deltaUl, deltaUr, length); } template void ossimResampler::resampleTileNearestNeighbor(T, // dummy template variable ossimImageData* input, ossimImageData* output, const ossimIrect& outputSubRect, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& deltaUl, const ossimDpt& deltaUr, const ossimDpt& length) { long inWidth = input->getWidth(); long inHeight = input->getHeight(); double stepSizeWidth = 1.0/length.x; double stepSizeHeight = 1.0/length.y; ossimIrect rect = input->getImageRectangle(); ossimDpt startSave(ul.x - rect.ul().x, ul.y - rect.ul().y ); ossimDpt endSave(ur.x - rect.ul().x, ur.y - rect.ul().y); ossimIrect outputRect = output->getImageRectangle(); ossimIpt subRectUl = outputSubRect.ul(); // ossimIpt subRectUl((int)outputSubRect.ul().x, // (int)outputSubRect.ul().y); long subRectH = outputSubRect.height(); long subRectW = outputSubRect.width(); ossimIpt outputRectUl = outputRect.ul(); long outputRectW = outputRect.width(); long resultOffset = (subRectUl.y - outputRectUl.y)*outputRectW + (subRectUl.x - outputRectUl.x); for(ossim_uint32 band = 0; band < input->getNumberOfBands(); ++band) { T* resultBuf = static_cast(output->getBuf(band))+resultOffset; const T *sourceBuf = static_cast(input->getBuf(band)); ossimDpt start = startSave; ossimDpt end = endSave; T inNp = (T)input->getNullPix(band); T outNp = (T)output->getNullPix(band); for(long y = 0; y < subRectH; ++y) { double deltaX = (end.x - start.x)*stepSizeWidth; double deltaY = (end.y - start.y)*stepSizeHeight; ossimDpt pointXY = start; for(long x = 0; x < subRectW; ++x) { int xPixel = pointXY.x<0?(int)floor(pointXY.x):(int)pointXY.x; int yPixel = pointXY.y<0?(int)floor(pointXY.y):(int)pointXY.y; if( (xPixel >=0) && (xPixel < inWidth) && (yPixel >=0) && (yPixel < inHeight)) { T value = sourceBuf[yPixel*inWidth + xPixel]; if(value != inNp) { resultBuf[x] = value; } else { resultBuf[x] = outNp; } } else { resultBuf[x] = outNp; } pointXY.y += deltaY; pointXY.x += deltaX; } resultBuf += outputRectW; start.x += deltaUl.x; start.y += deltaUl.y; end.x += deltaUr.x; end.y += deltaUr.y; } } } ossim_int32 ossimResampler::getKernelWidth()const { return theKernelWidth; } ossim_int32 ossimResampler::getKernelHeight()const { return theKernelHeight; } void ossimResampler::deleteWeightTable() { if(theWeightTableX) { for(ossim_int32 index = 0; index < theTableHeight; ++index) { delete [] theWeightTableX[index]; } delete [] theWeightTableX; theWeightTableX = NULL; } if(theWeightTableY) { for(ossim_int32 index = 0; index < theTableHeight; ++index) { delete [] theWeightTableY[index]; } delete [] theWeightTableY; theWeightTableY = NULL; } } void ossimResampler::allocateWeightTable()//uint32 outWidth) { if(theWeightTableX|| theWeightTableY) { deleteWeightTable(); } switch(theResamplerType) { case ossimResampler_BICUBIC: { theTableHeight = 4; break; } case ossimResampler_BILINEAR: { theTableHeight = 2; break; } case ossimResampler_NEAREST_NEIGHBOR: { theTableHeight = 1; break; } case ossimResampler_NONE: { theResamplerType = ossimResampler_NEAREST_NEIGHBOR; theTableHeight = 1; break; } } theTableWidthX = (ossim_int32)ossim::round(theOutputToInputRatio.x); theTableWidthY = (ossim_int32)ossim::round(theOutputToInputRatio.y); if(theTableWidthX&&theTableHeight) { theWeightTableX = new double*[theTableHeight]; for(ossim_int32 index = 0; index < theTableHeight; ++index) { theWeightTableX[index] = new double[theTableWidthX]; } } if(theTableWidthY&&theTableHeight) { theWeightTableY = new double*[theTableHeight]; for(ossim_int32 index = 0; index < theTableHeight; ++index) { theWeightTableY[index] = new double[theTableWidthY]; } } } void ossimResampler::generateWeightTable() { if(theWeightTableX&& theWeightTableY) { // ossim_int32 d = theOutputToInputRatio.theDen; // ossim_int32 n = theOutputToInputRatio.theNum; ossim_int32 i = 0; double x = 0.0; switch(theResamplerType) { case ossimResampler_NONE: { theResamplerType = ossimResampler_NEAREST_NEIGHBOR; for (i = 0; i < theTableWidthY; ++i) { theWeightTableY[0][i] = 1; } for (i = 0; i < theTableWidthX; ++i) { theWeightTableX[0][i] = 1; } break; } case ossimResampler_NEAREST_NEIGHBOR: { for (i = 0; i < theTableWidthY; ++i) { theWeightTableY[0][i] = 1; } for (i = 0; i < theTableWidthX; ++i) { theWeightTableX[0][i] = 1; } break; } case ossimResampler_BILINEAR: { for (i = 0; i < theTableWidthX; ++i) { x = (double)i/(double)(theTableWidthX); theWeightTableX[0][i] = x; theWeightTableX[1][i] = 1-x; } for (i = 0; i < theTableWidthY; ++i) { x = (double)i/(double)(theTableWidthY); theWeightTableY[0][i] = x; theWeightTableY[1][i] = 1-x; } break; } case ossimResampler_BICUBIC: { for (i = 0; i < theTableWidthX; ++i) { x = (double)i/(double)(theTableWidthX); theWeightTableX[0][i] = getCubicC0(x); theWeightTableX[1][i] = getCubicC1(x); theWeightTableX[2][i] = getCubicC2(x); theWeightTableX[3][i] = getCubicC3(x); } for (i = 0; i < theTableWidthY; ++i) { x = (double)i/(double)(theTableWidthY); theWeightTableY[0][i] = getCubicC0(x); theWeightTableY[1][i] = getCubicC1(x); theWeightTableY[2][i] = getCubicC2(x); theWeightTableY[3][i] = getCubicC3(x); } break; } } } } void ossimResampler::setResamplerType(ossimResLevelResamplerType type) { if(theResamplerType != type) { theResamplerType = type; switch(theResamplerType) { case ossimResampler_NONE: { theResamplerType = ossimResampler_NEAREST_NEIGHBOR; theKernelWidth = 1; theKernelHeight = 1; break; } case ossimResampler_NEAREST_NEIGHBOR: { theKernelWidth = 1; theKernelHeight = 1; break; } case ossimResampler_BILINEAR: { theKernelWidth = 2; theKernelHeight = 2; break; } case ossimResampler_BICUBIC: { theKernelWidth = 4; theKernelHeight = 4; break; } } allocateWeightTable(); generateWeightTable(); } } void ossimResampler::setRatio(double outputToInputRatio) { // make it square setRatio(ossimDpt(outputToInputRatio, outputToInputRatio)); } void ossimResampler::setRatio(const ossimDpt& outputToInputRatio) { // make it square theOutputToInputRatio.x = (outputToInputRatio.x); theOutputToInputRatio.y = (outputToInputRatio.y); if((theTableWidthX != ossim::round(outputToInputRatio.x))|| (theTableWidthY != ossim::round(outputToInputRatio.y))) { allocateWeightTable(); generateWeightTable(); } } double ossimResampler::getCubicC0(double t)const { return ((-theCubicAdjustableParameter * t * t * t) + (theCubicAdjustableParameter * t * t)); } double ossimResampler::getCubicC1(double t)const { return (-(theCubicAdjustableParameter + 2.0) * t * t * t + (2.0 * theCubicAdjustableParameter + 3.0) * t * t - theCubicAdjustableParameter * t); } double ossimResampler::getCubicC2(double t)const { return ((theCubicAdjustableParameter + 2.0) * t * t * t - (theCubicAdjustableParameter + 3.0) * t * t + 1.0); } double ossimResampler::getCubicC3(double t)const { return ((theCubicAdjustableParameter * t * t * t) - (2.0f * theCubicAdjustableParameter * t * t) + (theCubicAdjustableParameter * t)); } bool ossimResampler::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* resamplerType = kwl.find(prefix, RESAMPLER_CONVOLUTION_TYPE_KW); const char* scaleX = kwl.find(prefix, RESAMPLER_SCALE_X_KW); const char* scaleY = kwl.find(prefix, RESAMPLER_SCALE_Y_KW); const char* cubicParameter= kwl.find(prefix, RESAMPLER_CUBIC_PARAMETER_KW); if(cubicParameter) { theCubicAdjustableParameter = ossimString(cubicParameter).toDouble(); if(theCubicAdjustableParameter < -1) theCubicAdjustableParameter = -1; if(theCubicAdjustableParameter > 0) theCubicAdjustableParameter = 0; } else { theCubicAdjustableParameter = -.5; } if(resamplerType) { ossimString test =ossimString(resamplerType).upcase().trim(); if( test == "BICUBIC") { setResamplerType(ossimResampler::ossimResampler_BICUBIC); } else if( test == "BILINEAR") { setResamplerType(ossimResampler::ossimResampler_BILINEAR); } else { setResamplerType(ossimResampler::ossimResampler_NEAREST_NEIGHBOR); } } if(scaleX&&scaleY) { setRatio(ossimDpt(ossimString(scaleX).toDouble(), ossimString(scaleY).toDouble())); } allocateWeightTable(); generateWeightTable(); return ossimConnectableObject::loadState(kwl, prefix); } bool ossimResampler::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString resamplerType; if(getResamplerType() == ossimResampler_BICUBIC) { resamplerType = "BICUBIC"; } else if(getResamplerType() == ossimResampler_BILINEAR) { resamplerType = "BILINEAR"; } else { resamplerType = "NEAREST_NEIGHBOR"; } kwl.add(prefix, RESAMPLER_CONVOLUTION_TYPE_KW, resamplerType.c_str(), true); kwl.add(prefix, RESAMPLER_SCALE_X_KW, theOutputToInputRatio.x, true); kwl.add(prefix, RESAMPLER_SCALE_Y_KW, theOutputToInputRatio.y, true); kwl.add(prefix, RESAMPLER_CUBIC_PARAMETER_KW, theCubicAdjustableParameter, true); return ossimConnectableObject::saveState(kwl, prefix); } ossim-Miami-2.9.1/src/imaging/ossimRgbGridRemapEngine.cpp000066400000000000000000000223671352751253100233410ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimRgbGridRemapEngine.cc // // Copyright (C) 2001 ImageLinks, Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains implementation of class // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimRgbGridRemapEngine.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include RTTI_DEF1(ossimRgbGridRemapEngine, "ossimRgbGridRemapEngine", ossimGridRemapEngine); #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimRgbGridRemapEngine:exec"); static ossimTrace traceDebug ("ossimRgbGridRemapEngine:debug"); using namespace std; //***************************************************************************** // METHOD: ossimRgbGridRemapEngine::dup // //***************************************************************************** ossimObject* ossimRgbGridRemapEngine::dup() const { return new ossimRgbGridRemapEngine; } //***************************************************************************** // METHOD: ossimRgbGridRemapEngine::remapTile // //***************************************************************************** void ossimRgbGridRemapEngine::remapTile(const ossimDpt& origin, ossimGridRemapSource* remapper, ossimRefPtr& tile) { static const char MODULE[] = "ossimRgbGridRemapEngine::remapTile"; if (traceExec()) CLOG << "entering..." << endl; //*** // Fetch tile size and NULL pixel value: //*** int width = tile->getWidth(); int height = tile->getHeight(); int offset = 0; double null[3]; //*** // Determine null pixel values so that we can recognize a null coming in and // not remap it: //*** null[0] = tile->getNullPix(0); null[1] = tile->getNullPix(1); null[2] = tile->getNullPix(2); ossimDblGrid& gridR = *(remapper->getGrid(0)); ossimDblGrid& gridG = *(remapper->getGrid(1)); ossimDblGrid& gridB = *(remapper->getGrid(2)); //*** // Remap according to pixel type: //*** switch(tile->getScalarType()) { case OSSIM_UCHAR: { ossim_uint8* red_buf = (ossim_uint8*)tile->getBuf(0); ossim_uint8* grn_buf = (ossim_uint8*)tile->getBuf(1); ossim_uint8* blu_buf = (ossim_uint8*)tile->getBuf(2); short pixel_buffer[3]; for (double line=origin.line; line255) red_buf[offset] = 255; else red_buf[offset] = pixel_buffer[0]; if (pixel_buffer[1]<0) grn_buf[offset] = 0; else if (pixel_buffer[1]>255) grn_buf[offset] = 255; else grn_buf[offset] = pixel_buffer[1]; if (pixel_buffer[2]<0) blu_buf[offset] = 0; else if (pixel_buffer[2]>255) blu_buf[offset] = 255; else blu_buf[offset] = pixel_buffer[2]; //*** // Avoid NULLS: //*** if (red_buf[offset] == (ossim_uint8) null[0]) red_buf[offset]++; if (grn_buf[offset] == (ossim_uint8) null[1]) grn_buf[offset]++; if (blu_buf[offset] == (ossim_uint8) null[2]) blu_buf[offset]++; } offset++; } } break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimRgbGridRemapEngine::remapTile: Scalar type not handled" << std::endl; break; } } // end switch statement if (traceExec()) CLOG << "returning..." << endl; return; }; //***************************************************************************** // METHOD: ossimRgbGridRemapEngine::assignRemapValues // // This engine defines the target value as an RGB vector of doubles, computed // as the mean of all contributor RGB values. // //***************************************************************************** void ossimRgbGridRemapEngine::assignRemapValues ( vector& sources_list) { static const char MODULE[] = "ossimRgbGridRemapEngine::assignRemapValues"; if (traceExec()) CLOG << "entering..." << endl; int i; // index to individual sources //*** // Declare a 2D array that will contain all of the contributing sources' // RGB mean values. Also declare the accumulator target vector. //*** int num_contributors = (int)sources_list.size(); double** contributor_pixel = new double* [num_contributors]; for (i=0; i::iterator source; i = 0; for(source=sources_list.begin(); source!=sources_list.end(); source++) { (*source)->getSourceValue(contributor_pixel[i]); target_pixel[0] += contributor_pixel[i][0]/(double)num_contributors; target_pixel[1] += contributor_pixel[i][1]/(double)num_contributors; target_pixel[2] += contributor_pixel[i][2]/(double)num_contributors; i++; } //*** // The target pixel has been established. Now need to compute the actual // remap quantities that will be written to the appropriate remap grids: //*** i = 0; for(source=sources_list.begin(); source!=sources_list.end(); source++) { computeRemapNode(*source, contributor_pixel[i], target_pixel); i++; } //*** // Delete locally allocated memory: //*** for (i=0; i& source, void* result) { static const char MODULE[]="ossimRgbGridRemapEngine::computeSourceValue"; if (traceExec()) CLOG << "entering..." << endl; //*** // This engine defines "value" as the RGB vector corresponding to the mean // RGB pixel value of the source data: //*** ((double*)result)[0] = source->computeAverageBandValue(0); ((double*)result)[1] = source->computeAverageBandValue(1); ((double*)result)[2] = source->computeAverageBandValue(2); if (traceExec()) CLOG << "returning..." << endl; return; } //***************************************************************************** // METHOD: ossimRgbGridRemapEngine::computeRemapNode // // This engine defines the remap value as the difference between the target // RGB vector and the individual point source's value vector. // //***************************************************************************** void ossimRgbGridRemapEngine::computeRemapNode(ossimAtbPointSource* ps, void* source_value, void* target_value) { static const char MODULE[] = "ossimRgbGridRemapEngine::computeRemapNode"; if (traceExec()) CLOG << "entering..." << endl; //*** // Compute the remap grid node value specific to this RGB implementation: //*** double node[3]; node[0] = ((double*)target_value)[0] - ((double*)source_value)[0]; node[1] = ((double*)target_value)[1] - ((double*)source_value)[1]; node[2] = ((double*)target_value)[2] - ((double*)source_value)[2]; //*** // Fetch a pointer to the remapper feeding this point source in order to // pass it the node value: //*** ossimGridRemapSource* remapper = ps->getRemapSource(); remapper->setGridNode(ps->getViewPoint(), node); if (traceExec()) CLOG << "returning..." << endl; return; } ossim-Miami-2.9.1/src/imaging/ossimRgbImage.cpp000066400000000000000000001065711352751253100213630ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // Description: // // // Credits: // Much of the implementation within this file was taken from gd // We can use it but we need to give credit to the people who wrote // the algorithms. // // COPYRIGHT STATEMENT FOLLOWS THIS LINE // Portions copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 // by Cold Spring Harbor Laboratory. Funded under Grant P41-RR02188 by // the National Institutes of Health. // Portions copyright 1996, 1997, 1998, 1999, 2000, 2001 by // Boutell.Com, Inc. // Portions relating to GD2 format copyright 1999, 2000 Philip Warner. // Portions relating to PNG copyright 1999, 2000 Greg Roelofs. // Portions relating to libttf copyright 1999, 2000 John Ellson // (ellson@lucent.com). // Portions relating to JPEG and to color quantization copyright 2000, // Doug Becker and copyright (C) 1994-1998, Thomas G. Lane. This // software is based in part on the work of the Independent JPEG // Group. See the file README-JPEG.TXT for more information. // Portions relating to WBMP copyright 2000 Maurice Szmurlo and Johan // Van den Brande. // _Permission has been granted to copy, distribute and modify gd in // any context without fee, including a commercial application, // provided that this notice is present in user-accessible supporting // documentation._ // This does not affect your ownership of the derived work itself, and // the intent is to assure proper credit for the authors of gd, not to // interfere with your productive use of gd. If you have questions, // ask. "Derived works" includes all programs that utilize the // library. Credit must be given in user-accessible documentation. // _This software is provided "AS IS."_ The copyright holders disclaim // all warranties, either express or implied, including but not // limited to implied warranties of merchantability and fitness for a // particular purpose, with respect to this code and accompanying // documentation. // Although their code does not appear in gd 2.0.1, the authors wish // to thank David Koblas, David Rowley, and Hutchison Avenue Software // Corporation for their prior contributions. // END OF COPYRIGHT STATEMENT //************************************************************************* // $Id: ossimRgbImage.cpp 21184 2012-06-29 15:13:09Z dburken $ #include #include #include #include using namespace std; // this should be in another file. This is from gd's gdtable.c file and has // precomputations for sine and cosine. It looks like they multiply the cos and // sign by 1024 and store the rounded int. static const int gdCosT[] = { 1024, 1023, 1023, 1022, 1021, 1020, 1018, 1016, 1014, 1011, 1008, 1005, 1001, 997, 993, 989, 984, 979, 973, 968, 962, 955, 949, 942, 935, 928, 920, 912, 904, 895, 886, 877, 868, 858, 848, 838, 828, 817, 806, 795, 784, 772, 760, 748, 736, 724, 711, 698, 685, 671, 658, 644, 630, 616, 601, 587, 572, 557, 542, 527, 512, 496, 480, 464, 448, 432, 416, 400, 383, 366, 350, 333, 316, 299, 282, 265, 247, 230, 212, 195, 177, 160, 142, 124, 107, 89, 71, 53, 35, 17, 0, -17, -35, -53, -71, -89, -107, -124, -142, -160, -177, -195, -212, -230, -247, -265, -282, -299, -316, -333, -350, -366, -383, -400, -416, -432, -448, -464, -480, -496, -512, -527, -542, -557, -572, -587, -601, -616, -630, -644, -658, -671, -685, -698, -711, -724, -736, -748, -760, -772, -784, -795, -806, -817, -828, -838, -848, -858, -868, -877, -886, -895, -904, -912, -920, -928, -935, -942, -949, -955, -962, -968, -973, -979, -984, -989, -993, -997, -1001, -1005, -1008, -1011, -1014, -1016, -1018, -1020, -1021, -1022, -1023, -1023, -1024, -1023, -1023, -1022, -1021, -1020, -1018, -1016, -1014, -1011, -1008, -1005, -1001, -997, -993, -989, -984, -979, -973, -968, -962, -955, -949, -942, -935, -928, -920, -912, -904, -895, -886, -877, -868, -858, -848, -838, -828, -817, -806, -795, -784, -772, -760, -748, -736, -724, -711, -698, -685, -671, -658, -644, -630, -616, -601, -587, -572, -557, -542, -527, -512, -496, -480, -464, -448, -432, -416, -400, -383, -366, -350, -333, -316, -299, -282, -265, -247, -230, -212, -195, -177, -160, -142, -124, -107, -89, -71, -53, -35, -17, 0, 17, 35, 53, 71, 89, 107, 124, 142, 160, 177, 195, 212, 230, 247, 265, 282, 299, 316, 333, 350, 366, 383, 400, 416, 432, 448, 464, 480, 496, 512, 527, 542, 557, 572, 587, 601, 616, 630, 644, 658, 671, 685, 698, 711, 724, 736, 748, 760, 772, 784, 795, 806, 817, 828, 838, 848, 858, 868, 877, 886, 895, 904, 912, 920, 928, 935, 942, 949, 955, 962, 968, 973, 979, 984, 989, 993, 997, 1001, 1005, 1008, 1011, 1014, 1016, 1018, 1020, 1021, 1022, 1023, 1023 }; static const int gdSinT[] = { 0, 17, 35, 53, 71, 89, 107, 124, 142, 160, 177, 195, 212, 230, 247, 265, 282, 299, 316, 333, 350, 366, 383, 400, 416, 432, 448, 464, 480, 496, 512, 527, 542, 557, 572, 587, 601, 616, 630, 644, 658, 671, 685, 698, 711, 724, 736, 748, 760, 772, 784, 795, 806, 817, 828, 838, 848, 858, 868, 877, 886, 895, 904, 912, 920, 928, 935, 942, 949, 955, 962, 968, 973, 979, 984, 989, 993, 997, 1001, 1005, 1008, 1011, 1014, 1016, 1018, 1020, 1021, 1022, 1023, 1023, 1024, 1023, 1023, 1022, 1021, 1020, 1018, 1016, 1014, 1011, 1008, 1005, 1001, 997, 993, 989, 984, 979, 973, 968, 962, 955, 949, 942, 935, 928, 920, 912, 904, 895, 886, 877, 868, 858, 848, 838, 828, 817, 806, 795, 784, 772, 760, 748, 736, 724, 711, 698, 685, 671, 658, 644, 630, 616, 601, 587, 572, 557, 542, 527, 512, 496, 480, 464, 448, 432, 416, 400, 383, 366, 350, 333, 316, 299, 282, 265, 247, 230, 212, 195, 177, 160, 142, 124, 107, 89, 71, 53, 35, 17, 0, -17, -35, -53, -71, -89, -107, -124, -142, -160, -177, -195, -212, -230, -247, -265, -282, -299, -316, -333, -350, -366, -383, -400, -416, -432, -448, -464, -480, -496, -512, -527, -542, -557, -572, -587, -601, -616, -630, -644, -658, -671, -685, -698, -711, -724, -736, -748, -760, -772, -784, -795, -806, -817, -828, -838, -848, -858, -868, -877, -886, -895, -904, -912, -920, -928, -935, -942, -949, -955, -962, -968, -973, -979, -984, -989, -993, -997, -1001, -1005, -1008, -1011, -1014, -1016, -1018, -1020, -1021, -1022, -1023, -1023, -1024, -1023, -1023, -1022, -1021, -1020, -1018, -1016, -1014, -1011, -1008, -1005, -1001, -997, -993, -989, -984, -979, -973, -968, -962, -955, -949, -942, -935, -928, -920, -912, -904, -895, -886, -877, -868, -858, -848, -838, -828, -817, -806, -795, -784, -772, -760, -748, -736, -724, -711, -698, -685, -671, -658, -644, -630, -616, -601, -587, -572, -557, -542, -527, -512, -496, -480, -464, -448, -432, -416, -400, -383, -366, -350, -333, -316, -299, -282, -265, -247, -230, -212, -195, -177, -160, -142, -124, -107, -89, -71, -53, -35, -17 }; ossimRgbImage::ossimRgbImage() : ossimReferenced(), theImageData(0), theOffsets(0), theThickness(1), theRed(255), theGreen(255), theBlue(255) { } ossimRgbImage::ossimRgbImage(ossimRefPtr& currentImageData) : ossimReferenced(), theImageData(0), theOffsets(0), theThickness(1), theRed(255), theGreen(255), theBlue(255) { setCurrentImageData(currentImageData); } ossimRgbImage::~ossimRgbImage() { if(theOffsets) { delete [] theOffsets; theOffsets = 0; } } const ossimRefPtr ossimRgbImage::getImageData()const { return theImageData; } void ossimRgbImage::createNewGrey(ossim_int32 width, ossim_int32 height) { theImageData = new ossimImageData(0, OSSIM_UCHAR, 1, width, height); theImageData->initialize(); setCurrentImageData(theImageData); } void ossimRgbImage::createNewTrueColor(ossim_int32 width, ossim_int32 height) { theImageData = new ossimImageData(0, OSSIM_UCHAR, 3, width, height); theImageData->initialize(); } void ossimRgbImage::initialize() { if(!theImageData) { return; } if(theOffsets) { delete [] theOffsets; theOffsets = 0; } theWidth = theImageData->getWidth(); theHeight = theImageData->getHeight(); theOffsets = new ossim_int32[theHeight]; for(ossim_int32 row = 0; row < theHeight; ++row) { theOffsets[row] = row*theWidth; } // make it work for 1, 2, or 3 band data. // we assume the fourth band is for the alpha channel if(theImageData->getNumberOfBands() >= 3) { // point each band to r, g, b. theBands[0] = static_cast(theImageData->getBuf(0)); theBands[1] = static_cast(theImageData->getBuf(1)); theBands[2] = static_cast(theImageData->getBuf(2)); } else if(theImageData->getNumberOfBands() == 2) {//point r and g to the same place theBands[0] = static_cast(theImageData->getBuf(0)); theBands[1] = static_cast(theImageData->getBuf(0)); theBands[2] = static_cast(theImageData->getBuf(1)); } else if(theImageData->getNumberOfBands() == 1) {// point all band s to the first band theBands[0] = static_cast(theImageData->getBuf(0)); theBands[1] = static_cast(theImageData->getBuf(0)); theBands[2] = static_cast(theImageData->getBuf(0)); } } void ossimRgbImage::setCurrentImageData(ossimRefPtr& imageData) { if(imageData.valid()) { if((imageData->getScalarType() == OSSIM_UCHAR)&& (imageData->getDataObjectStatus()!=OSSIM_NULL)) { theImageData = imageData; initialize(); } } } ossimRefPtr ossimRgbImage::getImageData() { return theImageData; } void ossimRgbImage::drawPolygon(ossimIpt *p, int n) { if(!theImageData) { return; } int i; int lx, ly; if (!n) { return; } lx = p->x; ly = p->y; drawLine (lx, ly, p[n - 1].x, p[n - 1].y); for (i = 1; (i < n); i++) { p++; drawLine (lx, ly, p->x, p->y); lx = p->x; ly = p->y; } } void ossimRgbImage::drawPolygon(ossimDpt *p, int n) { if(!theImageData) { return; } int i; double lx, ly; if (!n) { return; } lx = p->x; ly = p->y; drawLine (lx, ly, p[n - 1].x, p[n - 1].y); for (i = 1; (i < n); i++) { p++; drawLine (lx, ly, p->x, p->y); lx = p->x; ly = p->y; } } void ossimRgbImage::drawPolygon(const std::vector &p) { if(!theImageData) { return; } int n = (int)p.size(); int i; int lx, ly; if (!n) { return; } lx = p[0].x; ly = p[0].y; drawLine (lx, ly, p[n - 1].x, p[n - 1].y); for (i = 1; (i < n); i++) { drawLine (lx, ly, p[i].x, p[i].y); lx = p[i].x; ly = p[i].y; } } void ossimRgbImage::drawPolygon(const std::vector &p) { if(!theImageData) { return; } int n = (int)p.size(); int i; double lx, ly; if (!n) { return; } lx = p[0].x; ly = p[0].y; drawLine (lx, ly, p[n - 1].x, p[n - 1].y); for (i = 1; (i < n); i++) { drawLine (lx, ly, p[i].x, p[i].y); lx = p[i].x; ly = p[i].y; } } inline int gdCompareInt (const void *a, const void *b) { return (*(const int *) a) - (*(const int *) b); } void ossimRgbImage::drawFilledArc (double cx, double cy, double w, double h, double s, double e) { // drawFilledArc((int)ossim::round(cx), // center x // (int)ossim::round(cy), // center y // (int)ossim::round(w), // width // (int)ossim::round(h), // height // (int)ossim::round(s), // start angle // (int)ossim::round(e)); // end angle drawFilledArc((int)(cx), // center x (int)(cy), // center y (int)(w), // width (int)(h), // height (int)(s), // start angle (int)(e)); // end angle } void ossimRgbImage::drawFilledArc (int cx, int cy, int w, int h, int s, int e) { if(!theImageData) { return; } ossimIpt pts[3]; int i; int lx = 0, ly = 0; // int fx, fy; int w2, h2; w2 = w / 2; h2 = h / 2; while (e < s) { e += 360; } for (i = s; (i <= e); i++) { int x, y; x = ((ossim_int32) gdCosT[i % 360] * (ossim_int32) w2 / 1024) + cx; y = ((ossim_int32) gdSinT[i % 360] * (ossim_int32) h2 / 1024) + cy; if (i != s) { /* This is expensive! */ pts[0].x = lx; pts[0].y = ly; pts[1].x = x; pts[1].y = y; pts[2].x = cx; pts[2].y = cy; drawFilledPolygon (pts, 3); } // else // { // fx = x; // fy = y; // } lx = x; ly = y; } } void ossimRgbImage::drawArc (int cx, int cy, int w, int h, int s, int e) { if(!theImageData) { return; } int i; int lx = 0, ly = 0; // int fx, fy; int w2, h2; w2 = w / 2; h2 = h / 2; while (e < s) { e += 360; } for (i = s; (i <= e); i++) { int x, y; x = ((ossim_int32) gdCosT[i % 360] * (ossim_int32) w2 / 1024) + cx; y = ((ossim_int32) gdSinT[i % 360] * (ossim_int32) h2 / 1024) + cy; if (i != s) { drawLine (lx, ly, x, y); } // else // { // fx = x; // fy = y; // } lx = x; ly = y; } } void ossimRgbImage::drawFilledEllipse (int cx, int cy, int axisMinor, int axisMajor, double rot) { if(!theImageData) { return; } int lx = 0; int ly = 0; int w2 = axisMinor/2; int h2 = axisMajor/2; ossimIpt pts[3]; float sinRot = sin(rot); float cosRot = cos(rot); for (int i = 0; i <= 360; ++i) { int x = ((ossim_int32) gdCosT[i % 360] * (ossim_int32) w2 / 1024); int y = ((ossim_int32) gdSinT[i % 360] * (ossim_int32) h2 / 1024); int rx = (ossim_int32)((float)x*cosRot - (float)y*sinRot + cx); int ry = (ossim_int32)((float)y*cosRot + (float)x*sinRot + cy); if (i != 0) { /* This is expensive! */ pts[0].x = lx; pts[0].y = ly; pts[1].x = rx; pts[1].y = ry; pts[2].x = cx; pts[2].y = cy; drawFilledPolygon (pts, 3); } lx = rx; ly = ry; } } void ossimRgbImage::drawEllipse (int cx, int cy, int axisMinor, int axisMajor, double rot, bool drawAxes) { if(!theImageData) { return; } // Range check rotation. if ( (rot < -TWO_PI) || (rot > TWO_PI) ) { rot = 0.0; // throw exception or continue??? } int lx = 0; int ly = 0; int w2 = axisMinor/2; int h2 = axisMajor/2; float sinRot = sin(rot); float cosRot = cos(rot); int xMaj[2]; int yMaj[2]; int xMin[2]; int yMin[2]; xMin[0] = 0; xMin[1] = 0; yMin[0] = 0; yMin[1] = 0; xMaj[0] = 0; xMaj[1] = 0; yMaj[0] = 0; yMaj[1] = 0; for (int i = 0; i <= 360; i++) { // Compute current coordinates int x = ((ossim_int32) gdCosT[i % 360] * (ossim_int32) w2 / 1024); int y = ((ossim_int32) gdSinT[i % 360] * (ossim_int32) h2 / 1024); // Rotate through orientation angle int rx = (ossim_int32)((float)x*cosRot - (float)y*sinRot + cx); int ry = (ossim_int32)((float)y*cosRot + (float)x*sinRot + cy); // Draw the 1-degree segment if (i != 0) { drawLine (lx, ly, rx, ry); } lx = rx; ly = ry; if (drawAxes) { // Save axes end-points switch (i) { case 0: xMin[0] = rx; yMin[0] = ry; break; case 90: xMaj[0] = rx; yMaj[0] = ry; break; case 180: xMin[1] = rx; yMin[1] = ry; break; case 270: xMaj[1] = rx; yMaj[1] = ry; break; default: break; } } } // Draw axes if selected if (drawAxes) { ossim_uint8 rCurr; ossim_uint8 gCurr; ossim_uint8 bCurr; getDrawColor(rCurr, gCurr, bCurr); ossim_int32 thickCurr = theThickness; ossim_uint8 mask = 0xff; // Draw the minor axis first so it is on the bottom. drawLine (xMin[0], yMin[0], xMin[1], yMin[1]); //set major axis to thicker yellow setDrawColor((rCurr^mask),(gCurr^mask),(bCurr^mask)); // setDrawColor(255,255,1); theThickness += 1; drawLine (xMaj[0], yMaj[0], xMaj[1], yMaj[1]); theThickness = thickCurr; setDrawColor(rCurr,gCurr,bCurr); //set back } } void ossimRgbImage::drawFilledPolygon(ossimIpt *p, int n) { if(!theImageData) { return; } int i; int y; int miny, maxy; int minx, maxx; int x1, y1; int x2, y2; int ind1, ind2; int ints; int *polyInts = 0; if(!n) { return; } polyInts = new int[n]; miny = p[0].y; maxy = p[0].y; minx = p[0].x; maxx = p[0].x; for (i = 1; (i < n); i++) { miny = std::min((int)p[i].y, miny); minx = std::min((int)p[i].x, minx); maxy = std::max((int)p[i].y, maxy); maxx = std::max((int)p[i].x, maxx); } /* Fix in 1.3: count a vertex only once */ for (y = miny; (y <= maxy); y++) { ints = 0; for (i = 0; (i < n); i++) { if (!i) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } y1 = p[ind1].y; y2 = p[ind2].y; if (y1 < y2) { x1 = p[ind1].x; x2 = p[ind2].x; } else if (y1 > y2) { y2 = p[ind1].y; y1 = p[ind2].y; x2 = p[ind1].x; x1 = p[ind2].x; } else { continue; } if ((y >= y1) && (y < y2)) { polyInts[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; } else if ((y == maxy) && (y > y1) && (y <= y2)) { polyInts[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; } } qsort (polyInts, ints, sizeof (int), gdCompareInt); if(ints) { for (i = 0; (i < (ints)); i += 2) { drawLine (polyInts[i], y, polyInts[i + 1], y); } } else { if((miny == maxy) && (minx==maxx)) { drawLine((int)p[0].x, (int)p[0].y, (int)p[0].x, (int)p[0].y); } } } if (polyInts) delete [] polyInts; } void ossimRgbImage::drawFilledPolygon(ossimDpt *p, int n) { if(!theImageData) { return; } int i; int y; int miny, maxy; int x1, y1; int x2, y2; int ind1, ind2; int ints; int *polyInts = 0; if(!n) { return; } polyInts = new int[n]; // miny = ossim::round(p[0].y); // maxy = ossim::round(p[0].y); miny = (int)(p[0].y); maxy = (int)(p[0].y); for (i = 1; (i < n); i++) { // int testPy = ossim::round(p[i].y); int testPy = (int)(p[i].y); if (testPy < miny) { miny = testPy; } if (testPy > maxy) { maxy = testPy; } } /* Fix in 1.3: count a vertex only once */ for (y = miny; (y <= maxy); y++) { ints = 0; for (i = 0; (i < n); i++) { if (!i) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } // y1 = ossim::round(p[ind1].y); // y2 = ossim::round(p[ind2].y); y1 = (int)(p[ind1].y); y2 = (int)(p[ind2].y); if (y1 < y2) { x1 = ossim::round(p[ind1].x); x2 = ossim::round(p[ind2].x); } else if (y1 > y2) { // y2 = ossim::round(p[ind1].y); // y1 = ossim::round(p[ind2].y); // x2 = ossim::round(p[ind1].x); // x1 = ossim::round(p[ind2].x); y2 = (int)(p[ind1].y); y1 = (int)(p[ind2].y); x2 = (int)(p[ind1].x); x1 = (int)(p[ind2].x); } else { continue; } if ((y >= y1) && (y < y2)) { polyInts[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; } else if ((y == maxy) && (y > y1) && (y <= y2)) { polyInts[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; } } qsort (polyInts, ints, sizeof (int), gdCompareInt); for (i = 0; (i < (ints)); i += 2) { drawLine (polyInts[i], y, polyInts[i + 1], y); } } if (polyInts) delete [] polyInts; } void ossimRgbImage::drawFilledPolygon(const std::vector &p) { if(!theImageData) { return; } int n = (int)p.size(); int i; int y; int miny, maxy; int x1, y1; int x2, y2; int ind1, ind2; int ints; int *polyInts = 0; if(!n) { return; } polyInts = new int[n]; miny = p[0].y; maxy = p[0].y; for (i = 1; (i < n); i++) { if (p[i].y < miny) { miny = p[i].y; } if (p[i].y > maxy) { maxy = p[i].y; } } /* Fix in 1.3: count a vertex only once */ for (y = miny; (y <= maxy); y++) { ints = 0; for (i = 0; (i < n); i++) { if (!i) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } y1 = p[ind1].y; y2 = p[ind2].y; if (y1 < y2) { x1 = p[ind1].x; x2 = p[ind2].x; } else if (y1 > y2) { y2 = p[ind1].y; y1 = p[ind2].y; x2 = p[ind1].x; x1 = p[ind2].x; } else { continue; } if ((y >= y1) && (y < y2)) { polyInts[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; } else if ((y == maxy) && (y > y1) && (y <= y2)) { polyInts[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; } } qsort (polyInts, ints, sizeof (int), gdCompareInt); for (i = 0; (i < (ints)); i += 2) { drawLine (polyInts[i], y, polyInts[i + 1], y); } } if (polyInts) delete [] polyInts; } void ossimRgbImage::drawFilledPolygon(const std::vector &p) { if(!theImageData) { return; } int n = (int)p.size(); int i; int y; int miny, maxy; int x1, y1; int x2, y2; int ind1, ind2; int ints; int *polyInts = 0; if(!n) { return; } polyInts = new int[n]; miny = (int)p[0].y;//ossim::round(p[0].y); maxy = (int)p[0].y;//ossim::round(p[0].y); for (i = 1; (i < n); i++) { int testPy = (int)p[i].y;//ossim::round(p[i].y); if (testPy < miny) { miny = testPy; } if (testPy > maxy) { maxy = testPy; } } /* Fix in 1.3: count a vertex only once */ for (y = miny; (y <= maxy); y++) { ints = 0; for (i = 0; (i < n); i++) { if (!i) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } // y1 = ossim::round(p[ind1].y); // y2 = ossim::round(p[ind2].y); y1 = (int)(p[ind1].y); y2 = (int)(p[ind2].y); if (y1 < y2) { // x1 = ossim::round(p[ind1].x); // x2 = ossim::round(p[ind2].x); x1 = (int)(p[ind1].x); x2 = (int)(p[ind2].x); } else if (y1 > y2) { // y2 = ossim::round(p[ind1].y); // y1 = ossim::round(p[ind2].y); // x2 = ossim::round(p[ind1].x); // x1 = ossim::round(p[ind2].x); y2 = (int)(p[ind1].y); y1 = (int)(p[ind2].y); x2 = (int)(p[ind1].x); x1 = (int)(p[ind2].x); } else { continue; } if ((y >= y1) && (y < y2)) { polyInts[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; } else if ((y == maxy) && (y > y1) && (y <= y2)) { polyInts[ints++] = (y - y1) * (x2 - x1) / (y2 - y1) + x1; } } qsort (polyInts, ints, sizeof (int), gdCompareInt); for (i = 0; (i < (ints)); i += 2) { drawLine (polyInts[i], y, polyInts[i + 1], y); } } if (polyInts) delete [] polyInts; } void ossimRgbImage::drawLine(const ossimIpt& start, const ossimIpt& end) { drawLine((int)start.x, (int)start.y, (int)end.x, (int)end.y); } void ossimRgbImage::drawLine(const ossimDpt& start, const ossimDpt& end) { // drawLine((int)ossim::round(start.x), // (int)ossim::round(start.y), // (int)ossim::round(end.x), // (int)ossim::round(end.y)); drawLine((int)(start.x), (int)(start.y), (int)(end.x), (int)(end.y)); } void ossimRgbImage::drawLine(double x1, double y1, double x2, double y2) { // drawLine((int)ossim::round(x1), // (int)ossim::round(y1), // (int)ossim::round(x2), // (int)ossim::round(y2)); drawLine((int)(x1), (int)(y1), (int)(x2), (int)(y2)); } void ossimRgbImage::drawLine(int x1, int y1, int x2, int y2) { if(!theImageData) { return; } // we need to shift x and y relative to the image data // origin. That way we are doing the algorithm relative to // the 0,0 // ossimIpt origin = ossimDpt(theImageData->getOrigin()); x1 += (-origin.x); y1 += (-origin.y); x2 += (-origin.x); y2 += (-origin.y); // ossimDpt start(x1, y1); // ossimDpt end(x2,y2); // ossimDrect bounds(0,0,theWidth-1, theHeight-1); // if(bounds.clip(start, end)) return; // x1 = (int)start.x; // y1 = (int)start.y; // x2 = (int)end.x; // y2 = (int)end.y; int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag; int wid; int w, wstart; int thick = theThickness; dx = abs (x2 - x1); dy = abs (y2 - y1); if (dy <= dx) { /* More-or-less horizontal. use wid for vertical stroke */ /* Doug Claar: watch out for NaN in atan2 (2.0.5) */ if ((dx == 0) && (dy == 0)) { wid = 1; } else { /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double ac = cos (atan2 ((double)dy, (double)dx)); if (ac != 0) { wid = ossim::round(thick / ac); } else { wid = 1; } if (wid == 0) { wid = 1; } } d = 2 * dy - dx; incr1 = 2 * dy; incr2 = 2 * (dy - dx); if (x1 > x2) { x = x2; y = y2; ydirflag = (-1); xend = x1; } else { x = x1; y = y1; ydirflag = 1; xend = x2; } /* Set up line thickness */ wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) slowPlotPixel(x, w, theRed, theGreen, theBlue); if (((y2 - y1) * ydirflag) > 0) { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y++; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) slowPlotPixel(x, w, theRed, theGreen, theBlue); } } else { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y--; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) slowPlotPixel(x, w, theRed, theGreen, theBlue); } } } else { /* More-or-less vertical. use wid for horizontal stroke */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 ((double)dy, (double)dx)); if (as != 0) { wid = ossim::round(thick / as); } else { wid = 1; } if (wid == 0) wid = 1; d = 2 * dx - dy; incr1 = 2 * dx; incr2 = 2 * (dx - dy); if (y1 > y2) { y = y2; x = x2; yend = y1; xdirflag = (-1); } else { y = y1; x = x1; yend = y2; xdirflag = 1; } /* Set up line thickness */ wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) slowPlotPixel(w, y, theRed, theGreen, theBlue); if (((x2 - x1) * xdirflag) > 0) { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x++; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) slowPlotPixel(w, y, theRed, theGreen, theBlue); } } else { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x--; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) slowPlotPixel(w, y, theRed, theGreen, theBlue); } } } } void ossimRgbImage::drawRectangle(double x1, double y1, double x2, double y2) { // drawRectangle(ossim::round(x1), // ossim::round(y1), // ossim::round(x2), // ossim::round(y2)); drawRectangle((int)(x1), (int)(y1), (int)(x2), (int)(y2)); } void ossimRgbImage::drawRectangle(int x1, int y1, int x2, int y2) { if(x1 > x2) { swap(x1, x2); } if(y1 > y2) { swap(y1, y2); } int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2; int thick = theThickness; if (thick > 1) { int half = thick / 2; int half1 = thick - half; if (y1 < y2) { y1v = y1h - half; y2v = y2h + half1 - 1; } else { y1v = y1h + half1 - 1; y2v = y2h - half; } } drawLine (x1h, y1h, x2h, y1h); drawLine (x1h, y2h, x2h, y2h); drawLine (x1v, y1v, x1v, y2v); drawLine (x2v, y1v, x2v, y2v); } void ossimRgbImage::drawFilledRectangle(double x1, double y1, double x2, double y2) { // drawFilledRectangle((int)ossim::round(x1), // (int)ossim::round(y1), // (int)ossim::round(x2), // (int)ossim::round(y2)); drawFilledRectangle((int)(x1), (int)(y1), (int)(x2), (int)(y2)); } void ossimRgbImage::drawFilledRectangle(int x1, int y1, int x2, int y2) { int x, y; if(x1 > x2) { swap(x1, x2); } if(y1 > y2) { swap(y1, y2); } for (y = y1; (y <= y2); y++) { for (x = x1; (x <= x2); x++) { slowPlotPixel (x, y, theRed, theGreen, theBlue); } } } void ossimRgbImage::fill() { if(!theImageData) { return; } ossim_int32 width = theWidth; ossim_int32 height = theHeight; for(ossim_int32 row = 0; row < height; ++row) { for(ossim_int32 col = 0; col < width; ++col) { fastPlotPixel(col, row, theRed, theGreen, theBlue); } } } void ossimRgbImage::setDrawColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { theRed = r; theGreen = g; theBlue = b; } void ossimRgbImage::getDrawColor(ossim_uint8& rCurr, ossim_uint8& gCurr, ossim_uint8& bCurr) { rCurr = theRed; gCurr = theGreen; bCurr = theBlue; } void ossimRgbImage::setThickness(ossim_int32 thickness) { theThickness = thickness; } ossim_int32 ossimRgbImage::getThickness() const { return theThickness; } ossim-Miami-2.9.1/src/imaging/ossimRgbToGreyFilter.cpp000066400000000000000000000145501352751253100227130ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToGreyFilter.cpp 19223 2011-03-24 13:38:21Z dburken $ #include #include #include #include #include RTTI_DEF1(ossimRgbToGreyFilter, "ossimRgbToGreyFilter", ossimImageSourceFilter) ossimRgbToGreyFilter::ossimRgbToGreyFilter(ossimObject* owner) :ossimImageSourceFilter(owner), theBlankTile(NULL), theTile(NULL), theC1(1.0/3.0), theC2(1.0/3.0), theC3(1.0/3.0) { } ossimRgbToGreyFilter::ossimRgbToGreyFilter(ossimImageSource* inputSource, double c1, double c2, double c3) : ossimImageSourceFilter(NULL, inputSource), theBlankTile(NULL), theTile(NULL), theC1(c1), theC2(c2), theC3(c3) { } ossimRgbToGreyFilter::ossimRgbToGreyFilter(ossimObject* owner, ossimImageSource* inputSource, double c1, double c2, double c3) : ossimImageSourceFilter(owner, inputSource), theBlankTile(NULL), theTile(NULL), theC1(c1), theC2(c2), theC3(c3) { } ossimRgbToGreyFilter::~ossimRgbToGreyFilter() { } ossimRefPtr ossimRgbToGreyFilter::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return NULL; // This filter requires an input. } ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if(!isSourceEnabled() || !inputTile.valid()) { return inputTile; } if(!theTile) { allocate(); // First time through... } // if (!theTile) // throw exeption... if( inputTile->getDataObjectStatus() == OSSIM_NULL || inputTile->getDataObjectStatus() == OSSIM_EMPTY ) { theBlankTile->setImageRectangle(tileRect); return theBlankTile; } // Set the origin, resize if needed of the output tile. theTile->setImageRectangle(tileRect); // Filter the tile. runUcharTransformation(inputTile); // Always validate to set the status. theTile->validate(); return theTile; } void ossimRgbToGreyFilter::initialize() { // Base class will recapture "theInputConnection". ossimImageSourceFilter::initialize(); } void ossimRgbToGreyFilter::allocate() { if(theInputConnection) { theTile = NULL; theBlankTile = NULL; if(isSourceEnabled()) { theBlankTile = new ossimU8ImageData(this, 1, theInputConnection->getTileWidth(), theInputConnection->getTileHeight()); theTile = (ossimImageData*)theBlankTile->dup(); theTile->initialize(); } } } ossim_uint32 ossimRgbToGreyFilter::getNumberOfOutputBands() const { if(isSourceEnabled()) { return 1; } return ossimImageSourceFilter::getNumberOfOutputBands(); } bool ossimRgbToGreyFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimImageSourceFilter::saveState(kwl, prefix); kwl.add(prefix, "c1", theC1, true); kwl.add(prefix, "c2", theC2, true); kwl.add(prefix, "c3", theC2, true); return true; } bool ossimRgbToGreyFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimImageSourceFilter::loadState(kwl, prefix); const char* lookup = kwl.find(prefix, "c1"); if(lookup) { theC1 = ossimString(lookup).toDouble(); } lookup = kwl.find(prefix, "c2"); if(lookup) { theC2 = ossimString(lookup).toDouble(); } lookup = kwl.find(prefix, "c3"); if(lookup) { theC3 = ossimString(lookup).toDouble(); } return true; } void ossimRgbToGreyFilter::runUcharTransformation(ossimRefPtr& tile) { unsigned char** bandSrc = new unsigned char*[tile->getNumberOfBands()]; unsigned char* bandDest; if(tile->getNumberOfBands() == 1) { bandSrc[0] = static_cast(tile->getBuf(0)); bandSrc[1] = static_cast(tile->getBuf(0)); bandSrc[2] = static_cast(tile->getBuf(0)); } else if(tile->getNumberOfBands() == 2) { bandSrc[0] = static_cast(tile->getBuf(0)); bandSrc[1] = static_cast(tile->getBuf(1)); bandSrc[2] = static_cast(tile->getBuf(1)); } else if(tile->getNumberOfBands() >= 3) { bandSrc[0] = static_cast(tile->getBuf(0)); bandSrc[1] = static_cast(tile->getBuf(1)); bandSrc[2] = static_cast(tile->getBuf(2)); } bandDest = static_cast(theTile->getBuf()); ossim_int32 offset; ossim_int32 upperBound = tile->getWidth()*tile->getHeight(); for(offset = 0; offset < upperBound; ++offset) { ossim_int32 value; value = ossim::round(theC1*(bandSrc[0][offset]) + theC2*(bandSrc[1][offset]) + theC3*(bandSrc[2][offset])); value = value<255?value:255; value = value>0?value:0; bandDest[offset] = value; } delete [] bandSrc; } ossimString ossimRgbToGreyFilter::getShortName()const { return ossimString("grey"); } ossimString ossimRgbToGreyFilter::getLongName()const { return ossimString("rgb to grey scale filter"); } ossimScalarType ossimRgbToGreyFilter::getOutputScalarType() const { if(isSourceEnabled()) { return OSSIM_UCHAR; } return ossimImageSourceFilter::getOutputScalarType(); } ossim-Miami-2.9.1/src/imaging/ossimRgbToHsiSource.cpp000066400000000000000000000103451352751253100225410ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToHsiSource.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include #include RTTI_DEF1(ossimRgbToHsiSource, "ossimRgbToHsiSource", ossimImageSourceFilter) ossimRgbToHsiSource::ossimRgbToHsiSource() :ossimImageSourceFilter(), theBlankTile(NULL), theTile(NULL) { } ossimRgbToHsiSource::ossimRgbToHsiSource(ossimImageSource* inputSource) : ossimImageSourceFilter(inputSource), theBlankTile(NULL), theTile(NULL) { } ossimRgbToHsiSource::~ossimRgbToHsiSource() { } ossimRefPtr ossimRgbToHsiSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return ossimRefPtr(); // This filter requires an input. } ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if(!isSourceEnabled() || !inputTile.valid()) { return inputTile; } if(!theTile) { allocate(); // First time through... } if (!theTile.valid()) { return inputTile; } if( inputTile->getDataObjectStatus() == OSSIM_NULL || inputTile->getDataObjectStatus() == OSSIM_EMPTY ) { theBlankTile->setImageRectangle(tileRect); return theBlankTile; } if((inputTile->getNumberOfBands()==3)&& (inputTile->getScalarType()==OSSIM_UCHAR)&& (inputTile->getDataObjectStatus()!=OSSIM_NULL)) { // Set the origin, resize if needed of the output tile. theTile->setImageRectangle(tileRect); float* outputBands[3]; ossim_uint8* inputBands[3]; outputBands[0] = static_cast(theTile->getBuf(0)); outputBands[1] = static_cast(theTile->getBuf(1)); outputBands[2] = static_cast(theTile->getBuf(2)); inputBands[0] = static_cast(inputTile->getBuf(0)); inputBands[1] = static_cast(inputTile->getBuf(1)); inputBands[2] = static_cast(inputTile->getBuf(2)); long height = inputTile->getHeight(); long width = inputTile->getWidth(); long offset = 0; for(long row = 0; row < height; ++row) { for(long col = 0; col < width; ++col) { ossimRgbVector rgb(inputBands[0][offset], inputBands[1][offset], inputBands[2][offset]); ossimHsiVector hsi(rgb); outputBands[0][offset] = hsi.getH(); outputBands[1][offset] = hsi.getS(); outputBands[2][offset] = hsi.getI(); ++offset; } } } else // Input tile not of correct type to process... { return inputTile; } theTile->validate(); return theTile; } ossimScalarType ossimRgbToHsiSource::getOutputScalarType() const { return OSSIM_NORMALIZED_FLOAT; } void ossimRgbToHsiSource::initialize() { // Base class will recapture "theInputConnection". ossimImageSourceFilter::initialize(); } void ossimRgbToHsiSource::allocate() { theBlankTile = NULL; theTile = NULL; if(!theInputConnection) return; theBlankTile = ossimImageDataFactory::instance()->create(this, this); theTile = (ossimImageData*)theBlankTile->dup(); theTile->initialize(); } ossim_uint32 ossimRgbToHsiSource::getNumberOfOutputBands()const { return 3; } double ossimRgbToHsiSource::getNullPixelValue()const { return ossim::nan(); } double ossimRgbToHsiSource::getMinPixelValue(ossim_uint32 /* band */)const { return 0.0; } double ossimRgbToHsiSource::getMaxPixelValue(ossim_uint32 /* band */)const { return 1.0; } ossim-Miami-2.9.1/src/imaging/ossimRgbToHsvSource.cpp000066400000000000000000000101261352751253100225530ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToHsvSource.cpp 17195 2010-04-23 17:32:18Z dburken $ #include #include #include #include #include #include #include RTTI_DEF1(ossimRgbToHsvSource, "ossimRgbToHsvSource", ossimImageSourceFilter) ossimRgbToHsvSource::ossimRgbToHsvSource() :ossimImageSourceFilter(), theBlankTile(NULL), theTile(NULL) { } ossimRgbToHsvSource::ossimRgbToHsvSource(ossimImageSource* inputSource) : ossimImageSourceFilter(inputSource), theBlankTile(NULL), theTile(NULL) { } ossimRgbToHsvSource::~ossimRgbToHsvSource() { } ossimRefPtr ossimRgbToHsvSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return ossimRefPtr(); // This filter requires an input. } ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if(!isSourceEnabled() || !inputTile.valid()) { return inputTile; } if(!theTile.valid()) { allocate(); // First time through... } if (!theTile.valid()) // throw exeption... { return inputTile; } if( inputTile->getDataObjectStatus() == OSSIM_NULL || inputTile->getDataObjectStatus() == OSSIM_EMPTY ) { theBlankTile->setImageRectangle(tileRect); return theBlankTile; } if((inputTile->getNumberOfBands()==3)&& (inputTile->getScalarType()==OSSIM_UCHAR)&& (inputTile->getDataObjectStatus()!=OSSIM_NULL)) { // Set the origin, resize if needed of the output tile. theTile->setImageRectangle(tileRect); float* outputBands[3]; ossim_uint8* inputBands[3]; outputBands[0] = static_cast(theTile->getBuf(0)); outputBands[1] = static_cast(theTile->getBuf(1)); outputBands[2] = static_cast(theTile->getBuf(2)); inputBands[0] = static_cast(inputTile->getBuf(0)); inputBands[1] = static_cast(inputTile->getBuf(1)); inputBands[2] = static_cast(inputTile->getBuf(2)); long height = inputTile->getHeight(); long width = inputTile->getWidth(); long offset = 0; for(long row = 0; row < height; ++row) { for(long col = 0; col < width; ++col) { ossimRgbVector rgb(inputBands[0][offset], inputBands[1][offset], inputBands[2][offset]); ossimHsvVector hsv(rgb); outputBands[0][offset] = hsv.getH(); outputBands[1][offset] = hsv.getS(); outputBands[2][offset] = hsv.getV(); ++offset; } } } else // Input tile not of correct type to process... { return inputTile; } theTile->validate(); return theTile; } void ossimRgbToHsvSource::initialize() { // Base class will recapture "theInputConnection". ossimImageSourceFilter::initialize(); } void ossimRgbToHsvSource::allocate() { theBlankTile = ossimImageDataFactory::instance()->create(this, this); theTile = (ossimImageData*)theBlankTile->dup(); theTile->initialize(); } ossimScalarType ossimRgbToHsvSource::getOutputScalarType() const { return OSSIM_NORMALIZED_FLOAT; } ossim_uint32 ossimRgbToHsvSource::getNumberOfOutputBands()const { return 3; } double ossimRgbToHsvSource::getNullPixelValue()const { return ossim::nan(); } double ossimRgbToHsvSource::getMinPixelValue(ossim_uint32 /* band */)const { return 0.0; } double ossimRgbToHsvSource::getMaxPixelValue(ossim_uint32 /* band */)const { return 1.0; } ossim-Miami-2.9.1/src/imaging/ossimRgbToIndexFilter.cpp000066400000000000000000000117041352751253100230520ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToIndexFilter.cpp 17195 2010-04-23 17:32:18Z dburken $ #include #include #include RTTI_DEF1(ossimRgbToIndexFilter, "ossimRgbToIndexFilter", ossimImageSourceFilter); ossimRgbToIndexFilter::ossimRgbToIndexFilter() :ossimImageSourceFilter(), theLut(new ossimRgbLutDataObject()), theTile(NULL) { } ossimRgbToIndexFilter::ossimRgbToIndexFilter(ossimImageSource* inputSource, const ossimRgbLutDataObject& rgbLut) :ossimImageSourceFilter(inputSource), theLut((ossimRgbLutDataObject*)rgbLut.dup()), theTile(NULL) { } ossimRgbToIndexFilter::~ossimRgbToIndexFilter() { theLut = 0; } void ossimRgbToIndexFilter::initialize() { ossimImageSourceFilter::initialize(); // Force allocate on next getTile. theTile = NULL; } void ossimRgbToIndexFilter::allocate() { theTile = NULL; if(isSourceEnabled()) { theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); } } void ossimRgbToIndexFilter::disableSource() { ossimImageSourceFilter::disableSource(); theTile = NULL; } ossimRefPtr ossimRgbToIndexFilter::getTile( const ossimIrect& origin, ossim_uint32 resLevel) { if(!theInputConnection) { return ossimRefPtr(); } if(!theTile.valid()) { allocate(); } ossimRefPtr input = theInputConnection->getTile(origin, resLevel); if(!theTile.valid() || !input.valid()) { return input; } theTile->setImageRectangle(origin); if(input->getScalarType() == OSSIM_UCHAR) { theTile->setDataObjectStatus(OSSIM_FULL); return convertInputTile(input); } else { theTile->makeBlank(); } theTile->setDataObjectStatus(OSSIM_FULL); return theTile; } ossimRefPtr ossimRgbToIndexFilter::convertInputTile(ossimRefPtr& tile) { if (!tile) { return theTile; } const ossim_uint32 BANDS = tile->getNumberOfBands(); if (!BANDS) { return theTile; } ossim_uint8* band[3]; ossim_uint8* outBand = (ossim_uint8*)theTile->getBuf(); if(BANDS >= 3) { band[0] = (ossim_uint8*)(tile->getBuf(0)); band[1] = (ossim_uint8*)(tile->getBuf(1)); band[2] = (ossim_uint8*)(tile->getBuf(2)); } else { band[0] = (ossim_uint8*)(tile->getBuf(0)); band[1] = (ossim_uint8*)(tile->getBuf(0)); band[2] = (ossim_uint8*)(tile->getBuf(0)); } if(band[0]) { ossim_uint32 upper = tile->getWidth()*tile->getHeight(); for(ossim_uint32 offset = 0; offset < upper; ++offset) { *outBand = theLut->findIndex(*band[0], *band[1], *band[2]); ++outBand; ++band[0]; ++band[1]; ++band[2]; } } return theTile; } bool ossimRgbToIndexFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString newPrefix = prefix; newPrefix = newPrefix + "lut."; theLut->saveState(kwl, newPrefix.c_str()); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimRgbToIndexFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString newPrefix = prefix; newPrefix = newPrefix + "lut."; theLut->loadState(kwl, newPrefix.c_str()); return ossimImageSourceFilter::loadState(kwl, prefix); } ossim_uint32 ossimRgbToIndexFilter::getNumberOfOutputBands() const { if(isSourceEnabled()) { return 1; } return ossimImageSourceFilter::getNumberOfOutputBands(); } ossimScalarType ossimRgbToIndexFilter::getOutputScalarType() const { if(isSourceEnabled()) { return OSSIM_UCHAR; } return ossimImageSourceFilter::getOutputScalarType(); } void ossimRgbToIndexFilter::setLut(ossimRgbLutDataObject& lut) { theLut = (ossimRgbLutDataObject*) lut.dup(); } double ossimRgbToIndexFilter::getNullPixelValue(ossim_uint32 band)const { if(isSourceEnabled()) { return 0.0; } return ossimImageSourceFilter::getNullPixelValue(band); } double ossimRgbToIndexFilter::getMinPixelValue(ossim_uint32 /* band */)const { if(isSourceEnabled()) { return 1.0; } return ossimImageSourceFilter::getMinPixelValue(); } double ossimRgbToIndexFilter::getMaxPixelValue(ossim_uint32 /* band */)const { if(isSourceEnabled()) { return 255.0; } return ossimImageSourceFilter::getMaxPixelValue(); } ossim-Miami-2.9.1/src/imaging/ossimRgbToJpegYCbCrSource.cpp000066400000000000000000000057231352751253100235720ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRgbToJpegYCbCrSource.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimRgbToJpegYCbCrSource, "ossimRgbToJpegYCbCrSource", ossimImageSourceFilter) ossimRgbToJpegYCbCrSource::ossimRgbToJpegYCbCrSource() :ossimImageSourceFilter() { theBlankTile = new ossimImageData(this, OSSIM_UCHAR, 3); } ossimRgbToJpegYCbCrSource::ossimRgbToJpegYCbCrSource(ossimImageSource* inputSource) : ossimImageSourceFilter(inputSource) { } ossimRgbToJpegYCbCrSource::~ossimRgbToJpegYCbCrSource() { } ossimRefPtr ossimRgbToJpegYCbCrSource::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { theBlankTile->setOrigin(tileRect.ul()); theBlankTile->setWidthHeight(tileRect.width(), tileRect.height()); if(theInputConnection) { ossimRefPtr imageData = theInputConnection->getTile(tileRect, resLevel); if(!imageData.valid()) { return theBlankTile; } if((isSourceEnabled())&& (imageData->getNumberOfBands()==3)&& (imageData->getScalarType()==OSSIM_UCHAR)&& (imageData->getDataObjectStatus()!=OSSIM_NULL)&& (imageData->getDataObjectStatus()!=OSSIM_EMPTY)) { ossim_uint8* bands[3]; bands[0] = static_cast(imageData->getBuf(0)); bands[1] = static_cast(imageData->getBuf(1)); bands[2] = static_cast(imageData->getBuf(2)); long height = imageData->getHeight(); long width = imageData->getWidth(); long offset = 0; for(long row = 0; row < height; ++row) { for(long col = 0; col < width; ++col) { ossimRgbVector rgb(bands[0][offset], bands[1][offset], bands[2][offset]); ossimJpegYCbCrVector ycbcr(rgb); bands[0][offset] = ycbcr.getY(); bands[1][offset] = ycbcr.getCb(); bands[2][offset] = ycbcr.getCr(); ++offset; } } imageData->validate(); } return imageData; } return theBlankTile; } ossim-Miami-2.9.1/src/imaging/ossimRpfCacheTileSource.cpp000066400000000000000000001150121352751253100233460ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimRpfCacheTileSource.cpp 1361 2010-08-26 00:24:22Z david.burken $ #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug = ossimTrace("ossimRpfCacheTileSource:debug"); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimRpfCacheTileSource.cpp 1361 2010-08-26 00:24:22Z david.burken $"; #endif RTTI_DEF1(ossimRpfCacheTileSource, "ossimRpfCacheTileSource", ossimImageHandler) const ossim_uint32 ossimRpfCacheTileSource::CIBCADRG_FRAME_WIDTH = 1536; const ossim_uint32 ossimRpfCacheTileSource::CIBCADRG_FRAME_HEIGHT = 1536; ossimRpfCacheTileSource::ossimRpfCacheTileSource() : ossimImageHandler(), // a CADRG and CIBis a 64*64*12 bit buffer and must divide by 8 to // convert to bytes m_compressedBuffer(new ossim_uint8[(64*64*12)/8]), // whether CIB or CADRG we will alocate the buffer // to the larger of the 2 (CADRG is 3 bands) m_uncompressedBuffer(new ossim_uint8[256*256*3]), m_numberOfLines(0), m_numberOfSamples(0), m_tile(0), m_fileNames(), m_tileSize(128, 128), m_productType(OSSIM_PRODUCT_TYPE_UNKNOWN), m_workFrame(new ossimRpfFrame), m_bBox_LL_Lon(0.0), m_bBox_LL_Lat(0.0), m_bBox_UR_Lon(0.0), m_bBox_UR_Lat(0.0), m_numOfFramesVertical(0), m_numOfFramesHorizontal(0), m_frameEntryArray() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfCacheTileSource::ossimRpfCacheTileSource entered...\n"; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << "\n"; #endif } m_actualImageRect.makeNan(); } ossimRpfCacheTileSource::~ossimRpfCacheTileSource() { if(m_compressedBuffer) { delete [] m_compressedBuffer; m_compressedBuffer = 0; } if(m_uncompressedBuffer) { delete [] m_uncompressedBuffer; m_uncompressedBuffer = 0; } if(m_workFrame) { delete m_workFrame; m_workFrame = 0; } close(); } ossimString ossimRpfCacheTileSource::getShortName()const { return ossimString("RpfCache"); } ossimString ossimRpfCacheTileSource::getLongName()const { return ossimString("RpfCache reader"); } void ossimRpfCacheTileSource::close() { deleteAll(); } bool ossimRpfCacheTileSource::isOpen()const { //return (theTableOfContents!=0); ossimString ext = theImageFile.ext().downcase(); if(ext == "rpf") { return true; } else { return false; } } bool ossimRpfCacheTileSource::open() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfCacheTileSource::open(): Entered....." << std::endl; } ossimFilename imageFile = theImageFile; bool result = true; if(isOpen() == false) { close(); result = false; } if(result) { if (m_fileNames.size() == 0 && m_frameEntryArray.size() == 0) { if (buildFrameEntryArray(imageFile) == false) { return false; } } setCurrentEntry(0); //--- // Adjust image rect so not to go over the -180 to 180 and -90 to 90 // bounds. //--- setActualImageRect(); // Set the base class image file name. theImageFile = imageFile; m_tile = ossimImageDataFactory::instance()->create(this, this); m_tile->initialize(); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfCacheTileSource::open(): Leaving at line" << __LINE__ << std::endl; } return result; } bool ossimRpfCacheTileSource::buildFrameEntryArray(ossimFilename imageFile) { static const char MODULE[] = "ossimRpfCacheTileSource::buildFrameEntryArray"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << endl; } std::ifstream in((imageFile).c_str() ); std::string line; ossim_uint32 index = 0; // used throughout while( in.good() ) { // Read in a line. std::getline(in, line); ossimString tmpStr = ossimString(line); if (!tmpStr.empty()) { if (index == 0) { std::vector box_lat_lon; tmpStr.split(box_lat_lon, "|"); if (box_lat_lon.size() > 2) { std::vector ll; std::vector ur; box_lat_lon[0].split(ll, ","); box_lat_lon[1].split(ur, ","); ossimString bandStr = box_lat_lon[2]; m_bBox_LL_Lon = ll[0].toFloat64(); m_bBox_LL_Lat = ll[1].toFloat64(); m_bBox_UR_Lon = ur[0].toFloat64(); m_bBox_UR_Lat = ur[1].toFloat64(); checkLongitude(m_bBox_LL_Lon, m_bBox_UR_Lon); ossim_int32 bands = ossimString(bandStr).toInt32(); if (bands == 1) { m_productType = OSSIM_PRODUCT_TYPE_CIB; } else if (bands == 3) { m_productType = OSSIM_PRODUCT_TYPE_CADRG; } } else { return false; } } else if (index == 1) { m_fileNames.push_back(tmpStr); std::vector frame_lat_lon = tmpStr.split("|"); if (frame_lat_lon.size() > 2) { ossimString ll_lon_lat = frame_lat_lon[1]; ossimString ur_lon_lat = frame_lat_lon[2]; ossim_float64 ll_lon = ossimString(ll_lon_lat.split(",")[0]).toDouble(); ossim_float64 ll_lat = ossimString(ll_lon_lat.split(",")[1]).toDouble(); ossim_float64 ur_lon = ossimString(ur_lon_lat.split(",")[0]).toDouble(); ossim_float64 ur_lat = ossimString(ur_lon_lat.split(",")[1]).toDouble(); checkLongitude(ll_lon, ur_lon); ossim_float64 bBox_lat_diff = std::fabs(m_bBox_UR_Lat - m_bBox_LL_Lat); ossim_float64 bBox_lon_diff = std::fabs(m_bBox_UR_Lon - m_bBox_LL_Lon); ossim_float64 lat_diff = std::fabs(ur_lat - ll_lat); ossim_float64 lon_diff = std::fabs(ur_lon - ll_lon); m_numOfFramesVertical = static_cast(bBox_lat_diff/lat_diff + 0.5); m_numOfFramesHorizontal = static_cast(bBox_lon_diff/lon_diff + 0.5); m_numberOfLines = m_numOfFramesVertical*CIBCADRG_FRAME_HEIGHT; m_numberOfSamples = m_numOfFramesHorizontal*CIBCADRG_FRAME_WIDTH; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nscene height in degrees: " << bBox_lat_diff << "\nscene width in degrees: " << bBox_lon_diff << "\nframe height in degrees: " << lat_diff << "\nframe width in degrees: " << lon_diff << "\nframes vertical: " << m_numOfFramesVertical << "\nframes horizontal: " << m_numOfFramesHorizontal << "\nlines: " << m_numberOfLines << "\nsamples: " << m_numberOfSamples << "\n"; } } else { return false; } } else { m_fileNames.push_back(tmpStr); } } // matches: if (!tmpStr.empty()) ++index; } // matches: while( in.good() ) in.close(); m_frameEntryArray.resize(m_numOfFramesVertical); for(index = 0; index < m_frameEntryArray.size(); ++index) { m_frameEntryArray[index].resize(m_numOfFramesHorizontal); } for(index = 0; index < m_fileNames.size(); ++index) { ossimString tmpStr = m_fileNames[index]; std::vector frameInfos = tmpStr.split("|"); if (frameInfos.size() > 1) { ossimString fileName = frameInfos[0]; ossimString ll_lon_lat = frameInfos[1]; ossimString ur_lon_lat = frameInfos[2]; double ll_lon = ossimString(ll_lon_lat.split(",")[0]).toDouble(); double ll_lat = ossimString(ll_lon_lat.split(",")[1]).toDouble(); double ur_lon = ossimString(ur_lon_lat.split(",")[0]).toDouble(); double ur_lat = ossimString(ur_lon_lat.split(",")[1]).toDouble(); checkLongitude(ll_lon, ur_lon); ossim_float64 tmpColPostion = std::fabs(ll_lon - m_bBox_LL_Lon); ossim_float64 tmpFrameLon = std::fabs(ur_lon - ll_lon); ossim_float64 tmpRowPostion = std::fabs(m_bBox_UR_Lat - ur_lat); ossim_float64 tmpFrameLat = std::fabs(ur_lat - ll_lat); ossim_uint32 colNum = static_cast(tmpColPostion/tmpFrameLon + 0.5); ossim_uint32 rowNum = static_cast(tmpRowPostion/tmpFrameLat + 0.5); if (colNum >= m_numOfFramesHorizontal) { colNum = m_numOfFramesHorizontal-1; // Clamp to last column. } if (rowNum >= m_numOfFramesVertical) { rowNum = m_numOfFramesVertical-1; // Clamp to last row. } ossimRpfFrameEntry tempEntry; tempEntry.setEntry(ossimFilename(""), fileName); m_frameEntryArray[rowNum][colNum] = tempEntry; } else { return false; } } return true; } void ossimRpfCacheTileSource::checkLongitude(ossim_float64& leftLon, const ossim_float64& rightLon) const { //--- // Test for scene coordinates being 180 to 180 and adjust leftLon to -180 // if so. // // NOTE: // Setting tolerance to 1/7200 about 15 meters. // Not sure if this is too loose or not. (drb) //--- const ossim_float64 TOLERANCE = 0.000138889; // 1/7200 about 15 meters. if ( ossim::almostEqual(leftLon, 180.0, TOLERANCE) ) { if ( ossim::almostEqual(rightLon, 180.0, TOLERANCE) ) { leftLon = -180.0; } } } ossimRefPtr ossimRpfCacheTileSource::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if (m_tile.valid()) { // Image rectangle must be set prior to calling getTile. m_tile->setImageRectangle(rect); if ( getTile( m_tile.get(), resLevel ) == false ) { if (m_tile->getDataObjectStatus() != OSSIM_NULL) { m_tile->makeBlank(); } } } return m_tile; } bool ossimRpfCacheTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) && (m_productType != OSSIM_PRODUCT_TYPE_UNKNOWN) ) { if ( resLevel > 0 ) { //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0 (if overview is not virtual). Method // returns true on success, false on error. //--- status = getOverviewTile(resLevel, result); } if (!status) // Did not get an overview tile. { status = true; ossimIrect rect = result->getImageRectangle(); ossimIrect imageRect = getImageRectangle(); if ( rect.intersects(imageRect) ) { //--- // Start with a blank tile in case there is not total coverage // for rect. //--- result->makeBlank(); vector frames = getIntersectingEntries(rect); if(frames.size() > 0) { //--- // Now lets render each frame. Note we will have to find // subframes // that intersect the rectangle of interest for each frame. //--- fillTile(rect, frames, result); // Revalidate tile status. result->validate(); } } else { result->makeBlank(); } } } return status; } ossim_uint32 ossimRpfCacheTileSource::getNumberOfInputBands()const { switch(m_productType) { case OSSIM_PRODUCT_TYPE_UNKNOWN: { return 0; } case OSSIM_PRODUCT_TYPE_CIB: { return 1; } case OSSIM_PRODUCT_TYPE_CADRG: { return 3; } } return 0; } ossim_uint32 ossimRpfCacheTileSource::getNumberOfOutputBands()const { switch(m_productType) { case OSSIM_PRODUCT_TYPE_UNKNOWN: { return 0; } case OSSIM_PRODUCT_TYPE_CIB: { return 1; } case OSSIM_PRODUCT_TYPE_CADRG: { return 3; } } return 0; } ossim_uint32 ossimRpfCacheTileSource::getNumberOfLines(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return m_numberOfLines; } else if (theOverview.valid()) { return theOverview->getNumberOfLines(reduced_res_level); } return 0; } ossim_uint32 ossimRpfCacheTileSource::getNumberOfSamples(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return m_numberOfSamples; } else if (theOverview.valid()) { return theOverview->getNumberOfSamples(reduced_res_level); } return 0; } void ossimRpfCacheTileSource::setActualImageRect() { m_actualImageRect = ossimIrect(0,0,m_numberOfLines, m_numberOfSamples); } ossimIrect ossimRpfCacheTileSource::getImageRectangle(ossim_uint32 reduced_res_level) const { return ossimIrect(0, // upper left x 0, // upper left y getNumberOfSamples(reduced_res_level) - 1, // lower right x getNumberOfLines(reduced_res_level) - 1); // lower right y } ossimRefPtr ossimRpfCacheTileSource::getImageGeometry() { if (theGeometry.valid()) return theGeometry; // datum // WGS 84 ossimKeywordlist kwl; const char* prefix = 0; // legacy kwl.add(prefix, ossimKeywordNames::DATUM_KW, "WGE", true); ossimGpt ul(m_bBox_UR_Lat,m_bBox_LL_Lon); ossimGpt ll(m_bBox_LL_Lat,m_bBox_LL_Lon); ossimGpt ur(m_bBox_UR_Lat,m_bBox_UR_Lon); ossimGpt lr(m_bBox_LL_Lat,m_bBox_UR_Lon); double latInterval = fabs(ul.latd() - lr.latd())/ getNumberOfLines(); double lonInterval = fabs(ul.lond() - ur.lond())/ getNumberOfSamples(); kwl.add(prefix, ossimKeywordNames::UL_LAT_KW, ul.latd(),//-(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::UL_LON_KW, ul.lond(),//+(lonInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::LL_LAT_KW, ll.latd(),//+(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::LL_LON_KW, ll.lond(),//+(lonInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::LR_LAT_KW, lr.latd(),//+(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::LR_LON_KW, lr.lond(),//-(lonInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::UR_LAT_KW, ur.latd(),//-(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::UR_LON_KW, ur.lond(),//-(latInterval/2.0), true); kwl.add(prefix, ossimKeywordNames::NUMBER_INPUT_BANDS_KW, getNumberOfInputBands(), true); kwl.add(prefix, ossimKeywordNames::NUMBER_OUTPUT_BANDS_KW, getNumberOfOutputBands(), true); kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, getNumberOfLines(), true); kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, getNumberOfSamples(), true); //--- // Make a projection to get the easting / northing of the tie point and // the scale in meters. This will only be used by the CIB. //--- kwl.add(prefix, ossimKeywordNames::DATUM_KW, "WGE", true); ossimGpt origin((ul.latd()+lr.latd())*.5, (ul.lond()+lr.lond())*.5, 0.0); double deltaLatPerPixel = latInterval; double deltaLonPerPixel = lonInterval; ossimDpt tie; tie.lat = ul.latd() - deltaLatPerPixel/2.0; tie.lon = ul.lond() + deltaLonPerPixel/2.0; kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, tie.toString(), true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, deltaLatPerPixel, true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, deltaLonPerPixel, true); kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, origin.latd(), true); kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, origin.lond(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LAT_KW, ul.latd()-(deltaLatPerPixel/2.0), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LON_KW, ul.lond()+(deltaLonPerPixel/2.0), true); kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimEquDistCylProjection", true); // Capture this for next time. theGeometry = new ossimImageGeometry; theGeometry->loadState(kwl, prefix); // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); return theGeometry; } ossimScalarType ossimRpfCacheTileSource::getOutputScalarType() const { return OSSIM_UCHAR; } ossim_uint32 ossimRpfCacheTileSource::getTileWidth() const { return m_tileSize.x; } ossim_uint32 ossimRpfCacheTileSource::getTileHeight() const { return m_tileSize.y; } bool ossimRpfCacheTileSource::setCurrentEntry(ossim_uint32 entryIdx) { // Clear the geometry. theGeometry = 0; // Must clear or openOverview will use last entries. theOverviewFile.clear(); if(!setEntryToRender(entryIdx)) { return false; } completeOpen(); return true; } void ossimRpfCacheTileSource::getEntryList(std::vector& entryList)const { entryList.push_back(0); } bool ossimRpfCacheTileSource::setEntryToRender(ossim_uint32 /* index */) { if(isOpen()) { populateLut(); return true; } return false; } bool ossimRpfCacheTileSource::isValidRLevel(ossim_uint32 reduced_res_level) const { if (reduced_res_level == 0) { return true; } else if (theOverview.valid()) { return theOverview->isValidRLevel(reduced_res_level); } else { return false; } } vector ossimRpfCacheTileSource::getIntersectingEntries(const ossimIrect& rect) { vector result; // make sure we have the Toc entry to render if(!isOpen()) return result; ossimIrect imageRect = getImageRectangle(); if(rect.intersects(imageRect)) { ossimIrect clipRect = rect.clipToRect(imageRect); ossimIrect frameRect(clipRect.ul().x/CIBCADRG_FRAME_WIDTH, clipRect.ul().y/CIBCADRG_FRAME_HEIGHT, clipRect.lr().x/CIBCADRG_FRAME_WIDTH, clipRect.lr().y/CIBCADRG_FRAME_HEIGHT); for(ossim_int32 row = frameRect.ul().y; row <= frameRect.lr().y; ++row) { for(ossim_int32 col = frameRect.ul().x; col <= frameRect.lr().x; ++col) { ossimRpfFrameEntry tempEntry = m_frameEntryArray[row][col]; if(tempEntry.exists()) { result.push_back(ossimFrameEntryData(row, col, row*CIBCADRG_FRAME_HEIGHT, col*CIBCADRG_FRAME_WIDTH, tempEntry)); } } } } return result; } void ossimRpfCacheTileSource::fillTile( const ossimIrect& tileRect, const vector& framesInvolved, ossimImageData* tile) { ossim_uint32 idx = 0; for(idx = 0; idx < framesInvolved.size(); ++idx) { if(m_workFrame->parseFile(framesInvolved[idx].theFrameEntry.getFullPath()) == ossimErrorCodes::OSSIM_OK) { // we will fill a subtile. We pass in which frame it is and the position of the frame. // the actual pixel will be 1536*row and 1536 *col. if(m_productType == OSSIM_PRODUCT_TYPE_CIB) { fillSubTileCib(*m_workFrame, tileRect, framesInvolved[idx], tile); } else { fillSubTileCadrg(*m_workFrame, tileRect, framesInvolved[idx], tile); } } } } void ossimRpfCacheTileSource::fillSubTileCadrg( const ossimRpfFrame& aFrame, const ossimIrect& tileRect, const ossimFrameEntryData& frameEntryData, ossimImageData* tile) {; // first let's grab the absolute position of the frame rectangle in pixel space ossimIrect frameRect(frameEntryData.thePixelCol, frameEntryData.thePixelRow, frameEntryData.thePixelCol + CIBCADRG_FRAME_WIDTH - 1, frameEntryData.thePixelRow + CIBCADRG_FRAME_HEIGHT - 1); // now clip it to the tile ossimIrect clipRect = tileRect.clipToRect(frameRect); const ossimRpfCompressionSection* compressionSection = aFrame.getCompressionSection(); if(!compressionSection) { return; } const vector& colorTable = aFrame.getColorGrayscaleTable(); // ESH 03/2009 -- Partial fix for ticket #646. // Crash fix on reading RPFs: Make sure the colorTable vector // has entries before trying to make use of them. int numTables = (int)colorTable.size(); if ( numTables <= 0 ) { return; } ossim_uint8 *tempRows[3]; tempRows[0] = m_uncompressedBuffer; tempRows[1] = (m_uncompressedBuffer + 256*256); tempRows[2] = (tempRows[1] + 256*256); // find the shift to 0,0 ossimIpt tempDelta(clipRect.ul().x - frameEntryData.thePixelCol, clipRect.ul().y - frameEntryData.thePixelRow); // In order to compute the subframe we will need the corner offsets of // the upper left of the frame and the upper left of the clip rect. The // clip rect should be completely within the frame. This just translates the value // to make the upper left of the frame be 0,0. // ossimIrect offsetRect(tempDelta.x, tempDelta.y, tempDelta.x + clipRect.width()-1, tempDelta.y + clipRect.height()-1); // each subframe is 64x64. We will actually use 256x256 since // we will be uncompressing them. Note CADRG is a 256x256 tile // compressed to 64x64x12 bit data // ossimIrect subFrameRect(offsetRect.ul().x/256, offsetRect.ul().y/256, (offsetRect.lr().x)/256, (offsetRect.lr().y)/256); ossim_uint32 readPtr = 0; ossim_int32 row = 0; ossim_int32 col = 0; ossim_uint32 i = 0; ossim_uint32 j = 0; ossim_int32 upperY = subFrameRect.lr().y; ossim_int32 upperX = subFrameRect.lr().x; ossim_int32 lowerY = subFrameRect.ul().y; ossim_int32 lowerX = subFrameRect.ul().x; for(row = lowerY; row <= upperY; ++row) { for(col = lowerX; col <= upperX; ++col) { readPtr = 0; if(aFrame.fillSubFrameBuffer(m_compressedBuffer, 0, row, col)) { for (i = 0; i < 256; i += 4) { for (j = 0; j < 256; j += 8) { ossim_uint16 firstByte = m_compressedBuffer[readPtr++] & 0xff; ossim_uint16 secondByte = m_compressedBuffer[readPtr++] & 0xff; ossim_uint16 thirdByte = m_compressedBuffer[readPtr++] & 0xff; //because dealing with half-bytes is hard, we //uncompress two 4x4 tiles at the same time. (a //4x4 tile compressed is 12 bits ) // this little code was grabbed from openmap software. /* Get first 12-bit value as index into VQ table */ // I think we need to swap ossim_uint16 val1 = (firstByte << 4) | (secondByte >> 4); /* Get second 12-bit value as index into VQ table*/ ossim_uint16 val2 = ((secondByte & 0x000F) << 8) | thirdByte; for (ossim_uint32 t = 0; t < 4; ++t) { for (ossim_uint32 e = 0; e < 4; ++e) { ossim_uint16 tableVal1 = compressionSection->getTable()[t].theData[val1*4 + e] & 0xff; ossim_uint16 tableVal2 = compressionSection->getTable()[t].theData[val2*4 + e] & 0xff; ossim_uint32 pixindex = ((i+t)*256) + (j + e); const ossim_uint8* color1 = colorTable[0].getStartOfData(tableVal1); const ossim_uint8* color2 = colorTable[0].getStartOfData(tableVal2); tempRows[0][pixindex] = color1[0]; tempRows[1][pixindex] = color1[1]; tempRows[2][pixindex] = color1[2]; tempRows[0][pixindex+4] = color2[0]; tempRows[1][pixindex+4] = color2[1]; tempRows[2][pixindex+4] = color2[2]; } //for e } //for t } /* for j */ } //for i } else { memset(m_uncompressedBuffer, 0, 256*256*3); } ossim_int32 tempCol = col*256; ossim_int32 tempRow = row*256; ossimIrect subRectToFill(frameRect.ul().x + tempCol, frameRect.ul().y + tempRow, frameRect.ul().x + tempCol + 255, frameRect.ul().y + tempRow + 255); tile->loadTile(m_uncompressedBuffer, subRectToFill, OSSIM_BSQ); } } } void ossimRpfCacheTileSource::fillSubTileCib( const ossimRpfFrame& aFrame, const ossimIrect& tileRect, const ossimFrameEntryData& frameEntryData, ossimImageData* tile) { // first let's grab the absolute position of the frame rectangle in pixel // space ossimIrect frameRect(frameEntryData.thePixelCol, frameEntryData.thePixelRow, frameEntryData.thePixelCol + CIBCADRG_FRAME_WIDTH - 1, frameEntryData.thePixelRow + CIBCADRG_FRAME_HEIGHT - 1); // now clip it to the tile ossimIrect clipRect = tileRect.clipToRect(frameRect); const ossimRpfCompressionSection* compressionSection = aFrame.getCompressionSection(); if(!compressionSection) { return; } const vector& colorTable = aFrame.getColorGrayscaleTable(); // ESH 03/2009 -- Partial fix for ticket #646. // Crash fix on reading RPFs: Make sure the colorTable vector // has entries before trying to make use of them. int numTables = (int)colorTable.size(); if ( numTables <= 0 ) { return; } // check to see if it does overlap. If it doesn't then the width and height // will be a single point { ossim_uint8 *tempRow; tempRow = m_uncompressedBuffer; // find the shift to 0,0 ossimIpt tempDelta(clipRect.ul().x - frameEntryData.thePixelCol, clipRect.ul().y - frameEntryData.thePixelRow); // In order to compute the subframe we will need the corner offsets of // the upper left of the frame and the upper left of the clip rect. The // clip rect should be completely within the frame. This just translates the value // to make the upper left of the frame be 0,0. // ossimIrect offsetRect(tempDelta.x, tempDelta.y, tempDelta.x + clipRect.width()-1, tempDelta.y + clipRect.height()-1); // each subframe is 64x64. We will actually use 256x256 since // we will be uncompressing them. Note CADRG is a 256x256 tile // compressed to 64x64x12 bit data // ossimIrect subFrameRect(offsetRect.ul().x/256, offsetRect.ul().y/256, (offsetRect.lr().x)/256, (offsetRect.lr().y)/256); ossim_int32 row = 0; ossim_int32 col = 0; ossim_uint32 i = 0; ossim_uint32 j = 0; ossim_uint32 readPtr = 0; for(row = subFrameRect.ul().y; row <= subFrameRect.lr().y; ++row) { for(col = subFrameRect.ul().x; col <= subFrameRect.lr().x; ++col) { readPtr = 0; if(aFrame.fillSubFrameBuffer(m_compressedBuffer, 0, row, col)) { for (i = 0; i < 256; i += 4) { for (j = 0; j < 256; j += 8) { ossim_uint16 firstByte = m_compressedBuffer[readPtr++] & 0xff; ossim_uint16 secondByte = m_compressedBuffer[readPtr++] & 0xff; ossim_uint16 thirdByte = m_compressedBuffer[readPtr++] & 0xff; //because dealing with half-bytes is hard, we //uncompress two 4x4 tiles at the same time. (a //4x4 tile compressed is 12 bits ) // this little code was grabbed from openmap software. /* Get first 12-bit value as index into VQ table */ // I think we need to swap ossim_uint16 val1 = (firstByte << 4) | (secondByte >> 4); /* Get second 12-bit value as index into VQ table*/ ossim_uint16 val2 = ((secondByte & 0x000F) << 8) | thirdByte; for (ossim_uint32 t = 0; t < 4; ++t) { for (ossim_uint32 e = 0; e < 4; ++e) { ossim_uint16 tableVal1 = compressionSection->getTable()[t].theData[val1*4 + e] & 0xff; ossim_uint16 tableVal2 = compressionSection->getTable()[t].theData[val2*4 + e] & 0xff; ossim_uint32 pixindex = ((i+t)*256) + (j + e); const ossim_uint8* color1 = colorTable[0].getStartOfData(tableVal1); const ossim_uint8* color2 = colorTable[0].getStartOfData(tableVal2); tempRow[pixindex] = color1[0]; tempRow[pixindex + 4] = color2[0]; } //for e } //for t } /* for j */ } //for i } else { memset(m_uncompressedBuffer, 0, 256*256); } ossim_int32 tCol = col*256; ossim_int32 tRow = row*256; ossimIrect subRectToFill(frameRect.ul().x + tCol, frameRect.ul().y + tRow, frameRect.ul().x + tCol + 255, frameRect.ul().y + tRow + 255); tile->loadTile(m_uncompressedBuffer, subRectToFill, OSSIM_BSQ); } } } } void ossimRpfCacheTileSource::allocateForProduct() { if(m_productType == OSSIM_PRODUCT_TYPE_UNKNOWN) { return; } if(m_uncompressedBuffer) { delete [] m_uncompressedBuffer; m_uncompressedBuffer = 0; } if(m_compressedBuffer) { delete [] m_compressedBuffer; m_compressedBuffer = 0; } // a CADRG and CIBis a 64*64*12 bit buffer and must divide by 8 to // convert to bytes m_compressedBuffer = new ossim_uint8[(64*64*12)/8]; if(m_productType == OSSIM_PRODUCT_TYPE_CIB) { m_uncompressedBuffer = new ossim_uint8[256*256]; } else { m_uncompressedBuffer = new ossim_uint8[256*256*3]; } m_tile = ossimImageDataFactory::instance()->create(this, this); m_tile->initialize(); } void ossimRpfCacheTileSource::deleteAll() { theOverview = 0; } bool ossimRpfCacheTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimImageHandler::saveState(kwl, prefix); return result; } bool ossimRpfCacheTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* MODULE = "ossimRpfCacheTileSource::loadState"; if(traceDebug()) { CLOG << "Entering..." << endl; } bool result = ossimImageHandler::loadState(kwl, prefix); if(!result) { if(traceDebug()) { CLOG << "Leaving..." << endl; } return false; } const char* lookup = 0; lookup = kwl.find(ossimString(prefix), "entry"); ossim_int32 entry = ossimString(lookup).toInt32(); // if an entry is specified then // call the open with an entry number if(lookup) { if(traceDebug()) { CLOG << "Leaving..." << endl; } result = ossimImageHandler::open(theImageFile); setCurrentEntry(entry); return result; } result = ossimImageHandler::open(theImageFile); return result; } ossim_uint32 ossimRpfCacheTileSource::getImageTileWidth() const { return 256; } ossim_uint32 ossimRpfCacheTileSource::getImageTileHeight() const { return 256; } bool ossimRpfCacheTileSource::isCib() const { return (m_productType==OSSIM_PRODUCT_TYPE_CIB); } bool ossimRpfCacheTileSource::isCadrg() const { return (m_productType==OSSIM_PRODUCT_TYPE_CADRG); } ossimRefPtr ossimRpfCacheTileSource::getProperty(const ossimString& name)const { if(name == "file_type") { if(m_productType == OSSIM_PRODUCT_TYPE_CIB) { return new ossimStringProperty("file_type", "CIB"); } else if(m_productType == OSSIM_PRODUCT_TYPE_CADRG) { return new ossimStringProperty("file_type", "CADRG"); } return 0; } return ossimImageHandler::getProperty(name); } void ossimRpfCacheTileSource::populateLut() { theLut = 0; if(m_fileNames.size() > 0) { // bool found = false; ossimRpfFrameEntry tempEntry; ossimRpfFrame aFrame; ossimFilename fileName = m_fileNames[0].split("|")[0]; // if (fileName.exists()) // { // found = true; // } if(aFrame.parseFile(fileName) == ossimErrorCodes::OSSIM_OK) { const vector& colorTable = aFrame.getColorGrayscaleTable(); // ESH 03/2009 -- Partial fix for ticket #646. // Crash fix on reading RPFs: Make sure the colorTable vector // has entries before trying to make use of them. int numTables = (int)colorTable.size(); ossim_uint32 numElements = (numTables > 0) ? colorTable[0].getNumberOfElements() : 0; if(numElements > 0) { if((m_productType == OSSIM_PRODUCT_TYPE_CIB)|| (m_productType == OSSIM_PRODUCT_TYPE_CADRG)) { theLut = new ossimNBandLutDataObject(numElements, 3, OSSIM_UINT8); } else { theLut = 0; return; } ossim_uint32 idx = 0; for(idx = 0; idx < numElements;++idx) { const ossim_uint8* startOfData = colorTable[0].getStartOfData(idx); switch(m_productType) { case OSSIM_PRODUCT_TYPE_CIB: { (*theLut)[idx][0] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[0]); (*theLut)[idx][1] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[0]); (*theLut)[idx][2] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[0]); break; } case OSSIM_PRODUCT_TYPE_CADRG: { (*theLut)[idx][0] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[0]); (*theLut)[idx][1] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[1]); (*theLut)[idx][2] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(startOfData[2]); break; } default: { break; } } } } } } } void ossimRpfCacheTileSource::establishDecimationFactors() { theDecimationFactors.clear(); // Just needed to set the first R level here, the base class can do the rest: ossimImageHandler::establishDecimationFactors(); } ossim-Miami-2.9.1/src/imaging/ossimS16ImageData.cpp000066400000000000000000000415561352751253100220150ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Class definition of ossimS16ImageData. Specialized image data object for // signed short data. // //************************************************************************* // $Id: ossimS16ImageData.cpp 16052 2009-12-08 22:20:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimS16ImageData, "ossimS16ImageData", ossimImageData) const ossimNormalizedS16RemapTable ossimS16ImageData::m_remapTable; ossimS16ImageData::ossimS16ImageData() : ossimImageData() { m_scalarType = OSSIM_SINT16; } ossimS16ImageData::ossimS16ImageData(ossimSource* source, ossim_uint32 bands) : ossimImageData(source, OSSIM_SINT16, bands) { } ossimS16ImageData::ossimS16ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height) : ossimImageData(source, OSSIM_SINT16, bands, width, height) { } ossimS16ImageData::ossimS16ImageData(const ossimS16ImageData &rhs) : ossimImageData(rhs) { } ossimS16ImageData::~ossimS16ImageData() { } ossimObject* ossimS16ImageData::dup()const { return new ossimS16ImageData(*this); } ossimDataObjectStatus ossimS16ImageData::validate() const { if (getBuf() == NULL) { setDataObjectStatus(OSSIM_NULL); return OSSIM_NULL; } ossim_uint32 count = 0; const ossim_uint32 SIZE = getSize(); const ossim_uint32 BOUNDS = getSizePerBand(); const ossim_uint32 NUMBER_OF_BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < NUMBER_OF_BANDS; ++band) { ossim_sint16 np = (ossim_sint16)m_nullPixelValue[band]; const ossim_sint16* p = getSshortBuf(band); for (ossim_uint32 i=0; i(m_remapTable.normFromPix(sourceBuf[offset])); } } void ossimS16ImageData::setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float inputValue) { if( (getDataObjectStatus() != OSSIM_NULL) && isValidBand(bandNumber) ) { ossim_sint16* sourceBuf = getSshortBuf(bandNumber); sourceBuf[offset] = static_cast(m_remapTable.pixFromNorm(inputValue)); } } void ossimS16ImageData::convertToNormalizedFloat(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_sint16* sourceBuf = getSshortBuf(bandCount); float* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. normFromPix(sourceBuf[counter])); } } } } void ossimS16ImageData::convertToNormalizedDouble(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_sint16* sourceBuf = getSshortBuf(bandCount); double* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = m_remapTable.normFromPix(sourceBuf[counter]); } } } } void ossimS16ImageData::unnormalizeInput(ossimImageData* normalizedInput) { if((normalizedInput->getScalarType() != OSSIM_NORMALIZED_FLOAT) && (normalizedInput->getScalarType() != OSSIM_NORMALIZED_DOUBLE) ) { //ERROR return; } ossim_uint32 counter = 0; ossim_uint32 bandCount = 0; ossim_uint32 size = getSizePerBand(); ossimScalarType scalarType = normalizedInput->getScalarType(); if(size > 0) { if(scalarType == OSSIM_NORMALIZED_FLOAT) { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { float* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_sint16* resultBuf = getSshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } else // Double { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { double* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_sint16* resultBuf = getSshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } } } double ossimS16ImageData::computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber) { double result = -1; // invalid MSE ossim_uint32 index = 0; double delta = 0; ossim_uint32 validPixelCount=0; ossim_sint16* buffer = getSshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getWidth()*getHeight(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { delta = *buffer - meanValue; result += (delta*delta); ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } double ossimS16ImageData::computeAverageBandValue(ossim_uint32 bandNumber) { double result = 0.0; ossim_uint32 index = 0; ossim_uint32 validPixelCount=0; ossim_sint16* buffer = getSshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getSizePerBand(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { result += *buffer; ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } void ossimS16ImageData::setValue(ossim_int32 x, ossim_int32 y, double color) { if(getBuf() != NULL && isWithin(x, y)) { //*** // Compute the offset into the buffer for (x,y). This should always // come out positive. //*** ossim_uint32 ux = static_cast(x - m_origin.x); ossim_uint32 uy = static_cast(y - m_origin.y); ossim_uint32 offset = uy * m_spatialExtents[0] + ux; for(ossim_uint32 band = 0; band < m_numberOfDataComponents; band++) { ossim_sint16* buf = getSshortBuf(band)+offset; *buf = (ossim_sint16)color; } } } void ossimS16ImageData::fill(ossim_uint32 band, double value) { void* s = getBuf(band); if (s == NULL) return; // nothing to do... ossim_uint32 size_in_pixels = getSizePerBand(); ossim_sint16* p = getSshortBuf(band); for (ossim_uint32 i=0; i(m_nullPixelValue[band]); } } void ossimS16ImageData::copyTileToNormalizedBuffer(double* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimS16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } const ossim_uint32 SIZE = getSizePerBand(); if(SIZE > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { const ossim_sint16* s = getSshortBuf(band); // source double* d = buf + (band*SIZE); // destination for(ossim_uint32 index = 0; index < SIZE; ++index) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimS16ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimS16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; const ossim_uint32 SIZE = getSizePerBand(); if(SIZE) { const ossim_float64 RANGE = (getMaxPix(band)-getMinPix(band)+1); const ossim_sint16* s = getSshortBuf(band); // source double* d = buf; // destination for(ossim_uint32 index = 0; index < SIZE; ++index) { ossim_float64 p = s[index]; if (p == m_nullPixelValue[band]) { d[index] = 0.0; } else if (p >= m_maxPixelValue[band]) { d[index] = 1.0; } else { //--- // Normalize... // Note that this will shift any negatives to positive prior // to dividing. //--- d[index] = ((p-m_minPixelValue[band]+1) / RANGE); } } } } void ossimS16ImageData::copyNormalizedBufferToTile(double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimS16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { double* s = buf + (band*size); // source ossim_sint16* d = getSshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimS16ImageData::copyNormalizedBufferToTile(ossim_uint32 band, double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimS11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { double* s = buf; // source ossim_sint16* d = getSshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } void ossimS16ImageData::copyTileToNormalizedBuffer(float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimS16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { const ossim_sint16* s = getSshortBuf(band); // source float* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimS16ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimS16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_sint16* s = getSshortBuf(band); // source float* d = buf; // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimS16ImageData::copyNormalizedBufferToTile(float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimS16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { float* s = buf + (band*size); // source ossim_sint16* d = getSshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimS16ImageData::copyNormalizedBufferToTile(ossim_uint32 band, float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimS16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { float* s = buf; // source ossim_sint16* d = getSshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } ossim-Miami-2.9.1/src/imaging/ossimSFIMFusion.cpp000066400000000000000000000334531352751253100216260ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // LICENSE: See top level LICENSE.txt // // Author: Garrett Potts // //******************************************************************* // $Id: ossimSFIMFusion.cpp 22755 2014-04-30 19:50:30Z dburken $ #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF2(ossimSFIMFusion, "ossimSFIMFusion", ossimFusionCombiner, ossimAdjustableParameterInterface); static const ossim_uint32 HIGH_PASS_GAIN_OFFSET = 0; static const ossim_uint32 LOW_PASS_WIDTH_OFFSET = 1; static const ossim_uint32 NUMBER_OF_ADJUSTABLE_PARAMETERS = 2; ossimSFIMFusion::ossimSFIMFusion() :theLowPassKernelWidth(1.5), theHighPassKernelWidth(3) { theAutoAdjustScales = true; theLowPassFilter = new ossimImageGaussianFilter; theHighPassFilter = new ossimConvolutionSource; setFilters(); initAdjustableParameters(); } ossimSFIMFusion::~ossimSFIMFusion() { } ossimRefPtr ossimSFIMFusion::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { if(!theInputConnection) { return ossimRefPtr(); } if (!theIntensityConnection) { return theInputConnection->getTile(rect, resLevel); } if(!theNormLowPassTile.valid()) { theNormLowPassTile = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT, 1, rect.width(), rect.height()); theNormHighPassTile = new ossimImageData(this, OSSIM_NORMALIZED_FLOAT, 1, rect.width(), rect.height()); theNormLowPassTile->initialize(); theNormHighPassTile->initialize(); } theNormLowPassTile->setImageRectangle(rect); theNormHighPassTile->setImageRectangle(rect); theNormLowPassTile->makeBlank(); theNormHighPassTile->makeBlank(); if(!theLowPassFilter->getInput() && getInput()) { initialize(); } ossimRefPtr lowTile = theLowPassFilter->getTile(rect, resLevel); ossimRefPtr highTile = theHighPassFilter->getTile(rect, resLevel); // ossimRefPtr highTile = getNormIntensity(rect, resLevel); // if we don't have valid low and high pass then return the input color tile // in its original format // if(!lowTile.valid()||!highTile.valid()) { // return theInputConnection->getTile(rect, resLevel); return 0; } if((lowTile->getDataObjectStatus() == OSSIM_EMPTY)|| (!lowTile->getBuf()) || (highTile->getDataObjectStatus() == OSSIM_EMPTY)|| (!highTile->getBuf())) { // return theInputConnection->getTile(rect, resLevel); return 0; } ossimRefPtr normColorData = getNormTile(rect, resLevel); if(!normColorData.valid()) { return 0; // return theTile; } // Must set the rectangle before querrying height and width. theTile->setImageRectangle(rect); // Do a make blank in case the whole tile is not stuffed. theTile->makeBlank(); if((normColorData->getDataObjectStatus() == OSSIM_EMPTY)|| !normColorData->getBuf()) { return theTile; } ossim_uint32 y = 0; ossim_uint32 x = 0; ossim_uint32 w = theTile->getWidth(); ossim_uint32 h = theTile->getHeight(); ossimRefPtr normColorOutputData = (ossimImageData*)normColorData->dup(); normColorOutputData->setImageRectangle(rect); normColorOutputData->loadTile(normColorData.get()); // ossim_float64 slopeResult = 0.0; ossim_uint32 idx = 0; std::vector bands(normColorData->getNumberOfBands()); // Use copyTileBand... in case n-band data passed in for pan input. lowTile->copyTileBandToNormalizedBuffer(0, (ossim_float32*)theNormLowPassTile->getBuf()); highTile->copyTileBandToNormalizedBuffer(0, (ossim_float32*)theNormHighPassTile->getBuf()); theNormLowPassTile->validate(); theNormHighPassTile->validate(); ossimRefPtr lowPan = (ossimImageData*)theNormLowPassTile->dup(); lowPan->setImageRectangle(rect); lowPan->loadTile(theNormLowPassTile.get()); ossimRefPtr highPan = (ossimImageData*)theNormHighPassTile->dup(); highPan->setImageRectangle(rect); highPan->loadTile(theNormHighPassTile.get()); ossim_float32* panHigh = (ossim_float32*)highPan->getBuf(); ossim_float32* panLow = (ossim_float32*)lowPan->getBuf(); for(idx = 0; idx < bands.size(); ++idx) { bands[idx] = (ossim_float32*)normColorOutputData->getBuf(idx); } // double delta = 0.0; ossim_uint32 bandsSize = (ossim_uint32)bands.size(); double normMinPix = 0.0; for(y = 0; y < h; ++y) { for(x = 0; x < w; ++x) { for(idx = 0; idx < bandsSize; ++idx) { if((*bands[idx] != 0.0)&& (*panLow > FLT_EPSILON) ) // if band is not null and not divide by 0 { normMinPix = (ossim_float32)normColorOutputData->getMinPix(idx); *bands[idx] = ((*bands[idx])*(*panHigh))/ (*panLow); if(*bands[idx] > 1.0) *bands[idx] = 1.0; if(*bands[idx] < normMinPix) *bands[idx] = normMinPix; } // let's comment out the nulling and we will instead just pass the color on // // else // { // *bands[idx] = 0.0; // } ++bands[idx]; } ++panHigh; ++panLow; } } theTile->copyNormalizedBufferToTile((ossim_float32*)normColorOutputData->getBuf()); theTile->validate(); return theTile; } void ossimSFIMFusion::initialize() { ossimFusionCombiner::initialize(); if(!theIntensityConnection) { theLowPassFilter->disconnectAllInputs(); theHighPassFilter->disconnectAllInputs(); } else { theLowPassFilter->connectMyInputTo(0, PTR_CAST(ossimConnectableObject, theIntensityConnection->getObject())); theHighPassFilter->connectMyInputTo(0, PTR_CAST(ossimConnectableObject, theIntensityConnection->getObject())); adjustableParametersChanged(); setFilters(); theLowPassFilter->initialize(); theHighPassFilter->initialize(); if(theAutoAdjustScales) { if(theInputConnection && theIntensityConnection) { ossimTypeNameVisitor visitor("ossimImageRenderer", true); theInputConnection->accept(visitor); ossimRefPtr inputColor = visitor.getObjectAs(); visitor.reset(); theIntensityConnection->accept(visitor); ossimRefPtr inputPan = visitor.getObjectAs(); if(inputColor.valid()&&inputPan.valid()) { ossimImageSource* inputColorSource = dynamic_cast (inputColor->getInput()); ossimImageSource* inputPanSource = dynamic_cast (inputPan->getInput()); if(inputColorSource&&inputPanSource) { ossimRefPtr colorGeom = inputColorSource->getImageGeometry(); ossimRefPtr intensityGeom = inputPanSource->getImageGeometry(); if(colorGeom.valid()&&intensityGeom.valid()) { ossimDpt gsdIntensity = intensityGeom->getMetersPerPixel(); ossimDpt gsdColor = colorGeom->getMetersPerPixel(); if(!gsdColor.hasNans()&&!gsdIntensity.hasNans()) { double scaleChange = gsdColor.length()/gsdIntensity.length(); if(scaleChange < 1.0) scaleChange = 1.0; setParameterOffset(LOW_PASS_WIDTH_OFFSET, scaleChange); } } } } } } } } void ossimSFIMFusion::setFilters() { theLowPassFilter->setGaussStd(theLowPassKernelWidth); theHighPassMatrix = NEWMAT::Matrix(theHighPassKernelWidth, theHighPassKernelWidth); theHighPassMatrix = 0; theHighPassMatrix[theHighPassKernelWidth>>1][theHighPassKernelWidth>>1] = 1; // adjust the gain for the high pass filter // NEWMAT::Matrix high = theHighPassMatrix; ossim_float64 kernelW2 = theHighPassKernelWidth*theHighPassKernelWidth; double gain = computeParameterOffset(HIGH_PASS_GAIN_OFFSET)*(kernelW2); double multiplier = gain/(kernelW2); high = -multiplier; ossim_int32 cx = theHighPassKernelWidth>>1; ossim_int32 cy = theHighPassKernelWidth>>1; if(gain > FLT_EPSILON) { high[cy][cx] = multiplier* ( (kernelW2-1)+kernelW2/gain); } else { high = 0.0; high[cy][cx] = 1.0; } theHighPassFilter->setConvolution(high); } void ossimSFIMFusion::initAdjustableParameters() { resizeAdjustableParameterArray(NUMBER_OF_ADJUSTABLE_PARAMETERS); setAdjustableParameter(HIGH_PASS_GAIN_OFFSET, -1.0); setParameterDescription(HIGH_PASS_GAIN_OFFSET, "High pass gain"); setParameterSigma(HIGH_PASS_GAIN_OFFSET, 1); setParameterCenter(HIGH_PASS_GAIN_OFFSET, 1.0); setAdjustableParameter(LOW_PASS_WIDTH_OFFSET, -1); setParameterDescription(LOW_PASS_WIDTH_OFFSET, "Low pass kernel width"); setParameterSigma(LOW_PASS_WIDTH_OFFSET, 40); setParameterCenter(LOW_PASS_WIDTH_OFFSET, 40.5); setParameterOffset(LOW_PASS_WIDTH_OFFSET, 1.5); } void ossimSFIMFusion::adjustableParametersChanged() { // std::cout << "Parameter offset = " << computeParameterOffset(2) << std::endl; theLowPassKernelWidth = (ossim_uint32)(ossim::round(computeParameterOffset(LOW_PASS_WIDTH_OFFSET))); } void ossimSFIMFusion::setProperty(ossimRefPtr property) { ossimString name = property->getName(); if(name=="low_pass_kernel_width") { setParameterOffset(LOW_PASS_WIDTH_OFFSET, property->valueToString().toDouble(), true); } else if(name=="high_pass_gain") { setParameterOffset(HIGH_PASS_GAIN_OFFSET, property->valueToString().toDouble(), true); } else if(name=="auto_adjust_scales") { theAutoAdjustScales = property->valueToString().toBool(); } else { ossimFusionCombiner::setProperty(property); } } ossimRefPtr ossimSFIMFusion::getProperty(const ossimString& name)const { if(name == "low_pass_kernel_width") { ossimNumericProperty* prop = new ossimNumericProperty(name, ossimString::toString(computeParameterOffset(LOW_PASS_WIDTH_OFFSET)), getParameterCenter(LOW_PASS_WIDTH_OFFSET)-getParameterSigma(LOW_PASS_WIDTH_OFFSET), getParameterCenter(LOW_PASS_WIDTH_OFFSET)+getParameterSigma(LOW_PASS_WIDTH_OFFSET)); prop->setCacheRefreshBit(); return prop; } else if(name == "high_pass_gain") { ossimNumericProperty* prop = new ossimNumericProperty(name, ossimString::toString(computeParameterOffset(HIGH_PASS_GAIN_OFFSET)), getParameterCenter(HIGH_PASS_GAIN_OFFSET)-getParameterSigma(HIGH_PASS_GAIN_OFFSET), getParameterCenter(HIGH_PASS_GAIN_OFFSET)+getParameterSigma(HIGH_PASS_GAIN_OFFSET)); prop->setCacheRefreshBit(); return prop; } else if(name=="auto_adjust_scales") { ossimBooleanProperty* prop = new ossimBooleanProperty(name,theAutoAdjustScales); prop->setCacheRefreshBit(); return prop; } return ossimFusionCombiner::getProperty(name); } void ossimSFIMFusion::getPropertyNames(std::vector& propertyNames)const { ossimFusionCombiner::getPropertyNames(propertyNames); propertyNames.push_back("low_pass_kernel_width"); propertyNames.push_back("high_pass_gain"); propertyNames.push_back("auto_adjust_scales"); } bool ossimSFIMFusion::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimFusionCombiner::saveState(kwl, prefix); saveAdjustments(kwl, prefix); kwl.add(prefix, "auto_adjust_scales", theAutoAdjustScales, true); return true; } bool ossimSFIMFusion::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimFusionCombiner::loadState(kwl, prefix); loadAdjustments(kwl, prefix); adjustableParametersChanged(); ossimString autoAdjustScales = kwl.find(prefix, "auto_adjust_scales"); if(!autoAdjustScales.empty()) { theAutoAdjustScales = autoAdjustScales.toBool(); } return true; } ossim-Miami-2.9.1/src/imaging/ossimSICDToDetectedImage.cpp000066400000000000000000000114561352751253100233350ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2010 Radiant Blue Technologies Inc. // // License: See LICENSE.txt file in the top level directory. // // Author: William Watkins // // Description: A brief description of the contents of the file. // //************************************************************************* #include #include #include #include #include #include RTTI_DEF1(ossimSICDToDetectedImage, "ossimSICDToDetectedImage", ossimImageSourceFilter) ossimSICDToDetectedImage::ossimSICDToDetectedImage() :ossimImageSourceFilter() { } ossimSICDToDetectedImage::~ossimSICDToDetectedImage() { } ossimRefPtr ossimSICDToDetectedImage::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr tile = NULL; if(theInputConnection) { tile = theInputConnection->getTile(tileRect, resLevel); if(!tile.valid()) { return tile; } if(!isSourceEnabled() || (tile->getDataObjectStatus()==OSSIM_NULL)|| (tile->getDataObjectStatus()==OSSIM_EMPTY)) { return tile; } if(!theTile.valid()) { allocate(); } if(!theTile.valid()) { return tile; } theTile->setImageRectangle(tileRect); if (tile->getNumberOfBands() == 2) { switch(tile->getScalarType()) { case OSSIM_UINT8: // SICD 8 Bit data is Amplitude and Phase { processAmplitudeAngleTile((ossim_uint8)0, tile.get()); break; } case OSSIM_SINT8: { processAmplitudeAngleTile((ossim_sint8)0, tile.get()); break; } case OSSIM_UINT16: // SICD 16 Bit data is complex { processComplexTile((ossim_uint16)0, tile.get()); break; } case OSSIM_SINT16: { processComplexTile((ossim_sint16)0, tile.get()); break; } case OSSIM_FLOAT32: { processComplexTile((ossim_float32)0, tile.get()); break; } default: { break; } } theTile->validate(); } return theTile; } return theTile; } template void ossimSICDToDetectedImage::processComplexTile(T /* dummy */, ossimImageData* tile) { T* bands[2]; T* result = (T*)theTile->getBuf(); bands[0] = (T*)tile->getBuf(0); bands[1] = (T*)tile->getBuf(1); ossim_uint32 offset = 0; ossim_uint32 maxIdx = tile->getWidth()*tile->getHeight(); for(offset = 0; offset < maxIdx; ++offset) { result[offset] = sqrt((ossim_float64)bands[0][offset]*(ossim_float64)bands[0][offset] + (ossim_float64)bands[1][offset]*(ossim_float64)bands[1][offset]); } } template void ossimSICDToDetectedImage::processAmplitudeAngleTile(T /* dummy */, ossimImageData* tile) { T* bands[2]; T* result = (T*)theTile->getBuf(); bands[0] = (T*)tile->getBuf(0); bands[1] = (T*)tile->getBuf(1); ossim_uint32 offset = 0; ossim_uint32 maxIdx = tile->getWidth()*tile->getHeight(); for(offset = 0; offset < maxIdx; ++offset) { result[offset] = bands[0][offset]; // The SICD spec says 8 bit data is Mag 8 bits and Phase 8 bits (Not complex) } } void ossimSICDToDetectedImage::initialize() { ossimImageSourceFilter::initialize(); theTile = 0; } void ossimSICDToDetectedImage::allocate() { if( isSourceEnabled() && theInputConnection ) { theTile = ossimImageDataFactory::instance()->create(this, this); if(theTile.valid()) { theTile->initialize(); } else { theTile = 0; } } } void ossimSICDToDetectedImage::setProperty(ossimRefPtr property) { if(!property) { return; } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimSICDToDetectedImage::getProperty(const ossimString& name)const { return ossimImageSourceFilter::getProperty(name); } void ossimSICDToDetectedImage::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); } ossim-Miami-2.9.1/src/imaging/ossimScalarRemapper.cpp000066400000000000000000000375411352751253100226070ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2001 ImageLinks Inc. // // License: MIT // // Author: David Burken // // Description: // // Contains class definition for ossimScalarRemapper. // This class is used to remap image data from one scalar type to another. // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimScalarRemapper, "ossimScalarRemapper", ossimImageSourceFilter) static const ossimTrace traceDebug("ossimScalarRemapper:debug"); ossimScalarRemapper::ossimScalarRemapper() : ossimImageSourceFilter(), theNormBuf(NULL), theTile(NULL), theOutputScalarType(OSSIM_UINT8), theByPassFlag(false), thePreserveMagnitudeFlag(false) { } ossimScalarRemapper::ossimScalarRemapper(ossimImageSource* inputSource, ossimScalarType outputScalarType) : ossimImageSourceFilter(inputSource), theNormBuf(NULL), theTile(NULL), theOutputScalarType(outputScalarType), theByPassFlag(false), thePreserveMagnitudeFlag(false) { if(inputSource) { if (inputSource->getOutputScalarType() == outputScalarType) { // Disable this filter simply return the inputSource's data. theByPassFlag = true; // Nothing else to do. } else { theByPassFlag = false; } } else { theByPassFlag = true; } } ossimScalarRemapper::~ossimScalarRemapper() { destroy(); } void ossimScalarRemapper::destroy() { if (theNormBuf) { delete [] theNormBuf; theNormBuf = NULL; } theTile = NULL; } ossimRefPtr ossimScalarRemapper::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(traceDebug()) { std::cout << "ossimScalarRemapper::getTile START ... " << tileRect << " RES: " << resLevel << std::endl; } if(!theInputConnection) { return ossimRefPtr(); } // Fetch tile from pointer from the input source. ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); // Check for remap bypass: if ( !isSourceEnabled()||theByPassFlag ) { return inputTile; } // Check for first time through. if ( !theTile.valid() ) { allocate(); if ( !theTile.valid() ) { // This can happen if input/output scalars are the same. return inputTile; } } // Capture the size prior to a possible resize. ossim_uint32 oldSize = theTile->getSize(); // Set the origin,bands of the output tile. theTile->setImageRectangle(tileRect); ossim_uint32 newSize = theTile->getSize(); // Check for size change before possible return. if(newSize != oldSize) { if(theNormBuf) { //--- // Delete the current buffer since it is the wrong size. // // NOTE: // We won't reallocate it yet since we could return without using it. // It will be checked prior to using later. //--- delete [] theNormBuf; theNormBuf = NULL; } } if ( !inputTile.valid() || (inputTile->getDataObjectStatus() == OSSIM_NULL) || (inputTile->getDataObjectStatus() == OSSIM_EMPTY) ) { //--- // Since the filter is enabled, return theTile which is of the // correct scalar type. //--- theTile->makeBlank(); return theTile; } if (!theNormBuf) // First time through or size changed and was deleted... { theNormBuf = new double[newSize]; memset(theNormBuf, '\0', newSize); } if (inputTile->getScalarType() == theOutputScalarType) { // Scalar types already the same. Nothing to do... return inputTile; } if(thePreserveMagnitudeFlag) { switch(inputTile->getScalarType()) { case OSSIM_SINT16: { inputTile->copyTileToFloatBuffer(ossim_sint16(0), theTile->getFloatBuf()); break; } case OSSIM_UINT16: { inputTile->copyTileToFloatBuffer(ossim_uint16(0), theTile->getFloatBuf()); break; } case OSSIM_SINT32: { inputTile->copyTileToFloatBuffer(ossim_sint32(0), theTile->getFloatBuf()); break; } case OSSIM_UINT32: { inputTile->copyTileToFloatBuffer(ossim_uint32(0), theTile->getFloatBuf()); break; } default: { break; } } } else { switch(inputTile->getScalarType()) { case OSSIM_NORMALIZED_DOUBLE: { // Un-normalize and copy the buffer to the destination tile. theTile->copyNormalizedBufferToTile( static_cast( inputTile->getBuf() ) ); break; } case OSSIM_NORMALIZED_FLOAT: { // Un-normalize and copy the buffer to the destination tile. theTile->copyNormalizedBufferToTile( static_cast( inputTile->getBuf() ) ); break; } default: { //--- // NOTE: stretchMinMax commented out as it was incorrectly not resetting // the tile's min/max data members; hence, messing up the downstream copy // to normalized buffer. (drb 02 Feb. 2013) // Special case. Stretch assuming caller want to view this data. //--- // inputTile->stretchMinMax(); // Normalize and copy the source tile to a buffer. inputTile->copyTileToNormalizedBuffer(theNormBuf); // Un-normalize and copy the buffer to the destination tile. theTile->copyNormalizedBufferToTile(theNormBuf); break; } } } theTile->validate(); if(traceDebug()) { std::cout << "ossimScalarRemapper::getTile END ... " << tileRect << " RES: " << resLevel << std::endl; } return theTile; } ossimScalarType ossimScalarRemapper::getOutputScalarType() const { if(isSourceEnabled()&&!theByPassFlag) { return theOutputScalarType; } return ossimImageSourceFilter::getOutputScalarType(); } void ossimScalarRemapper::setOutputScalarType(ossimScalarType scalarType) { if (scalarType == OSSIM_SCALAR_UNKNOWN) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimScalarRemapper::setOutputScalarType WARN:\n" << "OSSIM_SCALAR_UNKNOWN passed to method. No action taken..." << std::endl; } return; } if (theInputConnection) { if ( scalarType == theInputConnection->getOutputScalarType() ) { // Input same as output, nothing for us to do... theByPassFlag = true; } else // Types not equal... { theByPassFlag = false; destroy(); } } else // No input source, disable. { theByPassFlag = true; } theOutputScalarType = scalarType; } void ossimScalarRemapper::setOutputScalarType(ossimString scalarType) { int scalar = ossimScalarTypeLut::instance()->getEntryNumber(scalarType.c_str()); if (scalar != ossimLookUpTable::NOT_FOUND) { setOutputScalarType(static_cast(scalar)); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimScalarRemapper ERROR:" << "\nUnknown scalar type: " << scalarType.c_str() << std::endl; } } } void ossimScalarRemapper::initialize() { //--- // Call the base class initialize. // Note: This will reset "theInputConnection" if it changed... //--- ossimImageSourceFilter::initialize(); if (theInputConnection) { // Set the bypass flag accordingly... if ( theInputConnection->getOutputScalarType() == theOutputScalarType ) { theByPassFlag = true; } else { theByPassFlag = false; } if (theTile.valid()) { //--- // Check for: // - bypass // - disabled(!enabled) // - scalar change // - band count change //--- if ( theByPassFlag || !theEnableFlag || ( theInputConnection->getOutputScalarType() != theOutputScalarType ) || ( theInputConnection->getNumberOfOutputBands() != theTile->getNumberOfBands() ) ) { destroy(); // Reallocated first unbypassed getTile. } } } } void ossimScalarRemapper::allocate() { destroy(); if(!theInputConnection) // Nothing to do here. { setInitializedFlag(false); theByPassFlag = true; return; } if (theOutputScalarType == OSSIM_SCALAR_UNKNOWN) { // default to OSSIM_UINT8 theOutputScalarType = OSSIM_UINT8; } if(theInputConnection && (getOutputScalarType() != theInputConnection->getOutputScalarType())&& (theInputConnection->getOutputScalarType() != OSSIM_SCALAR_UNKNOWN)&& (getOutputScalarType() != OSSIM_SCALAR_UNKNOWN)) { theByPassFlag = false; theTile = ossimImageDataFactory::instance()->create(this, this); // Initialize the tile. theTile->initialize(); // Set the base class flags to be initialized and enabled. setInitializedFlag(true); } // End of "if(theInputConnection->isConnected()..." else { // Set to not initialized and disabled. setInitializedFlag(false); theByPassFlag = true; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimScalarRemapper::allocate() DEBUG" << "\ninput scalar: " << theInputConnection->getOutputScalarType() << "\noutput scalar: " << getOutputScalarType() << "\nenabled: " << (isSourceEnabled()?"true":"false") << std::endl; } } void ossimScalarRemapper::setProperty(ossimRefPtr property) { if(!property) return; if(property->getName() == "Output scalar type") { theOutputScalarType = ossimScalarTypeLut::instance()-> getScalarTypeFromString(property->valueToString()); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimScalarRemapper::getProperty(const ossimString& name)const { if(name == "Output scalar type") { std::vector scalarNames; ossim_int32 tableSize = (ossim_int32)ossimScalarTypeLut::instance()-> getTableSize(); ossim_int32 idx; for(idx = 0; idx < tableSize; ++idx) { scalarNames.push_back(ossimScalarTypeLut::instance()-> getEntryString(idx)); } ossimStringProperty* stringProp = new ossimStringProperty("Output scalar type", ossimScalarTypeLut::instance()->getEntryString((ossim_int32)theOutputScalarType), false, scalarNames); stringProp->clearChangeType(); stringProp->setReadOnlyFlag(false); stringProp->setCacheRefreshBit(); return stringProp; } return ossimImageSourceFilter::getProperty(name); } void ossimScalarRemapper::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("Output scalar type"); } bool ossimScalarRemapper::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimImageSourceFilter::saveState(kwl, prefix); kwl.add(prefix, ossimKeywordNames::SCALAR_TYPE_KW, ossimScalarTypeLut::instance()->getEntryString(theOutputScalarType), true); kwl.add(prefix, "elevation", ossimString::toString(thePreserveMagnitudeFlag).c_str()); return true; } bool ossimScalarRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimImageSourceFilter::loadState(kwl, prefix); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimScalarRemapper::loadState\n" << " ERROR detected in keyword list! State not loaded." << std::endl; } return false; } int scalar = ossimScalarTypeLut::instance()->getEntryNumber(kwl, prefix); if (scalar != ossimLookUpTable::NOT_FOUND) { setOutputScalarType(static_cast(scalar)); } const char* lookup = kwl.find(prefix, "elevation"); if(lookup) { thePreserveMagnitudeFlag = ossimString(lookup).toBool(); } return true; } ossimString ossimScalarRemapper::getOutputScalarTypeString() const { return ossimScalarTypeLut::instance()->getEntryString(theOutputScalarType); } void ossimScalarRemapper::propertyEvent(ossimPropertyEvent& event) { // if my properties have changed then just initialize // if(event.getObject() == this) { initialize(); } else // if an input property has changed just check to see if the number { // of bands has changed if(!theTile) { initialize(); } else { int b = theInputConnection->getNumberOfOutputBands(); if((int)theTile->getNumberOfBands() != b) { initialize(); } } } } void ossimScalarRemapper::refreshEvent(ossimRefreshEvent& event) { // if my properties have changed then just initialize if(event.getObject() == this) { initialize(); } else // if an input property has changed just check to see if the number { // of bands has changed if(!theTile) { initialize(); } else { int b = theInputConnection->getNumberOfOutputBands(); if((int)theTile->getNumberOfBands() != b) { initialize(); } } } } double ossimScalarRemapper::getNullPixelValue(ossim_uint32 band) const { if(!isSourceEnabled()||theByPassFlag) { if(theInputConnection) { return theInputConnection->getNullPixelValue(band); } } else if(theTile.valid()) { if (band < theTile->getNumberOfBands()) { return theTile->getNullPix(band); } } return ossim::defaultNull(theOutputScalarType); } double ossimScalarRemapper::getMinPixelValue(ossim_uint32 band) const { if(!isSourceEnabled()||theByPassFlag) { if(theInputConnection) { return theInputConnection->getMinPixelValue(band); } } else if(theTile.valid()) { if (band < theTile->getNumberOfBands()) { return theTile->getMinPix(band); } } return ossim::defaultMin(theOutputScalarType); } double ossimScalarRemapper::getMaxPixelValue(ossim_uint32 band) const { if(!isSourceEnabled()||theByPassFlag) { if(theInputConnection) { return theInputConnection->getMaxPixelValue(band); } } else if(theTile.valid()) { if (band < theTile->getNumberOfBands()) { return theTile->getMaxPix(band); } } return ossim::defaultMax(theOutputScalarType); } void ossimScalarRemapper::setPreserveMagnitude(bool value) { thePreserveMagnitudeFlag = value; } ossimString ossimScalarRemapper::getLongName()const { return ossimString("Scalar Remapper, filters between different scalar types."); } ossimString ossimScalarRemapper::getShortName()const { return ossimString("Scalar Remapper"); } ossim-Miami-2.9.1/src/imaging/ossimScaleFilter.cpp000066400000000000000000000671751352751253100221110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimScaleFilter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimScaleFilter, "ossimScaleFilter", ossimImageSourceFilter); //************************************************************************************************** ossimScaleFilter::ossimScaleFilter() :ossimImageSourceFilter(), m_BlankTile(NULL), m_Tile(NULL), m_MinifyFilter(NULL), m_MagnifyFilter(NULL), m_MinifyFilterType(ossimScaleFilter_NEAREST_NEIGHBOR), m_MagnifyFilterType(ossimScaleFilter_NEAREST_NEIGHBOR), m_ScaleFactor(1.0, 1.0), m_InverseScaleFactor(1.0, 1.0), m_TileSize(64, 64), m_BlurFactor(1.0) { m_InputRect.makeNan(); m_MinifyFilter = new ossimNearestNeighborFilter(); m_MagnifyFilter = new ossimNearestNeighborFilter(); } //************************************************************************************************** ossimScaleFilter::ossimScaleFilter(ossimImageSource* inputSource, const ossimDpt& scaleFactor) :ossimImageSourceFilter(inputSource), m_BlankTile(NULL), m_Tile(NULL), m_MinifyFilter(NULL), m_MagnifyFilter(NULL), m_MinifyFilterType(ossimScaleFilter_NEAREST_NEIGHBOR), m_MagnifyFilterType(ossimScaleFilter_NEAREST_NEIGHBOR), m_ScaleFactor(scaleFactor), m_TileSize(64, 64), m_BlurFactor(1.0) { m_InputRect.makeNan(); m_MinifyFilter = new ossimNearestNeighborFilter(); m_MagnifyFilter = new ossimNearestNeighborFilter(); } //************************************************************************************************** ossimScaleFilter::~ossimScaleFilter() { if(m_MinifyFilter) { delete m_MinifyFilter; m_MinifyFilter = NULL; } if(m_MagnifyFilter) { delete m_MagnifyFilter; m_MagnifyFilter = NULL; } } //************************************************************************************************** ossimRefPtr ossimScaleFilter::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if((!isSourceEnabled())|| (!theInputConnection)|| ((m_ScaleFactor.x == 1.0)&& (m_ScaleFactor.y == 1.0)&& (m_BlurFactor == 1.0))) { return ossimImageSourceFilter::getTile(tileRect, resLevel); } if(!m_Tile.valid()) { allocate(); } if(!m_Tile) { return ossimImageSourceFilter::getTile(tileRect, resLevel); } m_Tile->makeBlank(); ossimIrect imageRect = tileRect*m_InverseScaleFactor; m_Tile->setImageRectangle(tileRect); m_BlankTile->setImageRectangle(tileRect); double xSupport; double ySupport; getSupport(xSupport, ySupport); ossimIpt deltaPt; deltaPt.x = (ossim_int32)ceil(xSupport); deltaPt.y = (ossim_int32)ceil(ySupport); imageRect = ossimIrect(imageRect.ul().x - (deltaPt.x), imageRect.ul().y - (deltaPt.y), imageRect.lr().x + (deltaPt.x), imageRect.lr().y + (deltaPt.y)); runFilter(imageRect, tileRect); m_Tile->validate(); return m_Tile; } //************************************************************************************************** void ossimScaleFilter::runFilter(const ossimIrect& imageRect, const ossimIrect& viewRect) { switch(m_Tile->getScalarType()) { case OSSIM_UINT8: { runFilterTemplate((ossim_uint8)0, imageRect, viewRect); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { runFilterTemplate((ossim_uint16)0, imageRect, viewRect); break; } case OSSIM_SINT16: { runFilterTemplate((ossim_sint16)0, imageRect, viewRect); break; } case OSSIM_UINT32: { runFilterTemplate((ossim_uint32)0, imageRect, viewRect); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { runFilterTemplate((ossim_float64)0, imageRect, viewRect); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { runFilterTemplate((ossim_float32)0, imageRect, viewRect); break; } default: break; } } //************************************************************************************************** template void ossimScaleFilter::runFilterTemplate(T dummy, const ossimIrect& imageRect, const ossimIrect& viewRect) { ossimRefPtr inputData = theInputConnection->getTile(imageRect); if(!inputData.valid() || !inputData->getBuf() || (inputData->getDataObjectStatus() == OSSIM_EMPTY)) { return; } ossim_int32 h = imageRect.height(); ossimRefPtr tempData = ossimImageDataFactory::instance()->create(NULL, inputData->getScalarType(), inputData->getNumberOfBands(), viewRect.width(), h); tempData->setOrigin(ossimIpt(viewRect.ul().x, imageRect.ul().y)); tempData->initialize(); if((m_ScaleFactor.x != 1.0)|| (m_BlurFactor != 1.0)) { runHorizontalFilterTemplate(dummy, inputData, tempData); tempData->validate(); } else { tempData->loadTile(inputData.get()); } if((m_ScaleFactor.y != 1.0)|| (m_BlurFactor != 1.0)) { runVerticalFilterTemplate(dummy, tempData, m_Tile); } else { m_Tile->loadTile(tempData.get()); } m_Tile->validate(); } //************************************************************************************************** ossimIrect ossimScaleFilter::getBoundingRect(ossim_uint32 resLevel)const { ossimIrect result = ossimImageSourceFilter::getBoundingRect(resLevel); if(!result.hasNans()) { result *= m_ScaleFactor; } return result; } //************************************************************************************************** void ossimScaleFilter::setFilterType(ossimScaleFilterType filterType) { setFilterType(filterType, filterType); } //************************************************************************************************** void ossimScaleFilter::setFilterType(ossimScaleFilterType minifyFilterType, ossimScaleFilterType magnifyFilterType) { if(m_MinifyFilter) { delete m_MinifyFilter; m_MinifyFilter = NULL; } if(m_MagnifyFilter) { delete m_MagnifyFilter; m_MagnifyFilter = NULL; } m_MinifyFilterType = minifyFilterType; m_MagnifyFilterType = magnifyFilterType; m_MinifyFilter = createNewFilter(minifyFilterType, m_MinifyFilterType); m_MagnifyFilter = createNewFilter(magnifyFilterType, m_MagnifyFilterType); } //************************************************************************************************** ossimFilter* ossimScaleFilter::createNewFilter(ossimScaleFilterType filterType, ossimScaleFilterType& result) { switch(filterType) { case ossimScaleFilter_NEAREST_NEIGHBOR: { return new ossimNearestNeighborFilter(); } case ossimScaleFilter_BOX: { return new ossimBoxFilter(); } case ossimScaleFilter_GAUSSIAN: { return new ossimGaussianFilter(); } case ossimScaleFilter_CUBIC: { return new ossimCubicFilter(); } case ossimScaleFilter_HANNING: { return new ossimHanningFilter(); } case ossimScaleFilter_HAMMING: { return new ossimHammingFilter(); } case ossimScaleFilter_LANCZOS: { return new ossimLanczosFilter(); } case ossimScaleFilter_CATROM: { return new ossimCatromFilter(); } case ossimScaleFilter_MITCHELL: { return new ossimMitchellFilter(); } case ossimScaleFilter_BLACKMAN: { return new ossimBlackmanFilter(); } case ossimScaleFilter_BLACKMAN_SINC: { return new ossimBlackmanSincFilter(); } case ossimScaleFilter_BLACKMAN_BESSEL: { return new ossimBlackmanBesselFilter(); } case ossimScaleFilter_QUADRATIC: { return new ossimQuadraticFilter(); } case ossimScaleFilter_TRIANGLE: { return new ossimTriangleFilter(); } case ossimScaleFilter_HERMITE: { return new ossimHermiteFilter(); } } result = ossimScaleFilter_NEAREST_NEIGHBOR; return new ossimNearestNeighborFilter(); } //************************************************************************************************** void ossimScaleFilter::setScaleFactor(const ossimDpt& scale) { m_ScaleFactor = scale; if(fabs(m_ScaleFactor.x) <= FLT_EPSILON) { m_ScaleFactor.x = 1.0; } if(fabs(m_ScaleFactor.y) <= FLT_EPSILON) { m_ScaleFactor.y = 1.0; } m_InverseScaleFactor.x = 1.0/m_ScaleFactor.x; m_InverseScaleFactor.y = 1.0/m_ScaleFactor.y; // A change in the scale factor implies a change to the image geometry. If one has been created // it needs to be modified: updateGeometry(); } //************************************************************************************************** template void ossimScaleFilter::runHorizontalFilterTemplate( T /* dummy */, const ossimRefPtr& input, ossimRefPtr& output) { ossimIrect viewRect = output->getImageRectangle(); ossimIrect imageRect = input->getImageRectangle(); ossim_int32 vw = viewRect.width(); ossim_int32 vh = viewRect.height(); ossim_int32 iw = imageRect.width(); ossimIpt origin(viewRect.ul()); ossimIpt imageOrigin(imageRect.ul()); ossimIpt inputUl = m_InputRect.ul(); ossimIpt inputLr = m_InputRect.lr(); double scale = 0.0; double support = 0.0; ossim_int32 x = 0; ossim_int32 y = 0; ossim_int32 start = 0; ossim_int32 stop = 0; ossim_int32 kernelIdx = 0; const ossimFilter* filter = getHorizontalFilter(); ossim_float64 center = 0.0; ossim_int32 bandIdx = 0; ossim_int32 numberOfBands = m_Tile->getNumberOfBands(); scale = m_BlurFactor*ossim::max(1.0/m_ScaleFactor.x, 1.0); support=scale*filter->getSupport(); if (support <= 0.5) { support = 0.5 + FLT_EPSILON; scale = 1.0; } scale=1.0/scale; for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* imageBuf = (T*)input->getBuf(bandIdx); T* viewBuf = (T*)output->getBuf(bandIdx); T np = (T)input->getNullPix(bandIdx); T outNp = (T)output->getNullPix(bandIdx); T outMinPix = (T)output->getMinPix(bandIdx); T outMaxPix = (T)output->getMaxPix(bandIdx); for(x = 0; x < vw; ++x) { center=(origin.x + x+ .5)/m_ScaleFactor.x; start=ossim::max((ossim_int32)ossim::round(center-support), (ossim_int32)inputUl.x); stop=ossim::min((ossim_int32)ossim::round(center+support), (ossim_int32)inputLr.x); ossim_int32 delta = stop-start; if (delta <= 0) { break; } vector kernel(delta); double density=0.0; for(kernelIdx = 0; kernelIdx < delta; ++kernelIdx) { double t = scale*(start + kernelIdx - center + .5); kernel[kernelIdx] = filter->filter(t, filter->getSupport()); density += kernel[kernelIdx]; } if ((density != 0.0) && (density != 1.0)) { /* Normalize. */ density=1.0/density; for (kernelIdx=0; kernelIdx < delta; kernelIdx++) kernel[kernelIdx]*=density; } ossim_int32 offset = start - imageOrigin.x; T* xptr = imageBuf + offset; T* xCenterptr = imageBuf + offset; T* outptr = viewBuf + x; for(y = 0; y < vh; ++y) { double result = 0.0; density = 0.0; if((*xCenterptr) == np) { *outptr = outNp; } else { for(kernelIdx = 0; kernelIdx < (int)kernel.size(); ++kernelIdx) { if((*xptr != np)&& (kernel[kernelIdx] != 0.0)) { result += ((double)(*(xptr+kernelIdx))*kernel[kernelIdx]); density += kernel[kernelIdx]; } } if(density != 0.0) { result /= density; if(result < outMinPix) result = outMinPix; if(result > outMaxPix) result = outMaxPix; *outptr = (T)result; } else { *outptr = outNp; } } xCenterptr += iw; xptr += iw; outptr += vw; } } } } //************************************************************************************************** template void ossimScaleFilter::runVerticalFilterTemplate( T /* dummy */, const ossimRefPtr& input, ossimRefPtr& output) { ossimIrect viewRect = output->getImageRectangle(); ossimIrect imageRect = input->getImageRectangle(); ossim_int32 vw = viewRect.width(); ossim_int32 vh = viewRect.height(); ossim_int32 iw = imageRect.width(); ossimIpt origin(viewRect.ul()); ossimIpt imageOrigin(imageRect.ul()); ossimIpt inputUl = m_InputRect.ul(); ossimIpt inputLr = m_InputRect.lr(); double scale = 0.0; double support = 0.0; ossim_int32 x = 0; ossim_int32 y = 0; ossim_int32 start = 0; ossim_int32 stop = 0; ossim_int32 kernelIdx = 0; const ossimFilter* filter = getVerticalFilter(); ossim_float64 center = 0.0; ossim_int32 bandIdx = 0; ossim_int32 numberOfBands = m_Tile->getNumberOfBands(); scale = m_BlurFactor*ossim::max(1.0/m_ScaleFactor.y, 1.0); support=scale*filter->getSupport(); if (support <= 0.5) { support = .5 + FLT_EPSILON; scale = 1.0; } scale=1.0/scale; for(bandIdx = 0; bandIdx < numberOfBands; ++bandIdx) { T* imageBuf = (T*)input->getBuf(bandIdx); T* viewBuf = (T*)output->getBuf(bandIdx); T np = (T)input->getNullPix(bandIdx); T outNp = (T)output->getNullPix(bandIdx); T outMinPix = (T)output->getMinPix(bandIdx); T outMaxPix = (T)output->getMaxPix(bandIdx); for(y = 0; y < vh; ++y) { center=(double) ((y + origin.y+0.5)/m_ScaleFactor.y); start=ossim::max((ossim_int32)ossim::round(center-support), (ossim_int32)inputUl.y); stop=ossim::min((ossim_int32)ossim::round(center+support), (ossim_int32)inputLr.y); ossim_int32 delta = stop-start; if (delta <= 0) { break; } vector kernel(delta); double density = 0.0; for(kernelIdx = 0; kernelIdx < delta; ++kernelIdx) { kernel[kernelIdx] = filter->filter(scale*(start + kernelIdx - center + .5), filter->getSupport()); density += kernel[kernelIdx]; } if ((density != 0.0) && (density != 1.0)) { /* Normalize. */ density=1.0/density; for (kernelIdx=0; kernelIdx < delta; kernelIdx++) kernel[kernelIdx]*=density; } ossim_int32 offset = ((start - imageOrigin.y)*iw); ossim_int32 offsetCenter = ((((ossim_int32)center) - imageOrigin.y)*iw); for(x = 0; x < vw; ++x) { T* yptr = imageBuf + offset + x; T* yCenterptr = imageBuf + offsetCenter + x; double result = 0.0; density = 0.0; if((*yCenterptr) == np) { *viewBuf = outNp; } else { for(kernelIdx = 0; kernelIdx < delta; ++kernelIdx) { if((*yptr != np)&& (kernel[kernelIdx] != 0.0)) { result += ((*yptr)*kernel[kernelIdx]); density += kernel[kernelIdx]; } yptr += iw; } if(density != 0.0) { result /= density; if(result < outMinPix) result = outMinPix; if(result > outMaxPix) result = outMaxPix; *viewBuf = (T)result; } else { *viewBuf = outNp; } } ++viewBuf; } } } } //************************************************************************************************** void ossimScaleFilter::initialize() { ossimImageSourceFilter::initialize(); // Force an allocate next getTile. m_Tile = NULL; m_BlankTile = NULL; m_InputRect.makeNan(); } //************************************************************************************************** void ossimScaleFilter::allocate() { m_Tile = NULL; m_BlankTile = NULL; m_InputRect.makeNan(); if(theInputConnection&&isSourceEnabled()) { m_Tile = ossimImageDataFactory::instance()->create(this, this); m_BlankTile = ossimImageDataFactory::instance()->create(this, this); m_Tile->initialize(); m_InputRect = theInputConnection->getBoundingRect(); } } //************************************************************************************************** // Returns a pointer reference to the active image geometry at this filter. The input source // geometry is modified, so we need to maintain our own geometry object as a data member. //************************************************************************************************** ossimRefPtr ossimScaleFilter::getImageGeometry() { // Have we already defined our own geometry? Return it if so: if (m_ScaledGeometry.valid()) return m_ScaledGeometry; // Otherwise we'll need to establish a geometry based on the input connection: if(theInputConnection) { // Fetch the map projection of the input image if it exists: ossimRefPtr inputGeom = theInputConnection->getImageGeometry(); // If trivial case of identity scale, just pass along the input connection's geometry: if ((m_ScaleFactor.x == 1.0) && (m_ScaleFactor.y == 1.0)) return inputGeom; // Need to create a copy of the input geom and modify it as our own, then pass that: if ( inputGeom.valid() ) { m_ScaledGeometry = new ossimImageGeometry(*inputGeom); updateGeometry(); // Return the modified geometry: return m_ScaledGeometry; } } // No geometry defined, return NULL pointer: return ossimRefPtr(); } //************************************************************************************************** ossimIrect ossimScaleFilter::scaleRect(const ossimIrect input, const ossimDpt& scaleFactor)const { ossimIpt origin(ossim::round(input.ul().x*scaleFactor.x), ossim::round(input.ul().y*scaleFactor.y)); ossim_int32 w = ossim::round(input.width()*scaleFactor.x); ossim_int32 h = ossim::round(input.height()*scaleFactor.y); if(w < 1) w = 1; if(h < 1) h = 1; return ossimIrect(origin.x, origin.y, origin.x + (w-1), origin.y + (h-1)); } //************************************************************************************************** ossimString ossimScaleFilter::getFilterTypeAsString(ossimScaleFilterType type)const { switch(type) { case ossimScaleFilter_NEAREST_NEIGHBOR: { return "nearest_neighbor"; } case ossimScaleFilter_BOX: { return "box"; } case ossimScaleFilter_GAUSSIAN: { return "gaussian"; } case ossimScaleFilter_CUBIC: { return "cubic"; } case ossimScaleFilter_HANNING: { return "hanning"; } case ossimScaleFilter_HAMMING: { return "hamming"; } case ossimScaleFilter_LANCZOS: { return "lanczos"; } case ossimScaleFilter_MITCHELL: { return "mitchell"; } case ossimScaleFilter_CATROM: { return "catrom"; } case ossimScaleFilter_BLACKMAN: { return "blackman"; } case ossimScaleFilter_BLACKMAN_SINC: { return "blackman_sinc"; } case ossimScaleFilter_BLACKMAN_BESSEL: { return "blackman_bessel"; } case ossimScaleFilter_QUADRATIC: { return "quadratic"; } case ossimScaleFilter_TRIANGLE: { return "triangle"; } case ossimScaleFilter_HERMITE: { return "hermite"; } } return "nearest_neighbor"; } //************************************************************************************************** ossimScaleFilter::ossimScaleFilterType ossimScaleFilter::getFilterType(const ossimString& type)const { ossimString typeUpper = type; typeUpper = typeUpper.upcase(); if(typeUpper.contains("BOX")) { return ossimScaleFilter_BOX; } else if(typeUpper.contains("NEAREST_NEIGHBOR")) { return ossimScaleFilter_NEAREST_NEIGHBOR; } else if(typeUpper.contains("GAUSSIAN")) { return ossimScaleFilter_GAUSSIAN; } else if(typeUpper.contains("HANNING")) { return ossimScaleFilter_HANNING; } else if(typeUpper.contains("HAMMING")) { return ossimScaleFilter_HAMMING; } else if(typeUpper.contains("LANCZOS")) { return ossimScaleFilter_LANCZOS; } else if(typeUpper.contains("MITCHELL")) { return ossimScaleFilter_MITCHELL; } else if(typeUpper.contains("CATROM")) { return ossimScaleFilter_CATROM; } else if(typeUpper.contains("CUBIC")) { return ossimScaleFilter_CUBIC; } else if(typeUpper.contains("BLACKMAN_BESSEL")) { return ossimScaleFilter_BLACKMAN_BESSEL; } else if(typeUpper.contains("BLACKMAN_SINC")) { return ossimScaleFilter_BLACKMAN_SINC; } else if(typeUpper.contains("BLACKMAN")) { return ossimScaleFilter_BLACKMAN; } else if(typeUpper.contains("QUADRATIC")) { return ossimScaleFilter_QUADRATIC; } else if(typeUpper.contains("TRIANGLE")) { return ossimScaleFilter_TRIANGLE; } else if(typeUpper.contains("HERMITE")) { return ossimScaleFilter_HERMITE; } return ossimScaleFilter_NEAREST_NEIGHBOR; } //************************************************************************************************** void ossimScaleFilter::getSupport(double& x, double& y) { const ossimFilter* horizontalFilter = getHorizontalFilter(); const ossimFilter* verticalFilter = getVerticalFilter(); x = m_BlurFactor*ossim::max(1.0/m_ScaleFactor.x, 1.0)* horizontalFilter->getSupport(); y = m_BlurFactor*ossim::max(1.0/m_ScaleFactor.y, 1.0)* verticalFilter->getSupport(); } //************************************************************************************************** const ossimFilter* ossimScaleFilter::getHorizontalFilter()const { if(m_ScaleFactor.x < 1) { return m_MinifyFilter; } return m_MagnifyFilter; } //************************************************************************************************** const ossimFilter* ossimScaleFilter::getVerticalFilter()const { if(m_ScaleFactor.y < 1) { return m_MinifyFilter; } return m_MagnifyFilter; } //************************************************************************************************** bool ossimScaleFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::SCALE_X_KW, m_ScaleFactor.x, true); kwl.add(prefix, ossimKeywordNames::SCALE_Y_KW, m_ScaleFactor.y, true); kwl.add(prefix, "minify_type", getFilterTypeAsString(m_MinifyFilterType), true); kwl.add(prefix, "magnify_type", getFilterTypeAsString(m_MagnifyFilterType), true); return ossimImageSourceFilter::saveState(kwl, prefix); } //************************************************************************************************** bool ossimScaleFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString scalex = kwl.find(prefix, ossimKeywordNames::SCALE_X_KW); ossimString scaley = kwl.find(prefix, ossimKeywordNames::SCALE_Y_KW); ossimString minify = kwl.find(prefix, "minify_type"); ossimString magnify = kwl.find(prefix, "magnify_type"); m_ScaleFactor.x = scalex.toDouble(); m_ScaleFactor.y = scaley.toDouble(); if(fabs(m_ScaleFactor.x) <= FLT_EPSILON) { m_ScaleFactor.x = 1.0; } if(fabs(m_ScaleFactor.y) <= FLT_EPSILON) { m_ScaleFactor.y = 1.0; } m_InverseScaleFactor.x = 1.0/m_ScaleFactor.x; m_InverseScaleFactor.y = 1.0/m_ScaleFactor.y; setFilterType(getFilterType(minify), getFilterType(magnify)); // A change in the scale factor implies a change to the image geometry. If one has been created // it needs to be modified: updateGeometry(); return ossimImageSourceFilter::loadState(kwl, prefix); } //************************************************************************************************** //! If this object is maintaining an ossimImageGeometry, this method needs to be called after //! a scale change so that the geometry's projection is modified accordingly. //************************************************************************************************** void ossimScaleFilter::updateGeometry() { if (m_ScaledGeometry.valid()) { // Modify the image geometry's projection with the scale factor before returning geom: ossimProjection* proj = m_ScaledGeometry->getProjection(); ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, proj); if(mapProj) mapProj->applyScale(m_InverseScaleFactor, true); } } ossim-Miami-2.9.1/src/imaging/ossimShiftFilter.cpp000066400000000000000000000203101352751253100221130ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Filter for shifting input to an output range. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimShiftFilter, "ossimShiftFilter", ossimImageSourceFilter) static ossimTrace traceDebug("ossimShiftFilter:debug"); ossimShiftFilter::ossimShiftFilter() : ossimImageSourceFilter(), // base class m_tile(0), m_min(ossim::nan()), m_max(ossim::nan()), m_null(ossim::nan()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimShiftFilter::ossimShiftFilter entered...\n"; } } ossimShiftFilter::~ossimShiftFilter() { } void ossimShiftFilter::initialize() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimShiftFilter::initialize entered..." << endl; } //--- // Call the base class initialize. // Note: This will reset "theInputConnection" if it changed... //--- ossimImageSourceFilter::initialize(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimShiftFilter::initialize exited..." << endl; } } ossimRefPtr ossimShiftFilter::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimRefPtr result = 0; if ( theInputConnection ) { ossimRefPtr inputTile = theInputConnection->getTile( tileRect, resLevel ); if ( inputTile.get() && isSourceEnabled() && !ossim::isnan(m_null) && !ossim::isnan(m_min) && !ossim::isnan(m_max) ) { // Get its status of the input tile. ossimDataObjectStatus tile_status = inputTile->getDataObjectStatus(); if ( tile_status != OSSIM_NULL ) { if ( !m_tile ) { allocate(); // First time through. } if ( tile_status != OSSIM_EMPTY ) { // Set the origin,bands of the output tile. m_tile->setImageRectangle(tileRect); switch(inputTile->getScalarType()) { case OSSIM_UINT8: { fillTile( ossim_uint8(0), inputTile.get(), m_tile.get() ); break; } case OSSIM_SINT8: { fillTile( ossim_sint8(0), inputTile.get(), m_tile.get() ); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { fillTile( ossim_uint16(0), inputTile.get(), m_tile.get() ); break; } case OSSIM_SINT16: { fillTile( ossim_sint16(0), inputTile.get(), m_tile.get() ); break; } case OSSIM_SINT32: { fillTile( ossim_sint32(0), inputTile.get(), m_tile.get() ); break; } case OSSIM_UINT32: { fillTile( ossim_uint32(0), inputTile.get(), m_tile.get() ); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { fillTile( ossim_float32(0), inputTile.get(), m_tile.get() ); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { fillTile( ossim_float64(0), inputTile.get(), m_tile.get() ); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimShiftFilter::getTile ERROR Unhandled scalar!" << endl; break; } } // Matches: switch(inputTile->getScalarType()) m_tile->validate(); } else { m_tile->makeBlank(); } result = m_tile; } // Matches: if ( tile_status != OSSIM_NULL ) } // Matches: if ( inputTile.get() ... ) if ( !result && inputTile.get() ) { result = inputTile; } } // Matches: if ( theInputConnection ) return result; } template void ossimShiftFilter::fillTile(T /* dummy */, const ossimImageData* inputTile, ossimImageData* outputTile) const { const double BANDS = inputTile->getNumberOfBands(); const ossim_uint32 SPB = inputTile->getSizePerBand(); std::vector inNull(BANDS); std::vector inMin(BANDS); std::vector inMax(BANDS); std::vector coef(BANDS); ossim_uint32 band = 0; for( ; band < BANDS; ++band ) { inNull[band] = inputTile->getNullPix(band); inMin[band] = inputTile->getMinPix(band); inMax[band] = inputTile->getMaxPix(band); coef[band] = (m_max-m_min)/(inMax[band]-inMin[band]); } double pix = 0; for( band = 0; band < BANDS; ++band ) { const T* inBuf = static_cast(inputTile->getBuf(band)); T* outBuf = static_cast(outputTile->getBuf(band)); for ( ossim_uint32 i = 0; i < SPB; ++i ) { pix = inBuf[i]; if ( pix == inNull[band] ) { pix = m_null; } else { // Shift and multiply: pix = m_min + (pix - inMin[band]) * coef[band]; // Range check: pix = pix <= m_max ? (pix >= m_min ? pix : m_min) : m_max; } outBuf[i] = static_cast(pix); } } outputTile->validate(); } ossimString ossimShiftFilter::getClassName() const { return ossimString("ossimShiftFilter"); } ossimString ossimShiftFilter::getLongName()const { return ossimString("OSSIM shift filter"); } ossimString ossimShiftFilter::getShortName()const { return ossimString("shift filter"); } double ossimShiftFilter::getNullPixelValue(ossim_uint32 band )const { double result = 0;; if ( theEnableFlag && !ossim::isnan(m_null) ) { result = m_null; } else { result = ossimImageSourceFilter::getNullPixelValue( band ); } return result; } double ossimShiftFilter::getMinPixelValue(ossim_uint32 band )const { double result = 0;; if ( theEnableFlag && !ossim::isnan(m_min) ) { result = m_min; } else { result = ossimImageSourceFilter::getMinPixelValue( band ); } return result; } double ossimShiftFilter::getMaxPixelValue(ossim_uint32 band )const { double result = 0;; if ( theEnableFlag && !ossim::isnan(m_max) ) { result = m_max; } else { result = ossimImageSourceFilter::getMaxPixelValue( band ); } return result; } void ossimShiftFilter::setNullPixelValue(double null) { m_null = null; } void ossimShiftFilter::setMinPixelValue(double min) { m_min = min; } void ossimShiftFilter::setMaxPixelValue(double max) { m_max = max; } void ossimShiftFilter::allocate() { m_tile = ossimImageDataFactory::instance()->create(this,this); m_tile->initialize(); } // Private to disallow use... ossimShiftFilter::ossimShiftFilter(const ossimShiftFilter&) : m_min(0),m_max(0),m_null(0) { } // Private to disallow use... ossimShiftFilter& ossimShiftFilter::operator=(const ossimShiftFilter&) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimSingleImageChain.cpp000066400000000000000000000663341352751253100230370ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Utility class definition for a single image chain. // //--- // $Id$ #include #include #include #include #include #include // #include #include using namespace std; ossimSingleImageChain::ossimSingleImageChain() : ossimImageChain(), m_handler(0), m_bandSelector(0), m_histogramRemapper(0), m_gammaRemapper(0), m_brightnessContrast(0), m_sharpen(0), m_scalarRemapper(0), m_resamplerCache(0), m_resampler(0), m_chainCache(0), m_addNullPixelFlipFlag(false), m_addHistogramFlag(false), m_addGammaFlag(false), m_addResamplerCacheFlag(false), m_addChainCacheFlag(false), m_remapToEightBitFlag(false), m_threeBandFlag(false), m_threeBandReverseFlag(false), m_brightnessContrastFlag(false), m_sharpenFlag(false), m_geoPolyCutterFlag(false) { } ossimSingleImageChain::ossimSingleImageChain(bool addNullPixelFlipFlag, bool addHistogramFlag, bool addResamplerCacheFlag, bool addChainCacheFlag, bool remapToEightBitFlag, bool threeBandFlag, bool threeBandReverseFlag, bool brightnessContrastFlag, bool sharpenFlag, bool geoPolyCutterFlag) : ossimImageChain(), m_handler(0), m_bandSelector(0), m_histogramRemapper(0), m_gammaRemapper(0), m_brightnessContrast(0), m_sharpen(0), m_scalarRemapper(0), m_resamplerCache(0), m_resampler(0), m_chainCache(0), m_addNullPixelFlipFlag(addNullPixelFlipFlag), m_addHistogramFlag(addHistogramFlag), m_addResamplerCacheFlag(addResamplerCacheFlag), m_addChainCacheFlag(addChainCacheFlag), m_remapToEightBitFlag(remapToEightBitFlag), m_threeBandFlag(threeBandFlag), m_threeBandReverseFlag(threeBandReverseFlag), m_brightnessContrastFlag(brightnessContrastFlag), m_sharpenFlag(sharpenFlag), m_geoPolyCutterFlag(geoPolyCutterFlag) { } ossimSingleImageChain::~ossimSingleImageChain() { m_handler = 0; m_nullPixelFlip = 0; m_bandSelector = 0; m_histogramRemapper = 0; m_gammaRemapper = 0; m_brightnessContrast = 0; m_sharpen = 0; m_scalarRemapper = 0; m_resamplerCache = 0; m_resampler = 0; m_chainCache = 0; m_geoPolyCutter = 0; } void ossimSingleImageChain::reset() { bool result = true; do { result = deleteLast(); } while (result); m_handler = 0; m_bandSelector = 0; m_nullPixelFlip = 0; m_histogramRemapper = 0; m_gammaRemapper = 0; m_brightnessContrast = 0; m_sharpen = 0; m_scalarRemapper = 0; m_resamplerCache = 0; m_resampler = 0; m_geoPolyCutter = 0; m_chainCache = 0; m_addHistogramFlag = false; m_addGammaFlag = false; m_addNullPixelFlipFlag = false; m_addResamplerCacheFlag = false; m_addChainCacheFlag = false; m_remapToEightBitFlag = false; m_threeBandFlag = false; m_threeBandReverseFlag = false; m_brightnessContrastFlag = false; m_sharpenFlag = false; m_geoPolyCutterFlag = false; } void ossimSingleImageChain::close() { if ( m_handler.valid() ) { if ( removeChild(m_handler.get()) ) { m_handler = 0; } } } ossimFilename ossimSingleImageChain::getFilename() const { ossimFilename result; if ( m_handler.valid() ) { result = m_handler->getFilename(); } return result; } bool ossimSingleImageChain::open(const ossimFilename& file, bool openOverview) { return addImageHandler(file, openOverview); } bool ossimSingleImageChain::isOpen() const { return m_handler.valid(); } bool ossimSingleImageChain::open(const ossimSrcRecord& src) { return addImageHandler(src); } void ossimSingleImageChain::createRenderedChain() { // Band selector after image handler only if needed. if ( m_handler.valid() ) { // Only add if multiple bands. if ( m_handler->getNumberOfOutputBands() != 1 ) { addBandSelector(); if ( m_threeBandReverseFlag ) { setToThreeBandsReverse(); } } } else // No image handler so just add it. { addBandSelector(); } // will do this here. Not sure if we want flipped just before the resampler or if we want to do it here. // I think this is a better place for you can now manipulate the flipped pixel if (m_addNullPixelFlipFlag) { addNullPixelFlip(); } // histogram: if ( m_addHistogramFlag ) { addHistogramRemapper(); } if(m_addGammaFlag) { addGammaRemapper(); } // brightness contrast: if ( m_brightnessContrastFlag ) { addBrightnessContrast(); } // sharpen filter: if ( m_sharpenFlag ) { addSharpen(); } // scalar remapper if ( m_remapToEightBitFlag ) { if ( m_handler.valid() ) { // See if it's eight bit. if (m_handler->getOutputScalarType() != OSSIM_UINT8) { addScalarRemapper(); } } else { // Just add... addScalarRemapper(); } } // resampler cache if ( m_addResamplerCacheFlag ) { m_resamplerCache = addCache(); // If input image is tiled set the cache input tile size to that. if ( m_handler.valid() ) { if ( m_handler->isImageTiled() ) { ossimIpt inputImageTileSize; inputImageTileSize.x = (ossim_int32)m_handler->getImageTileWidth(); inputImageTileSize.y = (ossim_int32)m_handler->getImageTileHeight(); if ( m_resamplerCache.valid() ) { m_resamplerCache->setTileSize( inputImageTileSize ); } } } } #if 0 /* test code - drb */ ossimRefPtr tp = new ossimTiledImagePatch(); if ( m_handler.valid() ) { if ( m_handler->isImageTiled() ) { ossimIpt inputImageTileSize; inputImageTileSize.x = (ossim_int32)m_handler->getImageTileWidth(); inputImageTileSize.y = (ossim_int32)m_handler->getImageTileHeight(); tp->setInputTileSize( inputImageTileSize ); } } addFirst( tp.get() ); #endif // resampler addResampler(); #if 0 /* test code - drb */ ossimRefPtr tp2 = new ossimTiledImagePatch(); ossimIpt inputImageTileSize(64, 64); tp2->setInputTileSize( inputImageTileSize ); addFirst( tp2.get() ); #endif //--- // Do this here so that if a band selector is added to the end of the // chain it will go in before the end of chain cache. //--- if (m_threeBandFlag) { if (!m_bandSelector) { addBandSelector(); } setToThreeBands(); } //--- // Ditto... //--- if ( m_threeBandReverseFlag && !m_bandSelector ) { addBandSelector(); setToThreeBandsReverse(); } // Put the geo cutter just before the cache. if(m_geoPolyCutterFlag) { addGeoPolyCutter(); } // End of chain cache. if ( m_addChainCacheFlag ) { m_chainCache = addCache(); } initialize(); } void ossimSingleImageChain::createRenderedChain(const ossimSrcRecord& src) { // Band selector after image handler only if needed. if ( m_handler.valid() ) { // Only add if needed. if ( ( m_handler->getNumberOfOutputBands() != 1 ) || src.getBands().size() ) { addBandSelector(src); if ( m_threeBandReverseFlag ) { setToThreeBandsReverse(); } } } else // No image handler so just add it. { addBandSelector(src); } if(m_addNullPixelFlipFlag) { addNullPixelFlip(); } // histogram if ( m_addHistogramFlag || src.getHistogramOp().size() ) { addHistogramRemapper(src); } if(m_addGammaFlag) { addGammaRemapper(); } // brightness contrast: if ( m_brightnessContrastFlag ) { addBrightnessContrast(); } // sharpen filter: if ( m_sharpenFlag ) { addSharpen(); } // scalar remapper if ( m_remapToEightBitFlag ) { if ( m_handler.valid() ) { // See if it's eight bit. if (m_handler->getOutputScalarType() != OSSIM_UINT8) { addScalarRemapper(); } } else { // Just add... addScalarRemapper(); } } // resampler cache if ( m_addResamplerCacheFlag ) { m_resamplerCache = addCache(); } // resampler addResampler(); //--- // Do this here so that if a band selector is added to the end of the // chain it will go in before the end of chain cache. //--- if (m_threeBandFlag) { if (!m_bandSelector) // Input must be one band. { addBandSelector(src); } setToThreeBands(); } //--- // Ditto... //--- if ( m_threeBandReverseFlag && !m_bandSelector ) { addBandSelector(); setToThreeBandsReverse(); } // End of chain cache. if ( m_addChainCacheFlag ) { m_chainCache = addCache(); } initialize(); } bool ossimSingleImageChain::addImageHandler(const ossimFilename& file, bool openOverview) { bool result = false; close(); // m_handler = ossimImageHandlerRegistry::instance()->open(file, true, openOverview); m_handler = ossimImageHandlerRegistry::instance()->openConnection(file, openOverview); if ( m_handler.valid() ) { // Add to the chain. Note: last is really first. addLast( m_handler.get() ); result = true; } return result; } bool ossimSingleImageChain::addImageHandler(const ossimSrcRecord& src) { bool result = false; close(); // m_handler = ossimImageHandlerRegistry::instance()->open(file, true, openOverview); m_handler = ossimImageHandlerRegistry::instance()->open(src.getAttributesKwl()); if ( m_handler.valid() ) { // Add to the chain. Note: last is really first. addLast( m_handler.get() ); result = true; } return result; // bool result = addImageHandler( src.getFilename() ); #if 0 if (result) { //--- // When loading from ossimSrcRecord typically the overview/histograms are // not in the same directory and the "support" keyword is not set. For // the ossimImageHandler::getFilenameWithThisExtension to work correctly // the ossimImageHandler::theSupplementaryDirectory must be set. // So if the ossimSrcRecord::getSupportDir() is empty and the overview // or histogram is not co-located with the image we will set it here. //--- ossimFilename supportDir = src.getSupportDir(); if ( supportDir.empty() ) { if ( src.getOverviewPath().size() ) { if ( src.getOverviewPath().isDir() ) { supportDir = src.getOverviewPath(); } else { supportDir = src.getOverviewPath().path(); } } else if ( src.getHistogramPath().size() ) { if ( src.getHistogramPath().isDir() ) { supportDir = src.getHistogramPath(); } else { supportDir = src.getHistogramPath().path(); } } else if ( src.getMaskPath().size() ) { if ( src.getMaskPath().isDir() ) { supportDir = src.getMaskPath(); } else { supportDir = src.getMaskPath().path(); } } } if ( supportDir.size() && (src.getFilename().path() != supportDir) ) { m_handler->setSupplementaryDirectory( supportDir ); } if ( src.getEntryIndex() > 0 ) // defaulted to -1. { m_handler->setCurrentEntry( static_cast( src.getEntryIndex() ) ); } if ( m_handler->getOverview() == 0 ) { if ( src.getOverviewPath().size() ) { m_handler->openOverview( src.getOverviewPath() ); } else { ossimFilename ovrFile = m_handler->getFilenameWithThisExtension(ossimString(".ovr")); m_handler->openOverview( ovrFile ); } } } #endif return result; } void ossimSingleImageChain::addBandSelector() { if (!m_bandSelector) { m_bandSelector = new ossimBandSelector(); // Add to the end of the chain. addFirst(m_bandSelector.get()); } } void ossimSingleImageChain::addBandSelector(const ossimSrcRecord& src) { if (!m_bandSelector) { m_bandSelector = new ossimBandSelector(); // Add to the end of the chain. addFirst(m_bandSelector.get()); } if ( src.getBands().size() ) { m_bandSelector->setOutputBandList( src.getBands() ); } } void ossimSingleImageChain::addNullPixelFlip() { if(!m_nullPixelFlip) { m_nullPixelFlip = new ossimNullPixelFlip(); addFirst(m_nullPixelFlip.get()); } } void ossimSingleImageChain::addNullPixelFlip(const ossimSrcRecord& src) { if(!m_nullPixelFlip) { m_nullPixelFlip = new ossimNullPixelFlip(); addFirst(m_nullPixelFlip.get()); } } void ossimSingleImageChain::addHistogramRemapper() { if (!m_histogramRemapper) { m_histogramRemapper = new ossimHistogramRemapper(); m_histogramRemapper->setEnableFlag(false); // Add to the end of the chain. addFirst(m_histogramRemapper.get()); } } void ossimSingleImageChain::addHistogramRemapper(const ossimSrcRecord& src) { static const char MODULE[] = "ossimSingleImageChain::addHistogramRemapper(const ossimSrcRecord&)"; if (!m_histogramRemapper) { m_histogramRemapper = new ossimHistogramRemapper(); m_histogramRemapper->setEnableFlag(false); // Add to the end of the chain. addFirst(m_histogramRemapper.get()); } if ( src.getHistogramOp().size() && m_handler.valid() ) { // Create histogram code here??? // Open the histogram if needed. if ( m_histogramRemapper->getHistogramFile() == ossimFilename::NIL ) { ossimFilename f; if ( src.getSupportDir().size() ) { f = src.getSupportDir(); f.dirCat( m_handler->getFilename().fileNoExtension() ); f.setExtension(".his"); } else { f = m_handler->getFilenameWithThisExtension( ossimString("his") ); } if ( m_histogramRemapper->openHistogram( f ) == false ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << "\nCould not open: " << f << "\n"; } } // Set the histogram strech mode. if ( src.getHistogramOp().size() ) { // Enable. m_histogramRemapper->setEnableFlag(true); // Set the histo mode: ossimString op = src.getHistogramOp(); op.downcase(); if ( op == "auto-minmax" ) { m_histogramRemapper->setStretchMode( ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX ); } else if ( (op == "std-stretch-1") || (op == "std-stretch 1") ) { m_histogramRemapper->setStretchMode( ossimHistogramRemapper::LINEAR_1STD_FROM_MEAN ); } else if ( (op == "std-stretch-2") || (op == "std-stretch 2") ) { m_histogramRemapper->setStretchMode( ossimHistogramRemapper::LINEAR_2STD_FROM_MEAN ); } else if ( (op == "std-stretch-3") || (op == "std-stretch 3") ) { m_histogramRemapper->setStretchMode( ossimHistogramRemapper::LINEAR_3STD_FROM_MEAN ); } else { m_histogramRemapper->setEnableFlag(false); ossimNotify(ossimNotifyLevel_WARN) << MODULE << "\nUnhandled operation: " << op << "\n"; } } } // End: if ( src.setHistogramOp().size() && m_handler.valid() ) } ossimRefPtr ossimSingleImageChain::addCache() { ossimRefPtr cache = new ossimCacheTileSource(); // Add to the end of the chain. addFirst(cache.get()); return cache; } void ossimSingleImageChain::addResampler() { if ( !m_resampler ) { m_resampler = new ossimImageRenderer(); // Add to the end of the chain. addFirst(m_resampler.get()); } } void ossimSingleImageChain::addRenderer() { addResampler(); } void ossimSingleImageChain::addScalarRemapper() { if ( !m_scalarRemapper ) { m_scalarRemapper = new ossimScalarRemapper(); if ( m_resamplerCache.valid() ) { // Add to the left of the resampler cache. insertLeft(m_scalarRemapper.get(), m_resamplerCache.get()); } else { // Add to the end of the chain. addFirst(m_scalarRemapper.get()); } } } void ossimSingleImageChain::addGammaRemapper() { if ( !m_gammaRemapper ) { m_gammaRemapper = new ossimGammaRemapper(); // Add to the end of the chain. addFirst( m_gammaRemapper.get() ); } } void ossimSingleImageChain::addGammaRemapper(const ossimSrcRecord& src) { if ( !m_gammaRemapper ) { m_gammaRemapper = new ossimGammaRemapper(); m_gammaRemapper->setGamma(src.getGamma()); // Add to the end of the chain. addFirst( m_gammaRemapper.get() ); } } void ossimSingleImageChain::addBrightnessContrast() { if ( !m_brightnessContrast ) { m_brightnessContrast = new ossimBrightnessContrastSource(); // Add to the end of the chain. addFirst( m_brightnessContrast.get() ); } } void ossimSingleImageChain::addSharpen() { if ( !m_sharpen ) { m_sharpen = new ossimImageSharpenFilter(); // Add to the end of the chain. addFirst( m_sharpen.get() ); } } void ossimSingleImageChain::addGeoPolyCutter() { if(!m_geoPolyCutter.valid()) { m_geoPolyCutter = new ossimGeoPolyCutter(); //--- // ossimGeoPolyCutter requires a view geometry to transform the points. // So set prior to adding to end of chain if valid. If not, user is // responsible for setting. //--- ossimRefPtr geom = getImageGeometry(); if ( geom.valid() ) { m_geoPolyCutter->setView( geom.get() ); } addFirst( m_geoPolyCutter.get() ); } } void ossimSingleImageChain::addGeoPolyCutterPolygon(const vector& polygon) { if(!m_geoPolyCutter.valid()) { addGeoPolyCutter(); } // sanity check to verify that the add did not fail if(m_geoPolyCutter.valid()) { m_geoPolyCutter->addPolygon(polygon); } } void ossimSingleImageChain::addGeoPolyCutterPolygon(const ossimGeoPolygon& polygon) { if(!m_geoPolyCutter.valid()) { addGeoPolyCutter(); } // sanity check to verify that the add did not fail if(m_geoPolyCutter.valid()) { m_geoPolyCutter->addPolygon(polygon); } } ossimRefPtr ossimSingleImageChain::getImageHandler() const { return ossimRefPtr( m_handler.get() ); } ossimRefPtr ossimSingleImageChain::getImageHandler() { return m_handler; } ossimRefPtr ossimSingleImageChain::getBandSelector() const { return ossimRefPtr( m_bandSelector.get() ); } ossimRefPtr ossimSingleImageChain::getNullPixelFlip() const { return ossimRefPtr( m_nullPixelFlip.get() ); } ossimRefPtr ossimSingleImageChain::getBandSelector() { return m_bandSelector; } ossimRefPtr ossimSingleImageChain::getHistogramRemapper() const { return ossimRefPtr( m_histogramRemapper.get() ); } ossimRefPtr ossimSingleImageChain::getHistogramRemapper() { return m_histogramRemapper; } ossimRefPtr ossimSingleImageChain::getGammaRemapper() const { return ossimRefPtr( m_gammaRemapper.get() ); } ossimRefPtr ossimSingleImageChain::getGammaRemapper() { return m_gammaRemapper; } ossimRefPtr ossimSingleImageChain::getResamplerCache() const { return ossimRefPtr( m_resamplerCache.get() ); } ossimRefPtr ossimSingleImageChain::getResamplerCache() { return m_resamplerCache; } ossimRefPtr ossimSingleImageChain::getImageRenderer() const { return ossimRefPtr( m_resampler.get() ); } ossimRefPtr ossimSingleImageChain::getImageRenderer() { return m_resampler; } ossimRefPtr ossimSingleImageChain::getScalarRemapper() const { return ossimRefPtr( m_scalarRemapper.get() ); } ossimRefPtr ossimSingleImageChain::getScalarRemapper() { return m_scalarRemapper; } ossimRefPtr ossimSingleImageChain::getBrightnessContrast() const { return ossimRefPtr( m_brightnessContrast.get() ); } ossimRefPtr ossimSingleImageChain::getBrightnessContrast() { return m_brightnessContrast; } ossimRefPtr ossimSingleImageChain::getSharpenFilter() const { return ossimRefPtr( m_sharpen.get() ); } ossimRefPtr ossimSingleImageChain::getSharpenFilter() { return m_sharpen; } ossimRefPtr ossimSingleImageChain::getChainCache() const { return ossimRefPtr( m_chainCache.get() ); } ossimRefPtr ossimSingleImageChain::getChainCache() { return m_chainCache; } void ossimSingleImageChain::setAddNullPixelFlipFlag(bool flag) { m_addNullPixelFlipFlag = true; } bool ossimSingleImageChain::getNullPixelFlipFlag() const { return m_addNullPixelFlipFlag; } void ossimSingleImageChain::setAddHistogramFlag(bool flag) { m_addHistogramFlag = flag; } bool ossimSingleImageChain::getAddHistogramFlag() const { return m_addHistogramFlag; } void ossimSingleImageChain::setAddGammaFlag(bool flag) { m_addGammaFlag = flag; } bool ossimSingleImageChain::getAddGammaFlag() const { return m_addGammaFlag; } void ossimSingleImageChain::setAddResamplerCacheFlag(bool flag) { m_addResamplerCacheFlag = flag; } bool ossimSingleImageChain::getAddResamplerCacheFlag() const { return m_addResamplerCacheFlag; } void ossimSingleImageChain::setAddChainCacheFlag(bool flag) { m_addChainCacheFlag = flag; } bool ossimSingleImageChain::getAddChainCacheFlag() const { return m_addChainCacheFlag; } void ossimSingleImageChain::setRemapToEightBitFlag(bool flag) { m_remapToEightBitFlag = flag; } bool ossimSingleImageChain::getRemapToEightBitFlag() const { return m_remapToEightBitFlag; } void ossimSingleImageChain::setThreeBandFlag(bool flag) { m_threeBandFlag = flag; } bool ossimSingleImageChain::getThreeBandFlag() const { return m_threeBandFlag; } void ossimSingleImageChain::setThreeBandReverseFlag(bool flag) { m_threeBandReverseFlag = flag; } bool ossimSingleImageChain::getThreeBandReverseFlag() const { return m_threeBandReverseFlag; } void ossimSingleImageChain::setBrightnessContrastFlag(bool flag) { m_brightnessContrastFlag = flag; } bool ossimSingleImageChain::getBrightnessContrastFlag() const { return m_brightnessContrastFlag; } void ossimSingleImageChain::setSharpenFlag(bool flag) { m_sharpenFlag = flag; } bool ossimSingleImageChain::getSharpenFlag() const { return m_sharpenFlag; } void ossimSingleImageChain::setToThreeBands() { if (!m_bandSelector) { addBandSelector(); } m_bandSelector->setEnableFlag(true); m_bandSelector->setThreeBandRgb(); if ( m_histogramRemapper.valid() ) { m_histogramRemapper->initialize(); } #if 0 if ( m_handler.valid() ) { // Only do if not three bands already so the band list order is not wiped out. if ( !m_bandSelector.valid() || ( m_bandSelector.valid() && ( m_bandSelector->getNumberOfOutputBands() != 3 ) ) ) { std::vector bandList(3); if ( m_handler->getRgbBandList( bandList ) == false ) { const ossim_uint32 BANDS = m_handler->getNumberOfInputBands(); if(BANDS >= 3) { bandList[0] = 0; bandList[1] = 1; bandList[2] = 2; } else { bandList[0] = 0; bandList[1] = 0; bandList[2] = 0; } } setBandSelection(bandList); } } #endif } void ossimSingleImageChain::setToThreeBandsReverse() { if ( m_handler.valid() ) { std::vector bandList(3); const ossim_uint32 BANDS = m_handler->getNumberOfInputBands(); if(BANDS >= 3) { bandList[0] = 2; bandList[1] = 1; bandList[2] = 0; } else { bandList[0] = 0; bandList[1] = 0; bandList[2] = 0; } setBandSelection(bandList); } } void ossimSingleImageChain::setBandSelection( const std::vector& bandList) { if (!m_bandSelector) { addBandSelector(); } m_bandSelector->setEnableFlag(true); m_bandSelector->setOutputBandList(bandList); if ( m_histogramRemapper.valid() ) { m_histogramRemapper->initialize(); } } void ossimSingleImageChain::setDefaultBandSelection() { if(!m_bandSelector) { addBandSelector(); } m_bandSelector->setEnableFlag(true); if(m_bandSelector.valid()) { m_bandSelector->setThreeBandRgb(); } } ossimScalarType ossimSingleImageChain::getImageHandlerScalarType() const { ossimScalarType result = OSSIM_SCALAR_UNKNOWN; if ( m_handler.valid() ) { result = m_handler->getOutputScalarType(); } return result; } bool ossimSingleImageChain::openHistogram( ossimHistogramRemapper::StretchMode mode ) { bool result = false; ossimRefPtr ih = getImageHandler(); if ( ih.valid() ) { ossimRefPtr hr = getHistogramRemapper(); if ( hr.valid() ) { ossimFilename f = ih->getFilenameWithThisExtension( ossimString("his") ); if ( hr->openHistogram( f ) == true ) { // Enable: hr->setEnableFlag(true); // Set the mode: hr->setStretchMode( mode ); result = true; } } } return result; } ossim-Miami-2.9.1/src/imaging/ossimSlopeFilter.cpp000066400000000000000000000124521352751253100221300ustar00rootroot00000000000000//******************************************************************* // OSSIM // // License: See top level LICENSE.txt file. // //******************************************************************* // $Id: ossimSlopeFilter.cpp 23451 2015-07-27 15:42:17Z okramer $ #include #include #include #include RTTI_DEF1(ossimSlopeFilter, "ossimSlopeFilter", ossimImageSourceFilter) const char* SLOPE_TYPE_KW = "slope_type"; using namespace std; ossimSlopeFilter::ossimSlopeFilter() : ossimImageSourceFilter(), m_slopeType (DEGREES) { } ossimSlopeFilter::ossimSlopeFilter(ossimImageSource* inputSource) : ossimImageSourceFilter(inputSource), m_slopeType (DEGREES) { } ossimSlopeFilter::~ossimSlopeFilter() { m_normals = 0; } ossimRefPtr ossimSlopeFilter::getTile(const ossimIrect& rect, ossim_uint32 rLevel) { if(!theInputConnection) return ossimRefPtr(); if ( !isSourceEnabled() ) return theInputConnection->getTile(rect, rLevel); if (!m_normals.valid()) initialize(); ossimRefPtr normals = m_normals->getTile(rect, rLevel); if (!normals.valid()) return ossimRefPtr(); ossimRefPtr outputTile = new ossimImageData(this, OSSIM_FLOAT32, 1); outputTile->setImageRectangle(rect); outputTile->initialize(); ossim_float32* output_buf = outputTile->getFloatBuf(); ossim_float32 null_output = (ossim_float32) outputTile->getNullPix(0); double z, theta; double null_input = normals->getNullPix(2); ossim_uint32 num_pix = normals->getSizePerBand(); for (ossim_uint32 i=0; igetPix(i, 2); if (z == null_input) { theta = null_output; } else { switch (m_slopeType) { case RADIANS: theta = acos(z); break; case RATIO: theta = z; break; case NORMALIZED: theta = fabs(acos(z)/M_PI); break; default: // Degrees theta = ossim::acosd(z); }; } output_buf[i] = theta; } outputTile->validate(); return outputTile; } void ossimSlopeFilter::initialize() { if (!m_normals.valid()) m_normals = new ossimImageToPlaneNormalFilter(theInputConnection); m_normals->initialize(); } void ossimSlopeFilter::setProperty(ossimRefPtr property) { if(!property) return; if(property->getName() == SLOPE_TYPE_KW) { ossimString pts (property->valueToString()); pts.upcase(); if (pts.contains("RADIANS")) m_slopeType = RADIANS; else if (pts.contains("DEGREES")) m_slopeType = DEGREES; else if (pts.contains("RATIO")) m_slopeType = RATIO; else if (pts.contains("NORMALIZED")) m_slopeType = NORMALIZED; else return; initialize(); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr ossimSlopeFilter::getProperty(const ossimString& name)const { if(name == SLOPE_TYPE_KW) { ossimString propValue; switch (m_slopeType) { case RADIANS: propValue = getSlopeTypeString(RADIANS); break; case RATIO: propValue = getSlopeTypeString(RATIO); break; case NORMALIZED: propValue = getSlopeTypeString(NORMALIZED); default: propValue = getSlopeTypeString(DEGREES); } vector list; list.push_back(getSlopeTypeString(RADIANS)); list.push_back(getSlopeTypeString(DEGREES)); list.push_back(getSlopeTypeString(RATIO)); list.push_back(getSlopeTypeString(NORMALIZED)); return new ossimStringProperty(SLOPE_TYPE_KW, propValue, false, list); } return ossimImageSourceFilter::getProperty(name); } void ossimSlopeFilter::getPropertyNames(std::vector& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back(SLOPE_TYPE_KW); } bool ossimSlopeFilter::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimImageSourceFilter::saveState(kwl, prefix); kwl.add(prefix, SLOPE_TYPE_KW, getSlopeTypeString(m_slopeType).c_str(), true); return true; } bool ossimSlopeFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimImageSourceFilter::loadState(kwl, prefix); ossimString lookup = kwl.find(prefix, SLOPE_TYPE_KW); if (!lookup.empty()) { ossimRefPtr prop = new ossimStringProperty(SLOPE_TYPE_KW, lookup, false); setProperty(prop); } return true; } ossimString ossimSlopeFilter::getSlopeTypeString(SlopeType t) { if (t == RADIANS) return "RADIANS"; if (t == DEGREES) return "DEGREES"; if (t == RATIO) return "RATIO"; if (t == NORMALIZED) return "NORMALIZED"; return ""; } ossimString ossimSlopeFilter::getLongName()const { return ossimString("Slope Filter, Computes the change in pixel value in x, Y direction as a " "slope quantity. Assumes that the input source represents elevation in meters."); } ossimString ossimSlopeFilter::getShortName()const { return ossimString("Slope Filter"); } ossim-Miami-2.9.1/src/imaging/ossimSrtmTileSource.cpp000066400000000000000000000112061352751253100226200ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Image handler class for a Shuttle Radar Topography Mission (SRTM) file. // //---------------------------------------------------------------------------- // $Id: ossimSrtmTileSource.cpp 22769 2014-05-08 19:35:04Z dburken $ #include #include #include #include #include #include #include RTTI_DEF1(ossimSrtmTileSource, "ossimSrtmTileSource", ossimGeneralRasterTileSource) static ossimTrace traceDebug("ossimSrtmTileSource:debug"); ossimSrtmTileSource::ossimSrtmTileSource() : ossimGeneralRasterTileSource(), m_SrtmSupportData() { } ossimSrtmTileSource::~ossimSrtmTileSource() { } bool ossimSrtmTileSource::open() { static const char MODULE[] = "ossimSrtmTileSource::open"; if (traceDebug()) { CLOG << " Entered..." << std::endl << "srtm " << theImageFile << std::endl; } if(isOpen()) { close(); } bool result = false; //--- // Set the scan for min max flag to true. This will only scan if not found // in a omd file so this is a one time hit typically taken when building // reduced res sets. //--- if ( m_SrtmSupportData.setFilename(theImageFile, true) ) { ossimKeywordlist kwl; m_SrtmSupportData.saveState(kwl); ossimGeneralRasterInfo generalRasterInfo; if ( generalRasterInfo.loadState(kwl) ) { theMetaData = generalRasterInfo.getImageMetaData(); result = ossimGeneralRasterTileSource::open(generalRasterInfo); } } else { if (traceDebug()) CLOG << " Unable to set filename"<< std::endl; return false; } if (traceDebug()) { CLOG << " Exited with " << (result?"true":"false") << " ..." << std::endl; } return result; } //************************************************************************************************ //! Returns the image geometry object associated with this tile source or NULL if non defined. //! The geometry contains full-to-local image transform as well as projection (image-to-world) //************************************************************************************************ ossimRefPtr ossimSrtmTileSource::getImageGeometry() { if(!theGeometry.valid()) { // First time through set the projection. theGeometry = new ossimImageGeometry(); theGeometry->setProjection( m_SrtmSupportData.getProjection().get() ); // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } return theGeometry; } bool ossimSrtmTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { if (m_SrtmSupportData.saveState(kwl, prefix)) { return ossimImageHandler::saveState(kwl,prefix); } return false; } bool ossimSrtmTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; std::string pfx = ""; if (prefix) // Cannot give null to std::string. { pfx = prefix; } std::string key = ossimKeywordNames::TYPE_KW; std::string value = kwl.findKey( pfx, key ); if ( value == "ossimSrtmTileSource" ) { key = ossimKeywordNames::FILENAME_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { // Set the file name: theImageFile = value; // Call ossimSrtmTileSource::open which will do the rest of the work. if ( open() ) { // Must call to pick up id for connections. result = ossimImageSource::loadState(kwl, prefix); } } } return result; } ossimRefPtr ossimSrtmTileSource::getProperty( const ossimString& name)const { if(name == "file_type") { return new ossimStringProperty(name, getShortName()); } return ossimImageHandler::getProperty(name); } void ossimSrtmTileSource::getPropertyNames( std::vector& propertyNames)const { ossimImageHandler::getPropertyNames(propertyNames); propertyNames.push_back("file_type"); } ossimString ossimSrtmTileSource::getShortName() const { return ossimString("SRTM"); } ossimString ossimSrtmTileSource::getLongName() const { return ossimString("SRTM reader"); } ossim-Miami-2.9.1/src/imaging/ossimSubImageTileSource.cpp000066400000000000000000000141011352751253100233640ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimSubImageTileSource.cc // // Copyright (C) 2001 ImageLinks, Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains implementation of class ossimSubImageTileSource. // This tile source permits specifying an offset that is to be applied to the // tile origin for all getTile() requests. It is intended for converting // a full-image space coordinate to a sub-image coordinate. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimSubImageTileSource.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include using namespace std; RTTI_DEF1(ossimSubImageTileSource, "ossimSubImageTileSource", ossimImageSourceFilter); static const char* SUBIMAGE_OFFSET_X = "offset_x"; static const char* SUBIMAGE_OFFSET_Y = "offset_y"; ossimSubImageTileSource::ossimSubImageTileSource() : ossimImageSourceFilter(), theSubImageOffset(0, 0), theTile(0) { } ossimSubImageTileSource::ossimSubImageTileSource(ossimImageSource* inputSource) : ossimImageSourceFilter(inputSource), theSubImageOffset(0, 0), theTile(0) { } ossimSubImageTileSource::ossimSubImageTileSource(ossimImageSource* inputSource, const ossimIpt& offset) : ossimImageSourceFilter(inputSource), theSubImageOffset(offset), theTile(0) { } ossimSubImageTileSource::~ossimSubImageTileSource() { } //***************************************************************************** // METHOD: ossimSubImageTileSource::getTile() // //***************************************************************************** ossimRefPtr ossimSubImageTileSource::getTile( const ossimIrect& rect, ossim_uint32 res_level) { ossimIpt offset = theSubImageOffset; if(res_level) { //*** // Determine the offset for the particular rr level requested: //*** ossimDpt decimation_factor; theInputConnection->getDecimationFactor(res_level, decimation_factor); if(!decimation_factor.hasNans()) { offset = ossimIpt((int)(theSubImageOffset.x*decimation_factor.x + 0.5), (int)(theSubImageOffset.y*decimation_factor.y + 0.5)); } else { offset = theSubImageOffset; } } // // Apply the offset to the requested rect and fetch tile. The tile's origin // needs to be adjusted to reflect the requested origin: // ossimIrect rect_prime (rect - offset); ossimRefPtr tile = ossimImageSourceFilter::getTile(rect_prime, res_level); if(theTile.valid()) { theTile->setImageRectangle(rect_prime); if(tile.valid()) { theTile->loadTile(tile.get()); } else { theTile->makeBlank(); } } else { if(tile.valid()) { theTile = (ossimImageData*)tile->dup(); } } if(theTile.valid()) { theTile->setOrigin(rect.ul()); theTile->validate(); } return theTile; } //***************************************************************************** // METHOD: ossimSubImageTileSource::getBoundingRect() // //***************************************************************************** ossimIrect ossimSubImageTileSource::getBoundingRect(ossim_uint32 resLevel) const { ossimDrect result; result.makeNan(); if(!theInputConnection) return result; ossimDpt offset = theSubImageOffset; ossimDrect rect (theInputConnection->getBoundingRect(resLevel)); if(resLevel) { ossimDpt decimation_factor; theInputConnection->getDecimationFactor(resLevel, decimation_factor); if(!decimation_factor.hasNans()) { rect*=decimation_factor; offset= ossimDpt(theSubImageOffset.x*decimation_factor.x, theSubImageOffset.y*decimation_factor.y); } } ossimDrect rect_prime (rect + offset); return rect_prime; } //***************************************************************************** // METHOD: ossimSubImageTileSource::getValidImageVertices() // //***************************************************************************** void ossimSubImageTileSource::getValidImageVertices(vector& vertices, ossimVertexOrdering ordering, ossim_uint32 /* resLevel */) const { if(!theInputConnection) { vertices.clear(); return; } ossimDpt offset (theSubImageOffset); theInputConnection->getValidImageVertices(vertices, ordering); vector::iterator vertex = vertices.begin(); while (vertex != vertices.end()) { (*vertex) += offset; vertex++; } return; } void ossimSubImageTileSource::initialize() { ossimImageSourceFilter::initialize(); theTile = NULL; } bool ossimSubImageTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* offset_x = kwl.find(prefix, SUBIMAGE_OFFSET_X); const char* offset_y = kwl.find(prefix, SUBIMAGE_OFFSET_Y); if(offset_x) { theSubImageOffset.x = ossimString(offset_x).toLong(); } if(offset_y) { theSubImageOffset.y = ossimString(offset_y).toLong(); } return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimSubImageTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimImageSourceFilter::saveState(kwl, prefix); kwl.add(prefix, SUBIMAGE_OFFSET_X, theSubImageOffset.x, true); kwl.add(prefix, SUBIMAGE_OFFSET_Y, theSubImageOffset.y, true); return result; } ossim-Miami-2.9.1/src/imaging/ossimTableRemapper.cpp000066400000000000000000000410001352751253100224120ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Table remapper class definition. // // Takes input tile, remaps it through a table, then output tile in the desired // scalar type. // // Two modes one that works on native remap tables, that being of the same // scalar type (like ossim_uint8) of the input connection, and another that // uses a normalized remap table (more scalar independent). // //************************************************************************* // $Id: ossimTableRemapper.cpp 22745 2014-04-22 16:57:22Z dburken $ #include #include #include #include #include using namespace std; RTTI_DEF1(ossimTableRemapper, "ossimTableRemapper", ossimImageSourceFilter) static ossimTrace traceDebug("ossimTableRemapper:debug"); static const char* TABLE_TYPE[] = { "UNKNOWN", "NATIVE", "NORMALIZED" }; ossimTableRemapper::ossimTableRemapper() : ossimImageSourceFilter(), // base class theTile(0), theTmpTile(0), theNormBuf(0), theTableBinCount(0), theTableBandCount(0), theTableType(ossimTableRemapper::UKNOWN), theInputScalarType(OSSIM_SCALAR_UNKNOWN), theOutputScalarType(OSSIM_SCALAR_UNKNOWN) { //*** // Set the base class "theEnableFlag" to off since no adjustments have been // made yet. //*** //disableSource(); } ossimTableRemapper::~ossimTableRemapper() { destroy(); } void ossimTableRemapper::destroy() { if (theNormBuf) { delete [] theNormBuf; theNormBuf = 0; } theTmpTile = 0; theTile = 0; } void ossimTableRemapper::initialize() { //--- // Call the base class initialize. // Note: This will reset "theInputConnection" if it changed... //--- ossimImageSourceFilter::initialize(); destroy(); if (theInputConnection) { theInputScalarType = theInputConnection->getOutputScalarType(); // Since we override "getOutputScalarType" make sure something's set. if (theOutputScalarType == OSSIM_SCALAR_UNKNOWN) { theOutputScalarType = theInputConnection->getOutputScalarType(); } if (theTile.valid()) { //if ( theTile->getNumberOfBands() != // theInputConnection->getNumberOfOutputBands() ) // { // Wipe everything slick. The next getTile will call allocate. // destroy(); // } } } // Nothing else to do for this... } void ossimTableRemapper::allocate(const ossimIrect& rect) { //--- // It's either first getTile or we've had either a resize, so allocate // needed stuff... //--- destroy(); if (theInputConnection) { ossim_uint32 width = rect.width(); ossim_uint32 height = rect.height(); theTile = ossimImageDataFactory::instance()->create(this,this); theTile->setImageRectangle(rect); // theTile = // ossimImageDataFactory::instance()->create(this, // getOutputScalarType(), // getNumberOfOutputBands(), // width,x // height); theTile->initialize(); if (theInputScalarType != getOutputScalarType() && theTableType == ossimTableRemapper::NATIVE) { //--- // We need a temp tile so we can do two remaps // inputTile->remapTable->tmpTile then // tmpTile->normalize->theTile(unnormalize to new scalar)... //--- theTmpTile = ossimImageDataFactory::instance()->create(this, theInputScalarType, getNumberOfOutputBands(), width, height); theTmpTile->setMinPix(theTile->getMinPix(), theTile->getNumberOfBands()); theTmpTile->initialize(); } if (theTableType == ossimTableRemapper::NORMALIZED || theInputScalarType != theOutputScalarType) { theNormBuf = new ossim_float64[theTile->getSize()]; } } } ossimRefPtr ossimTableRemapper::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { ossimRefPtr result = 0; if(theInputConnection) { // Fetch tile from pointer from the input source. result = theInputConnection->getTile(tile_rect, resLevel); if (theEnableFlag&&result.valid()) { // Get its status of the input tile. ossimDataObjectStatus tile_status = result->getDataObjectStatus(); // Check for remap bypass: if ( (tile_status != OSSIM_NULL) && (tile_status != OSSIM_EMPTY) && theTable.size() ) { // OK we have an input tile... and it's not null or empty. if(!theTile) { allocate(tile_rect); } if (theTile.valid()) { theTile->setImageRectangle(tile_rect); if(theTmpTile.valid()) // not mandatory for all modes. { theTmpTile->setImageRectangle(tile_rect); } // Think things are good. Do the real work... if (theTableType == ossimTableRemapper::NATIVE) { // Most efficient case... remapFromNativeTable(result); } else { remapFromNormalizedTable(result); } theTile->validate(); result = theTile; } } } } return result; } void ossimTableRemapper::remapFromNativeTable( ossimRefPtr& inputTile) { switch (theOutputScalarType) { case OSSIM_UINT8: { remapFromNativeTable(ossim_uint8(0), inputTile); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { remapFromNativeTable(ossim_uint16(0), inputTile); break; } case OSSIM_SSHORT16: { remapFromNativeTable(ossim_sint16(0), inputTile); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT: { remapFromNativeTable(ossim_float32(0), inputTile); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_DOUBLE: { remapFromNativeTable(ossim_float64(0), inputTile); break; } case OSSIM_SCALAR_UNKNOWN: default: { if(traceDebug()) { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimTableRemapper::remapFromNativeTable" << "\nOutput scalar type is OSSIM_SCALAR_UNKNOWN!\n"; } break; } } // End of "switch (theTableType)" } template void ossimTableRemapper::remapFromNativeTable( T /* dummy */, ossimRefPtr& inputTile) { const ossim_uint32 BANDS = theTile->getNumberOfBands(); const ossim_uint32 PPB = theTile->getSizePerBand(); // pixels per band //--- // NOTE: // If (theTableBandCount == one) that means we only have one band; or, // the user wanted to remap all bands using the same table... //--- const ossim_uint32 BAND_OFFSET = (theTableBandCount != 1) ? theTableBinCount: 0; const T* rt = reinterpret_cast(&theTable.front()); // remap table (rt) ossimRefPtr id; if (theInputScalarType == theOutputScalarType) { id = theTile; } else { id = theTmpTile; } if(theTable.size() >= (BANDS*BAND_OFFSET)) { for (ossim_uint32 band = 0; band < BANDS; ++band) { const T NULL_PIX = static_cast(id->getNullPix(band)); //const T MIN_PIX = static_cast(id->getMinPix(band)); const T* s = static_cast(inputTile->getBuf(band)); // source (s) T* d = static_cast(id->getBuf(band)); // destination (d) if(s&&d) { for (ossim_uint32 pixel = 0; pixel < PPB; ++pixel) { //--- // Get the source pixel and use it as an index to the table. // Note Null is always the "0" index, min always the "1". //--- T p = s[pixel]; if (p == NULL_PIX) // Null is not always zero (dted). { d[pixel] = NULL_PIX; // p = 0; } else { // else // { // p = (p+1-MIN_PIX); // If min == 1 we want that to map to index 1. // } ossim_uint32 table_index = static_cast(p); //--- // If within range use to index the remap table; else, null. // Note: // There is no min, max range checking on value retrieved from table. // Range checking should be performed when the table is built. //--- if(table_index < theTableBinCount) { d[pixel] = rt[table_index]; } // else if(table_index < 0) // { // if(theTableBinCount > 1) // { // d[pixel] = rt[1]; // } // else // { // d[pixel] = table_index; // } // } else { if(theTableBinCount>0) { d[pixel] = rt[theTableBinCount-1]; } else { d[pixel] = p; } } } } } rt += BAND_OFFSET; // Go to next band in the table. } } if (theInputScalarType != theOutputScalarType) { // Normalize and copy the temp tile to a buffer. id->copyTileToNormalizedBuffer(theNormBuf); // Un-normalize and copy the buffer to the destination tile. theTile->copyNormalizedBufferToTile(theNormBuf); } } void ossimTableRemapper::remapFromNormalizedTable( ossimRefPtr& inputTile) { if (!theNormBuf) // First time... { theNormBuf = new ossim_float64[theTile->getSize()]; } // Normalize and copy the source tile to a buffer. inputTile->copyTileToNormalizedBuffer(theNormBuf); const ossim_uint32 BANDS = theTile->getNumberOfBands(); const ossim_uint32 PPB = theTile->getSizePerBand(); // pixels per band //--- // NOTE: // If (theTableBandCount == one) that means we only have one band; or, // the user wanted to remap all bands using the same table... //--- const ossim_uint32 BAND_OFFSET = (theTableBandCount == 1) ? 0 : PPB; // remap table (rt) ossim_float64* rt = reinterpret_cast(&theTable.front()); ossim_float64* buf = theNormBuf; ossim_float64 p = 0.0; for (ossim_uint32 band = 0; band < BANDS; ++band) { for (ossim_uint32 pixel = 0; pixel < PPB; ++pixel) { // Get the source pixel... ossim_uint32 idx = static_cast(buf[pixel]*theTableBinCount+0.5); if((idx < theTableBinCount)) { // If within range use to index the remap table; else, null. p = (idx < theTableBinCount) ? rt[idx] : 0.0; } // else if(idx < 0) // { // p = 0.0; // } else { p = 1.0; } // Range check (in case table bad) and assign to destination pixel. buf[pixel] = (p >= 0.0) ? ( (p <=1.0) ? p : 1) : 0.0; } // (GP)this is not for th table so this offset appears wrong // commenting this out and replacing with t bin count // Go to next band. //rt += BAND_OFFSET; rt += theTableBinCount; buf += PPB; } // Un-normalize and copy the buffer to the destination tile. theTile->copyNormalizedBufferToTile(theNormBuf); } ossimScalarType ossimTableRemapper::getOutputScalarType() const { if (theOutputScalarType != OSSIM_SCALAR_UNKNOWN) { return theOutputScalarType; } return ossimImageSourceFilter::getOutputScalarType(); } bool ossimTableRemapper::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Look for scalar type keyword. ossim_int32 st = ossimScalarTypeLut::instance()-> getEntryNumber(kwl, prefix, true); // Lookup table returns -1 if not found so check return... if ( (st != -1) && (st != OSSIM_SCALAR_UNKNOWN) ) { theOutputScalarType = static_cast(st); } return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimTableRemapper::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Save the output scalar type. kwl.add(prefix, ossimKeywordNames::SCALAR_TYPE_KW, ossimScalarTypeLut::instance()-> getEntryString(theOutputScalarType).c_str(), true); return ossimImageSourceFilter::saveState(kwl, prefix); } ostream& ossimTableRemapper::print(ostream& os) const { ossimScalarTypeLut* sl = ossimScalarTypeLut::instance(); os << "\nossimTableRemapper::print:" << "\ntheTableBinCount: " << theTableBinCount << "\ntheTableBandCount: " << theTableBandCount << "\ntheTableType: " << TABLE_TYPE[theTableType] << "\ntheInputScalarType: " << (*sl)[theInputScalarType] << "\ntheOutputScalarType: " << (*sl)[theOutputScalarType] << endl; if (theTile.valid()) { os << "theTile:\n" << *theTile << endl; } if (theTmpTile.valid()) { os << "theTmpTile:\n" << *theTmpTile << endl; } switch (theOutputScalarType) { case OSSIM_UCHAR: { dumpTable(ossim_uint8(0), os); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { dumpTable(ossim_uint16(0), os); break; } case OSSIM_SSHORT16: { dumpTable(ossim_sint16(0), os); break; } case OSSIM_NORMALIZED_FLOAT: case OSSIM_FLOAT: { dumpTable(ossim_float32(0), os); break; } case OSSIM_NORMALIZED_DOUBLE: case OSSIM_DOUBLE: { dumpTable(ossim_float64(0), os); break; } case OSSIM_SCALAR_UNKNOWN: default: { if(traceDebug()) { // Shouldn't hit this. ossimNotify(ossimNotifyLevel_WARN) << "ossimTableRemapper::print OSSIM_SCALAR_UNKNOWN!\n"; } break; } } // End of "switch (theTableType)" return os; } template void ossimTableRemapper::dumpTable(T /*dummy*/, ostream& os) const { if (theTable.empty() || !theTableBinCount || !theTableBandCount) { return; } const T* table = reinterpret_cast(&theTable.front()); ossim_uint32 table_index = 0; for (ossim_uint32 band = 0; band < theTableBandCount; ++band) { for (ossim_uint32 index = 0; index < theTableBinCount; ++index) { os << "tabel[" << band << "][" << index << "]: " << static_cast(table[table_index]) << endl; ++table_index; } } } ostream& operator<<(ostream& os, const ossimTableRemapper& tr) { return tr.print(os); } // Private to disallow use... ossimTableRemapper::ossimTableRemapper(const ossimTableRemapper&) : theNormBuf(0), theTableBinCount(0), theTableBandCount(0), theTableType(UKNOWN), theInputScalarType(OSSIM_SCALAR_UNKNOWN), theOutputScalarType(OSSIM_SCALAR_UNKNOWN) { } // Private to disallow use... ossimTableRemapper& ossimTableRemapper::operator=(const ossimTableRemapper&) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimTiffOverviewBuilder.cpp000066400000000000000000001251211352751253100236240ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: // // Contains class definition for TiffOverviewBuilder // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* for std::fill */ #include using namespace std; RTTI_DEF1(ossimTiffOverviewBuilder, "ossimTiffOverviewBuilder", ossimOverviewBuilderBase) static ossimTrace traceDebug("ossimTiffOverviewBuilder:debug"); // Property keywords. static const char COPY_ALL_KW[] = "copy_all_flag"; static const char TEMP_EXTENSION[] = "temp_extension"; static const char INTERNAL_OVERVIEWS_KW[] = "internal_overviews_flag"; #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimTiffOverviewBuilder.cpp 22362 2013-08-07 20:23:22Z dburken $"; #endif //******************************************************************* // Public Constructor: //******************************************************************* ossimTiffOverviewBuilder::ossimTiffOverviewBuilder() : ossimOverviewBuilderBase(), m_nullDataBuffer(0), m_bytesPerPixel(1), m_bitsPerSample(8), m_tileWidth(0), m_tileHeight(0), m_tileSizeInBytes(0), m_sampleFormat(0), m_currentTiffDir(0), m_tiffCompressType(COMPRESSION_NONE), m_jpegCompressQuality(DEFAULT_COMPRESS_QUALITY), m_resampleType(ossimFilterResampler::ossimFilterResampler_BOX), m_nullPixelValues(), m_copyAllFlag(false), m_outputTileSizeSetFlag(false), m_internalOverviewsFlag(false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffOverviewBuilder::ossimTiffOverviewBuilder DEBUG:\n"; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << "\n"; #endif ossimNotify(ossimNotifyLevel_DEBUG) << "overview stop dimension: " << m_overviewStopDimension << std::endl; } } ossimTiffOverviewBuilder::~ossimTiffOverviewBuilder() { } void ossimTiffOverviewBuilder::setResampleType( ossimFilterResampler::ossimFilterResamplerType resampleType) { m_resampleType = resampleType; } bool ossimTiffOverviewBuilder::buildOverview(const ossimFilename& overview_file, bool copy_all) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffOverviewBuilder::buildOverview DEBUG:" << "\noverview file: " << overview_file.c_str() << "\ncopy_all flag: " << (copy_all?"true":"false") << std::endl; } m_outputFile = overview_file; m_copyAllFlag = copy_all; return execute(); } bool ossimTiffOverviewBuilder::execute() { static const char MODULE[] = "ossimTiffOverviewBuilder::execute"; if (theErrorStatus == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nError status has been previously set! Returning..." << std::endl; return false; } if ( !m_imageHandler || m_imageHandler->hasError() ) { setErrorStatus(); return false; } m_outputFile = getOutputFile(); if (m_outputFile == ossimFilename::NIL) { return false; } // Check the file. Disallow same file overview building. if ( !buildInternalOverviews() && (m_imageHandler->getFilename() == m_outputFile) ) { ossimNotify(ossimNotifyLevel_WARN) << "Source image file and overview file cannot be the same!" << std::endl; return false; } // RP - allow user to set extension with hidden option. Used to add unique suffix to prevent duplicate requests from stomping each other ossimFilename outputFileTemp; if ( !buildInternalOverviews() ) { outputFileTemp = m_outputFile; if ( m_tempExtension.size() ) { outputFileTemp += "." + m_tempExtension; } // Add .tmp in case process gets aborted to avoid leaving bad .ovr file. outputFileTemp += ".tmp"; } // Required number of levels needed including r0. ossim_uint32 requiedResLevels = getRequiredResLevels(m_imageHandler.get()); // Zero based starting resLevel. ossim_uint32 startingResLevel = 0; if ( !copyR0() ) { startingResLevel = m_imageHandler->getNumberOfDecimationLevels(); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "\nCurrent number of reduced res sets: " << m_imageHandler->getNumberOfDecimationLevels() << "\nNumber of required reduced res sets: " << requiedResLevels << "\nStarting reduced res set: " << startingResLevel << "\nResampling type: " << getOverviewType().c_str() << std::endl; } if ( startingResLevel >= requiedResLevels ) { ossimNotify(ossimNotifyLevel_INFO) << MODULE << " NOTICE:" << "\nImage has required reduced resolution data sets.\nReturning..." << std::endl; return true; } //--- // If image handler is band selector, start with all bands. // Some sources, e.g. ossimEnviTileSource can pick up default // bands and filter out all other bands. //--- m_imageHandler->setOutputToInputBandList(); //--- // If alpha bit mask generation was requested, then need to instantiate the mask writer object. // This is simply a "transparent" tile source placed after to the right of the image handler // that scans the pixels being pulled and accumulates alpha bit mask for writing at the end. //--- if (m_bitMaskSpec.getSize() > 0) { m_maskWriter = new ossimBitMaskWriter(); m_maskWriter->loadState(m_bitMaskSpec); m_maskWriter->setStartingResLevel(1); ossimRefPtr bmts = new ossimBitMaskTileSource; bmts->setAssociatedMaskWriter(m_maskWriter.get()); m_maskFilter = new ossimMaskFilter(); m_maskFilter->connectMyInputTo(m_imageHandler.get()); m_maskFilter->setMaskSource((ossimImageSource*)bmts.get()); } ossimStdOutProgress* progressListener = 0; // Only used on master. TIFF* tif = 0; // Only used on master. setProcessStatus(ossimProcessInterface::PROCESS_STATUS_EXECUTING); setPercentComplete(0.0); if (ossimMpi::instance()->getRank() == 0 ) { //--- // See if the file can be opened for writing. // Note: If this file existed previously it will be overwritten. //--- tif = openTiff(outputFileTemp); if (!tif) { // Set the error... setErrorStatus(); ossimNotify(ossimNotifyLevel_WARN) << __FILE__ << " " << __LINE__ << " " << MODULE << "\nCannot open file: " << outputFileTemp << std::endl; return false; } //--- // Check for a listeners. If the list is empty, add a standard out // listener so that command line apps like img2rr will get some progress. //--- ossimStdOutProgress* progressListener = 0; if (theListenerList.empty()) { progressListener = new ossimStdOutProgress(0, true); addListener(progressListener); } if (startingResLevel == 0) { if (!writeR0(tif)) { // Set the error... setErrorStatus(); ossimNotify(ossimNotifyLevel_WARN) << __FILE__ << " " << __LINE__ << "\nError copying image!" << std::endl; closeTiff(tif); if (progressListener) { removeListener(progressListener); delete progressListener; progressListener = 0; } if ( outputFileTemp.exists() && !buildInternalOverviews() ) { ossimFilename::remove( outputFileTemp ); } return false; } ++startingResLevel; // Go to r1. } if (needsAborting()) { closeTiff(tif); if (progressListener) { removeListener(progressListener); delete progressListener; progressListener = 0; } return false; } TIFFFlush(tif); } // End of master only write of r0. for (ossim_uint32 i = startingResLevel; i < requiedResLevels; ++i) { if (ossimMpi::instance()->getRank() == 0 ) { TIFFFlush(tif); } // Sync all processes... ossimMpi::instance()->barrier(); ossimRefPtr ih = 0; //--- // If we copied r0 to the overview file use it instead of the // original image handler as it is probably faster. //--- if ( !copyR0() && (i <= m_imageHandler->getNumberOfDecimationLevels()) ) { ih = m_imageHandler; } else { // We know we're a tiff so don't use the factory. ih = new ossimTiffTileSource; if ( ih->open(outputFileTemp) == false ) { ih = 0; // Set the error... setErrorStatus(); ossimNotify(ossimNotifyLevel_WARN) << __FILE__ << " " << __LINE__ << " " << MODULE << "\nCannot open file: " << outputFileTemp << std::endl; return false; } //--- // Since the overview file is being opened here, need to set its handler's starting res // level where the original image file left off. This is usually R1 since the original // file only has R0, but the original file may have more than R0: //--- if ( !copyR0() && !buildInternalOverviews() ) { ih->setStartingResLevel( m_imageHandler->getNumberOfDecimationLevels()); } } // If mask is to be generated, need to notify both the writer and the reader of new // input source: if (m_bitMaskSpec.getSize() > 0) { m_maskFilter->connectMyInputTo(0, ih.get()); m_maskWriter->connectMyInputTo(ih.get()); } if ( !writeRn( ih.get(), tif, i, (i==startingResLevel) && !copyR0() ) ) { // Set the error... setErrorStatus(); ossimNotify(ossimNotifyLevel_WARN) << __FILE__ << " " << __LINE__ << " " << MODULE << "\nError creating reduced res set: " << i << std::endl; ih->disconnect(); ih = 0; if (tif) { closeTiff(tif); tif = 0; } if (progressListener) { removeListener(progressListener); delete progressListener; progressListener = 0; } if ( outputFileTemp.exists() && !buildInternalOverviews() ) { ossimFilename::remove( outputFileTemp ); } return false; } if (needsAborting()) { ih->disconnect(); ih = 0; if (tif) { closeTiff(tif); tif = 0; } if (progressListener) { removeListener(progressListener); delete progressListener; progressListener = 0; } return false; } if (m_bitMaskSpec.getSize() > 0) { m_maskFilter->disconnectMyInput(0); m_maskWriter->disconnectAllInputs(); } ih = 0; } if (ossimMpi::instance()->getRank() == 0 ) { if (tif) { closeTiff(tif); tif = 0; } // Write out the alpha bit mask if one was enabled: if (m_maskWriter.valid()) { ossimNotify(ossimNotifyLevel_INFO) << "Writing alpha bit mask file..." << std::endl; m_maskWriter->close(); } // Remove the listener if we had one. if (progressListener) { removeListener(progressListener); delete progressListener; progressListener = 0; } if ( !buildInternalOverviews() ) { outputFileTemp.rename(m_outputFile); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_INFO) << "Wrote file: " << m_outputFile.c_str() << std::endl; } setCurrentMessage(ossimString("Finished...")); } finalize(); // Reset band list if a band selector. return true; } bool ossimTiffOverviewBuilder::writeR0(TIFF* tif) { static const char MODULE[] = "ossimTiffOverviewBuilder::writeR0"; ossimIrect rect = m_imageHandler->getImageRectangle(); if (!setTags(tif, rect, 0)) { closeTiff(tif); ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error writing tags!" << std::endl; return false; } // Set the geotiff tags. if ( setGeotiffTags(m_imageHandler->getImageGeometry().get(), m_imageHandler->getBoundingRect(), 0, tif) == false ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_NOTICE) << MODULE << " NOTICE: geotiff tags not set." << std::endl; } } ossim_int32 samples = m_imageHandler->getNumberOfSamples(); ossim_int32 lines = m_imageHandler->getNumberOfLines(); ossim_int32 tilesWide = samples % m_tileWidth ? samples / m_tileWidth + 1 : samples / m_tileWidth; ossim_int32 tilesHigh = lines % m_tileHeight ? lines / m_tileHeight + 1 : lines / m_tileHeight; ossim_int32 numberOfTiles = tilesWide * tilesHigh; int tileNumber = 0; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffOverviewBuilder::writeR0 DEBUG:" << "\nsamples: " << samples << "\nlines: " << lines << "\ntilesWide: " << tilesWide << "\ntilesHigh: " << tilesHigh << "\nnumberOfTiles: " << numberOfTiles << std::endl; } setCurrentMessage(ossimString("Copying r0...")); //*** // Tile loop in the line direction. //*** for(int i = 0; i < tilesHigh; ++i) { ossimIpt origin(0, 0); origin.y = i * m_tileHeight; //*** // Tile loop in the sample (width) direction. //*** for(int j = 0; (j < tilesWide)&&(!needsAborting()); ++j) { origin.x = j * m_tileWidth; ossimRefPtr t = m_imageHandler->getTile(ossimIrect(origin.x, origin.y, origin.x +(m_tileWidth-1), origin.y +(m_tileHeight-1))); // Check for errors reading tile: if ( m_imageHandler->hasError() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR: reading tile: " << i << std::endl; return false; } // If masking was enabled, pass the tile onto that object for processing: if (m_maskWriter.valid()) m_maskWriter->generateMask(t, 0); //*** // Band loop. //*** for (uint32 band=0; (band < m_imageHandler->getNumberOfOutputBands())&&!needsAborting(); ++band) { tdata_t data; if ( t.valid() && (t->getDataObjectStatus() != OSSIM_NULL) ) { // Grab a pointer to the tile for the band. data = static_cast(t->getBuf(band)); } else { data = static_cast(&(m_nullDataBuffer.front())); } // Write the tile. int bytesWritten = 0; bytesWritten = TIFFWriteTile(tif, data, origin.x, origin.y, 0, // z band); // sample if (bytesWritten != m_tileSizeInBytes) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "Error returned writing tiff tile: " << i << "\nExpected bytes written: " << m_tileSizeInBytes << "\nBytes written: " << bytesWritten << std::endl; theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return false; } } // End of band loop. ++tileNumber; } // End of tile loop in the sample (width) direction. if (needsAborting()) { setPercentComplete(100.0); break; } else { double tile = tileNumber; double numTiles = numberOfTiles; setPercentComplete(tile / numTiles * 100.0); } } // End of tile loop in the line (height) direction. //*** // Write the current dirctory. //*** if (!TIFFWriteDirectory(tif)) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error writing directory!" << std::endl; return false; } ++m_currentTiffDir; return true; } bool ossimTiffOverviewBuilder::writeRn( ossimImageHandler* imageHandler, TIFF* tif, ossim_uint32 resLevel, bool firstResLevel ) { if ( ossimMpi::instance()->getRank() == 0 ) { if ( tif ) // && buildInternalOverviews() ) { // Create an empty directory to start with. TIFFCreateDirectory( tif ); } else { return false; } } //--- // Set up the sequencer. This will be one of three depending on if we're // running mpi and if we are a master process or a slave process. //--- ossimRefPtr sequencer; if(ossimMpi::instance()->getNumberOfProcessors() > 1) { if ( ossimMpi::instance()->getRank() == 0 ) { sequencer = new ossimMpiMasterOverviewSequencer(); } else { sequencer = new ossimMpiSlaveOverviewSequencer(); } } else { sequencer = new ossimOverviewSequencer(); } sequencer->setImageHandler(imageHandler); if (m_maskWriter.valid() && m_maskFilter.valid()) { sequencer->setBitMaskObjects(m_maskWriter.get(), m_maskFilter.get()); } // sourceResLevel: This is the res level to pull data from: ossim_uint32 sourceResLevel = imageHandler->getNumberOfDecimationLevels() + imageHandler->getStartingResLevel() - 1; sequencer->setSourceLevel(sourceResLevel); sequencer->setResampleType(m_resampleType); sequencer->setTileSize( ossimIpt(m_tileWidth, m_tileHeight) ); if ( firstResLevel ) { // Set up things that are only performed on first scan through tiles. if ( getHistogramMode() != OSSIM_HISTO_MODE_UNKNOWN ) { // Accumulate a histogram. Can't do with mpi/multi-process. if(ossimMpi::instance()->getNumberOfProcessors() == 1) { sequencer->setHistogramMode(getHistogramMode()); } //--- // else{} Not sure if we want an error thrown here. For now will handle at the // application level. //--- } if ( getScanForMinMaxNull() == true ) { sequencer->setScanForMinMaxNull(true); } else if ( getScanForMinMax() == true ) { sequencer->setScanForMinMax(true); } } // Note sequence setup must be performed before intialize. sequencer->initialize(); // If we are a slave process start the resampling of tiles. if (ossimMpi::instance()->getRank() != 0 ) { sequencer->slaveProcessTiles(); return true; } //--- // The rest of the method on master node only. //--- static const char MODULE[] = "ossimTiffOverviewBuilder::writeRn"; ostringstream os; os << "creating r" << resLevel << "..."; setCurrentMessage(os.str()); if (resLevel == 0) { return false; } ossimIrect rect; sequencer->getOutputImageRectangle(rect); if (!setTags(tif, rect, resLevel)) { setErrorStatus(); closeTiff(tif); tif = 0; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error writing tags!" << std::endl; return false; } if ( !buildInternalOverviews() && !copyR0() && (resLevel == 1) ) { //--- // Set the geotif tags for the first layer. // Note this is done in writeR0 method if m_copyAllFlag is set. //--- if ( setGeotiffTags(m_imageHandler->getImageGeometry().get(), ossimDrect(rect), resLevel, tif) == false ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_NOTICE) << MODULE << " NOTICE: geotiff tags not set." << std::endl; } } } ossim_uint32 outputTilesWide = sequencer->getNumberOfTilesHorizontal(); ossim_uint32 outputTilesHigh = sequencer->getNumberOfTilesVertical(); ossim_uint32 numberOfTiles = sequencer->getNumberOfTiles(); ossim_uint32 tileNumber = 0; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffOverviewBuilder::writeRn DEBUG:" << "\noutputTilesWide: " << outputTilesWide << "\noutputTilesHigh: " << outputTilesHigh << "\nnumberOfTiles: " << numberOfTiles << std::endl; } // Tile loop in the line direction. ossim_uint32 y = 0; for(ossim_uint32 i = 0; i < outputTilesHigh; ++i) { // Tile loop in the sample (width) direction. ossim_uint32 x = 0; for(ossim_uint32 j = 0; (j < outputTilesWide)&&!needsAborting(); ++j) { // Grab the resampled tile. ossimRefPtr t = sequencer->getNextTile(); // Check for errors reading tile: if ( sequencer->hasError() ) { setErrorStatus(); ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR: reading tile: " << i << std::endl; return false; } if ( t.valid() && ( t->getDataObjectStatus() != OSSIM_NULL ) ) { // Write it to the tiff. for (ossim_uint32 band = 0; (band < t->getNumberOfBands())&&!needsAborting(); ++band) { // Write the tile. int bytesWritten = 0; bytesWritten = TIFFWriteTile(tif, t->getBuf(band), x, y, 0, // z band); // sample if (bytesWritten != m_tileSizeInBytes) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "Error returned writing tiff tile: " << i << "\nExpected bytes written: " << m_tileSizeInBytes << "\nBytes written: " << bytesWritten << std::endl; theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return false; } } } x += m_tileWidth; // Increment x for next TIFFWriteTile. ++tileNumber; // Increment tile number for percent complete. } // End of tile loop in the sample (width) direction. if (needsAborting()) { setPercentComplete(100.0); break; } else { double tile = tileNumber; double numTiles = numberOfTiles; setPercentComplete(tile / numTiles * 100.0); } y += m_tileHeight; // Increment y for next TIFFWriteTile. } // End of tile loop in the line (height) direction. //--- // Write the current dirctory. //--- if (!TIFFFlush(tif)) { setErrorStatus(); ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error writing to TIF file!" << std::endl; return false; } if ( firstResLevel ) { if ( ossimMpi::instance()->getNumberOfProcessors() == 1 ) { if ( getHistogramMode() != OSSIM_HISTO_MODE_UNKNOWN ) { // Write the histogram. ossimFilename histoFilename = getOutputFile(); histoFilename.setExtension("his"); sequencer->writeHistogram(histoFilename); } if ( ( getScanForMinMaxNull() == true ) || ( getScanForMinMax() == true ) ) { // Write the omd file: ossimFilename file = getOutputFile(); file = file.setExtension("omd"); sequencer->writeOmdFile(file); } } } ++m_currentTiffDir; return true; } //******************************************************************* // Private Method: //******************************************************************* bool ossimTiffOverviewBuilder::setTags(TIFF* tif, const ossimIrect& outputRect, ossim_int32 resLevel) const { if (outputRect.hasNans()) { return false; } ossim_int32 imageWidth = outputRect.width(); ossim_int32 imageHeight = outputRect.height(); int16 samplesPerPixel = m_imageHandler->getNumberOfOutputBands(); ossim_float64 minSampleValue = m_imageHandler->getMinPixelValue(); ossim_float64 maxSampleValue = m_imageHandler->getMaxPixelValue(); if (resLevel) { TIFFSetField( tif, TIFFTAG_SUBFILETYPE, FILETYPE_REDUCEDIMAGE ); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffOverviewBuilder::setTags DEBUG:" << "\nrrds_level: " << resLevel << "\nimageWidth: " << imageWidth << "\nimageHeight: " << imageHeight << "\nminSampleValue: " << minSampleValue << "\nmaxSampleValue: " << maxSampleValue << "\ncompression: " << m_tiffCompressType << std::endl; } TIFFSetField( tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_SEPARATE ); TIFFSetField( tif, TIFFTAG_IMAGEWIDTH, imageWidth); TIFFSetField( tif, TIFFTAG_IMAGELENGTH, imageHeight); TIFFSetField( tif, TIFFTAG_BITSPERSAMPLE, m_bitsPerSample ); TIFFSetField( tif, TIFFTAG_SAMPLEFORMAT, m_sampleFormat ); TIFFSetField( tif, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel ); if( m_imageHandler->getNumberOfInputBands() == 3 ) TIFFSetField( tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB ); else TIFFSetField( tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK ); TIFFSetField( tif, TIFFTAG_TILEWIDTH, m_tileWidth ); TIFFSetField( tif, TIFFTAG_TILELENGTH, m_tileHeight ); // Set the compression related tags... if (m_tiffCompressType != COMPRESSION_JPEG) { TIFFSetField( tif, TIFFTAG_COMPRESSION, m_tiffCompressType ); } //--- // If jpeg only turn on compression for 8 bit, one or three band data. Not // sure what compression types can handle what but this was crashing // ossim-prepoc on a directory walk with jpeg compression. //--- else if ( (m_tiffCompressType == COMPRESSION_JPEG) && ( m_imageHandler->getOutputScalarType() == OSSIM_UINT8 ) && ( ( m_imageHandler->getNumberOfInputBands() == 3 ) || ( m_imageHandler->getNumberOfInputBands() == 1 ) ) ) { TIFFSetField( tif, TIFFTAG_COMPRESSION, m_tiffCompressType ); TIFFSetField( tif, TIFFTAG_JPEGQUALITY, m_jpegCompressQuality); } else { if ( traceDebug() && (m_tiffCompressType != COMPRESSION_NONE ) ) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffOverviewBuilder::setTags WARNING:\n" << "Compression not set for this data type:\n" << "scalar type: " << ossimScalarTypeLut::instance()->getEntryString( m_imageHandler->getOutputScalarType()) << "\nband count: " << m_imageHandler->getNumberOfInputBands() << std::endl; } TIFFSetField( tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE ); } // Set the min/max values. switch( m_imageHandler->getOutputScalarType() ) { case OSSIM_SINT16: case OSSIM_FLOAT32: case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: TIFFSetField( tif, TIFFTAG_SMINSAMPLEVALUE, minSampleValue ); TIFFSetField( tif, TIFFTAG_SMAXSAMPLEVALUE, maxSampleValue ); break; case OSSIM_UINT8: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: case OSSIM_UINT32: default: TIFFSetField( tif, TIFFTAG_MINSAMPLEVALUE, static_cast(minSampleValue) ); TIFFSetField( tif, TIFFTAG_MAXSAMPLEVALUE, static_cast(maxSampleValue) ); break; } return true; } bool ossimTiffOverviewBuilder::setGeotiffTags(const ossimImageGeometry* geom, const ossimDrect& boundingRect, ossim_uint32 resLevel, TIFF* tif) { bool result = false; if ( geom && tif ) { const ossimProjection* proj = geom->getProjection(); if (proj) { // Must duplicate if changing scale. ossimObject* obj = proj->dup(); ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, obj); if ( mapProj ) { if (resLevel) { ossim_float64 factor = (ossim_float64)(1 << resLevel); mapProj->applyScale(ossimDpt(factor, factor), true); } ossimRefPtr projInfo = new ossimMapProjectionInfo(mapProj, boundingRect); result = ossimGeoTiff::writeTags(tif, projInfo); } delete obj; // Cleanup from dup. obj = 0; } } return result; } TIFF* ossimTiffOverviewBuilder::openTiff(const ossimString& filename) const { ossimString openMode; if ( !buildInternalOverviews() ) { openMode = "w"; ossim_uint64 fourGigs = (static_cast(1024)* static_cast(1024)* static_cast(1024)* static_cast(4)); ossimIrect bounds = m_imageHandler->getBoundingRect(); ossim_uint64 byteCheck = (static_cast(bounds.width())* static_cast(bounds.height())* static_cast(m_imageHandler->getNumberOfOutputBands())* static_cast(ossim::scalarSizeInBytes(m_imageHandler-> getOutputScalarType()))); if((byteCheck*static_cast(2))>fourGigs) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << " Big tiff activated\n"; } openMode += "8"; } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << " No big tiff activated\n"; } } } else { openMode = "r+"; // Append to existing file... } // Open: return XTIFFOpen( filename.c_str(), openMode.c_str() ); } void ossimTiffOverviewBuilder::closeTiff(TIFF* tif) { XTIFFClose( tif ); } void ossimTiffOverviewBuilder::setCompressionType(ossim_uint16 compression_type) { switch (compression_type) { case COMPRESSION_JPEG: case COMPRESSION_LZW: case COMPRESSION_DEFLATE: case COMPRESSION_PACKBITS: m_tiffCompressType = compression_type; break; default: m_tiffCompressType = COMPRESSION_NONE; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << __FILE__ << " " << __LINE__ << "\nossimTiffOverviewBuilder::setCompressionType Unsupported compression type: " << compression_type << "\nDefaulting to none." << std::endl; } break; } } void ossimTiffOverviewBuilder::setJpegCompressionQuality(ossim_int32 quality) { if (quality > 1 && quality < 101) { m_jpegCompressQuality = quality; } else { m_jpegCompressQuality = DEFAULT_COMPRESS_QUALITY; ossimNotify(ossimNotifyLevel_WARN) << "ossimTiffOverviewBuilder::setJpegCompressionQuality\n" << "\nCompression quality of " << quality << " is out of range!" << "\nRange is 100 to 1. Current quality set to default of 75." << std::endl; } } bool ossimTiffOverviewBuilder::getCopyAllFlag() const { return m_copyAllFlag; } void ossimTiffOverviewBuilder::setCopyAllFlag(bool flag) { m_copyAllFlag = flag; } void ossimTiffOverviewBuilder::setInternalOverviewsFlag( bool flag ) { m_internalOverviewsFlag = flag; } bool ossimTiffOverviewBuilder::getInternalOverviewsFlag() const { return m_internalOverviewsFlag; } ossimObject* ossimTiffOverviewBuilder::getObject() { return this; } const ossimObject* ossimTiffOverviewBuilder::getObject() const { return this; } void ossimTiffOverviewBuilder::setOutputFile(const ossimFilename& file) { m_outputFile = file; } ossimFilename ossimTiffOverviewBuilder::getOutputFile() const { ossimFilename result; if ( buildInternalOverviews() ) { // m_imageHandler pointer good if buildInternalOverviews() returns true. result = m_imageHandler->getFilename(); } else { result = m_outputFile; } if (m_outputFile == ossimFilename::NIL) { if ( m_imageHandler.valid() ) { bool usePrefix = (m_imageHandler->getNumberOfEntries()>1?true:false); result = m_imageHandler-> getFilenameWithThisExtension(ossimString("ovr"), usePrefix); } } return result; } void ossimTiffOverviewBuilder::setOutputTileSize(const ossimIpt& tileSize) { m_tileWidth = tileSize.x; m_tileHeight = tileSize.y; m_outputTileSizeSetFlag = true; } bool ossimTiffOverviewBuilder::setInputSource(ossimImageHandler* imageSource) { static const char MODULE[] = "ossimTiffOverviewBuilder::initializeFromHandler"; bool result = ossimOverviewBuilderBase::setInputSource( imageSource ); if ( result ) { if(!m_outputTileSizeSetFlag) { ossimIpt tileSize; ossim::defaultTileSize(tileSize); m_tileWidth = tileSize.x; m_tileHeight = tileSize.y; } if (traceDebug()) { CLOG << "DEBUG:" << "\nm_tileWidth: " << m_tileWidth << "\nm_tileHeight: " << m_tileHeight << "\nSource image is tiled: " << (m_imageHandler->isImageTiled()?"true":"false") << "\nm_imageHandler->getTileWidth(): " << m_imageHandler->getTileWidth() << "\nm_imageHandler->getTileHeight(): " << m_imageHandler->getTileHeight() << "\nm_imageHandler->getImageTileWidth(): " << m_imageHandler->getImageTileWidth() << "\nm_imageHandler->getImageTileHeight(): " << m_imageHandler->getImageTileHeight() << std::endl; } switch(m_imageHandler->getOutputScalarType()) { case OSSIM_UINT8: m_bitsPerSample = 8; m_bytesPerPixel = 1; m_sampleFormat = SAMPLEFORMAT_UINT; break; case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: m_bitsPerSample = 16; m_bytesPerPixel = 2; m_sampleFormat = SAMPLEFORMAT_UINT; break; case OSSIM_SINT16: m_bitsPerSample = 16; m_bytesPerPixel = 2; m_sampleFormat = SAMPLEFORMAT_INT; break; case OSSIM_SINT32: m_bitsPerSample = 32; m_bytesPerPixel = 4; m_sampleFormat = SAMPLEFORMAT_INT; break; case OSSIM_UINT32: m_bitsPerSample = 32; m_bytesPerPixel = 4; m_sampleFormat = SAMPLEFORMAT_UINT; break; case OSSIM_FLOAT32: m_bitsPerSample = 32; m_bytesPerPixel = 4; m_sampleFormat = SAMPLEFORMAT_IEEEFP; break; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: m_bitsPerSample = 64; m_bytesPerPixel = 8; m_sampleFormat = SAMPLEFORMAT_IEEEFP; break; default: // Set the error... setErrorStatus(); ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nUnknown pixel type: " << (ossimScalarTypeLut::instance()-> getEntryString(m_imageHandler->getOutputScalarType())) << std::endl; result = false; } if ( result ) { m_tileSizeInBytes = m_tileWidth * m_tileHeight * m_bytesPerPixel; //--- // Make a buffer to pass to pass to the write tile methods when an image // handler returns a null tile. //--- m_nullDataBuffer.resize(m_tileSizeInBytes); // Fill it with zeroes. std::fill(m_nullDataBuffer.begin(), m_nullDataBuffer.end(), 0); } } else { // Set the error... setErrorStatus(); ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "\nSetting image handler as input failed!" << std::endl; } return result; } // End: ossimTiffOverviewBuilder::setInputSource(ossimImageHandler* imageSource) bool ossimTiffOverviewBuilder::setOverviewType(const ossimString& type) { bool result = true; if (type == "ossim_tiff_nearest") { m_resampleType = ossimFilterResampler::ossimFilterResampler_NEAREST_NEIGHBOR; } else if (type == "ossim_tiff_box") { m_resampleType = ossimFilterResampler::ossimFilterResampler_BOX; } else { result = false; } return result; } ossimString ossimTiffOverviewBuilder::getOverviewType() const { ossimString type; if (m_resampleType == ossimFilterResampler::ossimFilterResampler_NEAREST_NEIGHBOR) { type = "ossim_tiff_nearest"; } else { type = "ossim_tiff_box"; // This is default... } return type; } void ossimTiffOverviewBuilder::getTypeNameList( std::vector& typeList)const { typeList.push_back(ossimString("ossim_tiff_box")); typeList.push_back(ossimString("ossim_tiff_nearest")); } void ossimTiffOverviewBuilder::setProperty(ossimRefPtr property) { if ( property.valid() ) { if(property->getName() == ossimKeywordNames::COMPRESSION_QUALITY_KW) { m_jpegCompressQuality = property->valueToString().toInt32(); } else if(property->getName() == ossimKeywordNames::COMPRESSION_TYPE_KW) { ossimString value = property->valueToString(); value = value.downcase(); if(value == "jpeg") { m_tiffCompressType = COMPRESSION_JPEG; } else if(value == "lzw") { m_tiffCompressType = COMPRESSION_LZW; } else if(value == "deflate") { m_tiffCompressType = COMPRESSION_DEFLATE; } else if(value == "packbits") { m_tiffCompressType = COMPRESSION_PACKBITS; } else { m_tiffCompressType = COMPRESSION_NONE; } } else if(property->getName() == COPY_ALL_KW) { m_copyAllFlag = property->valueToString().toBool(); } else if(property->getName() == TEMP_EXTENSION) { m_tempExtension = property->valueToString(); } else if( property->getName() == INTERNAL_OVERVIEWS_KW ) { m_internalOverviewsFlag = property->valueToString().toBool(); } else if(property->getName() == ossimKeywordNames::OVERVIEW_STOP_DIMENSION_KW) { m_overviewStopDimension = property->valueToString().toUInt32(); } else if(property->getName() == ossimKeywordNames::OUTPUT_TILE_SIZE_KW) { ossimIpt ipt; ipt.toPoint(property->valueToString()); setOutputTileSize(ipt); } } } void ossimTiffOverviewBuilder::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back(ossimKeywordNames::COMPRESSION_QUALITY_KW); propertyNames.push_back(ossimKeywordNames::COMPRESSION_TYPE_KW); propertyNames.push_back(COPY_ALL_KW); propertyNames.push_back(INTERNAL_OVERVIEWS_KW); propertyNames.push_back(ossimKeywordNames::OVERVIEW_STOP_DIMENSION_KW); propertyNames.push_back(TEMP_EXTENSION); } bool ossimTiffOverviewBuilder::canConnectMyInputTo( ossim_int32 index, const ossimConnectableObject* obj) const { if ( (index == 0) && PTR_CAST(ossimImageHandler, obj) ) { return true; } return false; } bool ossimTiffOverviewBuilder::buildInternalOverviews() const { bool result = false; if ( m_internalOverviewsFlag && m_imageHandler.valid() ) { if ( m_imageHandler->getClassName() == "ossimTiffTileSource" ) { result = true; } else { ossimNotify(ossimNotifyLevel_NOTICE) << "Internal overviews opton not supported for class: " << m_imageHandler->getClassName() << std::endl; } } return result; } bool ossimTiffOverviewBuilder::copyR0() const { return ( m_copyAllFlag && !buildInternalOverviews()); } ossim-Miami-2.9.1/src/imaging/ossimTiffTileSource.cpp000066400000000000000000002470321352751253100225730ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // Frank Warmerdam (warmerdam@pobox.com) // // Description: // // Contains class definition for TiffTileSource. // //******************************************************************* // $Id: ossimTiffTileSource.cpp 23548 2015-09-28 21:01:36Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include /* for ossimIOMemoryStream */ #include #include #include #include #include #include #include #include #include #include /* for abs(int) */ #include #include using namespace std; RTTI_DEF1(ossimTiffTileSource, "ossimTiffTileSource", ossimImageHandler) static ossimTrace traceDebug("ossimTiffTileSource:debug"); #define OSSIM_TIFF_UNPACK_R4(value) ((value)&0x000000FF) #define OSSIM_TIFF_UNPACK_G4(value) (((value) >> 8) & 0x000000FF) #define OSSIM_TIFF_UNPACK_B4(value) (((value) >> 16) & 0x000000FF) #define OSSIM_TIFF_UNPACK_A4(value) (((value) >> 24) & 0x000000FF) //--- // OSSIM_BUFFER_SCAN_LINE_READS: // If set to 1 ossimTiffTileSource::loadFromScanLine method will buffer image // width by tile height. If set to 0 one line will be read at a time which // conserves memory on wide images or tall tiles. // // Buffered read is faster but uses more memory. Non-buffered slower less // memory. // // Only affects reading strip tiffs. //--- #define OSSIM_BUFFER_SCAN_LINE_READS 1 //******************************************************************* // Public Constructor: //******************************************************************* ossimTiffTileSource::ossimTiffTileSource() : ossimImageHandler(), theTiffPtr(0), theTile(0), theBuffer(0), theBufferSize(0), theBufferRect(0, 0, 0, 0), theBufferRLevel(0), theSamplesPerPixel(0), theBitsPerSample(0), theSampleFormatUnit(0), theMaxSampleValue(ossim::nan()), theMinSampleValue(ossim::nan()), theNullSampleValue(ossim::nan()), theNumberOfDirectories(0), theCurrentDirectory(0), theR0isFullRes(false), theBytesPerPixel(0), theScalarType(OSSIM_SCALAR_UNKNOWN), theApplyColorPaletteFlag(true), theImageWidth(0), theImageLength(0), theReadMethod(0), thePlanarConfig(0), thePhotometric(0), theRowsPerStrip(0), theImageDirectoryList(0), theCurrentTiffRlevel(0), theCompressionType(0), theOutputBandList(0) { } ossimTiffTileSource::~ossimTiffTileSource() { close(); } ossimRefPtr ossimTiffTileSource::getTile( const ossimIrect &tile_rect, ossim_uint32 resLevel) { if (theTile.valid() == false) { allocateTile(); // First time through... } if (theTile.valid()) { // Image rectangle must be set prior to calling getTile. theTile->setImageRectangle(tile_rect); if (getTile(theTile.get(), resLevel) == false) { if (theTile->getDataObjectStatus() != OSSIM_NULL) { theTile->makeBlank(); } } } return theTile; } bool ossimTiffTileSource::getTile(ossimImageData *result, ossim_uint32 resLevel) { static const char MODULE[] = "ossimTiffTileSource::getTile(ossimImageData*, resLevel)"; bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if (isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands())) { result->ref(); // Increment ref count. //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0. Method returns true on success, false // on error. //--- status = getOverviewTile(resLevel, result); if (!status) // Did not get an overview tile. { status = true; ossim_uint32 level = resLevel; //--- // If we have r0 our reslevels are the same as the callers so // no adjustment necessary. //--- if (theStartingResLevel && !theR0isFullRes) // Used as overview. { //--- // If we have r0 our reslevels are the same as the callers so // no adjustment necessary. //--- if (level >= theStartingResLevel) { //--- // Adjust the level to be relative to the reader using this // as overview. //--- level -= theStartingResLevel; } } ossimIrect tile_rect = result->getImageRectangle(); //--- // This should be the zero base image rectangle for this res level. // Note passed the non adjusted resLevel by design. //--- ossimIrect image_rect = getImageRectangle(resLevel); // See if any point of the requested tile is in the image. if (tile_rect.intersects(image_rect)) { // Initialize the tile if needed as we're going to stuff it. if (result->getDataObjectStatus() == OSSIM_NULL) { result->initialize(); } bool reallocateBuffer = false; if ((tile_rect.width() != (ossim_uint32)theOutputTileSize.x) || (tile_rect.height() != (ossim_uint32)theOutputTileSize.y)) { // Current tile size must be set prior to allocatBuffer call. theOutputTileSize.x = tile_rect.width(); theOutputTileSize.y = tile_rect.height(); reallocateBuffer = true; } if (getCurrentTiffRLevel() != theImageDirectoryList[level]) { status = setTiffDirectory(theImageDirectoryList[level]); if (status) { reallocateBuffer = true; } } if (status) { if (reallocateBuffer) { // NOTE: Using this buffer will be a thread issue. (drb) status = allocateBuffer(); } } if (status) { ossimIrect clip_rect = tile_rect.clipToRect(image_rect); if (!tile_rect.completely_within(clip_rect)) { //--- // We're not going to fill the whole tile so start with a // blank tile. //--- result->makeBlank(); } // Load the tile buffer with data from the tif. if (loadTile(tile_rect, clip_rect, result)) { result->validate(); status = true; } else { // Would like to change this to throw ossimException.(drb) status = false; if (traceDebug()) { // Error in filling buffer. ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error filling buffer. Return status = false..." << std::endl; } } } // matches: if (status) } // matches: if ( zeroBasedTileRect.intersects(image_rect) ) else { // No part of requested tile within the image rectangle. status = true; // Not an error. result->makeBlank(); } } // matches: if (!status) result->unref(); // Decrement ref count. } // matches: if( isOpen() && isSourceEnabled() && isValidRLevel(level) ) return status; } //******************************************************************* // Public method: //******************************************************************* bool ossimTiffTileSource::saveState(ossimKeywordlist &kwl, const char *prefix) const { bool result = ossimImageHandler::saveState(kwl, prefix); if (result) { if (isBandSelector() && theOutputBandList.size()) { if (isIdentityBandList(theOutputBandList) == false) { // If we're not identity output the bands. ossimString bandsString; ossim::toSimpleStringList(bandsString, theOutputBandList); kwl.add(prefix, ossimKeywordNames::BANDS_KW, bandsString, true); } } kwl.add(prefix, "apply_color_palette_flag", theApplyColorPaletteFlag, true); } return result; } //******************************************************************* // Public method: //******************************************************************* bool ossimTiffTileSource::loadState(const ossimKeywordlist &kwl, const char *prefix) { bool result = false; theOutputBandList.clear(); if (ossimImageHandler::loadState(kwl, prefix)) { std::string pfx = (prefix ? prefix : ""); std::string key = "apply_color_palette_flag"; ossimString value; value.string() = kwl.findKey(pfx, key); if (value.size()) { theApplyColorPaletteFlag = value.toBool(); } else { theApplyColorPaletteFlag = true; } key = ossimKeywordNames::BANDS_KW; value.string() = kwl.findKey(pfx, key); if (value.size()) { ossim::toSimpleVector(theOutputBandList, value); } if (open()) { // Set the band list after open so that the overview also gets set. result = true; } } return result; } bool ossimTiffTileSource::open(const ossimFilename &image_file) { if (theTiffPtr) { close(); } theImageFile = image_file; return open(); } void ossimTiffTileSource::close() { if (theTiffPtr) { XTIFFClose(theTiffPtr); theTiffPtr = 0; } if (m_streamAdaptor) { m_streamAdaptor->close(); m_streamAdaptor.reset(); } theImageWidth.clear(); theImageLength.clear(); theReadMethod.clear(); thePlanarConfig.clear(); thePhotometric.clear(); theRowsPerStrip.clear(); theInputTileSize.clear(); if (theBuffer) { delete[] theBuffer; theBuffer = 0; theBufferSize = 0; } ossimImageHandler::close(); } bool ossimTiffTileSource::open(std::shared_ptr &str, const std::string &connectionString) { static const char MODULE[] = "ossimTiffTileSource::open"; if (isOpen()) { close(); } // Check for empty file name. if (connectionString.empty()) { return false; } theImageFile = ossimFilename(connectionString); theImageDirectoryList.clear(); //--- // Note: The 'm' in "rm" is to tell TIFFOpen to not memory map the file. //--- //theTiffPtr = XTIFFOpen(theImageFile.c_str(), "rm"); //m_streamAdaptor = std::make_shared(this); m_streamAdaptor = std::make_shared(str, connectionString); theTiffPtr = XTIFFClientOpen(connectionString.c_str(), "rm", (thandle_t)m_streamAdaptor.get(), ossim::TiffIStreamAdaptor::tiffRead, ossim::TiffIStreamAdaptor::tiffWrite, ossim::TiffIStreamAdaptor::tiffSeek, ossim::TiffIStreamAdaptor::tiffClose, ossim::TiffIStreamAdaptor::tiffSize, ossim::TiffIStreamAdaptor::tiffMap, ossim::TiffIStreamAdaptor::tiffUnmap); if (!theTiffPtr) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << "libtiff could not open..." << std::endl; } return false; } std::shared_ptr state = getStateAs(); if (!state) { state = std::make_shared(); setState(state); state->loadDefaults(str, connectionString); //state->loadDefaults(theTiffPtr); state->setImageHandlerType(getClassName()); } state->setConnectionString(connectionString); // Current dir. theCurrentDirectory = TIFFCurrentDirectory(theTiffPtr); ossimString tempValue; theNumberOfDirectories = state->getNumberOfDirectories(); // Get the number of directories. if (!theNumberOfDirectories) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << "Unable to get the number of directories\n"; } return false; } theCompressionType = state->getCompressionType(theCurrentDirectory); //*** // Get the general tiff info. //*** if (!theCompressionType) { theCompressionType = COMPRESSION_NONE; } //*** // See if the first directory is of FILETYPE_REDUCEDIMAGE; if not, // the first level is considered to be full resolution data. // Note: If the tag is not present, consider the first level full // resolution. //*** theImageDirectoryList.push_back(0); if (state->isReduced(theCurrentDirectory)) { theR0isFullRes = false; } else { theR0isFullRes = true; } theBitsPerSample = state->getBitsPerSample(theCurrentDirectory); theSamplesPerPixel = state->getSamplesPerPixel(theCurrentDirectory); if (!theSamplesPerPixel) theSamplesPerPixel = 1; theSampleFormatUnit = state->getSampleFormat(); if (theSampleFormatUnit == SAMPLEFORMAT_COMPLEXINT) { //--- // Override the samples per pixel set above as sample data has set to // one. //--- theSamplesPerPixel = 2; } if (!state->getMaxSampleValue(theMaxSampleValue, theCurrentDirectory)) { theMaxSampleValue = ossim::nan(); } if (!state->getMinSampleValue(theMinSampleValue, theCurrentDirectory)) { theMinSampleValue = ossim::nan(); } if (traceDebug()) { CLOG << "DEBUG:" << "\ntheMinSampleValue: " << theMinSampleValue << "\ntheMaxSampleValue: " << theMaxSampleValue << endl; } theImageWidth.resize(theNumberOfDirectories); theImageLength.resize(theNumberOfDirectories); theReadMethod.resize(theNumberOfDirectories); thePlanarConfig.resize(theNumberOfDirectories); thePhotometric.resize(theNumberOfDirectories); theRowsPerStrip.resize(theNumberOfDirectories); theInputTileSize.resize(theNumberOfDirectories); for (ossim_uint32 dir = 0; dir < theNumberOfDirectories; ++dir) { // if (setTiffDirectory(dir) == false) // { // return false; // } // Note: Need lines, samples before acceptAsRrdsLayer check. theImageLength[dir] = state->getImageLength(dir); theImageWidth[dir] = state->getImageWidth(dir); // lines: if (!theImageLength[dir]) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Cannot determine image length." << endl; } // samples: if (!theImageWidth[dir]) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Cannot determine image width." << endl; } if (state->isReduced(dir)) { //--- // Check for a thumbnail image. If present don't use as it will mess with // overviews. Currently only checking if it's a two directory image, i.e. a full // res and a thumbnail. // // Note this shuts off the thumbnail which someone may want to see. We could make // this a reader prop if it becomes an issue. drb - 09 Jan. 2012. //--- if (dir != 0) { bool acceptAsRrdsLayer = true; if ((theNumberOfDirectories == 2) && (dir == 1)) { acceptAsRrdsLayer = isPowerOfTwoDecimation(dir); } if (acceptAsRrdsLayer) { theImageDirectoryList.push_back(dir); } } } thePlanarConfig[dir] = state->getPlanarConfig(dir); if (!thePlanarConfig[dir]) { thePlanarConfig[dir] = PLANARCONFIG_CONTIG; } thePhotometric[dir] = state->getPhotoInterpretation(dir); theLut = 0; if (state->hasColorMap(dir)) { if (theApplyColorPaletteFlag) { thePhotometric[dir] = PHOTOMETRIC_PALETTE; theSamplesPerPixel = 3; } populateLut(); } theRowsPerStrip[dir] = 0; theInputTileSize[dir].x = state->getTileWidth(dir); theInputTileSize[dir].y = state->getTileLength(dir); theOutputTileSize = theInputTileSize[dir]; if (state->isTiled(dir)) { if (!theInputTileSize[dir].x ) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << "ossimTiffTileSource::getTiffTileWidth ERROR:" << "\nCannot determine tile width." << endl; } if (!theInputTileSize[dir].y) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_WARN) << "ossimTiffTileSource::getTiffTileLength ERROR:" << "\nCannot determine tile length." << endl; theInputTileSize[dir].y = 0; } } else { //For strip NITF files let's set to a fixed 256x256 tile size // There is a bug in the TIF to support this. // I am commenting it out for now and will have to address this later // Can't hard coce to 256 // //theRowsPerStrip[dir] = 256; // if(theImageTileWidth[dir] < 256) // { // theImageTileWidth[dir] = 256; // } // we get core dumps if this is less so just set it if greater // if (state->getRowsPerStrip(dir) > theRowsPerStrip[dir]) // theRowsPerStrip[dir] = state->getRowsPerStrip(dir); theRowsPerStrip[dir] = state->getRowsPerStrip(dir); if (!theRowsPerStrip[dir]) theRowsPerStrip[dir] = 1; // Let's default the tile size to something efficient. // NOTE: This is not used by the strip reader method. Only by the getTileWidth // and getTileHeight methods. if (theInputTileSize[dir].x > 256) theOutputTileSize.x = 256; else if (theInputTileSize[dir].x < 64) theOutputTileSize.x = 64; if (theInputTileSize[dir].y > 256) theOutputTileSize.y = 256; else if (theInputTileSize[dir].y < 64) theOutputTileSize.y = 64; } } // End of "for (ossim_uint32 dir=0; dir 36535) ) { //--- // This is a hack for RadarSat data which is has tag 339 set to // signed sixteen bit data with a min sample value of 0 and // sometimes a max sample value greater than 36535. //--- theScalarType = OSSIM_UINT16; } else { theScalarType = OSSIM_SINT16; } #else theScalarType = OSSIM_SINT16; #endif } else if (theSampleFormatUnit == SAMPLEFORMAT_UINT) { // ESH 03/2009 -- Changed "== 2047" to "<= 2047" if (theMaxSampleValue <= 2047) // 2^11-1 { // 11 bit EO, i.e. Ikonos, QuickBird, WorldView, GeoEye. theScalarType = OSSIM_USHORT11; // IKONOS probably... } else if (theMaxSampleValue <= 4095) // 2^12-1 { theScalarType = OSSIM_USHORT12; } else if (theMaxSampleValue <= 8191) // 2^13-1 { theScalarType = OSSIM_USHORT13; } else if (theMaxSampleValue <= 16383) // 2^14-1 { theScalarType = OSSIM_USHORT14; } else if (theMaxSampleValue <= 32767) // 2^15-1 { theScalarType = OSSIM_USHORT15; } else { theScalarType = OSSIM_UINT16; } } else { if (theMaxSampleValue <= 2047) // 2^11-1 { // 11 bit EO, i.e. Ikonos, QuickBird, WorldView, GeoEye. theScalarType = OSSIM_USHORT11; // IKONOS probably... } else if (theMaxSampleValue <= 4095) // 2^12-1 { theScalarType = OSSIM_USHORT12; } else if (theMaxSampleValue <= 8191) // 2^13-1 { theScalarType = OSSIM_USHORT13; } else if (theMaxSampleValue <= 16383) // 2^14-1 { theScalarType = OSSIM_USHORT14; } else if (theMaxSampleValue <= 32767) // 2^15-1 { theScalarType = OSSIM_USHORT15; } else theScalarType = OSSIM_UINT16; // Default to unsigned... } } else if ((theBitsPerSample == 32) && (theSampleFormatUnit == SAMPLEFORMAT_UINT)) { theBytesPerPixel = 4; theScalarType = OSSIM_UINT32; } else if ((theBitsPerSample == 32) && (theSampleFormatUnit == SAMPLEFORMAT_INT)) { theBytesPerPixel = 4; theScalarType = OSSIM_SINT32; } else if ((theBitsPerSample == 32) && (theSampleFormatUnit == SAMPLEFORMAT_IEEEFP)) { theBytesPerPixel = 4; theScalarType = OSSIM_FLOAT32; } else if ((theBitsPerSample == 32) && (theSampleFormatUnit == SAMPLEFORMAT_COMPLEXINT)) { theBytesPerPixel = 2; theScalarType = OSSIM_SINT16; } else if (theBitsPerSample == 64 && theSampleFormatUnit == SAMPLEFORMAT_IEEEFP) { theBytesPerPixel = 8; theScalarType = OSSIM_FLOAT64; } else if (theBitsPerSample <= 8) { theBytesPerPixel = 1; theScalarType = OSSIM_UINT8; } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error:\nCannot determine scalar type.\n" << "Trace dump follows:\n"; print(ossimNotify(ossimNotifyLevel_WARN)); return false; } // Sanity check for min, max and null values. validateMinMaxNull(); setReadMethod(); ossim_uint16 rasterType = state->getRasterType(theCurrentDirectory); if (rasterType == 1) { thePixelType = OSSIM_PIXEL_IS_AREA; } else { thePixelType = OSSIM_PIXEL_IS_POINT; } completeOpen(); if (isBandSelector() && theOutputBandList.size() && (isIdentityBandList(theOutputBandList) == false)) { // This does range checking and will pass to overview if open. setOutputBandList(theOutputBandList); } //--- // Note: Logic changed to leave theTile and theBuffer uninitialized until first getTile(...) // request. (drb) // NOTE: Put back in //--- allocateTile(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Debug:"; print(ossimNotify(ossimNotifyLevel_DEBUG)); } // Finished... return true; } bool ossimTiffTileSource::open() { static const char MODULE[] = "ossimTiffTileSource::open"; bool result = false; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Entered..." << "\nFile: " << theImageFile.c_str() << std::endl; } std::shared_ptr tiffStream = ossim::StreamFactoryRegistry::instance()->createIstream(theImageFile); if (tiffStream) { result = open(tiffStream, theImageFile); } return result; } bool ossimTiffTileSource::isImageTiled() const { if (theRowsPerStrip.empty()) return false; if ((theRowsPerStrip[0] == 0) && (theInputTileSize[0].y > 1)) return true; return false; } ossim_uint32 ossimTiffTileSource::getNumberOfLines(ossim_uint32 resLevel) const { ossim_uint32 result = 0; if (theImageDirectoryList.size() && theTiffPtr && isValidRLevel(resLevel)) { //--- // If we have r0 our reslevels are the same as the callers so // no adjustment necessary. //--- if (!theStartingResLevel || theR0isFullRes) // not an overview or has r0. { //--- // If we have r0 our reslevels are the same as the callers so // no adjustment necessary. //--- if (resLevel < theImageDirectoryList.size()) { result = theImageLength[theImageDirectoryList[resLevel]]; } else if (theOverview.valid()) { result = theOverview->getNumberOfLines(resLevel); } } else // this is an overview without r0 { if (resLevel >= theStartingResLevel) { //--- // Adjust the level to be relative to the reader using this as // overview. //--- ossim_uint32 level = resLevel - theStartingResLevel; if (level < theImageDirectoryList.size()) { result = theImageLength[theImageDirectoryList[level]]; } } } } return result; } ossim_uint32 ossimTiffTileSource::getNumberOfSamples(ossim_uint32 resLevel) const { ossim_uint32 result = 0; if (theImageDirectoryList.size() && theTiffPtr && isValidRLevel(resLevel)) { //--- // If we have r0 our reslevels are the same as the callers so // no adjustment necessary. //--- if (!theStartingResLevel || theR0isFullRes) // not an overview or has r0. { if (resLevel < theImageDirectoryList.size()) { result = theImageWidth[theImageDirectoryList[resLevel]]; } else if (theOverview.valid()) { result = theOverview->getNumberOfSamples(resLevel); } } else // this is an overview. { if (resLevel >= theStartingResLevel) { //--- // Adjust the level to be relative to the reader using this as // overview. //--- ossim_uint32 level = resLevel - theStartingResLevel; if (level < theImageDirectoryList.size()) { result = theImageWidth[theImageDirectoryList[level]]; } } } } return result; } ossim_uint32 ossimTiffTileSource::getNumberOfDecimationLevels() const { ossim_uint32 result = theImageDirectoryList.size(); // If starting res level is not 0 then this is an overview. if (theStartingResLevel && theR0isFullRes) { // Don't count r0. --result; } else if (theOverview.valid()) { result += theOverview->getNumberOfDecimationLevels(); } return result; } //******************************************************************* // Public method: //******************************************************************* ossimScalarType ossimTiffTileSource::getOutputScalarType() const { return theScalarType; } bool ossimTiffTileSource::loadTile(const ossimIrect &tile_rect, const ossimIrect &clip_rect, ossimImageData *result) { static const char MODULE[] = "ossimTiffTileSource::loadTile"; bool status = true; if (!theBuffer) { status = allocateBuffer(); } if (status) { switch (theReadMethod[theCurrentDirectory]) { case READ_TILE: status = loadFromTile(clip_rect, result); break; case READ_SCAN_LINE: status = loadFromScanLine(clip_rect, result); break; case READ_RGBA_U8_TILE: status = loadFromRgbaU8Tile(tile_rect, clip_rect, result); break; case READ_RGBA_U8_STRIP: status = loadFromRgbaU8Strip(tile_rect, clip_rect, result); break; case READ_RGBA_U8A_STRIP: status = loadFromRgbaU8aStrip(tile_rect, clip_rect, result); break; case READ_U16_STRIP: status = loadFromU16Strip(clip_rect, result); break; default: ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Unsupported tiff type!" << endl; status = false; break; } } return status; } bool ossimTiffTileSource::loadFromScanLine(const ossimIrect &clip_rect, ossimImageData *result) { #if OSSIM_BUFFER_SCAN_LINE_READS ossimInterleaveType type = (thePlanarConfig[theCurrentDirectory] == PLANARCONFIG_CONTIG) ? OSSIM_BIP : OSSIM_BIL; if (theBufferRLevel != getCurrentTiffRLevel() || !clip_rect.completely_within(theBufferRect)) { //*** // Must reload the buffer. Grab enough lines to fill the depth of the // clip rectangle. //*** theBufferRLevel = getCurrentTiffRLevel(); theBufferRect = getImageRectangle(theBufferRLevel); theBufferRect.set_uly(clip_rect.ul().y); theBufferRect.set_lry(clip_rect.lr().y); ossim_uint32 startLine = clip_rect.ul().y; ossim_uint32 stopLine = clip_rect.lr().y; ossim_uint8 *buf = theBuffer; if (thePlanarConfig[theCurrentDirectory] == PLANARCONFIG_CONTIG) { ossim_uint32 lineSizeInBytes = getNumberOfSamples(theBufferRLevel) * theBytesPerPixel * theSamplesPerPixel; for (ossim_uint32 line = startLine; line <= stopLine; ++line) { TIFFReadScanline(theTiffPtr, (void *)buf, line, 0); buf += lineSizeInBytes; } } else { ossim_uint32 lineSizeInBytes = getNumberOfSamples(theBufferRLevel) * theBytesPerPixel; for (ossim_uint32 line = startLine; line <= stopLine; ++line) { for (ossim_uint32 band = 0; band < theSamplesPerPixel; ++band) { TIFFReadScanline(theTiffPtr, (void *)buf, line, band); buf += lineSizeInBytes; } } } } //--- // Since theTile's internal rectangle is relative to any sub image offset // we must adjust both the zero based "theBufferRect" and the zero base // "clip_rect" before passing to // theTile->loadTile method. //--- result->loadTile(theBuffer, theBufferRect, clip_rect, type); return true; #else ossimInterleaveType type = (thePlanarConfig[theCurrentDirectory] == PLANARCONFIG_CONTIG) ? OSSIM_BIP : OSSIM_BIL; ossim_int32 startLine = clip_rect.ul().y; ossim_int32 stopLine = clip_rect.lr().y; ossim_int32 stopSamp = static_cast(getNumberOfSamples(theBufferRLevel) - 1); if (thePlanarConfig[theCurrentDirectory] == PLANARCONFIG_CONTIG) { for (ossim_int32 line = startLine; line <= stopLine; ++line) { TIFFReadScanline(theTiffPtr, (void *)theBuffer, line, 0); result->copyLine((void *)theBuffer, line, 0, stopSamp, type); } } else { ossim_uint32 lineSizeInBytes = getNumberOfSamples(theBufferRLevel) * theBytesPerPixel; for (ossim_int32 line = startLine; line <= stopLine; ++line) { ossim_uint8 *buf = theBuffer; for (ossim_uint32 band = 0; band < theSamplesPerPixel; ++band) { TIFFReadScanline(theTiffPtr, (void *)buf, line, band); buf += lineSizeInBytes; } result->copyLine((void *)theBuffer, line, 0, stopSamp, type); } } return true; #endif /* #if OSSIM_BUFFER_SCAN_LINE_READS #else - Non buffered scan line reads. */ } bool ossimTiffTileSource::loadFromTile(const ossimIrect &clip_rect, ossimImageData *result) { static const char MODULE[] = "ossimTiffTileSource::loadFromTile"; ossim_int32 tileSizeRead = 0; //--- // Shift the upper left corner of the "clip_rect" to the an even tile // boundary. Note this will shift in the upper left direction. //--- ossimIpt tileOrigin = clip_rect.ul(); adjustToStartOfTile(tileOrigin); ossimIpt ulTilePt = tileOrigin; // ossimIpt subImageOffset = getSubImageOffset(getCurrentTiffRLevel()+theStartingResLevel); //--- // Calculate the number of tiles needed in the line/sample directions. //--- ossim_uint32 tiles_in_v_dir = (clip_rect.lr().x - tileOrigin.x + 1) / theInputTileSize[theCurrentDirectory].x; ossim_uint32 tiles_in_u_dir = (clip_rect.lr().y - tileOrigin.y + 1) / theInputTileSize[theCurrentDirectory].y; if ((clip_rect.lr().x - tileOrigin.x + 1) % theInputTileSize[theCurrentDirectory].x) ++tiles_in_v_dir; if ((clip_rect.lr().y - tileOrigin.y + 1) % theInputTileSize[theCurrentDirectory].y) ++tiles_in_u_dir; // Tile loop in line direction. for (ossim_uint32 u = 0; u < tiles_in_u_dir; ++u) { ulTilePt.x = tileOrigin.x; // Tile loop in sample direction. for (ossim_uint32 v = 0; v < tiles_in_v_dir; ++v) { ossimIrect tiff_tile_rect(ulTilePt.x, ulTilePt.y, ulTilePt.x + theInputTileSize[theCurrentDirectory].x - 1, ulTilePt.y + theInputTileSize[theCurrentDirectory].y - 1); if (tiff_tile_rect.intersects(clip_rect)) { ossimIrect tiff_tile_clip_rect = tiff_tile_rect.clipToRect(clip_rect); //--- // Since theTile's internal rectangle is relative to any sub // image offset we must adjust both the zero based // "theBufferRect" and the zero based "clip_rect" before // passing to theTile->loadTile method. //--- ossimIrect bufRectWithOffset = tiff_tile_rect; // + subImageOffset; ossimIrect clipRectWithOffset = tiff_tile_clip_rect; // + subImageOffset; if (thePlanarConfig[theCurrentDirectory] == PLANARCONFIG_CONTIG) { tileSizeRead = TIFFReadTile(theTiffPtr, theBuffer, ulTilePt.x, ulTilePt.y, 0, 0); if (tileSizeRead > 0) { result->loadTile(theBuffer, bufRectWithOffset, clipRectWithOffset, OSSIM_BIP); } else if (tileSizeRead < 0) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Read Error!" << "\nReturning error... " << endl; } theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return false; } } else { if (theOutputBandList.empty()) { // This will set to identity. ossimImageSource::getOutputBandList(theOutputBandList); } // band separate tiles... std::vector::const_iterator bandIter = theOutputBandList.begin(); ossim_uint32 destinationBand = 0; while (bandIter != theOutputBandList.end()) { tileSizeRead = TIFFReadTile(theTiffPtr, theBuffer, ulTilePt.x, ulTilePt.y, 0, (*bandIter)); if (tileSizeRead > 0) { result->loadBand(theBuffer, bufRectWithOffset, clipRectWithOffset, destinationBand); } else if (tileSizeRead < 0) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Read Error!" << "\nReturning error... " << endl; } theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return false; } ++bandIter; // Next band... ++destinationBand; } } } // End of if (tiff_tile_rect.intersects(clip_rect)) ulTilePt.x += theInputTileSize[theCurrentDirectory].x; } // End of tile loop in the sample direction. ulTilePt.y += theInputTileSize[theCurrentDirectory].y; } // End of tile loop in the line direction. return true; } bool ossimTiffTileSource::loadFromRgbaU8Tile(const ossimIrect &tile_rect, const ossimIrect &clip_rect, ossimImageData *result) { static const char MODULE[] = "ossimTiffTileSource::loadFromRgbaTile"; if (theSamplesPerPixel != 3 || theBytesPerPixel != 1) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error:" << "\nInvalid number of bands or bytes per pixel!" << endl; } //*** // Shift the upper left corner of the "clip_rect" to the an even tile // boundary. Note this will shift in the upper left direction. //*** ossimIpt tileOrigin = clip_rect.ul(); adjustToStartOfTile(tileOrigin); //--- // Calculate the number of tiles needed in the line/sample directions // to fill the tile. //--- ossim_uint32 tiles_in_v_dir = (clip_rect.lr().x - tileOrigin.x + 1) / theInputTileSize[theCurrentDirectory].x; ossim_uint32 tiles_in_u_dir = (clip_rect.lr().y - tileOrigin.y + 1) / theInputTileSize[theCurrentDirectory].y; if ((clip_rect.lr().x - tileOrigin.x + 1) % theInputTileSize[theCurrentDirectory].x) ++tiles_in_v_dir; if ((clip_rect.lr().y - tileOrigin.y + 1) % theInputTileSize[theCurrentDirectory].y) ++tiles_in_u_dir; ossimIpt ulTilePt = tileOrigin; #if 0 if (traceDebug()) { CLOG << "DEBUG:" << "\ntile_rect: " << tile_rect << "\nclip_rect: " << clip_rect << "\ntiles_in_v_dir: " << tiles_in_v_dir << "\ntiles_in_u_dir: " << tiles_in_u_dir << endl; } #endif // Tile loop in line direction. for (ossim_uint32 u = 0; u < tiles_in_u_dir; u++) { ulTilePt.x = tileOrigin.x; // Tile loop in sample direction. for (ossim_uint32 v = 0; v < tiles_in_v_dir; v++) { ossimIrect tiff_tile_rect = ossimIrect(ulTilePt.x, ulTilePt.y, ulTilePt.x + theInputTileSize[theCurrentDirectory].x - 1, ulTilePt.y + theInputTileSize[theCurrentDirectory].y - 1); if (getCurrentTiffRLevel() != theBufferRLevel || tiff_tile_rect != theBufferRect) { // Need to grab a new tile. // Read a tile into the buffer. if (!TIFFReadRGBATile(theTiffPtr, ulTilePt.x, ulTilePt.y, (uint32 *)theBuffer)) // use tiff typedef { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Read Error!" << "\nReturning error..." << endl; theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return false; } // Capture the rectangle. theBufferRect = tiff_tile_rect; theBufferRLevel = getCurrentTiffRLevel(); } ossimIrect tile_clip_rect = clip_rect.clipToRect(theBufferRect); //*** // Get the offset to the first valid pixel. // // Note: The data in the tile buffer is organized bottom up. So the // coordinate must be negated in the line direction since // the met assumes an origin of upper left. //*** ossim_uint32 in_buf_offset = (tiff_tile_rect.lr().y - tile_clip_rect.ul().y) * theInputTileSize[theCurrentDirectory].x * 4 + ((tile_clip_rect.ul().x - ulTilePt.x) * 4); ossim_uint32 out_buf_offset = (tile_clip_rect.ul().y - tile_rect.ul().y) * ((ossim_int32)result->getWidth()) + tile_clip_rect.ul().x - tile_rect.ul().x; // // Get a pointer positioned at the first valid pixel in buffers. // ossim_uint32 *s = (ossim_uint32 *)(theBuffer + in_buf_offset); // s for source... // ossim_uint8* s = theBuffer + in_buf_offset; // s for source... ossim_uint8 *r = static_cast(result->getBuf(0)) + out_buf_offset; ossim_uint8 *g = static_cast(result->getBuf(1)) + out_buf_offset; ossim_uint8 *b = static_cast(result->getBuf(2)) + out_buf_offset; ossim_uint32 lines2copy = tile_clip_rect.lr().y - tile_clip_rect.ul().y + 1; ossim_uint32 samps2copy = tile_clip_rect.lr().x - tile_clip_rect.ul().x + 1; // Line loop through valid portion of the tiff tile. for (ossim_uint32 line = 0; line < lines2copy; line++) { // Sample loop through the tiff tile. ossim_uint32 i = 0; ossim_uint32 j = 0; // note the bands from the TIFF READ are stored in a, b, g, r ordering. // we must reverse the bands and skip the first byte. for (ossim_uint32 sample = 0; sample < samps2copy; sample++) { r[i] = (ossim_uint8)OSSIM_TIFF_UNPACK_R4(s[j]); g[i] = (ossim_uint8)OSSIM_TIFF_UNPACK_G4(s[j]); b[i] = (ossim_uint8)OSSIM_TIFF_UNPACK_B4(s[j]); i++; ++j; } // Increment the pointers by one line. const ossim_uint32 OUTPUT_TILE_WIDTH = result->getWidth(); r += OUTPUT_TILE_WIDTH; g += OUTPUT_TILE_WIDTH; b += OUTPUT_TILE_WIDTH; s -= theInputTileSize[theCurrentDirectory].x; } ulTilePt.x += theInputTileSize[theCurrentDirectory].x; } // End of tile loop in the sample direction. ulTilePt.y += theInputTileSize[theCurrentDirectory].y; } // End of tile loop in the line direction. return true; } bool ossimTiffTileSource::loadFromRgbaU8Strip(const ossimIrect &tile_rect, const ossimIrect &clip_rect, ossimImageData *result) { static const char MODULE[] = "ossimTiffTileSource::loadFromRgbaU8Strip"; if (theSamplesPerPixel > 4 || theBytesPerPixel != 1) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error:" << "\nInvalid number of bands or bytes per pixel!" << endl; } //*** // Calculate the number of strips to read. //*** const ossim_uint32 OUTPUT_TILE_WIDTH = result->getWidth(); ossim_uint32 starting_strip = clip_rect.ul().y / theRowsPerStrip[theCurrentDirectory]; ossim_uint32 ending_strip = clip_rect.lr().y / theRowsPerStrip[theCurrentDirectory]; ossim_uint32 strip_width = theImageWidth[theCurrentDirectory] * 4; ossim_uint32 output_tile_offset = (clip_rect.ul().y - tile_rect.ul().y) * OUTPUT_TILE_WIDTH + clip_rect.ul().x - tile_rect.ul().x; #if 0 /* Please keep for debug: */ CLOG << "DEBUG:" << "\nsamples: " << theSamplesPerPixel << "\ntile_rect: " << tile_rect << "\nclip_rect: " << clip_rect << "\nstarting_strip: " << starting_strip << "\nending_strip: " << ending_strip << "\nstrip_width: " << strip_width << "\noutput_tile_offset: " << output_tile_offset << endl; #endif //*** // Get the pointers positioned at the first valid pixel in the buffers. // s = source // d = destination //*** ossim_uint32 band; ossim_uint8 **d = new ossim_uint8 *[theSamplesPerPixel]; for (band = 0; band < theSamplesPerPixel; band++) { d[band] = static_cast(result->getBuf(band)) + output_tile_offset; } // Loop through strips... for (ossim_uint32 strip = starting_strip; strip <= ending_strip; strip++) { if ((theBufferRLevel != theCurrentDirectory) || (clip_rect.completely_within(theBufferRect) == false)) { if (TIFFReadRGBAStrip(theTiffPtr, (strip * theRowsPerStrip[theCurrentDirectory]), (uint32 *)theBuffer) == 0) // use tiff typedef { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error reading strip!" << endl; delete[] d; return false; } // Capture rect and rlevel of buffer: theBufferRLevel = theCurrentDirectory; theBufferRect = ossimIrect( 0, starting_strip, theImageWidth[theCurrentDirectory] - 1, (ending_strip - starting_strip) ? (ending_strip - starting_strip) * theRowsPerStrip[theCurrentDirectory] - 1 : theRowsPerStrip[theCurrentDirectory] - 1); } //*** // If the last strip is a partial strip then the first line of the // strip will be the last line of the image. //*** ossim_uint32 last_line = theImageLength[theCurrentDirectory] - 1; ossim_uint32 strip_offset = ((strip * theRowsPerStrip[theCurrentDirectory]) + theRowsPerStrip[theCurrentDirectory] - 1) < last_line ? 0 : ((strip * theRowsPerStrip[theCurrentDirectory]) + theRowsPerStrip[theCurrentDirectory] - 1) - last_line; ossim_uint32 total_rows = theRowsPerStrip[theCurrentDirectory] - strip_offset; for (ossim_uint32 row = 0; row < total_rows; row++) { // Write the line if it's in the clip rectangle. ossim_int32 current_line = strip * theRowsPerStrip[theCurrentDirectory] + row; if (current_line >= clip_rect.ul().y && current_line <= clip_rect.lr().y) { // // Position the stip pointer to the correct spot. // // Note: // A strip is organized from bottom to top and the raster buffer is // orgainized from top to bottom so the lineBuf must be offset // accordingly. // ossim_uint32 *s = (ossim_uint32 *)(theBuffer + ((theRowsPerStrip[theCurrentDirectory] - row - strip_offset - 1) * strip_width + clip_rect.ul().x * 4)); // Copy the data to the output buffer. ossim_uint32 i = 0; for (int32 sample = clip_rect.ul().x; sample <= clip_rect.lr().x; sample++) { //We had a single band strip image that is coming into this method // Will add a sanity check on the samples per pixel. If it's == 1 for now // we will assign the value and if it has atleast the 3 samples then we will // extract as usual. // if (theSamplesPerPixel >= 3) { d[0][i] = OSSIM_TIFF_UNPACK_R4(*s); d[1][i] = OSSIM_TIFF_UNPACK_G4(*s); d[2][i] = OSSIM_TIFF_UNPACK_B4(*s); } else if (theSamplesPerPixel == 1) { d[0][i] = *s; } ++i; ++s; } for (band = 0; band < theSamplesPerPixel; band++) { d[band] += OUTPUT_TILE_WIDTH; } } } // End of loop through rows in a strip. } // End of loop through strips. delete[] d; return true; } //******************************************************************* // Private Method: //******************************************************************* bool ossimTiffTileSource::loadFromRgbaU8aStrip(const ossimIrect &tile_rect, const ossimIrect &clip_rect, ossimImageData *result) { static const char MODULE[] = "ossimTiffTileSource::loadFromRgbaU8aStrip"; //*** // Specialized for one bit data to handle null values. //*** const ossim_uint32 OUTPUT_TILE_WIDTH = result->getWidth(); const ossim_uint8 NULL_PIX = static_cast(result->getNullPix(0)); const ossim_uint8 MIN_PIX = static_cast(result->getMinPix(0)); if (theSamplesPerPixel > 4 || theBytesPerPixel != 1) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error:" << "\nInvalid number of bands or bytes per pixel!" << endl; } //*** // Calculate the number of strips to read. //*** ossim_uint32 starting_strip = clip_rect.ul().y / theRowsPerStrip[theCurrentDirectory]; ossim_uint32 ending_strip = clip_rect.lr().y / theRowsPerStrip[theCurrentDirectory]; ossim_uint32 output_tile_offset = (clip_rect.ul().y - tile_rect.ul().y) * OUTPUT_TILE_WIDTH + clip_rect.ul().x - tile_rect.ul().x; #if 0 if (traceDebug()) { CLOG << "DEBUG:" << "\ntile_rect: " << tile_rect << "\nclip_rect: " << clip_rect << "\nstarting_strip: " << starting_strip << "\nending_strip: " << ending_strip << "\nstrip_width: " << strip_width << "\noutput_tile_offset: " << output_tile_offset << "\nsamples: " << theSamplesPerPixel << endl; } #endif //*** // Get the pointers positioned at the first valid pixel in the buffers. // s = source // d = destination //*** ossim_uint32 band; ossim_uint8 **d = new ossim_uint8 *[theSamplesPerPixel]; for (band = 0; band < theSamplesPerPixel; band++) { d[band] = static_cast(result->getBuf(band)) + output_tile_offset; } // Loop through strips... for (ossim_uint32 strip = starting_strip; strip <= ending_strip; strip++) { if (TIFFReadRGBAStrip(theTiffPtr, (strip * theRowsPerStrip[theCurrentDirectory]), (uint32 *)theBuffer) == 0) // use tiff typedef { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Error reading strip!" << endl; delete[] d; return false; } //*** // If the last strip is a partial strip then the first line of the // strip will be the last line of the image. //*** ossim_uint32 last_line = theImageLength[theCurrentDirectory] - 1; ossim_uint32 strip_offset = ((strip * theRowsPerStrip[theCurrentDirectory]) + theRowsPerStrip[theCurrentDirectory] - 1) < last_line ? 0 : ((strip * theRowsPerStrip[theCurrentDirectory]) + theRowsPerStrip[theCurrentDirectory] - 1) - last_line; ossim_uint32 total_rows = theRowsPerStrip[theCurrentDirectory] - strip_offset; for (ossim_uint32 row = 0; row < total_rows; row++) { // Write the line if it's in the clip rectangle. ossim_int32 current_line = strip * theRowsPerStrip[theCurrentDirectory] + row; if (current_line >= clip_rect.ul().y && current_line <= clip_rect.lr().y) { //*** // Position the stip pointer to the correct spot. // // Note: // A strip is organized from bottom to top and the raster buffer is // orgainized from top to bottom so the lineBuf must be offset // accordingly. //*** ossim_uint8 *s = theBuffer; s += (theRowsPerStrip[theCurrentDirectory] - row - strip_offset - 1) * theImageWidth[theCurrentDirectory] * 4 + clip_rect.ul().x * 4; // Copy the data to the output buffer. ossim_uint32 i = 0; ossim_uint32 j = 0; for (int32 sample = clip_rect.ul().x; sample <= clip_rect.lr().x; sample++) { for (band = 0; band < theSamplesPerPixel; band++) { ossim_uint8 pix = s[j + band]; d[band][i] = pix != NULL_PIX ? pix : MIN_PIX; } ++i; j += 4; } for (band = 0; band < theSamplesPerPixel; band++) { d[band] += OUTPUT_TILE_WIDTH; } } } // End of loop through rows in a strip. } // End of loop through strips. delete[] d; return true; } // End: ossimTiffTileSource::loadFromRgbaU8aStrip( ... ) bool ossimTiffTileSource::loadFromU16Strip(const ossimIrect &clip_rect, ossimImageData *result) { bool status = true; // Calculate the strips to read. ossim_uint32 starting_strip = clip_rect.ul().y / theRowsPerStrip[theCurrentDirectory]; ossim_uint32 ending_strip = clip_rect.lr().y / theRowsPerStrip[theCurrentDirectory]; ossim_uint32 stripsPerBand = theImageLength[theCurrentDirectory] / theRowsPerStrip[theCurrentDirectory]; if (theImageLength[theCurrentDirectory] % theRowsPerStrip[theCurrentDirectory]) { ++stripsPerBand; } // Loop through strips.... for (ossim_uint32 strip = starting_strip; strip <= ending_strip; ++strip) { if ((theBufferRLevel != theCurrentDirectory) || !clip_rect.completely_within(theBufferRect)) { // Fill buffer block: ossim_uint32 linesInStrip = theRowsPerStrip[theCurrentDirectory]; // If last strip and not filling entirely memset it. if (strip == (stripsPerBand - 1)) { // Last strip of image. Strip may be clipped to end of image. linesInStrip = theImageLength[theCurrentDirectory] % theRowsPerStrip[theCurrentDirectory]; } ossim_uint32 bytesPerStrip = linesInStrip * theImageWidth[theCurrentDirectory] * 2; // TIFFReadEncodedStrip takes signed int32 arg. ossim_int32 bytesToRead = (ossim_int32)bytesPerStrip; ossim_uint32 startY = strip * theRowsPerStrip[theCurrentDirectory]; // Need to read in the strip data: ossim_uint32 bufferOffsetInBytes = 0; for (ossim_uint32 band = 0; band < theSamplesPerPixel; ++band) { ossim_uint32 bandStrip = strip + band * stripsPerBand; //--- // TIFFReadEncodedStrip does byte swapping for us. // -1 says to read entire strip. // Return of -1 is error. //--- ossim_int32 bytesRead = TIFFReadEncodedStrip(theTiffPtr, bandStrip, theBuffer + bufferOffsetInBytes, bytesToRead); // std::cout << "bytesRead" << bytesRead << " ?? " << bytesToRead << "\n"; if (bytesRead != bytesToRead) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimTiffTileSource::loadFromU16Strip Read Error!" << "\nReturning error... " << endl; } theErrorStatus = ossimErrorCodes::OSSIM_ERROR; status = false; result->makeBlank(); break; } bufferOffsetInBytes += bytesPerStrip; } if (status) { // Capture rect and rlevel of buffer: theBufferRLevel = theCurrentDirectory; theBufferRect = ossimIrect(0, startY, theImageWidth[theCurrentDirectory] - 1, startY + linesInStrip - 1); } } // End: Fill buffer block. if (status) { result->loadTile(theBuffer, theBufferRect, OSSIM_BSQ); } } // End of strip loop. return status; } // End: ossimTiffTileSource::loadFromU16Strip( ... ) void ossimTiffTileSource::adjustToStartOfTile(ossimIpt &pt) const { //*** // Notes: // - Assumes an origin of (0,0) // - Shifts in to the upper left direction. //*** ossim_int32 tw = static_cast(theInputTileSize[theCurrentDirectory].x); ossim_int32 th = static_cast(theInputTileSize[theCurrentDirectory].y); if (pt.x > 0) { pt.x = (pt.x / tw) * tw; } else if (pt.x < 0) { pt.x = std::abs(pt.x) < tw ? -tw : (pt.x / tw) * tw; } if (pt.y > 0) { pt.y = (pt.y / th) * th; } else if (pt.y < 0) { pt.y = std::abs(pt.y) < th ? -th : (pt.y / th) * th; } } bool ossimTiffTileSource::isValidRLevel(ossim_uint32 resLevel) const { bool result = false; const ossim_uint32 LEVELS = getNumberOfDecimationLevels(); //--- // If we have r0 our reslevels are the same as the callers so // no adjustment necessary. //--- if (!theStartingResLevel || theR0isFullRes) // Not an overview or has r0. { result = (resLevel < LEVELS); } else if (resLevel >= theStartingResLevel) // Used as overview. { result = ((resLevel - theStartingResLevel) < LEVELS); } return result; } ossim_uint32 ossimTiffTileSource::getCurrentTiffRLevel() const { return theCurrentTiffRlevel; // return theCurrentDirectory; } bool ossimTiffTileSource::getRgbBandList(std::vector &bandList) const { bool result = false; ossimString copyright; std::shared_ptr state = getStateAs(); if (state) { ossimString value; if (state->getValue(value, "tiff.imd.band_name_list")) { std::vector splitArray; value.split(splitArray, " "); ossim_uint32 nInputBands = getNumberOfInputBands(); if ((splitArray.size() <= nInputBands) && (nInputBands > 2)) { ossim_uint32 idx = 0; bandList.resize(3); bandList[0] = 0; bandList[1] = 1; bandList[2] = 2; result = true; for (idx = 0; idx < splitArray.size(); ++idx) { ossimString tempDowncase = splitArray[idx].trim().downcase(); switch (*tempDowncase.begin()) { case 'r': { bandList[0] = idx; break; } case 'g': { bandList[1] = idx; break; } case 'b': { bandList[2] = idx; break; } default: { break; } } } } } } return result; } ossimString ossimTiffTileSource::getReadMethod(ossim_uint32 directory) const { ossimString result = "UNKNOWN"; if (directory < theReadMethod.size()) { switch (theReadMethod[directory]) { case READ_RGBA_U8_TILE: result = "READ_RGBA_U8_TILE"; break; case READ_RGBA_U8_STRIP: result = "READ_RGBA_U8_STRIP"; break; case READ_RGBA_U8A_STRIP: result = "READ_RGBA_U8A_STRIP"; break; case READ_SCAN_LINE: result = "READ_SCAN_LINE"; break; case READ_TILE: result = "READ_TILE"; break; case UNKNOWN: default: break; } } return result; } ossim_uint32 ossimTiffTileSource::getNumberOfDirectories() const { return theNumberOfDirectories; } ossim_uint32 ossimTiffTileSource::getImageTileWidth() const { ossim_uint32 result = 0; if (isOpen()) { if (theCurrentDirectory < theInputTileSize.size()) { result = theInputTileSize[theCurrentDirectory].x; } } return result; } ossim_uint32 ossimTiffTileSource::getImageTileHeight() const { ossim_uint32 result = 0; if (isOpen()) { if (theCurrentDirectory < theInputTileSize.size()) { result = theInputTileSize[theCurrentDirectory].y; } } return result; } ossim_uint32 ossimTiffTileSource::getTileWidth() const { ossim_uint32 result = theOutputTileSize.x; if (!result) { ossim::defaultTileSize(theOutputTileSize); result = theOutputTileSize.x; } return result; } ossim_uint32 ossimTiffTileSource::getTileHeight() const { ossim_uint32 result = theOutputTileSize.y; if (!result) { ossim::defaultTileSize(theOutputTileSize); result = theOutputTileSize.y; } return result; } void ossimTiffTileSource::setApplyColorPaletteFlag(bool flag) { theApplyColorPaletteFlag = flag; if (isColorMapped()) { if (theApplyColorPaletteFlag) { thePhotometric[0] = PHOTOMETRIC_PALETTE; theSamplesPerPixel = 3; } else { thePhotometric[0] = PHOTOMETRIC_MINISBLACK; theSamplesPerPixel = 1; } setReadMethod(); theTile = 0; if (theBuffer) { delete[] theBuffer; theBuffer = 0; } } } bool ossimTiffTileSource::getApplyColorPaletteFlag() const { return theApplyColorPaletteFlag; } ossimString ossimTiffTileSource::getLongName() const { return ossimString("TIFF Image Handler"); } ossimString ossimTiffTileSource::getShortName() const { return ossimString("ossim_tiff"); } std::ostream &ossimTiffTileSource::print(std::ostream &os) const { //*** // Use a keyword format. //*** os << "image_file: " << theImageFile << "\nsamples_per_pixel: " << theSamplesPerPixel << "\nbits_per_sample: " << theBitsPerSample << "\nsample_format_unit: " << theSampleFormatUnit << "\nmin_sample_value: " << theMinSampleValue << "\nmax_sample_value: " << theMaxSampleValue << "\nnull_sample_value: " << theNullSampleValue << "\ntheNumberOfDirectories: " << theNumberOfDirectories << "\nr0_is_full_res: " << theR0isFullRes; for (ossim_uint32 i = 0; i < theNumberOfDirectories; ++i) { os << "\ndirectory[" << i << "]" << "\nimage width: " << theImageWidth[i] << "\nimage_length: " << theImageLength[i] << "\nread method: " << getReadMethod(i).c_str() << "\nplanar: " << thePlanarConfig[i] << "\nphotometric: " << thePhotometric[i]; if (theRowsPerStrip[i]) { os << "\nrows per strip: " << theRowsPerStrip[i]; } if (theInputTileSize[i].x) { os << "\ntile_width: " << theInputTileSize[i].x; } if (theInputTileSize[i].y) { os << "\ntile_length: " << theInputTileSize[i].y; } os << endl; } if (theTile.valid()) { os << "\nOutput tile dump:\n" << *theTile << endl; } if (theOverview.valid()) { os << "\nOverview file:\n"; theOverview->print(os); } os << endl; return ossimSource::print(os); } ossim_uint32 ossimTiffTileSource::getNumberOfInputBands() const { return theSamplesPerPixel; } ossim_uint32 ossimTiffTileSource::getNumberOfOutputBands() const { ossim_uint32 bands = theOutputBandList.size(); if (!bands) { bands = getNumberOfInputBands(); } return bands; } bool ossimTiffTileSource::isBandSelector() const { bool result = false; if (isOpen() && theReadMethod.size() && (theReadMethod.size() == thePlanarConfig.size())) { // Tiled band separate currently is only coded to be band selector. result = true; for (ossim_uint32 i = 0; i < theReadMethod.size(); ++i) { if ((theReadMethod[i] != READ_TILE) || (thePlanarConfig[i] == PLANARCONFIG_CONTIG)) { result = false; break; } } if (result && theOverview.valid()) { result = theOverview->isBandSelector(); } } return result; } bool ossimTiffTileSource::setOutputBandList(const std::vector &band_list) { bool result = false; if (isBandSelector()) { // Making a copy as passed in list could be our m_outputBandList. std::vector inputList = band_list; result = ossimImageHandler::setOutputBandList(inputList, theOutputBandList); if (result && theTile.valid()) { if (theTile->getNumberOfBands() != theOutputBandList.size()) { theTile = 0; // Force a reinitialize on next getTile. } } } return result; } void ossimTiffTileSource::getOutputBandList(std::vector &bandList) const { if (theOutputBandList.size()) { bandList = theOutputBandList; } else { ossimImageSource::getOutputBandList(bandList); } } bool ossimTiffTileSource::isOpen() const { return (theTiffPtr != NULL); } bool ossimTiffTileSource::hasR0() const { return theR0isFullRes; } ossim_float64 ossimTiffTileSource::getMinPixelValue(ossim_uint32 band) const { if (theMetaData.getNumberOfBands()) { return ossimImageHandler::getMinPixelValue(band); } return theMinSampleValue; } ossim_float64 ossimTiffTileSource::getMaxPixelValue(ossim_uint32 band) const { if (theMetaData.getNumberOfBands()) { return ossimImageHandler::getMaxPixelValue(band); } return theMaxSampleValue; } ossim_float64 ossimTiffTileSource::getNullPixelValue(ossim_uint32 band) const { if (theMetaData.getNumberOfBands()) { return ossimImageHandler::getNullPixelValue(band); } return theNullSampleValue; } bool ossimTiffTileSource::isColorMapped() const { bool result = false; std::shared_ptr state = getStateAs(); if (state) { result = state->hasColorMap(TIFFCurrentDirectory(theTiffPtr)); } return result; } void ossimTiffTileSource::setReadMethod() { std::shared_ptr state = getStateAs(); if (state) { for (ossim_uint32 dir = 0; dir < theNumberOfDirectories; ++dir) { //--- // Establish how this tiff directory will be read. //--- if (state->isTiled(dir)) { if ((thePhotometric[dir] == PHOTOMETRIC_YCBCR || thePhotometric[dir] == PHOTOMETRIC_PALETTE) && (theSamplesPerPixel <= 3) && (theBitsPerSample <= 8)) { theReadMethod[dir] = READ_RGBA_U8_TILE; } else { theReadMethod[dir] = READ_TILE; } } else // Not tiled... { if ((thePhotometric[dir] == PHOTOMETRIC_PALETTE || thePhotometric[dir] == PHOTOMETRIC_YCBCR) && theSamplesPerPixel <= 3 && theBitsPerSample <= 8) { theReadMethod[dir] = READ_RGBA_U8_STRIP; } else if ((theBitsPerSample == 16) && (theRowsPerStrip[dir] > 1) && ((thePlanarConfig[dir] == PLANARCONFIG_SEPARATE) || ((thePlanarConfig[dir] == PLANARCONFIG_CONTIG) && (theSamplesPerPixel == 1)))) { // Buffer a strip of bands. theReadMethod[dir] = READ_U16_STRIP; } else if (theSamplesPerPixel <= 3 && theBitsPerSample == 1) { //--- // Note: One bit data expands to zeroes and 255's so run it through // a specialized method to flip zeroes to one's since zeroes // are usually reserved for null value. //--- theReadMethod[dir] = READ_RGBA_U8A_STRIP; } else if ((theCompressionType == COMPRESSION_NONE) || (theRowsPerStrip[dir] == 1)) { theReadMethod[dir] = READ_SCAN_LINE; } else if ((theCompressionType != COMPRESSION_NONE) && (theSamplesPerPixel <= 4) && (theBitsPerSample <= 8)) { theReadMethod[dir] = READ_RGBA_U8_STRIP; } else { theReadMethod[dir] = UNKNOWN; } } } // End of loop through directories. } // Reset the directory back to "0". // setTiffDirectory(0); } void ossimTiffTileSource::setProperty(ossimRefPtr property) { if (!property.valid()) { return; } if (property->getName() == "apply_color_palette_flag") { // Assuming first directory... setApplyColorPaletteFlag(property->valueToString().toBool()); } else { ossimImageHandler::setProperty(property); } } ossimRefPtr ossimTiffTileSource::getProperty(const ossimString &name) const { if (name == "apply_color_palette_flag") { ossimBooleanProperty *property = new ossimBooleanProperty("apply_color_palette_flag", theApplyColorPaletteFlag); property->clearChangeType(); property->setFullRefreshBit(); return property; } else if (name == "file_type") { return new ossimStringProperty(name, "TIFF"); } return ossimImageHandler::getProperty(name); } void ossimTiffTileSource::getPropertyNames(std::vector &propertyNames) const { ossimImageHandler::getPropertyNames(propertyNames); propertyNames.push_back("file_type"); propertyNames.push_back("apply_color_palette_flag"); } bool ossimTiffTileSource::setTiffDirectory(ossim_uint16 directory) { bool status = true; theCurrentTiffRlevel = 0; if (theCurrentDirectory != directory) { status = TIFFSetDirectory(theTiffPtr, directory); if (status == true) { theCurrentDirectory = directory; } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimTiffTileSource::setTiffDirectory ERROR setting directory " << directory << "!" << endl; } } } ossim_uint32 idx = 0; for (idx = 0; idx < theImageDirectoryList.size(); ++idx) { if (theImageDirectoryList[idx] == directory) { theCurrentTiffRlevel = idx; break; } } return status; } void ossimTiffTileSource::populateLut() { std::shared_ptr state = getStateAs(); ossim_uint32 currentDir = TIFFCurrentDirectory(theTiffPtr); std::vector redValues; std::vector greenValues; std::vector blueValues; if (state->getColorMap(redValues, greenValues, blueValues, currentDir)) { ossim_uint16 *r = &redValues.front(); ossim_uint16 *g = &greenValues.front(); ossim_uint16 *b = &blueValues.front(); ossim_uint32 numEntries = redValues.size(); ossimScalarType scalarType = OSSIM_UINT8; if (theBitsPerSample == 16) { scalarType = OSSIM_UINT16; } theLut = new ossimNBandLutDataObject(numEntries, 3, scalarType, 0); ossim_uint32 entryIdx = 0; for (entryIdx = 0; entryIdx < numEntries; ++entryIdx) { if (scalarType == OSSIM_UINT8) { (*theLut)[entryIdx][0] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(((*r) / 65535.0) * 255.0); (*theLut)[entryIdx][1] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(((*g) / 65535.0) * 255.0); (*theLut)[entryIdx][2] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(((*b) / 65535.0) * 255.0); } else { (*theLut)[entryIdx][0] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(*r); (*theLut)[entryIdx][1] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(*g); (*theLut)[entryIdx][2] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(*b); } ++r; ++g; ++b; } } } void ossimTiffTileSource::validateMinMaxNull() { ossim_float64 tempNull = ossim::defaultNull(theScalarType); ossim_float64 tempMax = ossim::defaultMax(theScalarType); ossim_float64 tempMin = ossim::defaultMin(theScalarType); if ((theMinSampleValue == tempNull) || ossim::isnan(theMinSampleValue)) { theMinSampleValue = tempMin; } if ((theMaxSampleValue == tempNull) || ossim::isnan(theMaxSampleValue)) { theMaxSampleValue = tempMax; } if (ossim::isnan(theNullSampleValue)) { theNullSampleValue = tempNull; } if (theScalarType == OSSIM_FLOAT32) { std::ifstream inStr(theImageFile.c_str(), std::ios::in | std::ios::binary); if (inStr.good()) { // Do a print to a memory stream in key:value format. ossimTiffInfo ti; ossimIOMemoryStream memStr; ti.print(inStr, memStr); // Make keywordlist with all the tags. ossimKeywordlist gtiffKwl; if (gtiffKwl.parseStream(memStr)) { #if 0 /* Please keep for debug. (drb) */ if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffTileSource::validateMinMaxNull kwl:\n" << gtiffKwl << endl; } #endif const char *lookup; lookup = gtiffKwl.find("tiff.image0.gdal_nodata"); bool nullFound = false; if (lookup) { ossimString os = lookup; theNullSampleValue = os.toFloat32(); nullFound = true; } lookup = gtiffKwl.find("tiff.image0.vertical_citation"); if (lookup) { //--- // Format of string this handles: // "Null: -9999.000000, Non-Null Min: 12.428605, // Non-Null Avg: 88.944082, Non-Null Max: 165.459558|" ossimString citation = lookup; std::vector array; citation.split(array, ossimString(",")); if (array.size() == 4) { std::vector array2; if (!nullFound) { // null array[0].split(array2, ossimString(":")); if (array2.size() == 2) { ossimString os = array2[0].downcase(); if (os.contains(ossimString("null"))) { if (array2[1].size()) { theNullSampleValue = array2[1].toFloat64(); nullFound = true; } } } } // min array2.clear(); array[1].split(array2, ossimString(":")); if (array2.size() == 2) { ossimString os = array2[0].downcase(); if (os.contains(ossimString("min"))) { if (array2[1].size()) { theMinSampleValue = array2[1].toFloat64(); } } } // Skipping average. // max array2.clear(); array[3].split(array2, ossimString(":")); if (array2.size() == 2) { ossimString os = array2[0].downcase(); if (os.contains(ossimString("max"))) { if (array2[1].size()) { array2[1].trim(ossimString("|")); theMaxSampleValue = array2[1].toFloat64(); } } } } } } } } } bool ossimTiffTileSource::isPowerOfTwoDecimation(ossim_uint32 level) const { // Check size of this level against last level to see if it's half the previous. bool result = false; if ((level > 0) && (theImageWidth.size() > level) && (theImageLength.size() > level)) { ossim_uint32 i = level - 1; // previous level if (((theImageWidth[i] / 2 == theImageWidth[level]) || ((theImageWidth[i] + 1) / 2 == theImageWidth[level])) && ((theImageLength[i] / 2 == theImageLength[level]) || ((theImageLength[i] + 1) / 2 == theImageLength[level]))) { result = true; } } return result; } void ossimTiffTileSource::allocateTile() { theTile = 0; ossim_uint32 bands = 0; if (theOutputBandList.empty()) { bands = getNumberOfOutputBands(); } else { bands = theOutputBandList.size(); } if (bands) { theTile = ossimImageDataFactory::instance()->create(this, getOutputScalarType(), bands); if (theTile.valid()) { theTile->initialize(); // The width and height mus be set prior to call to allocateBuffer. theOutputTileSize.x = theTile->getWidth(); theOutputTileSize.y = theTile->getHeight(); } } } bool ossimTiffTileSource::allocateBuffer() { bool bSuccess = true; // Allocate memory for a buffer to hold data grabbed from the tiff file. ossim_uint32 buffer_size = 0; switch (theReadMethod[theCurrentDirectory]) { case READ_RGBA_U8_TILE: { buffer_size = theInputTileSize[theCurrentDirectory].x * theInputTileSize[theCurrentDirectory].x * theBytesPerPixel * 4; break; } case READ_TILE: { if (thePlanarConfig[theCurrentDirectory] == PLANARCONFIG_CONTIG) { buffer_size = theInputTileSize[theCurrentDirectory].x * theInputTileSize[theCurrentDirectory].y * theBytesPerPixel * theSamplesPerPixel; } else { buffer_size = theInputTileSize[theCurrentDirectory].x * theInputTileSize[theCurrentDirectory].y * theBytesPerPixel; } break; } case READ_RGBA_U8_STRIP: case READ_RGBA_U8A_STRIP: { buffer_size = theImageWidth[0] * theRowsPerStrip[theCurrentDirectory] * theBytesPerPixel * 4; break; } case READ_U16_STRIP: { // Encountered case where it was multiple rows per strip, yet PLANARCONFIG_CONTIG. The // case was in fact single band so planar config is irrelevant. (OLK July 2015) // I put the multiplication back in for the theSamplesPerPixel. In the read method that is used for this // it populates this buffer with all bands and then uses the load method on the image data object. // so all bands has to be populated for the buffer. (GCP Sept 2015) buffer_size = theImageWidth[0] * theRowsPerStrip[theCurrentDirectory] * theBytesPerPixel * theSamplesPerPixel; // I commented this out for this is core dumping for one of the tiff images. (GCP Sept 2015) // if (thePlanarConfig[theCurrentDirectory] == PLANARCONFIG_CONTIG) // buffer_size *= theSamplesPerPixel; break; } case READ_SCAN_LINE: { #if OSSIM_BUFFER_SCAN_LINE_READS // Buffer a image width by tile height. buffer_size = theImageWidth[0] * theBytesPerPixel * theSamplesPerPixel * theOutputTileSize.y; #else buffer_size = theImageWidth[0] * theBytesPerPixel * theSamplesPerPixel; #endif break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "Unknown read method!" << endl; print(ossimNotify(ossimNotifyLevel_WARN)); bSuccess = false; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffTileSource::allocateBuffer DEBUG:" << "\nbuffer_size: " << buffer_size << endl; } theBufferRect.makeNan(); theBufferRLevel = theCurrentDirectory; if (bSuccess && (buffer_size != theBufferSize)) { theBufferSize = buffer_size; if (theBuffer) { delete[] theBuffer; } // ESH 05/2009 -- Fix for ticket #738: // image_info crashing on aerial_ortho image during ingest try { theBuffer = new ossim_uint8[buffer_size]; } catch (...) { theBuffer = 0; bSuccess = false; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimTiffTileSource::allocateBuffer WARN:" << "\nNot enough memory: buffer_size: " << buffer_size << endl; } } } return bSuccess; } ossim-Miami-2.9.1/src/imaging/ossimTiffWriter.cpp000066400000000000000000001516301352751253100217670ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Frank Warmerdam (warmerda@home.com) // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef OSSIM_HAS_GEOTIFF # if OSSIM_HAS_GEOTIFF # include # include # include # include # endif #endif #include #include using namespace std; static ossimTrace traceDebug("ossimTiffWriter:debug"); static const char* TIFF_WRITER_OUTPUT_TILE_SIZE_X_KW = "output_tile_size_x"; static const char* TIFF_WRITER_OUTPUT_TILE_SIZE_Y_KW = "output_tile_size_y"; static const long DEFAULT_JPEG_QUALITY = 75; RTTI_DEF1(ossimTiffWriter, "ossimTiffWriter", ossimImageFileWriter); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimTiffWriter.cpp 22942 2014-11-02 20:39:27Z gpotts $"; #endif ossimTiffWriter::ossimTiffWriter() : ossimImageFileWriter(), theTif(NULL), theCompressionType("none"), theJpegQuality(DEFAULT_JPEG_QUALITY), theOutputGeotiffTagsFlag(true), theColorLutFlag(false), theProjectionInfo(NULL), theOutputTileSize(OSSIM_DEFAULT_TILE_WIDTH, OSSIM_DEFAULT_TILE_HEIGHT), theForceBigTiffFlag(false), theBigTiffFlag(false) { theColorLut = new ossimNBandLutDataObject(); ossim::defaultTileSize(theOutputTileSize); theOutputImageType = "tiff_tiled_band_separate"; #ifdef OSSIM_ID_ENABLED /* to quell unused variable warning. */ if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "OSSIM_ID: " << OSSIM_ID << endl; } #endif } ossimTiffWriter::~ossimTiffWriter() { if(isOpen()) { closeTiff(); } } bool ossimTiffWriter::openTiff() { static const char* MODULE = "ossimTiffWriter::openTiff()"; bool status = false; // Close the existing file pointer. closeTiff(); // Check for empty file name. if ( theFilename.size() ) { //--- // On windows libtiff can treat class tiff offsets as signed(2GB limit) or // unsigned(4GB) so if even close to 2GB (2.1.47 GB) limit make a big tiff. //--- const ossim_uint64 BIGTIFF_THRESHOLD = 2000000000; ossimIrect bounds = theInputConnection->getBoundingRect(); ossim_uint64 byteCheck = (static_cast(bounds.width())* static_cast(bounds.height())* static_cast(theInputConnection->getNumberOfOutputBands())* static_cast(ossim::scalarSizeInBytes(theInputConnection->getOutputScalarType()))); if( byteCheck > BIGTIFF_THRESHOLD ) { theBigTiffFlag = true; } ossimString openMode = "w"; if(theBigTiffFlag||theForceBigTiffFlag) { openMode += "8"; } // Open the new file. theTif = XTIFFOpen( theFilename.c_str(), openMode.c_str() ); if ( theTif ) { status = true; } else { setErrorStatus(); // base class ossimSetError(getClassName().c_str(), ossimErrorCodes::OSSIM_ERROR, "File %s line %d Module %s Error:\n\ Error opening file: %s\n", __FILE__, __LINE__, MODULE, theFilename.c_str()); } } return status; } bool ossimTiffWriter::closeTiff() { if (theTif) { XTIFFClose( (TIFF*)theTif ); theTif = NULL; } return true; } bool ossimTiffWriter::writeTiffTags() { static const char MODULE[] = "ossimTiffWriter::writeTiffTags"; TIFF* tiffPtr = (TIFF*)theTif; if (!tiffPtr) { setErrorStatus(); // base class ossimSetError(getClassName().c_str(), ossimErrorCodes::OSSIM_ERROR, "File %s line %d %s\nError: Tiff pointer is null!\n\ Call setFilename method.\n", __FILE__, __LINE__, MODULE); return false; } //--- // NOTE: // Since the tiff library uses the variable argument list function "va_arg" // it is important to use the correct data type. If in doubt see the // code for libtiff's _TIFFVSetField in "tif_dir.c" in the libtiff package. //--- int bitsPerSample = 0; int sampleFormat = 0; switch( theInputConnection->getOutputScalarType() ) { case OSSIM_UINT8: bitsPerSample = 8; sampleFormat = SAMPLEFORMAT_UINT; break; case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: bitsPerSample = 16; sampleFormat = SAMPLEFORMAT_UINT; break; case OSSIM_SINT16: bitsPerSample = 16; sampleFormat = SAMPLEFORMAT_INT; break; case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: bitsPerSample = 32; sampleFormat = SAMPLEFORMAT_IEEEFP; break; case OSSIM_NORMALIZED_DOUBLE: case OSSIM_FLOAT64: bitsPerSample = 64; sampleFormat = SAMPLEFORMAT_IEEEFP; break; default: return false; } // Set the pixel type. TIFFSetField( (TIFF*)tiffPtr, TIFFTAG_BITSPERSAMPLE, bitsPerSample ); TIFFSetField( (TIFF*)tiffPtr, TIFFTAG_SAMPLEFORMAT, sampleFormat ); // Set the image dimensions. ossim_uint32 width = theAreaOfInterest.width(); ossim_uint32 height = theAreaOfInterest.height(); TIFFSetField( tiffPtr, TIFFTAG_IMAGEWIDTH, width); TIFFSetField( tiffPtr, TIFFTAG_IMAGELENGTH, height); if (isTiled()) { ossim_uint32 tileXSize = theOutputTileSize.x; ossim_uint32 tileYSize = theOutputTileSize.y; TIFFSetField(tiffPtr, TIFFTAG_TILEWIDTH, tileXSize); TIFFSetField(tiffPtr, TIFFTAG_TILELENGTH, tileYSize); } else { // GP: Shouldn't this be theOutputTileSize.y ? //TIFFSetField(tiffPtr, TIFFTAG_ROWSPERSTRIP, ossim_uint32(1)); if(theOutputTileSize.hasNans()) { TIFFSetField(tiffPtr, TIFFTAG_ROWSPERSTRIP, ossim_uint32(1)); } else { TIFFSetField(tiffPtr, TIFFTAG_ROWSPERSTRIP, ossim_uint32(theOutputTileSize.y)); } } ossim_uint32 numberOfBands = theInputConnection->getNumberOfOutputBands(); // Set the min/max values. std::vector minBand(numberOfBands); std::vector maxBand(numberOfBands); for(ossim_uint32 idx = 0; idx < numberOfBands; ++idx) { maxBand[idx] = theInputConnection->getMaxPixelValue(idx); minBand[idx] = theInputConnection->getMinPixelValue(idx); } writeMinMaxTags(minBand, maxBand); // Set the planar configuration. if ( (theOutputImageType == "tiff_strip") || (theOutputImageType == "tiff_tiled") || (theOutputImageType == "image/tiff") || (theOutputImageType == "image/tif") || (theOutputImageType == "image/gtif") || (theOutputImageType == "image/gtiff") ) { TIFFSetField( tiffPtr, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); } else { TIFFSetField( tiffPtr, TIFFTAG_PLANARCONFIG, PLANARCONFIG_SEPARATE); } // Set the compression type: uint16 tiffCompressType = COMPRESSION_NONE; theCompressionType.downcase(); if( theCompressionType == "jpeg") { tiffCompressType = COMPRESSION_JPEG; // Set the jpeg quality. // note the compression type must be set before the quality or you will get an error TIFFSetField( tiffPtr, TIFFTAG_COMPRESSION, tiffCompressType); TIFFSetField( tiffPtr, TIFFTAG_JPEGQUALITY, theJpegQuality); } else if( theCompressionType == "lzw") { tiffCompressType = COMPRESSION_LZW; TIFFSetField( tiffPtr, TIFFTAG_COMPRESSION, tiffCompressType); } else if(theCompressionType == "packbits") { tiffCompressType = COMPRESSION_PACKBITS; TIFFSetField( tiffPtr, TIFFTAG_COMPRESSION, tiffCompressType); } else if((theCompressionType == "deflate") || (theCompressionType == "zip")) { tiffCompressType = COMPRESSION_DEFLATE; TIFFSetField( tiffPtr, TIFFTAG_COMPRESSION, tiffCompressType); } TIFFSetField(tiffPtr, TIFFTAG_SAMPLESPERPIXEL, (int)theInputConnection->getNumberOfOutputBands()); ossimScalarType scalarType = theInputConnection->getOutputScalarType(); bool lutEnabled = (theColorLutFlag&& ((scalarType == OSSIM_UINT8)|| (scalarType == OSSIM_UINT16)|| (scalarType == OSSIM_USHORT11)|| (scalarType == OSSIM_USHORT12)|| (scalarType == OSSIM_USHORT13)|| (scalarType == OSSIM_USHORT14)|| (scalarType == OSSIM_USHORT15))&& (theColorLut->getNumberOfEntries() > 0)&& (theInputConnection->getNumberOfOutputBands() == 1)); if(lutEnabled) { TIFFSetField( tiffPtr, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE ); TIFFSetField( tiffPtr, TIFFTAG_INDEXED, (ossim_uint16)1); if(scalarType == OSSIM_UINT8) { ossim_uint16 r[256], g[256], b[256]; memset(r, '\0', sizeof(ossim_uint16)*256); memset(g, '\0', sizeof(ossim_uint16)*256); memset(b, '\0', sizeof(ossim_uint16)*256); for(ossim_uint32 i = 0; i < theColorLut->getNumberOfEntries(); i++) { r[i] = (ossim_uint16) (((*theColorLut)[i][0]/255.0)*65535); g[i] = (ossim_uint16) (((*theColorLut)[i][1]/255.0)*65535); b[i] = (ossim_uint16) (((*theColorLut)[i][2]/255.0)*65535); } TIFFSetField(tiffPtr, TIFFTAG_COLORMAP, r, g ,b); } else { ossim_uint16 r[65536], g[65536], b[65536]; memset(r, '\0', sizeof(ossim_uint16)*65536); memset(g, '\0', sizeof(ossim_uint16)*65536); memset(b, '\0', sizeof(ossim_uint16)*65536); for(ossim_uint32 i = 0; i < theColorLut->getNumberOfEntries(); i++) { r[i] = (ossim_uint16) ((*theColorLut)[i][0]); g[i] = (ossim_uint16) ((*theColorLut)[i][1]); b[i] = (ossim_uint16) ((*theColorLut)[i][2]); } TIFFSetField(tiffPtr, TIFFTAG_COLORMAP, r, g ,b); } } else if( (theInputConnection->getNumberOfOutputBands() == 3 || theInputConnection->getNumberOfOutputBands() == 4 || (thePhotoMetric == "rgb"))&& (scalarType == OSSIM_UCHAR)) { TIFFSetField( tiffPtr, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB ); } else { TIFFSetField( tiffPtr, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK ); } return true; } bool ossimTiffWriter::writeGeotiffTags(ossimRefPtr projectionInfo) { TIFF* tiffPtr = (TIFF*)theTif; bool result = false; if ( tiffPtr ) { if ( projectionInfo.valid() ) { result = ossimGeoTiff::writeTags(tiffPtr, projectionInfo); } } return result; } void ossimTiffWriter::checkColorLut() { // this code appears to be wrong. We can only do an outo lut if the immediate input to the sequencer is // a handler with a lut or some kind of lut source. // // I think that we should add a flag to enable auto setting of the lut instead of just doing it. This code causes core // dumps if one is to replicate bands with a band selector where a lut is a single band output like a CIB // // I currenlty have to disable // #if 0 bool needColorLut = false; bool needLoop = true; ossimRefPtr colorLut = 0; ossimConnectableObject::ConnectableObjectList imageInputs = theInputConnection->getInputList(); if (imageInputs.size() > 0) { for (ossim_uint32 i = 0; i < imageInputs.size(); i++) { if (needLoop == false) { break; } ossimImageChain* source = PTR_CAST(ossimImageChain, imageInputs[i].get()); if (source) { ossimConnectableObject::ConnectableObjectList imageChains = source->getInputList(); for (ossim_uint32 j = 0; j < imageChains.size(); j++) { if (needLoop == false) { break; } ossimImageChain* imageChain = PTR_CAST(ossimImageChain, imageChains[j].get()); if (imageChain) { ossimConnectableObject::ConnectableObjectList imageHandlers = imageChain->findAllObjectsOfType(STATIC_TYPE_INFO(ossimImageHandler), false); for (ossim_uint32 h= 0; h < imageHandlers.size(); h++) { ossimImageHandler* handler = PTR_CAST(ossimImageHandler, imageHandlers[h].get()); if (handler) { if (handler->getLut() != 0) // { colorLut = handler->getLut(); needColorLut = true; } else //if not all handlers have color luts, ignore the color lut. { needColorLut = false; needLoop = false; break; } } } } } } } } if (needColorLut && colorLut != 0) { setLut(*colorLut.get()); } #endif } bool ossimTiffWriter::writeFile() { static const char MODULE[] = "ossimTiffWriter::writeFile"; if (traceDebug()) CLOG << "Entered..." << std::endl; //checkColorLut(); if(isLutEnabled()) { theNBandToIndexFilter = new ossimNBandToIndexFilter; theNBandToIndexFilter->connectMyInputTo(0, theInputConnection->getInput()); theNBandToIndexFilter->setLut(*theColorLut.get()); theNBandToIndexFilter->initialize(); theInputConnection->disconnect(); theInputConnection->connectMyInputTo(0, theNBandToIndexFilter.get()); theInputConnection->initialize(); } else { theNBandToIndexFilter = 0; } if (traceDebug() && theInputConnection.get()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "DEBUG:" << "\nnull: " << theInputConnection->getNullPixelValue() << "\nmin: " << theInputConnection->getMinPixelValue() << "\nmax: " << theInputConnection->getMaxPixelValue() << std::endl; } if (isTiled()) { if ( (theInputConnection->getTileWidth() != static_cast(theOutputTileSize.x)) || (theInputConnection->getTileHeight() != static_cast(theOutputTileSize.y)) ) { theInputConnection->setTileSize(theOutputTileSize); } } if(!theInputConnection->isMaster()) { theInputConnection->slaveProcessTiles(); if(theNBandToIndexFilter.valid()) { theInputConnection->connectMyInputTo(0, theNBandToIndexFilter->getInput()); theNBandToIndexFilter = 0; } return true; } open(); if (!isOpen()) { if (traceDebug()) { CLOG << " ERROR: Could not open! Returning..." << std::endl; } return false; } if(!theInputConnection) { if (traceDebug()) { CLOG << " ERROR: No input connection! Returning..." << std::endl; } return false; } // First write the tiff tags. if (writeTiffTags() == false) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:" << "\nError detected writing tiff tags. Returning..." << std::endl; return false; } } // Write the geotiff tags. if (theOutputGeotiffTagsFlag) { if(theViewController.get()) // let this override { // found in ossimImageWriter base ossimMapProjection* proj = PTR_CAST(ossimMapProjection, theViewController->getView()); if(proj) { ossimRefPtr projectionInfo = new ossimMapProjectionInfo(proj, theAreaOfInterest); projectionInfo->setPixelType(thePixelType); if (writeGeotiffTags(projectionInfo) == false) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:" << "\nError detected writing geotiff tags. Returning..." << std::endl; } return false; } } } else if(theProjectionInfo.valid()) { theProjectionInfo->setPixelType(thePixelType); if (writeGeotiffTags(theProjectionInfo) == false) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:" << "\nError detected writing geotiff tags. Returning..." << std::endl; } return false; } } else { // Fetch the map projection of the input image if it exists: ossimMapProjection* mapProj = 0; ossimRefPtr imgGeom = theInputConnection->getImageGeometry(); if ( imgGeom.valid() ) { const ossimProjection* proj = imgGeom->getProjection(); mapProj = PTR_CAST(ossimMapProjection, proj); } if(mapProj) { ossimRefPtr projectionInfo = new ossimMapProjectionInfo(mapProj, theAreaOfInterest); projectionInfo->setPixelType(thePixelType); if (writeGeotiffTags(projectionInfo) == false) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:" << "\nError detected writing geotiff tags. Returning..." << std::endl; } return false; } } } } // End of "if (theOutputGeotiffTagsFlag)" // Write the file with the image data. bool status = false; if(theOutputImageType == "tiff_strip") { status = writeToStrips(); } else if(theOutputImageType == "tiff_strip_band_separate") { status = writeToStripsBandSep(); } else if((theOutputImageType == "tiff_tiled")|| (ossimString::downcase(theOutputImageType) == "image/tiff")|| (ossimString::downcase(theOutputImageType) == "image/tif")|| (ossimString::downcase(theOutputImageType) == "image/gtif")|| (ossimString::downcase(theOutputImageType) == "image/gtiff")) { status = writeToTiles(); } else if(theOutputImageType == "tiff_tiled_band_separate") { status = writeToTilesBandSep(); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:" << "\nUnsupported output type: " << theOutputImageType << std::endl; } } close(); if (traceDebug()) CLOG << " Exited..." << std::endl; if(theNBandToIndexFilter.valid()) { theInputConnection->connectMyInputTo(0, theNBandToIndexFilter->getInput()); theNBandToIndexFilter = 0; } return status; } void ossimTiffWriter::setLut(const ossimNBandLutDataObject& lut) { theColorLutFlag = true; theColorLut = (ossimNBandLutDataObject*)lut.dup(); } bool ossimTiffWriter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "output_geotiff_flag", (int)theOutputGeotiffTagsFlag, true); kwl.add(prefix, TIFF_WRITER_OUTPUT_TILE_SIZE_X_KW, theOutputTileSize.x, true); kwl.add(prefix, TIFF_WRITER_OUTPUT_TILE_SIZE_Y_KW, theOutputTileSize.y, true); kwl.add(prefix, ossimKeywordNames::COMPRESSION_QUALITY_KW, theJpegQuality, true); kwl.add(prefix, ossimKeywordNames::COMPRESSION_TYPE_KW, theCompressionType, true); kwl.add(prefix, "color_lut_flag", (ossim_uint32)theColorLutFlag, true); if(theColorLutFlag) { if(theLutFilename != "") { kwl.add(prefix, "lut_filename", theLutFilename.c_str(), true); } else { ossimString newPrefix = ossimString(prefix) + "lut."; theColorLut->saveState(kwl, newPrefix.c_str()); } } return ossimImageFileWriter::saveState(kwl, prefix); } bool ossimTiffWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char *value; ossimIpt defaultTileSize; ossim::defaultTileSize(defaultTileSize); value = kwl.find(prefix, TIFF_WRITER_OUTPUT_TILE_SIZE_X_KW); if(value) { theOutputTileSize.x = ossimString(value).toLong(); if(theOutputTileSize.x<1) { theOutputTileSize.x = defaultTileSize.x; } } value = kwl.find(prefix, TIFF_WRITER_OUTPUT_TILE_SIZE_Y_KW); if(value) { theOutputTileSize.y = ossimString(value).toLong(); if(theOutputTileSize.y<1) { theOutputTileSize.y = defaultTileSize.y; } } value = kwl.find(prefix, ossimKeywordNames::COMPRESSION_TYPE_KW); if(value) { theCompressionType = ossimString(value).downcase(); } else { theCompressionType = "none"; } value = kwl.find(prefix, ossimKeywordNames::COMPRESSION_QUALITY_KW); if(value) { setJpegQuality(ossimString(value).toLong()); } value = kwl.find(prefix, ossimKeywordNames::PHOTOMETRIC_KW); if(value) { thePhotoMetric = ossimString(value).downcase(); } value = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if(value) { setFilename(ossimFilename(value)); } const char* flag = kwl.find(prefix, "output_geotiff_flag"); if(flag) { theOutputGeotiffTagsFlag = ossimString(flag).toBool(); } ossimString newPrefix = ossimString(prefix) + "lut."; const char* colorLutFlag = kwl.find(prefix, "color_lut_flag"); if(colorLutFlag) { theColorLutFlag = ossimString(colorLutFlag).toBool(); } else { theColorLutFlag = false; } theLutFilename = ossimFilename(kwl.find(prefix, "lut_filename")); theLutFilename = ossimFilename(theLutFilename.trim()); if(theLutFilename != "") { theColorLut->open(theLutFilename); } else { theColorLut->loadState(kwl, newPrefix.c_str()); } if(ossimImageFileWriter::loadState(kwl, prefix)) { if((theOutputImageType!="tiff_tiled") && (theOutputImageType!="tiff_tiled_band_separate") && (theOutputImageType!="tiff_strip") && (theOutputImageType!="tiff_strip_band_separate")&& (theOutputImageType!="image/tiff")&& (theOutputImageType!="image/tif")&& (theOutputImageType!="image/gtif")&& (theOutputImageType!="image/gtiff")) { theOutputImageType = "tiff_tiled_band_separate";; } } else { return false; } return true; } bool ossimTiffWriter::isTiled() const { return ( theOutputImageType == "tiff_tiled" || theOutputImageType == "image/tiff" || theOutputImageType == "image/tif" || theOutputImageType == "image/gtif" || theOutputImageType == "image/gtiff" || theOutputImageType == "tiff_tiled_band_separate" ); } bool ossimTiffWriter::writeToTiles() { static const char* const MODULE = "ossimTiffWriter::writeToTiles"; TIFF* tiffPtr = (TIFF*)theTif; if (traceDebug()) CLOG << " Entered." << std::endl; // Start the sequence at the first tile. theInputConnection->setToStartOfSequence(); ossimRefPtr tempTile = 0; if(theColorLutFlag) { tempTile = ossimImageDataFactory::instance()->create(this, 1, theInputConnection.get()); } else { tempTile = ossimImageDataFactory::instance()->create(this, theInputConnection.get()); } if(tempTile.valid()) { tempTile->initialize(); } ossim_uint32 tilesWide = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint32 tilesHigh = theInputConnection->getNumberOfTilesVertical(); ossim_uint32 tileWidth = theInputConnection->getTileWidth(); ossim_uint32 tileHeight = theInputConnection->getTileHeight(); ossim_uint32 numberOfTiles = theInputConnection->getNumberOfTiles(); // Tile loop in the height direction. ossim_uint32 tileNumber = 0; vector minBands; vector maxBands; for(ossim_uint32 i = 0; ((i < tilesHigh)&&!needsAborting()); i++) { ossimIpt origin(0,0); origin.y = i * tileHeight; // Tile loop in the sample (width) direction. for(ossim_uint32 j = 0; ((j < tilesWide)&&!needsAborting()); j++) { origin.x = j * tileWidth; // Grab the tile. ossimRefPtr id = theInputConnection->getNextTile(); if (!id) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "Error returned writing tiff tile: " << tileNumber << "\nNULL Tile encountered" << std::endl; return false; } ossimDataObjectStatus tileStatus = id->getDataObjectStatus(); ossim_uint32 tileSizeInBytes = id->getSizeInBytes(); if (tileStatus != OSSIM_FULL) { // Clear out the buffer since it won't be filled all the way. tempTile->setImageRectangle(id->getImageRectangle()); tempTile->makeBlank(); } if ((tileStatus == OSSIM_PARTIAL || tileStatus == OSSIM_FULL)) { // Stuff the tile into the tileBuffer. id->unloadTile(tempTile->getBuf(), id->getImageRectangle(), OSSIM_BIP); tempTile->setDataObjectStatus(id->getDataObjectStatus()); if(!theColorLutFlag&&!needsAborting()) { id->computeMinMaxPix(minBands, maxBands); } } //--- // Write the tile to disk. //--- ossim_uint32 bytesWritten = 0; bytesWritten = TIFFWriteTile(tiffPtr, tempTile->getBuf(), origin.x, origin.y, 0, // z 0); // s if (bytesWritten != tileSizeInBytes) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:" << "Error returned writing tiff tile: " << i << "\nExpected bytes written: " << tileSizeInBytes << "\nBytes written: " << bytesWritten << std::endl; } setErrorStatus(); return false; } ++tileNumber; } // End of tile loop in the sample (width) direction. double tile = tileNumber; double numTiles = numberOfTiles; setPercentComplete(tile / numTiles * 100); } // End of tile loop in the line (height) direction. if(!theColorLutFlag&&!needsAborting()) { writeMinMaxTags(minBands, maxBands); } if (traceDebug()) CLOG << " Exited." << std::endl; return true; } bool ossimTiffWriter::writeToTilesBandSep() { static const char* const MODULE = "ossimTiffWriter::writeToTilesBandSep"; TIFF* tiffPtr = (TIFF*)theTif; if (traceDebug()) CLOG << " Entered." << std::endl; // Start the sequence at the first tile. theInputConnection->setToStartOfSequence(); ossim_uint32 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint32 tilesWide = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint32 tilesHigh = theInputConnection->getNumberOfTilesVertical(); ossim_uint32 tileWidth = theInputConnection->getTileWidth(); ossim_uint32 tileHeight = theInputConnection->getTileHeight(); ossim_uint32 numberOfTiles = theInputConnection->getNumberOfTiles(); #if 0 if(traceDebug()) { ossimIrect boundingRect = theInputConnection->getBoundingRect(); ossimNotify(ossimNotifyLevel_NOTICE) << "Bounding rect = " << boundingRect << "\nBands = " << bands << "\ntilesWide = " << tilesWide << "\ntilesHigh = " << tilesHigh << "\ntileWidth = " << tileWidth << "\ntileHeight = " << tileHeight << std::endl; } #endif ossim_uint32 tileNumber = 0; vector minBands; vector maxBands; for(ossim_uint32 i = 0; ((i < tilesHigh)&&!needsAborting()); ++i) { ossimIpt origin; origin.y = i * tileHeight; //--- // Tile loop in the sample (width) direction. //--- for(ossim_uint32 j = 0; ((j < tilesWide)&&!needsAborting()); ++j) { origin.x = j * tileWidth; ossimRefPtr id = theInputConnection->getNextTile(); if(!id) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "Error returned writing tiff tile: " << i << "\nNULL Tile encountered" << std::endl; return false; } ossim_int32 tileSizeInBytes = id->getSizePerBandInBytes(); if(!theColorLutFlag) { id->computeMinMaxPix(minBands, maxBands); } //--- // Band loop. //--- for (ossim_uint32 band=0; ((bandgetBuf(band); // Write the tile. tsize_t bytesWritten = 0; if(data) { bytesWritten = TIFFWriteTile(tiffPtr, data, (ossim_uint32)origin.x, (ossim_uint32)origin.y, (ossim_uint32)0, // z (tsample_t)band); // sample } if ( ( bytesWritten != tileSizeInBytes ) && !needsAborting() ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:" << "Error returned writing tiff tile: " << i << "\nExpected bytes written: " << tileSizeInBytes << "\nBytes written: " << bytesWritten << std::endl; } setErrorStatus(); return false; } } // End of band loop. ++tileNumber; } // End of tile loop in the sample (width) direction. double tile = tileNumber; double numTiles = numberOfTiles; setPercentComplete(tile / numTiles * 100); if(needsAborting()) { setPercentComplete(100); } } // End of tile loop in the line (height) direction. if(!theColorLutFlag&&!needsAborting()) { writeMinMaxTags(minBands, maxBands); } if (traceDebug()) CLOG << " Exited." << std::endl; return true; } bool ossimTiffWriter::writeToStrips() { static const char* const MODULE = "ossimTiffWriter::writeToStrips"; TIFF* tiffPtr = (TIFF*)theTif; if (traceDebug()) CLOG << " Entered." << std::endl; // Start the sequence at the first tile. theInputConnection->setToStartOfSequence(); ossim_uint32 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint32 tilesWide = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint32 tilesHigh = theInputConnection->getNumberOfTilesVertical(); ossim_uint32 tileHeight = theInputConnection->getTileHeight(); ossim_uint32 numberOfTiles = theInputConnection->getNumberOfTiles(); ossim_uint32 width = theAreaOfInterest.width(); ossim_uint32 bytesInLine = ossim::scalarSizeInBytes(theInputConnection->getOutputScalarType()) * width * bands; //--- // Buffer to hold one line x tileHeight //--- ossim_uint32 bufferSizeInBytes = bytesInLine * tileHeight; unsigned char* buffer = new unsigned char[bufferSizeInBytes]; int tileNumber = 0; vector minBands; vector maxBands; for(ossim_uint32 i = 0; ((i < tilesHigh)&&(!needsAborting())); ++i) { // Clear the buffer. memset(buffer, 0, bufferSizeInBytes); // Set the buffer rectangle. ossimIrect bufferRect(theAreaOfInterest.ul().x, theAreaOfInterest.ul().y + i * tileHeight, theAreaOfInterest.ul().x + width - 1, theAreaOfInterest.ul().y + i * tileHeight + tileHeight - 1); // Tile loop in the sample (width) direction. for(ossim_uint32 j = 0; ((j < tilesWide)&&(!needsAborting())); ++j) { // Get the tile and copy it to the buffer. ossimRefPtr id = theInputConnection->getNextTile(); if (!id) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "Error returned writing tiff tile: " << tileNumber << "\nNULL Tile encountered" << std::endl; delete [] buffer; return false; } id->unloadTile(buffer, bufferRect, OSSIM_BIP); if(!theColorLutFlag&&!needsAborting()) { id->computeMinMaxPix(minBands, maxBands); } ++tileNumber; } // Get the number of lines to write from the buffer. ossim_uint32 linesToWrite = min(tileHeight, static_cast(theAreaOfInterest.lr().y - bufferRect.ul().y + 1)); // Write the buffer out to disk. ossim_uint32 row = static_cast(bufferRect.ul().y - theAreaOfInterest.ul().y); ossim_uint8* buf = buffer; for (ossim_uint32 ii=0; ((iisetToStartOfSequence(); ossim_uint32 bands = theInputConnection->getNumberOfOutputBands(); ossim_uint32 tilesWide = theInputConnection->getNumberOfTilesHorizontal(); ossim_uint32 tilesHigh = theInputConnection->getNumberOfTilesVertical(); ossim_uint32 tileHeight = theInputConnection->getTileHeight(); ossim_uint32 numberOfTiles = theInputConnection->getNumberOfTiles(); ossim_uint32 width = theAreaOfInterest.width(); ossim_uint32 bytesInLine = ossim::scalarSizeInBytes(theInputConnection->getOutputScalarType()) * width; //--- // Buffer to hold one line x tileHeight //--- ossim_uint32 bufferSizeInBytes = bytesInLine * tileHeight * bands; unsigned char* buffer = new unsigned char[bufferSizeInBytes]; // Tile loop in height direction. ossim_uint32 tileNumber = 0; vector minBands; vector maxBands; for(ossim_uint32 i = 0; ((i < tilesHigh)&&(!needsAborting())); ++i) { // Clear the buffer. memset(buffer, 0, bufferSizeInBytes); // Set the buffer rectangle. ossimIrect bufferRect(theAreaOfInterest.ul().x, theAreaOfInterest.ul().y + i * tileHeight, theAreaOfInterest.ul().x + width - 1, theAreaOfInterest.ul().y + i * tileHeight + tileHeight - 1); // Tile loop in the sample (width) direction. for(ossim_uint32 j = 0; ((j < tilesWide)&&(!needsAborting())); ++j) { // Get the tile and copy it to the buffer. ossimRefPtr id = theInputConnection->getNextTile(); if (!id) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "Error returned writing tiff tile: " << tileNumber << "\nNULL Tile encountered" << std::endl; delete [] buffer; return false; } id->unloadTile(buffer, bufferRect, OSSIM_BIL); if(!theColorLutFlag) { id->computeMinMaxPix(minBands, maxBands); } ++tileNumber; } // Get the number of lines to write from the buffer. ossim_uint32 linesToWrite = min(tileHeight, static_cast(theAreaOfInterest.lr().y - bufferRect.ul().y + 1)); // Write the buffer out to disk. ossim_uint32 row = static_cast(bufferRect.ul().y - theAreaOfInterest.ul().y); ossim_uint8* buf = buffer; for (ossim_uint32 ii=0; ((ii& minBand, const vector& maxBand) { TIFF* tiffPtr = (TIFF*)theTif; if(minBand.size() && maxBand.size()) { ossim_float64 minValue = *std::min_element(minBand.begin(), minBand.end()); ossim_float64 maxValue = *std::max_element(maxBand.begin(), maxBand.end()); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffWriter::writeMinMaxTags DEBUG:" << "\nminValue: " << minValue << "\nmaxValue: " << maxValue << std::endl; } switch( theInputConnection->getOutputScalarType() ) { case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { TIFFSetField( tiffPtr, TIFFTAG_MINSAMPLEVALUE, static_cast(0) ); TIFFSetField( tiffPtr, TIFFTAG_MAXSAMPLEVALUE, static_cast(2047) ); break; } case OSSIM_UINT8: case OSSIM_UINT16: { TIFFSetField( tiffPtr, TIFFTAG_MINSAMPLEVALUE, static_cast(minValue) ); TIFFSetField( tiffPtr, TIFFTAG_MAXSAMPLEVALUE, static_cast(maxValue) ); break; } case OSSIM_SINT16: case OSSIM_UINT32: case OSSIM_FLOAT32: case OSSIM_FLOAT64: case OSSIM_NORMALIZED_FLOAT: case OSSIM_NORMALIZED_DOUBLE: { TIFFSetField( tiffPtr, TIFFTAG_SMINSAMPLEVALUE, static_cast(minValue) ); TIFFSetField( tiffPtr, TIFFTAG_SMAXSAMPLEVALUE, static_cast(maxValue) ); break; } default: { break; } } } } void ossimTiffWriter::setProperty(ossimRefPtr property) { if(!property) { return; } if(property->getName() == ossimKeywordNames::COMPRESSION_QUALITY_KW) { // ossimNumericProperty* numericProperty = PTR_CAST(ossimNumericProperty, // property.get()); // if (numericProperty) // { setJpegQuality( property->valueToString().toInt32() ); // } } else if (property->getName() == ossimKeywordNames::COMPRESSION_TYPE_KW) { ossimStringProperty* stringProperty = PTR_CAST(ossimStringProperty, property.get()); if (stringProperty) { ossimString s; stringProperty->valueToString(s); setCompressionType(s); } } else if(property->getName() == "lut_file") { theLutFilename = ossimFilename(property->valueToString()); theColorLut->open(theLutFilename); } else if(property->getName() == "color_lut_flag") { theColorLutFlag = property->valueToString().toBool(); } else if(property->getName() == "big_tiff_flag") { theForceBigTiffFlag = property->valueToString().toBool(); } else if(property->getName() == ossimKeywordNames::OUTPUT_TILE_SIZE_KW) { theOutputTileSize.x = property->valueToString().toInt32(); theOutputTileSize.y = theOutputTileSize.x; } else { ossimImageFileWriter::setProperty(property); } } ossimRefPtr ossimTiffWriter::getProperty(const ossimString& name)const { ossimRefPtr prop = 0; if (name == "Filename") { prop = ossimImageFileWriter::getProperty(name); if ( prop.valid() ) { ossimRefPtr filenameProp = PTR_CAST(ossimFilenameProperty, prop.get()); if ( filenameProp.valid() ) { filenameProp->addFilter("*.tif"); } prop = filenameProp.get(); } } else if (name == ossimKeywordNames::COMPRESSION_QUALITY_KW) { ossimRefPtr numericProp = new ossimNumericProperty(name, ossimString::toString(theJpegQuality), 1.0, 100.0); numericProp->setNumericType(ossimNumericProperty::ossimNumericPropertyType_INT); prop = numericProp.get(); } else if (name == ossimKeywordNames::COMPRESSION_TYPE_KW) { ossimRefPtr stringProp = new ossimStringProperty(name, getCompressionType(), false); // editable flag stringProp->addConstraint(ossimString("none")); stringProp->addConstraint(ossimString("jpeg")); stringProp->addConstraint(ossimString("lzw")); stringProp->addConstraint(ossimString("packbits")); stringProp->addConstraint(ossimString("deflate")); stringProp->addConstraint(ossimString("zip")); prop = stringProp.get(); } else if (name == "lut_file") { ossimRefPtr property = new ossimFilenameProperty(name, theLutFilename); property->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); prop = property.get(); } else if (name == "color_lut_flag") { prop = new ossimBooleanProperty(name, theColorLutFlag); } else if(name == "big_tiff_flag") { prop = new ossimBooleanProperty(name, theForceBigTiffFlag); } else if( name == ossimKeywordNames::OUTPUT_TILE_SIZE_KW ) { ossimRefPtr stringProp = new ossimStringProperty(name, ossimString::toString(theOutputTileSize.x), false); // editable flag stringProp->addConstraint(ossimString("16")); stringProp->addConstraint(ossimString("32")); stringProp->addConstraint(ossimString("64")); stringProp->addConstraint(ossimString("128")); stringProp->addConstraint(ossimString("256")); stringProp->addConstraint(ossimString("512")); stringProp->addConstraint(ossimString("1024")); stringProp->addConstraint(ossimString("2048")); prop = stringProp.get(); } else { prop = ossimImageFileWriter::getProperty(name); } return prop; } void ossimTiffWriter::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back(ossimString( ossimKeywordNames::COMPRESSION_QUALITY_KW)); propertyNames.push_back(ossimString( ossimKeywordNames::COMPRESSION_TYPE_KW)); propertyNames.push_back(ossimString("lut_file")); propertyNames.push_back(ossimString("color_lut_flag")); propertyNames.push_back(ossimString("big_tiff_flag")); propertyNames.push_back(ossimString(ossimKeywordNames::OUTPUT_TILE_SIZE_KW)); ossimImageFileWriter::getPropertyNames(propertyNames); } bool ossimTiffWriter::isOpen()const { return (theTif!=NULL); } bool ossimTiffWriter::open() { if(theTif) { closeTiff(); } return openTiff(); } void ossimTiffWriter::close() { closeTiff(); } void ossimTiffWriter::setJpegQuality(ossim_int32 quality) { // Range 1 to 100 with 100 being best. if (quality > 0 && quality < 101) { theJpegQuality = quality; } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffWriter::setJpegQuality DEBUG:" << "\nquality out of range: " << quality << "\nquality has been set to default: " << DEFAULT_JPEG_QUALITY << "\nvalid range: 1 to 100 with 100 being best." << std::endl; } theJpegQuality = DEFAULT_JPEG_QUALITY; } } ossim_int32 ossimTiffWriter::getJpegQuality()const { return theJpegQuality; } void ossimTiffWriter::setCompressionType(const ossimString& type) { theCompressionType = type; } ossimString ossimTiffWriter::getCompressionType()const { return theCompressionType; } bool ossimTiffWriter::getGeotiffFlag()const { return theOutputGeotiffTagsFlag; } void ossimTiffWriter::setGeotiffFlag(bool flag) { theOutputGeotiffTagsFlag = flag; } ossimIpt ossimTiffWriter::getOutputTileSize()const { return theOutputTileSize; } ossim_int32 ossimTiffWriter::setProjectionInfo(const ossimMapProjectionInfo& proj) { theProjectionInfo = new ossimMapProjectionInfo(proj); return ossimErrorCodes::OSSIM_OK; } void ossimTiffWriter::getImageTypeList(std::vector& imageTypeList)const { imageTypeList.push_back(ossimString("tiff_strip")); imageTypeList.push_back(ossimString("tiff_strip_band_separate")); imageTypeList.push_back(ossimString("tiff_tiled")); imageTypeList.push_back(ossimString("tiff_tiled_band_separate")); } ossimString ossimTiffWriter::getExtension() const { return ossimString("tif"); } bool ossimTiffWriter::hasImageType(const ossimString& imageType) const { // check for non image type list types // We will support mime type // if((imageType == "image/tiff")|| (imageType == "image/gtiff")|| (imageType == "image/tif")|| (imageType == "image/gtif")) { return true; } return ossimImageFileWriter::hasImageType(imageType); } bool ossimTiffWriter::isLutEnabled()const { return (theColorLutFlag); } ossimTiffWriter::UnitType ossimTiffWriter::getUnitType( ossim_int32 pcsCode, const ossimString& projName) const { if ( ( projName == "ossimCylEquAreaProjection" ) || ( projName == "ossimEquDistCylProjection" ) || ( projName == "ossimLlxyProjection" ) ) { return ANGULAR_DEGREES; } UnitType pcsUnits = getPcsUnitType(pcsCode); UnitType type = UNDEFINED; switch (theLinearUnits) { case OSSIM_METERS: { type = LINEAR_METER; break; } case OSSIM_FEET: { type = LINEAR_FOOT; break; } case OSSIM_US_SURVEY_FEET: { type = LINEAR_FOOT_US_SURVEY; break; } default: { break; } } if (type == UNDEFINED) { return pcsUnits; } return type; } ossimTiffWriter::UnitType ossimTiffWriter::getPcsUnitType(ossim_int32 pcsCode) const { UnitType pcsUnits = UNDEFINED; ossimRefPtr proj = PTR_CAST(ossimMapProjection, ossimEpsgProjectionDatabase::instance()->findProjection((ossim_uint32) pcsCode)); if (proj.valid()) { ossimUnitType type = proj->getProjectionUnits(); if (type == OSSIM_METERS) { pcsUnits = LINEAR_METER; } else { pcsUnits = LINEAR_FOOT_US_SURVEY; } } return pcsUnits; } //************************************************************************************************* // Will take an ossimIMageData tile and write it to disk as a general raster file. //************************************************************************************************* void ossimTiffWriter::dumpTileToFile(ossimRefPtr t, const ossimFilename& f) { ossimRefPtr tile = new ossimMemoryImageSource; tile->setImage(t); ossimRefPtr remapper = new ossimScalarRemapper(tile.get(), OSSIM_UINT8); ossimRefPtr writer = new ossimTiffWriter(); writer->connectMyInputTo(0, remapper.get()); writer->setFilename(f); writer->setGeotiffFlag(false); writer->execute(); writer=0; tile=0; } ossim-Miami-2.9.1/src/imaging/ossimTileCache.cpp000066400000000000000000000112661352751253100215230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: This file contains the cache algorithm // //*********************************** // $Id: ossimTileCache.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include using namespace std; void ossimTileCache::display()const { ossimTileCache::Iterator tiles; for(long buckets = 0; buckets < theNumberOfBuckets; buckets++) { tiles = theCache[buckets].begin(); while(tiles != theCache[buckets].end()) { cout << ((*tiles).second) << endl; ++tiles; } } } ossimTileCache::ossimTileCache(long numberOfBuckets) : theCache(NULL), theNumberOfBuckets(numberOfBuckets>0?numberOfBuckets:255), theSizeInBytes(0) { theCache = new multimap[theNumberOfBuckets]; } ossimTileCache::~ossimTileCache() { deleteAll(); } ossimDataObject* ossimTileCache::get(const ossimDpt3d &origin, unsigned long resLevel) { ossimDataObject* result = NULL; Iterator anIterator; ossim_uint32 bucket = bucketHash(origin); anIterator = theCache[bucket].find(tileId(origin)); while(anIterator != theCache[bucket].end()) { CacheDataPtr info = (*anIterator).second; if(info) { if(info->theOrigin == origin && info->theResLevel == resLevel) { return info->theCachedTile.get(); } } ++anIterator; } return result; } ossimDataObject* ossimTileCache::remove(const ossimDpt3d &origin, unsigned long resLevel) { Iterator anIterator; ossimDataObject *result; ossim_uint32 bucket = bucketHash(origin); anIterator = theCache[bucket].find(tileId(origin)); while(anIterator != theCache[bucket].end()) { CacheDataPtr info = (*anIterator).second; if(info) { if(info->theOrigin == origin && info->theResLevel == resLevel) { theCache[bucket].erase(anIterator); theSizeInBytes -= info->theCachedTile->getDataSizeInBytes(); result = info->theCachedTile.get(); delete info; return result; } } ++anIterator; } return NULL; } ossimDataObject* ossimTileCache::insert(const ossimDpt3d &origin, ossimDataObject* data, unsigned long resLevel) { ossim_uint32 bucket = bucketHash(origin); // make sure we keep up with the current size of the // cache in bytes. This is only the count of the data // and not any overhead required by the cache. theSizeInBytes += data->getDataSizeInBytes(); theCache[bucket].insert(make_pair(tileId(origin), new CacheData(data, origin, resLevel))); return data; } void ossimTileCache::invalidate() { } void ossimTileCache::invalidate(const ossimDpt3d& /* origin */, ossim_uint32 /* resLevel */) { } ossim_uint32 ossimTileCache::tileId(const ossimDpt3d &aPt) { const unsigned char *bufx = (unsigned char*)(&aPt.x); const unsigned char *bufy = (unsigned char*)(&aPt.y); const unsigned char *bufz = (unsigned char*)(&aPt.z); // this just multiplies each byte by some prime number // and add together. return (ossim_uint32)(bufx[0]*101 + bufx[1]*103 + bufx[2]*107 + bufx[3]*109 + bufx[4]*113 + bufx[5]*127 + bufx[6]*131 + bufx[7]*137 + bufy[0]*139 + bufy[1]*149 + bufy[2]*151 + bufy[3]*157 + bufy[4]*163 + bufy[5]*167 + bufy[6]*173 + bufy[7]*179 + bufz[0]*181 + bufz[1]*191 + bufz[2]*193 + bufz[3]*197 + bufz[4]*199 + bufz[5]*211 + bufz[6]*223 + bufz[6]*227); } ossim_uint32 ossimTileCache::bucketHash(const ossimDpt3d &aPt) { return tileId(aPt)%theNumberOfBuckets; } void ossimTileCache::deleteAll() { Iterator anIterator; for(long bucket = 0; bucket < theNumberOfBuckets; bucket++) { anIterator = theCache[bucket].begin(); while(anIterator != theCache[bucket].end()) { CacheDataPtr info = (*anIterator).second; delete info; ++anIterator; } theCache[bucket].clear(); } delete [] theCache; } ossim-Miami-2.9.1/src/imaging/ossimTilePatch.cpp000066400000000000000000000377761352751253100215750ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimTilePatch.cpp 17195 2010-04-23 17:32:18Z dburken $ #include using namespace std; #include #include #include #include #include ossimDiscreteNearestNeighbor ossimTilePatch::nearestNeighborKernel; ossimTilePatch::ossimTilePatch(ossimImageSource* input) { thePatchData = ossimImageDataFactory::instance()->create(NULL, input); thePatchData->initialize(); } ossimTilePatch::ossimTilePatch(ossimScalarType scalarType, long numberOfComponents, long width, long height) :thePatchData(NULL) { thePatchData = ossimImageDataFactory::instance()->create(NULL, scalarType, numberOfComponents, width, height); thePatchData->initialize(); } ossimTilePatch::~ossimTilePatch() { } ossimIrect ossimTilePatch::getRect()const { return thePatchData->getImageRectangle(); } ossimDrect ossimTilePatch::findBoundingRect(const ossimDpt &p1, const ossimDpt &p2, const ossimDpt &p3, const ossimDpt &p4) { vector points(4); points[0] = p1; points[1] = p2; points[2] = p3; points[3] = p4; return ossimDrect(points); } void ossimTilePatch::fillPatch(ossimImageSource* tileSource, long resLevel) { // long w = tileSource->getTileWidth(); // long h = tileSource->getTileHeight(); if(thePatchData.valid()) { ossimIrect rect = thePatchData->getImageRectangle(); thePatchData->makeBlank(); // ossimIpt origin(rect.ul()); ossimRefPtr aTile = tileSource->getTile(rect, resLevel); thePatchData->loadTile(aTile.get()); } } void ossimTilePatch::setData(ossimRefPtr& patchData) { thePatchData = patchData; } void ossimTilePatch::convolve(ossimDiscreteConvolutionKernel* kernel) { if(!kernel) return; long w = thePatchData->getWidth(); long h = thePatchData->getHeight(); long kW = kernel->getWidth(); long kH = kernel->getHeight(); ossimIpt origin = thePatchData->getOrigin(); if( (w < kW) || (h < kH)) { cerr << " Error ossimTilePatch::convolve(kernel): patch is smaller than kernel size" << endl; return; } ossimRefPtr kernelBuffer =(ossimImageData*) thePatchData->dup(); // now let's make the buffer just fit the convolution filter // kernelBuffer->setWidth(w - kW); kernelBuffer->setHeight(h - kH); kernelBuffer->setOrigin(ossimDpt(origin.x + kW/2.0, origin.y + kH/2.0)); kernelBuffer->initialize(); fillTile(kernelBuffer, kernel); kernelBuffer->validate(); // now copy the data back to the buffer // thePatchData->loadTile(kernelBuffer.get()); // now make sure we validate the buffer. thePatchData->validate(); } void ossimTilePatch::fillTile(ossimRefPtr& aTile)const { if(aTile.valid() && (aTile->getNumberOfBands()==thePatchData->getNumberOfBands())&& (aTile->getBuf())&& (thePatchData->getBuf())&& (thePatchData->getScalarType()==aTile->getScalarType())) { aTile->loadTile(thePatchData.get()); } } void ossimTilePatch::fillTile(ossimRefPtr& result, ossimDiscreteConvolutionKernel* kernel)const { if(!kernel) { cerr << "Error: Kernel is NULL in ossimTilePatch::fillTile(tile, kernel)!!" << endl; } if(thePatchData->getScalarType() != result->getScalarType()) { //ERROR return; } else { switch(thePatchData->getScalarType()) { case OSSIM_UCHAR: { fillTileTemplate(static_cast(0), result, kernel); break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { fillTileTemplate(static_cast(0), result, kernel); break; } case OSSIM_SSHORT16: { fillTileTemplate(static_cast(0), result, kernel); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { fillTileTemplate(static_cast(0), result, kernel); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { fillTileTemplate(static_cast(0), result, kernel); break; } default: { ossimSetError("ossimTilePatch", ossimErrorCodes::OSSIM_ERROR, "unhandled scalar type %d", (int)thePatchData->getScalarType()); break; } } } } void ossimTilePatch::fillTile(ossimRefPtr& result, const ossimDpt &ul, const ossimDpt &ur, const ossimDpt &deltaUl, const ossimDpt &deltaUr, const ossimDpt &length)const { result->setNullPix(thePatchData->getNullPix(), thePatchData->getNumberOfBands()); result->setMinPix(thePatchData->getMinPix(), thePatchData->getNumberOfBands()); result->setMaxPix(thePatchData->getMaxPix(), thePatchData->getNumberOfBands()); result->makeBlank(); if(thePatchData->getScalarType() != result->getScalarType()) { //ERROR return; } else { switch(thePatchData->getScalarType()) { case OSSIM_UCHAR: { fillTileTemplate(static_cast(0), result, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { fillTileTemplate(static_cast(0), result, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_SSHORT16: { fillTileTemplate(static_cast(0), result, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { fillTileTemplate(static_cast(0), result, ul, ur, deltaUl, deltaUr, length); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { fillTileTemplate(static_cast(0), result, ul, ur, deltaUl, deltaUr, length); break; } default: { ossimSetError("ossimTilePatch", ossimErrorCodes::OSSIM_ERROR, "unhandled scalar type %d", (int)thePatchData->getScalarType()); break; } } } } template void ossimTilePatch::fillTileTemplate(T /* dummyVariable */, ossimRefPtr& result, ossimDiscreteConvolutionKernel* kernel)const { // get the origin. The convolution could be // an offset into the patch. // ossimIpt startOrigin = result->getOrigin(); // Make sure that the patch is not empty or NULL // ossimDataObjectStatus status = thePatchData->getDataObjectStatus(); if((status==OSSIM_EMPTY)|| (status == OSSIM_NULL)) { return; } ossimDpt startDelta(fabs((double)startOrigin.x - thePatchData->getOrigin().x), fabs((double)startOrigin.y - thePatchData->getOrigin().y)); // let's setup some variables that we will need to do the // convolution algorithm. // ossimIrect patchRect = thePatchData->getImageRectangle(); long tileHeight = result->getHeight(); long tileWidth = result->getWidth(); long outputBands = result->getNumberOfBands(); long convolutionWidth = kernel->getWidth(); long convolutionHeight = kernel->getHeight(); long convolutionOffsetX= convolutionWidth/2; long convolutionOffsetY= convolutionHeight/2; long patchWidth = patchRect.width(); long patchCenterOffset = (long)(patchWidth*startDelta.y + startDelta.x); long patchConvolutionOffsetDelta = patchWidth*convolutionOffsetY + convolutionOffsetX; long patchLineStartOffset = patchCenterOffset - patchConvolutionOffsetDelta; long outputOffset = 0; double min = 1.0; double max = 255.0; if(status == OSSIM_PARTIAL) // must check for NULLS { for(long y = 0; y isNull(patchCenterOffset)) { double convolveResult = 0; for(long b = 0; b < outputBands; ++b) { min=result->getMinPix(b); max=result->getMaxPix(b); T* buf = (T*)(thePatchData->getBuf(b)) + patchCenterOffset; T* outBuf = (T*)(result->getBuf(b)); kernel->convolveSubImage(buf, patchWidth, convolveResult); convolveResult = convolveResult < min?min:convolveResult; convolveResult = convolveResult > max?max:convolveResult; outBuf[outputOffset] = (ossim_uint8)convolveResult; } } else { result->setNull(outputOffset); } ++outputOffset; ++patchCenterOffset; } patchLineStartOffset += patchWidth; } } else { for(long b = 0; b < outputBands; ++b) { double convolveResult = 0; const T* buf = (const T*)thePatchData->getBuf(b); T* outBuf = (T*)(result->getBuf(b)); outputOffset = 0; patchCenterOffset = (long)(patchWidth*startDelta.y + startDelta.x); patchLineStartOffset = patchCenterOffset - patchConvolutionOffsetDelta; min=result->getMinPix(b); max=result->getMaxPix(b); for(long y = 0; y convolveSubImage(&buf[patchCenterOffset], patchWidth, convolveResult); convolveResult = convolveResult < min? min:convolveResult; convolveResult = convolveResult > max?max:convolveResult; outBuf[outputOffset] = (T)convolveResult; ++outputOffset; ++patchCenterOffset; } patchLineStartOffset += patchWidth; } } } } template void ossimTilePatch::fillTileTemplate(T /* dummyVariable */, ossimRefPtr& result, const ossimDpt &ul, const ossimDpt &ur, const ossimDpt &deltaUl, const ossimDpt &deltaUr, const ossimDpt &length)const { double stepSizeWidth = 1.0/length.x; double stepSizeHeight = 1.0/length.y; long patchWidth = thePatchData->getWidth(); long patchHeight = thePatchData->getHeight(); ossimIrect rect = thePatchData->getImageRectangle(); ossimDpt startSave(ul.x - rect.ul().x, ul.y - rect.ul().y ); ossimDpt endSave(ur.x - rect.ul().x, ur.y - rect.ul().y); for(ossim_uint32 band = 0; band < thePatchData->getNumberOfBands(); ++band) { T *resultBuf = (T*)result->getBuf(band); const T *sourceBuf = (T*)thePatchData->getBuf(band); ossimDpt start = startSave; ossimDpt end = endSave; T nullPix = static_cast(result->getNullPix(band)); for(long y = 0; y < length.y; y++) { double deltaX = (end.x - start.x)*stepSizeWidth; double deltaY = (end.y - start.y)*stepSizeHeight; ossimDpt pointXY = start; for(long x = 0; x < length.x; x++) { int xPixel = pointXY.x<0?(int)floor(pointXY.x):(int)pointXY.x; int yPixel = pointXY.y<0?(int)floor(pointXY.y):(int)pointXY.y; if( (xPixel >=0) && (xPixel < patchWidth) && (yPixel >=0) && (yPixel < patchHeight)) { *resultBuf = sourceBuf[yPixel*patchWidth + xPixel]; } else { *resultBuf = nullPix; } resultBuf++; pointXY.y += deltaY; pointXY.x += deltaX; } start.x += deltaUl.x; start.y += deltaUl.y; end.x += deltaUr.x; end.y += deltaUr.y; } } } void ossimTilePatch::setRect(const ossimDpt &p1, const ossimDpt &p2, const ossimDpt &p3, const ossimDpt &p4, const ossimDpt &tile_size, const ossimDpt &padding) { setRect(findBoundingRect(p1, p2, p3, p4), tile_size, padding); } void ossimTilePatch::setRect(const ossimDpt ¢er, const ossimDpt &rect_size, const ossimDpt &tile_size, const ossimDpt &padding) { ossimDpt ul (center - rect_size/2.0); ossimDpt lr (center + rect_size/2.0); ossimDrect rect (ul, lr); setRect(rect, tile_size, padding); } void ossimTilePatch::setRect(const ossimDrect& aRect, const ossimDpt& /* tile_size*/, const ossimDpt& padding) { ossimDpt ul(aRect.ul().x - padding.x, aRect.ul().y - padding.y); ossimDpt lr(aRect.lr().x + padding.x, aRect.lr().y + padding.y); ossimDrect rect(ul, lr); rect.stretchOut(); // rect = alignRectToBoundary(rect, tile_size); if(thePatchData.valid()) { if( ((long)thePatchData->getWidth() != (long)rect.width()) || ((long)thePatchData->getHeight() != (long)rect.height())) { thePatchData->setWidth((long)rect.width()); thePatchData->setHeight((long)rect.height()); } thePatchData->setOrigin(rect.ul()); thePatchData->initialize(); } } ossim-Miami-2.9.1/src/imaging/ossimTiledImageHandler.cpp000066400000000000000000000604641352751253100232100ustar00rootroot00000000000000//************************************************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: // // Image handler used for tile-files when the full image is distributed across multiple files, // as is the case for tiled Quickbird imagery. This is not for use with band-separate formats, // but only "spatially-separate" schemes. // //************************************************************************************************* // $Id: ossimTiledImageHandler.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimTiledImageHandler, "ossimTiledImageHandler", ossimImageHandler) // Static trace for debugging static ossimTrace traceDebug("ossimTiledImageHandler:debug"); //************************************************************************************************* //! Constructor (default): //************************************************************************************************* ossimTiledImageHandler::ossimTiledImageHandler() : m_tileFiles(0), m_tile(0), m_fullImgRect(), #if USING_SUB_OVRS m_startOvrResLevel(-1), m_lockSubOvrs(false) #else m_startOvrResLevel(1) #endif { } //************************************************************************************************* //! Destructor: //************************************************************************************************* ossimTiledImageHandler::~ossimTiledImageHandler() { close(); } //************************************************************************************************* //! Deletes the overview and clears the valid image vertices. Derived //! classes should implement. //************************************************************************************************* void ossimTiledImageHandler::close() { vector::iterator iter = m_tileFiles.begin(); while (iter != m_tileFiles.end()) { (*iter).imageHandler->close(); ++iter; } m_tileFiles.clear(); } //************************************************************************************************* //! Derived classes must implement this method to be concrete. //! @return true if open, false if not. //************************************************************************************************* bool ossimTiledImageHandler::isOpen()const { if (m_tileFiles.size() > 0) return true; return false; } //************************************************************************************************* //! Initialize tile buffer to natch image datatype //************************************************************************************************* void ossimTiledImageHandler::allocate() { m_tile = 0; if ((m_tileFiles.size() == 0)) return; // Just copy the image data tile of the first tile-file: ossimRefPtr h0 = m_tileFiles[0].imageHandler; ossimIrect rect (h0->getBoundingRect()); rect.set_lr(rect.ul() + ossimIpt(h0->getTileWidth()-1, h0->getTileHeight()-1)); ossimRefPtr source_tile = m_tileFiles[0].imageHandler->getTile(rect); if (!source_tile.valid()) { ossimNotify(ossimNotifyLevel_FATAL) << "ossimTiledImageHandler::allocate() -- Could not" "determine file-tile image data for allocating image tile. Aborting."<dup(); } //************************************************************************************************* //! Fills the requested tile by pulling pixels from multiple file tiles as needed. //************************************************************************************************* ossimRefPtr ossimTiledImageHandler::getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel) { // First verify that there are file-tiles available: if (m_tileFiles.size() == 0) return ossimRefPtr(); // Allocate data tile if needed: if(!m_tile.valid()) { allocate(); if(!m_tile.valid()) return ossimRefPtr(); } // Check if res level represents data inside the overall scene overview: if (theOverview.valid() && (resLevel >= m_startOvrResLevel)) return theOverview->getTile(tile_rect, resLevel); // Loop over all tile-files to find which intersect the requested image rect. This necessarily // needs to be done at full res coordinates, so need to adjust by res level requested: ossimDpt decimation_factor; // const ossim_uint32 BANDS = m_tile->getNumberOfBands(); // const ossim_uint32 PPB = m_tile->getSizePerBand(); // pixels per band // bool none_found = true; // ossim_uint32 wd, hd, ws, hs; // m_tile->getWidthHeight(wd, hd); // Always start with blank tile. m_tile->makeBlank(); //--- // Add in the sub image offset if any for the rest of this method to work // correctly. //--- ossimIrect adjusted_tile_rect = tile_rect + m_fullImgRect.ul(); // See if any point of the requested tile is in the image. if ( adjusted_tile_rect.intersects( m_fullImgRect ) ) { // This need to set for loadTile to work off the full image rect. m_tile->setImageRectangle(adjusted_tile_rect); vector::iterator tf_iter = m_tileFiles.begin(); ossimRefPtr source_tile = 0; while (tf_iter != m_tileFiles.end()) { if (( (*tf_iter).subImageRects.size() > resLevel) && adjusted_tile_rect.intersects((*tf_iter).subImageRects[resLevel])) { //--- // Current image handler lies within requested rect, need to adjust // this rect to be relative to this subimage offset before fetching // the tile: //--- ossimIrect full_image_clip_rect = adjusted_tile_rect.clipToRect( (*tf_iter).subImageRects[resLevel]); // Subtract the sub image offset to make zero base image rect. ossimIrect relative_clip_rect( full_image_clip_rect - (*tf_iter).subImageRects[resLevel].ul()); source_tile = (*tf_iter).imageHandler->getTile(relative_clip_rect, resLevel); if ( source_tile.valid() ) { if ( (source_tile->getDataObjectStatus() != OSSIM_NULL) && (source_tile->getDataObjectStatus() != OSSIM_EMPTY) ) { // Give the loadTile the clip rect relative to the full image. m_tile->loadTile( source_tile->getBuf(), full_image_clip_rect, OSSIM_BSQ); m_tile->validate(); if ( m_tile->getDataObjectStatus() == OSSIM_FULL ) { break; } } } } ++tf_iter; } } // Matches: if ( adjusted_tile_rect.intersects( m_fullImgRect ) ) // Set back to zero based rect. m_tile->setImageRectangle(tile_rect); return m_tile; } // Below code was core dumping on tiled DG data. drb - 20160822 #if 0 ossimIrect relative_rect (tile_rect - (*tf_iter).subImageRects[resLevel].ul()); std::cout << "reletive_rect: " << relative_rect << std::endl; source_tile = (*tf_iter).imageHandler->getTile(relative_rect, resLevel); // Quick check to see if a full tile was returned, in which case we can just return that // tile instead of looping below: //if (source_tile->getDataObjectStatus() == OSSIM_FULL) //{ // source_tile->setImageRectangle(tile_rect); // return source_tile; //} // Set the tile's rect back to full image space before saving to the list: source_tile->getWidthHeight(ws, hs); std::cout << "ws: " << ws << " hs: " << hs << " wd: " << wd << " hd: " << hd << std::endl; for (ossim_uint32 band = 0; band < BANDS; ++band) { const ossim_uint16 null_pixel = (ossim_uint16) m_tile->getNullPix(band); const ossim_uint16* s = (const ossim_uint16*) source_tile->getBuf(band); ossim_uint16* d = (ossim_uint16*) m_tile->getBuf(band); ossim_uint32 is = 0; ossim_uint32 id = 0; for (ossim_uint32 y=0; (yvalidate(); } // Matches: if ( tile_rect.intersects( m_fullImgRect ) ) return m_tile; } #endif //************************************************************************************************* //! @param resLevel Reduced resolution level to return lines of. //! Default = 0 //! @return The number of lines for specified reduced resolution level. //************************************************************************************************* ossim_uint32 ossimTiledImageHandler::getNumberOfLines(ossim_uint32 resLevel) const { if (m_fullImgRect.hasNans()) return 0; // Using simple decimation by powers of 2: ossim_uint32 numlines = m_fullImgRect.height() >> resLevel; return numlines; } //************************************************************************************************* //! @param resLevel Reduced resolution level to return samples of. //! Default = 0 //! @return The number of samples for specified reduced resolution level. //************************************************************************************************* ossim_uint32 ossimTiledImageHandler::getNumberOfSamples(ossim_uint32 resLevel) const { if (m_fullImgRect.hasNans()) return 0; // Using simple decimation by powers of 2: ossim_uint32 numsamps = m_fullImgRect.width() >> resLevel; return numsamps; } //************************************************************************************************* //! Method to save the state of an object to a keyword list. //! Return true if ok or false on error. //************************************************************************************************* bool ossimTiledImageHandler::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimImageHandler::saveState(kwl, prefix); } //************************************************************************************************* //! Method to the load (recreate) the state of an object from a keyword //! list. Return true if ok or false on error. //************************************************************************************************* bool ossimTiledImageHandler::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (!ossimImageHandler::loadState(kwl, prefix)) return false; return open(); } //************************************************************************************************* //! Indicates whether or not the image is tiled internally. //! This implementation returns true if (getImageTileWidth() && //! getImageTileHeight()) are both non zero. //! Override in the image handler if something else is desired. //! Returns true if tiled, false if not. //************************************************************************************************* bool ossimTiledImageHandler::isImageTiled() const { return true; } //************************************************************************************************* // Returns the number of bands of the first tile since all tiles need to have the same pixel type. //************************************************************************************************* ossim_uint32 ossimTiledImageHandler::getNumberOfInputBands() const { if ((m_tileFiles.size() == 0) || (!m_tileFiles[0].imageHandler.valid())) return 0; return m_tileFiles[0].imageHandler->getNumberOfInputBands(); } //************************************************************************************************* //! Returns the tile width of the image or 0 if the image is not tiled. //! Note: this is not the same as the ossimImageSource::getTileWidth which //! returns the output tile width which can be different than the internal //! image tile width on disk. //************************************************************************************************* ossim_uint32 ossimTiledImageHandler::getImageTileWidth() const { if ((m_tileFiles.size() == 0) || (!m_tileFiles[0].imageHandler.valid())) return 0; if (m_tileFiles[0].imageHandler->isImageTiled()) return m_tileFiles[0].imageHandler->getImageTileWidth(); return m_tileFiles[0].imageHandler->getNumberOfSamples(); } //************************************************************************************************* //! Returns the tile height of the image or 0 if the image is not tiled. //! Note: this is not the same as the ossimImageSource::getTileHeight which //! returns the output tile height which can be different than the internal //! image tile height on disk. //************************************************************************************************* ossim_uint32 ossimTiledImageHandler::getImageTileHeight() const { if ((m_tileFiles.size() == 0) || (!m_tileFiles[0].imageHandler.valid())) return 0; if (m_tileFiles[0].imageHandler->isImageTiled()) return m_tileFiles[0].imageHandler->getImageTileHeight(); return m_tileFiles[0].imageHandler->getNumberOfLines(); } //************************************************************************************************* //! Returns scalar type of first tile (should be the same for all tiles) //************************************************************************************************* ossimScalarType ossimTiledImageHandler::getOutputScalarType() const { if ((m_tileFiles.size() == 0) || (!m_tileFiles[0].imageHandler.valid())) return OSSIM_SCALAR_UNKNOWN; return m_tileFiles[0].imageHandler->getOutputScalarType(); } //************************************************************************************************* //! Returns overall bounding rect in image space. //************************************************************************************************* ossimIrect ossimTiledImageHandler::getImageRectangle(ossim_uint32 resLevel) const { //--- // Note: Rectangle should be zero based. Sub image offset handled in // getTile and getImageGeometry. drb //--- ossimIrect rect = m_fullImgRect - m_fullImgRect.ul(); if ( resLevel > 0 ) { ossimDpt decimation; getDecimationFactor(resLevel, decimation); rect = rect*decimation; } return rect; #if 0 if (resLevel == 0) return m_fullImgRect; ossimDpt decimation; getDecimationFactor(resLevel, decimation); return m_fullImgRect*decimation; #endif } #if USING_SUB_OVRS //************************************************************************************************* // Overrides base class //************************************************************************************************* void ossimTiledImageHandler::completeOpen() { openOverview(); openValidVertices(); } //************************************************************************************************* //! Will build over files, one for each tile file. //! @param includeFullResFlag if true the full resolution layer will also //! be put in the overview format. This is handy for inefficient formats. //************************************************************************************************* bool ossimTiledImageHandler::buildOverview(ossimImageHandlerOverviewCompressionType ctype, ossim_uint32 qual, ossimFilterResampler::ossimFilterResamplerType rtype, bool ifr_flag) { if (m_tileFiles.size() == 0) return false; bool all_ok = true; vector::iterator iter = m_tileFiles.begin(); while ((iter != m_tileFiles.end()) && all_ok) { if (!(*iter).imageHandler->hasOverviews()) { ossimNotify(ossimNotifyLevel_INFO)<<"\nBuilding overview for <" <<(*iter).imageHandler->getFilename()<<">"<buildOverview(ctype, qual, rtype, ifr_flag); } ++iter; } // Overviews for subimage tile-files have been processed. However, we need to check the // preferences for the overview stop dimension to see if we need additional decimation of the // overall scene to achieve the final desired dimension. ossimString stop_dim_str = ossimPreferences::instance()->findPreference(ossimKeywordNames::OVERVIEW_STOP_DIMENSION_KW); if (!stop_dim_str.empty()) { ossim_uint32 stop_dim = stop_dim_str.toUInt32(); ossimDpt decimation = theDecimationFactors.back(); ossim_uint32 nlines = decimation.y * m_fullImgRect.height(); ossim_uint32 nsamps = decimation.x * m_fullImgRect.width(); if ((nlines > stop_dim) || (nsamps > stop_dim)) { // Need to continue decimating. These decimations are stored in an overall scene file. // Need subimage OVRs open for this next operation: openOverview(); ossimTiffOverviewBuilder tob; tob.setInputSource(this); theOverviewFile = getFilenameWithThisExtension("ovr"); // This magically takes over where we left off in decimating: if (tob.buildOverview(theOverviewFile)) { // Overview was successfully written, now open it: theOverview = new ossimTiffTileSource; all_ok = openOverview(); } } } return all_ok; } //************************************************************************************************* // Will open overview files for all tile files. Actually, the tile-files will already have opened // their individual overviews, so this method only verifies the fact and initializes the // associated subimage rects at all decimation levels. //************************************************************************************************* bool ossimTiledImageHandler::openOverview() { if (m_tileFiles.size() == 0) return false; theDecimationFactors.clear(); bool all_ok = true; ossimRefPtr handler = 0; vector factors; ossim_uint32 min_num_rlevels = 999; // Loop over all tile-files to verify their OVR was opened and to calculate the associated // subimage rects at each res level: vector::iterator iter = m_tileFiles.begin(); while ((iter != m_tileFiles.end()) && all_ok) { handler = (*iter).imageHandler; if (!handler.valid()) { ++iter; continue; } if ((*iter).subImageRects.size() == 0) { ossimNotify(ossimNotifyLevel_INFO)<<"\nBounding image rectangle not defined for <" <<(*iter).imageHandler->getFilename()<<">! Cannot proceed with overviews."<getOverview()) { // Only verified that overview for tile-file was opened. Check number of decimation levels // to latch minimum: (*iter).overviewIsOpen = true; handler->getDecimationFactors(factors); if (factors.size() < min_num_rlevels) min_num_rlevels = (ossim_uint32) factors.size(); // Need to determine the sub image rects at each decimation level: ossimIrect subRectR0 ((*iter).subImageRects[0]); for (ossim_uint32 i=1; i<(ossim_uint32)factors.size(); i++) { ossimIrect r (factors[i].x * subRectR0.ul().x, factors[i].y * subRectR0.ul().y, factors[i].x * subRectR0.lr().x, factors[i].y * subRectR0.lr().y); (*iter).subImageRects.push_back(r); } } else { ossimNotify(ossimNotifyLevel_INFO)<<"\nNo overview available for <" <<(*iter).imageHandler->getFilename()<<">"<getDecimationFactors(theDecimationFactors); theDecimationFactors.resize(min_num_rlevels); } // Check for overall scene overview file, that takes over where the individual tile-file // overviews leave off: theOverviewFile = getFilenameWithThisExtension("ovr"); if (!theOverviewFile.exists()) theOverviewFile.setExtension("OVR"); if (theOverviewFile.exists()) { m_lockSubOvrs = true; // prevent closing and reopening of subimage ovrs ossimImageHandler::openOverview(theOverviewFile); m_lockSubOvrs = false; // reset if (theOverview.valid()) { vector extra_decimations; theOverview->getDecimationFactors(extra_decimations); if (extra_decimations.size()) { // Obtain the decimations and add it to our decimation list: m_startOvrResLevel = (ossim_uint32) theDecimationFactors.size(); ossimDpt start_decimation (theDecimationFactors.back() * 0.5); ossimDpt decimation; for (ossim_uint32 i=0; i::iterator iter = m_tileFiles.begin(); while ((iter != m_tileFiles.end())) { if ((*iter).imageHandler.valid()) (*iter).imageHandler->closeOverview(); ++iter; } } } //************************************************************************************************* //! Will return TRUE if all tile files have overviews. //************************************************************************************************* bool ossimTiledImageHandler::hasOverviews() const { bool all_have_ovrs = true; vector::const_iterator iter = m_tileFiles.begin(); while ((iter != m_tileFiles.end()) && all_have_ovrs) { if (((*iter).imageHandler.valid()) && !((*iter).imageHandler->hasOverviews())) all_have_ovrs = false; ++iter; } return all_have_ovrs; } //************************************************************************************************* //! Returns the number of decimation (resolution) levels. This is the minimum number //! among all sub-image tile-files. //************************************************************************************************* ossim_uint32 ossimTiledImageHandler::getNumberOfDecimationLevels() const { return (ossim_uint32) theDecimationFactors.size(); } #endif /* #if USING_SUB_OVRS */ ossim-Miami-2.9.1/src/imaging/ossimTiledImagePatch.cpp000066400000000000000000000142261352751253100226650ustar00rootroot00000000000000//--- // License: MIT // // Author: David Burken // // Description: // // Class to fill a patch from input tiles requested on even tile boundaries with // a tile size typically matching the input, with some output tile size // different from the input. // //--- // $Id$ #include #include #include RTTI_DEF1(ossimTiledImagePatch, "ossimTiledImagePatch", ossimImageSourceFilter) ossimTiledImagePatch::ossimTiledImagePatch() : ossimImageSourceFilter(), // base class m_tile(0), m_inputTileSize() { m_inputTileSize.makeNan(); } ossimTiledImagePatch::~ossimTiledImagePatch() { } void ossimTiledImagePatch::initialize() { //--- // Call the base class initialize. // Note: This will reset "theInputConnection" if it changed... //--- ossimImageSourceFilter::initialize(); // Clear everything. The tile will be allocated on first getTile call. m_tile = 0; // Get the input tile sizes: if ( theInputConnection ) { if ( m_inputTileSize.hasNans() ) { m_inputTileSize.x = theInputConnection->getTileWidth(); m_inputTileSize.y = theInputConnection->getTileHeight(); } } } ossimRefPtr ossimTiledImagePatch::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if ( m_tile.valid() == false ) { allocateTile(); // First time through... } if ( m_tile.valid() ) { // Image rectangle must be set prior to calling getTile. m_tile->setImageRectangle(tileRect); if ( getTile( m_tile.get(), resLevel ) == false ) { if (m_tile->getDataObjectStatus() != OSSIM_NULL) { m_tile->makeBlank(); } } } return m_tile; } bool ossimTiledImagePatch::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; if ( isSourceEnabled() && theInputConnection && isValidRLevel(resLevel) && result && (m_inputTileSize.hasNans() == false) ) { status = true; // See if any point of the requested tile is in the image. ossimIrect tile_rect = result->getImageRectangle(); ossimIrect input_rect; theInputConnection->getBoundingRect( input_rect, resLevel ); if ( tile_rect.intersects( input_rect ) ) { // Initialize the tile if needed as we're going to stuff it. if (result->getDataObjectStatus() == OSSIM_NULL) { result->initialize(); } // If empty imput tiles are pulled the entire output tile might not be filled. result->makeBlank(); // Clip rect: ossimIrect clip_rect = tile_rect.clipToRect( input_rect ); // Zero based start point. ossimIpt inputOrigin = clip_rect.ul() - input_rect.ul(); // Zero based point on input tile boundary. inputOrigin.x = (inputOrigin.x / m_inputTileSize.x) * m_inputTileSize.x; inputOrigin.y = (inputOrigin.y / m_inputTileSize.y) * m_inputTileSize.y; // Shift back to original space: inputOrigin += input_rect.ul(); // Line loop: for ( ossim_int32 y = inputOrigin.y; y < clip_rect.lr().y; y += m_inputTileSize.y ) { // Sample loop: for ( ossim_int32 x = inputOrigin.x; x < clip_rect.lr().x; x += m_inputTileSize.x ) { ossimIrect rect( x, y, x + m_inputTileSize.x - 1, y + m_inputTileSize.y - 1 ); ossimRefPtr tile = theInputConnection->getTile( rect, resLevel ); if ( tile.valid() ) { if ( (tile->getDataObjectStatus() != OSSIM_NULL) && (tile->getDataObjectStatus() != OSSIM_EMPTY) ) { result->loadTile( tile.get() ); } } } } result->validate(); } else { // No part of requested tile within the image rectangle. result->makeBlank(); } } // matches: if( isOpen() && isSourceEnabled() && isValidRLevel(level) ) return status; } ossimString ossimTiledImagePatch::getClassName() const { return ossimString("ossimTiledImagePatch"); } ossimString ossimTiledImagePatch::getLongName()const { return ossimString("OSSIM tiled image patch"); } ossimString ossimTiledImagePatch::getShortName()const { return ossimString("tiled_image_patch"); } const ossimIpt& ossimTiledImagePatch::getInputTileSize() const { return m_inputTileSize; } bool ossimTiledImagePatch::setInputTileSize( const ossimIpt& tileSize ) { bool status = true; if ( ( tileSize.hasNans() == false ) && (tileSize.x > 0) && (tileSize.y > 0) ) { m_inputTileSize = tileSize; } else { m_inputTileSize.makeNan(); status = false; } return status; } bool ossimTiledImagePatch::loadState(const ossimKeywordlist& kwl, const char* prefix) { std::string myPrefix = (prefix ? prefix : "" ); std::string key = "tile_size"; std::string value = kwl.findKey( myPrefix, key ); if ( value.size() ) { m_inputTileSize.toPoint( value ); } return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimTiledImagePatch::saveState(ossimKeywordlist& kwl, const char* prefix)const { std::string myPrefix = (prefix ? prefix : "" ); std::string key = "tile_size"; kwl.addPair( myPrefix, key, m_inputTileSize.toString().string() ); return ossimImageSourceFilter::saveState(kwl, prefix); } void ossimTiledImagePatch::allocateTile() { m_tile = ossimImageDataFactory::instance()->create(this,this); m_tile->initialize(); } bool ossimTiledImagePatch::isValidRLevel(ossim_uint32 resLevel) const { // return (resLevel < m_inputBoundingRect.size()); return (resLevel < theInputConnection->getNumberOfDecimationLevels()); } // Private to disallow use... ossimTiledImagePatch::ossimTiledImagePatch(const ossimTiledImagePatch&) : m_tile(0), m_inputTileSize() { } // Private to disallow use... ossimTiledImagePatch& ossimTiledImagePatch::operator=(const ossimTiledImagePatch&) { return *this; } ossim-Miami-2.9.1/src/imaging/ossimTiling.cpp000066400000000000000000000707371352751253100211400ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2004 Garrett Potts // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: implementation for image generator // //************************************************************************* // $Id: ossimTiling.cpp 22668 2014-03-10 16:52:03Z dburken $ #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimTiling:debug"); RTTI_DEF1(ossimTiling, "ossimTiling", ossimObject); ossimTiling::ossimTiling() :theTilingDistance(0,0), theTilingDistanceUnitType(OSSIM_UNIT_UNKNOWN), theDelta(0,0), theDeltaType(ossimTilingDeltaType_TOTAL_PIXELS), theOutputSizeInBytes(0), theNumberOfBands(1), theNumberOfBytesPerPixelPerBand(1), thePaddingSizeInPixels(0.0, 0.0), theMapProjection(), theImageRect(), theTilingRect(), theTileId(-1), theTotalHorizontalTiles(0), theTotalVerticalTiles(0), theTotalTiles(0), theTileNameMask(), theEdgeToEdgeFlag(false) { } bool ossimTiling::initialize(const ossimMapProjection& proj, const ossimIrect& boundingRect) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiling::initialize DEBUG: Entered..." << "\nBounding rect === " << boundingRect << std::endl; } bool result = true; theMapProjection = (ossimMapProjection*)proj.dup(); theImageRect = boundingRect; result = validate(); ossimDpt convertedTilingDistance = theTilingDistance; if(result) { // Let's setup the bounding tile rect. if(theTilingDistanceUnitType != OSSIM_PIXEL) { getConvertedTilingDistance(convertedTilingDistance); if(theMapProjection->isGeographic()) { ossimGpt ul; ossimGpt ur; ossimGpt lr; ossimGpt ll; theMapProjection->lineSampleToWorld(theImageRect.ul(), ul); theMapProjection->lineSampleToWorld(theImageRect.ur(), ur); theMapProjection->lineSampleToWorld(theImageRect.lr(), lr); theMapProjection->lineSampleToWorld(theImageRect.ll(), ll); theTilingRect = ossimDrect(ossimDpt(ul), ossimDpt(ur), ossimDpt(lr), ossimDpt(ll), OSSIM_RIGHT_HANDED); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Geographic input bounds = " << theTilingRect << std::endl; } theTilingRect.stretchToTileBoundary(convertedTilingDistance); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Geographic input bounds stretched = " << theTilingRect << std::endl; } clampGeographic(theTilingRect); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Geographic input bounds clamped = " << theTilingRect << std::endl; } } // End "if(theMapProjection->isGeographic())" else // meters { ossimDpt ul; ossimDpt ur; ossimDpt lr; ossimDpt ll; theMapProjection->lineSampleToEastingNorthing(theImageRect.ul(), ul); theMapProjection->lineSampleToEastingNorthing(theImageRect.ur(), ur); theMapProjection->lineSampleToEastingNorthing(theImageRect.lr(), lr); theMapProjection->lineSampleToEastingNorthing(theImageRect.ll(), ll); theTilingRect = ossimDrect(ul, ur, lr, ll, OSSIM_RIGHT_HANDED); theTilingRect.stretchToTileBoundary(convertedTilingDistance); } } else { ossim_int32 remainderX = (ossim_int32)((theImageRect.width()%((ossim_int32)theDelta.x)) != 0); ossim_int32 remainderY = (ossim_int32)((theImageRect.height()%((ossim_int32)theDelta.y)) != 0); ossim_int32 w = (ossim_int32)((theImageRect.width()/(ossim_int32)theDelta.x)*theDelta.x + (remainderX*theDelta.x)); ossim_int32 h = (ossim_int32)((theImageRect.height()/(ossim_int32)theDelta.y)*theDelta.y + (remainderY*theDelta.y)); theTilingRect = ossimDrect(theImageRect.ul().x, theImageRect.ul().y, theImageRect.ul().x + (w-1), theImageRect.ul().y + (h-1)); // since we are pixel space we force delta to be 1 pixel unit // theDelta.x = 1.0; theDelta.y = 1.0; theDeltaType = ossimTilingDeltaType_PER_PIXEL; } } theTotalHorizontalTiles = ossim::round(fabs(theTilingRect.ur().x - theTilingRect.ul().x)/convertedTilingDistance.x); theTotalVerticalTiles = ossim::round(fabs(theTilingRect.ur().y - theTilingRect.lr().y)/convertedTilingDistance.y); theTotalTiles = theTotalHorizontalTiles*theTotalVerticalTiles; // reset the tile id to the beginning // reset(); if(traceDebug()) { print(ossimNotify(ossimNotifyLevel_DEBUG)); ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimTiling::initialize DEBUG: Leaving..." << std::endl; } return result; } bool ossimTiling::next(ossimRefPtr& resultProjection, ossimIrect& resultingBounds, ossimString& resultingName)const { bool result = true; if(theTileId < theTotalTiles) { ossimDpt origin; ossim_int64 row=0; ossim_int64 col=0; getRowCol(row, col, theTileId); getTileName(resultingName, row, col, theTileId); getOrigin(origin, row, col); if(theTilingDistanceUnitType == OSSIM_PIXEL) { ossimIpt ul = origin; resultingBounds = ossimIrect(ul.x - (ossim_int32)thePaddingSizeInPixels.x, ul.y - (ossim_int32)thePaddingSizeInPixels.y, ul.x + ((ossim_int32)theTilingDistance.x-1) + (ossim_int32)thePaddingSizeInPixels.x, ul.y + ((ossim_int32)theTilingDistance.y-1) + (ossim_int32)thePaddingSizeInPixels.y); } else { ossimDpt deltaPerPixel = getDeltaPerPixel(); ossimIpt pixels; if(theDeltaType == ossimTilingDeltaType_TOTAL_PIXELS) { pixels = theDelta; } else { pixels = ossimDpt(theTilingDistance.x/theDelta.x, theTilingDistance.y/theDelta.y); } if(theMapProjection->isGeographic()) { if ( theEdgeToEdgeFlag ) { theMapProjection->setUlTiePoints( ossimGpt( origin.lat - (deltaPerPixel.y/2.0), origin.lon + (deltaPerPixel.x/2.0), 0.0, theMapProjection->origin().datum()) ); } else { theMapProjection->setUlTiePoints( ossimGpt(origin.lat, origin.lon, 0.0, theMapProjection->origin().datum())); } theMapProjection->setDecimalDegreesPerPixel(deltaPerPixel); } else { if ( theEdgeToEdgeFlag ) { theMapProjection->setUlTiePoints( ossimDpt( origin.x + (deltaPerPixel.x/2.0), origin.y - (deltaPerPixel.y/2.0) ) ); } else { theMapProjection->setUlTiePoints(ossimDpt(origin.x, origin.y)); } theMapProjection->setMetersPerPixel(deltaPerPixel); } resultingBounds = ossimIrect(-(ossim_int32)thePaddingSizeInPixels.x, -(ossim_int32)thePaddingSizeInPixels.y, (pixels.x-1) + (ossim_int32)thePaddingSizeInPixels.x, (pixels.y-1) + (ossim_int32)thePaddingSizeInPixels.y); } resultProjection = theMapProjection; ++theTileId; if(traceDebug()&&resultProjection.valid()) { ossimKeywordlist projKwl; resultProjection->saveState(projKwl); ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiling::next DEBUG: rect = " << resultingBounds << "\nproj = " << projKwl << "\ntileName = " << resultingName << "\norigin = " << origin << std::endl; } } else { result = false; } return result; } void ossimTiling::reset() { theTileId = 0; } void ossimTiling::setTilingDistance(const ossimDpt& tilingDistance, ossimUnitType unitType) { theTilingDistance = tilingDistance; theTilingDistanceUnitType = unitType; } void ossimTiling::setDelta(const ossimDpt& delta, ossimTilingDeltaType deltaType) { theDelta = delta; theDeltaType = deltaType; } bool ossimTiling::validate()const { bool result = true; if(theMapProjection.valid()) { if(theMapProjection->isGeographic()) { switch(theTilingDistanceUnitType) { case OSSIM_DEGREES: case OSSIM_RADIANS: case OSSIM_SECONDS: case OSSIM_MINUTES: case OSSIM_PIXEL: { break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimTiling::validate()\n" << "Map projeciton requires tiling in angular units but the" << "\nspacing is in non angular" << std::endl; result = false; } } } else { switch(theTilingDistanceUnitType) { case OSSIM_METERS: case OSSIM_FEET: case OSSIM_US_SURVEY_FEET: case OSSIM_NAUTICAL_MILES: case OSSIM_PIXEL: case OSSIM_MILES: case OSSIM_MILLIMETERS: { break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimTiling::validate()" << "\nMap projeciton requires tiling using linear spacing" << " but the spacing is in non linear" << std::endl; result = false; } } } } else { result = false; ossimNotify(ossimNotifyLevel_WARN) << "ossimTiling::validate()" << "\nthe image projection is null and so not valid" << std::endl; } if((theDelta.x <= FLT_EPSILON) || (theDelta.y <= FLT_EPSILON)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimTiling::validate() the delta is too small or is negative" << "value = " << theDelta << std::endl; result = false; } if((theTilingDistance.x <= FLT_EPSILON)|| (theTilingDistance.y <= FLT_EPSILON)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimTiling::validate()" << "\nthe tiling distance is too small or is negative" << "Value = " << theTilingDistance << std::endl; } if(theImageRect.hasNans()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimTiling::validate() the image rect has nans" << std::endl; result = false; } return result; } bool ossimTiling::isAngularUnit(ossimUnitType unitType)const { bool result = false; switch(unitType) { case OSSIM_DEGREES: case OSSIM_RADIANS: case OSSIM_SECONDS: case OSSIM_MINUTES: { result = true; break; } default: { break; } } return result; } bool ossimTiling::isLinearUnit(ossimUnitType unitType)const { bool result = false; switch(unitType) { case OSSIM_METERS: case OSSIM_FEET: case OSSIM_US_SURVEY_FEET: case OSSIM_NAUTICAL_MILES: case OSSIM_MILES: case OSSIM_MILLIMETERS: { result = true; break; } default: { break; } } return result; } void ossimTiling::setTileNameMask(const ossimString& mask) { if(theTileNameMask == "") { theTileNameMask = "tile%i%"; } if(mask.contains("%i%")|| mask.contains("%oc%")|| mask.contains("%or%")|| mask.contains("%r%")|| mask.contains("%c%")|| mask.contains("%SRTM%")) { theTileNameMask = mask; } else { theTileNameMask += "%i%"; } } ossimString ossimTiling::getTileNameMask()const { return theTileNameMask; } bool ossimTiling::getRowCol(ossim_int64& row, ossim_int64& col, ossim_int64 tileId)const { bool result = true; if((theTotalHorizontalTiles > 0)&& (tileId < theTotalTiles)) { row = tileId/static_cast(theTotalHorizontalTiles); col = tileId%static_cast(theTotalHorizontalTiles); if((col >= static_cast(theTotalHorizontalTiles)) && (row >= static_cast(theTotalVerticalTiles))) { result = false; } } return result; } bool ossimTiling::getOrigin(ossimDpt& origin, ossim_int64 tileId)const { ossim_int64 row=0; ossim_int64 col=0; bool result = getRowCol(row, col, tileId); if(result) { result = getOrigin(origin, row, col); } return result; } bool ossimTiling::getOrigin(ossimDpt& origin, ossim_int64 row, ossim_int64 col)const { bool result = false; if((col < static_cast(theTotalHorizontalTiles)) && (row < static_cast(theTotalVerticalTiles))) { ossimDpt convertedTilingDistance; getConvertedTilingDistance(convertedTilingDistance); result = true; if(theTilingRect.orientMode() == OSSIM_RIGHT_HANDED) { origin.x = theTilingRect.ul().x + col*convertedTilingDistance.x; origin.y = theTilingRect.ul().y - row*convertedTilingDistance.y; } else { origin.x = theTilingRect.ul().x + col*convertedTilingDistance.x; origin.y = theTilingRect.ul().y + row*convertedTilingDistance.y; } } return result; } ossimDpt ossimTiling::getDeltaPerPixel()const { ossimDpt result = theDelta; if (!theMapProjection) { return result; } if(theDeltaType == ossimTilingDeltaType_TOTAL_PIXELS) { result = ossimDpt(theTilingDistance.x/theDelta.x, theTilingDistance.y/theDelta.y); } ossimUnitConversionTool unitConverter(theMapProjection->origin(), 1.0, theTilingDistanceUnitType); if(theMapProjection->isGeographic()) { unitConverter.setValue(result.x, theTilingDistanceUnitType); result.x = unitConverter.getValue(OSSIM_DEGREES); unitConverter.setValue(result.y, theTilingDistanceUnitType); result.y = unitConverter.getValue(OSSIM_DEGREES); } else { unitConverter.setValue(result.x, theTilingDistanceUnitType); result.x = unitConverter.getValue(OSSIM_METERS); unitConverter.setValue(result.y, theTilingDistanceUnitType); result.y = unitConverter.getValue(OSSIM_METERS); } return result; } void ossimTiling::getTileName(ossimString& resultingName, ossim_int64 row, ossim_int64 col, ossim_int64 id)const { if(theTileNameMask == "") { ostringstream idString; idString << id; resultingName = ossimString("tile") + idString.str().c_str(); } else if(theTileNameMask.contains("%SRTM%")) { // must be a 1x1 degree tiling distance // if((theTilingDistanceUnitType == OSSIM_DEGREES)&& (theTilingDistance.x == 1.0)&& (theTilingDistance.x == 1.0)) { ostringstream latString; ostringstream lonString; resultingName = ""; ossimDpt origin; getOrigin(origin, row, col); // the name is lower left and not upper left // subtract one degree // origin.lat -=1; latString << setfill('0') << setw(2) << fabs(origin.lat); lonString << setfill('0') << setw(3) << fabs(origin.lon); if(origin.lat < 0.0) { resultingName += "S"; } else { resultingName += "N"; } resultingName += latString.str().c_str(); if(origin.lon < 0.0) { resultingName += "W"; } else { resultingName += "E"; } resultingName += lonString.str().c_str(); resultingName += ".hgt"; } } else { ostringstream rowString; ostringstream colString; ostringstream idString; ostringstream oRowString; ostringstream oColString; ossimDpt origin; getOrigin(origin, row, col); rowString << row; colString << col; idString << id; oRowString << row; oColString << col; resultingName = theTileNameMask; resultingName = resultingName.substitute("%r%", rowString.str().c_str()); resultingName = resultingName.substitute("%c%", colString.str().c_str()); resultingName = resultingName.substitute("%i%", idString.str().c_str()); resultingName = resultingName.substitute("%oc", oColString.str().c_str()); resultingName = resultingName.substitute("%or", oRowString.str().c_str()); } } void ossimTiling::clampGeographic(ossimDrect& rect)const { ossimDpt ul = rect.ul(); ossimDpt lr = rect.lr(); if(ul.lat > 90) ul.lat = 90.0; if(lr.lat < -90.0) lr.lat = -90.0; if(ul.lon < -180) ul.lon = -180; if(lr.lon > 180) lr.lon = 180; rect = ossimDrect(ul, lr, rect.orientMode()); } bool ossimTiling::saveState(ossimKeywordlist& kwl, const char* prefix)const { std::stringstream tilingDistance; tilingDistance << theTilingDistance.x << " " << theTilingDistance.y << std::endl; kwl.add(prefix, "tiling_distance", tilingDistance.str().c_str(), true); kwl.add(prefix, "tiling_distance_type", ossimUnitTypeLut::instance()-> getTableIndexString(theTilingDistanceUnitType), true); std::ostringstream delta; delta << theDelta.x << " " << theDelta.y; kwl.add(prefix, "delta", delta.str().c_str(), true); if(theDeltaType == ossimTilingDeltaType_TOTAL_PIXELS) { kwl.add(prefix, "delta_type", "total_pixels", true); } else { kwl.add(prefix, "delta_type", "delta_per_pixels", true); } std::ostringstream padding; padding << thePaddingSizeInPixels.x << " " << thePaddingSizeInPixels.y; kwl.add(prefix, "padding_size_in_pixels", padding.str().c_str(), true); kwl.add(prefix, "tile_name_mask", theTileNameMask.c_str(), true); if (theOutputSizeInBytes) { kwl.add(prefix, "output_size_in_bytes", ossimString::toString(theOutputSizeInBytes).c_str(), true); kwl.add(prefix, "output_bands", theNumberOfBands, true); kwl.add(prefix, "output_bytes_per_pixel_per_band", theNumberOfBytesPerPixelPerBand, true); } kwl.add(prefix, "edge_to_edge", ossimString::toString(theEdgeToEdgeFlag), true); return true; } bool ossimTiling::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; // Get the mask if any. theTileNameMask = kwl.find(prefix, "tile_name_mask"); setTileNameMask(theTileNameMask); const char* paddingSizeInPixels = kwl.find(prefix, "padding_size_in_pixels"); if (paddingSizeInPixels) { ossimString x,y; std::istringstream padding(ossimString(paddingSizeInPixels).c_str()); padding >> x >> y; thePaddingSizeInPixels.x = x.toFloat64(); thePaddingSizeInPixels.y = y.toFloat64(); } // Check to tile by size in bytes. const char* lookup; if (kwl.numberOf(prefix, "output_size_in_")) { lookup = kwl.find(prefix, "output_size_in_bytes"); if (lookup) { theOutputSizeInBytes = ossimString(lookup).toInt64(); } lookup = kwl.find(prefix, "output_size_in_kilo_bytes"); if (lookup) { theOutputSizeInBytes = ossimString(lookup).toInt64() * 1024; } lookup = kwl.find(prefix, "output_size_in_mega_bytes"); if (lookup) { theOutputSizeInBytes = ossimString(lookup).toInt64() * 1024 * 1024; } } if (theOutputSizeInBytes) { lookup = kwl.find(prefix, "output_bands"); if (lookup) { theNumberOfBands = ossimString(lookup).toInt32(); } lookup = kwl.find(prefix, "output_bytes_per_pixel_per_band"); if (lookup) { theNumberOfBytesPerPixelPerBand = ossimString(lookup).toInt32(); } ossim_int64 pixelsPerBand = theOutputSizeInBytes / (theNumberOfBands * theNumberOfBytesPerPixelPerBand); ossim_int32 oneDimension = static_cast(floor(sqrt((double)pixelsPerBand))); //--- // TODO: Clamp to power of two option. (drb) //--- // theDelta.x = oneDimension; // theDelta.y = oneDimension; // theTilingDistance.x = 1; // theTilingDistance.y = 1; theDelta.x = 1; theDelta.y = 1; theTilingDistance.x = oneDimension; theTilingDistance.y = oneDimension; theDeltaType = ossimTilingDeltaType_TOTAL_PIXELS; theTilingDistanceUnitType = OSSIM_PIXEL; result = true; } else { const char* tilingDistance = kwl.find(prefix, "tiling_distance"); const char* tilingDistanceType = kwl.find(prefix, "tiling_distance_type"); const char* delta = kwl.find(prefix, "delta"); const char* deltaType = kwl.find(prefix, "delta_type"); result = tilingDistance&&tilingDistanceType&&delta&&deltaType&&paddingSizeInPixels; ossimString x,y; std::istringstream distance(ossimString(tilingDistance).c_str()); distance >> x >> y; theTilingDistance.x = x.toFloat64(); theTilingDistance.y = y.toFloat64(); if(theTilingDistance.x <= 0.0) { theTilingDistance.x = 1.0; } if(theTilingDistance.y<=0.0) { theTilingDistance.y = theTilingDistance.x; } // unitLut.getTableIndexString(theTilingDistanceUnitType), ????? theTilingDistanceUnitType = (ossimUnitType) ossimUnitTypeLut::instance()->getEntryNumber( ossimString(tilingDistanceType).c_str()); theDelta = ossimDpt(0,0); x=""; y=""; std::istringstream deltaValues(ossimString(delta).c_str()); deltaValues >> x >> y; theDelta.x = x.toFloat64(); theDelta.y = y.toFloat64(); if(theDelta.x <= 0.0) { theDelta.x = 1.0; } if(theDelta.y <= 0.0) { theDelta.y = theDelta.x; } if(ossimString(deltaType).downcase().contains("total")) { theDeltaType = ossimTilingDeltaType_TOTAL_PIXELS; } else { theDeltaType = ossimTilingDeltaType_PER_PIXEL; } } lookup = kwl.find(prefix, "edge_to_edge"); if ( lookup ) { theEdgeToEdgeFlag = ossimString::toBool(lookup); } if (traceDebug()) { print(ossimNotify(ossimNotifyLevel_DEBUG)); } return result; } std::ostream& ossimTiling::print(std::ostream& out) const { out << "theTilingDistance: " << theTilingDistance << "\ntheTilingDistanceUnitType: " << theTilingDistanceUnitType << "\ntheDelta: " << theDelta << "\ntheDeltaType: " << theDeltaType << "\nthePaddingSizeInPixels: " << thePaddingSizeInPixels << "\ntheImageRect: " << theImageRect << "\ntheTilingRect: " << theTilingRect << "\ntheTileId: " << theTileId << "\ntheTotalHorizontalTiles: " << theTotalHorizontalTiles << "\ntheTotalVerticalTiles: " << theTotalVerticalTiles << "\ntheTotalTiles: " << theTotalTiles << "\ntheTileNameMask: " << theTileNameMask << "\ntheOutputSizeInBytes: " << theOutputSizeInBytes << "\ntheNumberOfBands: " << theNumberOfBands << "\ntheNumberOfBytesPerPixelPerBand: " << theNumberOfBytesPerPixelPerBand << "\ntheEdgeToEdgeFlag: " << theEdgeToEdgeFlag << "\n"; if (theMapProjection.valid()) { out << "\ntheMapProjection:\n"; theMapProjection->print(out); } else { out << "theMapProjection is not set."; } out << endl; return out; } void ossimTiling::getConvertedTilingDistance(ossimDpt& pt) const { if(theTilingDistanceUnitType == OSSIM_PIXEL) { pt = theTilingDistance; return; } if (!theMapProjection) { // This should not happen... ossimNotify(ossimNotifyLevel_WARN) << "ossimTiling::getConvertedTilingDistance WARNING" << " projection not set!" << endl; pt = theTilingDistance; return; } ossimUnitConversionTool unitConverter(theMapProjection->origin(), 1.0, theTilingDistanceUnitType); if(theMapProjection->isGeographic()) { unitConverter.setValue(theTilingDistance.x, theTilingDistanceUnitType); pt.x = unitConverter.getValue(OSSIM_DEGREES); unitConverter.setValue(theTilingDistance.y, theTilingDistanceUnitType); pt.y = unitConverter.getValue(OSSIM_DEGREES); } else { unitConverter.setValue(theTilingDistance.x, theTilingDistanceUnitType); pt.x = unitConverter.getValue(OSSIM_METERS); unitConverter.setValue(theTilingDistance.y, theTilingDistanceUnitType); pt.y = unitConverter.getValue(OSSIM_METERS); } } ossim-Miami-2.9.1/src/imaging/ossimTilingPoly.cpp000066400000000000000000000255701352751253100217770ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // // Description: implementation for image generator // //************************************************************************* // $Id: ossimTilingPoly.cpp 2725 2011-06-15 18:13:07Z david.burken $ #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimTilingPoly:debug"); RTTI_DEF1(ossimTilingPoly, "ossimTilingPoly", ossimTilingRect); ossimTilingPoly::ossimTilingPoly() : ossimTilingRect(), m_shpFilename(""), m_useMbr(true), m_bufferDistance(0.0), m_exteriorCut(0), m_interiorCut(0), m_featureBoundingIntersect(true) { } ossimTilingPoly::~ossimTilingPoly() { m_exteriorCut = 0; // Ref ptr, not a leak. m_interiorCut = 0; // ditto... m_features.clear(); } bool ossimTilingPoly::initialize(const ossimMapProjection& proj, const ossimIrect& boundingRect) { bool result = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTilingPoly::initialize DEBUG: Entered..." << "\nBounding rect === " << boundingRect << std::endl; } ossimDpt convertedTilingDistance = theTilingDistance; result = initializeBase(proj, boundingRect, convertedTilingDistance); if (result) { return parseShpFile(); } return result; } bool ossimTilingPoly::next(ossimRefPtr& resultProjection, ossimIrect& resultingBounds, ossimString& resultingName) { bool result = true; if(theTileId < theTotalTiles) { ostringstream idString; ossim_int64 tileId = theTileId + 1; if (tileId < static_cast(m_features.size())) { idString << m_features[tileId].m_fid; resultingName = theTileNameMask; resultingName = resultingName.substitute("%f%", idString.str().c_str()); } result = nextFeature(); resultingBounds = m_exteriorCut->getRectangle(); resultProjection = theMapProjection; ++theTileId; } else { result = false; } return result; } bool ossimTilingPoly::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "tile_source", m_shpFilename.c_str(), true); kwl.add(prefix, "paddding_use_mbr", m_useMbr, true); return ossimTilingRect::saveState(kwl, prefix);; } bool ossimTilingPoly::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimTilingRect::loadState(kwl, prefix); //Get the shp file if any m_shpFilename = kwl.find(prefix, "tile_source"); // Get the mask if any. if (!m_shpFilename.empty()) { if (theTileNameMask.contains("%r%_%c%")) { theTileNameMask = theTileNameMask.substitute("%r%_%c%", "%f%", true); } result = true; } const char* useMbr = kwl.find(prefix, "padding_use_mbr"); if (useMbr) { if (!ossimString(useMbr).toBool()) { m_useMbr = false; m_bufferDistance = thePaddingSizeInPixels.x; } } return result; } bool ossimTilingPoly::nextFeature() { if (!m_exteriorCut) { m_exteriorCut = new ossimGeoPolyCutter; m_exteriorCut->setView(theMapProjection.get()); } bool result = false; ossim_int64 tileId = theTileId + 1;//use (theTileId+1) because theTileId is intialized as -1 if (tileId < static_cast(m_features.size())) { if (m_features[tileId].m_polygon.size() > 0) { if (m_features[tileId].m_polyType == ossimGeoAnnotationPolyObject::OSSIM_POLY_INTERIOR_RING) { if (!m_interiorCut) { m_interiorCut = new ossimGeoPolyCutter; m_interiorCut->setView(theMapProjection.get()); m_interiorCut->setCutType(ossimPolyCutter::OSSIM_POLY_NULL_INSIDE); } m_interiorCut->setPolygon(m_features[tileId].m_polygon); } else { // std::vector points = m_features[tileId].m_polygon; // for (ossim_uint32 i = 0; i < points.size(); i++) // { // ossimGpt point = points[i]; // } m_exteriorCut->setPolygon(m_features[tileId].m_polygon); setRect(); } result = true; } else if (m_features[tileId].m_multiPolys.size() > 0) { for (ossim_uint32 i = 0; i < m_features[tileId].m_multiPolys.size(); i++) { ossimGeoPolygon geoPoly = m_features[tileId].m_multiPolys[i]; std::vector holePolys = geoPoly.getHoleList(); if (holePolys.size() > 0) { if (!m_interiorCut) { m_interiorCut = new ossimGeoPolyCutter; m_interiorCut->setView(theMapProjection.get()); m_interiorCut->setCutType(ossimPolyCutter::OSSIM_POLY_NULL_INSIDE); } m_interiorCut->clear(); for (ossim_uint32 j = 0; j < holePolys.size(); j++) { m_interiorCut->addPolygon(holePolys[j]); } } m_exteriorCut->setPolygon(m_features[tileId].m_multiPolys[i]); setRect(); } result = true; } } else { result = false; } return result; } void ossimTilingPoly::setRect() { ossimIrect rect = m_exteriorCut->getRectangle(); if (rect.intersects(theImageRect)) { m_featureBoundingIntersect = true; if (!rect.completely_within(theImageRect)) { ossimIrect clipRect = rect.clipToRect(theImageRect); m_exteriorCut->setRectangle(clipRect); rect = clipRect; } } else { m_featureBoundingIntersect = false; } if (m_useMbr) { if (thePaddingSizeInPixels.x > 0 && thePaddingSizeInPixels.y > 0) { ossimIrect newRect = ossimIrect(rect.ul().x-(ossim_int32)thePaddingSizeInPixels.x, rect.ul().y-(ossim_int32)thePaddingSizeInPixels.y, rect.lr().x + (ossim_int32)thePaddingSizeInPixels.x, rect.lr().y + (ossim_int32)thePaddingSizeInPixels.y); ossimIrect clipRect = newRect.clipToRect(theImageRect);//in case the bounding is larger than input image after adding buffer m_exteriorCut->setRectangle(clipRect); } } } bool ossimTilingPoly::parseShpFile() { m_features.clear(); ossimString query = ""; bool result = false; if (m_shpFilename.contains("|")) { ossimString fileName = m_shpFilename; std::vector fileList = fileName.split("|"); if (fileList.size() > 1) { m_shpFilename = fileList[0]; query = fileList[1]; } } ossimRefPtr shpHandler = ossimImageHandlerRegistry::instance()->open(m_shpFilename); ossimEsriShapeFileInterface* shpInterface = PTR_CAST(ossimEsriShapeFileInterface, shpHandler.get()); if (shpInterface != 0) { if (!query.empty()) { shpInterface->setQuery(query); } if (m_useMbr == false) { ossimProjection* proj = shpHandler->getImageGeometry()->getProjection(); ossimMapProjection* mapProj = PTR_CAST(ossimMapProjection, proj); if (mapProj) { if (mapProj->isGeographic()) { m_bufferDistance = thePaddingSizeInPixels.x * theMapProjection->getDecimalDegreesPerPixel().x; shpInterface->setGeometryBuffer(m_bufferDistance, OSSIM_DEGREES); } else { m_bufferDistance = thePaddingSizeInPixels.x * theMapProjection->getMetersPerPixel().x; shpInterface->setGeometryBuffer(m_bufferDistance, OSSIM_METERS); } } } std::multimap features = shpInterface->getFeatureTable(); if (features.size() > 0) { std::multimap::iterator it = features.begin(); while (it != features.end()) { ossimAnnotationObject* anno = it->second; if (anno != 0) { ossimGeoAnnotationPolyObject* annoPoly = PTR_CAST(ossimGeoAnnotationPolyObject, anno); ossimGeoAnnotationMultiPolyObject* annoMultiPoly = 0; if (annoPoly == 0) { annoMultiPoly = PTR_CAST(ossimGeoAnnotationMultiPolyObject, anno); } if (annoPoly != 0) { result = true; std::vector polygon; //get the points of a polygon std::vector points = annoPoly->getPoints(); for (ossim_uint32 i = 0; i < points.size(); i++) { polygon.push_back(points[i]); } //get polygon type, if it is an internal polygon, initialize the internal cutter ossimGeoAnnotationPolyObject::ossimPolyType polyType = annoPoly->getPolyType(); ossimShpFeature feature(it->first, polyType, polygon, std::vector()); m_features.push_back(feature); } else if (annoMultiPoly != 0) { std::vector multiPolys = annoMultiPoly->getMultiPolygon(); ossimShpFeature feature(it->first, 0, std::vector(), multiPolys); } } it++; } } } if (m_features.size() > 0) { theTotalTiles = m_features.size(); result = true; } return result; } bool ossimTilingPoly::useMbr() const { //if the use_mbr is set to true, no matter if the padding is set to 0 or greater than 0, //always clip the MBR of each feature return m_useMbr; } bool ossimTilingPoly::hasExteriorCut() const { return m_exteriorCut.valid(); } bool ossimTilingPoly::hasInteriorCut() const { return m_interiorCut.valid(); } ossimRefPtr& ossimTilingPoly::getExteriorCut() { return m_exteriorCut; } ossimRefPtr& ossimTilingPoly::getInteriorCut() { return m_interiorCut; } bool ossimTilingPoly::isFeatureBoundingIntersect() const { return m_featureBoundingIntersect; } ossim-Miami-2.9.1/src/imaging/ossimTilingRect.cpp000066400000000000000000000751531352751253100217530ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // // Description: implementation for image generator // //************************************************************************* // $Id: ossimTilingRect.cpp 2725 2011-06-15 18:13:07Z david.burken $ #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimTilingRect:debug"); RTTI_DEF1(ossimTilingRect, "ossimTilingRect", ossimTiling); ossimTilingRect::ossimTilingRect() : ossimTiling(), m_clipToAoi(true), m_lastWidth(0), m_lastHeight(0), m_useOffset(false), m_offsetInPixels(0,0), m_tilingDistanceInPixels(0,0), m_tilinResolutionDistance(ossim::nan(),ossim::nan()), m_tilingResolutionUnitType(OSSIM_UNIT_UNKNOWN), m_fractionalPixelMisalignment(ossim::nan(),ossim::nan()) { } ossimTilingRect::~ossimTilingRect() { } bool ossimTilingRect::initializeBase(const ossimMapProjection& proj, const ossimIrect& boundingRect, ossimDpt& convertedTilingDistance) { theMapProjection = (ossimMapProjection*)proj.dup(); theImageRect = boundingRect; ossimDpt gsd = theMapProjection->getMetersPerPixel(); // Find image center and GSD at that point: if (theMapProjection->isGeographic() && theTilingDistanceUnitType != OSSIM_DEGREES) { ossimRefPtr geom = new ossimImageGeometry (0, theMapProjection.get()); geom->setImageSize(ossimIpt(theImageRect.width(), theImageRect.height())); gsd = geom->getMetersPerPixel(); } m_tilingDistanceInPixels = theTilingDistance; //if resolution and resolution type are defined, need to reset degree/meter per pixel and the image rect. do calculation below ossim_float64 latDiff = 0.0; ossim_float64 lonDiff = 0.0; ossim_uint32 imageWidth = 0; ossim_uint32 imageHeight = 0; if (!m_tilinResolutionDistance.hasNans()) { ossimDpt result(0,0); if (m_tilingResolutionUnitType == OSSIM_DEGREES) { ossimGpt ulg; ossimGpt llg; ossimGpt lrg; ossimGpt urg; theMapProjection->lineSampleToWorld(theImageRect.ul(), ulg); theMapProjection->lineSampleToWorld(theImageRect.ll(), llg); theMapProjection->lineSampleToWorld(theImageRect.lr(), lrg); theMapProjection->lineSampleToWorld(theImageRect.ur(), urg); latDiff = fabs(ulg.lat - llg.lat); lonDiff = fabs(urg.lon - llg.lon); if (!theMapProjection->isGeographic()) { ossim_float64 tileHorizatalNum = lonDiff/m_tilinResolutionDistance.x; ossim_float64 tileVerticalNum = latDiff/m_tilinResolutionDistance.y; if (theTilingDistanceUnitType != OSSIM_PIXEL) //convert tiling distance to pixel if unit type is not pixel { ossimDpt convertedDis = m_tilingDistanceInPixels; getConvertedDistance(convertedDis, m_tilingDistanceInPixels); imageWidth = (ossim_uint32)convertedDis.x/gsd.x*tileHorizatalNum; imageHeight = (ossim_uint32)convertedDis.y/gsd.y*tileVerticalNum; } else { imageWidth = (ossim_uint32)m_tilingDistanceInPixels.x*tileHorizatalNum; imageHeight = (ossim_uint32)m_tilingDistanceInPixels.y*tileVerticalNum; } result = ossimDpt(theImageRect.width()*gsd.x/imageWidth, theImageRect.height()*gsd.y/imageHeight); gsd = result; theMapProjection->setMetersPerPixel(result); } else { result = ossimDpt(m_tilinResolutionDistance.x/m_tilingDistanceInPixels.x, m_tilinResolutionDistance.y/m_tilingDistanceInPixels.y); theMapProjection->setDecimalDegreesPerPixel(result); } } else //only handle degree type for resolution { return false; } } if (theTilingDistanceUnitType != OSSIM_PIXEL) { ossimDpt paddingSize = getPaddingSize();//convert padding size to meters or degree getConvertedDistance(convertedTilingDistance, theTilingDistance); ossimDpt convertedOffset = m_offsetInPixels; if (m_useOffset) { getConvertedDistance(convertedOffset, m_offsetInPixels); } if (theMapProjection->isGeographic() && theTilingDistanceUnitType == OSSIM_DEGREES) { thePaddingSizeInPixels.x = ossim::round(paddingSize.x / theMapProjection->getDecimalDegreesPerPixel().x); thePaddingSizeInPixels.y = ossim::round(paddingSize.y / theMapProjection->getDecimalDegreesPerPixel().y); double intpart; m_fractionalPixelMisalignment.x = modf(convertedTilingDistance.x / theMapProjection->getDecimalDegreesPerPixel().x, &intpart); m_fractionalPixelMisalignment.y = modf(convertedTilingDistance.y / theMapProjection->getDecimalDegreesPerPixel().y, &intpart); m_tilingDistanceInPixels.x = ossim::round(convertedTilingDistance.x / theMapProjection->getDecimalDegreesPerPixel().x); m_tilingDistanceInPixels.y = ossim::round(convertedTilingDistance.y / theMapProjection->getDecimalDegreesPerPixel().y); if (m_useOffset) { m_offsetInPixels.x = ossim::round(convertedOffset.x / theMapProjection->getDecimalDegreesPerPixel().x); m_offsetInPixels.y = ossim::round(convertedOffset.y / theMapProjection->getDecimalDegreesPerPixel().y); } } else { thePaddingSizeInPixels.x = ossim::round(paddingSize.x / gsd.x); thePaddingSizeInPixels.y = ossim::round(paddingSize.y / gsd.y); double intpart; m_fractionalPixelMisalignment.x = modf(convertedTilingDistance.x / gsd.x, &intpart); m_fractionalPixelMisalignment.y = modf(convertedTilingDistance.y / gsd.y, &intpart); m_tilingDistanceInPixels.x = ossim::round(convertedTilingDistance.x / gsd.x); m_tilingDistanceInPixels.y = ossim::round(convertedTilingDistance.y / gsd.y); if (m_useOffset) { m_offsetInPixels.x = ossim::round(convertedOffset.x / gsd.x); m_offsetInPixels.y = ossim::round(convertedOffset.y / gsd.y); } } } else { if (theMapProjection->isGeographic()) { theTilingDistance.x = theTilingDistance.x * theMapProjection->getDecimalDegreesPerPixel().x; theTilingDistance.y = theTilingDistance.y * theMapProjection->getDecimalDegreesPerPixel().y; } else { theTilingDistance.x = theTilingDistance.x * gsd.x; theTilingDistance.y = theTilingDistance.y * gsd.y; } } //re-calculation the image rect if resolution and resolution type defined if (!m_tilinResolutionDistance.hasNans()) { if (theMapProjection->isGeographic()) { imageWidth = (ossim_uint32)m_tilingDistanceInPixels.x * lonDiff; imageHeight = (ossim_uint32)m_tilingDistanceInPixels.y * latDiff; } //avoid very small pixel offset by calculation if tiling distance unit type is pixel if (theTilingDistanceUnitType == OSSIM_PIXEL) { if (imageWidth % (ossim_int32)m_tilingDistanceInPixels.x != 0) { ossim_int32 numX = ossim::round((double)imageWidth/m_tilingDistanceInPixels.x); imageWidth = m_tilingDistanceInPixels.x * numX; } if (imageHeight % (ossim_int32)m_tilingDistanceInPixels.y != 0) { ossim_int32 numY = ossim::round((double)imageHeight/m_tilingDistanceInPixels.y); imageHeight = m_tilingDistanceInPixels.y * numY; } } theImageRect = ossimIrect(boundingRect.ul(), ossimIpt((boundingRect.ul().x + imageWidth), boundingRect.ul().y), ossimIpt((boundingRect.ul().x + imageWidth), (imageHeight - boundingRect.ul().y)), ossimIpt(boundingRect.ul().x , (imageHeight - boundingRect.ul().y))); } return true; } bool ossimTilingRect::initialize(const ossimMapProjection& proj, const ossimIrect& boundingRect) { bool result = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTilingRect::initialize DEBUG: Entered..." << "\nBounding rect === " << boundingRect << std::endl; } ossimDpt convertedTilingDistance = theTilingDistance; result = initializeBase(proj, boundingRect, convertedTilingDistance); ossimDrect tilingRectInPixels = theImageRect; // Let's setup the bounding tile rect. if(theMapProjection->isGeographic()) { ossimGpt ul; ossimGpt ur; ossimGpt lr; ossimGpt ll; theMapProjection->lineSampleToWorld(theImageRect.ul(), ul); theMapProjection->lineSampleToWorld(theImageRect.ur(), ur); theMapProjection->lineSampleToWorld(theImageRect.lr(), lr); theMapProjection->lineSampleToWorld(theImageRect.ll(), ll); theTilingRect = ossimDrect(ossimDpt(ul), ossimDpt(ur), ossimDpt(lr), ossimDpt(ll), OSSIM_RIGHT_HANDED); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Geographic input bounds = " << theTilingRect << std::endl; } if (!m_clipToAoi) { theTilingRect.stretchToTileBoundary(convertedTilingDistance); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Geographic input bounds stretched = " << theTilingRect << std::endl; } clampGeographic(theTilingRect); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Geographic input bounds clamped = " << theTilingRect << std::endl; } } // End "if(theMapProjection->isGeographic())" else // meters { ossimDpt ul; ossimDpt ur; ossimDpt lr; ossimDpt ll; theMapProjection->lineSampleToEastingNorthing(theImageRect.ul(), ul); theMapProjection->lineSampleToEastingNorthing(theImageRect.ur(), ur); theMapProjection->lineSampleToEastingNorthing(theImageRect.lr(), lr); theMapProjection->lineSampleToEastingNorthing(theImageRect.ll(), ll); theTilingRect = ossimDrect(ul, ur, lr, ll, OSSIM_RIGHT_HANDED); if (!m_clipToAoi) { theTilingRect.stretchToTileBoundary(convertedTilingDistance); } } theTotalHorizontalTiles = ossim::round(fabs(tilingRectInPixels.ur().x - tilingRectInPixels.ul().x)/m_tilingDistanceInPixels.x); theTotalVerticalTiles = ossim::round(fabs(tilingRectInPixels.ur().y - tilingRectInPixels.lr().y)/m_tilingDistanceInPixels.y); if (m_clipToAoi) { if (m_useOffset) { ossim_float32 totalHorizontalTilesAfterOffset = ((fabs(tilingRectInPixels.ur().x - tilingRectInPixels.ul().x))-m_tilingDistanceInPixels.x)/(m_tilingDistanceInPixels.x - m_offsetInPixels.x) + 1; ossim_float32 totalVerticalTilesAfterOffset = ((fabs(tilingRectInPixels.ur().y - tilingRectInPixels.lr().y))-m_tilingDistanceInPixels.y)/(m_tilingDistanceInPixels.y - m_offsetInPixels.y) + 1; ossim_float32 lastHorizontal = totalHorizontalTilesAfterOffset - (ossim_int32)totalHorizontalTilesAfterOffset; ossim_float32 lastVertical = totalVerticalTilesAfterOffset - (ossim_int32)totalVerticalTilesAfterOffset; m_lastWidth = ossim::round(fabs(lastHorizontal* (m_tilingDistanceInPixels.x - m_offsetInPixels.x) + m_offsetInPixels.x)); m_lastHeight = ossim::round(fabs(lastVertical* (m_tilingDistanceInPixels.y - m_offsetInPixels.y) + m_offsetInPixels.y)); theTotalHorizontalTiles = ossim::round(totalHorizontalTilesAfterOffset); theTotalVerticalTiles = ossim::round(totalVerticalTilesAfterOffset); if (m_lastWidth > 0 && (lastHorizontal < 0.5))//if lastHorizontal is less than 0.5, the last tile will not add to total tiles after rounding, do here { theTotalHorizontalTiles = theTotalHorizontalTiles + 1; } if (m_lastHeight > 0 && (lastVertical < 0.5)) { theTotalVerticalTiles = theTotalVerticalTiles + 1; } } else { ossim_int32 tmpX = (ossim_int32)(fabs(tilingRectInPixels.ur().x - tilingRectInPixels.ul().x)) + 1; ossim_int32 tmpY = (ossim_int32)(fabs(tilingRectInPixels.ur().y - tilingRectInPixels.lr().y)) + 1; ossim_int32 modValueX = tmpX % (ossim_int32)m_tilingDistanceInPixels.x; ossim_int32 modValueY = tmpY % (ossim_int32)m_tilingDistanceInPixels.y; if (modValueX >= 1) { m_lastWidth = modValueX; } else { m_lastWidth = m_tilingDistanceInPixels.x; } if (modValueY >= 1) { m_lastHeight = modValueY; } else { m_lastHeight = m_tilingDistanceInPixels.y; } if (m_lastWidth > 0) { if (m_lastWidth < m_tilingDistanceInPixels.x/2) { theTotalHorizontalTiles = theTotalHorizontalTiles + 1; } } if (m_lastHeight > 0) { if (m_lastHeight < m_tilingDistanceInPixels.y/2) { theTotalVerticalTiles = theTotalVerticalTiles + 1; } } } } theTotalTiles = theTotalHorizontalTiles*theTotalVerticalTiles; // reset the tile id to the beginning reset(); if(traceDebug()) { print(ossimNotify(ossimNotifyLevel_DEBUG)); ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimTiling::initialize DEBUG: Leaving..." << std::endl; } return result; } bool ossimTilingRect::next(ossimRefPtr& resultProjection, ossimIrect& resultingBounds, ossimString& resultingName) { bool result = true; if(theTileId < theTotalTiles) { ossimDpt origin; ossim_int64 row=0; ossim_int64 col=0; getRowCol(row, col, theTileId); getTileName(resultingName, (row+1), (col+1), theTileId); getOrigin(origin, row, col); if (!m_fractionalPixelMisalignment.isNan()) { if (row == 0 && col != 0) { if (m_fractionalPixelMisalignment.x >= 0.5) { if (theMapProjection->isGeographic()) { origin.x = origin.x + (1 - m_fractionalPixelMisalignment.x) * theMapProjection->getDecimalDegreesPerPixel().x * col; } else { origin.x = origin.x + (1 - m_fractionalPixelMisalignment.x) * theMapProjection->getMetersPerPixel().x * col; } } else { if (theMapProjection->isGeographic()) { origin.x = origin.x - m_fractionalPixelMisalignment.x * theMapProjection->getDecimalDegreesPerPixel().x * col; } else { origin.x = origin.x - m_fractionalPixelMisalignment.x * theMapProjection->getMetersPerPixel().x * col; } } } else if (col == 0 && row != 0) { if (m_fractionalPixelMisalignment.y >= 0.5) { if (theMapProjection->isGeographic()) { origin.y = origin.y - (1 - m_fractionalPixelMisalignment.y) * theMapProjection->getDecimalDegreesPerPixel().y * row; } else { origin.y = origin.y - (1 - m_fractionalPixelMisalignment.y) * theMapProjection->getMetersPerPixel().y * row; } } else { if (theMapProjection->isGeographic()) { origin.y = origin.y + m_fractionalPixelMisalignment.y * theMapProjection->getDecimalDegreesPerPixel().y * row; } else { origin.y = origin.y + m_fractionalPixelMisalignment.y * theMapProjection->getMetersPerPixel().y * row; } } } else if (col != 0 && row != 0) { if (m_fractionalPixelMisalignment.x >= 0.5) { if (theMapProjection->isGeographic()) { origin.x = origin.x + (1 - m_fractionalPixelMisalignment.x) * theMapProjection->getDecimalDegreesPerPixel().x * col; } else { origin.x = origin.x + (1 - m_fractionalPixelMisalignment.x) * theMapProjection->getMetersPerPixel().x * col; } } else { if (theMapProjection->isGeographic()) { origin.x = origin.x - m_fractionalPixelMisalignment.x * theMapProjection->getDecimalDegreesPerPixel().x * col; } else { origin.x = origin.x - m_fractionalPixelMisalignment.x * theMapProjection->getMetersPerPixel().x * col; } } if (m_fractionalPixelMisalignment.y >= 0.5) { if (theMapProjection->isGeographic()) { origin.y = origin.y - (1 - m_fractionalPixelMisalignment.y) * theMapProjection->getDecimalDegreesPerPixel().y * row; } else { origin.y = origin.y - (1 - m_fractionalPixelMisalignment.y) * theMapProjection->getMetersPerPixel().y * row; } } else { if (theMapProjection->isGeographic()) { origin.y = origin.y + m_fractionalPixelMisalignment.y * theMapProjection->getDecimalDegreesPerPixel().y * row; } else { origin.y = origin.y + m_fractionalPixelMisalignment.y * theMapProjection->getMetersPerPixel().y * row; } } } } ossimIpt pixels = ossimDpt(m_tilingDistanceInPixels.x, m_tilingDistanceInPixels.y); if(theMapProjection->isGeographic()) { theMapProjection->setUlTiePoints( ossimGpt(origin.lat, origin.lon, 0.0, theMapProjection->origin().datum())); } else { theMapProjection->setUlTiePoints(ossimDpt(origin.x, origin.y)); } if (m_clipToAoi || m_useOffset) { if (row == 0 && col == 0) { resultingBounds = ossimIrect(0, 0, (pixels.x-1) + (ossim_int32)thePaddingSizeInPixels.x, (pixels.y-1) + (ossim_int32)thePaddingSizeInPixels.y); } else if (row == 0 && col != 0) { if (col == (theTotalHorizontalTiles-1)) { resultingBounds = ossimIrect(-(ossim_int32)thePaddingSizeInPixels.x, 0, (m_lastWidth-1), (pixels.y-1) + (ossim_int32)thePaddingSizeInPixels.y); if (m_useOffset) { ossim_int32 lr_x = -((ossim_int32)m_offsetInPixels.x*col)- resultingBounds.width(); resultingBounds = ossimIrect(-((ossim_int32)m_offsetInPixels.x*col), 0, lr_x, (resultingBounds.height()-1)); } } else { resultingBounds = ossimIrect(-(ossim_int32)thePaddingSizeInPixels.x, 0, (pixels.x-1) + (ossim_int32)thePaddingSizeInPixels.x, (pixels.y-1) + (ossim_int32)thePaddingSizeInPixels.y); if (m_useOffset) { resultingBounds = ossimIrect(-((ossim_int32)m_offsetInPixels.x*col), 0, (resultingBounds.width()-1)-((ossim_int32)m_offsetInPixels.x*col), (resultingBounds.height()-1)); } } } else if (row != 0 && col == 0) { if (row == (theTotalVerticalTiles-1)) { resultingBounds = ossimIrect(0, -(ossim_int32)thePaddingSizeInPixels.y, (pixels.x-1) + (ossim_int32)thePaddingSizeInPixels.x, (m_lastHeight-1)); if (m_useOffset) { ossim_int32 lr_y = -((ossim_int32)m_offsetInPixels.y*row)-resultingBounds.height(); resultingBounds = ossimIrect(0, -((ossim_int32)m_offsetInPixels.y*row), (resultingBounds.width()-1), lr_y); } } else { resultingBounds = ossimIrect(0, -(ossim_int32)thePaddingSizeInPixels.y, (pixels.x-1) + (ossim_int32)thePaddingSizeInPixels.x, (pixels.y-1) + (ossim_int32)thePaddingSizeInPixels.y); if (m_useOffset) { resultingBounds = ossimIrect(0, -((ossim_int32)m_offsetInPixels.y*row), (resultingBounds.width()-1), (resultingBounds.height()-1)-((ossim_int32)m_offsetInPixels.y*row)); } } } else if (row != 0 && col != 0) { if (row == (theTotalVerticalTiles-1) && col == (theTotalHorizontalTiles-1)) { resultingBounds = ossimIrect(-(ossim_int32)thePaddingSizeInPixels.x, -(ossim_int32)thePaddingSizeInPixels.y, (m_lastWidth-1), (m_lastHeight-1)); if (m_useOffset) { ossim_int32 lr_x = -((ossim_int32)m_offsetInPixels.x*col)-resultingBounds.width(); ossim_int32 lr_y = -((ossim_int32)m_offsetInPixels.y*row)-resultingBounds.height(); resultingBounds = ossimIrect(-((ossim_int32)m_offsetInPixels.x*col), -((ossim_int32)m_offsetInPixels.y*row), lr_x, lr_y); } } else if (row != (theTotalVerticalTiles-1) && col == (theTotalHorizontalTiles-1)) { resultingBounds = ossimIrect(-(ossim_int32)thePaddingSizeInPixels.x, -(ossim_int32)thePaddingSizeInPixels.y, (m_lastWidth-1), (pixels.y-1) + (ossim_int32)thePaddingSizeInPixels.y); if (m_useOffset) { ossim_int32 lr_x = -((ossim_int32)m_offsetInPixels.x*col)-resultingBounds.width(); resultingBounds = ossimIrect(-((ossim_int32)m_offsetInPixels.x*col), -((ossim_int32)m_offsetInPixels.y*row), lr_x, (resultingBounds.height()-1)-((ossim_int32)m_offsetInPixels.y*row)); } } else if (row == (theTotalVerticalTiles-1) && col != (theTotalHorizontalTiles-1)) { resultingBounds = ossimIrect(-(ossim_int32)thePaddingSizeInPixels.x, -(ossim_int32)thePaddingSizeInPixels.y, (pixels.x-1) + (ossim_int32)thePaddingSizeInPixels.x, (m_lastHeight-1)); if (m_useOffset) { ossim_int32 lr_y = -((ossim_int32)m_offsetInPixels.y*row)-resultingBounds.height(); resultingBounds = ossimIrect(-((ossim_int32)m_offsetInPixels.x*col), -((ossim_int32)m_offsetInPixels.y*row), (resultingBounds.width()-1)-((ossim_int32)m_offsetInPixels.x*col), lr_y); } } else { resultingBounds = ossimIrect(-(ossim_int32)thePaddingSizeInPixels.x, -(ossim_int32)thePaddingSizeInPixels.y, (pixels.x-1) + (ossim_int32)thePaddingSizeInPixels.x, (pixels.y-1) + (ossim_int32)thePaddingSizeInPixels.y); if (m_useOffset) { resultingBounds = ossimIrect(-((ossim_int32)m_offsetInPixels.x*col), -((ossim_int32)m_offsetInPixels.y*row), (resultingBounds.width()-1)-((ossim_int32)m_offsetInPixels.x*col), (resultingBounds.height()-1)-((ossim_int32)m_offsetInPixels.y*row)); } } } } else { resultingBounds = ossimIrect(-(ossim_int32)thePaddingSizeInPixels.x, -(ossim_int32)thePaddingSizeInPixels.y, (pixels.x-1) + (ossim_int32)thePaddingSizeInPixels.x, (pixels.y-1) + (ossim_int32)thePaddingSizeInPixels.y); if (m_useOffset) { resultingBounds = ossimIrect(-(ossim_int32)m_offsetInPixels.x, -(ossim_int32)m_offsetInPixels.y, (resultingBounds.width()-1), (resultingBounds.height()-1)); } } if(traceDebug()&&resultProjection.valid()) { ossimKeywordlist projKwl; resultProjection->saveState(projKwl); ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTilingRect::next DEBUG: rect = " << resultingBounds << "\nproj = " << projKwl << "\ntileName = " << resultingName << "\norigin = " << origin << std::endl; } resultProjection = theMapProjection; ++theTileId; } else { result = false; } return result; } bool ossimTilingRect::saveState(ossimKeywordlist& kwl, const char* prefix)const { std::stringstream tilingDistance; tilingDistance << theTilingDistance.x << " " << theTilingDistance.y << std::endl; kwl.add(prefix, "tile_size", tilingDistance.str().c_str(), true); kwl.add(prefix, "units", ossimUnitTypeLut::instance()-> getTableIndexString(theTilingDistanceUnitType), true); std::ostringstream padding; padding << thePaddingSizeInPixels.x << " " << thePaddingSizeInPixels.y; kwl.add(prefix, "padding", padding.str().c_str(), true); kwl.add(prefix, "output_file_name", theTileNameMask.c_str(), true); kwl.add(prefix, "clip_to_aoi", m_clipToAoi, true); return true; } bool ossimTilingRect::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; // Get the mask if any. theTileNameMask = kwl.find(prefix, "output_file_name"); if (!theTileNameMask.contains("%f%")) //%f% format is used for feature id in a shape file { setTileNameMask(theTileNameMask); } const char* paddingSizeInPixels = kwl.find(prefix, "padding"); if (paddingSizeInPixels) { ossimString x,y; std::istringstream padding(ossimString(paddingSizeInPixels).c_str()); padding >> x >> y; thePaddingSizeInPixels.x = x.toFloat64(); thePaddingSizeInPixels.y = y.toFloat64(); } const char* tilingDistance = kwl.find(prefix, "tile_size"); const char* tilingDistanceType = kwl.find(prefix, "units"); result = tilingDistance&&tilingDistanceType&&paddingSizeInPixels; ossimString x,y; std::istringstream distance(ossimString(tilingDistance).c_str()); distance >> x >> y; theTilingDistance.x = x.toFloat64(); theTilingDistance.y = y.toFloat64(); if(theTilingDistance.x <= 0.0) { theTilingDistance.x = 1.0; } if(theTilingDistance.y<=0.0) { theTilingDistance.y = theTilingDistance.x; } theTilingDistanceUnitType = (ossimUnitType) ossimUnitTypeLut::instance()->getEntryNumber( ossimString(tilingDistanceType).c_str()); const char* clipToAoi = kwl.find(prefix, "clip_to_aoi"); if (clipToAoi) { if (!ossimString(clipToAoi).toBool()) { m_clipToAoi = false; } } const char* offset = kwl.find(prefix, "use_offset"); if (offset) { ossimString width, height; std::istringstream distanceOffset(ossimString(offset).c_str()); distanceOffset >> width >> height; m_offsetInPixels.x = width.toFloat64(); m_offsetInPixels.y = height.toFloat64(); if (m_offsetInPixels.x > 0 || m_offsetInPixels.y > 0.0) { m_useOffset = true; result = true; } } const char* tileRes = kwl.find(prefix, "resolution"); if (tileRes) { theDelta = ossimDpt(0,0); x=""; y=""; std::istringstream tileResValues(ossimString(tileRes).c_str()); tileResValues >> x >> y; m_tilinResolutionDistance.x = x.toFloat64(); m_tilinResolutionDistance.y = y.toFloat64(); } const char* tilingResType = kwl.find(prefix, "resolution_units"); if (tilingResType) { m_tilingResolutionUnitType = (ossimUnitType) ossimUnitTypeLut::instance()->getEntryNumber( ossimString(tilingResType).c_str()); } if (traceDebug()) { print(ossimNotify(ossimNotifyLevel_DEBUG)); } return result; } ossimDpt ossimTilingRect::getPaddingSize()const { ossimDpt result = thePaddingSizeInPixels; if (!theMapProjection.valid()) return result; if(theMapProjection->isGeographic() && theTilingDistanceUnitType == OSSIM_DEGREES) { return result; } else { ossimUnitConversionTool unitConverter(1.0, theTilingDistanceUnitType); unitConverter.setValue(result.x, theTilingDistanceUnitType); result.x = unitConverter.getValue(OSSIM_METERS); unitConverter.setValue(result.y, theTilingDistanceUnitType); result.y = unitConverter.getValue(OSSIM_METERS); } return result; } void ossimTilingRect::getConvertedDistance(ossimDpt& pt, ossimDpt inputDistance) const { if (!theMapProjection) { // This should not happen... ossimNotify(ossimNotifyLevel_WARN) << "ossimTiling::getConvertedDistance WARNING" << " projection not set!" << endl; pt = inputDistance; return; } if(theMapProjection->isGeographic() && theTilingDistanceUnitType == OSSIM_DEGREES) { pt = inputDistance; } else { ossimUnitConversionTool unitConverter(theMapProjection->origin(), 1.0, theTilingDistanceUnitType); unitConverter.setValue(inputDistance.x, theTilingDistanceUnitType); pt.x = unitConverter.getValue(OSSIM_METERS); unitConverter.setValue(inputDistance.y, theTilingDistanceUnitType); pt.y = unitConverter.getValue(OSSIM_METERS); } } ossim-Miami-2.9.1/src/imaging/ossimTopographicCorrectionFilter.cpp000066400000000000000000001153251352751253100253600ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimTopographicCorrectionFilter.cpp 21184 2012-06-29 15:13:09Z dburken $ #include #include #include #include #include #include #include #include #include #include #include using namespace std; static const char* CORRECTION_TYPE_KW = "correction_type"; static const char* C_COMPUTED_FLAG_KW = "c_computed_flag"; static const char* NDVI_RANGE_KW = "ndvi_range"; RTTI_DEF1(ossimTopographicCorrectionFilter, "ossimTopographicCorrectionFilter", ossimImageCombiner); ossimTopographicCorrectionFilter::ossimTopographicCorrectionFilter() :ossimImageCombiner(NULL, 2, 0, true, false), theTile(NULL), // theScalarRemapper(NULL), theLightSourceElevationAngle(45.0), theLightSourceAzimuthAngle(45.0), theJulianDay(0), theCComputedFlag(false), theTopoCorrectionType(TOPO_CORRECTION_COSINE), // theTopoCorrectionType(TOPO_CORRECTION_MINNAERT), theNdviLowTest(-0.1), theNdviHighTest(0.1) { // theScalarRemapper = new ossimScalarRemapper(); // theScalarRemapper->setOutputScalarType(OSSIM_NORMALIZED_DOUBLE); // theScalarRemapper->initialize(); } ossimTopographicCorrectionFilter::ossimTopographicCorrectionFilter(ossimImageSource* colorSource, ossimImageSource* elevSource) :ossimImageCombiner(NULL, 2, 0, true, false), theTile(NULL), theLightSourceElevationAngle(45.0), theLightSourceAzimuthAngle(45.0), theJulianDay(0), theCComputedFlag(false), theTopoCorrectionType(TOPO_CORRECTION_COSINE), theNdviLowTest(-0.1), theNdviHighTest(0.1) { connectMyInputTo(colorSource); connectMyInputTo(elevSource); } ossimTopographicCorrectionFilter::~ossimTopographicCorrectionFilter() { } ossimRefPtr ossimTopographicCorrectionFilter::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); ossimImageSource* normalSource = PTR_CAST(ossimImageSource, getInput(1)); if(!isSourceEnabled()||!normalSource||!colorSource) { if(colorSource) { return colorSource->getTile(tileRect, resLevel); } } if(!theTile.valid()) { allocate(); } if(!theTile) { return ossimRefPtr(); } long w = tileRect.width(); long h = tileRect.height(); ossimIpt origin = tileRect.ul(); theTile->setOrigin(origin); long tileW = theTile->getWidth(); long tileH = theTile->getHeight(); if((w != tileW)|| (h != tileH)) { theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tileW*tileH)) { theTile->initialize(); } else { theTile->makeBlank(); } } else { theTile->makeBlank(); } // ossimImageData* inputTile = NULL; ossimRefPtr normalData = normalSource->getTile(tileRect, resLevel); ossimRefPtr colorData = colorSource->getTile(tileRect, resLevel); if(!colorData.valid() || !normalData.valid()) { return theTile; } if((normalData->getNumberOfBands() != 3)|| (normalData->getScalarType() != OSSIM_DOUBLE)|| !normalData->getBuf()|| !colorData->getBuf()|| (colorData->getDataObjectStatus() == OSSIM_EMPTY)|| (normalData->getDataObjectStatus()==OSSIM_EMPTY)) { return colorData; } executeTopographicCorrection(theTile, colorData, normalData); theTile->validate(); return theTile; } void ossimTopographicCorrectionFilter::initialize() { ossimImageCombiner::initialize(); // Force an "allocate()" on the first getTile. theTile = NULL; } void ossimTopographicCorrectionFilter::allocate() { if(!getInput(0) || !getInput(1)) return; theBandMapping.clear(); if(isSourceEnabled()) { // ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); int arraySize = theTile->getNumberOfBands(); if(theGain.size() > 0) { arraySize = (int)theGain.size(); } // we will do a non destructive resize onf the arrays // resizeArrays(arraySize); ossimImageSource* input1 = PTR_CAST(ossimImageSource, getInput(0)); if(input1) { input1->getOutputBandList(theBandMapping); for(ossim_uint32 idx = 0; idx < theBandMapping.size(); ++idx) { if(theBias.size()) { if(theBandMapping[idx] >= theBias.size()) { theBandMapping[idx] = (unsigned int)theBias.size()-1; } } else { theBandMapping[idx] = 0; } } } } computeLightDirection(); } void ossimTopographicCorrectionFilter::computeLightDirection() { NEWMAT::Matrix m = ossimMatrix3x3::createRotationMatrix(theLightSourceElevationAngle, 0.0, theLightSourceAzimuthAngle); NEWMAT::ColumnVector v(3); v[0] = 0; v[1] = 1; v[2] = 0; v = m*v; // reflect Z. We need the Z pointing up from the surface and not into it. // ossimColumnVector3d d(v[0], v[1], -v[2]); d = d.unit(); theLightDirection[0] = d[0]; theLightDirection[1] = d[1]; theLightDirection[2] = d[2]; } void ossimTopographicCorrectionFilter::executeTopographicCorrection( ossimRefPtr& outputData, ossimRefPtr& colorData, ossimRefPtr& normalData) { switch(colorData->getScalarType()) { case OSSIM_UCHAR: { if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT) { executeTopographicCorrectionTemplate((ossim_uint8)0, outputData, colorData, normalData); } else { executeTopographicCorrectionMinnaertTemplate((ossim_uint8)0, outputData, colorData, normalData); } break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT) { executeTopographicCorrectionTemplate((ossim_uint16)0, outputData, colorData, normalData); } else { executeTopographicCorrectionMinnaertTemplate((ossim_uint16)0, outputData, colorData, normalData); } break; } case OSSIM_SSHORT16: { if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT) { executeTopographicCorrectionTemplate((ossim_sint16)0, outputData, colorData, normalData); } else { executeTopographicCorrectionMinnaertTemplate((ossim_sint16)0, outputData, colorData, normalData); } break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT) { executeTopographicCorrectionTemplate((ossim_float64)0, outputData, colorData, normalData); } else { executeTopographicCorrectionMinnaertTemplate((ossim_float64)0, outputData, colorData, normalData); } break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT) { executeTopographicCorrectionTemplate((ossim_float32)0, outputData, colorData, normalData); } else { executeTopographicCorrectionMinnaertTemplate((ossim_float32)0, outputData, colorData, normalData); } break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimTopographicCorrectionFilter::executeTopographicCorrection WARN: Not handling scalar type" << endl; } } } template void ossimTopographicCorrectionFilter::executeTopographicCorrectionTemplate( T /* dummy */, ossimRefPtr& outputData, ossimRefPtr& colorData, ossimRefPtr& normalData) { ossim_int32 y = 0; ossim_int32 x = 0; ossim_int32 colorW = colorData->getWidth(); ossim_int32 colorH = colorData->getHeight(); T* colorDataBand = 0; T* outputDataBand = 0; ossim_float64 colorNp = 0; ossim_float64 colorMin = 0; ossim_float64 colorMax = 0; // ossim_float64 outputDelta = 0;; // ossim_float64 outputMin = 0; // ossim_float64 outputMax = 0; ossim_float64 outputNp; double normalNp = normalData->getNullPix(0); double LPrime = 0.0; double LNew = 0.0; double dn = 0.0; double cosineZenith = ossim::cosd(90 - theLightSourceElevationAngle); if(!colorData->getBuf()|| !normalData->getBuf()|| (colorData->getDataObjectStatus() == OSSIM_EMPTY)) { return; } for(ossim_uint32 b = 0; b < outputData->getNumberOfBands();++b) { int mappedBand = theBandMapping[b]; double* normalX = (double*)normalData->getBuf(0); double* normalY = (double*)normalData->getBuf(1); double* normalZ = (double*)normalData->getBuf(2); double numerator = cosineZenith + theC[mappedBand]; outputNp = (ossim_float64)outputData->getNullPix(b); // outputMin = (ossim_float64)outputData->getMinPix(b); // outputMax = (ossim_float64)outputData->getMaxPix(b); // outputDelta = outputMax - outputMin; colorDataBand = (T*)(colorData->getBuf(b)); colorNp = (ossim_float64)(colorData->getNullPix(b)); colorMin = (ossim_float64)(colorData->getMinPix(b)); colorMax = (ossim_float64)(colorData->getMaxPix(b)); outputDataBand = (T*)(outputData->getBuf(b)); bool theValuesAreGood = b < theC.size(); double c = theC[mappedBand]; if(theTopoCorrectionType != TOPO_CORRECTION_COSINE_C) { c = 0; } for(y = 0; y < colorH; ++y) { for(x = 0; x < colorW; ++x) { if((*colorDataBand) != colorNp) { if((*normalX != normalNp)&& (*normalY != normalNp)&& (*normalZ != normalNp)&& theValuesAreGood) { double cosineNewI = ((*normalX)*theLightDirection[0] + (*normalY)*theLightDirection[1] + (*normalZ)*theLightDirection[2]); double cosineRatioDenom = (cosineNewI + c); if((fabs(cosineRatioDenom) > FLT_EPSILON)&&(cosineNewI >= 0.0)) { double cosineRatio = numerator/cosineRatioDenom; LPrime = theGain[mappedBand]*((ossim_float64)(*colorDataBand)) + theBias[mappedBand]; LNew = LPrime*cosineRatio; dn = ((LNew-theBias[mappedBand])/theGain[mappedBand]); if(dn < colorMin) dn = colorMin; if(dn > colorMax) dn = colorMax; *outputDataBand = (T)(dn); } else { *outputDataBand = (T)(*colorDataBand); } } else { *outputDataBand = (T)(*colorDataBand); } } else { *outputDataBand = (T)outputNp; } ++outputDataBand; ++colorDataBand; ++normalX; ++normalY; ++normalZ; } } } } template void ossimTopographicCorrectionFilter::executeTopographicCorrectionMinnaertTemplate( T /* dummy */, ossimRefPtr& outputData, ossimRefPtr& colorData, ossimRefPtr& normalData) { ossim_int32 y = 0; ossim_int32 x = 0; ossim_int32 colorW = colorData->getWidth(); ossim_int32 colorH = colorData->getHeight(); T* colorDataBand = 0; T* outputDataBand = 0; ossim_float64 colorNp = 0; ossim_float64 colorMin = 0; ossim_float64 colorMax = 0; // ossim_float64 outputDelta = 0;; // ossim_float64 outputMin = 0; // ossim_float64 outputMax = 0; ossim_float64 outputNp; double normalNp = normalData->getNullPix(0); double LPrime = 0.0; double LNew = 0.0; double dn = 0.0; if(!colorData->getBuf()|| !normalData->getBuf()|| (colorData->getDataObjectStatus() == OSSIM_EMPTY)) { return; } int maxBands = ossim::min((int)theK.size(), (int)outputData->getNumberOfBands()); for(int b = 0; b < maxBands;++b) { int mappedBand = theBandMapping[b]; double* normalX = (double*)normalData->getBuf(0); double* normalY = (double*)normalData->getBuf(1); double* normalZ = (double*)normalData->getBuf(2); outputNp = (ossim_float64)outputData->getNullPix(b); // outputMin = (ossim_float64)outputData->getMinPix(b); // outputMax = (ossim_float64)outputData->getMaxPix(b); // outputDelta = outputMax - outputMin; colorDataBand = (T*)(colorData->getBuf(b)); colorNp = (ossim_float64)(colorData->getNullPix(b)); colorMin = (ossim_float64)(colorData->getMinPix(b)); colorMax = (ossim_float64)(colorData->getMaxPix(b)); outputDataBand = (T*)(outputData->getBuf(b)); for(y = 0; y < colorH; ++y) { for(x = 0; x < colorW; ++x) { if((*colorDataBand) != colorNp) { if((*normalX != normalNp)&& (*normalY != normalNp)&& (*normalZ != normalNp)) { // if(fabs(*normalZ) < FLT_EPSILON) // { // *normalZ = 0.0; // } double cosineNewI = (((*normalX)*theLightDirection[0] + (*normalY)*theLightDirection[1] + (*normalZ)*theLightDirection[2])); double slopeAngle = acos(*normalZ); double cosineSlope = cos(slopeAngle); double k = theK[mappedBand]; double cosineSlopeKPower = pow(cosineSlope, k); double denom = pow((double)cosineNewI, k)*cosineSlopeKPower; double numerator = cosineSlope; // double slopeAngle = asin(*normalZ); // double tempK = theK[mappedBand]*cosineNewI; // double denom = pow((double)cosineNewI*cosineSlope, theK[mappedBand]); // double numerator = pow((double)cosineSlope, 1-tempK); // if((fabs(denom) > .0001)&&(cosineNewI >= 0.0)) // if((cosineNewI >= 0.0) &&fabs(denom) > .000001) if(fabs(denom) > .00000001) { // double cosineRatio = cosineSlope/denom; double cosineRatio = numerator/denom; LPrime = theGain[mappedBand]*((ossim_float64)(*colorDataBand)) + theBias[mappedBand]; LNew = LPrime*cosineRatio; dn = ((LNew-theBias[mappedBand])/theGain[mappedBand]); if(dn < colorMin) dn = colorMin; if(dn > colorMax) dn = colorMax; *outputDataBand = (T)(dn); } else { *outputDataBand = (T)(*colorDataBand); } } else { *outputDataBand = (T)(*colorDataBand); } } else { *outputDataBand = (T)outputNp; } ++outputDataBand; ++colorDataBand; ++normalX; ++normalY; ++normalZ; } } } } #if 0 void ossimTopographicCorrectionFilter::computeC() { theCComputedFlag = false; int b = 0; int tileCount = 0; bool done = false; if(theC.size()<1) return; for(b = 0; b < (int) theC.size(); ++b) { theC[b] = 0.0; } theNdviLowTest = 0.1; theNdviHighTest = 1; ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); ossimImageSource* normalSource = PTR_CAST(ossimImageSource, getInput(1)); if(!colorSource || !normalSource) { return; } std::vector linearRegression(theC.size()); ossimIrect normalRect = normalSource->getBoundingRect(); ossimIrect colorRect = colorSource->getBoundingRect(); ossimIrect clipRect = normalRect.clipToRect(colorRect); ossimIpt ul = clipRect.ul(); ossimIpt lr = clipRect.lr(); ossimIpt tileSize(128,128); ossim_int32 tilesHoriz = clipRect.width()/tileSize.x; ossim_int32 tilesVert = clipRect.height()/tileSize.y; if(!normalRect.intersects(colorRect)) { return; } ossim_int32 maxSize = tilesHoriz*tilesVert;//ossim::min(200, ); int idx = 0; idx = 0; std::vector cosineIBucketCount(10); std::fill(cosineIBucketCount.begin(), cosineIBucketCount.end(), 0); const int maxBucketCount = 1000; bool goodCoefficients = false; long numberOfRuns = 0; while((!goodCoefficients)&&(numberOfRuns < 2)) { while((idx < maxSize)&& (!done)) { ossim_int32 ty = idx/tilesHoriz; ossim_int32 tx = idx%tilesHoriz; ossim_int32 x = (ul.x + tx*tileSize.x); ossim_int32 y = (ul.y + ty*tileSize.y); ossimIrect requestRect(x, y, x+tileSize.x-1, y+tileSize.y-1); ossimRefPtr colorData = colorSource->getTile(requestRect); ossimRefPtr normalData = normalSource->getTile(requestRect); switch(colorData->getScalarType()) { case OSSIM_UCHAR: { addRegressionPointsTemplate((ossim_uint8)0, linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_USHORT16: { addRegressionPointsTemplate((ossim_uint16)0, linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData); break; } case OSSIM_SSHORT16: { addRegressionPointsTemplate((ossim_sint16)0, linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { addRegressionPointsTemplate((ossim_float32)0, linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { addRegressionPointsTemplate((ossim_float64)0, linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData); break; } } if(((double)linearRegression[0].getNumberOfPoints()/(double)(maxBucketCount*10.0))>=.7) { done = true; } ++idx; } double intercept, m; long numberOfPositiveSlopes=0; for(b=0;b2) { linearRegression[b].solve(); linearRegression[b].getEquation(m, intercept); theC[b] = intercept/m; ossimNotify(ossimNotifyLevel_INFO) << "equation for b = " << b <<" is y = " << m << "*x + " << intercept << endl << "with c = " << theC[b] << endl; if(m >=0.0) { numberOfPositiveSlopes++; } } } for(idx = 0; idx < cosineIBucketCount.size(); ++idx) { ossimNotify(ossimNotifyLevel_INFO) << "bucket " << idx << " = " << cosineIBucketCount[idx] << endl; } if(numberOfPositiveSlopes > .5*theC.size()) { goodCoefficients = true; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimTopographicCorrectionFilter::computeC() WARN: not enough positive slopes" << endl << "changing test to look for dirt areas" << endl; theNdviLowTest = -1.0; theNdviHighTest = .1; for(b=0;b void ossimTopographicCorrectionFilter::addRegressionPointsTemplate( T, //dummy std::vector& regressionPoints, std::vector& cosineIBucketCount, ossim_int32 maxCountPerBucket, ossimRefPtr& colorData, ossimRefPtr& normalData) { if(!colorData||!normalData) { return; } if((colorData->getDataObjectStatus() == OSSIM_EMPTY)|| (!colorData->getBuf())|| (!normalData->getBuf())|| (normalData->getDataObjectStatus()==OSSIM_EMPTY)) { return; } ossim_float64* normalBands[3]; ossim_float64 normalBandsNp[3]; ossim_uint32 count=0; ossim_uint32 b = 0; std::vector colorBands(colorData->getNumberOfBands()); std::vector colorBandsNp(colorData->getNumberOfBands()); normalBands[0] = (ossim_float64*)normalData->getBuf(0); normalBands[1] = (ossim_float64*)normalData->getBuf(1); normalBands[2] = (ossim_float64*)normalData->getBuf(2); normalBandsNp[0] = normalData->getNullPix(0); normalBandsNp[1] = normalData->getNullPix(1); normalBandsNp[2] = normalData->getNullPix(2); for(b=0;bgetNumberOfBands();++b) { colorBands[b] = (T*)colorData->getBuf(b); colorBandsNp[b] = (T)colorData->getNullPix(b); } ossim_uint32 maxOffset = colorData->getWidth()*colorData->getHeight(); ossim_uint32 offset=0; ossim_float64 ndviTest=0.0; ossim_uint32 numberOfTests = 0; if(maxOffset) { maxOffset-=1; } ossim_int32 percent = (ossim_int32)(colorData->getWidth()*colorData->getHeight()*.2); offset = 0; ossim_uint32 countPixels = 0; while(offset < maxOffset) { bool nullBandsExist = false; for(b = 0; ((b < colorData->getNumberOfBands())&&(!nullBandsExist));++b) { if(*colorBands[b] == colorBandsNp[b]) { nullBandsExist = true; } } if((!nullBandsExist)&& (*normalBands[0] != normalBandsNp[0])&& (*normalBands[1] != normalBandsNp[1])&& (*normalBands[2] != normalBandsNp[2])) { if(computeNdvi((T)0, ndviTest, offset, colorBands)) { if((ndviTest >= theNdviLowTest) && (ndviTest <= theNdviHighTest)) { double cosineI = ((*(normalBands[0]+offset))*theLightDirection[0] + (*(normalBands[1]+offset))*theLightDirection[1] + (*(normalBands[2]+offset))*theLightDirection[2]); if(cosineI >= 0.0) { long bucketIdx = (long)(cosineI*cosineIBucketCount.size()); // we will try to disperse the normals out and so we don't clump everything // in one place // if(cosineIBucketCount[bucketIdx] < maxCountPerBucket) { for(b = 0; b < colorData->getNumberOfBands();++b) { regressionPoints[b].addPoint(ossimDpt(cosineI, *(colorBands[b]+offset))); } ++cosineIBucketCount[bucketIdx]; ++count; } } } } } ++offset; } } #endif template bool ossimTopographicCorrectionFilter::computeNdvi( T, ossim_float64& result, ossim_uint32 offset, const std::vector& bands)const { if(bands.size() > 3) { result = (((double)*(bands[3]+offset) - (double)*(bands[2]+offset))/ ((double)*(bands[3]+offset) + (double)*(bands[2]+offset))); return true; } return false; } void ossimTopographicCorrectionFilter::resizeArrays(ossim_uint32 newSize) { if(!getInput(0) || !getInput(1)) return; vector tempC = theC; vector tempK = theK; vector tempBias = theBias; vector tempGain = theGain; theC.resize(newSize); theK.resize(newSize); theBias.resize(newSize); theGain.resize(newSize); ossim_uint32 tempIdx = 0; if(tempC.size() > 0 && (theC.size() > 0)) { int numberOfElements = ossim::min((int)tempC.size(),(int)theC.size()); std::copy(tempC.begin(), tempC.begin()+numberOfElements, theC.begin()); std::copy(tempK.begin(), tempK.begin()+numberOfElements, theK.begin()); std::copy(tempBias.begin(), tempBias.begin()+numberOfElements, theBias.begin()); std::copy(tempGain.begin(), tempGain.begin()+numberOfElements, theGain.begin()); if(theC.size() > tempC.size()) { std::fill(theC.begin()+numberOfElements, theC.end(), (double)0.0); std::fill(theBias.begin()+numberOfElements, theBias.end(), (double)0.0); std::fill(theGain.begin()+numberOfElements, theGain.end(), (double)1.0); for(tempIdx = numberOfElements; tempIdx < theK.size(); ++tempIdx) { theK[tempIdx] = 0.3 + .4*(tempIdx/(double)(theK.size())); } } } else { std::fill(theC.begin(), theC.end(), (double)0.0); std::fill(theBias.begin(), theBias.end(), (double)0.0); std::fill(theGain.begin(), theGain.end(), (double)1.0); for(tempIdx = 0; tempIdx < theK.size(); ++tempIdx) { theK[tempIdx] = 0.3 + .4*(tempIdx/(double)(theK.size())); } } } bool ossimTopographicCorrectionFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString elevAngle = kwl.find(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW); ossimString azimuthAngle = kwl.find(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW); ossimString bands = kwl.find(prefix, ossimKeywordNames::NUMBER_BANDS_KW); ossimString correctionType = kwl.find(prefix, CORRECTION_TYPE_KW); ossimString julianDay = kwl.find(prefix, ossimKeywordNames::JULIAN_DAY_KW); ossimString cComputedFlag = kwl.find(prefix, C_COMPUTED_FLAG_KW); ossimString ndviRange = kwl.find(prefix, NDVI_RANGE_KW); theCComputedFlag = cComputedFlag.toBool(); correctionType = correctionType.downcase(); int numberOfBands = bands.toInt(); theLightSourceElevationAngle = elevAngle.toDouble(); theLightSourceAzimuthAngle = azimuthAngle.toDouble(); theJulianDay = julianDay.toDouble(); if(ndviRange != "") { std::istringstream input(ndviRange.c_str()); input >> theNdviLowTest >> theNdviHighTest; } if(numberOfBands>0) { theGain.resize(numberOfBands); theBias.resize(numberOfBands); theC.resize(numberOfBands); theK.resize(numberOfBands); for(int b = 0; b < numberOfBands; ++b) { ossimString k = "k"+ossimString::toString(b); ossimString c = "c"+ossimString::toString(b); ossimString bias = "bias"+ossimString::toString(b); ossimString gain = "gain"+ossimString::toString(b); const char* kValue = kwl.find(prefix, k); const char* cValue = kwl.find(prefix, c); const char* biasValue = kwl.find(prefix, bias); const char* gainValue = kwl.find(prefix, gain); if(kValue) { theK[b] = ossimString(kValue).toDouble(); } else { theK[b] = 1.0; } if(cValue) { theC[b] = ossimString(cValue).toDouble(); } else { theC[b] = 0.0;; } if(biasValue) { theBias[b] = ossimString(biasValue).toDouble(); } else { theBias[b] = 0.0; } if(gainValue) { theGain[b] = ossimString(gainValue).toDouble(); } else { theGain[b] = 1.0; } } } if(correctionType.contains("cosine_c")) { theTopoCorrectionType = TOPO_CORRECTION_COSINE_C; } else if(correctionType.contains("minnaert")) { theTopoCorrectionType = TOPO_CORRECTION_MINNAERT; } else { theTopoCorrectionType = TOPO_CORRECTION_COSINE; } bool result = ossimImageCombiner::loadState(kwl, prefix); computeLightDirection(); return result; } bool ossimTopographicCorrectionFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { // we can use any of the arrays theC, theBias, or theGain since // they mirror the number of input bands // int numberOfBands = (int)theC.size(); kwl.add(prefix, ossimKeywordNames::NUMBER_BANDS_KW, numberOfBands, true); kwl.add(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW, theLightSourceElevationAngle, true); kwl.add(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW, theLightSourceAzimuthAngle, true); kwl.add(prefix, C_COMPUTED_FLAG_KW, (ossim_uint32)theCComputedFlag, true); kwl.add(prefix, NDVI_RANGE_KW, ossimString::toString(theNdviLowTest) + " " + ossimString::toString(theNdviHighTest), true); if(theTopoCorrectionType == TOPO_CORRECTION_COSINE_C) { kwl.add(prefix, CORRECTION_TYPE_KW, "cosine_c", true); } else if(theTopoCorrectionType == TOPO_CORRECTION_MINNAERT) { kwl.add(prefix, CORRECTION_TYPE_KW, "minnaert", true); } else { kwl.add(prefix, CORRECTION_TYPE_KW, "cosine", true); } for(int b = 0; b < numberOfBands; ++b) { ossimString k = "k"+ossimString::toString(b); ossimString c = "c"+ossimString::toString(b); ossimString bias = "bias"+ossimString::toString(b); ossimString gain = "gain"+ossimString::toString(b); kwl.add(prefix, k, theK[b], true); kwl.add(prefix, c, theC[b], true); kwl.add(prefix, bias, theBias[b], true); kwl.add(prefix, gain, theGain[b], true); } return ossimImageCombiner::saveState(kwl, prefix); } ossim_uint32 ossimTopographicCorrectionFilter::getNumberOfOutputBands() const { ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); if(colorSource) { return colorSource->getNumberOfOutputBands(); } return ossimImageCombiner::getNumberOfOutputBands(); } ossimScalarType ossimTopographicCorrectionFilter::getOutputScalarType() const { ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); if(colorSource) { return colorSource->getOutputScalarType(); } return ossimImageCombiner::getOutputScalarType(); } double ossimTopographicCorrectionFilter::getNullPixelValue(ossim_uint32 band)const { ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); if(colorSource) { return colorSource->getNullPixelValue(band); } return ossimImageCombiner::getNullPixelValue(band); } double ossimTopographicCorrectionFilter::getMinPixelValue(ossim_uint32 band)const { ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); if(colorSource) { return colorSource->getMinPixelValue(band); } return ossimImageCombiner::getMinPixelValue(band); } double ossimTopographicCorrectionFilter::getMaxPixelValue(ossim_uint32 band)const { ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); if(colorSource) { return colorSource->getMaxPixelValue(band); } return ossimImageCombiner::getMaxPixelValue(band); } ossimIrect ossimTopographicCorrectionFilter::getBoundingRect(ossim_uint32 resLevel)const { ossimIrect result; result.makeNan(); ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); if(colorSource) { result = colorSource->getBoundingRect(resLevel); } return result; } void ossimTopographicCorrectionFilter::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { result.makeNan(); ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); if(colorSource) { colorSource->getDecimationFactor(resLevel, result); } } void ossimTopographicCorrectionFilter::getDecimationFactors(vector& decimations) const { ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); if(colorSource) { colorSource->getDecimationFactors(decimations); } } ossim_uint32 ossimTopographicCorrectionFilter::getNumberOfDecimationLevels()const { ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0)); if(colorSource) { return colorSource->getNumberOfDecimationLevels(); } return 0; } double ossimTopographicCorrectionFilter::getAzimuthAngle()const { return theLightSourceAzimuthAngle; } double ossimTopographicCorrectionFilter::getElevationAngle()const { return theLightSourceElevationAngle; } void ossimTopographicCorrectionFilter::setAzimuthAngle(double angle) { theLightSourceAzimuthAngle = angle; } void ossimTopographicCorrectionFilter::setElevationAngle(double angle) { theLightSourceElevationAngle = angle; } bool ossimTopographicCorrectionFilter::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const { return (object&& ( (inputIndex>=0) && inputIndex < 2)&& PTR_CAST(ossimImageSource, object)); } void ossimTopographicCorrectionFilter::connectInputEvent(ossimConnectionEvent& /* event */) { initialize(); } void ossimTopographicCorrectionFilter::disconnectInputEvent(ossimConnectionEvent& /* event */) { initialize(); } void ossimTopographicCorrectionFilter::propertyEvent(ossimPropertyEvent& /* event */) { initialize(); } void ossimTopographicCorrectionFilter::refreshEvent(ossimRefreshEvent& /* event */) { initialize(); } ossimTopographicCorrectionFilter::ossimTopoCorrectionType ossimTopographicCorrectionFilter::getTopoCorrectionType()const { return theTopoCorrectionType; } void ossimTopographicCorrectionFilter::setTopoCorrectionType(ossimTopoCorrectionType topoType) { theTopoCorrectionType = topoType; } const std::vector& ossimTopographicCorrectionFilter::getGainValues()const { return theGain; } void ossimTopographicCorrectionFilter::setGainValues(const std::vector& gainValues) { theGain = gainValues; } const vector& ossimTopographicCorrectionFilter::getBiasValues()const { return theBias; } void ossimTopographicCorrectionFilter::setBiasValues(const std::vector& biasValues) { theBias = biasValues; } const vector& ossimTopographicCorrectionFilter::getKValues()const { return theK; } double ossimTopographicCorrectionFilter::getK(int idx)const { if(idx < (int)theK.size()) { return theK[idx]; } else { return 1.0; } } void ossimTopographicCorrectionFilter::setK(int idx, double value) { if(idx < (int)theK.size()) { theK[idx] = value; } } void ossimTopographicCorrectionFilter::setKValues(const vector& kValues) { theK = kValues; } double ossimTopographicCorrectionFilter::getC(int idx)const { if(idx < (int)theC.size()) { return theC[idx]; } else { return 0.0; } } void ossimTopographicCorrectionFilter::setC(int idx, double value) { if(idx < (int)theC.size()) { theC[idx] = value; } } void ossimTopographicCorrectionFilter::setCValues(const vector& cValues) { theC = cValues; } ossim-Miami-2.9.1/src/imaging/ossimTrimFilter.cpp000066400000000000000000000243461352751253100217660ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimTrimFilter.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimTrimFilter:debug"); RTTI_DEF1(ossimTrimFilter, "ossimTrimFilter", ossimImageSourceFilter); ossimTrimFilter::ossimTrimFilter() :ossimImageSourceFilter(), theLeftPercent(0.0), theRightPercent(0.0), theTopPercent(0.0), theBottomPercent(0.0) { theCutter = new ossimPolyCutter; } ossimTrimFilter::~ossimTrimFilter() { theCutter = 0; } ossimRefPtr ossimTrimFilter::getTile( const ossimIrect& rect, ossim_uint32 resLevel) { if(!theInputConnection) { return NULL; } if(!theValidVertices.size()) { return ossimImageSourceFilter::getTile(rect, resLevel); } ossimRefPtr tile = theCutter->getTile(rect, resLevel); if(!isSourceEnabled()||!tile.valid()) { return tile; } if(tile->getDataObjectStatus() == OSSIM_NULL || tile->getDataObjectStatus() == OSSIM_EMPTY) { return tile; } return theCutter->getTile(rect, resLevel); // theTile->setImageRectangle(rect); // theTile->setDataObjectStatus(OSSIM_FULL); // theTile->makeBlank(); // ossimIrect boundingRect = getBoundingRect(resLevel); // ossimIrect tileRect = tile->getImageRectangle(); // ossimIrect clipRect = boundingRect.clipToRect(tileRect); // theTile->loadTile(tile->getBuf(), // tile->getImageRectangle(), // clipRect, // OSSIM_BSQ); // theTile->validate(); } void ossimTrimFilter::getValidImageVertices( vector& validVertices, ossimVertexOrdering ordering, ossim_uint32 resLevel)const { ossimImageSource::getValidImageVertices(validVertices, ordering, resLevel); if(validVertices.size()==4) { ossimDpt averagePt((ossimDpt(validVertices[0])+ ossimDpt(validVertices[1])+ ossimDpt(validVertices[2])+ ossimDpt(validVertices[3]))*.25); ossimDpt averageTop( ( ossimDpt(validVertices[0]+ validVertices[1])*.5) ); ossimDpt averageBottom( ( ossimDpt(validVertices[2]+ validVertices[3])*.5 ) ); ossimDpt averageLeft( (ossimDpt(validVertices[0]+ validVertices[3])*.5) ); ossimDpt averageRight( (ossimDpt(validVertices[1]+ validVertices[2])*.5) ); ossimDpt topAxis = (averageTop-averagePt); ossimDpt rightAxis = (averageRight-averagePt); ossimDpt leftAxis = (averageLeft-averagePt); ossimDpt bottomAxis = (averageBottom-averagePt); double topLen = topAxis.length(); double bottomLen = bottomAxis.length(); double rightLen = rightAxis.length(); double leftLen = leftAxis.length(); if((topLen > FLT_EPSILON)&& (bottomLen > FLT_EPSILON)&& (leftLen > FLT_EPSILON)&& (rightLen > FLT_EPSILON)) { topAxis = topAxis*(1.0/topLen); bottomAxis = bottomAxis*(1.0/bottomLen); leftAxis = leftAxis*(1.0/leftLen); rightAxis = rightAxis*(1.0/rightLen); ossim_uint32 idx = 0; ossim_uint32 count = 0; for(idx = 0; idx < validVertices.size(); ++idx) { ossimDpt axis[2]; double axisLen[2]; ossimDpt diff = validVertices[idx]-averagePt; double testLen = (topAxis.x*diff.x+ topAxis.y*diff.y); count = 0; if(testLen >= -FLT_EPSILON) { axis[count] = topAxis; axisLen[count] = testLen*(1.0-theTopPercent); ++count; } if(count < 2) { testLen = (bottomAxis.x*diff.x+ bottomAxis.y*diff.y); if(testLen >= -FLT_EPSILON) { axis[count] = bottomAxis; axisLen[count] = testLen*(1.0-theBottomPercent); ++count; } } if(count < 2) { testLen = (leftAxis.x*diff.x+ leftAxis.y*diff.y); if(testLen >= -FLT_EPSILON) { axis[count] = leftAxis; axisLen[count] = testLen*(1.0-theLeftPercent); ++count; } } if(count < 2) { testLen = (rightAxis.x*diff.x+ rightAxis.y*diff.y); if(testLen >= -FLT_EPSILON) { axis[count] = rightAxis; axisLen[count] = testLen*(1.0-theRightPercent); ++count; } } if(count == 2) { validVertices[idx] = (averagePt + (axis[0]*axisLen[0] + axis[1]*axisLen[1])); } } } } // ossimIrect rect = getBoundingRect(); // if(ordering == OSSIM_CLOCKWISE_ORDER) // { // validVertices.push_back(rect.ul()); // validVertices.push_back(rect.ur()); // validVertices.push_back(rect.lr()); // validVertices.push_back(rect.ll()); // } // else // { // validVertices.push_back(rect.ul()); // validVertices.push_back(rect.ll()); // validVertices.push_back(rect.lr()); // validVertices.push_back(rect.ur()); // } } ossimIrect ossimTrimFilter::getBoundingRect(ossim_uint32 resLevel)const { vector validVertices; ossimIrect result; result.makeNan(); getValidImageVertices(validVertices, OSSIM_CLOCKWISE_ORDER, resLevel); if(validVertices.size()) { result = ossimIrect(validVertices); } return result; } void ossimTrimFilter::initialize() { if(theInputConnection) { theCutter->disconnectMyInput(0, false, false); if(getInput()) { theCutter->connectMyInputTo(0, getInput()); } theCutter->initialize(); getValidImageVertices(theValidVertices); theCutter->setNumberOfPolygons(1); theCutter->setPolygon(theValidVertices); } } bool ossimTrimFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "left_percent", theLeftPercent, true); kwl.add(prefix, "right_percent", theRightPercent, true); kwl.add(prefix, "top_percent", theTopPercent, true); kwl.add(prefix, "bottom_percent", theBottomPercent, true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimTrimFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* leftPerc = kwl.find(prefix, "left_percent"); const char* rightPerc = kwl.find(prefix, "right_percent"); const char* topPerc = kwl.find(prefix, "top_percent"); const char* bottomPerc = kwl.find(prefix, "bottom_percent"); if(leftPerc) { theLeftPercent = ossimString(leftPerc).toDouble(); } if(rightPerc) { theRightPercent = ossimString(rightPerc).toDouble(); } if(topPerc) { theTopPercent = ossimString(topPerc).toDouble(); } if(bottomPerc) { theBottomPercent = ossimString(bottomPerc).toDouble(); } return ossimImageSourceFilter::loadState(kwl, prefix); } ossimRefPtr ossimTrimFilter::getProperty(const ossimString& name)const { ossimProperty* prop = 0; if(name == "left_percent") { prop = new ossimNumericProperty(name, ossimString::toString(theLeftPercent), 0.0, 1.0); prop->setFullRefreshBit(); } else if(name == "right_percent") { prop = new ossimNumericProperty(name, ossimString::toString(theRightPercent), 0.0, 1.0); prop->setFullRefreshBit(); } else if(name == "top_percent") { prop = new ossimNumericProperty(name, ossimString::toString(theTopPercent), 0.0, 1.0); prop->setFullRefreshBit(); } else if(name == "bottom_percent") { prop = new ossimNumericProperty(name, ossimString::toString(theBottomPercent), 0.0, 1.0); prop->setFullRefreshBit(); } if(prop) return prop; return ossimImageSourceFilter::getProperty(name); } void ossimTrimFilter::setProperty(ossimRefPtr property) { if(!property.valid())return; ossimString name = property->getName(); if(name == "left_percent") { theLeftPercent = property->valueToString().toDouble(); } else if(name == "right_percent") { theRightPercent = property->valueToString().toDouble(); } else if(name == "top_percent") { theTopPercent = property->valueToString().toDouble(); } else if(name == "bottom_percent") { theBottomPercent = property->valueToString().toDouble(); } else { return ossimImageSourceFilter::setProperty(property); } } void ossimTrimFilter::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back("left_percent"); propertyNames.push_back("right_percent"); propertyNames.push_back("top_percent"); propertyNames.push_back("bottom_percent"); } ossim-Miami-2.9.1/src/imaging/ossimTwoColorView.cpp000066400000000000000000000263561352751253100223130ustar00rootroot00000000000000//------------------------------------------------------------------- // License: LGPL. See top level LICENSE.txt file. // // Author: Garrett Potts // //------------------------------------------------------------------- // $Id$ #include #include RTTI_DEF1(ossimTwoColorView, "ossimTwoColorView" , ossimImageCombiner); ossimTwoColorView::ossimTwoColorView() : ossimImageCombiner(0, 2, 0, true, false) , m_byPassFlag(true), m_nativeFlag(false), m_newInput(0), m_oldInput(0), m_newInputBandIndex(0), m_oldInputBandIndex(0), m_redSource(ossimTwoColorView::OLD), m_grnSource(ossimTwoColorView::NEW), m_bluSource(ossimTwoColorView::NEW) { } ossim_uint32 ossimTwoColorView::getNumberOfOutputBands() const { if(m_byPassFlag||!isSourceEnabled()) { return ossimImageCombiner::getNumberOfOutputBands(); } return 3; } ossimScalarType ossimTwoColorView::getOutputScalarType() const { if(m_byPassFlag||!isSourceEnabled()) { return ossimImageCombiner::getOutputScalarType(); } return OSSIM_UINT8; } void ossimTwoColorView::setBandIndexMapping( ossim_uint32 oldInputBandIndex, ossim_uint32 newInputBandIndex, ossimTwoColorMultiViewOutputSource redOutputSource, ossimTwoColorMultiViewOutputSource grnOutputSource, ossimTwoColorMultiViewOutputSource bluOutputSource) { m_oldInputBandIndex = oldInputBandIndex; m_newInputBandIndex = newInputBandIndex; m_redSource = redOutputSource; m_grnSource = grnOutputSource; m_bluSource = bluOutputSource; } double ossimTwoColorView::getNullPixelValue(ossim_uint32 band)const { if(m_byPassFlag||!isSourceEnabled()) { return ossimImageCombiner::getNullPixelValue(band); } return 0; } double ossimTwoColorView::getMinPixelValue(ossim_uint32 band)const { if(m_byPassFlag||!isSourceEnabled()) { return ossimImageCombiner::getMinPixelValue(band); } return 1; } double ossimTwoColorView::getMaxPixelValue(ossim_uint32 band)const { if(m_byPassFlag||!isSourceEnabled()) { return ossimImageCombiner::getMaxPixelValue(band); } return 256; } ossimRefPtr ossimTwoColorView::getTile(const ossimIrect& rect, ossim_uint32 resLevel) { ossim_uint32 tileIdx = 0; if(m_byPassFlag||!isSourceEnabled()) { return getNextTile(tileIdx, 0, rect, resLevel); } if(!m_twoColorTile.valid()) { allocate(); } if(!m_twoColorTile.valid()) { return m_twoColorTile; } m_twoColorTile->setImageRectangle(rect); m_twoColorTile->makeBlank(); ossimRefPtr newData = m_newInput->getTile(rect, resLevel); ossimRefPtr oldData = m_oldInput->getTile(rect, resLevel); runAlgorithm(newData.get(), oldData.get()); m_twoColorTile->validate(); return m_twoColorTile; } void ossimTwoColorView::runAlgorithm(ossimImageData* newData, ossimImageData* oldData) { if(m_nativeFlag) { runNative8(newData, oldData); } else { runNorm(newData, oldData); } } void ossimTwoColorView::runNative8(ossimImageData* newData, ossimImageData* oldData) { if ( newData && oldData && m_twoColorTile.valid() && ( m_twoColorTile->getNumberOfBands() == 3 ) ) { // old, new, red, green, blue buffers... ossim_uint8* o = static_cast( oldData->getBuf(m_oldInputBandIndex) ); ossim_uint8* n = static_cast( newData->getBuf(m_newInputBandIndex) ); ossim_uint8* r = static_cast( m_twoColorTile->getBuf(0) ); ossim_uint8* g = static_cast( m_twoColorTile->getBuf(1) ); ossim_uint8* b = static_cast( m_twoColorTile->getBuf(2) ); if ( o && n && r && g && b ) { // Assuming null pix of 0 for 8 bit. const ossim_uint8 MP = 1; const ossim_uint8 NP = 0; ossim_uint8 newPix = 0; ossim_uint8 oldPix = 0; const ossim_uint32 MAX_IDX = m_twoColorTile->getSizePerBand(); for(ossim_uint32 idx = 0; idx < MAX_IDX; ++idx) { if( ( *n == NP ) && ( *o == NP ) ) { // Both inputs null, set all outputs null. *r = NP; *b = NP; *g = NP; } else { // At least one input is not null. newPix = (*n != NP) ? *n : MP; oldPix = (*o != NP) ? *o : MP; // Set red, OLD is default so check first: if ( m_redSource == ossimTwoColorView::OLD ) { *r = oldPix; } else if ( m_redSource == ossimTwoColorView::NEW ) { *r = newPix; } else { *r = MP; } // Set green, NEW is default so check first: if ( m_grnSource == ossimTwoColorView::NEW ) { *g = newPix; } else if ( m_grnSource == ossimTwoColorView::OLD ) { *g = oldPix; } else { *g = MP; } // Set blue, NEW is default so check first: if ( m_grnSource == ossimTwoColorView::NEW ) { *b = newPix; } else if ( m_grnSource == ossimTwoColorView::OLD ) { *b = oldPix; } else { *b = MP; } } // Next pixel: ++n; ++o; ++r; ++g; ++b; } } } } void ossimTwoColorView::runNorm(ossimImageData* newData, ossimImageData* oldData) { if ( newData && oldData && m_twoColorTile.valid() && ( m_twoColorTile->getNumberOfBands() == 3 ) ) { const ossim_uint32 MAX_IDX = m_twoColorTile->getSizePerBand(); // Buffers for normalized oldData and newData tiles. std::vector oldDataBuffer(MAX_IDX); std::vector newDataBuffer(MAX_IDX); // old and new input buffers. ossim_float32* o = &oldDataBuffer.front(); ossim_float32* n = &newDataBuffer.front(); // Normalize/copy to buffers. newData->copyTileBandToNormalizedBuffer(m_newInputBandIndex, n); oldData->copyTileBandToNormalizedBuffer(m_oldInputBandIndex, o); // Get the output buffers. ossim_uint8* r = static_cast( m_twoColorTile->getBuf(0) ); ossim_uint8* g = static_cast( m_twoColorTile->getBuf(1) ); ossim_uint8* b = static_cast( m_twoColorTile->getBuf(2) ); if ( o && n && r && g && b ) { // Assuming null pix of 0 for 8 bit. const ossim_uint8 MP = 1; const ossim_uint8 NP = 0; ossim_uint8 newPix = 0; ossim_uint8 oldPix = 0; ossim_float32 tmpPix = 0.0; const ossim_uint32 MAX_IDX = m_twoColorTile->getSizePerBand(); for(ossim_uint32 idx = 0; idx < MAX_IDX; ++idx) { if( ( *n == NP ) && ( *o == NP ) ) { // Both inputs null, set all outputs null. *r = NP; *b = NP; *g = NP; } else { // At least one input is not null. // Set the newPix: if ( *n != NP ) { // Un-normalize: tmpPix = (*n) * 255.0; // Clamp to min/max. tmpPix = (tmpPix <= 255.0) ? ( (tmpPix >= 1.0) ? tmpPix : 1.0) : 255.0; // Copy newPix = static_cast( tmpPix ); } else { newPix = MP; } // Set the oldPix: if ( *o != NP ) { // Un-normalize: tmpPix = (*o) * 255.0; // Clamp to min/max. tmpPix = (tmpPix <= 255.0) ? ( (tmpPix >= 1.0) ? tmpPix : 1.0) : 255.0; // Copy oldPix = static_cast( tmpPix ); } else { oldPix = MP; } // Set red, OLD is default so check first: if ( m_redSource == ossimTwoColorView::OLD ) { *r = oldPix; } else if ( m_redSource == ossimTwoColorView::NEW ) { *r = newPix; } else { *r = MP; } // Set green, NEW is default so check first: if ( m_grnSource == ossimTwoColorView::NEW ) { *g = newPix; } else if ( m_grnSource == ossimTwoColorView::OLD ) { *g = oldPix; } else { *g = MP; } // Set blue, NEW is default so check first: if ( m_grnSource == ossimTwoColorView::NEW ) { *b = newPix; } else if ( m_grnSource == ossimTwoColorView::OLD ) { *b = oldPix; } else { *b = MP; } } // Next pixel: ++n; ++o; ++r; ++g; ++b; } } } } void ossimTwoColorView::allocate() { m_twoColorTile = ossimImageDataFactory::instance()->create(this, this); if(m_twoColorTile.valid()) { m_twoColorTile->initialize(); } } void ossimTwoColorView::initialize() { ossimImageCombiner::initialize(); m_newInput = 0; m_oldInput = 0; m_twoColorTile = 0; m_nativeFlag = false; m_byPassFlag = false; if(getNumberOfInputs() < 2) { m_byPassFlag = true; } else { m_oldInput = dynamic_cast( getInput(0) ); m_newInput = dynamic_cast( getInput(1) ); //--- // Range check band selection. This can be set from setBandIndexMapping method which // does no error checking because inputs may not be set. //---- if ( m_oldInput.valid() ) { if ( m_oldInputBandIndex >= m_oldInput->getNumberOfOutputBands() ) { m_oldInputBandIndex = 0; } } if ( m_newInput.valid() ) { if ( m_newInputBandIndex >= m_newInput->getNumberOfOutputBands() ) { m_newInputBandIndex = 0; } } if(!m_newInput||!m_oldInput) { m_byPassFlag = true; } else { if((m_newInput->getOutputScalarType() == OSSIM_UINT8)&& (m_oldInput->getOutputScalarType() == OSSIM_UINT8)) { m_nativeFlag = true; } } } } ossim-Miami-2.9.1/src/imaging/ossimU11ImageData.cpp000066400000000000000000000412731352751253100220060ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Class definition of ossimU11ImageData. Specialized image data object for // unsigned short data with an 11 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 2047.0 (2^11 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU11ImageData.cpp 16052 2009-12-08 22:20:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimU11ImageData, "ossimU11ImageData", ossimImageData) const ossimNormalizedU11RemapTable ossimU11ImageData::m_remapTable; ossimU11ImageData::ossimU11ImageData() : ossimImageData() { m_scalarType = OSSIM_USHORT11; } ossimU11ImageData::ossimU11ImageData(ossimSource* source, ossim_uint32 bands) : ossimImageData(source, OSSIM_USHORT11, bands) { } ossimU11ImageData::ossimU11ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height) : ossimImageData(source, OSSIM_USHORT11, bands, width, height) { } ossimU11ImageData::ossimU11ImageData(const ossimU11ImageData &rhs) : ossimImageData(rhs) {} ossimU11ImageData::~ossimU11ImageData() { } ossimObject* ossimU11ImageData::dup()const { return new ossimU11ImageData(*this); } ossimDataObjectStatus ossimU11ImageData::validate() const { if (m_dataBuffer.size() == 0) { setDataObjectStatus(OSSIM_NULL); return OSSIM_NULL; } ossim_uint32 count = 0; const ossim_uint32 SIZE = getSize(); const ossim_uint32 BOUNDS = getSizePerBand(); const ossim_uint32 NUMBER_OF_BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < NUMBER_OF_BANDS; ++band) { const ossim_uint16* p = getUshortBuf(band); for (ossim_uint32 i=0; i(m_remapTable.normFromPix(sourceBuf[offset])); } } void ossimU11ImageData::setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float inputValue) { if( (getDataObjectStatus() != OSSIM_NULL) && isValidBand(bandNumber) ) { ossim_uint16* sourceBuf = getUshortBuf(bandNumber); sourceBuf[offset] = static_cast(m_remapTable.pixFromNorm(inputValue)); } } void ossimU11ImageData::convertToNormalizedFloat(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); float* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. normFromPix(sourceBuf[counter])); } } } } void ossimU11ImageData::convertToNormalizedDouble(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); double* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = m_remapTable.normFromPix(sourceBuf[counter]); } } } } void ossimU11ImageData::unnormalizeInput(ossimImageData* normalizedInput) { if((normalizedInput->getScalarType() != OSSIM_NORMALIZED_FLOAT) && (normalizedInput->getScalarType() != OSSIM_NORMALIZED_DOUBLE) ) { //ERROR return; } ossim_uint32 counter = 0; ossim_uint32 bandCount = 0; ossim_uint32 size = getSizePerBand(); ossimScalarType scalarType = normalizedInput->getScalarType(); if(size > 0) { if(scalarType == OSSIM_NORMALIZED_FLOAT) { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { float* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } else // Double { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { double* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } } } double ossimU11ImageData::computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber) { double result = -1; // invalid MSE ossim_uint32 index = 0; double delta = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getWidth()*getHeight(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { delta = *buffer - meanValue; result += (delta*delta); ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } double ossimU11ImageData::computeAverageBandValue(ossim_uint32 bandNumber) { double result = 0.0; ossim_uint32 index = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getSizePerBand(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { result += *buffer; ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } void ossimU11ImageData::setValue(long x, long y, double color) { if(m_dataBuffer.size() > 0 && isWithin(x, y)) { //*** // Compute the offset into the buffer for (x,y). This should always // come out positive. //*** ossim_uint32 ux = static_cast(x - m_origin.x); ossim_uint32 uy = static_cast(y - m_origin.y); ossim_uint32 offset = uy * m_spatialExtents[0] + ux; for(ossim_uint32 band = 0; offset < m_dataBuffer.size() && // prevent buffer overrun band < m_numberOfDataComponents; band++) { ossim_uint16* buf = getUshortBuf(band)+offset; *buf = (ossim_uint16)color; } } } void ossimU11ImageData::fill(ossim_uint32 band, double value) { void* s = getBuf(band); if (s == NULL) return; // nothing to do... ossim_uint32 size_in_pixels = getSizePerBand(); ossim_uint16* p = getUshortBuf(band); ossim_uint16 np = static_cast(value); for (ossim_uint32 i=0; i 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU11ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf; // destination for(ossim_uint32 index = 0; index < size; index++) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU11ImageData::copyNormalizedBufferToTile(double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { double* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU11ImageData::copyNormalizedBufferToTile(ossim_uint32 band, double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { double* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } void ossimU11ImageData::copyTileToNormalizedBuffer(float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU11ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf; // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU11ImageData::copyNormalizedBufferToTile(float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { float* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU11ImageData::copyNormalizedBufferToTile(ossim_uint32 band, float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { float* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } ossim-Miami-2.9.1/src/imaging/ossimU12ImageData.cpp000066400000000000000000000412731352751253100220070ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Class definition of ossimU12ImageData. Specialized image data object for // unsigned short data with an 11 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 4095.0 (2^12 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU12ImageData.cpp 16052 2009-12-08 22:20:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimU12ImageData, "ossimU12ImageData", ossimImageData) const ossimNormalizedU12RemapTable ossimU12ImageData::m_remapTable; ossimU12ImageData::ossimU12ImageData() : ossimImageData() { m_scalarType = OSSIM_USHORT12; } ossimU12ImageData::ossimU12ImageData(ossimSource* source, ossim_uint32 bands) : ossimImageData(source, OSSIM_USHORT12, bands) { } ossimU12ImageData::ossimU12ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height) : ossimImageData(source, OSSIM_USHORT12, bands, width, height) { } ossimU12ImageData::ossimU12ImageData(const ossimU12ImageData &rhs) : ossimImageData(rhs) {} ossimU12ImageData::~ossimU12ImageData() { } ossimObject* ossimU12ImageData::dup()const { return new ossimU12ImageData(*this); } ossimDataObjectStatus ossimU12ImageData::validate() const { if (m_dataBuffer.size() == 0) { setDataObjectStatus(OSSIM_NULL); return OSSIM_NULL; } ossim_uint32 count = 0; const ossim_uint32 SIZE = getSize(); const ossim_uint32 BOUNDS = getSizePerBand(); const ossim_uint32 NUMBER_OF_BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < NUMBER_OF_BANDS; ++band) { const ossim_uint16* p = getUshortBuf(band); for (ossim_uint32 i=0; i(m_remapTable.normFromPix(sourceBuf[offset])); } } void ossimU12ImageData::setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float inputValue) { if( (getDataObjectStatus() != OSSIM_NULL) && isValidBand(bandNumber) ) { ossim_uint16* sourceBuf = getUshortBuf(bandNumber); sourceBuf[offset] = static_cast(m_remapTable.pixFromNorm(inputValue)); } } void ossimU12ImageData::convertToNormalizedFloat(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); float* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. normFromPix(sourceBuf[counter])); } } } } void ossimU12ImageData::convertToNormalizedDouble(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); double* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = m_remapTable.normFromPix(sourceBuf[counter]); } } } } void ossimU12ImageData::unnormalizeInput(ossimImageData* normalizedInput) { if((normalizedInput->getScalarType() != OSSIM_NORMALIZED_FLOAT) && (normalizedInput->getScalarType() != OSSIM_NORMALIZED_DOUBLE) ) { //ERROR return; } ossim_uint32 counter = 0; ossim_uint32 bandCount = 0; ossim_uint32 size = getSizePerBand(); ossimScalarType scalarType = normalizedInput->getScalarType(); if(size > 0) { if(scalarType == OSSIM_NORMALIZED_FLOAT) { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { float* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } else // Double { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { double* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } } } double ossimU12ImageData::computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber) { double result = -1; // invalid MSE ossim_uint32 index = 0; double delta = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getWidth()*getHeight(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { delta = *buffer - meanValue; result += (delta*delta); ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } double ossimU12ImageData::computeAverageBandValue(ossim_uint32 bandNumber) { double result = 0.0; ossim_uint32 index = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getSizePerBand(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { result += *buffer; ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } void ossimU12ImageData::setValue(long x, long y, double color) { if(m_dataBuffer.size() > 0 && isWithin(x, y)) { //*** // Compute the offset into the buffer for (x,y). This should always // come out positive. //*** ossim_uint32 ux = static_cast(x - m_origin.x); ossim_uint32 uy = static_cast(y - m_origin.y); ossim_uint32 offset = uy * m_spatialExtents[0] + ux; for(ossim_uint32 band = 0; offset < m_dataBuffer.size() && // prevent buffer overrun band < m_numberOfDataComponents; band++) { ossim_uint16* buf = getUshortBuf(band)+offset; *buf = (ossim_uint16)color; } } } void ossimU12ImageData::fill(ossim_uint32 band, double value) { void* s = getBuf(band); if (s == NULL) return; // nothing to do... ossim_uint32 size_in_pixels = getSizePerBand(); ossim_uint16* p = getUshortBuf(band); ossim_uint16 np = static_cast(value); for (ossim_uint32 i=0; i 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU12ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU12ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf; // destination for(ossim_uint32 index = 0; index < size; index++) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU12ImageData::copyNormalizedBufferToTile(double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU12ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { double* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU12ImageData::copyNormalizedBufferToTile(ossim_uint32 band, double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU12ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { double* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } void ossimU12ImageData::copyTileToNormalizedBuffer(float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU12ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU12ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU12ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf; // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU12ImageData::copyNormalizedBufferToTile(float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU12ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { float* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU12ImageData::copyNormalizedBufferToTile(ossim_uint32 band, float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU12ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { float* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } ossim-Miami-2.9.1/src/imaging/ossimU13ImageData.cpp000066400000000000000000000412731352751253100220100ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Class definition of ossimU13ImageData. Specialized image data object for // unsigned short data with an 11 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 8191.0 (2^13 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU13ImageData.cpp 16052 2009-12-08 22:20:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimU13ImageData, "ossimU13ImageData", ossimImageData) const ossimNormalizedU13RemapTable ossimU13ImageData::m_remapTable; ossimU13ImageData::ossimU13ImageData() : ossimImageData() { m_scalarType = OSSIM_USHORT13; } ossimU13ImageData::ossimU13ImageData(ossimSource* source, ossim_uint32 bands) : ossimImageData(source, OSSIM_USHORT13, bands) { } ossimU13ImageData::ossimU13ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height) : ossimImageData(source, OSSIM_USHORT13, bands, width, height) { } ossimU13ImageData::ossimU13ImageData(const ossimU13ImageData &rhs) : ossimImageData(rhs) {} ossimU13ImageData::~ossimU13ImageData() { } ossimObject* ossimU13ImageData::dup()const { return new ossimU13ImageData(*this); } ossimDataObjectStatus ossimU13ImageData::validate() const { if (m_dataBuffer.size() == 0) { setDataObjectStatus(OSSIM_NULL); return OSSIM_NULL; } ossim_uint32 count = 0; const ossim_uint32 SIZE = getSize(); const ossim_uint32 BOUNDS = getSizePerBand(); const ossim_uint32 NUMBER_OF_BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < NUMBER_OF_BANDS; ++band) { const ossim_uint16* p = getUshortBuf(band); for (ossim_uint32 i=0; i(m_remapTable.normFromPix(sourceBuf[offset])); } } void ossimU13ImageData::setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float inputValue) { if( (getDataObjectStatus() != OSSIM_NULL) && isValidBand(bandNumber) ) { ossim_uint16* sourceBuf = getUshortBuf(bandNumber); sourceBuf[offset] = static_cast(m_remapTable.pixFromNorm(inputValue)); } } void ossimU13ImageData::convertToNormalizedFloat(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); float* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. normFromPix(sourceBuf[counter])); } } } } void ossimU13ImageData::convertToNormalizedDouble(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); double* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = m_remapTable.normFromPix(sourceBuf[counter]); } } } } void ossimU13ImageData::unnormalizeInput(ossimImageData* normalizedInput) { if((normalizedInput->getScalarType() != OSSIM_NORMALIZED_FLOAT) && (normalizedInput->getScalarType() != OSSIM_NORMALIZED_DOUBLE) ) { //ERROR return; } ossim_uint32 counter = 0; ossim_uint32 bandCount = 0; ossim_uint32 size = getSizePerBand(); ossimScalarType scalarType = normalizedInput->getScalarType(); if(size > 0) { if(scalarType == OSSIM_NORMALIZED_FLOAT) { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { float* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } else // Double { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { double* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } } } double ossimU13ImageData::computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber) { double result = -1; // invalid MSE ossim_uint32 index = 0; double delta = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getWidth()*getHeight(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { delta = *buffer - meanValue; result += (delta*delta); ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } double ossimU13ImageData::computeAverageBandValue(ossim_uint32 bandNumber) { double result = 0.0; ossim_uint32 index = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getSizePerBand(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { result += *buffer; ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } void ossimU13ImageData::setValue(long x, long y, double color) { if(m_dataBuffer.size() > 0 && isWithin(x, y)) { //*** // Compute the offset into the buffer for (x,y). This should always // come out positive. //*** ossim_uint32 ux = static_cast(x - m_origin.x); ossim_uint32 uy = static_cast(y - m_origin.y); ossim_uint32 offset = uy * m_spatialExtents[0] + ux; for(ossim_uint32 band = 0; offset < m_dataBuffer.size() && // prevent buffer overrun band < m_numberOfDataComponents; band++) { ossim_uint16* buf = getUshortBuf(band)+offset; *buf = (ossim_uint16)color; } } } void ossimU13ImageData::fill(ossim_uint32 band, double value) { void* s = getBuf(band); if (s == NULL) return; // nothing to do... ossim_uint32 size_in_pixels = getSizePerBand(); ossim_uint16* p = getUshortBuf(band); ossim_uint16 np = static_cast(value); for (ossim_uint32 i=0; i 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU13ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU13ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf; // destination for(ossim_uint32 index = 0; index < size; index++) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU13ImageData::copyNormalizedBufferToTile(double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU13ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { double* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU13ImageData::copyNormalizedBufferToTile(ossim_uint32 band, double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU13ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { double* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } void ossimU13ImageData::copyTileToNormalizedBuffer(float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU13ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU13ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU13ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf; // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU13ImageData::copyNormalizedBufferToTile(float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU13ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { float* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU13ImageData::copyNormalizedBufferToTile(ossim_uint32 band, float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU13ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { float* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } ossim-Miami-2.9.1/src/imaging/ossimU14ImageData.cpp000066400000000000000000000412741352751253100220120ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Class definition of ossimU14ImageData. Specialized image data object for // unsigned short data with an 11 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 16383.0 (2^14 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU14ImageData.cpp 16052 2009-12-08 22:20:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimU14ImageData, "ossimU14ImageData", ossimImageData) const ossimNormalizedU14RemapTable ossimU14ImageData::m_remapTable; ossimU14ImageData::ossimU14ImageData() : ossimImageData() { m_scalarType = OSSIM_USHORT14; } ossimU14ImageData::ossimU14ImageData(ossimSource* source, ossim_uint32 bands) : ossimImageData(source, OSSIM_USHORT14, bands) { } ossimU14ImageData::ossimU14ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height) : ossimImageData(source, OSSIM_USHORT14, bands, width, height) { } ossimU14ImageData::ossimU14ImageData(const ossimU14ImageData &rhs) : ossimImageData(rhs) {} ossimU14ImageData::~ossimU14ImageData() { } ossimObject* ossimU14ImageData::dup()const { return new ossimU14ImageData(*this); } ossimDataObjectStatus ossimU14ImageData::validate() const { if (m_dataBuffer.size() == 0) { setDataObjectStatus(OSSIM_NULL); return OSSIM_NULL; } ossim_uint32 count = 0; const ossim_uint32 SIZE = getSize(); const ossim_uint32 BOUNDS = getSizePerBand(); const ossim_uint32 NUMBER_OF_BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < NUMBER_OF_BANDS; ++band) { const ossim_uint16* p = getUshortBuf(band); for (ossim_uint32 i=0; i(m_remapTable.normFromPix(sourceBuf[offset])); } } void ossimU14ImageData::setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float inputValue) { if( (getDataObjectStatus() != OSSIM_NULL) && isValidBand(bandNumber) ) { ossim_uint16* sourceBuf = getUshortBuf(bandNumber); sourceBuf[offset] = static_cast(m_remapTable.pixFromNorm(inputValue)); } } void ossimU14ImageData::convertToNormalizedFloat(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); float* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. normFromPix(sourceBuf[counter])); } } } } void ossimU14ImageData::convertToNormalizedDouble(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); double* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = m_remapTable.normFromPix(sourceBuf[counter]); } } } } void ossimU14ImageData::unnormalizeInput(ossimImageData* normalizedInput) { if((normalizedInput->getScalarType() != OSSIM_NORMALIZED_FLOAT) && (normalizedInput->getScalarType() != OSSIM_NORMALIZED_DOUBLE) ) { //ERROR return; } ossim_uint32 counter = 0; ossim_uint32 bandCount = 0; ossim_uint32 size = getSizePerBand(); ossimScalarType scalarType = normalizedInput->getScalarType(); if(size > 0) { if(scalarType == OSSIM_NORMALIZED_FLOAT) { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { float* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } else // Double { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { double* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } } } double ossimU14ImageData::computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber) { double result = -1; // invalid MSE ossim_uint32 index = 0; double delta = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getWidth()*getHeight(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { delta = *buffer - meanValue; result += (delta*delta); ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } double ossimU14ImageData::computeAverageBandValue(ossim_uint32 bandNumber) { double result = 0.0; ossim_uint32 index = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getSizePerBand(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { result += *buffer; ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } void ossimU14ImageData::setValue(long x, long y, double color) { if(m_dataBuffer.size() > 0 && isWithin(x, y)) { //*** // Compute the offset into the buffer for (x,y). This should always // come out positive. //*** ossim_uint32 ux = static_cast(x - m_origin.x); ossim_uint32 uy = static_cast(y - m_origin.y); ossim_uint32 offset = uy * m_spatialExtents[0] + ux; for(ossim_uint32 band = 0; offset < m_dataBuffer.size() && // prevent buffer overrun band < m_numberOfDataComponents; band++) { ossim_uint16* buf = getUshortBuf(band)+offset; *buf = (ossim_uint16)color; } } } void ossimU14ImageData::fill(ossim_uint32 band, double value) { void* s = getBuf(band); if (s == NULL) return; // nothing to do... ossim_uint32 size_in_pixels = getSizePerBand(); ossim_uint16* p = getUshortBuf(band); ossim_uint16 np = static_cast(value); for (ossim_uint32 i=0; i 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU14ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU14ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf; // destination for(ossim_uint32 index = 0; index < size; index++) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU14ImageData::copyNormalizedBufferToTile(double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU14ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { double* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU14ImageData::copyNormalizedBufferToTile(ossim_uint32 band, double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU14ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { double* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } void ossimU14ImageData::copyTileToNormalizedBuffer(float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU14ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU14ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU14ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf; // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU14ImageData::copyNormalizedBufferToTile(float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU14ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { float* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU14ImageData::copyNormalizedBufferToTile(ossim_uint32 band, float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU14ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { float* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } ossim-Miami-2.9.1/src/imaging/ossimU15ImageData.cpp000066400000000000000000000412741352751253100220130ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Class definition of ossimU15ImageData. Specialized image data object for // unsigned short data with an 11 bit depth. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 32767.0 (2^15 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU15ImageData.cpp 16052 2009-12-08 22:20:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimU15ImageData, "ossimU15ImageData", ossimImageData) const ossimNormalizedU15RemapTable ossimU15ImageData::m_remapTable; ossimU15ImageData::ossimU15ImageData() : ossimImageData() { m_scalarType = OSSIM_USHORT15; } ossimU15ImageData::ossimU15ImageData(ossimSource* source, ossim_uint32 bands) : ossimImageData(source, OSSIM_USHORT15, bands) { } ossimU15ImageData::ossimU15ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height) : ossimImageData(source, OSSIM_USHORT15, bands, width, height) { } ossimU15ImageData::ossimU15ImageData(const ossimU15ImageData &rhs) : ossimImageData(rhs) {} ossimU15ImageData::~ossimU15ImageData() { } ossimObject* ossimU15ImageData::dup()const { return new ossimU15ImageData(*this); } ossimDataObjectStatus ossimU15ImageData::validate() const { if (m_dataBuffer.size() == 0) { setDataObjectStatus(OSSIM_NULL); return OSSIM_NULL; } ossim_uint32 count = 0; const ossim_uint32 SIZE = getSize(); const ossim_uint32 BOUNDS = getSizePerBand(); const ossim_uint32 NUMBER_OF_BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < NUMBER_OF_BANDS; ++band) { const ossim_uint16* p = getUshortBuf(band); for (ossim_uint32 i=0; i(m_remapTable.normFromPix(sourceBuf[offset])); } } void ossimU15ImageData::setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float inputValue) { if( (getDataObjectStatus() != OSSIM_NULL) && isValidBand(bandNumber) ) { ossim_uint16* sourceBuf = getUshortBuf(bandNumber); sourceBuf[offset] = static_cast(m_remapTable.pixFromNorm(inputValue)); } } void ossimU15ImageData::convertToNormalizedFloat(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); float* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. normFromPix(sourceBuf[counter])); } } } } void ossimU15ImageData::convertToNormalizedDouble(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); double* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = m_remapTable.normFromPix(sourceBuf[counter]); } } } } void ossimU15ImageData::unnormalizeInput(ossimImageData* normalizedInput) { if((normalizedInput->getScalarType() != OSSIM_NORMALIZED_FLOAT) && (normalizedInput->getScalarType() != OSSIM_NORMALIZED_DOUBLE) ) { //ERROR return; } ossim_uint32 counter = 0; ossim_uint32 bandCount = 0; ossim_uint32 size = getSizePerBand(); ossimScalarType scalarType = normalizedInput->getScalarType(); if(size > 0) { if(scalarType == OSSIM_NORMALIZED_FLOAT) { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { float* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } else // Double { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { double* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } } } double ossimU15ImageData::computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber) { double result = -1; // invalid MSE ossim_uint32 index = 0; double delta = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getWidth()*getHeight(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { delta = *buffer - meanValue; result += (delta*delta); ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } double ossimU15ImageData::computeAverageBandValue(ossim_uint32 bandNumber) { double result = 0.0; ossim_uint32 index = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getSizePerBand(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { result += *buffer; ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } void ossimU15ImageData::setValue(long x, long y, double color) { if(m_dataBuffer.size() > 0 && isWithin(x, y)) { //*** // Compute the offset into the buffer for (x,y). This should always // come out positive. //*** ossim_uint32 ux = static_cast(x - m_origin.x); ossim_uint32 uy = static_cast(y - m_origin.y); ossim_uint32 offset = uy * m_spatialExtents[0] + ux; for(ossim_uint32 band = 0; offset < m_dataBuffer.size() && // prevent buffer overrun band < m_numberOfDataComponents; band++) { ossim_uint16* buf = getUshortBuf(band)+offset; *buf = (ossim_uint16)color; } } } void ossimU15ImageData::fill(ossim_uint32 band, double value) { void* s = getBuf(band); if (s == NULL) return; // nothing to do... ossim_uint32 size_in_pixels = getSizePerBand(); ossim_uint16* p = getUshortBuf(band); ossim_uint16 np = static_cast(value); for (ossim_uint32 i=0; i 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU15ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU15ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf; // destination for(ossim_uint32 index = 0; index < size; index++) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU15ImageData::copyNormalizedBufferToTile(double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU15ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { double* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU15ImageData::copyNormalizedBufferToTile(ossim_uint32 band, double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU15ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { double* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } void ossimU15ImageData::copyTileToNormalizedBuffer(float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU15ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU15ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU15ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf; // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.normFromPix(static_cast(*s)); } } } void ossimU15ImageData::copyNormalizedBufferToTile(float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU15ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { float* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU15ImageData::copyNormalizedBufferToTile(ossim_uint32 band, float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU15ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { float* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } ossim-Miami-2.9.1/src/imaging/ossimU16ImageData.cpp000066400000000000000000000376031352751253100220150ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Class definition of ossimU16ImageData. Specialized image data object for // unsigned short data. // // NOTE: This object is optimized for unsigned short data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 65535.0 (2^16 - 1) // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU16ImageData.cpp 16052 2009-12-08 22:20:40Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimU16ImageData, "ossimU16ImageData", ossimImageData) const ossimNormalizedU16RemapTable ossimU16ImageData::m_remapTable; ossimU16ImageData::ossimU16ImageData() : ossimImageData() { m_scalarType = OSSIM_UINT16; } ossimU16ImageData::ossimU16ImageData(ossimSource* source, ossim_uint32 bands) : ossimImageData(source, OSSIM_UINT16, bands) { } ossimU16ImageData::ossimU16ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height) : ossimImageData(source, OSSIM_UINT16, bands, width, height) { } ossimU16ImageData::ossimU16ImageData(const ossimU16ImageData &rhs) : ossimImageData(rhs) { } ossimU16ImageData::~ossimU16ImageData() { } ossimObject* ossimU16ImageData::dup()const { return new ossimU16ImageData(*this); } ossimDataObjectStatus ossimU16ImageData::validate() const { if (getBuf() == NULL) { setDataObjectStatus(OSSIM_NULL); return OSSIM_NULL; } ossim_uint32 count = 0; const ossim_uint32 SIZE = getSize(); const ossim_uint32 BOUNDS = getSizePerBand(); const ossim_uint32 NUMBER_OF_BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < NUMBER_OF_BANDS; ++band) { const ossim_uint16* p = getUshortBuf(band); for (ossim_uint32 i=0; i(m_remapTable.normFromPix(sourceBuf[offset])); } } void ossimU16ImageData::setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float inputValue) { if( (getDataObjectStatus() != OSSIM_NULL) && isValidBand(bandNumber) ) { ossim_uint16* sourceBuf = getUshortBuf(bandNumber); sourceBuf[offset] = static_cast(m_remapTable.pixFromNorm(inputValue)); } } void ossimU16ImageData::convertToNormalizedFloat(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); float* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. normFromPix(sourceBuf[counter])); } } } } void ossimU16ImageData::convertToNormalizedDouble(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint16* sourceBuf = getUshortBuf(bandCount); double* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = m_remapTable.normFromPix(sourceBuf[counter]); } } } } void ossimU16ImageData::unnormalizeInput(ossimImageData* normalizedInput) { if((normalizedInput->getScalarType() != OSSIM_NORMALIZED_FLOAT) && (normalizedInput->getScalarType() != OSSIM_NORMALIZED_DOUBLE) ) { //ERROR return; } ossim_uint32 counter = 0; ossim_uint32 bandCount = 0; ossim_uint32 size = getSizePerBand(); ossimScalarType scalarType = normalizedInput->getScalarType(); if(size > 0) { if(scalarType == OSSIM_NORMALIZED_FLOAT) { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { float* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } else // Double { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { double* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint16* resultBuf = getUshortBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } } } double ossimU16ImageData::computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber) { double result = -1; // invalid MSE ossim_uint32 index = 0; double delta = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getWidth()*getHeight(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { delta = *buffer - meanValue; result += (delta*delta); ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } double ossimU16ImageData::computeAverageBandValue(ossim_uint32 bandNumber) { double result = 0.0; ossim_uint32 index = 0; ossim_uint32 validPixelCount=0; ossim_uint16* buffer = getUshortBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getSizePerBand(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { result += *buffer; ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } void ossimU16ImageData::setValue(long x, long y, double color) { if(getBuf() != NULL && isWithin(x, y)) { //*** // Compute the offset into the buffer for (x,y). This should always // come out positive. //*** ossim_uint32 ux = static_cast(x - m_origin.x); ossim_uint32 uy = static_cast(y - m_origin.y); ossim_uint32 offset = uy * m_spatialExtents[0] + ux; for(ossim_uint32 band = 0; band < m_numberOfDataComponents; band++) { ossim_uint16* buf = getUshortBuf(band)+offset; *buf = (ossim_uint16)color; } } } void ossimU16ImageData::fill(ossim_uint32 band, double value) { void* s = getBuf(band); if (s == NULL) return; // nothing to do... ossim_uint32 size_in_pixels = getSizePerBand(); ossim_uint16* p = getUshortBuf(band); ossim_uint16 np = static_cast(value); for (ossim_uint32 i=0; i 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU16ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source double* d = buf; // destination for(ossim_uint32 index = 0; index < size; index++) { *d = m_remapTable. normFromPix(static_cast(*s)); } } } void ossimU16ImageData::copyNormalizedBufferToTile(double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { double* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU16ImageData::copyNormalizedBufferToTile(ossim_uint32 band, double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { double* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } void ossimU16ImageData::copyTileToNormalizedBuffer(float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf + (band*size); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } void ossimU16ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { const ossim_uint16* s = getUshortBuf(band); // source float* d = buf; // destination for(ossim_uint32 index = 0; index < size; index++) { *d = m_remapTable. normFromPix(static_cast(*s)); } } } void ossimU16ImageData::copyNormalizedBufferToTile(float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU16ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); band++) { float* s = buf + (band*size); // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU16ImageData::copyNormalizedBufferToTile(ossim_uint32 band, float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU11ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if((size > 0)&&getBuf(band)) { float* s = buf; // source ossim_uint16* d = getUshortBuf(band); // destination for(ossim_uint32 index = 0; index < size; index++) { *d = m_remapTable.pixFromNorm(*s); ++d; ++s; } } } ossim-Miami-2.9.1/src/imaging/ossimU8ImageData.cpp000066400000000000000000000417611352751253100217360ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Class definition of ossimU8ImageData. Specialized image data object for // unsigned char data. // // NOTE: This object is optimized for unsigned char data and assumes the // following: null pixel value = 0.0 // min pixel value = 1.0 // max pixel value = 255.0 // // If you want anything else use the less efficient ossimImageData. // //************************************************************************* // $Id: ossimU8ImageData.cpp 16052 2009-12-08 22:20:40Z dburken $ #include // for memset function using namespace std; #include #include #include #include #include #include RTTI_DEF1(ossimU8ImageData, "ossimU8ImageData", ossimImageData) const ossimNormalizedU8RemapTable ossimU8ImageData::m_remapTable; ossimU8ImageData::ossimU8ImageData(ossimSource* source, ossim_uint32 bands) : ossimImageData(source, OSSIM_UCHAR, bands) { } ossimU8ImageData::ossimU8ImageData(ossimSource* source, ossim_uint32 bands, ossim_uint32 width, ossim_uint32 height) : ossimImageData(source, OSSIM_UCHAR, bands, width, height) { } ossimU8ImageData::~ossimU8ImageData() { } ossimObject* ossimU8ImageData::dup()const { return new ossimU8ImageData(*this); } void ossimU8ImageData::fill(double value) { ossimImageData::fill(value); } ossimDataObjectStatus ossimU8ImageData::validate() const { if (m_dataBuffer.size() == 0) { setDataObjectStatus(OSSIM_NULL); return OSSIM_NULL; } ossim_uint32 count = 0; const ossim_uint32 SIZE = getSize(); const ossim_uint32 BOUNDS = getSizePerBand(); const ossim_uint32 NUMBER_OF_BANDS = getNumberOfBands(); for(ossim_uint32 band = 0; band < NUMBER_OF_BANDS; ++band) { const ossim_uint8* p = getUcharBuf(band); ossim_uint8 np = (ossim_uint8)getNullPix(band); for (ossim_uint32 i=0; i(m_remapTable.normFromPix(sourceBuf[offset])); } void ossimU8ImageData::setNormalizedFloat(ossim_uint32 offset, ossim_uint32 bandNumber, float inputValue) { // make sure that the types and width and height are // good. if((getDataObjectStatus() == OSSIM_NULL)&& (bandNumber < getNumberOfBands())) { return; } ossim_uint8* sourceBuf = getUcharBuf(bandNumber); sourceBuf[offset] = static_cast(m_remapTable.pixFromNorm(inputValue)); } void ossimU8ImageData::convertToNormalizedFloat(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint8* sourceBuf = getUcharBuf(bandCount); float* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. normFromPix(sourceBuf[counter])); } } } } void ossimU8ImageData::convertToNormalizedDouble(ossimImageData* result)const { if(!result) { return; } // make sure that the types and width and height are // good. if( (result->getScalarType() != OSSIM_NORMALIZED_FLOAT) || (result->getNumberOfBands() != this->getNumberOfBands())|| (result->getWidth() != this->getWidth()) || (result->getHeight() != this->getHeight())|| (result->getDataObjectStatus() == OSSIM_NULL) || (getDataObjectStatus() == OSSIM_NULL)) { return; } ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { const ossim_uint8* sourceBuf = getUcharBuf(bandCount); double* resultBuf = static_cast(result->getBuf(bandCount)); for(ossim_uint32 counter = 0; counter < size; ++counter) { resultBuf[counter] = m_remapTable.normFromPix(sourceBuf[counter]); } } } } void ossimU8ImageData::unnormalizeInput(ossimImageData* normalizedInput) { if((normalizedInput->getScalarType() != OSSIM_NORMALIZED_FLOAT) && (normalizedInput->getScalarType() != OSSIM_NORMALIZED_DOUBLE) ) { //ERROR return; } ossim_uint32 counter = 0; ossim_uint32 bandCount = 0; ossim_uint32 size = getSizePerBand(); ossimScalarType scalarType = normalizedInput->getScalarType(); if(size > 0) { if(scalarType == OSSIM_NORMALIZED_FLOAT) { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { float* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint8* resultBuf = getUcharBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } else // Double { for(bandCount = 0; bandCount < m_numberOfDataComponents; ++bandCount) { double* sourceBuf = static_cast(normalizedInput->getBuf(bandCount)); ossim_uint8* resultBuf = getUcharBuf(bandCount); for(counter = 0; counter < size; ++counter) { resultBuf[counter] = static_cast(m_remapTable. pixFromNorm(sourceBuf[counter])); } } } } } double ossimU8ImageData::computeMeanSquaredError(double meanValue, ossim_uint32 bandNumber) { double result = -1; // invalid MSE ossim_uint32 index = 0; double delta = 0; ossim_uint32 validPixelCount=0; ossim_uint8* buffer = getUcharBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getWidth()*getHeight(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { delta = *buffer - meanValue; result += (delta*delta); ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } double ossimU8ImageData::computeAverageBandValue(ossim_uint32 bandNumber) { double result = 0.0; ossim_uint32 index = 0; ossim_uint32 validPixelCount=0; ossim_uint8* buffer = getUcharBuf(bandNumber); if(buffer) { ossim_uint32 bounds = getWidth()*getHeight(); for(index = 0; index < bounds; ++index) { if(!isNull(index)) { result += *buffer; ++validPixelCount; } ++buffer; } if(validPixelCount > 0) { result /= validPixelCount; } } return result; } void ossimU8ImageData::setValue(ossim_int32 x, ossim_int32 y, double color) { if(getBuf() != NULL && isWithin(x, y)) { //*** // Compute the offset into the buffer for (x,y). This should always // come out positive. //*** ossim_uint32 ux = static_cast(x - m_origin.x); ossim_uint32 uy = static_cast(y - m_origin.y); ossim_uint32 offset = uy * m_spatialExtents[0] + ux; for(ossim_uint32 band = 0; band < m_numberOfDataComponents; ++band) { ossim_uint8* buf = getUcharBuf(band)+offset; *buf = (ossim_uint8)color; } } } void ossimU8ImageData::fill(ossim_uint32 band, double value) { void* s = getBuf(band); if (s == NULL) return; // nothing to do... ossim_uint32 size_in_pixels = getSizePerBand(); ossim_uint8* p = getUcharBuf(band); ossim_uint8 np = static_cast(value); for (ossim_uint32 i=0; i 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { const ossim_uint8* s = getUcharBuf(band); // source double* d = buf + (band*size); // destination if(s&&d) { for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } } void ossimU8ImageData::copyTileToNormalizedBuffer(float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU8ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(!getBuf()) { memset(buf, '\0', size); return; } if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { const ossim_uint8* s = getUcharBuf(band); // source float* d = buf + (band*size); // destination if(s&&d) { for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable. normFromPix(static_cast(s[index])); } } } } } void ossimU8ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, double* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU8ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(!getBuf(band)) { memset(buf, '\0', size); return; } if(size > 0) { const ossim_uint8* s = getUcharBuf(band); // source double* d = buf; // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable. normFromPix(static_cast(*s)); ++d; ++s; } } } void ossimU8ImageData::copyTileToNormalizedBuffer(ossim_uint32 band, float* buf) const { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU8ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } ossim_uint32 size = getSizePerBand(); if(!getBuf(band)) { memset(buf, '\0', size); return; } if(size > 0) { const ossim_uint8* s = getUcharBuf(band); // source float* d = buf; // destination for(ossim_uint32 index = 0; index < size; ++index) { *d = m_remapTable. normFromPix(static_cast(*s)); ++d; ++s; } } } void ossimU8ImageData::copyNormalizedBufferToTile(double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU8ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf()) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { double* s = buf + (band*size); // source ossim_uint8* d = getUcharBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU8ImageData::copyNormalizedBufferToTile(float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU8ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf()) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { for(ossim_uint32 band = 0; band < getNumberOfBands(); ++band) { float* s = buf + (band*size); // source ossim_uint8* d = getUcharBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } } void ossimU8ImageData::copyNormalizedBufferToTile(ossim_uint32 band, double* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU8ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { double* s = buf; // source ossim_uint8* d = getUcharBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } void ossimU8ImageData::copyNormalizedBufferToTile(ossim_uint32 band, float* buf) { if (!buf) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "ossimU8ImageData::copyTileToNormalizedBuffer File %s line %d\nNull pointer passed to method!", __FILE__, __LINE__); return; } if(!getBuf(band)) return; ossim_uint32 size = getSizePerBand(); if(size > 0) { float* s = buf; // source ossim_uint8* d = getUcharBuf(band); // destination for(ossim_uint32 index = 0; index < size; ++index) { d[index] = m_remapTable.pixFromNorm(s[index]); } } } ossim-Miami-2.9.1/src/imaging/ossimUsgsDemTileSource.cpp000066400000000000000000000366521352751253100232560ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Contains class declaration for ossimUsgsDemTileSource. // //******************************************************************** // $Id: ossimUsgsDemTileSource.cpp 19640 2011-05-25 15:58:00Z oscarkramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimUsgsDemTileSource, "ossimUsgsDemTileSource", ossimImageHandler) // Static trace for debugging static ossimTrace traceDebug("ossimUsgsDemTileSource:debug"); static const char DEM_TYPE_KW[] = "dem_type"; static const char USGS_DEM_KW[] = "usgs_dem"; ossimUsgsDemTileSource::ossimUsgsDemTileSource() : ossimImageHandler(), theDem(0), theTile(0), theNullValue(0.0), theMinHeight(0.0), theMaxHeight(0.0), theFeetFlag(false), theIsDemFlag(false), theScalarType(OSSIM_SINT16) { // Construction not complete. Users should call "open" method. } ossimUsgsDemTileSource::~ossimUsgsDemTileSource() { if (theDem) { delete theDem; theDem = 0; } theTile = 0; } ossimRefPtr ossimUsgsDemTileSource::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { if (theTile.valid()) { // Image rectangle must be set prior to calling getTile. theTile->setImageRectangle(tile_rect); if ( getTile( theTile.get(), resLevel ) == false ) { if (theTile->getDataObjectStatus() != OSSIM_NULL) { theTile->makeBlank(); } } } return theTile; } bool ossimUsgsDemTileSource::getTile(ossimImageData* result, ossim_uint32 resLevel) { bool status = false; //--- // Not open, this tile source bypassed, or invalid res level, // return a blank tile. //--- if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) && result && (result->getNumberOfBands() == getNumberOfOutputBands()) ) { result->ref(); // Increment ref count. //--- // Check for overview tile. Some overviews can contain r0 so always // call even if resLevel is 0. Method returns true on success, false // on error. //--- status = getOverviewTile(resLevel, result); if (status) // From old code. Not sure if still needed. { result->setMinPix(theTile->getMinPix(), theTile->getNumberOfBands()); result->setMaxPix(theTile->getMaxPix(), theTile->getNumberOfBands()); result->setNullPix(theTile->getNullPix(), theTile->getNumberOfBands()); } if (!status) // Did not get an overview tile. { status = true; ossimIrect tile_rect = result->getImageRectangle(); ossimIrect image_rect = getImageRectangle(resLevel); //--- // See if any point of the requested tile is in the image. //--- if ( tile_rect.intersects(image_rect) ) { ossimIrect clip_rect = tile_rect.clipToRect(image_rect); if ( !tile_rect.completely_within(clip_rect) ) { // Start with a blank tile. result->makeBlank(); } // Load the tile buffer with data from the dem cell. if (theScalarType == OSSIM_FLOAT32) { status = fillBuffer(ossim_float32(0.0), tile_rect, clip_rect, result); } else { status = fillBuffer(ossim_sint16(0), tile_rect, clip_rect, result); } if (status == true) { result->validate(); } } else // No intersection: if ( tile_rect.intersects(image_rect) ) { result->makeBlank(); } } result->unref(); // Decrement ref count. } return status; } //******************************************************************* // Private Method: //******************************************************************* template bool ossimUsgsDemTileSource::fillBuffer(T, const ossimIrect& tile_rect, const ossimIrect& clip_rect, ossimImageData* tile) { const ossim_uint32 TILE_WIDTH = tile->getWidth(); T* d = static_cast(tile->getBuf()); ossim_float32 spatialResZ = theDem->getHeader().getSpatialResZ(); if (spatialResZ == 0.0) spatialResZ = 1.0; // Compute the starting offset. ossim_uint32 offset = (clip_rect.ul().y - tile_rect.ul().y) * TILE_WIDTH + clip_rect.ul().x - tile_rect.ul().x; for (ossim_int32 line = clip_rect.ul().y; line <= clip_rect.lr().y; ++line) { // Loop in the longitude or sample direction. int samp_offset = 0; for (ossim_int32 samp = clip_rect.ul().x; samp <= clip_rect.lr().x; ++samp) { ossim_float32 p = theDem->getElevation(samp, line); if (p != theNullValue) { p *= spatialResZ; if (theFeetFlag) p = p * MTRS_PER_FT; } d[offset + samp_offset] = static_cast(p); ++samp_offset; } offset += TILE_WIDTH; } return true; } ossimIrect ossimUsgsDemTileSource::getImageRectangle(ossim_uint32 reduced_res_level) const { return ossimIrect(0, 0, getNumberOfSamples(reduced_res_level) - 1, getNumberOfLines(reduced_res_level) - 1); } bool ossimUsgsDemTileSource::open() { static const char MODULE[] = "ossimUsgsDemTileSource::open"; if (traceDebug()) { CLOG << "DEBUG:" << "\nAttempting to parse file: " << theImageFile.c_str() << std::endl; } theIsDemFlag = ossimDemUtil::isUsgsDem(theImageFile); if (theIsDemFlag) { // Open up the file for reading. std::ifstream is(theImageFile.c_str(), std::ios_base::in | std::ios_base::binary); if (is.good()) { // Start out with a fresh dem. if (theDem) delete theDem; //--- // Set the null to -32768. This will also be the missing data values. //--- theNullValue = OSSIM_DEFAULT_NULL_PIX_SINT16; //--- // Read the dem. // // NOTE: This defines the missing data value. It should be the // same as null for mosaicing and min/max calculations. //--- theDem = new ossimDemGrid(theNullValue); theDem->read(is); is.close(); } else { theIsDemFlag = false; } } if (theIsDemFlag) { theFeetFlag = (theDem->getHeader().getElevationUnits() == 1) ? true : false; theMinHeight = theFeetFlag ? theDem->getHeader().getMinimumElev() * MTRS_PER_FT : theDem->getHeader().getMinimumElev(); theMaxHeight = theFeetFlag ? theDem->getHeader().getMaximumElev() * MTRS_PER_FT : theDem->getHeader().getMaximumElev(); completeOpen(); //--- // Set up the tiles. Note the blank tile will not get initialized to // save memory. This includes setting the min and max pixel value // gathered from the statistics. //--- theTile = ossimImageDataFactory::instance()->create(this, this); theTile->initialize(); if (traceDebug()) { CLOG << setiosflags(ios::fixed) << setprecision(5) << "DEBUG:" << "\nNull pix: " << (theTile->getNullPix(0)) << "\nMin pix: " << (theTile->getMinPix(0)) << "\nMax pix: " << (theTile->getMaxPix(0)) << "\nlines: " << theDem->getHeight() << "\nsamples: " << theDem->getWidth() << std::endl; } } return theIsDemFlag; } bool ossimUsgsDemTileSource::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Save of the dem type keyword. kwl.add(prefix, DEM_TYPE_KW, USGS_DEM_KW, true); // Save the scalar type. kwl.add(prefix, ossimKeywordNames::SCALAR_TYPE_KW, ossimScalarTypeLut::instance()->getEntryString(theScalarType)); return ossimImageHandler::saveState(kwl, prefix); } bool ossimUsgsDemTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (ossimImageHandler::loadState(kwl, prefix)) { //*** // Look for "dem_type: usgs_dem" key value pair. // Note: If not in the keyword list the "open" will look for it on // disk. //*** const char* lookup = kwl.find(prefix, DEM_TYPE_KW); if (lookup) { ossimString s = lookup; s.downcase(); if (s == USGS_DEM_KW) theIsDemFlag = true; } //--- // Look for scalar type override. // // Note: We only allow float or signed 16 bit. //--- lookup = kwl.find(prefix, ossimKeywordNames::SCALAR_TYPE_KW); if (lookup) { ossimScalarType st = static_cast(ossimScalarTypeLut::instance()-> getEntryNumber(lookup)); if ( (st == OSSIM_FLOAT32) || (st == OSSIM_SINT16)) { theScalarType = st; } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimUsgsDemTileSource::loadState WARNING:" << "\nInvalid scalar type: " << ossimScalarTypeLut::instance()-> getEntryString(st) << std::endl; } } } if (open()) { return true; } } return false; } ossimRefPtr ossimUsgsDemTileSource::getImageGeometry() { if ( !theGeometry ) { // Check for external geom: theGeometry = getExternalImageGeometry(); if ( !theGeometry ) { // Check the internal geometry first to avoid a factory call. theGeometry = getInternalImageGeometry(); // At this point it is assured theGeometry is set. //--- // WARNING: // Must create/set theGeometry at this point or the next call to // ossimImageGeometryRegistry::extendGeometry will put us in an infinite loop // as it does a recursive call back to ossimImageHandler::getImageGeometry(). //--- // Check for set projection. if ( !theGeometry->getProjection() ) { // Try factories for projection. ossimImageGeometryRegistry::instance()->extendGeometry(this); } } // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); } return theGeometry; } ossimRefPtr ossimUsgsDemTileSource::getInternalImageGeometry() const { ossimRefPtr geom = new ossimImageGeometry(); if (theDem) { const ossimDemHeader HDR = theDem->getHeader(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimUsgsDemTileSource::getInternalImageGeometry DEBUG:" << "\nDEM Header:" << std::endl; HDR.print(ossimNotify(ossimNotifyLevel_DEBUG)); } // The DEM's image geometry is a map projection, obtained here via KWL: ossimKeywordlist proj_kwl; if ( HDR.getImageGeometry(proj_kwl) ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimUsgsDemTileSource::getInternalImageGeometry DEBUG:" << "keyword list:\n" << proj_kwl << std::endl; } // Capture for next time. ossimRefPtr proj = ossimProjectionFactoryRegistry::instance()-> createProjection(proj_kwl); if ( proj.valid() ) { geom->setProjection(proj.get()); } } } return geom; } ossimScalarType ossimUsgsDemTileSource::getOutputScalarType() const { return theScalarType; } ossim_uint32 ossimUsgsDemTileSource::getTileWidth() const { return ( theTile.valid() ? theTile->getWidth() : 0 ); } ossim_uint32 ossimUsgsDemTileSource::getTileHeight() const { return ( theTile.valid() ? theTile->getHeight() : 0 ); } ossim_uint32 ossimUsgsDemTileSource::getNumberOfLines(ossim_uint32 reduced_res_level) const { ossim_uint32 result = 0; if (reduced_res_level == 0) { if (theDem) { result = theDem->getHeight(); } } else if (theOverview.valid()) { result = theOverview->getNumberOfLines(reduced_res_level); } return result; } ossim_uint32 ossimUsgsDemTileSource::getNumberOfSamples(ossim_uint32 reduced_res_level) const { ossim_uint32 result = 0; if (reduced_res_level == 0) { if (theDem) { result = theDem->getWidth(); } } else if (theOverview.valid()) { result = theOverview->getNumberOfSamples(reduced_res_level); } return result; } ossim_uint32 ossimUsgsDemTileSource::getImageTileWidth() const { return 0; } ossim_uint32 ossimUsgsDemTileSource::getImageTileHeight() const { return 0; } ossimString ossimUsgsDemTileSource::getShortName() const { return ossimString("usgs dem"); } ossimString ossimUsgsDemTileSource::getLongName() const { return ossimString("usgs dem reader"); } ossim_uint32 ossimUsgsDemTileSource::getNumberOfInputBands() const { return 1; } ossim_uint32 ossimUsgsDemTileSource::getNumberOfOutputBands()const { return 1; } double ossimUsgsDemTileSource::getNullPixelValue(ossim_uint32 /* band */)const { return theNullValue; } double ossimUsgsDemTileSource::getMinPixelValue(ossim_uint32 band)const { if(band < theMetaData.getNumberOfBands()) { return theMetaData.getMinPix(band); } return theMinHeight; } double ossimUsgsDemTileSource::getMaxPixelValue(ossim_uint32 band)const { if(theMetaData.getNumberOfBands()) { return theMetaData.getMaxPix(band); } return theMaxHeight; } bool ossimUsgsDemTileSource::isOpen()const { return (theDem ? true : false ); } const ossimUsgsDemTileSource& ossimUsgsDemTileSource::operator=(const ossimUsgsDemTileSource& rhs) { return rhs; } ossimUsgsDemTileSource::ossimUsgsDemTileSource(const ossimUsgsDemTileSource&) { } ossim-Miami-2.9.1/src/imaging/ossimValueAssignImageSourceFilter.cpp000066400000000000000000000244551352751253100254210ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimValueAssignImageSourceFilter.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include #include #include using namespace std; RTTI_DEF1(ossimValueAssignImageSourceFilter, "ossimValueAssignImageSourceFilter", ossimImageSourceFilter); ossimValueAssignImageSourceFilter::ossimValueAssignImageSourceFilter(ossimObject* owner) :ossimImageSourceFilter(owner), theAssignType(ossimValueAssignType_GROUP), theTile(NULL) { } ossimValueAssignImageSourceFilter::~ossimValueAssignImageSourceFilter() { } ossimRefPtr ossimValueAssignImageSourceFilter::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) { return NULL; // This filter requires an input. } ossimRefPtr inputTile = theInputConnection->getTile(tileRect, resLevel); if(!isSourceEnabled() || !inputTile.valid()) { return inputTile; } if(!theTile.valid()) { allocate(); // First time through... } if (!theTile.valid()) // throw exeption... { return inputTile; } // Set the origin, resize if needed of the output tile. theTile->setImageRectangle(tileRect); if( inputTile->getDataObjectStatus() == OSSIM_NULL || inputTile->getDataObjectStatus() == OSSIM_EMPTY ) { theTile->makeBlank(); return theTile; } if(!inputTile->getBuf()) { theTile->makeBlank(); } else { theTile->loadTile(inputTile.get()); } switch(inputTile->getScalarType()) { case OSSIM_UCHAR: { executeAssign(static_cast(0), theTile); break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { executeAssign(static_cast(0), theTile); break; } case OSSIM_USHORT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { executeAssign(static_cast(0), theTile); break; } case OSSIM_SSHORT16: { executeAssign(static_cast(0), theTile); break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { executeAssign(static_cast(0), theTile); break; } default: { ossimNotify(ossimNotifyLevel_WARN) << "ossimValueAssignImageSourceFilter::getTile WARN: Scalar type = " << theTile->getScalarType() << " Not supported!" << std::endl; break; } } theTile->validate(); return theTile; } void ossimValueAssignImageSourceFilter::setInputOutputValues(const vector& inputValues, const vector& outputValues) { theInputValueArray = inputValues; theOutputValueArray = outputValues; validateArrays(); } void ossimValueAssignImageSourceFilter::validateArrays() { if(theOutputValueArray.size() != theInputValueArray.size()) { ossim_uint32 index = std::min((ossim_uint32)theOutputValueArray.size(), (ossim_uint32)theInputValueArray.size()); vector copyVector(theOutputValueArray.begin(), theOutputValueArray.begin() + index); theOutputValueArray = copyVector; for(ossim_uint32 index2 = index; index < theInputValueArray.size(); ++index) { theOutputValueArray.push_back(theInputValueArray[index2]); } } } template void ossimValueAssignImageSourceFilter::executeAssign( T, ossimRefPtr& data) { if(!theInputValueArray.size()) return; if(theAssignType == ossimValueAssignType_SEPARATE) { executeAssignSeparate(static_cast(0), data); } else { executeAssignGroup(static_cast(0), data); } } template void ossimValueAssignImageSourceFilter::executeAssignSeparate( T, ossimRefPtr& data) { ossim_uint32 numberOfBands = std::min((ossim_uint32)data->getNumberOfBands(), (ossim_uint32)theInputValueArray.size()); ossim_uint32 maxOffset = data->getWidth()*data->getHeight(); for(ossim_uint32 band = 0; band(data->getBuf(band)); T inValue = static_cast(theInputValueArray[band]); T outValue = static_cast(theOutputValueArray[band]); for(ossim_uint32 count = 0; count < maxOffset; ++count) { if(*buf == inValue) { *buf = outValue; } ++buf; } } } template void ossimValueAssignImageSourceFilter::executeAssignGroup( T, ossimRefPtr& data) { ossim_uint32 numberOfBands = std::min((ossim_uint32)data->getNumberOfBands(), (ossim_uint32)theInputValueArray.size()); ossim_uint32 maxOffset = data->getWidth()*data->getHeight(); ossim_uint32 band = 0; bool equalFlag = false; T** bufArray = new T*[data->getNumberOfBands()]; for(band = 0; band < data->getNumberOfBands(); ++band) { bufArray[band] = static_cast(data->getBuf(band)); } for(ossim_uint32 offset = 0; offset < maxOffset; ++offset) { equalFlag = true; for(band = 0; band(theOutputValueArray[band]); } } } delete [] bufArray; } void ossimValueAssignImageSourceFilter::initialize() { // Base class will recapture "theInputConnection". ossimImageSourceFilter::initialize(); } void ossimValueAssignImageSourceFilter::allocate() { theTile = NULL; if(theInputConnection) { ossimImageDataFactory* idf = ossimImageDataFactory::instance(); theTile = idf->create(this, this); theTile->initialize(); } } bool ossimValueAssignImageSourceFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossim_uint32 index = 0; for(index =0; index < theInputValueArray.size(); ++index) { ossimString in = ("input_band" + ossimString::toString(index)); ossimString out = ("output_band" + ossimString::toString(index)); kwl.add(prefix, in.c_str(), theInputValueArray[index], true); kwl.add(prefix, out.c_str(), theOutputValueArray[index], true); } if(theAssignType == ossimValueAssignType_SEPARATE) { kwl.add(prefix, "assign_type", "separate", true); } else { kwl.add(prefix, "assign_type", "group", true); } return ossimImageSourceFilter::saveState(kwl, prefix); } /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ bool ossimValueAssignImageSourceFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString inRegExpression = ossimString("^(") + ossimString(prefix) + "input_band[0-9]+)"; ossimString outRegExpression = ossimString("^(") + ossimString(prefix) + "output_band[0-9]+)"; ossim_uint32 numberOfInputs = kwl.getNumberOfSubstringKeys(inRegExpression); ossim_uint32 numberOfOutputs = kwl.getNumberOfSubstringKeys(outRegExpression); ossim_uint32 index = 0; ossim_uint32 currentIndex = 0; theInputValueArray.clear(); theOutputValueArray.clear(); while(index < numberOfInputs) { const char* value = kwl.find(prefix, (ossimString("input_band") + ossimString::toString(currentIndex)).c_str() ); if(value) { theInputValueArray.push_back(ossimString(value).toDouble()); ++index; } ++currentIndex; } index = 0; currentIndex = 0; while(index < numberOfOutputs) { const char* value = kwl.find(prefix, (ossimString("output_band") + ossimString::toString(currentIndex)).c_str() ); if(value) { theOutputValueArray.push_back(ossimString(value).toDouble()); ++index; } ++currentIndex; } validateArrays(); const char* assignType = kwl.find(prefix, "assign_type"); if(assignType) { if(ossimString(assignType).trim().downcase() == "separate") { theAssignType = ossimValueAssignType_SEPARATE; } else { theAssignType = ossimValueAssignType_GROUP; } } else { theAssignType = ossimValueAssignType_GROUP; } return ossimImageSourceFilter::loadState(kwl, prefix); } const vector& ossimValueAssignImageSourceFilter::getInputValues()const { return theInputValueArray; } const vector& ossimValueAssignImageSourceFilter::getOutputValues()const { return theOutputValueArray; } ossimValueAssignImageSourceFilter::ossimValueAssignType ossimValueAssignImageSourceFilter::getValueAssignType()const { return theAssignType; } void ossimValueAssignImageSourceFilter::setValueAssignType(ossimValueAssignType type) { theAssignType = type; } ossim-Miami-2.9.1/src/imaging/ossimVectorRenderer.cpp000066400000000000000000000064021352751253100226270ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken (dburken@imagelinks.com) // // Description: // // Abstract class for rendering vector data. Derived classes should implement // the "rasterizeVectorData" data method. // //******************************************************************* // $Id: ossimVectorRenderer.cpp 17195 2010-04-23 17:32:18Z dburken $ #include using namespace std; #include #include #include #include #include #include #include RTTI_DEF1(ossimVectorRenderer, "ossimVectorRenderer", ossimImageSourceFilter) ossimVectorRenderer::ossimVectorRenderer() : ossimImageSourceFilter(), theImageViewTransform(NULL), theBoundingRect(), theAreaOfInterest(), theNumberOfAoiObjects(0), theNumberOfObjects(0) { } ossimVectorRenderer::ossimVectorRenderer(ossimImageSource* inputSource, ossimImageViewTransform* transform) : ossimImageSourceFilter(inputSource), theImageViewTransform(transform), theBoundingRect(), theAreaOfInterest(), theNumberOfAoiObjects(0), theNumberOfObjects(0) { } ossimVectorRenderer::~ossimVectorRenderer() { if (theImageViewTransform) { delete theImageViewTransform; theImageViewTransform = NULL; } } bool ossimVectorRenderer::saveState(ossimKeywordlist& /* kwl */, const char* /* prefix */ ) const { return false; } bool ossimVectorRenderer::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString newPrefix = prefix + ossimString("image_view_trans."); if(theImageViewTransform) { delete theImageViewTransform; theImageViewTransform = NULL; } theImageViewTransform = ossimImageViewTransformFactory::instance()-> createTransform(kwl, newPrefix.c_str()); return ossimImageSource::loadState(kwl, prefix); } void ossimVectorRenderer::setImageViewTransform(ossimImageViewTransform* transform) { if(theImageViewTransform) { delete theImageViewTransform; } theImageViewTransform = transform; } void ossimVectorRenderer::setAreaOfInterest(const ossimDrect& aoi) { theAreaOfInterest = aoi; } ossimDrect ossimVectorRenderer::getAreaOfInterest() const { return theAreaOfInterest; } ossimDrect ossimVectorRenderer::getBoundingRect(long /* resLevel */)const { return theBoundingRect; } ossim_int32 ossimVectorRenderer::getNumberOfAoiObjects() const { return theNumberOfAoiObjects; } ossim_int32 ossimVectorRenderer::getNumberOfObjects() const { return theNumberOfObjects; } void ossimVectorRenderer::setBoundingRect(ossimDrect& rect) { theBoundingRect = rect; } void ossimVectorRenderer::setNumberOfAoiObjects(ossim_int32 number_of_objects) { theNumberOfAoiObjects = number_of_objects; } void ossimVectorRenderer::setNumberOfObjects(ossim_int32 number_of_objects) { theNumberOfObjects = number_of_objects; } ossim-Miami-2.9.1/src/imaging/ossimVertexExtractor.cpp000066400000000000000000002143401352751253100230510ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // TR # 136 kminear Fix extractVertices method // //************************************************************************* // $Id: ossimVertexExtractor.cpp 21184 2012-06-29 15:13:09Z dburken $ #include using namespace std; #include #include #include #include #include static ossimTrace traceDebug("ossimVertexExtractor:debug"); RTTI_DEF2(ossimVertexExtractor, "ossimVertexExtractor", ossimSource, ossimProcessInterface); ossimVertexExtractor::ossimVertexExtractor(ossimImageSource* inputSource) : ossimOutputSource(0, // owner 1, 0, true, true), ossimProcessInterface(), theAreaOfInterest(), theFilename(ossimFilename::NIL), theFileStream(), theVertice(4), theLeftEdge(0), theRightEdge(0) { if (inputSource == 0) { ossimNotify(ossimNotifyLevel_WARN) << "ossimVertexExtractor::ossimVertexExtractor ERROR" << "\nNULL input image source passed to constructor!" << std::endl; } connectMyInputTo(0, inputSource); // theInputObjectList[0] = inputSource; theAreaOfInterest.makeNan(); } ossimVertexExtractor::~ossimVertexExtractor() { } bool ossimVertexExtractor::execute() { static const char MODULE[] = "ossimVertexExtractor::execute"; if (traceDebug()) CLOG << " Entered..." << endl; if (theFilename == ossimFilename::NIL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimVertexExtractor::execute WARNING:" << "\nOutput file name is empty. Use setFilename method..." << std::endl; return false; } if (theAreaOfInterest.isNan()) { ossimNotify(ossimNotifyLevel_NOTICE) << MODULE << " NOTICE ossimVertexExtractor::execute:" << "\nArea of interest is not set. Use setAreaOfInterest method..." << "\nDefaulting to bounding rectangle of input source." << std::endl; ossimImageSource* src = reinterpret_cast(getInput(0)); theAreaOfInterest = src->getBoundingRect(0); } setProcessStatus(ossimProcessInterface::PROCESS_STATUS_EXECUTING); if (scanForEdges()) { if (extractVertices()) { writeVertices(); } else { return false; } } else { return false; } setProcessStatus(ossimProcessInterface::PROCESS_STATUS_NOT_EXECUTING); if (traceDebug()) CLOG << " Exited..." << endl; return true; } bool ossimVertexExtractor::scanForEdges() { static const char MODULE[] = "ossimVertexExtractor::scanForEdges"; if (traceDebug()) CLOG << " Entered..." << endl; ossimImageSource* src = reinterpret_cast(getInput(0)); if (!src) { ossimNotify(ossimNotifyLevel_WARN) << "WARN ossimVertexExtractor::scanForEdges():" << "\nInput source is null. Returning..." << std::endl; return false; } // Allocate the arrays to hold the edges. theLeftEdge.resize(theAreaOfInterest.height()); theRightEdge.resize(theAreaOfInterest.height()); for (ossim_int32 i=0; i<(int)theAreaOfInterest.height(); ++i) { theLeftEdge[i] = OSSIM_INT_NAN; theRightEdge[i] = OSSIM_INT_NAN; } // Some constants needed throughout... const ossim_int32 TILE_HEIGHT = src->getTileHeight(); const ossim_int32 TILE_WIDTH = src->getTileWidth(); const ossim_int32 START_LINE = theAreaOfInterest.ul().y; const ossim_int32 STOP_LINE = theAreaOfInterest.lr().y; const ossim_int32 START_SAMP = theAreaOfInterest.ul().x; const ossim_int32 STOP_SAMP = theAreaOfInterest.lr().x; // For percent complete status. double total_tiles_y_dir = theAreaOfInterest.height() / TILE_HEIGHT; if (theAreaOfInterest.height() % TILE_HEIGHT) total_tiles_y_dir += 1.0; double tiles_processed = 0.0; // Set the status message to be "scanning source for edges..." ossimNotify(ossimNotifyLevel_INFO) << "Scanning image source for edges..." << std::endl; // Start off with a percent complete at 0... setPercentComplete(0.0); // Start of loop to get the left edges. // Tile loop in line direction through area of interest. for (ossim_int32 line = START_LINE; line < STOP_LINE; line += TILE_HEIGHT) { const ossim_int32 START_INDEX = line - START_LINE; const ossim_int32 STOP_INDEX = ( (line+TILE_HEIGHT-1) < STOP_LINE ) ? (START_INDEX+TILE_HEIGHT-1) : (theAreaOfInterest.height()-1); const ossim_int32 TILE_LINE_STOP = ((line+TILE_HEIGHT-1) < STOP_LINE) ? (line+TILE_HEIGHT-1) : STOP_LINE; // See if all the edges have been found for these tile lines. bool all_edges_found = true; for (ossim_int32 i = START_INDEX; i <= STOP_INDEX; ++i) { if (theLeftEdge[i] == OSSIM_INT_NAN) { all_edges_found = false; break; } } // Extract the left edges... if (all_edges_found == false) { //*** // Tile loop in sample direction through area of interest // (left edges). //*** for (ossim_int32 samp = START_SAMP; samp < STOP_SAMP; samp += TILE_WIDTH) { // Get the tile. ossimRefPtr id = src->getTile(ossimIpt(samp, line)); if (!id.valid() || id->getDataObjectStatus() == OSSIM_NULL || id->getDataObjectStatus() == OSSIM_EMPTY) { continue; // Nothing to do... } // Line loop through tile. const ossim_int32 TILE_SAMP_STOP = ((samp+TILE_WIDTH-1) < STOP_SAMP) ? (samp+TILE_WIDTH-1) : STOP_SAMP; for (ossim_int32 y = line; y <= TILE_LINE_STOP; ++y) { ossim_int32 edge_index = y - START_LINE; if (theLeftEdge[edge_index] == OSSIM_INT_NAN) { for (ossim_int32 x = samp; x <= TILE_SAMP_STOP; ++x) { if (! (id->isNull(ossimIpt(x,y)))) { // Capture the first valid pixel. theLeftEdge[edge_index] = x - START_SAMP; break; } } } } } // End of tile loop in sample direction through area of interest. } // End of (all_lines_checked == false) (left edges) // See if all the right edges have been found for these tile lines. all_edges_found = true; for (ossim_int32 i = START_INDEX; i <= STOP_INDEX; ++i) { if (theRightEdge[i] == OSSIM_INT_NAN) { all_edges_found = false; break; } } // Extract the right edges... if (all_edges_found == false) { //*** // Tile loop in sample direction through area of interest // (right edges). //*** // Get the x origin of the last tile in a row. const ossim_int32 END_TILE_X = START_SAMP + ((theAreaOfInterest.width()/ TILE_WIDTH)*TILE_WIDTH); for (ossim_int32 samp = END_TILE_X; samp >= START_SAMP; samp -= TILE_WIDTH) { // Get the tile. ossimRefPtr id = src->getTile(ossimIpt(samp, line)); if (!id.valid() || id->getDataObjectStatus() == OSSIM_NULL || id->getDataObjectStatus() == OSSIM_EMPTY) { continue; // Nothing to do... } // Line loop through tile. const ossim_int32 TILE_SAMP_STOP = ((samp+TILE_WIDTH-1) < STOP_SAMP) ? (samp+TILE_WIDTH-1) : STOP_SAMP; for (ossim_int32 y = line; y <= TILE_LINE_STOP; ++y) { ossim_int32 edge_index = y - START_LINE; if (theRightEdge[edge_index] == OSSIM_INT_NAN) { for (ossim_int32 x = TILE_SAMP_STOP; x >= samp; --x) { if (! (id->isNull(ossimIpt(x,y)))) { // Capture the first valid pixel. theRightEdge[edge_index] = x - START_SAMP; break; } } } } } // End of tile loop in sample direction through area of interest. } // End of (all_lines_checked == false) // Set the percent complete. tiles_processed += 1.0; setPercentComplete(tiles_processed/total_tiles_y_dir*100.0); } // End of loop through tiles in line direction. setPercentComplete(100.0); if (traceDebug()) { CLOG << "DEBUG:" << endl; for (ossim_int32 i=0; i<(int)theAreaOfInterest.height(); ++i) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: left[" << i << "]: " << theLeftEdge[i] << " right[" << i << "]: " << theRightEdge[i] << std::endl; } } return true; } bool ossimVertexExtractor::extractVertices() { //*** // This method returns the non-null vertexes of the image corners. // This can be used to initialize the "ValidImageVertices" for an // image. // This method does not handle images that have more than four vertexes. //*** static const char MODULE[] = "ossimVertexExtractor::extractVertices"; if (traceDebug()) CLOG << " Entered..." << endl; if (theLeftEdge.empty() || theRightEdge.empty()) { ossimNotify(ossimNotifyLevel_WARN) << "ERROR ossimVertexExtractor::extractVertices():" << "\nEdges not initialized!" << std::endl; return false; } // Image must be quadrilateral (i.e. 4 sided polygon) ossim_int32 total_lines = theAreaOfInterest.height(); ossim_int32 topLine = 0; ossim_int32 bottomLine = 0; ossim_int32 firstLeftSample = 0; ossim_int32 firstRightSample = 0; ossim_int32 lastLeftSample = 0; ossim_int32 lastRightSample = 0; ossim_int32 leftMostSample = 0; ossim_int32 leftMostSampleLine = 0; ossim_int32 rightMostSample = 0; ossim_int32 rightMostSampleLine = 0; ossim_int32 leftCorner_A = 0; ossim_int32 leftCornerLine_A = 0; ossim_int32 leftCorner_B = 0; ossim_int32 leftCornerLine_B = 0; ossim_int32 rightCorner_A = 0; ossim_int32 rightCornerLine_A = 0; ossim_int32 rightCorner_B = 0; ossim_int32 rightCornerLine_B = 0; bool found_first_non_null_line = 0; bool found_last_non_null_line = 0; bool rhombus = false; bool square = false; bool left = false; bool right = false; ossim_int32 first_non_null_line = 0; ossim_int32 last_non_null_line = 0; ossim_int32 i = 0; while(found_last_non_null_line == 0) { // Look for the first row with a valid DN // Nulls are negative if( (theLeftEdge[i] >= 0) && (found_first_non_null_line == 0) ) { // Found first valid pixel at row i found_first_non_null_line = 1; first_non_null_line = i; // Finish walking down the rows of the image while( (found_first_non_null_line == 1) && (theLeftEdge[i] >= 0) && (found_last_non_null_line == 0) && (i <= total_lines) ) { i = i+1; } found_last_non_null_line = 1; last_non_null_line = i-1; } i = i+1; }//end while "found_last_non_null_line == 0" last_non_null_line = last_non_null_line -1; topLine = first_non_null_line; bottomLine = last_non_null_line; // Record the slope searching from the right edge ossim_int32 k = 0; ossim_int32 start = first_non_null_line; ossim_int32 end = last_non_null_line; ossim_int32 sizeDeltaSlope = last_non_null_line - first_non_null_line; std::vector rightSlope(sizeDeltaSlope); for(ossim_int32 i = start; i <= (end - 100); i += 100) { ossim_int32 run = theRightEdge[i] - theRightEdge[i + 100]; if(run != 0) { rightSlope[k] = 100.0 / run; } else { rightSlope[k]= OSSIM_INT_NAN; } k = k + 1; } if (traceDebug()) { CLOG << "DEBUG:" << endl; for (ossim_int32 i=0; i<= k-1; i++) { ossimNotify(ossimNotifyLevel_DEBUG)<< setprecision(15) << "rightSlope[" << i << "]: " << rightSlope[i] << std::endl; } } // Record the slope searching from the left edge k = 0; std::vector leftSlope(sizeDeltaSlope); for(ossim_int32 i = start; i <= (end - 100); i += 100) { ossim_int32 run = theLeftEdge[i] - theLeftEdge[i + 100]; if(run != 0) { leftSlope[k] = 100.0 / run; } else { leftSlope[k] = OSSIM_INT_NAN; } k = k + 1; } if (traceDebug()) { CLOG << "DEBUG:" << endl; for (ossim_int32 i=0; i<= k-1; i++) { ossimNotify(ossimNotifyLevel_DEBUG) << setprecision(15) << "leftSlope[" << i << "]: " << leftSlope[i] << std::endl; } } ossim_int32 sizeOftheSlope = k-1; ossim_int32 counter = 0; // Find the right most sample ossim_int32 rightMostEdgeTemp = theRightEdge[topLine]; ossim_int32 rightMostEdgeTempLine = 0; for(ossim_int32 i= (topLine+1); i= rightMostEdgeTemp) { rightMostEdgeTemp = theRightEdge[i]; rightMostEdgeTempLine = i; } } rightMostSample = rightMostEdgeTemp; rightMostSampleLine = rightMostEdgeTempLine-1; lastLeftSample = theLeftEdge[bottomLine]; // Find the left most sample ossim_int32 leftMostEdgeTemp = theLeftEdge[topLine]; ossim_int32 leftMostEdgeTempLine = 0; for(ossim_int32 i= (topLine+1); i halfsamps ) { // Case is rhombus (clipped or not clipped) rhombus = 1; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<<"\n\n***Case = RHOMBUS***"<(theRightEdge[line1_pt1]), static_cast(theRightEdge[line1_pt2]), static_cast(theRightEdge[line1_pt3]) }; double line1RegPtsLines[] = { static_cast(-line1_pt1), static_cast(-line1_pt2), static_cast(-line1_pt3) }; double sum_xy_line1 = 0.0; double sum_x_line1 = 0.0; double sum_y_line1 = 0.0; double mean_x_line1 = 0.0; double mean_y_line1 = 0.0; double sum_x_squared_line1 = 0.0; double sum_squared_x_line1 = 0.0; double b_line1; double a_line1; double num_elements_line1 = 3.0; for(ossim_int32 i = 0; i < num_elements_line1; ++i) { sum_xy_line1 = sum_xy_line1 + (line1RegPtsSamples[i]*line1RegPtsLines[i]); sum_x_line1 = sum_x_line1 + line1RegPtsSamples[i]; sum_y_line1 = sum_y_line1 + line1RegPtsLines[i]; sum_squared_x_line1 = sum_squared_x_line1 + line1RegPtsSamples[i]*line1RegPtsSamples[i]; } sum_x_squared_line1 = sum_x_line1*sum_x_line1; mean_y_line1 = sum_y_line1/num_elements_line1; mean_x_line1 = sum_x_line1/num_elements_line1; b_line1 = (sum_xy_line1 - (sum_x_line1*sum_y_line1)/num_elements_line1) / (sum_squared_x_line1 - (sum_x_squared_line1/num_elements_line1)); a_line1 = mean_y_line1 - b_line1*mean_x_line1; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<<" a_line1: "<< a_line1 <(theRightEdge[line2_pt1]), static_cast(theRightEdge[line2_pt2]), static_cast(theRightEdge[line2_pt3]) }; double line2RegPtsLines[] = { static_cast(-line2_pt1), static_cast(-line2_pt2), static_cast(-line2_pt3) }; double sum_xy_line2 = 0.0; double sum_x_line2 = 0.0; double sum_y_line2 = 0.0; double mean_x_line2 = 0.0; double mean_y_line2 = 0.0; double sum_x_squared_line2 = 0.0; double sum_squared_x_line2 = 0.0; double b_line2; double a_line2; double num_elements_line2 = 3.0; for(ossim_int32 i = 0; i < num_elements_line2; ++i) { sum_xy_line2 = sum_xy_line2 + (line2RegPtsSamples[i]*line2RegPtsLines[i]); sum_x_line2 = sum_x_line2 + line2RegPtsSamples[i]; sum_y_line2 = sum_y_line2 + line2RegPtsLines[i]; sum_squared_x_line2 = sum_squared_x_line2 + line2RegPtsSamples[i]*line2RegPtsSamples[i]; } sum_x_squared_line2 = sum_x_line2*sum_x_line2; mean_y_line2 = sum_y_line2/num_elements_line2; mean_x_line2 = sum_x_line2/num_elements_line2; b_line2 = (sum_xy_line2 - (sum_x_line2*sum_y_line2)/num_elements_line2) / (sum_squared_x_line2 - (sum_x_squared_line2/num_elements_line2)); a_line2 = mean_y_line2 - b_line2*mean_x_line2; if(traceDebug()) { for(ossim_int32 i = 0; i < num_elements_line2; ++i) { ossimNotify(ossimNotifyLevel_DEBUG) << setprecision(15) << "line2RegPtsLines[" << i << "]: " <(theLeftEdge[line3_pt1]), static_cast(theLeftEdge[line3_pt2]), static_cast(theLeftEdge[line3_pt3]) }; double line3RegPtsLines[] = { static_cast(-line3_pt1), static_cast(-line3_pt2), static_cast(-line3_pt3) }; double sum_xy_line3 = 0.0; double sum_x_line3 = 0.0; double sum_y_line3 = 0.0; double mean_x_line3 = 0.0; double mean_y_line3 = 0.0; double sum_x_squared_line3 = 0.0; double sum_squared_x_line3 = 0.0; double b_line3; double a_line3; double num_elements_line3 = 3.0; for(ossim_int32 i = 0; i < num_elements_line3; ++i) { sum_xy_line3 = sum_xy_line3 + (line3RegPtsSamples[i]*line3RegPtsLines[i]); sum_x_line3 = sum_x_line3 + line3RegPtsSamples[i]; sum_y_line3 = sum_y_line3 + line3RegPtsLines[i]; sum_squared_x_line3 = sum_squared_x_line3 + line3RegPtsSamples[i]*line3RegPtsSamples[i]; } sum_x_squared_line3 = sum_x_line3*sum_x_line3; mean_y_line3 = sum_y_line3/num_elements_line3; mean_x_line3 = sum_x_line3/num_elements_line3; b_line3 = (sum_xy_line3 - (sum_x_line3*sum_y_line3)/num_elements_line3) / (sum_squared_x_line3 - (sum_x_squared_line3/num_elements_line3)); a_line3 = mean_y_line3 - b_line3*mean_x_line3; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\n\n a_line3: " << a_line3 <(theLeftEdge[line4_pt1]), static_cast(theLeftEdge[line4_pt2]), static_cast(theLeftEdge[line4_pt3]) }; double line4RegPtsLines[] = { static_cast(-line4_pt1), static_cast(-line4_pt2), static_cast(-line4_pt3) }; double sum_xy_line4 = 0.0; double sum_x_line4 = 0.0; double sum_y_line4 = 0.0; double mean_x_line4 = 0.0; double mean_y_line4 = 0.0; double sum_x_squared_line4 = 0.0; double sum_squared_x_line4 = 0.0; double b_line4; double a_line4; double num_elements_line4 = 3.0; for(ossim_int32 i = 0; i < num_elements_line4; ++i) { sum_xy_line4 = sum_xy_line4 + (line4RegPtsSamples[i]*line4RegPtsLines[i]); sum_x_line4 = sum_x_line4 + line4RegPtsSamples[i]; sum_y_line4 = sum_y_line4 + line4RegPtsLines[i]; sum_squared_x_line4 = sum_squared_x_line4 + line4RegPtsSamples[i]*line4RegPtsSamples[i]; } sum_x_squared_line4 = sum_x_line4*sum_x_line4; mean_y_line4 = sum_y_line4/num_elements_line4; mean_x_line4 = sum_x_line4/num_elements_line4; b_line4 = (sum_xy_line4 - (sum_x_line4*sum_y_line4)/num_elements_line4) / (sum_squared_x_line4 - (sum_x_squared_line4/num_elements_line4)); a_line4 = mean_y_line4 - b_line4*mean_x_line4; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<<"\na_line4: "<< a_line4 <<"\nb_line4: "<< b_line4 < than num samples // line should be between top and bottom lines //for corner 2 (lr), line should be between top and bottom line + 200 // sample should be between left and right most sample //for corner 3 (ll), line should be between top and bottom line // sample should can go negative due to jagged edges if( (leftCornerLine_A < (topLine - 300)) || (leftCornerLine_A > total_lines) || (leftCorner_A > rightMostSample) || (leftCorner_A < leftMostSample) || (rightCornerLine_A < topLine) || (rightCornerLine_A > bottomLine) || (rightCorner_A < leftMostSample) || (rightCorner_A > (rightMostSample + 200)) || (rightCornerLine_B < topLine) || (rightCornerLine_B > (bottomLine + 200)) || (rightCorner_B < leftMostSample) || (rightCorner_B > rightMostSample) || (leftCornerLine_B > bottomLine) || (leftCornerLine_B < topLine) || (leftCorner_B > rightMostSample) || (leftCorner_B < (leftMostSample - 200)) ) { right = false; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\n\n***Case = NOT TILTED RIGHT...***"< lastRightSample) {//begin tilted left if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\n\n***Case = TILTED LEFT***"<(theRightEdge[line1_pt1]), static_cast(theRightEdge[line1_pt2]), static_cast(theRightEdge[line1_pt3])}; double line1RegPtsLines[] = { static_cast(-line1_pt1), static_cast(-line1_pt2), static_cast(-line1_pt3) }; double sum_xy_line1 = 0.0; double sum_x_line1 = 0.0; double sum_y_line1 = 0.0; double mean_x_line1 = 0.0; double mean_y_line1 = 0.0; double sum_x_squared_line1 = 0.0; double sum_squared_x_line1 = 0.0; double b_line1; double a_line1; double num_elements_line1 = 3.0; for(ossim_int32 i = 0; i < num_elements_line1; ++i) { sum_xy_line1 = sum_xy_line1 + (line1RegPtsSamples[i]*line1RegPtsLines[i]); sum_x_line1 = sum_x_line1 + line1RegPtsSamples[i]; sum_y_line1 = sum_y_line1 + line1RegPtsLines[i]; sum_squared_x_line1 = sum_squared_x_line1 + line1RegPtsSamples[i]*line1RegPtsSamples[i]; } sum_x_squared_line1 = sum_x_line1*sum_x_line1; mean_y_line1 = sum_y_line1/num_elements_line1; mean_x_line1 = sum_x_line1/num_elements_line1; b_line1 = (sum_xy_line1 - (sum_x_line1*sum_y_line1)/num_elements_line1) / (sum_squared_x_line1 - (sum_x_squared_line1/num_elements_line1)); a_line1 = mean_y_line1 - b_line1*mean_x_line1; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<<"a_line1: "<< a_line1 <<"\nb_line1: "<< b_line1 <(theRightEdge[line2_pt1]), static_cast(theRightEdge[line2_pt2]), static_cast(theRightEdge[line2_pt3]) }; double line2RegPtsLines[] = { static_cast(-line2_pt1), static_cast(-line2_pt2), static_cast(-line2_pt3) }; double sum_xy_line2 = 0.0; double sum_x_line2 = 0.0; double sum_y_line2 = 0.0; double mean_x_line2 = 0.0; double mean_y_line2 = 0.0; double sum_x_squared_line2 = 0.0; double sum_squared_x_line2 = 0.0; double b_line2; double a_line2; double num_elements_line2 = 3.0; for(ossim_int32 i = 0; i < num_elements_line2; ++i) { sum_xy_line2 = sum_xy_line2 + (line2RegPtsSamples[i]*line2RegPtsLines[i]); sum_x_line2 = sum_x_line2 + line2RegPtsSamples[i]; sum_y_line2 = sum_y_line2 + line2RegPtsLines[i]; sum_squared_x_line2 = sum_squared_x_line2 + line2RegPtsSamples[i]*line2RegPtsSamples[i]; } sum_x_squared_line2 = sum_x_line2*sum_x_line2; mean_y_line2 = sum_y_line2/num_elements_line2; mean_x_line2 = sum_x_line2/num_elements_line2; b_line2 = (sum_xy_line2 - (sum_x_line2*sum_y_line2)/num_elements_line2) / (sum_squared_x_line2 - (sum_x_squared_line2/num_elements_line2)); a_line2 = mean_y_line2 - b_line2*mean_x_line2; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "a_line2: "<< a_line2 << "\nb_line2: "<< b_line2 <(theLeftEdge[line3_pt1]), static_cast(theLeftEdge[line3_pt2]), static_cast(theLeftEdge[line3_pt3]) }; double line3RegPtsLines[] = { static_cast(-line3_pt1), static_cast(-line3_pt2), static_cast(-line3_pt3) }; double sum_xy_line3 = 0.0; double sum_x_line3 = 0.0; double sum_y_line3 = 0.0; double mean_x_line3 = 0.0; double mean_y_line3 = 0.0; double sum_x_squared_line3 = 0.0; double sum_squared_x_line3 = 0.0; double b_line3; double a_line3; double num_elements_line3 = 3.0; for(ossim_int32 i = 0; i < num_elements_line3; ++i) { sum_xy_line3 = sum_xy_line3 + (line3RegPtsSamples[i]*line3RegPtsLines[i]); sum_x_line3 = sum_x_line3 + line3RegPtsSamples[i]; sum_y_line3 = sum_y_line3 + line3RegPtsLines[i]; sum_squared_x_line3 = sum_squared_x_line3 + line3RegPtsSamples[i]*line3RegPtsSamples[i]; } sum_x_squared_line3 = sum_x_line3*sum_x_line3; mean_y_line3 = sum_y_line3/num_elements_line3; mean_x_line3 = sum_x_line3/num_elements_line3; b_line3 = (sum_xy_line3 - (sum_x_line3*sum_y_line3)/num_elements_line3) / (sum_squared_x_line3 - (sum_x_squared_line3/num_elements_line3)); a_line3 = mean_y_line3 - b_line3*mean_x_line3; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<<"\n\n a_line3: "<< a_line3 <(theLeftEdge[line4_pt1]), static_cast(theLeftEdge[line4_pt2]), static_cast(theLeftEdge[line4_pt3])}; double line4RegPtsLines[] = { static_cast(-line4_pt1), static_cast(-line4_pt2), static_cast(-line4_pt3) }; double sum_xy_line4 = 0.0; double sum_x_line4 = 0.0; double sum_y_line4 = 0.0; double mean_x_line4 = 0.0; double mean_y_line4 = 0.0; double sum_x_squared_line4 = 0.0; double sum_squared_x_line4 = 0.0; double b_line4; double a_line4; double num_elements_line4 = 3.0; for(ossim_int32 i = 0; i < num_elements_line4; ++i) { sum_xy_line4 = sum_xy_line4 + (line4RegPtsSamples[i]*line4RegPtsLines[i]); sum_x_line4 = sum_x_line4 + line4RegPtsSamples[i]; sum_y_line4 = sum_y_line4 + line4RegPtsLines[i]; sum_squared_x_line4 = sum_squared_x_line4 + line4RegPtsSamples[i]*line4RegPtsSamples[i]; } sum_x_squared_line4 = sum_x_line4*sum_x_line4; mean_y_line4 = sum_y_line4/num_elements_line4; mean_x_line4 = sum_x_line4/num_elements_line4; b_line4 = (sum_xy_line4 - (sum_x_line4*sum_y_line4)/num_elements_line4) / (sum_squared_x_line4 - (sum_x_squared_line4/num_elements_line4)); a_line4 = mean_y_line4 - b_line4*mean_x_line4; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<< "\n\n a_line4: "<< a_line4 < bottomLine) || (leftCornerLine_A < topLine) || (leftCorner_A > rightMostSample) || (leftCorner_A < (leftMostSample - 300)) || (rightCornerLine_A < (topLine - 300)) || (rightCornerLine_A > total_lines) || (rightCorner_A > rightMostSample) || (rightCorner_A < leftMostSample) || (rightCornerLine_B < topLine) || (rightCornerLine_B > bottomLine) || (rightCorner_B < leftMostSample) || (rightCorner_B > (rightMostSample + 200)) || (leftCornerLine_B > (bottomLine + 200)) || (leftCornerLine_B < topLine) || (leftCorner_B < leftMostSample) || (leftCorner_B > rightMostSample) ) { left = false; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\n\n***Case = NOT TILTED LEFT..***"<(getInput(0)); ossimIrect tileRectUL(leftMostSample, topLine, leftMostSample+50, (topLine + 50) ); ossimRefPtr dataUL = src->getTile(tileRectUL); // ossimIrect imageRectangleUL = dataUL->getImageRectangle(); ossim_int32 tempSamp_corner0a = 0; ossim_int32 tempLine_corner0a = 0; if (dataUL.valid()) { for (ossim_int32 line = tileRectUL.ul().y; line <= tileRectUL.lr().y; ++line) { for (ossim_int32 samp = tileRectUL.ul().x; samp <=tileRectUL.ur().x; ++samp) { // uses band 0 corner points if(!(dataUL->isNull(ossimIpt(samp,line),0))) { foundULcornera = true; //Optimal Corner: leftCornerLine_A = line;//0 leftCorner_A = samp; tempLine_corner0a = line; tempSamp_corner0a = samp; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\nFound non null in ul corner pass 1 "<isNull(ossimIpt(samp,line),0))) { foundULcornerb = true; //Optimal Corner: leftCornerLine_A = line;//0 leftCorner_A = samp; tempLine_corner0b = line; tempSamp_corner0b = samp; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\nFound non null in ul corner pass 2 "< dataUR = src->getTile(tileRectUR); // ossimIrect imageRectangleUR = dataUR->getImageRectangle(); ossim_int32 tempSamp_corner1a = 0; ossim_int32 tempLine_corner1a = 0; if (dataUR.valid()) { for (ossim_int32 line = tileRectUR.ul().y; line <= tileRectUR.lr().y; ++line) { for (ossim_int32 samp = tileRectUR.ur().x; samp > tileRectUR.ul().x; --samp) { if(!(dataUR->isNull(ossimIpt(samp,line),0))) { foundURcornera = true; rightCornerLine_A = line; rightCorner_A = samp; tempLine_corner1a = line; tempSamp_corner1a = samp; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\nFound non null in ur corner pass 1 "< tileRectUR.ul().x; --samp) { for (ossim_int32 line = tileRectUR.ul().y; line <= tileRectUR.lr().y; ++line) { if(!(dataUR->isNull(ossimIpt(samp,line),0))) { foundURcornerb = true; rightCornerLine_A = line; rightCorner_A = samp; tempLine_corner1b = line; tempSamp_corner1b = samp; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\nFound non null in ur corner pass 2 "< dataLR = src->getTile(tileRectLR); // ossimIrect imageRectangleLR = dataLR->getImageRectangle(); ossim_int32 tempSamp_corner2a = 0; ossim_int32 tempLine_corner2a = 0; if (dataLR.valid()) { for (ossim_int32 line = tileRectLR.lr().y; line >= tileRectLR.ur().y; --line) { for (ossim_int32 samp = tileRectLR.lr().x; samp > tileRectLR.ul().x; --samp) { if(!(dataLR->isNull(ossimIpt(samp,line),0))) { foundLRcornera = true; rightCornerLine_B = line; rightCorner_B = samp; tempLine_corner2a = line; tempSamp_corner2a = samp; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\nFound non null in lr corner pass 1 "< tileRectLR.ul().x; --samp) { for (ossim_int32 line = tileRectLR.lr().y; line >= tileRectLR.ur().y; --line) { if(!(dataLR->isNull(ossimIpt(samp,line),0))) { foundLRcornerb = true; rightCornerLine_B = line; rightCorner_B = samp; tempLine_corner2b = line; tempSamp_corner2b = samp; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\nFound non null in lr corner pass 2"< dataLL = src->getTile(tileRectLL); // ossimIrect imageRectangleLL = dataLL->getImageRectangle(); ossim_int32 tempSamp_corner3a = 0; ossim_int32 tempLine_corner3a = 0; if (dataLL.valid()) { for (ossim_int32 samp = tileRectLL.ul().x; samp <= tileRectLL.ur().x; ++samp) { for (ossim_int32 line = tileRectLL.lr().y; line >= tileRectLL.ul().y; --line) { if(!(dataLL->isNull(ossimIpt(samp,line),0))) { foundLLcornera = true; leftCornerLine_B = line; leftCorner_B = samp; tempLine_corner3a = line; tempSamp_corner3a = samp; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\nFound non null in ll corner pass 1"<= tileRectLL.ul().y; --line) { for (ossim_int32 samp = tileRectLL.ul().x; samp <= tileRectLL.ur().x; ++samp) { if(!(dataLL->isNull(ossimIpt(samp,line),0))) { foundLLcornerb = true; leftCornerLine_B = line; leftCorner_B = samp; tempLine_corner3b = line; tempSamp_corner3b = samp; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<"\nFound non null in ll corner pass 2 "<(&theFileStream)->is_open(); } bool ossimVertexExtractor::open() { if(isOpen()) { close(); } if (theFilename == ossimFilename::NIL) { ossimNotify(ossimNotifyLevel_WARN) << "ossimVertexExtractor::open WARNING:" << "\nOutput file has not been set. Call setFilename() method..." << std::endl; return false; } theFileStream.open(theFilename.c_str()); return theFileStream.good(); } void ossimVertexExtractor::close() { if (isOpen()) theFileStream.close(); } template void ossimVertexExtractor::getMinAndIndex(T1* start, T1* end, T1& minValue, ossim_int32& offsetFromStart) { offsetFromStart =0; ossim_int32 currentOffset = 0; minValue = *start; while(start < end) { if(*start < minValue) { minValue = *start; offsetFromStart = currentOffset; } ++start; ++currentOffset; } } template void ossimVertexExtractor::getMaxAndIndex(T2* start, T2* end, T2& maxValue, ossim_int32& offsetFromStart) { offsetFromStart =0; ossim_int32 currentOffset = 0; maxValue = *start; while(start < end) { if(*start > maxValue) { maxValue = *start; offsetFromStart = currentOffset; } ++start; ++currentOffset; } } ossim-Miami-2.9.1/src/imaging/ossimVpfAnnotationCoverageInfo.cpp000066400000000000000000000131551352751253100247570ustar00rootroot00000000000000//************************************************************************* // Copyright (C) 2004 Intelligence Data Systems, Inc. All rights reserved. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************** // $Id: ossimVpfAnnotationCoverageInfo.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include #include #include #include #include using namespace std; bool ossimVpfAnnotationCoverageInfo::hasRenderableFeature()const { for(ossim_uint32 idx = 0; idx < theFeatureInfoArray.size();++idx) { if(theFeatureInfoArray[idx]->getEnabledFlag()) { return true; } } return false; } void ossimVpfAnnotationCoverageInfo::getEnabledFeatures(std::vector& result) { for(ossim_uint32 idx = 0; idx < theFeatureInfoArray.size();++idx) { if(theFeatureInfoArray[idx]->getEnabledFlag()) { result.push_back(theFeatureInfoArray[idx]); } } } void ossimVpfAnnotationCoverageInfo::getAllFeatures(std::vector& result) { for(ossim_uint32 idx = 0; idx < theFeatureInfoArray.size();++idx) { result.push_back(theFeatureInfoArray[idx]); } } ossimIrect ossimVpfAnnotationCoverageInfo::getBoundingProjectedRect()const { ossimIrect result; result.makeNan(); for(ossim_uint32 idx = 0; idx < theFeatureInfoArray.size();++idx) { ossimIrect tempRect = theFeatureInfoArray[idx]->getBoundingProjectedRect(); if(!tempRect.hasNans()) { if(result.hasNans()) { result = tempRect; } else { result = result.combine(tempRect); } } } return result; } void ossimVpfAnnotationCoverageInfo::transform(ossimImageGeometry* geom) { for(ossim_uint32 idx = 0; idx < theFeatureInfoArray.size();++idx) { theFeatureInfoArray[idx]->transform(geom); } } void ossimVpfAnnotationCoverageInfo::buildCoverage() { buildCoverage( "" ); } void ossimVpfAnnotationCoverageInfo::buildCoverage(const ossimString& feature) { deleteAllFeatures(); if(theLibrary) { ossimVpfCoverage coverage; if(theLibrary->getCoverage(theName, coverage)) { ossimVpfFeatureClassSchema schema; if(coverage.openFeatureClassSchema(schema)) { std::vector featureClassArray; schema.getFeatureClasses(featureClassArray); schema.closeTable(); for(ossim_uint32 idx = 0; idx < featureClassArray.size(); ++idx) { ossimString s1 = feature; ossimString s2 = featureClassArray[idx]; s1.downcase(); s2.downcase(); if (! feature.length() || (s1 == s2) ) { ossimVpfAnnotationFeatureInfo* featureInfo = new ossimVpfAnnotationFeatureInfo; featureInfo->setName(featureClassArray[idx]); featureInfo->setCoverage(coverage); theFeatureInfoArray.push_back(featureInfo); featureInfo->buildFeature(); } } } } } } void ossimVpfAnnotationCoverageInfo::drawAnnotations(ossimRgbImage* tile) { for(ossim_uint32 idx = 0; idx < theFeatureInfoArray.size();++idx) { if(theFeatureInfoArray[idx]->getEnabledFlag()) { theFeatureInfoArray[idx]->drawAnnotations(tile); } } } void ossimVpfAnnotationCoverageInfo::deleteAllFeatures() { for(ossim_uint32 idx = 0; idx < theFeatureInfoArray.size();++idx) { theFeatureInfoArray[idx]; } theFeatureInfoArray.clear(); } bool ossimVpfAnnotationCoverageInfo::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "name", theName, true); for(ossim_uint32 idx = 0; idx < theFeatureInfoArray.size(); ++idx) { theFeatureInfoArray[idx]->saveState(kwl, (ossimString(prefix) + "feature" + ossimString::toString(idx) + ".").c_str()); } return true; } bool ossimVpfAnnotationCoverageInfo::loadState(const ossimKeywordlist& kwl, const char* prefix) { deleteAllFeatures(); if(!theLibrary) { return false; } theName = kwl.find(prefix, "name"); ossimVpfCoverage coverage; if(theLibrary->getCoverage(theName, coverage)) { ossimString regExpression = ossimString("^(") + ossimString(prefix) + "feature[0-9]+.)"; vector keys = kwl.getSubstringKeyList( regExpression ); std::vector theNumberList(keys.size()); int offset = (int)(ossimString(prefix)+"feature").size(); int idx = 0; for(idx = 0; idx < (int)theNumberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); theNumberList[idx] = numberStr.toInt(); } std::sort(theNumberList.begin(), theNumberList.end()); for(idx=0;idx < (int)keys.size();++idx) { ossimString newPrefix = ossimString(prefix); newPrefix += ossimString("feature"); newPrefix += ossimString::toString(theNumberList[idx]); newPrefix += ossimString("."); ossimVpfAnnotationFeatureInfo* featureInfo = new ossimVpfAnnotationFeatureInfo; featureInfo->setCoverage(coverage); theFeatureInfoArray.push_back(featureInfo); if(!featureInfo->loadState(kwl, newPrefix)) { return false; } } } else { return false; } return true; } ossim-Miami-2.9.1/src/imaging/ossimVpfAnnotationFeatureInfo.cpp000066400000000000000000001317711352751253100246240ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimVpfAnnotationFeatureInfo:debug"); RTTI_DEF1(ossimVpfAnnotationFeatureInfo, "ossimVpfAnnotationFeatureInfo", ossimObject); ossimVpfAnnotationFeatureInfo::ossimVpfAnnotationFeatureInfo(const ossimString& featureName, const ossimRgbVector& penColor, const ossimRgbVector& brushColor, const ossimDpt& pointRadius, int thickness, bool enabledFlag) :theName(featureName), thePenColor(penColor), theBrushColor(brushColor), thePointRadius(pointRadius), theThickness(thickness), theFillEnabledFlag(false), theEnabledFlag(enabledFlag), theFeatureType(ossimVpfAnnotationFeatureType_UNKNOWN), theFontInformation(), theAnnotationArray(0) { ossimFont* font = ossimFontFactoryRegistry::instance()->getDefaultFont(); if(font) { std::vector fontInfoArray; font->getFontInformation(fontInfoArray); if(fontInfoArray.size()) { theFontInformation = fontInfoArray[0]; } } } ossimVpfAnnotationFeatureInfo::~ossimVpfAnnotationFeatureInfo() { deleteAllObjects(); } void ossimVpfAnnotationFeatureInfo::transform(ossimImageGeometry* proj) { if(theEnabledFlag) { for(int idx = 0; idx < (int)theAnnotationArray.size();++idx) { if(theAnnotationArray[idx].valid()) { theAnnotationArray[idx]->transform(proj); theAnnotationArray[idx]->computeBoundingRect(); } } } } ossimIrect ossimVpfAnnotationFeatureInfo::getBoundingProjectedRect()const { ossimIrect result; result.makeNan(); if(theEnabledFlag) { for(int idx = 0; idx < (int)theAnnotationArray.size();++idx) { if(theAnnotationArray[idx].valid()) { ossimIrect tempRect = theAnnotationArray[idx]->getBoundingRect(); if(!tempRect.hasNans()) { if(result.hasNans()) { result = tempRect; } else { result = result.combine(tempRect); } } } } } return result; } void ossimVpfAnnotationFeatureInfo::setEnabledFlag(bool flag) { if(!flag && theEnabledFlag) { deleteAllObjects(); } else if(flag&&(!theEnabledFlag)) { theEnabledFlag = flag; buildFeature(); } theEnabledFlag = flag; } void ossimVpfAnnotationFeatureInfo::buildFeature() { deleteAllObjects(); ossimVpfFeatureClassSchemaNode node; ossimVpfFeatureClassSchema schema; theCoverage.openFeatureClassSchema(schema); if(schema.getFeatureClassNode(theName, node)) { if(node.thePrimitiveTable.contains("edg")) { theFeatureType = ossimVpfAnnotationFeatureType_LINE; if(theEnabledFlag) { buildEdgFeature(node.theTable.trim(), node.theTableKey.trim(), node.thePrimitiveTable.trim(), node.thePrimitiveTableKey.trim()); } } else if(node.thePrimitiveTable.contains("txt")) { theFeatureType = ossimVpfAnnotationFeatureType_TEXT; if(theEnabledFlag) { buildTxtFeature(node.theTable.trim(), node.theTableKey.trim(), node.thePrimitiveTable.trim(), node.thePrimitiveTableKey.trim()); } } else if(node.thePrimitiveTable.contains("fac")) { theFeatureType = ossimVpfAnnotationFeatureType_POLYGON; if(theEnabledFlag) { buildFaceFeature(node.theTable.trim(), node.theTableKey.trim(), node.thePrimitiveTable.trim(), node.thePrimitiveTableKey.trim()); } } else if(node.thePrimitiveTable.contains("cnd")) { theFeatureType = ossimVpfAnnotationFeatureType_POINT; if(theEnabledFlag) { buildPointFeature("cnd", node.theTable.trim(), node.theTableKey.trim(), node.thePrimitiveTable.trim(), node.thePrimitiveTableKey.trim()); } } else if(node.thePrimitiveTable.contains("end")) { theFeatureType = ossimVpfAnnotationFeatureType_POINT; if(theEnabledFlag) { buildPointFeature("end", node.theTable.trim(), node.theTableKey.trim(), node.thePrimitiveTable.trim(), node.thePrimitiveTableKey.trim()); } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Primitive \""<draw(*tile); } } } bool ossimVpfAnnotationFeatureInfo::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "name", theName.c_str(), true); kwl.add(prefix, "description", theDescription.c_str(), true); ossimString penColor = (ossimString::toString((int)thePenColor.getR())+ " " + ossimString::toString((int)thePenColor.getG())+ " " + ossimString::toString((int)thePenColor.getB())); ossimString brushColor = (ossimString::toString((int)theBrushColor.getR())+ " " + ossimString::toString((int)theBrushColor.getG())+ " " + ossimString::toString((int)theBrushColor.getB())); kwl.add(prefix, "pen_color", penColor, true); kwl.add(prefix, "brush_color", brushColor, true); if(theFeatureType == ossimVpfAnnotationFeatureType_POINT) { kwl.add(prefix, "point_radius", ossimString::toString(thePointRadius.x) + " " + ossimString::toString(thePointRadius.y), true); kwl.add(prefix, "fill_enabled", theFillEnabledFlag, true); } else if(theFeatureType == ossimVpfAnnotationFeatureType_LINE) { kwl.add(prefix, "thickness", theThickness, true); } else if(theFeatureType == ossimVpfAnnotationFeatureType_POLYGON) { kwl.add(prefix, "fill_enabled", theFillEnabledFlag, true); kwl.add(prefix, "thickness", theThickness, true); } else if(theFeatureType == ossimVpfAnnotationFeatureType_TEXT) { theFontInformation.saveState(kwl, (ossimString(prefix)+"font.").c_str()); } kwl.add(prefix, "enabled", theEnabledFlag, true); kwl.add(prefix, "feature_type", getFeatureTypeAsString(), true); return true; } bool ossimVpfAnnotationFeatureInfo::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* name = kwl.find(prefix, "name"); const char* description = kwl.find(prefix, "description"); const char* enabled = kwl.find(prefix, "enabled"); const char* fillEnabled = kwl.find(prefix, "fill_enabled"); const char* thickness = kwl.find(prefix, "thickness"); const char* pointRadius = kwl.find(prefix, "point_radius"); const char* brushColor = kwl.find(prefix, "brush_color"); const char* penColor = kwl.find(prefix, "pen_color"); theFontInformation.loadState(kwl, (ossimString(prefix)+"font.").c_str()); if(name) { if(theName != name) { deleteAllObjects(); } theName = name; } if(description) { theDescription = description; } if(enabled) { theEnabledFlag = ossimString(enabled).toBool(); if(!theEnabledFlag) { deleteAllObjects(); } } if(fillEnabled) { theFillEnabledFlag = ossimString(fillEnabled).toBool(); } if(thickness) { theThickness = ossimString(thickness).toInt(); } if(pointRadius) { stringstream ptRadiusStream(pointRadius); ptRadiusStream >> thePointRadius.x >> thePointRadius.y; } if(brushColor) { int r, g, b; stringstream colorStream(brushColor); colorStream >> r >> g >> b; theBrushColor.setR((ossim_uint8)r); theBrushColor.setG((ossim_uint8)g); theBrushColor.setB((ossim_uint8)b); } if(penColor) { int r, g, b; stringstream colorStream(penColor); colorStream >> r >> g >> b; thePenColor.setR((ossim_uint8)r); thePenColor.setG((ossim_uint8)g); thePenColor.setB((ossim_uint8)b); } if(theEnabledFlag&&(theAnnotationArray.size() < 1)) { buildFeature(); } else { setDrawingFeaturesToAnnotation(); } return true; } ossimString ossimVpfAnnotationFeatureInfo::getFeatureTypeAsString()const { switch(theFeatureType) { case ossimVpfAnnotationFeatureType_POINT: { return "point"; } case ossimVpfAnnotationFeatureType_LINE: { return "line"; } case ossimVpfAnnotationFeatureType_POLYGON: { return "polygon"; } case ossimVpfAnnotationFeatureType_TEXT: { return "text"; } default: break; } return "unknown"; } ossimVpfAnnotationFeatureInfo::ossimVpfAnnotationFeatureType ossimVpfAnnotationFeatureInfo::getFeatureTypeFromString(const ossimString& featureType)const { ossimString downCased = featureType; downCased = downCased.downcase(); if(downCased.contains("point")) { return ossimVpfAnnotationFeatureType_POINT; } else if(downCased.contains("line")) { return ossimVpfAnnotationFeatureType_LINE; } else if(downCased.contains("polygon")) { return ossimVpfAnnotationFeatureType_POLYGON; } else if(downCased.contains("text")) { return ossimVpfAnnotationFeatureType_TEXT; } return ossimVpfAnnotationFeatureType_UNKNOWN; } void ossimVpfAnnotationFeatureInfo::deleteAllObjects() { theAnnotationArray.clear(); } void ossimVpfAnnotationFeatureInfo::setDrawingFeaturesToAnnotation() { switch(theFeatureType) { case ossimVpfAnnotationFeatureType_POINT: { ossimGeoAnnotationMultiEllipseObject* annotation = 0; for(int idx = 0; idx < (int)theAnnotationArray.size();++idx) { annotation = (ossimGeoAnnotationMultiEllipseObject*)theAnnotationArray[idx].get(); annotation->setColor(thePenColor.getR(), thePenColor.getG(), thePenColor.getB()); annotation->setThickness(theThickness); annotation->setFillFlag(theFillEnabledFlag); annotation->setWidthHeight(thePointRadius); } break; } case ossimVpfAnnotationFeatureType_TEXT: { ossimGeoAnnotationFontObject* annotation = 0; ossimRefPtr font = ossimFontFactoryRegistry::instance()->createFont(theFontInformation); for(int idx = 0; idx < (int)theAnnotationArray.size();++idx) { annotation = (ossimGeoAnnotationFontObject*)theAnnotationArray[idx].get(); annotation->setColor(thePenColor.getR(), thePenColor.getG(), thePenColor.getB()); annotation->setThickness(theThickness); if(font.valid()) { annotation->setFont((ossimFont*)font->dup()); } annotation->setPointSize(theFontInformation.thePointSize); annotation->setScale(theFontInformation.theScale); annotation->setShear(theFontInformation.theShear); annotation->setRotation(theFontInformation.theRotation); } break; } case ossimVpfAnnotationFeatureType_LINE: { ossimGeoAnnotationMultiPolyLineObject* annotation = 0; for(int idx = 0; idx < (int)theAnnotationArray.size();++idx) { annotation = (ossimGeoAnnotationMultiPolyLineObject*)theAnnotationArray[idx].get(); annotation->setColor(thePenColor.getR(), thePenColor.getG(), thePenColor.getB()); annotation->setThickness(theThickness); } break; } case ossimVpfAnnotationFeatureType_POLYGON: { ossimGeoAnnotationMultiPolyObject* annotation = 0; for(int idx = 0; idx < (int)theAnnotationArray.size();++idx) { annotation = (ossimGeoAnnotationMultiPolyObject*)theAnnotationArray[idx].get(); annotation->setColor(thePenColor.getR(), thePenColor.getG(), thePenColor.getB()); annotation->setThickness(theThickness); annotation->setFillFlag(theFillEnabledFlag); } break; } default: { break; } } } void ossimVpfAnnotationFeatureInfo::buildTxtFeature(const ossimFilename& tableName, const ossimString& tableKey, const ossimFilename& /* primitiveName */, const ossimString& /* primitiveKey */) { ossimFilename tableFileName = theCoverage.getPath().dirCat(tableName); ossimFilename primitiveTableName; ossimVpfTable table; ossimVpfTable primitiveTable; if(table.openTable(tableFileName)) { table.reset(); vector columnValues = table.getColumnValues(tableKey.trim()); primitiveTableName = theCoverage.getPath().dirCat("txt"); vector tileIds; ossim_int32 stringValuePosition = 0; ossim_int32 shapeLinePosition = 0; bool isTiled = false; if(table.getColumnPosition("tile_id") >= 0) { tileIds = table.getColumnValues("tile_id"); isTiled = true; } if(!isTiled) { primitiveTableName = theCoverage.getPath().dirCat("txt"); if(!primitiveTable.openTable(primitiveTableName)) { return; } stringValuePosition = primitiveTable.getColumnPosition("string"); shapeLinePosition = primitiveTable.getColumnPosition("shape_line"); } ossim_int32 tileId = -1; for(ossim_uint32 idx = 0; idx < columnValues.size();++idx) { if(isTiled) { if(tileId != tileIds[idx].toInt()) { tileId = tileIds[idx].toInt(); ossimFilename filename = theCoverage.getLibrary()->getTileName(tileIds[idx].toInt()); if(theCoverage.getPath().dirCat(filename).dirCat("txt").exists()) { primitiveTableName = theCoverage.getPath().dirCat(filename).dirCat("txt"); } else if(theCoverage.getPath().dirCat(filename.downcase()).dirCat("txt").exists()) { primitiveTableName = theCoverage.getPath().dirCat(filename.downcase()).dirCat("txt"); } if(!primitiveTable.openTable(primitiveTableName)) { return; } stringValuePosition = primitiveTable.getColumnPosition("string"); shapeLinePosition = primitiveTable.getColumnPosition("shape_line"); } } row_type row = read_row( columnValues[idx].toInt(), *primitiveTable.getVpfTableData()); ossim_int32 count = 0; ossimDpt* ptArray = getXy(*primitiveTable.getVpfTableData(), row, shapeLinePosition, &count); ossimDpt midPoint; if(ptArray) { midPoint = *ptArray; delete [] ptArray; } ossimString stringValue = primitiveTable.getColumnValueAsString(row, stringValuePosition); free_row(row, *primitiveTable.getVpfTableData()); if(!midPoint.hasNans()) { ossimGpt centerPoint(midPoint.lat, midPoint.lon, ossim::nan()); ossimFont* font = ossimFontFactoryRegistry::instance()->createFont(theFontInformation); ossimGeoAnnotationFontObject* annotation = new ossimGeoAnnotationFontObject(centerPoint, stringValue); annotation->setColor(thePenColor.getR(), thePenColor.getG(), thePenColor.getB()); annotation->setThickness(theThickness); annotation->setFont(font); annotation->setPointSize(theFontInformation.thePointSize); annotation->setScale(theFontInformation.theScale); annotation->setShear(theFontInformation.theShear); annotation->setRotation(theFontInformation.theRotation); theAnnotationArray.push_back(annotation); } } } } void ossimVpfAnnotationFeatureInfo::buildEdgFeature(const ossimFilename& tableName, const ossimString& tableKey, const ossimFilename& /* primitiveName */, const ossimString& /* primitiveKey */) { ossimFilename tableFileName = theCoverage.getPath().dirCat(tableName); ossimFilename primitiveTableName; ossimVpfTable table; ossimVpfTable primitiveTable; std::vector polyLineArray; if(table.openTable(tableFileName)) { vector columnValues = table.getColumnValues(tableKey.trim()); vector tileIds; bool isTiled = false; if(table.getColumnPosition("tile_id") >= 0) { tileIds = table.getColumnValues("tile_id"); isTiled = true; } ossim_int32 coordinateValuePosition = 0; if(!isTiled) { primitiveTableName = theCoverage.getPath().dirCat("edg"); if(!primitiveTable.openTable(primitiveTableName)) { return; } coordinateValuePosition = primitiveTable.getColumnPosition("coordinates"); } ossim_int32 tileId = -1; for(ossim_uint32 idx = 0; idx < columnValues.size();++idx) { if(isTiled) { if(tileId != tileIds[idx].toInt()) { tileId = tileIds[idx].toInt(); ossimFilename filename = theCoverage.getLibrary()->getTileName(tileIds[idx].toInt()); if(theCoverage.getPath().dirCat(filename).dirCat("edg").exists()) { primitiveTableName = theCoverage.getPath().dirCat(filename).dirCat("edg"); } else if(theCoverage.getPath().dirCat(filename.downcase()).dirCat("edg").exists()) { primitiveTableName = theCoverage.getPath().dirCat(filename.downcase()).dirCat("edg"); } if(!primitiveTable.openTable(primitiveTableName)) { return; } coordinateValuePosition = primitiveTable.getColumnPosition("coordinates"); } } ossimPolyLine polyLine; readEdge(polyLine, columnValues[idx].toInt(), coordinateValuePosition, primitiveTable); readAttributes(polyLine, table, idx + 1); // third parm is one-based row polyLineArray.push_back(polyLine); } } ossimGeoAnnotationMultiPolyLineObject* annotation = new ossimGeoAnnotationMultiPolyLineObject(polyLineArray); annotation->setColor(thePenColor.getR(), thePenColor.getG(), thePenColor.getB()); annotation->setThickness(theThickness); theAnnotationArray.push_back(annotation); } void ossimVpfAnnotationFeatureInfo::readAttributes(ossimPolyLine& polyLine, ossimVpfTable& table, int row) { int numCols = table.getNumberOfColumns(); for (int col = 0; col < numCols; col ++) { polyLine.addAttribute( table.getColumnValueAsString( row, col )); } } void ossimVpfAnnotationFeatureInfo::buildPointFeature(const ossimString& primitiveName, const ossimFilename& tableName, const ossimString& tableKey, const ossimFilename& /* primitive */, const ossimString& /* primitiveKey */) { ossimFilename tableFileName = theCoverage.getPath().dirCat(tableName); ossimFilename primitiveTableName; ossimVpfTable table; ossimVpfTable primitiveTable; std::vector centerPointArray; if(table.openTable(tableFileName)) { vector columnValues = table.getColumnValues(tableKey.trim()); vector tileIds; bool isTiled = false; if(table.getColumnPosition("tile_id") >= 0) { tileIds = table.getColumnValues("tile_id"); isTiled = true; } ossim_int32 coordinateValuePosition = 0; if(!isTiled) { primitiveTableName = theCoverage.getPath().dirCat(primitiveName); if(!primitiveTable.openTable(primitiveTableName)) { return; } coordinateValuePosition = primitiveTable.getColumnPosition("coordinate"); } ossim_int32 tileId = -1; for(ossim_uint32 idx = 0; idx < columnValues.size();++idx) { if(isTiled) { if(tileId != tileIds[idx].toInt()) { tileId = tileIds[idx].toInt(); ossimFilename filename = theCoverage.getLibrary()->getTileName(tileIds[idx].toInt()); if(theCoverage.getPath().dirCat(filename).dirCat(primitiveName).exists()) { primitiveTableName = theCoverage.getPath().dirCat(filename).dirCat(primitiveName); } else if(theCoverage.getPath().dirCat(filename.downcase()).dirCat(primitiveName).exists()) { primitiveTableName = theCoverage.getPath().dirCat(filename.downcase()).dirCat(primitiveName); } if(!primitiveTable.openTable(primitiveTableName)) { return; } coordinateValuePosition = primitiveTable.getColumnPosition("coordinate"); } } row_type row = read_row( columnValues[idx].toInt(), *primitiveTable.getVpfTableData()); ossim_int32 count = 0; ossimDpt* ptArray = getXy(*primitiveTable.getVpfTableData(), row, coordinateValuePosition, &count); if(ptArray) { for(int i = 0; i < count; ++i) { if((fabs(ptArray[i].x) <= 180.0)&& (fabs(ptArray[i].y) <= 90.0)) { centerPointArray.push_back(ossimGpt(ptArray[i].lat, ptArray[i].lon, ossim::nan())); } } delete [] ptArray; } free_row(row, *primitiveTable.getVpfTableData()); } } ossimGeoAnnotationMultiEllipseObject* annotation = new ossimGeoAnnotationMultiEllipseObject(centerPointArray, ossimDpt(2,2)); annotation->setColor(thePenColor.getR(), thePenColor.getG(), thePenColor.getB()); annotation->setThickness(theThickness); annotation->setFillFlag(theFillEnabledFlag); annotation->setWidthHeight(thePointRadius); theAnnotationArray.push_back(annotation); } int myFaceCount = 0; void ossimVpfAnnotationFeatureInfo::buildFaceFeature(const ossimFilename& tableName, const ossimString& tableKey, // face_id const ossimFilename& /* primitive */, //face const ossimString& /* primitiveKey */) // id { ossimFilename tableFileName = theCoverage.getPath().dirCat(tableName); ossimFilename primitiveTableName; ossimFilename rngTableName; ossimFilename edgTableName; ossimVpfTable table; ossimVpfTable primitiveTable; ossimVpfTable rngTable; ossimVpfTable edgTable; vector thePolyList; if(table.openTable(tableFileName)) { vector columnValues = table.getColumnValues(tableKey.trim()); // fac_id vector tileIds; bool isTiled = false; if(table.getColumnPosition("tile_id") >= 0) { tileIds = table.getColumnValues("tile_id"); isTiled = true; } // ossim_int32 coordinateValuePosition = 0; ossim_int32 startEdgePosition = 0; ossim_int32 rngPtrPosition = 0; if(!isTiled) { primitiveTableName = theCoverage.getPath().dirCat("fac"); rngTableName = theCoverage.getPath().dirCat("rng"); edgTableName = theCoverage.getPath().dirCat("edg"); if(!primitiveTable.openTable(primitiveTableName)|| !rngTable.openTable(rngTableName)|| !edgTable.openTable(edgTableName)) { return; } // coordinateValuePosition = edgTable.getColumnPosition("coordinates"); startEdgePosition = rngTable.getColumnPosition("start_edge"); rngPtrPosition = primitiveTable.getColumnPosition("ring_ptr"); } // else will get for each face in loop below ossim_int32 tileId = -1; for(ossim_uint32 idx = 0; idx < columnValues.size();++idx) // for each face feature { if(isTiled) // then get table names because we didn't get them above { if((tileId != tileIds[idx].toInt())|| (tileId < 0)) { tileId = tileIds[idx].toInt(); ossimFilename filename = theCoverage.getLibrary()->getTileName(tileIds[idx].toInt()); if(theCoverage.getPath().dirCat(filename).dirCat("fac").exists()) { primitiveTableName = theCoverage.getPath().dirCat(filename).dirCat("fac"); rngTableName = theCoverage.getPath().dirCat(filename).dirCat("rng"); edgTableName = theCoverage.getPath().dirCat(filename).dirCat("edg"); } else if(theCoverage.getPath().dirCat(filename.downcase()).dirCat("fac").exists()) { primitiveTableName = theCoverage.getPath().dirCat(filename.downcase()).dirCat("fac"); rngTableName = theCoverage.getPath().dirCat(filename.downcase()).dirCat("rng"); edgTableName = theCoverage.getPath().dirCat(filename.downcase()).dirCat("edg"); } if(!primitiveTable.openTable(primitiveTableName)|| !rngTable.openTable(rngTableName)|| !edgTable.openTable(edgTableName)) { return; } // coordinateValuePosition = edgTable.getColumnPosition("coordinates"); startEdgePosition = rngTable.getColumnPosition("start_edge"); rngPtrPosition = primitiveTable.getColumnPosition("ring_ptr"); } } // if(isTiled) // get the outer ring id for this face int thisFaceId = columnValues[idx].toInt(); int rngId = -1; if (thisFaceId <= primitiveTable.getNumberOfRows()) rngId = readRngId(thisFaceId, rngPtrPosition, primitiveTable); // face table else if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "not getting face " << thisFaceId << " from tile " << tileId << " " << primitiveTableName << " bacause it has only " << primitiveTable.getNumberOfRows() << " rows" << endl; } if(rngId > 0) { int startEdge = readStartEdgeId(rngId, startEdgePosition, rngTable); int outerStartEdge = startEdge; if(startEdge > 0 ) { ossimGeoPolygon polygon; myFaceCount ++; int ringTableFaceIdColumn = rngTable.getColumnPosition("face_id"); int ringFaceId = readTableCellAsInt(rngId, ringTableFaceIdColumn, rngTable); if (thisFaceId != ringFaceId) { // as of Mon Dec 20 2004, this has not been observed in vmap0 or vmap1 if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting face " << thisFaceId << " from " << tableFileName << " because it's ring (" << rngId << ") has face " << ringFaceId << " and startEdgeId " << startEdge << endl; } } else { readGeoPolygon( polygon, thisFaceId, startEdge, edgTable ); // get the inner rings (holes) int faceIdPosition = rngTable.getColumnPosition("face_id"); int innerRingOffset = 1; int rowFaceId = -1; if (rngId + innerRingOffset <= rngTable.getNumberOfRows()) rowFaceId = rngTable.getColumnValueAsString( rngId + innerRingOffset, faceIdPosition ).toInt(); while (rowFaceId == thisFaceId && rngId + innerRingOffset <= rngTable.getNumberOfRows()) { // while there are more inner rings startEdge = readStartEdgeId(rngId + innerRingOffset, startEdgePosition, rngTable); if (startEdge == outerStartEdge) { // as of Mon Dec 20 2004, this has not been observed in vmap0 or vmap1 if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting hole in face " << thisFaceId << " because inner ring " << rngId + innerRingOffset << " touches outer ring " << rngId << endl; } innerRingOffset ++; rowFaceId = rngTable.getColumnValueAsString( rngId + innerRingOffset, faceIdPosition ).toInt(); continue; } if(startEdge > 0 ) { ossimGeoPolygon holePolygon; readGeoPolygon( holePolygon, thisFaceId, startEdge, edgTable ); if(holePolygon.size()) polygon.addHole( holePolygon ); } innerRingOffset ++; if (rngId + innerRingOffset <= rngTable.getNumberOfRows()) rowFaceId = rngTable.getColumnValueAsString( rngId + innerRingOffset, faceIdPosition ).toInt(); } readAttributes(polygon, table, idx + 1); // third parm is one-based row thePolyList.push_back(polygon); } } } } // each fac_id } ossimGeoAnnotationMultiPolyObject* annotation = new ossimGeoAnnotationMultiPolyObject(thePolyList); annotation->setColor(thePenColor.getR(), thePenColor.getG(), thePenColor.getB()); annotation->setThickness(theThickness); annotation->setFillFlag(theFillEnabledFlag); theAnnotationArray.push_back(annotation); } void ossimVpfAnnotationFeatureInfo::readAttributes(ossimGeoPolygon& polygon, ossimVpfTable& table, int row) { int numCols = table.getNumberOfColumns(); for (int col = 0; col < numCols; col ++) { ossimString s = table.getColumnValueAsString( row, col ); polygon.addAttribute( s ); } } /* GET_XY */ /*****************************************************************************/ ossimDpt *ossimVpfAnnotationFeatureInfo::getXy(vpf_table_type table, row_type row, ossim_int32 pos, ossim_int32 *count) { ossim_int32 i; ossimDpt *coord = 0; switch (table.header[pos].type) { case 'C': { coordinate_type temp, *ptr; ptr = (coordinate_type*)get_table_element(pos, row, table, &temp, count); coord = new ossimDpt[*count]; if ((*count == 1) && (ptr == (coordinate_type*)0)) { coord->x = (double)temp.x; coord->y = (double)temp.y; } else { for (i=0; i<*count; i++) { coord[i].x = (double)ptr[i].x; coord[i].y = (double)ptr[i].y; } } if (ptr) { free((char *)ptr); } break; } case 'Z': { tri_coordinate_type temp, *ptr; ptr = (tri_coordinate_type*)get_table_element (pos, row, table, &temp, count); coord = new ossimDpt[*count]; if ((*count == 1) && (ptr == (tri_coordinate_type*)0)) { coord->x = (double)temp.x; coord->y = (double)temp.y; } else { for (i=0; i<*count; i++) { coord[i].x = (double)ptr[i].x; coord[i].y = (double)ptr[i].y; } } if (ptr) { free ((char*)ptr); } break; } case 'B': { double_coordinate_type temp, *ptr; ptr = (double_coordinate_type*)get_table_element (pos, row, table, &temp, count); coord = new ossimDpt[*count]; if ((*count == 1) && (ptr == (double_coordinate_type*)0)) { coord->x = temp.x; coord->y = temp.y; } else { for (i=0; i<*count; i++) { coord[i].x = ptr[i].x; coord[i].y = ptr[i].y; } } if (ptr) { free ((char*)ptr); } break; } case 'Y': { double_tri_coordinate_type temp, *ptr; ptr = (double_tri_coordinate_type*)get_table_element (pos, row, table, &temp, count); coord = new ossimDpt[*count]; if ((*count == 1) && (ptr == (double_tri_coordinate_type*)0)) { coord->x = temp.x; coord->y = temp.y; } else { for (i=0; i<*count; i++) { coord[i].x = ptr[i].x; coord[i].y = ptr[i].y; } } if (ptr) { free((char*)ptr); } break; } default: break; } /* switch type */ return (coord); } int ossimVpfAnnotationFeatureInfo::readTableCellAsInt (int rowNumber, int colNumber, ossimVpfTable& table) { int result = -1; row_type row = read_row( rowNumber, *table.getVpfTableData()); result = table.getColumnValueAsString(row, colNumber).toInt(); free_row(row, *table.getVpfTableData()); return result; } int ossimVpfAnnotationFeatureInfo::readRngId(int rowNumber, int colNumber, ossimVpfTable& faceTable) { int idResult = -1; row_type row = read_row( rowNumber, *faceTable.getVpfTableData()); idResult = faceTable.getColumnValueAsString(row, colNumber).toInt(); free_row(row, *faceTable.getVpfTableData()); return idResult; } int ossimVpfAnnotationFeatureInfo::readStartEdgeId(int rowNumber, int colNumber, ossimVpfTable& rngTable) { int idResult = -1; row_type row = read_row( rowNumber, *rngTable.getVpfTableData()); idResult = rngTable.getColumnValueAsString(row, colNumber).toInt(); free_row(row, *rngTable.getVpfTableData()); return idResult; } int ossimVpfAnnotationFeatureInfo::getEdgeKeyId (vpf_table_type& table, row_type& row, int col) { id_triplet_type key; ossim_int32 keyCount; get_table_element( col, row, table, & key, & keyCount ); return key.id; } void ossimVpfAnnotationFeatureInfo::readGeoPolygon(ossimGeoPolygon& polygon, int faceId, int startEdgeId, ossimVpfTable& edgTable) { ossim_int32 coordinatesCol = edgTable.getColumnPosition( "coordinates" ); ossim_int32 startNodeCol = edgTable.getColumnPosition( "start_node" ); ossim_int32 endNodeCol = edgTable.getColumnPosition( "end_node" ); ossim_int32 rightEdgeCol = edgTable.getColumnPosition( "right_edge" ); ossim_int32 leftEdgeCol = edgTable.getColumnPosition( "left_edge" ); ossim_int32 rightFaceCol = edgTable.getColumnPosition( "right_face" ); ossim_int32 leftFaceCol = edgTable.getColumnPosition( "left_face" ); // collect edges vector < int > edges; int lastEdge = startEdgeId; edges.push_back( lastEdge ); row_type row = read_row( startEdgeId, *edgTable.getVpfTableData() ); int startNode = edgTable.getColumnValueAsString( row, startNodeCol ).toInt(); int endNode = edgTable.getColumnValueAsString( row, endNodeCol ).toInt(); if (startNode != endNode) { // there's more than one edge to this ring int rightFace = getEdgeKeyId( *edgTable.getVpfTableData(), row, rightFaceCol ); int leftFace = getEdgeKeyId( *edgTable.getVpfTableData(), row, leftFaceCol ); int rightEdge = getEdgeKeyId( *edgTable.getVpfTableData(), row, rightEdgeCol ); int leftEdge = getEdgeKeyId( *edgTable.getVpfTableData(), row, leftEdgeCol ); int nextEdge; int firstNode, lastNode; if (rightFace == leftFace) { if (rightEdge == leftEdge) { free_row(row, *edgTable.getVpfTableData()); // as of Mon Dec 20 2004, this has not been observed in vmap0 or vmap1 // cout << "rejecting floating line face " << faceId << " line " << __LINE__ << endl; return; } // this is a dangling start edge; find a non dangling edge to use as the start edge int dirRight = 1; int nextEdge = startEdgeId; int nextLeftFace = leftFace; int nextRightFace = rightFace; int mobiusLimit = 1000; while (nextLeftFace == nextRightFace) { if (-- mobiusLimit < 0) { free_row(row, *edgTable.getVpfTableData()); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting mobius face " << faceId << " line " << __LINE__ << endl; } return; } int thisEdge = nextEdge; if (dirRight) { nextEdge = getEdgeKeyId( *edgTable.getVpfTableData(), row, rightEdgeCol ); if (nextEdge == thisEdge) dirRight = 0; else if (nextEdge == startEdgeId) { free_row(row, *edgTable.getVpfTableData()); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting mobius face " << faceId << " line " << __LINE__ << endl; } return; } } else { nextEdge = getEdgeKeyId( *edgTable.getVpfTableData(), row, leftEdgeCol ); if (nextEdge == thisEdge) { free_row(row, *edgTable.getVpfTableData()); // as of Mon Dec 20 2004, this has not been observed in vmap0 or vmap1 // cout << "rejecting multi floating line face " << faceId << " line " << __LINE__ << endl; return; } else if (nextEdge == startEdgeId) { free_row(row, *edgTable.getVpfTableData()); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting mobius face " << faceId << " line " << __LINE__ << endl; } return; } } free_row(row, *edgTable.getVpfTableData()); row = read_row( nextEdge, *edgTable.getVpfTableData() ); nextRightFace = getEdgeKeyId( *edgTable.getVpfTableData(), row, rightFaceCol ); nextLeftFace = getEdgeKeyId( *edgTable.getVpfTableData(), row, leftFaceCol ); } startEdgeId = nextEdge; rightFace = nextRightFace; leftFace = nextLeftFace; free_row(row, *edgTable.getVpfTableData()); row = read_row( startEdgeId, *edgTable.getVpfTableData() ); startNode = edgTable.getColumnValueAsString( row, startNodeCol ).toInt(); endNode = edgTable.getColumnValueAsString( row, endNodeCol ).toInt(); } if (rightFace == faceId) { nextEdge = getEdgeKeyId( *edgTable.getVpfTableData(), row, rightEdgeCol ); firstNode = startNode; lastNode = endNode; } else if (leftFace == faceId) { nextEdge = getEdgeKeyId( *edgTable.getVpfTableData(), row, leftEdgeCol ); firstNode = endNode; lastNode = startNode; } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting face " << faceId << " line " << __LINE__ << endl; } return; } row_type nextRow; while (true) { nextRow = read_row( nextEdge, *edgTable.getVpfTableData() ); int nextLeftEdge = getEdgeKeyId( *edgTable.getVpfTableData(), nextRow, leftEdgeCol ); int nextRightEdge = getEdgeKeyId( *edgTable.getVpfTableData(), nextRow, rightEdgeCol ); int nextLeftFace = getEdgeKeyId( *edgTable.getVpfTableData(), nextRow, leftFaceCol ); int nextRightFace = getEdgeKeyId( *edgTable.getVpfTableData(), nextRow, rightFaceCol ); int nextStartNode = edgTable.getColumnValueAsString( nextRow, startNodeCol ).toInt(); int nextEndNode = edgTable.getColumnValueAsString( nextRow, endNodeCol ).toInt(); while (nextLeftFace == nextRightFace) { int lastEnd; if (rightFace == faceId) lastEnd = edgTable.getColumnValueAsString( row, endNodeCol ).toInt(); else lastEnd = edgTable.getColumnValueAsString( row, startNodeCol ).toInt(); if (lastEnd == nextStartNode) nextEdge = nextLeftEdge; else if (lastEnd == nextEndNode) nextEdge = nextRightEdge; else { // bad face if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting face " << faceId << " line " << __LINE__ << endl; } return; } if (lastEdge == nextEdge) { // bad face if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting face " << faceId << " line " << __LINE__ << endl; } return; } free_row(nextRow, *edgTable.getVpfTableData()); nextRow = read_row( nextEdge, *edgTable.getVpfTableData() ); nextLeftEdge = getEdgeKeyId( *edgTable.getVpfTableData(), nextRow, leftEdgeCol ); nextRightEdge = getEdgeKeyId( *edgTable.getVpfTableData(), nextRow, rightEdgeCol ); nextLeftFace = getEdgeKeyId( *edgTable.getVpfTableData(), nextRow, leftFaceCol ); nextRightFace = getEdgeKeyId( *edgTable.getVpfTableData(), nextRow, rightFaceCol ); nextStartNode = edgTable.getColumnValueAsString( nextRow, startNodeCol ).toInt(); nextEndNode = edgTable.getColumnValueAsString( nextRow, endNodeCol ).toInt(); } lastEdge = nextEdge; edges.push_back( lastEdge ); { int lastEnd; if (nextRightFace == faceId) { if (lastNode != nextStartNode) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting face " << faceId << " line " << __LINE__ << endl; } return; } lastEnd = nextEndNode; } else if (nextLeftFace == faceId) { if (lastNode != nextEndNode) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting face " << faceId << " line " << __LINE__ << endl; } return; } lastEnd = nextStartNode; } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "rejecting face " << faceId << " line " << __LINE__ << endl; } return; } if (lastEnd == firstNode) break; } free_row(row, *edgTable.getVpfTableData()); row = nextRow; startNode = nextStartNode; endNode = nextEndNode; rightFace = nextRightFace; leftFace = nextLeftFace; if (rightFace == faceId) { nextEdge = nextRightEdge; lastNode = endNode; } else { nextEdge = nextLeftEdge; lastNode = startNode; } } free_row(nextRow, *edgTable.getVpfTableData()); nextRow = 0; } for (vector< int >::iterator i = edges.begin(); i != edges.end(); i++) { ossim_int32 count = 0; free_row(row, *edgTable.getVpfTableData()); row = read_row( *i, *edgTable.getVpfTableData() ); ossimDpt* ptArray = getXy(*edgTable.getVpfTableData(), row, coordinatesCol, &count); if(ptArray) { int rightFace = getEdgeKeyId( *edgTable.getVpfTableData(), row, rightFaceCol ); if (rightFace == faceId) { for(int p = 0; p < count; ++p) { if((fabs(ptArray[p].x) <= 180.0)&& (fabs(ptArray[p].y) <= 90.0)) { polygon.addPoint(ptArray[p].y, ptArray[p].x); } } } else { for(int p = count - 1; p >= 0; --p) { if((fabs(ptArray[p].x) <= 180.0)&& (fabs(ptArray[p].y) <= 90.0)) { polygon.addPoint(ptArray[p].y, ptArray[p].x); } } } delete [] ptArray; } } free_row(row, *edgTable.getVpfTableData()); } void ossimVpfAnnotationFeatureInfo::readEdge(ossimPolyLine& polyLine, int rowNumber, int colPosition, ossimVpfTable& edgeTable) { polyLine.clear(); row_type row = read_row( rowNumber, *edgeTable.getVpfTableData()); ossim_int32 count = 0; ossimDpt* ptArray = getXy(*edgeTable.getVpfTableData(), row, colPosition, &count); if(ptArray) { for(int i = 0; i < count; ++i) { if((fabs(ptArray[i].x) <= 180.0)&& (fabs(ptArray[i].y) <= 90.0)) { polyLine.addPoint(ossimDpt(ptArray[i].x, ptArray[i].y)); } } delete [] ptArray; } free_row(row, *edgeTable.getVpfTableData()); } ossim-Miami-2.9.1/src/imaging/ossimVpfAnnotationLibraryInfo.cpp000066400000000000000000000157101352751253100246270ustar00rootroot00000000000000//************************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************** // $Id: ossimVpfAnnotationLibraryInfo.cpp 15836 2009-10-30 12:29:09Z dburken $ #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimVpfAnnotationLibraryInfo:debug"); ossimVpfAnnotationLibraryInfo::ossimVpfAnnotationLibraryInfo(const ossimString& libraryName, bool enabledFlag) : theName(libraryName), theEnabledFlag(enabledFlag), theDatabase(NULL) { } ossimVpfAnnotationLibraryInfo::~ossimVpfAnnotationLibraryInfo() { deleteAllCoverage(); } bool ossimVpfAnnotationLibraryInfo::getEnabledFlag()const { return theEnabledFlag; } void ossimVpfAnnotationLibraryInfo::setEnabledFlag(bool flag) { theEnabledFlag = flag; } const ossimString& ossimVpfAnnotationLibraryInfo::getName()const { return theName; } void ossimVpfAnnotationLibraryInfo::setName(const ossimString& libraryName) { theName = libraryName; } void ossimVpfAnnotationLibraryInfo::setDatabase(ossimVpfDatabase* database) { theDatabase = database; } ossimVpfDatabase* ossimVpfAnnotationLibraryInfo::getDatabase() { return theDatabase; } ossimIrect ossimVpfAnnotationLibraryInfo::getBoundingProjectedRect()const { ossimIrect result; result.makeNan(); for(ossim_uint32 idx = 0; idx < theCoverageLayerList.size(); ++idx) { ossimIrect tempRect = theCoverageLayerList[idx]->getBoundingProjectedRect(); if(!tempRect.hasNans()) { if(result.hasNans()) { result = tempRect; } else { result = result.combine(tempRect); } } } return result; } void ossimVpfAnnotationLibraryInfo::getAllFeatures(std::vector& features) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationLibraryInfo::getAllFeatures DEBUG: entered..." << std::endl; } for(ossim_uint32 idx = 0; idx < theCoverageLayerList.size(); ++idx) { theCoverageLayerList[idx]->getAllFeatures(features); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationLibraryInfo::getAllFeatures DEBUG: leaving..." << std::endl; } } void ossimVpfAnnotationLibraryInfo::transform(ossimImageGeometry* geom) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationLibraryInfo::transform DEBUG: entered..." << std::endl; } for(ossim_uint32 idx = 0; idx < theCoverageLayerList.size(); ++idx) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "transforming coverage = " << theCoverageLayerList[idx]->getName() << std::endl; } theCoverageLayerList[idx]->transform(geom); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationLibraryInfo::transform DEBUG: leaving..." << std::endl; } } void ossimVpfAnnotationLibraryInfo::buildLibrary() { buildLibrary( "", ""); } void ossimVpfAnnotationLibraryInfo::buildLibrary(const ossimString& coverageName, const ossimString& feature) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationLibraryInfo::buildLibrary DEBUG: entered..." << std::endl; } deleteAllCoverage(); if(!theDatabase) { return; } ossimVpfLibrary* library = theDatabase->getLibrary(theName); if(library) { std::vector coverageNames; library->getCoverageNames(coverageNames); for(ossim_uint32 idx = 0; idx < coverageNames.size(); ++idx) { ossimString s1 = coverageName; ossimString s2 = coverageNames[idx]; s1.downcase(); s2.downcase(); if ( ! coverageName.length() || (s1 == s2) ) { ossimVpfAnnotationCoverageInfo* coverageInfo = new ossimVpfAnnotationCoverageInfo; coverageInfo->setName(coverageNames[idx]); coverageInfo->setLibrary(library); theCoverageLayerList.push_back(coverageInfo); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "coverage name = " << coverageNames[idx] << std::endl; } coverageInfo->buildCoverage(feature); } } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationLibraryInfo::buildLibrary DEBUG: leaving..." << std::endl; } } void ossimVpfAnnotationLibraryInfo::drawAnnotations(ossimRgbImage* tile) { for(ossim_uint32 idx = 0; idx < theCoverageLayerList.size(); ++idx) { theCoverageLayerList[idx]->drawAnnotations(tile); } } void ossimVpfAnnotationLibraryInfo::deleteAllCoverage() { for(ossim_uint32 idx = 0; idx < theCoverageLayerList.size(); ++idx) { delete theCoverageLayerList[idx]; } theCoverageLayerList.clear(); } bool ossimVpfAnnotationLibraryInfo::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossim_uint32 idx; kwl.add(prefix, "name", theName, true); for(idx = 0; idx < theCoverageLayerList.size(); ++idx) { theCoverageLayerList[idx]->saveState(kwl, (ossimString(prefix) + "coverage" + ossimString::toString(idx) + ".").c_str()); } return true; } bool ossimVpfAnnotationLibraryInfo::loadState(const ossimKeywordlist& kwl, const char* prefix) { deleteAllCoverage(); theName = kwl.find(prefix, "name"); ossimVpfLibrary* library = theDatabase->getLibrary(theName); if(!library) { return false; } ossimString regExpression = ossimString("^(") + ossimString(prefix) + "coverage[0-9]+.)"; vector keys = kwl.getSubstringKeyList( regExpression ); std::vector theNumberList(keys.size()); int offset = (int)(ossimString(prefix)+"coverage").size(); int idx = 0; for(idx = 0; idx < (int)theNumberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); theNumberList[idx] = numberStr.toInt(); } std::sort(theNumberList.begin(), theNumberList.end()); for(idx = 0; idx < (int)keys.size(); ++idx) { ossimString newPrefix = ossimString(prefix); newPrefix += ossimString("coverage"); newPrefix += ossimString::toString(theNumberList[idx]); newPrefix += ossimString("."); ossimVpfAnnotationCoverageInfo* coverageInfo = new ossimVpfAnnotationCoverageInfo; coverageInfo->setLibrary(library); theCoverageLayerList.push_back(coverageInfo); coverageInfo->loadState(kwl, newPrefix); } return true; } ossim-Miami-2.9.1/src/imaging/ossimVpfAnnotationSource.cpp000066400000000000000000000153661352751253100236560ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimVpfAnnotationSource:debug"); ossimVpfAnnotationSource::ossimVpfAnnotationSource() :ossimGeoAnnotationSource() { if(!m_geometry) { m_geometry = new ossimImageGeometry(0, new ossimEquDistCylProjection); } ossimMapProjection* mapProj = dynamic_cast(m_geometry->getProjection()); if(mapProj) { mapProj->setMetersPerPixel(ossimDpt(30, 30)); } } ossimVpfAnnotationSource::~ossimVpfAnnotationSource() { close(); } bool ossimVpfAnnotationSource::open(const ossimFilename& file) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationSource::open DEBUG: entering..." << std::endl; } bool result = false; if(file.file().downcase() == "dht") { if(openDatabase(file)) { vector libraryNames = theDatabase.getLibraryNames(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Library names list size = " << libraryNames.size() << std::endl; } for(int idx = 0; idx < (int)libraryNames.size();++idx) { ossimVpfAnnotationLibraryInfo* info = new ossimVpfAnnotationLibraryInfo; info->setName(libraryNames[idx]); theLibraryInfo.push_back(info); info->setDatabase(&theDatabase); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "loading library " << libraryNames[idx] << std::endl; } info->buildLibrary(); info->getAllFeatures(theFeatureList); } transformObjects(); result = true; } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationSource::open DEBUG: leaving..." << std::endl; } return result; } void ossimVpfAnnotationSource::close() { theDatabase.closeDatabase(); for(int idx = 0; idx < (int)theLibraryInfo.size(); ++idx) { delete theLibraryInfo[idx]; } theLibraryInfo.clear(); } ossimFilename ossimVpfAnnotationSource::getFilename()const { return theFilename; } void ossimVpfAnnotationSource::transformObjects(ossimImageGeometry* geom) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationSource::transformObjects DEBUG: entered..." << std::endl; } ossimImageGeometry* tempGeom = geom; if(!tempGeom) { tempGeom = m_geometry.get(); } if(!tempGeom) return; for(int idx = 0; idx < (int)theLibraryInfo.size(); ++idx) { theLibraryInfo[idx]->transform(tempGeom); } computeBoundingRect(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimVpfAnnotationSource::transformObjects DEBUG: leaving..." << std::endl; } } void ossimVpfAnnotationSource::computeBoundingRect() { ossimIrect result; result.makeNan(); for(int i = 0; i < (int)theLibraryInfo.size();++i) { ossimIrect tempRect = theLibraryInfo[i]->getBoundingProjectedRect(); if(!tempRect.hasNans()) { if(result.hasNans()) { result = tempRect; } else { result = result.combine(tempRect); } } } theRectangle = result; } void ossimVpfAnnotationSource::deleteAllLibraries() { for(int idx = 0; idx < (int)theLibraryInfo.size();++idx) { delete theLibraryInfo[idx]; } theLibraryInfo.clear(); } void ossimVpfAnnotationSource::getAllFeatures(std::vector& features) { features = theFeatureList; } void ossimVpfAnnotationSource::setAllFeatures(const std::vector& features) { theFeatureList = features; computeBoundingRect(); } void ossimVpfAnnotationSource::drawAnnotations(ossimRefPtr tile) { theImage->setCurrentImageData(tile); if(theImage->getImageData().valid()) { for(ossim_uint32 idx = 0; idx < theFeatureList.size();++idx) { if(theFeatureList[idx]->getEnabledFlag()) { theFeatureList[idx]->drawAnnotations(theImage.get()); } } } } bool ossimVpfAnnotationSource::openDatabase(const ossimFilename& file) { ossimAnnotationSource::deleteAll(); deleteAllLibraries(); theFeatureList.clear(); if(theDatabase.isOpened()) { theDatabase.closeDatabase(); } theFilename = file; return theDatabase.openDatabase(file); } bool ossimVpfAnnotationSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::FILENAME_KW, theFilename, true); for(ossim_uint32 idx = 0; idx < theLibraryInfo.size(); ++idx) { theLibraryInfo[idx]->saveState(kwl, (ossimString(prefix) + "library" + ossimString::toString(idx) + ".").c_str()); } return true; } bool ossimVpfAnnotationSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; deleteAllLibraries(); const char* filename = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if(filename) { if(openDatabase(filename)) { int idx = 0; ossimString regExpression = ossimString("^(") + ossimString(prefix) + "library[0-9]+.)"; vector keys = kwl.getSubstringKeyList( regExpression ); std::vector theNumberList(keys.size()); int offset = (int)(ossimString(prefix)+"library").size(); for(idx = 0; idx < (int)theNumberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); theNumberList[idx] = numberStr.toInt(); } std::sort(theNumberList.begin(), theNumberList.end()); for(idx=0;idx < (int)keys.size();++idx) { ossimString newPrefix = ossimString(prefix); newPrefix += ossimString("library"); newPrefix += ossimString::toString(theNumberList[idx]); newPrefix += ossimString("."); ossimVpfAnnotationLibraryInfo* info = new ossimVpfAnnotationLibraryInfo; theLibraryInfo.push_back(info); info->setDatabase(&theDatabase); info->loadState(kwl, newPrefix); info->getAllFeatures(theFeatureList); } transformObjects(); result = true; } } return result; } bool ossimVpfAnnotationSource::open() { return open(theFilename); } bool ossimVpfAnnotationSource::isOpen()const { return (theDatabase.isOpened()); } ossim-Miami-2.9.1/src/imaging/ossimVpfTileSource.cpp000066400000000000000000000117671352751253100224420ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // $Id: ossimVpfTileSource.cpp 17932 2010-08-19 20:34:35Z dburken $ //---------------------------------------------------------------------------- #include RTTI_DEF2(ossimVpfTileSource, "ossimVpfTileSource", ossimImageHandler, ossimViewInterface); ossimVpfTileSource::ossimVpfTileSource() : ossimViewInterface() { theObject = this; m_AnnotationSource = new ossimVpfAnnotationSource; m_AnnotationSource->setNumberOfBands(3); } ossimVpfTileSource::~ossimVpfTileSource() { m_AnnotationSource = 0; } bool ossimVpfTileSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { return m_AnnotationSource->saveState(kwl, prefix); } bool ossimVpfTileSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (ossimImageHandler::loadState(kwl, prefix)) { return m_AnnotationSource->loadState(kwl, prefix); } return false; } void ossimVpfTileSource::close() { m_AnnotationSource->close(); } bool ossimVpfTileSource::open() { return m_AnnotationSource->open(theImageFile); } ossimRefPtr ossimVpfTileSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { return m_AnnotationSource->getTile(tileRect, resLevel); } ossim_uint32 ossimVpfTileSource::getNumberOfInputBands() const { return m_AnnotationSource->getNumberOfOutputBands(); } ossim_uint32 ossimVpfTileSource::getNumberOfOutputBands() const { return m_AnnotationSource->getNumberOfOutputBands(); } ossim_uint32 ossimVpfTileSource::getNumberOfLines(ossim_uint32 /* reduced_res_level */) const { ossimIrect theBounds = m_AnnotationSource->getBoundingRect(); if(theBounds.hasNans()) { return theBounds.ul().x; } return theBounds.height(); } ossim_uint32 ossimVpfTileSource::getNumberOfSamples(ossim_uint32 /* reduced_res_level */) const { ossimIrect theBounds = m_AnnotationSource->getBoundingRect(); if(theBounds.hasNans()) { return theBounds.ul().x; } return theBounds.height(); } ossim_uint32 ossimVpfTileSource::getNumberOfDecimationLevels() const { return 32; } ossimIrect ossimVpfTileSource::getImageRectangle(ossim_uint32 /* reduced_res_level */) const { return m_AnnotationSource->getBoundingRect(); } //************************************************************************************************** // Returns the image geometry object associated with this tile source or NULL if non defined. //************************************************************************************************** ossimRefPtr ossimVpfTileSource::getImageGeometry() { if (theGeometry.valid()) return theGeometry; ossimRefPtr annotGeom = m_AnnotationSource->getImageGeometry(); if ( annotGeom.valid() ) { // Copy the annotation source's geometry as our own: theGeometry = new ossimImageGeometry(*annotGeom); // Set image things the geometry object should know about. initImageParameters( theGeometry.get() ); return theGeometry; } return ossimRefPtr(); } ossimScalarType ossimVpfTileSource::getOutputScalarType() const { return m_AnnotationSource->getOutputScalarType(); } ossim_uint32 ossimVpfTileSource::getTileWidth() const { return m_AnnotationSource->getTileWidth(); } ossim_uint32 ossimVpfTileSource::getTileHeight() const { return m_AnnotationSource->getTileHeight(); } ossim_uint32 ossimVpfTileSource::getImageTileWidth() const { return 0; } ossim_uint32 ossimVpfTileSource::getImageTileHeight() const { return 0; } bool ossimVpfTileSource::isOpen()const { return m_AnnotationSource->isOpen(); } double ossimVpfTileSource::getNullPixelValue(ossim_uint32 band)const { return m_AnnotationSource->getNullPixelValue(band); } double ossimVpfTileSource::getMinPixelValue(ossim_uint32 band)const { return m_AnnotationSource->getMinPixelValue(band); } double ossimVpfTileSource::getMaxPixelValue(ossim_uint32 band)const { return m_AnnotationSource->getMaxPixelValue(band); } ossimObject* ossimVpfTileSource::getView() { return m_AnnotationSource->getView(); } const ossimObject* ossimVpfTileSource::getView()const { return m_AnnotationSource->getView(); } bool ossimVpfTileSource::setView(ossimObject* baseObject) { return m_AnnotationSource->setView(baseObject); } void ossimVpfTileSource::getAllFeatures(std::vector& featureList) { m_AnnotationSource->getAllFeatures(featureList); } void ossimVpfTileSource::setAllFeatures(std::vector& featureList) { m_AnnotationSource->setAllFeatures(featureList); } void ossimVpfTileSource::transformObjects() { m_AnnotationSource->transformObjects(); } void ossimVpfTileSource::computeBoundingRect() { m_AnnotationSource->computeBoundingRect(); } ossim-Miami-2.9.1/src/imaging/ossimWatermarkFilter.cpp000066400000000000000000001004521352751253100230010ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, David Burken, all rights reserved. // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Class definition of ossimWatermarkFilter. // Applies an image or watermark to image. Positioning is based on mode. // Density is base on alpha weight. // //---------------------------------------------------------------------------- // $Id: ossimWatermarkFilter.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimWatermarkFilter, "ossimWatermarkFilter", ossimImageSourceFilter) static ossimTrace traceDebug(ossimString("ossimWatermarkFilter:debug")); // Keywords: static const char WATERMARK_MODE_KW[] = "watermark_mode"; static const char WEIGHT_KW[] = "weight"; #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimWatermarkFilter.cpp 15766 2009-10-20 12:37:09Z gpotts $"; #endif const ossim_float64 DEFAULT_WEIGHT = 0.20; ossimWatermarkFilter::ossimWatermarkFilter() : theFilename(ossimFilename::NIL), theWatermarkWeight(DEFAULT_WEIGHT), theTile(NULL), theWatermark(NULL), theMode(ossimWatermarkFilter::UPPER_LEFT), theInputBoundingRect(), theDirtyFlag(true) { theEnableFlag = true; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPixelFlipper::ossimPixelFlipper" << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } } ossimWatermarkFilter::~ossimWatermarkFilter() { // Dereference tiles and force a delete if last reference. theWatermark = NULL; theTile = NULL; } ossimString ossimWatermarkFilter::getShortName() const { return ossimString("Watermark Filter"); } ossimString ossimWatermarkFilter::getLongName() const { return ossimString("Watermark Filter - Applies watermark image onto getTile Request."); } ossimString ossimWatermarkFilter::getDescription() const { ossimString description; description = getLongName(); description += "\n"; description += "Valid modes:\n"; vector list; getModeList(list); vector::const_iterator i = list.begin(); while (i != list.end()) { description +=(*i); description += "\n"; ++i; } return description; } ossimRefPtr ossimWatermarkFilter::getTile( const ossimIrect& tile_rect, ossim_uint32 resLevel) { // Lock for the length of this method. // Check for input. if (!theInputConnection) { if (theTile.valid()) { theTile->setImageRectangle(tile_rect); theTile->makeBlank(); } return theTile; } // Fetch a tile from from the input source. ossimRefPtr inputTile = theInputConnection->getTile(tile_rect, resLevel); // Check for bypass. if (theEnableFlag == false) return inputTile; // Check for weight being 0.0. if (theWatermarkWeight == 0.0) return inputTile; //--- // Check for dirty state. // Note: This is set in initialize if something changes. //--- if (theDirtyFlag == true) { if (allocate() == false) // Something not right if false. { return inputTile; } } // We will only watermark (process) within the input bounding rectangle. if (tile_rect.intersects(theInputBoundingRect) == false) { return inputTile; } // Capture the rectangle and blank out theTile. theTile->setImageRectangle(tile_rect); if (inputTile.valid() && (inputTile->getDataObjectStatus() != OSSIM_NULL)) { // Copy the inputTile to theTile. theTile->loadTile(inputTile.get()); } else { theTile->makeBlank(); } // Write the watermarks... switch(theTile->getScalarType()) { case OSSIM_UINT8: { fill(ossim_uint8(0)); break; } case OSSIM_SINT8: { fill(ossim_sint8(0)); break; } case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: { fill(ossim_uint16(0)); break; } case OSSIM_SINT16: { fill(ossim_sint16(0)); break; } case OSSIM_UINT32: { fill(ossim_uint32(0)); break; } case OSSIM_SINT32: { fill(ossim_sint32(0)); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { fill(ossim_float32(0)); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { fill(ossim_float32(0)); break; } case OSSIM_SCALAR_UNKNOWN: default: { ossimNotify(ossimNotifyLevel_WARN) << "Scalar type = " << theTile->getScalarType() << " Not supported by ossimWatermarkFilter" << std::endl; return inputTile; } } return theTile; } template void ossimWatermarkFilter::fill(T /* dummy */) { const ossimIrect TILE_RECT = theTile->getImageRectangle(); // We will only fill data within the input bounding rect. const ossimIrect CLIPPED_TILE_RECT = TILE_RECT.clipToRect(theInputBoundingRect); // Get the bounding rectangles. vector rects(0); getIntersectingRects(rects); if (rects.size() == 0) { return; } //--- // Have watermark rectangles that intersect this tile so we need to process. //--- ossim_uint32 band = 0; ossim_float64 inputPixWeight = 1.0 - theWatermarkWeight; // Get a pointers to the watermark buffers (wmBuf) and nulls wn. T** wmBuf = new T*[theWatermarkNumberOfBands]; for (band = 0; band < theWatermarkNumberOfBands; ++band) { wmBuf[band] = static_cast(theWatermark->getBuf(band)); } // Get a pointers to the output tile buffers and nulls in. T** otBuf = new T*[theInputNumberOfBands]; for (band = 0; band < theInputNumberOfBands; ++band) { otBuf[band] = static_cast(theTile->getBuf(band)); } // Get the width of the buffers for indexing. ossim_int32 wmWidth = static_cast(theWatermark->getWidth()); ossim_int32 otWidth = static_cast(theTile->getWidth()); const ossim_float64* wmNull = theWatermark->getNullPix(); const ossim_float64* otMin = theTile->getMinPix(); const ossim_float64* otMax = theTile->getMaxPix(); const ossim_float64* otNull = theTile->getNullPix(); // Control loop through intersecting rectangles. vector::const_iterator i = rects.begin(); while (i != rects.end()) { if ( (*i).intersects(CLIPPED_TILE_RECT) ) { //--- // This is the rectangle we want to fill relative to requesting // image space. //--- const ossimIrect CLIPPED_WATERMARRK_RECT = (*i).clipToRect(CLIPPED_TILE_RECT); ossim_int32 clipHeight = CLIPPED_WATERMARRK_RECT.height(); ossim_int32 clipWidth = CLIPPED_WATERMARRK_RECT.width(); // Compute the starting offset into the wmBuf and otBuf. ossim_int32 wmOffset = (CLIPPED_WATERMARRK_RECT.ul().y - (*i).ul().y) * wmWidth + CLIPPED_WATERMARRK_RECT.ul().x - (*i).ul().x; ossim_int32 otOffset = (CLIPPED_WATERMARRK_RECT.ul().y - TILE_RECT.ul().y)* otWidth + CLIPPED_WATERMARRK_RECT.ul().x - TILE_RECT.ul().x; // Line loop... for (ossim_int32 line = 0; line < clipHeight; ++line) { // Sample loop... for (ossim_int32 sample = 0; sample < clipWidth; ++sample) { // Output band control loop until all output bands are filled. ossim_uint32 otBand = 0; while (otBand < theInputNumberOfBands) { // Band loop through the watermark. for (ossim_uint32 wmBand = 0; wmBand < theWatermarkNumberOfBands; ++wmBand) { if (wmBuf[wmBand][wmOffset+sample] != wmNull[wmBand]) { // Apply the weight to the input pixel. ossim_float64 p1 = (otBuf[otBand][otOffset+sample] != otNull[otBand]) ? otBuf[otBand][otOffset+sample] * inputPixWeight : 0.0; // Apply the Weight to the watermark pixel. ossim_float64 p2 = wmBuf[wmBand][wmOffset+sample]*theWatermarkWeight; // Add them up. ossim_float64 p3 = p1 + p2; // Cast to output type with range checking. otBuf[otBand][otOffset+sample] = static_cast( ( (p3 >= otMin[otBand]) ? (p3 < otMax[otBand] ? p3 : otMax[otBand]) : otNull[otBand]) ); } ++otBand; // We stop when we reach here. All output bands filled. if (otBand == theInputNumberOfBands) { break; } } // End of band through watermark. } // End of outer band loop. } // End of sample loop. wmOffset += wmWidth; otOffset += otWidth; } // End of line loop. } // End "if ( (*i).intersects(TILE_RECT) )" ++i; // Go to next rectangle to fill if any. } // End of "while (i != rects.end())" // Clean up. delete [] wmBuf; delete [] otBuf; theTile->validate(); } void ossimWatermarkFilter::getIntersectingRects(vector& rects) { switch(theMode) { case UPPER_LEFT: getUpperLeftRect(rects); break; case UPPER_CENTER: getUpperCenterRect(rects); break; case UPPER_RIGHT: getUpperRightRect(rects); break; case CENTER: getCenterRect(rects); break; case LOWER_LEFT: getLowerLeftRect(rects); break; case LOWER_CENTER: getLowerCenterRect(rects); break; case LOWER_RIGHT: getLowerRightRect(rects); break; case UNIFORM_DENSE: getUniformDenseRects(rects); break; case UNIFORM_SPARSE: getUniformSparceRects(rects); break; default: break; } } void ossimWatermarkFilter::getUpperLeftRect(vector& rects) { // First clip the rect to the bounding image rectangle. const ossimIrect CLIP_RECT = theTile->getImageRectangle().clipToRect(theInputBoundingRect); theWatermark->setOrigin(theInputBoundingRect.ul()); ossimIrect r = theWatermark->getImageRectangle(); if (r.intersects(CLIP_RECT)) { rects.push_back(r); } } void ossimWatermarkFilter::getUpperCenterRect(vector& rects) { // First clip the rect to the bounding image rectangle. const ossimIrect CLIP_RECT = theTile->getImageRectangle().clipToRect(theInputBoundingRect); ossim_uint32 watermarkWidth = theWatermark->getImageRectangle().width(); ossim_uint32 inputWidth = theInputBoundingRect.width(); ossimIpt origin = theInputBoundingRect.ul(); // Input wider than watermark so center. if (inputWidth > watermarkWidth) { ossim_int32 offset = static_cast((inputWidth - watermarkWidth) / 2); origin.x = origin.x + offset; } theWatermark->setOrigin(origin); ossimIrect r = theWatermark->getImageRectangle(); if (r.intersects(CLIP_RECT)) { rects.push_back(r); } } void ossimWatermarkFilter::getUpperRightRect(vector& rects) { // First clip the rect to the bounding image rectangle. const ossimIrect CLIP_RECT = theTile->getImageRectangle().clipToRect(theInputBoundingRect); ossim_uint32 watermarkWidth = theWatermark->getImageRectangle().width(); ossim_uint32 inputWidth = theInputBoundingRect.width(); ossimIpt origin = theInputBoundingRect.ul(); // Input wider than watermark so center. if (inputWidth > watermarkWidth) { ossim_int32 offset = static_cast(inputWidth - watermarkWidth); origin.x = origin.x + offset; } theWatermark->setOrigin(origin); ossimIrect r = theWatermark->getImageRectangle(); if (r.intersects(CLIP_RECT)) { rects.push_back(r); } } void ossimWatermarkFilter::getCenterRect(vector& rects) { // First clip the rect to the bounding image rectangle. const ossimIrect CLIP_RECT = theTile->getImageRectangle().clipToRect(theInputBoundingRect); ossim_uint32 watermarkWidth = theWatermark->getImageRectangle().width(); ossim_uint32 watermarkHeight = theWatermark->getImageRectangle().height(); ossim_uint32 inputWidth = theInputBoundingRect.width(); ossim_uint32 inputHeight = theInputBoundingRect.height(); ossimIpt origin = theInputBoundingRect.ul(); // Input wider than watermark so center. if (inputWidth > watermarkWidth) { ossim_int32 offset = static_cast((inputWidth - watermarkWidth) / 2); origin.x = origin.x + offset; } // Input higher than watermark so center. if (inputHeight > watermarkHeight) { ossim_int32 offset = static_cast((inputHeight - watermarkHeight) / 2); origin.y = origin.y + offset; } theWatermark->setOrigin(origin); ossimIrect r = theWatermark->getImageRectangle(); if (r.intersects(CLIP_RECT)) { rects.push_back(r); } } void ossimWatermarkFilter::getLowerLeftRect(vector& rects) { // First clip the rect to the bounding image rectangle. const ossimIrect CLIP_RECT = theTile->getImageRectangle().clipToRect(theInputBoundingRect); ossim_uint32 watermarkHeight = theWatermark->getImageRectangle().height(); ossim_uint32 inputHeight = theInputBoundingRect.height(); ossimIpt origin = theInputBoundingRect.ul(); // Input higher than watermark so apply offset. if (inputHeight > watermarkHeight) { ossim_int32 offset = static_cast(inputHeight - watermarkHeight); origin.y = origin.y + offset; } theWatermark->setOrigin(origin); ossimIrect r = theWatermark->getImageRectangle(); if (r.intersects(CLIP_RECT)) { rects.push_back(r); } } void ossimWatermarkFilter::getLowerCenterRect(vector& rects) { // First clip the rect to the bounding image rectangle. const ossimIrect CLIP_RECT = theTile->getImageRectangle().clipToRect(theInputBoundingRect); ossim_uint32 watermarkWidth = theWatermark->getImageRectangle().width(); ossim_uint32 watermarkHeight = theWatermark->getImageRectangle().height(); ossim_uint32 inputWidth = theInputBoundingRect.width(); ossim_uint32 inputHeight = theInputBoundingRect.height(); ossimIpt origin = theInputBoundingRect.ul(); // Input wider than watermark so center. if (inputWidth > watermarkWidth) { ossim_int32 offset = static_cast((inputWidth - watermarkWidth) / 2); origin.x = origin.x + offset; } // Input higher than watermark so apply offset. if (inputHeight > watermarkHeight) { ossim_int32 offset = static_cast(inputHeight - watermarkHeight); origin.y = origin.y + offset; } theWatermark->setOrigin(origin); ossimIrect r = theWatermark->getImageRectangle(); if (r.intersects(CLIP_RECT)) { rects.push_back(r); } } void ossimWatermarkFilter::getLowerRightRect(vector& rects) { // First clip the rect to the bounding image rectangle. const ossimIrect CLIP_RECT = theTile->getImageRectangle().clipToRect(theInputBoundingRect); ossim_uint32 watermarkWidth = theWatermark->getImageRectangle().width(); ossim_uint32 watermarkHeight = theWatermark->getImageRectangle().height(); ossim_uint32 inputWidth = theInputBoundingRect.width(); ossim_uint32 inputHeight = theInputBoundingRect.height(); ossimIpt origin = theInputBoundingRect.ul(); // Input wider than watermark so center. if (inputWidth > watermarkWidth) { ossim_int32 offset = static_cast(inputWidth - watermarkWidth); origin.x = origin.x + offset; } // Input higher than watermark so apply offset. if (inputHeight > watermarkHeight) { ossim_int32 offset = static_cast(inputHeight - watermarkHeight); origin.y = origin.y + offset; } theWatermark->setOrigin(origin); ossimIrect r = theWatermark->getImageRectangle(); if (r.intersects(CLIP_RECT)) { rects.push_back(r); } } void ossimWatermarkFilter::getUniformDenseRects(vector& rects) { // First clip the rect to the bounding image rectangle. const ossimIrect CLIP_RECT = theTile->getImageRectangle().clipToRect(theInputBoundingRect); ossim_uint32 watermarkWidth = theWatermark->getImageRectangle().width(); ossim_uint32 watermarkHeight = theWatermark->getImageRectangle().height(); ossim_uint32 inputWidth = theInputBoundingRect.width(); ossim_uint32 inputHeight = theInputBoundingRect.height(); ossim_uint32 watermarksHigh = inputHeight / watermarkHeight; if (inputHeight % watermarkHeight) ++watermarksHigh; ossim_uint32 watermarksWide = inputWidth / watermarkWidth; if (inputWidth % watermarkWidth) ++watermarksWide; ossim_int32 xOffset = static_cast(watermarkWidth); ossim_int32 yOffset = static_cast(watermarkHeight); ossimIpt origin = theInputBoundingRect.ul(); for (ossim_uint32 y = 0; y < watermarksHigh; ++y) { for (ossim_uint32 x = 0; x < watermarksWide; ++x) { theWatermark->setOrigin(origin); ossimIrect r = theWatermark->getImageRectangle(); if (r.intersects(CLIP_RECT)) { rects.push_back(r); } origin.x = origin.x + xOffset; } origin.y = origin.y + yOffset; origin.x = theInputBoundingRect.ul().x; } } void ossimWatermarkFilter::getUniformSparceRects(vector& rects) { // First clip the rect to the bounding image rectangle. const ossimIrect CLIP_RECT = theTile->getImageRectangle().clipToRect(theInputBoundingRect); ossim_uint32 watermarkWidth = theWatermark->getImageRectangle().width(); ossim_uint32 watermarkHeight = theWatermark->getImageRectangle().height(); ossim_uint32 inputWidth = theInputBoundingRect.width(); ossim_uint32 inputHeight = theInputBoundingRect.height(); ossim_uint32 gapWidth = watermarkWidth/2; ossim_uint32 gapHeight = watermarkHeight/2; ossim_uint32 watermarksHigh = inputHeight/(watermarkHeight+gapHeight); if (inputHeight % watermarkHeight) ++watermarksHigh; ossim_uint32 watermarksWide = inputWidth/(watermarkWidth+gapWidth); if (inputWidth % watermarkWidth) ++watermarksWide; ossim_int32 xOffset = static_cast(watermarkWidth + gapWidth); ossim_int32 yOffset = static_cast(watermarkHeight + gapHeight); ossimIpt origin = theInputBoundingRect.ul(); for (ossim_uint32 y = 0; y < watermarksHigh; ++y) { for (ossim_uint32 x = 0; x < watermarksWide; ++x) { theWatermark->setOrigin(origin); ossimIrect r = theWatermark->getImageRectangle(); if (r.intersects(CLIP_RECT)) { rects.push_back(r); } origin.x = origin.x + xOffset; } origin.y = origin.y + yOffset; origin.x = theInputBoundingRect.ul().x; } } void ossimWatermarkFilter::initialize() { //--- // If state is not already dirty and there is an input connection // check for: // // 1) Scalar change // 2) band number change // 3) bounding box change // // Set state to dirty on a change. // // NOTE: This method intentionally only sets the dirty state and doesn't do // anything else as it is called repetitively during chain setup or chain // state changes. // // The first getTile call will do the real work, call allocate(), // if the state is dirty. //--- // Lock for the length of this method. // Set the input connection. ossimImageSourceFilter::initialize(); // Once dirty flag is set no need to do it again. if (theDirtyFlag == false) { if (theInputConnection) { // Check for scalar type change. if (theInputScalarType != theInputConnection->getOutputScalarType()) { theDirtyFlag = true; return; } // Check for band change. if (theInputNumberOfBands != theInputConnection->getNumberOfOutputBands()) { theDirtyFlag = true; return; } // Check for bounding rectangle change. if ( theInputBoundingRect != theInputConnection->getBoundingRect() ) { theDirtyFlag = true; return; } } } } bool ossimWatermarkFilter::allocate() { // Capture the bounding rect: theInputBoundingRect = theInputConnection->getBoundingRect(); // Capture the scalar type: theInputScalarType = theInputConnection->getOutputScalarType(); // Capture the number of bands: theInputNumberOfBands = theInputConnection->getNumberOfOutputBands(); //--- // Check the watermark scalar type. //--- if (theWatermark.valid()) { if (theWatermark->getScalarType() != theInputScalarType) { //--- // We'll need to make a new one with a scalar remapper after it. //--- theWatermark = NULL; // We'll need to make a new one. } } //--- // Make a new watermark tile. This will do a scalar remap if needed. // If we don't have a watermark no point in going on... //--- if (!theWatermark) { if (openWatermarkFile() == false) { return false; } } if (theTile.valid()) { if ( (theTile->getScalarType() != theInputScalarType) || (theTile->getNumberOfBands() != theInputNumberOfBands) ) { theTile = NULL; // We'll need to make a new one. } } // Make a new output tile if we need to. if (!theTile) { theTile = ossimImageDataFactory::instance()->create(this, theInputConnection); if (theTile.valid()) { theTile->initialize(); } else { return false; } } //--- // If we get here things are good so clear the dirty flag so we don't // get called again needlessly. //--- theDirtyFlag = false; return true; } bool ossimWatermarkFilter::openWatermarkFile() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimWatermarkFilter::openWatermarkFile DEBUG: entered..." << std::endl; } if (!theInputConnection || (theFilename == ossimFilename::NIL)) { return false; } theWatermark = NULL; // This will destroy any previous tiles. // Open the watermark image. ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(theFilename); if (!ih) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimWatermarkFilter::openWatermarkFile" << "\nCould not open: " << theFilename << std::endl; } return false; } if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimWatermarkFilter::openWatermarkFile" << "\nError reading image: " << theFilename << std::endl; return false; } } ih->initialize(); ossimRefPtr imageSource = ih.get(); ossimRefPtr remapper; if (ih->getOutputScalarType() != theInputConnection->getOutputScalarType()) { // Remap the watemark to the same scalar type as the input. remapper = new ossimScalarRemapper(imageSource.get(), theInputConnection-> getOutputScalarType()); remapper->initialize(); imageSource = remapper.get(); } // Get the full image rectangle. theWatermark = imageSource->getTile(ih->getImageRectangle(), 0); // Cleanup... if (remapper.valid()) { remapper->disconnect(); remapper = NULL; } if(ih.valid()) { ih->disconnect(); ih = 0; } imageSource = 0; if (theWatermark.valid() == false) { return false; } // Capture the bands as we will need this repetitively. theWatermarkNumberOfBands = theWatermark->getNumberOfBands(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimWatermarkFilter::openWatermarkFile DEBUG:" << *(theWatermark.get()) << endl; } return true; } bool ossimWatermarkFilter::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, ossimKeywordNames::FILENAME_KW, theFilename.c_str()); kwl.add(prefix, WATERMARK_MODE_KW, getModeString().c_str()); kwl.add(prefix, WEIGHT_KW, theWatermarkWeight); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimWatermarkFilter::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Do this first so connections get set up. if (ossimImageSourceFilter::loadState(kwl, prefix) == false) { return false; } const char* lookupReturn; lookupReturn = kwl.find(prefix, WEIGHT_KW); if(lookupReturn) { setWeight(ossimString(lookupReturn).toDouble()); } lookupReturn = kwl.find(prefix, WATERMARK_MODE_KW); if(lookupReturn) { setMode(ossimString(lookupReturn)); } lookupReturn = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if(lookupReturn) { setFilename(lookupReturn); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimWatermarkFilter::loadState DEBUG:" << std::endl; print(ossimNotify(ossimNotifyLevel_DEBUG)); } return true; } ossimRefPtr ossimWatermarkFilter::getProperty( const ossimString& name) const { // Lock for the length of this method. if (name == ossimKeywordNames::FILENAME_KW) { ossimFilenameProperty* ofp = new ossimFilenameProperty(name, theFilename); ofp->setIoType(ossimFilenameProperty::ossimFilenamePropertyIoType_INPUT); ofp->setCacheRefreshBit(); return ossimRefPtr((ossimProperty*)ofp); } else if (name == WATERMARK_MODE_KW) { vector constraintList; getModeList(constraintList); ossimStringProperty* p = new ossimStringProperty(name, getModeString(), false, constraintList); p->setCacheRefreshBit(); return ossimRefPtr(p); } else if (name == WEIGHT_KW) { ossimProperty* p = new ossimNumericProperty(name, ossimString::toString(theWatermarkWeight)); p->setCacheRefreshBit(); return ossimRefPtr(p); } return ossimImageSourceFilter::getProperty(name); } void ossimWatermarkFilter::setProperty(ossimRefPtr property) { if (!property) return; ossimString os = property->valueToString(); ossimString name = property->getName(); if (name == ossimKeywordNames::FILENAME_KW) { setFilename(os); } else if (name == WATERMARK_MODE_KW) { setMode(os); } else if (name == WEIGHT_KW) { setWeight(os.toDouble()); } else { ossimImageSourceFilter::setProperty(property); } } void ossimWatermarkFilter::getPropertyNames( std::vector& propertyNames) const { propertyNames.push_back(ossimKeywordNames::FILENAME_KW); propertyNames.push_back(WATERMARK_MODE_KW); propertyNames.push_back(WEIGHT_KW); ossimImageSourceFilter::getPropertyNames(propertyNames); } void ossimWatermarkFilter::getModeList(vector& list) const { list.clear(); list.resize(ossimWatermarkFilter::END); list[0] = ossimString("upper_left"); list[1] = ossimString("upper_center"); list[2] = ossimString("upper_right"); list[3] = ossimString("center"); list[4] = ossimString("lower_left"); list[5] = ossimString("lower_center"); list[6] = ossimString("lower_right"); list[7] = ossimString("uniform_dense"); list[8] = ossimString("uniform_sparse"); } ossimWatermarkFilter::WatermarkMode ossimWatermarkFilter::getMode() const { return theMode; } ossimString ossimWatermarkFilter::getModeString() const { switch(theMode) { case UPPER_LEFT: return ossimString("upper_left"); case UPPER_CENTER: return ossimString("upper_center"); case UPPER_RIGHT: return ossimString("upper_right"); case CENTER: return ossimString("center"); case LOWER_LEFT: return ossimString("lower_left"); case LOWER_CENTER: return ossimString("lower_center"); case LOWER_RIGHT: return ossimString("lower_right"); case UNIFORM_DENSE: return ossimString("uniform_dense"); case UNIFORM_SPARSE: return ossimString("uniform_sparse"); default: break; } return ossimString("UNKNOWN_MODE"); } void ossimWatermarkFilter::setFilename(const ossimFilename& file) { if (file != theFilename) { theFilename = file; theWatermark = NULL; // Will be reallocated next getTile. theDirtyFlag = true; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimWatermarkFilter::setFilename DEBUG:" << std::endl; print(ossimNotify(ossimNotifyLevel_DEBUG)); } } void ossimWatermarkFilter::setMode(const ossimString& mode) { ossimString os = mode; os.downcase(); if (os == "upper_left") { theMode = UPPER_LEFT; } else if (os == "upper_center") { theMode = UPPER_CENTER; } else if (os == "upper_right") { theMode = UPPER_RIGHT; } else if (os == "center") { theMode = CENTER; } else if (os == "lower_left") { theMode = LOWER_LEFT; } else if (os == "lower_center") { theMode = LOWER_CENTER; } else if (os == "lower_right") { theMode = LOWER_RIGHT; } else if (os == "uniform_dense") { theMode = UNIFORM_DENSE; } else if (os == "uniform_sparse") { theMode = UNIFORM_SPARSE; } else { // Invalid mode... if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimWatermarkFilter::setMode DEBUG:" << "\nInvalid mode! " << mode << std::endl; } } } void ossimWatermarkFilter::setWeight(ossim_float64 weight) { if ( (weight >= 0.0) && (weight <= 1.0) ) { theWatermarkWeight = weight; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimWatermarkFilter::setWeight DEBUG:" << std::endl; print(ossimNotify(ossimNotifyLevel_DEBUG)); } } std::ostream& ossimWatermarkFilter::print(std::ostream& out) const { out << "ossimWatermarkFilter::print" << "\ntheFilename: " << theFilename << "\ntheWatermarkWeight: " << theWatermarkWeight << "\ntheMode: " << getModeString() << std::endl; return ossimImageSourceFilter::print(out); } ossim-Miami-2.9.1/src/imaging/ossimWorldFileWriter.cpp000066400000000000000000000120651352751253100227640ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2003 Storage Area Networks, Inc. // // License: See top level LICENSE.txt file. // // Author: Kenneth Melero (kmelero@sanz.com) // //******************************************************************* // $Id: ossimWorldFileWriter.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include // #include #include #include #include #include using namespace std; RTTI_DEF1(ossimWorldFileWriter, "ossimWorldFileWriter", ossimMetadataFileWriter) static ossimTrace traceDebug("ossimWorldFileWriter:debug"); ossimWorldFileWriter::ossimWorldFileWriter() : ossimMetadataFileWriter(), theUnits(OSSIM_METERS) { } ossimWorldFileWriter::~ossimWorldFileWriter() { } bool ossimWorldFileWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = kwl.find(prefix, "linear_units"); if(lookup) { ossimUnitType units = (ossimUnitType)ossimUnitTypeLut::instance()-> getEntryNumber(lookup, true); if ( (units == OSSIM_METERS) || (units == OSSIM_FEET) || (units == OSSIM_US_SURVEY_FEET) ) { theUnits = units; } } return ossimMetadataFileWriter::loadState(kwl, prefix); } //************************************************************************************************** // Outputs projection information to the output file. Returns TRUE if successful. //************************************************************************************************** bool ossimWorldFileWriter::writeFile() { if(!theInputConnection) return false; std::ofstream out(theFilename.c_str(), ios_base::out); if (!out) return false; // Fetch the map projection of the input image if it exists: const ossimMapProjection* mapProj = 0; ossimRefPtr imgGeom = theInputConnection->getImageGeometry(); if( imgGeom.valid() ) { const ossimProjection* proj = imgGeom->getProjection(); mapProj = PTR_CAST(ossimMapProjection, proj); } if (!mapProj) { out.close(); return false; } // Convert projection info to proper units: ossimDpt gsd = mapProj->getMetersPerPixel(); ossimDpt ul = mapProj->getUlEastingNorthing(); // ESH 05/2008 -- If the pcs code has been given, we // make use of the implied units. theUnits = mapProj->getProjectionUnits(); if (theUnits == OSSIM_FEET) { gsd.x = ossimUnitConversionTool(gsd.x, OSSIM_METERS).getFeet(); gsd.y = ossimUnitConversionTool(gsd.y, OSSIM_METERS).getFeet(); ul.x = ossimUnitConversionTool(ul.x, OSSIM_METERS).getFeet(); ul.y = ossimUnitConversionTool(ul.y, OSSIM_METERS).getFeet(); } else if (theUnits == OSSIM_US_SURVEY_FEET) { gsd.x = ossimUnitConversionTool(gsd.x, OSSIM_METERS).getUsSurveyFeet(); gsd.y = ossimUnitConversionTool(gsd.y, OSSIM_METERS).getUsSurveyFeet(); ul.x = ossimUnitConversionTool(ul.x, OSSIM_METERS).getUsSurveyFeet(); ul.y = ossimUnitConversionTool(ul.y, OSSIM_METERS).getUsSurveyFeet(); } // output projection info to file: out << setiosflags(ios::fixed) << setprecision(15) << gsd.x << endl << 0.0 << endl // rotation value X << 0.0 << endl // rotation value y << -gsd.y << endl << ul.x << endl << ul.y << endl; out.close(); return true; } //************************************************************************************************** void ossimWorldFileWriter::getMetadatatypeList( std::vector& metadatatypeList) const { metadatatypeList.push_back(ossimString("tiff_world_file")); metadatatypeList.push_back(ossimString("jpeg_world_file")); } bool ossimWorldFileWriter::hasMetadataType( const ossimString& metadataType)const { if ( (metadataType == "tiff_world_file") || (metadataType == "jpeg_world_file") ) { return true; } return false; } void ossimWorldFileWriter::setLinearUnits(ossimUnitType units) { if ( (units == OSSIM_UNIT_UNKNOWN) || (units == OSSIM_METERS) || (units == OSSIM_FEET) || (units == OSSIM_US_SURVEY_FEET) ) { theUnits = units; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimWorldFileWriter::setLinearUnits WARNING!" << "\nUnsupported units passed to method: " << ossimUnitTypeLut::instance()->getEntryString(units) << "\nUnits unchanged..." << std::endl; } } ossim-Miami-2.9.1/src/imaging/ossimWriter.cpp000066400000000000000000001120331352751253100211500ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Generic image writer class. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static const std::string ALIGN_TILES_KW = "align_tiles"; // bool static const std::string BLOCK_SIZE_KW = "block_size"; // unsigned int static const std::string FLUSH_TILES_KW = "flush_tiles"; // bool static const std::string INCLUDE_BLANK_TILES_KW = "include_blank_tiles"; // bool static const std::string TILE_SIZE_KW = "tile_size"; // (x,y) in pixels static const std::string TRUE_KW = "true"; static const ossimTrace traceDebug("ossimWriter:debug"); ossimWriter::ossimWriter() : ossimImageFileWriter(), m_str(0), m_ownsStreamFlag(false), m_kwl(new ossimKeywordlist()), m_outputTileSize(OSSIM_DEFAULT_TILE_WIDTH, OSSIM_DEFAULT_TILE_HEIGHT) { // Set default options: ossim::defaultTileSize(m_outputTileSize); m_kwl->addPair( ALIGN_TILES_KW, TRUE_KW ); m_kwl->addPair( BLOCK_SIZE_KW, "4096" ); m_kwl->addPair( FLUSH_TILES_KW, TRUE_KW ); m_kwl->addPair( INCLUDE_BLANK_TILES_KW, TRUE_KW ); m_kwl->addPair( TILE_SIZE_KW, m_outputTileSize.toString().string() ); } ossimWriter::~ossimWriter() { close(); // Not a leak, ref ptr. m_kwl = 0; } void ossimWriter::close() { if (m_str) { m_str->flush(); if (m_ownsStreamFlag) { delete m_str; m_str = 0; m_ownsStreamFlag = false; } } } ossimString ossimWriter::getShortName() const { return ossimString("ossim_writer"); } ossimString ossimWriter::getLongName() const { return ossimString("ossim writer"); } ossimString ossimWriter::getClassName() const { return ossimString("ossimWriter"); } ossimString ossimWriter::getExtension() const { ossimString result = ""; if ( theOutputImageType == "ossim_ttbs" ) // tiled tiff band separate { result = "tif"; } return result; } void ossimWriter::getImageTypeList(std::vector& imageTypeList) const { // imageTypeList.push_back(ossimString("tiff_tiled_band_separate")); imageTypeList.push_back(ossimString("ossim_ttbs")); // tmp drb } bool ossimWriter::isOpen() const { return ( m_str ? true : false ); } bool ossimWriter::open() { bool status = false; close(); if ( theFilename.size() && hasImageType( theOutputImageType ) ) { std::ofstream* os = new std::ofstream(); os->open( theFilename.c_str(), ios::out | ios::binary ); if( os->is_open() ) { m_str = os; m_ownsStreamFlag = true; status = true; } else { delete os; os = 0; } } return status; } bool ossimWriter::hasImageType(const ossimString& imageType) const { bool result = false; if ( (imageType == "ossim_ttbs") || (imageType == "image/tif") ) { result = true; } return result; } bool ossimWriter::writeFile() { bool status = true; if( theInputConnection.valid() && (getErrorStatus() == ossimErrorCodes::OSSIM_OK) ) { //--- // Check for stream if master process. // Note only the master process is used for writing... //--- if( theInputConnection->isMaster() ) { if (!isOpen()) { status = open(); } } if ( status ) { status = writeStream(); // Flush and close the stream. close(); } } return status; } bool ossimWriter::writeStream() { //--- // This can be called publically so we must to the same checks as the // writeFile method. //--- bool status = false; // Must have a sequencer... if( theInputConnection.valid() ) { if ( isOpen() ) { if ( theOutputImageType == "ossim_ttbs" ) { if ( (theInputConnection->getTileWidth() != static_cast(m_outputTileSize.x)) || (theInputConnection->getTileHeight() != static_cast(m_outputTileSize.y)) ) { theInputConnection->setTileSize(m_outputTileSize); } status = writeStreamTtbs(); } } } return status; } bool ossimWriter::writeStreamTtbs() { // Alway big tiff in native byte order. bool status = false; if ( writeTiffHdr() == true ) { std::vector tile_offsets; std::vector tile_byte_counts; //--- // Min/max arrays must start off empty for // ossimImageData::computeMinMaxPix code. //--- std::vector minBands(0); std::vector maxBands(0); if ( writeTiffTilesBandSeparate( tile_offsets, tile_byte_counts, minBands, maxBands ) == true ) { status = writeTiffTags( tile_offsets, tile_byte_counts, minBands, maxBands ); } } return status; } bool ossimWriter::writeTiffHdr() { //--- // First two bytes, byte order indication. // "MM"(big endian) or "II"(little endian. //--- std::string s; if ( ossim::byteOrder() == OSSIM_LITTLE_ENDIAN ) { s = "II"; } else { s = "MM"; } m_str->write( s.c_str(), 2 ); // Version, 42=classic tiff, 43=big tiff. ossim_uint16 us16 = 43; m_str->write( (const char*)&us16, 2 ); // Byte size of offsets. us16 = 8; m_str->write( (const char*)&us16, 2 ); // Always 0: us16 = 0; m_str->write( (const char*)&us16, 2 ); // Offset to the IFD(image file directory). ossim_uint64 ul64 = 16; m_str->write( (const char*)&ul64, 8 ); return m_str->good(); } bool ossimWriter::writeTiffTags( const std::vector& tile_offsets, const std::vector& tile_byte_counts, const std::vector& minBands, const std::vector& maxBands ) { bool status = false; ossimRefPtr mapProj = 0; ossimRefPtr geom = theInputConnection->getImageGeometry(); if ( geom.valid() ) { ossimRefPtr proj = geom->getProjection(); mapProj = dynamic_cast( proj.get() ); } // Seek to the IFD. m_str->seekp( 16, std::ios_base::beg ); // tag count, this will be rewritten at the end: ossim_uint64 tagCount = 0; m_str->write( (const char*)&tagCount, 8 ); //--- // This is where the tile offsets, tile byte counts and arrays bytes are // written. Starting at byte position 512 which gives from // 16 -> 512(496 bytes) to write tags. //--- std::streamoff arrayWritePos = 512; // Used throughout: ossim_uint16 tag; ossim_uint16 type; ossim_uint64 count; ossim_uint16 value_ui16; ossim_uint32 value_ui32; // image width tag 256: tag = ossim::OTIFFTAG_IMAGEWIDTH; count = 1; if ( theAreaOfInterest.width() <= OSSIM_DEFAULT_MAX_PIX_UINT16 ) { type = ossim::OTIFF_SHORT; value_ui16 = (ossim_uint16)theAreaOfInterest.width(); writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); } else { type = ossim::OTIFF_LONG; value_ui32 = theAreaOfInterest.width(); writeTiffTag( tag, type, count, &value_ui32, arrayWritePos ); } ++tagCount; // image length tag 257: tag = ossim::OTIFFTAG_IMAGELENGTH; count = 1; if ( theAreaOfInterest.height() <= OSSIM_DEFAULT_MAX_PIX_UINT16 ) { type = ossim::OTIFF_SHORT; value_ui16 = (ossim_uint16)theAreaOfInterest.height(); writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); } else { type = ossim::OTIFF_LONG; value_ui32 = theAreaOfInterest.height(); writeTiffTag( tag, type, count, &value_ui32, arrayWritePos ); } ++tagCount; // bits per sample tag 258: tag = ossim::OTIFFTAG_BITSPERSAMPLE; count = theInputConnection->getNumberOfOutputBands(); type = ossim::OTIFF_SHORT; value_ui16 = (ossim_uint16)ossim::getBitsPerPixel( theInputConnection->getOutputScalarType() ); if ( count == 1 ) { writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); } else { std::vector v(count, value_ui16); writeTiffTag( tag, type, count, &v.front(), arrayWritePos ); } ++tagCount; // compression tag 259: tag = ossim::OTIFFTAG_COMPRESSION; type = ossim::OTIFF_SHORT; count = 1; value_ui16 = ossim::COMPRESSION_NONE; // tmp only uncompressed supported. writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); ++tagCount; // photo interpretation tag 262: tag = ossim::OTIFFTAG_PHOTOMETRIC; type = ossim::OTIFF_SHORT; count = 1; if ( theInputConnection->getNumberOfOutputBands() == 3 ) { value_ui16 = ossim::OPHOTO_RGB; } else { value_ui16 = ossim::OPHOTO_MINISBLACK; } writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); ++tagCount; // samples per pixel tag 277: tag = ossim::OTIFFTAG_SAMPLESPERPIXEL; type = ossim::OTIFF_SHORT; count = 1; value_ui16 = theInputConnection->getNumberOfOutputBands(); writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); ++tagCount; // Writes two tags 280 and 281: if ( writeMinMaxTiffTags( arrayWritePos ) == true ) { tagCount += 2; } // planar conf tag 284: tag = ossim::OTIFFTAG_PLANARCONFIG; type = ossim::OTIFF_SHORT; count = 1; value_ui16 = ossim::OTIFFTAG_PLANARCONFIG_SEPARATE; writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); ++tagCount; if ( isTiled() ) { // tile width tag 322: tag = ossim::OTIFFTAG_TILEWIDTH; count = 1; if ( m_outputTileSize.x <= OSSIM_DEFAULT_MAX_PIX_UINT16 ) { type = ossim::OTIFF_SHORT; value_ui16 = (ossim_uint16)m_outputTileSize.x; writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); } else { type = ossim::OTIFF_LONG; value_ui32 = (ossim_uint32)m_outputTileSize.x; writeTiffTag( tag, type, count, &value_ui32, arrayWritePos ); } ++tagCount; // tile length tag 323: tag = ossim::OTIFFTAG_TILELENGTH; count = 1; if ( m_outputTileSize.y <= OSSIM_DEFAULT_MAX_PIX_UINT16 ) { type = ossim::OTIFF_SHORT; value_ui16 = (ossim_uint16)m_outputTileSize.y; writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); } else { type = ossim::OTIFF_LONG; value_ui32 = (ossim_uint32)m_outputTileSize.y; writeTiffTag( tag, type, count, &value_ui32, arrayWritePos ); } ++tagCount; } // tile offsets tag 324: tag = ossim::OTIFFTAG_TILEOFFSETS; count = tile_offsets.size(); type = ossim::OTIFF_LONG8; writeTiffTag( tag, type, count, &tile_offsets.front(), arrayWritePos ); ++tagCount; // tile byte counts tag 325: tag = ossim::OTIFFTAG_TILEBYTECOUNTS; count = tile_byte_counts.size(); type = ossim::OTIFF_LONG8; writeTiffTag( tag, type, count, &tile_byte_counts.front(), arrayWritePos ); ++tagCount; // sample format tag 339: tag = ossim::OTIFFTAG_SAMPLEFORMAT; count = theInputConnection->getNumberOfOutputBands(); type = ossim::OTIFF_SHORT; value_ui16 = getTiffSampleFormat(); if ( count == 1 ) { writeTiffTag( tag, type, count, &value_ui16, arrayWritePos ); } else { std::vector v(count, value_ui16); writeTiffTag( tag, type, count, &v.front(), arrayWritePos ); } ++tagCount; // Writes two tags 340 and 341 (conditional on scalar type): if ( writeSMinSMaxTiffTags( minBands, maxBands, arrayWritePos ) == true ) { tagCount += 2; } // Write geo keys if valid map projection: if ( mapProj.valid() ) { std::vector vf; ossimDpt scale; ossimDpt tie; if ( mapProj->isGeographic() ) { ossimGpt gpt; mapProj->lineSampleToWorld( theAreaOfInterest.ul(), gpt ); tie.x = gpt.lon; tie.y = gpt.lat; scale = mapProj->getDecimalDegreesPerPixel(); } else { mapProj->lineSampleToEastingNorthing( theAreaOfInterest.ul(), tie ); scale = mapProj->getMetersPerPixel(); } // Need to decide whehter to specify the full 4x4 model transform (in the case of a rotated // image), or simply use scale and offset tags: if (mapProj->isRotated()) { // Model transform needed -- tag 34264: auto transform = mapProj->getModelTransform(); count = 16; // 4x4 transform matrix tag = ossim::OMODEL_TRANSFORM_TAG; type = ossim::OTIFF_DOUBLE; vf.resize( count ); auto m = transform.getData(); for (int i=0; i<(int)count; ++i) vf.emplace_back(m[i/4][i%4]); writeTiffTag( tag, type, count, &vf.front(), arrayWritePos ); ++tagCount; } else { // model pixel scale tag 33550: tag = ossim::OMODEL_PIXEL_SCALE_TAG; count = 3; // x, y, z type = ossim::OTIFF_DOUBLE; vf.resize(count); vf[0] = scale.x; vf[1] = scale.y; vf[2] = 0.0; writeTiffTag(tag, type, count, &vf.front(), arrayWritePos); ++tagCount; // model tie point tag 33992: tag = ossim::OMODEL_TIE_POINT_TAG; count = 6; // x, y, z type = ossim::OTIFF_DOUBLE; vf.resize(count); vf[0] = 0.0; // x image point vf[1] = 0.0; // y image point vf[2] = 0.0; // z image point vf[3] = tie.x; // longitude or easting vf[4] = tie.y; // latitude of northing vf[5] = 0.0; writeTiffTag(tag, type, count, &vf.front(), arrayWritePos); ++tagCount; } // geo key directory tag 34735: tag = ossim::OGEO_KEY_DIRECTORY_TAG; count = 0; // set later. type = ossim::OTIFF_SHORT; std::vector vs(0); // No vs.push_back(1); vs.push_back(1); vs.push_back(0); vs.push_back(10); // Updated later. vs.push_back(ossim::OGT_MODEL_TYPE_GEO_KEY); // 1024 vs.push_back(0); vs.push_back(1); vs.push_back(mapProj->isGeographic() ? ossim::OMODEL_TYPE_GEOGRAPHIC : ossim::OMODEL_TYPE_PROJECTED); vs.push_back(ossim::OGT_RASTER_TYPE_GEO_KEY); // 1025 vs.push_back(0); vs.push_back(1); vs.push_back(ossim::OPIXEL_IS_POINT); if ( mapProj->isGeographic() ) { vs.push_back(ossim::OGEOGRAPHIC_TYPE_GEO_KEY); // 2048 vs.push_back(0); vs.push_back(1); vs.push_back((ossim_uint16)(mapProj->getPcsCode())); } vs.push_back(ossim::OGEOG_GEODETIC_DATUM_GEO_KEY); // 2050 vs.push_back(0); vs.push_back(1); vs.push_back((ossim_uint16)(mapProj->getDatum()->epsgCode())); if ( mapProj->isGeographic() ) { vs.push_back(ossim::OGEOG_ANGULAR_UNITS_GEO_KEY); // 2054 vs.push_back(0); vs.push_back(1); vs.push_back(ossim::OANGULAR_DEGREE); } vs.push_back(ossim::OGEOG_ELLIPSOID_GEO_KEY); // 2056 vs.push_back(0); vs.push_back(1); vs.push_back((ossim_uint16)(mapProj->getDatum()->ellipsoid()->getEpsgCode())); // Stored in external OOGEO_DOUBLE_PARAMS_TAG vs.push_back(ossim::OGEOG_SEMI_MAJOR_AXIS); // 2057 vs.push_back(ossim::OGEO_DOUBLE_PARAMS_TAG); vs.push_back(1); vs.push_back(0); vs.push_back(ossim::OGEOG_SEMI_MINOR_AXIS); // 2058 vs.push_back(ossim::OGEO_DOUBLE_PARAMS_TAG); vs.push_back(1); vs.push_back(1); vs.push_back(ossim::OPROJECTED_CS_TYPE_GEO_KEY); // 3072 vs.push_back(0); vs.push_back(1); vs.push_back((ossim_uint16)(mapProj->getPcsCode())); vs.push_back(ossim::OPROJECTION_GEO_KEY); // 3074 vs.push_back(0); vs.push_back(1); vs.push_back((ossim_uint16)(mapProj->getPcsCode())); if ( mapProj->isGeographic() == false ) { vs.push_back(ossim::OPROJ_LINEAR_UNITS_GEO_KEY); // 3076 vs.push_back(0); vs.push_back(1); vs.push_back(ossim::OLINEAR_METER); } count = vs.size(); vs[3] = (count / 4) - 1; writeTiffTag( tag, type, count, &vs.front(), arrayWritePos ); ++tagCount; // geo double params tag 33550: tag = ossim::OGEO_DOUBLE_PARAMS_TAG; count = 2; // ellipsoid major, minor axis type = ossim::OTIFF_DOUBLE; vf.resize( count ); vf[0] = mapProj->getDatum()->ellipsoid()->a(); vf[1] = mapProj->getDatum()->ellipsoid()->b(); writeTiffTag( tag, type, count, &vf.front(), arrayWritePos ); ++tagCount; } // Write trailing zero indicading no more IFDs. ossim_uint64 offsetToNextIfd = 0; m_str->write( (const char*)&offsetToNextIfd, 8 ); // Seek back and re-write the tag count. m_str->seekp( 16, std::ios_base::beg ); m_str->write( (const char*)&tagCount, 8 ); status = m_str->good(); return status; } bool ossimWriter::writeMinMaxTiffTags( std::streamoff& arrayWritePos ) { bool status = true; // DEFAULT for OSSIM_UINT32. ossim_uint16 minValue = 1; ossim_uint16 maxValue = 255; switch( theInputConnection->getOutputScalarType() ) { case OSSIM_UINT8: { break; // defaulted above } case OSSIM_USHORT11: { maxValue = 2047; break; } case OSSIM_USHORT12: { maxValue = 4095; break; } case OSSIM_USHORT13: { maxValue = 8191; break; } case OSSIM_USHORT14: { maxValue = 16383; break; } case OSSIM_USHORT15: { maxValue = 32767; break; } case OSSIM_UINT16: { maxValue = 65535; break; } default: status = false; } if ( status ) { writeTiffTag( ossim::OTIFFTAG_MINSAMPLEVALUE, ossim::OTIFF_SHORT, 1, &minValue, arrayWritePos ); writeTiffTag( ossim::OTIFFTAG_MAXSAMPLEVALUE, ossim::OTIFF_SHORT, 1, &maxValue, arrayWritePos ); } return status; } bool ossimWriter::writeSMinSMaxTiffTags( const vector& minBands, const vector& maxBands, std::streamoff& arrayWritePos ) { bool status = false; if(minBands.size() && maxBands.size()) { ossim_float64 minValue = *std::min_element(minBands.begin(), minBands.end()); ossim_float64 maxValue = *std::max_element(maxBands.begin(), maxBands.end()); switch( theInputConnection->getOutputScalarType() ) { case OSSIM_SINT16: case OSSIM_UINT32: case OSSIM_FLOAT32: case OSSIM_FLOAT64: case OSSIM_NORMALIZED_FLOAT: case OSSIM_NORMALIZED_DOUBLE: { ossim_float32 v = static_cast(minValue); writeTiffTag( ossim::OTIFFTAG_SMINSAMPLEVALUE, ossim::OTIFF_FLOAT, 1, &v, arrayWritePos ); v = static_cast(maxValue); writeTiffTag( ossim::OTIFFTAG_SMAXSAMPLEVALUE, ossim::OTIFF_FLOAT, 1, &v, arrayWritePos ); status = true; break; } default: { break; } } } return status; } template void ossimWriter::writeTiffTag( ossim_uint16 tag, ossim_uint16 type, ossim_uint64 count, const T* value, std::streamoff& arrayWritePos ) { m_str->write( (const char*)&tag, 2 ); m_str->write( (const char*)&type, 2 ); m_str->write( (const char*)&count, 8 ); ossim_uint64 bytes = sizeof( T ) * count; if ( bytes <= 8 ) { m_str->write( (const char*)value, bytes ); if ( bytes < 8 ) { // Fill remaining bytes with 0. char c = '\0'; m_str->write( (const char*)&c, (8-bytes) ); } } else // Greater than 8 bytes, must write at end of file. { // Store the offset to array: m_str->write( (const char*)&arrayWritePos, 8 ); // Capture posistion: std::streamoff currentPos = m_str->tellp(); // Seek to end: m_str->seekp( arrayWritePos, std::ios_base::beg ); // Write: m_str->write( (const char*)value, bytes ); // Capture new offset for next array write. arrayWritePos = m_str->tellp(); // Seek back: m_str->seekp( currentPos, std::ios_base::beg ); } } bool ossimWriter::writeTiffTilesBandSeparate( std::vector& tile_offsets, std::vector& tile_byte_counts, std::vector& minBands, std::vector& maxBands ) { static const char* const MODULE = "ossimWriter::writeToTilesBandSeparate"; if ( traceDebug() ) CLOG << " Entered...\n"; // Start the sequence at the first tile. theInputConnection->setToStartOfSequence(); // Control flags: bool alignTiles = getAlignTilesFlag(); bool flushTiles = getFlushTilesFlag(); bool writeBlanks = getWriteBlanksFlag(); bool computeMinMax = needsMinMax(); // Block size for write: const std::streamsize BLOCK_SIZE = getBlockSize(); const ossim_int32 BANDS = (ossim_int32)theInputConnection->getNumberOfOutputBands(); const ossim_int32 TILES_WIDE = (ossim_int32)theInputConnection->getNumberOfTilesHorizontal(); const ossim_int32 TILES_TOTAL = (ossim_int32)theInputConnection->getNumberOfTiles(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "align tiles flag: " << alignTiles << "\nflush tiles flag: " << flushTiles << "\nwrite blanks flag: " << writeBlanks << "\ncompute min max flag: " << computeMinMax << "\nwrite block size: " << BLOCK_SIZE << "\nBANDS: " << BANDS << "\nTILES_WIDE: " << TILES_WIDE << "\nTILES_TOTAL: " << TILES_TOTAL << "\n"; } tile_offsets.resize( TILES_TOTAL*BANDS ); tile_byte_counts.resize( TILES_TOTAL*BANDS ); ossimDataObjectStatus tileStatus = OSSIM_STATUS_UNKNOWN; ossim_int64 ossimTileIndex = 0; ossim_int64 tiffTileIndex = 0; ossim_int64 tileSizeInBytes = 0; ossim_int64 bandOffsetInBytes = 0; //--- // Adjust the starting file position to make room for IFD tags, tile offset // and tile byte counts and arrays. // // Assuming: // IFD start = 16, end 512, gives 496 bytes for tags. // Array section start = 512, end is start + (16 * tile_count * bands) + 256 bytes // for geotiff array bytes. //--- std::streamsize startPos = 512 + 16 * TILES_TOTAL * BANDS + 256; while ( ossimTileIndex < TILES_TOTAL ) { ossimRefPtr id = theInputConnection->getNextTile(); if(!id) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:" << "Error returned writing tiff tile: " << ossimTileIndex << "\nNULL Tile from input encountered" << std::endl; return false; } tileStatus = id->getDataObjectStatus(); if ( ossimTileIndex == 0 ) { tileSizeInBytes = (ossim_int64)id->getSizePerBandInBytes(); bandOffsetInBytes = tileSizeInBytes * TILES_TOTAL; } if ( computeMinMax ) { if ( (tileStatus == OSSIM_FULL) || (tileStatus == OSSIM_PARTIAL) ) { // Compute running min, max. id->computeMinMaxPix(minBands, maxBands); } } // Band loop. for (ossim_int32 band=0; band < BANDS; ++band) { tiffTileIndex = ossimTileIndex + band * TILES_TOTAL; if ( (writeBlanks == true) || (tileStatus == OSSIM_FULL) || (tileStatus == OSSIM_PARTIAL) ) { // Grab a pointer to the tile for the band. const char* data = (const char*)id->getBuf(band); // Compress data here(future maybe, i.e. jpeg, j2k... //--- // Write the tile. // Note: tiles laid out, all the red tiles, all the green tiles all the // blue tiles. //--- if(data) { // Compute the stream position: std::streampos pos = startPos + ossimTileIndex * tileSizeInBytes + band * bandOffsetInBytes; if ( alignTiles ) { // Snap to block boundary: std::streampos overflow = pos % BLOCK_SIZE; if ( overflow > 0 ) { pos += BLOCK_SIZE - overflow; } } m_str->seekp( pos ); if ( m_str->good() ) { tile_offsets[ tiffTileIndex ] = (ossim_uint64)pos; tile_byte_counts[ tiffTileIndex ] = (ossim_uint64)tileSizeInBytes; // Write the tile to stream: m_str->write( data, (std::streamsize)tileSizeInBytes); if ( flushTiles ) { m_str->flush(); } // Check stream: if ( m_str->fail() == true ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:\nWrite error on tiff tile: " << ossimTileIndex << std::endl; return false; } } else { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " ERROR:\nStream has gone bad!" << std::endl; return false; } } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\nNull input tile: " << ossimTileIndex << std::endl; return false; } } else { //--- // Writing sparse tiff. // Set the offset and byte count to 0 to indicate blank tile. //--- if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "sparse blank tile[" << tiffTileIndex << "]: " << tiffTileIndex << "\n"; } tile_offsets[ tiffTileIndex ] = 0; tile_byte_counts[ tiffTileIndex ] = 0; } } // End of band loop. ++ossimTileIndex; if( needsAborting() ) { setPercentComplete(100); break; // Get out... } else if ( ossimTileIndex % TILES_WIDE ) { // Output percent complete every row of tiles. double tileNum = ossimTileIndex; double numTiles = TILES_TOTAL; setPercentComplete(tileNum / numTiles * 100.0); } } // End: while ( ossimTileIndex < TILES_TOTAL ) if ( traceDebug() ) CLOG << " Exited...\n"; return m_str->good(); } bool ossimWriter::setOutputStream(std::ostream& stream) { if (m_ownsStreamFlag && m_str) { delete m_str; } m_str = &stream; m_ownsStreamFlag = false; return true; } void ossimWriter::setTileSize(const ossimIpt& tileSize) { if ( (tileSize.x % 16) || (tileSize.y % 16) ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimWriter::setTileSize ERROR:" << "\nTile size must be a multiple of 16!" << "\nSize remains: " << m_outputTileSize << std::endl; } } else { m_outputTileSize = tileSize; // For save state: m_kwl->addPair( TILE_SIZE_KW, m_outputTileSize.toString().string() ); } } const ossimIpt& ossimWriter::getOutputTileSize() const { return m_outputTileSize; } bool ossimWriter::saveState( ossimKeywordlist& kwl, const char* prefix) const { // Lazy man save state... kwl.add( prefix, *(m_kwl.get()), true ); return ossimImageFileWriter::saveState(kwl, prefix); } bool ossimWriter::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; if ( ossimImageFileWriter::loadState(kwl, prefix) ) { if ( theOutputImageType!="ossim_ttbs") { result = true; std::string pfx = prefix?prefix:""; std::string value; value = kwl.findKey( pfx, ALIGN_TILES_KW ); if ( value.size() ) { m_kwl->addPair( ALIGN_TILES_KW, value, true ); } value = kwl.findKey( pfx, BLOCK_SIZE_KW ); if ( value.size() ) { m_kwl->addPair( BLOCK_SIZE_KW, value, true ); } value = kwl.findKey( pfx, FLUSH_TILES_KW ); if ( value.size() ) { m_kwl->addPair( FLUSH_TILES_KW, value, true ); } value = kwl.findKey( pfx, INCLUDE_BLANK_TILES_KW ); if ( value.size() ) { m_kwl->addPair( INCLUDE_BLANK_TILES_KW, value, true ); } value = kwl.findKey( pfx, TILE_SIZE_KW ); if ( value.size() ) { m_outputTileSize.toPoint(value); m_kwl->addPair( TILE_SIZE_KW, m_outputTileSize.toString().string(), true ); } } } return result; } void ossimWriter::setProperty(ossimRefPtr property) { if( property.valid() ) { // See if it's one of our properties: std::string key = property->getName().string(); if ( traceDebug() ) { ossimString value; property->valueToString(value); ossimNotify(ossimNotifyLevel_DEBUG) << "ossimWriter::setProperty DEBUG:" << "\nkey: " << key << "\nvalue: " << value << "\n"; } if ( ( key == ALIGN_TILES_KW ) || ( key == BLOCK_SIZE_KW ) || ( key == FLUSH_TILES_KW ) || ( key == INCLUDE_BLANK_TILES_KW ) ) { ossimString value; property->valueToString(value); m_kwl->addPair( key, value.string(), true ); } else if ( key == TILE_SIZE_KW ) { // Comes in as a single int, e.g.: 256 ossimString value; property->valueToString(value); m_outputTileSize.x = value.toInt32(); m_outputTileSize.y = m_outputTileSize.x; // Store in keywordlist / save state as a point, e.g.: ( 256, 256 ) m_kwl->addPair( key, m_outputTileSize.toString().string(), true ); } else { ossimImageFileWriter::setProperty(property); } } } ossimRefPtr ossimWriter::getProperty(const ossimString& name)const { ossimRefPtr prop = 0; if ( name.string() == ALIGN_TILES_KW ) { std::string value = m_kwl->findKey( ALIGN_TILES_KW ); ossimRefPtr boolProp = new ossimBooleanProperty(name, ossimString(value).toBool()); prop = boolProp.get(); } else if( name == BLOCK_SIZE_KW ) { // Property a single int, e.g.: 4096 ossim_int64 blockSize = getBlockSize(); ossimRefPtr stringProp = new ossimStringProperty(name, ossimString::toString(blockSize), false); // editable flag prop = stringProp.get(); } else if ( name.string() == FLUSH_TILES_KW ) { std::string value = m_kwl->findKey( FLUSH_TILES_KW ); ossimRefPtr boolProp = new ossimBooleanProperty(name, ossimString(value).toBool()); prop = boolProp.get(); } else if ( name.string() == INCLUDE_BLANK_TILES_KW ) { std::string value = m_kwl->findKey( INCLUDE_BLANK_TILES_KW ); ossimRefPtr boolProp = new ossimBooleanProperty(name, ossimString(value).toBool()); prop = boolProp.get(); } else if( name == TILE_SIZE_KW ) { // Property a single int, e.g.: 256 ossimRefPtr stringProp = new ossimStringProperty(name, ossimString::toString(m_outputTileSize.x), false); // editable flag stringProp->setReadOnlyFlag(false); stringProp->setChangeType(ossimProperty::ossimPropertyChangeType_AFFECTS_OTHERS); stringProp->addConstraint(ossimString("16")); stringProp->addConstraint(ossimString("32")); stringProp->addConstraint(ossimString("64")); stringProp->addConstraint(ossimString("128")); stringProp->addConstraint(ossimString("256")); stringProp->addConstraint(ossimString("512")); stringProp->addConstraint(ossimString("1024")); stringProp->addConstraint(ossimString("2048")); prop = stringProp.get(); } else { prop = ossimImageFileWriter::getProperty(name); } return prop; } void ossimWriter::getPropertyNames(std::vector& propertyNames) const { propertyNames.push_back(ossimString(ALIGN_TILES_KW)); propertyNames.push_back(ossimString(BLOCK_SIZE_KW)); propertyNames.push_back(ossimString(FLUSH_TILES_KW)); propertyNames.push_back(ossimString(INCLUDE_BLANK_TILES_KW)); propertyNames.push_back(ossimString(TILE_SIZE_KW)); ossimImageFileWriter::getPropertyNames(propertyNames); } ossim_uint16 ossimWriter::getTiffSampleFormat() const { ossim_uint16 result = 0; switch( theInputConnection->getOutputScalarType() ) { case OSSIM_UINT8: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: case OSSIM_UINT32: result = ossim::OSAMPLEFORMAT_UINT; break; case OSSIM_SINT16: result = ossim::OSAMPLEFORMAT_INT; break; case OSSIM_FLOAT32: case OSSIM_FLOAT64: case OSSIM_NORMALIZED_FLOAT: case OSSIM_NORMALIZED_DOUBLE: result = ossim::OSAMPLEFORMAT_IEEEFP; break; default: break; } return result; } bool ossimWriter::isTiled() const { return ( theOutputImageType == "ossim_ttbs" ); } bool ossimWriter::getAlignTilesFlag() const { bool result = true; // default std::string value = m_kwl->findKey( ALIGN_TILES_KW ); if ( value.size() ) { result = ossimString(value).toBool(); } return result; } ossim_int64 ossimWriter::getBlockSize() const { ossim_int64 result = 4096; // default std::string value = m_kwl->findKey( BLOCK_SIZE_KW ); if ( value.size() ) { result = ossimString(value).toInt64(); // Disallow anything not on 1024 boundary. if ( result % 1024 ) { result = 4096; ossimNotify(ossimNotifyLevel_DEBUG) << "ossimWriter::getBlockSize ERROR:" << "\nBlock size MUST be a multiple of 1024!" << "\nBlock size remains: " << result << std::endl; } } return result; } bool ossimWriter::getFlushTilesFlag() const { bool result = true; // default std::string value = m_kwl->findKey( FLUSH_TILES_KW ); if ( value.size() ) { result = ossimString(value).toBool(); } return result; } bool ossimWriter::getWriteBlanksFlag() const { bool result = true; // default std::string value = m_kwl->findKey( INCLUDE_BLANK_TILES_KW ); if ( value.size() ) { result = ossimString(value).toBool(); } return result; } bool ossimWriter::needsMinMax() const { bool result = false; switch( theInputConnection->getOutputScalarType() ) { case OSSIM_SINT16: case OSSIM_UINT32: case OSSIM_FLOAT32: case OSSIM_FLOAT64: case OSSIM_NORMALIZED_FLOAT: case OSSIM_NORMALIZED_DOUBLE: { result = true; break; } default: { break; } } return result; } ossim-Miami-2.9.1/src/init/000077500000000000000000000000001352751253100154455ustar00rootroot00000000000000ossim-Miami-2.9.1/src/init/JsonConfig.cpp000066400000000000000000000310441352751253100202120ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include using namespace std; namespace ossim { JsonParam JsonConfig::s_nullParam; JsonParam::JsonParam(const ossimString& argname, const ossimString& arglabel, const ossimString& argdescr, ParamType argparamType, void* value) : _name (argname), _label (arglabel), _descr (argdescr), _type (argparamType), _value(0) { setValue(value); } JsonParam::JsonParam(const JsonParam& copy) : _label (copy._label), _name (copy._name), _descr (copy._descr), _type (copy._type), _value (0), _allowedValues (copy._allowedValues) { setValue(copy._value); } void JsonParam::setValue(void* value) { if (!value) return; switch (_type) { case JsonParam::BOOL: _value = new bool; memcpy(_value, value, sizeof(bool)); break; case JsonParam::INT: _value = new int; memcpy(_value, value, sizeof(int)); break; case JsonParam::UINT: _value = new unsigned int; memcpy(_value, value, sizeof(unsigned int)); break; case JsonParam::FLOAT: _value = new double; memcpy(_value, value, sizeof(double)); break; case JsonParam::STRING: _value = new string(*(string*)(value)); break; case JsonParam::VECTOR: _value = new vector(*(vector*)(value)); break; default: _value = 0; } } void JsonParam::resetValue() { if (!_value) return; switch (_type) { case JsonParam::BOOL: delete (bool*)_value; break; case JsonParam::INT: case JsonParam::UINT: delete (int*)_value; break; case JsonParam::FLOAT: delete (double*)_value; break; case JsonParam::STRING: delete (string*)_value; break; case JsonParam::VECTOR: ((vector*)_value)->clear(); delete (vector*)_value; break; default: break; } _value = 0; } bool JsonParam::loadJSON(const Json::Value& paramNode) { try { _name = paramNode["name"].asString(); _label = paramNode["label"].asString(); _descr = paramNode["descr"].asString(); Json::Value value = paramNode["value"]; Json::Value allowedValues = paramNode["allowedValues"]; ossimString ptype = paramNode["type"].asString(); if (ptype.empty() || _name.empty()) return false; ptype.upcase(); if (ptype == "VECTOR") { _type = JsonParam::VECTOR; vector v; if (value.isArray()) { int n = value.size(); for (unsigned int j=0; j."<& v = *(vector*)_value; // maybe not used since maybe not valid cast unsigned int n = 0; int i; double f; string s; bool b; paramNode["name"] = _name.string(); paramNode["label"] = _label.string(); paramNode["descr"] = _descr.string(); switch (_type) { case JsonParam::BOOL: paramNode["type"] = "bool"; b = *(bool*)_value; paramNode["value"] = b; break; case JsonParam::INT: paramNode["type"] = "int"; i = *(int*)_value; paramNode["value"] = i; break; case JsonParam::UINT: paramNode["type"] = "uint"; n = *(unsigned int*)_value; paramNode["value"] = n; break; case JsonParam::FLOAT: paramNode["type"] = "float"; f = *(double*)_value; paramNode["value"] = f; break; case JsonParam::STRING: paramNode["type"] = "string"; s = *(string*)_value; paramNode["value"] = s; if (!_allowedValues.empty()) { Json::Value allowedValues(Json::arrayValue); for (const auto &allowedValue : _allowedValues) allowedValues.append(allowedValue.c_str()); paramNode["allowedValues"] = allowedValues; } break; case JsonParam::VECTOR: paramNode["type"] = "vector"; n = v.size(); for (unsigned int j=0; j& v) const { v.clear(); if (_type == VECTOR) v = *(vector*)_value; } ostream& operator<<(std::ostream& out, const JsonParam& obj) { Json::Value jsonNode; obj.saveJSON(jsonNode); out << jsonNode << endl; return out; } //------------------------------------------------------------- JsonConfig::JsonConfig() { // This ctor could eventually curl a spring config server for the param JSON. For now it // is reading the installed share/ossim system directory for config JSON files. // The previous parameters list is cleared first for a fresh start: m_paramsMap.clear(); ossimFilename configFilename; try { // First establish the directory location of the default config files: ossimFilename shareName (ossimPreferences::instance()-> preferencesKWL().findKey( std::string( "ossim_share_directory" ))); if (!shareName.isDir()) throw ossimException("Nonexistent share drive provided for config files."); // Fetch all JSON files: ossimDirectory shareDir; if (!shareDir.open(shareName)) throw ossimException("Share drive provided for config files is not readable."); std::vector jsonFiles; shareDir.findAllFilesThatMatch(jsonFiles, ".*\\.json"); // Process those that contain the "parameters" JSON node: for (unsigned int i=0; i. Error: "<> jsonRoot; if (jsonRoot.empty()) return false; if (jsonRoot.isMember("parameters")) { Json::Value& paramsNode = jsonRoot["parameters"]; loadJSON(paramsNode); } configFile.close(); return true; } JsonParam& JsonConfig::getParameter(const char* paramName) { map::iterator i = m_paramsMap.find(string(paramName)); if (i != m_paramsMap.end()) return i->second; return s_nullParam; } void JsonConfig::setParameter(const JsonParam& p) { // Tricky stuff to make sure it is a deep copy of the parameter: string key = p.name().string(); std::map::iterator iter = m_paramsMap.find(key); if (iter != m_paramsMap.end()) m_paramsMap.erase(key); m_paramsMap.emplace(key, p); } bool JsonConfig::paramExists(const char* paramName) const { auto i = m_paramsMap.find(string(paramName)); if (i != m_paramsMap.end()) return true; return false; } void JsonConfig::loadJSON(const Json::Value& json_node) { // Support two forms: long (with full param descriptions and types), or short (just name: value) if (json_node.isArray()) { // Long form: for (const auto &i : json_node) { JsonParam p; if (p.loadJSON(i)) setParameter(p); } } else { // Short form expects a prior entry in the params map whose value will be overriden here: Json::Value::Members members = json_node.getMemberNames(); for (auto &member : members) { JsonParam& p = getParameter(member.c_str()); if (p.name().empty()) { ossimNotify(ossimNotifyLevel_WARN)<<"JsonConfig::loadJSON(): Attempted to override " "nonexistent parameter <"<< member << ">. Ignoring request."<::const_iterator param = m_paramsMap.begin(); int entry = 0; while (param != m_paramsMap.end()) { Json::Value paramNode; param->second.saveJSON(paramNode); json_node[entry++] = paramNode; ++param; } } bool JsonConfig::diagnosticLevel(unsigned int level) const { map::const_iterator i = m_paramsMap.find(string("diagnosticLevel")); if (i != m_paramsMap.end()) { unsigned int levelSetting = i->second.asUint(); return (level <= levelSetting); } return false; } std::ostream& operator<<(std::ostream& out, const JsonConfig& obj) { Json::Value configJsonNode; obj.saveJSON(configJsonNode); out< #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceExec = ossimTrace("ossimInit:exec"); static ossimTrace traceDebug = ossimTrace("ossimInit:debug"); ossimInit* ossimInit::theInstance = 0; ossimInit::~ossimInit() { theInstance = 0; } ossimInit::ossimInit() : theInitializedFlag(false), theAppName(), thePreferences(0), // Delay instance() call until stream factory init. theElevEnabledFlag(true), thePluginLoaderEnabledFlag(true) { } ossimInit* ossimInit::instance() { static std::mutex m; std::lock_guard lock(m); if (!theInstance) { theInstance = new ossimInit(); } return theInstance; } void ossimInit::addOptions(ossimArgumentParser& parser) { parser.getApplicationUsage()->addCommandLineOption("--env", "Specify an env variable to set. Any number of these can appear with format --env VARIABLE=VALUE"); parser.getApplicationUsage()->addCommandLineOption("-P", "specify a preference file to load"); parser.getApplicationUsage()->addCommandLineOption("-K", "specify individual keywords to add to the preferences keyword list: name=value"); parser.getApplicationUsage()->addCommandLineOption("-T", "specify the classes to trace, ex: ossimInit|ossimImage.* \nwill trace ossimInit and all ossimImage classes"); parser.getApplicationUsage()->addCommandLineOption("--disable-elev", "Will disable the elevation"); parser.getApplicationUsage()->addCommandLineOption("--disable-plugin", "Will disable the plugin loader"); parser.getApplicationUsage()->addCommandLineOption("--ossim-logfile", "takes a logfile as an argument. All output messages are redirected to the specified log file. By default there is no log file and all messages are enabled."); parser.getApplicationUsage()->addCommandLineOption("--disable-notify", "Takes an argument. Arguments are ALL, WARN, NOTICE, INFO, FATAL, DEBUG. If you want multiple disables then just do multiple --disable-notify on the command line. All argument are case insensitive. Default is all are enabled."); } /*!**************************************************************************** * METHOD: ossimInit::initialize() * * Method called from the OSSIM application main. * *****************************************************************************/ void ossimInit::initialize(int& argc, char** argv) { static std::mutex m; std::lock_guard lock(m); if( !theInitializedFlag ) { ossimArgumentParser argumentParser(&argc, argv); theInstance->initialize(argumentParser); } } void ossimInit::initialize(ossimArgumentParser& parser) { static std::mutex m; std::lock_guard lock(m); if(theInitializedFlag) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimInit::initialize(parser):" << " Already initialized, returning......" << std::endl; } return; } theInstance->parseEnvOptions(parser); theInstance->parseNotifyOption(parser); theInstance->parsePrefsOptions(parser); theInstance->theAppName = parser.getApplicationUsage()->getApplicationName(); //Parse the command line: theInstance->parseOptions(parser); // we will also support defining a trace pattern from an Environment // variable. This will make JNI code easier to enable tracing // ossimString traceVariable = ossimEnvironmentUtility::instance()->getEnvironmentVariable("OSSIM_TRACE"); if(!traceVariable.empty()) { ossimTraceManager::instance()->setTracePattern(traceVariable); } theInstance->initializeDefaultFactories(); if ( theElevEnabledFlag ) { theInstance->initializeElevation(); } theInstance->initializeLogFile(); if(thePluginLoaderEnabledFlag) { theInstance->initializePlugins(); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossim preferences file: " << theInstance->thePreferences->getPreferencesFilename() << "\nVersion: " << version() << "\nossimInit::initialize(parser): leaving..." << std::endl; } theInitializedFlag = true; } void ossimInit::initialize() { if(theInitializedFlag) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimInit::initialize(parser):" << " Already initialized, returning......" << std::endl; } return; } int argc = 1; char* argv[1]; argv[0] = new char[1]; argv[0][0] = '\0'; initialize(argc, argv); delete [] argv[0]; #if 0 static std::mutex m; std::lock_guard lock(m); if(theInitializedFlag) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimInit::initialize(): Already initialized, returning......" << std::endl; } return; } theInstance->theAppName = ""; theInstance->thePreferences = ossimPreferences::instance(); theInstance->initializeDefaultFactories(); if ( theElevEnabledFlag ) { theInstance->initializeElevation(); } theInstance->initializeLogFile(); //--- // To do: // We need a mechanism to register factories to the "front" or the // "back" of factory list so that plugins can override things. For // now we will initialize the plugins last... //--- if(thePluginLoaderEnabledFlag) { theInstance->initializePlugins(); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossim preferences file: " << theInstance->thePreferences->getPreferencesFilename() << "\nVersion: " << version() << "\nossimInit::initialize() leaving..." << std::endl; } theInitializedFlag = true; #endif } void ossimInit::finalize() { } /*!**************************************************************************** * Prints to stdout the list of command line options that this object parses. *****************************************************************************/ void ossimInit::usage() { ossimNotify(ossimNotifyLevel_INFO) << "INFORMATION ossimInit::usage():\n" << "Additional command-line options available are as follows: " << "\n" << "\n -P -- Allows the user to override the loading " << "\n of the default preferences with their own pref file." << "\n" << "\n -K[=] -- Allows the user to specify additional" << "\n keyword/value pairs that are added onto the preferences " << "\n previously loaded. Keywords specified here override those in" << "\n the preferences file." << "\n" << "\n -T -- Lets user turn on specific trace flags." << "\n" << "\n -S -- Allows user to specify a session file" << "\n to load." << std::endl; return; } bool ossimInit::getElevEnabledFlag() const { return theElevEnabledFlag; } void ossimInit::setElevEnabledFlag(bool flag) { theElevEnabledFlag = flag; } void ossimInit::setPluginLoaderEnabledFlag(bool flag) { thePluginLoaderEnabledFlag = flag; } void ossimInit::loadPlugins(const ossimFilename& plugin, const char* options) { if(!thePluginLoaderEnabledFlag) return; if(plugin.exists()) { if(plugin.isDir()) { ossimDirectory dir; if(dir.open(plugin)) { ossimFilename file; if(dir.getFirst(file, ossimDirectory::OSSIM_DIR_FILES)) { do { ossimSharedPluginRegistry::instance()->registerPlugin(file, options); } while(dir.getNext(file)); } } } else { ossimSharedPluginRegistry::instance()->registerPlugin(plugin, options); } } } void ossimInit::parsePrefsOptions(ossimArgumentParser& parser) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimInit::parseOptions: entering..." << std::endl; std::string tempString; ossimArgumentParser::ossimParameter stringParameter(tempString); tempString = ""; ossimString prefsFile = ossimEnvironmentUtility::instance()->getEnvironmentVariable("OSSIM_PREFS_FILE"); theInstance->thePreferences = ossimPreferences::instance(); if(!prefsFile.empty()) { thePreferences->loadPreferences();// Use the default load } tempString = ""; // override ENV with passed in variable while(parser.read("-P", stringParameter)); if(tempString != "") { thePreferences->loadPreferences(ossimFilename(tempString)); } tempString = ""; while(parser.read("-K", stringParameter)) { ossimString option = tempString; if (option.contains("=") ) { ossimString delimiter = "="; ossimString key (option.before(delimiter)); ossimString value = option.after(delimiter); thePreferences->addPreference(key.c_str(), value.c_str()); } else { ossimString key (option); thePreferences->addPreference(key, ""); } } } void ossimInit::parseOptions(ossimArgumentParser& parser) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimInit::parseOptions: entering..." << std::endl; std::string tempString; ossimArgumentParser::ossimParameter stringParameter(tempString); tempString = ""; while(parser.read("-T", stringParameter)) { ossimTraceManager::instance()->setTracePattern(ossimString(tempString)); } while(parser.read("--ossim-logfile", stringParameter)) { ossimSetLogFilename(ossimFilename(tempString)); } while(parser.read("--disable-notify", stringParameter)) { ossimString tempDownCase = tempString; tempDownCase = tempDownCase.downcase(); if(tempDownCase == "warn") { ossimDisableNotify(ossimNotifyFlags_WARN); } else if(tempDownCase == "fatal") { ossimDisableNotify(ossimNotifyFlags_FATAL); } else if(tempDownCase == "debug") { ossimDisableNotify(ossimNotifyFlags_DEBUG); } else if(tempDownCase == "info") { ossimDisableNotify(ossimNotifyFlags_INFO); } else if(tempDownCase == "notice") { ossimDisableNotify(ossimNotifyFlags_NOTICE); } else if(tempDownCase == "all") { ossimDisableNotify(ossimNotifyFlags_ALL); } } if(parser.read("--disable-elev")) { theElevEnabledFlag = false; } if(parser.read("--disable-plugin")) { thePluginLoaderEnabledFlag = false; } } void ossimInit::parseNotifyOption(ossimArgumentParser& parser) { std::string tempString; ossimArgumentParser::ossimParameter stringParameter(tempString); while(parser.read("--disable-notify", stringParameter)) { ossimString tempDownCase = tempString; tempDownCase = tempDownCase.downcase(); if(tempDownCase == "warn") { ossimDisableNotify(ossimNotifyFlags_WARN); } else if(tempDownCase == "fatal") { ossimDisableNotify(ossimNotifyFlags_FATAL); } else if(tempDownCase == "debug") { ossimDisableNotify(ossimNotifyFlags_DEBUG); } else if(tempDownCase == "info") { ossimDisableNotify(ossimNotifyFlags_INFO); } else if(tempDownCase == "notice") { ossimDisableNotify(ossimNotifyFlags_NOTICE); } else if(tempDownCase == "all") { ossimDisableNotify(ossimNotifyFlags_ALL); } } } void ossimInit::parseEnvOptions(ossimArgumentParser& parser) { std::string tempString; ossimArgumentParser::ossimParameter stringParameter(tempString); while(parser.read("--env", stringParameter)) { ossimString option = tempString; if (option.contains("=") ) { ossimString delimiter = "="; ossimString key (option.before(delimiter)); ossimString value = option.after(delimiter); ossimEnvironmentUtility::instance()->setEnvironmentVariable(key.c_str(), value.c_str()); } else { ossimString key (option); ossimEnvironmentUtility::instance()->setEnvironmentVariable(key.c_str(), ""); } } } /*!**************************************************************************** * METHOD: ossimInit::removeOption() * * Removes all characters associated with the indicated option from the * command line string. * *****************************************************************************/ void ossimInit::removeOption(int& argc, char** argv, int argToRemove) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimInit::removeOption(argc, argv, argToRemove): entering..." << std::endl; // Shift the args up by one position, overwriting the arg being removed: for (int i=argToRemove+1; iregisterFactory(ossim::ImageHandlerStateFactory::instance()); ossimObjectFactoryRegistry::instance()->registerFactory(ossimImageSourceFactoryRegistry::instance()); //--- // Because of how the imagehandlers work off a magic number make sure // we place the writer first if we don't then the imagehandler will // be false and will then try to open the filename and go through a // magic number and if the file already // existed it will open and create a handler instead of a writer. //--- ossimCodecFactoryRegistry::instance(); ossimImageWriterFactoryRegistry::instance(); ossimDatumFactoryRegistry::instance(); ossimImageMetaDataWriterRegistry::instance(); ossimImageHandlerRegistry::instance(); ossim2dTo2dTransformRegistry::instance(); ossimImageGeometryRegistry::instance(); // Initialize the overview factories. ossimOverviewBuilderFactoryRegistry::instance()-> registerFactory(ossimOverviewBuilderFactory::instance(), true); ossimObjectFactoryRegistry::instance()->addFactory(ossimBaseObjectFactory::instance()); // initialize. projection factory. ossimProjectionFactoryRegistry::instance(); // add the view controllers ossimObjectFactoryRegistry::instance()->registerFactory(ossimProjectionViewControllerFactory::instance()); ossimFontFactoryRegistry::instance(); } void ossimInit::initializePlugins() { #if 0 // Note: Removed "autoload" code. Commented out below. const ossimKeywordlist& KWL = thePreferences->preferencesKWL(); //--- // Look for plugins in the form of: // plugin0.file: $(OSSIM_INSTALL_PREFIX)/lib64/ossim/plugins/libossim_png_plugin.so // plugin0.option: front //--- ossimString regExp = ossimString("^(") + "plugin[0-9]+.file)"; ossim_uint32 numberOfPlugins = KWL.getNumberOfSubstringKeys( regExp ); if ( numberOfPlugins ) { const ossim_uint32 MAX_INDEX = numberOfPlugins + 1000; // for skipage... ossim_uint32 index = 0; ossim_uint32 processedIndexes = 0; const std::string PREFIX_BASE = "plugin"; const std::string DOT = "."; const std::string FILE_KEY = "file"; const std::string OPTIONS_KEY = "options"; ossimString prefix; ossimFilename pluginFile; ossimString pluginOptions; // Loop to load plugins in order. Note allows for skipage. while ( processedIndexes < MAX_INDEX ) { prefix = PREFIX_BASE + ossimString::toString(index).string() + DOT; pluginFile = KWL.findKey( prefix, FILE_KEY ); if ( pluginFile.size() ) { if ( pluginFile.exists() ) { // Found plugin, look for options: pluginOptions = KWL.findKey( prefix, OPTIONS_KEY ); ossimSharedPluginRegistry::instance()->registerPlugin(pluginFile, pluginOptions); } ++processedIndexes; } if ( processedIndexes == numberOfPlugins ) { break; } ++index; } } //--- // Look for plugins in the form of: // plugin.file0: $(OSSIM_INSTALL_PREFIX)/lib64/ossim/plugins/libossim_png_plugin.so //--- regExp = ossimString("^(") + "plugin.file[0-9]+)"; numberOfPlugins = KWL.getNumberOfSubstringKeys( regExp ); if ( numberOfPlugins ) { const ossim_uint32 MAX_INDEX = numberOfPlugins + 1000; // for skipage... ossim_uint32 index = 0; ossim_uint32 processedIndexes = 0; const std::string PREFIX_BASE = "plugin.file"; std::string fileKey; ossimString prefix; ossimFilename pluginFile; ossimString pluginOptions = ""; // No options: // Loop to load plugins in order. Note allows for skipage. while ( processedIndexes < MAX_INDEX ) { fileKey = PREFIX_BASE + ossimString::toString(index).string(); pluginFile = KWL.findKey( fileKey ); if ( pluginFile.size() ) { if ( pluginFile.exists() ) { ossimSharedPluginRegistry::instance()->registerPlugin(pluginFile, pluginOptions); } ++processedIndexes; } if ( processedIndexes == numberOfPlugins ) { break; } ++index; } } #else /* Old code that auto loads plugins. */ #if 0 ossimString regExpressionDir = ossimString("^(") + "plugin.dir[0-9]+)"; ossimString regExpressionFile = ossimString("^(") + "plugin.file[0-9]+)"; const ossimKeywordlist& kwl = thePreferences->preferencesKWL(); vector keys = kwl.getSubstringKeyList( regExpressionDir ); ossim_uint32 numberOfDirs = (ossim_uint32)keys.size(); ossim_uint32 offset = (ossim_uint32)ossimString("plugin.dir").size(); int idx = 0; std::vector numberList(numberOfDirs); // register user plugins first ossimFilename userPluginDir = ossimEnvironmentUtility::instance()->getUserOssimPluginDir(); loadPlugins(userPluginDir); if(numberList.size()>0) { for(idx = 0; idx < (int)numberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); numberList[idx] = numberStr.toInt(); } std::sort(numberList.begin(), numberList.end()); for(idx=0;idx < (int)numberList.size();++idx) { ossimString newPrefix = "plugin.dir"; newPrefix += ossimString::toString(numberList[idx]); const char* directory = kwl.find(newPrefix.c_str()); if(directory) { loadPlugins(ossimFilename(directory)); } } } keys = kwl.getSubstringKeyList( regExpressionFile ); ossim_uint32 numberOfFiles = (ossim_uint32)keys.size(); offset = (ossim_uint32)ossimString("plugin.file").size(); numberList.resize(numberOfFiles); if(numberList.size()>0) { for(idx = 0; idx < (int)numberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); numberList[idx] = numberStr.toInt(); } std::sort(numberList.begin(), numberList.end()); for(idx=0;idx < (int)numberList.size();++idx) { ossimString newPrefix="plugin.file"; newPrefix += ossimString::toString(numberList[idx]); const char* file = kwl.find(newPrefix.c_str()); if(file&&ossimFilename(file).exists()) { loadPlugins(file); // ossimSharedPluginRegistry::instance()->registerPlugin(file); } } } #endif // now check new plugin loading that supports passing options to the plugins // const ossimKeywordlist& kwl = thePreferences->preferencesKWL(); ossimString regExpressionFile = ossimString("^(") + "plugin[0-9]+\\.file)"; vector keys = kwl.getSubstringKeyList( regExpressionFile ); ossim_uint32 numberOfFiles = (ossim_uint32)keys.size(); ossim_uint32 offset = (ossim_uint32)ossimString("plugin").size(); std::vector numberList(numberOfFiles); if(numberList.size()>0) { ossim_uint32 idx = 0; for(idx = 0; idx < numberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); numberList[idx] = numberStr.toInt(); } std::sort(numberList.begin(), numberList.end()); ossimFilename pluginFile; ossimString options; for(std::vector::const_iterator iter = numberList.begin(); iter != numberList.end();++iter) { ossimString newPrefix = ossimString("plugin")+ossimString::toString(*iter) + "."; pluginFile = kwl.find((newPrefix+"file").c_str()); options = kwl.find((newPrefix+"options").c_str()); if(pluginFile.exists()) { ossimSharedPluginRegistry::instance()->registerPlugin(pluginFile, options); } } } regExpressionFile = ossimString("^(") + "plugin.file[0-9]+)"; keys = kwl.getSubstringKeyList( regExpressionFile ); numberOfFiles = (ossim_uint32)keys.size(); offset = (ossim_uint32)ossimString("plugin.file").size(); numberList.resize(numberOfFiles); if(numberList.size()>0) { ossim_uint32 idx = 0; for(idx = 0; idx < numberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); numberList[idx] = numberStr.toInt(); } std::sort(numberList.begin(), numberList.end()); ossimFilename pluginFile; ossimString options; for(std::vector::const_iterator iter = numberList.begin(); iter != numberList.end();++iter) { ossimString newPrefix = ossimString("plugin.file")+ossimString::toString(*iter); pluginFile = kwl.find(newPrefix.c_str()); if(pluginFile.exists()) { ossimSharedPluginRegistry::instance()->registerPlugin(pluginFile, options); } } } ossimString auto_load_plugins(ossimPreferences::instance()->findPreference("ossim_init.auto_load_plugins")); if(auto_load_plugins.empty()) auto_load_plugins = "false"; // now load any plugins not found in the keywordlist // // check for plugins in the current directory // and load them if(auto_load_plugins.toBool()) { ossimFilename ossimpluginsDir = ossimFilename(theAppName).dirCat("ossimplugins"); ossimDirectory currentDir(theAppName.path()); if(ossimpluginsDir.exists()) { currentDir = ossimpluginsDir; } std::vector result; currentDir.findAllFilesThatMatch(result, "ossim.*plugin.*", ossimDirectory::OSSIM_DIR_FILES); if(result.size()) { ossim_uint32 idx = 0; for(idx = 0; idx < result.size(); ++idx) { ossimSharedPluginRegistry::instance()->registerPlugin(result[idx]); } } } #endif } void ossimInit::initializeElevation() { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimInit::initializeElevation(): Entered..." << std::endl; const ossimKeywordlist& KWL = thePreferences->preferencesKWL(); #if 0 /* All autoload stuff disabled. drb 20170408 */ ossimFilename appPath = theAppName.path(); // look for bundled elevation and geoids { ossimFilename geoid = appPath.dirCat("geoids"); geoid = geoid.dirCat("geoid1996"); geoid = geoid.dirCat("egm96.grd"); if(geoid.exists()) { ossimGeoid* geoidPtr = new ossimGeoidEgm96(geoid); if (geoidPtr->getErrorStatus() == ossimErrorCodes::OSSIM_OK) { ossimGeoidManager::instance()->addGeoid(geoidPtr); } } } #endif ossimGeoidManager::instance()->loadState(KWL); //--- // Auto load removed to avoid un-wanted directory scanning. // Use ossim preferences. drb - 28 March 2016. //--- #if 0 ossimFilename elevation = appPath.dirCat("elevation"); if(elevation.exists()) { ossimElevManager::instance()->loadElevationPath(elevation); } #endif // lets do backward compatability here // ossimString regExpression = ossimString("^(") + "elevation_source[0-9]+.)"; vector keys = KWL.getSubstringKeyList( regExpression ); if(!keys.empty()) { ossimNotify(ossimNotifyLevel_WARN) << "Please specify elevation_source keywords with the new prefix\n" << "of elevation_manager.elevation_source....\n"; thePreferences->preferencesKWL().addPrefixToKeysThatMatch("elevation_manager.", regExpression); } ossimElevManager::instance()->loadState(KWL, "elevation_manager."); if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimInit::initializeElevation(): leaving..." << std::endl; } void ossimInit::initializeLogFile() { //--- // Do not set if already as --ossim-logfile take precidence over preferences // file. //--- ossimFilename logFile; ossimGetLogFilename(logFile); if ( (logFile.size() == 0) && thePreferences ) { const char* lookup = thePreferences->preferencesKWL().find("ossim.log.file"); if (lookup) { logFile = lookup; ossimSetLogFilename(logFile); } } } ossimString ossimInit::version() const { ossimString versionString; #ifdef OSSIM_VERSION versionString += OSSIM_VERSION; #else versionString += "Version ?.?.?"; #endif versionString += " "; #ifdef OSSIM_BUILD_DATE versionString += OSSIM_BUILD_DATE; #else versionString += "(yyyymmdd)"; #endif return versionString; } ossimFilename ossimInit::appName()const { return theAppName; } ossimInit::ossimInit(const ossimInit& /* obj */ ) : theInitializedFlag(false), theAppName(), thePreferences(ossimPreferences::instance()), theElevEnabledFlag(true), thePluginLoaderEnabledFlag(true) {} void ossimInit::operator=(const ossimInit& /* rhs */) const {} ossim-Miami-2.9.1/src/matrix/000077500000000000000000000000001352751253100160065ustar00rootroot00000000000000ossim-Miami-2.9.1/src/matrix/bandmat.cpp000066400000000000000000000370651352751253100201330ustar00rootroot00000000000000//$$ bandmat.cpp Band matrix definitions // Copyright (C) 1991,2,3,4,9: R B Davies #define WANT_MATH // include.h will get math fns //#define WANT_STREAM #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,10); ++ExeCount; } #else #define REPORT {} #endif static inline int my_min(int x, int y) { return x < y ? x : y; } static inline int my_max(int x, int y) { return x > y ? x : y; } BandMatrix::BandMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::BM); GetMatrix(gmx); CornerClear(); } void BandMatrix::SetParameters(const GeneralMatrix* gmx) { REPORT MatrixBandWidth bw = gmx->BandWidth(); lower = bw.lower; upper = bw.upper; } void BandMatrix::ReSize(int n, int lb, int ub) { REPORT Tracer tr("BandMatrix::ReSize"); if (lb<0 || ub<0) Throw(ProgramException("Undefined bandwidth")); lower = (lb<=n) ? lb : n-1; upper = (ub<=n) ? ub : n-1; GeneralMatrix::ReSize(n,n,n*(lower+1+upper)); CornerClear(); } // SimpleAddOK shows when we can add etc two matrices by a simple vector add // and when we can add one matrix into another // *gm must be the same type as *this // return 0 if simple add is OK // return 1 if we can add into *gm only // return 2 if we can add into *this only // return 3 if we can't add either way // For SP this will still be valid if we swap 1 and 2 short BandMatrix::SimpleAddOK(const GeneralMatrix* gm) { const BandMatrix* bm = (const BandMatrix*)gm; if (bm->lower == lower && bm->upper == upper) { REPORT return 0; } else if (bm->lower >= lower && bm->upper >= upper) { REPORT return 1; } else if (bm->lower <= lower && bm->upper <= upper) { REPORT return 2; } else { REPORT return 3; } } short SymmetricBandMatrix::SimpleAddOK(const GeneralMatrix* gm) { const SymmetricBandMatrix* bm = (const SymmetricBandMatrix*)gm; if (bm->lower == lower) { REPORT return 0; } else if (bm->lower > lower) { REPORT return 1; } else { REPORT return 2; } } void UpperBandMatrix::ReSize(int n, int lb, int ub) { REPORT if (lb != 0) { Tracer tr("UpperBandMatrix::ReSize"); Throw(ProgramException("UpperBandMatrix with non-zero lower band" )); } BandMatrix::ReSize(n, lb, ub); } void LowerBandMatrix::ReSize(int n, int lb, int ub) { REPORT if (ub != 0) { Tracer tr("LowerBandMatrix::ReSize"); Throw(ProgramException("LowerBandMatrix with non-zero upper band" )); } BandMatrix::ReSize(n, lb, ub); } void BandMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("BandMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } MatrixBandWidth mbw = A.BandWidth(); ReSize(n, mbw.Lower(), mbw.Upper()); } bool BandMatrix::SameStorageType(const GeneralMatrix& A) const { if (Type() != A.Type()) { REPORT return false; } REPORT return BandWidth() == A.BandWidth(); } void BandMatrix::ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B) { REPORT Tracer tr("BandMatrix::ReSizeForAdd"); MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); if ((A_BW.Lower() < 0) | (A_BW.Upper() < 0) | (B_BW.Lower() < 0) | (A_BW.Upper() < 0)) Throw(ProgramException("Can't ReSize to BandMatrix" )); // already know A and B are square ReSize(A.Nrows(), my_max(A_BW.Lower(), B_BW.Lower()), my_max(A_BW.Upper(), B_BW.Upper())); } void BandMatrix::ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B) { REPORT Tracer tr("BandMatrix::ReSizeForSP"); MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); if ((A_BW.Lower() < 0) | (A_BW.Upper() < 0) | (B_BW.Lower() < 0) | (A_BW.Upper() < 0)) Throw(ProgramException("Can't ReSize to BandMatrix" )); // already know A and B are square ReSize(A.Nrows(), my_min(A_BW.Lower(), B_BW.Lower()), my_min(A_BW.Upper(), B_BW.Upper())); } void BandMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::BM); CornerClear(); } void BandMatrix::CornerClear() const { // set unused parts of BandMatrix to zero REPORT int i = lower; Real* s = store; int bw = lower + 1 + upper; while (i) { int j = i--; Real* sj = s; s += bw; while (j--) *sj++ = 0.0; } i = upper; s = store + storage; while (i) { int j = i--; Real* sj = s; s -= bw; while (j--) *(--sj) = 0.0; } } MatrixBandWidth MatrixBandWidth::operator+(const MatrixBandWidth& bw) const { REPORT int l = bw.lower; int u = bw.upper; l = (lower < 0 || l < 0) ? -1 : (lower > l) ? lower : l; u = (upper < 0 || u < 0) ? -1 : (upper > u) ? upper : u; return MatrixBandWidth(l,u); } MatrixBandWidth MatrixBandWidth::operator*(const MatrixBandWidth& bw) const { REPORT int l = bw.lower; int u = bw.upper; l = (lower < 0 || l < 0) ? -1 : lower+l; u = (upper < 0 || u < 0) ? -1 : upper+u; return MatrixBandWidth(l,u); } MatrixBandWidth MatrixBandWidth::minimum(const MatrixBandWidth& bw) const { REPORT int l = bw.lower; int u = bw.upper; if ((lower >= 0) && ( (l < 0) || (l > lower) )) l = lower; if ((upper >= 0) && ( (u < 0) || (u > upper) )) u = upper; return MatrixBandWidth(l,u); } UpperBandMatrix::UpperBandMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::UB); GetMatrix(gmx); CornerClear(); } void UpperBandMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::UB); CornerClear(); } LowerBandMatrix::LowerBandMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::LB); GetMatrix(gmx); CornerClear(); } void LowerBandMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::LB); CornerClear(); } BandLUMatrix::BandLUMatrix(const BaseMatrix& m) { REPORT Tracer tr("BandLUMatrix"); storage2 = 0; store2 = 0; // in event of exception during build GeneralMatrix* gm = ((BaseMatrix&)m).Evaluate(MatrixType::BM); m1 = ((BandMatrix*)gm)->lower; m2 = ((BandMatrix*)gm)->upper; GetMatrix(gm); if (nrows!=ncols) Throw(NotSquareException(*this)); d = true; sing = false; indx = new int [nrows]; MatrixErrorNoSpace(indx); MONITOR_INT_NEW("Index (BndLUMat)",nrows,indx) storage2 = nrows * m1; store2 = new Real [storage2]; MatrixErrorNoSpace(store2); MONITOR_REAL_NEW("Make (BandLUMat)",storage2,store2) ludcmp(); } BandLUMatrix::~BandLUMatrix() { REPORT MONITOR_INT_DELETE("Index (BndLUMat)",nrows,indx) MONITOR_REAL_DELETE("Delete (BndLUMt)",storage2,store2) delete [] indx; delete [] store2; } MatrixType BandLUMatrix::Type() const { REPORT return MatrixType::BC; } LogAndSign BandLUMatrix::LogDeterminant() const { REPORT if (sing) return 0.0; Real* a = store; int w = m1+1+m2; LogAndSign sum; int i = nrows; // while (i--) { sum *= *a; a += w; } if (i) for (;;) { sum *= *a; if (!(--i)) break; a += w; } if (!d) sum.ChangeSign(); return sum; } GeneralMatrix* BandMatrix::MakeSolver() { REPORT GeneralMatrix* gm = new BandLUMatrix(*this); MatrixErrorNoSpace(gm); gm->ReleaseAndDelete(); return gm; } void BandLUMatrix::ludcmp() { REPORT Real* a = store2; int i = storage2; // clear store2 - so unused locations are always zero - // required by operator== while (i--) *a++ = 0.0; a = store; i = m1; int j = m2; int k; int n = nrows; int w = m1 + 1 + m2; while (i) { Real* ai = a + i; k = ++j; while (k--) *a++ = *ai++; k = i--; while (k--) *a++ = 0.0; } a = store; int l = m1; for (k=0; k=mini; i--) { Real* b = B + i; Real* bk = b; Real x = *bk; Real* a = store + w*i; Real y = *a; int k = l+m1; while (k--) x -= *(++a) * *(++bk); *b = x / y; if (l < m2) l++; } } void BandLUMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip; Real* el = mcin.data-i; Real* el1=el; while (i--) *el++ = 0.0; el += mcin.storage; i = nrows - mcin.skip - mcin.storage; while (i--) *el++ = 0.0; lubksb(el1, mcout.skip); } // Do we need check for entirely zero output? void UpperBandMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip-mcout.skip; Real* elx = mcin.data-i; while (i-- > 0) *elx++ = 0.0; int nr = mcin.skip+mcin.storage; elx = mcin.data+mcin.storage; Real* el = elx; int j = mcout.skip+mcout.storage-nr; i = nr-mcout.skip; while (j-- > 0) *elx++ = 0.0; Real* Ael = store + (upper+1)*(i-1)+1; j = 0; if (i > 0) for(;;) { elx = el; Real sum = 0.0; int jx = j; while (jx--) sum += *(--Ael) * *(--elx); elx--; *elx = (*elx - sum) / *(--Ael); if (--i <= 0) break; if (j 0) *elx++ = 0.0; int nc = mcin.skip; i = nc+mcin.storage; elx = mcin.data+mcin.storage; int nr = mcout.skip+mcout.storage; int j = nr-i; i = nr-nc; while (j-- > 0) *elx++ = 0.0; Real* el = mcin.data; Real* Ael = store + (lower+1)*nc + lower; j = 0; if (i > 0) for(;;) { elx = el; Real sum = 0.0; int jx = j; while (jx--) sum += *Ael++ * *elx++; *elx = (*elx - sum) / *Ael++; if (--i <= 0) break; if (jReleaseAndDelete(); return gm; } SymmetricBandMatrix::SymmetricBandMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::SB); GetMatrix(gmx); } GeneralMatrix* SymmetricBandMatrix::Transpose(TransposedMatrix*, MatrixType mt) { REPORT return Evaluate(mt); } LogAndSign SymmetricBandMatrix::LogDeterminant() const { REPORT BandLUMatrix C(*this); return C.LogDeterminant(); } void SymmetricBandMatrix::SetParameters(const GeneralMatrix* gmx) { REPORT lower = gmx->BandWidth().lower; } void SymmetricBandMatrix::ReSize(int n, int lb) { REPORT Tracer tr("SymmetricBandMatrix::ReSize"); if (lb<0) Throw(ProgramException("Undefined bandwidth")); lower = (lb<=n) ? lb : n-1; GeneralMatrix::ReSize(n,n,n*(lower+1)); } void SymmetricBandMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("SymmetricBandMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } MatrixBandWidth mbw = A.BandWidth(); int b = mbw.Lower(); if (b != mbw.Upper()) { Tracer tr("SymmetricBandMatrix::ReSize(GM)"); Throw(ProgramException("Upper and lower band-widths not equal")); } ReSize(n, b); } bool SymmetricBandMatrix::SameStorageType(const GeneralMatrix& A) const { if (Type() != A.Type()) { REPORT return false; } REPORT return BandWidth() == A.BandWidth(); } void SymmetricBandMatrix::ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B) { REPORT Tracer tr("SymmetricBandMatrix::ReSizeForAdd"); MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); if ((A_BW.Lower() < 0) | (B_BW.Lower() < 0)) Throw(ProgramException("Can't ReSize to SymmetricBandMatrix" )); // already know A and B are square ReSize(A.Nrows(), my_max(A_BW.Lower(), B_BW.Lower())); } void SymmetricBandMatrix::ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B) { REPORT Tracer tr("SymmetricBandMatrix::ReSizeForSP"); MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); if ((A_BW.Lower() < 0) | (B_BW.Lower() < 0)) Throw(ProgramException("Can't ReSize to SymmetricBandMatrix" )); // already know A and B are square ReSize(A.Nrows(), my_min(A_BW.Lower(), B_BW.Lower())); } void SymmetricBandMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::SB); } void SymmetricBandMatrix::CornerClear() const { // set unused parts of BandMatrix to zero REPORT int i = lower; Real* s = store; int bw = lower + 1; if (i) for(;;) { int j = i; Real* sj = s; while (j--) *sj++ = 0.0; if (!(--i)) break; s += bw; } } MatrixBandWidth SymmetricBandMatrix::BandWidth() const { REPORT return MatrixBandWidth(lower,lower); } inline Real square(Real x) { return x*x; } Real SymmetricBandMatrix::SumSquare() const { REPORT CornerClear(); Real sum1=0.0; Real sum2=0.0; Real* s=store; int i=nrows; int l=lower; while (i--) { int j = l; while (j--) sum2 += square(*s++); sum1 += square(*s++); } ((GeneralMatrix&)*this).tDelete(); return sum1 + 2.0 * sum2; } Real SymmetricBandMatrix::SumAbsoluteValue() const { REPORT CornerClear(); Real sum1=0.0; Real sum2=0.0; Real* s=store; int i=nrows; int l=lower; while (i--) { int j = l; while (j--) sum2 += std::fabs(*s++); sum1 += std::fabs(*s++); } ((GeneralMatrix&)*this).tDelete(); return sum1 + 2.0 * sum2; } Real SymmetricBandMatrix::Sum() const { REPORT CornerClear(); Real sum1=0.0; Real sum2=0.0; Real* s=store; int i=nrows; int l=lower; while (i--) { int j = l; while (j--) sum2 += *s++; sum1 += *s++; } ((GeneralMatrix&)*this).tDelete(); return sum1 + 2.0 * sum2; } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/bc.mak000066400000000000000000000072221352751253100170670ustar00rootroot00000000000000.AUTODEPEND BORLANDPATH = F:\BC5 TASM = TASM TLIB = tlib TLINK = tlink LIBPATH = $(BORLANDPATH)\LIB INCLUDEPATH = $(BORLANDPATH)\INCLUDE CCX = bcc -ml -wpro -weas -wpre -I$(INCLUDEPATH) -D CC = bcc -W- -v- -H- -x- -3 -N -Og -Oi -Ov -vGd- -vGt- -ml -f -I$(INCLUDEPATH) everything: tmt.exe example.exe nl_ex.exe sl_ex.exe garch.exe test_exc.exe .cpp.obj: $(CC) -c {$< } OBJ_LIB = bandmat.obj cholesky.obj evalue.obj fft.obj hholder.obj \ jacobi.obj myexcept.obj newmat1.obj newmat2.obj newmat3.obj \ newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj \ newmat9.obj newmatex.obj newmatnl.obj newmatrm.obj solution.obj \ sort.obj submat.obj svd.obj newfft.obj newmat.lib: $(OBJ_LIB) erase newmat.lib $(TLIB) newmat.lib /P32 +newmat1 +newmat2 +newmat3 +newmat4 +newmat5 +newmat6 $(TLIB) newmat.lib /P32+newmat7 +newmat8 +newmat9 +svd +fft +hholder +sort $(TLIB) newmat.lib /P32+cholesky +submat +jacobi +evalue +bandmat +myexcept $(TLIB) newmat.lib /P32+solution +newmatnl +newmatrm +newmatex +newfft OBJ_T = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj \ tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj \ tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmt.exe: newmat.lib $(OBJ_T) $(TLINK) /x/L$(LIBPATH) -Tde @&&| c0l.obj+tmt.obj+tmt1.obj+tmt2.obj+tmt3.obj+tmt4.obj+tmt5.obj+tmt6.obj+ tmt7.obj+tmt8.obj+tmt9.obj+tmta.obj+tmtb.obj+tmtc.obj+tmtd.obj+tmte.obj+ tmtf.obj+tmtg.obj+tmth.obj+tmti.obj+tmtj.obj+tmtk.obj+tmtl.obj+newmat.lib tmt # no map file bidsl.lib+emu.lib+mathl.lib+cl.lib | example.exe: newmat.lib example.obj $(TLINK) /x/L$(LIBPATH) -Tde @&&| c0l.obj+example.obj+newmat.lib example # no map file bidsl.lib+emu.lib+mathl.lib+cl.lib | nl_ex.exe: newmat.lib nl_ex.obj $(TLINK) /x/L$(LIBPATH) -Tde @&&| c0l.obj+nl_ex.obj+newmat.lib nl_ex # no map file bidsl.lib+emu.lib+mathl.lib+cl.lib | sl_ex.exe: newmat.lib sl_ex.obj $(TLINK) /x/L$(LIBPATH) -Tde @&&| c0l.obj+sl_ex.obj+newmat.lib sl_ex # no map file bidsl.lib+emu.lib+mathl.lib+cl.lib | garch.exe: newmat.lib garch.obj $(TLINK) /x/L$(LIBPATH) -Tde @&&| c0l.obj+garch.obj+newmat.lib garch # no map file bidsl.lib+emu.lib+mathl.lib+cl.lib | test_exc.exe: newmat.lib test_exc.obj $(TLINK) /x/L$(LIBPATH) -Tde @&&| c0l.obj+test_exc.obj+newmat.lib test_exc # no map file bidsl.lib+emu.lib+mathl.lib+cl.lib | bandmat.obj: bandmat.cpp cholesky.obj: cholesky.cpp evalue.obj: evalue.cpp myexcept.obj: myexcept.cpp fft.obj: fft.cpp newfft.obj: newfft.cpp hholder.obj: hholder.cpp jacobi.obj: jacobi.cpp newmat1.obj: newmat1.cpp newmat2.obj: newmat2.cpp newmat3.obj: newmat3.cpp newmat4.obj: newmat4.cpp newmat5.obj: newmat5.cpp newmat6.obj: newmat6.cpp newmat7.obj: newmat7.cpp newmat8.obj: newmat8.cpp newmat9.obj: newmat9.cpp newmatex.obj: newmatex.cpp newmatrm.obj: newmatrm.cpp newmatnl.obj: newmatnl.cpp sort.obj: sort.cpp submat.obj: submat.cpp svd.obj: svd.cpp example.obj: example.cpp tmt.obj: tmt.cpp tmt1.obj: tmt1.cpp tmt2.obj: tmt2.cpp tmt3.obj: tmt3.cpp tmt4.obj: tmt4.cpp tmt5.obj: tmt5.cpp tmt6.obj: tmt6.cpp tmt7.obj: tmt7.cpp tmt8.obj: tmt8.cpp tmt9.obj: tmt9.cpp tmta.obj: tmta.cpp tmtb.obj: tmtb.cpp tmtc.obj: tmtc.cpp tmtd.obj: tmtd.cpp tmte.obj: tmte.cpp tmtf.obj: tmtf.cpp tmtg.obj: tmtg.cpp tmth.obj: tmth.cpp tmti.obj: tmti.cpp tmtj.obj: tmtj.cpp tmtk.obj: tmtk.cpp tmtl.obj: tmtl.cpp nl_ex.obj: nl_ex.cpp sl_ex.obj: sl_ex.cpp solution.obj: solution.cpp garch.obj: garch.cpp test_exc.obj: test_exc.cpp ossim-Miami-2.9.1/src/matrix/bc32.mak000066400000000000000000000071711352751253100172370ustar00rootroot00000000000000.AUTODEPEND BORLANDPATH = F:\BC5 TASM = TASM32 TLIB = tlib TLINK = tlink32 LIBPATH = $(BORLANDPATH)\LIB INCLUDEPATH = $(BORLANDPATH)\INCLUDE CC = bcc32 -W- -v- -H- -x- -3 -N -Og -Oi -Ov -f -I$(INCLUDEPATH) everything: tmt.exe example.exe nl_ex.exe sl_ex.exe garch.exe test_exc.exe .cpp.obj: $(CC) -c {$< } OBJ_LIB = bandmat.obj cholesky.obj evalue.obj fft.obj hholder.obj \ jacobi.obj myexcept.obj newmat1.obj newmat2.obj newmat3.obj \ newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj \ newmat9.obj newmatex.obj newmatnl.obj newmatrm.obj solution.obj \ sort.obj submat.obj svd.obj newfft.obj newmat.lib: $(OBJ_LIB) erase newmat.lib $(TLIB) newmat.lib /P32 +newmat1 +newmat2 +newmat3 +newmat4 +newmat5 +newmat6 $(TLIB) newmat.lib /P32+newmat7 +newmat8 +newmat9 +svd +fft +hholder +sort $(TLIB) newmat.lib /P32+cholesky +submat +jacobi +evalue +bandmat +myexcept $(TLIB) newmat.lib /P32+solution +newmatnl +newmatrm +newmatex +newfft OBJ_T = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj \ tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj \ tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmt.exe: newmat.lib $(OBJ_T) $(TLINK) /x/L$(LIBPATH) -Tpe -ap -c @&&| c0x32.obj+tmt.obj+tmt1.obj+tmt2.obj+tmt3.obj+tmt4.obj+tmt5.obj+tmt6.obj+ tmt7.obj+tmt8.obj+tmt9.obj+tmta.obj+tmtb.obj+tmtc.obj+tmtd.obj+tmte.obj+ tmtf.obj+tmtg.obj+tmth.obj+tmti.obj+tmtj.obj+tmtk.obj+tmtl.obj+newmat.lib tmt # no map file bidsf.lib+import32.lib+cw32.lib | example.exe: newmat.lib example.obj $(TLINK) /x/L$(LIBPATH) -Tpe -ap -c @&&| c0x32.obj+example.obj+newmat.lib example # no map file bidsf.lib+import32.lib+cw32.lib | nl_ex.exe: newmat.lib nl_ex.obj $(TLINK) /x/L$(LIBPATH) -Tpe -ap -c @&&| c0x32.obj+nl_ex.obj+newmat.lib nl_ex # no map file bidsf.lib+import32.lib+cw32.lib | sl_ex.exe: newmat.lib sl_ex.obj $(TLINK) /x/L$(LIBPATH) -Tpe -ap -c @&&| c0x32.obj+sl_ex.obj+newmat.lib sl_ex # no map file bidsf.lib+import32.lib+cw32.lib | garch.exe: newmat.lib garch.obj $(TLINK) /x/L$(LIBPATH) -Tpe -ap -c @&&| c0x32.obj+garch.obj+newmat.lib garch # no map file bidsf.lib+import32.lib+cw32.lib | test_exc.exe: newmat.lib test_exc.obj $(TLINK) /x/L$(LIBPATH) -Tpe -ap -c @&&| c0x32.obj+test_exc.obj+newmat.lib test_exc # no map file bidsf.lib+import32.lib+cw32.lib | bandmat.obj: bandmat.cpp cholesky.obj: cholesky.cpp evalue.obj: evalue.cpp myexcept.obj: myexcept.cpp fft.obj: fft.cpp newfft.obj: newfft.cpp hholder.obj: hholder.cpp jacobi.obj: jacobi.cpp newmat1.obj: newmat1.cpp newmat2.obj: newmat2.cpp newmat3.obj: newmat3.cpp newmat4.obj: newmat4.cpp newmat5.obj: newmat5.cpp newmat6.obj: newmat6.cpp newmat7.obj: newmat7.cpp newmat8.obj: newmat8.cpp newmat9.obj: newmat9.cpp newmatex.obj: newmatex.cpp newmatrm.obj: newmatrm.cpp newmatnl.obj: newmatnl.cpp sort.obj: sort.cpp submat.obj: submat.cpp svd.obj: svd.cpp example.obj: example.cpp tmt.obj: tmt.cpp tmt1.obj: tmt1.cpp tmt2.obj: tmt2.cpp tmt3.obj: tmt3.cpp tmt4.obj: tmt4.cpp tmt5.obj: tmt5.cpp tmt6.obj: tmt6.cpp tmt7.obj: tmt7.cpp tmt8.obj: tmt8.cpp tmt9.obj: tmt9.cpp tmta.obj: tmta.cpp tmtb.obj: tmtb.cpp tmtc.obj: tmtc.cpp tmtd.obj: tmtd.cpp tmte.obj: tmte.cpp tmtf.obj: tmtf.cpp tmtg.obj: tmtg.cpp tmth.obj: tmth.cpp tmti.obj: tmti.cpp tmtj.obj: tmtj.cpp tmtk.obj: tmtk.cpp tmtl.obj: tmtl.cpp nl_ex.obj: nl_ex.cpp sl_ex.obj: sl_ex.cpp solution.obj: solution.cpp garch.obj: garch.cpp test_exc.obj: test_exc.cpp ossim-Miami-2.9.1/src/matrix/cc.mak000066400000000000000000000076751352751253100171040ustar00rootroot00000000000000CXX = CC CXXFLAGS = -O2 .SUFFIXES: .SUFFIXES: .a .o .c .cpp everything: libnewmat.a tmt example nl_ex sl_ex garch test_exc .cpp.o: rm -f $*.cxx ln $*.cpp $*.cxx $(CXX) $(CXXFLAGS) -c $*.cxx rm $*.cxx OBJ_LIB = bandmat.o cholesky.o evalue.o fft.o hholder.o \ jacobi.o myexcept.o newmat1.o newmat2.o newmat3.o \ newmat4.o newmat5.o newmat6.o newmat7.o newmat8.o \ newmat9.o newmatex.o newmatnl.o newmatrm.o solution.o \ sort.o submat.o svd.o newfft.o libnewmat.a: $(OBJ_LIB) $(AR) cr $@ $(OBJ_LIB) ranlib $@ OBJ_T = tmt.o tmt1.o tmt2.o tmt3.o tmt4.o tmt5.o tmt6.o \ tmt7.o tmt8.o tmt9.o tmta.o tmtb.o tmtc.o tmtd.o tmte.o \ tmtf.o tmtg.o tmth.o tmti.o tmtj.o tmtk.o tmtl.o tmt: $(OBJ_T) libnewmat.a $(CXX) -o $@ $(OBJ_T) -L. -lnewmat -lm OBJ_E = example.o example: $(OBJ_E) libnewmat.a $(CXX) -o $@ $(OBJ_E) -L. -lnewmat -lm OBJ_N = nl_ex.o nl_ex: $(OBJ_N) libnewmat.a $(CXX) -o $@ $(OBJ_N) -L. -lnewmat -lm OBJ_S = sl_ex.o sl_ex: $(OBJ_S) libnewmat.a $(CXX) -o $@ $(OBJ_S) -L. -lnewmat -lm OBJ_G = garch.o garch: $(OBJ_G) libnewmat.a $(CXX) -o $@ $(OBJ_G) -L. -lnewmat -lm OBJ_X = test_exc.o test_exc: $(OBJ_X) libnewmat.a $(CXX) -o $@ $(OBJ_X) -L. -lnewmat -lm newmatxx = include.h newmat.h boolean.h myexcept.h myexcept.o: include.h boolean.h myexcept.h myexcept.cpp newmatex.o: $(newmatxx) newmatex.cpp newmatnl.o: $(newmatxx) newmatnl.h newmatap.h example.o: $(newmatxx) newmatap.h example.cpp cholesky.o: $(newmatxx) cholesky.cpp evalue.o: $(newmatxx) newmatrm.h precisio.h evalue.cpp fft.o: $(newmatxx) newmatap.h fft.cpp newfft.o: $(newmatxx) newmatap.h newfft.cpp hholder.o: $(newmatxx) newmatap.h hholder.cpp jacobi.o: $(newmatxx) precisio.h newmatrm.h jacobi.cpp bandmat.o: $(newmatxx) newmatrc.h controlw.h bandmat.cpp newmat1.o: $(newmatxx) newmat1.cpp newmat2.o: $(newmatxx) newmatrc.h controlw.h newmat2.cpp newmat3.o: $(newmatxx) newmatrc.h controlw.h newmat3.cpp newmat4.o: $(newmatxx) newmatrc.h controlw.h newmat4.cpp newmat5.o: $(newmatxx) newmatrc.h controlw.h newmat5.cpp newmat6.o: $(newmatxx) newmatrc.h controlw.h newmat6.cpp newmat7.o: $(newmatxx) newmatrc.h controlw.h newmat7.cpp newmat8.o: $(newmatxx) newmatap.h newmat8.cpp newmat9.o: $(newmatxx) newmatrc.h controlw.h newmatio.h newmat9.cpp newmatrm.o: $(newmatxx) newmatrm.h newmatrm.cpp sort.o: $(newmatxx) newmatap.h sort.cpp submat.o: $(newmatxx) newmatrc.h controlw.h submat.cpp svd.o: $(newmatxx) newmatrm.h precisio.h svd.cpp tmt.o: $(newmatxx) newmatap.h tmt.cpp tmt1.o: $(newmatxx) newmatap.h tmt1.cpp tmt2.o: $(newmatxx) newmatap.h tmt2.cpp tmt3.o: $(newmatxx) newmatap.h tmt3.cpp tmt4.o: $(newmatxx) newmatap.h tmt4.cpp tmt5.o: $(newmatxx) newmatap.h tmt5.cpp tmt6.o: $(newmatxx) newmatap.h tmt6.cpp tmt7.o: $(newmatxx) newmatap.h tmt7.cpp tmt8.o: $(newmatxx) newmatap.h tmt8.cpp tmt9.o: $(newmatxx) newmatap.h tmt9.cpp tmta.o: $(newmatxx) newmatap.h tmta.cpp tmtb.o: $(newmatxx) newmatap.h tmtb.cpp tmtc.o: $(newmatxx) newmatap.h tmtc.cpp tmtd.o: $(newmatxx) newmatap.h tmtd.cpp tmte.o: $(newmatxx) newmatap.h tmte.cpp tmtf.o: $(newmatxx) newmatap.h tmtf.cpp tmtg.o: $(newmatxx) newmatap.h tmtg.cpp tmth.o: $(newmatxx) newmatap.h tmth.cpp tmti.o: $(newmatxx) newmatap.h tmti.cpp tmtj.o: $(newmatxx) newmatap.h tmtj.cpp tmtk.o: $(newmatxx) newmatap.h tmtk.cpp tmtl.o: $(newmatxx) newmatap.h tmtl.cpp nl_ex.o: $(newmatxx) newmatap.h newmatnl.h nl_ex.cpp sl_ex.o: include.h boolean.h myexcept.h sl_ex.cpp solution.o: include.h boolean.h myexcept.h solution.cpp garch.o: $(newmatxx) newmatap.h newmatnl.h garch.cpp test_exc.o: $(newmatxx) test_exc.cpp ossim-Miami-2.9.1/src/matrix/cholesky.cpp000066400000000000000000000177011352751253100203410ustar00rootroot00000000000000//$$ cholesky.cpp cholesky decomposition // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH //#define WANT_STREAM #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,14); ++ExeCount; } #else #define REPORT {} #endif /********* Cholesky decomposition of a positive definite matrix *************/ // Suppose S is symmetrix and positive definite. Then there exists a unique // lower triangular matrix L such that L L.t() = S; ReturnMatrix Cholesky(const SymmetricMatrix& S) { REPORT Tracer trace("Cholesky"); int nr = S.Nrows(); LowerTriangularMatrix T(nr); Real* s = S.Store(); Real* t = T.Store(); Real* ti = t; for (int i=0; i= 1.0) Throw(ProgramException("DowndateCholesky() fails", chol)); Real alpha = std::sqrt(1.0 - squareNormA); // compute and apply Givens rotations to the vector a ColumnVector cGivens(nRC); cGivens = 0.0; ColumnVector sGivens(nRC); sGivens = 0.0; for(i = nRC; i >= 1; i--) alpha = pythag(alpha, a(i), cGivens(i), sGivens(i)); // apply Givens rotations to the jth column of chol ColumnVector xtilde(nRC); xtilde = 0.0; for(j = nRC; j >= 1; j--) { // only the first j rotations have an affect on chol,0 for(int k = j; k >= 1; k--) GivensRotation(cGivens(k), -sGivens(k), chol(k,j), xtilde(j)); } } // produces the Cholesky decomposition of EAE where A = chol.t() * chol // and E produces a RIGHT circular shift of the rows and columns from // 1,...,k-1,k,k+1,...l,l+1,...,p to // 1,...,k-1,l,k,k+1,...l-1,l+1,...p void RightCircularUpdateCholesky(UpperTriangularMatrix &chol, int k, int l) { int nRC = chol.Nrows(); int i, j; // I. compute shift of column l to the kth position Matrix cholCopy = chol; // a. grab column l ColumnVector columnL = cholCopy.Column(l); // b. shift columns k,...l-1 to the RIGHT for(j = l-1; j >= k; --j) cholCopy.Column(j+1) = cholCopy.Column(j); // c. copy the top k-1 elements of columnL into the kth column of cholCopy cholCopy.Column(k) = 0.0; for(i = 1; i < k; ++i) cholCopy(i,k) = columnL(i); // II. determine the l-k Given's rotations int nGivens = l-k; ColumnVector cGivens(nGivens); cGivens = 0.0; ColumnVector sGivens(nGivens); sGivens = 0.0; for(i = l; i > k; i--) { int givensIndex = l-i+1; columnL(i-1) = pythag(columnL(i-1), columnL(i), cGivens(givensIndex), sGivens(givensIndex)); columnL(i) = 0.0; } // the kth entry of columnL is the new diagonal element in column k of cholCopy cholCopy(k,k) = columnL(k); // III. apply these Given's rotations to subsequent columns // for columns k+1,...,l-1 we only need to apply the last nGivens-(j-k) rotations for(j = k+1; j <= nRC; ++j) { ColumnVector columnJ = cholCopy.Column(j); int imin = nGivens - (j-k) + 1; if (imin < 1) imin = 1; for(int gIndex = imin; gIndex <= nGivens; ++gIndex) { // apply gIndex Given's rotation int topRowIndex = k + nGivens - gIndex; GivensRotationR(cGivens(gIndex), sGivens(gIndex), columnJ(topRowIndex), columnJ(topRowIndex+1)); } cholCopy.Column(j) = columnJ; } chol << cholCopy; } // produces the Cholesky decomposition of EAE where A = chol.t() * chol // and E produces a LEFT circular shift of the rows and columns from // 1,...,k-1,k,k+1,...l,l+1,...,p to // 1,...,k-1,k+1,...l,k,l+1,...,p to void LeftCircularUpdateCholesky(UpperTriangularMatrix &chol, int k, int l) { int nRC = chol.Nrows(); int i, j; // I. compute shift of column k to the lth position Matrix cholCopy = chol; // a. grab column k ColumnVector columnK = cholCopy.Column(k); // b. shift columns k+1,...l to the LEFT for(j = k+1; j <= l; ++j) cholCopy.Column(j-1) = cholCopy.Column(j); // c. copy the elements of columnK into the lth column of cholCopy cholCopy.Column(l) = 0.0; for(i = 1; i <= k; ++i) cholCopy(i,l) = columnK(i); // II. apply and compute Given's rotations int nGivens = l-k; ColumnVector cGivens(nGivens); cGivens = 0.0; ColumnVector sGivens(nGivens); sGivens = 0.0; for(j = k; j <= nRC; ++j) { ColumnVector columnJ = cholCopy.Column(j); // apply the previous Givens rotations to columnJ int imax = j - k; if (imax > nGivens) imax = nGivens; for(int i = 1; i <= imax; ++i) { int gIndex = i; int topRowIndex = k + i - 1; GivensRotationR(cGivens(gIndex), sGivens(gIndex), columnJ(topRowIndex), columnJ(topRowIndex+1)); } // compute a new Given's rotation when j < l if(j < l) { int gIndex = j-k+1; columnJ(j) = pythag(columnJ(j), columnJ(j+1), cGivens(gIndex), sGivens(gIndex)); columnJ(j+1) = 0.0; } cholCopy.Column(j) = columnJ; } chol << cholCopy; } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/evalue.cpp000066400000000000000000000220621352751253100177750ustar00rootroot00000000000000//$$evalue.cpp eigen-value decomposition // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,17); ++ExeCount; } #else #define REPORT {} #endif static void tred2(const SymmetricMatrix& A, DiagonalMatrix& D, DiagonalMatrix& E, Matrix& Z) { Tracer et("Evalue(tred2)"); REPORT Real tol = FloatingPointPrecision::Minimum()/FloatingPointPrecision::Epsilon(); int n = A.Nrows(); Z.ReSize(n,n); Z.Inject(A); D.ReSize(n); E.ReSize(n); Real* z = Z.Store(); int i; for (i=n-1; i > 0; i--) // i=0 is excluded { Real f = Z.element(i,i-1); Real g = 0.0; int k = i-1; Real* zik = z + i*n; while (k--) g += square(*zik++); Real h = g + square(f); if (g <= tol) { REPORT E.element(i) = f; h = 0.0; } else { REPORT g = sign(-sqrt(h), f); E.element(i) = g; h -= f*g; Z.element(i,i-1) = f-g; f = 0.0; Real* zji = z + i; Real* zij = z + i*n; Real* ej = E.Store(); int j; for (j=0; j=l; i--) { Real ei = E.element(i); Real di = D.element(i); Real& ei1 = E.element(i+1); g = c * ei; h = c * p; if ( fabs(p) >= fabs(ei)) { REPORT c = ei / p; r = sqrt(c*c + 1.0); ei1 = s*p*r; s = c/r; c = 1.0/r; } else { REPORT c = p / ei; r = sqrt(c*c + 1.0); ei1 = s * ei * r; s = 1.0/r; c /= r; } p = c * di - s*g; D.element(i+1) = h + s * (c*g + s*di); Real* zki = z + i; Real* zki1 = zki + 1; int k = n; if (k) for (;;) { REPORT h = *zki1; *zki1 = s*(*zki) + c*h; *zki = c*(*zki) - s*h; if (!(--k)) break; zki += n; zki1 += n; } } el = s*p; dl = c*p; if (fabs(el) <= b) { REPORT; test = true; break; } } if (!test) Throw ( ConvergenceException(D) ); dl += f; } /* for (int i=0; i= 0; i--) { Real h = 0.0; Real f = - FloatingPointPrecision::Maximum(); Real* d = D.Store(); Real* a = A.Store() + (i*(i+1))/2; int k = i; while (k--) { f = *a++; *d++ = f; h += square(f); } if (h <= tol) { REPORT *(--ei) = 0.0; h = 0.0; } else { REPORT Real g = sign(-sqrt(h), f); *(--ei) = g; h -= f*g; f -= g; *(d-1) = f; *(a-1) = f; f = 0.0; Real* dj = D.Store(); Real* ej = E.Store(); int j; for (j = 0; j < i; j++) { Real* dk = D.Store(); Real* ak = A.Store()+(j*(j+1))/2; Real g = 0.0; k = j; while (k--) g += *ak++ * *dk++; k = i-j; int l = j; if (k) for (;;) { g += *ak * *dk++; if (!(--k)) break; ak += ++l; } g /= h; *ej++ = g; f += g * *dj++; } Real hh = f / (2 * h); Real* ak = A.Store(); dj = D.Store(); ej = E.Store(); for (j = 0; j < i; j++) { f = *dj++; g = *ej - hh * f; *ej++ = g; Real* dk = D.Store(); Real* ek = E.Store(); k = j+1; while (k--) { *ak++ -= (f * *ek++ + g * *dk++); } } } *d = *a; *a = h; } } static void tql1(DiagonalMatrix& D, DiagonalMatrix& E) { Tracer et("Evalue(tql1)"); REPORT Real eps = FloatingPointPrecision::Epsilon(); int n = D.Nrows(); int l; for (l=1; l=l; i--) { Real ei = E.element(i); Real di = D.element(i); Real& ei1 = E.element(i+1); g = c * ei; h = c * p; if ( fabs(p) >= fabs(ei)) { REPORT c = ei / p; r = sqrt(c*c + 1.0); ei1 = s*p*r; s = c/r; c = 1.0/r; } else { REPORT c = p / ei; r = sqrt(c*c + 1.0); ei1 = s * ei * r; s = 1.0/r; c /= r; } p = c * di - s*g; D.element(i+1) = h + s * (c*g + s*di); } el = s*p; dl = c*p; if (fabs(el) <= b) { REPORT test = true; break; } } if (!test) Throw ( ConvergenceException(D) ); Real p = dl + f; test = false; for (i=l; i>0; i--) { if (p < D.element(i-1)) { REPORT D.element(i) = D.element(i-1); } else { REPORT test = true; break; } } if (!test) i=0; D.element(i) = p; } } void EigenValues(const SymmetricMatrix& A, DiagonalMatrix& D, Matrix& Z) { REPORT DiagonalMatrix E; tred2(A, D, E, Z); tql2(D, E, Z); SortSV(D,Z,true); } void EigenValues(const SymmetricMatrix& X, DiagonalMatrix& D) { REPORT DiagonalMatrix E; SymmetricMatrix A; tred3(X,D,E,A); tql1(D,E); } void EigenValues(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A) { REPORT DiagonalMatrix E; tred3(X,D,E,A); tql1(D,E); } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/example.txt000066400000000000000000000075501352751253100202110ustar00rootroot00000000000000 Demonstration of Matrix package Print a real number (may help lost memory test): 3.14159 Test 1 - traditional, bad Estimates and their standard errors 1.39166 0.53188 1.98310 0.20932 0.95221 0.27731 Observations, fitted value, residual value, hat value 2.400 1.700 8.300 7.770 0.530 0.280 1.800 0.900 5.500 5.818 -0.318 0.190 2.400 1.600 8.000 7.675 0.325 0.229 3.000 1.900 8.500 9.150 -0.650 0.446 2.000 0.500 5.700 5.834 -0.134 0.271 1.200 0.600 4.400 4.343 0.057 0.480 2.000 1.100 6.300 6.405 -0.105 0.143 2.700 1.000 7.900 7.698 0.202 0.153 3.600 0.500 9.100 9.007 0.093 0.808 Test 2 - traditional, OK Estimates and their standard errors 1.39166 0.53188 1.98310 0.20932 0.95221 0.27731 Observations, fitted value, residual value, hat value 2.400 1.700 8.300 7.770 0.530 0.280 1.800 0.900 5.500 5.818 -0.318 0.190 2.400 1.600 8.000 7.675 0.325 0.229 3.000 1.900 8.500 9.150 -0.650 0.446 2.000 0.500 5.700 5.834 -0.134 0.271 1.200 0.600 4.400 4.343 0.057 0.480 2.000 1.100 6.300 6.405 -0.105 0.143 2.700 1.000 7.900 7.698 0.202 0.153 3.600 0.500 9.100 9.007 0.093 0.808 Test 3 - Cholesky Estimates and their standard errors 1.39166 0.53188 1.98310 0.20932 0.95221 0.27731 Observations, fitted value, residual value, hat value 2.400 1.700 8.300 7.770 0.530 0.280 1.800 0.900 5.500 5.818 -0.318 0.190 2.400 1.600 8.000 7.675 0.325 0.229 3.000 1.900 8.500 9.150 -0.650 0.446 2.000 0.500 5.700 5.834 -0.134 0.271 1.200 0.600 4.400 4.343 0.057 0.480 2.000 1.100 6.300 6.405 -0.105 0.143 2.700 1.000 7.900 7.698 0.202 0.153 3.600 0.500 9.100 9.007 0.093 0.808 Test 4 - QR triangularisation Estimates and their standard errors 1.39166 0.53188 1.98310 0.20932 0.95221 0.27731 Observations, fitted value, residual value, hat value 2.400 1.700 8.300 7.770 0.530 0.280 1.800 0.900 5.500 5.818 -0.318 0.190 2.400 1.600 8.000 7.675 0.325 0.229 3.000 1.900 8.500 9.150 -0.650 0.446 2.000 0.500 5.700 5.834 -0.134 0.271 1.200 0.600 4.400 4.343 0.057 0.480 2.000 1.100 6.300 6.405 -0.105 0.143 2.700 1.000 7.900 7.698 0.202 0.153 3.600 0.500 9.100 9.007 0.093 0.808 Test 5 - singular value Estimates and their standard errors 1.39166 0.53188 1.98310 0.20932 0.95221 0.27731 Observations, fitted value, residual value, hat value 2.400 1.700 8.300 7.770 0.530 0.280 1.800 0.900 5.500 5.818 -0.318 0.190 2.400 1.600 8.000 7.675 0.325 0.229 3.000 1.900 8.500 9.150 -0.650 0.446 2.000 0.500 5.700 5.834 -0.134 0.271 1.200 0.600 4.400 4.343 0.057 0.480 2.000 1.100 6.300 6.405 -0.105 0.143 2.700 1.000 7.900 7.698 0.202 0.153 3.600 0.500 9.100 9.007 0.093 0.808 The following test does not work with all compilers - see documentation Checking for lost memory: 8206652 8206652 - ok ossim-Miami-2.9.1/src/matrix/fft.cpp000066400000000000000000000357361352751253100173070ustar00rootroot00000000000000//$$ fft.cpp Fast fourier transform // Copyright (C) 1991,2,3,4,8: R B Davies #define WANT_MATH // #define WANT_STREAM #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,19); ++ExeCount; } #else #define REPORT {} #endif static void cossin(int n, int d, Real& c, Real& s) // calculate cos(twopi*n/d) and sin(twopi*n/d) // minimise roundoff error { REPORT long n4 = n * 4; int sector = (int)std::floor( (Real)n4 / (Real)d + 0.5 ); n4 -= sector * d; if (sector < 0) { REPORT sector = 3 - (3 - sector) % 4; } else { REPORT sector %= 4; } Real ratio = 1.5707963267948966192 * (Real)n4 / (Real)d; switch (sector) { case 0: REPORT c = cos(ratio); s = sin(ratio); break; case 1: REPORT c = -sin(ratio); s = cos(ratio); break; case 2: REPORT c = -cos(ratio); s = -sin(ratio); break; case 3: REPORT c = sin(ratio); s = -cos(ratio); break; } } static void fftstep(ColumnVector& A, ColumnVector& B, ColumnVector& X, ColumnVector& Y, int after, int now, int before) { REPORT Tracer trace("FFT(step)"); // const Real twopi = 6.2831853071795864769; const int gamma = after * before; const int delta = now * after; // const Real angle = twopi / delta; Real temp; // Real r_omega = cos(angle); Real i_omega = -sin(angle); Real r_arg = 1.0; Real i_arg = 0.0; Real* x = X.Store(); Real* y = Y.Store(); // pointers to array storage const int m = A.Nrows() - gamma; for (int j = 0; j < now; j++) { Real* a = A.Store(); Real* b = B.Store(); // pointers to array storage Real* x1 = x; Real* y1 = y; x += after; y += after; for (int ia = 0; ia < after; ia++) { // generate sins & cosines explicitly rather than iteratively // for more accuracy; but slower cossin(-(j*after+ia), delta, r_arg, i_arg); Real* a1 = a++; Real* b1 = b++; Real* x2 = x1++; Real* y2 = y1++; if (now==2) { REPORT int ib = before; if (ib) for (;;) { REPORT Real* a2 = m + a1; Real* b2 = m + b1; a1 += after; b1 += after; Real r_value = *a2; Real i_value = *b2; *x2 = r_value * r_arg - i_value * i_arg + *(a2-gamma); *y2 = r_value * i_arg + i_value * r_arg + *(b2-gamma); if (!(--ib)) break; x2 += delta; y2 += delta; } } else { REPORT int ib = before; if (ib) for (;;) { REPORT Real* a2 = m + a1; Real* b2 = m + b1; a1 += after; b1 += after; Real r_value = *a2; Real i_value = *b2; int in = now-1; while (in--) { // it should be possible to make this faster // hand code for now = 2,3,4,5,8 // use symmetry to halve number of operations a2 -= gamma; b2 -= gamma; Real temp = r_value; r_value = r_value * r_arg - i_value * i_arg + *a2; i_value = temp * i_arg + i_value * r_arg + *b2; } *x2 = r_value; *y2 = i_value; if (!(--ib)) break; x2 += delta; y2 += delta; } } // temp = r_arg; // r_arg = r_arg * r_omega - i_arg * i_omega; // i_arg = temp * i_omega + i_arg * r_omega; } } } void FFTI(const ColumnVector& U, const ColumnVector& V, ColumnVector& X, ColumnVector& Y) { // Inverse transform Tracer trace("FFTI"); REPORT FFT(U,-V,X,Y); const Real n = X.Nrows(); X /= n; Y /= (-n); } void RealFFT(const ColumnVector& U, ColumnVector& X, ColumnVector& Y) { // Fourier transform of a real series Tracer trace("RealFFT"); REPORT const int n = U.Nrows(); // length of arrays const int n2 = n / 2; if (n != 2 * n2) Throw(ProgramException("Vector length not multiple of 2", U)); ColumnVector A(n2), B(n2); Real* a = A.Store(); Real* b = B.Store(); Real* u = U.Store(); int i = n2; while (i--) { *a++ = *u++; *b++ = *u++; } FFT(A,B,A,B); int n21 = n2 + 1; X.ReSize(n21); Y.ReSize(n21); i = n2 - 1; a = A.Store(); b = B.Store(); // first els of A and B Real* an = a + i; Real* bn = b + i; // last els of A and B Real* x = X.Store(); Real* y = Y.Store(); // first els of X and Y Real* xn = x + n2; Real* yn = y + n2; // last els of X and Y *x++ = *a + *b; *y++ = 0.0; // first complex element *xn-- = *a++ - *b++; *yn-- = 0.0; // last complex element int j = -1; i = n2/2; while (i--) { Real c,s; cossin(j--,n,c,s); Real am = *a - *an; Real ap = *a++ + *an--; Real bm = *b - *bn; Real bp = *b++ + *bn--; Real samcbp = s * am + c * bp; Real sbpcam = s * bp - c * am; *x++ = 0.5 * ( ap + samcbp); *y++ = 0.5 * ( bm + sbpcam); *xn-- = 0.5 * ( ap - samcbp); *yn-- = 0.5 * (-bm + sbpcam); } } void RealFFTI(const ColumnVector& A, const ColumnVector& B, ColumnVector& U) { // inverse of a Fourier transform of a real series Tracer trace("RealFFTI"); REPORT const int n21 = A.Nrows(); // length of arrays if (n21 != B.Nrows() || n21 == 0) Throw(ProgramException("Vector lengths unequal or zero", A, B)); const int n2 = n21 - 1; const int n = 2 * n2; int i = n2 - 1; ColumnVector X(n2), Y(n2); Real* a = A.Store(); Real* b = B.Store(); // first els of A and B Real* an = a + n2; Real* bn = b + n2; // last els of A and B Real* x = X.Store(); Real* y = Y.Store(); // first els of X and Y Real* xn = x + i; Real* yn = y + i; // last els of X and Y Real hn = 0.5 / n2; *x++ = hn * (*a + *an); *y++ = - hn * (*a - *an); a++; an--; b++; bn--; int j = -1; i = n2/2; while (i--) { Real c,s; cossin(j--,n,c,s); Real am = *a - *an; Real ap = *a++ + *an--; Real bm = *b - *bn; Real bp = *b++ + *bn--; Real samcbp = s * am - c * bp; Real sbpcam = s * bp + c * am; *x++ = hn * ( ap + samcbp); *y++ = - hn * ( bm + sbpcam); *xn-- = hn * ( ap - samcbp); *yn-- = - hn * (-bm + sbpcam); } FFT(X,Y,X,Y); // have done inverting elsewhere U.ReSize(n); i = n2; x = X.Store(); y = Y.Store(); Real* u = U.Store(); while (i--) { *u++ = *x++; *u++ = - *y++; } } void FFT(const ColumnVector& U, const ColumnVector& V, ColumnVector& X, ColumnVector& Y) { // from Carl de Boor (1980), Siam J Sci Stat Comput, 1 173-8 // but first try Sande and Gentleman Tracer trace("FFT"); REPORT const int n = U.Nrows(); // length of arrays if (n != V.Nrows() || n == 0) Throw(ProgramException("Vector lengths unequal or zero", U, V)); if (n == 1) { REPORT X = U; Y = V; return; } // see if we can use the newfft routine if (!FFT_Controller::OnlyOldFFT && FFT_Controller::CanFactor(n)) { REPORT X = U; Y = V; if ( FFT_Controller::ar_1d_ft(n,X.Store(),Y.Store()) ) return; } ColumnVector B = V; ColumnVector A = U; X.ReSize(n); Y.ReSize(n); const int nextmx = 8; int prime[8] = { 2,3,5,7,11,13,17,19 }; int after = 1; int before = n; int next = 0; bool inzee = true; int now = 0; int b1; // initialised to keep gnu happy do { for (;;) { if (next < nextmx) { REPORT now = prime[next]; } b1 = before / now; if (b1 * now == before) { REPORT break; } next++; now += 2; } before = b1; if (inzee) { REPORT fftstep(A, B, X, Y, after, now, before); } else { REPORT fftstep(X, Y, A, B, after, now, before); } inzee = !inzee; after *= now; } while (before != 1); if (inzee) { REPORT A.Release(); X = A; B.Release(); Y = B; } } // Trigonometric transforms // see Charles Van Loan (1992) "Computational frameworks for the fast // Fourier transform" published by SIAM; section 4.4. void DCT_II(const ColumnVector& U, ColumnVector& V) { // Discrete cosine transform, type II, of a real series Tracer trace("DCT_II"); REPORT const int n = U.Nrows(); // length of arrays const int n2 = n / 2; const int n4 = n * 4; if (n != 2 * n2) Throw(ProgramException("Vector length not multiple of 2", U)); ColumnVector A(n); Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); int i = n2; while (i--) { *a++ = *u++; *(--b) = *u++; } ColumnVector X, Y; RealFFT(A, X, Y); A.CleanUp(); V.ReSize(n); Real* x = X.Store(); Real* y = Y.Store(); Real* v = V.Store(); Real* w = v + n; *v = *x; int k = 0; i = n2; while (i--) { Real c, s; cossin(++k, n4, c, s); Real xi = *(++x); Real yi = *(++y); *(++v) = xi * c + yi * s; *(--w) = xi * s - yi * c; } } void DCT_II_inverse(const ColumnVector& V, ColumnVector& U) { // Inverse of discrete cosine transform, type II Tracer trace("DCT_II_inverse"); REPORT const int n = V.Nrows(); // length of array const int n2 = n / 2; const int n4 = n * 4; const int n21 = n2 + 1; if (n != 2 * n2) Throw(ProgramException("Vector length not multiple of 2", V)); ColumnVector X(n21), Y(n21); Real* x = X.Store(); Real* y = Y.Store(); Real* v = V.Store(); Real* w = v + n; *x = *v; *y = 0.0; int i = n2; int k = 0; while (i--) { Real c, s; cossin(++k, n4, c, s); Real vi = *(++v); Real wi = *(--w); *(++x) = vi * c + wi * s; *(++y) = vi * s - wi * c; } ColumnVector A; RealFFTI(X, Y, A); X.CleanUp(); Y.CleanUp(); U.ReSize(n); Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); i = n2; while (i--) { *u++ = *a++; *u++ = *(--b); } } void DST_II(const ColumnVector& U, ColumnVector& V) { // Discrete sine transform, type II, of a real series Tracer trace("DST_II"); REPORT const int n = U.Nrows(); // length of arrays const int n2 = n / 2; const int n4 = n * 4; if (n != 2 * n2) Throw(ProgramException("Vector length not multiple of 2", U)); ColumnVector A(n); Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); int i = n2; while (i--) { *a++ = *u++; *(--b) = -(*u++); } ColumnVector X, Y; RealFFT(A, X, Y); A.CleanUp(); V.ReSize(n); Real* x = X.Store(); Real* y = Y.Store(); Real* v = V.Store(); Real* w = v + n; *(--w) = *x; int k = 0; i = n2; while (i--) { Real c, s; cossin(++k, n4, c, s); Real xi = *(++x); Real yi = *(++y); *v++ = xi * s - yi * c; *(--w) = xi * c + yi * s; } } void DST_II_inverse(const ColumnVector& V, ColumnVector& U) { // Inverse of discrete sine transform, type II Tracer trace("DST_II_inverse"); REPORT const int n = V.Nrows(); // length of array const int n2 = n / 2; const int n4 = n * 4; const int n21 = n2 + 1; if (n != 2 * n2) Throw(ProgramException("Vector length not multiple of 2", V)); ColumnVector X(n21), Y(n21); Real* x = X.Store(); Real* y = Y.Store(); Real* v = V.Store(); Real* w = v + n; *x = *(--w); *y = 0.0; int i = n2; int k = 0; while (i--) { Real c, s; cossin(++k, n4, c, s); Real vi = *v++; Real wi = *(--w); *(++x) = vi * s + wi * c; *(++y) = - vi * c + wi * s; } ColumnVector A; RealFFTI(X, Y, A); X.CleanUp(); Y.CleanUp(); U.ReSize(n); Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); i = n2; while (i--) { *u++ = *a++; *u++ = -(*(--b)); } } void DCT_inverse(const ColumnVector& V, ColumnVector& U) { // Inverse of discrete cosine transform, type I Tracer trace("DCT_inverse"); REPORT const int n = V.Nrows()-1; // length of transform const int n2 = n / 2; const int n21 = n2 + 1; if (n != 2 * n2) Throw(ProgramException("Vector length not multiple of 2", V)); ColumnVector X(n21), Y(n21); Real* x = X.Store(); Real* y = Y.Store(); Real* v = V.Store(); Real vi = *v++; *x++ = vi; *y++ = 0.0; Real sum1 = vi / 2.0; Real sum2 = sum1; vi = *v++; int i = n2-1; while (i--) { Real vi2 = *v++; sum1 += vi2 + vi; sum2 += vi2 - vi; *x++ = vi2; vi2 = *v++; *y++ = vi - vi2; vi = vi2; } sum1 += vi; sum2 -= vi; vi = *v; *x = vi; *y = 0.0; vi /= 2.0; sum1 += vi; sum2 += vi; ColumnVector A; RealFFTI(X, Y, A); X.CleanUp(); Y.CleanUp(); U.ReSize(n+1); Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); v = u + n; i = n2; int k = 0; *u++ = sum1 / n2; *v-- = sum2 / n2; while (i--) { Real s = sin(1.5707963267948966192 * (++k) / n2); Real ai = *(++a); Real bi = *(--b); Real bz = (ai - bi) / 4 / s; Real az = (ai + bi) / 2; *u++ = az - bz; *v-- = az + bz; } } void DCT(const ColumnVector& U, ColumnVector& V) { // Discrete cosine transform, type I Tracer trace("DCT"); REPORT DCT_inverse(U, V); V *= (V.Nrows()-1)/2; } void DST_inverse(const ColumnVector& V, ColumnVector& U) { // Inverse of discrete sine transform, type I Tracer trace("DST_inverse"); REPORT const int n = V.Nrows()-1; // length of transform const int n2 = n / 2; const int n21 = n2 + 1; if (n != 2 * n2) Throw(ProgramException("Vector length not multiple of 2", V)); ColumnVector X(n21), Y(n21); Real* x = X.Store(); Real* y = Y.Store(); Real* v = V.Store(); Real vi = *(++v); *x++ = 2 * vi; *y++ = 0.0; int i = n2-1; while (i--) { *y++ = *(++v); Real vi2 = *(++v); *x++ = vi2 - vi; vi = vi2; } *x = -2 * vi; *y = 0.0; ColumnVector A; RealFFTI(X, Y, A); X.CleanUp(); Y.CleanUp(); U.ReSize(n+1); Real* a = A.Store(); Real* b = a + n; Real* u = U.Store(); v = u + n; i = n2; int k = 0; *u++ = 0.0; *v-- = 0.0; while (i--) { Real s = sin(1.5707963267948966192 * (++k) / n2); Real ai = *(++a); Real bi = *(--b); Real az = (ai + bi) / 4 / s; Real bz = (ai - bi) / 2; *u++ = az - bz; *v-- = az + bz; } } void DST(const ColumnVector& U, ColumnVector& V) { // Discrete sine transform, type I Tracer trace("DST"); REPORT DST_inverse(U, V); V *= (V.Nrows()-1)/2; } // Two dimensional FFT void FFT2(const Matrix& U, const Matrix& V, Matrix& X, Matrix& Y) { Tracer trace("FFT2"); REPORT int m = U.Nrows(); int n = U.Ncols(); if (m != V.Nrows() || n != V.Ncols() || m == 0 || n == 0) Throw(ProgramException("Matrix dimensions unequal or zero", U, V)); X = U; Y = V; int i; ColumnVector CVR; ColumnVector CVI; for (i = 1; i <= m; ++i) { FFT(X.Row(i).t(), Y.Row(i).t(), CVR, CVI); X.Row(i) = CVR.t(); Y.Row(i) = CVI.t(); } for (i = 1; i <= n; ++i) { FFT(X.Column(i), Y.Column(i), CVR, CVI); X.Column(i) = CVR; Y.Column(i) = CVI; } } void FFT2I(const Matrix& U, const Matrix& V, Matrix& X, Matrix& Y) { // Inverse transform Tracer trace("FFT2I"); REPORT FFT2(U,-V,X,Y); const Real n = X.Nrows() * X.Ncols(); X /= n; Y /= (-n); } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/gnu.mak000066400000000000000000000075471352751253100173060ustar00rootroot00000000000000CXX = g++ CXXFLAGS = -O2 -Wall everything: libnewmat.a tmt example nl_ex sl_ex garch test_exc %.o: %.cpp $(CXX) $(CXXFLAGS) -c $*.cpp OBJ_LIB = bandmat.o cholesky.o evalue.o fft.o hholder.o \ jacobi.o myexcept.o newmat1.o newmat2.o newmat3.o \ newmat4.o newmat5.o newmat6.o newmat7.o newmat8.o \ newmat9.o newmatex.o newmatnl.o newmatrm.o solution.o \ sort.o submat.o svd.o newfft.o libnewmat.a: $(OBJ_LIB) $(AR) cr $@ $(OBJ_LIB) ranlib $@ OBJ_T = tmt.o tmt1.o tmt2.o tmt3.o tmt4.o tmt5.o tmt6.o \ tmt7.o tmt8.o tmt9.o tmta.o tmtb.o tmtc.o tmtd.o tmte.o \ tmtf.o tmtg.o tmth.o tmti.o tmtj.o tmtk.o tmtl.o tmt: $(OBJ_T) libnewmat.a $(CXX) -o $@ $(OBJ_T) -L. -lnewmat -lm OBJ_E = example.o example: $(OBJ_E) libnewmat.a $(CXX) -o $@ $(OBJ_E) -L. -lnewmat -lm OBJ_N = nl_ex.o nl_ex: $(OBJ_N) libnewmat.a $(CXX) -o $@ $(OBJ_N) -L. -lnewmat -lm OBJ_S = sl_ex.o sl_ex: $(OBJ_S) libnewmat.a $(CXX) -o $@ $(OBJ_S) -L. -lnewmat -lm OBJ_G = garch.o garch: $(OBJ_G) libnewmat.a $(CXX) -o $@ $(OBJ_G) -L. -lnewmat -lm OBJ_X = test_exc.o test_exc: $(OBJ_X) libnewmat.a $(CXX) -o $@ $(OBJ_X) -L. -lnewmat -lm newmatxx = include.h newmat.h boolean.h myexcept.h myexcept.o: include.h boolean.h myexcept.h myexcept.cpp newmatex.o: $(newmatxx) newmatex.cpp newmatnl.o: $(newmatxx) newmatnl.h newmatap.h example.o: $(newmatxx) newmatap.h example.cpp cholesky.o: $(newmatxx) cholesky.cpp evalue.o: $(newmatxx) newmatrm.h precisio.h evalue.cpp fft.o: $(newmatxx) newmatap.h fft.cpp hholder.o: $(newmatxx) newmatap.h hholder.cpp jacobi.o: $(newmatxx) precisio.h newmatrm.h jacobi.cpp bandmat.o: $(newmatxx) newmatrc.h controlw.h bandmat.cpp newfft.o: $(newmatxx) newmatap.h newfft.cpp newmat1.o: $(newmatxx) newmat1.cpp newmat2.o: $(newmatxx) newmatrc.h controlw.h newmat2.cpp newmat3.o: $(newmatxx) newmatrc.h controlw.h newmat3.cpp newmat4.o: $(newmatxx) newmatrc.h controlw.h newmat4.cpp newmat5.o: $(newmatxx) newmatrc.h controlw.h newmat5.cpp newmat6.o: $(newmatxx) newmatrc.h controlw.h newmat6.cpp newmat7.o: $(newmatxx) newmatrc.h controlw.h newmat7.cpp newmat8.o: $(newmatxx) newmatap.h newmat8.cpp newmat9.o: $(newmatxx) newmatrc.h controlw.h newmatio.h newmat9.cpp newmatrm.o: $(newmatxx) newmatrm.h newmatrm.cpp sort.o: $(newmatxx) newmatap.h sort.cpp submat.o: $(newmatxx) newmatrc.h controlw.h submat.cpp svd.o: $(newmatxx) newmatrm.h precisio.h svd.cpp tmt.o: $(newmatxx) newmatap.h tmt.cpp tmt1.o: $(newmatxx) newmatap.h tmt1.cpp tmt2.o: $(newmatxx) newmatap.h tmt2.cpp tmt3.o: $(newmatxx) newmatap.h tmt3.cpp tmt4.o: $(newmatxx) newmatap.h tmt4.cpp tmt5.o: $(newmatxx) newmatap.h tmt5.cpp tmt6.o: $(newmatxx) newmatap.h tmt6.cpp tmt7.o: $(newmatxx) newmatap.h tmt7.cpp tmt8.o: $(newmatxx) newmatap.h tmt8.cpp tmt9.o: $(newmatxx) newmatap.h tmt9.cpp tmta.o: $(newmatxx) newmatap.h tmta.cpp tmtb.o: $(newmatxx) newmatap.h tmtb.cpp tmtc.o: $(newmatxx) newmatap.h tmtc.cpp tmtd.o: $(newmatxx) newmatap.h tmtd.cpp tmte.o: $(newmatxx) newmatap.h tmte.cpp tmtf.o: $(newmatxx) newmatap.h tmtf.cpp tmtg.o: $(newmatxx) newmatap.h tmtg.cpp tmth.o: $(newmatxx) newmatap.h tmth.cpp tmti.o: $(newmatxx) newmatap.h tmti.cpp tmtj.o: $(newmatxx) newmatap.h tmtj.cpp tmtk.o: $(newmatxx) newmatap.h tmtk.cpp tmtl.o: $(newmatxx) newmatap.h tmtl.cpp nl_ex.o: $(newmatxx) newmatap.h newmatnl.h nl_ex.cpp sl_ex.o: include.h boolean.h myexcept.h sl_ex.cpp solution.o: include.h boolean.h myexcept.h solution.cpp garch.o: $(newmatxx) newmatap.h newmatnl.h garch.cpp test_exc.o: $(newmatxx) test_exc.cpp ossim-Miami-2.9.1/src/matrix/hholder.cpp000066400000000000000000000201611352751253100201370ustar00rootroot00000000000000//$$ hholder.cpp QR decomposition // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH //#define WANT_STREAM #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,16); ++ExeCount; } #else #define REPORT {} #endif /*************************** QR decompositions ***************************/ inline Real square(Real x) { return x*x; } void QRZT(Matrix& X, LowerTriangularMatrix& L) { REPORT Tracer et("QRZT(1)"); int n = X.Ncols(); int s = X.Nrows(); L.ReSize(s); Real* xi = X.Store(); int k; for (int i=0; i #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,18); ++ExeCount; } #else #define REPORT {} #endif void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A, Matrix& V, bool eivec) { Real epsilon = FloatingPointPrecision::Epsilon(); Tracer et("Jacobi"); REPORT int n = X.Nrows(); DiagonalMatrix B(n), Z(n); D.ReSize(n); A = X; if (eivec) { REPORT V.ReSize(n,n); D = 1.0; V = D; } B << A; D = B; Z = 0.0; A.Inject(Z); bool converged = false; for (int i=1; i<=50; i++) { Real sm=0.0; Real* a = A.Store(); int p = A.Storage(); while (p--) sm += fabs(*a++); // have previously zeroed diags if (sm==0.0) { REPORT converged = true; break; } Real tresh = (i<4) ? 0.2 * sm / square(n) : 0.0; a = A.Store(); for (p = 0; p < n; p++) { Real* ap1 = a + (p*(p+1))/2; Real& zp = Z.element(p); Real& dp = D.element(p); for (int q = p+1; q < n; q++) { Real* ap = ap1; Real* aq = a + (q*(q+1))/2; Real& zq = Z.element(q); Real& dq = D.element(q); Real& apq = A.element(q,p); Real g = 100 * fabs(apq); Real adp = fabs(dp); Real adq = fabs(dq); if (i>4 && g < epsilon*adp && g < epsilon*adq) { REPORT apq = 0.0; } else if (fabs(apq) > tresh) { REPORT Real t; Real h = dq - dp; Real ah = fabs(h); if (g < epsilon*ah) { REPORT t = apq / h; } else { REPORT Real theta = 0.5 * h / apq; t = 1.0 / ( fabs(theta) + sqrt(1.0 + square(theta)) ); if (theta<0.0) { REPORT t = -t; } } Real c = 1.0 / sqrt(1.0 + square(t)); Real s = t * c; Real tau = s / (1.0 + c); h = t * apq; zp -= h; zq += h; dp -= h; dq += h; apq = 0.0; int j = p; while (j--) { g = *ap; h = *aq; *ap++ = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau); } int ip = p+1; j = q-ip; ap += ip++; aq++; while (j--) { g = *ap; h = *aq; *ap = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau); ap += ip++; } if (q < n-1) // last loop is non-empty { int iq = q+1; j = n-iq; ap += ip++; aq += iq++; for (;;) { g = *ap; h = *aq; *ap = g-s*(h+g*tau); *aq = h+s*(g-h*tau); if (!(--j)) break; ap += ip++; aq += iq++; } } if (eivec) { REPORT RectMatrixCol VP(V,p); RectMatrixCol VQ(V,q); Rotate(VP, VQ, tau, s); } } } } B = B + Z; D = B; Z = 0.0; } if (!converged) Throw(ConvergenceException(X)); if (eivec) SortSV(D, V, true); else SortAscending(D); } void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D) { REPORT SymmetricMatrix A; Matrix V; Jacobi(X,D,A,V,false); } void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A) { REPORT Matrix V; Jacobi(X,D,A,V,false); } void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, Matrix& V) { REPORT SymmetricMatrix A; Jacobi(X,D,A,V,true); } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/ms.mak000066400000000000000000000163151352751253100171250ustar00rootroot00000000000000.SUFFIXES: .cpp everything: tmt.exe example.exe nl_ex.exe sl_ex.exe garch.exe test_exc.exe .cpp.obj: cl -AL -c $*.cpp OBJ_LIB = bandmat.obj cholesky.obj evalue.obj fft.obj hholder.obj \ jacobi.obj myexcept.obj newmat1.obj newmat2.obj newmat3.obj \ newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj \ newmat9.obj newmatex.obj newmatnl.obj newmatrm.obj solution.obj \ sort.obj submat.obj svd.obj newfft.obj OBJ_T = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj \ tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj \ tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmt.exe: $(OBJ_T) $(OBJ_LIB) echo newmat1.obj+newmat2.obj+newmat3.obj+ > link.lnk echo newmat4.obj+svd.obj+newmat5.obj+ >> link.lnk echo newmat6.obj+newmat7.obj+newmat8.obj+ >> link.lnk echo tmt.obj+tmt1.obj+tmt2.obj+tmt3.obj+ >> link.lnk echo tmt4.obj+tmt5.obj+tmt6.obj+tmt7.obj+ >> link.lnk echo tmt8.obj+tmt9.obj+tmta.obj+tmti.obj+ >> link.lnk echo tmtb.obj+tmtc.obj+tmtd.obj+tmte.obj+ >> link.lnk echo tmtf.obj+tmtg.obj+tmth.obj+tmtj.obj+ >> link.lnk echo tmtk.obj+tmtl.obj+ >> link.lnk echo cholesky.obj+hholder.obj+sort.obj+ >> link.lnk echo submat.obj+jacobi.obj+newmatrm.obj+ >> link.lnk echo fft.obj+evalue.obj+bandmat.obj+ >> link.lnk echo newmatex.obj+myexcept.obj+newfft.obj, >> link.lnk echo tmt.exe; >> link.lnk link @link.lnk OBJ_E = example.obj example.exe: $(OBJ_E) $(OBJ_LIB) echo newmat1.obj+newmat2.obj+newmat3.obj+ > link.lnk echo newmat4.obj+svd.obj+newmat5.obj+ >> link.lnk echo newmat6.obj+newmat7.obj+newmat8.obj+ >> link.lnk echo cholesky.obj+hholder.obj+sort.obj+ >> link.lnk echo submat.obj+jacobi.obj+newmatrm.obj+ >> link.lnk echo fft.obj+evalue.obj+bandmat.obj+ >> link.lnk echo newmatex.obj+myexcept.obj+newmat9+ >> link.lnk echo newfft.obj+example.obj, >> link.lnk echo example.exe; >> link.lnk link @link.lnk OBJ_N = nl_ex.obj nl_ex.exe: $(OBJ_N) $(OBJ_LIB) echo newmat1.obj+newmat2.obj+newmat3.obj+ > link.lnk echo newmat4.obj+svd.obj+newmat5.obj+ >> link.lnk echo newmat6.obj+newmat7.obj+newmat8.obj+ >> link.lnk echo cholesky.obj+hholder.obj+sort.obj+ >> link.lnk echo submat.obj+jacobi.obj+newmatrm.obj+ >> link.lnk echo fft.obj+evalue.obj+bandmat.obj+ >> link.lnk echo newmatex.obj+myexcept.obj+newmat9.obj+ >> link.lnk echo newmatnl.obj+nl_ex.obj+newfft.obj, >> link.lnk echo nl_ex.exe; >> link.lnk link @link.lnk OBJ_S = sl_ex.obj sl_ex.exe: $(OBJ_S) $(OBJ_LIB) echo solution.obj+myexcept.obj+sl_ex.obj, > link.lnk echo sl_ex.exe; >> link.lnk link @link.lnk OBJ_G = garch.obj garch.exe: $(OBJ_G) $(OBJ_LIB) echo newmat1.obj+newmat2.obj+newmat3.obj+ > link.lnk echo newmat4.obj+svd.obj+newmat5.obj+ >> link.lnk echo newmat6.obj+newmat7.obj+newmat8.obj+ >> link.lnk echo cholesky.obj+hholder.obj+sort.obj+ >> link.lnk echo submat.obj+jacobi.obj+newmatrm.obj+ >> link.lnk echo fft.obj+evalue.obj+bandmat.obj+ >> link.lnk echo newmatex.obj+myexcept.obj+newmat9.obj+ >> link.lnk echo newmatnl.obj+garch.obj+newfft.obj, >> link.lnk echo garch.exe; >> link.lnk link @link.lnk OBJ_X = test_exc.obj test_exc.exe: $(OBJ_X) $(OBJ_LIB) echo newmat1.obj+newmat2.obj+newmat3.obj+ > link.lnk echo newmat4.obj+svd.obj+newmat5.obj+ >> link.lnk echo newmat6.obj+newmat7.obj+newmat8.obj+ >> link.lnk echo cholesky.obj+hholder.obj+sort.obj+ >> link.lnk echo submat.obj+jacobi.obj+newmatrm.obj+ >> link.lnk echo fft.obj+evalue.obj+bandmat.obj+ >> link.lnk echo newmatex.obj+myexcept.obj+newmat9.obj+ >> link.lnk echo test_exc.obj+newfft.obj, >> link.lnk echo test_exc.exe; >> link.lnk link @link.lnk newmatxx = include.h newmat.h boolean.h myexcept.h myexcept.obj: include.h boolean.h myexcept.h myexcept.cpp newmatex.obj: $(newmatxx) newmatex.cpp newmatnl.obj: $(newmatxx) newmatnl.h newmatap.h example.obj: $(newmatxx) newmatap.h example.cpp cholesky.obj: $(newmatxx) cholesky.cpp evalue.obj: $(newmatxx) newmatrm.h precisio.h evalue.cpp fft.obj: $(newmatxx) newmatap.h fft.cpp newfft.obj: $(newmatxx) newmatap.h newfft.cpp hholder.obj: $(newmatxx) newmatap.h hholder.cpp jacobi.obj: $(newmatxx) precisio.h newmatrm.h jacobi.cpp bandmat.obj: $(newmatxx) newmatrc.h controlw.h bandmat.cpp newmat1.obj: $(newmatxx) newmat1.cpp newmat2.obj: $(newmatxx) newmatrc.h controlw.h newmat2.cpp newmat3.obj: $(newmatxx) newmatrc.h controlw.h newmat3.cpp newmat4.obj: $(newmatxx) newmatrc.h controlw.h newmat4.cpp newmat5.obj: $(newmatxx) newmatrc.h controlw.h newmat5.cpp newmat6.obj: $(newmatxx) newmatrc.h controlw.h newmat6.cpp newmat7.obj: $(newmatxx) newmatrc.h controlw.h newmat7.cpp newmat8.obj: $(newmatxx) newmatap.h newmat8.cpp newmat9.obj: $(newmatxx) newmatrc.h controlw.h newmatio.h newmat9.cpp newmatrm.obj: $(newmatxx) newmatrm.h newmatrm.cpp sort.obj: $(newmatxx) newmatap.h sort.cpp submat.obj: $(newmatxx) newmatrc.h controlw.h submat.cpp svd.obj: $(newmatxx) newmatrm.h precisio.h svd.cpp tmt.obj: $(newmatxx) newmatap.h tmt.cpp tmt1.obj: $(newmatxx) newmatap.h tmt1.cpp tmt2.obj: $(newmatxx) newmatap.h tmt2.cpp tmt3.obj: $(newmatxx) newmatap.h tmt3.cpp tmt4.obj: $(newmatxx) newmatap.h tmt4.cpp tmt5.obj: $(newmatxx) newmatap.h tmt5.cpp tmt6.obj: $(newmatxx) newmatap.h tmt6.cpp tmt7.obj: $(newmatxx) newmatap.h tmt7.cpp tmt8.obj: $(newmatxx) newmatap.h tmt8.cpp tmt9.obj: $(newmatxx) newmatap.h tmt9.cpp tmta.obj: $(newmatxx) newmatap.h tmta.cpp tmtb.obj: $(newmatxx) newmatap.h tmtb.cpp tmtc.obj: $(newmatxx) newmatap.h tmtc.cpp tmtd.obj: $(newmatxx) newmatap.h tmtd.cpp tmte.obj: $(newmatxx) newmatap.h tmte.cpp tmtf.obj: $(newmatxx) newmatap.h tmtf.cpp tmtg.obj: $(newmatxx) newmatap.h tmtg.cpp tmth.obj: $(newmatxx) newmatap.h tmth.cpp tmti.obj: $(newmatxx) newmatap.h tmti.cpp tmtj.obj: $(newmatxx) newmatap.h tmtj.cpp tmtk.obj: $(newmatxx) newmatap.h tmtk.cpp tmtl.obj: $(newmatxx) newmatap.h tmtl.cpp nl_ex.obj: $(newmatxx) newmatap.h newmatnl.h nl_ex.cpp sl_ex.obj: include.h boolean.h myexcept.h sl_ex.cpp solution.obj: include.h boolean.h myexcept.h solution.cpp garch.obj: $(newmatxx) newmatap.h newmatnl.h garch.cpp test_exc.obj: $(newmatxx) test_exc.cpp ossim-Miami-2.9.1/src/matrix/ms_nt.mak000066400000000000000000000102651352751253100176240ustar00rootroot00000000000000!include .SUFFIXES: .cpp everything: tmt.exe example.exe nl_ex.exe sl_ex.exe garch.exe test_exc.exe .cpp.obj: cl -c -W3 -Ox $*.cpp OBJ_LIB = bandmat.obj cholesky.obj evalue.obj fft.obj hholder.obj \ jacobi.obj myexcept.obj newmat1.obj newmat2.obj newmat3.obj \ newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj \ newmat9.obj newmatex.obj newmatnl.obj newmatrm.obj solution.obj \ sort.obj submat.obj svd.obj newfft.obj OBJ_T = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj \ tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj \ tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmt.exe: $(OBJ_T) $(OBJ_LIB) link -OUT:tmt.exe $(conlflags) $(conlibs) $(OBJ_T) $(OBJ_LIB) OBJ_E = example.obj example.exe: $(OBJ_E) $(OBJ_LIB) link -OUT:example.exe $(conlflags) $(conlibs) $(OBJ_E) $(OBJ_LIB) OBJ_N = nl_ex.obj nl_ex.exe: $(OBJ_N) $(OBJ_LIB) link -OUT:nl_ex.exe $(conlflags) $(conlibs) $(OBJ_N) $(OBJ_LIB) OBJ_S = sl_ex.obj sl_ex.exe: $(OBJ_S) $(OBJ_LIB) link -OUT:sl_ex.exe $(conlflags) $(conlibs) $(OBJ_S) $(OBJ_LIB) OBJ_G = garch.obj garch.exe: $(OBJ_G) $(OBJ_LIB) link -OUT:garch.exe $(conlflags) $(conlibs) $(OBJ_G) $(OBJ_LIB) OBJ_X = test_exc.obj test_exc.exe: $(OBJ_X) $(OBJ_LIB) link -OUT:test_exc.exe $(conlflags) $(conlibs) $(OBJ_X) $(OBJ_LIB) newmatxx = include.h newmat.h boolean.h myexcept.h myexcept.obj: include.h boolean.h myexcept.h myexcept.cpp newmatex.obj: $(newmatxx) newmatex.cpp newmatnl.obj: $(newmatxx) newmatnl.h newmatap.h example.obj: $(newmatxx) newmatap.h example.cpp cholesky.obj: $(newmatxx) cholesky.cpp evalue.obj: $(newmatxx) newmatrm.h precisio.h evalue.cpp fft.obj: $(newmatxx) newmatap.h fft.cpp newfft.obj: $(newmatxx) newmatap.h newfft.cpp hholder.obj: $(newmatxx) newmatap.h hholder.cpp jacobi.obj: $(newmatxx) precisio.h newmatrm.h jacobi.cpp bandmat.obj: $(newmatxx) newmatrc.h controlw.h bandmat.cpp newmat1.obj: $(newmatxx) newmat1.cpp newmat2.obj: $(newmatxx) newmatrc.h controlw.h newmat2.cpp newmat3.obj: $(newmatxx) newmatrc.h controlw.h newmat3.cpp newmat4.obj: $(newmatxx) newmatrc.h controlw.h newmat4.cpp newmat5.obj: $(newmatxx) newmatrc.h controlw.h newmat5.cpp newmat6.obj: $(newmatxx) newmatrc.h controlw.h newmat6.cpp newmat7.obj: $(newmatxx) newmatrc.h controlw.h newmat7.cpp newmat8.obj: $(newmatxx) newmatap.h newmat8.cpp newmat9.obj: $(newmatxx) newmatrc.h controlw.h newmatio.h newmat9.cpp newmatrm.obj: $(newmatxx) newmatrm.h newmatrm.cpp sort.obj: $(newmatxx) newmatap.h sort.cpp submat.obj: $(newmatxx) newmatrc.h controlw.h submat.cpp svd.obj: $(newmatxx) newmatrm.h precisio.h svd.cpp tmt.obj: $(newmatxx) newmatap.h tmt.cpp tmt1.obj: $(newmatxx) newmatap.h tmt1.cpp tmt2.obj: $(newmatxx) newmatap.h tmt2.cpp tmt3.obj: $(newmatxx) newmatap.h tmt3.cpp tmt4.obj: $(newmatxx) newmatap.h tmt4.cpp tmt5.obj: $(newmatxx) newmatap.h tmt5.cpp tmt6.obj: $(newmatxx) newmatap.h tmt6.cpp tmt7.obj: $(newmatxx) newmatap.h tmt7.cpp tmt8.obj: $(newmatxx) newmatap.h tmt8.cpp tmt9.obj: $(newmatxx) newmatap.h tmt9.cpp tmta.obj: $(newmatxx) newmatap.h tmta.cpp tmtb.obj: $(newmatxx) newmatap.h tmtb.cpp tmtc.obj: $(newmatxx) newmatap.h tmtc.cpp tmtd.obj: $(newmatxx) newmatap.h tmtd.cpp tmte.obj: $(newmatxx) newmatap.h tmte.cpp tmtf.obj: $(newmatxx) newmatap.h tmtf.cpp tmtg.obj: $(newmatxx) newmatap.h tmtg.cpp tmth.obj: $(newmatxx) newmatap.h tmth.cpp tmti.obj: $(newmatxx) newmatap.h tmti.cpp tmtj.obj: $(newmatxx) newmatap.h tmtj.cpp tmtk.obj: $(newmatxx) newmatap.h tmtk.cpp tmtl.obj: $(newmatxx) newmatap.h tmtl.cpp nl_ex.obj: $(newmatxx) newmatap.h newmatnl.h nl_ex.cpp sl_ex.obj: include.h boolean.h myexcept.h sl_ex.cpp solution.obj: include.h boolean.h myexcept.h solution.cpp garch.obj: $(newmatxx) newmatap.h newmatnl.h garch.cpp test_exc.obj: $(newmatxx) test_exc.cpp ossim-Miami-2.9.1/src/matrix/myexcept.cpp000066400000000000000000000321571352751253100203600ustar00rootroot00000000000000//$$myexcept.cpp Exception handler // Copyright (C) 1993,4,6: R B Davies #define WANT_STREAM // include.h will get stream fns #define WANT_STRING #include #include #include #include using namespace std; #include #ifdef use_namespace namespace RBD_COMMON { #endif //#define REG_DEREG // for print out uses of new/delete //#define CLEAN_LIST // to print entries being added to // or deleted from cleanup list #ifdef SimulateExceptions void Throw() { for (Janitor* jan = JumpBase::jl->janitor; jan; jan = jan->NextJanitor) jan->CleanUp(); JumpItem* jx = JumpBase::jl->ji; // previous jumpbase; if ( !jx ) { Terminate(); } // jl was initial JumpItem JumpBase::jl = jx; // drop down a level; cannot be in front // of previous line Tracer::last = JumpBase::jl->trace; longjmp(JumpBase::jl->env, 1); } #endif // end of simulate exceptions unsigned long BaseException::Select; char* BaseException::what_error; int BaseException::SoFar; int BaseException::LastOne; BaseException::BaseException(const char* a_what) { Select++; SoFar = 0; if (!what_error) // make space for exception message { LastOne = 511; what_error = new char[512]; if (!what_error) // fail to make space { LastOne = 0; what_error = (char *)"No heap space for exception message\n"; } } AddMessage("\n\nAn exception has been thrown\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } void BaseException::AddMessage(const char* a_what) { if (a_what) { int l = (int)strlen(a_what); int r = LastOne - SoFar; if (l < r) { strcpy(what_error+SoFar, a_what); SoFar += l; } else if (r > 0) { strncpy(what_error+SoFar, a_what, r); what_error[LastOne] = 0; SoFar = LastOne; } } } void BaseException::AddInt(int value) { bool negative; if (value == 0) { AddMessage("0"); return; } else if (value < 0) { value = -value; negative = true; } else negative = false; int n = 0; int v = value; // how many digits will we need? while (v > 0) { v /= 10; n++; } if (negative) n++; if (LastOne-SoFar < n) { AddMessage("***"); return; } SoFar += n; n = SoFar; what_error[n] = 0; while (value > 0) { int nv = value / 10; int rm = value - nv * 10; value = nv; what_error[--n] = (char)(rm + '0'); } if (negative) what_error[--n] = '-'; return; } void Tracer::PrintTrace() { std::cout << "\n"; for (Tracer* et = last; et; et=et->previous) std::cout << " * " << et->entry << "\n"; } void Tracer::AddTrace() { if (last) { BaseException::AddMessage("Trace: "); BaseException::AddMessage(last->entry); for (Tracer* et = last->previous; et; et=et->previous) { BaseException::AddMessage("; "); BaseException::AddMessage(et->entry); } BaseException::AddMessage(".\n"); } } #ifdef SimulateExceptions Janitor::Janitor() { if (do_not_link) { do_not_link = false; NextJanitor = 0; OnStack = false; #ifdef CLEAN_LIST std::cout << "Not added to clean-list " << (unsigned long)this << "\n"; #endif } else { OnStack = true; #ifdef CLEAN_LIST std::cout << "Add to clean-list " << (unsigned long)this << "\n"; #endif NextJanitor = JumpBase::jl->janitor; JumpBase::jl->janitor=this; } } Janitor::~Janitor() { // expect the item to be deleted to be first on list // but must be prepared to search list if (OnStack) { #ifdef CLEAN_LIST std::cout << "Delete from clean-list " << (unsigned long)this << "\n"; #endif Janitor* lastjan = JumpBase::jl->janitor; if (this == lastjan) JumpBase::jl->janitor = NextJanitor; else { for (Janitor* jan = lastjan->NextJanitor; jan; jan = lastjan->NextJanitor) { if (jan==this) { lastjan->NextJanitor = jan->NextJanitor; return; } lastjan=jan; } Throw(BaseException( "Cannot resolve memory linked list\nSee notes in myexcept.cpp for details\n" )); // This message occurs when a call to ~Janitor() occurs, apparently // without a corresponding call to Janitor(). This could happen if my // way of deciding whether a constructor is being called by new // fails. // It may happen if you are using my simulated exceptions and also have // your compiler s exceptions turned on. // It can also happen if you have a class derived from Janitor // which does not include a copy constructor [ eg X(const &X) ]. // Possibly also if delete is applied an object on the stack (ie not // called by new). Otherwise, it is a bug in myexcept or your compiler. // If you do not #define TEMPS_DESTROYED_QUICKLY you will get this // error with Microsoft C 7.0. There are probably situations where // you will get this when you do define TEMPS_DESTROYED_QUICKLY. This // is a bug in MSC. Beware of "operator" statements for defining // conversions; particularly for converting from a Base class to a // Derived class. // You may get away with simply deleting this error message and Throw // statement if you can not find a better way of overcoming the // problem. In any case please tell me if you get this error message, // particularly for compilers apart from Microsoft C 7.0. } } } JumpItem* JumpBase::jl; // will be set to zero jmp_buf JumpBase::env; bool Janitor::do_not_link; // will be set to false int JanitorInitializer::ref_count; JanitorInitializer::JanitorInitializer() { if (ref_count++ == 0) new JumpItem; // need JumpItem at head of list } #endif // end of SimulateExceptions Tracer* Tracer::last; // will be set to zero void Terminate() { std::cout << "\n\nThere has been an exception with no handler - exiting"; const char* what = BaseException::what(); if (what) std::cout << what << "\n"; exit(1); } #ifdef DO_FREE_CHECK // Routines for tracing whether new and delete calls are balanced FreeCheckLink::FreeCheckLink() : next(FreeCheck::next) { FreeCheck::next = this; } FCLClass::FCLClass(void* t, char* name) : ClassName(name) { ClassStore=t; } FCLRealArray::FCLRealArray(void* t, char* o, int s) : Operation(o), size(s) { ClassStore=t; } FCLIntArray::FCLIntArray(void* t, char* o, int s) : Operation(o), size(s) { ClassStore=t; } FreeCheckLink* FreeCheck::next; int FreeCheck::BadDelete; void FCLClass::Report() { std::cout << " " << ClassName << " " << (unsigned long)ClassStore << "\n"; } void FCLRealArray::Report() { std::cout << " " << Operation << " " << (unsigned long)ClassStore << " " << size << "\n"; } void FCLIntArray::Report() { std::cout << " " << Operation << " " << (unsigned long)ClassStore << " " << size << "\n"; } void FreeCheck::Register(void* t, char* name) { FCLClass* f = new FCLClass(t,name); if (!f) { std::cout << "Out of memory in FreeCheck\n"; exit(1); } #ifdef REG_DEREG std::cout << "Registering " << name << " " << (unsigned long)t << "\n"; #endif } void FreeCheck::RegisterR(void* t, char* o, int s) { FCLRealArray* f = new FCLRealArray(t,o,s); if (!f) { std::cout << "Out of memory in FreeCheck\n"; exit(1); } #ifdef REG_DEREG std::cout << o << " " << s << " " << (unsigned long)t << "\n"; #endif } void FreeCheck::RegisterI(void* t, char* o, int s) { FCLIntArray* f = new FCLIntArray(t,o,s); if (!f) { std::cout << "Out of memory in FreeCheck\n"; exit(1); } #ifdef REG_DEREG std::cout << o << " " << s << " " << (unsigned long)t << "\n"; #endif } void FreeCheck::DeRegister(void* t, char* name) { FreeCheckLink* last = 0; #ifdef REG_DEREG std::cout << "Deregistering " << name << " " << (unsigned long)t << "\n"; #endif for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) { if (fcl->ClassStore==t) { if (last) last->next = fcl->next; else next = fcl->next; delete fcl; return; } last = fcl; } std::cout << "\nRequest to delete non-existent object of class and location:\n"; std::cout << " " << name << " " << (unsigned long)t << "\n"; BadDelete++; Tracer::PrintTrace(); std::cout << "\n"; } void FreeCheck::DeRegisterR(void* t, char* o, int s) { FreeCheckLink* last = 0; #ifdef REG_DEREG std::cout << o << " " << s << " " << (unsigned long)t << "\n"; #endif for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) { if (fcl->ClassStore==t) { if (last) last->next = fcl->next; else next = fcl->next; if (s >= 0 && ((FCLRealArray*)fcl)->size != s) { std::cout << "\nArray sizes do not agree:\n"; std::cout << " " << o << " " << (unsigned long)t << " " << ((FCLRealArray*)fcl)->size << " " << s << "\n"; Tracer::PrintTrace(); std::cout << "\n"; } delete fcl; return; } last = fcl; } std::cout << "\nRequest to delete non-existent real array:\n"; std::cout << " " << o << " " << (unsigned long)t << " " << s << "\n"; BadDelete++; Tracer::PrintTrace(); std::cout << "\n"; } void FreeCheck::DeRegisterI(void* t, char* o, int s) { FreeCheckLink* last = 0; #ifdef REG_DEREG std::cout << o << " " << s << " " << (unsigned long)t << "\n"; #endif for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) { if (fcl->ClassStore==t) { if (last) last->next = fcl->next; else next = fcl->next; if (s >= 0 && ((FCLIntArray*)fcl)->size != s) { std::cout << "\nArray sizes do not agree:\n"; std::cout << " " << o << " " << (unsigned long)t << " " << ((FCLIntArray*)fcl)->size << " " << s << "\n"; Tracer::PrintTrace(); std::cout << "\n"; } delete fcl; return; } last = fcl; } std::cout << "\nRequest to delete non-existent int array:\n"; std::cout << " " << o << " " << (unsigned long)t << " " << s << "\n"; BadDelete++; Tracer::PrintTrace(); std::cout << "\n"; } void FreeCheck::Status() { if (next) { std::cout << "\nObjects of the following classes remain undeleted:\n"; for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) fcl->Report(); std::cout << "\n"; } else std::cout << "\nNo objects remain undeleted\n\n"; if (BadDelete) { std::cout << "\nThere were " << BadDelete << " requests to delete non-existent items\n\n"; } } #endif // end of DO_FREE_CHECK // derived exception bodies Logic_error::Logic_error(const char* a_what) : BaseException() { Select = BaseException::Select; AddMessage("Logic error:- "); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Runtime_error::Runtime_error(const char* a_what) : BaseException() { Select = BaseException::Select; AddMessage("Runtime error:- "); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Domain_error::Domain_error(const char* a_what) : Logic_error() { Select = BaseException::Select; AddMessage("domain error\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Invalid_argument::Invalid_argument(const char* a_what) : Logic_error() { Select = BaseException::Select; AddMessage("invalid argument\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Length_error::Length_error(const char* a_what) : Logic_error() { Select = BaseException::Select; AddMessage("length error\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Out_of_range::Out_of_range(const char* a_what) : Logic_error() { Select = BaseException::Select; AddMessage("out of range\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } //Bad_cast::Bad_cast(const char* a_what) : Logic_error() //{ // Select = BaseException::Select; // AddMessage("bad cast\n"); AddMessage(a_what); // if (a_what) Tracer::AddTrace(); //} //Bad_typeid::Bad_typeid(const char* a_what) : Logic_error() //{ // Select = BaseException::Select; // AddMessage("bad type id.\n"); AddMessage(a_what); // if (a_what) Tracer::AddTrace(); //} Range_error::Range_error(const char* a_what) : Runtime_error() { Select = BaseException::Select; AddMessage("range error\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Overflow_error::Overflow_error(const char* a_what) : Runtime_error() { Select = BaseException::Select; AddMessage("overflow error\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Bad_alloc::Bad_alloc(const char* a_what) : BaseException() { Select = BaseException::Select; AddMessage("bad allocation\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } unsigned long Logic_error::Select; unsigned long Runtime_error::Select; unsigned long Domain_error::Select; unsigned long Invalid_argument::Select; unsigned long Length_error::Select; unsigned long Out_of_range::Select; //unsigned long Bad_cast::Select; //unsigned long Bad_typeid::Select; unsigned long Range_error::Select; unsigned long Overflow_error::Select; unsigned long Bad_alloc::Select; #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newfft.cpp000066400000000000000000001035631352751253100200130ustar00rootroot00000000000000//$ newfft.cpp // This is originally by Sande and Gentleman in 1967! I have translated from // Fortran into C and a little bit of C++. // It takes about twice as long as fftw // (http://theory.lcs.mit.edu/~fftw/homepage.html) // but is much shorter than fftw and so despite its age // might represent a reasonable // compromise between speed and complexity. // If you really need the speed get fftw. // THIS SUBROUTINE WAS WRITTEN BY G.SANDE OF PRINCETON UNIVERSITY AND // W.M.GENTLMAN OF THE BELL TELEPHONE LAB. IT WAS BROUGHT TO LONDON // BY DR. M.D. GODFREY AT THE IMPERIAL COLLEGE AND WAS ADAPTED FOR // BURROUGHS 6700 BY D. R. BRILLINGER AND J. PEMBERTON // IT REPRESENTS THE STATE OF THE ART OF COMPUTING COMPLETE FINITE // DISCRETE FOURIER TRANSFORMS AS OF NOV.1967. // OTHER PROGRAMS REQUIRED. // ONLY THOSE SUBROUTINES INCLUDED HERE. // USAGE. // CALL AR1DFT(N,X,Y) // WHERE N IS THE NUMBER OF POINTS IN THE SEQUENCE . // X - IS A ONE-DIMENSIONAL ARRAY CONTAINING THE REAL // PART OF THE SEQUENCE. // Y - IS A ONE-DIMENSIONAL ARRAY CONTAINING THE // IMAGINARY PART OF THE SEQUENCE. // THE TRANSFORM IS RETURNED IN X AND Y. // METHOD // FOR A GENERAL DISCUSSION OF THESE TRANSFORMS AND OF // THE FAST METHOD FOR COMPUTING THEM, SEE GENTLEMAN AND SANDE, // @FAST FOURIER TRANSFORMS - FOR FUN AND PROFIT,@ 1966 FALL JOINT // COMPUTER CONFERENCE. // THIS PROGRAM COMPUTES THIS FOR A COMPLEX SEQUENCE Z(T) OF LENGTH // N WHOSE ELEMENTS ARE STORED AT(X(I) , Y(I)) AND RETURNS THE // TRANSFORM COEFFICIENTS AT (X(I), Y(I)). // DESCRIPTION // AR1DFT IS A HIGHLY MODULAR ROUTINE CAPABLE OF COMPUTING IN PLACE // THE COMPLETE FINITE DISCRETE FOURIER TRANSFORM OF A ONE- // DIMENSIONAL SEQUENCE OF RATHER GENERAL LENGTH N. // THE MAIN ROUTINE , AR1DFT ITSELF, FACTORS N. IT THEN CALLS ON // ON GR 1D FT TO COMPUTE THE ACTUAL TRANSFORMS, USING THESE FACTORS. // THIS GR 1D FT DOES, CALLING AT EACH STAGE ON THE APPROPRIATE KERN // EL R2FTK, R4FTK, R8FTK, R16FTK, R3FTK, R5FTK, OR RPFTK TO PERFORM // THE COMPUTATIONS FOR THIS PASS OVER THE SEQUENCE, DEPENDING ON // WHETHER THE CORRESPONDING FACTOR IS 2, 4, 8, 16, 3, 5, OR SOME // MORE GENERAL PRIME P. WHEN GR1DFT IS FINISHED THE TRANSFORM IS // COMPUTED, HOWEVER, THE RESULTS ARE STORED IN "DIGITS REVERSED" // ORDER. AR1DFT THEREFORE, CALLS UPON GR 1S FS TO SORT THEM OUT. // TO RETURN TO THE FACTORIZATION, SINGLETON HAS POINTED OUT THAT // THE TRANSFORMS ARE MORE EFFICIENT IF THE SAMPLE SIZE N, IS OF THE // FORM B*A**2 AND B CONSISTS OF A SINGLE FACTOR. IN SUCH A CASE // IF WE PROCESS THE FACTORS IN THE ORDER ABA THEN // THE REORDERING CAN BE DONE AS FAST IN PLACE, AS WITH SCRATCH // STORAGE. BUT AS B BECOMES MORE COMPLICATED, THE COST OF THE DIGIT // REVERSING DUE TO B PART BECOMES VERY EXPENSIVE IF WE TRY TO DO IT // IN PLACE. IN SUCH A CASE IT MIGHT BE BETTER TO USE EXTRA STORAGE // A ROUTINE TO DO THIS IS, HOWEVER, NOT INCLUDED HERE. // ANOTHER FEATURE INFLUENCING THE FACTORIZATION IS THAT FOR ANY FIXED // FACTOR N WE CAN PREPARE A SPECIAL KERNEL WHICH WILL COMPUTE // THAT STAGE OF THE TRANSFORM MORE EFFICIENTLY THAN WOULD A KERNEL // FOR GENERAL FACTORS, ESPECIALLY IF THE GENERAL KERNEL HAD TO BE // APPLIED SEVERAL TIMES. FOR EXAMPLE, FACTORS OF 4 ARE MORE // EFFICIENT THAN FACTORS OF 2, FACTORS OF 8 MORE EFFICIENT THAN 4,ETC // ON THE OTHER HAND DIMINISHING RETURNS RAPIDLY SET IN, ESPECIALLY // SINCE THE LENGTH OF THE KERNEL FOR A SPECIAL CASE IS ROUGHLY // PROPORTIONAL TO THE FACTOR IT DEALS WITH. HENCE THESE PROBABLY ARE // ALL THE KERNELS WE WISH TO HAVE. // RESTRICTIONS. // AN UNFORTUNATE FEATURE OF THE SORTING PROBLEM IS THAT THE MOST // EFFICIENT WAY TO DO IT IS WITH NESTED DO LOOPS, ONE FOR EACH // FACTOR. THIS PUTS A RESTRICTION ON N AS TO HOW MANY FACTORS IT // CAN HAVE. CURRENTLY THE LIMIT IS 16, BUT THE LIMIT CAN BE READILY // RAISED IF NECESSARY. // A SECOND RESTRICTION OF THE PROGRAM IS THAT LOCAL STORAGE OF THE // THE ORDER P**2 IS REQUIRED BY THE GENERAL KERNEL RPFTK, SO SOME // LIMIT MUST BE SET ON P. CURRENTLY THIS IS 19, BUT IT CAN BE INCRE // INCREASED BY TRIVIAL CHANGES. // OTHER COMMENTS. //(1) THE ROUTINE IS ADAPTED TO CHECK WHETHER A GIVEN N WILL MEET THE // ABOVE FACTORING REQUIREMENTS AN, IF NOT, TO RETURN THE NEXT HIGHER // NUMBER, NX, SAY, WHICH WILL MEET THESE REQUIREMENTS. // THIS CAN BE ACCHIEVED BY A STATEMENT OF THE FORM // CALL FACTR(N,X,Y). // IF A DIFFERENT N, SAY NX, IS RETURNED THEN THE TRANSFORMS COULD BE // OBTAINED BY EXTENDING THE SIZE OF THE X-ARRAY AND Y-ARRAY TO NX, // AND SETTING X(I) = Y(I) = 0., FOR I = N+1, NX. //(2) IF THE SEQUENCE Z IS ONLY A REAL SEQUENCE, THEN THE IMAGINARY PART // Y(I)=0., THIS WILL RETURN THE COSINE TRANSFORM OF THE REAL SEQUENCE // IN X, AND THE SINE TRANSFORM IN Y. #define WANT_STREAM #define WANT_MATH #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,20); ++ExeCount; } #else #define REPORT {} #endif inline Real square(Real x) { return x*x; } inline int square(int x) { return x*x; } static void GR_1D_FS (int PTS, int N_SYM, int N_UN_SYM, const SimpleIntArray& SYM, int P_SYM, const SimpleIntArray& UN_SYM, Real* X, Real* Y); static void GR_1D_FT (int N, int N_FACTOR, const SimpleIntArray& FACTOR, Real* X, Real* Y); static void R_P_FTK (int N, int M, int P, Real* X, Real* Y); static void R_2_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1); static void R_3_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2); static void R_4_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2, Real* X3, Real* Y3); static void R_5_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2, Real* X3, Real* Y3, Real* X4, Real* Y4); static void R_8_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2, Real* X3, Real* Y3, Real* X4, Real* Y4, Real* X5, Real* Y5, Real* X6, Real* Y6, Real* X7, Real* Y7); static void R_16_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2, Real* X3, Real* Y3, Real* X4, Real* Y4, Real* X5, Real* Y5, Real* X6, Real* Y6, Real* X7, Real* Y7, Real* X8, Real* Y8, Real* X9, Real* Y9, Real* X10, Real* Y10, Real* X11, Real* Y11, Real* X12, Real* Y12, Real* X13, Real* Y13, Real* X14, Real* Y14, Real* X15, Real* Y15); static int BitReverse(int x, int prod, int n, const SimpleIntArray& f); bool FFT_Controller::ar_1d_ft (int PTS, Real* X, Real *Y) { // ARBITRARY RADIX ONE DIMENSIONAL FOURIER TRANSFORM REPORT int F,J,N,NF,P,PMAX,P_SYM,P_TWO,Q,R,TWO_GRP; // NP is maximum number of squared factors allows PTS up to 2**32 at least // NQ is number of not-squared factors - increase if we increase PMAX const int NP = 16, NQ = 10; SimpleIntArray PP(NP), QQ(NQ); TWO_GRP=16; PMAX=19; // PMAX is the maximum factor size // TWO_GRP is the maximum power of 2 handled as a single factor // Doesn't take advantage of combining powers of 2 when calculating // number of factors if (PTS<=1) return true; N=PTS; P_SYM=1; F=2; P=0; Q=0; // P counts the number of squared factors // Q counts the number of the rest // R = 0 for no non-squared factors; 1 otherwise // FACTOR holds all the factors - non-squared ones in the middle // - length is 2*P+Q // SYM also holds all the factors but with the non-squared ones // multiplied together - length is 2*P+R // PP holds the values of the squared factors - length is P // QQ holds the values of the rest - length is Q // P_SYM holds the product of the squared factors // find the factors - load into PP and QQ while (N > 1) { bool fail = true; for (J=F; J<=PMAX; J++) if (N % J == 0) { fail = false; F=J; break; } if (fail || P >= NP || Q >= NQ) return false; // can't factor N /= F; if (N % F != 0) QQ[Q++] = F; else { N /= F; PP[P++] = F; P_SYM *= F; } } R = (Q == 0) ? 0 : 1; // R = 0 if no not-squared factors, 1 otherwise NF = 2*P + Q; SimpleIntArray FACTOR(NF + 1), SYM(2*P + R); FACTOR[NF] = 0; // we need this in the "combine powers of 2" // load into SYM and FACTOR for (J=0; J0) { REPORT for (J=0; J 0) { REPORT SimpleIntArray U(N_SYM); for(MultiRadixCounter MRC(N_SYM, SYM, U); !MRC.Finish(); ++MRC) { if (MRC.Swap()) { int P = MRC.Reverse(); int JJ = MRC.Counter(); Real T; T=X[JJ]; X[JJ]=X[P]; X[P]=T; T=Y[JJ]; Y[JJ]=Y[P]; Y[P]=T; } } } int J,JL,K,L,M,MS; // UN_SYM contains the non-squared factors // I have replaced the Sande-Gentleman code as it runs into // integer overflow problems // My code (and theirs) would be improved by using a bit array // as suggested by Van Loan if (N_UN_SYM==0) { REPORT return; } P_UN_SYM=PTS/square(P_SYM); JL=(P_UN_SYM-3)*P_SYM; MS=P_UN_SYM*P_SYM; for (J = P_SYM; J<=JL; J+=P_SYM) { K=J; do K = P_SYM * BitReverse(K / P_SYM, P_UN_SYM, N_UN_SYM, UN_SYM); while (K 1) { bool fail = true; for (int J = F; J <= PMAX; J++) if (N % J == 0) { fail = false; F=J; break; } if (fail || P >= NP || Q >= NQ) { REPORT return false; } N /= F; if (N % F != 0) Q++; else { N /= F; P++; } } return true; // can factorise } bool FFT_Controller::OnlyOldFFT; // static variable // **************************** multi radix counter ********************** MultiRadixCounter::MultiRadixCounter(int nx, const SimpleIntArray& rx, SimpleIntArray& vx) : Radix(rx), Value(vx), n(nx), reverse(0), product(1), counter(0), finish(false) { REPORT for (int k = 0; k < n; k++) { Value[k] = 0; product *= Radix[k]; } } void MultiRadixCounter::operator++() { REPORT counter++; int p = product; for (int k = 0; k < n; k++) { Value[k]++; int p1 = p / Radix[k]; reverse += p1; if (Value[k] == Radix[k]) { REPORT Value[k] = 0; reverse -= p; p = p1; } else { REPORT return; } } finish = true; } static int BitReverse(int x, int prod, int n, const SimpleIntArray& f) { // x = c[0]+f[0]*(c[1]+f[1]*(c[2]+... // return c[n-1]+f[n-1]*(c[n-2]+f[n-2]*(c[n-3]+... // prod is the product of the f[i] // n is the number of f[i] (don't assume f has the correct length) REPORT const int* d = f.Data() + n; int sum = 0; int q = 1; while (n--) { prod /= *(--d); int c = x / prod; x-= c * prod; sum += q * c; q *= *d; } return sum; } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmat.txt000066400000000000000000003662131352751253100200550ustar00rootroot00000000000000 DOCUMENTATION FOR NEWMAT10, A MATRIX LIBRARY IN C++ Copyright (C) 1991,2,3,4,5,6,7,8,9: R B Davies Beta version of 26 December, 1999 Introduction 1 Getting started 2 Reference manual 3 Error messages 4 Bugs 5 Files in newmat10 6 Problem report form 7 Design of the library 8 This is the "how to use" documentation for newmat plus the background information on its design. This document is available as an ascii file, newmat.txt, and in hypertext format for reading with an HTML browser such as Netscape or Internet Explorer. Cross-references in the ascii version are given as section numbers. The HTML version can be downloaded from the same site [1.5] as the source files. There is also a version in RTF format. There is additional support material on my web site [1.5]. Be sure to read the section on customising [2.3] before attempting to compile newmat. 1 Introduction = ============ Conditions of use 1.1 Description 1.2 Is this the library for you? 1.3 Other matrix libraries 1.4 Where to find this library 1.5 How to contact the author 1.6 Change history 1.7 References 1.8 1.1 Conditions of use === ========== == === Copyright (C) 1991,2,3,4,5,6,7: R B Davies. Permission is granted to use and distribute but not to sell except for costs of distribution. Distribution as part of low cost CD-ROM collections is welcomed. You can use it in your commercial projects. However if you distribute the source, please make it clear which parts are mine and that they are available essentially for free over the internet. ----------------------------------------------------------------------------- Please understand that there may still be bugs and errors. Use at your own risk. I take no responsibility for any errors or omissions in this package or for any misfortune that may befall you or others as a result of its use. ----------------------------------------------------------------------------- Please report bugs to me at robertd@netlink.co.nz When reporting a bug please tell me which C++ compiler you are using (if known), and what version. Also give me details of your computer (if known). And tell me which version of Newmat (eg newmat03 or newmat04) you are using. Note any changes you have made to my code. If at all possible give me a piece of code illustrating the bug. See the problem report form [7]. "Please do report bugs to me." 1.2 General description === ======= =========== The package is intended for scientists and engineers who need to manipulate a variety of types of matrices using standard matrix operations. Emphasis is on the kind of operations needed in statistical calculations such as least squares, linear equation solve and eigenvalues. It supports matrix types Matrix (rectangular matrix) nricMatrix (variant of rectangular matrix) UpperTriangularMatrix LowerTriangularMatrix DiagonalMatrix SymmetricMatrix BandMatrix UpperBandMatrix (upper triangular band matrix) LowerBandMatrix (lower triangular band matrix) SymmetricBandMatrix RowVector (derived from Matrix) ColumnVector (derived from Matrix). Only one element type (float or double) is supported. The package includes the operations '*', '+', '-', concatenation, inverse, transpose, conversion between types, submatrix, determinant, Cholesky decomposition, QR triangularisation, singular value decomposition, eigenvalues of a symmetric matrix, sorting, fast Fourier transform, printing and an interface with "Numerical Recipes in C". It is intended for matrices in the range 15 x 15 to the maximum size your machine will accommodate in a single array. On a PC using the large model, this is 90 x 90 (125 x 125 for triangular matrices). For Unix machines or PCs running under a 32 bit flat model the limit is set by the size of available memory. The number of elements in an array cannot exceed the maximum size of an "int". The package will work for very small matrices but becomes rather inefficient. Some of the factorisation functions are not (yet) optimised for paged memory and so become inefficient when used with very large matrices. A "lazy evaluation" approach to evaluating matrix expressions is used to improve efficiency and reduce the use of temporary storage. I have tested the package on variety of compilers and platforms including AT&T, Borland, Gnu, HP, Microsoft, Sun and Watcom. For more details see the section on compiler performance [2.4]. 1.3 Is this the library for you? === == ==== === ======= === ==== Do you 1: understand '*' to mean matrix multiply and not element by element multiply 2: need matrix operators such as '*' and '+' defined as operators so you can write things like X = A * (B + C); 3: need a variety of types of matrices (but not sparse); 4: need only one element type (float or double); 5: work with matrices in the range 10 x 10 up to what can be stored in memory; 6: tolerate a large package. Then maybe this is the right package for you. 1.4 Other matrix libraries === ===== ====== ========= For details of other C++ matrix libraries look at http://webnz.com/robert/cpp_site.html or http://webnz.co.nz/robert/cpp_site.html or download the text file ftp://webnz.com/robert/cpp_site.txt or ftp://webnz.co.nz/robert/cpp_site.txt . Look at the section "lists of libraries" which gives the locations of several very comprehensive lists of matrix and other C++ libraries and at the section "source code". 1.5 Where to find this library === ===== == ==== ==== ======= * http://webnz.com/robert/ * http://webnz.co.nz/robert/ * ftp://webnz.com/robert/newmat10.zip * ftp://webnz.com/robert/newmat10.tar.gz * ftp://webnz.co.nz/robert/newmat10.zip * ftp://webnz.co.nz/robert/newmat10.tar.gz For the HTML version of the documentation download either nm10html.zip or nm10html.tar.gz from the same sites. 1.6 How to contact the author === === == ======= === ====== Robert Davies 16 Gloucester Street Wilton Wellington New Zealand "email:" robertd@netlink.co.nz (don't forget the "d" in "robertd"). 1.7 Change history === ====== ======= Newmat10 - August, 1999: Improve compatibility with GCC, fix errors in FFT and GenericMatrix, update simulated exceptions, maxima and minima functions, Determinant function, update make files for CC and GCC, faster FFT, 'A.ReSize(B)'. Newmat09 - September, 1997: Operator '==', '!=', '+=', '-=', '*=', '/=', '|=', '&='. Follow new rules for "for (int i; ... )" construct. Change Boolean, TRUE, FALSE to bool, true, false. Change ReDimension to ReSize. SubMatrix allows zero rows and columns. Scalar '+', '-' or '*' matrix is OK. Simplify simulated exceptions. Fix non-linear programs for AT&T compilers. Dummy inequality operators. Improve internal row/column operations. Improve matrix LU decomposition. Improve sort. Reverse function. IsSingular function. Fast trig transforms. Namespace definitions. Newmat08A - July, 1995: Fix error in SVD. Newmat08 - January, 1995: Corrections to improve compatibility with Gnu, Watcom. Concatenation of matrices. Elementwise products. Option to use compilers supporting exceptions. Correction to exception module to allow global declarations of matrices. Fix problem with inverse of symmetric matrices. Fix divide-by-zero problem in SVD. Include new QR routines. Sum function. Non-linear optimisation. GenericMatrices. Newmat07 - January, 1993 Minor corrections to improve compatibility with Zortech, Microsoft and Gnu. Correction to exception module. Additional FFT functions. Some minor increases in efficiency. Submatrices can now be used on RHS of =. Option for allowing C type subscripts. Method for loading short lists of numbers. Newmat06 - December 1992: Added band matrices; 'real' changed to 'Real' (to avoid potential conflict in complex class); Inject doesn't check for no loss of information; fixes for AT&T C++ version 3.0; real(A) becomes A.AsScalar(); CopyToMatrix becomes AsMatrix, etc; .c() is no longer required (to be deleted in next version); option for version 2.1 or later. Suffix for include files changed to .h; BOOL changed to Boolean (BOOL doesn't work in g++ v 2.0); modifications to allow for compilers that destroy temporaries very quickly; (Gnu users - see the section of compiler performance). Added CleanUp, LinearEquationSolver, primitive version of exceptions. Newmat05 - June 1992: For private release only Newmat04 - December 1991: Fix problem with G++1.40, some extra documentation Newmat03 - November 1991: Col and Cols become Column and Columns. Added Sort, SVD, Jacobi, Eigenvalues, FFT, real conversion of 1x1 matrix, "Numerical Recipes in C" interface, output operations, various scalar functions. Improved return from functions. Reorganised setting options in "include.hxx". Newmat02 - July 1991: Version with matrix row/column operations and numerous additional functions. Matrix - October 1990: Early version of package. 1.8 References === ========== The matrix LU decomposition is from Golub, G.H. & Van Loan, C.F. (1996), "Matrix Computations", published by John Hopkins University Press. Part of the matrix inverse/solve routine is adapted from Press, Flannery, Teukolsky, Vetterling (1988), "Numerical Recipes in C", published by the Cambridge University Press. Many of the advanced matrix routines are adapted from routines in Wilkinson and Reinsch (1971), "Handbook for Automatic Computation, Vol II, Linear Algebra" published by Springer Verlag. The fast Fourier transform is adapted from Carl de Boor (1980), "Siam J Sci Stat Comput", pp173-8 and the fast trigonometric transforms from Charles Van Loan (1992) in "Computational frameworks for the fast Fourier transform" published by SIAM. The sort function is derived from Sedgewick, Robert (1992), "Algorithms in C++" published by Addison Wesley. For references about "Newmat" see Davies, R.B. (1994) Writing a matrix package in C++. In OON-SKI'94: The second annual object-oriented numerics conference, pp 207-213. Rogue Wave Software, Corvallis. Eddelbuttel, Dirk (1996) Object-oriented econometrics: matrix programming in C++ using GCC and Newmat. Journal of Applied Econometrics, Vol 11, No 2, pp 199-209. 2 Getting started = ======= ======= Overview 2.1 Make files 2.2 Customising 2.3 Compiler performance 2.4 Updating from previous versions 2.5 Example 2.6 Testing 2.7 2.1 Overview === ======== I use .h as the suffix of definition files and .cpp as the suffix of C++ source files. You will need to compile all the *.cpp files listed as program files in the files section [6] to get the complete package. Ideally you should store the resulting object files as a library. The tmt*.cpp files are used for testing [2.7], example.cpp is an example [2.6] and sl_ex.cpp, nl_ex.cpp and garch.cpp are examples of the non-linear [3.27] solve and optimisation routines. A demonstration of the exception mechanism is in test_exc.cpp. I include a number of "make" files for compiling the example and the test package. See the section on make files [2.2] for details. But with the PC compilers, its pretty quick just to load all the files in the interactive environments by pointing and clicking. Use the large or win32 console model when you are using a PC. Do not "outline" inline functions. You may need to increase the stack size. Your source files that access the newmat will need to #include one or more of the following files. include.h: if you want to access just the compiler options newmat.h: to access just the main matrix library (includes include.h) newmatap.h: to access the advanced matrix routines such as Cholesky decomposition, QR triangularisation etc (includes newmat.h) newmatio.h: to access the output routines (includes newmat.h) You can use this only with compilers that support the standard input/output routines including manipulators. newmatnl.h: to access the non-linear optimisation routines (includes newmat.h) See the section on customising [2.3] to see how to edit include.h for your environment and the section on compilers [2.4] for any special problems with the compiler you are using. 2.2 Make files === ==== ===== I have included "make" files for a number of compilers. These provide an alternative way of compiling your programs than with the IDE that comes with PC compilers. See the files section [6] for details. See the example [2.6] for how to use them. Leave out the target name to compile and link all my examples and test files. PC I include make files for some of PC compilers I have access to. They all use the make utility that comes with the compiler. I don't know whether they work with versions of the compilers other than the ones I have. The make files for Borland need editing to show where you have stored your Borland compiler. Unix The "make" file for the Unix CC compilers link a .cxx file to each .cpp file since some of these compilers do not recognise .cpp as a legitimate extension for a C++ file. I suggest you delete this part of the "make" file and, if necessary, rename the .cpp files to something your compiler recognises. My "make" file for Gnu GCC on Unix systems are for use with 'gmake' rather than 'make'. This defines BOOL_LIB so there is no need to do this in 'include.h'. I assume your compiler recognises the .cpp extension. Ordinary 'make' works with it on the Sun but not the Silicon Graphics or HP machines. On Linux use 'make'. My make file for the CC compilers works with the ordinary make. To compile everything with the CC compiler use make -f cc.mak or for the gnu compiler use gmake -f gnu.mak There is a line in the make file for CC 'rm -f $*.cxx'. Some systems won't accept this line and you will need to delete it. In this case, if you have a bad compile and you are using my scheme for linking .cxx files, you will need to delete the .cxx file link generated by that compile before you can do the next one. 2.3 Customising === =========== The file "include.h" sets a variety of options including several compiler dependent options. You may need to edit include.h to get the options you require. If you are using a compiler different from one I have worked with you may have to set up a new section in include.h appropriate for your compiler. Borland, Turbo, Gnu, Microsoft and Watcom are recognised automatically. If none of these are recognised a default set of options is used. These are fine for AT&T, HPUX and Sun C++. If you using a compiler I don't know about you may have to write a new set of options. There is an option in include.h for selecting whether you use compiler supported exceptions, simulated exceptions, or disable exceptions. Use the option for compiler supported exceptions if and only if you have set the option on your compiler to recognise exceptions. Disabling exceptions sometimes helps with compilers that are incompatible with my exception simulation scheme. If your compiler recognises bool as required by the standard activate the statement '#define bool_LIB'. This will deactivate my Boolean class. If you are using my make file with the Gnu compiler, then this #define is automatically activated. Activate the appropriate statement to make the element type float or double. I suggest you leave the option TEMPS_DESTROYED_QUICKLY activated, even though the Gnu compiler (<2.6) is the only one I know about that requires it (C-Set also requires it?). This stores the "trees" describing matrix expressions on the heap rather than the stack and, surprisingly, seems to give better performance. See the discussion on destruction of temporaries [8.8] for more explanation. Leave the option TEMPS_DESTROYED_QUICKLY_R not activated unless you are using the Gnu G++ [2.4.3] compiler earlier than version 2.6. This option controls whether the ReturnMatrix [3.13] construct uses the stack or the heap. The heap version is rather kludgy and probably should be avoided where possible. The option DO_FREE_CHECK [2.7] is used for tracking memory leaks and normally should not be activated. Activate SETUP_C_SUBSCRIPTS if you want to use traditional C style element access [3.2]. Activate '#define use_namespace' if you want to use namespaces [3.29]. Do this only if you are sure your compiler supports namespaces. If you do turn this option on, be prepared to turn it off again if the linker reports missing links. Activate '#define _STANDARD_' to use the standard names for the included files and to find the floating point precision data using the floating point standard. Assume that this doesn't work at present. If you are using a compiler that "include.h" does not recognise and you want to pick up the floating point precision data from "float.h" then activate '#define use_float_h'. Otherwise the floating point precision data will be accessd from "values.h". You will may need to do this with computers from Digital, in particular. 2.4 Compiler performance === ======== =========== I have tested this library on a number of compilers. Here are the levels of success and any special considerations. In most cases I have chosen code that works under all the compilers I have access to, but I have had to include some specific work-arounds for some compilers. For the PC versions, I use a 486dx computer running windows 95, a Pentium computer running windows NT or Linux (Red Hat 4.1) and a 386sx running MSDOS 5. The unix versions are on a Sun Sparc station or a HP unix workstation. Thanks to Victoria University and Industrial Research Ltd for access to the Unix machines. I have set up a block of code for each of the compilers in include.h. Turbo, Borland, Gnu, Microsoft and Watcom are recognised automatically. There is a default option that works for AT&T, Sun C++ 4.0.1 and HPUX. So you don't have to make any changes for these compilers. Otherwise you may have to build your own set of options in include.h. AT&T 2.4.1 Borland 2.4.2 Gnu G++ 2.4.3 HPUX 2.4.4 Microsoft 2.4.5 Sun 2.4.6 Watcom 2.4.7 Zortech 2.4.8 2.4.1 AT&T ===== ==== AT&T C++ 2.1;3.0.1 on a Sun: Previous versions worked on these compilers, which I no longer have access to. In AT&T 2.1 you may get an error when you use an expression for the single argument when constructing a Vector or DiagonalMatrix or one of the Triangular Matrices. You need to evaluate the expression separately. 2.4.2 Borland ===== ======= Borland C++ 3.1, 4.5, 5.02: Recently this has been my main development platform, so naturally everything works with this compiler. There was a problem with the library utility in version 2.0 which is now fixed. You will need to use the large or 32 bit flat model. If you are not debugging, turn off the options that collect debugging information. Make sure you don't run Borland's exceptions and my simulated exceptions at the same time. If you are using version 5 remember to edit include.h to deactivate my Boolean class. When running my test program under ms-dos you may run out of memory. Either compile the test routine to run under "easywin" or use simulated exceptions rather than the built in exceptions. Under "easywin" the test program indicates a memory leak. I presume this is partly because of the way windows organises its heap rather than there being a real problem. If you can, upgrade to windows 95 or window NT and use the 32 bit console model. If you are using the 16 bit large model, don't forget to keep all matrices less than 64K bytes in length (90x90 for a rectangular matrix if you are using 'double' as your element type). Otherwise your program will crash without warning or explanation. You may need to break the tmt [2.7] set of test files into two parts to get the program to fit into your computer. In version 4.5, under "easywin" the automatic clean-up of objects by the exception mechanism does not seem to work correctly. Use my simulated exceptions if this is a problem. One version of Borland had DBL_MIN incorrectly defined. If you are using an older version of Borland and are getting strange numerical errors in the test programs reinstate the commented out statements in precision.h. I include make files that work under Borland 4.5 and 5. You will need to edit these to correctly locate the directories for the include and library files. Both assume you are using simulated exceptions. 'BC.MAK' also works with version 3.1 if you delete the options that are not recognised and the reference to the library file that is not recognised. C++ Builder version 4: I have successfully used this using the console wizard (menu item file/new - select new tab). Either use namespace or rename a couple of my exception names that conflict with Borland. Use compiler exceptions. Suppose you are compiling my test program tmt. Rename my "main()" function in "tmt.cpp" to "my_main()". Rename "tmt.cpp" to "tmt_main.cpp". Borland will generate a new file "tmt.cpp" containing their "main()" function. Put the line 'int my_main();' above this function and put 'return my_main();' into the body of "main()". 2.4.3 Gnu G++ ===== === === Gnu G++ 2.6.0, 2.7.2, 2.8.1: These work OK. If you are using 2.7 or later remember to edit include.h to deactivate my Boolean class - not necessary if you are using my make [2.2] file. But if you are using a version earlier than 2.7 edit the second line of gnu.mak to 'CXXFLAGS = -O2 -Wall' For versions earlier than 2.6.0 you must enable the options TEMPS_DESTROYED_QUICKLY and TEMPS_DESTROYED_QUICKLY_R. You can't use expressions like 'Matrix(X*Y)' in the middle of an expression and '(Matrix)(X*Y)' is unreliable. If you write a function returning a matrix, you MUST use the ReturnMatrix [3.13] method described in this documentation. This is because g++ destroys temporaries occurring in an expression too soon for the two stage way of evaluating expressions that newmat uses. You will have problems with versions of Gnu earlier than 2.3.1. Gnu seems to leave some rubbish on the stack. Possibly this is a buffer or dynamically loaded subprogram so may not be a bug. Linux: It works fine on my copy of G++ 2.7.2. In 2.6.?, 'fabs(*X++)' causes a problem. You may need to write you own non-inlined version. 2.4.4 HP-UX ===== ===== HP 9000 series HP-UX. I no longer have access to this compiler. Newmat09 worked without problems with the simulated exceptions; haven't tried the built-in exceptions. With recent versions of the compiler you may get warning messages like 'Unsafe cast between pointers/references to incomplete classes'. At present, I think these can be ignored. Here are comments I made two years ago. I have tried the library on two versions of HP-UX. (I don't know the version numbers, the older is a clone of AT&T 3, the newer is HP's version with exceptions). Both worked after the modifications described in this section. With the older version of the compiler I needed to edit the math.h library file to remove a duplicate definition of abs. With the newer version you can set the +eh option to enable exceptions and activate the UseExceptions option in include.h. If you are using my make file, you will need to replace CC with CC +eh where ever CC occurs. I recommend that you do not do this and either disable exceptions or use my simulated exceptions. I get core dumps when I use the built-in exceptions and suspect they are not sufficiently debugged as yet. If you are using my simulated exceptions you may get a mass of error messages from the linker about __EH_JMPBUF_TEMP. In this case get file setjmp.h (in directory /usr/include/CC ?) and put extern in front of the line jmp_buf * __EH_JMPBUF_TEMP; The file setjmp.h is accessed in my file myexcept.h. You may want to change the #include statement to access your edited copy of setjmp.h. 2.4.5 Microsoft ===== ========= Microsoft Visual C++ 2.0: Seems to work OK. You can use the makefile 'ms_nt.mak'. You must '#define TEMPS_DESTROYED_QUICKLY' owing to a bug in version 7 (at least) of MSC. There are some notes in the file 'include.h' on changes to run under version 7. I haven't tried newmat10 on version 7. Microsoft Visual C++ 1.51. Disable exceptions, comment out the line in include.h '#define TEMPS_DESTROYED_QUICKLY_R'. In 'tmt.cpp', comment out the 'Try' and 'CatchAll' lines at the beginning of 'main()' and the line 'trymati()'. You can use the makefile 'ms.mak'. You will probably need to break the tmt [2.7] test files into two parts to get the program to link. If you can, upgrade to windows 95, 98 or window NT and use the 32 bit console model. If you are using the 16 bit large model, don't forget to keep all matrices less than 64K bytes in length (90x90 for a rectangular matrix if you are using 'double' as your element type). Otherwise your program will crash without warning or explanation. You may need to break the tmt [2.7] set of test files into two parts to get the program to fit into your computer. Microsoft Visual C++ 4: I haven't tried this - a correspondent reports: I use Microsoft Visual C++ Version 4. there is only one minor problem. In all files you must include '#include "stdafx.h"' (presumably if you are using MFC). This file contains essential information for VC++. Leave it out and you get "Unexpected end of file". Microsoft Visual C++ 5: I have tried this in console mode and it seems to work satisfactorily. There may be a problem with namespace [3.29] (fixed by Service Pack 3?). Turn optimisation off. Edit 'include.h' to use the compiler supported exceptions. If you want to work under MFC '#include "stdafx.h"' at the beginning of each .cpp file. Microsoft Visual C++ 6: Get the latest service pack. I have tried this in console mode and it seems to work satisfactorily. Edit 'include.h' to use the compiler supported exceptions. If you want to work under MFC '#include "stdafx.h"' at the beginning of each .cpp file. 2.4.6 Sun ===== === Sun C++ (version 4.2): This seems to work fine. Sun C++ (version 5): There seems to be a problem with exceptions. If you my simulated exceptions the non-linear optimsation programs hang. If you use the compiler supported exceptions my test_exc program crashes. So take your choice. 2.4.7 Watcom & Optima++ ===== ====== = ======== Watcom C++ (version 10): this works fine. Don't try to run Watcom's exceptions and my simulated exceptions at the same time. But best don't use Watcom's exceptions at all in this version as they do seem to cause problems; even when not used. It seems fine on Optima++ 1.0 in console mode. I haven't tested it in gui mode. Optima++ provides some stuff to insert in the main program. 2.4.8 Zortech ===== ======= I don't support Zortech any more and haven't tried the Symantec successors to Zortech. 2.5 Updating from previous versions === ======== ==== ======== ======== Newmat10 includes new maxima, minima and Determinant [3.8] functions, a faster FFT [3.22], revised make [2.2] files for GCC and CC compilers and several corrections, new ReSize [3.10] function. The program files include a new file, 'newfft.cpp', so you will need to include this in the list of files in your IDE and make files. If you are updating from a beta version of newmat09 look through the next section as there were some late changes to newmat09. If you are upgrading from newmat08 note the following: * Boolean, TRUE, FALSE are now bool, true, false. See customising [2.3] if your compiler supports the bool class. * ReDimension is now ReSize [3.10]. * The simulated exception [3.25] package has been updated. * Operators '==', '!=', '+=', '-=', '*=', '|=', '&=' are now supported as binary [3.6] matrix operators. * 'A+=f', 'A-=f', 'A*=f', 'A/=f', 'f+A', 'f-A', 'f*A' are supported for A matrix, f scalar [3.7]. * Fast trigonometric transforms [3.23]. * Reverse [3.5] function for reversing order of elements in a vector or matrix. * IsSingular [3.8] function. * An option is included for defining namespaces [3.29]. * Dummy inequality operators are defined for compatibiity with the STL. * The row/column classes in newmat3.cpp have been modified to improve efficiency and correct an invalid use of pointer arithmetic. Most users won't be using these classes explicitly; if you are, please contact me for details of the changes. * Matrix LU decomposition rewritten (faster for large arrays). * The sort function rewritten (faster). * The documentation files newmata.txt and newmatb.txt have been amalgamated and both are included in the hypertext version. * Some of the make [2.2] files reorganised again. If you are upgrading from newmat07 note the following: * .cxx files are now .cpp files. Some versions of won't accept .cpp. The "make" files for Gnu and AT&T link the .cpp files to .cxx files before compilation and delete the links after compilation. * An option [2.3] in include.h allows you to use compiler supported exceptions, simulated exceptions or disable exceptions. Edit the file include.h to select one of these three options. Don't simulate exceptions if you have set your compiler's option to implement exceptions. * New QR decomposition [3.18] functions. * A non-linear least squares [3.27] class. * No need to explicitly set the AT&T option in include.h. * Concatenation and elementwise multiplication [3.6]. * A new GenericMatrix [3.16] class. * Sum [3.8] function. * Some of the make [2.2] files reorganised. If you are upgrading from newmat06 note the following: * If you are using << to load a Real into a submatrix change this to =. If you are upgrading from newmat03 or newmat04 note the following * .hxx files are now .h files * real changed to Real * BOOL changed to Boolean * CopyToMatrix changed to AsMatrix, etc * real(A) changed to A.AsScalar() The current version is quite a bit longer that newmat04, so if you are almost out of space with newmat04, don't throw newmat04 away until you have checked your program will work under this version. See the change history [1.7] for other changes. 2.6 Example === ======= An example is given in 'example.cpp'. This gives a simple linear regression example using five different algorithms. The correct output is given in 'example.txt'. The program carries out a rough check that no memory is left allocated on the heap when it terminates. See the section on testing [2.7] for a comment on the reliability of this check and the use of the DO_FREE_CHECK option. I include a variety of make files. To compile the example use a command like gmake example -f gnu.mak (Gnu G++) gmake example -f cc.mak (AT&T, HPUX, Sun) nmake example.exe -f ms_nt.mak (Microsoft Visual C++ 2.0) nmake example.exe -f ms.mak (Microsoft Visual C++ 1.51) make -f bc.mak example.exe (Borland C++ 4.5, 5) make -f bc32.mak example.exe (Borland C++ 4.5, 5, 32 bit) wmake example.exe -f watcom.mak (Watcom C++ 10A) wmake example.exe -f watco_nt.mak (Watcom C++ 10A, for win NT) To compile all the example and test files use a command like gmake -f gnu.mak (Gnu G++) ----------------------------------------------------------------------------- The example uses io manipulators. It will not work with a compiler that does not support the standard io manipulators. ----------------------------------------------------------------------------- Other example files are 'nl_ex.cpp' and 'garch.cpp' for demonstrating the non-linear fitting routines, 'sl_ex' for demonstrating the solve function and 'test_exc' for demonstrating the exceptions. 2.7 Testing === ======= The library package contains a comprehensive test program in the form of a series of files with names of the form tmt?.cxx. The files consist of a large number of matrix formulae all of which evaluate to zero (except the first one which is used to check that we are detecting non-zero matrices). The printout should state that it has found just one non-zero matrix. The test program should be run with "Real" typedefed to "double" rather than "float" in include.h [2.3]. Make sure the C subscripts [3.2] are enabled if you want to test these. Various versions of the make file (extension .mak) are included with the package. See the section on make files [2.2]. The program also allocates and deletes a large block and small block of memory before it starts the main testing and then at the end of the test. It then checks that the blocks of memory were allocated in the same place. If not then one suspects that there has been a memory leak. i.e. a piece of memory has been allocated and not deleted. This is not completely foolproof. Programs may allocate extra print buffers while the program is running. I have tried to overcome this by doing a print before I allocate the first memory block. Programs may allocate memory for different sized items in different places, or might not allocate items consecutively. Or they might mix the items with memory blocks from other programs. Nevertheless, I seem to get consistent answers from many of the compilers I am working with, so I think this is a worthwhile test. If the DO_FREE_CHECK [2.3] option in include.h is activated, the program checks that each 'new' is balanced with exactly one 'delete'. This provides a more definitive test of no memory leaks. There are additional statements in myexcept.cpp which can be activated to print out details of the memory being allocated and released. I have included a facility for checking that each piece of code in the library is really exercised by the test routines. Each block of code in the main part of the library contains a word 'REPORT'. 'newmat.h' has a line defining 'REPORT' that can be activated (deactivate the dummy version). This gives a printout of the number of times each of the 'REPORT' statements in the '.cpp' files is accessed. Use a grep with line numbers to locate the lines on which 'REPORT' occurs and compare these with the lines that the printout shows were actually accessed. One can then see which lines of code were not accessed. 3 Reference manual = ========= ====== Constructors 3.1 Accessing elements 3.2 Assignment and copying 3.3 Entering values 3.4 Unary operations 3.5 Binary operations 3.6 Matrix and scalar ops 3.7 Scalar functions 3.8 Submatrices 3.9 Change dimension 3.10 Change type 3.11 Multiple matrix solve 3.12 Memory management 3.13 Efficiency 3.14 Output 3.15 Accessing unspecified type 3.16 Cholesky decomposition 3.17 QR decomposition 3.18 Singular value decomposition 3.19 Eigenvalue decomposition 3.20 Sorting 3.21 Fast Fourier transform 3.22 Fast trigonometric transforms 3.23 Numerical recipes in C 3.24 Exceptions 3.25 Cleanup following exception 3.26 Non-linear applications 3.27 Standard template library 3.28 Namespace 3.29 3.1 Constructors === ============ To construct an m x n matrix, 'A', (m and n are integers) use Matrix A(m,n); The UpperTriangularMatrix, LowerTriangularMatrix, SymmetricMatrix and DiagonalMatrix types are square. To construct an n x n matrix use, for example UpperTriangularMatrix UT(n); LowerTriangularMatrix LT(n); SymmetricMatrix S(n); DiagonalMatrix D(n); Band matrices need to include bandwidth information in their constructors. BandMatrix BM(n, lower, upper); UpperBandMatrix UB(n, upper); LowerBandMatrix LB(n, lower); SymmetricBandMatrix SB(n, lower); The integers upper and lower are the number of non-zero diagonals above and below the diagonal (excluding the diagonal) respectively. The RowVector and ColumnVector types take just one argument in their constructors: RowVector RV(n); ColumnVector CV(n); These constructors do *not* initialise the elements of the matrices. To set all the elements to zero use, for example, Matrix A(m, n); A = 0.0; You can also construct vectors and matrices without specifying the dimension. For example Matrix A; In this case the dimension must be set by an assignment statement [3.3] or a re-dimension statement [3.10]. You can also use a constructor to set a matrix equal to another matrix or matrix expression. Matrix A = UT; Matrix A = UT * LT; Only conversions that don't lose information are supported - eg you cannot convert an upper triangular matrix into a diagonal matrix using =. 3.2 Accessing elements === ========= ======== Elements are accessed by expressions of the form 'A(i,j)' where i and j run from 1 to the appropriate dimension. Access elements of vectors with just one argument. Diagonal matrices can accept one or two subscripts. This is different from the earliest version of the package in which the subscripts ran from 0 to one less than the appropriate dimension. Use 'A.element(i,j)' if you want this earlier convention. 'A(i,j)' and 'A.element(i,j)' can appear on either side of an = sign. If you activate the '#define SETUP_C_SUBSCRIPTS' in 'include.h' you can also access elements using the traditional C style notation. That is 'A[i][j]' for matrices (except diagonal) and 'V[i]' for vectors and diagonal matrices. The subscripts start at zero (ie like element) and there is no range checking. Because of the possibility of confusing 'V(i)' and 'V[i]', I suggest you do not activate this option unless you really want to use it. Symmetric matrices are stored as lower triangular matrices. It is important to remember this if you are using the 'A[i][j]' method of accessing elements. Make sure the first subscript is greater than or equal to the second subscript. However, if you are using the 'A(i,j)' method the program will swap 'i' and 'j' if necessary; so it doesn't matter if you think of the storage as being in the upper triangle (but it "does" matter in some other situations such as when entering [3.4] data). 3.3 Assignment and copying === ========== === ======= The operator '=' is used for copying matrices, converting matrices, or evaluating expressions. For example A = B; A = L; A = L * U; Only conversions that don't lose information are supported. The dimensions of the matrix on the left hand side are adjusted to those of the matrix or expression on the right hand side. Elements on the right hand side which are not present on the left hand side are set to zero. The operator '<<' can be used in place of '=' where it is permissible for information to be lost. For example SymmetricMatrix S; Matrix A; ...... S << A.t() * A; is acceptable whereas S = A.t() * A; // error will cause a runtime error since the package does not (yet?) recognise 'A.t()*A' as symmetric. Note that you can not use '<<' with constructors. For example SymmetricMatrix S << A.t() * A; // error does not work. Also note that '<<' cannot be used to load values from a full matrix into a band matrix, since it will be unable to determine the bandwidth of the band matrix. A third copy routine is used in a similar role to '='. Use A.Inject(D); to copy the elements of 'D' to the corresponding elements of 'A' but leave the elements of 'A' unchanged if there is no corresponding element of 'D' (the '=' operator would set them to 0). This is useful, for example, for setting the diagonal elements of a matrix without disturbing the rest of the matrix. Unlike '=' and '<<', Inject does not reset the dimensions of 'A', which must match those of 'D'. Inject does not test for no loss of information. You cannot replace 'D' by a matrix expression. The effect of 'Inject(D)' depends on the type of 'D'. If 'D' is an expression it might not be obvious to the user what type it would have. So I thought it best to disallow expressions. Inject can be used for loading values from a regular matrix into a band matrix. (Don't forget to zero any elements of the left hand side that will not be set by the loading operation). Both '<<' and Inject can be used with submatrix expressions on the left hand side. See the section on submatrices [3.9]. To set the elements of a matrix to a scalar use operator '=' Real r; int m,n; ...... Matrix A(m,n); A = r; 3.4 Entering values === ======== ====== You can load the elements of a matrix from an array: Matrix A(3,2); Real a[] = { 11,12,21,22,31,33 }; A << a; This construction does not check that the numbers of elements match correctly. This version of '<<' can be used with submatrices on the left hand side. It is not defined for band matrices. Alternatively you can enter short lists using a sequence of numbers separated by '<<' . Matrix A(3,2); A << 11 << 12 << 21 << 22 << 31 << 32; This does check for the correct total number of entries, although the message for there being insufficient numbers in the list may be delayed until the end of the block or the next use of this construction. This does not work for band matrices or submatrices, or for long lists. Also try to restrict its use to numbers. You can include expressions, but these must not call a function which includes the same construction. Remember that matrices are stored by rows and that symmetric matrices are stored as lower triangular matrices when using these methods to enter data. 3.5 Unary operators === ===== ========= The package supports unary operations X = -A; // change sign of elements X = A.t(); // transpose X = A.i(); // inverse (of square matrix A) X = A.Reverse(); // reverse order of elements of vector // or matrix (not band matrix) 3.6 Binary operators === ====== ========= The package supports binary operations X = A + B; // matrix addition X = A - B; // matrix subtraction X = A * B; // matrix multiplication X = A.i() * B; // equation solve (square matrix A) X = A | B; // concatenate horizontally (concatenate the rows) X = A & B; // concatenate vertically (concatenate the columns) X = SP(A, B); // elementwise product of A and B (Schur product) bool b = A == B; // test whether A and B are equal bool b = A != B; // ! (A == B) A += B; // A = A + B; A -= B; // A = A - B; A *= B; // A = A * B; A |= B; // A = A | B; A &= B; // A = A & B; <, >, <=, >= // included for compatibility with STL - see notes Notes: * If you are doing repeated multiplication. For example 'A*B*C', use brackets to force the order of evaluation to minimise the number of operations. If 'C' is a column vector and 'A' is not a vector, then it will usually reduce the number of operations to use 'A*(B*C)'. * In the equation solve example case the inverse is not explicitly calculated. An LU decomposition of 'A' is performed and this is applied to 'B'. This is more efficient than calculating the inverse and then multiplying. See also multiple matrix solving [3.12]. * The package does not (yet?) recognise 'B*A.i()' as an equation solve and the inverse of 'A' would be calculated. It is probably better to use '(A.t().i()*B.t()).t()'. * Horizontal or vertical concatenation returns a result of type Matrix, RowVector or ColumnVector. * If 'A' is m x p, 'B' is m x q, then 'A | B' is m x (p+q) with the k-th row being the elements of the k-th row of 'A' followed by the elements of the k-th row of 'B'. * If 'A' is p x n, 'B' is q x n, then 'A & B' is (p+q) x n with the k-th column being the elements of the k-th column of 'A' followed by the elements of the k-th column of 'B'. * For complicated concatenations of matrices, consider instead using submatrices [3.9]. * See the section on submatrices [3.9] on using a submatrix on the RHS of an expression. * Two matrices are equal if their difference is zero. They may be of different types. For the CroutMatrix or BandLUMatrix they must be of the same type and have all their elements equal. This is not a very useful operator and is included for compatibility with some container templates. * The inequality operators are included for compatibility with the standard template library [3.28]. If actually called, they will throw an exception. So don't try to sort a "list" of matrices. 3.7 Matrix and scalar === ====== === ====== The following expressions multiply the elements of a matrix 'A' by a scalar f: 'A * f' or 'f * A' . Likewise one can divide the elements of a matrix 'A' by a scalar f: 'A / f' The expressions 'A + f' and 'A - f' add or subtract a rectangular matrix of the same dimension as 'A' with elements equal to 'f' to or from the matrix 'A'. The expression 'f + A' is an alternative to 'A + f'. The expression 'f - A' subtracts matrix 'A' from a rectangular matrix of the same dimension as 'A' and with elements equal to 'f' The expression 'A += f' replaces 'A' by 'A + f'. Operators '-=', '*=', '/=' are similarly defined. 3.8 Scalar functions of a matrix === ====== ========= == = ====== int i, j; int m = A.Nrows(); // number of rows int n = A.Ncols(); // number of columns Real r = A.AsScalar(); // value of 1x1 matrix Real ssq = A.SumSquare(); // sum of squares of elements Real sav = A.SumAbsoluteValue(); // sum of absolute values Real s = A.Sum(); // sum of values Real mv = A.MaximumAbsoluteValue(); // maximum of absolute values Real mv = A.MinimumAbsoluteValue(); // minimum of absolute values Real mv = A.Maximum(); // maximum value Real mv = A.Minimum(); // minimum value Real mv = A.MaximumAbsoluteValue1(i); // maximum of absolute values Real mv = A.MinimumAbsoluteValue1(i); // minimum of absolute values Real mv = A.Maximum1(i); // maximum value Real mv = A.Minimum1(i); // minimum value Real mv = A.MaximumAbsoluteValue2(i,j);// maximum of absolute values Real mv = A.MinimumAbsoluteValue2(i,j);// minimum of absolute values Real mv = A.Maximum2(i,j); // maximum value Real mv = A.Minimum2(i,j); // minimum value Real norm = A.Norm1(); // maximum of sum of absolute values of elements of a column Real norm = A.NormInfinity(); // maximum of sum of absolute values of elements of a row Real t = A.Trace(); // trace Real d = A.Determinant(); // determinant LogAndSign ld = A.LogDeterminant(); // log of determinant bool z = A.IsZero(); // test all elements zero MatrixType mt = A.Type(); // type of matrix Real* s = Store(); // pointer to array of elements int l = Storage(); // length of array of elements bool s = A.IsSingular(); // A is a CroutMatrix or BandLUMatrix MatrixBandWidth mbw = A.BandWidth(); // upper and lower bandwidths The functions 'A.MaximumAbsoluteValue()', 'A.MinimumAbsoluteValue()', 'A.Maximum()' and 'A.Minimum()' throw an exception if 'A' has no rows or no columns. The versions 'A.MaximumAbsoluteValue1(i)', etc return the location of the extreme element in a RowVector, ColumnVector or DiagonalMatrix. The versions 'A.MaximumAbsoluteValue2(i,j)', etc return the row and column numbers of the extreme element. These versions also throw an exception if 'A' has no rows or no columns. If the extreme value occurs more than once the location of the last one is given. 'A.LogDeterminant()' returns a value of type LogAndSign. If ld is of type LogAndSign use ld.Value() to get the value of the determinant ld.Sign() to get the sign of the determinant (values 1, 0, -1) ld.LogValue() to get the log of the absolute value. Note that the direct use of the function 'Determinant()' will often cause a floating point overflow exception. 'A.IsZero()' returns Boolean value 'true' if the matrix 'A' has all elements equal to 0.0. 'IsSingular' is defined only for CroutMatrix and BandLUMatrix. It returns 'true' if one of the diagonal elements of the LU decomposition is exactly zero. 'MatrixType mt = A.Type()' returns the type of a matrix. Use '(char*)mt' to get a string (UT, LT, Rect, Sym, Diag, Band, UB, LB, Crout, BndLU) showing the type (Vector types are returned as Rect). 'MatrixBandWidth' has member functions 'Upper()' and 'Lower()' for finding the upper and lower bandwidths (number of diagonals above and below the diagonal, both zero for a diagonal matrix). For non-band matrices -1 is returned for both these values. The versions Sum(A), SumSquare(A), SumAbsoluteValue(A), MaximumAbsoluteValue(A), MinimumAbsoluteValue(A), Maximum(A), Minimum(A), Trace(A), LogDeterminant(A), Determinant(A), Norm1(A), NormInfinity(A) can be used in place of A.Sum(), A.SumSquare(), A.SumAbsoluteValue(), A.MaximumAbsoluteValue(), A.MinimumAbsoluteValue(), A.Maximum(), A.Minimum(), A.Trace(), A.LogDeterminant(), A.Norm1(), A.NormInfinity(). 3.9 Submatrices === =========== A.SubMatrix(fr,lr,fc,lc) This selects a submatrix from 'A'. The arguments fr,lr,fc,lc are the first row, last row, first column, last column of the submatrix with the numbering beginning at 1. This may be used in any matrix expression or on the left hand side of '=', '<<' or Inject. Inject does not check no information loss. You can also use the construction Real c; .... A.SubMatrix(fr,lr,fc,lc) = c; to set a submatrix equal to a constant. The following are variants of SubMatrix: A.SymSubMatrix(f,l) // This assumes fr=fc and lr=lc. A.Rows(f,l) // select rows A.Row(f) // select single row A.Columns(f,l) // select columns A.Column(f) // select single column In each case f and l mean the first and last row or column to be selected (starting at 1). I allow lr = fr-1, lc = fc-1 or l = f-1 to indicate that a matrix of zero rows or columns is to be returned. If SubMatrix or its variant occurs on the right hand side of an '=' or '<<' or within an expression its type is as follows A.SubMatrix(fr,lr,fc,lc): If A is RowVector or ColumnVector then same type otherwise type Matrix A.SymSubMatrix(f,l): Same type as A A.Rows(f,l): Type Matrix A.Row(f): Type RowVector A.Columns(f,l): Type Matrix A.Column(f): Type ColumnVector If SubMatrix or its variant appears on the left hand side of '=' or '<<' , think of its type being Matrix. Thus 'L.Row(1)' where 'L' is LowerTriangularMatrix expects 'L.Ncols()' elements even though it will use only one of them. If you are using '=' the program will check for no loss of data. A SubMatrix can appear on the left-hand side of '+=' or '-=' with a matrix expression on the right-hand side. It can also appear on the left-hand side of '+=', '-=', '*=' or '/=' with a Real on the right-hand side. In each case there must be no loss of information. Do not use the '+=' and '-=' operations with a submatrix of a SymmetricMatrix or BandSymmetricMatrix on the LHS and a Real on the RHS. If you are are using the submatrix facility to build a matrix from a small number of components, consider instead using the concatenation operators [3.6]. 3.10 Change dimensions ==== ====== ========== The following operations change the dimensions of a matrix. The values of the elements are lost. A.ReSize(nrows,ncols); // for type Matrix or nricMatrix A.ReSize(n); // for all other types, except Band A.ReSize(n,lower,upper); // for BandMatrix A.ReSize(n,lower); // for LowerBandMatrix A.ReSize(n,upper); // for UpperBandMatrix A.ReSize(n,lower); // for SymmetricBandMatrix A.ReSize(B); // set dims to those of B Use 'A.CleanUp()' to set the dimensions of 'A' to zero and release all the heap memory. 'A.ReSize(B)' sets the dimensions of 'A' to those of a matrix 'B'. This includes the band-width in the case of a band matrix. It is an error for 'A' to be a band matrix and 'B' not a band matrix (or diagonal matrix). Remember that 'ReSize' destroys values. If you want to 'ReSize', but keep the values in the bit that is left use something like ColumnVector V(100); ... // load values V = V.Rows(1,50); // to get first 50 values. If you want to extend a matrix or vector use something like ColumnVector V(50); ... // load values { V.Release(); ColumnVector X=V; V.ReSize(100); V.Rows(1,50)=X; } // V now length 100 3.11 Change type ==== ====== ==== The following functions interpret the elements of a matrix (stored row by row) to be a vector or matrix of a different type. Actual copying is usually avoided where these occur as part of a more complicated expression. A.AsRow() A.AsColumn() A.AsDiagonal() A.AsMatrix(nrows,ncols) A.AsScalar() The expression 'A.AsScalar()' is used to convert a 1 x 1 matrix to a scalar. 3.12 Multiple matrix solve ==== ======== ====== ===== To solve the matrix equation 'Ay = b' where 'A' is a square matrix of equation coefficients, 'y' is a column vector of values to be solved for, and 'b' is a column vector, use the code int n = something Matrix A(n,n); ColumnVector b(n); ... put values in A and b ColumnVector y = A.i() * b; // solves matrix equation The following notes are for the case where you want to solve more than one matrix equation with different values of 'b' but the same 'A'. Or where you want to solve a matrix equation and also find the determinant of 'A'. In these cases you probably want to avoid repeating the LU decomposition of 'A' for each solve or determinant calculation. If 'A' is a square or symmetric matrix use CroutMatrix X = A; // carries out LU decomposition Matrix AP = X.i()*P; Matrix AQ = X.i()*Q; LogAndSign ld = X.LogDeterminant(); rather than Matrix AP = A.i()*P; Matrix AQ = A.i()*Q; LogAndSign ld = A.LogDeterminant(); since each operation will repeat the LU decomposition. If 'A' is a BandMatrix or a SymmetricBandMatrix begin with BandLUMatrix X = A; // carries out LU decomposition A CroutMatrix or a BandLUMatrix can't be manipulated or copied. Use references as an alternative to copying. Alternatively use LinearEquationSolver X = A; This will choose the most appropriate decomposition of 'A'. That is, the band form if 'A' is banded; the Crout decomposition if 'A' is square or symmetric and no decomposition if 'A' is triangular or diagonal. If you want to use the LinearEquationSolver '#include newmatap.h'. 3.13 Memory management ==== ====== ========== The package does not support delayed copy. Several strategies are required to prevent unnecessary matrix copies. Where a matrix is called as a function argument use a constant reference. For example YourFunction(const Matrix& A) rather than YourFunction(Matrix A) Skip the rest of this section on your first reading. ----------------------------------------------------------------------------- Gnu g++ (< 2.6) users please read on; if you are returning matrix values from a function, then you must use the ReturnMatrix construct. ----------------------------------------------------------------------------- A second place where it is desirable to avoid unnecessary copies is when a function is returning a matrix. Matrices can be returned from a function with the return command as you would expect. However these may incur one and possibly two copyings of the matrix. To avoid this use the following instructions. Make your function of type ReturnMatrix . Then precede the return statement with a Release statement (or a ReleaseAndDelete statement if the matrix was created with new). For example ReturnMatrix MakeAMatrix() { Matrix A; // or any other matrix type ...... A.Release(); return A; } or ReturnMatrix MakeAMatrix() { Matrix* m = new Matrix; ...... m->ReleaseAndDelete(); return *m; } If your compiler objects to this code, replace the return statements with return A.ForReturn(); or return m->ForReturn(); If you are using AT&T C++ you may wish to replace 'return A;' by return '(ReturnMatrix)A;' to avoid a warning message; but this will give a runtime error with Gnu. (You can't please everyone.) ----------------------------------------------------------------------------- Do not forget to make the function of type ReturnMatrix; otherwise you may get incomprehensible run-time errors. ----------------------------------------------------------------------------- You can also use '.Release()' or '->ReleaseAndDelete()' to allow a matrix expression to recycle space. Suppose you call A.Release(); just before 'A' is used just once in an expression. Then the memory used by 'A' is either returned to the system or reused in the expression. In either case, 'A''s memory is destroyed. This procedure can be used to improve efficiency and reduce the use of memory. Use '->ReleaseAndDelete' for matrices created by new if you want to completely delete the matrix after it is accessed. 3.14 Efficiency ==== ========== The package tends to be not very efficient for dealing with matrices with short rows. This is because some administration is required for accessing rows for a variety of types of matrices. To reduce the administration a special multiply routine is used for rectangular matrices in place of the generic one. Where operations can be done without reference to the individual rows (such as adding matrices of the same type) appropriate routines are used. When you are using small matrices (say smaller than 10 x 10) you may find it faster to use rectangular matrices rather than the triangular or symmetric ones. 3.15 Output ==== ====== To print a matrix use an expression like Matrix A; ...... cout << setw(10) << setprecision(5) << A; This will work only with systems that support the standard input/output routines including manipulators. You need to #include the file newmatio.h. The present version of this routine is useful only for matrices small enough to fit within a page or screen width. To print several vectors or matrices in columns use a concatenation operator [3.6]: ColumnVector A, B; ..... cout << setw(10) << setprecision(5) << (A | B); 3.16 Unspecified type ==== =========== ==== Skip this section on your first reading. If you want to work with a matrix of unknown type, say in a function. You can construct a matrix of type 'GenericMatrix'. Eg Matrix A; ..... // put some values in A GenericMatrix GM = A; A GenericMatrix matrix can be used anywhere where a matrix expression can be used and also on the left hand side of an '='. You can pass any type of matrix (excluding the Crout and BandLUMatrix types) to a 'const GenericMatrix&' argument in a function. However most scalar functions including Nrows(), Ncols(), Type() and element access do not work with it. Nor does the ReturnMatrix construct. See also the paragraph on LinearEquationSolver [3.12]. An alternative and less flexible approach is to use BaseMatrix or GeneralMatrix. Suppose you wish to write a function which accesses a matrix of unknown type including expressions (eg 'A*B'). Then use a layout similar to the following: void YourFunction(BaseMatrix& X) { GeneralMatrix* gm = X.Evaluate(); // evaluate an expression // if necessary ........ // operations on *gm gm->tDelete(); // delete *gm if a temporary } See, as an example, the definitions of 'operator<<' in newmat9.cpp. Under certain circumstances; particularly where 'X' is to be used just once in an expression you can leave out the 'Evaluate()' statement and the corresponding 'tDelete()'. Just use 'X' in the expression. If you know YourFunction will never have to handle a formula as its argument you could also use void YourFunction(const GeneralMatrix& X) { ........ // operations on X } Do not try to construct a GeneralMatrix or BaseMatrix. 3.17 Cholesky decomposition ==== ======== ============= Suppose 'S' is symmetric and positive definite. Then there exists a unique lower triangular matrix 'L' such that 'L * L.t() = S'. To calculate this use SymmetricMatrix S; ...... LowerTriangularMatrix L = Cholesky(S); If 'S' is a symmetric band matrix then 'L' is a band matrix and an alternative procedure is provided for carrying out the decomposition: SymmetricBandMatrix S; ...... LowerBandMatrix L = Cholesky(S); 3.18 QR decomposition ==== == ============= This is a variant on the usual QR transformation. Start with matrix / 0 0 \ s \ X Y / n s t Our version of the QR decomposition multiplies this matrix by an orthogonal matrix Q to get / U M \ s \ 0 Z / n s t where 'U' is upper triangular (the R of the QR transform). This is good for solving least squares problems: choose b (matrix or row vector) to minimise the sum of the squares of the elements of Y - X*b Then choose 'b = U.i()*M;' The residuals 'Y - X*b' are in 'Z'. This is the usual QR transformation applied to the matrix 'X' with the square zero matrix attached concatenated on top of it. It gives the same triangular matrix as the QR transform applied directly to 'X' and generally seems to work in the same way as the usual QR transform. However it fits into the matrix package better and also gives us the residuals directly. It turns out to be essentially a modified Gram-Schmidt decomposition. Two routines are provided: QRZ(X, U); replaces 'X' by orthogonal columns and forms 'U'. QRZ(X, Y, M); uses 'X' from the first routine, replaces 'Y' by 'Z' and forms 'M'. The are also two routines 'QRZT(X, L)' and 'QRZT(X, Y, M)' which do the same decomposition on the transposes of all these matrices. QRZT replaces the routines HHDecompose in earlier versions of newmat. HHDecompose is still defined but just calls QRZT. 3.19 Singular value decomposition ==== ======== ===== ============= The singular value decomposition of an m x n 'Matrix' 'A' (where m >= n) is a decomposition A = U * D * V.t() where 'U' is m x n with 'U.t() * U' equalling the identity, 'D' is an n x n 'DiagonalMatrix' and 'V' is an n x n orthogonal matrix (type 'Matrix' in "Newmat"). Singular value decompositions are useful for understanding the structure of ill-conditioned matrices, solving least squares problems, and for finding the eigenvalues of 'A.t() * A'. To calculate the singular value decomposition of 'A' (with m >= n) use one of SVD(A, D, U, V); // U = A is OK SVD(A, D); SVD(A, D, U); // U = A is OK SVD(A, D, U, false); // U (can = A) for workspace only SVD(A, D, U, V, false); // U (can = A) for workspace only where 'A', 'U' and 'V' are of type 'Matrix' and 'D' is a 'DiagonalMatrix'. The values of 'A' are not changed unless 'A' is also inserted as the third argument. 3.20 Eigenvalue decomposition ==== ========== ============= An eigenvalue decomposition of a SymmetricMatrix 'A' is a decomposition A = V * D * V.t() where 'V' is an orthogonal matrix (type 'Matrix' in "Newmat") and 'D' is a DiagonalMatrix. Eigenvalue analyses are used in a wide variety of engineering, statistical and other mathematical analyses. The package includes two algorithms: Jacobi and Householder. The first is extremely reliable but much slower than the second. The code is adapted from routines in "Handbook for Automatic Computation, Vol II, Linear Algebra" by Wilkinson and Reinsch, published by Springer Verlag. Jacobi(A,D,S,V); // A, S symmetric; S is workspace, // S = A is OK; V is a matrix Jacobi(A,D); // A symmetric Jacobi(A,D,S); // A, S symmetric; S is workspace, // S = A is OK Jacobi(A,D,V); // A symmetric; V is a matrix EigenValues(A,D); // A symmetric EigenValues(A,D,S); // A, S symmetric; S is for back // transforming, S = A is OK EigenValues(A,D,V); // A symmetric; V is a matrix where 'A', 'S' are of type 'SymmetricMatrix', 'D' is of type 'DiagonalMatrix' and 'V' is of type 'Matrix'. The values of 'A' are not changed unless 'A' is also inserted as the third argument. If you need eigenvectors use one of the forms with matrix 'V'. The eigenvectors are returned as the columns of 'V'. 3.21 Sorting ==== ======= To sort the values in a matrix or vector, 'A', (in general this operation makes sense only for vectors and diagonal matrices) use SortAscending(A); or SortDescending(A); I use the quicksort algorithm. The algorithm is similar to that in Sedgewick's algorithms in C++. If the sort seems to be failing (as quicksort can do) an exception is thrown. You will get incorrect results if you try to sort a band matrix - but why would you want to sort a band matrix? 3.22 Fast Fourier transform ==== ==== ======= ========= FFT(X, Y, F, G); // F=X and G=Y are OK where 'X', 'Y', 'F', 'G' are column vectors. 'X' and 'Y' are the real and imaginary input vectors; 'F' and 'G' are the real and imaginary output vectors. The lengths of 'X' and 'Y' must be equal and should be the product of numbers less than about 10 for fast execution. The formula is n-1 h[k] = SUM z[j] exp (-2 pi i jk/n) j=0 where 'z[j]' is stored complex and stored in 'X(j+1)' and 'Y(j+1)'. Likewise 'h[k]' is complex and stored in 'F(k+1)' and 'G(k+1)'. The fast Fourier algorithm takes order n log(n) operations (for "good" values of n) rather than n**2 that straight evaluation (see the file 'tmtf.cpp') takes. I use one of two methods: * A program originally written by Sande and Gentleman. This requires that "n" can be expressed as a product of small numbers. * A method of Carl de Boor (1980), "Siam J Sci Stat Comput", pp 173-8. The sines and cosines are calculated explicitly. This gives better accuracy, at an expense of being a little slower than is otherwise possible. This is slower than the Sande-Gentleman program but will work for all "n" --- although it will be very slow for "bad" values of "n". Related functions FFTI(F, G, X, Y); // X=F and Y=G are OK RealFFT(X, F, G); RealFFTI(F, G, X); 'FFTI' is the inverse transform for 'FFT'. 'RealFFT' is for the case when the input vector is real, that is 'Y = 0'. I assume the length of 'X', denoted by n, is even. The program sets the lengths of 'F' and 'G' to n/2 + 1. 'RealFFTI' is the inverse of 'RealFFT'. See also the section on fast trigonometric transforms [3.23]. 3.23 Fast trigonometric transforms ==== ==== ============= ========== These are the sin and cosine transforms as defined by Charles Van Loan (1992) in "Computational frameworks for the fast Fourier transform" published by SIAM. See page 229. Some other authors use slightly different conventions. All the functions call the fast Fourier transforms [3.22] and require an even transform length, denoted by "m" in these notes. As with the FFT "m" should be the product of numbers less than about 10 for fast execution. The functions I define are DCT(U,V); // U, V are ColumnVectors, length "m+1" DCT_inverse(U,V); // inverse of DCT DST(U,V); // U, V are ColumnVectors, length "m+1" DST_inverse(U,V); // inverse of DST DCT_II(U,V); // U, V are ColumnVectors, length "m" DCT_II_inverse(U,V); // inverse of DCT_II DST_II(U,V); // U, V are ColumnVectors, length "m" DST_II_inverse(U,V); // inverse of DST_II where 'U' is the input and 'V' is the output. 'V = U' is OK. The length of 'V' is set by the functions. Here are the formulae: DCT m-1 k v[k] = u[0]/2 + SUM { u[j] cos (pi jk/m) } + (-) u[m]/2 j=1 for 'k = 0...m', where 'u[j]' and 'v[k]' are stored in 'U(j+1)' and 'V(k+1)'. DST m-1 v[k] = SUM { u[j] sin (pi jk/m) } j=1 for 'k = 1...(m-1)', where 'u[j]' and 'v[k]' are stored in 'U(j+1)' and 'V(k+1)'. 'u[0]' and 'u[m]' are ignored and 'v[0]' and 'v[m]' are set to zero. DCT_II m-1 v[k] = SUM { u[j] cos (pi (j+1/2)k/m) } j=0 for 'k = 0...(m-1)', where 'u[j]' and 'v[k]' are stored in 'U(j+1)' and 'V(k+1)'. DST_II m v[k] = SUM { u[j] sin (pi (j-1/2)k/m) } j=1 for 'k = 1...m', where 'u[j]' and 'v[k]' are stored in 'U(j)' and 'V(k)'. Note that the relationship between the subscripts in the formulae and those used in "newmat" is different for DST_II (and DST_II_inverse). 3.24 Interface to Numerical Recipes in C ==== ========= == ========= ======= == = This package can be used with the vectors and matrices defined in "Numerical Recipes in C". You need to edit the routines in Numerical Recipes so that the elements are of the same type as used in this package. Eg replace float by double, vector by dvector and matrix by dmatrix, etc. You may need to edit the function definitions to use the version acceptable to your compiler (if you are using the first edition of NRIC). You may need to enclose the code from Numerical Recipes in 'extern "C" { ... }'. You will also need to include the matrix and vector utility routines. Then any vector in Numerical Recipes with subscripts starting from 1 in a function call can be accessed by a RowVector, ColumnVector or DiagonalMatrix in the present package. Similarly any matrix with subscripts starting from 1 can be accessed by an nricMatrix in the present package. The class nricMatrix is derived from Matrix and can be used in place of Matrix. In each case, if you wish to refer to a RowVector, ColumnVector, DiagonalMatrix or nricMatrix X in an function from Numerical Recipes, use 'X.nric()' in the function call. Numerical Recipes cannot change the dimensions of a matrix or vector. So matrices or vectors must be correctly dimensioned before a Numerical Recipes routine is called. For example SymmetricMatrix B(44); ..... // load values into B nricMatrix BX = B; // copy values to an nricMatrix DiagonalMatrix D(44); // Matrices for output nricMatrix V(44,44); // correctly dimensioned int nrot; jacobi(BX.nric(),44,D.nric(),V.nric(),&nrot); // jacobi from NRIC cout << D; // print eigenvalues 3.25 Exceptions ==== ========== Here is the class structure for exceptions: Exception Logic_error ProgramException miscellaneous matrix error IndexException index out of bounds VectorException unable to convert matrix to vector NotSquareException matrix is not square (invert, solve) SubMatrixDimensionException out of bounds index of submatrix IncompatibleDimensionsException (multiply, add etc) NotDefinedException operation not defined (eg <) CannotBuildException copying a matrix where copy is undefined InternalException probably an error in newmat Runtime_error NPDException matrix not positive definite (Cholesky) ConvergenceException no convergence (e-values, non-linear, sort) SingularException matrix is singular (invert, solve) SolutionException no convergence in solution routine OverflowException floating point overflow Bad_alloc out of space (new fails) I have attempted to mimic the exception class structure in the C++ standard library, by defining the Logic_error and Runtime_error classes. If there is no catch statement or exceptions are disabled then my 'Terminate()' function in 'myexcept.h' is called. This prints out an error message, the dimensions and types of the matrices involved, the name of the routine detecting the exception, and any other information set by the Tracer [4] class. Also see the section on error messages [4] for additional notes on the messages generated by the exceptions. You can also print this information by printing 'Exception::what()'. See the file 'test_exc.cpp' as an example of catching an exception and printing the error message. The 08 version of newmat defined a member function 'void SetAction(int)' to help customise the action when an exception is called. This has been deleted in the 09 version. Now include an instruction such as 'cout << Exception::what() << endl;' in the 'Catch' or 'CatchAll' block to determine the action. The library includes the alternatives of using the inbuilt exceptions provided by a compiler, simulating exceptions, or disabling exceptions. See customising [2.3] for selecting the correct exception option. The rest of this section describes my partial simulation of exceptions for compilers which do not support C++ exceptions. I use Carlos Vidal's article in the September 1992 "C Users Journal" as a starting point. Newmat does a partial clean up of memory following throwing an exception - see the next section. However, the present version will leave a little heap memory unrecovered under some circumstances. I would not expect this to be a major problem, but it is something that needs to be sorted out. The functions/macros I define are Try, Throw, Catch, CatchAll and CatchAndThrow. Try, Throw, Catch and CatchAll correspond to try, throw, catch and catch(...) in the C++ standard. A list of Catch clauses must be terminated by either CatchAll or CatchAndThrow but not both. Throw takes an Exception as an argument or takes no argument (for passing on an exception). I do not have a version of Throw for specifying which exceptions a function might throw. Catch takes an exception class name as an argument; CatchAll and CatchAndThrow don't have any arguments. Try, Catch and CatchAll must be followed by blocks enclosed in curly brackets. I have added another macro ReThrow to mean a rethrow, Throw(). This was necessary to enable the package to be compatible with both my exception package and C++ exceptions. If you want to throw an exception, use a statement like Throw(Exception("Error message\n")); It is important to have the exception declaration in the Throw statement, rather than as a separate statement. All exception classes must be derived from the class, Exception, defined in newmat and can contain only static variables. See the examples in newmat if you want to define additional exceptions. 3.26 Cleanup after an exception ==== ======= ===== == ========= This section is about the simulated exceptions used in newmat. It is irrelevant if you are using the exceptions built into a compiler or have set the disable-exceptions option. The simulated exception mechanisms in newmat are based on the C functions setjmp and longjmp. These functions do not call destructors so can lead to garbage being left on the heap. (I refer to memory allocated by "new" as heap memory). For example, when you call Matrix A(20,30); a small amount of space is used on the stack containing the row and column dimensions of the matrix and 600 doubles are allocated on the heap for the actual values of the matrix. At the end of the block in which A is declared, the destructor for A is called and the 600 doubles are freed. The locations on the stack are freed as part of the normal operations of the stack. If you leave the block using a longjmp command those 600 doubles will not be freed and will occupy space until the program terminates. To overcome this problem newmat keeps a list of all the currently declared matrices and its exception mechanism will return heap memory when you do a Throw and Catch. However it will not return heap memory from objects from other packages. If you want the mechanism to work with another class you will have to do four things: 1: derive your class from class Janitor defined in except.h; 2: define a function 'void CleanUp()' in that class to return all heap memory; 3: include the following lines in the class definition public: void* operator new(size_t size) { do_not_link=true; void* t = ::operator new(size); return t; } void operator delete(void* t) { ::operator delete(t); } 4: be sure to include a copy constructor in you class definition, that is, something like X(const X&); Note that the function 'CleanUp()' does somewhat the same duties as the destructor. However 'CleanUp()' has to do the "cleaning" for the class you are working with and also the classes it is derived from. So it will often be wrong to use exactly the same code for both 'CleanUp()' and the destructor or to define your destructor as a call to 'CleanUp()'. 3.27 Non-linear applications ==== ========== ============ Files solution.h, solution.cpp contain a class for solving for x in y = f(x) where x is a one-dimensional continuous monotonic function. This is not a matrix thing at all but is included because it is a useful thing and because it is a simpler version of the technique used in the non-linear least squares. Files newmatnl.h, newmatnl.cpp contain a series of classes for non-linear least squares and maximum likelihood. Documentation for both of these is in the definition files. Simple examples are in sl_ex.cpp, nl_ex.cpp and garch.cpp. 3.28 Standard template library ==== ======== ======== ======= The standard template library (STL) is the set of "container templates" (vector, deque, list etc) defined by the C++ standards committee. Newmat is intended to be compatible with the STL in the sense that you can store matrices in the standard containers. I have defined '==' and inequality [3.6] operators to help make this possible. Probably there will have to be some other changes. My experiments with the Rogue Wave STL that comes with Borland C++ 5.0 showed that some things worked and some things unexpectedly didn't work. In particular, I couldn't get the list container to work. I don't know whose fault this is. If you want to use the container classes with Newmat please note * Don't use simulated exceptions. * Make sure the option DO_FREE_CHECK [2.3] is *not* turned on. * You can store only one type of matrix in a container. If you want to use a variety of types use the GenericMatrix type or store pointers to the matrices. * The vector and deque container templates like to copy their elements. For the vector container this happens when you insert an element anywhere except at the end or when you append an element and the current vector storage overflows. Since Newmat does not have "copy-on-write" this could get very inefficient. (Later versions may have "copy-on-write" for the GenericMatrix type). * You won't be able to sort the container or do anything that would call an inequality operator. I doubt whether the STL container will be used often for matrices. So I don't think these limitations are very critical. If you think otherwise, please tell me. 3.29 Namespace ==== ========= "Namespace" is a new facility in C++. Its purpose is to avoid name clashes between different libraries. I have included the namespace capability. Activate the line '#define use_namespace' in 'include.h'. Then include either the statement using namespace NEWMAT; at the beginning of any file that needs to access the newmat library or using namespace RBD_LIBRARIES; at the beginning of any file that needs to access all my libraries. This works correctly with Borland [2.4.2] C++ version 5. Microsoft [2.4.5] Visual C++ version 5 works in my example and test files, but fails with apparently insignificant changes (it may be more reliable if you have applied service pack 3). If you #include "newmatap.h", but no other newmat include file, then also #include "newmatio.h". My use of namespace does not work with Gnu g++ [2.4.3] version 2.7.2. I have defined the following namespaces: * RBD_COMMON for functions and classes used by most of my libraries * NEWMAT for the newmat library * RBD_LIBRARIES for all my libraries 4 Error messages = ===== ======== Most error messages are self-explanatory. The message gives the size of the matrices involved. Matrix types are referred to by the following codes: Matrix or vector Rect Symmetric matrix Sym Band matrix Band Symmetric band matrix SmBnd Lower triangular matrix LT Lower triangular band matrix LwBnd Upper triangular matrix UT Upper triangular band matrix UpBnd Diagonal matrix Diag Crout matrix (LU matrix) Crout Band LU matrix BndLU Other codes should not occur. See the section on exceptions [3.25] for more details on the structure of the exception classes. I have defined a class Tracer that is intended to help locate the place where an error has occurred. At the beginning of a function I suggest you include a statement like Tracer tr("name"); where name is the name of the function. This name will be printed as part of the error message, if an exception occurs in that function, or in a function called from that function. You can change the name as you proceed through a function with the ReName function tr.ReName("new name"); if, for example, you want to track progress through the function. 5 Bugs = ==== * Small memory leaks may occur when an exception is thrown and caught. * My exception scheme may not be not properly linked in with the standard library exceptions. In particular, my scheme may fail to catch out-of-memory exceptions. 6 List of files = ==== == ===== Documentation README readme file NEWMAT TXT documentation file Definition files BOOLEAN H boolean class definition CONTROLW H control word definition file INCLUDE H details of include files and options MYEXCEPT H general exception handler definitions NEWMAT H main matrix class definition file NEWMATAP H applications definition file NEWMATIO H input/output definition file NEWMATNL H non-linear optimisation definition file NEWMATRC H row/column functions definition files NEWMATRM H rectangular matrix access definition files PRECISIO H numerical precision constants SOLUTION H one dimensional solve definition file Program files BANDMAT CPP band matrix routines CHOLESKY CPP Cholesky decomposition EVALUE CPP eigenvalues and eigenvector calculation FFT CPP fast Fourier, trig. transforms HHOLDER CPP QR routines JACOBI CPP eigenvalues by the Jacobi method MYEXCEPT CPP general error and exception handler NEWFFT CPP new fast Fourier transform NEWMAT1 CPP type manipulation routines NEWMAT2 CPP row and column manipulation functions NEWMAT3 CPP row and column access functions NEWMAT4 CPP constructors, resize, utilities NEWMAT5 CPP transpose, evaluate, matrix functions NEWMAT6 CPP operators, element access NEWMAT7 CPP invert, solve, binary operations NEWMAT8 CPP LU decomposition, scalar functions NEWMAT9 CPP output routines NEWMATEX CPP matrix exception handler NEWMATNL CPP non-linear optimisation NEWMATRM CPP rectangular matrix access functions SORT CPP sorting functions SOLUTION CPP one dimensional solve SUBMAT CPP submatrix functions SVD CPP singular value decomposition Example files EXAMPLE CPP example of use of package EXAMPLE TXT output from example SL_EX CPP example of OneDimSolve routine SL_EX TXT output from example NL_EX CPP example of non-linear least squares NL_EX TXT output from example GARCH CPP example of maximum-likelihood fit GARCH DAT data file for garch.cpp GARCH TXT output from example TEST_EXC CPP demonstration exceptions TEST_EXC TXT output from TEST_EXC.CPP Test files TMT* CPP test files TMT TXT output from the test files See the section on testing [2.7] for details of the test files. Make files GNU MAK make file for Gnu G++ CC MAK make file for AT&T, Sun and HPUX MS_NT MAK make file for Microsoft Visual C++ 2 (windows NT) MS MAK make file for Microsoft Visual C++ 1.51 (DOS) BC MAK make file for Borland C++ 4.5,5 (large model) BC32 MAK make file for Borland C++ 4.5,5 (32 bit console model) WATCOM MAK make file for Watcom 10 WATCO_NT MAK make file for Watcom 10 (windows NT) 7 Problem report form = ======= ====== ==== Copy and paste this to your editor; fill it out and email to robertd@netlink.co.nz (don't forget the "d" in robertd). But first look in my web page http://webnz.com/robert/ to see if the bug has already been reported. Version: ............... newmat10 beta (26 December 1999) Your email address: .... Today's date: .......... Your machine: .......... Operating system: ...... Compiler & version: .... Compiler options (eg GUI or console)... Describe the problem - attach examples if possible: 8 Notes on the design of the library = ===== == === ====== == === ======= Safety, usability, efficiency 8.1 Matrix vs array library 8.2 Design questions 8.3 Data storage 8.4 Memory management 8.5 Evaluation of expressions 8.6 Explosion in the number of operations 8.7 Destruction of temporaries 8.8 A calculus of matrix types 8.9 Error handling 8.10 Sparse matrices 8.11 Complex matrices 8.12 I describe some of the ideas behind this package, some of the decisions that I needed to make and give some details about the way it works. You don't need to read this part of the documentation in order to use the package. It isn't obvious what is the best way of going about structuring a matrix package. I don't think you can figure this out with "thought" experiments. Different people have to try out different approaches. And someone else may have to figure out which is best. Or, more likely, the ultimate packages will lift some ideas from each of a variety of trial packages. So, I don't claim my package is an "ultimate" package, but simply a trial of a number of ideas. The following pages give some background on these ideas. 8.1 Safety, usability, efficiency === ======= ========== ========== Some general comments A library like "newmat" needs to balance "safety", "usability" and "efficiency". By safety, I mean getting the right answer, and not causing crashes or damage to the computer system. By usability, I mean being easy to learn and use, including not being too complicated, being intuitive, saving the users' time, being nice to use. Efficiency means minimising the use of computer memory and time. In the early days of computers the emphasis was on efficiency. But computer power gets cheaper and cheaper, halving in price every 18 months. On the other hand the unaided human brain is probably not a lot better than it was 100,000 years ago! So we should expect the balance to shift to put more emphasis on safety and usability and a little less on efficiency. So I don't mind if my programs are a little less efficient than programs written in pure C (or Fortran) if I gain substantially in safety and usability. But I would mind if they were a lot less efficient. Type of use Second reason for putting extra emphasis on safety and usability is the way I and, I suspect, most other users actually use "newmat". Most completed programs are used only a few times. Some result is required for a client, paper or thesis. The program is developed and tested, the result is obtained, and the program archived. Of course bits of the program will be recycled for the next project. But it may be less usual for the same program to be run over and over again. So the cost, computer time + people time, is in the development time and often, much less in the actual time to run the final program. So good use of people time, especially during development is really important. This means you need highly usable libraries. So if you are dealing with matrices, you want the good interface that I have tried to provide in "newmat", and, of course, reliable methods underneath it. Of course, efficiency is still important. We often want to run the biggest problem our computer will handle and often a little bigger. The C++ language almost lets us have both worlds. We can define a reasonably good interface, and get good efficiency in the use of the computer. Levels of access We can imagine the "black box" model of a "newmat". Suppose the inside is hidden but can be accessed by the methods described in the reference [3] section. Then the interface is reasonably consistent and intuitive. Matrices can be accessed and manipulated in much the same way as doubles or ints in regular C. All accesses are checked. It is most unlikely that an incorrect index will crash the system. In general, users do not need to use pointers, so one shouldn't get pointers pointing into space. And, hopefully, you will get simpler code and so less errors. There are some exceptions to this. In particular, the C-like subscripts [3.2] are not checked for validity. They give faster access but with a lower level of safety. Then there is the Store() [3.8] function which takes you to the data array within a matrix. This takes you right inside the "black box". But this is what you have to use if you are writing, for example, a new matrix factorisation, and require fast access to the data array. I have tried to write code to simplify access to the interior of a rectangular matrix, see file newmatrm.cpp, but I don't regard this as very successful, as yet, and have not included it in the documentation. Ideally we should have improved versions of this code for each of the major types of matrix. But, in reality, most of my matrix factorisations are written in what is basically the C language with very little C++. So our "box" is not very "black". You have a choice of how far you penetrate. On the outside you have a good level of safety, but in some cases efficiency is compromised a little. If you penetrate inside the "box" safety is reduced but you can get better efficiency. Some performance data This section looks at the performance on "newmat" for simple sums, comparing it with pure C code and with a somewhat unintelligent array program. The following table lists the time (in seconds) for carrying out the operations 'X=A+B;', 'X=A+B+C;', 'X=A+B+C+D;', where 'X,A,B,C,D' are of type ColumnVector, with a variety of programs. I am using Borland C++, version 5 in 32 bit console mode under windows NT 4.0 on a PC with a 150 mhz pentium and 128 mbytes of memory. length iters. newmat subs. C C-resz array X=A+B 2000000 2 1.2 3.7 1.2 1.4 3.3 200000 20 1.2 3.7 1.2 1.5 3.1 20000 200 1.0 3.6 1.0 1.2 2.9 2000 2000 1.0 3.6 0.9 0.9 2.2 200 20000 0.8 3.0 0.4 0.5 1.9 20 200000 5.5 2.9 0.4 0.9 2.8 2 2000000 43.9 3.2 1.0 4.2 12.3 X=A+B+C 2000000 2 2.5 4.6 1.6 2.1 32.5 200000 20 2.1 4.6 1.6 1.8 6.2 20000 200 1.8 4.5 1.5 1.8 5.6 2000 2000 1.8 4.4 1.3 1.3 3.9 200 20000 2.2 4.3 1.0 0.9 2.3 20 200000 8.5 4.3 1.0 1.2 3.0 2 2000000 62.5 3.9 1.0 4.4 17.7 X=A+B+C+D 2000000 2 3.7 6.7 2.4 2.8 260.7 200000 20 3.7 6.7 2.4 2.5 9.2 20000 200 3.4 6.6 2.3 2.9 8.2 2000 2000 2.9 6.4 2.0 2.0 5.9 200 20000 2.5 5.5 1.0 1.3 4.3 20 200000 9.9 5.5 1.0 1.6 4.5 2 2000000 76.5 5.8 1.7 5.0 24.9 The first column gives the lengths of the arrays, the second the number of iterations and the remaining columns the total time required in seconds. If the only thing that consumed time was the double precision addition then the numbers within each block of the table would be the same. The column labelled "newmat" is using the standard "newmat" add. In the next column the calculation is using the usual C style "for" loop and accessing the elements using "newmat" subscripts such as 'A(i)'. The column labelled "C" uses the usual C method: 'while (j--) *x++ = *a++ + *b++;' . The following column also includes an 'X.ReSize()' in the outer loop to correspond to the reassignment of memory that "newmat" would do. The final column is the time taken by a simple array package that makes no attempt to eliminate unnecessary copying or to recycle temporary memory but does have array definitions of the basic operators. It does, however, do its sums in blocks of 4 and copies in blocks of 8 in the same way that "newmat" does. Here are my conclusions. * "Newmat" does very badly for length 2 and doesn't do very well for length 20. There is some particularly tortuous code in "newmat" for determining which sum algorithm to use and I am sure this could be improved. However the "array" program is also having difficulty with length 2 so it is unlikely that the problem could be completely eliminated. * The "array" program is running into problems for length 2,000,000. This is because RAM memory is being exhausted. * For arrays of length 2000 or longer "newmat" is doing about as well as C and slightly better than C with resize in the 'X=A+B' table. For the other two tables it is slower, but not dramatically so. * Addition using the "newmat" subscripts, while considerably slower than the others, is still surprisingly good. * The "array" program is more than 2 times slower than "newmat" for lengths 2000 or higher. In summary: for the situation considered here, "newmat" is doing very well for large ColumnVectors, even for sums with several terms, but not so well for shorter ColumnVectors. 8.2 Matrix vs array library === ====== == ===== ======= The "newmat" library is for the manipulation of matrices, including the standard operations such as multiplication as understood by numerical analysts, engineers and mathematicians. A matrix is a two dimensional array of numbers. However, very special operations such as matrix multiplication are defined specifically for matrices. This means that a "matrix" library, as I understand the term, is different from a general "array" library. I see a matrix package as providing the following 1. Evaluation of matrix expressions in a form familiar to scientists and engineers. For example 'A = B * (C + D.t());'. In particular '*' means matrix multiply. 2. Access to the elements of a matrix; 3. Access to submatrices; 4. Common elementary matrix functions such as determinant and trace; 5. A platform for developing advanced matrix functions such as eigen-value analysis; 6. Good efficiency and storage management; 7. Graceful exit from errors. It may also provide 8. A variety of types of elements (eg real and complex); 9. A variety of types of matrices (eg rectangular and symmetric). In contrast an array package should provide 1'. Arrays can be copied with a single instruction; may have some arithmetic operations for elementwise combination of arrays, say '+', '-', '*', '/', it may provide matrix multiplication as a function; 2'. High speed access to elements directly and perhaps with iterators; 3'. Access to subarrays and rows (and columns?); 6'. Good efficiency and storage management; 7'. Graceful exit from errors; 8'. A wide variety of types of elements (eg int, float, double, string etc); 9'. One, two and three dimensional arrays, at least, with starting points of the indices set by user. It may be possible to amalgamate these two sets of requirements to some extent. However "newmat" is definitely oriented towards the first set. 8.3 Design questions === ====== ========= Even within the bounds set by the requirements of a matrix library there is a substantial opportunity for variation between what different matrix packages might provide. It is not possible to build a matrix package that will meet everyone's requirements. In many cases if you put in one facility, you impose overheads on everyone using the package. This both in storage required for the program and in efficiency. Likewise a package that is optimised towards handling large matrices is likely to become less efficient for very small matrices where the administration time for the matrix may become significant compared with the time to carry out the operations. It is better to provide a variety of packages (hopefully compatible) so that most users can find one that meets their requirements. This package is intended to be one of these packages; but not all of them. Since my background is in statistical methods, this package is oriented towards the kinds things you need for statistical analyses. Now looking at some specific questions. What size of matrices? A matrix library may target small matrices (say 3 x 3), or medium sized matrices, or very large matrices. A library targeting very small matrices will seek to minimise administration. A library for medium sized or very large matrices can spend more time on administration in order to conserve space or optimise the evaluation of expressions. A library for very large matrices will need to pay special attention to storage and numerical properties. This library is designed for medium sized matrices. This means it is worth introducing some optimisations, but I don't have to worry about setting up some form of virtual memory. Which matrix types? As well as the usual rectangular matrices, matrices occuring repeatedly in numerical calculations are upper and lower triangular matrices, symmetric matrices and diagonal matrices. This is particularly the case in calculations involving least squares and eigenvalue calculations. So as a first stage these were the types I decided to include. It is also necessary to have types row vector and column vector. In a "matrix" package, in contrast to an "array" package, it is necessary to have both these types since they behave differently in matrix expressions. The vector types can be derived for the rectangular matrix type, so having them does not greatly increase the complexity of the package. The problem with having several matrix types is the number of versions of the binary operators one needs. If one has 5 distinct matrix types then a simple library will need 25 versions of each of the binary operators. In fact, we can evade this problem, but at the cost of some complexity. What element types? Ideally we would allow element types double, float, complex and int, at least. It might be reasonably easy, using templates or equivalent, to provide a library which could handle a variety of element types. However, as soon as one starts implementing the binary operators between matrices with different element types, again one gets an explosion in the number of operations one needs to consider. At the present time the compilers I deal with are not up to handling this problem with templates. (Of course, when I started writing "newmat" there were no templates). But even when the compilers do meet the specifications of the draft standard, writing a matrix package that allows for a variety of element types using the template mechanism is going to be very difficult. I am inclined to use templates in an "array" library but not in a "matrix" library. Hence I decided to implement only one element type. But the user can decide whether this is float or double. The package assumes elements are of type Real. The user typedefs Real to float or double. It might also be worth including symmetric and triangular matrices with extra precision elements (double or long double) to be used for storage only and with a minimum of operations defined. These would be used for accumulating the results of sums of squares and product matrices or multistage QR triangularisations. Allow matrix expressions I want to be able to write matrix expressions the way I would on paper. So if I want to multiply two matrices and then add the transpose of a third one I can write something like 'X = A * B + C.t();'. I want this expression to be evaluated with close to the same efficiency as a hand-coded version. This is not so much of a problem with expressions including a multiply since the multiply will dominate the time. However, it is not so easy to achieve with expressions with just '+' and '-'. A second requirement is that temporary matrices generated during the evaluation of an expression are destroyed as quickly as possible. A desirable feature is that a certain amount of "intelligence" be displayed in the evaluation of an expression. For example, in the expression 'X = A.i() * B;' where 'i()' denotes inverse, it would be desirable if the inverse wasn't explicitly calculated. Naming convention How are classes and public member functions to be named? As a general rule I have spelt identifiers out in full with individual words being capitalised. For example "UpperTriangularMatrix". If you don't like this you can #define or typedef shorter names. This convention means you can select an abbreviation scheme that makes sense to you. Exceptions to the general rule are the functions for transpose and inverse. To make matrix expressions more like the corresponding mathematical formulae, I have used the single letter abbreviations, 't()' and 'i()'. Row and column index ranges In mathematical work matrix subscripts usually start at one. In C, array subscripts start at zero. In Fortran, they start at one. Possibilities for this package were to make them start at 0 or 1 or be arbitrary. Alternatively one could specify an "index set" for indexing the rows and columns of a matrix. One would be able to add or multiply matrices only if the appropriate row and column index sets were identical. In fact, I adopted the simpler convention of making the rows and columns of a matrix be indexed by an integer starting at one, following the traditional convention. In an earlier version of the package I had them starting at zero, but even I was getting mixed up when trying to use this earlier package. So I reverted to the more usual notation and started at 1. Element access - method and checking We want to be able to use the notation 'A(i,j)' to specify the '(i,j)'-th element of a matrix. This is the way mathematicians expect to address the elements of matrices. I consider the notation 'A[i][j]' totally alien. However I include this as an option to help people converting from C. There are two ways of working out the address of 'A(i,j)'. One is using a "dope" vector which contains the first address of each row. Alternatively you can calculate the address using the formula appropriate for the structure of 'A'. I use this second approach. It is probably slower, but saves worrying about an extra bit of storage. The other question is whether to check for 'i' and 'j' being in range. I do carry out this check following years of experience with both systems that do and systems that don't do this check. I would hope that the routines I supply with this package will reduce your need to access elements of matrices so speed of access is not a high priority. Use iterators Iterators are an alternative way of providing fast access to the elements of an array or matrix when they are to be accessed sequentially. They need to be customised for each type of matrix. I have not implemented iterators in this package, although some iterator like functions are used internally for some row and column functions. 8.4 Data storage === ==== ======= Structure Each matrix object contains the basic information such as the number of rows and columns and a status variable plus a pointer to the data array which is on the heap. One block or several The elements of the matrix are stored as a single array. Alternatives would have been to store each row as a separate array or a set of adjacent rows as a separate array. The present solution simplifies the program but limits the size of matrices in 16 bit PCs that have a 64k byte limit on the size of arrays (I don't use the 'huge' keyword). The large arrays may also cause problems for memory management in smaller machines. By row or by column or other In Fortran two dimensional arrays are stored by column. In most other systems they are stored by row. I have followed this later convention. This makes it easier to interface with other packages written in C but harder to interface with those written in Fortran. This may have been a wrong decision. Most work on the efficient manipulation of large matrices is being done in Fortran. It would have been easier to use this work if I had adopted the Fortran convention. An alternative would be to store the elements by mid-sized rectangular blocks. This might impose less strain on memory management when one needs to access both rows and columns. Storage of symmetric matrices Symmetric matrices are stored as lower triangular matrices. The decision was pretty arbitrary, but it does slightly simplify the Cholesky decomposition program. 8.5 Memory management - reference counting or status variable? === ====== ========== = ========= ======== == ====== ========= Consider the instruction X = A + B + C; To evaluate this a simple program will add 'A' to 'B' putting the total in a temporary 'T1'. Then it will add 'T1' to 'C' creating another temporary 'T2' which will be copied into 'X'. 'T1' and 'T2' will sit around till the end of the execution of the statement and perhaps of the block. It would be faster if the program recognised that 'T1' was temporary and stored the sum of 'T1' and 'C' back into 'T1' instead of creating 'T2' and then avoided the final copy by just assigning the contents of 'T1' to 'X' rather than copying. In this case there will be no temporaries requiring deletion. (More precisely there will be a header to be deleted but no contents). For an instruction like X = (A * B) + (C * D); we can't easily avoid one temporary being left over, so we would like this temporary deleted as quickly as possible. I provide the functionality for doing all this by attaching a status variable to each matrix. This indicates if the matrix is temporary so that its memory is available for recycling or deleting. Any matrix operation checks the status variables of the matrices it is working with and recycles or deletes any temporary memory. An alternative or additional approach would be to use "reference counting and delayed copying" - also known as "copy on write". If a program requests a matrix to be copied, the copy is delayed until an instruction is executed which modifies the memory of either the original matrix or the copy. If the original matrix is deleted before either matrix is modified, in effect, the values of the original matrix are transfered to the copy without any actual copying taking place. This solves the difficult problem of returning an object from a function without copying and saves the unnecessary copying in the previous examples. There are downsides to the delayed copying approach. Typically, for delayed copying one uses a structure like the following: Matrix | +------> Array Object | | | +------> Data array | | | +------- Counter | +------ Dimension information where the arrows denote a pointer to a data structure. If one wants to access the "Data array" one will need to track through two pointers. If one is going to write, one will have to check whether one needs to copy first. This is not important when one is going to access the whole array, say, for a add operation. But if one wants to access just a single element, then it imposes a significant additional overhead on that operation. Any subscript operation would need to check whether an update was required - even read since it is hard for the compiler to tell whether a subscript access is a read or write. Some matrix libraries don't bother to do this. So if you write 'A = B;' and then modify an element of one of 'A' or 'B', then the same element of the other is also modified. I don't think this is acceptable behaviour. Delayed copy does not provide the additional functionality of my approach but I suppose it would be possible to have both delayed copy and tagging temporaries. My approach does not automatically avoid all copying. In particular, you need use a special technique to return a matrix from a function without copying. 8.6 Evaluation of expressions - lazy evaluation === ========== == =========== = ==== ========== Consider the instruction X = B - X; A simple program will subtract 'X' from 'B', store the result in a temporary 'T1' and copy 'T1' into 'X'. It would be faster if the program recognised that the result could be stored directly into 'X'. This would happen automatically if the program could look at the instruction first and mark 'X' as temporary. C programmers would expect to avoid the same problem with X = X - B; by using an operator '-=' X -= B; However this is an unnatural notation for non C users and it may be nicer to write 'X = X - B'; and know that the program will carry out the simplification. Another example where this intelligent analysis of an instruction is helpful is in X = A.i() * B; where 'i()' denotes inverse. Numerical analysts know it is inefficient to evaluate this expression by carrying out the inverse operation and then the multiply. Yet it is a convenient way of writing the instruction. It would be helpful if the program recognised this expression and carried out the more appropriate approach. I regard this interpretation of 'A.i() * B' as just providing a convenient notation. The objective is not to correct the errors of people who are unaware of the inefficiency of 'A.i() * B' if interpreted literally. There is a third reason for the two-stage evaluation of expressions and this is probably the most important one. In C++ it is quite hard to return an expression from a function such as ('*', '+' etc) without a copy. This is particularly the case when an assignment ('=') is involved. The mechanism described here provides one way for avoiding this in matrix expressions. To carry out this "intelligent" analysis of an instruction matrix expressions are evaluated in two stages. In the the first stage a tree representation of the expression is formed. For example '(A+B)*C' is represented by a tree ' * / \ + C / \ A B ' Rather than adding 'A' and 'B' the '+' operator yields an object of a class "AddedMatrix" which is just a pair of pointers to 'A' and 'B'. Then the '*' operator yields a "MultipliedMatrix" which is a pair of pointers to the "AddedMatrix" and 'C'. The tree is examined for any simplifications and then evaluated recursively. Further possibilities not yet included are to recognise 'A.t()*A' and 'A.t()+A' as symmetric or to improve the efficiency of evaluation of expressions like 'A+B+C', 'A*B*C', 'A*B.t()' ('t()' denotes transpose). One of the disadvantages of the two-stage approach is that the types of matrix expressions are determined at run-time. So the compiler will not detect errors of the type Matrix M; DiagonalMatrix D; ....; D = M; We don't allow conversions using '=' when information would be lost. Such errors will be detected when the statement is executed. 8.7 How to overcome an explosion in number of operations === === == ======== == ========= == ====== == ========== The package attempts to solve the problem of the large number of versions of the binary operations required when one has a variety of types. With "n" types of matrices the binary operations will each require "n"-squared separate algorithms. Some reduction in the number may be possible by carrying out conversions. However, the situation rapidly becomes impossible with more than 4 or 5 types. Doug Lea told me that it was possible to avoid this problem. I don't know what his solution is. Here's mine. Each matrix type includes routines for extracting individual rows or columns. I assume a row or column consists of a sequence of zeros, a sequence of stored values and then another sequence of zeros. Only a single algorithm is then required for each binary operation. The rows can be located very quickly since most of the matrices are stored row by row. Columns must be copied and so the access is somewhat slower. As far as possible my algorithms access the matrices by row. There is another approach. Each of the matrix types defined in this package can be set up so both rows and columns have their elements at equal intervals provided we are prepared to store the rows and columns in up to three chunks. With such an approach one could write a single "generic" algorithm for each of multiply and add. This would be a reasonable alternative to my approach. I provide several algorithms for operations like + . If one is adding two matrices of the same type then there is no need to access the individual rows or columns and a faster general algorithm is appropriate. Generally the method works well. However symmetric matrices are not always handled very efficiently (yet) since complete rows are not stored explicitly. The original version of the package did not use this access by row or column method and provided the multitude of algorithms for the combination of different matrix types. The code file length turned out to be just a little longer than the present one when providing the same facilities with 5 distinct types of matrices. It would have been very difficult to increase the number of matrix types in the original version. Apparently 4 to 5 types is about the break even point for switching to the approach adopted in the present package. However it must also be admitted that there is a substantial overhead in the approach adopted in the present package for small matrices. The test program developed for the original version of the package takes 30 to 50% longer to run with the current version (though there may be some other reasons for this). This is for matrices in the range 6x6 to 10x10. To try to improve the situation a little I do provide an ordinary matrix multiplication routine for the case when all the matrices involved are rectangular. 8.8 Destruction of temporaries === =========== == =========== Versions before version 5 of newmat did not work correctly with Gnu C++ (version 5 or earlier). This was because the tree structure used to represent a matrix expression was set up on the stack. This was fine for AT&T, Borland and Zortech C++. However early version Gnu C++ destroys temporary structures as soon as the function that accesses them finishes. The other compilers wait until the end of the current expression or current block. To overcome this problem, there is now an option to store the temporaries forming the tree structure on the heap (created with new) and to delete them explicitly. Activate the definition of TEMPS_DESTROYED_QUICKLY to set this option. In fact, I suggest this be the default option as, with it, the package uses less storage and runs faster. There still exist situations Gnu C++ will go wrong. These include statements like A = X * Matrix(P * Q); Real r = (A*B)(3,4); Neither of these kinds of statements will occur often in practice. Now that the C++ standards committee has said that temporary structures should not be destroyed before a statement finishes, my policy needs to be re-evaluated. Probably, I'll return to using the stack, because of the difficulty of managing exceptions with the heap version. 8.9 A calculus of matrix types === = ======== == ====== ===== The program needs to be able to work out the class of the result of a matrix expression. This is to check that a conversion is legal or to determine the class of an intermediate result. To assist with this, a class MatrixType is defined. Operators '+', '-', '*', '>=' are defined to calculate the types of the results of expressions or to check that conversions are legal. Early versions of "newmat" stored the types of the results of operations in a table. So, for example, if you multiplied an UpperTriangularMatrix by a LowerTriangularMatrix, "newmat" would look up the table and see that the result was of type Matrix. With this approach the exploding [8.7] number of operations problem recurred although not as seriously as when code had to be written for each pair of types. But there was always the suspicion that somewhere, there was an error in one of those 9x9 tables, that would be very hard to find. And the problem would get worse as additional matrix types or operators were included. The present version of "newmat" solves the problem by assigning "attributes" such as "diagonal" or "band" or "upper triangular" to each matrix type. Which attributes a matrix type has, is stored as bits in an integer. As an example, the DiagonalMatrix type has the bits corresponding to "diagonal", "symmetric" and "band" equal to 1. By looking at the attributes of each of the operands of a binary operator, the program can work out the attributes of the result of the operation with simple bitwise operations. Hence it can deduce an appropriate type. The "symmetric" attribute is a minor problem because "symmetric" * "symmetric" does not yield "symmetric" unless both operands are "diagonal". But otherwise very simple code can be used to deduce the attributes of the result of a binary operation. Tables of the types resulting from the binary operators are output at the beginning of the test [2.7] program. 8.10 Error handling ==== ===== ======== The library now does have a moderately graceful exit from errors. One can use either the simulated exceptions or the compiler supported exceptions. When newmat08 was released (in 1995), compiler exception handling in the compilers I had access to was unreliable. I recommended you used my simulated exceptions. Now (in 1997) compiler supported exceptions do seem to work on a variety of compilers - but not all compilers. The approach in the present library, attempting to simulate C++ exceptions, is not completely satisfactory, but seems a good interim solution for those who cannot use compiler supported exceptions. People who don't want exceptions in any shape or form, can set the option to exit the program if an exception is thrown. The exception mechanism cannot clean-up objects explicitly created by new. This must be explicitly carried out by the package writer or the package user. I have not yet done this completely with the present package so occasionally a little garbage may be left behind after an exception. I don't think this is a big problem, but it is one that needs fixing. 8.11 Sparse matrices ==== ====== ======== The library does not support sparse matrices. For sparse matrices there is going to be some kind of structure vector. It is going to have to be calculated for the results of expressions in much the same way that types are calculated. In addition, a whole new set of row and column operations would have to be written. Sparse matrices are important for people solving large sets of differential equations as well as being important for statistical and operational research applications. But there are packages being developed specifically for sparse matrices and these might present the best approach, at least where sparse matrices are the main interest. 8.12 Complex matrices ==== ======= ======== The package does not yet support matrices with complex elements. There are at least two approaches to including these. One is to have matrices with complex elements. This probably means making new versions of the basic row and column operations for Real*Complex, Complex*Complex, Complex*Real and similarly for + and -. This would be OK, except that if I also want to do this for sparse matrices, then when you put these together, the whole thing will get out of hand. The alternative is to represent a Complex matrix by a pair of Real matrices. One probably needs another level of decoding expressions but I think it might still be simpler than the first approach. But there is going to be a problem with accessing elements and it does not seem possible to solve this in an entirely satisfactory way. Complex matrices are used extensively by electrical engineers and physicists and really should be fully supported in a comprehensive package. You can simulate most complex operations by representing 'Z = X + iY' by / X Y \ \ -Y X / Most matrix operations will simulate the corresponding complex operation, when applied to this matrix. But, of course, this matrix is twice as big as you would need with a genuine complex matrix library. ossim-Miami-2.9.1/src/matrix/newmat1.cpp000066400000000000000000000134411352751253100200710ustar00rootroot00000000000000//$$ newmat1.cpp Matrix type functions // Copyright (C) 1991,2,3,4: R B Davies //#define WANT_STREAM #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,1); ++ExeCount; } #else #define REPORT {} #endif /************************* MatrixType functions *****************************/ // Skew needs more work <<<<<<<<< // all operations to return MatrixTypes which correspond to valid types // of matrices. // Eg: if it has the Diagonal attribute, then it must also have // Upper, Lower, Band, Square and Symmetric. MatrixType MatrixType::operator*(const MatrixType& mt) const { REPORT int a = attribute & mt.attribute & ~(Symmetric | Skew); a |= (a & Diagonal) * 63; // recognise diagonal return MatrixType(a); } MatrixType MatrixType::SP(const MatrixType& mt) const // elementwise product // Lower, Upper, Diag, Band if only one is // Symmetric, Ones, Valid (and Real) if both are // Need to include Lower & Upper => Diagonal // Will need to include both Skew => Symmetric { REPORT int a = ((attribute | mt.attribute) & ~(Symmetric + Skew + Valid + Ones)) | (attribute & mt.attribute); if ((a & Lower) != 0 && (a & Upper) != 0) a |= Diagonal; if ((attribute & Skew) != 0) { if ((mt.attribute & Symmetric) != 0) a |= Skew; if ((mt.attribute & Skew) != 0) { a &= ~Skew; a |= Symmetric; } } else if ((mt.attribute & Skew) != 0 && (attribute & Symmetric) != 0) a |= Skew; a |= (a & Diagonal) * 63; // recognise diagonal return MatrixType(a); } MatrixType MatrixType::KP(const MatrixType& mt) const // Kronecker product // Lower, Upper, Diag, Symmetric, Band, Valid if both are // Band if LHS is band & other is square // Ones is complicated so leave this out { REPORT int a = (attribute & mt.attribute) & ~Ones; if ((attribute & Band) != 0 && (mt.attribute & Square) != 0) a |= Band; //int a = ((attribute & mt.attribute) | (attribute & Band)) & ~Ones; return MatrixType(a); } MatrixType MatrixType::i() const // type of inverse { REPORT int a = attribute & ~(Band+LUDeco); a |= (a & Diagonal) * 63; // recognise diagonal return MatrixType(a); } MatrixType MatrixType::t() const // swap lower and upper attributes // assume Upper is in bit above Lower { REPORT int a = attribute; a ^= (((a >> 1) ^ a) & Lower) * 3; return MatrixType(a); } MatrixType MatrixType::MultRHS() const { REPORT // remove symmetric attribute unless diagonal return (attribute >= Dg) ? attribute : (attribute & ~Symmetric); } // this is used for deciding type of multiplication bool Rectangular(MatrixType a, MatrixType b, MatrixType c) { REPORT return ((a.attribute | b.attribute | c.attribute) & ~(MatrixType::Valid | MatrixType::Square)) == 0; } const char* MatrixType::Value() const { // make a string with the name of matrix with the given attributes switch (attribute) { case Valid: REPORT return "Rect "; case Valid+Square: REPORT return "Squ "; case Valid+Symmetric+Square: REPORT return "Sym "; case Valid+Skew+Square: REPORT return "Skew "; case Valid+Band+Square: REPORT return "Band "; case Valid+Symmetric+Band+Square: REPORT return "SmBnd"; case Valid+Upper+Square: REPORT return "UT "; case Valid+Diagonal+Symmetric+Band+Upper+Lower+Square: REPORT return "Diag "; case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones+Square: REPORT return "Ident"; case Valid+Band+Upper+Square: REPORT return "UpBnd"; case Valid+Lower+Square: REPORT return "LT "; case Valid+Band+Lower+Square: REPORT return "LwBnd"; default: REPORT if (!(attribute & Valid)) return "UnSp "; if (attribute & LUDeco) return (attribute & Band) ? "BndLU" : "Crout"; return "?????"; } } GeneralMatrix* MatrixType::New(int nr, int nc, BaseMatrix* bm) const { // make a new matrix with the given attributes Tracer tr("New"); GeneralMatrix* gm=0; // initialised to keep gnu happy switch (attribute) { case Valid: REPORT if (nc==1) { gm = new ColumnVector(nr); break; } if (nr==1) { gm = new RowVector(nc); break; } gm = new Matrix(nr, nc); break; case Valid+Square: REPORT if (nc!=nr) { Throw(NotSquareException()); } gm = new SquareMatrix(nr); break; case Valid+Symmetric+Square: REPORT gm = new SymmetricMatrix(nr); break; case Valid+Band+Square: { REPORT MatrixBandWidth bw = bm->BandWidth(); gm = new BandMatrix(nr,bw.lower,bw.upper); break; } case Valid+Symmetric+Band+Square: REPORT gm = new SymmetricBandMatrix(nr,bm->BandWidth().lower); break; case Valid+Upper+Square: REPORT gm = new UpperTriangularMatrix(nr); break; case Valid+Diagonal+Symmetric+Band+Upper+Lower+Square: REPORT gm = new DiagonalMatrix(nr); break; case Valid+Band+Upper+Square: REPORT gm = new UpperBandMatrix(nr,bm->BandWidth().upper); break; case Valid+Lower+Square: REPORT gm = new LowerTriangularMatrix(nr); break; case Valid+Band+Lower+Square: REPORT gm = new LowerBandMatrix(nr,bm->BandWidth().lower); break; case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones+Square: REPORT gm = new IdentityMatrix(nr); break; default: Throw(ProgramException("Invalid matrix type")); } MatrixErrorNoSpace(gm); gm->Protect(); return gm; } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmat2.cpp000066400000000000000000000451201352751253100200710ustar00rootroot00000000000000//$$ newmat2.cpp Matrix row and column operations // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,2); ++ExeCount; } #else #define REPORT {} #endif //#define MONITOR(what,storage,store) { cout << what << " " << storage << " at " << (long)store << "\n"; } #define MONITOR(what,store,storage) {} /************************** Matrix Row/Col functions ************************/ void MatrixRowCol::Add(const MatrixRowCol& mrc) { // THIS += mrc REPORT int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; if (f < skip) f = skip; if (l > lx) l = lx; l -= f; if (l<=0) return; Real* elx=data+(f-skip); Real* el=mrc.data+(f-mrc.skip); while (l--) *elx++ += *el++; } void MatrixRowCol::AddScaled(const MatrixRowCol& mrc, Real x) { REPORT // THIS += (mrc * x) int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; if (f < skip) f = skip; if (l > lx) l = lx; l -= f; if (l<=0) return; Real* elx=data+(f-skip); Real* el=mrc.data+(f-mrc.skip); while (l--) *elx++ += *el++ * x; } void MatrixRowCol::Sub(const MatrixRowCol& mrc) { REPORT // THIS -= mrc int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; if (f < skip) f = skip; if (l > lx) l = lx; l -= f; if (l<=0) return; Real* elx=data+(f-skip); Real* el=mrc.data+(f-mrc.skip); while (l--) *elx++ -= *el++; } void MatrixRowCol::Inject(const MatrixRowCol& mrc) // copy stored elements only { REPORT int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; if (f < skip) f = skip; if (l > lx) l = lx; l -= f; if (l<=0) return; Real* elx=data+(f-skip); Real* ely=mrc.data+(f-mrc.skip); while (l--) *elx++ = *ely++; } Real DotProd(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) { REPORT // not accessed int f = mrc1.skip; int f2 = mrc2.skip; int l = f + mrc1.storage; int l2 = f2 + mrc2.storage; if (f < f2) f = f2; if (l > l2) l = l2; l -= f; if (l<=0) return 0.0; Real* el1=mrc1.data+(f-mrc1.skip); Real* el2=mrc2.data+(f-mrc2.skip); Real sum = 0.0; while (l--) sum += *el1++ * *el2++; return sum; } void MatrixRowCol::Add(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) { // THIS = mrc1 + mrc2 int f = skip; int l = skip + storage; int f1 = mrc1.skip; int l1 = f1 + mrc1.storage; if (f1l) l1=l; int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; if (f2l) l2=l; Real* el = data + (f-skip); Real* el1 = mrc1.data+(f1-mrc1.skip); Real* el2 = mrc2.data+(f2-mrc2.skip); if (f1l) l1=l; int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; if (f2l) l2=l; Real* el = data + (f-skip); Real* el1 = mrc1.data+(f1-mrc1.skip); Real* el2 = mrc2.data+(f2-mrc2.skip); if (f1 lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = x; l1 = l-f; while (l1--) *elx++ = *ely++ + x; lx -= l; while (lx--) *elx++ = x; } void MatrixRowCol::NegAdd(const MatrixRowCol& mrc1, Real x) { // THIS = x - mrc1 REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = x; l1 = l-f; while (l1--) *elx++ = x - *ely++; lx -= l; while (lx--) *elx++ = x; } void MatrixRowCol::RevSub(const MatrixRowCol& mrc1) { // THIS = mrc - THIS REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) { *elx = - *elx; elx++; } l1 = l-f; while (l1--) { *elx = *ely++ - *elx; elx++; } lx -= l; while (lx--) { *elx = - *elx; elx++; } } void MatrixRowCol::ConCat(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) { // THIS = mrc1 | mrc2 REPORT int f1 = mrc1.skip; int l1 = f1 + mrc1.storage; int lx = skip + storage; if (f1 < skip) { f1 = skip; if (l1 < f1) l1 = f1; } if (l1 > lx) { l1 = lx; if (f1 > lx) f1 = lx; } Real* elx = data; int i = f1-skip; while (i--) *elx++ =0.0; i = l1-f1; if (i) // in case f1 would take ely out of range { Real* ely = mrc1.data+(f1-mrc1.skip); while (i--) *elx++ = *ely++; } int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; i = mrc1.length; int skipx = l1 - i; lx -= i; // addresses rel to second seg, maybe -ve if (f2 < skipx) { f2 = skipx; if (l2 < f2) l2 = f2; } if (l2 > lx) { l2 = lx; if (f2 > lx) f2 = lx; } i = f2-skipx; while (i--) *elx++ = 0.0; i = l2-f2; if (i) // in case f2 would take ely out of range { Real* ely = mrc2.data+(f2-mrc2.skip); while (i--) *elx++ = *ely++; } lx -= l2; while (lx--) *elx++ = 0.0; } void MatrixRowCol::Multiply(const MatrixRowCol& mrc1) // element by element multiply into { REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0; l1 = l-f; while (l1--) *elx++ *= *ely++; lx -= l; while (lx--) *elx++ = 0; } void MatrixRowCol::Multiply(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) // element by element multiply { int f = skip; int l = skip + storage; int f1 = mrc1.skip; int l1 = f1 + mrc1.storage; if (f1l) l1=l; int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; if (f2l) l2=l; Real* el = data + (f-skip); int i; if (f1l2) l1 = l2; if (l1<=f1) { REPORT i = l-f; while (i--) *el++ = 0.0; } // disjoint else { REPORT Real* el1 = mrc1.data+(f1-mrc1.skip); Real* el2 = mrc2.data+(f1-mrc2.skip); i = f1-f ; while (i--) *el++ = 0.0; i = l1-f1; while (i--) *el++ = *el1++ * *el2++; i = l-l1; while (i--) *el++ = 0.0; } } void MatrixRowCol::KP(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) // row for Kronecker product { int f = skip; int s = storage; Real* el = data; int i; i = mrc1.skip * mrc2.length; if (i > f) { i -= f; f = 0; if (i > s) { i = s; s = 0; } else s -= i; while (i--) *el++ = 0.0; if (s == 0) return; } else f -= i; i = mrc1.storage; Real* el1 = mrc1.data; int mrc2_skip = mrc2.skip; int mrc2_storage = mrc2.storage; int mrc2_length = mrc2.length; int mrc2_remain = mrc2_length - mrc2_skip - mrc2_storage; while (i--) { int j; Real* el2 = mrc2.data; Real vel1 = *el1; if (f == 0 && mrc2_length <= s) { j = mrc2_skip; s -= j; while (j--) *el++ = 0.0; j = mrc2_storage; s -= j; while (j--) *el++ = vel1 * *el2++; j = mrc2_remain; s -= j; while (j--) *el++ = 0.0; } else if (f >= mrc2_length) f -= mrc2_length; else { j = mrc2_skip; if (j > f) { j -= f; f = 0; if (j > s) { j = s; s = 0; } else s -= j; while (j--) *el++ = 0.0; } else f -= j; j = mrc2_storage; if (j > f) { j -= f; el2 += f; f = 0; if (j > s) { j = s; s = 0; } else s -= j; while (j--) *el++ = vel1 * *el2++; } else f -= j; j = mrc2_remain; if (j > f) { j -= f; f = 0; if (j > s) { j = s; s = 0; } else s -= j; while (j--) *el++ = 0.0; } else f -= j; } if (s == 0) return; ++el1; } i = (mrc1.length - mrc1.skip - mrc1.storage) * mrc2.length; if (i > f) { i -= f; if (i > s) i = s; while (i--) *el++ = 0.0; } } void MatrixRowCol::Copy(const MatrixRowCol& mrc1) { // THIS = mrc1 REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = 0; if (l-f) ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ = *ely++; lx -= l; while (lx--) *elx++ = 0.0; } void MatrixRowCol::CopyCheck(const MatrixRowCol& mrc1) // Throw an exception if this would lead to a loss of data { REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip || l > lx) Throw(ProgramException("Illegal Conversion")); Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ = *ely++; lx -= l; while (lx--) *elx++ = 0.0; } void MatrixRowCol::Check(const MatrixRowCol& mrc1) // Throw an exception if +=, -=, copy etc would lead to a loss of data { REPORT int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip || l > lx) Throw(ProgramException("Illegal Conversion")); } void MatrixRowCol::Check() // Throw an exception if +=, -= of constant would lead to a loss of data // that is: check full row is present // may not be appropriate for symmetric matrices { REPORT if (skip!=0 || storage!=length) Throw(ProgramException("Illegal Conversion")); } void MatrixRowCol::Negate(const MatrixRowCol& mrc1) { // THIS = -mrc1 REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ = - *ely++; lx -= l; while (lx--) *elx++ = 0.0; } void MatrixRowCol::Multiply(const MatrixRowCol& mrc1, Real s) { // THIS = mrc1 * s REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ = *ely++ * s; lx -= l; while (lx--) *elx++ = 0.0; } void DiagonalMatrix::Solver(MatrixColX& mrc, const MatrixColX& mrc1) { // mrc = mrc / mrc1 (elementwise) REPORT int f = mrc1.skip; int f0 = mrc.skip; int l = f + mrc1.storage; int lx = f0 + mrc.storage; if (f < f0) { f = f0; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = mrc.data; Real* eld = store+f; int l1 = f-f0; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ /= *eld++; lx -= l; while (lx--) *elx++ = 0.0; // Solver makes sure input and output point to same memory } void IdentityMatrix::Solver(MatrixColX& mrc, const MatrixColX& mrc1) { // mrc = mrc / mrc1 (elementwise) REPORT int f = mrc1.skip; int f0 = mrc.skip; int l = f + mrc1.storage; int lx = f0 + mrc.storage; if (f < f0) { f = f0; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = mrc.data; Real eldv = *store; int l1 = f-f0; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ /= eldv; lx -= l; while (lx--) *elx++ = 0.0; // Solver makes sure input and output point to same memory } void MatrixRowCol::Copy(const Real*& r) { // THIS = *r REPORT Real* elx = data; const Real* ely = r+skip; r += length; int l = storage; while (l--) *elx++ = *ely++; } void MatrixRowCol::Copy(const int*& r) { // THIS = *r REPORT Real* elx = data; const int* ely = r+skip; r += length; int l = storage; while (l--) *elx++ = *ely++; } void MatrixRowCol::Copy(Real r) { // THIS = r REPORT Real* elx = data; int l = storage; while (l--) *elx++ = r; } void MatrixRowCol::Zero() { // THIS = 0 REPORT Real* elx = data; int l = storage; while (l--) *elx++ = 0; } void MatrixRowCol::Multiply(Real r) { // THIS *= r REPORT Real* elx = data; int l = storage; while (l--) *elx++ *= r; } void MatrixRowCol::Add(Real r) { // THIS += r REPORT Real* elx = data; int l = storage; while (l--) *elx++ += r; } Real MatrixRowCol::SumAbsoluteValue() { REPORT Real sum = 0.0; Real* elx = data; int l = storage; while (l--) sum += std::fabs(*elx++); return sum; } // max absolute value of r and elements of row/col // we use <= or >= in all of these so we are sure of getting // r reset at least once. Real MatrixRowCol::MaximumAbsoluteValue1(Real r, int& i) { REPORT Real* elx = data; int l = storage; int li = -1; while (l--) { Real f = std::fabs(*elx++); if (r <= f) { r = f; li = l; } } i = (li >= 0) ? storage - li + skip : 0; return r; } // min absolute value of r and elements of row/col Real MatrixRowCol::MinimumAbsoluteValue1(Real r, int& i) { REPORT Real* elx = data; int l = storage; int li = -1; while (l--) { Real f = std::fabs(*elx++); if (r >= f) { r = f; li = l; } } i = (li >= 0) ? storage - li + skip : 0; return r; } // max value of r and elements of row/col Real MatrixRowCol::Maximum1(Real r, int& i) { REPORT Real* elx = data; int l = storage; int li = -1; while (l--) { Real f = *elx++; if (r <= f) { r = f; li = l; } } i = (li >= 0) ? storage - li + skip : 0; return r; } // min value of r and elements of row/col Real MatrixRowCol::Minimum1(Real r, int& i) { REPORT Real* elx = data; int l = storage; int li = -1; while (l--) { Real f = *elx++; if (r >= f) { r = f; li = l; } } i = (li >= 0) ? storage - li + skip : 0; return r; } Real MatrixRowCol::Sum() { REPORT Real sum = 0.0; Real* elx = data; int l = storage; while (l--) sum += *elx++; return sum; } void MatrixRowCol::SubRowCol(MatrixRowCol& mrc, int skip1, int l1) const { mrc.length = l1; int d = skip - skip1; if (d<0) { mrc.skip = 0; mrc.data = data - d; } else { mrc.skip = d; mrc.data = data; } d = skip + storage - skip1; d = ((l1 < d) ? l1 : d) - mrc.skip; mrc.storage = (d < 0) ? 0 : d; mrc.cw = 0; } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmat3.cpp000066400000000000000000000576011352751253100201010ustar00rootroot00000000000000//$$ newmat3.cpp Matrix get and restore rows and columns // Copyright (C) 1991,2,3,4: R B Davies //#define WANT_STREAM #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,3); ++ExeCount; } #else #define REPORT {} #endif //#define MONITOR(what,storage,store) // { cout << what << " " << storage << " at " << (long)store << "\n"; } #define MONITOR(what,store,storage) {} // Control bits codes for GetRow, GetCol, RestoreRow, RestoreCol // // LoadOnEntry: // Load data into MatrixRow or Col dummy array under GetRow or GetCol // StoreOnExit: // Restore data to original matrix under RestoreRow or RestoreCol // DirectPart: // Load or restore only part directly stored; must be set with StoreOnExit // Still have decide how to handle this with symmetric // StoreHere: // used in columns only - store data at supplied storage address; // used for GetCol, NextCol & RestoreCol. No need to fill out zeros // HaveStore: // dummy array has been assigned (internal use only). // For symmetric matrices, treat columns as rows unless StoreHere is set; // then stick to columns as this will give better performance for doing // inverses // How components are used: // Use rows wherever possible in preference to columns // Columns without StoreHere are used in in-exact transpose, sum column, // multiply a column vector, and maybe in future access to column, // additional multiply functions, add transpose // Columns with StoreHere are used in exact transpose (not symmetric matrices // or vectors, load only) // Columns with MatrixColX (Store to full column) are used in inverse and solve // Functions required for each matrix class // GetRow(MatrixRowCol& mrc) // GetCol(MatrixRowCol& mrc) // GetCol(MatrixColX& mrc) // RestoreRow(MatrixRowCol& mrc) // RestoreCol(MatrixRowCol& mrc) // RestoreCol(MatrixColX& mrc) // NextRow(MatrixRowCol& mrc) // NextCol(MatrixRowCol& mrc) // NextCol(MatrixColX& mrc) // The Restore routines assume StoreOnExit has already been checked // Defaults for the Next routines are given below // Assume cannot have both !DirectPart && StoreHere for MatrixRowCol routines // Default NextRow and NextCol: // will work as a default but need to override NextRow for efficiency void GeneralMatrix::NextRow(MatrixRowCol& mrc) { REPORT if (+(mrc.cw*StoreOnExit)) { REPORT this->RestoreRow(mrc); } mrc.rowcol++; if (mrc.rowcolGetRow(mrc); } else { REPORT mrc.cw -= StoreOnExit; } } void GeneralMatrix::NextCol(MatrixRowCol& mrc) { REPORT // 423 if (+(mrc.cw*StoreOnExit)) { REPORT this->RestoreCol(mrc); } mrc.rowcol++; if (mrc.rowcolGetCol(mrc); } else { REPORT mrc.cw -= StoreOnExit; } } void GeneralMatrix::NextCol(MatrixColX& mrc) { REPORT // 423 if (+(mrc.cw*StoreOnExit)) { REPORT this->RestoreCol(mrc); } mrc.rowcol++; if (mrc.rowcolGetCol(mrc); } else { REPORT mrc.cw -= StoreOnExit; } } // routines for matrix void Matrix::GetRow(MatrixRowCol& mrc) { REPORT mrc.skip=0; mrc.storage=mrc.length=ncols; mrc.data=store+mrc.rowcol*ncols; } void Matrix::GetCol(MatrixRowCol& mrc) { REPORT mrc.skip=0; mrc.storage=mrc.length=nrows; if ( ncols==1 && !(mrc.cw*StoreHere) ) // ColumnVector { REPORT mrc.data=store; } else { Real* ColCopy; if ( !(mrc.cw*(HaveStore+StoreHere)) ) { REPORT ColCopy = new Real [nrows]; MatrixErrorNoSpace(ColCopy); MONITOR_REAL_NEW("Make (MatGetCol)",nrows,ColCopy) mrc.data = ColCopy; mrc.cw += HaveStore; } else { REPORT ColCopy = mrc.data; } if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+mrc.rowcol; int i=nrows; //while (i--) { *ColCopy++ = *Mstore; Mstore+=ncols; } if (i) for (;;) { *ColCopy++ = *Mstore; if (!(--i)) break; Mstore+=ncols; } } } } void Matrix::GetCol(MatrixColX& mrc) { REPORT mrc.skip=0; mrc.storage=nrows; mrc.length=nrows; if (+(mrc.cw*LoadOnEntry)) { REPORT Real* ColCopy = mrc.data; Real* Mstore = store+mrc.rowcol; int i=nrows; //while (i--) { *ColCopy++ = *Mstore; Mstore+=ncols; } if (i) for (;;) { *ColCopy++ = *Mstore; if (!(--i)) break; Mstore+=ncols; } } } void Matrix::RestoreCol(MatrixRowCol& mrc) { // always check StoreOnExit before calling RestoreCol REPORT // 429 if (+(mrc.cw*HaveStore)) { REPORT // 426 Real* Mstore = store+mrc.rowcol; int i=nrows; Real* Cstore = mrc.data; // while (i--) { *Mstore = *Cstore++; Mstore+=ncols; } if (i) for (;;) { *Mstore = *Cstore++; if (!(--i)) break; Mstore+=ncols; } } } void Matrix::RestoreCol(MatrixColX& mrc) { REPORT Real* Mstore = store+mrc.rowcol; int i=nrows; Real* Cstore = mrc.data; // while (i--) { *Mstore = *Cstore++; Mstore+=ncols; } if (i) for (;;) { *Mstore = *Cstore++; if (!(--i)) break; Mstore+=ncols; } } void Matrix::NextRow(MatrixRowCol& mrc) { REPORT mrc.IncrMat(); } // 1808 void Matrix::NextCol(MatrixRowCol& mrc) { REPORT // 632 if (+(mrc.cw*StoreOnExit)) { REPORT RestoreCol(mrc); } mrc.rowcol++; if (mrc.rowcol= LoadOnEntry) { REPORT *(mrc.data) = *(store+mrc.rowcol); } } void RowVector::NextCol(MatrixRowCol& mrc) { REPORT mrc.rowcol++; mrc.data++; } void RowVector::NextCol(MatrixColX& mrc) { if (+(mrc.cw*StoreOnExit)) { REPORT *(store+mrc.rowcol)=*(mrc.data); } mrc.rowcol++; if (mrc.rowcol < ncols) { if (+(mrc.cw*LoadOnEntry)) { REPORT *(mrc.data)=*(store+mrc.rowcol); } } else { REPORT mrc.cw -= StoreOnExit; } } void RowVector::RestoreCol(MatrixColX& mrc) { REPORT *(store+mrc.rowcol)=*(mrc.data); } // not accessed // routines for band matrices void BandMatrix::GetRow(MatrixRowCol& mrc) { REPORT int r = mrc.rowcol; int w = lower+1+upper; mrc.length=ncols; int s = r-lower; if (s<0) { mrc.data = store+(r*w-s); w += s; s = 0; } else mrc.data = store+r*w; mrc.skip = s; s += w-ncols; if (s>0) w -= s; mrc.storage = w; } // should make special versions of this for upper and lower band matrices void BandMatrix::NextRow(MatrixRowCol& mrc) { REPORT int r = ++mrc.rowcol; if (r<=lower) { mrc.storage++; mrc.data += lower+upper; } else { mrc.skip++; mrc.data += lower+upper+1; } if (r>=ncols-upper) mrc.storage--; } void BandMatrix::GetCol(MatrixRowCol& mrc) { REPORT int c = mrc.rowcol; int n = lower+upper; int w = n+1; mrc.length=nrows; Real* ColCopy; int b; int s = c-upper; if (s<=0) { w += s; s = 0; b = c+lower; } else b = s*w+n; mrc.skip = s; s += w-nrows; if (s>0) w -= s; mrc.storage = w; if ( +(mrc.cw*(StoreHere+HaveStore)) ) { REPORT ColCopy = mrc.data; } else { REPORT ColCopy = new Real [n+1]; MatrixErrorNoSpace(ColCopy); MONITOR_REAL_NEW("Make (BMGetCol)",n+1,ColCopy) mrc.cw += HaveStore; mrc.data = ColCopy; } if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+b; // while (w--) { *ColCopy++ = *Mstore; Mstore+=n; } if (w) for (;;) { *ColCopy++ = *Mstore; if (!(--w)) break; Mstore+=n; } } } void BandMatrix::GetCol(MatrixColX& mrc) { REPORT int c = mrc.rowcol; int n = lower+upper; int w = n+1; mrc.length=nrows; int b; int s = c-upper; if (s<=0) { w += s; s = 0; b = c+lower; } else b = s*w+n; mrc.skip = s; s += w-nrows; if (s>0) w -= s; mrc.storage = w; mrc.data = mrc.store+mrc.skip; if (+(mrc.cw*LoadOnEntry)) { REPORT Real* ColCopy = mrc.data; Real* Mstore = store+b; // while (w--) { *ColCopy++ = *Mstore; Mstore+=n; } if (w) for (;;) { *ColCopy++ = *Mstore; if (!(--w)) break; Mstore+=n; } } } void BandMatrix::RestoreCol(MatrixRowCol& mrc) { REPORT int c = mrc.rowcol; int n = lower+upper; int s = c-upper; Real* Mstore = store + ((s<=0) ? c+lower : s*n+s+n); Real* Cstore = mrc.data; int w = mrc.storage; // while (w--) { *Mstore = *Cstore++; Mstore += n; } if (w) for (;;) { *Mstore = *Cstore++; if (!(--w)) break; Mstore += n; } } // routines for symmetric band matrix void SymmetricBandMatrix::GetRow(MatrixRowCol& mrc) { REPORT int r=mrc.rowcol; int s = r-lower; int w1 = lower+1; int o = r*w1; mrc.length = ncols; if (s<0) { w1 += s; o -= s; s = 0; } mrc.skip = s; if (+(mrc.cw*DirectPart)) { REPORT mrc.data = store+o; mrc.storage = w1; } else { // do not allow StoreOnExit and !DirectPart if (+(mrc.cw*StoreOnExit)) Throw(InternalException("SymmetricBandMatrix::GetRow(MatrixRowCol&)")); int w = w1+lower; s += w-ncols; Real* RowCopy; if (s>0) w -= s; mrc.storage = w; int w2 = w-w1; if (!(mrc.cw*HaveStore)) { REPORT RowCopy = new Real [2*lower+1]; MatrixErrorNoSpace(RowCopy); MONITOR_REAL_NEW("Make (SmBGetRow)",2*lower+1,RowCopy) mrc.cw += HaveStore; mrc.data = RowCopy; } else { REPORT RowCopy = mrc.data; } if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+o; while (w1--) *RowCopy++ = *Mstore++; Mstore--; while (w2--) { Mstore += lower; *RowCopy++ = *Mstore; } } } } void SymmetricBandMatrix::GetCol(MatrixRowCol& mrc) { // do not allow StoreHere if (+(mrc.cw*StoreHere)) Throw(InternalException("SymmetricBandMatrix::GetCol(MatrixRowCol&)")); int c=mrc.rowcol; int w1 = lower+1; mrc.length=nrows; REPORT int s = c-lower; int o = c*w1; if (s<0) { w1 += s; o -= s; s = 0; } mrc.skip = s; if (+(mrc.cw*DirectPart)) { REPORT mrc.data = store+o; mrc.storage = w1; } else { // do not allow StoreOnExit and !DirectPart if (+(mrc.cw*StoreOnExit)) Throw(InternalException("SymmetricBandMatrix::GetCol(MatrixRowCol&)")); int w = w1+lower; s += w-ncols; Real* ColCopy; if (s>0) w -= s; mrc.storage = w; int w2 = w-w1; if ( +(mrc.cw*HaveStore) ) { REPORT ColCopy = mrc.data; } else { REPORT ColCopy = new Real [2*lower+1]; MatrixErrorNoSpace(ColCopy); MONITOR_REAL_NEW("Make (SmBGetCol)",2*lower+1,ColCopy) mrc.cw += HaveStore; mrc.data = ColCopy; } if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+o; while (w1--) *ColCopy++ = *Mstore++; Mstore--; while (w2--) { Mstore += lower; *ColCopy++ = *Mstore; } } } } void SymmetricBandMatrix::GetCol(MatrixColX& mrc) { int c=mrc.rowcol; int w1 = lower+1; mrc.length=nrows; if (+(mrc.cw*DirectPart)) { REPORT int b = c*w1+lower; mrc.skip = c; c += w1-nrows; w1 -= c; mrc.storage = w1; Real* ColCopy = mrc.data = mrc.store+mrc.skip; if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+b; // while (w1--) { *ColCopy++ = *Mstore; Mstore += lower; } if (w1) for (;;) { *ColCopy++ = *Mstore; if (!(--w1)) break; Mstore += lower; } } } else { REPORT // do not allow StoreOnExit and !DirectPart if (+(mrc.cw*StoreOnExit)) Throw(InternalException("SymmetricBandMatrix::GetCol(MatrixColX&)")); int s = c-lower; int o = c*w1; if (s<0) { w1 += s; o -= s; s = 0; } mrc.skip = s; int w = w1+lower; s += w-ncols; if (s>0) w -= s; mrc.storage = w; int w2 = w-w1; Real* ColCopy = mrc.data = mrc.store+mrc.skip; if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+o; while (w1--) *ColCopy++ = *Mstore++; Mstore--; while (w2--) { Mstore += lower; *ColCopy++ = *Mstore; } } } } void SymmetricBandMatrix::RestoreCol(MatrixColX& mrc) { REPORT int c = mrc.rowcol; Real* Mstore = store + c*lower+c+lower; Real* Cstore = mrc.data; int w = mrc.storage; // while (w--) { *Mstore = *Cstore++; Mstore += lower; } if (w) for (;;) { *Mstore = *Cstore++; if (!(--w)) break; Mstore += lower; } } // routines for identity matrix void IdentityMatrix::GetRow(MatrixRowCol& mrc) { REPORT mrc.skip=mrc.rowcol; mrc.storage=1; mrc.data=store; mrc.length=ncols; } void IdentityMatrix::GetCol(MatrixRowCol& mrc) { REPORT mrc.skip=mrc.rowcol; mrc.storage=1; mrc.length=nrows; if (+(mrc.cw*StoreHere)) // should not happen Throw(InternalException("IdentityMatrix::GetCol(MatrixRowCol&)")); else { REPORT mrc.data=store; } } void IdentityMatrix::GetCol(MatrixColX& mrc) { REPORT mrc.skip=mrc.rowcol; mrc.storage=1; mrc.length=nrows; mrc.data = mrc.store+mrc.skip; *(mrc.data)=*store; } void IdentityMatrix::NextRow(MatrixRowCol& mrc) { REPORT mrc.IncrId(); } void IdentityMatrix::NextCol(MatrixRowCol& mrc) { REPORT mrc.IncrId(); } void IdentityMatrix::NextCol(MatrixColX& mrc) { REPORT if (+(mrc.cw*StoreOnExit)) { REPORT *store=*(mrc.data); } mrc.IncrDiag(); // must increase mrc.data so need IncrDiag int t1 = +(mrc.cw*LoadOnEntry); if (t1 && mrc.rowcol < ncols) { REPORT *(mrc.data)=*store; } } // *************************** destructors ******************************* MatrixRowCol::~MatrixRowCol() { if (+(cw*HaveStore)) { MONITOR_REAL_DELETE("Free (RowCol)",-1,data) // do not know length delete [] data; } } MatrixRow::~MatrixRow() { if (+(cw*StoreOnExit)) gm->RestoreRow(*this); } MatrixCol::~MatrixCol() { if (+(cw*StoreOnExit)) gm->RestoreCol(*this); } MatrixColX::~MatrixColX() { if (+(cw*StoreOnExit)) gm->RestoreCol(*this); } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmat4.cpp000066400000000000000000000634121352751253100200770ustar00rootroot00000000000000//$$ newmat4.cpp Constructors, ReSize, basic utilities // Copyright (C) 1991,2,3,4,8,9: R B Davies #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,4); ++ExeCount; } #else #define REPORT {} #endif #define DO_SEARCH // search for LHS of = in RHS // ************************* general utilities *************************/ static int tristore(int n) // elements in triangular matrix { return (n*(n+1))/2; } // **************************** constructors ***************************/ GeneralMatrix::GeneralMatrix() { store=0; storage=0; nrows=0; ncols=0; tag=-1; } GeneralMatrix::GeneralMatrix(ArrayLengthSpecifier s) { REPORT storage=s.Value(); tag=-1; if (storage) { store = new Real [storage]; MatrixErrorNoSpace(store); MONITOR_REAL_NEW("Make (GenMatrix)",storage,store) } else store = 0; } Matrix::Matrix(int m, int n) : GeneralMatrix(m*n) { REPORT nrows=m; ncols=n; } SquareMatrix::SquareMatrix(ArrayLengthSpecifier n) : Matrix(n.Value(),n.Value()) { REPORT } SymmetricMatrix::SymmetricMatrix(ArrayLengthSpecifier n) : GeneralMatrix(tristore(n.Value())) { REPORT nrows=n.Value(); ncols=n.Value(); } UpperTriangularMatrix::UpperTriangularMatrix(ArrayLengthSpecifier n) : GeneralMatrix(tristore(n.Value())) { REPORT nrows=n.Value(); ncols=n.Value(); } LowerTriangularMatrix::LowerTriangularMatrix(ArrayLengthSpecifier n) : GeneralMatrix(tristore(n.Value())) { REPORT nrows=n.Value(); ncols=n.Value(); } DiagonalMatrix::DiagonalMatrix(ArrayLengthSpecifier m) : GeneralMatrix(m) { REPORT nrows=m.Value(); ncols=m.Value(); } Matrix::Matrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Rt); GetMatrix(gmx); } SquareMatrix::SquareMatrix(const BaseMatrix& M) : Matrix(M) { REPORT if (ncols != nrows) { Tracer tr("SquareMatrix"); Throw(NotSquareException(*this)); } } SquareMatrix::SquareMatrix(const Matrix& gm) { REPORT if (gm.ncols != gm.nrows) { Tracer tr("SquareMatrix(Matrix)"); Throw(NotSquareException(gm)); } GetMatrix(&gm); } RowVector::RowVector(const BaseMatrix& M) : Matrix(M) { REPORT if (nrows!=1) { Tracer tr("RowVector"); Throw(VectorException(*this)); } } ColumnVector::ColumnVector(const BaseMatrix& M) : Matrix(M) { REPORT if (ncols!=1) { Tracer tr("ColumnVector"); Throw(VectorException(*this)); } } SymmetricMatrix::SymmetricMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Sm); GetMatrix(gmx); } UpperTriangularMatrix::UpperTriangularMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::UT); GetMatrix(gmx); } LowerTriangularMatrix::LowerTriangularMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::LT); GetMatrix(gmx); } DiagonalMatrix::DiagonalMatrix(const BaseMatrix& M) { REPORT //CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Dg); GetMatrix(gmx); } IdentityMatrix::IdentityMatrix(const BaseMatrix& M) { REPORT //CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Id); GetMatrix(gmx); } GeneralMatrix::~GeneralMatrix() { if (store) { MONITOR_REAL_DELETE("Free (GenMatrix)",storage,store) delete [] store; } } CroutMatrix::CroutMatrix(const BaseMatrix& m) { REPORT Tracer tr("CroutMatrix"); indx = 0; // in case of exception at next line GeneralMatrix* gm = ((BaseMatrix&)m).Evaluate(MatrixType::Rt); GetMatrix(gm); if (nrows!=ncols) { CleanUp(); Throw(NotSquareException(*gm)); } d=true; sing=false; indx=new int [nrows]; MatrixErrorNoSpace(indx); MONITOR_INT_NEW("Index (CroutMat)",nrows,indx) ludcmp(); } CroutMatrix::~CroutMatrix() { MONITOR_INT_DELETE("Index (CroutMat)",nrows,indx) delete [] indx; } //ReturnMatrix::ReturnMatrix(GeneralMatrix& gmx) //{ // REPORT // gm = gmx.Image(); gm->ReleaseAndDelete(); //} GeneralMatrix::operator ReturnMatrix() const { REPORT GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); return ReturnMatrix(gm); } ReturnMatrix GeneralMatrix::ForReturn() const { REPORT GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); return ReturnMatrix(gm); } // ************************** ReSize matrices ***************************/ void GeneralMatrix::ReSize(int nr, int nc, int s) { REPORT if (store) { MONITOR_REAL_DELETE("Free (ReDimensi)",storage,store) delete [] store; } storage=s; nrows=nr; ncols=nc; tag=-1; if (s) { store = new Real [storage]; MatrixErrorNoSpace(store); MONITOR_REAL_NEW("Make (ReDimensi)",storage,store) } else store = 0; } void Matrix::ReSize(int nr, int nc) { REPORT GeneralMatrix::ReSize(nr,nc,nr*nc); } void SquareMatrix::ReSize(int n) { REPORT GeneralMatrix::ReSize(n,n,n*n); } void SquareMatrix::ReSize(int nr, int nc) { REPORT Tracer tr("SquareMatrix::ReSize"); if (nc != nr) Throw(NotSquareException(*this)); GeneralMatrix::ReSize(nr,nc,nr*nc); } void SymmetricMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,tristore(nr)); } void UpperTriangularMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,tristore(nr)); } void LowerTriangularMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,tristore(nr)); } void DiagonalMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,nr); } void RowVector::ReSize(int nc) { REPORT GeneralMatrix::ReSize(1,nc,nc); } void ColumnVector::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,1,nr); } void RowVector::ReSize(int nr, int nc) { Tracer tr("RowVector::ReSize"); if (nr != 1) Throw(VectorException(*this)); REPORT GeneralMatrix::ReSize(1,nc,nc); } void ColumnVector::ReSize(int nr, int nc) { Tracer tr("ColumnVector::ReSize"); if (nc != 1) Throw(VectorException(*this)); REPORT GeneralMatrix::ReSize(nr,1,nr); } void IdentityMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,1); *store = 1; } void Matrix::ReSize(const GeneralMatrix& A) { REPORT ReSize(A.Nrows(), A.Ncols()); } void SquareMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("SquareMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void nricMatrix::ReSize(const GeneralMatrix& A) { REPORT ReSize(A.Nrows(), A.Ncols()); } void ColumnVector::ReSize(const GeneralMatrix& A) { REPORT ReSize(A.Nrows(), A.Ncols()); } void RowVector::ReSize(const GeneralMatrix& A) { REPORT ReSize(A.Nrows(), A.Ncols()); } void SymmetricMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("SymmetricMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void DiagonalMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("DiagonalMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void UpperTriangularMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("UpperTriangularMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void LowerTriangularMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("LowerTriangularMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void IdentityMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("IdentityMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void GeneralMatrix::ReSize(const GeneralMatrix&) { REPORT Tracer tr("GeneralMatrix::ReSize(GM)"); Throw(NotDefinedException("ReSize", "this type of matrix")); } void GeneralMatrix::ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix&) { REPORT ReSize(A); } void GeneralMatrix::ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix&) { REPORT ReSize(A); } // ************************* SameStorageType ******************************/ // SameStorageType checks A and B have same storage type including bandwidth // It does not check same dimensions since we assume this is already done bool GeneralMatrix::SameStorageType(const GeneralMatrix& A) const { REPORT return Type() == A.Type(); } // ******************* manipulate types, storage **************************/ int GeneralMatrix::search(const BaseMatrix* s) const { REPORT return (s==this) ? 1 : 0; } int GenericMatrix::search(const BaseMatrix* s) const { REPORT return gm->search(s); } int MultipliedMatrix::search(const BaseMatrix* s) const { REPORT return bm1->search(s) + bm2->search(s); } int ShiftedMatrix::search(const BaseMatrix* s) const { REPORT return bm->search(s); } int NegatedMatrix::search(const BaseMatrix* s) const { REPORT return bm->search(s); } int ReturnMatrix::search(const BaseMatrix* s) const { REPORT return (s==gm) ? 1 : 0; } MatrixType Matrix::Type() const { return MatrixType::Rt; } MatrixType SquareMatrix::Type() const { return MatrixType::Sq; } MatrixType SymmetricMatrix::Type() const { return MatrixType::Sm; } MatrixType UpperTriangularMatrix::Type() const { return MatrixType::UT; } MatrixType LowerTriangularMatrix::Type() const { return MatrixType::LT; } MatrixType DiagonalMatrix::Type() const { return MatrixType::Dg; } MatrixType RowVector::Type() const { return MatrixType::RV; } MatrixType ColumnVector::Type() const { return MatrixType::CV; } MatrixType CroutMatrix::Type() const { return MatrixType::Ct; } MatrixType BandMatrix::Type() const { return MatrixType::BM; } MatrixType UpperBandMatrix::Type() const { return MatrixType::UB; } MatrixType LowerBandMatrix::Type() const { return MatrixType::LB; } MatrixType SymmetricBandMatrix::Type() const { return MatrixType::SB; } MatrixType IdentityMatrix::Type() const { return MatrixType::Id; } MatrixBandWidth BaseMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth DiagonalMatrix::BandWidth() const { REPORT return 0; } MatrixBandWidth IdentityMatrix::BandWidth() const { REPORT return 0; } MatrixBandWidth UpperTriangularMatrix::BandWidth() const { REPORT return MatrixBandWidth(0,-1); } MatrixBandWidth LowerTriangularMatrix::BandWidth() const { REPORT return MatrixBandWidth(-1,0); } MatrixBandWidth BandMatrix::BandWidth() const { REPORT return MatrixBandWidth(lower,upper); } MatrixBandWidth GenericMatrix::BandWidth()const { REPORT return gm->BandWidth(); } MatrixBandWidth AddedMatrix::BandWidth() const { REPORT return gm1->BandWidth() + gm2->BandWidth(); } MatrixBandWidth SPMatrix::BandWidth() const { REPORT return gm1->BandWidth().minimum(gm2->BandWidth()); } MatrixBandWidth KPMatrix::BandWidth() const { int lower, upper; MatrixBandWidth bw1 = gm1->BandWidth(), bw2 = gm2->BandWidth(); if (bw1.Lower() < 0) { if (bw2.Lower() < 0) { REPORT lower = -1; } else { REPORT lower = bw2.Lower() + (gm1->Nrows() - 1) * gm2->Nrows(); } } else { if (bw2.Lower() < 0) { REPORT lower = (1 + bw1.Lower()) * gm2->Nrows() - 1; } else { REPORT lower = bw2.Lower() + bw1.Lower() * gm2->Nrows(); } } if (bw1.Upper() < 0) { if (bw2.Upper() < 0) { REPORT upper = -1; } else { REPORT upper = bw2.Upper() + (gm1->Nrows() - 1) * gm2->Nrows(); } } else { if (bw2.Upper() < 0) { REPORT upper = (1 + bw1.Upper()) * gm2->Nrows() - 1; } else { REPORT upper = bw2.Upper() + bw1.Upper() * gm2->Nrows(); } } return MatrixBandWidth(lower, upper); } MatrixBandWidth MultipliedMatrix::BandWidth() const { REPORT return gm1->BandWidth() * gm2->BandWidth(); } MatrixBandWidth ConcatenatedMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth SolvedMatrix::BandWidth() const { if (+gm1->Type() & MatrixType::Diagonal) { REPORT return gm2->BandWidth(); } else { REPORT return -1; } } MatrixBandWidth ScaledMatrix::BandWidth() const { REPORT return gm->BandWidth(); } MatrixBandWidth NegatedMatrix::BandWidth() const { REPORT return gm->BandWidth(); } MatrixBandWidth TransposedMatrix::BandWidth() const { REPORT return gm->BandWidth().t(); } MatrixBandWidth InvertedMatrix::BandWidth() const { if (+gm->Type() & MatrixType::Diagonal) { REPORT return MatrixBandWidth(0,0); } else { REPORT return -1; } } MatrixBandWidth RowedMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth ColedMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth DiagedMatrix::BandWidth() const { REPORT return 0; } MatrixBandWidth MatedMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth ReturnMatrix::BandWidth() const { REPORT return gm->BandWidth(); } MatrixBandWidth GetSubMatrix::BandWidth() const { if (row_skip==col_skip && row_number==col_number) { REPORT return gm->BandWidth(); } else { REPORT return MatrixBandWidth(-1); } } // ********************** the memory managment tools **********************/ // Rules regarding tDelete, reuse, GetStore, BorrowStore // All matrices processed during expression evaluation must be subject // to exactly one of reuse(), tDelete(), GetStore() or BorrowStore(). // If reuse returns true the matrix must be reused. // GetMatrix(gm) always calls gm->GetStore() // gm->Evaluate obeys rules // bm->Evaluate obeys rules for matrices in bm structure void GeneralMatrix::tDelete() { if (tag<0) { if (tag<-1) { REPORT store = 0; delete this; return; } // borrowed else { REPORT return; } // not a temporary matrix - leave alone } if (tag==1) { if (store) { REPORT MONITOR_REAL_DELETE("Free (tDelete)",storage,store) delete [] store; } MiniCleanUp(); return; // CleanUp } if (tag==0) { REPORT delete this; return; } REPORT tag--; return; } static void BlockCopy(int n, Real* from, Real* to) { REPORT int i = (n >> 3); while (i--) { *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; } i = n & 7; while (i--) *to++ = *from++; } bool GeneralMatrix::reuse() { if (tag < -1) // borrowed storage { if (storage) { REPORT Real* s = new Real [storage]; MatrixErrorNoSpace(s); MONITOR_REAL_NEW("Make (reuse)",storage,s) BlockCopy(storage, store, s); store = s; } else { REPORT MiniCleanUp(); } // CleanUp tag = 0; return true; } if (tag < 0 ) { REPORT return false; } if (tag <= 1 ) { REPORT return true; } REPORT tag--; return false; } Real* GeneralMatrix::GetStore() { if (tag<0 || tag>1) { Real* s; if (storage) { s = new Real [storage]; MatrixErrorNoSpace(s); MONITOR_REAL_NEW("Make (GetStore)",storage,s) BlockCopy(storage, store, s); } else s = 0; if (tag > 1) { REPORT tag--; } else if (tag < -1) { REPORT store = 0; delete this; } // borrowed store else { REPORT } return s; } Real* s = store; // CleanUp - done later if (tag==0) { REPORT store = 0; delete this; } else { REPORT MiniCleanUp(); } return s; } void GeneralMatrix::GetMatrix(const GeneralMatrix* gmx) { REPORT tag=-1; nrows=gmx->Nrows(); ncols=gmx->Ncols(); storage=gmx->storage; SetParameters(gmx); store=((GeneralMatrix*)gmx)->GetStore(); } GeneralMatrix* GeneralMatrix::BorrowStore(GeneralMatrix* gmx, MatrixType mt) // Copy storage of *this to storage of *gmx. Then convert to type mt. // If mt == 0 just let *gmx point to storage of *this if tag==-1. { if (!mt) { if (tag == -1) { REPORT gmx->tag = -2; gmx->store = store; } else { REPORT gmx->tag = 0; gmx->store = GetStore(); } } else if (Compare(gmx->Type(),mt)) { REPORT gmx->tag = 0; gmx->store = GetStore(); } else { REPORT gmx->tag = -2; gmx->store = store; gmx = gmx->Evaluate(mt); gmx->tag = 0; tDelete(); } return gmx; } void GeneralMatrix::Eq(const BaseMatrix& X, MatrixType mt) // Count number of references to this in X. // If zero delete storage in this; // otherwise tag this to show when storage can be deleted // evaluate X and copy to this { #ifdef DO_SEARCH int counter=X.search(this); if (counter==0) { REPORT if (store) { MONITOR_REAL_DELETE("Free (operator=)",storage,store) REPORT delete [] store; storage = 0; store = 0; } } else { REPORT Release(counter); } GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(mt); if (gmx!=this) { REPORT GetMatrix(gmx); } else { REPORT } Protect(); #else GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(mt); if (gmx!=this) { REPORT if (store) { MONITOR_REAL_DELETE("Free (operator=)",storage,store) REPORT delete [] store; storage = 0; store = 0; } GetMatrix(gmx); } else { REPORT } Protect(); #endif } // version with no conversion void GeneralMatrix::Eq(const GeneralMatrix& X) { GeneralMatrix* gmx = (GeneralMatrix*)&X; if (gmx!=this) { REPORT if (store) { MONITOR_REAL_DELETE("Free (operator=)",storage,store) REPORT delete [] store; storage = 0; store = 0; } GetMatrix(gmx); } else { REPORT } Protect(); } // version to work with operator<< void GeneralMatrix::Eq(const BaseMatrix& X, MatrixType mt, bool ldok) { REPORT if (ldok) mt.SetDataLossOK(); Eq(X, mt); } void GeneralMatrix::Eq2(const BaseMatrix& X, MatrixType mt) // a cut down version of Eq for use with += etc. // we know BaseMatrix points to two GeneralMatrix objects, // the first being this (may be the same). // we know tag has been set correctly in each. { GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(mt); if (gmx!=this) { REPORT GetMatrix(gmx); } // simplify GetMatrix ? else { REPORT } Protect(); } void GeneralMatrix::Inject(const GeneralMatrix& X) // copy stored values of X; otherwise leave els of *this unchanged { REPORT Tracer tr("Inject"); if (nrows != X.nrows || ncols != X.ncols) Throw(IncompatibleDimensionsException()); MatrixRow mr((GeneralMatrix*)&X, LoadOnEntry); MatrixRow mrx(this, LoadOnEntry+StoreOnExit+DirectPart); int i=nrows; while (i--) { mrx.Inject(mr); mrx.Next(); mr.Next(); } } // ************* checking for data loss during conversion *******************/ bool Compare(const MatrixType& source, MatrixType& destination) { if (!destination) { destination=source; return true; } if (destination==source) return true; if (!destination.DataLossOK && !(destination>=source)) Throw(ProgramException("Illegal Conversion", source, destination)); return false; } // ************* Make a copy of a matrix on the heap *********************/ GeneralMatrix* Matrix::Image() const { REPORT GeneralMatrix* gm = new Matrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* SquareMatrix::Image() const { REPORT GeneralMatrix* gm = new SquareMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* SymmetricMatrix::Image() const { REPORT GeneralMatrix* gm = new SymmetricMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* UpperTriangularMatrix::Image() const { REPORT GeneralMatrix* gm = new UpperTriangularMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* LowerTriangularMatrix::Image() const { REPORT GeneralMatrix* gm = new LowerTriangularMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* DiagonalMatrix::Image() const { REPORT GeneralMatrix* gm = new DiagonalMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* RowVector::Image() const { REPORT GeneralMatrix* gm = new RowVector(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* ColumnVector::Image() const { REPORT GeneralMatrix* gm = new ColumnVector(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* BandMatrix::Image() const { REPORT GeneralMatrix* gm = new BandMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* UpperBandMatrix::Image() const { REPORT GeneralMatrix* gm = new UpperBandMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* LowerBandMatrix::Image() const { REPORT GeneralMatrix* gm = new LowerBandMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* SymmetricBandMatrix::Image() const { REPORT GeneralMatrix* gm = new SymmetricBandMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* nricMatrix::Image() const { REPORT GeneralMatrix* gm = new nricMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* IdentityMatrix::Image() const { REPORT GeneralMatrix* gm = new IdentityMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* GeneralMatrix::Image() const { // bool dummy = true; // if (dummy) // get rid of warning message Throw(InternalException("Cannot apply Image to this matrix type")); return 0; } // *********************** nricMatrix routines *****************************/ void nricMatrix::MakeRowPointer() { REPORT if (nrows > 0) { row_pointer = new Real* [nrows]; MatrixErrorNoSpace(row_pointer); Real* s = Store() - 1; int i = nrows; Real** rp = row_pointer; if (i) for (;;) { *rp++ = s; if (!(--i)) break; s+=ncols; } } else row_pointer = 0; } void nricMatrix::DeleteRowPointer() { REPORT if (nrows) delete [] row_pointer; } void GeneralMatrix::CheckStore() const { REPORT if (!store) Throw(ProgramException("NRIC accessing matrix with unset dimensions")); } // *************************** CleanUp routines *****************************/ void GeneralMatrix::CleanUp() { // set matrix dimensions to zero, delete storage REPORT if (store && storage) { MONITOR_REAL_DELETE("Free (CleanUp) ",storage,store) REPORT delete [] store; } store=0; storage=0; nrows=0; ncols=0; tag = -1; } void nricMatrix::CleanUp() { REPORT DeleteRowPointer(); GeneralMatrix::CleanUp(); } void nricMatrix::MiniCleanUp() { REPORT DeleteRowPointer(); GeneralMatrix::MiniCleanUp(); } void RowVector::CleanUp() { REPORT GeneralMatrix::CleanUp(); nrows=1; } void ColumnVector::CleanUp() { REPORT GeneralMatrix::CleanUp(); ncols=1; } void CroutMatrix::CleanUp() { REPORT if (nrows) delete [] indx; GeneralMatrix::CleanUp(); } void CroutMatrix::MiniCleanUp() { REPORT if (nrows) delete [] indx; GeneralMatrix::MiniCleanUp(); } void BandLUMatrix::CleanUp() { REPORT if (nrows) delete [] indx; if (storage2) delete [] store2; GeneralMatrix::CleanUp(); } void BandLUMatrix::MiniCleanUp() { REPORT if (nrows) delete [] indx; if (storage2) delete [] store2; GeneralMatrix::MiniCleanUp(); } // ************************ simple integer array class *********************** // construct a new array of length xn. Check that xn is non-negative and // that space is available SimpleIntArray::SimpleIntArray(int xn) : n(xn) { if (n < 0) Throw(Logic_error("invalid array length")); else if (n == 0) { REPORT a = 0; } else { REPORT a = new int [n]; if (!a) Throw(Bad_alloc()); } } // destroy an array - return its space to memory SimpleIntArray::~SimpleIntArray() { REPORT if (a) delete [] a; } // access an element of an array; return a "reference" so elements // can be modified. // check index is within range // in this array class the index runs from 0 to n-1 int& SimpleIntArray::operator[](int i) { REPORT if (i < 0 || i >= n) Throw(Logic_error("array index out of range")); return a[i]; } // same thing again but for arrays declared constant so we can't // modify its elements int SimpleIntArray::operator[](int i) const { REPORT if (i < 0 || i >= n) Throw(Logic_error("array index out of range")); return a[i]; } // set all the elements equal to a given value void SimpleIntArray::operator=(int ai) { REPORT for (int i = 0; i < n; i++) a[i] = ai; } // set the elements equal to those of another array. // check the arrays are of the same length void SimpleIntArray::operator=(const SimpleIntArray& b) { REPORT if (b.n != n) Throw(Logic_error("array lengths differ in copy")); for (int i = 0; i < n; i++) a[i] = b.a[i]; } // construct a new array equal to an existing array // check that space is available SimpleIntArray::SimpleIntArray(const SimpleIntArray& b) : n(b.n) { if (n == 0) { REPORT a = 0; } else { REPORT a = new int [n]; if (!a) Throw(Bad_alloc()); for (int i = 0; i < n; i++) a[i] = b.a[i]; } } // change the size of an array; optionally copy data from old array to // new array void SimpleIntArray::ReSize(int n1, bool keep) { if (n1 == n) { REPORT return; } else if (n1 == 0) { REPORT n = 0; delete [] a; a = 0; } else if (n == 0) { REPORT a = new int [n1]; if (!a) Throw(Bad_alloc()); n = n1; } else { int* a1 = a; if (keep) { REPORT a = new int [n1]; if (!a) Throw(Bad_alloc()); if (n > n1) n = n1; for (int i = 0; i < n; i++) a[i] = a1[i]; n = n1; delete [] a1; } else { REPORT n = n1; delete [] a1; a = new int [n]; if (!a) Throw(Bad_alloc()); } } } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmat5.cpp000066400000000000000000000312401352751253100200720ustar00rootroot00000000000000//$$ newmat5.cpp Transpose, evaluate etc // Copyright (C) 1991,2,3,4: R B Davies //#define WANT_STREAM #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,5); ++ExeCount; } #else #define REPORT {} #endif /************************ carry out operations ******************************/ GeneralMatrix* GeneralMatrix::Transpose(TransposedMatrix* tm, MatrixType mt) { GeneralMatrix* gm1; if (Compare(Type().t(),mt)) { REPORT gm1 = mt.New(ncols,nrows,tm); for (int i=0; iReleaseAndDelete(); return gm1; } GeneralMatrix* SymmetricMatrix::Transpose(TransposedMatrix*, MatrixType mt) { REPORT return Evaluate(mt); } GeneralMatrix* DiagonalMatrix::Transpose(TransposedMatrix*, MatrixType mt) { REPORT return Evaluate(mt); } GeneralMatrix* ColumnVector::Transpose(TransposedMatrix*, MatrixType mt) { REPORT GeneralMatrix* gmx = new RowVector; MatrixErrorNoSpace(gmx); gmx->nrows = 1; gmx->ncols = gmx->storage = storage; return BorrowStore(gmx,mt); } GeneralMatrix* RowVector::Transpose(TransposedMatrix*, MatrixType mt) { REPORT GeneralMatrix* gmx = new ColumnVector; MatrixErrorNoSpace(gmx); gmx->ncols = 1; gmx->nrows = gmx->storage = storage; return BorrowStore(gmx,mt); } GeneralMatrix* IdentityMatrix::Transpose(TransposedMatrix*, MatrixType mt) { REPORT return Evaluate(mt); } GeneralMatrix* GeneralMatrix::Evaluate(MatrixType mt) { if (Compare(this->Type(),mt)) { REPORT return this; } REPORT GeneralMatrix* gmx = mt.New(nrows,ncols,this); MatrixRow mr(this, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); int i=nrows; while (i--) { mrx.Copy(mr); mrx.Next(); mr.Next(); } tDelete(); gmx->ReleaseAndDelete(); return gmx; } GeneralMatrix* GenericMatrix::Evaluate(MatrixType mt) { REPORT return gm->Evaluate(mt); } GeneralMatrix* ShiftedMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); int nr=gm->Nrows(); int nc=gm->Ncols(); Compare(gm->Type().AddEqualEl(),mt); if (!(mt==gm->Type())) { REPORT GeneralMatrix* gmx = mt.New(nr,nc,this); MatrixRow mr(gm, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); while (nr--) { mrx.Add(mr,f); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); return gmx; } else if (gm->reuse()) { REPORT gm->Add(f); return gm; } else { REPORT GeneralMatrix* gmy = gm->Type().New(nr,nc,this); gmy->ReleaseAndDelete(); gmy->Add(gm,f); return gmy; } } GeneralMatrix* NegShiftedMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); int nr=gm->Nrows(); int nc=gm->Ncols(); Compare(gm->Type().AddEqualEl(),mt); if (!(mt==gm->Type())) { REPORT GeneralMatrix* gmx = mt.New(nr,nc,this); MatrixRow mr(gm, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); while (nr--) { mrx.NegAdd(mr,f); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); return gmx; } else if (gm->reuse()) { REPORT gm->NegAdd(f); return gm; } else { REPORT GeneralMatrix* gmy = gm->Type().New(nr,nc,this); gmy->ReleaseAndDelete(); gmy->NegAdd(gm,f); return gmy; } } GeneralMatrix* ScaledMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); int nr=gm->Nrows(); int nc=gm->Ncols(); if (Compare(gm->Type(),mt)) { if (gm->reuse()) { REPORT gm->Multiply(f); return gm; } else { REPORT GeneralMatrix* gmx = gm->Type().New(nr,nc,this); gmx->ReleaseAndDelete(); gmx->Multiply(gm,f); return gmx; } } else { REPORT GeneralMatrix* gmx = mt.New(nr,nc,this); MatrixRow mr(gm, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); while (nr--) { mrx.Multiply(mr,f); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); return gmx; } } GeneralMatrix* NegatedMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); int nr=gm->Nrows(); int nc=gm->Ncols(); if (Compare(gm->Type(),mt)) { if (gm->reuse()) { REPORT gm->Negate(); return gm; } else { REPORT GeneralMatrix* gmx = gm->Type().New(nr,nc,this); gmx->ReleaseAndDelete(); gmx->Negate(gm); return gmx; } } else { REPORT GeneralMatrix* gmx = mt.New(nr,nc,this); MatrixRow mr(gm, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); while (nr--) { mrx.Negate(mr); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); return gmx; } } GeneralMatrix* ReversedMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx; if ((gm->Type()).IsBand() && ! (gm->Type()).IsDiagonal()) { gm->tDelete(); Throw(NotDefinedException("Reverse", "band matrices")); } if (gm->reuse()) { REPORT gm->ReverseElements(); gmx = gm; } else { REPORT gmx = gm->Type().New(gm->Nrows(), gm->Ncols(), this); gmx->ReverseElements(gm); gmx->ReleaseAndDelete(); } return gmx->Evaluate(mt); // target matrix is different type? } GeneralMatrix* TransposedMatrix::Evaluate(MatrixType mt) { REPORT gm=((BaseMatrix*&)bm)->Evaluate(); Compare(gm->Type().t(),mt); GeneralMatrix* gmx=gm->Transpose(this, mt); return gmx; } GeneralMatrix* RowedMatrix::Evaluate(MatrixType mt) { gm = ((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx = new RowVector; MatrixErrorNoSpace(gmx); gmx->nrows = 1; gmx->ncols = gmx->storage = gm->storage; return gm->BorrowStore(gmx,mt); } GeneralMatrix* ColedMatrix::Evaluate(MatrixType mt) { gm = ((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx = new ColumnVector; MatrixErrorNoSpace(gmx); gmx->ncols = 1; gmx->nrows = gmx->storage = gm->storage; return gm->BorrowStore(gmx,mt); } GeneralMatrix* DiagedMatrix::Evaluate(MatrixType mt) { gm = ((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx = new DiagonalMatrix; MatrixErrorNoSpace(gmx); gmx->nrows = gmx->ncols = gmx->storage = gm->storage; return gm->BorrowStore(gmx,mt); } GeneralMatrix* MatedMatrix::Evaluate(MatrixType mt) { Tracer tr("MatedMatrix::Evaluate"); gm = ((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx = new Matrix; MatrixErrorNoSpace(gmx); gmx->nrows = nr; gmx->ncols = nc; gmx->storage = gm->storage; if (nr*nc != gmx->storage) Throw(IncompatibleDimensionsException()); return gm->BorrowStore(gmx,mt); } GeneralMatrix* GetSubMatrix::Evaluate(MatrixType mt) { REPORT Tracer tr("SubMatrix(evaluate)"); gm = ((BaseMatrix*&)bm)->Evaluate(); if (row_number < 0) row_number = gm->Nrows(); if (col_number < 0) col_number = gm->Ncols(); if (row_skip+row_number > gm->Nrows() || col_skip+col_number > gm->Ncols()) { gm->tDelete(); Throw(SubMatrixDimensionException()); } if (IsSym) Compare(gm->Type().ssub(), mt); else Compare(gm->Type().sub(), mt); GeneralMatrix* gmx = mt.New(row_number, col_number, this); int i = row_number; MatrixRow mr(gm, LoadOnEntry, row_skip); MatrixRow mrx(gmx, StoreOnExit+DirectPart); MatrixRowCol sub; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub mrx.Copy(sub); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); return gmx; } GeneralMatrix* ReturnMatrix::Evaluate(MatrixType mt) { return gm->Evaluate(mt); } void GeneralMatrix::Add(GeneralMatrix* gm1, Real f) { REPORT Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); while (i--) { *s++ = *s1++ + f; *s++ = *s1++ + f; *s++ = *s1++ + f; *s++ = *s1++ + f; } i = storage & 3; while (i--) *s++ = *s1++ + f; } void GeneralMatrix::Add(Real f) { REPORT Real* s=store; int i=(storage >> 2); while (i--) { *s++ += f; *s++ += f; *s++ += f; *s++ += f; } i = storage & 3; while (i--) *s++ += f; } void GeneralMatrix::NegAdd(GeneralMatrix* gm1, Real f) { REPORT Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); while (i--) { *s++ = f - *s1++; *s++ = f - *s1++; *s++ = f - *s1++; *s++ = f - *s1++; } i = storage & 3; while (i--) *s++ = f - *s1++; } void GeneralMatrix::NegAdd(Real f) { REPORT Real* s=store; int i=(storage >> 2); while (i--) { *s = f - *s; s++; *s = f - *s; s++; *s = f - *s; s++; *s = f - *s; s++; } i = storage & 3; while (i--) { *s = f - *s; s++; } } void GeneralMatrix::Negate(GeneralMatrix* gm1) { // change sign of elements REPORT Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); while (i--) { *s++ = -(*s1++); *s++ = -(*s1++); *s++ = -(*s1++); *s++ = -(*s1++); } i = storage & 3; while(i--) *s++ = -(*s1++); } void GeneralMatrix::Negate() { REPORT Real* s=store; int i=(storage >> 2); while (i--) { *s = -(*s); s++; *s = -(*s); s++; *s = -(*s); s++; *s = -(*s); s++; } i = storage & 3; while(i--) { *s = -(*s); s++; } } void GeneralMatrix::Multiply(GeneralMatrix* gm1, Real f) { REPORT Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); while (i--) { *s++ = *s1++ * f; *s++ = *s1++ * f; *s++ = *s1++ * f; *s++ = *s1++ * f; } i = storage & 3; while (i--) *s++ = *s1++ * f; } void GeneralMatrix::Multiply(Real f) { REPORT Real* s=store; int i=(storage >> 2); while (i--) { *s++ *= f; *s++ *= f; *s++ *= f; *s++ *= f; } i = storage & 3; while (i--) *s++ *= f; } /************************ MatrixInput routines ****************************/ // int MatrixInput::n; // number values still to be read // Real* MatrixInput::r; // pointer to next location to be read to MatrixInput MatrixInput::operator<<(Real f) { REPORT Tracer et("MatrixInput"); if (n<=0) Throw(ProgramException("List of values too long")); *r = f; int n1 = n-1; n=0; // n=0 so we won't trigger exception return MatrixInput(n1, r+1); } MatrixInput GeneralMatrix::operator<<(Real f) { REPORT Tracer et("MatrixInput"); int n = Storage(); if (n<=0) Throw(ProgramException("Loading data to zero length matrix")); Real* r; r = Store(); *r = f; n--; return MatrixInput(n, r+1); } MatrixInput GetSubMatrix::operator<<(Real f) { REPORT Tracer et("MatrixInput (GetSubMatrix)"); SetUpLHS(); if (row_number != 1 || col_skip != 0 || col_number != gm->Ncols()) { Throw(ProgramException("MatrixInput requires complete rows")); } MatrixRow mr(gm, DirectPart, row_skip); // to pick up location and length int n = mr.Storage(); if (n<=0) { Throw(ProgramException("Loading data to zero length row")); } Real* r; r = mr.Data(); *r = f; n--; if (+(mr.cw*HaveStore)) { Throw(ProgramException("Fails with this matrix type")); } return MatrixInput(n, r+1); } MatrixInput::~MatrixInput() { REPORT Tracer et("MatrixInput"); if (n!=0) Throw(ProgramException("A list of values was too short")); } MatrixInput BandMatrix::operator<<(Real) { Tracer et("MatrixInput"); // bool dummy = true; // if (dummy) // get rid of warning message Throw(ProgramException("Cannot use list read with a BandMatrix")); return MatrixInput(0, 0); } void BandMatrix::operator<<(const Real*) { Throw(ProgramException("Cannot use array read with a BandMatrix")); } void BandMatrix::operator<<(const int*) { Throw(ProgramException("Cannot use array read with a BandMatrix")); } void SymmetricBandMatrix::operator<<(const Real*) { Throw(ProgramException("Cannot use array read with a BandMatrix")); } void SymmetricBandMatrix::operator<<(const int*) { Throw(ProgramException("Cannot use array read with a BandMatrix")); } // ************************* Reverse order of elements *********************** void GeneralMatrix::ReverseElements(GeneralMatrix* gm) { // reversing into a new matrix REPORT int n = Storage(); Real* rx = Store() + n; Real* x = gm->Store(); while (n--) *(--rx) = *(x++); } void GeneralMatrix::ReverseElements() { // reversing in place REPORT int n = Storage(); Real* x = Store(); Real* rx = x + n; n /= 2; while (n--) { Real t = *(--rx); *rx = *x; *(x++) = t; } } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmat6.cpp000066400000000000000000000521611352751253100201000ustar00rootroot00000000000000//$$ newmat6.cpp Operators, element access, submatrices // Copyright (C) 1991,2,3,4: R B Davies #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,6); ++ExeCount; } #else #define REPORT {} #endif /*************************** general utilities *************************/ static int tristore(int n) // els in triangular matrix { return (n*(n+1))/2; } /****************************** operators *******************************/ Real& Matrix::operator()(int m, int n) { REPORT if (m<=0 || m>nrows || n<=0 || n>ncols) Throw(IndexException(m,n,*this)); return store[(m-1)*ncols+n-1]; } Real& SymmetricMatrix::operator()(int m, int n) { REPORT if (m<=0 || n<=0 || m>nrows || n>ncols) Throw(IndexException(m,n,*this)); if (m>=n) return store[tristore(m-1)+n-1]; else return store[tristore(n-1)+m-1]; } Real& UpperTriangularMatrix::operator()(int m, int n) { REPORT if (m<=0 || nncols) Throw(IndexException(m,n,*this)); return store[(m-1)*ncols+n-1-tristore(m-1)]; } Real& LowerTriangularMatrix::operator()(int m, int n) { REPORT if (n<=0 || mnrows) Throw(IndexException(m,n,*this)); return store[tristore(m-1)+n-1]; } Real& DiagonalMatrix::operator()(int m, int n) { REPORT if (n<=0 || m!=n || m>nrows || n>ncols) Throw(IndexException(m,n,*this)); return store[n-1]; } Real& DiagonalMatrix::operator()(int m) { REPORT if (m<=0 || m>nrows) Throw(IndexException(m,*this)); return store[m-1]; } Real& ColumnVector::operator()(int m) { REPORT if (m<=0 || m> nrows) Throw(IndexException(m,*this)); return store[m-1]; } Real& RowVector::operator()(int n) { REPORT if (n<=0 || n> ncols) Throw(IndexException(n,*this)); return store[n-1]; } Real& BandMatrix::operator()(int m, int n) { REPORT int w = upper+lower+1; int i = lower+n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real& UpperBandMatrix::operator()(int m, int n) { REPORT int w = upper+1; int i = n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real& LowerBandMatrix::operator()(int m, int n) { REPORT int w = lower+1; int i = lower+n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real& SymmetricBandMatrix::operator()(int m, int n) { REPORT int w = lower+1; if (m>=n) { REPORT int i = lower+n-m; if ( m>nrows || n<=0 || i<0 ) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } else { REPORT int i = lower+m-n; if ( n>nrows || m<=0 || i<0 ) Throw(IndexException(m,n,*this)); return store[w*(n-1)+i]; } } Real Matrix::operator()(int m, int n) const { REPORT if (m<=0 || m>nrows || n<=0 || n>ncols) Throw(IndexException(m,n,*this)); return store[(m-1)*ncols+n-1]; } Real SymmetricMatrix::operator()(int m, int n) const { REPORT if (m<=0 || n<=0 || m>nrows || n>ncols) Throw(IndexException(m,n,*this)); if (m>=n) return store[tristore(m-1)+n-1]; else return store[tristore(n-1)+m-1]; } Real UpperTriangularMatrix::operator()(int m, int n) const { REPORT if (m<=0 || nncols) Throw(IndexException(m,n,*this)); return store[(m-1)*ncols+n-1-tristore(m-1)]; } Real LowerTriangularMatrix::operator()(int m, int n) const { REPORT if (n<=0 || mnrows) Throw(IndexException(m,n,*this)); return store[tristore(m-1)+n-1]; } Real DiagonalMatrix::operator()(int m, int n) const { REPORT if (n<=0 || m!=n || m>nrows || n>ncols) Throw(IndexException(m,n,*this)); return store[n-1]; } Real DiagonalMatrix::operator()(int m) const { REPORT if (m<=0 || m>nrows) Throw(IndexException(m,*this)); return store[m-1]; } Real ColumnVector::operator()(int m) const { REPORT if (m<=0 || m> nrows) Throw(IndexException(m,*this)); return store[m-1]; } Real RowVector::operator()(int n) const { REPORT if (n<=0 || n> ncols) Throw(IndexException(n,*this)); return store[n-1]; } Real BandMatrix::operator()(int m, int n) const { REPORT int w = upper+lower+1; int i = lower+n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real UpperBandMatrix::operator()(int m, int n) const { REPORT int w = upper+1; int i = n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real LowerBandMatrix::operator()(int m, int n) const { REPORT int w = lower+1; int i = lower+n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real SymmetricBandMatrix::operator()(int m, int n) const { REPORT int w = lower+1; if (m>=n) { REPORT int i = lower+n-m; if ( m>nrows || n<=0 || i<0 ) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } else { REPORT int i = lower+m-n; if ( n>nrows || m<=0 || i<0 ) Throw(IndexException(m,n,*this)); return store[w*(n-1)+i]; } } Real BaseMatrix::AsScalar() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); if (gm->nrows!=1 || gm->ncols!=1) { Tracer tr("AsScalar"); Try { Throw(ProgramException("Cannot convert to scalar", *gm)); } CatchAll { gm->tDelete(); ReThrow; } } Real x = *(gm->store); gm->tDelete(); return x; } AddedMatrix BaseMatrix::operator+(const BaseMatrix& bm) const { REPORT return AddedMatrix(this, &bm); } SPMatrix SP(const BaseMatrix& bm1,const BaseMatrix& bm2) { REPORT return SPMatrix(&bm1, &bm2); } KPMatrix KP(const BaseMatrix& bm1,const BaseMatrix& bm2) { REPORT return KPMatrix(&bm1, &bm2); } MultipliedMatrix BaseMatrix::operator*(const BaseMatrix& bm) const { REPORT return MultipliedMatrix(this, &bm); } ConcatenatedMatrix BaseMatrix::operator|(const BaseMatrix& bm) const { REPORT return ConcatenatedMatrix(this, &bm); } StackedMatrix BaseMatrix::operator&(const BaseMatrix& bm) const { REPORT return StackedMatrix(this, &bm); } SolvedMatrix InvertedMatrix::operator*(const BaseMatrix& bmx) const { REPORT return SolvedMatrix(bm, &bmx); } SubtractedMatrix BaseMatrix::operator-(const BaseMatrix& bm) const { REPORT return SubtractedMatrix(this, &bm); } ShiftedMatrix BaseMatrix::operator+(Real f) const { REPORT return ShiftedMatrix(this, f); } ShiftedMatrix operator+(Real f, const BaseMatrix& BM) { REPORT return ShiftedMatrix(&BM, f); } NegShiftedMatrix operator-(Real f, const BaseMatrix& bm) { REPORT return NegShiftedMatrix(f, &bm); } ScaledMatrix BaseMatrix::operator*(Real f) const { REPORT return ScaledMatrix(this, f); } ScaledMatrix BaseMatrix::operator/(Real f) const { REPORT return ScaledMatrix(this, 1.0/f); } ScaledMatrix operator*(Real f, const BaseMatrix& BM) { REPORT return ScaledMatrix(&BM, f); } ShiftedMatrix BaseMatrix::operator-(Real f) const { REPORT return ShiftedMatrix(this, -f); } TransposedMatrix BaseMatrix::t() const { REPORT return TransposedMatrix(this); } NegatedMatrix BaseMatrix::operator-() const { REPORT return NegatedMatrix(this); } ReversedMatrix BaseMatrix::Reverse() const { REPORT return ReversedMatrix(this); } InvertedMatrix BaseMatrix::i() const { REPORT return InvertedMatrix(this); } RowedMatrix BaseMatrix::AsRow() const { REPORT return RowedMatrix(this); } ColedMatrix BaseMatrix::AsColumn() const { REPORT return ColedMatrix(this); } DiagedMatrix BaseMatrix::AsDiagonal() const { REPORT return DiagedMatrix(this); } MatedMatrix BaseMatrix::AsMatrix(int nrx, int ncx) const { REPORT return MatedMatrix(this,nrx,ncx); } void GeneralMatrix::operator=(Real f) { REPORT int i=storage; Real* s=store; while (i--) { *s++ = f; } } void Matrix::operator=(const BaseMatrix& X) { REPORT //CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::Rt); } void SquareMatrix::operator=(const BaseMatrix& X) { REPORT //CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::Rt); if (nrows != ncols) { Tracer tr("SquareMatrix(=)"); Throw(NotSquareException(*this)); } } void SquareMatrix::operator=(const Matrix& m) { REPORT if (m.nrows != m.ncols) { Tracer tr("SquareMatrix(=Matrix)"); Throw(NotSquareException(*this)); } Eq(m); } void RowVector::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::RV); if (nrows!=1) { Tracer tr("RowVector(=)"); Throw(VectorException(*this)); } } void ColumnVector::operator=(const BaseMatrix& X) { REPORT //CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::CV); if (ncols!=1) { Tracer tr("ColumnVector(=)"); Throw(VectorException(*this)); } } void SymmetricMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::Sm); } void UpperTriangularMatrix::operator=(const BaseMatrix& X) { REPORT //CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::UT); } void LowerTriangularMatrix::operator=(const BaseMatrix& X) { REPORT //CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::LT); } void DiagonalMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::Dg); } void IdentityMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::Id); } void GeneralMatrix::operator<<(const Real* r) { REPORT int i = storage; Real* s=store; while(i--) *s++ = *r++; } void GeneralMatrix::operator<<(const int* r) { REPORT int i = storage; Real* s=store; while(i--) *s++ = *r++; } void GenericMatrix::operator=(const GenericMatrix& bmx) { if (&bmx != this) { REPORT if (gm) delete gm; gm = bmx.gm->Image();} else { REPORT } gm->Protect(); } void GenericMatrix::operator=(const BaseMatrix& bmx) { if (gm) { int counter=bmx.search(gm); if (counter==0) { REPORT delete gm; gm=0; } else { REPORT gm->Release(counter); } } else { REPORT } GeneralMatrix* gmx = ((BaseMatrix&)bmx).Evaluate(); if (gmx != gm) { REPORT if (gm) delete gm; gm = gmx->Image(); } else { REPORT } gm->Protect(); } /*************************** += etc ***************************************/ // will also need versions for SubMatrix // GeneralMatrix operators void GeneralMatrix::operator+=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator+="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); AddedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); } void GeneralMatrix::operator-=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator-="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); SubtractedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); } void GeneralMatrix::operator*=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator*="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); MultipliedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); } void GeneralMatrix::operator|=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator|="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); ConcatenatedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); } void GeneralMatrix::operator&=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator&="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); StackedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); } void GeneralMatrix::operator+=(Real r) { REPORT Tracer tr("GeneralMatrix::operator+=(Real)"); // MatrixConversionCheck mcc; ShiftedMatrix am(this,r); Release(); Eq2(am,Type()); } void GeneralMatrix::operator*=(Real r) { REPORT Tracer tr("GeneralMatrix::operator*=(Real)"); // MatrixConversionCheck mcc; ScaledMatrix am(this,r); Release(); Eq2(am,Type()); } // Generic matrix operators void GenericMatrix::operator+=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator+="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); AddedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator-=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator-="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); SubtractedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator*=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator*="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); MultipliedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator|=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator|="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); ConcatenatedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator&=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator&="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); StackedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator+=(Real r) { REPORT Tracer tr("GenericMatrix::operator+= (Real)"); if (!gm) Throw(ProgramException("GenericMatrix is null")); ShiftedMatrix am(gm,r); gm->Release(); GeneralMatrix* gmy = am.Evaluate(); if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator*=(Real r) { REPORT Tracer tr("GenericMatrix::operator*= (Real)"); if (!gm) Throw(ProgramException("GenericMatrix is null")); ScaledMatrix am(gm,r); gm->Release(); GeneralMatrix* gmy = am.Evaluate(); if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } /************************* element access *********************************/ Real& Matrix::element(int m, int n) { REPORT if (m<0 || m>= nrows || n<0 || n>= ncols) Throw(IndexException(m,n,*this,true)); return store[m*ncols+n]; } Real Matrix::element(int m, int n) const { REPORT if (m<0 || m>= nrows || n<0 || n>= ncols) Throw(IndexException(m,n,*this,true)); return store[m*ncols+n]; } Real& SymmetricMatrix::element(int m, int n) { REPORT if (m<0 || n<0 || m >= nrows || n>=ncols) Throw(IndexException(m,n,*this,true)); if (m>=n) return store[tristore(m)+n]; else return store[tristore(n)+m]; } Real SymmetricMatrix::element(int m, int n) const { REPORT if (m<0 || n<0 || m >= nrows || n>=ncols) Throw(IndexException(m,n,*this,true)); if (m>=n) return store[tristore(m)+n]; else return store[tristore(n)+m]; } Real& UpperTriangularMatrix::element(int m, int n) { REPORT if (m<0 || n=ncols) Throw(IndexException(m,n,*this,true)); return store[m*ncols+n-tristore(m)]; } Real UpperTriangularMatrix::element(int m, int n) const { REPORT if (m<0 || n=ncols) Throw(IndexException(m,n,*this,true)); return store[m*ncols+n-tristore(m)]; } Real& LowerTriangularMatrix::element(int m, int n) { REPORT if (n<0 || m=nrows) Throw(IndexException(m,n,*this,true)); return store[tristore(m)+n]; } Real LowerTriangularMatrix::element(int m, int n) const { REPORT if (n<0 || m=nrows) Throw(IndexException(m,n,*this,true)); return store[tristore(m)+n]; } Real& DiagonalMatrix::element(int m, int n) { REPORT if (n<0 || m!=n || m>=nrows || n>=ncols) Throw(IndexException(m,n,*this,true)); return store[n]; } Real DiagonalMatrix::element(int m, int n) const { REPORT if (n<0 || m!=n || m>=nrows || n>=ncols) Throw(IndexException(m,n,*this,true)); return store[n]; } Real& DiagonalMatrix::element(int m) { REPORT if (m<0 || m>=nrows) Throw(IndexException(m,*this,true)); return store[m]; } Real DiagonalMatrix::element(int m) const { REPORT if (m<0 || m>=nrows) Throw(IndexException(m,*this,true)); return store[m]; } Real& ColumnVector::element(int m) { REPORT if (m<0 || m>= nrows) Throw(IndexException(m,*this,true)); return store[m]; } Real ColumnVector::element(int m) const { REPORT if (m<0 || m>= nrows) Throw(IndexException(m,*this,true)); return store[m]; } Real& RowVector::element(int n) { REPORT if (n<0 || n>= ncols) Throw(IndexException(n,*this,true)); return store[n]; } Real RowVector::element(int n) const { REPORT if (n<0 || n>= ncols) Throw(IndexException(n,*this,true)); return store[n]; } Real& BandMatrix::element(int m, int n) { REPORT int w = upper+lower+1; int i = lower+n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real BandMatrix::element(int m, int n) const { REPORT int w = upper+lower+1; int i = lower+n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real& UpperBandMatrix::element(int m, int n) { REPORT int w = upper+1; int i = n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real UpperBandMatrix::element(int m, int n) const { REPORT int w = upper+1; int i = n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real& LowerBandMatrix::element(int m, int n) { REPORT int w = lower+1; int i = lower+n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real LowerBandMatrix::element(int m, int n) const { REPORT int w = lower+1; int i = lower+n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real& SymmetricBandMatrix::element(int m, int n) { REPORT int w = lower+1; if (m>=n) { REPORT int i = lower+n-m; if ( m>=nrows || n<0 || i<0 ) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } else { REPORT int i = lower+m-n; if ( n>=nrows || m<0 || i<0 ) Throw(IndexException(m,n,*this,true)); return store[w*n+i]; } } Real SymmetricBandMatrix::element(int m, int n) const { REPORT int w = lower+1; if (m>=n) { REPORT int i = lower+n-m; if ( m>=nrows || n<0 || i<0 ) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } else { REPORT int i = lower+m-n; if ( n>=nrows || m<0 || i<0 ) Throw(IndexException(m,n,*this,true)); return store[w*n+i]; } } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmat7.cpp000066400000000000000000000745441352751253100201120ustar00rootroot00000000000000//$$ newmat7.cpp Invert, solve, binary operations // Copyright (C) 1991,2,3,4: R B Davies #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,7); ++ExeCount; } #else #define REPORT {} #endif //***************************** solve routines ******************************/ GeneralMatrix* GeneralMatrix::MakeSolver() { REPORT GeneralMatrix* gm = new CroutMatrix(*this); MatrixErrorNoSpace(gm); gm->ReleaseAndDelete(); return gm; } GeneralMatrix* Matrix::MakeSolver() { REPORT GeneralMatrix* gm = new CroutMatrix(*this); MatrixErrorNoSpace(gm); gm->ReleaseAndDelete(); return gm; } void CroutMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip; Real* el = mcin.data-i; Real* el1 = el; while (i--) *el++ = 0.0; el += mcin.storage; i = nrows - mcin.skip - mcin.storage; while (i--) *el++ = 0.0; lubksb(el1, mcout.skip); } // Do we need check for entirely zero output? void UpperTriangularMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip-mcout.skip; Real* elx = mcin.data-i; while (i-- > 0) *elx++ = 0.0; int nr = mcin.skip+mcin.storage; elx = mcin.data+mcin.storage; Real* el = elx; int j = mcout.skip+mcout.storage-nr; int nc = ncols-nr; i = nr-mcout.skip; while (j-- > 0) *elx++ = 0.0; Real* Ael = store + (nr*(2*ncols-nr+1))/2; j = 0; while (i-- > 0) { elx = el; Real sum = 0.0; int jx = j++; Ael -= nc; while (jx--) sum += *(--Ael) * *(--elx); elx--; *elx = (*elx - sum) / *(--Ael); } } void LowerTriangularMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip-mcout.skip; Real* elx = mcin.data-i; while (i-- > 0) *elx++ = 0.0; int nc = mcin.skip; i = nc+mcin.storage; elx = mcin.data+mcin.storage; int nr = mcout.skip+mcout.storage; int j = nr-i; i = nr-nc; while (j-- > 0) *elx++ = 0.0; Real* el = mcin.data; Real* Ael = store + (nc*(nc+1))/2; j = 0; while (i-- > 0) { elx = el; Real sum = 0.0; int jx = j++; Ael += nc; while (jx--) sum += *Ael++ * *elx++; *elx = (*elx - sum) / *Ael++; } } //******************* carry out binary operations *************************/ static GeneralMatrix* GeneralMult(GeneralMatrix*,GeneralMatrix*,MultipliedMatrix*,MatrixType); static GeneralMatrix* GeneralSolv(GeneralMatrix*,GeneralMatrix*,BaseMatrix*,MatrixType); static GeneralMatrix* GeneralSolvI(GeneralMatrix*,BaseMatrix*,MatrixType); static GeneralMatrix* GeneralKP(GeneralMatrix*,GeneralMatrix*,KPMatrix*,MatrixType); GeneralMatrix* MultipliedMatrix::Evaluate(MatrixType mt) { REPORT gm2 = ((BaseMatrix*&)bm2)->Evaluate(); gm2 = gm2->Evaluate(gm2->Type().MultRHS()); // no symmetric on RHS gm1=((BaseMatrix*&)bm1)->Evaluate(); return GeneralMult(gm1, gm2, this, mt); } GeneralMatrix* SolvedMatrix::Evaluate(MatrixType mt) { REPORT gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); return GeneralSolv(gm1,gm2,this,mt); } GeneralMatrix* KPMatrix::Evaluate(MatrixType mt) { REPORT gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); return GeneralKP(gm1,gm2,this,mt); } // routines for adding or subtracting matrices of identical storage structure static void Add(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT Real* s1=gm1->Store(); Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ = *s1++ + *s2++; *s++ = *s1++ + *s2++; *s++ = *s1++ + *s2++; *s++ = *s1++ + *s2++; } i=gm->Storage() & 3; while (i--) *s++ = *s1++ + *s2++; } static void AddTo(GeneralMatrix* gm, const GeneralMatrix* gm2) { REPORT const Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ += *s2++; *s++ += *s2++; *s++ += *s2++; *s++ += *s2++; } i=gm->Storage() & 3; while (i--) *s++ += *s2++; } void GeneralMatrix::PlusEqual(const GeneralMatrix& gm) { REPORT if (nrows != gm.nrows || ncols != gm.ncols) Throw(IncompatibleDimensionsException(*this, gm)); AddTo(this, &gm); } static void Subtract(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT Real* s1=gm1->Store(); Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ = *s1++ - *s2++; *s++ = *s1++ - *s2++; *s++ = *s1++ - *s2++; *s++ = *s1++ - *s2++; } i=gm->Storage() & 3; while (i--) *s++ = *s1++ - *s2++; } static void SubtractFrom(GeneralMatrix* gm, const GeneralMatrix* gm2) { REPORT const Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ -= *s2++; *s++ -= *s2++; *s++ -= *s2++; *s++ -= *s2++; } i=gm->Storage() & 3; while (i--) *s++ -= *s2++; } void GeneralMatrix::MinusEqual(const GeneralMatrix& gm) { REPORT if (nrows != gm.nrows || ncols != gm.ncols) Throw(IncompatibleDimensionsException(*this, gm)); SubtractFrom(this, &gm); } static void ReverseSubtract(GeneralMatrix* gm, const GeneralMatrix* gm2) { REPORT const Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s = *s2++ - *s; s++; *s = *s2++ - *s; s++; *s = *s2++ - *s; s++; *s = *s2++ - *s; s++; } i=gm->Storage() & 3; while (i--) { *s = *s2++ - *s; s++; } } static void SP(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT Real* s1=gm1->Store(); Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ = *s1++ * *s2++; *s++ = *s1++ * *s2++; *s++ = *s1++ * *s2++; *s++ = *s1++ * *s2++; } i=gm->Storage() & 3; while (i--) *s++ = *s1++ * *s2++; } static void SP(GeneralMatrix* gm, GeneralMatrix* gm2) { REPORT Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ *= *s2++; *s++ *= *s2++; *s++ *= *s2++; *s++ *= *s2++; } i=gm->Storage() & 3; while (i--) *s++ *= *s2++; } // routines for adding or subtracting matrices of different storage structure static void AddDS(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gm, StoreOnExit+DirectPart); while (nr--) { mr.Add(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } } static void AddDS(GeneralMatrix* gm, GeneralMatrix* gm2) // Add into first argument { REPORT int nr = gm->Nrows(); MatrixRow mr(gm, StoreOnExit+LoadOnEntry+DirectPart); MatrixRow mr2(gm2, LoadOnEntry); while (nr--) { mr.Add(mr2); mr.Next(); mr2.Next(); } } static void SubtractDS (GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gm, StoreOnExit+DirectPart); while (nr--) { mr.Sub(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } } static void SubtractDS(GeneralMatrix* gm, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart); MatrixRow mr2(gm2, LoadOnEntry); while (nr--) { mr.Sub(mr2); mr.Next(); mr2.Next(); } } static void ReverseSubtractDS(GeneralMatrix* gm, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart); MatrixRow mr2(gm2, LoadOnEntry); while (nr--) { mr.RevSub(mr2); mr2.Next(); mr.Next(); } } static void SPDS(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gm, StoreOnExit+DirectPart); while (nr--) { mr.Multiply(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } } static void SPDS(GeneralMatrix* gm, GeneralMatrix* gm2) // SP into first argument { REPORT int nr = gm->Nrows(); MatrixRow mr(gm, StoreOnExit+LoadOnEntry+DirectPart); MatrixRow mr2(gm2, LoadOnEntry); while (nr--) { mr.Multiply(mr2); mr.Next(); mr2.Next(); } } static GeneralMatrix* GeneralMult1(GeneralMatrix* gm1, GeneralMatrix* gm2, MultipliedMatrix* mm, MatrixType mtx) { REPORT Tracer tr("GeneralMult1"); int nr=gm1->Nrows(); int nc=gm2->Ncols(); if (gm1->Ncols() !=gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr,nc,mm); MatrixCol mcx(gmx, StoreOnExit+DirectPart); MatrixCol mc2(gm2, LoadOnEntry); while (nc--) { MatrixRow mr1(gm1, LoadOnEntry, mcx.Skip()); Real* el = mcx.Data(); // pointer to an element int n = mcx.Storage(); while (n--) { *(el++) = DotProd(mr1,mc2); mr1.Next(); } mc2.Next(); mcx.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; } static GeneralMatrix* GeneralMult2(GeneralMatrix* gm1, GeneralMatrix* gm2, MultipliedMatrix* mm, MatrixType mtx) { // version that accesses by row only - not good for thin matrices // or column vectors in right hand term. REPORT Tracer tr("GeneralMult2"); int nr=gm1->Nrows(); int nc=gm2->Ncols(); if (gm1->Ncols() !=gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr,nc,mm); MatrixRow mrx(gmx, LoadOnEntry+StoreOnExit+DirectPart); MatrixRow mr1(gm1, LoadOnEntry); while (nr--) { MatrixRow mr2(gm2, LoadOnEntry, mr1.Skip()); Real* el = mr1.Data(); // pointer to an element int n = mr1.Storage(); mrx.Zero(); while (n--) { mrx.AddScaled(mr2, *el++); mr2.Next(); } mr1.Next(); mrx.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; } static GeneralMatrix* mmMult(GeneralMatrix* gm1, GeneralMatrix* gm2) { // matrix multiplication for type Matrix only REPORT Tracer tr("MatrixMult"); int nr=gm1->Nrows(); int ncr=gm1->Ncols(); int nc=gm2->Ncols(); if (ncr != gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1,*gm2)); Matrix* gm = new Matrix(nr,nc); MatrixErrorNoSpace(gm); Real* s1=gm1->Store(); Real* s2=gm2->Store(); Real* s=gm->Store(); if (ncr) { while (nr--) { Real* s2x = s2; int j = ncr; Real* sx = s; Real f = *s1++; int k = nc; while (k--) *sx++ = f * *s2x++; while (--j) { sx = s; f = *s1++; k = nc; while (k--) *sx++ += f * *s2x++; } s = sx; } } else *gm = 0.0; gm->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gm; } static GeneralMatrix* GeneralMult(GeneralMatrix* gm1, GeneralMatrix* gm2, MultipliedMatrix* mm, MatrixType mtx) { if ( Rectangular(gm1->Type(), gm2->Type(), mtx)) { REPORT return mmMult(gm1, gm2); } else { REPORT Compare(gm1->Type() * gm2->Type(),mtx); int nr = gm2->Nrows(); int nc = gm2->Ncols(); if (nc <= 5 && nr > nc) { REPORT return GeneralMult1(gm1, gm2, mm, mtx); } else { REPORT return GeneralMult2(gm1, gm2, mm, mtx); } } return 0; } static GeneralMatrix* GeneralKP(GeneralMatrix* gm1, GeneralMatrix* gm2, KPMatrix* kp, MatrixType mtx) { REPORT Tracer tr("GeneralKP"); int nr1 = gm1->Nrows(); int nc1 = gm1->Ncols(); int nr2 = gm2->Nrows(); int nc2 = gm2->Ncols(); Compare((gm1->Type()).KP(gm2->Type()),mtx); GeneralMatrix* gmx = mtx.New(nr1*nr2, nc1*nc2, kp); MatrixRow mrx(gmx, LoadOnEntry+StoreOnExit+DirectPart); MatrixRow mr1(gm1, LoadOnEntry); for (int i = 1; i <= nr1; ++i) { MatrixRow mr2(gm2, LoadOnEntry); for (int j = 1; j <= nr2; ++j) { mrx.KP(mr1,mr2); mr2.Next(); mrx.Next(); } mr1.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; } static GeneralMatrix* GeneralSolv(GeneralMatrix* gm1, GeneralMatrix* gm2, BaseMatrix* sm, MatrixType mtx) { REPORT Tracer tr("GeneralSolv"); Compare(gm1->Type().i() * gm2->Type(),mtx); int nr = gm1->Nrows(); if (nr != gm1->Ncols()) Throw(NotSquareException(*gm1)); int nc = gm2->Ncols(); if (gm1->Ncols() != gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr,nc,sm); MatrixErrorNoSpace(gmx); Real* r = new Real [nr]; MatrixErrorNoSpace(r); MONITOR_REAL_NEW("Make (GenSolv)",nr,r) GeneralMatrix* gms = gm1->MakeSolver(); Try { MatrixColX mcx(gmx, r, StoreOnExit+DirectPart); // copy to and from r // this must be inside Try so mcx is destroyed before gmx MatrixColX mc2(gm2, r, LoadOnEntry); while (nc--) { gms->Solver(mcx, mc2); mcx.Next(); mc2.Next(); } } CatchAll { if (gms) gms->tDelete(); delete gmx; // <-------------------- gm2->tDelete(); MONITOR_REAL_DELETE("Delete (GenSolv)",nr,r) // AT&T version 2.1 gives an internal error delete [] r; ReThrow; } gms->tDelete(); gmx->ReleaseAndDelete(); gm2->tDelete(); MONITOR_REAL_DELETE("Delete (GenSolv)",nr,r) // AT&T version 2.1 gives an internal error delete [] r; return gmx; } // version for inverses - gm2 is identity static GeneralMatrix* GeneralSolvI(GeneralMatrix* gm1, BaseMatrix* sm, MatrixType mtx) { REPORT Tracer tr("GeneralSolvI"); Compare(gm1->Type().i(),mtx); int nr = gm1->Nrows(); if (nr != gm1->Ncols()) Throw(NotSquareException(*gm1)); int nc = nr; // DiagonalMatrix I(nr); I = 1; IdentityMatrix I(nr); GeneralMatrix* gmx = mtx.New(nr,nc,sm); MatrixErrorNoSpace(gmx); Real* r = new Real [nr]; MatrixErrorNoSpace(r); MONITOR_REAL_NEW("Make (GenSolvI)",nr,r) GeneralMatrix* gms = gm1->MakeSolver(); Try { MatrixColX mcx(gmx, r, StoreOnExit+DirectPart); // copy to and from r // this must be inside Try so mcx is destroyed before gmx MatrixColX mc2(&I, r, LoadOnEntry); while (nc--) { gms->Solver(mcx, mc2); mcx.Next(); mc2.Next(); } } CatchAll { if (gms) gms->tDelete(); delete gmx; MONITOR_REAL_DELETE("Delete (GenSolvI)",nr,r) // AT&T version 2.1 gives an internal error delete [] r; ReThrow; } gms->tDelete(); gmx->ReleaseAndDelete(); MONITOR_REAL_DELETE("Delete (GenSolvI)",nr,r) // AT&T version 2.1 gives an internal error delete [] r; return gmx; } GeneralMatrix* InvertedMatrix::Evaluate(MatrixType mtx) { // Matrix Inversion - use solve routines Tracer tr("InvertedMatrix::Evaluate"); REPORT gm=((BaseMatrix*&)bm)->Evaluate(); return GeneralSolvI(gm,this,mtx); } //*************************** New versions ************************ GeneralMatrix* AddedMatrix::Evaluate(MatrixType mtd) { REPORT Tracer tr("AddedMatrix::Evaluate"); gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); int nr=gm1->Nrows(); int nc=gm1->Ncols(); if (nr!=gm2->Nrows() || nc!=gm2->Ncols()) { Try { Throw(IncompatibleDimensionsException(*gm1, *gm2)); } CatchAll { gm1->tDelete(); gm2->tDelete(); ReThrow; } } MatrixType mt1 = gm1->Type(), mt2 = gm2->Type(); MatrixType mts = mt1 + mt2; if (!mtd) { REPORT mtd = mts; } else if (!(mtd.DataLossOK || mtd >= mts)) { REPORT gm1->tDelete(); gm2->tDelete(); Throw(ProgramException("Illegal Conversion", mts, mtd)); } GeneralMatrix* gmx; bool c1 = (mtd == mt1), c2 = (mtd == mt2); if ( c1 && c2 && (gm1->SimpleAddOK(gm2) == 0) ) { if (gm1->reuse()) { REPORT AddTo(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (gm2->reuse()) { REPORT AddTo(gm2,gm1); gmx = gm2; } else { REPORT // what if new throws an exception Try { gmx = mt1.New(nr,nc,this); } CatchAll { ReThrow; } gmx->ReleaseAndDelete(); Add(gmx,gm1,gm2); } } else { if (c1 && c2) { short SAO = gm1->SimpleAddOK(gm2); if (SAO & 1) { REPORT c1 = false; } if (SAO & 2) { REPORT c2 = false; } } if (c1 && gm1->reuse() ) // must have type test first { REPORT AddDS(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (c2 && gm2->reuse() ) { REPORT AddDS(gm2,gm1); if (!c1) gm1->tDelete(); gmx = gm2; } else { REPORT Try { gmx = mtd.New(nr,nc,this); } CatchAll { if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); ReThrow; } AddDS(gmx,gm1,gm2); if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); gmx->ReleaseAndDelete(); } } return gmx; } GeneralMatrix* SubtractedMatrix::Evaluate(MatrixType mtd) { REPORT Tracer tr("SubtractedMatrix::Evaluate"); gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); int nr=gm1->Nrows(); int nc=gm1->Ncols(); if (nr!=gm2->Nrows() || nc!=gm2->Ncols()) { Try { Throw(IncompatibleDimensionsException(*gm1, *gm2)); } CatchAll { gm1->tDelete(); gm2->tDelete(); ReThrow; } } MatrixType mt1 = gm1->Type(), mt2 = gm2->Type(); MatrixType mts = mt1 + mt2; if (!mtd) { REPORT mtd = mts; } else if (!(mtd.DataLossOK || mtd >= mts)) { gm1->tDelete(); gm2->tDelete(); Throw(ProgramException("Illegal Conversion", mts, mtd)); } GeneralMatrix* gmx; bool c1 = (mtd == mt1), c2 = (mtd == mt2); if ( c1 && c2 && (gm1->SimpleAddOK(gm2) == 0) ) { if (gm1->reuse()) { REPORT SubtractFrom(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (gm2->reuse()) { REPORT ReverseSubtract(gm2,gm1); gmx = gm2; } else { REPORT Try { gmx = mt1.New(nr,nc,this); } CatchAll { ReThrow; } gmx->ReleaseAndDelete(); Subtract(gmx,gm1,gm2); } } else { if (c1 && c2) { short SAO = gm1->SimpleAddOK(gm2); if (SAO & 1) { REPORT c1 = false; } if (SAO & 2) { REPORT c2 = false; } } if (c1 && gm1->reuse() ) // must have type test first { REPORT SubtractDS(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (c2 && gm2->reuse() ) { REPORT ReverseSubtractDS(gm2,gm1); if (!c1) gm1->tDelete(); gmx = gm2; } else { REPORT // what if New throws and exception Try { gmx = mtd.New(nr,nc,this); } CatchAll { if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); ReThrow; } SubtractDS(gmx,gm1,gm2); if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); gmx->ReleaseAndDelete(); } } return gmx; } GeneralMatrix* SPMatrix::Evaluate(MatrixType mtd) { REPORT Tracer tr("SPMatrix::Evaluate"); gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); int nr=gm1->Nrows(); int nc=gm1->Ncols(); if (nr!=gm2->Nrows() || nc!=gm2->Ncols()) { Try { Throw(IncompatibleDimensionsException(*gm1, *gm2)); } CatchAll { gm1->tDelete(); gm2->tDelete(); ReThrow; } } MatrixType mt1 = gm1->Type(), mt2 = gm2->Type(); MatrixType mts = mt1.SP(mt2); if (!mtd) { REPORT mtd = mts; } else if (!(mtd.DataLossOK || mtd >= mts)) { gm1->tDelete(); gm2->tDelete(); Throw(ProgramException("Illegal Conversion", mts, mtd)); } GeneralMatrix* gmx; bool c1 = (mtd == mt1), c2 = (mtd == mt2); if ( c1 && c2 && (gm1->SimpleAddOK(gm2) == 0) ) { if (gm1->reuse()) { REPORT SP(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (gm2->reuse()) { REPORT SP(gm2,gm1); gmx = gm2; } else { REPORT Try { gmx = mt1.New(nr,nc,this); } CatchAll { ReThrow; } gmx->ReleaseAndDelete(); SP(gmx,gm1,gm2); } } else { if (c1 && c2) { short SAO = gm1->SimpleAddOK(gm2); if (SAO & 1) { REPORT c2 = false; } // c1 and c2 swapped if (SAO & 2) { REPORT c1 = false; } } if (c1 && gm1->reuse() ) // must have type test first { REPORT SPDS(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (c2 && gm2->reuse() ) { REPORT SPDS(gm2,gm1); if (!c1) gm1->tDelete(); gmx = gm2; } else { REPORT // what if New throws and exception Try { gmx = mtd.New(nr,nc,this); } CatchAll { if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); ReThrow; } SPDS(gmx,gm1,gm2); if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); gmx->ReleaseAndDelete(); } } return gmx; } //*************************** norm functions ****************************/ Real BaseMatrix::Norm1() const { // maximum of sum of absolute values of a column REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); int nc = gm->Ncols(); Real value = 0.0; MatrixCol mc(gm, LoadOnEntry); while (nc--) { Real v = mc.SumAbsoluteValue(); if (value < v) value = v; mc.Next(); } gm->tDelete(); return value; } Real BaseMatrix::NormInfinity() const { // maximum of sum of absolute values of a row REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); int nr = gm->Nrows(); Real value = 0.0; MatrixRow mr(gm, LoadOnEntry); while (nr--) { Real v = mr.SumAbsoluteValue(); if (value < v) value = v; mr.Next(); } gm->tDelete(); return value; } //********************** Concatenation and stacking *************************/ GeneralMatrix* ConcatenatedMatrix::Evaluate(MatrixType mtx) { REPORT Tracer tr("Concatenate"); gm2 = ((BaseMatrix*&)bm2)->Evaluate(); gm1 = ((BaseMatrix*&)bm1)->Evaluate(); Compare(gm1->Type() | gm2->Type(),mtx); int nr=gm1->Nrows(); int nc = gm1->Ncols() + gm2->Ncols(); if (nr != gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr,nc,this); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gmx, StoreOnExit+DirectPart); while (nr--) { mr.ConCat(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; } GeneralMatrix* StackedMatrix::Evaluate(MatrixType mtx) { REPORT Tracer tr("Stack"); gm2 = ((BaseMatrix*&)bm2)->Evaluate(); gm1 = ((BaseMatrix*&)bm1)->Evaluate(); Compare(gm1->Type() & gm2->Type(),mtx); int nc=gm1->Ncols(); int nr1 = gm1->Nrows(); int nr2 = gm2->Nrows(); if (nc != gm2->Ncols()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr1+nr2,nc,this); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gmx, StoreOnExit+DirectPart); while (nr1--) { mr.Copy(mr1); mr1.Next(); mr.Next(); } while (nr2--) { mr.Copy(mr2); mr2.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; } // ************************* equality of matrices ******************** // static bool RealEqual(Real* s1, Real* s2, int n) { int i = n >> 2; while (i--) { if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; } i = n & 3; while (i--) if (*s1++ != *s2++) return false; return true; } static bool intEqual(int* s1, int* s2, int n) { int i = n >> 2; while (i--) { if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; } i = n & 3; while (i--) if (*s1++ != *s2++) return false; return true; } bool operator==(const BaseMatrix& A, const BaseMatrix& B) { Tracer tr("BaseMatrix =="); REPORT GeneralMatrix* gmA = ((BaseMatrix&)A).Evaluate(); GeneralMatrix* gmB = ((BaseMatrix&)B).Evaluate(); if (gmA == gmB) // same matrix { REPORT gmA->tDelete(); return true; } if ( gmA->Nrows() != gmB->Nrows() || gmA->Ncols() != gmB->Ncols() ) // different dimensions { REPORT gmA->tDelete(); gmB->tDelete(); return false; } // check for CroutMatrix or BandLUMatrix MatrixType AType = gmA->Type(); MatrixType BType = gmB->Type(); if (AType.CannotConvert() || BType.CannotConvert() ) { REPORT bool bx = gmA->IsEqual(*gmB); gmA->tDelete(); gmB->tDelete(); return bx; } // is matrix storage the same // will need to modify if further matrix structures are introduced if (AType == BType && gmA->BandWidth() == gmB->BandWidth()) { // compare store REPORT bool bx = RealEqual(gmA->Store(),gmB->Store(),gmA->Storage()); gmA->tDelete(); gmB->tDelete(); return bx; } // matrix storage different - just subtract REPORT return IsZero(*gmA-*gmB); } bool operator==(const GeneralMatrix& A, const GeneralMatrix& B) { Tracer tr("GeneralMatrix =="); // May or may not call tDeletes REPORT if (&A == &B) // same matrix { REPORT return true; } if ( A.Nrows() != B.Nrows() || A.Ncols() != B.Ncols() ) { REPORT return false; } // different dimensions // check for CroutMatrix or BandLUMatrix MatrixType AType = A.Type(); MatrixType BType = B.Type(); if (AType.CannotConvert() || BType.CannotConvert() ) { REPORT return A.IsEqual(B); } // is matrix storage the same // will need to modify if further matrix structures are introduced if (AType == BType && A.BandWidth() == B.BandWidth()) { REPORT return RealEqual(A.Store(),B.Store(),A.Storage()); } // matrix storage different - just subtract REPORT return IsZero(A-B); } bool GeneralMatrix::IsZero() const { REPORT Real* s=store; int i = storage >> 2; while (i--) { if (*s++) return false; if (*s++) return false; if (*s++) return false; if (*s++) return false; } i = storage & 3; while (i--) if (*s++) return false; return true; } bool IsZero(const BaseMatrix& A) { Tracer tr("BaseMatrix::IsZero"); REPORT GeneralMatrix* gm1 = 0; bool bx; Try { gm1=((BaseMatrix&)A).Evaluate(); bx = gm1->IsZero(); } CatchAll { if (gm1) gm1->tDelete(); ReThrow; } gm1->tDelete(); return bx; } // IsEqual functions - insist matrices are of same type // as well as equal values to be equal bool GeneralMatrix::IsEqual(const GeneralMatrix& A) const { Tracer tr("GeneralMatrix IsEqual"); if (A.Type() != Type()) // not same types { REPORT return false; } if (&A == this) // same matrix { REPORT return true; } if (A.nrows != nrows || A.ncols != ncols) // different dimensions { REPORT return false; } // is matrix storage the same - compare store REPORT return RealEqual(A.store,store,storage); } bool CroutMatrix::IsEqual(const GeneralMatrix& A) const { Tracer tr("CroutMatrix IsEqual"); if (A.Type() != Type()) // not same types { REPORT return false; } if (&A == this) // same matrix { REPORT return true; } if (A.nrows != nrows || A.ncols != ncols) // different dimensions { REPORT return false; } // is matrix storage the same - compare store REPORT return RealEqual(A.store,store,storage) && intEqual(((CroutMatrix&)A).indx, indx, nrows); } bool BandLUMatrix::IsEqual(const GeneralMatrix& A) const { Tracer tr("BandLUMatrix IsEqual"); if (A.Type() != Type()) // not same types { REPORT return false; } if (&A == this) // same matrix { REPORT return true; } if ( A.Nrows() != nrows || A.Ncols() != ncols || ((BandLUMatrix&)A).m1 != m1 || ((BandLUMatrix&)A).m2 != m2 ) // different dimensions { REPORT return false; } // matrix storage the same - compare store REPORT return RealEqual(A.Store(),store,storage) && RealEqual(((BandLUMatrix&)A).store2,store2,storage2) && intEqual(((BandLUMatrix&)A).indx, indx, nrows); } // ************************* cross products ******************** // inline void CrossProductBody(Real* a, Real* b, Real* c) { c[0] = a[1] * b[2] - a[2] * b[1]; c[1] = a[2] * b[0] - a[0] * b[2]; c[2] = a[0] * b[1] - a[1] * b[0]; } Matrix CrossProduct(const Matrix& A, const Matrix& B) { REPORT int ac = A.Ncols(); int ar = A.Nrows(); int bc = B.Ncols(); int br = B.Nrows(); Real* a = A.Store(); Real* b = B.Store(); if (ac == 3) { if (bc != 3 || ar != 1 || br != 1) { Tracer et("CrossProduct"); IncompatibleDimensionsException(A, B); } REPORT RowVector C(3); Real* c = C.Store(); CrossProductBody(a, b, c); return C; } else { if (ac != 1 || bc != 1 || ar != 3 || br != 3) { Tracer et("CrossProduct"); IncompatibleDimensionsException(A, B); } REPORT ColumnVector C(3); Real* c = C.Store(); CrossProductBody(a, b, c); return C; } } ReturnMatrix CrossProductRows(const Matrix& A, const Matrix& B) { REPORT int n = A.Nrows(); if (A.Ncols() != 3 || B.Ncols() != 3 || n != B.Nrows()) { Tracer et("CrossProductRows"); IncompatibleDimensionsException(A, B); } Matrix C(n, 3); Real* a = A.Store(); Real* b = B.Store(); Real* c = C.Store(); if (n--) { for (;;) { CrossProductBody(a, b, c); if (!(n--)) break; a += 3; b += 3; c += 3; } } return C.ForReturn(); } ReturnMatrix CrossProductColumns(const Matrix& A, const Matrix& B) { REPORT int n = A.Ncols(); if (A.Nrows() != 3 || B.Nrows() != 3 || n != B.Ncols()) { Tracer et("CrossProductColumns"); IncompatibleDimensionsException(A, B); } Matrix C(3, n); Real* a = A.Store(); Real* b = B.Store(); Real* c = C.Store(); Real* an = a+n; Real* an2 = an+n; Real* bn = b+n; Real* bn2 = bn+n; Real* cn = c+n; Real* cn2 = cn+n; int i = n; while (i--) { *c++ = *an * *bn2 - *an2 * *bn; *cn++ = *an2++ * *b - *a * *bn2++; *cn2++ = *a++ * *bn++ - *an++ * *b++; } return C.ForReturn(); } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmat8.cpp000066400000000000000000000470121352751253100201010ustar00rootroot00000000000000//$$ newmat8.cpp Advanced LU transform, scalar functions // Copyright (C) 1991,2,3,4,8: R B Davies #define WANT_MATH #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,8); ++ExeCount; } #else #define REPORT {} #endif /************************** LU transformation ****************************/ void CroutMatrix::ludcmp() // LU decomposition from Golub & Van Loan, algorithm 3.4.1, (the "outer // product" version). // This replaces the code derived from Numerical Recipes in C in previous // versions of newmat and being row oriented runs much faster with large // matrices. { REPORT Tracer trace( "Crout(ludcmp)" ); sing = false; Real* akk = store; // runs down diagonal Real big = fabs(*akk); int mu = 0; Real* ai = akk; int k; for (k = 1; k < nrows; k++) { ai += nrows; const Real trybig = fabs(*ai); if (big < trybig) { big = trybig; mu = k; } } if (nrows) for (k = 0;;) { /* int mu1; { Real big = fabs(*akk); mu1 = k; Real* ai = akk; int i; for (i = k+1; i < nrows; i++) { ai += nrows; const Real trybig = fabs(*ai); if (big < trybig) { big = trybig; mu1 = i; } } } if (mu1 != mu) cout << k << " " << mu << " " << mu1 << endl; */ indx[k] = mu; if (mu != k) //row swap { Real* a1 = store + nrows * k; Real* a2 = store + nrows * mu; d = !d; int j = nrows; while (j--) { const Real temp = *a1; *a1++ = *a2; *a2++ = temp; } } Real diag = *akk; big = 0; mu = k + 1; if (diag != 0) { ai = akk; int i = nrows - k - 1; while (i--) { ai += nrows; Real* al = ai; Real mult = *al / diag; *al = mult; int l = nrows - k - 1; Real* aj = akk; // work out the next pivot as part of this loop // this saves a column operation if (l-- != 0) { *(++al) -= (mult * *(++aj)); const Real trybig = fabs(*al); if (big < trybig) { big = trybig; mu = nrows - i - 1; } while (l--) *(++al) -= (mult * *(++aj)); } } } else sing = true; if (++k == nrows) break; // so next line won't overflow akk += nrows + 1; } } void CroutMatrix::lubksb(Real* B, int mini) { REPORT // this has been adapted from Numerical Recipes in C. The code has been // substantially streamlined, so I do not think much of the original // copyright remains. However there is not much opportunity for // variation in the code, so it is still similar to the NR code. // I follow the NR code in skipping over initial zeros in the B vector. Tracer trace("Crout(lubksb)"); sing = false; // if ((this->LogDeterminant()).Value() != 0) sing = false; if (sing) Throw(SingularException(*this)); int i, j, ii = nrows; // ii initialised : B might be all zeros // scan for first non-zero in B for (i = 0; i < nrows; i++) { int ip = indx[i]; Real temp = B[ip]; B[ip] = B[i]; B[i] = temp; if (temp != 0.0) { ii = i; break; } } Real* bi; Real* ai; i = ii + 1; if (i < nrows) { bi = B + ii; ai = store + ii + i * nrows; for (;;) { int ip = indx[i]; Real sum = B[ip]; B[ip] = B[i]; Real* aij = ai; Real* bj = bi; j = i - ii; while (j--) sum -= *aij++ * *bj++; B[i] = sum; if (++i == nrows) break; ai += nrows; } } ai = store + nrows * nrows; for (i = nrows - 1; i >= mini; i--) { Real* bj = B+i; ai -= nrows; Real* ajx = ai+i; Real sum = *bj; Real diag = *ajx; j = nrows - i; while(--j) sum -= *(++ajx) * *(++bj); B[i] = sum / diag; } } /****************************** scalar functions ****************************/ inline Real square(Real x) { return x*x; } Real GeneralMatrix::SumSquare() const { REPORT Real sum = 0.0; int i = storage; Real* s = store; while (i--) sum += square(*s++); ((GeneralMatrix&)*this).tDelete(); return sum; } Real GeneralMatrix::SumAbsoluteValue() const { REPORT Real sum = 0.0; int i = storage; Real* s = store; while (i--) sum += fabs(*s++); ((GeneralMatrix&)*this).tDelete(); return sum; } Real GeneralMatrix::Sum() const { REPORT Real sum = 0.0; int i = storage; Real* s = store; while (i--) sum += *s++; ((GeneralMatrix&)*this).tDelete(); return sum; } // maxima and minima // There are three sets of routines // MaximumAbsoluteValue, MinimumAbsoluteValue, Maximum, Minimum // ... these find just the maxima and minima // MaximumAbsoluteValue1, MinimumAbsoluteValue1, Maximum1, Minimum1 // ... these find the maxima and minima and their locations in a // one dimensional object // MaximumAbsoluteValue2, MinimumAbsoluteValue2, Maximum2, Minimum2 // ... these find the maxima and minima and their locations in a // two dimensional object // If the matrix has no values throw an exception // If we do not want the location find the maximum or minimum on the // array stored by GeneralMatrix // This won't work for BandMatrices. We call ClearCorner for // MaximumAbsoluteValue but for the others use the AbsoluteMinimumValue2 // version and discard the location. // For one dimensional objects, when we want the location of the // maximum or minimum, work with the array stored by GeneralMatrix // For two dimensional objects where we want the location of the maximum or // minimum proceed as follows: // For rectangular matrices use the array stored by GeneralMatrix and // deduce the location from the location in the GeneralMatrix // For other two dimensional matrices use the Matrix Row routine to find the // maximum or minimum for each row. static void NullMatrixError(const GeneralMatrix* gm) { ((GeneralMatrix&)*gm).tDelete(); Throw(ProgramException("Maximum or minimum of null matrix")); } Real GeneralMatrix::MaximumAbsoluteValue() const { REPORT if (storage == 0) NullMatrixError(this); Real maxval = 0.0; int l = storage; Real* s = store; while (l--) { Real a = fabs(*s++); if (maxval < a) maxval = a; } ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::MaximumAbsoluteValue1(int& i) const { REPORT if (storage == 0) NullMatrixError(this); Real maxval = 0.0; int l = storage; Real* s = store; int li = storage; while (l--) { Real a = fabs(*s++); if (maxval <= a) { maxval = a; li = l; } } i = storage - li; ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::MinimumAbsoluteValue() const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real minval = fabs(*s++); while (l--) { Real a = fabs(*s++); if (minval > a) minval = a; } ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::MinimumAbsoluteValue1(int& i) const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real minval = fabs(*s++); int li = l; while (l--) { Real a = fabs(*s++); if (minval >= a) { minval = a; li = l; } } i = storage - li; ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::Maximum() const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real maxval = *s++; while (l--) { Real a = *s++; if (maxval < a) maxval = a; } ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::Maximum1(int& i) const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real maxval = *s++; int li = l; while (l--) { Real a = *s++; if (maxval <= a) { maxval = a; li = l; } } i = storage - li; ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::Minimum() const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real minval = *s++; while (l--) { Real a = *s++; if (minval > a) minval = a; } ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::Minimum1(int& i) const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real minval = *s++; int li = l; while (l--) { Real a = *s++; if (minval >= a) { minval = a; li = l; } } i = storage - li; ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::MaximumAbsoluteValue2(int& i, int& j) const { REPORT if (storage == 0) NullMatrixError(this); Real maxval = 0.0; int nr = Nrows(); MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); for (int r = 1; r <= nr; r++) { int c; maxval = mr.MaximumAbsoluteValue1(maxval, c); if (c > 0) { i = r; j = c; } mr.Next(); } ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::MinimumAbsoluteValue2(int& i, int& j) const { REPORT if (storage == 0) NullMatrixError(this); Real minval = FloatingPointPrecision::Maximum(); int nr = Nrows(); MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); for (int r = 1; r <= nr; r++) { int c; minval = mr.MinimumAbsoluteValue1(minval, c); if (c > 0) { i = r; j = c; } mr.Next(); } ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::Maximum2(int& i, int& j) const { REPORT if (storage == 0) NullMatrixError(this); Real maxval = -FloatingPointPrecision::Maximum(); int nr = Nrows(); MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); for (int r = 1; r <= nr; r++) { int c; maxval = mr.Maximum1(maxval, c); if (c > 0) { i = r; j = c; } mr.Next(); } ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::Minimum2(int& i, int& j) const { REPORT if (storage == 0) NullMatrixError(this); Real minval = FloatingPointPrecision::Maximum(); int nr = Nrows(); MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); for (int r = 1; r <= nr; r++) { int c; minval = mr.Minimum1(minval, c); if (c > 0) { i = r; j = c; } mr.Next(); } ((GeneralMatrix&)*this).tDelete(); return minval; } Real Matrix::MaximumAbsoluteValue2(int& i, int& j) const { REPORT int k; Real m = GeneralMatrix::MaximumAbsoluteValue1(k); k--; i = k / Ncols(); j = k - i * Ncols(); i++; j++; return m; } Real Matrix::MinimumAbsoluteValue2(int& i, int& j) const { REPORT int k; Real m = GeneralMatrix::MinimumAbsoluteValue1(k); k--; i = k / Ncols(); j = k - i * Ncols(); i++; j++; return m; } Real Matrix::Maximum2(int& i, int& j) const { REPORT int k; Real m = GeneralMatrix::Maximum1(k); k--; i = k / Ncols(); j = k - i * Ncols(); i++; j++; return m; } Real Matrix::Minimum2(int& i, int& j) const { REPORT int k; Real m = GeneralMatrix::Minimum1(k); k--; i = k / Ncols(); j = k - i * Ncols(); i++; j++; return m; } Real SymmetricMatrix::SumSquare() const { REPORT Real sum1 = 0.0; Real sum2 = 0.0; Real* s = store; int nr = nrows; for (int i = 0; iSumSquare(); return s; } Real BaseMatrix::NormFrobenius() const { REPORT return sqrt(SumSquare()); } Real BaseMatrix::SumAbsoluteValue() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->SumAbsoluteValue(); return s; } Real BaseMatrix::Sum() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Sum(); return s; } Real BaseMatrix::MaximumAbsoluteValue() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MaximumAbsoluteValue(); return s; } Real BaseMatrix::MaximumAbsoluteValue1(int& i) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MaximumAbsoluteValue1(i); return s; } Real BaseMatrix::MaximumAbsoluteValue2(int& i, int& j) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MaximumAbsoluteValue2(i, j); return s; } Real BaseMatrix::MinimumAbsoluteValue() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MinimumAbsoluteValue(); return s; } Real BaseMatrix::MinimumAbsoluteValue1(int& i) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MinimumAbsoluteValue1(i); return s; } Real BaseMatrix::MinimumAbsoluteValue2(int& i, int& j) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MinimumAbsoluteValue2(i, j); return s; } Real BaseMatrix::Maximum() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Maximum(); return s; } Real BaseMatrix::Maximum1(int& i) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Maximum1(i); return s; } Real BaseMatrix::Maximum2(int& i, int& j) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Maximum2(i, j); return s; } Real BaseMatrix::Minimum() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Minimum(); return s; } Real BaseMatrix::Minimum1(int& i) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Minimum1(i); return s; } Real BaseMatrix::Minimum2(int& i, int& j) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Minimum2(i, j); return s; } Real DotProduct(const Matrix& A, const Matrix& B) { REPORT int n = A.storage; if (n != B.storage) Throw(IncompatibleDimensionsException(A,B)); Real sum = 0.0; Real* a = A.store; Real* b = B.store; while (n--) sum += *a++ * *b++; return sum; } Real Matrix::Trace() const { REPORT Tracer trace("Trace"); int i = nrows; int d = i+1; if (i != ncols) Throw(NotSquareException(*this)); Real sum = 0.0; Real* s = store; // while (i--) { sum += *s; s += d; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += d; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real DiagonalMatrix::Trace() const { REPORT int i = nrows; Real sum = 0.0; Real* s = store; while (i--) sum += *s++; ((GeneralMatrix&)*this).tDelete(); return sum; } Real SymmetricMatrix::Trace() const { REPORT int i = nrows; Real sum = 0.0; Real* s = store; int j = 2; // while (i--) { sum += *s; s += j++; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += j++; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real LowerTriangularMatrix::Trace() const { REPORT int i = nrows; Real sum = 0.0; Real* s = store; int j = 2; // while (i--) { sum += *s; s += j++; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += j++; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real UpperTriangularMatrix::Trace() const { REPORT int i = nrows; Real sum = 0.0; Real* s = store; while (i) { sum += *s; s += i--; } // won t cause a problem ((GeneralMatrix&)*this).tDelete(); return sum; } Real BandMatrix::Trace() const { REPORT int i = nrows; int w = lower+upper+1; Real sum = 0.0; Real* s = store+lower; // while (i--) { sum += *s; s += w; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += w; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real SymmetricBandMatrix::Trace() const { REPORT int i = nrows; int w = lower+1; Real sum = 0.0; Real* s = store+lower; // while (i--) { sum += *s; s += w; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += w; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real IdentityMatrix::Trace() const { Real sum = *store * nrows; ((GeneralMatrix&)*this).tDelete(); return sum; } Real BaseMatrix::Trace() const { REPORT MatrixType Diag = MatrixType::Dg; Diag.SetDataLossOK(); GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(Diag); Real sum = gm->Trace(); return sum; } void LogAndSign::operator*=(Real x) { if (x > 0.0) { log_value += log(x); } else if (x < 0.0) { log_value += log(-x); sign = -sign; } else sign = 0; } void LogAndSign::PowEq(int k) { if (sign) { log_value *= k; if ( (k & 1) == 0 ) sign = 1; } } Real LogAndSign::Value() const { Tracer et("LogAndSign::Value"); if (log_value >= FloatingPointPrecision::LnMaximum()) Throw(OverflowException("Overflow in exponential")); return sign * exp(log_value); } LogAndSign::LogAndSign(Real f) { if (f == 0.0) { log_value = 0.0; sign = 0; return; } else if (f < 0.0) { sign = -1; f = -f; } else sign = 1; log_value = log(f); } LogAndSign DiagonalMatrix::LogDeterminant() const { REPORT int i = nrows; LogAndSign sum; Real* s = store; while (i--) sum *= *s++; ((GeneralMatrix&)*this).tDelete(); return sum; } LogAndSign LowerTriangularMatrix::LogDeterminant() const { REPORT int i = nrows; LogAndSign sum; Real* s = store; int j = 2; // while (i--) { sum *= *s; s += j++; } if (i) for(;;) { sum *= *s; if (!(--i)) break; s += j++; } ((GeneralMatrix&)*this).tDelete(); return sum; } LogAndSign UpperTriangularMatrix::LogDeterminant() const { REPORT int i = nrows; LogAndSign sum; Real* s = store; while (i) { sum *= *s; s += i--; } ((GeneralMatrix&)*this).tDelete(); return sum; } LogAndSign IdentityMatrix::LogDeterminant() const { REPORT int i = nrows; LogAndSign sum; if (i > 0) { sum = *store; sum.PowEq(i); } ((GeneralMatrix&)*this).tDelete(); return sum; } LogAndSign BaseMatrix::LogDeterminant() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); LogAndSign sum = gm->LogDeterminant(); return sum; } LogAndSign GeneralMatrix::LogDeterminant() const { REPORT Tracer tr("LogDeterminant"); if (nrows != ncols) Throw(NotSquareException(*this)); CroutMatrix C(*this); return C.LogDeterminant(); } LogAndSign CroutMatrix::LogDeterminant() const { REPORT if (sing) return 0.0; int i = nrows; int dd = i+1; LogAndSign sum; Real* s = store; if (i) for(;;) { sum *= *s; if (!(--i)) break; s += dd; } if (!d) sum.ChangeSign(); return sum; } Real BaseMatrix::Determinant() const { REPORT Tracer tr("Determinant"); REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); LogAndSign ld = gm->LogDeterminant(); return ld.Value(); } LinearEquationSolver::LinearEquationSolver(const BaseMatrix& bm) { gm = ((BaseMatrix&) bm ).Evaluate()->MakeSolver(); if (gm==&bm) { REPORT gm = gm->Image(); } // want a copy if *gm is actually bm else { REPORT gm->Protect(); } } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmat9.cpp000066400000000000000000000032431352751253100201000ustar00rootroot00000000000000//$$ newmat9.cpp Input and output // Copyright (C) 1991,2,3,4: R B Davies #define WANT_STREAM #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif using namespace std; #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,9); ++ExeCount; } #else #define REPORT {} #endif // for G++ 3.01 #ifndef ios_format_flags #define ios_format_flags long #endif ostream& operator<<(ostream& s, const BaseMatrix& X) { GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); operator<<(s, *gm); gm->tDelete(); return s; } ostream& operator<<(ostream& s, const GeneralMatrix& X) { MatrixRow mr((GeneralMatrix*)&X, LoadOnEntry); int w = s.width(); int nr = X.Nrows(); std::ios_base::fmtflags f = s.flags(); s.setf(ios::fixed, ios::floatfield); for (int i=1; i<=nr; i++) { int skip = mr.skip; int storage = mr.storage; Real* store = mr.data; skip *= w+1; while (skip--) s << " "; while (storage--) { s.width(w); s << *store++ << " "; } // while (storage--) s << setw(w) << *store++ << " "; mr.Next(); s << "\n"; } s << flush; s.flags(f); return s; } // include this stuff if you are using an old version of G++ // with an incomplete io library /* ostream& operator<<(ostream& os, Omanip_precision i) { os.precision(i.x); return os; } Omanip_precision setprecision(int i) { return Omanip_precision(i); } ostream& operator<<(ostream& os, Omanip_width i) { os.width(i.x); return os; } Omanip_width setw(int i) { return Omanip_width(i); } */ #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmatex.cpp000066400000000000000000000207131352751253100203450ustar00rootroot00000000000000//$$ newmatex.cpp Exception handler // Copyright (C) 1992,3,4,7: R B Davies #define WANT_STREAM // include.h will get stream fns #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif unsigned long OverflowException::Select; unsigned long SingularException::Select; unsigned long NPDException::Select; unsigned long ConvergenceException::Select; unsigned long ProgramException::Select; unsigned long IndexException::Select; unsigned long VectorException::Select; unsigned long NotSquareException::Select; unsigned long SubMatrixDimensionException::Select; unsigned long IncompatibleDimensionsException::Select; unsigned long NotDefinedException::Select; unsigned long CannotBuildException::Select; unsigned long InternalException::Select; static void MatrixDetails(const GeneralMatrix& A) // write matrix details to Exception buffer { MatrixBandWidth bw = A.BandWidth(); int ubw = bw.upper; int lbw = bw.lower; BaseException::AddMessage("MatrixType = "); BaseException::AddMessage(A.Type().Value()); BaseException::AddMessage(" # Rows = "); BaseException::AddInt(A.Nrows()); BaseException::AddMessage("; # Cols = "); BaseException::AddInt(A.Ncols()); if (lbw >=0) { BaseException::AddMessage("; lower BW = "); BaseException::AddInt(lbw); } if (ubw >=0) { BaseException::AddMessage("; upper BW = "); BaseException::AddInt(ubw); } BaseException::AddMessage("\n"); } NPDException::NPDException(const GeneralMatrix& A) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: matrix not positive definite\n\n"); MatrixDetails(A); Tracer::AddTrace(); } SingularException::SingularException(const GeneralMatrix& A) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: matrix is singular\n\n"); MatrixDetails(A); Tracer::AddTrace(); } ConvergenceException::ConvergenceException(const GeneralMatrix& A) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: process fails to converge\n\n"); MatrixDetails(A); Tracer::AddTrace(); } ConvergenceException::ConvergenceException(const char* c) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); if (c) Tracer::AddTrace(); } OverflowException::OverflowException(const char* c) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); if (c) Tracer::AddTrace(); } ProgramException::ProgramException(const char* c) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); if (c) Tracer::AddTrace(); } ProgramException::ProgramException(const char* c, const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); MatrixDetails(A); if (c) Tracer::AddTrace(); } ProgramException::ProgramException(const char* c, const GeneralMatrix& A, const GeneralMatrix& B) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); MatrixDetails(A); MatrixDetails(B); if (c) Tracer::AddTrace(); } ProgramException::ProgramException(const char* c, MatrixType a, MatrixType b) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\nMatrixTypes = "); AddMessage(a.Value()); AddMessage("; "); AddMessage(b.Value()); AddMessage("\n\n"); if (c) Tracer::AddTrace(); } VectorException::VectorException() : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: cannot convert matrix to vector\n\n"); Tracer::AddTrace(); } VectorException::VectorException(const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: cannot convert matrix to vector\n\n"); MatrixDetails(A); Tracer::AddTrace(); } NotSquareException::NotSquareException(const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: matrix is not square\n\n"); MatrixDetails(A); Tracer::AddTrace(); } NotSquareException::NotSquareException() : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: matrix is not square\n\n"); Tracer::AddTrace(); } SubMatrixDimensionException::SubMatrixDimensionException() : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: incompatible submatrix dimension\n\n"); Tracer::AddTrace(); } IncompatibleDimensionsException::IncompatibleDimensionsException() : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: incompatible dimensions\n\n"); Tracer::AddTrace(); } IncompatibleDimensionsException::IncompatibleDimensionsException (const GeneralMatrix& A, const GeneralMatrix& B) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: incompatible dimensions\n\n"); MatrixDetails(A); MatrixDetails(B); Tracer::AddTrace(); } NotDefinedException::NotDefinedException(const char* op, const char* matrix) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(op); AddMessage(" not defined for "); AddMessage(matrix); AddMessage("\n\n"); Tracer::AddTrace(); } CannotBuildException::CannotBuildException(const char* matrix) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: cannot build matrix type "); AddMessage(matrix); AddMessage("\n\n"); Tracer::AddTrace(); } IndexException::IndexException(int i, const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: index error: requested index = "); AddInt(i); AddMessage("\n\n"); MatrixDetails(A); Tracer::AddTrace(); } IndexException::IndexException(int i, int j, const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: index error: requested indices = "); AddInt(i); AddMessage(", "); AddInt(j); AddMessage("\n\n"); MatrixDetails(A); Tracer::AddTrace(); } IndexException::IndexException(int i, const GeneralMatrix& A, bool) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: element error: requested index (wrt 0) = "); AddInt(i); AddMessage("\n\n"); MatrixDetails(A); Tracer::AddTrace(); } IndexException::IndexException(int i, int j, const GeneralMatrix& A, bool) : Logic_error() { Select = BaseException::Select; AddMessage( "detected by Newmat: element error: requested indices (wrt 0) = "); AddInt(i); AddMessage(", "); AddInt(j); AddMessage("\n\n"); MatrixDetails(A); Tracer::AddTrace(); } InternalException::InternalException(const char* c) : Logic_error() { Select = BaseException::Select; AddMessage("internal error detected by Newmat: please inform author\n"); AddMessage(c); AddMessage("\n\n"); Tracer::AddTrace(); } /************************* ExeCounter functions *****************************/ #ifdef DO_REPORT int ExeCounter::nreports; // will be set to zero ExeCounter::ExeCounter(int xl, int xf) : line(xl), fileid(xf), nexe(0) {} ExeCounter::~ExeCounter() { nreports++; std::cout << "REPORT " << std::setw(6) << nreports << " " << std::setw(6) << fileid << " " << std::setw(6) << line << " " << std::setw(6) << nexe << "\n"; } #endif /**************************** error handler *******************************/ void MatrixErrorNoSpace(const void* v) { if (!v) Throw(Bad_alloc()); } // throw exception if v is null /************************* miscellanous errors ***************************/ void CroutMatrix::GetRow(MatrixRowCol&) { Throw(NotDefinedException("GetRow","Crout")); } void CroutMatrix::GetCol(MatrixRowCol&) { Throw(NotDefinedException("GetCol","Crout")); } void BandLUMatrix::GetRow(MatrixRowCol&) { Throw(NotDefinedException("GetRow","BandLUMatrix")); } void BandLUMatrix::GetCol(MatrixRowCol&) { Throw(NotDefinedException("GetCol","BandLUMatrix")); } void BaseMatrix::IEQND() const { Throw(NotDefinedException("inequalities", "matrices")); } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmatnl.cpp000066400000000000000000000162251352751253100203450ustar00rootroot00000000000000//$$ newmatnl.cpp Non-linear optimisation // Copyright (C) 1993,4,5,6: R B Davies #define WANT_MATH #define WANT_STREAM #include #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif using namespace std; void FindMaximum2::Fit(ColumnVector& Theta, int n_it) { Tracer tr("FindMaximum2::Fit"); enum State {Start, Restart, Continue, Interpolate, Extrapolate, Fail, Convergence}; State TheState = Start; Real z,w,x,x2,g,l1,l2,l3,d1,d2=0,d3; ColumnVector Theta1, Theta2, Theta3; int np = Theta.Nrows(); ColumnVector H1(np), H3, HP(np), K, K1(np); bool oorg, conv; int counter = 0; Theta1 = Theta; HP = 0.0; g = 0.0; // This is really a set of gotos and labels, but they do not work // correctly in AT&T C++ and Sun 4.01 C++. for(;;) { switch (TheState) { case Start: tr.ReName("FindMaximum2::Fit/Start"); Value(Theta1, true, l1, oorg); if (oorg) Throw(ProgramException("invalid starting value\n")); case Restart: tr.ReName("FindMaximum2::Fit/ReStart"); conv = NextPoint(H1, d1); if (conv) { TheState = Convergence; break; } if (counter++ > n_it) { TheState = Fail; break; } z = 1.0 / sqrt(d1); H3 = H1 * z; K = (H3 - HP) * g; HP = H3; g = 0.0; // de-activate to use curved projection if (g==0.0) K1 = 0.0; else K1 = K * 0.2 + K1 * 0.6; // (K - K1) * alpha + K1 * (1 - alpha) // = K * alpha + K1 * (1 - 2 * alpha) K = K1 * d1; g = z; case Continue: tr.ReName("FindMaximum2::Fit/Continue"); Theta2 = Theta1 + H1 + K; Value(Theta2, false, l2, oorg); if (counter++ > n_it) { TheState = Fail; break; } if (oorg) { H1 *= 0.5; K *= 0.25; d1 *= 0.5; g *= 2.0; TheState = Continue; break; } d2 = LastDerivative(H1 + K * 2.0); case Interpolate: tr.ReName("FindMaximum2::Fit/Interpolate"); z = d1 + d2 - 3.0 * (l2 - l1); w = z * z - d1 * d2; if (w < 0.0) { TheState = Extrapolate; break; } w = z + sqrt(w); if (1.5 * w + d1 < 0.0) { TheState = Extrapolate; break; } if (d2 > 0.0 && l2 > l1 && w > 0.0) { TheState = Extrapolate; break; } x = d1 / (w + d1); x2 = x * x; g /= x; Theta3 = Theta1 + H1 * x + K * x2; Value(Theta3, true, l3, oorg); if (counter++ > n_it) { TheState = Fail; break; } if (oorg) { if (x <= 1.0) { x *= 0.5; x2 = x*x; g *= 2.0; d1 *= x; H1 *= x; K *= x2; } else { x = 0.5 * (x-1.0); x2 = x*x; Theta1 = Theta2; H1 = (H1 + K * 2.0) * x; K *= x2; g = 0.0; d1 = x * d2; l1 = l2; } TheState = Continue; break; } if (l3 >= l1 && l3 >= l2) { Theta1 = Theta3; l1 = l3; TheState = Restart; break; } d3 = LastDerivative(H1 + K * 2.0); if (l1 > l2) { H1 *= x; K *= x2; Theta2 = Theta3; d1 *= x; d2 = d3*x; } else { Theta1 = Theta2; Theta2 = Theta3; x -= 1.0; x2 = x*x; g = 0.0; H1 = (H1 + K * 2.0) * x; K *= x2; l1 = l2; l2 = l3; d1 = x*d2; d2 = x*d3; if (d1 <= 0.0) { TheState = Start; break; } } TheState = Interpolate; break; case Extrapolate: tr.ReName("FindMaximum2::Fit/Extrapolate"); Theta1 = Theta2; g = 0.0; K *= 4.0; H1 = (H1 * 2.0 + K); d1 = 2.0 * d2; l1 = l2; TheState = Continue; break; case Fail: Throw(ConvergenceException(Theta)); case Convergence: Theta = Theta1; return; } } } void NonLinearLeastSquares::Value (const ColumnVector& Parameters, bool, Real& v, bool& oorg) { Tracer tr("NonLinearLeastSquares::Value"); Y.ReSize(n_obs); X.ReSize(n_obs,n_param); // put the fitted values in Y, the derivatives in X. Pred.Set(Parameters); if (!Pred.IsValid()) { oorg=true; return; } for (int i=1; i<=n_obs; i++) { Y(i) = Pred(i); X.Row(i) = Pred.Derivatives(); } if (!Pred.IsValid()) { oorg=true; return; } // check afterwards as well Y = *DataPointer - Y; Real ssq = Y.SumSquare(); errorvar = ssq / (n_obs - n_param); cout << endl; cout << setw(15) << setprecision(10) << " " << errorvar; Derivs = Y.t() * X; // get the derivative and stash it oorg = false; v = -0.5 * ssq; } bool NonLinearLeastSquares::NextPoint(ColumnVector& Adj, Real& test) { Tracer tr("NonLinearLeastSquares::NextPoint"); QRZ(X, U); QRZ(X, Y, M); // do the QR decomposition test = M.SumSquare(); cout << " " << setw(15) << setprecision(10) << test << " " << Y.SumSquare() / (n_obs - n_param); Adj = U.i() * M; if (test < errorvar * criterion) return true; else return false; } Real NonLinearLeastSquares::LastDerivative(const ColumnVector& H) { return (Derivs * H).AsScalar(); } void NonLinearLeastSquares::Fit(const ColumnVector& Data, ColumnVector& Parameters) { Tracer tr("NonLinearLeastSquares::Fit"); n_param = Parameters.Nrows(); n_obs = Data.Nrows(); DataPointer = &Data; FindMaximum2::Fit(Parameters, Lim); cout << "\nConverged" << endl; } void NonLinearLeastSquares::MakeCovariance() { if (Covariance.Nrows()==0) { UpperTriangularMatrix UI = U.i(); Covariance << UI * UI.t() * errorvar; SE << Covariance; // get diagonals for (int i = 1; i<=n_param; i++) SE(i) = sqrt(SE(i)); } } void NonLinearLeastSquares::GetStandardErrors(ColumnVector& SEX) { MakeCovariance(); SEX = SE.AsColumn(); } void NonLinearLeastSquares::GetCorrelations(SymmetricMatrix& Corr) { MakeCovariance(); Corr << SE.i() * Covariance * SE.i(); } void NonLinearLeastSquares::GetHatDiagonal(DiagonalMatrix& Hat) const { Hat.ReSize(n_obs); for (int i = 1; i<=n_obs; i++) Hat(i) = X.Row(i).SumSquare(); } // the MLE_D_FI routines void MLE_D_FI::Value (const ColumnVector& Parameters, bool wg, Real& v, bool& oorg) { Tracer tr("MLE_D_FI::Value"); if (!LL.IsValid(Parameters,wg)) { oorg=true; return; } v = LL.LogLikelihood(); if (!LL.IsValid()) { oorg=true; return; } // check validity again cout << endl; cout << setw(20) << setprecision(10) << v; oorg = false; Derivs = LL.Derivatives(); // Get derivatives } bool MLE_D_FI::NextPoint(ColumnVector& Adj, Real& test) { Tracer tr("MLE_D_FI::NextPoint"); SymmetricMatrix FI = LL.FI(); LT = Cholesky(FI); ColumnVector Adj1 = LT.i() * Derivs; Adj = LT.t().i() * Adj1; test = SumSquare(Adj1); cout << " " << setw(20) << setprecision(10) << test; return (test < Criterion); } Real MLE_D_FI::LastDerivative(const ColumnVector& H) { return (Derivs.t() * H).AsScalar(); } void MLE_D_FI::Fit(ColumnVector& Parameters) { Tracer tr("MLE_D_FI::Fit"); FindMaximum2::Fit(Parameters,Lim); cout << "\nConverged" << endl; } void MLE_D_FI::MakeCovariance() { if (Covariance.Nrows()==0) { LowerTriangularMatrix LTI = LT.i(); Covariance << LTI.t() * LTI; SE << Covariance; // get diagonal int n = Covariance.Nrows(); for (int i=1; i <= n; i++) SE(i) = sqrt(SE(i)); } } void MLE_D_FI::GetStandardErrors(ColumnVector& SEX) { MakeCovariance(); SEX = SE.AsColumn(); } void MLE_D_FI::GetCorrelations(SymmetricMatrix& Corr) { MakeCovariance(); Corr << SE.i() * Covariance * SE.i(); } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/newmatrm.cpp000066400000000000000000000122561352751253100203520ustar00rootroot00000000000000//$$newmatrm.cpp rectangular matrix operations // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,12); ++ExeCount; } #else #define REPORT {} #endif // operations on rectangular matrices void RectMatrixRow::Reset (const Matrix& M, int row, int skip, int length) { REPORT RectMatrixRowCol::Reset ( M.Store()+row*M.Ncols()+skip, length, 1, M.Ncols() ); } void RectMatrixRow::Reset (const Matrix& M, int row) { REPORT RectMatrixRowCol::Reset( M.Store()+row*M.Ncols(), M.Ncols(), 1, M.Ncols() ); } void RectMatrixCol::Reset (const Matrix& M, int skip, int col, int length) { REPORT RectMatrixRowCol::Reset ( M.Store()+col+skip*M.Ncols(), length, M.Ncols(), 1 ); } void RectMatrixCol::Reset (const Matrix& M, int col) { REPORT RectMatrixRowCol::Reset( M.Store()+col, M.Nrows(), M.Ncols(), 1 ); } Real RectMatrixRowCol::SumSquare() const { REPORT long_Real sum = 0.0; int i = n; Real* s = store; int d = spacing; // while (i--) { sum += (long_Real)*s * *s; s += d; } if (i) for(;;) { sum += (long_Real)*s * *s; if (!(--i)) break; s += d; } return (Real)sum; } Real RectMatrixRowCol::operator*(const RectMatrixRowCol& rmrc) const { REPORT long_Real sum = 0.0; int i = n; Real* s = store; int d = spacing; Real* s1 = rmrc.store; int d1 = rmrc.spacing; if (i!=rmrc.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in *")); } // while (i--) { sum += (long_Real)*s * *s1; s += d; s1 += d1; } if (i) for(;;) { sum += (long_Real)*s * *s1; if (!(--i)) break; s += d; s1 += d1; } return (Real)sum; } void RectMatrixRowCol::AddScaled(const RectMatrixRowCol& rmrc, Real r) { REPORT int i = n; Real* s = store; int d = spacing; Real* s1 = rmrc.store; int d1 = rmrc.spacing; if (i!=rmrc.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in AddScaled")); } // while (i--) { *s += *s1 * r; s += d; s1 += d1; } if (i) for (;;) { *s += *s1 * r; if (!(--i)) break; s += d; s1 += d1; } } void RectMatrixRowCol::Divide(const RectMatrixRowCol& rmrc, Real r) { REPORT int i = n; Real* s = store; int d = spacing; Real* s1 = rmrc.store; int d1 = rmrc.spacing; if (i!=rmrc.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in Divide")); } // while (i--) { *s = *s1 / r; s += d; s1 += d1; } if (i) for (;;) { *s = *s1 / r; if (!(--i)) break; s += d; s1 += d1; } } void RectMatrixRowCol::Divide(Real r) { REPORT int i = n; Real* s = store; int d = spacing; // while (i--) { *s /= r; s += d; } if (i) for (;;) { *s /= r; if (!(--i)) break; s += d; } } void RectMatrixRowCol::Negate() { REPORT int i = n; Real* s = store; int d = spacing; // while (i--) { *s = - *s; s += d; } if (i) for (;;) { *s = - *s; if (!(--i)) break; s += d; } } void RectMatrixRowCol::Zero() { REPORT int i = n; Real* s = store; int d = spacing; // while (i--) { *s = 0.0; s += d; } if (i) for (;;) { *s = 0.0; if (!(--i)) break; s += d; } } void ComplexScale(RectMatrixCol& U, RectMatrixCol& V, Real x, Real y) { REPORT int n = U.n; if (n != V.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in ComplexScale")); } Real* u = U.store; Real* v = V.store; int su = U.spacing; int sv = V.spacing; //while (n--) //{ // Real z = *u * x - *v * y; *v = *u * y + *v * x; *u = z; // u += su; v += sv; //} if (n) for (;;) { Real z = *u * x - *v * y; *v = *u * y + *v * x; *u = z; if (!(--n)) break; u += su; v += sv; } } void Rotate(RectMatrixCol& U, RectMatrixCol& V, Real tau, Real s) { REPORT // (U, V) = (U, V) * (c, s) where tau = s/(1+c), c^2 + s^2 = 1 int n = U.n; if (n != V.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in Rotate")); } Real* u = U.store; Real* v = V.store; int su = U.spacing; int sv = V.spacing; //while (n--) //{ // Real zu = *u; Real zv = *v; // *u -= s * (zv + zu * tau); *v += s * (zu - zv * tau); // u += su; v += sv; //} if (n) for(;;) { Real zu = *u; Real zv = *v; *u -= s * (zv + zu * tau); *v += s * (zu - zv * tau); if (!(--n)) break; u += su; v += sv; } } // misc procedures for numerical things Real pythag(Real f, Real g, Real& c, Real& s) // return z=std::sqrt(f*f+g*g), c=f/z, s=g/z // set c=1,s=0 if z==0 // avoid floating point overflow or divide by zero { if (f==0 && g==0) { c=1.0; s=0.0; return 0.0; } Real af = f>=0 ? f : -f; Real ag = g>=0 ? g : -g; if (ag #include #include #include #ifdef use_namespace namespace RBD_COMMON { #endif R1_R1::~R1_R1() { } void R1_R1::Set(Real X) { if ((!minXinf && X <= minX) || (!maxXinf && X >= maxX)) Throw(SolutionException("X value out of range")); x = X; xSet = true; } R1_R1::operator Real() { if (!xSet) Throw(SolutionException("Value of X not set")); Real y = operator()(); return y; } unsigned long SolutionException::Select; SolutionException::SolutionException(const char* a_what) : Exception() { Select = Exception::Select; AddMessage("Error detected by solution package\n"); AddMessage(a_what); AddMessage("\n"); if (a_what) Tracer::AddTrace(); }; inline Real square(Real x) { return x*x; } void OneDimSolve::LookAt(int V) { lim--; if (!lim) Throw(SolutionException("Does not converge")); Last = V; Real yy = function(x[V]) - YY; Finish = (std::fabs(yy) <= accY) || (Captured && std::fabs(x[L]-x[U]) <= accX ); y[V] = vpol*yy; } void OneDimSolve::HFlip() { hpol=-hpol; State(U,C,L); } void OneDimSolve::VFlip() { vpol = -vpol; y[0] = -y[0]; y[1] = -y[1]; y[2] = -y[2]; } void OneDimSolve::Flip() { hpol=-hpol; vpol=-vpol; State(U,C,L); y[0] = -y[0]; y[1] = -y[1]; y[2] = -y[2]; } void OneDimSolve::State(int I, int J, int K) { L=I; C=J; U=K; } void OneDimSolve::Linear(int I, int J, int K) { x[J] = (x[I]*y[K] - x[K]*y[I])/(y[K] - y[I]); // cout << "Linear\n"; } void OneDimSolve::Quadratic(int I, int J, int K) { // result to overwrite I Real YJK, YIK, YIJ, XKI, XKJ; YJK = y[J] - y[K]; YIK = y[I] - y[K]; YIJ = y[I] - y[J]; XKI = (x[K] - x[I]); XKJ = (x[K]*y[J] - x[J]*y[K])/YJK; if ( square(YJK/YIK)>(x[K] - x[J])/XKI || square(YIJ/YIK)>(x[J] - x[I])/XKI ) { x[I] = XKJ; // cout << "Quadratic - exceptional\n"; } else { XKI = (x[K]*y[I] - x[I]*y[K])/YIK; x[I] = (XKJ*y[I] - XKI*y[J])/YIJ; // cout << "Quadratic - normal\n"; } } Real OneDimSolve::Solve(Real Y, Real X, Real Dev, int Lim) { enum Loop { start, captured1, captured2, binary, finish }; Tracer et("OneDimSolve::Solve"); lim=Lim; Captured = false; if (Dev==0.0) Throw(SolutionException("Dev is zero")); L=0; C=1; U=2; vpol=1; hpol=1; y[C]=0.0; y[U]=0.0; if (Dev<0.0) { hpol=-1; Dev = -Dev; } YY=Y; // target value x[L] = X; // initial trial value if (!function.IsValid(X)) Throw(SolutionException("Starting value is invalid")); Loop TheLoop = start; for (;;) { switch (TheLoop) { case start: LookAt(L); if (Finish) { TheLoop = finish; break; } if (y[L]>0.0) VFlip(); // so Y[L] < 0 x[U] = X + Dev * hpol; if (!function.maxXinf && x[U] > function.maxX) x[U] = (function.maxX + X) / 2.0; if (!function.minXinf && x[U] < function.minX) x[U] = (function.minX + X) / 2.0; LookAt(U); if (Finish) { TheLoop = finish; break; } if (y[U] > 0.0) { TheLoop = captured1; Captured = true; break; } if (y[U] == y[L]) Throw(SolutionException("Function is flat")); if (y[U] < y[L]) HFlip(); // Change direction State(L,U,C); for (i=0; i<20; i++) { // cout << "Searching for crossing point\n"; // Have L C then crossing point, Y[L] function.maxX) x[U] = (function.maxX + x[C]) / 2.0; if (!function.minXinf && x[U] < function.minX) x[U] = (function.minX + x[C]) / 2.0; LookAt(U); if (Finish) { TheLoop = finish; break; } if (y[U] > 0) { TheLoop = captured2; Captured = true; break; } if (y[U] < y[C]) Throw(SolutionException("Function is not monotone")); Dev *= 2.0; State(C,U,L); } if (TheLoop != start ) break; Throw(SolutionException("Cannot locate a crossing point")); case captured1: // cout << "Captured - 1\n"; // We have 2 points L and U with crossing between them Linear(L,C,U); // linear interpolation // - result to C LookAt(C); if (Finish) { TheLoop = finish; break; } if (y[C] > 0.0) Flip(); // Want y[C] < 0 if (y[C] < 0.5*y[L]) { State(C,L,U); TheLoop = binary; break; } case captured2: // cout << "Captured - 2\n"; // We have L,C before crossing, U after crossing Quadratic(L,C,U); // quad interpolation // - result to L State(C,L,U); if ((x[C] - x[L])*hpol <= 0.0 || (x[C] - x[U])*hpol >= 0.0) { TheLoop = captured1; break; } LookAt(C); if (Finish) { TheLoop = finish; break; } // cout << "Through first stage\n"; if (y[C] > 0.0) Flip(); if (y[C] > 0.5*y[L]) { TheLoop = captured2; break; } else { State(C,L,U); TheLoop = captured1; break; } case binary: // We have L, U around crossing - do binary search // cout << "Binary\n"; for (i=3; i; i--) { x[C] = 0.5*(x[L]+x[U]); LookAt(C); if (Finish) { TheLoop = finish; break; } if (y[C]>0.0) State(L,U,C); else State(C,L,U); } if (TheLoop != binary) break; TheLoop = captured1; break; case finish: return x[Last]; } } } bool R1_R1::IsValid(Real X) { Set(X); return (minXinf || x > minX) && (maxXinf || x < maxX); } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/sort.cpp000066400000000000000000000165731352751253100175150ustar00rootroot00000000000000//$$ sort.cpp Sorting // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,13); ++ExeCount; } #else #define REPORT {} #endif /******************************** Quick sort ********************************/ // Quicksort. // Essentially the method described in Sedgewick s algorithms in C++ // My version is still partially recursive, unlike Segewick s, but the // smallest segment of each split is used in the recursion, so it should // not overlead the stack. // If the process does not seems to be converging an exception is thrown. #define DoSimpleSort 17 // when to switch to insert sort #define MaxDepth 50 // maximum recursion depth static void MyQuickSortDescending(Real* first, Real* last, int depth); static void InsertionSortDescending(Real* first, const int length, int guard); static Real SortThreeDescending(Real* a, Real* b, Real* c); static void MyQuickSortAscending(Real* first, Real* last, int depth); static void InsertionSortAscending(Real* first, const int length, int guard); void SortDescending(GeneralMatrix& GM) { REPORT Tracer et("QuickSortDescending"); Real* data = GM.Store(); int max = GM.Storage(); if (max > DoSimpleSort) MyQuickSortDescending(data, data + max - 1, 0); InsertionSortDescending(data, max, DoSimpleSort); } static Real SortThreeDescending(Real* a, Real* b, Real* c) { // sort *a, *b, *c; return *b; optimise for already sorted if (*a >= *b) { if (*b >= *c) { REPORT return *b; } else if (*a >= *c) { REPORT Real x = *c; *c = *b; *b = x; return x; } else { REPORT Real x = *a; *a = *c; *c = *b; *b = x; return x; } } else if (*c >= *b) { REPORT Real x = *c; *c = *a; *a = x; return *b; } else if (*a >= *c) { REPORT Real x = *a; *a = *b; *b = x; return x; } else { REPORT Real x = *c; *c = *a; *a = *b; *b = x; return x; } } static void InsertionSortDescending(Real* first, const int length, int guard) // guard gives the length of the sequence to scan to find first // element (eg = length) { REPORT if (length <= 1) return; // scan for first element Real* f = first; Real v = *f; Real* h = f; if (guard > length) { REPORT guard = length; } int i = guard - 1; while (i--) if (v < *(++f)) { v = *f; h = f; } *h = *first; *first = v; // do the sort i = length - 1; f = first; while (i--) { Real* g = f++; h = f; v = *h; while (*g < v) *h-- = *g--; *h = v; } } static void MyQuickSortDescending(Real* first, Real* last, int depth) { REPORT for (;;) { const int length = last - first + 1; if (length < DoSimpleSort) { REPORT return; } if (depth++ > MaxDepth) Throw(ConvergenceException("QuickSortDescending fails: ")); Real* centre = first + length/2; const Real test = SortThreeDescending(first, centre, last); Real* f = first; Real* l = last; for (;;) { while (*(++f) > test) {} while (*(--l) < test) {} if (l <= f) break; const Real temp = *f; *f = *l; *l = temp; } if (f > centre) { REPORT MyQuickSortDescending(l+1, last, depth); last = f-1; } else { REPORT MyQuickSortDescending(first, f-1, depth); first = l+1; } } } void SortAscending(GeneralMatrix& GM) { REPORT Tracer et("QuickSortAscending"); Real* data = GM.Store(); int max = GM.Storage(); if (max > DoSimpleSort) MyQuickSortAscending(data, data + max - 1, 0); InsertionSortAscending(data, max, DoSimpleSort); } static void InsertionSortAscending(Real* first, const int length, int guard) // guard gives the length of the sequence to scan to find first // element (eg guard = length) { REPORT if (length <= 1) return; // scan for first element Real* f = first; Real v = *f; Real* h = f; if (guard > length) { REPORT guard = length; } int i = guard - 1; while (i--) if (v > *(++f)) { v = *f; h = f; } *h = *first; *first = v; // do the sort i = length - 1; f = first; while (i--) { Real* g = f++; h = f; v = *h; while (*g > v) *h-- = *g--; *h = v; } } static void MyQuickSortAscending(Real* first, Real* last, int depth) { REPORT for (;;) { const int length = last - first + 1; if (length < DoSimpleSort) { REPORT return; } if (depth++ > MaxDepth) Throw(ConvergenceException("QuickSortAscending fails: ")); Real* centre = first + length/2; const Real test = SortThreeDescending(last, centre, first); Real* f = first; Real* l = last; for (;;) { while (*(++f) < test) {} while (*(--l) > test) {} if (l <= f) break; const Real temp = *f; *f = *l; *l = temp; } if (f > centre) { REPORT MyQuickSortAscending(l+1, last, depth); last = f-1; } else { REPORT MyQuickSortAscending(first, f-1, depth); first = l+1; } } } //********* sort diagonal matrix & rearrange matrix columns **************** // used by SVD // these are for sorting singular values - should be updated with faster // sorts that handle exchange of columns better // however time is probably not significant compared with SVD time void SortSV(DiagonalMatrix& D, Matrix& U, bool ascending) { REPORT Tracer trace("SortSV_DU"); int m = U.Nrows(); int n = U.Ncols(); if (n != D.Nrows()) Throw(IncompatibleDimensionsException(D,U)); Real* u = U.Store(); for (int i=0; i p) { k = j; p = D.element(j); } } } if (k != i) { D.element(k) = D.element(i); D.element(i) = p; int j = m; Real* uji = u + i; Real* ujk = u + k; if (j) for(;;) { p = *uji; *uji = *ujk; *ujk = p; if (!(--j)) break; uji += n; ujk += n; } } } } void SortSV(DiagonalMatrix& D, Matrix& U, Matrix& V, bool ascending) { REPORT Tracer trace("SortSV_DUV"); int mu = U.Nrows(); int mv = V.Nrows(); int n = D.Nrows(); if (n != U.Ncols()) Throw(IncompatibleDimensionsException(D,U)); if (n != V.Ncols()) Throw(IncompatibleDimensionsException(D,V)); Real* u = U.Store(); Real* v = V.Store(); for (int i=0; i p) { k = j; p = D.element(j); } } } if (k != i) { D.element(k) = D.element(i); D.element(i) = p; Real* uji = u + i; Real* ujk = u + k; Real* vji = v + i; Real* vjk = v + k; int j = mu; if (j) for(;;) { p = *uji; *uji = *ujk; *ujk = p; if (!(--j)) break; uji += n; ujk += n; } j = mv; if (j) for(;;) { p = *vji; *vji = *vjk; *vjk = p; if (!(--j)) break; vji += n; vjk += n; } } } } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/submat.cpp000066400000000000000000000230011352751253100200010ustar00rootroot00000000000000//$$ submat.cpp submatrices // Copyright (C) 1991,2,3,4: R B Davies #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,11); ++ExeCount; } #else #define REPORT {} #endif /****************************** submatrices *********************************/ GetSubMatrix BaseMatrix::SubMatrix(int first_row, int last_row, int first_col, int last_col) const { REPORT Tracer tr("SubMatrix"); int a = first_row - 1; int b = last_row - first_row + 1; int c = first_col - 1; int d = last_col - first_col + 1; if (a<0 || b<0 || c<0 || d<0) Throw(SubMatrixDimensionException()); // allow zero rows or columns return GetSubMatrix(this, a, b, c, d, false); } GetSubMatrix BaseMatrix::SymSubMatrix(int first_row, int last_row) const { REPORT Tracer tr("SubMatrix(symmetric)"); int a = first_row - 1; int b = last_row - first_row + 1; if (a<0 || b<0) Throw(SubMatrixDimensionException()); // allow zero rows or columns return GetSubMatrix( this, a, b, a, b, true); } GetSubMatrix BaseMatrix::Row(int first_row) const { REPORT Tracer tr("SubMatrix(row)"); int a = first_row - 1; if (a<0) Throw(SubMatrixDimensionException()); return GetSubMatrix(this, a, 1, 0, -1, false); } GetSubMatrix BaseMatrix::Rows(int first_row, int last_row) const { REPORT Tracer tr("SubMatrix(rows)"); int a = first_row - 1; int b = last_row - first_row + 1; if (a<0 || b<0) Throw(SubMatrixDimensionException()); // allow zero rows or columns return GetSubMatrix(this, a, b, 0, -1, false); } GetSubMatrix BaseMatrix::Column(int first_col) const { REPORT Tracer tr("SubMatrix(column)"); int c = first_col - 1; if (c<0) Throw(SubMatrixDimensionException()); return GetSubMatrix(this, 0, -1, c, 1, false); } GetSubMatrix BaseMatrix::Columns(int first_col, int last_col) const { REPORT Tracer tr("SubMatrix(columns)"); int c = first_col - 1; int d = last_col - first_col + 1; if (c<0 || d<0) Throw(SubMatrixDimensionException()); // allow zero rows or columns return GetSubMatrix(this, 0, -1, c, d, false); } void GetSubMatrix::SetUpLHS() { REPORT Tracer tr("SubMatrix(LHS)"); const BaseMatrix* bm1 = bm; GeneralMatrix* gm1 = ((BaseMatrix*&)bm)->Evaluate(); if ((BaseMatrix*)gm1!=bm1) Throw(ProgramException("Invalid LHS")); if (row_number < 0) row_number = gm1->Nrows(); if (col_number < 0) col_number = gm1->Ncols(); if (row_skip+row_number > gm1->Nrows() || col_skip+col_number > gm1->Ncols()) Throw(SubMatrixDimensionException()); } void GetSubMatrix::operator<<(const BaseMatrix& bmx) { REPORT Tracer tr("SubMatrix(<<)"); GeneralMatrix* gmx = 0; Try { SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) Throw(IncompatibleDimensionsException()); MatrixRow mrx(gmx, LoadOnEntry); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Copy(mrx); mr.Next(); mrx.Next(); } gmx->tDelete(); } CatchAll { if (gmx) gmx->tDelete(); ReThrow; } } void GetSubMatrix::operator=(const BaseMatrix& bmx) { REPORT Tracer tr("SubMatrix(=)"); GeneralMatrix* gmx = 0; // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) Throw(IncompatibleDimensionsException()); LoadAndStoreFlag lasf = ( row_skip == col_skip && gm->Type().IsSymmetric() && gmx->Type().IsSymmetric() ) ? LoadOnEntry+DirectPart : LoadOnEntry; MatrixRow mrx(gmx, lasf); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.CopyCheck(mrx); mr.Next(); mrx.Next(); } gmx->tDelete(); } CatchAll { if (gmx) gmx->tDelete(); ReThrow; } } void GetSubMatrix::operator<<(const Real* r) { REPORT Tracer tr("SubMatrix(< gm->Nrows() || col_skip+col_number > gm->Ncols()) Throw(SubMatrixDimensionException()); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Copy(r); mr.Next(); } } void GetSubMatrix::operator<<(const int* r) { REPORT Tracer tr("SubMatrix(< gm->Nrows() || col_skip+col_number > gm->Ncols()) Throw(SubMatrixDimensionException()); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Copy(r); mr.Next(); } } void GetSubMatrix::operator=(Real r) { REPORT Tracer tr("SubMatrix(=Real)"); SetUpLHS(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Copy(r); mr.Next(); } } void GetSubMatrix::Inject(const GeneralMatrix& gmx) { REPORT Tracer tr("SubMatrix(inject)"); SetUpLHS(); if (row_number != gmx.Nrows() || col_number != gmx.Ncols()) Throw(IncompatibleDimensionsException()); MatrixRow mrx((GeneralMatrix*)(&gmx), LoadOnEntry); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Inject(mrx); mr.Next(); mrx.Next(); } } void GetSubMatrix::operator+=(const BaseMatrix& bmx) { REPORT Tracer tr("SubMatrix(+=)"); GeneralMatrix* gmx = 0; // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) Throw(IncompatibleDimensionsException()); MatrixRow mrx(gmx, LoadOnEntry); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Check(mrx); // check for loss of info sub.Add(mrx); mr.Next(); mrx.Next(); } gmx->tDelete(); } CatchAll { if (gmx) gmx->tDelete(); ReThrow; } } void GetSubMatrix::operator-=(const BaseMatrix& bmx) { REPORT Tracer tr("SubMatrix(-=)"); GeneralMatrix* gmx = 0; // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) Throw(IncompatibleDimensionsException()); MatrixRow mrx(gmx, LoadOnEntry); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Check(mrx); // check for loss of info sub.Sub(mrx); mr.Next(); mrx.Next(); } gmx->tDelete(); } CatchAll { if (gmx) gmx->tDelete(); ReThrow; } } void GetSubMatrix::operator+=(Real r) { REPORT Tracer tr("SubMatrix(+= or -= Real)"); // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Check(); // check for loss of info sub.Add(r); mr.Next(); } } CatchAll { ReThrow; } } void GetSubMatrix::operator*=(Real r) { REPORT Tracer tr("SubMatrix(*= or /= Real)"); // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Multiply(r); mr.Next(); } } CatchAll { ReThrow; } } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/svd.cpp000066400000000000000000000137331352751253100173150ustar00rootroot00000000000000//$$svd.cpp singular value decomposition // Copyright (C) 1991,2,3,4,5: R B Davies // Updated 17 July, 1995 #define WANT_MATH #include #include #include #include #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,15); ++ExeCount; } #else #define REPORT {} #endif void SVD(const Matrix& A, DiagonalMatrix& Q, Matrix& U, Matrix& V, bool withU, bool withV) // from Wilkinson and Reinsch: "Handbook of Automatic Computation" { REPORT Tracer trace("SVD"); Real eps = FloatingPointPrecision::Epsilon(); Real tol = FloatingPointPrecision::Minimum()/eps; int m = A.Nrows(); int n = A.Ncols(); if (m= no. Cols", A)); if (withV && &U == &V) Throw(ProgramException("Need different matrices for U and V", U, V)); U = A; Real g = 0.0; Real f,h; Real x = 0.0; int i; RowVector E(n); RectMatrixRow EI(E,0); Q.ReSize(n); RectMatrixCol UCI(U,0); RectMatrixRow URI(U,0,1,n-1); if (n) for (i=0;;) { EI.First() = g; Real ei = g; EI.Right(); Real s = UCI.SumSquare(); if (s=0; i--) { VCI.Left(); if (g!=0.0) { VCI.Divide(URI, URI.First()*g); int j = n-i; RectMatrixCol VCJ = VCI; while (--j) { VCJ.Right(); VCJ.AddScaled( VCI, (URI*VCJ) ); } } VCI.Zero(); VCI.Up(); VCI.First() = 1.0; g=E.element(i); if (i==0) break; URI.UpDiag(); } } if (withU) { REPORT for (i=n-1; i>=0; i--) { g = Q.element(i); URI.Reset(U,i,i+1,n-i-1); URI.Zero(); if (g!=0.0) { h=UCI.First()*g; int j=n-i; RectMatrixCol UCJ = UCI; while (--j) { UCJ.Right(); UCI.Down(); UCJ.Down(); Real s = UCI*UCJ; UCI.Up(); UCJ.Up(); UCJ.AddScaled(UCI,s/h); } UCI.Divide(g); } else UCI.Zero(); UCI.First() += 1.0; if (i==0) break; UCI.UpDiag(); } } eps *= x; for (int k=n-1; k>=0; k--) { Real z = -FloatingPointPrecision::Maximum(); // to keep Gnu happy Real y; int limit = 50; int l = 0; while (limit--) { Real c, s; int i; int l1=k; bool tfc=false; for (l=k; l>=0; l--) { // if (fabs(E.element(l))<=eps) goto test_f_convergence; if (fabs(E.element(l))<=eps) { REPORT tfc=true; break; } if (fabs(Q.element(l-1))<=eps) { REPORT l1=l; break; } REPORT } if (!tfc) { REPORT l=l1; l1=l-1; s = -1.0; c = 0.0; for (i=l; i<=k; i++) { f = - s * E.element(i); E.element(i) *= c; // if (fabs(f)<=eps) goto test_f_convergence; if (fabs(f)<=eps) { REPORT break; } g = Q.element(i); h = pythag(g,f,c,s); Q.element(i) = h; if (withU) { REPORT RectMatrixCol UCI(U,i); RectMatrixCol UCJ(U,l1); ComplexScale(UCJ, UCI, c, s); } } } // test_f_convergence: z = Q.element(k); if (l==k) goto convergence; z = Q.element(k); if (l==k) { REPORT break; } x = Q.element(l); y = Q.element(k-1); g = E.element(k-1); h = E.element(k); f = ((y-z)*(y+z) + (g-h)*(g+h)) / (2*h*y); if (f>1) { REPORT g = f * sqrt(1 + square(1/f)); } else if (f<-1) { REPORT g = -f * sqrt(1 + square(1/f)); } else { REPORT g = sqrt(f*f + 1); } { REPORT f = ((x-z)*(x+z) + h*(y / ((f<0.0) ? f-g : f+g)-h)) / x; } c = 1.0; s = 1.0; for (i=l+1; i<=k; i++) { g = E.element(i); y = Q.element(i); h = s*g; g *= c; z = pythag(f,h,c,s); E.element(i-1) = z; f = x*c + g*s; g = -x*s + g*c; h = y*s; y *= c; if (withV) { REPORT RectMatrixCol VCI(V,i); RectMatrixCol VCJ(V,i-1); ComplexScale(VCI, VCJ, c, s); } z = pythag(f,h,c,s); Q.element(i-1) = z; f = c*g + s*y; x = -s*g + c*y; if (withU) { REPORT RectMatrixCol UCI(U,i); RectMatrixCol UCJ(U,i-1); ComplexScale(UCI, UCJ, c, s); } } E.element(l) = 0.0; E.element(k) = f; Q.element(k) = x; } if (l!=k) { Throw(ConvergenceException(A)); } // convergence: if (z < 0.0) { REPORT Q.element(k) = -z; if (withV) { RectMatrixCol VCI(V,k); VCI.Negate(); } } } if (withU & withV) SortSV(Q, U, V); else if (withU) SortSV(Q, U); else if (withV) SortSV(Q, V); else SortDescending(Q); } void SVD(const Matrix& A, DiagonalMatrix& D) { REPORT Matrix U; SVD(A, D, U, U, false, false); } #ifdef use_namespace } #endif ossim-Miami-2.9.1/src/matrix/test_exc.txt000066400000000000000000000077231352751253100203760ustar00rootroot00000000000000 This tests the exception system, so you will get a long list of error messages Print a real number (may help lost memory test): 3.14159 ----------------------------------------- Incompatible dimensions An exception has been thrown Logic error:- detected by Newmat: incompatible dimensions MatrixType = Rect # Rows = 2; # Cols = 3 MatrixType = Rect # Rows = 4; # Cols = 5 Trace: AddedMatrix::Evaluate; Block A; Test. ----------------------------------------- Bad index An exception has been thrown Logic error:- detected by Newmat: index error: requested indices = 3, 3 MatrixType = Rect # Rows = 2; # Cols = 3 Trace: Block B; Test. ----------------------------------------- Illegal conversion An exception has been thrown Logic error:- detected by Newmat: Illegal Conversion MatrixTypes = Rect ; UT Trace: Block C; Test. ----------------------------------------- Invert non-square matrix - 1 An exception has been thrown Logic error:- detected by Newmat: matrix is not square MatrixType = Rect # Rows = 2; # Cols = 3 Trace: CroutMatrix; Block D; Test. ----------------------------------------- Invert non-square matrix - 2 An exception has been thrown Logic error:- detected by Newmat: matrix is not square MatrixType = Rect # Rows = 2; # Cols = 3 Trace: GeneralSolvI; InvertedMatrix::Evaluate; Block E; Test. ----------------------------------------- Non 1x1 matrix to scalar An exception has been thrown Logic error:- detected by Newmat: Cannot convert to scalar MatrixType = Rect # Rows = 2; # Cols = 3 Trace: AsScalar; Block F; Test. ----------------------------------------- Matrix to vector An exception has been thrown Logic error:- detected by Newmat: cannot convert matrix to vector MatrixType = Rect # Rows = 2; # Cols = 3 Trace: ColumnVector; Block G; Test. ----------------------------------------- Invert singular matrix An exception has been thrown Runtime error:- detected by Newmat: matrix is singular MatrixType = Crout # Rows = 2; # Cols = 2 Trace: Crout(lubksb); GeneralSolvI; InvertedMatrix::Evaluate; Block H; Test. ----------------------------------------- SubMatrix error An exception has been thrown Logic error:- detected by Newmat: incompatible submatrix dimension Trace: SubMatrix(evaluate); Block I; Test. ----------------------------------------- SubMatrix error An exception has been thrown Logic error:- detected by Newmat: incompatible submatrix dimension Trace: SubMatrix(row); Block J; Test. ----------------------------------------- Cholesky error An exception has been thrown Runtime error:- detected by Newmat: matrix not positive definite MatrixType = Sym # Rows = 50; # Cols = 50 Trace: Cholesky; Block K; Test. ----------------------------------------- Inequality error An exception has been thrown Logic error:- detected by Newmat: inequalities not defined for matrices Trace: Block L; Test. ----------------------------------------- Maximum of empty matrix An exception has been thrown Logic error:- detected by Newmat: Maximum or minimum of null matrix Trace: Block M; Test. ----------------------------------------- Incorrectly ReSizing band matrix An exception has been thrown Logic error:- detected by Newmat: UpperBandMatrix with non-zero lower band Trace: UpperBandMatrix::ReSize; Block N; Test. ----------------------------------------- Incorrectly ReSizing symmetric band matrix An exception has been thrown Logic error:- detected by Newmat: Upper and lower band-widths not equal Trace: SymmetricBandMatrix::ReSize(GM); Block M; Test. ----------------------------------------- ReSize CroutMatrix An exception has been thrown Logic error:- detected by Newmat: ReSize not defined for this type of matrix Trace: GeneralMatrix::ReSize(GM); Block O; Test. ----------------------------------------- End test (The following memory checks are probably not valid with all compilers - see documentation) Checking for lost memory: 8141636 8141636 - ok Checking for lost memory: 8141636 8141636 - ok ossim-Miami-2.9.1/src/matrix/watco_nt.mak000066400000000000000000000173771352751253100203350ustar00rootroot00000000000000everything: tmt.exe example.exe nl_ex.exe sl_ex.exe garch.exe test_exc.exe .cpp.obj: wpp386/bt=nt $*.cpp OBJ_LIB = bandmat.obj cholesky.obj evalue.obj fft.obj hholder.obj & jacobi.obj myexcept.obj newmat1.obj newmat2.obj newmat3.obj & newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj & newmat9.obj newmatex.obj newmatnl.obj newmatrm.obj solution.obj & sort.obj submat.obj svd.obj newfft.obj OBJ_T = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj & tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj & tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmt.exe: $(OBJ_T) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file tmt.obj,tmt1.obj,tmt2.obj,tmt3.obj >> link.lnk echo file tmt4.obj,tmt5.obj,tmt6.obj,tmt7.obj >> link.lnk echo file tmt8.obj,tmt9.obj,tmta.obj,tmti.obj >> link.lnk echo file tmtb.obj,tmtc.obj,tmtd.obj,tmte.obj >> link.lnk echo file tmtf.obj,tmtg.obj,tmth.obj,tmtj.obj >> link.lnk echo file tmtk.obj,tmtl.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,newfft.obj >> link.lnk echo name tmt.exe >> link.lnk echo SYSTEM nt >> link.lnk wlink @link.lnk OBJ_E = example.obj example.exe: $(OBJ_E) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,example.obj >> link.lnk echo file newmat9.obj,newfft.obj >> link.lnk echo name example.exe >> link.lnk echo SYSTEM nt >> link.lnk wlink @link.lnk OBJ_N = nl_ex.obj nl_ex.exe: $(OBJ_N) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file nl_ex.obj,newmatnl.obj,newmat9.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,newfft.obj >> link.lnk echo name nl_ex.exe >> link.lnk echo SYSTEM nt >> link.lnk wlink @link.lnk OBJ_S = sl_ex.obj sl_ex.exe: $(OBJ_S) $(OBJ_LIB) echo file sl_ex.obj,myexcept.obj,solution.obj > link.lnk echo name sl_ex.exe >> link.lnk echo SYSTEM nt >> link.lnk wlink @link.lnk OBJ_G = garch.obj garch.exe: $(OBJ_G) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file garch.obj,newmatnl.obj,newmat9.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,newfft.obj >> link.lnk echo name garch.exe >> link.lnk echo SYSTEM nt >> link.lnk wlink @link.lnk OBJ_X = test_exc.obj test_exc.exe: $(OBJ_X) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file test_exc.obj,newmatnl.obj,newmat9.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,newfft.obj >> link.lnk echo name test_exc.exe >> link.lnk echo SYSTEM nt >> link.lnk wlink @link.lnk newmatxx = include.h newmat.h boolean.h myexcept.h myexcept.obj: include.h boolean.h myexcept.h myexcept.cpp newmatex.obj: $(newmatxx) newmatex.cpp newmatnl.obj: $(newmatxx) newmatnl.h newmatap.h example.obj: $(newmatxx) newmatap.h example.cpp cholesky.obj: $(newmatxx) cholesky.cpp evalue.obj: $(newmatxx) newmatrm.h precisio.h evalue.cpp fft.obj: $(newmatxx) newmatap.h fft.cpp newfft.obj: $(newmatxx) newmatap.h newfft.cpp hholder.obj: $(newmatxx) newmatap.h hholder.cpp jacobi.obj: $(newmatxx) precisio.h newmatrm.h jacobi.cpp bandmat.obj: $(newmatxx) newmatrc.h controlw.h bandmat.cpp newmat1.obj: $(newmatxx) newmat1.cpp newmat2.obj: $(newmatxx) newmatrc.h controlw.h newmat2.cpp newmat3.obj: $(newmatxx) newmatrc.h controlw.h newmat3.cpp newmat4.obj: $(newmatxx) newmatrc.h controlw.h newmat4.cpp newmat5.obj: $(newmatxx) newmatrc.h controlw.h newmat5.cpp newmat6.obj: $(newmatxx) newmatrc.h controlw.h newmat6.cpp newmat7.obj: $(newmatxx) newmatrc.h controlw.h newmat7.cpp newmat8.obj: $(newmatxx) newmatap.h newmat8.cpp newmat9.obj: $(newmatxx) newmatrc.h controlw.h newmatio.h newmat9.cpp newmatrm.obj: $(newmatxx) newmatrm.h newmatrm.cpp sort.obj: $(newmatxx) newmatap.h sort.cpp submat.obj: $(newmatxx) newmatrc.h controlw.h submat.cpp svd.obj: $(newmatxx) newmatrm.h precisio.h svd.cpp tmt.obj: $(newmatxx) newmatap.h tmt.cpp tmt1.obj: $(newmatxx) newmatap.h tmt1.cpp tmt2.obj: $(newmatxx) newmatap.h tmt2.cpp tmt3.obj: $(newmatxx) newmatap.h tmt3.cpp tmt4.obj: $(newmatxx) newmatap.h tmt4.cpp tmt5.obj: $(newmatxx) newmatap.h tmt5.cpp tmt6.obj: $(newmatxx) newmatap.h tmt6.cpp tmt7.obj: $(newmatxx) newmatap.h tmt7.cpp tmt8.obj: $(newmatxx) newmatap.h tmt8.cpp tmt9.obj: $(newmatxx) newmatap.h tmt9.cpp tmta.obj: $(newmatxx) newmatap.h tmta.cpp tmtb.obj: $(newmatxx) newmatap.h tmtb.cpp tmtc.obj: $(newmatxx) newmatap.h tmtc.cpp tmtd.obj: $(newmatxx) newmatap.h tmtd.cpp tmte.obj: $(newmatxx) newmatap.h tmte.cpp tmtf.obj: $(newmatxx) newmatap.h tmtf.cpp tmtg.obj: $(newmatxx) newmatap.h tmtg.cpp tmth.obj: $(newmatxx) newmatap.h tmth.cpp tmti.obj: $(newmatxx) newmatap.h tmti.cpp tmtj.obj: $(newmatxx) newmatap.h tmtj.cpp tmtk.obj: $(newmatxx) newmatap.h tmtk.cpp tmtl.obj: $(newmatxx) newmatap.h tmtl.cpp nl_ex.obj: $(newmatxx) newmatap.h newmatnl.h nl_ex.cpp sl_ex.obj: include.h boolean.h myexcept.h sl_ex.cpp solution.obj: include.h boolean.h myexcept.h solution.cpp garch.obj: $(newmatxx) newmatap.h newmatnl.h garch.cpp test_exc.obj: $(newmatxx) test_exc.cpp ossim-Miami-2.9.1/src/matrix/watcom.mak000066400000000000000000000167331352751253100200040ustar00rootroot00000000000000everything: tmt.exe example.exe nl_ex.exe sl_ex.exe garch.exe test_exc.exe .cpp.obj: wpp386 $*.cpp OBJ_LIB = bandmat.obj cholesky.obj evalue.obj fft.obj hholder.obj & jacobi.obj myexcept.obj newmat1.obj newmat2.obj newmat3.obj & newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj & newmat9.obj newmatex.obj newmatnl.obj newmatrm.obj solution.obj & sort.obj submat.obj svd.obj newfft.obj OBJ_T = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj & tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj & tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmt.exe: $(OBJ_T) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file tmt.obj,tmt1.obj,tmt2.obj,tmt3.obj >> link.lnk echo file tmt4.obj,tmt5.obj,tmt6.obj,tmt7.obj >> link.lnk echo file tmt8.obj,tmt9.obj,tmta.obj,tmti.obj >> link.lnk echo file tmtb.obj,tmtc.obj,tmtd.obj,tmte.obj >> link.lnk echo file tmtf.obj,tmtg.obj,tmth.obj,tmtj.obj >> link.lnk echo file tmtk.obj,tmtl.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,newfft.obj >> link.lnk echo name tmt.exe >> link.lnk echo option stack=8192 >> link.lnk wlink @link.lnk OBJ_E = example.obj example.exe: $(OBJ_E) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,example.obj >> link.lnk echo file newmat9.obj,newfft.obj >> link.lnk echo name example.exe >> link.lnk wlink @link.lnk OBJ_N = nl_ex.obj nl_ex.exe: $(OBJ_N) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file nl_ex.obj,newmatnl.obj,newmat9.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,newfft.obj >> link.lnk echo name nl_ex.exe >> link.lnk wlink @link.lnk OBJ_S = sl_ex.obj sl_ex.exe: $(OBJ_S) $(OBJ_LIB) echo file sl_ex.obj,myexcept.obj,solution.obj > link.lnk echo name sl_ex.exe >> link.lnk wlink @link.lnk OBJ_G = garch.obj garch.exe: $(OBJ_G) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file garch.obj,newmatnl.obj,newmat9.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,newfft.obj >> link.lnk echo name garch.exe >> link.lnk wlink @link.lnk OBJ_X = test_exc.obj test_exc.exe: $(OBJ_X) $(OBJ_LIB) echo file newmat1.obj,newmat2.obj,newmat3.obj > link.lnk echo file newmat4.obj,svd.obj,newmat5.obj >> link.lnk echo file newmat6.obj,newmat7.obj,newmat8.obj >> link.lnk echo file test_exc.obj,newmatnl.obj,newmat9.obj >> link.lnk echo file cholesky.obj,hholder.obj,sort.obj >> link.lnk echo file submat.obj,jacobi.obj,newmatrm.obj >> link.lnk echo file fft.obj,evalue.obj,bandmat.obj >> link.lnk echo file newmatex.obj,myexcept.obj,newfft.obj >> link.lnk echo name test_exc.exe >> link.lnk wlink @link.lnk newmatxx = include.h newmat.h boolean.h myexcept.h myexcept.obj: include.h boolean.h myexcept.h myexcept.cpp newmatex.obj: $(newmatxx) newmatex.cpp newmatnl.obj: $(newmatxx) newmatnl.h newmatap.h example.obj: $(newmatxx) newmatap.h example.cpp cholesky.obj: $(newmatxx) cholesky.cpp evalue.obj: $(newmatxx) newmatrm.h precisio.h evalue.cpp fft.obj: $(newmatxx) newmatap.h fft.cpp newfft.obj: $(newmatxx) newmatap.h newfft.cpp hholder.obj: $(newmatxx) newmatap.h hholder.cpp jacobi.obj: $(newmatxx) precisio.h newmatrm.h jacobi.cpp bandmat.obj: $(newmatxx) newmatrc.h controlw.h bandmat.cpp newmat1.obj: $(newmatxx) newmat1.cpp newmat2.obj: $(newmatxx) newmatrc.h controlw.h newmat2.cpp newmat3.obj: $(newmatxx) newmatrc.h controlw.h newmat3.cpp newmat4.obj: $(newmatxx) newmatrc.h controlw.h newmat4.cpp newmat5.obj: $(newmatxx) newmatrc.h controlw.h newmat5.cpp newmat6.obj: $(newmatxx) newmatrc.h controlw.h newmat6.cpp newmat7.obj: $(newmatxx) newmatrc.h controlw.h newmat7.cpp newmat8.obj: $(newmatxx) newmatap.h newmat8.cpp newmat9.obj: $(newmatxx) newmatrc.h controlw.h newmatio.h newmat9.cpp newmatrm.obj: $(newmatxx) newmatrm.h newmatrm.cpp sort.obj: $(newmatxx) newmatap.h sort.cpp submat.obj: $(newmatxx) newmatrc.h controlw.h submat.cpp svd.obj: $(newmatxx) newmatrm.h precisio.h svd.cpp tmt.obj: $(newmatxx) newmatap.h tmt.cpp tmt1.obj: $(newmatxx) newmatap.h tmt1.cpp tmt2.obj: $(newmatxx) newmatap.h tmt2.cpp tmt3.obj: $(newmatxx) newmatap.h tmt3.cpp tmt4.obj: $(newmatxx) newmatap.h tmt4.cpp tmt5.obj: $(newmatxx) newmatap.h tmt5.cpp tmt6.obj: $(newmatxx) newmatap.h tmt6.cpp tmt7.obj: $(newmatxx) newmatap.h tmt7.cpp tmt8.obj: $(newmatxx) newmatap.h tmt8.cpp tmt9.obj: $(newmatxx) newmatap.h tmt9.cpp tmta.obj: $(newmatxx) newmatap.h tmta.cpp tmtb.obj: $(newmatxx) newmatap.h tmtb.cpp tmtc.obj: $(newmatxx) newmatap.h tmtc.cpp tmtd.obj: $(newmatxx) newmatap.h tmtd.cpp tmte.obj: $(newmatxx) newmatap.h tmte.cpp tmtf.obj: $(newmatxx) newmatap.h tmtf.cpp tmtg.obj: $(newmatxx) newmatap.h tmtg.cpp tmth.obj: $(newmatxx) newmatap.h tmth.cpp tmti.obj: $(newmatxx) newmatap.h tmti.cpp tmtj.obj: $(newmatxx) newmatap.h tmtj.cpp tmtk.obj: $(newmatxx) newmatap.h tmtk.cpp tmtl.obj: $(newmatxx) newmatap.h tmtl.cpp nl_ex.obj: $(newmatxx) newmatap.h newmatnl.h nl_ex.cpp sl_ex.obj: include.h boolean.h myexcept.h sl_ex.cpp solution.obj: include.h boolean.h myexcept.h solution.cpp garch.obj: $(newmatxx) newmatap.h newmatnl.h garch.cpp test_exc.obj: $(newmatxx) newmatap.h newmatnl.h test_exc.cpp ossim-Miami-2.9.1/src/ossimConfig.h.in000066400000000000000000000015671352751253100175510ustar00rootroot00000000000000/* $Id: ossimConfig.h.in 13607 2008-09-25 19:39:45Z gpotts $ */ #ifndef ossimConfig_HEADER #define ossimConfig_HEADER /* Define to "1" if you have libz installed, "0" if not. */ #define OSSIM_HAS_LIBZ @OSSIM_HAS_LIBZ@ /* Define to "1" if you have MPI(lam/mpi), "0" if not. */ #define OSSIM_HAS_MPI @OSSIM_HAS_MPI@ /* Define to "1" if you have FREETYPE, "0" if not. */ #define OSSIM_HAS_FREETYPE @OSSIM_HAS_FREETYPE@ /* Define to "1" if you have GEOTIFF, "0" if not. */ #define OSSIM_HAS_GEOTIFF @OSSIM_HAS_GEOTIFF@ /* Define to "1" if you have HDF5 installed, "0" if not. */ #define OSSIM_HAS_HDF5 @OSSIM_HAS_HDF5@ /* Enable cvs id strings for use with "ident" application. */ #define OSSIM_ID_ENABLED @OSSIM_ID_ENABLED@ /* Enable cvs id strings for use with "ident" application. */ #define OSSIM_HAS_JSONCPP @OSSIM_HAS_JSONCPP@ #endif /* End of "#ifndef ossimConfig_HEADER" */ ossim-Miami-2.9.1/src/ossimVersion.h.in000066400000000000000000000010221352751253100177530ustar00rootroot00000000000000#ifndef ossimVersion_HEADER #define ossimVersion_HEADER 1 #define OSSIM_VERSION @OSSIM_VERSION_NUMBER@ #define OSSIM_MAJOR_VERSION_NUMBER @OSSIM_MAJOR_VERSION_NUMBER@ #define OSSIM_MINOR_VERSION_NUMBER @OSSIM_MINOR_VERSION_NUMBER@ #define OSSIM_PATCH_VERSION_NUMBER @OSSIM_PATCH_VERSION_NUMBER@ #define OSSIM_RELEASE_NUMBER @OSSIM_RELEASE_NUMBER@ #define OSSIM_REVISION @OSSIM_REVISION@ // date format = (yyyymmdd) #define OSSIM_BUILD_DATE @OSSIM_BUILD_DATE@ #endif /* End of #ifndef ossimVersion_HEADER */ ossim-Miami-2.9.1/src/parallel/000077500000000000000000000000001352751253100162765ustar00rootroot00000000000000ossim-Miami-2.9.1/src/parallel/ossimIgen.cpp000066400000000000000000000565261352751253100207550ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: implementation for image generator // //************************************************************************* // $Id: ossimIgen.cpp 22299 2013-07-02 19:28:28Z dburken $ #include /* To pick up define OSSIM_HAS_MPI. */ #if OSSIM_HAS_MPI # include # include # include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //### For debug/performance eval #include #include using namespace std; static ossimTrace traceDebug(ossimString("ossimIgen:debug")); static ossimTrace traceLog(ossimString("ossimIgen:log")); ossimIgen::ossimIgen() : theContainer(new ossimConnectableContainer()), theProductProjection(0), theProductChain(0), theTiling(new ossimTiling), theOutputRect(), theBuildThumbnailFlag(false), theThumbnailSize(0, 0), theNumberOfTilesToBuffer(2), theKwl(), theTilingEnabled(false), theProgressFlag(true), theStdoutFlag(false), theThreadCount(9999) // Default no threading { theOutputRect.makeNan(); } ossimIgen::~ossimIgen() { theProductProjection = 0; theTiling = 0; theContainer->disconnect(); theContainer->deleteAllChildren(); theContainer = 0; } void ossimIgen::initializeAttributes() { theBuildThumbnailFlag = false; theThumbnailSize = ossimIpt(0,0); theTilingEnabled = false; if(ossimMpi::instance()->getRank() != 0) { ossimPreferences::instance()->addPreferences(theKwl, "preferences.", true); } const char* lookup = theKwl.find("igen.output_progress"); if (lookup) { ossimString os = lookup; theProgressFlag = os.toBool(); } const char* thumbnailStr = theKwl.find("igen.thumbnail"); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Thumbnail string = " << ossimString(thumbnailStr) << std::endl; } if(thumbnailStr) { theBuildThumbnailFlag= ossimString(thumbnailStr).toBool(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Generate thumbnail attribute is set to " << theBuildThumbnailFlag << std::endl; } if(theBuildThumbnailFlag) { const char* resStr = theKwl.find("igen.thumbnail_res"); if(resStr) { theThumbnailSize = ossimIpt(0,0); std::istringstream in(resStr); ossimString x,y; in >> x >> y; ossim_int32 ix = x.toInt32(); ossim_int32 iy = y.toInt32(); if (ix > 0) { theThumbnailSize.x = ix; } else { theThumbnailSize.x = 128; } if (iy > 0) { theThumbnailSize.y = iy; } else { theThumbnailSize.y = theThumbnailSize.x; } } else { theThumbnailSize = ossimIpt(128, 128); } } } const char* numberOfSlaveTileBuffersStr = theKwl.find("igen.slave_tile_buffers"); if(numberOfSlaveTileBuffersStr) { theNumberOfTilesToBuffer = ossimString(numberOfSlaveTileBuffersStr).toLong(); } const char* tilingKw = theKwl.find("igen.tiling.type"); if(tilingKw) { theTilingEnabled = true; if(!theTiling->loadState(theKwl, "igen.tiling.")) { theTilingEnabled = false; } } } void ossimIgen::slaveSetup() { #if OSSIM_HAS_MPI int stringSize; MPI_Status status; int numberOfTimes = 0; memset((void *)&status, 0, sizeof(MPI_Status)); // we first need to receive the size of the keyword list to load MPI_Recv(&stringSize, 1, MPI_INT, 0, // source 0, // tag MPI_COMM_WORLD, &status); if(status.MPI_ERROR != MPI_SUCCESS) { ossimNotify(ossimNotifyLevel_WARN) << "SLAVE = " << ossimMpi::instance()->getRank() << "Had errors receiving!!!!" << std::endl; return; } char* buf = new char[stringSize+1]; numberOfTimes = 0; memset((void *)&status, 0, sizeof(MPI_Status)); // now lets get the keywordlist as a string so we can load it up MPI_Recv(buf, stringSize, MPI_CHAR, 0, // source 0, // tag MPI_COMM_WORLD, &status); if(status.MPI_ERROR != MPI_SUCCESS) { ossimNotify(ossimNotifyLevel_WARN) << "SLAVE = " << ossimMpi::instance()->getRank() << "Had errors receiving in ossimIgen::slaveCreate(!!!!" << std::endl; return; } buf[stringSize] = '\0'; if(status.MPI_ERROR != MPI_SUCCESS) { ossimNotify(ossimNotifyLevel_WARN) << "SLAVE = " << ossimMpi::instance()->getRank() << "Had errors receiving!!!!" << std::endl; return; } // now lets convert the received keywordlist into an actual // ossimKeywordlist by using the parsStream method. std::ostringstream kwlStream; kwlStream << buf << ends; istringstream kwlInStream(kwlStream.str()); theKwl.clear(); theKwl.parseStream(kwlInStream); initializeAttributes(); delete [] buf; buf = 0; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "****************** KWL ************************" << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << theKwl << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "**************** END KWL ************************" << std::endl; } loadProductSpec(); #endif } void ossimIgen::initialize(const ossimKeywordlist& kwl) { #if OSSIM_HAS_MPI if(ossimMpi::instance()->getNumberOfProcessors() > 0) { if(ossimMpi::instance()->getRank() != 0) { slaveSetup(); return; } } #endif theKwl = kwl; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "The igen kewyord list ==== \n" << theKwl << std::endl; } ossimKeywordlist kwlPrefs = ossimPreferences::instance()->preferencesKWL(); kwlPrefs.addPrefixToAll("preferences."); theKwl.add(kwlPrefs); initializeAttributes(); // now stream it to all slave processors // #if OSSIM_HAS_MPI if(ossimMpi::instance()->getNumberOfProcessors() > 0) { std::ostringstream outputKeywordlist; theKwl.writeToStream(outputKeywordlist); ossimString kwlString = outputKeywordlist.str(); ossim_uint32 size = kwlString.size(); for(long processor = 1; processor < ossimMpi::instance()->getNumberOfProcessors(); ++processor) { // let's send the keywordlist argument. // This is two steps. We send a message to // indicate the size and then we send the // string. // MPI_Send(&size, 1, MPI_INT, processor, 0, MPI_COMM_WORLD); MPI_Send((void*)kwlString.c_str(), size, MPI_CHAR, processor, 0, MPI_COMM_WORLD); } } #endif loadProductSpec(); } bool ossimIgen::loadProductSpec() { const char* MODULE = "ossimIgen::loadProductSpec"; if(traceDebug()) CLOG << "entered..." << std::endl; // Clear out the overall container and initialize it with spec in KWL: theContainer->deleteAllChildren(); theContainer->loadState(theKwl); // There should be a product chain defined in the container: // ossimConnectableObject* obj = // theContainer->findFirstObjectOfType(STATIC_TYPE_NAME(ossimImageChain), false); // theProductChain = PTR_CAST(ossimImageChain, obj); ossimTypeNameVisitor visitor( ossimString("ossimImageChain"), true, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS | ossimVisitor::VISIT_CHILDREN) ); theContainer->accept( visitor ); theProductChain = visitor.getObjectAs(0); if (!theProductChain.valid()) { // Search for a connectable container specified that contains the entire product chain: // ossimConnectableObject* obj2 = // theContainer->findFirstObjectOfType(STATIC_TYPE_NAME(ossimImageFileWriter), true); // ossimImageFileWriter* writer = PTR_CAST(ossimImageFileWriter, obj2); visitor.reset(); visitor.setTypeName( ossimString( "ossimImageFileWriter" ) ); theContainer->accept( visitor ); ossimRefPtr writer = visitor.getObjectAs(0); if ( writer.valid() ) { theProductChain = dynamic_cast( writer->getInput() ); } if (!theProductChain.valid()) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " -- No processing chain defined for generating product." << std::endl; return false; } } // The output projection is specified separately in the KWL: ossimString prefix = "product.projection."; theProductProjection = dynamic_cast( ossimProjectionFactoryRegistry::instance()->createProjection(theKwl, prefix) ); const char* lookup = theKwl.find("igen.write_to_stdout"); if (lookup && ossimString(lookup).toBool()) { theStdoutFlag = true; } return true; } //************************************************************************************************* //! Writes the output product image. Throws an ossimException if error encountered. //************************************************************************************************* void ossimIgen::outputProduct() { // Verify that all vitals have been initialized: if (!theProductChain.valid()) { std::string err = "ossimIgen::outputProduct() ERROR: No product processing chain has yet" " been established. Nothing to output!"; throw(ossimException(err)); } if (!theProductProjection.valid()) { std::string err = "ossimIgen::outputProduct() ERROR: No product projection has yet" " been established. Nothing to output!"; throw(ossimException(err)); } // Update the chain with the product view specified: setView(); initializeChain(); // if it's a thumbnail then adjust the GSD and reset the view proj to the chain. if(theBuildThumbnailFlag) initThumbnailProjection(); ossimRefPtr sequencer = 0; #if OSSIM_HAS_MPI // only allocate the slave connection if the number of processors is larger than 1 if(ossimMpi::instance()->getNumberOfProcessors() > 1) { if(ossimMpi::instance()->getRank()!=0) sequencer = new ossimImageMpiSWriterSequenceConnection(0, theNumberOfTilesToBuffer); else sequencer = new ossimImageMpiMWriterSequenceConnection(); } #endif // we will just load a serial connection if MPI is not supported. // Threading? if (!sequencer.valid() && (theThreadCount != 9999)) sequencer = new ossimMultiThreadSequencer(0, theThreadCount); if (!sequencer.valid()) sequencer = new ossimImageSourceSequencer(0); // Look for the first writer (should be the only writer) in our list of objects: // ossimRefPtr writer = 0; // ossimConnectableObject::ConnectableObjectList imageWriters = // theContainer->findAllObjectsOfType(STATIC_TYPE_INFO(ossimImageFileWriter), false); ossimTypeNameVisitor visitor( ossimString("ossimImageFileWriter"), true, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS | ossimVisitor::VISIT_CHILDREN) ); theContainer->accept( visitor ); ossimRefPtr writer = visitor.getObjectAs(0); if ( !writer.valid() ) { sequencer = 0; std::string err = "ossimIgen::outputProduct() ERROR: No image writer object was found in " " processing chain."; throw(ossimException(err)); } // writer = PTR_CAST(ossimImageFileWriter, imageWriters[0].get()); writer->changeSequencer(sequencer.get()); writer->connectMyInputTo(theProductChain.get()); // Check for writing to standard output flag. Not all writers support this so check and // throw an error if not supported. if (theStdoutFlag) { if ( writer->setOutputStream(std::cout) == false ) { std::string err = "ERROR: The write to standard out flag is set; however, writer does " "not support going to standard out. Bummer..."; throw(ossimException(err)); } } writer->initialize(); if ( theBuildThumbnailFlag ) { //--- // Use theOutputRect as it has been clamped to be within the requested thumbnail size. // // Relying of the bounding rectangle of the scaled product chain has given us off by // one rectangles, i.e., a width of 513 instead of 512. // // NOTE: This must be called after the writer->initialize() as // ossimImageFileWriter::initialize incorrectly resets theAreaOfInterest // back to the bounding rect. //--- writer->setAreaOfInterest( ossimIrect(theOutputRect) ); } // If multi-file tiled output is not desired perform simple output, handle special: if(theTilingEnabled && theProductProjection.valid()) { theTiling->initialize(*(theProductProjection.get()), theOutputRect); ossimRectangleCutFilter* cut = 0; ossimTilingPoly* tilingPoly = dynamic_cast( theTiling.get() ); ossimFilename tempFile = writer->getFilename(); if(!tempFile.isDir()) { tempFile = tempFile.path(); } ossimString tileName; ossimIrect clipRect; // 'next' method modifies the mapProj which is the same instance as theProductProjection, // so this data member is modified here, then later accessed by setView: while(theTiling->next(theProductProjection, clipRect, tileName)) { if ( !tilingPoly )//use ossimTiling or ossimTilingRect { // Disconnect prior to setting up chain. writer->disconnect(); // This will progate the updated projection from theTiling->next call. setView(); // Recompute the bounding rect: initializeChain(); // Hook writer up: writer->connectMyInputTo(theProductChain.get()); writer->setFilename(tempFile.dirCat(tileName)); writer->initialize(); // Set the clip rect for tile: writer->setAreaOfInterest( clipRect ); } else //otherwise use ossimTilingPoly { if (tilingPoly != NULL) { if (!tilingPoly->isFeatureBoundingIntersect())//if clip rect does not intersect with output rect, do nothing { continue; } if (tilingPoly->useMbr())//if use_mbr flag is set to true, all pixels within the MBR will be preserved { if (cut == NULL) { cut = new ossimRectangleCutFilter; theProductChain->addFirst(cut); } setView(); cut->setRectangle(clipRect); } else { if ( tilingPoly->hasExteriorCut() ) { theProductChain->addFirst( tilingPoly->getExteriorCut().get() ); } if ( tilingPoly->hasInteriorCut() ) { theProductChain->addFirst( tilingPoly->getInteriorCut().get() ); } } } initializeChain(); writer->disconnect(); writer->connectMyInputTo(theProductChain.get()); writer->setFilename(tempFile.dirCat(tileName)); writer->initialize(); } // if ( !tilingPoly ){} else{ // Write the file: if ( !writeToFile( writer.get() )) { break; } } } else { // No multi-file tiling, just conventional write to single file: writeToFile(writer.get()); } //########## DEBUG CODE FOR TIMING MULTI THREAD LOCKS ############## if (sequencer.valid() && (theThreadCount != 9999)) { ossimMultiThreadSequencer* mts = dynamic_cast(sequencer.get()); if (mts != NULL) { double jgtt = mts->d_jobGetTileT; ossim_uint32 num_threads = mts->getNumberOfThreads(); double jgttpj = jgtt/num_threads; cout<d_maxCacheUsed << endl; cout << " Cache emptied count: "<< ossimString::toString(mts->d_cacheEmptyCount) << endl; cout << " Time waiting on jobs: "<d_idleTime2<<" s"<d_idleTime5<<" s"<handlerGetTileT()<<" s"<getRank() == 0) && theProgressFlag) { // Add a listener to master. prog = new ossimStdOutProgress(0, true); writer->addListener(prog); } if (traceLog() && (ossimMpi::instance()->getRank() == 0)) { ossimFilename logFile = writer->getFilename(); logFile.setExtension(ossimString("log")); ossimRefPtr container = new ossimConnectableContainer; writer->fillContainer(*container.get()); ossimKeywordlist logKwl; container->saveState(logKwl); logKwl.write(logFile.c_str()); } try { writer->execute(); } // Catch internal exceptions: catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_FATAL) << "ossimIgen::outputProduct ERROR:\n" << "Caught exception!\n" << e.what() << std::endl; return false; } catch(...) { ossimNotify(ossimNotifyLevel_FATAL) << "ossimIgen::outputProduct ERROR:\n" << "Unknown exception caught!\n" << std::endl; return false; } if (prog) { writer->removeListener(prog); delete prog; prog = 0; } return true; } //************************************************************************************************* //! Initializes all clients of the view projection to the current product projection. //************************************************************************************************* void ossimIgen::setView() { if( theProductChain.valid() && theProductProjection.valid() ) { // Find all view clients in the chain, and notify them of the new view: #if 0 ossimConnectableObject::ConnectableObjectList clientList; theProductChain->findAllInputsOfType(clientList, STATIC_TYPE_INFO(ossimViewInterface), true, true); for(ossim_uint32 i = 0; i < clientList.size();++i) { ossimViewInterface* viewClient = dynamic_cast( clientList[i].get() ); if (viewClient) viewClient->setView(theProductProjection->dup()); } #endif ossimTypeNameVisitor visitor( ossimString("ossimViewInterface"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); for( ossim_uint32 i = 0; i < visitor.getObjects().size(); ++i ) { ossimViewInterface* viewClient = visitor.getObjectAs( i ); if (viewClient) { viewClient->setView( theProductProjection->dup() ); } } // Force recompute of bounding rect: initializeChain(); } } //************************************************************************************************* //! Modifies the production chain to output redused-resolution thumbnail image. //************************************************************************************************* void ossimIgen::initThumbnailProjection() { double thumb_size = ossim::max(theThumbnailSize.x, theThumbnailSize.y); ossimMapProjection* mapProj = dynamic_cast(theProductProjection.get()); if(mapProj && !theOutputRect.hasNans()) { double xScale = theOutputRect.width() / thumb_size; double yScale = theOutputRect.height() / thumb_size; double scale = ossim::max(xScale, yScale); mapProj->applyScale(ossimDpt(scale, scale), true); } // Need to change the view in the product chain: setView(); // Clamp output rectangle to thumbnail bounds. ossimDpt ul = theOutputRect.ul(); ossimDpt lr = theOutputRect.lr(); if ( (lr.x - ul.x + 1) > thumb_size) { lr.x = ul.x + thumb_size - 1; } if ( (lr.y - ul.y + 1) > thumb_size ) { lr.y = ul.y + thumb_size - 1; } theOutputRect = ossimDrect(ul, lr); } //************************************************************************************************* // This method is called after a change is made to the product chain. It recomputes the bounding // rectangle. //************************************************************************************************* void ossimIgen::initializeChain() { // Force initialization of the chain to recompute parameters: theProductChain->initialize(); theOutputRect = theProductChain->getBoundingRect(); if(!theOutputRect.hasNans()) { // Stretch the rectangle out to integer boundaries. theOutputRect.stretchOut(); // Communicate the new product size to the view's geometry object. This is a total HACK that // external code needs to worry about setting this. Something is wrong with this picture // (OLK 02/11) ossimImageGeometry* geom = theProductChain->getImageGeometry().get(); if (geom) geom->setImageSize(ossimIpt(theOutputRect.size())); } } ossim-Miami-2.9.1/src/parallel/ossimImageChainMtAdaptor.cpp000066400000000000000000000506741352751253100236720ustar00rootroot00000000000000//************************************************************************************************* // OSSIM // // License: LGPL -- See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // This class supports multi-threading of image chain getTile() requests and associated chain // updating. It accepts an original ossimImageChain object which is then cloned (replicated). // One replicant per thread is created (counting the original as replicant[0]), with all replicants // sharing a common input handler (if directed) so that disk access is serialized and thread-safe. // //************************************************************************************************* // $Id$ #include #include #include #include #include #include #include using namespace std; static const char* NUM_THREADS_KW = "ossimImageChainMtAdaptor.num_threads"; static const char* ORIGINAL_SOURCE_ID_KW = "ossimImageChainMtAdaptor.original_source_id"; //************************************************************************************************* // Constructor. //************************************************************************************************* ossimImageChainMtAdaptor::ossimImageChainMtAdaptor() : m_numThreads (0), d_useSharedHandlers(false), d_debugEnabled(false), d_cacheTileSize(1024), d_useCache(false) { //###### DEBUG ############ ossimMtDebug* mt_debug = ossimMtDebug::instance(); //d_useSharedHandlers = mt_debug->chainSharedHandlers; d_debugEnabled = mt_debug->chainDebugEnabled; //###### END DEBUG ############ } //************************************************************************************************* // Constructor with original image chain provided. This source becomes the first clone in the list. //************************************************************************************************* ossimImageChainMtAdaptor::ossimImageChainMtAdaptor(ossimImageChain* original, ossim_uint32 num_threads_req, bool use_shared_handlers, bool use_cache, ossim_uint32 cache_tile_size) : m_numThreads (0), d_useSharedHandlers(false), d_debugEnabled(false), d_cacheTileSize(1024), d_useCache(false) { //###### DEBUG ############ ossimMtDebug* mt_debug = ossimMtDebug::instance(); //d_useSharedHandlers = mt_debug->chainSharedHandlers; d_debugEnabled = mt_debug->chainDebugEnabled; //###### END DEBUG ############ setNumberOfThreads(num_threads_req); setUseSharedHandlers(use_shared_handlers); setUseCache(use_cache); setCacheTileSize(cache_tile_size); setOriginalChain(original); } //************************************************************************************************* // Destructor. //************************************************************************************************* ossimImageChainMtAdaptor::~ossimImageChainMtAdaptor() { removeListener((ossimConnectableObjectListener*)this); if (d_useSharedHandlers) m_sharedHandlers[0]->disconnectAllOutputs(); m_clones.clear(); m_chainContainers.clear(); if (d_useSharedHandlers) { m_sharedHandlers[0]->close(); m_sharedHandlers[0] = 0; m_sharedHandlers.clear(); } } //************************************************************************************************* //! Alternate way of specifying number of threads to support. This is the same as the number of //! clones that will be available after replicating the original chain. //************************************************************************************************* void ossimImageChainMtAdaptor::setNumberOfThreads(ossim_uint32 num_threads) { if (m_numThreads == num_threads) return; // Determine number of cores/threads to set up: if (num_threads > 0) { m_numThreads = num_threads; } else { // Look in ossim preferences if arg is provided above. ossimString value = ossimPreferences::instance()->findPreference("ossim_threads"); if ( !value.empty() ) m_numThreads = value.toUInt32(); } // If there is a valid original chain, we can perform the replication: if (!m_chainContainers.empty()) replicate(); } void ossimImageChainMtAdaptor::setUseSharedHandlers(bool use_shared_handlers) { d_useSharedHandlers = use_shared_handlers; } void ossimImageChainMtAdaptor::setCacheTileSize(ossim_uint32 cache_tile_size) { d_cacheTileSize = cache_tile_size; } void ossimImageChainMtAdaptor::setUseCache(bool use_cache) { d_useCache = use_cache; } //************************************************************************************************* //! Alternate way of specifying the original chain being adapted for multi-threading. //************************************************************************************************* void ossimImageChainMtAdaptor::setOriginalChain(ossimImageChain* original) { if (original == NULL) return; ossimImageSource* first_source = original->getFirstSource(); if (first_source == NULL) return; // Assign the adaptee and put it in the first position of the clones list: m_adaptedChain = original; m_clones.clear(); m_clones.push_back(first_source); m_chainContainers.clear(); m_chainContainers.push_back(new ossimConnectableContainer); m_adaptedChain->fillContainer(*m_chainContainers[0].get()); // If we know the number of threads, we can begin replicating: if (m_numThreads > 1) replicate(); } //************************************************************************************************* // Creates clones of the original and pushes them onto the clone list. // // Need to consider the possibility that the original chain is a combiner with multiple image // handler inputs, and also the possibility that one handler is wired to multiple input chains // before the combiner. In order to handle this, we will save the connection information for each // input handler encountered so that we can later reproduce it using a shared handler (if requested) //************************************************************************************************* bool ossimImageChainMtAdaptor::replicate() { if ((m_clones.empty()) || (m_numThreads == 0)) return false; // Don't need to replicate if only one thread is being requested. This is not an error though: if (m_numThreads == 1) return true; // If the handlers are to be shared, need to isolate them from the original chain and replace // them with a "hollow adaptor" (i.e., a handler adaptor without the adaptee set yet: m_sharedHandlers.clear(); if (d_useSharedHandlers) { if (m_chainContainers.empty()) return false; // Collect all image handlers in original chain for possible sharing with all clones: ossimTypeNameVisitor visitor (ossimString("ossimImageHandler")); m_chainContainers[0]->accept(visitor); ossimRefPtr handler = 0; ossimRefPtr handler_adaptor = 0; ossimRefPtr output_connection = 0; ossim_uint32 handler_idx = 0; // Loop over all image handlers found in the original chain. Each handler's connection info // is stored and the handler is removed temporarily from the original chain. while (1) { // Fetch a handler from the chain and wrap it with a handler adaptor: handler = visitor.getObjectAs(handler_idx++); if (!handler) break; // Only exit point of while loop handler_adaptor = new ossimImageHandlerMtAdaptor(handler.get(), d_useCache, d_cacheTileSize); m_sharedHandlers.push_back(handler_adaptor); // Change ownership: m_chainContainers[0]->removeChild(handler.get()); handler->changeOwner(this); } // If no handler was found, we can't continue. if (m_sharedHandlers.empty()) return false; } // Fetch the state of this and the original chain. This KWL will be used for creating replicas // via the loadState. The saveState essentially bootstraps the replication task: ossimKeywordlist kwl; bool succeeded = saveState(kwl); // The original chain may have had the handlers temporarily removed for the saveState in support // of shared handlers. If so, need to restore them now: if (d_useSharedHandlers) succeeded = connectSharedHandlers(0); // Finally, initialize THIS chain with the original chain's state. This call will also create // the clones: if (succeeded) succeeded = loadState(kwl); return succeeded; } //************************************************************************************************* // Deletes instances of all replicas from the clone list and leaves only the original. //************************************************************************************************* void ossimImageChainMtAdaptor::deleteReplicas() { if (m_clones.size() > 1) { std::vector< ossimRefPtr >::iterator first_copy = m_clones.begin(); first_copy++; m_clones.erase(first_copy, m_clones.end()); } m_numThreads = 1; } //************************************************************************************************* // Saves the state of the original chain along with number of clones present. //************************************************************************************************* bool ossimImageChainMtAdaptor::saveState(ossimKeywordlist& kwl, const char* prefix) const { if (m_chainContainers.empty()) return false; kwl.add(prefix, NUM_THREADS_KW, m_numThreads); kwl.add(prefix, ORIGINAL_SOURCE_ID_KW, m_clones[0]->getId().getId()); bool rtn_state = m_chainContainers[0]->saveState(kwl, prefix); if (d_debugEnabled) kwl.write("ossimImageChainMtAdaptor.kwl"); return rtn_state; } //************************************************************************************************* // Fetches the state of the original chain and regenerates the clones. Special handling is required // when the image handlers are to be shared among all clones. //************************************************************************************************* bool ossimImageChainMtAdaptor::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool succeeded; // Reset this object: deleteReplicas(); // Fetch this object's data members before moving onto original chain: ossimString value = kwl.find(prefix, NUM_THREADS_KW); if (value.empty()) return false; m_numThreads = value.toUInt32(); if (m_numThreads == 0) return false; // The chain ID needs to be read from KWL: ossimId orig_source_id (ossimId::INVALID_ID); value = kwl.find(prefix, ORIGINAL_SOURCE_ID_KW); if (value.empty()) return false; orig_source_id.setId(value.toInt64()); // This loadState may be called for the purpose of replicating the existing original, or it can // be intended as an adapter to a yet-to-be-instantiated original chain. Check if we already // have a valid original chain: ossimConnectableObject* candidate = 0; ossimImageSource* original_source = 0; if (!m_adaptedChain.valid() || m_chainContainers.empty()) { m_chainContainers.clear(); m_chainContainers.push_back(new ossimConnectableContainer); m_chainContainers[0]->loadState(kwl, prefix); // Need to instantiate a new original. This is a bootstrap for a full initialization of this // object. We'll need to replicate the clones afterwards: ossimIdVisitor visitor (orig_source_id); m_chainContainers[0]->accept(visitor); candidate = visitor.getObject(); original_source = dynamic_cast(candidate); if (original_source == NULL) return false; m_clones.push_back(original_source); // original is always in first position of clones list // The original "chain" is morphed into a chain with a single child (original first source). // This source is the one maintaining the connection to the rest of the sources in the real // processing chain: m_adaptedChain = new ossimImageChain; m_adaptedChain->add(original_source); // Now that we have an original chain, Recursive code to replicate clones: succeeded = replicate(); if (!succeeded) return false; } // We may be done: if (m_numThreads == 1) return true; // In preparation for multi-threading jobs, loop to instantiate all clone chains. The container // class is used to perform a deep copy of the original chain with all connections established. // It would have been cleaner to just use the ossimImageChain::dup() but that method was not // traversing the full chain, resulting in missing input sources: succeeded = true; for (ossim_uint32 i=1; (iloadState(kwl, prefix); // Special handling required if the handlers are being shared. In this case, the handler had // been removed from the original chain, so connections need to be identified and made: if (d_useSharedHandlers) { succeeded = connectSharedHandlers(i); if (!succeeded) return false; } // Find the first (right-most) source in the chain and store it in the clone list. Need to // Modify all IDs ossimIdVisitor visitor (orig_source_id); m_chainContainers[i]->accept(visitor); candidate = visitor.getObject(); m_chainContainers[i]->makeUniqueIds(); ossimRefPtr clone_source = dynamic_cast(candidate); if (!clone_source) return false; m_clones.push_back(clone_source); } return succeeded; } //************************************************************************************************* //! Adapts call to original chain so that all clones are initialized. //************************************************************************************************* void ossimImageChainMtAdaptor::initialize() { for (size_t i=0; iinitialize(); } //************************************************************************************************* // Intercept this getTile because it should never be called directly. The tile request must go // to the specific chain clone. //************************************************************************************************* ossimRefPtr ossimImageChainMtAdaptor::getTile(const ossimIrect& tileRect, ossim_uint32 resLevel) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimImageChainMtAdaptor::getTile() -- This method " "Should never be called directly. The tile request must go to the specific chain clone. " "Returning a tile using the original chain's getTile (not threaded)..."<(0); return m_adaptedChain->getTile(tileRect, resLevel); } //************************************************************************************************* // Manages reconnecting shared image handlers to an image chain after its creation. // This is in support of shared image handlers. Returns TRUE if successful. //************************************************************************************************* bool ossimImageChainMtAdaptor::connectSharedHandlers(ossim_uint32 chain_index) { if ((size_t)chain_index >= m_chainContainers.size()) return false; // Loop over each adapted handler in our shared handler list: SharedHandlerList::iterator handler = m_sharedHandlers.begin(); while (handler != m_sharedHandlers.end()) { // Fetch all objects connected to this adapted handler. The list will point to objects in // m_chainContainers[0], the original chain. The new chain's objects share the same ID's as // the original chain for the moment. So we can search for the output connection // in the new chain using the ID of the corresponding object in the original chain: ConnectableObjectList handler_connections = (*handler)->getOutputList(); ConnectableObjectList::iterator output_connection = handler_connections.begin(); // BUG HERE AFTER UPGRADING FROM 1.8.14 to 1.8.20 - only grabbing the first output connection //while (output_connection != handler_connections.end()) //{ ossimId obj_id = (*output_connection)->getId(); ossimIdVisitor visitor (obj_id); m_chainContainers[chain_index]->accept(visitor); // Get the pointer to the actual output object that needs to be connected to the shared // handler: ossimConnectableObject* output_obj = visitor.getObject(); if (output_obj == NULL) return false; // Should never happen output_obj->connectMyInputTo((*handler).get(), true, true); output_connection++; //} handler++; } return true; } //************************************************************************************************* // Adapts base class method for accessing connectables in the original chain. //************************************************************************************************* ossimConnectableObject::ConnectableObjectList& ossimImageChainMtAdaptor::imageChainList() { // If there is no original chain defined, then just return our own blank list: if (!m_adaptedChain.valid()) return theImageChainList; return m_adaptedChain->imageChainList(); } //************************************************************************************************* // Adapts base class method for accessing connectables in the original chain. //************************************************************************************************* const ossimConnectableObject::ConnectableObjectList& ossimImageChainMtAdaptor::imageChainList()const { // If there is no original chain defined, then just return our own blank list: if (!m_adaptedChain.valid()) return theImageChainList; return m_adaptedChain->imageChainList(); } //************************************************************************************************* //! Adapts the image chain event handler. If the event involves a change to the original image //! chain, then the clones will need to be regenerated here. //************************************************************************************************* void ossimImageChainMtAdaptor::processEvent(ossimEvent& /* event */) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimImageChainMtAdaptor::processEvent() -- " "NOT YET IMPLEMENTED"< >::iterator clone_source = m_clones.begin(); while (clone_source != m_clones.end()) { (*clone_source)->connectMyOutputTo(outputObject, false, false); clone_source++; } // Now make master connection including making input connection on outputObject and firing event: return ossimConnectableObject::connectMyOutputTo(outputObject, makeInputConnection, createEventFlag); } ossim-Miami-2.9.1/src/parallel/ossimImageHandlerMtAdaptor.cpp000066400000000000000000000341531352751253100242170ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // //! Intended mainly to provide a mechanism for mutex-locking access to a shared resource during //! a getTile operation on an ossimImageHandler. This is needed for multi-threaded implementation. // //************************************************************************************************** // $Id$ #include #include // #include #include #include #include #include #include // #include using namespace std; RTTI_DEF1(ossimImageHandlerMtAdaptor, "ossimImageHandlerMtAdaptor", ossimImageHandler); const char* ossimImageHandlerMtAdaptor::ADAPTEE_ID_KW = "adaptee_id"; static ossimTrace traceDebug = ossimTrace("ossimImageHandlerMtAdaptor:debug"); //************************************************************************************************** // Constructor //************************************************************************************************** ossimImageHandlerMtAdaptor::ossimImageHandlerMtAdaptor(ossimImageHandler* adaptee, bool use_cache, ossim_uint32 cache_tile_size) : d_getTileT (0), d_cacheTileSize(1024), m_adaptedHandler (0), m_cache (0), d_useCache (false), d_useFauxTile (false) { //###### DEBUG ############ // ossimMtDebug* mt_debug = ossimMtDebug::instance(); //d_useCache = mt_debug->handlerCacheEnabled; //d_useFauxTile = mt_debug->handlerUseFauxTile; //###### END DEBUG ############ setUseCache(use_cache); setCacheTileSize(cache_tile_size); setAdaptee(adaptee); } //************************************************************************************************** // Destructor //************************************************************************************************** ossimImageHandlerMtAdaptor::~ossimImageHandlerMtAdaptor() { m_adaptedHandler = 0; m_cache = 0; d_fauxTile = 0; } //************************************************************************************************** //! Sets the handler being adapted. //************************************************************************************************** void ossimImageHandlerMtAdaptor::setAdaptee(ossimImageHandler* handler) { m_adaptedHandler = handler; if (handler == NULL) return; // Fetch the adaptee's output list and make it our own: ConnectableObjectList output_list = handler->getOutputList(); if (d_useCache) { // Create the cache and connect this adaptor as its output: m_cache = new ossimCacheTileSource; m_cache->setTileSize(ossimIpt(d_cacheTileSize, d_cacheTileSize)); m_cache->connectMyOutputTo(this, true, false); m_cache->changeOwner(this); //m_cache->connectMyOutputTo(this, true, false); handler->disconnectMyOutputs(output_list, true, false); handler->connectMyOutputTo(m_cache.get(), true, true); } else { handler->disconnectMyOutputs(output_list, true, false); handler->connectMyOutputTo(this, true, false); } // Finally connect the adaptee's outputs to this and fire connection events: connectMyOutputTo(output_list, true, true); handler->changeOwner(this); if (d_useFauxTile) { d_fauxTile = (ossimImageData*) handler->getTile(ossimIpt(0,0), 0)->dup(); //d_fauxTile = new ossimImageData(this, // handler->getOutputScalarType(), // handler->getNumberOfOutputBands(), // handler->getTileWidth(), // handler->getTileHeight()); //d_fauxTile->fill(128.0); } } //************************************************************************************************** //! Only an ossimImageHandler is allowed as input here. //************************************************************************************************** bool ossimImageHandlerMtAdaptor::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* obj) const { const ossimImageHandler* h = dynamic_cast(obj); if ((inputIndex == 0) && (h != NULL)) return true; return false; } //************************************************************************************************** //! Intercepts the getTile call intended for the adaptee and sets a mutex lock around the //! adaptee's getTile call. //************************************************************************************************** ossimRefPtr ossimImageHandlerMtAdaptor::getTile(const ossimIpt& origin, ossim_uint32 rLevel) { if (!m_adaptedHandler.valid()) return NULL; // Establish tile rect to call overloaded getTile(tile_rect): ossim_uint32 h = m_adaptedHandler->getTileHeight(); ossim_uint32 w = m_adaptedHandler->getTileWidth(); ossimIpt lr (origin.x + w - 1, origin.y + h - 1); ossimIrect tile_rect (origin, lr); // Need to unlock to prevent freezing in the called getTile(): return getTile(tile_rect, rLevel); } //************************************************************************************************** //! Intercepts the getTile call intended for the adaptee and sets a mutex lock around the //! adaptee's getTile call. //************************************************************************************************** ossimRefPtr ossimImageHandlerMtAdaptor::getTile(const ossimIrect& tile_rect, ossim_uint32 rLevel) { if (traceDebug()) { std::cout << "TILE: " << tile_rect << std::endl; } if (d_useFauxTile) { ossimRefPtr ftile = new ossimImageData(*(d_fauxTile.get())); ftile->setOrigin(tile_rect.ul()); return ftile; } if (!m_adaptedHandler.valid()) return NULL; // The sole purpose of the adapter is this mutex lock around the actual handler getTile: //std::lock_guard lock(m_mutex); ossimRefPtr tile = new ossimImageData(); ossimRefPtr temp_tile = 0; double dt = ossimTimer::instance()->time_s(); //writeTime(); if (traceDebug()) { std::cout << "WAIT LOCK: " << tile_rect << std::endl; } std::lock_guard lock(m_mutex); if (traceDebug()) { std::cout << "START LOCK: " << tile_rect << std::endl; } if (d_useCache) temp_tile = m_cache->getTile(tile_rect, rLevel); else temp_tile = m_adaptedHandler->getTile(tile_rect, rLevel); d_getTileT += ossimTimer::instance()->time_s() - dt; // We make our own instance of a tile and copy the adaptee's returned tile to it. This avoids // the product tile from changing while being processed up the chain. The adaptee's tile can // change as soon as the mutex lock is released: if (temp_tile.valid()) *tile = *(temp_tile.get()); else tile = NULL; //writeTime(); if (traceDebug()) { std::cout << "END LOCK: " << tile_rect << std::endl; } if (traceDebug()) { std::cout << "END TILE: " << tile_rect << std::endl; } return tile; } //************************************************************************************************** //! Intercepts the getTile call intended for the adaptee and sets a mutex lock around the //! adaptee's getTile call. //************************************************************************************************** bool ossimImageHandlerMtAdaptor::getTile(ossimImageData* tile, ossim_uint32 rLevel) { if ((!m_adaptedHandler.valid()) || (tile == NULL)) return false; // The sole purpose of the adapter is this mutex lock around the actual handler getTile: std::lock_guard lock(m_mutex); // This is effectively a copy of ossimImageSource::getTile(ossimImageData*). It is reimplemented // here to save two additional function calls: tile->ref(); bool status = true; ossimIrect tile_rect = tile->getImageRectangle(); ossimRefPtr temp_tile = 0; if (d_useCache) temp_tile = m_cache->getTile(tile_rect, rLevel); else temp_tile = m_adaptedHandler->getTile(tile_rect, rLevel); if (temp_tile.valid()) *tile = *(temp_tile.get()); else status = false; tile->unref(); return status; } //************************************************************************************************** //! Method to save the state of an object to a keyword list. //! Return true if ok or false on error. //************************************************************************************************** bool ossimImageHandlerMtAdaptor::saveState(ossimKeywordlist& kwl, const char* prefix)const { if (!m_adaptedHandler.valid()) return false; // Skip the ossimImageHandler::saveState() since it is not necessary here: ossimImageSource::saveState(kwl, prefix); kwl.add(prefix, ADAPTEE_ID_KW, m_adaptedHandler->getId().getId()); return true; } //************************************************************************************************** //! Method to the load (recreate) the state of an object from a keyword //! list. Return true if ok or false on error. //************************************************************************************************** bool ossimImageHandlerMtAdaptor::loadState(const ossimKeywordlist& kwl, const char* prefix) { m_adaptedHandler = 0; // Skip the ossimImageHandler::loadState() since it is not necessary here: if (!ossimImageSource::loadState(kwl, prefix)) return false; // The adaptee's ID at least will be in the KWL: ossimString value = kwl.find(prefix, ADAPTEE_ID_KW); if (value.empty()) return false; return true; } //************************************************************************************************** // The following are virtuals in the base class. Implemented here as pass-through to adaptee //************************************************************************************************** ossim_uint32 ossimImageHandlerMtAdaptor::getNumberOfInputBands() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getNumberOfInputBands(); return 0; } bool ossimImageHandlerMtAdaptor::isOpen() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->isOpen(); return false; } bool ossimImageHandlerMtAdaptor::open() { if (m_adaptedHandler.valid()) return m_adaptedHandler->open(); return false; } ossim_uint32 ossimImageHandlerMtAdaptor::getNumberOfLines(ossim_uint32 resLevel) const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getNumberOfLines(resLevel); return 0; } ossim_uint32 ossimImageHandlerMtAdaptor::getNumberOfSamples(ossim_uint32 resLevel) const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getNumberOfSamples(resLevel); return 0; } ossim_uint32 ossimImageHandlerMtAdaptor::getImageTileWidth() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getImageTileWidth(); return 0; } ossim_uint32 ossimImageHandlerMtAdaptor::getImageTileHeight() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getImageTileHeight(); return 0; } ossimString ossimImageHandlerMtAdaptor::getLongName() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getLongName(); return ossimString(); } ossimString ossimImageHandlerMtAdaptor::getShortName() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getShortName(); return ossimString(); } void ossimImageHandlerMtAdaptor::close() { removeListener((ossimConnectableObjectListener*)this); this->disconnectAllOutputs(); m_cache = 0; if (m_adaptedHandler.valid()) { m_adaptedHandler->closeOverview(); m_adaptedHandler->close(); } d_fauxTile = 0; } ossim_uint32 ossimImageHandlerMtAdaptor::getNumberOfOutputBands() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getNumberOfOutputBands(); return 0; } void ossimImageHandlerMtAdaptor::setUseCache(bool use_cache) { d_useCache = use_cache; } void ossimImageHandlerMtAdaptor::setCacheTileSize(ossim_uint32 cache_tile_size) { d_cacheTileSize = cache_tile_size; } ossim_uint32 ossimImageHandlerMtAdaptor::getNumberOfDecimationLevels() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getNumberOfDecimationLevels(); return 0; } void ossimImageHandlerMtAdaptor::writeTime() const { #if 0 /* not portable (drb) */ struct timeval tv; struct timezone tz; struct tm *tm; gettimeofday(&tv, &tz); tm=localtime(&tv.tv_sec); printf("%d:%02d:%02d.%ld ", tm->tm_hour, tm->tm_min,tm->tm_sec,tv.tv_usec); #endif // Sorry no usecs... time_t rawTime = (time_t)ossim::getTime(); char buf[9]; strftime(buf, 9, "%H:%M:%S", gmtime(&rawTime)); cerr << buf << std::endl; } ossimScalarType ossimImageHandlerMtAdaptor::getOutputScalarType() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getOutputScalarType(); return OSSIM_SCALAR_UNKNOWN; } ossim_uint32 ossimImageHandlerMtAdaptor::getTileWidth() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getTileWidth(); return 0; } ossim_uint32 ossimImageHandlerMtAdaptor::getTileHeight() const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getTileHeight(); return 0; } ossim_float64 ossimImageHandlerMtAdaptor::getMinPixelValue(ossim_uint32 band) const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getMinPixelValue(band); return 0.0; } ossim_float64 ossimImageHandlerMtAdaptor::getMaxPixelValue(ossim_uint32 band) const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getMaxPixelValue(band); return 0.0; } ossim_float64 ossimImageHandlerMtAdaptor::getNullPixelValue(ossim_uint32 band) const { if (m_adaptedHandler.valid()) return m_adaptedHandler->getNullPixelValue(band); return 0.0; } ossim-Miami-2.9.1/src/parallel/ossimImageMpiMWriterSequenceConnection.cpp000066400000000000000000000207061352751253100265750ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // This class is specific to the Master connection and is optimized // for the writer sequence and batch processing chain. For the Slave // implementation look for the ossimImageMpiSWriterSequenceConnection.cc and .h // files. The Master connection is currently implemented to allways do // a recieve and does no processing itself. The slave connection does // all the actual work and processing. // //******************************************************************* // $Id: ossimImageMpiMWriterSequenceConnection.cpp 12099 2007-12-01 16:09:36Z dburken $ #include /* To pick up OSSIM_HAS_MPI. */ #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI # include # endif #endif #include #include #include #include #include #include static ossimTrace traceDebug = ossimTrace("ossimImageMpiMWriterSequenceConnection:debug"); RTTI_DEF1(ossimImageMpiMWriterSequenceConnection, "ossimImageMpiMWriterSequenceConnection", ossimImageSourceSequencer) ossimImageMpiMWriterSequenceConnection::ossimImageMpiMWriterSequenceConnection( ossimImageSource* inputSource, ossimObject* owner) :ossimImageSourceSequencer(inputSource, owner), theOutputTile(NULL) { theRank = 0; theNumberOfProcessors = 1; #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI MPI_Comm_rank(MPI_COMM_WORLD, &theRank); MPI_Comm_size(MPI_COMM_WORLD, &theNumberOfProcessors); # endif #endif if(theRank!=0) { theCurrentTileNumber = theRank -1; } else { theCurrentTileNumber = 0; } theNeedToSendRequest = true; } ossimImageMpiMWriterSequenceConnection::ossimImageMpiMWriterSequenceConnection(ossimObject* owner) :ossimImageSourceSequencer(NULL, owner), theOutputTile(NULL) { theRank = 0; theNumberOfProcessors = 1; #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI MPI_Comm_rank(MPI_COMM_WORLD, &theRank); MPI_Comm_size(MPI_COMM_WORLD, &theNumberOfProcessors); # endif #endif if(theRank!=0) { theCurrentTileNumber = theRank -1; } else { theCurrentTileNumber = 0; } theNeedToSendRequest = true; } ossimImageMpiMWriterSequenceConnection::~ossimImageMpiMWriterSequenceConnection() { } void ossimImageMpiMWriterSequenceConnection::initialize() { ossimImageSourceSequencer::initialize(); theCurrentTileNumber = theRank;//-1; theOutputTile = NULL; if(theInputConnection) { theOutputTile = ossimImageDataFactory::instance()->create(this, this); theOutputTile->initialize(); } } void ossimImageMpiMWriterSequenceConnection::setToStartOfSequence() { ossimImageSourceSequencer::setToStartOfSequence(); if(theRank != 0) { // we will subtract one since the masters job is just // writting and not issue getTiles. theCurrentTileNumber = theRank-1; } else { // the master will start at 0 theCurrentTileNumber = 0; } } /*! * Will allow you to get the next tile in the sequence. */ ossimRefPtr ossimImageMpiMWriterSequenceConnection::getNextTile(ossim_uint32 resLevel) { #if OSSIM_HAS_MPI ossimEndian endian; if(!theOutputTile) { initialize(); if (!theOutputTile) { return theOutputTile; } } void* buf = theOutputTile->getBuf(); ossim_uint32 numberOfTiles = getNumberOfTiles(); int errorValue = 0; if(theCurrentTileNumber >= numberOfTiles) { return NULL; } errorValue = MPI_Recv(buf, theOutputTile->getSizeInBytes(), MPI_UNSIGNED_CHAR, theCurrentTileNumber%(theNumberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); if((endian.getSystemEndianType()!=OSSIM_BIG_ENDIAN)&& (theOutputTile->getScalarType()!=OSSIM_UINT8)) { endian.swap(theOutputTile->getScalarType(), buf, theOutputTile->getSize()); } #if 0 // Since MPI can run on different platforms // I am not sure if MPI has built in byte // swap. If so I will name each datatype // so it can handle byte swap. Does anyone // know if MPI does byte swapping. switch(theOutputTile->getScalarType()) { case OSSIM_UINT8: { // we add 1 to the rank so we don't wait on a message // to ourself (rank = 0). errorValue = MPI_Recv(buf, theOutputTile->getSize(), MPI_UNSIGNED_CHAR, theCurrentTileNumber%(theNumberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); break; } case OSSIM_SINT8: { // we add 1 to the rank so we don't wait on a message // to ourself (rank = 0). errorValue = MPI_Recv(buf, theOutputTile->getSize(), MPI_CHAR, theCurrentTileNumber%(theNumberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); break; } case OSSIM_UINT16: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: { errorValue = MPI_Recv(buf, theOutputTile->getSize(), MPI_UNSIGNED_SHORT, theCurrentTileNumber%(theNumberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); break; } case OSSIM_SINT16: { errorValue = MPI_Recv(buf, theOutputTile->getSize(), MPI_SHORT, theCurrentTileNumber%(theNumberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); break; } case OSSIM_SINT32: { errorValue = MPI_Recv(buf, theOutputTile->getSize(), MPI_LONG, theCurrentTileNumber%(theNumberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); break; } case OSSIM_UINT32: { errorValue = MPI_Recv(buf, theOutputTile->getSize(), MPI_UNSIGNED_LONG, theCurrentTileNumber%(theNumberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { errorValue = MPI_Recv(buf, theOutputTile->getSize(), MPI_FLOAT, theCurrentTileNumber%(theNumberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { errorValue = MPI_Recv(buf, theOutputTile->getSize(), MPI_DOUBLE, theCurrentTileNumber%(theNumberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); break; } default: { break; } } #endif ossimIpt origin; getTileOrigin(theCurrentTileNumber, origin); theOutputTile->setOrigin(origin); theOutputTile->validate(); ++theCurrentTileNumber; return theOutputTile; #else return ossimImageSourceSequencer::getNextTile(resLevel); #endif } ossim-Miami-2.9.1/src/parallel/ossimImageMpiSWriterSequenceConnection.cpp000066400000000000000000000270761352751253100266120ustar00rootroot00000000000000//---------------------------------------------------------------------------- // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // $Id: ossimImageMpiSWriterSequenceConnection.cpp 17206 2010-04-25 23:20:40Z dburken $ //---------------------------------------------------------------------------- #include /* To pick up OSSIM_HAS_MPI. */ #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI # include # endif #endif #include #include #include #include #include #include #include static ossimTrace traceDebug = ossimTrace("ossimImageMpiSWriterSequenceConnection:debug"); RTTI_DEF1(ossimImageMpiSWriterSequenceConnection, "ossimImageMpiSWriterSequenceConnection", ossimImageSourceSequencer) ossimImageMpiSWriterSequenceConnection::ossimImageMpiSWriterSequenceConnection(ossimObject* owner, long numberOfTilesToBuffer) :ossimImageSourceSequencer(NULL, owner), theNumberOfTilesToBuffer(numberOfTilesToBuffer), theOutputTile(NULL) { theRank = 0; theNumberOfProcessors = 1; theNumberOfTilesToBuffer = ((theNumberOfTilesToBuffer>0)?theNumberOfTilesToBuffer:2); #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI MPI_Comm_rank(MPI_COMM_WORLD, &theRank); MPI_Comm_size(MPI_COMM_WORLD, &theNumberOfProcessors); # endif #endif if(theRank!=0) { theCurrentTileNumber = theRank -1; } else { theCurrentTileNumber = 0; } } ossimImageMpiSWriterSequenceConnection::ossimImageMpiSWriterSequenceConnection(ossimImageSource* inputSource, ossimObject* owner, long numberOfTilesToBuffer) :ossimImageSourceSequencer(inputSource, owner), theNumberOfTilesToBuffer(numberOfTilesToBuffer), theOutputTile(NULL) { theRank = 0; theNumberOfProcessors = 1; theNumberOfTilesToBuffer = ((theNumberOfTilesToBuffer>0)?theNumberOfTilesToBuffer:2); #if OSSIM_HAS_MPI MPI_Comm_rank(MPI_COMM_WORLD, &theRank); MPI_Comm_size(MPI_COMM_WORLD, &theNumberOfProcessors); #endif if(theRank!=0) { theCurrentTileNumber = theRank -1; } else { theCurrentTileNumber = 0; } } ossimImageMpiSWriterSequenceConnection::~ossimImageMpiSWriterSequenceConnection() { deleteOutputTiles(); } void ossimImageMpiSWriterSequenceConnection::deleteOutputTiles() { if(theOutputTile) { delete [] theOutputTile; theOutputTile = NULL; } } void ossimImageMpiSWriterSequenceConnection::initialize() { ossimImageSourceSequencer::initialize(); theCurrentTileNumber = theRank-1; if(theOutputTile) { deleteOutputTiles(); } if(theInputConnection) { theOutputTile = new ossimRefPtr[theNumberOfTilesToBuffer]; for(long index = 0; index < theNumberOfTilesToBuffer; ++index) { theOutputTile[index] = ossimImageDataFactory::instance()->create(this, this); theOutputTile[index]->initialize(); } } } void ossimImageMpiSWriterSequenceConnection::setToStartOfSequence() { ossimImageSourceSequencer::setToStartOfSequence(); if(theRank != 0) { // we will subtract one since the masters job is just // writting and not issue getTiles. theCurrentTileNumber = theRank-1; } else { // the master will start at 0 theCurrentTileNumber = 0; } } void ossimImageMpiSWriterSequenceConnection::slaveProcessTiles() { #ifdef OSSIM_HAS_MPI # if OSSIM_HAS_MPI ossimEndian endian; ossim_uint32 numberOfTiles = getNumberOfTiles(); long currentSendRequest = 0; //long numberOfTilesSent = 0; int errorValue= 0; MPI_Request *requests = new MPI_Request[theNumberOfTilesToBuffer]; for (int i = 0; i < theNumberOfTilesToBuffer; ++i) { requests[i] = MPI_REQUEST_NULL; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimImageMpiSWriterSequenceConnection::slaveProcessTiles(): entering slave and will look at " << numberOfTiles << " tiles" << std::endl; } while(theCurrentTileNumber < numberOfTiles) { ossimRefPtr data = ossimImageSourceSequencer::getTile(theCurrentTileNumber); // if the current send requests have looped around // make sure we wait to see if it was sent // errorValue = MPI_Wait(&requests[currentSendRequest], MPI_STATUS_IGNORE); requests[currentSendRequest] = MPI_REQUEST_NULL; if(data.valid() && (data->getDataObjectStatus()!=OSSIM_NULL)&& (data->getDataObjectStatus()!=OSSIM_EMPTY)) { theOutputTile[currentSendRequest]->setImageRectangle(data->getImageRectangle()); theOutputTile[currentSendRequest]->initialize(); theOutputTile[currentSendRequest]->loadTile(data.get()); theOutputTile[currentSendRequest]->setDataObjectStatus(data->getDataObjectStatus()); if(traceDebug()) { if(data->getDataObjectStatus() == OSSIM_EMPTY) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimImageMpiSWriterSequenceConnection::slaveProcessTiles(): In salve = " << theRank << " tile is empty" << std::endl; } } } else { if(traceDebug()) { if(!data) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimImageMpiSWriterSequenceConnection::slaveProcessTiles(): In slave = " << theRank << " ptr is null " << std::endl; } else { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimImageMpiSWriterSequenceConnection::slaveProcessTiles(): In slave = " << theRank << " tile is empty" << std::endl; } } theOutputTile[currentSendRequest]->makeBlank(); } void* buf = theOutputTile[currentSendRequest]->getBuf(); if((endian.getSystemEndianType()!=OSSIM_BIG_ENDIAN)&& (theOutputTile[currentSendRequest]->getScalarType()!=OSSIM_UINT8)) { endian.swap(theOutputTile[currentSendRequest]->getScalarType(), buf, theOutputTile[currentSendRequest]->getSize()); } errorValue = MPI_Isend(buf, theOutputTile[currentSendRequest]->getSizeInBytes(), MPI_UNSIGNED_CHAR, 0, 0, MPI_COMM_WORLD, &requests[currentSendRequest]); #if 0 switch(theOutputTile[currentSendRequest]->getScalarType()) { case OSSIM_UINT8: { errorValue = MPI_Isend(buf, theOutputTile[currentSendRequest]->getSize(), MPI_UNSIGNED_CHAR, 0, 0, MPI_COMM_WORLD, &requests[currentSendRequest]); break; } case OSSIM_SINT8: { errorValue = MPI_Isend(buf, theOutputTile[currentSendRequest]->getSize(), MPI_CHAR, 0, 0, MPI_COMM_WORLD, &requests[currentSendRequest]); break; } case OSSIM_UINT16: { errorValue = MPI_Isend(buf, theOutputTile[currentSendRequest]->getSize(), MPI_UNSIGNED_SHORT, 0, 0, MPI_COMM_WORLD, &requests[currentSendRequest]); break; } case OSSIM_SINT16: { errorValue = MPI_Isend(buf, theOutputTile[currentSendRequest]->getSize(), MPI_SHORT, 0, 0, MPI_COMM_WORLD, &requests[currentSendRequest]); break; } case OSSIM_UINT32: { errorValue = MPI_Isend(buf, theOutputTile[currentSendRequest]->getSize(), MPI_UNSIGNED_LONG, 0, 0, MPI_COMM_WORLD, &requests[currentSendRequest]); break; } case OSSIM_SINT32: { errorValue = MPI_Isend(buf, theOutputTile[currentSendRequest]->getSize(), MPI_LONG, 0, 0, MPI_COMM_WORLD, &requests[currentSendRequest]); break; } case OSSIM_FLOAT32: case OSSIM_NORMALIZED_FLOAT: { errorValue = MPI_Isend(buf, theOutputTile[currentSendRequest]->getSize(), MPI_FLOAT, 0, 0, MPI_COMM_WORLD, &requests[currentSendRequest]); break; } case OSSIM_FLOAT64: case OSSIM_NORMALIZED_DOUBLE: { errorValue = MPI_Isend(buf, theOutputTile[currentSendRequest]->getSize(), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &requests[currentSendRequest]); break; } default: break; } #endif theCurrentTileNumber += (theNumberOfProcessors-1); //numberOfTilesSent++; currentSendRequest++; currentSendRequest %= theNumberOfTilesToBuffer; } ossim_int32 tempCount = 0; // must wait in the correct order // while(tempCount < theNumberOfTilesToBuffer) { errorValue = MPI_Wait(&requests[currentSendRequest], MPI_STATUS_IGNORE); currentSendRequest++; currentSendRequest %= theNumberOfTilesToBuffer; ++tempCount; } // MPI_Waitall(theNumberOfTilesToBuffer, // requests, // MPI_STATUS_IGNORE); delete [] requests; # endif #endif } ossimRefPtr ossimImageMpiSWriterSequenceConnection::getNextTile( ossim_uint32 /* resLevel */) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimImageMpiSWriterSequenceConnection::getNextTile(): " << "should not be called" << std::endl; return ossimRefPtr(); } ossim-Miami-2.9.1/src/parallel/ossimJob.cpp000066400000000000000000000032241352751253100205700ustar00rootroot00000000000000#include void ossimJob::start() { setState(ossimJob_RUNNING); run(); if(!(state() & ossimJob_CANCEL)) { setState(ossimJob_FINISHED); } } void ossimJob::setState(int value, bool on) { std::shared_ptr thisShared = getSharedFromThis(); // we will need to make sure that the state flags are set properly // so if you turn on running then you can't have finished or ready turned onturned on // but can stil have cancel turned on // int newState = m_state; if(on) { newState = ((newState | value)&ossimJob_ALL); } else { newState = ((newState & ~value)&ossimJob_ALL); } int oldState = 0; int currentState = 0; std::shared_ptr callback; bool stateChangedFlag = false; { std::lock_guard lock(m_jobMutex); stateChangedFlag = newState != m_state; oldState = m_state; m_state = static_cast(newState); currentState = m_state; callback = m_callback; } if(stateChangedFlag&&callback) { if(!(oldState&ossimJob_READY)&& (currentState&ossimJob_READY)) { callback->ready(thisShared); } else if(!(oldState&ossimJob_RUNNING)&& (currentState&ossimJob_RUNNING)) { callback->started(thisShared); } else if(!(oldState&ossimJob_CANCEL)&& (currentState&ossimJob_CANCEL)) { callback->canceled(thisShared); } else if(!(oldState&ossimJob_FINISHED)&& (currentState&ossimJob_FINISHED)) { callback->finished(thisShared); } } } ossim-Miami-2.9.1/src/parallel/ossimJobMultiThreadQueue.cpp000066400000000000000000000063121352751253100237410ustar00rootroot00000000000000#include ossimJobMultiThreadQueue::ossimJobMultiThreadQueue(std::shared_ptr q, ossim_uint32 nThreads) :m_jobQueue(q?q:std::make_shared()) { setNumberOfThreads(nThreads); } ossimJobMultiThreadQueue::~ossimJobMultiThreadQueue() { cancel(); waitForCompletion(); m_threadQueueList.clear(); } std::shared_ptr ossimJobMultiThreadQueue::getJobQueue() { std::lock_guard lock(m_mutex); return m_jobQueue; } const std::shared_ptr ossimJobMultiThreadQueue::getJobQueue()const { std::lock_guard lock(m_mutex); return m_jobQueue; } void ossimJobMultiThreadQueue::setJobQueue(std::shared_ptr q) { std::lock_guard lock(m_mutex); ossim_uint32 idx = 0; m_jobQueue = q; for(idx = 0; idx < m_threadQueueList.size(); ++idx) { m_threadQueueList[idx]->setJobQueue(m_jobQueue); } } void ossimJobMultiThreadQueue::setNumberOfThreads(ossim_uint32 nThreads) { std::lock_guard lock(m_mutex); ossim_uint32 idx = 0; ossim_uint32 queueSize = m_threadQueueList.size(); if(nThreads > queueSize) { for(idx = queueSize; idx < nThreads;++idx) { std::shared_ptr threadQueue = std::make_shared(); threadQueue->setJobQueue(m_jobQueue); m_threadQueueList.push_back(threadQueue); } } else if(nThreads < queueSize) { ThreadQueueList::iterator iter = m_threadQueueList.begin()+nThreads; while(iter != m_threadQueueList.end()) { (*iter)->cancel(); iter = m_threadQueueList.erase(iter); } } } ossim_uint32 ossimJobMultiThreadQueue::getNumberOfThreads() const { std::lock_guard lock(m_mutex); return static_cast( m_threadQueueList.size() ); } ossim_uint32 ossimJobMultiThreadQueue::numberOfBusyThreads()const { ossim_uint32 result = 0; std::lock_guard lock(m_mutex); ossim_uint32 idx = 0; ossim_uint32 queueSize = m_threadQueueList.size(); for(idx = 0; idx < queueSize;++idx) { if(m_threadQueueList[idx]->isProcessingJob()) ++result; } return result; } bool ossimJobMultiThreadQueue::areAllThreadsBusy()const { std::lock_guard lock(m_mutex); ossim_uint32 idx = 0; ossim_uint32 queueSize = m_threadQueueList.size(); for(idx = 0; idx < queueSize;++idx) { if(!m_threadQueueList[idx]->isProcessingJob()) return false; } return true; } bool ossimJobMultiThreadQueue::hasJobsToProcess()const { bool result = false; { std::lock_guard lock(m_mutex); ossim_uint32 queueSize = m_threadQueueList.size(); ossim_uint32 idx = 0; for(idx = 0; ((idxhasJobsToProcess(); } } return result; } void ossimJobMultiThreadQueue::cancel() { for(auto thread:m_threadQueueList) { thread->cancel(); } } void ossimJobMultiThreadQueue::waitForCompletion() { for(auto thread:m_threadQueueList) { thread->waitForCompletion(); } } ossim-Miami-2.9.1/src/parallel/ossimJobQueue.cpp000066400000000000000000000157601352751253100216050ustar00rootroot00000000000000#include #include /* for std::find */ ossimJobQueue::ossimJobQueue() { } void ossimJobQueue::add(std::shared_ptr job, bool guaranteeUniqueFlag) { std::shared_ptr cb; { { std::lock_guard lock(m_jobQueueMutex); if(guaranteeUniqueFlag) { if(findByPointer(job) != m_jobQueue.end()) { m_block.set(true); return; } } cb = m_callback; } if(cb) cb->adding(getSharedFromThis(), job); job->ready(); m_jobQueueMutex.lock(); m_jobQueue.push_back(job); m_jobQueueMutex.unlock(); } if(cb) { cb->added(getSharedFromThis(), job); } m_block.set(true); } std::shared_ptr ossimJobQueue::removeByName(const ossimString& name) { std::shared_ptr result; std::shared_ptr cb; if(name.empty()) return result; { std::lock_guard lock(m_jobQueueMutex); ossimJob::List::iterator iter = findByName(name); if(iter!=m_jobQueue.end()) { result = *iter; m_jobQueue.erase(iter); } cb = m_callback; } m_block.set(!m_jobQueue.empty()); if(cb&&result) { cb->removed(getSharedFromThis(), result); } return result; } std::shared_ptr ossimJobQueue::removeById(const ossimString& id) { std::shared_ptr result; std::shared_ptr cb; if(id.empty()) return result; { std::lock_guard lock(m_jobQueueMutex); ossimJob::List::iterator iter = findById(id); if(iter!=m_jobQueue.end()) { result = *iter; m_jobQueue.erase(iter); } cb = m_callback; m_block.set(!m_jobQueue.empty()); } if(cb&&result) { cb->removed(getSharedFromThis(), result); } return result; } void ossimJobQueue::remove(const std::shared_ptr job) { std::shared_ptr removedJob; std::shared_ptr cb; { std::lock_guard lock(m_jobQueueMutex); ossimJob::List::iterator iter = std::find(m_jobQueue.begin(), m_jobQueue.end(), job); if(iter!=m_jobQueue.end()) { removedJob = (*iter); m_jobQueue.erase(iter); } cb = m_callback; } if(cb&&removedJob) { cb->removed(getSharedFromThis(), removedJob); } } void ossimJobQueue::removeStoppedJobs() { ossimJob::List removedJobs; std::shared_ptr cb; { std::lock_guard lock(m_jobQueueMutex); cb = m_callback; ossimJob::List::iterator iter = m_jobQueue.begin(); while(iter!=m_jobQueue.end()) { if((*iter)->isStopped()) { removedJobs.push_back(*iter); iter = m_jobQueue.erase(iter); } else { ++iter; } } } if(!removedJobs.empty()) { if(cb) { ossimJob::List::iterator iter = removedJobs.begin(); while(iter!=removedJobs.end()) { cb->removed(getSharedFromThis(), (*iter)); ++iter; } } removedJobs.clear(); } } void ossimJobQueue::clear() { ossimJob::List removedJobs(m_jobQueue); std::shared_ptr cb; { std::lock_guard lock(m_jobQueueMutex); m_jobQueue.clear(); cb = m_callback; } if(cb) { for(ossimJob::List::iterator iter=removedJobs.begin();iter!=removedJobs.end();++iter) { cb->removed(getSharedFromThis(), (*iter)); } } } std::shared_ptr ossimJobQueue::nextJob(bool blockIfEmptyFlag) { m_jobQueueMutex.lock(); bool emptyFlag = m_jobQueue.empty(); m_jobQueueMutex.unlock(); if (blockIfEmptyFlag && emptyFlag) { m_block.block(); } std::shared_ptr result; std::lock_guard lock(m_jobQueueMutex); if (m_jobQueue.empty()) { m_block.set(false); return result; } ossimJob::List::iterator iter= m_jobQueue.begin(); while((iter != m_jobQueue.end())&& (((*iter)->isCanceled()))) { (*iter)->finished(); // mark the ob as being finished iter = m_jobQueue.erase(iter); } if(iter != m_jobQueue.end()) { result = *iter; m_jobQueue.erase(iter); } m_block.set(!m_jobQueue.empty()); return result; } void ossimJobQueue::releaseBlock() { m_block.release(); } bool ossimJobQueue::isEmpty()const { // std::lock_guard lock(m_jobQueueMutex); // return m_jobQueue.empty(); m_jobQueueMutex.lock(); bool result = m_jobQueue.empty(); m_jobQueueMutex.unlock(); return result; } ossim_uint32 ossimJobQueue::size() { std::lock_guard lock(m_jobQueueMutex); return (ossim_uint32) m_jobQueue.size(); } ossimJob::List::iterator ossimJobQueue::findById(const ossimString& id) { if(id.empty()) return m_jobQueue.end(); ossimJob::List::iterator iter = m_jobQueue.begin(); while(iter != m_jobQueue.end()) { if(id == (*iter)->id()) { return iter; } ++iter; } return m_jobQueue.end(); } ossimJob::List::iterator ossimJobQueue::findByName(const ossimString& name) { if(name.empty()) return m_jobQueue.end(); ossimJob::List::iterator iter = m_jobQueue.begin(); while(iter != m_jobQueue.end()) { if(name == (*iter)->name()) { return iter; } ++iter; } return m_jobQueue.end(); } ossimJob::List::iterator ossimJobQueue::findByPointer(const std::shared_ptr job) { return std::find(m_jobQueue.begin(), m_jobQueue.end(), job); } ossimJob::List::iterator ossimJobQueue::findByNameOrPointer(const std::shared_ptr job) { ossimString n = job->name(); ossimJob::List::iterator iter = std::find_if(m_jobQueue.begin(), m_jobQueue.end(), [n, job](const std::shared_ptr jobIter){ bool result = (jobIter == job); if(!result&&!n.empty()) result = jobIter->name() == n; return result; }); // ossimJob::List::iterator iter = m_jobQueue.begin(); // while(iter != m_jobQueue.end()) // { // if((*iter) == job) // { // return iter; // } // else if((!n.empty())&& // (job->name() == (*iter)->name())) // { // return iter; // } // ++iter; // } return iter; } bool ossimJobQueue::hasJob(std::shared_ptr job) { ossimJob::List::const_iterator iter = m_jobQueue.begin(); while(iter != m_jobQueue.end()) { if(job == (*iter)) { return true; } ++iter; } return false; } void ossimJobQueue::setCallback(std::shared_ptr c) { std::lock_guard lock(m_jobQueueMutex); m_callback = c; } std::shared_ptr ossimJobQueue::callback() { std::lock_guard lock(m_jobQueueMutex); return m_callback; } ossim-Miami-2.9.1/src/parallel/ossimJobThreadQueue.cpp000066400000000000000000000111001352751253100227150ustar00rootroot00000000000000#include #include // for std::nullptr ossimJobThreadQueue::ossimJobThreadQueue(std::shared_ptr jqueue) :m_doneFlag(false) { setJobQueue(jqueue); } void ossimJobThreadQueue::setJobQueue(std::shared_ptr jqueue) { std::lock_guard lock(m_threadMutex); if (m_jobQueue == jqueue) return; pause(); while(isRunning()&&!isPaused()) { m_jobQueue->releaseBlock(); } m_jobQueue = jqueue; resume(); if(m_jobQueue) startThreadForQueue(); } std::shared_ptr ossimJobThreadQueue::getJobQueue() { std::lock_guard lock(m_threadMutex); return m_jobQueue; } const std::shared_ptr ossimJobThreadQueue::getJobQueue() const { std::lock_guard lock(m_threadMutex); return m_jobQueue; } std::shared_ptr ossimJobThreadQueue::currentJob() { std::lock_guard lock(m_threadMutex); return m_currentJob; } void ossimJobThreadQueue::cancelCurrentJob() { std::lock_guard lock(m_threadMutex); if(m_currentJob) { m_currentJob->cancel(); } } bool ossimJobThreadQueue::isValidQueue()const { std::lock_guard lock(m_threadMutex); return (m_jobQueue!=nullptr); } void ossimJobThreadQueue::run() { bool firstTime = true; bool validQueue = true; std::shared_ptr job; do { interrupt(); // osg::notify(osg::NOTICE)<<"In thread loop "< lock(m_threadMutex); m_currentJob = job; } // if the job is ready to execute if(job->isReady()) { job->start(); } { std::lock_guard lock(m_threadMutex); m_currentJob = 0; } job.reset(); } if (firstTime) { ossim::Thread::yieldCurrentThread(); firstTime = false; } } while (!m_doneFlag&&validQueue); { std::lock_guard lock(m_threadMutex); m_currentJob = 0; } if(job&&m_doneFlag&&job->isReady()) { job->cancel(); } job = 0; } void ossimJobThreadQueue::setDone(bool done) { m_threadMutex.lock(); if (m_doneFlag==done) { m_threadMutex.unlock(); return; } m_doneFlag = done; m_threadMutex.unlock(); if(done) { { std::lock_guard lock(m_threadMutex); if (m_currentJob) m_currentJob->release(); } if (m_jobQueue) m_jobQueue->releaseBlock(); } } bool ossimJobThreadQueue::isDone() const { std::lock_guard lock(m_threadMutex); return m_doneFlag; } bool ossimJobThreadQueue::isProcessingJob()const { std::lock_guard lock(m_threadMutex); return (m_currentJob!=nullptr); } void ossimJobThreadQueue::cancel() { if( isRunning() ) { { std::lock_guard lock(m_threadMutex); m_doneFlag = true; if (m_currentJob) { m_currentJob->cancel(); } if (m_jobQueue) { m_jobQueue->releaseBlock(); } } // then wait for the the thread to stop running. while(isRunning()) { #if 1 { std::lock_guard lock(m_threadMutex); if (m_jobQueue) { m_jobQueue->releaseBlock(); } } #endif ossim::Thread::yieldCurrentThread(); } } } bool ossimJobThreadQueue::isEmpty()const { std::lock_guard lock(m_threadMutex); return m_jobQueue->isEmpty(); } ossimJobThreadQueue::~ossimJobThreadQueue() { cancel(); } void ossimJobThreadQueue::startThreadForQueue() { if(m_jobQueue) { if(!isRunning()) { start(); } } } bool ossimJobThreadQueue::hasJobsToProcess()const { bool result = false; { std::lock_guard lock(m_threadMutex); result = (!m_jobQueue->isEmpty()||m_currentJob); } return result; } std::shared_ptr ossimJobThreadQueue::nextJob() { std::shared_ptr job; m_threadMutex.lock(); std::shared_ptr jobQueue = m_jobQueue; bool checkIfValid = !m_doneFlag&&jobQueue; m_threadMutex.unlock(); if(checkIfValid) { job = jobQueue->nextJob(true); } return job; } ossim-Miami-2.9.1/src/parallel/ossimMpi.cpp000066400000000000000000000072201352751253100206030ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimMpi.cpp 23002 2014-11-24 17:11:17Z dburken $ #include #include #include #include #if OSSIM_HAS_MPI # include #endif #if OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimMpi.cpp 23002 2014-11-24 17:11:17Z dburken $"; #endif static ossimTrace traceDebug = ossimTrace("ossimMpi:debug"); ossimMpi* ossimMpi::theInstance=0; ossimMpi* ossimMpi::instance() { if(!theInstance) { theInstance = new ossimMpi; } return theInstance; } bool ossimMpi::isEnabled()const { return theEnabledFlag; } void ossimMpi::barrier() { #if OSSIM_HAS_MPI if(theEnabledFlag) { // Blocks until all processes have reached this routine. MPI_Barrier( MPI_COMM_WORLD ); } #endif } ossim_float64 ossimMpi::getTime()const { #if OSSIM_HAS_MPI if(theEnabledFlag) { return MPI_Wtime(); } else { return time(0); } #else return time(0); #endif } #if OSSIM_HAS_MPI void ossimMpi::initialize(int* argc, char*** argv) { int success=0; success = MPI_Init(argc, argv); if(success == MPI_SUCCESS) { theEnabledFlag = true; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimMpi::initialize\n" << "MPI is initialized and running with " << getNumberOfProcessors() << " processors..." << std::endl; } } else { theEnabledFlag = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimMpi::initialize: MPI is not initialized." << std::endl; } } } #else void ossimMpi::initialize(int* /* argc */, char*** /* argv */) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimMpi::initialize: Not compiled with mpi!" << std::endl; } } #endif void ossimMpi::setEnabledFlag(bool flag) { theEnabledFlag = flag; } void ossimMpi::finalize() { #if OSSIM_HAS_MPI if(theEnabledFlag) { int success; success = MPI_Finalize(); if(traceDebug()) { if(success == MPI_SUCCESS) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimMpi::finalize(): mpi is finalized" << std::endl; } else { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimMpi::finalize(): " << "mpi is not finalized successfully" << std::endl; } } } #endif } int ossimMpi::getRank()const { int result = 0; #if OSSIM_HAS_MPI if(theEnabledFlag) { MPI_Comm_rank(MPI_COMM_WORLD, &result); } #endif return result; } int ossimMpi::getNumberOfProcessors()const { int result = 1; #if OSSIM_HAS_MPI if(theEnabledFlag) { MPI_Comm_size(MPI_COMM_WORLD, &result); } #endif return result; } ossimMpi::ossimMpi() : theEnabledFlag(false) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimMpi::ossimMpi entered..." << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID = " << OSSIM_ID << std::endl; #endif } } ossimMpi::ossimMpi(const ossimMpi& obj) : theEnabledFlag(obj.theEnabledFlag) {} void ossimMpi::operator=(const ossimMpi& rhs) { theEnabledFlag = rhs.theEnabledFlag; } ossim-Miami-2.9.1/src/parallel/ossimMpiMasterOverviewSequencer.cpp000066400000000000000000000070501352751253100253620ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Class definition for mpi master sequencer for building // overview files. // //---------------------------------------------------------------------------- // $Id: ossimMpiMasterOverviewSequencer.cpp 17870 2010-08-12 13:12:32Z sbortman $ #include #include /* To pick up OSSIM_HAS_MPI. */ #include #if OSSIM_HAS_MPI # include #endif ossimMpiMasterOverviewSequencer::ossimMpiMasterOverviewSequencer() : ossimOverviewSequencer(), m_rank(0), m_numberOfProcessors(1) { #if OSSIM_HAS_MPI MPI_Comm_rank(MPI_COMM_WORLD, &m_rank); MPI_Comm_size(MPI_COMM_WORLD, &m_numberOfProcessors); #endif //--- // Since this is the master sequencer it should always be rank 0; else, // we have a coding error. Since we have the getNextTile implemented to // recieve from the slave processes we always start the tile count at 0. //--- m_currentTileNumber = 0; } ossimMpiMasterOverviewSequencer::~ossimMpiMasterOverviewSequencer() { } void ossimMpiMasterOverviewSequencer::initialize() { ossimOverviewSequencer::initialize(); } void ossimMpiMasterOverviewSequencer::setToStartOfSequence() { m_currentTileNumber = 0; } ossimRefPtr ossimMpiMasterOverviewSequencer::getNextTile() { if ( m_dirtyFlag ) { //--- // If this happens we have a coding error. Someone started sequencing // without initializing us properly. //--- return ossimRefPtr(); } #if OSSIM_HAS_MPI //--- // Using mpi. The slaves will send us tiles to be returned by this method. // They will alway be sent in big endian (network byte order) so we must // swap back if the scalar type is not 8 bit and the system byte order is // little endian. We will use the endian pointer itself as a flag to swap. //--- ossimEndian* endian = 0; if (m_imageHandler.valid()) { if (m_imageHandler->getOutputScalarType() != OSSIM_UINT8) { if (ossim::byteOrder() != OSSIM_BIG_ENDIAN) { endian = new ossimEndian(); } } } int errorValue; // Buffer to receive the data from slaves. void* buf = m_tile->getBuf(); // Total number of tiles to process... ossim_uint32 numberOfTiles = getNumberOfTiles(); if(m_currentTileNumber >= numberOfTiles) { return ossimRefPtr(); } errorValue = MPI_Recv(buf, m_tile->getSizeInBytes(), MPI_UNSIGNED_CHAR, m_currentTileNumber%(m_numberOfProcessors-1)+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // Data always sent in big endian order. if ( endian ) { endian->swap(m_tile->getScalarType(), buf, m_tile->getSize()); } // Get the output rectangle. ossimIrect outputRect; getOutputTileRectangle(outputRect); // Capture the output rectangle. m_tile->setImageRectangle(outputRect); // Set the tile status. m_tile->validate(); // Increment the tile index. ++m_currentTileNumber; // cleanup... if ( endian ) { delete endian; endian = 0; } return m_tile; #else // Not compiled with mpi. return ossimOverviewSequencer::getNextTile(); #endif /* End of #if OSSIM_HAS_MPI */ } ossim-Miami-2.9.1/src/parallel/ossimMpiSlaveOverviewSequencer.cpp000066400000000000000000000102041352751253100251740ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Class definition for mpi slave sequencer for building // overview files. // //---------------------------------------------------------------------------- // $Id: ossimMpiSlaveOverviewSequencer.cpp 17870 2010-08-12 13:12:32Z sbortman $ #include #include /* To pick up OSSIM_HAS_MPI. */ #include /* For get byte order. */ #include #include #include #if OSSIM_HAS_MPI # include #endif ossimMpiSlaveOverviewSequencer::ossimMpiSlaveOverviewSequencer() : ossimOverviewSequencer(), m_rank(0), m_numberOfProcessors(1) { #if OSSIM_HAS_MPI MPI_Comm_rank(MPI_COMM_WORLD, &m_rank); MPI_Comm_size(MPI_COMM_WORLD, &m_numberOfProcessors); #endif if( m_rank != 0 ) { //--- // Master process (rank 0) does not resample tiles so our process rank // is 1 then we'll start at tile 0, rank 2 starts at 1, rank 3 starts // at 2 and so on... //--- m_currentTileNumber = m_rank -1; } else { m_currentTileNumber = 0; } } ossimMpiSlaveOverviewSequencer::~ossimMpiSlaveOverviewSequencer() { } bool ossimMpiSlaveOverviewSequencer::isMaster()const { return false; } void ossimMpiSlaveOverviewSequencer::initialize() { ossimOverviewSequencer::initialize(); m_currentTileNumber = m_rank-1; } void ossimMpiSlaveOverviewSequencer::setToStartOfSequence() { if(m_rank != 0) { //--- // Subtract one since the masters job is just writing and not issue // getTiles. //--- m_currentTileNumber = m_rank-1; } else { // the master will start at 0 m_currentTileNumber = 0; } } void ossimMpiSlaveOverviewSequencer::slaveProcessTiles() { #if OSSIM_HAS_MPI //--- // Bytes must be swapped to big endian (network byte order) if the scalar // type is not 8 bit and the system byte order is little endian. We will // use the endian pointer itself as a flag to swap. //--- ossimEndian* endian = 0; if (m_imageHandler.valid()) { if (m_imageHandler->getOutputScalarType() != OSSIM_UINT8) { if (ossim::byteOrder() != OSSIM_BIG_ENDIAN) { endian = new ossimEndian(); } } } // Total number of tiles for all processes. ossim_uint32 numberOfTiles = getNumberOfTiles(); int errorValue; // Needed for MPI_Isend and MPI_Wait. MPI_Request request; // Needed for MPI_Isend and MPI_Wait. while(m_currentTileNumber < numberOfTiles) { ossimRefPtr data = ossimOverviewSequencer::getNextTile(); void* buf = data->getBuf(); // Data always sent in big endian byte order. if (endian) { endian->swap(m_tile->getScalarType(), buf, m_tile->getSize()); } // Send the buffer to the master process. request = MPI_REQUEST_NULL; errorValue = MPI_Isend(buf, data->getSizeInBytes(), MPI_UNSIGNED_CHAR, 0, 0, MPI_COMM_WORLD, &request); //--- // Wait for send to complete before we overwrite the buffer with the // next tile. //--- errorValue = MPI_Wait(&request, MPI_STATUS_IGNORE); //--- // If we have eight processes only seven are used for resampling tiles, // so we would process every seventh tile. // // The call to getNextTile has already incremented m_currentTileNumber // by one so adjust accordingly. //--- if (m_numberOfProcessors>2) { m_currentTileNumber += (m_numberOfProcessors-2); } } // End of while loop through number of tiles. // cleanup... if (endian) { delete endian; endian = 0; } #endif /* End of #if OSSIM_HAS_MPI */ } ossim-Miami-2.9.1/src/parallel/ossimMultiThreadSequencer.cpp000066400000000000000000000440161352751253100241570ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // //! This class manages the sequencing of tile requests across multiple threads. Note that multi- //! threading can only be achieved through the use of getNextTile() method for sequencing. //! Conventional getTiles will not be multi-threaded. // //************************************************************************************************** // $Id$ #include #include #include #include static const ossim_uint32 DEFAULT_MAX_TILE_CACHE_FACTOR = 8; // Must be > 1 using namespace std; ossimMtDebug* ossimMtDebug::m_instance = NULL; //************************************************************************************************* // Job's start method performs actual getTile in a thread on cloned chain and saves the result // in the sequencer's results cache. //************************************************************************************************* void ossimMultiThreadSequencer::ossimGetTileJob::run() { running(); if (m_sequencer.d_debugEnabled) { ostringstream s1; s1<<"THREAD #"< tile = 0; ossimImageSource* source = m_sequencer.m_inputChain->getClone(m_chainID); double dt = ossimTimer::instance()->time_s(); //### if (source != NULL) tile = source->getTile(tileRect); if (!tile.valid()) { tile = m_sequencer.theBlankTile; tile->setImageRectangle(tileRect); } dt = ossimTimer::instance()->time_s() - dt; //### // Give the sequencer the tile. Execution may pause here while waiting for space to free up // if the cache is full. m_sequencer.setTileInCache(m_tileID, (ossimImageData*)tile->dup(), m_chainID, dt); } // Unblock the main thread which might be blocked waiting for jobs to finish: m_sequencer.m_getTileBlock.release(); // Queue the next job using this job's freed-up image chain: if (t_launchNewJob) m_sequencer.nextJob(m_chainID); finished(); if (m_sequencer.d_debugEnabled) { ostringstream s2; s2<<"THREAD #"<()), m_nextTileID (0), m_tileCache(), m_maxCacheSize (DEFAULT_MAX_TILE_CACHE_FACTOR * num_threads), m_maxTileCacheFactor (DEFAULT_MAX_TILE_CACHE_FACTOR), m_cacheMutex(), m_jobMutex(), m_totalNumberOfTiles(0), m_getTileBlock(), m_nextJobBlock(), d_printMutex(), d_timerMutex(), d_debugEnabled(false), d_timedBlocksDt(0), d_timeMetricsEnabled(false), d_useSharedHandlers(true), d_cacheTileSize(1024), d_useCache(true), d_t1(0.0) { //###### DEBUG ############ ossimMtDebug* mt_debug = ossimMtDebug::instance(); if (mt_debug->maxTileCacheSize != 0) m_maxCacheSize = mt_debug->maxTileCacheSize; d_debugEnabled = mt_debug->seqDebugEnabled; d_timedBlocksDt = mt_debug->seqTimedBlocksDt; d_timeMetricsEnabled = mt_debug->seqMetricsEnabled; //###### END DEBUG ############ // The base-class' initialize() method should have been called by the base class constructor // unless somebody moved it! m_nextJobBlock.release(); m_getTileBlock.release(); ossimTimer::instance()->setStartTick(); } //************************************************************************************************* // Destructor //************************************************************************************************* ossimMultiThreadSequencer::~ossimMultiThreadSequencer() { m_inputChain = 0; //!< Same as base class' theInputConnection m_jobMtQueue = 0; m_callback.reset(); } //************************************************************************************************* //! Overrides base class in order to implement multi-threaded tile requests. //************************************************************************************************* void ossimMultiThreadSequencer::setToStartOfSequence() { // Reset important indices: theCurrentTileNumber = 0; m_nextTileID = 0; m_totalNumberOfTiles = theNumberOfTilesHorizontal * theNumberOfTilesVertical; //! The base class should have successfully assigned its input: if (theInputConnection == NULL) return; // Check if this param was already set externally. Query the system capability if not: if (m_numThreads == 0) { m_numThreads = 2 * ossim::getNumberOfThreads(); m_maxCacheSize = m_maxTileCacheFactor * m_numThreads; } // Adapt the input source to be an ossimImageChainMtAdaptor since we can only work // with this type: m_inputChain = dynamic_cast(theInputConnection); if (m_inputChain.valid()) { m_inputChain->setNumberOfThreads(m_numThreads); m_inputChain->setUseSharedHandlers(d_useSharedHandlers); m_inputChain->setCacheTileSize(d_cacheTileSize); m_inputChain->setUseCache(d_useCache); } else { // Need to adapt input. First, is it a chain? ossimImageChain* chain = dynamic_cast(theInputConnection); if (chain == NULL) { // The input is just a common image source. Make it a chain: chain = new ossimImageChain; chain->add(theInputConnection); } // This instantiation creates a set of cloned image chains, one per thread, that will be // accessed in parallel for the getTile() operation: m_inputChain = new ossimImageChainMtAdaptor(chain, m_numThreads, d_useSharedHandlers, d_useCache, d_cacheTileSize); } // Set the output of the chain to be this sequencer: m_inputChain->disconnectAllOutputs(); //connectMyInputTo(m_inputChain.get()); //setAreaOfInterest(m_inputChain->getBoundingRect()); //// EXPERIMENTAL -- Fetch the first N tiles sequentially: for (ossim_uint32 i=0; i job = std::make_shared(m_nextTileID++, i, *this); job->setCallback(m_callback); job->t_launchNewJob = false; job->start(); } // Set up the job queue and fill it with first N jobs: ossim_uint32 num_jobs_to_launch = min(m_numThreads, m_totalNumberOfTiles); std::shared_ptr jobQueue = std::make_shared(); for (ossim_uint32 chain_id=0; chain_id job = std::make_shared(m_nextTileID++, chain_id, *this); job->setCallback(m_callback); jobQueue->add(job, false); } // Initialize the multi-thread queue. Note the setJobQueue is done after construction as it was // crashing do to jobs being launched during init: m_jobMtQueue = std::make_shared(nullptr, num_jobs_to_launch); m_jobMtQueue->setJobQueue(jobQueue); } //************************************************************************************************* //! Overrides base class in order to implement multi-threaded tile requests. The output tile //! should be available in the tile cache, otherwise, method waits until it becomes available. //************************************************************************************************* ossimRefPtr ossimMultiThreadSequencer::getNextTile(ossim_uint32 /*resLevel*/) { if (!m_inputChain.valid()) return NULL; // May need to initiate the threaded sequencing if not already done: if (m_nextTileID == 0) setToStartOfSequence(); // Terminate with null return if done: ossimRefPtr tile = 0; if (theCurrentTileNumber >= m_totalNumberOfTiles) { return tile; } // May need to wait until the corresponding job is finished if the tile is not in the cache: TileCache::iterator tile_iter = m_tileCache.begin(); while (!tile.valid()) { // If the tile is not yet copied into the cache, it means the job is still running. Let's // block this thread and let the getTile jobs unlock as they finish. We'll exit this loop // when the job of interest finishes. if (d_timeMetricsEnabled) d_t1 = ossimTimer::instance()->time_s(); m_cacheMutex.lock(); if (d_timeMetricsEnabled) d_idleTime1 += ossimTimer::instance()->time_s() - d_t1; // RP - Just grab the first tile for better performance, because order does not matter, we need // to process them all tile_iter = m_tileCache.begin(); //.find(theCurrentTileNumber); m_cacheMutex.unlock(); if (tile_iter == m_tileCache.end()) { if (d_debugEnabled) { ostringstream s1; s1<<"getNextTile() -- Waiting on tile #"<second; if (d_timeMetricsEnabled) d_t1 = ossimTimer::instance()->time_s(); m_cacheMutex.lock(); m_tileCache.erase(tile_iter); m_cacheMutex.unlock(); if (d_timeMetricsEnabled) d_idleTime3 += ossimTimer::instance()->time_s() - d_t1; if (m_tileCache.empty()) ++d_cacheEmptyCount; m_nextJobBlock.release(); // nextJob() may be blocked until cache space is freed } } // Advance the caller-requested tile ID. This is different from the last threaded getTile()'s // tile index maintained in m_nextTileID and advanced in initNextJob(): ++theCurrentTileNumber; return tile; } //************************************************************************************************* // Specifies number of thread to support. Default behavior (if this method is never called) is // query the system for number of cores available. //************************************************************************************************* void ossimMultiThreadSequencer::setNumberOfThreads(ossim_uint32 num_threads) { m_numThreads = num_threads; m_maxCacheSize = m_maxTileCacheFactor * m_numThreads; if (m_inputChain.valid()) m_inputChain->setNumberOfThreads(num_threads); if (m_jobMtQueue && m_jobMtQueue->hasJobsToProcess()) m_jobMtQueue->getJobQueue()->clear(); m_nextTileID = 0; // effectively resets this sequencer } void ossimMultiThreadSequencer::setUseSharedHandlers(bool use_shared_handlers) { d_useSharedHandlers = use_shared_handlers; if (m_inputChain.valid()) m_inputChain->setUseSharedHandlers(use_shared_handlers); } void ossimMultiThreadSequencer::setCacheTileSize(ossim_uint32 cache_tile_size) { d_cacheTileSize = cache_tile_size; if (m_inputChain.valid()) m_inputChain->setCacheTileSize(cache_tile_size); } void ossimMultiThreadSequencer::setUseCache(bool use_cache) { d_useCache = use_cache; if (m_inputChain.valid()) m_inputChain->setUseCache(use_cache); } //************************************************************************************************* //! Access method to tile cache with scope lock to avoid multiple threads writing to //! the cache simultaneously. //************************************************************************************************* void ossimMultiThreadSequencer::setTileInCache(ossim_uint32 tile_id, ossimImageData* tile, ossim_uint32 chain_id, double dt) { if (d_timeMetricsEnabled) d_t1 = ossimTimer::instance()->time_s(); std::lock_guard lock(m_cacheMutex); if (d_timeMetricsEnabled) d_idleTime4 += ossimTimer::instance()->time_s() - d_t1; d_jobGetTileT += dt; m_tileCache[tile_id] = tile; if (d_debugEnabled) { ostringstream s2; s2<<"THREAD #"<= m_totalNumberOfTiles) return; while (((ossim_uint32) m_tileCache.size()) >= m_maxCacheSize) { if (d_debugEnabled) { m_cacheMutex.lock(); TileCache::const_iterator iter = m_tileCache.begin(); ostringstream s1; s1<<"THREAD #"<time_s(); std::lock_guard lock(m_jobMutex); if (d_timeMetricsEnabled) d_idleTime6 += ossimTimer::instance()->time_s() - d_t1; std::shared_ptr job = std::make_shared(m_nextTileID++, chain_id, *this); job->setCallback(m_callback); m_jobMtQueue->getJobQueue()->add(job); } //************************************************************************************************* // For Debugging //************************************************************************************************* void ossimMultiThreadSequencer::print(ostringstream& msg) const { std::lock_guard lock(d_printMutex); cerr << msg.str() << endl; } double ossimMultiThreadSequencer::handlerGetTileT() { if (m_inputChain->m_sharedHandlers.empty()) return -1.0; ossimRefPtr ha = m_inputChain->m_sharedHandlers[0].get(); if (ha.valid()) return ha->d_getTileT; return -1; } bool ossimMultiThreadSequencer::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup; lookup = kwl.find(prefix, "num_threads"); if(lookup) { ossim_uint32 num_threads = ossimString(lookup).toUInt32(); setNumberOfThreads(num_threads); } lookup = kwl.find(prefix, "use_shared_handlers"); if(lookup) { bool use_shared_handlers = ossimString(lookup).toBool(); setUseSharedHandlers(use_shared_handlers); } lookup = kwl.find(prefix, "cache_tile_size"); if(lookup) { ossim_uint32 cache_tile_size = ossimString(lookup).toUInt32(); setCacheTileSize(cache_tile_size); } lookup = kwl.find(prefix, "use_cache"); if(lookup) { bool use_cache = ossimString(lookup).toBool(); setUseCache(use_cache); } bool status = ossimImageSourceSequencer::loadState(kwl, prefix); return status; } ossim-Miami-2.9.1/src/plugin/000077500000000000000000000000001352751253100160005ustar00rootroot00000000000000ossim-Miami-2.9.1/src/plugin/ossimDynamicLibrary.cpp000066400000000000000000000050241352751253100224710ustar00rootroot00000000000000//******************************************************************* // // LICENSE: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //********************************************************************* // $Id: ossimDynamicLibrary.cpp 20694 2012-03-19 12:22:05Z dburken $ #include #include #include #include // Static trace for debugging. static ossimTrace traceDebug(ossimString("ossimDynamicLibrary:debug")); ossimDynamicLibrary::ossimDynamicLibrary() :theLibrary(0) { } ossimDynamicLibrary::ossimDynamicLibrary(const ossimString& name) { load(name); } ossimDynamicLibrary::~ossimDynamicLibrary() { unload(); } bool ossimDynamicLibrary::load() { return load(theLibraryName); } bool ossimDynamicLibrary::load(const ossimString& name) { ossimFilename libraryName = name.trim(); if(libraryName.empty()||!libraryName.isFile()) return false; # if defined(__WIN32__) || defined(_WIN32) theLibrary = LoadLibrary(libraryName.c_str()); # else //theLibrary = dlopen(libraryName.c_str(), RTLD_LAZY|RTLD_LOCAL); // Use of RTLD_GLOBAL fixes CSM3 plugin with MSP loading CSM plugins, but requires unique // variable and method names in all *PluginInit.cpp code. theLibrary = dlopen(libraryName.c_str(), RTLD_LAZY|RTLD_GLOBAL); #endif if (isLoaded()) { theLibraryName = libraryName; } else { ossimNotify(ossimNotifyLevel_WARN)<<"ossimDynamicLibrary:"<<__LINE__ << " Failed to load library: " << name << std::endl; #if !defined(__WIN32__) && !defined(_WIN32) ossimNotify(ossimNotifyLevel_WARN) << dlerror() << std::endl; #endif } if (traceDebug()) { if (isLoaded()) { ossimNotify(ossimNotifyLevel_DEBUG)<<"ossimDynamicLibrary:"<<__LINE__ << " Loaded library: " << name << std::endl; } } return isLoaded(); } void ossimDynamicLibrary::unload() { if(isLoaded()) { #if defined(__WIN32__) || defined(_WIN32) FreeLibrary(theLibrary); // #else HAVE_DLFCN_H #else dlclose(theLibrary); #endif theLibrary = 0; } } void *ossimDynamicLibrary::getSymbol(const ossimString& name) const { if(isLoaded()) { #if defined(__WIN32__) || defined(_WIN32) return (void*)GetProcAddress( (HINSTANCE)theLibrary, name.c_str()); #else return dlsym(theLibrary, name.c_str()); #endif } return (void*)0; } ossim-Miami-2.9.1/src/plugin/ossimPluginLibrary.cpp000066400000000000000000000036331352751253100223470ustar00rootroot00000000000000//******************************************************************* /// // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimPluginLibrary.cpp 20694 2012-03-19 12:22:05Z dburken $ #include #include ossimPluginLibrary::ossimPluginLibrary() :ossimDynamicLibrary(), m_info(0) { } ossimPluginLibrary::ossimPluginLibrary(const ossimString& name, const ossimString& options) :ossimDynamicLibrary(name), m_options(options), m_info(0) { initialize(); } ossimPluginLibrary::~ossimPluginLibrary() { finalize(); } void ossimPluginLibrary::initialize() { if(!isLoaded()) { load(); } ossimSharedLibraryInitializePtr init = (ossimSharedLibraryInitializePtr)getSymbol("ossimSharedLibraryInitialize"); if(init) { init(&m_info, m_options.c_str()); } } void ossimPluginLibrary::finalize() { ossimSharedLibraryFinalizePtr finalizeLib = (ossimSharedLibraryFinalizePtr)getSymbol("ossimSharedLibraryFinalize"); if(finalizeLib) { finalizeLib(); } unload(); } ossimString ossimPluginLibrary::getDescription()const { ossimString result; if(m_info&&isLoaded()&&m_info->getDescription) { result = m_info->getDescription(); } return result; } void ossimPluginLibrary::getClassNames(std::vector& classNames)const { if(m_info&&m_info->getNumberOfClassNames&&m_info->getClassName) { ossim_int32 idx = 0; ossim_int32 numObjects = 0; numObjects = m_info->getNumberOfClassNames(); for(idx = 0; idx < numObjects; ++idx) { classNames.push_back(m_info->getClassName(idx)); } } } void ossimPluginLibrary::setOptions(const ossimString& options) { m_options = options; } ossim-Miami-2.9.1/src/plugin/ossimSharedObjectBridge.cpp000066400000000000000000000005771352751253100232420ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimSharedObjectBridge.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include extern "C" { } ossim-Miami-2.9.1/src/plugin/ossimSharedPluginRegistry.cpp000066400000000000000000000132201352751253100236730ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimSharedPluginRegistry.cpp 23326 2015-05-27 13:07:51Z dburken $ #include #include #include #include #include #include #include #include //ossimSharedPluginRegistry* ossimSharedPluginRegistry::theInstance = NULL; //ossimPluginBridgeStructure ossimSharedPluginRegistry::thePluginBridgeFactoryPointers; static ossimTrace traceDebug("ossimSharedPluginRegistry:debug"); ossimSharedPluginRegistry::ossimSharedPluginRegistry() { } ossimSharedPluginRegistry::~ossimSharedPluginRegistry() { theLibraryList.clear(); } ossimSharedPluginRegistry* ossimSharedPluginRegistry::instance() { static ossimSharedPluginRegistry sharedInstance; return &sharedInstance;//theInstance; } bool ossimSharedPluginRegistry::registerPlugin(const ossimFilename& filename, const ossimString& options)//, bool insertFrontFlag) { bool result = false; if(!getPlugin(filename)) { ossimPluginLibrary *lib =new ossimPluginLibrary; if(lib->load(filename)) { lib->setOptions(options); if(lib->getSymbol("ossimSharedLibraryInitialize")) { lib->initialize(); // if(!insertFrontFlag) // { theLibraryList.push_back(lib); // } // else // { // theLibraryList.insert(theLibraryList.begin(), lib); // } result = true; } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSharedPluginRegistry DEBUG:" << "ossimSharedLibraryInitialize symbol not found\n" << std::endl; } } if ( !result ) { delete lib; lib = 0; } } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: Plugin with the name " << filename << std::endl << "Already registered with OSSIM" << std::endl; } return result; } bool ossimSharedPluginRegistry::unregisterPlugin(int idx) { ossimPluginLibrary* lib = getPlugin(idx); return unregisterPlugin(lib); } bool ossimSharedPluginRegistry::unregisterPlugin(ossimPluginLibrary* library) { std::vector >::iterator iter = theLibraryList.begin(); while(iter!=theLibraryList.end()) { if((*iter).get() == library) { theLibraryList.erase(iter); return true; } ++iter; } return false; } const ossimPluginLibrary* ossimSharedPluginRegistry::getPlugin(const ossimFilename& filename)const { ossim_uint32 idx = 0; ossimFilename fileOnly = filename.file(); for(idx = 0; idx < theLibraryList.size();++idx) { if(fileOnly == ossimFilename(theLibraryList[idx]->getName()).file()) { return theLibraryList[idx].get(); } } return 0; } ossimPluginLibrary* ossimSharedPluginRegistry::getPlugin(const ossimFilename& filename) { ossim_uint32 idx = 0; ossimFilename fileOnly = filename.file(); for(idx = 0; idx < theLibraryList.size();++idx) { if(fileOnly == ossimFilename(theLibraryList[idx]->getName()).file()) { return theLibraryList[idx].get(); } } return 0; } ossim_uint32 ossimSharedPluginRegistry::getIndex(const ossimPluginLibrary* lib)const { ossim_uint32 idx = 0; for(idx = 0; idx < theLibraryList.size(); ++idx) { if(theLibraryList[idx] == lib) { return idx; } } return idx; } ossimPluginLibrary* ossimSharedPluginRegistry::getPlugin(ossim_uint32 idx) { ossimPluginLibrary* result = 0; if(idx < theLibraryList.size()) { result = theLibraryList[idx].get(); } return result; } const ossimPluginLibrary* ossimSharedPluginRegistry::getPlugin(ossim_uint32 idx)const { const ossimPluginLibrary* result = 0; if(idx < theLibraryList.size()) { result = theLibraryList[idx].get(); } return result; } ossim_uint32 ossimSharedPluginRegistry::getNumberOfPlugins()const { return (ossim_uint32)theLibraryList.size(); } bool ossimSharedPluginRegistry::isLoaded(const ossimFilename& filename) const { ossimFilename fileOnly = filename.file(); bool result = false; ossim_uint32 count = getNumberOfPlugins(); for (ossim_uint32 i = 0; i < count; ++i) { const ossimPluginLibrary* pi = getPlugin(i); if (pi) { if (fileOnly == ossimFilename(pi->getName()).file()) { result = true; break; } } } return result; } void ossimSharedPluginRegistry::printAllPluginInformation(std::ostream& out) { ossim_uint32 count = getNumberOfPlugins(); ossim_uint32 idx = 0; for(idx = 0; idx < count; ++idx) { std::vector classNames; const ossimPluginLibrary* pi = getPlugin(idx); if(pi) { pi->getClassNames(classNames); out << "Plugin: " << pi->getName() << std::endl; out << "DESCRIPTION: \n"; out << pi->getDescription() << "\n"; out << "CLASSES SUPPORTED\n "; std::copy(classNames.begin(), classNames.end(), std::ostream_iterator(out, "\n ")); out << "\n"; } } } ossim-Miami-2.9.1/src/point_cloud/000077500000000000000000000000001352751253100170215ustar00rootroot00000000000000ossim-Miami-2.9.1/src/point_cloud/ossimGenericPointCloudHandler.cpp000066400000000000000000000041171352751253100254560ustar00rootroot00000000000000#include using namespace std; ossimGenericPointCloudHandler::ossimGenericPointCloudHandler(vector& ecef_points) { // Fill the point storage in any order. // Loop to add your points (assume your points are passed in a vector ecef_points[]) for (ossim_uint32 i=0; i& ground_points) { // Fill the point storage in any order. // Loop to add your points (assume your points are passed in a vector ecef_points[]) for (ossim_uint32 i=0; i= m_pointBlock.size()) return; for (ossim_uint32 i=offset; i using namespace std; RTTI_DEF1(ossimPointBlock, "ossimPointBlock", ossimDataObject) ossimPointBlock::ossimPointBlock(ossimSource* owner, ossim_uint32 fields) : ossimDataObject(owner), m_nullPCR(fields), m_minMaxValid(false), m_fieldCode(0), m_isNormalized(false) { } ossimPointBlock::~ossimPointBlock() { } void ossimPointBlock::getFieldMin(ossimPointRecord::FIELD_CODES field, ossim_float32& value) const { if (empty()) value = ossim::nan(); else if (!m_minMaxValid) scanForMinMax(); value = m_minRecord.getField(field); } void ossimPointBlock::getFieldMax(ossimPointRecord::FIELD_CODES field, ossim_float32& value) const { if (empty()) value = ossim::nan(); else if (!m_minMaxValid) scanForMinMax(); value = m_maxRecord.getField(field); } void ossimPointBlock::getBounds(ossimGrect& block_bounds) const { if (!m_minMaxValid) scanForMinMax(); block_bounds = ossimGrect(m_minRecord.getPosition(), m_maxRecord.getPosition()); } const ossimPointRecord* ossimPointBlock::getPoint(ossim_uint32 point_offset) const { if (point_offset < m_pointList.size()) return m_pointList[point_offset].get(); return 0; } ossimPointRecord* ossimPointBlock::getPoint(ossim_uint32 point_offset) { if (point_offset < m_pointList.size()) return m_pointList[point_offset].get(); return 0; } const ossimPointBlock& ossimPointBlock::operator=(const ossimPointBlock& block ) { ossim_uint32 numPoints = block.size(); if (numPoints == 0) return *this; for (ossim_uint32 i=0; igetFieldCode(); return m_fieldCode; } vector ossimPointBlock::getFieldCodesAsList() const { vector code_list; if (m_fieldCode & ossimPointRecord::Intensity) code_list.push_back(ossimPointRecord::Intensity); if (m_fieldCode & ossimPointRecord::ReturnNumber) code_list.push_back(ossimPointRecord::ReturnNumber); if (m_fieldCode & ossimPointRecord::NumberOfReturns) code_list.push_back(ossimPointRecord::NumberOfReturns); if (m_fieldCode & ossimPointRecord::Red) code_list.push_back(ossimPointRecord::Red); if (m_fieldCode & ossimPointRecord::Green) code_list.push_back(ossimPointRecord::Green); if (m_fieldCode & ossimPointRecord::Blue) code_list.push_back(ossimPointRecord::Blue); if (m_fieldCode & ossimPointRecord::GpsTime) code_list.push_back(ossimPointRecord::GpsTime); if (m_fieldCode & ossimPointRecord::Infrared) code_list.push_back(ossimPointRecord::Infrared); return code_list; } void ossimPointBlock::setFieldCode(ossim_uint32 code) { if (getFieldCode() != code) clear(); m_fieldCode = code; } void ossimPointBlock::addPoint(ossimPointRecord* opr) { // First check that the fields match the expected. If not, sync up to this point: if ((opr->getFieldCode() & m_fieldCode) != m_fieldCode) m_fieldCode = opr->getFieldCode(); m_pointList.push_back(ossimRefPtr(opr)); m_minMaxValid = false; } void ossimPointBlock::scanForMinMax() const { ossim_uint32 numPoints = size(); if (numPoints == 0) return; // Latch first point: m_minRecord = *(m_pointList[0].get()); m_maxRecord = m_minRecord; ossimGpt minPos (m_minRecord.getPosition()); ossimGpt maxPos (minPos); // For shorthand later: const ossimPointRecord::FIELD_CODES I = ossimPointRecord::Intensity; const ossimPointRecord::FIELD_CODES R = ossimPointRecord::Red; const ossimPointRecord::FIELD_CODES G = ossimPointRecord::Green; const ossimPointRecord::FIELD_CODES B = ossimPointRecord::Blue; const ossimPointRecord::FIELD_CODES S = ossimPointRecord::ReturnNumber; const ossimPointRecord::FIELD_CODES N = ossimPointRecord::NumberOfReturns; // If color available, latch the min for all bands as one to minimize color distortion: bool hasRGB = false; if (m_minRecord.hasFields(R|G|B)) { hasRGB = true; ossim_float32 r = m_pointList[0]->getField(R); ossim_float32 g = m_pointList[0]->getField(G); ossim_float32 b = m_pointList[0]->getField(B); float minC = std::min(r, std::min(g, b)); float maxC = std::max(r, std::max(g, b)); m_minRecord.setField(R, minC); m_minRecord.setField(G, minC); m_minRecord.setField(B, minC); m_maxRecord.setField(R, maxC); m_maxRecord.setField(G, maxC); m_maxRecord.setField(B, maxC); } // Now loop over all points in file to latch min/max: for (ossim_uint32 i=0; igetPosition().lat < minPos.lat) minPos.lat = m_pointList[i]->getPosition().lat; if (m_pointList[i]->getPosition().lon < minPos.lon) minPos.lon = m_pointList[i]->getPosition().lon; if (m_pointList[i]->getPosition().hgt < minPos.hgt) minPos.hgt = m_pointList[i]->getPosition().hgt; if (m_pointList[i]->getPosition().lat > maxPos.lat) maxPos.lat = m_pointList[i]->getPosition().lat; if (m_pointList[i]->getPosition().lon > maxPos.lon) maxPos.lon = m_pointList[i]->getPosition().lon; if (m_pointList[i]->getPosition().hgt > maxPos.hgt) maxPos.hgt = m_pointList[i]->getPosition().hgt; if (m_minRecord.hasFields(I) && (m_minRecord.getField(I) > m_pointList[i]->getField(I))) m_minRecord.setField(I, m_pointList[i]->getField(I)); if (m_minRecord.hasFields(S) && (m_minRecord.getField(S) > m_pointList[i]->getField(S))) m_minRecord.setField(S, m_pointList[i]->getField(S)); if (m_minRecord.hasFields(N) && (m_minRecord.getField(N) > m_pointList[i]->getField(N))) m_minRecord.setField(N, m_pointList[i]->getField(N)); if (hasRGB) { ossim_float32 r = m_pointList[i]->getField(R); ossim_float32 g = m_pointList[i]->getField(G); ossim_float32 b = m_pointList[i]->getField(B); float minC = std::min(r, std::min(g, b)); if (m_minRecord.getField(R) > minC) { m_minRecord.setField(R, minC); m_minRecord.setField(G, minC); m_minRecord.setField(B, minC); } float maxC = std::max(r, std::max(g, b)); if (m_maxRecord.getField(R) < maxC) { m_maxRecord.setField(R, maxC); m_maxRecord.setField(G, maxC); m_maxRecord.setField(B, maxC); } } } // end loop over all points m_minRecord.setPosition(minPos); m_maxRecord.setPosition(maxPos); m_minMaxValid = true; } ossim-Miami-2.9.1/src/point_cloud/ossimPointCloudGeometry.cpp000066400000000000000000000047571352751253100244110ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: LGPL -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #include #include #include #include #include RTTI_DEF1(ossimPointCloudGeometry, "ossimPointCloudGeometry" , ossimObject); ossimPointCloudGeometry::ossimPointCloudGeometry(const ossimString& wkt) : m_format(GEOGRAPHIC), m_projection(0), m_datum(ossimDatumFactory::instance()->wgs84()) { // Establish projection from WKT: m_projection = dynamic_cast( ossimWktProjectionFactory::instance()->createProjection(wkt)); if (m_projection.valid()) { m_datum = m_projection->getDatum(); if (!m_projection->isGeographic()) m_format = MAP_PROJECTED; } } bool ossimPointCloudGeometry::operator==(const ossimPointCloudGeometry& other) const { if (m_format != other.m_format) return false; if (m_projection.valid() && other.m_projection.valid() && (*m_projection == *(other.m_projection))) return true; return false; } void ossimPointCloudGeometry::convertPos(const ossimDpt3d& oldPt, ossimGpt& converted_gpos) const { converted_gpos.makeNan(); // If the data buffer has existing points, transform them into the new projection and datum: if (m_format == GEOGRAPHIC) { ossimGpt gpt (oldPt.y, oldPt.x, oldPt.z, m_datum); gpt.changeDatum(converted_gpos.datum()); converted_gpos = gpt; } else if ((m_format == MAP_PROJECTED) && m_projection.valid()) { ossimUnitConversionTool uct (1.0, m_projection->getProjectionUnits()); double coord_scale = uct.getMeters(); //Need to convert map E, N to lat, lon ossimDpt oldMapPt(oldPt.x*coord_scale, oldPt.y*coord_scale); ossimGpt gpt(getProjection()->inverse(oldMapPt)); gpt.changeDatum(m_datum); gpt.hgt = oldPt.z*coord_scale; gpt.changeDatum(converted_gpos.datum()); converted_gpos = gpt; } else if (m_format == ECF_METERS) { ossimEcefPoint oldEcfPt(oldPt); converted_gpos = ossimGpt (oldEcfPt, converted_gpos.datum()); } return; } ossim-Miami-2.9.1/src/point_cloud/ossimPointCloudHandler.cpp000066400000000000000000000055241352751253100241640ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: LGPL -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #include using namespace std; RTTI_DEF1(ossimPointCloudHandler, "ossimPointCloudHandler" , ossimPointCloudSource); ossim_uint32 ossimPointCloudHandler::DEFAULT_BLOCK_SIZE = 0x400000; ossimPointCloudHandler::ossimPointCloudHandler() : m_currentPID(0) { } ossimPointCloudHandler::ossimPointCloudHandler(ossimObject* owner) : ossimPointCloudSource(owner), m_currentPID(0) { } ossimPointCloudHandler::~ossimPointCloudHandler() { } void ossimPointCloudHandler::getNextFileBlock(ossimPointBlock& block, ossim_uint32 maxPts) const { getFileBlock(m_currentPID, block, maxPts); return; } void ossimPointCloudHandler::getBlock(const ossimGrect& bounds, ossimPointBlock& block) const { block.clear(); // This default implementation simply reads the whole datafile in file-blocks, retaining // only those points inside the bounds: ossimPointBlock file_block; rewind(); ossimGpt gpt; do { file_block.clear(); getNextFileBlock(file_block, DEFAULT_BLOCK_SIZE); ossimPointBlock::PointList& pointList = file_block.getPoints(); ossimPointBlock::PointList::iterator iter = pointList.begin(); while (iter != pointList.end()) { gpt = (*iter)->getPosition(); if (bounds.pointWithin(gpt)) { block.addPoint(iter->get()); } ++iter; } } while (file_block.size() == DEFAULT_BLOCK_SIZE); } void ossimPointCloudHandler::getBounds(ossimGrect& bounds) const { if (m_minRecord.valid() && m_maxRecord.valid()) bounds = ossimGrect(m_minRecord->getPosition(), m_maxRecord->getPosition()); else bounds.makeNan(); } void ossimPointCloudHandler::normalizeBlock(ossimPointBlock& block) { if (!m_minRecord.valid() || !m_maxRecord.valid()) return; ossim_uint32 numPoints = block.size(); float val, norm, min, max; vector field_codes = block.getFieldCodesAsList(); vector::const_iterator iter; ossimPointRecord::FIELD_CODES field_code; for (ossim_uint32 i=0; igetField(field_code); max = m_maxRecord->getField(field_code); val = opr->getField(field_code); norm = (val - min) / (max - min); opr->setField(field_code, norm); ++iter; } } } ossim-Miami-2.9.1/src/point_cloud/ossimPointCloudHandlerRegistry.cpp000066400000000000000000000056561352751253100257230ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: LGPL -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #include #include #include ossimPointCloudHandlerRegistry* ossimPointCloudHandlerRegistry::m_instance = 0; RTTI_DEF1(ossimPointCloudHandlerRegistry, "ossimPointCloudHandlerRegistry" , ossimObjectFactory); ossimPointCloudHandlerRegistry::ossimPointCloudHandlerRegistry() { // TODO Auto-generated constructor stub } ossimPointCloudHandlerRegistry::~ossimPointCloudHandlerRegistry() { // TODO Auto-generated destructor stub } ossimPointCloudHandlerRegistry* ossimPointCloudHandlerRegistry::instance() { if (m_instance) return m_instance; m_instance = new ossimPointCloudHandlerRegistry; return m_instance; } ossimPointCloudHandler* ossimPointCloudHandlerRegistry::open(const ossimFilename& fileName) const { ossimPointCloudHandler* result = NULL; std::vector::const_iterator factory; factory = m_factoryList.begin(); while((factory != m_factoryList.end()) && !result) { result = (*factory)->open(fileName); ++factory; } return result; } ossimPointCloudHandler* ossimPointCloudHandlerRegistry::open(const ossimKeywordlist& kwl, const char* prefix) const { ossimPointCloudHandler* result = NULL; std::vector::const_iterator factory; factory = m_factoryList.begin(); while((factory != m_factoryList.end()) && !result) { result = (*factory)->open(kwl, prefix); ++factory; } return result; } ossimRefPtr ossimPointCloudHandlerRegistry::open(std::istream* /*str*/, std::streamoff /*restartPosition*/, bool /*youOwnIt*/) const { // TODO Auto-generated constructor stub return 0; } ossimObject* ossimPointCloudHandlerRegistry::createObject(const ossimString& typeName) const { return createObjectFromRegistry(typeName); } ossimObject* ossimPointCloudHandlerRegistry::createObject(const ossimKeywordlist& kwl, const char* prefix) const { return createObjectFromRegistry(kwl, prefix); } const ossimPointCloudHandlerRegistry& ossimPointCloudHandlerRegistry::operator=( const ossimPointCloudHandlerRegistry& /*rhs*/) { return *this; } void ossimPointCloudHandlerRegistry::getTypeNameList(std::vector& typeList) const { getAllTypeNamesFromRegistry(typeList); } ossim-Miami-2.9.1/src/point_cloud/ossimPointCloudImageHandler.cpp000066400000000000000000000616731352751253100251360ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: LGPL -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimPointCloudImageHandler:debug"); static const char* GSD_FACTOR_KW = "gsd_factor"; static const char* COMPONENT_KW = "component"; // The member m_activeComponent should be one of the following strings. This is set either in a // state KWL or by a call to setProperty(<"active_component", >) static const char* INTENSITY_KW = "INTENSITY"; static const char* HIGHEST_KW = "HIGHEST"; static const char* LOWEST_KW = "LOWEST"; static const char* RETURNS_KW = "RETURNS"; static const char* RGB_KW = "RGB"; ossimPointCloudImageHandler::PcrBucket::PcrBucket(const ossim_float32* init_value, ossim_uint32 numBands) : m_numSamples (1) { m_bucket = new ossim_float32[numBands]; for (ossim_uint32 i=0; iopen(theImageFile); if (!m_pch.valid()) return false; getImageGeometry(); ossimImageHandler::completeOpen(); // Needed here after open to make sure that min/max pixels are set for active component/entry setCurrentEntry((ossim_uint32)m_activeComponent); return true; } bool ossimPointCloudImageHandler::setPointCloudHandler(ossimPointCloudHandler* pch) { close(); // Need to utilize the Point Cloud handler registry to open the PC file: m_pch = pch; if (!m_pch.valid()) return false; getImageGeometry(); ossimImageHandler::completeOpen(); // Needed here after open to make sure that min/max pixels are set for active component/entry setCurrentEntry((ossim_uint32)m_activeComponent); return true; } void ossimPointCloudImageHandler::close() { if (isOpen()) { m_pch->close(); m_tile = 0; ossimImageHandler::close(); } } ossimRefPtr ossimPointCloudImageHandler::getImageGeometry() { if (!isOpen()) return 0; if (theGeometry.valid()) return theGeometry; // Check for external geom (i.e., a *.geom file) theGeometry = getExternalImageGeometry(); if (theGeometry.valid()) return theGeometry; theGeometry = new ossimImageGeometry(); ossimString epsgCode ("EPSG:4326"); ossimMapProjection* proj = dynamic_cast( // NOLINT ossimEpsgProjectionFactory::instance()->createProjection(epsgCode)); if (!proj) return 0; theGeometry->setProjection(proj); // Need to establish image bounds and optimal GSD given ground rect. Use this switch to also // initialize the UL tiepoint of image projection: ossimGrect bounds; m_pch->getBounds(bounds); proj->setOrigin(bounds.ul()); proj->setUlTiePoints(bounds.ul()); // The GSD depends on the point density on the ground. count all final returns and // assume they are evenly distributed over the bounding ground rect. Note that this can have // up to a sqrt(2)X error if the collection was taken in a cardinal-diagonal direction. // Also use this point loop to latch the ground quad vertices vertices. ossim_uint32 numPulses = m_pch->getNumPoints(); // count of final returns if (numPulses == 0) { // Not yet determined. Set GSD to NAN and expect it will be set later: m_gsd.makeNan(); } else if (m_gsd.hasNans()) { ossimDpt delta (bounds.widthMeters(), bounds.heightMeters()); ossim_float64 gsd = sqrt(delta.x * delta.y / numPulses) * m_gsdFactor; setGSD(gsd); // also recomputes the image size } return theGeometry; } ossimRefPtr ossimPointCloudImageHandler::getTile(const ossimIrect& tile_rect, ossim_uint32 resLevel) { if (!m_tile.valid()) initTile(); // Image rectangle must be set prior to calling getTile. m_tile->setImageRectangle(tile_rect); if (!getTile(m_tile.get(), resLevel)) { if (m_tile->getDataObjectStatus() != OSSIM_NULL) m_tile->makeBlank(); } return m_tile; } bool ossimPointCloudImageHandler::getTile(ossimImageData* result, ossim_uint32 resLevel) { // check for all systems go and valid args: if (!m_pch.valid() || !result || (result->getScalarType() != OSSIM_FLOAT32) || (result->getDataObjectStatus() == OSSIM_NULL) || m_gsd.hasNans()) { return false; } // Overviews achieved with GSD setting. This may be too slow. ossimDpt gsd (m_gsd); if (resLevel > 0) getGSD(gsd, resLevel); // Establish the ground and image rects for this tile: const ossimIrect img_tile_rect = result->getImageRectangle(); const ossimIpt tile_offset (img_tile_rect.ul()); const ossim_uint32 tile_width = img_tile_rect.width(); const ossim_uint32 tile_height = img_tile_rect.height(); const ossim_uint32 tile_size = img_tile_rect.area(); ossimGpt gnd_ul, gnd_lr; ossimDpt dpt_ul (img_tile_rect.ul().x - 0.5, img_tile_rect.ul().y - 0.5); ossimDpt dpt_lr (img_tile_rect.lr().x + 0.5, img_tile_rect.lr().y + 0.5); theGeometry->rnToWorld(dpt_ul, resLevel, gnd_ul); theGeometry->rnToWorld(dpt_lr, resLevel, gnd_lr); const ossimGrect gnd_rect (gnd_ul, gnd_lr); // Create array of buckets to store accumulated point data. ossim_uint32 numBands = result->getNumberOfBands(); if (numBands > getNumberOfInputBands()) { // This should never happen; ossimNotify(ossimNotifyLevel_FATAL) << "ossimPointCloudImageHandler::getTile() ERROR: \n" << "More bands were requested than was available from the point cloud source. Returning " << "blank tile." << endl; result->makeBlank(); return false; } std::map accumulator; // initialize a point block with desired fields as requested in the reader properties ossimPointBlock pointBlock (this); pointBlock.setFieldCode(componentToFieldCode()); m_pch->rewind(); ossimDpt ipt; ossimGpt pos; #define USE_GETBLOCK #ifdef USE_GETBLOCK m_pch->getBlock(gnd_rect, pointBlock); for (ossim_uint32 id=0; idgetPosition(); theGeometry->worldToRn(pos, resLevel, ipt); ipt.x = ossim::round(ipt.x) - tile_offset.x; ipt.y = ossim::round(ipt.y) - tile_offset.y; ossim_int32 bucketIndex = ipt.y*tile_width + ipt.x; if ((bucketIndex >= 0) && (bucketIndex < (ossim_int32)tile_size)) addSample(accumulator, bucketIndex, pointBlock[id]); } #else // using getFileBlock ossim_uint32 numPoints = m_pch->getNumPoints(); if (numPoints > ossimPointCloudHandler::DEFAULT_BLOCK_SIZE) numPoints = ossimPointCloudHandler::DEFAULT_BLOCK_SIZE; // Loop to read all point blocks: do { pointBlock.clear(); m_pch->getNextFileBlock(pointBlock, numPoints); //m_pch->normalizeBlock(pointBlock); for (ossim_uint32 id=0; idgetPosition(); if (gnd_rect.pointWithin(pos)) { theGeometry->worldToRn(pos, resLevel, ipt); ipt.x = ossim::round(ipt.x) - tile_offset.x; ipt.y = ossim::round(ipt.y) - tile_offset.y; ossim_int32 bucketIndex = ipt.y*tile_width + ipt.x; if ((bucketIndex >= 0) && (bucketIndex < (ossim_int32)tile_size)) addSample(accumulator, bucketIndex, pointBlock[id]); } } } while (pointBlock.size() == numPoints); #endif // Finished accumulating, need to normalize and fill the tile. // We must always blank out the tile as we may not have a point for every pixel. normalize(accumulator); auto buf = new ossim_float32*[numBands]; std::map::iterator accum_iter; ossim_float32 null_pixel = OSSIM_DEFAULT_NULL_PIX_FLOAT; result->setNullPix(null_pixel); for (ossim_uint32 band = 0; band < numBands; band++) { ossim_uint32 index = 0; buf[band] = result->getFloatBuf(band); for (ossim_uint32 y = 0; y < tile_height; y++) { for (ossim_uint32 x = 0; x < tile_width; x++) { accum_iter = accumulator.find(index); if (accum_iter != accumulator.end()) buf[band][index] = accum_iter->second->m_bucket[band]; else buf[band][index] = null_pixel; ++index; } } } delete [] buf; buf = 0; auto pcr_iter = accumulator.begin(); while (pcr_iter != accumulator.end()) { delete pcr_iter->second; pcr_iter++; } result->validate(); return true; } void ossimPointCloudImageHandler::addSample(std::map& accumulator, ossim_int32 index, const ossimPointRecord* sample) { if (sample == 0) return; //cout << "sample: "<<*sample<getField(ossimPointRecord::Intensity)); } else if (m_activeComponent == RGB) { ossim_float32 color[3]; color[0] = sample->getField(ossimPointRecord::Red); color[1] = sample->getField(ossimPointRecord::Green); color[2] = sample->getField(ossimPointRecord::Blue); accumulator[index] = new PcrBucket(color, 3); } else if ((m_activeComponent == LOWEST) || (m_activeComponent == HIGHEST)) accumulator[index] = new PcrBucket(sample->getPosition().hgt); else if (m_activeComponent == RETURNS) accumulator[index] = new PcrBucket(sample->getField(ossimPointRecord::NumberOfReturns)); } else { // Not the first hit at this location, accumulate: // First hit. Initialize location with current sample: if (m_activeComponent == INTENSITY) { iter->second->m_bucket[0] += sample->getField(ossimPointRecord::Intensity); } else if (m_activeComponent == RGB) { iter->second->m_bucket[0] += sample->getField(ossimPointRecord::Red); iter->second->m_bucket[1] += sample->getField(ossimPointRecord::Green); iter->second->m_bucket[2] += sample->getField(ossimPointRecord::Blue); } else if ((m_activeComponent == HIGHEST) && (sample->getPosition().hgt > iter->second->m_bucket[0])) iter->second->m_bucket[0] = sample->getPosition().hgt; else if ((m_activeComponent == LOWEST) && (sample->getPosition().hgt < iter->second->m_bucket[0])) iter->second->m_bucket[0] = sample->getPosition().hgt; else if (m_activeComponent == RETURNS) iter->second->m_bucket[0] += sample->getField(ossimPointRecord::NumberOfReturns); iter->second->m_numSamples++; } } void ossimPointCloudImageHandler::normalize(std::map& accumulator) { // highest and lowest elevations latch extremes, no mean is computed but needs to be normalized if ((m_activeComponent == LOWEST) || (m_activeComponent == HIGHEST) || (m_activeComponent == RETURNS)) return; int numBands = 1; if (m_activeComponent == RGB) numBands = 3; auto iter = accumulator.begin(); ossim_float32 avg; while (iter != accumulator.end()) { for (int i=0; isecond->m_bucket[i] / iter->second->m_numSamples; iter->second->m_bucket[i] = avg; } iter++; } } ossim_uint32 ossimPointCloudImageHandler::getNumberOfInputBands() const { ossim_uint32 numBands = 0; if (m_pch.valid()) { if (m_activeComponent == INTENSITY) numBands = 1; else if (m_activeComponent == RGB) numBands = 3; else if ((m_activeComponent == LOWEST) || (m_activeComponent == HIGHEST)) numBands = 1; else if (m_activeComponent == RETURNS) numBands = 1; } return numBands; } ossim_uint32 ossimPointCloudImageHandler::getNumberOfLines(ossim_uint32 resLevel) const { ossim_uint32 result = 0; if (isOpen() && theGeometry.valid()) { ossimIpt image_size(theGeometry->getImageSize()); result = image_size.line; if (resLevel) result = (result >> resLevel); } return result; } ossim_uint32 ossimPointCloudImageHandler::getNumberOfSamples(ossim_uint32 resLevel) const { ossim_uint32 result = 0; if (isOpen() && theGeometry.valid()) { ossimIpt image_size(theGeometry->getImageSize()); result = image_size.samp; if (resLevel) result = (result >> resLevel); } return result; } ossim_uint32 ossimPointCloudImageHandler::getImageTileWidth() const { return getTileWidth(); } ossim_uint32 ossimPointCloudImageHandler::getImageTileHeight() const { return getTileHeight(); } ossim_uint32 ossimPointCloudImageHandler::getTileWidth() const { ossimIpt ipt; ossim::defaultTileSize(ipt); return ipt.x; } ossim_uint32 ossimPointCloudImageHandler::getTileHeight() const { ossimIpt ipt; ossim::defaultTileSize(ipt); return ipt.y; } ossimScalarType ossimPointCloudImageHandler::getOutputScalarType() const { return OSSIM_FLOAT32; } void ossimPointCloudImageHandler::getEntryList(std::vector& entryList) const { entryList.clear(); for (ossim_uint32 i = 0; i < m_componentNames.size(); i++) { entryList.emplace_back(i); } } void ossimPointCloudImageHandler::getEntryNames(std::vector& entryNames) const { entryNames = m_componentNames; } ossim_uint32 ossimPointCloudImageHandler::getCurrentEntry() const { return (ossim_uint32) m_activeComponent; } bool ossimPointCloudImageHandler::setCurrentEntry(ossim_uint32 entryIdx) { if (entryIdx >= NUM_COMPONENTS) return false; m_activeComponent = (Components) entryIdx; if (m_pch.valid() && m_pch->getMinPoint() && m_pch->getMaxPoint()) { if (m_activeComponent == INTENSITY) { m_minPixel = m_pch->getMinPoint()->getField(ossimPointRecord::Intensity); m_maxPixel = m_pch->getMaxPoint()->getField(ossimPointRecord::Intensity); } else if (m_activeComponent == RGB) { m_minPixel = m_pch->getMinPoint()->getField(ossimPointRecord::Red); m_maxPixel = m_pch->getMaxPoint()->getField(ossimPointRecord::Red); } else if ((m_activeComponent == LOWEST) || (m_activeComponent == HIGHEST)) { m_minPixel = m_pch->getMinPoint()->getPosition().hgt; m_maxPixel = m_pch->getMaxPoint()->getPosition().hgt; } else if (m_activeComponent == RETURNS) { m_minPixel = 0; m_maxPixel = m_pch->getMaxPoint()->getField(ossimPointRecord::NumberOfReturns); } } return true; } ossimString ossimPointCloudImageHandler::getShortName() const { return ossimString("Point Cloud Image Handler"); } ossimString ossimPointCloudImageHandler::getLongName() const { return ossimString("ossim point cloud to image renderer"); } double ossimPointCloudImageHandler::getMinPixelValue(ossim_uint32 /* band */) const { return m_minPixel; } double ossimPointCloudImageHandler::getMaxPixelValue(ossim_uint32 /* band */) const { return m_maxPixel; } double ossimPointCloudImageHandler::getNullPixelValue(ossim_uint32 /* band */) const { return OSSIM_DEFAULT_NULL_PIX_FLOAT; } ossim_uint32 ossimPointCloudImageHandler::getNumberOfDecimationLevels() const { // Can support any number of rlevels. ossim_uint32 result = 1; const ossim_uint32 STOP_DIMENSION = 16; ossim_uint32 largestImageDimension = getNumberOfSamples(0) > getNumberOfLines(0) ? getNumberOfSamples(0) : getNumberOfLines(0); while (largestImageDimension > STOP_DIMENSION) { largestImageDimension /= 2; ++result; } return result; } void ossimPointCloudImageHandler::initTile() { const ossim_uint32 BANDS = getNumberOfOutputBands(); m_tile = new ossimImageData(this, getOutputScalarType(), BANDS, getTileWidth(), getTileHeight()); for (ossim_uint32 band = 0; band < BANDS; ++band) { m_tile->setMinPix(getMinPixelValue(band), band); m_tile->setMaxPix(getMaxPixelValue(band), band); m_tile->setNullPix(getNullPixelValue(band), band); } m_tile->initialize(); } void ossimPointCloudImageHandler::getGSD(ossimDpt& gsd, ossim_uint32 resLevel) const { // std::pow(2.0, 0) returns 1. ossim_float64 d = std::pow(2.0, static_cast(resLevel)); gsd.x = m_gsd.x * d; gsd.y = m_gsd.y * d; } void ossimPointCloudImageHandler::setGSD(const ossim_float64& gsd) { if (ossim::isnan(gsd) || (gsd<=0.0) || !theGeometry.valid()) return; m_gsd = ossimDpt(gsd, gsd); m_gsdFactor = 1.0; // resets after GSD adjusted ossimMapProjection* proj = dynamic_cast(theGeometry->getProjection()); if (!proj) return; proj->setMetersPerPixel(m_gsd); ossimGrect bounds; m_pch->getBounds(bounds); ossimDpt ipt_ul, ipt_lr; theGeometry->worldToLocal(bounds.ul(), ipt_ul); theGeometry->worldToLocal(bounds.lr(), ipt_lr); ossimIpt image_size; image_size.x = ossim::round(ipt_lr.x - ipt_ul.x) + 1; image_size.y = ossim::round(ipt_lr.y - ipt_ul.y) + 1; theGeometry->setImageSize(image_size); } bool ossimPointCloudImageHandler::saveState(ossimKeywordlist& kwl, const char* prefix) const { static const char MODULE[] = "ossimPointCloudImageHandler::saveState()"; ossimImageHandler::saveState(kwl, prefix); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR detected in keyword list! State not saved." << std::endl; return false; } kwl.add(prefix, ossimKeywordNames::ENTRY_KW, (int) m_activeComponent, true); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_KW, m_gsd.x, true); return true; } bool ossimPointCloudImageHandler::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimPointCloudImageHandler::loadState()"; theDecimationFactors.clear(); if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<< MODULE << " DEBUG: entered ..."<< std::endl; ossimImageHandler::loadState(kwl, prefix); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR) { ossimNotify(ossimNotifyLevel_WARN)<< MODULE << "WARNING: error detected in keyword list! State not load." << std::endl; return false; } m_activeComponent = INTENSITY; ossimString value = kwl.find(prefix, ossimKeywordNames::ENTRY_KW); if (!value.empty()) { ossim_uint32 i = value.toUInt32(); if (i < NUM_COMPONENTS) m_activeComponent = (Components) i; } value = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_KW); if (!value.empty()) setGSD(value.toDouble()); // The rest of the state is established by opening the file: bool good_open = open(); return good_open; } void ossimPointCloudImageHandler::getValidImageVertices(std::vector& validVertices, ossimVertexOrdering ordering, ossim_uint32 resLevel) const { validVertices.clear(); if (!m_pch.valid()) return; int divisor = 1; if (resLevel) divisor = resLevel<<1; // Transform the world coords for the four vertices into image vertices: ossimDpt r0Pt; ossimGrect bounds; m_pch->getBounds(bounds); theGeometry->worldToLocal(bounds.ul(), r0Pt); validVertices.emplace_back(r0Pt); theGeometry->worldToLocal(bounds.ur(), r0Pt); validVertices.emplace_back(r0Pt); theGeometry->worldToLocal(bounds.lr(), r0Pt); validVertices.emplace_back(r0Pt); theGeometry->worldToLocal(bounds.ll(), r0Pt); validVertices.emplace_back(r0Pt); if (ordering == OSSIM_COUNTERCLOCKWISE_ORDER) { for (int i=3; i>=0; i--) validVertices.emplace_back(validVertices[i]/divisor); validVertices.erase(validVertices.begin(), validVertices.begin()+4); } } void ossimPointCloudImageHandler::setProperty(ossimRefPtr property) { if (!property.valid()) return; ossimString s; property->valueToString(s); if (s.empty()) return; // The user should select either explicit GSD or relative GSD factor, never both: if ( property->getName() == ossimKeywordNames::METERS_PER_PIXEL_KW ) { ossim_float64 gsd = s.toFloat64(); if (!ossim::isnan(gsd)) setGSD(gsd); } else if ( property->getName() == GSD_FACTOR_KW ) { m_gsdFactor = s.toDouble(); if (!ossim::isnan(m_gsdFactor)) { if (!m_gsd.hasNans()) setGSD(m_gsd.x * m_gsdFactor); } else m_gsdFactor = 1.0; } else if ( property->getName() == ossimKeywordNames::ENTRY_KW ) { m_activeComponent = (Components) s.toUInt32(); } else if ( property->getName() == COMPONENT_KW ) { for (int i=0; i ossimPointCloudImageHandler::getProperty(const ossimString& name)const { ossimRefPtr prop = 0; if ( name == ossimKeywordNames::METERS_PER_PIXEL_KW ) { ossimString value = ossimString::toString(m_gsd.x); prop = new ossimStringProperty(name, value); } else if ( name == GSD_FACTOR_KW ) { prop = new ossimNumericProperty(name, ossimString::toString(m_gsdFactor)); } else if ( name == ossimKeywordNames::ENTRY_KW ) { prop = new ossimNumericProperty(name, ossimString::toString((ossim_uint32) m_activeComponent)); } else if ( name == COMPONENT_KW ) { prop = new ossimStringProperty(name, m_componentNames[m_activeComponent]); } else { prop = ossimImageHandler::getProperty(name); } return prop; } ossim_uint32 ossimPointCloudImageHandler::componentToFieldCode() const { ossim_uint32 field_code = 0; switch (m_activeComponent) { case INTENSITY: field_code = ossimPointRecord::Intensity; break; case RETURNS: field_code = ossimPointRecord::NumberOfReturns; break; case RGB: field_code = ossimPointRecord::Red | ossimPointRecord::Green | ossimPointRecord::Blue; break; default: break; } return field_code; } ossim-Miami-2.9.1/src/point_cloud/ossimPointCloudImageHandlerFactory.cpp000066400000000000000000000116341352751253100264560ustar00rootroot00000000000000/* * ossimPointCloudImageHandlerFactory.cpp * * Created on: Dec 8, 2014 * Author: okramer */ #include #include #include #include static const ossimTrace traceDebug("ossimPointCloudImageHandlerFactory:debug"); RTTI_DEF1(ossimPointCloudImageHandlerFactory, "ossimPointCloudImageHandlerFactory", ossimImageHandlerFactoryBase); ossimPointCloudImageHandlerFactory* ossimPointCloudImageHandlerFactory::m_instance = 0; ossimPointCloudImageHandlerFactory::~ossimPointCloudImageHandlerFactory() { m_instance = (ossimPointCloudImageHandlerFactory*)0; } ossimPointCloudImageHandlerFactory* ossimPointCloudImageHandlerFactory::instance() { if(!m_instance) { m_instance = new ossimPointCloudImageHandlerFactory; } return m_instance; } ossimImageHandler* ossimPointCloudImageHandlerFactory::open(const ossimFilename& fileName, bool openOverview) const { static const char* M = "ossimPointCloudImageHandlerFactory::open(filename) -- "; ossimFilename copyFilename = fileName; ossimRefPtr result = 0; // Check for empty file. copyFilename.trim(); if (copyFilename.empty() || !copyFilename.exists()) return 0; ossimString ext = copyFilename.ext().downcase(); if(ext == "gz") copyFilename = copyFilename.setExtension(""); if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<setFilename(copyFilename); if (!result->open()) result = 0; result->setOpenOverviewFlag(openOverview); return result.release(); } ossimImageHandler* ossimPointCloudImageHandlerFactory::open(const ossimKeywordlist& kwl, const char* prefix)const { static const char* M = "ossimPointCloudImageHandlerFactory::open(kwl,prefix) -- "; if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << M <<" entered..." << std::endl; ossimRefPtr result = 0; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<loadState(kwl, prefix)) result = 0; return result.get(); } ossimRefPtr ossimPointCloudImageHandlerFactory::openOverview( const ossimFilename& /* file */ ) const { ossimRefPtr result = 0; return result; } ossimObject* ossimPointCloudImageHandlerFactory::createObject(const ossimString& typeName)const { if(STATIC_TYPE_NAME(ossimPointCloudImageHandler) == typeName) { return new ossimPointCloudImageHandler(); } return (ossimObject*)0; } void ossimPointCloudImageHandlerFactory::getSupportedExtensions(ossimImageHandlerFactoryBase::UniqueStringList& extensionList)const { extensionList.push_back("las"); extensionList.push_back("gpkg"); } void ossimPointCloudImageHandlerFactory::getImageHandlersBySuffix(ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& ext)const { if ((ext == "las") || (ext == "gpkg")) { result.push_back(new ossimPointCloudImageHandler); return; } } void ossimPointCloudImageHandlerFactory::getImageHandlersByMimeType(ossimImageHandlerFactoryBase::ImageHandlerList& result, const ossimString& mimeType)const { ossimString test(mimeType.begin(), mimeType.begin()+6); if(test == "image/") { ossimString mimeTypeTest(mimeType.begin() + 6, mimeType.end()); getImageHandlersBySuffix(result, mimeTypeTest); if(mimeTypeTest == "las") { result.push_back(new ossimPointCloudImageHandler); } } } ossimObject* ossimPointCloudImageHandlerFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { ossimObject* result = (ossimObject*)0; const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if(type) { if (ossimString(type).trim() == STATIC_TYPE_NAME(ossimImageHandler)) { const char* lookup = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if (lookup) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "BEBUG: filename " << lookup << std::endl; } // Call the open that takes a filename... result = this->open(kwl, prefix);//ossimFilename(lookup)); } } else { result = createObject(ossimString(type)); if(result) { result->loadState(kwl, prefix); } } } return result; } void ossimPointCloudImageHandlerFactory::getTypeNameList(std::vector& typeList)const { typeList.push_back(STATIC_TYPE_NAME(ossimPointCloudImageHandler)); } ossim-Miami-2.9.1/src/point_cloud/ossimPointCloudSource.cpp000066400000000000000000000033031352751253100240400ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: LGPL -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** #include #include #include RTTI_DEF1(ossimPointCloudSource, "ossimPointCloudSource" , ossimSource); ossimPointCloudSource::ossimPointCloudSource(ossimObject* owner) : ossimSource(owner) { } ossimPointCloudSource::ossimPointCloudSource(const ossimPointCloudSource& rhs) : ossimSource(rhs) { } ossimPointCloudSource::~ossimPointCloudSource() { } const ossimPointRecord* ossimPointCloudSource::getMinPoint() const { if (getInput(0) == 0) return &m_nullPCR; return ((ossimPointCloudSource*)getInput(0))->getMinPoint(); } const ossimPointRecord* ossimPointCloudSource::getMaxPoint() const { if (getInput(0) == 0) return &m_nullPCR; return ((ossimPointCloudSource*)getInput(0))->getMaxPoint(); } ossim_uint32 ossimPointCloudSource::getFieldCode() const { if (getInput(0) == 0) return 0; return ((ossimPointCloudSource*)getInput(0))->getFieldCode(); } void ossimPointCloudSource::setFieldCode(ossim_uint32 fc) { if (getInput(0) != 0) ((ossimPointCloudSource*) getInput(0))->setFieldCode(fc); } bool ossimPointCloudSource::canConnectMyInputTo(ossim_int32 i,const ossimConnectableObject* p) const { if ( (i>0) || (p==0) ) return false; return (p->canCastTo("ossimPointCloudSource")); } ossim-Miami-2.9.1/src/point_cloud/ossimPointCloudUtilityFilter.cpp000066400000000000000000000055661352751253100254260ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //******************************************************************* // $Id$ #include #include #include #include #include RTTI_DEF1(ossimPointCloudUtilityFilter, "ossimPointCloudUtilityFilter", ossimImageSourceFilter); // NOLINT ossimPointCloudUtilityFilter::ossimPointCloudUtilityFilter( ossimPointCloudTool* pc_util) : m_util (pc_util) { } bool ossimPointCloudUtilityFilter::getTile(ossimImageData* result, ossim_uint32 resLevel) { if (!result) return false; ossimIrect irect (result->getImageRectangle()); ossimIpt ipt; ossimGpt gpt; double h, dh; ossimElevManager* elevation = ossimElevManager::instance(); ossimRefPtr highest = 0; ossimRefPtr lowest = 0; // Fetch tile from inputs as needed: if ((m_util->m_operation == ossimPointCloudTool::HIGHEST_DEM) || (m_util->m_operation == ossimPointCloudTool::HIGHEST_LOWEST)) { m_util->m_pciHandler->setCurrentEntry(ossimPointCloudImageHandler::HIGHEST); highest = m_util->m_pciHandler->getTile(irect, resLevel); } if ((m_util->m_operation == ossimPointCloudTool::LOWEST_DEM) || (m_util->m_operation == ossimPointCloudTool::HIGHEST_LOWEST)) { m_util->m_pciHandler->setCurrentEntry(ossimPointCloudImageHandler::LOWEST); lowest = m_util->m_pciHandler->getTile(irect, resLevel); } // Now loop over all pixels in tile and perform operations as needed: ossimIpt pt_l0; for (ipt.y=irect.ul().y; ipt.y<=irect.lr().y; ++ipt.y) { for (ipt.x=irect.ul().x; ipt.x<=irect.lr().x; ++ipt.x) { pt_l0 = ipt * (resLevel + 1); switch (m_util->m_operation) { case ossimPointCloudTool::HIGHEST_DEM: m_util->m_prodGeom->localToWorld(pt_l0, gpt); h = elevation->getHeightAboveEllipsoid(gpt); dh = highest->getPix(ipt) - h; break; case ossimPointCloudTool::HIGHEST_LOWEST: dh = highest->getPix(ipt) - lowest->getPix(ipt); break; default: // LOWEST_DEM m_util->m_prodGeom->localToWorld(pt_l0, gpt); h = elevation->getHeightAboveEllipsoid(gpt); dh = lowest->getPix(ipt) - h; break; } result->setValue(ipt.x, ipt.y, dh); } } result->validate(); return true; } ossimRefPtr ossimPointCloudUtilityFilter::getImageGeometry() { if (!m_util.valid()) return 0; return m_util->m_prodGeom; } ossim-Miami-2.9.1/src/point_cloud/ossimPointRecord.cpp000066400000000000000000000121101352751253100230230ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM (http://trac.osgeo.org/ossim/) // // License: LGPL -- See LICENSE.txt file in the top level directory for more details. // //************************************************************************************************** // $Id: ossimPointRecord.cpp 23352 2015-05-29 17:38:12Z okramer $ #include using namespace std; ossimPointRecord::ossimPointRecord(ossim_uint32 field_code) : m_pointId(0) { if (field_code & Intensity) m_fieldMap[Intensity] = ossim::nan(); if (field_code & ReturnNumber) m_fieldMap[ReturnNumber] = ossim::nan(); if (field_code & NumberOfReturns) m_fieldMap[NumberOfReturns] = ossim::nan(); if (field_code & Red) m_fieldMap[Red] = ossim::nan(); if (field_code & Green) m_fieldMap[Green] = ossim::nan(); if (field_code & Blue) m_fieldMap[Blue] = ossim::nan(); if (field_code & GpsTime) m_fieldMap[GpsTime] = ossim::nan(); if (field_code & Infrared) m_fieldMap[Infrared] = ossim::nan(); } ossimPointRecord::ossimPointRecord(const ossimPointRecord& pcr) : m_pointId(pcr.m_pointId), m_position(pcr.m_position), m_fieldMap (pcr.m_fieldMap) { } ossimPointRecord::ossimPointRecord(const ossimGpt& pos) : m_pointId(0), m_position(pos) { } ossimPointRecord::~ossimPointRecord() { } inline bool ossimPointRecord::hasFields(ossim_uint32 field_code) const { bool found = true; if (field_code & Intensity) found &= m_fieldMap.find(Intensity) != m_fieldMap.end(); if (found && (field_code & ReturnNumber)) found = m_fieldMap.find(ReturnNumber) != m_fieldMap.end(); if (found && (field_code & NumberOfReturns)) found = m_fieldMap.find(NumberOfReturns) != m_fieldMap.end(); if (found && (field_code & Red)) found = m_fieldMap.find(Red) != m_fieldMap.end(); if (found && (field_code & Green)) found = m_fieldMap.find(Green) != m_fieldMap.end(); if (found && (field_code & Blue)) found = m_fieldMap.find(Blue) != m_fieldMap.end(); if (found && (field_code & GpsTime)) found = m_fieldMap.find(GpsTime) != m_fieldMap.end(); if (found && (field_code & Infrared)) found = m_fieldMap.find(Infrared) != m_fieldMap.end(); return found; } inline ossim_uint32 ossimPointRecord::getFieldCode() const { ossim_uint32 field_code = 0; if (m_fieldMap.find(Intensity) != m_fieldMap.end()) field_code |= Intensity; if (m_fieldMap.find(ReturnNumber) != m_fieldMap.end()) field_code |= ReturnNumber; if (m_fieldMap.find(NumberOfReturns) != m_fieldMap.end()) field_code |= NumberOfReturns; if (m_fieldMap.find(Red) != m_fieldMap.end()) field_code |= Red; if (m_fieldMap.find(Green) != m_fieldMap.end()) field_code |= Green; if (m_fieldMap.find(Blue) != m_fieldMap.end()) field_code |= Blue; if (m_fieldMap.find(GpsTime) != m_fieldMap.end()) field_code |= GpsTime; if (m_fieldMap.find(Infrared) != m_fieldMap.end()) field_code |= Infrared; return field_code; } ossim_float32 ossimPointRecord::getField(FIELD_CODES fc) const { std::map::const_iterator v = m_fieldMap.find(fc); if (v == m_fieldMap.end()) return ossim::nan(); return v->second; } void ossimPointRecord::setField(FIELD_CODES fc, ossim_float32 value) { m_fieldMap[fc] = value; } ossimPointRecord& ossimPointRecord::operator=(const ossimPointRecord& pcr) { if (this == &pcr) return *this; m_pointId = pcr.m_pointId; m_position = pcr.m_position; m_fieldMap = pcr.m_fieldMap; return *this; } std::ostream& operator << (std::ostream& out, const ossimPointRecord& p) { out << "ossimPointCloudRecord for pointId: " << p.m_pointId << "\n Position: " << p.m_position << ends; std::map::const_iterator iter = p.m_fieldMap.begin(); while (iter != p.m_fieldMap.end()) { switch (iter->first) { case ossimPointRecord::Intensity: out << "\n Intensity: "; break; case ossimPointRecord::ReturnNumber: out << "\n ReturnNumber: "; break; case ossimPointRecord::NumberOfReturns: out << "\n NumberOfReturns: "; break; case ossimPointRecord::Red: out << "\n Red: "; break; case ossimPointRecord::Green: out << "\n Green: "; break; case ossimPointRecord::Blue: out << "\n Blue: "; break; case ossimPointRecord::GpsTime: out << "\n GpsTime: "; break; case ossimPointRecord::Infrared: out << "\n Infrared: "; break; default: out << "\n Unidentified: "; } out << iter->second; ++iter; } return out; } void ossimPointRecord::clear() { m_pointId = 0; } bool ossimPointRecord::isValid() const { if ((m_pointId == 0) || m_fieldMap.empty() || m_position.hasNans()) return false; return true; } ossim-Miami-2.9.1/src/projection/000077500000000000000000000000001352751253100166565ustar00rootroot00000000000000ossim-Miami-2.9.1/src/projection/ossimAdjMapModel.cpp000066400000000000000000000354551352751253100225660ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (c) 2005, Oscar Kramer, all rights reserved. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: // // Special "sensor model" that provides a conventional map projection but // with additional capability for adjusting the map x,y coordinates with // offset, scale, and rotation transform. Funtions to control notifications, // information and error output. // //---------------------------------------------------------------------------- // $Id: ossimAdjMapModel.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include /* for atof */ #include #include #include #include #include using namespace std; // Geometry File Keywords: static const char* PARAMETER_KEYWORDS[] = {"map_offset_x", "map_offset_y", "map_rotation", "map_scale_x", "map_scale_y"}; static const char* MAP_PROJ_FILE_KW = "map_proj_filename"; RTTI_DEF1(ossimAdjMapModel, "ossimAdjMapModel", ossimSensorModel); //---------------------------------------------------------------------------- //! Constructs to uninitialized state (needed by factory). //---------------------------------------------------------------------------- ossimAdjMapModel::ossimAdjMapModel() : ossimSensorModel(), theAdjParams(NUM_ADJ_PARAMS), theMapProjection(), theCosTheta(0.0), theSinTheta(0.0) { theImageSize = ossimIpt(0,0); initAdjustableParameters(); theErrorStatus++; } //---------------------------------------------------------------------------- //! Constructs with map projection and image rectangle size. //---------------------------------------------------------------------------- ossimAdjMapModel::ossimAdjMapModel(ossimMapProjection* map_proj, const ossimIpt& image_size) : ossimSensorModel(), theAdjParams(NUM_ADJ_PARAMS), theMapProjection(map_proj), theCosTheta(0.0), theSinTheta(0.0) { initializeFromMap(); theImageSize = image_size; initAdjustableParameters(); } //---------------------------------------------------------------------------- //! Copy constructor //---------------------------------------------------------------------------- ossimAdjMapModel::ossimAdjMapModel(const ossimAdjMapModel& copy_this) : ossimSensorModel(copy_this), theAdjParams(NUM_ADJ_PARAMS), theMapProjection(copy_this.theMapProjection), theCosTheta(0.0), theSinTheta(0.0) { theAdjParams = copy_this.theAdjParams; } //---------------------------------------------------------------------------- //! Constructs from Geom KWL //---------------------------------------------------------------------------- ossimAdjMapModel::ossimAdjMapModel(const ossimKeywordlist& kwl, const char* prefix) : ossimSensorModel(kwl), theAdjParams(NUM_ADJ_PARAMS), theMapProjection(), theCosTheta(0.0), theSinTheta(0.0) { initAdjustableParameters(); loadState(kwl, prefix); } //---------------------------------------------------------------------------- //! Constructs from Geom KWL //---------------------------------------------------------------------------- ossimAdjMapModel::ossimAdjMapModel(const ossimFilename& kwl_filename) : ossimSensorModel(), theAdjParams(NUM_ADJ_PARAMS), theMapProjection(), theCosTheta(0.0), theSinTheta(0.0) { initAdjustableParameters(); ossimKeywordlist kwl (kwl_filename); loadState(kwl); } //---------------------------------------------------------------------------- //! Initializes base class data members after map model established. Returns TRUE if all's well. //---------------------------------------------------------------------------- bool ossimAdjMapModel::initializeFromMap() { if (!theMapProjection) { theErrorStatus++; return false; } theSensorID = "AdjMapModel"; theGSD = theMapProjection->getMetersPerPixel(); theMeanGSD = 0.5*(theGSD.x + theGSD.y); theRefGndPt = theMapProjection->origin(); return true; } //---------------------------------------------------------------------------- //! Destructor //---------------------------------------------------------------------------- ossimAdjMapModel::~ossimAdjMapModel() { theAdjParams.CleanUp(); } //---------------------------------------------------------------------------- //! Initializes adjustable parameters to their default values. //! Overrides ossimAdjustableParameterInterface virtual method. //---------------------------------------------------------------------------- void ossimAdjMapModel::initAdjustableParameters() { // Initialize this adjustment as the initial geometry "adjustment": removeAllAdjustments(); newAdjustment(NUM_ADJ_PARAMS); setAdjustmentDescription("Initial Geometry"); // Initialize each adjustable parameter for this initial: setAdjustableParameter (OFFSET_X, 0.0, 1.0); setParameterDescription(OFFSET_X, "map_offset_x"); setParameterCenter (OFFSET_X, 0.0); setAdjustableParameter (OFFSET_Y, 0.0, 1.0); setParameterDescription(OFFSET_Y, "map_offset_y"); setParameterCenter (OFFSET_Y, 0.0); setAdjustableParameter (ROTATION, 0.0, 1.0); setParameterDescription(ROTATION, "map_rotation"); setParameterCenter (ROTATION, 0.0); setAdjustableParameter (SCALE_X, 0.0, 1.0); setParameterDescription(SCALE_X, "map_scale_x"); setParameterCenter (SCALE_X, 1.0); setAdjustableParameter (SCALE_Y, 0.0, 1.0); setParameterDescription(SCALE_Y, "map_scale_y"); setParameterCenter (SCALE_Y, 1.0); updateModel(); } //---------------------------------------------------------------------------- //! Following a change to the adjustable parameter set, this virtual is called //! to permit instances to compute derived quantities after parameter change. //---------------------------------------------------------------------------- void ossimAdjMapModel::updateModel() { for (int i=0; ilineSampleHeightToWorld(adjusted_point, heightEllipsoid, worldPoint); worldPoint.height(heightEllipsoid); } //---------------------------------------------------------------------------- //! Overrides base class virtual. //---------------------------------------------------------------------------- void ossimAdjMapModel::lineSampleToWorld(const ossimDpt& image_point, ossimGpt& worldPoint) const { lineSampleHeightToWorld(image_point, 0.0, worldPoint); if (!worldPoint.hasNans()) { // worldPoint.height(theElevation->getHeightAboveEllipsoid(worldPoint)); } } //---------------------------------------------------------------------------- //! Rigorous inverse transform implented, overrides base-class' iterative //! solution. //---------------------------------------------------------------------------- void ossimAdjMapModel::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { // Check for bad map projection pointer: if (!theMapProjection) { image_point = ossimDpt(ossim::nan(), ossim::nan()); return; } // Obtain non-adjusted image point given ground point: ossimDpt p1; theMapProjection->worldToLineSample(world_point, p1); // Adjust image point by transform: ossimDpt p2 (p1.x*theCosTheta - p1.y*theSinTheta, p1.y*theCosTheta + p1.x*theSinTheta); image_point.x = p2.x/theAdjParams[SCALE_X] + theAdjParams[OFFSET_X]; image_point.y = p2.y/theAdjParams[SCALE_Y] + theAdjParams[OFFSET_Y]; } //---------------------------------------------------------------------------- //! Fulfills ossimObject base-class pure virtuals. Saves geometry //! KWL files. Returns true if successful. //---------------------------------------------------------------------------- bool ossimAdjMapModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Save off map projection info: if (theMapProjection.valid()) { ossimString map_prefix(prefix); if (map_prefix.size() && (map_prefix[map_prefix.size()-1] != '.')) map_prefix += "."; map_prefix += "map_proj."; theMapProjection->saveState(kwl, map_prefix.chars()); } // Hand off to base class for common stuff: ossimSensorModel::saveState(kwl, prefix); // Save off data members: kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimAdjMapModel"); for (int i=0; i( ossimMapProjectionFactory::instance()->createProjection(kwl, map_prefix.chars())); //--- // Instantiate the map projection via the factory if one has not been // initialized yet: //--- if (!theMapProjection) { // should find the map projection filename in the KWL: value_str = kwl.find(prefix, MAP_PROJ_FILE_KW); if (!value_str) { throw (error_msg + MAP_PROJ_FILE_KW); } theMapProjection = PTR_CAST(ossimMapProjection, ossimMapProjectionFactory::instance()->createProjection(ossimKeywordlist(value_str))); if (!theMapProjection) { throw "Error encountered instantiating map "; } } // Hand off to base class for common stuff: ossimSensorModel::loadState(kwl, prefix); // Everything OK so far, just load in the adjustable parameters. This involves modifying the // center value of the bsae class adjustable parameter: for (int i=0; i\n" << PARAMETER_KEYWORDS[OFFSET_Y] << ": \n" << PARAMETER_KEYWORDS[ROTATION] << ": \n" << PARAMETER_KEYWORDS[SCALE_X] << ": \n" << PARAMETER_KEYWORDS[SCALE_Y] << ": \n" << endl; return; } //---------------------------------------------------------------------------- //! Extends base-class implementation. Dumps contents of object to ostream. //---------------------------------------------------------------------------- std::ostream& ossimAdjMapModel::print(std::ostream& out) const { ossimSensorModel::print(out); for (int i=0; igetMetersPerPixel(); } return ossimDpt(0,0); } ossimObject* ossimAdjMapModel::dup() const { return new ossimAdjMapModel(*this); } ossim-Miami-2.9.1/src/projection/ossimAffineProjection.cpp000066400000000000000000000226011352751253100236630ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: // Contains implementation of class ossimAffineModel. This is an // implementation of a warping interpolation model. // //***************************************************************************** // $Id: ossimAffineProjection.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include RTTI_DEF1(ossimAffineProjection, "ossimAffineProjection", ossimProjection); #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimAffineProjection:exec"); static ossimTrace traceDebug ("ossimAffineProjection:debug"); //***************************************************************************** // CONSTRUCTOR: Default // //***************************************************************************** ossimAffineProjection::ossimAffineProjection() : ossimProjection(), theClientProjection (NULL), theAffineTransform (NULL) { } //***************************************************************************** // CONSTRUCTOR: Primary constructor accepting pointer to the underlying // client projection // //***************************************************************************** ossimAffineProjection::ossimAffineProjection(ossimProjection* client) : ossimProjection(), theClientProjection (client), theAffineTransform (NULL) { } //***************************************************************************** // CONSTRUCTOR: Accepts geom keywordlist //***************************************************************************** ossimAffineProjection::ossimAffineProjection(const ossimKeywordlist& geom_kwl, const char* prefix) : ossimProjection(), theClientProjection (NULL), theAffineTransform (NULL) { theClientProjection = ossimProjectionFactoryRegistry::instance()-> createProjection(geom_kwl, prefix); theAffineTransform = new ossimAffineTransform(); bool rtn_stat = theAffineTransform->loadState(geom_kwl, prefix); if (!theClientProjection || theClientProjection->getErrorStatus() || !rtn_stat) setErrorStatus(ossimErrorCodes::OSSIM_ERROR); } //***************************************************************************** // DESTRUCTOR //***************************************************************************** ossimAffineProjection::~ossimAffineProjection() { } //***************************************************************************** // METHOD: ossimAffineProjection::worldToLineSample() //***************************************************************************** void ossimAffineProjection::worldToLineSample (const ossimGpt& worldPoint, ossimDpt& lineSampPt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAffineProjection::worldToLineSample: Entering..." << std::endl; if (theClientProjection.valid() && theAffineTransform.valid()) { theClientProjection->worldToLineSample(worldPoint, lineSampPt); theAffineTransform->inverse(lineSampPt); } else lineSampPt.makeNan(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAffineProjection::worldToLineSample: Returning..." << std::endl; } //***************************************************************************** // METHOD: ossimAffineProjection::lineSampleToWorld() //***************************************************************************** void ossimAffineProjection::lineSampleToWorld(const ossimDpt& lineSampPt, ossimGpt& worldPt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAffineProjection::lineSampleToWorld: Entering..." << std::endl; if (theClientProjection.valid() && theAffineTransform.valid()) { ossimDpt adjustedPt; theAffineTransform->forward(lineSampPt, adjustedPt); theClientProjection->lineSampleToWorld(adjustedPt, worldPt); } else { worldPt.makeNan(); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAffineProjection::lineSampleToWorld: Returning..." << std::endl; } //***************************************************************************** // METHOD: ossimAffineProjection::lineSampleToWorld() //***************************************************************************** void ossimAffineProjection::lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& hgt, ossimGpt& worldPt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAffineProjection::lineSampleHeightToWorld: Entering..." << std::endl; if (theClientProjection.valid() && theAffineTransform.valid()) { ossimDpt adjustedPt; theAffineTransform->forward(lineSampPt, adjustedPt); theClientProjection->lineSampleHeightToWorld(adjustedPt, hgt, worldPt); } else { worldPt.makeNan(); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "dEBUG ossimAffineProjection::lineSampleHeightToWorld: Returning..." << std::endl; } //***************************************************************************** // METHOD: ossimAffineProjection::print() //***************************************************************************** std::ostream& ossimAffineProjection::print(std::ostream& out) const { if (theClientProjection.valid() && theAffineTransform.valid()) { out << "ossimAffineProjection:\n" " Member theClientProjection: "; theClientProjection->print(out); out << "\n Member theAffineTransform: " << *theAffineTransform << std::endl; } else { out << "ossimAffineProjection -- Not initialized." << std::endl; } return out; } std::ostream& operator<<(std::ostream& os, const ossimAffineProjection& m) { return m.print(os); } //***************************************************************************** // METHOD: ossimAffineProjection::() //***************************************************************************** bool ossimAffineProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAffineProjection::saveState: entering..." << std::endl; if (theClientProjection.valid() && theAffineTransform.valid()) { theClientProjection->saveState(kwl, prefix); theAffineTransform->saveState(kwl, prefix); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAffineProjection::saveState: returning..." << std::endl; return true; } //***************************************************************************** // METHOD: ossimAffineProjection::() //***************************************************************************** bool ossimAffineProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAffineProjection::loadState: entering..." << std::endl; bool good_load; int err_stat; if (!theClientProjection) { theClientProjection = ossimProjectionFactoryRegistry::instance()-> createProjection(kwl, prefix); err_stat = theClientProjection->getErrorStatus(); if (err_stat != ossimErrorCodes::OSSIM_OK) { return false; } } else { good_load = theClientProjection->loadState(kwl, prefix); if (!good_load) { return false; } } if (!theAffineTransform) { theAffineTransform = new ossimAffineTransform(); } good_load = theAffineTransform->loadState(kwl, prefix); if (!good_load) { return false; } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAffineProjection::loadState: returning..." << std::endl; return true; } //***************************************************************************** // METHOD: ossimAffineProjection::() //***************************************************************************** ossimObject* ossimAffineProjection::dup() const { ossimKeywordlist kwl; saveState(kwl); ossimProjection* duped = new ossimAffineProjection(kwl); return duped; } //***************************************************************************** // METHOD: //***************************************************************************** ossimGpt ossimAffineProjection::origin() const { if (theClientProjection.valid()) return theClientProjection->origin(); return ossimGpt(0.0, 0.0, 0.0); } //***************************************************************************** // METHOD: //***************************************************************************** ossimDpt ossimAffineProjection::getMetersPerPixel() const { if (theClientProjection.valid()) return theClientProjection->getMetersPerPixel(); return ossimDpt(ossim::nan(), ossim::nan()); } ossim-Miami-2.9.1/src/projection/ossimAlbersProjection.cpp000066400000000000000000000515141352751253100237100ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Albers projection code. //******************************************************************* // $Id: ossimAlbersProjection.cpp 23002 2014-11-24 17:11:17Z dburken $ #include #include RTTI_DEF1(ossimAlbersProjection, "ossimAlbersProjection", ossimMapProjection) #ifdef PI_OVER_2 # undef PI_OVER_2 #endif #define ALBERS_NO_ERROR 0x0000 #define ALBERS_LAT_ERROR 0x0001 #define ALBERS_LON_ERROR 0x0002 #define ALBERS_EASTING_ERROR 0x0004 #define ALBERS_NORTHING_ERROR 0x0008 #define ALBERS_ORIGIN_LAT_ERROR 0x0010 #define ALBERS_CENT_MER_ERROR 0x0020 #define ALBERS_A_ERROR 0x0040 #define ALBERS_INV_F_ERROR 0x0080 #define ALBERS_FIRST_STDP_ERROR 0x0100 #define ALBERS_SECOND_STDP_ERROR 0x0200 #define ALBERS_FIRST_SECOND_ERROR 0x0400 #define ALBERS_HEMISPHERE_ERROR 0x0800 #define PI_OVER_2 ( M_PI / 2.0) #define ES_SIN(sinlat) (es * sinlat) #define ONE_MINUS_SQR(x) (1.0 - x * x) #define ALBERS_M(clat,oneminussqressin) (clat / sqrt(oneminussqressin)) #define ALBERS_Q(slat,oneminussqressin,essin) (one_MINUS_es2)*(slat / (oneminussqressin)- \ (1 / (two_es)) *log((1 - essin) / (1 + essin))) ossimAlbersProjection::ossimAlbersProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { Albers_Delta_Northing = 40000000.0; Albers_Delta_Easting = 40000000.0; setDefaults(); update(); } ossimAlbersProjection::ossimAlbersProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double stdParallel1, double stdParallel2, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Albers_Std_Parallel_1 = stdParallel1*RAD_PER_DEG; Albers_Std_Parallel_2 = stdParallel2*RAD_PER_DEG; Albers_Delta_Northing = 40000000.0; Albers_Delta_Easting = 40000000.0; Albers_False_Easting = falseEasting; Albers_False_Northing = falseNorthing; update(); } ossimObject* ossimAlbersProjection::dup() const { return new ossimAlbersProjection(*this); } ossimAlbersProjection::~ossimAlbersProjection() { } void ossimAlbersProjection::update() { Set_Albers_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Albers_Std_Parallel_1, Albers_Std_Parallel_2, Albers_False_Easting, Albers_False_Northing); theFalseEastingNorthing.x = Albers_False_Easting; theFalseEastingNorthing.y = Albers_False_Northing; ossimMapProjection::update(); } ossimGpt ossimAlbersProjection::inverse(const ossimDpt &eastingNorthing)const { double lat, lon; Convert_Albers_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0, theDatum); } ossimDpt ossimAlbersProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Albers(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } void ossimAlbersProjection::setStandardParallel1(double degree) { Albers_Std_Parallel_1 = degree*RAD_PER_DEG; update(); } void ossimAlbersProjection::setStandardParallel2(double degree) { Albers_Std_Parallel_2 = degree*RAD_PER_DEG; update(); } void ossimAlbersProjection::setStandardParallels(double parallel1Degree, double parallel2Degree) { Albers_Std_Parallel_1 = parallel1Degree*RAD_PER_DEG; Albers_Std_Parallel_2 = parallel2Degree*RAD_PER_DEG; update(); } void ossimAlbersProjection::setFalseEasting(double falseEasting) { Albers_False_Easting = falseEasting; update(); } void ossimAlbersProjection::setFalseNorthing(double falseNorthing) { Albers_False_Northing = falseNorthing; update(); } void ossimAlbersProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Albers_False_Easting = falseEasting; Albers_False_Northing = falseNorthing; update(); } void ossimAlbersProjection::setParameters(double parallel1, double parallel2, double falseEasting, double falseNorthing) { Albers_False_Easting = falseEasting; Albers_False_Northing = falseNorthing; Albers_Std_Parallel_1 = parallel1*RAD_PER_DEG; Albers_Std_Parallel_2 = parallel2*RAD_PER_DEG; update(); } double ossimAlbersProjection::getStandardParallel1()const { return Albers_Std_Parallel_1/RAD_PER_DEG; } double ossimAlbersProjection::getStandardParallel2()const { return Albers_Std_Parallel_2/RAD_PER_DEG; } void ossimAlbersProjection::setDefaults() { // initialize to some default Albers_Std_Parallel_1 = 29.5*RAD_PER_DEG; Albers_Std_Parallel_2 = 45.5*RAD_PER_DEG; Albers_False_Easting = 0.0; Albers_False_Northing = 0.0; } bool ossimAlbersProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, ossimKeywordNames::STD_PARALLEL_1_KW, Albers_Std_Parallel_1*DEG_PER_RAD, true); kwl.add(prefix, ossimKeywordNames::STD_PARALLEL_2_KW, Albers_Std_Parallel_2*DEG_PER_RAD, true); return ossimMapProjection::saveState(kwl, prefix); } bool ossimAlbersProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Must do this first... bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); const char* stdParallel1 = kwl.find(prefix, ossimKeywordNames::STD_PARALLEL_1_KW); const char* stdParallel2 = kwl.find(prefix, ossimKeywordNames::STD_PARALLEL_2_KW); if(ossimString(type) == STATIC_TYPE_NAME(ossimAlbersProjection)) { Albers_False_Easting = theFalseEastingNorthing.x; Albers_False_Northing = theFalseEastingNorthing.y; if(stdParallel1) { Albers_Std_Parallel_1 = ossimString(stdParallel1).toDouble()*RAD_PER_DEG; } else { Albers_Std_Parallel_1 = 29.5*RAD_PER_DEG; } if(stdParallel2) { Albers_Std_Parallel_2 = ossimString(stdParallel2).toDouble()*RAD_PER_DEG; } else { Albers_Std_Parallel_2 = 45.5*RAD_PER_DEG; } } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimAlbersProjection::Set_Albers_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double Std_Parallel_1, double Std_Parallel_2, double False_Easting, double False_Northing) { /* * The function Set_Albers_Parameters receives the ellipsoid parameters and * projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise ALBERS_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * Std_Parallel_1 : First standard parallel (input) * Std_Parallel_2 : Second standard parallel (input) * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double sin_lat, sin_lat_1, cos_lat; double m1, m2, SQRm1; double q0, q1, q2; double es_sin, one_MINUS_SQRes_sin; double nq0; double inv_f = 1 / f; long Error_Code = ALBERS_NO_ERROR; if (a <= 0.0) { /* Semi-major axis must be greater than zero */ Error_Code |= ALBERS_A_ERROR; } if ((inv_f < 250) || (inv_f > 350)) { /* Inverse flattening must be between 250 and 350 */ Error_Code |= ALBERS_INV_F_ERROR; } if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) { /* origin latitude out of range */ Error_Code |= ALBERS_ORIGIN_LAT_ERROR; } if ((Central_Meridian < -M_PI) || (Central_Meridian > TWO_PI)) { /* origin longitude out of range */ Error_Code |= ALBERS_CENT_MER_ERROR; } if ((Std_Parallel_1 < -PI_OVER_2) || (Std_Parallel_1 > PI_OVER_2)) { /* First Standard Parallel out of range */ Error_Code |= ALBERS_FIRST_STDP_ERROR; } if ((Std_Parallel_2 < -PI_OVER_2) || (Std_Parallel_2 > PI_OVER_2)) { /* Second Standard Parallel out of range */ Error_Code |= ALBERS_SECOND_STDP_ERROR; } if ((Std_Parallel_1 == 0.0) && (Std_Parallel_2 == 0.0)) { /* First & Second Standard Parallels equal 0 */ Error_Code |= ALBERS_FIRST_SECOND_ERROR; } if (Std_Parallel_1 == -Std_Parallel_2) { /* Parallels are opposite latitudes */ Error_Code |= ALBERS_HEMISPHERE_ERROR; } if (!Error_Code) { /* no errors */ Albers_a = a; Albers_f = f; Albers_Origin_Lat = Origin_Latitude; Albers_Std_Parallel_1 = Std_Parallel_1; Albers_Std_Parallel_2 = Std_Parallel_2; if (Central_Meridian > M_PI) Central_Meridian -= TWO_PI; Albers_Origin_Long = Central_Meridian; Albers_False_Easting = False_Easting; Albers_False_Northing = False_Northing; es2 = 2 * Albers_f - Albers_f * Albers_f; es = sqrt(es2); one_MINUS_es2 = 1 - es2; two_es = 2 * es; sin_lat = sin(Albers_Origin_Lat); es_sin = ES_SIN(sin_lat); one_MINUS_SQRes_sin = ONE_MINUS_SQR(es_sin); q0 = ALBERS_Q(sin_lat, one_MINUS_SQRes_sin, es_sin); sin_lat_1 = sin(Albers_Std_Parallel_1); cos_lat = cos(Albers_Std_Parallel_1); es_sin = ES_SIN(sin_lat_1); one_MINUS_SQRes_sin = ONE_MINUS_SQR(es_sin); m1 = ALBERS_M(cos_lat, one_MINUS_SQRes_sin); q1 = ALBERS_Q(sin_lat_1, one_MINUS_SQRes_sin, es_sin); SQRm1 = m1 * m1; if (fabs(Albers_Std_Parallel_1 - Albers_Std_Parallel_2) > 1.0e-10) { sin_lat = sin(Albers_Std_Parallel_2); cos_lat = cos(Albers_Std_Parallel_2); es_sin = ES_SIN(sin_lat); one_MINUS_SQRes_sin = ONE_MINUS_SQR(es_sin); m2 = ALBERS_M(cos_lat, one_MINUS_SQRes_sin); q2 = ALBERS_Q(sin_lat, one_MINUS_SQRes_sin, es_sin); n = (SQRm1 - m2 * m2) / (q2 - q1); } else n = sin_lat_1; C = SQRm1 + n * q1; Albers_a_OVER_n = Albers_a / n; nq0 = n * q0; if (C < nq0) rho0 = 0; else rho0 = Albers_a_OVER_n * sqrt(C - nq0); } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Set_Albers_Parameters */ void ossimAlbersProjection::Get_Albers_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *Std_Parallel_1, double *Std_Parallel_2, double *False_Easting, double *False_Northing)const { /* BEGIN Get_Albers_Parameters */ /* * The function Get_Albers_Parameters returns the current ellipsoid * parameters, and Albers projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Origin_Longitude : Longitude in radians at the center of (output) * the projection * Std_Parallel_1 : First standard parallel (output) * Std_Parallel_2 : Second standard parallel (output) * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Albers_a; *f = Albers_f; *Origin_Latitude = Albers_Origin_Lat; *Std_Parallel_1 = Albers_Std_Parallel_1; *Std_Parallel_2 = Albers_Std_Parallel_2; *Central_Meridian = Albers_Origin_Long; *False_Easting = Albers_False_Easting; *False_Northing = Albers_False_Northing; return; } /* END OF Get_Albers_Parameters */ long ossimAlbersProjection::Convert_Geodetic_To_Albers (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Albers */ /* * The function Convert_Geodetic_To_Albers converts geodetic (latitude and * longitude) coordinates to Albers projection (easting and northing) * coordinates, according to the current ellipsoid and Albers projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise ALBERS_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double dlam; /* Longitude - Central Meridan */ double sin_lat; // double cos_lat; double es_sin, one_MINUS_SQRes_sin; double q; double rho; double theta; double nq; long Error_Code = ALBERS_NO_ERROR; if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) { /* Latitude out of range */ Error_Code |= ALBERS_LAT_ERROR; } if ((Longitude < -M_PI) || (Longitude > TWO_PI)) { /* Longitude out of range */ Error_Code|= ALBERS_LON_ERROR; } if (!Error_Code) { /* no errors */ dlam = Longitude - Albers_Origin_Long; if (dlam > M_PI) { dlam -= TWO_PI; } if (dlam < -M_PI) { dlam += TWO_PI; } sin_lat = sin(Latitude); // cos_lat = cos(Latitude); es_sin = ES_SIN(sin_lat); one_MINUS_SQRes_sin = ONE_MINUS_SQR(es_sin); q = ALBERS_Q(sin_lat, one_MINUS_SQRes_sin, es_sin); nq = n * q; if (C < nq) rho = 0; else rho = Albers_a_OVER_n * sqrt(C - nq); theta = n * dlam; *Easting = rho * sin(theta) + Albers_False_Easting; *Northing = rho0 - rho * cos(theta) + Albers_False_Northing; } return (Error_Code); } /* END OF Convert_Geodetic_To_Albers */ long ossimAlbersProjection::Convert_Albers_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Albers_To_Geodetic */ /* * The function Convert_Albers_To_Geodetic converts Albers projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Albers projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise ALBERS_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dy, dx; double rho0_MINUS_dy; double q, qconst, q_OVER_2; double rho, rho_n; double PHI, Delta_PHI = 1.0; double sin_phi; double es_sin, one_MINUS_SQRes_sin; double theta = 0.0; double tolerance = 4.85e-10; /* approximately 1/1000th of an arc second or 1/10th meter */ long Error_Code = ALBERS_NO_ERROR; if ((Easting < (Albers_False_Easting - Albers_Delta_Easting)) || (Easting > Albers_False_Easting + Albers_Delta_Easting)) { /* Easting out of range */ Error_Code |= ALBERS_EASTING_ERROR; } if ((Northing < (Albers_False_Northing - Albers_Delta_Northing)) || (Northing > Albers_False_Northing + Albers_Delta_Northing)) { /* Northing out of range */ Error_Code |= ALBERS_NORTHING_ERROR; } if (!Error_Code) { dy = Northing - Albers_False_Northing; dx = Easting - Albers_False_Easting; rho0_MINUS_dy = rho0 - dy; rho = sqrt(dx * dx + rho0_MINUS_dy * rho0_MINUS_dy); if (n < 0) { rho *= -1.0; dy *= -1.0; dx *= -1.0; rho0_MINUS_dy *= -1.0; } if (rho != 0.0) theta = atan2(dx, rho0_MINUS_dy); rho_n = rho * n; q = (C - (rho_n * rho_n) / (Albers_a * Albers_a)) / n; qconst = 1 - ((one_MINUS_es2) / (two_es)) * log((1.0 - es) / (1.0 + es)); if (fabs(fabs(qconst) - fabs(q)) > 1.0e-6) { q_OVER_2 = q / 2.0; if (q_OVER_2 > 1.0) *Latitude = PI_OVER_2; else if (q_OVER_2 < -1.0) *Latitude = -PI_OVER_2; else { PHI = asin(q_OVER_2); if (es < 1.0e-10) *Latitude = PHI; else { while (fabs(Delta_PHI) > tolerance) { sin_phi = sin(PHI); es_sin = ES_SIN(sin_phi); one_MINUS_SQRes_sin = ONE_MINUS_SQR(es_sin); Delta_PHI = (one_MINUS_SQRes_sin * one_MINUS_SQRes_sin) / (2.0 * cos(PHI)) * (q / (one_MINUS_es2) - sin_phi / one_MINUS_SQRes_sin + (log((1.0 - es_sin) / (1.0 + es_sin)) / (two_es))); PHI += Delta_PHI; } *Latitude = PHI; } if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ *Latitude = PI_OVER_2; else if (*Latitude < -PI_OVER_2) *Latitude = -PI_OVER_2; } } else { if (q >= 0.0) *Latitude = PI_OVER_2; else *Latitude = -PI_OVER_2; } *Longitude = Albers_Origin_Long + theta / n; if (*Longitude > M_PI) *Longitude -= TWO_PI; if (*Longitude < -M_PI) *Longitude += TWO_PI; if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ *Longitude = M_PI; else if (*Longitude < -M_PI) *Longitude = -M_PI; } return (Error_Code); } /* END OF Convert_Albers_To_Geodetic */ //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimAlbersProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimAlbersProjection* p = dynamic_cast(&proj); if (!p) return false; if (!ossim::almostEqual(Albers_Std_Parallel_1,p->Albers_Std_Parallel_1)) return false; if (!ossim::almostEqual(Albers_Std_Parallel_2,p->Albers_Std_Parallel_2)) return false; if (!ossim::almostEqual(Albers_Delta_Northing,p->Albers_Delta_Northing)) return false; if (!ossim::almostEqual(Albers_Delta_Easting, p->Albers_Delta_Easting) ) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimAlphaSensor.cpp000066400000000000000000000505441352751253100226640ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Dave Hicks // // Description: Alpha Sensor Base Class // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceExec ("ossimAlphaSensor:exec"); static ossimTrace traceDebug("ossimAlphaSensor:debug"); RTTI_DEF1(ossimAlphaSensor, "ossimAlphaSensor", ossimSensorModel); enum { PARAM_ADJ_LON_OFFSET = 0, PARAM_ADJ_LAT_OFFSET = 1, PARAM_ADJ_ALTITUDE_OFFSET = 2, PARAM_ADJ_ROLL_OFFSET = 3, PARAM_ADJ_PITCH_OFFSET = 4, PARAM_ADJ_HDG_OFFSET = 5, PARAM_ADJ_FOCAL_LENGTH_OFFSET = 6, PARAM_ADJ_COUNT = 7 }; ossimAlphaSensor::ossimAlphaSensor() : m_rollBias(0.0), m_pitchBias(0.0), m_headingBias(0.0), m_fov(0.0), m_slitRot(0.0), m_focalLength(0.0), m_adjustedFocalLength(0.0) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensor::ossimAlphaSensor DEBUG:" << std::endl; } m_cam2Platform.ReSize(3,3); m_cam2Platform = 0.0; initAdjustableParameters(); } ossimAlphaSensor::ossimAlphaSensor(const ossimAlphaSensor& src) : ossimSensorModel(src), m_rollBias(src.m_rollBias), m_pitchBias(src.m_pitchBias), m_headingBias(src.m_headingBias), m_fov(src.m_fov), m_slitRot(src.m_slitRot), m_focalLength(src.m_focalLength), m_rollPoly(src.m_rollPoly), m_pitchPoly(src.m_pitchPoly), m_headingPoly(src.m_headingPoly), m_lonPoly(src.m_lonPoly), m_latPoly(src.m_latPoly), m_altPoly(src.m_altPoly), m_scanPoly(src.m_scanPoly), m_cam2Platform(src.m_cam2Platform), m_adjustedFocalLength(src.m_adjustedFocalLength) { } ossimObject* ossimAlphaSensor::dup()const { return new ossimAlphaSensor(*this); } void ossimAlphaSensor::lineSampToWorld(const ossimDpt& imagePoint, ossimGpt& worldPt) const { ossimEcefRay ray; imagingRay(imagePoint, ray); ossimElevManager::instance()->intersectRay(ray, worldPt); } void ossimAlphaSensor::lineSampleHeightToWorld(const ossimDpt& imagePoint, const double& heightEllipsoid, ossimGpt& worldPt) const { ossimEcefRay ray; imagingRay(imagePoint, ray); ossimEcefPoint pecf(ray.intersectAboveEarthEllipsoid(heightEllipsoid)); worldPt = ossimGpt(pecf); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHSI::lineSampleHeightToWorld DEBUG:" << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << " imagePoint = " << imagePoint << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << " heightEllipsoid = " << heightEllipsoid << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << " ray = " << ray << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << " worldPt = " << worldPt << std::endl; } } void ossimAlphaSensor::setFov(const double fov) { m_fov = fov; m_focalLength = (theImageSize.x/2)/tan((m_fov/DEG_PER_RAD)/2); } void ossimAlphaSensor::setRollBias(const double rollBias) { m_rollBias = rollBias; } void ossimAlphaSensor::setPitchBias(const double pitchBias) { m_pitchBias = pitchBias; } void ossimAlphaSensor::setHeadingBias(const double headingBias) { m_headingBias = headingBias; } void ossimAlphaSensor::setSlitRot(const double slitRot) { m_slitRot = slitRot; } void ossimAlphaSensor::setRollPoly(const std::vector< ossim_float64 > rollPoly) { m_rollPoly = rollPoly; } void ossimAlphaSensor::setPitchPoly(const std::vector< ossim_float64 > pitchPoly) { m_pitchPoly = pitchPoly; } void ossimAlphaSensor::setHeadingPoly(const std::vector< ossim_float64 > headingPoly) { m_headingPoly = headingPoly; } void ossimAlphaSensor::setLonPoly(const std::vector< ossim_float64 > lonPoly) { m_lonPoly = lonPoly; } void ossimAlphaSensor::setLatPoly(const std::vector< ossim_float64 > latPoly) { m_latPoly = latPoly; } void ossimAlphaSensor::setAltPoly(const std::vector< ossim_float64 > altPoly) { m_altPoly = altPoly; } void ossimAlphaSensor::setScanPoly(const std::vector< ossim_float64 > scanPoly) { m_scanPoly = scanPoly; } void ossimAlphaSensor::getPositionOrientation(const ossim_float64& line, ossimEcefPoint& pos, NEWMAT::Matrix& cam2EcfRot) const { // Platform position pos = getCameraPosition(line); // Local platform orientation NEWMAT::Matrix platform2Local = getPlatform2LocalRot(line); // Form local<-ECF matrix ossimGpt posG = ossimGpt(pos); NEWMAT::Matrix local2Ecf = formLLAmat(posG.latr(), posG.lonr(), 0.0); // Form full ECF<-camera matrix cam2EcfRot = local2Ecf.t() * platform2Local * m_cam2Platform; } ossimEcefPoint ossimAlphaSensor::getCameraPosition(const ossim_float64& line) const { // Interpolate position at given line number ossim_float64 lat = evalPoly(m_latPoly, line); ossim_float64 lon = evalPoly(m_lonPoly, line); ossim_float64 alt = evalPoly(m_altPoly, line); ossimGpt cameraPositionEllipsoid(lat, lon, alt); // Update adjusted position double deltap = computeParameterOffset(PARAM_ADJ_LAT_OFFSET)/ cameraPositionEllipsoid.metersPerDegree().y; double deltal = computeParameterOffset(PARAM_ADJ_LON_OFFSET)/ cameraPositionEllipsoid.metersPerDegree().x; ossimGpt adjustedCameraPosition = ossimGpt(cameraPositionEllipsoid.latd() + deltap, cameraPositionEllipsoid.lond() + deltal, cameraPositionEllipsoid.height() + computeParameterOffset(PARAM_ADJ_ALTITUDE_OFFSET)); ossimEcefPoint pos(adjustedCameraPosition); return pos; } NEWMAT::Matrix ossimAlphaSensor::getPlatform2LocalRot(const ossim_float64& line) const { // Interpolate orientation at given line number ossim_float64 roll = evalPoly(m_rollPoly, line); ossim_float64 pitch = evalPoly(m_pitchPoly, line); ossim_float64 heading = evalPoly(m_headingPoly, line); // Form orientation matrix NEWMAT::Matrix rmat = formHPRmat(-roll, -pitch, -heading); return rmat; } ossim_float64 ossimAlphaSensor::evalPoly(const std::vector& polyCoef, const ossim_float64& line) const { int nCoef = polyCoef.size(); ossim_float64 result = polyCoef[nCoef-1]; if (nCoef > 1) { for(int i=nCoef-2; i >= 0 ; --i) result = result * line + polyCoef[i]; } return result; } void ossimAlphaSensor::updateModel() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensor::updateModel DEBUG:" << std::endl; } // Apply bias corrections double r = ossim::degreesToRadians(m_rollBias + computeParameterOffset(PARAM_ADJ_ROLL_OFFSET)); double p = ossim::degreesToRadians(m_pitchBias + computeParameterOffset(PARAM_ADJ_PITCH_OFFSET)); double h = ossim::degreesToRadians(m_headingBias + computeParameterOffset(PARAM_ADJ_HDG_OFFSET)); // Form bias rotation matrix m_cam2Platform = formHPRmat(r, p, h); // Apply focal length correction m_focalLength = (theImageSize.x/2)/tan((m_fov/DEG_PER_RAD)/2); m_adjustedFocalLength = m_focalLength + computeParameterOffset(PARAM_ADJ_FOCAL_LENGTH_OFFSET); } void ossimAlphaSensor::initAdjustableParameters() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAlphaSensor::initAdjustableParameters: returning..." << std::endl; resizeAdjustableParameterArray(PARAM_ADJ_COUNT); setAdjustableParameter(PARAM_ADJ_LON_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_LON_OFFSET, "lon_offset"); setParameterUnit(PARAM_ADJ_LON_OFFSET, "meters"); setParameterSigma(PARAM_ADJ_LON_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_LAT_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_LAT_OFFSET, "lat_offset"); setParameterUnit(PARAM_ADJ_LAT_OFFSET, "meters"); setParameterSigma(PARAM_ADJ_LAT_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_ALTITUDE_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_ALTITUDE_OFFSET, "altitude_offset"); setParameterUnit(PARAM_ADJ_ALTITUDE_OFFSET, "meters"); setParameterSigma(PARAM_ADJ_ALTITUDE_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_ROLL_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_ROLL_OFFSET, "roll_offset"); setParameterUnit(PARAM_ADJ_ROLL_OFFSET, "degrees"); setParameterSigma(PARAM_ADJ_ROLL_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_PITCH_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_PITCH_OFFSET, "pitch_offset"); setParameterUnit(PARAM_ADJ_PITCH_OFFSET, "degrees"); setParameterSigma(PARAM_ADJ_PITCH_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_HDG_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_HDG_OFFSET, "heading_offset"); setParameterUnit(PARAM_ADJ_HDG_OFFSET, "degrees"); setParameterSigma(PARAM_ADJ_HDG_OFFSET, 5); setAdjustableParameter(PARAM_ADJ_FOCAL_LENGTH_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_FOCAL_LENGTH_OFFSET, "focal_length_offset"); setParameterUnit(PARAM_ADJ_FOCAL_LENGTH_OFFSET, "pixels"); setParameterSigma(PARAM_ADJ_FOCAL_LENGTH_OFFSET, 20.0); } bool ossimAlphaSensor::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensor::loadState DEBUG:" << std::endl; } theGSD.makeNan(); theRefImgPt.makeNan(); ossimSensorModel::loadState(kwl, prefix); ossimString fov = kwl.find(prefix, "fov"); ossimString number_samples = kwl.find(prefix, "number_samples"); ossimString number_lines = kwl.find(prefix, "number_lines"); ossimString rollBias = kwl.find(prefix, "roll_bias"); ossimString pitchBias = kwl.find(prefix, "pitch_bias"); ossimString headingBias = kwl.find(prefix, "heading_bias"); ossimString slitRot = kwl.find(prefix, "slit_rotation"); ossim_uint32 pcount; const char* lookup; // Roll polynomial m_rollPoly.clear(); pcount = kwl.numberOf("roll_poly_coeff"); if (pcount>0) { ossim_uint32 found = 0; ossim_uint32 count = 0; while ( (found < pcount) && (count < 100) ) { ossimString kw = "roll_poly_coeff"; kw += ossimString::toString(count);; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { ++found; m_rollPoly.push_back(ossimString::toFloat64(lookup)); } ++count; } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "DEBUG ossimAlphaSensor::loadState() roll_poly_coeff lookup failure..." << std::endl; } return false; } // Pitch polynomial m_pitchPoly.clear(); pcount = kwl.numberOf("pitch_poly_coeff"); if (pcount>0) { ossim_uint32 found = 0; ossim_uint32 count = 0; while ( (found < pcount) && (count < 100) ) { ossimString kw = "pitch_poly_coeff"; kw += ossimString::toString(count);; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { ++found; m_pitchPoly.push_back(ossimString::toFloat64(lookup)); } ++count; } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "DEBUG ossimAlphaSensor::loadState() pitch_poly_coeff lookup failure..." << std::endl; } return false; } // Heading polynomial m_headingPoly.clear(); pcount = kwl.numberOf("heading_poly_coeff"); if (pcount>0) { ossim_uint32 found = 0; ossim_uint32 count = 0; while ( (found < pcount) && (count < 100) ) { ossimString kw = "heading_poly_coeff"; kw += ossimString::toString(count);; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { ++found; m_headingPoly.push_back(ossimString::toFloat64(lookup)); } ++count; } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "DEBUG ossimAlphaSensor::loadState() heading_poly_coeff lookup failure..." << std::endl; } return false; } // Latitude polynomial m_latPoly.clear(); pcount = kwl.numberOf("lat_poly_coeff"); if (pcount>0) { ossim_uint32 found = 0; ossim_uint32 count = 0; while ( (found < pcount) && (count < 100) ) { ossimString kw = "lat_poly_coeff"; kw += ossimString::toString(count);; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { ++found; m_latPoly.push_back(ossimString::toFloat64(lookup)); } ++count; } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "DEBUG ossimAlphaSensor::loadState() lat_poly_coeff lookup failure..." << std::endl; } return false; } // Longitude polynomial m_lonPoly.clear(); pcount = kwl.numberOf("lon_poly_coeff"); if (pcount>0) { ossim_uint32 found = 0; ossim_uint32 count = 0; while ( (found < pcount) && (count < 100) ) { ossimString kw = "lon_poly_coeff"; kw += ossimString::toString(count);; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { ++found; m_lonPoly.push_back(ossimString::toFloat64(lookup)); } ++count; } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "DEBUG ossimAlphaSensor::loadState() lon_poly_coeff lookup failure..." << std::endl; } return false; } // Altitude polynomial m_altPoly.clear(); pcount = kwl.numberOf("alt_poly_coeff"); if (pcount>0) { ossim_uint32 found = 0; ossim_uint32 count = 0; while ( (found < pcount) && (count < 100) ) { ossimString kw = "alt_poly_coeff"; kw += ossimString::toString(count);; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { ++found; m_altPoly.push_back(ossimString::toFloat64(lookup)); } ++count; } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "DEBUG ossimAlphaSensor::loadState() alt_poly_coeff lookup failure..." << std::endl; } return false; } // Scan angle polynomial m_scanPoly.clear(); pcount = kwl.numberOf("scan_poly_coeff"); if (pcount>0) { ossim_uint32 found = 0; ossim_uint32 count = 0; while ( (found < pcount) && (count < 100) ) { ossimString kw = "scan_poly_coeff"; kw += ossimString::toString(count);; lookup = kwl.find(prefix, kw.c_str()); if (lookup) { ++found; m_scanPoly.push_back(ossimString::toFloat64(lookup)); } ++count; } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "DEBUG ossimAlphaSensor::loadState() scan_poly_coeff lookup failure..." << std::endl; } return false; } if(!number_samples.empty()) { theImageSize = ossimIpt(number_samples.toDouble(), number_lines.toDouble()); theRefImgPt = ossimDpt(theImageSize.x*.5, theImageSize.y*.5); theImageClipRect = ossimDrect(0,0,theImageSize.x-1, theImageSize.y-1); } if(theImageClipRect.hasNans()) { theImageClipRect = ossimDrect(0,0,theImageSize.x-1,theImageSize.y-1); } if(theRefImgPt.hasNans()) { theRefImgPt = theImageClipRect.midPoint(); } if(!fov.empty()) { m_fov = fov.toDouble(); } if(!rollBias.empty()) { m_rollBias = rollBias.toDouble(); } if(!pitchBias.empty()) { m_pitchBias = pitchBias.toDouble(); } if(!headingBias.empty()) { m_headingBias = headingBias.toDouble(); } if(!slitRot.empty()) { m_slitRot = slitRot.toDouble(); } updateModel(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensor::loadState complete..." << std::endl; } return true; } bool ossimAlphaSensor::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimSensorModel::saveState(kwl, prefix); kwl.add(prefix, "roll_bias", ossimString::toString(m_rollBias), true); kwl.add(prefix, "pitch_bias", ossimString::toString(m_pitchBias), true); kwl.add(prefix, "heading_bias", ossimString::toString(m_headingBias), true); kwl.add(prefix, "fov", ossimString::toString(m_fov) ,true); kwl.add(prefix, "slit_rotation", ossimString::toString(m_slitRot) ,true); kwl.add(prefix, "image_size", theImageSize.toString() ,true); ossim_uint32 i; for (i = 0; i < m_rollPoly.size(); ++i) { ossimString kw = "roll_poly_coeff"; kw += ossimString::toString(i); kwl.add(prefix, kw, m_rollPoly[i]); } for (i = 0; i < m_pitchPoly.size(); ++i) { ossimString kw = "pitch_poly_coeff"; kw += ossimString::toString(i); kwl.add(prefix, kw, m_pitchPoly[i]); } for (i = 0; i < m_headingPoly.size(); ++i) { ossimString kw = "heading_poly_coeff"; kw += ossimString::toString(i); kwl.add(prefix, kw, m_headingPoly[i]); } for (i = 0; i < m_lonPoly.size(); ++i) { ossimString kw = "lon_poly_coeff"; kw += ossimString::toString(i); kwl.add(prefix, kw, m_lonPoly[i]); } for (i = 0; i < m_latPoly.size(); ++i) { ossimString kw = "lat_poly_coeff"; kw += ossimString::toString(i); kwl.add(prefix, kw, m_latPoly[i]); } for (i = 0; i < m_altPoly.size(); ++i) { ossimString kw = "alt_poly_coeff"; kw += ossimString::toString(i); kwl.add(prefix, kw, m_altPoly[i]); } for (i = 0; i < m_scanPoly.size(); ++i) { ossimString kw = "scan_poly_coeff"; kw += ossimString::toString(i); kwl.add(prefix, kw, m_scanPoly[i]); } return true; } // Form ARINC 705 standard {heading/pitch/roll} rotation matrix // Rotates local<-body NEWMAT::Matrix ossimAlphaSensor::formHPRmat(const ossim_float64& r, const ossim_float64& p, const ossim_float64& h)const { ossim_float64 cp = cos(p); ossim_float64 sp = sin(p); ossim_float64 ch = cos(h); ossim_float64 sh = sin(h); ossim_float64 cr = cos(r); ossim_float64 sr = sin(r); NEWMAT::Matrix rollM = ossimMatrix3x3::create( 1, 0, 0, 0, cr,-sr, 0, sr, cr); NEWMAT::Matrix pitchM = ossimMatrix3x3::create( cp, 0, sp, 0, 1, 0, -sp, 0, cp); NEWMAT::Matrix hdgM = ossimMatrix3x3::create( ch,-sh, 0, sh, ch, 0, 0, 0, 1); NEWMAT::Matrix body2LocalRot = hdgM * pitchM * rollM; return body2LocalRot; } // Form local <- ECF rotation matrix NEWMAT::Matrix ossimAlphaSensor::formLLAmat(const ossim_float64& lat, const ossim_float64& lon, const ossim_float64& az)const { ossim_float64 cp = cos(lat); ossim_float64 sp = sin(lat); ossim_float64 cl = cos(lon); ossim_float64 sl = sin(lon); ossim_float64 ca = cos(az); ossim_float64 sa = sin(az); NEWMAT::Matrix ecf2LocalRot(3,3); ecf2LocalRot(1,1) = -sl*sa - sp*cl*ca; ecf2LocalRot(1,2) = cl*sa - sp*sl*ca; ecf2LocalRot(1,3) = cp*ca; ecf2LocalRot(2,1) = sl*ca - sp*cl*sa; ecf2LocalRot(2,2) = -cl*ca - sp*sl*sa; ecf2LocalRot(2,3) = cp*sa; ecf2LocalRot(3,1) = cp*cl; ecf2LocalRot(3,2) = cp*sl; ecf2LocalRot(3,3) = sp; return ecf2LocalRot; } ossim-Miami-2.9.1/src/projection/ossimAlphaSensorHRI.cpp000066400000000000000000000152651352751253100232300ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Dave Hicks // // Description: Alpha HRI Sensor Model // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include static ossimTrace traceExec ("ossimAlphaSensorHRI:exec"); static ossimTrace traceDebug("ossimAlphaSensorHRI:debug"); RTTI_DEF1(ossimAlphaSensorHRI, "ossimAlphaSensorHRI", ossimSensorModel); ossimAlphaSensorHRI::ossimAlphaSensorHRI() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHRI::ossimAlphaSensorHRI DEBUG:" << std::endl; } initAdjustableParameters(); theSensorID = "AlphaHRI"; } ossimAlphaSensorHRI::ossimAlphaSensorHRI(const ossimAlphaSensorHRI& src) : ossimAlphaSensor(src) { } ossimObject* ossimAlphaSensorHRI::dup()const { return new ossimAlphaSensorHRI(*this); } void ossimAlphaSensorHRI::imagingRay(const ossimDpt& imagePoint, ossimEcefRay& imageRay) const { ossim_float64 line = imagePoint.y; ossim_float64 samp = imagePoint.x - theImageSize.x/2; // Flip x because raw image is mirrored in sample direction samp = -samp; // Form camera frame LOS vector ossimColumnVector3d camLOS(0.0, samp, -m_adjustedFocalLength); // Compute camera position & orientation matrix ossimEcefPoint platPos; NEWMAT::Matrix cam2EcfRot; getPositionOrientation(line, platPos, cam2EcfRot); // Rotate camera vector to ECF ossimColumnVector3d ecfLOS = cam2EcfRot * camLOS.unit(); // Construct ECF image ray imageRay.setOrigin(platPos); ossimEcefVector ecfRayDir(ecfLOS); imageRay.setDirection(ecfRayDir); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHRI::imagingRay DEBUG:\n" << " imagePoint = " << imagePoint << "\n" << " imageRay = " << imageRay << "\n" << " camLOS = " << camLOS << "\n" << " platPos = " << platPos << "\n" << std::endl; } } void ossimAlphaSensorHRI::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { // Initialize at middle ossim_float64 refL = theImageSize.y/2; ossim_float64 drefL = 5; int nIter = 0; ossimColumnVector3d camLOS; // Iterate using Newton's method while (nIter<3) { ossim_float64 Fx[2]; ossim_float64 refl[2]; refl[0] = refL; refl[1] = refL + drefL; for (int ll=0; ll<2; ++ll) { // Compute camera position & orientation matrix ossimEcefPoint platPos; NEWMAT::Matrix cam2EcfRot; getPositionOrientation(refl[ll], platPos, cam2EcfRot); // Compute ECF vector ossimEcefPoint worldPointECF = ossimEcefPoint(world_point); ossimColumnVector3d ecfLOS = worldPointECF.data() - platPos.data(); // Rotate to camera frame camLOS = cam2EcfRot.t() * ecfLOS; // Set function value Fx[ll] = camLOS[0]; } // Compute numeric 1st derivative & new estimate for reference line (refL) ossim_float64 dFx = (Fx[1]-Fx[0]) / drefL; refL -= Fx[0]/dFx; nIter++; } ossim_float64 samp = -m_adjustedFocalLength*camLOS[1]/camLOS[2] + theImageSize.x/2; // Flip x because raw image is mirrored in sample direction samp = theImageSize.x - samp; ossimDpt p(samp, refL); image_point = p; } void ossimAlphaSensorHRI::updateModel() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHRI::updateModel DEBUG:" << std::endl; } ossimAlphaSensor::updateModel(); try { computeGsd(); } catch(...) { } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHRI::updateModel complete..." << std::endl; } // Ref point lineSampleToWorld(theRefImgPt, theRefGndPt); // Bounding rectangle ossimGpt gpt; theBoundGndPolygon.clear(); lineSampleToWorld(theImageClipRect.ul(),gpt); //+ossimDpt(-w, -h), gpt); theBoundGndPolygon.addPoint(gpt.lond(), gpt.latd()); lineSampleToWorld(theImageClipRect.ur(),gpt); //+ossimDpt(w, -h), gpt); theBoundGndPolygon.addPoint(gpt.lond(), gpt.latd()); lineSampleToWorld(theImageClipRect.lr(),gpt); //+ossimDpt(w, h), gpt); theBoundGndPolygon.addPoint(gpt.lond(), gpt.latd()); lineSampleToWorld(theImageClipRect.ll(),gpt); //+ossimDpt(-w, h), gpt); theBoundGndPolygon.addPoint(gpt.lond(), gpt.latd()); } void ossimAlphaSensorHRI::initAdjustableParameters() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAlphaSensorHRI::initAdjustableParameters: returning..." << std::endl; ossimAlphaSensor::initAdjustableParameters(); } bool ossimAlphaSensorHRI::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHRI::loadState DEBUG:" << std::endl; } ossimAlphaSensor::loadState(kwl, prefix); if(getNumberOfAdjustableParameters() < 1) { initAdjustableParameters(); } updateModel(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHRI::loadState complete..." << std::endl; } return true; } bool ossimAlphaSensorHRI::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimAlphaSensor::saveState(kwl, prefix); return true; } bool ossimAlphaSensorHRI::initialize( const ossimAlphaSensorSupportData& supData ) { bool result = true; // Currently no error checking. ossimDpt imageSize = supData.getImageSize(); setImageSize(imageSize); setImageRect(ossimDrect(0,0,imageSize.x-1, imageSize.y-1)); setRefImgPt(ossimDpt(imageSize.x*.5, imageSize.y*.5)); setFov(supData.getFov()); setRollBias(supData.getRollBias()); setPitchBias(supData.getPitchBias()); setHeadingBias(supData.getHeadingBias()); setSlitRot(supData.getSlitRot()); setRollPoly(supData.getRollPoly()); setPitchPoly(supData.getPitchPoly()); setHeadingPoly(supData.getHeadingPoly()); setLonPoly(supData.getLonPoly()); setLatPoly(supData.getLatPoly()); setAltPoly(supData.getAltPoly()); setScanPoly(supData.getScanPoly()); updateModel(); return result; } ossim-Miami-2.9.1/src/projection/ossimAlphaSensorHSI.cpp000066400000000000000000000157701352751253100232320ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Dave Hicks // // Description: Alpha HSI Sensor Model // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include static ossimTrace traceExec ("ossimAlphaSensorHSI:exec"); static ossimTrace traceDebug("ossimAlphaSensorHSI:debug"); RTTI_DEF1(ossimAlphaSensorHSI, "ossimAlphaSensorHSI", ossimSensorModel); ossimAlphaSensorHSI::ossimAlphaSensorHSI() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHSI::ossimAlphaSensorHSI DEBUG:" << std::endl; } initAdjustableParameters(); theSensorID = "AlphaHSI"; } ossimAlphaSensorHSI::ossimAlphaSensorHSI(const ossimAlphaSensorHSI& src) : ossimAlphaSensor(src) { } ossimObject* ossimAlphaSensorHSI::dup()const { return new ossimAlphaSensorHSI(*this); } void ossimAlphaSensorHSI::imagingRay(const ossimDpt& imagePoint, ossimEcefRay& imageRay) const { ossim_float64 line = imagePoint.y; // Form camera frame LOS vector ossim_float64 scanAngle = getScanAngle(line); ossimColumnVector3d camLOS(imagePoint.x - theImageSize.x/2, m_adjustedFocalLength * tan(scanAngle), m_adjustedFocalLength); // Compute camera position & orientation matrix ossimEcefPoint platPos; NEWMAT::Matrix cam2EcfRot; getPositionOrientation(line, platPos, cam2EcfRot); // Rotate camera vector to ECF ossimColumnVector3d ecfLOS = cam2EcfRot * camLOS.unit(); // Construct ECF image ray imageRay.setOrigin(platPos); ossimEcefVector ecfRayDir(ecfLOS); imageRay.setDirection(ecfRayDir); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHSI::imagingRay DEBUG:\n" << " imagePoint = " << imagePoint << "\n" << " imageRay = " << imageRay << "\n" << " camLOS = " << camLOS << "\n" << " platPos = " << platPos << "\n" << std::endl; } } void ossimAlphaSensorHSI::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { // Initialize at middle ossim_float64 refL = theImageSize.y/2; ossim_float64 drefL = 5; int nIter = 0; ossimColumnVector3d camLOS; ossimColumnVector3d camLOS1; // Iterate using Newton's method while (nIter<3) { ossim_float64 Fx[2]; ossim_float64 refl[2]; refl[0] = refL; refl[1] = refL + drefL; for (int ll=0; ll<2; ++ll) { // Compute camera position & orientation matrix ossimEcefPoint platPos; NEWMAT::Matrix cam2EcfRot; getPositionOrientation(refl[ll], platPos, cam2EcfRot); // Compute ECF vector ossimEcefPoint worldPointECF = ossimEcefPoint(world_point); ossimColumnVector3d ecfLOS = worldPointECF.data() - platPos.data(); // Rotate to camera frame camLOS = cam2EcfRot.t() * ecfLOS; if (ll==0) camLOS1 = camLOS; // Set function value ossim_float64 cScanAngle = atan(camLOS[1]/camLOS[2]); ossim_float64 scanAngle = getScanAngle(refl[ll]); Fx[ll] = cScanAngle - scanAngle; } // Compute numeric 1st derivative & new estimate for reference line (refL) ossim_float64 dFx = (Fx[1]-Fx[0]) / drefL; refL -= Fx[0]/dFx; nIter++; } ossim_float64 samp = m_adjustedFocalLength*camLOS1[0]/camLOS1[2] + theImageSize.x/2; ossimDpt p(samp, refL); image_point = p; } ossim_float64 ossimAlphaSensorHSI::getScanAngle(const ossim_float64& line) const { ossim_float64 scanAngle = evalPoly(m_scanPoly, line); return scanAngle; } void ossimAlphaSensorHSI::updateModel() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHSI::updateModel DEBUG:" << std::endl; } ossimAlphaSensor::updateModel(); try { computeGsd(); } catch(...) { } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHSI::updateModel complete..." << std::endl; } // Ref point lineSampleToWorld(theRefImgPt, theRefGndPt); // Bounding rectangle ossimGpt gpt; theBoundGndPolygon.clear(); lineSampleToWorld(theImageClipRect.ul(),gpt); //+ossimDpt(-w, -h), gpt); theBoundGndPolygon.addPoint(gpt.lond(), gpt.latd()); lineSampleToWorld(theImageClipRect.ur(),gpt); //+ossimDpt(w, -h), gpt); theBoundGndPolygon.addPoint(gpt.lond(), gpt.latd()); lineSampleToWorld(theImageClipRect.lr(),gpt); //+ossimDpt(w, h), gpt); theBoundGndPolygon.addPoint(gpt.lond(), gpt.latd()); lineSampleToWorld(theImageClipRect.ll(),gpt); //+ossimDpt(-w, h), gpt); theBoundGndPolygon.addPoint(gpt.lond(), gpt.latd()); } void ossimAlphaSensorHSI::initAdjustableParameters() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimAlphaSensorHSI::initAdjustableParameters: returning..." << std::endl; ossimAlphaSensor::initAdjustableParameters(); } bool ossimAlphaSensorHSI::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHSI::loadState DEBUG:" << std::endl; } ossimAlphaSensor::loadState(kwl, prefix); if(getNumberOfAdjustableParameters() < 1) { initAdjustableParameters(); } updateModel(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorHSI::loadState complete..." << std::endl; } return true; } bool ossimAlphaSensorHSI::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimAlphaSensor::saveState(kwl, prefix); return true; } bool ossimAlphaSensorHSI::initialize( const ossimAlphaSensorSupportData& supData ) { bool result = true; // Currently no error checking. ossimDpt imageSize = supData.getImageSize(); setImageSize(imageSize); setImageRect(ossimDrect(0,0,imageSize.x-1, imageSize.y-1)); setRefImgPt(ossimDpt(imageSize.x*.5, imageSize.y*.5)); setFov(supData.getFov()); setRollBias(supData.getRollBias()); setPitchBias(supData.getPitchBias()); setHeadingBias(supData.getHeadingBias()); setSlitRot(supData.getSlitRot()); setRollPoly(supData.getRollPoly()); setPitchPoly(supData.getPitchPoly()); setHeadingPoly(supData.getHeadingPoly()); setLonPoly(supData.getLonPoly()); setLatPoly(supData.getLatPoly()); setAltPoly(supData.getAltPoly()); setScanPoly(supData.getScanPoly()); updateModel(); return result; } ossim-Miami-2.9.1/src/projection/ossimApplanixEcefModel.cpp000066400000000000000000000644211352751253100237640ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimApplanixEcefModel.cpp 23564 2015-10-02 14:12:25Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimApplanixEcefModel:debug"); RTTI_DEF1(ossimApplanixEcefModel, "ossimApplanixEcefModel", ossimSensorModel); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimApplanixEcefModel.cpp 23564 2015-10-02 14:12:25Z dburken $"; #endif ossimApplanixEcefModel::ossimApplanixEcefModel() { theCompositeMatrix = ossimMatrix4x4::createIdentity(); theCompositeMatrixInverse = ossimMatrix4x4::createIdentity(); theRoll = 0.0; thePitch = 0.0; theHeading = 0.0; theFocalLength = 55.0; thePixelSize = ossimDpt(.009, .009); theEcefPlatformPosition = ossimGpt(0.0,0.0, 1000.0); theAdjEcefPlatformPosition = ossimGpt(0.0,0.0, 1000.0); theGSD.x = 0.1524; theGSD.y = 0.1524; theMeanGSD = 0.1524; theLensDistortion = new ossimMeanRadialLensDistortion; initAdjustableParameters(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimApplanixEcefModel::ossimApplanixEcefModel DEBUG:" << endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG)<< "OSSIM_ID: " << OSSIM_ID << endl; #endif } } ossimApplanixEcefModel::ossimApplanixEcefModel(const ossimDrect& imageRect, const ossimGpt& platformPosition, double roll, double pitch, double heading, const ossimDpt& /* principalPoint */, // in millimeters double focalLength, // in millimeters const ossimDpt& pixelSize) // in millimeters { theImageClipRect = imageRect; theRefImgPt = theImageClipRect.midPoint(); theCompositeMatrix = ossimMatrix4x4::createIdentity(); theCompositeMatrixInverse = ossimMatrix4x4::createIdentity(); theRoll = roll; thePitch = pitch; theHeading = heading; theFocalLength = focalLength; thePixelSize = pixelSize; theEcefPlatformPosition = platformPosition; theAdjEcefPlatformPosition = platformPosition; theLensDistortion = new ossimMeanRadialLensDistortion; initAdjustableParameters(); updateModel(); try { // Method throws ossimException. computeGsd(); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "ossimApplanixEcefModel Constructor caught Exception:\n" << e.what() << std::endl; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimApplanixEcefModel::ossimApplanixEcefModel DEBUG:" << endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG)<< "OSSIM_ID: " << OSSIM_ID << endl; #endif } } ossimApplanixEcefModel::ossimApplanixEcefModel(const ossimApplanixEcefModel& src) :ossimSensorModel(src) { initAdjustableParameters(); if(src.theLensDistortion.valid()) { theLensDistortion = new ossimMeanRadialLensDistortion(*(src.theLensDistortion.get())); } else { theLensDistortion = new ossimMeanRadialLensDistortion(); } } ossimObject* ossimApplanixEcefModel::dup()const { return new ossimApplanixEcefModel(*this); } void ossimApplanixEcefModel::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { // if(traceDebug()) // { // ossimNotify(ossimNotifyLevel_DEBUG) << "ossimApplanixEcefModel::imagingRay: ..... entered" << std::endl; // } ossimDpt f1 ((image_point) - theRefImgPt); f1.x *= thePixelSize.x; f1.y *= -thePixelSize.y; ossimDpt film (f1 - thePrincipalPoint); // if(traceDebug()) // { // ossimNotify(ossimNotifyLevel_DEBUG) << "pixel size = " << thePixelSize << std::endl; // ossimNotify(ossimNotifyLevel_DEBUG) << "principal pt = " << thePrincipalPoint << std::endl; // ossimNotify(ossimNotifyLevel_DEBUG) << "film pt = " << film << std::endl; // } if (theLensDistortion.valid()) { ossimDpt filmOut; theLensDistortion->undistort(film, filmOut); film = filmOut; } ossimColumnVector3d cam_ray_dir (film.x, film.y, -theFocalLength); ossimEcefVector ecf_ray_dir (theCompositeMatrix*cam_ray_dir); ecf_ray_dir = ecf_ray_dir*(1.0/ecf_ray_dir.magnitude()); image_ray.setOrigin(theAdjEcefPlatformPosition); image_ray.setDirection(ecf_ray_dir); // if(traceDebug()) // { // ossimNotify(ossimNotifyLevel_DEBUG) << "ossimApplanixEcefModel::imagingRay: ..... leaving" << std::endl; // } } void ossimApplanixEcefModel::lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimApplanixEcefModel::lineSampleToWorld:entering..." << std::endl; if(image_point.hasNans()) { gpt.makeNan(); return; } //*** // Extrapolate if image point is outside image: //*** // if (!insideImage(image_point)) // { // gpt.makeNan(); // gpt = extrapolate(image_point); // return; // } //*** // Determine imaging ray and invoke elevation source object's services to // intersect ray with terrain model: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimElevManager::instance()->intersectRay(ray, gpt); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "image_point = " << image_point << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "ray = " << ray << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "gpt = " << gpt << std::endl; } if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::lineSampleToWorld: returning..." << std::endl; return; } void ossimApplanixEcefModel::lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const { // if (!insideImage(image_point)) // { // worldPoint.makeNan(); // worldPoint = extrapolate(image_point, heightEllipsoid); // } // else { //*** // First establish imaging ray from image point: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimEcefPoint Pecf (ray.intersectAboveEarthEllipsoid(heightEllipsoid)); worldPoint = ossimGpt(Pecf); } } void ossimApplanixEcefModel::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { #if 0 if((theBoundGndPolygon.getNumberOfVertices() > 0)&& (!theBoundGndPolygon.hasNans())) { if (!(theBoundGndPolygon.pointWithin(world_point))) { // image_point.makeNan(); // image_point = extrapolate(world_point); // return; } } #endif ossimEcefPoint g_ecf(world_point); ossimEcefVector ecfRayDir(g_ecf - theAdjEcefPlatformPosition); ossimColumnVector3d camRayDir (theCompositeMatrixInverse*ecfRayDir.data()); double scale = -theFocalLength/camRayDir[2]; ossimDpt film (scale*camRayDir[0], scale*camRayDir[1]); if (theLensDistortion.valid()) { ossimDpt filmOut; theLensDistortion->distort(film, filmOut); film = filmOut; } ossimDpt f1(film + thePrincipalPoint); ossimDpt p1(f1.x/thePixelSize.x, -f1.y/thePixelSize.y); ossimDpt p0 (p1.x + theRefImgPt.x, p1.y + theRefImgPt.y); image_point = p0; } void ossimApplanixEcefModel::updateModel() { ossimGpt gpt; ossimGpt wgs84Pt; double metersPerDegree = wgs84Pt.metersPerDegree().x; double degreePerMeter = 1.0/metersPerDegree; double latShift = -computeParameterOffset(1)*theMeanGSD*degreePerMeter; double lonShift = computeParameterOffset(0)*theMeanGSD*degreePerMeter; gpt = theEcefPlatformPosition; double height = gpt.height(); gpt.height(height + computeParameterOffset(5)); gpt.latd(gpt.latd() + latShift); gpt.lond(gpt.lond() + lonShift); theAdjEcefPlatformPosition = gpt; ossimLsrSpace lsrSpace(theAdjEcefPlatformPosition, theHeading+computeParameterOffset(4)); // make a left handed roational matrix; ossimMatrix4x4 lsrMatrix(lsrSpace.lsrToEcefRotMatrix()); NEWMAT::Matrix orientation = (ossimMatrix4x4::createRotationXMatrix(thePitch+computeParameterOffset(3), OSSIM_LEFT_HANDED)* ossimMatrix4x4::createRotationYMatrix(theRoll+computeParameterOffset(2), OSSIM_LEFT_HANDED)); theCompositeMatrix = (lsrMatrix.getData()*orientation); theCompositeMatrixInverse = theCompositeMatrix.i(); theBoundGndPolygon.resize(4); // ossim_float64 w = theImageClipRect.width()*2.0; // ossim_float64 h = theImageClipRect.height()*2.0; theExtrapolateImageFlag = false; theExtrapolateGroundFlag = false; lineSampleToWorld(theImageClipRect.ul(),gpt);//+ossimDpt(-w, -h), gpt); theBoundGndPolygon[0] = gpt; lineSampleToWorld(theImageClipRect.ur(),gpt);//+ossimDpt(w, -h), gpt); theBoundGndPolygon[1] = gpt; lineSampleToWorld(theImageClipRect.lr(),gpt);//+ossimDpt(w, h), gpt); theBoundGndPolygon[2] = gpt; lineSampleToWorld(theImageClipRect.ll(),gpt);//+ossimDpt(-w, h), gpt); theBoundGndPolygon[3] = gpt; } void ossimApplanixEcefModel::initAdjustableParameters() { resizeAdjustableParameterArray(6); setAdjustableParameter(0, 0.0); setParameterDescription(0, "x_offset"); setParameterUnit(0, "pixels"); setAdjustableParameter(1, 0.0); setParameterDescription(1, "y_offset"); setParameterUnit(1, "pixels"); setAdjustableParameter(2, 0.0); setParameterDescription(2, "roll"); setParameterUnit(2, "degrees"); setAdjustableParameter(3, 0.0); setParameterDescription(3, "pitch"); setParameterUnit(3, "degrees"); setAdjustableParameter(4, 0.0); setParameterDescription(4, "heading"); setParameterUnit(4, "degrees"); setAdjustableParameter(5, 0.0); setParameterDescription(5, "altitude"); setParameterUnit(5, "meters"); setParameterSigma(0, 20.0); setParameterSigma(1, 20.0); setParameterSigma(2, .1); setParameterSigma(3, .1); setParameterSigma(4, .1); setParameterSigma(5, 50); } void ossimApplanixEcefModel::setPrincipalPoint(ossimDpt principalPoint) { thePrincipalPoint = principalPoint; } void ossimApplanixEcefModel::setRollPitchHeading(double roll, double pitch, double heading) { theRoll = roll; thePitch = pitch; theHeading = heading; updateModel(); } void ossimApplanixEcefModel::setPixelSize(const ossimDpt& pixelSize) { thePixelSize = pixelSize; } void ossimApplanixEcefModel::setImageRect(const ossimDrect& rect) { theImageClipRect = rect; theRefImgPt = rect.midPoint(); } void ossimApplanixEcefModel::setFocalLength(double focalLength) { theFocalLength = focalLength; } void ossimApplanixEcefModel::setPlatformPosition(const ossimGpt& gpt) { theRefGndPt = gpt; theEcefPlatformPosition = gpt; updateModel(); } bool ossimApplanixEcefModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimSensorModel::saveState(kwl, prefix); kwl.add(prefix, "type", "ossimApplanixEcefModel", true); kwl.add(prefix, "roll", theRoll, true); kwl.add(prefix, "pitch", thePitch, true); kwl.add(prefix, "heading", theHeading, true); kwl.add(prefix, "principal_point", ossimString::toString(thePrincipalPoint.x) + " " + ossimString::toString(thePrincipalPoint.y)); kwl.add(prefix, "pixel_size", ossimString::toString(thePixelSize.x) + " " + ossimString::toString(thePixelSize.y)); kwl.add(prefix, "focal_length", theFocalLength); kwl.add(prefix, "ecef_platform_position", ossimString::toString(theEcefPlatformPosition.x()) + " " + ossimString::toString(theEcefPlatformPosition.y()) + " " + ossimString::toString(theEcefPlatformPosition.z())); if(theLensDistortion.valid()) { ossimString lensPrefix = ossimString(prefix)+"distortion."; theLensDistortion->saveState(kwl, lensPrefix.c_str()); } return true; } bool ossimApplanixEcefModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { if(traceDebug()) { std::cout << "ossimApplanixEcefModel::loadState: ......... entered" << std::endl; } theImageClipRect = ossimDrect(0,0,4076,4091); theRefImgPt = ossimDpt(2046.0, 2038.5); ossimSensorModel::loadState(kwl, prefix); if(getNumberOfAdjustableParameters() < 1) { initAdjustableParameters(); } theEcefPlatformPosition = ossimGpt(0.0,0.0,1000.0); theAdjEcefPlatformPosition = ossimGpt(0.0,0.0,1000.0); theRoll = 0.0; thePitch = 0.0; theHeading = 0.0; // bool computeGsdFlag = false; const char* roll = kwl.find(prefix, "roll"); const char* pitch = kwl.find(prefix, "pitch"); const char* heading = kwl.find(prefix, "heading"); const char* principal_point = kwl.find(prefix, "principal_point"); const char* pixel_size = kwl.find(prefix, "pixel_size"); const char* focal_length = kwl.find(prefix, "focal_length"); const char* ecef_platform_position = kwl.find(prefix, "ecef_platform_position"); const char* latlonh_platform_position = kwl.find(prefix, "latlonh_platform_position"); const char* compute_gsd_flag = kwl.find(prefix, "compute_gsd_flag"); const char* eo_file = kwl.find(prefix, "eo_file"); const char* camera_file = kwl.find(prefix, "camera_file"); const char* eo_id = kwl.find(prefix, "eo_id"); bool result = true; if(eo_id) { theImageID = eo_id; } if(eo_file) { ossimApplanixEOFile eoFile; if(eoFile.parseFile(ossimFilename(eo_file))) { ossimRefPtr record = eoFile.getRecordGivenId(theImageID); if(record.valid()) { ossim_int32 rollIdx = eoFile.getFieldIdx("ROLL"); ossim_int32 pitchIdx = eoFile.getFieldIdx("PITCH"); ossim_int32 headingIdx = eoFile.getFieldIdx("HEADING"); ossim_int32 xIdx = eoFile.getFieldIdx("X"); ossim_int32 yIdx = eoFile.getFieldIdx("Y"); ossim_int32 zIdx = eoFile.getFieldIdx("Z"); if((rollIdx >= 0)&& (pitchIdx >= 0)&& (headingIdx >= 0)&& (xIdx >= 0)&& (yIdx >= 0)&& (zIdx >= 0)) { theRoll = (*record)[rollIdx].toDouble(); thePitch = (*record)[pitchIdx].toDouble(); theHeading = (*record)[headingIdx].toDouble(); theEcefPlatformPosition = ossimEcefPoint((*record)[xIdx].toDouble(), (*record)[yIdx].toDouble(), (*record)[zIdx].toDouble()); theAdjEcefPlatformPosition = theEcefPlatformPosition; } else { return false; } } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimApplanixEcefModel::loadState() Image id " << theImageID << " not found in eo file " << eo_file << std::endl; return false; } } else { return false; } // computeGsdFlag = true; } else { if(roll) { theRoll = ossimString(roll).toDouble(); } if(pitch) { thePitch = ossimString(pitch).toDouble(); } if(heading) { theHeading = ossimString(heading).toDouble(); } if(ecef_platform_position) { std::vector splitString; ossimString tempString(ecef_platform_position); tempString.split(splitString, ossimString(" ")); if(splitString.size() > 2) { theEcefPlatformPosition = ossimEcefPoint(splitString[0].toDouble(), splitString[1].toDouble(), splitString[2].toDouble()); } } else if(latlonh_platform_position) { std::vector splitString; ossimString tempString(latlonh_platform_position); tempString.split(splitString, ossimString(" ")); std::string datumString; double lat=0.0, lon=0.0, h=0.0; if(splitString.size() > 2) { lat = splitString[0].toDouble(); lon = splitString[1].toDouble(); h = splitString[2].toDouble(); } theEcefPlatformPosition = ossimGpt(lat,lon,h); } } if(camera_file) { ossimKeywordlist cameraKwl; ossimKeywordlist lensKwl; cameraKwl.add(camera_file); const char* sensor = cameraKwl.find("sensor"); const char* image_size = cameraKwl.find(prefix, "image_size"); principal_point = cameraKwl.find("principal_point"); focal_length = cameraKwl.find("focal_length"); pixel_size = cameraKwl.find(prefix, "pixel_size"); focal_length = cameraKwl.find(prefix, "focal_length"); const char* distortion_units = cameraKwl.find(prefix, "distortion_units"); ossimUnitConversionTool tool; ossimUnitType unitType = OSSIM_MILLIMETERS; if(distortion_units) { unitType = (ossimUnitType)ossimUnitTypeLut::instance()->getEntryNumber(distortion_units); if(unitType == OSSIM_UNIT_UNKNOWN) { unitType = OSSIM_MILLIMETERS; } } if(image_size) { std::vector splitString; ossimString tempString(image_size); tempString.split(splitString, ossimString(" ")); double w=1, h=1; if(splitString.size() == 2) { w = splitString[0].toDouble(); h = splitString[1].toDouble(); } theImageClipRect = ossimDrect(0,0,w-1,h-1); theRefImgPt = ossimDpt(w/2.0, h/2.0); theImageSize = ossimDpt(w,h); } if(sensor) { theSensorID = sensor; } if(principal_point) { std::vector splitString; ossimString tempString(principal_point); tempString.split(splitString, ossimString(" ")); if(splitString.size() == 2) { thePrincipalPoint.x = splitString[0].toDouble(); thePrincipalPoint.y = splitString[1].toDouble(); } } if(pixel_size) { std::vector splitString; ossimString tempString(pixel_size); tempString.split(splitString, ossimString(" ")); if(splitString.size() == 1) { thePixelSize.x = splitString[0].toDouble(); thePixelSize.y = thePixelSize.x; } else if(splitString.size() == 2) { thePixelSize.x = splitString[0].toDouble(); thePixelSize.y = splitString[1].toDouble(); } } if(focal_length) { theFocalLength = ossimString(focal_length).toDouble(); } cameraKwl.trimAllValues(); ossimString regExpression = ossimString("^(") + "d[0-9]+)"; vector keys; cameraKwl.getSubstringKeyList( keys, regExpression ); long numberOfDistortions = (long)keys.size(); int offset = (int)ossimString("d").size(); ossim_uint32 idx = 0; std::vector numberList(numberOfDistortions); for(idx = 0; idx < numberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); numberList[idx] = numberStr.toInt(); } std::sort(numberList.begin(), numberList.end()); double distance=0.0, distortion=0.0; for(idx = 0; idx < numberList.size(); ++idx) { ossimString value = cameraKwl.find(ossimString("d")+ossimString::toString(numberList[idx])); if(!value.empty()) { std::istringstream inStr(value.c_str()); inStr >> distance; ossim::skipws(inStr); inStr >> distortion; #if 0 std::vector splitString; ossimString tempString(value); tempString = tempString.trim(); tempString.split(splitString, " "); std::cout << splitString.size() << std::endl; if(splitString.size() >= 2) { distance = splitString[0].toDouble(); distortion = splitString[1].toDouble(); } #endif tool.setValue(distortion, unitType); lensKwl.add(ossimString("distance") + ossimString::toString(idx), distance, true); lensKwl.add(ossimString("distortion") + ossimString::toString(idx), tool.getMillimeters(), true); } lensKwl.add("convergence_threshold", .00001, true); if(pixel_size) { lensKwl.add("dxdy", ossimString(pixel_size) + " " + ossimString(pixel_size), true); } else { lensKwl.add("dxdy", ".009 .009", true); } } if(theLensDistortion.valid()) { theLensDistortion->loadState(lensKwl,""); } } else { if(principal_point) { std::vector splitString; ossimString tempString(principal_point); tempString.split(splitString, ossimString(" ")); if(splitString.size() == 2) { thePrincipalPoint.x = splitString[0].toDouble(); thePrincipalPoint.y = splitString[1].toDouble(); } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No principal_point found" << std::endl; result = false; } } if(pixel_size) { std::vector splitString; ossimString tempString(pixel_size); tempString.split(splitString, ossimString(" ")); if(splitString.size() == 1) { thePixelSize.x = splitString[0].toDouble(); thePixelSize.y = thePixelSize.x; } else if(splitString.size() == 2) { thePixelSize.x = splitString[0].toDouble(); thePixelSize.y = splitString[1].toDouble(); } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No pixel size found" << std::endl; result = false; } } if(focal_length) { theFocalLength = ossimString(focal_length).toDouble(); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No focal length found" << std::endl; result = false; } } if(theLensDistortion.valid()) { ossimString lensPrefix = ossimString(prefix)+"distortion."; if(!theLensDistortion->loadState(kwl, lensPrefix.c_str())) { result = false; } } } theRefGndPt = theEcefPlatformPosition; theRefGndPt.height(0.0); updateModel(); if(compute_gsd_flag) { if(ossimString(compute_gsd_flag).toBool()) { try { //--- // This will set theGSD and theMeanGSD. Method throws // ossimException. //--- computeGsd(); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "ossimApplanixEcefModel::loadState Caught Exception:\n" << e.what() << std::endl; } } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << std::setprecision(15) << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "roll: " << theRoll << std::endl << "pitch: " << thePitch << std::endl << "heading: " << theHeading << std::endl << "platform: " << theEcefPlatformPosition << std::endl << "latlon Platform: " << ossimGpt(theEcefPlatformPosition) << std::endl << "focal len: " << theFocalLength << std::endl << "principal: " << thePrincipalPoint << std::endl << "Ground: " << ossimGpt(theEcefPlatformPosition) << std::endl; } return result; } bool ossimApplanixEcefModel::setupOptimizer(const ossimString& init_file) { ossimKeywordlist kwl; kwl.addFile(init_file.c_str()); return loadState(kwl); } ossim-Miami-2.9.1/src/projection/ossimApplanixUtmModel.cpp000066400000000000000000001020431352751253100236600ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // LGPL // // Author: Garrett Potts // //******************************************************************* // $Id: ossimApplanixUtmModel.cpp 23564 2015-10-02 14:12:25Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimApplanixUtmModel:debug"); RTTI_DEF1(ossimApplanixUtmModel, "ossimApplanixUtmModel", ossimSensorModel); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimApplanixUtmModel.cpp 23564 2015-10-02 14:12:25Z dburken $"; #endif ossimApplanixUtmModel::ossimApplanixUtmModel() :theOmega(0.0), thePhi(0.0), theKappa(0.0), theBoreSightTx(0.0), theBoreSightTy(0.0), theBoreSightTz(0.0) { theCompositeMatrix = ossimMatrix4x4::createIdentity(); theCompositeMatrixInverse = ossimMatrix4x4::createIdentity(); theFocalLength = 55.0; thePixelSize = ossimDpt(.009, .009); theEcefPlatformPosition = ossimGpt(0.0,0.0, 1000.0); theGSD.x = 0.1524; theGSD.y = 0.1524; theMeanGSD = 0.1524; theLensDistortion = new ossimMeanRadialLensDistortion; initAdjustableParameters(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimApplanixUtmModel::ossimApplanixUtmModel DEBUG:" << endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG)<< "OSSIM_ID: " << OSSIM_ID << endl; #endif } } ossimApplanixUtmModel::ossimApplanixUtmModel(const ossimApplanixUtmModel& src) :ossimSensorModel(src), theCompositeMatrix(src.theCompositeMatrix), theCompositeMatrixInverse(src.theCompositeMatrixInverse), theOmega(src.theOmega), thePhi(src.thePhi), theKappa(src.theKappa), theBoreSightTx(src.theBoreSightTx), theBoreSightTy(src.theBoreSightTy), theBoreSightTz(src.theBoreSightTz), thePrincipalPoint(src.thePrincipalPoint), thePixelSize(src.thePixelSize), theFocalLength(src.theFocalLength), theEcefPlatformPosition(src.theEcefPlatformPosition), thePlatformPosition(src.thePlatformPosition), theUtmZone(src.theUtmZone), theUtmHemisphere(src.theUtmHemisphere), theUtmPlatformPosition(src.theUtmPlatformPosition) { if(src.theLensDistortion.valid()) { theLensDistortion = new ossimMeanRadialLensDistortion(*(src.theLensDistortion.get())); } else { theLensDistortion = new ossimMeanRadialLensDistortion(); } } ossimObject* ossimApplanixUtmModel::dup()const { return new ossimApplanixUtmModel(*this); } void ossimApplanixUtmModel::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { // if(traceDebug()) // { // ossimNotify(ossimNotifyLevel_DEBUG) << "ossimApplanixUtmModel::imagingRay: ..... entered" << std::endl; // } ossimDpt f1 ((image_point) - theRefImgPt); f1.x *= thePixelSize.x; f1.y *= -thePixelSize.y; ossimDpt film (f1 - thePrincipalPoint); // if(traceDebug()) // { // ossimNotify(ossimNotifyLevel_DEBUG) << "pixel size = " << thePixelSize << std::endl; // ossimNotify(ossimNotifyLevel_DEBUG) << "principal pt = " << thePrincipalPoint << std::endl; // ossimNotify(ossimNotifyLevel_DEBUG) << "film pt = " << film << std::endl; // } if (theLensDistortion.valid()) { ossimDpt filmOut; theLensDistortion->undistort(film, filmOut); film = filmOut; } ossimColumnVector3d cam_ray_dir (film.x, film.y, -theFocalLength); ossimEcefVector ecf_ray_dir (theCompositeMatrix*cam_ray_dir); ecf_ray_dir = ecf_ray_dir*(1.0/ecf_ray_dir.magnitude()); image_ray.setOrigin(theAdjEcefPlatformPosition); image_ray.setDirection(ecf_ray_dir); // if(traceDebug()) // { // ossimNotify(ossimNotifyLevel_DEBUG) << "ossimApplanixUtmModel::imagingRay: ..... leaving" << std::endl; // } } void ossimApplanixUtmModel::lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimApplanixEcefModel::lineSampleToWorld:entering..." << std::endl; if(image_point.hasNans()) { gpt.makeNan(); return; } //*** // Extrapolate if image point is outside image: //*** // if (!insideImage(image_point)) // { // gpt.makeNan(); // gpt = extrapolate(image_point); // return; //} //*** // Determine imaging ray and invoke elevation source object's services to // intersect ray with terrain model: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimElevManager::instance()->intersectRay(ray, gpt); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "image_point = " << image_point << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "ray = " << ray << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "gpt = " << gpt << std::endl; } if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::lineSampleToWorld: returning..." << std::endl; return; } void ossimApplanixUtmModel::lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const { // if (!insideImage(image_point)) // { //worldPoint.makeNan(); // worldPoint = extrapolate(image_point, heightEllipsoid); // } // else { //*** // First establish imaging ray from image point: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimEcefPoint Pecf (ray.intersectAboveEarthEllipsoid(heightEllipsoid)); worldPoint = ossimGpt(Pecf); } } void ossimApplanixUtmModel::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { #if 0 if((theBoundGndPolygon.getNumberOfVertices() > 0)&& (!theBoundGndPolygon.hasNans())) { if (!(theBoundGndPolygon.pointWithin(world_point))) { image_point.makeNan(); // image_point = extrapolate(world_point); return; } } #endif ossimEcefPoint g_ecf(world_point); ossimEcefVector ecfRayDir(g_ecf - theAdjEcefPlatformPosition); ossimColumnVector3d camRayDir (theCompositeMatrixInverse*ecfRayDir.data()); double scale = -theFocalLength/camRayDir[2]; ossimDpt film (scale*camRayDir[0], scale*camRayDir[1]); if (theLensDistortion.valid()) { ossimDpt filmOut; theLensDistortion->distort(film, filmOut); film = filmOut; } ossimDpt f1(film + thePrincipalPoint); ossimDpt p1(f1.x/thePixelSize.x, -f1.y/thePixelSize.y); ossimDpt p0 (p1.x + theRefImgPt.x, p1.y + theRefImgPt.y); image_point = p0; } void ossimApplanixUtmModel::updateModel() { ossimGpt wgs84Pt; double metersPerDegree = wgs84Pt.metersPerDegree().x; double degreePerMeter = 1.0/metersPerDegree; double latShift = -computeParameterOffset(1)*theMeanGSD*degreePerMeter; double lonShift = computeParameterOffset(0)*theMeanGSD*degreePerMeter; ossimGpt gpt = thePlatformPosition; // gpt.height(0.0); double height = gpt.height(); gpt.height(height + computeParameterOffset(5)); gpt.latd(gpt.latd() + latShift); gpt.lond(gpt.lond() + lonShift); theAdjEcefPlatformPosition = gpt; ossimLsrSpace lsrSpace(theAdjEcefPlatformPosition); // ORIENT TO A UTM AXIS // NEWMAT::ColumnVector v(3); v[0] = 0.0; v[1] = 0.0; v[2] = 1.0; NEWMAT::ColumnVector v2 = lsrSpace.lsrToEcefRotMatrix()*v; ossimEcefVector zVector(v2[0], v2[1], v2[2]); zVector.normalize(); // now lets create a UTM axis by creating a derivative at the center // by shift over a few pixels and subtracting // ossimUtmProjection utmProj; utmProj.setZone(theUtmZone); utmProj.setZone(theUtmHemisphere); utmProj.setMetersPerPixel(ossimDpt(1.0,1.0)); ossimDpt midPt = utmProj.forward(theAdjEcefPlatformPosition); ossimDpt rPt = midPt + ossimDpt(10, 0.0); ossimDpt uPt = midPt + ossimDpt(0.0, 10.0); ossimGpt wMidPt = utmProj.inverse(midPt); ossimGpt wRPt = utmProj.inverse(rPt); ossimGpt wUPt = utmProj.inverse(uPt); ossimEcefPoint ecefMidPt = wMidPt; ossimEcefPoint ecefRPt = wRPt; ossimEcefPoint ecefUPt = wUPt; ossimEcefVector east = ecefRPt-ecefMidPt; ossimEcefVector north = ecefUPt-ecefMidPt; east.normalize(); north.normalize(); // now use the lsr space constructors to construct an orthogonal set of axes // lsrSpace = ossimLsrSpace(thePlatformPosition, 0, north, east.cross(north)); // lsrSpace = ossimLsrSpace(thePlatformPosition); // DONE ORIENT TO UTM AXIS NEWMAT::Matrix platformLsrMatrix = lsrSpace.lsrToEcefRotMatrix(); NEWMAT::Matrix orientationMatrix = (ossimMatrix3x3::createRotationXMatrix(theOmega+computeParameterOffset(2), OSSIM_LEFT_HANDED)* ossimMatrix3x3::createRotationYMatrix(thePhi+computeParameterOffset(3), OSSIM_LEFT_HANDED)* ossimMatrix3x3::createRotationZMatrix(theKappa+computeParameterOffset(4), OSSIM_LEFT_HANDED)); theCompositeMatrix = platformLsrMatrix*orientationMatrix; theCompositeMatrixInverse = theCompositeMatrix.i(); // theAdjEcefPlatformPosition = theEcefPlatformPosition; theBoundGndPolygon.resize(4); // ossim_float64 w = theImageClipRect.width();//*2.0; // ossim_float64 h = theImageClipRect.height();//*2.0; lineSampleToWorld(theImageClipRect.ul(),gpt);//+ossimDpt(-w, -h), gpt); theBoundGndPolygon[0] = gpt; lineSampleToWorld(theImageClipRect.ur(),gpt);//+ossimDpt(w, -h), gpt); theBoundGndPolygon[1] = gpt; lineSampleToWorld(theImageClipRect.lr(),gpt);//+ossimDpt(w, h), gpt); theBoundGndPolygon[2] = gpt; lineSampleToWorld(theImageClipRect.ll(),gpt);//+ossimDpt(-w, h), gpt); theBoundGndPolygon[3] = gpt; } void ossimApplanixUtmModel::initAdjustableParameters() { resizeAdjustableParameterArray(6); setAdjustableParameter(0, 0.0); setParameterDescription(0, "x_offset"); setParameterUnit(0, "pixels"); setAdjustableParameter(1, 0.0); setParameterDescription(1, "y_offset"); setParameterUnit(1, "pixels"); setAdjustableParameter(2, 0.0); setParameterDescription(2, "orientation x"); setParameterUnit(2, "degrees"); setAdjustableParameter(3, 0.0); setParameterDescription(3, "orientation y"); setParameterUnit(3, "degrees"); setAdjustableParameter(4, 0.0); setParameterDescription(4, "orientation z"); setParameterUnit(4, "degrees"); setAdjustableParameter(5, 0.0); setParameterDescription(5, "Altitude delta"); setParameterUnit(5, "meters"); setParameterSigma(0, 20.0); setParameterSigma(1, 20.0); setParameterSigma(2, .1); setParameterSigma(3, .1); setParameterSigma(4, .1); setParameterSigma(5, 50); } void ossimApplanixUtmModel::setPrincipalPoint(ossimDpt principalPoint) { thePrincipalPoint = principalPoint; } void ossimApplanixUtmModel::setPixelSize(const ossimDpt& pixelSize) { thePixelSize = pixelSize; } void ossimApplanixUtmModel::setImageRect(const ossimDrect& rect) { theImageClipRect = rect; theRefImgPt = rect.midPoint(); } void ossimApplanixUtmModel::setFocalLength(double focalLength) { theFocalLength = focalLength; } void ossimApplanixUtmModel::setPlatformPosition(const ossimGpt& gpt) { theRefGndPt = gpt; theEcefPlatformPosition = gpt; updateModel(); } bool ossimApplanixUtmModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimSensorModel::saveState(kwl, prefix); kwl.add(prefix, "type", "ossimApplanixUtmModel", true); kwl.add(prefix, "omega", theOmega, true); kwl.add(prefix, "phi", thePhi, true); kwl.add(prefix, "kappa", theKappa, true); kwl.add(prefix, "bore_sight_tx", theBoreSightTx*60, true); kwl.add(prefix, "bore_sight_ty", theBoreSightTy*60, true); kwl.add(prefix, "bore_sight_tz", theBoreSightTz*60, true); kwl.add(prefix, "principal_point", ossimString::toString(thePrincipalPoint.x) + " " + ossimString::toString(thePrincipalPoint.y)); kwl.add(prefix, "pixel_size", ossimString::toString(thePixelSize.x) + " " + ossimString::toString(thePixelSize.y)); kwl.add(prefix, "focal_length", theFocalLength); kwl.add(prefix, "ecef_platform_position", ossimString::toString(theEcefPlatformPosition.x()) + " " + ossimString::toString(theEcefPlatformPosition.y()) + " " + ossimString::toString(theEcefPlatformPosition.z())); kwl.add(prefix, "latlonh_platform_position", ossimString::toString(thePlatformPosition.latd()) + " " + ossimString::toString(thePlatformPosition.lond()) + " " + ossimString::toString(thePlatformPosition.height()) + " " + thePlatformPosition.datum()->code()); kwl.add(prefix, "utm_platform_position", ossimString::toString(theUtmPlatformPosition.x) + " " + ossimString::toString(theUtmPlatformPosition.y) + " " + ossimString::toString(theUtmPlatformPosition.z) + " " + thePlatformPosition.datum()->code(), true); kwl.add(prefix, "utm_zone", theUtmZone, true); kwl.add(prefix, "utm_hemisphere", theUtmHemisphere, true); kwl.add(prefix, "shift_values", ossimString::toString(theShiftValues.x()) + " " + ossimString::toString(theShiftValues.y()) + " " + ossimString::toString(theShiftValues.z()), true); if(theLensDistortion.valid()) { ossimString lensPrefix = ossimString(prefix)+"distortion."; theLensDistortion->saveState(kwl, lensPrefix.c_str()); } return true; } bool ossimApplanixUtmModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { if(traceDebug()) { std::cout << "ossimApplanixUtmModel::loadState: ......... entered" << std::endl; } theImageClipRect = ossimDrect(0,0,4076,4091); theRefImgPt = ossimDpt(2046.0, 2038.5); ossimSensorModel::loadState(kwl, prefix); if(getNumberOfAdjustableParameters() < 1) { initAdjustableParameters(); } const char* eo_file = kwl.find(prefix, "eo_file"); const char* eo_id = kwl.find(prefix, "eo_id"); const char* omega = kwl.find(prefix, "omega"); const char* phi = kwl.find(prefix, "phi"); const char* kappa = kwl.find(prefix, "kappa"); const char* bore_sight_tx = kwl.find(prefix, "bore_sight_tx"); const char* bore_sight_ty = kwl.find(prefix, "bore_sight_ty"); const char* bore_sight_tz = kwl.find(prefix, "bore_sight_tz"); const char* principal_point = kwl.find(prefix, "principal_point"); const char* pixel_size = kwl.find(prefix, "pixel_size"); const char* focal_length = kwl.find(prefix, "focal_length"); const char* latlonh_platform_position = kwl.find(prefix, "latlonh_platform_position"); const char* utm_platform_position = kwl.find(prefix, "utm_platform_position"); const char* compute_gsd_flag = kwl.find(prefix, "compute_gsd_flag"); const char* utm_zone = kwl.find(prefix, "utm_zone"); const char* utm_hemisphere = kwl.find(prefix, "utm_hemisphere"); const char* camera_file = kwl.find(prefix, "camera_file"); const char* shift_values = kwl.find(prefix, "shift_values"); theCompositeMatrix = ossimMatrix3x3::createIdentity(); theCompositeMatrixInverse = ossimMatrix3x3::createIdentity(); theOmega = 0.0; thePhi = 0.0; theKappa = 0.0; theBoreSightTx = 0.0; theBoreSightTy = 0.0; theBoreSightTz = 0.0; theFocalLength = 55.0; thePixelSize = ossimDpt(.009, .009); theEcefPlatformPosition = ossimGpt(0.0,0.0, 1000.0); bool loadedFromEoFile = false; if(eo_id) { theImageID = eo_id; } // loading from standard eo file with given record id // if(eo_file) { ossimApplanixEOFile eoFile; if(eoFile.parseFile(ossimFilename(eo_file))) { ossimRefPtr record = eoFile.getRecordGivenId(theImageID); if(record.valid()) { loadedFromEoFile = true; theBoreSightTx = eoFile.getBoreSightTx()/60.0; theBoreSightTy = eoFile.getBoreSightTy()/60.0; theBoreSightTz = eoFile.getBoreSightTz()/60.0; theShiftValues = ossimEcefVector(eoFile.getShiftValuesX(), eoFile.getShiftValuesY(), eoFile.getShiftValuesZ()); ossim_int32 easting = eoFile.getFieldIdxLike("EASTING"); ossim_int32 northing = eoFile.getFieldIdxLike("NORTHING"); ossim_int32 height = eoFile.getFieldIdxLike("HEIGHT"); ossim_int32 omega = eoFile.getFieldIdxLike("OMEGA"); ossim_int32 phi = eoFile.getFieldIdxLike("PHI"); ossim_int32 kappa = eoFile.getFieldIdxLike("KAPPA"); if((omega>=0)&& (phi>=0)&& (kappa>=0)&& (height>=0)&& (easting>=0)&& (northing>=0)) { theOmega = (*record)[omega].toDouble(); thePhi = (*record)[phi].toDouble(); theKappa = (*record)[kappa].toDouble(); double h = (*record)[height].toDouble(); ossimString heightType = kwl.find(prefix, "height_type"); if(eoFile.isUtmFrame()) { theUtmZone = eoFile.getUtmZone(); theUtmHemisphere = eoFile.getUtmHemisphere()=="North"?'N':'S'; ossimUtmProjection utmProj; utmProj.setZone(theUtmZone); utmProj.setHemisphere((char)theUtmHemisphere); theUtmPlatformPosition.x = (*record)[easting].toDouble(); theUtmPlatformPosition.y = (*record)[northing].toDouble(); theUtmPlatformPosition.z = h; thePlatformPosition = utmProj.inverse(ossimDpt(theUtmPlatformPosition.x, theUtmPlatformPosition.y)); thePlatformPosition.height(h); if(eoFile.isHeightAboveMSL()) { double offset = ossimGeoidManager::instance()->offsetFromEllipsoid(thePlatformPosition); if(!ossim::isnan(offset)) { thePlatformPosition.height(h + offset); theUtmPlatformPosition.z = h + offset; } } } else { return false; } } theEcefPlatformPosition = thePlatformPosition; } else { return false; } } } if(!loadedFromEoFile) { if(shift_values) { std::vector splitString; ossimString tempString(shift_values); tempString = tempString.trim(); tempString.split(splitString, " " ); if(splitString.size() == 3) { theShiftValues = ossimEcefVector(splitString[0].toDouble(), splitString[1].toDouble(), splitString[2].toDouble()); } } if(omega&&phi&&kappa) { theOmega = ossimString(omega).toDouble(); thePhi = ossimString(phi).toDouble(); theKappa = ossimString(kappa).toDouble(); } if(bore_sight_tx&&bore_sight_ty&&bore_sight_tz) { theBoreSightTx = ossimString(bore_sight_tx).toDouble()/60.0; theBoreSightTy = ossimString(bore_sight_ty).toDouble()/60.0; theBoreSightTz = ossimString(bore_sight_tz).toDouble()/60.0; } double lat=0.0, lon=0.0, h=0.0; if(utm_zone) { theUtmZone = ossimString(utm_zone).toInt32(); } if(utm_hemisphere) { ossimString hem = utm_hemisphere; hem = hem.trim(); hem = hem.upcase(); theUtmHemisphere = *(hem.begin()); } if(utm_platform_position) { ossimUtmProjection utmProj; std::vector splitString; ossimString tempString(utm_platform_position); tempString = tempString.trim(); ossimString datumString; utmProj.setZone(theUtmZone); utmProj.setHemisphere((char)theUtmHemisphere); tempString.split(splitString, " "); if(splitString.size() > 2) { theUtmPlatformPosition.x = splitString[0].toDouble(); theUtmPlatformPosition.y = splitString[1].toDouble(); theUtmPlatformPosition.z = splitString[2].toDouble(); } if(splitString.size() > 3) { datumString = splitString[3]; } const ossimDatum* datum = ossimDatumFactory::instance()->create(datumString); if(datum) { utmProj.setDatum(datum); } thePlatformPosition = utmProj.inverse(ossimDpt(theUtmPlatformPosition.x, theUtmPlatformPosition.y)); thePlatformPosition.height(theUtmPlatformPosition.z); ossimString heightType = kwl.find(prefix, "height_type"); if(heightType == "msl") { double offset = ossimGeoidManager::instance()->offsetFromEllipsoid(thePlatformPosition); if(ossim::isnan(offset) == false) { thePlatformPosition.height(thePlatformPosition.height() + offset); theUtmPlatformPosition.z = thePlatformPosition.height(); } } theEcefPlatformPosition = thePlatformPosition; } else if(latlonh_platform_position) { std::vector splitString; ossimString tempString(latlonh_platform_position); std::string datumString; tempString = tempString.trim(); tempString.split(splitString, " "); if(splitString.size() > 2) { lat = splitString[0].toDouble(); lon = splitString[1].toDouble(); h = splitString[2].toDouble(); } if(splitString.size() > 3) { datumString = splitString[3].string(); } thePlatformPosition.latd(lat); thePlatformPosition.lond(lon); thePlatformPosition.height(h); const ossimDatum* datum = ossimDatumFactory::instance()->create(datumString); if(datum) { thePlatformPosition.datum(datum); } ossimString heightType = kwl.find(prefix, "height_type"); if(heightType == "msl") { double offset = ossimGeoidManager::instance()->offsetFromEllipsoid(thePlatformPosition); if(ossim::isnan(offset) == false) { thePlatformPosition.height(thePlatformPosition.height() + offset); } } theEcefPlatformPosition = thePlatformPosition; } } if(principal_point) { std::vector splitString; ossimString tempString(principal_point); tempString = tempString.trim(); tempString.split(splitString, " "); if(splitString.size() == 2) { thePrincipalPoint.x = splitString[0].toDouble(); thePrincipalPoint.y = splitString[1].toDouble(); } } if(pixel_size) { std::vector splitString; ossimString tempString(principal_point); tempString = tempString.trim(); tempString.split(splitString, " "); if(splitString.size() == 2) { thePixelSize.x = splitString[0].toDouble(); thePixelSize.y = splitString[1].toDouble(); } } if(focal_length) { theFocalLength = ossimString(focal_length).toDouble(); } if(camera_file) { ossimKeywordlist cameraKwl; ossimKeywordlist lensKwl; cameraKwl.add(camera_file); const char* sensor = cameraKwl.find("sensor"); const char* image_size = cameraKwl.find(prefix, "image_size"); principal_point = cameraKwl.find("principal_point"); focal_length = cameraKwl.find("focal_length"); pixel_size = cameraKwl.find(prefix, "pixel_size"); focal_length = cameraKwl.find(prefix, "focal_length"); const char* distortion_units = cameraKwl.find(prefix, "distortion_units"); ossimUnitConversionTool tool; ossimUnitType unitType = OSSIM_MILLIMETERS; if(distortion_units) { unitType = (ossimUnitType)ossimUnitTypeLut::instance()->getEntryNumber(distortion_units); if(unitType == OSSIM_UNIT_UNKNOWN) { unitType = OSSIM_MILLIMETERS; } } if(image_size) { std::vector splitString; ossimString tempString(image_size); tempString = tempString.trim(); tempString.split(splitString, " "); double w=1, h=1; if(splitString.size() == 2) { w = splitString[0].toDouble(); h = splitString[1].toDouble(); } theImageClipRect = ossimDrect(0,0,w-1,h-1); theRefImgPt = ossimDpt(w/2.0, h/2.0); theImageSize = ossimDpt(w, h); } if(sensor) { theSensorID = sensor; } if(principal_point) { std::vector splitString; ossimString tempString(principal_point); tempString = tempString.trim(); tempString.split(splitString, " "); if(splitString.size() == 2) { thePrincipalPoint.x = splitString[0].toDouble(); thePrincipalPoint.y = splitString[1].toDouble(); } } if(pixel_size) { std::vector splitString; ossimString tempString(pixel_size); tempString = tempString.trim(); tempString.split(splitString, " "); if(splitString.size() == 1) { thePixelSize.x = splitString[0].toDouble(); thePixelSize.y = thePixelSize.x; } else if(splitString.size() == 2) { thePixelSize.x = splitString[0].toDouble(); thePixelSize.y = splitString[1].toDouble(); } } if(focal_length) { theFocalLength = ossimString(focal_length).toDouble(); } cameraKwl.trimAllValues(); ossimString regExpression = ossimString("^(") + "d[0-9]+)"; vector keys; cameraKwl.getSubstringKeyList( keys, regExpression ); long numberOfDistortions = (long)keys.size(); int offset = (int)ossimString("d").size(); ossim_uint32 idx = 0; std::vector numberList(numberOfDistortions); for(idx = 0; idx < numberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); numberList[idx] = numberStr.toInt(); } std::sort(numberList.begin(), numberList.end()); double distance=0.0, distortion=0.0; for(idx = 0; idx < numberList.size(); ++idx) { ossimString value = cameraKwl.find(ossimString("d")+ossimString::toString(numberList[idx])); if(!value.empty()) { std::istringstream inStr(value.c_str()); inStr >> distance; ossim::skipws(inStr); inStr >> distortion; #if 0 std::vector splitString; ossimString tempString(value); tempString = tempString.trim(); tempString.split(splitString, " "); std::cout << splitString.size() << std::endl; if(splitString.size() >= 2) { distance = splitString[0].toDouble(); distortion = splitString[1].toDouble(); } #endif tool.setValue(distortion, unitType); lensKwl.add(ossimString("distance") + ossimString::toString(idx), distance, true); lensKwl.add(ossimString("distortion") + ossimString::toString(idx), tool.getMillimeters(), true); } lensKwl.add("convergence_threshold", .00001, true); if(pixel_size) { lensKwl.add("dxdy", ossimString::toString(thePixelSize.x) + " " +ossimString::toString(thePixelSize.y), true); } else { lensKwl.add("dxdy", ".009 .009", true); } } if(theLensDistortion.valid()) { theLensDistortion->loadState(lensKwl,""); } } else { if(principal_point) { std::vector splitString; ossimString tempString(principal_point); tempString = tempString.trim(); tempString.split(splitString, " "); if(splitString.size() >= 2) { thePrincipalPoint.x = splitString[0].toDouble(); thePrincipalPoint.y = splitString[1].toDouble(); } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No principal_point found" << std::endl; return false; } } if(pixel_size) { std::vector splitString; ossimString tempString(pixel_size); tempString = tempString.trim(); tempString.split(splitString, " "); if(splitString.size() == 1) { thePixelSize.x = splitString[0].toDouble(); thePixelSize.y = thePixelSize.x; } else if(splitString.size() == 2) { thePixelSize.x = splitString[0].toDouble(); thePixelSize.y = splitString[1].toDouble(); } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No pixel size found" << std::endl; return false; } } if(focal_length) { theFocalLength = ossimString(focal_length).toDouble(); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No focal length found" << std::endl; return false; } } if(theLensDistortion.valid()) { ossimString lensPrefix = ossimString(prefix)+"distortion."; theLensDistortion->loadState(kwl, lensPrefix.c_str()); } } theRefGndPt = thePlatformPosition; updateModel(); lineSampleToWorld(theRefImgPt, theRefGndPt); if(compute_gsd_flag) { if(ossimString(compute_gsd_flag).toBool()) { ossimGpt right; ossimGpt top; lineSampleToWorld(theRefImgPt + ossimDpt(1.0, 0.0), right); lineSampleToWorld(theRefImgPt + ossimDpt(1.0, 0.0), top); ossimEcefVector horizontal = ossimEcefPoint(theRefGndPt)-ossimEcefPoint(right); ossimEcefVector vertical = ossimEcefPoint(theRefGndPt)-ossimEcefPoint(top); theGSD.x = horizontal.length(); theGSD.y = vertical.length(); theMeanGSD = (theGSD.x+theGSD.y)*.5; } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "theOmega: " << theOmega << std::endl << "thePhi: " << thePhi << std::endl << "theKappa: " << theKappa << std::endl; std::cout << "platform position: " << thePlatformPosition << std::endl; std::cout << "platform position ECF: " << theEcefPlatformPosition << std::endl; std::cout << "ossimApplanixModel::loadState: ......... leaving" << std::endl; } return true; } bool ossimApplanixUtmModel::setupOptimizer(const ossimString& init_file) { ossimKeywordlist kwl; kwl.addFile(init_file.c_str()); return loadState(kwl); } ossim-Miami-2.9.1/src/projection/ossimAzimEquDistProjection.cpp000066400000000000000000000417211352751253100246760ustar00rootroot00000000000000//******************************************************************* // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Utm projection code. //******************************************************************* // $Id: ossimAzimEquDistProjection.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include #define PI_OVER_2 ( M_PI / 2.0) #define ONE (1.0 * M_PI / 180.0) /* 1 degree in radians */ #define AZEQ_NO_ERROR 0x0000 #define AZEQ_LAT_ERROR 0x0001 #define AZEQ_LON_ERROR 0x0002 #define AZEQ_EASTING_ERROR 0x0004 #define AZEQ_NORTHING_ERROR 0x0008 #define AZEQ_ORIGIN_LAT_ERROR 0x0010 #define AZEQ_CENT_MER_ERROR 0x0020 #define AZEQ_A_ERROR 0x0040 #define AZEQ_INV_F_ERROR 0x0080 #define AZEQ_PROJECTION_ERROR 0x0100 RTTI_DEF1(ossimAzimEquDistProjection,"ossimAzimEquDistProjection", ossimMapProjection) ossimAzimEquDistProjection::ossimAzimEquDistProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); } ossimAzimEquDistProjection::ossimAzimEquDistProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { setFalseEastingNorthing(falseEasting, falseNorthing); } void ossimAzimEquDistProjection::update() { Set_Azimuthal_Equidistant_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Azeq_False_Easting, Azeq_False_Northing); theFalseEastingNorthing.x = Azeq_False_Easting; theFalseEastingNorthing.y = Azeq_False_Northing; ossimMapProjection::update(); } ossimGpt ossimAzimEquDistProjection::inverse(const ossimDpt &eastingNorthing)const { double lat, lon; Convert_Azimuthal_Equidistant_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimAzimEquDistProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Azimuthal_Equidistant(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } void ossimAzimEquDistProjection::setFalseEasting(double falseEasting) { Azeq_False_Easting = falseEasting; update(); } void ossimAzimEquDistProjection::setFalseNorthing(double falseNorthing) { Azeq_False_Northing = falseNorthing; update(); } void ossimAzimEquDistProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Azeq_False_Easting = falseEasting; Azeq_False_Northing = falseNorthing; update(); } void ossimAzimEquDistProjection::setDefaults() { Azeq_False_Easting = 0.0; Azeq_False_Northing = 0.0; update(); } bool ossimAzimEquDistProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimAzimEquDistProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Must do first... bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimAzimEquDistProjection)) { Azeq_False_Easting = theFalseEastingNorthing.x; Azeq_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } long ossimAzimEquDistProjection::Set_Azimuthal_Equidistant_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing) { /* BEGIN Set_Azimuthal_Equidistant_Parameters */ /* * The function Set_Azimuthal_Equidistant_Parameters receives the ellipsoid parameters and * projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise AZEQ_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double es2, es4, es6; // double inv_f = 1 / f; double temp_Northing = 0.0; long Error_Code = AZEQ_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= AZEQ_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= AZEQ_INV_F_ERROR; // } // if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) // { /* origin latitude out of range */ // Error_Code |= AZEQ_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= AZEQ_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Azeq_a = a; Azeq_f = f; es2 = 2 * Azeq_f - Azeq_f * Azeq_f; es4 = es2 * es2; es6 = es4 * es2; /* spherical radius */ Ra = Azeq_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 / 3024.0); Azeq_Origin_Lat = Origin_Latitude; Sin_Azeq_Origin_Lat = sin(Azeq_Origin_Lat); Cos_Azeq_Origin_Lat = cos(Azeq_Origin_Lat); abs_Azeq_Origin_Lat = fabs(Azeq_Origin_Lat); // if (Central_Meridian > M_PI) // Central_Meridian -= TWO_PI; Azeq_Origin_Long = Central_Meridian; Azeq_False_Northing = False_Northing; Azeq_False_Easting = False_Easting; if (fabs(abs_Azeq_Origin_Lat - PI_OVER_2) < 1.0e-10) { Azeq_Delta_Northing = 20015110.0; Azeq_Delta_Easting = 20015110.0; } else if (abs_Azeq_Origin_Lat >= 1.0e-10) { if (Azeq_Origin_Long > 0.0) { Convert_Geodetic_To_Azimuthal_Equidistant(-Azeq_Origin_Lat, (Azeq_Origin_Long - M_PI - ONE), &Azeq_Delta_Easting, &temp_Northing); } else { Convert_Geodetic_To_Azimuthal_Equidistant(-Azeq_Origin_Lat, (Azeq_Origin_Long + M_PI - ONE), &Azeq_Delta_Easting, &temp_Northing); } Azeq_Delta_Northing = 19903915.0; } else { Azeq_Delta_Northing = 19903915.0; Azeq_Delta_Easting = 19903915.0; } } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Azimuthal_Equidistant_Parameters */ void ossimAzimEquDistProjection::Get_Azimuthal_Equidistant_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Azimuthal_Equidistant_Parameters */ /* * The function Get_Azimuthal_Equidistant_Parameters returns the current ellipsoid * parameters and Azimuthal Equidistant projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Azeq_a; *f = Azeq_f; *Origin_Latitude = Azeq_Origin_Lat; *Central_Meridian = Azeq_Origin_Long; *False_Easting = Azeq_False_Easting; *False_Northing = Azeq_False_Northing; return; } /* End Get_Azimuthal_Equidistant_Parameters */ long ossimAzimEquDistProjection::Convert_Geodetic_To_Azimuthal_Equidistant (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Azimuthal_Equidistant */ /* * The function Convert_Geodetic_To_Azimuthal_Equidistant converts geodetic (latitude and * longitude) coordinates to Azimuthal Equidistant projection (easting and northing) * coordinates, according to the current ellipsoid and Azimuthal Equidistant projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise AZEQ_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double dlam; /* Longitude - Central Meridan */ double k_prime; /* scale factor */ double c; /* angular distance from center */ double slat = sin(Latitude); double clat = cos(Latitude); double cos_c; double sin_dlam, cos_dlam; double Ra_kprime; double Ra_PI_OVER_2_Lat; long Error_Code = AZEQ_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= AZEQ_LAT_ERROR; // } // if ((Longitude < -M_PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= AZEQ_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Azeq_Origin_Long; if (dlam > M_PI) { dlam -= TWO_PI; } if (dlam < -M_PI) { dlam += TWO_PI; } sin_dlam = sin(dlam); cos_dlam = cos(dlam); if (fabs(abs_Azeq_Origin_Lat - PI_OVER_2) < 1.0e-10) { if (Azeq_Origin_Lat >= 0.0) { Ra_PI_OVER_2_Lat = Ra * (PI_OVER_2 - Latitude); *Easting = Ra_PI_OVER_2_Lat * sin_dlam + Azeq_False_Easting; *Northing = -1.0 * (Ra_PI_OVER_2_Lat * cos_dlam) + Azeq_False_Northing; } else { Ra_PI_OVER_2_Lat = Ra * (PI_OVER_2 + Latitude); *Easting = Ra_PI_OVER_2_Lat * sin_dlam + Azeq_False_Easting; *Northing = Ra_PI_OVER_2_Lat * cos_dlam + Azeq_False_Northing; } } else if (abs_Azeq_Origin_Lat <= 1.0e-10) { cos_c = clat * cos_dlam; if (fabs(fabs(cos_c) - 1.0) < 1.0e-14) { if (cos_c >= 0.0) { *Easting = Azeq_False_Easting; *Northing = Azeq_False_Northing; } else { /* if cos_c == -1 */ Error_Code |= AZEQ_PROJECTION_ERROR; } } else { c = acos(cos_c); k_prime = c / sin(c); Ra_kprime = Ra * k_prime; *Easting = Ra_kprime * clat * sin_dlam + Azeq_False_Easting; *Northing = Ra_kprime * slat + Azeq_False_Northing; } } else { cos_c = (Sin_Azeq_Origin_Lat * slat) + (Cos_Azeq_Origin_Lat * clat * cos_dlam); if (fabs(fabs(cos_c) - 1.0) < 1.0e-14) { if (cos_c >= 0.0) { *Easting = Azeq_False_Easting; *Northing = Azeq_False_Northing; } else { /* if cos_c == -1 */ Error_Code |= AZEQ_PROJECTION_ERROR; } } else { c = acos(cos_c); k_prime = c / sin(c); Ra_kprime = Ra * k_prime; *Easting = Ra_kprime * clat * sin_dlam + Azeq_False_Easting; *Northing = Ra_kprime * (Cos_Azeq_Origin_Lat * slat - Sin_Azeq_Origin_Lat * clat * cos_dlam) + Azeq_False_Northing; } } } return (Error_Code); } /* End Convert_Geodetic_To_Azimuthal_Equidistant */ long ossimAzimEquDistProjection::Convert_Azimuthal_Equidistant_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Azimuthal_Equidistant_To_Geodetic */ /* * The function Convert_Azimuthal_Equidistant_To_Geodetic converts Azimuthal_Equidistant projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Azimuthal_Equidistant projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise AZEQ_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx, dy; double rho; /* height above ellipsoid */ double c; /* angular distance from center */ double sin_c, cos_c, dy_sinc; long Error_Code = AZEQ_NO_ERROR; // if ((Easting < (Azeq_False_Easting - Azeq_Delta_Easting)) // || (Easting > (Azeq_False_Easting + Azeq_Delta_Easting))) // { /* Easting out of range */ // Error_Code |= AZEQ_EASTING_ERROR; // } // if ((Northing < (Azeq_False_Northing - Azeq_Delta_Northing)) // || (Northing > (Azeq_False_Northing + Azeq_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= AZEQ_NORTHING_ERROR; // } if (!Error_Code) { dy = Northing - Azeq_False_Northing; dx = Easting - Azeq_False_Easting; rho = sqrt(dx * dx + dy * dy); if (fabs(rho) <= 1.0e-10) { *Latitude = Azeq_Origin_Lat; *Longitude = Azeq_Origin_Long; } else { c = rho / Ra; sin_c = sin(c); cos_c = cos(c); dy_sinc = dy * sin_c; *Latitude = asin((cos_c * Sin_Azeq_Origin_Lat) + ((dy_sinc * Cos_Azeq_Origin_Lat) / rho)); if (fabs(abs_Azeq_Origin_Lat - PI_OVER_2) < 1.0e-10) { if (Azeq_Origin_Lat >= 0.0) *Longitude = Azeq_Origin_Long + atan2(dx, -dy); else *Longitude = Azeq_Origin_Long + atan2(dx, dy); } else *Longitude = Azeq_Origin_Long + atan2((dx * sin_c), ((rho * Cos_Azeq_Origin_Lat * cos_c) - (dy_sinc * Sin_Azeq_Origin_Lat))); } if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ *Latitude = PI_OVER_2; else if (*Latitude < -PI_OVER_2) *Latitude = -PI_OVER_2; // if (*Longitude > M_PI) // *Longitude -= TWO_PI; // if (*Longitude < -M_PI) // *Longitude += TWO_PI; if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ *Longitude = M_PI; else if (*Longitude < -M_PI) *Longitude = -M_PI; } return (Error_Code); } /* End Convert_Azimuthal_Equidistant_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimBilinearProjection.cpp000066400000000000000000000351371352751253100242300ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimBilinearProjection.cpp 19682 2011-05-31 14:21:20Z dburken $ #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimBilinearProjection.cpp 19682 2011-05-31 14:21:20Z dburken $"; #endif // static const ossim_uint32 MINIMUM_NMBER_OF_POINTS = 4; static ossimTrace traceDebug("ossimBilinearProjection:debug"); RTTI_DEF2(ossimBilinearProjection, "ossimBilinearProjection", ossimProjection, ossimOptimizableProjection); ossimBilinearProjection::ossimBilinearProjection() : ossimOptimizableProjection(), theLineSamplePt(0), theGeographicPt(0), theLatFit(), theLonFit() { #ifdef OSSIM_ID_ENABLED if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << OSSIM_ID << endl; #endif } ossimBilinearProjection::ossimBilinearProjection(const ossimBilinearProjection& rhs) : ossimOptimizableProjection(rhs), theLineSamplePt(rhs.theLineSamplePt), theGeographicPt(rhs.theGeographicPt), theLonFit(rhs.theLonFit) { } ossimBilinearProjection::ossimBilinearProjection(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll, const ossimGpt& ulg, const ossimGpt& urg, const ossimGpt& lrg, const ossimGpt& llg) : ossimOptimizableProjection(), theLineSamplePt(4), theGeographicPt(4), theLatFit(), theLonFit() { theLineSamplePt[0] = ul; theLineSamplePt[1] = ur; theLineSamplePt[2] = lr; theLineSamplePt[3] = ll; theGeographicPt[0] = ulg; theGeographicPt[1] = urg; theGeographicPt[2] = lrg; theGeographicPt[3] = llg; initializeBilinear(); } ossimBilinearProjection::~ossimBilinearProjection() { } ossimObject *ossimBilinearProjection::dup()const { return new ossimBilinearProjection(*this); } ossimGpt ossimBilinearProjection::origin()const { ossimGpt result; result.makeNan(); if ( (theGeographicPt.size() == 0) || gPtsHaveNan() ) { return result; } double lat = 0.0; double lon = 0.0; const double SIZE = theGeographicPt.size(); vector::const_iterator i = theGeographicPt.begin(); while (i != theGeographicPt.end()) { lat += (*i).latd(); lon += (*i).lond(); ++i; } result.latd(lat/SIZE); result.lond(lon/SIZE); result.height(0.0); result.datum(theGeographicPt[0].datum()); return result; } void ossimBilinearProjection::worldToLineSample(const ossimGpt& worldPoint, ossimDpt& lineSampPt) const { if(!theInverseSupportedFlag) { ossimProjection::worldToLineSample(worldPoint, lineSampPt); } else { lineSampPt.makeNan(); if (!theInterpolationPointsHaveNanFlag) { lineSampPt.x = theXFit.lsFitValue(worldPoint.lond(), worldPoint.latd()); lineSampPt.y = theYFit.lsFitValue(worldPoint.lond(), worldPoint.latd()); } } } void ossimBilinearProjection::lineSampleToWorld(const ossimDpt& lineSampPt, ossimGpt& worldPt) const { lineSampleHeightToWorld(lineSampPt, ossim::nan(), worldPt); } void ossimBilinearProjection::lineSampleHeightToWorld( const ossimDpt& lineSampPt, const double& heightAboveEllipsoid, ossimGpt& worldPt) const { worldPt.makeNan(); if (theInterpolationPointsHaveNanFlag) { return; } worldPt.lat = theLatFit.lsFitValue(lineSampPt.x, lineSampPt.y); worldPt.lon = theLonFit.lsFitValue(lineSampPt.x, lineSampPt.y); if (ossim::isnan(heightAboveEllipsoid) == false) { worldPt.hgt = heightAboveEllipsoid; } if (theGeographicPt.size()) { worldPt.datum(theGeographicPt[0].datum()); } } bool ossimBilinearProjection::saveState(ossimKeywordlist& kwl, const char* prefix)const { if (theLineSamplePt.size() != theGeographicPt.size()) { // Should never happen. return false; } ossimProjection::saveState(kwl, prefix); ossimString imagePoints; ossimString groundPoints; ossim::toStringList(imagePoints, theLineSamplePt); ossim::toStringList(groundPoints, theGeographicPt); kwl.add(prefix, "image_points", imagePoints, true); kwl.add(prefix, "ground_points", groundPoints, true); #if 0 const ossim_uint32 SIZE = (ossim_uint32)theLineSamplePt.size(); for (ossim_uint32 i = 0; i < SIZE; ++i) { ossimString index_string = ossimString::toString(i); // Add the geographic point. ossimString kw = "gpt"; kw += index_string; ostringstream os1; os1 << theGeographicPt[i]; kwl.add(prefix, kw, os1.str().c_str()); // Add the sample line.. kw = "dpt"; kw += index_string; ostringstream os2; os2 << theLineSamplePt[i]; kwl.add(prefix, kw, os2.str().c_str()); } #endif return true; } bool ossimBilinearProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Load the base class. ossimProjection::loadState(kwl, prefix); // Start with clear lists. theLineSamplePt.clear(); theGeographicPt.clear(); ossimString imagePoints = kwl.find(prefix, "image_points"); ossimString groundPoints = kwl.find(prefix, "ground_points"); if(!imagePoints.empty()&&!groundPoints.empty()) { ossim::toVector(theLineSamplePt, imagePoints); ossim::toVector(theGeographicPt, groundPoints); } else { //--- // Get the number of points. // If 0 or gpt size not equal to dpt size get out. //--- const ossim_uint32 SIZE = kwl.numberOf(prefix, "gpt"); if ( (SIZE == 0) || (SIZE != kwl.numberOf(prefix, "dpt")) ) { return false; } for (ossim_uint32 i = 0; i < SIZE; ++i) { const char* lookup; ossimString index_string = ossimString::toString(i); // Get the geographic point. ossimString kw = "gpt"; kw += index_string; lookup = kwl.find(prefix, kw); if (lookup) { ossimGpt gp; gp.toPoint(std::string(lookup)); //--- // Allow for "nan" height values by substituting with 0.0 so the // hasNans() will work. "nan"s will get placed in the point if the // user doesn't have the elevation manager preferences set up // correctly. //--- if (gp.isHgtNan()) { gp.height(0.0); } theGeographicPt.push_back(gp); } // Get the line sample point. kw = "dpt"; kw += index_string; lookup = kwl.find(prefix, kw); if (lookup) { ossimDpt dp; dp.toPoint(std::string(lookup)); theLineSamplePt.push_back(dp); } } } if (traceDebug()) { print(ossimNotify(ossimNotifyLevel_DEBUG)); } initializeBilinear(); return true; } bool ossimBilinearProjection::operator==(const ossimProjection& /* projection */) const { return false; } ossimDpt ossimBilinearProjection::getMetersPerPixel() const { ossimGpt centerG; ossimGpt rightG; ossimGpt topG; ossimDpt midPoint = midLineSamplePt(); lineSampleToWorld(midPoint, centerG); lineSampleToWorld(midPoint+ossimDpt(1,0), rightG); lineSampleToWorld(midPoint+ossimDpt(0,-1), topG); ossimEcefPoint centerP = centerG; ossimEcefPoint rightP = rightG; ossimEcefPoint topP = topG; ossimEcefVector horizontal = rightP-centerP; ossimEcefVector vertical = topP-centerP; ossimDpt result(horizontal.magnitude(), vertical.magnitude()); result.x = (result.x + result.y)/2.0; result.y = result.x; return result; } void ossimBilinearProjection::initializeBilinear() { theInterpolationPointsHaveNanFlag = dPtsHaveNan()||gPtsHaveNan(); theInverseSupportedFlag = true; if(!theInterpolationPointsHaveNanFlag) { theLatFit.clear(); theLonFit.clear(); theXFit.clear(); theYFit.clear(); const ossim_uint32 SIZE = (ossim_uint32)theLineSamplePt.size(); if (SIZE != theGeographicPt.size()) { return; } for (ossim_uint32 i = 0; i < SIZE; ++i) { theLatFit.addSample(theLineSamplePt[i].x, theLineSamplePt[i].y, theGeographicPt[i].latd()); theLonFit.addSample(theLineSamplePt[i].x, theLineSamplePt[i].y, theGeographicPt[i].lond()); theXFit.addSample(theGeographicPt[i].lond(), theGeographicPt[i].latd(), theLineSamplePt[i].x); theYFit.addSample(theGeographicPt[i].lond(), theGeographicPt[i].latd(), theLineSamplePt[i].y); } theLatFit.solveLS(); theLonFit.solveLS(); theXFit.solveLS(); theYFit.solveLS(); ossimDpt errorResult; getRoundTripError(theLineSamplePt[0], errorResult); if(errorResult.length() > 1) { theInverseSupportedFlag = false; } } } bool ossimBilinearProjection::dPtsHaveNan() const { if (theLineSamplePt.size() == 0) { return false; } vector::const_iterator i = theLineSamplePt.begin(); while (i != theLineSamplePt.end()) { if ( (*i).hasNans() ) { return true; } ++i; } return false; } bool ossimBilinearProjection::gPtsHaveNan() const { //--- // NOTE: This method ignores nans in the height field. //--- if (theGeographicPt.size() == 0) { return false; } vector::const_iterator i = theGeographicPt.begin(); while (i != theGeographicPt.end()) { if ( (*i).isLatNan() || (*i).isLonNan() ) { return true; } ++i; } return false; } ossimDpt ossimBilinearProjection::midLineSamplePt() const { ossimDpt result; if ( (theLineSamplePt.size() == 0) || dPtsHaveNan()) { result.makeNan(); return result; } double x = 0.0; double y = 0.0; vector::const_iterator i = theLineSamplePt.begin(); while (i != theLineSamplePt.end()) { x += (*i).x; y += (*i).y; ++i; } const double SIZE = theLineSamplePt.size(); result.x = x / SIZE; result.y = y / SIZE; return result; } std::ostream& ossimBilinearProjection::print(std::ostream& out) const { ossimNotify(ossimNotifyLevel_INFO) << "ossimBilinearProjection::print\n"; ossim_uint32 index = 0; vector::const_iterator di = theLineSamplePt.begin(); while (di != theLineSamplePt.end()) { ossimNotify(ossimNotifyLevel_INFO) << "theLineSamplePt[" << index << "]: " << (*di) << endl; ++di; ++index; } index = 0; vector::const_iterator gi = theGeographicPt.begin(); while (gi != theGeographicPt.end()) { ossimNotify(ossimNotifyLevel_INFO) << "theGeographicPt[" << index << "]: " << (*gi) << endl; ++gi; ++index; } return ossimProjection::print(out); } ossim_float64 ossimBilinearProjection::setTiePoints(const std::vector& lsPt, const std::vector& geoPt) { if (lsPt.size() != geoPt.size()) { ossimNotify(ossimNotifyLevel_INFO) << "mismatch in image and ground point number" << endl; return -1.0; } if (lsPt.size() < 4) { ossimNotify(ossimNotifyLevel_INFO) << "not enough tie points - need at least 4" << endl; return -1.0; } theLineSamplePt = lsPt; theGeographicPt = geoPt; //compute fit initializeBilinear(); //compute variance ossim_float64 sumerr2=0.0; vector::const_iterator i; vector::const_iterator j; ossimGpt gres; for(i=theLineSamplePt.begin() , j=theGeographicPt.begin() ; i != theLineSamplePt.end() ; ++i, ++j ) { gres.lat = theLatFit.lsFitValue(i->x, i->y); gres.lon = theLonFit.lsFitValue(i->x, i->y); gres.hgt = j->hgt; //same height as ground point sumerr2 += ( ossimEcefPoint(gres) - ossimEcefPoint(*j) ).norm2(); //add squared error in meters } return sumerr2 / theLineSamplePt.size(); //variance in meter^2 } bool ossimBilinearProjection::setupOptimizer(const ossimString& /* setup */) { return false; } ossim_uint32 ossimBilinearProjection::degreesOfFreedom()const { return 2*4; //height not used } double ossimBilinearProjection::optimizeFit(const ossimTieGptSet& tieSet, double* /* targetVariance */) { //NOTE : IGNORE targetVariance std::vector imagePoints; std::vector groundPoints; tieSet.getSlaveMasterPoints(imagePoints, groundPoints); return setTiePoints(imagePoints, groundPoints); //variance in meters } //************************************************************************************************** //! Access method for tie point information //************************************************************************************************** void ossimBilinearProjection::getTiePoints(std::vector& lsPt, std::vector& geoPt) const { lsPt = theLineSamplePt; geoPt = theGeographicPt; } ossim-Miami-2.9.1/src/projection/ossimBngProjection.cpp000066400000000000000000000525521352751253100232110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimBngProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include #include #include #include #include #include #define BNG_NO_ERROR 0x0000 #define BNG_LAT_ERROR 0x0001 #define BNG_LON_ERROR 0x0002 #define BNG_EASTING_ERROR 0x0004 #define BNG_NORTHING_ERROR 0x0008 #define BNG_INVALID_AREA_ERROR 0x0010 #define BNG_STRING_ERROR 0x0020 #define BNG_ELLIPSOID_ERROR 0x0040 #define PI_OVER_2 (M_PI / 2.0e0) /* PI over 2 */ #define MAX_LAT (61.5 * M_PI / 180.0) /* 61.5 degrees */ #define MIN_LAT (49.5 * M_PI / 180.0) /* 49.5 degrees */ #define MAX_LON (3.5 * M_PI / 180.0) /* 3.5 degrees */ #define MIN_LON (-10.0 * M_PI / 180.0) /* -10 degrees */ #define BNG500GRID "STNOHJ" /* 500,000 unit square identifications */ #define BNG100GRID "VWXYZQRSTULMNOPFGHJKABCDE" /* 100,000 unit square identifications */ static double BNG_Max_Easting = 759961.0; static double BNG_Max_Northing = 1257875.0; static double BNG_Min_Easting = -133134.0; static double BNG_Min_Northing = -14829.0; static char BNG_Letters[3] = "SV"; static double BNG_Easting = 0.0; static double BNG_Northing = 0.0; static const char* Airy = "AA"; static char BNG_Ellipsoid_Code[3] = "AA"; RTTI_DEF1(ossimBngProjection, "ossimBngProjection", ossimMapProjection); ossimBngProjection::ossimBngProjection() :ossimMapProjection(*ossimEllipsoidFactory::instance()->create("AA"), ossimGpt(49.0, -2.0, ossim::nan(), ossimDatumFactory::instance()->create(ossimString("OGB-M")))) { string_Broken = 0; theDatum = ossimDatumFactory::instance()->create(ossimString("OGB-M")); update(); } ossimGpt ossimBngProjection::inverse(const ossimDpt &eastingNorthing)const { char s[100]; double lat; double lon; string_Broken = 0; Set_Transverse_Mercator_Parameters(BNG_a, BNG_f, BNG_Origin_Lat, BNG_Origin_Long, BNG_False_Easting, BNG_False_Northing, BNG_Scale_Factor); Convert_Transverse_Mercator_To_BNG(eastingNorthing.x, eastingNorthing.y, 5, s); Convert_BNG_To_Geodetic(s, &lat, &lon); ossimGpt result(49, -2, ossim::nan(),theDatum); result.latr(lat); result.lonr(lon); return result; } ossimDpt ossimBngProjection::forward(const ossimGpt &latLon)const { char BNG[100]; string_Broken = 0; Set_Transverse_Mercator_Parameters(BNG_a, BNG_f, BNG_Origin_Lat, BNG_Origin_Long, BNG_False_Easting, BNG_False_Northing, BNG_Scale_Factor); Convert_Geodetic_To_BNG (latLon.latr(), latLon.lonr(), 5, BNG); ossimDpt en; Convert_BNG_To_Transverse_Mercator(BNG, &en.x, &en.y); return en; } void ossimBngProjection::update() { BNG_Origin_Lat = (49.0 * M_PI / 180.0); BNG_Origin_Long = (-2.0 * M_PI / 180.0); BNG_False_Northing = -100000.0; BNG_False_Easting = 400000.0; BNG_Scale_Factor = .9996012717; BNG_a = 6377563.396; BNG_f = 1 / 299.324964600; // ossimString code = theDatum->code(); // if(code.upcase().contains("OGB")) // { theOrigin = ossimGpt(49.0, -2.0, ossim::nan(), theDatum); theFalseEastingNorthing.x = BNG_False_Easting; theFalseEastingNorthing.y = BNG_False_Northing; // } // else // { // theOrigin = ossimGpt(49.0, -2.0, ossim::nan(), ossimDatumFactory::instance()->create("OGB-7")); // } ossimMapProjection::update(); } /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ bool ossimBngProjection::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::TYPE_KW, getClassName(), true); kwl.add(prefix, ossimKeywordNames::SCALE_FACTOR_KW, BNG_Scale_Factor, true); return ossimMapProjection::saveState(kwl, prefix); } /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ bool ossimBngProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimMapProjection::loadState(kwl, prefix); update(); return true; } long ossimBngProjection::Find_Index (char letter, const char* letter_Array, long *index)const { /* * The function Find_Index searches for a given letter in an array. * It returns the index of the letter in the array if the letter is found. * If the letter is not found, an error code is returned, otherwise * BNG_NO_ERROR is returned. * * letter : Letter being searched for * letter_Array : Array being searched * index : Index of letter in array */ ossim_uint32 i = 0; ossim_uint32 not_Found = 1; ossim_uint32 length = (ossim_uint32)strlen(letter_Array); ossim_uint32 Error_Code = BNG_NO_ERROR; while ((i < length) && (not_Found)) { if (letter == letter_Array[i]) { *index = i; not_Found = 0; } i++; } if (not_Found) Error_Code = BNG_STRING_ERROR; return Error_Code; } long ossimBngProjection::Round_BNG (double value)const /* Round value to nearest integer, using standard engineering rule */ { /* Round_BNG */ double ivalue; long ival; double fraction = modf (value, &ivalue); ival = (long)(ivalue); if ((fraction > 0.5) || ((fraction == 0.5) && (ival%2 == 1))) ival++; return (ival); } long ossimBngProjection::Make_BNG_String (char ltrnum[4], long Easting, long Northing, char* BNG, long Precision)const { /* Make_BNG_String */ /* Construct a BNG string from its component parts */ double divisor; long east; long north; long i; long j; double unitInterval; long error_code = BNG_NO_ERROR; i = 0; for (j = 0; j < 3; j++) { BNG[i++] = ltrnum[j]; } divisor = pow ((double)10.0,(double) (5 - Precision)); unitInterval = pow ((double)10.0, (double)Precision); east = Round_BNG (Easting/divisor); if (east == unitInterval) east -= 1; if ((Precision == 0) && (east == 1)) east = 0; i += sprintf (BNG + i, "%*.*ld",(int) Precision,(int) Precision, east); north = Round_BNG (Northing/divisor); if (north == unitInterval) north -= 1; if ((Precision == 0) && (north == 1)) north = 0; i += sprintf (BNG + i, "%*.*ld",(int) Precision,(int) Precision, north); return (error_code); } /* Make_BNG_String */ long ossimBngProjection::Break_BNG_String (char* BNG, char Letters[3], double* Easting, double* Northing, long* Precision)const /* Break down a BNG string into its component parts */ { /* Break_BNG_String */ long i = 0; long j; long num_digits = 0; long num_letters; long temp_error = 0; long length = (long)strlen(BNG); long error_code = BNG_NO_ERROR; string_Broken = 1; while (BNG[i] == ' ') i++; /* skip any leading blanks */ j = i; while (isalpha(BNG[i])) i++; num_letters = i - j; if (num_letters == 2) { /* get letters */ Letters[0] = (char)toupper(BNG[j]); Letters[1] = (char)toupper(BNG[j+1]); Letters[2] = 0; } else error_code |= BNG_STRING_ERROR; if (!error_code) { error_code |= Check_Out_Of_Area(Letters[0], Letters[1]); while (BNG[i] == ' ') i++; j = i; if (BNG[length-1] == ' ') length --; while ((i < length) && (!temp_error)) { if (isdigit(BNG[i])) i++; else { temp_error = BNG_STRING_ERROR; } } if (temp_error) error_code |= temp_error; if (!error_code) { num_digits = i - j; if ((num_digits <= 10) && (num_digits%2 == 0)) { long n; char east_string[6]; char north_string[6]; long east; long north; double multiplier; /* get easting & northing */ n = num_digits / 2; *Precision = n; if (n > 0) { strncpy (east_string, BNG+j, n); east_string[n] = 0; sscanf (east_string, "%ld", &east); strncpy (north_string, BNG+j+n, n); north_string[n] = 0; sscanf (north_string, "%ld", &north); multiplier = pow ((double)10.0,(double)( 5 - n)); *Easting = east * multiplier; *Northing = north * multiplier; } else { *Easting = 0.0; *Northing = 0.0; } } else error_code |= BNG_STRING_ERROR; } } return (error_code); } /* Break_BNG_String */ long ossimBngProjection::Check_Out_Of_Area(char BNG500, char BNG100)const { /* BEGIN Check_Out_Of_Area */ /* * The function Check_Out_Of_Area checks if the 500,000 and * 100,000 unit square identifications are within the valid area. If * they are not, an error code is returned, otherwise BNG_NO_ERROR * is returned. * * BNG500 : 500,000 square unit identification * BNG100 : 100,000 square unit identification */ long Error_Code = BNG_NO_ERROR; switch (BNG500) { case 'S': switch (BNG100) { case 'A': case 'F': case 'L': Error_Code |= BNG_INVALID_AREA_ERROR; break; default: break; } break; case 'N': switch (BNG100) { case 'V': Error_Code |= BNG_INVALID_AREA_ERROR; break; default: break; } break; case 'H': if (BNG100 < 'L') Error_Code |= BNG_INVALID_AREA_ERROR; break; case 'T': switch (BNG100) { case 'D': case 'E': case 'J': case 'K': case 'O': case 'P': case 'T': case 'U': case 'X': case 'Y': case 'Z': Error_Code |= BNG_INVALID_AREA_ERROR; break; default: break; } break; case 'O': switch (BNG100) { case 'C': case 'D': case 'E': case 'J': case 'K': case 'O': case 'P': case 'T': case 'U': case 'Y': case 'Z': Error_Code |= BNG_INVALID_AREA_ERROR; break; default: break; } break; case 'J': switch (BNG100) { case 'L': case 'M': case 'Q': case 'R': case 'V': case 'W': Error_Code = BNG_NO_ERROR; break; default: Error_Code |= BNG_INVALID_AREA_ERROR; break; } break; default: Error_Code |= BNG_INVALID_AREA_ERROR; break; } return Error_Code; } /* END OF Check_Out_Of_Area */ long ossimBngProjection::Set_BNG_Parameters(char *Ellipsoid_Code) { /* BEGIN Set_BNG_Parameters */ /* * The function Set_BNG_Parameters receives the ellipsoid code and sets * the corresponding state variables. If any errors occur, the error code(s) * are returned by the function, otherwise BNG_NO_ERROR is returned. * * Ellipsoid_Code : 2-letter code for ellipsoid (input) */ long Error_Code = BNG_NO_ERROR; if (strcmp(Ellipsoid_Code, Airy) != 0) { /* Ellipsoid must be Airy */ Error_Code |= BNG_ELLIPSOID_ERROR; } if (!Error_Code) { /* no errors */ strcpy(BNG_Ellipsoid_Code, Ellipsoid_Code); string_Broken = 0; Set_Transverse_Mercator_Parameters(BNG_a, BNG_f, BNG_Origin_Lat, BNG_Origin_Long, BNG_False_Easting, BNG_False_Northing, BNG_Scale_Factor); } return (Error_Code); } /* END of Set_BNG_Parameters */ void ossimBngProjection::Get_BNG_Parameters(char *Ellipsoid_Code) { /* BEGIN Get_BNG_Parameters */ /* * The function Get_BNG_Parameters returns the current ellipsoid * code. * * Ellipsoid_Code : 2-letter code for ellipsoid (output) */ strcpy(Ellipsoid_Code, BNG_Ellipsoid_Code); return; } /* END OF Get_BNG_Parameters */ long ossimBngProjection::Convert_Geodetic_To_BNG (double Latitude, double Longitude, long Precision, char* BNG)const { /* BEGIN Convert_Geodetic_To_BNG */ /* * The function Convert_Geodetic_To_BNG converts geodetic (latitude and * longitude) coordinates to a BNG coordinate string, according to the * current ellipsoid parameters. If any errors occur, the error code(s) * are returned by the function, otherwise BNG_NO_ERROR is returned. * * Latitude : Latitude, in radians (input) * Longitude : Longitude, in radians (input) * Precision : Precision level of BNG string (input) * BNG : British National Grid coordinate string (output) * */ double TMEasting, TMNorthing; long Error_Code = BNG_NO_ERROR; if ((Latitude < MIN_LAT) || (Latitude > MAX_LAT)) { /* Latitude out of range */ Error_Code|= BNG_LAT_ERROR; } if ((Longitude < MIN_LON) || (Longitude > MAX_LON)) { /* Longitude out of range */ Error_Code|= BNG_LON_ERROR; } if (!Error_Code) { /* no errors */ Error_Code |= Convert_Geodetic_To_Transverse_Mercator(Latitude, Longitude, &TMEasting, &TMNorthing); if ((TMEasting < 0.0) && (TMEasting > -2.0)) TMEasting = 0.0; if ((TMNorthing < 0.0) && (TMNorthing > -2.0)) TMNorthing = 0.0; if ((TMEasting < BNG_Min_Easting) || (TMEasting > BNG_Max_Easting)) Error_Code |= BNG_INVALID_AREA_ERROR; if ((TMNorthing < BNG_Min_Northing) || (TMNorthing > BNG_Max_Northing)) Error_Code |= BNG_INVALID_AREA_ERROR; if (!Error_Code) Error_Code |= Convert_Transverse_Mercator_To_BNG(TMEasting, TMNorthing, Precision, BNG); } return Error_Code; } /* END OF Convert_Geodetic_To_BNG */ long ossimBngProjection::Convert_BNG_To_Geodetic (char *BNG, double *Latitude, double *Longitude)const { /* Convert_BNG_To_Geodetic */ /* * The function Convert_BNG_To_Geodetic converts a BNG coordinate string * to geodetic (latitude and longitude) coordinates, according to the current * ellipsoid parameters. If any errors occur, the error code(s) are returned * by the function, otherwise BNG_NO_ERROR is returned. * * BNG : British National Grid coordinate string (input) * Latitude : Latitude, in radians (output) * Longitude : Longitude, in radians (output) * */ double TMEasting, TMNorthing; long in_Precision; long temp_Error = 0; long Error_Code = BNG_NO_ERROR; Error_Code |= Break_BNG_String(BNG, BNG_Letters, &BNG_Easting, &BNG_Northing, &in_Precision); if(!Error_Code) { Error_Code |= Convert_BNG_To_Transverse_Mercator(BNG, &TMEasting, &TMNorthing); if ((TMEasting < BNG_Min_Easting) || (TMEasting > BNG_Max_Easting)) Error_Code |= BNG_INVALID_AREA_ERROR; if ((TMNorthing < BNG_Min_Northing) || (TMNorthing > BNG_Max_Northing)) Error_Code |= BNG_INVALID_AREA_ERROR; if(!Error_Code) { temp_Error |= Convert_Transverse_Mercator_To_Geodetic(TMEasting, TMNorthing, Latitude, Longitude); if (temp_Error & TRANMERC_EASTING_ERROR) Error_Code |= BNG_EASTING_ERROR; if (temp_Error & TRANMERC_NORTHING_ERROR) Error_Code |= BNG_NORTHING_ERROR; if ((*Latitude < MIN_LAT) || (*Latitude > MAX_LAT)) Error_Code|= BNG_INVALID_AREA_ERROR; if ((*Longitude < MIN_LON) || (*Longitude > MAX_LON)) Error_Code|= BNG_INVALID_AREA_ERROR; } } return Error_Code; } /* END OF Convert_BNG_To_Geodetic */ long ossimBngProjection::Convert_Transverse_Mercator_To_BNG(double Easting, double Northing, long Precision, char *BNG)const {/* BEGIN Convert_Transverse_Mercator_To_BNG */ /* * The function Convert_Transverse_Mercator_To_BNG converts Transverse Mercator * (easting and northing) coordinates to a BNG coordinate string, according * to the current ellipsoid parameters. If any errors occur, the error code(s) * are returned by the function, otherwise BNG_NO_ERROR is returned. * * Easting : Easting (X), in meters (input) * Northing : Northing (Y), in meters (input) * Precision : Precision level of BNG string (input) * BNG : British National Grid coordinate string (output) */ char letters[4]; long x, y; long index; long temp_Easting, temp_Northing; long Error_Code = BNG_NO_ERROR; if ((Easting < BNG_Min_Easting) || (Easting > BNG_Max_Easting)) { /* Easting out of range */ Error_Code |= BNG_EASTING_ERROR; } if ((Northing < BNG_Min_Northing) || (Northing > BNG_Max_Northing)) { /* Northing out of range */ Error_Code |= BNG_NORTHING_ERROR; } if (!Error_Code) { /* no errors */ temp_Easting = Round_BNG(Easting); temp_Northing = Round_BNG(Northing); temp_Easting += 1000000; temp_Northing += 500000; x = temp_Easting / 500000; y = temp_Northing / 500000; index = y * 5 + x; if ((index >= 0) && (index < 25)) { letters[0] = BNG100GRID[index]; temp_Easting %= 500000; temp_Northing %= 500000; x = temp_Easting / 100000; y = temp_Northing / 100000; index = y * 5 + x; if ((index >= 0) && (index < 25)) { letters[1] = BNG100GRID[index]; Error_Code |= Check_Out_Of_Area(letters[0], letters[1]); if (!Error_Code) { letters[2] = ' '; letters[3] = 0; temp_Easting %= 100000; temp_Northing %= 100000; Make_BNG_String(letters, temp_Easting, temp_Northing, BNG, Precision); } } else { long five_y = 5 * y; if ((x >= (25 - five_y)) || (x < -five_y)) Error_Code |= BNG_EASTING_ERROR; if ((five_y >= (25 - x)) || (five_y < -x)) Error_Code |= BNG_NORTHING_ERROR; } } else { long five_y = 5 * y; if ((x >= (25 - five_y)) || (x < -five_y)) Error_Code |= BNG_EASTING_ERROR; if ((five_y >= (25 - x)) || (five_y < -x)) Error_Code |= BNG_NORTHING_ERROR; } } return Error_Code; } /* END OF Convert_Transverse_Mercator_To_BNG */ long ossimBngProjection::Convert_BNG_To_Transverse_Mercator(char *BNG, double *Easting, double *Northing)const { /* Convert_BNG_To_Transverse_Mercator */ /* * The function Convert_BNG_To_Transverse_Mercator converts a BNG coordinate string * to Transverse Mercator projection (easting and northing) coordinates * according to the current ellipsoid parameters. If any errors occur, * the error code(s) are returned by the function, otherwise BNG_NO_ERROR * is returned. * * BNG : British National Grid coordinate string (input) * Easting : Easting (X), in meters (output) * Northing : Northing (Y), in meters (output) */ long northing_Offset, easting_Offset; long i = 0; long j = 0; long in_Precision; long Error_Code = BNG_NO_ERROR; if (!string_Broken) { Error_Code |= Break_BNG_String(BNG, BNG_Letters, &BNG_Easting, &BNG_Northing, &in_Precision); } if (!Error_Code) { Error_Code |= Find_Index(BNG_Letters[0], BNG500GRID, &i); if (!Error_Code) { northing_Offset = 500000 * (i / 2); easting_Offset = 500000 * (i % 2); Error_Code |= Find_Index(BNG_Letters[1], BNG100GRID, &j); if (!Error_Code) { northing_Offset += 100000 * (j / 5); easting_Offset += 100000 * (j % 5); *Easting = BNG_Easting + easting_Offset; *Northing = BNG_Northing + northing_Offset; } } } return Error_Code; } /* END OF Convert_BNG_To_Transverse_Mercator */ ossim-Miami-2.9.1/src/projection/ossimBonneProjection.cpp000066400000000000000000000437111352751253100235410ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Bonne projection code. //******************************************************************* // $Id: ossimBonneProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include RTTI_DEF1(ossimBonneProjection, "ossimBonneProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #define BONN_NO_ERROR 0x0000 #define BONN_LAT_ERROR 0x0001 #define BONN_LON_ERROR 0x0002 #define BONN_EASTING_ERROR 0x0004 #define BONN_NORTHING_ERROR 0x0008 #define BONN_ORIGIN_LAT_ERROR 0x0010 #define BONN_CENT_MER_ERROR 0x0020 #define BONN_A_ERROR 0x0040 #define BONN_B_ERROR 0x0080 #define BONN_A_LESS_B_ERROR 0x0100 #define PI_OVER_2 (M_PI / 2.0) #define BONN_m(coslat,sinlat) (coslat/sqrt(1.0 - es2*sinlat*sinlat)) #define BONN_M(c0lat,c1s2lat,c2s4lat,c3s6lat) (Bonn_a*(c0lat-c1s2lat+c2s4lat-c3s6lat)) #define COEFF_TIMES_BONN_SIN(coeff,x,latit) (coeff*(sin(x * latit))) #define FLOAT_EQ(x,v,epsilon) (((v - epsilon) < x) && (x < (v + epsilon))) ossimBonneProjection::ossimBonneProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimBonneProjection::ossimBonneProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, const double falseEasting, const double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Bonn_False_Easting = falseEasting; Bonn_False_Northing = falseNorthing; Bonn_Delta_Northing = 25000000.0; update(); } void ossimBonneProjection::update() { Set_Bonne_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Bonn_False_Easting, Bonn_False_Northing); theFalseEastingNorthing.x = Bonn_False_Easting; theFalseEastingNorthing.y = Bonn_False_Northing; ossimMapProjection::update(); } void ossimBonneProjection::setFalseEasting(double falseEasting) { Bonn_False_Easting = falseEasting; update(); } void ossimBonneProjection::setFalseNorthing(double falseNorthing) { Bonn_False_Northing = falseNorthing; update(); } void ossimBonneProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Bonn_False_Easting = falseEasting; Bonn_False_Northing = falseNorthing; update(); } void ossimBonneProjection::setDefaults() { Bonn_False_Easting = 0.0; Bonn_False_Northing = 0.0; Bonn_Delta_Northing = 25000000.0; if(theOrigin.latd() == 0.0) { // we can't have the origin of lat 0 for Bonne // so bump it up an arc second. // theOrigin.latd(1.0/3600.0); } } ossimGpt ossimBonneProjection::inverse(const ossimDpt &eastingNorthing)const { double lat, lon; Convert_Bonne_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0, theDatum); } ossimDpt ossimBonneProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Bonne(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimBonneProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimBonneProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Must do this first. bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimBonneProjection)) { Bonn_False_Easting = theFalseEastingNorthing.x; Bonn_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /* * These state variables are for optimization purposes. The only function * that should modify them is Set_Bonne_Parameters. */ /***************************************************************************/ /* * FUNCTIONS */ long ossimBonneProjection::Set_Bonne_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing) { /* Begin Set_Bonne_Parameters */ /* * The function Set_Bonne_Parameters receives the ellipsoid parameters and * Bonne projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the * function, otherwise BONN_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double j, three_es4; double x,e1,e2,e3,e4; double clat; double sin2lat, sin4lat, sin6lat, lat; // double inv_f = 1 / f; long Error_Code = BONN_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= BONN_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= BONN_INV_F_ERROR; // } // if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) // { /* origin latitude out of range */ // Error_Code |= BONN_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= BONN_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Bonn_a = a; Bonn_f = f; Bonn_Origin_Lat = Origin_Latitude; // if (Central_Meridian > PI) // Central_Meridian -= TWO_PI; Bonn_Origin_Long = Central_Meridian; Bonn_False_Northing = False_Northing; Bonn_False_Easting = False_Easting; if (Bonn_Origin_Lat == 0.0) { if (Bonn_Origin_Long > 0) { Bonn_Max_Easting = 19926189.0; Bonn_Min_Easting = -20037509.0; } else if (Bonn_Origin_Long < 0) { Bonn_Max_Easting = 20037509.0; Bonn_Min_Easting = -19926189.0; } else { Bonn_Max_Easting = 20037509.0; Bonn_Min_Easting = -20037509.0; } Bonn_Delta_Northing = 10001966.0; Set_Sinusoidal_Parameters(Bonn_a, Bonn_f, Bonn_Origin_Long, Bonn_False_Easting, Bonn_False_Northing); } else { Sin_Bonn_Origin_Lat = sin(Bonn_Origin_Lat); es2 = 2 * Bonn_f - Bonn_f * Bonn_f; es4 = es2 * es2; es6 = es4 * es2; j = 45.0 * es6 / 1024.0; three_es4 = 3.0 * es4; c0 = 1 - es2 / 4.0 - three_es4 / 64.0 - 5.0 * es6 / 256.0; c1 = 3.0 * es2 / 8.0 + three_es4 / 32.0 + j; c2 = 15.0 * es4 / 256.0 + j; c3 = 35.0 * es6 / 3072.0; clat = cos(Bonn_Origin_Lat); m1 = BONN_m(clat, Sin_Bonn_Origin_Lat); lat = c0 * Bonn_Origin_Lat; sin2lat = COEFF_TIMES_BONN_SIN(c1, 2.0, Bonn_Origin_Lat); sin4lat = COEFF_TIMES_BONN_SIN(c2, 4.0, Bonn_Origin_Lat); sin6lat = COEFF_TIMES_BONN_SIN(c3, 6.0, Bonn_Origin_Lat); M1 = BONN_M(lat, sin2lat, sin4lat, sin6lat); x = sqrt (1.0 - es2); e1 = (1.0 - x) / (1.0 + x); e2 = e1 * e1; e3 = e2 * e1; e4 = e3 * e1; a0 = 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0; a1 = 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0; a2 = 151.0 * e3 / 96.0; a3 = 1097.0 * e4 / 512.0; if (Sin_Bonn_Origin_Lat == 0.0) Bonn_am1sin = 0.0; else Bonn_am1sin = Bonn_a * m1 / Sin_Bonn_Origin_Lat; Bonn_Max_Easting = 20027474.0; Bonn_Min_Easting = -20027474.0; Bonn_Delta_Northing = 20003932.0; } } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Bonne_Parameters */ void ossimBonneProjection::Get_Bonne_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Bonne_Parameters */ /* * The function Get_Bonne_Parameters returns the current ellipsoid * parameters and Bonne projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Bonn_a; *f = Bonn_f; *Origin_Latitude = Bonn_Origin_Lat; *Central_Meridian = Bonn_Origin_Long; *False_Easting = Bonn_False_Easting; *False_Northing = Bonn_False_Northing; return; } /* End Get_Bonne_Parameters */ long ossimBonneProjection::Convert_Geodetic_To_Bonne (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Bonne */ /* * The function Convert_Geodetic_To_Bonne converts geodetic (latitude and * longitude) coordinates to Bonne projection (easting and northing) * coordinates, according to the current ellipsoid and Bonne projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise BONN_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double dlam; /* Longitude - Central Meridan */ double mm; double MM; double rho; double EE; double clat = cos(Latitude); double slat = sin(Latitude); double lat, sin2lat, sin4lat, sin6lat; long Error_Code = BONN_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= BONN_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= BONN_LON_ERROR; // } if (!Error_Code) { /* no errors */ if (Bonn_Origin_Lat == 0.0) Convert_Geodetic_To_Sinusoidal(Latitude, Longitude, Easting, Northing); else { dlam = Longitude - Bonn_Origin_Long; if (dlam > M_PI) { dlam -= TWO_PI; } if (dlam < -M_PI) { dlam += TWO_PI; } if ((Latitude - Bonn_Origin_Lat) == 0.0 && FLOAT_EQ(fabs(Latitude),PI_OVER_2,.00001)) { *Easting = 0.0; *Northing = 0.0; } else { mm = BONN_m(clat, slat); lat = c0 * Latitude; sin2lat = COEFF_TIMES_BONN_SIN(c1, 2.0, Latitude); sin4lat = COEFF_TIMES_BONN_SIN(c2, 4.0, Latitude); sin6lat = COEFF_TIMES_BONN_SIN(c3, 6.0, Latitude); MM = BONN_M(lat, sin2lat, sin4lat, sin6lat); rho = Bonn_am1sin + M1 - MM; if (rho == 0) EE = 0; else EE = Bonn_a * mm * dlam / rho; *Easting = rho * sin(EE) + Bonn_False_Easting; *Northing = Bonn_am1sin - rho * cos(EE) + Bonn_False_Northing; } } } return (Error_Code); } /* End Convert_Geodetic_To_Bonne */ long ossimBonneProjection::Convert_Bonne_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Bonne_To_Geodetic */ /* * The function Convert_Bonne_To_Geodetic converts Bonne projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Bonne projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise BONN_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx; /* Delta easting - Difference in easting (easting-FE) */ double dy; /* Delta northing - Difference in northing (northing-FN) */ double mu; double MM; double mm; double am1sin_dy; double rho; double sin2mu, sin4mu, sin6mu, sin8mu; double clat, slat; long Error_Code = BONN_NO_ERROR; // if ((Easting < (Bonn_False_Easting + Bonn_Min_Easting)) // || (Easting > (Bonn_False_Easting + Bonn_Max_Easting))) // { /* Easting out of range */ // Error_Code |= BONN_EASTING_ERROR; // } // if ((Northing < (Bonn_False_Northing - Bonn_Delta_Northing)) // || (Northing > (Bonn_False_Northing + Bonn_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= BONN_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ if (Bonn_Origin_Lat == 0.0) Convert_Sinusoidal_To_Geodetic(Easting, Northing, Latitude, Longitude); else { dy = Northing - Bonn_False_Northing; dx = Easting - Bonn_False_Easting; am1sin_dy = Bonn_am1sin - dy; rho = sqrt(dx * dx + am1sin_dy * am1sin_dy); if (Bonn_Origin_Lat < 0.0) rho = -rho; MM = Bonn_am1sin + M1 - rho; mu = MM / (Bonn_a * c0); sin2mu = COEFF_TIMES_BONN_SIN(a0, 2.0, mu); sin4mu = COEFF_TIMES_BONN_SIN(a1, 4.0, mu); sin6mu = COEFF_TIMES_BONN_SIN(a2, 6.0, mu); sin8mu = COEFF_TIMES_BONN_SIN(a3, 8.0, mu); *Latitude = mu + sin2mu + sin4mu + sin6mu + sin8mu; if (FLOAT_EQ(fabs(*Latitude),PI_OVER_2,.00001)) { *Longitude = Bonn_Origin_Long; } else { clat = cos(*Latitude); slat = sin(*Latitude); mm = BONN_m(clat, slat); if (Bonn_Origin_Lat < 0.0) { dx = -dx; am1sin_dy = -am1sin_dy; } *Longitude = Bonn_Origin_Long + rho * (atan2(dx, am1sin_dy)) / (Bonn_a * mm); } if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ *Latitude = PI_OVER_2; else if (*Latitude < -PI_OVER_2) *Latitude = -PI_OVER_2; // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; if (*Longitude > M_PI)/* force distorted values to 180, -180 degrees */ *Longitude = M_PI; else if (*Longitude < -M_PI) *Longitude = -M_PI; } } return (Error_Code); } /* End Convert_Bonne_To_Geodetic */ //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimBonneProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimBonneProjection* p = dynamic_cast(&proj); if (!p) return false; if (!ossim::almostEqual(Bonn_False_Easting, p->Bonn_False_Easting) ) return false; if (!ossim::almostEqual(Bonn_False_Northing,p->Bonn_False_Northing)) return false; if (!ossim::almostEqual(Bonn_Delta_Northing,p->Bonn_Delta_Northing)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimBuckeyeSensor.cpp000066400000000000000000000566411352751253100232320ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // //******************************************************************* // $Id: ossimBuckeyeSensor.cpp $ #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimBuckeyeSensor:debug"); RTTI_DEF1(ossimBuckeyeSensor, "ossimBuckeyeSensor", ossimSensorModel); ossimBuckeyeSensor::ossimBuckeyeSensor() { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::ossimBuckeyeSensor(): entering..." << std::endl; theCompositeMatrix = ossimMatrix4x4::createIdentity(); theCompositeMatrixInverse = ossimMatrix4x4::createIdentity(); theRoll = 0.0; thePitch = 0.0; theHeading = 0.0; theFocalLength = 0.0; thePixelSize = ossimDpt(0.0, 0.0); thePrincipalPoint = ossimDpt(0.0, 0.0); theEcefPlatformPosition = ossimGpt(0.0, 0.0, 0.0); theAdjEcefPlatformPosition = ossimGpt(0.0, 0.0, 0.0); theLensDistortion = new ossimSmacCallibrationSystem(); theGSD.makeNan(); initAdjustableParameters(); if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::ossimBuckeyeSensor(): returning..." << std::endl; } ossimBuckeyeSensor::ossimBuckeyeSensor(const ossimDrect& imageRect, const ossimGpt& platformPosition, double roll, double pitch, double heading, const ossimDpt& /* principalPoint */, // in millimeters double focalLength, // in millimeters const ossimDpt& pixelSize) // in millimeters { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::ossimBuckeyeSensor(imageRect,platformPosition,roll,pitch,heading,ossimDpt,focalLength,pixelSize): entering..." << std::endl; theImageClipRect = imageRect; theRefImgPt = theImageClipRect.midPoint(); theCompositeMatrix = ossimMatrix4x4::createIdentity(); theCompositeMatrixInverse = ossimMatrix4x4::createIdentity(); theRoll = roll; thePitch = pitch; theHeading = heading; theFocalLength = focalLength; thePixelSize = pixelSize; theEcefPlatformPosition = platformPosition; theAdjEcefPlatformPosition = platformPosition; theLensDistortion = new ossimSmacCallibrationSystem(); theGSD.makeNan(); initAdjustableParameters(); updateModel(); if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::ossimBuckeyeSensor(imageRect,platformPosition,roll,pitch,heading,ossimDpt,focalLength,pixelSize): returning..." << std::endl; } ossimBuckeyeSensor::ossimBuckeyeSensor(const ossimBuckeyeSensor& src) :ossimSensorModel(src) { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::ossimBuckeyeSensor(src): entering..." << std::endl; initAdjustableParameters(); if(src.theLensDistortion.valid()) { theLensDistortion = new ossimSmacCallibrationSystem(*(src.theLensDistortion.get())); } else { theLensDistortion = new ossimSmacCallibrationSystem(); } theGSD.makeNan(); if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::ossimBuckeyeSensor(src): returning..." << std::endl; } ossimObject* ossimBuckeyeSensor::dup()const { return new ossimBuckeyeSensor(*this); } void ossimBuckeyeSensor::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "ossimBuckeyeSensor::imagingRay: ..... entered" << std::endl; ossimDpt f1 ((image_point) - theRefImgPt); f1.x *= thePixelSize.x; f1.y *= -thePixelSize.y; ossimDpt film (f1 - thePrincipalPoint); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "pixel size = " << thePixelSize << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "principal pt = " << thePrincipalPoint << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "film pt = " << film << std::endl; } if (theLensDistortion.valid()) { ossimDpt filmOut; theLensDistortion->undistort(film, filmOut); film = filmOut; } ossimColumnVector3d cam_ray_dir (film.x, film.y, -theFocalLength); ossimEcefVector ecf_ray_dir (theCompositeMatrix*cam_ray_dir); ecf_ray_dir = ecf_ray_dir*(1.0/ecf_ray_dir.magnitude()); image_ray.setOrigin(theAdjEcefPlatformPosition); image_ray.setDirection(ecf_ray_dir); if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "ossimBuckeyeSensor::imagingRay: ..... leaving" << std::endl; } void ossimBuckeyeSensor::lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::lineSampleToWorld:entering..." << std::endl; if(image_point.hasNans()) { gpt.makeNan(); return; } //*** // Determine imaging ray and invoke elevation source object's services to // intersect ray with terrain model: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimElevManager::instance()->intersectRay(ray, gpt); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "image_point = " << image_point << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "ray = " << ray << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "gpt = " << gpt << std::endl; } if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::lineSampleToWorld: returning..." << std::endl; return; } void ossimBuckeyeSensor::lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::lineSampleHeightToWorld: entering..." << std::endl; if (!insideImage(image_point)) { worldPoint.makeNan(); } else { //*** // First establish imaging ray from image point: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimEcefPoint Pecf (ray.intersectAboveEarthEllipsoid(heightEllipsoid)); worldPoint = ossimGpt(Pecf); } if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::lineSampleHeightToWorld: returning..." << std::endl; } void ossimBuckeyeSensor::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::worldToLineSample: entering..." << std::endl; if((theBoundGndPolygon.getNumberOfVertices() > 0)&& (!theBoundGndPolygon.hasNans())) { if (!(theBoundGndPolygon.pointWithin(world_point))) { image_point.makeNan(); return; } } ossimEcefPoint g_ecf(world_point); ossimEcefVector ecfRayDir(g_ecf - theAdjEcefPlatformPosition); ossimColumnVector3d camRayDir (theCompositeMatrixInverse*ecfRayDir.data()); double scale = -theFocalLength/camRayDir[2]; ossimDpt film (scale*camRayDir[0], scale*camRayDir[1]); if (theLensDistortion.valid()) { ossimDpt filmOut; theLensDistortion->distort(film, filmOut); film = filmOut; } ossimDpt f1(film + thePrincipalPoint); ossimDpt p1(f1.x/thePixelSize.x, -f1.y/thePixelSize.y); ossimDpt p0 (p1.x + theRefImgPt.x, p1.y + theRefImgPt.y); image_point = p0; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::worldToLineSample: returning..." << std::endl; } void ossimBuckeyeSensor::updateModel() { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::updateModel: entering..." << std::endl; ossimGpt gpt; ossimGpt wgs84Pt; double metersPerDegree = wgs84Pt.metersPerDegree().x; double degreePerMeter = 1.0/metersPerDegree; double latShift = -computeParameterOffset(1)*degreePerMeter; double lonShift = computeParameterOffset(0)*degreePerMeter; gpt = theEcefPlatformPosition; double height = gpt.height(); gpt.height(height + computeParameterOffset(5)); gpt.latd(gpt.latd() + latShift); gpt.lond(gpt.lond() + lonShift); theAdjEcefPlatformPosition = gpt; ossimLsrSpace lsrSpace(theAdjEcefPlatformPosition, theHeading+computeParameterOffset(4)); // make a left handed rotational matrix; ossimMatrix4x4 lsrMatrix(lsrSpace.lsrToEcefRotMatrix()); NEWMAT::Matrix orientation = (ossimMatrix4x4::createRotationXMatrix(thePitch+computeParameterOffset(3), OSSIM_LEFT_HANDED)* ossimMatrix4x4::createRotationYMatrix(theRoll+computeParameterOffset(2), OSSIM_LEFT_HANDED)); theCompositeMatrix = (lsrMatrix.getData()*orientation); theCompositeMatrixInverse = theCompositeMatrix.i(); theBoundGndPolygon.resize(4); theExtrapolateImageFlag = false; theExtrapolateGroundFlag = false; try { // Method throws ossimException. computeGsd(); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "ossimBuckeyeSensor Constructor caught Exception:\n" << e.what() << std::endl; } lineSampleToWorld(theImageClipRect.ul(),gpt); theBoundGndPolygon[0] = gpt; lineSampleToWorld(theImageClipRect.ur(),gpt); theBoundGndPolygon[1] = gpt; lineSampleToWorld(theImageClipRect.lr(),gpt); theBoundGndPolygon[2] = gpt; lineSampleToWorld(theImageClipRect.ll(),gpt); theBoundGndPolygon[3] = gpt; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::updateModel: returning..." << std::endl; } void ossimBuckeyeSensor::initAdjustableParameters() { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::initAdjustableParameters: entering..." << std::endl; resizeAdjustableParameterArray(6); setAdjustableParameter(0, 0.0); setParameterDescription(0, "x_offset"); setParameterUnit(0, "pixels"); setAdjustableParameter(1, 0.0); setParameterDescription(1, "y_offset"); setParameterUnit(1, "pixels"); setAdjustableParameter(2, 0.0); setParameterDescription(2, "roll"); setParameterUnit(2, "degrees"); setAdjustableParameter(3, 0.0); setParameterDescription(3, "pitch"); setParameterUnit(3, "degrees"); setAdjustableParameter(4, 0.0); setParameterDescription(4, "heading"); setParameterUnit(4, "degrees"); setAdjustableParameter(5, 0.0); setParameterDescription(5, "altitude"); setParameterUnit(5, "meters"); // TODO: default to correct default values, or just leave it up to the input file, since we have different offsets for the B100, 182, and Metroliner, also need a z offset setParameterSigma(0, 1.0); setParameterSigma(1, 1.0); setParameterSigma(2, 0); setParameterSigma(3, 0); setParameterSigma(4, 0); setParameterSigma(5, 1000); if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::initAdjustableParameters: returning..." << std::endl; } void ossimBuckeyeSensor::setLensDistortion(ossimSmacCallibrationSystem* lensDistortion) { theLensDistortion = lensDistortion; updateModel(); } bool ossimBuckeyeSensor::saveState(ossimKeywordlist& kwl, const char* prefix) const { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::saveState: entering..." << std::endl; ossimSensorModel::saveState(kwl, prefix); kwl.add(prefix, "type", "ossimBuckeyeSensor", true); kwl.add(prefix, "roll", theRoll, true); kwl.add(prefix, "pitch", thePitch, true); kwl.add(prefix, "heading", theHeading, true); kwl.add(prefix, "principal_point", "("+ossimString::toString(thePrincipalPoint.x) + "," + ossimString::toString(thePrincipalPoint.y)+")"); kwl.add(prefix, "pixel_size", "("+ossimString::toString(thePixelSize.x) + "," + ossimString::toString(thePixelSize.y)+")"); kwl.add(prefix, "focal_length", theFocalLength); kwl.add(prefix, "ecef_platform_position", ossimString::toString(theEcefPlatformPosition.x()) + " " + ossimString::toString(theEcefPlatformPosition.y()) + " " + ossimString::toString(theEcefPlatformPosition.z())); if(theLensDistortion.valid()) { ossimString lensPrefix = ossimString(prefix)+"distortion."; theLensDistortion->saveState(kwl, lensPrefix.c_str()); } if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::saveState: returning..." << std::endl; return true; } bool ossimBuckeyeSensor::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::loadState: entering..." << std::endl; ossimSensorModel::loadState(kwl, prefix); // If theRefImgPt remains unset by ossimSensorModel::loadState(), // set it to the image center. if ( theRefImgPt == ossimDpt(0, 0) ) { theRefImgPt = theImageClipRect.midPoint(); } if(getNumberOfAdjustableParameters() < 1) { initAdjustableParameters(); } ossimString framemeta_gsti = kwl.find(prefix, "framemeta_gsti"); ossimString framemeta = kwl.find(prefix,"framemeta"); ossimString frame_number = kwl.find(prefix, "frame_number"); ossimString pixel_size = kwl.find(prefix, "pixel_size"); ossimString principal_point = kwl.find(prefix, "principal_point"); ossimString focal_length = kwl.find(prefix, "focal_length"); ossimString smac_radial = kwl.find(prefix, "smac_radial"); ossimString smac_decent = kwl.find(prefix, "smac_decent"); ossimString roll; ossimString pitch; ossimString yaw; ossimString platform_position; ossimFilename file_to_load; ossimString FRAME_STRING = "Frame#"; ossimString ROLL_STRING = "Roll(deg)"; ossimString PITCH_STRING = "Pitch(deg)"; ossimString YAW_STRING = "Yaw(deg)"; ossimString LAT_STRING = "Lat(deg)"; ossimString LON_STRING = "Lon(deg)"; ossimString HAE_STRING = "HAE(m)"; // Deal with the fact that there are 3 different types of 'FrameMeta' file if (framemeta_gsti.empty() && !framemeta.empty() && !frame_number.empty()) { file_to_load.setFile(framemeta); YAW_STRING = "Azimuth(deg)"; } else if (!framemeta_gsti.empty() && framemeta.empty() && !frame_number.empty()) { file_to_load.setFile(framemeta_gsti); } if (file_to_load.exists() && !frame_number.empty()) { ossimCsvFile csv(" \t"); // we will use tab or spaces as separator if(csv.open(file_to_load)) { if(csv.readHeader()) { ossimCsvFile::StringListType heads = csv.fieldHeaderList(); // Try to see if you can find the first header item, if not, then you either have a file that doesn't work in this case, or it's uppercase if (std::find(heads.begin(), heads.end(), FRAME_STRING) == heads.end()) { FRAME_STRING = FRAME_STRING.upcase(); ROLL_STRING = ROLL_STRING.upcase(); PITCH_STRING = PITCH_STRING.upcase(); YAW_STRING = YAW_STRING.upcase(); LAT_STRING = LAT_STRING.upcase(); LON_STRING = LON_STRING.upcase(); HAE_STRING = HAE_STRING.upcase(); } ossimRefPtr record; bool foundFrameNumber = false; while( ((record = csv.nextRecord()).valid()) && !foundFrameNumber) { if( (*record)[FRAME_STRING] == frame_number) { foundFrameNumber = true; roll = (*record)[ROLL_STRING]; pitch = (*record)[PITCH_STRING]; yaw = (*record)[YAW_STRING]; platform_position = (*record)[LAT_STRING] + " " + (*record)[LON_STRING]+ " " + (*record)[HAE_STRING] + " WGE"; } } } } csv.close(); } else { roll = kwl.find(prefix, "roll"); pitch = kwl.find(prefix, "pitch"); yaw = kwl.find(prefix, "heading"); platform_position = kwl.find(prefix, "ecef_platform_position"); } bool result = (!pixel_size.empty()&& !principal_point.empty()&& !focal_length.empty()&& !platform_position.empty()); if(!focal_length.empty()) { theFocalLength = focal_length.toDouble(); } if(!pixel_size.empty()) { thePixelSize.toPoint(pixel_size); } if(!roll.empty()) { theRoll = roll.toDouble(); } if(!pitch.empty()) { thePitch = pitch.toDouble(); } if(!yaw.empty()) { theHeading = yaw.toDouble(); } if(!principal_point.empty()) { thePrincipalPoint.toPoint(principal_point); } if(platform_position.contains("WGE")) { std::vector splitString; ossimString tempString(platform_position); tempString.split(splitString, ossimString(" ")); std::string datumString; double lat=0.0, lon=0.0, h=0.0; if(splitString.size() > 2) { lat = splitString[0].toDouble(); lon = splitString[1].toDouble(); h = splitString[2].toDouble(); } theEcefPlatformPosition = ossimGpt(lat,lon,h); } else { std::vector splitString; ossimString tempString(platform_position); tempString.split(splitString, ossimString(" ")); std::string datumString; double x=0.0, y=0.0, z=0.0; if(splitString.size() > 2) { x = splitString[0].toDouble(); y = splitString[1].toDouble(); z = splitString[2].toDouble(); } theEcefPlatformPosition = ossimEcefPoint(x, y, z); } theLensDistortion = 0; if(!smac_radial.empty()&& !smac_decent.empty()) { std::vector radial; std::vector decent; smac_radial.split(radial, " "); smac_decent.split(decent, " "); if((radial.size() == 5)&& (decent.size() == 4)) { // Just for debugging really.. optimization will make this sleeker double k0 = radial[0].toDouble(); double k1 = radial[1].toDouble(); double k2 = radial[2].toDouble(); double k3 = radial[3].toDouble(); double k4 = radial[4].toDouble(); double p0 = decent[0].toDouble(); double p1 = decent[1].toDouble(); double p2 = decent[2].toDouble(); double p3 = decent[3].toDouble(); theLensDistortion = new ossimSmacCallibrationSystem(k0,k1,k2,k3,k4,p0,p1,p2,p3); } } theImageSize = ossimDpt(theImageClipRect.width(), theImageClipRect.height()); updateModel(); if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::loadState: returning..." << std::endl; return result; } bool ossimBuckeyeSensor::setupOptimizer(const ossimString& init_file) { ossimKeywordlist kwl; kwl.addFile(init_file.c_str()); return loadState(kwl); } void ossimBuckeyeSensor::setPrincipalPoint(ossimDpt principalPoint) { thePrincipalPoint = principalPoint; } void ossimBuckeyeSensor::setRollPitchHeading(double roll, double pitch, double heading) { theRoll = roll; thePitch = pitch; theHeading = heading; updateModel(); } void ossimBuckeyeSensor::setPixelSize(const ossimDpt& pixelSize) { thePixelSize = pixelSize; } void ossimBuckeyeSensor::setImageRect(const ossimDrect& rect) { theImageClipRect = rect; theRefImgPt = rect.midPoint(); } void ossimBuckeyeSensor::setFocalLength(double focalLength) { theFocalLength = focalLength; } void ossimBuckeyeSensor::setPlatformPosition(const ossimGpt& gpt) { theRefGndPt = gpt; theEcefPlatformPosition = gpt; updateModel(); } bool ossimBuckeyeSensor::getImageGeometry( const ossimString& ref, const ossimString& value, ossimKeywordlist& geomKwl ) const { if ( ref == ossimString( "parameters/fsmmgSensorImage/collectionTime" ) ) { /* not currently used */ } else if ( ref == ossimString( "parameters/fsmmgSensorSession/sensorType" ) ) { /* not currently used */ } else if ( ref == ossimString( "parameters/fsmmgSensorSession/focus/focalLength" ) ) { geomKwl.add( "focal_length", value.toDouble() ); } else if ( ref == ossimString( "parameters/fsmmgSensorSession/pixelGridCharacteristics/numberOfRowsInImage" ) ) { /* Add check to value already set from limits/GridEnvelope/low,high: should be equal */ } else if ( ref == ossimString( "parameters/fsmmgSensorSession/pixelGridCharacteristics/numberOfColumnsInImage" ) ) { /* Add check to value already set from limits/GridEnvelope/low,high: should be equal */ } else if ( ref == ossimString( "parameters/fsmmgSensorSession/pixelGridCharacteristics/rowSpacing" ) ) { ossimDpt point = ossimDpt(); ossimString pixel_size = geomKwl.find( "pixel_size" ); if ( !pixel_size.empty() ) { point.toPoint( pixel_size ); } point.y = value.toDouble(); geomKwl.add( "pixel_size", point.toString().c_str() ); } else if ( ref == ossimString( "parameters/fsmmgSensorSession/pixelGridCharacteristics/columnSpacing" ) ) { ossimDpt point = ossimDpt(); ossimString pixel_size = geomKwl.find( "pixel_size" ); if ( !pixel_size.empty() ) { point.toPoint( pixel_size ); } point.x = value.toDouble(); geomKwl.add( "pixel_size", point.toString().c_str() ); } else if ( ref == ossimString( "parameters/fsmmgSensorImage/positionOrientationState/perspectiveCenter/geocentric-x-y-z" ) ) { // first remove trailing spaces size_t first_space = value.find_first_of( ' ', 0 ); ossimString truncatedValue = value.beforePos( first_space ); // change commas into spaces ossimString platformPositionStr = truncatedValue.substitute( ossimString( "," ), ossimString( " " ), true ); // add to keywordlist geomKwl.add( "ecef_platform_position", platformPositionStr ); } else if ( ref == ossimString( "parameters/fsmmgSensorImage/velocity/components/geocentric-x-y-z" ) ) { /* not currently used */ } else if ( ref == ossimString( "parameters/fsmmgSensorSession/principalPointOffset/components/imagePlaneCRS-x0-y0" ) ) { ossimDpt principal_point_offset; size_t first_comma = value.find_first_of( ',', 0 ); ossimString offsetxStr = value.beforePos( first_comma ); ossimString offsetyStr = value.afterPos( first_comma ); principal_point_offset.x = offsetxStr.toDouble(); principal_point_offset.y = offsetyStr.toDouble(); geomKwl.add( "principal_point", principal_point_offset.toString().c_str() ); } else if ( ref == ossimString( "parameters/fsmmgSensorSession/radialDistortion/coefficients/k0-k1-k2-k3-k4" ) ) { // first remove trailing spaces size_t first_space = value.find_first_of( ' ', 0 ); ossimString truncatedValue = value.beforePos( first_space ); // change commas into spaces ossimString radialDistortionStr = truncatedValue.substitute( ossimString( "," ), ossimString( " " ), true ); // add to keywordlist geomKwl.add( "smac_radial", radialDistortionStr ); } else if ( ref == ossimString( "parameters/fsmmgSensorSession/decenteringDistortion/coefficients/p0-p1-p2-p3" ) ) { // first remove trailing spaces size_t first_space = value.find_first_of( ' ', 0 ); ossimString truncatedValue = value.beforePos( first_space ); // change commas into spaces ossimString decenteringDistortionStr = truncatedValue.substitute( ossimString( "," ), ossimString( " " ), true ); // add to keywordlist geomKwl.add( "smac_decent", decenteringDistortionStr ); } else if ( ref == ossimString( "parameters/fsmmgPlatformImage/positionOrientationState/externalOrientation/platformCS-roll-pitch-yaw" ) ) { size_t pos_comma = value.find_first_of( ',', 0 ); ossimString rollStr = value.beforePos( pos_comma ); ossimString remainderStr0 = value.afterPos( pos_comma ); pos_comma = remainderStr0.find_first_of( ',', 0 ); ossimString pitchStr = remainderStr0.beforePos( pos_comma ); ossimString remainderStr1 = remainderStr0.afterPos( pos_comma ); pos_comma = remainderStr1.find_first_of( ',', 0 ); ossimString yawStr = remainderStr1.beforePos( pos_comma ); geomKwl.add( "roll", rollStr.toDouble() ); geomKwl.add( "pitch", pitchStr.toDouble() ); geomKwl.add( "heading", yawStr.toDouble() ); } else // need to add in all supported parameters from the primary SensorML document { /* Add debug message */ return false; } return true; } ossim-Miami-2.9.1/src/projection/ossimCadrgProjection.cpp000066400000000000000000000242551352751253100235220ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimCadrgProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include #include #include #include RTTI_DEF1(ossimCadrgProjection, "ossimCadrgProjection", ossimMapProjection) double ossimCadrgProjection::theOldZoneExtents[] = {0.0, 32.0, 48.0, 56.0, 64.0, 68.0, 72.0, 76.0, 80.0, 90.0}; double ossimCadrgProjection::theCadrgArcA[] = { 369664, 302592, 245760, 199168, 163328, 137216, 110080, 82432 }; double ossimCadrgProjection::theNorthLimit = 90.0*M_PI/180.0; double ossimCadrgProjection::theSouthLimit = -90.0*M_PI/180.0; ossimCadrgProjection::ossimCadrgProjection() :ossimMapProjection(ossimEllipsoid(), ossimGpt()), theCadrgZone(1), theMapScale(5000000), theWidth(0.0), theHeight(0.0) { computeParameters(); } ossimCadrgProjection::~ossimCadrgProjection() { } ossimObject *ossimCadrgProjection::dup()const { return new ossimCadrgProjection(*this); } ossimDpt ossimCadrgProjection::worldToLineSample(const ossimGpt &worldPoint) const { ossimDpt lineSample; worldToLineSample(worldPoint, lineSample); return lineSample; } ossimGpt ossimCadrgProjection::inverse(const ossimDpt& /* eastingNorthing */)const { double lat=0.0; double lon=0.0; return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimCadrgProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } return ossimDpt(easting, northing); } ossimGpt ossimCadrgProjection::lineSampleToWorld(const ossimDpt &projectedPoint)const { ossimGpt worldPoint; lineSampleToWorld(projectedPoint, worldPoint); return worldPoint; } void ossimCadrgProjection::worldToLineSample(const ossimGpt &worldPoint, ossimDpt& lineSample)const { double lat = worldPoint.latd(); double lon = worldPoint.lond(); double centerLat = theOrigin.latd(); double centerLon = theOrigin.lond()*DEG_PER_RAD; lineSample.y = (centerLat - lat)/90.0*thePixelConstant.y; lineSample.x = (lon - centerLon)/360.0*thePixelConstant.x; lineSample = lineSample - theUlLineSample; } void ossimCadrgProjection::lineSampleToWorld(const ossimDpt &projectedPoint, ossimGpt& gpt)const { gpt = theOrigin; ossimDpt adjustedPixel(projectedPoint.x + theUlLineSample.x, projectedPoint.y + theUlLineSample.y); // double lat = gpt.latd() - (90/thePixelConstant.y)*adjustedPixel.y; // double lon = gpt.lond() + (360/thePixelConstant.x)*adjustedPixel.x; double lat = gpt.latd() - (90/thePixelConstant.y)*adjustedPixel.y; double lon = gpt.lond() + (360/thePixelConstant.x)*adjustedPixel.x; gpt.latd(lat); gpt.lond(lon); gpt.clampLat(-90, 90); gpt.clampLon(-180, 180); } double ossimCadrgProjection::computeXPixConstant(double scale, long zone)const { double adrgscale = 1000000/scale; // E-W pixel constant double x_pix = (double) adrgscale*theCadrgArcA[zone-1] / 512.0; // Increase, if necessary, to the next highest integer value x_pix = ceil(x_pix); x_pix = x_pix * 1.33333;//(512*100)/(150*256); // Round the final result. x_pix = ossim::round(x_pix); return x_pix*256.0; } double ossimCadrgProjection::computeYPixConstant(double scale)const { double adrgscale = 1000000/scale; const long CADRG_ARC_B = 400384; double y_pix = (double) adrgscale * CADRG_ARC_B / 512.0; // Increase, if necessary, to the next highest integer value y_pix = ceil(y_pix); y_pix = y_pix * 0.33333;//(512*100)/(4*150*256); // Round the final result. y_pix = ossim::round(y_pix); return y_pix*256.0; } void ossimCadrgProjection::computeParameters() { theUlLineSample = ossimDpt(0,0); thePixelConstant.y = computeYPixConstant(theMapScale); thePixelConstant.x = computeXPixConstant(theMapScale, theCadrgZone); double height = theHeight; double width = theWidth; if(width > thePixelConstant.x) { width = thePixelConstant.x; } if(height > thePixelConstant.y) { height = thePixelConstant.y; } theUlLineSample.x = -width/2.0; theUlLineSample.y = -height/2.0; } bool ossimCadrgProjection::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = ossimProjection::saveState(kwl, prefix); kwl.add(prefix, ossimKeywordNames::ZONE_KW, theCadrgZone, true); kwl.add(prefix, "map_scale", theMapScale, true); kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, theHeight, true); kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, theWidth, true); kwl.add(prefix, ossimKeywordNames::UL_LAT_KW, theUlGpt.latd(), true); kwl.add(prefix, ossimKeywordNames::UL_LON_KW, theUlGpt.lond(), true); kwl.add(prefix, ossimKeywordNames::LL_LAT_KW, theLlGpt.latd(), true); kwl.add(prefix, ossimKeywordNames::LL_LON_KW, theLlGpt.lond(), true); kwl.add(prefix, ossimKeywordNames::LR_LAT_KW, theLrGpt.latd(), true); kwl.add(prefix, ossimKeywordNames::LR_LON_KW, theLrGpt.lond(), true); kwl.add(prefix, ossimKeywordNames::UR_LAT_KW, theUrGpt.latd(), true); kwl.add(prefix, ossimKeywordNames::UR_LON_KW, theUrGpt.lond(), true); if(theDatum) { kwl.add(prefix, ossimKeywordNames::DATUM_KW, theDatum->code(), true); } return result; } bool ossimCadrgProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimProjection::loadState(kwl, prefix); const char* lookup = kwl.find(prefix, ossimKeywordNames::UL_LAT_KW); if(lookup) { theUlGpt.latd(ossimString(lookup).toDouble()); } else { theUlGpt.latd(90.0); } lookup = kwl.find(prefix, ossimKeywordNames::UL_LON_KW); if(lookup) { theUlGpt.lond(ossimString(lookup).toDouble()); } else { theUlGpt.lond(-180.0); } lookup = kwl.find(prefix, ossimKeywordNames::LL_LAT_KW); if(lookup) { theLlGpt.latd(ossimString(lookup).toDouble()); } else { theLlGpt.latd(0.0); } lookup = kwl.find(prefix, ossimKeywordNames::LL_LON_KW); if(lookup) { theLlGpt.lond(ossimString(lookup).toDouble()); } else { theLlGpt.lond(-180.0); } lookup = kwl.find(prefix, ossimKeywordNames::LR_LAT_KW); if(lookup) { theLrGpt.latd(ossimString(lookup).toDouble()); } else { theLrGpt.latd(0.0); } lookup = kwl.find(prefix, ossimKeywordNames::LR_LON_KW); if(lookup) { theLrGpt.lond(ossimString(lookup).toDouble()); } else { theLrGpt.lond(180.0); } lookup = kwl.find(prefix, ossimKeywordNames::LR_LAT_KW); if(lookup) { theLrGpt.latd(ossimString(lookup).toDouble()); } else { theLrGpt.latd(0.0); } lookup = kwl.find(prefix, ossimKeywordNames::LR_LON_KW); if(lookup) { theLrGpt.lond(ossimString(lookup).toDouble()); } else { theLrGpt.lond(180.0); } lookup = kwl.find(prefix, ossimKeywordNames::UR_LAT_KW); if(lookup) { theUrGpt.latd(ossimString(lookup).toDouble()); } else { theUrGpt.latd(90.0); } lookup = kwl.find(prefix, ossimKeywordNames::UR_LON_KW); if(lookup) { theUrGpt.lond(ossimString(lookup).toDouble()); } else { theUrGpt.lond(180.0); } const char* zone = kwl.find(prefix, ossimKeywordNames::ZONE_KW); if(zone) { theCadrgZone = ossimString(zone).toLong(); } const char* mapScale = kwl.find(prefix, "map_scale"); if(mapScale) { theMapScale = ossimString(mapScale).toDouble(); } const char *height = kwl.find(prefix, ossimKeywordNames::NUMBER_LINES_KW); const char *width = kwl.find(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW); if(height) { theHeight = ossimString(height).toDouble(); } if(width) { theWidth = ossimString(width).toDouble(); } computeParameters(); return true; } //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimCadrgProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimCadrgProjection* p = dynamic_cast(&proj); if (!p) return false; if (theUlGpt != p->theUlGpt) return false; if (theLlGpt != p->theLlGpt) return false; if (theLrGpt != p->theLrGpt) return false; if (theUrGpt != p->theUrGpt) return false; if (!ossim::almostEqual(theWidth,p->theWidth)) return false; if (!ossim::almostEqual(theHeight,p->theHeight)) return false; if (theCadrgZone != p->theCadrgZone) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimCassiniProjection.cpp000066400000000000000000000430071352751253100240670ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Cassini projection code. //******************************************************************* // $Id: ossimCassiniProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include RTTI_DEF1(ossimCassiniProjection, "ossimCassiniProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #ifdef PI_OVER_2 # undef PI_OVER_2 #endif #define CASS_NO_ERROR 0x0000 #define CASS_LAT_ERROR 0x0001 #define CASS_LON_ERROR 0x0002 #define CASS_EASTING_ERROR 0x0004 #define CASS_NORTHING_ERROR 0x0008 #define CASS_ORIGIN_LAT_ERROR 0x0010 #define CASS_CENT_MER_ERROR 0x0020 #define CASS_A_ERROR 0x0040 #define CASS_B_ERROR 0x0080 #define CASS_A_LESS_B_ERROR 0x0100 #define CASS_LON_WARNING 0x0200 #define PI_OVER_2 ( M_PI / 2.0) #define CASS_M(c0lat, c1s2lat, c2s4lat, c3s6lat) (Cass_a*(c0lat-c1s2lat+c2s4lat-c3s6lat)) #define CASS_RD(sinlat) (sqrt(1.0 - es2 * (sinlat * sinlat))) #define CASS_COEFF_TIMES_SIN(coeff, x, latit) (coeff * (sin (x * latit))) #define FLOAT_EQ(x,v,epsilon) (((v - epsilon) < x) && (x < (v + epsilon))) #define THIRTY_ONE (31.0 * M_PI / 180.0) /* 31 degrees in radians */ ossimCassiniProjection::ossimCassiniProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimCassiniProjection::ossimCassiniProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, const double falseEasting, const double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Cass_False_Easting = falseEasting; Cass_False_Northing = falseNorthing; Cass_Min_Easting = -20037508.4; Cass_Max_Easting = 20037508.4; Cass_Min_Northing = -56575846.0; Cass_Max_Northing = 56575846.0; update(); } void ossimCassiniProjection::update() { Set_Cassini_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Cass_False_Easting, Cass_False_Northing); theFalseEastingNorthing.x = Cass_False_Easting; theFalseEastingNorthing.y = Cass_False_Northing; ossimMapProjection::update(); } void ossimCassiniProjection::setFalseEasting(double falseEasting) { Cass_False_Easting = falseEasting; update(); } void ossimCassiniProjection::setFalseNorthing(double falseNorthing) { Cass_False_Northing = falseNorthing; update(); } void ossimCassiniProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Cass_False_Easting = falseEasting; Cass_False_Northing = falseNorthing; update(); } void ossimCassiniProjection::setDefaults() { Cass_Min_Easting = -20037508.4; Cass_Max_Easting = 20037508.4; Cass_Min_Northing = -56575846.0; Cass_Max_Northing = 56575846.0; Cass_False_Easting = 0.0; Cass_False_Northing = 0.0; } ossimGpt ossimCassiniProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Cassini_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0, theDatum); } ossimDpt ossimCassiniProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Cassini(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimCassiniProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimCassiniProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Must do this first. bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimCassiniProjection)) { Cass_False_Easting = theFalseEastingNorthing.x; Cass_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimCassiniProjection::Set_Cassini_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing) { /* Begin Set_Cassini_Parameters */ /* * The function Set_Cassini_Parameters receives the ellipsoid parameters and * Cassini projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the * function, otherwise CASS_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double j,three_es4; double x, e1, e2, e3, e4; double lat, sin2lat, sin4lat, sin6lat; double temp; // double inv_f = 1 / f; long Error_Code = CASS_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= CASS_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= CASS_INV_F_ERROR; // } // if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) // { /* origin latitude out of range */ // Error_Code |= CASS_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= CASS_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Cass_a = a; Cass_f = f; Cass_Origin_Lat = Origin_Latitude; // if (Central_Meridian > PI) // Central_Meridian -= TWO_PI; Cass_Origin_Long = Central_Meridian; Cass_False_Northing = False_Northing; Cass_False_Easting = False_Easting; es2 = 2 * Cass_f - Cass_f * Cass_f; es4 = es2 * es2; es6 = es4 * es2; j = 45.0 * es6 / 1024.0; three_es4 = 3.0 * es4; c0 = 1 - es2 / 4.0 - three_es4 / 64.0 - 5.0 * es6 / 256.0; c1 = 3.0 * es2 /8.0 + three_es4 / 32.0 + j; c2 = 15.0 * es4 / 256.0 + j; c3 = 35.0 * es6 / 3072.0; lat = c0 * Cass_Origin_Lat; sin2lat = CASS_COEFF_TIMES_SIN(c1, 2.0, Cass_Origin_Lat); sin4lat = CASS_COEFF_TIMES_SIN(c2, 4.0, Cass_Origin_Lat); sin6lat = CASS_COEFF_TIMES_SIN(c3, 6.0, Cass_Origin_Lat); M0 = CASS_M(lat, sin2lat, sin4lat, sin6lat); One_Minus_es2 = 1.0 - es2; x = sqrt (One_Minus_es2); e1 = (1 - x) / (1 + x); e2 = e1 * e1; e3 = e2 * e1; e4 = e3 * e1; a0 = 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0; a1 = 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0; a2 = 151.0 * e3 / 96.0; a3 = 1097.0 * e4 /512.0; if (Cass_Origin_Long > 0) { Convert_Geodetic_To_Cassini(THIRTY_ONE, Cass_Origin_Long - M_PI, &temp, &Cass_Max_Northing); Convert_Geodetic_To_Cassini(-THIRTY_ONE, Cass_Origin_Long - M_PI, &temp, &Cass_Min_Northing); Cass_Max_Easting = 19926188.9; Cass_Min_Easting = -20037508.4; } else if (Cass_Origin_Long < 0) { Convert_Geodetic_To_Cassini(THIRTY_ONE, M_PI + Cass_Origin_Long, &temp, &Cass_Max_Northing); Convert_Geodetic_To_Cassini(-THIRTY_ONE, M_PI + Cass_Origin_Long, &temp, &Cass_Min_Northing); Cass_Max_Easting = 20037508.4; Cass_Min_Easting = -19926188.9; } else { Convert_Geodetic_To_Cassini(THIRTY_ONE, M_PI, &temp, &Cass_Max_Northing); Convert_Geodetic_To_Cassini(-THIRTY_ONE, M_PI , &temp, &Cass_Min_Northing); Cass_Max_Easting = 20037508.4; Cass_Min_Easting = -20037508.4; } } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Cassini_Parameters */ void ossimCassiniProjection::Get_Cassini_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Cassini_Parameters */ /* * The function Get_Cassini_Parameters returns the current ellipsoid * parameters, Cassini projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Cass_a; *f = Cass_f; *Origin_Latitude = Cass_Origin_Lat; *Central_Meridian = Cass_Origin_Long; *False_Easting = Cass_False_Easting; *False_Northing = Cass_False_Northing; return; } /* End Get_Cassini_Parameters */ long ossimCassiniProjection::Convert_Geodetic_To_Cassini (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Cassini */ /* * The function Convert_Geodetic_To_Cassini converts geodetic (latitude and * longitude) coordinates to Cassini projection (easting and northing) * coordinates, according to the current ellipsoid and Cassini projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise CASS_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double lat, sin2lat, sin4lat, sin6lat; double RD; double tlat = tan(Latitude); double clat = cos(Latitude); double slat = sin(Latitude); double dlam; /* Longitude - Central Meridan */ double NN; double TT; double AA, A2, A3, A4, A5; double CC; double MM; long Error_Code = CASS_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= CASS_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= CASS_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Cass_Origin_Long; if (fabs(dlam) > (4.0 * M_PI / 180.0)) { /* Distortion will result if Longitude is more than 4 degrees from the Central Meridian */ Error_Code |= CASS_LON_WARNING; } if (dlam > M_PI) { dlam -= TWO_PI; } if (dlam < -M_PI) { dlam += TWO_PI; } RD = CASS_RD(slat); NN = Cass_a / RD; TT = tlat * tlat; AA = dlam * clat; A2 = AA * AA; A3 = AA * A2; A4 = AA * A3; A5 = AA * A4; CC = es2 * clat * clat / One_Minus_es2; lat = c0 * Latitude; sin2lat = CASS_COEFF_TIMES_SIN(c1, 2.0, Latitude); sin4lat = CASS_COEFF_TIMES_SIN(c2, 4.0, Latitude); sin6lat = CASS_COEFF_TIMES_SIN(c3, 6.0, Latitude); MM = CASS_M(lat, sin2lat, sin4lat, sin6lat); *Easting = NN * (AA - (TT * A3 / 6.0) - (8.0 - TT + 8.0 * CC) * (TT * A5 / 120.0)) + Cass_False_Easting; *Northing = MM - M0 + NN * tlat * ((A2 / 2.0) + (5.0 - TT + 6.0 * CC) * A4 / 24.0) + Cass_False_Northing; } return (Error_Code); } /* End Convert_Geodetic_To_Cassini */ long ossimCassiniProjection::Convert_Cassini_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Cassini_To_Geodetic */ /* * The function Convert_Cassini_To_Geodetic converts Cassini projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Cassini projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise CASS_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx; /* Delta easting - Difference in easting (easting-FE) */ double dy; /* Delta northing - Difference in northing (northing-FN) */ double mu1; double sin2mu, sin4mu, sin6mu, sin8mu; double M1; double phi1; double tanphi1, sinphi1, cosphi1; double T1, T; double N1; double RD, R1; double DD, D2, D3, D4, D5; // const double epsilon = 1.0e-1; long Error_Code = CASS_NO_ERROR; // if ((Easting < (Cass_False_Easting + Cass_Min_Easting)) // || (Easting > (Cass_False_Easting + Cass_Max_Easting))) // { /* Easting out of range */ // Error_Code |= CASS_EASTING_ERROR; // } // if ((Northing < (Cass_False_Northing + Cass_Min_Northing - epsilon)) // || (Northing > (Cass_False_Northing + Cass_Max_Northing + epsilon))) // { /* Northing out of range */ // Error_Code |= CASS_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ dy = Northing - Cass_False_Northing; dx = Easting - Cass_False_Easting; M1 = M0 + dy; mu1 = M1 / (Cass_a * c0); sin2mu = CASS_COEFF_TIMES_SIN(a0, 2.0, mu1); sin4mu = CASS_COEFF_TIMES_SIN(a1, 4.0, mu1); sin6mu = CASS_COEFF_TIMES_SIN(a2, 6.0, mu1); sin8mu = CASS_COEFF_TIMES_SIN(a3, 8.0, mu1); phi1 = mu1 + sin2mu + sin4mu + sin6mu + sin8mu; if (FLOAT_EQ(phi1,PI_OVER_2,.00001)) { *Latitude = PI_OVER_2; *Longitude = Cass_Origin_Long; } else if (FLOAT_EQ(phi1,-PI_OVER_2,.00001)) { *Latitude = -PI_OVER_2; *Longitude = Cass_Origin_Long; } else { tanphi1 = tan(phi1); sinphi1 = sin(phi1); cosphi1 = cos(phi1); T1 = tanphi1 * tanphi1; RD = CASS_RD(sinphi1); N1 = Cass_a / RD; R1 = N1 * One_Minus_es2 / (RD * RD); DD = dx / N1; D2 = DD * DD; D3 = D2 * DD; D4 = D3 * DD; D5 = D4 * DD; T = (1.0 + 3.0 * T1); *Latitude = phi1 - (N1 * tanphi1 / R1) * (D2 / 2.0 - T * D4 / 24.0); *Longitude = Cass_Origin_Long + (DD - T1 * D3 / 3.0 + T * T1 * D5 / 15.0) / cosphi1; if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ *Latitude = PI_OVER_2; else if (*Latitude < -PI_OVER_2) *Latitude = -PI_OVER_2; // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ *Longitude = M_PI; else if (*Longitude < -M_PI) *Longitude = -M_PI; } if (fabs(*Longitude - Cass_Origin_Long) > (4.0 * M_PI / 180.0)) { /* Distortion will result if Longitude is more than 4 degrees from the Central Meridian */ Error_Code |= CASS_LON_WARNING; } } return (Error_Code); } /* End Convert_Cassini_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimCoarseGridModel.cpp000066400000000000000000001127541352751253100234520ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimCoarseGridModel.cc // // License: See LICENSE.txt file in the top level directory. // // AUTHOR: Oscar Kramer // // DESCRIPTION: // Contains implementation of class ossimCoarseGridModel. This is an // implementation of an interpolation sensor model. // // IMPORTANT: The lat/lon grid is for ground points on the ellipsoid. // The dLat/dHgt and dLon/dHgt partials therefore are used against // elevations relative to the ellipsoid. // //***************************************************************************** // $Id: ossimCoarseGridModel.cpp 22825 2014-07-07 23:14:52Z dburken $ #include RTTI_DEF1(ossimCoarseGridModel, "ossimCoarseGridModel", ossimSensorModel); #include #include #include #include #include #include #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include using namespace std; static ossimTrace traceExec ("ossimCoarseGridModel:exec"); static ossimTrace traceDebug ("ossimCoarseGridModel:debug"); static const char* MODEL_TYPE = "ossimCoarseGridModel"; static const char* GRID_FILE_NAME_KW = "grid_file_name"; static const char* CROSSES_DATELINE_KW = "crosses_dateline"; const ossimFilename DEFAULT_GEOM_FILE_EXT ("geom"); const ossimFilename DEFAULT_GRID_FILE_EXT ("ocg"); double ossimCoarseGridModel::theInterpolationError = .1; ossim_int32 ossimCoarseGridModel::theMinGridSpacing = 100; //***************************************************************************** // DEFAULT CONSTRUCTOR: ossimCoarseGridModel() // //***************************************************************************** ossimCoarseGridModel::ossimCoarseGridModel() : ossimSensorModel(), theDlatDparamGrid (0), theDlonDparamGrid (0), theHeightEnabledFlag(true) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::ossimCoarseGridModel: entering..." << std::endl; theLatGrid.setDomainType(ossimDblGrid::SAWTOOTH_90); theLonGrid.setDomainType(ossimDblGrid::WRAP_180); theLatGrid.enableExtrapolation(); theLonGrid.enableExtrapolation(); setErrorStatus(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::ossimCoarseGridModel: returning..." << std::endl; } //***************************************************************************** // COPY CONSTRUCTOR: ossimCoarseGridModel(ossimCoarseGridModel) // //***************************************************************************** ossimCoarseGridModel::ossimCoarseGridModel(const ossimCoarseGridModel& model) : ossimSensorModel (model), theGridFilename (model.theGridFilename), theLatGrid (model.theLatGrid), theLonGrid (model.theLonGrid), theDlatDhGrid (model.theDlatDhGrid), theDlonDhGrid (model.theDlonDhGrid), theDlatDparamGrid (0), theDlonDparamGrid (0), theHeightEnabledFlag(true) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::ossimCoarseGridModel(model): entering..." << std::endl; int numberOfParams = getNumberOfAdjustableParameters(); if(numberOfParams) { //*** // Allocate adjustable parameter partials grids then assign: //*** theDlatDparamGrid = new ossimDblGrid [numberOfParams]; theDlonDparamGrid = new ossimDblGrid [numberOfParams]; for (int i=0; i geom = new ossimImageGeometry(); geom->setProjection(proj); buildGrid(imageBounds, geom.get(), heightDelta, enableHeightFlag, makeAdjustableFlag); } //************************************************************************************************* //! Assigns the grid data given a geometry //************************************************************************************************* void ossimCoarseGridModel::buildGrid(const ossimDrect& imageBounds, ossimImageGeometry* geom, double heightDelta, bool enableHeightFlag, bool makeAdjustableFlag) { theHeightEnabledFlag = enableHeightFlag; if (!geom->getProjection() || imageBounds.hasNans()) return; // don't let it get any smaller than 100, 100 pixels // on the input projector // // may want this to be adjusted by outside // const ossimDatum* targetDatum = ossimDatumFactory::instance()->wgs84(); ossimIpt gridSize(2,2); ossimDpt gridOrigin(0,0); ossimGpt gpt; ossimGpt gpt2; ossimGpt bilinearGpt; resizeAdjustableParameterArray(0); double normSplit = 1.0; ossimIpt imageSize = ossimIpt(imageBounds.width(), imageBounds.height()); double error = 0.0; ossimIpt imageOrigin = imageBounds.ul(); ossimDpt spacing ((double)(imageBounds.width()-1)/(gridSize.x-1), (double)(imageBounds.height()-1)/(gridSize.y-1)); if(theDlatDparamGrid) { delete [] theDlatDparamGrid; theDlatDparamGrid = NULL; } if(theDlonDparamGrid) { delete [] theDlonDparamGrid; theDlonDparamGrid = NULL; } geom->localToWorld(imageBounds.midPoint(), gpt); do { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Checking grid size " << gridSize << std::endl; } spacing = ossimDpt((double)(imageBounds.width()-1)/(gridSize.x-1), (double)(imageBounds.height()-1)/(gridSize.y-1)); theLatGrid.setNullValue(ossim::nan()); theLonGrid.setNullValue(ossim::nan()); theDlatDhGrid.setNullValue(0.0); theDlonDhGrid.setNullValue(0.0); theLatGrid.setDomainType(ossimDblGrid::SAWTOOTH_90); theLonGrid.setDomainType(ossimDblGrid::WRAP_180); theLatGrid.initialize(gridSize, gridOrigin, spacing); theLonGrid.initialize(gridSize, gridOrigin, spacing); theDlatDhGrid.initialize(gridSize, gridOrigin, spacing); theDlonDhGrid.initialize(gridSize, gridOrigin, spacing); ossim_int32 x, y; for(y = 0; y < gridSize.y; ++y) { for(x = 0; x < gridSize.x; ++x) { ossimDpt norm((double)x/(double)(gridSize.x-1), (double)y/(double)(gridSize.y-1)); ossimDpt pt(imageOrigin.x + norm.x*(imageSize.x-1), imageOrigin.y + norm.y*(imageSize.y-1)); geom->localToWorld(pt, gpt); double h = gpt.height(); if(ossim::isnan(h)) { h += heightDelta; } ossimDpt fullPt; geom->rnToFull(pt, 0, fullPt); geom->getProjection()->lineSampleHeightToWorld(fullPt, h, gpt2); gpt.changeDatum(targetDatum); gpt2.changeDatum(targetDatum); theLatGrid.setNode(x, y, gpt.latd()); theLonGrid.setNode(x, y, gpt.lond()); theDlatDhGrid.setNode(x, y, (gpt2.latd() - gpt.latd())/heightDelta); theDlonDhGrid.setNode(x, y, (gpt2.lond() - gpt.lond())/heightDelta); } } ossim_int32 upperY = 2*gridSize.y; ossim_int32 upperX = 2*gridSize.x; error = 0.0; // Set all base-class data members needed for subsequent calls to projection code: initializeModelParams(imageBounds); for(y = 0; ((y < upperY)&&(error < theInterpolationError)); ++y) { for(x = 0; ((x < upperX)&&(errorlocalToWorld(imagePoint, gpt); worldToLineSample(gpt, testIpt); error = (testIpt-imagePoint).length(); } } gridSize.x *= 2; gridSize.y *= 2; normSplit *= .5; } while((error > theInterpolationError) && ((imageSize.x*normSplit) > theMinGridSpacing) && ((imageSize.y*normSplit) > theMinGridSpacing)); gridSize = theLatGrid.size(); ossimAdjustableParameterInterface* adjustableParameters = PTR_CAST(ossimAdjustableParameterInterface, geom->getProjection()); removeAllAdjustments(); if(adjustableParameters&&makeAdjustableFlag) { if(adjustableParameters->getNumberOfAdjustableParameters() > 0) { newAdjustment(adjustableParameters->getNumberOfAdjustableParameters()); int numberOfParams = getNumberOfAdjustableParameters(); if(numberOfParams) { //*** // Allocate adjustable parameter partials grids then assign: //*** theDlatDparamGrid = new ossimDblGrid [numberOfParams]; theDlonDparamGrid = new ossimDblGrid [numberOfParams]; for(int paramIdx = 0; paramIdx < numberOfParams; ++ paramIdx) { theDlonDparamGrid[paramIdx].setNullValue(0.0); theDlatDparamGrid[paramIdx].setNullValue(0.0); theDlatDparamGrid[paramIdx].initialize(gridSize, gridOrigin, spacing); theDlonDparamGrid[paramIdx].initialize(gridSize, gridOrigin, spacing); setAdjustableParameter(paramIdx, 0.0); setParameterSigma(paramIdx, adjustableParameters->getParameterSigma(paramIdx)); setParameterUnit(paramIdx, adjustableParameters->getParameterUnit(paramIdx)); setParameterCenter(paramIdx, 0.0); setParameterDescription(paramIdx, adjustableParameters->getParameterDescription(paramIdx)); double oldParameter = adjustableParameters->getAdjustableParameter(paramIdx); adjustableParameters->setAdjustableParameter(paramIdx, 1.0, true); double adjust = adjustableParameters->computeParameterOffset(paramIdx); double deltaLat = 0; double deltaLon = 0; if(adjust != 0.0) { for(int y = 0; y < gridSize.y; ++y) { for(int x = 0; x < gridSize.x; ++x) { ossimDpt norm((double)x/(double)(gridSize.x-1), (double)y/(double)(gridSize.y-1)); ossimDpt pt(imageOrigin.x + norm.x*(imageSize.x-1), imageOrigin.y + norm.y*(imageSize.y-1)); geom->localToWorld(pt, gpt); gpt.changeDatum(targetDatum); gpt2.latd(theLatGrid(pt)); gpt2.lond(theLonGrid(pt)); deltaLat = gpt.latd()-gpt2.latd(); deltaLon = gpt.lond()-gpt2.lond(); theDlatDparamGrid[paramIdx].setNode(x, y, deltaLat/adjust); theDlonDparamGrid[paramIdx].setNode(x, y, deltaLon/adjust); } } // The partials grids for this parameter are initialized, now initialize the // grid's extrapolator: theDlatDparamGrid[paramIdx].enableExtrapolation(); theDlonDparamGrid[paramIdx].enableExtrapolation(); } adjustableParameters->setAdjustableParameter(paramIdx, oldParameter, true); } } } } getAdjustment(theInitialAdjustment); } void ossimCoarseGridModel::setInterpolationError(double error) { theInterpolationError = error; } void ossimCoarseGridModel::setMinGridSpacing(ossim_int32 minSpacing) { theMinGridSpacing = minSpacing; } //************************************************************************************************* //! Initializes base class data members after grids have been assigned. //! It is assumed that theImageSize and the origin image point were already set. //************************************************************************************************* void ossimCoarseGridModel::initializeModelParams(ossimIrect imageBounds) { // NOTE: it is assumed that the grid size and spacing is the same for ALL grids: ossimIpt gridSize (theLatGrid.size()); ossimDpt spacing (theLatGrid.spacing()); ossimDpt v[4]; v[0].lat = theLatGrid.getNode(0,0); v[0].lon = theLonGrid.getNode(0,0); v[1].lat = theLatGrid.getNode(gridSize.x-1, 0); v[1].lon = theLonGrid.getNode(gridSize.x-1, 0); v[2].lat = theLatGrid.getNode(gridSize.x-1, gridSize.y-2); v[2].lon = theLonGrid.getNode(gridSize.x-1, gridSize.y-2); v[3].lat = theLatGrid.getNode(0, gridSize.y-2); v[3].lon = theLonGrid.getNode(0, gridSize.y-2); // Guaranty longitude values are -180 to 180 for (int i=0; i<4; i++) { if (v[i].lon > 180.0) v[i].lon -= 360.0; } theBoundGndPolygon = ossimPolygon(4, v); theImageSize = ossimDpt(imageBounds.width(), imageBounds.height()); theRefImgPt = imageBounds.midPoint(); theRefGndPt.lat = theLatGrid(theRefImgPt); theRefGndPt.lon = theLonGrid(theRefImgPt); ossimDpt ref_ip_dx (theRefImgPt.x+1.0, theRefImgPt.y ); ossimDpt ref_ip_dy (theRefImgPt.x , theRefImgPt.y+1.0); ossimGpt ref_gp_dx (theLatGrid(ref_ip_dx), theLonGrid(ref_ip_dx)); ossimGpt ref_gp_dy (theLatGrid(ref_ip_dy), theLonGrid(ref_ip_dy)); theGSD.x = theRefGndPt.distanceTo(ref_gp_dx); theGSD.y = theRefGndPt.distanceTo(ref_gp_dy); theMeanGSD = (theGSD.line + theGSD.samp)/2.0; theImageClipRect = imageBounds; theSubImageOffset = imageBounds.ul(); } //***************************************************************************** // DESTRUCTOR: ~ossimCoarseGridModel() // //***************************************************************************** ossimCoarseGridModel::~ossimCoarseGridModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::~ossimCoarseGridModel: entering..." << std::endl; if(theDlatDparamGrid&&theDlonDparamGrid) { //*** // Deallocate memory: //*** delete [] theDlatDparamGrid; delete [] theDlonDparamGrid; theDlatDparamGrid = NULL; theDlonDparamGrid = NULL; } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::~ossimCoarseGridModel: returning..." << std::endl; } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimCoarseGridModel::lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const { if(!theHeightEnabledFlag) { // // Extrapolate if image point is outside image: // if (!insideImage(image_point)) { gpt = extrapolate(image_point); return; } lineSampleHeightToWorld(image_point, 0.0, gpt); } else { ossimSensorModel::lineSampleToWorld(image_point, gpt); } } //***************************************************************************** // METHOD: ossimCoarseGridModel::lineSampleHeightToWorld() // // Establishes the ground point corresponding to the input image_point and // specified elevation above MSL // //***************************************************************************** void ossimCoarseGridModel::lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& arg_hgt_above_ellipsoid, ossimGpt& worldPt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::lineSampleHeightToWorld: entering..." << std::endl; if(theLatGrid.size().x < 1 || theLatGrid.size().y < 1) { worldPt.makeNan(); return; } double height = (ossim::isnan(arg_hgt_above_ellipsoid)) ? 0.0 : arg_hgt_above_ellipsoid; // Note that there is no check for image point outside of valid image rect because this model // uses the extrapolation inherent to the ossimDblGrid. // The image point may correspond to an offset sub-image. Need to convert // to full image space before anything: ossimDpt ip = lineSampPt + theSubImageOffset; // Establish the interpolated values from the grids: worldPt.lat = theLatGrid(ip); worldPt.lon = theLonGrid(ip); worldPt.hgt = height; if(theHeightEnabledFlag) { // Adjust horizontally due to elevation: worldPt.lat += theDlatDhGrid(ip)*height; worldPt.lon += theDlonDhGrid(ip)*height; } int numberOfParams = getNumberOfAdjustableParameters(); // Now add increments due to adjustable parameter deltas: for (int p=0; p." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::loadState: returning with error..." << std::endl; theErrorStatus++; return false; } // Load the coarse grid file specified in KWL. This method resets the // theErrorStatus to OSSIM_OK if successful: if (!loadCoarseGrid(theGridFilename)) { theErrorStatus++; return false; } // crossesDateline legacy. No longer saved. bool crossesDateline = false; kwl.getBoolKeywordValue(crossesDateline, CROSSES_DATELINE_KW, prefix); if (crossesDateline) theLonGrid.setDomainType(ossimDblGrid::WRAP_360); // Add the coarse grid filename to list of support files being referenced for logging purposes: ossimSupportFilesList::instance()->add(theGridFilename.expand()); ossimString initAdjPrefix = ossimString(prefix) + "init_adjustment."; theInitialAdjustment.loadState(kwl, initAdjPrefix.c_str()); if((ossim::isnan(theRefGndPt.hgt)) || (theRefGndPt.hgt == 0)) { theRefGndPt.hgt = ossimElevManager::instance()->getHeightAboveEllipsoid(theRefGndPt); if(theRefGndPt.hgt < 0) { theRefGndPt.hgt = fabs(theRefGndPt.hgt); } } if(theInitialAdjustment.getNumberOfAdjustableParameters() < 1) { getAdjustment(theInitialAdjustment); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::loadState: returning..." << std::endl; if (theErrorStatus) return false; return true; } //***************************************************************************** // METHOD: ossimCoarseGridModel::saveCoarseGrid(cgFileName) // // Saves the coarse grid to disk file. // // Returns true if successful. // //***************************************************************************** bool ossimCoarseGridModel::saveCoarseGrid(const ossimFilename& fileName)const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::saveCoarseGrid: entering..." << std::endl; // Create and open grid file as stream: theGridFilename = fileName.expand(); theGridFilename.setExtension(DEFAULT_GRID_FILE_EXT); ofstream outstream (theGridFilename.chars()); if (!outstream.is_open()) { theErrorStatus++; ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::saveCoarseGrid: Error " "encountered creating coarse grid file <" << theGridFilename<< ">. Check that directory " "exists and is writable." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::saveCoarseGrid: returning with error..." << std::endl; return false; } // Let each grid object write itself to the output file: theLatGrid.save(outstream, "Latitude Grid"); theLonGrid.save(outstream, "Longitude Grid"); theDlatDhGrid.save(outstream, "dLat/dH Grid"); theDlonDhGrid.save(outstream, "dLon_dH Grid"); ossimString descr; int numberOfParams = getNumberOfAdjustableParameters(); for (int p=0; padd(geom_file); ossimSupportFilesList::instance()->add(theGridFilename); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::saveCoarseGrid: returning..." << std::endl; return true; } //***************************************************************************** // METHOD: ossimCoarseGridModel::loadCoarseGrid(cgFileName) // // Loads the coarse grid from disk file. // // Returns true if successful. // //***************************************************************************** bool ossimCoarseGridModel::loadCoarseGrid(const ossimFilename& cgFileName) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::loadCoarseGrid: entering..." << std::endl; ossimDpt v[4]; ossimIpt grid_size; //*** // Open existing grid file: //*** ifstream instream (cgFileName.chars()); if (!instream.is_open()) { theErrorStatus++; if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimCoarseGridModel::loadCoarseGrid: Error encountered opening coarse grid file <" << cgFileName << ">. Check that the file exists and is readable." << std::endl; } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "CEBUG ossimCoarseGridModel::loadCoarseGrid: returning with error..." << std::endl; return false; } theGridFilename = cgFileName; if(theDlatDparamGrid) { delete [] theDlatDparamGrid; theDlatDparamGrid = NULL; } if(theDlonDparamGrid) { delete [] theDlonDparamGrid; theDlonDparamGrid = NULL; } // // Reallocate memory: // int numberOfParams = getNumberOfAdjustableParameters(); if(numberOfParams) { theDlatDparamGrid = new ossimDblGrid [numberOfParams]; theDlonDparamGrid = new ossimDblGrid [numberOfParams]; } //*** // Let each grid object read itself from the input file: //*** if (!theLatGrid.load(instream)) { ++theErrorStatus; return false; } if (!theLonGrid.load(instream)) { ++theErrorStatus; return false; } if (!theDlatDhGrid.load(instream)) { ++theErrorStatus; return false; } if (!theDlonDhGrid.load(instream)) { ++theErrorStatus; return false; } for (int p=0; p\n" << endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimCoarseGridModel::writeGeomTemplate: returning..." << std::endl; return; } //************************************************************************************************* // Overrides base-class extrapolation code. Uses extrapolation inherent to ossimDbleGrid //************************************************************************************************* ossimGpt ossimCoarseGridModel::extrapolate(const ossimDpt& local_ip, const double& height) const { ossimGpt gpt; lineSampleHeightToWorld(local_ip, height, gpt); return gpt; } bool ossimCoarseGridModel::isAffectedByElevation() const { return theHeightEnabledFlag; } ossim-Miami-2.9.1/src/projection/ossimCylEquAreaProjection.cpp000066400000000000000000000367531352751253100245030ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Cylinder Equal Area projection code. //******************************************************************* // $Id: ossimCylEquAreaProjection.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include RTTI_DEF1(ossimCylEquAreaProjection, "ossimCylEquAreaProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #define CYEQ_NO_ERROR 0x0000 #define CYEQ_LAT_ERROR 0x0001 #define CYEQ_LON_ERROR 0x0002 #define CYEQ_EASTING_ERROR 0x0004 #define CYEQ_NORTHING_ERROR 0x0008 #define CYEQ_ORIGIN_LAT_ERROR 0x0010 #define CYEQ_CENT_MER_ERROR 0x0020 #define CYEQ_A_ERROR 0x0040 #define CYEQ_B_ERROR 0x0080 #define CYEQ_A_LESS_B_ERROR 0x0100 /***************************************************************************/ /* * DEFINES */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define CYLEQAR_Q(slat, x) (1.0-es2)*(slat/(1.0-x*x)-(1.0/(2.0*es))* \ log((1.0-x)/(1.0+x))) #define CYEQ_COEFF_TIMES_SIN(coeff, c, Beta) (coeff * sin(c * Beta)) #define ONE (1.0 * M_PI / 180.0) /* 1 degree in radians */ ossimCylEquAreaProjection::ossimCylEquAreaProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimCylEquAreaProjection::ossimCylEquAreaProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Cyeq_False_Easting = falseEasting; Cyeq_False_Northing = falseNorthing; Cyeq_Max_Easting = 20037509.0; Cyeq_Min_Easting = -20037509.0; Cyeq_Delta_Northing = 6363886.0; update(); } void ossimCylEquAreaProjection::setFalseEasting(double falseEasting) { Cyeq_False_Easting = falseEasting; update(); } void ossimCylEquAreaProjection::setFalseNorthing(double falseNorthing) { Cyeq_False_Northing = falseNorthing; update(); } void ossimCylEquAreaProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Cyeq_False_Easting = falseEasting; Cyeq_False_Northing = falseNorthing; update(); } void ossimCylEquAreaProjection::setDefaults() { Cyeq_False_Easting = 0.0; Cyeq_False_Northing = 0.0; Cyeq_Max_Easting = 20037509.0; Cyeq_Min_Easting = -20037509.0; Cyeq_Delta_Northing = 6363886.0; } void ossimCylEquAreaProjection::update() { Cyeq_Max_Easting = 20037509.0; Cyeq_Min_Easting = -20037509.0; Cyeq_Delta_Northing = 6363886.0; Set_Cyl_Eq_Area_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Cyeq_False_Easting, Cyeq_False_Northing); theFalseEastingNorthing.x = Cyeq_False_Easting; theFalseEastingNorthing.y = Cyeq_False_Northing; ossimMapProjection::update(); } ossimGpt ossimCylEquAreaProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Cyl_Eq_Area_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0, theDatum); } ossimDpt ossimCylEquAreaProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Cyl_Eq_Area(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimCylEquAreaProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimCylEquAreaProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimCylEquAreaProjection)) { Cyeq_False_Easting = theFalseEastingNorthing.x; Cyeq_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimCylEquAreaProjection::Set_Cyl_Eq_Area_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing) { /* Begin Set_Cyl_Eq_Area_Parameters */ /* * The function Set_Cyl_Eq_Area_Parameters receives the ellipsoid parameters and * Cylindrical Equal Area projcetion parameters as inputs, and sets the corresponding * state variables. If any errors occur, the error code(s) are returned by the * function, otherwise CYEQ_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double Sin_Cyeq_Origin_Lat; double temp; // double inv_f = 1 / f; long Error_Code = CYEQ_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= CYEQ_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= CYEQ_INV_F_ERROR; // } // if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) // { /* origin latitude out of range */ // Error_Code |= CYEQ_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= CYEQ_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Cyeq_a = a; Cyeq_f = f; Cyeq_Origin_Lat = Origin_Latitude; if (Central_Meridian > M_PI) Central_Meridian -= TWO_PI; Cyeq_Origin_Long = Central_Meridian; Cyeq_False_Northing = False_Northing; Cyeq_False_Easting = False_Easting; es2 = 2 * Cyeq_f - Cyeq_f * Cyeq_f; es4 = es2 * es2; es6 = es4 * es2; es = sqrt(es2); c0 = es2 / 3.0 + 31.0 * es4 / 180.0 + 517.0 * es6 / 5040.0; c1 = 23.0 * es4 / 360.0 + 251.0 * es6 / 3780.0; c2 = 761.0 * es6 / 45360.0; Sin_Cyeq_Origin_Lat = sin(Cyeq_Origin_Lat); k0 = cos(Cyeq_Origin_Lat) / sqrt(1.0 - es2 * Sin_Cyeq_Origin_Lat * Sin_Cyeq_Origin_Lat); Cyeq_a_k0 = Cyeq_a * k0; two_k0 = 2.0 * k0; if (Cyeq_Origin_Long > 0) { Convert_Geodetic_To_Cyl_Eq_Area(PI_OVER_2, Cyeq_Origin_Long - M_PI - ONE, &Cyeq_Max_Easting, &temp); Convert_Geodetic_To_Cyl_Eq_Area(PI_OVER_2, Cyeq_Origin_Long - M_PI, &Cyeq_Min_Easting, &temp); Convert_Geodetic_To_Cyl_Eq_Area(PI_OVER_2, M_PI, &temp, &Cyeq_Delta_Northing); } else if (Cyeq_Origin_Long < 0) { Convert_Geodetic_To_Cyl_Eq_Area(PI_OVER_2, Cyeq_Origin_Long + M_PI, &Cyeq_Max_Easting, &temp); Convert_Geodetic_To_Cyl_Eq_Area(PI_OVER_2, Cyeq_Origin_Long + M_PI + ONE, &Cyeq_Min_Easting, &temp); Convert_Geodetic_To_Cyl_Eq_Area(PI_OVER_2, M_PI, &temp, &Cyeq_Delta_Northing); } else { Convert_Geodetic_To_Cyl_Eq_Area(PI_OVER_2, M_PI, &Cyeq_Max_Easting, &Cyeq_Delta_Northing); Cyeq_Min_Easting = -Cyeq_Max_Easting; } } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Cyl_Eq_Area_Parameters */ void ossimCylEquAreaProjection::Get_Cyl_Eq_Area_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Cyl_Eq_Area_Parameters */ /* * The function Get_Cyl_Eq_Area_Parameters returns the current ellipsoid * parameters, and Cylindrical Equal Area projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Cyeq_a; *f = Cyeq_f; *Origin_Latitude = Cyeq_Origin_Lat; *Central_Meridian = Cyeq_Origin_Long; *False_Easting = Cyeq_False_Easting; *False_Northing = Cyeq_False_Northing; return; } /* End Get_Cyl_Eq_Area_Parameters */ long ossimCylEquAreaProjection::Convert_Geodetic_To_Cyl_Eq_Area (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Cyl_Eq_Area */ /* * The function Convert_Geodetic_To_Cyl_Eq_Area converts geodetic (latitude and * longitude) coordinates to Cylindrical Equal Area projection (easting and northing) * coordinates, according to the current ellipsoid and Cylindrical Equal Area projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise CYEQ_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double dlam; /* Longitude - Central Meridan */ double qq; double x; double sin_lat = sin(Latitude); long Error_Code = CYEQ_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= CYEQ_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= CYEQ_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Cyeq_Origin_Long; // if (dlam > PI) // { // dlam -= TWO_PI; // } // if (dlam < -PI) // { // dlam += TWO_PI; // } x = es * sin_lat; qq = CYLEQAR_Q(sin_lat,x); *Easting = Cyeq_a_k0 * dlam + Cyeq_False_Easting; *Northing = Cyeq_a * qq / two_k0 + Cyeq_False_Northing; } return (Error_Code); } /* End Convert_Geodetic_To_Cyl_Eq_Area */ long ossimCylEquAreaProjection::Convert_Cyl_Eq_Area_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Cyl_Eq_Area_To_Geodetic */ /* * The function Convert_Cyl_Eq_Area_To_Geodetic converts * Cylindrical Equal Area projection (easting and northing) coordinates * to geodetic (latitude and longitude) coordinates, according to the * current ellipsoid and Cylindrical Equal Area projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise CYEQ_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double sin2beta, sin4beta, sin6beta; double dx; /* Delta easting - Difference in easting (easting-FE) */ double dy; /* Delta northing - Difference in northing (northing-FN) */ double qp; double beta; double sin_lat = sin(PI_OVER_2); double i; double x; long Error_Code = CYEQ_NO_ERROR; // if ((Easting < (Cyeq_False_Easting + Cyeq_Min_Easting)) // || (Easting > (Cyeq_False_Easting + Cyeq_Max_Easting))) // { /* Easting out of range */ // Error_Code |= CYEQ_EASTING_ERROR; // } // if ((Northing < (Cyeq_False_Northing - fabs(Cyeq_Delta_Northing))) // || (Northing > (Cyeq_False_Northing + fabs(Cyeq_Delta_Northing)))) // { /* Northing out of range */ // Error_Code |= CYEQ_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ dy = Northing - Cyeq_False_Northing; dx = Easting - Cyeq_False_Easting; x = es * sin_lat; qp = CYLEQAR_Q(sin_lat,x); i = two_k0 * dy / (Cyeq_a * qp); if (i > 1.0) i = 1.0; else if (i < -1.0) i = -1.0; beta = asin(i); sin2beta = CYEQ_COEFF_TIMES_SIN(c0, 2.0, beta); sin4beta = CYEQ_COEFF_TIMES_SIN(c1, 4.0, beta); sin6beta = CYEQ_COEFF_TIMES_SIN(c2, 6.0, beta); *Latitude = beta + sin2beta + sin4beta + sin6beta; *Longitude = Cyeq_Origin_Long + dx / Cyeq_a_k0; // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; // if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ // *Longitude = PI; // else if (*Longitude < -PI) // *Longitude = -PI; } return (Error_Code); } /* End Convert_Cyl_Eq_Area_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimEckert4Projection.cpp000066400000000000000000000331771352751253100240060ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Eckert4 projection code. //******************************************************************* // $Id: ossimEckert4Projection.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include RTTI_DEF1(ossimEckert4Projection, "ossimEckert4Projection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define NUM(Theta, SinTheta, CosTheta) (Theta + SinTheta * CosTheta + 2.0 * SinTheta) #define ECK4_NO_ERROR 0x0000 #define ECK4_LAT_ERROR 0x0001 #define ECK4_LON_ERROR 0x0002 #define ECK4_EASTING_ERROR 0x0004 #define ECK4_NORTHING_ERROR 0x0008 #define ECK4_CENT_MER_ERROR 0x0020 #define ECK4_A_ERROR 0x0040 #define ECK4_B_ERROR 0x0080 #define ECK4_A_LESS_B_ERROR 0x0100 /***************************************************************************/ /* * GLOBALS */ const double two_PLUS_PI_OVER_2 = (2.0 + M_PI / 2.0); ossimEckert4Projection::ossimEckert4Projection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimEckert4Projection::ossimEckert4Projection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Eck4_False_Easting = falseEasting; Eck4_False_Northing = falseNorthing; Eck4_Delta_Northing = 8451144.0; Eck4_Max_Easting = 16902288.0; Eck4_Min_Easting = -16902288.0; update(); } void ossimEckert4Projection::update() { Set_Eckert4_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.lonr(), Eck4_False_Easting, Eck4_False_Northing); theFalseEastingNorthing.x = Eck4_False_Easting; theFalseEastingNorthing.y = Eck4_False_Northing; ossimMapProjection::update(); } ossimGpt ossimEckert4Projection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Eckert4_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimEckert4Projection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Eckert4(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } void ossimEckert4Projection::setFalseEasting(double falseEasting) { Eck4_False_Easting = falseEasting; update(); } void ossimEckert4Projection::setFalseNorthing(double falseNorthing) { Eck4_False_Northing = falseNorthing; update(); } void ossimEckert4Projection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Eck4_False_Easting = falseEasting; Eck4_False_Northing = falseNorthing; update(); } void ossimEckert4Projection::setDefaults() { Eck4_Delta_Northing = 8451144.0; Eck4_Max_Easting = 16902288.0; Eck4_Min_Easting = -16902288.0; Eck4_False_Easting = 0.0; Eck4_False_Northing = 0.0; } bool ossimEckert4Projection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimEckert4Projection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimEckert4Projection)) { Eck4_False_Easting = theFalseEastingNorthing.x; Eck4_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimEckert4Projection::Set_Eckert4_Parameters(double a, double f, double Central_Meridian, double False_Easting, double False_Northing) { /* Begin Set_Eckert4_Parameters */ /* * The function Set_Eckert4_Parameters receives the ellipsoid parameters and * projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the * function, otherwise ECK4_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double Ra; /* Spherical radius */ // double inv_f = 1 / f; long Error_Code = ECK4_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= ECK4_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= ECK4_INV_F_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= ECK4_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Eck4_a = a; Eck4_f = f; es2 = 2 * Eck4_f - Eck4_f * Eck4_f; es4 = es2 * es2; es6 = es4 * es2; /* spherical radius */ Ra = Eck4_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 / 3024.0); Ra0 = 0.4222382 * Ra; Ra1 = 1.3265004 * Ra; // if (Central_Meridian > PI) // Central_Meridian -= TWO_PI; Eck4_Origin_Long = Central_Meridian; Eck4_False_Easting = False_Easting; Eck4_False_Northing = False_Northing; if (Eck4_Origin_Long > 0) { Eck4_Max_Easting = 16808386.0; Eck4_Min_Easting = -16902288.0; } else if (Eck4_Origin_Long < 0) { Eck4_Max_Easting = 16902288.0; Eck4_Min_Easting = -16808386.0; } else { Eck4_Max_Easting = 16902288.0; Eck4_Min_Easting = -16902288.0; } } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Eckert4_Parameters */ void ossimEckert4Projection::Get_Eckert4_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Eckert4_Parameters */ /* * The function Get_Eckert4_Parameters returns the current ellipsoid * parameters and Eckert IV projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Eck4_a; *f = Eck4_f; *Central_Meridian = Eck4_Origin_Long; *False_Easting = Eck4_False_Easting; *False_Northing = Eck4_False_Northing; return; } /* End Get_Eckert4_Parameters */ long ossimEckert4Projection::Convert_Geodetic_To_Eckert4 (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Eckert4 */ /* * The function Convert_Geodetic_To_Eckert4 converts geodetic (latitude and * longitude) coordinates to Eckert IV projection (easting and northing) * coordinates, according to the current ellipsoid, spherical radius and * Eckert IV projection parameters. * If any errors occur, the error code(s) are returned by the * function, otherwise ECK4_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double slat = sin(Latitude); double sin_theta, cos_theta; double num; double dlam; /* Longitude - Central Meridan */ double theta = Latitude / 2.0; double delta_theta = 1.0; double dt_tolerance = 4.85e-10; /* approximately 1/1000th of an arc second or 1/10th meter */ long Error_Code = ECK4_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= ECK4_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code|= ECK4_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Eck4_Origin_Long; // if (dlam > PI) // { // dlam -= TWO_PI; // } // if (dlam < -PI) // { // dlam += TWO_PI; // } while (fabs(delta_theta) > dt_tolerance) { sin_theta = sin(theta); cos_theta = cos(theta); num = NUM(theta, sin_theta, cos_theta); delta_theta = -(num - two_PLUS_PI_OVER_2 * slat) / (2.0 * cos_theta * (1.0 + cos_theta)); theta += delta_theta; } *Easting = Ra0 * dlam * (1.0 + cos(theta)) + Eck4_False_Easting; *Northing = Ra1 * sin(theta) + Eck4_False_Northing; } return (Error_Code); } /* End Convert_Geodetic_To_Eckert4 */ long ossimEckert4Projection::Convert_Eckert4_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Eckert4_To_Geodetic */ /* * The function Convert_Eckert4_To_Geodetic converts Eckert IV projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid, spherical radius and * Eckert IV projection coordinates. * If any errors occur, the error code(s) are returned by the * function, otherwise ECK4_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double theta; double sin_theta, cos_theta; double num; double dx, dy; double i; long Error_Code = ECK4_NO_ERROR; // if ((Easting < (Eck4_False_Easting + Eck4_Min_Easting)) // || (Easting > (Eck4_False_Easting + Eck4_Max_Easting))) // { /* Easting out of range */ // Error_Code |= ECK4_EASTING_ERROR; // } // if ((Northing < (Eck4_False_Northing - Eck4_Delta_Northing)) // || (Northing > (Eck4_False_Northing + Eck4_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= ECK4_NORTHING_ERROR; // } if (!Error_Code) { dy = Northing - Eck4_False_Northing; dx = Easting - Eck4_False_Easting; i = dy / Ra1; if (i > 1.0) i = 1.0; else if (i < -1.0) i = -1.0; theta = asin(i); sin_theta = sin(theta); cos_theta = cos(theta); num = NUM(theta, sin_theta, cos_theta); *Latitude = asin(num / two_PLUS_PI_OVER_2); *Longitude = Eck4_Origin_Long + dx / (Ra0 * (1 + cos_theta)); // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; // if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ // *Longitude = PI; // else if (*Longitude < -PI) // *Longitude = -PI; } return (Error_Code); } /* End Convert_Eckert4_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimEckert6Projection.cpp000066400000000000000000000331771352751253100240100ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Eckert6 projection code. //******************************************************************* // $Id: ossimEckert6Projection.cpp 17815 2010-08-03 13:23:14Z dburken $ /***************************************************************************/ /* * DEFINES */ #include #include RTTI_DEF1(ossimEckert6Projection, "ossimEckert6Projection", ossimMapProjection) #define ECK6_NO_ERROR 0x0000 #define ECK6_LAT_ERROR 0x0001 #define ECK6_LON_ERROR 0x0002 #define ECK6_EASTING_ERROR 0x0004 #define ECK6_NORTHING_ERROR 0x0008 #define ECK6_CENT_MER_ERROR 0x0020 #define ECK6_A_ERROR 0x0040 #define ECK6_B_ERROR 0x0080 #define ECK6_A_LESS_B_ERROR 0x0100 #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define MAX_LAT ( (M_PI * 90.0) / 180.0 ) /* 90 degrees in radians */ /***************************************************************************/ /* * GLOBALS */ const double one_PLUS_PI_OVER_2 = (1.0 + M_PI / 2.0); ossimEckert6Projection::ossimEckert6Projection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); } ossimEckert6Projection::ossimEckert6Projection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Eck6_False_Easting = falseEasting; Eck6_False_Northing = falseNorthing; Eck6_Delta_Northing = 8451144.0; Eck6_Max_Easting = 16902288.0; Eck6_Min_Easting = -16902288.0; update(); } void ossimEckert6Projection::update() { Set_Eckert6_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.lonr(), Eck6_False_Easting, Eck6_False_Northing); theFalseEastingNorthing.x = Eck6_False_Easting; theFalseEastingNorthing.y = Eck6_False_Northing; ossimMapProjection::update(); } ossimGpt ossimEckert6Projection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Eckert6_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimEckert6Projection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Eckert6(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } void ossimEckert6Projection::setFalseEasting(double falseEasting) { Eck6_False_Easting = falseEasting; update(); } void ossimEckert6Projection::setFalseNorthing(double falseNorthing) { Eck6_False_Northing = falseNorthing; update(); } void ossimEckert6Projection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Eck6_False_Easting = falseEasting; Eck6_False_Northing = falseNorthing; update(); } void ossimEckert6Projection::setDefaults() { Eck6_Delta_Northing = 8451144.0; Eck6_Max_Easting = 16902288.0; Eck6_Min_Easting = -16902288.0; Eck6_False_Easting = 0.0; Eck6_False_Northing = 0.0; update(); } void ossimEckert6Projection::setCentralMeridian(double centralMeridian) { Eck6_Origin_Long = centralMeridian; update(); } bool ossimEckert6Projection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimEckert6Projection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimEckert6Projection)) { Eck6_False_Easting = theFalseEastingNorthing.x; Eck6_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimEckert6Projection::Set_Eckert6_Parameters(double a, double f, double Central_Meridian, double False_Easting, double False_Northing) { /* Begin Set_Eckert6_Parameters */ /* * The function Set_Eckert6_Parameters receives the ellipsoid parameters and * Eckert VI projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the * function, otherwise ECK6_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double Ra; /* Spherical radius */ // double inv_f = 1 / f; long Error_Code = ECK6_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= ECK6_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= ECK6_INV_F_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= ECK6_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Eck6_a = a; Eck6_f = f; es2 = 2 * Eck6_f - Eck6_f * Eck6_f; es4 = es2 * es2; es6 = es4 * es2; /* spherical radius */ Ra = Eck6_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 /3024.0); Ra_Over_Sqrt_Two_Plus_PI = Ra / (sqrt(2.0 + M_PI)); Inv_Ra_Over_Sqrt_Two_Plus_PI = 1 / Ra_Over_Sqrt_Two_Plus_PI; // if (Central_Meridian > PI) // Central_Meridian -= TWO_PI; Eck6_Origin_Long = Central_Meridian; Eck6_False_Easting = False_Easting; Eck6_False_Northing = False_Northing; if (Eck6_Origin_Long > 0) { Eck6_Max_Easting = 17555761.0; Eck6_Min_Easting = -17653839.0; } else if (Eck6_Origin_Long < 0) { Eck6_Max_Easting = 17653838.0; Eck6_Min_Easting = -17555761.0; } else { Eck6_Max_Easting = 17653838.0; Eck6_Min_Easting = -17653838.0; } } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Eckert6_Parameters */ void ossimEckert6Projection::Get_Eckert6_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Eckert6_Parameters */ /* * The function Get_Eckert6_Parameters returns the current ellipsoid * parameters and Eckert VI projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Eck6_a; *f = Eck6_f; *Central_Meridian = Eck6_Origin_Long; *False_Easting = Eck6_False_Easting; *False_Northing = Eck6_False_Northing; return; } /* End Get_Eckert6_Parameters */ long ossimEckert6Projection::Convert_Geodetic_To_Eckert6 (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Eckert6 */ /* * The function Convert_Geodetic_To_Eckert6 converts geodetic (latitude and * longitude) coordinates to Eckert VI projection (easting and northing) * coordinates, according to the current ellipsoid and Eckert VI projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise ECK6_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double slat = sin(Latitude); double dlam; /* Longitude - Central Meridan */ double theta = Latitude; double delta_theta = 1.0; double dt_tolerance = 4.85e-10; /* approximately 1/1000th of an arc second or 1/10th meter */ long Error_Code = ECK6_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= ECK6_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code|= ECK6_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Eck6_Origin_Long; // if (dlam > PI) // { // dlam -= TWO_PI; // } // if (dlam < -PI) // { // dlam += TWO_PI; // } while (fabs(delta_theta) > dt_tolerance) { delta_theta = -(theta + sin(theta) - one_PLUS_PI_OVER_2 * slat) / (1.0 + cos(theta)); theta += delta_theta; } *Easting = Ra_Over_Sqrt_Two_Plus_PI * dlam * (1.0 + cos(theta)) + Eck6_False_Easting; *Northing = 2.0 * Ra_Over_Sqrt_Two_Plus_PI * theta + Eck6_False_Northing; } return (Error_Code); } /* End Convert_Geodetic_To_Eckert6 */ long ossimEckert6Projection::Convert_Eckert6_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Eckert6_To_Geodetic */ /* * The function Convert_Eckert6_To_Geodetic converts Eckert VI projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Eckert VI projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise ECK6_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx, dy; double theta; double i; long Error_Code = ECK6_NO_ERROR; // if ((Easting < (Eck6_False_Easting + Eck6_Min_Easting)) // || (Easting > (Eck6_False_Easting + Eck6_Max_Easting))) // { /* Easting out of range */ // Error_Code |= ECK6_EASTING_ERROR; // } // if ((Northing < (Eck6_False_Northing - Eck6_Delta_Northing)) // || (Northing > (Eck6_False_Northing + Eck6_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= ECK6_NORTHING_ERROR; // } if (!Error_Code) { dy = Northing - Eck6_False_Northing; dx = Easting - Eck6_False_Easting; theta = Inv_Ra_Over_Sqrt_Two_Plus_PI * dy / 2.0; i = (theta + sin(theta)) / one_PLUS_PI_OVER_2; if (i > 1.0) *Latitude = MAX_LAT; else if (i < -1.0) *Latitude = -MAX_LAT; else *Latitude = asin(i); *Longitude = Eck6_Origin_Long + Inv_Ra_Over_Sqrt_Two_Plus_PI * dx / (1 + cos(theta)); // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; // if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ // *Longitude = PI; // else if (*Longitude < -PI) // *Longitude = -PI; } return (Error_Code); } /* End Convert_Eckert6_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimEnviCgModel.cpp000066400000000000000000000111501352751253100225670ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimCoarseGridModel.cc // // License: See LICENSE.txt file in the top level directory. // // AUTHOR: Oscar Kramer // // DESCRIPTION: // Contains implementation of class ossimCoarseGridModel. This is an // implementation of an interpolation sensor model. // // IMPORTANT: The lat/lon grid is for ground points on the ellipsoid. // The dLat/dHgt and dLon/dHgt partials therefore are used against // elevations relative to the ellipsoid. // //***************************************************************************** // $Id: ossimCoarseGridModel.cpp 22825 2014-07-07 23:14:52Z dburken $ #include RTTI_DEF1(ossimEnviCgModel, "ossimEnviCgModel", ossimCoarseGridModel); #include #include #include #include #include using namespace std; static const char* MODEL_TYPE = "ossimEnviCgModel"; //***************************************************************************** ossimEnviCgModel::ossimEnviCgModel() : ossimCoarseGridModel() {} //***************************************************************************** ossimEnviCgModel::ossimEnviCgModel(const ossimFilename& geoc_file) : ossimCoarseGridModel() { loadEnviGeocFile(geoc_file); } //***************************************************************************** bool ossimEnviCgModel::loadEnviGeocFile(const ossimFilename& geoc_file) { theHeightEnabledFlag = false; setErrorStatus(); ossimFilename geoc_hdr (geoc_file + ".hdr"); ifstream geocHdrStream (geoc_hdr.c_str()); if (geocHdrStream.fail()) { cout << "ossimEnviCgModel:loadEnviGeocFile() Error encountered opening GEOC header file <"<"< missing \"ENVI\" magic number."< strSplit; if (oline.contains("samples")) imageSize.x = oline.after("=").trim().toInt(); else if (oline.contains("lines")) imageSize.y = oline.after("=").trim().toInt(); else if (oline.contains("byte order")) bigEndian = oline.after("=").trim().toInt(); } ossimDpt gridOrigin(0,0); ifstream geocStream (geoc_file.c_str(), ios_base::binary|ios_base::in); if (geocStream.fail()) { cout << "ossimEnviCgModel:Ctor Error encountered opening GEOC file <"<"<(&value) , sizeof(double) ); if (bigEndian) { char * pc = reinterpret_cast(&value); std::swap(pc[0], pc[7]); std::swap(pc[1], pc[6]); std::swap(pc[2], pc[5]); std::swap(pc[3], pc[4]); cout< #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //ossimEpsgProjectionDatabase* ossimEpsgProjectionDatabase::m_instance = 0; // Indexes into the DB file fields using "SPADAC EPSG" format (format "A"). // IF THE LINE FIELDS CHANGE ORDER, THIS LIST WILL NEED TO BE CHANGED TO REFLECT THE NEW ORDER! enum { A_CODE = 0, // This is the EPSG code A_NAME, A_PROJ_TYPE, A_UNITS, A_DATUM_CODE, A_DATUM_NAME, A_ELLIPSOID_NAME, A_FALSE_EASTING, A_NAT_ORG_LAT, A_FALSE_NORTHING, A_NAT_ORG_LON, A_NAT_ORG_SCALE, A_INIT_LINE_AZ, A_PROJ_CTR_LAT, A_PROJ_CTR_NORTHING, A_RECT_TO_SKEW_ANGLE, A_INIT_LINE_SCALE, A_PROJ_CTR_EASTING, A_PROJ_CTR_LON, A_PSEUDO_STD_PARL_1, A_PSEUDO_STD_PARL_1_SCALE, A_ORG_LON, A_STD_PARL_2_LAT, A_FALSE_ORG_LAT, A_FALSE_ORG_LON, A_STD_PARL_1_LAT, A_FALSE_ORG_NORTHING, A_FALSE_ORG_EASTING, A_STD_PARL_LAT, A_TOPOCTR_HGT, A_TOPOCTR_LAT, A_TOPOCTR_Z, A_TOPOCTR_Y, A_TOPOCTR_X, A_VIEWPOINT_H, A_INIT_LON, A_ZONE_WIDTH, A_NUM_FIELDS // Not an index, but a count }; static const ossimString EPSG_DB_FORMAT_A ("EPSG_DB_FORMAT_A"); // State Plane database CSV file field format (format "B") // NOTE: Eventually, all EPSG-coded projections, including State Plane/HARN should be specified // in the EPSG database format. Presently there is a disconnect between Geotrans params and EPSG-Db // params, particularly regarding datums, that makes a purely EPSG-Db solution too awkward to // implement, so provision is made here to continue reading the state plane CSV files. enum { B_NAME = 0, B_CODE, // This is the EPSG code B_PROJ_TYPE, B_PARAM1, B_PARAM2, B_PARAM3, B_PARAM4, B_FALSE_EASTING, B_FALSE_NORTHING, B_UNITS, B_DATUM_CODE, B_NUM_FIELDS // Not an index, but a count }; static const ossimString STATE_PLANE_FORMAT_B ("STATE_PLANE"); // "Ming Special" database CSV file format (format "C") // State Plane Coordinate System (SPCS) coding is an alternate coding scheme that maps to EPSG. // http://www.pcigeomatics.com/cgi-bin/pcihlp/PROJ%7CSPCS+ZONES enum { C_NAME = 0, C_CODE, C_NUM_FIELDS // Not an index, but a count }; static const ossimString SPCS_EPSG_MAP_FORMAT_C ("SPCS_EPSG_MAP"); //************************************************************************************************* //! Converts sexagesimal DMS to decimal degrees //************************************************************************************************* double decodeSexagesimalDms(const ossimString& sex_str) { if (!sex_str.contains(".")) return sex_str.toDouble(); double sign = 1.0; if (sex_str.chars()[0] == '-') sign = -1.0; double dsex, msex, ssex; std::vector splitstr = sex_str.split("."); dsex = splitstr[0].toDouble(); if (splitstr.size() < 2) return dsex; const char* MMSSssstr = splitstr[1].chars(); unsigned int str_size = (unsigned int) splitstr[1].size(); char minstr[] = "00"; ossimString secstr ("00."); minstr[0] = MMSSssstr[0]; if (str_size > 1) { minstr[1] = MMSSssstr[1]; if (str_size > 2) { secstr = &(MMSSssstr[2]); if (str_size == 3) secstr += ossimString("0."); else if (str_size > 4) secstr.insert(2, "."); } } msex = ossimString(minstr).toDouble(); ssex = secstr.toDouble(); dsex += sign*(msex + ssex/60.0)/60.0; return dsex; } //************************************************************************************************* //! Implements singleton pattern //************************************************************************************************* ossimEpsgProjectionDatabase* ossimEpsgProjectionDatabase::instance() { static ossimEpsgProjectionDatabase inst; return &inst; //if(!m_instance) // m_instance = new ossimEpsgProjectionDatabase; //return m_instance; } //************************************************************************************************* //! Destructor //************************************************************************************************* ossimEpsgProjectionDatabase::~ossimEpsgProjectionDatabase() { } //************************************************************************************************* //! Constructor loads all DB CSV files specified in the ossim prefs //************************************************************************************************* ossimEpsgProjectionDatabase::ossimEpsgProjectionDatabase() : m_projDatabase(), m_mutex() { } //************************************************************************************************* //! Populates the database with contents of DB files as specified in ossim_preferences. //************************************************************************************************* void ossimEpsgProjectionDatabase::initialize() const { // Fetch filenames of all projection DB files from the share directory specified in // ossim_preferences: // Optional ossim share dir: ossimFilename share_dir = ossimPreferences::instance()-> preferencesKWL().findKey( std::string( "ossim_share_directory" ) ); ossimString regEx = ossimString("^epsg_database_file[0-9]+"); vector keys = ossimPreferences::instance()->preferencesKWL().getSubstringKeyList(regEx); vector::const_iterator i = keys.begin(); // Create only once outside the loop: ossimFilename epsg_path; ossimFilename db_name; ossimString group_id; ossimString format_id; ossimString line; // Loop over each file and read contents into memory: while ( i != keys.end() ) { db_name.clear(); epsg_path = ossimPreferences::instance()->preferencesKWL().findKey( (*i).string() ); if ( epsg_path.size() ) { if ( !epsg_path.isRelative() ) { //--- // example: // epsg_database_file0:/usr/share/ossim/projection/ossim_epsg_projections-v7_4.csv //--- db_name = epsg_path; } else if ( share_dir.size() ) { //--- // example: // ossim_share_dir: /usr/share/ossim // epsg_database_file0: projection/ossim_epsg_projections-v7_4.csv //--- db_name = share_dir.dirCat( epsg_path ); //--- // This block is for backwards compatibility. // Try tacking "projection" onto share dir. //--- if ( !db_name.isReadable() ) { db_name = share_dir.dirCat( ossimFilename("projection") ); db_name = db_name.dirCat( epsg_path); // Lastly: Try tacking "ossim/projection" onto share dir. if ( !db_name.isReadable() ) { db_name = share_dir.dirCat( ossimFilename("ossim/projection") ); db_name = db_name.dirCat( epsg_path); } } } } ++i; if (!db_name.isReadable()) { continue; } // Open the DB file: std::ifstream db_stream (db_name.chars()); bool good_file = false; if (db_stream.good()) { // Format specification implied in file's magic number: std::getline(db_stream, format_id.string()); format_id.trim(); if ((format_id == EPSG_DB_FORMAT_A) || (format_id == STATE_PLANE_FORMAT_B) || (format_id == SPCS_EPSG_MAP_FORMAT_C)) good_file = true; } if (!good_file) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimEpsgProjectionDatabase::initialize() -- " "Encountered bad database file <"<. Skipping this file."< db_record = new ProjDbRecord; std::getline(db_stream, line.string()); db_record->csvRecord = line.explode(","); // ONLY CSV FILES CONSIDERED HERE if (db_record->csvRecord.size()) { // Check if primary EPSG database format A: if (format_id == EPSG_DB_FORMAT_A) { db_record->code = db_record->csvRecord[A_CODE].toUInt32(); db_record->name = db_record->csvRecord[A_NAME]; db_record->csvFormat = FORMAT_A; } // Check if State Plane (subset of EPSG but handled differently until projection // geotrans-EPSG disconnect is resolved. else if (format_id == STATE_PLANE_FORMAT_B) { db_record->code = db_record->csvRecord[B_CODE].toUInt32(); db_record->name = db_record->csvRecord[B_NAME]; db_record->csvFormat = FORMAT_B; } // This format is for Ming-special State Plane Coordinate System coded format. // This format is simply a mapping from SPCS spec name (OSSIM-specific) to EPSG code. // Note that no proj is instantiated and no KWL is populated. Only name and EPSG mapped // code is saved. else if (format_id == SPCS_EPSG_MAP_FORMAT_C) { db_record->code = db_record->csvRecord[C_CODE].toUInt32(); db_record->name = db_record->csvRecord[C_NAME]; db_record->csvFormat = FORMAT_C; } m_projDatabase.insert(make_pair(db_record->code, db_record)); } } db_stream.close(); } // end of while loop over all DB files } //************************************************************************************************* //! Returns a projection corresponding to the group (e.g., "EPSG") and PCS code provided, //! or NULL if no entry found. //************************************************************************************************* ossimProjection* ossimEpsgProjectionDatabase::findProjection(ossim_uint32 epsg_code) const { ossimMapProjection* proj = 0; // Quick check for bogus EPSG: if ((epsg_code == 0) || (epsg_code == 32767)) return 0; // Check for Google projection: else if (( epsg_code==3857) || (epsg_code == 900913)) { proj = new ossimGoogleProjection(); // Set this for saveState: proj->setPcsCode( 3857 ); /* const ossimDatum* datum = ossimDatumFactory::instance()->create(ossimString("6055")); ossimMercatorProjection* merc_proj = new ossimMercatorProjection(); ossimGpt origin(0.0,0.0,0.0, datum); merc_proj->setFalseEasting(0.0); merc_proj->setFalseNorthing(0.0); merc_proj->setOrigin(origin); // Also sets the projections datum to the origin's datum merc_proj->update(); merc_proj->setPcsCode(900913); proj = merc_proj; */ } else { // Search database for entry: m_mutex.lock(); if (m_projDatabase.empty()) { initialize(); } m_mutex.unlock(); std::multimap >::iterator db_iter = m_projDatabase.find(epsg_code); if (db_iter != m_projDatabase.end()) { // See if a projection has already been created for this entry: m_mutex.lock(); ossimRefPtr db_record = db_iter->second; if ( db_record.valid() ) { if (db_record->proj.valid()) proj = (ossimMapProjection*) db_record->proj->dup(); else { // Try decoding the EPSG code before accessing DB: proj = createProjFromUtmCode(epsg_code); if (proj) { db_record->proj = proj; db_record->datumValid = true; } else if (db_iter->second->csvFormat == FORMAT_A) { proj = createProjFromFormatARecord( db_record.get() ); } else if (db_iter->second->csvFormat == FORMAT_B) { proj = createProjFromFormatBRecord( db_record.get() ); } if (proj) { // To save allocated memory, get rid of the original CSV entry since a real // projection is now represented in the database: db_record->csvRecord.clear(); db_record->csvFormat = NOT_ASSIGNED; } } } // Matches: if ( db_record.valid() ) m_mutex.unlock(); } } return proj; } //************************************************************************************************* //! Returns a projection corresponding to the group (e.g., "EPSG") and PCS code provided, //! or NULL if no entry found. //************************************************************************************************* ossimProjection* ossimEpsgProjectionDatabase::findProjection(const ossimString& spec) const { //std::cout << "ossimEpsgProjectionDatabase::findProjection: entered with spec " << spec << "\n"; ossimProjection* proj = 0; // Use the CRS code to access the database. The spec should be : where is // "EPSG" (the only group handled here): ossim_uint32 spec_code; ossimString spec_group ("epsg"); // default if only integer code provided if (spec.contains(":")) { spec_group = spec.before(":"); spec_code = spec.after(":").toUInt32(); spec_group = spec_group.downcase(); } else { spec_code = spec.toUInt32(); } // Presently only EPSG database is handled: if ((spec_code != 0) && (spec_group == "epsg")) return findProjection(spec_code); // The spec is probably a projection name. Need to search Db by the projection name. // Search database for entry. The spec may use different delimiters than // the DB so need to split the strings and compare the words: ossimString separators ("_ /()"); vector split_spec = spec.split(separators, true); vector split_db_name; ossimRefPtr map_proj = 0; if (m_projDatabase.empty()) initialize(); std::multimap >::iterator db_iter = m_projDatabase.begin(); while ((db_iter != m_projDatabase.end()) && !proj) { ossimRefPtr db_record = db_iter->second; if ( db_record.valid() ) { split_db_name.clear(); db_record->name.split(split_db_name, separators, true); if (split_spec == split_db_name) { // We may already have instantiated this projection, in which case just return its copy. // Otherwise, create the projection from the EPSG code that corresponds to the name: if (db_record->proj.valid()) proj = (ossimMapProjection*) db_record->proj->dup(); else proj = findProjection(db_record->code); return proj; } } ++db_iter; } // No hit? Could be that just a datum was identified, in which case we need a simple // Platte Carree: const ossimDatum* datum = ossimDatumFactoryRegistry::instance()->create(spec); if (datum) { ossimEquDistCylProjection* proj = new ossimEquDistCylProjection(*(datum->ellipsoid())); proj->setDatum(datum); proj->setPcsCode(spec_code); return proj; } return 0; } //************************************************************************************************* //! Given a projection name, assigns the group (e.g., "EPSG") and code of the projection. //! Returns ":" if match was found or empty string if not found. //************************************************************************************************* ossim_uint32 ossimEpsgProjectionDatabase::findProjectionCode(const ossimString& proj_name) const { if (m_projDatabase.empty()) initialize(); std::multimap >::iterator db_iter = m_projDatabase.begin(); while (db_iter != m_projDatabase.end()) { ossimRefPtr db_record = db_iter->second.get(); if ( db_record.valid() ) { if (db_record->name == proj_name) return (db_record->code); } ++db_iter; } return 0; } //************************************************************************************************* //! Given a projection instance, this method determines the corresponding EPSG code. Obviously //! this is only needed if the projection does not have its PCS code assigned (it is NULL). This //! happens when the projection was constructed with full parameters instead of the EPSG code. //! Returns integer EPSG code if match was found or 0 if not found. //************************************************************************************************* ossim_uint32 ossimEpsgProjectionDatabase::findProjectionCode(const ossimMapProjection& lost_proj) const { ossimString lost_type (lost_proj.getClassName()); // Shortcut for EPSG:4326 (WGS-85 geographic rectangular -- very common): if ((lost_type == "ossimEquDistCylProjection") && (lost_proj.getDatum()->epsgCode() == 6326)) return 4326; ossim_uint32 found_code = 0; if (lost_type == "ossimUtmProjection") { found_code = getCodeFromUtmProj(dynamic_cast(&lost_proj)); if (found_code) return found_code; } if (m_projDatabase.empty()) initialize(); ossimString lookup; std::multimap >::iterator db_iter = m_projDatabase.begin(); while ((db_iter != m_projDatabase.end()) && (found_code == 0)) { ossimRefPtr db_record = db_iter->second; if ( db_record.valid() ) { // Has a projection already been created for this db iter? if (!db_record->proj.valid()) { // No projection has been created yet for this DB entry. // NOTE: THIS IS VERY SLOW BECAUSE WE ARE INSTANTIATING EVERY PROJECTION IN THE DB!!! db_record->proj = dynamic_cast(findProjection(db_record->code)); } if (db_record->proj.valid() && (*(db_record->proj.get()) == lost_proj)) { found_code = db_record->code; // Hack to remap projection code 4087 to 4326 (which is not really a projection // code but other packages like to see 4326 for geographic projections. // Hacked under protest (OLK, 08/2010) if (found_code == 4087) found_code = 4326; } } ++db_iter; } return found_code; } //************************************************************************************************* //! This method provides acess to the projection name given the EPSG code. The name provides //! enough info for recognizing a non-meters HARN-based projection. //************************************************************************************************* ossimString ossimEpsgProjectionDatabase::findProjectionName(ossim_uint32 epsg_code) const { if (m_projDatabase.empty()) initialize(); ossimString name (""); std::multimap >::iterator db_iter = m_projDatabase.find(epsg_code); if (db_iter != m_projDatabase.end()) name = db_iter->second->name; return name; } //************************************************************************************************* //! Populates caller's list with all projections currently represented in the database. //! The format is: //! EPSG: "" //! There may be duplicate entries if the projection is duplicated in the various Db files. //************************************************************************************************* void ossimEpsgProjectionDatabase::getProjectionsList(std::vector& list) const { if (m_projDatabase.empty()) initialize(); std::multimap >::iterator db_iter = m_projDatabase.begin(); while (db_iter != m_projDatabase.end()) { ossimRefPtr db_record = db_iter->second; if ( db_record.valid() ) { ossimString record ("EPSG:"); record += ossimString::toString(db_record->code); record += " \""; record += db_record->name; record += "\""; list.push_back(record); } ++db_iter; } return; } //************************************************************************************************* //! This method is invoked to parse the Db record and produce a projection (or NULL if spec invalid) // // LIMITATION: Currently not parsing the datum info from the EPSG database file due to disconnect // with current ossimDatumFactory. Setting to default WGS84 with warning message. //************************************************************************************************* ossimMapProjection* ossimEpsgProjectionDatabase::createProjFromFormatARecord(ProjDbRecord* record) const { // Establish EPSG code and test for UTM (full projection is implied in the code itself -- no // accessing the database). Until the database is solidified, it is probably better to do // it this way: record->datumValid = true; record->proj = 0; // Establish the units in which the easting/northing is provided: ossimUnitType mapProjUnits = OSSIM_METERS; double mtrs_per_unit = 1.0; if (record->csvRecord[A_UNITS] == "US survey foot") { mapProjUnits = OSSIM_US_SURVEY_FEET; mtrs_per_unit = US_METERS_PER_FT; } else if (record->csvRecord[A_UNITS].contains("foot")) // THIS IS INTERNATIONAL FOOT, NOT EXACT FOR MANY INTERNATIONAL VARIETIES { mapProjUnits = OSSIM_FEET; mtrs_per_unit = MTRS_PER_FT; } else if (record->csvRecord[A_UNITS].contains("kilometre")) { mapProjUnits = OSSIM_KILOMETERS; mtrs_per_unit = 1000.0; } else if (!record->csvRecord[A_UNITS].contains("metre")) { // ### SKIP THIS MESSAGE BUT BE AWARE THAT THIS PROJECTION WON'T BE REPRESENTED IN DB ### //ossimNotify(ossimNotifyLevel_WARN)<csvRecord[A_UNITS]<<"> not presently supported."<csvRecord[A_DATUM_CODE].toUInt32(); const ossimDatum* datum = ossimEpsgDatumFactory::instance()->create(gcs_code); if (!datum) { // Default to WGS 84 -- this may throw an exception: datum = ossimDatumFactory::instance()->create(ossimString("WGE")); record->datumValid = false; } const ossimEllipsoid* ellipsoid = datum->ellipsoid(); ossimGpt origin(0,0,0,datum); ossimString proj_type = record->csvRecord[A_PROJ_TYPE]; if (proj_type.contains("Transverse Mercator")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LON]); double fe = mtrs_per_unit*record->csvRecord[A_FALSE_EASTING].toDouble(); double fn = mtrs_per_unit*record->csvRecord[A_FALSE_NORTHING].toDouble(); double sf = record->csvRecord[A_NAT_ORG_SCALE].toDouble(); record->proj = new ossimTransMercatorProjection(*ellipsoid, origin, fe, fn, sf); } else if (proj_type.contains("Lambert Conic Conformal (1SP)")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LON]); double fe = mtrs_per_unit*record->csvRecord[A_FALSE_EASTING].toDouble(); double fn = mtrs_per_unit*record->csvRecord[A_FALSE_NORTHING].toDouble(); record->proj = new ossimLambertConformalConicProjection(*ellipsoid, origin, origin.lat, origin.lat, fe, fn); } else if (proj_type.contains("Lambert Conic Conformal (2SP)")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_FALSE_ORG_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_FALSE_ORG_LON]); double p1 = decodeSexagesimalDms(record->csvRecord[A_STD_PARL_1_LAT]); double p2 = decodeSexagesimalDms(record->csvRecord[A_STD_PARL_2_LAT]); double fe = mtrs_per_unit*record->csvRecord[A_FALSE_ORG_EASTING].toDouble(); double fn = mtrs_per_unit*record->csvRecord[A_FALSE_ORG_NORTHING].toDouble(); record->proj = new ossimLambertConformalConicProjection(*ellipsoid, origin, p1, p2, fe, fn); } else if (proj_type.contains("Cassini")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LON]); double fe = mtrs_per_unit*record->csvRecord[A_FALSE_EASTING].toDouble(); double fn = mtrs_per_unit*record->csvRecord[A_FALSE_NORTHING].toDouble(); record->proj = new ossimCassiniProjection(*ellipsoid, origin, fe, fn); } else if (proj_type.contains("Mercator (1SP)")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LON]); double fe = mtrs_per_unit*record->csvRecord[A_FALSE_EASTING].toDouble(); double fn = mtrs_per_unit*record->csvRecord[A_FALSE_NORTHING].toDouble(); double sf = record->csvRecord[A_NAT_ORG_SCALE].toDouble(); record->proj = new ossimMercatorProjection(*ellipsoid, origin, fe, fn, sf); } else if(proj_type.contains("Popular Visualisation Sphere")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LON]); double fe = mtrs_per_unit*record->csvRecord[A_FALSE_EASTING].toDouble(); double fn = mtrs_per_unit*record->csvRecord[A_FALSE_NORTHING].toDouble(); double sf = record->csvRecord[A_NAT_ORG_SCALE].toDouble(); record->proj = new ossimMercatorProjection(*ellipsoid, origin, fe, fn, sf); // Set this for saveState: record->proj->setPcsCode( 3785 ); } else if(proj_type.contains("Pseudo Mercator")) { record->proj = new ossimGoogleProjection(); // Set this for saveState: record->proj->setPcsCode( 3857 ); } else if (proj_type.contains("Albers")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_FALSE_ORG_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_FALSE_ORG_LON]); double p1 = decodeSexagesimalDms(record->csvRecord[A_STD_PARL_1_LAT]); double p2 = decodeSexagesimalDms(record->csvRecord[A_STD_PARL_2_LAT]); double fe = mtrs_per_unit*record->csvRecord[A_FALSE_ORG_EASTING].toDouble(); double fn = mtrs_per_unit*record->csvRecord[A_FALSE_ORG_NORTHING].toDouble(); record->proj = new ossimAlbersProjection(*ellipsoid, origin, p1, p2, fe, fn); } else if (proj_type.contains("Equidistant Cylindrical")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_STD_PARL_1_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LON]); double fe = mtrs_per_unit*record->csvRecord[A_FALSE_EASTING].toDouble(); double fn = mtrs_per_unit*record->csvRecord[A_FALSE_NORTHING].toDouble(); record->proj = new ossimEquDistCylProjection(*ellipsoid, origin, fe, fn); } else if (proj_type.contains("New Zealand Map Grid")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LON]); double fe = mtrs_per_unit*record->csvRecord[A_FALSE_EASTING].toDouble(); double fn = mtrs_per_unit*record->csvRecord[A_FALSE_NORTHING].toDouble(); ossimNewZealandMapGridProjection* nz_proj = new ossimNewZealandMapGridProjection; nz_proj->setOrigin(origin); nz_proj->setFalseEastingNorthing(fe, fn); record->proj = nz_proj; } else if (proj_type.contains("Polar Stereographic")) { origin.lat = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LAT]); origin.lon = decodeSexagesimalDms(record->csvRecord[A_NAT_ORG_LON]); // double fe = mtrs_per_unit*record->csvRecord[A_FALSE_EASTING].toDouble(); // double fn = mtrs_per_unit*record->csvRecord[A_FALSE_NORTHING].toDouble(); ossimUpsProjection* ups_proj = new ossimUpsProjection(ossimEllipsoid(), origin); record->proj = ups_proj; } else { // Can't handle it now. //ossimNotify(ossimNotifyLevel_FATAL)<csvRecord[A_CODE]<<" \""<proj->setDatum(datum); record->proj->setPcsCode(record->code); record->proj->setProjectionUnits(mapProjUnits); return record->proj.get(); } //************************************************************************************************* // ### HACK ### //! State Plane projections as specified in the EPSG are indistinguishable from regular TM. //! Unfortunately OSSIM does make a distinction. For the time being, parse the code and //! programmatically arrive at the UTM projection. //************************************************************************************************* ossimMapProjection* ossimEpsgProjectionDatabase::createProjFromFormatBRecord(ProjDbRecord* db_record) const { // Unfortunately, as of this writing, there is a disconnect between the Geotrans projection // parameters and those provided by EPSG database. In the meantime, to maintain functionality, // we intercept the EPSG code and programmatically arrive at the projection versus pulling // all the parameters out of the Db record-> ossimStatePlaneProjectionInfo info(db_record->name, db_record->code, db_record->csvRecord[B_PROJ_TYPE], db_record->csvRecord[B_PARAM1], db_record->csvRecord[B_PARAM2], db_record->csvRecord[B_PARAM3], db_record->csvRecord[B_PARAM4], db_record->csvRecord[B_FALSE_EASTING].toDouble(), db_record->csvRecord[B_FALSE_NORTHING].toDouble(), db_record->csvRecord[B_UNITS], db_record->csvRecord[B_DATUM_CODE]); // NOTE: In order to avoid infinite recursion with this object, we initialized the PCS code in // info to NULL to insure that the projection is instantiated directly (not via this class): ossimKeywordlist kwl; info.populateProjectionKeywords(kwl); kwl.remove(ossimKeywordNames::PCS_CODE_KW); db_record->proj = PTR_CAST(ossimMapProjection, ossimMapProjectionFactory::instance()->createProjection(kwl)); if (db_record->proj.valid()) { db_record->proj->setPcsCode(db_record->csvRecord[B_CODE].toUInt32()); db_record->datumValid = true; } return db_record->proj.get(); } //************************************************************************************************* // ### HACK ### //! UTM projections as specified in the EPSG are indistinguishable from regular TM. Unfortunately //! OSSIM does make a distinction. For the time being, parse the code and programmatically arrive //! at the UTM projection. //************************************************************************************************* ossimMapProjection* ossimEpsgProjectionDatabase::createProjFromUtmCode(ossim_uint32 code) const { // This code originally found in deprecated ossimPcsCodeProjectionFactory authored by // David Burken. int type = code/100; int zone = code%100; ossimUtmProjection* proj = NULL; switch (type) { case 322: // utm, WGS72 (WGD), northern hemisphere if ( (zone > 0 ) && (zone < 61) ) { proj = new ossimUtmProjection(*(ossimDatumFactory::instance()->wgs72()->ellipsoid())); proj->setDatum(ossimDatumFactory::instance()->wgs72()); proj->setZone(zone); proj->setHemisphere('N'); } break; case 323: // utm, WGS72 (WGD), southern hemisphere if ( (zone > 0) && (zone < 61) ) { proj = new ossimUtmProjection(*(ossimDatumFactory::instance()->wgs72()->ellipsoid())); proj->setDatum(ossimDatumFactory::instance()->wgs72()); proj->setZone(zone); proj->setHemisphere('S'); } break; case 326: // utm, WGS84 (WGE), northern hemisphere if ( (zone > 0) && (zone < 61) ) { proj = new ossimUtmProjection(*(ossimDatumFactory::instance()->wgs84()->ellipsoid())); proj->setDatum(ossimDatumFactory::instance()->wgs84()); proj->setZone(zone); proj->setHemisphere('N'); } break; case 327: // utm, WGS84 (WGE), southern hemisphere if ( (zone > 0) && (zone < 61) ) { proj = new ossimUtmProjection(*(ossimDatumFactory::instance()->wgs84()->ellipsoid())); proj->setDatum(ossimDatumFactory::instance()->wgs84()); proj->setZone(zone); proj->setHemisphere('S'); } break; case 267: // utm, "NAS-C", northern hemisphere // Only UTM NAD27 North zones 3 to 22 are in the 267xx range... // 26729 through 26803 handled by state plane factory. //--- if ( (code > 26702) && (code < 26723) ) { proj = new ossimUtmProjection(*(ossimDatumFactory::instance()-> create(ossimString("NAS-C"))->ellipsoid())); proj->setDatum(ossimDatumFactory::instance()->create(ossimString("NAS-C"))); proj->setZone(zone); proj->setHemisphere('N'); } break; case 269: // utm, "NAR-C", northern hemisphere // Only UTM NAD83 North zones 3 to 23 are in the 269xx range... // 26929 through 26998 handled by state plane factory. if ( (code > 26902) && (code < 26924) ) { proj = new ossimUtmProjection(*(ossimDatumFactory::instance()-> create(ossimString("NAR-C"))->ellipsoid())); proj->setDatum(ossimDatumFactory::instance()->create(ossimString("NAR-C"))); proj->setZone(zone); proj->setHemisphere('N'); } break; case 248: // Provisional S. American 1956, 24818 through 24880 if ( (code > 24817) && (code < 24881) ) { proj = new ossimUtmProjection(*(ossimDatumFactory::instance()-> create(ossimString("PRP-M"))->ellipsoid())); proj->setDatum(ossimDatumFactory::instance()->create(ossimString("PRP-M"))); if (zone > 60) { proj->setZone(zone - 60); proj->setHemisphere('S'); } else { proj->setZone(zone); proj->setHemisphere('N'); } } break; } // End of switch on code. if (proj) proj->setPcsCode(code); return proj; } //************************************************************************************************* //! Given UTM projection, derives the associated EPSG code. This is faster than a Db lookup. //************************************************************************************************* ossim_uint32 ossimEpsgProjectionDatabase::getCodeFromUtmProj(const ossimUtmProjection* proj) const { if (proj == NULL) return 0; char hemisphere = proj->getHemisphere(); ossim_uint32 zone = proj->getZone(); ossimString datum_code = proj->getDatum()->code(); if ((zone < 1 ) || (zone > 60)) return 0; ossim_uint32 epsg_code = zone; if ((hemisphere == 'N') && (datum_code == "WGD")) epsg_code += 32200; else if ((hemisphere == 'S') && (datum_code == "WGD")) epsg_code += 32300; else if ((hemisphere == 'N') && (datum_code == "WGE")) epsg_code += 32600; else if ((hemisphere == 'S') && (datum_code == "WGE")) epsg_code += 32700; else if ((hemisphere == 'N') && (datum_code == "NAS-C") && (zone > 2) && (zone < 23)) epsg_code += 26700; else if ((hemisphere == 'N') && (datum_code == "NAR-C") && (zone > 2) && (zone < 24)) epsg_code += 26900; else if ((hemisphere == 'N') && (datum_code == "PRP-M")) epsg_code += 24800; else if ((hemisphere == 'S') && (datum_code == "PRP-M")) epsg_code += 24800 + 60; else { //--- // Use a projection code that does not imply a datum. // See section "6.3.3.2 Projection Codes" for definition. //--- if ( hemisphere == 'N' ) // Northern hemisphere. { epsg_code += 16000; } else // Southern hemisphere. { epsg_code += 16100; } } return epsg_code; } ossim-Miami-2.9.1/src/projection/ossimEpsgProjectionFactory.cpp000066400000000000000000000203361352751253100247240ustar00rootroot00000000000000//************************************************************************************************* // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // DESCRIPTION: // Projection Factory for EPSG coded projections. These are projections // that are fully defined in database files and specified via a projection coordinate system (PCS) // code. // //************************************************************************************************* // $Id: ossimEpsgProjectionFactory.cpp 22929 2014-10-29 18:11:04Z gpotts $ #include #include #include #include #include #include #include //ossimEpsgProjectionFactory* ossimEpsgProjectionFactory::m_instance = 0; //************************************************************************************************* //! Implements singleton pattern //************************************************************************************************* ossimEpsgProjectionFactory* ossimEpsgProjectionFactory::instance() { static ossimEpsgProjectionFactory inst; return &inst; //if(!m_instance) // m_instance = new ossimEpsgProjectionFactory; //return m_instance; } //************************************************************************************************* //! Constructor loads all SRS CSV files specified in the ossim prefs //************************************************************************************************* ossimEpsgProjectionFactory::ossimEpsgProjectionFactory() { } //************************************************************************************************* //! From keywordlist //************************************************************************************************* ossimProjection* ossimEpsgProjectionFactory::createProjection(const ossimKeywordlist &keywordList, const char *prefix) const { ossimProjection* proj = 0; // Look for a PCS (Projected Coordinate System) code entry and construct the basic projection. // This is the bootstrap for creating the fully-initialized proj: ossimString proj_spec = keywordList.find(prefix, ossimKeywordNames::PCS_CODE_KW); if(!proj_spec.empty()) proj = createProjection(proj_spec); if (!proj) { // An alternate way of specifying an EPSG projection is by its database name: proj_spec = keywordList.find(prefix, ossimKeywordNames::PROJECTION_KW); proj = createProjection(proj_spec); } if (!proj) return NULL; // The tie points and perhaps other params might still be in the KWL, so pass the KWL on to the // new projection after it has been amended with the default proj info extracted from the // EPSG code (i.e., sans tiepoints and gsd): ossimKeywordlist proj_kwl; proj->saveState(proj_kwl, prefix); proj_kwl.remove(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW); proj_kwl.remove(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW); proj_kwl.remove(prefix, ossimKeywordNames::TIE_POINT_XY_KW); proj_kwl.remove(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW); proj_kwl.addList(keywordList, false); // false: do not override existing items proj->loadState(proj_kwl, prefix); return proj; } //************************************************************************************************* // This is the principal factory method. It accepts a string in one of three formats: // // 1. :, for example "EPSG:32615" // 2. , for example "32615", this is the CRS code ID for the projerection. // 3. AUTO:, for specifying custom user-defined codes. // // Both projected and geographic (Platte Carre) codes are handled. // // IMPORTANT NOTE: Image tie-points cannot be conveyed by an EPSG projection code. The projection // created here will not be fully initialized for use in rendering imagery. //************************************************************************************************* ossimProjection* ossimEpsgProjectionFactory::createProjection(const ossimString &spec) const { std::vector split_line; // Intercept custom codes here before resorting to the database. This really shouldn't be in this // class but nobody else is parsing for it, so leave it here for now. if (ossimString(spec).downcase().contains("auto")) { split_line = spec.after(":").explode(","); return createProjFromAutoCode(split_line); } // Strip commonly found or bar '|' from end if present. ossimString s = spec; s.trim(ossimString("|")); // Otherwise, pass along the request to the database object for record search: return ossimEpsgProjectionDatabase::instance()->findProjection(s); } //************************************************************************************************* //! When the CRS is specified with the "AUTO:" code format, this method is invoked to //! parse the and produce a projection (or NULL if spec invalid): //************************************************************************************************* ossimMapProjection* ossimEpsgProjectionFactory::createProjFromAutoCode(const std::vector& spec) const { if (spec.size() < 3) return 0; ossim_uint32 code = spec[0].toUInt32(); ossimGpt origin (spec[2].toDouble(), spec[1].toDouble()) ; // Only a few AUTO codes are considered: switch(code) { case 42001: { ossimUtmProjection* utm = new ossimUtmProjection; utm->setZone(origin); utm->setHemisphere(origin); utm->setOrigin(origin); utm->update(); //utm->setPcsCode(42001); return utm; } case 42002: { ossimTransMercatorProjection* transMerc = new ossimTransMercatorProjection; transMerc->setFalseNorthing(origin.latd()>=0.0?0.0:10000000.0); transMerc->setOrigin(ossimGpt(0.0, origin.lond())); transMerc->setScaleFactor(.9996); transMerc->update(); // transMerc->setPcsCode(42002); return transMerc; } case 42003: { ossimOrthoGraphicProjection* ortho = new ossimOrthoGraphicProjection; ortho->setOrigin(origin); ortho->update(); //ortho->setPcsCode(42003); return ortho; } case 42004: { ossimEquDistCylProjection* geographic = new ossimEquDistCylProjection; geographic->setOrigin(origin); geographic->update(); //geographic->setPcsCode(42004); return geographic; } } return 0; } //************************************************************************************************* ossimObject* ossimEpsgProjectionFactory::createObject(const ossimString& typeName)const { return createProjection(typeName); } //************************************************************************************************* ossimObject* ossimEpsgProjectionFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { return createProjection(kwl, prefix); } //************************************************************************************************* //! STUB. Not implemented //************************************************************************************************* ossimProjection* ossimEpsgProjectionFactory::createProjection(const ossimFilename& /* filename */, ossim_uint32 /* entryIdx */)const { return 0; } //************************************************************************************************* //! This returns the type name of all objects in all factories. This is the name used to //! construct the objects dynamically and this name must be unique. //************************************************************************************************* void ossimEpsgProjectionFactory::getTypeNameList(std::vector& typeList) const { ossimEpsgProjectionDatabase::instance()->getProjectionsList(typeList); return; } ossim-Miami-2.9.1/src/projection/ossimEquDistCylProjection.cpp000066400000000000000000000412321352751253100245220ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Equidistant Cylinder projection code. //******************************************************************* // $Id: ossimEquDistCylProjection.cpp 23373 2015-06-13 17:16:38Z okramer $ #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimEquDistCylProjection:debug"); RTTI_DEF1(ossimEquDistCylProjection, "ossimEquDistCylProjection", ossimMapProjection); /***************************************************************************/ /* * DEFINES */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define ONE (1.0 * M_PI / 180.0) /* 1 degree in radians*/ #define EQCY_NO_ERROR 0x0000 #define EQCY_LAT_ERROR 0x0001 #define EQCY_LON_ERROR 0x0002 #define EQCY_EASTING_ERROR 0x0004 #define EQCY_NORTHING_ERROR 0x0008 #define EQCY_ORIGIN_LAT_ERROR 0x0010 #define EQCY_CENT_MER_ERROR 0x0020 #define EQCY_A_ERROR 0x0040 #define EQCY_B_ERROR 0x0080 #define EQCY_A_LESS_B_ERROR 0x0100 ossimEquDistCylProjection::ossimEquDistCylProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimEquDistCylProjection::ossimEquDistCylProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Eqcy_False_Easting = falseEasting; Eqcy_False_Northing = falseNorthing; Eqcy_Delta_Northing = 10007555.0; Eqcy_Max_Easting = 20015110.0; Eqcy_Min_Easting = -20015110.0; update(); } void ossimEquDistCylProjection::update() { Set_Equidistant_Cyl_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Eqcy_False_Easting, Eqcy_False_Northing); theFalseEastingNorthing.x = Eqcy_False_Easting; theFalseEastingNorthing.y = Eqcy_False_Northing; ossimMatrix4x4 identity; if (theModelTransform.isEqualTo(identity)) theMetersPerPixel.makeNan(); // force recompute by base class ossimMapProjection::update(); // For geographic projection, the PCS EPSG code can be derived from the datum in most cases: if ((thePcsCode == 0) && (theDatum != NULL)) { ossim_uint32 datum_code = theDatum->epsgCode(); if ((datum_code >= 6000) && (datum_code < 7000)) thePcsCode = datum_code - 2000; } // Workaround for bug } void ossimEquDistCylProjection::setOrigin(const ossimGpt& origin) { theOrigin = origin; Set_Equidistant_Cyl_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Eqcy_False_Easting, Eqcy_False_Northing); // Changing the projection origin from the equator implies a scale change in the longitude // direction to maintain GSD (meters) square at origin: ossimDpt gsd = getMetersPerPixel(); gsd.x = gsd.y; // reset X (longitude) direction GSD setMetersPerPixel(gsd); } void ossimEquDistCylProjection::setFalseEasting(double falseEasting) { Eqcy_False_Easting = falseEasting; update(); } void ossimEquDistCylProjection::setFalseNorthing(double falseNorthing) { Eqcy_False_Northing = falseNorthing; update(); } void ossimEquDistCylProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Eqcy_False_Easting = falseEasting; Eqcy_False_Northing = falseNorthing; update(); } void ossimEquDistCylProjection::setDefaults() { theProjectionUnits = OSSIM_DEGREES; Eqcy_False_Easting = 0.0; Eqcy_False_Northing = 0.0; Eqcy_Delta_Northing = 10007555.0; Eqcy_Max_Easting = 20015110.0; Eqcy_Min_Easting = -20015110.0; update(); } ossimGpt ossimEquDistCylProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Equidistant_Cyl_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimEquDistCylProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Equidistant_Cyl(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimEquDistCylProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimEquDistCylProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimEquDistCylProjection::loadState: Input keyword list is \n" << kwl << endl; } setDefaults(); ossimMapProjection::loadState(kwl, prefix); // Make sure the origin.lat is defined since it is needed to relate degrees/meter: if (ossim::isnan(theOrigin.lat)) { theOrigin.lat = theUlGpt.lat; if (ossim::isnan(theOrigin.lat)) theOrigin.lat = 0.0; } // Make sure degrees per pixel is defined: if (theDegreesPerPixel.hasNans() && !theMetersPerPixel.hasNans()) computeDegreesPerPixel(); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); // make sure we are of the same type. If we are then the easting // northing values will make since // if(ossimString(type) == STATIC_TYPE_NAME(ossimEquDistCylProjection)) { Eqcy_False_Easting = theFalseEastingNorthing.x; Eqcy_False_Northing = theFalseEastingNorthing.y; } else { theUlEastingNorthing.makeNan(); } // finalize the initialization. update(); return true; } /***************************************************************************/ /* * FUNCTIONS */ long ossimEquDistCylProjection::Set_Equidistant_Cyl_Parameters(double a, double f, double Std_Parallel, double Central_Meridian, double False_Easting, double False_Northing) { /* Begin Set_Equidistant_Cyl_Parameters */ /* * The function Set_Equidistant_Cyl_Parameters receives the ellipsoid parameters and * projection parameters as inputs, and sets the corresponding state * variables. It also calculates the spherical radius of the sphere having * the same area as the ellipsoid. If any errors occur, the error code(s) * are returned by the function, otherwise EQCY_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Std_Parallel : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * standard parallel of the projection (input) */ double temp; // double inv_f = 1 / f; long Error_Code = EQCY_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= EQCY_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= EQCY_INV_F_ERROR; // } // if ((Std_Parallel < -PI_OVER_2) || (Std_Parallel > PI_OVER_2)) // { /* standard parallel out of range */ // Error_Code |= EQCY_STDP_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= EQCY_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Eqcy_a = a; Eqcy_f = f; es2 = 2 * Eqcy_f - Eqcy_f * Eqcy_f; es4 = es2 * es2; es6 = es4 * es2; /* spherical radius */ Ra = Eqcy_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 /3024.0); Eqcy_Std_Parallel = Std_Parallel; Cos_Eqcy_Std_Parallel = cos(Eqcy_Std_Parallel); Ra_Cos_Eqcy_Std_Parallel = Ra * Cos_Eqcy_Std_Parallel; // if (Central_Meridian > M_PI) // Central_Meridian -= TWO_PI; Eqcy_Origin_Long = Central_Meridian; Eqcy_False_Easting = False_Easting; Eqcy_False_Northing = False_Northing; if (Eqcy_Origin_Long > 0) { Convert_Geodetic_To_Equidistant_Cyl(PI_OVER_2, Eqcy_Origin_Long - M_PI - ONE, &Eqcy_Max_Easting, &temp); Convert_Geodetic_To_Equidistant_Cyl(PI_OVER_2, Eqcy_Origin_Long - M_PI, &Eqcy_Min_Easting, &temp); } else if (Eqcy_Origin_Long < 0) { Convert_Geodetic_To_Equidistant_Cyl(PI_OVER_2, Eqcy_Origin_Long + M_PI, &Eqcy_Max_Easting, &temp); Convert_Geodetic_To_Equidistant_Cyl(PI_OVER_2, Eqcy_Origin_Long + M_PI + ONE, &Eqcy_Min_Easting, &temp); } else { Convert_Geodetic_To_Equidistant_Cyl(PI_OVER_2, M_PI, &Eqcy_Max_Easting, &temp); Eqcy_Min_Easting = -Eqcy_Max_Easting; } } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Equidistant_Cyl_Parameters */ void ossimEquDistCylProjection::Get_Equidistant_Cyl_Parameters(double *a, double *f, double *Std_Parallel, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Equidistant_Cyl_Parameters */ /* * The function Get_Equidistant_Cyl_Parameters returns the current ellipsoid * parameters and Equidistant Cylindrical projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Std_Parallel : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * standard parallel of the projection (output) */ *a = Eqcy_a; *f = Eqcy_f; *Std_Parallel = Eqcy_Std_Parallel; *Central_Meridian = Eqcy_Origin_Long; *False_Easting = Eqcy_False_Easting; *False_Northing = Eqcy_False_Northing; return; } /* End Get_Equidistant_Cyl_Parameters */ long ossimEquDistCylProjection::Convert_Geodetic_To_Equidistant_Cyl (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Equidistant_Cyl */ /* * The function Convert_Geodetic_To_Equidistant_Cyl converts geodetic (latitude and * longitude) coordinates to Equidistant Cylindrical projection (easting and northing) * coordinates, according to the current ellipsoid, spherical radiius * and Equidistant Cylindrical projection parameters. * If any errors occur, the error code(s) are returned by the * function, otherwise EQCY_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double dlam; /* Longitude - Central Meridan */ long Error_Code = EQCY_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= EQCY_LAT_ERROR; // } // if ((Longitude < -M_PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code|= EQCY_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Eqcy_Origin_Long; //if (dlam >= TWO_PI) //{ // dlam -= TWO_PI; // } // if (dlam <= -TWO_PI) // { // dlam += TWO_PI; // } *Easting = Ra_Cos_Eqcy_Std_Parallel * dlam + Eqcy_False_Easting; *Northing = Ra * Latitude + Eqcy_False_Northing; } return (Error_Code); } /* End Convert_Geodetic_To_Equidistant_Cyl */ long ossimEquDistCylProjection::Convert_Equidistant_Cyl_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Equidistant_Cyl_To_Geodetic */ /* * The function Convert_Equidistant_Cyl_To_Geodetic converts Equidistant Cylindrical projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid, spherical radius * and Equidistant Cylindrical projection coordinates. * If any errors occur, the error code(s) are returned by the * function, otherwise EQCY_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx, dy; long Error_Code = EQCY_NO_ERROR; // if ((Easting < (Eqcy_False_Easting + Eqcy_Min_Easting)) // || (Easting > (Eqcy_False_Easting + Eqcy_Max_Easting))) // { /* Easting out of range */ // Error_Code |= EQCY_EASTING_ERROR; // } // if ((Northing < (Eqcy_False_Northing - Eqcy_Delta_Northing)) // || (Northing > (Eqcy_False_Northing + Eqcy_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= EQCY_NORTHING_ERROR; // } if (!Error_Code) { dy = Northing - Eqcy_False_Northing; dx = Easting - Eqcy_False_Easting; double RaInv = 1.0/Ra; *Latitude = dy *RaInv; if (Ra_Cos_Eqcy_Std_Parallel == 0) *Longitude = 0; else { double RaCosLatInv = 1.0/Ra_Cos_Eqcy_Std_Parallel; *Longitude = Eqcy_Origin_Long + dx*RaCosLatInv; } // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; // if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ // *Longitude = PI; // else if (*Longitude < -PI) // *Longitude = -PI; } return (Error_Code); } /* End Convert_Equidistant_Cyl_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimFcsiModel.cpp000066400000000000000000001165611352751253100223140ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimFcsiModel.cc // // Copyright (C) 2001 ImageLinks, Inc. // // LGPL // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: Contains sensor model implementation for "Frame Camera Scanned // Image" (FCSI, pronounced "foxy"). // // This model represents image data that was scanned from film exposed by a // conventional aerial frame camera. The data members defined in this class // represent the fundamental quantities needed for the transformation. // Typically, a different set of parameters will be provided in the metadata. // An interface (support data) class will need to be implemented to convert // a particular system's format to the quantities needed by this model. // // Coordinate systems in use are described here: // // Pixel -- line/sample in the digital image. The origin of this system is // the upper left corner of the image, and represents a LEFT- // HANDED coordinate system with Y (line) positive down and X // (sample) positive to the right. // // Film -- x, y related to pixel space by affine transform (which includes // mirror reflection due to left-handed system above) represented // by thePrincipalPoint and the theScanXformMatrix. The latter // contains scale, skew, and rotation/reflection. The film // coordinates are adjusted for radial and decentering distortion. // // Camera/ -- 3D system containing film plane and optical (Z) axis. Given the // Platform focal length (Z) and the film point (X,Y), a 3D ray direction // is established in this space. This space is also termed "LSR" // in the code. If there is a rotation between the film/optical // axes and the platform (interior orientation), then that // transformation must be included as part of the LSR-to-ECF // rotation by the metadata reader object. // // ECF -- Universal earth frame of reference. The imaging ray direction // is transformed from Camera space to ECF by theAdjLsrToEcfRot. // // There are two rotations to go from Camera to ECF. First is the initial // camera orientation as derived from the metadata, combining the interior // orientation (relation between camera and platform) and the exterior // orientation dependent on the platform attitude w.r.t. the ECF system. // The second rotation is a differential rotation due to the attitude // adjustable params. These are arbitrarily taken as rotations about the ECF // XYZ axes, not the platform attitude axes of roll/pitch/yaw. The // combined rotation is stored in theAdjLsrToEcfRot, which is precomputed // in updateModel() once with each adjustment. // // When the time comes to incorporate least-squares parameter adjustment, care // must be taken to propagate the a priori sigmas for position and attitude // (including both internal and external orientation angles) into the ECF // coordinates. This also applies to the affine transform parameters used in // transforming pixels to film coordinates. The propagated uncertainties can // then be used to assign the adjustable parameter sigmas array (and // covariance when we get to that...) // // SOFTWARE HISTORY: // 16JAN2003 Oscar Kramer, ImageLinks // Initial coding // //***************************************************************************** // $Id: ossimFcsiModel.cpp 13005 2008-06-08 20:26:36Z dburken $ #include #include #include #include #include #include #include #include RTTI_DEF1(ossimFcsiModel, "ossimFcsiModel", ossimSensorModel); //*** // Define Trace flags for use within this file: //*** #include using namespace std; static ossimTrace traceExec ("ossimFcsiModel:exec"); static ossimTrace traceDebug ("ossimFcsiModel:debug"); //*** // File-scope constants: //*** static const int MODEL_VERSION_NUMBER = 1; static const ossimString PARAM_NAMES[] ={"x_pos_offset", "y_pos_offset", "z_pos_offset", "x_rot_corr", "y_rot_corr", "z_rot_corr", "foc_len_offset", "scan_skew_corr"}; static const ossimString PARAM_UNITS[] ={"meters", "meters", "meters", "degrees", "degress", "degress", "millimeters", "degrees"}; //*** // Public FCSI Keywords: //*** const char* ossimFcsiModel::PRINCIPAL_POINT_X_KW = "principal_point_x"; const char* ossimFcsiModel::PRINCIPAL_POINT_Y_KW = "principal_point_y"; const char* ossimFcsiModel::SCAN_SCALE_MATRIX_00_KW = "scan_scale_matrix_00"; const char* ossimFcsiModel::SCAN_SCALE_MATRIX_01_KW = "scan_scale_matrix_01"; const char* ossimFcsiModel::SCAN_SCALE_MATRIX_10_KW = "scan_scale_matrix_10"; const char* ossimFcsiModel::SCAN_SCALE_MATRIX_11_KW = "scan_scale_matrix_11"; const char* ossimFcsiModel::SCAN_ROTATION_ANGLE_KW = "scan_rotation_angle"; const char* ossimFcsiModel::SCAN_SKEW_ANGLE_KW = "scan_skew_angle"; const char* ossimFcsiModel::FOCAL_LENGTH_KW = "focal_length"; const char* ossimFcsiModel::PLATFORM_POSITION_X_KW = "platform_position_x"; const char* ossimFcsiModel::PLATFORM_POSITION_Y_KW = "platform_position_y"; const char* ossimFcsiModel::PLATFORM_POSITION_Z_KW = "platform_position_z"; const char* ossimFcsiModel::CAMERA_ORIENTATION_MATRIX_ELEM_KW = "camera_orientation_matrix_elem_"; //***************************************************************************** // DEFAULT CONSTRUCTOR: ossimFcsiModel() // // Note: Using this constructor results in an uninitialized model. It is // expected that either a loadState with valid keywordlist is called, or that // the individual set-methods (including the base-class' set methods are // called. When set-methods are used, a final call to completeInitialization() // (declared in ossimSensorModel) is required to give the model a chance to // "digest" the values previously set. // //***************************************************************************** ossimFcsiModel::ossimFcsiModel() : ossimSensorModel (), thePrincipalPoint (0, 0), theScanSkew (0.0), theScanRotation (0.0), theOpticalDistortion (0), theLsrToEcfRot (3, 3), theEcfOffset (0, 0, 0), theXrotCorr (0.0), theYrotCorr (0.0), theZrotCorr (0.0), theFocalOffset (0.0), theScanSkewCorr (0.0), theAdjLsrToEcfRot (3, 3), theAdjEcfToLsrRot (3, 3) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: entering..." << std::endl; theScanScaleMatrix[0] = 1.0; theScanScaleMatrix[1] = 0.0; theScanScaleMatrix[2] = 0.0; theScanScaleMatrix[3] = 1.0; theScanXformMatrix[0] = 1.0; theScanXformMatrix[1] = 0.0; theScanXformMatrix[2] = 0.0; theScanXformMatrix[3] = 1.0; initAdjustableParameters(); setErrorStatus(); // indicate uninitialized if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: returning..." << std::endl; } //***************************************************************************** // CONSTRUCTOR: ossimFcsiModel(filename) // // Constructs model from a keywordlist filename // //***************************************************************************** ossimFcsiModel::ossimFcsiModel(const ossimFilename& init_file) : ossimSensorModel (), thePrincipalPoint (0, 0), theScanSkew (0.0), theScanRotation (0.0), theOpticalDistortion (0), theLsrToEcfRot (3, 3), theEcfOffset (0, 0, 0), theXrotCorr (0.0), theYrotCorr (0.0), theZrotCorr (0.0), theFocalOffset (0.0), theScanSkewCorr (0.0), theAdjLsrToEcfRot (3, 3), theAdjEcfToLsrRot (3, 3) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: entering..." << std::endl; initAdjustableParameters(); ossimKeywordlist kwl (init_file); loadState(kwl); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: Exited..." << std::endl; } //***************************************************************************** // CONSTRUCTOR: ossimFcsiModel(kwl) // // Constructs model from keywordlist geometry file // //***************************************************************************** ossimFcsiModel::ossimFcsiModel(const ossimKeywordlist& geom_kwl) : ossimSensorModel (), thePrincipalPoint (0, 0), theScanSkew (0.0), theScanRotation (0.0), theOpticalDistortion (0), theLsrToEcfRot (3, 3), theEcfOffset (0, 0, 0), theXrotCorr (0.0), theYrotCorr (0.0), theZrotCorr (0.0), theFocalOffset (0.0), theScanSkewCorr (0.0), theAdjLsrToEcfRot (3, 3), theAdjEcfToLsrRot (3, 3) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: entering..." << std::endl; initAdjustableParameters(); loadState(geom_kwl); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: Exited..." << std::endl; } //***************************************************************************** // COPY CONSTRUCTOR: //***************************************************************************** ossimFcsiModel::ossimFcsiModel(const ossimFcsiModel& foxy) : ossimSensorModel (foxy), thePrincipalPoint (foxy.thePrincipalPoint), theScanSkew (foxy.theScanSkew), theScanRotation (foxy.theScanRotation), theFocalLen (foxy.theFocalLen), thePlatformPos (foxy.thePlatformPos), theLsrToEcfRot (foxy.theLsrToEcfRot), theEcfOffset (foxy.theEcfOffset), theXrotCorr (foxy.theXrotCorr), theYrotCorr (foxy.theYrotCorr), theZrotCorr (foxy.theZrotCorr), theFocalOffset (foxy.theFocalOffset), theScanSkewCorr (foxy.theScanSkewCorr) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: entering..." << std::endl; if(foxy.theOpticalDistortion) { // // Finish the copy: // theOpticalDistortion = new ossimRadialDecentLensDistortion (*(foxy.theOpticalDistortion)); } for (int i=0; i<4; i++) theScanScaleMatrix[i] = foxy.theScanScaleMatrix[i]; //*** // Compute quantities derived from adjustables: //*** updateModel(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: returning..." << std::endl; } //***************************************************************************** // METHOD: ossimFcsiModel::lineSampleHeightToWorld() // // Performs the line/sample to groundpoint projection given an elevation. // // 1. Compute ECF Imaging ray (see imagingRay() method below) // 5. Intersect imaging ray with elevation surface. // //***************************************************************************** void ossimFcsiModel::lineSampleHeightToWorld(const ossimDpt& image_point, const double& height, ossimGpt& gpt) const { bool debug = false; // setable via interactive debugger if (traceExec() || debug) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: entering..." << std::endl; //*** // Extrapolate if point is outside image: //*** if (!insideImage(image_point)) { gpt = extrapolate(image_point, height); } else { //*** // First establish imaging ray from image point: //*** ossimEcefRay imaging_ray; imagingRay(image_point, imaging_ray); ossimEcefPoint Pecf (imaging_ray.intersectAboveEarthEllipsoid(height)); gpt = ossimGpt(Pecf); if (traceDebug() || debug) { ossimNotify(ossimNotifyLevel_DEBUG) << "Pecf = " << Pecf << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "gpt = " << gpt << std::endl; } } if (traceExec() || debug) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::ossimFcsiModel: returning..." << std::endl; } //***************************************************************************** // METHOD: ossimFcsiModel::imagingRay() // // Establishes an origin (at the platform position) and direction of the // imaging ray as follows: // // 1. Remove any pixel offset into the image (in the case where the digital // image is a sub-image of a larger scan). // 2. Transform pixel coordinates to film point (with inherent lens distortion) // 3. Remove radial and decentering lens distortion to arrive at ideal film // coordinates. // 4. Establish an internal imaging ray direction vector given the focal length // 5. Transform ray direction vector to ECF coordinates and assign origin. // //***************************************************************************** void ossimFcsiModel::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { bool debug = false; // setable via interactive debugger: "set debug = true" if (traceExec() || debug) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::imagingRay: entering..." << std::endl; //*** // In case this is a sub-image of a full image scan, need to add the // sub-image offset maintained in the base-class: //*** ossimDpt p0 (image_point + theSubImageOffset); if (traceDebug() || debug) { ossimNotify(ossimNotifyLevel_DEBUG) << "image_point = " << image_point << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "theSubImageOffset = " << theSubImageOffset << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "p0 = " << p0 << std::endl; } //*** // Apply pixel to film coordinates affine transform: //*** ossimDpt p1 (p0 - theRefImgPt); ossimDpt f1 (theScanXformMatrix[0]*p1.x + theScanXformMatrix[1]*p1.y, theScanXformMatrix[2]*p1.x + theScanXformMatrix[3]*p1.y); ossimDpt film (f1 - thePrincipalPoint); if (traceDebug() || debug) { ossimNotify(ossimNotifyLevel_DEBUG) << "theRefImgPt = " << theRefImgPt << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "p1 = " << p1 << std::endl; for (int i=0; i<4; i++) { ossimNotify(ossimNotifyLevel_DEBUG) << "theScanXformMatrix["<saveState(kwl, ostr.str().c_str()); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::saveState: returning..." << std::endl; return true; } //***************************************************************************** // METHOD: ossimFcsiModel::loadState() // // Restores the model's state from the KWL. This KWL also serves as a // geometry file. // //***************************************************************************** bool ossimFcsiModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::loadState: entering..." << std::endl; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:" << "\nInput kwl: " << kwl << std::endl; } const char* value; const char* keyword; bool success; //*** // Assure this keywordlist contains correct type info: //*** keyword = ossimKeywordNames::TYPE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "Type name not found"); return false; } if (strcmp(value, TYPE_NAME(this))) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::saveState: returning..." << std::endl; return false; } //*** // Clear out any existing adjustable params: //*** //*** // Pass on to the base-class for parsing first: //*** success = ossimSensorModel::loadState(kwl, prefix); if (!success) { return false; } if(!getNumberOfAdjustableParameters()) { initAdjustableParameters(); } //*** // Now begin loading data members: //*** keyword = PRINCIPAL_POINT_X_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "principle point x not given"); return false; } thePrincipalPoint.x = atof(value); keyword = PRINCIPAL_POINT_Y_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "principle point y not given"); return false; } thePrincipalPoint.y = atof(value); keyword = SCAN_SCALE_MATRIX_00_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "scale matrix 0,0 not given"); return false; } theScanScaleMatrix[0] = atof(value); keyword = SCAN_SCALE_MATRIX_01_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "scale matrix 0,1 not given"); return false; } theScanScaleMatrix[1] = atof(value); keyword = SCAN_SCALE_MATRIX_10_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "scale matrix 1,0 not given"); return false; } theScanScaleMatrix[2] = atof(value); keyword = SCAN_SCALE_MATRIX_11_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "scale matrix 1,1 not given"); return false; } theScanScaleMatrix[3] = atof(value); keyword = SCAN_SKEW_ANGLE_KW; value = kwl.find(prefix, keyword); if (!value) theScanSkew = 0.0; else theScanSkew = atof(value); keyword = SCAN_ROTATION_ANGLE_KW; value = kwl.find(prefix, keyword); if (!value) theScanRotation = 0.0; else theScanRotation = atof(value); keyword = FOCAL_LENGTH_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "Focal length not given"); return false; } theFocalLen = atof(value); keyword = PLATFORM_POSITION_X_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "Platform position X not given"); return false; } thePlatformPos.x() = atof(value); keyword = PLATFORM_POSITION_Y_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "Platform position Y not given"); } thePlatformPos.y() = atof(value); keyword = PLATFORM_POSITION_Z_KW; value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "Platform position Z not given"); } thePlatformPos.z() = atof(value); //*** // Platform orientation matrix: //*** for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { ostringstream ostr; ostr << CAMERA_ORIENTATION_MATRIX_ELEM_KW << i << "_" << j << ends; ossimString s = ostr.str(); keyword = s.c_str(); value = kwl.find(prefix, keyword); if (!value) { ossimSetError(getClassName(), ossimErrorCodes::OSSIM_ERROR, "Camera orientation matrix not given"); } theLsrToEcfRot[i][j] = ossimString(value).toDouble(); } } //*** // Reading of optical distortion coefficients is left to the service object: //*** if (theOpticalDistortion) delete theOpticalDistortion; theOpticalDistortion = new ossimRadialDecentLensDistortion(kwl, prefix); //*** // Initialize given parameters read: //*** clearErrorStatus(); updateModel(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::loadState: returning..." << std::endl; return true; } //***************************************************************************** // PROTECTED METHOD: ossimFcsiModel::updateModel() // // Following a parameter adjustment, this method is called to recompute all // dependent quantities that are used by the projection methods. // //***************************************************************************** void ossimFcsiModel::updateModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::updateModel: entering..." << std::endl; //*** // Update the geometry... // Adjusted = Initial + adj_parm[i]*adj_sigma[i] // Some parameters have a zero initial value and that term is not included. //*** theEcfOffset.x() = getAdjustableParameter(X_POS) * getParameterSigma(X_POS); theEcfOffset.y() = getAdjustableParameter(Y_POS) * getParameterSigma(Y_POS); theEcfOffset.z() = getAdjustableParameter(Z_POS) * getParameterSigma(Z_POS); theXrotCorr = getAdjustableParameter(X_ROT) * getParameterSigma(X_ROT); theYrotCorr = getAdjustableParameter(Y_ROT) * getParameterSigma(Y_ROT); theZrotCorr = getAdjustableParameter(Z_ROT) * getParameterSigma(Z_ROT); theFocalOffset = getAdjustableParameter(FOCAL_LEN) * getParameterSigma(FOCAL_LEN); theScanSkewCorr = getAdjustableParameter(SCAN_SKEW) * getParameterSigma(SCAN_SKEW); //*** // Compute adjusted quatities used in projection code: //*** theAdjFocalLen = theFocalLen + theFocalOffset; theAdjPlatformPos = thePlatformPos + theEcfOffset; //*** // Establish the Scanner to film transform matrix. // // NOTE FOR IMPLEMENTING PARAMETER ADJUSTMENT: while the scan skew // angle is an adjustable parameter, the pixel scaling is not since this // error can be absorbed by the focal length adjustment, though the sigma // for the focal length must be inflated to account for the additional error // source. A similar situation occurrs with the scan rotation which manifests // as an attitude adjustment. //*** double cos_rot = ossim::cosd(theScanRotation); double sin_rot = ossim::sind(theScanRotation); double tan_skew = ossim::tand(theScanSkew + theScanSkewCorr); double a = theScanScaleMatrix[0]*(sin_rot*tan_skew + cos_rot) + theScanScaleMatrix[1]*(cos_rot*tan_skew - sin_rot); double b = theScanScaleMatrix[0]*sin_rot + theScanScaleMatrix[1]*cos_rot; double c = theScanScaleMatrix[2]*(sin_rot*tan_skew + cos_rot) + theScanScaleMatrix[3]*(cos_rot*tan_skew - sin_rot); double d = theScanScaleMatrix[2]*sin_rot + theScanScaleMatrix[3]*cos_rot; theScanXformMatrix[0] = a; theScanXformMatrix[1] = b; theScanXformMatrix[2] = c; theScanXformMatrix[3] = d; //*** // The inverse of the scanner-to-film transform must be computed since it is // not an orthogonal matrix (inverse != transpose): //*** theInvScanXformMatrix[0] = d/(d*a - b*c); theInvScanXformMatrix[1] = -b/(d*a - b*c); theInvScanXformMatrix[2] = c/(b*c - a*d); theInvScanXformMatrix[3] = -a/(b*c - a*d); //*** // Establish the differential rotation matrix due to attitude correction: //*** double cw = ossim::cosd(theXrotCorr); double sw = ossim::sind(theXrotCorr); double cp = ossim::cosd(theYrotCorr); double sp = ossim::sind(theYrotCorr); double ck = ossim::cosd(theZrotCorr); double sk = ossim::sind(theZrotCorr); NEWMAT::Matrix attitudeCorrection(3, 3); attitudeCorrection(1,1) = ck*cw - sk*sp*sw; attitudeCorrection(1,2) = sk*cp; attitudeCorrection(1,3) = ck*sw + sk*sp*cw; attitudeCorrection(2,1) = -sk*cw - ck*sp*sw; attitudeCorrection(2,2) = cp*ck; attitudeCorrection(2,3) = -sk*sw + ck*sp*cw; attitudeCorrection(3,1) = -cp*sw; attitudeCorrection(3,2) = -sp; attitudeCorrection(3,3) = cp*cw; //*** // Now compute the final LSR to ECF rotation: //*** theAdjLsrToEcfRot = attitudeCorrection * theLsrToEcfRot; theAdjEcfToLsrRot = theAdjLsrToEcfRot.t(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::updateModel: returning..." << std::endl; } //***************************************************************************** // PRIVATE METHOD: ossimFcsiModel::initAdjustableParameters() // // This method initializes the base class adjustable parameter and associated // sigmas arrays with quantities specific to this model. These are default // values only. A functional implementation would assign the sigmas via a // keywordlist or camera specific derived class. // //***************************************************************************** void ossimFcsiModel::initAdjustableParameters() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::initAdjustableParameters: entering..." << std::endl; int numParams = NUM_ADJUSTABLE_PARAMS; resizeAdjustableParameterArray(NUM_ADJUSTABLE_PARAMS); // if(!getNumberOfAdjustableParameters()) /// { //*** // Allocate storage for adjustables and assign their names and units strings //*** // newAdjustment(NUM_ADJUSTABLE_PARAMS); // } //*** // Initialize base-class adjustable parameter array: //*** for (int i=0; i\n" << PRINCIPAL_POINT_Y_KW << ": \n" << SCAN_SCALE_MATRIX_00_KW << ": \n" << SCAN_SCALE_MATRIX_01_KW << ": \n" << SCAN_SCALE_MATRIX_10_KW << ": \n" << SCAN_SCALE_MATRIX_11_KW << ": \n" << SCAN_SKEW_ANGLE_KW << ": [OPTIONAL]\n" << SCAN_ROTATION_ANGLE_KW << ": [OPTIONAL]\n" << FOCAL_LENGTH_KW << ": \n" << PLATFORM_POSITION_X_KW << ": \n" << PLATFORM_POSITION_Y_KW << ": \n" << PLATFORM_POSITION_Z_KW << ": \n" << "\n" << "//***\n" << "// Camera (LSR) to ECF orientation matrix:\n" << "//***\n"; for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { ostringstream ostr; ostr << CAMERA_ORIENTATION_MATRIX_ELEM_KW << i << "_" << j << ends; os << ostr.str() << ": \n"; } } os << "\n" << "//***\n" << "// Optical distortion coefficients [OPTIONAL]:\n" << "//***\n" << "distortion." << ossimRadialDecentLensDistortion::RADIAL_DISTORTION_COEFF_KW << "N: (for N <= 5)\n" << "distortion." << ossimRadialDecentLensDistortion::DECENT_DISTORTION_COEFF_KW << "N: (for N <= 4)\n" << endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimFcsiModel::writeGeomTemplate: returning..." << std::endl; return; } ossim-Miami-2.9.1/src/projection/ossimGnomonicProjection.cpp000066400000000000000000000352761352751253100242600ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimGnomonicProjection.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include RTTI_DEF1(ossimGnomonicProjection, "ossimGnomonicProjection", ossimMapProjection) #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define GNOM_NO_ERROR 0x0000 #define GNOM_LAT_ERROR 0x0001 #define GNOM_LON_ERROR 0x0002 #define GNOM_EASTING_ERROR 0x0004 #define GNOM_NORTHING_ERROR 0x0008 #define GNOM_ORIGIN_LAT_ERROR 0x0010 #define GNOM_CENT_MER_ERROR 0x0020 #define GNOM_A_ERROR 0x0040 #define GNOM_INV_F_ERROR 0x0080 ossimGnomonicProjection::ossimGnomonicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimGnomonicProjection::ossimGnomonicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Gnom_False_Easting = falseEasting; Gnom_False_Northing = falseNorthing; update(); } void ossimGnomonicProjection::update() { Set_Gnomonic_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Gnom_False_Easting, Gnom_False_Northing); theFalseEastingNorthing.x = Gnom_False_Easting; theFalseEastingNorthing.y = Gnom_False_Northing; ossimMapProjection::update(); } void ossimGnomonicProjection::setFalseEasting(double falseEasting) { Gnom_False_Easting = falseEasting; update(); } void ossimGnomonicProjection::setFalseNorthing(double falseNorthing) { Gnom_False_Northing = falseNorthing; update(); } void ossimGnomonicProjection::setDefaults() { Gnom_False_Easting = 0.0; Gnom_False_Northing = 0.0; Gnom_Delta_Northing = 40000000; Gnom_Delta_Easting = 40000000; } void ossimGnomonicProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Gnom_False_Easting = falseEasting; Gnom_False_Northing = falseNorthing; update(); } ossimGpt ossimGnomonicProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Gnomonic_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimGnomonicProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Gnomonic(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimGnomonicProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimGnomonicProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimGnomonicProjection)) { Gnom_False_Easting = theFalseEastingNorthing.x; Gnom_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimGnomonicProjection::Set_Gnomonic_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing) { /* BEGIN Set_Gnomonic_Parameters */ /* * The function Set_Gnomonic_Parameters receives the ellipsoid parameters and * projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise GNOM_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double es2, es4, es6; // double inv_f = 1 / f; long Error_Code = GNOM_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= GNOM_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= GNOM_INV_F_ERROR; // } // if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) // { /* origin latitude out of range */ // Error_Code |= GNOM_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= GNOM_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Gnom_a = a; Gnom_f = f; es2 = 2 * Gnom_f - Gnom_f * Gnom_f; es4 = es2 * es2; es6 = es4 * es2; /* spherical radius */ Ra = Gnom_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 / 3024.0); Gnom_Origin_Lat = Origin_Latitude; Sin_Gnom_Origin_Lat = sin(Gnom_Origin_Lat); Cos_Gnom_Origin_Lat = cos(Gnom_Origin_Lat); abs_Gnom_Origin_Lat = fabs(Gnom_Origin_Lat); // if (Central_Meridian > PI) // Central_Meridian -= TWO_PI; Gnom_Origin_Long = Central_Meridian; Gnom_False_Northing = False_Northing; Gnom_False_Easting = False_Easting; } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Gnomonic_Parameters */ void ossimGnomonicProjection::Get_Gnomonic_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Gnomonic_Parameters */ /* * The function Get_Gnomonic_Parameters returns the current ellipsoid * parameters and Gnomonic projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Gnom_a; *f = Gnom_f; *Origin_Latitude = Gnom_Origin_Lat; *Central_Meridian = Gnom_Origin_Long; *False_Easting = Gnom_False_Easting; *False_Northing = Gnom_False_Northing; return; } /* End Get_Gnomonic_Parameters */ long ossimGnomonicProjection::Convert_Geodetic_To_Gnomonic (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Gnomonic */ /* * The function Convert_Geodetic_To_Gnomonic converts geodetic (latitude and * longitude) coordinates to Gnomonic projection (easting and northing) * coordinates, according to the current ellipsoid and Gnomonic projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise GNOM_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double dlam; /* Longitude - Central Meridan */ double cos_c; double k_prime; /* scale factor */ double Ra_kprime; double slat = sin(Latitude); double clat = cos(Latitude); double Ra_cotlat; double sin_dlam, cos_dlam; double temp_Easting, temp_Northing; long Error_Code = GNOM_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= GNOM_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= GNOM_LON_ERROR; // } dlam = Longitude - Gnom_Origin_Long; sin_dlam = sin(dlam); cos_dlam = cos(dlam); cos_c = Sin_Gnom_Origin_Lat * slat + Cos_Gnom_Origin_Lat * clat * cos_dlam; if (cos_c <= 1.0e-10) { /* Point is out of view. Will return longitude out of range message since no point out of view is implemented. */ Error_Code |= GNOM_LON_ERROR; } if (!Error_Code) { /* no errors */ // if (dlam > PI) // { // dlam -= TWO_PI; // } // if (dlam < -PI) // { // dlam += TWO_PI; // } if (fabs(abs_Gnom_Origin_Lat - PI_OVER_2) < 1.0e-10) { Ra_cotlat = Ra * (clat / slat); temp_Easting = Ra_cotlat * sin_dlam; temp_Northing = Ra_cotlat * cos_dlam; if (Gnom_Origin_Lat >= 0.0) { *Easting = temp_Easting + Gnom_False_Easting; *Northing = -1.0 * temp_Northing + Gnom_False_Northing; } else { *Easting = -1.0 * temp_Easting + Gnom_False_Easting; *Northing = temp_Northing + Gnom_False_Northing; } } else if (abs_Gnom_Origin_Lat <= 1.0e-10) { *Easting = Ra * tan(dlam) + Gnom_False_Easting; *Northing = Ra * tan(Latitude) / cos_dlam + Gnom_False_Northing; } else { k_prime = 1 / cos_c; Ra_kprime = Ra * k_prime; *Easting = Ra_kprime * clat * sin_dlam + Gnom_False_Easting; *Northing = Ra_kprime * (Cos_Gnom_Origin_Lat * slat - Sin_Gnom_Origin_Lat * clat * cos_dlam) + Gnom_False_Northing; } } return (Error_Code); } /* End Convert_Geodetic_To_Gnomonic */ long ossimGnomonicProjection::Convert_Gnomonic_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Gnomonic_To_Geodetic */ /* * The function Convert_Gnomonic_To_Geodetic converts Gnomonic projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Gnomonic projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise GNOM_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx, dy; double rho; double c; double sin_c, cos_c; double dy_sinc; long Error_Code = GNOM_NO_ERROR; // if ((Easting < (Gnom_False_Easting - Gnom_Delta_Easting)) // || (Easting > (Gnom_False_Easting + Gnom_Delta_Easting))) // { /* Easting out of range */ // Error_Code |= GNOM_EASTING_ERROR; // } // if ((Northing < (Gnom_False_Northing - Gnom_Delta_Northing)) // || (Northing > (Gnom_False_Northing + Gnom_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= GNOM_NORTHING_ERROR; // } if (!Error_Code) { dy = Northing - Gnom_False_Northing; dx = Easting - Gnom_False_Easting; rho = sqrt(dx * dx + dy * dy); if (fabs(rho) <= 1.0e-10) { *Latitude = Gnom_Origin_Lat; *Longitude = Gnom_Origin_Long; } else { c = atan(rho / Ra); sin_c = sin(c); cos_c = cos(c); dy_sinc = dy * sin_c; *Latitude = asin((cos_c * Sin_Gnom_Origin_Lat) + ((dy_sinc * Cos_Gnom_Origin_Lat) / rho)); if (fabs(abs_Gnom_Origin_Lat - PI_OVER_2) < 1.0e-10) { if (Gnom_Origin_Lat >= 0.0) *Longitude = Gnom_Origin_Long + atan2(dx, -dy); else *Longitude = Gnom_Origin_Long + atan2(dx, dy); } else *Longitude = Gnom_Origin_Long + atan2((dx * sin_c), (rho * Cos_Gnom_Origin_Lat * cos_c - dy_sinc * Sin_Gnom_Origin_Lat)); } // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; // if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ // *Longitude = PI; // else if (*Longitude < -PI) // *Longitude = -PI; } return (Error_Code); } /* End Convert_Gnomonic_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimGoogleProjection.cpp000066400000000000000000000072441352751253100237150ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // //******************************************************************* #include RTTI_DEF1(ossimGoogleProjection, "ossimGoogleProjection", ossimMapProjection) //***************** THIS CODE WAS PULLED FROM THE INTERNET FOR GLOBAL MERCATOR ****** // I will leave as is without modifications // #define deg2rad(d) (((d)*M_PI)/180) #define rad2deg(d) (((d)*180)/M_PI) #define earth_radius 6378137 /* The following functions take or return there results in degrees */ double y2lat_d(double y) { return rad2deg(2 * atan(exp( deg2rad(y) ) ) - M_PI/2); } double x2lon_d(double x) { return x; } double lat2y_d(double lat) { return rad2deg(log(tan(M_PI/4+ deg2rad(lat)/2))); } double lon2x_d(double lon) { return lon; } /* The following functions take or return there results in something close to meters, along the equator */ double y2lat_m(double y) { return rad2deg(2 * atan(exp( (y / earth_radius ) )) - M_PI/2); } double x2lon_m(double x) { return rad2deg(x / earth_radius); } double lat2y_m(double lat) { return earth_radius * log(tan(M_PI/4+ deg2rad(lat)/2)); } double lon2x_m(double lon) { return deg2rad(lon) * earth_radius; } //******************** END GLOBAL MERCATOR CODE *********************** ossimGoogleProjection::ossimGoogleProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { thePcsCode = 3857; update(); } ossimGoogleProjection::ossimGoogleProjection(const ossimGoogleProjection& src) :ossimMapProjection(src) { thePcsCode = 3857; update(); } ossimGoogleProjection::~ossimGoogleProjection() { } void ossimGoogleProjection::update() { ossimMapProjection::update(); } ossimGpt ossimGoogleProjection::inverse(const ossimDpt &eastingNorthing)const { /* double lon = (eastingNorthing.x / 20037508.34) * 180.0; double lat = (eastingNorthing.y / 20037508.34) * 180.0; lat = 180.0/M_PI * (2.0 * atan(exp(lat * M_PI / 180)) - M_PI / 2.0); return ossimGpt(lat, lon, 0, theDatum); */ //return ossimGpt(merc_lat(eastingNorthing.y), merc_lon(eastingNorthing.x), 0, theDatum); return ossimGpt(y2lat_m(eastingNorthing.y), x2lon_m(eastingNorthing.x), 0, theDatum); } ossimDpt ossimGoogleProjection::forward(const ossimGpt &latLon)const { /* double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } //double y = Math.Log(Math.Tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180); easting = gpt.lond()*20037508.34/180.0; northing = log(tan((90.0 + gpt.latd())*M_PI/360.0))/(M_PI/180.0); northing *=20037508.34/180.0; return ossimDpt(easting, northing); */ return ossimDpt(lon2x_m(latLon.lond()), lat2y_m(latLon.latd())); } bool ossimGoogleProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimGoogleProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { thePcsCode = 3857; // Must do this first. bool flag = ossimMapProjection::loadState(kwl, prefix); update(); return flag; } bool ossimGoogleProjection::operator==(const ossimProjection& projection) const { if (!ossimMapProjection::operator==(projection)) return false; const ossimGoogleProjection* p = dynamic_cast(&projection); return (p != 0); } ossim-Miami-2.9.1/src/projection/ossimIkonosRpcModel.cpp000066400000000000000000000720711352751253100233340ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains implementation of class ossimIkonosRpcModel. This // derived class implements the capability of reading Ikonos RPC support // data. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimIkonosRpcModel.cpp 23323 2015-05-27 12:53:00Z gpotts $ #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimIkonosRpcModel, "ossimIkonosRpcModel", ossimRpcModel); //*** // Define Trace flags for use within this file: //*** static ossimTrace traceExec ("ossimIkonosRpcModel:exec"); static ossimTrace traceDebug ("ossimIkonosRpcModel:debug"); const ossimFilename INIT_RPC_GEOM_FILENAME ("rpc_init.geom"); static const char* MODEL_TYPE = "ossimIkonosRpcModel"; static const char* META_DATA_FILE = "meta_data_file"; static const char* RPC_DATA_FILE = "rpc_data_file"; static const char* LINE_OFF_KW = "LINE_OFF"; static const char* SAMP_OFF_KW = "SAMP_OFF"; static const char* LAT_OFF_KW = "LAT_OFF"; static const char* LONG_OFF_KW = "LONG_OFF"; static const char* HEIGHT_OFF_KW = "HEIGHT_OFF"; static const char* LINE_SCALE_KW = "LINE_SCALE"; static const char* SAMP_SCALE_KW = "SAMP_SCALE"; static const char* LAT_SCALE_KW = "LAT_SCALE"; static const char* LONG_SCALE_KW = "LONG_SCALE"; static const char* HEIGHT_SCALE_KW = "HEIGHT_SCALE"; static const char* LINE_NUM_COEFF_KW = "LINE_NUM_COEFF_"; static const char* LINE_DEN_COEFF_KW = "LINE_DEN_COEFF_"; static const char* SAMP_NUM_COEFF_KW = "SAMP_NUM_COEFF_"; static const char* SAMP_DEN_COEFF_KW = "SAMP_DEN_COEFF_"; ossimIkonosRpcModel::ossimIkonosRpcModel() :ossimRpcModel(), theSupportData(new ossimIkonosMetaData()) { } //***************************************************************************** // CONSTRUCTOR: ossimIkonosRpcModel // // Constructs given a geometry file that specifies the filenames for the // metadata and RPC data files. // //***************************************************************************** ossimIkonosRpcModel::ossimIkonosRpcModel(const ossimFilename& geom_file) : ossimRpcModel(), theSupportData(new ossimIkonosMetaData()) { if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel Constructor #1: entering..." << std::endl; } ossimKeywordlist kwl(geom_file); const char* value; //*** // Assure this keywordlist contains correct type info: //*** value = kwl.find(ossimKeywordNames::TYPE_KW); if (!value || (strcmp(value, "ossimIkonosRpcModel"))) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel Constructor #1:" << "\nFailed attempt to construct. sensor type \""<. "<< "doesn't exist..." << std::endl; } return false; } FILE* fptr = fopen (data_file, "r"); if (!fptr) { ++theErrorStatus; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimIkonosRpcModel::parseHdrData(data_file) WARN:" << "\nCould not open hdr data file <" << data_file << ">. " << "returning with error..." << std::endl; } return false; } char* strptr = 0; // char linebuf[80]; char dummy[80]; // , name[80]; //*** // Read the file into a buffer: //*** char filebuf[5000]; fread(filebuf, 1, 5000, fptr); //*** // GSD: NOTE - this will be recomputed by computeGsd method later. //*** strptr = strstr(filebuf, "\nPixel Size X:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimIkonosRpcModel::parseHdrData(data_file):" << "\n\tAborting construction. Error encountered parsing " << "presumed hdr file." << endl; } fclose( fptr ); // cleanup fptr = 0; return false; } sscanf(strptr, "%14c %lf", dummy, &theGSD.samp); strptr = strstr(strptr, "\nPixel Size Y:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimIkonosRpcModel::parseHdrData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed hdr file." << endl; } fclose( fptr ); // cleanup fptr = 0; return false; } sscanf(strptr, "%14c %lf", dummy, &theGSD.line); //*** // Image size: //*** strptr = strstr(strptr, "\nColumns:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimIkonosRpcModel::parseHdrData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed hdr file." << endl; } fclose( fptr ); // cleanup fptr = 0; return false; } sscanf(strptr, "%s %d", dummy, &theImageSize.samp); strptr = strstr(strptr, "\nRows:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimIkonosRpcModel::parseHdrData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed hdr file." << endl; } fclose( fptr ); // cleanup fptr = 0; return false; } sscanf(strptr, "%s %d", dummy, &theImageSize.line); fclose( fptr ); // cleanup fptr = 0; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel::parseHdrData(data_file): returning..." << std::endl; } return true; } //***************************************************************************** // PROTECTED METHOD: ossimIkonosRpcModel::parseRpcData() // // Parses the Ikonos RPC data file. // //***************************************************************************** void ossimIkonosRpcModel::parseRpcData(const ossimFilename& data_file) { if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel::parseRpcData(data_file): entering..." << std::endl; } if( !data_file.exists() ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimIkonosRpcModel::parseRpcData(data_file) WARN:" << "\nrpc data file <" << data_file << ">. "<< "doesn't exist..." << std::endl; } ++theErrorStatus; return; } //*** // The Ikonos RPC data file is conveniently formatted as KWL file: //*** ossimKeywordlist kwl (data_file); if (kwl.getErrorStatus()) { ossimNotify(ossimNotifyLevel_FATAL) << "ERROR ossimIkonosRpcModel::parseRpcData(data_file): Could not open RPC data file <" << data_file << ">. " << "Aborting..." << std::endl; ++theErrorStatus; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "returning with error..." << std::endl; return; } const char* buf; const char* keyword; //*** // Parse data from KWL: //*** keyword = LINE_OFF_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theLineOffset = atof(buf); keyword = SAMP_OFF_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theSampOffset = atof(buf); keyword = LAT_OFF_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theLatOffset = atof(buf); keyword = LONG_OFF_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theLonOffset = atof(buf); keyword = HEIGHT_OFF_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theHgtOffset = atof(buf); keyword = LINE_SCALE_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theLineScale = atof(buf); keyword = SAMP_SCALE_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theSampScale = atof(buf); keyword = LAT_SCALE_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } else { // copy ossimIkonosMetada-sensor into ossimIkonosRpcModel-sensorId theSensorID = theSupportData->getSensorID(); } theLatScale = atof(buf); keyword = LONG_SCALE_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theLonScale = atof(buf); keyword = HEIGHT_SCALE_KW; buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theHgtScale = atof(buf); char kwbuf[32]; keyword = kwbuf; for(int i=1; i<=20; i++) { sprintf(kwbuf, "%s%d", LINE_NUM_COEFF_KW, i); buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theLineNumCoef[i-1] = atof(buf); sprintf(kwbuf, "%s%d", LINE_DEN_COEFF_KW, i); buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theLineDenCoef[i-1] = atof(buf); sprintf(kwbuf, "%s%d", SAMP_NUM_COEFF_KW, i); buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theSampNumCoef[i-1] = atof(buf); sprintf(kwbuf, "%s%d", SAMP_DEN_COEFF_KW, i); buf = kwl.find(keyword); if (!buf) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseRpcData(data_file):" << "\nAborting construction. Error looking up keyword: " << keyword << std::endl; return; } theSampDenCoef[i-1] = atof(buf); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel::parseRpcData(data_file): returning..." << std::endl; return; theErrorStatus++; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel::parseRpcData(data_file): returning with error..." << std::endl; return; } //***************************************************************************** // METHOD: ossimIkonosRpcModel::writeGeomTemplate() // // Writes a template of an ossimIkonosRpcModel geometry file. // //***************************************************************************** void ossimIkonosRpcModel::writeGeomTemplate(ostream& os) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcModel::writeGeomTemplate(os): entering..." << std::endl; os << "//**************************************************************\n" "// Template for Ikonos RPC geometry keywordlist\n" "//\n" "// NOTE: It is preferable to select the full RPC geometry KWL \n" "// that should have been created with the first use of the\n" "// derived model type ossimIkonosRpcModel. Using this KWL \n" "// implies that an initial geometry is being constructed \n" "// with all adjustable parameters initialized to 0. \n" "//**************************************************************\n" << ossimKeywordNames::TYPE_KW << ": " << MODEL_TYPE << endl; os << META_DATA_FILE << ": \n" << RPC_DATA_FILE << ": \n" << endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcModel::writeGeomTemplate(os): returning..." << std::endl; return; } bool ossimIkonosRpcModel::saveState(ossimKeywordlist& kwl, const char* prefix)const { if(theSupportData.valid()) { ossimString supportPrefix = ossimString(prefix) + "support_data."; // copy ossimIkonosMetada-sensor into ossimIkonosRpcModel-sensorId theSupportData->saveState(kwl, supportPrefix); } ossimRpcModel::saveState(kwl, prefix); // this model just sets the base class values so // we do not need to re-construct this model so // specify the type as the base class type // // kwl.add(prefix, // ossimKeywordNames::TYPE_KW, // STATIC_TYPE_NAME(ossimRpcModel), // true); // cout << "kwl:\n" << kwl << std::endl; return true; } bool ossimIkonosRpcModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { if(theSupportData.valid()) { ossimString supportPrefix = ossimString(prefix) + "support_data."; theSupportData->loadState(kwl, supportPrefix); } return ossimRpcModel::loadState(kwl, prefix); } bool ossimIkonosRpcModel::parseFile(const ossimFilename& file) { return parseTiffFile(file); } bool ossimIkonosRpcModel::parseTiffFile(const ossimFilename& filename) { bool result = false; ossimRefPtr tiff = new ossimTiffTileSource(); if ( tiff->open(filename) ) { if ( !theSupportData ) { theSupportData = new ossimIkonosMetaData(); } if ( theSupportData->open(filename) == false ) { if(traceDebug()) { // Currently not required by model so we will not error out here. ossimNotify(ossimNotifyLevel_DEBUG) << "WARNING: ossimIkonosMetaData::open returned false.\n" << std::endl; } } else { // copy ossimIkonosMetada-sensor into ossimIkonosRpcModel-sensorId theSensorID = theSupportData->getSensorID(); } //convert file to rpc filename and hdr filename so we can get some info ossimFilename rpcfile = filename.noExtension(); rpcfile += "_rpc.txt"; ossimFilename hdrfile = filename; hdrfile.setExtension(ossimString("hdr")); if( parseHdrData(hdrfile) ) { // parseRpcData sets the error status on error. parseRpcData (rpcfile); if ( !getErrorStatus() ) //check for errors in parsing rpc data { finishConstruction(); //--- // Save current state in RPC model format: //--- ossimString drivePart; ossimString pathPart; ossimString filePart; ossimString extPart; filename.split(drivePart, pathPart, filePart, extPart); ossimFilename init_rpc_geom; init_rpc_geom.merge(drivePart, pathPart, INIT_RPC_GEOM_FILENAME, ""); ossimKeywordlist kwl (init_rpc_geom); saveState(kwl); // If we get here set the return status to true. result = true; } // matches: if ( !getErrorStatus() ) } // matches: if( parseHdrData(hdrfile) ) } // matches: if ( tiff->open(filename) ) if ( traceExec() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "return status: " << (result?"true\n":"false\n") << "DEBUG ossimIkonosRpcModel parseTiffFile: returning..." << std::endl; } return result; } bool ossimIkonosRpcModel::isNitf(const ossimFilename& filename) { std::ifstream in(filename.c_str(), ios::in|ios::binary); if(in) { char nitfFile[4]; in.read((char*)nitfFile, 4); return (ossimString(nitfFile, nitfFile+4) == "NITF"); } return false; } ossim-Miami-2.9.1/src/projection/ossimImageProjectionModel.cpp000066400000000000000000000026551352751253100245050ustar00rootroot00000000000000//----------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class definition of ossimImageProjectionModel. // //----------------------------------------------------------------------------- // $Id$ #include #include #include #include #include RTTI_DEF1(ossimImageProjectionModel, "ossimImageProjectionModel", ossimImageModel) ossimImageProjectionModel::ossimImageProjectionModel() : ossimImageModel(), theProjection(0) { } ossimImageProjectionModel::~ossimImageProjectionModel() { theProjection = 0; } void ossimImageProjectionModel::initialize(const ossimImageHandler& ih) { // Initialize base. ossimImageModel::initialize(ih); theProjection = 0; // Fetch the handler's image geometry and see if it has a projection: ossimImageHandler* iih = const_cast(&ih); // cast away constness ossimRefPtr image_geom = iih->getImageGeometry(); if ( image_geom.valid() ) { theProjection = image_geom->getProjection(); } } const ossimProjection* ossimImageProjectionModel::getProjection() const { return theProjection; } ossim-Miami-2.9.1/src/projection/ossimImageViewAffineTransform.cpp000066400000000000000000000233131352751253100253210ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimImageViewAffineTransform.cpp 23423 2015-07-13 19:07:38Z dburken $ #include #include #include #include RTTI_DEF1(ossimImageViewAffineTransform, "ossimImageViewAffineTransform", ossimImageViewTransform) ossimImageViewAffineTransform::ossimImageViewAffineTransform(double rotateDegrees, double imageScaleX, double imageScaleY, double scaleXValue, double scaleYValue, double translateXValue, double translateYValue, double pivotXValue, double pivotYValue) :m_transform(3,3), m_inverseTransform(3,3), m_rotation(rotateDegrees), m_imageSpaceScale(imageScaleX,imageScaleY), m_scale(scaleXValue, scaleYValue), m_translate(translateXValue, translateYValue), m_pivot(pivotXValue, pivotYValue) { m_transform << 1 << 0 << 0 << 0 << 1 << 0 << 0 << 0 << 1; m_inverseTransform << 1 << 0 << 0 << 0 << 1 << 0 << 0 << 0 << 1; rotate(rotateDegrees); scale(scaleXValue, scaleYValue); translate(translateXValue, translateYValue); pivot(m_pivot.x, m_pivot.y); } ossimImageViewAffineTransform::~ossimImageViewAffineTransform() { } void ossimImageViewAffineTransform::imageToView(const ossimDpt& imagePoint, ossimDpt& viewPoint)const { viewPoint.x = m_transform[0][0]*imagePoint.x + m_transform[0][1]*imagePoint.y + m_transform[0][2]; viewPoint.y = m_transform[1][0]*imagePoint.x + m_transform[1][1]*imagePoint.y + m_transform[1][2]; } void ossimImageViewAffineTransform::viewToImage(const ossimDpt& viewPoint, ossimDpt& imagePoint)const { imagePoint.x = m_inverseTransform[0][0]*viewPoint.x + m_inverseTransform[0][1]*viewPoint.y + m_inverseTransform[0][2]; imagePoint.y = m_inverseTransform[1][0]*viewPoint.x + m_inverseTransform[1][1]*viewPoint.y + m_inverseTransform[1][2]; } void ossimImageViewAffineTransform::setMatrix(NEWMAT::Matrix& matrix) { m_transform = matrix; m_inverseTransform = m_transform.i(); } const NEWMAT::Matrix& ossimImageViewAffineTransform::getMatrix()const { return m_transform; } void ossimImageViewAffineTransform::translate(double deltaX, double deltaY) { m_translate = ossimDpt(deltaX, deltaY); buildCompositeTransform(); // NEWMAT::Matrix m(3,3); // m << 1 << 0 << deltaX // << 0 << 1 << deltaY // << 0 << 0 << 1; // m_transform = m*m_transform; // m_inverseTransform = m_transform.i(); } void ossimImageViewAffineTransform::translateX(double deltaX) { translate(deltaX, m_translate.y); } void ossimImageViewAffineTransform::translateY(double deltaY) { translate(m_translate.x, deltaY); } void ossimImageViewAffineTransform::imageSpaceScale(double x, double y) { m_imageSpaceScale = ossimDpt(x,y); buildCompositeTransform(); } void ossimImageViewAffineTransform::imageSpaceScaleX(double x) { imageSpaceScale(x, m_imageSpaceScale.y); } void ossimImageViewAffineTransform::imageSpaceScaleY(double y) { imageSpaceScale(m_imageSpaceScale.x, y); } void ossimImageViewAffineTransform::scale(double x, double y) { // NEWMAT::Matrix m(3, 3); // m << x << 0 << 0 // << 0 << y << 0 // << 0 << 0 << 1; // m_transform = (m*m_transform); // m_inverseTransform = m_transform.i(); m_scale = ossimDpt(x,y); buildCompositeTransform(); } void ossimImageViewAffineTransform::scaleX(double x) { scale(x, m_scale.y); } void ossimImageViewAffineTransform::scaleY(double y) { scale(m_scale.x, y); } void ossimImageViewAffineTransform::pivot(double originX, double originY) { m_pivot.x = originX; m_pivot.y = originY; buildCompositeTransform(); } void ossimImageViewAffineTransform::pivotX(double originX) { pivot(originX,m_pivot.y); } void ossimImageViewAffineTransform::pivotY(double originY) { pivot(m_pivot.x, originY); } void ossimImageViewAffineTransform::rotate(double degrees) { m_rotation = degrees; buildCompositeTransform(); // m_transform = (m_transform * ossimMatrix3x3::createRotationZMatrix(degrees)); // m_transform = ossimMatrix3x3::createRotationZMatrix(degrees) * m_transform; // m_inverseTransform = m_transform.i(); } void ossimImageViewAffineTransform::buildCompositeTransform() { NEWMAT::Matrix imageSpaceScaleM(3,3); NEWMAT::Matrix scaleM(3, 3); NEWMAT::Matrix rotzM = ossimMatrix3x3::createRotationZMatrix(m_rotation); NEWMAT::Matrix transM(3,3); NEWMAT::Matrix transOriginM(3,3); NEWMAT::Matrix transOriginNegatedM(3,3); transM << 1 << 0 << m_translate.x << 0 << 1 << m_translate.y << 0 << 0 << 1; transOriginM << 1 << 0 << m_pivot.x << 0 << 1 << m_pivot.y << 0 << 0 << 1; transOriginNegatedM << 1 << 0 << -m_pivot.x << 0 << 1 << -m_pivot.y << 0 << 0 << 1; scaleM << m_scale.x << 0 << 0 << 0 << m_scale.y << 0 << 0 << 0 << 1; imageSpaceScaleM << m_imageSpaceScale.x << 0 << 0 << 0 << m_imageSpaceScale.y << 0 << 0 << 0 << 1; // m_transform = transOriginM*transM*scaleM*rotzM*transOriginNegatedM; // pivot should just be around the rotation m_transform = transM*scaleM*transOriginM*rotzM*imageSpaceScaleM*transOriginNegatedM; m_inverseTransform = m_transform.i(); } bool ossimImageViewAffineTransform::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString imageScaleString(kwl.find(prefix,"image_scale")); ossimString scaleString(kwl.find(prefix,"scale")); ossimString pivotString(kwl.find(prefix,"pivot")); ossimString translateString(kwl.find(prefix,"translate")); ossimString rotateString(kwl.find(prefix,"rotate")); if(!imageScaleString.empty()) { m_imageSpaceScale.toPoint(imageScaleString); } if(!scaleString.empty()) { m_scale.toPoint(scaleString); } if(!pivotString.empty()) { m_pivot.toPoint(pivotString); } if(!translateString.empty()) { m_translate.toPoint(translateString); } if(!rotateString.empty()) { m_rotation = rotateString.toDouble(); } buildCompositeTransform(); ossimImageViewTransform::loadState(kwl, prefix); return true; } bool ossimImageViewAffineTransform::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "image_scale", m_imageSpaceScale.toString(), true); kwl.add(prefix, "rotation", m_rotation, true); // Fixed for multithread sequencer load, this uses saveState/loadState to // clone image chains and rotate was not cloning, producing invalid tiles kwl.add(prefix, "rotate", m_rotation, true); kwl.add(prefix, "pivot", m_pivot.toString(), true); kwl.add(prefix, "scale", m_scale.toString(), true); kwl.add(prefix, "translate", m_translate.toString(), true); return ossimImageViewTransform::saveState(kwl,prefix); } bool ossimImageViewAffineTransform::isValid()const { return true; } bool ossimImageViewAffineTransform::setView(ossimObject* obj) { ossimImageViewAffineTransform* view = dynamic_cast (obj); if(view) { m_transform = view->m_transform; m_inverseTransform = view->m_inverseTransform; m_rotation = view->m_rotation; m_imageSpaceScale = view->m_imageSpaceScale; m_scale = view->m_scale; m_translate = view->m_translate; m_pivot = view->m_pivot; } return (view!=0); } ossimObject* ossimImageViewAffineTransform::getView() { return this; } const ossimObject* ossimImageViewAffineTransform::getView()const { return this; } ossimDpt ossimImageViewAffineTransform::getInputMetersPerPixel()const { return ossimDpt(1,1); } ossimDpt ossimImageViewAffineTransform::getOutputMetersPerPixel()const { ossimDpt result; result.makeNan(); return result; } bool ossimImageViewAffineTransform::isEqualTo(const ossimObject& obj, ossimCompareType compareType)const { bool result = ossimImageViewTransform::isEqualTo(obj,compareType); if(result) { result = false; const ossimImageViewAffineTransform* rhs = dynamic_cast (&obj); if(rhs) { result = (ossim::almostEqual(m_rotation, rhs->m_rotation)&& (m_imageSpaceScale.isEqualTo(rhs->m_imageSpaceScale))&& (m_scale.isEqualTo(rhs->m_scale))&& (m_translate.isEqualTo(rhs->m_translate))&& (m_pivot.isEqualTo(rhs->m_pivot)) ); } } return result; } ossim-Miami-2.9.1/src/projection/ossimImageViewProjectionTransform.cpp000066400000000000000000000622061352751253100262510ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimImageViewProjectionTransform.cc // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Garrett Potts // Oscar Kramer (oscar@krameranalytic.com) // // DESCRIPTION: Contains declaration of ossimImageViewProjectionTransform. // This class provides an image to view transform that utilizes two // independent 2D-to-3D projections. Intended for transforming view to // geographic "world" space to input image space. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimImageViewProjectionTransform.cpp 20489 2012-01-23 20:07:56Z dburken $ // #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimImageViewProjectionTransform, "ossimImageViewProjectionTransform", ossimImageViewTransform); //***************************************************************************** // CONSTRUCTOR: ossimImageViewProjectionTransform //***************************************************************************** ossimImageViewProjectionTransform::ossimImageViewProjectionTransform ( ossimImageGeometry* imageGeometry, ossimImageGeometry* viewGeometry) : m_imageGeometry(imageGeometry), m_viewGeometry(viewGeometry), m_crossesDateline(false) { } //***************************************************************************** // CONSTRUCTOR: ossimImageViewProjectionTransform //***************************************************************************** ossimImageViewProjectionTransform:: ossimImageViewProjectionTransform(const ossimImageViewProjectionTransform& src) : ossimImageViewTransform(src), m_imageGeometry(src.m_imageGeometry), m_viewGeometry(src.m_viewGeometry), m_crossesDateline(false) { } //***************************************************************************** // DESTRUCTOR: ~ossimImageViewProjectionTransform //***************************************************************************** ossimImageViewProjectionTransform::~ossimImageViewProjectionTransform() { } //! Assigns the geometry to use for output view. This object does NOT own the geometry. void ossimImageViewProjectionTransform::setViewGeometry(ossimImageGeometry* g) { m_viewGeometry = g; initializeDatelineCrossing(); } //! Assigns the geometry to use for input image. This object does NOT own the geometry. void ossimImageViewProjectionTransform::setImageGeometry(ossimImageGeometry* g) { m_imageGeometry = g; initializeDatelineCrossing(); } //***************************************************************************** // Workhorse of the object. Converts image-space to view-space. //***************************************************************************** void ossimImageViewProjectionTransform::imageToView(const ossimDpt& ip, ossimDpt& vp) const { // Check for same geometries on input and output (this includes NULL geoms): if (m_imageGeometry == m_viewGeometry) { vp = ip; return; } // Otherwise we need access to good geoms. Check for a bad geometry object: if (!m_imageGeometry || !m_viewGeometry) { vp.makeNan(); return; } // Check for same projection on input and output sides to save projection to ground: if (m_imageGeometry->getProjection() == m_viewGeometry->getProjection()) { // Check for possible same 2D transforms as well: if ( (m_imageGeometry->getTransform() == m_viewGeometry->getTransform()) && (m_imageGeometry->decimationFactor(0) == m_viewGeometry->decimationFactor(0)) ) { vp = ip; return; } // Not the same 2D transform, so just perform local-image -> full-image -> local-view: ossimDpt fp; m_imageGeometry->rnToFull(ip, 0, fp); m_viewGeometry->fullToRn(fp, 0, vp); return; } //--- // Completely different left and right side geoms (typical situation). // Need to project to ground. //--- ossimGpt gp; m_imageGeometry->localToWorld(ip, gp); m_viewGeometry->worldToLocal(gp, vp); #if 0 /* Please leave for debug. */ cout <<"DEBUG ossimImageViewProjectionTransform::imageToView:" <<"\n ip: "<getProjection(); const ossimProjection* vproj = m_viewGeometry->getProjection(); if ((iproj && vproj && iproj->isEqualTo(*vproj)) || (iproj == vproj)) { // Check for possible same 2D transforms as well: const ossim2dTo2dTransform* ixform = m_imageGeometry->getTransform(); const ossim2dTo2dTransform* vxform = m_viewGeometry->getTransform(); if (((ixform && vxform && ixform->isEqualTo(*vxform)) || (ixform == vxform)) && (m_imageGeometry->decimationFactor(0) == m_viewGeometry->decimationFactor(0))) { ip = vp; return; } // Not the same 2D transform, so just perform local-image -> full-image -> local-view: ossimDpt fp; m_viewGeometry->rnToFull(vp, 0, fp); m_imageGeometry->fullToRn(fp, 0, ip); return; } //--- // Completely different left and right side geoms (typical situation). // Need to project to ground. //--- ossimGpt gp; m_viewGeometry->localToWorld(vp, gp); m_imageGeometry->worldToLocal(gp, ip); #if 0 /* Please leave for debug. */ cout <<"DEBUG ossimImageViewProjectionTransform::viewToImage:" <<"\n vp: "<& viewBounds, ossimPolyArea2d& polyArea, ossim_uint32 numberOfEdgePoints)const { ossimDrect imageRect; ossimDrect worldRect(ossimDpt(-180,-90), ossimDpt(-180,90), ossimDpt(180,90), ossimDpt(180,-90)); viewBounds.clear(); polyArea.clear(); if(m_imageGeometry.valid()) { m_imageGeometry->getBoundingRect(imageRect); ossim_uint32 idx=0; std::vector points; std::vector gPoints; bool affectedByElevation = m_imageGeometry->isAffectedByElevation(); if((numberOfEdgePoints > 2)&&(affectedByElevation)) { m_imageGeometry->getImageEdgePoints(points, numberOfEdgePoints); } else { points.resize(4); points[0] = imageRect.ul(); points[1] = imageRect.ur(); points[2] = imageRect.lr(); points[3] = imageRect.ll(); } if(m_crossesDateline) { ossimDpt testPt; ossimGpt cg; m_imageGeometry->localToWorld(imageRect.midPoint(), cg); ossim_int32 sgn = static_cast(ossim::sgn(cg.lond())); std::vector polyList; for(idx=0; idx < points.size();++idx) { ossimGpt testGpt; m_imageGeometry->localToWorld(points[idx], testGpt); if(!testGpt.isLatNan()&&!testGpt.isLonNan()) { gPoints.push_back(testGpt); } } // first we get the list of ground points initialized // and shifted to one side of the full world rect // We will do the other side next // for(idx=0; idx < gPoints.size();++idx) { if(std::fabs(gPoints[idx].lond()-cg.lond()) > 180) { gPoints[idx].lond(gPoints[idx].lond()+sgn*360); } } // now clip the ground list to the full ground rect // ossimPolygon tempPoly(gPoints); tempPoly.clipToRect(polyList, worldRect); ossim_uint32 pointListIdx=0; // Loop through the clipped polygons and find their // view projection. We will add this to the view // bounds and we will add to the poly Area. Poly Area // is used for a tighter clip. // for(pointListIdx=0;pointListIdx& clipPoints = polyList[pointListIdx].getVertexList(); points.clear(); for(idx = 0; idxworldToLocal(ossimGpt(clipPoints[idx]), testPt); if(!testPt.hasNans()) { points.push_back(testPt); } } viewBounds.push_back(ossimDrect(points)); if (points.size() >= 4) { points.push_back(points[0]); polyArea.add(ossimPolyArea2d(points));//ossimPolygon(points))); } } // now shift the ground points to the other side of the world rect // for(idx=0; idx < gPoints.size();++idx) { gPoints[idx].lond(gPoints[idx].lond()+(-sgn*360)); } // Now we will do the same thing to the other side of the world // and find the view projection and add those to the poly area // and the view rect // tempPoly = gPoints; polyList.clear(); tempPoly.clipToRect(polyList, worldRect); for(pointListIdx=0;pointListIdx& clipPoints = polyList[pointListIdx].getVertexList(); points.clear(); for(idx = 0; idxworldToLocal(ossimGpt(clipPoints[idx]), testPt); if(!testPt.hasNans()) { points.push_back(testPt); } } viewBounds.push_back(ossimDrect(points)); if (points.size() >= 4) { points.push_back(points[0]); polyArea.add(ossimPolyArea2d(points));//ossimPolygon(points))); } } }// end: if(m_crossesDateline) else { ossimDpt testPoint; std::vector vpoints; for(idx=0; idx < points.size();++idx) { ossimDpt testDpt; imageToView(points[idx], testDpt); if(!testDpt.hasNans()) { vpoints.push_back(testDpt); } } if(vpoints.size()) { vpoints.push_back(vpoints[0]); viewBounds.push_back(ossimDrect(vpoints)); polyArea = vpoints;// = ossimPolyArea2d(points); } } } } bool ossimImageViewProjectionTransform::setView(ossimObject* baseObject) { ossimImageGeometry* g = dynamic_cast(baseObject); bool new_view_set = false; m_crossesDateline = false; if (g) { m_viewGeometry = g; new_view_set = true; } else { ossimProjection* proj = dynamic_cast(baseObject); if(proj) { if(m_viewGeometry.valid()) { m_viewGeometry->setProjection(proj); } else { m_viewGeometry = new ossimImageGeometry(0, proj); } new_view_set = true; } } if ( m_viewGeometry.valid() && m_viewGeometry-> getImageSize().hasNans() ) { // Sets the view image size from the image geometry if present. initializeViewSize(); } return new_view_set; } //***************************************************************************** // Dumps contents to stream //***************************************************************************** std::ostream& ossimImageViewProjectionTransform::print(std::ostream& out)const { out << "ossimImageViewProjectionTransform::print: ..... entered " <print(out); } else { out << " None defined." << endl; } if(m_viewGeometry.valid()) { out << "Output View (RIGHT) Geometry: " << endl; m_viewGeometry->print(out); } else { out << " None defined." << endl; } return out; } //************************************************************************************************** // Converts the local image space rect into bounding view-space rect //************************************************************************************************** ossimDrect ossimImageViewProjectionTransform::getImageToViewBounds(const ossimDrect& imageRect)const { // Let base class try: ossimDrect result = ossimImageViewTransform::getImageToViewBounds(imageRect); // If not successful, compute using input and output geometries: if (result.hasNans() && m_imageGeometry.valid() && m_viewGeometry.valid() && m_imageGeometry->hasProjection() && m_viewGeometry->hasProjection()) { ossimGeoPolygon viewClip; m_viewGeometry->getProjection()->getGroundClipPoints(viewClip); if(viewClip.size()) { std::vector imageGpts(4); m_imageGeometry->localToWorld(imageRect.ul(), imageGpts[0]); m_imageGeometry->localToWorld(imageRect.ur(), imageGpts[1]); m_imageGeometry->localToWorld(imageRect.lr(), imageGpts[2]); m_imageGeometry->localToWorld(imageRect.ll(), imageGpts[3]); const ossimDatum* viewDatum = m_viewGeometry->getProjection()->origin().datum(); imageGpts[0].changeDatum(viewDatum); imageGpts[1].changeDatum(viewDatum); imageGpts[2].changeDatum(viewDatum); imageGpts[3].changeDatum(viewDatum); ossimPolyArea2d viewPolyArea(viewClip.getVertexList()); ossimPolyArea2d imagePolyArea(imageGpts); viewPolyArea &= imagePolyArea; std::vector visiblePolygons; viewPolyArea.getVisiblePolygons(visiblePolygons); if(visiblePolygons.size()) { std::vector vpts; ossim_uint32 idx = 0; for(idx=0; idxworldToLocal(gpt, tempPt); vpts.push_back(tempPt); } result = ossimDrect(vpts); } } } return result; } //***************************************************************************** // METHOD: ossimImageViewProjectionTransform::loadState //***************************************************************************** bool ossimImageViewProjectionTransform::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimImageViewTransform::loadState(kwl, prefix); if(result) { ossimString imagePrefix = ossimString(prefix)+"image_geometry."; ossimString viewPrefix = ossimString(prefix)+"view_geometry."; if(kwl.numberOf(imagePrefix.c_str())>0) { m_imageGeometry = new ossimImageGeometry(); m_imageGeometry->loadState(kwl, imagePrefix.c_str()); } if(kwl.numberOf(viewPrefix.c_str())>0) { m_viewGeometry = new ossimImageGeometry(); m_viewGeometry->loadState(kwl, viewPrefix.c_str()); } } return result; } //************************************************************************************************** // //************************************************************************************************** bool ossimImageViewProjectionTransform::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString imagePrefix = ossimString(prefix)+"image_geometry."; ossimString viewPrefix = ossimString(prefix)+"view_geometry."; if(m_imageGeometry.valid()) { m_imageGeometry->saveState(kwl, imagePrefix.c_str()); } if(m_viewGeometry.valid()) { m_viewGeometry->saveState(kwl, viewPrefix.c_str()); } return ossimImageViewTransform::saveState(kwl, prefix); } //************************************************************************************************** // Returns the GSD of input image. //************************************************************************************************** ossimDpt ossimImageViewProjectionTransform::getInputMetersPerPixel() const { ossimDpt result; if (m_imageGeometry.valid() && m_imageGeometry->hasProjection()) result = m_imageGeometry->getProjection()->getMetersPerPixel(); else result.makeNan(); return result; } //************************************************************************************************** // Returns the GSD of the output view. //************************************************************************************************** ossimDpt ossimImageViewProjectionTransform::getOutputMetersPerPixel() const { ossimDpt result; if(m_viewGeometry.valid() && m_viewGeometry->hasProjection()) result = m_viewGeometry->getProjection()->getMetersPerPixel(); else result.makeNan(); return result; } // Initialize view geometry image size from image geometry. bool ossimImageViewProjectionTransform::initializeViewSize() { bool result = false; m_crossesDateline = false; if ( m_imageGeometry.valid() ) { m_crossesDateline = m_imageGeometry->getCrossesDateline(); ossimDrect imageRect( 0, 0, m_imageGeometry->getImageSize().x - 1, m_imageGeometry->getImageSize().y - 1); ossimDpt size; ossimDrect rect; if(m_crossesDateline) { ossimGpt ulg; ossimGpt urg; ossimGpt lrg; ossimGpt llg; ossimGpt cg; ossimDpt ul; ossimDpt ur; ossimDpt lr; ossimDpt ll; m_imageGeometry->localToWorld(imageRect.ul(), ulg); m_imageGeometry->localToWorld(imageRect.ur(), urg); m_imageGeometry->localToWorld(imageRect.lr(), lrg); m_imageGeometry->localToWorld(imageRect.ll(), llg); m_imageGeometry->localToWorld(imageRect.midPoint(), cg); if(std::fabs(ulg.lond()-cg.lond()) > 180) { ulg.lond(ulg.lond()+ossim::sgn(cg.lond())*360); } if(std::fabs(urg.lond()-cg.lond()) > 180) { urg.lond((urg.lond()+ossim::sgn(cg.lond())*360)); } if(std::fabs(lrg.lond()-cg.lond()) > 180) { lrg.lond(lrg.lond()+ossim::sgn(cg.lond())*360); } if(std::fabs(llg.lond()-cg.lond()) > 180) { llg.lond(llg.lond()+ossim::sgn(cg.lond())*360); } m_viewGeometry->worldToLocal(ulg, ul); m_viewGeometry->worldToLocal(urg, ur); m_viewGeometry->worldToLocal(lrg, lr); m_viewGeometry->worldToLocal(llg, ll); rect= ossimDrect(ul,ur,lr,ll); } else { rect = getImageToViewBounds( imageRect ); } size.x = ossim::round( rect.width() ); size.y = ossim::round( rect.height() ); if ( size.hasNans() == false ) { m_viewGeometry->setImageSize( size ); result = true; } // std::cout << "VIEW SIZE ============== " << size << "\n"; #if 0 if ( (imageRect.hasNans() == false) && m_viewGeometry.valid() ) { ossimRefPtr viewProj = m_viewGeometry->getProjection(); if ( viewProj.valid() ) { ossimIpt size; size.makeNan(); const ossimEquDistCylProjection* eqProj = dynamic_cast( viewProj.get() ); if ( eqProj ) { // Specialized to take into consideration a date line crossing. // Get the ground points we need: ossimDpt iRight(imageRect.ul().x+1, imageRect.ul().y); ossimDpt iDown(imageRect.ul().x, imageRect.ul().y+1); ossimGpt gul; ossimGpt gur; ossimGpt glr; ossimGpt gll; ossimGpt gRight; ossimGpt gDown; ossim_float64 hdd; // height decimal degrees ossim_float64 wdd; // width decimal degrees ossim_float64 leftLon; ossim_float64 rightLon; m_imageGeometry->localToWorld( imageRect.ul(), gul ); m_imageGeometry->localToWorld( imageRect.ur(), gur ); m_imageGeometry->localToWorld( imageRect.lr(), glr ); m_imageGeometry->localToWorld( imageRect.ll(), gll ); m_imageGeometry->localToWorld( iRight, gRight ); m_imageGeometry->localToWorld( iDown, gDown ); //--- // Determine the direction of the image and get the geographic bounding box. // For the longitude consider a date line crossing. //--- if ( gul.lat > gDown.lat ) // oriented north up { if ( gul.lat >= gRight.lat ) // straight up or leaning right { hdd = gul.lat - glr.lat; leftLon = gll.lon; rightLon = gur.lon; } else // leaning left { hdd = gur.lat - gll.lat; leftLon = gul.lon; rightLon = glr.lon; } } else // south or on side { if ( gRight.lat >= gul.lat ) // straight down or leaning right { hdd = glr.lat - gul.lat; leftLon = gur.lon; rightLon = gll.lon; } else // leaning left { hdd = gll.lat - gur.lat; leftLon = glr.lon; rightLon = gul.lon; } } if ( rightLon > leftLon ) { wdd = rightLon - leftLon; } else // Date line cross: { wdd = rightLon + 360.0 - leftLon; } //--- // Add one pixel width/height to the point to point size to make it edge to edge // before dividing by gsd to get the size. The view projection gsd is used here // since the view could be a different resolution than the input projection. //--- size.x = ossim::round( ( wdd + eqProj->getDecimalDegreesPerPixel().x ) / eqProj->getDecimalDegreesPerPixel().x ); size.y = ossim::round( ( hdd + eqProj->getDecimalDegreesPerPixel().y ) / eqProj->getDecimalDegreesPerPixel().y ); #if 0 /* Please leave for debug: */ cout << "\nwdd: " << wdd << "\nhdd: " << hdd << "\ngul: " << gul << "\ngur: " << gur << "\nglr: " << glr << "\ngll: " << gll << endl; #endif } else // Not an ossimEquDistCylProjection: { ossimDrect rect = getImageToViewBounds( imageRect ); size.x = ossim::round( rect.width() ); size.y = ossim::round( rect.height() ); } #if 0 /* Please leave for debug: */ cout << "m_imageGeometry:\n" << *(m_imageGeometry.get()) << "\n\nm_viewGeometry:\n" << *(m_viewGeometry.get()) << "\n\ncomputed view size: " << size << endl; #endif if ( size.hasNans() == false ) { m_viewGeometry->setImageSize( size ); result = true; } } // Matches: if ( viewProj.valid() ) } // Matches: if ( (imageRect.hasNans() == false) ... #endif } // Matches: if ( m_imageGeometry.valid() && ... return result; } // End: bool ossimImageViewProjectionTransform::initializeViewSize() void ossimImageViewProjectionTransform::initializeDatelineCrossing() { m_crossesDateline = false; if(m_imageGeometry.valid()) { m_crossesDateline = m_imageGeometry->getCrossesDateline(); } }ossim-Miami-2.9.1/src/projection/ossimImageViewTransform.cpp000066400000000000000000000265161352751253100242200ustar00rootroot00000000000000#include #include #include #include #include RTTI_DEF2(ossimImageViewTransform, "ossimImageViewTransform", ossim2dTo2dTransform, ossimViewInterface) ossimImageViewTransform::ossimImageViewTransform() : ossim2dTo2dTransform(), ossimViewInterface(NULL) { ossimViewInterface::theObject = this; } void ossimImageViewTransform::forward(const ossimDpt& input, ossimDpt& output) const { imageToView(input, output); } void ossimImageViewTransform::inverse(const ossimDpt& input, ossimDpt& output) const { viewToImage(input, output); } void ossimImageViewTransform::imageToView(const ossimDpt& imagePoint, ossimDpt& viewPoint)const { viewPoint = imagePoint; } void ossimImageViewTransform::viewToImage(const ossimDpt& viewPoint, ossimDpt& imagePoint)const { ossim2dTo2dTransform::inverse(viewPoint, imagePoint); } ossimDpt ossimImageViewTransform::imageToView(const ossimDpt& imagePoint)const { ossimDpt tempPt; imageToView(imagePoint, tempPt); return tempPt; } ossimDpt ossimImageViewTransform::viewToImage(const ossimDpt& viewPoint)const { ossimDpt tempPt; viewToImage(viewPoint, tempPt); return tempPt; } void ossimImageViewTransform::getRoundTripErrorView(ossimDpt& result, const ossimDpt& viewPt )const { ossimDpt ipt; ossimDpt vpt; viewToImage(viewPt, ipt); if(ipt.hasNans()) { vpt.makeNan(); } else { imageToView(ipt, vpt); } if(vpt.hasNans()) { result.makeNan(); } else { result = viewPt-vpt; } // result = ossimDpt(0,0); } ossimDpt ossimImageViewTransform::getRoundTripErrorView(const ossimDpt& viewPt)const { ossimDpt result; getRoundTripErrorView(result, viewPt); return result; } void ossimImageViewTransform::getRoundTripErrorImage(ossimDpt& result, const ossimDpt& imagePt )const { ossimDpt ipt; ossimDpt vpt; imageToView(imagePt, vpt); if(vpt.hasNans()) { ipt.makeNan(); } else { viewToImage(vpt, ipt); } if(ipt.hasNans()) { result.makeNan(); } else { result = imagePt-ipt; } // result = ossimDpt(0,0); } ossimDpt ossimImageViewTransform::getRoundTripErrorImage(const ossimDpt& imagePt)const { ossimDpt result; getRoundTripErrorView(result, imagePt); return result; } bool ossimImageViewTransform::loadState(const ossimKeywordlist& kwl, const char* prefix) { return ossim2dTo2dTransform::loadState(kwl, prefix); } bool ossimImageViewTransform::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossim2dTo2dTransform::saveState(kwl, prefix); } void ossimImageViewTransform::getScaleChangeImageToView(ossimDpt& result, const ossimDrect& imageRect) { result.makeNan(); if(!imageRect.hasNans()) { ossimDpt vul; ossimDpt vur; ossimDpt vlr; ossimDpt vll; imageToView(imageRect.ul(), vul); imageToView(imageRect.ur(), vur); imageToView(imageRect.lr(), vlr); imageToView(imageRect.ll(), vll); if(!vul.hasNans()&& !vur.hasNans()&& !vlr.hasNans()&& !vll.hasNans()) { double deltaTop = (vul - vur).length(); double deltaBottom = (vll - vlr).length(); double deltaRight = (vur - vlr).length(); double w = imageRect.width(); double h = imageRect.height(); result.x = (deltaTop/w + deltaBottom/w)*.5; result.y = (deltaRight/h + deltaRight/h)*.5; } } } void ossimImageViewTransform::getScaleChangeViewToImage(ossimDpt& result, const ossimDrect& viewRect) { result.makeNan(); if(!viewRect.hasNans()) { ossimDpt iul; ossimDpt iur; ossimDpt ilr; ossimDpt ill; imageToView(viewRect.ul(), iul); imageToView(viewRect.ur(), iur); imageToView(viewRect.lr(), ilr); imageToView(viewRect.ll(), ill); if(!iul.hasNans()&& !iur.hasNans()&& !ilr.hasNans()&& !ill.hasNans()) { double deltaTop = (iul - iur).length(); double deltaBottom = (ill - ilr).length(); double deltaRight = (iur - ilr).length(); double w = viewRect.width(); double h = viewRect.height(); result.x = (deltaTop/w + deltaBottom/w)*.5; result.y = (deltaRight/h + deltaRight/h)*.5; } } } ossimDrect ossimImageViewTransform::getImageToViewBounds(const ossimDrect& imageRect)const { ossimDpt p1; ossimDpt p2; ossimDpt p3; ossimDpt p4; imageToView(imageRect.ul(), p1); imageToView(imageRect.ur(), p2); imageToView(imageRect.lr(), p3); imageToView(imageRect.ll(), p4); return ossimDrect(p1, p2, p3, p4); } ossimDrect ossimImageViewTransform::getViewToImageBounds(const ossimDrect& viewRect)const { ossimDpt p1; ossimDpt p2; ossimDpt p3; ossimDpt p4; viewToImage(viewRect.ul(), p1); viewToImage(viewRect.ur(), p2); viewToImage(viewRect.lr(), p3); viewToImage(viewRect.ll(), p4); return ossimDrect(p1, p2, p3, p4); } #if 0 void ossimImageViewTransform::getViewToImageScale(ossimDpt &resultScale, const ossimDpt &viewPoint, const ossimDpt &deltaViewPointXY) const { ossimDpt p1 = viewPoint; ossimDpt p2(viewPoint.x + deltaViewPointXY.x, viewPoint.y); ossimDpt p3(viewPoint.x, viewPoint.y + deltaViewPointXY.y); ossimDpt transformedP1; ossimDpt transformedP2; ossimDpt transformedP3; viewToImage(p1, transformedP1); viewToImage(p2, transformedP2); viewToImage(p3, transformedP3); ossimDpt deltaP1P2 = transformedP1 - transformedP2; ossimDpt deltaP1P3 = transformedP1 - transformedP3; // now compute the distances. double sumSquaredSqrtP1P2 = sqrt((deltaP1P2.x * deltaP1P2.x) + (deltaP1P2.y * deltaP1P2.y)); double sumSquaredSqrtP1P3 = sqrt((deltaP1P3.x * deltaP1P3.x) + (deltaP1P3.y * deltaP1P3.y)); resultScale.x = 0; resultScale.y = 0; if (sumSquaredSqrtP1P2 > FLT_EPSILON) { resultScale.x = sumSquaredSqrtP1P2 / deltaViewPointXY.x; } if (sumSquaredSqrtP1P3 > FLT_EPSILON) { resultScale.y = sumSquaredSqrtP1P3 / deltaViewPointXY.y; } } #else void ossimImageViewTransform::getViewToImageScale(ossimDpt &result, const ossimDpt &viewSeedPoint, const ossimDpt &dxdy) const { result.makeNan(); ossimDpt dxdyHalf(dxdy.x / 2.0, dxdy.y / 2.0); ossimDpt iptdx1 = viewSeedPoint - ossimDpt(dxdyHalf.x, 0.0); ossimDpt iptdx2 = iptdx1 + ossimDpt(dxdy.x, 0.0); ossimDpt iptdy1 = viewSeedPoint - ossimDpt(dxdyHalf.y, 0.0); ossimDpt iptdy2 = iptdx1 + ossimDpt(0.0, dxdy.y); ossimDpt dx1; ossimDpt dx2; ossimDpt dy1; ossimDpt dy2; viewToImage(iptdx1, dx1); viewToImage(iptdx2, dx2); viewToImage(iptdy1, dy1); viewToImage(iptdy2, dy2); if (!(dx1.hasNans() || dx2.hasNans())) { ossimDpt delta = dx1 - dx2; // now compute the distances. ossim_float64 sumSquared = sqrt((delta.x * delta.x) + (delta.y * delta.y)); if (sumSquared > FLT_EPSILON) { result.x = sumSquared / dxdy.x; } else { result.x = ossim::nan(); } } if (!(dy1.hasNans() || dy2.hasNans())) { ossimDpt delta = dy1 - dy2; // now compute the distances. ossim_float64 sumSquared = sqrt((delta.x * delta.x) + (delta.y * delta.y)); if (sumSquared > FLT_EPSILON) { result.y = sumSquared / dxdy.y; } else { result.y = ossim::nan(); } } if (result.hasNans()) { result.makeNan(); } } #endif #if 0 void ossimImageViewTransform::getImageToViewScale(ossimDpt &resultScale, const ossimDpt &imagePoint, const ossimDpt &deltaImagePointXY) const { ossimDpt p1 = imagePoint; ossimDpt p2(imagePoint.x + deltaImagePointXY.x, imagePoint.y); ossimDpt p3(imagePoint.x, imagePoint.y + deltaImagePointXY.y); ossimDpt transformedP1; ossimDpt transformedP2; ossimDpt transformedP3; imageToView(p1, transformedP1); imageToView(p2, transformedP2); imageToView(p3, transformedP3); ossimDpt deltaP1P2 = transformedP1 - transformedP2; ossimDpt deltaP1P3 = transformedP1 - transformedP3; // now compute the distances. double sumSquaredSqrtP1P2 = sqrt((deltaP1P2.x * deltaP1P2.x) + (deltaP1P2.y * deltaP1P2.y)); double sumSquaredSqrtP1P3 = sqrt((deltaP1P3.x * deltaP1P3.x) + (deltaP1P3.y * deltaP1P3.y)); resultScale.x = 0; resultScale.y = 0; if (sumSquaredSqrtP1P2 > FLT_EPSILON) { resultScale.x = sumSquaredSqrtP1P2 / deltaImagePointXY.x; } if (sumSquaredSqrtP1P3 > FLT_EPSILON) { resultScale.y = sumSquaredSqrtP1P3 / deltaImagePointXY.y; } } #else void ossimImageViewTransform::getImageToViewScale(ossimDpt &result, const ossimDpt &imageSeedPoint, const ossimDpt &dxdy) const { result.makeNan(); ossimDpt dxdyHalf(dxdy.x / 2.0, dxdy.y / 2.0); ossimDpt iptdx1 = imageSeedPoint - ossimDpt(dxdyHalf.x, 0.0); ossimDpt iptdx2 = iptdx1 + ossimDpt(dxdy.x,0.0); ossimDpt iptdy1 = imageSeedPoint - ossimDpt(dxdyHalf.y, 0.0); ossimDpt iptdy2 = iptdx1 + ossimDpt(0.0,dxdy.y); ossimDpt dx1; ossimDpt dx2; ossimDpt dy1; ossimDpt dy2; imageToView(iptdx1, dx1); imageToView(iptdx2, dx2); imageToView(iptdy1, dy1); imageToView(iptdy2, dy2); if (!(dx1.hasNans() || dx2.hasNans())) { ossimDpt delta = dx1 - dx2; // now compute the distances. ossim_float64 sumSquared = sqrt((delta.x * delta.x) + (delta.y * delta.y)); if (sumSquared > FLT_EPSILON) { result.x = sumSquared / dxdy.x; } else { result.x = ossim::nan(); } } if (!(dy1.hasNans() || dy2.hasNans())) { ossimDpt delta = dy1 - dy2; // now compute the distances. ossim_float64 sumSquared = sqrt((delta.x * delta.x) + (delta.y * delta.y)); if (sumSquared > FLT_EPSILON) { result.y = sumSquared / dxdy.y; } else { result.y = ossim::nan(); } } if (result.hasNans()) { result.makeNan(); } } #endif std::ostream& ossimImageViewTransform::print(std::ostream& out) const { return out; } std::ostream& operator<<(std::ostream& out, const ossimImageViewTransform& data) { return data.print(out); } ossim-Miami-2.9.1/src/projection/ossimImageViewTransformFactory.cpp000066400000000000000000000031571352751253100255440ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // //******************************************************************* // $Id: ossimImageViewTransformFactory.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include #include #include RTTI_DEF1(ossimImageViewTransformFactory, "ossimImageViewTransformFactory", ossimObject) ossimImageViewTransformFactory* ossimImageViewTransformFactory::theInstance = 0; ossimImageViewTransformFactory* ossimImageViewTransformFactory::instance() { if(!theInstance) { theInstance = new ossimImageViewTransformFactory; } return theInstance; } ossimImageViewTransform* ossimImageViewTransformFactory::createTransform(const ossimKeywordlist& kwl, const char* prefix) { ossimImageViewTransform* result=NULL; const char *lookup = kwl.find(prefix, "type"); if(lookup) { if(ossimString(lookup) == STATIC_TYPE_NAME(ossimImageViewProjectionTransform)) { result = new ossimImageViewProjectionTransform; } if(ossimString(lookup) == STATIC_TYPE_NAME(ossimImageViewAffineTransform)) { result = new ossimImageViewAffineTransform; } } if(result) { result->loadState(kwl, prefix); } return result; } ossim-Miami-2.9.1/src/projection/ossimIpodSensor.cpp000066400000000000000000000233311352751253100225240ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Sonoma //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimIpodSensor:debug"); RTTI_DEF1(ossimIpodSensor, "ossimIpodSensor", ossimSensorModel); ossimIpodSensor::ossimIpodSensor() { initAdjustableParameters(); theSensorID = "Ipod"; } void ossimIpodSensor::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { ossimDpt f1 (image_point - theRefImgPt); f1.x *= m_pixelSize.x; f1.y *= -m_pixelSize.y; ossimDpt film (f1 - m_principalPoint); // once we have them we can add distortion fixes // here on the film // // now orient the local film point to the ECEF axes // in a north east down lsr space. // ossimColumnVector3d rc_body(film.y, film.x, m_focalLength + computeParameterOffset(6)); ossimColumnVector3d rc_ecef = m_ecef2NedInverse*m_air2Ned*rc_body; image_ray.setOrigin(m_adjustedPlatformPosition); ossimEcefVector ecf_ray_dir (rc_ecef); image_ray.setDirection(ecf_ray_dir); } void ossimIpodSensor::lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& heightEllipsoid, ossimGpt& worldPt) const { if (!insideImage(lineSampPt)) { worldPt.makeNan(); // worldPoint = extrapolate(image_point, heightEllipsoid); } else { //*** // First establish imaging ray from image point: //*** ossimEcefRay ray; imagingRay(lineSampPt, ray); ossimEcefPoint Pecf (ray.intersectAboveEarthEllipsoid(heightEllipsoid)); worldPt = ossimGpt(Pecf); } } void ossimIpodSensor::updateModel() { m_adjustedPlatformPosition = ossimGpt(m_platformPositionEllipsoid.latd() + computeParameterOffset(1), m_platformPositionEllipsoid.lond() + computeParameterOffset(0), m_platformPositionEllipsoid.height() + computeParameterOffset(5)); double r = ossim::degreesToRadians(m_roll + computeParameterOffset(2)); double p = ossim::degreesToRadians(m_pitch + computeParameterOffset(3) ); double y = ossim::degreesToRadians(m_yaw + computeParameterOffset(4)); NEWMAT::Matrix rollM = ossimMatrix3x3::create(1, 0, 0, 0, cos(-r), sin(-r), 0, -sin(-r), cos(-r)); NEWMAT::Matrix pitchM = ossimMatrix3x3::create(cos(-p), 0, -sin(-p), 0, 1, 0, sin(-p), 0, cos(-p)); NEWMAT::Matrix yawM = ossimMatrix3x3::create(cos(-y), sin(-y), 0, -sin(-y), cos(-y), 0, 0,0,1); NEWMAT::Matrix camAM = ossimMatrix3x3::create(0,1,0,-1,0,0,0,0,1); //90 deg rotation @ 3- for camera orientation on copter NEWMAT::Matrix camM = ossimMatrix3x3::create(-1,0,0,0,-1,0,0,0,1); //180 deg rotation @ 3- for corner alignment (mirroring) m_air2Ned = camM*rollM*pitchM*yawM*camAM; double sin_lat = ossim::sind(m_adjustedPlatformPosition.latd()); double cos_lat = ossim::cosd(m_adjustedPlatformPosition.latd()); double sin_lon = ossim::sind(m_adjustedPlatformPosition.lond()); double cos_lon = ossim::cosd(m_adjustedPlatformPosition.lond()); m_ecef2Ned = (ossimMatrix3x3::create(0,0,1,0,1,0,-1,0,0)* ossimMatrix3x3::create(cos_lat, 0, sin_lat, 0,1,0, -sin_lat,0,cos_lat)* ossimMatrix3x3::create(cos_lon,sin_lon,0, -sin_lon, cos_lon, 0, 0, 0, 1)); m_ecef2NedInverse = m_ecef2Ned.t(); double adjustedFocal = m_focalLength + computeParameterOffset(6); m_fovIntrack = (atan((theImageSize.y*theRefImgPt.y)/adjustedFocal)); m_fovCrossTrack = (atan((theImageSize.x*theRefImgPt.x)/adjustedFocal)); lineSampleToWorld(theRefImgPt, theRefGndPt); theBoundGndPolygon.resize(4); ossim_float64 w = theImageClipRect.width()*2.0; ossim_float64 h = theImageClipRect.height()*2.0; ossimGpt gpt; lineSampleToWorld(theImageClipRect.ul()+ossimDpt(-w, -h), gpt); theBoundGndPolygon[0] = gpt; lineSampleToWorld(theImageClipRect.ur()+ossimDpt(w, -h), gpt); theBoundGndPolygon[1] = gpt; lineSampleToWorld(theImageClipRect.lr()+ossimDpt(w, h), gpt); theBoundGndPolygon[2] = gpt; lineSampleToWorld(theImageClipRect.ll()+ossimDpt(-w, h), gpt); theBoundGndPolygon[3] = gpt; try{ computeGsd(); } catch(...) { } } void ossimIpodSensor::initAdjustableParameters() { resizeAdjustableParameterArray(7); setAdjustableParameter(0, 0.0); setParameterDescription(0, "lon_offset"); setParameterUnit(0, "degrees"); setAdjustableParameter(1, 0.0); setParameterDescription(1, "lat_offset"); setParameterUnit(1, "degrees"); setAdjustableParameter(2, 0.0); setParameterDescription(2, "roll"); setParameterUnit(2, "degrees"); setAdjustableParameter(3, 0.0); setParameterDescription(3, "pitch"); setParameterUnit(3, "degrees"); setAdjustableParameter(4, 0.0); setParameterDescription(4, "yaw"); setParameterUnit(4, "degrees"); setAdjustableParameter(5, 0.0); setParameterDescription(5, "Altitude delta"); setParameterUnit(5, "meters"); setAdjustableParameter(6, 0.0); setParameterDescription(6, "focal length delta"); setParameterUnit(6, "meters"); setParameterSigma(0, .001); setParameterSigma(1, .001); setParameterSigma(2, 10); setParameterSigma(3, 10); setParameterSigma(4, 10); setParameterSigma(5, 100); setParameterSigma(6, .04); } bool ossimIpodSensor::loadState(const ossimKeywordlist& kwl, const char* prefix) { if(getNumberOfAdjustableParameters() < 1) { initAdjustableParameters(); } theGSD.makeNan(); theRefImgPt.makeNan(); ossimSensorModel::loadState(kwl, prefix); ossimString image_size = kwl.find(prefix, "image_size"); ossimString pixel_size = kwl.find(prefix, "pixel_size"); ossimString principal_point = kwl.find(prefix, "principal_point"); ossimString focal_length = kwl.find(prefix, "focal_length"); ossimString roll; ossimString pitch; ossimString yaw; ossimString platform_position; m_roll = 0; m_pitch = 0; m_yaw = 0; roll = kwl.find(prefix, "roll"); pitch = kwl.find(prefix, "pitch"); yaw = kwl.find(prefix, "yaw"); platform_position = kwl.find(prefix, "platform_position"); bool result = (!pixel_size.empty()&& !principal_point.empty()&& !focal_length.empty()&& !platform_position.empty()); if(!image_size.empty()) { theImageSize.toPoint(image_size); theRefImgPt = ossimDpt(theImageSize.x*.5, theImageSize.y*.5); theImageClipRect = ossimDrect(0,0,theImageSize.x-1, theImageSize.y-1); } if(theImageClipRect.hasNans()) { theImageClipRect = ossimDrect(0,0,theImageSize.x-1,theImageSize.y-1); } if(theRefImgPt.hasNans()) { theRefImgPt = theImageClipRect.midPoint(); } if(!focal_length.empty()) { m_focalLength = focal_length.toDouble(); } if(!pixel_size.empty()) { m_pixelSize.toPoint(pixel_size); } if(!roll.empty()) { m_roll = roll.toDouble(); } if(!pitch.empty()) { m_pitch = pitch.toDouble(); } if(!yaw.empty()) { m_yaw = yaw.toDouble(); } if(!principal_point.empty()) { m_principalPoint.toPoint(principal_point); } if(!platform_position.empty()) { m_platformPosition.toPoint(platform_position); m_platformPositionEllipsoid = m_platformPosition; double offset = ossimGeoidManager::instance()->offsetFromEllipsoid(m_platformPosition); if(!ossim::isnan(offset)) { m_platformPositionEllipsoid.height(m_platformPosition.height() + offset); } } updateModel(); if(theGSD.isNan()) { try { // This will set theGSD and theMeanGSD. Method throws ossimException. computeGsd(); } catch (const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimIpodSensor::loadState Caught Exception:\n" << e.what() << std::endl; } } } return result; } bool ossimIpodSensor::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimSensorModel::saveState(kwl, prefix); kwl.add(prefix, "roll", ossimString::toString(m_roll), true); kwl.add(prefix, "pitch", ossimString::toString(m_pitch), true); kwl.add(prefix, "yaw", ossimString::toString(m_yaw), true); kwl.add(prefix, "principal_point", m_principalPoint.toString(), true); kwl.add(prefix, "pixel_size", m_pixelSize.toString(), true); kwl.add(prefix, "platform_position",m_platformPosition.toString() ,true); kwl.add(prefix, "focal_length", ossimString::toString(m_focalLength) ,true); kwl.add(prefix, "image_size", theImageSize.toString() ,true); return true; } ossim-Miami-2.9.1/src/projection/ossimLambertConformalConicProjection.cpp000066400000000000000000000534731352751253100267110ustar00rootroot00000000000000//******************************************************************* // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Lamberts Conformal Conic projection code. //******************************************************************* // $Id: ossimLambertConformalConicProjection.cpp 19640 2011-05-25 15:58:00Z oscarkramer $ #include #include #include #include using namespace std; RTTI_DEF1(ossimLambertConformalConicProjection, "ossimLambertConformalConicProjection", ossimMapProjection) /***************************************************************************/ /* DEFINES * */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define MAX_LAT (( M_PI * 89.99972222222222) / 180.0) /* 89 59 59.0 degrees in radians */ #define LAMBERT_m(clat,essin) (clat / sqrt(1.0 - essin * essin)) #define LAMBERT_t(lat,essin) tan(PI_OVER_4 - lat / 2) / \ pow((1.0 - essin) / (1.0 + essin), es_OVER_2) #define ES_SIN(sinlat) (es * sinlat) /**************************************************************************/ /* GLOBAL DECLARATIONS * */ const double PI_OVER_4 = (M_PI / 4.0); #define LAMBERT_NO_ERROR 0x0000 #define LAMBERT_LAT_ERROR 0x0001 #define LAMBERT_LON_ERROR 0x0002 #define LAMBERT_EASTING_ERROR 0x0004 #define LAMBERT_NORTHING_ERROR 0x0008 #define LAMBERT_FIRST_STDP_ERROR 0x0010 #define LAMBERT_SECOND_STDP_ERROR 0x0020 #define LAMBERT_ORIGIN_LAT_ERROR 0x0040 #define LAMBERT_CENT_MER_ERROR 0x0080 #define LAMBERT_A_ERROR 0x0100 #define LAMBERT_B_ERROR 0x0200 #define LAMBERT_A_LESS_B_ERROR 0x0400 #define LAMBERT_HEMISPHERE_ERROR 0x0800 #define LAMBERT_FIRST_SECOND_ERROR 0x1000 ossimLambertConformalConicProjection::ossimLambertConformalConicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimLambertConformalConicProjection::ossimLambertConformalConicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double stdParallel1, double stdParallel2, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Lambert_Std_Parallel_1 = stdParallel1*RAD_PER_DEG; Lambert_Std_Parallel_2 = stdParallel2*RAD_PER_DEG; Lambert_False_Easting = falseEasting; Lambert_False_Northing = falseNorthing; update(); } ossimLambertConformalConicProjection::~ossimLambertConformalConicProjection() { } ossimObject* ossimLambertConformalConicProjection::dup()const { return new ossimLambertConformalConicProjection(*this); } void ossimLambertConformalConicProjection::update() { Set_Lambert_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Lambert_Std_Parallel_1, Lambert_Std_Parallel_2, Lambert_False_Easting, Lambert_False_Northing); theFalseEastingNorthing.x = Lambert_False_Easting; theFalseEastingNorthing.y = Lambert_False_Northing; ossimMapProjection::update(); } void ossimLambertConformalConicProjection::setStandardParallel1(double degree) { Lambert_Std_Parallel_1 = degree*RAD_PER_DEG; update(); } void ossimLambertConformalConicProjection::setStandardParallel2(double degree) { Lambert_Std_Parallel_2 = degree*RAD_PER_DEG; update(); } void ossimLambertConformalConicProjection::setStandardParallels(double parallel1Degree, double parallel2Degree) { Lambert_Std_Parallel_1 = parallel1Degree*RAD_PER_DEG; Lambert_Std_Parallel_2 = parallel2Degree*RAD_PER_DEG; update(); } void ossimLambertConformalConicProjection::setFalseEasting(double falseEasting) { Lambert_False_Easting = falseEasting; update(); } void ossimLambertConformalConicProjection::setFalseNorthing(double falseNorthing) { Lambert_False_Northing = falseNorthing; update(); } void ossimLambertConformalConicProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Lambert_False_Easting = falseEasting; Lambert_False_Northing = falseNorthing; update(); } void ossimLambertConformalConicProjection::setParameters(double parallel1, double parallel2, double falseEasting, double falseNorthing) { Lambert_False_Easting = falseEasting; Lambert_False_Northing = falseNorthing; Lambert_Std_Parallel_1 = parallel1*RAD_PER_DEG; Lambert_Std_Parallel_2 = parallel2*RAD_PER_DEG; update(); } void ossimLambertConformalConicProjection::setDefaults() { Lambert_Std_Parallel_1 = 40*RAD_PER_DEG; Lambert_Std_Parallel_2 = 50*RAD_PER_DEG; Lambert_False_Northing = 0.0; Lambert_False_Easting = 0.0; } ossimGpt ossimLambertConformalConicProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Lambert_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimLambertConformalConicProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Lambert(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimLambertConformalConicProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, ossimKeywordNames::STD_PARALLEL_1_KW, Lambert_Std_Parallel_1*DEG_PER_RAD, true); kwl.add(prefix, ossimKeywordNames::STD_PARALLEL_2_KW, Lambert_Std_Parallel_2*DEG_PER_RAD, true); return ossimMapProjection::saveState(kwl, prefix); } bool ossimLambertConformalConicProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); const char* stdParallel1 = kwl.find(prefix, ossimKeywordNames::STD_PARALLEL_1_KW); const char* stdParallel2 = kwl.find(prefix, ossimKeywordNames::STD_PARALLEL_2_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimLambertConformalConicProjection)) { Lambert_False_Easting = theFalseEastingNorthing.x; Lambert_False_Northing = theFalseEastingNorthing.y; if(stdParallel1) { Lambert_Std_Parallel_1 = ossimString(stdParallel1).toDouble()*RAD_PER_DEG; } if(stdParallel2) { Lambert_Std_Parallel_2 = ossimString(stdParallel2).toDouble()*RAD_PER_DEG; } } update(); return flag; } std::ostream& ossimLambertConformalConicProjection::print( std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << setiosflags(ios::fixed) << setprecision(15); out << "// ossimLambertConformalConicProjection::print\n" << ossimKeywordNames::STD_PARALLEL_1_KW << ": " << Lambert_Std_Parallel_1*DEG_PER_RAD << "\n" << ossimKeywordNames::STD_PARALLEL_2_KW << ": " << Lambert_Std_Parallel_2*DEG_PER_RAD << std::endl; // Reset flags. out.setf(f); return ossimMapProjection::print(out); } /************************************************************************/ /* FUNCTIONS * */ long ossimLambertConformalConicProjection::Set_Lambert_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double Std_Parallel_1, double Std_Parallel_2, double False_Easting, double False_Northing) { /* BEGIN Set_Lambert_Parameters */ /* * The function Set_Lambert_Parameters receives the ellipsoid parameters and * Lambert Conformal Conic projection parameters as inputs, and sets the * corresponding state variables. If any errors occur, the error code(s) * are returned by the function, otherwise LAMBERT_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude of origin, in radians (input) * Central_Meridian : Longitude of origin, in radians (input) * Std_Parallel_1 : First standard parallel, in radians (input) * Std_Parallel_2 : Second standard parallel, in radians (input) * False_Easting : False easting, in meters (input) * False_Northing : False northing, in meters (input) */ double slat, slat1, clat; double es_sin; double t0, t1, t2; double m1, m2; // double inv_f = 1 / f; long Error_Code = LAMBERT_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= LAMBERT_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= LAMBERT_INV_F_ERROR; // } // if ((Origin_Latitude < -MAX_LAT) || (Origin_Latitude > MAX_LAT)) // { /* Origin Latitude out of range */ // Error_Code |= LAMBERT_ORIGIN_LAT_ERROR; // } // if ((Std_Parallel_1 < -MAX_LAT) || (Std_Parallel_1 > MAX_LAT)) // { /* First Standard Parallel out of range */ // Error_Code |= LAMBERT_FIRST_STDP_ERROR; // } // if ((Std_Parallel_2 < -MAX_LAT) || (Std_Parallel_2 > MAX_LAT)) // { /* Second Standard Parallel out of range */ // Error_Code |= LAMBERT_SECOND_STDP_ERROR; // } // if ((Std_Parallel_1 == 0) && (Std_Parallel_2 == 0)) // { /* First & Second Standard Parallels are both 0 */ // Error_Code |= LAMBERT_FIRST_SECOND_ERROR; // } // if (Std_Parallel_1 == -Std_Parallel_2) // { /* Parallels are the negation of each other */ // Error_Code |= LAMBERT_HEMISPHERE_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* Origin Longitude out of range */ // Error_Code |= LAMBERT_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Lambert_a = a; Lambert_f = f; Lambert_Origin_Lat = Origin_Latitude; Lambert_Std_Parallel_1 = Std_Parallel_1; Lambert_Std_Parallel_2 = Std_Parallel_2; // if (Central_Meridian > PI) // Central_Meridian -= TWO_PI; Lambert_Origin_Long = Central_Meridian; Lambert_False_Easting = False_Easting; Lambert_False_Northing = False_Northing; es2 = 2 * Lambert_f - Lambert_f * Lambert_f; es = sqrt(es2); es_OVER_2 = es / 2.0; slat = sin(Lambert_Origin_Lat); es_sin = ES_SIN(slat); t0 = LAMBERT_t(Lambert_Origin_Lat, es_sin); slat1 = sin(Lambert_Std_Parallel_1); clat = cos(Lambert_Std_Parallel_1); es_sin = ES_SIN(slat1); m1 = LAMBERT_m(clat, es_sin); t1 = LAMBERT_t(Lambert_Std_Parallel_1, es_sin); if (fabs(Lambert_Std_Parallel_1 - Lambert_Std_Parallel_2) > 1.0e-10) { slat = sin(Lambert_Std_Parallel_2); clat = cos(Lambert_Std_Parallel_2); es_sin = ES_SIN(slat); m2 = LAMBERT_m(clat, es_sin); t2 = LAMBERT_t(Lambert_Std_Parallel_2, es_sin); n = log(m1 / m2) / log(t1 / t2); } else n = slat1; F = m1 / (n * pow(t1, n)); Lambert_aF = Lambert_a * F; if ((t0 == 0) && (n < 0)) rho0 = 0.0; else rho0 = Lambert_aF * pow(t0, n); } return (Error_Code); } /* END OF Set_Lambert_Parameters */ void ossimLambertConformalConicProjection::Get_Lambert_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *Std_Parallel_1, double *Std_Parallel_2, double *False_Easting, double *False_Northing)const { /* BEGIN Get_Lambert_Parameters */ /* * The function Get_Lambert_Parameters returns the current ellipsoid * parameters and Lambert Conformal Conic projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude of origin, in radians (output) * Central_Meridian : Longitude of origin, in radians (output) * Std_Parallel_1 : First standard parallel, in radians (output) * Std_Parallel_2 : Second standard parallel, in radians (output) * False_Easting : False easting, in meters (output) * False_Northing : False northing, in meters (output) */ *a = Lambert_a; *f = Lambert_f; *Std_Parallel_1 = Lambert_Std_Parallel_1; *Std_Parallel_2 = Lambert_Std_Parallel_2; *Origin_Latitude = Lambert_Origin_Lat; *Central_Meridian = Lambert_Origin_Long; *False_Easting = Lambert_False_Easting; *False_Northing = Lambert_False_Northing; return; } /* END OF Get_Lambert_Parameters */ long ossimLambertConformalConicProjection::Convert_Geodetic_To_Lambert (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Lambert */ /* * The function Convert_Geodetic_To_Lambert converts Geodetic (latitude and * longitude) coordinates to Lambert Conformal Conic projection (easting * and northing) coordinates, according to the current ellipsoid and * Lambert Conformal Conic projection parameters. If any errors occur, the * error code(s) are returned by the function, otherwise LAMBERT_NO_ERROR is * returned. * * Latitude : Latitude, in radians (input) * Longitude : Longitude, in radians (input) * Easting : Easting (X), in meters (output) * Northing : Northing (Y), in meters (output) */ double slat; double es_sin; double t; double rho; double dlam; double theta; long Error_Code = LAMBERT_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code|= LAMBERT_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code|= LAMBERT_LON_ERROR; // } if (!Error_Code) { /* no errors */ if (fabs(fabs(Latitude) - PI_OVER_2) > 1.0e-10) { slat = sin(Latitude); es_sin = ES_SIN(slat); t = LAMBERT_t(Latitude, es_sin); rho = Lambert_aF * pow(t, n); } else { if ((Latitude * n) <= 0) { /* Point can not be projected */ Error_Code |= LAMBERT_LAT_ERROR; return (Error_Code); } rho = 0.0; } dlam = Longitude - Lambert_Origin_Long; // if (dlam > PI) // { // dlam -= TWO_PI; // } // if (dlam < -PI) // { // dlam += TWO_PI; // } theta = n * dlam; *Easting = rho * sin(theta) + Lambert_False_Easting; *Northing = rho0 - rho * cos(theta) + Lambert_False_Northing; } return (Error_Code); } /* END OF Convert_Geodetic_To_Lambert */ long ossimLambertConformalConicProjection::Convert_Lambert_To_Geodetic (double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Lambert_To_Geodetic */ /* * The function Convert_Lambert_To_Geodetic converts Lambert Conformal * Conic projection (easting and northing) coordinates to Geodetic * (latitude and longitude) coordinates, according to the current ellipsoid * and Lambert Conformal Conic projection parameters. If any errors occur, * the error code(s) are returned by the function, otherwise LAMBERT_NO_ERROR * is returned. * * Easting : Easting (X), in meters (input) * Northing : Northing (Y), in meters (input) * Latitude : Latitude, in radians (output) * Longitude : Longitude, in radians (output) */ double dy, dx; double rho, rho0_MINUS_dy; double t; double PHI; double tempPHI = 0.0; double sin_PHI; double es_sin; double theta = 0.0; double tolerance = 4.85e-10; long Error_Code = LAMBERT_NO_ERROR; // if ((Easting < (Lambert_False_Easting - Lambert_Delta_Easting)) // ||(Easting > (Lambert_False_Easting + Lambert_Delta_Easting))) // { /* Easting out of range */ // Error_Code |= LAMBERT_EASTING_ERROR; // } // if ((Northing < (Lambert_False_Northing - Lambert_Delta_Northing)) // || (Northing > (Lambert_False_Northing + Lambert_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= LAMBERT_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ dy = Northing - Lambert_False_Northing; dx = Easting - Lambert_False_Easting; rho0_MINUS_dy = rho0 - dy; rho = sqrt(dx * dx + (rho0_MINUS_dy) * (rho0_MINUS_dy)); if (n < 0.0) { rho *= -1.0; dy *= -1.0; dx *= -1.0; rho0_MINUS_dy *= -1.0; } if (rho != 0.0) { theta = atan2(dx, rho0_MINUS_dy); t = pow(rho / (Lambert_aF) , 1.0 / n); PHI = PI_OVER_2 - 2.0 * atan(t); while (fabs(PHI - tempPHI) > tolerance) { tempPHI = PHI; sin_PHI = sin(PHI); es_sin = ES_SIN(sin_PHI); PHI = PI_OVER_2 - 2.0 * atan(t * pow((1.0 - es_sin) / (1.0 + es_sin), es_OVER_2)); } *Latitude = PHI; *Longitude = theta / n + Lambert_Origin_Long; if (fabs(*Latitude) < 2.0e-7) /* force lat to 0 to avoid -0 degrees */ *Latitude = 0.0; if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ *Latitude = PI_OVER_2; else if (*Latitude < -PI_OVER_2) *Latitude = -PI_OVER_2; if (*Longitude > M_PI) { if (*Longitude - M_PI < 3.5e-6) *Longitude = M_PI; // else // *Longitude -= TWO_PI; } if (*Longitude < -M_PI) { if (fabs(*Longitude + M_PI) < 3.5e-6) *Longitude = -M_PI; // else // *Longitude += TWO_PI; } if (fabs(*Longitude) < 2.0e-7) /* force lon to 0 to avoid -0 degrees */ *Longitude = 0.0; if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ *Longitude = M_PI; else if (*Longitude < -M_PI) *Longitude = -M_PI; } else { if (n > 0.0) *Latitude = PI_OVER_2; else *Latitude = -PI_OVER_2; *Longitude = Lambert_Origin_Long; } } return (Error_Code); } /* END OF Convert_Lambert_To_Geodetic */ double ossimLambertConformalConicProjection::getStandardParallel1()const { return Lambert_Std_Parallel_1/RAD_PER_DEG; } double ossimLambertConformalConicProjection::getStandardParallel2()const { return Lambert_Std_Parallel_2/RAD_PER_DEG; } //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimLambertConformalConicProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimLambertConformalConicProjection* p = dynamic_cast(&proj); if (!p) return false; if (!ossim::almostEqual(Lambert_Std_Parallel_1,p->Lambert_Std_Parallel_1)) return false; if (!ossim::almostEqual(Lambert_Std_Parallel_2,p->Lambert_Std_Parallel_2)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimLandSatModel.cpp000066400000000000000000001227121352751253100227510ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer (okramer@imagelinks.com) // // DESCRIPTION: // // SOFTWARE HISTORY: // 01AUG2002 O. Kramer, ImageLinks // Initial coding. // 21NOV2002 O. Kramer, ImageLinks // Fixed use of map projection to use forward/inverse instead of // worldTLinesample/lineSampleToWorld methods. // //***************************************************************************** #include #include RTTI_DEF1(ossimLandSatModel, "ossimLandSatModel", ossimSensorModel); #include #include #include #include #include #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include using namespace std; static ossimTrace traceExec ("ossimLandSatModel:exec"); static ossimTrace traceDebug ("ossimLandSatModel:debug"); static const char* PROJECTION_TYPE_KW = "theProjectionType"; static const char* MAP_ZONE_KW = "theMapZone"; static const char* MAP_OFFSET_X_KW = "theMapOffset.x"; static const char* MAP_OFFSET_Y_KW = "theMapOffset.y"; static const char* WRS_PATH_NUMBER_KW = "theWrsPathNumber"; static const char* ROW_NUMBER_KW = "theWrsRowNumber"; static const char* ILLUM_AZIMUTH_KW = "theIllumAzimuth"; static const char* ILLUM_ELEVATION_KW = "theIllumElevation"; static const char* MERIDIANAL_ANGLE_KW = "theMeridianalAngle"; static const char* ORBIT_ALTITUDE_KW = "theOrbitAltitude"; static const char* ORBIT_INCLINATION_KW = "theOrbitInclination"; static const char* MAP_AZIM_ANGLE_KW = "theMapAzimAngle"; static const char* MAP_2Ic_ROT_ANGLE_KW = "theMap2IcRotAngle"; static const char* INTRACK_OFFSET_KW = "theIntrackOffset"; static const char* CRTRACK_OFFSET_KW = "theCrtrackOffset"; static const char* LINE_GSD_CORR_KW = "theLineGsdCorr"; static const char* SAMP_GSD_CORR_KW = "theSampGsdCorr"; static const char* ROLL_OFFSET_KW = "theRollOffset"; static const char* YAW_OFFSET_KW = "theYawOffset"; static const char* YAW_RATE_KW = "theYawRate"; static const char* MAP_ROTATION_KW = "theMapRotation"; static const double GEODETIC_2_GEOCENTRIC_FACTOR = 1.00674; static const double L7_ORBIT_ALTITUDE = 705300.0; static const double L7_ORBIT_INCLINATION = 98.22; static const double L7_NOMINAL_POS_ERROR = 200.0; static const double L5_ORBIT_ALTITUDE = 705300.0; static const double L5_ORBIT_INCLINATION = 98.22; static const double L5_NOMINAL_POS_ERROR = 12000.0; //arbitrary : to be fixed static const char* PARAM_NAMES[] ={"intrack_offset", "crtrack_offset", "line_gsd_corr", "samp_gsd_corr", "roll_offset", "yaw_offset", "yaw_rate", "map_rotation"}; static const char* PARAM_UNITS[] ={"meters", "meters", "meters", "meters", "degrees", "degrees", "seconds", "degrees"}; static const char* PROJ_TYPE[] = { "UNKNOWN_PROJECTION", "UTM_MAP", "UTM_ORBIT", "SOM_MAP", "SOM_ORBIT" }; //***************************************************************************** // DEFAULT CONSTRUCTOR: ossimLandSatModel() // //***************************************************************************** ossimLandSatModel::ossimLandSatModel() : ossimSensorModel(), theIntrackOffset (0.0), theCrtrackOffset (0.0), theLineGsdCorr (0.0), theSampGsdCorr (0.0), theRollOffset (0.0), theYawOffset (0.0), theYawRate (0.0), theMapRotation (0.0) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel: entering..." << std::endl; initAdjustableParameters(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel: returning..." << std::endl; } //***************************************************************************** // COPY CONSTRUCTOR: ossimLandSatModel(ossimLandSatModel) // //***************************************************************************** ossimLandSatModel::ossimLandSatModel(const ossimFfL7& head) : ossimSensorModel(), theIntrackOffset (0.0), theCrtrackOffset (0.0), theLineGsdCorr (0.0), theSampGsdCorr (0.0), theRollOffset (0.0), theYawOffset (0.0), theYawRate (0.0), theMapRotation (0.0) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel(head): entering..." << std::endl; initFromHeader(head); if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel(head): Exited..." << std::endl; } //***************************************************************************** // CONSTRUCTOR: ossimLandSatModel(filename) // // Constructs model from a filename. The file can be either a FF header file // or a KWL file. // //***************************************************************************** ossimLandSatModel::ossimLandSatModel(const ossimFilename& init_file) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel(init_file): entering..." << std::endl; setupOptimizer(init_file); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel(init_file): Exited..." << std::endl; } //***************************************************************************** // CONSTRUCTOR: ossimLandSatModel(kwl) // // Constructs model from keywordlist geometry file // //***************************************************************************** ossimLandSatModel::ossimLandSatModel(const ossimKeywordlist& geom_kwl) : ossimSensorModel(), theIntrackOffset (0.0), theCrtrackOffset (0.0), theLineGsdCorr (0.0), theSampGsdCorr (0.0), theRollOffset (0.0), theYawOffset (0.0), theYawRate (0.0), theMapRotation (0.0) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel(geom_kwl): entering..." << std::endl; initAdjustableParameters(); //*** // Parse keywordlist for geometry: //*** loadState(geom_kwl); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel(geom_kwl): Exited..." << std::endl; } //***************************************************************************** // COPY CONSTRUCTOR: //***************************************************************************** ossimLandSatModel::ossimLandSatModel(const ossimLandSatModel& rhs) : ossimSensorModel (rhs), theIllumAzimuth (rhs.theIllumAzimuth), theIllumElevation (rhs.theIllumElevation), theOrbitAltitude (rhs.theOrbitAltitude), theOrbitInclination(rhs.theOrbitInclination), theMapZone (rhs.theMapZone), theMapOffset (rhs.theMapOffset), theWrsPathNumber (rhs.theWrsPathNumber), theWrsRowNumber (rhs.theWrsRowNumber), theMeridianalAngle (rhs.theMeridianalAngle), thePositionError (rhs.thePositionError), theProjectionType (rhs.theProjectionType), theMapProjection (rhs.theMapProjection.valid()? (ossimMapProjection*)rhs.theMapProjection->dup(): (ossimMapProjection*)0), theMapAzimAngle (rhs.theMapAzimAngle), theMapAzimCos (rhs.theMapAzimCos), theMapAzimSin (rhs.theMapAzimSin), theMap2IcRotAngle (rhs.theMap2IcRotAngle), theMap2IcRotCos (rhs.theMap2IcRotCos), theMap2IcRotSin (rhs.theMap2IcRotSin), theIntrackOffset (rhs.theIntrackOffset), theCrtrackOffset (rhs.theCrtrackOffset), theLineGsdCorr (rhs.theLineGsdCorr), theSampGsdCorr (rhs.theSampGsdCorr), theRollOffset (rhs.theRollOffset), theYawOffset (rhs.theYawOffset), theYawRate (rhs.theYawRate), theMapRotation (rhs.theMapRotation), theRollRotMat (rhs.theRollRotMat) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel(rhs): entering..." << std::endl; initAdjustableParameters(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::ossimLandSatModel(rhs): returning..." << std::endl; } ossimObject* ossimLandSatModel::dup()const { return new ossimLandSatModel(*this); } //***************************************************************************** // DESTRUCTOR: ~ossimLandSatModel() // //***************************************************************************** ossimLandSatModel::~ossimLandSatModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::~ossimLandSatModel: entering..." << std::endl; theMapProjection = 0; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::~ossimLandSatModel: returning..." << std::endl; } //***************************************************************************** // METHOD: ossimLandSatModel::initFromHeader() // //***************************************************************************** void ossimLandSatModel::initFromHeader(const ossimFfL7& head) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::initFromHeader: entering..." << std::endl; //*** // Initialize base-class data members: //*** theRefGndPt = head.theCenterGP; theRefImgPt = head.theCenterImagePoint; theImageSize.x = head.thePixelsPerLine; theImageSize.y = head.theLinesPerBand; theImageID = head.theRequestNumber; theImageClipRect = ossimDrect(0, 0, theImageSize.x-1, theImageSize.y-1); theGSD.samp = head.theGsd; theGSD.line = head.theGsd; theIllumAzimuth = head.theSunAzimuth; theIllumElevation = head.theSunElevation; theMapZone = head.theUsgsMapZone; theWrsPathNumber = head.thePathNumber; theWrsRowNumber = head.theRowNumber; theRollOffset = head.theOffNadirAngle; theMeanGSD = head.theGsd; //satellite orbit and accuracy ossimString satname(head.theSatName); if (satname.contains("7")) { theOrbitAltitude = L7_ORBIT_ALTITUDE; theOrbitInclination = L7_ORBIT_INCLINATION; theNominalPosError = L7_NOMINAL_POS_ERROR; } else if (satname.contains("5")) { theOrbitAltitude = L5_ORBIT_ALTITUDE; theOrbitInclination = L5_ORBIT_INCLINATION; theNominalPosError = L5_NOMINAL_POS_ERROR; } else { theErrorStatus = 1; //MODEL_ERROR if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimLandSatModel::initFromHeader: " << "Unknown satellite name : " << satname << std::endl; } } //*** // Assign the meridianal angle. The Meridianal angle is // the angle between true north and the vehicles ground track. The // orientation angle is the rotation of the raster image from north (this // will be 0 for map-oriented imagery). // // Compute meridianal angle between the along-track direction // and the meridian going through the scene center excluding earth rotation // effects. The spherical triangle equation is Napier's rule for right-angle // spherical triangles. This angle is a negative number from -8.2 to -90 // depending on scene latitude: //*** double phi_c = ossim::atand(ossim::tand(theRefGndPt.lat)/ GEODETIC_2_GEOCENTRIC_FACTOR); double cos_phi_c = ossim::cosd(phi_c); theMeridianalAngle = -ossim::asind(ossim::cosd(theOrbitInclination) / cos_phi_c); theMapAzimAngle = head.theOrientationAngle; //*** // Fetch the corner points from the header: //*** ossimDpt v[4]; // temporarily holds vertices for ground polygon v[0] = head.theUL_Corner; v[1] = head.theUR_Corner; v[2] = head.theLR_Corner; v[3] = head.theLL_Corner; theBoundGndPolygon = ossimPolygon(4, v); //*** // Initialize map projection parameters: // Determine the projection/orientation type: //*** ossimString orient_type = head.theProductType; ossimString proj_type = head.theMapProjectionName; if (proj_type.contains("SOM")) { //*** // Inverse the line direction GSD for SOM, since projection "intrack" // axis (x) is descending: //*** if (orient_type.contains("ORBIT")) theProjectionType = SOM_ORBIT; else theProjectionType = SOM_MAP; // this is a hack. After testing two it is consistently off // by 90 degrees. // theMapAzimAngle -= 90.0; } else if (proj_type.contains("UTM")) { if (orient_type.contains("ORBIT")) theProjectionType = UTM_ORBIT; else theProjectionType = UTM_MAP; } else { theErrorStatus = 1; //MODEL_ERROR if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimLandSatModel::initFromHeader: " << "Unknown projection/orientation type." << std::endl; } return; } //*** // Establish the map projection: //*** initMapProjection(); theMapOffset = theMapProjection->forward(head.theUL_Corner); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::initFromHeader:" << "\ntheMapProjection:\n"; theMapProjection->print(ossimNotify(ossimNotifyLevel_DEBUG)); ossimNotify(ossimNotifyLevel_DEBUG) << "\nHeader upper left ground point: " << head.theUL_Corner << std::endl; } //*** // initialize remaining data members: //*** initAdjustableParameters(); updateModel(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::initFromHeader: returning..." << std::endl; } //***************************************************************************** // METHOD: ossimLandSatModel::lineSampleHeightToWorld() // // Performs the line/sample to groundpoint projection given an elevation. // // 5. Intersect imaging ray with elevation surface. // //***************************************************************************** void ossimLandSatModel::lineSampleHeightToWorld(const ossimDpt& image_point, const double& height, ossimGpt& gpt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::lineSampleHeightToWorld: entering..." << std::endl; #if 0 //*** // Extrapolate if point is outside image: //*** if (!insideImage(image_point)) { gpt = extrapolate(image_point, height); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::lineSampleHeightToWorld: returning..." << std::endl; return; } #endif //*** // First establish imaging ray from image point: //*** ossimEcefRay imaging_ray; imagingRay(image_point, imaging_ray); ossimEcefPoint Pecf (imaging_ray.intersectAboveEarthEllipsoid(height)); gpt = ossimGpt(Pecf); } //***************************************************************************** // METHOD: ossimLandSatModel::imagingRay() // // This model implements an affine transform with scaling to arrive at an // ECF ray given an image point. This ray is intersected with a constant // elevation surface to arrive at a ground point. The transform to arrive at a // point on the ground [p,l,0] is implemented briefly as follows: // // 0. Establish the lat/lon map point given input point. // // 1. Determine intrack/crosstrack coordinates of image map point by rotating // the input coordinates by meridianal angle. // // 2. Given intrack line number, compute vehicle position at time of imaging. // // 3. Establish imaging ray given input point ground coordinates and vehicle // position. // // 4. Perturb imaging ray by adjustable parameters for platform attitude and // position error. // //***************************************************************************** void ossimLandSatModel::imagingRay(const ossimDpt& inImgPt, ossimEcefRay& image_ray) const { #if 0 if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "ossimLandSatModel::imagingRay: entering..." << std::endl; bool debug_flag = false; // setable by interactive debugger if (traceDebug() || debug_flag) { ossimNotify(ossimNotifyLevel_DEBUG) << "inImgPt = " << inImgPt << std::endl; } #endif //*** // Get ground point for given map image point: //*** ossimDpt rot_img_pt(-inImgPt.line*theMapAzimSin+inImgPt.samp*theMapAzimCos, inImgPt.line*theMapAzimCos+inImgPt.samp*theMapAzimSin); ossimDpt map_point (theMapOffset.x + rot_img_pt.samp*(theGSD.samp+theSampGsdCorr), theMapOffset.y - rot_img_pt.line*(theGSD.line+theLineGsdCorr)); ossimGpt inGndPt (theMapProjection->inverse(map_point)); #if 0 if (traceDebug() || debug_flag) { ossimNotify(ossimNotifyLevel_DEBUG) << "\t theMapOffset="<\n" << MAP_ZONE_KW << ": \n" << MAP_OFFSET_X_KW << ": \n" << MAP_OFFSET_Y_KW << ": \n" << WRS_PATH_NUMBER_KW << ": \n" << ROW_NUMBER_KW << ": \n" << ILLUM_AZIMUTH_KW << ": \n" << ILLUM_ELEVATION_KW << ": \n" << MERIDIANAL_ANGLE_KW << ": \n" << ORBIT_ALTITUDE_KW << ": \n" << ORBIT_INCLINATION_KW << ": \n" << MAP_AZIM_ANGLE_KW << ": \n" << MAP_2Ic_ROT_ANGLE_KW << ": \n" << INTRACK_OFFSET_KW << ": [optional]\n" << CRTRACK_OFFSET_KW << ": [optional]\n" << LINE_GSD_CORR_KW << ": [optional]\n" << SAMP_GSD_CORR_KW << ": [optional]\n" << ROLL_OFFSET_KW << ": [optional]\n" << YAW_OFFSET_KW << ": [optional]\n" << YAW_RATE_KW << ": [optional]\n" << MAP_ROTATION_KW << ": [optional]\n" << endl; os << "\n" <setHemisphere('S'); } else { utm->setHemisphere('N'); } } //*** // Initialize angle sines/cosines used in phiLambda projection: //*** theMap2IcRotAngle = theMeridianalAngle + theMapAzimAngle; theMap2IcRotCos = ossim::cosd(theMap2IcRotAngle); theMap2IcRotSin = ossim::sind(theMap2IcRotAngle); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::writeGeomTemplate: returning... " << std::endl; return; } //***************************************************************************** // PROTECTED METHOD: //***************************************************************************** void ossimLandSatModel::updateModel() { //*** // Update the geometry... // Adjusted = Initial + adj_parm[i]*adj_sigma[i] // Some parameters have a zero initial value and that term is not included. //*** theIntrackOffset = computeParameterOffset(INTRACK_OFFSET); theCrtrackOffset = computeParameterOffset(CRTRACK_OFFSET); theLineGsdCorr = computeParameterOffset(LINE_GSD_CORR); theSampGsdCorr = computeParameterOffset(SAMP_GSD_CORR); theRollOffset = computeParameterOffset(ROLL_OFFSET); theYawOffset = computeParameterOffset(YAW_OFFSET); theYawRate = computeParameterOffset(YAW_RATE); theMapRotation = computeParameterOffset(MAP_ROTATION); // int numParams = getNumberOfAdjustableParameters(); //*** // Now the initial values have been updated, zero out the adjustment: //*** // for (int i=0; i ff_headerp; if (ossimString::downcase(init_file).contains("header.dat")) { ossimRefPtr h = new ossimFfL5(init_file); ff_headerp = h.get(); if (!ff_headerp->getErrorStatus()) { double d = fabs(h->revb()->theUlEasting - h->revb()->theCenterEasting)/h->theGsd; h->theCenterImagePoint.x = static_cast(d); // d + 0.5 ??? d = fabs(h->revb()->theUlNorthing - h->revb()->theCenterNorthing)/h->theGsd; h->theCenterImagePoint.y = static_cast(d); // d + 0.5 ??? initFromHeader(*ff_headerp); theMapOffset.x = h->revb()->theUlEasting; theMapOffset.y = h->revb()->theUlNorthing; } else { ff_headerp = 0; } } else { ff_headerp=new ossimFfL7(init_file); if (!ff_headerp->getErrorStatus()) { initFromHeader(*ff_headerp); } else { ff_headerp = 0; } } if(!ff_headerp.valid()) { // // If not header, then check for possible KWL file. The loadState sets the // error status: // ossimFilename init_filename(init_file); ossimKeywordlist kwl(init_filename); loadState(kwl); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimLandSatModel::setupOptimizer(init_file): Exited..." << std::endl; return true; } ossim-Miami-2.9.1/src/projection/ossimLensDistortion.cpp000066400000000000000000000065321352751253100234230ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2005 Garrett Potts // // LGPL // // Author: Garrett Potts // // Description: // // ossimLensDistortion //******************************************************************* // $Id: ossimLensDistortion.cpp 15929 2009-11-16 18:20:46Z gpotts $ #include #include #include #include RTTI_DEF1(ossimLensDistortion, "ossimLensDistortion", ossim2dTo2dTransform); bool ossimLensDistortion::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossim2dTo2dTransform::saveState(kwl, prefix); kwl.add(prefix, "center", ossimString::toString(theCenter.x) + " " + ossimString::toString(theCenter.y), true); return true; } bool ossimLensDistortion::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* center = kwl.find(prefix, "center"); theCenter.x = 0.0; theCenter.y = 0.0; if(center) { std::vector splitString; ossimString tempString(center); tempString = tempString.trim(); tempString.split(splitString, " "); if(splitString.size() == 2) { theCenter.x = splitString[0].toDouble(); theCenter.y = splitString[1].toDouble(); } } return ossim2dTo2dTransform::loadState(kwl, prefix); } void ossimLensDistortion::distort(const ossimDpt& input, ossimDpt& output)const { int iters = 0; //*** // Begin with guess. Forward transform is defined as trasforming left to // right. We are therefore solving for left: //*** ossimDpt left (input); ossimDpt left_dx; ossimDpt left_dy; ossimDpt right; ossimDpt right_dx; ossimDpt right_dy; ossimDpt dr_dx; ossimDpt dr_dy; ossimDpt r_diff; ossimDpt l_diff; double inverse_norm; //*** // Begin iterations: //*** do { //*** // establish perturbed image points about the guessed point: //*** left_dx.x = left.x + 1.0; left_dx.y = left.y; left_dy.x = left.x; left_dy.y = left.y + 1.0; //*** // Compute numerical partials at current guessed point: //*** undistort(left, right); undistort(left_dx, right_dx); undistort(left_dy, right_dy); dr_dx.x = (right_dx.x - right.x); //e dr_dx.y = (right_dx.y - right.y); //g dr_dy.x = (right_dy.x - right.x); //f dr_dy.y = (right_dy.y - right.y); //h //*** // Test for convergence: //*** r_diff = input - right; //*** // Compute linearized estimate of image point given gp delta: //*** inverse_norm = dr_dy.u*dr_dx.v - dr_dx.u*dr_dy.v; // fg-eh if (std::fabs(inverse_norm) > DBL_EPSILON) { l_diff.u = (-dr_dy.v*r_diff.u + dr_dy.u*r_diff.v)/inverse_norm; l_diff.v = ( dr_dx.v*r_diff.u - dr_dx.u*r_diff.v)/inverse_norm; left += l_diff; } else { l_diff.u = 0; l_diff.v = 0; } iters++; } while (((fabs(l_diff.u) > theConvergenceThreshold) || (fabs(l_diff.v) > theConvergenceThreshold)) && (iters < theMaxIterations)); output = left; } ossim-Miami-2.9.1/src/projection/ossimLlxyProjection.cpp000066400000000000000000000226301352751253100234250ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Contains class definition for ossimLlxy. This is a simple "latitude / // longitude to x / y" projection. // //******************************************************************* // $Id: ossimLlxyProjection.cpp 20060 2011-09-07 12:33:46Z gpotts $ #include #include #include #include #include using namespace std; // RTTI information for the ossimMapProjection RTTI_DEF1(ossimLlxyProjection, "ossimLlxyProjection" , ossimMapProjection); // About 1 meter. static const ossim_float64 DEFAULT_DEGREES_PER_PIXEL = 8.9831528412e-006; ossimLlxyProjection::ossimLlxyProjection() { theProjectionUnits = OSSIM_DEGREES; // set to about 1 meter per pixel theDegreesPerPixel.y = DEFAULT_DEGREES_PER_PIXEL; theDegreesPerPixel.x = DEFAULT_DEGREES_PER_PIXEL; theUlEastingNorthing.y = ossim::nan(); theUlEastingNorthing.x = ossim::nan(); computeMetersPerPixel(theOrigin, theDegreesPerPixel.y, theDegreesPerPixel.x, theMetersPerPixel); updateTransform(); } ossimLlxyProjection::ossimLlxyProjection(const ossimLlxyProjection& rhs) : ossimMapProjection(rhs) { theProjectionUnits = OSSIM_DEGREES; theOrigin = rhs.theOrigin; theUlGpt = rhs.theUlGpt; theUlEastingNorthing.y = ossim::nan(); theUlEastingNorthing.x = ossim::nan(); theDatum = theOrigin.datum(); theEllipsoid = *(theDatum->ellipsoid()); theDegreesPerPixel.y = rhs.theDegreesPerPixel.y; theDegreesPerPixel.x = rhs.theDegreesPerPixel.x; computeMetersPerPixel(theOrigin, theDegreesPerPixel.y, theDegreesPerPixel.x, theMetersPerPixel); updateTransform(); } ossimLlxyProjection::ossimLlxyProjection(const ossimGpt& origin, double latSpacing, double lonSpacing) : ossimMapProjection() { theProjectionUnits = OSSIM_DEGREES; theOrigin = origin; theUlGpt = origin; theUlEastingNorthing.y = 0.0; theUlEastingNorthing.x = 0.0; theDatum = theOrigin.datum(); theEllipsoid = *(theDatum->ellipsoid()); theDegreesPerPixel.y = latSpacing; theDegreesPerPixel.x = lonSpacing; computeMetersPerPixel(theOrigin, theDegreesPerPixel.y, theDegreesPerPixel.x, theMetersPerPixel); updateTransform(); } ossimLlxyProjection::ossimLlxyProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) : ossimMapProjection(ellipsoid, origin) { theProjectionUnits = OSSIM_DEGREES; theDegreesPerPixel.y = 1.0; theDegreesPerPixel.x = 1.0; theUlEastingNorthing.y = 0.0; theUlEastingNorthing.x = 0.0; computeMetersPerPixel(theOrigin, theDegreesPerPixel.y, theDegreesPerPixel.x, theMetersPerPixel); updateTransform(); } ossimLlxyProjection::~ossimLlxyProjection() { } ossimObject* ossimLlxyProjection::dup()const { return new ossimLlxyProjection(*this); } void ossimLlxyProjection::updateTransform () { theModelTransform.setIdentity(); auto m = theModelTransform.getData(); // Scale and rotation: double cosAz = 1.0, sinAz = 0.0; if (theImageToModelAzimuth != 0) { cosAz = ossim::cosd(theImageToModelAzimuth); sinAz = ossim::sind(theImageToModelAzimuth); } m[0][0] = theDegreesPerPixel.lon * cosAz; m[0][1] = theDegreesPerPixel.lat * sinAz; m[1][0] = -theDegreesPerPixel.lon * sinAz; m[1][1] = theDegreesPerPixel.lat * cosAz; // Offset: m[0][3] = theOrigin.lond(); m[1][3] = theOrigin.latd(); theInverseModelTransform = theModelTransform; theInverseModelTransform.i(); } void ossimLlxyProjection::computeDegreesPerPixel(const ossimGpt& ground, const ossimDpt& metersPerPixel, double &deltaLat, double &deltaLon) { ossimDpt mpd = ground.metersPerDegree(); ossimDpt dpm(1.0/mpd.x, 1.0/mpd.y); deltaLat = metersPerPixel.y*dpm.y; deltaLon = metersPerPixel.x*dpm.x; } void ossimLlxyProjection::computeMetersPerPixel(const ossimGpt& center, double deltaDegreesPerPixelLat, double deltaDegreesPerPixelLon, ossimDpt &metersPerPixel) { metersPerPixel = center.metersPerDegree(); metersPerPixel.x *= deltaDegreesPerPixelLon; metersPerPixel.y *= deltaDegreesPerPixelLat; } void ossimLlxyProjection::worldToLineSample(const ossimGpt& worldPoint, ossimDpt& lineSampPt) const { // Differs from the base class in that no call to inverse() is needed since modelToImage is enough ossimGpt gpt = worldPoint; if (*theOrigin.datum() != *gpt.datum()) { // Apply datum shift if it's not the same. gpt.changeDatum(theOrigin.datum()); } ossimDpt modelPt(gpt.lon, gpt.lat); eastingNorthingToLineSample(modelPt, lineSampPt); } void ossimLlxyProjection::lineSampleHeightToWorld(const ossimDpt &lineSample, const double& hgtEllipsoid, ossimGpt& gpt) const { gpt.makeNan(); // Start with the origin. This will keep the origin's datum. gpt.datum(theOrigin.datum()); ossimDpt modelPt; // The model coordinates here are x=lon, y=lat lineSampleToEastingNorthing(lineSample, modelPt); gpt.latd(modelPt.y); gpt.lond(modelPt.lon); gpt.hgt = hgtEllipsoid; } std::ostream& ossimLlxyProjection::print(std::ostream& out) const { out << setiosflags(ios::fixed) << setprecision(15) << "ossimLlxyProjection dump:" << "\norigin: " << theOrigin << "\nlatitude spacing in decimal degrees: " << theDegreesPerPixel.y << "\nlongitude spacing in decimal degrees: " << theDegreesPerPixel.x << "\n\nossimMapProjection dump:\n" << endl; return ossimMapProjection::print(out); } void ossimLlxyProjection::setMetersPerPixel(const ossimDpt& pt) { ossimMapProjection::setMetersPerPixel(pt); computeDegreesPerPixel(theOrigin, theMetersPerPixel, theDegreesPerPixel.y, theDegreesPerPixel.x); } bool ossimLlxyProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Base class... ossimMapProjection::saveState(kwl, prefix); return true; } bool ossimLlxyProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Base class... ossimMapProjection::loadState(kwl, prefix); if (theOrigin.hasNans() == false) { if ( (theDegreesPerPixel.hasNans() == false) && theMetersPerPixel.hasNans() ) { // Compute meters per pixel from origin and decimal degrees. computeMetersPerPixel(theOrigin, theDegreesPerPixel.y, theDegreesPerPixel.x, theMetersPerPixel); } else if( (theMetersPerPixel.hasNans() == false) && theDegreesPerPixel.hasNans() ) { // Compute decimal degrees per pixel from origin and meters. computeDegreesPerPixel(theOrigin, theMetersPerPixel, theDegreesPerPixel.y, theDegreesPerPixel.x); } else { // Assign some value. theDegreesPerPixel.y = DEFAULT_DEGREES_PER_PIXEL; theDegreesPerPixel.x = DEFAULT_DEGREES_PER_PIXEL; computeMetersPerPixel(theOrigin, theDegreesPerPixel.y, theDegreesPerPixel.x, theMetersPerPixel); } } return true; } bool ossimLlxyProjection::operator==(const ossimProjection& projection) const { const ossimLlxyProjection* proj = dynamic_cast(&projection); if(!proj) { return false; } return ( // (theOrigin == proj->theOrigin) && // tmp... fix gpt! (theDegreesPerPixel.y == proj->theDegreesPerPixel.y) && (theDegreesPerPixel.x == proj->theDegreesPerPixel.x) ); } ossimDpt ossimLlxyProjection::forward(const ossimGpt &worldPoint) const { ossimDpt result; worldToLineSample(worldPoint, result); return result; } ossimGpt ossimLlxyProjection::inverse(const ossimDpt &projectedPoint) const { ossimGpt result; lineSampleToWorld(projectedPoint, result); return result; } void ossimLlxyProjection::setLatSpacing(double spacing) { theDegreesPerPixel.y = spacing; // Update the meters per pixel. ossimDpt pt = ossimGpt(0.0, 0.0).metersPerDegree(); theMetersPerPixel.y = pt.y * theDegreesPerPixel.y; } void ossimLlxyProjection::setLonSpacing(double spacing) { theDegreesPerPixel.x = spacing; // Update the meters per pixel. ossimDpt pt = ossimGpt(0.0, 0.0).metersPerDegree(); theMetersPerPixel.x = pt.x * theDegreesPerPixel.x; } bool ossimLlxyProjection::isGeographic() const { return true; } double ossimLlxyProjection::getLatSpacing() const { return theDegreesPerPixel.y; } double ossimLlxyProjection::getLonSpacing() const { return theDegreesPerPixel.x; } ossim-Miami-2.9.1/src/projection/ossimMapProjection.cpp000066400000000000000000001306541352751253100232200ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Base class for all map projections. // //******************************************************************* // $Id: ossimMapProjection.cpp 23418 2015-07-09 18:46:41Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define USE_MODEL_TRANSFORM 1 static ossimTrace traceDebug("ossimMapProjection:debug"); // RTTI information for the ossimMapProjection RTTI_DEF1(ossimMapProjection, "ossimMapProjection" , ossimProjection); ossimMapProjection::ossimMapProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :theEllipsoid(ellipsoid), theOrigin(origin), theDatum(origin.datum()), // force no shifting theUlGpt(0, 0), theUlEastingNorthing(0, 0), theFalseEastingNorthing(0, 0), thePcsCode(0), theElevationLookupFlag(false), theModelTransform(), theInverseModelTransform(), theProjectionUnits(OSSIM_METERS), theImageToModelAzimuth(0) { theModelTransform.setIdentity(); theInverseModelTransform.setIdentity(); theUlGpt = theOrigin; theUlEastingNorthing.makeNan(); theMetersPerPixel.makeNan(); theDegreesPerPixel.makeNan(); } ossimMapProjection::ossimMapProjection(const ossimMapProjection& src) : ossimProjection(src), theEllipsoid(src.theEllipsoid), theOrigin(src.theOrigin), theDatum(src.theDatum), theMetersPerPixel(src.theMetersPerPixel), theDegreesPerPixel(src.theDegreesPerPixel), theUlGpt(src.theUlGpt), theUlEastingNorthing(src.theUlEastingNorthing), theFalseEastingNorthing(src.theFalseEastingNorthing), thePcsCode(src.thePcsCode), theElevationLookupFlag(false), theModelTransform(src.theModelTransform), theInverseModelTransform(src.theInverseModelTransform), theProjectionUnits(src.theProjectionUnits), theImageToModelAzimuth(src.theImageToModelAzimuth) { } ossimMapProjection::~ossimMapProjection() { } ossimGpt ossimMapProjection::origin()const { return theOrigin; } void ossimMapProjection::setPcsCode(ossim_uint32 pcsCode) { thePcsCode = pcsCode; } ossim_uint32 ossimMapProjection::getPcsCode() const { // The PCS code is not always set when the projection is instantiated with explicit parameters, // since the code is only necessary when looking up those parameters in a database. However, it // is still necessary to recognize when an explicit projection coincides with an EPSG-specified // projection, and assign our PCS code to match it. So let's take this opportunity now to make // sure the PCS code is properly initialized. if (thePcsCode == 0) { thePcsCode = ossimEpsgProjectionDatabase::instance()->findProjectionCode(*this); if (thePcsCode == 0) thePcsCode = 32767; // user-defined (non-EPSG) projection } if (thePcsCode == 32767) return 0; // 32767 only used internally. To the rest of OSSIM, the PCS=0 is undefined return thePcsCode; } ossimString ossimMapProjection::getProjectionName() const { return getClassName(); } double ossimMapProjection::getA() const { return theEllipsoid.getA(); } double ossimMapProjection::getB() const { return theEllipsoid.getB(); } double ossimMapProjection::getF() const { return theEllipsoid.getFlattening(); } ossimDpt ossimMapProjection::getMetersPerPixel() const { return theMetersPerPixel; } const ossimDpt& ossimMapProjection::getDecimalDegreesPerPixel() const { return theDegreesPerPixel; } const ossimDpt& ossimMapProjection::getUlEastingNorthing() const { return theUlEastingNorthing; } const ossimGpt& ossimMapProjection::getUlGpt() const { return theUlGpt; } const ossimGpt& ossimMapProjection::getOrigin() const { return theOrigin; } const ossimDatum* ossimMapProjection::getDatum() const { return theDatum; } bool ossimMapProjection::isGeographic()const { return false; } void ossimMapProjection::setEllipsoid(const ossimEllipsoid& ellipsoid) { theEllipsoid = ellipsoid; update(); } void ossimMapProjection::setAB(double a, double b) { theEllipsoid.setA(a); theEllipsoid.setB(b); update(); } void ossimMapProjection::setDatum(const ossimDatum* datum) { if (!datum || (*theDatum == *datum)) return; theDatum = datum; theEllipsoid = *(theDatum->ellipsoid()); // Change the datum of the ossimGpt data members: theOrigin.changeDatum(theDatum); theUlGpt.changeDatum(theDatum); update(); // A change of datum usually implies a change of EPSG codes. Reset the PCS code. It will be // reestablished as needed in the getPcsCode() method: thePcsCode = 0; } void ossimMapProjection::setOrigin(const ossimGpt& origin) { // Set the origin and since the origin has a datum which in turn has // an ellipsoid, sync them up. // NOTE: Or perhaps we need to change the datum of the input origin to that of theDatum? (OLK 05/11) theOrigin = origin; theOrigin.changeDatum(theDatum); update(); } void ossimMapProjection::assign(const ossimProjection &aProjection) { if(&aProjection!=this) { ossimKeywordlist kwl; aProjection.saveState(kwl); loadState(kwl); } } void ossimMapProjection::update() { // if the delta lat and lon per pixel is set then // check to see if the meters were set. // if (!theDegreesPerPixel.hasNans() && theMetersPerPixel.hasNans()) { computeMetersPerPixel(); } else if (!theMetersPerPixel.hasNans()) { computeDegreesPerPixel(); } // compute the tie points if not already computed // // The tiepoint was specified either as easting/northing or lat/lon. Need to initialize the one // that has not been assigned yet: if (theUlEastingNorthing.hasNans() && !theUlGpt.hasNans()) theUlEastingNorthing = forward(theUlGpt); else if (theUlGpt.hasNans() && !theUlEastingNorthing.hasNans()) theUlGpt = inverse(theUlEastingNorthing); else if (theUlGpt.hasNans() && theUlEastingNorthing.hasNans()) { theUlGpt = theOrigin; theUlEastingNorthing = forward(theUlGpt); } if (theMetersPerPixel.hasNans() && theDegreesPerPixel.hasNans()) { ossimDpt mpd = ossimGpt().metersPerDegree(); if (isGeographic()) { theDegreesPerPixel.lat = 1.0 / mpd.y; theDegreesPerPixel.lon = 1.0 / mpd.x; computeMetersPerPixel(); } else { theMetersPerPixel.x = 1.0; theMetersPerPixel.y = 1.0; computeDegreesPerPixel(); } } // The last bit to do is the most important: Update the model transform so that we properly // convert between E, N and line, sample: updateTransform(); } void ossimMapProjection::setModelTransform (const ossimMatrix4x4& transform) { theModelTransform = transform; theInverseModelTransform = theModelTransform; theInverseModelTransform.i(); updateFromTransform(); } void ossimMapProjection::updateTransform() { // The transform contains the map rotation, GSD, and tiepoint. These individual parameters are // also saved in members theImageToModelAzimuth, theMetersPerPixel, and theUlEastingNorthing. // Any one of those may have changed requiring a new transform to be computed from the new // values. All calls to update() will also call this, so the rotation, scale and offset need // to be preserved to avoid blowing them away by resetting theModelTransform to identity. // Assumes model coordinates in meters: theModelTransform.setIdentity(); NEWMAT::Matrix& m = theModelTransform.getData(); double cosAz = 1.0, sinAz = 0.0; if (theImageToModelAzimuth != 0) { cosAz = ossim::cosd(theImageToModelAzimuth); sinAz = ossim::sind(theImageToModelAzimuth); } // Note that northing in the map projection is positive up, while in image space the y-axis // is positive is down, so apply that inversion by forcing theMetersPerPixel.y to be negative: // Scale and rotation: m[0][0] = theMetersPerPixel.x * cosAz; m[0][1] = -theMetersPerPixel.y * sinAz; m[1][0] = -theMetersPerPixel.x * sinAz; m[1][1] = -theMetersPerPixel.y * cosAz; // Offset: m[0][3] = theUlEastingNorthing.x; m[1][3] = theUlEastingNorthing.y; theInverseModelTransform = theModelTransform; theInverseModelTransform.i(); } void ossimMapProjection::updateFromTransform() { // Extract scale, rotation and offset from the transform matrix. Note that with scale, rotation, // and offset preserved in theMetersPerPixel, theImageToModelAzimuth, and theUlEastingNorthing, // respectively, the transform can be regenerated with a call to update(). const NEWMAT::Matrix& m = theModelTransform.getData(); theMetersPerPixel.x = sqrt(m[0][0]*m[0][0] + m[1][0]*m[1][0]); theMetersPerPixel.y = sqrt(m[1][0]*m[1][0] + m[1][1]*m[1][1]); theUlEastingNorthing.x = m[0][3]; theUlEastingNorthing.y = m[1][3]; theImageToModelAzimuth = ossim::acosd(m[0][0]/theMetersPerPixel.x); theUlGpt = inverse(theUlEastingNorthing); computeDegreesPerPixel(); } void ossimMapProjection::applyScale(const ossimDpt& scale, bool recenterTiePoint) { ossimDpt mapTieDpt; ossimGpt mapTieGpt; if (recenterTiePoint) { if (isGeographic()) { mapTieGpt = getUlGpt(); mapTieGpt.lat += theDegreesPerPixel.lat/2.0; mapTieGpt.lon -= theDegreesPerPixel.lon/2.0; } else { mapTieDpt = getUlEastingNorthing(); mapTieDpt.x -= theMetersPerPixel.x/2.0; mapTieDpt.y += theMetersPerPixel.y/2.0; } } theDegreesPerPixel.x *= scale.x; theDegreesPerPixel.y *= scale.y; theMetersPerPixel.x *= scale.x; theMetersPerPixel.y *= scale.y; if ( recenterTiePoint ) { if (isGeographic()) { mapTieGpt.lat -= theDegreesPerPixel.lat/2.0; mapTieGpt.lon += theDegreesPerPixel.lon/2.0; setUlTiePoints(mapTieGpt); } else { mapTieDpt.x += theMetersPerPixel.x/2.0; mapTieDpt.y -= theMetersPerPixel.y/2.0; setUlTiePoints(mapTieDpt); } } updateTransform(); } void ossimMapProjection::applyRotation(const double& azimuthDeg) { theImageToModelAzimuth += azimuthDeg; if (theImageToModelAzimuth >= 360.0) theImageToModelAzimuth -= 360.0; updateTransform(); } ossimDpt ossimMapProjection::worldToLineSample(const ossimGpt &worldPoint)const { ossimDpt result; worldToLineSample(worldPoint, result); return result; } ossimGpt ossimMapProjection::lineSampleToWorld(const ossimDpt &lineSample)const { ossimGpt result; lineSampleToWorld(lineSample, result); return result; } void ossimMapProjection::worldToLineSample(const ossimGpt &worldPoint, ossimDpt& lineSample) const { lineSample.makeNan(); if(worldPoint.isLatLonNan()) return; // Shift the world point to the datum being used by this projection, if defined: ossimGpt gpt = worldPoint; if ( theDatum ) gpt.changeDatum(theDatum); // Transform world point to model coordinates using the concrete map projection equations: ossimDpt modelPoint = forward(gpt); // Now convert map model coordinates to image line/sample space: eastingNorthingToLineSample(modelPoint, lineSample); } void ossimMapProjection::lineSampleHeightToWorld(const ossimDpt &lineSample, const double& hgtEllipsoid, ossimGpt& gpt)const { gpt.makeNan(); // make sure that the passed in lineSample is good and // check to make sure our easting northing is good so // we can compute the line sample. if(lineSample.hasNans()) return; // Transform image coordinates (line, sample) to model coordinates (easting, northing): ossimDpt modelPoint; lineSampleToEastingNorthing(lineSample, modelPoint); // Transform model coordinates to world point using concrete map projection equations: gpt = inverse(modelPoint); gpt.hgt = hgtEllipsoid; } void ossimMapProjection::lineSampleToWorld (const ossimDpt& lineSampPt, ossimGpt& worldPt) const { lineSampleHeightToWorld(lineSampPt, ossim::nan(), worldPt); if(theElevationLookupFlag) worldPt.hgt = ossimElevManager::instance()->getHeightAboveEllipsoid(worldPt); } void ossimMapProjection::lineSampleToEastingNorthing(const ossimDpt& lineSample, ossimDpt& eastingNorthing)const { #ifdef USE_MODEL_TRANSFORM // Transform according to 4x4 transform embedded in the projection: const NEWMAT::Matrix& m = theModelTransform.getData(); eastingNorthing.x = m[0][0]*lineSample.x + m[0][1]*lineSample.y + m[0][3]; eastingNorthing.y = m[1][0]*lineSample.x + m[1][1]*lineSample.y + m[1][3]; #else /** Performs image to model coordinate transformation. This implementation bypasses * theModelTransform. Probably should eventually switch to use theModelTransform * because this cannot handle map rotation. */ // make sure that the passed in lineSample is good and // check to make sure our easting northing is good so // we can compute the line sample. // if(lineSample.hasNans()||theUlEastingNorthing.hasNans()) { eastingNorthing.makeNan(); return; } ossimDpt deltaPoint = lineSample; eastingNorthing.x = theUlEastingNorthing.x + deltaPoint.x*theMetersPerPixel.x; eastingNorthing.y = theUlEastingNorthing.y + (-deltaPoint.y)*theMetersPerPixel.y ; // eastingNorthing.x += (lineSample.x*theMetersPerPixel.x); // Note: the Northing is positive up. In image space // the positive axis is down so we must multiply by // -1 // eastingNorthing.y += (-lineSample.y*theMetersPerPixel.y); #endif } void ossimMapProjection::eastingNorthingToLineSample(const ossimDpt& eastingNorthing, ossimDpt& lineSample)const { #ifdef USE_MODEL_TRANSFORM // Transform according to 4x4 transform embedded in the projection: const NEWMAT::Matrix& m = theInverseModelTransform.getData(); lineSample.x = m[0][0]*eastingNorthing.x + m[0][1]*eastingNorthing.y + m[0][3]; lineSample.y = m[1][0]*eastingNorthing.x + m[1][1]*eastingNorthing.y + m[1][3]; #else /** Performs model to image coordinate transformation. This implementation bypasses * theModelTransform. Probably should eventually switch to use equivalent theModelTransform * because this cannot handle map rotation. */ if(eastingNorthing.hasNans()) { lineSample.makeNan(); return; } // check the final result to make sure there were no // problems. // lineSample.x = (eastingNorthing.x - theUlEastingNorthing.x)/theMetersPerPixel.x; // We must remember that the Northing is negative since the positive // axis for an image is assumed to go down since it's image space. lineSample.y = (-(eastingNorthing.y-theUlEastingNorthing.y))/theMetersPerPixel.y; #endif } void ossimMapProjection::eastingNorthingToWorld(const ossimDpt& eastingNorthing, ossimGpt& worldPt)const { ossimDpt lineSample; eastingNorthingToLineSample(eastingNorthing, lineSample); lineSampleToWorld(lineSample, worldPt); } void ossimMapProjection::setMetersPerPixel(const ossimDpt& resolution) { theMetersPerPixel = resolution; computeDegreesPerPixel(); updateTransform(); } void ossimMapProjection::setDecimalDegreesPerPixel(const ossimDpt& resolution) { theDegreesPerPixel = resolution; computeMetersPerPixel(); // this method will update the transform updateTransform(); } void ossimMapProjection::setUlTiePoints(const ossimGpt& gpt) { setUlGpt(gpt); } void ossimMapProjection::setUlTiePoints(const ossimDpt& eastingNorthing) { setUlEastingNorthing(eastingNorthing); } void ossimMapProjection::setUlEastingNorthing(const ossimDpt& ulEastingNorthing) { theUlEastingNorthing = ulEastingNorthing; theUlGpt = inverse(ulEastingNorthing); updateTransform(); } void ossimMapProjection::setUlGpt(const ossimGpt& ulGpt) { theUlGpt = ulGpt; // The ossimGpt data members need to use the same datum as this projection: if (*theDatum != *(ulGpt.datum())) theUlGpt.changeDatum(theDatum); // Adjust the stored easting / northing. theUlEastingNorthing = forward(theUlGpt); updateTransform(); } bool ossimMapProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimProjection::saveState(kwl, prefix); kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, theOrigin.latd(), true); kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, theOrigin.lond(), true); theEllipsoid.saveState(kwl, prefix); if(theDatum) { kwl.add(prefix, ossimKeywordNames::DATUM_KW, theDatum->code(), true); } // Calling access method to give it an opportunity to update the code in case of param change: ossim_uint32 code = getPcsCode(); if (code) { ossimString epsg_spec = ossimString("EPSG:") + ossimString::toString(code); kwl.add(prefix, ossimKeywordNames::SRS_NAME_KW, epsg_spec, true); } if(isGeographic()) { kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, ossimDpt(theUlGpt).toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW, theDegreesPerPixel.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES), true); } else { kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, theUlEastingNorthing.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW, theMetersPerPixel.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true); } kwl.add(prefix, ossimKeywordNames::PCS_CODE_KW, code, true); kwl.add(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_KW, theFalseEastingNorthing.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true); kwl.add(prefix, ossimKeywordNames::ELEVATION_LOOKUP_FLAG_KW, ossimString::toString(theElevationLookupFlag), true); kwl.add(prefix, ossimKeywordNames::ORIGINAL_MAP_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(theProjectionUnits), true); kwl.add(prefix, ossimKeywordNames::IMAGE_MODEL_ROTATION_KW, theImageToModelAzimuth, true); return true; } bool ossimMapProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimProjection::loadState(kwl, prefix); // Initialize the image-to-map transform to identity (no scale, rotation, or offset): theModelTransform.setIdentity(); theInverseModelTransform.setIdentity(); const char* elevLookupFlag = kwl.find(prefix, ossimKeywordNames::ELEVATION_LOOKUP_FLAG_KW); if(elevLookupFlag) { theElevationLookupFlag = ossimString(elevLookupFlag).toBool(); } // Get the ellipsoid. theEllipsoid.loadState(kwl, prefix); const char *lookup; // Get the Projection Coordinate System (assumed from EPSG database). // NOTE: the code is read here for saving in this object only. // The code is not verified until a call to getPcs() is called. If ONLY this code // had been provided, then the EPSG projection factory would populate a new instance of the // corresponding map projection and have it saveState for constructing again later in the // conventional fashion here thePcsCode = 0; lookup = kwl.find(prefix, ossimKeywordNames::PCS_CODE_KW); if(lookup) thePcsCode = ossimString(lookup).toUInt32(); // EPSG PROJECTION CODE // The datum can be specified in 2 ways: either via OSSIM/geotrans alpha-codes or EPSG code. // Last resort use WGS 84 (consider throwing an exception to catch any bad datums): theDatum = ossimDatumFactoryRegistry::instance()->create(kwl, prefix); if (theDatum == NULL) { theDatum = ossimDatumFactory::instance()->wgs84(); } // Set all ossimGpt-type members to use this datum: theOrigin.datum(theDatum); theUlGpt.datum(theDatum); // Fetch the ellipsoid from the datum: const ossimEllipsoid* ellipse = theDatum->ellipsoid(); if(ellipse) theEllipsoid = *ellipse; // Get the latitude of the origin. lookup = kwl.find(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW); if (lookup) { theOrigin.latd(ossimString(lookup).toFloat64()); } // else ??? // Get the central meridian. lookup = kwl.find(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW); if (lookup) { theOrigin.lond(ossimString(lookup).toFloat64()); } // else ??? // Get the pixel scale. theMetersPerPixel.makeNan(); theDegreesPerPixel.makeNan(); lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW); if (lookup) { ossimUnitType units = static_cast(ossimUnitTypeLut::instance()-> getEntryNumber(lookup)); lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW); if (lookup) { ossimDpt scale; scale.toPoint(std::string(lookup)); switch (units) { case OSSIM_METERS: { theMetersPerPixel = scale; break; } case OSSIM_DEGREES: { theDegreesPerPixel.x = scale.x; theDegreesPerPixel.y = scale.y; break; } case OSSIM_FEET: case OSSIM_US_SURVEY_FEET: { ossimUnitConversionTool ut; ut.setValue(scale.x, units); theMetersPerPixel.x = ut.getValue(OSSIM_METERS); ut.setValue(scale.y, units); theMetersPerPixel.y = ut.getValue(OSSIM_METERS); break; } default: { if(traceDebug()) { // Unhandled unit type! ossimNotify(ossimNotifyLevel_WARN) << "ossimMapProjection::loadState WARNING!" << "Unhandled unit type for " << ossimKeywordNames::PIXEL_SCALE_UNITS_KW << ": " << ( ossimUnitTypeLut::instance()-> getEntryString(units).c_str() ) << endl; } break; } } // End of switch (units) } // End of if (PIXEL_SCALE_XY) } // End of if (PIXEL_SCALE_UNITS) else { // BACKWARDS COMPATIBILITY LOOKUPS... lookup = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_X_KW); if(lookup) { theMetersPerPixel.x = fabs(ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW); if(lookup) { theMetersPerPixel.y = fabs(ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT); if(lookup) { theDegreesPerPixel.y = fabs(ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON); if(lookup) { theDegreesPerPixel.x = fabs(ossimString(lookup).toFloat64()); } } // Get the tie point. theUlGpt.makeNan(); // Since this won't be picked up from keywords set to 0 to keep nan out. theUlGpt.hgt = 0.0; theUlEastingNorthing.makeNan(); lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW); if (lookup) { ossimUnitType units = static_cast(ossimUnitTypeLut::instance()-> getEntryNumber(lookup)); lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_XY_KW); if (lookup) { ossimDpt tie; tie.toPoint(std::string(lookup)); switch (units) { case OSSIM_METERS: { theUlEastingNorthing = tie; break; } case OSSIM_DEGREES: { theUlGpt.lond(tie.x); theUlGpt.latd(tie.y); break; } case OSSIM_FEET: case OSSIM_US_SURVEY_FEET: { ossimUnitConversionTool ut; ut.setValue(tie.x, units); theUlEastingNorthing.x = ut.getValue(OSSIM_METERS); ut.setValue(tie.y, units); theUlEastingNorthing.y = ut.getValue(OSSIM_METERS); break; } default: { if(traceDebug()) { // Unhandled unit type! ossimNotify(ossimNotifyLevel_WARN) << "ossimMapProjection::loadState WARNING!" << "Unhandled unit type for " << ossimKeywordNames::TIE_POINT_UNITS_KW << ": " << ( ossimUnitTypeLut::instance()-> getEntryString(units).c_str() ) << endl; } break; } } // End of switch (units) } // End of if (TIE_POINT_XY) } // End of if (TIE_POINT_UNITS) else { // BACKWARDS COMPATIBILITY LOOKUPS... lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_EASTING_KW); if(lookup) { theUlEastingNorthing.x = (ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_NORTHING_KW); if(lookup) { theUlEastingNorthing.y = (ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LAT_KW); if (lookup) { theUlGpt.latd(ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LON_KW); if (lookup) { theUlGpt.lond(ossimString(lookup).toFloat64()); } } // Get the false easting northing. theFalseEastingNorthing.x = 0.0; theFalseEastingNorthing.y = 0.0; ossimUnitType en_units = OSSIM_METERS; lookup = kwl.find(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW); if (lookup) { en_units = static_cast(ossimUnitTypeLut::instance()->getEntryNumber(lookup)); } lookup = kwl.find(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_KW); if (lookup) { ossimDpt eastingNorthing; eastingNorthing.toPoint(std::string(lookup)); switch (en_units) { case OSSIM_METERS: { theFalseEastingNorthing = eastingNorthing; break; } case OSSIM_FEET: case OSSIM_US_SURVEY_FEET: { ossimUnitConversionTool ut; ut.setValue(eastingNorthing.x, en_units); theFalseEastingNorthing.x = ut.getValue(OSSIM_METERS); ut.setValue(eastingNorthing.y, en_units); theFalseEastingNorthing.y = ut.getValue(OSSIM_METERS); break; } default: { if(traceDebug()) { // Unhandled unit type! ossimNotify(ossimNotifyLevel_WARN) << "ossimMapProjection::loadState WARNING! Unhandled unit type for " << ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW << ": " << (ossimUnitTypeLut::instance()->getEntryString(en_units).c_str()) << endl; } break; } } // End of switch (units) } // End of if (FALSE_EASTING_NORTHING_KW) else { // BACKWARDS COMPATIBILITY LOOKUPS... lookup = kwl.find(prefix, ossimKeywordNames::FALSE_EASTING_KW); if(lookup) { theFalseEastingNorthing.x = (ossimString(lookup).toFloat64()); } lookup = kwl.find(prefix, ossimKeywordNames::FALSE_NORTHING_KW); if(lookup) { theFalseEastingNorthing.y = (ossimString(lookup).toFloat64()); } } // if((theDegreesPerPixel.x!=OSSIM_DBL_NAN)&& // (theDegreesPerPixel.y!=OSSIM_DBL_NAN)&& // theMetersPerPixel.hasNans()) // { // theMetersPerPixel = theOrigin.metersPerDegree(); // theMetersPerPixel.x *= theDegreesPerPixel.x; // theMetersPerPixel.y *= theDegreesPerPixel.y; // } lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_TYPE_KW); if (lookup) { ossimString pixelType = lookup; pixelType=pixelType.trim(); if(pixelType!="") { pixelType.downcase(); if(pixelType.contains("area")) { if( theMetersPerPixel.hasNans() == false) { if(!theUlEastingNorthing.hasNans()) { theUlEastingNorthing.x += (theMetersPerPixel.x*0.5); theUlEastingNorthing.y -= (theMetersPerPixel.y*0.5); } } if(theDegreesPerPixel.hasNans() == false) { theUlGpt.latd( theUlGpt.latd() - (theDegreesPerPixel.y*0.5) ); theUlGpt.lond( theUlGpt.lond() + (theDegreesPerPixel.x*0.5) ); } } } } // We preserve the units of the originally created projection (typically from EPSG proj factory) // in case user needs map coordinates in those units (versus default meters) lookup = kwl.find(prefix, ossimKeywordNames::ORIGINAL_MAP_UNITS_KW); if (lookup) { theProjectionUnits = static_cast(ossimUnitTypeLut::instance()->getEntryNumber(lookup)); } // Possible map-to-image rotation handled by theModelTransform: lookup = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_ROTATION_KW); if (lookup) { theImageToModelAzimuth = ossimString(lookup).toFloat64(); } #if 0 theModelUnitType = OSSIM_UNIT_UNKNOWN; const char* mapUnit = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_UNIT_KW); theModelUnitType = static_cast(ossimUnitTypeLut::instance()->getEntryNumber(mapUnit)); #endif //--- // Set the datum of the origin and tie point. // Use method that does NOT perform a shift. //--- if (theDatum) { theOrigin.datum(theDatum); theUlGpt.datum(theDatum); } if (theMetersPerPixel.hasNans() && theDegreesPerPixel.hasNans()) { ossimDpt mpd = ossimGpt().metersPerDegree(); if (isGeographic()) { theDegreesPerPixel.lat = 1.0/mpd.y; theDegreesPerPixel.lon = 1.0/mpd.y; } else { theMetersPerPixel.x = 1.0; theMetersPerPixel.y = 1.0; } } ossimString transformElems = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_MATRIX_KW); if (!transformElems.empty()) { // The model transform trumps (I hate that word) settings for scale, rotation, and map offset: vector elements = transformElems.split(" "); NEWMAT::Matrix& m = theModelTransform.getData(); // At this scope for IDE debugging if (elements.size() != 16) { ossimNotify(ossimNotifyLevel_WARN) << __FILE__ << ": " << __LINE__<< "\nossimMapProjection::loadState ERROR: Model " "Transform matrix must have 16 elements!"<< std::endl; } else { int i = 0; for (ossimString &e : elements) { m[i / 4][i % 4] = e.toDouble(); ++i; } } theInverseModelTransform = theModelTransform; theInverseModelTransform.i(); updateFromTransform(); } else { // No model transform matrix was provided, so calculate it given scale rotation and offset: update(); } return true; } std::ostream& ossimMapProjection::print(std::ostream& out) const { const char MODULE[] = "ossimMapProjection::print"; out << setiosflags(ios::fixed) << setprecision(15) << "\n// " << MODULE << "\n" << ossimKeywordNames::TYPE_KW << ": " << getClassName() << "\n" << ossimKeywordNames::MAJOR_AXIS_KW << ": " << theEllipsoid.getA() << "\n" << ossimKeywordNames::MINOR_AXIS_KW << ": " << theEllipsoid.getB() << "\n" << ossimKeywordNames::ORIGIN_LATITUDE_KW << ": " << theOrigin.latd() << "\n" << ossimKeywordNames::CENTRAL_MERIDIAN_KW << ": " << theOrigin.lond() << "\norigin: " << theOrigin << "\n" << ossimKeywordNames::DATUM_KW << ": " << (theDatum?theDatum->code().c_str():"unknown") << "\n" << ossimKeywordNames::METERS_PER_PIXEL_X_KW << ": " << ((ossim::isnan(theMetersPerPixel.x))?ossimString("nan"):ossimString::toString(theMetersPerPixel.x, 15)) << "\n" << ossimKeywordNames::METERS_PER_PIXEL_Y_KW << ": " << ((ossim::isnan(theMetersPerPixel.y))?ossimString("nan"):ossimString::toString(theMetersPerPixel.y, 15)) << "\n" << ossimKeywordNames::FALSE_EASTING_NORTHING_KW << ": " << theFalseEastingNorthing.toString().c_str() << "\n" << ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW << ": " << ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS) << "\n" << ossimKeywordNames::PCS_CODE_KW << ": " << thePcsCode << "\n" << ossimKeywordNames::IMAGE_MODEL_ROTATION_KW << ": " << theImageToModelAzimuth; const NEWMAT::Matrix& m = theModelTransform.getData(); out << "\nImageModelTransform [2x3]: "<getEntryString(OSSIM_DEGREES) << "\n" << ossimKeywordNames::PIXEL_SCALE_XY_KW << ": " << theDegreesPerPixel.toString().c_str() << "\n" << ossimKeywordNames::PIXEL_SCALE_UNITS_KW << ": " << ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES) << std::endl; } else { out << "\n" << ossimKeywordNames::TIE_POINT_XY_KW << ": " << theUlEastingNorthing.toString().c_str() << "\n" << ossimKeywordNames::TIE_POINT_UNITS_KW << ": " << ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS) << "\n" << ossimKeywordNames::PIXEL_SCALE_XY_KW << ": " << theMetersPerPixel.toString().c_str() << "\n" << ossimKeywordNames::PIXEL_SCALE_UNITS_KW << ": " << ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS) << std::endl; } return ossimProjection::print(out); } void ossimMapProjection::computeDegreesPerPixel() { ossimDpt eastNorthGround = forward(theOrigin); ossimDpt rightEastNorth = eastNorthGround; ossimDpt downEastNorth = eastNorthGround; rightEastNorth.x += theMetersPerPixel.x; downEastNorth.y -= theMetersPerPixel.y; ossimGpt rightGpt = inverse(rightEastNorth); ossimGpt downGpt = inverse(downEastNorth); // use euclidean distance to get length along the horizontal (lon) // and vertical (lat) directions // double tempDeltaLat = rightGpt.latd() - theOrigin.latd(); double tempDeltaLon = rightGpt.lond() - theOrigin.lond(); theDegreesPerPixel.lon = sqrt(tempDeltaLat*tempDeltaLat + tempDeltaLon*tempDeltaLon); tempDeltaLat = downGpt.latd() - theOrigin.latd(); tempDeltaLon = downGpt.lond() - theOrigin.lond(); theDegreesPerPixel.lat = sqrt(tempDeltaLat*tempDeltaLat + tempDeltaLon*tempDeltaLon); } void ossimMapProjection::computeMetersPerPixel() { //#define USE_OSSIMGPT_METERS_PER_DEGREE #ifdef USE_OSSIMGPT_METERS_PER_DEGREE ossimDpt metersPerDegree (theOrigin.metersPerDegree()); theMetersPerPixel.x = metersPerDegree.x * theDegreesPerPixel.lon; theMetersPerPixel.y = metersPerDegree.y * theDegreesPerPixel.lat; #elif USE_MODEL_TRANSFORM_XXX // Not working so hide // Transform according to 4x4 transform embedded in the projection: const NEWMAT::Matrix& m = theModelTransform.getData(); theMetersPerPixel.x = sqrt(m[0][0]*m[0][0] + m[1][0]*m[1][0]); theMetersPerPixel.y = sqrt(m[0][1]*m[0][1] + m[1][1]*m[1][1]); #else ossimGpt right=theOrigin; ossimGpt down=theOrigin; down.latd(theOrigin.latd() + theDegreesPerPixel.lat); right.lond(theOrigin.lond() + theDegreesPerPixel.lon); ossimDpt centerMeters = forward(theOrigin); ossimDpt rightMeters = forward(right); ossimDpt downMeters = forward(down); theMetersPerPixel.x = (rightMeters - centerMeters).length(); theMetersPerPixel.y = (downMeters - centerMeters).length(); #endif } //************************************************************************************************** // METHOD: ossimMapProjection::operator== //! Compares this to arg projection and returns TRUE if the same. //! NOTE: As currently implemented in OSSIM, map projections also contain image geometry //! information like tiepoint and scale. This operator is only concerned with the map //! specification and ignores image geometry differences. //************************************************************************************************** bool ossimMapProjection::operator==(const ossimProjection& projection) const { // Verify that derived types match: if (getClassName() != projection.getClassName()) return false; // If both PCS codes are non-zero, that's all we need to check: // unless there are model transforms // const ossimMapProjection* mapProj = dynamic_cast(&projection); if(!mapProj) return false; if (thePcsCode && mapProj->thePcsCode && (thePcsCode != 32767) && (thePcsCode == mapProj->thePcsCode) ) { return true; } if ( *theDatum != *(mapProj->theDatum) ) return false; if (theOrigin != mapProj->theOrigin) return false; if (theFalseEastingNorthing != mapProj->theFalseEastingNorthing) return false; #if 0 THIS SECTION IGNORED SINCE IT DEALS WITH IMAGE GEOMETRY, NOT MAP PROJECTION if((theModelTransform.getData() != mapProj->theModelTransform.getData())) return false; #endif return true; } bool ossimMapProjection::isEqualTo(const ossimObject& obj, ossimCompareType compareType)const { const ossimMapProjection* mapProj = dynamic_cast(&obj); bool result = mapProj&&ossimProjection::isEqualTo(obj, compareType); if(result) { result = (theEllipsoid.isEqualTo(mapProj->theEllipsoid, compareType)&& theOrigin.isEqualTo(mapProj->theOrigin, compareType)&& theMetersPerPixel.isEqualTo(mapProj->theMetersPerPixel, compareType)&& theDegreesPerPixel.isEqualTo(mapProj->theDegreesPerPixel, compareType)&& theUlGpt.isEqualTo(mapProj->theUlGpt, compareType)&& theUlEastingNorthing.isEqualTo(mapProj->theUlEastingNorthing, compareType)&& theFalseEastingNorthing.isEqualTo(mapProj->theFalseEastingNorthing, compareType)&& (thePcsCode == mapProj->thePcsCode)&& (theElevationLookupFlag == mapProj->theElevationLookupFlag)&& (theModelTransform.isEqualTo(mapProj->theModelTransform))); if(result) { if(compareType == OSSIM_COMPARE_FULL) { if(theDatum&&mapProj->theDatum) { result = theDatum->isEqualTo(*mapProj->theDatum, compareType); } } else { result = (theDatum==mapProj->theDatum); } } } return result; } double ossimMapProjection::getFalseEasting() const { return theFalseEastingNorthing.x; } double ossimMapProjection::getFalseNorthing() const { return theFalseEastingNorthing.y; } double ossimMapProjection::getStandardParallel1() const { return 0.0; } double ossimMapProjection::getStandardParallel2() const { return 0.0; } void ossimMapProjection::snapTiePointTo(ossim_float64 multiple, ossimUnitType unitType) { ossim_float64 convertedMultiple = multiple; if (isGeographic() && (unitType != OSSIM_DEGREES) ) { // Convert to degrees. ossimUnitConversionTool convertor; convertor.setOrigin(theOrigin); convertor.setValue(multiple, unitType); convertedMultiple = convertor.getDegrees(); } else if ( !isGeographic() && (unitType != OSSIM_METERS) ) { // Convert to meters. ossimUnitConversionTool convertor; convertor.setOrigin(theOrigin); convertor.setValue(multiple, unitType); convertedMultiple = convertor.getMeters(); } // Convert the tie point. if (isGeographic()) { // Snap the latitude. ossim_float64 d = theUlGpt.latd(); d = ossim::round(d / convertedMultiple) * convertedMultiple; theUlGpt.latd(d); // Snap the longitude. d = theUlGpt.lond(); d = ossim::round(d / convertedMultiple) * convertedMultiple; theUlGpt.lond(d); // Adjust the stored easting / northing. theUlEastingNorthing = forward(theUlGpt); } else { // Snap the easting. ossim_float64 d = theUlEastingNorthing.x - getFalseEasting(); d = ossim::round(d / convertedMultiple) * convertedMultiple; theUlEastingNorthing.x = d + getFalseEasting(); // Snap the northing. d = theUlEastingNorthing.y - getFalseNorthing(); d = ossim::round(d / convertedMultiple) * convertedMultiple; theUlEastingNorthing.y = d + getFalseNorthing(); // Adjust the stored upper left ground point. theUlGpt = inverse(theUlEastingNorthing); } updateTransform(); } void ossimMapProjection::snapTiePointToOrigin() { // Convert the tie point. if (isGeographic()) { // Note the origin may not be 0.0, 0.0: // Snap the latitude. ossim_float64 d = theUlGpt.latd() - origin().latd(); d = ossim::round(d / theDegreesPerPixel.y) * theDegreesPerPixel.y; theUlGpt.latd(d + origin().latd()); // Snap the longitude. d = theUlGpt.lond() - origin().lond(); d = ossim::round(d / theDegreesPerPixel.x) * theDegreesPerPixel.x; theUlGpt.lond(d + origin().lond()); // Adjust the stored easting / northing. theUlEastingNorthing = forward(theUlGpt); } else { // Snap the easting. ossim_float64 d = theUlEastingNorthing.x - getFalseEasting(); d = ossim::round(d / theMetersPerPixel.x) * theMetersPerPixel.x; theUlEastingNorthing.x = d + getFalseEasting(); // Snap the northing. d = theUlEastingNorthing.y - getFalseNorthing(); d = ossim::round(d / theMetersPerPixel.y) * theMetersPerPixel.y; theUlEastingNorthing.y = d + getFalseNorthing(); // Adjust the stored upper left ground point. theUlGpt = inverse(theUlEastingNorthing); } updateTransform(); } void ossimMapProjection::setElevationLookupFlag(bool flag) { theElevationLookupFlag = flag; } bool ossimMapProjection::getElevationLookupFlag()const { return theElevationLookupFlag; } ossim-Miami-2.9.1/src/projection/ossimMapProjectionFactory.cpp000066400000000000000000000273321352751253100245460ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimMapProjectionFactory.cc // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains implementation of class ossimMapProjectionFactory // // SOFTWARE HISTORY: //> // 15Jun2001 Garrett Potts // Initial coding. //< //***************************************************************************** // $Id: ossimMapProjectionFactory.cpp 22602 2014-01-31 18:39:11Z gpotts $ #include #include #include #include #include //*** // Note to programmer: To add a new projection, search this file for // "ADD_PROJECTION" to locate places requiring editing. Functional example // below... // // ADD_PROJECTION: Include all map projection headers here: //*** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //*** // ADD_PROJECTION: List names of all map projections produced by this factory: //*** ossimMapProjectionFactory* ossimMapProjectionFactory::theInstance = 0; //***************************************************************************** // STATIC METHOD: ossimMapProjectionFactory::instance() // //***************************************************************************** ossimMapProjectionFactory* ossimMapProjectionFactory::instance() { if(!theInstance) { theInstance = new ossimMapProjectionFactory; } return (ossimMapProjectionFactory*) theInstance; } ossimProjection* ossimMapProjectionFactory::createProjection(const ossimFilename& filename, ossim_uint32 entryIdx)const { if(!filename.exists()) { return NULL; } // Check for external geometry file. ossimProjection* proj = createProjectionFromGeometryFile(filename, entryIdx); if (proj) { return proj; } ossimFilename geomFile = filename; geomFile = geomFile.setExtension("geom"); if(!geomFile.exists()) { return NULL; } ossimKeywordlist kwl; if(kwl.addFile(geomFile)) { return createProjection(kwl); } return NULL; } //***************************************************************************** // METHOD: ossimMapProjectionFactory::create(kwl, prefix) // //***************************************************************************** ossimProjection* ossimMapProjectionFactory::createProjection(const ossimKeywordlist &keywordList, const char *prefix) const { ossimProjection *result=NULL; const char *lookup = keywordList.find(prefix, ossimKeywordNames::TYPE_KW); const char *lookupSpaceImaging = keywordList.find(prefix, ossimSpaceImagingGeom::SIG_PRODUCER_KW); if(lookup) { result = createProjection(ossimString(lookup).trim()); if(result) { result->loadState(keywordList, prefix); } } else { if(lookupSpaceImaging) { ossimKeywordlist kwl; ossimKeywordlist kwl2; kwl.add(keywordList, prefix, true); ossimSpaceImagingGeom spaceImaging; spaceImaging.setGeometry(kwl); spaceImaging.exportToOssim(kwl2); result = ossimProjectionFactoryRegistry::instance()->createProjection(kwl2); if(result) { return result; } } // look for the geom_file keyword. // lookup = keywordList.find(prefix, ossimKeywordNames::GEOM_FILE_KW); if(lookup) { ossimKeywordlist kwl; kwl.addFile(lookup); result = createProjection(kwl); if(!result) { // maybe they prepend projection. in the geom // file. result = createProjection(kwl, "projection."); } } } return result; } //***************************************************************************** // METHOD: ossimMapProjectionFactory::create(projection_name) //***************************************************************************** ossimProjection* ossimMapProjectionFactory::createProjection(const ossimString &name) const { //*** // ADD_PROJECTION: Test for each map projection here: //*** if(name == STATIC_TYPE_NAME(ossimAlbersProjection)) return new ossimAlbersProjection; if(name == STATIC_TYPE_NAME(ossimAzimEquDistProjection)) return new ossimAzimEquDistProjection; if( name == STATIC_TYPE_NAME(ossimBonneProjection)) return new ossimBonneProjection; if( name == STATIC_TYPE_NAME(ossimBngProjection)) return new ossimBngProjection; if(name == STATIC_TYPE_NAME(ossimCassiniProjection)) return new ossimCassiniProjection; if(name == STATIC_TYPE_NAME(ossimCylEquAreaProjection)) return new ossimCylEquAreaProjection; if(name == STATIC_TYPE_NAME(ossimEquDistCylProjection)) return new ossimEquDistCylProjection; if(name == STATIC_TYPE_NAME(ossimEckert4Projection)) return new ossimEckert4Projection; if(name == STATIC_TYPE_NAME(ossimEckert6Projection)) return new ossimEckert6Projection; if(name == STATIC_TYPE_NAME(ossimGnomonicProjection)) return new ossimGnomonicProjection; if(name == STATIC_TYPE_NAME(ossimLambertConformalConicProjection)) return new ossimLambertConformalConicProjection; if(name == STATIC_TYPE_NAME(ossimLlxyProjection)) return new ossimLlxyProjection; if(name == STATIC_TYPE_NAME(ossimMercatorProjection)) return new ossimMercatorProjection; if(name == STATIC_TYPE_NAME(ossimMillerProjection)) return new ossimMillerProjection; if(name == STATIC_TYPE_NAME(ossimMollweidProjection)) return new ossimMollweidProjection; if(name == STATIC_TYPE_NAME(ossimNewZealandMapGridProjection)) return new ossimNewZealandMapGridProjection; if(name == STATIC_TYPE_NAME(ossimObliqueMercatorProjection)) return new ossimObliqueMercatorProjection; if(name == STATIC_TYPE_NAME(ossimOrthoGraphicProjection)) return new ossimOrthoGraphicProjection; if(name == STATIC_TYPE_NAME(ossimPolarStereoProjection)) return new ossimPolarStereoProjection; if(name == STATIC_TYPE_NAME(ossimPolyconicProjection)) return new ossimPolyconicProjection; if(name == STATIC_TYPE_NAME(ossimSinusoidalProjection)) return new ossimSinusoidalProjection; if(name == STATIC_TYPE_NAME(ossimStereographicProjection)) return new ossimStereographicProjection; if(name == STATIC_TYPE_NAME(ossimTransCylEquAreaProjection)) return new ossimTransCylEquAreaProjection; if(name == STATIC_TYPE_NAME(ossimTransMercatorProjection)) return new ossimTransMercatorProjection; if(name == STATIC_TYPE_NAME(ossimUpsProjection)) return new ossimUpsProjection; if(name == STATIC_TYPE_NAME(ossimUtmProjection)) return new ossimUtmProjection; if(name == STATIC_TYPE_NAME(ossimVanDerGrintenProjection)) return new ossimVanDerGrintenProjection; if(name == STATIC_TYPE_NAME(ossimSpaceObliqueMercatorProjection)) return new ossimSpaceObliqueMercatorProjection; if(name == STATIC_TYPE_NAME(ossimGoogleProjection)) return new ossimGoogleProjection; if(name == STATIC_TYPE_NAME(ossimAdjMapModel)) return new ossimAdjMapModel; return NULL; } ossimObject* ossimMapProjectionFactory::createObject(const ossimString& typeName)const { return createProjection(typeName); } ossimObject* ossimMapProjectionFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { return createProjection(kwl, prefix); } void ossimMapProjectionFactory::getTypeNameList(std::vector& typeList)const { typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimAlbersProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimAzimEquDistProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimBonneProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimBngProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimCassiniProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimCylEquAreaProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimEquDistCylProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimEckert4Projection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimEckert6Projection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimGnomonicProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimLambertConformalConicProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimLlxyProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimMercatorProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimMillerProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimMollweidProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimNewZealandMapGridProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimObliqueMercatorProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimOrthoGraphicProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimPolarStereoProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimPolyconicProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimSinusoidalProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimStereographicProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimTransCylEquAreaProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimTransMercatorProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimUpsProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimUtmProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimVanDerGrintenProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimSpaceObliqueMercatorProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimGoogleProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimAdjMapModel))); } ossim-Miami-2.9.1/src/projection/ossimMapProjectionInfo.cpp000066400000000000000000000346121352751253100240310ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2001 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // Class for encapsulate projection info given a projection, datum, and // output rectangle. // // NOTE: // - Output rectangle should be relative to the center of pixels. // Shifts will be made for "pixel is area" internally. // //******************************************************************* // $Id: ossimMapProjectionInfo.cpp 13025 2008-06-13 17:06:30Z sbortman $ #include #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include //*** // Static trace for debugging. //*** static ossimTrace traceDebug("ossimMapProjectionInfo::debug"); //*** // Keywords for getStateFrom/saveStateTo. //*** const char* ossimMapProjectionInfo::OUTPUT_US_FT_INFO_KW = "viewinfo.output_readme_in_us_ft_flag"; const char* ossimMapProjectionInfo::PIXEL_TYPE_KW = "viewinfo.pixel_type"; const char* ossimMapProjectionInfo::README_IMAGE_STRING_KW = "viewinfo.readme_image_string"; ossimMapProjectionInfo::ossimMapProjectionInfo(const ossimMapProjection* proj, const ossimDrect& output_rect) : theProjection (proj), theErrorStatus (false), theLinesPerImage (0), thePixelsPerLine (0), theCornerGroundPt (), theCornerEastingNorthingPt (), theCenterGroundPt (), theCenterEastingNorthingPt (0.0, 0.0), thePixelType (OSSIM_PIXEL_IS_POINT), theOutputInfoInFeetFlag (false), theImageInfoString () { if (!theProjection) { theErrorStatus = true; ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimMapProjectionInfo::ossimMapProjectionInfo: " << "Null projection pointer passed to constructor!" << "\nError status has been set. Returning..." << std::endl; return; } initializeMembers(output_rect); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimMapProjectionInfo::ossimMapProjectionInfo:\n" << "output_rect: " << output_rect << "\n" << *this << std::endl; } } ossimMapProjectionInfo::~ossimMapProjectionInfo() { } bool ossimMapProjectionInfo::errorStatus() const { return theErrorStatus; } void ossimMapProjectionInfo::initializeMembers(const ossimDrect& rect) { theBoundingRect = rect; theLinesPerImage = ossim::round(rect.height()); thePixelsPerLine = ossim::round(rect.width()); theProjection->lineSampleToWorld(rect.ul(), theCornerGroundPt[0]); theProjection->lineSampleToWorld(rect.ur(), theCornerGroundPt[1]); theProjection->lineSampleToWorld(rect.lr(), theCornerGroundPt[2]); theProjection->lineSampleToWorld(rect.ll(), theCornerGroundPt[3]); theProjection->lineSampleToEastingNorthing(rect.ul(), theCornerEastingNorthingPt[0]); theProjection->lineSampleToEastingNorthing(rect.ur(), theCornerEastingNorthingPt[1]); theProjection->lineSampleToEastingNorthing(rect.lr(), theCornerEastingNorthingPt[2]); theProjection->lineSampleToEastingNorthing(rect.ll(), theCornerEastingNorthingPt[3]); theCenterEastingNorthingPt.x = (theCornerEastingNorthingPt[0].x + theCornerEastingNorthingPt[1].x + theCornerEastingNorthingPt[2].x + theCornerEastingNorthingPt[3].x) / 4.0; theCenterEastingNorthingPt.y = (theCornerEastingNorthingPt[0].y + theCornerEastingNorthingPt[1].y + theCornerEastingNorthingPt[2].y + theCornerEastingNorthingPt[3].y) / 4.0; theCenterGroundPt = theProjection->inverse(theCenterEastingNorthingPt); } void ossimMapProjectionInfo::getGeom(ossimKeywordlist& kwl, const char* prefix)const { theProjection->saveState(kwl, prefix); if(theProjection->isGeographic()) { ossimGpt gpt = ulGroundPt(); kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, ossimDpt(gpt).toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES), true); } else { ossimDpt dpt = ulEastingNorthingPt(); kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, dpt.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true); } } std::ostream& ossimMapProjectionInfo::print(std::ostream& os) const { if (!os) { return os; } os << setiosflags(ios::left) << setiosflags(ios::fixed) << "ossimMapProjectionInfo Data Members:\n" << "Projection name: " << theProjection->getProjectionName() << setw(30) << "\nOutput pixel type:" << ((getPixelType() == OSSIM_PIXEL_IS_POINT) ? "pixel is point" : "pixel is area") << setw(30) << "\nMeters per pixel:" << getMetersPerPixel() << setw(30) << "\nUS survey feet per pixel:" << getUsSurveyFeetPerPixel() << setw(30) << "\nDecimal degrees per pixel:" << getDecimalDegreesPerPixel() << setw(30) << "\nNumber of lines:" << theLinesPerImage << setw(30) << "\nNumber of pixels:" << thePixelsPerLine << setw(30) << "\nUpper left ground point:" << theCornerGroundPt[0] << setw(30) << "\nUpper right ground point:" << theCornerGroundPt[1] << setw(30) << "\nLower right ground point:" << theCornerGroundPt[2] << setw(30) << "\nLower left ground point:" << theCornerGroundPt[3] << setw(30) << "\nUpper left easting_northing:" << theCornerEastingNorthingPt[0] << setw(30) << "\nUpper right easting_northing:" << theCornerEastingNorthingPt[1] << setw(30) << "\nLower right easting_northing:" << theCornerEastingNorthingPt[2] << setw(30) << "\nLower left easting_northing:" << theCornerEastingNorthingPt[3] << setw(30) << "\nCenter ground point:" << theCenterGroundPt << setw(30) << "\nCenter easting_northing:" << theCenterEastingNorthingPt << "\nMap Projection dump:"; theProjection->print(os); return os; } void ossimMapProjectionInfo::setPixelType (ossimPixelType type) { thePixelType = type; } ossimPixelType ossimMapProjectionInfo::getPixelType () const { return thePixelType; } void ossimMapProjectionInfo::setOutputFeetFlag (bool flag) { theOutputInfoInFeetFlag = flag; } bool ossimMapProjectionInfo::unitsInFeet() const { return theOutputInfoInFeetFlag; } ossimString ossimMapProjectionInfo::getImageInfoString () const { return theImageInfoString; } void ossimMapProjectionInfo::setImageInfoString (const ossimString& string) { theImageInfoString = string; } const ossimMapProjection* ossimMapProjectionInfo::getProjection() const { return theProjection; } ossimDpt ossimMapProjectionInfo::ulEastingNorthingPt( ) const { if (getPixelType() == OSSIM_PIXEL_IS_AREA) { ossimDpt mpp = getMetersPerPixel(); ossimDpt pt; pt.x = theCornerEastingNorthingPt[0].x - (mpp.x / 2.0); pt.y = theCornerEastingNorthingPt[0].y + (mpp.y / 2.0); return pt; } else { return theCornerEastingNorthingPt[0]; } } ossimDpt ossimMapProjectionInfo::urEastingNorthingPt( ) const { if (getPixelType() == OSSIM_PIXEL_IS_AREA) { ossimDpt mpp = getMetersPerPixel(); ossimDpt pt; pt.x = theCornerEastingNorthingPt[1].x + (mpp.x / 2.0); pt.y = theCornerEastingNorthingPt[1].y + (mpp.y / 2.0); return pt; } else { return theCornerEastingNorthingPt[1]; } } ossimDpt ossimMapProjectionInfo::lrEastingNorthingPt( ) const { if (getPixelType() == OSSIM_PIXEL_IS_AREA) { ossimDpt mpp = getMetersPerPixel(); ossimDpt pt; pt.x = theCornerEastingNorthingPt[2].x + (mpp.x / 2.0); pt.y = theCornerEastingNorthingPt[2].y - (mpp.y / 2.0); return pt; } else { return theCornerEastingNorthingPt[2]; } } ossimDpt ossimMapProjectionInfo::llEastingNorthingPt( ) const { if (getPixelType() == OSSIM_PIXEL_IS_AREA) { ossimDpt mpp = getMetersPerPixel(); ossimDpt pt; pt.x = theCornerEastingNorthingPt[3].x - (mpp.x / 2.0); pt.y = theCornerEastingNorthingPt[3].y - (mpp.y / 2.0); return pt; } else { return theCornerEastingNorthingPt[3]; } } ossimGpt ossimMapProjectionInfo::ulGroundPt( ) const { if (getPixelType() == OSSIM_PIXEL_IS_AREA) { ossimDpt ddpp = getDecimalDegreesPerPixel(); ossimGpt gpt; gpt.latd(theCornerGroundPt[0].latd() + (ddpp.y / 2.0)); gpt.lond(theCornerGroundPt[0].lond() - (ddpp.x / 2.0)); return gpt; } else { return theCornerGroundPt[0]; } } ossimGpt ossimMapProjectionInfo::urGroundPt( ) const { if (getPixelType() == OSSIM_PIXEL_IS_AREA) { ossimDpt ddpp = getDecimalDegreesPerPixel(); ossimGpt gpt; gpt.latd(theCornerGroundPt[1].latd() + (ddpp.y / 2.0)); gpt.lond(theCornerGroundPt[1].lond() + (ddpp.x / 2.0)); return gpt; } else { return theCornerGroundPt[1]; } } ossimGpt ossimMapProjectionInfo::lrGroundPt( ) const { if (getPixelType() == OSSIM_PIXEL_IS_AREA) { ossimDpt ddpp = getDecimalDegreesPerPixel(); ossimGpt gpt; gpt.latd(theCornerGroundPt[2].latd() - (ddpp.y / 2.0)); gpt.lond(theCornerGroundPt[2].lond() + (ddpp.x / 2.0)); return gpt; } else { return theCornerGroundPt[2]; } } ossimGpt ossimMapProjectionInfo::llGroundPt( ) const { if (getPixelType() == OSSIM_PIXEL_IS_AREA) { ossimDpt ddpp = getDecimalDegreesPerPixel(); ossimGpt gpt; gpt.latd(theCornerGroundPt[3].latd() - (ddpp.y / 2.0)); gpt.lond(theCornerGroundPt[3].lond() - (ddpp.x / 2.0)); return gpt; } else { return theCornerGroundPt[3]; } } ossimGpt ossimMapProjectionInfo::centerGroundPt( ) const { // Center is simply center, no shift for pixel is area... return theCenterGroundPt; } ossimDpt ossimMapProjectionInfo::centerEastingNorthingPt() const { return theCenterEastingNorthingPt; } ossim_int32 ossimMapProjectionInfo::linesPerImage() const { return theLinesPerImage; } ossim_int32 ossimMapProjectionInfo::pixelsPerLine() const { return thePixelsPerLine; } bool ossimMapProjectionInfo::loadState(const ossimKeywordlist& kwl, const char* ) { const char* lookupReturn = kwl.find(README_IMAGE_STRING_KW); //*** // "theImageInfoString" goes in the README file "Image:" field and can // be used to identify the image. //*** if (lookupReturn) theImageInfoString = lookupReturn; lookupReturn = kwl.find(ossimKeywordNames::PIXEL_TYPE_KW); if (lookupReturn) { ossimString tmp = lookupReturn; tmp.downcase(); if (tmp.contains("area")) { thePixelType = OSSIM_PIXEL_IS_AREA; } else { thePixelType = OSSIM_PIXEL_IS_POINT; } } lookupReturn = kwl.find(OUTPUT_US_FT_INFO_KW); if (lookupReturn) { int tmp = atoi(lookupReturn); if (tmp) { theOutputInfoInFeetFlag = true; } else { theOutputInfoInFeetFlag = false; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimMapProjectionInfo::loadState:" << "\ntheImageInfoString: " << theImageInfoString << "\nthePixelType: " << int(thePixelType) << "\ntheOutputInfoInFeetFlag: " << theOutputInfoInFeetFlag << endl; } return true; } bool ossimMapProjectionInfo::saveState(ossimKeywordlist& kwl, const char* ) const { kwl.add(README_IMAGE_STRING_KW, theImageInfoString.chars()); ossimString tmp; if (thePixelType == OSSIM_PIXEL_IS_POINT) { tmp = "point"; } else { tmp = "area"; } kwl.add(PIXEL_TYPE_KW, tmp.chars()); kwl.add(OUTPUT_US_FT_INFO_KW, int(theOutputInfoInFeetFlag)); return true; } ossimDpt ossimMapProjectionInfo::ulEastingNorthingPtInFt() const { ossimDpt pt = ulEastingNorthingPt(); pt.x = ossim::mtrs2usft(pt.x); pt.y = ossim::mtrs2usft(pt.y); return pt; } ossimDpt ossimMapProjectionInfo::urEastingNorthingPtInFt() const { ossimDpt pt = urEastingNorthingPt(); pt.x = ossim::mtrs2usft(pt.x); pt.y = ossim::mtrs2usft(pt.y); return pt; } ossimDpt ossimMapProjectionInfo::lrEastingNorthingPtInFt() const { ossimDpt pt = lrEastingNorthingPt(); pt.x = ossim::mtrs2usft(pt.x); pt.y = ossim::mtrs2usft(pt.y); return pt; } ossimDpt ossimMapProjectionInfo::llEastingNorthingPtInFt() const { ossimDpt pt = llEastingNorthingPt(); pt.x = ossim::mtrs2usft(pt.x); pt.y = ossim::mtrs2usft(pt.y); return pt; } ossimDpt ossimMapProjectionInfo::getMetersPerPixel() const { return theProjection->getMetersPerPixel(); } ossimDpt ossimMapProjectionInfo::getUsSurveyFeetPerPixel() const { ossimDpt pt = getMetersPerPixel(); pt.x = ossim::mtrs2usft(pt.x); pt.y = ossim::mtrs2usft(pt.y); return pt; } ossimDpt ossimMapProjectionInfo::getDecimalDegreesPerPixel() const { return theProjection->getDecimalDegreesPerPixel(); } ossim-Miami-2.9.1/src/projection/ossimMapViewController.cpp000066400000000000000000000120631352751253100240530ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // //************************************************************************* // $Id: ossimMapViewController.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimMapViewController, "ossimMapViewController", ossimViewController); ossimMapViewController::ossimMapViewController() :ossimViewController() { } ossimMapViewController::ossimMapViewController(ossimObject* owner, ossim_uint32 inputListSize, ossim_uint32 outputListSize, bool inputListFixedFlag, bool outputListFixedFlag) :ossimViewController(owner, inputListSize, outputListSize, inputListFixedFlag, outputListFixedFlag) { if(theOwner) { const ossimObject* obj = findFirstViewOfType(STATIC_TYPE_INFO(ossimMapProjection)); ossimMapProjection* proj = PTR_CAST(ossimMapProjection, obj); if(proj) { // we are initialized to the first view. theView = proj->dup(); } else { // initialize the controller to true geographic theView = new ossimEquDistCylProjection; } } else { // initialize the controller to true geographic theView = new ossimEquDistCylProjection; } } ossimMapViewController::~ossimMapViewController() { } bool ossimMapViewController::setView(ossimObject* object) { if(PTR_CAST(ossimMapProjection, object)) { return ossimViewController::setView(object); } return false; } void ossimMapViewController::changeOwner(ossimObject* owner) { ossimConnectableObject::changeOwner(owner); if(!theView) { // initialize the controller to geographic const ossimObject* obj = findFirstViewOfType(STATIC_TYPE_INFO(ossimMapProjection)); ossimMapProjection* proj = PTR_CAST(ossimMapProjection, obj); if(proj) { // we are initialized to the first view. setView(proj->dup()); propagateView(); } else { // initialize the controller to true geographic setView(new ossimEquDistCylProjection); propagateView(); } } else { propagateView(); } } void ossimMapViewController::setFilename(const ossimFilename& file) { if(file.exists()) { ossimKeywordlist kwl; kwl.addFile(file.c_str()); ossimRefPtr proj = ossimProjectionFactoryRegistry::instance()->createProjection(kwl); if(dynamic_cast(proj.get())) { setView(proj.get()); } } theGeometryFile = file; } bool ossimMapViewController::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimSource::saveState(kwl, prefix); ossimMapProjection* proj = PTR_CAST(ossimMapProjection, getView()); ossimString newPrefix = prefix; newPrefix += "projection."; if(proj) { if(theGeometryFile == "") { proj->saveState(kwl, newPrefix.c_str()); } else { ofstream output(theGeometryFile.c_str()); if(output) { kwl.add(prefix, ossimKeywordNames::FILENAME_KW, theGeometryFile); ossimKeywordlist kwl2; proj->saveState(kwl2); kwl2.writeToStream(output); } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimMapViewController::saveState can't open filename " << theGeometryFile << "\nsaving inline to passed in keywordlist" << std::endl; proj->saveState(kwl, newPrefix); } } } return true; } bool ossimMapViewController::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimSource::loadState(kwl, prefix); theGeometryFile = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); ossimRefPtr proj; if(theGeometryFile == "") { ossimString newPrefix = prefix; newPrefix += "projection."; proj = ossimProjectionFactoryRegistry::instance()->createProjection(kwl, newPrefix.c_str()); } else { ossimKeywordlist kwl2; kwl2.addFile(theGeometryFile); proj = ossimProjectionFactoryRegistry::instance()->createProjection(kwl2); } if(dynamic_cast(proj.get())) { setView(proj.get()); } return true; } ossim-Miami-2.9.1/src/projection/ossimMeanRadialLensDistortion.cpp000066400000000000000000000127331352751253100253410ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // MeanRadialLens distortion. //******************************************************************* // $Id: ossimMeanRadialLensDistortion.cpp 15929 2009-11-16 18:20:46Z gpotts $ #include #include #include #include RTTI_DEF1(ossimMeanRadialLensDistortion, "ossimMeanRadialLensDistortion", ossimLensDistortion); void ossimMeanRadialLensDistortion::solveCoefficients(const std::vector& radialDistance, const std::vector& radialDistortion) { NEWMAT::ColumnVector distanceVec((int)radialDistance.size()); NEWMAT::ColumnVector distortionVec((int)radialDistortion.size()); ossim_uint32 idx = 0; theCoefficients[0] = 0; theCoefficients[1] = 0; theCoefficients[2] = 0; theCoefficients[3] = 0; if(radialDistance.size() == radialDistortion.size()) { for(idx = 0; idx < radialDistance.size();++idx) { distanceVec[idx] = radialDistance[idx]; distortionVec[idx] = radialDistortion[idx]; } solveCoefficients(distanceVec, distortionVec); } } void ossimMeanRadialLensDistortion::solveCoefficients(const NEWMAT::ColumnVector &radialDistance, const NEWMAT::ColumnVector &radialDistortion) { NEWMAT::ColumnVector coefficients(4); theCoefficients.resize(4); theCoefficients[0] = 0; theCoefficients[1] = 0; theCoefficients[2] = 0; theCoefficients[3] = 0; if((radialDistance.Nrows() == 0) || (radialDistortion.Nrows() == 0)) { return; } if(radialDistance.Nrows() == radialDistortion.Nrows()) { NEWMAT::Matrix M(radialDistance.Nrows(), 4); // set up the matrix for(long row = 0; row < M.Nrows(); row++) { M[row][0] = radialDistance[row]; M[row][1] = M[row][0]*radialDistance[row]*radialDistance[row]; M[row][2] = M[row][1]*radialDistance[row]*radialDistance[row]; M[row][3] = M[row][2]*radialDistance[row]*radialDistance[row]; } NEWMAT::Matrix mTranspose = M.t(); coefficients = ((mTranspose*M).i())*(mTranspose*radialDistortion); theCoefficients[0] = coefficients[0]; theCoefficients[1] = coefficients[1]; theCoefficients[2] = coefficients[2]; theCoefficients[3] = coefficients[3]; } else { } } double ossimMeanRadialLensDistortion::deltaR(double radius)const { double r3 = radius*radius*radius; double r5 = r3*radius*radius; double r7 = r5*radius*radius; return (radius*theCoefficients[0] +r3*theCoefficients[1] + r5*theCoefficients[2] + r7*theCoefficients[3]); } void ossimMeanRadialLensDistortion::undistort(const ossimDpt& input, ossimDpt& output)const { ossimDpt deltaPosition(input.x - theCenter.x, input.y - theCenter.y); double r = sqrt(deltaPosition.x*deltaPosition.x + deltaPosition.y*deltaPosition.y); double deltaRadius = deltaR(r); if((fabs(r) <= FLT_EPSILON)|| (fabs(deltaRadius) <= FLT_EPSILON)) { output = input; return; } double deltaX = (deltaPosition.x*(deltaRadius/r)); double deltaY = (deltaPosition.y*(deltaRadius/r)); output.x = deltaPosition.x-deltaX; output.y = deltaPosition.y-deltaY; } bool ossimMeanRadialLensDistortion::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "k0", theCoefficients[0], true); kwl.add(prefix, "k1", theCoefficients[1], true); kwl.add(prefix, "k2", theCoefficients[2], true); kwl.add(prefix, "k3", theCoefficients[3], true); return ossimLensDistortion::saveState(kwl, prefix); } bool ossimMeanRadialLensDistortion::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* k0 = kwl.find(prefix, "k0"); const char* k1 = kwl.find(prefix, "k1"); const char* k2 = kwl.find(prefix, "k2"); const char* k3 = kwl.find(prefix, "k3"); if(k1&&k2&&k3&&k3) { theCoefficients[0] = ossimString(k0).toDouble(); theCoefficients[1] = ossimString(k1).toDouble(); theCoefficients[2] = ossimString(k2).toDouble(); theCoefficients[3] = ossimString(k3).toDouble(); } else { std::vector distances; std::vector distortions; ossim_uint32 idx = 0; const char* distance = kwl.find(prefix, "distance0"); const char* distortion = kwl.find(prefix, "distortion0"); while(distance&&distortion) { distances.push_back(ossimString(distance).toDouble()); distortions.push_back(ossimString(distortion).toDouble()); ++idx; distance = kwl.find(prefix, ossimString("distance")+ossimString::toString(idx)); distortion = kwl.find(prefix, ossimString("distortion")+ossimString::toString(idx)); } solveCoefficients(distances, distortions); } return ossimLensDistortion::loadState(kwl, prefix); } ossim-Miami-2.9.1/src/projection/ossimMercatorProjection.cpp000066400000000000000000000437751352751253100242660ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Mercator projection code. //******************************************************************* // $Id: ossimMercatorProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include RTTI_DEF1(ossimMercatorProjection, "ossimMercatorProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #define PI 3.14159265358979323e0 /* PI */ #define PI_OVER_2 ( PI / 2.0e0) //#define MAX_LAT ( (PI * 89.5) / 180.0 ) /* 89.5 degrees in radians */ #define MAX_LAT ( (PI * 89.99) / 180.0 ) /* 89.99 degrees in radians */ #define MERC_NO_ERROR 0x0000 #define MERC_LAT_ERROR 0x0001 #define MERC_LON_ERROR 0x0002 #define MERC_EASTING_ERROR 0x0004 #define MERC_NORTHING_ERROR 0x0008 #define MERC_ORIGIN_LAT_ERROR 0x0010 #define MERC_CENT_MER_ERROR 0x0020 #define MERC_A_ERROR 0x0040 #define MERC_B_ERROR 0x0080 #define MERC_A_LESS_B_ERROR 0x0100 ossimMercatorProjection::ossimMercatorProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimMercatorProjection::ossimMercatorProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing, double scaleFactor) :ossimMapProjection(ellipsoid, origin) { setDefaults(); Merc_False_Easting = falseEasting; Merc_False_Northing = falseNorthing; Merc_Scale_Factor = scaleFactor; update(); } void ossimMercatorProjection::update() { Set_Mercator_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Merc_False_Easting, Merc_False_Northing, &Merc_Scale_Factor); theFalseEastingNorthing.x = Merc_False_Easting; theFalseEastingNorthing.y = Merc_False_Northing; ossimMapProjection::update(); } void ossimMercatorProjection::setFalseEasting(double falseEasting) { Merc_False_Easting = falseEasting; update(); } void ossimMercatorProjection::setFalseNorthing(double falseNorthing) { Merc_False_Northing = falseNorthing; update(); } void ossimMercatorProjection::setScaleFactor(double scaleFactor) { Merc_Scale_Factor = scaleFactor; update(); } void ossimMercatorProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Merc_False_Easting = falseEasting; Merc_False_Northing = falseNorthing; update(); } void ossimMercatorProjection::setParameters(double falseEasting, double falseNorthing, double scaleFactor) { Merc_False_Easting = falseEasting; Merc_False_Northing = falseNorthing; Merc_Scale_Factor = scaleFactor; update(); } void ossimMercatorProjection::setDefaults() { Merc_False_Easting = 0.0; Merc_False_Northing = 0.0; Merc_Delta_Easting = 20237883.0; Merc_Delta_Northing = 23421740.0; Merc_Scale_Factor = 1.0; } ossimGpt ossimMercatorProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; if(theSphericalFlag) { double shift = M_PI * 6378137.0; lon = (eastingNorthing.x / shift) * 180.0; lat = (eastingNorthing.y / shift) * 180.0; lat = 180 / M_PI * (2 * atan( exp( lat * M_PI / 180.0)) - M_PI / 2.0); } else { Convert_Mercator_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); lat = ossim::radiansToDegrees(lat); lon = ossim::radiansToDegrees(lon); } return ossimGpt(lat, lon, 0.0, theDatum); } ossimDpt ossimMercatorProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; ossimDpt result; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } if(theSphericalFlag) { double lat = latLon.latd(); double lon = latLon.lond(); double shift = M_PI * Merc_a; easting = lon * shift / 180.0; northing = log( tan((90 + lat) * M_PI / 360.0 )) / (M_PI / 180.0); northing = northing * shift / 180.0; result = ossimDpt(easting, northing); } else { long errorCode = Convert_Geodetic_To_Mercator(gpt.latr(), gpt.lonr(), &easting, &northing); if(errorCode!=MERC_NO_ERROR) { result.makeNan(); } else { result = ossimDpt(easting, northing); } } return result; } bool ossimMercatorProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, ossimKeywordNames::SCALE_FACTOR_KW, Merc_Scale_Factor, true); return ossimMapProjection::saveState(kwl, prefix); } bool ossimMercatorProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); const char* scaleFactor = kwl.find(prefix, ossimKeywordNames::SCALE_FACTOR_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimMercatorProjection)) { Merc_False_Easting = theFalseEastingNorthing.x; Merc_False_Northing = theFalseEastingNorthing.y; if(scaleFactor) { Merc_Scale_Factor = ossimString(scaleFactor).toDouble(); } } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimMercatorProjection::Set_Mercator_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing, double *Scale_Factor) { /* BEGIN Set_Mercator_Parameters */ /* * The function Set_Mercator_Parameters receives the ellipsoid parameters and * Mercator projection parameters as inputs, and sets the corresponding state * variables. It calculates and returns the scale factor. If any errors * occur, the error code(s) are returned by the function, otherwise Merc_NO_ERROR * is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) * Scale_Factor : Multiplier which reduces distances in the * projection to the actual distance on the * ellipsoid (output) */ double es2; /* Eccentricity squared of ellipsoid to the second power */ double es3; /* Eccentricity squared of ellipsoid to the third power */ double es4; /* Eccentricity squared of ellipsoid to the fourth power */ double sin_olat; /* sin(Origin_Latitude), temp variable */ // double inv_f = 1 / f; long Error_Code = MERC_NO_ERROR; theSphericalFlag = ossim::almostEqual(f, 0.0); // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= MERC_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= MERC_INV_F_ERROR; // } // if ((Origin_Latitude < -MAX_LAT) || (Origin_Latitude > MAX_LAT)) // { /* origin latitude out of range */ // Error_Code |= MERC_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > (2*PI))) // { /* origin longitude out of range */ // Error_Code |= MERC_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Merc_a = a; Merc_f = f; Merc_Origin_Lat = Origin_Latitude; // if (Central_Meridian > PI) // Central_Meridian -= (2*PI); Merc_Origin_Long = Central_Meridian; Merc_False_Northing = False_Northing; Merc_False_Easting = False_Easting; Merc_es = 2 * Merc_f - Merc_f * Merc_f; Merc_e = sqrt(Merc_es); sin_olat = sin(Origin_Latitude); Merc_Scale_Factor = 1.0 / ( sqrt(1.e0 - Merc_es * sin_olat * sin_olat) / cos(Origin_Latitude) ); es2 = Merc_es * Merc_es; es3 = es2 * Merc_es; es4 = es3 * Merc_es; Merc_ab = Merc_es / 2.e0 + 5.e0 * es2 / 24.e0 + es3 / 12.e0 + 13.e0 * es4 / 360.e0; Merc_bb = 7.e0 * es2 / 48.e0 + 29.e0 * es3 / 240.e0 + 811.e0 * es4 / 11520.e0; Merc_cb = 7.e0 * es3 / 120.e0 + 81.e0 * es4 / 1120.e0; Merc_db = 4279.e0 * es4 / 161280.e0; *Scale_Factor = Merc_Scale_Factor; Convert_Geodetic_To_Mercator( MAX_LAT, (Merc_Origin_Long + PI), &Merc_Delta_Easting, &Merc_Delta_Northing); if (Merc_Delta_Easting < 0) Merc_Delta_Easting = -Merc_Delta_Easting; Merc_Delta_Easting *= 1.01; Merc_Delta_Easting -= Merc_False_Easting; Merc_Delta_Northing *= 1.01; Merc_Delta_Northing -= Merc_False_Northing; } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Set_Mercator_Parameters */ void ossimMercatorProjection::Get_Mercator_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing, double *Scale_Factor)const { /* BEGIN Get_Mercator_Parameters */ /* * The function Get_Mercator_Parameters returns the current ellipsoid * parameters, Mercator projection parameters, and scale factor. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) * Scale_Factor : Multiplier which reduces distances in the * projection to the actual distance on the * ellipsoid (output) */ *a = Merc_a; *f = Merc_f; *Origin_Latitude = Merc_Origin_Lat; *Central_Meridian = Merc_Origin_Long; *False_Easting = Merc_False_Easting; *False_Northing = Merc_False_Northing; *Scale_Factor = Merc_Scale_Factor; return; } /* END OF Get_Mercator_Parameters */ long ossimMercatorProjection::Convert_Geodetic_To_Mercator (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Mercator */ long Error_Code = MERC_NO_ERROR; /* * The function Convert_Geodetic_To_Mercator converts geodetic (latitude and * longitude) coordinates to Mercator projection (easting and northing) * coordinates, according to the current ellipsoid and Mercator projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise MERC_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double ctanz2; /* Cotangent of z/2 - z - Isometric colatitude */ double e_x_sinlat; /* e * sin(Latitude) */ double Delta_Long; /* Difference in origin longitude and longitude */ double tan_temp; double pow_temp; if ((Latitude < -MAX_LAT) || (Latitude > MAX_LAT)) { /* Latitude out of range */ Error_Code |= MERC_LAT_ERROR; } // if ((Longitude < -PI) || (Longitude > (2*PI))) // { /* Longitude out of range */ // Error_Code |= MERC_LON_ERROR; // } if (!Error_Code) { /* no errors */ if (Longitude > PI) Longitude -= (2*PI); e_x_sinlat = Merc_e * sin(Latitude); tan_temp = tan(PI / 4.e0 + Latitude / 2.e0); pow_temp = pow( ((1.e0 - e_x_sinlat) / (1.e0 + e_x_sinlat)), (Merc_e / 2.e0) ); ctanz2 = tan_temp * pow_temp; *Northing = Merc_Scale_Factor * Merc_a * log(ctanz2) + Merc_False_Northing; Delta_Long = Longitude - Merc_Origin_Long; // if (Delta_Long > PI) // Delta_Long -= (2 * PI); // if (Delta_Long < -PI) // Delta_Long += (2 * PI); *Easting = Merc_Scale_Factor * Merc_a * Delta_Long + Merc_False_Easting; } return (Error_Code); } /* END OF Convert_Geodetic_To_Mercator */ long ossimMercatorProjection::Convert_Mercator_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Mercator_To_Geodetic */ /* * The function Convert_Mercator_To_Geodetic converts Mercator projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Mercator projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise MERC_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx; /* Delta easting - Difference in easting (easting-FE) */ double dy; /* Delta northing - Difference in northing (northing-FN) */ double xphi; /* Isometric latitude */ long Error_Code = MERC_NO_ERROR; #if 0 if(theSphericalFlag) { *Latitude = M_PI*.5 - 2.0 * atan(exp(-Easting / Merc_a)); *Longitude = Easting/Merc_a; return Error_Code; } #endif // if ((Easting < (Merc_False_Easting - Merc_Delta_Easting)) // || (Easting > (Merc_False_Easting + Merc_Delta_Easting))) // { /* Easting out of range */ // Error_Code |= MERC_EASTING_ERROR; // } // if ((Northing < (Merc_False_Northing - Merc_Delta_Northing)) // || (Northing > (Merc_False_Northing + Merc_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= MERC_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ dy = Northing - Merc_False_Northing; dx = Easting - Merc_False_Easting; *Longitude = Merc_Origin_Long + dx / (Merc_Scale_Factor * Merc_a); xphi = PI / 2.e0 - 2.e0 * atan(1.e0 / exp(dy / (Merc_Scale_Factor * Merc_a))); *Latitude = xphi + Merc_ab * sin(2.e0 * xphi) + Merc_bb * sin(4.e0 * xphi) + Merc_cb * sin(6.e0 * xphi) + Merc_db * sin(8.e0 * xphi); // if (*Longitude > PI) // *Longitude -= (2 * PI); // if (*Longitude < -PI) // *Longitude += (2 * PI); } return (Error_Code); } /* END OF Convert_Mercator_To_Geodetic */ //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimMercatorProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimMercatorProjection* p = dynamic_cast(&proj); if (!p) return false; if (!ossim::almostEqual(Merc_Scale_Factor,p->Merc_Scale_Factor)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimMgrs.c000066400000000000000000001255011352751253100210110ustar00rootroot00000000000000/***************************************************************************/ /* RSC IDENTIFIER: MGRS * * ABSTRACT * * This component converts between geodetic coordinates (latitude and * longitude) and Military Grid Reference System (MGRS) coordinates. * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid value * is found, the error code is combined with the current error code using * the bitwise or. This combining allows multiple error codes to be * returned. The possible error codes are: * * MGRS_NO_ERROR : No errors occurred in function * MGRS_LAT_ERROR : Latitude outside of valid range * (-90 to 90 degrees) * MGRS_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees) * MGRS_STR_ERROR : An MGRS string error: string too long, * too short, or badly formed * MGRS_PRECISION_ERROR : The precision must be between 0 and 5 * inclusive. * MGRS_A_ERROR : Semi-major axis less than or equal to zero * MGRS_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * MGRS_EASTING_ERROR : Easting outside of valid range * (100,000 to 900,000 meters for UTM) * (0 to 4,000,000 meters for UPS) * MGRS_NORTHING_ERROR : Northing outside of valid range * (0 to 10,000,000 meters for UTM) * (0 to 4,000,000 meters for UPS) * MGRS_ZONE_ERROR : Zone outside of valid range (1 to 60) * MGRS_HEMISPHERE_ERROR : Invalid hemisphere ('N' or 'S') * * REUSE NOTES * * MGRS is intended for reuse by any application that does conversions * between geodetic coordinates and MGRS coordinates. * * REFERENCES * * Further information on MGRS can be found in the Reuse Manual. * * MGRS originated from : U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * * ENVIRONMENT * * MGRS was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC version 2.8.1 * 2. Windows 95 with MS Visual C++ version 6 * * MODIFICATIONS * * Date Description * ---- ----------- * 16-11-94 Original Code * 15-09-99 Reengineered upper layers * */ /***************************************************************************/ /* * INCLUDES */ #include #include #include #include #include #include #include /* * ctype.h - Standard C character handling library * math.h - Standard C math library * stdio.h - Standard C input/output library * string.h - Standard C string handling library * ups.h - Universal Polar Stereographic (UPS) projection * utm.h - Universal Transverse Mercator (UTM) projection * mgrs.h - function prototype error checking */ /***************************************************************************/ /* * GLOBAL DECLARATIONS */ #define DEGRAD 0.017453292519943295 /* PI/180 */ #define R3 0.052359877559829890 /* RADIANS FOR 3 DEGREES */ #define R8 0.139626340159546400 /* RADIANS FOR 8 DEGREES */ #define R9 0.157079632679489700 /* RADIANS FOR 9 DEGREES */ #define R21 0.366519142918809200 /* RADIANS FOR 21 DEGREES */ #define R33 0.575958653158128800 /* RADIANS FOR 33 DEGREES */ #define R56 0.977384381116824600 /* RADIANS FOR 56 DEGREES */ #define R64 1.117010721276371000 /* RADIANS FOR 64 DEGREES */ #define R72 1.256637061435917000 /* RADIANS FOR 72 DEGREES */ #define R80 1.396263401595464000 /* RADIANS FOR 80 DEGREES */ #define UPS_SOUTH 3 /* UPS COORDINATE IN SOUTHERN HEMISPHERE */ #define UPS_NORTH 2 /* UPS COORDINATE IN NORTHERN HEMISPHERE */ #define UTM 1 /* UTM COORDINATE */ #define ALBET "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* ALPHABET */ #define LETTER_A 0 /* ARRAY INDEX FOR LETTER A */ #define LETTER_B 1 /* ARRAY INDEX FOR LETTER B */ #define LETTER_C 2 /* ARRAY INDEX FOR LETTER C */ #define LETTER_D 3 /* ARRAY INDEX FOR LETTER D */ #define LETTER_E 4 /* ARRAY INDEX FOR LETTER E */ #define LETTER_H 7 /* ARRAY INDEX FOR LETTER H */ #define LETTER_I 8 /* ARRAY INDEX FOR LETTER I */ #define LETTER_J 9 /* ARRAY INDEX FOR LETTER J */ #define LETTER_L 11 /* ARRAY INDEX FOR LETTER L */ #define LETTER_M 12 /* ARRAY INDEX FOR LETTER M */ #define LETTER_N 13 /* ARRAY INDEX FOR LETTER N */ #define LETTER_O 14 /* ARRAY INDEX FOR LETTER O */ #define LETTER_P 15 /* ARRAY INDEX FOR LETTER P */ #define LETTER_Q 16 /* ARRAY INDEX FOR LETTER Q */ #define LETTER_R 17 /* ARRAY INDEX FOR LETTER R */ #define LETTER_S 18 /* ARRAY INDEX FOR LETTER S */ #define LETTER_U 20 /* ARRAY INDEX FOR LETTER U */ #define LETTER_V 21 /* ARRAY INDEX FOR LETTER V */ #define LETTER_W 22 /* ARRAY INDEX FOR LETTER W */ #define LETTER_X 23 /* ARRAY INDEX FOR LETTER X */ #define LETTER_Y 24 /* ARRAY INDEX FOR LETTER Y */ #define LETTER_Z 25 /* ARRAY INDEX FOR LETTER Z */ #define RND1 0.1e0 /* ROUND TO NEAREST .1 */ #define RND5 0.5e0 /* ROUND TO NEAREST .5 */ #define EOLN '\0' /* END OF STRING CHARACTER */ #define BLANK ' ' /* BLANK CHARACTER */ #define OSSIM_MGRS_LETTERS 3 /* NUMBER OF LETTERS IN MGRS */ #define NUM_OFFSET 48 /* USED TO CONVERT NUMBERS TO LETTERS */ #define ONEHT 100000.e0 /* ONE HUNDRED THOUSAND */ #define TWOMIL 2000000.e0 /* TWO MILLION */ #define EIGHT 800000.e0 /* EIGHT HUNDRED THOUSAND */ #define ONE3HT 1300000.e0 /* ONE MILLION THREE HUNDRED THOUSAND */ #define ZERO 0.e0 /* ZERO */ #define TEN 10.e0 /* TEN */ #define TRUE 1 /* CONSTANT VALUE FOR TRUE VALUE */ #define FALSE 0 /* CONSTANT VALUE FOR FALSE VALUE */ #define PI 3.14159265358979323e0 /* PI */ #define PI_OVER_2 (PI / 2.0e0) #define NUM "01234567890" /* NUMBERS */ #define MAXALBET 25 /* LAST INDEX IN ALPHABET ARRAY(0-25) */ #define MAXNUMBER 10 /* LAST INDEX IN NUMBER ARRAY(0-9) */ #define OSSIM_MGRS_ZONE_AND_LETTERS 5 /* NUM. OF CHARS. IN ZONE AND LETTERS */ #define OSSIM_MGRS_MINIMUM 9 /* MINIMUM NUMBER OF CHARS FOR MGRS */ #define OSSIM_MGRS_MAXIMUM 15 /* MAXIMUM NUMBER OF CHARS FOR MGRS */ #define MIN_EASTING 100000 #define MAX_EASTING 900000 #define MIN_NORTHING 0 #define MAX_NORTHING 10000000 #define MAX_PRECISION 5 /* Maximum precision of easting & northing */ #define MIN_UTM_LAT ( (-80 * PI) / 180.0 ) /* -80 degrees in radians */ #define MAX_UTM_LAT ( (84 * PI) / 180.0 ) /* 84 degrees in radians */ #define MIN_EAST_NORTH 0 #define MAX_EAST_NORTH 4000000 /* Ellipsoid parameters, default to WGS 84 */ double OSSIM_MGRS_a = 6378137.0; /* Semi-major axis of ellipsoid in meters */ double OSSIM_MGRS_f = 1 / 298.257223563; /* Flattening of ellipsoid */ double OSSIM_MGRS_recpf = 298.257223563; char OSSIM_MGRS_Ellipsoid_Code[3] = {'W','E',0}; const char* OSSIM_CLARKE_1866 = "CC"; const char* OSSIM_CLARKE_1880 = "CD"; const char* OSSIM_BESSEL_1841 = "BR"; /* * OSSIM_CLARKE_1866 : Ellipsoid code for OSSIM_CLARKE_1866 * OSSIM_CLARKE_1880 : Ellipsoid code for OSSIM_CLARKE_1880 * OSSIM_BESSEL_1841 : Ellipsoid code for OSSIM_BESSEL_1841 */ /***************************************************************************/ /* * FUNCTIONS */ void UTMSET (long izone, long* ltrlow, long* ltrhi, double *fnltr) { /* BEGIN UTMSET */ /* * izone : Zone number * ltrlow : 2nd letter low number * ltrhi : 2nd letter high number * fnltr : False northing */ long iset; /* Set number (1-6) based on UTM zone number */ long igroup; /* Group number (1-2) based on ellipsoid code and zone */ iset = 1; while (((izone-iset) / 6) * 6 + iset != izone) { iset = iset +1; if (iset > 6) { return; } } igroup = 1; if (!strcmp(OSSIM_MGRS_Ellipsoid_Code,OSSIM_CLARKE_1866) || !strcmp(OSSIM_MGRS_Ellipsoid_Code, OSSIM_CLARKE_1880) || !strcmp(OSSIM_MGRS_Ellipsoid_Code,OSSIM_BESSEL_1841)) { igroup = 2; } else if (!strcmp(OSSIM_MGRS_Ellipsoid_Code, OSSIM_CLARKE_1866) && (izone >= 47) && (izone <= 55 )) { igroup = 1; } if ((iset == 1) || (iset == 4)) { *ltrlow = LETTER_A; *ltrhi = LETTER_H; } else if ((iset == 2) || (iset == 5)) { *ltrlow = LETTER_J; *ltrhi = LETTER_R; } else if ((iset == 3) || (iset == 6)) { *ltrlow = LETTER_S; *ltrhi = LETTER_Z; } if (igroup == 1) { *fnltr = ZERO; if ((iset % 2) == 0) { *fnltr = 1500000.e0; } } else if (igroup == 2) { *fnltr = 1000000.0e0; if ((iset % 2) == 0) { *fnltr = 500000.e0; } } return; } /* END OF UTMSET */ void UTMLIM (long* n, double sphi, long izone, double *spsou, double *spnor, double *sleast, double *slwest) { /* BEGIN UTMLIM */ /* * n : 1st letter number for MGRS * sphi : Latitude in radians * izone : Zone number * spsou : South latitude limit * spnor : North latitude limit * sleast : East longitude limit * slwest : West longitude limit */ double slcm; /* Central meridian - Longitude of origin */ double temp; /* Temporary variable */ long icm; /* Central meridian */ long isphi; /* South latitude limit */ if (*n <= LETTER_A) { temp = ((sphi + R80) / (R8)) + 2; temp = temp + .00000001; *n = (long)temp; if (*n > LETTER_H) { *n = *n + 1; } if (*n > LETTER_N) { *n = *n + 1; } if (*n >= LETTER_Y) { *n = LETTER_X; } if ((*n == LETTER_M) && (sphi == ZERO )) { *n = LETTER_N; } isphi = (*n - 3) * 8 - 80; } else { isphi = (*n - 3) * 8 - 80; *n = *n - 1; } if (*n > LETTER_H) { isphi = isphi - 8; } if (*n > LETTER_N) { isphi = isphi - 8; } *spsou = (double)(isphi) * DEGRAD; *spnor = *spsou + R8; if (*n == LETTER_X) { *spnor = *spsou + 12.e0 * DEGRAD; } icm = izone * 6 - 183; slcm = (double) icm * DEGRAD; *sleast = slcm + R3; *slwest = slcm - R3; if ((izone < 31) || (izone > 37)) { return; } if (*n < LETTER_V) { return; } if ((*n == LETTER_V) && (izone == 31)) { *sleast = R3; } if ((*n == LETTER_V) && (izone == 32)) { *slwest = R3; } if (*n < LETTER_X) { return; } if (izone == 31) { *sleast = R9; } if (izone == 33) { *slwest = R9; *sleast = R21; } if (izone == 35) { *slwest = R21; *sleast = R33; } if (izone == 37) { *slwest = R33; } return; } /* END OF UTMLIM */ void UTMOSSIM_MGRS (long izone, long* ltrnum, double sphi, double x, double y) { /* BEGIN UTMMGRS */ /* * izone : Zone number. * ltrnum : Values of letters in the MGRS coordinate. * sphi : Latitude in radians. * x : Easting. * y : Northing. * * UTMMGRS CALLS THE FOLLOWING ROUTINES: * * GPTUTM * UTMLIM * UTMSET */ double fnltr; /* False northing for 3rd letter */ double slcm; /* Central meridian - longitude of origin */ double sleast; /* Longitude east limit - UTM */ double slwest; /* Longitude west limit -UTM */ double spnor; /* MGRS north latitude limits based on 1st letter */ double spsou; /* MGRS south latitude limits based on 1st letter */ double xltr; /* Easting used to derive 2nd letter of MGRS */ double yltr; /* Northing used to derive 3rd letter of MGRS */ long ltrlow; /* 2nd letter range - low number */ long ltrhi; /* 2nd letter range - high number */ char hemisphere; UTMSET(izone, <rlow, <rhi, &fnltr); ltrnum[0] = LETTER_A; UTMLIM(<rnum[0], sphi, izone, &spsou, &spnor, &sleast, &slwest); slcm = (double)(izone * 6 - 183) * DEGRAD; /* GPTUTM(a, recf, spsou, slcm, &izone, &yltr, &xltr, (long)1); */ Set_UTM_Parameters(OSSIM_MGRS_a,OSSIM_MGRS_f,izone); Convert_Geodetic_To_UTM(spsou,slcm,&izone,&hemisphere,&xltr,&yltr); yltr = (double)((long)(y + RND5)); if (((double)((long)(yltr + RND5))) == ((double)((long)(1.e7 + RND5)))) { yltr = (double)((long)(yltr - 1.e0 + RND5)); } while (yltr >= TWOMIL) { yltr = yltr - TWOMIL; } yltr = yltr - fnltr; if (yltr < ZERO) { yltr = yltr + TWOMIL; } ltrnum[2] = (long)((yltr + RND1) / ONEHT); if (ltrnum[2] > LETTER_H) { ltrnum[2] = ltrnum[2] + 1; } if (ltrnum[2] > LETTER_N) { ltrnum[2] = ltrnum[2] + 1; } xltr = (double)((long)(x)); if (((ltrnum[0] == LETTER_V) && (izone == 31)) && (((double)((long)(xltr + RND5))) == ((double)((long)(5.e5 + RND5))))) { xltr = (double)((long)(xltr - 1.e0 + RND5)); /* SUBTRACT 1 METER */ } ltrnum[1] = ltrlow + ((long)((xltr + RND1) / ONEHT) -1); if ((ltrlow == LETTER_J) && (ltrnum[1] > LETTER_N)) { ltrnum[1] = ltrnum[1] + 1; } return; } /* END UTMMGRS */ void UPSSET (long n, long* ltrlow, long* ltrhi, double *feltr, double *fnltr, long* ltrhy) { /* BEGIN UPSSET */ /* * n : Value of 1st letter in MGRS coordinate. * ltrlow : Low number for 2nd letter. * ltrhi : High number for 2nd letter. * feltr : False easting. * fnltr : False northing. * ltrhy : High number for 3rd letter. */ if (n == LETTER_Z) /* EASTERN HEMISPHERE-NORTH ZONE */ { *ltrlow = LETTER_A; *ltrhi = LETTER_J; *feltr = TWOMIL; *fnltr = ONE3HT; *ltrhy = LETTER_P; } else if (n == LETTER_Y) /* WESTERN HEMISPHERE-NORTH ZONE */ { *ltrlow = LETTER_J; *ltrhi = LETTER_Z; *feltr = EIGHT; *fnltr = ONE3HT; *ltrhy = LETTER_P; } else if (n == LETTER_B) /* ** EASTERN HEMISPHERE - SOUTH ZONE */ { *ltrlow = LETTER_A; *ltrhi = LETTER_R; *feltr = TWOMIL; *fnltr = EIGHT; *ltrhy = LETTER_Z; } else if (n == LETTER_A) /* ** WESTERN HEMISPHERE - SOUTH ZONE */ { *ltrlow = LETTER_J; *ltrhi = LETTER_Z; *feltr = EIGHT; *fnltr = EIGHT; *ltrhy = LETTER_Z; } return; } /* END OF UPSSET */ void UPS (char* mgrs, long* ltrnum, double x, double y, long iarea) { /* BEGIN UPS */ /* * mgrs : MGRS coordinate. * ltrnum : Values of the letters in the MGRS coordinate. * x : Easting. * y : Northing. * iarea : Set to UPS_NORTH or UPS_SOUTH. * * UPS CALLS THE FOLLOWING ROUTINES: * * UPSSET */ double feltr=0.0; /* False easting for 2nd letter */ double fnltr=0.0; /* False northing for 3rd letter */ double xltr=0.0; /* Easting used to derive 2nd letter of MGRS */ double yltr=0.0; /* Northing used to derive 3rd letter of MGRS */ long ltrlow=0; /* 2nd letter range - low number */ long ltrhi=0; /* 2nd letter range - high number */ long ltrhy=0; /* 3rd letter range - high number (UPS) */ if (iarea == UPS_NORTH) { ltrnum[0] = LETTER_Y; if (((double)((long)(x + RND5))) >= TWOMIL) { ltrnum[0] = LETTER_Z; } } else if (iarea == UPS_SOUTH) { ltrnum[0] = LETTER_A; if (((double)((long)(x + RND5))) >= TWOMIL) { ltrnum[0] = LETTER_B; } } UPSSET(ltrnum[0], <rlow, <rhi, &feltr, &fnltr, <rhy); mgrs[0] = BLANK; mgrs[1] = BLANK; yltr = (double)((long)(y + RND5)); yltr = yltr - fnltr; ltrnum[2] = (long)((yltr + RND1) / ONEHT); if (ltrnum[2] > LETTER_H) { ltrnum[2] = ltrnum[2] + 1; } if (ltrnum[2] > LETTER_N) { ltrnum[2] = ltrnum[2] + 1; } xltr = (double)((long)(x + RND5)); xltr = xltr - feltr; ltrnum[1] = ltrlow + ((long)((xltr + RND1) / ONEHT)); if (x < TWOMIL) { if (ltrnum[1] > LETTER_L) { ltrnum[1] = ltrnum[1] + 3; } if (ltrnum[1] > LETTER_U) { ltrnum[1] = ltrnum[1] + 2; } } if (x >= TWOMIL) { if (ltrnum[1] > LETTER_C) { ltrnum[1] = ltrnum[1] + 2; } if (ltrnum[1] > LETTER_H) { ltrnum[1] = ltrnum[1] + 1; } if (ltrnum[1] > LETTER_L) { ltrnum[1] = ltrnum[1] + 3; } } return; } /* END OF UPS */ void LTR2UPS (long* ltrnum, long ltrlow, long ltrhi, long ltrhy, long* ierr, double *xltr, double *yltr, double fnltr, double feltr, double *x, double *y, double sign) { /* BEGIN LTR2UPS */ /* * ltrnum : Values of the letters in the MGRS coordinate * ltrlow : Low number * ltrhi : High number-2nd letter * ltrhy : High number-3rd letter * ierr : Error code * xltr : Easting for 100,000 meter grid square * yltr : Northing for 100,000 meter grid square * fnltr : False northing for 3rd letter * feltr : False easting for 2nd letter * x : Easting * y : Northing * sign : Set to either positive or negative */ if (ltrnum[1] < ltrlow) { *ierr = TRUE; return; } if (ltrnum[1] > ltrhi) { *ierr = TRUE; return; } if (ltrnum[2] > ltrhy) { *ierr = TRUE; return; } if ((ltrnum[1] == LETTER_D) || (ltrnum[1] == LETTER_E) || (ltrnum[1] == LETTER_M) || (ltrnum[1] == LETTER_N) || (ltrnum[1] == LETTER_V) || (ltrnum[1] == LETTER_W)) { *ierr = TRUE; return; } *yltr = (double)ltrnum[2] * ONEHT + fnltr; if (ltrnum[2] > LETTER_I) { *yltr = *yltr - ONEHT; } if (ltrnum[2] > LETTER_O) { *yltr = *yltr - ONEHT; } *xltr = (double)((ltrnum[1]) - ltrlow) * ONEHT + feltr; if (ltrlow != LETTER_A) { if (ltrnum[1] > LETTER_L) { *xltr = *xltr - 3.e0 * ONEHT; } if (ltrnum[1] > LETTER_U) { *xltr = *xltr - 2.e0 * ONEHT; } } else if (ltrlow == LETTER_A) { if (ltrnum[1] > LETTER_C) { *xltr = *xltr - 2.e0 * ONEHT; } if (ltrnum[1] > LETTER_I) { *xltr = *xltr - ONEHT; } if (ltrnum[1] > LETTER_L) { *xltr = *xltr - 3.e0 * ONEHT ; } } *x = *xltr; *y = *yltr * sign; return; } /* END OF LTR2UPS */ void GRID_UPS (long *Letters, char *Hemisphere, double *Easting, double *Northing, long *Error) { /* BEGIN GRID_UPS */ double feltr=0.0; /* False easting for 2nd letter */ double fnltr=0.0; /* False northing for 3rd letter */ // double sleast=0.0; /* Longitude east limit - UTM */ // double slwest=0.0; /* Longitude west limit -UTM */ // double spnor=0.0; /* North latitude limits based on 1st letter */ double spsou=0.0; /* South latitude limits based on 1st letter */ double x=0.0; /* easting */ double xltr=0.0; /* easting for 100,000 meter grid square */ double xnum=0.0; /* easting part of MGRS */ double y=0.0; /* northing */ double yltr=0.0; /* northing for 100,000 meter grid square */ double ynum=0.0; /* northing part of MGRS */ // long izone=0; /* Zone number */ long ltrhi=0; /* 2nd letter range - high number */ long ltrhy=0; /* 3rd letter range - high number (UPS) */ long ltrlow=0; /* 2nd letter range - low number */ long sign=0; double sphi=0.0; double slam=0.0; if ((Letters[0] == LETTER_Y) || (Letters[0] == LETTER_Z)) { spsou = MAX_UTM_LAT; sign = 1; } else { spsou = MIN_UTM_LAT; sign = -1; } slam = PI / 2.e0; if ((Letters[0] == LETTER_Y) || (Letters[0] == LETTER_A)) { slam = -slam; } // izone = 0; sphi = spsou; Set_UPS_Parameters(OSSIM_MGRS_a,OSSIM_MGRS_f); Convert_Geodetic_To_UPS(sphi,slam,Hemisphere,&x,&y); // spnor = sphi; // sleast = slam; // slwest = slam; UPSSET(Letters[0], <rlow, <rhi, &feltr, &fnltr, <rhy); LTR2UPS(Letters, ltrlow, ltrhi, ltrhy, Error, &xltr, &yltr, fnltr, feltr, &x, &y, sign); xnum = *Easting; ynum = *Northing; y = (yltr + ynum); x = xltr + xnum; *Easting = x; *Northing = y; return; } /* END OF GRID_UPS */ void LTR2UTM (long* ltrnum, long ltrlow, long ltrhi, long* ierr, double *xltr, double *yltr, double fnltr, double yslow, double ylow) { /* BEGIN LTR2UTM */ /* * xltr : Easting for 100,000 meter grid square. * yltr : Northing for 100,000 meter grid square. * ierr : Error code. * ltrnum : Values of the letters in the OSSIM_MGRS coordinate. * ltrlow : Low number. * ltrhi : High number. * fnltr : False northing for 3rd letter. * yslow : Northing scaled down to less than 2 million. * ylow : Lowest northing of area to nearest 100,000. */ if (ltrnum[1] < ltrlow) { *ierr = TRUE; return; } if (ltrnum[1] > ltrhi) { *ierr = TRUE; return; } if (ltrnum[2] > LETTER_V) { *ierr = TRUE; return; } *yltr = (double)(ltrnum[2]) * ONEHT + fnltr; *xltr = (double)((ltrnum[1]) - ltrlow + 1) * ONEHT; if ((ltrlow == LETTER_J) && (ltrnum[1] > LETTER_O)) { *xltr = *xltr - ONEHT; } if (ltrnum[2] > LETTER_O) { *yltr = *yltr - ONEHT; } if (ltrnum[2] > LETTER_I) { *yltr = *yltr - ONEHT; } if (((double)((long)(*yltr + RND5))) >= ((double)((long)(TWOMIL + RND5)))) { *yltr = *yltr - TWOMIL; } *yltr = ((double)((long)(*yltr + RND5))); *yltr = *yltr - yslow; if (*yltr < ZERO) { *yltr = *yltr + TWOMIL; } *yltr = ((double)((long)(ylow + *yltr + RND5))); return; } /* END OF LTR2UTM */ void GRID_UTM (long *Zone, long *Letters, char *Hemisphere, double *Easting, double *Northing, long In_Precision, long *Error) { /* BEGIN GRID_UTM */ double fnltr; /* False northing for 3rd letter */ long ltrhi; /* 2nd letter range - High number */ long ltrlow; /* 2nd letter range - Low number */ long number; /* Value of ltrnum[0] + 1 */ /* double slam;*/ double slcm; /* Central meridian */ double sleast; /* Longitude east limit - UTM */ double slwest; /* Longitude west limit -UTM */ double sphi; /* Latitude (needed by UTMLIM) */ double spnor; /* North latitude limits based on 1st letter */ double spsou; /* South latitude limits based on 1st letter */ double xltr; /* Easting for 100,000 meter grid square */ double ylow; /* Lowest northing of area to nearest 100,000 */ double yltr; /* Northing for 100,000 meter grid square */ double yslow; /* Northing scaled down to less than 2 million*/ double Latitude = 0.0; double Longitude = 0.0; double divisor = 1.0; if ((*Zone == 32) && (Letters[0] == LETTER_X)) { *Error = TRUE; return; } if ((*Zone == 34) && (Letters[0] == LETTER_X)) { *Error = TRUE; return; } if ((*Zone == 36) && (Letters[0] == LETTER_X)) { *Error = TRUE; return; } number = Letters[0] + 1; sphi = 0.0; UTMLIM(&number,sphi,*Zone,&spsou,&spnor,&sleast,&slwest); Set_UTM_Parameters(OSSIM_MGRS_a,OSSIM_MGRS_f,*Zone); slcm = (double)(*Zone * 6 - 183) * DEGRAD; Convert_Geodetic_To_UTM(spsou,slcm,Zone,Hemisphere,&xltr,&yltr); ylow = ((double)((long)((double)((long)(yltr / ONEHT)) * ONEHT))); yslow = ylow; while (yslow >= TWOMIL) { yslow = yslow - TWOMIL; } yslow = ((double)((long)(yslow))); UTMSET(*Zone, <rlow, <rhi, &fnltr); LTR2UTM(Letters, ltrlow, ltrhi, Error, &xltr, &yltr, fnltr, yslow, ylow); *Easting = xltr + *Easting; *Northing = yltr + *Northing; /* check that point is within Zone Letter bounds */ Convert_UTM_To_Geodetic(*Zone,*Hemisphere,*Easting,*Northing,&Latitude,&Longitude); divisor = pow (10.0, In_Precision); if (((spsou - DEGRAD/divisor) <= Latitude) && (Latitude <= (spnor + DEGRAD/divisor))) return; else *Error = TRUE; return; }/* END OF GRID_UTM */ long Round_OSSIM_MGRS (double value) /* Round value to nearest integer, using standard engineering rule */ { /* Round_OSSIM_MGRS */ double ivalue; long ival; double fraction = modf (value, &ivalue); ival = (long)(ivalue); if ((fraction > 0.5) || ((fraction == 0.5) && (ival%2 == 1))) ival++; return (ival); } /* Round_OSSIM_MGRS */ long Make_OSSIM_MGRS_String (char* OSSIM_MGRS, long Zone, long ltrnum[OSSIM_MGRS_LETTERS], double Easting, double Northing, long Precision) /* Construct an OSSIM_MGRS string from its component parts */ { /* Make_OSSIM_MGRS_String */ int i; int j; int error_code = OSSIM_MGRS_NO_ERROR; double divisor; long int east; /* double data type? (drb) */ long int north; /* double data type? (drb) */ i = 0; if (Zone) i = sprintf (OSSIM_MGRS+i,"%2.2ld",Zone); for (j=0;j<3;j++) OSSIM_MGRS[i++] = ALBET[ltrnum[j]]; divisor = pow (10.0, (5 - Precision)); Easting = fmod (Easting, 100000.0); if (Easting >= 99999.5) Easting = 99999.0; east = (long int)(Easting/divisor); i += sprintf (OSSIM_MGRS+i, "%*.*ld", (int)Precision, (int)Precision, east); Northing = fmod (Northing, 100000.0); if (Northing >= 99999.5) Northing = 99999.0; north = (long int)(Northing/divisor); i += sprintf (OSSIM_MGRS+i, "%*.*ld", (int)Precision, (int)Precision, north); return (error_code); } /* Make_OSSIM_MGRS_String */ long Break_OSSIM_MGRS_String (const char* OSSIM_MGRS, long* Zone, long Letters[OSSIM_MGRS_LETTERS], double* Easting, double* Northing, long* Precision) /* Break down an OSSIM_MGRS string into its component parts */ { /* Break_OSSIM_MGRS_String */ long error_code = OSSIM_MGRS_NO_ERROR; long i = 0; long j; long num_digits; long num_letters; while (OSSIM_MGRS[i] == ' ') i++; /* skip any leading blanks */ j = i; while (isdigit(OSSIM_MGRS[i])) i++; num_digits = i - j; if (num_digits <= 2) if (num_digits > 0) { char zone_string[3]; /* get zone */ strncpy (zone_string, OSSIM_MGRS+j, 2); zone_string[2] = 0; sscanf (zone_string, "%ld", Zone); if ((*Zone < 1) || (*Zone > 60)) error_code |= OSSIM_MGRS_STRING_ERROR; } else *Zone = 0; else error_code |= OSSIM_MGRS_STRING_ERROR; j = i; while (isalpha(OSSIM_MGRS[i])) i++; num_letters = i - j; if (num_letters == 3) { /* get letters */ Letters[0] = (toupper(OSSIM_MGRS[j]) - (long)'A'); if ((Letters[0] == LETTER_I) || (Letters[0] == LETTER_O)) error_code |= OSSIM_MGRS_STRING_ERROR; Letters[1] = (toupper(OSSIM_MGRS[j+1]) - (long)'A'); if ((Letters[1] == LETTER_I) || (Letters[1] == LETTER_O)) error_code |= OSSIM_MGRS_STRING_ERROR; Letters[2] = (toupper(OSSIM_MGRS[j+2]) - (long)'A'); if ((Letters[2] == LETTER_I) || (Letters[2] == LETTER_O)) error_code |= OSSIM_MGRS_STRING_ERROR; } else error_code |= OSSIM_MGRS_STRING_ERROR; j = i; while (isdigit(OSSIM_MGRS[i])) i++; num_digits = i - j; if ((num_digits <= 10) && (num_digits%2 == 0)) { long n; char east_string[6]; char north_string[6]; long east; long north; double multiplier; /* get easting & northing */ n = num_digits/2; *Precision = n; if (n > 0) { strncpy (east_string, OSSIM_MGRS+j, n); east_string[n] = 0; sscanf (east_string, "%ld", &east); strncpy (north_string, OSSIM_MGRS+j+n, n); north_string[n] = 0; sscanf (north_string, "%ld", &north); multiplier = pow (10.0, 5 - n); *Easting = east * multiplier; *Northing = north * multiplier; } else { *Easting = 0.0; *Northing = 0.0; } } else error_code |= OSSIM_MGRS_STRING_ERROR; return (error_code); } /* Break_OSSIM_MGRS_String */ long Set_OSSIM_MGRS_Parameters (double a, double f, const char* Ellipsoid_Code) /* * The function SET_OSSIM_MGRS_PARAMETERS receives the ellipsoid parameters and sets * the corresponding state variables. If any errors occur, the error code(s) * are returned by the function, otherwise OSSIM_MGRS_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid in meters (input) * f : Flattening of ellipsoid (input) * Ellipsoid_Code : 2-letter code for ellipsoid (input) */ { /* Set_OSSIM_MGRS_Parameters */ double inv_f = 1 / f; long Error_Code = OSSIM_MGRS_NO_ERROR; if (a <= 0.0) { /* Semi-major axis must be greater than zero */ Error_Code |= OSSIM_MGRS_A_ERROR; } if ((inv_f < 250) || (inv_f > 350)) { /* Inverse flattening must be between 250 and 350 */ Error_Code |= OSSIM_MGRS_INV_F_ERROR; } if (!Error_Code) { /* no errors */ OSSIM_MGRS_a = a; OSSIM_MGRS_f = f; OSSIM_MGRS_recpf = inv_f; strcpy (OSSIM_MGRS_Ellipsoid_Code, Ellipsoid_Code); } return (Error_Code); } /* Set_OSSIM_MGRS_Parameters */ void Get_OSSIM_MGRS_Parameters (double *a, double *f, char* Ellipsoid_Code) /* * The function Get_OSSIM_MGRS_Parameters returns the current ellipsoid * parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Ellipsoid_Code : 2-letter code for ellipsoid (output) */ { /* Get_OSSIM_MGRS_Parameters */ *a = OSSIM_MGRS_a; *f = OSSIM_MGRS_f; strcpy (Ellipsoid_Code, OSSIM_MGRS_Ellipsoid_Code); return; } /* Get_OSSIM_MGRS_Parameters */ long Convert_Geodetic_To_OSSIM_MGRS (double Latitude, double Longitude, long Precision, char* OSSIM_MGRS) /* * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * OSSIM_MGRS : OSSIM_MGRS coordinate string (output) * */ { /* Convert_Geodetic_To_OSSIM_MGRS */ long error_code = OSSIM_MGRS_NO_ERROR; long zone; char hemisphere; double easting; double northing; if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) { /* Latitude out of range */ error_code |= OSSIM_MGRS_LAT_ERROR; } if ((Longitude < -PI) || (Longitude > (2*PI))) { /* Longitude out of range */ error_code |= OSSIM_MGRS_LON_ERROR; } if ((Precision < 0) || (Precision > MAX_PRECISION)) error_code |= OSSIM_MGRS_PRECISION_ERROR; if (!error_code) { if ((Latitude < MIN_UTM_LAT) || (Latitude > MAX_UTM_LAT)) { Set_UPS_Parameters (OSSIM_MGRS_a, OSSIM_MGRS_f); error_code |= Convert_Geodetic_To_UPS (Latitude, Longitude, &hemisphere, &easting, &northing); error_code |= Convert_UPS_To_OSSIM_MGRS (hemisphere, easting, northing, Precision, OSSIM_MGRS); } else { Set_UTM_Parameters (OSSIM_MGRS_a, OSSIM_MGRS_f, 0); error_code |= Convert_Geodetic_To_UTM (Latitude, Longitude, &zone, &hemisphere, &easting, &northing); error_code |= Convert_UTM_To_OSSIM_MGRS (zone, hemisphere, easting, northing, Precision, OSSIM_MGRS); } } return (error_code); } /* Convert_Geodetic_To_OSSIM_MGRS */ long Convert_OSSIM_MGRS_To_Geodetic (const char* OSSIM_MGRS, double *Latitude, double *Longitude) /* * OSSIM_MGRS : OSSIM_MGRS coordinate string (output) * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * */ { /* Convert_OSSIM_MGRS_To_Geodetic */ long error_code = OSSIM_MGRS_NO_ERROR; long Zone; long Letters[OSSIM_MGRS_LETTERS]; char Hemisphere; double Easting; double Northing; long In_Precision; error_code = Break_OSSIM_MGRS_String (OSSIM_MGRS, &Zone, Letters, &Easting, &Northing, &In_Precision); if (!error_code) { if (Zone) { error_code |= Convert_OSSIM_MGRS_To_UTM (OSSIM_MGRS, &Zone, &Hemisphere, &Easting, &Northing); Set_UTM_Parameters (OSSIM_MGRS_a, OSSIM_MGRS_f, 0); error_code |= Convert_UTM_To_Geodetic (Zone, Hemisphere, Easting, Northing, Latitude, Longitude); } else { error_code |= Convert_OSSIM_MGRS_To_UPS (OSSIM_MGRS, &Hemisphere, &Easting, &Northing); Set_UPS_Parameters (OSSIM_MGRS_a, OSSIM_MGRS_f); error_code |= Convert_UPS_To_Geodetic (Hemisphere, Easting, Northing, Latitude, Longitude); } } return (error_code); } /* END OF Convert_OSSIM_MGRS_To_Geodetic */ long Convert_UTM_To_OSSIM_MGRS (long Zone, char Hemisphere, double Easting, double Northing, long Precision, char* OSSIM_MGRS) /* * The function Convert_UTM_To_OSSIM_MGRS converts UTM (zone, easting, and * northing) coordinates to an OSSIM_MGRS coordinate string, according to the * current ellipsoid parameters. If any errors occur, the error code(s) * are returned by the function, otherwise OSSIM_MGRS_NO_ERROR is returned. * * Zone : UTM zone (input) * Hemisphere : North or South hemisphere (input) * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Precision : Precision level of OSSIM_MGRS string (input) * OSSIM_MGRS : OSSIM_MGRS coordinate string (output) */ { /* Convert_UTM_To_OSSIM_MGRS */ long error_code = OSSIM_MGRS_NO_ERROR; long temp_error = OSSIM_MGRS_NO_ERROR; long Letters[OSSIM_MGRS_LETTERS]; /* Number location of 3 letters in alphabet */ double Latitude; /* Latitude of UTM point */ double Longitude; /* Longitude of UTM point */ double divisor; if ((Zone < 1) || (Zone > 60)) error_code |= OSSIM_MGRS_ZONE_ERROR; if ((Hemisphere != 'S') && (Hemisphere != 'N')) error_code |= OSSIM_MGRS_HEMISPHERE_ERROR; if ((Easting < MIN_EASTING) || (Easting > MAX_EASTING)) error_code |= OSSIM_MGRS_EASTING_ERROR; if ((Northing < MIN_NORTHING) || (Northing > MAX_NORTHING)) error_code |= OSSIM_MGRS_NORTHING_ERROR; if ((Precision < 0) || (Precision > MAX_PRECISION)) error_code |= OSSIM_MGRS_PRECISION_ERROR; if (!error_code) { Set_UTM_Parameters (OSSIM_MGRS_a, OSSIM_MGRS_f,0); temp_error = Convert_UTM_To_Geodetic (Zone, Hemisphere, Easting, Northing, &Latitude, &Longitude); if (temp_error & UTM_NORTHING_ERROR) error_code |= OSSIM_MGRS_NORTHING_ERROR; else { /* Round easting and northing values */ divisor = pow (10.0, (5 - Precision)); Easting = Round_OSSIM_MGRS (Easting/divisor) * divisor; Northing = Round_OSSIM_MGRS (Northing/divisor) * divisor; UTMOSSIM_MGRS (Zone, Letters, Latitude, Easting, Northing); /* UTM checks - these should be done in UTMOSSIM_MGRS */ if ((Zone == 31) && (Letters[0] == LETTER_V)) if (Easting > 500000) Easting = 500000; if (Northing > 10000000) Northing = 10000000; Make_OSSIM_MGRS_String (OSSIM_MGRS, Zone, Letters, Easting, Northing, Precision); } } return (error_code); } /* Convert_UTM_To_OSSIM_MGRS */ long Convert_OSSIM_MGRS_To_UTM (const char *OSSIM_MGRS, long *Zone, char *Hemisphere, double *Easting, double *Northing) /* * The function Convert_OSSIM_MGRS_To_UTM converts an OSSIM_MGRS coordinate string * to UTM projection (zone, hemisphere, easting and northing) coordinates * according to the current ellipsoid parameters. If any errors occur, * the error code(s) are returned by the function, otherwise UTM_NO_ERROR * is returned. * * OSSIM_MGRS : OSSIM_MGRS coordinate string (input) * Zone : UTM zone (output) * Hemisphere : North or South hemisphere (output) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ { /* Convert_OSSIM_MGRS_To_UTM */ long error_code = OSSIM_MGRS_NO_ERROR; long Letters[OSSIM_MGRS_LETTERS]; long In_Precision; long Error = 0; error_code = Break_OSSIM_MGRS_String (OSSIM_MGRS, Zone, Letters, Easting, Northing, &In_Precision); if (!*Zone) error_code |= OSSIM_MGRS_STRING_ERROR; if (!error_code) { GRID_UTM (Zone, Letters, Hemisphere, Easting, Northing, In_Precision, &Error); if (Error) error_code = OSSIM_MGRS_STRING_ERROR; } return (error_code); } /* Convert_OSSIM_MGRS_To_UTM */ long Convert_UPS_To_OSSIM_MGRS (char Hemisphere, double Easting, double Northing, long Precision, char* OSSIM_MGRS) /* * The function Convert_UPS_To_OSSIM_MGRS converts UPS (hemisphere, easting, * and northing) coordinates to an OSSIM_MGRS coordinate string according to * the current ellipsoid parameters. If any errors occur, the error * code(s) are returned by the function, otherwise UPS_NO_ERROR is * returned. * * Hemisphere : Hemisphere either 'N' or 'S' (input) * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Precision : Precision level of OSSIM_MGRS string (input) * OSSIM_MGRS : OSSIM_MGRS coordinate string (output) */ { /* Convert_UPS_To_OSSIM_MGRS */ double divisor; long error_code = OSSIM_MGRS_NO_ERROR; long ltrnum[OSSIM_MGRS_LETTERS]; /* Number location of 3 letters in alphabet */ if ((Hemisphere != 'N') && (Hemisphere != 'S')) error_code |= OSSIM_MGRS_HEMISPHERE_ERROR; if ((Easting < MIN_EAST_NORTH) || (Easting > MAX_EAST_NORTH)) error_code |= OSSIM_MGRS_EASTING_ERROR; if ((Northing < MIN_EAST_NORTH) || (Northing > MAX_EAST_NORTH)) error_code |= OSSIM_MGRS_NORTHING_ERROR; if ((Precision < 0) || (Precision > MAX_PRECISION)) error_code |= OSSIM_MGRS_PRECISION_ERROR; if (!error_code) { divisor = pow (10.0, (5 - Precision)); Easting = Round_OSSIM_MGRS (Easting/divisor) * divisor; Northing = Round_OSSIM_MGRS (Northing/divisor) * divisor; if (Hemisphere == 'S') UPS (OSSIM_MGRS, ltrnum, Easting, Northing, UPS_SOUTH); else UPS (OSSIM_MGRS, ltrnum, Easting, Northing, UPS_NORTH); Make_OSSIM_MGRS_String (OSSIM_MGRS, 0, ltrnum, Easting, Northing, Precision); } return (error_code); } /* Convert_UPS_To_OSSIM_MGRS */ long Convert_OSSIM_MGRS_To_UPS ( const char *OSSIM_MGRS, char *Hemisphere, double *Easting, double *Northing) /* * The function Convert_OSSIM_MGRS_To_UPS converts an OSSIM_MGRS coordinate string * to UPS (hemisphere, easting, and northing) coordinates, according * to the current ellipsoid parameters. If any errors occur, the error * code(s) are returned by the function, otherwide UPS_NO_ERROR is returned. * * OSSIM_MGRS : OSSIM_MGRS coordinate string (input) * Hemisphere : Hemisphere either 'N' or 'S' (output) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ { /* Convert_OSSIM_MGRS_To_UPS */ long error_code = OSSIM_MGRS_NO_ERROR; long Error = 0; long Zone; long Letters[OSSIM_MGRS_LETTERS]; long In_Precision; error_code = Break_OSSIM_MGRS_String (OSSIM_MGRS, &Zone, Letters, Easting, Northing, &In_Precision); if (Zone) error_code |= OSSIM_MGRS_STRING_ERROR; if (!error_code) { GRID_UPS (Letters, Hemisphere, Easting, Northing, &Error); if (Error) error_code = OSSIM_MGRS_STRING_ERROR; } return (error_code); } /* Convert_OSSIM_MGRS_To_UPS */ ossim-Miami-2.9.1/src/projection/ossimMillerProjection.cpp000066400000000000000000000312241352751253100237200ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Miller projection code. //******************************************************************* // $Id: ossimMillerProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include RTTI_DEF1(ossimMillerProjection, "ossimMillerProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define MILL_NO_ERROR 0x0000 #define MILL_LAT_ERROR 0x0001 #define MILL_LON_ERROR 0x0002 #define MILL_EASTING_ERROR 0x0004 #define MILL_NORTHING_ERROR 0x0008 #define MILL_CENT_MER_ERROR 0x0020 #define MILL_A_ERROR 0x0040 #define MILL_B_ERROR 0x0080 #define MILL_A_LESS_B_ERROR 0x0100 ossimMillerProjection::ossimMillerProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); // Mill_Delta_Northing = 14675058.0; // Mill_Max_Easting = 20015110.0; // Mill_Min_Easting = -20015110.0; } ossimMillerProjection::ossimMillerProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Mill_False_Easting = falseEasting; Mill_False_Northing = falseNorthing; Mill_Delta_Northing = 14675058.0; Mill_Max_Easting = 20015110.0; Mill_Min_Easting = -20015110.0; update(); } void ossimMillerProjection::update() { Set_Miller_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.lonr(), Mill_False_Easting, Mill_False_Northing); theFalseEastingNorthing.x = Mill_False_Easting; theFalseEastingNorthing.y = Mill_False_Northing; ossimMapProjection::update(); } void ossimMillerProjection::setFalseEasting(double falseEasting) { Mill_False_Easting = falseEasting; update(); } void ossimMillerProjection::setFalseNorthing(double falseNorthing) { Mill_False_Northing = falseNorthing; update(); } void ossimMillerProjection::setDefaults() { Mill_False_Easting = 0.0; Mill_False_Northing = 0.0; Mill_Delta_Northing = 14675058.0; Mill_Max_Easting = 20015110.0; Mill_Min_Easting = -20015110.0; } void ossimMillerProjection::setCentralMeridian(double centralMeridian) { Mill_Origin_Long = centralMeridian; update(); } void ossimMillerProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Mill_False_Easting = falseEasting; Mill_False_Northing = falseNorthing; update(); } ossimGpt ossimMillerProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Miller_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimMillerProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Miller(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimMillerProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimMillerProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimMillerProjection)) { Mill_False_Easting = theFalseEastingNorthing.x; Mill_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimMillerProjection::Set_Miller_Parameters(double a, double f, double Central_Meridian , double False_Easting, double False_Northing) { /* Begin Set_Miller_Parameters */ /* * The function Set_Miller_Parameters receives the ellipsoid parameters and * Miller Cylindrical projcetion parameters as inputs, and sets the corresponding * state variables. If any errors occur, the error code(s) are returned by the * function, otherwise MILL_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ // double inv_f = 1 / f; long Error_Code = MILL_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= MILL_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= MILL_INV_F_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= MILL_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Mill_a = a; Mill_f = f; es2 = 2 * Mill_f - Mill_f * Mill_f; es4 = es2 * es2; es6 = es4 * es2; /* spherical radius */ Ra = Mill_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 /3024.0); // if (Central_Meridian > PI) // Central_Meridian -= TWO_PI; Mill_Origin_Long = Central_Meridian; Mill_False_Easting = False_Easting; Mill_False_Northing = False_Northing; if (Mill_Origin_Long > 0) { Mill_Max_Easting = 19903915.0; Mill_Min_Easting = -20015110.0; } else if (Mill_Origin_Long < 0) { Mill_Max_Easting = 20015110.0; Mill_Min_Easting = -19903915.0; } else { Mill_Max_Easting = 20015110.0; Mill_Min_Easting = -20015110.0; } } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Miller_Parameters */ void ossimMillerProjection::Get_Miller_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Miller_Parameters */ /* * The function Get_Miller_Parameters returns the current ellipsoid * parameters and Miller Cylindrical projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Mill_a; *f = Mill_f; *Central_Meridian = Mill_Origin_Long; *False_Easting = Mill_False_Easting; *False_Northing = Mill_False_Northing; return; } /* End Get_Miller_Parameters */ long ossimMillerProjection::Convert_Geodetic_To_Miller (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Miller */ /* * The function Convert_Geodetic_To_Miller converts geodetic (latitude and * longitude) coordinates to Miller Cylindrical projection (easting and northing) * coordinates, according to the current ellipsoid and Miller Cylindrical projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise MILL_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double slat = sin(0.8 * Latitude); double dlam; /* Longitude - Central Meridan */ long Error_Code = MILL_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= MILL_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code|= MILL_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Mill_Origin_Long; // if (dlam > PI) // { // dlam -= TWO_PI; // } // if (dlam < -PI) // { // dlam += TWO_PI; // } *Easting = Ra * dlam + Mill_False_Easting; *Northing = (Ra / 1.6) * log((1.0 + slat) / (1.0 - slat)) + Mill_False_Northing; } return (Error_Code); } /* End Convert_Geodetic_To_Miller */ long ossimMillerProjection::Convert_Miller_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Miller_To_Geodetic */ /* * The function Convert_Miller_To_Geodetic converts Miller Cylindrical projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Miller Cylindrical projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise MILL_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx, dy; long Error_Code = MILL_NO_ERROR; // if ((Easting < (Mill_False_Easting + Mill_Min_Easting)) // || (Easting > (Mill_False_Easting + Mill_Max_Easting))) // { /* Easting out of range */ // Error_Code |= MILL_EASTING_ERROR; // } // if ((Northing < (Mill_False_Northing - Mill_Delta_Northing)) || // (Northing > (Mill_False_Northing + Mill_Delta_Northing) )) // { /* Northing out of range */ // Error_Code |= MILL_NORTHING_ERROR; // } if (!Error_Code) { dy = Northing - Mill_False_Northing; dx = Easting - Mill_False_Easting; *Latitude = atan(sinh(0.8 * dy / Ra)) / 0.8; *Longitude = Mill_Origin_Long + dx / Ra; // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; // if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ // *Longitude = PI; // else if (*Longitude < -PI) // *Longitude = -PI; } return (Error_Code); } /* End Convert_Miller_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimMiscProjectionFactory.cpp000066400000000000000000000134201352751253100247150ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimMiscProjectionFactory.cc // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains implementation of class ossimMiscProjectionFactory // // SOFTWARE HISTORY: //> // 15Jun2001 Garrett Potts // Initial coding. //< //***************************************************************************** // $Id: ossimMiscProjectionFactory.cpp 17623 2010-06-25 15:03:42Z gpotts $ #include #include #include #include //*** // Note to programmer: To add a new projection, search this file for // "ADD_PROJECTION" to locate places requiring editing. Functional example // below... // // ADD_PROJECTION: Include all map projection headers here: //*** #include #include #include #include #include #include #include //*** // ADD_PROJECTION: List names of all map projections produced by this factory: //*** ossimMiscProjectionFactory* ossimMiscProjectionFactory::theInstance = 0; //***************************************************************************** // STATIC METHOD: ossimMiscProjectionFactory::instance() // //***************************************************************************** ossimMiscProjectionFactory* ossimMiscProjectionFactory::instance() { if(!theInstance) { theInstance = new ossimMiscProjectionFactory; } return (ossimMiscProjectionFactory*) theInstance; } ossimProjection* ossimMiscProjectionFactory::createProjection(const ossimFilename& filename, ossim_uint32 entryIdx) const { // Check for external geometry file. return createProjectionFromGeometryFile(filename, entryIdx); } //***************************************************************************** // METHOD: ossimMiscProjectionFactory::createProjection(kwl, prefix) // //***************************************************************************** ossimProjection* ossimMiscProjectionFactory::createProjection(const ossimKeywordlist &kwl, const char *prefix) const { ossimProjection *result=NULL; const char *lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if(lookup) { result = createProjection(ossimString(lookup).trim()); if(result) { result->loadState(kwl, prefix); } } else { // look for the geom_file keyword. // lookup = kwl.find(prefix, "geom_file"); if(lookup) { ossimKeywordlist kwl2; kwl2.addFile(lookup); result = createProjection(kwl2, "projection."); // maybe they did not prepend projection. in the pro // file. if(!result) { result = createProjection(kwl2); } } } return result; } //***************************************************************************** // METHOD: ossimMiscProjectionFactory::createProjection(projection_name) // //***************************************************************************** ossimProjection* ossimMiscProjectionFactory::createProjection(const ossimString &name) const { //*** // ADD_PROJECTION: Test for each map projection here: //*** if(name == STATIC_TYPE_NAME(ossimSonomaSensor)) { return new ossimSonomaSensor; } if(name == STATIC_TYPE_NAME(ossimAffineProjection)) { return new ossimAffineProjection; } if(name == STATIC_TYPE_NAME(ossimBilinearProjection)) { return new ossimBilinearProjection; } if(name == STATIC_TYPE_NAME(ossimQuadProjection)) { return new ossimQuadProjection; } if(name == STATIC_TYPE_NAME(ossimRpcProjection)) { return new ossimRpcProjection; } if(name == STATIC_TYPE_NAME(ossimWarpProjection)) { return new ossimWarpProjection; } if(name == STATIC_TYPE_NAME(ossimPolynomProjection)) { return new ossimPolynomProjection; } return NULL; } //***************************************************************************** // METHOD //***************************************************************************** ossimObject* ossimMiscProjectionFactory::createObject(const ossimString& typeName)const { return createProjection(typeName); } //***************************************************************************** // METHOD //***************************************************************************** ossimObject* ossimMiscProjectionFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { return createProjection(kwl, prefix); } //***************************************************************************** // METHOD //***************************************************************************** void ossimMiscProjectionFactory::getTypeNameList(std::vector& typeList)const { typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimSonomaSensor))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimAffineProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimBilinearProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimRpcProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimQuadProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimWarpProjection))); typeList.push_back(ossimString(STATIC_TYPE_NAME(ossimPolynomProjection))); } ossim-Miami-2.9.1/src/projection/ossimMollweidProjection.cpp000066400000000000000000000350171352751253100242540ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Mollweid projection code. //******************************************************************* // $Id: ossimMollweidProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include RTTI_DEF1(ossimMollweidProjection, "ossimMollweidProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define MAX_LAT ( (M_PI * 90.0) / 180.0 ) /* 90 degrees in radians */ #define MOLL_NO_ERROR 0x0000 #define MOLL_LAT_ERROR 0x0001 #define MOLL_LON_ERROR 0x0002 #define MOLL_EASTING_ERROR 0x0004 #define MOLL_NORTHING_ERROR 0x0008 #define MOLL_CENT_MER_ERROR 0x0020 #define MOLL_A_ERROR 0x0040 #define MOLL_B_ERROR 0x0080 #define MOLL_A_LESS_B_ERROR 0x0100 ossimMollweidProjection::ossimMollweidProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimMollweidProjection::ossimMollweidProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Moll_False_Easting = falseEasting; Moll_False_Northing = falseNorthing; Moll_Delta_Northing = 9009965.0; Moll_Max_Easting = 18019930.0; Moll_Min_Easting = -18019930.0; update(); } void ossimMollweidProjection::update() { Set_Mollweide_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.lonr(), Moll_False_Easting, Moll_False_Northing); theFalseEastingNorthing.x = Moll_False_Easting; theFalseEastingNorthing.y = Moll_False_Northing; ossimMapProjection::update(); } void ossimMollweidProjection::setFalseEasting(double falseEasting) { Moll_False_Easting = falseEasting; update(); } void ossimMollweidProjection::setFalseNorthing(double falseNorthing) { Moll_False_Northing = falseNorthing; update(); } void ossimMollweidProjection::setDefaults() { Moll_False_Easting = 0.0; Moll_False_Northing = 0.0; Moll_Delta_Northing = 9009965.0; Moll_Max_Easting = 18019930.0; Moll_Min_Easting = -18019930.0; } void ossimMollweidProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Moll_False_Easting = falseEasting; Moll_False_Northing = falseNorthing; update(); } void ossimMollweidProjection::setCentralMeridian(double centralMeridian) { Moll_Origin_Long = centralMeridian; update(); } ossimGpt ossimMollweidProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Mollweide_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimMollweidProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Mollweide(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimMollweidProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimMollweidProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimMollweidProjection)) { Moll_False_Easting = theFalseEastingNorthing.x; Moll_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimMollweidProjection::Set_Mollweide_Parameters(double a, double f, double Central_Meridian, double False_Easting, double False_Northing) { /* Begin Set_Mollweide_Parameters */ /* * The function Set_Mollweide_Parameters receives the ellipsoid parameters and * Mollweide projcetion parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the * function, otherwise MOLL_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double Ra; /* Spherical Radius */ // double inv_f = 1 / f; long Error_Code = MOLL_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= MOLL_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= MOLL_INV_F_ERROR; // } // if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= MOLL_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Moll_a = a; Moll_f = f; es2 = 2 * Moll_f - Moll_f * Moll_f; es4 = es2 * es2; es6 = es4 * es2; /* spherical radius */ Ra = Moll_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 / 3024.0); Sqrt2_Ra = sqrt(2.0) * Ra; Sqrt8_Ra = sqrt(8.0) * Ra; // if (Central_Meridian > PI) // Central_Meridian -= TWO_PI; Moll_Origin_Long = Central_Meridian; Moll_False_Easting = False_Easting; Moll_False_Northing = False_Northing; if (Moll_Origin_Long > 0) { Moll_Max_Easting = 17919819.0; Moll_Min_Easting = -18019930.0; } else if (Moll_Origin_Long < 0) { Moll_Max_Easting = 18019930.0; Moll_Min_Easting = -17919819.0; } else { Moll_Max_Easting = 18019930.0; Moll_Min_Easting = -18019930.0; } } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Mollweide_Parameters */ void ossimMollweidProjection::Get_Mollweide_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* Begin Get_Mollweide_Parameters */ /* * The function Get_Mollweide_Parameters returns the current ellipsoid * parameters and Mollweide projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Moll_a; *f = Moll_f; *Central_Meridian = Moll_Origin_Long; *False_Easting = Moll_False_Easting; *False_Northing = Moll_False_Northing; return; } /* End Get_Mollweide_Parameters */ long ossimMollweidProjection::Convert_Geodetic_To_Mollweide (double Latitude, double Longitude, double *Easting, double *Northing)const { /* Begin Convert_Geodetic_To_Mollweide */ /* * The function Convert_Geodetic_To_Mollweide converts geodetic (latitude and * longitude) coordinates to Mollweide projection (easting and northing) * coordinates, according to the current ellipsoid and Mollweide projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise MOLL_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double PI_Sin_Latitude = M_PI * sin(Latitude); double dlam; /* Longitude - Central Meridan */ double theta; double theta_primed = Latitude; double delta_theta_primed = 0.1745329; /* arbitrarily initialized to 10 deg */ double dtp_tolerance = 4.85e-10; /* approximately 1/1000th of an arc second or 1/10th meter */ long Error_Code = MOLL_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= MOLL_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code|= MOLL_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Moll_Origin_Long; // if (dlam > PI) // { // dlam -= TWO_PI; // } // if (dlam < -PI) // { // dlam += TWO_PI; // } while (fabs(delta_theta_primed) > dtp_tolerance) { delta_theta_primed = -(theta_primed + sin(theta_primed) - PI_Sin_Latitude) / (1.0 + cos(theta_primed)); theta_primed += delta_theta_primed; } theta = theta_primed / 2.0; *Easting = (Sqrt8_Ra / M_PI ) * dlam * cos(theta) + Moll_False_Easting; *Northing = Sqrt2_Ra * sin(theta) + Moll_False_Northing; } return (Error_Code); } /* End Convert_Geodetic_To_Mollweide */ long ossimMollweidProjection::Convert_Mollweide_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Mollweide_To_Geodetic */ /* * The function Convert_Mollweide_To_Geodetic converts Mollweide projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Mollweide projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise MOLL_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx, dy; double theta = 0.0; double two_theta; double i; long Error_Code = MOLL_NO_ERROR; // if ((Easting < (Moll_False_Easting + Moll_Min_Easting)) // || (Easting > (Moll_False_Easting + Moll_Max_Easting))) // { /* Easting out of range */ // Error_Code |= MOLL_EASTING_ERROR; // } // if ((Northing < (Moll_False_Northing - Moll_Delta_Northing)) || // (Northing >(Moll_False_Northing + Moll_Delta_Northing) )) // { /* Northing out of range */ // Error_Code |= MOLL_NORTHING_ERROR; // } if (!Error_Code) { dy = Northing - Moll_False_Northing; dx = Easting - Moll_False_Easting; i = dy / Sqrt2_Ra; if (fabs(i) > 1.0) { *Latitude = MAX_LAT; if (Northing < 0.0) *Latitude *= -1.0; } else { theta = asin(i); two_theta = 2.0 * theta; *Latitude = asin((two_theta + sin(two_theta)) / M_PI); if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ *Latitude = PI_OVER_2; else if (*Latitude < -PI_OVER_2) *Latitude = -PI_OVER_2; } if (fabs(fabs(*Latitude) - MAX_LAT) < 1.0e-10) *Longitude = Moll_Origin_Long; else *Longitude = Moll_Origin_Long + M_PI * dx / (Sqrt8_Ra * cos(theta)); // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; // if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ // *Longitude = PI; // else if (*Longitude < -PI) // *Longitude = -PI; } return (Error_Code); } /* End Convert_Mollweide_To_Geodetic */ //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimMollweidProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimMollweidProjection* p = dynamic_cast(&proj); if (!p) return false; if (!ossim::almostEqual(Moll_Origin_Long,p->Moll_Origin_Long)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimNewZealandMapGridProjection.cpp000066400000000000000000000307211352751253100257710ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimNewZealandMapGridProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include #include #include RTTI_DEF1(ossimNewZealandMapGridProjection, "ossimNewZealandMapGridProjection", ossimMapProjection) #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define MAX_LAT (-33.5 * M_PI / 180.0) /* -33.5 degrees */ #define MIN_LAT (-48.5 * M_PI / 180.0) /* -48.5 degrees */ #define MAX_LON (180.0 * M_PI / 180.0) /* 180 degrees */ #define MIN_LON (165.5 * M_PI / 180.0) /* 165.5 degrees */ #define NZMG_NO_ERROR 0x0000 #define NZMG_LAT_ERROR 0x0001 #define NZMG_LON_ERROR 0x0002 #define NZMG_EASTING_ERROR 0x0004 #define NZMG_NORTHING_ERROR 0x0008 #define NZMG_ELLIPSOID_ERROR 0x0010 typedef struct ComplexNumber { double real; double imag; } Complex; static double A[] = { 0.6399175073, -0.1358797613, 0.063294409, -0.02526853, 0.0117879, -0.0055161, 0.0026906, -0.001333, 0.00067, -0.00034 }; static Complex B[] = { { 0.7557853228, 0.0 }, { 0.249204646, 0.003371507 }, { -0.001541739, 0.041058560 }, { -0.10162907, 0.01727609 }, { -0.26623489, -0.36249218 }, { -0.6870983, -1.1651967 } }; static Complex C[] = { { 1.3231270439, 0.0 }, { -0.577245789, -0.007809598 }, { 0.508307513, -0.112208952 }, { -0.15094762, 0.18200602 }, { 1.01418179, 1.64497696 }, { 1.9660549, 2.5127645 } }; static double D[] = { 1.5627014243, 0.5185406398, -0.03333098, -0.1052906, -0.0368594, 0.007317, 0.01220, 0.00394, -0.0013 }; /* These state variables are for optimization purposes. The only function * that should modify them is Set_NZMG_Parameters. */ /************************************************************************/ /* FUNCTIONS * */ /* Add two complex numbers */ static Complex Add(Complex z1, Complex z2) { Complex z; z.real = z1.real + z2.real; z.imag = z1.imag + z2.imag; return z; } /* Multiply two complex numbers */ static Complex Multiply(Complex z1, Complex z2) { Complex z; z.real = z1.real * z2.real - z1.imag * z2.imag; z.imag = z1.imag * z2.real + z1.real * z2.imag; return z; } /* Divide two complex numbers */ static Complex Divide(Complex z1, Complex z2) { Complex z; double denom; denom = z2.real * z2.real + z2.imag * z2.imag; z.real = (z1.real * z2.real + z1.imag * z2.imag) / denom; z.imag = (z1.imag * z2.real - z1.real * z2.imag) / denom; return z; } ossimNewZealandMapGridProjection::ossimNewZealandMapGridProjection() :ossimMapProjection(*ossimEllipsoidFactory::instance()->create("IN"), ossimGpt(-41, 173.0)) { setDefaults(); update(); } ossimNewZealandMapGridProjection::~ossimNewZealandMapGridProjection() { } void ossimNewZealandMapGridProjection::setFalseEasting(double falseEasting) { NZMG_False_Easting = falseEasting; update(); } void ossimNewZealandMapGridProjection::setFalseNorthing(double falseNorthing) { NZMG_False_Northing = falseNorthing; update(); } void ossimNewZealandMapGridProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { NZMG_False_Easting = falseEasting; NZMG_False_Northing = falseNorthing; update(); } void ossimNewZealandMapGridProjection::setDefaults() { theOrigin.latd(-41.0); theOrigin.lond(173.0); // origin of lat needs to be in degrees NZMG_Origin_Lat = theOrigin.latd(); // origin of lon is in radians NZMG_Origin_Long = theOrigin.lonr(); NZMG_Max_Easting = 3170000.0; NZMG_Max_Northing = 6900000.0; NZMG_Min_Easting = 1810000.0; NZMG_Min_Northing = 5160000.0; NZMG_False_Easting = 2510000.0; NZMG_False_Northing = 6023150.0; } void ossimNewZealandMapGridProjection::update() { theOrigin = ossimGpt(-41, 173); // create the new zealand datum. theDatum = ossimDatumFactory::instance()->create(ossimString("GEO")); if(theDatum) { theEllipsoid = *(theDatum->ellipsoid()); } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimNewZealandMapGridProjection::update(): Was unable to locate the newzealand datum!" << std::endl; } NZMG_Origin_Lat = theOrigin.latd(); NZMG_Origin_Long = theOrigin.lonr(); NZMG_a = theEllipsoid.getA(); theFalseEastingNorthing.x = NZMG_False_Easting; theFalseEastingNorthing.y = NZMG_False_Northing; ossimMapProjection::update(); } ossimGpt ossimNewZealandMapGridProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_NZMG_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimNewZealandMapGridProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_NZMG(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimNewZealandMapGridProjection::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimMapProjection::saveState(kwl, prefix); return true; } bool ossimNewZealandMapGridProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimKeywordlist newKwl = kwl; // force a New Zealand Datum and the origin of lat and lon // to the New Zealand. newKwl.add(prefix, ossimKeywordNames::DATUM_KW, "GEO", true); newKwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, -41, true); newKwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, 173.0, true); setDefaults(); ossimMapProjection::loadState(newKwl, prefix); update(); return true; } long ossimNewZealandMapGridProjection::Convert_Geodetic_To_NZMG (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_NZMG */ /* * The function Convert_Geodetic_To_NZMG converts geodetic (latitude and * longitude) coordinates to New Zealand Map Grid projection (easting and northing) * coordinates, according to the current ellipsoid and New Zealand Map Grid * projection parameters. If any errors occur, the error code(s) are returned * by the function, otherwise NZMG_NO_ERROR is returned. * * Latitude : Latitude (phi), in radians (input) * Longitude : Longitude (lambda), in radians (input) * Easting : Easting (X), in meters (output) * Northing : Northing (Y), in meters (output) */ Complex Zeta, z; int n; double dphi; double du, dlam; long Error_Code = NZMG_NO_ERROR; // if ((Latitude < MIN_LAT) || (Latitude > MAX_LAT)) // { /* Latitude out of range */ // Error_Code|= NZMG_LAT_ERROR; // } // if ((Longitude < MIN_LON) || (Longitude > MAX_LON)) // { /* Longitude out of range */ // Error_Code|= NZMG_LON_ERROR; // } if (!Error_Code) { /* no errors */ dphi = (Latitude * (180.0 / M_PI) - NZMG_Origin_Lat) * 3600.0 * 1.0e-5; du = A[9]; for (n = 8; n >= 0; n--) du = du * dphi + A[n]; du *= dphi; dlam = Longitude - NZMG_Origin_Long; Zeta.real = du; Zeta.imag = dlam; z.real = B[5].real; z.imag = B[5].imag; for (n = 4; n >= 0; n--) { z = Multiply(z, Zeta); z = Add(B[n], z); } z = Multiply(z, Zeta); *Easting = (z.imag * NZMG_a) + NZMG_False_Easting; *Northing = (z.real * NZMG_a) + NZMG_False_Northing; // if ((*Easting < NZMG_Min_Easting) || (*Easting > NZMG_Max_Easting)) // Error_Code |= NZMG_EASTING_ERROR; // if ((*Northing < NZMG_Min_Northing) || (*Northing > NZMG_Max_Northing)) // Error_Code |= NZMG_NORTHING_ERROR; } return (Error_Code); } /* END OF Convert_Geodetic_To_NZMG */ long ossimNewZealandMapGridProjection::Convert_NZMG_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_NZMG_To_Geodetic */ /* * The function Convert_NZMG_To_Geodetic converts New Zealand Map Grid projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and New Zealand Map Grid projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise NZMG_NO_ERROR is returned. * * Easting : Easting (X), in meters (input) * Northing : Northing (Y), in meters (input) * Latitude : Latitude (phi), in radians (output) * Longitude : Longitude (lambda), in radians (output) */ int i, n; Complex coeff; Complex z, Zeta, Zeta_Numer, Zeta_Denom, Zeta_sqr; double dphi; long Error_Code = NZMG_NO_ERROR; // if ((Easting < NZMG_Min_Easting) || (Easting > NZMG_Max_Easting)) // { /* Easting out of range */ // Error_Code |= NZMG_EASTING_ERROR; // } // if ((Northing < NZMG_Min_Northing) || (Northing > NZMG_Max_Northing)) // { /* Northing out of range */ // Error_Code |= NZMG_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ z.real = (Northing - NZMG_False_Northing) / NZMG_a; z.imag = (Easting - NZMG_False_Easting) / NZMG_a; Zeta.real = C[5].real; Zeta.imag = C[5].imag; for (n = 4; n >= 0; n--) { Zeta = Multiply(Zeta, z); Zeta = Add(C[n], Zeta); } Zeta = Multiply(Zeta, z); for (i = 0; i < 2; i++) { Zeta_Numer.real = 5.0 * B[5].real; Zeta_Numer.imag = 5.0 * B[5].imag; Zeta_Denom.real = 6.0 * B[5].real; Zeta_Denom.imag = 6.0 * B[5].imag; for (n = 4; n >= 1; n--) { Zeta_Numer = Multiply(Zeta_Numer, Zeta); coeff.real = n * B[n].real; coeff.imag = n * B[n].imag; Zeta_Numer = Add(coeff, Zeta_Numer); Zeta_Denom = Multiply(Zeta_Denom, Zeta); coeff.real = (n+1) * B[n].real; coeff.imag = (n+1) * B[n].imag; Zeta_Denom = Add(coeff, Zeta_Denom); } Zeta_sqr = Multiply(Zeta, Zeta); Zeta_Numer = Multiply(Zeta_Numer, Zeta_sqr); Zeta_Numer = Add(z, Zeta_Numer); Zeta_Denom = Multiply(Zeta_Denom, Zeta); Zeta_Denom = Add(B[0], Zeta_Denom); Zeta = Divide(Zeta_Numer, Zeta_Denom); } dphi = D[8]; for (n = 7; n >= 0; n--) dphi = dphi * Zeta.real + D[n]; dphi *= Zeta.real; *Latitude = NZMG_Origin_Lat + (dphi * 1.0e5 / 3600.0); *Latitude *= M_PI / 180.0; *Longitude = NZMG_Origin_Long + Zeta.imag; // if ((*Longitude > M_PI) && (*Longitude - M_PI < 1.0e-6)) // *Longitude = M_PI; // if ((*Latitude < MIN_LAT) || (*Latitude > MAX_LAT)) // Error_Code|= NZMG_LAT_ERROR; // if ((*Longitude < MIN_LON) || (*Longitude > MAX_LON)) // Error_Code|= NZMG_LON_ERROR; } return (Error_Code); } /* END OF Convert_NZMG_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimNgaProjectionFactory.cpp000066400000000000000000000057041352751253100245350ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2014 RadiantBlue, Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //******************************************************************* // $Id$ #include #include #include #include #include // Define Trace flags for use within this file: #include static ossimTrace traceDebug = ossimTrace("ossimNgaProjectionFactory:debug"); RTTI_DEF1(ossimNgaProjectionFactory, "ossimNgaProjectionFactory", ossimProjectionFactoryBase); //************************************************************************************************* //! Implements singleton pattern //************************************************************************************************* ossimNgaProjectionFactory* ossimNgaProjectionFactory::instance() { static ossimNgaProjectionFactory inst; return &inst; } ossimProjection* ossimNgaProjectionFactory::createProjection(const ossimFilename& filename, ossim_uint32 entryIdx) const { // Check for external geometry file. return createProjectionFromGeometryFile(filename, entryIdx); } //************************************************************************************************** // This is the principal factory method. It accepts a string in format: // // :, for example "NGA:235" (Currently only code supported, used in GeoPackage) // // IMPORTANT NOTE: Image tie-points cannot be conveyed by a projection code. The projection // created here will not be fully initialized for use in rendering imagery. //************************************************************************************************** ossimProjection* ossimNgaProjectionFactory::createProjection(const ossimString& spec) const { ossimProjection* proj = 0; if ((!ossimString(spec).downcase().contains("nga")) && (spec.after(":").toInt() == 235)) { const ossimEllipsoid* e = ossimEllipsoidFactory::instance()->create("WE"); proj = new ossimMercatorProjection(*e, ossimGpt(0,0), 0, 0, 0.857385503731176); } return proj; } /** * Take a keywordlist. */ ossimProjection* ossimNgaProjectionFactory::createProjection( const ossimKeywordlist& /* kwl */, const char* /* prefix */) const { return 0; } ossimObject* ossimNgaProjectionFactory::createObject( const ossimString& typeName) const { return createProjection(typeName); } ossimObject* ossimNgaProjectionFactory::createObject(const ossimKeywordlist& kwl, const char* prefix) const { return createProjection(kwl, prefix); } void ossimNgaProjectionFactory::getTypeNameList(std::vector& typeList) const { typeList.push_back(ossimString("NGA:235 \"Scaled World Mercator\"")); } ossim-Miami-2.9.1/src/projection/ossimNitfMapModel.cpp000066400000000000000000000523301352751253100227570ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Doug Shibla (dshibla@imagelinks.com) // // DESCRIPTION: // // LIMITATIONS: // //***************************************************************************** #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfMapModel, "ossimNitfMapModel", ossimSensorModel); //*** // Define Trace flags for use within this file: //*** static ossimTrace traceExec ("ossimNitfMapModel:exec"); static ossimTrace traceDebug ("ossimNitfMapModel:debug"); static const char* PIAIMC_TAG = "PIAIMC"; static const char* USE26A_TAG = "USE26A"; static const char* USE00A_TAG = "USE00A"; static const char* IMAGE_ID_KW = "image_id"; //***************************************************************************** // DEFAULT CONSTRUCTOR: ossimNitfMapModel() // //***************************************************************************** ossimNitfMapModel::ossimNitfMapModel() : ossimSensorModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::ossimNitfMapModel: entering..." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::ossimNitfMapModel: returning..." << std::endl; } //***************************************************************************** // CONSTRUCTOR: ossimNitfMapModel(filename) // // Constructs model from a filename. The file can be either a FF header file // or a KWL file. // //***************************************************************************** ossimNitfMapModel::ossimNitfMapModel(const ossimFilename& init_file) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::ossimNitfMapModel(init_file): entering..." << std::endl; //*** // Open the NITF file: //*** FILE* fptr = fopen (init_file.chars(), "r"); if (!fptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimNitfMapModel::ossimNitfMapModel(init_file): Could not open NITF file at: <" << init_file << ">." << " Aborting with error..." << std::endl; } theErrorStatus = 1; return; } //*** // Read a sufficient number of bytes to include USE tag: //*** char* header = new char [6000]; fread(header, 6000, 1, fptr); fclose(fptr); fptr = 0; //*** // Validate correct NITF version: //*** if (strncmp(header, "NITF02.00", 9)) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::ossimNitfMapModel(init_file):" << "\n\tFailed attempt to open <" << init_file << "> as NITF2.00."< tag in the NITF file at: <" << init_file << "> to extract GSD." << " Searching for alternate <" << USE26A_TAG << ">... "<< std::endl; } //*** // Search USE26A tag: //*** const char* tag_ptr = strstr(header, USE26A_TAG); if (tag_ptr) { //*** // Parse the tag for GSD (in inches): //*** strncpy(charbuf, &tag_ptr[15], 5); charbuf[6] = '\0'; theGSD.line = atof(charbuf)/12.0 * MTRS_PER_FT; theGSD.samp = theGSD.line; } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimNitfMapModel::ossimNitfMapModel(init_file): Could not find the <" << USE26A_TAG << "> tag in the NITF file at: <" << init_file << "> to extract GSD." << " Searching for alternate <" << USE00A_TAG << ">... "<< std::endl; } //*** // Search USE00A tag: //*** const char* tag_ptr = strstr(header, USE00A_TAG); if (!tag_ptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "WARNING ossimNitfMapModel::ossimNitfMapModel(init_file): Could not find the <" << USE00A_TAG << "> tag in the NITF file at: <" << init_file << ">." << " Aborting with error..." << std::endl; } theErrorStatus = 1; delete [] header; return; } //*** // Parse the tag for GSD (in inches): //*** strncpy(charbuf, &tag_ptr[15], 5); charbuf[6] = '\0'; theGSD.line = atof(charbuf)/12.0 * MTRS_PER_FT; theGSD.samp = theGSD.line; } } ossimString drivePart; ossimString pathPart; ossimString filePart; ossimString extPart; init_file.split(drivePart, pathPart, filePart, extPart); //*** // Save current state: //*** ossimFilename geom_filename; geom_filename.merge(drivePart, pathPart, filePart, "geom"); ossimKeywordlist geom_kwl; saveState(geom_kwl); geom_kwl.write(geom_filename.chars()); delete [] header; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::ossimNitfMapModel: Exited..." << std::endl; } //***************************************************************************** // CONSTRUCTOR: ossimNitfMapModel(kwl) // // Constructs model from keywordlist geometry file // //***************************************************************************** ossimNitfMapModel::ossimNitfMapModel(const ossimKeywordlist& geom_kwl) : ossimSensorModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::ossimNitfMapModel(geom_file): entering..." << std::endl; //*** // Parse keywordlist for geometry: //*** loadState(geom_kwl); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::ossimNitfMapModel(geom_file): Exited..." << std::endl; } //***************************************************************************** // DESTRUCTOR: ~ossimNitfMapModel() // //***************************************************************************** ossimNitfMapModel::~ossimNitfMapModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::~ossimNitfMapModel: entering..." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::~ossimNitfMapModel: returning..." << std::endl; } //***************************************************************************** // METHOD: ossimNitfMapModel::lineSampleHeightToWorld() // // Performs reverse projection of image line/sample to ground point. // The imaging ray is intersected with a level plane at height above ellipsoid. // //***************************************************************************** void ossimNitfMapModel::lineSampleHeightToWorld(const ossimDpt& /* image_point */, const double& /* height */, ossimGpt& /* gpt */) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::lineSampleHeightToWorld: entering..." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::lineSampleHeightToWorld: exiting..." << std::endl; } //***************************************************************************** // METHOD: ossimNitfMapModel::print() // // Formatted dump of data members. // //***************************************************************************** std::ostream& ossimNitfMapModel::print(std::ostream& out) const { out << "\nDump of ossimNitfMapModel object at " << hex << this << ":" << endl; return ossimSensorModel::print(out); } //***************************************************************************** // METHOD: ossimNitfMapModel::saveState() // // Saves the model state to the KWL. This KWL also serves as a geometry file. // //***************************************************************************** bool ossimNitfMapModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::saveState: entering..." << std::endl; // Hand off to base class for common stuff: ossimSensorModel::saveState(kwl, prefix); kwl.add(prefix, IMAGE_ID_KW, theImageID.chars()); kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, theImageSize.line, true); kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, theImageSize.samp, true); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW, theGSD.line, true); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_X_KW, theGSD.samp, true); kwl.add(prefix, ossimKeywordNames::UL_Y_KW, 0, true); kwl.add(prefix, ossimKeywordNames::UL_X_KW, 0, true); kwl.add(prefix, ossimKeywordNames::LR_Y_KW, theImageSize.line - 1, true); kwl.add(prefix, ossimKeywordNames::LR_X_KW, theImageSize.samp - 1, true); ossimDpt ulcorner; if(!theBoundGndPolygon.vertex(0, ulcorner)) { ulcorner = ossimDpt(0,0); } kwl.add(prefix, ossimKeywordNames::UL_LAT_KW, ulcorner.lat, true); kwl.add(prefix, ossimKeywordNames::UL_LON_KW, ulcorner.lon, true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LAT_KW, ulcorner.lat, true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LON_KW, ulcorner.lon, true); ossimDpt corner; if(!theBoundGndPolygon.nextVertex(corner)) { corner = ossimDpt(0,0); } kwl.add(prefix, ossimKeywordNames::UR_LAT_KW, corner.lat, true); kwl.add(prefix, ossimKeywordNames::UR_LON_KW, corner.lon, true); ossimDpt lrcorner; if(!theBoundGndPolygon.nextVertex(lrcorner)) { lrcorner = ossimDpt(0,0); } kwl.add(prefix, ossimKeywordNames::LR_LAT_KW, lrcorner.lat, true); kwl.add(prefix, ossimKeywordNames::LR_LON_KW, lrcorner.lon, true); if(!theBoundGndPolygon.nextVertex(corner)) { corner = ossimDpt(0,0); } kwl.add(prefix, ossimKeywordNames::LL_LAT_KW, corner.lat, true); kwl.add(prefix, ossimKeywordNames::LL_LON_KW, corner.lon, true); kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, (ulcorner.lat + lrcorner.lat)/2, true); kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, (lrcorner.lon + ulcorner.lon)/2, true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, fabs((ulcorner.lat - lrcorner.lat))/(theImageSize.line - 1), true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, fabs((lrcorner.lon - ulcorner.lon))/(theImageSize.samp - 1), true); kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimEquDistCylProjection"); // kwl.add(prefix, ossimKeywordNames::TYPE_KW, TYPE_NAME(this)); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::saveState: returning..." << std::endl; return true; } //***************************************************************************** // METHOD: ossimNitfMapModel::loadState() // // Restores the model's state from the KWL. This KWL also serves as a // geometry file. // //***************************************************************************** bool ossimNitfMapModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::loadState: entering..." << std::endl; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::loadState:" << "\nInput kwl: " << kwl << std::endl; } const char* value = 0; const char* keyword = 0; bool success = false; //*** // Assure this keywordlist contains correct type info: //*** value = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if (!value || (strcmp(value, TYPE_NAME(this)))) goto loadStateError; //*** // Pass on to the base-class for parsing first: //*** success = ossimSensorModel::loadState(kwl, prefix); if (!success) goto loadStateError; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::loadState: returning..." << std::endl; return true; //*** // Local error handling: //*** loadStateError: theErrorStatus++; ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimNitfMapModel::loadState: encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::loadState: returning with error..." << std::endl; return false; } //***************************************************************************** // STATIC METHOD: ossimNitfMapModel::writeGeomTemplate // // Writes a sample kwl to output stream. // //***************************************************************************** void ossimNitfMapModel::writeGeomTemplate(ostream& os) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::writeGeomTemplate: entering..." << std::endl; os << "//**************************************************************\n" "// Template for LandSat model keywordlist\n" "//**************************************************************\n" << ossimKeywordNames::TYPE_KW << ": " << "ossimNitfMapModel" << endl; ossimSensorModel::writeGeomTemplate(os); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfMapModel::writeGeomTemplate: returning..." << std::endl; return; } ossim-Miami-2.9.1/src/projection/ossimNitfProjectionFactory.cpp000066400000000000000000001036031352751253100247250ustar00rootroot00000000000000//--- // License: MIT // // Description: // // Contains class definition for ossimNitfProjectionFactory. //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; // Define Trace flags for use within this file: static ossimTrace traceDebug(ossimString("ossimNitfProjectionFactory:debug")); ossimNitfProjectionFactory* ossimNitfProjectionFactory::theInstance = 0; ossimNitfProjectionFactory::ossimNitfProjectionFactory() { } ossimNitfProjectionFactory::~ossimNitfProjectionFactory() { } ossimNitfProjectionFactory* ossimNitfProjectionFactory::instance() { if(!theInstance) { theInstance = new ossimNitfProjectionFactory(); } return theInstance; } ossimProjection* ossimNitfProjectionFactory::createProjection(const ossimFilename& filename, ossim_uint32 entryIdx)const { static const char MODULE[]="ossimNitfProjectionFactory::createProjection"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nfilename: " << filename << "\nentryIdx: " << entryIdx << std::endl; } // See if there is an external geomtry. ossimProjection* result = createProjectionFromGeometryFile(filename, entryIdx); if (result) { return result; } if(!isNitf(filename)) { return result; // result is NULL } ossimRefPtr nitf = new ossimNitfFile(); if (!nitf->parseFile(filename)) { return result; // result is NULL } long imageIndex = static_cast(entryIdx); if ( imageIndex > (nitf->getHeader()->getNumberOfImages()-1) ) { return result; } ossimRefPtr imageHeader = nitf->getNewImageHeader(imageIndex); { if (!imageHeader) { return result; } } result = createProjectionFromHeaders(nitf.get(), nitf->getHeader(), imageHeader.get()); if (traceDebug()) { ossimString coordinateSystem = imageHeader->getCoordinateSystem(); ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\ncoordinateSysetm: " << coordinateSystem << std::endl; } return result; } ossimProjection* ossimNitfProjectionFactory::createProjection(const ossimKeywordlist& /* kwl */, const char* /* prefix */) const { return 0; } ossimProjection* ossimNitfProjectionFactory::createProjection(const ossimString& /* name */) const { return 0; } ossimObject* ossimNitfProjectionFactory::createObject(const ossimString& typeName)const { return (ossimObject*)createProjection(typeName); } ossimObject* ossimNitfProjectionFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { return createProjection(kwl, prefix); } void ossimNitfProjectionFactory::getTypeNameList(std::vector& /* typeList */)const { } ossimProjection* ossimNitfProjectionFactory::createProjection(ossimImageHandler* handler)const { ossimNitfTileSource* nitfTileSource = dynamic_cast (handler); ossimProjection* result = 0; if(nitfTileSource) { if(!result) { ossimNitfImageHeader* imageHeader = nitfTileSource->getCurrentImageHeader(); if(imageHeader) { result = createProjectionFromHeaders(nitfTileSource->getNitfFile(), nitfTileSource->getFileHeader(),imageHeader); } } } else if(isNitf(handler->getFilename())) { result = createProjection(handler->getFilename(), handler->getCurrentEntry()); } return result; } bool ossimNitfProjectionFactory::isNitf(const ossimFilename& filename)const { std::ifstream in(filename.c_str(), ios::in|ios::binary); if(in) { char nitfFile[4]; in.read((char*)nitfFile, 4); ossimString s(nitfFile, nitfFile+4); if ( (s == "NITF") || (s == "NSIF") ) { return true; } } return false; } ossimProjection* ossimNitfProjectionFactory::createProjectionFromHeaders( ossimNitfFile* nitfFile, ossimNitfFileHeader* fileHeader, ossimNitfImageHeader* imageHeader)const { ossimProjection* result = 0; ossimString version = fileHeader->getVersion(); ossimString coordinateSystem = imageHeader->getCoordinateSystem(); ossimNitfDesInformation desInfo; if(fileHeader->getDesInformation(desInfo, "XML")) { ossimRefPtr regDes = desInfo.getDesData(); if(regDes) { const std::vector dataBuffer = regDes->getDesDataBuffer(); if(!dataBuffer.empty()) { const char* buf = static_cast(&dataBuffer.front()); ossimString buffer(buf, buf + dataBuffer.size()); if(buffer.startsWith(" gpts(0); std::vector geolobPts(0); std::vector blockaPts(0); std::vector igeoloPts(0); //--- // Look for points from the GEOLOB tag if geographic coordinate // system. This has an origin and scale with good precision. // // NOTES: // 1) More precise than the BLOCKA // 2) Making an assumption this is not present if rotated. // Might need to test for rotation in BLOCKA and IGEOLO // 3) GEOLOB points are always rectangular as they are derived // from a single origin. //--- getGeolobPoints(hdr, geolobPts); //--- // Look for points from the BLOCKA tag. This may or may not be present. // If present since it has six digit precision use it for the points. //--- getBlockaPoints(hdr, blockaPts); if ( blockaPts.empty() ) { // Least precise IGEOLO field: ossimString geographicLocation = hdr->getGeographicLocation(); if ( geographicLocation.size() ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfProjectionFactory::makeGeographic DEBUG:" << "\ngeographicLocation: " << geographicLocation << std::endl; } if (coordinateSysetm == "G") { //--- // If coord system is G then format is: // Lat = ddmmssX // where d is degrees and m is minutes // and s is seconds and X is either N (North) or S (South). // Lon = dddmmssX // where d is degrees and m is minutes // and s is seconds and X is either N (North) or S (South). //--- parseGeographicString(geographicLocation, igeoloPts); } else if (coordinateSysetm == "D") { //--- // If coor system is D then format is: // +-dd.ddd +-dd.ddd four times where + is northern hemispher and // - is souther hemisphere for lat and longitude // + is easting and - is westing. //--- parseDecimalDegreesString(geographicLocation, igeoloPts); } } // matches: if ( geographicLocation.size() ) } // matches: if ( getBlockaPoints(hdr, gpts) == false ) bool isSkewedFlag = false; if ( blockaPts.size() ) { isSkewedFlag = isSkewed(blockaPts); if ( (isSkewedFlag == false) && geolobPts.size() ) { gpts = geolobPts; // Not skewed and have more accurate geolob points. } else { gpts = blockaPts; } } else if ( igeoloPts.size() ) { isSkewedFlag = isSkewed(igeoloPts); if ( (isSkewedFlag == false) && geolobPts.size() ) { gpts = geolobPts; // Not skewed and have more accurate geolob points. } else { gpts = igeoloPts; } } if (gpts.size() == 4) { ossimDpt scaleTest; computeScaleInDecimalDegrees(hdr, gpts, scaleTest); //--- // Getting very small value above 1.0 when dividing; hence the .000001. // Code calling arc cosine function in makeEquDistant(...) clamps to 1.0. //--- if ( !isSkewedFlag && (ossim::abs(scaleTest.y/scaleTest.x) <= 1.000001)) { proj = makeEuiDistant(hdr, gpts); } else { // Image is rotated. Make a Bilinear. proj = makeBilinear(hdr, gpts); } } if (traceDebug() && proj) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfProjectionFactory::makeGeographic DEBUG:" << "\nUpper left corner: " << gpts[0] << "\nUpper right corner: " << gpts[1] << "\nLower right corner: " << gpts[2] << "\nLower left corner: " << gpts[3] << "\n"; proj->print( ossimNotify(ossimNotifyLevel_DEBUG)); } } // matches: if (hdr) return proj; } ossimProjection* ossimNitfProjectionFactory::makeUtm( const ossimNitfImageHeader* hdr, const ossimString& coordinateSystem) const { ossimProjection* proj = 0; bool isBilinear = false; if (hdr) { ossimString geographicLocation = hdr->getGeographicLocation(); if ( geographicLocation.size() ) { std::vector utmPoints; ossim_uint32 zone; ossimDpt scale; char hemisphere = 'N'; bool status = true; if ( coordinateSystem == "U") { // Sets zone, hemisphere and utmPoints. Returns true on success. status = parseMgrsString(geographicLocation, zone, hemisphere, utmPoints); } else { // Sets zone and utmPoints. Void return... parseUtmString(geographicLocation, zone, utmPoints); if(coordinateSystem == "S") { hemisphere = 'S'; } } if ( status ) { if ( traceDebug() ) { std::string s; s.push_back(hemisphere); ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfProjectionFactory::makeUtm DEBUG" << "\ngeo string: " << geographicLocation << "\nutm zone: " << zone << "\nhemisphere: " << hemisphere << std::endl; for (ossim_uint32 i=0; i uproj = new ossimUtmProjection; uproj->setHemisphere(hemisphere); uproj->setZone(zone); if(isSkewed(utmPoints)) { std::vector gpts; // Try blocka points first as they are more accurate. if ( getBlockaPoints(hdr, gpts) == false ) { ossimGpt ul = uproj->inverse(utmPoints[0]); ossimGpt ur = uproj->inverse(utmPoints[1]); ossimGpt lr = uproj->inverse(utmPoints[2]); ossimGpt ll = uproj->inverse(utmPoints[3]); gpts.push_back(ul); gpts.push_back(ur); gpts.push_back(lr); gpts.push_back(ll); } //--- // Make a bilinear either from our skewed utm points or the points from the blocka // tag. //--- proj = makeBilinear(hdr, gpts); if(proj) scale = proj->getMetersPerPixel(); isBilinear = true; uproj = 0; // Done with utm projeciton } else { computeScaleInMeters(hdr, utmPoints, scale); //--- // Assign our projection to the return "proj". // Use ossimRefPtr::release the so we don't delete proj when uproj // goes out of scope. //--- proj = uproj.release(); } if( (scale.hasNans() == false)&&(!isBilinear) ) { //--- // Get the tie point. // // Look for the the BLOCKA tag which may or may not be present. // This has six digit precision in decimal degrees which equates to // about 0.11 meters (at equator) as compared to 1.0 accuaracy of the // IGEOLO field. //--- ossimDpt tie; std::vector gpts; if ( getBlockaPoints(hdr, gpts) ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfProjectionFactory::makeUtm DEBUG:" << "\nTie point from blocka: " << gpts[0] << endl; } tie = proj->forward(gpts[0]); tie.x += scale.x/2.0; tie.y -= scale.y/2.0; } else { tie.x = utmPoints[0].x + scale.x/2.0; tie.y = utmPoints[0].y - scale.y/2.0; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfProjectionFactory::makeUtm DEBUG:" << "\nTie point: " << tie << "\nScale: " << scale << endl; } // Set the tie and scale. ossimMapProjection* mproj = dynamic_cast(proj); if ( mproj ) { mproj->setUlEastingNorthing(tie); mproj->setMetersPerPixel(scale); } else // cannot cast { if ( proj ) { delete proj; proj = 0; } } } else if(isBilinear) { // blank } else // Scale has nans { if ( proj ) { delete proj; proj = 0; } } } // matches: if (status) } // matches: if ( geographicLocation.size() ) } // matches: if (hdr) return proj; } bool ossimNitfProjectionFactory::parseMgrsString(const ossimString& mgrsLocationString, ossim_uint32& zone, char& hemisphere, std::vector& utmPoints)const { bool result = false; // Start false. //--- // From spec: // UTM expressed in MGRS use the format zzBJKeeeeennnnn (15 characters). // Assumption Zone and hemisphere same for all corners. //--- if ( mgrsLocationString.size() >= 60 ) { // Split the location string into four separate ones. std::vector mgrsStr(4); // Corner strings. mgrsStr[0] = mgrsLocationString.substr(0, 15); mgrsStr[1] = mgrsLocationString.substr(15, 15); mgrsStr[2] = mgrsLocationString.substr(30, 15); mgrsStr[3] = mgrsLocationString.substr(45, 15); utmPoints.resize(4); long z = 0; ossim_float64 e=0.0; ossim_float64 n=0.0; result = true; // Set to true. //--- // Convert each string to Easting Northing. This also sets zone hemisphere. // Method takes long for zone. //--- for (ossim_uint32 i = 0; i < 4; ++i) { if ( Convert_OSSIM_MGRS_To_UTM(mgrsStr[i].c_str(), &z, &hemisphere, &e, &n) == 0 ) { utmPoints[i].x = e; utmPoints[i].y = n; } else { result = false; // Geotrans code errored on string. break; } } if (result) zone = static_cast(z); // Set the zone. } return result; } ossimProjection* ossimNitfProjectionFactory::makeEuiDistant( const ossimNitfImageHeader* hdr, const std::vector& gpts) const { ossimEquDistCylProjection* proj = 0; // Get the scale. ossimDpt scale; computeScaleInDecimalDegrees(hdr, gpts, scale); if (scale.hasNans()) { return proj; } // Make the projection. proj = new ossimEquDistCylProjection(); if ( scale.x ) { ossimGpt origin = proj->getOrigin(); //--- // ossimEquDistCylProjection uses the origin_latitude for meters per pixel (gsd) // computation. So is not set in tiff tags, compute to achieve the proper // horizontal scaling. //--- ossim_float64 x = (scale.y/scale.x); if ( x > 1.0 ) x = 1.0; // Limit to domain of arc cosine function. origin.lat = ossim::acosd(x); proj->setOrigin(origin); } // Shift the tie to the center of the pixel. ossimGpt tiePoint; tiePoint.latd(gpts[0].latd() - (scale.y/2.0)); tiePoint.lond(gpts[0].lond() + (scale.x/2.0)); // Set the tie points. proj->setUlTiePoints(tiePoint); // Set the scale. proj->setDecimalDegreesPerPixel(scale); return proj; } ossimProjection* ossimNitfProjectionFactory::makeBilinear( const ossimNitfImageHeader* hdr, const std::vector& gpts) const { double rows = hdr->getNumberOfRows(); double cols = hdr->getNumberOfCols(); ossimDpt ul(0.0, 0.0); ossimDpt ur(cols-1.0, 0.0); ossimDpt lr(cols-1.0, rows-1.0); ossimDpt ll(0.0, rows-1.0); ossimRefPtr proj; try { proj = new ossimBilinearProjection(ul, ur, lr, ll, gpts[0], gpts[1], gpts[2], gpts[3]); } catch(...) { proj = 0; } return proj.release(); } bool ossimNitfProjectionFactory::isSkewed( const std::vector& gpts) const { return !( (gpts[0].latd() == gpts[1].latd()) && (gpts[2].latd() == gpts[3].latd()) && (gpts[0].lond() == gpts[3].lond()) && (gpts[1].lond() == gpts[2].lond()) ); } bool ossimNitfProjectionFactory::isSkewed( const std::vector& dpts) const { return !( (dpts[0].y == dpts[1].y) && (dpts[2].y == dpts[3].y) && (dpts[0].x == dpts[3].x) && (dpts[1].x == dpts[2].x) ); } bool ossimNitfProjectionFactory::getBlockaPoints( const ossimNitfImageHeader* hdr, std::vector& gpts) const { if (!hdr) { return false; } ossimRefPtr tag = hdr->getTagData(ossimString("BLOCKA")); if (!tag) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfProjectionFactory::getBlockaPoints DEBUG:" << "\nBLOCKA tag not found." << std::endl; } return false; } if (gpts.size()) { gpts.clear(); } ossimNitfBlockaTag* blockaTag = PTR_CAST(ossimNitfBlockaTag, tag.get()); if (!blockaTag) { return false; } ossimDpt dpt; ossimGpt gpt; // Get the upper left or first row first column. blockaTag->getFrfcLoc(dpt); gpt.latd(dpt.y); gpt.lond(dpt.x); gpts.push_back(gpt); // Get the upper right or first row last column. blockaTag->getFrlcLoc(dpt); gpt.latd(dpt.y); gpt.lond(dpt.x); gpts.push_back(gpt); // Get the lower right or last row last column. blockaTag->getLrlcLoc(dpt); gpt.latd(dpt.y); gpt.lond(dpt.x); gpts.push_back(gpt); // Get the lower left or last row first column. blockaTag->getLrfcLoc(dpt); gpt.latd(dpt.y); gpt.lond(dpt.x); gpts.push_back(gpt); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfProjectionFactory::getBlockaPoints DEBUG:" << std::endl; for (int i=0; i<4; ++i) { ossimNotify(ossimNotifyLevel_DEBUG) << "gpt[" << i << "] " << gpts[i] << std::endl; } } return true; } bool ossimNitfProjectionFactory::getGeolobPoints( const ossimNitfImageHeader* hdr, std::vector& gpts) const { static const char MODULE[] = "ossimNitfProjectionFactory::getGeolobPoints"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool result = false; gpts.clear(); if ( hdr ) { ossimRefPtr tag = hdr->getTagData(ossimString("GEOLOB")); if ( tag.valid() ) { ossimNitfGeolobTag* geolob = dynamic_cast(tag.get()); if ( geolob ) { ossimDpt gsd( geolob->getDegreesPerPixelLon(), geolob->getDegreesPerPixelLat() ); if ( (gsd.x > 0.0 ) && (gsd.y > 0.0) ) { ossim_int32 rows = hdr->getNumberOfRows(); ossim_int32 cols = hdr->getNumberOfCols(); if ( (rows > 0) && (cols > 0) ) { ossimGpt gpt(0.0, 0.0, 0.0); ossimDpt origin( geolob->getLso(), geolob->getPso() ); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "origin: " << origin << "\ngsd: " << gsd << "\n"; } // Note: Edge to edge here as origin is shifted makeEuiDistant method. // UL: gpt.latd(origin.y); gpt.lond(origin.x); gpts.push_back(gpt); // UR: gpt.latd(origin.y); gpt.lond(origin.x + cols*gsd.x); gpts.push_back(gpt); // LR: gpt.latd(origin.y - rows*gsd.y); gpt.lond(origin.x + cols*gsd.x); gpts.push_back(gpt); // LL: gpt.latd(origin.y - rows*gsd.y); gpt.lond(origin.x); gpts.push_back(gpt); result = true; } } } } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No GEOLOB tag found.\n"; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status: " << (result?"true":"false") << "\n"; } return result; } void ossimNitfProjectionFactory::computeScaleInDecimalDegrees( const ossimNitfImageHeader* hdr, const std::vector& gpts, ossimDpt& scale) const { if ( !hdr || isSkewed(gpts)) { scale.makeNan(); return; } ossimIrect imageRect = hdr->getImageRect(); //--- // Calculate the scale. This assumes that the corner points are for the // edge of the corner pixels, not the center of the corner pixels. //--- double longitudeSize = 0.0; double latitudeSize = 0.0; if ( (gpts[1].lond() < 0.0) && (gpts[0].lond() >= 0) ) { //--- // Upper right negative(Western), upper left positive (Eastern). // Crossing date line maybe??? //--- longitudeSize = (gpts[1].lond() + 360.0) - gpts[0].lond(); } else { longitudeSize = gpts[1].lond() - gpts[0].lond(); } latitudeSize = gpts[0].latd() - gpts[2].latd(); double rows = imageRect.height(); double cols = imageRect.width(); // double rows = hdr->getNumberOfRows(); // double cols = hdr->getNumberOfCols(); if (!rows || !cols) { scale.makeNan(); return; } scale.y = latitudeSize / rows; scale.x = longitudeSize / cols; } void ossimNitfProjectionFactory::computeScaleInMeters( const ossimNitfImageHeader* hdr, const std::vector& dpts, ossimDpt& scale) const { if ( !hdr || isSkewed(dpts)) { scale.makeNan(); return; } ossimIrect imageRect = hdr->getImageRect(); //--- // Calculate the scale. This assumes that the corner points are for the // edge of the corner pixels, not the center of the corner pixels. //--- double eastingSize = 0.0; double northingSize = 0.0; eastingSize = fabs(dpts[1].x - dpts[0].x); northingSize = fabs(dpts[0].y - dpts[3].y); double rows = imageRect.height();//hdr->getNumberOfRows(); double cols = imageRect.width();//hdr->getNumberOfCols(); if (!rows || !cols) { scale.makeNan(); return; } scale.y = northingSize / rows; scale.x = eastingSize / cols; } void ossimNitfProjectionFactory::parseUtmString(const ossimString& utmLocation, ossim_uint32& zone, std::vector& utmPoints)const { ossim_uint32 idx = 0; ossimString z; ossimString east; ossimString north; z = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 2); idx += 2; east = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 6); idx += 6; north = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 7); idx += 7; utmPoints.push_back(ossimDpt(east.toDouble(), north.toDouble())); z = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 2); idx += 2; east = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 6); idx += 6; north = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 7); idx += 7; utmPoints.push_back(ossimDpt(east.toDouble(), north.toDouble())); z = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 2); idx += 2; east = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 6); idx += 6; north = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 7); idx += 7; utmPoints.push_back(ossimDpt(east.toDouble(), north.toDouble())); z = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 2); idx += 2; east = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 6); idx += 6; north = ossimString(utmLocation.begin() + idx, utmLocation.begin() + idx + 7); idx += 7; utmPoints.push_back(ossimDpt(east.toDouble(), north.toDouble())); zone = z.toUInt32(); } void ossimNitfProjectionFactory::parseGeographicString( const ossimString& geographicLocation, std::vector& gpts) const { gpts.clear(); if (geographicLocation.size() != 60) { return; } std::string::size_type geo_index = 0; for (int i=0; i<4; ++i) { //--- // We have to split up the geographicLocation string for the dms class. // // geographicLocation = ddmmssXdddmmssX (four times). // "dd mm ss X" has a string length of 10 // "ddd mm ss X" has a string length of 11 //--- std::string::size_type lat_index = 0; std::string::size_type lon_index = 0; const char SPACE = ' '; ossimString latString(10, SPACE); ossimString lonString(11, SPACE); // degrees latitude latString[lat_index++] = geographicLocation[geo_index++]; latString[lat_index++] = geographicLocation[geo_index++]; ++lat_index; // minutes latitude latString[lat_index++] = geographicLocation[geo_index++]; latString[lat_index++] = geographicLocation[geo_index++]; ++lat_index; // seconds latitude latString[lat_index++] = geographicLocation[geo_index++]; latString[lat_index++] = geographicLocation[geo_index++]; ++lat_index; // hemisphere latString[lat_index++] = geographicLocation[geo_index++]; // degrees longitude lonString[lon_index++] = geographicLocation[geo_index++]; lonString[lon_index++] = geographicLocation[geo_index++]; lonString[lon_index++] = geographicLocation[geo_index++]; ++lon_index; // minutes longitude lonString[lon_index++] = geographicLocation[geo_index++]; lonString[lon_index++] = geographicLocation[geo_index++]; ++lon_index; // seconds longitude lonString[lon_index++] = geographicLocation[geo_index++]; lonString[lon_index++] = geographicLocation[geo_index++]; ++lon_index; // hemisphere lonString[lon_index++] = geographicLocation[geo_index++]; // Convert to decimal degrees using the dms class. ossimGpt gpt; ossimDms dms(0.0); dms.setLatFlag(true); if ( ! dms.setDegrees(latString.c_str()) ) { gpts.clear(); return; } gpt.latd(dms.getDegrees()); dms.setLatFlag(false); if ( ! dms.setDegrees(lonString.c_str()) ) { gpts.clear(); return; } gpt.lond(dms.getDegrees()); gpts.push_back(gpt); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfProjectionFactory::parseGeographicString DEBUG:" << "\nground point[" << i << "]: " << gpt << std::endl; } } } void ossimNitfProjectionFactory::parseDecimalDegreesString(const ossimString& geographicLocation, std::vector& gpts) const { const char* bufPtr = geographicLocation.c_str(); ossimString ulLat(bufPtr, bufPtr + 7); bufPtr+=7; ossimString ulLon(bufPtr, bufPtr+8); bufPtr+=8; ossimString urLat(bufPtr, bufPtr + 7); bufPtr+=7; ossimString urLon(bufPtr, bufPtr+8); bufPtr+=8; ossimString lrLat(bufPtr, bufPtr + 7); bufPtr+=7; ossimString lrLon(bufPtr, bufPtr+8); bufPtr+=8; ossimString llLat(bufPtr, bufPtr + 7); bufPtr+=7; ossimString llLon(bufPtr, bufPtr+8); gpts.push_back(ossimGpt(ulLat.toDouble(), ulLon.toDouble())); gpts.push_back(ossimGpt(urLat.toDouble(), urLon.toDouble())); gpts.push_back(ossimGpt(lrLat.toDouble(), lrLon.toDouble())); gpts.push_back(ossimGpt(llLat.toDouble(), llLon.toDouble())); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfProjectionFactory::parseDecimalDegreesString DEBUG:" << "\nground point[" << 0 << "]: " << gpts[0] << "\nground point[" << 1 << "]: " << gpts[1] << "\nground point[" << 2 << "]: " << gpts[2] << "\nground point[" << 3 << "]: " << gpts[3] << std::endl; } } ossimNitfProjectionFactory::ossimNitfProjectionFactory(const ossimNitfProjectionFactory&) { } ossimNitfProjectionFactory& ossimNitfProjectionFactory::operator=(const ossimNitfProjectionFactory&) { return *this; } ossim-Miami-2.9.1/src/projection/ossimNitfRpcModel.cpp000066400000000000000000000317471352751253100227770ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimNitfRpcModel.cc // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: Contains implementation of class ossimNitfRpcModel. This // derived class implements the capability of reading Nitf RPC support // data. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimNitfRpcModel.cpp 16643 2010-02-22 21:32:43Z dburken $ #include RTTI_DEF1(ossimNitfRpcModel, "ossimNitfRpcModel", ossimRpcModel); #include #include #include #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include using namespace std; static ossimTrace traceExec ("ossimNitfRpcModel:exec"); static ossimTrace traceDebug ("ossimNitfRpcModel:debug"); static const char* RPC00A_TAG = "RPC00A"; static const char* RPC00B_TAG = "RPC00B"; static const char* PIAIMC_TAG = "PIAIMC"; static const char* STDIDC_TAG = "STDIDC"; static const char* USE00A_TAG = "USE00A"; ossimNitfRpcModel::ossimNitfRpcModel() : ossimRpcModel(), theDecimation(1.0) { } ossimNitfRpcModel::ossimNitfRpcModel(const ossimNitfRpcModel& rhs) : ossimRpcModel(rhs), theDecimation(1.0) { } //***************************************************************************** // CONSTRUCTOR: ossimNitfRpcModel // // Constructs given filename for NITF file // //***************************************************************************** ossimNitfRpcModel::ossimNitfRpcModel(const ossimFilename& nitfFile) : ossimRpcModel(), theDecimation(1.0) { if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfRpcModel::ossimNitfRpcModel(nitfFile): entering..." << std::endl; } if(!parseFile(nitfFile)) { if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfRpcModel::ossimNitfRpcModel(nitfFile): Unable to parse file " << nitfFile << std::endl; } ++theErrorStatus; } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfRpcModel::ossimNitfRpcModel(nitfFile): returning..." << std::endl; } } ossimObject* ossimNitfRpcModel::dup() const { return new ossimNitfRpcModel(*this); } bool ossimNitfRpcModel::parseFile(const ossimFilename& nitfFile, ossim_uint32 entryIndex) { ossimRefPtr file = new ossimNitfFile; if(!file->parseFile(nitfFile)) { setErrorStatus(); return false; } ossimRefPtr ih = file->getNewImageHeader(entryIndex); if(!ih) { setErrorStatus(); return false; } return parseImageHeader(ih.get()); } bool ossimNitfRpcModel::parseImageHeader(const ossimNitfImageHeader* ih) { // Do this first so we don't waste time if not rpc image. if (getRpcData(ih) == false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::parseFile DEBUG:" << "\nError parsing rpc tags. Aborting with error." << std::endl; } setErrorStatus(); return false; } //--- // Get the decimation if any from the header "IMAG" field. // // Look for string like: // "/2" = 1/2 // "/4 = 1/4 // ... // "/16 = 1/16 // If it is full resolution it should be "1.0" //--- ossimString os = ih->getImageMagnification(); if ( os.contains("/") ) { os = os.after("/"); ossim_float64 d = os.toFloat64(); if (d) { theDecimation = 1.0 / d; } } //*** // Fetch Image ID: //*** theImageID = ih->getImageId(); ossimIrect imageRect = ih->getImageRect(); //--- // Fetch Image Size: //--- theImageSize.line = static_cast(imageRect.height() / theDecimation); theImageSize.samp = static_cast(imageRect.width() / theDecimation); // Search for the STDID Tag to fetch mission (satellite) name: getSensorID(ih); //*** // Assign other data members: //*** theRefImgPt.line = theImageSize.line/2.0; theRefImgPt.samp = theImageSize.samp/2.0; theRefGndPt.lat = theLatOffset; theRefGndPt.lon = theLonOffset; theRefGndPt.hgt = theHgtOffset; //*** // Assign the bounding image space rectangle: //*** theImageClipRect = ossimDrect(0.0, 0.0, theImageSize.samp-1, theImageSize.line-1); //--- // Assign the bounding ground polygon: // // NOTE: We will use the base ossimRpcModel for transformation since all // of our calls are in full image space (not decimated). //--- ossimGpt v0, v1, v2, v3; ossimDpt ip0 (0.0, 0.0); ossimRpcModel::lineSampleHeightToWorld(ip0, theHgtOffset, v0); ossimDpt ip1 (theImageSize.samp-1.0, 0.0); ossimRpcModel::lineSampleHeightToWorld(ip1, theHgtOffset, v1); ossimDpt ip2 (theImageSize.samp-1.0, theImageSize.line-1.0); ossimRpcModel::lineSampleHeightToWorld(ip2, theHgtOffset, v2); ossimDpt ip3 (0.0, theImageSize.line-1.0); ossimRpcModel::lineSampleHeightToWorld(ip3, theHgtOffset, v3); theBoundGndPolygon = ossimPolygon (ossimDpt(v0), ossimDpt(v1), ossimDpt(v2), ossimDpt(v3)); updateModel(); // Set the ground reference point. ossimRpcModel::lineSampleHeightToWorld(theRefImgPt, theHgtOffset, theRefGndPt); if ( theRefGndPt.isLatNan() || theRefGndPt.isLonNan() ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::ossimNitfRpcModel DEBUG:" << "\nGround Reference Point not valid." << " Aborting with error..." << std::endl; } setErrorStatus(); return false; } //--- // This will set theGSD and theMeanGSD. This model doesn't need these but // others do. //--- try { computeGsd(); } catch (const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::ossimNitfRpcModel DEBUG:\n" << e.what() << std::endl; } } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfRpcModel::parseFile: returning..." << std::endl; } return true; } void ossimNitfRpcModel::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { // Get the full res (not decimated) point. ossimRpcModel::worldToLineSample(world_point, image_point); // Apply decimation. image_point.x = image_point.x * theDecimation; image_point.y = image_point.y * theDecimation; } void ossimNitfRpcModel::lineSampleHeightToWorld( const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const { // Convert image point to full res (not decimated) point. ossimDpt pt; pt.x = image_point.x / theDecimation; pt.y = image_point.y / theDecimation; // Call base... ossimRpcModel::lineSampleHeightToWorld(pt, heightEllipsoid, worldPoint); } bool ossimNitfRpcModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { // Save the decimation. kwl.add(prefix, "decimation", theDecimation); // Call base. return ossimRpcModel::saveState(kwl, prefix); } bool ossimNitfRpcModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Lookup decimation. const char* value = kwl.find(prefix, "decimation"); if (value) { theDecimation = ossimString(value).toFloat64(); if (theDecimation <= 0.0) { // Do not allow negative or "0.0"(divide by zero). theDecimation = 1.0; } } // Call base. return ossimRpcModel::loadState(kwl, prefix); } void ossimNitfRpcModel::getGsd(const ossimNitfImageHeader* ih) { theGSD.line = ossim::nan(); theGSD.samp = ossim::nan(); if (!ih) { return; } ossimRefPtr tag; tag = ih->getTagData(PIAIMC_TAG); if (tag.valid()) { ossimNitfPiaimcTag* p = PTR_CAST(ossimNitfPiaimcTag, tag.get()); if (p) { theGSD.line = p->getMeanGsdInMeters(); theGSD.samp = theGSD.line; return; } } tag = ih->getTagData(USE00A_TAG); if (tag.valid()) { ossimNitfUse00aTag* p = PTR_CAST(ossimNitfUse00aTag, tag.get()); if (p) { theGSD.line = p->getMeanGsdInMeters(); theGSD.samp = theGSD.line; } } } void ossimNitfRpcModel::getSensorID(const ossimNitfImageHeader* ih) { theSensorID = "UNKNOWN"; if (!ih) { return; } ossimRefPtr tag; tag = ih->getTagData(STDIDC_TAG); if (tag.valid()) { ossimNitfStdidcTag* p = PTR_CAST(ossimNitfStdidcTag, tag.get()); if (p) { theSensorID = p->getMission(); return; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::getSensorID DEBUG:" << "\ntheSensorID set to: " << theSensorID << endl; } } bool ossimNitfRpcModel::getRpcData(const ossimNitfImageHeader* ih) { if (!ih) { return false; } // Get the the RPC tag: ossimNitfRpcBase* rpcTag = 0; // Look for the RPC00B tag first. ossimRefPtr tag = ih->getTagData(RPC00B_TAG); if (tag.valid()) { rpcTag = PTR_CAST(ossimNitfRpcBase, tag.get()); } if (!rpcTag) { // Look for RPC00A tag. tag = ih->getTagData(RPC00A_TAG); if (tag.valid()) { rpcTag = PTR_CAST(ossimNitfRpcBase, tag.get()); } } if (!rpcTag) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::getRpcData DEBUG:" << "\nCould not find neither RPC tags <" << RPC00A_TAG << "> nor <" << RPC00B_TAG << "\nAborting with error..." << std::endl; } return false; } if ( rpcTag->getSuccess() == false ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::getRpcData DEBUG:" << "\nSuccess flag set to false." << "\nAborting with error..." << std::endl; } return false; } // Set the polynomial type. if (rpcTag->getRegisterTagName() == "RPC00B") { thePolyType = B; } else { thePolyType = A; } // Now parse the tag block for pertinent data: theBiasError = rpcTag->getErrorBias().toFloat64(); theRandError = rpcTag->getErrorRand().toFloat64(); theLineOffset = rpcTag->getLineOffset().toFloat64(); theSampOffset = rpcTag->getSampleOffset().toFloat64(); theLatOffset = rpcTag->getGeodeticLatOffset().toFloat64(); theLonOffset = rpcTag->getGeodeticLonOffset().toFloat64(); theHgtOffset = rpcTag->getGeodeticHeightOffset().toFloat64(); theLineScale = rpcTag->getLineScale().toFloat64(); theSampScale = rpcTag->getSampleScale().toFloat64(); theLatScale = rpcTag->getGeodeticLatScale().toFloat64(); theLonScale = rpcTag->getGeodeticLonScale().toFloat64(); theHgtScale = rpcTag->getGeodeticHeightScale().toFloat64(); // OBC has some data with negative height offsets that blows up the ray intersection with elevation model. The bilinear model seems more accurate than trying to work around this. if (ih->getImageSource().trim() == "OBC" && theHgtOffset < 0) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::getRpcData DEBUG:" << "\nHeight Offset will force invalid ellipsoid intersection." << "\nAborting with error..." << std::endl; } return false; } // Parse coefficients: ossim_uint32 i; for (i=0; i<20; ++i) { theLineNumCoef[i] = rpcTag->getLineNumeratorCoeff(i).toFloat64(); theLineDenCoef[i] = rpcTag->getLineDenominatorCoeff(i).toFloat64(); theSampNumCoef[i] = rpcTag->getSampleNumeratorCoeff(i).toFloat64(); theSampDenCoef[i] = rpcTag->getSampleDenominatorCoeff(i).toFloat64(); } // Assign other data members to default values: theNominalPosError = sqrt(theBiasError*theBiasError + theRandError*theRandError); // meters return true; } ossim-Miami-2.9.1/src/projection/ossimNitfRsmModel.cpp000066400000000000000000000302311352751253100227770ustar00rootroot00000000000000//--- // File: ossimNitfRsmModel.cpp // // RP // LIMITATIONS - This is supporting only the RSM features that have been // observed in current data samples and does not attempt to support the entire // RSM specification. // Examples of currently unsupported items include -> // 1. multiple RSMPC tags for different polynomials for separate image sections // 2. Error Covariance (this may gain priority as we have access to RSMECA data) // 3. Illumination model // 4. Rectangular coodinate system conversion (RSDIDA GRNDD = "R") //--- #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimNitfRsmModel, "ossimNitfRsmModel", ossimRsmModel); //--- // Define Trace flags for use within this file: //--- static ossimTrace traceExec ("ossimNitfRsmModel:exec"); static ossimTrace traceDebug ("ossimNitfRsmModel:debug"); ossimNitfRsmModel::ossimNitfRsmModel() : ossimRsmModel() { } ossimNitfRsmModel::ossimNitfRsmModel( const ossimNitfRsmModel& obj ) : ossimRsmModel(obj) { } const ossimNitfRsmModel& ossimNitfRsmModel::operator=( const ossimNitfRsmModel& rhs ) { if (this != &rhs) { ossimRsmModel::operator=(rhs); } return *this; } ossimNitfRsmModel::~ossimNitfRsmModel() { } bool ossimNitfRsmModel::parseFile( const ossimFilename& nitfFile, ossim_uint32 entryIndex ) { bool status = false; if ( nitfFile.exists() ) { ossimRefPtr file = new ossimNitfFile; if( file->parseFile(nitfFile) ) { ossimRefPtr ih = file->getNewImageHeader(entryIndex); if ( ih.valid() ) { status = parseImageHeader( ih.get() ); } } } if( !status ) { setErrorStatus(); } return status; } bool ossimNitfRsmModel::parseImageHeader(const ossimNitfImageHeader* ih) { static const char MODULE[] = "ossimNitfRsmModel::getRsmData"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entering..." << std::endl; } bool status = false; if ( getRsmData(ih) ) { theImageID = m_pca[0].m_iid; // tmp drb... theImageID = theImageID.trim(); ossimIrect imageRect = ih->getImageRect(); // Fetch Image Size: theImageSize.line = static_cast(imageRect.height()); theImageSize.samp = static_cast(imageRect.width()); // Assign other data members: theRefImgPt.line = theImageSize.line/2.0; theRefImgPt.samp = theImageSize.samp/2.0; // Assign the bounding image space rectangle: theImageClipRect = ossimDrect(0.0, 0.0, theImageSize.samp-1, theImageSize.line-1); ossimGpt v0, v1, v2, v3; ossimDpt ip0 (0.0, 0.0); lineSampleHeightToWorld(ip0, m_pca[0].m_znrmo, v0); ossimDpt ip1 (theImageSize.samp-1.0, 0.0); lineSampleHeightToWorld(ip1, m_pca[0].m_znrmo, v1); ossimDpt ip2 (theImageSize.samp-1.0, theImageSize.line-1.0); lineSampleHeightToWorld(ip2, m_pca[0].m_znrmo, v2); ossimDpt ip3 (0.0, theImageSize.line-1.0); lineSampleHeightToWorld(ip3, m_pca[0].m_znrmo, v3); theBoundGndPolygon = ossimPolygon (ossimDpt(v0), ossimDpt(v1), ossimDpt(v2), ossimDpt(v3)); updateModel(); // Set the ground reference point. lineSampleHeightToWorld(theRefImgPt, m_pca[0].m_znrmo, theRefGndPt); // Height could have nan if elevation is not set so check lat, lon individually. if ( ( theRefGndPt.isLatNan() == false ) && ( theRefGndPt.isLonNan() == false ) ) { //--- // This will set theGSD and theMeanGSD. This model doesn't need these but // others do. //--- try { computeGsd(); // Set return status. status = true; } catch (const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::ossimNitfRpcModel DEBUG:\n" << e.what() << std::endl; } setErrorStatus(); } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::ossimNitfRpcModel DEBUG:" << "\nGround Reference Point not valid(has nans)." << " Aborting with error..." << std::endl; } setErrorStatus(); } } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcModel::parseFile DEBUG:" << "\nError parsing rsm tags. Aborting with error." << std::endl; } setErrorStatus(); } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status: " << ( status ? "true" : "false" ) << "\n"; } return status; } // End: ossimNitfRsmModel::parseImageHeader(const ossimNitfImageHeader* ih) bool ossimNitfRsmModel::getRsmData(const ossimNitfImageHeader* ih) { static const char MODULE[] = "ossimNitfRsmModel::getRsmData"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entering..." << std::endl; } bool status = false; if ( ih ) { ossimRefPtr tag = 0; // RSMECA: const ossimString RSMECA_TAG = "RSMECA"; tag = ih->getTagData(RSMECA_TAG); if (tag.valid()) { ossimRefPtr rsmecaTag = dynamic_cast(tag.get()); if ( rsmecaTag.valid() ) { if ( initializeModel( rsmecaTag.get() ) ) { // RSMIDA: ossimString RSMIDA_TAG = "RSMIDA"; tag = ih->getTagData(RSMIDA_TAG); if (tag.valid()) { ossimRefPtr rsmidaTag = dynamic_cast( tag.get() ); if ( rsmidaTag.valid() ) { if ( m_ida.initialize( rsmidaTag.get() ) ) { // RSMPIA: const ossimString RSMPIA_TAG = "RSMPIA"; tag = ih->getTagData(RSMPIA_TAG); if (tag.valid()) { ossimRefPtr rsmpiaTag = dynamic_cast( tag.get() ); if ( rsmpiaTag.valid() ) { if ( m_pia.initialize( rsmpiaTag.get() ) ) { //--- // RSMPCA: // Multiple tags if image is sectioned. //--- const ossimString RSMPCA_TAG = "RSMPCA"; std::vector< const ossimNitfRegisteredTag* > tags; ih->getTagData( RSMPCA_TAG, tags ); if ( tags.size() == m_pia.m_tnis ) { for ( ossim_uint32 tagIndex = 0; tagIndex < m_pia.m_tnis; ++tagIndex ) { const ossimNitfRsmpcaTag* rsmpcaTag = dynamic_cast( tags[tagIndex] ); if ( rsmpcaTag ) { ossimRsmpca pca; if ( pca.initialize( rsmpcaTag ) ) { m_pca.push_back( pca ); } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING! RSMPCA[" << tagIndex << "] intitialization failed!" << std::endl; } } } // Call base ossimRsmModel::validate() for sanity check: status = validate(); } } // Matches: if ( m_pia.initialize( rsmpiaTag ) ) } } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "\nCould not find RSM tag: " << RSMPIA_TAG << "\nAborting with error..." << std::endl; } } } } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "\nCould not find RSM tag: " << RSMIDA_TAG << "\nAborting with error..." << std::endl; } } } } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfRsmModel::getRsmData WARNING!" << "\nCould not find RSM tag: " << RSMECA_TAG << "\nAborting with error..." << std::endl; } } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status: " << ( status ? "true" : "false" ) << "\n"; } return status; } // End: ossimNitfRsmModel::getRsmData(const ossimNitfImageHeader* ih) bool ossimNitfRsmModel::initializeModel( const ossimNitfRsmecaTag* rsmecaTag ) { bool status = false; if ( rsmecaTag ) { // TODO: status = true; } return status; } // End: ossimNitfRsmModel::initializeModel( rsmecaTag ) ossimObject* ossimNitfRsmModel::dup() const { return new ossimNitfRsmModel(*this); } bool ossimNitfRsmModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { static const char MODULE[] = "ossimNitfRsmModel::saveState"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } //--- // Hand off to base class for common stuff: // // Note: Class type "ossimKeywordNames::TYPE_KW" is saved in // ossimOject::saveState. //--- bool status = ossimRsmModel::saveState(kwl, prefix); if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return status; } bool ossimNitfRsmModel::loadState( const ossimKeywordlist& kwl, const char* prefix ) { static const char MODULE[] = "ossimNitfRsmModel::loadState"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool status = false; // Check for type match before preceeding: std::string myPrefix = ( prefix ? prefix : "" ); std::string type = kwl.findKey( myPrefix, std::string(ossimKeywordNames::TYPE_KW) ); if ( type == "ossimNitfRsmModel" ) { // Pass on to the base-class for parsing first: status = ossimRsmModel::loadState(kwl, prefix); } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status = " << (status?"true":"false") << "\n"; } return status; } ossim-Miami-2.9.1/src/projection/ossimObliqueMercatorProjection.cpp000066400000000000000000000650761352751253100256050ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimObliqueMercatorProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #define OMERC_NO_ERROR 0x0000 #define OMERC_LAT_ERROR 0x0001 #define OMERC_LON_ERROR 0x0002 #define OMERC_ORIGIN_LAT_ERROR 0x0004 #define OMERC_LAT1_ERROR 0x0008 #define OMERC_LAT2_ERROR 0x0010 #define OMERC_LON1_ERROR 0x0020 #define OMERC_LON2_ERROR 0x0040 #define OMERC_LAT1_LAT2_ERROR 0x0080 #define OMERC_DIFF_HEMISPHERE_ERROR 0x0100 #define OMERC_EASTING_ERROR 0x0200 #define OMERC_NORTHING_ERROR 0x0400 #define OMERC_A_ERROR 0x0800 #define OMERC_INV_F_ERROR 0x1000 #define OMERC_SCALE_FACTOR_ERROR 0x2000 #define OMERC_LON_WARNING 0x4000 RTTI_DEF1(ossimObliqueMercatorProjection, "ossimObliqueMercatorProjection", ossimMapProjection) #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef PI_OVER_4 # define PI_OVER_4 ( M_PI / 4.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define MIN_SCALE_FACTOR 0.3 #define MAX_SCALE_FACTOR 3.0 #define OMERC_t(lat, e_sinlat, e_over_2) (tan(PI_OVER_4 - lat / 2.0)) / \ (pow((1 - e_sinlat) / (1 + e_sinlat), e_over_2)) ossimObliqueMercatorProjection::ossimObliqueMercatorProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) : ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimObliqueMercatorProjection::ossimObliqueMercatorProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, const ossimGpt& point1, const ossimGpt& point2, double falseEasting, double falseNorthing, double scaleFactor) : ossimMapProjection(ellipsoid, origin) { setParameters(point1, point2, falseEasting, falseNorthing, scaleFactor); } void ossimObliqueMercatorProjection::update() { Set_Oblique_Mercator_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theCentralPoint1.latr(), theCentralPoint1.lonr(), theCentralPoint2.latr(), theCentralPoint2.lonr(), OMerc_False_Easting, OMerc_False_Northing, OMerc_Scale_Factor); theFalseEastingNorthing.x = OMerc_False_Easting; theFalseEastingNorthing.y = OMerc_False_Northing; ossimMapProjection::update(); } void ossimObliqueMercatorProjection::setFalseEasting(double falseEasting) { OMerc_False_Easting = falseEasting; update(); } void ossimObliqueMercatorProjection::setFalseNorthing(double falseNorthing) { OMerc_False_Northing = falseNorthing; update(); } void ossimObliqueMercatorProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { OMerc_False_Easting = falseEasting; OMerc_False_Northing = falseNorthing; update(); } void ossimObliqueMercatorProjection::setCentralPoint1(const ossimGpt& point) { theCentralPoint1 = point; update(); } void ossimObliqueMercatorProjection::setCentralPoint2(const ossimGpt& point) { theCentralPoint2 = point; update(); } void ossimObliqueMercatorProjection::setScaleFactor(double scaleFactor) { OMerc_Scale_Factor = scaleFactor; update(); } void ossimObliqueMercatorProjection::setParameters(const ossimGpt& point1, const ossimGpt& point2, double falseEasting, double falseNorthing, double scaleFactor) { theCentralPoint1 = point1; theCentralPoint2 = point2; OMerc_False_Easting = falseEasting; OMerc_False_Northing = falseNorthing; OMerc_Scale_Factor = scaleFactor; update(); } void ossimObliqueMercatorProjection::setDefaults() { // initialize the central points to be 5 degrees about the origin. OMerc_Delta_Northing = 40000000.0; OMerc_Delta_Easting = 40000000.0; theCentralPoint1.latd(theOrigin.latd() - 5.0); theCentralPoint1.lond(theOrigin.lond() - 5.0); theCentralPoint2.latd(theOrigin.latd() + 5.0); theCentralPoint2.lond(theOrigin.lond() + 5.0); theCentralPoint1.clampLat(-90.0, 90.0); theCentralPoint1.clampLon(-180.0, 180.0); theCentralPoint2.clampLat(-90.0, 90.0); theCentralPoint2.clampLon(-180.0, 180.0); OMerc_False_Easting = 0.0; OMerc_False_Northing = 0.0; OMerc_Scale_Factor = 1.0; } ossimGpt ossimObliqueMercatorProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Oblique_Mercator_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimObliqueMercatorProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Oblique_Mercator(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimObliqueMercatorProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, ossimKeywordNames::SCALE_FACTOR_KW, OMerc_Scale_Factor, true); kwl.add(prefix, ossimKeywordNames::CENTRAL_POINT1_LAT_KW, theCentralPoint1.latd(), true); kwl.add(prefix, ossimKeywordNames::CENTRAL_POINT1_LON_KW, theCentralPoint1.lond(), true); kwl.add(prefix, ossimKeywordNames::CENTRAL_POINT2_LAT_KW, theCentralPoint2.latd(), true); kwl.add(prefix, ossimKeywordNames::CENTRAL_POINT2_LON_KW, theCentralPoint2.lond(), true); return ossimMapProjection::saveState(kwl, prefix); } bool ossimObliqueMercatorProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); const char* point1Lat = kwl.find(prefix, ossimKeywordNames::CENTRAL_POINT1_LAT_KW); const char* point1Lon = kwl.find(prefix, ossimKeywordNames::CENTRAL_POINT1_LON_KW); const char* point2Lat = kwl.find(prefix, ossimKeywordNames::CENTRAL_POINT2_LAT_KW); const char* point2Lon = kwl.find(prefix, ossimKeywordNames::CENTRAL_POINT2_LON_KW); const char* scale = kwl.find(prefix, ossimKeywordNames::SCALE_FACTOR_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimObliqueMercatorProjection)) { OMerc_False_Easting = theFalseEastingNorthing.x; OMerc_False_Northing = theFalseEastingNorthing.y; if(point1Lat&&point1Lon&&point2Lat&&point2Lon) { theCentralPoint1.latd(ossimString(point1Lat).toDouble()); theCentralPoint1.lond(ossimString(point1Lon).toDouble()); theCentralPoint2.latd(ossimString(point2Lat).toDouble()); theCentralPoint2.lond(ossimString(point2Lon).toDouble()); } if(scale) { OMerc_Scale_Factor = ossimString(scale).toDouble(); } } update(); return flag; } /* * FUNCTIONS */ long ossimObliqueMercatorProjection::Set_Oblique_Mercator_Parameters(double a, double f, double Origin_Latitude, double Latitude_1, double Longitude_1, double Latitude_2, double Longitude_2, double False_Easting, double False_Northing, double Scale_Factor) { /* BEGIN Set_Oblique_Mercator_Parameters */ /* * The function Set_Oblique_Mercator_Parameters receives the ellipsoid parameters and * projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise OMERC_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude, in radians, at which the (input) * point scale factor is 1.0 * Latitude_1 : Latitude, in radians, of first point lying on * central line (input) * Longitude_1 : Longitude, in radians, of first point lying on * central line (input) * Latitude_2 : Latitude, in radians, of second point lying on * central line (input) * Longitude_2 : Longitude, in radians, of second point lying on * central line (input) * False_Easting : A coordinate value, in meters, assigned to the * central meridian of the projection (input) * False_Northing : A coordinate value, in meters, assigned to the * origin latitude of the projection (input) * Scale_Factor : Multiplier which reduces distances in the * projection to the actual distance on the * ellipsoid (input) */ // double inv_f = 1 / f; double es2, one_MINUS_es2; double cos_olat, cos_olat2; double sin_olat, sin_olat2, es2_sin_olat2; double t0, t1, t2; double D, D2, D2_MINUS_1, sqrt_D2_MINUS_1; double H, L, LH; double E2; double F, G, J, P; double dlon; long Error_Code = OMERC_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= OMERC_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= OMERC_INV_F_ERROR; // } // if ((Origin_Latitude <= -PI_OVER_2) || (Origin_Latitude >= PI_OVER_2)) // { /* origin latitude out of range - can not be at a pole */ // Error_Code |= OMERC_ORIGIN_LAT_ERROR; // } // if ((Latitude_1 <= -PI_OVER_2) || (Latitude_1 >= PI_OVER_2)) // { /* first latitude out of range - can not be at a pole */ // Error_Code |= OMERC_LAT1_ERROR; // } // if ((Latitude_2 <= -PI_OVER_2) || (Latitude_2 >= PI_OVER_2)) // { /* second latitude out of range - can not be at a pole */ // Error_Code |= OMERC_LAT2_ERROR; // } // if (Latitude_1 == 0.0) // { /* first latitude can not be at the equator */ // Error_Code |= OMERC_LAT1_ERROR; // } // if (Latitude_1 == Latitude_2) // { /* first and second latitudes can not be equal */ // Error_Code |= OMERC_LAT1_LAT2_ERROR; // } // if (((Latitude_1 < 0.0) && (Latitude_2 > 0.0)) || // ((Latitude_1 > 0.0) && (Latitude_2 < 0.0))) // { /*first and second points can not be in different hemispheres */ // Error_Code |= OMERC_DIFF_HEMISPHERE_ERROR; // } // if ((Longitude_1 < -PI) || (Longitude_1 > TWO_PI)) // { /* first longitude out of range */ // Error_Code |= OMERC_LON1_ERROR; // } // if ((Longitude_2 < -PI) || (Longitude_2 > TWO_PI)) // { /* first longitude out of range */ // Error_Code |= OMERC_LON2_ERROR; // } // if ((Scale_Factor < MIN_SCALE_FACTOR) || (Scale_Factor > MAX_SCALE_FACTOR)) // { /* scale factor out of range */ // Error_Code |= OMERC_SCALE_FACTOR_ERROR; // } if (!Error_Code) { /* no errors */ OMerc_a = a; OMerc_f = f; OMerc_Origin_Lat = Origin_Latitude; OMerc_Lat_1 = Latitude_1; OMerc_Lat_2 = Latitude_2; OMerc_Lon_1 = Longitude_1; OMerc_Lon_2 = Longitude_2; OMerc_Scale_Factor = Scale_Factor; OMerc_False_Northing = False_Northing; OMerc_False_Easting = False_Easting; es2 = 2 * OMerc_f - OMerc_f * OMerc_f; es = sqrt(es2); one_MINUS_es2 = 1 - es2; es_OVER_2 = es / 2.0; cos_olat = cos(OMerc_Origin_Lat); cos_olat2 = cos_olat * cos_olat; sin_olat = sin(OMerc_Origin_Lat); sin_olat2 = sin_olat * sin_olat; es2_sin_olat2 = es2 * sin_olat2; OMerc_B = sqrt(1 + (es2 * cos_olat2 * cos_olat2) / one_MINUS_es2); OMerc_A = (OMerc_a * OMerc_B * OMerc_Scale_Factor * sqrt(one_MINUS_es2)) / (1.0 - es2_sin_olat2); A_over_B = OMerc_A / OMerc_B; B_over_A = OMerc_B / OMerc_A; t0 = OMERC_t(OMerc_Origin_Lat, es * sin_olat, es_OVER_2); t1 = OMERC_t(OMerc_Lat_1, es * sin(OMerc_Lat_1), es_OVER_2); t2 = OMERC_t(OMerc_Lat_2, es * sin(OMerc_Lat_2), es_OVER_2); D = (OMerc_B * sqrt(one_MINUS_es2)) / (cos_olat * sqrt(1.0 - es2_sin_olat2)); D2 = D * D; if (D2 < 1.0) D2 = 1.0; D2_MINUS_1 = D2 - 1.0; sqrt_D2_MINUS_1 = sqrt(D2_MINUS_1); if (D2_MINUS_1 > 1.0e-10) { if (OMerc_Origin_Lat >= 0.0) OMerc_E = (D + sqrt_D2_MINUS_1) * pow(t0, OMerc_B); else OMerc_E = (D - sqrt_D2_MINUS_1) * pow(t0, OMerc_B); } else OMerc_E = D * pow(t0, OMerc_B); H = pow(t1, OMerc_B); L = pow(t2, OMerc_B); F = OMerc_E / H; G = (F - 1.0 / F) / 2.0; E2 = OMerc_E * OMerc_E; LH = L * H; J = (E2 - LH) / (E2 + LH); P = (L - H) / (L + H); dlon = OMerc_Lon_1 - OMerc_Lon_2; if (dlon < -M_PI ) OMerc_Lon_2 -= TWO_PI; if (dlon > M_PI) OMerc_Lon_2 += TWO_PI; dlon = OMerc_Lon_1 - OMerc_Lon_2; OMerc_Origin_Long = (OMerc_Lon_1 + OMerc_Lon_2) / 2.0 - (atan(J * tan(OMerc_B * dlon / 2.0) / P)) / OMerc_B; dlon = OMerc_Lon_1 - OMerc_Origin_Long; // if (dlon < -M_PI ) // OMerc_Origin_Long -= TWO_PI; // if (dlon > M_PI) // OMerc_Origin_Long += TWO_PI; dlon = OMerc_Lon_1 - OMerc_Origin_Long; OMerc_gamma = atan(sin(OMerc_B * dlon) / G); cos_gamma = cos(OMerc_gamma); sin_gamma = sin(OMerc_gamma); OMerc_azimuth = asin(D * sin_gamma); cos_azimuth = cos(OMerc_azimuth); sin_azimuth = sin(OMerc_azimuth); if (OMerc_Origin_Lat >= 0) OMerc_u = A_over_B * atan(sqrt_D2_MINUS_1/cos_azimuth); else OMerc_u = -A_over_B * atan(sqrt_D2_MINUS_1/cos_azimuth); } /* End if(!Error_Code) */ return (Error_Code); } /* End Set_Oblique_Mercator_Parameters */ void ossimObliqueMercatorProjection::Get_Oblique_Mercator_Parameters(double *a, double *f, double *Origin_Latitude, double *Latitude_1, double *Longitude_1, double *Latitude_2, double *Longitude_2, double *False_Easting, double *False_Northing, double *Scale_Factor)const { /* Begin Get_Oblique_Mercator_Parameters */ /* * The function Get_Oblique_Mercator_Parameters returns the current ellipsoid * parameters and Oblique Mercator projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude, in radians, at which the (output) * point scale factor is 1.0 * Latitude_1 : Latitude, in radians, of first point lying on * central line (output) * Longitude_1 : Longitude, in radians, of first point lying on * central line (output) * Latitude_2 : Latitude, in radians, of second point lying on * central line (output) * Longitude_2 : Longitude, in radians, of second point lying on * central line (output) * False_Easting : A coordinate value, in meters, assigned to the * central meridian of the projection (output) * False_Northing : A coordinate value, in meters, assigned to the * origin latitude of the projection (output) * Scale_Factor : Multiplier which reduces distances in the * projection to the actual distance on the * ellipsoid (output) */ *a = OMerc_a; *f = OMerc_f; *Origin_Latitude = OMerc_Origin_Lat; *Latitude_1 = OMerc_Lat_1; *Longitude_1 = OMerc_Lon_1; *Latitude_2 = OMerc_Lat_2; *Longitude_2 = OMerc_Lon_2; *Scale_Factor = OMerc_Scale_Factor; *False_Easting = OMerc_False_Easting; *False_Northing = OMerc_False_Northing; return; } /* End Get_Azimuthal_Equidistant_Parameters */ long ossimObliqueMercatorProjection::Convert_Geodetic_To_Oblique_Mercator(double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Oblique_Mercator */ /* * The function Convert_Geodetic_To_Oblique_Mercator converts geodetic (latitude and * longitude) coordinates to Oblique Mercator projection (easting and * northing) coordinates, according to the current ellipsoid and Oblique Mercator * projection parameters. If any errors occur, the error code(s) are returned * by the function, otherwise OMERC_NO_ERROR is returned. * * Latitude : Latitude (phi), in radians (input) * Longitude : Longitude (lambda), in radians (input) * Easting : Easting (X), in meters (output) * Northing : Northing (Y), in meters (output) */ double dlam, B_dlam, cos_B_dlam; double t, S, T, V, U; double Q, Q_inv; /* Coordinate axes defined with respect to the azimuth of the center line */ /* Natural origin*/ double v = 0; double u = 0; long Error_Code = OMERC_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= OMERC_LAT_ERROR; // } // if ((Longitude < -M_PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= OMERC_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - OMerc_Origin_Long; // if (fabs(dlam) >= PI_OVER_2) // { /* Distortion will result if Longitude is 90 degrees or more from the Central Meridian */ // Error_Code |= OMERC_LON_WARNING; // } // if (dlam > M_PI) // { // dlam -= TWO_PI; // } // if (dlam < -M_PI) // { // dlam += TWO_PI; // } if (fabs(fabs(Latitude) - PI_OVER_2) > 1.0e-10) { t = OMERC_t(Latitude, es * sin(Latitude), es_OVER_2); Q = OMerc_E / pow(t, OMerc_B); Q_inv = 1.0 / Q; S = (Q - Q_inv) / 2.0; T = (Q + Q_inv) / 2.0; B_dlam = OMerc_B * dlam; V = sin(B_dlam); U = ((-1.0 * V * cos_gamma) + (S * sin_gamma)) / T; if (fabs(fabs(U) - 1.0) < 1.0e-10) { /* Point projects into infinity */ Error_Code |= OMERC_LON_ERROR; } else { v = A_over_B * log((1.0 - U) / (1.0 + U)) / 2.0; cos_B_dlam = cos(B_dlam); if (fabs(cos_B_dlam) < 1.0e-10) u = OMerc_A * B_dlam; else u = A_over_B * atan(((S * cos_gamma) + (V * sin_gamma)) / cos_B_dlam); } } else { if (Latitude > 0.0) v = A_over_B * log(tan(PI_OVER_4 - (OMerc_gamma / 2.0))); else v = A_over_B * log(tan(PI_OVER_4 + (OMerc_gamma / 2.0))); u = A_over_B * Latitude; } u = u - OMerc_u; *Easting = OMerc_False_Easting + v * cos_azimuth + u * sin_azimuth; *Northing = OMerc_False_Northing + u * cos_azimuth - v * sin_azimuth; } return (Error_Code); } /* End Convert_Geodetic_To_Oblique_Mercator */ long ossimObliqueMercatorProjection::Convert_Oblique_Mercator_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* Begin Convert_Oblique_Mercator_To_Geodetic */ /* * The function Convert_Oblique_Mercator_To_Geodetic converts Oblique Mercator projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Oblique Mercator projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise OMERC_NO_ERROR is returned. * * Easting : Easting (X), in meters (input) * Northing : Northing (Y), in meters (input) * Latitude : Latitude (phi), in radians (output) * Longitude : Longitude (lambda), in radians (output) */ double dx, dy; /* Coordinate axes defined with respect to the azimuth of the center line */ /* Natural origin*/ double u, v; double Q_prime, Q_prime_inv; double S_prime, T_prime, V_prime, U_prime; double t; double es_sin; double u_B_over_A; double phi; double temp_phi = 0.0; long Error_Code = OMERC_NO_ERROR; // if ((Easting < (OMerc_False_Easting - OMerc_Delta_Easting)) // || (Easting > (OMerc_False_Easting + OMerc_Delta_Easting))) // { /* Easting out of range */ // Error_Code |= OMERC_EASTING_ERROR; // } // if ((Northing < (OMerc_False_Northing - OMerc_Delta_Northing)) // || (Northing > (OMerc_False_Northing + OMerc_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= OMERC_NORTHING_ERROR; // } if (!Error_Code) { dy = Northing - OMerc_False_Northing; dx = Easting - OMerc_False_Easting; v = dx * cos_azimuth - dy * sin_azimuth; u = dy * cos_azimuth + dx * sin_azimuth; u = u + OMerc_u; Q_prime = exp(-1.0 * (v * B_over_A )); Q_prime_inv = 1.0 / Q_prime; S_prime = (Q_prime - Q_prime_inv) / 2.0; T_prime = (Q_prime + Q_prime_inv) / 2.0; u_B_over_A = u * B_over_A; V_prime = sin(u_B_over_A); U_prime = (V_prime * cos_gamma + S_prime * sin_gamma) / T_prime; if (fabs(fabs(U_prime) - 1.0) < 1.0e-10) { if (U_prime > 0) *Latitude = PI_OVER_2; else *Latitude = -PI_OVER_2; *Longitude = OMerc_Origin_Long; } else { t = pow(OMerc_E / sqrt((1.0 + U_prime) / (1.0 - U_prime)), 1.0 / OMerc_B); phi = PI_OVER_2 - 2.0 * atan(t); while (fabs(phi - temp_phi) > 1.0e-10) { temp_phi = phi; es_sin = es * sin(phi); phi = PI_OVER_2 - 2.0 * atan(t * pow((1.0 - es_sin) / (1.0 + es_sin), es_OVER_2)); } *Latitude = phi; *Longitude = OMerc_Origin_Long - atan2((S_prime * cos_gamma - V_prime * sin_gamma), cos(u_B_over_A)) / OMerc_B; } // if (fabs(*Latitude) < 2.0e-7) /* force lat to 0 to avoid -0 degrees */ // *Latitude = 0.0; // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > PI) // *Longitude -= TWO_PI; // if (*Longitude < -PI) // *Longitude += TWO_PI; // if (fabs(*Longitude) < 2.0e-7) /* force lon to 0 to avoid -0 degrees */ // *Longitude = 0.0; // if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ // *Longitude = PI; // else if (*Longitude < -PI) // *Longitude = -PI; // if (fabs(*Longitude - OMerc_Origin_Long) >= PI_OVER_2) // { /* Distortion will result if Longitude is 90 degrees or more from the Central Meridian */ // Error_Code |= OMERC_LON_WARNING; // } } return (Error_Code); } /* End Convert_Oblique_Mercator_To_Geodetic */ //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimObliqueMercatorProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimObliqueMercatorProjection* p = dynamic_cast(&proj); if (!p) return false; if (theCentralPoint1 != p->theCentralPoint1) return false; if (theCentralPoint2 != p->theCentralPoint2) return false; if (!ossim::almostEqual(OMerc_Scale_Factor,p->OMerc_Scale_Factor)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimOptimizableProjection.cpp000066400000000000000000000014471352751253100247570ustar00rootroot00000000000000#include RTTI_DEF(ossimOptimizableProjection, "ossimOptimizableProjection"); ossimOptimizableProjection::ossimOptimizableProjection() {} ossimOptimizableProjection::ossimOptimizableProjection( const ossimOptimizableProjection& /* source */ ) { // nothing to do (copy) in base. } ossimOptimizableProjection::~ossimOptimizableProjection() {} ossimOptimizableProjection& ossimOptimizableProjection::operator=( const ossimOptimizableProjection& /* source */ ) { // nothing to do (copy) in base. // if (this != & source) // { // } return *this; } bool ossimOptimizableProjection::setupOptimizer( const ossimString& /* setup */ ) { return false; } bool ossimOptimizableProjection::needsInitialState() const { return false; } ossim-Miami-2.9.1/src/projection/ossimOrthoGraphicProjection.cpp000066400000000000000000000377201352751253100250740ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans OrthoGraphic projection code. //******************************************************************* // $Id: ossimOrthoGraphicProjection.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include RTTI_DEF1(ossimOrthoGraphicProjection, "ossimOrthoGraphicProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define MAX_LAT ( (M_PI * 90) / 180.0 ) /* 90 degrees in radians */ #define ORTH_NO_ERROR 0x0000 #define ORTH_LAT_ERROR 0x0001 #define ORTH_LON_ERROR 0x0002 #define ORTH_EASTING_ERROR 0x0004 #define ORTH_NORTHING_ERROR 0x0008 #define ORTH_ORIGIN_LAT_ERROR 0x0010 #define ORTH_CENT_MER_ERROR 0x0020 #define ORTH_A_ERROR 0x0040 #define ORTH_B_ERROR 0x0080 #define ORTH_A_LESS_B_ERROR 0x0100 #define ORTH_RADIUS_ERROR 0x0200 ossimOrthoGraphicProjection::ossimOrthoGraphicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimOrthoGraphicProjection::ossimOrthoGraphicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Orth_False_Easting = falseEasting; Orth_False_Northing = falseNorthing; update(); } void ossimOrthoGraphicProjection::update() { Set_Orthographic_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Orth_False_Easting, Orth_False_Northing); theFalseEastingNorthing.x = Orth_False_Easting; theFalseEastingNorthing.y = Orth_False_Northing; ossimMapProjection::update(); } void ossimOrthoGraphicProjection::setFalseEasting(double falseEasting) { Orth_False_Easting = falseEasting; update(); } void ossimOrthoGraphicProjection::setFalseNorthing(double falseNorthing) { Orth_False_Northing = falseNorthing; update(); } void ossimOrthoGraphicProjection::setDefaults() { Orth_False_Easting = 0.0; Orth_False_Northing = 0.0; } void ossimOrthoGraphicProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Orth_False_Easting = falseEasting; Orth_False_Northing = falseNorthing; update(); } void ossimOrthoGraphicProjection::getGroundClipPoints(ossimGeoPolygon& gpts)const { gpts.addPoint(ossimGpt(theOrigin.latd(), theOrigin.lond()-90.0, 0.0, theDatum)); gpts.addPoint(ossimGpt(theOrigin.latd()+90.0, theOrigin.lond(), 0.0, theDatum)); gpts.addPoint(ossimGpt(theOrigin.latd(), theOrigin.lond()+90.0, 0.0, theDatum)); gpts.addPoint(ossimGpt(theOrigin.latd()-90.0, theOrigin.lond(), 0.0, theDatum)); } ossimGpt ossimOrthoGraphicProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; ossimGpt result; if(Convert_Orthographic_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon)==ORTH_NO_ERROR) { result.datum(theDatum); result.latr(lat); result.lonr(lon); } else { result.makeNan(); } return result; } ossimDpt ossimOrthoGraphicProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; ossimDpt result; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } if(Convert_Geodetic_To_Orthographic(gpt.latr(), gpt.lonr(), &easting, &northing) == ORTH_NO_ERROR) { result = ossimDpt(easting, northing); } else { result.makeNan(); } return result; } bool ossimOrthoGraphicProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimOrthoGraphicProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimOrthoGraphicProjection)) { Orth_False_Easting = theFalseEastingNorthing.x; Orth_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimOrthoGraphicProjection::Set_Orthographic_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing) { /* BEGIN Set_Orthographic_Parameters */ /* * The function Set_Orthographic_Parameters receives the ellipsoid parameters and * projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise ORTH_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ // double inv_f = 1 / f; long Error_Code = ORTH_NO_ERROR; if (a <= 0.0) { /* Semi-major axis must be greater than zero */ Error_Code |= ORTH_A_ERROR; } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= ORTH_INV_F_ERROR; // } if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) { /* origin latitude out of range */ Error_Code |= ORTH_ORIGIN_LAT_ERROR; } if ((Central_Meridian < -M_PI) || (Central_Meridian > TWO_PI)) { /* origin longitude out of range */ Error_Code |= ORTH_CENT_MER_ERROR; } if (!Error_Code) { /* no errors */ Orth_a = a; Orth_f = f; es2 = 2 * Orth_f - Orth_f * Orth_f; es4 = es2 * es2; es6 = es4 * es2; Ra = Orth_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 /3024.0); Orth_Origin_Lat = Origin_Latitude; Sin_Orth_Origin_Lat = sin(Orth_Origin_Lat); Cos_Orth_Origin_Lat = cos(Orth_Origin_Lat); // if (Central_Meridian > M_PI) // Central_Meridian -= TWO_PI; Orth_Origin_Long = Central_Meridian; Orth_False_Easting = False_Easting; Orth_False_Northing = False_Northing; } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Set_Orthographic_Parameters */ void ossimOrthoGraphicProjection::Get_Orthographic_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* BEGIN Get_Orthographic_Parameters */ /* * The function Get_Orthographic_Parameters returns the current ellipsoid * parameters and Orthographic projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Orth_a; *f = Orth_f; *Origin_Latitude = Orth_Origin_Lat; *Central_Meridian = Orth_Origin_Long; *False_Easting = Orth_False_Easting; *False_Northing = Orth_False_Northing; return; } /* END OF Get_Orthographic_Parameters */ long ossimOrthoGraphicProjection::Convert_Geodetic_To_Orthographic (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Orthographic */ /* * The function Convert_Geodetic_To_Orthographic converts geodetic (latitude and * longitude) coordinates to Orthographic projection (easting and northing) * coordinates, according to the current ellipsoid and Orthographic projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise ORTH_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double slat = sin(Latitude); double clat = cos(Latitude); double dlam; /* Longitude - Central Meridan */ double clat_cdlam; double cos_c; /* Value used to determine whether the point is beyond viewing. If zero or positive, the point is within view. */ long Error_Code = ORTH_NO_ERROR; if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) { /* Latitude out of range */ Error_Code |= ORTH_LAT_ERROR; } if ((Longitude < -M_PI) || (Longitude > TWO_PI)) { /* Longitude out of range */ Error_Code|= ORTH_LON_ERROR; } dlam = Longitude - Orth_Origin_Long; clat_cdlam = clat * cos(dlam); cos_c = Sin_Orth_Origin_Lat * slat + Cos_Orth_Origin_Lat * clat_cdlam; if (cos_c < 0.0) { /* Point is out of view. Will return longitude out of range message since no point out of view is implemented. */ Error_Code |= ORTH_LON_ERROR; } if (!Error_Code) { /* no errors */ if (dlam > M_PI) { dlam -= TWO_PI; } if (dlam < -M_PI) { dlam += TWO_PI; } *Easting = Ra * clat * sin(dlam) + Orth_False_Easting; *Northing = Ra * (Cos_Orth_Origin_Lat * slat - Sin_Orth_Origin_Lat * clat_cdlam) + Orth_False_Northing; } return (Error_Code); } /* END OF Convert_Geodetic_To_Orthographic */ long ossimOrthoGraphicProjection::Convert_Orthographic_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Orthographic_To_Geodetic */ /* * The function Convert_Orthographic_To_Geodetic converts Orthographic projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Orthographic projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise ORTH_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double cc; double cos_cc, sin_cc; double rho; double dx, dy; double atan_dx_over_dy; // double temp; double rho_OVER_Ra; long Error_Code = ORTH_NO_ERROR; if ((Easting > (Orth_False_Easting + Ra)) || (Easting < (Orth_False_Easting - Ra))) { /* Easting out of range */ Error_Code |= ORTH_EASTING_ERROR; } if ((Northing > (Orth_False_Northing + Ra)) || (Northing < (Orth_False_Northing - Ra))) { /* Northing out of range */ Error_Code |= ORTH_NORTHING_ERROR; } if (!Error_Code) { double temp = sqrt(Easting * Easting + Northing * Northing); if ((temp > (Orth_False_Easting + Ra)) || (temp > (Orth_False_Northing + Ra)) || (temp < (Orth_False_Easting - Ra)) || (temp < (Orth_False_Northing - Ra))) { /* Point is outside of projection area */ Error_Code |= ORTH_RADIUS_ERROR; } } if (!Error_Code) { dx = Easting - Orth_False_Easting; dy = Northing - Orth_False_Northing; atan_dx_over_dy = atan(dx / dy); rho = sqrt(dx * dx + dy * dy); if (rho == 0.0) { *Latitude = Orth_Origin_Lat; *Longitude = Orth_Origin_Long; } else { rho_OVER_Ra = rho / Ra; if (rho_OVER_Ra > 1.0) rho_OVER_Ra = 1.0; else if (rho_OVER_Ra < -1.0) rho_OVER_Ra = -1.0; cc = asin(rho_OVER_Ra); cos_cc = cos(cc); sin_cc = sin(cc); *Latitude = asin(cos_cc * Sin_Orth_Origin_Lat + (dy * sin_cc * Cos_Orth_Origin_Lat / rho)); if (Orth_Origin_Lat == MAX_LAT) *Longitude = Orth_Origin_Long - atan_dx_over_dy; else if (Orth_Origin_Lat == -MAX_LAT) *Longitude = Orth_Origin_Long + atan_dx_over_dy; else *Longitude = Orth_Origin_Long + atan(dx * sin_cc / (rho * Cos_Orth_Origin_Lat * cos_cc - dy * Sin_Orth_Origin_Lat * sin_cc)); // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > M_PI) // *Longitude -= TWO_PI; // if (*Longitude < -M_PI) // *Longitude += TWO_PI; // if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ // *Longitude = M_PI; // else if (*Longitude < -M_PI) // *Longitude = -M_PI; } } return (Error_Code); } /* END OF Convert_Orthographic_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimPolarStereoProjection.cpp000066400000000000000000000420161352751253100247340ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Polar Stereographic projection code. //******************************************************************* // $Id: ossimPolarStereoProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include RTTI_DEF1(ossimPolarStereoProjection, "ossimPolarStereoProjection", ossimMapProjection) /************************************************************************/ /* DEFINES * */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define POLAR_POW(EsSin) pow((1.0 - EsSin) / (1.0 + EsSin), es_OVER_2) #define POLAR_NO_ERROR 0x0000 #define POLAR_LAT_ERROR 0x0001 #define POLAR_LON_ERROR 0x0002 #define POLAR_ORIGIN_LAT_ERROR 0x0004 #define POLAR_ORIGIN_LON_ERROR 0x0008 #define POLAR_EASTING_ERROR 0x0010 #define POLAR_NORTHING_ERROR 0x0020 #define POLAR_A_ERROR 0x0040 #define POLAR_B_ERROR 0x0080 #define POLAR_A_LESS_B_ERROR 0x0100 #define POLAR_RADIUS_ERROR 0x0200 /************************************************************************/ /* GLOBAL DECLARATIONS * */ const double PI_Over_4 = (M_PI / 4.0); ossimPolarStereoProjection::ossimPolarStereoProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); // Polar_Delta_Easting = 12713601.0; // Polar_Delta_Northing = 12713601.0; } ossimPolarStereoProjection::ossimPolarStereoProjection(const ossimEllipsoid& /* ellipsoid */, const ossimGpt& /* origin */, double falseEasting, double falseNorthing) { Polar_False_Easting = falseEasting; Polar_False_Northing = falseNorthing; Polar_Delta_Easting = 12713601.0; Polar_Delta_Northing = 12713601.0; update(); } void ossimPolarStereoProjection::update() { Set_Polar_Stereographic_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Polar_False_Easting, Polar_False_Northing); theFalseEastingNorthing.x = Polar_False_Easting; theFalseEastingNorthing.y = Polar_False_Northing; ossimMapProjection::update(); } void ossimPolarStereoProjection::setFalseEasting(double falseEasting) { Polar_False_Easting = falseEasting; update(); } void ossimPolarStereoProjection::setFalseNorthing(double falseNorthing) { Polar_False_Northing = falseNorthing; update(); } void ossimPolarStereoProjection::setDefaults() { Polar_False_Easting = 0.0; Polar_False_Northing = 0.0; } void ossimPolarStereoProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Polar_False_Easting = falseEasting; Polar_False_Northing = falseNorthing; update(); } ossimGpt ossimPolarStereoProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Polar_Stereographic_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimPolarStereoProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Polar_Stereographic(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimPolarStereoProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimPolarStereoProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimPolarStereoProjection)) { Polar_False_Easting = theFalseEastingNorthing.x; Polar_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /************************************************************************/ /* FUNCTIONS * */ long ossimPolarStereoProjection::Set_Polar_Stereographic_Parameters (double a, double f, double Latitude_of_True_Scale, double Longitude_Down_from_Pole, double False_Easting, double False_Northing) { /* BEGIN Set_Polar_Stereographic_Parameters */ /* * The function Set_Polar_Stereographic_Parameters receives the ellipsoid * parameters and Polar Stereograpic projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, error * code(s) are returned by the function, otherwise POLAR_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Latitude_of_True_Scale : Latitude of true scale, in radians (input) * Longitude_Down_from_Pole : Longitude down from pole, in radians (input) * False_Easting : Easting (X) at center of projection, in meters (input) * False_Northing : Northing (Y) at center of projection, in meters (input) */ double es2; double slat, clat; double essin; double one_PLUS_es, one_MINUS_es; double pow_es; double temp; // double inv_f = 1 / f; const double epsilon = 1.0e-2; long Error_Code = POLAR_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= POLAR_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= POLAR_INV_F_ERROR; // } // if ((Latitude_of_True_Scale < -PI_OVER_2) || (Latitude_of_True_Scale > PI_OVER_2)) // { /* Origin Latitude out of range */ // Error_Code |= POLAR_ORIGIN_LAT_ERROR; // } // if ((Longitude_Down_from_Pole < -PI) || (Longitude_Down_from_Pole > TWO_PI)) // { /* Origin Longitude out of range */ // Error_Code |= POLAR_ORIGIN_LON_ERROR; // } if (!Error_Code) { /* no errors */ Polar_a = a; two_Polar_a = 2.0 * Polar_a; Polar_f = f; if (Longitude_Down_from_Pole > M_PI) Longitude_Down_from_Pole -= TWO_PI; if (Latitude_of_True_Scale < 0) { Southern_Hemisphere = 1; Polar_Origin_Lat = -Latitude_of_True_Scale; Polar_Origin_Long = -Longitude_Down_from_Pole; } else { Southern_Hemisphere = 0; Polar_Origin_Lat = Latitude_of_True_Scale; Polar_Origin_Long = Longitude_Down_from_Pole; } Polar_False_Easting = False_Easting; Polar_False_Northing = False_Northing; es2 = 2 * Polar_f - Polar_f * Polar_f; es = sqrt(es2); es_OVER_2 = es / 2.0; if (fabs(fabs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) { slat = sin(Polar_Origin_Lat); essin = es * slat; pow_es = POLAR_POW(essin); clat = cos(Polar_Origin_Lat); mc = clat / sqrt(1.0 - essin * essin); Polar_a_mc = Polar_a * mc; tc = tan(PI_Over_4 - Polar_Origin_Lat / 2.0) / pow_es; } else { one_PLUS_es = 1.0 + es; one_MINUS_es = 1.0 - es; e4 = sqrt(pow(one_PLUS_es, one_PLUS_es) * pow(one_MINUS_es, one_MINUS_es)); } } /* Calculate Radius */ Convert_Geodetic_To_Polar_Stereographic(0, Polar_Origin_Long, &temp, &Polar_Delta_Northing); Polar_Delta_Northing = fabs(Polar_Delta_Northing) + epsilon; Polar_Delta_Easting = Polar_Delta_Northing; return (Error_Code); } /* END OF Set_Polar_Stereographic_Parameters */ void ossimPolarStereoProjection::Get_Polar_Stereographic_Parameters (double *a, double *f, double *Latitude_of_True_Scale, double *Longitude_Down_from_Pole, double *False_Easting, double *False_Northing)const { /* BEGIN Get_Polar_Stereographic_Parameters */ /* * The function Get_Polar_Stereographic_Parameters returns the current * ellipsoid parameters and Polar projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Latitude_of_True_Scale : Latitude of true scale, in radians (output) * Longitude_Down_from_Pole : Longitude down from pole, in radians (output) * False_Easting : Easting (X) at center of projection, in meters (output) * False_Northing : Northing (Y) at center of projection, in meters (output) */ *a = Polar_a; *f = Polar_f; *Latitude_of_True_Scale = Polar_Origin_Lat; *Longitude_Down_from_Pole = Polar_Origin_Long; *False_Easting = Polar_False_Easting; *False_Northing = Polar_False_Northing; return; } /* END OF Get_Polar_Stereographic_Parameters */ long ossimPolarStereoProjection::Convert_Geodetic_To_Polar_Stereographic (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Polar_Stereographic */ /* * The function Convert_Geodetic_To_Polar_Stereographic converts geodetic * coordinates (latitude and longitude) to Polar Stereographic coordinates * (easting and northing), according to the current ellipsoid * and Polar Stereographic projection parameters. If any errors occur, error * code(s) are returned by the function, otherwise POLAR_NO_ERROR is returned. * * Latitude : Latitude, in radians (input) * Longitude : Longitude, in radians (input) * Easting : Easting (X), in meters (output) * Northing : Northing (Y), in meters (output) */ double dlam; double slat; double essin; double t; double rho; double pow_es; long Error_Code = POLAR_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= POLAR_LAT_ERROR; // } // if ((Latitude < 0) && (Southern_Hemisphere == 0)) // { /* Latitude and Origin Latitude in different hemispheres */ // Error_Code |= POLAR_LAT_ERROR; // } // if ((Latitude > 0) && (Southern_Hemisphere == 1)) // { /* Latitude and Origin Latitude in different hemispheres */ // Error_Code |= POLAR_LAT_ERROR; // } // if ((Longitude < -PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= POLAR_LON_ERROR; // } if (!Error_Code) { /* no errors */ if (fabs(fabs(Latitude) - PI_OVER_2) < 1.0e-10) { *Easting = 0.0; *Northing = 0.0; } else { if (Southern_Hemisphere != 0) { Longitude *= -1.0; Latitude *= -1.0; } dlam = Longitude - Polar_Origin_Long; // if (dlam > M_PI) // { // dlam -= TWO_PI; // } // if (dlam < -M_PI) // { // dlam += TWO_PI; // } slat = sin(Latitude); essin = es * slat; pow_es = POLAR_POW(essin); t = tan(PI_Over_4 - Latitude / 2.0) / pow_es; if (fabs(fabs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) rho = Polar_a_mc * t / tc; else rho = two_Polar_a * t / e4; *Easting = rho * sin(dlam) + Polar_False_Easting; if (Southern_Hemisphere != 0) { *Easting *= -1.0; *Northing = rho * cos(dlam) + Polar_False_Northing; } else *Northing = -rho * cos(dlam) + Polar_False_Northing; } } return (Error_Code); } /* END OF Convert_Geodetic_To_Polar_Stereographic */ long ossimPolarStereoProjection::Convert_Polar_Stereographic_To_Geodetic (double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Polar_Stereographic_To_Geodetic */ /* * The function Convert_Polar_Stereographic_To_Geodetic converts Polar * Stereographic coordinates (easting and northing) to geodetic * coordinates (latitude and longitude) according to the current ellipsoid * and Polar Stereographic projection Parameters. If any errors occur, the * code(s) are returned by the function, otherwise POLAR_NO_ERROR * is returned. * * Easting : Easting (X), in meters (input) * Northing : Northing (Y), in meters (input) * Latitude : Latitude, in radians (output) * Longitude : Longitude, in radians (output) * */ double dy, dx; double rho; double t; double PHI, sin_PHI; double tempPHI = 0.0; double essin; double pow_es; // double temp; long Error_Code = POLAR_NO_ERROR; // if ((Easting > (Polar_False_Easting + Polar_Delta_Easting)) || // (Easting < (Polar_False_Easting - Polar_Delta_Easting))) // { /* Easting out of range */ // Error_Code |= POLAR_EASTING_ERROR; // } // if ((Northing > (Polar_False_Northing + Polar_Delta_Northing)) || // (Northing < (Polar_False_Northing - Polar_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= POLAR_NORTHING_ERROR; // } // if (!Error_Code) // { // temp = sqrt(Easting * Easting + Northing * Northing); // if ((temp > (Polar_False_Easting + Polar_Delta_Easting)) || // (temp > (Polar_False_Northing + Polar_Delta_Northing)) || // (temp < (Polar_False_Easting - Polar_Delta_Easting)) || // (temp < (Polar_False_Northing - Polar_Delta_Northing))) // { /* Point is outside of projection area */ // Error_Code |= POLAR_RADIUS_ERROR; // } // } if (!Error_Code) { /* no errors */ dy = Northing - Polar_False_Northing; dx = Easting - Polar_False_Easting; if ((dy == 0.0) && (dx == 0.0)) { *Latitude = PI_OVER_2; *Longitude = Polar_Origin_Long; } else { if (Southern_Hemisphere != 0) { dy *= -1.0; dx *= -1.0; } rho = sqrt(dx * dx + dy * dy); if (fabs(fabs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) t = rho * tc / (Polar_a_mc); else t = rho * e4 / (two_Polar_a); PHI = PI_OVER_2 - 2.0 * atan(t); while (fabs(PHI - tempPHI) > 1.0e-10) { tempPHI = PHI; sin_PHI = sin(PHI); essin = es * sin_PHI; pow_es = POLAR_POW(essin); PHI = PI_OVER_2 - 2.0 * atan(t * pow_es); } *Latitude = PHI; *Longitude = Polar_Origin_Long + atan2(dx, -dy); // if (*Longitude > M_PI) // *Longitude -= TWO_PI; // else if (*Longitude < -M_PI) // *Longitude += TWO_PI; // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ // *Longitude = M_PI; // else if (*Longitude < -M_PI) // *Longitude = -M_PI; } if (Southern_Hemisphere != 0) { *Latitude *= -1.0; *Longitude *= -1.0; } } return (Error_Code); } /* END OF Convert_Polar_Stereographic_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimPolarst.c000066400000000000000000000404411352751253100215240ustar00rootroot00000000000000/***************************************************************************/ /* RSC IDENTIFIER: POLAR STEREOGRAPHIC * * * ABSTRACT * * This component provides conversions between geodetic (latitude and * longitude) coordinates and Polar Stereographic (easting and northing) * coordinates. * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid * value is found the error code is combined with the current error code * using the bitwise or. This combining allows multiple error codes to * be returned. The possible error codes are: * * POLAR_NO_ERROR : No errors occurred in function * POLAR_LAT_ERROR : Latitude outside of valid range * (-90 to 90 degrees) * POLAR_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees) * POLAR_ORIGIN_LAT_ERROR : Latitude of true scale outside of valid * range (-90 to 90 degrees) * POLAR_ORIGIN_LON_ERROR : Longitude down from pole outside of valid * range (-180 to 360 degrees) * POLAR_EASTING_ERROR : Easting outside of valid range, * depending on ellipsoid and * projection parameters * POLAR_NORTHING_ERROR : Northing outside of valid range, * depending on ellipsoid and * projection parameters * POLAR_RADIUS_ERROR : Coordinates too far from pole, * depending on ellipsoid and * projection parameters * POLAR_A_ERROR : Semi-major axis less than or equal to zero * POLAR_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * * * REUSE NOTES * * POLAR STEREOGRAPHIC is intended for reuse by any application that * performs a Polar Stereographic projection. * * * REFERENCES * * Further information on POLAR STEREOGRAPHIC can be found in the * Reuse Manual. * * * POLAR STEREOGRAPHIC originated from : * U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * * LICENSES * * None apply to this component. * * * RESTRICTIONS * * POLAR STEREOGRAPHIC has no restrictions. * * * ENVIRONMENT * * POLAR STEREOGRAPHIC was tested and certified in the following * environments: * * 1. Solaris 2.5 with GCC, version 2.8.1 * 2. Window 95 with MS Visual C++, version 6 * * * MODIFICATIONS * * Date Description * ---- ----------- * 06-11-95 Original Code * 03-01-97 Original Code * * */ /************************************************************************/ /* * INCLUDES */ #include #include /* * math.h - Standard C math library * polarst.h - Is for prototype error checking */ /************************************************************************/ /* DEFINES * */ #define PI 3.14159265358979323e0 /* PI */ #define PI_OVER_2 (PI / 2.0) #define TWO_PI (2.0 * PI) #define POLAR_POW(EsSin) pow((1.0 - EsSin) / (1.0 + EsSin), es_OVER_2) /************************************************************************/ /* GLOBAL DECLARATIONS * */ const double PI_Over_4 = (PI / 4.0); /* Ellipsoid Parameters, default to WGS 84 */ static double Polar_a = 6378137.0; /* Semi-major axis of ellipsoid in meters */ static double Polar_f = 1 / 298.257223563; /* Flattening of ellipsoid */ static double es = 0.08181919084262188000; /* Eccentricity of ellipsoid */ static double es_OVER_2 = .040909595421311; /* es / 2.0 */ static double Southern_Hemisphere = 0; /* Flag variable */ static double mc = 1.0; static double tc = 1.0; static double e4 = 1.0033565552493; static double Polar_a_mc = 6378137.0; /* Polar_a * mc */ static double two_Polar_a = 12756274.0; /* 2.0 * Polar_a */ /* Polar Stereographic projection Parameters */ static double Polar_Origin_Lat = ((PI * 90) / 180); /* Latitude of origin in radians */ static double Polar_Origin_Long = 0.0; /* Longitude of origin in radians */ static double Polar_False_Easting = 0.0; /* False easting in meters */ static double Polar_False_Northing = 0.0; /* False northing in meters */ /* Maximum variance for easting and northing values for WGS 84. */ static double Polar_Delta_Easting = 12713601.0; static double Polar_Delta_Northing = 12713601.0; /* These state variables are for optimization purposes. The only function * that should modify them is Set_Polar_Stereographic_Parameters. */ /************************************************************************/ /* FUNCTIONS * */ long Set_Polar_Stereographic_Parameters (double a, double f, double Latitude_of_True_Scale, double Longitude_Down_from_Pole, double False_Easting, double False_Northing) { /* BEGIN Set_Polar_Stereographic_Parameters */ /* * The function Set_Polar_Stereographic_Parameters receives the ellipsoid * parameters and Polar Stereograpic projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, error * code(s) are returned by the function, otherwise POLAR_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Latitude_of_True_Scale : Latitude of true scale, in radians (input) * Longitude_Down_from_Pole : Longitude down from pole, in radians (input) * False_Easting : Easting (X) at center of projection, in meters (input) * False_Northing : Northing (Y) at center of projection, in meters (input) */ double es2; double slat, clat; double essin; double one_PLUS_es, one_MINUS_es; double pow_es; double temp; double inv_f = 1 / f; const double epsilon = 1.0e-2; long Error_Code = POLAR_NO_ERROR; if (a <= 0.0) { /* Semi-major axis must be greater than zero */ Error_Code |= POLAR_A_ERROR; } if ((inv_f < 250) || (inv_f > 350)) { /* Inverse flattening must be between 250 and 350 */ Error_Code |= POLAR_INV_F_ERROR; } if ((Latitude_of_True_Scale < -PI_OVER_2) || (Latitude_of_True_Scale > PI_OVER_2)) { /* Origin Latitude out of range */ Error_Code |= POLAR_ORIGIN_LAT_ERROR; } if ((Longitude_Down_from_Pole < -PI) || (Longitude_Down_from_Pole > TWO_PI)) { /* Origin Longitude out of range */ Error_Code |= POLAR_ORIGIN_LON_ERROR; } if (!Error_Code) { /* no errors */ Polar_a = a; two_Polar_a = 2.0 * Polar_a; Polar_f = f; if (Longitude_Down_from_Pole > PI) Longitude_Down_from_Pole -= TWO_PI; if (Latitude_of_True_Scale < 0) { Southern_Hemisphere = 1; Polar_Origin_Lat = -Latitude_of_True_Scale; Polar_Origin_Long = -Longitude_Down_from_Pole; } else { Southern_Hemisphere = 0; Polar_Origin_Lat = Latitude_of_True_Scale; Polar_Origin_Long = Longitude_Down_from_Pole; } Polar_False_Easting = False_Easting; Polar_False_Northing = False_Northing; es2 = 2 * Polar_f - Polar_f * Polar_f; es = sqrt(es2); es_OVER_2 = es / 2.0; if (fabs(fabs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) { slat = sin(Polar_Origin_Lat); essin = es * slat; pow_es = POLAR_POW(essin); clat = cos(Polar_Origin_Lat); mc = clat / sqrt(1.0 - essin * essin); Polar_a_mc = Polar_a * mc; tc = tan(PI_Over_4 - Polar_Origin_Lat / 2.0) / pow_es; } else { one_PLUS_es = 1.0 + es; one_MINUS_es = 1.0 - es; e4 = sqrt(pow(one_PLUS_es, one_PLUS_es) * pow(one_MINUS_es, one_MINUS_es)); } } /* Calculate Radius */ Convert_Geodetic_To_Polar_Stereographic(0, Polar_Origin_Long, &temp, &Polar_Delta_Northing); Polar_Delta_Northing = fabs(Polar_Delta_Northing) + epsilon; Polar_Delta_Easting = Polar_Delta_Northing; return (Error_Code); } /* END OF Set_Polar_Stereographic_Parameters */ void Get_Polar_Stereographic_Parameters (double *a, double *f, double *Latitude_of_True_Scale, double *Longitude_Down_from_Pole, double *False_Easting, double *False_Northing) { /* BEGIN Get_Polar_Stereographic_Parameters */ /* * The function Get_Polar_Stereographic_Parameters returns the current * ellipsoid parameters and Polar projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Latitude_of_True_Scale : Latitude of true scale, in radians (output) * Longitude_Down_from_Pole : Longitude down from pole, in radians (output) * False_Easting : Easting (X) at center of projection, in meters (output) * False_Northing : Northing (Y) at center of projection, in meters (output) */ *a = Polar_a; *f = Polar_f; *Latitude_of_True_Scale = Polar_Origin_Lat; *Longitude_Down_from_Pole = Polar_Origin_Long; *False_Easting = Polar_False_Easting; *False_Northing = Polar_False_Northing; return; } /* END OF Get_Polar_Stereographic_Parameters */ long Convert_Geodetic_To_Polar_Stereographic (double Latitude, double Longitude, double *Easting, double *Northing) { /* BEGIN Convert_Geodetic_To_Polar_Stereographic */ /* * The function Convert_Geodetic_To_Polar_Stereographic converts geodetic * coordinates (latitude and longitude) to Polar Stereographic coordinates * (easting and northing), according to the current ellipsoid * and Polar Stereographic projection parameters. If any errors occur, error * code(s) are returned by the function, otherwise POLAR_NO_ERROR is returned. * * Latitude : Latitude, in radians (input) * Longitude : Longitude, in radians (input) * Easting : Easting (X), in meters (output) * Northing : Northing (Y), in meters (output) */ double dlam; double slat; double essin; double t; double rho; double pow_es; long Error_Code = POLAR_NO_ERROR; if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) { /* Latitude out of range */ Error_Code |= POLAR_LAT_ERROR; } if ((Latitude < 0) && (Southern_Hemisphere == 0)) { /* Latitude and Origin Latitude in different hemispheres */ Error_Code |= POLAR_LAT_ERROR; } if ((Latitude > 0) && (Southern_Hemisphere == 1)) { /* Latitude and Origin Latitude in different hemispheres */ Error_Code |= POLAR_LAT_ERROR; } if ((Longitude < -PI) || (Longitude > TWO_PI)) { /* Longitude out of range */ Error_Code |= POLAR_LON_ERROR; } if (!Error_Code) { /* no errors */ if (fabs(fabs(Latitude) - PI_OVER_2) < 1.0e-10) { *Easting = 0.0; *Northing = 0.0; } else { if (Southern_Hemisphere != 0) { Longitude *= -1.0; Latitude *= -1.0; } dlam = Longitude - Polar_Origin_Long; if (dlam > PI) { dlam -= TWO_PI; } if (dlam < -PI) { dlam += TWO_PI; } slat = sin(Latitude); essin = es * slat; pow_es = POLAR_POW(essin); t = tan(PI_Over_4 - Latitude / 2.0) / pow_es; if (fabs(fabs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) rho = Polar_a_mc * t / tc; else rho = two_Polar_a * t / e4; *Easting = rho * sin(dlam) + Polar_False_Easting; if (Southern_Hemisphere != 0) { *Easting *= -1.0; *Northing = rho * cos(dlam) + Polar_False_Northing; } else *Northing = -rho * cos(dlam) + Polar_False_Northing; } } return (Error_Code); } /* END OF Convert_Geodetic_To_Polar_Stereographic */ long Convert_Polar_Stereographic_To_Geodetic (double Easting, double Northing, double *Latitude, double *Longitude) { /* BEGIN Convert_Polar_Stereographic_To_Geodetic */ /* * The function Convert_Polar_Stereographic_To_Geodetic converts Polar * Stereographic coordinates (easting and northing) to geodetic * coordinates (latitude and longitude) according to the current ellipsoid * and Polar Stereographic projection Parameters. If any errors occur, the * code(s) are returned by the function, otherwise POLAR_NO_ERROR * is returned. * * Easting : Easting (X), in meters (input) * Northing : Northing (Y), in meters (input) * Latitude : Latitude, in radians (output) * Longitude : Longitude, in radians (output) * */ double dy, dx; double rho; double t; double PHI, sin_PHI; double tempPHI = 0.0; double essin; double pow_es; double temp; long Error_Code = POLAR_NO_ERROR; if ((Easting > (Polar_False_Easting + Polar_Delta_Easting)) || (Easting < (Polar_False_Easting - Polar_Delta_Easting))) { /* Easting out of range */ Error_Code |= POLAR_EASTING_ERROR; } if ((Northing > (Polar_False_Northing + Polar_Delta_Northing)) || (Northing < (Polar_False_Northing - Polar_Delta_Northing))) { /* Northing out of range */ Error_Code |= POLAR_NORTHING_ERROR; } if (!Error_Code) { temp = sqrt(Easting * Easting + Northing * Northing); if ((temp > (Polar_False_Easting + Polar_Delta_Easting)) || (temp > (Polar_False_Northing + Polar_Delta_Northing)) || (temp < (Polar_False_Easting - Polar_Delta_Easting)) || (temp < (Polar_False_Northing - Polar_Delta_Northing))) { /* Point is outside of projection area */ Error_Code |= POLAR_RADIUS_ERROR; } } if (!Error_Code) { /* no errors */ dy = Northing - Polar_False_Northing; dx = Easting - Polar_False_Easting; if ((dy == 0.0) && (dx == 0.0)) { *Latitude = PI_OVER_2; *Longitude = Polar_Origin_Long; } else { if (Southern_Hemisphere != 0) { dy *= -1.0; dx *= -1.0; } rho = sqrt(dx * dx + dy * dy); if (fabs(fabs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10) t = rho * tc / (Polar_a_mc); else t = rho * e4 / (two_Polar_a); PHI = PI_OVER_2 - 2.0 * atan(t); while (fabs(PHI - tempPHI) > 1.0e-10) { tempPHI = PHI; sin_PHI = sin(PHI); essin = es * sin_PHI; pow_es = POLAR_POW(essin); PHI = PI_OVER_2 - 2.0 * atan(t * pow_es); } *Latitude = PHI; *Longitude = Polar_Origin_Long + atan2(dx, -dy); if (*Longitude > PI) *Longitude -= TWO_PI; else if (*Longitude < -PI) *Longitude += TWO_PI; if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ *Latitude = PI_OVER_2; else if (*Latitude < -PI_OVER_2) *Latitude = -PI_OVER_2; if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ *Longitude = PI; else if (*Longitude < -PI) *Longitude = -PI; } if (Southern_Hemisphere != 0) { *Latitude *= -1.0; *Longitude *= -1.0; } } return (Error_Code); } /* END OF Convert_Polar_Stereographic_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimPolyconicProjection.cpp000066400000000000000000000430021352751253100244300ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Polyconic projection code. //******************************************************************* // $Id: ossimPolyconicProjection.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include RTTI_DEF1(ossimPolyconicProjection, "ossimPolyconicProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define POLY_COEFF_TIMES_SIN(coeff, x, latit) (coeff * (sin (x * latit))) #define POLY_M(c0lat,c1s2lat,c2s4lat,c3s6lat) (Poly_a*(c0lat - c1s2lat + c2s4lat - c3s6lat)) #define FLOAT_EQ(x,v,epsilon) (((v - epsilon) < x) && (x < (v + epsilon))) #define FOURTY_ONE (41.0 * M_PI / 180.0) /* 41 degrees in radians */ #define POLY_NO_ERROR 0x0000 #define POLY_LAT_ERROR 0x0001 #define POLY_LON_ERROR 0x0002 #define POLY_EASTING_ERROR 0x0004 #define POLY_NORTHING_ERROR 0x0008 #define POLY_ORIGIN_LAT_ERROR 0x0010 #define POLY_CENT_MER_ERROR 0x0020 #define POLY_A_ERROR 0x0040 #define POLY_B_ERROR 0x0080 #define POLY_A_LESS_B_ERROR 0x0100 #define POLY_LON_WARNING 0x0200 ossimPolyconicProjection::ossimPolyconicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimPolyconicProjection::ossimPolyconicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Poly_False_Easting = falseEasting; Poly_False_Northing = falseNorthing; Poly_Max_Easting = 20037509.0; Poly_Max_Northing = 15348215.0; Poly_Min_Easting = -20037509.0; Poly_Min_Northing = -15348215.0; update(); } void ossimPolyconicProjection::update() { Set_Polyconic_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Poly_False_Easting, Poly_False_Northing); theFalseEastingNorthing.x = Poly_False_Easting; theFalseEastingNorthing.y = Poly_False_Northing; ossimMapProjection::update(); } void ossimPolyconicProjection::setFalseEasting(double falseEasting) { Poly_False_Easting = falseEasting; update(); } void ossimPolyconicProjection::setFalseNorthing(double falseNorthing) { Poly_False_Northing = falseNorthing; update(); } void ossimPolyconicProjection::setDefaults() { Poly_False_Easting = 0.0; Poly_False_Northing = 0.0; Poly_Max_Easting = 20037509.0; Poly_Max_Northing = 15348215.0; Poly_Min_Easting = -20037509.0; Poly_Min_Northing = -15348215.0; } void ossimPolyconicProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Poly_False_Easting = falseEasting; Poly_False_Northing = falseNorthing; update(); } ossimGpt ossimPolyconicProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Polyconic_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimPolyconicProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Polyconic(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimPolyconicProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimPolyconicProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimPolyconicProjection)) { Poly_False_Easting = theFalseEastingNorthing.x; Poly_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimPolyconicProjection::Set_Polyconic_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing) { /* BEGIN Set_Polyconic_Parameters */ /* * The function Set_Polyconic_Parameters receives the ellipsoid parameters and * Polyconic projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise POLY_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double j, three_es4; double lat, sin2lat, sin4lat, sin6lat; double temp; // double inv_f = 1 / f; long Error_Code = POLY_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= POLY_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= POLY_INV_F_ERROR; // } // if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) // { /* origin latitude out of range */ // Error_Code |= POLY_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -M_PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= POLY_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Poly_a = a; Poly_f = f; Poly_Origin_Lat = Origin_Latitude; // if (Central_Meridian > M_PI) // Central_Meridian -= TWO_PI; Poly_Origin_Long = Central_Meridian; Poly_False_Northing = False_Northing; Poly_False_Easting = False_Easting; es2 = 2 * Poly_f - Poly_f * Poly_f; es4 = es2 * es2; es6 = es4 * es2; j = 45.0 * es6 / 1024.0; three_es4 = 3.0 * es4; c0 = 1.0 - es2 / 4.0 - three_es4 / 64.0 - 5.0 * es6 / 256.0; c1 = 3.0 * es2 / 8.0 + three_es4 / 32.0 + j; c2 = 15.0 * es4 / 256.0 + j; c3 = 35.0 * es6 / 3072.0; lat = c0 * Poly_Origin_Lat; sin2lat = POLY_COEFF_TIMES_SIN(c1, 2.0, Poly_Origin_Lat); sin4lat = POLY_COEFF_TIMES_SIN(c2, 4.0, Poly_Origin_Lat); sin6lat = POLY_COEFF_TIMES_SIN(c3, 6.0, Poly_Origin_Lat); M0 = POLY_M(lat, sin2lat, sin4lat, sin6lat); if (Poly_Origin_Long > 0) { Convert_Geodetic_To_Polyconic(FOURTY_ONE, Poly_Origin_Long - M_PI, &temp, &Poly_Max_Northing); Convert_Geodetic_To_Polyconic(-FOURTY_ONE, Poly_Origin_Long - M_PI, &temp, &Poly_Min_Northing); Poly_Max_Easting = 19926189.0; Poly_Min_Easting = -20037509.0; } else if (Poly_Origin_Long < 0) { Convert_Geodetic_To_Polyconic(FOURTY_ONE, Poly_Origin_Long + M_PI, &temp, &Poly_Max_Northing); Convert_Geodetic_To_Polyconic(-FOURTY_ONE, Poly_Origin_Long + M_PI, &temp, &Poly_Min_Northing); Poly_Max_Easting = 20037509.0; Poly_Min_Easting = -19926189.0; } else { Convert_Geodetic_To_Polyconic(FOURTY_ONE, M_PI, &temp, &Poly_Max_Northing); Convert_Geodetic_To_Polyconic(-FOURTY_ONE, M_PI, &temp, &Poly_Min_Northing); Poly_Max_Easting = 20037509.0; Poly_Min_Easting = -20037509.0; } } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Set_Polyconic_Parameters */ void ossimPolyconicProjection::Get_Polyconic_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* BEGIN Get_Polyconic_Parameters */ /* * The function Get_Polyconic_Parameters returns the current ellipsoid * parameters, and Polyconic projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Poly_a; *f = Poly_f; *Origin_Latitude = Poly_Origin_Lat; *Central_Meridian = Poly_Origin_Long; *False_Easting = Poly_False_Easting; *False_Northing = Poly_False_Northing; return; } /* END OF Get_Polyconic_Parameters */ long ossimPolyconicProjection::Convert_Geodetic_To_Polyconic (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Polyconic */ /* * The function Convert_Geodetic_To_Polyconic converts geodetic (latitude and * longitude) coordinates to Polyconic projection (easting and northing) * coordinates, according to the current ellipsoid and Polyconic projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise POLY_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double slat = sin(Latitude); double lat, sin2lat, sin4lat, sin6lat; double dlam; /* Longitude - Central Meridan */ double NN; double NN_OVER_tlat; double MM; double EE; long Error_Code = POLY_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= POLY_LAT_ERROR; // } // if ((Longitude < -M_PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= POLY_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Poly_Origin_Long; if (fabs(dlam) > (M_PI / 2.0)) { /* Distortion will result if Longitude is more than 90 degrees from the Central Meridian */ Error_Code |= POLY_LON_WARNING; } // if (dlam > M_PI) // { // dlam -= TWO_PI; // } // if (dlam < -M_PI) // { // dlam += TWO_PI; // } if (Latitude == 0.0) { *Easting = Poly_a * dlam + Poly_False_Easting; *Northing = -M0 + Poly_False_Northing; } else { NN = Poly_a / sqrt(1.0 - es2 * (slat * slat)); NN_OVER_tlat = NN / tan(Latitude); lat = c0 * Latitude; sin2lat = POLY_COEFF_TIMES_SIN(c1, 2.0, Latitude); sin4lat = POLY_COEFF_TIMES_SIN(c2, 4.0, Latitude); sin6lat = POLY_COEFF_TIMES_SIN(c3, 6.0, Latitude); MM = POLY_M(lat, sin2lat, sin4lat, sin6lat); EE = dlam * slat; *Easting = NN_OVER_tlat * sin(EE) + Poly_False_Easting; *Northing = MM - M0 + NN_OVER_tlat * (1.0 - cos(EE)) + Poly_False_Northing; } } return (Error_Code); } /* END OF Convert_Geodetic_To_Polyconic */ long ossimPolyconicProjection::Convert_Polyconic_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Polyconic_To_Geodetic */ /* * The function Convert_Polyconic_To_Geodetic converts Polyconic projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Polyconic projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise POLY_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx; /* Delta easting - Difference in easting (easting-FE) */ double dy; /* Delta northing - Difference in northing (northing-FN) */ double dx_OVER_Poly_a; double AA; double BB; double CC = 0.0; double PHIn, Delta_PHI = 1.0; double sin_PHIn; double PHI, sin2PHI,sin4PHI, sin6PHI; double Mn, Mn_prime, Ma; double AA_Ma; double Ma2_PLUS_BB; double AA_MINUS_Ma; double tolerance = 1.0e-12; /* approximately 1/1000th of an arc second or 1/10th meter */ long Error_Code = POLY_NO_ERROR; // if ((Easting < (Poly_False_Easting + Poly_Min_Easting)) // || (Easting > (Poly_False_Easting + Poly_Max_Easting))) // { /* Easting out of range */ // Error_Code |= POLY_EASTING_ERROR; // } // if ((Northing < (Poly_False_Northing + Poly_Min_Northing)) // || (Northing > (Poly_False_Northing + Poly_Max_Northing))) // { /* Northing out of range */ // Error_Code |= POLY_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ dy = Northing - Poly_False_Northing; dx = Easting - Poly_False_Easting; dx_OVER_Poly_a = dx / Poly_a; if (FLOAT_EQ(dy,-M0,1)) { *Latitude = 0.0; *Longitude = dx_OVER_Poly_a + Poly_Origin_Long; } else { AA = (M0 + dy) / Poly_a; BB = dx_OVER_Poly_a * dx_OVER_Poly_a + (AA * AA); PHIn = AA; while (fabs(Delta_PHI) > tolerance) { sin_PHIn = sin(PHIn); CC = sqrt(1.0 - es2 * sin_PHIn * sin_PHIn) * tan(PHIn); PHI = c0 * PHIn; sin2PHI = POLY_COEFF_TIMES_SIN(c1, 2.0, PHIn); sin4PHI = POLY_COEFF_TIMES_SIN(c2, 4.0, PHIn); sin6PHI = POLY_COEFF_TIMES_SIN(c3, 6.0, PHIn); Mn = POLY_M(PHI, sin2PHI, sin4PHI, sin6PHI); Mn_prime = c0 - 2.0 * c1 * cos(2.0 * PHIn) + 4.0 * c2 * cos(4.0 * PHIn) - 6.0 * c3 * cos(6.0 * PHIn); Ma = Mn / Poly_a; AA_Ma = AA * Ma; Ma2_PLUS_BB = Ma * Ma + BB; AA_MINUS_Ma = AA - Ma; Delta_PHI = (AA_Ma * CC + AA_MINUS_Ma - 0.5 * (Ma2_PLUS_BB) * CC) / (es2 * sin2PHI * (Ma2_PLUS_BB - 2.0 * AA_Ma) / 4.0 * CC + (AA_MINUS_Ma) * (CC * Mn_prime - 2.0 / sin2PHI) - Mn_prime); PHIn -= Delta_PHI; } *Latitude = PHIn; // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; if (FLOAT_EQ(fabs(*Latitude),PI_OVER_2,.00001) || (*Latitude == 0)) *Longitude = Poly_Origin_Long; else { *Longitude = (asin(dx_OVER_Poly_a * CC)) / sin(*Latitude) + Poly_Origin_Long; } } // if (*Longitude > M_PI) // *Longitude -= TWO_PI; // if (*Longitude < -M_PI) // *Longitude += TWO_PI; // if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ // *Longitude = M_PI; // else if (*Longitude < -M_PI) // *Longitude = -M_PI; } return (Error_Code); } /* END OF Convert_Polyconic_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimPolynomProjection.cpp000066400000000000000000000573241352751253100241420ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimPolynomProjection.cpp // AUTHOR: Frederic Claudel Meraka/CSIR, oct 2005 //***************************************************************************** //TODO: speed up getMetersPerPixel using polynom derivatives // #include #include #include RTTI_DEF2(ossimPolynomProjection, "ossimPolynomProjection", ossimProjection, ossimOptimizableProjection); #include #include #include #include #include #include #include #include #include using namespace std; // keywords static const char* MODEL_TYPE = "ossimPolynomProjection"; static const char* LAT_SCALE_KW = "lat_scale"; static const char* LON_SCALE_KW = "long_scale"; static const char* HGT_SCALE_KW = "height_scale"; static const char* LAT_OFFSET_KW = "lat_off"; static const char* LON_OFFSET_KW = "long_off"; static const char* HGT_OFFSET_KW = "height_off"; static const char* POLY_LINE_KW = "poly_line"; static const char* POLY_SAMP_KW = "poly_samp"; ossimPolynomProjection::ossimPolynomProjection() : ossimOptimizableProjection(), theLonOffset(0.0), theLonScale(1.0), theLatOffset(0.0), theLatScale(1.0), theHgtOffset(0.0), theHgtScale(1e-5) {} ossimPolynomProjection::ossimPolynomProjection(const ossimPolynomProjection& model) : ossimOptimizableProjection(model), thePolyLine(model.thePolySamp), thePolySamp(model.thePolyLine), thePolyLine_DLon(model.thePolyLine_DLon), thePolyLine_DLat(model.thePolyLine_DLat), thePolySamp_DLon(model.thePolySamp_DLon), thePolySamp_DLat(model.thePolySamp_DLat), theLonOffset(model.theLonOffset), theLonScale(model.theLonScale), theLatOffset(model.theLatOffset), theLatScale(model.theLatScale), theHgtOffset(model.theHgtOffset), theHgtScale(model.theHgtScale) { } ossimPolynomProjection::~ossimPolynomProjection() {} //***************************************************************************** // METHOD: ossimPolynomProjection::worldToLineSample() // // Overrides base class implementation. Directly computes line-sample from // the polynomials. //***************************************************************************** void ossimPolynomProjection::worldToLineSample(const ossimGpt& ground_point, ossimDpt& imgPt)const { if(ground_point.isLatNan() || ground_point.isLonNan() ) { imgPt.makeNan(); return; } //*** // Normalize the lat, lon, hgt: //*** vector gpt(3); gpt[0] = (ground_point.lon - theLonOffset) * theLonScale; gpt[1] = (ground_point.lat - theLatOffset) * theLatScale; if(ossim::isnan(ground_point.hgt)||ossim::almostEqual(theHgtOffset, 0.0)) { gpt[2] = 0.0; } else { gpt[2] = (ground_point.hgt - theHgtOffset) * theHgtScale; } imgPt.x = thePolySamp.eval(gpt); imgPt.y = thePolyLine.eval(gpt); return; } void ossimPolynomProjection::lineSampleToWorld(const ossimDpt& imagePoint, ossimGpt& worldPoint)const { // how does this work on a DEM?? if(!imagePoint.hasNans()) { lineSampleHeightToWorld(imagePoint, worldPoint.height(), worldPoint); } else { worldPoint.makeNan(); } } //***************************************************************************** // METHOD: ossimPolynomProjection::lineSampleHeightToWorld() // // Performs reverse projection of image line/sample to ground point. // The imaging ray is intersected with a level plane at height = elev. // // NOTE: U = line, V = sample -- this differs from the convention. // //***************************************************************************** void ossimPolynomProjection::lineSampleHeightToWorld(const ossimDpt& image_point, const double& ellHeight, ossimGpt& gpt) const { // // Constants for convergence tests: // static const int MAX_NUM_ITERATIONS = 10; static const double CONVERGENCE_EPSILON = 0.1; // pixels // // The image point must be adjusted by the adjustable parameters as well // as the scale and offsets given as part of the RPC param normalization. // // NOTE: U = line, V = sample // double U = image_point.y; double V = image_point.x; //*** // Initialize quantities to be used in the iteration for ground point: //*** vector ngpt(3); ngpt[0] = 0.0; //normalized longitude (center) ngpt[1] = 0.0; //normalized latitude if(ossim::isnan(ellHeight)||ossim::almostEqual(theHgtOffset, 0.0)) { ngpt[2] = 0; // norm height } else { ngpt[2] = (ellHeight - theHgtOffset) * theHgtScale; // norm height } double epsilonU = CONVERGENCE_EPSILON; double epsilonV = CONVERGENCE_EPSILON; int iteration = 0; //*** // Declare variables only once outside the loop. These include: // * polynomials (numerators Pu, Pv, and denominators Qu, Qv), // * partial derivatives of polynomials wrt X, Y, // * computed normalized image point: Uc, Vc, // * residuals of normalized image point: deltaU, deltaV, // * partial derivatives of Uc and Vc wrt X, Y, // * corrections to normalized lat, lon: deltaLat, deltaLon. //*** double Uc, Vc; double deltaU, deltaV; double dU_dLat, dU_dLon, dV_dLat, dV_dLon, W; double deltaLat, deltaLon; //*** // Now iterate until the computed Uc, Vc is within epsilon of the desired // image point U, V: //*** do { //*** // Calculate the normalized line and sample Uc, Vc as ratio of // polynomials Pu, Qu and Pv, Qv: //*** Uc = thePolyLine.eval(ngpt); //TBC Vc = thePolySamp.eval(ngpt); //TBC //*** // Compute residuals between desired and computed line, sample: //*** deltaU = U - Uc; deltaV = V - Vc; //*** // Check for convergence and skip re-linearization if converged: //*** if ((fabs(deltaU) > epsilonU) || (fabs(deltaV) > epsilonV)) { //*** // Analytically compute partials of quotients U and V wrt lat, lon: //*** dU_dLat = thePolyLine_DLat.eval(ngpt); dU_dLon = thePolyLine_DLon.eval(ngpt); dV_dLat = thePolySamp_DLat.eval(ngpt); dV_dLon = thePolySamp_DLon.eval(ngpt); W = dU_dLon*dV_dLat - dU_dLat*dV_dLon; //*** // Now compute the corrections to normalized lat, lon: //*** deltaLat = (dU_dLon*deltaV - dV_dLon*deltaU) / W; deltaLon = (dV_dLat*deltaU - dU_dLat*deltaV) / W; ngpt[0] += deltaLon; ngpt[1] += deltaLat; } iteration++; } while (((fabs(deltaU)>epsilonU) || (fabs(deltaV)>epsilonV)) && (iteration < MAX_NUM_ITERATIONS)); //*** // Test for exceeding allowed number of iterations. Flag error if so: //*** if (iteration == MAX_NUM_ITERATIONS) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimPolynomProjection::lineSampleHeightToWorld: \nMax number of iterations reached in ground point " << "solution. Results are inaccurate." << endl; } //*** // Now un-normalize the ground point lat, lon and establish return quantity: //*** gpt.lat = ngpt[1] / theLatScale + theLatOffset; gpt.lon = ngpt[0] / theLonScale + theLonOffset; gpt.hgt = ellHeight; } ossimGpt ossimPolynomProjection::origin()const { //TBC should return samp = 0, line = 0, but this has no meaning here return ossimGpt(theLatOffset, theLonOffset, theHgtOffset); } ossimDpt ossimPolynomProjection::getMetersPerPixel() const { //TBC TBD : use derivative polynoms (this is approximative anyway) ossimGpt centerG(theLatOffset, theLonOffset, theHgtOffset); ossimDpt centerI; worldToLineSample(centerG,centerI); ossimDpt left = centerI + ossimDpt(-1,0); ossimDpt right = centerI + ossimDpt(1,0); ossimDpt top = centerI + ossimDpt(0,-1); ossimDpt bottom = centerI + ossimDpt(0,1); ossimGpt leftG; ossimGpt rightG; ossimGpt topG; ossimGpt bottomG; lineSampleToWorld(left, leftG); lineSampleToWorld(right, rightG); lineSampleToWorld(top, topG); lineSampleToWorld(bottom, bottomG); ossimDpt result; result.x = (ossimEcefPoint(leftG) - ossimEcefPoint(rightG)).magnitude()/2.0; result.y = (ossimEcefPoint(topG) - ossimEcefPoint(bottomG)).magnitude()/2.0; return result; } bool ossimPolynomProjection::operator==(const ossimProjection& projection) const { if(&projection == this) return true; //TBD TBC: compare polynoms after applying affine transforms (=polynom) // TBD => need polynom composition return false; } //***************************************************************************** // METHOD: ossimPolynomProjection::print() // // Formatted dump of data members. // //***************************************************************************** std::ostream& ossimPolynomProjection::print(std::ostream& out) const { out << "\nDump of ossimPolynomProjection object at " << hex << this << ":\n" << LAT_SCALE_KW << ": " << theLatScale << "\n" << LON_SCALE_KW << ": " << theLonScale << "\n" << HGT_SCALE_KW << ": " << theHgtScale << "\n" << LAT_OFFSET_KW << ": " << theLatOffset << "\n" << LON_OFFSET_KW << ": " << theLonOffset << "\n" << HGT_OFFSET_KW << ": " << theHgtOffset << "\n" << "PolySamp: " <. Check the keywordlist for proper syntax." << std::endl; return false; } theLatScale = ossimString(value).toDouble(); keyword = LON_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLonScale = ossimString(value).toDouble(); keyword = HGT_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theHgtScale = ossimString(value).toDouble(); keyword = LAT_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLatOffset = ossimString(value).toDouble(); keyword = LON_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLonOffset = ossimString(value).toDouble(); keyword = HGT_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theHgtOffset = ossimString(value).toDouble(); //load polynoms using streams keyword = POLY_LINE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } std::istringstream polyLineIS; polyLineIS.str(std::string(value)); thePolyLine.import(polyLineIS); keyword = POLY_SAMP_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } std::istringstream polySampIS; polySampIS.str(std::string(value)); thePolySamp.import(polySampIS); //init dependent members buildDerivatives(); return true; } void ossimPolynomProjection::setPolyLine(const ossimPolynom< ossim_float64 , 3 >& poly) { thePolyLine = poly; buildLineDerivatives(); } void ossimPolynomProjection::setPolySamp(const ossimPolynom< ossim_float64 , 3 >& poly) { thePolySamp = poly; buildSampDerivatives(); } void ossimPolynomProjection::buildDerivatives() { buildLineDerivatives(); buildSampDerivatives(); } void ossimPolynomProjection::buildLineDerivatives() { thePolyLine.pdiff(0, thePolyLine_DLon); thePolyLine.pdiff(1, thePolyLine_DLat); } void ossimPolynomProjection::buildSampDerivatives() { thePolySamp.pdiff(0, thePolySamp_DLon); thePolySamp.pdiff(1, thePolySamp_DLat); } bool ossimPolynomProjection::setupOptimizer(const ossimString& setup) { return setupDesiredExponents(setup); } ossim_uint32 ossimPolynomProjection::degreesOfFreedom()const { //is number of desired monoms * 2 return (ossim_uint32)theExpSet.size() * 2; } bool ossimPolynomProjection::setupDesiredExponents(const ossimString& monoms) { bool res=false; theExpSet.clear(); //setup monoms from a xyz1 string, eg: y 1 xy x2y3 x2y2z2 std::vector< ossimString > spm = monoms.explode(" \t,;"); for (std::vector< ossimString >::const_iterator it = spm.begin(); it!=spm.end() ;++it) { ossimPolynom< ossim_float64 , 3 >::EXP_TUPLE et; res = stringToExp(*it, et); if (!res) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::setupDesiredExponents(): bad exponent tuple string: "<<*it<(0)] == '1') { for(int i=0;i<3;i++) et.push_back(0); return true; } //loop on symbols int ex[3]={0,0,0}; while (ts.size()>0) { int symb = getSymbol(ts, tkeys); if (symb<0) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::stringToExp(): cant find any symbol"<< std::endl; return false; } int expo = getExponent(ts); if (ex[symb]>0) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimPolynomProjection::stringToExp(): symbol appears twice: " <(symb)] << std::endl; return false; } ex[symb] = expo; } for(int i=0;i<3;i++) et.push_back(ex[i]); return true; } int ossimPolynomProjection::getSymbol(ossimString& ts,const ossimString& symbols) const { //remove symbol from string ts and return symbol index, -1 = error for(unsigned int i=0;i='0')) { expo = 10*expo + (cts.operator[](pos)-'0'); ++pos; } //remove exp from string if (pos>0) ts=ts.afterPos(pos-1); if (expo==0) expo=1; return expo; } ossim-Miami-2.9.1/src/projection/ossimPositionQualityEvaluator.cpp000066400000000000000000001111131352751253100254730ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Base class for position quality evaluation operations. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug(ossimString("ossimPositionQualityEvaluator:debug")); static ossimTrace traceExec(ossimString("ossimPositionQualityEvaluator:exec")); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimPositionQualityEvaluator.cpp"; #endif // 2D 90% function coefficients const ossim_uint32 nTableEntries = 21; const ossim_uint32 nMultiplier = nTableEntries-1; const ossim_float64 table90[nTableEntries]= {1.644854,1.645623,1.647912,1.651786,1.657313, 1.664580,1.673829,1.685227,1.699183,1.716257, 1.737080,1.762122,1.791522,1.825112,1.862530, 1.903349,1.947158,1.993595,2.042360,2.093214,2.145966}; // 1D conversion factors relative to ONE_SIGMA const ossim_float64 Fac1D[NUM_PROB_LEVELS] = {1.0, 0.6745, 1.6449, 1.96}; // 2D conversion factors relative to ONE_SIGMA const ossim_float64 Fac2D[NUM_PROB_LEVELS] = {1.0, 1.1774, 2.1460, 2.4477}; // 2D conversion factors relative to P90 const ossim_float64 Fac2D90[NUM_PROB_LEVELS] = {0.46598, 0.54865, 1.0, 1.14059}; //***************************************************************************** // METHOD: ossimPositionQualityEvaluator::ossimPositionQualityEvaluator() // // Constructor. // //***************************************************************************** ossimPositionQualityEvaluator::ossimPositionQualityEvaluator() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimPositionQualityEvaluator::ossimPositionQualityEvaluator DEBUG:" << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } theEvaluatorValid = false; theRpcModel.theType = 'N'; } //***************************************************************************** // METHOD: ossimPositionQualityEvaluator::ossimPositionQualityEvaluator() // // Covariance matrix-based constructor. // //***************************************************************************** ossimPositionQualityEvaluator:: ossimPositionQualityEvaluator(const ossimEcefPoint& pt,const NEWMAT::Matrix& covMat) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimPositionQualityEvaluator::ossimPositionQualityEvaluator DEBUG:" << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } theRpcModel.theType = 'N'; // Set the point ossimGpt ptG(pt); thePtG = ptG; // Define the local frame centered on the point ossimLsrSpace enu(ptG); theLocalFrame = enu; // Propagate input ECF cov matrix to local theCovMat = theLocalFrame.ecefToLsrRotMatrix()*covMat* theLocalFrame.lsrToEcefRotMatrix(); // Compute evaluation parameters theEvaluatorValid = decomposeMatrix(); } //***************************************************************************** // METHOD: ossimPositionQualityEvaluator::ossimPositionQualityEvaluator() // // LOS error/geometry-based constructor. // //***************************************************************************** ossimPositionQualityEvaluator:: ossimPositionQualityEvaluator(const ossimEcefPoint& pt, const ossim_float64& errBiasLOS, const ossim_float64& errRandLOS, const ossim_float64& elevAngleLOS, const ossim_float64& azimAngleLOS, const ossimColumnVector3d& surfN, const NEWMAT::Matrix& surfCovMat) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimPositionQualityEvaluator::ossimPositionQualityEvaluator DEBUG:" << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } theRpcModel.theType = 'N'; // Set the point ossimGpt ptG(pt); thePtG = ptG; // Define the local frame centered on the point ossimLsrSpace enu(ptG); theLocalFrame = enu; // Form the covariance matrix if (constructMatrix (errBiasLOS, errRandLOS, elevAngleLOS, azimAngleLOS, surfN, surfCovMat)) { // Compute evaluation parameters theEvaluatorValid = decomposeMatrix(); } else { theEvaluatorValid = false; } } //***************************************************************************** // METHOD: ossimPositionQualityEvaluator::ossimPositionQualityEvaluator() // // LOS error/coefficient-based constructor. // //***************************************************************************** ossimPositionQualityEvaluator:: ossimPositionQualityEvaluator(const ossimEcefPoint& pt, const ossim_float64& errBiasLOS, const ossim_float64& errRandLOS, const pqeRPCModel& rpc, const ossimColumnVector3d& surfN, const NEWMAT::Matrix& surfCovMat) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimPositionQualityEvaluator::ossimPositionQualityEvaluator DEBUG:" << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } // Set the point ossimGpt ptG(pt); thePtG = ptG; // Define the local frame centered on the point ossimLsrSpace enu(ptG); theLocalFrame = enu; // Set the model parameters theRpcModel = rpc; // Compute the target elevation & azimuth angles double elevAngleLOS; double azimAngleLOS; computeElevAzim(rpc, elevAngleLOS, azimAngleLOS); // Form the covariance matrix if (constructMatrix (errBiasLOS, errRandLOS, elevAngleLOS, azimAngleLOS, surfN, surfCovMat)) { // Compute evaluation parameters theEvaluatorValid = decomposeMatrix(); } else { theEvaluatorValid = false; } } //***************************************************************************** // DESTRUCTOR: ~ossimPositionQualityEvaluator() // //***************************************************************************** ossimPositionQualityEvaluator::~ossimPositionQualityEvaluator() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: ~ossimPositionQualityEvaluator(): returning..." << std::endl; } //***************************************************************************** // METHOD: ossimPositionQualityEvaluator::print() // // Print info. // //***************************************************************************** std::ostream& ossimPositionQualityEvaluator:: print(std::ostream& out) const { out << "\nPositionQualityEvaluator Summary..."< DBL_EPSILON) { pMinU = pMinAxis.unit(); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<" pMinU: "< 0.0) { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Compute the LOS error the surface plane // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ double planeErrorL = eTot/sin(elevAngTerr); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Project axes to horizontal // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ossimColumnVector3d pL = vperp(pMaxU, lsrNorm); ossimColumnVector3d pN = vperp(pMinU, lsrNorm); ossimColumnVector3d eL = pL * planeErrorL; ossimColumnVector3d eN = pN * eTot; double magL = eL.magnitude(); double magN = eN.magnitude(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Compute vertical component due to intersection geometry // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ossimColumnVector3d pV = pMaxU - pL; ossimColumnVector3d eV = pV * planeErrorL; double magV = eV.magnitude(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) <<" Projected horizontal/vertical components...."< magN) { pMax = magL; pMin = magN; theta = atan3(pL[1],pL[0]); } else { pMax = magN; pMin = magL; theta = atan3(pN[1],pN[0]); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Form final covariance matrix from axes & rotation angle // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NEWMAT::Matrix Cov(2,2); NEWMAT::Matrix Vcomp(2,2); NEWMAT::DiagonalMatrix Dcomp(2); Dcomp(1,1) = pMax*pMax; Dcomp(2,2) = pMin*pMin; Vcomp(1,1) = cos(theta); Vcomp(2,1) = sin(theta); Vcomp(1,2) =-Vcomp(2,1); Vcomp(2,2) = Vcomp(1,1); Cov = Vcomp*Dcomp*Vcomp.t(); // Load full 3X3 matrix in local frame NEWMAT::Matrix covMat(3,3); covMat(1,1) = Cov(1,1); covMat(1,2) = Cov(1,2); covMat(1,3) = 0.0; covMat(2,1) = Cov(2,1); covMat(2,2) = Cov(2,2); covMat(2,3) = 0.0; covMat(3,1) = covMat(1,3); covMat(3,2) = covMat(2,3); covMat(3,3) = magV*magV + vSigV*vSigV; // Save the matrix in local frame theCovMat = covMat; } //end if (elevAngTerr > 0.0) else { constructOK = false; ossimNotify(ossimNotifyLevel_WARN) << "WARNING: ossimPositionQualityEvaluator::constructMatrix(): " << "\n terrain-referenced elev ang: "<ellipsoid()->jacobianWrtEcef(location, jMat); ossimDpt pWRTx; ossimDpt pWRTy; ossimDpt pWRTz; // Line pWRTx.u = dU_dLat*jMat(1,1)+dU_dLon*jMat(2,1)+dU_dHgt*jMat(3,1); pWRTy.u = dU_dLat*jMat(1,2)+dU_dLon*jMat(2,2)+dU_dHgt*jMat(3,2); pWRTz.u = dU_dLat*jMat(1,3)+dU_dLon*jMat(2,3)+dU_dHgt*jMat(3,3); // Samp pWRTx.v = dV_dLat*jMat(1,1)+dV_dLon*jMat(2,1)+dV_dHgt*jMat(3,1); pWRTy.v = dV_dLat*jMat(1,2)+dV_dLon*jMat(2,2)+dV_dHgt*jMat(3,2); pWRTz.v = dV_dLat*jMat(1,3)+dV_dLon*jMat(2,3)+dV_dHgt*jMat(3,3); // Form required partials in local frame NEWMAT::Matrix jECF(3,2); jECF(1,1) = pWRTx.u; jECF(1,2) = pWRTx.v; jECF(2,1) = pWRTy.u; jECF(2,2) = pWRTy.v; jECF(3,1) = pWRTz.u; jECF(3,2) = pWRTz.v; NEWMAT::Matrix jLSR(3,2); jLSR = theLocalFrame.ecefToLsrRotMatrix()*jECF; double dU_dx = jLSR(1,1); double dU_dy = jLSR(2,1); double dU_dz = jLSR(3,1); double dV_dx = jLSR(1,2); double dV_dy = jLSR(2,2); double dV_dz = jLSR(3,2); // Compute azimuth & elevation angles double den = dU_dy*dV_dx - dV_dy*dU_dx; double dY = dU_dx*dV_dz - dV_dx*dU_dz; double dX = dV_dy*dU_dz - dU_dy*dV_dz; double dy_dH = dY / den; double dx_dH = dX / den; azimAngleLOS = atan2(dx_dH, dy_dH); elevAngleLOS = atan2(1.0, sqrt(dy_dH*dy_dH+dx_dH*dx_dH)); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<<"DEBUG: computeElevAzim..."< 0.0) result = 0.0; else result = M_PI; } else { u = y/x; v = fabs(u); result = atan(v); result *= v/u; if (x < 0.0) result += M_PI; else if (result < 0.0) result += TWO_PI; } } return result; } //***************************************************************************** // PRIVATE METHOD: ossimPositionQualityEvaluator::polynomial // // Evaluates polynomial function. // //***************************************************************************** double ossimPositionQualityEvaluator::polynomial( const double& P, const double& L, const double& H, const double* c) const { double r; if (theRpcModel.theType == 'A') { r = c[ 0] + c[ 1]*L + c[ 2]*P + c[ 3]*H + c[ 4]*L*P + c[ 5]*L*H + c[ 6]*P*H + c[ 7]*L*P*H + c[ 8]*L*L + c[ 9]*P*P + c[10]*H*H + c[11]*L*L*L + c[12]*L*L*P + c[13]*L*L*H + c[14]*L*P*P + c[15]*P*P*P + c[16]*P*P*H + c[17]*L*H*H + c[18]*P*H*H + c[19]*H*H*H; } else { r = c[ 0] + c[ 1]*L + c[ 2]*P + c[ 3]*H + c[ 4]*L*P + c[ 5]*L*H + c[ 6]*P*H + c[ 7]*L*L + c[ 8]*P*P + c[ 9]*H*H + c[10]*L*P*H + c[11]*L*L*L + c[12]*L*P*P + c[13]*L*H*H + c[14]*L*L*P + c[15]*P*P*P + c[16]*P*H*H + c[17]*L*L*H + c[18]*P*P*H + c[19]*H*H*H; } return r; } //***************************************************************************** // PRIVATE METHOD: ossimPositionQualityEvaluator::dPoly_dLat // // Computes derivative of polynomial WRT normalized latitude P. // //***************************************************************************** double ossimPositionQualityEvaluator::dPoly_dLat( const double& P, const double& L, const double& H, const double* c) const { double dr; if (theRpcModel.theType == 'A') { dr = c[2] + c[4]*L + c[6]*H + c[7]*L*H + 2*c[9]*P + c[12]*L*L + 2*c[14]*L*P + 3*c[15]*P*P +2*c[16]*P*H + c[18]*H*H; } else { dr = c[2] + c[4]*L + c[6]*H + 2*c[8]*P + c[10]*L*H + 2*c[12]*L*P + c[14]*L*L + 3*c[15]*P*P + c[16]*H*H + 2*c[18]*P*H; } return dr; } //***************************************************************************** // PRIVATE METHOD: ossimPositionQualityEvaluator::dPoly_dLon // // Computes derivative of polynomial WRT normalized longitude L. // //***************************************************************************** double ossimPositionQualityEvaluator::dPoly_dLon( const double& P, const double& L, const double& H, const double* c) const { double dr; if (theRpcModel.theType == 'A') { dr = c[1] + c[4]*P + c[5]*H + c[7]*P*H + 2*c[8]*L + 3*c[11]*L*L + 2*c[12]*L*P + 2*c[13]*L*H + c[14]*P*P + c[17]*H*H; } else { dr = c[1] + c[4]*P + c[5]*H + 2*c[7]*L + c[10]*P*H + 3*c[11]*L*L + c[12]*P*P + c[13]*H*H + 2*c[14]*P*L + 2*c[17]*L*H; } return dr; } //***************************************************************************** // PRIVATE METHOD: ossimPositionQualityEvaluator::dPoly_dHgt // // Computes derivative of polynomial WRT normalized height H. // //***************************************************************************** double ossimPositionQualityEvaluator::dPoly_dHgt( const double& P, const double& L, const double& H, const double* c) const { double dr; if (theRpcModel.theType == 'A') { dr = c[3] + c[5]*L + c[6]*P + c[7]*L*P + 2*c[10]*H + c[13]*L*L + c[16]*P*P + 2*c[17]*L*H + 2*c[18]*P*H + 3*c[19]*H*H; } else { dr = c[3] + c[5]*L + c[6]*P + 2*c[9]*H + c[10]*L*P + 2*c[13]*L*H + 2*c[16]*P*H + c[17]*L*L + c[18]*P*P + 3*c[19]*H*H; } return dr; } ossim-Miami-2.9.1/src/projection/ossimPpjFrameSensor.cpp000066400000000000000000000405651352751253100233450ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Dave Hicks // // Description: PPJ Frame Model // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceExec ("ossimPpjFrameSensor:exec"); static ossimTrace traceDebug("ossimPpjFrameSensor:debug"); RTTI_DEF1(ossimPpjFrameSensor, "ossimPpjFrameSensor", ossimSensorModel); enum { PARAM_ADJ_LON_OFFSET = 0, PARAM_ADJ_LAT_OFFSET = 1, PARAM_ADJ_ALTITUDE_OFFSET =2, // PARAM_ADJ_ROLL_OFFSET, // PARAM_ADJ_PITCH_OFFSET, // PARAM_ADJ_YAW_OFFSET, PARAM_ADJ_FOCAL_LENGTH_OFFSET=6, PARAM_ADJ_COUNT = 7 }; ossimPpjFrameSensor::ossimPpjFrameSensor() : m_ecef2Cam(), m_ecef2CamInverse(), m_principalPoint(0.0, 0.0), m_focalLengthX(0.0), m_focalLengthY(0.0), m_focalLength(0.0), m_ecefCameraPosition(), m_cameraPositionEllipsoid(), m_radialK1(0.0), m_radialK2(0.0), m_radialP1(0.0), m_radialP2(0.0), m_adjustedCameraPosition(), m_adjustedFocalLength(0.0), m_averageProjectedHeight(0.0) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPpjFrameSensor::ossimPpjFrameSensor DEBUG:" << std::endl; } initAdjustableParameters(); theSensorID = "PpjFrame"; m_ecef2Cam.ReSize(3,3); m_ecef2CamInverse.ReSize(3,3); std::fill(m_ecef2Cam.Store(), m_ecef2Cam.Store()+9, 0.0); std::fill(m_ecef2CamInverse.Store(), m_ecef2CamInverse.Store()+9, 0.0); m_ecef2Cam[0][0] = 1.0; m_ecef2Cam[1][1] = 1.0; m_ecef2Cam[2][2] = 1.0; m_ecef2CamInverse[0][0] = 1.0; m_ecef2CamInverse[1][1] = 1.0; m_ecef2CamInverse[2][2] = 1.0; } ossimPpjFrameSensor::ossimPpjFrameSensor(const ossimPpjFrameSensor& src) : ossimSensorModel(src), m_ecef2Cam(src.m_ecef2Cam), m_ecef2CamInverse(src.m_ecef2CamInverse), m_principalPoint(src.m_principalPoint), m_focalLengthX(src.m_focalLengthX), m_focalLengthY(src.m_focalLengthY), m_focalLength(src.m_focalLength), m_ecefCameraPosition(src.m_ecefCameraPosition), m_cameraPositionEllipsoid(src.m_cameraPositionEllipsoid), m_radialK1(src.m_radialK1), m_radialK2(src.m_radialK2), m_radialP1(src.m_radialP1), m_radialP2(src.m_radialP2), m_adjustedCameraPosition(src.m_adjustedCameraPosition), m_adjustedFocalLength(src.m_adjustedFocalLength), m_averageProjectedHeight(src.m_averageProjectedHeight) { } ossimObject* ossimPpjFrameSensor::dup()const { return new ossimPpjFrameSensor(*this); } void ossimPpjFrameSensor::setFocalLength(double focX, double focY) { m_focalLengthX = focX; m_focalLengthY = focY; m_focalLength = m_focalLengthX; } void ossimPpjFrameSensor::setCameraPosition(const ossimGpt& value) { m_cameraPositionEllipsoid = value; m_ecefCameraPosition = value; } void ossimPpjFrameSensor::setPrincipalPoint(const ossimDpt& value) { m_principalPoint = value; } void ossimPpjFrameSensor::setecef2CamMatrix(const NEWMAT::Matrix& value) { m_ecef2Cam = value; m_ecef2CamInverse = m_ecef2Cam.t(); } void ossimPpjFrameSensor::setAveragePrjectedHeight(double averageProjectedHeight) { m_averageProjectedHeight = averageProjectedHeight; } void ossimPpjFrameSensor::imagingRay(const ossimDpt& imagePoint, ossimEcefRay& imageRay) const { // Form camera frame LOS vector ossimColumnVector3d camLOS(imagePoint.x - m_principalPoint.x, imagePoint.y - m_principalPoint.y, m_adjustedFocalLength); // Rotate to ECF ossimColumnVector3d ecfLOS = m_ecef2CamInverse * camLOS; imageRay.setOrigin(m_adjustedCameraPosition); ossimEcefVector ecfRayDir(ecfLOS); imageRay.setDirection(ecfRayDir); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPpjFrameSensor::imagingRay DEBUG:\n" << " camLOS = " << camLOS << "\n" << " m_adjustedPlatformPosition = " << m_adjustedCameraPosition << "\n" << " imageRay = " << imageRay << "\n" << std::endl; } } void ossimPpjFrameSensor::lineSampleToWorld(const ossimDpt& imagePoint, ossimGpt& worldPt) const { ossimEcefRay ray; imagingRay(imagePoint, ray); ossimElevManager::instance()->intersectRay(ray, worldPt, m_averageProjectedHeight); } void ossimPpjFrameSensor::lineSampleHeightToWorld(const ossimDpt& imagePoint, const double& heightEllipsoid, ossimGpt& worldPt) const { ossimEcefRay ray; imagingRay(imagePoint, ray); double h = (ossim::isnan(heightEllipsoid)||ossim::almostEqual(heightEllipsoid, 0.0))?m_averageProjectedHeight:heightEllipsoid; ossimEcefPoint pecf(ray.intersectAboveEarthEllipsoid(h)); worldPt = ossimGpt(pecf); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPpjFrameSensor::lineSampleHeightToWorld DEBUG:" << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << " imagePoint = " << imagePoint << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << " heightEllipsoid = " << heightEllipsoid << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << " ray = " << ray << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << " worldPt = " << worldPt << std::endl; } } void ossimPpjFrameSensor::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { ossimGpt wpt = world_point; if(wpt.isHgtNan()) { wpt.height(m_averageProjectedHeight); } ossimEcefPoint gnd_ecf(wpt); ossimEcefPoint cam_ecf(m_adjustedCameraPosition); ossimEcefVector ecfRay(gnd_ecf - cam_ecf); ossimColumnVector3d camRay(m_ecef2Cam*ecfRay.data()); double x = m_principalPoint.x + m_adjustedFocalLength*camRay[0]/camRay[2]; double y = m_principalPoint.y + m_adjustedFocalLength*camRay[1]/camRay[2]; ossimDpt p(x, y); image_point = p; } void ossimPpjFrameSensor::updateModel() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPpjFrameSensor::updateModel DEBUG:" << std::endl; } double deltap = computeParameterOffset(PARAM_ADJ_LAT_OFFSET)/ m_cameraPositionEllipsoid.metersPerDegree().y; double deltal = computeParameterOffset(PARAM_ADJ_LON_OFFSET)/ m_cameraPositionEllipsoid.metersPerDegree().x; m_adjustedCameraPosition = ossimGpt(m_cameraPositionEllipsoid.latd() + deltap, m_cameraPositionEllipsoid.lond() + deltal, m_cameraPositionEllipsoid.height() + computeParameterOffset(PARAM_ADJ_ALTITUDE_OFFSET)); // TODO Need to add correction matrix to accommodate orientation offsets. It // shouldn't be done in ECF frame. // double r = ossim::degreesToRadians(m_roll + computeParameterOffset(PARAM_ADJ_ROLL_OFFSET)); // double p = ossim::degreesToRadians(m_pitch + computeParameterOffset(PARAM_ADJ_PITCH_OFFSET) ); // double y = ossim::degreesToRadians(m_yaw + computeParameterOffset(PARAM_ADJ_YAW_OFFSET)); // NEWMAT::Matrix rollM = ossimMatrix3x3::create(1, 0, 0, // 0, cos(r), sin(r), // 0, -sin(r), cos(r)); // NEWMAT::Matrix pitchM = ossimMatrix3x3::create(cos(p), 0, -sin(p), // 0, 1, 0, // sin(p), 0, cos(p)); // NEWMAT::Matrix yawM = ossimMatrix3x3::create(cos(y), sin(y), 0, // -sin(y), cos(y), 0, // 0,0,1); m_adjustedFocalLength = m_focalLength + computeParameterOffset(PARAM_ADJ_FOCAL_LENGTH_OFFSET); try { computeGsd(); } catch(...) { } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPpjFrameSensor::updateModel complete..." << std::endl; } /* ossimGpt gpt; lineSampleToWorld(theImageClipRect.ul(),gpt);//+ossimDpt(-w, -h), gpt); theBoundGndPolygon[0] = gpt; lineSampleToWorld(theImageClipRect.ur(),gpt);//+ossimDpt(w, -h), gpt); theBoundGndPolygon[1] = gpt; lineSampleToWorld(theImageClipRect.lr(),gpt);//+ossimDpt(w, h), gpt); theBoundGndPolygon[2] = gpt; lineSampleToWorld(theImageClipRect.ll(),gpt);//+ossimDpt(-w, h), gpt); theBoundGndPolygon[3] = gpt; */ } void ossimPpjFrameSensor::initAdjustableParameters() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimPpjFrameSensor::initAdjustableParameters: returning..." << std::endl; resizeAdjustableParameterArray(PARAM_ADJ_COUNT); setAdjustableParameter(PARAM_ADJ_LON_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_LON_OFFSET, "lon_offset"); setParameterUnit(PARAM_ADJ_LON_OFFSET, "meters"); setParameterSigma(PARAM_ADJ_LON_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_LAT_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_LAT_OFFSET, "lat_offset"); setParameterUnit(PARAM_ADJ_LAT_OFFSET, "meters"); setParameterSigma(PARAM_ADJ_LAT_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_ALTITUDE_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_ALTITUDE_OFFSET, "altitude_offset"); setParameterUnit(PARAM_ADJ_ALTITUDE_OFFSET, "meters"); setParameterSigma(PARAM_ADJ_ALTITUDE_OFFSET, 10); // TODO Add these back in when orientation angle offsets are fixed. // setAdjustableParameter(PARAM_ADJ_ROLL_OFFSET, 0.0); // setParameterDescription(PARAM_ADJ_ROLL_OFFSET, "roll_offset"); // setParameterUnit(PARAM_ADJ_ROLL_OFFSET, "degrees"); // setParameterSigma(PARAM_ADJ_ROLL_OFFSET, 10); // setAdjustableParameter(PARAM_ADJ_PITCH_OFFSET, 0.0); // setParameterDescription(PARAM_ADJ_PITCH_OFFSET, "pitch_offset"); // setParameterUnit(PARAM_ADJ_PITCH_OFFSET, "degrees"); // setParameterSigma(PARAM_ADJ_PITCH_OFFSET, 10); // setAdjustableParameter(PARAM_ADJ_YAW_OFFSET, 0.0); // setParameterDescription(PARAM_ADJ_YAW_OFFSET, "yaw_offset"); // setParameterUnit(PARAM_ADJ_YAW_OFFSET, "degrees"); // setParameterSigma(PARAM_ADJ_YAW_OFFSET, .04); setAdjustableParameter(PARAM_ADJ_FOCAL_LENGTH_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_FOCAL_LENGTH_OFFSET, "focal_length_offset"); setParameterUnit(PARAM_ADJ_FOCAL_LENGTH_OFFSET, "pixels"); setParameterSigma(PARAM_ADJ_FOCAL_LENGTH_OFFSET, 20.0); } bool ossimPpjFrameSensor::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPpjFrameSensor::loadState DEBUG:" << std::endl; } theGSD.makeNan(); theRefImgPt.makeNan(); ossimSensorModel::loadState(kwl, prefix); if(getNumberOfAdjustableParameters() < 1) { initAdjustableParameters(); } ossimString principal_point = kwl.find(prefix, "principal_point"); ossimString focal_length_x = kwl.find(prefix, "focal_length_x"); ossimString focal_length_y = kwl.find(prefix, "focal_length_y"); ossimString number_samples = kwl.find(prefix, "number_samples"); ossimString number_lines = kwl.find(prefix, "number_lines"); ossimString ecf_to_cam_row1 = kwl.find(prefix, "ecf_to_cam_row1"); ossimString ecf_to_cam_row2 = kwl.find(prefix, "ecf_to_cam_row2"); ossimString ecf_to_cam_row3 = kwl.find(prefix, "ecf_to_cam_row3"); ossimString platform_position = kwl.find(prefix, "ecef_camera_position"); ossimString averageProjectedHeight = kwl.find(prefix, "average_projected_height"); // ossimString roll; // ossimString pitch; // ossimString yaw; // m_roll = 0; // m_pitch = 0; // m_yaw = 0; // roll = kwl.find(prefix, "roll"); // pitch = kwl.find(prefix, "pitch"); // yaw = kwl.find(prefix, "yaw"); bool result = (!principal_point.empty()&& !focal_length_x.empty()&& !platform_position.empty()&& !ecf_to_cam_row1.empty()&& !ecf_to_cam_row2.empty()&& !ecf_to_cam_row3.empty()); if(!averageProjectedHeight.empty()) { m_averageProjectedHeight = averageProjectedHeight.toDouble(); } if(!number_samples.empty()) { theImageSize = ossimIpt(number_samples.toDouble(), number_lines.toDouble()); theRefImgPt = ossimDpt(theImageSize.x*.5, theImageSize.y*.5); theImageClipRect = ossimDrect(0,0,theImageSize.x-1, theImageSize.y-1); } if(theImageClipRect.hasNans()) { theImageClipRect = ossimDrect(0,0,theImageSize.x-1,theImageSize.y-1); } if(theRefImgPt.hasNans()) { theRefImgPt = theImageClipRect.midPoint(); } if(!focal_length_x.empty()) { m_focalLengthX = focal_length_x.toDouble(); m_focalLength = m_focalLengthX; } if(!focal_length_y.empty()) { m_focalLengthY = focal_length_y.toDouble(); } std::vector row; if(!ecf_to_cam_row1.empty()) { row = ecf_to_cam_row1.explode(" "); for (int i=0; i<3; ++i) m_ecef2Cam[0][i] = row[i].toDouble(); row = ecf_to_cam_row2.explode(" "); for (int i=0; i<3; ++i) m_ecef2Cam[1][i] = row[i].toDouble(); row = ecf_to_cam_row3.explode(" "); for (int i=0; i<3; ++i) m_ecef2Cam[2][i] = row[i].toDouble(); m_ecef2CamInverse = m_ecef2Cam.t(); } // if(!roll.empty()) // { // m_roll = roll.toDouble(); // } // if(!pitch.empty()) // { // m_pitch = pitch.toDouble(); // } // if(!yaw.empty()) // { // m_yaw = yaw.toDouble(); // } if(!principal_point.empty()) { m_principalPoint.toPoint(principal_point); } if(!platform_position.empty()) { m_ecefCameraPosition.toPoint(platform_position); m_cameraPositionEllipsoid = ossimGpt(m_ecefCameraPosition); } updateModel(); if(theGSD.isNan()) { try { computeGsd(); } catch (const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPpjFrameSensor::loadState Caught Exception:\n" << e.what() << std::endl; } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimPpjFrameSensor::loadState complete..." << std::endl; } return result; } bool ossimPpjFrameSensor::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimSensorModel::saveState(kwl, prefix); // kwl.add(prefix, "roll", ossimString::toString(m_roll), true); // kwl.add(prefix, "pitch", ossimString::toString(m_pitch), true); // kwl.add(prefix, "yaw", ossimString::toString(m_yaw), true); kwl.add(prefix, "gsd", theGSD.toString(), true); kwl.add(prefix, "principal_point", m_principalPoint.toString(), true); kwl.add(prefix, "ecef_camera_position",m_ecefCameraPosition.toString() ,true); kwl.add(prefix, "focal_length_x", ossimString::toString(m_focalLengthX) ,true); kwl.add(prefix, "focal_length_y", ossimString::toString(m_focalLengthY) ,true); kwl.add(prefix, "image_size", theImageSize.toString() ,true); kwl.add(prefix, "average_projected_height", m_averageProjectedHeight, true); ossimString row1 = ossimString::toString(m_ecef2Cam[0][0]) + " " + ossimString::toString(m_ecef2Cam[0][1]) + " " + ossimString::toString(m_ecef2Cam[0][2]); kwl.add(prefix, "ecf_to_cam_row1", row1, true); ossimString row2 = ossimString::toString(m_ecef2Cam[1][0]) + " " + ossimString::toString(m_ecef2Cam[1][1]) + " " + ossimString::toString(m_ecef2Cam[1][2]); kwl.add(prefix, "ecf_to_cam_row2", row2, true); ossimString row3 = ossimString::toString(m_ecef2Cam[2][0]) + " " + ossimString::toString(m_ecef2Cam[2][1]) + " " + ossimString::toString(m_ecef2Cam[2][2]); kwl.add(prefix, "ecf_to_cam_row3", row3, true); return true; } ossim-Miami-2.9.1/src/projection/ossimProjection.cpp000066400000000000000000000135661352751253100225640ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Base class for all projections. //******************************************************************* // $Id: ossimProjection.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimProjection:exec"); static ossimTrace traceDebug ("ossimProjection:debug"); using namespace std; RTTI_DEF1(ossimProjection, "ossimProjection", ossimObject); //******************************************************************* // Public constructor: //******************************************************************* ossimProjection::ossimProjection() { } //***************************************************************************** // METHOD: ossimProjection::saveState() //***************************************************************************** bool ossimProjection::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::TYPE_KW, TYPE_NAME(this), true); return true; } //***************************************************************************** // METHOD: ossimProjection::loadState() //***************************************************************************** bool ossimProjection::loadState(const ossimKeywordlist& /* kwl */, const char* /* prefix */) { return true; } //***************************************************************************** // METHOD: ossimProjection::worldToLineSample() // // Performs forward projection of ground point to image space via iterative // calls to lineSampleHeightToWorld // //***************************************************************************** void ossimProjection::worldToLineSample(const ossimGpt& worldPoint, ossimDpt& ip) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimProjection::worldToLineSample: entering..." << std::endl; static const double PIXEL_THRESHOLD = 0.1; // acceptable pixel error static const int MAX_NUM_ITERATIONS = 20; //*** // First check if the world point is inside bounding rectangle: //*** int iters = 0; double height = worldPoint.hgt; if ( ossim::isnan(height) ) { height = 0.0; } //*** // Utilize iterative scheme for arriving at image point. Begin with guess // at image center: //*** ip.u = 0; ip.v = 0; ossimDpt ip_du; ossimDpt ip_dv; ossimGpt gp, gp_du, gp_dv; double dlat_du, dlat_dv, dlon_du, dlon_dv; double delta_lat, delta_lon, delta_u, delta_v; double inverse_norm; //*** // Begin iterations: //*** do { //*** // establish perturbed image points about the guessed point: //*** ip_du.u = ip.u + 1.0; ip_du.v = ip.v; ip_dv.u = ip.u; ip_dv.v = ip.v + 1.0; //*** // Compute numerical partials at current guessed point: //*** lineSampleHeightToWorld(ip, height, gp); lineSampleHeightToWorld(ip_du, height, gp_du); lineSampleHeightToWorld(ip_dv, height, gp_dv); dlat_du = gp_du.lat - gp.lat; //e dlon_du = gp_du.lon - gp.lon; //g dlat_dv = gp_dv.lat - gp.lat; //f dlon_dv = gp_dv.lon - gp.lon; //h //*** // Test for convergence: //*** delta_lat = worldPoint.lat - gp.lat; delta_lon = worldPoint.lon - gp.lon; //*** // Compute linearized estimate of image point given gp delta: //*** inverse_norm = dlat_dv*dlon_du - dlat_du*dlon_dv; // fg-eh if (inverse_norm != 0) { delta_u = (-dlon_dv*delta_lat + dlat_dv*delta_lon)/inverse_norm; delta_v = ( dlon_du*delta_lat - dlat_du*delta_lon)/inverse_norm; ip.u += delta_u; ip.v += delta_v; } else { delta_u = 0; delta_v = 0; } iters++; } while (((fabs(delta_u) > PIXEL_THRESHOLD) || (fabs(delta_v) > PIXEL_THRESHOLD)) && (iters < MAX_NUM_ITERATIONS)); //*** // Note that this error mesage appears only if max count was reached while // iterating. A linear (no iteration) solution would finish with iters = // MAX_NUM_ITERATIONS + 1: //*** if (iters == MAX_NUM_ITERATIONS) { // ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimProjection::worldToLineSample: Exceeded max number of iterations computing image \n" // << "point for ground point: " << worldPoint // << "\nCheck the geometry file for valid quantities." << endl; } } void ossimProjection::getRoundTripError(const ossimDpt& imagePoint, ossimDpt& errorResult)const { ossimGpt world; ossimDpt testPt; lineSampleToWorld(imagePoint, world); worldToLineSample(world, testPt); errorResult = imagePoint - testPt; } void ossimProjection::getRoundTripError(const ossimGpt& groundPoint, ossimDpt& errorResult)const { ossimDpt tempPt; ossimGpt tempGround; worldToLineSample(groundPoint, tempPt); lineSampleToWorld(tempPt, tempGround); errorResult = ossimDpt(groundPoint) - ossimDpt(tempGround); } void ossimProjection::getGroundClipPoints(ossimGeoPolygon& /* gpts */)const { } std::ostream& ossimProjection::print(std::ostream& out) const { return ossimErrorStatusInterface::print(out); } ossim-Miami-2.9.1/src/projection/ossimProjectionFactoryBase.cpp000066400000000000000000000065071352751253100247040ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts //******************************************************************* // $Id: ossimProjectionFactoryBase.cpp 22626 2014-02-11 22:18:06Z dburken $ #include #include #include #include #include //--- // Define Trace flags for use within this file: //--- #include static ossimTrace traceDebug = ossimTrace("ossimProjectionFactoryBase:debug"); RTTI_DEF1(ossimProjectionFactoryBase, "ossimProjectionFactoryBase", ossimObjectFactory); ossimProjection* ossimProjectionFactoryBase::createProjectionFromGeometryFile(const ossimFilename& imageFile, ossim_uint32 entryIdx)const { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimProjectionFactoryBase::createProjectionFromGeometryFile " << "DEBUG:" << "\nimageFile: " << imageFile << "\nentryIdx: " << entryIdx << std::endl; } // Try to find a geometry file for imageFile. ossimFilename geomFile = imageFile; if (entryIdx == 0) { geomFile.setExtension("geom"); if(geomFile.exists()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Found geometry file: " << geomFile << std::endl; } ossimKeywordlist kwl; if(kwl.addFile(geomFile)) { //--- // Add the geometry file to the keyword list. // This was added for ossimCoarseGridModel so it can pick up the // file.ocg with a relative path. // // NOTE: The can't be called "geometry_file" as it causes an infinite loop in the factory // code. (drb - 20140211) //--- kwl.addPair( std::string("kwl_source"), geomFile.expand().string(), false); // Don't overwrite if in there already. return ossimProjectionFactoryRegistry::instance()-> createProjection(kwl); } } } // Look for an indexed geometry file. geomFile = imageFile.fileNoExtension(); geomFile += "_e"; geomFile += ossimString::toString(entryIdx); geomFile.setExtension("geom"); if(geomFile.exists()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Found geometry file: " << geomFile << std::endl; } ossimKeywordlist kwl; if(kwl.addFile(geomFile)) { return ossimProjectionFactoryRegistry::instance()-> createProjection(kwl); } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: No geometry file found. Returning NULL..." << std::endl; } return NULL; } ossimProjection* ossimProjectionFactoryBase::createProjection(ossimImageHandler* handler)const { if(!handler) return 0; return createProjection(handler->getFilename(), handler->getCurrentEntry()); } ossim-Miami-2.9.1/src/projection/ossimProjectionFactoryRegistry.cpp000066400000000000000000000135651352751253100256440ustar00rootroot00000000000000//******************************************************************* // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimProjectionFactoryRegistry.cpp 22898 2014-09-29 15:22:32Z okramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if OSSIM_HAS_HDF5 #include #endif //ossimProjectionFactoryRegistry* ossimProjectionFactoryRegistry::m_instance = 0; ossimProjectionFactoryRegistry::ossimProjectionFactoryRegistry() { initializeDefaults(); ossimObjectFactoryRegistry::instance()->registerFactory(this); } ossimProjectionFactoryRegistry::ossimProjectionFactoryRegistry(const ossimProjectionFactoryRegistry& rhs) : ossimObjectFactory(rhs) {} void ossimProjectionFactoryRegistry::operator=(const ossimProjectionFactoryRegistry&) {} ossimProjectionFactoryRegistry::~ossimProjectionFactoryRegistry() { } ossimProjectionFactoryRegistry* ossimProjectionFactoryRegistry::instance() { static ossimProjectionFactoryRegistry inst; return &inst; // if(!m_instance) // { // m_instance = new ossimProjectionFactoryRegistry(); // } // return m_instance; } ossimProjection* ossimProjectionFactoryRegistry::createProjection(const ossimFilename& name, ossim_uint32 entryIdx)const { ossimProjection* result = 0; ossim_uint32 idx = 0; for(idx = 0; ((idx < m_factoryList.size())&&(!result)); ++idx) { result = m_factoryList[idx]->createProjection(name, entryIdx); } return result; } ossimProjection* ossimProjectionFactoryRegistry::createProjection(ossimImageHandler* handler)const { ossimProjection* result = 0; ossim_uint32 idx = 0; for(idx = 0; ((idx < m_factoryList.size())&&(!result)); ++idx) { result = m_factoryList[idx]->createProjection(handler); } return result; } ossimProjection* ossimProjectionFactoryRegistry::createProjection( const ossimKeywordlist& kwl, const char* prefix)const { ossimProjection* result = 0;//createNativeObjectFromRegistry(kwl, prefix); ossim_uint32 idx = 0; for(idx = 0; ((idx < m_factoryList.size())&&!result);++idx) { result = m_factoryList[idx]->createProjection(kwl, prefix); } if ( (result == 0) && (prefix == 0) ) { //--- // Check for an embedded prefix like "image0." // // This is a workaround for people who use the "image_info" application // to create a geometry file. // // If the image has an external geometry file and it has a prefix like // "image0." and someone does: // // theInputConnection->getImageGeometry(kwl); // ossimRefPtr proj = // ossimProjectionFactoryRegistry::instance()->createProjection(kwl); // // It will fail because the factory doesn't know it has a prefix. // // ESH 01/2009: I've changed the following so that not just the first // line is checked for "image" and ".". If the image_info .geom file // was created with the -m (metadata) option, the first lines of the // file will not have the expected structure. //--- bool bFoundImageLine = false; ossimKeywordlist::KeywordMap::const_iterator i = kwl.getMap().begin(); while ( (i != kwl.getMap().end()) && (bFoundImageLine == false) ) { ossimString s1 = (*i).first; if ( s1.size() ) { std::vector v; s1.split(v, ossimString(".")); if ( v.size() ) { if ( v[0].contains("image") ) { bFoundImageLine = true; ossimString s2 = v[0]; s2 += "."; idx = 0; for(;((idx < m_factoryList.size())&&!result); ++idx) { result = m_factoryList[idx]->createProjection(kwl, s2.c_str()); } } } } // Go to the next line of the .geom file ++i; } } return result; } void ossimProjectionFactoryRegistry::initializeDefaults() { registerFactory(ossimSensorModelFactory::instance()); registerFactory(ossimNitfProjectionFactory::instance()); registerFactory(ossimTiffProjectionFactory::instance()); registerFactory(ossimWktProjectionFactory::instance()); registerFactory(ossimMapProjectionFactory::instance()); registerFactory(ossimMiscProjectionFactory::instance()); registerFactory(ossimNgaProjectionFactory::instance()); #if OSSIM_HAS_HDF5 registerFactory(ossimHdf5ProjectionFactory::instance()); #endif // KEEP THIS LAST PLEASE! // This factory constructs map projections from EPSG codes. An infinite loop will occur if this // is placed before the explicit (non-coded) factories, since this factory will invoke the above // factories via this registry after populating a KWL which includes a PCS code. If this factory // sees that request before the others, it will be caught in a loop. registerFactory(ossimEpsgProjectionFactory::instance()); } extern "C" { void* ossimProjectionFactoryRegistryGetInstance() { return ossimProjectionFactoryRegistry::instance(); } } ossim-Miami-2.9.1/src/projection/ossimProjectionViewControllerFactory.cpp000066400000000000000000000045251352751253100270060ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks) // Description: // //************************************************************************* // $Id: ossimProjectionViewControllerFactory.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include #include #include #include RTTI_DEF1(ossimProjectionViewControllerFactory, "ossimProjectionViewControllerFactory", ossimObjectFactory); ossimProjectionViewControllerFactory* ossimProjectionViewControllerFactory::theInstance = NULL; ossimProjectionViewControllerFactory* ossimProjectionViewControllerFactory::instance() { if(!theInstance) { theInstance = new ossimProjectionViewControllerFactory; } return theInstance; } ossimViewController* ossimProjectionViewControllerFactory::createViewController(const ossimString& name)const { if(name == STATIC_TYPE_NAME(ossimMapViewController)) { return new ossimMapViewController; } return (ossimViewController*)NULL; } ossimViewController* ossimProjectionViewControllerFactory::createViewController(const ossimKeywordlist& kwl, const char* prefix)const { const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); ossimViewController* result = NULL; if(type) { result = createViewController(ossimString(type)); if(result) { if(!result->loadState(kwl, prefix)) { delete result; result = NULL; } } } return result; } ossimObject* ossimProjectionViewControllerFactory::createObject(const ossimString& typeName)const { return createViewController(typeName); } ossimObject* ossimProjectionViewControllerFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { return createViewController(kwl, prefix); } void ossimProjectionViewControllerFactory::getTypeNameList(std::vector& typeList)const { typeList.push_back("ossimMapViewController"); } ossim-Miami-2.9.1/src/projection/ossimQuadProjection.cpp000066400000000000000000000331251352751253100233700ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimQuadProjection.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimQuadProjection, "ossimQuadProjection", ossimProjection); ossimQuadProjection::ossimQuadProjection() :ossimProjection() { theInputRect.makeNan(); theUlg.makeNan(); theUrg.makeNan(); theLrg.makeNan(); theLlg.makeNan(); } ossimQuadProjection::ossimQuadProjection(const ossimQuadProjection& rhs) :ossimProjection(rhs), theInputRect(rhs.theInputRect), theUlg(rhs.theUlg), theUrg(rhs.theUrg), theLrg(rhs.theLrg), theLlg(rhs.theLlg), theLatGrid(rhs.theLatGrid), theLonGrid(rhs.theLonGrid) { } ossimQuadProjection::ossimQuadProjection(const ossimIrect& rect, const ossimGpt& ulg, const ossimGpt& urg, const ossimGpt& lrg, const ossimGpt& llg) :theInputRect(rect), theUlg(ulg), theUrg(urg), theLrg(lrg), theLlg(llg) { initializeGrids(); } ossimQuadProjection::~ossimQuadProjection() { } ossimObject *ossimQuadProjection::dup()const { return new ossimQuadProjection(*this); } ossimGpt ossimQuadProjection::origin()const { ossimGpt result; result.makeNan(); if(theUlg.isLatNan()|| theUlg.isLonNan()|| theUrg.isLatNan()|| theUrg.isLonNan()|| theLrg.isLatNan()|| theLrg.isLonNan()|| theLlg.isLatNan()|| theLlg.isLonNan()) { return result; } result.latd( (theUlg.latd() + theUrg.latd() + theLrg.latd() + theLlg.latd())*.25); result.lond( (theUlg.lond() + theUrg.lond() + theLrg.lond() + theLlg.lond())*.25); result.datum(theUlg.datum()); return result; } void ossimQuadProjection::worldToLineSample(const ossimGpt& worldPoint, ossimDpt& lineSampPt) const { ossimProjection::worldToLineSample(worldPoint, lineSampPt); } void ossimQuadProjection::lineSampleToWorld(const ossimDpt& lineSampPt, ossimGpt& worldPt) const { lineSampleHeightToWorld(lineSampPt, ossim::nan(), worldPt); } void ossimQuadProjection::lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& heightAboveEllipsoid, ossimGpt& worldPt) const { worldPt.makeNan(); worldPt.datum(theUlg.datum()); if(theUlg.isLatNan()|| theUlg.isLonNan()|| theUrg.isLatNan()|| theUrg.isLonNan()|| theLrg.isLatNan()|| theLrg.isLonNan()|| theLlg.isLatNan()|| theLlg.isLonNan()|| theInputRect.hasNans()) { return; } if(!theInputRect.pointWithin(lineSampPt)) { worldPt = extrapolate(lineSampPt, heightAboveEllipsoid); worldPt.hgt = ossimElevManager::instance()->getHeightAboveEllipsoid(worldPt); return; } worldPt.lat = theLatGrid(lineSampPt); worldPt.lon = theLonGrid(lineSampPt); worldPt.hgt = heightAboveEllipsoid; worldPt.hgt = ossimElevManager::instance()->getHeightAboveEllipsoid(worldPt); } bool ossimQuadProjection::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimProjection::saveState(kwl, prefix); kwl.add(prefix, ossimKeywordNames::DATUM_KW, theUlg.datum()->code(), true); if(theInputRect.hasNans()) { kwl.add(prefix, ossimKeywordNames::UL_X_KW, "nan", true); kwl.add(prefix, ossimKeywordNames::UL_Y_KW, "nan", true); kwl.add(prefix, "width", 0, true); kwl.add(prefix, "height", 0, true); } else { kwl.add(prefix, ossimKeywordNames::UL_X_KW, theInputRect.ul().x, true); kwl.add(prefix, ossimKeywordNames::UL_Y_KW, theInputRect.ul().y, true); kwl.add(prefix, "width", theInputRect.width(), true); kwl.add(prefix, "height", theInputRect.height(), true); } if(theUlg.isLatNan()|| theUlg.isLonNan()|| theUrg.isLatNan()|| theUrg.isLonNan()|| theLrg.isLatNan()|| theLrg.isLonNan()|| theLlg.isLatNan()|| theLlg.isLonNan()) { kwl.add(prefix, ossimKeywordNames::UL_LAT_KW, "nan", true); kwl.add(prefix, ossimKeywordNames::UL_LON_KW, "nan", true); kwl.add(prefix, ossimKeywordNames::UR_LAT_KW, "nan", true); kwl.add(prefix, ossimKeywordNames::UR_LON_KW, "nan", true); kwl.add(prefix, ossimKeywordNames::LR_LAT_KW, "nan", true); kwl.add(prefix, ossimKeywordNames::LR_LON_KW, "nan", true); kwl.add(prefix, ossimKeywordNames::LL_LAT_KW, "nan", true); kwl.add(prefix, ossimKeywordNames::LL_LON_KW, "nan", true); } else { kwl.add(prefix, ossimKeywordNames::UL_LAT_KW, theUlg.latd(), true); kwl.add(prefix, ossimKeywordNames::UL_LON_KW, theUlg.lond(), true); kwl.add(prefix, ossimKeywordNames::UR_LAT_KW, theUrg.latd(), true); kwl.add(prefix, ossimKeywordNames::UR_LON_KW, theUrg.lond(), true); kwl.add(prefix, ossimKeywordNames::LR_LAT_KW, theLrg.latd(), true); kwl.add(prefix, ossimKeywordNames::LR_LON_KW, theLrg.lond(), true); kwl.add(prefix, ossimKeywordNames::LL_LAT_KW, theLlg.latd(), true); kwl.add(prefix, ossimKeywordNames::LL_LON_KW, theLlg.lond(), true); } return true; } bool ossimQuadProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimProjection::loadState(kwl, prefix); theUlg.makeNan(); theUrg.makeNan(); theLrg.makeNan(); theLlg.makeNan(); theInputRect.makeNan(); ossimString ulLat = kwl.find(prefix, ossimKeywordNames::UL_LAT_KW); ossimString ulLon = kwl.find(prefix, ossimKeywordNames::UL_LON_KW); ossimString urLat = kwl.find(prefix, ossimKeywordNames::UR_LAT_KW); ossimString urLon = kwl.find(prefix, ossimKeywordNames::UR_LON_KW); ossimString lrLat = kwl.find(prefix, ossimKeywordNames::LR_LAT_KW); ossimString lrLon = kwl.find(prefix, ossimKeywordNames::LR_LON_KW); ossimString llLat = kwl.find(prefix, ossimKeywordNames::LL_LAT_KW); ossimString llLon = kwl.find(prefix, ossimKeywordNames::LL_LON_KW); ossimString datum = kwl.find(prefix, ossimKeywordNames::DATUM_KW); ossimString ulX = kwl.find(prefix, ossimKeywordNames::UL_X_KW); ossimString ulY = kwl.find(prefix, ossimKeywordNames::UL_Y_KW); ossimString width = kwl.find(prefix, "width"); ossimString height = kwl.find(prefix, "height"); if(ulLat == "nan") { theUlg.latd(ossim::nan()); } else { theUlg.latd(ulLat.toDouble()); } if(ulLon == "nan") { theUlg.lond(ossim::nan()); } else { theUlg.lond(ulLon.toDouble()); } if(urLat == "nan") { theUrg.latd(ossim::nan()); } else { theUrg.latd(urLat.toDouble()); } if(urLon == "nan") { theUrg.lond(ossim::nan()); } else { theUrg.lond(urLon.toDouble()); } if(lrLat == "nan") { theLrg.latd(ossim::nan()); } else { theLrg.latd(lrLat.toDouble()); } if(lrLon == "nan") { theLrg.lond(ossim::nan()); } else { theLrg.lond(lrLon.toDouble()); } if(llLat == "nan") { theLlg.latd(ossim::nan()); } else { theLlg.latd(llLat.toDouble()); } if(llLon == "nan") { theLlg.lond(ossim::nan()); } else { theLlg.lond(llLon.toDouble()); } ossimIpt ul; ul.makeNan(); if((ulX != "nan") && (ulY != "nan")) { ul.x = ulX.toInt32(); ul.y = ulY.toInt32(); } ossim_uint32 w = width.toUInt32(); ossim_uint32 h = height.toUInt32(); if(datum == "") { datum = "WGE"; } const ossimDatum* datumPtr = ossimDatumFactory::instance()->create(datum); theUlg.datum(datumPtr); theUrg.datum(datumPtr); theLrg.datum(datumPtr); theLlg.datum(datumPtr); if(w&&h) { theInputRect = ossimIrect(ul.x, ul.y, ul.x + w - 1, ul.y + h - 1); } else { theInputRect.makeNan(); } initializeGrids(); return true; } bool ossimQuadProjection::operator==(const ossimProjection& /* projection */) const { return false; } ossimDpt ossimQuadProjection::getMetersPerPixel() const { ossimGpt centerG; ossimGpt rightG; ossimGpt topG; lineSampleToWorld(theInputRect.midPoint(), centerG); lineSampleToWorld(theInputRect.midPoint()+ossimDpt(1,0), rightG); lineSampleToWorld(theInputRect.midPoint()+ossimDpt(0,-1), topG); ossimEcefPoint centerP = centerG; ossimEcefPoint rightP = rightG; ossimEcefPoint topP = topG; ossimEcefVector horizontal = rightP-centerP; ossimEcefVector vertical = topP-centerP; ossimDpt result(horizontal.magnitude(), vertical.magnitude()); result.x = (result.x + result.y)/2.0; result.y = result.x; return result; } void ossimQuadProjection::initializeGrids() { ossimIpt gridSize(2,2); ossimDpt spacing = ossimDpt((double)(theInputRect.width()-1)/(gridSize.x-1), (double)(theInputRect.height()-1)/(gridSize.y-1)); theLatGrid.setNullValue(ossim::nan()); theLonGrid.setNullValue(ossim::nan()); theLatGrid.initialize(gridSize, theInputRect.ul(), spacing); theLonGrid.initialize(gridSize, theInputRect.ul(), spacing); theLatGrid.setNode(0,0, theUlg.latd()); theLatGrid.setNode(1,0, theUrg.latd()); theLatGrid.setNode(1,1, theLrg.latd()); theLatGrid.setNode(0,1, theLlg.latd()); theLonGrid.setNode(0,0, theUlg.lond()); theLonGrid.setNode(1,0, theUrg.lond()); theLonGrid.setNode(1,1, theLrg.lond()); theLonGrid.setNode(0,1, theLlg.lond()); } ossimGpt ossimQuadProjection::extrapolate(const ossimDpt& imagePoint, const double& height) const { //--- // If image point supplied has NaN components, return now with a NaN point. // This prevents an infinite recursion between model worldToLineSample // and this method: //--- if (imagePoint.hasNans()) { return ossimGpt(ossim::nan(), ossim::nan(), ossim::nan()); } //*** // Determine which edge is intersected by the radial, and establish // intersection: //*** ossimGpt gpt; ossimDpt edgePt (imagePoint); ossimDpt image_center (theInputRect.midPoint()); ossimDrect clipRect = theInputRect; clipRect.clip(image_center, edgePt); //*** // Need edgePt relative to image center. Compute an epsilon perturbation in // the direction of edgePt for later computing directional derivative, // and back out the offset to origin: //*** ossimDpt deltaPt (edgePt - image_center); ossimDpt epsilon (deltaPt/deltaPt.length()); edgePt -= epsilon; // insure that we are inside the image ossimDpt edgePt_prime (edgePt - epsilon); // epsilon=1pixel //*** // Establish ground point corresponding to edge point and edgePt+epsilon: //*** ossimGpt edgeGP; ossimGpt edgeGP_prime; if (ossim::isnan(height)) { lineSampleToWorld(edgePt, edgeGP); lineSampleToWorld(edgePt_prime, edgeGP_prime); } else { lineSampleHeightToWorld(edgePt, height, edgeGP); lineSampleHeightToWorld(edgePt_prime, height, edgeGP_prime); } //*** // Compute approximate directional derivatives of lat and lon along radial // at the edge: //*** double dpixel = (edgePt-edgePt_prime).length(); double dlat_drad = (edgeGP.lat - edgeGP_prime.lat)/dpixel; double dlon_drad = (edgeGP.lon - edgeGP_prime.lon)/dpixel; //*** // Now extrapolate to image point of interest: //*** double delta_pixel = (imagePoint - edgePt).length(); gpt.lat = edgeGP.lat + dlat_drad*delta_pixel; gpt.lon = edgeGP.lon + dlon_drad*delta_pixel; // if (height == OSSIM_DBL_NAN) // { // gpt.hgt = theElevation->getHeightAboveMSL(gpt); // } // else gpt.hgt = height; return gpt; } ossim-Miami-2.9.1/src/projection/ossimQuickbirdRpcModel.cpp000066400000000000000000000465751352751253100240210ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimQuickbirdRpcModel.cpp // // License: See top level LICENSE.txt file. // // DESCRIPTION: Contains declaration of class ossimQuickbirdRpcModel. This // derived class implements the capability of reading Quickbird RPC support // data. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimQuickbirdRpcModel.cpp 23564 2015-10-02 14:12:25Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const char *RPC00A_TAG = "RPC00A"; static const char *RPC00B_TAG = "RPC00B"; static const char *ICHIPB_TAG = "ICHIPB"; static const char *PIAIMC_TAG = "PIAIMC"; static const char *USE00A_TAG = "USE00A"; RTTI_DEF1(ossimQuickbirdRpcModel, "ossimQuickbirdRpcModel", ossimRpcModel); //************************************************************************************************* // Constructor //************************************************************************************************* ossimQuickbirdRpcModel::ossimQuickbirdRpcModel() : ossimRpcModel(), theSupportData(new ossimQuickbirdMetaData()) { } //************************************************************************************************* // Constructor //************************************************************************************************* ossimQuickbirdRpcModel::ossimQuickbirdRpcModel(const ossimQuickbirdRpcModel &rhs) : ossimRpcModel(rhs), theSupportData(new ossimQuickbirdMetaData()) { } //************************************************************************************************* //! Constructor for multiple tile-files sharing common RPC model initializes given pointer //! to multi-tile-files handler. //************************************************************************************************* ossimQuickbirdRpcModel::ossimQuickbirdRpcModel(const ossimQbTileFilesHandler *handler) : ossimRpcModel(), theSupportData(new ossimQuickbirdMetaData()) { setErrorStatus(); if (!handler) return; // Make the gsd nan so it gets computed. theGSD.makeNan(); theImageClipRect = handler->getImageRectangle(); ossimFilename imageFile = handler->getFilename(); if (!parseRpcData(imageFile)) return; finishConstruction(); clearErrorStatus(); return; } //************************************************************************************************* // Destructor //************************************************************************************************* ossimQuickbirdRpcModel::~ossimQuickbirdRpcModel() { theSupportData = 0; } //************************************************************************************************* // Infamous DUP //************************************************************************************************* ossimObject *ossimQuickbirdRpcModel::dup() const { return new ossimQuickbirdRpcModel(*this); } //************************************************************************************************* //! Public method for parsing generic image file. //************************************************************************************************* bool ossimQuickbirdRpcModel::parseFile(const ossimFilename &file) { bool result = true; while (1) { if (parseNitfFile(file)) break; if (parseTiffFile(file)) break; result = false; break; } return result; } //************************************************************************************************* //! Parses a NITF image file for RPC info. Returns TRUE if successful. //************************************************************************************************* bool ossimQuickbirdRpcModel::parseNitfFile(const ossimFilename &file) { setErrorStatus(); //--- // ossimNitfFile::parseFile(...) checks the first eight byte so three calls // to parseFile are not necessary. drb - 21 Dec. 2016 //--- ossimRefPtr nitfFilePtr = new ossimNitfFile; if (nitfFilePtr->parseFile(file) == false) { return false; } #if 0 ossimFilename nitfFile = file; ossimRefPtr nitfFilePtr = new ossimNitfFile; if(!nitfFilePtr->parseFile(nitfFile)) { nitfFile = nitfFile.setExtension("NTF"); if(!nitfFilePtr->parseFile(nitfFile)) { nitfFile = nitfFile.setExtension("ntf"); if(!nitfFilePtr->parseFile(nitfFile)) return false; } } #endif ossimRefPtr ih = nitfFilePtr->getNewImageHeader(0); if (!ih) return false; theImageClipRect = ih->getImageRect(); // Give preference to external RPC data file. Only consider external tiling data if RPC is // provided externally, otherwise expect ICHIPB in NITF: bool useInternalRpcTags = true; if (parseRpcData(file)) { useInternalRpcTags = false; if (!parseTileData(file)) return false; } // Check for IMD (metadata) file: parseMetaData(file); // Get the gsd. theGSD.line = ossim::nan(); theGSD.samp = ossim::nan(); ossimRefPtr tag; tag = ih->getTagData(PIAIMC_TAG); if (tag.valid()) { ossimNitfPiaimcTag *p = PTR_CAST(ossimNitfPiaimcTag, tag.get()); if (p) { theGSD.line = p->getMeanGsdInMeters(); theGSD.samp = theGSD.line; } } if (ossim::isnan(theGSD.line)) { tag = ih->getTagData(USE00A_TAG); if (tag.valid()) { ossimNitfUse00aTag *p = PTR_CAST(ossimNitfUse00aTag, tag.get()); if (p) { theGSD.line = p->getMeanGsdInMeters(); theGSD.samp = theGSD.line; } } } // If external RPC data file was correctly parsed, then we can bypass this code block. Otherwise // need to parse internal NITF tags for RPC data: if (useInternalRpcTags) { // Get the the RPC tag: ossimNitfRpcBase *rpcTag = NULL; // Look for the RPC00B tag first. tag = ih->getTagData(RPC00B_TAG); if (tag.valid()) rpcTag = PTR_CAST(ossimNitfRpcBase, tag.get()); if (!tag.valid()) { // Look for RPC00A tag. tag = ih->getTagData(RPC00A_TAG); if (tag.valid()) rpcTag = PTR_CAST(ossimNitfRpcBase, tag.get()); } if (!rpcTag) return false; // Set the polynomial type. if (rpcTag->getRegisterTagName() == "RPC00B") thePolyType = B; else thePolyType = A; // Parse coefficients: for (ossim_uint32 i = 0; i < 20; ++i) { theLineNumCoef[i] = rpcTag->getLineNumeratorCoeff(i).toFloat64(); theLineDenCoef[i] = rpcTag->getLineDenominatorCoeff(i).toFloat64(); theSampNumCoef[i] = rpcTag->getSampleNumeratorCoeff(i).toFloat64(); theSampDenCoef[i] = rpcTag->getSampleDenominatorCoeff(i).toFloat64(); } // Initialize other items in tags: theLineScale = rpcTag->getLineScale().toFloat64(); theSampScale = rpcTag->getSampleScale().toFloat64(); theLatScale = rpcTag->getGeodeticLatScale().toFloat64(); theLonScale = rpcTag->getGeodeticLonScale().toFloat64(); theHgtScale = rpcTag->getGeodeticHeightScale().toFloat64(); theLineOffset = rpcTag->getLineOffset().toFloat64(); theSampOffset = rpcTag->getSampleOffset().toFloat64(); theLatOffset = rpcTag->getGeodeticLatOffset().toFloat64(); theLonOffset = rpcTag->getGeodeticLonOffset().toFloat64(); theHgtOffset = rpcTag->getGeodeticHeightOffset().toFloat64(); theBiasError = rpcTag->getErrorBias().toFloat64(); theRandError = rpcTag->getErrorRand().toFloat64(); theImageID = ih->getImageId(); } finishConstruction(); clearErrorStatus(); return true; } //************************************************************************************************* //! Parses a tagged TIFF image file for RPC info. Returns TRUE if successful. //************************************************************************************************* bool ossimQuickbirdRpcModel::parseTiffFile(const ossimFilename &file) { setErrorStatus(); // Make the gsd nan so it gets computed. theGSD.makeNan(); ossimFilename tiffFile = file; ossimRefPtr tiff = new ossimTiffTileSource(); if (!tiff->open(file)) { return false; } theImageClipRect = tiff->getImageRectangle(); parseMetaData(file); // TIFF format expects the RPC and TILE info to be provided externally: if (!parseRpcData(file)) return false; // If no TIL data present, assumes full image: if (!parseTileData(file)) return false; finishConstruction(); clearErrorStatus(); return true; } //************************************************************************************************* //! Given some base name for the image data, parses the associated RPC data file. Returns TRUE //! if successful //************************************************************************************************* bool ossimQuickbirdRpcModel::parseRpcData(const ossimFilename &base_name) { ossimFilename rpcFile(base_name); // Make the gsd nan so it gets computed. theGSD.makeNan(); // There are three possibilities for RPC data files: either each image file has its own RPC data // file, or a single RPC file is provided for a multi-tile scene. while (1) { rpcFile.setExtension("RPB"); if (findSupportFile(rpcFile)) break; rpcFile.setExtension("RPA"); if (findSupportFile(rpcFile)) break; rpcFile.setExtension("XML"); if (findSupportFile(rpcFile)) break; return false; } // An RPC file was located, open it: m_qbRpcHeader = std::make_shared(); if (!m_qbRpcHeader->open(rpcFile)) { m_qbRpcHeader = 0; return false; } if (m_qbRpcHeader->isAPolynomial()) thePolyType = A; else thePolyType = B; std::copy(m_qbRpcHeader->theLineNumCoeff.begin(), m_qbRpcHeader->theLineNumCoeff.end(), theLineNumCoef); std::copy(m_qbRpcHeader->theLineDenCoeff.begin(), m_qbRpcHeader->theLineDenCoeff.end(), theLineDenCoef); std::copy(m_qbRpcHeader->theSampNumCoeff.begin(), m_qbRpcHeader->theSampNumCoeff.end(), theSampNumCoef); std::copy(m_qbRpcHeader->theSampDenCoeff.begin(), m_qbRpcHeader->theSampDenCoeff.end(), theSampDenCoef); theLineScale = m_qbRpcHeader->theLineScale; theSampScale = m_qbRpcHeader->theSampScale; theLatScale = m_qbRpcHeader->theLatScale; theLonScale = m_qbRpcHeader->theLonScale; theHgtScale = m_qbRpcHeader->theHeightScale; theLineOffset = m_qbRpcHeader->theLineOffset; theSampOffset = m_qbRpcHeader->theSampOffset; theLatOffset = m_qbRpcHeader->theLatOffset; theLonOffset = m_qbRpcHeader->theLonOffset; theHgtOffset = m_qbRpcHeader->theHeightOffset; theBiasError = m_qbRpcHeader->theErrBias; theRandError = m_qbRpcHeader->theErrRand; theImageID = rpcFile.fileNoExtension(); if (theImageSize.length() == 0) { theImageSize.x = 2 * (int) theSampOffset; theImageSize.y = 2 * (int) theLineOffset; theRefImgPt = ossimDpt(theSampOffset, theLineOffset); } finishConstruction(); return true; } //************************************************************************************************* //! Initializes the support data member with metadata file info. Returns TRUE if successful //************************************************************************************************* bool ossimQuickbirdRpcModel::parseMetaData(const ossimFilename &base_name) { ossimFilename metadataFile(base_name); metadataFile.setExtension("IMD"); if (!findSupportFile(metadataFile)) return false; if (!theSupportData.valid()) theSupportData = new ossimQuickbirdMetaData(); if (!theSupportData->open(metadataFile)) { theSupportData = 0; // ossimRefPtr #if 0 /* This should be wrapped in trace. drb */ ossimNotify(ossimNotifyLevel_WARN) << "ossimQuickbirdRpcModel::parseMetaData WARNING:" << "\nCould not open IMD file. Sensor ID unknown." << std::endl; #endif return false; } theSensorID = theSupportData->getSatID(); return true; } //************************************************************************************************* //! Reads the TIL file for pertinent info. Returns TRUE if successful //************************************************************************************************* bool ossimQuickbirdRpcModel::parseTileData(const ossimFilename &image_file) { ossimFilename tileFile(image_file); tileFile.setExtension("TIL"); // The TIL file is optional. Consider the image to be the full image if not present: if (!findSupportFile(tileFile)) return true; ossimQuickbirdTile tileHdr; if (!tileHdr.open(tileFile)) return false; ossimQuickbirdTileInfo info; if (!tileHdr.getInfo(info, image_file.file())) return false; // if((info.theUlXOffset != OSSIM_INT_NAN) && (info.theUlYOffset != OSSIM_INT_NAN) && // (info.theLrXOffset != OSSIM_INT_NAN) && (info.theLrYOffset != OSSIM_INT_NAN) && // (info.theLlXOffset != OSSIM_INT_NAN) && (info.theLlYOffset != OSSIM_INT_NAN) && // (info.theUrXOffset != OSSIM_INT_NAN) && (info.theUrYOffset != OSSIM_INT_NAN)) // { // theImageClipRect = ossimIrect(ossimIpt(info.theUlXOffset, info.theUlYOffset), // ossimIpt(info.theUrXOffset, info.theUrYOffset), // ossimIpt(info.theLrXOffset, info.theLrYOffset), // ossimIpt(info.theLlXOffset, info.theLlYOffset)); // } // else if ((info.theUlXOffset != OSSIM_INT_NAN) && (info.theUlYOffset != OSSIM_INT_NAN) && // (theImageClipRect.width() != OSSIM_INT_NAN) && (theImageClipRect.height() != OSSIM_INT_NAN)) // { // theImageClipRect = ossimIrect(info.theUlXOffset, info.theUlYOffset, // info.theUlXOffset+theImageClipRect.width()-1, // info.theUlYOffset+theImageClipRect.height()-1); // } // Define the RPC model's 2D transform for chipped imagery. Note that the TIL file will only // define an offset, not a full affine. Can only use the tile's UL corner: ossimDpt ul (info.theUlXOffset, info.theUlYOffset); //******************************************** // gpotts: I am not confident that the TIL is needed for the RPC WV02. The // RPC has a line and offset and what I have seen they are for the local // image not it's tile location. Added chack and will only use if its quickbird // // if (m_qbRpcHeader) { if (m_qbRpcHeader->isGlobal() && (!ul.hasNans())) { setImageOffset(ul); } } return true; } //************************************************************************************************* //! Collects common code among all parsers //************************************************************************************************* void ossimQuickbirdRpcModel::finishConstruction() { theImageSize.line = theImageClipRect.height(); theImageSize.samp = theImageClipRect.width(); theRefImgPt.line = theImageClipRect.midPoint().y; theRefImgPt.samp = theImageClipRect.midPoint().x; theRefGndPt.lat = theLatOffset; theRefGndPt.lon = theLonOffset; theRefGndPt.hgt = theHgtOffset; //--- // NOTE: We must call "updateModel()" to set parameter used by base // ossimRpcModel prior to calling lineSampleHeightToWorld or all // the world points will be same. //--- updateModel(); ossimGpt v0, v1, v2, v3; lineSampleHeightToWorld(theImageClipRect.ul(), theHgtOffset, v0); lineSampleHeightToWorld(theImageClipRect.ur(), theHgtOffset, v1); lineSampleHeightToWorld(theImageClipRect.lr(), theHgtOffset, v2); lineSampleHeightToWorld(theImageClipRect.ll(), theHgtOffset, v3); theBoundGndPolygon = ossimPolygon(ossimDpt(v0), ossimDpt(v1), ossimDpt(v2), ossimDpt(v3)); // Set the ground reference point using the model. lineSampleHeightToWorld(theRefImgPt, theHgtOffset, theRefGndPt); if (theGSD.hasNans()) { try { // This will set theGSD and theMeanGSD. Method throws ossimException. computeGsd(); } catch (const ossimException &e) { ossimNotify(ossimNotifyLevel_WARN) << "ossimQuickbirdRpcModel::finishConstruction -- caught exception:\n" << e.what() << std::endl; } } } bool ossimQuickbirdRpcModel::saveState(ossimKeywordlist &kwl, const char *prefix) const { // sanity check only. This shoulc always be true if (theSupportData.valid()) { ossimString supportPrefix = ossimString(prefix) + "support_data."; theSupportData->saveState(kwl, supportPrefix); } return ossimRpcModel::saveState(kwl, prefix); } bool ossimQuickbirdRpcModel::loadState(const ossimKeywordlist &kwl, const char *prefix) { // sanity check only. This shoulc always be true if (theSupportData.valid()) { ossimString supportPrefix = ossimString(prefix) + "support_data."; theSupportData->loadState(kwl, supportPrefix); } return ossimRpcModel::loadState(kwl, prefix); } //************************************************************************************************* // Given an initial filename with case-agnostic extension, this method searches first for an // image-specific instance of that file (i.e., with R*C* in the filename) before considering // the mosaic-global support file (R*C* removed). If a file is found, the argument is modified to // match the actual filename and TRUE is returned. Otherwise, argument filename is left unchanged // and FALSE is returned. //************************************************************************************************* bool ossimQuickbirdRpcModel::findSupportFile(ossimFilename &filename) const { ossimFilename f(filename); ossimString extension = f.ext(); if (f.exists()) { filename = f; return true; } // Search for support file with same basename as image: extension.upcase(); f.setExtension(extension); if (f.exists()) { filename = f; return true; } extension.downcase(); f.setExtension(extension); if (f.exists()) { filename = f; return true; } // None found so far, search for mosaic-global support file: f = f.replaceAllThatMatch("_R[0-9]+C[0-9]+"); if (f.exists()) { filename = f; return true; } extension.upcase(); f.setExtension(extension); if (f.exists()) { filename = f; return true; } // Modify argument to match good filename: return false; } ossim-Miami-2.9.1/src/projection/ossimRS1SarModel.cpp000066400000000000000000001115471352751253100225020ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // Description: // // Sensor Model for Radarsat1 SAR sensor. // //******************************************************************* // $Id:$ #include #include #include #include #include #include #include #include #include #include #include using namespace std; using namespace ossim; static ossimTrace traceDebug("ossimRS1SarModel:debug"); static const double SEC_PER_DAY = 86400.0; static const double NOMINAL_ORBIT_ELEVATION = 798000.0; // m static const double DEG_PER_SEC = 0.004178074; static const double INTRACK_OFFSET_SIGMA = 1000.0; // meters static const double CRTRACK_OFFSET_SIGMA = 300.0; static const double RADIAL_OFFSET_SIGMA = 300.0; static const double LINE_SCALE_SIGMA = 0.01; static const double SKEW_SIGMA = 0.1; // deg static const double ORIENTATION_SIGMA = 0.2; // deg static const double EARTH_ANGULAR_VELOCITY = 7.2921151467e-05; // radians/sec static const char* IMAGING_MODE_ID[] = {"UNKNOWN", "SCN", "SCW", "SGC", "SGF", "SGX", "SLC", "SPG", "SSG","RAW","ERS"}; //****************************************************************************** // Default. //****************************************************************************** ossimRS1SarModel::ossimRS1SarModel() : theCeosData (0), theImagingMode (UNKNOWN_MODE) { setErrorStatus(); } //****************************************************************************** // Takes a ossimFilename& directory containing support data, initializes the model, // and writes out the initial geometry file. //****************************************************************************** ossimRS1SarModel::ossimRS1SarModel(const ossimFilename& imageFile) : theCeosData (0), theImagingMode (UNKNOWN_MODE) { static const char MODULE[] = "Constructor ossimRS1SarModel(ossimFilename)"; if (traceDebug()) CLOG << "entering..." << endl; clearErrorStatus(); // Parse the CEOS data files: ossimFilename dataDirName (imageFile.path()); initFromCeos(dataDirName); if(getErrorStatus() != ossimErrorCodes::OSSIM_OK) { return; } if (theImagingMode == UNKNOWN_MODE) return; // Parse the image data file for the local ORPs interpolator: if ((theImagingMode == SCN) || (theImagingMode == SCW)) establishOrpGrid(); else establishOrpInterp(); // Establish the ephemeris interpolator: establishEphemeris(); initAdjParms(); establishVehicleSpace(); if (traceDebug()) CLOG << "returning..." << endl; return; } //****************************************************************************** // DESTRUCTOR: ~ossimRS1SarModel //****************************************************************************** ossimRS1SarModel::~ossimRS1SarModel() { deallocateMemory(); } //****************************************************************************** // loadSate() //****************************************************************************** bool ossimRS1SarModel::loadState(const ossimKeywordlist& /* kwl */, const char* /* prefix */) { // NOT YET IMPLEMENTED setErrorStatus(); return false; } //****************************************************************************** // saveState() //****************************************************************************** bool ossimRS1SarModel::saveState(ossimKeywordlist& /* kwl */, const char* /* prefix */) const { // NOT YET IMPLEMENTED setErrorStatus(); return false; } //************************************************************************************************* //! Given an image point, returns a ray originating at some arbitrarily high //! point (in this model at the sensor position) and pointing towards the target. //************************************************************************************************* void ossimRS1SarModel::imagingRay(const ossimDpt& image_point, ossimEcefRay& /* image_ray */) const { const char* MODULE = "ossimRS1SarModel::imagingRay()"; // Apply offset, scale, skew, and rotation to image point: ossimDpt offset (theImageSize.line/2.0, theImageSize.samp/2.0); ossimDpt ip1 = image_point - offset; ossimDpt ip2; ip2.line = ip1.line*theCosOrientation*theLineScale + ip1.samp*(theCosOrientation*theSinSkew+theSinOrientation); ip2.samp = -ip1.line*theSinOrientation*theLineScale - ip1.samp*(theSinOrientation*theSinSkew-theCosOrientation); // Offset point back to origin of image: ip1 = ip2 + offset; // Given new line number, obtain the interpolated ORP: ossimEcefPoint localORP; if ((theImagingMode == SCN) || (theImagingMode == SCW)) { ossimGpt gpt (theLatGrid(ip1.x, ip1.y), theLonGrid(ip1.x, ip1.y), theRefHeight); localORP = ossimEcefPoint(gpt); } else { NEWMAT::ColumnVector orpPos(3); theLocalOrpInterp->interpolate(ip1.line, orpPos); localORP = ossimEcefPoint(orpPos[0], orpPos[1], orpPos[2]); } // Establish imaging line time (zero-Doppler time): double arpTime = theFirstLineTime + ip1.line*theTimePerLine; NEWMAT::ColumnVector arpEph(3); theArpPosInterp->interpolate(arpTime, arpEph); ossimEcefPoint ecfArpPos (arpEph[0], arpEph[1], arpEph[2]); theArpVelInterp->interpolate(arpTime, arpEph); ossimEcefVector ecfArpVel (arpEph[0], arpEph[1], arpEph[2]); // Need to correct the velocity vector by the earth rotational velocity: ossimEcefVector earthVel (-ecfArpPos.y()*EARTH_ANGULAR_VELOCITY, ecfArpPos.x()*EARTH_ANGULAR_VELOCITY, 0.0); ecfArpVel = ecfArpVel - earthVel; // Compute a vehicle space with Z near intrack, X normal to Z and range // vector to ORP (slant range normal), and Y in range direction. // Note the application of the position adjustable parameter to the space's // origin (after the range vector was established): ossimEcefVector rangeVector = localORP - ecfArpPos; ossimEcefVector rangeNormal = rangeVector.cross(ecfArpVel); // ossimEcefVector zDirection = rangeNormal.cross(rangeVector); ossimLsrSpace localVehicleSpace (ossimEcefPoint(ecfArpPos + thePosCorrection), // origin rangeNormal, // X-direction rangeVector, 0); // Y-direction (Z not specified double local_orp_range = rangeVector.length(); // Compute slant range distance to pixel in question: double slant_range = local_orp_range; switch (theImagingMode) { case SLC: if (theDirectionFlag == ASCENDING) slant_range += thePixelSpacing.samp*ip1.samp; else slant_range += (theImageSize.samp-1.0-ip1.samp) * thePixelSpacing.samp; break; case SGC: case SGF: case SGX: case ERS: { // Compute the slant range as a polynomial expansion given ground range double ground_range; if (theDirectionFlag == ASCENDING) ground_range = ip1.samp * thePixelSpacing.samp; else ground_range = (theImageSize.samp - 1.0 - ip1.samp) * thePixelSpacing.samp; // double delta_g_i = 1.0; // for (int 0=1; i<6; i++) double delta_g_i = ground_range; for (int i=1; i<6; i++) // NOTE: not using offset (i=0) term { slant_range += theSrGrCoeff[i] * delta_g_i; delta_g_i *= ground_range; } } break; case SCN: case SCW: slant_range = local_orp_range; break; default: CLOG << "ERROR: Invalid imaging mode encountered." << endl; setErrorStatus(); } } //************************************************************************************************* // PUBLIC METHOD: ossimRS1SarModel::lineSampleHeightToWorld(image_point, height, is_inside_image) // // Performs image to ground projection. //************************************************************************************************* void ossimRS1SarModel::lineSampleHeightToWorld(const ossimDpt& image_point, const double& height_ellip, ossimGpt& worldPt) const { static const char MODULE[] = "ossimRS1SarModel::lineSampleHeightToWorld()"; if (traceDebug()) CLOG << "entering..." << endl; // static const int MAX_NUM_ITERS = 50; // static const double MAX_ELEV_DIFF = 0.001; ossimEcefRay imaging_ray; imagingRay(image_point, imaging_ray); worldPt = imaging_ray.intersectAboveEarthEllipsoid(height_ellip); if (traceDebug()) CLOG << "returning..." << endl; } //****************************************************************************** // This method sets theImagingMode data member given a character string // abbreviation of the mode. //****************************************************************************** void ossimRS1SarModel::setImagingMode(char* modeStr) { static const char MODULE[] = "ossimRS1SarModel::setImagingMode(modeStr)"; if (traceDebug()) CLOG << "entering..." << endl; bool illegal_mode = false; if (strcmp(modeStr, "SCN") == 0) { theImagingMode = SCN; } else if (strcmp(modeStr, "SCW") == 0) { theImagingMode = SCW; } else if (strcmp(modeStr, "SGC") == 0) { theImagingMode = SGC; } else if (strcmp(modeStr, "SGF") == 0) { theImagingMode = SGF; } else if (strcmp(modeStr, "SGX") == 0) { theImagingMode = SGX; } else if (strcmp(modeStr, "SLC") == 0) { theImagingMode = SLC; } else if (strcmp(modeStr, "SPG") == 0) { theImagingMode = SPG; illegal_mode = true; } else if (strcmp(modeStr, "SSG") == 0) { theImagingMode = SSG; illegal_mode = true; } else if (strcmp(modeStr, "RAW") == 0) { theImagingMode = RAW; illegal_mode = true; } else if (strcmp(modeStr, "ERS") == 0) { theImagingMode = ERS; } else { theImagingMode = UNKNOWN_MODE; illegal_mode = true; } // Test for ERS product: if ((theImagingMode == UNKNOWN_MODE) && theCeosData.valid()) { char buf[] = "xxx"; strncpy(buf, &(theCeosData->textRec()->product_type[8]), 3); if (strcmp(buf, "ERS") == 0) { theImagingMode = ERS; illegal_mode = false; } } // Filter the imaging modes that are not handled: if (illegal_mode) { CLOG << "\n\t ERROR: The imaging mode <" << IMAGING_MODE_ID[(int) theImagingMode] << "> is currently not supported. \n" << endl; theImagingMode = UNKNOWN_MODE; } if (traceDebug()) CLOG << "returning..." << endl; } //****************************************************************************** // Initialize various data members from the CEOS records. //****************************************************************************** void ossimRS1SarModel::initFromCeos(const ossimFilename& fname) { static const char MODULE[] = "ossimRS1SarModel::initFromCeos()"; if (traceDebug()) CLOG << "entering..." << endl; // Instantiate a CeosData object: theCeosData = new ossimCeosData(fname); if(theCeosData->errorStatus() != ossimErrorCodes::OSSIM_OK) return; const dataset_sum_rec* dsr = theCeosData->dataSetSumRec(); const proc_parm_rec* ppr = theCeosData->procParmRec(); char buf[1024]; // Set imaging mode: strncpy(buf, &(theCeosData->volDescRec()->logvol_id[11]), 3); buf[3] = '\0'; setImagingMode(buf); // Determine whether ascending or descending path acquisition. This flag // dictates whether the first or last pixel of a line is of shorter range: if (theImagingMode == ERS) { theDirectionFlag = DESCENDING; } else { if (dsr->asc_des[0] == 'A') theDirectionFlag = ASCENDING; else if (dsr->asc_des[0] == 'D') theDirectionFlag = DESCENDING; else { CLOG << "ERROR: Direction Flag: " << dsr->asc_des << " not supported" << endl; theDirectionFlag = UNKNOWN_DIRECTION; setErrorStatus(); if (traceDebug()) CLOG << "returning with error..." << endl; return; } } // Image (Product) ID: buf[8] = '\0'; strncpy(buf, theCeosData->volDescRec()->product_id, 8); theImageID = buf; // pixel spacing in range: buf[16] = '\0'; strncpy(buf, dsr->pix_spacing, 16); thePixelSpacing.samp = atof(buf); // pixel spacing in azimuth: strncpy(buf, dsr->line_spacing, 16); buf[16] = '\0'; thePixelSpacing.line = atof(buf); // The ground reference point (ORP) latitude: ossimGpt grp; strncpy(buf, dsr->pro_lat, 16); buf[16] = '\0'; grp.lat = atof(buf); // The ground reference point (ORP) longitude: strncpy(buf, dsr->pro_long, 16); buf[16] = '\0'; grp.lon = atof(buf); // The ground reference point (ORP) elevation: strncpy(buf, dsr->terrain_h, 16); buf[16] = '\0'; grp.hgt = atof(buf); theORP = ossimEcefPoint(grp); theRefHeight = grp.hgt; // Illumination elevation: strncpy(buf, dsr->incident_ang, 8); buf[8] = '\0'; double incidence = atof(buf); theIllumElevation = 90.0 - incidence; // Illumination azimuth -- need to determine whether sensor is in normal // right-looking mode or "antarctic" (left-looking) mode: strncpy(buf, dsr->plat_head, 8); theIllumAzimuth = atof(buf); char sensor_orientation[] = "123456789"; strncpy(sensor_orientation, ppr->sens_orient, 9); if (strcmp(sensor_orientation, "ANTARCTIC") == 0) { theIllumAzimuth -= 90.0; if (theIllumAzimuth < 0.0) theIllumAzimuth += 360.0; } else { theIllumAzimuth += 90.0; if (theIllumAzimuth >= 360.0) theIllumAzimuth -= 360.0; } // Determine the number of lines per image and pixels per line. NOTE: if // image is scan mode, the number of lines must be computed indirectly. if ((theImagingMode == SCN) || (theImagingMode == SCW)) { FILE* fptr = fopen(theCeosData->imageFile().chars(), "r"); if (!fptr) { CLOG << " ERROR:\n\tCannot open CEOS image file: " << theCeosData->imageFile() << endl; setErrorStatus(); return; } fseek(fptr, 0, SEEK_END); long byte_count = ftell(fptr); buf[6] = '\0'; strncpy(buf, theCeosData->imopDescRec()->l_dataset, 6); int lengthOfRec = atoi(buf); theImageSize.line = (byte_count - sizeof(*theCeosData->imopDescRec())) /lengthOfRec; fclose(fptr); } else { strncpy(buf, theCeosData->imopDescRec()->n_dataset, 6); buf[6] = '\0'; theImageSize.line = atoi(buf); } strncpy(buf, theCeosData->imopDescRec()->nleft, 4); buf[4] = '\0'; int left_pixels = atoi(buf); strncpy(buf, theCeosData->imopDescRec()->ngrp, 8); buf[8] = '\0'; int data_pixels = atoi(buf); strncpy(buf, theCeosData->imopDescRec()->nright, 4); buf[4] = '\0'; int right_pixels = atoi(buf); theImageSize.samp = left_pixels + data_pixels + right_pixels; // If ground range product, need to read the ground-to-slant range // conversion coefficients from the proc_parm_rec. NOTE: only single-look // products handled properly. ScanSAR requires reading multiple coefficient // sets. See MDA Detailed Processing Parameter Record Description sec.3.84. if ((theImagingMode==SGC) || (theImagingMode==SGF) || (theImagingMode==SGX) || (theImagingMode==ERS)) { buf[16] = '\0'; for (int i=0; i<6; i++) { strncpy(buf, ppr->srgr_coefset[0].srgr_coef[i], 16); theSrGrCoeff[i] = atof(buf); } } else { theSrGrCoeff[0] = 0.0; theSrGrCoeff[1] = 1.0; // note 1.0 here (should never be accessed) theSrGrCoeff[2] = 0.0; theSrGrCoeff[3] = 0.0; theSrGrCoeff[4] = 0.0; theSrGrCoeff[5] = 0.0; } if (traceDebug()) { CLOG << "DEBUG -- " << "\n\t theDirectionFlag = " << theDirectionFlag << "\n\t thePixelSpacing = " << thePixelSpacing << "\n\t theORP = " << theORP << "\n\t theRefHeight = " << theRefHeight << "\n\t theImageSize = " << theImageSize << "\n\t sensor_orientation = " << sensor_orientation << "\n\t theIllumElevation = " << theIllumElevation << "\n\t theIllumAzimuth = " << theIllumAzimuth << endl; } if (traceDebug()) CLOG << "returning..." << endl; } //****************************************************************************** // This method sets the rigorous model adjustable parameters to // their initial values. //****************************************************************************** void ossimRS1SarModel::initAdjParms() { // Adjustable model not yet implemented #if 0 static const char* MODULE = "ossimRS1SarModel::initAdjParms()"; if (traceDebug()) CLOG << "entering..." << endl; theInTrackOffset = (init_adj_parm[INTRACK_OFFSET]+adj_parm[INTRACK_OFFSET]) * adj_sigma[INTRACK_OFFSET]; theCrTrackOffset = (init_adj_parm[CRTRACK_OFFSET]+adj_parm[CRTRACK_OFFSET]) * adj_sigma[CRTRACK_OFFSET]; theRadialOffset = (init_adj_parm[RADIAL_OFFSET]+adj_parm[RADIAL_OFFSET]) * adj_sigma[RADIAL_OFFSET]; theLineScale = (init_adj_parm[LINE_SCALE]+adj_parm[LINE_SCALE]) * adj_sigma[LINE_SCALE]; theSkew = (init_adj_parm[SKEW]+adj_parm[SKEW]) * adj_sigma[SKEW]; theOrientation = (init_adj_parm[ORIENTATION]+adj_parm[ORIENTATION]); // Initialize base-class initial adjustable parameter array: init_adj_parm[INTRACK_OFFSET] = theInTrackOffset/adj_sigma[INTRACK_OFFSET]; init_adj_parm[CRTRACK_OFFSET] = theCrTrackOffset/adj_sigma[CRTRACK_OFFSET]; init_adj_parm[RADIAL_OFFSET] = theRadialOffset/adj_sigma[RADIAL_OFFSET]; init_adj_parm[LINE_SCALE] = theLineScale/adj_sigma[LINE_SCALE]; init_adj_parm[SKEW] = theSkew/adj_sigma[SKEW]; init_adj_parm[ORIENTATION] = theOrientation/adj_sigma[ORIENTATION]; // Initialize sensor adjustable parameter description strings: strncpy (adj_desc[INTRACK_OFFSET], "intrack_offset", MAX_DESC_CHARS); strncpy (adj_desc[CRTRACK_OFFSET], "crtrack_offset", MAX_DESC_CHARS); strncpy (adj_desc[RADIAL_OFFSET], "radial_offset", MAX_DESC_CHARS); // strncpy (adj_desc[SAMP_SCALE], "samp_scale", MAX_DESC_CHARS); strncpy (adj_desc[LINE_SCALE], "line_scale", MAX_DESC_CHARS); strncpy (adj_desc[SKEW], "image_skew", MAX_DESC_CHARS); strncpy (adj_desc[ORIENTATION], "image_orientation",MAX_DESC_CHARS); // Initialize the adj_parms (parameter corrections) to 0: for (int i=0; iposDataRec(); // Establish the Greenwich mean hour angle at time of first sample: char gha_str [23]; strncpy(gha_str, pdr->hr_angle, 22); gha_str[22] = '\0'; theGHA = atof(gha_str); // Fetch number of points in record and allocate memory: strncpy(buf, pdr->ndata, 4); buf[4] = '\0'; int numPoints = atoi(buf); // Fetch sampling period: strncpy(buf, pdr->data_int, 22); buf[22] = '\0'; double sampling_period = atof(buf); // Establish the first sample time's day: strncpy(buf, pdr->gmt_day, 4); buf[4] = '\0'; int first_day = atoi(buf); double time_offset = (double) (first_day - theFirstLineDay)*SEC_PER_DAY; // Establish the first sample time in seconds from beginning of day: strncpy(buf, pdr->gmt_sec, 22); buf[22] = '\0'; theEphFirstSampTime = atof(buf) + time_offset; int i, j; double sample_time = theEphFirstSampTime; buf[22] = '\0'; NEWMAT::ColumnVector eciArpPos(3); NEWMAT::ColumnVector eciArpVel(3); NEWMAT::ColumnVector ecfArpPos(3); NEWMAT::ColumnVector ecfArpVel(3); NEWMAT::ColumnVector earthVel(3); NEWMAT::Matrix xform; theArpPosInterp = new ossimLagrangeInterpolator; theArpVelInterp = new ossimLagrangeInterpolator; // Loop over each point, converting them to vectors: for (i=0; ipos_vect[i].pos[j], 22); eciArpPos[j] = atof(buf); strncpy(buf, pdr->pos_vect[i].vel[j], 22); eciArpVel[j] = atof(buf)/1000.0; } // Convert pos and vel vectors from ECI to ECF: eciToEcfXform(sample_time, xform); ecfArpPos = xform*eciArpPos; ecfArpVel = xform*eciArpVel; theArpPosInterp->addData(sample_time, ecfArpPos); // Correct velocity for earth rotation: earthVel[0] = -ecfArpPos[1]*EARTH_ANGULAR_VELOCITY; earthVel[1] = ecfArpPos[0]*EARTH_ANGULAR_VELOCITY; earthVel[2] = 0.0; ecfArpVel = ecfArpVel - earthVel; theArpVelInterp->addData(sample_time, ecfArpVel); sample_time += sampling_period; } if (traceDebug()) { CLOG << "DEBUG -- " << "\n\t theGHA: " << theGHA << "\n\t numPoints: " << numPoints << "\n\t sampling_period: " << sampling_period << "\n\t theEphFirstSampTime: " << theEphFirstSampTime << endl; } if (traceDebug()) CLOG << "returning..." << endl; } //****************************************************************************** // Returns 3x3 transform to rotate ECI into ECF. The argument is // in seconds of the day. //****************************************************************************** void ossimRS1SarModel::eciToEcfXform(const double& acq_time, NEWMAT::Matrix& xform) const { static const char MODULE[] = "ossimRS1SarModel::eciToEcfXform(acq_time)"; if (traceDebug()) CLOG << "entering..." << endl; // Determine time elapsed since ephemeris first sample time: double delta_t = acq_time - theEphFirstSampTime; // Compute GHA at time of this image line (in degrees): double gha = theGHA + delta_t*DEG_PER_SEC; if (gha >= 360.0) gha -=360.0; else if (gha < 0.0) gha += 360.0; // Establish rotation: double cos_gha = ossim::cosd(gha); double sin_gha = ossim::sind(gha); // Establish rotation matrix: xform = ossimMatrix3x3::create(cos_gha, sin_gha, 0.0, -sin_gha, cos_gha, 0.0, 0.0, 0.0, 1.0); if (traceDebug()) { CLOG << "DEBUG -- " << "\n\t acq_time = " << acq_time << "\n\t delta_t = " << delta_t << "\n\t gha = " << gha << endl; } if (traceDebug()) CLOG << "returning..." << endl; } //****************************************************************************** // PRIVATE METHOD: ossimRS1SarModel::establishOrpInterp() // // This method reads the image data file for obtaining the local ORPs (taken // to be the lat-lon of the nearest pixel for each line), and the zero-doppler // time for each line. These ORPs are used for computing SPNs. // // The processed data records correspond to lines of imagery. Accompanying // each data line is the lat-lon (at the ellipsoid) of the first, middle, and // last sample of the line, the time of zero-doppler (broadside) imaging for // the line. // // A Lagrange interpolator is established with N data points representing the // local ORPs and their corresponding image line numbers // uniformly distributed over the image. // // If the image is a ground range product, need to also read the ground-to- // slant range conversion coefficients. // //****************************************************************************** void ossimRS1SarModel::establishOrpInterp() { static const char MODULE[] = "ossimRS1SarModel::establishOrpInterp()"; if (traceDebug()) CLOG << "entering..." << endl; if (traceDebug()) CLOG << "DEBUG -- " << endl; static const int NUM_DATA_POINTS = 11; desc_rec descRec; pdr_prefix_rec prefix; int sizeOfDescRec = sizeof(descRec); int sizeOfPrefRec = sizeof(prefix); int headerSize = sizeOfDescRec + sizeOfPrefRec; char buf[] = "123456"; ossimGpt localOrp (0.0, 0.0, theRefHeight); std::vector line_numbers_list; std::vector orpVectorList; // X, Y, Z if (traceDebug()) { CLOG << "DEBUG:" << "\nsizeOfDescRec: " << sizeOfDescRec << "\nsizeOfPrefRec: " << sizeOfPrefRec << endl; } // Open the image data file given the image directory name and seek to first // SAR data record: FILE* fptr = fopen(theCeosData->imageFile().chars(), "r"); if (!fptr) { CLOG << "ERROR: Could not open data file <" << theCeosData->imageFile() << ">" << endl; setErrorStatus(); return; } fseek(fptr, theCeosData->imopDescRec()->desc.length, SEEK_SET); // Declare some constants and variables used in loop: int last_line = (int) theImageSize.line - 1; int delta_line = (int)ceil(last_line/((double)NUM_DATA_POINTS-1.0)); int line_number = 0; // Compute the number of SAR data bytes to skip to reach prefix of next // record of interest: strncpy(buf, theCeosData->imopDescRec()->l_dataset, 6); int record_size = atoi(buf); // Loop over each imaging line: int index; theLocalOrpInterp = new ossimLagrangeInterpolator; for (index=0; indexaddData(line_number, ossimEcefPoint(localOrp).toVector()); // Update the line number for next record, insuring we don't go passed // the last line: line_number += delta_line; if (line_number > last_line) { delta_line -= line_number - last_line; // adjust for fseek below line_number = last_line; } // Advance to read the next prefix record of interest: fseek(fptr, (delta_line)*record_size-headerSize, SEEK_CUR); } // Compute time interval between each line, handle possible day rollover: double lastLineTime = (double) prefix.acq_date.acq_msec/1000.0; if ((lastLineTime-theFirstLineTime) > (SEC_PER_DAY/2.0)) lastLineTime -= SEC_PER_DAY; else if ((theFirstLineTime-lastLineTime) > (SEC_PER_DAY/2.0)) lastLineTime += SEC_PER_DAY; theTimePerLine = (lastLineTime - theFirstLineTime)/line_number; if (traceDebug()) { clog << "\n\t line_number (last) = " << line_number << "\n\t last_line (in image) = " << last_line << "\n\t theFirstLineTime = " << theFirstLineTime << "\n\t lastLineTime = " << lastLineTime << "\n\t theTimePerLine = " << theTimePerLine << endl; } if (traceDebug()) CLOG << "returning..." << endl; } //****************************************************************************** // This method establishes a common mean intrack-crosstrack-radial LSR // space at the ARP. //****************************************************************************** void ossimRS1SarModel::establishVehicleSpace() { static const char MODULE[] = "ossimRS1SarModel::establishVehicleSpace()"; if (traceDebug()) CLOG << "entering..." << endl; // Obtain the imaging time when the vehicle is at the ARP: double line = theImageSize.line/2.0; double arpTime = theFirstLineTime + line*theTimePerLine; // Obtain the ephemeris at this time: NEWMAT::ColumnVector arpPos(3); theArpPosInterp->interpolate(arpTime, arpPos); NEWMAT::ColumnVector arpVel(3); theArpVelInterp->interpolate(arpTime, arpVel); // Convert ephemeris to ECF: NEWMAT::Matrix xform; eciToEcfXform(arpTime, xform); ossimEcefPoint ecfArpPos (xform * arpPos); ossimEcefVector ecfArpVel (xform * arpVel); // Need to correct the velocity vector by the earth rotational velocity: ossimEcefVector earthVel(-ecfArpPos.y()*EARTH_ANGULAR_VELOCITY, ecfArpPos.x()*EARTH_ANGULAR_VELOCITY, 0.0); ecfArpVel = ecfArpVel - earthVel; // Establish LSR space for intrack-crosstrack-radial at vehicle: ossimEcefVector intrackDir (ecfArpVel); ossimEcefVector crtrackDir (ecfArpPos.data().cross(intrackDir.data())); theVehicleSpace = ossimLsrSpace (ecfArpPos, intrackDir, crtrackDir, 0); if (traceDebug()) { CLOG << "DEBUG -- " << "\n\t theVehicleSpace: " << theVehicleSpace << endl; } if (traceDebug()) CLOG << "returning..." << endl; } //****************************************************************************** // For scan-mode imagery, this method interpolates the lat/lon given the image pixel. //****************************************************************************** void ossimRS1SarModel::interpolatedScanORP(const ossimDpt& orp, ossimEcefPoint& orp_ecf) const { static const char MODULE[] = "ossimRS1SarModel::interpolatedScanORP(gDblPoint)"; if (traceDebug()) CLOG << "entering..." << endl; ossimGpt gpt; gpt.lat = theLatGrid(orp); gpt.lon = theLonGrid(orp); // Convert to ECF: orp_ecf = ossimEcefPoint(gpt); if (traceDebug()) CLOG << "returning..." << endl; } //****************************************************************************** // PRIVATE METHOD: ossimRS1SarModel::establishOrpGrid() // // This method establishes a grid of lat-lon across the image for interpolating // the geographic point on the ellipsoid given a pixel value. This is used for // scan-mode imagery for obtaining a local ORP. // //****************************************************************************** void ossimRS1SarModel::establishOrpGrid() { static const char MODULE[] = "ossimRS1SarModel::establishOrpGrid()"; if (traceDebug()) CLOG << "entering..." << endl; if (traceDebug()) { CLOG << "DEBUG -- " << endl; } static const int NUM_GRID_POINTS_U = 11; desc_rec descRec; pdr_prefix_rec prefix; int sizeOfDescRec = sizeof(descRec); int sizeOfPrefRec = sizeof(prefix); int headerSize = sizeOfDescRec + sizeOfPrefRec; char buf[] = "123456"; ossimDpt gridSize ((double) NUM_GRID_POINTS_U, 3.0); ossimDpt cellSize (theImageSize.line/gridSize.u, theImageSize.samp/gridSize.v); // Because we are doing integer arithmetic, it will be necessary to // consider the last grid cells as being of a slightly different size: //theLastGridCellSize.line = theImageSize.line - 1.0 - // (theGridSize.u-2.0)*theGridCellSize.u; //theLastGridCellSize.samp = theImageSize.samp - 1.0 - // (theGridSize.v-2.0)*theGridCellSize.v; // Open the image data file given the image directory name and seek to first // SAR data record: FILE* fptr = fopen(theCeosData->imageFile().chars(), "r"); if (!fptr) { CLOG << "ERROR: Could not open data file <" << theCeosData->imageFile() << ">" << endl; setErrorStatus(); return; } fseek(fptr, theCeosData->imopDescRec()->desc.length, SEEK_SET); // Declare some constants and variables used in loop: int last_line = (int) theImageSize.line - 1; int delta_line = (int) cellSize.u; int line_number = 0; // Allocate memory for coarse grid: theLatGrid.initialize(gridSize, ossimDpt(0,0), ossimDpt(1,1)); theLonGrid.initialize(gridSize, ossimDpt(0,0), ossimDpt(1,1)); // Compute the number of SAR data bytes to skip to reach prefix of next // record of interest: strncpy(buf, theCeosData->imopDescRec()->l_dataset, 6); int record_size = atoi(buf); int test_line = (int) gridSize.u - 2; // Loop over each imaging line: for (int u=0; u<(int)gridSize.u; u++) { if (traceDebug()) { clog << "\t Processing grid line number " << u << endl; } // Read the image line prefix info: fread(&descRec, sizeOfDescRec, 1, fptr); fread(&prefix, sizeOfPrefRec, 1, fptr); // Verify correct line number being read: if ((prefix.line_num-1) != line_number) { CLOG << "\n\tERROR: Synchronization error reading image file. " << "Expected line number " << line_number+1 << " but read line number " << prefix.line_num << "." << endl; setErrorStatus(); fclose(fptr); fptr = 0; return; } // Latch the imaging time for the first line collected: if (u == 0) { theFirstLineDay = prefix.acq_date.acq_day; theFirstLineTime = (double) prefix.acq_date.acq_msec/1000.0; } // Read the ground points for this line: theLatGrid.setNode(u, 0, (double) prefix.lat_first /1.0e6); theLatGrid.setNode(u, 1, (double) prefix.lat_mid /1.0e6); theLatGrid.setNode(u, 2, (double) prefix.lat_last /1.0e6); theLonGrid.setNode(u, 0, (double) prefix.long_first/1.0e6); theLonGrid.setNode(u, 1, (double) prefix.long_mid /1.0e6); theLonGrid.setNode(u, 2, (double) prefix.long_last /1.0e6); // Update the line number for next record, insuring we don't go passed // the last line: if (u == test_line) { delta_line = last_line - line_number; line_number = last_line; } else { line_number += delta_line; } //*** // Advance to read the next prefix record of interest: //*** fseek(fptr, (delta_line)*record_size-headerSize, SEEK_CUR); } // Compute time interval between each line, handle possible day rollover: double lastLineTime = (double) prefix.acq_date.acq_msec/1000.0; if ((lastLineTime-theFirstLineTime) > (SEC_PER_DAY/2.0)) { lastLineTime -= SEC_PER_DAY; } else if ((theFirstLineTime-lastLineTime) > (SEC_PER_DAY/2.0)) { lastLineTime += SEC_PER_DAY; } theTimePerLine = (lastLineTime - theFirstLineTime)/line_number; if (traceDebug()) { clog << "\n\t line_number (last) = " << line_number << "\n\t last_line (in image) = " << last_line << "\n\t theFirstLineTime = " << theFirstLineTime << "\n\t lastLineTime = " << lastLineTime << "\n\t theTimePerLine = " << theTimePerLine << endl; } if (traceDebug()) CLOG << "returning..." << endl; } //****************************************************************************** // PRIVATE METHOD: deallocateMemory() // // This method permits the partial destruction of the object so that it may // be reconstructed without invoking the destructor. // //****************************************************************************** void ossimRS1SarModel::deallocateMemory() { static const char MODULE[] = "ossimRS1SarModel::deallocateMemory()"; if (traceDebug()) CLOG << "entering..." << endl; theArpPosInterp = 0; theArpVelInterp = 0; theLocalOrpInterp = 0; theCeosData = 0; theLatGrid.clear(); theLonGrid.clear(); if (traceDebug()) CLOG << "returning..." << endl; } ossim-Miami-2.9.1/src/projection/ossimRadialDecentLensDistortion.cpp000066400000000000000000000150541352751253100256620ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // MeanRadialLens distortion. // //******************************************************************* // $Id: ossimRadialDecentLensDistortion.cpp 15766 2009-10-20 12:37:09Z gpotts $ #include #include #include #include #include using namespace std; RTTI_DEF1(ossimRadialDecentLensDistortion, "ossimRadialDecentLensDistortion", ossim2dTo2dTransform); const char* ossimRadialDecentLensDistortion::PRINCIPAL_POINT_X_KW = "principal_point_x"; const char* ossimRadialDecentLensDistortion::PRINCIPAL_POINT_Y_KW = "principal_point_y"; const char* ossimRadialDecentLensDistortion::RADIAL_DISTORTION_COEFF_KW = "radial_distortion_coeff_K"; const char* ossimRadialDecentLensDistortion::DECENT_DISTORTION_COEFF_KW = "decent_distortion_coeff_P"; ossimRadialDecentLensDistortion::ossimRadialDecentLensDistortion (const ossimKeywordlist& kwl, const char* prefix) : theCalibratedPrincipalPoint (0, 0), theRadialDistortionParameters(5), theDecentDistortionParameters(5) { loadState(kwl, prefix); } bool ossimRadialDecentLensDistortion::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* value; theCalibratedPrincipalPoint = ossimDpt(0, 0); value = kwl.find(prefix, PRINCIPAL_POINT_X_KW); if (value) { theCalibratedPrincipalPoint.x = atof(value); } value = kwl.find(prefix, PRINCIPAL_POINT_Y_KW); if (value) { theCalibratedPrincipalPoint.y = atof(value); } for (int i=0; i<5; ++i) { ossimString key = RADIAL_DISTORTION_COEFF_KW; key += ossimString::toString(i); value = kwl.find(prefix, key.c_str()); if (!value) { theRadialDistortionParameters[i] = 0.0; } else { theRadialDistortionParameters[i] = ossimString::toDouble(value); } key = DECENT_DISTORTION_COEFF_KW; key += ossimString::toString(i); value = kwl.find(prefix, key.c_str()); if (!value) { theDecentDistortionParameters[i] = 0.0; } else { theDecentDistortionParameters[i] = ossimString::toDouble(value); } } //*** // Pass on to base class: //*** bool rtn_val = ossim2dTo2dTransform::loadState(kwl, prefix); return rtn_val; } bool ossimRadialDecentLensDistortion::saveState(ossimKeywordlist& kwl, const char* prefix) const { //*** // Principal Point: //*** kwl.add(prefix, PRINCIPAL_POINT_X_KW, theCalibratedPrincipalPoint.x); kwl.add(prefix, PRINCIPAL_POINT_Y_KW, theCalibratedPrincipalPoint.y); for(int i=0; i<5; ++i) { //--- // Radial distortion coefficients: //--- ossimString key = RADIAL_DISTORTION_COEFF_KW; key += ossimString::toString(i); kwl.add(prefix, key.c_str(), theRadialDistortionParameters[i], true, // overwrite 15); // scientific //--- // Decentering distortion coefficients: //--- key = DECENT_DISTORTION_COEFF_KW; key += ossimString::toString(i); kwl.add(prefix, key.c_str(), theDecentDistortionParameters[i], true, // overwrite 15); // scientific } //*** // Pass on to base class: //*** bool rtn_val = ossim2dTo2dTransform::saveState(kwl, prefix); return rtn_val; } //***************************************************************************** // METHOD //***************************************************************************** double ossimRadialDecentLensDistortion::deltaR(double radius)const { double rSquare = radius*radius; return theRadialDistortionParameters[0] + rSquare*(theRadialDistortionParameters[1] + rSquare*(theRadialDistortionParameters[2] + rSquare*(theRadialDistortionParameters[3] + rSquare*theRadialDistortionParameters[4]))); } //***************************************************************************** // METHOD //***************************************************************************** void ossimRadialDecentLensDistortion::forward(const ossimDpt& input_pt, ossimDpt& output_pt) const { ossimDpt deltaPosition(input_pt.x - theCalibratedPrincipalPoint.x, input_pt.y - theCalibratedPrincipalPoint.y); double r = sqrt(ossim::square(deltaPosition.x) + ossim::square(deltaPosition.y)); double dr = deltaR(r); double deltaX1 = deltaPosition.x*dr; double deltaY1 = deltaPosition.y*dr; double rSquare = r*r; double deltaX2 = (1 + theDecentDistortionParameters[3]*rSquare + theDecentDistortionParameters[4]*rSquare*rSquare)* (theDecentDistortionParameters[1]*(rSquare + 2*deltaPosition.x*deltaPosition.x) + 2*theDecentDistortionParameters[2]*deltaPosition.x*deltaPosition.y); double deltaY2 = (1 + theDecentDistortionParameters[3]*rSquare + theDecentDistortionParameters[4]*rSquare*rSquare)* (theDecentDistortionParameters[2]*(rSquare + 2*deltaPosition.y*deltaPosition.y) + 2*theDecentDistortionParameters[1]*deltaPosition.x*deltaPosition.y); output_pt.x = deltaPosition.x + deltaX1 + deltaX2; output_pt.y = deltaPosition.y + deltaY1 + deltaY2; } //***************************************************************************** // METHOD: ossimRadialDecentLensDistortion::print() // //***************************************************************************** std::ostream& ossimRadialDecentLensDistortion::print(std::ostream& os) const { os << "\nDump of ossimRadialDecentLensDistortion object" << endl; os << " theCalibratedPrincipalPoint: " << theCalibratedPrincipalPoint; for (unsigned int i=0; i<5; i++) os << "\n K["< #include RTTI_DEF1(ossimRpcModel, "ossimRpcModel", ossimSensorModel); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if OSSIM_HAS_JSONCPP #include #endif //*** // Define Trace flags for use within this file: //*** #include using namespace std; static ossimTrace traceExec ("ossimRpcModel:exec"); static ossimTrace traceDebug ("ossimRpcModel:debug"); //static const int MODEL_VERSION_NUMBER = 1; static const int NUM_COEFFS = 20; static const char* MODEL_TYPE = "ossimRpcModel"; static const char* POLY_TYPE_KW = "polynomial_format"; static const char* LINE_SCALE_KW = "line_scale"; static const char* SAMP_SCALE_KW = "samp_scale"; static const char* LAT_SCALE_KW = "lat_scale"; static const char* LON_SCALE_KW = "long_scale"; static const char* HGT_SCALE_KW = "height_scale"; static const char* LINE_OFFSET_KW = "line_off"; static const char* SAMP_OFFSET_KW = "samp_off"; static const char* LAT_OFFSET_KW = "lat_off"; static const char* LON_OFFSET_KW = "long_off"; static const char* HGT_OFFSET_KW = "height_off"; static const char* BIAS_ERROR_KW = "bias_error"; static const char* RAND_ERROR_KW = "rand_error"; static const char* LINE_NUM_COEF_KW = "line_num_coeff_"; static const char* LINE_DEN_COEF_KW = "line_den_coeff_"; static const char* SAMP_NUM_COEF_KW = "samp_num_coeff_"; static const char* SAMP_DEN_COEF_KW = "samp_den_coeff_"; static const ossimString PARAM_NAMES[] ={"intrack_offset", "crtrack_offset", "intrack_scale", "crtrack_scale", "map_rotation", "yaw_offset"}; static const ossimString PARAM_UNITS[] ={"pixel", "pixel", "scale", "scale", "degrees", "degrees"}; //***************************************************************************** // DEFAULT CONSTRUCTOR: ossimRpcModel() // //***************************************************************************** ossimRpcModel::ossimRpcModel() : ossimSensorModel(), thePolyType (A), theLineScale (0.0), theSampScale (0.0), theLatScale (0.0), theLonScale (0.0), theHgtScale (0.0), theLineOffset (0.0), theSampOffset (0.0), theLatOffset (0.0), theLonOffset (0.0), theHgtOffset (0.0), theIntrackOffset(0.0), theCrtrackOffset(0.0), theIntrackScale (0.0), theCrtrackScale (0.0), theCosMapRot (1.0), theSinMapRot (0.0), theBiasError (0.0), theRandError (0.0) { initAdjustableParameters(); } //***************************************************************************** // COPY CONSTRUCTOR: ossimRpcModel(ossimRpcModel) // //***************************************************************************** ossimRpcModel::ossimRpcModel(const ossimRpcModel& model) : ossimSensorModel(model), thePolyType (model.thePolyType), theLineScale (model.theLineScale), theSampScale (model.theSampScale), theLatScale (model.theLatScale), theLonScale (model.theLonScale), theHgtScale (model.theHgtScale), theLineOffset (model.theLineOffset), theSampOffset (model.theSampOffset), theLatOffset (model.theLatOffset), theLonOffset (model.theLonOffset), theHgtOffset (model.theHgtOffset), theIntrackOffset(model.theIntrackOffset), theCrtrackOffset(model.theCrtrackOffset), theIntrackScale(model.theIntrackScale), theCrtrackScale(model.theCrtrackScale), theCosMapRot (model.theCosMapRot), theSinMapRot (model.theSinMapRot), theBiasError (model.theBiasError), theRandError (model.theRandError) { for (int i=0; i<20; ++i ) { theLineNumCoef[i] = model.theLineNumCoef[i]; theLineDenCoef[i] = model.theLineDenCoef[i]; theSampNumCoef[i] = model.theSampNumCoef[i]; theSampDenCoef[i] = model.theSampDenCoef[i]; } } //***************************************************************************** // DESTRUCTOR: ~ossimRpcModel() // //***************************************************************************** ossimRpcModel::~ossimRpcModel() { } void ossimRpcModel::setAttributes(ossim_float64 sampleOffset, ossim_float64 lineOffset, ossim_float64 sampleScale, ossim_float64 lineScale, ossim_float64 latOffset, ossim_float64 lonOffset, ossim_float64 heightOffset, ossim_float64 latScale, ossim_float64 lonScale, ossim_float64 heightScale, const std::vector& xNumeratorCoeffs, const std::vector& xDenominatorCoeffs, const std::vector& yNumeratorCoeffs, const std::vector& yDenominatorCoeffs, PolynomialType polyType, bool computeGsdFlag) { thePolyType = polyType; theLineScale = lineScale; theSampScale = sampleScale; theLatScale = latScale; theLonScale = lonScale; theHgtScale = heightScale; theLineOffset = lineOffset; theSampOffset = sampleOffset; theLatOffset = latOffset; theLonOffset = lonOffset; theHgtOffset = heightOffset; if(xNumeratorCoeffs.size() == 20) { std::copy(xNumeratorCoeffs.begin(), xNumeratorCoeffs.end(), theSampNumCoef); } if(xDenominatorCoeffs.size() == 20) { std::copy(xDenominatorCoeffs.begin(), xDenominatorCoeffs.end(), theSampDenCoef); } if(yNumeratorCoeffs.size() == 20) { std::copy(yNumeratorCoeffs.begin(), yNumeratorCoeffs.end(), theLineNumCoef); } if(yDenominatorCoeffs.size() == 20) { std::copy(yDenominatorCoeffs.begin(), yDenominatorCoeffs.end(), theLineDenCoef); } if(computeGsdFlag) { try { // This will set theGSD and theMeanGSD. Method throws ossimException. computeGsd(); } catch (const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpcModel::setAttributes Caught Exception:\n" << e.what() << std::endl; } } } } void ossimRpcModel::setMetersPerPixel(const ossimDpt& metersPerPixel) { theGSD = metersPerPixel; theMeanGSD = (theGSD.x+theGSD.y)*.5; } void ossimRpcModel::setPositionError(const ossim_float64& biasError, const ossim_float64& randomError, bool initNominalPostionErrorFlag) { theBiasError = biasError; theRandError = randomError; if (initNominalPostionErrorFlag) { theNominalPosError = sqrt(theBiasError*theBiasError + theRandError*theRandError); // meters } } //***************************************************************************** // METHOD: ossimRpcModel::worldToLineSample() // // Overrides base class implementation. Directly computes line-sample from // the polynomials. //***************************************************************************** void ossimRpcModel::worldToLineSample(const ossimGpt& ground_point, ossimDpt& img_pt) const { // if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcModel::worldToLineSample(): entering..." << std::endl; if(ground_point.isLatNan() || ground_point.isLonNan() ) { img_pt.makeNan(); return; } //*** // First check if the world point is inside bounding rectangle: //*** //ossimDpt wdp (ground_point); //if (!(theBoundGndPolygon.pointWithin(ground_point))) // { //img_pt = extrapolate(ground_point); //if (traceExec()) CLOG << "returning..." << endl; // img_pt.makeNan(); // return; // } //*** // Normalize the lat, lon, hgt: //*** double nlat = (ground_point.lat - theLatOffset) / theLatScale; double nlon = (ground_point.lon - theLonOffset) / theLonScale; double nhgt; if( ground_point.isHgtNan() ) { // nhgt = (theHgtScale - theHgtOffset) / theHgtScale; nhgt = ( - theHgtOffset) / theHgtScale; } else { nhgt = (ground_point.hgt - theHgtOffset) / theHgtScale; } //*** // Compute the adjusted, normalized line (U) and sample (V): //*** double Pu = polynomial(nlat, nlon, nhgt, theLineNumCoef); double Qu = polynomial(nlat, nlon, nhgt, theLineDenCoef); double Pv = polynomial(nlat, nlon, nhgt, theSampNumCoef); double Qv = polynomial(nlat, nlon, nhgt, theSampDenCoef); double U_rot = Pu / Qu; double V_rot = Pv / Qv; //*** // U, V are normalized quantities. Need now to establish the image file // line and sample. First, back out the adjustable parameter effects // starting with rotation: //*** double U = U_rot*theCosMapRot + V_rot*theSinMapRot; double V = V_rot*theCosMapRot - U_rot*theSinMapRot; //*** // Now back out skew, scale, and offset adjustments: //*** img_pt.line = U*(theLineScale+theIntrackScale) + theLineOffset + theIntrackOffset; img_pt.samp = V*(theSampScale+theCrtrackScale) + theSampOffset + theCrtrackOffset; // if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcModel::worldToLineSample(): returning..." << std::endl; return; } //***************************************************************************** // METHOD: ossimRpcModel::lineSampleToWorld() // // Overrides base class implementation. Performs DEM intersection. //***************************************************************************** void ossimRpcModel::lineSampleToWorld(const ossimDpt& imagePoint, ossimGpt& worldPoint) const { //--- // Under debate... (drb 20130610) // this seems to be more accurate for the round trip //--- #if 0 if(!imagePoint.hasNans()) { lineSampleHeightToWorld(imagePoint, worldPoint.height(), worldPoint); } else { worldPoint.makeNan(); } #else if(!imagePoint.hasNans()) { ossimEcefRay ray; imagingRay(imagePoint, ray); ossimElevManager::instance()->intersectRay(ray, worldPoint); } else { worldPoint.makeNan(); } #endif } //***************************************************************************** // METHOD: ossimRpcModel::imagingRay() // // Constructs an RPC ray by intersecting 2 ellipsoid heights above and // below the RPC height offset, and then forming a vector between the two. // //***************************************************************************** void ossimRpcModel::imagingRay(const ossimDpt& imagePoint, ossimEcefRay& imageRay) const { //--- // For "from point", "to point" we want the image ray to be from above the // ellipsoid down to Earth. // // It appears the ray "from point" must be above the ellipsiod for the // ossimElevSource::intersectRay method; ultimately, the // ossimEllipsoid::nearestIntersection method, else it goes off in the // weeds... //--- // this one is messed up so keep as #if 0 untill tested more #if 0 ossimGpt gpt; lineSampleHeightToWorld(imagePoint, theHgtOffset, gpt); //lineSampleHeightToWorld(imagePoint, ossim::nan(), gpt); ossimEcefVector v; if(gpt.datum()) { if(gpt.datum()->ellipsoid()) { gpt.datum()->ellipsoid()->gradient(ossimEcefPoint(gpt), v); v = v.unitVector(); ossimEcefPoint intECFto(gpt); ossimEcefPoint intECFfrom = (intECFto + v*100000); ossimEcefRay ray(intECFfrom, intECFto); imageRay = ray; } } #else double vectorLength = theHgtScale ? (theHgtScale * 2.0) : 1000.0; ossimGpt gpt; // "from" point double intHgt = theHgtOffset + vectorLength; lineSampleHeightToWorld(imagePoint, intHgt, gpt); ossimEcefPoint intECFfrom(gpt); // "to" point lineSampleHeightToWorld(imagePoint, theHgtOffset, gpt); ossimEcefPoint intECFto(gpt); // Construct ray ossimEcefRay ray(intECFfrom, intECFto); imageRay = ray; #endif } //***************************************************************************** // METHOD: ossimRpcModel::lineSampleHeightToWorld() // // Performs reverse projection of image line/sample to ground point. // The imaging ray is intersected with a level plane at height = elev. // // NOTE: U = line, V = sample -- this differs from the convention. // //***************************************************************************** void ossimRpcModel::lineSampleHeightToWorld(const ossimDpt& image_point, const double& ellHeight, ossimGpt& gpt) const { // if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) // << "DEBUG ossimRpcModel::lineSampleHeightToWorld: entering..." << std::endl; //--- // Removed below "gpt.makeNan()" if outside of image. This was put in // troubleshooting dateline wrap issues. Returned nans are also // causing issues so commenting out. drb - 17 Dec. 2015 //--- // Extrapolate if point is outside image: // if (!insideImage(image_point)) // { // gpt = extrapolate(image_point, ellHeight); // // if (traceExec()) CLOG << "returning..." << endl; // return; // } // Constants for convergence tests: static const int MAX_NUM_ITERATIONS = 10; static const double CONVERGENCE_EPSILON = 0.1; // pixels // The image point must be adjusted by the adjustable parameters as well // as the scale and offsets given as part of the RPC param normalization. // NOTE: U = line, V = sample double U = (image_point.y-theLineOffset - theIntrackOffset) / (theLineScale+theIntrackScale); double V = (image_point.x-theSampOffset - theCrtrackOffset) / (theSampScale+theCrtrackScale); // Rotate the normalized U, V by the map rotation error (adjustable param): double U_rot = theCosMapRot*U - theSinMapRot*V; double V_rot = theSinMapRot*U + theCosMapRot*V; U = U_rot; V = V_rot; // Initialize quantities to be used in the iteration for ground point: double nlat = 0.0; // normalized latitude double nlon = 0.0; // normalized longitude double nhgt; if(ossim::isnan(ellHeight)) { nhgt = (theHgtScale - theHgtOffset) / theHgtScale; // norm height } else { nhgt = (ellHeight - theHgtOffset) / theHgtScale; // norm height } double epsilonU = CONVERGENCE_EPSILON/(theLineScale+theIntrackScale); double epsilonV = CONVERGENCE_EPSILON/(theSampScale+theCrtrackScale); int iteration = 0; // Declare variables only once outside the loop. These include: // * polynomials (numerators Pu, Pv, and denominators Qu, Qv), // * partial derivatives of polynomials wrt X, Y, // * computed normalized image point: Uc, Vc, // * residuals of normalized image point: deltaU, deltaV, // * partial derivatives of Uc and Vc wrt X, Y, // * corrections to normalized lat, lon: deltaLat, deltaLon. double Pu, Qu, Pv, Qv; double dPu_dLat, dQu_dLat, dPv_dLat, dQv_dLat; double dPu_dLon, dQu_dLon, dPv_dLon, dQv_dLon; double Uc, Vc; double deltaU, deltaV; double dU_dLat, dU_dLon, dV_dLat, dV_dLon, W; double deltaLat, deltaLon; // Now iterate until the computed Uc, Vc is within epsilon of the desired // image point U, V: do { // Calculate the normalized line and sample Uc, Vc as ratio of // polynomials Pu, Qu and Pv, Qv: Pu = polynomial(nlat, nlon, nhgt, theLineNumCoef); Qu = polynomial(nlat, nlon, nhgt, theLineDenCoef); Pv = polynomial(nlat, nlon, nhgt, theSampNumCoef); Qv = polynomial(nlat, nlon, nhgt, theSampDenCoef); if (ossim::isnan(Pu) || ossim::isnan(Pv) || (Qu == 0.0) || (Qv == 0.0)) { gpt.makeNan(); break; } Uc = Pu/Qu; Vc = Pv/Qv; // Compute residuals between desired and computed line, sample: deltaU = U - Uc; deltaV = V - Vc; // Check for convergence and skip re-linearization if converged: if ((fabs(deltaU) > epsilonU) || (fabs(deltaV) > epsilonV)) { // Analytically compute the partials of each polynomial wrt lat, lon: dPu_dLat = dPoly_dLat(nlat, nlon, nhgt, theLineNumCoef); dQu_dLat = dPoly_dLat(nlat, nlon, nhgt, theLineDenCoef); dPv_dLat = dPoly_dLat(nlat, nlon, nhgt, theSampNumCoef); dQv_dLat = dPoly_dLat(nlat, nlon, nhgt, theSampDenCoef); dPu_dLon = dPoly_dLon(nlat, nlon, nhgt, theLineNumCoef); dQu_dLon = dPoly_dLon(nlat, nlon, nhgt, theLineDenCoef); dPv_dLon = dPoly_dLon(nlat, nlon, nhgt, theSampNumCoef); dQv_dLon = dPoly_dLon(nlat, nlon, nhgt, theSampDenCoef); // Analytically compute partials of quotients U and V wrt lat, lon: dU_dLat = (Qu*dPu_dLat - Pu*dQu_dLat)/(Qu*Qu); dU_dLon = (Qu*dPu_dLon - Pu*dQu_dLon)/(Qu*Qu); dV_dLat = (Qv*dPv_dLat - Pv*dQv_dLat)/(Qv*Qv); dV_dLon = (Qv*dPv_dLon - Pv*dQv_dLon)/(Qv*Qv); W = dU_dLon*dV_dLat - dU_dLat*dV_dLon; // Now compute the corrections to normalized lat, lon: deltaLat = (dU_dLon*deltaV - dV_dLon*deltaU) / W; deltaLon = (dV_dLat*deltaU - dU_dLat*deltaV) / W; nlat += deltaLat; nlon += deltaLon; } //double h = ossimElevManager::instance()->getHeightAboveEllipsoid(ossimGpt(nlat, nlon)); // if(!ossim::isnan(h)) // { // nhgt = h; // } iteration++; } while (((fabs(deltaU)>epsilonU) || (fabs(deltaV)>epsilonV)) && (iteration < MAX_NUM_ITERATIONS)); if (gpt.hasNans()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimRpcModel::lineSampleHeightToWorld: \n" <<"NaN detected computing RPC polynomials. Results are invalid." << endl; } else { // Test for exceeding allowed number of iterations. Flag error if so: if (iteration == MAX_NUM_ITERATIONS) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimRpcModel::lineSampleHeightToWorld: \n" << "Max number of iterations reached in ground point " << "solution. Results are inaccurate." << endl; } // Now un-normalize the ground point lat, lon and establish return quantity: gpt.lat = nlat * theLatScale + theLatOffset; gpt.lon = nlon * theLonScale + theLonOffset; gpt.hgt = ellHeight; } } //***************************************************************************** // PRIVATE METHOD: ossimRpcModel::polynomial // // Computes polynomial. // //***************************************************************************** double ossimRpcModel::polynomial(const double& P, const double& L, const double& H, const double* c) const { double r; if (thePolyType == A) { r = c[ 0] + c[ 1]*L + c[ 2]*P + c[ 3]*H + c[ 4]*L*P + c[ 5]*L*H + c[ 6]*P*H + c[ 7]*L*P*H + c[ 8]*L*L + c[ 9]*P*P + c[10]*H*H + c[11]*L*L*L + c[12]*L*L*P + c[13]*L*L*H + c[14]*L*P*P + c[15]*P*P*P + c[16]*P*P*H + c[17]*L*H*H + c[18]*P*H*H + c[19]*H*H*H; } else { r = c[ 0] + c[ 1]*L + c[ 2]*P + c[ 3]*H + c[ 4]*L*P + c[ 5]*L*H + c[ 6]*P*H + c[ 7]*L*L + c[ 8]*P*P + c[ 9]*H*H + c[10]*L*P*H + c[11]*L*L*L + c[12]*L*P*P + c[13]*L*H*H + c[14]*L*L*P + c[15]*P*P*P + c[16]*P*H*H + c[17]*L*L*H + c[18]*P*P*H + c[19]*H*H*H; } return r; } //***************************************************************************** // PRIVATE METHOD: ossimRpcModel::dPoly_dLat // // Computes derivative of polynomial wrt normalized Latitude P. // //***************************************************************************** double ossimRpcModel::dPoly_dLat(const double& P, const double& L, const double& H, const double* c) const { double dr; if (thePolyType == A) { dr = c[2] + c[4]*L + c[6]*H + c[7]*L*H + 2*c[9]*P + c[12]*L*L + 2*c[14]*L*P + 3*c[15]*P*P +2*c[16]*P*H + c[18]*H*H; } else { dr = c[2] + c[4]*L + c[6]*H + 2*c[8]*P + c[10]*L*H + 2*c[12]*L*P + c[14]*L*L + 3*c[15]*P*P + c[16]*H*H + 2*c[18]*P*H; } return dr; } //***************************************************************************** // PRIVATE METHOD: ossimRpcModel::dPoly_dLon // // Computes derivative of polynomial wrt normalized Longitude L. // //***************************************************************************** double ossimRpcModel::dPoly_dLon(const double& P, const double& L, const double& H, const double* c) const { double dr; if (thePolyType == A) { dr = c[1] + c[4]*P + c[5]*H + c[7]*P*H + 2*c[8]*L + 3*c[11]*L*L + 2*c[12]*L*P + 2*c[13]*L*H + c[14]*P*P + c[17]*H*H; } else { dr = c[1] + c[4]*P + c[5]*H + 2*c[7]*L + c[10]*P*H + 3*c[11]*L*L + c[12]*P*P + c[13]*H*H + 2*c[14]*P*L + 2*c[17]*L*H; } return dr; } //***************************************************************************** // PRIVATE METHOD: ossimRpcModel::dPoly_dHgt // // Computes derivative of polynomial wrt normalized Height H. // //***************************************************************************** double ossimRpcModel::dPoly_dHgt(const double& P, const double& L, const double& H, const double* c) const { double dr; if (thePolyType == A) { dr = c[3] + c[5]*L + c[6]*P + c[7]*L*P + 2*c[10]*H + c[13]*L*L + c[16]*P*P + 2*c[17]*L*H + 2*c[18]*P*H + 3*c[19]*H*H; } else { dr = c[3] + c[5]*L + c[6]*P + 2*c[9]*H + c[10]*L*P + 2*c[13]*L*H + 2*c[16]*P*H + c[17]*L*L + c[18]*P*P + 3*c[19]*H*H; } return dr; } void ossimRpcModel::updateModel() { theIntrackOffset = computeParameterOffset(INTRACK_OFFSET); theCrtrackOffset = computeParameterOffset(CRTRACK_OFFSET); theIntrackScale = computeParameterOffset(INTRACK_SCALE); theCrtrackScale = computeParameterOffset(CRTRACK_SCALE); double mapRotation = computeParameterOffset(MAP_ROTATION); theCosMapRot = ossim::cosd(mapRotation); theSinMapRot = ossim::sind(mapRotation); } void ossimRpcModel::initAdjustableParameters() { resizeAdjustableParameterArray(NUM_ADJUSTABLE_PARAMS); int numParams = getNumberOfAdjustableParameters(); for (int i=0; i. Check the keywordlist for proper syntax." << std::endl; return false; } thePolyType = (PolynomialType) value.at(0); keyword = LINE_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLineScale = value.toDouble(); keyword = SAMP_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theSampScale = value.toDouble(); keyword = LAT_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLatScale = value.toDouble(); keyword = LON_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLonScale = value.toDouble(); keyword = HGT_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theHgtScale = value.toDouble(); keyword = LINE_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLineOffset = value.toDouble(); keyword = SAMP_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theSampOffset = value.toDouble(); keyword = LAT_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLatOffset = value.toDouble(); keyword = LON_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLonOffset = value.toDouble(); keyword = HGT_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theHgtOffset = value.toDouble(); for (int i=0; i. Check the keywordlist for proper syntax." << std::endl; return false; } theLineNumCoef[i] = value.toDouble(); keyword = LINE_DEN_COEF_KW; keyword += os.str(); value = kwl.find(prefix, keyword.c_str()); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLineDenCoef[i] = value.toDouble(); keyword = SAMP_NUM_COEF_KW; keyword += os.str(); value = kwl.find(prefix, keyword.c_str()); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theSampNumCoef[i] = value.toDouble(); keyword = SAMP_DEN_COEF_KW; keyword += os.str(); value = kwl.find(prefix, keyword.c_str()); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcModel::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theSampDenCoef[i] = value.toDouble(); } //*** // Initialize other data members given quantities read in KWL: //*** theCosMapRot = 1.0; theSinMapRot = 0.0; updateModel(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcModel::loadState(): returning..." << std::endl; return true; } //***************************************************************************** // STATIC METHOD: ossimRpcModel::writeGeomTemplate // // Writes a sample kwl to output stream. // //***************************************************************************** void ossimRpcModel::writeGeomTemplate(ostream& os) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcModel::writeGeomTemplate(): entering..." << std::endl; os << "//**************************************************************\n" "// Template for RPC model keywordlist\n" "//**************************************************************\n" << ossimKeywordNames::TYPE_KW << ": " << MODEL_TYPE << endl; ossimSensorModel::writeGeomTemplate(os); os << "//\n" << "// Derived-class ossimRpcModel Keywords:\n" << "//\n" << POLY_TYPE_KW << ": A|B\n" << "\n" << "// RPC data consists of coefficients and normalization \n" << "// parameters. The RPC keywords used here are compatible with \n" << "// keywords found in Ikonos \"rpc.txt\" files.\n" << "// First are the normalization parameters:\n" << LINE_OFFSET_KW << ": \n" << SAMP_OFFSET_KW << ": \n" << LAT_OFFSET_KW << ": \n" << LON_OFFSET_KW << ": \n" << HGT_OFFSET_KW << ": \n" << LINE_SCALE_KW << ": \n" << SAMP_SCALE_KW << ": \n" << LAT_SCALE_KW << ": \n" << LON_SCALE_KW << ": \n" << HGT_SCALE_KW << ": \n" << BIAS_ERROR_KW << ": \n" << RAND_ERROR_KW << ": \n" << "\n" << "// RPC Coefficients are specified with indexes. Coefficients \n " << "// are specified for the four polynomials: line numerator, line \n" << "// denominator, sample numerator, and sample denominator:" << endl; for (int i=1; i<=20; i++) os << LINE_NUM_COEF_KW << setw(2) << setfill('0') << right << i << ": " << endl; os << endl; for (int i=1; i<=20; i++) os << LINE_DEN_COEF_KW << setw(2) << setfill('0') << right << i << ": " << endl; os << endl; for (int i=1; i<=20; i++) os << SAMP_NUM_COEF_KW << setw(2) << setfill('0') << right << i << ": " << endl; os << endl; for (int i=1; i<=20; i++) os << SAMP_DEN_COEF_KW << setw(2) << setfill('0') << right << i << ": " << endl; os << "\n" < proj = ossimProjectionFactoryRegistry::instance()->createProjection(init_file); if(proj.valid()) { kwl.clear(); proj->saveState(kwl); return loadState(kwl); } } return false; } //***************************************************************************** // METHOD: ossimSarModel::getForwardDeriv() // // Compute partials of samp/line WRT to ground. // //***************************************************************************** ossimDpt ossimRpcModel::getForwardDeriv(int derivMode, const ossimGpt& pos, double h) { // If derivMode (parmIdx) >= 0 call base class version // for "adjustable parameters" if (derivMode >= 0) { return ossimSensorModel::getForwardDeriv(derivMode, pos, h); } // Use alternative derivMode definitions else { ossimDpt returnData; //****************************************** // OBS_INIT mode // [1] // [2] // Note: In this mode, pos is used to pass // in the (s,l) observations. //****************************************** if (derivMode==OBS_INIT) { // Image coordinates ossimDpt obs; obs.samp = pos.latd(); obs.line = pos.lond(); theObs = obs; } //****************************************** // EVALUATE mode // [1] evaluate & save partials, residuals // [2] return residuals //****************************************** else if (derivMode==EVALUATE) { //*** // Normalize the lat, lon, hgt: //*** double nlat = (pos.lat - theLatOffset) / theLatScale; double nlon = (pos.lon - theLonOffset) / theLonScale; double nhgt; if( ossim::isnan(pos.hgt) ) { nhgt = (theHgtScale - theHgtOffset) / theHgtScale; } else { nhgt = (pos.hgt - theHgtOffset) / theHgtScale; } //*** // Compute the normalized line (Un) and sample (Vn): //*** double Pu = polynomial(nlat, nlon, nhgt, theLineNumCoef); double Qu = polynomial(nlat, nlon, nhgt, theLineDenCoef); double Pv = polynomial(nlat, nlon, nhgt, theSampNumCoef); double Qv = polynomial(nlat, nlon, nhgt, theSampDenCoef); double Un = Pu / Qu; double Vn = Pv / Qv; //*** // Compute the actual line (U) and sample (V): //*** double U = Un*theLineScale + theLineOffset; double V = Vn*theSampScale + theSampOffset; //*** // Compute the partials of each polynomial wrt lat, lon, hgt //*** double dPu_dLat, dQu_dLat, dPv_dLat, dQv_dLat; double dPu_dLon, dQu_dLon, dPv_dLon, dQv_dLon; double dPu_dHgt, dQu_dHgt, dPv_dHgt, dQv_dHgt; dPu_dLat = dPoly_dLat(nlat, nlon, nhgt, theLineNumCoef); dQu_dLat = dPoly_dLat(nlat, nlon, nhgt, theLineDenCoef); dPv_dLat = dPoly_dLat(nlat, nlon, nhgt, theSampNumCoef); dQv_dLat = dPoly_dLat(nlat, nlon, nhgt, theSampDenCoef); dPu_dLon = dPoly_dLon(nlat, nlon, nhgt, theLineNumCoef); dQu_dLon = dPoly_dLon(nlat, nlon, nhgt, theLineDenCoef); dPv_dLon = dPoly_dLon(nlat, nlon, nhgt, theSampNumCoef); dQv_dLon = dPoly_dLon(nlat, nlon, nhgt, theSampDenCoef); dPu_dHgt = dPoly_dHgt(nlat, nlon, nhgt, theLineNumCoef); dQu_dHgt = dPoly_dHgt(nlat, nlon, nhgt, theLineDenCoef); dPv_dHgt = dPoly_dHgt(nlat, nlon, nhgt, theSampNumCoef); dQv_dHgt = dPoly_dHgt(nlat, nlon, nhgt, theSampDenCoef); //*** // Compute partials of quotients U and V wrt lat, lon, hgt //*** double dU_dLat, dU_dLon, dU_dHgt, dV_dLat, dV_dLon, dV_dHgt; dU_dLat = (Qu*dPu_dLat - Pu*dQu_dLat)/(Qu*Qu); dU_dLon = (Qu*dPu_dLon - Pu*dQu_dLon)/(Qu*Qu); dU_dHgt = (Qu*dPu_dHgt - Pu*dQu_dHgt)/(Qu*Qu); dV_dLat = (Qv*dPv_dLat - Pv*dQv_dLat)/(Qv*Qv); dV_dLon = (Qv*dPv_dLon - Pv*dQv_dLon)/(Qv*Qv); dV_dHgt = (Qv*dPv_dHgt - Pv*dQv_dHgt)/(Qv*Qv); //*** // Apply necessary scale factors //*** dU_dLat *= theLineScale/theLatScale; dU_dLon *= theLineScale/theLonScale; dU_dHgt *= theLineScale/theHgtScale; dV_dLat *= theSampScale/theLatScale; dV_dLon *= theSampScale/theLonScale; dV_dHgt *= theSampScale/theHgtScale; dU_dLat *= DEG_PER_RAD; dU_dLon *= DEG_PER_RAD; dV_dLat *= DEG_PER_RAD; dV_dLon *= DEG_PER_RAD; // Save the partials referenced to ECF ossimEcefPoint location(pos); NEWMAT::Matrix jMat(3,3); pos.datum()->ellipsoid()->jacobianWrtEcef(location, jMat); // Line theParWRTx.u = dU_dLat*jMat(1,1)+dU_dLon*jMat(2,1)+dU_dHgt*jMat(3,1); theParWRTy.u = dU_dLat*jMat(1,2)+dU_dLon*jMat(2,2)+dU_dHgt*jMat(3,2); theParWRTz.u = dU_dLat*jMat(1,3)+dU_dLon*jMat(2,3)+dU_dHgt*jMat(3,3); // Samp theParWRTx.v = dV_dLat*jMat(1,1)+dV_dLon*jMat(2,1)+dV_dHgt*jMat(3,1); theParWRTy.v = dV_dLat*jMat(1,2)+dV_dLon*jMat(2,2)+dV_dHgt*jMat(3,2); theParWRTz.v = dV_dLat*jMat(1,3)+dV_dLon*jMat(2,3)+dV_dHgt*jMat(3,3); // Residuals ossimDpt resid(theObs.samp-V, theObs.line-U); returnData = resid; } //****************************************** // P_WRT_X, P_WRT_Y, P_WRT_Z modes // [1] 3 separate calls required // [2] return 3 sets of partials //****************************************** else if (derivMode==P_WRT_X) { returnData = theParWRTx; } else if (derivMode==P_WRT_Y) { returnData = theParWRTy; } else { returnData = theParWRTz; } return returnData; } } double ossimRpcModel::getBiasError() const { return theBiasError; } double ossimRpcModel::getRandError() const { return theRandError; } //***************************************************************************** // METHOD: ossimSarModel::getRpcParameters) // // Accessor for RPC parameter set. // //***************************************************************************** void ossimRpcModel::getRpcParameters(ossimRpcModel::rpcModelStruct& model) const { model.lineScale = theLineScale; model.sampScale = theSampScale; model.latScale = theLatScale; model.lonScale = theLonScale; model.hgtScale = theHgtScale; model.lineOffset = theLineOffset; model.sampOffset = theSampOffset; model.latOffset = theLatOffset; model.lonOffset = theLonOffset; model.hgtOffset = theHgtOffset; for (int i=0; i<20; ++i) { model.lineNumCoef[i] = theLineNumCoef[i]; model.lineDenCoef[i] = theLineDenCoef[i]; model.sampNumCoef[i] = theSampNumCoef[i]; model.sampDenCoef[i] = theSampDenCoef[i]; } if (thePolyType == A) { model.type= 'A'; } else { model.type= 'B'; } } void ossimRpcModel::setImageOffset(const ossimDpt& offset) { theLineOffset -= offset.line; theSampOffset -= offset.samp; if (theImageClipRect.hasNans()) theImageClipRect = ossimDrect(0, 0, theImageSize.x - offset.x - 1, theImageSize.y - offset.y - 1); else theImageClipRect -= offset; } bool ossimRpcModel::toJSON(std::ostream& jsonStream) const { #if OSSIM_HAS_JSONCPP Json::Value IMAGE; IMAGE["ERRBIAS"] = theBiasError; IMAGE["ERRRAND"] = theRandError; IMAGE["LINEOFFSET"] = (int)theLineOffset; IMAGE["SAMPOFFSET"] = (int)theSampOffset; IMAGE["LATOFFSET"] = theLatOffset; IMAGE["LONGOFFSET"] = theLonOffset; IMAGE["HEIGHTOFFSET"] = theHgtOffset; IMAGE["LINESCALE"] = theLineScale; IMAGE["SAMPSCALE"] = theSampScale; IMAGE["LATSCALE"] = theLatScale; IMAGE["LONGSCALE"] = theLonScale; IMAGE["HEIGHTSCALE"] = theHgtScale; // Preferred way to output coeff arrays: // Json::Value LINENUMCOEF(Json::arrayValue); // Json::Value LINEDENCOEF(Json::arrayValue); // Json::Value SAMPNUMCOEF(Json::arrayValue); // Json::Value SAMPDENCOEF(Json::arrayValue); // for (int i=0; i<20; ++i) // { // LINENUMCOEF.append(theLineNumCoef[i]); // LINEDENCOEF.append(theLineDenCoef[i]); // SAMPNUMCOEF.append(theSampNumCoef[i]); // SAMPDENCOEF.append(theSampDenCoef[i]); // } // Write coeffs as string list for JSON to XML converter to output properly: ossimString LINENUMCOEF; ossimString LINEDENCOEF; ossimString SAMPNUMCOEF; ossimString SAMPDENCOEF; for (int i=0; i<20; ++i) { LINENUMCOEF += ossimString::toString(theLineNumCoef[i]) + " "; LINEDENCOEF += ossimString::toString(theLineDenCoef[i]) + " "; SAMPNUMCOEF += ossimString::toString(theSampNumCoef[i]) + " "; SAMPDENCOEF += ossimString::toString(theSampDenCoef[i]) + " "; } Json::Value LINENUMCOEFList; LINENUMCOEFList["LINENUMCOEF"] = LINENUMCOEF.string(); IMAGE["LINENUMCOEFList"] = LINENUMCOEFList; Json::Value LINEDENCOEFList; LINEDENCOEFList["LINEDENCOEF"] = LINEDENCOEF.string(); IMAGE["LINEDENCOEFList"] = LINEDENCOEFList; Json::Value SAMPNUMCOEFList; SAMPNUMCOEFList["SAMPNUMCOEF"] = SAMPNUMCOEF.string(); IMAGE["SAMPNUMCOEFList"] = SAMPNUMCOEFList; Json::Value SAMPDENCOEFList; SAMPDENCOEFList["SAMPDENCOEF"] = SAMPDENCOEF.string(); IMAGE["SAMPDENCOEFList"] = SAMPDENCOEFList; Json::Value RPB; RPB["SATID"] = "NOT_ASSIGNED"; RPB["BANDID"] = "NOT_ASSIGNED"; if (thePolyType == A) RPB["SPECID"] = "RPC00A"; // Not sure this will work else RPB["SPECID"] = "RPC00B"; RPB["IMAGE"] = IMAGE; Json::Value ISD; ISD["RPB"] = RPB; Json::Value root; root["isd"] = ISD; jsonStream << root; return true; #else jsonStream<<"Error: JSON format not supported."< #include #include #include #include #include #include #include RTTI_DEF3(ossimRpcProjection, "ossimRpcProjection", ossimProjection, ossimOptimizableProjection, ossimAdjustableParameterInterface); #include #include #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include using namespace std; static ossimTrace traceExec ("ossimRpcProjection:exec"); static ossimTrace traceDebug ("ossimRpcProjection:debug"); //static const int MODEL_VERSION_NUMBER = 1; static const int NUM_COEFFS = 20; static const char* MODEL_TYPE = "ossimRpcModel"; static const char* POLY_TYPE_KW = "polynomial_format"; static const char* LINE_SCALE_KW = "line_scale"; static const char* SAMP_SCALE_KW = "samp_scale"; static const char* LAT_SCALE_KW = "lat_scale"; static const char* LON_SCALE_KW = "long_scale"; static const char* HGT_SCALE_KW = "height_scale"; static const char* LINE_OFFSET_KW = "line_off"; static const char* SAMP_OFFSET_KW = "samp_off"; static const char* LAT_OFFSET_KW = "lat_off"; static const char* LON_OFFSET_KW = "long_off"; static const char* HGT_OFFSET_KW = "height_off"; static const char* LINE_NUM_COEF_KW = "line_num_coeff_"; static const char* LINE_DEN_COEF_KW = "line_den_coeff_"; static const char* SAMP_NUM_COEF_KW = "samp_num_coeff_"; static const char* SAMP_DEN_COEF_KW = "samp_den_coeff_"; static const ossim_int32 INTRACK_OFFSET = 0; static const ossim_int32 CRTRACK_OFFSET = 1; static const ossim_int32 INTRACK_SCALE = 2; static const ossim_int32 CRTRACK_SCALE = 3; static const ossim_int32 MAP_ROTATION = 4; //static const ossim_int32 YAW_OFFSET; static const ossim_int32 NUM_ADJUSTABLE_PARAMS = 5; static const ossimString PARAM_NAMES[] ={"intrack_offset", "crtrack_offset", "intrack_scale", "crtrack_scale", "map_rotation", "yaw_offset"}; static const ossimString PARAM_UNITS[] ={"pixel", "pixel", "scale", "scale", "degrees", "degrees"}; //***************************************************************************** // DEFAULT CONSTRUCTOR: ossimRpcModel() // //***************************************************************************** ossimRpcProjection::ossimRpcProjection() : ossimOptimizableProjection(), theIntrackOffset(0), theCrtrackOffset(0), theIntrackScale(0.0), theCrtrackScale(0.0), theYawSkew (0.0), theCosMapRot (1.0), theSinMapRot (0.0) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcProjection Default Constructor: entering..." << std::endl; initAdjustableParameters(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcProjection Default Constructor: returning..." << std::endl; } //***************************************************************************** // COPY CONSTRUCTOR: ossimRpcProjection(ossimRpcProjection) // //***************************************************************************** ossimRpcProjection::ossimRpcProjection(const ossimRpcProjection& model) : ossimOptimizableProjection(model), ossimAdjustableParameterInterface(model), thePolyType (model.thePolyType), theLineScale (model.theLineScale), theSampScale (model.theSampScale), theLatScale (model.theLatScale), theLonScale (model.theLonScale), theHgtScale (model.theHgtScale), theLineOffset (model.theLineOffset), theSampOffset (model.theSampOffset), theLatOffset (model.theLatOffset), theLonOffset (model.theLonOffset), theHgtOffset (model.theHgtOffset), theIntrackOffset(model.theIntrackOffset), theCrtrackOffset(model.theCrtrackOffset), theIntrackScale(model.theIntrackScale), theCrtrackScale(model.theCrtrackScale), theYawSkew (model.theYawSkew), theCosMapRot (model.theCosMapRot), theSinMapRot (model.theSinMapRot) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcProjection Copy Constructor: entering..." << std::endl; for (int i=0; i<20; i++) { theLineNumCoef[i] = model.theLineNumCoef[i]; theLineDenCoef[i] = model.theLineDenCoef[i]; theSampNumCoef[i] = model.theSampNumCoef[i]; theSampDenCoef[i] = model.theSampDenCoef[i]; } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcProjection Copy Constructor: returning..." << std::endl; } //***************************************************************************** // DESTRUCTOR: ~ossimRpcProjection() // //***************************************************************************** ossimRpcProjection::~ossimRpcProjection() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ~ossimRpcProjection() Destructor: entering..." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNotify(ossimNotifyLevel_DEBUG): returning..." << std::endl; } ossimObject* ossimRpcProjection::getBaseObject() { return this; } const ossimObject* ossimRpcProjection::getBaseObject()const { return this; } ossimRpcProjection& ossimRpcProjection::operator=(const ossimRpcProjection& source) { if (this != &source) { ossimOptimizableProjection::operator=(source); thePolyType = source.thePolyType; theLineScale = source.theLineScale; theSampScale = source.theSampScale; theLatScale = source.theLatScale; theLonScale = source.theLonScale; theHgtScale = source.theHgtScale; theLineOffset = source.theLineOffset; theSampOffset = source.theSampOffset; theLatOffset = source.theLatOffset; theLonOffset = source.theLonOffset; theHgtOffset = source.theHgtOffset; for (int i=0; i<20; i++) { theLineNumCoef[i] = source.theLineNumCoef[i]; theLineDenCoef[i] = source.theLineDenCoef[i]; theSampNumCoef[i] = source.theSampNumCoef[i]; theSampDenCoef[i] = source.theSampDenCoef[i]; } } return *this; } void ossimRpcProjection::setAttributes(ossim_float64 sampleOffset, ossim_float64 lineOffset, ossim_float64 sampleScale, ossim_float64 lineScale, ossim_float64 latOffset, ossim_float64 lonOffset, ossim_float64 heightOffset, ossim_float64 latScale, ossim_float64 lonScale, ossim_float64 heightScale, const std::vector& xNumeratorCoeffs, const std::vector& xDenominatorCoeffs, const std::vector& yNumeratorCoeffs, const std::vector& yDenominatorCoeffs, PolynomialType polyType) { thePolyType = polyType; theLineScale = lineScale; theSampScale = sampleScale; theLatScale = latScale; theLonScale = lonScale; theHgtScale = heightScale; theLineOffset = lineOffset; theSampOffset = sampleOffset; theLatOffset = latOffset; theLonOffset = lonOffset; theHgtOffset = heightOffset; if(xNumeratorCoeffs.size() == 20) { std::copy(xNumeratorCoeffs.begin(), xNumeratorCoeffs.end(), theSampNumCoef); } if(xDenominatorCoeffs.size() == 20) { std::copy(xDenominatorCoeffs.begin(), xDenominatorCoeffs.end(), theSampDenCoef); } if(yNumeratorCoeffs.size() == 20) { std::copy(yNumeratorCoeffs.begin(), yNumeratorCoeffs.end(), theLineNumCoef); } if(yDenominatorCoeffs.size() == 20) { std::copy(yDenominatorCoeffs.begin(), yDenominatorCoeffs.end(), theLineDenCoef); } } //***************************************************************************** // METHOD: ossimRpcProjection::worldToLineSample() // // Overrides base class implementation. Directly computes line-sample from // the polynomials. //***************************************************************************** void ossimRpcProjection::worldToLineSample(const ossimGpt& ground_point, ossimDpt& imgPt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcProjection::worldToLineSample(): entering..." << std::endl; if(ground_point.isLatNan() || ground_point.isLonNan() ) { imgPt.makeNan(); return; } //* // Normalize the lat, lon, hgt: //* double nlat = (ground_point.lat - theLatOffset) / theLatScale; double nlon = (ground_point.lon - theLonOffset) / theLonScale; double nhgt; if(ossim::isnan(ground_point.hgt)) { nhgt = (theHgtScale - theHgtOffset) / theHgtScale; } else { nhgt = (ground_point.hgt - theHgtOffset) / theHgtScale; } //*** // Compute the adjusted, normalized line (U) and sample (V): //*** double Pu = polynomial(nlat, nlon, nhgt, theLineNumCoef); double Qu = polynomial(nlat, nlon, nhgt, theLineDenCoef); double Pv = polynomial(nlat, nlon, nhgt, theSampNumCoef); double Qv = polynomial(nlat, nlon, nhgt, theSampDenCoef); double U_rot = Pu / Qu; double V_rot = Pv / Qv; //*** // U, V are normalized quantities. Need now to establish the image file // line and sample. First, back out the adjustable parameter effects // starting with rotation: //*** double U = U_rot*theCosMapRot + V_rot*theSinMapRot; double V = V_rot*theCosMapRot - U_rot*theSinMapRot; //*** // Now back out skew, scale, and offset adjustments: //*** imgPt.line = U*(theLineScale+theIntrackScale) + theLineOffset + theIntrackOffset; imgPt.samp = V*(theSampScale+theCrtrackScale) + theSampOffset + theCrtrackOffset; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcProjection::worldToLineSample(): returning..." << std::endl; return; } void ossimRpcProjection::lineSampleToWorld(const ossimDpt& imagePoint, ossimGpt& worldPoint) const { if(!imagePoint.hasNans()) { lineSampleHeightToWorld(imagePoint, worldPoint.height(), worldPoint); } else { worldPoint.makeNan(); } } //***************************************************************************** // METHOD: ossimRpcProjection::lineSampleHeightToWorld() // // Performs reverse projection of image line/sample to ground point. // The imaging ray is intersected with a level plane at height = elev. // // NOTE: U = line, V = sample -- this differs from the convention. // //***************************************************************************** void ossimRpcProjection::lineSampleHeightToWorld(const ossimDpt& image_point, const double& ellHeight, ossimGpt& gpt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcProjection::lineSampleHeightToWorld: entering..." << std::endl; //*** // Constants for convergence tests: //*** static const int MAX_NUM_ITERATIONS = 10; static const double CONVERGENCE_EPSILON = 0.1; // pixels //*** // The image point must be adjusted by the adjustable parameters as well // as the scale and offsets given as part of the RPC param normalization. // // NOTE: U = line, V = sample //*** double skew = (image_point.x-theSampOffset - theCrtrackOffset)*theYawSkew; double U = (image_point.y-theLineOffset - theIntrackOffset+skew) / (theLineScale+theIntrackScale); double V = (image_point.x-theSampOffset - theCrtrackOffset) / (theSampScale+theCrtrackScale); //*** // Rotate the normalized U, V by the map rotation error (adjustable param): //*** double U_rot = theCosMapRot*U - theSinMapRot*V; double V_rot = theSinMapRot*U + theCosMapRot*V; U = U_rot; V = V_rot; // now apply adjust intrack and cross track //*** // Initialize quantities to be used in the iteration for ground point: //*** double nlat = 0.0; // normalized latitude double nlon = 0.0; // normalized longitude double nhgt; if(ossim::isnan(ellHeight)) { nhgt = (theHgtScale - theHgtOffset) / theHgtScale; // norm height } else { nhgt = (ellHeight - theHgtOffset) / theHgtScale; // norm height } double epsilonU = CONVERGENCE_EPSILON/(theLineScale+theIntrackScale); double epsilonV = CONVERGENCE_EPSILON/(theSampScale+theCrtrackScale); int iteration = 0; //*** // Declare variables only once outside the loop. These include: // * polynomials (numerators Pu, Pv, and denominators Qu, Qv), // * partial derivatives of polynomials wrt X, Y, // * computed normalized image point: Uc, Vc, // * residuals of normalized image point: deltaU, deltaV, // * partial derivatives of Uc and Vc wrt X, Y, // * corrections to normalized lat, lon: deltaLat, deltaLon. //*** double Pu, Qu, Pv, Qv; double dPu_dLat, dQu_dLat, dPv_dLat, dQv_dLat; double dPu_dLon, dQu_dLon, dPv_dLon, dQv_dLon; double Uc, Vc; double deltaU, deltaV; double dU_dLat, dU_dLon, dV_dLat, dV_dLon, W; double deltaLat, deltaLon; //*** // Now iterate until the computed Uc, Vc is within epsilon of the desired // image point U, V: //*** do { //*** // Calculate the normalized line and sample Uc, Vc as ratio of // polynomials Pu, Qu and Pv, Qv: //*** Pu = polynomial(nlat, nlon, nhgt, theLineNumCoef); Qu = polynomial(nlat, nlon, nhgt, theLineDenCoef); Pv = polynomial(nlat, nlon, nhgt, theSampNumCoef); Qv = polynomial(nlat, nlon, nhgt, theSampDenCoef); Uc = Pu/Qu; Vc = Pv/Qv; //*** // Compute residuals between desired and computed line, sample: //*** deltaU = U - Uc; deltaV = V - Vc; //*** // Check for convergence and skip re-linearization if converged: //*** if ((fabs(deltaU) > epsilonU) || (fabs(deltaV) > epsilonV)) { //*** // Analytically compute the partials of each polynomial wrt lat, lon: //*** dPu_dLat = dPoly_dLat(nlat, nlon, nhgt, theLineNumCoef); dQu_dLat = dPoly_dLat(nlat, nlon, nhgt, theLineDenCoef); dPv_dLat = dPoly_dLat(nlat, nlon, nhgt, theSampNumCoef); dQv_dLat = dPoly_dLat(nlat, nlon, nhgt, theSampDenCoef); dPu_dLon = dPoly_dLon(nlat, nlon, nhgt, theLineNumCoef); dQu_dLon = dPoly_dLon(nlat, nlon, nhgt, theLineDenCoef); dPv_dLon = dPoly_dLon(nlat, nlon, nhgt, theSampNumCoef); dQv_dLon = dPoly_dLon(nlat, nlon, nhgt, theSampDenCoef); //*** // Analytically compute partials of quotients U and V wrt lat, lon: //*** dU_dLat = (Qu*dPu_dLat - Pu*dQu_dLat)/(Qu*Qu); dU_dLon = (Qu*dPu_dLon - Pu*dQu_dLon)/(Qu*Qu); dV_dLat = (Qv*dPv_dLat - Pv*dQv_dLat)/(Qv*Qv); dV_dLon = (Qv*dPv_dLon - Pv*dQv_dLon)/(Qv*Qv); W = dU_dLon*dV_dLat - dU_dLat*dV_dLon; //*** // Now compute the corrections to normalized lat, lon: //*** deltaLat = (dU_dLon*deltaV - dV_dLon*deltaU) / W; deltaLon = (dV_dLat*deltaU - dU_dLat*deltaV) / W; nlat += deltaLat; nlon += deltaLon; } iteration++; } while (((fabs(deltaU)>epsilonU) || (fabs(deltaV)>epsilonV)) && (iteration < MAX_NUM_ITERATIONS)); //*** // Test for exceeding allowed number of iterations. Flag error if so: //*** if (iteration == MAX_NUM_ITERATIONS) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimRpcProjection::lineSampleHeightToWorld: \nMax number of iterations reached in ground point " << "solution. Results are inaccurate." << endl; } //*** // Now un-normalize the ground point lat, lon and establish return quantity: //*** gpt.lat = nlat*theLatScale + theLatOffset; gpt.lon = nlon*theLonScale + theLonOffset; gpt.hgt = ellHeight; } ossimGpt ossimRpcProjection::origin()const { return ossimGpt(theLatOffset, theLonOffset, theHgtOffset); } ossimDpt ossimRpcProjection::getMetersPerPixel() const { ossimDpt result; // ossimDpt left = ossimDpt(theSampOffset-1, // theLineOffset); // ossimDpt right = ossimDpt(theSampOffset+1, // theLineOffset); ossimDpt top = ossimDpt(theSampOffset, theLineOffset-1); ossimDpt bottom = ossimDpt(theSampOffset, theLineOffset+1); // ossimGpt leftG; // ossimGpt rightG; ossimGpt topG; ossimGpt bottomG; // lineSampleToWorld(left, leftG); // lineSampleToWorld(right, rightG); lineSampleToWorld(top, topG); lineSampleToWorld(bottom, bottomG); // result.x = (ossimEcefPoint(leftG) - ossimEcefPoint(rightG)).magnitude()/2.0; result.y = (ossimEcefPoint(topG) - ossimEcefPoint(bottomG)).magnitude()/2.0; result.x = result.y; return result; } bool ossimRpcProjection::operator==(const ossimProjection& projection) const { if(&projection == this) return true; // not implemented yet // return false; } //***************************************************************************** // PRIVATE METHOD: ossimRpcProjection::polynomial // // Computes polynomial. // //***************************************************************************** double ossimRpcProjection::polynomial(const double& P, const double& L, const double& H, const double* c) const { double r; if (thePolyType == A) { r = c[ 0] + c[ 1]*L + c[ 2]*P + c[ 3]*H + c[ 4]*L*P + c[ 5]*L*H + c[ 6]*P*H + c[ 7]*L*P*H + c[ 8]*L*L + c[ 9]*P*P + c[10]*H*H + c[11]*L*L*L + c[12]*L*L*P + c[13]*L*L*H + c[14]*L*P*P + c[15]*P*P*P + c[16]*P*P*H + c[17]*L*H*H + c[18]*P*H*H + c[19]*H*H*H; } else { r = c[ 0] + c[ 1]*L + c[ 2]*P + c[ 3]*H + c[ 4]*L*P + c[ 5]*L*H + c[ 6]*P*H + c[ 7]*L*L + c[ 8]*P*P + c[ 9]*H*H + c[10]*L*P*H + c[11]*L*L*L + c[12]*L*P*P + c[13]*L*H*H + c[14]*L*L*P + c[15]*P*P*P + c[16]*P*H*H + c[17]*L*L*H + c[18]*P*P*H + c[19]*H*H*H; } return r; } //***************************************************************************** // PRIVATE METHOD: ossimRpcProjection::dPoly_dLat // // Computes derivative of polynomial wrt normalized Latitude P. // //***************************************************************************** double ossimRpcProjection::dPoly_dLat(const double& P, const double& L, const double& H, const double* c) const { double dr; if (thePolyType == A) { dr = c[2] + c[4]*L + c[6]*H + c[7]*L*H + 2*c[9]*P + c[12]*L*L + 2*c[14]*L*P + 3*c[15]*P*P +2*c[16]*P*H + c[18]*H*H; } else { dr = c[2] + c[4]*L + c[6]*H + 2*c[8]*P + c[10]*L*H + 2*c[12]*L*P + c[14]*L*L + 3*c[15]*P*P + c[16]*H*H + 2*c[18]*P*H; } return dr; } //***************************************************************************** // PRIVATE METHOD: ossimRpcProjection::dPoly_dLon // // Computes derivative of polynomial wrt normalized Longitude L. // //***************************************************************************** double ossimRpcProjection::dPoly_dLon(const double& P, const double& L, const double& H, const double* c) const { double dr; if (thePolyType == A) { dr = c[1] + c[4]*P + c[5]*H + c[7]*P*H + 2*c[8]*L + 3*c[11]*L*L + 2*c[12]*L*P + 2*c[13]*L*H + c[14]*P*P + c[17]*H*H; } else { dr = c[1] + c[4]*P + c[5]*H + 2*c[7]*L + c[10]*P*H + 3*c[11]*L*L + c[12]*P*P + c[13]*H*H + 2*c[14]*P*L + 2*c[17]*L*H; } return dr; } //***************************************************************************** // METHOD: ossimRpcProjection::print() // // Formatted dump of data members. // //***************************************************************************** std::ostream& ossimRpcProjection::print(std::ostream& out) const { out << "\nDump of ossimRpcProjection object at " << hex << this << ":\n" << POLY_TYPE_KW << ": " << thePolyType << "\n" << LINE_SCALE_KW << ": " << theLineScale << "\n" << SAMP_SCALE_KW << ": " << theSampScale << "\n" << LAT_SCALE_KW << ": " << theLatScale << "\n" << LON_SCALE_KW << ": " << theLonScale << "\n" << HGT_SCALE_KW << ": " << theHgtScale << "\n" << LINE_OFFSET_KW << ": " << theLineOffset << "\n" << SAMP_OFFSET_KW << ": " << theSampOffset << "\n" << LAT_OFFSET_KW << ": " << theLatOffset << "\n" << LON_OFFSET_KW << ": " << theLonOffset << "\n" << HGT_OFFSET_KW << ": " << theHgtOffset << endl; for (int i=0; i. Check the keywordlist for proper syntax." << std::endl; return false; } thePolyType = (PolynomialType) value[0]; keyword = LINE_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLineScale = ossimString(value).toDouble(); keyword = SAMP_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theSampScale = ossimString(value).toDouble(); keyword = LAT_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLatScale = ossimString(value).toDouble(); keyword = LON_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLonScale = ossimString(value).toDouble(); keyword = HGT_SCALE_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theHgtScale = ossimString(value).toDouble(); keyword = LINE_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLineOffset = ossimString(value).toDouble(); keyword = SAMP_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theSampOffset = ossimString(value).toDouble(); keyword = LAT_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLatOffset = ossimString(value).toDouble(); keyword = LON_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLonOffset = ossimString(value).toDouble(); keyword = HGT_OFFSET_KW; value = kwl.find(prefix, keyword); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theHgtOffset = ossimString(value).toDouble(); for (int i=0; i. Check the keywordlist for proper syntax." << std::endl; return false; } theLineNumCoef[i] = ossimString(value).toDouble(); value = kwl.find(prefix, (LINE_DEN_COEF_KW+ossimString::toString(i)).c_str()); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theLineDenCoef[i] = ossimString(value).toDouble(); value = kwl.find(prefix, (SAMP_NUM_COEF_KW+ossimString::toString(i)).c_str()); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theSampNumCoef[i] = ossimString(value).toDouble(); value = kwl.find(prefix, (SAMP_DEN_COEF_KW+ossimString::toString(i)).c_str()); if (!value) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::loadState(): Error encountered parsing the following required keyword: " << "<" << keyword << ">. Check the keywordlist for proper syntax." << std::endl; return false; } theSampDenCoef[i] = ossimString(value).toDouble(); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimRpcProjection::loadState(): returning..." << std::endl; return true; } void ossimRpcProjection::initAdjustableParameters() { resizeAdjustableParameterArray(NUM_ADJUSTABLE_PARAMS); int numParams = getNumberOfAdjustableParameters(); for (int i=0; i proj = ossimProjectionFactoryRegistry::instance()->createProjection(setup); if(proj.valid()) { kwl.clear(); proj->saveState(kwl); return loadState(kwl); } } return false; } ossim_uint32 ossimRpcProjection::degreesOfFreedom()const { ossim_uint32 dof = 0; ossim_uint32 idx = 0; ossim_uint32 numAdj = getNumberOfAdjustableParameters(); for(idx = 0; idx < numAdj; ++idx) { if(!isParameterLocked(idx)) { ++dof; } } return dof; } //give inverse() partial derivative regarding parameter parmIdx (>=0) ossimGpt ossimRpcProjection::getInverseDeriv(int parmIdx, const ossimDpt& ipos, double hdelta) { double den = 0.5/hdelta; ossimGpt res,gd; double middle = getAdjustableParameter(parmIdx); //set parm to high value setAdjustableParameter(parmIdx, middle + hdelta, true); res = inverse(ipos); //set parm to low value and gte difference setAdjustableParameter(parmIdx, middle - hdelta, true); gd = inverse(ipos); //reset parm setAdjustableParameter(parmIdx, middle, true); res.lon = den*(res.lon - gd.lon) * 100000.0; //TBC : approx meters res.lat = den*(res.lat - gd.lat) * 100000.0 * cos(gd.lat / 180.0 * M_PI); res.hgt = den*(res.hgt - gd.hgt); return res; } //give forward() partial derivative regarding parameter parmIdx (>=0) ossimDpt ossimRpcProjection::getForwardDeriv(int parmIdx, const ossimGpt& gpos, double hdelta) { static double den = 0.5/hdelta; ossimDpt res; double middle = getAdjustableParameter(parmIdx); //set parm to high value setAdjustableParameter(parmIdx, middle + hdelta, true); res = forward(gpos); //set parm to low value and gte difference setAdjustableParameter(parmIdx, middle - hdelta, true); res -= forward(gpos); //get partial derivative res = res*den; //reset parm setAdjustableParameter(parmIdx, middle, true); return res; } double ossimRpcProjection::optimizeFit(const ossimTieGptSet& tieSet, double* /* targetVariance */) { //NOTE : ignore targetVariance ossimRefPtr solver = new ossimRpcSolver(false, false); //TBD : choices should be part of setupFromString std::vector imagePoints; std::vector groundPoints; tieSet.getSlaveMasterPoints(imagePoints, groundPoints); solver->solveCoefficients(imagePoints, groundPoints); const ossimRefPtr< ossimRpcModel > optProj = solver->getRpcModel(); if (!optProj) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimRpcProjection::optimizeFit(): error when optimizing the RPC with given tie points" << std::endl; return -1.0; } ossimKeywordlist kwl; optProj->saveState(kwl); this->loadState(kwl); return std::pow(solver->getRmsError(), 2); //variance in pixel^2 } void ossimRpcProjection::buildNormalEquation(const ossimTieGptSet& tieSet, NEWMAT::SymmetricMatrix& A, NEWMAT::ColumnVector& residue, NEWMAT::ColumnVector& projResidue, double pstep_scale) { //goal: build Least Squares system //constraint: never store full Jacobian matrix in memory (can be huge) // so we build the matrices incrementally // the system can be built using forward() or inverse() depending on the projection capabilities : useForward() // //TBD : add covariance matrix for each tie point //init int np = getNumberOfAdjustableParameters(); int dimObs; bool useImageObs = useForward(); //caching if (useImageObs) { dimObs = 2; //image observation } else { dimObs = 3; //ground observations } int no = dimObs * tieSet.size(); //number of observations A.ReSize(np); residue.ReSize(no); projResidue.ReSize(np); //Zeroify matrices that will be accumulated A = 0.0; projResidue = 0.0; const vector >& theTPV = tieSet.getTiePoints(); vector >::const_iterator tit; unsigned long c=1; if (useImageObs) { //image observations ossimDpt* imDerp = new ossimDpt[np]; ossimDpt resIm; // loop on tie points for (tit = theTPV.begin() ; tit != theTPV.end() ; ++tit) { //compute residue resIm = (*tit)->tie - forward(*(*tit)); residue(c++) = resIm.x; residue(c++) = resIm.y; //compute all image derivatives regarding parametres for the tie point position for(int p=0;p gdDerp(np); ossimGpt gd, resGd; // loop on tie points for (tit = theTPV.begin() ; tit != theTPV.end() ; ++tit) { //compute residue gd = inverse((*tit)->tie); residue(c++) = resGd.lon = ((*tit)->lon - gd.lon) * 100000.0; residue(c++) = resGd.lat = ((*tit)->lat - gd.lat) * 100000.0 * cos(gd.lat / 180.0 * M_PI); residue(c++) = resGd.hgt = (*tit)->hgt - gd.hgt; //TBD : normalize to meters? //compute all image derivatives regarding parametres for the tie point position for(int p=0;ptie, pstep_scale); } //compute influence of tie point on all sytem elements for(int p1=0;p1 >& theTPV = tieSet.getTiePoints(); vector >::const_iterator tit; unsigned long c=1; if (useImageObs) { //image observations ossimDpt resIm; // loop on tie points for (tit = theTPV.begin() ; tit != theTPV.end() ; ++tit) { //compute residue resIm = (*tit)->tie - forward(**tit); residue(c++) = resIm.x; residue(c++) = resIm.y; } } else { // ground observations ossimGpt gd; // loop on tie points for (tit = theTPV.begin() ; tit != theTPV.end() ; ++tit) { //compute residue gd = inverse((*tit)->tie); residue(c++) = ((*tit)->lon - gd.lon) * 100000.0; //approx meters //TBC TBD residue(c++) = ((*tit)->lat - gd.lat) * 100000.0 * cos(gd.lat / 180.0 * M_PI); residue(c++) = (*tit)->hgt - gd.hgt; //meters } } //end of if (useImageObs) return residue; } /*! * solves Ax = r , with A symmetric positive definite * A can be rank deficient * size of A is typically between 10 and 100 rows */ NEWMAT::ColumnVector ossimRpcProjection::solveLeastSquares(NEWMAT::SymmetricMatrix& A, NEWMAT::ColumnVector& r)const { NEWMAT::ColumnVector x = invert(A)*r; return x; } /** * stable invert stolen from ossimRpcSolver */ NEWMAT::Matrix ossimRpcProjection::invert(const NEWMAT::Matrix& m)const { ossim_uint32 idx = 0; NEWMAT::DiagonalMatrix d; NEWMAT::Matrix u; NEWMAT::Matrix v; // decompose m.t*m which is stored in Temp into the singular values and vectors. // NEWMAT::SVD(m, d, u, v, true, true); // invert the diagonal // this is just doing the reciprical fo all diagonal components and store back int // d. ths compute d inverse. // for(idx=0; idx < (ossim_uint32)d.Ncols(); ++idx) { if(d[idx] > 1e-14) //TBC : use DBL_EPSILON ? { d[idx] = 1.0/d[idx]; } else { d[idx] = 0.0; //DEBUG TBR cout<<"warning: singular matrix in SVD"< #include #include #include #include #include using namespace ossim; using namespace std; static const ossim_uint32 STARTING_GRID_SIZE = 8; static const ossim_uint32 ENDING_GRID_SIZE = 64; ossimRpcSolver::ossimRpcSolver(bool useElevation, bool useHeightAboveMSLFlag) : theUseElevationFlag(useElevation), theHeightAboveMSLFlag(useHeightAboveMSLFlag), theMeanResidual(0), theMaxResidual(0) { } void ossimRpcSolver::solveCoefficients(const ossimDrect& imageBounds, ossimProjection* proj, ossim_uint32 xSamples, ossim_uint32 ySamples) { ossimRefPtr geom = new ossimImageGeometry(); geom->setProjection(proj); solveCoefficients(imageBounds, geom.get(), xSamples, ySamples); } void ossimRpcSolver::solveCoefficients(const ossimDrect& imageBounds, ossimImageGeometry* geom, ossim_uint32 xSamples, ossim_uint32 ySamples) { if (!geom || !(geom->getProjection())) return; theRefGeom = geom; std::vector groundPoints; std::vector imagePoints; ossim_uint32 x,y; ossimGpt gpt; ossimGpt defaultGround; if (ySamples <= 1) ySamples = STARTING_GRID_SIZE; if (xSamples <= 1) xSamples = STARTING_GRID_SIZE; srand(time(0)); double Dx = imageBounds.width()/(xSamples-1); double Dy = imageBounds.height()/(ySamples-1); ossimDpt dpt; for(y = 0; y < ySamples; ++y) { dpt.y = y*Dy + imageBounds.ul().y; for(x = 0; x < xSamples; ++x) { dpt.x = x*Dx + imageBounds.ul().x; if (theUseElevationFlag) geom->localToWorld(dpt, gpt); else geom->localToWorld(dpt, 0, gpt); if (gpt.isLatLonNan()) continue; if(gpt.isHgtNan()) gpt.height(0.0); gpt.changeDatum(defaultGround.datum()); if(theHeightAboveMSLFlag) { double h = ossimElevManager::instance()->getHeightAboveMSL(gpt); if(ossim::isnan(h) == false) gpt.height(h); } imagePoints.push_back(dpt); groundPoints.push_back(gpt); } } solveCoefficients(imagePoints, groundPoints); } void ossimRpcSolver::solveCoefficients(const std::vector& imagePoints, const std::vector& groundControlPoints) { if((imagePoints.size() != groundControlPoints.size())) return; // we will first create f which holds the result of f(x,y,z). // This basically holds the cooresponding image point for each // ground control point. One for x and a second array for y int numPoints = imagePoints.size(); std::vector fx, fy; // Holds the x, y, z vectors // std::vector x; std::vector y; std::vector z; ossim_uint32 c = 0; fx.resize(imagePoints.size()); fy.resize(imagePoints.size()); x.resize(imagePoints.size()); y.resize(imagePoints.size()); z.resize(imagePoints.size()); // compute the image bounds for the given image points ossimDrect rect(imagePoints); ossimDpt centerImagePoint = rect.midPoint(); // get the width and height that will be used in data normalization ossim_float64 w = rect.width(); ossim_float64 h = rect.height(); double latSum=0.0; double lonSum=0.0; double heightSum=0.0; // find the center ground Use elevation only if its enabled for(c = 0; c < groundControlPoints.size();++c) { if(ossim::isnan(groundControlPoints[c].latd()) == false) { latSum += groundControlPoints[c].latd(); } if(ossim::isnan(groundControlPoints[c].lond()) == false) { lonSum += groundControlPoints[c].lond(); } if(!groundControlPoints[c].isHgtNan()) { if(theUseElevationFlag) { heightSum += groundControlPoints[c].height(); } } } // set the center ground for the offset // ossimGpt centerGround(latSum/groundControlPoints.size(), lonSum/groundControlPoints.size(), heightSum/groundControlPoints.size()); // set up ground scales and deltas for normalization ossim_float64 deltaLat = 0.0; ossim_float64 deltaLon = 0.0; ossim_float64 deltaHeight = 0.0; ossim_float64 maxDeltaLat = 0.0; ossim_float64 maxDeltaLon = 0.0; ossim_float64 maxDeltaHeight = 0.0; ossim_float64 heightTest = 0.0; for(c = 0; c < groundControlPoints.size(); ++c) { deltaLat = (groundControlPoints[c].latd()-centerGround.latd()); deltaLon = (groundControlPoints[c].lond()-centerGround.lond()); if(!groundControlPoints[c].isHgtNan()) { if(theUseElevationFlag) { deltaHeight = groundControlPoints[c].height() - centerGround.height(); heightTest = groundControlPoints[c].height(); } else { deltaHeight = 0.0; heightTest = 0.0; } } else { deltaHeight = 0.0; } fx[c] = (imagePoints[c].x - centerImagePoint.x)/(w/2.0); fy[c] = (imagePoints[c].y - centerImagePoint.y)/(h/2.0); x[c] = deltaLon; y[c] = deltaLat; z[c] = deltaHeight; if(fabs(deltaLat) > maxDeltaLat) maxDeltaLat = fabs(deltaLat); if(fabs(deltaLon) > maxDeltaLon) maxDeltaLon = fabs(deltaLon); if(fabs(heightTest) > maxDeltaHeight) maxDeltaHeight = fabs(heightTest); } bool elevationEnabled = theUseElevationFlag; // if max delta is less than a degree set it to 1 degree. // if(maxDeltaLat < 1.0) // maxDeltaLat = 1.0; // if(maxDeltaLon < 1.0) // maxDeltaLon = 1.0; if(maxDeltaHeight < FLT_EPSILON) elevationEnabled = false; if(maxDeltaHeight < 1.0) maxDeltaHeight = 1.0; // set the height scale to something pretty large if(!elevationEnabled) { maxDeltaHeight = 1.0/DBL_EPSILON; maxDeltaHeight = 10000; centerGround.height(0.0); } // normalize the ground points for(c = 0; c < groundControlPoints.size(); ++c) { x[c] /= maxDeltaLon; y[c] /= maxDeltaLat; z[c] /= maxDeltaHeight; } theRpcModel = new ossimRpcModel; theRpcModel->thePolyType = ossimRpcModel::B; theRpcModel->theLineOffset = centerImagePoint.y; theRpcModel->theSampOffset = centerImagePoint.x; theRpcModel->theLineScale = h/2.0; theRpcModel->theSampScale = w/2.0; theRpcModel->theLatScale = maxDeltaLat; theRpcModel->theLonScale = maxDeltaLon; theRpcModel->theHgtScale = maxDeltaHeight; theRpcModel->theLatOffset = centerGround.lat; theRpcModel->theLonOffset = centerGround.lon; theRpcModel->theHgtOffset = centerGround.hgt; if(ossim::isnan(theRpcModel->theHgtOffset)) theRpcModel->theHgtOffset = 0.0; NEWMAT::ColumnVector coeffxVec; NEWMAT::ColumnVector coeffyVec; // perform a least squares fit for sample values found in f // given the world values with variables x, y, z solveCoefficients(coeffxVec, fx, x, y, z); // perform a least squares fit for line values found in f // given the world values with variables x, y, z solveCoefficients(coeffyVec, fy, x, y, z); // there are 20 numerator coefficients and 19 denominator coefficients. // I believe that the very first one for the denominator coefficients is fixed at 1. theRpcModel->theLineNumCoef[0] = coeffyVec[0]; theRpcModel->theLineDenCoef[0] = 1.0; theRpcModel->theSampNumCoef[0] = coeffxVec[0]; theRpcModel->theSampDenCoef[0] = 1.0; for (int i=1; i<20; i++) { theRpcModel->theLineNumCoef[i] = coeffyVec[i]; theRpcModel->theLineDenCoef[i] = coeffyVec[i+19]; theRpcModel->theSampNumCoef[i] = coeffxVec[i]; theRpcModel->theSampDenCoef[i] = coeffxVec[i+19]; } // now lets compute the RMSE for the given control points by feeding it // back through the modeled RPC ossim_float64 sumSquareError = 0.0; ossim_uint32 idx = 0; theMaxResidual = 0; for (idx = 0; idx theMaxResidual) theMaxResidual = len; sumSquareError += (len*len); } // set the error theMeanResidual = sqrt(sumSquareError/imagePoints.size()); } bool ossimRpcSolver::solve(const ossimDrect& imageBounds, ossimImageGeometry* geom, const double& tolerance) { static const char* MODULE = "ossimRpcSolver::solve() "; if (!geom) return false; theRefGeom = geom; ossimDpt ul = imageBounds.ul(); ossim_float64 w = imageBounds.width(); ossim_float64 h = imageBounds.height(); ossimDpt ipt, irpc; ossimGpt gpt; // Start at the minimum grid size: ossim_uint32 xSamples = STARTING_GRID_SIZE; ossim_uint32 ySamples = STARTING_GRID_SIZE; // Loop until error is below threshold: bool converged = false; while (!converged) { double residual = 0; double sumResiduals = 0; int numResiduals = 0; theMaxResidual = 0; converged = true; // hope for the best and get proved otherwise below solveCoefficients(imageBounds, geom, xSamples, ySamples); // Sample along x and y directions to accumulate errors: double deltaX = w/(xSamples-1); double deltaY = h/(ySamples-1); // Sample the midpoints between image grid used to compute RPC: for (ossim_uint32 y=0; ylocalToWorld(ipt, gpt); else geom->localToWorld(ipt, 0, gpt); if(theHeightAboveMSLFlag) { double h = ossimElevManager::instance()->getHeightAboveMSL(gpt); if(ossim::isnan(h) == false) gpt.height(h); } // Reverse projection using RPC: evalPoint(gpt, irpc); // Compute residual and accumulate: residual = (ipt-irpc).length(); if (residual > theMaxResidual) theMaxResidual = residual; sumResiduals += residual; ++numResiduals; } } theMeanResidual = sumResiduals/numResiduals; if (theMaxResidual > tolerance) converged = false; #if 1 { //### DEBUG BLOCK ### ossimNotify(ossimNotifyLevel_INFO)<= ENDING_GRID_SIZE) && (ySamples >= ENDING_GRID_SIZE)) break; if (!converged) { xSamples *= 2; if (xSamples > ENDING_GRID_SIZE) xSamples = ENDING_GRID_SIZE; ySamples *= 2; if (ySamples > ENDING_GRID_SIZE) ySamples = ENDING_GRID_SIZE; } } // Was testing the max residual. But use the mean for final test: if (theMeanResidual <= tolerance) converged = true; if (!converged) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: Unable to converge on desired error tolerance ("< tolerance) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: While the RPC solution did converge, at least one residual (" <setMetersPerPixel(geom->getMetersPerPixel()); return converged; } bool ossimRpcSolver::solve(const ossimFilename& imageFilename, const double& pixel_tolerance) { // Establish input geometry: ossimRefPtr h = ossimImageHandlerRegistry::instance()->open(imageFilename); if(!h.valid()) return false; ossimRefPtr geom = h->getImageGeometry(); ossimDrect imageRect (h->getBoundingRect()); return solve(imageRect, geom.get(), pixel_tolerance); } double ossimRpcSolver::getRmsError()const { return theMeanResidual; } double ossimRpcSolver::getMaxError()const { return theMaxResidual; } void ossimRpcSolver::solveInitialCoefficients(NEWMAT::ColumnVector& coeff, const std::vector& f, const std::vector& x, const std::vector& y, const std::vector& z)const { ossim_uint32 idx = 0; NEWMAT::Matrix m; NEWMAT::ColumnVector r((int)f.size()); for(idx = 0; idx < f.size(); ++idx) { r[idx] = f[idx]; } setupSystemOfEquations(m, r, x, y, z); coeff = invert(m.t()*m)*m.t()*r; } void ossimRpcSolver::solveCoefficients(NEWMAT::ColumnVector& coeff, const std::vector& f, const std::vector& x, const std::vector& y, const std::vector& z)const { // this is an iterative linear least square fit. We really pobably need // a nonlinear fit instead // ossim_uint32 idx = 0; NEWMAT::Matrix m; NEWMAT::ColumnVector r((int)f.size()); for(idx = 0; idx < f.size(); ++idx) { r[idx] = f[idx]; } NEWMAT::ColumnVector tempCoeff; NEWMAT::DiagonalMatrix weights((int)f.size()); NEWMAT::ColumnVector denominator(20); // initialize the weight matrix to the identity // for(idx = 0; idx < f.size(); ++idx) { weights[idx] = 1.0; } double residualValue = 1.0/FLT_EPSILON; ossim_uint32 iterations = 0; NEWMAT::Matrix w2; do { w2 = weights*weights; #if 0 { //### DEBUG ### cout<<"\nw2 = \n"< #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimRsmModel, "ossimRsmModel", ossimSensorModel); // Define Trace flags for use within this file: static const ossimTrace traceExec ("ossimRsmModel:exec"); static const ossimTrace traceDebug ("ossimRsmModel:debug"); static std::string MODEL_TYPE_KW = "ossimRsmModel"; ossimRsmModel::ossimRsmModel() : ossimSensorModel(), m_ida(), m_pia(), m_pca() { initAdjustableParameters(); } ossimRsmModel::ossimRsmModel( const ossimRsmModel& obj ) : ossimSensorModel( obj ), m_ida( obj.m_ida ), m_pia( obj.m_pia ), m_pca( obj.m_pca ) { } const ossimRsmModel& ossimRsmModel::operator=( const ossimRsmModel& rhs ) { if (this != &rhs) { ossimSensorModel::operator=(rhs); m_ida = rhs.m_ida; m_pia = rhs.m_pia; m_pca = rhs.m_pca; } return *this; } ossimRsmModel::~ossimRsmModel() { } //--- // METHOD: ossimRsmModel::worldToLineSample() // // Overrides base class implementation. Directly computes line-sample from // the polynomials. //--- void ossimRsmModel::worldToLineSample(const ossimGpt& ground_point, ossimDpt& img_pt) const { if(ground_point.isLatNan() || ground_point.isLonNan() ) { img_pt.makeNan(); return; } //--- // RSMIDA GRNDD Ground Domain Form: // G: Geodetic: range x is -pi to pi, y is -pi/2 to pi/2 // H: Geodetic: range x is 0 to 2pi, y is -pi/2 to pi/2 (where image is close to pi. // R: Rectangular (not supported). //--- // Initial xyz for computing the pca index. double x; if ( m_ida.m_grndd == 'H' ) { x = ossim::degreesToRadians((ground_point.lon >= 0.0) ? ground_point.lon : ground_point.lon + 360.0); } else { x = ossim::degreesToRadians( ground_point.lon ); } double y = ossim::degreesToRadians(ground_point.lat); double z = ground_point.hgt; if ( ossim::isnan( z ) ) { z = 0.0; // ??? drb } ossim_uint32 pcaIndex = getPcaIndex( x, y, z ); //--- // Normalize the lat, lon, hgt: // a_norm = (a-offset)/scalefactor //--- y = (y - m_pca[pcaIndex].m_ynrmo) / m_pca[pcaIndex].m_ynrmsf; x = (x - m_pca[pcaIndex].m_xnrmo) / m_pca[pcaIndex].m_xnrmsf; if( ground_point.isHgtNan() ) { z = ( - m_pca[pcaIndex].m_znrmo) / m_pca[pcaIndex].m_znrmsf; } else { z = (ground_point.hgt - m_pca[pcaIndex].m_znrmo) / m_pca[pcaIndex].m_znrmsf; } double rnNrm = polynomial(x, y, z, m_pca[pcaIndex].m_rnpwrx, m_pca[pcaIndex].m_rnpwry, m_pca[pcaIndex].m_rnpwrz, m_pca[pcaIndex].m_rnpcf); double rdNrm = polynomial(x, y, z, m_pca[pcaIndex].m_rdpwrx, m_pca[pcaIndex].m_rdpwry, m_pca[pcaIndex].m_rdpwrz, m_pca[pcaIndex].m_rdpcf); double cnNrm = polynomial(x, y, z, m_pca[pcaIndex].m_cnpwrx, m_pca[pcaIndex].m_cnpwry, m_pca[pcaIndex].m_cnpwrz, m_pca[pcaIndex].m_cnpcf); double cdNrm = polynomial(x, y, z, m_pca[pcaIndex].m_cdpwrx, m_pca[pcaIndex].m_cdpwry, m_pca[pcaIndex].m_cdpwrz, m_pca[pcaIndex].m_cdpcf); double rNrm = rnNrm / rdNrm; double cNrm = cnNrm / cdNrm; //--- // Unnormalize the computed value // a = (a_norm * scalefactor) + offset // // Note: // // RSM (0,0) is upper left corner of pixel(0,0). OSSIM (0,0) is // center of the pixel; hence, the - 0.5. (drb 22 May 2015) //--- // img_pt.line = (rNrm * m_rnrmsf) + m_rnrmo; // img_pt.samp = (cNrm * m_cnrmsf) + m_cnrmo; img_pt.line = (rNrm * m_pca[pcaIndex].m_rnrmsf) + m_pca[pcaIndex].m_rnrmo - 0.5; img_pt.samp = (cNrm * m_pca[pcaIndex].m_cnrmsf) + m_pca[pcaIndex].m_cnrmo - 0.5; } // End: ossimRsmModel::worldToLineSample( ... ) //--- // METHOD: ossimRsmModel::lineSampleToWorld() // // Overrides base class implementation. Performs DEM intersection. //--- void ossimRsmModel::lineSampleToWorld(const ossimDpt& imagePoint, ossimGpt& worldPoint) const { if(!imagePoint.hasNans()) { ossimEcefRay ray; //--- // Note: // RSM (0,0) is upper left corner of pixel(0,0). OSSIM (0,0) is // center of the pixel; hence, the + 0.5. (drb 22 May 2015) //--- // imagingRay(imagePoint, ray); imagingRay(ossimDpt(imagePoint.x+0.5, imagePoint.y+0.5), ray); ossimElevManager::instance()->intersectRay(ray, worldPoint); } else { worldPoint.makeNan(); } } //--- // METHOD: ossimRsmModel::lineSampleHeightToWorld() // // Performs reverse projection of image line/sample to ground point. // The imaging ray is intersected with a level plane at height = elev. // // NOTE: U = line, V = sample -- this differs from the convention. // //--- void ossimRsmModel::lineSampleHeightToWorld(const ossimDpt& image_point, const double& ellHeight, ossimGpt& gpt) const { // Borrowed from ossimRpcModel algorithm to converge on polynomial roots //--- // Constants for convergence tests: //--- // SPEC says 1/20 of a pixel for polynomial fit, so converge to at least that point static const int MAX_NUM_ITERATIONS = 100; static const double CONVERGENCE_EPSILON = 0.05; // pixels ossim_uint32 pcaIndex = getPcaIndex( image_point, true ); // Image point of 0 to ossim is 0.5 to RSM. // double U = (image_point.y-m_rnrmo) / (m_rnrmsf); // double V = (image_point.x-m_cnrmo) / (m_cnrmsf); double U = (image_point.y+0.5-m_pca[pcaIndex].m_rnrmo) / (m_pca[pcaIndex].m_rnrmsf); double V = (image_point.x+0.5-m_pca[pcaIndex].m_cnrmo) / (m_pca[pcaIndex].m_cnrmsf); //--- // Initialize quantities to be used in the iteration for ground point: //--- double nlat = 0.0; // normalized latitude double nlon = 0.0; // normalized longitude double nhgt; if(ossim::isnan(ellHeight)) { nhgt = (- m_pca[pcaIndex].m_znrmo) / m_pca[pcaIndex].m_znrmsf; // norm height } else { nhgt = (ellHeight - m_pca[pcaIndex].m_znrmo) / m_pca[pcaIndex].m_znrmsf; // norm height } double epsilonU = CONVERGENCE_EPSILON/m_pca[pcaIndex].m_rnrmsf; double epsilonV = CONVERGENCE_EPSILON/m_pca[pcaIndex].m_cnrmsf; int iteration = 0; //--- // Declare variables only once outside the loop. These include: // * polynomials (numerators Pu, Pv, and denominators Qu, Qv), // * partial derivatives of polynomials wrt X, Y, // * computed normalized image point: Uc, Vc, // * residuals of normalized image point: deltaU, deltaV, // * partial derivatives of Uc and Vc wrt X, Y, // * corrections to normalized lat, lon: deltaLat, deltaLon. //--- double Pu, Qu, Pv, Qv; double dPu_dLat, dQu_dLat, dPv_dLat, dQv_dLat; double dPu_dLon, dQu_dLon, dPv_dLon, dQv_dLon; double Uc, Vc; double deltaU, deltaV; double dU_dLat, dU_dLon, dV_dLat, dV_dLon, W; double deltaLat, deltaLon; //--- // Now iterate until the computed Uc, Vc is within epsilon of the desired // image point U, V: //--- do { //--- // Calculate the normalized line and sample Uc, Vc as ratio of // polynomials Pu, Qu and Pv, Qv: //--- Pu = polynomial(nlon, nlat, nhgt, m_pca[pcaIndex].m_rnpwrx, m_pca[pcaIndex].m_rnpwry, m_pca[pcaIndex].m_rnpwrz, m_pca[pcaIndex].m_rnpcf); Qu = polynomial(nlon, nlat, nhgt, m_pca[pcaIndex].m_rdpwrx, m_pca[pcaIndex].m_rdpwry, m_pca[pcaIndex].m_rdpwrz, m_pca[pcaIndex].m_rdpcf); Pv = polynomial(nlon, nlat, nhgt, m_pca[pcaIndex].m_cnpwrx, m_pca[pcaIndex].m_cnpwry, m_pca[pcaIndex].m_cnpwrz, m_pca[pcaIndex].m_cnpcf); Qv = polynomial(nlon, nlat, nhgt, m_pca[pcaIndex].m_cdpwrx, m_pca[pcaIndex].m_cdpwry, m_pca[pcaIndex].m_cdpwrz, m_pca[pcaIndex].m_cdpcf); Uc = Pu/Qu; Vc = Pv/Qv; //--- // Compute residuals between desired and computed line, sample: //--- deltaU = U - Uc; deltaV = V - Vc; //--- // Check for convergence and skip re-linearization if converged: //--- if ((fabs(deltaU) > epsilonU) || (fabs(deltaV) > epsilonV)) { //--- // Analytically compute the partials of each polynomial wrt lat, lon: //--- dPu_dLat = dPoly_dLat(nlon, nlat, nhgt, m_pca[pcaIndex].m_rnpwrx, m_pca[pcaIndex].m_rnpwry, m_pca[pcaIndex].m_rnpwrz, m_pca[pcaIndex].m_rnpcf); dQu_dLat = dPoly_dLat(nlon, nlat, nhgt, m_pca[pcaIndex].m_rdpwrx, m_pca[pcaIndex].m_rdpwry, m_pca[pcaIndex].m_rdpwrz, m_pca[pcaIndex].m_rdpcf); dPv_dLat = dPoly_dLat(nlon, nlat, nhgt, m_pca[pcaIndex].m_cnpwrx, m_pca[pcaIndex].m_cnpwry, m_pca[pcaIndex].m_cnpwrz, m_pca[pcaIndex].m_cnpcf); dQv_dLat = dPoly_dLat(nlon, nlat, nhgt, m_pca[pcaIndex].m_cdpwrx, m_pca[pcaIndex].m_cdpwry, m_pca[pcaIndex].m_cdpwrz, m_pca[pcaIndex].m_cdpcf); dPu_dLon = dPoly_dLon(nlon, nlat, nhgt, m_pca[pcaIndex].m_rnpwrx, m_pca[pcaIndex].m_rnpwry, m_pca[pcaIndex].m_rnpwrz, m_pca[pcaIndex].m_rnpcf); dQu_dLon = dPoly_dLon(nlon, nlat, nhgt, m_pca[pcaIndex].m_rdpwrx, m_pca[pcaIndex].m_rdpwry, m_pca[pcaIndex].m_rdpwrz, m_pca[pcaIndex].m_rdpcf); dPv_dLon = dPoly_dLon(nlon, nlat, nhgt, m_pca[pcaIndex].m_cnpwrx, m_pca[pcaIndex].m_cnpwry, m_pca[pcaIndex].m_cnpwrz, m_pca[pcaIndex].m_cnpcf); dQv_dLon = dPoly_dLon(nlon, nlat, nhgt, m_pca[pcaIndex].m_cdpwrx, m_pca[pcaIndex].m_cdpwry, m_pca[pcaIndex].m_cdpwrz, m_pca[pcaIndex].m_cdpcf); //--- // Analytically compute partials of quotients U and V wrt lat, lon: //--- dU_dLat = (Qu*dPu_dLat - Pu*dQu_dLat)/(Qu*Qu); dU_dLon = (Qu*dPu_dLon - Pu*dQu_dLon)/(Qu*Qu); dV_dLat = (Qv*dPv_dLat - Pv*dQv_dLat)/(Qv*Qv); dV_dLon = (Qv*dPv_dLon - Pv*dQv_dLon)/(Qv*Qv); W = dU_dLon*dV_dLat - dU_dLat*dV_dLon; //--- // Now compute the corrections to normalized lat, lon: //--- deltaLat = (dU_dLon*deltaV - dV_dLon*deltaU) / W; deltaLon = (dV_dLat*deltaU - dU_dLat*deltaV) / W; nlat += deltaLat; nlon += deltaLon; } ++iteration; } while (((fabs(deltaU)>epsilonU) || (fabs(deltaV)>epsilonV)) && (iteration < MAX_NUM_ITERATIONS)); //--- // Test for exceeding allowed number of iterations. Flag error if so: //--- if (iteration == MAX_NUM_ITERATIONS) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimRsmModel::lineSampleHeightToWorld:\n" << "Max number of iterations reached in ground point " << "solution. Results are inaccurate." << endl; } //--- // Now un-normalize the ground point lat, lon and establish return quantity: // // lon will 0 to 2PI when image is near PI radians as specified in RSMIDA // GRNDD field when value is "H" versus "G". OSSIMGPT wrap handles this // automatically, so no need to worry about it. //--- gpt.lat = ossim::radiansToDegrees(nlat*m_pca[pcaIndex].m_ynrmsf + m_pca[pcaIndex].m_ynrmo); gpt.lon = ossim::radiansToDegrees(nlon*m_pca[pcaIndex].m_xnrmsf + m_pca[pcaIndex].m_xnrmo); gpt.hgt = (nhgt * m_pca[pcaIndex].m_znrmsf) + m_pca[pcaIndex].m_znrmo; //ellHeight; gpt.wrap(); //--- // Note: See above note. Added in wrap call. Longitude was coming out 242 // when should have been -118. (drb - 22 May 2015) //--- } // End: ossimRsmModel::lineSampleHeightToWorld( ... ) //--- // METHOD: ossimRsmModel::imagingRay() // // Constructs a ray by intersecting 2 ellipsoid heights above and // below the RPC height offset, and then forming a vector between the two. // //--- void ossimRsmModel::imagingRay(const ossimDpt& imagePoint, ossimEcefRay& imageRay) const { ossim_uint32 pcaIndex = getPcaIndex( imagePoint, true ); //--- // For "from point", "to point" we want the image ray to be from above the // ellipsoid down to Earth. // // It appears the ray "from point" must be above the ellipsiod for the // ossimElevSource::intersectRay method; ultimately, the // ossimEllipsoid::nearestIntersection method, else it goes off in the // weeds... //--- double vectorLength = m_pca[pcaIndex].m_znrmsf * 2.0; ossimGpt gpt; // "from" point double intHgt = m_pca[pcaIndex].m_znrmo + vectorLength; lineSampleHeightToWorld(imagePoint, intHgt, gpt); ossimEcefPoint intECFfrom(gpt); // "to" point lineSampleHeightToWorld(imagePoint, m_pca[pcaIndex].m_znrmo, gpt); ossimEcefPoint intECFto(gpt); // Construct ray ossimEcefRay ray(intECFfrom, intECFto); imageRay = ray; } void ossimRsmModel::updateModel() { } void ossimRsmModel::initAdjustableParameters() { } ossimObject* ossimRsmModel::dup() const { return new ossimRsmModel(*this); } //--- // METHOD: ossimRsmModel::print() // // Formatted dump of data members. //--- std::ostream& ossimRsmModel::print(std::ostream& out) const { std::string prefix = ""; ossimKeywordlist kwl; saveState( kwl, prefix.c_str() ); out << kwl; return out; } bool ossimRsmModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { static const char MODULE[] = "ossimRsmModel::saveState"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } kwl.add(prefix, ossimKeywordNames::TYPE_KW, MODEL_TYPE_KW.c_str()); //--- // Hand off to base class for common stuff: //--- ossimSensorModel::saveState(kwl, prefix); std::string pfx = (prefix ? prefix : "" ); // IDA: m_ida.saveState( kwl, prefix ); // PIA: m_pia.saveState( kwl, prefix ); // PCA: for ( ossim_uint32 i = 0; i < m_pca.size(); ++i ) { m_pca[i].saveState( kwl, pfx, i ); } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return true; } bool ossimRsmModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "ossimRsmModel::loadState"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool status = false; // Check for type match before preceeding: std::string pfx = ( prefix ? prefix : "" ); std::string type = kwl.findKey( pfx, std::string(ossimKeywordNames::TYPE_KW) ); if ( (type == "ossimNitfRsmModel" ) || ( type == MODEL_TYPE_KW ) ) { // Pass on to the base-class for parsing first: if ( ossimSensorModel::loadState(kwl, prefix) ) { if ( m_ida.loadState( kwl, pfx ) ) { if ( m_pia.loadState( kwl, pfx ) ) { m_pca.clear(); for ( ossim_uint32 tagIndex = 0; tagIndex < m_pia.m_tnis; ++tagIndex ) { ossimRsmpca pca; if ( pca.loadState( kwl, pfx, tagIndex ) ) { m_pca.push_back( pca ); } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING! RSMPCA[" << tagIndex << "] intitialization failed!" << std::endl; break; // Get out... } } // Should now have a rsmpca record for each segment. if ( m_pia.m_tnis == (ossim_uint32)m_pca.size() ) { // Set the status for downstream code. status = true; updateModel(); } } // Matches: if ( m_pia.loadState( kwl, pfx ) ) } // Matches:if ( m_ida.loadState( kwl, pfx ) ) } // Matches: if ( ossimSensorModel::loadState(kwl, prefix) ) } // Matches: if ( (type == "ossimNitfRsmModel" ) || ... if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status = " << (status?"true":"false") << "\n"; } return status; } ossim_uint32 ossimRsmModel::getPcaIndex( const double& x, const double& y, const double& z) const { ossimDpt ipt; lowOrderPolynomial( x, y, z, ipt ); return getPcaIndex( ipt, false ); } ossim_uint32 ossimRsmModel::getPcaIndex( const ossimDpt& ipt, bool shiftPoint ) const { //--- // RSM (0,0) is upper left corner of pixel(0,0). OSSIM (0,0) is // center of the pixel; hence, the shift 0.5 if coming from ossim. //--- double shift = shiftPoint ? 0.5 : 0.0; // Row section number: double rsn = std::floor( ( ipt.y + shift - (double)(m_ida.m_minr) ) / (double)(m_pia.m_rssiz) ); if ( rsn < 0.0 ) { rsn = 0.0; } else if ( rsn > (m_pia.m_rnis-1) ) { rsn = m_pia.m_rnis-1; } // Column section number: double csn = std::floor( ( ipt.x + shift - (double)(m_ida.m_minc) ) / (double)(m_pia.m_cssiz) ); if ( csn < 0.0 ) { csn = 0.0; } else if ( csn > (m_pia.m_cnis-1) ) { csn = m_pia.m_cnis-1; } //return static_cast(rsn) * m_pia.m_rnis + static_cast(csn); return static_cast(rsn) * m_pia.m_cnis + static_cast(csn); } void ossimRsmModel::lowOrderPolynomial( const double& x, const double& y, const double& z, ossimDpt& ipt ) const { ipt.y = m_pia.m_r0 + m_pia.m_rx * x + m_pia.m_ry * y + m_pia.m_rz * z + m_pia.m_rxx * x * x + m_pia.m_rxy * x * y + m_pia.m_rxz * x * z + m_pia.m_ryy * y * y + m_pia.m_ryz * y * z + m_pia.m_rzz * z * z; ipt.x = m_pia.m_c0 + m_pia.m_cx * x + m_pia.m_cy * y + m_pia.m_cz * z + m_pia.m_cxx * x * x + m_pia.m_cxy * x * y + m_pia.m_cxz * x * z + m_pia.m_cyy * y * y + m_pia.m_cyz * y * z + m_pia.m_czz * z * z; } double ossimRsmModel::polynomial( const double& x, const double& y, const double& z, const ossim_uint32& maxx, const ossim_uint32& maxy, const ossim_uint32& maxz, std::vector pcf) const { double r = 0.0; ossim_uint32 index = 0; for (ossim_uint32 k = 0; k <= maxz; ++k) { for (ossim_uint32 j = 0; j <= maxy; ++j) { for (ossim_uint32 i = 0; i <= maxx; ++i) { r+=pcf[index]*std::pow(x,(double)i)*std::pow(y,(double)j)*std::pow(z,(double)k); ++index; } } } return r; } double ossimRsmModel::dPoly_dLat( const double& x, const double& y, const double& z, const ossim_uint32& maxx, const ossim_uint32& maxy, const ossim_uint32& maxz, std::vector pcf) const { double dr = 0.0; ossim_uint32 index = 0; for (ossim_uint32 k = 0; k <= maxz; ++k) { for (ossim_uint32 j = 0; j <= maxy; ++j) { for (ossim_uint32 i = 0; i <= maxx; ++i) { if (j>0) { dr+=j*pcf[index]*std::pow(x,(double)i)*std::pow(y,(double)(j-1))*std::pow(z,(double)k); } ++index; } } } return dr; } double ossimRsmModel::dPoly_dLon( const double& x, const double& y, const double& z, const ossim_uint32& maxx, const ossim_uint32& maxy, const ossim_uint32& maxz, std::vector pcf) const { double dr = 0.0; ossim_uint32 index = 0; for (ossim_uint32 k = 0; k <= maxz; ++k) { for (ossim_uint32 j = 0; j <= maxy; ++j) { for (ossim_uint32 i = 0; i <= maxx; ++i) { if (i>0) { dr += i*pcf[index]*std::pow(x,(double)(i-1)) * std::pow(y,(double)j)*std::pow(z,(double)k); } ++index; } } } return dr; } double ossimRsmModel::dPoly_dHgt( const double& x, const double& y, const double& z, const ossim_uint32& maxx, const ossim_uint32& maxy, const ossim_uint32& maxz, std::vector pcf) const { double dr = 0.0; ossim_uint32 index = 0; for (ossim_uint32 k = 0; k <= maxz; ++k) { for (ossim_uint32 j = 0; j <= maxy; ++j) { for (ossim_uint32 i = 0; i <= maxx; ++i) { if (k>0) { dr += k*pcf[index]*std::pow(x,(double)i) * std::pow(y,(double)j)*std::pow(z,(double)(k-1)); } ++index; } } } return dr; } bool ossimRsmModel::validate() const { static const char MODULE[] = "ossimRsmModel::validate"; bool status = true; if ( (m_pia.m_rnis == 0) || (m_pia.m_rnis == 0) || (m_pia.m_tnis == 0) ) { status = false; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR: rsmpia must have at least one section!" << std::endl; } if ( m_pca.size() != m_pia.m_tnis ) { status = false; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR: rsmpca array not equal to section count!" << std::endl; } if ( ( m_ida.m_grndd != 'G' ) && ( m_ida.m_grndd != 'H' ) && ( m_ida.m_grndd != 'R' ) ) { status = false; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR: rsmida grndd Ground Domain Form not set!" << std::endl; } if ( m_ida.m_grndd == 'R' ) { status = false; ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR: rsmida grndd Rectangular Ground Domain not supported!" << std::endl; } if ( m_pia.m_rssiz == 0 ) { status = false; // divide by zero. ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR: rsmpia rrsiz Section row size cannot be zero!" << std::endl; } if ( m_pia.m_cssiz == 0 ) { status = false; // divide by zero. ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR: rsmpia cssiz Section column size cannot be zero!" << std::endl; } return status; } ossim-Miami-2.9.1/src/projection/ossimSarModel.cpp000066400000000000000000001256271352751253100221600ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Base class for Synthetic Aperture Radar model. // // This model represents a standard model using relatively // generic support data based on the following references: // [1] Modern Photogrammetry; Mikhail, Bethel, & McGlone; // Sections 11.7-11.9. Equation number references are // provided where possible for added clarity. // [2] The Compendium of Controlled Extensions for NITFS // 21 Mar 2006, paragraph E.3.8, SAR MPDSR // //---------------------------------------------------------------------------- // $Id: ossimSarModel.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimSarModel, "ossimSarModel", ossimSensorModel); static ossimTrace traceExec (ossimString("ossimSarModel:exec")); static ossimTrace traceDebug(ossimString("ossimSarModel:debug")); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimSarModel.cpp 17206 2010-04-25 23:20:40Z dburken $"; #endif static const char ACQ_MODE_KW[] = "acq_mode"; static const char ORP_POS_KW[] = "orp_pos"; static const char ORP_CENTER_KW[] = "orp_ctr_xy"; static const char OPNORM_KW[] = "opnorm"; static const char OP_X_AXIS_KW[] = "opx"; static const char OIPR_KW[] = "oipr"; static const char PIX_SIZE_KW[] = "pixel_size"; static const char ARP_TIME_KW[] = "arptm"; static const char ARP_POLY_COEFF_X_KW[] = "arppol_coeff_x"; static const char ARP_POLY_COEFF_Y_KW[] = "arppol_coeff_y"; static const char ARP_POLY_COEFF_Z_KW[] = "arppol_coeff_z"; static const char TIME_COEFF[] = "time_coeff"; static const ossimString PARAM_NAMES[] ={"x_pos_offset", "y_pos_offset", "z_pos_offset"}; static const ossimString PARAM_UNITS[] ={"meters", "meters", "meters"}; //***************************************************************************** // METHOD: ossimSarModel::ossimSarModel() // // Constructor. // //***************************************************************************** ossimSarModel::ossimSarModel() : theAcquisitionMode(), theOrpPosition(), theOrpCenter(), theOutputPlaneNormal(), theOipr(0.0), theLsrOffset(0, 0, 0) { initAdjustableParameters(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSarModel::ossimSarModel DEBUG:" << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } } //***************************************************************************** // DESTRUCTOR: ~ossimSarModel() // //***************************************************************************** ossimSarModel::~ossimSarModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG DESTRUCTOR: ~ossimSarModel(): entering..." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG DESTRUCTOR: ~ossimSarModel(): returning..." << std::endl; } //***************************************************************************** // METHOD: ossimSarModel::initAdjustableParameters() // // This method initializes the base class adjustable parameter and associated // sigmas arrays with quantities specific to this model. These are default // values only. A functional implementation would assign the sigmas via a // keywordlist or camera specific derived class. // //***************************************************************************** void ossimSarModel::initAdjustableParameters() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSarModel::initAdjustableParameters: entering..." << std::endl; int numParams = NUM_ADJUSTABLE_PARAMS; resizeAdjustableParameterArray(NUM_ADJUSTABLE_PARAMS); //*** // Initialize adjustable parameter array: //*** for (int i=0; i\n" << ORP_POS_KW << ": \n" << ORP_CENTER_KW << ": \n" << OPNORM_KW << ": \n" << OP_X_AXIS_KW << ": \n" << OIPR_KW << ": \n" << PIX_SIZE_KW << ": \n" << ARP_TIME_KW << ": \n" << ARP_POLY_COEFF_X_KW << ": \n" << ARP_POLY_COEFF_Y_KW << ": \n" << ARP_POLY_COEFF_Z_KW << ": \n" << TIME_COEFF << ": \n"; } //***************************************************************************** // METHOD: ossimSarModel::print() // // Print the KWL. // //***************************************************************************** std::ostream& ossimSarModel::print(std::ostream& out) const { out << "// ossimSarModel::print:" << std::endl; ossimKeywordlist kwl; if (saveState(kwl)) { kwl.print(out); } else { out << "// ossimSarModel::saveState failed!" << std::endl; } return ossimSensorModel::print(out); } //***************************************************************************** // METHOD: ossimSarModel::getAcquisitionMode() // // Get internal acquisition mode parameter. // //***************************************************************************** ossimString ossimSarModel::getAcquistionModeString() const { ossimString result; switch (theAcquisitionMode) { case ossimSarModel::SCAN: result = "scan"; break; case ossimSarModel::SPOT: result = "spot"; break; case ossimSarModel::UNKNOWN: default: result = "unknown"; break; } return result; } //***************************************************************************** // METHOD: ossimSarModel::lineSampleHeightToWorld() // // Perform inverse projection of image space to ground point @ specified hgt. // // Note: Special case indicated by 'heightAboveEllipsoid=OSSIM_NAN' // will utilize the ORP height for intersection. // //***************************************************************************** void ossimSarModel::lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& heightAboveEllipsoid, ossimGpt& worldPt) const { // Compute OP position from image coordinates ossimEcefPoint opPt; computeOPfromImage(lineSampPt, opPt); // Get image time ossim_float64 iTime = getArpTime(lineSampPt); // Get ARP state ossimEcefPoint arpPos = getArpPos(iTime); ossimEcefVector arpVel = getArpVel(iTime); // Get range/Doppler ossim_float64 range; ossim_float64 doppler; computeRangeDoppler(opPt, arpPos, arpVel, range, doppler); // Set the height reference ossim_float64 hgtSet; if ( ossim::isnan(heightAboveEllipsoid) ) { ossimGpt orpG(theOrpPosition); hgtSet = orpG.height(); } else { hgtSet = heightAboveEllipsoid; } ossimHgtRef hgtRef(AT_HGT, hgtSet); // Project OP to DEM ossimEcefPoint ellPt; projOPtoSurface(opPt, range, doppler, arpPos, arpVel, &hgtRef, ellPt); ossimGpt iPt(ellPt); worldPt = iPt; } //***************************************************************************** // METHOD: ossimSarModel::worldToLineSample() // // Perform forward projection of ground point to image space. // //***************************************************************************** void ossimSarModel::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { ossimEcefPoint pt(world_point); // Project to OP plane ossimEcefPoint opPt; projEllipsoidToOP(pt, opPt); // Compute image coordinates from OP position computeImageFromOP(opPt,image_point); } //***************************************************************************** // METHOD: ossimSarModel::lineSampleToWorld() // // Perform inverse projection of image space to ground point. // //***************************************************************************** void ossimSarModel::lineSampleToWorld(const ossimDpt& lineSampPt, ossimGpt& worldPt) const { // Compute OP position from image coordinates ossimEcefPoint opPt; computeOPfromImage(lineSampPt, opPt); // Get image time ossim_float64 iTime = getArpTime(lineSampPt); // Get ARP state vector ossimEcefPoint arpPos = getArpPos(iTime); ossimEcefVector arpVel = getArpVel(iTime); // Get range/Doppler ossim_float64 range; ossim_float64 doppler; computeRangeDoppler(opPt, arpPos, arpVel, range, doppler); // Set the height reference ossimHgtRef hgtRef(AT_DEM); // Project OP to DEM ossimEcefPoint ellPt; projOPtoSurface(opPt, range, doppler, arpPos, arpVel, &hgtRef, ellPt); ossimGpt iPt(ellPt); worldPt = iPt; } //***************************************************************************** // METHOD: ossimSarModel::imagingRay() // // Given an image point, returns a ray originating at the ARP position // and pointing towards the target's position in the Output // Plane. // This DOES NOT provide the conventional definition for an imaging ray // because the imaging locus for SAR is not a ray. // // It DOES provide a radius vector for the range/Doppler circle. // //***************************************************************************** void ossimSarModel::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { // Compute OP position from image coordinates ossimEcefPoint opPt; computeOPfromImage(image_point, opPt); // Get image time ossim_float64 iTime = getArpTime(image_point); // Get ARP position ossimEcefPoint arpPos = getArpPos(iTime); // Construct the ray ossimGpt start(arpPos); ossimGpt end(opPt); image_ray = ossimEcefRay(start, end); return; } //***************************************************************************** // METHOD: ossimSarModel::getObsCovMat() // // Gives 2X2 covariance matrix of observations. // // Note: At this base class level, the only error source currently // considered is mensuration error. This is obviously optimistic, // but is included as a placeholder/example. // //***************************************************************************** ossimSensorModel::CovMatStatus ossimSarModel::getObsCovMat( const ossimDpt& /* ipos */, NEWMAT::SymmetricMatrix& Cov) { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Mensuration error contribution // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Sensitivity matrix NEWMAT::SymmetricMatrix B(2); B(1,1) = thePixelSpacing; B(2,2) = B(1,1); B(1,2) = 0.0; // Default pointing error = 0.5 pixels ossim_float64 defPointingSigma = 0.5; NEWMAT::SymmetricMatrix P(2); P(1,1) = defPointingSigma*defPointingSigma; P(2,2) = P(1,1); P(1,2) = 0.0; // Propagate to rng/az NEWMAT::SymmetricMatrix Cm; Cm << B * P * B.t(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Sum total covariance in rng/az // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NEWMAT::SymmetricMatrix Ctot = Cm; //+ other contributors as identified // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Propagate to rng/Dop // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NEWMAT::SymmetricMatrix Bad(2); Bad(1,1) = 1.0; Bad(2,2) = theParDopWRTaz; Bad(1,2) = 0.0; Cov << Bad * Ctot * Bad.t(); return ossimSensorModel::COV_PARTIAL; } //***************************************************************************** // METHOD: ossimSarModel::updateModel() // // Update computed parameters. // //***************************************************************************** void ossimSarModel::updateModel() { // Set the pixel size thePixelSpacing = thePixelSize; // Define the output(focus) plane // Ref[1], eq. 11-29 -> 11-31 theOPZ = theOutputPlaneNormal.unitVector(); theOPX = theOutputPlaneXaxis.unitVector(); theOPY = theOPZ.cross(theOPX); theOPY.normalize(); theOPX = theOPY.cross(theOPZ); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG updateModel:\n OP vectors..."; ossimNotify(ossimNotifyLevel_DEBUG) << "\n OPX: "<=0; i--) x = x*time + theArpXPolCoeff[i]; ossim_float64 y = theArpYPolCoeff[nTermsY-1]; for (i=nTermsY-2; i>=0; i--) y = y*time + theArpYPolCoeff[i]; ossim_float64 z = theArpZPolCoeff[nTermsZ-1]; for (i=nTermsZ-2; i>=0; i--) z = z*time + theArpZPolCoeff[i]; ossimEcefPoint pos(x, y, z); // Handle the adjustable offset // Define ENU space at pos ossimGpt posG(pos); ossimLsrSpace enu(posG); // Rotate offset vector to ECF ossimColumnVector3d tpnn(theLsrOffset[0],theLsrOffset[1], theLsrOffset[2]); ossimEcefVector ecfOffset = enu.lsrToEcefRotMatrix()*tpnn; // Add the offset pos = pos + ecfOffset; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG getArpPos:"< 11-35 // //***************************************************************************** bool ossimSarModel::computeOPfromImage(const ossimDpt& imgPt, ossimEcefPoint& opPt) const { ossim_float64 dL = imgPt.line - theOrpCenter.line; ossim_float64 dS = imgPt.samp - theOrpCenter.samp; dL *= thePixelSpacing; dS *= thePixelSpacing; opPt = theOPX*dL + theOPY*dS + theOrpPosition; return true; } //***************************************************************************** // METHOD: ossimSarModel::computeImageFromOP() // // Compute image coordinates from Output Plane coordinates. // Ref[1], eq. 11-32 -> 11-35 // //***************************************************************************** bool ossimSarModel::computeImageFromOP(const ossimEcefPoint& opPt, ossimDpt& imgPt) const { ossimEcefVector delta(opPt - theOrpPosition); ossim_float64 dL = delta.dot(theOPX) / thePixelSpacing; ossim_float64 dS = delta.dot(theOPY) / thePixelSpacing; imgPt.line = theOrpCenter.line + dL; imgPt.samp = theOrpCenter.samp + dS; return true; } //***************************************************************************** // METHOD: ossimSarModel::projOPtoSurface() // // Project Output Plane coordinates to ellipsoid at reference height. // //***************************************************************************** bool ossimSarModel::projOPtoSurface(const ossimEcefPoint& opPt, const ossim_float64& range, const ossim_float64& doppler, const ossimEcefPoint& arpPos, const ossimEcefVector& arpVel, const ossimHgtRef* hgtRef, ossimEcefPoint& ellPt) const { // Set slopes for tangent plane ossim_float64 sx = 0.0; ossim_float64 sy = 0.0; // Set tangent plane normal vector in ENU ossimColumnVector3d tpn(sx, sy, 1.0); ossimColumnVector3d tpnn(-sx, -sy, 1.0); // Initialize at OP point ossimEcefPoint rg(opPt); // Matrices NEWMAT::SymmetricMatrix BtB(3); NEWMAT::ColumnVector BtF(3); NEWMAT::ColumnVector F(3); NEWMAT::ColumnVector dR(3); // Initialize criteria F(1)=theOipr; ossim_int32 iter = 0; while ((F(1)>=theOipr || F(2)>=0.0003048 || F(3)>=0.5) && iter<5) { // Compute current latitude/longitude estimate ossimGpt pg(rg); // Set reference point @ desired elevation ossim_float64 atHgt = hgtRef->getRefHeight(pg); pg.height(atHgt); ossimEcefPoint rt(pg); // Define ENU space at reference point ossimLsrSpace enu(pg); // Rotate normal vector to ECF ossimEcefVector st = enu.lsrToEcefRotMatrix()*tpn; // Compute current range & Doppler estimate ossim_float64 rngComp; ossim_float64 dopComp; computeRangeDoppler(rg, arpPos, arpVel, rngComp, dopComp); // Compute current height estimate ossim_float64 diffHgt = st.dot(rg-rt); // Compute current fr, fd, ft F(1) = rngComp - range; F(2) = dopComp - doppler; F(3) = diffHgt; // Compute fr partials ossimEcefVector delta = rg - arpPos; ossimEcefVector deltaUv = delta.unitVector(); ossimEcefVector p_fr = -deltaUv; // Compute fd partials ossim_float64 vDotr = arpVel.dot(deltaUv); ossimEcefVector p_fd = (arpVel - deltaUv*vDotr)/rngComp; // Compute ft partials ossimColumnVector3d p_ft = enu.lsrToEcefRotMatrix()*tpnn; // Form B-matrix NEWMAT::Matrix B = ossimMatrix3x3::create(p_fr[0], p_fr[1], p_fr[2], p_fd[0], p_fd[1], p_fd[2], p_ft[0], p_ft[1], p_ft[2]); // Form coefficient matrix & discrepancy vector BtF << B.t()*F; BtB << B.t()*B; // Solve system dR = solveLeastSquares(BtB, BtF); // Update estimate for (ossim_int32 k=0; k<3; k++) rg[k] -= dR(k+1); iter++; } // Set intersection for return ellPt = rg; return true; } //***************************************************************************** // METHOD: ossimSarModel::projEllipsoidToOP() // // Projects ellipsoid coordinates to Output Plane. // //***************************************************************************** bool ossimSarModel::projEllipsoidToOP(const ossimEcefPoint& ellPt, ossimEcefPoint& opPt) const { ossimDpt currentImagePt; ossimEcefPoint selPt; // Initialize at ORP image point currentImagePt = theOrpCenter; ossim_float64 checkTime = 1.0; ossim_float64 lTime=10000.0; ossim_int32 iter = 0; // Iterate on imaging time while (checkTime > 10.0e-6 && iter<5) { // Get current time estimate ossim_float64 cTime = getArpTime(currentImagePt); checkTime = fabs(cTime-lTime)/cTime; // Get state vector at current time estimate ossimEcefPoint arpPos = getArpPos(cTime); ossimEcefVector arpVel = getArpVel(cTime); ossimEcefVector arpVelunit = arpVel.unitVector(); // Define planes ossim_float64 constOP = theOPZ.dot( ossimEcefVector(theOrpPosition[0],theOrpPosition[1],theOrpPosition[2])); ossim_float64 constRD = arpVelunit.dot( ossimEcefVector(ellPt[0],ellPt[1],ellPt[2])); // Compute dot product of normals ossim_float64 ndot = theOPZ.dot(arpVelunit); // Compute line of intersection of OP and RD planes ossim_float64 det = 1.0 - ndot*ndot; ossim_float64 c1 = (constOP - ndot*constRD) / det; ossim_float64 c2 = (constRD - ndot*constOP) / det; ossimEcefPoint ori = (theOPZ*c1+arpVelunit*c2)+ossimEcefPoint(0.0,0.0,0.0); ossimEcefVector dir = theOPZ.cross(arpVelunit); // Solve for intersection points (RD circle and OP) ossimEcefVector delta = ori - arpPos; ossim_float64 a2 = dir.length()*dir.length(); ossim_float64 a1 = delta.dot(dir); ossimEcefVector rng(ellPt-arpPos); ossim_float64 a0 = delta.length()*delta.length()-rng.length()*rng.length(); ossim_float64 rootSqr = a1*a1-a0*a2; ossim_float64 root = sqrt(rootSqr); ossimEcefPoint p1 = ori - dir*((a1+root)/a2); ossimEcefPoint p2 = ori - dir*((a1-root)/a2); ossimEcefVector p1Delta = p1 - ellPt; ossimEcefVector p2Delta = p2 - ellPt; // Pick correct point if (p1Delta.magnitude()= 0 call base class version // for "adjustable parameters" if (derivMode >= 0) { return ossimSensorModel::getForwardDeriv(derivMode, pos, h); } // Use alternative derivMode definitions else { ossimDpt returnData; //****************************************** // OBS_INIT mode // [1] compute r/D corresponding to (s,l) // [2] compute time, ARP posvel and save // Note: In this mode, pos is used to pass // in the (s,l) observations. //****************************************** if (derivMode==OBS_INIT) { // Compute the r/D observations from image coordinates ossimDpt obs; obs.samp = pos.latd(); obs.line = pos.lond(); theObsTime = getArpTime(obs); theObsArpPos = getArpPos(theObsTime); theObsArpVel = getArpVel(theObsTime); theObsArpVel_U = theObsArpVel.unitVector(); theObsArpVel_Mag = theObsArpVel.magnitude(); computeOPfromImage(obs, theObsOP); computeRangeDoppler (theObsOP, theObsArpPos, theObsArpVel, theObsRng, theObsDop); ossimDpt obsRD(theObsRng, theObsDop); theObs = obsRD; } //****************************************** // EVALUATE mode // [1] evaluate & save partials, residuals // [2] return residuals //****************************************** else if (derivMode==EVALUATE) { // Compute the partials ossimEcefPoint gpos(pos); ossimEcefPoint ellObs = gpos; theObsPosition = gpos; // Partials of range WRT ground ossimEcefVector rng = ellObs - theObsArpPos; ossimEcefVector rngU = rng.unitVector(); // Partials of azimuth WRT ground ossimEcefVector slantPerp = rngU.cross(theObsArpVel); ossimEcefVector rs(theObsArpPos[0],theObsArpPos[1],theObsArpPos[2]); ossim_float64 signPar = (slantPerp.dot(rs)<0.0) ? -1:1; ossimEcefVector slantNormal = slantPerp.unitVector() * signPar; ossimEcefVector azU = slantNormal.unitVector().cross(rngU); // Partials of Doppler WRT azimuth ossim_float64 dca = acos(theObsArpVel_U.dot(rngU)); signPar = ((theObsArpVel.cross(rng)).dot(slantNormal)<0.0) ? 1:-1; theParDopWRTaz = signPar*sin(dca)*theObsArpVel_Mag/rng.magnitude(); // Save the partials // Range theParWRTx.u = rngU.x(); theParWRTy.u = rngU.y(); theParWRTz.u = rngU.z(); // Doppler theParWRTx.v = azU.x()*theParDopWRTaz; theParWRTy.v = azU.y()*theParDopWRTaz; theParWRTz.v = azU.z()*theParDopWRTaz; // Residuals ossim_float64 cRng; ossim_float64 cDop; ossimEcefPoint opPt; projEllipsoidToOP(ellObs, opPt); computeRangeDoppler(opPt, theObsArpPos, theObsArpVel, cRng, cDop); ossimDpt resid(theObsRng-cRng, theObsDop-cDop); returnData = resid; } //****************************************** // P_WRT_X, P_WRT_Y, P_WRT_Z modes // [1] 3 separate calls required // [2] return 3 sets of partials //****************************************** else if (derivMode==P_WRT_X) { returnData = theParWRTx; } else if (derivMode==P_WRT_Y) { returnData = theParWRTy; } else { returnData = theParWRTz; } return returnData; } } //***************************************************************************** // METHOD: ossimSarModel::setAcquisitionMode() // // Set internal acquisition mode parameter. // //***************************************************************************** void ossimSarModel::setAcquisitionMode(const ossimString& mode) { ossimString os = mode; os.downcase(); if (os == "scan") { theAcquisitionMode = ossimSarModel::SCAN; } else if (os == "spot") { theAcquisitionMode = ossimSarModel::SPOT; } else { theAcquisitionMode = ossimSarModel::UNKNOWN; } } double ossimSarModel::sensorAzimuth(const ossimDpt& image_point) const { ossimGpt ground; lineSampleToWorld(image_point, ground); // Get image time ossim_float64 iTime = getArpTime(image_point); // Get ARP position ossimEcefPoint arpPos = getArpPos(iTime); ossimGpt sensor(arpPos); return ground.azimuthTo(sensor); } ossim-Miami-2.9.1/src/projection/ossimSensorModel.cpp000066400000000000000000001543261352751253100227020ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimSensorModel.cc // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // AUTHOR: Oscar Kramer // // DESCRIPTION: // Contains implementation of class ossimSensorModel. This is the base // class to all sensor model-related projections including replacement // models such as coarse grids and polynomial models. This base class // supports adjustable parameters for registration adjustment. // // Important note to sensor model implementors: In order to avoid a separate // set of "initial adjustable parameters," this design assumes ALL initial // values are 0. When designing the derived-class model, insure that the // adjustable parameters are 0-based. This applies to the adjustable param // array declared in this base class only. The derived classes can declare // their own adjstable params that are more descriptive and that can be // assigned an initial value thet is non-zero, but that are linearly related // to the adjustable params of this class. In that case, the updateModel() // method will compute the derived-class's parameters based on // theAdjustableParams array, after an adjustment is made. // // LIMITATIONS: None. // //***************************************************************************** // $Id: ossimSensorModel.cpp 23564 2015-10-02 14:12:25Z dburken $ #include #include using namespace std; // #include #include RTTI_DEF3(ossimSensorModel, "ossimSensorModel", ossimProjection, ossimOptimizableProjection, ossimAdjustableParameterInterface); #include #include #include #include #include #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimSensorModel:exec"); static ossimTrace traceDebug ("ossimSensorModel:debug"); static const char* REF_GPT_LAT_KW = "ref_point_lat"; static const char* REF_GPT_LON_KW = "ref_point_lon"; static const char* REF_GPT_HGT_KW = "ref_point_hgt"; static const char* REF_IPT_LINE_KW = "ref_point_line"; static const char* REF_IPT_SAMP_KW = "ref_point_samp"; static const char* IMAGE_ID_KW = "image_id"; static const char* SENSOR_ID_KW = "sensor"; static const ossimString NULL_STRING = "NULL"; static const double RAY_ORIGIN_HEIGHT = 10000.0; //meters //DEBUG TBR : output ops std::ostream& operator<<(std::ostream& os, NEWMAT::GeneralMatrix& mat) { int nr=mat.Nrows(); int nc=mat.Ncols(); NEWMAT::MatrixRow crow(&mat,NEWMAT::LoadOnEntry); // NEWMAT::MatrixRowCol crow; mat.RestoreRow(crow); for (int r=0;rloadState(geom_kwl); loadState(geom_kwl); if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::ossimSensorModel(geom_kwl): returning..." << std::endl; } } const ossimSensorModel& ossimSensorModel::operator=( const ossimSensorModel& rhs ) { if (this != &rhs) { // ossimProjection base has no data members. ossimOptimizableProjection::operator=(rhs); ossimAdjustableParameterInterface::operator=(rhs); theImageSize = rhs.theImageSize; theSubImageOffset = rhs.theSubImageOffset; theImageID = rhs.theImageID; theSensorID = rhs.theSensorID; theGSD = rhs.theGSD; theMeanGSD = rhs.theMeanGSD; theRefGndPt = rhs.theRefGndPt; theRefImgPt = rhs.theRefImgPt; theBoundGndPolygon = rhs.theBoundGndPolygon; theImageClipRect = rhs.theImageClipRect; theRelPosError = rhs.theRelPosError; theNominalPosError = rhs.theNominalPosError; theParWRTx = rhs.theParWRTx; theParWRTy = rhs.theParWRTy; theParWRTz = rhs.theParWRTz; theObs = rhs.theObs; theResid = rhs.theResid; theExtrapolateImageFlag = rhs.theExtrapolateImageFlag; theExtrapolateGroundFlag = rhs.theExtrapolateGroundFlag; } return *this; } //***************************************************************************** // DESTRUCTOR: ~ossimSensorModel // //***************************************************************************** ossimSensorModel::~ossimSensorModel() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::~ossimSensorModel: entering..." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::~ossimSensorModel: returning..." << std::endl; } ossimObject* ossimSensorModel::getBaseObject() { return this; } const ossimObject* ossimSensorModel::getBaseObject()const { return this; } //***************************************************************************** // METHOD: ossimSensorModel::lineSampleToWorld(image_pt, &gpt) // // Intersects the ray associated with image_pt with the available elevation // model. Returns ground point // //***************************************************************************** void ossimSensorModel::lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const { bool debug = false; // setable via interactive debugger if (traceExec() || debug) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::lineSampleToWorld:entering..." << std::endl; if(image_point.hasNans()) { gpt.makeNan(); return; } //*** // Extrapolate if image point is outside image: //*** if (!insideImage(image_point)&&(!theExtrapolateImageFlag)) { gpt = extrapolate(image_point); return; } //*** // Determine imaging ray and invoke elevation source object's services to // intersect ray with terrain model: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimElevManager::instance()->intersectRay(ray, gpt); if (traceDebug() || debug) { ossimNotify(ossimNotifyLevel_DEBUG) << "image_point = " << image_point << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "ray = " << ray << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "gpt = " << gpt << std::endl; } if (traceExec() || debug) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::lineSampleToWorld: returning..." << std::endl; return; } //***************************************************************************** // METHOD: ossimSensorModel::worldToLineSample() // // Performs forward projection of ground point to image space. // //***************************************************************************** void ossimSensorModel::worldToLineSample(const ossimGpt& worldPoint, ossimDpt& ip) const { // static bool recursionFlag = false; static const double PIXEL_THRESHOLD = .1; // acceptable pixel error static const int MAX_NUM_ITERATIONS = 20; if(worldPoint.isLatNan() || worldPoint.isLonNan()) { ip.makeNan(); return; } //*** // First check if the world point is inside bounding rectangle: //*** int iters = 0; ossimDpt wdp (worldPoint); // if ((!recursionFlag)&&!(theBoundGndPolygon.pointWithin(wdp))) if((theBoundGndPolygon.getNumberOfVertices() > 0)&& (!theBoundGndPolygon.hasNans())) { if (!(theBoundGndPolygon.pointWithin(wdp))) { if(theSeedFunction.valid()) { theSeedFunction->worldToLineSample(worldPoint, ip); } else if(!theExtrapolateGroundFlag) // if I am not already in the extrapolation routine { // recursionFlag = true; ip = extrapolate(worldPoint); // recursionFlag = false; } return; } } //*** // Substitute zero for null elevation if present: //*** double height = worldPoint.hgt; if ( ossim::isnan(height) ) { height = 0.0; } // // Utilize iterative scheme for arriving at image point. Begin with guess // at image center: // if(theSeedFunction.valid()) { theSeedFunction->worldToLineSample(worldPoint, ip); } else { ip.u = theRefImgPt.u; ip.v = theRefImgPt.v; } ossimDpt ip_du; ossimDpt ip_dv; ossimGpt gp, gp_du, gp_dv; double dlat_du, dlat_dv, dlon_du, dlon_dv; double delta_lat, delta_lon, delta_u, delta_v; double inverse_norm; bool done = false; //*** // Begin iterations: //*** do { //*** // establish perturbed image points about the guessed point: //*** ip_du.u = ip.u + 1.0; ip_du.v = ip.v; ip_dv.u = ip.u; ip_dv.v = ip.v + 1.0; //*** // Compute numerical partials at current guessed point: //*** lineSampleHeightToWorld(ip, height, gp); lineSampleHeightToWorld(ip_du, height, gp_du); lineSampleHeightToWorld(ip_dv, height, gp_dv); if(gp.isLatNan() || gp.isLonNan()) { gp = extrapolate(ip); } if(gp_du.isLatNan() || gp_du.isLonNan()) { gp_du = extrapolate(ip_du); } if(gp_dv.isLatNan() | gp_dv.isLonNan()) { gp_dv = extrapolate(ip_dv); } dlat_du = gp_du.lat - gp.lat; //e dlon_du = gp_du.lon - gp.lon; //g dlat_dv = gp_dv.lat - gp.lat; //f dlon_dv = gp_dv.lon - gp.lon; //h // // Test for convergence: // delta_lat = worldPoint.lat - gp.lat; delta_lon = worldPoint.lon - gp.lon; // // Compute linearized estimate of image point given gp delta: // inverse_norm = dlat_dv*dlon_du - dlat_du*dlon_dv; // fg-eh if (!ossim::almostEqual(inverse_norm, 0.0, DBL_EPSILON)) { delta_u = (-dlon_dv*delta_lat + dlat_dv*delta_lon)/inverse_norm; delta_v = ( dlon_du*delta_lat - dlat_du*delta_lon)/inverse_norm; ip.u += delta_u; ip.v += delta_v; } else { delta_u = 0; delta_v = 0; } done = ((fabs(delta_u) < PIXEL_THRESHOLD)&& (fabs(delta_v) < PIXEL_THRESHOLD)); iters++; } while ((!done) && (iters < MAX_NUM_ITERATIONS)); // } while (((fabs(delta_u) > PIXEL_THRESHOLD) || // (fabs(delta_v) > PIXEL_THRESHOLD)) && // (iters < MAX_NUM_ITERATIONS)); #if 0 /* Please leave for debug. */ //--- // Note that this error mesage appears only if max count was reached while // iterating. A linear (no iteration) solution would finish with iters = // MAX_NUM_ITERATIONS + 1: //--- if (iters >= MAX_NUM_ITERATIONS) { std::cout << "MAX ITERATION!!!" << std::endl; std::cout << "delta_u = " << delta_u << "\ndelta_v = " << delta_v << "\n"; } else { std::cout << "ITERS === " << iters << std::endl; } std::cout << "iters = " << iters << "\n"; #endif //*** // The image point computed this way corresponds to full image space. // Apply image offset in the case this is a sub-image rectangle: //*** ip -= theSubImageOffset; } //***************************************************************************** // METHOD: ossimSensorModel::print(ostream) // // Dumps contents of object to ostream. // //***************************************************************************** std::ostream& ossimSensorModel::print(std::ostream& out) const { out << setprecision(15) << setiosflags(ios::fixed) << "\n ossimSensorModel base-class data members:\n" << "\n theImageID: " << theImageID << "\n theSensorID: " << theSensorID << "\n theImageSize: " << theImageSize << "\n theSubImageOffset: " << theSubImageOffset << "\n theGSD: " << theGSD << "\n theMeanGSD: " << theMeanGSD << "\n theRefGndPt: " << theRefGndPt << "\n theRefImgPt: " << theRefImgPt << "\n theBoundGndPolygon: \n" << theBoundGndPolygon << "\n theImageClipRect: " << theImageClipRect << "\n theNominalPosError: " << theNominalPosError << "\n theRelPosError: " << theRelPosError << endl; //--- // Note: // need ossimAdjustableParameterInterface::print(os); //--- return ossimProjection::print(out); } void ossimSensorModel::setRefImgPt(const ossimDpt& pt) { theRefImgPt = pt; } void ossimSensorModel::setRefGndPt(const ossimGpt& pt) { theRefGndPt = pt; } void ossimSensorModel::setImageRect(const ossimDrect& imageRect) { theImageClipRect = imageRect; theRefImgPt = imageRect.midPoint(); theImageSize = imageRect.size(); } void ossimSensorModel::setGroundRect(const ossimGpt& ul, const ossimGpt& ur, const ossimGpt& lr, const ossimGpt& ll) { theBoundGndPolygon.clear(); theBoundGndPolygon.addPoint(ul); theBoundGndPolygon.addPoint(ur); theBoundGndPolygon.addPoint(lr); theBoundGndPolygon.addPoint(ll); } //***************************************************************************** // METHOD: ossimSensorModel::saveState() // // Saves the state of this object to KWL. // //***************************************************************************** bool ossimSensorModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::saveState: entering..." << std::endl; kwl.add(prefix, IMAGE_ID_KW, theImageID.chars()); kwl.add(prefix, SENSOR_ID_KW, theSensorID.chars()); kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, theImageSize.line, true); kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, theImageSize.samp, true); kwl.add(prefix, REF_GPT_LAT_KW, theRefGndPt.lat, true); kwl.add(prefix, REF_GPT_LON_KW, theRefGndPt.lon, true); kwl.add(prefix, REF_GPT_HGT_KW, theRefGndPt.hgt, true); kwl.add(prefix, REF_IPT_LINE_KW, theRefImgPt.line, true); kwl.add(prefix, REF_IPT_SAMP_KW, theRefImgPt.samp, true); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW, theGSD.line, true); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_X_KW, theGSD.samp, true); ossimDpt corner; if(!theBoundGndPolygon.vertex(0, corner)) { corner = ossimDpt(0,0); } kwl.add(prefix, ossimKeywordNames::UL_LAT_KW, corner.lat, true); kwl.add(prefix, ossimKeywordNames::UL_LON_KW, corner.lon, true); if(!theBoundGndPolygon.nextVertex(corner)) { corner = ossimDpt(0,0); } kwl.add(prefix, ossimKeywordNames::UR_LAT_KW, corner.lat, true); kwl.add(prefix, ossimKeywordNames::UR_LON_KW, corner.lon, true); if(!theBoundGndPolygon.nextVertex(corner)) { corner = ossimDpt(0,0); } kwl.add(prefix, ossimKeywordNames::LR_LAT_KW, corner.lat, true); kwl.add(prefix, ossimKeywordNames::LR_LON_KW, corner.lon, true); if(!theBoundGndPolygon.nextVertex(corner)) { corner = ossimDpt(0,0); } kwl.add(prefix, ossimKeywordNames::LL_LAT_KW, corner.lat, true); kwl.add(prefix, ossimKeywordNames::LL_LON_KW, corner.lon, true); kwl.add(prefix, ossimKeywordNames::CE90_ABSOLUTE_KW, theNominalPosError, true, 20); kwl.add(prefix, ossimKeywordNames::CE90_RELATIVE_KW, theRelPosError, true, 20); kwl.add(prefix, "rect", ossimString::toString(theImageClipRect.ul().x) + " " + ossimString::toString(theImageClipRect.ul().y) + " " + ossimString::toString(theImageClipRect.lr().x) + " " + ossimString::toString(theImageClipRect.lr().y), true); if ( theSeedFunction.valid() ) { ossimString seedPrefix = prefix; seedPrefix += "seed_projection."; theSeedFunction->saveState(kwl, seedPrefix.c_str()); } // Avoid passing null char* to method that takes an ossimString. ossimString tmpStr; if (prefix) { tmpStr = prefix; } saveAdjustments(kwl, tmpStr); // // Also save the state of the elevation object: // // ossimElevManager::instance()->saveState(kwl, prefix); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::saveState:returning..." << std::endl; return ossimProjection::saveState(kwl, prefix);; } //***************************************************************************** // METHOD: ossimSensorModel::loadState() // // Loads the state of this object from KWL. // //***************************************************************************** bool ossimSensorModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::loadState: entering..." << std::endl; const char* keyword; const char* value; // int nconv; ossimDpt v[4]; // temporarily holds vertices for ground polygon //*** // Read each keyword, breaking out if error occurs: //*** keyword = IMAGE_ID_KW; value = kwl.find(prefix, keyword); if (value) theImageID = value; else theImageID = NULL_STRING; keyword = SENSOR_ID_KW; value = kwl.find(prefix, keyword); if (value) theSensorID = value; else theSensorID = NULL_STRING; keyword = ossimKeywordNames::NUMBER_LINES_KW;//IMAGE_SIZE_LINES_KW; value = kwl.find(prefix, keyword); if (value) { theImageSize.line = ossimString(value).toLong(); } keyword = ossimKeywordNames::NUMBER_SAMPLES_KW;// IMAGE_SIZE_SAMPS_KW; value = kwl.find(prefix, keyword); if (value) { theImageSize.samp = ossimString(value).toLong(); } keyword = REF_IPT_LINE_KW; value = kwl.find(prefix, keyword); if (value) { theRefImgPt.line = ossimString(value).toDouble(); } keyword = REF_IPT_SAMP_KW; value = kwl.find(prefix, keyword); if (value) { theRefImgPt.samp = ossimString(value).toDouble(); } keyword = REF_GPT_LAT_KW; value = kwl.find(prefix, keyword); if(value) { theRefGndPt.latd(ossimString(value).toDouble()); } keyword = REF_GPT_LON_KW; value = kwl.find(prefix, keyword); if(value) { theRefGndPt.lond(ossimString(value).toDouble()); } keyword = REF_GPT_HGT_KW; value = kwl.find(prefix, keyword); if(value) { theRefGndPt.hgt = ossimString(value).toDouble(); } keyword = ossimKeywordNames::METERS_PER_PIXEL_Y_KW;// GSD_LINE_DIR_KW; value = kwl.find(prefix, keyword); if (value) { theGSD.line = ossimString(value).toDouble(); } keyword = ossimKeywordNames::METERS_PER_PIXEL_X_KW;//GSD_SAMP_DIR_KW; value = kwl.find(prefix, keyword); if (value) { theGSD.samp = ossimString(value).toDouble(); } theMeanGSD = (fabs(theGSD.line) + fabs(theGSD.samp))/2.0; keyword = ossimKeywordNames::UL_LAT_KW; value = kwl.find(prefix, keyword); if (value) { v[0].lat = ossimString(value).toDouble(); } keyword = ossimKeywordNames::UL_LON_KW; value = kwl.find(prefix, keyword); if (value) { v[0].lon = ossimString(value).toDouble(); } keyword = ossimKeywordNames::UR_LAT_KW; value = kwl.find(prefix, keyword); if (value) { v[1].lat = ossimString(value).toDouble(); } keyword = ossimKeywordNames::UR_LON_KW; value = kwl.find(prefix, keyword); if (value) { v[1].lon = ossimString(value).toDouble(); } keyword = ossimKeywordNames::LR_LAT_KW; value = kwl.find(prefix, keyword); if (value) { v[2].lat = ossimString(value).toDouble(); } keyword = ossimKeywordNames::LR_LON_KW; value = kwl.find(prefix, keyword); if (value) { v[2].lon = ossimString(value).toDouble(); } keyword = ossimKeywordNames::LL_LAT_KW; value = kwl.find(prefix, keyword); if (value) { v[3].lat = ossimString(value).toDouble(); } keyword = ossimKeywordNames::LL_LON_KW; value = kwl.find(prefix, keyword); if (value) { v[3].lon = ossimString(value).toDouble(); } keyword = ossimKeywordNames::CE90_ABSOLUTE_KW; value = kwl.find(prefix, keyword); if (!value) { // Try old keyword for legacy purposes: keyword = ossimKeywordNames::IMAGE_CE90_KW; value = kwl.find(prefix, keyword); } if (value) theNominalPosError = atof(value); else theNominalPosError = 0.0; keyword = ossimKeywordNames::CE90_RELATIVE_KW; value = kwl.find(prefix, keyword); if (value) theRelPosError = atof(value); else theRelPosError = theNominalPosError; //*** // Initialize other data members given quantities read in KWL: //*** theBoundGndPolygon = ossimPolygon(4, v); const char* rect = kwl.find(prefix, "rect"); if(rect) { std::vector splitArray; ossimString rectString(rect); rectString = rectString.trim(); rectString.split(splitArray, " "); if(splitArray.size() == 4) { theImageClipRect = ossimDrect(splitArray[0].toDouble(), splitArray[1].toDouble(), splitArray[2].toDouble(), splitArray[3].toDouble()); } else { theImageClipRect = ossimDrect(0.0, 0.0, theImageSize.samp-1, theImageSize.line-1); } } else { theImageClipRect = ossimDrect(0.0, 0.0, theImageSize.samp-1, theImageSize.line-1); } // theSeedFunction: This is in the base class ossimSensorModel but is not // in the ossimSensorModel::loadState so do it here. ossimString seedPrefix = prefix; seedPrefix += ".seed_projection."; value = kwl.find( seedPrefix.chars(), ossimKeywordNames::TYPE_KW ); if ( value ) { // Only do expensive factory call if key is found... theSeedFunction = ossimProjectionFactoryRegistry::instance()-> createProjection(kwl, seedPrefix.chars()); } // Avoid passing null char* to method that takes an ossimString. ossimString tmpStr; if (prefix) { tmpStr = prefix; } loadAdjustments(kwl, tmpStr); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::loadState: returning..." << std::endl; return ossimProjection::loadState(kwl, prefix);; } //***************************************************************************** // PROTECTED METHOD: Model_type::extrapolate(image_point) // // This method computes extrapolated values of latitude and longitude for // points which are outside the actual image boundaries. //***************************************************************************** ossimGpt ossimSensorModel::extrapolate (const ossimDpt& imagePoint, const double& height) const { theExtrapolateImageFlag = true; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::extrapolate: entering... " << std::endl; //--- // If image point supplied has NaN components, return now with a NaN point. // This prevents an infinite recursion between model worldToLineSample // and this method: //--- if (imagePoint.hasNans()) { theExtrapolateImageFlag = false; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::extrapolate: returning..." << std::endl; return ossimGpt(ossim::nan(), ossim::nan(), ossim::nan()); } if(theSeedFunction.valid()) { ossimGpt wpt; theSeedFunction->lineSampleToWorld(imagePoint, wpt); theExtrapolateImageFlag = false; return wpt; } //*** // Determine which edge is intersected by the radial, and establish // intersection: //*** ossimGpt gpt; ossimDpt edgePt (imagePoint); ossimDpt image_center (theRefImgPt); theImageClipRect.clip(image_center, edgePt); //*** // Need edgePt relative to image center. Compute an epsilon perturbation in // the direction of edgePt for later computing directional derivative, // and back out the offset to origin: //*** ossimDpt deltaPt (edgePt - image_center); ossimDpt epsilon (deltaPt/deltaPt.length()); edgePt -= epsilon; // insure that we are inside the image ossimDpt edgePt_prime (edgePt - epsilon); // epsilon=1pixel //*** // Establish ground point corresponding to edge point and edgePt+epsilon: //*** ossimGpt edgeGP; ossimGpt edgeGP_prime; if (ossim::isnan(height)) { lineSampleToWorld(edgePt, edgeGP); lineSampleToWorld(edgePt_prime, edgeGP_prime); } else { lineSampleHeightToWorld(edgePt, height, edgeGP); lineSampleHeightToWorld(edgePt_prime, height, edgeGP_prime); } //*** // Compute approximate directional derivatives of lat and lon along radial // at the edge: //*** double dpixel = (edgePt-edgePt_prime).length(); double dlat_drad = (edgeGP.lat - edgeGP_prime.lat)/dpixel; double dlon_drad = (edgeGP.lon - edgeGP_prime.lon)/dpixel; //*** // Now extrapolate to image point of interest: //*** double delta_pixel = (imagePoint - edgePt).length(); gpt.lat = edgeGP.lat + dlat_drad*delta_pixel; gpt.lon = edgeGP.lon + dlon_drad*delta_pixel; if ( ossim::isnan(height) ) { gpt.hgt = ossimElevManager::instance()->getHeightAboveEllipsoid(gpt); } else { gpt.hgt = height; } theExtrapolateImageFlag = false; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::extrapolate: returning..." << std::endl; return gpt; } //***************************************************************************** // PROTECTED METHOD: Model_type::extrapolate(ground_point) // // This method computes extrapolated values of line and sample for // points which are outside the actual image boundaries. //***************************************************************************** ossimDpt ossimSensorModel::extrapolate (const ossimGpt& gpt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::extrapolate: entering... " << std::endl; theExtrapolateGroundFlag = true; double height = 0.0; //--- // If ground point supplied has NaN components, return now with a NaN point. //--- if ( (ossim::isnan(gpt.lat)) || (ossim::isnan(gpt.lon)) ) // (gpt.hgt==OSSIM_DBL_NAN)) { theExtrapolateGroundFlag = false; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::extrapolate: returning..." << std::endl; return ossimDpt(ossim::nan(), ossim::nan()); } if(ossim::isnan(gpt.hgt) == false) { height = gpt.hgt; } if(theSeedFunction.valid()) { ossimDpt ipt; theSeedFunction->worldToLineSample(gpt, ipt); theExtrapolateGroundFlag = false; return ipt; } //*** // Determine which edge is intersected by the radial, and establish // intersection: //*** ossimDpt edgePt (gpt); ossimDpt image_center (theRefGndPt); theBoundGndPolygon.clipLineSegment(image_center, edgePt); //--- // Compute an epsilon perturbation in the direction away from edgePt for // later computing directional derivative: //--- const double DEG_PER_MTR = 8.983152841e-06; // Equator WGS-84... double epsilon = theMeanGSD*DEG_PER_MTR; //degrees (latitude) per pixel ossimDpt deltaPt (edgePt-image_center); ossimDpt epsilonPt (deltaPt*epsilon/deltaPt.length()); edgePt -= epsilonPt; ossimDpt edgePt_prime (edgePt - epsilonPt); //*** // Establish image point corresponding to edge point and edgePt+epsilon: //*** ossimGpt edgeGP (edgePt.lat, edgePt.lon, height);//gpt.hgt); ossimGpt edgeGP_prime (edgePt_prime.lat, edgePt_prime.lon, height);//gpt.hgt); worldToLineSample(edgeGP, edgePt); worldToLineSample(edgeGP_prime, edgePt_prime); //*** // Compute approximate directional derivatives of line and sample along // radial at the edge: //*** double dsamp_drad = (edgePt.samp - edgePt_prime.samp)/epsilon; double dline_drad = (edgePt.line - edgePt_prime.line)/epsilon; //*** // Now extrapolate to point of interest: //*** double delta = (ossimDpt(gpt) - ossimDpt(edgeGP)).length(); ossimDpt extrapolated_ip (edgePt.samp + delta*dsamp_drad, edgePt.line + delta*dline_drad); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::extrapolate: returning..." << std::endl; theExtrapolateGroundFlag = false; return extrapolated_ip; } //***************************************************************************** // METHOD: ossimSensorModel::imagingRay() // // Default implementation for computing imaging ray from image point. // //***************************************************************************** void ossimSensorModel::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::imagingRay: entering..." << std::endl; ossimGpt start; ossimGpt end; lineSampleHeightToWorld(image_point, RAY_ORIGIN_HEIGHT, start); lineSampleHeightToWorld(image_point, 0.0, end); image_ray = ossimEcefRay(start, end); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::imagingRay: returning..." << std::endl; return; } //***************************************************************************** // METHOD: ossimSensorModel::getObsCovMat() // // Default implementation for forming observation covariance matrix. // // Note: At this base class level, the only error source currently // considered is mensuration error. This is obviously optimistic, // but is included as a placeholder/example, and is presently // the trivial case. // //***************************************************************************** ossimSensorModel::CovMatStatus ossimSensorModel::getObsCovMat( const ossimDpt& /* ipos */ , NEWMAT::SymmetricMatrix& Cov, const ossim_float64 defPointingSigma) const { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Mensuration error contribution // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Sensitivity matrix NEWMAT::SymmetricMatrix B(2); B = 0.0; B(1,1) = 1.0; B(2,2) = B(1,1); // Pointing covariance matrix NEWMAT::SymmetricMatrix P(2); P = 0.0; P(1,1) = defPointingSigma*defPointingSigma; P(2,2) = P(1,1); // Propagate NEWMAT::SymmetricMatrix Cm; Cm << B * P * B.t(); // ~~~~~~~~~~~~~~~~~~~~ // Sum total covariance // ~~~~~~~~~~~~~~~~~~~~ NEWMAT::SymmetricMatrix Ctot = Cm; //+ other contributors as identified // ~~~~~~~~~~~~~~~~~~ // Propagate to image // ~~~~~~~~~~~~~~~~~~ NEWMAT::SymmetricMatrix Bi(2); Bi = 0.0; Bi(1,1) = 1.0; Bi(2,2) = Bi(1,1); Cov << Bi * Ctot * Bi.t(); return ossimSensorModel::COV_PARTIAL; } void ossimSensorModel::computeGsd() { static const char MODULE[] = "ossimSensorModel::computeGsd"; if (theImageSize.hasNans()) { std::string e = MODULE; e += "Error image size has nans!"; throw ossimException(e); } //--- // Compute gsd in the x direction from left to right points across the middle of image. // Compute gsd in the y direction from top to bottom points across the middle of image. //--- // ossim_float64 midLine = 0.0; // ossim_float64 midSamp = 0.0; // ossim_float64 endLine = 1.0; // ossim_float64 endSamp = 1.0; // if (theImageSize.x > 2) // { // midSamp = (theImageSize.x-1)/2.0; // endSamp = theImageSize.x-1; // } // if (theImageSize.y > 2) // { // midLine = (theImageSize.y-1)/2.0; // endLine = theImageSize.y-1; // } ossimDpt centerImagePoint = theRefImgPt; ossimDpt quarterSize; if(!theImageSize.hasNans()) { quarterSize = ossimDpt(theImageSize.x/4.0, theImageSize.y/4.0); } else if(!theImageClipRect.hasNans()) { ossim_float32 w = theImageClipRect.width(); ossim_float32 h = theImageClipRect.height(); quarterSize = ossimDpt(w/4.0, h/4.0); } else { quarterSize = ossimDpt(1.0,1.0); } if(centerImagePoint.hasNans()&&(!theImageSize.hasNans())) { centerImagePoint.x = (theImageSize.x)/2.0; centerImagePoint.y = (theImageSize.y-1.0)/2.0; } else if(centerImagePoint.hasNans()&&!theImageClipRect.hasNans()) { centerImagePoint = theImageClipRect.midPoint(); } if(!centerImagePoint.hasNans()) { ossimDpt leftDpt(centerImagePoint.x-quarterSize.x, centerImagePoint.y);// (0.0, midLine); ossimDpt rightDpt(centerImagePoint.x+quarterSize.y, centerImagePoint.y);// (endSamp, midLine); ossimDpt topDpt(centerImagePoint.x, centerImagePoint.y-quarterSize.y);// (midSamp, 0.0); ossimDpt bottomDpt(centerImagePoint.x, centerImagePoint.y+quarterSize.y);//(midSamp, endLine); ossimGpt leftGpt; ossimGpt rightGpt; ossimGpt topGpt; ossimGpt bottomGpt; //--- // Left point. // For the first point use lineSampleToWorld to get the height. //--- lineSampleToWorld(leftDpt, leftGpt); if (leftGpt.hasNans()) { std::string e = MODULE; e += "Error leftGpt has nans!"; throw ossimException(e); } //--- // Right point: // Use lineSampleHeightToWorld using the left height since we want the horizontal distance. //--- lineSampleHeightToWorld(rightDpt, leftGpt.hgt, rightGpt); if (rightGpt.hasNans()) { std::string e = MODULE; e += "Error rightGpt has nans!"; throw ossimException(e); } //--- // Top point: // Use lineSampleHeightToWorld using the left height since we want the horizontal distance. //--- lineSampleHeightToWorld(topDpt, leftGpt.hgt, topGpt); if (topGpt.hasNans()) { std::string e = MODULE; e += "Error topGpt has nans!"; throw ossimException(e); } //--- // Bottom point: // Use lineSampleHeightToWorld using the left height since we want the horizontal distance. //--- lineSampleHeightToWorld(bottomDpt, leftGpt.hgt, bottomGpt); if (bottomGpt.hasNans()) { std::string e = MODULE; e += "Error bottomGpt has nans!"; throw ossimException(e); } #if 0 /* Please leave for debug. (drb) */ ossimNotify(ossimNotifyLevel_DEBUG) << "image size: " << theImageSize << "\nleftDpt: " << leftDpt << "\nrightDpt: " << rightDpt << "\ntopDpt: " << topDpt << "\nbottomDpt: " << bottomDpt << "\nleftGpt: " << leftGpt << "\nrightGpt: " << rightGpt << "\ntopGpt: " << topGpt << "\nbottomGpt: " << bottomGpt << "\n"; #endif theGSD.x = leftGpt.distanceTo(rightGpt)/(rightDpt.x-leftDpt.x); theGSD.y = topGpt.distanceTo(bottomGpt)/(bottomDpt.y-topDpt.y); theMeanGSD = (theGSD.x + theGSD.y)/2.0; } else { std::string e = MODULE; e += "Error center has nans!"; throw ossimException(e); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSensorModel::computGsd DEBUG:" << "\ntheGSD: " << theGSD << "\ntheMeanGSD: " << theMeanGSD << std::endl; } } //***************************************************************************** // STATIC METHOD: ossimSensorModel::writeGeomTemplate // // Outputs a sample geometry KWL to stream provided. // //***************************************************************************** void ossimSensorModel::writeGeomTemplate(ostream& os) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::writeGeomTemplate:entering..." << std::endl; os << "//***\n" << "// Base-class ossimSensorModel Keywords:\n" << "//***\n" << ossimKeywordNames::ID_KW << ": \n" << SENSOR_ID_KW << ": \n" << ossimKeywordNames::NUMBER_LINES_KW << ": \n" << ossimKeywordNames::NUMBER_SAMPLES_KW << ": \n" << REF_GPT_LAT_KW << ": \n" << REF_GPT_LON_KW << ": \n" << REF_GPT_HGT_KW << ": \n" << REF_IPT_LINE_KW << ": \n" << REF_IPT_SAMP_KW << ": \n" << ossimKeywordNames::METERS_PER_PIXEL_Y_KW << ": \n" << ossimKeywordNames::METERS_PER_PIXEL_X_KW << ": \n" << ossimKeywordNames::UL_LAT_KW << ": \n" << ossimKeywordNames::UL_LON_KW << ": \n" << ossimKeywordNames::UR_LAT_KW << ": \n" << ossimKeywordNames::UR_LON_KW << ": \n" << ossimKeywordNames::LR_LAT_KW << ": \n" << ossimKeywordNames::LR_LON_KW << ": \n" << ossimKeywordNames::LL_LAT_KW << ": \n" << ossimKeywordNames::LL_LON_KW << ": \n" << "\n" << "//***\n" << "// Repeat following four entries for each adjustable parameter:\n" << "//***\n" // << PARAM_PREFIX << "N." << PARAM_NAME_KW << ": \n" // << PARAM_PREFIX << "N." << PARAM_UNITS_KW << ": \n" // << PARAM_PREFIX << "N." << PARAM_VALUE_KW << ": \n" // << PARAM_PREFIX << "N." << PARAM_SIGMA_KW << ": \n" << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::writeGeomTemplate: returning..." << std::endl; return; } ossim_uint32 ossimSensorModel::degreesOfFreedom()const { ossim_uint32 dof = 0; ossim_uint32 idx = 0; ossim_uint32 numAdj = getNumberOfAdjustableParameters(); for(idx = 0; idx < numAdj; ++idx) { if(!isParameterLocked(idx)) { ++dof; } } return dof; } double ossimSensorModel::optimizeFit(const ossimTieGptSet& tieSet, double* /* targetVariance */) { //use a simple Levenberg-Marquardt non-linear optimization //note : please limit the number of tie points // //INPUTS: requires Jacobian matrix (partial derivatives with regards to parameters) //OUTPUTS: will also compute parameter covariance matrix // //TBD: use targetVariance! int np = getNumberOfAdjustableParameters(); int nobs = tieSet.size(); //setup initail values int iter=0; int iter_max = 200; double minResidue = 1e-10; //TBC double minDelta = 1e-10; //TBC //build Least Squares initial normal equation // don't waste memory, add samples one at a time NEWMAT::SymmetricMatrix A; NEWMAT::ColumnVector residue; NEWMAT::ColumnVector projResidue; double deltap_scale = 1e-4; //step_Scale is 1.0 because we expect parameters to be between -1 and 1 buildNormalEquation(tieSet, A, residue, projResidue, deltap_scale); double ki2=residue.SumSquare(); //get current adjustment (between -1 and 1 normally) and convert to ColumnVector ossimAdjustmentInfo cadj; getAdjustment(cadj); std::vector< ossimAdjustableParameterInfo >& parmlist = cadj.getParameterList(); NEWMAT::ColumnVector cparm(np), nparm(np); for(int n=0;n 0) { //accept new parms cparm = nparm; ki2=newki2; deltap_scale = max(1e-15, deltap.NormInfinity()*1e-4); buildNormalEquation(tieSet, A, residue, projResidue, deltap_scale); olddamping = 0.0; found = ( projResidue.NormInfinity() <= minResidue ); //update damping factor damping *= std::max( 1.0/3.0, 1.0-std::pow((2.0*res_reduction-1.0),3)); damping_speed = 2.0; decrease = true; } else { //cancel parameter update for(int n=0;n >& theTPV = tieSet.getTiePoints(); vector >::const_iterator tit; unsigned long c=1; if (useImageObs) { //image observations std::vector imDerp(np); ossimDpt resIm; // loop on tie points for (tit = theTPV.begin() ; tit != theTPV.end() ; ++tit) { //compute residue resIm = (*tit)->tie - forward(*(*tit)); residue(c++) = resIm.x; residue(c++) = resIm.y; //compute all image derivatives regarding parametres for the tie point position for(int p=0;p gdDerp(np); ossimGpt gd, resGd; // loop on tie points for (tit = theTPV.begin() ; tit != theTPV.end() ; ++tit) { //compute residue gd = inverse((*tit)->tie); residue(c++) = resGd.lon = ((*tit)->lon - gd.lon) * 100000.0; residue(c++) = resGd.lat = ((*tit)->lat - gd.lat) * 100000.0 * cos(gd.lat / 180.0 * M_PI); residue(c++) = resGd.hgt = (*tit)->hgt - gd.hgt; //TBD : normalize to meters? //compute all image derivatives regarding parametres for the tie point position for(int p=0;ptie, pstep_scale); } //compute influence of tie point on all sytem elements for(int p1=0;p1=0) ossimGpt ossimSensorModel::getInverseDeriv(int parmIdx, const ossimDpt& ipos, double hdelta) { double den = 0.5/hdelta; ossimGpt res,gd; double middle = getAdjustableParameter(parmIdx); //set parm to high value setAdjustableParameter(parmIdx, middle + hdelta, true); res = inverse(ipos); //set parm to low value and gte difference setAdjustableParameter(parmIdx, middle - hdelta, true); gd = inverse(ipos); //reset parm setAdjustableParameter(parmIdx, middle, true); res.lon = den*(res.lon - gd.lon) * 100000.0; //TBC : approx meters res.lat = den*(res.lat - gd.lat) * 100000.0 * cos(gd.lat / 180.0 * M_PI); res.hgt = den*(res.hgt - gd.hgt); return res; } //give forward() partial derivative regarding parameter parmIdx (>=0) ossimDpt ossimSensorModel::getForwardDeriv(int parmIdx, const ossimGpt& gpos, double hdelta) { static double den = 0.5/hdelta; ossimDpt res; double middle = getAdjustableParameter(parmIdx); //set parm to high value setAdjustableParameter(parmIdx, middle + hdelta, true); res = forward(gpos); //set parm to low value and gte difference setAdjustableParameter(parmIdx, middle - hdelta, true); res -= forward(gpos); //get partial derivative res = res*den; //reset parm setAdjustableParameter(parmIdx, middle, true); return res; } NEWMAT::ColumnVector ossimSensorModel::getResidue(const ossimTieGptSet& tieSet) { //init NEWMAT::ColumnVector residue; int dimObs; bool useImageObs = useForward(); //caching if (useImageObs) { dimObs = 2; //image observation } else { dimObs = 3; //ground observations } int no = dimObs * tieSet.size(); //number of observations residue.ReSize(no); const vector >& theTPV = tieSet.getTiePoints(); vector >::const_iterator tit; unsigned long c=1; if (useImageObs) { //image observations ossimDpt resIm; // loop on tie points for (tit = theTPV.begin() ; tit != theTPV.end() ; ++tit) { //compute residue resIm = (*tit)->tie - forward(**tit); residue(c++) = resIm.x; residue(c++) = resIm.y; } } else { // ground observations ossimGpt gd; // loop on tie points for (tit = theTPV.begin() ; tit != theTPV.end() ; ++tit) { //compute residue gd = inverse((*tit)->tie); residue(c++) = ((*tit)->lon - gd.lon) * 100000.0; //approx meters //TBC TBD residue(c++) = ((*tit)->lat - gd.lat) * 100000.0 * cos(gd.lat / 180.0 * M_PI); residue(c++) = (*tit)->hgt - gd.hgt; //meters } } //end of if (useImageObs) return residue; } /*! * solves Ax = r , with A symmetric positive definite * A can be rank deficient * size of A is typically between 10 and 100 rows */ NEWMAT::ColumnVector ossimSensorModel::solveLeastSquares(NEWMAT::SymmetricMatrix& A, NEWMAT::ColumnVector& r)const { NEWMAT::ColumnVector x = invert(A)*r; return x; } /** * stable invert stolen from ossimRpcSolver */ NEWMAT::Matrix ossimSensorModel::invert(const NEWMAT::Matrix& m)const { ossim_uint32 idx = 0; NEWMAT::DiagonalMatrix d; NEWMAT::Matrix u; NEWMAT::Matrix v; // decompose m.t*m which is stored in Temp into the singular values and vectors. // NEWMAT::SVD(m, d, u, v, true, true); // invert the diagonal // this is just doing the reciprical fo all diagonal components and store back int // d. ths compute d inverse. // for(idx=0; idx < (ossim_uint32)d.Ncols(); ++idx) { if(d[idx] > 1e-14) //TBC : use DBL_EPSILON ? { d[idx] = 1.0/d[idx]; } else { d[idx] = 0.0; //DEBUG TBR cout<<"warning: singular matrix in SVD"< #include #include #include #include #include #include #include #include #include //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec = ossimTrace("ossimSensorModelFactory:exec"); static ossimTrace traceDebug = ossimTrace("ossimSensorModelFactory:debug"); #define TRACE_DEBUG if(traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)< #include #include #include #include #include #include #include #include #include #include //#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //*** // ADD_MODEL: List names of all sensor models produced by this factory: //*** //const char* MY_NEW_MODEL = "myNewModel"; // const char* OCG_MODEL = "ossimCoarseGridModel"; // const char* RPC_MODEL = "ossimRpcModel"; // const char* IKONOS_RPC_MODEL = "ossimIkonosRpcModel"; // const char* NITF_RPC_MODEL = "ossimNitfRpcModel"; // const char* LANDSAT_MODEL = "ossimLandSatModel"; // const char* NITF_MAP_MODEL = "ossimNitfMapModel"; // const char* FCSI_MODEL = "ossimFcsiModel"; // const char* EMERGE_FCSI_MODEL= "ossimEmergeFcsiModel"; //***************************************************************************** // STATIC METHOD: ossimSensorModelFactory::instance() //***************************************************************************** ossimSensorModelFactory* ossimSensorModelFactory::instance() { static ossimSensorModelFactory inst; return &inst; } //***************************************************************************** // METHOD: ossimSensorModelFactory::create(kwl, prefix) //***************************************************************************** ossimProjection* ossimSensorModelFactory::createProjection(const ossimKeywordlist &keywordList, const char *prefix) const { ossimRefPtr result; // // Permit specification of geometry file name in lieu of type: // const char* value = keywordList.find(prefix, ossimKeywordNames::GEOM_FILE_KW); if (value) { result = createProjection(ossimFilename(value), 0); } // // Search for occurence of "type" keyword: // else { value = keywordList.find(prefix, ossimKeywordNames::TYPE_KW); if(value) { result = createProjection(ossimString(value)); if(result.valid()) { if(!result->loadState(keywordList, prefix)) { result = 0; } } } } return result.release(); } //***************************************************************************** // METHOD: // //***************************************************************************** ossimProjection* ossimSensorModelFactory::createProjection(const ossimString &name) const { //*** // Name should represent the model type: //*** if(name == STATIC_TYPE_NAME(ossimSkyBoxLearSensor)) { return new ossimSkyBoxLearSensor; } if(name == STATIC_TYPE_NAME(ossimIpodSensor)) { return new ossimIpodSensor; } if(name == STATIC_TYPE_NAME(ossimCoarseGridModel)) { return new ossimCoarseGridModel; } if(name == STATIC_TYPE_NAME(ossimBuckeyeSensor)) { return new ossimBuckeyeSensor; } if (name == STATIC_TYPE_NAME(ossimRpcModel)) { return new ossimRpcModel; } if(name == STATIC_TYPE_NAME(ossimLandSatModel)) { return new ossimLandSatModel; } // if(name == STATIC_TYPE_NAME(ossimNitfMapModel)) // { // return new ossimNitfMapModel; // } if(name == STATIC_TYPE_NAME(ossimQuickbirdRpcModel)) { return new ossimQuickbirdRpcModel; } if(name == STATIC_TYPE_NAME(ossimIkonosRpcModel)) { return new ossimIkonosRpcModel; } if(name == STATIC_TYPE_NAME(ossimNitfRpcModel)) { return new ossimNitfRpcModel; } if(name == STATIC_TYPE_NAME(ossimFcsiModel)) { return new ossimFcsiModel; } if(name == STATIC_TYPE_NAME(ossimApplanixUtmModel)) { return new ossimApplanixUtmModel; } if(name == STATIC_TYPE_NAME(ossimApplanixEcefModel)) { return new ossimApplanixEcefModel; } if(name == STATIC_TYPE_NAME(ossimSpot5Model)) { return new ossimSpot5Model; } if(name == STATIC_TYPE_NAME(ossimSarModel)) { return new ossimSarModel; } if(name == STATIC_TYPE_NAME(ossimRS1SarModel)) { return new ossimRS1SarModel; } if(name == STATIC_TYPE_NAME(ossimPpjFrameSensor)) { return new ossimPpjFrameSensor; } if(name == STATIC_TYPE_NAME(ossimAlphaSensorHRI)) { return new ossimAlphaSensorHRI; } if(name == STATIC_TYPE_NAME(ossimAlphaSensorHSI)) { return new ossimAlphaSensorHSI; } if(name == STATIC_TYPE_NAME(ossimNitfRsmModel)) { return new ossimNitfRsmModel(); } if(name == STATIC_TYPE_NAME(ossimSpectraboticsRedEdgeModel)) { return new ossimSpectraboticsRedEdgeModel(); } //*** // ADD_MODEL: (Please leave this comment for the next programmer) //*** // if(name == MY_NEW_MODEL) // return new myNewModel; return NULL; } //***************************************************************************** // METHOD //***************************************************************************** ossimObject* ossimSensorModelFactory::createObject(const ossimString& typeName)const { return createProjection(typeName); } //***************************************************************************** // METHOD //***************************************************************************** ossimObject* ossimSensorModelFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { return createProjection(kwl, prefix); } //***************************************************************************** // METHOD //***************************************************************************** void ossimSensorModelFactory::getTypeNameList(std::vector& typeList) const { typeList.push_back(STATIC_TYPE_NAME(ossimApplanixEcefModel)); typeList.push_back(STATIC_TYPE_NAME(ossimApplanixUtmModel)); typeList.push_back(STATIC_TYPE_NAME(ossimCoarseGridModel)); typeList.push_back(STATIC_TYPE_NAME(ossimRpcModel)); typeList.push_back(STATIC_TYPE_NAME(ossimIkonosRpcModel)); typeList.push_back(STATIC_TYPE_NAME(ossimQuickbirdRpcModel)); typeList.push_back(STATIC_TYPE_NAME(ossimNitfRpcModel)); typeList.push_back(STATIC_TYPE_NAME(ossimLandSatModel)); // typeList.push_back(STATIC_TYPE_NAME(ossimNitfMapModel)); typeList.push_back(STATIC_TYPE_NAME(ossimFcsiModel)); typeList.push_back(STATIC_TYPE_NAME(ossimSpot5Model)); typeList.push_back(STATIC_TYPE_NAME(ossimSarModel)); typeList.push_back(STATIC_TYPE_NAME(ossimRS1SarModel)); typeList.push_back(STATIC_TYPE_NAME(ossimBuckeyeSensor)); typeList.push_back(STATIC_TYPE_NAME(ossimSkyBoxLearSensor)); typeList.push_back(STATIC_TYPE_NAME(ossimIpodSensor)); typeList.push_back(STATIC_TYPE_NAME(ossimPpjFrameSensor)); typeList.push_back(STATIC_TYPE_NAME(ossimAlphaSensorHRI)); typeList.push_back(STATIC_TYPE_NAME(ossimAlphaSensorHSI)); typeList.push_back(STATIC_TYPE_NAME(ossimNitfRsmModel)); typeList.push_back(STATIC_TYPE_NAME(ossimSpectraboticsRedEdgeModel)); //*** // ADD_MODEL: Please leave this comment for the next programmer. Add above. //*** //typeList.push_back(ossimString(MY_NEW_MODEL)); } ossimProjection* ossimSensorModelFactory::createProjection(const ossimFilename& filename, ossim_uint32 entryIdx) const { static const char MODULE[] = "ossimSensorModelFactory::createProjection"; // ossimFilename::exists() currently does not work with s3 url's. // if(!filename.exists()) return 0; if(filename.empty()) return 0; ossimKeywordlist kwl; ossimRefPtr model = 0; ossimFilename geomFile = filename; geomFile = geomFile.setExtension("geom"); do { TRACE_DEBUG<<"Testing ossimCoarsGridModel" << std::endl; if (geomFile.exists() && kwl.addFile(filename.c_str())) { ossimFilename coarseGrid; const char* type = kwl.find(ossimKeywordNames::TYPE_KW); if (type && (ossimString(type)==ossimString(STATIC_TYPE_NAME(ossimCoarseGridModel)))) { findCoarseGrid(coarseGrid, filename); if(coarseGrid.exists() &&(coarseGrid != "")) { kwl.add("grid_file_name", coarseGrid.c_str(), true); model = new ossimCoarseGridModel(kwl); if(!model->getErrorStatus()) break; model = 0; } } kwl.clear(); } // See if there is an external geomtry. model = createProjectionFromGeometryFile(filename, entryIdx); if(model.valid()) break; // first check for override if(geomFile.exists()&&kwl.addFile(geomFile.c_str())) { model = createProjection(kwl); if(model.valid()) break; } ifstream input(geomFile.c_str()); char ecgTest[4] = { 0 }; input.read(ecgTest, 3); // even if `read()` fails, it will be initialized thanks to `= { 0 };` input.close(); if(std::string(ecgTest) == "eCG") { ossimKeywordlist kwlTemp; kwlTemp.add("type", "ossimCoarseGridModel", true); kwlTemp.add("geom_file", geomFile.c_str(), true); model = createProjection(kwlTemp); break; } //--- // Test for quick bird rpc. Could be either a tiff or nitf so not wrapped // around "isNitf()" anymore. //--- TRACE_DEBUG<<"testing ossimQuickbirdRpcModel"<< std::endl; ossimRefPtr qbModel = new ossimQuickbirdRpcModel; if(qbModel->parseFile(filename)) { model = qbModel.get(); break; } // Test for ikonos rpc. Could be tiff or nitf which is handled in parseFile method. TRACE_DEBUG<<"testing ossimIkonosRpcModel" << std::endl; ossimRefPtr ikModel = new ossimIkonosRpcModel; if (ikModel->parseFile(filename)) { model = ikModel.get(); break; } if(isNitf(filename)) { TRACE_DEBUG<<"testing ossimNitfRsmModel" << std::endl; ossimRefPtr rsmModel = new ossimNitfRsmModel(); if(rsmModel->parseFile(filename, entryIdx)) { model = rsmModel.get(); break; } TRACE_DEBUG<<"testing ossimNitfRpcModel" << std::endl; ossimRefPtr rpcModel = new ossimNitfRpcModel(); if ( rpcModel->parseFile(filename, entryIdx) ) // filename = NITF_file { model = rpcModel.get(); break; } } TRACE_DEBUG<<"testing ossimLandSatModel" << std::endl; if(isLandsat(filename)) { model = new ossimLandSatModel(filename); if(!model->getErrorStatus()) break; } TRACE_DEBUG<<"testing ossimRS1SarModel" << std::endl; model = new ossimRS1SarModel(filename); if(model->getErrorStatus()!= ossimErrorCodes::OSSIM_OK) break; // SPOT: TRACE_DEBUG<<"testing ossimSpot5Model" << std::endl; ossimFilename spot5Test = geomFile; if(!spot5Test.exists()) { spot5Test = geomFile.path(); spot5Test = spot5Test.dirCat(ossimFilename("METADATA.DIM")); if (spot5Test.exists() == false) { spot5Test = geomFile.path(); spot5Test = spot5Test.dirCat(ossimFilename("metadata.dim")); } } if(spot5Test.exists()) { //--- // Check the basename of the input file. So we don't create a projection // for ancillary files, icon.jpg amd preview.jpg. //--- ossimFilename baseName = filename.file(); baseName.downcase(); if ( (baseName != "icon.jpg" ) && ( baseName != "preview.jpg" ) ) { ossimRefPtr meta = new ossimSpotDimapSupportData; if(meta->loadXmlFile(spot5Test)) { model = new ossimSpot5Model(meta.get()); if(!model->getErrorStatus()) break; } } } TRACE_DEBUG<<"testing ossimPpjFrameSensor" << std::endl; ossimFilename ppjFilename = filename; ppjFilename = ppjFilename.setExtension("ppj"); if(ppjFilename.exists()) { ossimRefPtr ppjFile = new ossimPpjFrameSensorFile(); if(ppjFile->readFile(ppjFilename)) { ossimRefPtr sensor = new ossimPpjFrameSensor(); ossimDpt imageSize = ppjFile->getImageSize(); sensor->setFocalLength(ppjFile->getIntrinsic()[0][0], ppjFile->getIntrinsic()[1][1]); sensor->setPrincipalPoint(ppjFile->getPrincipalPoint()); sensor->setecef2CamMatrix(ppjFile->getExtrinsic().SymSubMatrix(1,3)); sensor->setCameraPosition(ppjFile->getPlatformPosition()); sensor->setImageSize(imageSize); sensor->setImageRect(ossimDrect(0,0,imageSize.x-1, imageSize.y-1)); sensor->setRefImgPt(ossimDpt(imageSize.x*.5, imageSize.y*.5)); sensor->setAveragePrjectedHeight(ppjFile->getAverageProjectedHeight()); sensor->updateModel(); model = sensor.get(); break; } } ossimFilename hdrFilename = filename; hdrFilename = hdrFilename.setExtension("hdr"); // image.hdr if ( !hdrFilename.exists() ) { hdrFilename = filename; hdrFilename.string() += ".hdr"; // image.ras.hdr } TRACE_DEBUG<<"testing ossimAlphaSensor\nheader file: " << hdrFilename << std::endl; if(hdrFilename.exists()) { ossimRefPtr supData = new ossimAlphaSensorSupportData(); if(supData->readSupportFiles(hdrFilename)) { if (supData->isHSI()) { TRACE_DEBUG<<"loading ossimAlphaSensorHSI" << std::endl; ossimRefPtr sensor = new ossimAlphaSensorHSI(); if ( sensor->initialize( *(supData.get()) ) ) { model = sensor.get(); break; } } else { TRACE_DEBUG<<"loading ossimAlphaSensorHRI" << std::endl; ossimRefPtr sensor = new ossimAlphaSensorHRI(); if ( sensor->initialize( *(supData.get()) ) ) { model = sensor.get(); break; } } } } // Nothing found: TRACE_DEBUG<<"No sensor model found."<< std::endl; model = 0; } while (false); return model.release(); } bool ossimSensorModelFactory::isNitf(const ossimFilename& filename)const { std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream( filename, std::ios_base::in | std::ios_base::binary ); if( in ) { char nitfFile[4]; in->read((char*)nitfFile, 4); return (ossimString(nitfFile, nitfFile+4) == "NITF"); } return false; } bool ossimSensorModelFactory::isLandsat(const ossimFilename& filename)const { ossimFilename temp(filename); temp.downcase(); ossimRefPtr ff_headerp; if (temp.contains("header.dat")) { ff_headerp = new ossimFfL5(filename); } else { ff_headerp = new ossimFfL7(filename); } bool r = !(ff_headerp->getErrorStatus()); ff_headerp = 0; return r; } void ossimSensorModelFactory::findCoarseGrid(ossimFilename& result, const ossimFilename& geomFile)const { result = geomFile; result.setFile(result.fileNoExtension()+"_ocg"); result.setExtension("dat"); if(!result.exists()) { result = geomFile; result.setExtension("dat"); } // let's find a .dat file in the current directory // if(!result.exists()) { result = ""; ossimDirectory directoryList(geomFile.path()); ossimFilename file; if(directoryList.getFirst(file, ossimDirectory::OSSIM_DIR_FILES)) { ossimString testString = "OSSIM_DBL_GRID"; char tempBuf[14]; do { if(file.ext().downcase() == "dat") { std::ifstream in(file.c_str()); if(in) { in.read((char*)tempBuf, 14); in.close(); if(ossimString(tempBuf, tempBuf+14) == testString) { result = file; } } } }while((directoryList.getNext(file))&&(result == "")); } // try to find it } } ossim-Miami-2.9.1/src/projection/ossimSensorModelTuple.cpp000066400000000000000000000474541352751253100237170ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Base class for tuple-based ossimSensorModel metric operations. // //---------------------------------------------------------------------------- // $Id: ossimSensorModelTuple.cpp 22045 2012-12-28 21:22:35Z dhicks $ #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug(ossimString("ossimSensorModelTuple:debug")); static ossimTrace traceExec(ossimString("ossimSensorModelTuple:exec")); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimSensorModelTuple.cpp 22045 2012-12-28 21:22:35Z dhicks $"; #endif ossimRpcPqeInputs::ossimRpcPqeInputs() : theRpcElevationAngle(ossim::nan()), theRpcAzimuthAngle(ossim::nan()), theRpcBiasError(ossim::nan()), theRpcRandError(ossim::nan()), theSurfaceNormalVector(), theSurfaceCovMatrix(3,3) { } ossimRpcPqeInputs::~ossimRpcPqeInputs() { } //***************************************************************************** // METHOD: ossimSensorModelTuple::ossimSensorModelTuple() // // Constructor. // //***************************************************************************** ossimSensorModelTuple::ossimSensorModelTuple() : theNumImages(0), theSurfCE90(0.0), theSurfLE90(0.0), theSurfAccSet(false), theSurfAccRepresentsNoDEM(false), theRpcPqeInputs() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimSensorModelTuple::ossimSensorModelTuple DEBUG:" << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "OSSIM_ID: " << OSSIM_ID << std::endl; #endif } } //***************************************************************************** // DESTRUCTOR: ~ossimSensorModelTuple() // //***************************************************************************** ossimSensorModelTuple::~ossimSensorModelTuple() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: ~ossimSensorModelTuple(): entering..." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: ~ossimSensorModelTuple(): returning..." << std::endl; } //***************************************************************************** // METHOD: ossimSensorModelTuple::addImage() // // Add an image to the tuple. // //***************************************************************************** void ossimSensorModelTuple::addImage(ossimSensorModel* image) { theImages.push_back(image); theNumImages++; } //***************************************************************************** // METHOD: ossimSensorModelTuple::setIntersectionSurfaceAccuracy() // // Allow calling program to set the DEM accuracy. // // If both values are negative, it is assumed that no DEM is used. // //***************************************************************************** bool ossimSensorModelTuple:: setIntersectionSurfaceAccuracy(const ossim_float64& surfCE90, const ossim_float64& surfLE90) { bool setOK = false; if (surfCE90>=0.0 && surfLE90>=0.0) { theSurfCE90 = surfCE90; theSurfLE90 = surfLE90; theSurfAccSet = true; theSurfAccRepresentsNoDEM = false; setOK = true; } else { //*************************************************************** // RPC_No_DEM_State Demo case // In this case, surfCE90/surfLE90 are interpreted differently: // [1] surfCE90 contains the scale divisor for RPC hgtScale // [2] surfLE90 contains the probability level divisor for // RPC hgtScale to yield a 1-sigma value // These coputations are performed in computeSingleInterCov. //*************************************************************** theSurfCE90 = surfCE90; theSurfLE90 = surfLE90; theSurfAccSet = false; theSurfAccRepresentsNoDEM = true; setOK = true; } return setOK; } void ossimSensorModelTuple::getRpcPqeInputs(ossimRpcPqeInputs& obj) const { obj = theRpcPqeInputs; } //***************************************************************************** // METHOD: ossimSensorModelTuple::print() // // Print info. // //***************************************************************************** std::ostream& ossimSensorModelTuple::print(std::ostream& out) const { out << "\n ossimSensorModelTuple::print:" << std::endl; for (int i=0; iprint(out); return out; } //***************************************************************************** // METHOD: ossimSensorModelTuple::intersect() // // Perform multi-image intersection. // //***************************************************************************** ossimSensorModelTuple::IntersectStatus ossimSensorModelTuple:: intersect(const DptSet_t obs, ossimEcefPoint& pt, NEWMAT::Matrix& covMat) const { IntersectStatus opOK = OP_FAIL; bool covOK = true; bool epOK; ossim_int32 nImages = (ossim_int32)obs.size(); if (nImages > 1) { // Matrices NEWMAT::SymmetricMatrix N(3); NEWMAT::SymmetricMatrix BtWB(3); NEWMAT::Matrix Ni(3,3); NEWMAT::ColumnVector C(3); NEWMAT::ColumnVector BtWF(3); NEWMAT::ColumnVector F(2); NEWMAT::ColumnVector dR(3); NEWMAT::Matrix B(2,3); NEWMAT::SymmetricMatrix W(2); // Get a priori ground estimate using first point ossimGpt estG; theImages[0]->lineSampleToWorld(obs[0], estG); for (int iter=0; iter<5; iter++) { // cout<<"\n iter: "<lineSampleHeightToWorld(obs, atHeightAboveEllipsoid, ptG); ossimEcefPoint ptECF(ptG); pt = ptECF; // Error propagation bool epOK = computeSingleInterCov(img, obs, ptG, AT_HGT, covMat); // Set operation status if (epOK) opOK = OP_SUCCESS; else opOK = ERROR_PROP_FAIL; return opOK; } //***************************************************************************** // METHOD: ossimSensorModelTuple::intersect() // // Perform single-image intersection at DEM. // //***************************************************************************** ossimSensorModelTuple::IntersectStatus ossimSensorModelTuple:: intersect(const ossim_int32& img, const ossimDpt& obs, ossimEcefPoint& pt, NEWMAT::Matrix& covMat) { IntersectStatus opOK = OP_FAIL; ossimGpt ptG; // Intersection theImages[img]->lineSampleToWorld(obs, ptG); ossimEcefPoint ptECF(ptG); pt = ptECF; // Error propagation bool epOK = computeSingleInterCov(img, obs, ptG, AT_DEM, covMat); // Set operation status if (epOK) opOK = OP_SUCCESS; else opOK = ERROR_PROP_FAIL; return opOK; } //***************************************************************************** // METHOD: ossimSensorModelTuple::getGroundObsEqComponents() // // Extract residuals, partials and weight matrix for observation. // //***************************************************************************** bool ossimSensorModelTuple::getGroundObsEqComponents( const ossim_int32 img, const ossimDpt& obs, const ossimGpt& ptEst, ossimDpt& resid, NEWMAT::Matrix& B, NEWMAT::SymmetricMatrix& W) const { // Temporary image geometry ossimImageGeometry* iGeom = new ossimImageGeometry(NULL, (ossimProjection*) theImages[img].get()); // Evaluate residuals ossimDpt computedImg; iGeom->worldToLocal(ptEst, computedImg); resid = obs - computedImg; // Evaluate partials B(2X3) NEWMAT::Matrix Bt(3,2); iGeom->computeGroundToImagePartials(Bt, ptEst); B = Bt.t(); // Get covariance matrix & form weight matrix NEWMAT::SymmetricMatrix Cov(2); ossimSensorModel::CovMatStatus covStatus; covStatus = theImages[img]->getObsCovMat(obs,Cov); if (covStatus == ossimSensorModel::COV_INVALID) { W = 0.0; W(1,1) = 1.0; W(2,2) = 1.0; } else { NEWMAT::Matrix Wfull = invert(Cov); W << Wfull; } bool covOK = false; if (covStatus == ossimSensorModel::COV_FULL) covOK = true; return covOK; } //***************************************************************************** // METHOD: ossimSensorModelTuple::computeSingleInterCov() // // Compute single image intersection covariance matrix. // //***************************************************************************** bool ossimSensorModelTuple::computeSingleInterCov( const ossim_int32& img, const ossimDpt& obs, const ossimGpt& ptG, HeightRefType_t cRefType, NEWMAT::Matrix& covMat) { NEWMAT::SymmetricMatrix BtWB(3); NEWMAT::Matrix B(2,3); NEWMAT::SymmetricMatrix W(2); NEWMAT::Matrix surfCovENU(3,3); ossimDpt resid; bool tCovOK; bool covOK; // Set the height reference ossimHgtRef hgtRef(cRefType); if (PTR_CAST(ossimRpcModel, theImages[img])) { ossimRpcModel* model = PTR_CAST(ossimRpcModel, theImages[img]); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Special case for handling RPC LOS error components // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ossimGpt ptObs(obs.samp,obs.line); theImages[img]->getForwardDeriv(OBS_INIT, ptObs); resid = theImages[img]->getForwardDeriv(EVALUATE, ptG); ossimDpt pWRTx = theImages[img]->getForwardDeriv(P_WRT_X, ptG); ossimDpt pWRTy = theImages[img]->getForwardDeriv(P_WRT_Y, ptG); ossimDpt pWRTz = theImages[img]->getForwardDeriv(P_WRT_Z, ptG); // Form required partials in local frame ossimLsrSpace enu(ptG); NEWMAT::Matrix jECF(3,2); jECF(1,1) = pWRTx.u; jECF(1,2) = pWRTx.v; jECF(2,1) = pWRTy.u; jECF(2,2) = pWRTy.v; jECF(3,1) = pWRTz.u; jECF(3,2) = pWRTz.v; NEWMAT::Matrix jLSR(3,2); jLSR = enu.ecefToLsrRotMatrix()*jECF; ossim_float64 dU_dx = jLSR(1,1); ossim_float64 dU_dy = jLSR(2,1); ossim_float64 dU_dz = jLSR(3,1); ossim_float64 dV_dx = jLSR(1,2); ossim_float64 dV_dy = jLSR(2,2); ossim_float64 dV_dz = jLSR(3,2); // Compute azimuth & elevation angles ossim_float64 den = dU_dy*dV_dx - dV_dy*dU_dx; ossim_float64 dY = dU_dx*dV_dz - dV_dx*dU_dz; ossim_float64 dX = dV_dy*dU_dz - dU_dy*dV_dz; ossim_float64 dy_dH = dY / den; ossim_float64 dx_dH = dX / den; ossim_float64 tAz = atan2(dx_dH, dy_dH); ossim_float64 tEl = atan2(1.0, sqrt(dy_dH*dy_dH+dx_dH*dx_dH)); // Get the terrain surface info required by ossimPositionQualityEvaluator ossimColumnVector3d surfN = hgtRef.getLocalTerrainNormal(ptG); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Currently, the CE/LE must be explicitly set by the // setIntersectionSurfaceAccuracy. When DEM accuracy maintenance // is fully supported, the following call should be used. // bool tCovOK = hgtRef.getHeightCovMatrix(ptG, covECF); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ossim_float64 surfCE; ossim_float64 surfLE; if (theSurfAccRepresentsNoDEM) { //*************************************************************** // RPC_No_DEM_State Demo case // In this case, surfCE90/surfLE90 are interpreted differently: // [1] surfCE90 contains the scale divisor for RPC hgtScale // [2] surfLE90 contains the probability level divisor for // RPC hgtScale to yield a 1-sigma value //*************************************************************** // Reset the surface normal to vertical surfN = surfN.zAligned(); // Set approximate surface CE/LE based on RPC parameters // [1] Assume range (scale) only to be 90% vertical error for now // [2] Assume bias could be used for height ossimRpcModel::rpcModelStruct rpcPar; model->getRpcParameters(rpcPar); ossim_float64 hgtRng = rpcPar.hgtScale; surfCE = 0.0; ossim_float64 scaledHgtRng = abs(hgtRng/theSurfCE90); ossim_float64 scaled1SigmaHgtRng = abs(scaledHgtRng/theSurfLE90); surfLE = scaled1SigmaHgtRng*1.6449; if(traceDebug()) { ossimNotify(ossimNotifyLevel_INFO) << "\n computeSingleInterCov() RPC NoDEM state selected..." << "\n RPC Height Scale = " << rpcPar.hgtScale <<" m" << "\n Scale Divisor = " <getBiasError(),model->getRandError(), tEl,tAz,surfN,surfCovENU); NEWMAT::Matrix covENU(3,3); covOK = qev.getCovMatrix(covENU); // Transform to ECF for output if (covOK) { covMat = enu.lsrToEcefRotMatrix()*covENU*enu.ecefToLsrRotMatrix(); } } else { covOK = false; } } else { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Standard covariance matrix formation // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Image contribution covOK = getGroundObsEqComponents(img, obs, ptG, resid, B, W); BtWB << B.t() * W * B; // Height contribution NEWMAT::Matrix St(3,3); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Currently, the CE/LE must be explicitly set by the // setIntersectionSurfaceAccuracy. When DEM accuracy maintenance // is fully supported, the following call should be used. // hgtRef.getHeightCovMatrix(ptG, St); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Check for special case of "no DEM" error propagation, only used for RPC if (theSurfAccRepresentsNoDEM) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_INFO) << "\n computeSingleInterCov() RPC NoDEM state selected..." << " Not valid for this sensor model" << std::endl; } } if (hgtRef.getSurfaceCovMatrix(theSurfCE90, theSurfLE90, surfCovENU)) { tCovOK = hgtRef.getSurfaceNormalCovMatrix(ptG, surfCovENU, St); } else { tCovOK = false; } if (tCovOK) { NEWMAT::Matrix Sti = invert(St); // Full ECF covariance matrix covMat = invert(BtWB + Sti); } else { // Don't include height covMat = invert(BtWB); } } return covOK; } //***************************************************************************** // METHOD: ossimSensorModelTuple::invert() // // Perform SVD matrix inversion. // //***************************************************************************** NEWMAT::Matrix ossimSensorModelTuple::invert(const NEWMAT::Matrix& m) const { ossim_uint32 idx = 0; NEWMAT::DiagonalMatrix d; NEWMAT::Matrix u; NEWMAT::Matrix v; // decompose m.t*m into the singular values and vectors. NEWMAT::SVD(m, d, u, v, true, true); // invert the diagonal for(idx=0; idx < (ossim_uint32)d.Ncols(); ++idx) { if(d[idx] > 1e-14) //TBC : use DBL_EPSILON ? { d[idx] = 1.0/d[idx]; } else { d[idx] = 0.0; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "DEBUG: ossimSensorModelTuple::invert(): " << "\nsingular matrix in SVD..." << std::endl; } } } //compute inverse of decomposed m; return v*d*u.t(); } ossim-Miami-2.9.1/src/projection/ossimSinusoid.c000066400000000000000000000344001352751253100216730ustar00rootroot00000000000000/***************************************************************************/ /* RSC IDENTIFIER: SINUSOIDAL * * ABSTRACT * * This component provides conversions between Geodetic coordinates * (latitude and longitude in radians) and Sinusoid projection coordinates * (easting and northing in meters). * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid value * is found, the error code is combined with the current error code using * the bitwise or. This combining allows multiple error codes to be * returned. The possible error codes are: * * SINU_NO_ERROR : No errors occurred in function * SINU_LAT_ERROR : Latitude outside of valid range * (-90 to 90 degrees) * SINU_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees) * SINU_EASTING_ERROR : Easting outside of valid range * (False_Easting +/- ~20,000,000 m, * depending on ellipsoid parameters) * SINU_NORTHING_ERROR : Northing outside of valid range * (False_Northing +/- ~10,000,000 m, * depending on ellipsoid parameters) * SINU_CENT_MER_ERROR : Origin longitude outside of valid range * (-180 to 360 degrees) * SINU_A_ERROR : Semi-major axis less than or equal to zero * SINU_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * * REUSE NOTES * * SINUSOIDAL is intended for reuse by any application that performs a * Sinusoid projection or its inverse. * * REFERENCES * * Further information on SINUSOIDAL can be found in the Reuse Manual. * * SINUSOIDAL originated from : U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * SINUSOIDAL has no restrictions. * * ENVIRONMENT * * SINUSOIDAL was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC, version 2.8.1 * 2. Windows 95 with MS Visual C++, version 6 * * MODIFICATIONS * * Date Description * ---- ----------- * 7-15-99 Original Code * */ /***************************************************************************/ /* * INCLUDES */ #include #include /* * math.h - Standard C math library * sinusoid.h - Is for prototype error checking */ /***************************************************************************/ /* * DEFINES */ #define PI 3.14159265358979323e0 /* PI */ #define PI_OVER_2 (PI / 2.0) #define TWO_PI (2.0 * PI) #define SINU_COEFF_TIMES_SIN(coeff, x, latit) (coeff * sin(x * latit)) #define FLOAT_EQ(x,v,epsilon) (((v - epsilon) < x) && (x < (v + epsilon))) /***************************************************************************/ /* * GLOBALS */ /* Ellipsoid Parameters, default to WGS 84 */ static double Sinu_a = 6378137.0; /* Semi-major axis of ellipsoid in meters */ static double Sinu_f = 1 / 298.257223563; /* Flattening of ellipsoid */ static double es2 = 0.0066943799901413800; /* Eccentricity (0.08181919084262188000) squared */ static double es4 = 4.4814723452405e-005; /* es2 * es2 */ static double es6 = 3.0000678794350e-007; /* es4 * es2 */ static double c0 = .99832429845280; /* 1 - es2 / 4.0 - 3.0 * es4 / 64.0 - 5.0 * es6 / 256.0 */ static double c1 = .0025146070605187; /* 3.0 * es2 / 8.0 + 3.0 * es4 / 32.0 + 45.0 * es6 / 1024.0 */ static double c2 = 2.6390465943377e-006; /* 15.0 * es4 / 256.0 + 45.0 * es6 / 1024.0 */ static double c3 = 3.4180460865959e-009; /* 35.0 * es6 / 3072.0 */ static double a0 = .0025188265843907; /* 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0 */ static double a1 = 3.7009490356205e-006; /* 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0 */ static double a2 = 7.4478137675038e-009; /* 151.0 * e3 / 96.0 */ static double a3 = 1.7035993238596e-011; /* 1097.0 * e4 / 512.0 */ /* Sinusoid projection Parameters */ static double Sinu_Origin_Long = 0.0; /* Longitude of origin in radians */ static double Sinu_False_Northing = 0.0; /* False northing in meters */ static double Sinu_False_Easting = 0.0; /* False easting in meters */ /* Maximum variance for easting and northing values for WGS 84. */ static double Sinu_Max_Easting = 20037509.0; static double Sinu_Min_Easting = -20037509.0; static double Sinu_Delta_Northing = 10001966.0; /* * These state variables are for optimization purposes. The only function * that should modify them is Set_Sinusoidal_Parameters. */ /***************************************************************************/ /* * FUNCTIONS */ long Set_Sinusoidal_Parameters(double a, double f, double Central_Meridian, double False_Easting, double False_Northing) { /* BEGIN Set_Sinusoidal_Parameters */ /* * The function Set_Sinusoidal_Parameters receives the ellipsoid parameters and * Sinusoidal projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise SINU_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double j; double One_MINUS_es2, Sqrt_One_MINUS_es2, e1, e2, e3, e4; double inv_f = 1 / f; long Error_Code = SINU_NO_ERROR; if (a <= 0.0) { /* Semi-major axis must be greater than zero */ Error_Code |= SINU_A_ERROR; } if ((inv_f < 250) || (inv_f > 350)) { /* Inverse flattening must be between 250 and 350 */ Error_Code |= SINU_INV_F_ERROR; } if ((Central_Meridian < -PI) || (Central_Meridian > TWO_PI)) { /* origin longitude out of range */ Error_Code |= SINU_CENT_MER_ERROR; } if (!Error_Code) { /* no errors */ Sinu_a = a; Sinu_f = f; es2 = 2 * Sinu_f - Sinu_f * Sinu_f; es4 = es2 * es2; es6 = es4 * es2; j = 45.0 * es6 / 1024.0; c0 = 1.0 - es2 / 4.0 - 3.0 * es4 / 64.0 - 5.0 * es6 / 256.0; c1 = 3.0 * es2 / 8.0 + 3.0 * es4 / 32.0 + j; c2 = 15.0 * es4 / 256.0 + j; c3 = 35.0 * es6 / 3072.0; One_MINUS_es2 = 1.0 - es2; Sqrt_One_MINUS_es2 = sqrt(One_MINUS_es2); e1 = (1.0 - Sqrt_One_MINUS_es2) / (1.0 + Sqrt_One_MINUS_es2); e2 = e1 * e1; e3 = e2 * e1; e4 = e3 * e1; a0 = 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0 ; a1 = 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0; a2 = 151.0 * e3 / 96.0; a3 = 1097.0 * e4 / 512.0; if (Central_Meridian > PI) Central_Meridian -= TWO_PI; Sinu_Origin_Long = Central_Meridian; Sinu_False_Northing = False_Northing; Sinu_False_Easting = False_Easting; if (Sinu_Origin_Long > 0) { Sinu_Max_Easting = 19926189.0; Sinu_Min_Easting = -20037509.0; } else if (Sinu_Origin_Long < 0) { Sinu_Max_Easting = 20037509.0; Sinu_Min_Easting = -19926189.0; } else { Sinu_Max_Easting = 20037509.0; Sinu_Min_Easting = -20037509.0; } } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Set_Sinusoidal_Parameters */ void Get_Sinusoidal_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing) { /* BEGIN Get_Sinusoidal_Parameters */ /* * The function Get_Sinusoidal_Parameters returns the current ellipsoid * parameters, and Sinusoidal projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Sinu_a; *f = Sinu_f; *Central_Meridian = Sinu_Origin_Long; *False_Easting = Sinu_False_Easting; *False_Northing = Sinu_False_Northing; return; } /* END OF Get_Sinusoidal_Parameters */ long Convert_Geodetic_To_Sinusoidal (double Latitude, double Longitude, double *Easting, double *Northing) { /* BEGIN Convert_Geodetic_To_Sinusoidal */ /* * The function Convert_Geodetic_To_Sinusoidal converts geodetic (latitude and * longitude) coordinates to Sinusoidal projection (easting and northing) * coordinates, according to the current ellipsoid and Sinusoidal projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise SINU_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double slat = sin(Latitude); double sin2lat, sin4lat, sin6lat; double dlam; /* Longitude - Central Meridan */ double mm; double MM; long Error_Code = SINU_NO_ERROR; if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) { /* Latitude out of range */ Error_Code |= SINU_LAT_ERROR; } if ((Longitude < -PI) || (Longitude > TWO_PI)) { /* Longitude out of range */ Error_Code |= SINU_LON_ERROR; } if (!Error_Code) { /* no errors */ dlam = Longitude - Sinu_Origin_Long; if (dlam > PI) { dlam -= TWO_PI; } if (dlam < -PI) { dlam += TWO_PI; } mm = sqrt(1.0 - es2 * slat * slat); sin2lat = SINU_COEFF_TIMES_SIN(c1, 2.0, Latitude); sin4lat = SINU_COEFF_TIMES_SIN(c2, 4.0, Latitude); sin6lat = SINU_COEFF_TIMES_SIN(c3, 6.0, Latitude); MM = Sinu_a * (c0 * Latitude - sin2lat + sin4lat - sin6lat); *Easting = Sinu_a * dlam * cos(Latitude) / mm + Sinu_False_Easting; *Northing = MM + Sinu_False_Northing; } return (Error_Code); } /* END OF Convert_Geodetic_To_Sinusoidal */ long Convert_Sinusoidal_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude) { /* BEGIN Convert_Sinusoidal_To_Geodetic */ /* * The function Convert_Sinusoidal_To_Geodetic converts Sinusoidal projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Sinusoidal projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise SINU_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx; /* Delta easting - Difference in easting (easting-FE) */ double dy; /* Delta northing - Difference in northing (northing-FN) */ double mu; double sin2mu, sin4mu, sin6mu, sin8mu; double sin_lat; long Error_Code = SINU_NO_ERROR; if ((Easting < (Sinu_False_Easting + Sinu_Min_Easting)) || (Easting > (Sinu_False_Easting + Sinu_Max_Easting))) { /* Easting out of range */ Error_Code |= SINU_EASTING_ERROR; } if ((Northing < (Sinu_False_Northing - Sinu_Delta_Northing)) || (Northing > (Sinu_False_Northing + Sinu_Delta_Northing))) { /* Northing out of range */ Error_Code |= SINU_NORTHING_ERROR; } if (!Error_Code) { /* no errors */ dy = Northing - Sinu_False_Northing; dx = Easting - Sinu_False_Easting; mu = dy / (Sinu_a * c0); sin2mu = SINU_COEFF_TIMES_SIN(a0, 2.0, mu); sin4mu = SINU_COEFF_TIMES_SIN(a1, 4.0, mu); sin6mu = SINU_COEFF_TIMES_SIN(a2, 6.0, mu); sin8mu = SINU_COEFF_TIMES_SIN(a3, 8.0, mu); *Latitude = mu + sin2mu + sin4mu + sin6mu + sin8mu; if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ *Latitude = PI_OVER_2; else if (*Latitude < -PI_OVER_2) *Latitude = -PI_OVER_2; if (FLOAT_EQ(fabs(*Latitude),PI_OVER_2,1.0e-8)) *Longitude = Sinu_Origin_Long; else { sin_lat = sin(*Latitude); *Longitude = Sinu_Origin_Long + dx * sqrt(1.0 - es2 * sin_lat * sin_lat) / (Sinu_a * cos(*Latitude)); if (*Longitude > PI) *Longitude -= TWO_PI; if (*Longitude < -PI) *Longitude += TWO_PI; if (*Longitude > PI) /* force distorted values to 180, -180 degrees */ *Longitude = PI; else if (*Longitude < -PI) *Longitude = -PI; } } return (Error_Code); } /* END OF Convert_Sinusoidal_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimSinusoidalProjection.cpp000066400000000000000000000364401352751253100246130ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Sinusoidal projection code. //******************************************************************* // $Id: ossimSinusoidalProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include RTTI_DEF1(ossimSinusoidalProjection, "ossimSinusoidalProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #define SINU_NO_ERROR 0x0000 #define SINU_LAT_ERROR 0x0001 #define SINU_LON_ERROR 0x0002 #define SINU_EASTING_ERROR 0x0004 #define SINU_NORTHING_ERROR 0x0008 #define SINU_CENT_MER_ERROR 0x0020 #define SINU_A_ERROR 0x0040 #define SINU_B_ERROR 0x0080 #define SINU_A_LESS_B_ERROR 0x0100 #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define SINU_COEFF_TIMES_SIN(coeff, x, latit) (coeff * sin(x * latit)) #define FLOAT_EQ(x,v,epsilon) (((v - epsilon) < x) && (x < (v + epsilon))) /***************************************************************************/ /* * FUNCTIONS */ ossimSinusoidalProjection::ossimSinusoidalProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimSinusoidalProjection::ossimSinusoidalProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Sinu_False_Easting = falseEasting; Sinu_False_Northing = falseNorthing; Sinu_Max_Easting = 20037509.0; Sinu_Min_Easting = -20037509.0; Sinu_Delta_Northing = 10001966.0; update(); } void ossimSinusoidalProjection::update() { Set_Sinusoidal_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.lonr(), Sinu_False_Easting, Sinu_False_Northing); theFalseEastingNorthing.x = Sinu_False_Easting; theFalseEastingNorthing.y = Sinu_False_Northing; ossimMapProjection::update(); } void ossimSinusoidalProjection::setFalseEasting(double falseEasting) { Sinu_False_Easting = falseEasting; update(); } void ossimSinusoidalProjection::setFalseNorthing(double falseNorthing) { Sinu_False_Northing = falseNorthing; update(); } void ossimSinusoidalProjection::setDefaults() { Sinu_Max_Easting = 20037509.0; Sinu_Min_Easting = -20037509.0; Sinu_Delta_Northing = 10001966.0; Sinu_False_Easting = 0.0; Sinu_False_Northing = 0.0; } void ossimSinusoidalProjection::setCentralMeridian(double centralMeridian) { Sinu_Origin_Long = centralMeridian; update(); } void ossimSinusoidalProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Sinu_False_Easting = falseEasting; Sinu_False_Northing = falseNorthing; update(); } ossimGpt ossimSinusoidalProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Sinusoidal_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimSinusoidalProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Sinusoidal(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimSinusoidalProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimSinusoidalProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimSinusoidalProjection)) { Sinu_False_Easting = theFalseEastingNorthing.x; Sinu_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimSinusoidalProjection::Set_Sinusoidal_Parameters(double a, double f, double Central_Meridian, double False_Easting, double False_Northing) { /* BEGIN Set_Sinusoidal_Parameters */ /* * The function Set_Sinusoidal_Parameters receives the ellipsoid parameters and * Sinusoidal projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise SINU_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ double j; double One_MINUS_es2, Sqrt_One_MINUS_es2, e1, e2, e3, e4; // double inv_f = 1 / f; long Error_Code = SINU_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= SINU_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= SINU_INV_F_ERROR; // } // if ((Central_Meridian < -M_PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= SINU_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Sinu_a = a; Sinu_f = f; es2 = 2 * Sinu_f - Sinu_f * Sinu_f; es4 = es2 * es2; es6 = es4 * es2; j = 45.0 * es6 / 1024.0; c0 = 1.0 - es2 / 4.0 - 3.0 * es4 / 64.0 - 5.0 * es6 / 256.0; c1 = 3.0 * es2 / 8.0 + 3.0 * es4 / 32.0 + j; c2 = 15.0 * es4 / 256.0 + j; c3 = 35.0 * es6 / 3072.0; One_MINUS_es2 = 1.0 - es2; Sqrt_One_MINUS_es2 = sqrt(One_MINUS_es2); e1 = (1.0 - Sqrt_One_MINUS_es2) / (1.0 + Sqrt_One_MINUS_es2); e2 = e1 * e1; e3 = e2 * e1; e4 = e3 * e1; a0 = 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0 ; a1 = 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0; a2 = 151.0 * e3 / 96.0; a3 = 1097.0 * e4 / 512.0; // if (Central_Meridian > M_PI) // Central_Meridian -= TWO_PI; Sinu_Origin_Long = Central_Meridian; Sinu_False_Northing = False_Northing; Sinu_False_Easting = False_Easting; if (Sinu_Origin_Long > 0) { Sinu_Max_Easting = 19926189.0; Sinu_Min_Easting = -20037509.0; } else if (Sinu_Origin_Long < 0) { Sinu_Max_Easting = 20037509.0; Sinu_Min_Easting = -19926189.0; } else { Sinu_Max_Easting = 20037509.0; Sinu_Min_Easting = -20037509.0; } } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Set_Sinusoidal_Parameters */ void ossimSinusoidalProjection::Get_Sinusoidal_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* BEGIN Get_Sinusoidal_Parameters */ /* * The function Get_Sinusoidal_Parameters returns the current ellipsoid * parameters, and Sinusoidal projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Sinu_a; *f = Sinu_f; *Central_Meridian = Sinu_Origin_Long; *False_Easting = Sinu_False_Easting; *False_Northing = Sinu_False_Northing; return; } /* END OF Get_Sinusoidal_Parameters */ long ossimSinusoidalProjection::Convert_Geodetic_To_Sinusoidal (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Sinusoidal */ /* * The function Convert_Geodetic_To_Sinusoidal converts geodetic (latitude and * longitude) coordinates to Sinusoidal projection (easting and northing) * coordinates, according to the current ellipsoid and Sinusoidal projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise SINU_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double slat = sin(Latitude); double sin2lat, sin4lat, sin6lat; double dlam; /* Longitude - Central Meridan */ double mm; double MM; long Error_Code = SINU_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= SINU_LAT_ERROR; // } // if ((Longitude < -M_PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= SINU_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Sinu_Origin_Long; // if (dlam > M_PI) // { // dlam -= TWO_PI; // } // if (dlam < -M_PI) // { // dlam += TWO_PI; // } mm = sqrt(1.0 - es2 * slat * slat); sin2lat = SINU_COEFF_TIMES_SIN(c1, 2.0, Latitude); sin4lat = SINU_COEFF_TIMES_SIN(c2, 4.0, Latitude); sin6lat = SINU_COEFF_TIMES_SIN(c3, 6.0, Latitude); MM = Sinu_a * (c0 * Latitude - sin2lat + sin4lat - sin6lat); *Easting = Sinu_a * dlam * cos(Latitude) / mm + Sinu_False_Easting; *Northing = MM + Sinu_False_Northing; } return (Error_Code); } /* END OF Convert_Geodetic_To_Sinusoidal */ long ossimSinusoidalProjection::Convert_Sinusoidal_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Sinusoidal_To_Geodetic */ /* * The function Convert_Sinusoidal_To_Geodetic converts Sinusoidal projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Sinusoidal projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise SINU_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx; /* Delta easting - Difference in easting (easting-FE) */ double dy; /* Delta northing - Difference in northing (northing-FN) */ double mu; double sin2mu, sin4mu, sin6mu, sin8mu; double sin_lat; long Error_Code = SINU_NO_ERROR; // if ((Easting < (Sinu_False_Easting + Sinu_Min_Easting)) // || (Easting > (Sinu_False_Easting + Sinu_Max_Easting))) // { /* Easting out of range */ // Error_Code |= SINU_EASTING_ERROR; // } // if ((Northing < (Sinu_False_Northing - Sinu_Delta_Northing)) // || (Northing > (Sinu_False_Northing + Sinu_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= SINU_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ dy = Northing - Sinu_False_Northing; dx = Easting - Sinu_False_Easting; mu = dy / (Sinu_a * c0); sin2mu = SINU_COEFF_TIMES_SIN(a0, 2.0, mu); sin4mu = SINU_COEFF_TIMES_SIN(a1, 4.0, mu); sin6mu = SINU_COEFF_TIMES_SIN(a2, 6.0, mu); sin8mu = SINU_COEFF_TIMES_SIN(a3, 8.0, mu); *Latitude = mu + sin2mu + sin4mu + sin6mu + sin8mu; if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ *Latitude = PI_OVER_2; else if (*Latitude < -PI_OVER_2) *Latitude = -PI_OVER_2; if (FLOAT_EQ(fabs(*Latitude),PI_OVER_2,1.0e-8)) *Longitude = Sinu_Origin_Long; else { sin_lat = sin(*Latitude); *Longitude = Sinu_Origin_Long + dx * sqrt(1.0 - es2 * sin_lat * sin_lat) / (Sinu_a * cos(*Latitude)); // if (*Longitude > M_PI) // *Longitude -= TWO_PI; // if (*Longitude < -M_PI) // *Longitude += TWO_PI; // if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ // *Longitude = M_PI; // else if (*Longitude < -M_PI) // *Longitude = -M_PI; } } return (Error_Code); } /* END OF Convert_Sinusoidal_To_Geodetic */ //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimSinusoidalProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimSinusoidalProjection* p = dynamic_cast(&proj); if (!p) return false; if (!ossim::almostEqual(Sinu_Origin_Long,p->Sinu_Origin_Long)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimSkyBoxLearSensor.cpp000066400000000000000000000253511352751253100236600ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Sonoma //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimSkyBoxLearSensor:debug"); RTTI_DEF1(ossimSkyBoxLearSensor, "ossimSkyBoxLearSensor", ossimSensorModel); enum { PARAM_ADJ_LON_OFFSET = 0, PARAM_ADJ_LAT_OFFSET, PARAM_ADJ_ALTITUDE_OFFSET, PARAM_ADJ_ROLL_OFFSET, PARAM_ADJ_PITCH_OFFSET, PARAM_ADJ_YAW_OFFSET, PARAM_ADJ_FOCAL_LENGTH_OFFSET, PARAM_ADJ_COUNT // here as last paramter for resizing the adjustment list }; ossimSkyBoxLearSensor::ossimSkyBoxLearSensor() { initAdjustableParameters(); theSensorID = "SkyBoxLear"; } void ossimSkyBoxLearSensor::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { ossimDpt f1 (image_point - theRefImgPt); f1.x *= m_pixelSize.x; f1.y *= -m_pixelSize.y; ossimDpt film (f1 - m_principalPoint); // once we have them we can add distortion fixes // here on the film // // now orient the local film point to the ECEF axes // in a north east down lsr space. // ossimColumnVector3d rc_body(film.y, film.x, m_focalLength + computeParameterOffset(PARAM_ADJ_FOCAL_LENGTH_OFFSET)); ossimColumnVector3d rc_ecef = m_ecef2NedInverse*m_air2Ned*rc_body; image_ray.setOrigin(m_adjustedPlatformPosition); ossimEcefVector ecf_ray_dir (rc_ecef); image_ray.setDirection(ecf_ray_dir); } void ossimSkyBoxLearSensor::lineSampeToWorld(const ossimDpt& image_point, ossimGpt& worldPoint) const { ossimEcefRay ray; imagingRay(image_point, ray); ossimElevManager::instance()->intersectRay(ray, worldPoint); } void ossimSkyBoxLearSensor::lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& heightEllipsoid, ossimGpt& worldPt) const { //*** // First establish imaging ray from image point: //*** ossimEcefRay ray; imagingRay(lineSampPt, ray); ossimEcefPoint Pecf (ray.intersectAboveEarthEllipsoid(heightEllipsoid)); worldPt = ossimGpt(Pecf); } void ossimSkyBoxLearSensor::updateModel() { m_adjustedPlatformPosition = ossimGpt(m_platformPositionEllipsoid.latd() + computeParameterOffset(PARAM_ADJ_LAT_OFFSET), m_platformPositionEllipsoid.lond() + computeParameterOffset(PARAM_ADJ_LON_OFFSET), m_platformPositionEllipsoid.height() + computeParameterOffset(PARAM_ADJ_ALTITUDE_OFFSET)); double r = ossim::degreesToRadians(m_roll + computeParameterOffset(PARAM_ADJ_ROLL_OFFSET)); double p = ossim::degreesToRadians(m_pitch + computeParameterOffset(PARAM_ADJ_PITCH_OFFSET) ); double y = ossim::degreesToRadians(m_yaw + computeParameterOffset(PARAM_ADJ_YAW_OFFSET)); NEWMAT::Matrix rollM = ossimMatrix3x3::create(1, 0, 0, 0, cos(r), sin(r), 0, -sin(r), cos(r)); NEWMAT::Matrix pitchM = ossimMatrix3x3::create(cos(p), 0, -sin(p), 0, 1, 0, sin(p), 0, cos(p)); NEWMAT::Matrix yawM = ossimMatrix3x3::create(cos(y), sin(y), 0, -sin(y), cos(y), 0, 0,0,1); m_air2Ned = rollM*pitchM*yawM; double sin_lat = ossim::sind(m_adjustedPlatformPosition.latd()); double cos_lat = ossim::cosd(m_adjustedPlatformPosition.latd()); double sin_lon = ossim::sind(m_adjustedPlatformPosition.lond()); double cos_lon = ossim::cosd(m_adjustedPlatformPosition.lond()); m_ecef2Ned = (ossimMatrix3x3::create(0,0,1,0,1,0,-1,0,0)* ossimMatrix3x3::create(cos_lat, 0, sin_lat, 0,1,0, -sin_lat,0,cos_lat)* ossimMatrix3x3::create(cos_lon,sin_lon,0, -sin_lon, cos_lon, 0, 0, 0, 1)); m_ecef2NedInverse = m_ecef2Ned.t(); double adjustedFocal = m_focalLength + computeParameterOffset(PARAM_ADJ_FOCAL_LENGTH_OFFSET); m_fovIntrack = (atan((theImageSize.y*theRefImgPt.y)/adjustedFocal)); m_fovCrossTrack = (atan((theImageSize.x*theRefImgPt.x)/adjustedFocal)); lineSampleToWorld(theRefImgPt, theRefGndPt); theBoundGndPolygon.resize(4); ossim_float64 w = theImageClipRect.width()*2.0; ossim_float64 h = theImageClipRect.height()*2.0; ossimGpt gpt; lineSampleToWorld(theImageClipRect.ul()+ossimDpt(-w, -h), gpt); theBoundGndPolygon[0] = gpt; lineSampleToWorld(theImageClipRect.ur()+ossimDpt(w, -h), gpt); theBoundGndPolygon[1] = gpt; lineSampleToWorld(theImageClipRect.lr()+ossimDpt(w, h), gpt); theBoundGndPolygon[2] = gpt; lineSampleToWorld(theImageClipRect.ll()+ossimDpt(-w, h), gpt); theBoundGndPolygon[3] = gpt; try { computeGsd(); } catch(...) { } } void ossimSkyBoxLearSensor::initAdjustableParameters() { resizeAdjustableParameterArray(PARAM_ADJ_COUNT); setAdjustableParameter(PARAM_ADJ_LON_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_LON_OFFSET, "lon_offset"); setParameterUnit(PARAM_ADJ_LON_OFFSET, "degrees"); setParameterSigma(PARAM_ADJ_LON_OFFSET, .001); setAdjustableParameter(PARAM_ADJ_LAT_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_LAT_OFFSET, "lat_offset"); setParameterUnit(PARAM_ADJ_LAT_OFFSET, "degrees"); setParameterSigma(PARAM_ADJ_LAT_OFFSET, .001); setAdjustableParameter(PARAM_ADJ_ALTITUDE_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_ALTITUDE_OFFSET, "altitude_offset"); setParameterUnit(PARAM_ADJ_ALTITUDE_OFFSET, "meters"); setParameterSigma(PARAM_ADJ_ALTITUDE_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_ROLL_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_ROLL_OFFSET, "roll_offset"); setParameterUnit(PARAM_ADJ_ROLL_OFFSET, "degrees"); setParameterSigma(PARAM_ADJ_ROLL_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_PITCH_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_PITCH_OFFSET, "pitch_offset"); setParameterUnit(PARAM_ADJ_PITCH_OFFSET, "degrees"); setParameterSigma(PARAM_ADJ_PITCH_OFFSET, 10); setAdjustableParameter(PARAM_ADJ_YAW_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_YAW_OFFSET, "yaw_offset"); setParameterUnit(PARAM_ADJ_YAW_OFFSET, "degrees"); setParameterSigma(PARAM_ADJ_YAW_OFFSET, .04); setAdjustableParameter(PARAM_ADJ_FOCAL_LENGTH_OFFSET, 0.0); setParameterDescription(PARAM_ADJ_FOCAL_LENGTH_OFFSET, "focal_length_offset"); setParameterUnit(PARAM_ADJ_FOCAL_LENGTH_OFFSET, "meters"); setParameterSigma(PARAM_ADJ_FOCAL_LENGTH_OFFSET, .004); } bool ossimSkyBoxLearSensor::loadState(const ossimKeywordlist& kwl, const char* prefix) { theGSD.makeNan(); theRefImgPt.makeNan(); ossimSensorModel::loadState(kwl, prefix); if(getNumberOfAdjustableParameters() < 1) { initAdjustableParameters(); } ossimString image_size = kwl.find(prefix, "image_size"); ossimString pixel_size = kwl.find(prefix, "pixel_size"); ossimString principal_point = kwl.find(prefix, "principal_point"); ossimString focal_length = kwl.find(prefix, "focal_length"); ossimString roll; ossimString pitch; ossimString yaw; ossimString platform_position; m_roll = 0; m_pitch = 0; m_yaw = 0; roll = kwl.find(prefix, "roll"); pitch = kwl.find(prefix, "pitch"); yaw = kwl.find(prefix, "yaw"); platform_position = kwl.find(prefix, "platform_position"); bool result = (!pixel_size.empty()&& !principal_point.empty()&& !focal_length.empty()&& !platform_position.empty()); if(!image_size.empty()) { theImageSize.toPoint(image_size); theRefImgPt = ossimDpt(theImageSize.x*.5, theImageSize.y*.5); theImageClipRect = ossimDrect(0,0,theImageSize.x-1, theImageSize.y-1); } if(theImageClipRect.hasNans()) { theImageClipRect = ossimDrect(0,0,theImageSize.x-1,theImageSize.y-1); } if(theRefImgPt.hasNans()) { theRefImgPt = theImageClipRect.midPoint(); } if(!focal_length.empty()) { m_focalLength = focal_length.toDouble(); } if(!pixel_size.empty()) { m_pixelSize.toPoint(pixel_size); } if(!roll.empty()) { m_roll = roll.toDouble(); } if(!pitch.empty()) { m_pitch = pitch.toDouble(); } if(!yaw.empty()) { m_yaw = yaw.toDouble(); } if(!principal_point.empty()) { m_principalPoint.toPoint(principal_point); } if(!platform_position.empty()) { m_platformPosition.toPoint(platform_position); m_platformPositionEllipsoid = m_platformPosition; double offset = ossimGeoidManager::instance()->offsetFromEllipsoid(m_platformPosition); if(!ossim::isnan(offset)) { m_platformPositionEllipsoid.height(m_platformPosition.height() + offset); } } updateModel(); if(theGSD.isNan()) { try { // This will set theGSD and theMeanGSD. Method throws ossimException. computeGsd(); } catch (const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSkyBoxLearSensor::loadState Caught Exception:\n" << e.what() << std::endl; } } } return result; } bool ossimSkyBoxLearSensor::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimSensorModel::saveState(kwl, prefix); kwl.add(prefix, "roll", ossimString::toString(m_roll), true); kwl.add(prefix, "pitch", ossimString::toString(m_pitch), true); kwl.add(prefix, "yaw", ossimString::toString(m_yaw), true); kwl.add(prefix, "principal_point", m_principalPoint.toString(), true); kwl.add(prefix, "pixel_size", m_pixelSize.toString(), true); kwl.add(prefix, "platform_position",m_platformPosition.toString() ,true); kwl.add(prefix, "focal_length", ossimString::toString(m_focalLength) ,true); kwl.add(prefix, "image_size", theImageSize.toString() ,true); return true; } ossim-Miami-2.9.1/src/projection/ossimSmacCallibrationSystem.cpp000066400000000000000000000052161352751253100250550ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Proecedure for compensation of aerial camera lens distortion // as computed by the Simultaneous Multiframe Analytical Calibration // (SMAC) System: // //******************************************************************* // $Id$ #include #include #include void ossimSmacCallibrationSystem::undistort(const ossimDpt& input, ossimDpt& output)const { double x = input.x - theCenter.x; double y = input.y - theCenter.y; double x2 = x*x; double y2 = y*y; double r = std::sqrt(x2 + y2); double r2 = r*r; double r4 = r2*r2; double r6 = r2*r4; double r8 = r4*r4; double sum = (_symmetricRadialDistortionCoefficients[0] + _symmetricRadialDistortionCoefficients[1]*r2 + _symmetricRadialDistortionCoefficients[2]*r4 + _symmetricRadialDistortionCoefficients[3]*r6 + _symmetricRadialDistortionCoefficients[4]*r8); double DXr = x*(sum); double DYr = y*(sum); double DXd = ((1 + _decenteringDistortionCoefficients[2]*r2 + _decenteringDistortionCoefficients[3]*r4)* (_decenteringDistortionCoefficients[0]*(r2 + 2*x*x) + 2*_decenteringDistortionCoefficients[1]*x*y)); double DYd = ((1 + _decenteringDistortionCoefficients[2]*r2 + _decenteringDistortionCoefficients[3]*r4)* (2*_decenteringDistortionCoefficients[0]*x*y + _decenteringDistortionCoefficients[1]*(r2 + 2*y*y))); output.x = x + DXr + DXd; output.y = y + DYr + DYd; } void ossimSmacCallibrationSystem::test() { // this example was grabbed from a sample callibration report; double k0 = -.2165e-3; double k1 = .4230e-7; double k2 = -.1652e-11; double k3 = .2860e-19; double k4 = .5690e-26; double p1 = -.1483e-6; double p2 = .1558e-6; double p3 = -.1464e-18; double p4 = .1233e-38; ossimSmacCallibrationSystem smac(k0, k1, k2, k3, k4, p1, p2, p3, p4, ossimDpt(.003, -.001)); ossimDpt output; smac.undistort(ossimDpt(62.142, -62.336), output); std::cout << "Input: " << ossimDpt(62.142, -62.336) << std::endl; std::cout << "Output should be close to x = 62.136 and y = -62.332 <====> " << output << std::endl; ossimDpt input = output; std::cout << "Now test the inverse!" << std::endl; smac.distort(input, output); std::cout << "Inverse should be close to " << ossimDpt(62.142, -62.336) << " <=====> " << output << std::endl; } ossim-Miami-2.9.1/src/projection/ossimSonomaSensor.cpp000066400000000000000000000510521352751253100230660ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Sonoma //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimSonomaSensor:debug"); RTTI_DEF1(ossimSonomaSensor, "ossimSonomaSensor", ossimSensorModel); ossimSonomaSensor::ossimSonomaSensor() { m_utmProjection = new ossimUtmProjection; theSensorID = "Sonoma"; m_mount = ossimMatrix4x4::createIdentity(); m_mountInverse = m_mount; initAdjustableParameters(); } void ossimSonomaSensor::imagingRay(const ossimDpt& /* image_point */, ossimEcefRay& /* image_ray */) const { #if 0 ossimColumnVector3d v(image_point.x,image_point.y,1.0); ossimColumnVector3d v2(0,0,0); v2 = m_compositeMatrix*v2; v = m_compositeMatrix*(m_mount*(m_pixelToCamera*v)); ossimEcefVector vec = ossimEcefPoint(v[0], v[1], v[2]) - ossimEcefPoint(v2[0], v2[1], v2[2]); //ossimEcefPoint(v[0], v[1], v[2]) - m_ecefPlatformPosition; vec.normalize(); image_ray.setOrigin(v2); image_ray.setDirection(vec); std::cout << "image ====== " << image_point << std::endl; std::cout << "V2 ====== " << v2 << std::endl; std::cout << "v ====== " << v << std::endl; std::cout << "platform ====== " << m_ecefPlatformPosition << std::endl; #endif #if 0 ossimDpt f1 ((image_point) - theRefImgPt); f1.x *= m_pixelSize.x; f1.y *= -m_pixelSize.y; ossimDpt film (f1 - m_principalPoint); ossimColumnVector3d cam_ray_dir (film.x, film.y, -(m_focalLength+computeParameterOffset(6))); ossimEcefVector ecf_ray_dir (m_compositeMatrix*m_mount*cam_ray_dir); ecf_ray_dir = ecf_ray_dir*(1.0/ecf_ray_dir.magnitude()); image_ray.setOrigin(m_ecefPlatformPosition); image_ray.setDirection(ecf_ray_dir); #endif } void ossimSonomaSensor::lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const { if (!insideImage(image_point)) { worldPoint.makeNan(); worldPoint = extrapolate(image_point, heightEllipsoid); } else { ossimColumnVector3d origin = m_compositeMatrix*ossimColumnVector3d(0,0,0); ossimColumnVector3d v = m_compositeMatrix*(m_mountInverse*(m_pixelToCamera*ossimColumnVector3d(image_point.x, image_point.y, 1.0))); ossimDpt3d rayOrigin(origin[0], origin[1], origin[2]); ossimDpt3d rayDirection(v[0]-origin[0], v[1]-origin[1], v[2]-origin[2]); rayDirection = rayDirection/rayDirection.length(); ossimDpt3d result; double h = heightEllipsoid; if(ossim::isnan(heightEllipsoid)) { h = 0.0; } intersectRayWithHeight(*(m_utmProjection.get()), result, rayOrigin, rayDirection, h); worldPoint = m_utmProjection->inverse(ossimDpt(result.x, result.y)); worldPoint.height(result.z); //*** // First establish imaging ray from image point: //*** // ossimEcefRay ray; // imagingRay(image_point, ray); // ossimEcefPoint Pecf (ray.intersectAboveEarthEllipsoid(heightEllipsoid)); // worldPoint = ossimGpt(Pecf); } } void ossimSonomaSensor::lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const { if(image_point.hasNans()) { gpt.makeNan(); return; } ossimColumnVector3d origin = m_compositeMatrix*ossimColumnVector3d(0,0,0); ossimColumnVector3d v = m_compositeMatrix*(m_mountInverse*(m_pixelToCamera*ossimColumnVector3d(image_point.x, image_point.y, 1.0))); ossimDpt3d rayOrigin(origin[0], origin[1], origin[2]); ossimDpt3d rayDirection(v[0]-origin[0], v[1]-origin[1], v[2]-origin[2]); rayDirection = rayDirection/rayDirection.length(); ossimDpt3d result; // ossim_uint32 iterIdx = 0; intersectRay(*(m_utmProjection.get()), result, rayOrigin, rayDirection); gpt = m_utmProjection->inverse(ossimDpt(result.x, result.y)); gpt.height(result.z); #if 0 //*** // Determine imaging ray and invoke elevation source object's services to // intersect ray with terrain model: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimElevManager::instance()->intersectRay(ray, gpt); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "image_point = " << image_point << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "ray = " << ray << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "gpt = " << gpt << std::endl; } #endif if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::lineSampleToWorld: returning..." << std::endl; return; } void ossimSonomaSensor::updateModel() { ossimGpt gpt = m_platformPositionEllipsoid; m_ecefPlatformPosition = gpt; double r = ossim::degreesToRadians(m_roll); double p = ossim::degreesToRadians(-(90+m_pitch)); double y = ossim::degreesToRadians(m_heading); NEWMAT::Matrix rollM = ossimMatrix4x4(cos(r), -sin(r), 0.0, 0.0, sin(r), cos(r), 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0).getData(); NEWMAT::Matrix pitchM = ossimMatrix4x4(1.0, 0.0, 0.0, 0.0, 0.0, cos(p), -sin(p), 0.0, 0.0, sin(p), cos(p), 0.0, 0.0, 0.0, 0.0, 1.0).getData(); NEWMAT::Matrix headingM = ossimMatrix4x4(cos(y), -sin(y), 0.0, 0.0, sin(y), cos(y), 0.0, 0.0, 0, 0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0).getData(); m_utmProjection->setZone(ossimUtmProjection::computeZone(m_platformPositionEllipsoid)); m_utmProjection->setHemisphere(m_platformPositionEllipsoid.latd()>=0.0?'N':'S'); m_pixelToCamera = ossimMatrix3x3::create(m_pixelSize.x/m_focalLength, 0.0, -(m_pixelSize.x/m_focalLength)*theImageSize.x/2, 0.0, -m_pixelSize.x/m_focalLength, (m_pixelSize.x/m_focalLength)*theImageSize.y/2, 0.0, 0.0,-1.0); ossimDpt utm = m_utmProjection->forward(m_platformPositionEllipsoid); m_compositeMatrixInverse = rollM * pitchM * headingM * ossimMatrix4x4::createTranslationMatrix(-utm.x, -utm.y, -m_platformPositionEllipsoid.height()); m_compositeMatrix = m_compositeMatrixInverse.i(); #if 0 ossimGpt gpt = m_platformPositionEllipsoid; m_ecefPlatformPosition = gpt; double r = ossim::degreesToRadians(m_roll); double p = ossim::degreesToRadians(-(90+m_pitch)); double y = ossim::degreesToRadians(m_heading); NEWMAT::Matrix rollM = ossimMatrix4x4(cos(r), -sin(r), 0.0, 0.0, sin(r), cos(r), 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0).getData(); NEWMAT::Matrix pitchM = ossimMatrix4x4(1.0, 0.0, 0.0, 0.0, 0.0, cos(p), -sin(p), 0.0, 0.0, sin(p), cos(p), 0.0, 0.0, 0.0, 0.0, 1.0).getData(); NEWMAT::Matrix headingM = ossimMatrix4x4(cos(y), -sin(y), 0.0, 0.0, sin(y), cos(y), 0.0, 0.0, 0, 0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0).getData(); ossimLsrSpace lsrSpace(m_ecefPlatformPosition);//,m_heading+computeParameterOffset(4)); NEWMAT::Matrix platformLsrMatrix4x4 = ossimMatrix4x4::createIdentity(); #endif #if 0 // now lets create a UTM axis by creating a derivative at the center // by shift over a few pixels and subtracting // m_utmProjection.setZone(ossimUtmProjection::computeZone(m_platformPositionEllipsoid)); m_utmProjection.setHemisphere(m_platformPositionEllipsoid.latd()>=0.0?'N':'S'); m_utmProjection.setMetersPerPixel(ossimDpt(1.0,1.0)); ossimDpt midPt = m_utmProjection.forward(m_ecefPlatformPosition); ossimDpt rPt = midPt + ossimDpt(10, 0.0); ossimDpt uPt = midPt + ossimDpt(0.0, 10.0); ossimGpt wMidPt = m_utmProjection.inverse(midPt); ossimGpt wRPt = m_utmProjection.inverse(rPt); ossimGpt wUPt = m_utmProjection.inverse(uPt); ossimEcefPoint ecefMidPt = wMidPt; ossimEcefPoint ecefRPt = wRPt; ossimEcefPoint ecefUPt = wUPt; ossimEcefVector east = ecefRPt-ecefMidPt; ossimEcefVector north = ecefUPt-ecefMidPt; east.normalize(); north.normalize(); // now use the lsr space constructors to construct an orthogonal set of axes // lsrSpace = ossimLsrSpace(m_ecefPlatformPosition, east, north, 0); #endif #if 0 NEWMAT::Matrix platformLsrMatrix = lsrSpace.ecefToLsrRotMatrix(); platformLsrMatrix4x4[0][0] = platformLsrMatrix[0][0]; platformLsrMatrix4x4[1][0] = platformLsrMatrix[1][0]; platformLsrMatrix4x4[2][0] = platformLsrMatrix[2][0]; platformLsrMatrix4x4[0][1] = platformLsrMatrix[0][1]; platformLsrMatrix4x4[1][1] = platformLsrMatrix[1][1]; platformLsrMatrix4x4[2][1] = platformLsrMatrix[2][1]; platformLsrMatrix4x4[0][2] = platformLsrMatrix[0][2]; platformLsrMatrix4x4[1][2] = platformLsrMatrix[1][2]; platformLsrMatrix4x4[2][2] = platformLsrMatrix[2][2]; m_compositeMatrix = (rollM*pitchM*headingM*platformLsrMatrix4x4).i(); m_compositeMatrixInverse = m_compositeMatrix.i(); // m_compositeMatrix = ((rollM*pitchM*headingM)*platformLsrMatrix4x4).t()*m_mount; // m_compositeMatrixInverse = m_compositeMatrix.i(); #endif #if 0 platformLsrMatrix4x4[0][0] = platformLsrMatrix[0][0]; platformLsrMatrix4x4[1][0] = platformLsrMatrix[1][0]; platformLsrMatrix4x4[2][0] = platformLsrMatrix[2][0]; platformLsrMatrix4x4[0][1] = platformLsrMatrix[0][1]; platformLsrMatrix4x4[1][1] = platformLsrMatrix[1][1]; platformLsrMatrix4x4[2][1] = platformLsrMatrix[2][1]; platformLsrMatrix4x4[0][2] = platformLsrMatrix[0][2]; platformLsrMatrix4x4[1][2] = platformLsrMatrix[1][2]; platformLsrMatrix4x4[2][2] = platformLsrMatrix[2][2]; NEWMAT::Matrix m = (platformLsrMatrix4x4*(ossimMatrix4x4::createRotationZMatrix(r)*ossimMatrix4x4::createRotationXMatrix(p)*ossimMatrix4x4::createRotationZMatrix(y)))* ossimMatrix4x4::createTranslationMatrix(-m_ecefPlatformPosition.x(), -m_ecefPlatformPosition.y(), -m_ecefPlatformPosition.z()); m_compositeMatrixInverse = m; m_compositeMatrix = m.i(); NEWMAT::Matrix pixelToCamera = NEWMAT::Matrix(3, 3); double f = m_focalLength/m_pixelSize.x; double w = theImageClipRect.width(); double h = theImageClipRect.height(); pixelToCamera << f << 0 << (-f*w/2.0) << 0 << -f << (f*h/2.0) << 0 << 0 <<-1; pixelToCamera = pixelToCamera.t(); m_pixelToCamera = pixelToCamera; #endif theBoundGndPolygon.resize(0); #if 0 theBoundGndPolygon.resize(4); ossim_float64 w2 = theImageClipRect.width()*2; ossim_float64 h2 = theImageClipRect.height()*2; lineSampleToWorld(theImageClipRect.ul()+ossimDpt(-w2, -h2), gpt); // std::cout << "gpt1 = " << gpt << std::endl; theBoundGndPolygon[0] = gpt; lineSampleToWorld(theImageClipRect.ur()+ossimDpt(w2, -h2), gpt); // std::cout << "gpt2 = " << gpt << std::endl; theBoundGndPolygon[1] = gpt; lineSampleToWorld(theImageClipRect.lr()+ossimDpt(w2, h2), gpt); theBoundGndPolygon[2] = gpt; // std::cout << "gpt3 = " << gpt << std::endl; lineSampleToWorld(theImageClipRect.ll()+ossimDpt(-w2, h2), gpt); theBoundGndPolygon[3] = gpt; #endif // std::cout << "gpt4 = " << gpt << std::endl; lineSampleToWorld(theRefImgPt, theRefGndPt); // ossimColumnVector3d v(0.0,0.0,1.0); // v = m*(m_mountInverse*(m_pixelToCamera*v)); // ossimEcefVector vec = ossimEcefPoint(v[0], v[1], v[2]) - m_ecefPlatformPosition; // vec.normalize(); // ossimEcefRay image_ray; // image_ray.setOrigin(m_ecefPlatformPosition); // image_ray.setDirection(vec); // ossimEcefPoint Pecf (image_ray.intersectAboveEarthEllipsoid(0.0)); computeGsd(); } void ossimSonomaSensor::initAdjustableParameters() { resizeAdjustableParameterArray(7); setAdjustableParameter(0, 0.0); setParameterDescription(0, "x_offset"); setParameterUnit(0, "meters"); setAdjustableParameter(1, 0.0); setParameterDescription(1, "y_offset"); setParameterUnit(1, "meters"); setAdjustableParameter(2, 0.0); setParameterDescription(2, "roll"); setParameterUnit(2, "degrees"); setAdjustableParameter(3, 0.0); setParameterDescription(3, "pitch"); setParameterUnit(3, "degrees"); setAdjustableParameter(4, 0.0); setParameterDescription(4, "heading"); setParameterUnit(4, "degrees"); setAdjustableParameter(5, 0.0); setParameterDescription(5, "Altitude delta"); setParameterUnit(5, "meters"); setAdjustableParameter(6, 0.0); setParameterDescription(6, "focal length delta"); setParameterUnit(6, "meters"); setParameterSigma(0, 10); setParameterSigma(1, 10); setParameterSigma(2, 1); setParameterSigma(3, 1); setParameterSigma(4, 5); setParameterSigma(5, 100); setParameterSigma(6, 50); } bool ossimSonomaSensor::loadState(const ossimKeywordlist& kwl, const char* prefix) { theGSD.makeNan(); theRefImgPt.makeNan(); ossimSensorModel::loadState(kwl, prefix); if(getNumberOfAdjustableParameters() < 7) { initAdjustableParameters(); } if(theRefImgPt.hasNans()) { theRefImgPt = theImageClipRect.midPoint(); } ossimString mount = kwl.find(prefix, "mount"); ossimString pixel_size = kwl.find(prefix, "pixel_size"); ossimString principal_point = kwl.find(prefix, "principal_point"); ossimString focal_length = kwl.find(prefix, "focal_length"); ossimString roll; ossimString pitch; ossimString heading; ossimString platform_position; m_roll = 0; m_pitch = 0; m_heading = 0; roll = kwl.find(prefix, "roll"); pitch = kwl.find(prefix, "pitch"); heading = kwl.find(prefix, "heading"); platform_position = kwl.find(prefix, "platform_position"); bool result = (!pixel_size.empty()&& !principal_point.empty()&& !focal_length.empty()&& !platform_position.empty()); if(!mount.empty()) { mount = mount.trim(); std::vector values; mount.split(values, " "); bool valid = true; if(values.size() == 9) { m_mount = ossimMatrix3x3::createIdentity(); } else if((values.size() == 16) || (values.size() == 12)) { m_mount = ossimMatrix4x4::createIdentity(); } else { m_mount = ossimMatrix4x4::createIdentity(); m_mountInverse = m_mount; valid = false; } if(valid) { ossim_uint32 idx = 0; ossim_int32 row = -1; for(idx = 0; idx < values.size(); ++idx) { if(idx%4 == 0) ++row; m_mount[row][idx%4] = values[idx].toDouble(); } m_mountInverse = m_mount.i(); } } if(!focal_length.empty()) { m_focalLength = focal_length.toDouble(); } if(!pixel_size.empty()) { m_pixelSize.toPoint(pixel_size); } if(!roll.empty()) { m_roll = roll.toDouble(); } if(!pitch.empty()) { m_pitch = pitch.toDouble(); } if(!heading.empty()) { m_heading = heading.toDouble(); } if(!principal_point.empty()) { m_principalPoint.toPoint(principal_point); } if(!platform_position.empty()) { m_platformPosition.toPoint(platform_position); m_platformPositionEllipsoid = m_platformPosition; double offset = ossimGeoidManager::instance()->offsetFromEllipsoid(m_platformPosition); if(!ossim::isnan(offset)) { m_platformPositionEllipsoid.height(m_platformPosition.height() + offset); } } theImageSize = ossimDpt(theImageClipRect.width(), theImageClipRect.height()); updateModel(); if(theGSD.isNan()) { try { // This will set theGSD and theMeanGSD. Method throws ossimException. computeGsd(); } catch (const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSonomaSensor::loadState Caught Exception:\n" << e.what() << std::endl; } } } return result; } bool ossimSonomaSensor::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimSensorModel::saveState(kwl, prefix); ossimString mount; ossim_int32 rowIdx = 0; ossim_int32 colIdx = 0; for(rowIdx = 0; rowIdx < m_mount.Nrows(); ++rowIdx) { for(colIdx = 0; colIdx < m_mount.Ncols(); ++ colIdx) { mount += (ossimString::toString(m_mount[rowIdx][colIdx]) + " "); } } kwl.add(prefix, "mount", mount.trim(), true); kwl.add(prefix, "roll", ossimString::toString(m_roll), true); kwl.add(prefix, "pitch", ossimString::toString(m_pitch), true); kwl.add(prefix, "heading", ossimString::toString(m_heading), true); kwl.add(prefix, "principal_point", m_principalPoint.toString(), true); kwl.add(prefix, "pixel_size", m_pixelSize.toString(), true); kwl.add(prefix, "platform_position",m_platformPosition.toString() ,true); kwl.add(prefix, "focal_length", ossimString::toString(m_focalLength) ,true); return true; } bool ossimSonomaSensor::intersectRay(const ossimMapProjection& proj, ossimDpt3d& result, ossimDpt3d& origin, ossimDpt3d& dir)const { ossimPlane plane(0.0, 0.0, 1.0, 0.0); static const double CONVERGENCE_THRESHOLD = 0.0001; // meters static const int MAX_NUM_ITERATIONS = 50; double h; // height above ellipsoid bool intersected; ossimDpt3d prev_intersect_pt (origin); ossimDpt3d new_intersect_pt; double distance; bool done = false; int iteration_count = 0; if(dir.hasNans()) { result.makeNan(); return false; } ossimGpt gpt = proj.inverse(ossimDpt(origin.x, origin.y)); // // Loop to iterate on ray intersection with variable elevation surface: // do { // // Intersect ray with ellipsoid inflated by h_ellips: // h = ossimElevManager::instance()->getHeightAboveEllipsoid(gpt); if ( ossim::isnan(h) ) h = 0.0; plane.setOffset(-h); intersected = plane.intersect(new_intersect_pt, origin, dir); if (!intersected) { result.makeNan(); done = true; } else { // // Assign the ground point to the latest iteration's intersection // point: // gpt = proj.inverse(ossimDpt(new_intersect_pt.x, new_intersect_pt.y)); gpt.height(new_intersect_pt.z); result = new_intersect_pt; // // Determine if convergence achieved: // distance = (new_intersect_pt - prev_intersect_pt).length(); if (distance < CONVERGENCE_THRESHOLD) { done = true; } else { prev_intersect_pt = new_intersect_pt; } } iteration_count++; } while ((!done) && (iteration_count < MAX_NUM_ITERATIONS)); return intersected; } bool ossimSonomaSensor::intersectRayWithHeight(const ossimMapProjection& /* proj */, ossimDpt3d& result, ossimDpt3d& origin, ossimDpt3d& dir, double h)const { ossimPlane plane(0.0, 0.0, 1.0, -h); bool intersected = plane.intersect(result, origin, dir); return intersected; } ossim-Miami-2.9.1/src/projection/ossimSpaceObliqueMercatorProjection.cpp000066400000000000000000000273021352751253100265470ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimSpaceObliqueMercatorProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include #define PI_OVER_2 (M_PI/2) #define PI (M_PI) #define TWOPI (2*M_PI) #define HALFPI (M_PI/2.0) #define TOL 1e-7 #define PI_HALFPI 4.71238898038468985766 #define TWOPI_HALFPI 7.85398163397448309610 #define ONE_TOL 1.00000000000001 #define ATOL 1e-50 #define FORTPI 0.78539816339744833 double aasin(double v) { double av; if ((av = fabs(v)) >= 1.) { return (v < 0. ? -HALFPI : HALFPI); } return asin(v); } double aacos(double v) { double av; if ((av = fabs(v)) >= 1.) { return (v < 0. ? PI : 0.); } return acos(v); } double asqrt(double v) { return ((v <= 0) ? 0. : sqrt(v)); } double aatan2(double n, double d) { return ((fabs(n) < ATOL && fabs(d) < ATOL) ? 0. : atan2(n,d)); } static const char* PATH_KW = "path"; static const char* SATELLITE_TYPE_KW = "satellite_type"; #if 0 static const char* ANGLE_OF_INCLINATION_KW = "angle_of_inclination"; static const char* REVOLUTION_TIME_KW = "earth_rev_time"; static const char* EARTH_ROTATION_LENGTH_KW = "earth_rot_length"; static const char* LONGITUDE_ASCENDING_NODE_KW = "lon_ascending_node"; static const char* J_COEFFICIENT_KW = "j_coeff"; static const char* W_COEFFICIENT_KW = "w_coeff"; static const char* Q_COEFFICIENT_KW = "q_coeff"; static const char* T_COEFFICIENT_KW = "t_coeff"; static const char* A2_COEFFICIENT_KW = "a2_coeff"; static const char* A4_COEFFICIENT_KW = "a4_coeff"; static const char* B_COEFFICIENT_KW = "b_coeff"; static const char* C1_COEFFICIENT_KW = "c1_coeff"; static const char* C3_COEFFICIENT_KW = "c3_coeff"; static const char* ECCENTRICITY_KW = "eccentricity"; #endif RTTI_DEF1(ossimSpaceObliqueMercatorProjection, "ossimSpaceObliqueMercatorProjection", ossimMapProjection); //***************************************************************************** // CONSTRUCTOR //***************************************************************************** ossimSpaceObliqueMercatorProjection::ossimSpaceObliqueMercatorProjection (ossimSatelliteType type, double pathNumber, const ossimEllipsoid& ellipsoid) : ossimMapProjection(ellipsoid) { setParameters(type, pathNumber); } //***************************************************************************** // METHOD //***************************************************************************** void ossimSpaceObliqueMercatorProjection::setParameters(ossimSatelliteType type, double path) { thePath = path; theSatelliteType = type; double lam = 0.0; double alf = 0.0; double esc = 0.0; double ess = 0.0; e = theEllipsoid.eccentricity(); es = e*e; one_es = 1- es; rone_es = 1.0/one_es; a = theEllipsoid.a(); switch(theSatelliteType) { case SOM_TYPE_LANDSAT_1: case SOM_TYPE_LANDSAT_2: case SOM_TYPE_LANDSAT_3: { lam0 = RAD_PER_DEG*(128.87 - (360.0/251.0)*path); p22 = 103.2669323; alf = RAD_PER_DEG * 99.092; break; } case SOM_TYPE_LANDSAT_4: case SOM_TYPE_LANDSAT_5: case SOM_TYPE_LANDSAT_7: { lam0 = RAD_PER_DEG*(129.305582487 - (360.0/233.0)*path); p22 = 98.8841202; alf = RAD_PER_DEG * 98.2; break; } } p22 /= 1440.; sa = sin(alf); ca = cos(alf); if (fabs(ca) < 1e-9) ca = 1e-9; esc = es * ca * ca; ess = es * sa * sa; w = (1. - esc) * rone_es; w = w * w - 1.; q = ess * rone_es; t = ess * (2. - es) * rone_es * rone_es; u = esc * rone_es; xj = one_es * one_es * one_es; rlm = PI * (1. / 248. + .5161290322580645); rlm2 = rlm + TWOPI; a2 = a4 = b = c1 = c3 = 0.; seraz0(0.0, 1.0); for (lam = 9.; lam <= 81.0001; lam += 18.) seraz0(lam, 4.0); for (lam = 18; lam <= 72.0001; lam += 18.) seraz0(lam, 2.0); seraz0(90.0, 1.0); a2 /= 30.0; a4 /= 60.0; b /= 30.0; c1 /= 15.0; c3 /= 45.0; update(); } //***************************************************************************** // METHOD //***************************************************************************** void ossimSpaceObliqueMercatorProjection::seraz0(double lam, double mult) { double sdsq, h, s, fc, sd, sq, d__1; lam *= RAD_PER_DEG; sd = sin(lam); sdsq = sd * sd; s = p22 * sa * cos(lam) * sqrt((1. + t * sdsq) / (( 1. + w * sdsq) * (1. + q * sdsq))); d__1 = 1. + q * sdsq; h = sqrt((1. + q * sdsq) / (1. + w * sdsq)) * ((1. + w * sdsq) / (d__1 * d__1) - p22 * ca); sq = sqrt(xj * xj + s * s); b += fc = mult * (h * xj - s * s) / sq; a2 += fc * cos(lam + lam); a4 += fc * cos(lam * 4.); fc = mult * s * (h + xj) / sq; c1 += fc * cos(lam); c3 += fc * cos(lam * 3.); } //***************************************************************************** // METHOD //***************************************************************************** ossimDpt ossimSpaceObliqueMercatorProjection::forward(const ossimGpt &worldPoint) const { ossimGpt gpt = worldPoint; if (theDatum) { if (theDatum->code() != worldPoint.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } ossimDpt xy; int l, nn; double lamt, xlam, sdsq, c, d, s, lamdp, phidp, lampp, tanph, lamtp, cl, sd, sp, fac, sav, tanphi; double phi = gpt.latr(); double lam = gpt.lonr() - lam0; if (phi > HALFPI) phi = HALFPI; else if (phi < -HALFPI) phi = -HALFPI; lampp = phi >= 0. ? HALFPI : PI_HALFPI; tanphi = tan(phi); for (nn = 0;;) { sav = lampp; lamtp = lam + p22 * lampp; cl = cos(lamtp); if (fabs(cl) < TOL) lamtp -= TOL; fac = lampp - sin(lampp) * (cl < 0. ? -HALFPI : HALFPI); for (l = 50; l; --l) { lamt = lam + p22 * sav; if (fabs(c = cos(lamt)) < TOL) lamt -= TOL; xlam = (one_es * tanphi * sa + sin(lamt) * ca) / c; lamdp = atan(xlam) + fac; if (fabs(fabs(sav) - fabs(lamdp)) < TOL) break; sav = lamdp; } if (!l || ++nn >= 3 || (lamdp > rlm && lamdp < rlm2)) break; if (lamdp <= rlm) lampp = TWOPI_HALFPI; else if (lamdp >= rlm2) lampp = HALFPI; } if (l) { sp = sin(phi); phidp = aasin((one_es * ca * sp - sa * cos(phi) * sin(lamt)) / sqrt(1. - es * sp * sp)); tanph = log(tan(FORTPI + .5 * phidp)); sd = sin(lamdp); sdsq = sd * sd; s = p22 * sa * cos(lamdp) * sqrt((1. + t * sdsq) / ((1. + w * sdsq) * (1. + q * sdsq))); d = sqrt(xj * xj + s * s); xy.x = b * lamdp + a2 * sin(2. * lamdp) + a4 * sin(lamdp * 4.) - tanph * s / d; xy.y = c1 * sd + c3 * sin(lamdp * 3.) + tanph * xj / d; } else { xy.makeNan(); return xy; // xy.x = xy.y = 1.0/DBL_EPSILON; // st to large number } xy.x*=a; xy.y*=a; return xy; } //***************************************************************************** // METHOD //***************************************************************************** ossimGpt ossimSpaceObliqueMercatorProjection::inverse(const ossimDpt &projectedPoint) const { int nn; double lamt, sdsq, s, lamdp, phidp, sppsq, dd, sd, sl, fac, scl, sav, spp; double lam, phi; ossimDpt xy = projectedPoint; xy.x/=a; xy.y/=a; lamdp = xy.x / b; nn = 50; do { sav = lamdp; sd = sin(lamdp); sdsq = sd * sd; s = p22 * sa * cos(lamdp) * sqrt((1. + t * sdsq) / ((1. + w * sdsq) * (1. + q * sdsq))); lamdp = xy.x + xy.y * s / xj - a2 * sin( 2. * lamdp) - a4 * sin(lamdp * 4.) - s / xj * ( c1 * sin(lamdp) + c3 * sin(lamdp * 3.)); lamdp /= b; } while (fabs(lamdp - sav) >= TOL && --nn); sl = sin(lamdp); fac = exp(sqrt(1. + s * s / xj / xj) * (xy.y - c1 * sl - c3 * sin(lamdp * 3.))); phidp = 2. * (atan(fac) - FORTPI); dd = sl * sl; if (fabs(cos(lamdp)) < TOL) lamdp -= TOL; spp = sin(phidp); sppsq = spp * spp; lamt = atan(((1. - sppsq * rone_es) * tan(lamdp) * ca - spp * sa * sqrt((1. + q * dd) * (1. - sppsq) - sppsq * u) / cos(lamdp)) / (1. - sppsq * (1. + u))); sl = lamt >= 0. ? 1. : -1.; scl = cos(lamdp) >= 0. ? 1. : -1; lamt -= HALFPI * (1. - scl) * sl; lam = lamt - p22 * lamdp; if (fabs(sa) < TOL) phi = aasin(spp / sqrt(one_es * one_es + es * sppsq)); else phi = atan((tan(lamdp) * cos(lamt) - ca * sin(lamt)) / (one_es * sa)); return ossimGpt(phi*DEG_PER_RAD, (lam+lam0)*DEG_PER_RAD, 0.0, theDatum); } //***************************************************************************** // METHOD //***************************************************************************** void ossimSpaceObliqueMercatorProjection::update() { // theMetersPerPixel.x = 1.0; // theMetersPerPixel.y = 1.0; // theUlEastingNorthing.x = 0.0; // theUlEastingNorthing.y = 0.0; } //***************************************************************************** // METHOD //***************************************************************************** bool ossimSpaceObliqueMercatorProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, PATH_KW, thePath, true); kwl.add(prefix, SATELLITE_TYPE_KW, (int)theSatelliteType, true); return ossimMapProjection::saveState(kwl, prefix); } //***************************************************************************** // METHOD //***************************************************************************** bool ossimSpaceObliqueMercatorProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = true; const char* path = kwl.find(prefix, PATH_KW); const char* type = kwl.find(prefix, SATELLITE_TYPE_KW); if(path) { thePath = ossimString(path).toDouble(); } else { result = false; } if(type) { theSatelliteType = (ossimSatelliteType)ossimString(type).toInt(); } else { result = false; } setParameters(theSatelliteType, thePath); if(result) { result = ossimMapProjection::loadState(kwl, prefix); } else { ossimMapProjection::loadState(kwl, prefix); } return result; } //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimSpaceObliqueMercatorProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimSpaceObliqueMercatorProjection* p = dynamic_cast(&proj); if (!p) return false; if (theSatelliteType != p->theSatelliteType) return false; if (!ossim::almostEqual(thePath,p->thePath)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimSpectraboticsRedEdgeModel.cpp000066400000000000000000000654531352751253100254600ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimSpectraboticsRedEdgeModel:debug"); RTTI_DEF1(ossimSpectraboticsRedEdgeModel, "ossimSpectraboticsRedEdgeModel", ossimSensorModel); #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimSpectraboticsRedEdgeModel.cpp 23562 2015-10-02 13:12:40Z gpotts $"; #endif ossimSpectraboticsRedEdgeModel::ossimSpectraboticsRedEdgeModel() { m_compositeMatrix = ossimMatrix4x4::createIdentity(); m_compositeMatrixInverse = ossimMatrix4x4::createIdentity(); m_roll = 0.0; m_pitch = 0.0; m_heading = 0.0; m_focalLength = 5.5; m_pixelSize = ossimDpt(0.003, 0.003); m_ecefPlatformPosition = ossimGpt(0.0,0.0, 1000.0); m_adjEcefPlatformPosition = ossimGpt(0.0,0.0, 1000.0); theGSD.x = 0.076; theGSD.y = 0.076; theMeanGSD = 0.076; m_fov = 48.8; // degrees m_lensDistortion = new ossimTangentialRadialLensDistortion(); initAdjustableParameters(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSpectraboticsRedEdgeModel::ossimSpectrabotics DEBUG:" << endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG)<< "OSSIM_ID: " << OSSIM_ID << endl; #endif } } ossimSpectraboticsRedEdgeModel::ossimSpectraboticsRedEdgeModel(const ossimDrect& imageRect, const ossimGpt& platformPosition, double roll, double pitch, double heading, const ossimDpt& /* principalPoint */, // in millimeters double focalLength, // in millimeters const ossimDpt& pixelSize) // in millimeters { theImageClipRect = imageRect; theRefImgPt = theImageClipRect.midPoint(); m_compositeMatrix = ossimMatrix4x4::createIdentity(); m_compositeMatrixInverse = ossimMatrix4x4::createIdentity(); m_roll = roll; m_pitch = pitch; m_heading = heading; m_focalLength = focalLength; m_pixelSize = pixelSize; m_ecefPlatformPosition = platformPosition; m_adjEcefPlatformPosition = platformPosition; m_lensDistortion = new ossimTangentialRadialLensDistortion(); initAdjustableParameters(); updateModel(); try { // Method throws ossimException. // computeGsd(); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "ossimSpectrabotics Constructor caught Exception:\n" << e.what() << std::endl; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSpectraboticsRedEdgeModel::ossimSpectrabotics DEBUG:" << endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG)<< "OSSIM_ID: " << OSSIM_ID << endl; #endif } } ossimSpectraboticsRedEdgeModel::ossimSpectraboticsRedEdgeModel(const ossimSpectraboticsRedEdgeModel& src) :ossimSensorModel(src) { initAdjustableParameters(); if(src.m_lensDistortion.valid()) { m_lensDistortion = new ossimTangentialRadialLensDistortion(*(src.m_lensDistortion.get())); } else { m_lensDistortion = new ossimTangentialRadialLensDistortion(); } } ossimObject* ossimSpectraboticsRedEdgeModel::dup()const { return new ossimSpectraboticsRedEdgeModel(*this); } void ossimSpectraboticsRedEdgeModel::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSpectraboticsRedEdgeModel::imagingRay: ..... entered" << std::endl; } ossimDpt film (image_point.x-m_calibratedCenter.x, m_calibratedCenter.y - image_point.y); //- theRefImgPt); // ossimDpt film (image_point-m_calibratedCenter); //- theRefImgPt); if(m_lensDistortion.valid()) { ossimDpt tempFilm(film.x/m_norm, film.y/m_norm); ossimDpt filmOut; m_lensDistortion->undistort(tempFilm, filmOut); film.x = filmOut.x*m_norm; film.y = filmOut.y*m_norm; } film.x *= m_pixelSize.x; // pixel size on the film film.y *= m_pixelSize.y; // pixel size on the film ossimColumnVector3d cam_ray_dir (film.x, film.y, -m_focalLength); ossimEcefVector ecf_ray_dir (m_compositeMatrix*cam_ray_dir); ecf_ray_dir = ecf_ray_dir*(1.0/ecf_ray_dir.magnitude()); image_ray.setOrigin(m_adjEcefPlatformPosition); image_ray.setDirection(ecf_ray_dir); } void ossimSpectraboticsRedEdgeModel::lineSampleToWorld(const ossimDpt& image_point, ossimGpt& gpt) const { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpectraboticsRedEdgeModel::lineSampleToWorld:entering..." << std::endl; if(image_point.hasNans()) { gpt.makeNan(); return; } //*** // Extrapolate if image point is outside image: //*** // if (!insideImage(image_point)) // { // gpt.makeNan(); // gpt = extrapolate(image_point); // return; // } //*** // Determine imaging ray and invoke elevation source object's services to // intersect ray with terrain model: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimElevManager::instance()->intersectRay(ray, gpt); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "image_point = " << image_point << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "ray = " << ray << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "gpt = " << gpt << std::endl; } if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSensorModel::lineSampleToWorld: returning..." << std::endl; return; } void ossimSpectraboticsRedEdgeModel::lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const { // if (!insideImage(image_point)) // { // worldPoint.makeNan(); // worldPoint = extrapolate(image_point, heightEllipsoid); // } // else { //*** // First establish imaging ray from image point: //*** ossimEcefRay ray; imagingRay(image_point, ray); ossimEcefPoint Pecf (ray.intersectAboveEarthEllipsoid(heightEllipsoid)); worldPoint = ossimGpt(Pecf); } } void ossimSpectraboticsRedEdgeModel::worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const { #if 0 if((theBoundGndPolygon.getNumberOfVertices() > 0)&& (!theBoundGndPolygon.hasNans())) { if (!(theBoundGndPolygon.pointWithin(world_point))) { // image_point.makeNan(); // image_point = extrapolate(world_point); // return; } } #endif ossimEcefPoint g_ecf(world_point); ossimEcefVector ecfRayDir(g_ecf - m_adjEcefPlatformPosition); ossimColumnVector3d camRayDir (m_compositeMatrixInverse*ecfRayDir.data()); double scale = -m_focalLength/camRayDir[2]; ossimDpt film (scale*camRayDir[0], scale*camRayDir[1]); film.x /= m_pixelSize.x; // get into pixel coordinates film.y /= m_pixelSize.y; // now distort to find the true image coordinate location if (m_lensDistortion.valid()) { ossimDpt filmOut; film.x /= m_norm; // normalize radial film.y /= m_norm; m_lensDistortion->distort(film, filmOut); film = filmOut;//+m_lensDistortion->getCenter(); film.x *= m_norm; film.y *= m_norm; } // invert Y to get back to left handed image space ossimDpt f1(film.x+m_calibratedCenter.x, m_calibratedCenter.y-film.y); image_point = f1; } void ossimSpectraboticsRedEdgeModel::updateModel() { ossimGpt gpt; ossimGpt wgs84Pt; double metersPerDegree = wgs84Pt.metersPerDegree().x; double degreePerMeter = 1.0/metersPerDegree; double latShift = computeParameterOffset(1)*theMeanGSD*degreePerMeter; double lonShift = computeParameterOffset(0)*theMeanGSD*degreePerMeter; gpt = m_ecefPlatformPosition; double height = gpt.height(); gpt.height(height + computeParameterOffset(5)); gpt.latd(gpt.latd() + latShift); gpt.lond(gpt.lond() + lonShift); m_adjEcefPlatformPosition = gpt; ossimLsrSpace lsrSpace(m_adjEcefPlatformPosition); NEWMAT::Matrix heading = ossimMatrix4x4::createRotationZMatrix(m_heading+computeParameterOffset(4), OSSIM_RIGHT_HANDED); NEWMAT::Matrix roll = ossimMatrix4x4::createRotationYMatrix(m_roll+computeParameterOffset(2), OSSIM_RIGHT_HANDED); NEWMAT::Matrix pitch = ossimMatrix4x4::createRotationXMatrix(m_pitch+computeParameterOffset(3), OSSIM_LEFT_HANDED); ossimMatrix4x4 lsrMatrix(lsrSpace.lsrToEcefRotMatrix()); NEWMAT::Matrix orientation = heading*pitch*roll;//roll*pitch*heading; m_compositeMatrix = (lsrMatrix.getData()*orientation); m_compositeMatrixInverse = m_compositeMatrix.i(); theBoundGndPolygon.resize(4); // ossim_float64 w = theImageClipRect.width()*2.0; // ossim_float64 h = theImageClipRect.height()*2.0; theExtrapolateImageFlag = false; theExtrapolateGroundFlag = false; lineSampleToWorld(theImageClipRect.ul(),gpt);//+ossimDpt(-w, -h), gpt); theBoundGndPolygon[0] = gpt; lineSampleToWorld(theImageClipRect.ur(),gpt);//+ossimDpt(w, -h), gpt); theBoundGndPolygon[1] = gpt; lineSampleToWorld(theImageClipRect.lr(),gpt);//+ossimDpt(w, h), gpt); theBoundGndPolygon[2] = gpt; lineSampleToWorld(theImageClipRect.ll(),gpt);//+ossimDpt(-w, h), gpt); theBoundGndPolygon[3] = gpt; } void ossimSpectraboticsRedEdgeModel::initAdjustableParameters() { resizeAdjustableParameterArray(6); setAdjustableParameter(0, 0.0); setParameterDescription(0, "x_offset"); setParameterUnit(0, "pixels"); setAdjustableParameter(1, 0.0); setParameterDescription(1, "y_offset"); setParameterUnit(1, "pixels"); setAdjustableParameter(2, 0.0); setParameterDescription(2, "roll"); setParameterUnit(2, "degrees"); setAdjustableParameter(3, 0.0); setParameterDescription(3, "pitch"); setParameterUnit(3, "degrees"); setAdjustableParameter(4, 0.0); setParameterDescription(4, "heading"); setParameterUnit(4, "degrees"); setAdjustableParameter(5, 0.0); setParameterDescription(5, "altitude"); setParameterUnit(5, "meters"); setParameterSigma(0, 50.0); setParameterSigma(1, 50.0); setParameterSigma(2, 1); setParameterSigma(3, 1); setParameterSigma(4, 10); setParameterSigma(5, 50); } void ossimSpectraboticsRedEdgeModel::setPrincipalPoint(ossimDpt principalPoint) { m_principalPoint = principalPoint; } void ossimSpectraboticsRedEdgeModel::setRollPitchHeading(double roll, double pitch, double heading) { m_roll = roll; m_pitch = pitch; m_heading = heading; updateModel(); } void ossimSpectraboticsRedEdgeModel::setPixelSize(const ossimDpt& pixelSize) { m_pixelSize = pixelSize; } void ossimSpectraboticsRedEdgeModel::setImageRect(const ossimDrect& rect) { theImageClipRect = rect; theRefImgPt = rect.midPoint(); } void ossimSpectraboticsRedEdgeModel::setFocalLength(double focalLength) { m_focalLength = focalLength; } void ossimSpectraboticsRedEdgeModel::setPlatformPosition(const ossimGpt& gpt) { theRefGndPt = gpt; m_ecefPlatformPosition = gpt; updateModel(); } bool ossimSpectraboticsRedEdgeModel::saveState(ossimKeywordlist& kwl, const char* prefix) const { ossimSensorModel::saveState(kwl, prefix); kwl.add(prefix, "type", "ossimSpectraboticsRedEdgeModel", true); kwl.add(prefix, "roll", m_roll, true); kwl.add(prefix, "pitch", m_pitch, true); kwl.add(prefix, "heading", m_heading, true); kwl.add(prefix, "principal_point", ossimString::toString(m_principalPoint.x) + " " + ossimString::toString(m_principalPoint.y)); kwl.add(prefix, "pixel_size", ossimString::toString(m_pixelSize.x) + " " + ossimString::toString(m_pixelSize.y)); kwl.add(prefix, "focal_length", m_focalLength); kwl.add(prefix, "field_of_view", m_fov); kwl.add(prefix, "cx", m_calibratedCenter.x); kwl.add(prefix, "cy", m_calibratedCenter.y); kwl.add(prefix, "fx", m_focalX); kwl.add(prefix, "fy", m_focalY); kwl.add(prefix, "ecef_platform_position", ossimString::toString(m_ecefPlatformPosition.x()) + " " + ossimString::toString(m_ecefPlatformPosition.y()) + " " + ossimString::toString(m_ecefPlatformPosition.z())); if(m_lensDistortion.valid()) { m_lensDistortion->saveState(kwl, prefix); } return true; } bool ossimSpectraboticsRedEdgeModel::loadState(const ossimKeywordlist& kwl, const char* prefix) { if(traceDebug()) { std::cout << "ossimSpectraboticsRedEdgeModel::loadState: ......... entered" << std::endl; } //ossimSensorModel::loadState(kwl,prefix); ossimSensorModel::loadState(kwl, prefix); if(getNumberOfAdjustableParameters() < 1) { initAdjustableParameters(); } m_ecefPlatformPosition = ossimGpt(0.0,0.0,1000.0); m_adjEcefPlatformPosition = ossimGpt(0.0,0.0,1000.0); m_roll = 0.0; m_pitch = 0.0; m_heading = 0.0; // bool computeGsdFlag = false; const char* roll = kwl.find(prefix, "Roll"); const char* pitch = kwl.find(prefix, "Pitch"); const char* heading = kwl.find(prefix, "Yaw"); const char* focalLength = kwl.find(prefix, "Focal Length"); const char* imageWidth = kwl.find(prefix, "Image Width"); const char* imageHeight = kwl.find(prefix, "Image Height"); const char* fov = kwl.find(prefix, "Field Of View"); const char* gpsPos = kwl.find(prefix, "GPS Position"); const char* gpsAlt = kwl.find(prefix, "GPS Altitude"); const char* imageCenter = kwl.find(prefix, "Image Center"); const char* fx = kwl.find(prefix, "fx"); const char* fy = kwl.find(prefix, "fy"); const char* cx = kwl.find(prefix, "cx"); const char* cy = kwl.find(prefix, "cy"); const char* k = kwl.find(prefix, "k"); const char* p = kwl.find(prefix, "p"); bool result = true; #if 0 std::cout << "roll: " << roll << "\n"; std::cout << "pitch: " << pitch << "\n"; std::cout << "heading: " << heading << "\n"; std::cout << "focalLength: " << focalLength << "\n"; std::cout << "imageWidth: " << imageWidth << "\n"; std::cout << "imageHeight: " << imageHeight << "\n"; // std::cout << "fov: " << fov << "\n"; std::cout << "gpsPos: " << gpsPos << "\n"; std::cout << "gpsAlt: " << gpsAlt << "\n"; #endif // if(k&&p) { m_lensDistortion = new ossimTangentialRadialLensDistortion(); m_lensDistortion->loadState(kwl, prefix); } if(roll&& pitch&& heading&& focalLength&& imageWidth&& imageHeight&& gpsPos&& gpsAlt) { theSensorID = "MicaSense RedEdge"; m_roll = ossimString(roll).toDouble(); m_pitch = ossimString(pitch).toDouble(); m_heading = ossimString(heading).toDouble(); m_focalLength = ossimString(focalLength).toDouble(); m_fov = fov?ossimString(fov).toDouble():48.8; theImageSize.x = ossimString(imageWidth).toDouble(); theImageSize.y = ossimString(imageHeight).toDouble(); theImageClipRect = ossimDrect(0,0,theImageSize.x-1,theImageSize.y-1); theRefImgPt = ossimDpt(theImageSize.x/2.0, theImageSize.y/2.0); m_calibratedCenter = theImageClipRect.midPoint(); // now lets use the field of view and the focal length to // calculate the pixel size on the ccd in millimeters double d = tan((m_fov*0.5)*M_PI/180.0)*m_focalLength; d*=2.0; double tempRadiusPixel = theImageSize.length(); m_pixelSize.x = (d)/tempRadiusPixel; m_pixelSize.y = m_pixelSize.x; if(imageCenter) { std::vector splitString; ossimString tempString(imageCenter); tempString.split(splitString, ossimString(" ")); if(splitString.size() == 2) { theRefImgPt = ossimDpt(splitString[0].toDouble(), splitString[1].toDouble()); } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No Image Center found" << std::endl; // result = false; } } // now extract the GPS position and shift it to the ellipsoidal height. std::vector splitArray; ossimString(gpsPos).split(splitArray, ","); splitArray[0] = splitArray[0].replaceAllThatMatch("deg", " "); splitArray[1] = splitArray[1].replaceAllThatMatch("deg", " "); ossimDms dmsLat; ossimDms dmsLon; double h = ossimString(gpsAlt).toDouble(); dmsLat.setDegrees(splitArray[0]); dmsLon.setDegrees(splitArray[1]); double lat = dmsLat.getDegrees(); double lon = dmsLon.getDegrees(); h = h+ossimGeoidManager::instance()->offsetFromEllipsoid(ossimGpt(lat,lon)); m_ecefPlatformPosition = ossimGpt(lat,lon,h); // double height1 = ossimElevManager::instance()->getHeightAboveEllipsoid(ossimGpt(lat, lon)); //std::cout << "PLATFORM HEIGHT: " << h << "\n" // << "ELEVATION: " << height1 << "\n"; // std::cout << m_ecefPlatformPosition << std::endl; // std::cout << "POINT: " << ossimGpt(lat,lon,h) << std::endl; // std::cout << "MSL: " << height1 << "\n"; theRefGndPt = m_ecefPlatformPosition; theRefGndPt.height(0.0); m_norm = ossim::nan(); // lens parameters if(m_lensDistortion.valid()&&cx&&cy&&fx&&fy) { m_focalX = ossimString(fx).toDouble(); m_focalY = ossimString(fy).toDouble(); // our lens distorion assume center point. So // lets shift to center and then set calibrated relative to // image center. We will then normalize. // ossimDpt focal(m_focalX,m_focalY); m_norm = focal.length()*0.5; // convert from diameter to radial m_calibratedCenter = ossimDpt(ossimString(cx).toDouble(), ossimString(cy).toDouble()); m_principalPoint = m_calibratedCenter-theImageClipRect.midPoint(); m_principalPoint.x /= m_norm; m_principalPoint.y /= m_norm; // lets initialize the root to be about one pixel norm along the diagonal // and the convergence will be approximately 100th of a pixel. // double temp = m_norm; if(temp < FLT_EPSILON) temp = 1.0; else temp = 1.0/temp; m_lensDistortion->setCenter(m_principalPoint); m_lensDistortion->setDxDy(ossimDpt(temp,temp)); m_lensDistortion->setConvergenceThreshold(temp*0.001); } else { m_lensDistortion = 0; m_calibratedCenter = theImageClipRect.midPoint(); m_norm = theImageSize.length()*0.5; m_principalPoint = ossimDpt(0,0); } updateModel(); } else // load from regular save state { const char* principal_point = kwl.find(prefix, "principal_point"); const char* pixel_size = kwl.find(prefix, "pixel_size"); const char* ecef_platform_position = kwl.find(prefix, "ecef_platform_position"); const char* latlonh_platform_position = kwl.find(prefix, "latlonh_platform_position"); // const char* compute_gsd_flag = kwl.find(prefix, "compute_gsd_flag"); roll = kwl.find(prefix, "roll"); pitch = kwl.find(prefix, "pitch"); heading = kwl.find(prefix, "heading"); fov = kwl.find(prefix, "field_of_view"); focalLength = kwl.find(prefix, "focal_length"); if(roll) { m_roll = ossimString(roll).toDouble(); } if(pitch) { m_pitch = ossimString(pitch).toDouble(); } if(heading) { m_heading = ossimString(heading).toDouble(); } if(cx&&cy) { m_calibratedCenter = ossimDpt(ossimString(cx).toDouble(), ossimString(cy).toDouble()); } if(principal_point) { std::vector splitString; ossimString tempString(principal_point); tempString.split(splitString, ossimString(" ")); if(splitString.size() == 2) { m_principalPoint.x = splitString[0].toDouble(); m_principalPoint.y = splitString[1].toDouble(); } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No principal_point found" << std::endl; // result = false; } } if(pixel_size) { std::vector splitString; ossimString tempString(pixel_size); tempString.split(splitString, ossimString(" ")); if(splitString.size() == 1) { m_pixelSize.x = splitString[0].toDouble(); m_pixelSize.y = m_pixelSize.x; } else if(splitString.size() == 2) { m_pixelSize.x = splitString[0].toDouble(); m_pixelSize.y = splitString[1].toDouble(); } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No pixel size found" << std::endl; // result = false; } } if(ecef_platform_position) { std::vector splitString; ossimString tempString(ecef_platform_position); tempString.split(splitString, ossimString(" ")); if(splitString.size() > 2) { m_ecefPlatformPosition = ossimEcefPoint(splitString[0].toDouble(), splitString[1].toDouble(), splitString[2].toDouble()); } } else if(latlonh_platform_position) { std::vector splitString; ossimString tempString(latlonh_platform_position); tempString.split(splitString, ossimString(" ")); std::string datumString; double lat=0.0, lon=0.0, h=0.0; if(splitString.size() > 2) { lat = splitString[0].toDouble(); lon = splitString[1].toDouble(); h = splitString[2].toDouble(); } m_ecefPlatformPosition = ossimGpt(lat,lon,h); } if(focalLength) { m_focalLength = ossimString(focalLength).toDouble(); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No focal length found" << std::endl; result = false; } } if(fov) { m_fov = ossimString(fov).toDouble(); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "No field of view found" << std::endl; result = false; } } theRefGndPt = m_ecefPlatformPosition; if(m_lensDistortion.valid()&&cx&&cy&&fx&&fy) { m_focalX = ossimString(fx).toDouble(); m_focalY = ossimString(fy).toDouble(); // our lens distorion assume center point. So // lets shift to center and then set calibrated relative to // image center. We will then normalize. // ossimDpt focal(m_focalX,m_focalY); m_norm = focal.length()*0.5; m_calibratedCenter = ossimDpt(ossimString(cx).toDouble(), ossimString(cy).toDouble()); // m_principalPoint = m_calibratedCenter-theImageClipRect.midPoint(); // m_principalPoint.x /= m_norm; // m_principalPoint.y /= m_norm; // lets initialize the root to be about one pixel norm along the diagonal // and the convergence will be approximately 100th of a pixel. // double temp = m_norm; if(temp < FLT_EPSILON) temp = 1.0; else temp = 1.0/temp; m_lensDistortion->setCenter(m_principalPoint); m_lensDistortion->setDxDy(ossimDpt(temp,temp)); m_lensDistortion->setConvergenceThreshold(temp*0.001); } else { m_lensDistortion = 0; } updateModel(); } try { //--- // This will set theGSD and theMeanGSD. Method throws // ossimException. //--- computeGsd(); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "ossimSpectraboticsRedEdgeModel::loadState Caught Exception:\n" << e.what() << std::endl; } // std::cout << "METERS PER PIXEL : " << getMetersPerPixel() << std::endl; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << std::setprecision(15) << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "roll: " << m_roll << std::endl << "pitch: " << m_pitch << std::endl << "heading: " << m_heading << std::endl << "platform: " << m_ecefPlatformPosition << std::endl << "latlon Platform: " << ossimGpt(m_ecefPlatformPosition) << std::endl << "focal len: " << m_focalLength << std::endl << "FOV : " << m_fov << std::endl << "principal: " << m_principalPoint << std::endl << "Ground: " << ossimGpt(m_ecefPlatformPosition) << std::endl; } // ossimGpt wpt; // ossimDpt dpt(100,100); // lineSampleToWorld(dpt, wpt); // std::cout << "dpt: " << dpt << "\n" // << "wpt: " << wpt << "\n"; // worldToLineSample(wpt,dpt); // std::cout << "dpt: " << dpt << "\n" // << "wpt: " << wpt << "\n"; return result; } bool ossimSpectraboticsRedEdgeModel::setupOptimizer(const ossimString& init_file) { ossimKeywordlist kwl; kwl.addFile(init_file.c_str()); return loadState(kwl); } ossim-Miami-2.9.1/src/projection/ossimSpot5Model.cpp000066400000000000000000000612131352751253100224330ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer (ossim port by D. Burken) // // Description: // // Contains definition of class ossimSpot5Model. // //***************************************************************************** // $Id: ossimSpot5Model.cpp 19658 2011-05-26 13:16:06Z gpotts $ #include #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimSpot5Model, "ossimSpot5Model", ossimSensorModel); //--- // Define Trace flags for use within this file: //--- #include static ossimTrace traceExec ("ossimSpot5Model:exec"); static ossimTrace traceDebug ("ossimSpot5Model:debug"); static const ossim_int32 MODEL_VERSION_NUMBER = 1; static const char* PARAM_NAMES[] = { "roll_offset", "pitch_offset", "yaw_offset", "roll_rate", "pitch_rate", "yaw_rate", "focal_length_offset" }; static const char* PARAM_UNITS[] = { "degrees", // degrees "degrees", // degrees "degrees", // degrees "degrees", // degrees/sec "degrees", // degrees/sec "degrees", // degrees/sec "unknown" }; // percent deviation from nominal static const ossim_float64 SIGMA[] = { 0.0001, // degrees 0.0001, // degrees 0.0003, // degrees 0.00002, // delta degrees 0.00002, // delta degrees 0.00005, // delta degrees 0.0001 }; // percent ossimSpot5Model::ossimSpot5Model() : ossimSensorModel (), theSupportData (NULL), theMetaDataFile ("NOT ASSIGNED"), theIllumAzimuth (0.0), theIllumElevation (0.0), thePositionError (0.0), theRefImagingTime (0.0), theRefImagingTimeLine (0.0), theLineSamplingPeriod (0.0), // theSatToOrbRotation (3, 3), // theOrbToEcfRotation (3, 3), theRollOffset (0.0), thePitchOffset (0.0), theYawOffset (0.0), theRollRate (0.0), thePitchRate (0.0), theYawRate (0.0), theFocalLenOffset (0.0) { initAdjustableParameters(); } ossimSpot5Model::ossimSpot5Model(ossimSpotDimapSupportData* sd) : ossimSensorModel (), theSupportData (sd), theMetaDataFile ("NOT ASSIGNED"), theIllumAzimuth (0.0), theIllumElevation (0.0), thePositionError (0.0), theRefImagingTime (0.0), theRefImagingTimeLine (0.0), theLineSamplingPeriod (0.0), // theSatToOrbRotation (3, 3), // theOrbToEcfRotation (3, 3), theRollOffset (0.0), thePitchOffset (0.0), theYawOffset (0.0), theRollRate (0.0), thePitchRate (0.0), theYawRate (0.0), theFocalLenOffset (0.0) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model(dimap_file) Constructor: entering..." << std::endl; //--- // Instantiate the support data classes after establishing the filenames: //--- loadSupportData(); if (getErrorStatus() != ossimErrorCodes::OSSIM_OK) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model(dimap_file) Constructor: returning with error..." << std::endl; return; } //--- // initialize remaining data members: //--- initAdjustableParameters(); updateModel(); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model(dimap_file) Constructor: returning..." << std::endl; } //***************************************************************************** // DESTRUCTOR: ~ossimSpot5Model() // //***************************************************************************** ossimSpot5Model::~ossimSpot5Model() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG DESTRUCTOR: ~ossimSpot5Model(): entering..." << std::endl; theSupportData = 0; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG DESTRUCTOR: ~ossimSpot5Model(): returning..." << std::endl; } ossimSpot5Model::ossimSpot5Model(const ossimSpot5Model& rhs) :ossimSensorModel(rhs) { if(rhs.theSupportData.valid()) { theSupportData = (ossimSpotDimapSupportData*)rhs.theSupportData->dup(); } loadSupportData(); updateModel(); } void ossimSpot5Model::computeSatToOrbRotation(NEWMAT::Matrix& result, ossim_float64 t)const { if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::computeSatToOrbRotation(): entering..." << std::endl; } //--- // Linearly interpolate attitudes angles: //--- ossimDpt3d att; theSupportData->getAttitude(t, att); //--- // Apply the attitude adjustable parameters: //--- double dt = theRefImagingTime - t; att.x += thePitchOffset + dt*thePitchRate; att.y += theRollOffset + dt*theRollRate; att.z += theYawOffset + dt*theYawRate; //--- // Compute trig functions to populate rotation matrices: ANGLES IN RADIANS //--- double cp = cos(att.x); double sp = sin(att.x); double cr = cos(att.y); double sr = sin(att.y); double cy = cos(att.z); double sy = sin(att.z); //--- // Populate rotation matrix: //--- result = NEWMAT::Matrix(3,3); result << (cr*cy) << (-cr*sy) << (-sr) << (cp*sy+sp*sr*cy) << (cp*cy-sp*sr*sy) << (sp*cr) << (-sp*sy+cp*sr*cy) << (-sp*cy-cp*sr*sy) << cp*cr; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::computeSatToOrbRotation(): returning..." << std::endl; } #if 0 //***************************************************************************** // METHOD //***************************************************************************** void ossimSpot5Model::computeSatToOrbRotation(ossim_float64 t)const { if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::computeSatToOrbRotation(): entering..." << std::endl; } //--- // Linearly interpolate attitudes angles: //--- ossimDpt3d att; theSupportData->getAttitude(t, att); //--- // Apply the attitude adjustable parameters: //--- double dt = theRefImagingTime - t; att.x += thePitchOffset + dt*thePitchRate; att.y += theRollOffset + dt*theRollRate; att.z += theYawOffset + dt*theYawRate; //--- // Compute trig functions to populate rotation matrices: ANGLES IN RADIANS //--- double cp = cos(att.x); double sp = sin(att.x); double cr = cos(att.y); double sr = sin(att.y); double cy = cos(att.z); double sy = sin(att.z); //--- // Populate rotation matrix: //--- theSatToOrbRotation = NEWMAT::Matrix(3,3); theSatToOrbRotation << (cr*cy) << (-cr*sy) << (-sr) << (cp*sy+sp*sr*cy) << (cp*cy-sp*sr*sy) << (sp*cr) << (-sp*sy+cp*sr*cy) << (-sp*cy-cp*sr*sy) << cp*cr; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::computeSatToOrbRotation(): returning..." << std::endl; } #endif //***************************************************************************** // PUBLIC METHOD: ossimSpot5Model::updateModel() // // Updates the model parameters given the normalized adjustable parameter // array. // //***************************************************************************** void ossimSpot5Model::updateModel() { clearErrorStatus(); try { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::updateModel(): entering..." << std::endl; if(getNumberOfAdjustableParameters() < 1) { theRollOffset = 0; thePitchOffset = 0; theYawOffset = 0; theRollRate = 0; thePitchRate = 0; theYawRate = 0; theFocalLenOffset = 0; } else { theRollOffset = computeParameterOffset(0); thePitchOffset = computeParameterOffset(1); theYawOffset = computeParameterOffset(2); theRollRate = computeParameterOffset(3); thePitchRate = computeParameterOffset(4); theYawRate = computeParameterOffset(5); theFocalLenOffset = computeParameterOffset(6); } theSeedFunction = 0; ossimGpt ulg, urg, lrg, llg; lineSampleToWorld(theImageClipRect.ul(), ulg); lineSampleToWorld(theImageClipRect.ur(), urg); lineSampleToWorld(theImageClipRect.lr(), lrg); lineSampleToWorld(theImageClipRect.ll(), llg); theSeedFunction = new ossimBilinearProjection(theImageClipRect.ul(), theImageClipRect.ur(), theImageClipRect.lr(), theImageClipRect.ll(), ulg, urg, lrg, llg); if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::updateModel(): returning..." << std::endl; } catch(...) { setErrorStatus(ossimErrorCodes::OSSIM_ERROR); } } void ossimSpot5Model::initAdjustableParameters() { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::initAdjustableParameters(): entering..." << std::endl; //--- // Allocate storage for adjustables and assign their names and units // strings. //--- resizeAdjustableParameterArray(7); ossim_uint32 numParams = getNumberOfAdjustableParameters(); //--- // Initialize base-class adjustable parameter array: //--- for (ossim_uint32 i=0; igetErrorStatus() != ossimErrorCodes::OSSIM_OK) { setErrorStatus(); ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimSpot5Model::loadSupportData(): Bad SpotDimapSupportData detected. Aborting..." << std::endl; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::loadSupportData(): returning..." << std::endl; return; } //--- // Initialize some member variables from the support data: //--- theSensorID = theSupportData->getSensorID(); theImageID = theSupportData->getImageID(); theMetaDataFile = theSupportData->getMetadataFile(); // Center of frame, sub image if we have one. theSupportData->getRefGroundPoint(theRefGndPt); theSupportData->getSunAzimuth(theIllumAzimuth); theSupportData->getSunElevation(theIllumElevation); ossimDpt sz; theSupportData->getImageSize(sz); theImageSize = sz; theSupportData->getRefLineTime(theRefImagingTime); theSupportData->getRefLineTimeLine(theRefImagingTimeLine); theSupportData->getLineSamplingPeriod(theLineSamplingPeriod); theSupportData->getSubImageOffset(theSpotSubImageOffset); //--- // We make this zero base as the base ossimSensorModel does not know about // any sub image we have. //--- theSupportData->getImageRect(theImageClipRect); theSupportData->getRefImagePoint(theRefImgPt); ossimGpt p1; ossimGpt p2; ossimGpt p3; ossimGpt p4; // I need to find the nominal scale of the spot 5 dataset //--- // Position error is a function of whether star tracker information was // available: //--- if (theSupportData->isStarTrackerUsed()) { thePositionError = 50.0; } else { thePositionError = 200.0; // meters } updateModel(); lineSampleToWorld(theImageClipRect.ul(), p1); lineSampleToWorld(theImageClipRect.ur(), p2); lineSampleToWorld(theImageClipRect.lr(), p3); lineSampleToWorld(theImageClipRect.ll(), p4); // theSupportData->getUlCorner(p1); // theSupportData->getUrCorner(p2); // theSupportData->getLrCorner(p3); // theSupportData->getLlCorner(p4); ossimDpt v[4]; // temporarily holds vertices for ground polygon v[0] = p1; v[1] = p2; v[2] = p3; v[3] = p4; theBoundGndPolygon = ossimPolygon(4, v); ossimGpt cgpt, hgpt, vgpt; // ossimEcefPoint hVector, vVector; ossimDpt midpt = theImageClipRect.midPoint(); lineSampleToWorld(midpt, cgpt); lineSampleToWorld(midpt + ossimDpt(1,0), hgpt); lineSampleToWorld(midpt + ossimDpt(0,1), vgpt); theGSD = ossimDpt((ossimEcefPoint(cgpt) - ossimEcefPoint(hgpt)).magnitude(), (ossimEcefPoint(cgpt) - ossimEcefPoint(vgpt)).magnitude()); theMeanGSD = (theGSD.x+theGSD.y)/2.0; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::loadSupportData(): returning..." << std::endl; } ossimObject* ossimSpot5Model::dup() const { return new ossimSpot5Model(*this); } std::ostream& ossimSpot5Model::print(std::ostream& out) const { // Capture stream flags since we are going to mess with them. std::ios_base::fmtflags f = out.flags(); out << "\nDump of ossimSpot5Model at address " << (hex) << this << (dec) << "\n------------------------------------------------" << "\n theImageID = " << theImageID << "\n theMetadataFile = " << theMetaDataFile << "\n theIllumAzimuth = " << theIllumAzimuth << "\n theIllumElevation = " << theIllumElevation << "\n thePositionError = " << thePositionError << "\n theImageSize = " << theImageSize << "\n theRefGndPt = " << theRefGndPt << "\n theRefImgPt = " << theRefImgPt << "\n theRefImagingTime = " << theRefImagingTime << "\n theRefImagingTimeLine = " << theRefImagingTimeLine << "\n theLineSamplingPeriod = " << theLineSamplingPeriod << "\n theRollOffset = " << theRollOffset << "\n thePitchOffset = " << thePitchOffset << "\n theYawOffset = " << theYawOffset << "\n theRollRate = " << theRollRate << "\n thePitchRate = " << thePitchRate << "\n theYawRate = " << theYawRate << "\n theFocalLenOffset = " << theFocalLenOffset << "\n------------------------------------------------" << "\n " << endl; // Set the flags back. out.flags(f); return ossimSensorModel::print(out); } bool ossimSpot5Model::saveState(ossimKeywordlist& kwl, const char* prefix) const { if(theSupportData.valid()) { ossimString supportPrefix = ossimString(prefix) + "support_data."; theSupportData->saveState(kwl, supportPrefix); } else { return false; } return ossimSensorModel::saveState(kwl, prefix); } bool ossimSpot5Model::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString supportPrefix = ossimString(prefix) + "support_data."; if(!theSupportData) { theSupportData = new ossimSpotDimapSupportData; } if(theSupportData->loadState(kwl, supportPrefix)) { if(!ossimSensorModel::loadState(kwl, prefix)) { return false; } } else { return false; } loadSupportData(); updateModel(); return (getErrorStatus()==ossimErrorCodes::OSSIM_OK); } void ossimSpot5Model::imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const { bool runtime_dbflag = 0; NEWMAT::Matrix satToOrbit; ossimDpt iPt = image_point; iPt.samp += theSpotSubImageOffset.samp; iPt.line += theSpotSubImageOffset.line; // // 1. Establish time of line imaging: // double t_line = theRefImagingTime + theLineSamplingPeriod*(iPt.line - theRefImagingTimeLine); if (traceDebug() || runtime_dbflag) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG Spot5Model::imagingRay():------------ BEGIN DEBUG PASS ---------------" << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG Spot5Model::imagingRay(): t_line = " << t_line << std::endl; } // // 2. Interpolate ephemeris position and velocity (in ECF): // ossimEcefPoint tempEcefPoint; ossimEcefPoint P_ecf; theSupportData->getPositionEcf(t_line, P_ecf); theSupportData->getVelocityEcf(t_line, tempEcefPoint); ossimEcefVector V_ecf(tempEcefPoint.x(), tempEcefPoint.y(), tempEcefPoint.z()); if (traceDebug() || runtime_dbflag) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\n\tP_ecf = " << P_ecf << "\n\t V_ecf = " << V_ecf << std::endl; } // // 3. Establish the look direction in Vehicle LSR space (S_sat). // ANGLES IN RADIANS // ossim_float64 Psi_x; theSupportData->getPixelLookAngleX(iPt.samp, Psi_x); ossim_float64 Psi_y; theSupportData->getPixelLookAngleY(iPt.samp, Psi_y); if (traceDebug() || runtime_dbflag) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\n\t Psi_x = " << Psi_x << "\n\t Psi_y = " << Psi_y << endl; } ossimColumnVector3d u_sat (-tan(Psi_y), tan(Psi_x), -(1.0 + theFocalLenOffset)); if (traceDebug() || runtime_dbflag) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG \n\t u_sat = " << u_sat << endl; } // // 4. Transform vehicle LSR space look direction vector to orbital LSR space // (S_orb): // computeSatToOrbRotation(satToOrbit, t_line); ossimColumnVector3d u_orb = (satToOrbit*u_sat).unit(); if (traceDebug() || runtime_dbflag) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\n\t theSatToOrbRotation = " << satToOrbit << "\n\t u_orb = " << u_orb << endl; } // // 5. Transform orbital LSR space look direction vector to ECF. // // a. S_orb space Z-axis (Z_orb) is || to the ECF radial vector (P_ecf), // b. X_orb axis is computed as cross-product between velocity and radial, // c. Y_orb completes the orthogonal S_orb coordinate system. // ossimColumnVector3d Z_orb (P_ecf.x(), P_ecf.y(), P_ecf.z()); Z_orb = Z_orb.unit(); ossimColumnVector3d X_orb = ossimColumnVector3d(V_ecf.x(), V_ecf.y(), V_ecf.z()).cross(Z_orb).unit(); ossimColumnVector3d Y_orb = Z_orb.cross(X_orb); NEWMAT::Matrix orbToEcfRotation = NEWMAT::Matrix(3, 3); orbToEcfRotation << X_orb[0] << Y_orb[0] << Z_orb[0] << X_orb[1] << Y_orb[1] << Z_orb[1] << X_orb[2] << Y_orb[2] << Z_orb[2]; ossimColumnVector3d u_ecf = (orbToEcfRotation*u_orb); if (traceDebug() || runtime_dbflag) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\n\t orbToEcfRotation = " << orbToEcfRotation << "\n\t u_ecf = " << u_ecf << endl; } // // Establish the imaging ray given direction and origin: // image_ray = ossimEcefRay(P_ecf, ossimEcefVector(u_ecf[0], u_ecf[1], u_ecf[2])); if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG Spot5Model::imagingRay(): returning..." << std::endl; } } void ossimSpot5Model::lineSampleHeightToWorld(const ossimDpt& image_point, const ossim_float64& heightEllipsoid, ossimGpt& worldPoint) const { // if (!insideImage(image_point)) if ( !theImageClipRect.pointWithin(image_point, 1.0-FLT_EPSILON) ) { if(theSeedFunction.valid()) { theSeedFunction->lineSampleToWorld(image_point, worldPoint); } else { worldPoint = extrapolate(image_point, heightEllipsoid); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::lineSampleHeightToWorld(): returning..." << std::endl; return; } //*** // First establish imaging ray from image point: //*** ossimEcefRay imaging_ray; imagingRay(image_point, imaging_ray); ossimEcefPoint Pecf (imaging_ray.intersectAboveEarthEllipsoid(heightEllipsoid)); worldPoint = ossimGpt(Pecf); } // ossimDpt ossimSpot5Model::extrapolate (const ossimGpt& gp) const // { // ossimDpt temp; // temp.makeNan(); // return temp; // ossimDpt tempGpt = gp; // ossimDpt dest; // theGroundToImageMap.map(tempGpt, dest); // return dest; // } // ossimGpt ossimSpot5Model::extrapolate (const ossimDpt& ip, // const double& height) const // { // return ossimGpt(ossim::nan(), ossim::nan(), ossim::nan(), 0); // ossimDpt dest; // theImageToGroundMap.map(ip, dest); // return ossimGpt(dest.lat, dest.lon, ossim::nan(), origin().datum()); // } bool ossimSpot5Model::setupOptimizer(const ossimString& init_file) { ossimFilename spot5Test = init_file; ossimFilename geomFile = init_file; geomFile = geomFile.setExtension("geom"); bool tryKwl = false; if(!spot5Test.exists()) { spot5Test = geomFile.path(); spot5Test = spot5Test.dirCat(ossimFilename("METADATA.DIM")); if(spot5Test.exists() == false) { spot5Test = geomFile.path(); spot5Test = spot5Test.dirCat(ossimFilename("metadata.dim")); } } if(spot5Test.exists()) { ossimRefPtr meta = new ossimSpotDimapSupportData; if(meta->loadXmlFile(spot5Test)) { initFromMetadata(meta.get()); if (getErrorStatus()) { tryKwl = true; meta=0; } else { return true; } } else { meta=0; tryKwl = true; } } if(tryKwl) { ossimKeywordlist kwl; if(kwl.addFile(init_file.c_str())) { return loadState(kwl); } } return false; } bool ossimSpot5Model::initFromMetadata(ossimSpotDimapSupportData* sd) { // init parms theSupportData = sd; theMetaDataFile = "NOT ASSIGNED"; theIllumAzimuth = 0.0; theIllumElevation = 0.0; thePositionError = 0.0; theRefImagingTime = 0.0; theLineSamplingPeriod = 0.0; // theSatToOrbRotation = 0.0; //matrix // theOrbToEcfRotation = 0.0; //matrix theRollOffset = 0.0; thePitchOffset = 0.0; theYawOffset = 0.0; theRollRate = 0.0; thePitchRate = 0.0; theYawRate = 0.0; theFocalLenOffset = 0.0; //--- // Instantiate the support data classes after establishing the filenames: //--- loadSupportData(); if (getErrorStatus() != ossimErrorCodes::OSSIM_OK) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimSpot5Model::initFromMetadata(dimap_file): returning with error..." << std::endl; return false; } //--- // initialize remaining data members: //--- initAdjustableParameters(); updateModel(); return true; } ossim-Miami-2.9.1/src/projection/ossimStatePlaneProjectionInfo.cpp000066400000000000000000000244031352751253100253510ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts //******************************************************************* // $Id: ossimStatePlaneProjectionInfo.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include #include #include #include #include #include #include using namespace std; ossimStatePlaneProjectionInfo::ossimStatePlaneProjectionInfo( const std::string& name, int pcsCode, const std::string& projName, const std::string& param1, const std::string& param2, const std::string& param3, const std::string& param4, double falseEast, double falseNorth, const std::string& units, const std::string& datumName) : thePcsCode (pcsCode), theName (name), theProjectionName (projName), theDatum (0), theOriginLat (param1), theOriginLon (param2), theOrigin (), theParameter3 (0.0), theParameter4 (0.0), theFalseEasting (falseEast), theFalseNorthing (falseNorth), theScaleFactor (0.0), theUnits (OSSIM_UNIT_UNKNOWN) { //--- // If the projection name is abreviated, expand to be ossim class name. //--- if (projName == "tm") { theProjectionName = "ossimTransMercatorProjection"; } else if (projName == "lcc") { theProjectionName = "ossimLambertConformalConicProjection"; } // Set the projection specific stuff. if (theProjectionName == "ossimTransMercatorProjection") { theParameter3 = ossimString::toDouble(param3); if(fabs(theParameter3) > FLT_EPSILON) { theScaleFactor = 1.0 - (1.0 / theParameter3); } else { theScaleFactor = 1.0; } } else if (theProjectionName == "ossimLambertConformalConicProjection") { theParameter3 = ossimDms(param3).getDegrees(); theParameter4 = ossimDms(param4).getDegrees(); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimStatePlaneProjectionInfo unhandled projection type: " << projName << std::endl; } theDatum = ossimDatumFactoryRegistry::instance()->create(datumName); if (!theDatum) { ossimNotify(ossimNotifyLevel_WARN) << "ossimStatePlaneProjectionInfo unhandled datum type: " << datumName << std::endl; } theOrigin = ossimGpt(theOriginLat.getDegrees(), theOriginLon.getDegrees(), 0, theDatum); theUnits = static_cast( ossimUnitTypeLut::instance()->getEntryNumber(units.c_str())); // Currently only handle meters and us_survey_feet. if ( (theUnits != OSSIM_METERS) && (theUnits != OSSIM_US_SURVEY_FEET) && (theUnits != OSSIM_FEET) ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimStatePlaneProjectionInfo unhandled unit type: " << units.c_str() << std::endl; } } int ossimStatePlaneProjectionInfo::code() const { return thePcsCode; } const ossimString& ossimStatePlaneProjectionInfo::name() const { return theName; } const ossimString& ossimStatePlaneProjectionInfo::projName() const { return theProjectionName; } double ossimStatePlaneProjectionInfo::originLat() const { return theOriginLat.getDegrees(); } double ossimStatePlaneProjectionInfo::originLon() const { return theOriginLon.getDegrees(); } const ossimDatum* ossimStatePlaneProjectionInfo::datum() const { return theDatum; } ossimGpt ossimStatePlaneProjectionInfo::origin() const { return theOrigin; } double ossimStatePlaneProjectionInfo::parallel1() const { return theParameter3; } double ossimStatePlaneProjectionInfo::parallel2() const { return theParameter4; } double ossimStatePlaneProjectionInfo::falseEasting() const { return theFalseEasting; } double ossimStatePlaneProjectionInfo::falseNorthing() const { return theFalseNorthing; } double ossimStatePlaneProjectionInfo::scaleFactor() const { return theScaleFactor; } ossimString ossimStatePlaneProjectionInfo::units() const { return ossimUnitTypeLut::instance()->getEntryString(theUnits); } bool ossimStatePlaneProjectionInfo::isSameCode(int pcsCode) const { if(pcsCode == thePcsCode) { return true; } return false; } double ossimStatePlaneProjectionInfo::falseEastingInMeters() const { double result = theFalseEasting; switch (theUnits) { case OSSIM_US_SURVEY_FEET: result *= US_METERS_PER_FT; break; case OSSIM_FEET: result *= MTRS_PER_FT; break; default: break; } return result; } double ossimStatePlaneProjectionInfo::falseNorthingInMeters() const { double result = theFalseNorthing; switch (theUnits) { case OSSIM_US_SURVEY_FEET: result *= US_METERS_PER_FT; break; case OSSIM_FEET: result *= MTRS_PER_FT; break; default: break; } return result; } void ossimStatePlaneProjectionInfo::populateProjectionKeywords( ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::PCS_CODE_KW, thePcsCode, true); kwl.add(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW, (ossimUnitTypeLut::instance()->getEntryString(theUnits)), true); ossimDpt pt(theFalseEasting, theFalseNorthing); kwl.add(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_KW, pt.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, origin().latd(), true); kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, origin().lond(), true); kwl.add(prefix, ossimKeywordNames::TYPE_KW, projName(), true); if(theDatum) { kwl.add(prefix, ossimKeywordNames::DATUM_KW, theDatum->code(), true); } if (projName()== STATIC_TYPE_NAME(ossimLambertConformalConicProjection)) { kwl.add(prefix, ossimKeywordNames::STD_PARALLEL_1_KW, parallel1(), true); kwl.add(prefix, ossimKeywordNames::STD_PARALLEL_2_KW, parallel2(), true); } else { kwl.add(prefix, ossimKeywordNames::SCALE_FACTOR_KW, theScaleFactor, true); } } ossimUnitType ossimStatePlaneProjectionInfo::getUnitType() const { return theUnits; } bool ossimStatePlaneProjectionInfo::matchesProjection( const ossimMapProjection* proj) const { if (!proj) { return false; } #if 0 cout << "\ntheProjectionName: " << theProjectionName << "\nclassName: " << proj->getClassName() << "\ntheOrigin: " << theOrigin << "\nproj->origin(): "<< proj->origin() << "\nfalseEastingInMeters(): "<< falseEastingInMeters() << "\nproj->getFalseEasting(): " << proj->getFalseEasting() << "\nfalseNorthingInMeters(): " << falseNorthingInMeters() << "\nproj->getFalseNorthing(): " << proj->getFalseNorthing() << "\ndatum: " << theDatum->code() << endl; #endif if ( (theProjectionName != proj->getClassName()) || ( (theOrigin == proj->origin()) == false) || (falseEastingInMeters() != proj->getFalseEasting()) || (falseNorthingInMeters() != proj->getFalseNorthing()) ) { return false; } //--- // NOTE: Going from double to strings, radians to degrees and back is // causing a wiggle in the floating point values; hence the // ALLOWABLE_VARIANCE. //--- const double ALLOWABLE_VARIANCE = 0.00000000000001; if (theProjectionName == "ossimTransMercatorProjection") { ossimTransMercatorProjection* tm = PTR_CAST(ossimTransMercatorProjection, proj); if (!tm) { return false; } double d1 = fabs(theScaleFactor - tm->getScaleFactor()); if (d1 < ALLOWABLE_VARIANCE) { return true; } } else // Lambert. { ossimLambertConformalConicProjection* lam = PTR_CAST(ossimLambertConformalConicProjection, proj); if (!lam) { return false; } double d1 = fabs(parallel1() - lam->getStandardParallel1()); double d2 = fabs(parallel2() - lam->getStandardParallel2()); if ( (d1 < ALLOWABLE_VARIANCE) && (d2 < ALLOWABLE_VARIANCE) ) { return true; } } return false; } std::ostream& operator<<(std::ostream& os, const ossimStatePlaneProjectionInfo& thePlane) { if (thePlane.projName()== STATIC_TYPE_NAME(ossimTransMercatorProjection)) { return os << "ossimStatePlaneProjection: " << "\nName: " << thePlane.name() << "\nPcsCode: " << thePlane.code() << "\norigin: " << thePlane.origin() << "\nscale factor: " << setprecision(12) << thePlane.scaleFactor() << "\nfalseEasting: " << thePlane.falseEasting() << "\nfalseNorthing: " << thePlane.falseNorthing() << endl; } else // Lambert { return os << "ossimStatePlaneProjection: " << "\nName: " << thePlane.name() << "\nPcsCode: " << thePlane.code() << "\norigin: " << thePlane.origin() << "\nphi1: " << setprecision(12) << thePlane.parallel1() << "\nphi2: " << setprecision(12) << thePlane.parallel2() << "\nfalseEasting: " << thePlane.falseEasting() << "\nfalseNorthing: " << thePlane.falseNorthing() << endl; } } ossim-Miami-2.9.1/src/projection/ossimStereographicProjection.cpp000066400000000000000000000410771352751253100253020ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimStereographicProjection.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include RTTI_DEF1(ossimStereographicProjection, "ossimStereographicProjection", ossimMapProjection) #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef PI_OVER_4 # define PI_OVER_4 ( M_PI / 4.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define ONE (1.0 * M_PI / 180.0) /* 1 degree in radians*/ #define STEREO_NO_ERROR 0x0000 #define STEREO_LAT_ERROR 0x0001 #define STEREO_LON_ERROR 0x0002 #define STEREO_ORIGIN_LAT_ERROR 0x0004 #define STEREO_CENT_MER_ERROR 0x0008 #define STEREO_EASTING_ERROR 0x0010 #define STEREO_NORTHING_ERROR 0x0020 #define STEREO_A_ERROR 0x0040 #define STEREO_INV_F_ERROR 0x0080 ossimStereographicProjection::ossimStereographicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimStereographicProjection::ossimStereographicProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Stereo_False_Easting = falseEasting; Stereo_False_Northing = falseNorthing; Stereo_Delta_Easting = 1460090226.0; Stereo_Delta_Northing = 1460090226.0; update(); } void ossimStereographicProjection::update() { Set_Stereographic_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Stereo_False_Easting, Stereo_False_Northing); theFalseEastingNorthing.x = Stereo_False_Easting; theFalseEastingNorthing.y = Stereo_False_Northing; ossimMapProjection::update(); } void ossimStereographicProjection::setFalseEasting(double falseEasting) { Stereo_False_Easting = falseEasting; update(); } void ossimStereographicProjection::setFalseNorthing(double falseNorthing) { Stereo_False_Northing = falseNorthing; update(); } void ossimStereographicProjection::setDefaults() { Stereo_False_Easting = 0.0; Stereo_False_Northing = 0.0; Stereo_Delta_Easting = 1460090226.0; Stereo_Delta_Northing = 1460090226.0; } void ossimStereographicProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Stereo_False_Easting = falseEasting; Stereo_False_Northing = falseNorthing; update(); } ossimGpt ossimStereographicProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Stereographic_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimStereographicProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Stereographic(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimStereographicProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimStereographicProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimStereographicProjection)) { Stereo_False_Easting = theFalseEastingNorthing.x; Stereo_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /************************************************************************/ /* FUNCTIONS * */ long ossimStereographicProjection::Set_Stereographic_Parameters (double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing) { /* BEGIN Set_Stereographic_Parameters */ /* * The function Set_Stereographic_Parameters receives the ellipsoid * parameters and Stereograpic projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, error * code(s) are returned by the function, otherwise STEREO_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude, in radians, at the center of (input) * the projection * Central_Meridian : Longitude, in radians, at the center of (input) * the projection * False_Easting : Easting (X) at center of projection, in meters (input) * False_Northing : Northing (Y) at center of projection, in meters (input) */ double es2, es4, es6; double temp = 0; // double inv_f = 1 / f; long Error_Code = STEREO_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= STEREO_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= STEREO_INV_F_ERROR; // } // if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) // { /* origin latitude out of range */ // Error_Code |= STEREO_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -M_PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= STEREO_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Stereo_a = a; Stereo_f = f; es2 = 2 * Stereo_f - Stereo_f * Stereo_f; es4 = es2 * es2; es6 = es4 * es2; Stereo_Ra = Stereo_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 /3024.0); Two_Stereo_Ra = 2.0 * Stereo_Ra; Stereo_Origin_Lat = Origin_Latitude; Sin_Stereo_Origin_Lat = sin(Stereo_Origin_Lat); Cos_Stereo_Origin_Lat = cos(Stereo_Origin_Lat); // if (Central_Meridian > M_PI) // Central_Meridian -= TWO_PI; Stereo_Origin_Long = Central_Meridian; Stereo_False_Easting = False_Easting; Stereo_False_Northing = False_Northing; if(fabs(fabs(Stereo_Origin_Lat) - PI_OVER_2) < 1.0e-10) Stereo_At_Pole = 1; else Stereo_At_Pole = 0; if ((Stereo_At_Pole) || (fabs(Stereo_Origin_Lat) < 1.0e-10)) { Stereo_Delta_Easting = 1460090226.0; } else { if (Stereo_Origin_Long <= 0) Convert_Geodetic_To_Stereographic(-Stereo_Origin_Lat, M_PI + Stereo_Origin_Long - ONE, &Stereo_Delta_Easting, &temp); else Convert_Geodetic_To_Stereographic(-Stereo_Origin_Lat, Stereo_Origin_Long - M_PI - ONE, &Stereo_Delta_Easting, &temp); } } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Set_Stereographic_Parameters */ void ossimStereographicProjection::Get_Stereographic_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* BEGIN Get_Stereographic_Parameters */ /* * The function Get_Stereographic_Parameters returns the current ellipsoid * parameters and Stereographic projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude, in radians, at the center of (output) * the projection * Central_Meridian : Longitude, in radians, at the center of (output) * the projection * False_Easting : A coordinate value, in meters, assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value, in meters, assigned to the * origin latitude of the projection (output) */ *a = Stereo_a; *f = Stereo_f; *Origin_Latitude = Stereo_Origin_Lat; *Central_Meridian = Stereo_Origin_Long; *False_Easting = Stereo_False_Easting; *False_Northing = Stereo_False_Northing; return; } /* END OF Get_Stereographic_Parameters */ long ossimStereographicProjection::Convert_Geodetic_To_Stereographic (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Stereographic */ /* * The function Convert_Geodetic_To_Stereographic converts geodetic * coordinates (latitude and longitude) to Stereographic coordinates * (easting and northing), according to the current ellipsoid * and Stereographic projection parameters. If any errors occur, error * code(s) are returned by the function, otherwise STEREO_NO_ERROR is returned. * * Latitude : Latitude, in radians (input) * Longitude : Longitude, in radians (input) * Easting : Easting (X), in meters (output) * Northing : Northing (Y), in meters (output) */ double g, k; double num = 0; double Ra_k = 0; double slat = sin(Latitude); double clat = cos(Latitude); double dlam; /* Longitude - Central Meridan */ double cos_dlam; long Error_Code = STEREO_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= STEREO_LAT_ERROR; // } // if ((Longitude < -M_PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code|= STEREO_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Stereo_Origin_Long; // if (dlam > M_PI) // { // dlam -= TWO_PI; // } // if (dlam < -M_PI) // { // dlam += TWO_PI; // } cos_dlam = cos(dlam); g = 1.0 + Sin_Stereo_Origin_Lat * slat + Cos_Stereo_Origin_Lat * clat * cos_dlam; if (fabs(g) <= 1.0e-10) { /* Point is out of view. Will return longitude out of range message since no point out of view is implemented. */ Error_Code |= STEREO_LON_ERROR; } else { if (Stereo_At_Pole) { if (fabs(fabs(Latitude) - PI_OVER_2) < 1.0e-10) { *Easting = Stereo_False_Easting; *Northing = Stereo_False_Northing; } else { if (Stereo_Origin_Lat > 0) { num = Two_Stereo_Ra * tan(PI_OVER_4 - Latitude / 2.0); *Easting = Stereo_False_Easting + num * sin(dlam); *Northing = Stereo_False_Northing + (-num * cos_dlam); } else { num = Two_Stereo_Ra * tan(PI_OVER_4 + Latitude / 2.0); *Easting = Stereo_False_Easting + num * sin(dlam); *Northing = Stereo_False_Northing + num * cos_dlam; } } } else { if (fabs(Stereo_Origin_Lat) <= 1.0e-10) { k = 2.0 / (1.0 + clat * cos_dlam); Ra_k = Stereo_Ra * k; *Northing = Stereo_False_Northing + Ra_k * slat; } else { k = 2.0 / g; Ra_k = Stereo_Ra * k; *Northing = Stereo_False_Northing + Ra_k * (Cos_Stereo_Origin_Lat * slat - Sin_Stereo_Origin_Lat * clat * cos_dlam); } *Easting = Stereo_False_Easting + Ra_k * clat * sin(dlam); } } } return (Error_Code); } /* END OF Convert_Geodetic_To_Stereographic */ long ossimStereographicProjection::Convert_Stereographic_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Stereographic_To_Geodetic */ /* * The function Convert_Stereographic_To_Geodetic converts Stereographic projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Stereographic projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise STEREO_NO_ERROR is returned. * * Easting : Easting (X), in meters (input) * Northing : Northing (Y), in meters (input) * Latitude : Latitude (phi), in radians (output) * Longitude : Longitude (lambda), in radians (output) */ double dx, dy; double rho, c; double sin_c, cos_c; double dy_sin_c; long Error_Code = STEREO_NO_ERROR; // if ((Easting < (Stereo_False_Easting - Stereo_Delta_Easting)) // ||(Easting > (Stereo_False_Easting + Stereo_Delta_Easting))) // { /* Easting out of range */ // Error_Code |= STEREO_EASTING_ERROR; // } // if ((Northing < (Stereo_False_Northing - Stereo_Delta_Northing)) // || (Northing > (Stereo_False_Northing + Stereo_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= STEREO_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ dy = Northing - Stereo_False_Northing; dx = Easting - Stereo_False_Easting; rho = sqrt(dx * dx + dy * dy); if (fabs(rho) <= 1.0e-10) { *Latitude = Stereo_Origin_Lat; *Longitude = Stereo_Origin_Long; } else { c = 2.0 * atan(rho / (Two_Stereo_Ra)); sin_c = sin(c); cos_c = cos(c); dy_sin_c = dy * sin_c; if (Stereo_At_Pole) { if (Stereo_Origin_Lat > 0) *Longitude = Stereo_Origin_Long + atan2(dx, -dy); else *Longitude = Stereo_Origin_Long + atan2(dx, dy); } else *Longitude = Stereo_Origin_Long + atan2(dx * sin_c, (rho * Cos_Stereo_Origin_Lat * cos_c - dy_sin_c * Sin_Stereo_Origin_Lat)); *Latitude = asin(cos_c * Sin_Stereo_Origin_Lat + ((dy_sin_c * Cos_Stereo_Origin_Lat) / rho)); } // if (fabs(*Latitude) < 2.2e-8) /* force lat to 0 to avoid -0 degrees */ // *Latitude = 0.0; // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > M_PI) // { // if (*Longitude - M_PI < 3.5e-6) // *Longitude = M_PI; // else // *Longitude -= TWO_PI; // } // if (*Longitude < -M_PI) // { // if (fabs(*Longitude + M_PI) < 3.5e-6) // *Longitude = -M_PI; // else // *Longitude += TWO_PI; // } // // if (fabs(*Longitude) < 2.0e-7) /* force lon to 0 to avoid -0 degrees */ // *Longitude = 0.0; // if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ // *Longitude = M_PI; // else if (*Longitude < -M_PI) // *Longitude = -M_PI; } return (Error_Code); } /* END OF Convert_Stereographic_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimTangentialRadialLensDistortion.cpp000066400000000000000000000057531352751253100265530ustar00rootroot00000000000000#include #include #include RTTI_DEF1(ossimTangentialRadialLensDistortion, "ossimTangentialRadialLensDistortion", ossimLensDistortion); ossimTangentialRadialLensDistortion::ossimTangentialRadialLensDistortion() :ossimLensDistortion() { m_k.resize(3); m_p.resize(2); m_k[0] = m_k[1] = m_k[2] = 0.0; m_p[0] = m_p[1]; } ossimTangentialRadialLensDistortion::ossimTangentialRadialLensDistortion(const ossimDpt& calibratedCenter, double k1, double k2, double k3, double p1, double p2) :ossimLensDistortion(calibratedCenter) { m_k.resize(3); m_p.resize(2); m_k[0] = k1; m_k[1] = k2; m_k[2] = k3; m_p[0] = p1; m_p[1] = p2; } ossimTangentialRadialLensDistortion::ossimTangentialRadialLensDistortion(const ossimDpt& calibratedCenter, std::vector k, std::vector p) :ossimLensDistortion(calibratedCenter), m_k(k), m_p(p) { } void ossimTangentialRadialLensDistortion::undistort(const ossimDpt& input, ossimDpt& output)const { // make relative to calibrated center //ossimDpt deltaPosition(input.x - theCenter.x, // input.y - theCenter.y); double r = sqrt(input.x*input.x + input.y*input.y); double r2 = r*r; double rMultiplier = r2; ossim_uint32 idx = 0; // comnpute the radial portion of the equation of the form // 1 + k0*r^2 + k1*r^4 + ....... double tempRadial = 1.0; for(idx = 0; idx < m_k.size();++idx) { tempRadial += m_k[idx]*rMultiplier; rMultiplier*=r2; } // now apply the radial to the input point and then // shift and apply the tangential coefficients along x and y. output.x = (input.x*tempRadial) + (2.0*m_p[0]*input.x*input.y) + (m_p[1]*(r2 + 2*input.x*input.x)); output.y = (input.y*tempRadial) + (2.0*m_p[1]*input.x*input.y) + (m_p[0]*(r2 + 2*input.y*input.y)); // output.x += theCenter.x; // output.y += theCenter.y; } bool ossimTangentialRadialLensDistortion::saveState(ossimKeywordlist& kwl, const char* prefix )const { bool result = ossimLensDistortion::saveState(kwl, prefix); ossimString kValues; ossimString pValues; ossim::toSimpleStringList(kValues, m_k); ossim::toSimpleStringList(pValues, m_p); kwl.add(prefix, "k", kValues); kwl.add(prefix, "p", pValues); return result; } bool ossimTangentialRadialLensDistortion::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimLensDistortion::loadState(kwl, prefix); ossimString k = kwl.find(prefix, "k"); ossimString p = kwl.find(prefix, "p"); m_k.clear(); m_p.clear(); ossim::toSimpleVector(m_k, k); ossim::toSimpleVector(m_p, p); return result; } ossim-Miami-2.9.1/src/projection/ossimTiffProjectionFactory.cpp000066400000000000000000000106001352751253100247070ustar00rootroot00000000000000//***************************************************************************** // FILE: ossimTiffProjectionFactory.cc // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains implementation of class ossimTiffProjectionFactory // //***************************************************************************** // $Id: ossimTiffProjectionFactory.cpp 17108 2010-04-15 21:08:06Z dburken $ #include #include #include #include #include #include #include #include #include #include using namespace std; ossimTiffProjectionFactory* ossimTiffProjectionFactory::theInstance = 0; //***************************************************************************** // STATIC METHOD: ossimTiffProjectionFactory::instance() // //***************************************************************************** ossimTiffProjectionFactory* ossimTiffProjectionFactory::instance() { if(!theInstance) { theInstance = new ossimTiffProjectionFactory; } return (ossimTiffProjectionFactory*) theInstance; } ossimProjection* ossimTiffProjectionFactory::createProjection(const ossimFilename& filename, ossim_uint32 entryIdx)const { std::shared_ptr state = std::make_shared(); if(state->loadDefaults(filename)) { ossimGeoTiff geotiff; ossimKeywordlist kwl; if(geotiff.readTags(state, entryIdx)) { if(geotiff.addImageGeometry(kwl)) { return ossimProjectionFactoryRegistry::instance()->createProjection(kwl); } } } return 0; } //***************************************************************************** // METHOD: ossimSensorModelFactory::create(kwl, prefix) // //***************************************************************************** ossimProjection* ossimTiffProjectionFactory::createProjection(const ossimKeywordlist& /* keywordList */, const char* /* prefix */) const { return 0; } //***************************************************************************** // METHOD: ossimSensorModelFactory::create(projection_name) // //***************************************************************************** ossimProjection* ossimTiffProjectionFactory::createProjection(const ossimString& /* name */) const { return 0; } ossimProjection* ossimTiffProjectionFactory::createProjection(ossimImageHandler* handler)const { ossimTiffTileSource* tiff = dynamic_cast (handler); if(tiff) { ossimGeoTiff geotiff; ossimKeywordlist kwl; std::shared_ptr state = std::dynamic_pointer_cast(tiff->getState()); bool addGeometry = false; if(state) { addGeometry = geotiff.readTags(state, tiff->getCurrentEntry()); } else { addGeometry = geotiff.readTags(tiff->tiffPtr(), tiff->getCurrentEntry(), false); } if(addGeometry&&geotiff.addImageGeometry(kwl)) { return ossimProjectionFactoryRegistry::instance()->createProjection(kwl); } } return 0; } ossimObject* ossimTiffProjectionFactory::createObject(const ossimString& typeName)const { return (ossimObject*)createProjection(typeName); } ossimObject* ossimTiffProjectionFactory::createObject(const ossimKeywordlist& kwl, const char* prefix)const { return createProjection(kwl, prefix); } void ossimTiffProjectionFactory::getTypeNameList(std::vector& /* typeList */)const { } bool ossimTiffProjectionFactory::isTiff(const ossimFilename& filename)const { std::ifstream in; unsigned char header[2]; in.open( filename.c_str(), ios::in|ios::binary); if( !in) return false; in.read( (char*)header, 2); if( (header[0] != 'M' || header[1] != 'M') && (header[0] != 'I' || header[1] != 'I') ) { return false; } return true; } ossim-Miami-2.9.1/src/projection/ossimTranmerc.c000066400000000000000000000601501352751253100216520ustar00rootroot00000000000000/***************************************************************************/ /* RSC IDENTIFIER: TRANSVERSE MERCATOR * * ABSTRACT * * This component provides conversions between Geodetic coordinates * (latitude and longitude) and Transverse Mercator projection coordinates * (easting and northing). * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid value * is found the error code is combined with the current error code using * the bitwise or. This combining allows multiple error codes to be * returned. The possible error codes are: * * TRANMERC_NO_ERROR : No errors occurred in function * TRANMERC_LAT_ERROR : Latitude outside of valid range * (-90 to 90 degrees) * TRANMERC_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees, and within * +/-90 of Central Meridian) * TRANMERC_EASTING_ERROR : Easting outside of valid range * (depending on ellipsoid and * projection parameters) * TRANMERC_NORTHING_ERROR : Northing outside of valid range * (depending on ellipsoid and * projection parameters) * TRANMERC_ORIGIN_LAT_ERROR : Origin latitude outside of valid range * (-90 to 90 degrees) * TRANMERC_CENT_MER_ERROR : Central meridian outside of valid range * (-180 to 360 degrees) * TRANMERC_A_ERROR : Semi-major axis less than or equal to zero * TRANMERC_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * TRANMERC_SCALE_FACTOR_ERROR : Scale factor outside of valid * range (0.3 to 3.0) * TM_LON_WARNING : Distortion will result if longitude is more * than 9 degrees from the Central Meridian * * REUSE NOTES * * TRANSVERSE MERCATOR is intended for reuse by any application that * performs a Transverse Mercator projection or its inverse. * * REFERENCES * * Further information on TRANSVERSE MERCATOR can be found in the * Reuse Manual. * * TRANSVERSE MERCATOR originated from : * U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * TRANSVERSE MERCATOR has no restrictions. * * ENVIRONMENT * * TRANSVERSE MERCATOR was tested and certified in the following * environments: * * 1. Solaris 2.5 with GCC, version 2.8.1 * 2. Windows 95 with MS Visual C++, version 6 * * MODIFICATIONS * * Date Description * ---- ----------- * 10-02-97 Original Code * 03-02-97 Re-engineered Code * */ /***************************************************************************/ /* * INCLUDES */ #include #include #include #include /* * math.h - Standard C math library * tranmerc.h - Is for prototype error checking */ /****************************** DEFINES ************************************/ #define MAX_LAT ((M_PI * 90.0)/180.0) /* 90 degrees in radians */ #define MAX_DELTA_LONG ((M_PI * 90.0)/180.0) /* 90 degrees in radians */ #define MIN_SCALE_FACTOR 0.3 #define MAX_SCALE_FACTOR 3.0 #define SPHTMD(Latitude) ((double) (TranMerc_ap * Latitude \ - TranMerc_bp * sin(2.e0 * Latitude) + TranMerc_cp * sin(4.e0 * Latitude) \ - TranMerc_dp * sin(6.e0 * Latitude) + TranMerc_ep * sin(8.e0 * Latitude) ) ) #define SPHSN(Latitude) ((double) (TranMerc_a / sqrt( 1.e0 - TranMerc_es * \ pow(sin(Latitude), 2)))) #define SPHSR(Latitude) ((double) (TranMerc_a * (1.e0 - TranMerc_es) / \ pow(DENOM(Latitude), 3))) #define DENOM(Latitude) ((double) (sqrt(1.e0 - TranMerc_es * pow(sin(Latitude),2)))) /**************************************************************************/ /* GLOBAL DECLARATIONS * */ /* Ellipsoid Parameters, default to WGS 84 */ static double TranMerc_a = 6378137.0; /* Semi-major axis of ellipsoid i meters */ static double TranMerc_f = 1 / 298.257223563; /* Flattening of ellipsoid */ static double TranMerc_es = 0.0066943799901413800; /* Eccentricity (0.08181919084262188000) squared */ static double TranMerc_ebs = 0.0067394967565869; /* Second Eccentricity squared */ /* Transverse_Mercator projection Parameters */ static double TranMerc_Origin_Lat = 0.0; /* Latitude of origin in radians */ static double TranMerc_Origin_Long = 0.0; /* Longitude of origin in radians */ static double TranMerc_False_Northing = 0.0; /* False northing in meters */ static double TranMerc_False_Easting = 0.0; /* False easting in meters */ static double TranMerc_Scale_Factor = 1.0; /* Scale factor */ /* Isometeric to geodetic latitude parameters, default to WGS 84 */ static double TranMerc_ap = 6367449.1458008; static double TranMerc_bp = 16038.508696861; static double TranMerc_cp = 16.832613334334; static double TranMerc_dp = 0.021984404273757; static double TranMerc_ep = 3.1148371319283e-005; /* Maximum variance for easting and northing values for WGS 84. */ static double TranMerc_Delta_Easting = 40000000.0; static double TranMerc_Delta_Northing = 40000000.0; /* These state variables are for optimization purposes. The only function * that should modify them is Set_Tranverse_Mercator_Parameters. */ /************************************************************************/ /* FUNCTIONS * */ long Set_Transverse_Mercator_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing, double Scale_Factor) { /* BEGIN Set_Tranverse_Mercator_Parameters */ /* * The function Set_Tranverse_Mercator_Parameters receives the ellipsoid * parameters and Tranverse Mercator projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, the error * code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at the origin of the (input) * projection * Central_Meridian : Longitude in radians at the center of the (input) * projection * False_Easting : Easting/X at the center of the projection (input) * False_Northing : Northing/Y at the center of the projection (input) * Scale_Factor : Projection scale factor (input) */ double tn; /* True Meridianal distance constant */ double tn2; double tn3; double tn4; double tn5; double dummy_northing; double TranMerc_b; /* Semi-minor axis of ellipsoid, in meters */ /* double inv_f = 1 / f; */ long Error_Code = TRANMERC_NO_ERROR; #if 0 if (a <= 0.0) { /* Semi-major axis must be greater than zero */ Error_Code |= TRANMERC_A_ERROR; } if ((inv_f < 250) || (inv_f > 350)) { /* Inverse flattening must be between 250 and 350 */ Error_Code |= TRANMERC_INV_F_ERROR; } if ((Origin_Latitude < -MAX_LAT) || (Origin_Latitude > MAX_LAT)) { /* origin latitude out of range */ Error_Code |= TRANMERC_ORIGIN_LAT_ERROR; } if ((Central_Meridian < -M_PI) || (Central_Meridian > (TWO_PI))) { /* origin longitude out of range */ Error_Code |= TRANMERC_CENT_MER_ERROR; } if ((Scale_Factor < MIN_SCALE_FACTOR) || (Scale_Factor > MAX_SCALE_FACTOR)) { Error_Code |= TRANMERC_SCALE_FACTOR_ERROR; } #endif if (!Error_Code) { /* no errors */ TranMerc_a = a; TranMerc_f = f; TranMerc_Origin_Lat = 0; TranMerc_Origin_Long = 0; TranMerc_False_Northing = 0; TranMerc_False_Easting = 0; TranMerc_Scale_Factor = 1; /* Eccentricity Squared */ TranMerc_es = 2 * TranMerc_f - TranMerc_f * TranMerc_f; /* Second Eccentricity Squared */ TranMerc_ebs = (1 / (1 - TranMerc_es)) - 1; TranMerc_b = TranMerc_a * (1 - TranMerc_f); /*True meridianal constants */ tn = (TranMerc_a - TranMerc_b) / (TranMerc_a + TranMerc_b); tn2 = tn * tn; tn3 = tn2 * tn; tn4 = tn3 * tn; tn5 = tn4 * tn; TranMerc_ap = TranMerc_a * (1.e0 - tn + 5.e0 * (tn2 - tn3)/4.e0 + 81.e0 * (tn4 - tn5)/64.e0 ); TranMerc_bp = 3.e0 * TranMerc_a * (tn - tn2 + 7.e0 * (tn3 - tn4) /8.e0 + 55.e0 * tn5/64.e0 )/2.e0; TranMerc_cp = 15.e0 * TranMerc_a * (tn2 - tn3 + 3.e0 * (tn4 - tn5 )/4.e0) /16.0; TranMerc_dp = 35.e0 * TranMerc_a * (tn3 - tn4 + 11.e0 * tn5 / 16.e0) / 48.e0; TranMerc_ep = 315.e0 * TranMerc_a * (tn4 - tn5) / 512.e0; Convert_Geodetic_To_Transverse_Mercator(MAX_LAT, MAX_DELTA_LONG, &TranMerc_Delta_Easting, &TranMerc_Delta_Northing); Convert_Geodetic_To_Transverse_Mercator(0, MAX_DELTA_LONG, &TranMerc_Delta_Easting, &dummy_northing); TranMerc_Origin_Lat = Origin_Latitude; if (Central_Meridian > M_PI) Central_Meridian -= (TWO_PI); TranMerc_Origin_Long = Central_Meridian; TranMerc_False_Northing = False_Northing; TranMerc_False_Easting = False_Easting; TranMerc_Scale_Factor = Scale_Factor; } /* END OF if(!Error_Code) */ return (Error_Code); } /* END of Set_Transverse_Mercator_Parameters */ void Get_Transverse_Mercator_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing, double *Scale_Factor) { /* BEGIN Get_Tranverse_Mercator_Parameters */ /* * The function Get_Transverse_Mercator_Parameters returns the current * ellipsoid and Transverse Mercator projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at the origin of the (output) * projection * Central_Meridian : Longitude in radians at the center of the (output) * projection * False_Easting : Easting/X at the center of the projection (output) * False_Northing : Northing/Y at the center of the projection (output) * Scale_Factor : Projection scale factor (output) */ *a = TranMerc_a; *f = TranMerc_f; *Origin_Latitude = TranMerc_Origin_Lat; *Central_Meridian = TranMerc_Origin_Long; *False_Easting = TranMerc_False_Easting; *False_Northing = TranMerc_False_Northing; *Scale_Factor = TranMerc_Scale_Factor; return; } /* END OF Get_Tranverse_Mercator_Parameters */ long Convert_Geodetic_To_Transverse_Mercator (double Latitude, double Longitude, double *Easting, double *Northing) { /* BEGIN Convert_Geodetic_To_Transverse_Mercator */ /* * The function Convert_Geodetic_To_Transverse_Mercator converts geodetic * (latitude and longitude) coordinates to Transverse Mercator projection * (easting and northing) coordinates, according to the current ellipsoid * and Transverse Mercator projection coordinates. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ double c; /* Cosine of latitude */ double c2; double c3; double c5; double c7; double dlam; /* Delta longitude - Difference in Longitude */ double eta; /* constant - TranMerc_ebs *c *c */ double eta2; double eta3; double eta4; double s; /* Sine of latitude */ double sn; /* Radius of curvature in the prime vertical */ double t; /* Tangent of latitude */ double tan2; double tan3; double tan4; double tan5; double tan6; double t1; /* Term in coordinate conversion formula - GP to Y */ double t2; /* Term in coordinate conversion formula - GP to Y */ double t3; /* Term in coordinate conversion formula - GP to Y */ double t4; /* Term in coordinate conversion formula - GP to Y */ double t5; /* Term in coordinate conversion formula - GP to Y */ double t6; /* Term in coordinate conversion formula - GP to Y */ double t7; /* Term in coordinate conversion formula - GP to Y */ double t8; /* Term in coordinate conversion formula - GP to Y */ double t9; /* Term in coordinate conversion formula - GP to Y */ double tmd; /* True Meridional distance */ double tmdo; /* True Meridional distance for latitude of origin */ long Error_Code = TRANMERC_NO_ERROR; /* double temp_Origin; */ /* double temp_Long; */ #if 0 if ((Latitude < -MAX_LAT) || (Latitude > MAX_LAT)) { /* Latitude out of range */ Error_Code|= TRANMERC_LAT_ERROR; } if (Longitude > M_PI) Longitude -= (TWO_PI); if ((Longitude < (TranMerc_Origin_Long - MAX_DELTA_LONG)) || (Longitude > (TranMerc_Origin_Long + MAX_DELTA_LONG))) { if (Longitude < 0) temp_Long = Longitude + TWO_PI; else temp_Long = Longitude; if (TranMerc_Origin_Long < 0) temp_Origin = TranMerc_Origin_Long + TWO_PI; else temp_Origin = TranMerc_Origin_Long; if ((temp_Long < (temp_Origin - MAX_DELTA_LONG)) || (temp_Long > (temp_Origin + MAX_DELTA_LONG))) Error_Code|= TRANMERC_LON_ERROR; } #endif if (!Error_Code) { /* no errors */ /* * Delta Longitude */ dlam = Longitude - TranMerc_Origin_Long; if (fabs(dlam) > (9.0 * RAD_PER_DEG)) { /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian */ Error_Code |= TRANMERC_LON_WARNING; } if (dlam > M_PI) dlam -= (TWO_PI); if (dlam < -M_PI) dlam += (TWO_PI); if (fabs(dlam) < 2.e-10) dlam = 0.0; s = sin(Latitude); c = cos(Latitude); c2 = c * c; c3 = c2 * c; c5 = c3 * c2; c7 = c5 * c2; t = tan (Latitude); tan2 = t * t; tan3 = tan2 * t; tan4 = tan3 * t; tan5 = tan4 * t; tan6 = tan5 * t; eta = TranMerc_ebs * c2; eta2 = eta * eta; eta3 = eta2 * eta; eta4 = eta3 * eta; /* radius of curvature in prime vertical */ sn = SPHSN(Latitude); /* True Meridianal Distances */ tmd = SPHTMD(Latitude); /* Origin */ tmdo = SPHTMD (TranMerc_Origin_Lat); /* northing */ t1 = (tmd - tmdo) * TranMerc_Scale_Factor; t2 = sn * s * c * TranMerc_Scale_Factor/ 2.e0; t3 = sn * s * c3 * TranMerc_Scale_Factor * (5.e0 - tan2 + 9.e0 * eta + 4.e0 * eta2) /24.e0; t4 = sn * s * c5 * TranMerc_Scale_Factor * (61.e0 - 58.e0 * tan2 + tan4 + 270.e0 * eta - 330.e0 * tan2 * eta + 445.e0 * eta2 + 324.e0 * eta3 -680.e0 * tan2 * eta2 + 88.e0 * eta4 -600.e0 * tan2 * eta3 - 192.e0 * tan2 * eta4) / 720.e0; t5 = sn * s * c7 * TranMerc_Scale_Factor * (1385.e0 - 3111.e0 * tan2 + 543.e0 * tan4 - tan6) / 40320.e0; *Northing = TranMerc_False_Northing + t1 + pow(dlam,2.e0) * t2 + pow(dlam,4.e0) * t3 + pow(dlam,6.e0) * t4 + pow(dlam,8.e0) * t5; /* Easting */ t6 = sn * c * TranMerc_Scale_Factor; t7 = sn * c3 * TranMerc_Scale_Factor * (1.e0 - tan2 + eta ) /6.e0; t8 = sn * c5 * TranMerc_Scale_Factor * (5.e0 - 18.e0 * tan2 + tan4 + 14.e0 * eta - 58.e0 * tan2 * eta + 13.e0 * eta2 + 4.e0 * eta3 - 64.e0 * tan2 * eta2 - 24.e0 * tan2 * eta3 )/ 120.e0; t9 = sn * c7 * TranMerc_Scale_Factor * ( 61.e0 - 479.e0 * tan2 + 179.e0 * tan4 - tan6 ) /5040.e0; *Easting = TranMerc_False_Easting + dlam * t6 + pow(dlam,3.e0) * t7 + pow(dlam,5.e0) * t8 + pow(dlam,7.e0) * t9; } return (Error_Code); } /* END OF Convert_Geodetic_To_Transverse_Mercator */ long Convert_Transverse_Mercator_To_Geodetic ( double Easting, double Northing, double *Latitude, double *Longitude) { /* BEGIN Convert_Transverse_Mercator_To_Geodetic */ /* * The function Convert_Transverse_Mercator_To_Geodetic converts Transverse * Mercator projection (easting and northing) coordinates to geodetic * (latitude and longitude) coordinates, according to the current ellipsoid * and Transverse Mercator projection parameters. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ double c; /* Cosine of latitude */ double de; /* Delta easting - Difference in Easting (Easting-Fe) */ double dlam; /* Delta longitude - Difference in Longitude */ double eta; /* constant - TranMerc_ebs *c *c */ double eta2; double eta3; double eta4; double ftphi; /* Footpoint latitude */ int i; /* Loop iterator */ // double s; /* Sine of latitude */ double sn; /* Radius of curvature in the prime vertical */ double sr; /* Radius of curvature in the meridian */ double t; /* Tangent of latitude */ double tan2; double tan4; double t10; /* Term in coordinate conversion formula - GP to Y */ double t11; /* Term in coordinate conversion formula - GP to Y */ double t12; /* Term in coordinate conversion formula - GP to Y */ double t13; /* Term in coordinate conversion formula - GP to Y */ double t14; /* Term in coordinate conversion formula - GP to Y */ double t15; /* Term in coordinate conversion formula - GP to Y */ double t16; /* Term in coordinate conversion formula - GP to Y */ double t17; /* Term in coordinate conversion formula - GP to Y */ double tmd; /* True Meridional distance */ double tmdo; /* True Meridional distance for latitude of origin */ long Error_Code = TRANMERC_NO_ERROR; #if 0 if ((Easting < (TranMerc_False_Easting - TranMerc_Delta_Easting)) ||(Easting > (TranMerc_False_Easting + TranMerc_Delta_Easting))) { /* Easting out of range */ Error_Code |= TRANMERC_EASTING_ERROR; } if ((Northing < (TranMerc_False_Northing - TranMerc_Delta_Northing)) || (Northing > (TranMerc_False_Northing + TranMerc_Delta_Northing))) { /* Northing out of range */ Error_Code |= TRANMERC_NORTHING_ERROR; } #endif if (!Error_Code) { /* True Meridional Distances for latitude of origin */ tmdo = SPHTMD(TranMerc_Origin_Lat); /* Origin */ tmd = tmdo + (Northing - TranMerc_False_Northing) / TranMerc_Scale_Factor; /* First Estimate */ sr = SPHSR(0.e0); ftphi = tmd/sr; for (i = 0; i < 5 ; i++) { t10 = SPHTMD (ftphi); sr = SPHSR(ftphi); ftphi = ftphi + (tmd - t10) / sr; } /* Radius of Curvature in the meridian */ sr = SPHSR(ftphi); /* Radius of Curvature in the meridian */ sn = SPHSN(ftphi); /* Sine Cosine terms */ // s = sin(ftphi); c = cos(ftphi); /* Tangent Value */ t = tan(ftphi); tan2 = t * t; tan4 = tan2 * tan2; eta = TranMerc_ebs * pow(c,2); eta2 = eta * eta; eta3 = eta2 * eta; eta4 = eta3 * eta; de = Easting - TranMerc_False_Easting; if (fabs(de) < 0.0001) de = 0.0; /* Latitude */ t10 = t / (2.e0 * sr * sn * pow(TranMerc_Scale_Factor, 2)); t11 = t * (5.e0 + 3.e0 * tan2 + eta - 4.e0 * pow(eta,2) - 9.e0 * tan2 * eta) / (24.e0 * sr * pow(sn,3) * pow(TranMerc_Scale_Factor,4)); t12 = t * (61.e0 + 90.e0 * tan2 + 46.e0 * eta + 45.E0 * tan4 - 252.e0 * tan2 * eta - 3.e0 * eta2 + 100.e0 * eta3 - 66.e0 * tan2 * eta2 - 90.e0 * tan4 * eta + 88.e0 * eta4 + 225.e0 * tan4 * eta2 + 84.e0 * tan2* eta3 - 192.e0 * tan2 * eta4) / ( 720.e0 * sr * pow(sn,5) * pow(TranMerc_Scale_Factor, 6) ); t13 = t * ( 1385.e0 + 3633.e0 * tan2 + 4095.e0 * tan4 + 1575.e0 * pow(t,6))/ (40320.e0 * sr * pow(sn,7) * pow(TranMerc_Scale_Factor,8)); *Latitude = ftphi - pow(de,2) * t10 + pow(de,4) * t11 - pow(de,6) * t12 + pow(de,8) * t13; t14 = 1.e0 / (sn * c * TranMerc_Scale_Factor); t15 = (1.e0 + 2.e0 * tan2 + eta) / (6.e0 * pow(sn,3) * c * pow(TranMerc_Scale_Factor,3)); t16 = (5.e0 + 6.e0 * eta + 28.e0 * tan2 - 3.e0 * eta2 + 8.e0 * tan2 * eta + 24.e0 * tan4 - 4.e0 * eta3 + 4.e0 * tan2 * eta2 + 24.e0 * tan2 * eta3) / (120.e0 * pow(sn,5) * c * pow(TranMerc_Scale_Factor,5)); t17 = (61.e0 + 662.e0 * tan2 + 1320.e0 * tan4 + 720.e0 * pow(t,6)) / (5040.e0 * pow(sn,7) * c * pow(TranMerc_Scale_Factor,7)); /* Difference in Longitude */ dlam = de * t14 - pow(de,3) * t15 + pow(de,5) * t16 - pow(de,7) * t17; /* Longitude */ (*Longitude) = TranMerc_Origin_Long + dlam; while (*Latitude > (90.0 * RAD_PER_DEG)) { *Latitude = M_PI - *Latitude; *Longitude += M_PI; if (*Longitude > M_PI) *Longitude -= (TWO_PI); } while (*Latitude < (-90.0 * RAD_PER_DEG)) { *Latitude = - (*Latitude + M_PI); *Longitude += M_PI; if (*Longitude > M_PI) *Longitude -= (TWO_PI); } if (*Longitude > (TWO_PI)) *Longitude -= (TWO_PI); if (*Longitude < -M_PI) *Longitude += (TWO_PI); if (fabs(dlam) > (9.0 * RAD_PER_DEG)) { /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian */ Error_Code |= TRANMERC_LON_WARNING; } } return (Error_Code); } /* END OF Convert_Transverse_Mercator_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimTransCylEquAreaProjection.cpp000066400000000000000000000521301352751253100254760ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Transverse Cylindrical Equal Area // projection code. //******************************************************************* // $Id: ossimTransCylEquAreaProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #include RTTI_DEF1(ossimTransCylEquAreaProjection, "ossimTransCylEquAreaProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define TCEA_Q(sinlat,x) (One_MINUS_es2*(sinlat/(1.0-es2*sinlat*sinlat)-One_OVER_2es*log((1-x)/(1+x)))) #define TCEA_COEFF_TIMES_SIN(coeff,x,latit) (coeff * sin(x*latit)) #define TCEA_M(c0lat,c1lat,c2lat,c3lat) (Tcea_a * (c0lat - c1lat + c2lat - c3lat)) #define TCEA_L(Beta,c0lat,c1lat,c2lat) (Beta + c0lat + c1lat + c2lat) #define MIN_SCALE_FACTOR 0.3 #define MAX_SCALE_FACTOR 3.0 #define TCEA_NO_ERROR 0x0000 #define TCEA_LAT_ERROR 0x0001 #define TCEA_LON_ERROR 0x0002 #define TCEA_EASTING_ERROR 0x0004 #define TCEA_NORTHING_ERROR 0x0008 #define TCEA_ORIGIN_LAT_ERROR 0x0010 #define TCEA_CENT_MER_ERROR 0x0020 #define TCEA_A_ERROR 0x0040 #define TCEA_INV_F_ERROR 0x0080 #define TCEA_SCALE_FACTOR_ERROR 0x0100 #define TCEA_LON_WARNING 0x0200 ossimTransCylEquAreaProjection::ossimTransCylEquAreaProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimTransCylEquAreaProjection::ossimTransCylEquAreaProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing, double scaleFactor) :ossimMapProjection(ellipsoid, origin) { Tcea_False_Easting = falseEasting; Tcea_False_Northing = falseNorthing; Tcea_Scale_Factor = scaleFactor; Tcea_Min_Easting = -6398628.0; Tcea_Max_Easting = 6398628.0; Tcea_Min_Northing = -20003931.0; Tcea_Max_Northing = 20003931.0; update(); } void ossimTransCylEquAreaProjection::setFalseEasting(double falseEasting) { Tcea_False_Easting = falseEasting; update(); } void ossimTransCylEquAreaProjection::setFalseNorthing(double falseNorthing) { Tcea_False_Northing = falseNorthing; update(); } void ossimTransCylEquAreaProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Tcea_False_Easting = falseEasting; Tcea_False_Northing = falseNorthing; update(); } void ossimTransCylEquAreaProjection::setScaleFactor(double scaleFactor) { Tcea_Scale_Factor = scaleFactor; update(); } void ossimTransCylEquAreaProjection::setParameters(double falseEasting, double falseNorthing, double scaleFactor) { Tcea_False_Easting = falseEasting; Tcea_False_Northing = falseNorthing; Tcea_Scale_Factor = scaleFactor; update(); } void ossimTransCylEquAreaProjection::setDefaults() { Tcea_Scale_Factor = 1.0; Tcea_False_Easting = 0.0; Tcea_False_Northing = 0.0; Tcea_Min_Easting = -6398628.0; Tcea_Max_Easting = 6398628.0; Tcea_Min_Northing = -20003931.0; Tcea_Max_Northing = 20003931.0; } void ossimTransCylEquAreaProjection::update() { Set_Trans_Cyl_Eq_Area_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), Tcea_False_Easting, Tcea_False_Northing, Tcea_Scale_Factor); theFalseEastingNorthing.x = Tcea_False_Easting; theFalseEastingNorthing.y = Tcea_False_Northing; ossimMapProjection::update(); } ossimGpt ossimTransCylEquAreaProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Trans_Cyl_Eq_Area_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimTransCylEquAreaProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Trans_Cyl_Eq_Area(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimTransCylEquAreaProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, ossimKeywordNames::SCALE_FACTOR_KW, Tcea_Scale_Factor, true); return ossimMapProjection::saveState(kwl, prefix); } bool ossimTransCylEquAreaProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); const char* scaleFactor = kwl.find(prefix, ossimKeywordNames::SCALE_FACTOR_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimTransCylEquAreaProjection)) { Tcea_False_Easting = theFalseEastingNorthing.x; Tcea_False_Northing = theFalseEastingNorthing.y; if(scaleFactor) { Tcea_Scale_Factor = ossimString(scaleFactor).toDouble(); } } update(); return flag; } long ossimTransCylEquAreaProjection::Set_Trans_Cyl_Eq_Area_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing, double Scale_Factor) { /* BEGIN Set_Trans_Cyl_Eq_Area_Parameters */ /* * The function Set_Trans_Cyl_Eq_Area_Parameters receives the ellipsoid parameters and * Transverse Cylindrical Equal Area projection parameters as inputs, and sets the * corresponding state variables. If any errors occur, the error code(s) are returned * by the function, otherwise TCEA_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at which the (input) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) * Scale_Factor : Multiplier which reduces distances in the * projection to the actual distance on the * ellipsoid (input) */ double sin_lat_90 = sin(PI_OVER_2); double x, j, three_es4; double Sqrt_One_MINUS_es2; double e1, e2, e3, e4; double lat, sin2lat, sin4lat, sin6lat; double temp, temp_northing; // double inv_f = 1 / f; long Error_Code = TCEA_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= TCEA_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= TCEA_INV_F_ERROR; // } // if ((Origin_Latitude < -PI_OVER_2) || (Origin_Latitude > PI_OVER_2)) // { /* origin latitude out of range */ // Error_Code |= TCEA_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -M_PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= TCEA_CENT_MER_ERROR; // } // if ((Scale_Factor < MIN_SCALE_FACTOR) || (Scale_Factor > MAX_SCALE_FACTOR)) // { // Error_Code |= TCEA_SCALE_FACTOR_ERROR; // } if (!Error_Code) { /* no errors */ Tcea_a = a; Tcea_f = f; Tcea_Origin_Lat = Origin_Latitude; if (Central_Meridian > M_PI) Central_Meridian -= TWO_PI; Tcea_Origin_Long = Central_Meridian; Tcea_False_Northing = False_Northing; Tcea_False_Easting = False_Easting; Tcea_Scale_Factor = Scale_Factor; es2 = 2 * Tcea_f - Tcea_f * Tcea_f; es = sqrt(es2); One_MINUS_es2 = 1.0 - es2; Sqrt_One_MINUS_es2 = sqrt(One_MINUS_es2); One_OVER_2es = 1.0 / (2.0 * es); es4 = es2 * es2; es6 = es4 * es2; x = es * sin_lat_90; qp = TCEA_Q(sin_lat_90,x); a0 = es2 / 3.0 + 31.0 * es4 / 180.0 + 517.0 * es6 / 5040.0; a1 = 23.0 * es4 / 360.0 + 251.0 * es6 / 3780.0; a2 = 761.0 * es6 / 45360.0; e1 = (1.0 - Sqrt_One_MINUS_es2) / (1.0 + Sqrt_One_MINUS_es2); e2 = e1 * e1; e3 = e2 * e1; e4 = e3 * e1; b0 = 3.0 * e1 / 2.0 - 27.0 * e3 / 32.0; b1 = 21.0 * e2 / 16.0 - 55.0 * e4 / 32.0; b2 = 151.0 * e3 / 96.0; b3 = 1097.0 * e4 / 512.0; j = 45.0 * es6 / 1024.0; three_es4 = 3.0 * es4; c0 = 1.0 - es2 / 4.0 - three_es4 / 64.0 - 5.0 * es6 / 256.0; c1 = 3.0 * es2 / 8.0 + three_es4 / 32.0 + j; c2 = 15.0 * es4 / 256.0 + j; c3 = 35.0 * es6 / 3072.0; lat = c0 * Tcea_Origin_Lat; sin2lat = TCEA_COEFF_TIMES_SIN(c1, 2.0, Tcea_Origin_Lat); sin4lat = TCEA_COEFF_TIMES_SIN(c2, 4.0, Tcea_Origin_Lat); sin6lat = TCEA_COEFF_TIMES_SIN(c3, 6.0, Tcea_Origin_Lat); M0 = TCEA_M(lat, sin2lat, sin4lat, sin6lat); Convert_Geodetic_To_Trans_Cyl_Eq_Area(PI_OVER_2, M_PI, &temp, &temp_northing); if (temp_northing > 0) { Tcea_Min_Northing = temp_northing - 20003931.458986; Tcea_Max_Northing = temp_northing; } else if (temp_northing < 0) { Tcea_Max_Northing = temp_northing + 20003931.458986; Tcea_Min_Northing = temp_northing; } } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Set_Trans_Cyl_Eq_Area_Parameters */ void ossimTransCylEquAreaProjection::Get_Trans_Cyl_Eq_Area_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing, double *Scale_Factor)const { /* BEGIN Get_Trans_Cyl_Eq_Area_Parameters */ /* * The function Get_Trans_Cyl_Eq_Area_Parameters returns the current ellipsoid * parameters, Transverse Cylindrical Equal Area projection parameters, and scale factor. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at which the (output) * point scale factor is 1.0 * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) * Scale_Factor : Multiplier which reduces distances in the * projection to the actual distance on the * ellipsoid (output) */ *a = Tcea_a; *f = Tcea_f; *Origin_Latitude = Tcea_Origin_Lat; *Central_Meridian = Tcea_Origin_Long; *False_Easting = Tcea_False_Easting; *False_Northing = Tcea_False_Northing; *Scale_Factor = Tcea_Scale_Factor; return; } /* END OF Get_Trans_Cyl_Eq_Area_Parameters */ long ossimTransCylEquAreaProjection::Convert_Geodetic_To_Trans_Cyl_Eq_Area (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Trans_Cyl_Eq_Area */ /* * The function Convert_Geodetic_To_Trans_Cyl_Eq_Area converts geodetic (latitude and * longitude) coordinates to Transverse Cylindrical Equal Area projection (easting and * northing) coordinates, according to the current ellipsoid and Transverse Cylindrical * Equal Area projection parameters. If any errors occur, the error code(s) are returned * by the function, otherwise TCEA_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double x; double dlam; /* Longitude - Central Meridan */ double sin_lat = sin(Latitude); double qq, qq_OVER_qp; double beta, betac; double sin2betac, sin4betac, sin6betac; double PHIc; double phi, sin2phi, sin4phi, sin6phi; double sinPHIc; double Mc; long Error_Code = TCEA_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= TCEA_LAT_ERROR; // } // if ((Longitude < -M_PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code |= TCEA_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Tcea_Origin_Long; if (fabs(dlam) >= (M_PI / 2.0)) { /* Distortion will result if Longitude is more than 90 degrees from the Central Meridian */ Error_Code |= TCEA_LON_WARNING; } if (dlam > M_PI) { dlam -= TWO_PI; } if (dlam < -M_PI) { dlam += TWO_PI; } if (Latitude == PI_OVER_2) { qq = qp; qq_OVER_qp = 1.0; } else { x = es * sin_lat; qq = TCEA_Q(sin_lat, x); qq_OVER_qp = qq / qp; } if (qq_OVER_qp > 1.0) qq_OVER_qp = 1.0; else if (qq_OVER_qp < -1.0) qq_OVER_qp = -1.0; beta = asin(qq_OVER_qp); betac = atan(tan(beta) / cos(dlam)); if ((fabs(betac) - PI_OVER_2) > 1.0e-8) PHIc = betac; else { sin2betac = TCEA_COEFF_TIMES_SIN(a0, 2.0, betac); sin4betac = TCEA_COEFF_TIMES_SIN(a1, 4.0, betac); sin6betac = TCEA_COEFF_TIMES_SIN(a2, 6.0, betac); PHIc = TCEA_L(betac, sin2betac, sin4betac, sin6betac); } sinPHIc = sin(PHIc); *Easting = Tcea_a * cos(beta) * cos(PHIc) * sin(dlam) / (Tcea_Scale_Factor * cos(betac) * sqrt(1.0 - es2 * sinPHIc * sinPHIc)) + Tcea_False_Easting; phi = c0 * PHIc; sin2phi = TCEA_COEFF_TIMES_SIN(c1, 2.0, PHIc); sin4phi = TCEA_COEFF_TIMES_SIN(c2, 4.0, PHIc); sin6phi = TCEA_COEFF_TIMES_SIN(c3, 6.0, PHIc); Mc = TCEA_M(phi, sin2phi, sin4phi, sin6phi); *Northing = Tcea_Scale_Factor * (Mc - M0) + Tcea_False_Northing; } return (Error_Code); } /* END OF Convert_Geodetic_To_Trans_Cyl_Eq_Area */ long ossimTransCylEquAreaProjection::Convert_Trans_Cyl_Eq_Area_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Trans_Cyl_Eq_Area_To_Geodetic */ /* * The function Convert_Trans_Cyl_Eq_Area_To_Geodetic converts Transverse * Cylindrical Equal Area projection (easting and northing) coordinates * to geodetic (latitude and longitude) coordinates, according to the * current ellipsoid and Transverse Cylindrical Equal Area projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise TCEA_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double x; double dx; /* Delta easting - Difference in easting (easting-FE) */ double dy; /* Delta northing - Difference in northing (northing-FN) */ double Mc; double MUc; double sin2mu, sin4mu, sin6mu, sin8mu; double PHIc; double Qc; double sin_lat; double beta, betac, beta_prime; double sin2beta, sin4beta, sin6beta; double cosbetac; double Qc_OVER_qp; double temp; long Error_Code = TCEA_NO_ERROR; // if ((Easting < (Tcea_False_Easting + Tcea_Min_Easting)) // || (Easting > (Tcea_False_Easting + Tcea_Max_Easting))) // { /* Easting out of range */ // Error_Code |= TCEA_EASTING_ERROR; // } // if ((Northing < (Tcea_False_Northing + Tcea_Min_Northing)) // || (Northing > (Tcea_False_Northing + Tcea_Max_Northing))) // { /* Northing out of range */ // Error_Code |= TCEA_NORTHING_ERROR; // } if (!Error_Code) { /* no errors */ dy = Northing - Tcea_False_Northing; dx = Easting - Tcea_False_Easting; Mc = M0 + dy / Tcea_Scale_Factor; MUc = Mc / (Tcea_a * c0); sin2mu = TCEA_COEFF_TIMES_SIN(b0, 2.0, MUc); sin4mu = TCEA_COEFF_TIMES_SIN(b1, 4.0, MUc); sin6mu = TCEA_COEFF_TIMES_SIN(b2, 6.0, MUc); sin8mu = TCEA_COEFF_TIMES_SIN(b3, 8.0, MUc); PHIc = MUc + sin2mu + sin4mu + sin6mu + sin8mu; sin_lat = sin(PHIc); x = es * sin_lat; Qc = TCEA_Q(sin_lat, x); Qc_OVER_qp = Qc / qp; if (Qc_OVER_qp < -1.0) Qc_OVER_qp = -1.0; else if (Qc_OVER_qp > 1.0) Qc_OVER_qp = 1.0; betac = asin(Qc_OVER_qp); cosbetac = cos(betac); temp = Tcea_Scale_Factor * dx * cosbetac * sqrt(1.0 - es2 * sin_lat * sin_lat) / (Tcea_a * cos(PHIc)); if (temp > 1.0) temp = 1.0; else if (temp < -1.0) temp = -1.0; beta_prime = -asin(temp); beta = asin(cos(beta_prime) * sin(betac)); sin2beta = TCEA_COEFF_TIMES_SIN(a0, 2.0, beta); sin4beta = TCEA_COEFF_TIMES_SIN(a1, 4.0, beta); sin6beta = TCEA_COEFF_TIMES_SIN(a2, 6.0, beta); *Latitude = TCEA_L(beta, sin2beta, sin4beta, sin6beta); *Longitude = Tcea_Origin_Long - atan(tan(beta_prime) / cosbetac); // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > M_PI) // *Longitude -= TWO_PI; // if (*Longitude < -M_PI) // *Longitude += TWO_PI; // if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ // *Longitude = M_PI; // else if (*Longitude < -M_PI) // *Longitude = -M_PI; } return (Error_Code); } /* END OF Convert_Trans_Cyl_Eq_Area_To_Geodetic */ //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimTransCylEquAreaProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimTransCylEquAreaProjection* p = dynamic_cast(&proj); if (!p) return false; if (!ossim::almostEqual(Tcea_Scale_Factor,p->Tcea_Scale_Factor)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimTransMercatorProjection.cpp000066400000000000000000000671101352751253100252630ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Transverse Mercator projection code. //******************************************************************* // $Id: ossimTransMercatorProjection.cpp 23002 2014-11-24 17:11:17Z dburken $ #include using namespace std; #include #include RTTI_DEF1(ossimTransMercatorProjection, "ossimTransMercatorProjection", ossimMapProjection) /******************************* DEFINES *********************************/ #define TRANMERC_NO_ERROR 0x0000 #define TRANMERC_LAT_ERROR 0x0001 #define TRANMERC_LON_ERROR 0x0002 #define TRANMERC_EASTING_ERROR 0x0004 #define TRANMERC_NORTHING_ERROR 0x0008 #define TRANMERC_ORIGIN_LAT_ERROR 0x0010 #define TRANMERC_CENT_MER_ERROR 0x0020 #define TRANMERC_A_ERROR 0x0040 #define TRANMERC_B_ERROR 0x0080 #define TRANMERC_A_LESS_B_ERROR 0x0100 #define TRANMERC_SCALE_FACTOR_ERROR 0x0200 #define TRANMERC_LON_WARNING 0x0400 #define MAX_LAT ((M_PI * 90.0)/180.0) /* 90 degrees in radians */ #define MAX_DELTA_LONG ((M_PI * 90.0)/180.0) /* 90 degrees in radians */ #define MIN_SCALE_FACTOR 0.3 #define MAX_SCALE_FACTOR 3.0 #define SPHTMD(Latitude) ((double) (TranMerc_ap * Latitude \ - TranMerc_bp * sin(2.e0 * Latitude) + TranMerc_cp * sin(4.e0 * Latitude) \ - TranMerc_dp * sin(6.e0 * Latitude) + TranMerc_ep * sin(8.e0 * Latitude) ) ) #define SPHSN(Latitude) ((double) (getA() / sqrt( 1.e0 - TranMerc_es * \ pow(sin(Latitude), 2)))) #define SPHSR(Latitude) ((double) (getA() * (1.e0 - TranMerc_es) / \ pow(DENOM(Latitude), 3))) #define DENOM(Latitude) ((double) (sqrt(1.e0 - TranMerc_es * pow(sin(Latitude),2)))) ossimTransMercatorProjection::ossimTransMercatorProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) : ossimMapProjection(ellipsoid, origin), TranMerc_a(6378137.0), TranMerc_f(1.0/298.257223563), TranMerc_es(0.0066943799901413800), TranMerc_ebs(0.0067394967565869), TranMerc_Origin_Lat(origin.latr()), TranMerc_Origin_Long(origin.lonr()), TranMerc_False_Northing(0.0), TranMerc_False_Easting(0.0), TranMerc_Scale_Factor(1.0), TranMerc_ap(6367449.1458008), TranMerc_bp(16038.508696861), TranMerc_cp(16.832613334334), TranMerc_dp(0.021984404273757), TranMerc_Delta_Easting(40000000.0), TranMerc_Delta_Northing(40000000.0) { update(); } ossimTransMercatorProjection::ossimTransMercatorProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing, double scaleFactor) : ossimMapProjection(ellipsoid, origin), TranMerc_a(6378137.0), TranMerc_f(1.0/298.257223563), TranMerc_es(0.0066943799901413800), TranMerc_ebs(0.0067394967565869), TranMerc_Origin_Lat(origin.latr()), TranMerc_Origin_Long(origin.lonr()), TranMerc_False_Northing(falseNorthing), TranMerc_False_Easting(falseEasting), TranMerc_Scale_Factor(scaleFactor), TranMerc_ap(6367449.1458008), TranMerc_bp(16038.508696861), TranMerc_cp(16.832613334334), TranMerc_dp(0.021984404273757), TranMerc_Delta_Easting(40000000.0), TranMerc_Delta_Northing(40000000.0) { update(); } void ossimTransMercatorProjection::update() { Set_Transverse_Mercator_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.latr(), theOrigin.lonr(), TranMerc_False_Easting, TranMerc_False_Northing, TranMerc_Scale_Factor); theFalseEastingNorthing.x = TranMerc_False_Easting; theFalseEastingNorthing.y = TranMerc_False_Northing; ossimMapProjection::update(); } void ossimTransMercatorProjection::setFalseEasting(double falseEasting) { TranMerc_False_Easting = falseEasting; update(); } void ossimTransMercatorProjection::setFalseNorthing(double falseNorthing) { TranMerc_False_Northing = falseNorthing; update(); } void ossimTransMercatorProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { TranMerc_False_Easting = falseEasting; TranMerc_False_Northing = falseNorthing; update(); } void ossimTransMercatorProjection::setScaleFactor(double scaleFactor) { TranMerc_Scale_Factor = scaleFactor; update(); } void ossimTransMercatorProjection::setParameters(double falseEasting, double falseNorthing, double scaleFactor) { TranMerc_False_Easting = falseEasting; TranMerc_False_Northing = falseNorthing; TranMerc_Scale_Factor = scaleFactor; update(); } void ossimTransMercatorProjection::setDefaults() { TranMerc_False_Easting = 0.0; TranMerc_False_Northing = 0.0; TranMerc_Scale_Factor = 1.0; TranMerc_Delta_Easting = 40000000.0; TranMerc_Delta_Northing = 40000000.0; } ossimGpt ossimTransMercatorProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Transverse_Mercator_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimTransMercatorProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Transverse_Mercator(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimTransMercatorProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, ossimKeywordNames::SCALE_FACTOR_KW, TranMerc_Scale_Factor, true); return ossimMapProjection::saveState(kwl, prefix); } bool ossimTransMercatorProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); const char* scaleFactor = kwl.find(prefix, ossimKeywordNames::SCALE_FACTOR_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimTransMercatorProjection)) { TranMerc_False_Easting = theFalseEastingNorthing.x; TranMerc_False_Northing = theFalseEastingNorthing.y; if(scaleFactor) { double d = ossimString(scaleFactor).toDouble(); if (d > 0.0) // Check to avoid divide by zero. { TranMerc_Scale_Factor = d; } } } update(); return flag; } /************************************************************************/ /* FUNCTIONS * */ long ossimTransMercatorProjection::Set_Transverse_Mercator_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing, double Scale_Factor) { /* BEGIN Set_Tranverse_Mercator_Parameters */ /* * The function Set_Tranverse_Mercator_Parameters receives the ellipsoid * parameters and Tranverse Mercator projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, the error * code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at the origin of the (input) * projection * Central_Meridian : Longitude in radians at the center of the (input) * projection * False_Easting : Easting/X at the center of the projection (input) * False_Northing : Northing/Y at the center of the projection (input) * Scale_Factor : Projection scale factor (input) */ double tn; /* True Meridianal distance constant */ double tn2; double tn3; double tn4; double tn5; double dummy_northing; double TranMerc_b; /* Semi-minor axis of ellipsoid, in meters */ // double inv_f = 1 / f; long Error_Code = TRANMERC_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= TRANMERC_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= TRANMERC_INV_F_ERROR; // } // if ((Origin_Latitude < -MAX_LAT) || (Origin_Latitude > MAX_LAT)) // { /* origin latitude out of range */ // Error_Code |= TRANMERC_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -M_PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= TRANMERC_CENT_MER_ERROR; // } // if ((Scale_Factor < MIN_SCALE_FACTOR) || (Scale_Factor > MAX_SCALE_FACTOR)) // { // Error_Code |= TRANMERC_SCALE_FACTOR_ERROR; // } if (!Error_Code) { /* no errors */ TranMerc_a = a; TranMerc_f = f; TranMerc_Origin_Lat = 0; TranMerc_Origin_Long = 0; TranMerc_False_Northing = 0; TranMerc_False_Easting = 0; TranMerc_Scale_Factor = 1; /* Eccentricity Squared */ TranMerc_es = 2 * TranMerc_f - TranMerc_f * TranMerc_f; /* Second Eccentricity Squared */ TranMerc_ebs = (1 / (1 - TranMerc_es)) - 1; TranMerc_b = TranMerc_a * (1 - TranMerc_f); /*True meridianal constants */ tn = (TranMerc_a - TranMerc_b) / (TranMerc_a + TranMerc_b); tn2 = tn * tn; tn3 = tn2 * tn; tn4 = tn3 * tn; tn5 = tn4 * tn; TranMerc_ap = TranMerc_a * (1.e0 - tn + 5.e0 * (tn2 - tn3)/4.e0 + 81.e0 * (tn4 - tn5)/64.e0 ); TranMerc_bp = 3.e0 * TranMerc_a * (tn - tn2 + 7.e0 * (tn3 - tn4) /8.e0 + 55.e0 * tn5/64.e0 )/2.e0; TranMerc_cp = 15.e0 * TranMerc_a * (tn2 - tn3 + 3.e0 * (tn4 - tn5 )/4.e0) /16.0; TranMerc_dp = 35.e0 * TranMerc_a * (tn3 - tn4 + 11.e0 * tn5 / 16.e0) / 48.e0; TranMerc_ep = 315.e0 * TranMerc_a * (tn4 - tn5) / 512.e0; Convert_Geodetic_To_Transverse_Mercator(MAX_LAT, MAX_DELTA_LONG, &TranMerc_Delta_Easting, &TranMerc_Delta_Northing); Convert_Geodetic_To_Transverse_Mercator(0, MAX_DELTA_LONG, &TranMerc_Delta_Easting, &dummy_northing); TranMerc_Origin_Lat = Origin_Latitude; if (Central_Meridian > M_PI) Central_Meridian -= TWO_PI; TranMerc_Origin_Long = Central_Meridian; TranMerc_False_Northing = False_Northing; TranMerc_False_Easting = False_Easting; TranMerc_Scale_Factor = Scale_Factor; } /* END OF if(!Error_Code) */ return (Error_Code); } /* END of Set_Transverse_Mercator_Parameters */ void ossimTransMercatorProjection::Get_Transverse_Mercator_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing, double *Scale_Factor)const { /* BEGIN Get_Tranverse_Mercator_Parameters */ /* * The function Get_Transverse_Mercator_Parameters returns the current * ellipsoid and Transverse Mercator projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at the origin of the (output) * projection * Central_Meridian : Longitude in radians at the center of the (output) * projection * False_Easting : Easting/X at the center of the projection (output) * False_Northing : Northing/Y at the center of the projection (output) * Scale_Factor : Projection scale factor (output) */ *a = TranMerc_a; *f = TranMerc_f; *Origin_Latitude = TranMerc_Origin_Lat; *Central_Meridian = TranMerc_Origin_Long; *False_Easting = TranMerc_False_Easting; *False_Northing = TranMerc_False_Northing; *Scale_Factor = TranMerc_Scale_Factor; return; } /* END OF Get_Tranverse_Mercator_Parameters */ long ossimTransMercatorProjection::Convert_Geodetic_To_Transverse_Mercator (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Transverse_Mercator */ /* * The function Convert_Geodetic_To_Transverse_Mercator converts geodetic * (latitude and longitude) coordinates to Transverse Mercator projection * (easting and northing) coordinates, according to the current ellipsoid * and Transverse Mercator projection coordinates. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ double c; /* Cosine of latitude */ double c2; double c3; double c5; double c7; double dlam; /* Delta longitude - Difference in Longitude */ double eta; /* constant - TranMerc_ebs *c *c */ double eta2; double eta3; double eta4; double s; /* Sine of latitude */ double sn; /* Radius of curvature in the prime vertical */ double t; /* Tangent of latitude */ double tan2; double tan3; double tan4; double tan5; double tan6; double t1; /* Term in coordinate conversion formula - GP to Y */ double t2; /* Term in coordinate conversion formula - GP to Y */ double t3; /* Term in coordinate conversion formula - GP to Y */ double t4; /* Term in coordinate conversion formula - GP to Y */ double t5; /* Term in coordinate conversion formula - GP to Y */ double t6; /* Term in coordinate conversion formula - GP to Y */ double t7; /* Term in coordinate conversion formula - GP to Y */ double t8; /* Term in coordinate conversion formula - GP to Y */ double t9; /* Term in coordinate conversion formula - GP to Y */ double tmd; /* True Meridional distance */ double tmdo; /* True Meridional distance for latitude of origin */ long Error_Code = TRANMERC_NO_ERROR; // double temp_Origin; // double temp_Long; // if ((Latitude < -MAX_LAT) || (Latitude > MAX_LAT)) // { /* Latitude out of range */ // Error_Code|= TRANMERC_LAT_ERROR; // } if (Longitude > M_PI) Longitude -= TWO_PI; // if ((Longitude < (TranMerc_Origin_Long - MAX_DELTA_LONG)) // || (Longitude > (TranMerc_Origin_Long + MAX_DELTA_LONG))) // { // if (Longitude < 0) // temp_Long = Longitude + TWO_PI; // else // temp_Long = Longitude; // if (TranMerc_Origin_Long < 0) // temp_Origin = TranMerc_Origin_Long + TWO_PI; // else // temp_Origin = TranMerc_Origin_Long; // if ((temp_Long < (temp_Origin - MAX_DELTA_LONG)) // || (temp_Long > (temp_Origin + MAX_DELTA_LONG))) // Error_Code|= TRANMERC_LON_ERROR; // } if (!Error_Code) { /* no errors */ /* * Delta Longitude */ dlam = Longitude - TranMerc_Origin_Long; // if (fabs(dlam) > (9.0 * M_PI / 180)) // { /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian */ // Error_Code |= TRANMERC_LON_WARNING; // } if (dlam > M_PI) dlam -= TWO_PI; if (dlam < -M_PI) dlam += TWO_PI; if (fabs(dlam) < 2.e-10) dlam = 0.0; s = sin(Latitude); c = cos(Latitude); c2 = c * c; c3 = c2 * c; c5 = c3 * c2; c7 = c5 * c2; t = tan (Latitude); tan2 = t * t; tan3 = tan2 * t; tan4 = tan3 * t; tan5 = tan4 * t; tan6 = tan5 * t; eta = TranMerc_ebs * c2; eta2 = eta * eta; eta3 = eta2 * eta; eta4 = eta3 * eta; /* radius of curvature in prime vertical */ sn = SPHSN(Latitude); /* True Meridianal Distances */ tmd = SPHTMD(Latitude); /* Origin */ tmdo = SPHTMD (TranMerc_Origin_Lat); /* northing */ t1 = (tmd - tmdo) * TranMerc_Scale_Factor; t2 = sn * s * c * TranMerc_Scale_Factor/ 2.e0; t3 = sn * s * c3 * TranMerc_Scale_Factor * (5.e0 - tan2 + 9.e0 * eta + 4.e0 * eta2) /24.e0; t4 = sn * s * c5 * TranMerc_Scale_Factor * (61.e0 - 58.e0 * tan2 + tan4 + 270.e0 * eta - 330.e0 * tan2 * eta + 445.e0 * eta2 + 324.e0 * eta3 -680.e0 * tan2 * eta2 + 88.e0 * eta4 -600.e0 * tan2 * eta3 - 192.e0 * tan2 * eta4) / 720.e0; t5 = sn * s * c7 * TranMerc_Scale_Factor * (1385.e0 - 3111.e0 * tan2 + 543.e0 * tan4 - tan6) / 40320.e0; *Northing = TranMerc_False_Northing + t1 + pow(dlam,2.e0) * t2 + pow(dlam,4.e0) * t3 + pow(dlam,6.e0) * t4 + pow(dlam,8.e0) * t5; /* Easting */ t6 = sn * c * TranMerc_Scale_Factor; t7 = sn * c3 * TranMerc_Scale_Factor * (1.e0 - tan2 + eta ) /6.e0; t8 = sn * c5 * TranMerc_Scale_Factor * (5.e0 - 18.e0 * tan2 + tan4 + 14.e0 * eta - 58.e0 * tan2 * eta + 13.e0 * eta2 + 4.e0 * eta3 - 64.e0 * tan2 * eta2 - 24.e0 * tan2 * eta3 )/ 120.e0; t9 = sn * c7 * TranMerc_Scale_Factor * ( 61.e0 - 479.e0 * tan2 + 179.e0 * tan4 - tan6 ) /5040.e0; *Easting = TranMerc_False_Easting + dlam * t6 + pow(dlam,3.e0) * t7 + pow(dlam,5.e0) * t8 + pow(dlam,7.e0) * t9; } return (Error_Code); } /* END OF Convert_Geodetic_To_Transverse_Mercator */ long ossimTransMercatorProjection::Convert_Transverse_Mercator_To_Geodetic (double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Transverse_Mercator_To_Geodetic */ /* * The function Convert_Transverse_Mercator_To_Geodetic converts Transverse * Mercator projection (easting and northing) coordinates to geodetic * (latitude and longitude) coordinates, according to the current ellipsoid * and Transverse Mercator projection parameters. If any errors occur, the * error code(s) are returned by the function, otherwise TRANMERC_NO_ERROR is * returned. * * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ double c; /* Cosine of latitude */ double de; /* Delta easting - Difference in Easting (Easting-Fe) */ double dlam; /* Delta longitude - Difference in Longitude */ double eta; /* constant - TranMerc_ebs *c *c */ double eta2; double eta3; double eta4; double ftphi; /* Footpoint latitude */ int i; /* Loop iterator */ // double s; /* Sine of latitude */ double sn; /* Radius of curvature in the prime vertical */ double sr; /* Radius of curvature in the meridian */ double t; /* Tangent of latitude */ double tan2; double tan4; double t10; /* Term in coordinate conversion formula - GP to Y */ double t11; /* Term in coordinate conversion formula - GP to Y */ double t12; /* Term in coordinate conversion formula - GP to Y */ double t13; /* Term in coordinate conversion formula - GP to Y */ double t14; /* Term in coordinate conversion formula - GP to Y */ double t15; /* Term in coordinate conversion formula - GP to Y */ double t16; /* Term in coordinate conversion formula - GP to Y */ double t17; /* Term in coordinate conversion formula - GP to Y */ double tmd; /* True Meridional distance */ double tmdo; /* True Meridional distance for latitude of origin */ long Error_Code = TRANMERC_NO_ERROR; // if ((Easting < (TranMerc_False_Easting - TranMerc_Delta_Easting)) // ||(Easting > (TranMerc_False_Easting + TranMerc_Delta_Easting))) // { /* Easting out of range */ // Error_Code |= TRANMERC_EASTING_ERROR; // } // if ((Northing < (TranMerc_False_Northing - TranMerc_Delta_Northing)) // || (Northing > (TranMerc_False_Northing + TranMerc_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= TRANMERC_NORTHING_ERROR; // } if (!Error_Code) { /* True Meridional Distances for latitude of origin */ tmdo = SPHTMD(TranMerc_Origin_Lat); /* Origin */ tmd = tmdo + (Northing - TranMerc_False_Northing) / TranMerc_Scale_Factor; /* First Estimate */ sr = SPHSR(0.e0); ftphi = tmd/sr; for (i = 0; i < 5 ; i++) { t10 = SPHTMD (ftphi); sr = SPHSR(ftphi); ftphi = ftphi + (tmd - t10) / sr; } /* Radius of Curvature in the meridian */ sr = SPHSR(ftphi); /* Radius of Curvature in the meridian */ sn = SPHSN(ftphi); /* Sine Cosine terms */ // s = sin(ftphi); c = cos(ftphi); /* Tangent Value */ t = tan(ftphi); tan2 = t * t; tan4 = tan2 * tan2; eta = TranMerc_ebs * pow(c,2); eta2 = eta * eta; eta3 = eta2 * eta; eta4 = eta3 * eta; de = Easting - TranMerc_False_Easting; if (fabs(de) < 0.0001) de = 0.0; /* Latitude */ t10 = t / (2.e0 * sr * sn * pow(TranMerc_Scale_Factor, 2)); t11 = t * (5.e0 + 3.e0 * tan2 + eta - 4.e0 * pow(eta,2) - 9.e0 * tan2 * eta) / (24.e0 * sr * pow(sn,3) * pow(TranMerc_Scale_Factor,4)); t12 = t * (61.e0 + 90.e0 * tan2 + 46.e0 * eta + 45.E0 * tan4 - 252.e0 * tan2 * eta - 3.e0 * eta2 + 100.e0 * eta3 - 66.e0 * tan2 * eta2 - 90.e0 * tan4 * eta + 88.e0 * eta4 + 225.e0 * tan4 * eta2 + 84.e0 * tan2* eta3 - 192.e0 * tan2 * eta4) / ( 720.e0 * sr * pow(sn,5) * pow(TranMerc_Scale_Factor, 6) ); t13 = t * ( 1385.e0 + 3633.e0 * tan2 + 4095.e0 * tan4 + 1575.e0 * pow(t,6))/ (40320.e0 * sr * pow(sn,7) * pow(TranMerc_Scale_Factor,8)); *Latitude = ftphi - pow(de,2) * t10 + pow(de,4) * t11 - pow(de,6) * t12 + pow(de,8) * t13; t14 = 1.e0 / (sn * c * TranMerc_Scale_Factor); t15 = (1.e0 + 2.e0 * tan2 + eta) / (6.e0 * pow(sn,3) * c * pow(TranMerc_Scale_Factor,3)); t16 = (5.e0 + 6.e0 * eta + 28.e0 * tan2 - 3.e0 * eta2 + 8.e0 * tan2 * eta + 24.e0 * tan4 - 4.e0 * eta3 + 4.e0 * tan2 * eta2 + 24.e0 * tan2 * eta3) / (120.e0 * pow(sn,5) * c * pow(TranMerc_Scale_Factor,5)); t17 = (61.e0 + 662.e0 * tan2 + 1320.e0 * tan4 + 720.e0 * pow(t,6)) / (5040.e0 * pow(sn,7) * c * pow(TranMerc_Scale_Factor,7)); /* Difference in Longitude */ dlam = de * t14 - pow(de,3) * t15 + pow(de,5) * t16 - pow(de,7) * t17; /* Longitude */ (*Longitude) = TranMerc_Origin_Long + dlam; while (*Latitude > (90.0 * RAD_PER_DEG)) { *Latitude = M_PI - *Latitude; *Longitude += M_PI; if (*Longitude > M_PI) *Longitude -= TWO_PI; } while (*Latitude < (-90.0 * RAD_PER_DEG)) { *Latitude = - (*Latitude + M_PI); *Longitude += M_PI; if (*Longitude > M_PI) *Longitude -= TWO_PI; } if (*Longitude > TWO_PI) *Longitude -= TWO_PI; if (*Longitude < -M_PI) *Longitude += TWO_PI; // if (fabs(dlam) > (9.0 * M_PI / 180)) // { /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian */ // Error_Code |= TRANMERC_LON_WARNING; // } } return (Error_Code); } /* END OF Convert_Transverse_Mercator_To_Geodetic */ std::ostream& ossimTransMercatorProjection::print(std::ostream& out) const { out << setiosflags(ios::fixed) << setprecision(15) << "// ossimTransMercatorProjection::print\n" << ossimKeywordNames::SCALE_FACTOR_KW << ": " << TranMerc_Scale_Factor << endl; return ossimMapProjection::print(out); } //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimTransMercatorProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimTransMercatorProjection* p = dynamic_cast(&proj); if (!p) return false; if (!ossim::almostEqual(TranMerc_Scale_Factor,p->TranMerc_Scale_Factor)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimUps.c000066400000000000000000000235731352751253100206560ustar00rootroot00000000000000/********************************************************************/ /* RSC IDENTIFIER: UPS * * * ABSTRACT * * This component provides conversions between geodetic (latitude * and longitude) coordinates and Universal Polar Stereographic (UPS) * projection (hemisphere, easting, and northing) coordinates. * * * ERROR HANDLING * * This component checks parameters for valid values. If an * invalid value is found the error code is combined with the * current error code using the bitwise or. This combining allows * multiple error codes to be returned. The possible error codes * are: * * UPS_NO_ERROR : No errors occurred in function * UPS_LAT_ERROR : Latitude outside of valid range * (North Pole: 83.5 to 90, * South Pole: -79.5 to -90) * UPS_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees) * UPS_HEMISPHERE_ERROR : Invalid hemisphere ('N' or 'S') * UPS_EASTING_ERROR : Easting outside of valid range, * (0 to 4,000,000m) * UPS_NORTHING_ERROR : Northing outside of valid range, * (0 to 4,000,000m) * UPS_A_ERROR : Semi-major axis less than or equal to zero * UPS_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * * * REUSE NOTES * * UPS is intended for reuse by any application that performs a Universal * Polar Stereographic (UPS) projection. * * * REFERENCES * * Further information on UPS can be found in the Reuse Manual. * * UPS originated from : U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * * LICENSES * * None apply to this component. * * * RESTRICTIONS * * UPS has no restrictions. * * * ENVIRONMENT * * UPS was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC version 2.8.1 * 2. Windows 95 with MS Visual C++ version 6 * * * MODIFICATIONS * * Date Description * ---- ----------- * 06-11-95 Original Code * 03-01-97 Original Code * * */ /************************************************************************/ /* * INCLUDES */ #include #include #include /* * math.h - Is needed to call the math functions. * polar.h - Is used to convert polar stereographic coordinates * ups.h - Defines the function prototypes for the ups module. */ /************************************************************************/ /* GLOBAL DECLARATIONS * */ #define PI 3.14159265358979323e0 /* PI */ #define PI_OVER (PI/2.0e0) /* PI over 2 */ #define MAX_LAT ((PI * 90)/180.0) /* 90 degrees in radians */ #define MAX_ORIGIN_LAT ((81.114528 * PI) / 180.0) #define MIN_NORTH_LAT (83.5*PI/180.0) #define MIN_SOUTH_LAT (-79.5*PI/180.0) #define MIN_EAST_NORTH 0 #define MAX_EAST_NORTH 4000000 /* Ellipsoid Parameters, default to WGS 84 */ static double UPS_a = 6378137.0; /* Semi-major axis of ellipsoid in meters */ static double UPS_f = 1 / 298.257223563; /* Flattening of ellipsoid */ const double UPS_False_Easting = 2000000; const double UPS_False_Northing = 2000000; static double UPS_Origin_Latitude = MAX_ORIGIN_LAT; /*set default = North Hemisphere */ static double UPS_Origin_Longitude = 0.0; static double false_easting = 0.0; static double false_northing = 0.0; static double UPS_Easting = 0.0; static double UPS_Northing = 0.0; /************************************************************************/ /* FUNCTIONS * */ long Set_UPS_Parameters( double a, double f) { /* * The function SET_UPS_PARAMETERS receives the ellipsoid parameters and sets * the corresponding state variables. If any errors occur, the error code(s) * are returned by the function, otherwise UPS_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid in meters (input) * f : Flattening of ellipsoid (input) */ double inv_f = 1 / f; long Error_Code = UPS_NO_ERROR; if (a <= 0.0) { /* Semi-major axis must be greater than zero */ Error_Code |= UPS_A_ERROR; } if ((inv_f < 250) || (inv_f > 350)) { /* Inverse flattening must be between 250 and 350 */ Error_Code |= UPS_INV_F_ERROR; } if (!Error_Code) { /* no errors */ UPS_a = a; UPS_f = f; } return (Error_Code); } /* END of Set_UPS_Parameters */ void Get_UPS_Parameters( double *a, double *f) { /* * The function Get_UPS_Parameters returns the current ellipsoid parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) */ *a = UPS_a; *f = UPS_f; return; } /* END OF Get_UPS_Parameters */ long Convert_Geodetic_To_UPS ( double Latitude, double Longitude, char *Hemisphere, double *Easting, double *Northing) { /* * The function Convert_Geodetic_To_UPS converts geodetic (latitude and * longitude) coordinates to UPS (hemisphere, easting, and northing) * coordinates, according to the current ellipsoid parameters. If any * errors occur, the error code(s) are returned by the function, * otherwide UPS_NO_ERROR is returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Hemisphere : Hemisphere either 'N' or 'S' (output) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ double tempEasting, tempNorthing; long Error_Code = UPS_NO_ERROR; if ((Latitude < -MAX_LAT) || (Latitude > MAX_LAT)) { /* latitude out of range */ Error_Code |= UPS_LAT_ERROR; } if ((Latitude < 0) && (Latitude > MIN_SOUTH_LAT)) Error_Code |= UPS_LAT_ERROR; if ((Latitude >= 0) && (Latitude < MIN_NORTH_LAT)) Error_Code |= UPS_LAT_ERROR; if ((Longitude < -PI) || (Longitude > (2 * PI))) { /* slam out of range */ Error_Code |= UPS_LON_ERROR; } if (!Error_Code) { /* no errors */ if (Latitude < 0) { UPS_Origin_Latitude = -MAX_ORIGIN_LAT; *Hemisphere = 'S'; } else { UPS_Origin_Latitude = MAX_ORIGIN_LAT; *Hemisphere = 'N'; } Set_Polar_Stereographic_Parameters( UPS_a, UPS_f, UPS_Origin_Latitude, UPS_Origin_Longitude, false_easting, false_northing); Convert_Geodetic_To_Polar_Stereographic(Latitude, Longitude, &tempEasting, &tempNorthing); UPS_Easting = UPS_False_Easting + tempEasting; UPS_Northing = UPS_False_Northing + tempNorthing; *Easting = UPS_Easting; *Northing = UPS_Northing; } /* END of if(!Error_Code) */ return (Error_Code); } /* END OF Convert_Geodetic_To_UPS */ long Convert_UPS_To_Geodetic(char Hemisphere, double Easting, double Northing, double *Latitude, double *Longitude) { /* * The function Convert_UPS_To_Geodetic converts UPS (hemisphere, easting, * and northing) coordinates to geodetic (latitude and longitude) coordinates * according to the current ellipsoid parameters. If any errors occur, the * error code(s) are returned by the function, otherwise UPS_NO_ERROR is * returned. * * Hemisphere : Hemisphere either 'N' or 'S' (input) * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ long Error_Code = UPS_NO_ERROR; if ((Hemisphere != 'N') && (Hemisphere != 'S')) Error_Code |= UPS_HEMISPHERE_ERROR; if ((Easting < MIN_EAST_NORTH) || (Easting > MAX_EAST_NORTH)) Error_Code |= UPS_EASTING_ERROR; if ((Northing < MIN_EAST_NORTH) || (Northing > MAX_EAST_NORTH)) Error_Code |= UPS_NORTHING_ERROR; if (Hemisphere =='N') {UPS_Origin_Latitude = MAX_ORIGIN_LAT;} if (Hemisphere =='S') {UPS_Origin_Latitude = -MAX_ORIGIN_LAT;} if (!Error_Code) { /* no errors */ Set_Polar_Stereographic_Parameters( UPS_a, UPS_f, UPS_Origin_Latitude, UPS_Origin_Longitude, UPS_False_Easting, UPS_False_Northing); Convert_Polar_Stereographic_To_Geodetic( Easting, Northing, Latitude, Longitude); if ((*Latitude < 0) && (*Latitude > MIN_SOUTH_LAT)) Error_Code |= UPS_LAT_ERROR; if ((*Latitude >= 0) && (*Latitude < MIN_NORTH_LAT)) Error_Code |= UPS_LAT_ERROR; } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Convert_UPS_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimUpsProjection.cpp000066400000000000000000000255211352751253100232460ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimUpsProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include #define PI 3.14159265358979323e0 /* PI */ #define PI_OVER (PI/2.0e0) /* PI over 2 */ #define MAX_LAT ((PI * 90)/180.0) /* 90 degrees in radians */ #define MAX_ORIGIN_LAT ((81.114528 * PI) / 180.0) #define MIN_NORTH_LAT (83.5*PI/180.0) #define MIN_SOUTH_LAT (-79.5*PI/180.0) #define MIN_EAST_NORTH 0 #define MAX_EAST_NORTH 4000000 #define UPS_NO_ERROR 0x0000 #define UPS_LAT_ERROR 0x0001 #define UPS_LON_ERROR 0x0002 #define UPS_HEMISPHERE_ERROR 0x0004 #define UPS_EASTING_ERROR 0x0008 #define UPS_NORTHING_ERROR 0x0010 #define UPS_A_ERROR 0x0020 #define UPS_INV_F_ERROR 0x0040 RTTI_DEF1(ossimUpsProjection, "ossimUpsProjection", ossimMapProjection); ossimUpsProjection::ossimUpsProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } void ossimUpsProjection::setDefaults() { if(theOrigin.latd() >= -FLT_EPSILON) { UPS_Origin_Latitude = MAX_ORIGIN_LAT; theHemisphere = 'N'; } else { UPS_Origin_Latitude = -MAX_ORIGIN_LAT; theHemisphere = 'S'; } UPS_False_Easting = 2000000; UPS_False_Northing = 2000000; false_easting = 0.0; false_northing = 0.0; UPS_Easting = 0.0; UPS_Northing = 0.0; UPS_Origin_Longitude = 0.0; theOrigin = ossimGpt(UPS_Origin_Latitude*DEG_PER_RAD, 0.0,0.0); } void ossimUpsProjection::setHemisphere(char hemisphere) { theHemisphere = hemisphere; update(); } ossimGpt ossimUpsProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_UPS_To_Geodetic(theHemisphere, eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimUpsProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_UPS(gpt.latr(), gpt.lonr(), &theHemisphere, &easting, &northing); return ossimDpt(easting, northing); } void ossimUpsProjection::update() { Set_UPS_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening()); theFalseEastingNorthing.x = UPS_False_Easting; theFalseEastingNorthing.y = UPS_False_Northing; ossimMapProjection::update(); } /*! * Method to save the state of an object to a keyword list. * Return true if ok or false on error. */ bool ossimUpsProjection::saveState(ossimKeywordlist& kwl, const char* prefix)const { return ossimMapProjection::saveState(kwl, prefix); } /*! * Method to the load (recreate) the state of an object from a keyword * list. Return true if ok or false on error. */ bool ossimUpsProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { setDefaults(); return ossimMapProjection::loadState(kwl, prefix); } /************************************************************************/ /* FUNCTIONS * */ long ossimUpsProjection::Set_UPS_Parameters( double a, double f) { /* * The function SET_UPS_PARAMETERS receives the ellipsoid parameters and sets * the corresponding state variables. If any errors occur, the error code(s) * are returned by the function, otherwise UPS_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid in meters (input) * f : Flattening of ellipsoid (input) */ // double inv_f = 1 / f; long Error_Code = UPS_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= UPS_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= UPS_INV_F_ERROR; // } if (!Error_Code) { /* no errors */ UPS_a = a; UPS_f = f; } return (Error_Code); } /* END of Set_UPS_Parameters */ void ossimUpsProjection::Get_UPS_Parameters( double *a, double *f)const { /* * The function Get_UPS_Parameters returns the current ellipsoid parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) */ *a = UPS_a; *f = UPS_f; return; } /* END OF Get_UPS_Parameters */ long ossimUpsProjection::Convert_Geodetic_To_UPS ( double Latitude, double Longitude, char * /* Hemisphere */, double *Easting, double *Northing)const { /* * The function Convert_Geodetic_To_UPS converts geodetic (latitude and * longitude) coordinates to UPS (hemisphere, easting, and northing) * coordinates, according to the current ellipsoid parameters. If any * errors occur, the error code(s) are returned by the function, * otherwide UPS_NO_ERROR is returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Hemisphere : Hemisphere either 'N' or 'S' (output) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ double tempEasting, tempNorthing; long Error_Code = UPS_NO_ERROR; // if ((Latitude < -MAX_LAT) || (Latitude > MAX_LAT)) // { /* latitude out of range */ // Error_Code |= UPS_LAT_ERROR; // } // if ((Latitude < 0) && (Latitude > MIN_SOUTH_LAT)) // Error_Code |= UPS_LAT_ERROR; // if ((Latitude >= 0) && (Latitude < MIN_NORTH_LAT)) // Error_Code |= UPS_LAT_ERROR; // if ((Longitude < -PI) || (Longitude > (2 * PI))) // { /* slam out of range */ // Error_Code |= UPS_LON_ERROR; // } if (!Error_Code) { /* no errors */ // if (Latitude < 0) // { // UPS_Origin_Latitude = -MAX_ORIGIN_LAT; // *Hemisphere = 'S'; // } // else // { // UPS_Origin_Latitude = MAX_ORIGIN_LAT; // *Hemisphere = 'N'; // } Set_Polar_Stereographic_Parameters( UPS_a, UPS_f, UPS_Origin_Latitude, UPS_Origin_Longitude, false_easting, false_northing); Convert_Geodetic_To_Polar_Stereographic(Latitude, Longitude, &tempEasting, &tempNorthing); UPS_Easting = UPS_False_Easting + tempEasting; UPS_Northing = UPS_False_Northing + tempNorthing; *Easting = UPS_Easting; *Northing = UPS_Northing; } /* END of if(!Error_Code) */ return (Error_Code); } /* END OF Convert_Geodetic_To_UPS */ long ossimUpsProjection::Convert_UPS_To_Geodetic(char Hemisphere, double Easting, double Northing, double *Latitude, double *Longitude)const { /* * The function Convert_UPS_To_Geodetic converts UPS (hemisphere, easting, * and northing) coordinates to geodetic (latitude and longitude) coordinates * according to the current ellipsoid parameters. If any errors occur, the * error code(s) are returned by the function, otherwise UPS_NO_ERROR is * returned. * * Hemisphere : Hemisphere either 'N' or 'S' (input) * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ long Error_Code = UPS_NO_ERROR; // if ((Hemisphere != 'N') && (Hemisphere != 'S')) // Error_Code |= UPS_HEMISPHERE_ERROR; // if ((Easting < MIN_EAST_NORTH) || (Easting > MAX_EAST_NORTH)) // Error_Code |= UPS_EASTING_ERROR; // if ((Northing < MIN_EAST_NORTH) || (Northing > MAX_EAST_NORTH)) // Error_Code |= UPS_NORTHING_ERROR; if (Hemisphere =='N') {UPS_Origin_Latitude = MAX_ORIGIN_LAT;} if (Hemisphere =='S') {UPS_Origin_Latitude = -MAX_ORIGIN_LAT;} if (!Error_Code) { /* no errors */ Set_Polar_Stereographic_Parameters( UPS_a, UPS_f, UPS_Origin_Latitude, UPS_Origin_Longitude, UPS_False_Easting, UPS_False_Northing); Convert_Polar_Stereographic_To_Geodetic( Easting, Northing, Latitude, Longitude); // if ((*Latitude < 0) && (*Latitude > MIN_SOUTH_LAT)) // Error_Code |= UPS_LAT_ERROR; // if ((*Latitude >= 0) && (*Latitude < MIN_NORTH_LAT)) // Error_Code |= UPS_LAT_ERROR; } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Convert_UPS_To_Geodetic */ //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimUpsProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimUpsProjection* p = dynamic_cast(&proj); if (!p) return false; if (theHemisphere != p->theHemisphere) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimUpspt.cpp000066400000000000000000000026411352751253100215530ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // // Description: // // This is the Universal Polar Stereographic (UPS) point. Allows // easy onversion between different coordinates. //******************************************************************* // $Id: ossimUpspt.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include #include #include #include #include #include ossimUpspt::ossimUpspt(const ossimGpt &aPt) { convertFromGeodetic(aPt); } ossimUpspt::ossimUpspt(const ossimEcefPoint &aPt) { convertFromGeodetic(ossimGpt(aPt)); } void ossimUpspt::convertFromGeodetic(const ossimGpt &aPt) { const ossimDatum *aDatum = aPt.datum(); if(aDatum) { Set_UPS_Parameters(aDatum->ellipsoid()->a(), aDatum->ellipsoid()->b()); Convert_Geodetic_To_UPS(aPt.latr(), aPt.lonr(), &theHemisphere, &theEasting, &theNorthing); theDatum = const_cast(aDatum); } else { //ERROR: should never happen } } ossim-Miami-2.9.1/src/projection/ossimUtm.c000066400000000000000000000277261352751253100206600ustar00rootroot00000000000000/***************************************************************************/ /* RSC IDENTIFIER: UTM * * ABSTRACT * * This component provides conversions between geodetic coordinates * (latitude and longitudes) and Universal Transverse Mercator (UTM) * projection (zone, hemisphere, easting, and northing) coordinates. * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid value * is found, the error code is combined with the current error code using * the bitwise or. This combining allows multiple error codes to be * returned. The possible error codes are: * * UTM_NO_ERROR : No errors occurred in function * UTM_LAT_ERROR : Latitude outside of valid range * (-80.5 to 84.5 degrees) * UTM_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees) * UTM_EASTING_ERROR : Easting outside of valid range * (100,000 to 900,000 meters) * UTM_NORTHING_ERROR : Northing outside of valid range * (0 to 10,000,000 meters) * UTM_ZONE_ERROR : Zone outside of valid range (1 to 60) * UTM_HEMISPHERE_ERROR : Invalid hemisphere ('N' or 'S') * UTM_ZONE_OVERRIDE_ERROR: Zone outside of valid range * (1 to 60) and within 1 of 'natural' zone * UTM_A_ERROR : Semi-major axis less than or equal to zero * UTM_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * * REUSE NOTES * * UTM is intended for reuse by any application that performs a Universal * Transverse Mercator (UTM) projection or its inverse. * * REFERENCES * * Further information on UTM can be found in the Reuse Manual. * * UTM originated from : U.S. Army Topographic Engineering Center * Geospatial Information Division * 7701 Telegraph Road * Alexandria, VA 22310-3864 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * UTM has no restrictions. * * ENVIRONMENT * * UTM was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC, version 2.8.1 * 2. MSDOS with MS Visual C++, version 6 * * MODIFICATIONS * * Date Description * ---- ----------- * 10-02-97 Original Code * */ /***************************************************************************/ /* * INCLUDES */ #include #include /* * tranmerc.h - Is used to convert transverse mercator coordinates * utm.h - Defines the function prototypes for the utm module. */ /***************************************************************************/ /* * DEFINES */ #define PI 3.14159265358979323e0 /* PI */ #define MIN_LAT ( (-80.5 * PI) / 180.0 ) /* -80.5 degrees in radians */ #define MAX_LAT ( (84.5 * PI) / 180.0 ) /* 84.5 degrees in radians */ #define MIN_EASTING 100000 #define MAX_EASTING 900000 #define MIN_NORTHING 0 #define MAX_NORTHING 10000000 /***************************************************************************/ /* * GLOBAL DECLARATIONS */ static double UTM_a = 6378137.0; /* Semi-major axis of ellipsoid in meters */ static double UTM_f = 1 / 298.257223563; /* Flattening of ellipsoid */ static long UTM_Override = 0; /* Zone override flag */ /***************************************************************************/ /* * FUNCTIONS * */ long Set_UTM_Parameters(double a, double f, long override) { /* * The function Set_UTM_Parameters receives the ellipsoid parameters and * UTM zone override parameter as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the * function, otherwise UTM_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * override : UTM override zone, zero indicates no override (input) */ double inv_f = 1 / f; long Error_Code = UTM_NO_ERROR; if (a <= 0.0) { /* Semi-major axis must be greater than zero */ Error_Code |= UTM_A_ERROR; } if ((inv_f < 250) || (inv_f > 350)) { /* Inverse flattening must be between 250 and 350 */ Error_Code |= UTM_INV_F_ERROR; } if ((override < 0) || (override > 60)) { Error_Code |= UTM_ZONE_OVERRIDE_ERROR; } if (!Error_Code) { /* no errors */ UTM_a = a; UTM_f = f; UTM_Override = override; } return (Error_Code); } /* END OF Set_UTM_Parameters */ void Get_UTM_Parameters(double *a, double *f, long *override) { /* * The function Get_UTM_Parameters returns the current ellipsoid * parameters and UTM zone override parameter. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * override : UTM override zone, zero indicates no override (output) */ *a = UTM_a; *f = UTM_f; *override = UTM_Override; } /* END OF Get_UTM_Parameters */ long Convert_Geodetic_To_UTM (double Latitude, double Longitude, long *Zone, char *Hemisphere, double *Easting, double *Northing) { /* * The function Convert_Geodetic_To_UTM converts geodetic (latitude and * longitude) coordinates to UTM projection (zone, hemisphere, easting and * northing) coordinates according to the current ellipsoid and UTM zone * override parameters. If any errors occur, the error code(s) are returned * by the function, otherwise UTM_NO_ERROR is returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Zone : UTM zone (output) * Hemisphere : North or South hemisphere (output) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ long Lat_Degrees; long Long_Degrees; long temp_zone; long Error_Code = UTM_NO_ERROR; double Origin_Latitude = 0; double Central_Meridian = 0; double False_Easting = 500000; double False_Northing = 0; double Scale = 0.9996; if ((Latitude < MIN_LAT) || (Latitude > MAX_LAT)) { /* Latitude out of range */ Error_Code |= UTM_LAT_ERROR; } if ((Longitude < -PI) || (Longitude > (2*PI))) { /* Longitude out of range */ Error_Code |= UTM_LON_ERROR; } if (!Error_Code) { /* no errors */ if (Longitude < 0) Longitude += (2*PI); Lat_Degrees = (long)(Latitude * 180.0 / PI); Long_Degrees = (long)(Longitude * 180.0 / PI); if (Longitude < PI) temp_zone = (long)(31 + ((Longitude * 180.0 / PI) / 6.0)); else temp_zone = (long)(((Longitude * 180.0 / PI) / 6.0) - 29); if (temp_zone > 60) temp_zone = 1; /* UTM special cases */ if ((Lat_Degrees > 55) && (Lat_Degrees < 64) && (Long_Degrees > -1) && (Long_Degrees < 3)) temp_zone = 31; if ((Lat_Degrees > 55) && (Lat_Degrees < 64) && (Long_Degrees > 2) && (Long_Degrees < 12)) temp_zone = 32; if ((Lat_Degrees > 71) && (Long_Degrees > -1) && (Long_Degrees < 9)) temp_zone = 31; if ((Lat_Degrees > 71) && (Long_Degrees > 8) && (Long_Degrees < 21)) temp_zone = 33; if ((Lat_Degrees > 71) && (Long_Degrees > 20) && (Long_Degrees < 33)) temp_zone = 35; if ((Lat_Degrees > 71) && (Long_Degrees > 32) && (Long_Degrees < 42)) temp_zone = 37; if (UTM_Override) { if ((temp_zone == 1) && (UTM_Override == 60)) temp_zone = UTM_Override; else if ((temp_zone == 60) && (UTM_Override == 1)) temp_zone = UTM_Override; else if (((temp_zone-1) <= UTM_Override) && (UTM_Override <= (temp_zone+1))) temp_zone = UTM_Override; else Error_Code = UTM_ZONE_OVERRIDE_ERROR; } if (!Error_Code) { if (temp_zone >= 31) Central_Meridian = (6 * temp_zone - 183) * PI / 180.0; else Central_Meridian = (6 * temp_zone + 177) * PI / 180.0; *Zone = temp_zone; if (Latitude < 0) { False_Northing = 10000000; *Hemisphere = 'S'; } else *Hemisphere = 'N'; Set_Transverse_Mercator_Parameters(UTM_a, UTM_f, Origin_Latitude, Central_Meridian, False_Easting, False_Northing, Scale); Convert_Geodetic_To_Transverse_Mercator(Latitude, Longitude, Easting, Northing); if ((*Easting < MIN_EASTING) || (*Easting > MAX_EASTING)) Error_Code = UTM_EASTING_ERROR; if ((*Northing < MIN_NORTHING) || (*Northing > MAX_NORTHING)) Error_Code |= UTM_NORTHING_ERROR; } } /* END OF if (!Error_Code) */ return (Error_Code); } /* END OF Convert_Geodetic_To_UTM */ long Convert_UTM_To_Geodetic(long Zone, char Hemisphere, double Easting, double Northing, double *Latitude, double *Longitude) { /* * The function Convert_UTM_To_Geodetic converts UTM projection (zone, * hemisphere, easting and northing) coordinates to geodetic(latitude * and longitude) coordinates, according to the current ellipsoid * parameters. If any errors occur, the error code(s) are returned * by the function, otherwise UTM_NO_ERROR is returned. * * Zone : UTM zone (input) * Hemisphere : North or South hemisphere (input) * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ long Error_Code = UTM_NO_ERROR; double Origin_Latitude = 0; double Central_Meridian = 0; double False_Easting = 500000; double False_Northing = 0; double Scale = 0.9996; if ((Zone < 1) || (Zone > 60)) Error_Code |= UTM_ZONE_ERROR; if ((Hemisphere != 'S') && (Hemisphere != 'N')) Error_Code |= UTM_HEMISPHERE_ERROR; if ((Easting < MIN_EASTING) || (Easting > MAX_EASTING)) Error_Code |= UTM_EASTING_ERROR; if ((Northing < MIN_NORTHING) || (Northing > MAX_NORTHING)) Error_Code |= UTM_NORTHING_ERROR; if (!Error_Code) { /* no errors */ if (Zone >= 31) Central_Meridian = ((6 * Zone - 183) * PI / 180.0 + 0.00000005); else Central_Meridian = ((6 * Zone + 177) * PI / 180.0 + 0.00000005); if (Hemisphere == 'S') False_Northing = 10000000; Set_Transverse_Mercator_Parameters(UTM_a, UTM_f, Origin_Latitude, Central_Meridian, False_Easting, False_Northing, Scale); if (Convert_Transverse_Mercator_To_Geodetic(Easting, Northing, Latitude, Longitude)) Error_Code |= UTM_NORTHING_ERROR; if ((*Latitude < MIN_LAT) || (*Latitude > MAX_LAT)) { /* Latitude out of range */ Error_Code |= UTM_NORTHING_ERROR; } } return (Error_Code); } /* END OF Convert_UTM_To_Geodetic */ ossim-Miami-2.9.1/src/projection/ossimUtmProjection.cpp000066400000000000000000001011371352751253100232420ustar00rootroot00000000000000//******************************************************************* // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Geotrans Utm projection code. //******************************************************************* // $Id: ossimUtmProjection.cpp 20133 2011-10-12 19:03:47Z oscarkramer $ #include #include using namespace std; #include #include #include #include RTTI_DEF1(ossimUtmProjection, "ossimUtmProjection", ossimMapProjection) /******************************* DEFINES *********************************/ #define UTM_NO_ERROR 0x0000 #define UTM_LAT_ERROR 0x0001 #define UTM_LON_ERROR 0x0002 #define UTM_EASTING_ERROR 0x0004 #define UTM_NORTHING_ERROR 0x0008 #define UTM_ZONE_ERROR 0x0010 #define UTM_HEMISPHERE_ERROR 0x0020 #define UTM_ZONE_OVERRIDE_ERROR 0x0040 #define UTM_A_ERROR 0x0080 #define UTM_B_ERROR 0x0100 #define UTM_A_LESS_B_ERROR 0x0200 #define MIN_LAT ( (-80.5 * M_PI) / 180.0 ) /* -80.5 degrees in radians */ #define MAX_LAT ( (84.5 * M_PI) / 180.0 ) /* 84.5 degrees in radians */ #define MAX_DELTA_LONG ((M_PI * 90.0)/180.0) /* 90 degrees in radians */ #define MIN_EASTING 100000 #define MAX_EASTING 900000 #define MIN_NORTHING 0 #define MAX_NORTHING 10000000 #define MIN_SCALE_FACTOR 0.3 #define MAX_SCALE_FACTOR 3.0 #define SPHTMD(Latitude) ((double) (theTranMerc_ap * Latitude \ - theTranMerc_bp * sin(2.e0 * Latitude) + theTranMerc_cp * sin(4.e0 * Latitude) \ - theTranMerc_dp * sin(6.e0 * Latitude) + theTranMerc_ep * sin(8.e0 * Latitude) ) ) #define SPHSN(Latitude) ((double) (getA() / sqrt( 1.e0 - theTranMerc_es * \ pow(sin(Latitude), 2)))) #define SPHSR(Latitude) ((double) (getA() * (1.e0 - theTranMerc_es) / \ pow(DENOM(Latitude), 3))) #define DENOM(Latitude) ((double) (sqrt(1.e0 - theTranMerc_es * pow(sin(Latitude),2)))) ossimUtmProjection::ossimUtmProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) : ossimMapProjection(ellipsoid, origin), theTranMerc_a(6378137.0), theTranMerc_f(1.0/298.257223563), theTranMerc_es(0.0066943799901413800), theTranMerc_ebs(0.0067394967565869), theTranMerc_Origin_Lat(0.0), theTranMerc_Origin_Long(0.0), theTranMerc_False_Northing(0.0), theTranMerc_False_Easting(500000.0), theTranMerc_Scale_Factor(0.9996), theTranMerc_ap(6367449.1458008), theTranMerc_bp(16038.508696861), theTranMerc_cp(16.832613334334), theTranMerc_dp(0.021984404273757), theTranMerc_Delta_Easting(40000000.0), theTranMerc_Delta_Northing(40000000.0), theZone(1), theHemisphere('N') { setZone(origin); setHemisphere(origin); update(); } ossimUtmProjection::ossimUtmProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, ossim_int32 zone, char hemisphere) : ossimMapProjection(ellipsoid, origin), theTranMerc_a(6378137.0), theTranMerc_f(1.0/298.257223563), theTranMerc_es(0.0066943799901413800), theTranMerc_ebs(0.0067394967565869), theTranMerc_Origin_Lat(0.0), theTranMerc_Origin_Long(0.0), theTranMerc_False_Northing(0.0), theTranMerc_False_Easting(500000.0), theTranMerc_Scale_Factor(0.9996), theTranMerc_ap(6367449.1458008), theTranMerc_bp(16038.508696861), theTranMerc_cp(16.832613334334), theTranMerc_dp(0.021984404273757), theTranMerc_Delta_Easting(40000000.0), theTranMerc_Delta_Northing(40000000.0), theZone(zone), theHemisphere(hemisphere) { setZone(zone); setHemisphere(hemisphere); update(); } ossimUtmProjection::ossimUtmProjection(ossim_int32 zone) : ossimMapProjection(), theTranMerc_a(6378137.0), theTranMerc_f(1.0/298.257223563), theTranMerc_es(0.0066943799901413800), theTranMerc_ebs(0.0067394967565869), theTranMerc_Origin_Lat(0.0), theTranMerc_Origin_Long(0.0), theTranMerc_False_Northing(0.0), theTranMerc_False_Easting(500000.0), theTranMerc_Scale_Factor(0.9996), theTranMerc_ap(6367449.1458008), theTranMerc_bp(16038.508696861), theTranMerc_cp(16.832613334334), theTranMerc_dp(0.021984404273757), theTranMerc_Delta_Easting(40000000.0), theTranMerc_Delta_Northing(40000000.0), theZone(zone), theHemisphere('N') { setZone(zone); update(); } ossimUtmProjection::ossimUtmProjection(const ossimUtmProjection& src) :ossimMapProjection(src), theTranMerc_a(src.theTranMerc_a), theTranMerc_f(src.theTranMerc_f), theTranMerc_es(src.theTranMerc_es), theTranMerc_ebs(src.theTranMerc_ebs), theTranMerc_Origin_Lat(src.theTranMerc_Origin_Lat), theTranMerc_Origin_Long(src.theTranMerc_Origin_Long), theTranMerc_False_Northing(src.theTranMerc_False_Northing), theTranMerc_False_Easting(src.theTranMerc_False_Easting), theTranMerc_Scale_Factor(src.theTranMerc_Scale_Factor), theTranMerc_ap(src.theTranMerc_ap), theTranMerc_bp(src.theTranMerc_bp), theTranMerc_cp(src.theTranMerc_cp), theTranMerc_dp(src.theTranMerc_dp), theTranMerc_Delta_Easting(src.theTranMerc_Delta_Easting), theTranMerc_Delta_Northing(src.theTranMerc_Delta_Northing), theZone(src.theZone), theHemisphere(src.theHemisphere) { setZone(theZone); setHemisphere(theHemisphere); update(); } void ossimUtmProjection::update() { ossimGpt origin = theOrigin; origin.lond(computeZoneMeridian(theZone)); origin.latd(0.0); double falseNorthing = 10000000.0; if (theHemisphere == 'N') { falseNorthing = 0.0; } Set_Transverse_Mercator_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), origin.latr(), origin.lonr(), theTranMerc_False_Easting, falseNorthing, theTranMerc_Scale_Factor); theFalseEastingNorthing.x = theTranMerc_False_Easting; theFalseEastingNorthing.y = theTranMerc_False_Northing; ossimMapProjection::update(); } ossimGpt ossimUtmProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Transverse_Mercator_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimUtmProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Transverse_Mercator(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } ossimObject* ossimUtmProjection::dup()const { ossimUtmProjection* proj = new ossimUtmProjection(*this); return proj; } ossim_int32 ossimUtmProjection::getZone() const { return theZone; } char ossimUtmProjection::getHemisphere() const { return theHemisphere; } void ossimUtmProjection::setOrigin(const ossimGpt& origin) { setZone(origin); // NOTE: We will not set the hemisphere if the origin latitude is 0.0. if (origin.latd() != 0.0) { setHemisphere(origin); } ossimMapProjection::setOrigin(origin); } void ossimUtmProjection::setZone(const ossimGpt& ground) { setZone(computeZone(ground)); } void ossimUtmProjection::setZone(ossim_int32 zone) { if( (zone < 1) || (zone > 60) ) { theZone = computeZone(theOrigin); } else { theZone = zone; } theOrigin.lond(computeZoneMeridian(theZone)); theOrigin.latd(0); theOrigin.datum(theDatum); theTranMerc_Origin_Long = theOrigin.lonr(); } void ossimUtmProjection::setHemisphere(const ossimGpt& ground) { char hemisphere = ground.latd()<0.0?'S':'N'; setHemisphere(hemisphere); } void ossimUtmProjection::setHemisphere(char hemisphere) { hemisphere = toupper(hemisphere); if((hemisphere != 'N') && (hemisphere != 'S')) { theHemisphere = theOrigin.latd() < 0?'S':'N'; } else { theHemisphere = hemisphere; } if (theHemisphere == 'N') { theTranMerc_False_Northing = 0.0; } else { theTranMerc_False_Northing = 10000000.0; } } ossim_int32 ossimUtmProjection::computeZone(const ossimGpt& ground) { ossim_int32 result = 0; double longitude = ground.lonr(); double lat_Degrees = (ossim_int32)( (ground.latd()) + 0.00000005); double long_Degrees = (ossim_int32)( (ground.lond()) + 0.00000005); if (longitude < M_PI) result = (ossim_int32)( (31 + ((180 * longitude) / (6 * M_PI)) ) + 0.00000005); else result = (ossim_int32)( (((180 * longitude) / (6 * M_PI)) - 29) + 0.00000005); if (result > 60) result = 1; /* UTM special cases */ if ((lat_Degrees > 55) && (lat_Degrees < 64) && (long_Degrees > -1) && (long_Degrees < 3)) result = 31; if ((lat_Degrees > 55) && (lat_Degrees < 64) && (long_Degrees > 2) && (long_Degrees < 12)) result = 32; if ((lat_Degrees > 71) && (long_Degrees > -1) && (long_Degrees < 9)) result = 31; if ((lat_Degrees > 71) && (long_Degrees > 8) && (long_Degrees < 21)) result = 33; if ((lat_Degrees > 71) && (long_Degrees > 20) && (long_Degrees < 33)) result = 35; if ((lat_Degrees > 71) && (long_Degrees > 32) && (long_Degrees < 42)) result = 37; return result; } double ossimUtmProjection::computeZoneMeridian(ossim_int32 zone) { return (6.0 * zone - 183.0);; } bool ossimUtmProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* zone = kwl.find(prefix, ossimKeywordNames::ZONE_KW); const char* hemisphere = kwl.find(prefix, ossimKeywordNames::HEMISPHERE_KW); ossimMapProjection::loadState(kwl, prefix); // initialize zone to a dummy value. // theZone = 0; // if(ossimString(type) == STATIC_TYPE_NAME(ossimUtmProjection)) { if(!zone) { theZone = computeZone(theOrigin); } else if (zone) { theZone = atoi(zone); if( (theZone < 1) || (theZone > 60) ) { theZone = computeZone(theOrigin); } else { // if(!kwl.find(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW)) // { theOrigin.lond(computeZoneMeridian(theZone)); // } // if(!kwl.find(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW)) // { theOrigin.latd(0); // } } } if (hemisphere) { ossimString s = hemisphere; s = s.trim(); s = s.upcase(); setHemisphere(*s.c_str()); } else { char hemisphere = theOrigin.latd()<0?'S':'N'; setHemisphere(hemisphere); } } update(); return true; } bool ossimUtmProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, ossimKeywordNames::ZONE_KW, theZone, true); kwl.add(prefix, ossimKeywordNames::HEMISPHERE_KW, theHemisphere, true); return ossimMapProjection::saveState(kwl, prefix); } ossim_int32 ossimUtmProjection::Set_Transverse_Mercator_Parameters(double a, double f, double Origin_Latitude, double Central_Meridian, double False_Easting, double False_Northing, double /* Scale_Factor */) { /* BEGIN Set_Tranverse_Mercator_Parameters */ /* * The function Set_Tranverse_Mercator_Parameters receives the ellipsoid * parameters and Tranverse Mercator projection parameters as inputs, and * sets the corresponding state variables. If any errors occur, the error * code(s) are returned by the function, otherwise UTM_NO_ERROR is * returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Origin_Latitude : Latitude in radians at the origin of the (input) * projection * Central_Meridian : Longitude in radians at the center of the (input) * projection * False_Easting : Easting/X at the center of the projection (input) * False_Northing : Northing/Y at the center of the projection (input) * Scale_Factor : Projection scale factor (input) */ double tn; /* True Meridianal distance constant */ double tn2; double tn3; double tn4; double tn5; double dummy_northing; double TranMerc_b; /* Semi-minor axis of ellipsoid, in meters */ // double inv_f = 1 / f; ossim_int32 Error_Code = UTM_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= UTM_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= UTM_INV_F_ERROR; // } // if ((Origin_Latitude < -MAX_LAT) || (Origin_Latitude > MAX_LAT)) // { /* origin latitude out of range */ // Error_Code |= UTM_ORIGIN_LAT_ERROR; // } // if ((Central_Meridian < -M_PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= UTM_CENT_MER_ERROR; // } // if ((Scale_Factor < MIN_SCALE_FACTOR) || (Scale_Factor > MAX_SCALE_FACTOR)) // { // Error_Code |= UTM_SCALE_FACTOR_ERROR; // } if (!Error_Code) { /* no errors */ theTranMerc_a = a; theTranMerc_f = f; theTranMerc_Origin_Lat = 0; theTranMerc_Origin_Long = 0; theTranMerc_False_Northing = 0; theTranMerc_False_Easting = 0; // theTranMerc_Scale_Factor = 1; /* Eccentricity Squared */ theTranMerc_es = 2 * theTranMerc_f - theTranMerc_f * theTranMerc_f; /* Second Eccentricity Squared */ theTranMerc_ebs = (1 / (1 - theTranMerc_es)) - 1; TranMerc_b = theTranMerc_a * (1 - theTranMerc_f); /*True meridianal constants */ tn = (theTranMerc_a - TranMerc_b) / (theTranMerc_a + TranMerc_b); tn2 = tn * tn; tn3 = tn2 * tn; tn4 = tn3 * tn; tn5 = tn4 * tn; theTranMerc_ap = theTranMerc_a * (1.e0 - tn + 5.e0 * (tn2 - tn3)/4.e0 + 81.e0 * (tn4 - tn5)/64.e0 ); theTranMerc_bp = 3.e0 * theTranMerc_a * (tn - tn2 + 7.e0 * (tn3 - tn4) /8.e0 + 55.e0 * tn5/64.e0 )/2.e0; theTranMerc_cp = 15.e0 * theTranMerc_a * (tn2 - tn3 + 3.e0 * (tn4 - tn5 )/4.e0) /16.0; theTranMerc_dp = 35.e0 * theTranMerc_a * (tn3 - tn4 + 11.e0 * tn5 / 16.e0) / 48.e0; theTranMerc_ep = 315.e0 * theTranMerc_a * (tn4 - tn5) / 512.e0; Convert_Geodetic_To_Transverse_Mercator(MAX_LAT, MAX_DELTA_LONG, &theTranMerc_Delta_Easting, &theTranMerc_Delta_Northing); Convert_Geodetic_To_Transverse_Mercator(0, MAX_DELTA_LONG, &theTranMerc_Delta_Easting, &dummy_northing); theTranMerc_Origin_Lat = Origin_Latitude; if (Central_Meridian > M_PI) Central_Meridian -= TWO_PI; theTranMerc_Origin_Long = Central_Meridian; theTranMerc_False_Northing = False_Northing; theTranMerc_False_Easting = False_Easting; // theTranMerc_Scale_Factor = Scale_Factor; } /* END OF if(!Error_Code) */ return (Error_Code); } /* END of Set_Transverse_Mercator_Parameters */ void ossimUtmProjection::Get_Transverse_Mercator_Parameters(double *a, double *f, double *Origin_Latitude, double *Central_Meridian, double *False_Easting, double *False_Northing, double *Scale_Factor)const { /* BEGIN Get_Tranverse_Mercator_Parameters */ /* * The function Get_Transverse_Mercator_Parameters returns the current * ellipsoid and Transverse Mercator projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Origin_Latitude : Latitude in radians at the origin of the (output) * projection * Central_Meridian : Longitude in radians at the center of the (output) * projection * False_Easting : Easting/X at the center of the projection (output) * False_Northing : Northing/Y at the center of the projection (output) * Scale_Factor : Projection scale factor (output) */ *a = theTranMerc_a; *f = theTranMerc_f; *Origin_Latitude = theTranMerc_Origin_Lat; *Central_Meridian = theTranMerc_Origin_Long; *False_Easting = theTranMerc_False_Easting; *False_Northing = theTranMerc_False_Northing; *Scale_Factor = theTranMerc_Scale_Factor; return; } /* END OF Get_Tranverse_Mercator_Parameters */ ossim_int32 ossimUtmProjection::Convert_Geodetic_To_Transverse_Mercator (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Transverse_Mercator */ /* * The function Convert_Geodetic_To_Transverse_Mercator converts geodetic * (latitude and longitude) coordinates to Transverse Mercator projection * (easting and northing) coordinates, according to the current ellipsoid * and Transverse Mercator projection coordinates. If any errors occur, the * error code(s) are returned by the function, otherwise UTM_NO_ERROR is * returned. * * Latitude : Latitude in radians (input) * Longitude : Longitude in radians (input) * Easting : Easting/X in meters (output) * Northing : Northing/Y in meters (output) */ double c; /* Cosine of latitude */ double c2; double c3; double c5; double c7; double dlam; /* Delta longitude - Difference in Longitude */ double eta; /* constant - theTranMerc_ebs *c *c */ double eta2; double eta3; double eta4; double s; /* Sine of latitude */ double sn; /* Radius of curvature in the prime vertical */ double t; /* Tangent of latitude */ double tan2; double tan3; double tan4; double tan5; double tan6; double t1; /* Term in coordinate conversion formula - GP to Y */ double t2; /* Term in coordinate conversion formula - GP to Y */ double t3; /* Term in coordinate conversion formula - GP to Y */ double t4; /* Term in coordinate conversion formula - GP to Y */ double t5; /* Term in coordinate conversion formula - GP to Y */ double t6; /* Term in coordinate conversion formula - GP to Y */ double t7; /* Term in coordinate conversion formula - GP to Y */ double t8; /* Term in coordinate conversion formula - GP to Y */ double t9; /* Term in coordinate conversion formula - GP to Y */ double tmd; /* True Meridional distance */ double tmdo; /* True Meridional distance for latitude of origin */ ossim_int32 Error_Code = UTM_NO_ERROR; // double temp_Origin; // double temp_Long; // if ((Latitude < -MAX_LAT) || (Latitude > MAX_LAT)) // { /* Latitude out of range */ // Error_Code|= UTM_LAT_ERROR; // } if (Longitude > M_PI) Longitude -= TWO_PI; // if ((Longitude < (theTranMerc_Origin_Long - MAX_DELTA_LONG)) // || (Longitude > (theTranMerc_Origin_Long + MAX_DELTA_LONG))) // { // if (Longitude < 0) // temp_Long = Longitude + TWO_PI; // else // temp_Long = Longitude; // if (theTranMerc_Origin_Long < 0) // temp_Origin = theTranMerc_Origin_Long + TWO_PI; // else // temp_Origin = theTranMerc_Origin_Long; // if ((temp_Long < (temp_Origin - MAX_DELTA_LONG)) // || (temp_Long > (temp_Origin + MAX_DELTA_LONG))) // Error_Code|= UTM_LON_ERROR; // } if (!Error_Code) { /* no errors */ /* * Delta Longitude */ dlam = Longitude - theTranMerc_Origin_Long; // if (fabs(dlam) > (9.0 * M_PI / 180)) // { /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian */ // Error_Code |= UTM_LON_WARNING; // } if (dlam > M_PI) dlam -= TWO_PI; if (dlam < -M_PI) dlam += TWO_PI; if (fabs(dlam) < 2.e-10) dlam = 0.0; s = sin(Latitude); c = cos(Latitude); c2 = c * c; c3 = c2 * c; c5 = c3 * c2; c7 = c5 * c2; t = tan (Latitude); tan2 = t * t; tan3 = tan2 * t; tan4 = tan3 * t; tan5 = tan4 * t; tan6 = tan5 * t; eta = theTranMerc_ebs * c2; eta2 = eta * eta; eta3 = eta2 * eta; eta4 = eta3 * eta; /* radius of curvature in prime vertical */ sn = SPHSN(Latitude); /* True Meridianal Distances */ tmd = SPHTMD(Latitude); /* Origin */ tmdo = SPHTMD (theTranMerc_Origin_Lat); /* northing */ t1 = (tmd - tmdo) * theTranMerc_Scale_Factor; t2 = sn * s * c * theTranMerc_Scale_Factor/ 2.e0; t3 = sn * s * c3 * theTranMerc_Scale_Factor * (5.e0 - tan2 + 9.e0 * eta + 4.e0 * eta2) /24.e0; t4 = sn * s * c5 * theTranMerc_Scale_Factor * (61.e0 - 58.e0 * tan2 + tan4 + 270.e0 * eta - 330.e0 * tan2 * eta + 445.e0 * eta2 + 324.e0 * eta3 -680.e0 * tan2 * eta2 + 88.e0 * eta4 -600.e0 * tan2 * eta3 - 192.e0 * tan2 * eta4) / 720.e0; t5 = sn * s * c7 * theTranMerc_Scale_Factor * (1385.e0 - 3111.e0 * tan2 + 543.e0 * tan4 - tan6) / 40320.e0; *Northing = theTranMerc_False_Northing + t1 + pow(dlam,2.e0) * t2 + pow(dlam,4.e0) * t3 + pow(dlam,6.e0) * t4 + pow(dlam,8.e0) * t5; /* Easting */ t6 = sn * c * theTranMerc_Scale_Factor; t7 = sn * c3 * theTranMerc_Scale_Factor * (1.e0 - tan2 + eta ) /6.e0; t8 = sn * c5 * theTranMerc_Scale_Factor * (5.e0 - 18.e0 * tan2 + tan4 + 14.e0 * eta - 58.e0 * tan2 * eta + 13.e0 * eta2 + 4.e0 * eta3 - 64.e0 * tan2 * eta2 - 24.e0 * tan2 * eta3 )/ 120.e0; t9 = sn * c7 * theTranMerc_Scale_Factor * ( 61.e0 - 479.e0 * tan2 + 179.e0 * tan4 - tan6 ) /5040.e0; *Easting = theTranMerc_False_Easting + dlam * t6 + pow(dlam,3.e0) * t7 + pow(dlam,5.e0) * t8 + pow(dlam,7.e0) * t9; } return (Error_Code); } /* END OF Convert_Geodetic_To_Transverse_Mercator */ ossim_int32 ossimUtmProjection::Convert_Transverse_Mercator_To_Geodetic (double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Transverse_Mercator_To_Geodetic */ /* * The function Convert_Transverse_Mercator_To_Geodetic converts Transverse * Mercator projection (easting and northing) coordinates to geodetic * (latitude and longitude) coordinates, according to the current ellipsoid * and Transverse Mercator projection parameters. If any errors occur, the * error code(s) are returned by the function, otherwise UTM_NO_ERROR is * returned. * * Easting : Easting/X in meters (input) * Northing : Northing/Y in meters (input) * Latitude : Latitude in radians (output) * Longitude : Longitude in radians (output) */ double c; /* Cosine of latitude */ double de; /* Delta easting - Difference in Easting (Easting-Fe) */ double dlam; /* Delta longitude - Difference in Longitude */ double eta; /* constant - theTranMerc_ebs *c *c */ double eta2; double eta3; double eta4; double ftphi; /* Footpoint latitude */ int i; /* Loop iterator */ /*double s; Sine of latitude */ double sn; /* Radius of curvature in the prime vertical */ double sr; /* Radius of curvature in the meridian */ double t; /* Tangent of latitude */ double tan2; double tan4; double t10; /* Term in coordinate conversion formula - GP to Y */ double t11; /* Term in coordinate conversion formula - GP to Y */ double t12; /* Term in coordinate conversion formula - GP to Y */ double t13; /* Term in coordinate conversion formula - GP to Y */ double t14; /* Term in coordinate conversion formula - GP to Y */ double t15; /* Term in coordinate conversion formula - GP to Y */ double t16; /* Term in coordinate conversion formula - GP to Y */ double t17; /* Term in coordinate conversion formula - GP to Y */ double tmd; /* True Meridional distance */ double tmdo; /* True Meridional distance for latitude of origin */ ossim_int32 Error_Code = UTM_NO_ERROR; // if ((Easting < (theTranMerc_False_Easting - theTranMerc_Delta_Easting)) // ||(Easting > (theTranMerc_False_Easting + theTranMerc_Delta_Easting))) // { /* Easting out of range */ // Error_Code |= UTM_EASTING_ERROR; // } // if ((Northing < (theTranMerc_False_Northing - theTranMerc_Delta_Northing)) // || (Northing > (theTranMerc_False_Northing + theTranMerc_Delta_Northing))) // { /* Northing out of range */ // Error_Code |= UTM_NORTHING_ERROR; // } if (!Error_Code) { /* True Meridional Distances for latitude of origin */ tmdo = SPHTMD(theTranMerc_Origin_Lat); /* Origin */ tmd = tmdo + (Northing - theTranMerc_False_Northing) / theTranMerc_Scale_Factor; /* First Estimate */ sr = SPHSR(0.e0); ftphi = tmd/sr; for (i = 0; i < 5 ; i++) { t10 = SPHTMD (ftphi); sr = SPHSR(ftphi); ftphi = ftphi + (tmd - t10) / sr; } /* Radius of Curvature in the meridian */ sr = SPHSR(ftphi); /* Radius of Curvature in the meridian */ sn = SPHSN(ftphi); /* Sine Cosine terms */ // s = sin(ftphi); c = cos(ftphi); /* Tangent Value */ t = tan(ftphi); tan2 = t * t; tan4 = tan2 * tan2; eta = theTranMerc_ebs * pow(c,2); eta2 = eta * eta; eta3 = eta2 * eta; eta4 = eta3 * eta; de = Easting - theTranMerc_False_Easting; if (fabs(de) < 0.0001) de = 0.0; /* Latitude */ t10 = t / (2.e0 * sr * sn * pow(theTranMerc_Scale_Factor, 2)); t11 = t * (5.e0 + 3.e0 * tan2 + eta - 4.e0 * pow(eta,2) - 9.e0 * tan2 * eta) / (24.e0 * sr * pow(sn,3) * pow(theTranMerc_Scale_Factor,4)); t12 = t * (61.e0 + 90.e0 * tan2 + 46.e0 * eta + 45.E0 * tan4 - 252.e0 * tan2 * eta - 3.e0 * eta2 + 100.e0 * eta3 - 66.e0 * tan2 * eta2 - 90.e0 * tan4 * eta + 88.e0 * eta4 + 225.e0 * tan4 * eta2 + 84.e0 * tan2* eta3 - 192.e0 * tan2 * eta4) / ( 720.e0 * sr * pow(sn,5) * pow(theTranMerc_Scale_Factor, 6) ); t13 = t * ( 1385.e0 + 3633.e0 * tan2 + 4095.e0 * tan4 + 1575.e0 * pow(t,6))/ (40320.e0 * sr * pow(sn,7) * pow(theTranMerc_Scale_Factor,8)); *Latitude = ftphi - pow(de,2) * t10 + pow(de,4) * t11 - pow(de,6) * t12 + pow(de,8) * t13; t14 = 1.e0 / (sn * c * theTranMerc_Scale_Factor); t15 = (1.e0 + 2.e0 * tan2 + eta) / (6.e0 * pow(sn,3) * c * pow(theTranMerc_Scale_Factor,3)); t16 = (5.e0 + 6.e0 * eta + 28.e0 * tan2 - 3.e0 * eta2 + 8.e0 * tan2 * eta + 24.e0 * tan4 - 4.e0 * eta3 + 4.e0 * tan2 * eta2 + 24.e0 * tan2 * eta3) / (120.e0 * pow(sn,5) * c * pow(theTranMerc_Scale_Factor,5)); t17 = (61.e0 + 662.e0 * tan2 + 1320.e0 * tan4 + 720.e0 * pow(t,6)) / (5040.e0 * pow(sn,7) * c * pow(theTranMerc_Scale_Factor,7)); /* Difference in Longitude */ dlam = de * t14 - pow(de,3) * t15 + pow(de,5) * t16 - pow(de,7) * t17; /* Longitude */ (*Longitude) = theTranMerc_Origin_Long + dlam; while (*Latitude > (90.0 * RAD_PER_DEG)) { *Latitude = M_PI - *Latitude; *Longitude += M_PI; if (*Longitude > M_PI) *Longitude -= TWO_PI; } while (*Latitude < (-90.0 * RAD_PER_DEG)) { *Latitude = - (*Latitude + M_PI); *Longitude += M_PI; if (*Longitude > M_PI) *Longitude -= TWO_PI; } if (*Longitude > TWO_PI) *Longitude -= TWO_PI; if (*Longitude < -M_PI) *Longitude += TWO_PI; // if (fabs(dlam) > (9.0 * M_PI / 180)) // { /* Distortion will result if Longitude is more than 9 degrees from the Central Meridian */ // Error_Code |= UTM_LON_WARNING; // } } return (Error_Code); } /* END OF Convert_Transverse_Mercator_To_Geodetic */ std::ostream& ossimUtmProjection::print(std::ostream& out) const { out << setiosflags(ios::fixed) << setprecision(15) << "// ossimUtmProjection::print" << "\ntheZone: " << theZone << "\ntheHemisphere: " << theHemisphere << endl; return ossimMapProjection::print(out); } double ossimUtmProjection::getFalseEasting() const { return theTranMerc_False_Easting; } double ossimUtmProjection::getFalseNorthing() const { return theTranMerc_False_Northing; } double ossimUtmProjection::getScaleFactor() const { return theTranMerc_Scale_Factor; } //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimUtmProjection::operator==(const ossimProjection& proj) const { bool result = false; if ( this == &proj ) { result = true; // Pointer addresses the same. } else { //--- // Check our stuff first. No sense going onto ossimMapProjection::operator== // if we are not a utm projection. //--- const ossimUtmProjection* p = dynamic_cast(&proj); if ( p ) { if ( theZone == p->theZone ) { if ( theHemisphere == p->theHemisphere ) { result = ossimMapProjection::operator==(proj); } } } } return result; } ossim_uint32 ossimUtmProjection::getPcsCode() const { // Always recompute in case origin, zone, or hemisphere were changed. return ossimEpsgProjectionDatabase::instance()->getCodeFromUtmProj( this ); } ossim-Miami-2.9.1/src/projection/ossimUtmpt.cpp000066400000000000000000000046131352751253100215520ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: // // This is the Universal Transverse Mercator (UTM) point. Allows // easy onversion between different coordinates. //******************************************************************* // $Id: ossimUtmpt.cpp 10058 2006-12-08 20:04:23Z mlucas $ #include #include #include #include #include #include ossimUtmpt::ossimUtmpt(const ossimGpt &aPt) { convertFromGround(aPt); } ossimUtmpt::ossimUtmpt(const ossimEcefPoint &aPt) { convertFromGround(ossimGpt(aPt)); } ossimUtmpt::ossimUtmpt(long zone, char hemisphere, // N or S double easting, double northing, const ossimDatum* datum) : theZone (zone), theHemisphere (hemisphere), theEasting (easting), theNorthing (northing), theDatum (datum) {} void ossimUtmpt::convertFromGround(const ossimGpt &aPt) { const ossimDatum *aDatum = aPt.datum(); if(aDatum) { //call Geotrans init code Set_UTM_Parameters(aDatum->ellipsoid()->a(), aDatum->ellipsoid()->flattening(), 0); Convert_Geodetic_To_UTM(aPt.latr(), aPt.lonr(), &theZone, &theHemisphere, &theEasting, &theNorthing); theDatum = aDatum; } else { //ERROR: Should never happen } } void ossimUtmpt::convertToGround(ossimGpt &aPt) { Set_UTM_Parameters( theDatum->ellipsoid()->a(), theDatum->ellipsoid()->flattening(), 0 ); double latitude = 0.0; double longitude = 0.0; Convert_UTM_To_Geodetic( zone(), hemisphere(), easting(), northing(), &latitude, &longitude ); aPt.latr(latitude); aPt.lonr(longitude); aPt.datum(theDatum); } ossim-Miami-2.9.1/src/projection/ossimVanDerGrintenProjection.cpp000066400000000000000000000421101352751253100251760ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Calls Grinten projection code. //******************************************************************* // $Id: ossimVanDerGrintenProjection.cpp 17815 2010-08-03 13:23:14Z dburken $ #include #include RTTI_DEF1(ossimVanDerGrintenProjection, "ossimVanDerGrintenProjection", ossimMapProjection) /***************************************************************************/ /* * DEFINES */ #ifndef PI_OVER_2 # define PI_OVER_2 ( M_PI / 2.0) #endif #ifndef TWO_PI # define TWO_PI (2.0 * M_PI) #endif #define MAX_LAT ( 90.0 * (M_PI / 180.0) ) /* 90 degrees in radians */ #define FLOAT_EQ(x,v,epsilon) (((v - epsilon) < x) && (x < (v + epsilon))) #define GRIN_NO_ERROR 0x0000 #define GRIN_LAT_ERROR 0x0001 #define GRIN_LON_ERROR 0x0002 #define GRIN_EASTING_ERROR 0x0004 #define GRIN_NORTHING_ERROR 0x0008 #define GRIN_CENT_MER_ERROR 0x0020 #define GRIN_A_ERROR 0x0040 #define GRIN_B_ERROR 0x0080 #define GRIN_A_LESS_B_ERROR 0x0100 #define GRIN_RADIUS_ERROR 0x0200 /***************************************************************************/ /* * GLOBALS */ const double TWO_OVER_PI = (2.0 / M_PI); const double PI_OVER_3 = (M_PI / 3.0); const double ONE_THIRD = (1.0 / 3.0); ossimVanDerGrintenProjection::ossimVanDerGrintenProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin) :ossimMapProjection(ellipsoid, origin) { setDefaults(); update(); } ossimVanDerGrintenProjection::ossimVanDerGrintenProjection(const ossimEllipsoid& ellipsoid, const ossimGpt& origin, double falseEasting, double falseNorthing) :ossimMapProjection(ellipsoid, origin) { Grin_False_Easting = falseEasting; Grin_False_Northing = falseNorthing; update(); } void ossimVanDerGrintenProjection::update() { Set_Van_der_Grinten_Parameters(theEllipsoid.getA(), theEllipsoid.getFlattening(), theOrigin.lonr(), Grin_False_Easting, Grin_False_Northing); theFalseEastingNorthing.x = Grin_False_Easting; theFalseEastingNorthing.y = Grin_False_Northing; ossimMapProjection::update(); } void ossimVanDerGrintenProjection::setFalseEasting(double falseEasting) { Grin_False_Easting = falseEasting; update(); } void ossimVanDerGrintenProjection::setFalseNorthing(double falseNorthing) { Grin_False_Northing = falseNorthing; update(); } void ossimVanDerGrintenProjection::setDefaults() { Grin_False_Easting = 0.0; Grin_False_Northing = 0.0; } void ossimVanDerGrintenProjection::setCentralMeridian(double centralMeridian) { Grin_Origin_Long = centralMeridian; update(); } void ossimVanDerGrintenProjection::setFalseEastingNorthing(double falseEasting, double falseNorthing) { Grin_False_Easting = falseEasting; Grin_False_Northing = falseNorthing; update(); } ossimGpt ossimVanDerGrintenProjection::inverse(const ossimDpt &eastingNorthing)const { double lat = 0.0; double lon = 0.0; Convert_Van_der_Grinten_To_Geodetic(eastingNorthing.x, eastingNorthing.y, &lat, &lon); return ossimGpt(lat*DEG_PER_RAD, lon*DEG_PER_RAD, 0.0, theDatum); } ossimDpt ossimVanDerGrintenProjection::forward(const ossimGpt &latLon)const { double easting = 0.0; double northing = 0.0; ossimGpt gpt = latLon; if (theDatum) { if (theDatum->code() != latLon.datum()->code()) { gpt.changeDatum(theDatum); // Shift to our datum. } } Convert_Geodetic_To_Van_der_Grinten(gpt.latr(), gpt.lonr(), &easting, &northing); return ossimDpt(easting, northing); } bool ossimVanDerGrintenProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { return ossimMapProjection::saveState(kwl, prefix); } bool ossimVanDerGrintenProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool flag = ossimMapProjection::loadState(kwl, prefix); const char* type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); setDefaults(); if(ossimString(type) == STATIC_TYPE_NAME(ossimVanDerGrintenProjection)) { Grin_False_Easting = theFalseEastingNorthing.x; Grin_False_Northing = theFalseEastingNorthing.y; } update(); return flag; } /***************************************************************************/ /* * FUNCTIONS */ long ossimVanDerGrintenProjection::Set_Van_der_Grinten_Parameters(double a, double f, double Central_Meridian, double False_Easting, double False_Northing) { /* BEGIN Set_Van_der_Grinten_Parameters */ /* * The function Set_Van_der_Grinten_Parameters receives the ellipsoid parameters and * projection parameters as inputs, and sets the corresponding state * variables. If any errors occur, the error code(s) are returned by the function, * otherwise Grin_NO_ERROR is returned. * * a : Semi-major axis of ellipsoid, in meters (input) * f : Flattening of ellipsoid (input) * Central_Meridian : Longitude in radians at the center of (input) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (input) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (input) */ // double inv_f = 1 / f; long Error_Code = GRIN_NO_ERROR; // if (a <= 0.0) // { /* Semi-major axis must be greater than zero */ // Error_Code |= GRIN_A_ERROR; // } // if ((inv_f < 250) || (inv_f > 350)) // { /* Inverse flattening must be between 250 and 350 */ // Error_Code |= GRIN_INV_F_ERROR; // } // if ((Central_Meridian < -M_PI) || (Central_Meridian > TWO_PI)) // { /* origin longitude out of range */ // Error_Code |= GRIN_CENT_MER_ERROR; // } if (!Error_Code) { /* no errors */ Grin_a = a; Grin_f = f; es2 = 2 * Grin_f - Grin_f * Grin_f; es4 = es2 * es2; es6 = es4 * es2; /* spherical radius */ Ra = Grin_a * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 /3024.0); PI_Ra = M_PI * Ra; // if (Central_Meridian > M_PI) // Central_Meridian -= TWO_PI; Grin_Origin_Long = Central_Meridian; Grin_False_Easting = False_Easting; Grin_False_Northing = False_Northing; } /* END OF if(!Error_Code) */ return (Error_Code); } /* END OF Set_Van_der_Grinten_Parameters */ void ossimVanDerGrintenProjection::Get_Van_der_Grinten_Parameters(double *a, double *f, double *Central_Meridian, double *False_Easting, double *False_Northing)const { /* BEGIN Get_Van_der_Grinten_Parameters */ /* * The function Get_Van_der_Grinten_Parameters returns the current ellipsoid * parameters, and Van Der Grinten projection parameters. * * a : Semi-major axis of ellipsoid, in meters (output) * f : Flattening of ellipsoid (output) * Central_Meridian : Longitude in radians at the center of (output) * the projection * False_Easting : A coordinate value in meters assigned to the * central meridian of the projection. (output) * False_Northing : A coordinate value in meters assigned to the * origin latitude of the projection (output) */ *a = Grin_a; *f = Grin_f; *Central_Meridian = Grin_Origin_Long; *False_Easting = Grin_False_Easting; *False_Northing = Grin_False_Northing; return; } /* END OF Get_Van_der_Grinten_Parameters */ long ossimVanDerGrintenProjection::Convert_Geodetic_To_Van_der_Grinten (double Latitude, double Longitude, double *Easting, double *Northing)const { /* BEGIN Convert_Geodetic_To_Van_der_Grinten */ /* * The function Convert_Geodetic_To_Van_der_Grinten converts geodetic (latitude and * longitude) coordinates to Van Der Grinten projection (easting and northing) * coordinates, according to the current ellipsoid and Van Der Grinten projection * parameters. If any errors occur, the error code(s) are returned by the * function, otherwise GRIN_NO_ERROR is returned. * * Latitude : Latitude (phi) in radians (input) * Longitude : Longitude (lambda) in radians (input) * Easting : Easting (X) in meters (output) * Northing : Northing (Y) in meters (output) */ double dlam; /* Longitude - Central Meridan */ double aa, aasqr; double gg; double pp, ppsqr; double gg_MINUS_ppsqr, ppsqr_PLUS_aasqr; double in_theta; double theta; double sin_theta, cos_theta; double qq; long Error_Code = GRIN_NO_ERROR; // if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2)) // { /* Latitude out of range */ // Error_Code |= GRIN_LAT_ERROR; // } // if ((Longitude < -M_PI) || (Longitude > TWO_PI)) // { /* Longitude out of range */ // Error_Code|= GRIN_LON_ERROR; // } if (!Error_Code) { /* no errors */ dlam = Longitude - Grin_Origin_Long; // if (dlam > M_PI) // { // dlam -= TWO_PI; // } // if (dlam < -M_PI) // { // dlam += TWO_PI; // } if (Latitude == 0.0) { *Easting = Ra * dlam + Grin_False_Easting; *Northing = 0.0; } else if (dlam == 0.0 || FLOAT_EQ(Latitude,MAX_LAT,.00001) || FLOAT_EQ(Latitude,-MAX_LAT,.00001)) { in_theta = fabs(TWO_OVER_PI * Latitude); if (in_theta > 1.0) in_theta = 1.0; else if (in_theta < -1.0) in_theta = -1.0; theta = asin(in_theta); *Easting = 0.0; *Northing = PI_Ra * tan(theta / 2) + Grin_False_Northing; if (Latitude < 0.0) *Northing *= -1.0; } else { aa = 0.5 * fabs(M_PI / dlam - dlam / M_PI); in_theta = fabs(TWO_OVER_PI * Latitude); if (in_theta > 1.0) in_theta = 1.0; else if (in_theta < -1.0) in_theta = -1.0; theta = asin(in_theta); sin_theta = sin(theta); cos_theta = cos(theta); gg = cos_theta / (sin_theta + cos_theta - 1); pp = gg * (2 / sin_theta - 1); aasqr = aa * aa; ppsqr = pp * pp; gg_MINUS_ppsqr = gg - ppsqr; ppsqr_PLUS_aasqr = ppsqr + aasqr; qq = aasqr + gg; *Easting = PI_Ra * (aa * (gg_MINUS_ppsqr) + sqrt(aasqr * (gg_MINUS_ppsqr) * (gg_MINUS_ppsqr) - (ppsqr_PLUS_aasqr) * (gg * gg - ppsqr))) / (ppsqr_PLUS_aasqr) + Grin_False_Easting; if (dlam < 0.0) *Easting *= -1.0; *Northing = PI_Ra * (pp * qq - aa * sqrt ((aasqr + 1) * (ppsqr_PLUS_aasqr) - qq * qq)) / (ppsqr_PLUS_aasqr) + Grin_False_Northing; if (Latitude < 0.0) *Northing *= -1.0; } } return (Error_Code); } /* END OF Convert_Geodetic_To_Van_der_Grinten */ long ossimVanDerGrintenProjection::Convert_Van_der_Grinten_To_Geodetic(double Easting, double Northing, double *Latitude, double *Longitude)const { /* BEGIN Convert_Van_der_Grinten_To_Geodetic */ /* * The function Convert_Van_der_Grinten_To_Geodetic converts Grinten projection * (easting and northing) coordinates to geodetic (latitude and longitude) * coordinates, according to the current ellipsoid and Grinten projection * coordinates. If any errors occur, the error code(s) are returned by the * function, otherwise GRIN_NO_ERROR is returned. * * Easting : Easting (X) in meters (input) * Northing : Northing (Y) in meters (input) * Latitude : Latitude (phi) in radians (output) * Longitude : Longitude (lambda) in radians (output) */ double dx, dy; double xx, xxsqr; double yy, yysqr, two_yysqr; double xxsqr_PLUS_yysqr; double c1; double c2; double c3, c3sqr; double c2_OVER_3c3; double dd; double a1; double m1; double i; double theta1; // double temp; // const double epsilon = 1.0e-2; long Error_Code = GRIN_NO_ERROR; // if ((Easting > (Grin_False_Easting + PI_Ra + epsilon)) || // (Easting < (Grin_False_Easting - PI_Ra - epsilon))) // { /* Easting out of range */ // Error_Code |= GRIN_EASTING_ERROR; // } // if ((Northing > (Grin_False_Northing + PI_Ra + epsilon)) || // (Northing < (Grin_False_Northing - PI_Ra - epsilon))) // { /* Northing out of range */ // Error_Code |= GRIN_NORTHING_ERROR; // } // if (!Error_Code) // { // temp = sqrt(Easting * Easting + Northing * Northing); // if ((temp > (Grin_False_Easting + PI_Ra + epsilon)) || // (temp > (Grin_False_Northing + PI_Ra + epsilon)) || // (temp < (Grin_False_Easting - PI_Ra - epsilon)) || // (temp < (Grin_False_Northing - PI_Ra - epsilon))) // { /* Point is outside of projection area */ // Error_Code |= GRIN_RADIUS_ERROR; // } // } if (!Error_Code) { dy = Northing - Grin_False_Northing; dx = Easting - Grin_False_Easting; xx = dx / PI_Ra; yy = dy / PI_Ra; xxsqr = xx * xx; yysqr = yy * yy; xxsqr_PLUS_yysqr = xxsqr + yysqr; two_yysqr = 2 * yysqr; if (Northing == 0.0) *Latitude = 0.0; else { c1 = - fabs(yy) * (1 + xxsqr_PLUS_yysqr); c2 = c1 - two_yysqr + xxsqr; c3 = - 2 * c1 + 1 + two_yysqr + (xxsqr_PLUS_yysqr) * (xxsqr_PLUS_yysqr); c2_OVER_3c3 = c2 / (3.0 * c3); c3sqr = c3 * c3; dd = yysqr / c3 + ((2 * c2 * c2 * c2) / (c3sqr * c3) - (9 * c1 * c2) / (c3sqr)) / 27; a1 = (c1 - c2 * c2_OVER_3c3) /c3; m1 = 2 * sqrt(-ONE_THIRD * a1); i = 3 * dd/ (a1 * m1); if ((i > 1.0)||(i < -1.0)) *Latitude = MAX_LAT; else { theta1 = ONE_THIRD * acos(3 * dd / (a1 * m1)); *Latitude = M_PI * (-m1 * cos(theta1 + PI_OVER_3) - c2_OVER_3c3); } } if (Northing < 0.0) *Latitude *= -1.0; if (xx == 0.0) *Longitude = Grin_Origin_Long; else { *Longitude = M_PI * (xxsqr_PLUS_yysqr - 1 + sqrt(1 + (2 * xxsqr - two_yysqr) + (xxsqr_PLUS_yysqr) * (xxsqr_PLUS_yysqr))) / (2 * xx) + Grin_Origin_Long; } // if (*Latitude > PI_OVER_2) /* force distorted values to 90, -90 degrees */ // *Latitude = PI_OVER_2; // else if (*Latitude < -PI_OVER_2) // *Latitude = -PI_OVER_2; // if (*Longitude > M_PI) // *Longitude -= TWO_PI; // if (*Longitude < -M_PI) // *Longitude += TWO_PI; // if (*Longitude > M_PI) /* force distorted values to 180, -180 degrees */ // *Longitude = M_PI; // else if (*Longitude < -M_PI) // *Longitude = -M_PI; } return (Error_Code); } /* END OF Convert_Van_der_Grinten_To_Geodetic */ //************************************************************************************************* //! Returns TRUE if principal parameters are within epsilon tolerance. //************************************************************************************************* bool ossimVanDerGrintenProjection::operator==(const ossimProjection& proj) const { if (!ossimMapProjection::operator==(proj)) return false; const ossimVanDerGrintenProjection* p = dynamic_cast(&proj); if (!p) return false; if (!ossim::almostEqual(Grin_Origin_Long,p->Grin_Origin_Long)) return false; return true; } ossim-Miami-2.9.1/src/projection/ossimWarpProjection.cpp000066400000000000000000000261241352751253100234100ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer // // DESCRIPTION: // Contains implementation of class ossimWarpModel. This is an // implementation of a warping interpolation model. // //***************************************************************************** // $Id: ossimWarpProjection.cpp 21214 2012-07-03 16:20:11Z dburken $ #include RTTI_DEF1(ossimWarpProjection, "ossimWarpProjection", ossimProjection); #include #include #include #include static const char* AFFINE_PREFIX = "affine."; static const char* QUADWARP_PREFIX = "quadwarp."; static const char* PROJECTION_PREFIX = "projection."; //*** // Define Trace flags for use within this file: //*** #include static ossimTrace traceExec ("ossimWarpProjection:exec"); static ossimTrace traceDebug ("ossimWarpProjection:debug"); //***************************************************************************** // CONSTRUCTOR: Default // //***************************************************************************** ossimWarpProjection::ossimWarpProjection() : ossimProjection(), theClientProjection (0), theWarpTransform (0), theAffineTransform (0) { theWarpTransform = new ossimQuadTreeWarp; theAffineTransform = new ossimAffineTransform; } //***************************************************************************** // CONSTRUCTOR: Primary constructor accepting pointer to the underlying // client projection // //***************************************************************************** ossimWarpProjection::ossimWarpProjection(ossimProjection* client) : ossimProjection(), theClientProjection (client), theWarpTransform (0), theAffineTransform (0) { theWarpTransform = new ossimQuadTreeWarp; theAffineTransform = new ossimAffineTransform; } //***************************************************************************** // CONSTRUCTOR: Accepts geom keywordlist //***************************************************************************** ossimWarpProjection::ossimWarpProjection(const ossimKeywordlist& geom_kwl, const char* prefix) : ossimProjection(), theClientProjection (0), theWarpTransform (0), theAffineTransform (0) { theClientProjection = ossimProjectionFactoryRegistry::instance()-> createProjection(geom_kwl, prefix); theWarpTransform = new ossimQuadTreeWarp(); bool rtn_stat = theWarpTransform->loadState(geom_kwl, prefix); theAffineTransform = new ossimAffineTransform(); rtn_stat &= theAffineTransform->loadState(geom_kwl, prefix); if ((!theClientProjection) || (theClientProjection->getErrorStatus()) || (!rtn_stat)) setErrorStatus(ossimErrorCodes::OSSIM_ERROR); } //***************************************************************************** // DESTRUCTOR //***************************************************************************** ossimWarpProjection::~ossimWarpProjection() { theClientProjection = 0; theWarpTransform = 0; theAffineTransform = 0; } //***************************************************************************** // METHOD: ossimWarpProjection::worldToLineSample() //***************************************************************************** void ossimWarpProjection::worldToLineSample (const ossimGpt& worldPoint, ossimDpt& lineSampPt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimWarpProjection::worldToLineSample: Entering..." << std::endl; if (theClientProjection.valid() && theWarpTransform.valid() && theAffineTransform.valid()) { theClientProjection->worldToLineSample(worldPoint, lineSampPt); theAffineTransform->inverse(lineSampPt); theWarpTransform->inverse(lineSampPt); } else { lineSampPt.makeNan(); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimWarpProjection::worldToLineSample: Returning..." << std::endl; } //***************************************************************************** // METHOD: ossimWarpProjection::lineSampleToWorld() //***************************************************************************** void ossimWarpProjection::lineSampleToWorld(const ossimDpt& lineSampPt, ossimGpt& worldPt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimWarpProjection::lineSampleToWorld: Entering..." << std::endl; if (theClientProjection.valid() && theWarpTransform.valid() && theAffineTransform.valid()) { ossimDpt adjustedPt; theWarpTransform->forward(adjustedPt); theAffineTransform->forward(lineSampPt, adjustedPt); theClientProjection->lineSampleToWorld(adjustedPt, worldPt); } else { worldPt.makeNan(); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimWarpProjection::lineSampleToWorld: Returning..." << std::endl; } //***************************************************************************** // METHOD: ossimWarpProjection::lineSampleToWorld() //***************************************************************************** void ossimWarpProjection::lineSampleHeightToWorld(const ossimDpt& lineSampPt, const double& hgt, ossimGpt& worldPt) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimWarpProjection::lineSampleHeightToWorld: Entering..." << std::endl; if (theClientProjection.valid() && theWarpTransform.valid() && theAffineTransform.valid()) { ossimDpt adjustedPt; theAffineTransform->forward(lineSampPt, adjustedPt); theWarpTransform->forward(adjustedPt); theClientProjection->lineSampleHeightToWorld(adjustedPt, hgt, worldPt); } else { worldPt.makeNan(); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimWarpProjection::lineSampleHeightToWorld: Returning..." << std::endl; } //***************************************************************************** // METHOD: ossimWarpProjection::print() //***************************************************************************** std::ostream& ossimWarpProjection::print(std::ostream& out) const { if (theClientProjection.valid() && theWarpTransform.valid() && theAffineTransform.valid()) { out << "ossimWarpProjection:\n" << " Member theClientProjection: "; theClientProjection->print(out); out << " Member theAffineTransform: " << *theAffineTransform << "\n" << " Member theWarpTransform: " << *theWarpTransform << std::endl; } else { out << "ossimWarpProjection -- Not inititialized." << std::endl; } return out; } std::ostream& operator<<(std::ostream& os, const ossimWarpProjection& m) { return m.print(os); } //***************************************************************************** // METHOD: ossimWarpProjection::saveState() //***************************************************************************** bool ossimWarpProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimWarpProjection::saveState: entering..." << std::endl; ossimString projPrefix = ossimString(prefix) + PROJECTION_PREFIX; ossimString affinePrefix = ossimString(prefix) + AFFINE_PREFIX; ossimString quadwarpPrefix = ossimString(prefix) + QUADWARP_PREFIX; if (theClientProjection.valid() && theWarpTransform.valid() && theAffineTransform.valid()) { theClientProjection->saveState(kwl, projPrefix.c_str()); theAffineTransform->saveState(kwl, affinePrefix.c_str()); theWarpTransform->saveState(kwl, quadwarpPrefix.c_str()); } if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimWarpProjection::saveState: returning..." << std::endl; return ossimProjection::saveState(kwl, prefix); } //***************************************************************************** // METHOD: ossimWarpProjection::loadState() //***************************************************************************** bool ossimWarpProjection::loadState(const ossimKeywordlist& kwl, const char* prefix) { if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimWarpProjection::loadState: entering..." << std::endl; // bool good_load; // int err_stat; // bool result = true; ossimString projPrefix = ossimString(prefix) + PROJECTION_PREFIX; ossimString affinePrefix = ossimString(prefix) + AFFINE_PREFIX; ossimString quadwarpPrefix = ossimString(prefix) + QUADWARP_PREFIX; theClientProjection = 0; if (!theWarpTransform) theWarpTransform = new ossimQuadTreeWarp(); if (!theAffineTransform) theAffineTransform = new ossimAffineTransform(); theClientProjection = ossimProjectionFactoryRegistry::instance()->createProjection(kwl, projPrefix.c_str()); if ( theClientProjection.valid() ) { theWarpTransform->loadState(kwl, quadwarpPrefix.c_str()); theAffineTransform->loadState(kwl, affinePrefix.c_str()); } #if 0 /* set but not used warning... */ if(!theClientProjection) { result = false; } else { theWarpTransform->loadState(kwl, quadwarpPrefix.c_str()); theAffineTransform->loadState(kwl, affinePrefix.c_str()); } #endif return ossimProjection::loadState(kwl, prefix); } //***************************************************************************** // METHOD: ossimWarpProjection::dup() //***************************************************************************** ossimObject* ossimWarpProjection::dup() const { ossimKeywordlist kwl; saveState(kwl); return new ossimWarpProjection(kwl); } //***************************************************************************** // METHOD: //***************************************************************************** ossimGpt ossimWarpProjection::origin() const { if (theClientProjection.valid()) return theClientProjection->origin(); return ossimGpt(0.0, 0.0, 0.0); } //***************************************************************************** // METHOD: //***************************************************************************** ossimDpt ossimWarpProjection::getMetersPerPixel() const { if (theClientProjection.valid()) return theClientProjection->getMetersPerPixel(); return ossimDpt(ossim::nan(), ossim::nan()); } void ossimWarpProjection::setNewWarpTransform(ossim2dTo2dTransform* warp) { if(warp) { theWarpTransform = warp; } } void ossimWarpProjection::setNewAffineTransform(ossim2dTo2dTransform* affine) { if(affine) { theAffineTransform = affine; } } ossim-Miami-2.9.1/src/projection/ossimWktProjectionFactory.cpp000077500000000000000000000415261352751253100246020ustar00rootroot00000000000000//************************************************************************************************* // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // DESCRIPTION: // Projection Factory for EPSG coded projections. These are projections // that are fully defined in database files and specified via a projection coordinate system (PCS) // code. // //************************************************************************************************* // $Id: ossimWktProjectionFactory.cpp 23379 2015-06-17 19:17:24Z okramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; ossimWktProjectionFactory* ossimWktProjectionFactory::m_instance = 0; static const ossimString WKT_MAGIC("WKT_PCS"); /************************************************************************************************* * Sample WKT string (for reference, line feeds and spaces added for human readability) * * PROJCS["NAD_1983_HARN_Lambert_Conformal_Conic", * GEOGCS["GCS_North_American_1983_HARN", * DATUM["NAD83_High_Accuracy_Regional_Network", * SPHEROID["GRS_1980",6378137,298.257222101, AUTHORITY["EPSG","7019"]], * AUTHORITY["EPSG","6152"]], * PRIMEM["Greenwich",0], * UNIT["degree",0.0174532925199433]], * PROJECTION["Lambert_Conformal_Conic_2SP"], * PARAMETER["standard_parallel_1",43], * PARAMETER["standard_parallel_2",45.5], * PARAMETER["latitude_of_origin",41.75], * PARAMETER["central_meridian",-120.5], * PARAMETER["false_easting",1312335.958005249], * PARAMETER["false_northing",0], * UNIT["foot",0.3048, AUTHORITY["EPSG","9002"]]] * * Another sample (with EPSG at the top for easy instantiation of full projection): * * PROJCS["WGS 84 / UTM zone 41N", * AUTHORITY["EPSG","32641"], * GEOGCS["WGS 84", * DATUM["WGS_1984", * SPHEROID["WGS 84",6378137,298.2572235630016, AUTHORITY["EPSG","7030"]], * AUTHORITY["EPSG","6326"]], * PRIMEM["Greenwich",0], * UNIT["degree",0.0174532925199433]], * PROJECTION["Transverse_Mercator"], * PARAMETER["latitude_of_origin",0], * PARAMETER["central_meridian",63], * PARAMETER["scale_factor",0.9996], * PARAMETER["false_easting",500000], * PARAMETER["false_northing",0], * UNIT["metre",1, AUTHORITY["EPSG","9001"]]] * **************************************************************************************************/ //************************************************************************************************* //! Implements singleton pattern //************************************************************************************************* ossimWktProjectionFactory* ossimWktProjectionFactory::instance() { if (!m_instance) m_instance = new ossimWktProjectionFactory; return m_instance; } //************************************************************************************************* //! Loads all SRS CSV files specified in the ossim prefs //************************************************************************************************* void ossimWktProjectionFactory::loadRecords() const { // Fetch filename of WKT projection DB file specified in ossim_preferences: // Optional ossim share dir: ossimFilename share_dir = ossimPreferences::instance()-> preferencesKWL().findKey( std::string( "ossim_share_directory" ) ); ossimFilename db_name; ossimFilename wkt_path = ossimPreferences::instance()->preferencesKWL(). findKey( std::string( "wkt_database_file" ) ); if ( wkt_path.size() ) { if ( !wkt_path.isRelative() ) { //--- // example: // wkt_database_file:/usr/share/ossim/projection/ossim_wkt_pcs.csv //--- db_name = wkt_path; } else if ( share_dir.size() ) { //--- // example: // ossim_share_dir: /usr/share/ossim // wkt_database_file: projection/ossim_wkt_pcs.csv //--- db_name = share_dir.dirCat( wkt_path ); //--- // This block is for backwards compatibility. // Try tacking "projection" onto share dir. //--- if ( !db_name.isReadable() ) { db_name = share_dir.dirCat( ossimFilename("projection") ); db_name = db_name.dirCat( wkt_path); // Lastly: Try tacking "ossim/projection" onto share dir. if ( !db_name.isReadable() ) { db_name = share_dir.dirCat( ossimFilename("ossim/projection") ); db_name = db_name.dirCat( wkt_path); } } } } if (!db_name.isReadable()) return; // Create only once outside the loop: ossimString format_id; ossimString line; // Open the DB file: std::ifstream db_stream(db_name.chars()); bool good_file = false; if (db_stream.good()) { // Format specification implied in file's magic number: std::getline(db_stream, format_id.string()); format_id.trim(); if (format_id == WKT_MAGIC) good_file = true; } if (!good_file) { ossimNotify(ossimNotifyLevel_WARN) << "ossimWktProjectionDatabase::loadRecords() -- Encountered bad WKT database file <" << db_name << ">. Skipping this file." << endl; db_stream.close(); return; } // The file is good. Skip over the column descriptor line: std::getline(db_stream, line.string()); // Loop to read all data records: while (!db_stream.eof()) { std::getline(db_stream, line.string()); std::vector csvRecord = line.explode(","); // ONLY CSV FILES CONSIDERED HERE if (csvRecord.size()) { std::pair projRecord; projRecord.first = csvRecord[1].string(); projRecord.second = csvRecord[0].toUInt32(); m_wktProjRecords.insert(projRecord); } } // for ( std::map::const_iterator it = m_wktProjRecords.begin(); // it != m_wktProjRecords.end(); it++) // cout << "[" << it->first << ", " << it->second << "]"<::const_iterator it = m_wktProjRecords.find(pcsName.string()); if (it != m_wktProjRecords.end()) { // Found an entry by this name, fetch the EPSG code: return it->second; } return 0; } //************************************************************************************************* //! From keywordlist (as generated typically by ossimWkt class) //************************************************************************************************* ossimProjection* ossimWktProjectionFactory::createProjection(const ossimKeywordlist &keywordList, const char *prefix) const { // The WKT for the horizontal projection may be part of a compound coordinate system, as // indicated by the "COMPD_CS" prefix. Need to remove that prefix first. ossimString compd_cs ("COMPD_CS."); ossimKeywordlist temp_kwl (keywordList); temp_kwl.stripPrefixFromAll(compd_cs); ossimProjection* proj = 0; ossimString pcs_name = temp_kwl.find(prefix, "PROJCS.name"); if (pcs_name.empty()) return 0; if (m_wktProjRecords.empty()) loadRecords(); // Search the WKT DB for a mapping of projection name to EPSG code. This should take care of // majority of cases, like UTM: ossimString epsg_code; std::map::const_iterator it = m_wktProjRecords.find(pcs_name.string()); if (it != m_wktProjRecords.end()) { // Found an entry by this name, fetch the EPSG code: epsg_code = ossimString::toString(it->second); } else { // The name specified in the WKT could not be found in our WKT->EPSG map. // Check for EPSG code in WKT itself: ossimString auth_name = temp_kwl.find(prefix, "PROJCS.AUTHORITY.name"); if (auth_name == "EPSG") epsg_code = temp_kwl.find(prefix, "PROJCS.AUTHORITY.param0"); } // Use EPSG if determined: if (!epsg_code.empty()) { // Strip quotes if any: epsg_code.trim( ossimString("\"") ); proj = ossimEpsgProjectionDatabase::instance()->findProjection(epsg_code.toUInt32()); if (proj) return proj; } // Not EPSG, so check conventional proj spec in WKT: ossimString proj_name = temp_kwl.find(prefix, "PROJCS.PROJECTION.name"); if (proj_name.empty()) return 0; proj_name.downcase(); proj_name.gsub(" ", "_", true); // Note that prefix is ignored. This KWL is assumed to come from ossimWkt that doesn't prefix: if (proj_name.contains("transverse_mercator")) proj = doTransverseMercator(temp_kwl); else if (proj_name.contains("mercator")) proj = doMercator(temp_kwl); else if (proj_name.contains("lambert")) proj = doLambertConformalConic(temp_kwl); else if (proj_name.contains("equirectangular")) proj = doEquiDistCylindrical(temp_kwl); else if (proj_name.contains("cylindrical_equal_area")) proj = doEquiAreaCylindrical(temp_kwl); return proj; } //************************************************************************************************* // This is the principal factory method. It accepts a WKT string, e.g. // // "Anguilla_1957_British_West_Indies_Grid", // // or complete WKT, e.g. // // PROJCS["Anguilla_1957_British_West_Indies_Grid", GEOGCS[... // // IMPORTANT NOTE: Image tie-points cannot be conveyed by a WKT projection string. The projection // created here will not be fully initialized for use in rendering imagery. //************************************************************************************************* ossimProjection* ossimWktProjectionFactory::createProjection(const ossimString &spec) const { ossimProjection* proj = 0; ossimWkt wkt; if (wkt.parse(spec)) { proj = createProjection(wkt.getKwl()); } return proj; } //************************************************************************************************* ossimObject* ossimWktProjectionFactory::createObject(const ossimString& typeName) const { return createProjection(typeName); } //************************************************************************************************* ossimObject* ossimWktProjectionFactory::createObject(const ossimKeywordlist& kwl, const char* prefix) const { return createProjection(kwl, prefix); } //************************************************************************************************* //! STUB. Not implemented //************************************************************************************************* ossimProjection* ossimWktProjectionFactory::createProjection(const ossimFilename& /* filename */, ossim_uint32 /* entryIdx */) const { return 0; } //************************************************************************************************* //! This returns the type name of all objects in all factories. This is the name used to //! construct the objects dynamically and this name must be unique. //************************************************************************************************* void ossimWktProjectionFactory::getTypeNameList(std::vector& typeList) const { if (m_wktProjRecords.empty()) loadRecords(); std::map::iterator db_iter = m_wktProjRecords.begin(); while (db_iter != m_wktProjRecords.end()) { typeList.push_back(ossimString(db_iter->first)); db_iter++; } return; } ossimProjection* ossimWktProjectionFactory::doTransverseMercator(const ossimKeywordlist& kwl) const { ossimTransMercatorProjection* proj = new ossimTransMercatorProjection(); doMapCommon(kwl, proj); // Determine first the units: ossimString name_read; ossimString val_read; // Read projection parameters from WKT KWL: int param_idx = 0; do { ossimString param("PROJCS.PARAMETER"); param += ossimString::toString(param_idx++); name_read = kwl.find(param + ".name"); val_read = kwl.find(param + ".param0"); if (name_read.contains("scale_factor")) { proj->setScaleFactor(val_read.toDouble()); break; } } while (!name_read.empty()); return proj; } ossimProjection* ossimWktProjectionFactory::doMercator(const ossimKeywordlist& kwl) const { ossimMercatorProjection* proj = new ossimMercatorProjection(); doMapCommon(kwl, proj); // Determine first the units: ossimString name_read; ossimString val_read; // Read projection parameters from WKT KWL: int param_idx = 0; do { ossimString param("PROJCS.PARAMETER"); param += ossimString::toString(param_idx++); name_read = kwl.find(param + ".name"); val_read = kwl.find(param + ".param0"); if (name_read.contains("scale_factor")) { proj->setScaleFactor(val_read.toDouble()); break; } } while (!name_read.empty()); return proj; } ossimProjection* ossimWktProjectionFactory::doLambertConformalConic(const ossimKeywordlist& kwl) const { ossimLambertConformalConicProjection* proj = new ossimLambertConformalConicProjection(); doMapCommon(kwl, proj); // Determine first the units: ossimString name_read; ossimString val_read; // Read projection parameters from WKT KWL: int param_idx = 0; do { ossimString param("PROJCS.PARAMETER"); param += ossimString::toString(param_idx++); name_read = kwl.find(param + ".name"); val_read = kwl.find(param + ".param0"); if (name_read.contains("standard_parallel_1")) proj->setStandardParallel1(val_read.toDouble()); else if (name_read.contains("standard_parallel_2")) proj->setStandardParallel2(val_read.toDouble()); } while (!name_read.empty()); return proj; } ossimProjection* ossimWktProjectionFactory::doEquiDistCylindrical(const ossimKeywordlist& kwl) const { ossimEquDistCylProjection* proj = new ossimEquDistCylProjection(); doMapCommon(kwl, proj); return proj; } ossimProjection* ossimWktProjectionFactory::doEquiAreaCylindrical(const ossimKeywordlist& kwl) const { ossimCylEquAreaProjection* proj = new ossimCylEquAreaProjection(); doMapCommon(kwl, proj); return proj; } template void ossimWktProjectionFactory::doMapCommon(const ossimKeywordlist& kwl, T proj) const { ossimString name_read; ossimString val_read; const ossimDatum* datum = 0; name_read = kwl.find("PROJCS.GEOGCS.AUTHORITY.name"); val_read = kwl.find("PROJCS.GEOGCS.AUTHORITY.param0"); if ((name_read == "EPSG") && (!val_read.empty())) { datum = ossimEpsgDatumFactory::instance()->create(val_read.toUInt32()); if (datum) proj->setDatum(datum); // TODO: HARN Datum not being handled } // Determine first the units: name_read = kwl.find("PROJCS.UNIT.name"); double conv_factor = 1.0; if (name_read.contains("f")) // feet|foot { conv_factor = MTRS_PER_FT; proj->setProjectionUnits(OSSIM_FEET); } // Read projection parameters from WKT KWL: int param_idx = 0; ossimGpt origin(0, 0, 0, datum); do { ossimString param("PROJCS.PARAMETER"); param += ossimString::toString(param_idx++); name_read = kwl.find(param + ".name"); val_read = kwl.find(param + ".param0"); if (name_read.contains("central_meridian")) origin.lon = val_read.toDouble(); else if (name_read.contains("latitude_of_origin")) origin.lat = val_read.toDouble(); else if (name_read.contains("false_easting")) proj->setFalseEasting(val_read.toDouble() * conv_factor); else if (name_read.contains("false_northing")) proj->setFalseNorthing(val_read.toDouble() * conv_factor); } while (!name_read.empty()); proj->setOrigin(origin); } ossim-Miami-2.9.1/src/reg/000077500000000000000000000000001352751253100152575ustar00rootroot00000000000000ossim-Miami-2.9.1/src/reg/GroundControlPoint.cpp000066400000000000000000000071731352751253100216040ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include using namespace std; namespace ossim { GroundControlPoint::GroundControlPoint() { } GroundControlPoint::GroundControlPoint(const Json::Value& json_node) : m_covariance (3) { m_covariance.ReSize(3); loadJSON(json_node); } GroundControlPoint::~GroundControlPoint() { } void GroundControlPoint::loadJSON(const Json::Value& json_node) { ostringstream xmsg; xmsg<<__FILE__<<": "; m_id = json_node["gcpId"].asString(); if (m_id.empty()) m_id = json_node["pointId"].asString(); if (json_node.isMember("lat") && json_node.isMember("lon") && json_node.isMember("hgt")) { ossimGpt refGpt; refGpt.lat = json_node["lat"].asDouble(); refGpt.lon = json_node["lon"].asDouble(); refGpt.hgt = json_node["hgt"].asDouble(); m_gcp = ossimEcefPoint(refGpt); } else if (json_node.isMember("x") && json_node.isMember("y") && json_node.isMember("z")) { m_gcp.x() = json_node["x"].asDouble(); m_gcp.y() = json_node["y"].asDouble(); m_gcp.z() = json_node["z"].asDouble(); } else { xmsg<<"Ground point coordinates JSON not correct. JSON: \n"< ECF conversion needed here? if (covSize == 6) { m_covariance(0,0) = covariance[0].asDouble(); m_covariance(1,1) = covariance[1].asDouble(); m_covariance(2,2) = covariance[2].asDouble(); m_covariance(0,1) = covariance[3].asDouble(); m_covariance(0,2) = covariance[4].asDouble(); m_covariance(1,2) = covariance[5].asDouble(); } else { m_covariance(0,0) = covariance[0].asDouble(); m_covariance(0,1) = covariance[1].asDouble(); m_covariance(0,2) = covariance[2].asDouble(); m_covariance(1,0) = covariance[3].asDouble(); m_covariance(1,1) = covariance[4].asDouble(); m_covariance(1,2) = covariance[5].asDouble(); m_covariance(2,0) = covariance[6].asDouble(); m_covariance(2,1) = covariance[7].asDouble(); m_covariance(2,2) = covariance[8].asDouble(); } // TODO: Implement GCP cross-correlation if (json_node.isMember("crossCovariances") || json_node.isMember("gpCrossCovList")) { ossimNotify(ossimNotifyLevel_WARN)<<"GCP cross covariances are specified in the JSON, but the" " capability is not yet implemented!"< #include #include #include using namespace std; namespace ossim { Image::Image(const std::string& imageId, const std::string& filename, const std::string& modelName, unsigned int entryIndex, unsigned int band) : m_imageId (imageId), m_filename (filename), m_entryIndex (entryIndex), m_activeBand (band), m_modelName (modelName) { } Image::Image(const Json::Value& json_node) : m_entryIndex (0), m_activeBand (1) { loadJSON(json_node); } Image::~Image() { //m_handler.reset(); } void Image::getAvailableModels(std::vector< pair >& availableModels) const { ossimProjection* proj = ossimProjectionFactoryRegistry::instance()-> createProjection(m_filename, m_entryIndex); if (proj) { availableModels.push_back(pair("OSSIM", proj->getLongName().string())); delete proj; } } void Image::loadJSON(const Json::Value& json_node) { ostringstream xmsg; xmsg<<__FILE__<<": loadJSON(JSON) -- "; // Parse JSON. Filename is required: if (json_node.isMember("filename")) { ossimFilename imageFile = json_node["filename"].asString(); m_filename = imageFile.expand(); // allow embedded environment variables } else { xmsg<<"JSON node missing required field: \"filename\"."; throw ossimException(xmsg.str()); } // Entry index defaults to 0 if not present: if (json_node["entryIndex"].isUInt()) m_entryIndex = json_node["entryIndex"].asUInt(); // Band defaults to 1 if not present: if (json_node["band"].isUInt()) m_activeBand = json_node["band"].asUInt(); // Sensor model defaults to most accurate available if not provided (indicated by blank name): if (json_node.isMember("sensorModel")) m_modelName = json_node["sensorModel"].asString(); // Sensor model defaults to most accurate available if not provided (indicated by blank name): if (json_node.isMember("imageId")) m_imageId = json_node["imageId"].asString(); // Establish the sensor model. This also sets the official image ID, which will be overwritten // if JSON field provided string modelState = json_node["modelState"].asString(); ossimKeywordlist kwl; kwl.parseString(modelState); ossimProjection* proj = ossimProjectionFactoryRegistry::instance()->createProjection(kwl); m_sensorModel = dynamic_cast(proj); } void Image::saveJSON(Json::Value& json_node) const { json_node.clear(); json_node["imageId"] = m_imageId; json_node["filename"] = m_filename.string(); json_node["entryIndex"] = m_entryIndex; if (m_modelName.size()) json_node["sensorModel"] = m_modelName; if (m_sensorModel.valid()) { ossimKeywordlist kwl; m_sensorModel->saveState(kwl); json_node["modelState"] = kwl.toString().string(); } } } // end namespace ossim-Miami-2.9.1/src/reg/PhotoBlock.cpp000066400000000000000000000111771352751253100200360ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include using namespace std; namespace ossim { PhotoBlock::PhotoBlock() { } PhotoBlock::PhotoBlock(const Json::Value& pb_json_node) { loadJSON(pb_json_node); } PhotoBlock::PhotoBlock(const PhotoBlock& copyThis) : m_imageList (copyThis.m_imageList), m_tiePointList (copyThis.m_tiePointList) { *this = copyThis; } PhotoBlock::~PhotoBlock() { m_imageList.clear(); m_tiePointList.clear(); } PhotoBlock& PhotoBlock::operator=(const PhotoBlock& copythis) { m_imageList = copythis.m_imageList; m_tiePointList = copythis.m_tiePointList; m_gcpList = copythis.m_gcpList; return *this; } // TODO: Add of individual components not available until proper management of the JCM can be // provided unsigned int PhotoBlock::addImage(shared_ptr image) { unsigned int last_idx = m_imageList.size(); m_imageList.push_back(image); return last_idx; } unsigned int PhotoBlock::addGroundPoint(shared_ptr gcp) { unsigned int last_idx = m_gcpList.size(); m_gcpList.push_back(gcp); return last_idx; } unsigned int PhotoBlock::addTiePoint(shared_ptr tiepoint) { unsigned int index = m_tiePointList.size(); m_tiePointList.push_back(tiepoint); return index; } void PhotoBlock::addTiePoints(TiePointList& tiepointList) { for (size_t i=0; i PhotoBlock::getImage(const std::string& imageId) { std::shared_ptr result; for (size_t i=0; igetImageId() == imageId) { result = m_imageList[i]; break; } } return result; } shared_ptr PhotoBlock::getGroundPoint(const std::string& gcpId) { std::shared_ptr result; for (size_t i=0; igetId() == gcpId) { result = m_gcpList[i]; break; } } return result; } shared_ptr PhotoBlock::getTiePoint(unsigned int tpId) { std::shared_ptr result; for (size_t i=0; igetTiePointId() == tpId) { result = m_tiePointList[i]; break; } } return result; } void PhotoBlock::loadJSON(const Json::Value& pb_json_node) { // Always do images first, as tiepoints will be using the image list to correct image ID: if (pb_json_node.isMember("images")) { const Json::Value& listJson = pb_json_node["images"]; unsigned int count = listJson.size(); for (unsigned int i=0; i item (new Image(jsonItem)); m_imageList.push_back(item); } } if (pb_json_node.isMember("groundPoints")) { const Json::Value& listJson = pb_json_node["groundPoints"]; unsigned int count = listJson.size(); for (unsigned int i=0; i item (new GroundControlPoint(jsonItem)); m_gcpList.push_back(item); } } if (pb_json_node.isMember("tiePoints")) { const Json::Value& listJson = pb_json_node["tiePoints"]; unsigned int count = listJson.size(); for (unsigned int i=0; i item (new TiePoint(jsonItem)); m_tiePointList.push_back(item); } } } void PhotoBlock::saveJSON(Json::Value& pbJSON) const { Json::Value imageListJson (Json::arrayValue); unsigned int count = m_imageList.size(); for (unsigned int i=0; isaveJSON(imageListJson[i]); } pbJSON["images"] = imageListJson; Json::Value gcpListJson (Json::arrayValue); count = m_gcpList.size(); for (unsigned int i=0; isaveJSON(gcpListJson[i]); } pbJSON["groundPoints"] = gcpListJson; Json::Value tpListJson (Json::arrayValue); count = m_tiePointList.size(); for (unsigned int i=0; isaveJSON(tpListJson[i]); } pbJSON["tiePoints"] = tpListJson; } } // end namespace ossim-Miami-2.9.1/src/reg/TiePoint.cpp000066400000000000000000000141231352751253100175170ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include using namespace std; namespace ossim { int TiePoint::s_runningId = 1; TiePoint::TiePoint() : m_type (UNASSIGNED), m_gsd (0.0) { } TiePoint::TiePoint(const TiePoint& copy) : m_type (copy.m_type), m_gsd (copy.m_gsd), m_gcpId (copy.m_gcpId) { for (size_t i=0; i= m_images.size()) return; imageId = m_images[index]->getImageId(); imagePoint = m_imagePoints[index]; if (m_covariances.size() > index) cov = m_covariances[index]; } void TiePoint::setImagePoint(std::shared_ptr image, const ossimDpt& imagePoint, const NEWMAT::SymmetricMatrix& cov) { bool found = false; // Possible edit of existing point? for (size_t i=0; igetImageId().compare(image->getImageId()) == 0) { found = true; if (i >= m_imagePoints.size()) { // This shouldn't happen, but go ahead and resize for this image: m_imagePoints.resize(i+1); m_covariances.resize(i+1); } m_imagePoints[i] = imagePoint; m_covariances[i] = cov; break; } } if (!found) { m_images.push_back(image); m_imagePoints.push_back(imagePoint); m_covariances.push_back(cov); } } void TiePoint::setGcpId(const std::string& id) { m_gcpId = id; m_type = GCP; } void TiePoint::loadJSON(const Json::Value& json_node) { ostringstream xmsg; xmsg<<__FILE__<<": TiePoint(JSON) --"; // ID setTiePointId(json_node["id"].asString()); // Type string tpType = json_node["type"].asString(); switch (tpType[0]) { case 'M': m_type = TiePoint::MANUAL; break; case 'A': m_type = TiePoint::AUTO; break; case 'G': m_type = TiePoint::GCP; break; default: xmsg<<"Tiepoint JSON field \"type\" must be specified as 'M', 'A', or 'G'."; throw ossimException(xmsg.str()); } // Read the GCP ID if present: if (m_type == TiePoint::GCP) m_gcpId = json_node["gcpId"].asString(); // Image points const Json::Value& imagePoints = json_node["imagePoints"]; if (!imagePoints || (imagePoints.size() < 1)) { xmsg<<"Tiepoint JSON field \"imagePoints\" not found or is empty!"; throw ossimException(xmsg.str()); } // Loop over points on each image: for (int i=0; i image (new Image(imageId, filename)); m_images.push_back(image); ossimDpt xy(p["x"].asDouble(), p["y"].asDouble()); m_imagePoints.push_back(xy); const Json::Value& covariance = p["covariance"]; if (covariance.size() == 3) { NEWMAT::SymmetricMatrix c(2); c(1, 1) = covariance[0].asDouble(); c(2, 2) = covariance[1].asDouble(); c(1, 2) = covariance[2].asDouble(); m_covariances.push_back(c); } } } void TiePoint::saveJSON(Json::Value& json_node) const { // ID json_node["id"] = m_tiePointId; // Type string tpType = json_node["type"].asString(); switch (m_type) { case TiePoint::MANUAL: json_node["type"] = "M"; break; case TiePoint::AUTO: json_node["type"] = "A"; break; case TiePoint::GCP: json_node["type"] = "G"; break; default: json_node["type"] = "UNNASSIGNED"; } // Image points Json::Value jsonList (Json::arrayValue); // Loop over points on each image: for (int i=0; igetFilename(); jsonList[i]["imageId"] = m_images[i]->getImageId(); jsonList[i]["x"] = m_imagePoints[i].x; jsonList[i]["y"] = m_imagePoints[i].y; if (i #include #include #include #include #include #include #include #include #include #include #ifdef _MSC_VER #include #include #else #include #endif using namespace std; #define MAX_BUF_LEN 4096 #define _DEBUG_ false ossimToolClient::ossimToolClient() : m_svrsockfd(-1), m_buffer(new char[MAX_BUF_LEN]) { ossimFilename tmpdir = "/tmp"; #ifdef _MSC_VER if (GetTempPath(MAX_BUF_LEN, m_buffer)) tmpdir = m_buffer; #endif setProductFilePath(tmpdir); } ossimToolClient::~ossimToolClient() { disconnect(); } bool ossimToolClient::disconnect() { bool success = true; if (m_svrsockfd < 0) return success; // Need to send close request to server: if (close(m_svrsockfd) < 0) { error("Error closing socket"); success = false; } m_svrsockfd = -1; return success; } void ossimToolClient::error(const char *msg) { perror(msg); } int ossimToolClient::connectToServer(char* hostname, char* portname) { m_svrsockfd = -1; while (1) { // Consider port number in host URL: ossimString host (hostname); ossimString port; if (portname) port = portname; else if (host.contains(":")) { port = host.after(":"); host = host.before(":"); } if (port.empty()) { // Maybe implied port then '/': port = host.after("/"); port = "/" + port; host = host.before("/"); } // Establish full server address including port: struct addrinfo hints; memset(&hints, 0, sizeof hints); // make sure the struct is empty hints.ai_family = AF_INET; // don't care IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // TCP stream sockets hints.ai_canonname = host.stringDup(); // fill in my IP for me struct addrinfo *res; int failed = getaddrinfo(host.stringDup(), port.stringDup(), &hints, &res); if (failed) { error(gai_strerror(failed)); break; } // Create socket for this server by walking the linked list of available addresses: struct addrinfo *server_info = res; while (server_info) { m_svrsockfd = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol); if (m_svrsockfd >= 0) break; server_info = server_info->ai_next; } if ((m_svrsockfd < 0) || (server_info == NULL)) { error("Error opening socket"); break; } // Connect to the server:portno: struct sockaddr_in* serv_addr = (sockaddr_in*) server_info->ai_addr; serv_addr->sin_family = AF_INET; if (connect(m_svrsockfd,(struct sockaddr*) serv_addr, server_info->ai_addrlen) < 0) { error("ERROR connecting"); disconnect(); } break; } return m_svrsockfd; } bool ossimToolClient::execute(const char* command_spec) { // Clear previous file path of product filename: if (!m_prodFilePath.isDir()) m_prodFilePath =m_prodFilePath.path(); if (command_spec == NULL) return false; // Write command to the OSSIM tool server socket: if (_DEBUG_) cout<<"ossimToolClient:"<<__LINE__<<" sending <"<..."<..."<"<"<"<."<"< is not writable."< #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _MSC_VER #include #include /* for getpid() and the exec..() family */ #include #define dup2 _dup2 #define close closesocket #define pipe(phandles) _pipe(phandles, 4096, _O_BINARY) #else #include #include #include #include #include #include #include using namespace std; #endif #define OWARN ossimNotify(ossimNotifyLevel_WARN) #define OINFO ossimNotify(ossimNotifyLevel_INFO) #define MAX_BUF_LEN 4096 #define FORK_PROCESS false #define _DEBUG_ false ossimToolServer::ossimToolServer() : m_svrsockfd(-1), m_clisockfd(-1), m_buffer(new char[MAX_BUF_LEN]) {} ossimToolServer::~ossimToolServer() { close(m_svrsockfd); } void ossimToolServer::startListening(const char* portid) { initSocket(portid); socklen_t clilen; ostringstream xmsg; bool status_ok = true; // Loop forever to listen for OSSIM requests: OINFO<<"Waiting for connections...\n"<ai_family, server_info->ai_socktype, server_info->ai_protocol); if (m_svrsockfd >= 0) break; server_info = server_info->ai_next; } if ((m_svrsockfd < 0) || (server_info == NULL)) error("Error opening socket"); // lose the pesky "Address already in use" error message when requently restarting the daemon: int yes=1; if (setsockopt(m_svrsockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof yes) == -1) error("Error on setsockopt() call"); #if defined (__APPLE__) || defined(__FreeBSD__) int bindResult = ::bind(m_svrsockfd, server_info->ai_addr, server_info->ai_addrlen); #else int bindResult = bind(m_svrsockfd, server_info->ai_addr, server_info->ai_addrlen); #endif // Bind the server's socket to the specified port number: if ( bindResult < 0) error("Error on binding to socket:port."); struct sockaddr_in *server_addr = (sockaddr_in*) &(server_info->ai_addr); OINFO<<"ossimToolServer daemon started. Listening on port "< 0); errno = saved_errno; } void ossimToolServer::error(const char* msg) { perror(msg); exit (1); } void ossimToolServer::writeSocket(const char* buf, int bufsize) { int remaining = bufsize; int n; //int optval = 1; //setsockopt(clientfd, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(int)); while (remaining) { n = send(m_clisockfd, buf, remaining, 0); if (n < 0) error("ERROR writing to socket"); remaining -= n; } } bool ossimToolServer::sendFile(const ossimFilename& fname) { ostringstream xmsg; // Open the server-side image file: ifstream svrfile (fname.chars(), ios::binary|ios::in); if (svrfile.fail()) { xmsg<<"ossimToolServer.sendFile() -- Error opening file <"<."<"<"<"< utility = 0; // Intercept help request: ossimString c1 = command.before(" "); ossimString c2 = command.after(" "); while (1) { if (c1 == "help") { if (!c2.empty()) { command = c2 + " --help"; } else { map capabilities; factory->getCapabilities(capabilities); map::iterator iter = capabilities.begin(); cout<<"\nAvailable commands:\n"<first<<" -- "<second<createTool(util_name); try { // Perform OSSIM command execution: if (!utility.valid()) cout<"<initialize(ap)) cout<."<helpRequested() && !utility->execute()) cout<\nCheck options."< 0) full_output.append(m_buffer, n); } if (status_ok) { if (utility.valid() && !utility->helpRequested() && utility->isChipProcessor()) { const char* response = "FILE "; writeSocket(response, strlen(response)); ossimChipProcTool* ocp = (ossimChipProcTool*) utility.get(); ossimFilename prodFilename = ocp->getProductFilename(); sendFile(prodFilename); } else { const char* response = "TEXT "; writeSocket(response, strlen(response)); writeSocket(full_output.c_str(), full_output.size()); if (!acknowledgeRcvd()) error("ERROR receiving acknowledge from client."); } } else { const char* response = "ERROR"; writeSocket(response, strlen(response)); writeSocket(full_output.c_str(), full_output.size()); cout << "Sending ERROR to client and closing connection: <"<"<"< #include #include const ossimString ossim::ImageHandlerState::m_typeName = "ossim::ImageHandlerState"; ossim::ImageHandlerState::ImageHandlerState() : State(), m_currentEntry(0) { } ossim::ImageHandlerState::ImageHandlerState::~ImageHandlerState() { } const ossimString& ossim::ImageHandlerState::getTypeName()const { return m_typeName; } const ossimString& ossim::ImageHandlerState::getStaticTypeName() { return m_typeName; } bool ossim::ImageHandlerState::hasMetaData()const { if(m_omd) { return m_omd->isValid(); } return false; } bool ossim::ImageHandlerState::loadDefaults(const ossimFilename& filename, ossim_uint32 entry) { m_connectionString = filename; m_currentEntry = entry; // we still need to add initialization of the defaults for // valid vertices and overview detections, ... etc // return true; } bool ossim::ImageHandlerState::load(const ossimKeywordlist& kwl, const ossimString& prefix) { bool result = ossim::State::load(kwl, prefix); m_overviewState = ossim::ImageHandlerStateRegistry::instance()->createState(kwl, prefix+"overview."); m_connectionString = kwl.find(prefix, "connection_string"); m_imageHandlerType = kwl.find(prefix, "image_handler_type"); ossimString currentEntry = kwl.find(prefix, "current_entry"); if(currentEntry.empty()) { m_currentEntry = 0; } else { m_currentEntry = currentEntry.toUInt32(); } ossimString omdType = kwl.find(prefix, "ossimImageMetaData"); if(!omdType.empty()) { m_omd = std::make_shared(); m_omd->loadState(kwl, prefix+"omd."); } ossimKeywordlist tempKwl; kwl.extractKeysThatMatch(tempKwl, "^("+prefix+"valid_vertices.)"); if(tempKwl.getSize()) { tempKwl.stripPrefixFromAll("^("+prefix+"valid_vertices.)"); m_validVertices = std::make_shared(tempKwl); } return result; } bool ossim::ImageHandlerState::save(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = ossim::State::save(kwl, prefix); if(m_overviewState) { ossimString tempPrefix = prefix + "overview."; m_overviewState->save(kwl, tempPrefix); } if(m_omd) { ossimString tempPrefix = prefix + "omd."; m_omd->saveState(kwl, tempPrefix); } kwl.add(prefix, "connection_string", m_connectionString.c_str(), true); kwl.add(prefix, "image_handler_type", m_imageHandlerType.c_str(), true); kwl.add(prefix, "current_entry", m_currentEntry, true); if(m_validVertices) { ossimString validVerticesPrefix = prefix+"valid_vertices."; kwl.add(validVerticesPrefix.c_str(), *m_validVertices); kwl.add(validVerticesPrefix, "type", "ossimValidVertices"); } return result; } ossim-Miami-2.9.1/src/support_data/ImageHandlerStateFactory.cpp000066400000000000000000000027741352751253100245760ustar00rootroot00000000000000#include #include #include #include #include ossim::ImageHandlerStateFactory::ImageHandlerStateFactory() { } std::shared_ptr ossim::ImageHandlerStateFactory::instance() { static std::shared_ptr imageHandlerFactory = std::make_shared< ossim::ImageHandlerStateFactory >(); return imageHandlerFactory; } std::shared_ptr ossim::ImageHandlerStateFactory::createState(const ossimKeywordlist& kwl, const ossimString& prefix)const { std::shared_ptr result; ossimString typeValue = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if(typeValue) { result = createState(typeValue); if(result) { try { result->load(kwl, prefix); } catch(ossimException& e) { result = nullptr; } } } return result; } std::shared_ptr ossim::ImageHandlerStateFactory::createState(const ossimString& typeName)const { std::shared_ptr result; if(typeName == ossim::TiffHandlerState::getStaticTypeName()) { result = std::make_shared(); } return result; } ossim-Miami-2.9.1/src/support_data/ImageHandlerStateRegistry.cpp000066400000000000000000000024061352751253100247670ustar00rootroot00000000000000#include #include ossim::ImageHandlerStateRegistry::ImageHandlerStateRegistry() { } std::shared_ptr ossim::ImageHandlerStateRegistry::instance() { static std::shared_ptr imageHandlerStateRegistry = std::make_shared(); return imageHandlerStateRegistry; } std::shared_ptr ossim::ImageHandlerStateRegistry::createState(const ossimKeywordlist& kwl, const ossimString& prefix)const { ScopeReadLock scopedReadLock(m_rwlock); std::shared_ptr result; for(const auto& factory:m_factoryList) { result = factory->createState(kwl, prefix); if(result) break; } return result; } std::shared_ptr ossim::ImageHandlerStateRegistry::createState(const ossimString& typeName)const { ScopeReadLock scopedReadLock(m_rwlock); std::shared_ptr result; for(const auto& factory:m_factoryList) { result = factory->createState(typeName); if(result) break; } return result; } ossim-Miami-2.9.1/src/support_data/TiffHandlerState.cpp000066400000000000000000001015121352751253100231020ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //nullptr #include static ossimTrace traceDebug("ossim::TiffHandlerState"); static const ossimGeoTiffCoordTransformsLut COORD_TRANS_LUT; static const ossimGeoTiffDatumLut DATUM_LUT; const ossimString ossim::TiffHandlerState::m_typeName = "ossim::TiffHandlerState"; ossim::TiffHandlerState::TiffHandlerState() { } ossim::TiffHandlerState::~TiffHandlerState() { } const ossimString& ossim::TiffHandlerState::getTypeName()const { return m_typeName; } const ossimString& ossim::TiffHandlerState::getStaticTypeName() { return m_typeName; } void ossim::TiffHandlerState::addValue(const ossimString& key, const ossimString& value) { m_tags.add(key.c_str(), value.c_str()); } bool ossim::TiffHandlerState::getValue(ossimString& value, const ossim_uint32 directory, const ossimString& key)const { return getValue(value, "tiff.image"+ossimString::toString(directory)+"."+key); } bool ossim::TiffHandlerState::getValue(ossimString& value, const ossimString& key)const { bool result = false; const char* v = m_tags.find(key.c_str()); if(v) { result = true; value = v; } return result; } bool ossim::TiffHandlerState::exists(ossim_uint32 directory, const ossimString& key)const { return exists("tiff.image"+ ossimString::toString(directory)+ "."+key); } bool ossim::TiffHandlerState::exists(const ossimString& key)const { return (m_tags.find(key)!= 0); } bool ossim::TiffHandlerState::checkBool(ossim_uint32 directory, const ossimString& key)const { return checkBool("tiff.image"+ossimString::toString(directory)+"."+key); } bool ossim::TiffHandlerState::checkBool(const ossimString& key)const { bool result = false; const char* value = m_tags.find(key); if(value) { result = ossimString(value).toBool(); } return result; } bool ossim::TiffHandlerState::loadDefaults(const ossimFilename& file, ossim_uint32 entry) { bool result = ImageHandlerState::loadDefaults(file, entry); if(result) { std::shared_ptr tiffStream = ossim::StreamFactoryRegistry::instance()->createIstream(file); if(tiffStream) { std::shared_ptr streamAdaptor = std::make_shared(tiffStream, file.c_str()); TIFF* tiffPtr = XTIFFClientOpen(file.c_str(), "rm", (thandle_t)streamAdaptor.get(), ossim::TiffIStreamAdaptor::tiffRead, ossim::TiffIStreamAdaptor::tiffWrite, ossim::TiffIStreamAdaptor::tiffSeek, ossim::TiffIStreamAdaptor::tiffClose, ossim::TiffIStreamAdaptor::tiffSize, ossim::TiffIStreamAdaptor::tiffMap, ossim::TiffIStreamAdaptor::tiffUnmap); if(tiffPtr) { loadDefaults(tiffPtr); result = true; XTIFFClose(tiffPtr); tiffPtr = 0; } } } return result; } void ossim::TiffHandlerState::loadDefaults(TIFF* tiffPtr) { ossim_int64 currentDirectory = TIFFCurrentDirectory(tiffPtr); TIFFSetDirectory(tiffPtr, 0); ossim_int32 numberOfDirectories = TIFFNumberOfDirectories(tiffPtr); addValue("number_of_directories", ossimString::toString(numberOfDirectories)); ossim_int32 idx=0; for(;idx < numberOfDirectories;++idx) { if (!TIFFSetDirectory(tiffPtr, idx)) { break; } else { loadDirectory(tiffPtr, idx); } } TIFFSetDirectory(tiffPtr, currentDirectory); } void ossim::TiffHandlerState::loadDefaults(std::shared_ptr &str, const std::string &connectionString) { setConnectionString(connectionString); ossim_int64 offset = str->tellg(); ossimTiffInfo info; std::ostringstream out; str->seekg(0); if(info.open(str, connectionString)) { std::vector prefixValues; ossim_int32 nValues=0; info.print(out); m_tags.parseString(out.str()); m_tags.getSortedList(prefixValues, "tiff.image"); nValues = prefixValues.size(); addValue("tiff.number_of_directories", ossimString::toString(nValues)); ossim_uint32 idx = 0; ossim_int64 h = getImageLength(0); ossim_int64 w = getImageWidth(0); ossim_int64 tw = getTileWidth(0); ossim_int64 th = getTileLength(0); bool isTiled = (th&&tw&& ((tw < w) && (th < h))); for (auto key : prefixValues) { if(isTiled) { addValue(key + ".is_tiled", "true"); } else { addValue(key+".is_tiled", "false"); } } } // std::cout << "______________________________________________\n" // << m_tags // << "_______________________________________________\n"; str->clear(); str->seekg(offset); } void ossim::TiffHandlerState::loadCurrentDirectory(TIFF* tiffPtr) { if(tiffPtr) { loadDirectory(tiffPtr, TIFFCurrentDirectory(tiffPtr)); } } void ossim::TiffHandlerState::loadDirectory(TIFF* tiffPtr, ossim_uint32 directory) { ossim_uint32 imageWidth=0; ossim_uint32 imageLength=0; ossim_int32 readMethod=0; ossim_uint16 planarConfig=0; ossim_uint16 photometric=0; ossim_uint32 rowsPerStrip=0; ossim_uint32 imageTileWidth=0; ossim_uint32 imageTileLength=0; ossim_uint32 imageDirectoryList=0; ossim_int32 compressionType=0; ossim_uint32 subFileType=0; ossim_uint16 bitsPerSample=0; ossim_uint16 samplesPerPixel=0; ossim_uint16 sampleFormatUnit=0; ossim_float64 sampleValue=0; ossim_uint16 sampleUintValue = 0; ossim_int32 numberOfDirectories = TIFFNumberOfDirectories(tiffPtr); addValue("number_of_directories", ossimString::toString(numberOfDirectories)); if(TIFFCurrentDirectory(tiffPtr) != directory) { if(!TIFFSetDirectory(tiffPtr, directory)) { return; } } ossimString dirPrefix = "tiff.image"+ossimString::toString(directory)+"."; if(TIFFGetField(tiffPtr, TIFFTAG_COMPRESSION, &compressionType)) { addValue(dirPrefix+"compression", ossimString::toString(compressionType)); } if( TIFFGetField(tiffPtr, TIFFTAG_BITSPERSAMPLE, &bitsPerSample) ) { addValue(dirPrefix+"bits_per_sample", ossimString::toString(bitsPerSample)); } if( TIFFGetField(tiffPtr, TIFFTAG_SAMPLESPERPIXEL, &samplesPerPixel ) ) { addValue(dirPrefix+"samples_per_pixel", ossimString::toString(samplesPerPixel)); } if ( TIFFGetField( tiffPtr, TIFFTAG_SAMPLEFORMAT, &sampleFormatUnit ) ) { addValue(dirPrefix+"sample_format", ossimString::toString(sampleFormatUnit)); } if (TIFFGetField(tiffPtr, TIFFTAG_SMAXSAMPLEVALUE, &sampleValue ) ) { addValue(dirPrefix+"max_sample_value", ossimString::toString(sampleValue)); } else { if(TIFFGetField( tiffPtr, TIFFTAG_MAXSAMPLEVALUE, &sampleUintValue)) { addValue(dirPrefix+"max_sample_value", ossimString::toString(sampleUintValue)); } } if ( TIFFGetField( tiffPtr, TIFFTAG_SMINSAMPLEVALUE, &sampleValue ) ) { addValue(dirPrefix+"min_sample_value", ossimString::toString(sampleValue)); } else { if(TIFFGetField( tiffPtr, TIFFTAG_MINSAMPLEVALUE, &sampleUintValue)) { addValue(dirPrefix+"min_sample_value", ossimString::toString(sampleUintValue)); } } // lines: if ( TIFFGetField( tiffPtr, TIFFTAG_IMAGELENGTH, &imageLength ) ) { addValue(dirPrefix+"image_length", ossimString::toString(imageLength)); } // samples: if ( TIFFGetField( tiffPtr, TIFFTAG_IMAGEWIDTH, &imageWidth ) ) { addValue(dirPrefix+"image_width", ossimString::toString(imageWidth)); } if (TIFFGetField(tiffPtr, TIFFTAG_SUBFILETYPE , &subFileType ) ) { addValue(dirPrefix+"sub_file_type", ossimString::toString(subFileType)); } if( TIFFGetField( tiffPtr, TIFFTAG_PLANARCONFIG, &planarConfig ) ) { addValue(dirPrefix+"planar_configuration", ossimString::toString(planarConfig)); } if( TIFFGetField( tiffPtr, TIFFTAG_PHOTOMETRIC, &photometric ) ) { addValue(dirPrefix + "photo_interpretation", ossimString::toString(photometric)); } // Check for palette. ossim_uint16* red; ossim_uint16* green; ossim_uint16* blue; if(TIFFGetField(tiffPtr, TIFFTAG_COLORMAP, &red, &green, &blue)) { if(bitsPerSample) { saveColorMap(dirPrefix, red, green, blue, 1<UOMAngle)); } if (!exists(dirPrefix + "linear_units")) { loadedGeotiff = true; addValue(dirPrefix + "linear_units", ossimString::toString(defs->UOMLength)); } if (!exists(dirPrefix + "datum_code")) { loadedGeotiff = true; addValue(dirPrefix + "datum_code", ossimString::toString(defs->Datum)); } if (!exists(dirPrefix + "pcs_code")) { loadedGeotiff = true; addValue(dirPrefix + "pcs_code", ossimString::toString(defs->PCS)); } if (!exists(dirPrefix + "gcs_code")) { loadedGeotiff = true; addValue(dirPrefix + "gcs_code", ossimString::toString(defs->GCS)); } if (!exists(dirPrefix + "model_type")) { loadedGeotiff = true; addValue(dirPrefix + "model_type", ossimString::toString(defs->Model)); } GTIFFreeDefn(defs); } #endif addValue(dirPrefix+"is_geotiff", ossimString::toString(loadedGeotiff)); GTIFFree(gtif); } bool ossim::TiffHandlerState::isDigitalGlobe() const { ossimString value; bool result = false; if(getValue(value, "tiff.is_digital_globe")) { result = value.toBool(); } return result; } bool ossim::TiffHandlerState::isReduced(ossim_uint32 directory)const { return getSubFileType(directory)&FILETYPE_REDUCEDIMAGE; } bool ossim::TiffHandlerState::isMask(ossim_uint32 directory)const { return getSubFileType(directory) & FILETYPE_MASK; } bool ossim::TiffHandlerState::isPage(ossim_uint32 directory)const { return getSubFileType(directory) & FILETYPE_PAGE; } bool ossim::TiffHandlerState::isTiled(ossim_uint32 directory)const { return checkBool(directory, "is_tiled"); } void ossim::TiffHandlerState::convertArrayToStringList(ossimString& result, double* doubleArray, ossim_int32 doubleArraySize)const { ossim_int32 idx = 0; result = ""; if(doubleArray && (doubleArraySize > 0)) { ossim_int32 precision = 20; std::ostringstream doubleArrayStream; doubleArrayStream << "("; for(idx = 0; idx < doubleArraySize-1;++idx) { doubleArrayStream << ossimString::toString(doubleArray[idx],20) << ","; } doubleArrayStream << ossimString::toString(doubleArray[idx],20) << ")"; result = doubleArrayStream.str(); } } ossim_int32 ossim::TiffHandlerState::getModelType(ossim_int32 directory)const { ossimString tempStr; ossim_int32 result = 0; if (!getValue(tempStr, directory, "model_type")) { tempStr = "unknown"; } if (tempStr == "geographic") { result = ModelTypeGeographic; } else if (tempStr == "projected") { result = ModelTypeProjected; } else if (tempStr == "geocentric") { result = ModelTypeGeocentric; } return result; } ossim_int32 ossim::TiffHandlerState::getAngularUnits(ossim_int32 directory)const { return getInt32Value("angular_units", directory); } ossim_int32 ossim::TiffHandlerState::getLinearUnits(ossim_int32 directory)const { return getInt32Value("linear_units", directory); } ossim_int32 ossim::TiffHandlerState::getDatumCode(ossim_int32 directory)const { return getInt32Value("datum_code", directory); } ossim_int32 ossim::TiffHandlerState::getPcsCode(ossim_int32 directory)const { return getInt32Value("pcs_code", directory); } ossim_int32 ossim::TiffHandlerState::getGcsCode(ossim_int32 directory)const { return getInt32Value("gcs_code", directory); } ossim_int32 ossim::TiffHandlerState::getInt32Value(const ossimString& key, ossim_int32 directory)const { ossimString tempStr; if(getValue(tempStr, directory, key)) { return tempStr.toInt32(); } return ossimGeoTiff::UNDEFINED; } ossim_float64 ossim::TiffHandlerState::getDoubleValue(const ossimString& key, ossim_int32 directory)const { ossimString tempStr; if(getValue(tempStr, directory, key)) { return tempStr.toDouble(); } return ossim::nan(); } ossim_float64 ossim::TiffHandlerState::getOriginLat(ossim_int32 directory)const { return getDoubleValue("origin_lat", directory); } ossim_float64 ossim::TiffHandlerState::getOriginLon(ossim_int32 directory)const { return getDoubleValue("origin_lon", directory); } ossim_float64 ossim::TiffHandlerState::getStandardParallel1(ossim_int32 directory)const { return getDoubleValue("std_parallel_1", directory); } ossim_float64 ossim::TiffHandlerState::getStandardParallel2(ossim_int32 directory)const { return getDoubleValue("std_parallel_2", directory); } ossim_float64 ossim::TiffHandlerState::getFalseEasting(ossim_int32 directory)const { return getDoubleValue("false_easting", directory); } ossim_float64 ossim::TiffHandlerState::getFalseNorthing(ossim_int32 directory)const { return getDoubleValue("false_northing", directory); } ossim_float64 ossim::TiffHandlerState::getScaleFactor(ossim_int32 directory)const { return getDoubleValue("scale_factor", directory); } ossim_int32 ossim::TiffHandlerState::getCompressionType(ossim_int32 directory) const { ossim_int32 result = 0; ossimString tempValue; if (getValue(tempValue, directory, "compression")) { result = tempValue.toInt32(); } return result; } ossim_uint16 ossim::TiffHandlerState::getBitsPerSample(ossim_int32 directory) const { ossim_uint16 result = 8; ossimString tempValue; if (getValue(tempValue, directory, "bits_per_sample")) { result = tempValue.toUInt16(); } return result; } ossim_uint16 ossim::TiffHandlerState::getSamplesPerPixel(ossim_int32 directory) const { ossim_uint16 result = 0; ossimString tempValue; if (getValue(tempValue, directory, "samples_per_pixel")) { result = tempValue.toUInt16(); } return result; } ossim_uint16 ossim::TiffHandlerState::getSampleFormat(ossim_int32 directory) const { ossim_uint16 result = 1; ossimString tempValue; if (getValue(tempValue, directory, "sample_format")) { result = tempValue.toUInt16(); } return result; } bool ossim::TiffHandlerState::getMinSampleValue(ossim_float64 &minSampleValue, ossim_int32 directory)const { bool result = false; ossimString tempValue; if (getValue(tempValue, directory, "min_sample_value")) { minSampleValue = tempValue.toFloat64(); result = true; } else if (getValue(tempValue, directory, "smin_sample_value")) { minSampleValue = tempValue.toFloat64(); result = true; } return result; } bool ossim::TiffHandlerState::getMaxSampleValue(ossim_float64 &maxSampleValue, ossim_int32 directory)const { bool result = false; ossimString tempValue; if (getValue(tempValue, directory, "max_sample_value")) { maxSampleValue = tempValue.toFloat64(); result = true; } else if (getValue(tempValue, directory, "smax_sample_value")) { maxSampleValue = tempValue.toFloat64(); result = true; } return result; } ossim_uint32 ossim::TiffHandlerState::getRowsPerStrip(ossim_int32 directory) const { ossim_uint32 result = 0; ossimString tempValue; if(getValue(tempValue, directory, "rows_per_strip")) { result = tempValue.toUInt32(); } return result; } bool ossim::TiffHandlerState::hasColorMap(ossim_int32 directory)const { return exists(directory, "colormap"); } bool ossim::TiffHandlerState::isReduced(ossim_int32 directory) const { return getSubFileType(directory) == FILETYPE_REDUCEDIMAGE; } bool ossim::TiffHandlerState::isPage(ossim_int32 directory) const { return getSubFileType(directory) == FILETYPE_PAGE; } bool ossim::TiffHandlerState::isMask(ossim_int32 directory) const { return getSubFileType(directory) == FILETYPE_MASK; } ossim_int32 ossim::TiffHandlerState::getSubFileType(ossim_int32 directory) const { ossim_int32 result = 0; ossimString tempValue; if (getValue(tempValue, directory, "sub_file_type")) { result = tempValue.toInt32(); } return result; } ossim_uint32 ossim::TiffHandlerState::getNumberOfDirectories() const { ossim_uint32 result = 0; ossimString tempValue; if(getValue(tempValue, "tiff.number_of_directories")) { result = tempValue.toUInt32(); } return result; } bool ossim::TiffHandlerState::getColorMap(std::vector &red, std::vector &green, std::vector &blue, ossim_int32 directory) const { ossimString tempStr; red.clear(); green.clear(); blue.clear(); bool result = false; if (getValue(tempStr, directory, "colormap")) { std::vector values; ossim::toSimpleVector(values, "("+tempStr.substitute(" ", ",", true)+")"); ossim_uint32 offset = 0; if(values.size() == 768) { offset = 256; } else if (values.size() == 196608) { offset = 65536; } if(offset) { ossim_uint16 *valuesPtr = &values.front(); red = std::vector(valuesPtr, (valuesPtr + offset)); valuesPtr += offset; green = std::vector(valuesPtr, (valuesPtr + offset)); valuesPtr += offset; blue = std::vector(valuesPtr, (valuesPtr + offset)); result = true; } } return result; } ossim_int32 ossim::TiffHandlerState::getPlanarConfig(ossim_int32 directory) const { ossimString tempStr; ossim_int32 result = 0; if (getValue(tempStr, directory, "planar_configuration")) { if (tempStr.contains("separate")) { result = PLANARCONFIG_SEPARATE; } else if(tempStr.contains("contig")) { result = PLANARCONFIG_CONTIG; } } return result; } ossim_int32 ossim::TiffHandlerState::getRasterType(ossim_int32 directory) const { ossimString tempStr; ossimPixelType result = OSSIM_PIXEL_IS_POINT; if (getValue(tempStr, directory, "raster_type")) { if (tempStr.contains("area")) { result = OSSIM_PIXEL_IS_AREA; } } return result; } ossim_int32 ossim::TiffHandlerState::getPhotoInterpretation(ossim_int32 directory) const { ossimString tempStr; ossim_int32 result = 0; if (getValue(tempStr, directory, "photo_interpretation")) { if (tempStr.contains("MINISWHITE")) { result = PHOTOMETRIC_MINISWHITE; } else if (tempStr.contains("MINISBLACK")) { result = PHOTOMETRIC_MINISBLACK; } else if (tempStr.contains("RGB")) { result = PHOTOMETRIC_RGB; } else if (tempStr.contains("PALETTE")) { result = PHOTOMETRIC_PALETTE; } else if (tempStr.contains("MASK")) { result = PHOTOMETRIC_MASK; } else if (tempStr.contains("SEPARATED")) { result = PHOTOMETRIC_SEPARATED; } else if (tempStr.contains("YCBCR")) { result = PHOTOMETRIC_YCBCR; } else if (tempStr.contains("CIELAB")) { result = PHOTOMETRIC_CIELAB; } else if (tempStr.contains("ICCLAB")) { result = PHOTOMETRIC_ICCLAB; } else if (tempStr.contains("ITULAB")) { result = PHOTOMETRIC_ITULAB; } else if (tempStr.contains("LOGL")) { result = PHOTOMETRIC_LOGL; } else if (tempStr.contains("LOGLUV")) { result = PHOTOMETRIC_LOGLUV; } } return result; } ossim_int64 ossim::TiffHandlerState::getTileLength(ossim_int32 directory) const { ossimString tempStr; ossim_int64 result = 0; if (getValue(tempStr, directory, "tile_length")) { result = tempStr.toInt64(); } return result; } ossim_int64 ossim::TiffHandlerState::getImageLength(ossim_int32 directory) const { ossimString tempStr; ossim_int64 result = 0; if (getValue(tempStr, directory, "image_length")) { result = tempStr.toInt64(); } return result; } ossim_int64 ossim::TiffHandlerState::getTileWidth(ossim_int32 directory) const { ossimString tempStr; ossim_int64 result = 0; if (getValue(tempStr, directory, "tile_width")) { result = tempStr.toInt64(); } return result; } ossim_int64 ossim::TiffHandlerState::getImageWidth(ossim_int32 directory) const { ossimString tempStr; ossim_int64 result = 0; if (getValue(tempStr, directory, "image_width")) { result = tempStr.toInt64(); } return result; } bool ossim::TiffHandlerState::getDoubleArray(std::vector& result, ossim_int32 directory, const ossimString& key)const { ossimString tempStr; if(getValue(tempStr, directory, key)) { if(!tempStr.empty()) { tempStr=tempStr.substitute(" ", ",", true); if(!toSimpleVector(result, "("+tempStr+")")) { result.clear(); } tempStr=""; } } return !result.empty(); } bool ossim::TiffHandlerState::getGeoDoubleParams(std::vector& result, ossim_int32 directory)const { return getDoubleArray(result, directory, "geo_double_params"); } bool ossim::TiffHandlerState::getGeoPixelScale(std::vector& result, ossim_int32 directory)const { return getDoubleArray(result, directory, "model_pixel_scale"); } bool ossim::TiffHandlerState::getGeoTiePoints(std::vector& result, ossim_int32 directory)const { return getDoubleArray(result, directory, "model_tie_point"); } bool ossim::TiffHandlerState::getGeoTransMatrix(std::vector& result, ossim_int32 directory)const { return getDoubleArray(result, directory, "model_transform"); } bool ossim::TiffHandlerState::getCitation(ossimString &citation, ossim_int32 directory) const { bool result = true; if (!getValue(citation, directory, "citation")) { result = false; } return result; } bool ossim::TiffHandlerState::getCopyright(ossimString ©right, ossim_int32 directory) const { bool result = true; if (!getValue(copyright, directory, "copyright")) { result = false; } return result; } bool ossim::TiffHandlerState::load(const ossimKeywordlist& kwl, const ossimString& prefix) { bool result = ossim::ImageHandlerState::load(kwl, prefix); m_tags.clear(); kwl.extractKeysThatMatch(m_tags, "^("+prefix+"dir[0-9]+)"); if(!prefix.empty()) { m_tags.stripPrefixFromAll("^("+prefix+")"); } ossimString numberOfDirectories = kwl.find(prefix, "number_of_directories"); if(!numberOfDirectories.empty()) m_tags.add("number_of_directories", numberOfDirectories, true); return result; } bool ossim::TiffHandlerState::save(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = ossim::ImageHandlerState::save(kwl, prefix); kwl.add(prefix.c_str(), m_tags); return result; } ossim-Miami-2.9.1/src/support_data/TiffStreamAdaptor.cpp000066400000000000000000000044461352751253100233020ustar00rootroot00000000000000#include tsize_t ossim::TiffIStreamAdaptor::tiffRead(thandle_t st,tdata_t buffer,tsize_t size) { TiffIStreamAdaptor* streamAdaptor = static_cast(st); tsize_t result = -1; std::shared_ptr is = streamAdaptor->getStream(); if(is) { if(!is->good()) is->clear(); is->read((char*)buffer, size); result = is->gcount(); } return result; }; tsize_t ossim::TiffIStreamAdaptor::tiffWrite(thandle_t st, tdata_t buffer,tsize_t size) { return -1; }; int ossim::TiffIStreamAdaptor::tiffClose(thandle_t st) { TiffIStreamAdaptor* streamAdaptor = static_cast(st); streamAdaptor->close(); return 0; }; toff_t ossim::TiffIStreamAdaptor::tiffSeek(thandle_t st,toff_t pos, int whence) { TiffIStreamAdaptor* streamAdaptor = static_cast(st); toff_t result = -1; std::ios_base::seekdir seekDir = std::ios::beg; std::shared_ptr is = streamAdaptor->getStream(); if(is) { // Because we are adapting, on each seek we need to clear our previous error so // we can continue on. Do not want the stream to stay in a failed state. // if(!is->good()) is->clear(); switch(whence) { case 0: // SEEK_SET { seekDir = std::ios::beg; break; } case 1: // SEEK_CUR { seekDir = std::ios::cur; break; } case 2: // SEEK_END { seekDir = std::ios::end; break; } } is->seekg(pos, seekDir); result = is->tellg(); } return result; }; toff_t ossim::TiffIStreamAdaptor::tiffSize(thandle_t st) { toff_t result = -1; TiffIStreamAdaptor* streamAdaptor = static_cast(st); std::shared_ptr is = streamAdaptor->getStream(); if (is) { if(!is->good()) is->clear(); ossim_int64 currentOffset = is->tellg(); is->seekg(0, std::ios::end); result = is->tellg(); is->seekg(currentOffset); } return result; }; int ossim::TiffIStreamAdaptor::tiffMap(thandle_t, tdata_t*, toff_t*) { return 0; }; void ossim::TiffIStreamAdaptor::tiffUnmap(thandle_t, tdata_t, toff_t) { return; }; ossim-Miami-2.9.1/src/support_data/ossimAigBounds.cpp000066400000000000000000000030671352751253100226470ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigBounds.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include #include std::ostream& operator <<(std::ostream& out, const ossimAigBounds& data) { out << "ll_x: " << data.ll_x << std::endl << "ll_y: " << data.ll_y << std::endl << "ur_x: " << data.ur_x << std::endl << "ur_y: " << data.ur_y; return out; } ossimAigBounds::ossimAigBounds() { reset(); } void ossimAigBounds::reset() { ll_x = 0.0; ll_y = 0.0; ur_x = 0.0; ur_y = 0.0; } bool ossimAigBounds::writeStream(std::ostream& out) { ossimEndian endian; double tempDouble; if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { tempDouble = ll_x; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); tempDouble = ll_y; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); tempDouble = ur_x; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); tempDouble = ur_y; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); } else { out.write((char*)(&ll_x), 8); out.write((char*)(&ll_y), 8); out.write((char*)(&ur_x), 8); out.write((char*)(&ur_y), 8); } return out.good(); } ossim-Miami-2.9.1/src/support_data/ossimAigDataFileHeader.cpp000066400000000000000000000020131352751253100241650ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigDataFileHeader.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include bool ossimAigDataFileHeader::writeStream(std::ostream& out)const { ossimEndian endian; ossim_uint32 tempInt; if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { out.write((char*)theMagicNumber, 8); out.write((char*)theZeroFill1, 16); tempInt = theFileSize; endian.swap(tempInt); out.write((char*)(&tempInt), 4); out.write((char*)theZeroFill2, 72); } else { out.write((char*)theMagicNumber, 8); out.write((char*)theZeroFill1, 16); out.write((char*)(&theFileSize), 8); out.write((char*)theZeroFill2, 72); } return out.good(); } ossim-Miami-2.9.1/src/support_data/ossimAigHeader.cpp000066400000000000000000000045231352751253100226030ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigHeader.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include bool ossimAigHeader::writeStream(std::ostream& out) { ossimEndian endian; double tempDouble; ossim_uint32 tempInt; if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { out.write((char*)theMagic, 8); out.write((char*)theUnknownData, 8); tempInt = theCellType; endian.swap(tempInt); out.write((char*)&tempInt, 4); out.write((char*)theUnknownAssortedData, 236); tempDouble = thePixelSizeX; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); tempDouble = thePixelSizeY; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); tempDouble = 0.0; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); out.write((char*)(&tempDouble), 8); tempInt = theNumberOfTilesPerRow; endian.swap(tempInt); out.write((char*)&tempInt, 4); tempInt = theNumberOfTilesPerColumn; endian.swap(tempInt); out.write((char*)&tempInt, 4); tempInt = theWidthOfTileInPixels; endian.swap(tempInt); out.write((char*)&tempInt, 4); tempInt = theUnknownValue; endian.swap(tempInt); out.write((char*)&tempInt, 4); tempInt = theHeightOfTileInPixels; endian.swap(tempInt); out.write((char*)&tempInt, 4); } else { out.write((char*)theMagic, 8); out.write((char*)theUnknownData, 8); out.write((char*)&theCellType, 4); out.write((char*)theUnknownAssortedData, 236); out.write((char*)(&thePixelSizeX), 8); out.write((char*)(&thePixelSizeY), 8); tempDouble = 0.0; out.write((char*)(&tempDouble), 8); out.write((char*)(&tempDouble), 8); out.write((char*)&theNumberOfTilesPerRow, 4); out.write((char*)&theNumberOfTilesPerColumn, 4); out.write((char*)&theWidthOfTileInPixels, 4); out.write((char*)&theUnknownValue, 4); out.write((char*)&theHeightOfTileInPixels, 4); } return true; } ossim-Miami-2.9.1/src/support_data/ossimAigIndexFileHeader.cpp000066400000000000000000000016121352751253100243670ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigIndexFileHeader.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include bool ossimAigIndexFileHeader::writeStream(std::ostream& out) { ossimEndian endian; ossim_uint32 tempInt; if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { out.write((char*)theMagicNumber, 8); out.write((char*)theZeroFill1, 16); tempInt = theFileSize; endian.swap(tempInt); out.write((char*)(&tempInt), 4); out.write((char*)theZeroFill2, 72); } else { out.write((char*)(&theFileSize), 8); } return out.good(); } ossim-Miami-2.9.1/src/support_data/ossimAigStatistics.cpp000066400000000000000000000027061352751253100235460ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // //******************************************************************* // $Id: ossimAigStatistics.cpp 9963 2006-11-28 21:11:01Z gpotts $ #include #include #include ossimAigStatistics::ossimAigStatistics() :theMin(0.0), theMax(0.0), theMean(0.0), theStandardDev(0.0) { } void ossimAigStatistics::reset() { theMin = 0.0; theMax = 0.0; theMean = 0.0; theStandardDev = 0.0; } bool ossimAigStatistics::writeStream(std::ostream& out) { ossimEndian endian; double tempDouble; if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { tempDouble = theMin; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); tempDouble = theMax; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); tempDouble = theMean; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); tempDouble = theStandardDev; endian.swap(tempDouble); out.write((char*)(&tempDouble), 8); } else { out.write((char*)(&theMin), 8); out.write((char*)(&theMax), 8); out.write((char*)(&theMean), 8); out.write((char*)(&theStandardDev), 8); } return true; } ossim-Miami-2.9.1/src/support_data/ossimAlphaSensorSupportData.cpp000066400000000000000000000501021352751253100253720ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimAlphaSensorSupportData:debug"); ossimAlphaSensorSupportData::ossimAlphaSensorSupportData() : m_isHSI(false), m_sensorType(), m_imageSize(), m_rollBias(ossim::nan()), m_pitchBias(ossim::nan()), m_headingBias(ossim::nan()), m_fov(ossim::nan()), m_slitRot(ossim::nan()), m_imgLine(), m_roll(), m_pitch(), m_heading(), m_lon(), m_lat(), m_alt(), m_scanAng(), m_rollPolyCoef(), m_pitchPolyCoef(), m_headingPolyCoef(), m_lonPolyCoef(), m_altPolyCoef(), m_scanAngPolyCoef() { reset(); } void ossimAlphaSensorSupportData::reset() { m_imageSize.makeNan(); } bool ossimAlphaSensorSupportData::readSupportFiles(const ossimFilename& hdrFile) { bool readOK = false; // Read ENVI hdr file ossimEnviHeader hdr; if ( hdr.open(hdrFile) ) { readOK= readSupportFiles( hdr ); } return readOK; } bool ossimAlphaSensorSupportData::readSupportFiles(const ossimEnviHeader& hdr) { bool readOK = readHdrFile(hdr); ossimFilename txtFile = hdr.getFile(); if ( readOK ) { // Derive associated insgps.txt file name if (m_isHSI) { // HSI: // Associated file is located in /NavData, sub-directory of current container // example: // .hdr = "/data/AH/2012-06-15_20-00-29/HSI/Scan_00002/2012-06-15_20-00-29.HSI.Scan_00002.scene.corrected.hsi.hdr" // .txt = "/data/AH/2012-06-15_20-00-29/HSI/Scan_00002/NavData/2012-06-15_20-00-29.HSI.Scan_00002.scene.insgps.txt" // txtFile.insert(hdr.getFile().find_last_of('/'), "/NavData"); // txtFile.gsub("corrected.hsi.hdr", "insgps.txt"); ossimFilename navDir = hdr.getFile().path(); navDir = navDir.dirCat("NavData"); if ( navDir.exists() ) { txtFile = navDir.dirCat( hdr.getFile().file() ); txtFile.gsub("corrected.hsi.hdr", "insgps.txt"); } else { //-- // Example header and inertial nav support(INS) data file paths: // // Header: /data/20131113/hsi/cal/001_001_hsi_cal_001.hsi.hdr // INS: /data/20131113/hsi/nav/001_001_hsi_cal_001.txt //--- // Expand header file out to absolute path: txtFile = hdr.getFile().expand(); // Substitute the "cal" directory with "nav". txtFile.gsub("cal/", "nav/"); // Substitute the "hsi.hdr" directory with "txt". txtFile.gsub("hsi.hdr", "txt"); } } else { // HRI: // Associated file is located in ../NavData, parallel to current container // There is one insgps.txt file common to multiple hdr files // example: // .hdr = "/data/AH/2012-06-15_20-00-29/HRI/HRI_2/2012-06-15_20-00-29.HRI_2.Strip_00004.corrected.hri.hdr" // .txt = "/data/AH/2012-06-15_20-00-29/HRI/NavData/2012-06-15_20-00-29.HRI.Strip_00004.insgps.txt" // Replaced: 29 July 2013 (drb) // txtFile = hdr.getFile().path(); // if ( txtFile.empty() ) // { // txtFile = txtFile.dirCat("../NavData"); // } // else // { // txtFile.replace(txtFile.find("HRI_"), 5, "NavData"); // } // txtFile = txtFile.dirCat( hdr.getFile().file() ); // txtFile.replace(txtFile.find("HRI_"), 5, "HRI"); // txtFile.gsub("corrected.hri.hdr", "insgps.txt"); // // with: ossimFilename navDir = hdr.getFile().path(); if ( navDir.empty() ) { navDir = navDir.dirCat("../NavData"); } else { std::string::size_type pos = navDir.find("HRI_"); if(pos!=std::string::npos) { navDir = navDir.replace(pos, 5, "NavData"); } } if ( navDir.exists() ) { txtFile = navDir.dirCat( hdr.getFile().file() ); std::string::size_type pos = txtFile.find("HRI_"); if(pos!=std::string::npos) { txtFile.replace(pos, 5, "HRI"); } txtFile.gsub("corrected.hri.hdr", "insgps.txt"); } else { navDir = "../nav"; txtFile = navDir.dirCat( hdr.getFile().file() ); txtFile.gsub("hri.hdr", "txt"); } } // Read .txt file readOK = readInsGpsFile(txtFile); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorSupportData::readSupportFiles DEBUG:" << "\n hdrFile = " << hdr.getFile() << "\n txtFile = " << txtFile << std::endl; } return readOK; } bool ossimAlphaSensorSupportData::readHdrFile(const ossimFilename& hdrFile) { bool result = false; ossimEnviHeader hdr; if ( hdr.open(hdrFile) ) { result = readHdrFile( hdr ); } return result; } bool ossimAlphaSensorSupportData::readHdrFile(const ossimEnviHeader& hdr) { bool result = false; while( 1 ) { // Required stuff will break from loop if not found/valid. m_sensorType = hdr.getSensorType(); if ( m_sensorType.empty() ) break; if ( m_sensorType == "Unknown" ) { // Make an assumption from file name... if ( hdr.getFile().file().contains( ossimString("HSI") ) ) { m_sensorType = "ACES_YOGI-HSI"; } else if ( hdr.getFile().file().contains( ossimString("HRI") ) ) { m_sensorType = "ACES_YOGI-HRI2"; } } if ( m_sensorType == "Unknown" ) { break; // Get out... } // Set the hsi flag: if ( m_sensorType.contains("HSI") || (hdr.getBands() > 7 ) ) // arbitrary... { m_isHSI = true; } else { m_isHSI = false; } m_imageSize.x = hdr.getSamples(); m_imageSize.y = hdr.getLines(); if ( !m_imageSize.x || !m_imageSize.y ) break; ossimString value; hdr.getValue("roll bias", value); if ( value.size() ) { m_rollBias = ossimString::toDouble(value); } else { break; } hdr.getValue("pitch bias", value); if ( value.size() ) { m_pitchBias = ossimString::toDouble(value); } else { break; } hdr.getValue("heading bias", value); if ( value.size() ) { m_headingBias = ossimString::toDouble(value); } else { break; } hdr.getValue("fpa fov deg", value); if ( value.size() ) { m_fov = ossimString::toDouble(value); } else { break; } hdr.getValue("slit rotation deg", value); if ( value.size() ) { m_slitRot = ossimString::toDouble(value); } else { // Removed requirement. Missing in some support data and always 0 when present. if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Missing: \"slit rotation deg\"\n"; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorSupportData::readHdrFile DEBUG:" << "\n getSensorType = " << m_sensorType << "\n getSamples = " << m_imageSize.x << "\n getLines = " << m_imageSize.y << "\n roll bias = " << m_rollBias << "\n pitch bias = " << m_pitchBias << "\n heading bias = " << m_headingBias << "\n fpa fov deg = " << m_fov << "\n slit rotation deg = " << m_slitRot << "\n"; } // Last two lines of while forever. If we get here, set status true and break out. result = true; break; } return result; } // End: bool ossimAlphaSensorSupportData::readHdrFile(const ossimEnviHeader& ) bool ossimAlphaSensorSupportData::readInsGpsFile(const ossimFilename& file) { bool result = true; static const char M[] = "ossimAlphaSensorSupportData::readInsGpsFile"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered:\n" << "file: " << file << "\n"; } std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream( file, std::ios_base::in); if ( in && in->good() ) { ossim_float64 inum; ossim_float64 roll; ossim_float64 pitch; ossim_float64 heading; ossim_float64 lon; ossim_float64 lat; ossim_float64 alt; ossim_float64 scanAng; int res; int frm; const ossim_float64 BOGUS = -99999.0; // To detect read error/missing value. ossim_float64 timeCode = BOGUS; std::vector< ossim_uint32 > lines; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimAlphaSensorSupportData::readInsGpsFile DEBUG:" << std::endl; ossimNotify(ossimNotifyLevel_DEBUG)<> s; if ( s.size() ) { ++fields; s.clear(); } } if ( fields == 11 ) { // First line is valid. in->seekg( 0, std::ios_base::beg ); } } while( !in->eof() ) { // To detect read error/missing value. Check eof was missing last line. timeCode = BOGUS; *in >> inum >> roll >> pitch >> heading >> lon >> lat >> alt >> scanAng >> res >> frm >> timeCode; // if(!in.eof()) if ( timeCode != BOGUS ) { lines.push_back(inum); m_roll.push_back(roll); m_pitch.push_back(pitch); m_heading.push_back(heading); m_lon.push_back(lon); m_lat.push_back(lat); m_alt.push_back(alt); m_scanAng.push_back(scanAng); } } // Make sure we have a value per line if( (lines.size() < m_imageSize.y) || (lines.size() < 10) ) { return false; } // Load independent variable (line number, referenced to first line) vector< ossimPolynom< ossim_float64 , 1 >::VAR_TUPLE >::iterator pit; m_imgLine.resize(lines.size()); int j; for (pit=m_imgLine.begin(), j=0; pit!=m_imgLine.end(); ++pit,++j) { pit->push_back(lines[j]-lines[0]); } // Dependent variable solutions follow... double rms=0.0; // Exponent sets std::vector< ossimPolynom::EXPT_SET > expSet; expSet.resize(MAX_TERMS); ossimPolynom::EXP_TUPLE et(1); for (int numExp=1; numExp<=MAX_TERMS; ++numExp) { for(int o=0; o saPoly; // orientation angles (roll, pitch, heading) ossimPolynom rPoly; ossimPolynom pPoly; ossimPolynom hPoly; // position (longitude, latitude, altitude) ossimPolynom lonPoly; ossimPolynom latPoly; ossimPolynom altPoly; // Solve for polynomial coefficients if (m_isHSI) { result = saPoly.SLSfit(expSet[SCAN_ANGLE_DEG], m_imgLine, m_scanAng, &rms); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\n SA poly deg, rms error = " << SCAN_ANGLE_DEG << ", " << ossim::radiansToDegrees(rms) << " deg\n"; } } if (result) { result = rPoly.SLSfit(expSet[ROLL_DEG], m_imgLine, m_roll, &rms); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\n R poly deg, rms error = " << ROLL_DEG << ", " << ossim::radiansToDegrees(rms) << " deg\n"; } if (result) { result = pPoly.SLSfit(expSet[PITCH_DEG], m_imgLine, m_pitch, &rms); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\n P poly deg, rms error = " << PITCH_DEG << ", " << ossim::radiansToDegrees(rms) << " deg\n"; } if (result) { result = hPoly.SLSfit(expSet[HEADING_DEG], m_imgLine, m_heading, &rms); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\n H poly deg, rms error = " << HEADING_DEG << ", " << ossim::radiansToDegrees(rms) << " deg\n"; } if (result) { result = lonPoly.SLSfit(expSet[LON_DEG], m_imgLine, m_lon, &rms); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\n Lon poly deg, rms error = " << LON_DEG << ", " << ossim::radiansToDegrees(rms) << " deg\n"; } if (result) { result = latPoly.SLSfit(expSet[LAT_DEG], m_imgLine, m_lat, &rms); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\n Lat poly deg, rms error = " << LAT_DEG << ", " << ossim::radiansToDegrees(rms) << " deg\n"; } if (result) { result = altPoly.SLSfit(expSet[ALT_DEG], m_imgLine, m_alt, &rms); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\n Alt poly deg, rms error = " << ALT_DEG << ", " << rms << " mtr" << std::endl; } } } } } } } if (result) { // Save coefficients ossimPolynom::MONOM_MAP::const_iterator it; for (it = rPoly.getMonoms().begin(); it != rPoly.getMonoms().end() ; ++it ) { m_rollPolyCoef.push_back(it->second); } for (it = pPoly.getMonoms().begin(); it != pPoly.getMonoms().end() ; ++it ) { m_pitchPolyCoef.push_back(it->second); } for (it = hPoly.getMonoms().begin(); it != hPoly.getMonoms().end() ; ++it ) { m_headingPolyCoef.push_back(it->second); } for (it = lonPoly.getMonoms().begin(); it != lonPoly.getMonoms().end() ; ++it ) { m_lonPolyCoef.push_back(it->second); } for (it = latPoly.getMonoms().begin(); it != latPoly.getMonoms().end() ; ++it ) { m_latPolyCoef.push_back(it->second); } for (it = altPoly.getMonoms().begin(); it != altPoly.getMonoms().end() ; ++it ) { m_altPolyCoef.push_back(it->second); } if (m_isHSI) { for (it = saPoly.getMonoms().begin(); it != saPoly.getMonoms().end() ; ++it ) { m_scanAngPolyCoef.push_back(it->second); } } else { m_scanAngPolyCoef.push_back(0.0); } } if (traceDebug()) { if (result) { vector inp(1); inp[0] = 510.0; ossimNotify(ossimNotifyLevel_DEBUG) << "\n Test eval line number = " << inp[0] << endl; if (m_isHSI) { saPoly.print(ossimNotify(ossimNotifyLevel_DEBUG)); ossim_float64 sa = saPoly.eval(inp); ossimNotify(ossimNotifyLevel_DEBUG)<<"\n sa="<& ossimAlphaSensorSupportData::getRollPoly()const { return m_rollPolyCoef; } const std::vector< ossim_float64 >& ossimAlphaSensorSupportData::getPitchPoly()const { return m_pitchPolyCoef; } const std::vector< ossim_float64 >& ossimAlphaSensorSupportData::getHeadingPoly()const { return m_headingPolyCoef; } const std::vector< ossim_float64 >& ossimAlphaSensorSupportData::getLonPoly()const { return m_lonPolyCoef; } const std::vector< ossim_float64 >& ossimAlphaSensorSupportData::getLatPoly()const { return m_latPolyCoef; } const std::vector< ossim_float64 >& ossimAlphaSensorSupportData::getAltPoly()const { return m_altPolyCoef; } const std::vector< ossim_float64 >& ossimAlphaSensorSupportData::getScanPoly()const { return m_scanAngPolyCoef; } // Hidden from use... ossimAlphaSensorSupportData::ossimAlphaSensorSupportData(const ossimAlphaSensorSupportData& /* src */) { } ossimAlphaSensorSupportData& ossimAlphaSensorSupportData::operator=( const ossimAlphaSensorSupportData& /* src */) { return *this; } ossim-Miami-2.9.1/src/support_data/ossimApplanixEOFile.cpp000066400000000000000000000433001352751253100235660ustar00rootroot00000000000000//******************************************************************* // // MIT // // Author: Garrett Potts // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimApplanixEOFile:debug"); static std::istream& applanix_skipws(ossim::istream& in) { int c = in.peek(); while(((c == ' ') || (c == '\r') || (c == '\t') || (c == '\n'))&& (in.good())) { in.ignore(1); c = in.peek(); } return in; } std::ostream& operator <<(std::ostream& out, const ossimApplanixEORecord& src) { if(src.theField.size()) { std::copy(src.theField.begin(), src.theField.end(), std::ostream_iterator(out, " ")); } return out; } std::ostream& operator <<(std::ostream& out, const ossimApplanixEOFile& src) { ossim_uint32 idx = 0; out << src.theHeader << std::endl << std::endl; if(src.theRecordFormat.size()) { std::copy(src.theRecordFormat.begin(), src.theRecordFormat.end()-1, std::ostream_iterator(out, ", ")); out << *(src.theRecordFormat.end()-1); out << std::endl; } out << "Kappa Cardinal Rotation = " << src.theKappaCardinal << std::endl; out << "Bore Sight tx = " << src.theBoreSightTx << std::endl << "Bore Sight ty = " << src.theBoreSightTy << std::endl << "Bore Sight tz = " << src.theBoreSightTz << std::endl; out << "Lever arm lx = " << src.theLeverArmLx << std::endl << "Lever arm ly = " << src.theLeverArmLy << std::endl << "Lever arm lz = " << src.theLeverArmLz << std::endl; out << "Shift Value X = " << src.theShiftValuesX << std::endl << "Shift Value Y = " << src.theShiftValuesY << std::endl << "Shift Value Z = " << src.theShiftValuesZ << std::endl; out << "Mapping Frame Datum = " << src.theMappingFrameDatum << std::endl << "Mapping Frame Projection = " << src.theMappingFrameProjection << std::endl << "Central Meridian = " << src.theCentralMeridian << std::endl << "Origin of Latitude = " << src.theOriginLatitude << std::endl << "Grid Scale Factor = " << src.theGridScaleFactor << std::endl << "False easting = " << src.theFalseEasting << std::endl << "False northing = " << src.theFalseNorthing << std::endl; out << "theUtmZone = " << src.theUtmZone << std::endl; out << "theUtmHemisphere = " << src.theUtmHemisphere << std::endl; if(src.theApplanixRecordList.size()) { out << std::endl; for(idx = 0; idx < src.theApplanixRecordList.size()-1; ++idx) { out << *(src.theApplanixRecordList[idx]) << std::endl; } out << *(src.theApplanixRecordList[idx]); } return out; } ossimApplanixEOFile::ossimApplanixEOFile() { theMinLat = ossim::nan(); theMinLon = ossim::nan(); theMaxLat = ossim::nan(); theMaxLon = ossim::nan(); } bool ossimApplanixEOFile::parseFile(const ossimFilename& file) { bool result = false; std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream(file, std::ios_base::in); if ( in ) { result = parseStream( *in ); } return result; } bool ossimApplanixEOFile::isEOFile(const ossimFilename& file)const { bool result = false; std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream( file, std::ios_base::in); if ( in ) { result = isEOFile( *in ); } return result; } bool ossimApplanixEOFile::isEOFile(std::istream& in)const { ossimString header; return parseHeader(in, header); } bool ossimApplanixEOFile::parseStream(std::istream& in) { theRecordIdMap.clear(); ossimString line; int c = '\0'; if(!parseHeader(in, theHeader)) { return false; } // now parse parameters in>>applanix_skipws; line = ""; while(in.good()&& !line.contains("RECORD FORMAT")) { std::getline(in, line.string()); line = line.upcase(); line = line.substitute("\r","\n", true); if(line.contains("KAPPA CARDINAL")) { theKappaCardinal = line; theKappaCardinal = theKappaCardinal.substitute("KAPPA CARDINAL ROTATION",""); theKappaCardinal = theKappaCardinal.substitute(":",""); theKappaCardinal = theKappaCardinal.substitute("\n",""); } else if(line.contains("LEVER ARM")) { ossimKeywordlist kwl('='); line = line.substitute("LEVER ARM VALUES:", ""); line = line.substitute(",", "\n", true); std::istringstream in(line); kwl.parseStream(in); theLeverArmLx = kwl.find("LX"); theLeverArmLy = kwl.find("LY"); theLeverArmLz = kwl.find("LZ"); } else if(line.contains("BORESIGHT VALUES")) { ossimKeywordlist kwl('='); line = line.substitute("BORESIGHT VALUES:", ""); line = line.substitute(",", "\n", true); std::istringstream in(line); kwl.parseStream(in); theBoreSightTx = kwl.find("TX"); theBoreSightTy = kwl.find("TY"); theBoreSightTz = kwl.find("TZ"); } else if(line.contains("SHIFT VALUES:")) { ossimKeywordlist kwl('='); line = line.substitute("SHIFT VALUES:",""); line = line.substitute(",", "\n", true); std::istringstream in(line); kwl.parseStream(in); theShiftValuesX = kwl.find("X"); theShiftValuesY = kwl.find("Y"); theShiftValuesZ = kwl.find("Z"); } else if(line.contains("GRID:")) { ossimKeywordlist kwl(':'); line = line.substitute(";", "\n", true); std::istringstream in(line); kwl.parseStream(in); theUtmZone = kwl.find("ZONE"); if(theUtmZone.contains("NORTH")) { theUtmHemisphere = "North"; } else { theUtmHemisphere = "South"; } theUtmZone = theUtmZone.replaceAllThatMatch("UTM|\\(.*\\)|NORTH|SOUTH",""); theUtmZone = theUtmZone.trim(); } else if(line.contains("FRAME DATUM")) { ossimKeywordlist kwl(':'); line = line.substitute(";", "\n", true); std::istringstream in(line); kwl.parseStream(in); theMappingFrameDatum = kwl.find("MAPPING FRAME DATUM"); theMappingFrameProjection = kwl.find("MAPPING FRAME PROJECTION"); theMappingFrameDatum = theMappingFrameDatum.trim(); theMappingFrameProjection = theMappingFrameProjection.trim(); } else if(line.contains("POSPROC SBET")) { theSbetField = line.after(":"); theSbetField = theSbetField.trim(); } else if(line.contains("CENTRAL MERIDIAN")) { theCentralMeridian = line; theCentralMeridian = theCentralMeridian.substitute("CENTRAL MERIDIAN",""); theCentralMeridian = theCentralMeridian.substitute("=",""); theCentralMeridian = theCentralMeridian.substitute("DEG",""); theCentralMeridian = theCentralMeridian.substitute(";",""); } else if(line.contains("LATITUDE OF THE GRID ORIGIN")) { ossimKeywordlist kwl('='); line = line.substitute(";", "\n", true); std::istringstream in(line); kwl.parseStream(in); theOriginLatitude = kwl.find("LATITUDE OF THE GRID ORIGIN"); theGridScaleFactor = kwl.find("GRID SCALE FACTOR"); } else if(line.contains("FALSE EASTING")) { ossimKeywordlist kwl('='); line = line.substitute(";", "\n", true); std::istringstream in(line); kwl.parseStream(in); theFalseEasting = kwl.find("FALSE EASTING"); theFalseNorthing = kwl.find("FALSE NORTHING"); } } in>>applanix_skipws; c = in.get(); std::vector fieldArray; ossimString field; while(in.good()&& (c!='\n')&& (c!='\r')) { field = ""; while((c != ',')&& (c != '\n')&& (c != '\r')) { field += (char)c; c = in.get(); } if((c!='\n')&& (c!='\r')) { c = in.get(); } field = field.trim(); if(field != "") { theRecordFormat.push_back(field); } } in>>applanix_skipws; if(in.peek() == '(') { std::getline(in, line.string()); } in>>applanix_skipws; ossimRefPtr record = new ossimApplanixEORecord((ossim_uint32)theRecordFormat.size()); ossim_int32 latIdx = getFieldIdx("LAT"); ossim_int32 lonIdx = getFieldIdx("LONG");; bool hasLatLon = (latIdx >=0)&&(lonIdx >= 0); if(hasLatLon) { theMinLat = 90.0; theMaxLat = -90.0; theMinLon = 180.0; theMaxLon = -180.0; } else { theMinLat = ossim::nan(); theMaxLat = ossim::nan(); theMinLon = ossim::nan(); theMaxLon = ossim::nan(); } while(in.good()&&theRecordFormat.size()) { std::getline(in, line.string()); line = line.trim(); if(line != "") { std::istringstream inStr(line); ossim_uint32 idx; ossimString value; for(idx = 0; idx < theRecordFormat.size(); ++idx) { inStr >> (*record)[idx]; } if(hasLatLon) { double lat = (*record)[latIdx].toDouble(); double lon = (*record)[lonIdx].toDouble(); if(lattheMaxLat) theMaxLat = lat; if(lontheMaxLon) theMaxLon = lon; } theApplanixRecordList.push_back(new ossimApplanixEORecord(*record)); } } indexRecordIds(); if(traceDebug()) { if(hasLatLon) { ossimNotify(ossimNotifyLevel_DEBUG) << "min lat: " << theMinLat << std::endl << "min lon: " << theMinLon << std::endl << "max lat: " << theMaxLat << std::endl << "max lon: " << theMaxLon << std::endl; } } return true; } bool ossimApplanixEOFile::parseHeader(const ossimFilename& file, ossimString& header)const { bool result = false; std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream( file, std::ios_base::in); if ( in ) { result = parseHeader( *in, header); } return result; } bool ossimApplanixEOFile::parseHeader(std::istream& in, ossimString& header)const { header = ""; in >> applanix_skipws; int c = in.peek(); if((c!='*')|| (!in.good())) { return false; } ossimString line; std::getline(in, line.string()); line = line .substitute("\r", "\n"); if(!line.contains("************")) { return false; } header = line; header += "\n"; in>>applanix_skipws; std::getline(in, line.string()); line = line .substitute("\r", "\n"); while((in.good())&& (!line.contains("***********"))) { header += line; header += "\n"; std::getline(in, line.string()); line = line .substitute("\r", "\n"); } header += line; header += "\n"; if(!header.contains("Applanix")) { return false; } return true; } void ossimApplanixEOFile::indexRecordIds() { ossimString id; ossim_uint32 idx; ossim_int32 idIdx = getFieldIdxLike("ID"); ossim_uint32 size = (ossim_uint32)theApplanixRecordList.size(); theRecordIdMap.clear(); if(idIdx < 0) return; for(idx = 0; idx < size; ++idx) { id = (*theApplanixRecordList[idx])[idIdx]; theRecordIdMap.insert(std::make_pair(id, theApplanixRecordList[idx])); } } ossim_int32 ossimApplanixEOFile::getFieldIdxLike(const ossimString& searchKey)const { ossimString key = searchKey; ossim_uint32 idx = 0; key = key.upcase(); for(idx = 0; idx < theRecordFormat.size(); ++idx) { if(ossimString::upcase(theRecordFormat[idx]).contains(key)) { return (int)idx; } } return -1; } ossim_int32 ossimApplanixEOFile::getFieldIdx(const ossimString& searchKey)const { ossimString key = searchKey; ossim_uint32 idx = 0; key = key.upcase(); for(idx = 0; idx < theRecordFormat.size(); ++idx) { if(ossimString::upcase(theRecordFormat[idx]) == key) { return (int)idx; } } return -1; } const ossimRefPtr ossimApplanixEOFile::getRecordGivenId(const ossimString& id)const { if(theRecordIdMap.size()) { std::map, ossimStringLtstr >::const_iterator iter = theRecordIdMap.find(id); if(iter!=theRecordIdMap.end()) { return iter->second; } } else { ossim_uint32 idx; ossim_int32 idxId = getFieldIdx("ID"); if(idxId >= 0) { for(idx = 0; idx < theApplanixRecordList.size(); ++idx) { if((*theApplanixRecordList[idx])[idxId] == id) { return theApplanixRecordList[idx]; } } } } return 0; } ossim_uint32 ossimApplanixEOFile::getNumberOfRecords()const { return (ossim_uint32)theApplanixRecordList.size(); } const ossimRefPtr ossimApplanixEOFile::getRecord(ossim_uint32 idx)const { if(idx < theApplanixRecordList.size()) { return theApplanixRecordList[idx]; } return 0; } bool ossimApplanixEOFile::isHeightAboveMSL()const { return (getFieldIdx("ORTHOMETRIC HEIGHT") >= 0); } bool ossimApplanixEOFile::isEcefModel()const { ossim_int32 xIdx = getFieldIdx("X"); ossim_int32 yIdx = getFieldIdx("Y"); ossim_int32 zIdx = getFieldIdx("Z"); ossim_int32 rollIdx = getFieldIdx("ROLL"); ossim_int32 pitchIdx = getFieldIdx("PITCH"); ossim_int32 headingIdx = getFieldIdx("HEADING"); return ((xIdx >=0)&& (yIdx >=0)&& (zIdx >=0)&& (rollIdx>=0)&& (pitchIdx>=0)&& (headingIdx>=0)); } bool ossimApplanixEOFile::isUtmFrame()const { return ((getFieldIdxLike("EASTING")>=0)&& (getFieldIdxLike("NORTHING") >=0)&& (getFieldIdxLike("HEIGHT") >= 0)&& (getFieldIdxLike("OMEGA") >=0)&& (getFieldIdxLike("PHI") >=0)&& (getFieldIdxLike("KAPPA") >=0)); return (getUtmZone() >= 0.0); } ossim_int32 ossimApplanixEOFile::getUtmZone()const { return theUtmZone.toInt32(); } ossimString ossimApplanixEOFile::getUtmHemisphere()const { return theUtmHemisphere; } ossimString ossimApplanixEOFile::getSbetField()const { return theSbetField; } double ossimApplanixEOFile::getBoreSightTx()const { return theBoreSightTx.toDouble(); } double ossimApplanixEOFile::getBoreSightTy()const { return theBoreSightTy.toDouble(); } double ossimApplanixEOFile::getBoreSightTz()const { return theBoreSightTz.toDouble(); } double ossimApplanixEOFile::getLeverArmLx()const { return theLeverArmLx.toDouble(); } double ossimApplanixEOFile::getLeverArmLy()const { return theLeverArmLy.toDouble(); } double ossimApplanixEOFile::getLeverArmLz()const { return theLeverArmLz.toDouble(); } double ossimApplanixEOFile::getKardinalKappa()const { return theKappaCardinal.toDouble(); } double ossimApplanixEOFile::getShiftValuesX()const { return theShiftValuesX.toDouble(); } double ossimApplanixEOFile::getShiftValuesY()const { return theShiftValuesY.toDouble(); } double ossimApplanixEOFile::getShiftValuesZ()const { return theShiftValuesZ.toDouble(); } ossimString ossimApplanixEOFile::getMappingFrameDatum()const { return theMappingFrameDatum; } ossimString ossimApplanixEOFile::getMappingFrameProjection()const { return theMappingFrameProjection; } double ossimApplanixEOFile::getMappingFrameCentralMeridian()const { return theCentralMeridian.toDouble(); } double ossimApplanixEOFile::getMappingFrameOriginLatitude()const { return theOriginLatitude.toDouble(); } double ossimApplanixEOFile::getMappingFrameGridScaleFactor()const { return theGridScaleFactor.toDouble(); } double ossimApplanixEOFile::getMappingFrameFalseEasting()const { return theFalseEasting.toDouble(); } double ossimApplanixEOFile::getMappingFrameFalseNorthing()const { return theFalseNorthing.toDouble(); } ossimString ossimApplanixEOFile::convertToOssimDatumCode(const ossimString& datum)const { ossimString result = "WGE"; ossimString temp = datum; temp = temp.upcase(); if(temp == "NAD83") { result = "NAR-C"; } return result; } ossim-Miami-2.9.1/src/support_data/ossimAuxFileHandler.cpp000066400000000000000000000602311352751253100236230ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: SPADAC Inc // Adaptd from the GDAL package hfadataset.cpp // Description: This class provides some simple utilities for aux file. // //******************************************************************** // $Id: ossimAuxFileHandler.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $ #include #include #include #include #include #include using namespace std; void ossimAuxStandardFile( int nBytes, void * pData ) { int i; char *entryData = (char *) pData; for( i = nBytes/2-1; i >= 0; i-- ) { ossim_uint8 byTemp; byTemp = entryData[i]; entryData[i] = entryData[nBytes-i-1]; entryData[nBytes-i-1] = byTemp; } } int ossimAuxGetDataTypeBits( int nDataType ) { switch( nDataType ) { case EPT_u1: return 1; case EPT_u2: return 2; case EPT_u4: return 4; case EPT_u8: case EPT_s8: return 8; case EPT_u16: case EPT_s16: return 16; case EPT_u32: case EPT_s32: case EPT_f32: return 32; case EPT_f64: case EPT_c64: return 64; case EPT_c128: return 128; } return 0; } static char * ossimAuxGetDictionary(ossimAuxInfo* hHFA) { int nDictMax = 100; char *pszDictionary = (char *)malloc(nDictMax); int nDictSize = 0; fseek(hHFA->fp, hHFA->nDictionaryPos, SEEK_SET ); while( true ) { if( nDictSize >= nDictMax-1 ) { nDictMax = nDictSize * 2 + 100; pszDictionary = (char *) realloc(pszDictionary, nDictMax ); } if( fread( pszDictionary + nDictSize, 1, 1, hHFA->fp ) < 1 || pszDictionary[nDictSize] == '\0' || (nDictSize > 2 && pszDictionary[nDictSize-2] == ',' && pszDictionary[nDictSize-1] == '.') ) break; nDictSize++; } pszDictionary[nDictSize] = '\0'; return( pszDictionary ); } ossimAuxFileHandler::ossimAuxFileHandler() { m_auxInfo = NULL; } ossimAuxFileHandler::~ossimAuxFileHandler() { if (m_auxInfo != NULL) { delete m_auxInfo; m_auxInfo = 0; } } bool ossimAuxFileHandler::isAuxFile(const ossimFilename& file) { bool result = false; if ( file.exists() ) { ossimString ext = file.ext(); ext.downcase(); if (ext == "aux") { result = true; } else { result = false; } } return result; } bool ossimAuxFileHandler::open(const ossimFilename& file) { FILE *fp = fopen(file.c_str(), "r"); char header[16]; ossim_uint32 nHeaderPos; if( fp == NULL ) { return false; } fread( header, 16, 1, fp); char* tmpHeader = const_cast(header); if(strcmp(tmpHeader,"EHFA_HEADER_TAG") != 0) { fclose( fp ); return false; } //Create the ossimAuxInfo m_auxInfo = new ossimAuxInfo(); m_auxInfo->fp = fp; //Where is the header? fread( &nHeaderPos, sizeof(ossim_int32), 1, fp ); fseek( fp, nHeaderPos, SEEK_SET ); fread( &(m_auxInfo->nVersion), sizeof(ossim_int32), 1, fp ); fread( header, 4, 1, fp ); /* skip freeList */ fread( &(m_auxInfo->nRootPos), sizeof(ossim_int32), 1, fp ); fread( &(m_auxInfo->nEntryHeaderLength), sizeof(ossim_int16), 1, fp ); fread( &(m_auxInfo->nDictionaryPos), sizeof(ossim_int32), 1, fp ); fseek( fp, 0, SEEK_END ); m_auxInfo->nEndOfFile = (ossim_int32) ftell(fp); m_auxInfo->m_Root = new ossimAuxEntry( m_auxInfo, m_auxInfo->nRootPos, NULL, NULL ); m_auxInfo->dictionaryData = ossimAuxGetDictionary(m_auxInfo); m_auxInfo->m_Dictionary = new ossimAuxDictionary( m_auxInfo->dictionaryData ); ossimAuxEntry *node = m_auxInfo->m_Root->getChild(); while( node != NULL ) { std::string typeStr = node->getType(); size_t typeLen = typeStr.length(); std::string str = "Eimg_Layer"; size_t strLen = str.length(); if( typeLen == strLen) { ossimAuxEntry* projEntry = node->getNamedChild("Map_Info"); if( projEntry == NULL ) { ossimAuxEntry* childEntry; for( childEntry = node->getChild(); childEntry != NULL && projEntry == NULL; childEntry = childEntry->getNext() ) { if (ossimString(childEntry->getType()) == "Eprj_MapInfo") projEntry = childEntry; } } const char* proj = NULL; const char* units = NULL; if (projEntry) { proj = projEntry->getStringField("proName"); units = projEntry->getStringField("units"); } if (proj != NULL) { m_projName = ossimString(proj); } if (units != NULL) { m_unitsType = ossimString(proj); } ossimAuxEntry* datumEntry = node->getNamedChild( "Projection.Datum" ); const char* datumStr = NULL; if (datumEntry) { datumStr = datumEntry->getStringField("datumname"); } if (datumStr != NULL) { m_datumName = ossimString(datumStr);; } break; } node = node->getNext(); } fclose(fp); return true; } /************************************************************************/ /* ossimAuxInfo() */ /************************************************************************/ ossimAuxInfo::ossimAuxInfo() { fp = NULL; m_Root = NULL; m_Dictionary = NULL; dictionaryData = NULL; } ossimAuxInfo::~ossimAuxInfo() { if (m_Root != NULL) { delete m_Root; m_Root = 0; } if (m_Dictionary != NULL) { delete m_Dictionary; m_Dictionary = 0; } if (dictionaryData != NULL) { delete[] dictionaryData; dictionaryData = 0; } } /************************************************************************/ /* ossimAuxEntry() */ /************************************************************************/ ossimAuxEntry::ossimAuxEntry(ossimAuxInfo * auxInfoIn, ossim_uint32 nPos, ossimAuxEntry * parentIn, ossimAuxEntry * prevIn) { m_auxInfo = auxInfoIn; nFilePos = nPos; m_Parent = parentIn; m_Prev = prevIn; m_Next = NULL; m_Child = NULL; entryData = NULL; nDataPos = nDataSize = 0; nNextPos = nChildPos = 0; entryNodeName[0] = entryType[0] = '\0'; ossim_int32 anEntryNums[6]; if( fseek( m_auxInfo->fp, nFilePos, SEEK_SET ) == -1 || fread( anEntryNums, sizeof(ossim_uint32), 6, m_auxInfo->fp ) < 1 ) { return; } nNextPos = anEntryNums[0]; nChildPos = anEntryNums[3]; nDataPos = anEntryNums[4]; nDataSize = anEntryNums[5]; if( fread( entryNodeName, 1, 64, m_auxInfo->fp ) < 1 || fread( entryType, 1, 32, m_auxInfo->fp ) < 1 ) { return; } } ossimAuxEntry::~ossimAuxEntry() { if( entryData != NULL ) { delete entryData; entryData = 0; } if( m_Next != NULL ) { delete m_Next; m_Next = 0; } if( m_Child != NULL ) { delete m_Child; m_Child = 0; } } void ossimAuxEntry::setName( const char *nodeName ) { memset( entryNodeName, '\0', 64 ); strncpy( entryNodeName, nodeName, 64 ); } ossimAuxEntry *ossimAuxEntry::getChild() { if( m_Child == NULL && nChildPos != 0 ) { m_Child = new ossimAuxEntry( m_auxInfo, nChildPos, this, NULL ); } return( m_Child ); } ossimAuxEntry* ossimAuxEntry::getNext() { if( m_Next == NULL && nNextPos != 0 ) { // Check if we have a loop on the next node in this sibling chain. ossimAuxEntry *past; for( past = this; past != NULL && past->nFilePos != nNextPos; past = past->m_Prev ) {} if( past != NULL ) { nNextPos = 0; return NULL; } m_Next = new ossimAuxEntry(m_auxInfo, nNextPos, m_Parent, this ); } return( m_Next ); } void ossimAuxEntry::loadData() { if( entryData != NULL || nDataSize == 0 ) { return; } entryData = (char*) malloc(nDataSize); if (entryData == NULL) { return; } if(fseek(m_auxInfo->fp, nDataPos, SEEK_SET ) < 0 ) { return; } if( fread( entryData, 1, nDataSize, m_auxInfo->fp ) < 1 ) { return; } m_Type = m_auxInfo->m_Dictionary->findType( entryType ); if(m_Type == NULL) { return; } } ossimAuxEntry* ossimAuxEntry::getNamedChild( const char* name ) { int nNameLen; ossimAuxEntry *entry; for( nNameLen = 0; name[nNameLen] != '.' && name[nNameLen] != '\0' && name[nNameLen] != ':'; nNameLen++ ) {} for( entry = getChild(); entry != NULL; entry = entry->getNext() ) { std::string tmpEntryName = const_cast(entry->getName()); tmpEntryName = tmpEntryName.substr(0, nNameLen); std::string tmpName = const_cast(name); tmpName = tmpName.substr(0, nNameLen); if( strcmp(tmpEntryName.c_str(),tmpName.c_str()) == 0 && (int) strlen(entry->getName()) == nNameLen ) { if( name[nNameLen] == '.' ) { ossimAuxEntry *result; result = entry->getNamedChild( name+nNameLen+1 ); if( result != NULL ) return result; } else return entry; } } return NULL; } int ossimAuxEntry::getFieldValue( const char * auxFieldPath, char chReqType, void *reqReturn ) { ossimAuxEntry *entry = this; if( strchr(auxFieldPath,':') != NULL ) { entry = getNamedChild( auxFieldPath ); if( entry == NULL ) return false; auxFieldPath = strchr(auxFieldPath,':') + 1; } loadData(); if( entryData == NULL ) { return false; } if( m_Type == NULL ) { return false; } return (m_Type->extractInstValue( auxFieldPath, entryData, nDataPos, nDataSize, chReqType, reqReturn )); } ossim_int16 ossimAuxEntry::getIntField(const char* auxFieldPath) { ossim_int16 nIntValue; if( !getFieldValue( auxFieldPath, 'i', &nIntValue ) ) { return 0; } else { return nIntValue; } } const char* ossimAuxEntry::getStringField( const char* auxFieldPath) { char *result = NULL; if( !getFieldValue( auxFieldPath, 's', &result ) ) { return NULL; } else { return result; } } /************************************************************************/ /* ossimAuxField() */ /************************************************************************/ ossimAuxField::ossimAuxField() { nBytes = 0; nItemCount = 0; chPointer = '\0'; chItemType = '\0'; itemObjectType = NULL; m_auxItemObjectType = NULL; enumNames = NULL; fieldName = NULL; } ossimAuxField::~ossimAuxField() { if (itemObjectType != NULL) { delete[] itemObjectType; itemObjectType = 0; } if (enumNames != NULL) { delete[] enumNames; enumNames = 0; } if (fieldName != NULL) { delete[] fieldName; fieldName = 0; } } int ossimAuxField::extractInstValue( const char* /* auxField */, int nIndexValue, char* entryData, ossim_uint32 nDataOffset, int nDataSize, char chReqType, void *reqReturn ) { int nInstItemCount = getInstCount( entryData, nDataSize ); if( nIndexValue < 0 || nIndexValue >= nInstItemCount ) { if( chItemType == 'b' && nIndexValue >= -3 && nIndexValue < 0 ) /* ok - special index values */; else return false; } if( chPointer != '\0' ) { ossim_uint32 nOffset; memcpy( &nOffset, entryData+4, 4 ); entryData += 8; nDataOffset += 8; nDataSize -= 8; } if( (chItemType == 'c' || chItemType == 'C') && chReqType == 's' ) { *((char **)reqReturn) = entryData; return( entryData != NULL ); } return false; } int ossimAuxField::getInstCount( char * entryData, int nDataSize ) { if( chPointer == '\0' ) return nItemCount; else if( chItemType == 'b' ) { ossim_int32 nRows, nColumns; if( nDataSize < 20 ) return 0; memcpy( &nRows, entryData+8, 4 ); ossimAuxStandardFile( 4, &nRows ); memcpy( &nColumns, entryData+12, 4 ); ossimAuxStandardFile( 4, &nColumns ); return nRows * nColumns; } else { ossim_int32 nCount; if( nDataSize < 4 ) return 0; memcpy( &nCount, entryData, 4 ); ossimAuxStandardFile( 4, &nCount ); return nCount; } } void ossimAuxField::completeDefn( ossimAuxDictionary * auxDict ) { if( itemObjectType != NULL ) { m_auxItemObjectType = auxDict->findType( itemObjectType ); } if( chPointer == 'p' ) { nBytes = -1; /* we can't know the instance size */ } else if( m_auxItemObjectType != NULL ) { m_auxItemObjectType->completeDefn( auxDict ); if( m_auxItemObjectType->nBytes == -1 ) { nBytes = -1; } else { nBytes = m_auxItemObjectType->nBytes * nItemCount; } if( chPointer == '*' && nBytes != -1 ) { nBytes += 8; /* count, and offset */ } } else { nBytes = auxDict->getItemSize( chItemType ) * nItemCount; } } const char *ossimAuxField::initialize( const char * fieldInput ) { int i; nItemCount = atoi(fieldInput); while( *fieldInput != '\0' && *fieldInput != ':' ) { fieldInput++; } if( *fieldInput == '\0' ) { return NULL; } fieldInput++; if( *fieldInput == 'p' || *fieldInput == '*' ) chPointer = *(fieldInput++); if( *fieldInput == '\0' ) return NULL; chItemType = *(fieldInput++); if( chItemType == 'o' ) { for( i = 0; fieldInput[i] != '\0' && fieldInput[i] != ','; i++ ) {} itemObjectType = (char *) malloc(i+1); strncpy( itemObjectType, fieldInput, i ); itemObjectType[i] = '\0'; fieldInput += i+1; } if( chItemType == 'x' && *fieldInput == '{' ) { int nBraceDepth = 1; fieldInput++; // Skip past the definition. while( nBraceDepth > 0 && *fieldInput != '\0' ) { if( *fieldInput == '{' ) nBraceDepth++; else if( *fieldInput == '}' ) nBraceDepth--; fieldInput++; } chItemType = 'o'; // find the comma terminating the type name. for( i = 0; fieldInput[i] != '\0' && fieldInput[i] != ','; i++ ) {} itemObjectType = (char *) malloc(i+1); strncpy( itemObjectType, fieldInput, i ); itemObjectType[i] = '\0'; fieldInput += i+1; } if( chItemType == 'e' ) { int nEnumCount = atoi(fieldInput); int iEnum; fieldInput = strchr(fieldInput,':'); if( fieldInput == NULL ) return NULL; fieldInput++; enumNames = (char **) calloc(sizeof(char *), nEnumCount+1); for( iEnum = 0; iEnum < nEnumCount; iEnum++ ) { char *pszToken; for( i = 0; fieldInput[i] != '\0' && fieldInput[i] != ','; i++ ) {} if( fieldInput[i] != ',' ) return NULL; pszToken = (char *) malloc(i+1); strncpy( pszToken, fieldInput, i ); pszToken[i] = '\0'; enumNames[iEnum] = pszToken; fieldInput += i+1; } } for( i = 0; fieldInput[i] != '\0' && fieldInput[i] != ','; i++ ) {} fieldName = (char *) malloc(i+1); strncpy( fieldName, fieldInput, i ); fieldName[i] = '\0'; fieldInput += i+1; return( fieldInput ); } int ossimAuxField::getInstBytes( char *entryData, int nDataSize ) { int nCount; int nInstBytes = 0; if( nBytes > -1 ) return nBytes; if( chPointer != '\0' ) { memcpy( &nCount, entryData, 4 ); ossimAuxStandardFile( 4, &nCount ); entryData += 8; nInstBytes += 8; } else nCount = 1; if( chItemType == 'b' && nCount != 0 ) // BASEDATA { ossim_int32 nRows, nColumns; ossim_int16 nBaseItemType; memcpy( &nRows, entryData, 4 ); ossimAuxStandardFile( 4, &nRows ); memcpy( &nColumns, entryData+4, 4 ); ossimAuxStandardFile( 4, &nColumns ); memcpy( &nBaseItemType, entryData+8, 2 ); ossimAuxStandardFile( 2, &nBaseItemType ); nInstBytes += 12; nInstBytes += ((ossimAuxGetDataTypeBits(nBaseItemType) + 7) / 8) * nRows * nColumns; } else if( m_auxItemObjectType == NULL ) { nInstBytes += nCount * ossimAuxDictionary::getItemSize(chItemType); } else { int i; for( i = 0; i < nCount; i++ ) { int nThisBytes; nThisBytes = m_auxItemObjectType->getInstBytes( entryData, nDataSize - nInstBytes ); nInstBytes += nThisBytes; entryData += nThisBytes; } } return( nInstBytes ); } /************************************************************************/ /* ossimAuxType() */ /************************************************************************/ ossimAuxType::ossimAuxType() { nBytes = 0; nFields = 0; m_auxFields = NULL; auxTypeName = NULL; } ossimAuxType::~ossimAuxType() { for(int i = 0; i < nFields; i++ ) { delete m_auxFields[i]; m_auxFields[i] = 0; } if (auxTypeName != NULL) { delete[] auxTypeName; auxTypeName = 0; } } const char* ossimAuxType::initialize( const char * typeInput ) { int i; if( *typeInput != '{' ) { while( *typeInput != '{' && *typeInput != '\0' ) typeInput++; if( *typeInput == '\0' ) return NULL; } typeInput++; while( typeInput != NULL && *typeInput != '}' ) { ossimAuxField *newField = new ossimAuxField(); typeInput = newField->initialize( typeInput ); if( typeInput != NULL ) { m_auxFields = (ossimAuxField **)realloc(m_auxFields, sizeof(void*) * (nFields+1) ); m_auxFields[nFields++] = newField; } else { delete newField; } } if( typeInput == NULL ) { return NULL; } typeInput++; /* skip `}' */ for( i = 0; typeInput[i] != '\0' && typeInput[i] != ','; i++ ) {} auxTypeName = (char *) malloc(i+1); strncpy( auxTypeName, typeInput, i ); auxTypeName[i] = '\0'; typeInput += i+1; return( typeInput ); } void ossimAuxType::completeDefn( ossimAuxDictionary* auxDict ) { int i; if( nBytes != 0 ) return; for( i = 0; i < nFields; i++ ) { m_auxFields[i]->completeDefn( auxDict ); if( m_auxFields[i]->nBytes < 0 || nBytes == -1 ) { nBytes = -1; } else { nBytes += m_auxFields[i]->nBytes; } } } int ossimAuxType::extractInstValue( const char * auxFieldPath, char *entryData, ossim_uint32 nDataOffset, int nDataSize, char chReqType, void *reqReturn ) { int nArrayIndex = 0, nNameLen, iField, nByteOffset; const char *remainder; const char *firstArray = strchr(auxFieldPath,'['); const char *firstDot = strchr(auxFieldPath,'.'); if( firstArray != NULL && (firstDot == NULL || firstDot > firstArray) ) { const char *theEnd = firstArray; nArrayIndex = atoi(theEnd+1); nNameLen = theEnd - auxFieldPath; remainder = strchr(auxFieldPath,'.'); if( remainder != NULL ) { remainder++; } } else if( firstDot != NULL ) { const char *theEnd = firstDot; nNameLen = theEnd - auxFieldPath; remainder = theEnd + 1; } else { nNameLen = (int)strlen(auxFieldPath); remainder = NULL; } //Find this field within this type, if possible. nByteOffset = 0; for( iField = 0; iField < nFields && nByteOffset < nDataSize; iField++ ) { std::string tmpFieldPath = const_cast(auxFieldPath); tmpFieldPath = tmpFieldPath.substr(0, nNameLen); std::string tmpFieldName = const_cast(m_auxFields[iField]->fieldName); tmpFieldName = tmpFieldName.substr(0, nNameLen); if( strcmp(tmpFieldPath.c_str(),tmpFieldName.c_str()) == 0 && m_auxFields[iField]->fieldName[nNameLen] == '\0' ) { break; } nByteOffset += m_auxFields[iField]->getInstBytes( entryData + nByteOffset, nDataSize - nByteOffset ); } if( iField == nFields || nByteOffset >= nDataSize ) { return false; } //Extract this field value, and return. return( m_auxFields[iField]-> extractInstValue( remainder, nArrayIndex, entryData + nByteOffset, nDataOffset + nByteOffset, nDataSize - nByteOffset, chReqType, reqReturn ) ); } int ossimAuxType::getInstBytes( char* entryData, int nDataSize ) { if( nBytes >= 0 ) { return( nBytes ); } else { int nTotal = 0; int iField; for( iField = 0; iField < nFields && nTotal < nDataSize; iField++ ) { ossimAuxField *poField = m_auxFields[iField]; int nInstBytes = poField->getInstBytes( entryData, nDataSize - nTotal ); entryData += nInstBytes; nTotal += nInstBytes; } return( nTotal ); } } /************************************************************************/ /* ossimAuxDictionary() */ /************************************************************************/ static const char *defDefn[] = { "Eprj_MapInfo", "{0:pcproName,1:*oEprj_Coordinate,upperLeftCenter,1:*oEprj_Coordinate,lowerRightCenter,1:*oEprj_Size,pixelSize,0:pcunits,}Eprj_MapInfo", NULL, NULL }; ossimAuxDictionary::ossimAuxDictionary( const char* auxDictStr ) { int i; nTypes = 0; nTypesMax = 0; m_auxTypes = NULL; //Read all the types. while( auxDictStr != NULL && *auxDictStr != '.' ) { ossimAuxType* newType = new ossimAuxType(); auxDictStr = newType->initialize( auxDictStr ); if( auxDictStr != NULL ) { addType( newType ); } else { delete newType; } } for( i = 0; defDefn[i] != NULL; i += 2 ) { if( findType( defDefn[i] ) == NULL ) { ossimAuxType *newType = new ossimAuxType(); newType->initialize( defDefn[i+1] ); addType( newType ); } } //Complete the definitions. for( i = 0; i < nTypes; i++ ) { m_auxTypes[i]->completeDefn( this ); } } ossimAuxDictionary::~ossimAuxDictionary() { for(int i = 0; i < nTypes; i++ ) { delete m_auxTypes[i]; m_auxTypes[i] = 0; } } void ossimAuxDictionary::addType( ossimAuxType *type ) { if( nTypes == nTypesMax ) { nTypesMax = nTypes * 2 + 10; m_auxTypes = (ossimAuxType **) realloc( m_auxTypes, sizeof(void*) * nTypesMax ); } m_auxTypes[nTypes++] = type; } ossimAuxType* ossimAuxDictionary::findType( const char * name ) { int i; for( i = 0; i < nTypes; i++ ) { if( strcmp(name, m_auxTypes[i]->auxTypeName) == 0 ) { return( m_auxTypes[i] ); } } return NULL; } int ossimAuxDictionary::getItemSize( char chType ) { switch( chType ) { case '1': case '2': case '4': case 'c': case 'C': return 1; case 'e': case 's': case 'S': return 2; case 't': case 'l': case 'L': case 'f': return 4; case 'd': case 'm': return 8; case 'M': return 16; case 'b': return -1; case 'o': case 'x': return 0; } return 0; } ossim-Miami-2.9.1/src/support_data/ossimAuxXmlSupportData.cpp000066400000000000000000000257351352751253100244070ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Utility/support data class to extract the projection from a dot aux dot xml // file commonly found with mrsid data. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; // Static trace for debugging. static const ossimTrace traceDebug( ossimString("ossimAuxXmlSupportData:debug") ); ossimAuxXmlSupportData::ossimAuxXmlSupportData() { } ossimAuxXmlSupportData::~ossimAuxXmlSupportData() { } ossimRefPtr ossimAuxXmlSupportData::getProjection(const ossimFilename& file) const { ossimRefPtr result = 0; std::shared_ptr is = ossim::StreamFactoryRegistry::instance()-> createIstream(file, std::ios_base::in | std::ios_base::binary); if ( is && is->good() ) { // Read the xml document: ossimXmlDocument xdoc; if ( xdoc.read( *is ) ) { // Get the WKT string ossimString wkt; ossimString path = "/PAMDataset/Metadata/GeodataXform/SpatialReference/WKT"; if ( getPath( path, xdoc, wkt ) ) { if ( wkt.size() ) { // Substitute """: ossimString tmpWkt = wkt.substitute( ossimString("""), ossimString(""), true ); ossimString name; if ( getProjcsName( tmpWkt.string(), name.string() ) ) { result = ossimProjectionFactoryRegistry::instance()->createProjection( name ); if ( result.valid() == false ) { // Hack... if ( name.contains("_NAD83_") ) { cout << "name1: " << name << endl; name.gsub( ossimString("Georef_NAD83_m"), ossimString("GeoRef_M"), false ); name.string() = std::string("NAD_1983_") + name.string(); cout << "name2: " << name << endl; result = ossimProjectionFactoryRegistry::instance()-> createProjection( name ); } } if ( result.valid() ) { if ( initializeProjection( xdoc, tmpWkt.string(), result.get() ) == false ) { // Zero out the result if tie or scale not set. result = 0; } } } } } } } return result; } // End: ossimAuxXmlSupportData::getProjection bool ossimAuxXmlSupportData::initializeProjection( const ossimXmlDocument xdoc, const std::string& wkt, ossimProjection* proj ) const { bool result = false; ossimRefPtr mapProj = dynamic_cast( proj ); if ( mapProj.valid() ) { // Find the tie and scale. ossimString path = "/PAMDataset/Metadata/MDI"; std::vector > xnodes; xdoc.findNodes(path, xnodes); if ( xnodes.size() ) { ossimDpt tie; ossimDpt scale; tie.makeNan(); scale.makeNan(); for ( ossim_uint32 i = 0; i < xnodes.size(); ++i ) { if ( xnodes[i].valid() ) { ossimString value; ossimString attrName = "key"; ossimRefPtr attr = xnodes[i]->findAttribute( attrName ); if ( attr.valid() ) { if (attr->getValue() == "IMAGE__XY_ORIGIN" ) { value = xnodes[i]->getText(); if ( value.size() ) { // Split it: std::vector list; value.split( list, ossimString(","), true ); if ( list.size() == 2 ) { if ( list[0].size() ) { tie.x = list[0].toFloat64(); } if ( list[1].size() ) { tie.y = list[1].toFloat64(); } } } } else if (attr->getValue() == "IMAGE__X_RESOLUTION" ) { value = xnodes[i]->getText(); if ( value.size() ) { scale.x = value.toFloat64(); } } else if (attr->getValue() == "IMAGE__Y_RESOLUTION" ) { value = xnodes[i]->getText(); if ( value.size() ) { scale.y = value.toFloat64(); } } } } // Matches: if ( xnodes[i].valid() ) } // Matches: for ( ossim_uint32 i = 0; i < xnodes.size(); ++i ) if ( !tie.hasNans() && !scale.hasNans() ) { if ( mapProj->isGeographic() ) { // Assuming tie and scale in decimal degrees: mapProj->setDecimalDegreesPerPixel( scale ); ossimGpt gpt(tie.y, tie.x, 0.0); mapProj->setUlTiePoints( ossimGpt( gpt ) ); result = true; } else { // Get the units: ossimUnitType units = getUnits( wkt ); // Convert to meters: result = true; if ( units != OSSIM_METERS ) { if ( units == OSSIM_FEET ) { tie.x = tie.x * MTRS_PER_FT; tie.y = tie.y * MTRS_PER_FT; scale.x = scale.x * MTRS_PER_FT; scale.y = scale.y * MTRS_PER_FT; } else if ( units == OSSIM_US_SURVEY_FEET) { tie.x = tie.x * US_METERS_PER_FT; tie.y = tie.y * US_METERS_PER_FT; scale.x = scale.x * OSSIM_US_SURVEY_FEET; scale.y = scale.y * OSSIM_US_SURVEY_FEET; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimAuxXmlSupportData::initializeProjection WARNING: " << "Unhandled unit type: " << units << std::endl; result = false; } } if ( result ) { mapProj->setMetersPerPixel( scale ); mapProj->setUlTiePoints( tie ); } } } } // Matches: if ( xnodes.size() ) } return result; } // ossimAuxXmlSupportData::initializeProjection bool ossimAuxXmlSupportData::getPath( const ossimString& path, const ossimXmlDocument& xdoc, ossimString& s) const { bool result = false; std::vector > xnodes; xdoc.findNodes(path, xnodes); if ( xnodes.size() == 1 ) // Error if more than one. { if ( xnodes[0].valid() ) { s = xnodes[0]->getText(); result = true; } else if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimAuxXmlSupportData::getPath ERROR:\n" << "Node not found: " << path << std::endl; } } else if ( xnodes.size() == 0 ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimAuxXmlSupportData::getPath ERROR:\n" << "Node not found: " << path << std::endl; } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimAuxXmlSupportData::getPath ERROR:\n" << "Multiple nodes found: " << path << std::endl; } } if (!result) { s.clear(); } return result; } // bool ossimAuxXmlSupportData::getPath bool ossimAuxXmlSupportData::getProjcsName( const std::string& wkt, std::string& name ) const { bool result = false; if ( wkt.size() ) { // Find "PROJCS": std::string::size_type startPos = wkt.find( std::string("PROJCS[") ); if ( startPos != std::string::npos ) { startPos += 7; // Move to end of projcs[ string. // Find first comma ',': std::string::size_type endPos = wkt.find( ',', startPos+1 ); if ( endPos != std::string::npos ) { if ( startPos < endPos ) { name = wkt.substr( startPos, endPos-startPos ); if ( name.size() ) { result = true; } } } } } return result; } // End: ossimAuxXmlSupportData::getProgcsName ossimUnitType ossimAuxXmlSupportData::getUnits( const std::string& wkt ) const { ossimUnitType units = OSSIM_UNIT_UNKNOWN; if ( wkt.size() ) { // Note this is order dependent, i.e. you have to look for "Foot_US" before "Foot". ossimString os = wkt; os.downcase(); if ( os.contains("feet_intl") ) { units = OSSIM_FEET; } else if ( os.contains("foot_us") ) { units = OSSIM_US_SURVEY_FEET; } else if ( os.contains("feet") || os.contains("foot") ) { units = OSSIM_FEET; } //--- // There can be two "unit" blocks. One for PROJCS and one for GEOGCS. // Do this last as the GEOGCS block will have Degree in it. May need to split // the two blocks and then search if this doesn't work. //--- else if ( os.contains("degree") ) { units = OSSIM_DEGREES; } } return units; } // End: ossimAuxXmlSupportData::getUnits ossim-Miami-2.9.1/src/support_data/ossimCcfInfo.cpp000066400000000000000000000030731352751253100223000ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: CCF Info object. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include ossimCcfInfo::ossimCcfInfo() { } ossimCcfInfo::~ossimCcfInfo() { } bool ossimCcfInfo::open(const ossimFilename& file) { std::string connectionString = file.c_str(); std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( file.c_str(), std::ios_base::in|std::ios_base::binary); if(!str) return false; return open(str, connectionString); } bool ossimCcfInfo::open(std::shared_ptr& str, const std::string& connectionString) { bool result = false; m_fileStr.reset(); m_connectionString.clear(); ossimString extension = ossimFilename(connectionString).ext(); extension.downcase(); if (extension == "ccf") { m_fileStr = str; m_connectionString = connectionString; result = true; } return result; } std::ostream& ossimCcfInfo::print(std::ostream& out) const { if(m_fileStr) { ossimCcfHead ccf(m_fileStr, m_connectionString); out << "File: " << m_connectionString << "\n" << ccf; } return out; } ossim-Miami-2.9.1/src/support_data/ossimCeosData.cpp000066400000000000000000002032511352751253100224540ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // Description: // // Class for reading CEOS-formatted metadata. // //******************************************************************* // $Id:$ #include #include #include using namespace std; #include #include "ossim/base/ossimCommon.h" #include // Define Trace flags for use within this file: static ossimTrace traceExec ("ossimCeosData:exec"); static ossimTrace traceDebug ("ossimCeosData:debug"); static const ossimFilename CEOS_VOL_DIR_FILENAME = "vdf_dat.001"; static const ossimFilename CEOS_LEADER_FILENAME = "lea_01.001"; static const ossimFilename CEOS_IMAGE_FILENAME = "dat_01.001"; static const ossimFilename CEOS_TRAILER_FILENAME = "tra_01.001"; //****************************************************************************** // CONSTRUCTOR: //****************************************************************************** ossimCeosData::ossimCeosData(const ossimFilename& volDirFile, const ossimFilename& leaderFile, const ossimFilename& imageFile, const ossimFilename& trailerFile) : theVolDirFileName (volDirFile), theLeaderFileName (leaderFile), theImageFileName (imageFile), theTrailerFileName (trailerFile), theErrorStatus (OK), theVolDescRec (0), theTextRec (0), theDataSetSumRec (0), theQualSumRec (0), theSdrHistRec (0), thePdr16HistRec (0), thePdr8HistRec (0), theProcParmRec (0), theMapProjRec (0), thePosDataRec (0), theAttDataRec (0), theRadiDataRec (0), theRadiCompRec (0) { static const char MODULE[] = "ossimCeosData Constructor #1"; if (traceExec()) CLOG << "entering..." << endl; loadCeosRecords(); if (traceExec()) CLOG << "returning..." << endl; } //****************************************************************************** // CONSTRUCTOR: ossimCeosData(ossimFilename) // // Initializes given the image directory (assumes default filenames). // //****************************************************************************** ossimCeosData::ossimCeosData(const ossimFilename& imageDir) : theErrorStatus (OK), theVolDescRec (0), theTextRec (0), theDataSetSumRec (0), theQualSumRec (0), theSdrHistRec (0), thePdr16HistRec (0), thePdr8HistRec (0), theProcParmRec (0), theMapProjRec (0), thePosDataRec (0), theAttDataRec (0), theRadiDataRec (0), theRadiCompRec (0) { static const char MODULE[] = "ossimCeosData Constructor #1"; if (traceExec()) CLOG << "entering..." << endl; //*** // Assign values to ossimFilename data members: //*** theVolDirFileName = imageDir.dirCat(CEOS_VOL_DIR_FILENAME); theLeaderFileName = imageDir.dirCat(CEOS_LEADER_FILENAME); theImageFileName = imageDir.dirCat(CEOS_IMAGE_FILENAME); theTrailerFileName = imageDir.dirCat(CEOS_TRAILER_FILENAME); loadCeosRecords(); if (traceExec()) CLOG << "returning..." << endl; } //****************************************************************************** // PUBLIC METHOD: ossimCeosData::dump(ostream&) // //****************************************************************************** void ossimCeosData::dump(ostream& stream) const { static const char MODULE[] = "ossimCeosData::dump(ostream& stream)"; if (traceExec()) CLOG << "entering..." << endl; stream << "\nDump of ossimCeosData Object -----------------------------" << endl; if (theVolDescRec) dumpVolDescRec(stream); else stream << "\n\n\tvol_desc_rec not present." << endl; if (theTextRec) dumpTextRec(stream); else stream << "\n\n\ttext_rec not present." << endl; if (imopDescRec()) dumpImopDescRec(stream); else stream << "\n\n\timop_desc_rec not present." << endl; if (theDataSetSumRec) dumpDataSetSumRec(stream); else stream << "\n\n\tdataset_sum_rec not present." << endl; if (theQualSumRec) dumpQualSumRec(stream); else stream << "\n\n\tqual_sum_rec not present." << endl; if (theSdrHistRec) dumpSdrHistRec(stream); else stream << "\n\n\tsdr_hist_rec not present." << endl; if (thePdr16HistRec) dumpPdr16HistRec(stream); else stream << "\n\n\tpdr16_hist_rec not present." << endl; if (thePdr8HistRec) dumpPdr8HistRec(stream); else stream << "\n\n\tpdr8_hist_rec not present." << endl; if (theProcParmRec) dumpProcParmRec(stream); else stream << "\n\n\tproc_parm_rec not present." << endl; if (theMapProjRec) dumpMapProjRec(stream); else stream << "\n\n\tmap_proj_rec not present." << endl; if (thePosDataRec) dumpPosDataRec(stream); else stream << "\n\n\tpos_data_rec not present." << endl; if (theAttDataRec) dumpAttDataRec(stream); else stream << "\n\n\tatt_data_rec not present." << endl; if (theRadiDataRec) dumpRadiDataRec(stream); else stream << "\n\n\tradi_data_rec not present." << endl; if (theRadiCompRec) dumpRadiCompRec(stream); else stream << "\n\n\tradi_comp_rec not present." << endl; stream << "\nEnd of ossimCeosData Object Dump -------------------------" << endl; if (traceExec()) CLOG << "returning..." << endl; return; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpVolDescRec() // //****************************************************************************** void ossimCeosData::dumpVolDescRec(ostream& stream) const { const vol_desc_rec* p = theVolDescRec; stream << "\n\n\tContents of vol_desc_rec:\n"; stream << "\n\t ascii_flag \""; stream.write(p->ascii_flag, 2); stream << "\"\n\t format_doc \""; stream.write(p->format_doc, 12); stream << "\"\n\t format_ver \""; stream.write(p->format_ver, 2); stream << "\"\n\t format_rev \""; stream.write(p->format_rev, 2); stream << "\"\n\t software_id \""; stream.write(p->software_id, 12); stream << "\"\n\t phyvol_id \""; stream.write(p->phyvol_id, 16); stream << "\"\n\t logvol_id \""; stream.write(p->logvol_id, 16); stream << "\"\n\t volset_id \""; stream.write(p->volset_id, 16); stream << "\"\n\t phyvol_cnt \""; stream.write(p->phyvol_cnt, 2); stream << "\"\n\t first_phyvol \""; stream.write(p->first_phyvol, 2); stream << "\"\n\t last_phyvol \""; stream.write(p->last_phyvol, 2); stream << "\"\n\t curr_phyvol \""; stream.write(p->curr_phyvol, 2); stream << "\"\n\t first_file \""; stream.write(p->first_file, 4); stream << "\"\n\t volset_log \""; stream.write(p->volset_log, 4); stream << "\"\n\t phyvol_log \""; stream.write(p->phyvol_log, 4); stream << "\"\n\t logvol_date \""; stream.write(p->logvol_date, 8); stream << "\"\n\t logvol_time \""; stream.write(p->logvol_time, 8); stream << "\"\n\t logvol_country \""; stream.write(p->logvol_country, 12); stream << "\"\n\t logvol_agency \""; stream.write(p->logvol_agency, 8); stream << "\"\n\t logvol_facility \""; stream.write(p->logvol_facility,12); stream << "\"\n\t n_filepoint \""; stream.write(p->n_filepoint, 4); stream << "\"\n\t n_voldir \""; stream.write(p->n_voldir, 4); stream << "\"\n\t product_id \""; stream.write(p->product_id, 8); stream << "\"" << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpTextRec() // //****************************************************************************** void ossimCeosData::dumpTextRec(ostream& stream) const { const text_rec* p = theTextRec; stream << "\n\n\tContents of text_rec:\n\t"; stream << "\n\t ascii_flag \""; stream.write(p->ascii_flag, 2); stream << "\"\n\t cont_flag \""; stream.write(p->cont_flag, 2); stream << "\"\n\t product_type \""; stream.write(p->product_type, 40); stream << "\"\n\t product_create \""; stream.write(p->product_create, 60); stream << "\"\n\t phyvol_id \""; stream.write(p->phyvol_id, 40); stream << "\"\n\t scene_id \""; stream.write(p->scene_id, 40); stream << "\"\n\t scene_loc \""; stream.write(p->scene_loc, 40); stream << "\"" << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpImopDescRec() // //****************************************************************************** void ossimCeosData::dumpImopDescRec(ostream& stream) const { const imop_desc_rec* p = &theImopDescRec; stream << "\n\n\tContents of imop_desc_rec:\n\t"; stream << "\n\t ascii_flag \""; stream.write(p->ascii_flag, 2); stream << "\"\n\t spare1 \""; stream.write(p->spare1, 2); stream << "\"\n\t format_doc \""; stream.write(p->format_doc, 12); stream << "\"\n\t format_rev \""; stream.write(p->format_rev, 2); stream << "\"\n\t design_rev \""; stream.write(p->design_rev, 2); stream << "\"\n\t software_id \""; stream.write(p->software_id, 12); stream << "\"\n\t file_num \""; stream.write(p->file_num, 4); stream << "\"\n\t file_name \""; stream.write(p->file_name, 16); stream << "\"\n\t rec_seq \""; stream.write(p->rec_seq, 4); stream << "\"\n\t seq_loc \""; stream.write(p->seq_loc, 8); stream << "\"\n\t seq_len \""; stream.write(p->seq_len, 4); stream << "\"\n\t rec_code \""; stream.write(p->rec_code, 4); stream << "\"\n\t code_loc \""; stream.write(p->code_loc, 8); stream << "\"\n\t code_len \""; stream.write(p->code_len, 4); stream << "\"\n\t rec_len \""; stream.write(p->rec_len, 4); stream << "\"\n\t rlen_loc \""; stream.write(p->rlen_loc, 8); stream << "\"\n\t rlen_len \""; stream.write(p->rlen_len, 4); stream << "\"\n\t spare2 \""; stream.write(p->spare2, 4); stream << "\"\n\t spare3 \""; stream.write(p->spare3, 64); stream << "\"\n\t n_dataset \""; stream.write(p->n_dataset, 6); stream << "\"\n\t l_dataset \""; stream.write(p->l_dataset, 6); stream << "\"\n\t spare4 \""; stream.write(p->spare4, 24); stream << "\"\n\t nbit \""; stream.write(p->nbit, 4); stream << "\"\n\t nsamp \""; stream.write(p->nsamp, 4); stream << "\"\n\t nbyte \""; stream.write(p->nbyte, 4); stream << "\"\n\t justify \""; stream.write(p->justify, 4); stream << "\"\n\t nchn \""; stream.write(p->nchn, 4); stream << "\"\n\t nlin \""; stream.write(p->nlin, 8); stream << "\"\n\t nleft \""; stream.write(p->nleft, 4); stream << "\"\n\t ngrp \""; stream.write(p->ngrp, 8); stream << "\"\n\t nright \""; stream.write(p->nright, 4); stream << "\"\n\t ntop \""; stream.write(p->ntop, 4); stream << "\"\n\t nbott \""; stream.write(p->nbott, 4); stream << "\"\n\t intleav \""; stream.write(p->intleav, 4); stream << "\"\n\t nrec_lin \""; stream.write(p->nrec_lin, 2); stream << "\"\n\t nrec_chn \""; stream.write(p->nrec_chn, 2); stream << "\"\n\t n_prefix \""; stream.write(p->n_prefix, 4); stream << "\"\n\t n_sar \""; stream.write(p->n_sar, 8); stream << "\"\n\t n_suffix \""; stream.write(p->n_suffix, 4); stream << "\"\n\t spare5 \""; stream.write(p->spare5, 4); stream << "\"\n\t lin_loc \""; stream.write(p->lin_loc, 8); stream << "\"\n\t chn_loc \""; stream.write(p->chn_loc, 8); stream << "\"\n\t tim_loc \""; stream.write(p->tim_loc, 8); stream << "\"\n\t left_loc \""; stream.write(p->left_loc, 8); stream << "\"\n\t right_loc \""; stream.write(p->right_loc, 8); stream << "\"\n\t pad_ind \""; stream.write(p->pad_ind, 4); stream << "\"\n\t spare6 \""; stream.write(p->spare6, 28); stream << "\"\n\t qual_loc \""; stream.write(p->qual_loc, 8); stream << "\"\n\t cali_loc \""; stream.write(p->cali_loc, 8); stream << "\"\n\t gain_loc \""; stream.write(p->gain_loc, 8); stream << "\"\n\t bias_loc \""; stream.write(p->bias_loc, 8); stream << "\"\n\t type_id \""; stream.write(p->type_id, 28); stream << "\"\n\t type_code \""; stream.write(p->type_code, 4); stream << "\"\n\t left_fill \""; stream.write(p->left_fill, 4); stream << "\"\n\t right_fill \""; stream.write(p->right_fill, 4); stream << "\"\n\t pix_rng \""; stream.write(p->pix_rng, 8); stream << "\"" << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpDataSetSumRec() // //****************************************************************************** void ossimCeosData::dumpDataSetSumRec(ostream& stream) const { const dataset_sum_rec* p = theDataSetSumRec; stream << "\n\n\tContents of dataset_sum_rec:\n\t \""; stream << "\n\t seq_num \""; stream.write(p->seq_num, 4); stream << "\"\n\t sar_chn \""; stream.write(p->sar_chn, 4); stream << "\"\n\t scene_id \""; stream.write(p->scene_id, 16); stream << "\"\n\t scene_des \""; stream.write(p->scene_des, 32); stream << "\"\n\t inp_sctim \""; stream.write(p->inp_sctim, 32); stream << "\"\n\t asc_des \""; stream.write(p->asc_des, 16); stream << "\"\n\t pro_lat \""; stream.write(p->pro_lat, 16); stream << "\"\n\t pro_long \""; stream.write(p->pro_long, 16); stream << "\"\n\t pro_head \""; stream.write(p->pro_head, 16); stream << "\"\n\t ellip_des \""; stream.write(p->ellip_des, 16); stream << "\"\n\t ellip_maj \""; stream.write(p->ellip_maj, 16); stream << "\"\n\t ellip_min \""; stream.write(p->ellip_min, 16); stream << "\"\n\t earth_mass \""; stream.write(p->earth_mass, 16); stream << "\"\n\t grav_const \""; stream.write(p->grav_const, 16); stream << "\"\n\t ellip_j[0] \""; stream.write(p->ellip_j[0], 16); stream << "\"\n\t ellip_j[1] \""; stream.write(p->ellip_j[1], 16); stream << "\"\n\t ellip_j[2] \""; stream.write(p->ellip_j[2], 16); stream << "\"\n\t spare1 \""; stream.write(p->spare1, 16); stream << "\"\n\t terrain_h \""; stream.write(p->terrain_h, 16); stream << "\"\n\t sc_lin \""; stream.write(p->sc_lin, 8); stream << "\"\n\t sc_pix \""; stream.write(p->sc_pix, 8); stream << "\"\n\t scene_len \""; stream.write(p->scene_len, 16); stream << "\"\n\t scene_wid \""; stream.write(p->scene_wid, 16); stream << "\"\n\t spare2 \""; stream.write(p->spare2, 16); stream << "\"\n\t nchn \""; stream.write(p->nchn, 4); stream << "\"\n\t spare3 \""; stream.write(p->spare3, 4); stream << "\"\n\t mission_id \""; stream.write(p->mission_id, 16); stream << "\"\n\t sensor_id \""; stream.write(p->sensor_id, 32); stream << "\"\n\t orbit_num \""; stream.write(p->orbit_num, 8); stream << "\"\n\t plat_lat \""; stream.write(p->plat_lat, 8); stream << "\"\n\t plat_long \""; stream.write(p->plat_long, 8); stream << "\"\n\t plat_head \""; stream.write(p->plat_head, 8); stream << "\"\n\t clock_ang \""; stream.write(p->clock_ang, 8); stream << "\"\n\t incident_ang \""; stream.write(p->incident_ang, 8); stream << "\"\n\t spare4 \""; stream.write(p->spare4, 8); stream << "\"\n\t wave_length \""; stream.write(p->wave_length, 16); stream << "\"\n\t motion_comp \""; stream.write(p->motion_comp, 2); stream << "\"\n\t pulse_code \""; stream.write(p->pulse_code, 16); stream << "\"\n\t ampl_coef[0] \""; stream.write(p->ampl_coef[0], 16); stream << "\"\n\t ampl_coef[1] \""; stream.write(p->ampl_coef[1], 16); stream << "\"\n\t ampl_coef[2] \""; stream.write(p->ampl_coef[2], 16); stream << "\"\n\t ampl_coef[3] \""; stream.write(p->ampl_coef[3], 16); stream << "\"\n\t ampl_coef[4] \""; stream.write(p->ampl_coef[4], 16); stream << "\"\n\t phas_coef[0] \""; stream.write(p->phas_coef[0], 16); stream << "\"\n\t phas_coef[1] \""; stream.write(p->phas_coef[1], 16); stream << "\"\n\t phas_coef[2] \""; stream.write(p->phas_coef[2], 16); stream << "\"\n\t phas_coef[3] \""; stream.write(p->phas_coef[3], 16); stream << "\"\n\t phas_coef[4] \""; stream.write(p->phas_coef[4], 16); stream << "\"\n\t chirp_ext_ind \""; stream.write(p->chirp_ext_ind, 8); stream << "\"\n\t spare5 \""; stream.write(p->spare5, 8); stream << "\"\n\t fr \""; stream.write(p->fr, 16); stream << "\"\n\t rng_gate \""; stream.write(p->rng_gate, 16); stream << "\"\n\t rng_length \""; stream.write(p->rng_length, 16); stream << "\"\n\t baseband_f \""; stream.write(p->baseband_f, 4); stream << "\"\n\t rngcmp_f \""; stream.write(p->rngcmp_f, 4); stream << "\"\n\t gn_polar \""; stream.write(p->gn_polar, 16); stream << "\"\n\t gn_cross \""; stream.write(p->gn_cross, 16); stream << "\"\n\t chn_bits \""; stream.write(p->chn_bits, 8); stream << "\"\n\t quant_desc \""; stream.write(p->quant_desc, 12); stream << "\"\n\t i_bias \""; stream.write(p->i_bias, 16); stream << "\"\n\t q_bias \""; stream.write(p->q_bias, 16); stream << "\"\n\t iq_ratio \""; stream.write(p->iq_ratio, 16); stream << "\"\n\t spare6 \""; stream.write(p->spare6, 16); stream << "\"\n\t spare7 \""; stream.write(p->spare7, 16); stream << "\"\n\t ele_sight \""; stream.write(p->ele_sight, 16); stream << "\"\n\t mech_sight \""; stream.write(p->mech_sight, 16); stream << "\"\n\t echo_track \""; stream.write(p->echo_track, 4); stream << "\"\n\t fa \""; stream.write(p->fa, 16); stream << "\"\n\t elev_beam \""; stream.write(p->elev_beam, 16); stream << "\"\n\t azim_beam \""; stream.write(p->azim_beam, 16); stream << "\"\n\t sat_bintim \""; stream.write(p->sat_bintim, 16); stream << "\"\n\t sat_clktim \""; stream.write(p->sat_clktim, 32); stream << "\"\n\t sat_clkinc \""; stream.write(p->sat_clkinc, 8); stream << "\"\n\t spare8 \""; stream.write(p->spare8, 8); stream << "\"\n\t fac_id \""; stream.write(p->fac_id, 16); stream << "\"\n\t sys_id \""; stream.write(p->sys_id, 8); stream << "\"\n\t ver_id \""; stream.write(p->ver_id, 8); stream << "\"\n\t fac_code \""; stream.write(p->fac_code, 16); stream << "\"\n\t lev_code \""; stream.write(p->lev_code, 16); stream << "\"\n\t prod_type \""; stream.write(p->prod_type, 32); stream << "\"\n\t algor_id \""; stream.write(p->algor_id, 32); stream << "\"\n\t n_azilok \""; stream.write(p->n_azilok, 16); stream << "\"\n\t n_rnglok \""; stream.write(p->n_rnglok, 16); stream << "\"\n\t bnd_azilok \""; stream.write(p->bnd_azilok, 16); stream << "\"\n\t bnd_rnglok \""; stream.write(p->bnd_rnglok, 16); stream << "\"\n\t bnd_azi \""; stream.write(p->bnd_azi, 16); stream << "\"\n\t bnd_rng \""; stream.write(p->bnd_rng, 16); stream << "\"\n\t azi_weight \""; stream.write(p->azi_weight, 32); stream << "\"\n\t rng_weight \""; stream.write(p->rng_weight, 32); stream << "\"\n\t data_inpsrc \""; stream.write(p->data_inpsrc, 16); stream << "\"\n\t rng_res \""; stream.write(p->rng_res, 16); stream << "\"\n\t azi_res \""; stream.write(p->azi_res, 16); stream << "\"\n\t radi_stretch[0] \""; stream.write(p->radi_stretch[0],16); stream << "\"\n\t radi_stretch[1] \""; stream.write(p->radi_stretch[1],16); stream << "\"\n\t alt_dopcen[0] \""; stream.write(p->alt_dopcen[0],16); stream << "\"\n\t alt_dopcen[1] \""; stream.write(p->alt_dopcen[1],16); stream << "\"\n\t alt_dopcen[2] \""; stream.write(p->alt_dopcen[2],16); stream << "\"\n\t spare9 \""; stream.write(p->spare9, 16); stream << "\"\n\t crt_dopcen[0] \""; stream.write(p->crt_dopcen[0],16); stream << "\"\n\t crt_dopcen[1] \""; stream.write(p->crt_dopcen[1],16); stream << "\"\n\t crt_dopcen[2] \""; stream.write(p->crt_dopcen[2],16); stream << "\"\n\t time_dir_pix \""; stream.write(p->time_dir_pix, 8); stream << "\"\n\t time_dir_lin \""; stream.write(p->time_dir_lin, 8); stream << "\"\n\t alt_rate[0] \""; stream.write(p->alt_rate[0], 16); stream << "\"\n\t alt_rate[1] \""; stream.write(p->alt_rate[1], 16); stream << "\"\n\t alt_rate[2] \""; stream.write(p->alt_rate[2], 16); stream << "\"\n\t spare10 \""; stream.write(p->spare10, 16); stream << "\"\n\t crt_rate[0] \""; stream.write(p->crt_rate[0], 16); stream << "\"\n\t crt_rate[1] \""; stream.write(p->crt_rate[1], 16); stream << "\"\n\t crt_rate[2] \""; stream.write(p->crt_rate[2], 16); stream << "\"\n\t spare11 \""; stream.write(p->spare11, 16); stream << "\"\n\t line_cont \""; stream.write(p->line_cont, 8); stream << "\"\n\t clutter_lock \""; stream.write(p->clutter_lock, 4); stream << "\"\n\t auto_focus \""; stream.write(p->auto_focus, 4); stream << "\"\n\t line_spacing \""; stream.write(p->line_spacing, 16); stream << "\"\n\t pix_spacing \""; stream.write(p->pix_spacing, 16); stream << "\"\n\t rngcmp_desg \""; stream.write(p->rngcmp_desg, 16); stream << "\"" << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpQualSumRec() // //****************************************************************************** void ossimCeosData::dumpQualSumRec(ostream& stream) const { const qual_sum_rec* p = theQualSumRec; stream << "\n\n\tContents of qual_sum_rec:\n\t"; stream << "\n\t rec_seq \""; stream.write(p->rec_seq, 4); stream << "\"\n\t sar_chn \""; stream.write(p->sar_chn, 4); stream << "\"\n\t cali_date \""; stream.write(p->cali_date, 6); stream << "\"\n\t nchn \""; stream.write(p->nchn, 4); stream << "\"\n\t islr \""; stream.write(p->islr, 16); stream << "\"\n\t pslr \""; stream.write(p->pslr, 16); stream << "\"\n\t azi_ambig \""; stream.write(p->azi_ambig, 16); stream << "\"\n\t rng_ambig \""; stream.write(p->rng_ambig, 16); stream << "\"\n\t snr \""; stream.write(p->snr, 16); stream << "\"\n\t ber \""; stream.write(p->ber, 16); stream << "\"\n\t rng_res \""; stream.write(p->rng_res, 16); stream << "\"\n\t azi_res \""; stream.write(p->azi_res, 16); stream << "\"\n\t rad_res \""; stream.write(p->rad_res, 16); stream << "\"\n\t dyn_rng \""; stream.write(p->dyn_rng, 16); stream << "\"\n\t rad_unc_db \""; stream.write(p->rad_unc_db, 16); stream << "\"\n\t rad_unc_deg \""; stream.write(p->rad_unc_deg, 16); int i; for (i=0; i<16; i++) { stream << "\"\n\t rad_unc[" << i << "]:"; stream << "\n\t db \""; stream.write(p->rad_unc[i].db, 16); stream << "\"\n\t deg \""; stream.write(p->rad_unc[i].deg, 16); } stream << "\"\n\t alt_locerr \""; stream.write(p->alt_locerr, 16); stream << "\"\n\t crt_locerr \""; stream.write(p->crt_locerr, 16); stream << "\"\n\t alt_scale \""; stream.write(p->alt_scale, 16); stream << "\"\n\t crt_scale \""; stream.write(p->crt_scale, 16); stream << "\"\n\t dis_skew \""; stream.write(p->dis_skew, 16); stream << "\"\n\t ori_err \""; stream.write(p->ori_err, 16); for (i=0; i<16; i++) { stream << "\"\n\t misreg[" << i << "]:"; stream << "\n\t alt_m \""; stream.write(p->misreg[i].alt_m, 16); stream << "\"\n\t crt_m \""; stream.write(p->misreg[i].crt_m, 16); } stream << "\"\n\t nesz \""; stream.write(p->nesz, 16); stream << "\"\n\t enl \""; stream.write(p->enl, 16); stream << "\"\n\t tb_update \""; stream.write(p->tb_update, 8); stream << "\"" << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpSdrHistRec() // //****************************************************************************** void ossimCeosData::dumpSdrHistRec(ostream& stream) const { const sdr_hist_rec* p = theSdrHistRec; stream << "\n\n\tContents of sdr_hist_rec:\n\t"; stream << "\n\t rec_seq \""; stream.write(p->rec_seq, 4); stream << "\"\n\t sar_chn \""; stream.write(p->sar_chn, 4); stream << "\"\n\t ntab \""; stream.write(p->ntab, 8); stream << "\"\n\t ltab \""; stream.write(p->ltab, 8); stream << "\"\n\t htab[0] (only one sdr_htab_rec declared in data struct):"; stream << "\n\t hist_desc \""; stream.write(p->htab.hist_desc, 32); stream << "\"\n\t nrec \""; stream.write(p->htab.nrec, 4); stream << "\"\n\t tab_seq \""; stream.write(p->htab.tab_seq, 4); stream << "\"\n\t nbin \""; stream.write(p->htab.nbin, 8); stream << "\"\n\t ns_lin \""; stream.write(p->htab.ns_lin, 8); stream << "\"\n\t ns_pix \""; stream.write(p->htab.ns_pix, 8); stream << "\"\n\t ngrp_lin \""; stream.write(p->htab.ngrp_lin, 8); stream << "\"\n\t ngrp_pix \""; stream.write(p->htab.ngrp_pix, 8); stream << "\"\n\t nsamp_lin \""; stream.write(p->htab.nsamp_lin,8); stream << "\"\n\t nsamp_pix \""; stream.write(p->htab.nsamp_pix,8); stream << "\"\n\t min_smp \""; stream.write(p->htab.min_smp, 16); stream << "\"\n\t max_smp \""; stream.write(p->htab.max_smp, 16); stream << "\"\n\t mean_smp \""; stream.write(p->htab.mean_smp,16); stream << "\"\n\t std_smp \""; stream.write(p->htab.std_smp, 16); stream << "\"\n\t smp_inc \""; stream.write(p->htab.smp_inc, 16); stream << "\"\n\t min_hist \""; stream.write(p->htab.min_hist,16); stream << "\"\n\t max_hist \""; stream.write(p->htab.max_hist,16); stream << "\"\n\t mean_hist \""; stream.write(p->htab.mean_hist, 16); stream << "\"\n\t std_hist \""; stream.write(p->htab.std_hist,16); stream << "\"\n\t nhist \""; stream.write(p->htab.nhist, 8); stream << "\"\n\t [Use debugger to view histogram]"; stream << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpPdr16HistRec() // //****************************************************************************** void ossimCeosData::dumpPdr16HistRec(ostream& stream) const { const pdr16_hist_rec* p = thePdr16HistRec; stream << "\n\n\tContents of pdr16_hist_rec:\n\t"; stream << "\n\t rec_seq \""; stream.write(p->rec_seq, 4); stream << "\"\n\t sar_chn \""; stream.write(p->sar_chn, 4); stream << "\"\n\t ntab \""; stream.write(p->ntab, 8); stream << "\"\n\t ltab \""; stream.write(p->ltab, 8); char buf[] = "12345678"; strncpy(buf, p->ntab, 8); int n = atoi(buf); for (int i=0; ihtab[i].hist_desc, 32); stream << "\"\n\t nrec \""; stream.write(p->htab[i].nrec, 4); stream << "\"\n\t tab_seq \""; stream.write(p->htab[i].tab_seq, 4); stream << "\"\n\t nbin \""; stream.write(p->htab[i].nbin, 8); stream << "\"\n\t ns_lin \""; stream.write(p->htab[i].ns_lin, 8); stream << "\"\n\t ns_pix \""; stream.write(p->htab[i].ns_pix, 8); stream << "\"\n\t ngrp_lin \""; stream.write(p->htab[i].ngrp_lin, 8); stream << "\"\n\t ngrp_pix \""; stream.write(p->htab[i].ngrp_pix, 8); stream << "\"\n\t nsamp_lin \""; stream.write(p->htab[i].nsamp_lin, 8); stream << "\"\n\t nsamp_pix \""; stream.write(p->htab[i].nsamp_pix, 8); stream << "\"\n\t min_smp \""; stream.write(p->htab[i].min_smp, 16); stream << "\"\n\t max_smp \""; stream.write(p->htab[i].max_smp, 16); stream << "\"\n\t mean_smp \""; stream.write(p->htab[i].mean_smp, 16); stream << "\"\n\t std_smp \""; stream.write(p->htab[i].std_smp, 16); stream << "\"\n\t smp_inc \""; stream.write(p->htab[i].smp_inc, 16); stream << "\"\n\t min_hist \""; stream.write(p->htab[i].min_hist, 16); stream << "\"\n\t max_hist \""; stream.write(p->htab[i].max_hist, 16); stream << "\"\n\t mean_hist \""; stream.write(p->htab[i].mean_hist, 16); stream << "\"\n\t std_hist \""; stream.write(p->htab[i].std_hist, 16); stream << "\"\n\t nhist \""; stream.write(p->htab[i].nhist, 8); stream << "\n\t [Use debugger to view histogram]"; } stream << "\"" << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpPdr8HistRec() // //****************************************************************************** void ossimCeosData::dumpPdr8HistRec(ostream& stream) const { const pdr8_hist_rec* p = thePdr8HistRec; stream << "\n\n\tContents of pdr18hist_rec:\n\t"; stream << "\n\t rec_seq \""; stream.write(p->rec_seq, 4); stream << "\"\n\t sar_chn \""; stream.write(p->sar_chn, 4); stream << "\"\n\t ntab \""; stream.write(p->ntab, 8); stream << "\"\n\t ltab \""; stream.write(p->ltab, 8); stream << "\"\n\t htab[0] (only one sdr_htab_rec declared in data struct):"; stream << "\n\t hist_desc \""; stream.write(p->htab.hist_desc, 32); stream << "\"\n\t nrec \""; stream.write(p->htab.nrec, 4); stream << "\"\n\t tab_seq \""; stream.write(p->htab.tab_seq, 4); stream << "\"\n\t nbin \""; stream.write(p->htab.nbin, 8); stream << "\"\n\t ns_lin \""; stream.write(p->htab.ns_lin, 8); stream << "\"\n\t ns_pix \""; stream.write(p->htab.ns_pix, 8); stream << "\"\n\t ngrp_lin \""; stream.write(p->htab.ngrp_lin, 8); stream << "\"\n\t ngrp_pix \""; stream.write(p->htab.ngrp_pix, 8); stream << "\"\n\t nsamp_lin \""; stream.write(p->htab.nsamp_lin,8); stream << "\"\n\t nsamp_pix \""; stream.write(p->htab.nsamp_pix,8); stream << "\"\n\t min_smp \""; stream.write(p->htab.min_smp, 16); stream << "\"\n\t max_smp \""; stream.write(p->htab.max_smp, 16); stream << "\"\n\t mean_smp \""; stream.write(p->htab.mean_smp,16); stream << "\"\n\t std_smp \""; stream.write(p->htab.std_smp, 16); stream << "\"\n\t smp_inc \""; stream.write(p->htab.smp_inc, 16); stream << "\"\n\t min_hist \""; stream.write(p->htab.min_hist,16); stream << "\"\n\t max_hist \""; stream.write(p->htab.max_hist,16); stream << "\"\n\t mean_hist \""; stream.write(p->htab.mean_hist, 16); stream << "\"\n\t std_hist \""; stream.write(p->htab.std_hist,16); stream << "\"\n\t nhist \""; stream.write(p->htab.nhist, 16); stream << "\"\n\t [Use debugger to view histogram]"; stream << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpProcParmRec() // //****************************************************************************** void ossimCeosData::dumpProcParmRec(ostream& stream) const { const proc_parm_rec* p = theProcParmRec; stream << "\n\n\tContents of proc_parm_rec:\n\t"; stream << "\n\t slow_time_coef[1] \""; stream.write(p->slow_time_coef[1], 22); stream << "\"\n\t rec_seq \""; stream.write(p->rec_seq, 4); stream << "\"\n\t spare1 \""; stream.write(p->spare1, 4); stream << "\"\n\t inp_media \""; stream.write(p->inp_media, 3); stream << "\"\n\t n_tape_id \""; stream.write(p->n_tape_id, 4); stream << "\"\n\t tape_id[0] \""; stream.write(p->tape_id[0], 8); stream << "\"\n\t exp_ing_start \""; stream.write(p->exp_ing_start,21); stream << "\"\n\t exp_ing_stop \""; stream.write(p->exp_ing_stop, 21); stream << "\"\n\t act_ing_start \""; stream.write(p->act_ing_start,21); stream << "\"\n\t act_ing_stop \""; stream.write(p->act_ing_stop, 21); stream << "\"\n\t proc_start \""; stream.write(p->proc_start, 21); stream << "\"\n\t proc_stop \""; stream.write(p->proc_stop, 21); stream << "\"\n\t mn_sig_lev[0] \""; stream.write(p->mn_sig_lev[0],16); stream << "\"\n\t mn_sig_lev[1] \""; stream.write(p->mn_sig_lev[1],16); stream << "\"\n\t mn_sig_lev[2] \""; stream.write(p->mn_sig_lev[2],16); stream << "\"\n\t mn_sig_lev[3] \""; stream.write(p->mn_sig_lev[3],16); stream << "\"\n\t mn_sig_lev[4] \""; stream.write(p->mn_sig_lev[4],16); stream << "\"\n\t mn_sig_lev[5] \""; stream.write(p->mn_sig_lev[5],16); stream << "\"\n\t mn_sig_lev[6] \""; stream.write(p->mn_sig_lev[6],16); stream << "\"\n\t mn_sig_lev[7] \""; stream.write(p->mn_sig_lev[7],16); stream << "\"\n\t mn_sig_lev[8] \""; stream.write(p->mn_sig_lev[8],16); stream << "\"\n\t mn_sig_lev[9] \""; stream.write(p->mn_sig_lev[9],16); stream << "\"\n\t scr_data_ind \""; stream.write(p->scr_data_ind, 4); stream << "\"\n\t miss_ln \""; stream.write(p->miss_ln, 8); stream << "\"\n\t rej_ln \""; stream.write(p->rej_ln, 8); stream << "\"\n\t large_gap \""; stream.write(p->large_gap, 8); stream << "\"\n\t bit_err_rate \""; stream.write(p->bit_err_rate, 16); stream << "\"\n\t fm_crc_err \""; stream.write(p->fm_crc_err, 16); stream << "\"\n\t date_incons \""; stream.write(p->date_incons, 8); stream << "\"\n\t prf_changes \""; stream.write(p->prf_changes, 8); stream << "\"\n\t delay_changes \""; stream.write(p->delay_changes, 8); stream << "\"\n\t skipd_frams \""; stream.write(p->skipd_frams, 8); stream << "\"\n\t rej_bf_start \""; stream.write(p->rej_bf_start, 8); stream << "\"\n\t rej_few_fram \""; stream.write(p->rej_few_fram, 8); stream << "\"\n\t rej_many_fram \""; stream.write(p->rej_many_fram, 8); stream << "\"\n\t rej_mchn_err \""; stream.write(p->rej_mchn_err, 8); stream << "\"\n\t rej_vchn_err \""; stream.write(p->rej_vchn_err, 8); stream << "\"\n\t rej_rec_type \""; stream.write(p->rej_rec_type, 8); stream << "\"\n\t sens_config \""; stream.write(p->sens_config, 10); stream << "\"\n\t sens_orient \""; stream.write(p->sens_orient, 9); stream << "\"\n\t sych_marker \""; stream.write(p->sych_marker, 8); stream << "\"\n\t rng_ref_src \""; stream.write(p->rng_ref_src, 12); stream << "\"\n\t rng_amp_coef[0] \""; stream.write(p->rng_amp_coef[0],16); stream << "\"\n\t rng_amp_coef[1] \""; stream.write(p->rng_amp_coef[1],16); stream << "\"\n\t rng_amp_coef[2] \""; stream.write(p->rng_amp_coef[2],16); stream << "\"\n\t rng_amp_coef[3] \""; stream.write(p->rng_amp_coef[3],16); stream << "\"\n\t rng_phas_coef[0] \""; stream.write(p->rng_phas_coef[0], 16); stream << "\"\n\t rng_phas_coef[1] \""; stream.write(p->rng_phas_coef[1], 16); stream << "\"\n\t rng_phas_coef[2] \""; stream.write(p->rng_phas_coef[2], 16); stream << "\"\n\t rng_phas_coef[3] \""; stream.write(p->rng_phas_coef[3], 16); stream << "\"\n\t err_amp_coef[0] \""; stream.write(p->err_amp_coef[0],16); stream << "\"\n\t err_amp_coef[1] \""; stream.write(p->err_amp_coef[1],16); stream << "\"\n\t err_amp_coef[2] \""; stream.write(p->err_amp_coef[2],16); stream << "\"\n\t err_amp_coef[3] \""; stream.write(p->err_amp_coef[3],16); stream << "\"\n\t err_phas_coef[0] \""; stream.write(p->err_phas_coef[0], 16); stream << "\"\n\t err_phas_coef[1] \""; stream.write(p->err_phas_coef[1], 16); stream << "\"\n\t err_phas_coef[2] \""; stream.write(p->err_phas_coef[2], 16); stream << "\"\n\t err_phas_coef[3] \""; stream.write(p->err_phas_coef[3], 16); stream << "\"\n\t pulse_bandw \""; stream.write(p->pulse_bandw, 4); stream << "\"\n\t adc_samp_rate \""; stream.write(p->adc_samp_rate, 5); stream << "\"\n\t rep_agc_attn \""; stream.write(p->rep_agc_attn, 16); stream << "\"\n\t gn_corctn_fctr \""; stream.write(p->gn_corctn_fctr, 16); stream << "\"\n\t rep_energy_gn \""; stream.write(p->rep_energy_gn,16); stream << "\"\n\t orb_data_src \""; stream.write(p->orb_data_src, 11); stream << "\"\n\t pulse_cnt_1 \""; stream.write(p->pulse_cnt_1, 4); stream << "\"\n\t pulse_cnt_2 \""; stream.write(p->pulse_cnt_2, 4); stream << "\"\n\t beam_edge_rqd \""; stream.write(p->beam_edge_rqd, 3); stream << "\"\n\t beam_edge_conf \""; stream.write(p->beam_edge_conf, 16); stream << "\"\n\t pix_overlap \""; stream.write(p->pix_overlap, 4); stream << "\"\n\t n_beams \""; stream.write(p->n_beams, 4); stream << "\"\n\t [Use debugger to view contents of beam_info record] "; stream << "\n\t n_pix_updates \""; stream.write(p->n_pix_updates, 4); stream << "\"\n\t [Use debugger to view contents of pix_count record] "; stream << "\n\t pwin_start \""; stream.write(p->pwin_start, 16); stream << "\"\n\t pwin_end \""; stream.write(p->pwin_end, 16); stream << "\"\n\t recd_type \""; stream.write(p->recd_type, 9); stream << "\"\n\t temp_set_inc \""; stream.write(p->temp_set_inc, 16); stream << "\"\n\t n_temp_set \""; stream.write(p->n_temp_set, 4); stream << "\"\n\t [Use debugger to view contents of temp record] "; stream << "\n\t n_image_pix \""; stream.write(p->n_image_pix, 8); stream << "\"\n\t prc_zero_pix \""; stream.write(p->prc_zero_pix, 16); stream << "\"\n\t prc_satur_pix \""; stream.write(p->prc_satur_pix,16); stream << "\"\n\t img_hist_mean \""; stream.write(p->img_hist_mean,16); stream << "\"\n\t img_cumu_dist[0] \""; stream.write(p->img_cumu_dist[0], 16); stream << "\"\n\t img_cumu_dist[1] \""; stream.write(p->img_cumu_dist[1], 16); stream << "\"\n\t img_cumu_dist[2] \""; stream.write(p->img_cumu_dist[2], 16); stream << "\"\n\t pre_img_gn \""; stream.write(p->pre_img_gn, 16); stream << "\"\n\t post_img_gn \""; stream.write(p->post_img_gn, 16); stream << "\"\n\t dopcen_inc \""; stream.write(p->dopcen_inc, 16); stream << "\"\n\t n_dopcen \""; stream.write(p->n_dopcen, 4); stream << "\"\n\t [Use debugger to view contents of dopcen_est record] "; stream << "\n\t dop_amb_err \""; stream.write(p->dop_amb_err, 4); stream << "\"\n\t dopamb_conf \""; stream.write(p->dopamb_conf, 16); stream << "\"\n\t eph_orb_data[0] \""; stream.write(p->eph_orb_data[0],16); stream << "\"\n\t eph_orb_data[1] \""; stream.write(p->eph_orb_data[1],16); stream << "\"\n\t eph_orb_data[2] \""; stream.write(p->eph_orb_data[2],16); stream << "\"\n\t eph_orb_data[3] \""; stream.write(p->eph_orb_data[3],16); stream << "\"\n\t eph_orb_data[4] \""; stream.write(p->eph_orb_data[4],16); stream << "\"\n\t eph_orb_data[5] \""; stream.write(p->eph_orb_data[5],16); stream << "\"\n\t eph_orb_data[6] \""; stream.write(p->eph_orb_data[6],16); stream << "\"\n\t appl_type \""; stream.write(p->appl_type, 12); stream << "\"\n\t slow_time_coef[1] \""; stream.write(p->slow_time_coef[1], 22); stream << "\"\n\t slow_time_coef[2] \""; stream.write(p->slow_time_coef[2], 22); stream << "\"\n\t slow_time_coef[3] \""; stream.write(p->slow_time_coef[3], 22); stream << "\"\n\t slow_time_coef[4] \""; stream.write(p->slow_time_coef[4], 22); stream << "\"\n\t n_srgr \""; stream.write(p->n_srgr, 4); stream << "\"\n\t [Use debugger to view contents of srgr_coefset record]"; stream << "\n\t pixel_spacing \""; stream.write(p->pixel_spacing,16); stream << "\"\n\t gics_reqd \""; stream.write(p->gics_reqd, 3); stream << "\"\n\t wo_number \""; stream.write(p->wo_number, 8); stream << "\"\n\t wo_date \""; stream.write(p->wo_date, 20); stream << "\"\n\t satellite_id \""; stream.write(p->satellite_id, 10); stream << "\"\n\t user_id \""; stream.write(p->user_id, 20); stream << "\"\n\t complete_msg \""; stream.write(p->complete_msg, 3); stream << "\"\n\t scene_id \""; stream.write(p->scene_id, 5); stream << "\"\n\t density_in \""; stream.write(p->density_in, 4); stream << "\"\n\t media_id \""; stream.write(p->media_id, 8); stream << "\"\n\t angle_first \""; stream.write(p->angle_first, 16); stream << "\"\n\t angle_last \""; stream.write(p->angle_last, 16); stream << "\"\n\t prod_type \""; stream.write(p->prod_type, 3); stream << "\"\n\t map_system \""; stream.write(p->map_system, 16); stream << "\"\n\t centre_lat \""; stream.write(p->centre_lat, 22); stream << "\"\n\t centre_long \""; stream.write(p->centre_long, 22); stream << "\"\n\t span_x \""; stream.write(p->span_x, 22); stream << "\"\n\t span_y \""; stream.write(p->span_y, 22); stream << "\"\n\t apply_dtm \""; stream.write(p->apply_dtm, 3); stream << "\"\n\t density_out \""; stream.write(p->density_out, 4); stream << "\"\n\t state_time \""; stream.write(p->state_time, 21); stream << "\"\n\t num_state_vectors \""; stream.write(p->num_state_vectors, 4); stream << "\"\n\t state_time_inc \""; stream.write(p->state_time_inc, 16); stream << "\"" << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpMapProjRec() // //****************************************************************************** void ossimCeosData::dumpMapProjRec(ostream& stream) const { const map_proj_rec* p = theMapProjRec; stream << "\n\n\tContents of map_proj_rec:\n\t"; stream << "\n\t spare1 \""; stream.write(p->spare1, 16); stream << "\"\n\t map_desc \""; stream.write(p->map_desc, 32); stream << "\"\n\t n_pixel \""; stream.write(p->n_pixel, 16); stream << "\"\n\t n_line \""; stream.write(p->n_line, 16); stream << "\"\n\t pixel_spacing \""; stream.write(p->pixel_spacing,16); stream << "\"\n\t line_spacing \""; stream.write(p->line_spacing, 16); stream << "\"\n\t osc_orient \""; stream.write(p->osc_orient, 16); stream << "\"\n\t orb_incl \""; stream.write(p->orb_incl, 16); stream << "\"\n\t asc_node \""; stream.write(p->asc_node, 16); stream << "\"\n\t isc_dist \""; stream.write(p->isc_dist, 16); stream << "\"\n\t geo_alt \""; stream.write(p->geo_alt, 16); stream << "\"\n\t isc_vel \""; stream.write(p->isc_vel, 16); stream << "\"\n\t plat_head \""; stream.write(p->plat_head, 16); stream << "\"\n\t ref_ellip \""; stream.write(p->ref_ellip, 32); stream << "\"\n\t semi_major \""; stream.write(p->semi_major, 16); stream << "\"\n\t semi_minor \""; stream.write(p->semi_minor, 16); stream << "\"\n\t datum_shift[0] \""; stream.write(p->datum_shift[0], 16); stream << "\"\n\t datum_shift[1] \""; stream.write(p->datum_shift[1], 16); stream << "\"\n\t datum_shift[2] \""; stream.write(p->datum_shift[2], 16); stream << "\"\n\t aux_datum_shift[0] \""; stream.write(p->aux_datum_shift[0], 16); stream << "\"\n\t aux_datum_shift[1] \""; stream.write(p->aux_datum_shift[1], 16); stream << "\"\n\t aux_datum_shift[2] \""; stream.write(p->aux_datum_shift[2], 16); stream << "\"\n\t scal_ellip \""; stream.write(p->scal_ellip, 16); stream << "\"\n\t proj_desc \""; stream.write(p->proj_desc, 32); stream << "\"\n\t utm_desc \""; stream.write(p->utm_desc, 32); stream << "\"\n\t utm_zone_sig \""; stream.write(p->utm_zone_sig, 4); stream << "\"\n\t utm_east_orig \""; stream.write(p->utm_east_orig,16); stream << "\"\n\t utm_north_orig \""; stream.write(p->utm_north_orig, 16); stream << "\"\n\t utm_cent_long \""; stream.write(p->utm_cent_long,16); stream << "\"\n\t utm_cent_lat \""; stream.write(p->utm_cent_lat, 16); stream << "\"\n\t utm_stand_par[0] \""; stream.write(p->utm_stand_par[0], 16); stream << "\"\n\t utm_stand_par[1] \""; stream.write(p->utm_stand_par[1], 16); stream << "\"\n\t utm_scale \""; stream.write(p->utm_scale, 16); stream << "\"\n\t ups_desc \""; stream.write(p->ups_desc, 32); stream << "\"\n\t ups_cent_long \""; stream.write(p->ups_cent_long,16); stream << "\"\n\t ups_cent_lat \""; stream.write(p->ups_cent_lat, 16); stream << "\"\n\t ups_scale \""; stream.write(p->ups_scale, 16); stream << "\"\n\t nsp_desc \""; stream.write(p->nsp_desc, 32); stream << "\"\n\t nsp_east_orig \""; stream.write(p->nsp_east_orig,16); stream << "\"\n\t nsp_north_orig \""; stream.write(p->nsp_north_orig,16); stream << "\"\n\t nsp_cent_long \""; stream.write(p->nsp_cent_long,16); stream << "\"\n\t nsp_cent_lat \""; stream.write(p->nsp_cent_lat, 16); stream << "\"\n\t nsp_stand_par[0] \""; stream.write(p->nsp_stand_par[0], 16); stream << "\"\n\t nsp_stand_par[1] \""; stream.write(p->nsp_stand_par[1], 16); stream << "\"\n\t nsp_stand_par[2] \""; stream.write(p->nsp_stand_par[2], 16); stream << "\"\n\t nsp_stand_par[3] \""; stream.write(p->nsp_stand_par[3], 16); stream << "\"\n\t nsp_stand_mer[0] \""; stream.write(p->nsp_stand_mer[0], 16); stream << "\"\n\t nsp_stand_mer[1] \""; stream.write(p->nsp_stand_mer[1], 16); stream << "\"\n\t nsp_stand_mer[2] \""; stream.write(p->nsp_stand_mer[2], 16); stream << "\"\n\t nsp_spare[0] \""; stream.write(p->nsp_spare[0], 16); stream << "\"\n\t nsp_spare[1] \""; stream.write(p->nsp_spare[1], 16); stream << "\"\n\t nsp_spare[2] \""; stream.write(p->nsp_spare[2], 16); stream << "\"\n\t nsp_spare[3] \""; stream.write(p->nsp_spare[3], 16); stream << "\"\n\t corner_ne[0] \""; stream.write(p->corner_ne[0], 16); stream << "\"\n\t corner_ne[1] \""; stream.write(p->corner_ne[1], 16); stream << "\"\n\t corner_ne[2] \""; stream.write(p->corner_ne[2], 16); stream << "\"\n\t corner_ne[3] \""; stream.write(p->corner_ne[3], 16); stream << "\"\n\t corner_ne[4] \""; stream.write(p->corner_ne[4], 16); stream << "\"\n\t corner_ne[5] \""; stream.write(p->corner_ne[5], 16); stream << "\"\n\t corner_ne[6] \""; stream.write(p->corner_ne[6], 16); stream << "\"\n\t corner_ne[7] \""; stream.write(p->corner_ne[7], 16); stream << "\"\n\t corner_ll[0] \""; stream.write(p->corner_ll[0], 16); stream << "\"\n\t corner_ll[1] \""; stream.write(p->corner_ll[1], 16); stream << "\"\n\t corner_ll[2] \""; stream.write(p->corner_ll[2], 16); stream << "\"\n\t corner_ll[3] \""; stream.write(p->corner_ll[3], 16); stream << "\"\n\t corner_ll[4] \""; stream.write(p->corner_ll[4], 16); stream << "\"\n\t corner_ll[5] \""; stream.write(p->corner_ll[5], 16); stream << "\"\n\t corner_ll[6] \""; stream.write(p->corner_ll[6], 16); stream << "\"\n\t corner_ll[7] \""; stream.write(p->corner_ll[7], 16); stream << "\"\n\t terr_height[0] \""; stream.write(p->terr_height[0], 16); stream << "\"\n\t terr_height[1] \""; stream.write(p->terr_height[1], 16); stream << "\"\n\t terr_height[2] \""; stream.write(p->terr_height[2], 16); stream << "\"\n\t terr_height[3] \""; stream.write(p->terr_height[3], 16); stream << "\"\n\t lp_conv_coef[0] \""; stream.write(p->lp_conv_coef[0],20); stream << "\"\n\t lp_conv_coef[1] \""; stream.write(p->lp_conv_coef[1],20); stream << "\"\n\t lp_conv_coef[2] \""; stream.write(p->lp_conv_coef[2],20); stream << "\"\n\t lp_conv_coef[3] \""; stream.write(p->lp_conv_coef[3],20); stream << "\"\n\t lp_conv_coef[4] \""; stream.write(p->lp_conv_coef[4],20); stream << "\"\n\t lp_conv_coef[5] \""; stream.write(p->lp_conv_coef[5],20); stream << "\"\n\t lp_conv_coef[6] \""; stream.write(p->lp_conv_coef[6],20); stream << "\"\n\t lp_conv_coef[7] \""; stream.write(p->lp_conv_coef[7],20); stream << "\"\n\t mp_conv_coef[0] \""; stream.write(p->mp_conv_coef[0],20); stream << "\"\n\t mp_conv_coef[1] \""; stream.write(p->mp_conv_coef[1],20); stream << "\"\n\t mp_conv_coef[2] \""; stream.write(p->mp_conv_coef[2],20); stream << "\"\n\t mp_conv_coef[3] \""; stream.write(p->mp_conv_coef[3],20); stream << "\"\n\t mp_conv_coef[4] \""; stream.write(p->mp_conv_coef[4],20); stream << "\"\n\t mp_conv_coef[5] \""; stream.write(p->mp_conv_coef[5],20); stream << "\"\n\t mp_conv_coef[6] \""; stream.write(p->mp_conv_coef[6],20); stream << "\"\n\t mp_conv_coef[7] \""; stream.write(p->mp_conv_coef[7],20); stream << "\"\n\t dem_type \""; stream.write(p->dem_type, 4); stream << "\"\n\t spare3 \""; stream.write(p->spare3, 32); stream << "\"" << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpPosDataRec() // //****************************************************************************** void ossimCeosData::dumpPosDataRec(ostream& stream) const { const pos_data_rec* p = thePosDataRec; stream << "\n\n\tContents of pos_data_rec:\n\t"; stream << "\n\t orbit_ele_desg \""; stream.write(p->orbit_ele_desg, 32); stream << "\"\n\t orbit_ele[0] \""; stream.write(p->orbit_ele[0], 16); stream << "\"\n\t orbit_ele[1] \""; stream.write(p->orbit_ele[1], 16); stream << "\"\n\t orbit_ele[2] \""; stream.write(p->orbit_ele[2], 16); stream << "\"\n\t orbit_ele[3] \""; stream.write(p->orbit_ele[3], 16); stream << "\"\n\t orbit_ele[4] \""; stream.write(p->orbit_ele[4], 16); stream << "\"\n\t orbit_ele[5] \""; stream.write(p->orbit_ele[5], 16); stream << "\"\n\t ndata \""; stream.write(p->ndata, 4); stream << "\"\n\t year \""; stream.write(p->year, 4); stream << "\"\n\t month \""; stream.write(p->month, 4); stream << "\"\n\t day \""; stream.write(p->day, 4); stream << "\"\n\t gmt_day \""; stream.write(p->gmt_day, 4); stream << "\"\n\t gmt_sec \""; stream.write(p->gmt_sec, 22); stream << "\"\n\t data_int \""; stream.write(p->data_int, 22); stream << "\"\n\t ref_coord \""; stream.write(p->ref_coord, 64); stream << "\"\n\t hr_angle \""; stream.write(p->hr_angle, 22); stream << "\"\n\t alt_poserr \""; stream.write(p->alt_poserr, 16); stream << "\"\n\t crt_poserr \""; stream.write(p->crt_poserr, 16); stream << "\"\n\t rad_poserr \""; stream.write(p->rad_poserr, 16); stream << "\"\n\t alt_velerr \""; stream.write(p->alt_velerr, 16); stream << "\"\n\t crt_velerr \""; stream.write(p->crt_velerr, 16); stream << "\"\n\t rad_velerr \""; stream.write(p->rad_velerr, 16); stream << "\"\n\t [Use debugger to view contents of pos_vect record]"; stream << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpAttDataRec() // //****************************************************************************** void ossimCeosData::dumpAttDataRec(ostream& stream) const { const att_data_rec* p = theAttDataRec; stream << "\n\n\tContents of att_data_rec:\n\t"; stream << "\n\t npoint \""; stream.write(p->npoint, 4); stream << "\"\n\t [Use debugger to view contents of att_vect record]"; stream << "\n\t pitch_bias \""; stream.write(p->pitch_bias, 14); stream << "\"\n\t roll_bias \""; stream.write(p->roll_bias, 14); stream << "\"\n\t yaw_bias \""; stream.write(p->yaw_bias, 14); stream << "\"" << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpRadiDataRec() // //****************************************************************************** void ossimCeosData::dumpRadiDataRec(ostream& stream) const { const radi_data_rec* p = theRadiDataRec; stream << "\n\n\tContents of radi_data_rec:\n\t"; stream << "\n\t seq_num \""; stream.write(p->seq_num, 4); stream << "\"\n\t n_data \""; stream.write(p->n_data, 4); stream << "\"\n\t field_size \""; stream.write(p->field_size, 8); stream << "\"\n\t [Use debugger to view contents of dset record]"; stream << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::dumpRadiCompRec() // //****************************************************************************** void ossimCeosData::dumpRadiCompRec(ostream& stream) const { const radi_comp_rec* p = theRadiCompRec; stream << "\n\n\tContents of radi_comp_rec:\n\t"; stream << "\n\t seq_num \""; stream.write(p->seq_num, 4); stream << "\"\n\t chan_ind \""; stream.write(p->chan_ind, 4); stream << "\"\n\t n_dset \""; stream.write(p->n_dset, 8); stream << "\"\n\t dset_size \""; stream.write(p->dset_size, 8); stream << "\"\n\t [Use debugger to view contents of dset record]"; stream << endl; } //***************************************************************************** // PRIVATE METHOD: ossimCeosData::loadCeosRecords() // // Reads the data files and initializes the data members. // //***************************************************************************** void ossimCeosData::loadCeosRecords() { static const char MODULE[] = "ossimCeosData::loadCeosFile()"; if (traceExec()) CLOG << " Entered method." << endl; int sizeOfRec; char bufI6[] = "123456"; int numRecords; //*** // Open Volume Directory File and parse: //*** FILE* fptr = fopen(theVolDirFileName.chars(), "r"); if (!fptr) { if(traceDebug()) { CLOG << " ERROR:\n\tCannot open CEOS Volume Directory file: " << theVolDirFileName << endl; } theErrorStatus = ERROR; return; } sizeOfRec = sizeof(theVolumeDirectory); fread(&theVolumeDirectory, sizeOfRec, 1, fptr); fclose(fptr); theVolDescRec = &theVolumeDirectory.volDescRec; theTextRec = &theVolumeDirectory.textRec; if (traceDebug()) { CLOG << "DEBUG\n -- List of Records Present ---" << endl; } //*** // Open and parse Leader File: //*** if (!theLeaderFileName.empty()) { fptr = fopen(theLeaderFileName.chars(), "r"); if (!fptr) { if(traceDebug()) { CLOG << " ERROR:\n\tCannot open CEOS Leader file: " << theLeaderFileName << endl; } theErrorStatus = ERROR; return; } fread(&(theSarLeaderFile.sarDescRec), 720, 1, fptr); //*** // Establish which CEOS records are in the leader file, and read them. // First the dataset summary record: //*** strncpy(bufI6, theSarLeaderFile.sarDescRec.n_dataset, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&theSarLeaderFile.dataSetSumRec, sizeOfNextRec(fptr), 1, fptr); theDataSetSumRec = &(theSarLeaderFile.dataSetSumRec); if (traceDebug()) clog << "\t Leader: dataSetSumRec" << endl; } //*** // Data quality summary record: //*** strncpy(bufI6, theSarLeaderFile.sarDescRec.n_qual_sum, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarLeaderFile.qualSumRec), sizeOfNextRec(fptr), 1, fptr); theQualSumRec = &(theSarLeaderFile.qualSumRec); if (traceDebug()) clog << "\t Leader: qualSumRec" << endl; } //*** // Histogram records: //*** strncpy(bufI6, theSarLeaderFile.sarDescRec.n_data_hist, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarLeaderFile.sdrHistRec), sizeOfNextRec(fptr), 1, fptr); theSdrHistRec = &(theSarLeaderFile.sdrHistRec); fread(&(theSarLeaderFile.pdr16HistRec), sizeOfNextRec(fptr), 1, fptr); thePdr16HistRec = &(theSarLeaderFile.pdr16HistRec); if (traceDebug()) clog << "\t Leader: sdrHistRec & pdr16HistRec" << endl; } //*** // Processing parameter record: //*** strncpy(bufI6, theSarLeaderFile.sarDescRec.n_det_proc, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarLeaderFile.procParmRec), sizeOfNextRec(fptr), 1, fptr); theProcParmRec = &(theSarLeaderFile.procParmRec); if (traceDebug()) clog << "\t Leader: procParmRec" << endl; } //*** // Map projection record: //*** strncpy(bufI6, theSarLeaderFile.sarDescRec.n_map_proj, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarLeaderFile.mapProjRec), sizeOfNextRec(fptr), 1, fptr); theMapProjRec = &(theSarLeaderFile.mapProjRec); if (traceDebug()) clog << "\t Leader: mapProjRec" << endl; } //*** // Position data record: //*** strncpy(bufI6, theSarLeaderFile.sarDescRec.n_plat_pos, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarLeaderFile.posDataRec), sizeOfNextRec(fptr), 1, fptr); thePosDataRec = &(theSarLeaderFile.posDataRec); if (traceDebug()) clog << "\t Leader: posDataRec" << endl; } //*** // Attitude data record: //*** strncpy(bufI6, theSarLeaderFile.sarDescRec.n_att_data, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarLeaderFile.attDataRec), sizeOfNextRec(fptr), 1, fptr); theAttDataRec = &(theSarLeaderFile.attDataRec); if (traceDebug()) clog << "\t Leader: attDataRec" << endl; } //*** // Radiometric data record: //*** strncpy(bufI6, theSarLeaderFile.sarDescRec.n_radi_data, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarLeaderFile.radiDataRec), sizeOfNextRec(fptr), 1, fptr); theRadiDataRec = &(theSarLeaderFile.radiDataRec); if (traceDebug()) clog << "\t Leader: radiDataRec" << endl; } //*** // Radiometric compensation data record: //*** strncpy(bufI6, theSarLeaderFile.sarDescRec.n_radi_comp, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarLeaderFile.radiCompRec), sizeOfNextRec(fptr), 1, fptr); theRadiCompRec = &(theSarLeaderFile.radiCompRec); if (traceDebug()) clog << "\t Leader: radiCompRec" << endl; } fclose(fptr); } //*** // Open and parse CEOS SAR data File to read the image options: //*** fptr = fopen(theImageFileName.chars(), "r"); if (!fptr) { CLOG << " ERROR:\n\tCannot open CEOS image file: " << theImageFileName << endl; theErrorStatus = ERROR; return; } sizeOfRec = sizeof(theImopDescRec); fread(&theImopDescRec, sizeOfRec, 1, fptr); fclose(fptr); //*** // Open and parse trailer file: //*** if (!theTrailerFileName.empty()) { fptr = fopen(theTrailerFileName.chars(), "r"); if (!fptr) { CLOG << " ERROR:\n\tCannot open CEOS Trailer file: " << theTrailerFileName << endl; theErrorStatus = ERROR; return; } fread(&(theSarTrailerFile.sarDescRec), 720, 1, fptr); //*** // Establish which CEOS records are in the Trailer file, and read them. // First the dataset summary record: //*** strncpy(bufI6, theSarTrailerFile.sarDescRec.n_dataset, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarTrailerFile.dataSetSumRec), sizeOfNextRec(fptr),1, fptr); theDataSetSumRec = &(theSarTrailerFile.dataSetSumRec); if (traceDebug()) clog << "\t Trailer: dataSetSumRec" << endl; } //*** // Data quality summary record: //*** strncpy(bufI6, theSarTrailerFile.sarDescRec.n_qual_sum, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarTrailerFile.qualSumRec), sizeOfNextRec(fptr), 1, fptr); theQualSumRec = &(theSarTrailerFile.qualSumRec); if (traceDebug()) clog << "\t Trailer: qualSumRec" << endl; } //*** // Histogram records: //*** strncpy(bufI6, theSarTrailerFile.sarDescRec.n_data_hist, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarTrailerFile.sdrHistRec), sizeOfNextRec(fptr), 1, fptr); theSdrHistRec = &(theSarTrailerFile.sdrHistRec); fread(&(theSarTrailerFile.pdr8HistRec), 16920, 1, fptr); thePdr8HistRec = &(theSarTrailerFile.pdr8HistRec); if (traceDebug()) clog << "\t Trailer: sdrHistRec & pdr8HistRec" << endl; } //*** // Processing parameter record: //*** strncpy(bufI6, theSarTrailerFile.sarDescRec.n_det_proc, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarTrailerFile.procParmRec), sizeOfNextRec(fptr), 1, fptr); theProcParmRec = &(theSarTrailerFile.procParmRec); if (traceDebug()) clog << "\t Trailer: procParmRec" << endl; } //*** // Attitude data record: //*** strncpy(bufI6, theSarTrailerFile.sarDescRec.n_att_data, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarTrailerFile.attDataRec), sizeOfNextRec(fptr), 1, fptr); theAttDataRec = &(theSarTrailerFile.attDataRec); if (traceDebug()) clog << "\t Trailer: attDataRec" << endl; } //*** // Radiometric data record: //*** strncpy(bufI6, theSarTrailerFile.sarDescRec.n_radi_data, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarTrailerFile.radiDataRec), sizeOfNextRec(fptr), 1, fptr); theRadiDataRec = &(theSarTrailerFile.radiDataRec); if (traceDebug()) clog << "\t Trailer: radiDataRec" << endl; } //*** // Radiometric compensation data record: //*** strncpy(bufI6, theSarTrailerFile.sarDescRec.n_radi_comp, 6); numRecords = atoi(bufI6); if (numRecords) { fread(&(theSarTrailerFile.radiCompRec), sizeOfNextRec(fptr), 1, fptr); theRadiCompRec = &(theSarTrailerFile.radiCompRec); if (traceDebug()) clog << "\t Trailer: radiCompRec" << endl; } fclose(fptr); } if (traceExec()) CLOG << " Exiting method." << endl; } //****************************************************************************** // PRIVATE METHOD: ossimCeosData::sizeOfNextRec(FILE*) // // Reads the descriptor record pointed to by the file ptr and returns the // size of the following record in bytes. // //****************************************************************************** int ossimCeosData::sizeOfNextRec(FILE* fptr) { static const char MODULE[] = "ossimCeosData::sizeOfNextRec(FILE* fptr)"; if (traceExec()) CLOG << "entering..." << endl; static desc_rec descRec; static int DESC_REC_SIZE = 12; fread(&descRec, DESC_REC_SIZE, 1, fptr); fseek(fptr, (long) -DESC_REC_SIZE, SEEK_CUR); if (traceDebug()) { CLOG << "DEBUG -- " << "\n\t length = " << descRec.length << endl; } if (traceExec()) CLOG << "returning..." << endl; return descRec.length; } ossim-Miami-2.9.1/src/support_data/ossimDemGrid.cpp000066400000000000000000000140511352751253100223020ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero (kmelero@imagelinks.com) // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class defines a DEM grid. // //******************************************************************** // $Id$ #include #include #include #include #include ossimDemGrid::ossimDemGrid(ossim_float32 missingDataValue) : _missDataVal(missingDataValue), _width(0), _height(0), _grid(0), _firstTime(true), _curProfile(0) { } ossimDemGrid::~ossimDemGrid() { if(_grid) { delete [] _grid; _grid =0; } } long ossimDemGrid::read(ossim::istream& dem, bool incrementalRead) { if (_firstTime) { dem >> _header; } long retval; if (_header.getGroundRefSysCode() == 0) // Geographic retval = fillGeographic(dem,incrementalRead); else retval = fillUTM(dem,incrementalRead); // This may not work if it's // really in State Plane. if (_firstTime) _firstTime = false; return retval; } ossimDemHeader const& ossimDemGrid::getHeader() const { return _header; } long ossimDemGrid::getWidth() const { return _width; } long ossimDemGrid::getHeight() const { return _height; } ossim_float32 ossimDemGrid::getElevation(long x, long y) const { if (_grid == 0) return _missDataVal; if ((x < 0) || (y < 0) || (x >= _width) || (y >= _height)) return _missDataVal; return _grid[(y * _width) + x]; } ossim_float32 ossimDemGrid::getMissingDataValue() const { return _missDataVal; } long ossimDemGrid::fillGeographic(ossim::istream& dem,bool incrementalRead) { if (_firstTime) { _curProfile = 0; _width = _header.getProfileColumns(); } while (_curProfile < _width) { _profiles.push_back(ossimDemProfile()); dem >> _profiles.back(); _curProfile++; if (incrementalRead) return _width - _curProfile + 1; } // Assume all profiles have as many elevations as the first. _height = _profiles[0].getNumberOfElevations(); if(_grid) { delete [] _grid; _grid =0; } _grid = new ossim_float32[_width * _height]; ossimDemPoint sw_corner = _profiles[0].getProfileLocation(); _northwest_x = sw_corner.getX(); _northwest_y = sw_corner.getY() + ((_profiles[0].getNumberOfElevations() - 1) * _header.getSpatialResY()); unsigned int i,j; for (i = 0; (int)i < _width; i++) { ossimDemElevationVector const& elev = _profiles[i].getElevations(); for (j = 0; j < elev.size(); j++) { setElevation(i, _height - j - 1, elev[j]); } } _profiles.erase(_profiles.begin(), _profiles.end()); return 0; } long ossimDemGrid::fillUTM(ossim::istream& dem, bool incrementalRead) { // 7.5 UTM DEMs are small enough we can get away with doing this stupid... unsigned int i; unsigned int x,y; if (_firstTime) { _curProfile = 0; _width = _header.getProfileColumns(); } while (_curProfile < _width) { _profiles.push_back(ossimDemProfile()); dem >> _profiles.back(); _curProfile++; if (incrementalRead) return _width - _curProfile + 1; } double dy = _header.getSpatialResY(); // Determine min and max Y values. // Some DEMs can have profiles which do not have any // elevations, and erroneous (x,y) values. I suspect // these are probably illegal DEMs, but we'll try to // do the right thing anyway. ossimDemPoint curpoint; i = 0; while ((_profiles[i].getNumberOfElevations() == 0) && (i < _profiles.size())) i++; if (i < _profiles.size()) curpoint = _profiles[i].getProfileLocation(); else { // XXX This isn't the best way to handle this... ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimDemGrid::fillUTM: Yikes! All profiles have zero elevations!\n"; return(1); } double miny, maxy; miny = curpoint.getY(); maxy = miny; double profymin, profymax; // Min and max y values for current profile. for (i = 0; i < _profiles.size(); i++) { if (_profiles[i].getNumberOfElevations() > 0) { curpoint = _profiles[i].getProfileLocation(); profymin = curpoint.getY(); profymax = profymin + ((_profiles[i].getNumberOfElevations() - 1) * dy); if (profymin < miny) miny = profymin; if (profymax > maxy) maxy = profymax; } } // We now have minimum and maximum y values over all profiles in the DEM. // Allocate a rectangular array large enough to hold them. _height = static_cast(((maxy - miny) / dy) + 1); if(_grid) { delete [] _grid; _grid =0; } _grid = new ossim_float32[_width * _height]; // Fill grid with the "missing data" value. for (i = 0; (int)i < _width * _height; i++) _grid[i] = _missDataVal; ossimDemPoint sw_corner = _profiles[0].getProfileLocation(); _northwest_x = sw_corner.getX(); _northwest_y = maxy; // Now, insert the elevations in the profiles in the appropriate place in the grid. long startpos; for (x = 0; (int)x < _width; x++) { ossimDemElevationVector const& elev = _profiles[x].getElevations(); curpoint = _profiles[x].getProfileLocation(); startpos = static_cast((curpoint.getY() - miny) / dy); for (y = 0; y < elev.size(); y++) { setElevation(x, _height - startpos - y - 1, elev[y]); } } _profiles.erase(_profiles.begin(), _profiles.end()); return 0; } void ossimDemGrid::getGroundCoords(long x, long y, double& ground_x, double& ground_y) { ground_x = _northwest_x + (x * _header.getSpatialResX()); ground_y = _northwest_y - (y * _header.getSpatialResY()); } ossim-Miami-2.9.1/src/support_data/ossimDemHeader.cpp000066400000000000000000000540671352751253100226200ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class parses a DEM header. // //******************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include static const char* PROCESS_CODE[] = { "Autocorrelation resample simple bilinear", "Manual profile GRIDEM simple bilinear", "DLG/hypsography CTOG 8-direction bilinear", "Interpolation from photogrammetic system contours DCASS", "direction bilinear", "DLG/hypsography LINETRACE, LT4X complex linear", "DLG/hypsography CPS-3, ANUDEM, GRASS complex polynomial", "Electronic imaging (non-photogrammetric), active or passive", "sensor systems" }; static const int MAX_PROCESS_CODE_INDEX = 8; static const char* GROUND_REF_SYSTEM[] = { "Geographic", "UTM", "State Plane" }; static const int MAX_GROUND_REF_SYSTEM_INDEX = 2; static const char* GROUND_REF_SYSTEM_UNITS[] = { "Radians", "Feet", "Meters", "Arc Seconds" }; static const int MAX_GROUND_REF_SYSTEM_UNITS_INDEX = 3; static const char* VERTICAL_DATUM[] = { "local mean sea level", "National Geodetic Vertical Datum 1929", "North American Vertical Datum 1988" }; static const int MAX_VERTICAL_DATUM_INDEX = 2; static const char* HORIZONTAL_DATUM[] = { "North American Datum 1927 (NAD 27)", "World Geoditic System 1972 (WGS 72)", "WGS 84", "NAD 83", "Old Hawaii Datum", "Puerto Rico Datum" }; static const int MAX_HORIZONTAL_DATUM_INDEX = 5; ossimDemHeader::ossimDemHeader() : _seGeoCornerX(0.0), _seGeoCornerY(0.0), _processCode(0), _levelCode(0), _elevPattern(0), _groundRefSysCode(0), _groundRefSysZone(0), _groundRefSysUnits(0), _elevUnits(0), _numPolySides(0), _counterclockAngle(0.0), _elevAccuracyCode(0), _minElevation(0), _maxElevation(0), _spatialResX(0.0), _spatialResY(0.0), _spatialResZ(0.0), _profileRows(0), _profileColumns(0), _largeContInt(0), _maxSourceUnits(0), _smallContInt(0), _minSourceUnits(0), _sourceDate(0), _inspRevDate(0), _valFlag(0), _suspectVoidFlg(0), _vertDatum(0), _horizDatum(0), _dataEdition(0), _perctVoid(0), _westEdgeFlag(0), _northEdgeFlag(0), _eastEdgeFlag(0), _southEdgeFlag(0), _vertDatumShift(0.0) { } std::string const& ossimDemHeader::getQuadName() const { return _quadName; } std::string const& ossimDemHeader::getProcessInfo() const { return _processInfo; } double ossimDemHeader::getSEGeoCornerX() const { return _seGeoCornerX; } double ossimDemHeader::getSEGeoCornerY() const { return _seGeoCornerY; } ossim_int32 ossimDemHeader::getProcessCode() const { return _processCode; } std::string const& ossimDemHeader::getSectionIndicator() const { return _sectionIndicator; } std::string const& ossimDemHeader::getMappingCenterCode() const { return _mapCenterCode; } ossim_int32 ossimDemHeader::getLevelCode() const { return _levelCode; } ossim_int32 ossimDemHeader::getElevPattern() const { return _elevPattern; } ossim_int32 ossimDemHeader::getGroundRefSysCode() const { return _groundRefSysCode; } ossim_int32 ossimDemHeader::getGroundRefSysZone() const { return _groundRefSysZone; } ossim_int32 ossimDemHeader::getGroundRefSysUnits() const { return _groundRefSysUnits; } ossim_int32 ossimDemHeader::getElevationUnits() const { return _elevUnits; } ossim_int32 ossimDemHeader::getNumPolySides() const { return _numPolySides; } ossimDemPointVector const& ossimDemHeader::getDEMCorners() const { return _demCorners; } double ossimDemHeader::getCounterclockAngle() const { return _counterclockAngle; } ossim_int32 ossimDemHeader::getElevAccuracyCode() const { return _elevAccuracyCode; } double ossimDemHeader::getMinimumElev() const { return _minElevation; } double ossimDemHeader::getMaximumElev() const { return _maxElevation; } double ossimDemHeader::getSpatialResX() const { return _spatialResX; } double ossimDemHeader::getSpatialResY() const { return _spatialResY; } double ossimDemHeader::getSpatialResZ() const { return _spatialResZ; } ossim_int32 ossimDemHeader::getProfileRows() const { return _profileRows; } ossim_int32 ossimDemHeader::getProfileColumns() const { return _profileColumns; } ossim_int32 ossimDemHeader::getLargeContInt() const { return _largeContInt; } ossim_int32 ossimDemHeader::getMaxSourceUnits() const { return _maxSourceUnits; } ossim_int32 ossimDemHeader::getSmallContInt() const { return _smallContInt; } ossim_int32 ossimDemHeader::getMinSourceUnits() const { return _minSourceUnits; } ossim_int32 ossimDemHeader::getSourceDate() const { return _sourceDate; } ossim_int32 ossimDemHeader::getInspRevDate() const { return _inspRevDate; } std::string const& ossimDemHeader::getInspFlag() const { return _inspFlag; } ossim_int32 ossimDemHeader::getDataValFlag() const { return _valFlag; } ossim_int32 ossimDemHeader::getSuspectVoidFlag() const { return _suspectVoidFlg; } ossim_int32 ossimDemHeader::getVertDatum () const { return _vertDatum; } ossim_int32 ossimDemHeader::getHorizDatum() const { return _horizDatum; } ossim_int32 ossimDemHeader::getDataEdition() const { return _dataEdition; } ossim_int32 ossimDemHeader::getPerctVoid() const { return _perctVoid; } ossim_int32 ossimDemHeader::getWestEdgeFlag() const { return _westEdgeFlag; } ossim_int32 ossimDemHeader::getNorthEdgeFlag() const { return _northEdgeFlag; } ossim_int32 ossimDemHeader::getEastEdgeFlag() const { return _eastEdgeFlag; } ossim_int32 ossimDemHeader::getSouthEdgeFlag() const { return _southEdgeFlag; } double ossimDemHeader::getVertDatumShift() const { return _vertDatumShift; } std::ostream& operator<<(std::ostream& s, const ossimDemHeader& header) { return header.print(s); } bool ossimDemHeader::open(const ossimFilename& file) { bool result = ossimDemUtil::isUsgsDem(file); std::string connectionString = file.c_str(); std::shared_ptr is = ossim::StreamFactoryRegistry::instance()-> createIstream(connectionString, std::ios_base::in | std::ios_base::binary); if(result) { if ( is && is->good() ) { open( is, connectionString ); } else { result = false; } } return result; } bool ossimDemHeader::open(std::shared_ptr& str, const std::string& connectionString) { bool result = ossimDemUtil::isUsgsDem(ossimFilename(connectionString)); if ( result&&str&& str->good() ) { char* bufstr = new char[1024]; char* temp = new char[1024]; ossim_int32 i; ossimDemUtil::getRecord(*str, bufstr); strncpy(temp, bufstr, 40); temp[40] = '\0'; _quadName = temp; strncpy(temp,bufstr+40,40); temp[40] = '\0'; _processInfo = temp; ossimDemUtil::getDouble(bufstr, 109, 13, _seGeoCornerX); ossimDemUtil::getDouble(bufstr, 122, 13, _seGeoCornerY); _processCode = ossimDemUtil::getLong(bufstr, 135, 1); strncpy(temp,bufstr+137,3); temp[3] = '\0'; _sectionIndicator = temp; strncpy(temp,bufstr+140,4); temp[4] = '\0'; _mapCenterCode = temp; _levelCode = ossimDemUtil::getLong(bufstr, 144, 6); _elevPattern = ossimDemUtil::getLong(bufstr, 150, 6); _groundRefSysCode = ossimDemUtil::getLong(bufstr, 156, 6); _groundRefSysZone = ossimDemUtil::getLong(bufstr, 162, 6); _groundRefSysUnits = ossimDemUtil::getLong(bufstr, 528, 6); _elevUnits = ossimDemUtil::getLong(bufstr, 534, 6); _numPolySides = ossimDemUtil::getLong(bufstr, 540, 6); for (i = 0; i < 4; i++) { double x,y; ossim_int32 pos = 546 + (i * 48); ossimDemUtil::getDouble(bufstr, pos, 24, x); ossimDemUtil::getDouble(bufstr, pos + 24, 24, y); _demCorners.push_back(ossimDemPoint(x,y)); } ossimDemUtil::getDouble(bufstr, 738, 24, _minElevation); ossimDemUtil::getDouble(bufstr, 762, 24, _maxElevation); ossimDemUtil::getDouble(bufstr, 786, 24, _counterclockAngle ); _elevAccuracyCode = ossimDemUtil::getLong(bufstr, 810, 6); ossimDemUtil::getDouble(bufstr, 816, 12, _spatialResX); ossimDemUtil::getDouble(bufstr, 828, 12, _spatialResY); ossimDemUtil::getDouble(bufstr, 840, 12, _spatialResZ); _profileRows = ossimDemUtil::getLong(bufstr, 852, 6); _profileColumns = ossimDemUtil::getLong(bufstr, 858, 6); _largeContInt = ossimDemUtil::getLong(bufstr, 864, 5); _maxSourceUnits = ossimDemUtil::getLong(bufstr, 869, 1); _smallContInt = ossimDemUtil::getLong(bufstr, 870, 5); _minSourceUnits = ossimDemUtil::getLong(bufstr, 875, 1); _sourceDate = ossimDemUtil::getLong(bufstr, 876, 4); _inspRevDate = ossimDemUtil::getLong(bufstr, 880, 4); strncpy(temp, bufstr+884,1); temp[1]='\0'; _inspFlag = temp; _valFlag = ossimDemUtil::getLong(bufstr, 885, 1); _suspectVoidFlg = ossimDemUtil::getLong(bufstr, 886, 2); _vertDatum = ossimDemUtil::getLong(bufstr, 888, 2); _horizDatum = ossimDemUtil::getLong(bufstr, 890, 2); if (_horizDatum == 0) _horizDatum = 1; // Default to NAD27 _dataEdition = ossimDemUtil::getLong(bufstr, 892, 4); _perctVoid = ossimDemUtil::getLong(bufstr, 896, 4); _westEdgeFlag = ossimDemUtil::getLong(bufstr, 900, 2); _northEdgeFlag = ossimDemUtil::getLong(bufstr, 902, 2); _eastEdgeFlag = ossimDemUtil::getLong(bufstr, 904, 2); _southEdgeFlag = ossimDemUtil::getLong(bufstr, 906, 2); ossimDemUtil::getDouble(bufstr, 908, 7, _vertDatumShift); delete [] bufstr; delete [] temp; bufstr = 0; temp = 0; } return result; } std::istream& ossimDemHeader::open(ossim::istream& in) { if(in.good()) { char* bufstr = new char[1024]; char* temp = new char[1024]; ossim_int32 i; ossimDemUtil::getRecord(in, bufstr); strncpy(temp, bufstr, 40); temp[40] = '\0'; _quadName = temp; strncpy(temp,bufstr+40,40); temp[40] = '\0'; _processInfo = temp; ossimDemUtil::getDouble(bufstr, 109, 13, _seGeoCornerX); ossimDemUtil::getDouble(bufstr, 122, 13, _seGeoCornerY); _processCode = ossimDemUtil::getLong(bufstr, 135, 1); strncpy(temp,bufstr+137,3); temp[3] = '\0'; _sectionIndicator = temp; strncpy(temp,bufstr+140,4); temp[4] = '\0'; _mapCenterCode = temp; _levelCode = ossimDemUtil::getLong(bufstr, 144, 6); _elevPattern = ossimDemUtil::getLong(bufstr, 150, 6); _groundRefSysCode = ossimDemUtil::getLong(bufstr, 156, 6); _groundRefSysZone = ossimDemUtil::getLong(bufstr, 162, 6); _groundRefSysUnits = ossimDemUtil::getLong(bufstr, 528, 6); _elevUnits = ossimDemUtil::getLong(bufstr, 534, 6); _numPolySides = ossimDemUtil::getLong(bufstr, 540, 6); for (i = 0; i < 4; i++) { double x,y; ossim_int32 pos = 546 + (i * 48); ossimDemUtil::getDouble(bufstr, pos, 24, x); ossimDemUtil::getDouble(bufstr, pos + 24, 24, y); _demCorners.push_back(ossimDemPoint(x,y)); } ossimDemUtil::getDouble(bufstr, 738, 24, _minElevation); ossimDemUtil::getDouble(bufstr, 762, 24, _maxElevation); ossimDemUtil::getDouble(bufstr, 786, 24, _counterclockAngle ); _elevAccuracyCode = ossimDemUtil::getLong(bufstr, 810, 6); ossimDemUtil::getDouble(bufstr, 816, 12, _spatialResX); ossimDemUtil::getDouble(bufstr, 828, 12, _spatialResY); ossimDemUtil::getDouble(bufstr, 840, 12, _spatialResZ); _profileRows = ossimDemUtil::getLong(bufstr, 852, 6); _profileColumns = ossimDemUtil::getLong(bufstr, 858, 6); _largeContInt = ossimDemUtil::getLong(bufstr, 864, 5); _maxSourceUnits = ossimDemUtil::getLong(bufstr, 869, 1); _smallContInt = ossimDemUtil::getLong(bufstr, 870, 5); _minSourceUnits = ossimDemUtil::getLong(bufstr, 875, 1); _sourceDate = ossimDemUtil::getLong(bufstr, 876, 4); _inspRevDate = ossimDemUtil::getLong(bufstr, 880, 4); strncpy(temp, bufstr+884,1); temp[1]='\0'; _inspFlag = temp; _valFlag = ossimDemUtil::getLong(bufstr, 885, 1); _suspectVoidFlg = ossimDemUtil::getLong(bufstr, 886, 2); _vertDatum = ossimDemUtil::getLong(bufstr, 888, 2); _horizDatum = ossimDemUtil::getLong(bufstr, 890, 2); if (_horizDatum == 0) _horizDatum = 1; // Default to NAD27 _dataEdition = ossimDemUtil::getLong(bufstr, 892, 4); _perctVoid = ossimDemUtil::getLong(bufstr, 896, 4); _westEdgeFlag = ossimDemUtil::getLong(bufstr, 900, 2); _northEdgeFlag = ossimDemUtil::getLong(bufstr, 902, 2); _eastEdgeFlag = ossimDemUtil::getLong(bufstr, 904, 2); _southEdgeFlag = ossimDemUtil::getLong(bufstr, 906, 2); ossimDemUtil::getDouble(bufstr, 908, 7, _vertDatumShift); delete [] bufstr; delete [] temp; bufstr = 0; temp = 0; } return in; } std::ostream& ossimDemHeader::print(std::ostream& out) const { const int W = 24; // format width const int CW = W-8; // format corner width // Capture the original flags then set float output to full precision. std::ios_base::fmtflags f = out.flags(); // Note: This is only a partial print for now... std::string prefix = "usgs_dem."; out << std::setiosflags(std::ios_base::fixed|std::ios_base::left) << std::setprecision(10) << prefix << std::setw(W) << "quadrangle_name:" << getQuadName().c_str() << "\n" << prefix << std::setw(W) << "process_info:" << getProcessInfo().c_str() << "\n" << prefix << std::setw(W) << "se_geo_corner_x:" << getSEGeoCornerX() << "\n" << prefix << std::setw(W) << "se_geo_corner_y:" << getSEGeoCornerY() << "\n" << prefix << std::setw(W) << "process_code:"; ossim_int32 tmpl = getProcessCode() - 1; if ( tmpl >= 0 && tmpl <= MAX_PROCESS_CODE_INDEX) { out << PROCESS_CODE[tmpl] << "\n"; } else { out << "unknown" << "\n"; } out << prefix << std::setw(W) << "section_indicator: " << getSectionIndicator().c_str() << "\n" << prefix << std::setw(W) << "mapping_center_code: " << getMappingCenterCode().c_str() << "\n" << prefix << std::setw(W) << "level_code: " << getLevelCode() << "\n" << prefix << std::setw(W) << "elev_pattern: " << getElevPattern() << "\n" << prefix << std::setw(W) << "ground_ref_sys: "; tmpl = getGroundRefSysCode(); if ( tmpl >= 0 && tmpl <= MAX_GROUND_REF_SYSTEM_INDEX) { out << GROUND_REF_SYSTEM[tmpl] << "\n"; } else { out << "unknown\n"; } out << prefix << std::setw(W) << "ground_ref_sys_zone: " << getGroundRefSysZone() << "\n" << prefix << std::setw(W) << "ground_ref_sys_units:"; tmpl = getGroundRefSysUnits(); if ( tmpl >= 0 && tmpl <= MAX_GROUND_REF_SYSTEM_UNITS_INDEX) { out << GROUND_REF_SYSTEM_UNITS[tmpl] << "\n"; } else { out << "unknown\n"; } out << prefix << std::setw(W) << "elevation_units: "; tmpl = getElevationUnits(); if ( tmpl >= 0 && tmpl <= MAX_GROUND_REF_SYSTEM_UNITS_INDEX) { out << GROUND_REF_SYSTEM_UNITS[tmpl] << "\n"; } else { out << "unknown\n"; } out << prefix << std::setw(W) << "number_poly_sides: " << getNumPolySides() << "\n" << prefix << std::setw(W) << "counterclock_angle: " << getCounterclockAngle()<< "\n" << prefix << std::setw(W) << "elev_accuracy_code: " << getElevAccuracyCode()<< "\n" << prefix << std::setw(W) << "minimum_elevation: " << getMinimumElev() << "\n" << prefix << std::setw(W) << "maximum_elevation: " << getMaximumElev() << "\n" << prefix << std::setw(W) << "spatial_res_x: " << getSpatialResX() << "\n" << prefix << std::setw(W) << "spatial_res_y: " << getSpatialResY() << "\n" << prefix << std::setw(W) << "spatial_res_z:" << getSpatialResZ() << "\n" << prefix << std::setw(W) << "profile_rows: " << getProfileRows() << "\n" << prefix << std::setw(W) << "profile_columns:" << getProfileColumns() << "\n" << prefix << std::setw(W) << "source_date:" << getSourceDate() << "\n" << prefix << std::setw(W) << "revision_date:" << getInspRevDate() << "\n" << prefix << std::setw(W) << "vertical_datum:"; tmpl = getVertDatum() - 1; if ( tmpl >= 0 && tmpl <= MAX_VERTICAL_DATUM_INDEX) { out << VERTICAL_DATUM[tmpl] << "\n"; } else { out << "unknown\n"; } out << prefix << std::setw(W) << "vertical_datum_shift:" << getVertDatumShift() << "\n" << prefix << std::setw(W) << "horizontal_datum:"; tmpl = getHorizDatum() - 1; if ( tmpl >= 0 && tmpl <= MAX_HORIZONTAL_DATUM_INDEX) { out << HORIZONTAL_DATUM[tmpl] << "\n"; } else { out << "unknown\n"; } const ossimDemPointVector CORNERS = getDEMCorners(); for (unsigned int i=0; i < CORNERS.size(); ++i) { out << prefix << "corner[" << i << std::setw(CW)<< "].x: " << CORNERS[i].getX() << "\n" << prefix << "corner[" << i << std::setw(CW)<< "].y: " << CORNERS[i].getY() << "\n" << std::endl; } out << std::endl; // Reset flags. out.setf(f); return out; } ossim::istream& operator>>(ossim::istream& s, ossimDemHeader& header) { return header.open(s); } bool ossimDemHeader::getImageGeometry(ossimKeywordlist& kwl, const char* prefix) const { ossimString type = getProjectionType(); ossimString datum = getHorizDatumCode(); if ( (type == "unknown") || (datum == "unknown") ) { return false; } if (_demCorners.size() != 4) { return false; } double tieX = _demCorners[1].getX(); double tieY = _demCorners[1].getY(); double scaleX = getSpatialResX(); double scaleY = getSpatialResX(); // Add these for all projections. kwl.add(prefix, ossimKeywordNames::TYPE_KW, type); kwl.add(prefix, ossimKeywordNames::DATUM_KW, datum); if (getGroundRefSysCode() == 0) // Geographic. { // ESH 10/2008 -- The Dem ground units can be either radians or // arc seconds, so we have to convert parameters in these units // to degrees which is what OSSIM is assuming. bool bIsArcSecs = (getGroundRefSysUnits() == 3) ? true : false; bool bIsRadians = (getGroundRefSysUnits() == 0) ? true : false; double convertFactor = 1.0; if ( bIsArcSecs == true ) { convertFactor = 1.0 / 3600; } else if ( bIsRadians == true ) { convertFactor = 180.0 / M_PI; } kwl.add(prefix, ossimKeywordNames::TIE_POINT_LON_KW, (tieX * convertFactor) ); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LAT_KW, (tieY * convertFactor) ); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, (scaleX * convertFactor) ); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, (scaleY * convertFactor) ); } else if (getGroundRefSysCode() == 1) // UTM { // Get the zone. kwl.add(prefix, ossimKeywordNames::ZONE_KW, abs(getGroundRefSysZone())); // Set the hemisphere. kwl.add(prefix, ossimKeywordNames::HEMISPHERE_KW, (getGroundRefSysZone()<0?"S":"N")); // Set the tie. if (getGroundRefSysUnits() == 1) // Feet... { tieX = ossim::usft2mtrs(tieX); tieY = ossim::usft2mtrs(tieY); scaleX = ossim::usft2mtrs(scaleX); scaleY = ossim::usft2mtrs(scaleY); } kwl.add(prefix, ossimKeywordNames::TIE_POINT_EASTING_KW, tieX); kwl.add(prefix, ossimKeywordNames::TIE_POINT_NORTHING_KW, tieY); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_X_KW, scaleX); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW, scaleY); } else if (getGroundRefSysCode() == 2) // State Plane { return false; // Need to code... } return true; } ossimString ossimDemHeader::getHorizDatumCode() const { ossimString code; switch(getHorizDatum()) { case 1: code = "NAS-C"; break; case 2: code = "WGD"; break; case 3: code = "WGE"; break; case 4: code = "NAR-C"; break; case 5: code = "OHA-M"; break; case 6: code = "PUR"; break; default: code = "unknown"; break; } return code; } ossimString ossimDemHeader::getProjectionType() const { ossimString type; switch(getGroundRefSysCode()) { case 0: type = "ossimEquDistCylProjection"; break; case 1: type = "ossimUtmProjection"; break; case 2: default: type = "unknown"; break; } return type; } ossim-Miami-2.9.1/src/support_data/ossimDemInfo.cpp000066400000000000000000000033021352751253100223050ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: USGS DEM Info object. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include ossimDemInfo::ossimDemInfo() { } ossimDemInfo::~ossimDemInfo() { } bool ossimDemInfo::open(const ossimFilename& file) { std::string connectionString = file.c_str(); std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( file.c_str(), std::ios_base::in|std::ios_base::binary); if(!str) return false; return open(str, connectionString); } bool ossimDemInfo::open(std::shared_ptr& str, const std::string& connectionString) { if(!str) return false; bool result = ossimDemUtil::isUsgsDem(str, connectionString); if ( result ) { m_fileStr = str; m_connectionString = connectionString; } else { m_connectionString = ""; } return result; } std::ostream& ossimDemInfo::print(std::ostream& out) const { if ( m_fileStr ) { ossimDemHeader hdr; m_fileStr->clear(); m_fileStr->seekg(0); if ( hdr.open(m_fileStr, m_connectionString) ) { // std::string prefix; hdr.print(std::cout); } } return out; } ossim-Miami-2.9.1/src/support_data/ossimDemPoint.cpp000066400000000000000000000007321352751253100225070ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Contains class definition for DEMPoint. //******************************************************************* // $Id: ossimDemPoint.cpp 9094 2006-06-13 19:12:40Z dburken $ #include ossim-Miami-2.9.1/src/support_data/ossimDemProfile.cpp000066400000000000000000000065231352751253100230220ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class defines a DEM profile. // //******************************************************************** // $Id: ossimDemProfile.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include ossimDemProfile::ossimDemProfile() : _row(0), _column(0), _numberElevations(0), _locDatumElev(0.0), _minElev(0.0), _maxElev(0.0) { } ossimDemProfile::ossimDemProfile(ossimDemProfile const& right) { operator=(right); } ossimDemProfile const& ossimDemProfile::operator=(ossimDemProfile const& right) { if (this == &right) return *this; _row = right._row; _column = right._column; _numberElevations = right._numberElevations; _profileLocation = right._profileLocation; _locDatumElev = right._locDatumElev; _minElev = right._minElev; _maxElev = right._maxElev; _elevations = right._elevations; return *this; } ossim_int32 ossimDemProfile::getRowNumber() const { return _row; } ossim_int32 ossimDemProfile::getColumnNumber() const { return _column; } ossim_int32 ossimDemProfile::getNumberOfElevations() const { return _numberElevations; } ossimDemPoint const& ossimDemProfile::getProfileLocation() const { return _profileLocation; } double ossimDemProfile::getLocalDatumElevation() const { return _locDatumElev; } double ossimDemProfile::getMinimumElev() const { return _minElev; } double ossimDemProfile::getMaximumElev() const { return _maxElev; } ossimDemElevationVector const& ossimDemProfile::getElevations() const { return _elevations; } std::istream& operator>>(std::istream& s, ossimDemProfile& demp) { // string bufstr; char bufstr[1024]; ossimDemUtil::getRecord(s,bufstr); demp._row = ossimDemUtil::getLong(bufstr, 0, 6); demp._column = ossimDemUtil::getLong(bufstr, 6, 6); demp._numberElevations = ossimDemUtil::getLong(bufstr, 12, 6); double x,y; ossimDemUtil::getDouble(bufstr, 24, 24, x); ossimDemUtil::getDouble(bufstr, 48, 24, y); demp._profileLocation.setXY(x,y); ossimDemUtil::getDouble(bufstr, 72, 24, demp._locDatumElev); ossimDemUtil::getDouble(bufstr, 96, 24, demp._minElev); ossimDemUtil::getDouble(bufstr, 120, 24, demp._maxElev); demp._elevations.erase(demp._elevations.begin(), demp._elevations.end()); demp._elevations.reserve(demp._numberElevations); // Extract elevations in this record. ossim_int32 count = 0; while ((count < 146) && (count < demp._numberElevations)) { demp._elevations.push_back(ossimDemUtil::getLong(bufstr, 144+(count*6), 6)); count++; } ossim_int32 t; while (count < demp._numberElevations) { t = (count - 146) % 170; if (t == 0) ossimDemUtil::getRecord(s,bufstr); demp._elevations.push_back(ossimDemUtil::getLong(bufstr, t*6, 6)); count++; } return s; } std::ostream& operator<<(std::ostream& s, ossimDemProfile& /* demp */) { return s; } ossim-Miami-2.9.1/src/support_data/ossimDemStats.cpp000066400000000000000000000046471352751253100225250ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class provides some statistics for DEMs. // //******************************************************************** // $Id: ossimDemStats.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include using namespace std; ossimDemStats::ossimDemStats() : _availCodeDE2(0), _rsmeDE2x(0), _rsmeDE2y(0), _rsmeDE2z(0), _sampleSizeDE2(0), _availCodeDE5(0), _rsmeDE5x(0), _rsmeDE5y(0), _rsmeDE5z(0), _sampleSizeDE5(0) { } ossimDemStats::~ossimDemStats() { } long ossimDemStats::getAvailCodeDE2() const { return _availCodeDE2; } long ossimDemStats::getRSMEDE2x() const { return _rsmeDE2x; } long ossimDemStats::getRSMEDE2y() const { return _rsmeDE2y; } long ossimDemStats::getRSMEDE2z() const { return _rsmeDE2z; } long ossimDemStats::getSampleSizeDE2() const { return _sampleSizeDE2; } long ossimDemStats::getAvailCodeDE5() const { return _availCodeDE5; } long ossimDemStats::getRSMEDE5x() const { return _rsmeDE5x; } long ossimDemStats::getRSMEDE5y() const { return _rsmeDE5y; } long ossimDemStats::getRSMEDE5z() const { return _rsmeDE5z; } long ossimDemStats::getSampleSizeDE5() const { return _sampleSizeDE5; } ostream& operator<<(ostream& s, ossimDemStats const& /* stats */) { return s; } istream& operator>>(istream& s, ossimDemStats& stats) { char bufstr[1024]; ossimDemUtil::getRecord(s, bufstr); stats._availCodeDE2 = ossimDemUtil::getLong(bufstr, 0, 6); stats._rsmeDE2x = ossimDemUtil::getLong(bufstr, 6, 6); stats._rsmeDE2y = ossimDemUtil::getLong(bufstr, 12, 6); stats._rsmeDE2z = ossimDemUtil::getLong(bufstr, 18, 6); stats._sampleSizeDE2 = ossimDemUtil::getLong(bufstr, 24, 6); stats._availCodeDE5 = ossimDemUtil::getLong(bufstr, 30, 6); stats._rsmeDE5x = ossimDemUtil::getLong(bufstr, 36, 6); stats._rsmeDE5y = ossimDemUtil::getLong(bufstr, 42, 6); stats._rsmeDE5z = ossimDemUtil::getLong(bufstr, 48, 6); stats._sampleSizeDE5 = ossimDemUtil::getLong(bufstr, 54, 6); return s; } ossim-Miami-2.9.1/src/support_data/ossimDemUtil.cpp000066400000000000000000000120171352751253100223320ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // Orginally written by Jamie Moyers (jmoyers@geeks.com) // Adapted from the package KDEM. // Description: This class provides some simple utilities for DEMs. // //******************************************************************** // $Id$ #include #include #include #include #include #include #include #include static const char DEM_TYPE_KW[] = "dem_type"; static const char USGS_DEM_KW[] = "usgs_dem"; bool ossimDemUtil::isUsgsDem(const ossimFilename& file) { bool result = false; ossimString ext = file.ext(); ext.downcase(); if (ext == "dem") { result = true; } else { // Look for file.omd ossimFilename kwlFile = file; kwlFile.setExtension("omd"); if (! kwlFile.exists() ) { kwlFile.setExtension("OMD"); } if ( kwlFile.exists() ) { ossimKeywordlist kwl(kwlFile); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_OK) { const char* lookup = kwl.find(DEM_TYPE_KW); if (lookup) { ossimString s = lookup; s.downcase(); if (s == USGS_DEM_KW) { result = true; } } } } } if ( result ) { // Open up the file for reading. // std::shared_ptr is = ossim::StreamFactoryRegistry::instance()-> // createIstream(file, std::ios_base::in | std::ios_base::binary); } return result; } bool ossimDemUtil::isUsgsDem(std::shared_ptr str, const std::string& connectionString) { bool result = false; ossimFilename tempFile = connectionString; ossimString ext = tempFile.ext(); ext.downcase(); if (ext == "dem") { result = true; } else { // Look for file.omd ossimFilename kwlFile = tempFile; kwlFile.setExtension("omd"); if (! kwlFile.exists() ) { kwlFile.setExtension("OMD"); } if ( kwlFile.exists() ) { ossimKeywordlist kwl(kwlFile); if (kwl.getErrorStatus() == ossimErrorCodes::OSSIM_OK) { const char* lookup = kwl.find(DEM_TYPE_KW); if (lookup) { ossimString s = lookup; s.downcase(); if (s == USGS_DEM_KW) { result = true; } } } } } if(result&&str&&str->good()) { //--- // SPECIAL HACK (drb): // Check some bytes and make sure there is no binary data. // There are files out there with .dem extension that are binary // rasters. //--- ossim_uint8* ubuf = new ossim_uint8[512]; str->read((char*)ubuf, 512); for (int i = 0; i < 512; ++i) { if (ubuf[i] > 0x7f) { result = false; break; } } delete [] ubuf; ubuf = 0; } else { result = false; } return result; } bool ossimDemUtil::getRecord(ossim::istream& s, std::string& strbuf, long reclength) { char* buf = new char[reclength + 1]; bool flag = ossimDemUtil::getRecord(s,buf,reclength); if (flag == true) strbuf = buf; delete [] buf; return flag; } bool ossimDemUtil::getRecord(ossim::istream& s, char* buf, long reclength) { // buf is assumed to be at least reclength+1 in size. if (!s) return false; long curpos = 0; buf[curpos] = s.get(); while ((buf[curpos] != EOF) && (buf[curpos] != '\n') && (curpos < reclength-1)) { curpos++; buf[curpos] = s.get(); } buf[curpos] = '\0'; if (s.peek() == '\n') s.get(); return true; } bool ossimDemUtil::getDouble(std::string const& strbuf, long const startpos, long const width, double& val) { if ((startpos + width - 1) > (long)(strbuf.length())) return false; // Convert FORTRAN 'D' exponent indicator to 'E'. std::string tempbuf(strbuf.substr(startpos,width)); for (unsigned int i = 0; i < tempbuf.length(); i++) if (tempbuf[i] == 'D') tempbuf[i] = 'E'; val = atof(tempbuf.c_str()); return true; } long ossimDemUtil::getLong(char* const strbuf, // string to extract long from long const startpos, // starting position of field long const width) // width of field { char temp[1024]; std::strncpy(temp,strbuf+startpos,width); temp[width] = '\0'; return atol(temp); } ossim-Miami-2.9.1/src/support_data/ossimDoqq.cpp000066400000000000000000000261341352751253100217000ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class parses a Digital Ortho Quarter Quad (DOQQ) // header. // //******************************************************************** // $Id: ossimDoqq.cpp 22855 2014-08-05 14:46:38Z gpotts $ #include #include #include #include static ossimTrace traceDebug("ossimDoqq:debug"); //************************************************************************** // CONSTRUCTOR //************************************************************************** ossimDoqq::ossimDoqq() : theErrorStatus(OSSIM_ERROR) { } //************************************************************************** // CONSTRUCTOR //************************************************************************** ossimDoqq::ossimDoqq(ossimFilename file) : theErrorStatus(OSSIM_ERROR) { ossimInfoBase::open(file); //theDoqFile.close(); } bool ossimDoqq::open(std::shared_ptr& str, const std::string& connectionString) { theErrorStatus = OSSIM_OK; if(!str) return false; char header[23]; str->clear(); str->seekg(0); str->get(header, 22); header[22] = '\0'; if(strcmp((const char*)header, "BEGIN_USGS_DOQ_HEADER") == 0) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDoqq::ossimDoqq Loading DOQ version 2 header..." << std::endl; } ldstr_v2(*str); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDoqq::ossimDoqq Loading DOQ version 1 header..." << std::endl; } ldstr_v1(*str); } // Check for error. if(theErrorStatus) return false; m_connectionString = connectionString; m_doqqFileStr = str; return true; } ossimDoqq::~ossimDoqq() { m_doqqFileStr.reset(); } void ossimDoqq::ldstr_v2(std::istream& in) { static const char MODULE[] = "ossimDoqq::ldstr_v2(istream& in)"; if (!in) { theErrorStatus = OSSIM_ERROR; return; } char line[100]; char dum1[30]; char dum2[30]; char dum3[30]; char dum4[30]; while((strncmp(line, "END_USGS_HEADER", 15) != 0)&& (in.good())) { // Read in one line of header at a time. in.getline(line, 100); if(strncmp(line, "SAMPLES_AND_LINES", 17) == 0) { sscanf(line, "%s %s %s", dum1, dum2, dum3); theLine = atoi(dum3); theSample = atoi(dum2); } else if(strncmp(line, "HORIZONTAL_COORDINATE_SYSTEM", 28) == 0) { sscanf(line, "%s %s", dum1, dum2); theProjection = dum2; } else if(strncmp(line, "NW_QUAD_CORNER_XY", 17) == 0) { sscanf(line, "%s %s %s", dum1, dum2, dum3); theUE = atof(dum2); theUN = atof(dum3); } else if(strncmp(line, "NE_QUAD_CORNER_XY", 17) == 0) { sscanf(line, "%s %s %s", dum1, dum2, dum3); theLE = atof(dum2); theLN = atof(dum3); } else if(strncmp(line, "COORDINATE_ZONE", 15) == 0) { sscanf(line, "%s %s", dum1, dum2); theUtmZone = atoi(dum2); } else if(strncmp(line, "SOURCE_IMAGE_DATE", 17) == 0) { sscanf(line, "%s %s %s %s", dum1, dum2, dum3, dum4); theAcqYear = ossimString(dum2); theAcqMonth = ossimString(dum3); theAcqDay = ossimString(dum4); } else if((strncmp(line, "XY_ORIGIN", 9) == 0)) { sscanf(line, "%s %s %s", dum1, dum2, dum3); theEasting = atof(dum2); theNorthing = atof(dum3); } else if((strncmp(line, "HORIZONTAL_DATUM", 16) == 0) && theDatum.empty()) { ossimString datum; sscanf(line, "%s %s", dum1, dum2); datum = dum2; if(datum.contains("NAD27")) theDatum = "NAD"; else theDatum = "NAR"; } else if(strncmp(line, "BYTE_COUNT", 10) == 0) { ossimString header; sscanf(line, "%s %s", dum1, dum2); header = dum2; theHeaderSize = atoi(header.chars()); } else if(strncmp(line, "BAND_CONTENT", 12) == 0) { ossimString rgbType; sscanf(line, "%s %s", dum1, dum2); rgbType = dum2; if(rgbType.contains("BLACK&WHITE")) theRgb = 1; else theRgb = 3; } else if(strncmp(line, "HORIZONTAL_RESOLUTION", 21) == 0) { ossimString gsd; sscanf(line, "%s %s", dum1, dum2); gsd = dum2; theGsd.x = gsd.toDouble(); theGsd.y = gsd.toDouble(); } else if(strncmp(line, "QUADRANGLE_NAME", 15) == 0) { sscanf(line, "%s %29c", dum1, dum2); dum2[29] = 0; theQuadName = dum2; } else if(strncmp(line, "QUADRANT", 8) == 0) { sscanf(line, "%s %s", dum1, dum2); theQuad = dum2; } else if(strncmp(line, "NATION", 6) == 0) { sscanf(line, "%s %s", dum1, dum2); theNation = dum2; } else if(strncmp(line, "STATE", 5) == 0) { sscanf(line, "%s %s", dum1, dum2); theState = dum2; } else if(strncmp(line, "RMSE_XY", 7) == 0) { sscanf(line, "%s %s", dum1, dum2); theRMSE = ossimString(dum2).toDouble(); } else if(strncmp(line, "IMAGE_SOURCE", 12) == 0) { sscanf(line, "%s %29c", dum1, dum2); dum2[29] = 0; theImageSource = dum2; } else if(strncmp(line, "SOURCE_IMAGE_ID", 15) == 0) { sscanf(line, "%s %29c", dum1, dum2); dum2[29] = 0; theSourceImageID = dum2; } } if (!in.good()) { theErrorStatus = OSSIM_ERROR; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << "\tHeader stream is bad." << std::endl; } return; } // Check for valid lines and samples and header size. if(theLine <= 0 || theSample <= 0 || theHeaderSize <= 0) { theErrorStatus = OSSIM_ERROR; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << "\tInvalid lines or samples or header size." << std::endl; } return; } // Assign concatenated acquisition date: theAcqYearMonthDay = theAcqYear; theAcqYearMonthDay += "-"; theAcqYearMonthDay += theAcqMonth; theAcqYearMonthDay += "-"; theAcqYearMonthDay += theAcqDay; } void ossimDoqq::ldstr_v1(std::istream& in) { static const char MODULE[] = "ossimDoqq::ldstr_v1(istream& in)"; if (!in) { theErrorStatus = OSSIM_ERROR; return; } char tmp1[DATA_ORDER_SIZE+1]; in.seekg(DATA_ORDER_OFFSET, std::ios::beg); in.get(tmp1, DATA_ORDER_SIZE+1); theDataOrder = tmp1; //*** // Perform a sanity check on the data order just in case this isn't a // ossimDoqq file. //*** tmp1[DATA_ORDER_SIZE] = '\0'; int data_order = atoi(tmp1); if ( (data_order != 1) && (data_order != 2) ) { theErrorStatus = OSSIM_ERROR; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " NOTICE:\n" << "Invalid data ordering. Not a doq?" << std::endl; } } char tmp2[LINE_SIZE+1]; in.seekg(LINE_OFFSET, std::ios::beg); in.get(tmp2, LINE_SIZE+1); theLine = atoi(tmp2); char tmp3[SAMPLE_SIZE+1]; in.seekg(SAMPLE_OFFSET,std::ios::beg); in.get(tmp3, SAMPLE_SIZE+1); theSample = atoi(tmp3); // Check for valid lines and samples. if (theLine <= 0 || theSample <= 0) { theErrorStatus = OSSIM_ERROR; if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " ERROR:\n" << "\tInvalid lines or samples." << std::endl; } return; } char tmp4[PROJECTION_SIZE+1]; in.seekg(PROJECTION_OFFSET, std::ios::beg); in.get(tmp4, PROJECTION_SIZE+1); theProjection = tmp4; char tmp5[UTM_ZONE_SIZE+1]; in.seekg(UTM_ZONE_OFFSET, std::ios::beg); in.get(tmp5, UTM_ZONE_SIZE+1); theUtmZone = atoi(tmp5); char tmp8[DATUM_SIZE+1]; in.seekg(DATUM_OFFSET, std::ios::beg); in.get(tmp8, DATUM_SIZE+1); theDatum = tmp8; char rgbType[RGB_SIZE+1]; in.seekg(RGB_OFFSET, std::ios::beg); in.get(rgbType, RGB_SIZE+1); if(atoi(rgbType) == 5) { theRgb = 3; } else { theRgb = 1; } theHeaderSize = (theSample * theRgb * 4); // Calculate the size of each record. theRecordSize = (theSample * theRgb); char tmp6[UL_EASTING_SIZE+1]; in.seekg( (theRecordSize * 2) + UL_EASTING_OFFSET, std::ios::beg); in.get(tmp6, UL_EASTING_SIZE+1); char tmp7[UL_NORTHING_SIZE+1]; in.seekg( (theRecordSize * 2) + UL_NORTHING_OFFSET, std::ios::beg); in.get(tmp7, UL_NORTHING_SIZE+1); // Get Easting and Northing. theEasting = convertStr(tmp6); theNorthing = convertStr(tmp7); char tmp10[GSD_SIZE+1]; in.seekg( (theRecordSize*3) + GSD_X_OFFSET, std::ios::beg); in.get(tmp10, GSD_SIZE+1); theGsd.x = std::abs(ossimString(tmp10, tmp10+GSD_SIZE).toDouble()); in.seekg( (theRecordSize*3) + GSD_Y_OFFSET, std::ios::beg); in.get(tmp10, GSD_SIZE+1); theGsd.y = std::abs(ossimString(tmp10, tmp10+GSD_SIZE).toDouble()); } ossim_float64 ossimDoqq::convertStr(const char* str) const { //*** // The USGS Projection Parameters in a OssimDoqq header have a "D" to // denote the exponent. This simply substitutes the "D" with an // "E" so that atof works properly. //*** ossimString tmp = str; tmp.gsub("D", "E"); return tmp.toFloat64(); } std::ostream& ossimDoqq::print(std::ostream& out) const { const char* prefix = "doqq."; out << prefix << "Quadrangle_Name: " << theQuadName << std::endl; out << prefix << "Quadrant: " << theQuad << std::endl; out << prefix << "Image_Source: " << theImageSource << std::endl; out << prefix << "Source_Image_ID: " << theSourceImageID << std::endl; out << prefix << "RMSE_XY: " << theRMSE << std::endl; out << prefix << "Line: " << theLine << std::endl; out << prefix << "Sample: " << theSample << std::endl; out << prefix << "Projection: " << theProjection << std::endl; out << prefix << "Datum: " << theDatum << std::endl; out << prefix << "Easting: " << theEasting << std::endl; out << prefix << "Northing: " << theNorthing << std::endl; out << prefix << "UN: " << theUN << std::endl; out << prefix << "UE: " << theUE << std::endl; out << prefix << "LN: " << theLN << std::endl; out << prefix << "LE: " << theLE << std::endl; out << prefix << "GSD: " << theGsd << std::endl; out << prefix << "Band: " << theRgb << std::endl; out << prefix << "Utm_Zone: " << theUtmZone << std::endl; return out; } ossim-Miami-2.9.1/src/support_data/ossimDtedAcc.cpp000066400000000000000000000153351352751253100222640ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero // // Description: This class gives access to the Accuracy Description // (ACC) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedAcc.cpp 23276 2015-04-24 21:01:51Z rashadkm $ #include #include #include #include #include #include #include #include #include #include #include using namespace std; ossimDtedAcc::ossimDtedAcc() { } ossimDtedAcc::ossimDtedAcc(std::shared_ptr& str, ossim_int64 offset) { if(str) { str->seekg(offset); parse(*str); } else { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } } void ossimDtedAcc::clearFields() { memset(theRecSen, '\0', FIELD1_SIZE+1); memset(theAbsoluteCE, '\0',FIELD2_SIZE+1); memset(theAbsoluteLE, '\0',FIELD3_SIZE+1); memset(theRelativeCE, '\0',FIELD4_SIZE+1); memset(theRelativeLE, '\0',FIELD5_SIZE+1); memset(theField6, '\0',FIELD6_SIZE+1); memset(theField7, '\0',FIELD7_SIZE+1); memset(theField8, '\0',FIELD8_SIZE+1); memset(theField9, '\0',FIELD9_SIZE+1); memset(theField10, '\0',FIELD10_SIZE+1); memset(theField11, '\0',FIELD11_SIZE+1); memset(theField12, '\0',FIELD12_SIZE+1); memset(theField13, '\0',FIELD13_SIZE+1); memset(theField14, '\0',FIELD14_SIZE+1); memset(theField15, '\0',FIELD15_SIZE+1); memset(theField16, '\0',FIELD16_SIZE+1); memset(theField17, '\0',FIELD17_SIZE+1); theStartOffset = 0; theStopOffset = 0; } //************************************************************************** // ossimDtedAcc::parse() //************************************************************************** void ossimDtedAcc::parse(std::istream& in) { clearErrorStatus(); clearFields(); theStartOffset = in.tellg(); theStopOffset = theStartOffset; // Parse theRecSen in.read(theRecSen, FIELD1_SIZE); theRecSen[FIELD1_SIZE] = '\0'; if(!(strncmp(theRecSen, "ACC", 3) == 0)) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; in.seekg(theStartOffset); return; } // Parse theAbsoluteCE in.read(theAbsoluteCE, FIELD2_SIZE); theAbsoluteCE[FIELD2_SIZE] = '\0'; // Parse theAbsoluteLE in.read(theAbsoluteLE, FIELD3_SIZE); theAbsoluteLE[FIELD3_SIZE] = '\0'; // Parse theRelativeCE in.read(theRelativeCE, FIELD4_SIZE); theRelativeCE[FIELD4_SIZE] = '\0'; // Parse theRelativeLE in.read(theRelativeLE, FIELD5_SIZE); theRelativeLE[FIELD5_SIZE] = '\0'; // Parse Field 6 in.read(theField6, FIELD6_SIZE); theField6[FIELD6_SIZE] = '\0'; // Parse Field 7 in.read(theField7, FIELD7_SIZE); theField7[FIELD7_SIZE] = '\0'; // Parse Field 8 in.read(theField8, FIELD8_SIZE); theField8[FIELD8_SIZE] = '\0'; // Parse Field 9 in.read(theField9, FIELD9_SIZE); theField9[FIELD9_SIZE] = '\0'; // Parse Field 10 in.read(theField10, FIELD10_SIZE); theField10[FIELD10_SIZE] = '\0'; // Parse Field 11 in.read(theField11, FIELD11_SIZE); theField11[FIELD11_SIZE] = '\0'; // Parse Field 12 in.read(theField12, FIELD12_SIZE); theField12[FIELD12_SIZE] = '\0'; // Parse Field 13 in.read(theField13, FIELD13_SIZE); theField13[FIELD13_SIZE] = '\0'; // Parse Field 14 in.read(theField14, FIELD14_SIZE); theField14[FIELD14_SIZE] = '\0'; // Parse Field 15 in.read(theField15, FIELD15_SIZE); theField15[FIELD15_SIZE] = '\0'; // Parse Field 16 in.read(theField16, FIELD16_SIZE); theField16[FIELD16_SIZE] = '\0'; // Parse Field 17 in.read(theField17, FIELD17_SIZE); theField17[FIELD17_SIZE] = '\0'; in.ignore(FIELD18_SIZE); // Set the stop offset. theStopOffset = theStartOffset + ACC_LENGTH; } ossimRefPtr ossimDtedAcc::getProperty( const ossimString& name) const { ossimRefPtr result = 0; if (name == "recognition_sentinel") { result = new ossimStringProperty(name, theRecSen); } else if (name == "absolute_ce") { result = new ossimStringProperty(name, theAbsoluteCE); } else if (name == "absolute_le") { result = new ossimStringProperty(name, theAbsoluteLE); } else if (name == "relative_ce") { result = new ossimStringProperty(name, theRelativeCE); } else if (name == "relative_le") { result = new ossimStringProperty(name, theRelativeLE); } return result; } void ossimDtedAcc::getPropertyNames( std::vector& propertyNames) const { propertyNames.push_back(ossimString("recognition_sentinel")); propertyNames.push_back(ossimString("absolute_ce")); propertyNames.push_back(ossimString("absolute_le")); propertyNames.push_back(ossimString("relative_ce")); propertyNames.push_back(ossimString("relative_le")); } std::ostream& ossimDtedAcc::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += "acc."; out << setiosflags(ios::left) << pfx << setw(28) << "recognition_sentinel:" << theRecSen << "\n" << pfx << setw(28) << "absolute_ce:" << theAbsoluteCE << "\n" << pfx << setw(28) << "absolute_le:" << theAbsoluteLE << "\n" << pfx << setw(28) << "relative ce:" << theRelativeCE << "\n" << pfx << setw(28) << "relative le:" << theRelativeLE << "\n" << pfx << setw(28) << "start_offset:" << theStartOffset << "\n" << pfx << setw(28) << "stop_offset:" << theStopOffset << std::endl; return out; } ossim_int32 ossimDtedAcc::absCE() const { return atoi(theAbsoluteCE); } ossim_int32 ossimDtedAcc::absLE() const { return atoi(theAbsoluteLE); } ossim_int32 ossimDtedAcc::relCE() const { return atoi(theRelativeCE); } ossim_int32 ossimDtedAcc::relLE() const { return atoi(theRelativeLE); } ossim_int32 ossimDtedAcc::startOffset() const { return theStartOffset; } ossim_int32 ossimDtedAcc::stopOffset() const { return theStopOffset; } //************************************************************************** // operator << //************************************************************************** std::ostream& operator<<( std::ostream& os, const ossimDtedAcc& acc) { std::string prefix; return acc.print(os, prefix); } ossimDtedAcc::ossimDtedAcc(const ossimDtedAcc& /* source */) { clearFields(); } const ossimDtedAcc& ossimDtedAcc::operator=(const ossimDtedAcc& rhs) { return rhs; } ossim-Miami-2.9.1/src/support_data/ossimDtedDsi.cpp000066400000000000000000000335541352751253100223200ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class gives access to the Data Set Identification // (DSI) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedDsi.cpp 23276 2015-04-24 21:01:51Z rashadkm $ #include #include #include #include #include #include #include #include #include using namespace std; ossimDtedDsi::ossimDtedDsi() : theRecSen(), theSecurityCode(), theField3(), theField4(), theProductLevel(), theField7(), theField8(), theEdition(), theMatchMergeVersion(), theMaintenanceDate(), theMatchMergeDate(), theMaintenanceCode(), theProducerCode(), theField15(), theProductStockSpecNumber(), theProductSpecNumber(), theProductSpecDate(), theVerticalDatum(), theHorizontalDatum(), theField21(), theCompilationDate(), theField23(), theLatOrigin(), theLonOrigin(), theLatSW(), theLonSW(), theLatNW(), theLonNW(), theLatNE(), theLonNE(), theLatSE(), theLonSE(), theOrientation(), theLatInterval(), theLonInterval(), theNumLatPoints(), theNumLonLines(), theCellIndicator(), theField40(), theField41(), theField42(), theStartOffset(0), theStopOffset(0) { } ossimDtedDsi::ossimDtedDsi(std::shared_ptr& str, ossim_int64 offset) : theRecSen(), theSecurityCode(), theField3(), theField4(), theProductLevel(), theField7(), theField8(), theEdition(), theMatchMergeVersion(), theMaintenanceDate(), theMatchMergeDate(), theMaintenanceCode(), theProducerCode(), theField15(), theProductStockSpecNumber(), theProductSpecNumber(), theProductSpecDate(), theVerticalDatum(), theHorizontalDatum(), theField21(), theCompilationDate(), theField23(), theLatOrigin(), theLonOrigin(), theLatSW(), theLonSW(), theLatNW(), theLonNW(), theLatNE(), theLonNE(), theLatSE(), theLonSE(), theOrientation(), theLatInterval(), theLonInterval(), theNumLatPoints(), theNumLonLines(), theCellIndicator(), theField40(), theField41(), theField42(), theStartOffset(0), theStopOffset(0) { if(str) { str->seekg(offset); parse(*str); } else { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } } void ossimDtedDsi::parse(std::istream& in) { clearErrorStatus(); theStartOffset = in.tellg(); theStopOffset = theStartOffset; char tmp_chars[26]; // For blank field reads. // Seek to the start of the record. in.seekg(theStartOffset, std::ios::beg); // Parse theRecSen in.read(theRecSen, FIELD1_SIZE); theRecSen[FIELD1_SIZE] = '\0'; if(!(strncmp(theRecSen, "DSI", 3) == 0)) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; in.seekg(theStartOffset); return; } // Parse theSecurityCode in.read(theSecurityCode, FIELD2_SIZE); theSecurityCode[FIELD2_SIZE] = '\0'; // Parse Field 3 in.read(theField3, FIELD3_SIZE); theField3[FIELD3_SIZE] = '\0'; // Parse Field 4 in.read(theField4, FIELD4_SIZE); theField4[FIELD4_SIZE] = '\0'; // Parse Field 5 (currently blank) in.read(tmp_chars, FIELD5_SIZE); // Parse theProductLevel in.read(theProductLevel, FIELD6_SIZE); theProductLevel[FIELD6_SIZE] = '\0'; // Parse Field 7 in.read(theField7, FIELD7_SIZE); theField7[FIELD7_SIZE] = '\0'; // Parse Field 8 in.read(theField8, FIELD8_SIZE); theField8[FIELD8_SIZE] = '\0'; // Parse theEdition in.read(theEdition, FIELD9_SIZE); theEdition[FIELD9_SIZE] = '\0'; // Parse theMatchMergeVersion in.read(theMatchMergeVersion, FIELD10_SIZE); theMatchMergeVersion[FIELD10_SIZE] = '\0'; // Parse theMaintenanceDate in.read(theMaintenanceDate, FIELD11_SIZE); theMaintenanceDate[FIELD11_SIZE] = '\0'; // Parse theMatchMergeDate in.read(theMatchMergeDate, FIELD12_SIZE); theMatchMergeDate[FIELD12_SIZE] = '\0'; // Parse theMaintenanceCode in.read(theMaintenanceCode, FIELD13_SIZE); theMaintenanceCode[FIELD13_SIZE] = '\0'; // Parse theProducerCode in.read(theProducerCode, FIELD14_SIZE); theProducerCode[FIELD14_SIZE] = '\0'; // Parse Field 15 in.read(theField15, FIELD15_SIZE); theField15[FIELD15_SIZE] = '\0'; // Parse theProductStockSpecNumber in.read(theProductStockSpecNumber, FIELD16_SIZE); theProductStockSpecNumber[FIELD16_SIZE] = '\0'; // Parse theProductSpecNumber in.read(theProductSpecNumber, FIELD17_SIZE); theProductSpecNumber[FIELD17_SIZE] = '\0'; // Parse theProductSpecDate in.read(theProductSpecDate, FIELD18_SIZE); theProductSpecDate[FIELD18_SIZE] = '\0'; // Parse theVerticalDatum in.read(theVerticalDatum, FIELD19_SIZE); theVerticalDatum[FIELD19_SIZE] = '\0'; // Parse theHorizontalDatum in.read(theHorizontalDatum, FIELD20_SIZE); theHorizontalDatum[FIELD20_SIZE] = '\0'; // Parse Field 21 in.read(theField21, FIELD21_SIZE); theField21[FIELD21_SIZE] = '\0'; // Parse theCompilationDate in.read(theCompilationDate, FIELD22_SIZE); theCompilationDate[FIELD22_SIZE] = '\0'; // Parse Field 23 in.read(theField23, FIELD23_SIZE); theField23[FIELD23_SIZE] = '\0'; // Parse theLatOrigin in.read(theLatOrigin, FIELD24_SIZE); theLatOrigin[FIELD24_SIZE] = '\0'; // Parse theLonOrigin in.read(theLonOrigin, FIELD25_SIZE); theLonOrigin[FIELD25_SIZE] = '\0'; // Parse theLatSW in.read(theLatSW, FIELD26_SIZE); theLatSW[FIELD26_SIZE] = '\0'; // Parse theLonSW in.read(theLonSW, FIELD27_SIZE); theLonSW[FIELD27_SIZE] = '\0'; // Parse theLatNW in.read(theLatNW, FIELD28_SIZE); theLatNW[FIELD28_SIZE] = '\0'; // Parse theLonNW in.read(theLonNW, FIELD29_SIZE); theLonNW[FIELD29_SIZE] = '\0'; // Parse theLatNE in.read(theLatNE, FIELD30_SIZE); theLatNE[FIELD30_SIZE] = '\0'; // Parse theLonNE in.read(theLonNE, FIELD31_SIZE); theLonNE[FIELD31_SIZE] = '\0'; // Parse theLatSE in.read(theLatSE, FIELD32_SIZE); theLatSE[FIELD32_SIZE] = '\0'; // Parse theLonSE in.read(theLonSE, FIELD33_SIZE); theLonSE[FIELD33_SIZE] = '\0'; // Parse theOrientation in.read(theOrientation, FIELD34_SIZE); theOrientation[FIELD34_SIZE] = '\0'; // Parse theLatInterval in.read(theLatInterval, FIELD35_SIZE); theLatInterval[FIELD35_SIZE] = '\0'; // Parse theLonInterval in.read(theLonInterval, FIELD36_SIZE); theLonInterval[FIELD36_SIZE] = '\0'; // Parse theNumLatPoints in.read(theNumLatPoints, FIELD37_SIZE); theNumLatPoints[FIELD37_SIZE] = '\0'; // Parse theNumLonLines in.read(theNumLonLines, FIELD38_SIZE); theNumLonLines[FIELD38_SIZE] = '\0'; // Parse theCellIndicator in.read(theCellIndicator, FIELD39_SIZE); theCellIndicator[FIELD39_SIZE] = '\0'; // Parse Field 40 in.read(theField40, FIELD40_SIZE); theField40[FIELD40_SIZE] = '\0'; // Parse Field 41 in.read(theField41, FIELD41_SIZE); theField41[FIELD41_SIZE] = '\0'; // Parse Field 42 in.read(theField42, FIELD42_SIZE); theField42[FIELD42_SIZE] = '\0'; // Set the stop offset. theStopOffset = theStartOffset + DSI_LENGTH; } ossimRefPtr ossimDtedDsi::getProperty( const ossimString& /* name */) const { ossimRefPtr result = 0; return result; } void ossimDtedDsi::getPropertyNames( std::vector& propertyNames) const { propertyNames.push_back(ossimString("dted_dsi_record")); } ossimString ossimDtedDsi::recognitionSentinel() const { return theRecSen; } ossimString ossimDtedDsi::securityCode() const { return ossimString(theSecurityCode); } ossimString ossimDtedDsi::productLevel() const { return ossimString(theProductLevel); } ossimString ossimDtedDsi::edition() const { return ossimString(theEdition); } ossimString ossimDtedDsi::matchMergeVersion() const { return ossimString(theMatchMergeVersion); } ossimString ossimDtedDsi::maintanenceDate() const { return ossimString(theMaintenanceDate); } ossimString ossimDtedDsi::matchMergeDate() const { return ossimString(theMatchMergeDate); } ossimString ossimDtedDsi::maintenanceCode() const { return ossimString(theMaintenanceCode); } ossimString ossimDtedDsi::producerCode() const { return ossimString(theProducerCode); } ossimString ossimDtedDsi::productStockSpecNumber() const { return ossimString(theProductStockSpecNumber); } ossimString ossimDtedDsi::productSpecNumber() const { return ossimString(theProductSpecNumber); } ossimString ossimDtedDsi::productSpecDate() const { return ossimString(theProductSpecDate); } ossimString ossimDtedDsi::verticalDatum() const { return ossimString(theVerticalDatum); } ossimString ossimDtedDsi::horizontalDatum() const { return ossimString(theHorizontalDatum); } ossimString ossimDtedDsi::compilationDate() const { return ossimString(theCompilationDate); } ossimString ossimDtedDsi::latOrigin() const { return ossimString(theLatOrigin); } ossimString ossimDtedDsi::lonOrigin() const { return ossimString(theLonOrigin); } ossimString ossimDtedDsi::latSW() const { return ossimString(theLatSW); } ossimString ossimDtedDsi::lonSW() const { return ossimString(theLonSW); } ossimString ossimDtedDsi::latNW() const { return ossimString(theLatNW); } ossimString ossimDtedDsi::lonNW() const { return ossimString(theLonNW); } ossimString ossimDtedDsi::latNE() const { return ossimString(theLatNE); } ossimString ossimDtedDsi::lonNE() const { return ossimString(theLonNE); } ossimString ossimDtedDsi::latSE() const { return ossimString(theLatSE); } ossimString ossimDtedDsi::lonSE() const { return ossimString(theLonSE); } ossimString ossimDtedDsi::orientation() const { return ossimString(theOrientation); } ossimString ossimDtedDsi::latInterval() const { return ossimString(theLatInterval); } ossimString ossimDtedDsi::lonInterval() const { return ossimString(theLonInterval); } ossim_int32 ossimDtedDsi::numLatPoints() const { return atoi(theNumLatPoints); } ossim_int32 ossimDtedDsi::numLonLines() const { return atoi(theNumLonLines); } ossim_int32 ossimDtedDsi::cellIndicator() const { return atoi(theCellIndicator); } ossim_int32 ossimDtedDsi::startOffset() const { return theStartOffset; } ossim_int32 ossimDtedDsi::stopOffset() const { return theStopOffset; } //************************************************************************** // operator << //************************************************************************** std::ostream& operator<<( std::ostream& os, const ossimDtedDsi& dsi) { std::string prefix; return dsi.print(os, prefix); } std::ostream& ossimDtedDsi::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += "dsi."; out << setiosflags(ios::left) << pfx << setw(28) << "recognition_sentinel:" << theRecSen << "\n" << pfx << setw(28) << "security_code:" << theSecurityCode << "\n" << pfx << setw(28) << "product_level:" << theProductLevel << "\n" << pfx << setw(28) << "edition:" << theEdition << "\n" << pfx << setw(28) << "match_merge_version:" << theMatchMergeVersion << "\n" << pfx << setw(28) << "maintenance_date:" << theMaintenanceDate << "\n" << pfx << setw(28) << "match_merge_date:" << theMatchMergeDate << "\n" << pfx << setw(28) << "maintenance_code:" << theMaintenanceCode << "\n" << pfx << setw(28) << "producer_code:" << theProducerCode << "\n" << pfx << setw(28) << "product_stock_spec_number:" << theProductStockSpecNumber << "\n" << pfx << setw(28) << "product_spec_number:" << theProductSpecNumber << "\n" << pfx << setw(28) << "vertical_datum:" << theVerticalDatum << "\n" << pfx << setw(28) << "horizontal_datum:" << theHorizontalDatum << "\n" << pfx << setw(28) << "compilation_date:" << theCompilationDate << "\n" << pfx << setw(28) << "lat_origin:" << theLatOrigin << "\n" << pfx << setw(28) << "lon_origin:" << theLonOrigin << "\n" << pfx << setw(28) << "lat_sw:" << theLatSW << "\n" << pfx << setw(28) << "lon_sw:" << theLonSW << "\n" << pfx << setw(28) << "lat_nw:" << theLatNW << "\n" << pfx << setw(28) << "lon_nw:" << theLonNW << "\n" << pfx << setw(28) << "lat_ne:" << theLatNE << "\n" << pfx << setw(28) << "lon_ne:" << theLonNE << "\n" << pfx << setw(28) << "lat_se:" << theLatSE << "\n" << pfx << setw(28) << "lon_se:" << theLonSE << "\n" << pfx << setw(28) << "orientation:" << theOrientation << "\n" << pfx << setw(28) << "lat_interval:" << theLatInterval << "\n" << pfx << setw(28) << "lon_interval:" << theLonInterval << "\n" << pfx << setw(28) << "number_of_lat_points:" << theNumLatPoints << "\n" << pfx << setw(28) << "number_of_lon_lines:" << theNumLonLines << "\n" << pfx << setw(28) << "cell_indicator:" << theCellIndicator << "\n" << pfx << setw(28) << "start_offset:" << theStartOffset << "\n" << pfx << setw(28) << "stop_offset:" << theStopOffset << std::endl; return out; } ossimDtedDsi::ossimDtedDsi(const ossimDtedDsi& /* source */) {} const ossimDtedDsi& ossimDtedDsi::operator=(const ossimDtedDsi& rhs) { return rhs; } ossim-Miami-2.9.1/src/support_data/ossimDtedHdr.cpp000066400000000000000000000123011352751253100223010ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class gives access to the File Header Label // (HDR) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedHdr.cpp 17501 2010-06-02 11:14:55Z dburken $ #include #include #include #include #include #include #include ossimDtedHdr::ossimDtedHdr() : theStartOffset(0), theStopOffset(0) { } ossimDtedHdr::ossimDtedHdr(std::shared_ptr& str, ossim_int64 offset) : theStartOffset(0), theStopOffset(0) { if(str) { str->seekg(offset); // Continue parsing all the record fields. parse(*str); } else { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } } //************************************************************************** // ossimDtedHdr::parse() //************************************************************************** void ossimDtedHdr::parse(std::istream& in) { clearErrorStatus(); theStartOffset = in.tellg(); theStopOffset = theStartOffset; // Parse theRecSen in.read(theRecSen, FIELD1_SIZE); theRecSen[FIELD1_SIZE] = '\0'; if(!(strncmp(theRecSen, "HDR", 3) == 0)) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; in.seekg(theStartOffset); return; } // Parse Field 2 in.read(theField2, FIELD2_SIZE); theField2[FIELD2_SIZE] = '\0'; // Parse theFilename in.read(theFilename, FIELD3_SIZE); theFilename[FIELD3_SIZE] = '\0'; // Parse Field 4 in.read(theField4, FIELD4_SIZE); theField4[FIELD4_SIZE] = '\0'; // Parse Field 5 in.read(theField5, FIELD5_SIZE); theField5[FIELD5_SIZE] = '\0'; // Parse Field 6 in.read(theField6, FIELD6_SIZE); theField6[FIELD6_SIZE] = '\0'; // Parse Field 7 in.read(theVersion, FIELD7_SIZE); theVersion[FIELD7_SIZE] = '\0'; // Parse theCreationDate in.read(theCreationDate, FIELD8_SIZE); theCreationDate[FIELD8_SIZE] = '\0'; // Parse Field 9 in.read(theField9, FIELD9_SIZE); theField9[FIELD9_SIZE] = '\0'; // Parse Field 10 in.read(theField10, FIELD10_SIZE); theField10[FIELD10_SIZE] = '\0'; // Parse Field 11 in.read(theField11, FIELD11_SIZE); theField11[FIELD11_SIZE] = '\0'; // Parse Field 12 in.read(theField12, FIELD12_SIZE); theField12[FIELD12_SIZE] = '\0'; // Parse Field 13 in.read(theField13, FIELD13_SIZE); theField13[FIELD13_SIZE] = '\0'; // Parse Field 14 in.read(theField14, FIELD14_SIZE); theField14[FIELD14_SIZE] = '\0'; // Set the stop offset. theStopOffset = theStartOffset + HDR_LENGTH; } ossimRefPtr ossimDtedHdr::getProperty( const ossimString& /* name */) const { ossimRefPtr result = 0; return result; } void ossimDtedHdr::getPropertyNames( std::vector& propertyNames) const { propertyNames.push_back(ossimString("dted_hdr_record")); } //************************************************************************** // operator << //************************************************************************** std::ostream& operator<<( std::ostream& os, const ossimDtedHdr& hdr) { std::string prefix; return hdr.print(os, prefix); } std::ostream& ossimDtedHdr::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += "hdr."; out << pfx << "recognition_sentinel: " << theRecSen << "\n" << pfx << "field2: " << theField2 << "\n" << pfx << "filename: " << theFilename << "\n" << pfx << "field4: " << theField4 << "\n" << pfx << "field5: " << theField5 << "\n" << pfx << "field6: " << theField6 << "\n" << pfx << "version: " << theVersion << "\n" << pfx << "creation_date: " << theCreationDate << "\n" << pfx << "field9: " << theField9 << "\n" << pfx << "field10: " << theField10 << "\n" << pfx << "field11: " << theField11 << "\n" << pfx << "field12: " << theField12 << "\n" << pfx << "field13: " << theField13 << "\n" << pfx << "field14: " << theField14 << "\n" << std::endl; return out; } ossimString ossimDtedHdr::recognitionSentinel() const { return theRecSen; } ossimString ossimDtedHdr::fileName() const { return theFilename; } ossimString ossimDtedHdr::version() const { return theVersion; } ossimString ossimDtedHdr::creationDate() const { return theCreationDate; } ossim_int32 ossimDtedHdr::startOffset() const { return theStartOffset; } ossim_int32 ossimDtedHdr::stopOffset() const { return theStopOffset; } ossimDtedHdr::ossimDtedHdr(const ossimDtedHdr& /* source */) {} const ossimDtedHdr& ossimDtedHdr::operator=(const ossimDtedHdr& rhs) { return rhs; } ossim-Miami-2.9.1/src/support_data/ossimDtedInfo.cpp000066400000000000000000000202751352751253100224700ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: DTED Info object. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include ossimDtedInfo::ossimDtedInfo() { } ossimDtedInfo::~ossimDtedInfo() { } bool ossimDtedInfo::open(std::shared_ptr& str, const std::string& connectionString) { bool result = false; if(!str) return false; // Test for extension, like dt0, dt1... ossimString ext = ossimFilename(connectionString).ext(); ossimRegExp regExp("^[d|D][t|T][0-9]"); m_dtedFileStr.reset(); if ( regExp.find( ext.c_str() ) ) { m_vol.parse(*str); m_hdr.parse(*str); m_uhl.parse(*str); m_dsi.parse(*str); m_acc.parse(*str); //--- // Check for errors. Must have uhl, dsi and acc records. vol and hdr // are for magnetic tape only; hence, may or may not be there. //--- if ( (m_uhl.getErrorStatus() == ossimErrorCodes::OSSIM_OK) && (m_dsi.getErrorStatus() == ossimErrorCodes::OSSIM_OK) && (m_acc.getErrorStatus() == ossimErrorCodes::OSSIM_OK) ) { result = true; m_connectionString = connectionString; m_dtedFileStr = str; } else { m_connectionString.clear(); m_dtedFileStr.reset(); } } return result; } std::ostream& ossimDtedInfo::print(std::ostream& out) const { std::string prefix = "dted."; if( m_vol.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { m_vol.print(out, prefix); } if( m_hdr.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { m_hdr.print(out, prefix); } if( m_uhl.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { m_uhl.print(out, prefix); } if( m_dsi.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { m_dsi.print(out, prefix); } if( m_acc.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { m_acc.print(out, prefix); } return out; } ossimRefPtr ossimDtedInfo::getProperty( const ossimString& name)const { ossimRefPtr result = 0; //--- // Look through dted records. // Must have uhl, dsi and acc records. vol and hdr // are for magnetic tape only; hence, may or may not be there. //--- //ossimDtedVol vol(m_dtedFileStr, 0); if( m_vol.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { if (name == "dted_vol_record") { ossimContainerProperty* box = new ossimContainerProperty(); box->setName(name); std::vector list; m_vol.getPropertyNames(list); std::vector< ossimRefPtr > propList; std::vector::const_iterator i = list.begin(); while (i != list.end()) { ossimRefPtr prop = m_vol.getProperty( (*i) ); if (prop.valid()) { propList.push_back(prop); } ++i; } box->addChildren(propList); result = box; } } if (result.valid() == false) { //ossimDtedHdr hdr(m_dtedFileStr, vol.stopOffset()); if( m_hdr.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { if (name == "dted_hdr_record") { ossimContainerProperty* box = new ossimContainerProperty(); box->setName(name); std::vector list; m_hdr.getPropertyNames(list); std::vector< ossimRefPtr > propList; std::vector::const_iterator i = list.begin(); while (i != list.end()) { ossimRefPtr prop = m_hdr.getProperty( (*i) ); if (prop.valid()) { propList.push_back(prop); } ++i; } box->addChildren(propList); result = box; } } if (result.valid() == false) { // ossimDtedUhl uhl(m_dtedFileStr, hdr.stopOffset()); if( m_uhl.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { if (name == "dted_uhl_record") { ossimContainerProperty* box = new ossimContainerProperty(); box->setName(name); std::vector list; m_uhl.getPropertyNames(list); std::vector< ossimRefPtr > propList; std::vector::const_iterator i = list.begin(); while (i != list.end()) { ossimRefPtr prop = m_uhl.getProperty( (*i) ); if (prop.valid()) { propList.push_back(prop); } ++i; } box->addChildren(propList); result = box; } } if (result.valid() == false) { //ossimDtedDsi dsi(m_dtedFileStr, uhl.stopOffset()); if( m_dsi.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { if (name == "dted_dsi_record") { ossimContainerProperty* box = new ossimContainerProperty(); box->setName(name); std::vector list; m_dsi.getPropertyNames(list); std::vector< ossimRefPtr > propList; std::vector::const_iterator i = list.begin(); while (i != list.end()) { ossimRefPtr prop = m_dsi.getProperty( (*i) ); if (prop.valid()) { propList.push_back(prop); } ++i; } box->addChildren(propList); result = box; } } if (result.valid() == false) { //ossimDtedAcc acc(m_dtedFileStr, dsi.stopOffset()); if( m_acc.getErrorStatus() == ossimErrorCodes::OSSIM_OK ) { if (name == "dted_acc_record") { ossimContainerProperty* box = new ossimContainerProperty(); box->setName(name); std::vector list; m_acc.getPropertyNames(list); std::vector< ossimRefPtr > propList; ossimRefPtr prop = 0; std::vector::const_iterator i = list.begin(); while (i != list.end()) { ossimRefPtr prop = m_acc.getProperty( (*i) ); if (prop.valid()) { propList.push_back(prop); } ++i; } box->addChildren(propList); result = box; } } } } } } return result; } void ossimDtedInfo::getPropertyNames( std::vector& propertyNames)const { propertyNames.push_back(ossimString("dted_vol_record")); propertyNames.push_back(ossimString("dted_hdr_record")); propertyNames.push_back(ossimString("dted_uhl_record")); propertyNames.push_back(ossimString("dted_dsi_record")); propertyNames.push_back(ossimString("dted_acc_record")); } ossim-Miami-2.9.1/src/support_data/ossimDtedRecord.cpp000066400000000000000000000215161352751253100230120ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero // // Description: This class gives access to the Data Record Description // of a DTED Level 1 file. // // Notes: Each elevation is a true value referenced to meas sea level // (MSL) datum recorded to the nearest meter. The horizontal // position is referenced to precise longitude-latitiude // locations in terms of the current World Geodetic System // (WGS84) determined for each file by reference to the origin // at the southwest corner. The elevations are evenly spaced // in latitude and longitude at the interval designated in the // User Header Label (UHL) in South to North profile sequence. // //******************************************************************** // $Id: ossimDtedRecord.cpp 20611 2012-02-27 12:21:51Z gpotts $ #include #include #include #include #include #include static const ossim_uint16 DATA_NULL_VALUE = 0xffff; // -32767 static const ossim_uint16 DATA_MIN_VALUE = 0xfffe; // -32766 static const ossim_uint16 DATA_MAX_VALUE = 0x7fff; // +32767 static const ossim_uint16 DATA_VALUE_MASK = 0x7fff; // 0111 1111 1111 1111 static const ossim_uint16 DATA_SIGN_MASK = 0x8000; // 1000 0000 0000 0000 static const ossim_uint16 DATA_RECOGNITION_SENTINEL = 0xAA; // 170 //*** // Offsets from start of data record (one record per longitude line): //*** static const int BLOCK_COUNT_OFFSET = 2; static const int LON_INDEX_OFFSET = 4; static const int LAT_INDEX_OFFSET = 6; static const int ELEV_DATA_OFFSET = 8; static const int RECORD_HDR_LENGTH = 12; static const int BYTES_PER_POINT = 2; //************************************************************************** // CONSTRUCTOR //************************************************************************** ossimDtedRecord::ossimDtedRecord(std::istream& in, ossim_int32 offset, ossim_int32 num_points) : theRecSen("170"), theDataBlockCount(0), theLonCount(0), theLatCount(0), theCheckSum(0), thePoints(new ossim_int32[num_points]), thePointsData(new ossim_uint16[num_points]), theComputedCheckSum(0), theNumPoints(num_points), theStartOffset(offset), theStopOffset(offset + RECORD_HDR_LENGTH + (num_points*BYTES_PER_POINT)) { // Verify we are at a cell record by checking the Recognition Sentinel. ossim_uint8 buf[1]; in.seekg(theStartOffset, std::ios::beg); in.read((char*)buf, 1); #if 0 printf("\nBuf: %02X", (int)buf[0]); // Display in HEX #endif if(buf[0] != DATA_RECOGNITION_SENTINEL) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimDtedRecord::ossimDtedRecord: reading DTED's data record at: " << theStartOffset << std::endl; return; } // Valid data record, so let's process on. parse(in); //*** // Note: The validateCheckSum method works; however, our in-house // dted has bad stored check sums even though the post are good. // So this in temporarily shut off. //*** // Verify Check Sum for uncorrupted elevation data. if(validateCheckSum(in) == false) { //*** // Note: The validateCheckSum method works; however, our in-house // dted has bad stored check sums even though the posts are good. // So this in temporarily shut off. //*** theErrorStatus = ossimErrorCodes::OSSIM_ERROR; ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimDtedRecord::ossimDtedRecord:" << "\nInvalid checksum in data record at: " << theStartOffset << "\nParsed Check Sum = " << theCheckSum << "\nComputed Check Sum = " << theComputedCheckSum << "\nDTED Elevation File is considered corrupted." << std::endl; return; } } ossimDtedRecord::~ossimDtedRecord() { if (thePoints) { delete [] thePoints; thePoints = NULL; } if (thePointsData) { delete [] thePointsData; thePointsData = NULL; } } //************************************************************************** // parse() //************************************************************************** void ossimDtedRecord::parse(std::istream& in) { // DTED is stored in big endian byte order so swap the bytes if needed. bool swap_bytes = ossim::byteOrder() == OSSIM_LITTLE_ENDIAN ? true : false; ossim_sint16 s; // parse data block count in.seekg(theStartOffset + BLOCK_COUNT_OFFSET, std::ios::beg); in.read((char*)&s, 2); theDataBlockCount = (swap_bytes ? ( ( (s & 0x00ff) << 8) | ( (s & 0xff00) >> 8) ) : s); // parse lon count in.seekg(theStartOffset + LON_INDEX_OFFSET, std::ios::beg); in.read((char*)&s, 2); theLonCount = (swap_bytes ? ( ( (s & 0x00ff) << 8) | ( (s & 0xff00) >> 8) ) : s); // parse lat count in.seekg(theStartOffset + LAT_INDEX_OFFSET, std::ios::beg); in.read((char*)&s, 2); theLatCount = (swap_bytes ? ( ( (s & 0x00ff) << 8) | ( (s & 0xff00) >> 8) ) : s); // Parse all elevation points. in.seekg(theStartOffset + ELEV_DATA_OFFSET, std::ios::beg); for(int i = 0; i < theNumPoints; ++i) { in.read((char*)&s, 2); s = (swap_bytes ? ( ( (s & 0x00ff) << 8) | ( (s & 0xff00) >> 8) ) : s); if (s & DATA_SIGN_MASK) { s = (s & DATA_VALUE_MASK) * -1; } thePoints[i] = static_cast(s); thePointsData[i] = s; } } //************************************************************************** // validateCheckSum() //************************************************************************** bool ossimDtedRecord::validateCheckSum(std::istream& in) { // DTED is stored in big endian byte order so swap the bytes if needed. bool swap_bytes = ossim::byteOrder() == OSSIM_LITTLE_ENDIAN ? true : false; // Compute the check sum. in.seekg(theStartOffset, std::ios::beg); theComputedCheckSum = 0; ossim_int32 bytesToRead = (theNumPoints * 2) + ELEV_DATA_OFFSET; int i = 0; for(i = 0; i < bytesToRead; i++) { ossim_uint8 c; in.read((char*)&c, 1); theComputedCheckSum += static_cast(c); } // Read the stored check sum and swap the byte if needed. in.read((char*)&theCheckSum, 4); if (swap_bytes) { ossimEndian swapper; swapper.swap(theCheckSum); } // Compare computed and parsed checksums. if(theCheckSum != theComputedCheckSum) { return false; } return true; } ossimString ossimDtedRecord::recognitionSentinel() const { return theRecSen; } ossim_int32 ossimDtedRecord::dataBlockCount() const { return theDataBlockCount; } ossim_int32 ossimDtedRecord::lonCount() const { return theLonCount; } ossim_int32 ossimDtedRecord::latCount() const { return theLatCount; } ossim_uint32 ossimDtedRecord::checkSum() const { return theCheckSum; } ossim_uint32 ossimDtedRecord::computedCheckSum() const { return theComputedCheckSum; } ossim_int32 ossimDtedRecord::numPoints() const { return theNumPoints; } ossim_int32 ossimDtedRecord::getPoint(ossim_int32 i) const { return thePoints[i]; } ossim_uint16 ossimDtedRecord::getPointData(ossim_int32 i) const { return thePointsData[i]; } ossim_int32* ossimDtedRecord::points() const { return thePoints; } ossim_uint16* ossimDtedRecord::pointsData() const { return thePointsData; } ossim_int32 ossimDtedRecord::startOffset() const { return theStartOffset; } ossim_int32 ossimDtedRecord::stopOffset() const { return theStopOffset; } //************************************************************************** // operator << //************************************************************************** std::ostream& operator<<( std::ostream& os, const ossimDtedRecord& rec) { os << "\nDTED Record:" << "\n-------------------------------" << "\n Recognition Sentinel: " << rec.theRecSen << "\nData Block Count: " << rec.theDataBlockCount << "\nLon Count: " << rec.theLonCount << "\nLat Count: " << rec.theLatCount << "\nNum Points: " << rec.theNumPoints << "\nParsed Check Sum: " << rec.theCheckSum << "\nComputed Check Sum " << rec.theComputedCheckSum << "\nStart Offset: " << rec.theStartOffset << "\nStop Offset: " << rec.theStopOffset << std::endl; int i = 0; for(i = 0; i < rec.theNumPoints; i++) { os << "\nPoint[" << i << "]: " << rec.thePoints[i]; } os << std::endl; return os; } ossim-Miami-2.9.1/src/support_data/ossimDtedUhl.cpp000066400000000000000000000163011352751253100223200ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: This class gives access to the User Header Label // (UHL) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedUhl.cpp 23277 2015-04-24 21:02:24Z rashadkm $ #include #include #include #include #include #include #include #include #include using namespace std; ossimDtedUhl::ossimDtedUhl() { } ossimDtedUhl::ossimDtedUhl(std::shared_ptr& str, ossim_int64 offset) : theRecSen(), theField2(), theLonOrigin(), theLatOrigin(), theLonInterval(), theLatInterval(), theAbsoluteLE(), theSecurityCode(), theNumLonLines(), theNumLatPoints(), theMultipleAccuracy(), theStartOffset(0), theStopOffset(0) { if(str) { str->seekg(offset); parse(*str); } else { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } } //************************************************************************** // ossimDtedUhl::parse() //************************************************************************** void ossimDtedUhl::parse(std::istream& in) { clearErrorStatus(); theStartOffset = in.tellg(); theStopOffset = theStartOffset; // Parse theRecSen in.read(theRecSen, FIELD1_SIZE); theRecSen[FIELD1_SIZE] = '\0'; if(!(strncmp(theRecSen, "UHL", 3) == 0)) { // Not a user header label. theErrorStatus = ossimErrorCodes::OSSIM_ERROR; in.seekg(theStartOffset); return; } // Parse Field 2 in.read(theField2, FIELD2_SIZE); theField2[FIELD2_SIZE] = '\0'; // Parse theLonOrigin in.read(theLonOrigin, FIELD3_SIZE); theLonOrigin[FIELD3_SIZE] = '\0'; // Parse theLatOrigin in.read(theLatOrigin, FIELD4_SIZE); theLatOrigin[FIELD4_SIZE] = '\0'; // Parse theLonInterval in.read(theLonInterval, FIELD5_SIZE); theLonInterval[FIELD5_SIZE] = '\0'; // Parse theLatInterval in.read(theLatInterval, FIELD6_SIZE); theLatInterval[FIELD6_SIZE] = '\0'; // Parse theAbsoluteLE in.read(theAbsoluteLE, FIELD7_SIZE); theAbsoluteLE[FIELD7_SIZE] = '\0'; // Parse theSecurityCode in.read(theSecurityCode, FIELD8_SIZE); theSecurityCode[FIELD8_SIZE] = '\0'; // Parse Field 9 in.read(theField9, FIELD9_SIZE); theField9[FIELD9_SIZE] = '\0'; // Parse theNumLonLines in.read(theNumLonLines, FIELD10_SIZE); theNumLonLines[FIELD10_SIZE] = '\0'; // Parse theNumLatPoints in.read(theNumLatPoints, FIELD11_SIZE); theNumLatPoints[FIELD11_SIZE] = '\0'; // Parse theMultipleAccuracy in.read(theMultipleAccuracy, FIELD12_SIZE); theMultipleAccuracy[FIELD12_SIZE] = '\0'; // Field 13 not parsed as it's unused. in.ignore(FIELD13_SIZE); // Set the stop offset. theStopOffset = theStartOffset + UHL_LENGTH; } ossimRefPtr ossimDtedUhl::getProperty( const ossimString& /* name */) const { ossimRefPtr result = 0; return result; } void ossimDtedUhl::getPropertyNames( std::vector& propertyNames) const { propertyNames.push_back(ossimString("dted_uhl_record")); } ossimString ossimDtedUhl::recognitionSentinel() const { return theRecSen; } double ossimDtedUhl::lonOrigin() const { return degreesFromString(theLonOrigin); } double ossimDtedUhl::latOrigin() const { return degreesFromString(theLatOrigin); } double ossimDtedUhl::lonInterval() const { return spacingFromString(theLonInterval); } double ossimDtedUhl::latInterval() const { return spacingFromString(theLatInterval); } double ossimDtedUhl::degreesFromString(const char* str) const { // Parse the string: DDDMMMSSH if (!str) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimDtedUhl::degreesFromString: " << "Null pointer passed to method!" << std::endl; return 0.0; } if (strlen(str) < 8) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimDtedUhl::decimalDegreesFromString:" << "String not big enough!" << std::endl; return 0.0; } double d = ((str[0]-'0')*100 + (str[1]-'0')*10 + (str[2]-'0') + (str[3]-'0')/6.0 + (str[4]-'0')/60.0 + (str[5]-'0')/360.0 + (str[6]-'0')/3600.0); if ( (str[7] == 'S') || (str[7] == 's') || (str[7] == 'W') || (str[7] == 'w') ) { d *= -1.0; } return d; } double ossimDtedUhl::spacingFromString(const char* str) const { // Parse the string: SSSS (tenths of a second) if (!str) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimDtedUhl::decimalDegreesFromString: " << "Null pointer passed to method!" << std::endl; return 0.0; } return atof(str) / 36000.0; // return 10ths of second as decimal degrees. } double ossimDtedUhl::absoluteLE() const { return strtod(theAbsoluteLE, NULL); } ossimString ossimDtedUhl::securityCode() const { return theSecurityCode; } ossim_int32 ossimDtedUhl::numLonLines() const { return atoi(theNumLonLines); } ossim_int32 ossimDtedUhl::numLatPoints() const { return atoi(theNumLatPoints); } ossim_int32 ossimDtedUhl::mulitpleAccuracy() const { return atoi(theMultipleAccuracy); } ossim_int32 ossimDtedUhl::startOffset() const { return theStartOffset; } ossim_int32 ossimDtedUhl::stopOffset() const { return theStopOffset; } //************************************************************************** // operator << //************************************************************************** std::ostream& operator<<( std::ostream& out, const ossimDtedUhl& uhl) { std::string prefix; return uhl.print(out, prefix); } std::ostream& ossimDtedUhl::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += "uhl."; out << setiosflags(ios::left) << pfx << setw(28) << "recognition_sentinel:" << theRecSen << "\n" << pfx << setw(28) << "lon_origin:" << theLonOrigin << "\n" << pfx << setw(28) << "lat_origin:" << theLatOrigin << "\n" << pfx << setw(28) << "lon_interval:" << theLonInterval << "\n" << pfx << setw(28) << "lat_interval:" << theLatInterval << "\n" << pfx << setw(28) << "absolute_le:" << theAbsoluteLE << "\n" << pfx << setw(28) << "security_code:" << theSecurityCode << "\n" << pfx << setw(28) << "number_of_lat_points:" << theNumLatPoints << "\n" << pfx << setw(28) << "number_of_lon_lines:" << theNumLonLines << "\n" << pfx << setw(28) << "multiple_accuracy:" << theMultipleAccuracy << "\n" << pfx << setw(28) << "start_offset:" << theStartOffset << "\n" << pfx << setw(28) << "stop_offset:" << theStopOffset << std::endl; return out; } ossimDtedUhl::ossimDtedUhl(const ossimDtedUhl& /* source */) { } const ossimDtedUhl& ossimDtedUhl::operator=(const ossimDtedUhl& rhs) { return rhs; } ossim-Miami-2.9.1/src/support_data/ossimDtedVol.cpp000066400000000000000000000135431352751253100223350ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero // // Description: This class gives access to the Volume Header Label // (VOL) of a DTED Level 1 file. // //******************************************************************** // $Id: ossimDtedVol.cpp 17501 2010-06-02 11:14:55Z dburken $ #include #include #include #include #include #include #include ossimDtedVol::ossimDtedVol() :theStartOffset(0), theStopOffset(0) { } ossimDtedVol::ossimDtedVol(std::shared_ptr& str, ossim_int64 offset) : theStartOffset(0), theStopOffset(0) { if(str) { str->seekg(offset); parse(*str); } else { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } } //************************************************************************** // CONSTRUCTOR //************************************************************************** // ossimDtedVol::ossimDtedVol(const ossimFilename& dted_file, // ossim_int32 offset) // : // theStartOffset(0), // theStopOffset(0) // { // if(!dted_file.empty()) // { // // Check to see that dted file exists. // if(!dted_file.exists()) // { // theErrorStatus = ossimErrorCodes::OSSIM_ERROR; // ossimNotify(ossimNotifyLevel_FATAL) // << "FATAL ossimDtedVol::ossimDtedVol" // << "\nThe DTED file does not exist: " << dted_file << std::endl; // return; // } // // Check to see that the dted file is readable. // if(!dted_file.isReadable()) // { // theErrorStatus = ossimErrorCodes::OSSIM_ERROR; // ossimNotify(ossimNotifyLevel_FATAL) // << "FATAL ossimDtedVol::ossimDtedVol" // << "\nThe DTED file is not readable: " << dted_file << std::endl; // return; // } // // Open the dted file for reading. // std::ifstream in(dted_file.c_str()); // if(!in) // { // theErrorStatus = ossimErrorCodes::OSSIM_ERROR; // ossimNotify(ossimNotifyLevel_FATAL) // << "FATAL ossimDtedVol::ossimDtedVol" // << "\nUnable to open the DTED file: " << dted_file << std::endl; // return; // } // in.seekg(offset); // parse(in); // in.close(); // } // } //************************************************************************** // CONSTRUCTOR //************************************************************************** // ossimDtedVol::ossimDtedVol(std::istream& in) // : // theStartOffset(0), // theStopOffset(0) // { // parse(in); // } void ossimDtedVol::parse(std::istream& in) { clearErrorStatus(); theStartOffset = in.tellg(); theStopOffset = theStartOffset; // Parse theRecSen in.read(theRecSen, FIELD1_SIZE); theRecSen[FIELD1_SIZE] = '\0'; if(!(strncmp(theRecSen, "VOL", 3) == 0)) { // Not a volume header label. theErrorStatus = ossimErrorCodes::OSSIM_ERROR; in.seekg(theStartOffset); return; } // Parse Field 2 in.read(theField2, FIELD2_SIZE); theField2[FIELD2_SIZE] = '\0'; // Parse theReelNumber in.read(theReelNumber, FIELD3_SIZE); theReelNumber[FIELD3_SIZE] = '\0'; // Parse Field 4 in.read(theField4, FIELD4_SIZE); theField4[FIELD4_SIZE] = '\0'; // Parse Field 5 in.read(theField5, FIELD5_SIZE); theField5[FIELD5_SIZE] = '\0'; // Parse theAccountNumber in.read(theAccountNumber, FIELD6_SIZE); theAccountNumber[FIELD6_SIZE] = '\0'; // Parse Field 7 in.read(theField7, FIELD7_SIZE); theField7[FIELD7_SIZE] = '\0'; // Parse Field 8 in.read(theField8, FIELD8_SIZE); theField8[FIELD8_SIZE] = '\0'; // Set the stop offset. theStopOffset = theStartOffset + VOL_LENGTH; } ossimRefPtr ossimDtedVol::getProperty( const ossimString& /* name */) const { ossimRefPtr result = 0; return result; } void ossimDtedVol::getPropertyNames( std::vector& propertyNames) const { propertyNames.push_back(ossimString("dted_vol_record")); } ossimString ossimDtedVol::getRecognitionSentinel() const { return ossimString(theRecSen); } ossimString ossimDtedVol::getReelNumber() const { return ossimString(theReelNumber); } ossimString ossimDtedVol::getAccountNumber() const { return ossimString(theAccountNumber); } ossim_int32 ossimDtedVol::startOffset() const { return theStartOffset; } ossim_int32 ossimDtedVol::stopOffset() const { return theStopOffset; } std::ostream& ossimDtedVol::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += "vol."; out << pfx << "recognition_sentinel: " << theRecSen << "\n" << pfx << "field2: " << theField2 << "\n" << pfx << "reel_number: " << theReelNumber << "\n" << pfx << "field4: " << theField4 << "\n" << pfx << "field5: " << theField5 << "\n" << pfx << "account_number: " << theAccountNumber << "\n" << pfx << "field7: " << theField7 << "\n" << pfx << "field8: " << theField8 << "\n" << std::endl; return out; } //************************************************************************** // operator << //************************************************************************** std::ostream& operator<<( std::ostream& out, const ossimDtedVol& vol) { std::string prefix; return vol.print(out, prefix); } ossimDtedVol::ossimDtedVol(const ossimDtedVol& /* source */) { } const ossimDtedVol& ossimDtedVol::operator=(const ossimDtedVol& rhs) { return rhs; } ossim-Miami-2.9.1/src/support_data/ossimERS.cpp000066400000000000000000000424511352751253100214250ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Chong-Ket Chuah // Contributor: Anrew Huang // // Description: // Implementation of ossimERS class for parsing a ER Mapper raster // file format header. // //******************************************************************** // $Id: ossimERS.cpp 17501 2010-06-02 11:14:55Z dburken $ #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimERS:debug"); ossimERS::ossimERS() : ossimErrorStatusInterface() { clearFields(); } ossimERS::ossimERS(const char* headerFile) : ossimErrorStatusInterface() { clearFields(); // open the header file: std::ifstream in; in.open(headerFile, std::ios::in | std::ios::binary); if (!in) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } // Begin parsing records: if (!theErrorStatus) { parseHeader(in); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimERS DEBUG:" << *this << std::endl; } } void ossimERS::parseError(const char* /* msg*/ ) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } void ossimERS::parseRasterInfo(std::istream& in) { std::vector tokens; bool done = false; while (!done) { tokens = parseLine(in); if (tokens.empty()) { parseError("premature end of header file."); return; } if (tokens[0] == "CellType") { if (tokens[1] == "Unsigned8BitInteger") { theCelltype = OSSIM_UCHAR; } else if (tokens[1] == "Unsigned16BitInteger") { theCelltype = OSSIM_USHORT16; } else if (tokens[1] == "Signed16BitInteger") { theCelltype = OSSIM_SSHORT16; } else if (tokens[1] == "IEEE4ByteReal") { theCelltype = OSSIM_FLOAT; } else if (tokens[1] == "IEEE8ByteReal") { theCelltype = OSSIM_DOUBLE; } else { parseError("Unsupported CellType."); } } else if (tokens[0] == "NullCellValue") { theHasNullCells = true; theNullCell = tokens[1].toInt(); // float nullcell value? } else if (tokens[0] == "Xdimension") { // ignore "CellInfo" theCellSizeX = tokens[1].toDouble(); } else if (tokens[0] == "Ydimension") { // ignore "CellInfo" theCellSizeY = tokens[1].toDouble(); } else if (tokens[0] == "NrOfLines") { theLine = tokens[1].toInt(); } else if (tokens[0] == "NrOfCellsPerLine") { theSample = tokens[1].toInt(); } else if (tokens[0] == "Eastings") { // ignore "RegistrationCoord" theTieUnitType = OSSIM_METERS; theOriginX = tokens[1].toDouble(); } else if (tokens[0] == "Northings") { // ignore "RegistrationCoord" theTieUnitType = OSSIM_METERS; theOriginY = tokens[1].toDouble(); } else if (tokens[0] == "Longitude") { // ignore "RegistrationCoord" // need to check coordinatestype ("Cannot use Latitude with UTM projection") double deg, min, sec; sscanf (tokens[1].chars(), "%lg:%lg:%lg", °, &min, &sec); theOriginX = std::abs(deg) + min/60.0 + sec/3600.0; if (deg < 0.0) { theOriginX = -theOriginX; } theTieUnitType = OSSIM_DEGREES; } else if (tokens[0] == "Latitude") { // ignore "RegistrationCoord" double deg, min, sec; sscanf (tokens[1].chars(), "%lg:%lg:%lg", °, &min, &sec); theOriginY = std::abs(deg) + min/60.0 + sec/3600.0; if (deg < 0.0) { theOriginY = -theOriginY; } theTieUnitType = OSSIM_DEGREES; } else if (tokens[0] == "NrOfBands") { theBands = tokens[1].toInt(); } else if (tokens[0] == "Value") { // ignore "BandID" // keep adding to the bandID vector // delete Value key then join the rest of tokens tokens.erase(tokens.begin()); ossimString id; id.join(tokens, " "); theBandID.push_back(id); } else if (tokens[0] == "RasterInfo") { done = true; } } } void ossimERS::parseCoordinateSpace(std::istream& in) { std::vector tokens; bool done = false; while (!done) { tokens = parseLine(in); if (tokens.empty()) { parseError("premature end of header file."); return; } if (tokens[0] == "Datum") { theDatum = tokens[1]; if (theDatum != "WGS84" && theDatum != "RAW") { parseError("Datum must be WGS84 or RAW"); } } else if (tokens[0] == "Projection") { theProjection = tokens[1]; // need to parse projection string /*(EqualStrings (tok(1,3), "UTM")) { coordinateSystem = 'U'; if (tok(0) == 'N') northernHemisphere = 1; else northernHemisphere = 0; spString zoneStr = tok(4,2); sscanf (zoneStr.chars(), "%d", &zone); */ } else if (tokens[0] == "CoordinateType") { // ignore it } else if (tokens[0] == "Units") { // ignore it for now } else if (tokens[0] == "Rotation") { double deg, min, sec; sscanf (tokens[1].chars(), "%lg:%lg:%lg", °, &min, &sec); theRotation = deg + min/60.0 + sec/3600.0; } else if (tokens[0] == "CoordinateSpace") { done = true; } } // requires more error checking on unit and rotation here return; } void ossimERS::parseHeader(std::istream& in) { theErrorStatus = ossimErrorCodes::OSSIM_OK; char magicNumberTest[14]; in.read(magicNumberTest, 13); if(ossimString(magicNumberTest, magicNumberTest+13) != "DatasetHeader") { parseError("First line must be DatasetHeader"); return; } in.seekg(0); std::vector tokens = parseLine(in); if(!tokens.size()) { parseError("First line must be DatasetHeader"); return; } if (tokens[0] != "DatasetHeader") { parseError("First line must be DatasetHeader"); return; } bool done = false; while (!done) { tokens = parseLine(in); if (tokens.empty()) { parseError("premature end of header file."); return; } if (tokens[0] == "Version") { theVersion = tokens[1].toDouble(); if (theVersion < 4.0) { parseError("Version must be 4.0 or greater"); } } else if (tokens[0] == "DataSetType") { theDatasetType = tokens[1]; if (theDatasetType != "ERStorage") { parseError("DataSetType must be ERStorage"); } } else if (tokens[0] == "DataType") { theDatatype = tokens[1]; if (theDatatype != "Raster") { parseError("DataType must be Raster"); } } else if (tokens[0] == "ByteOrder") { theByteorder = tokens[1]; if (theByteorder != "MSBFirst" && theByteorder != "LSBFirst") { parseError("ByteOrder must either be MSBFirst or LSBFirst"); } } else if (tokens[0] == "CoordinateSpace") { if (tokens[1] == "Begin") { parseCoordinateSpace(in); } } else if (tokens[0] == "RasterInfo") { if (tokens[1] == "Begin") { parseRasterInfo(in); } } else if (tokens[0] == "SenseDate") { // ignore for now } else if (tokens[0] == "Comments") { // ignore for now } else if (tokens[0] == "DatasetHeader") { done = true; } } if(theProjection.contains("GEODETIC")) { theTieUnitType = OSSIM_DEGREES; } return; } // read a line from the file, split it using "= \t\n" delimiters. // if the first token is empty, if the line begins with a tab, delete // the token. The second token, the value for the key, may be quoted. // trim the quotes. std::vector ossimERS::parseLine(std::istream& in) { /* const int bufSize = 500; */ ossimString line; std::vector tokens; bool invalidCharHit = false; const int MAX_LENGTH = 10000; int tempCount = 0; // read a line, skipping empty line while (tokens.empty()&&(in)&&(tempCount < MAX_LENGTH)) { tempCount = 1; char c = in.get(); while( (c != '\n')&& (!in.eof())&& (!invalidCharHit)) { if(c > 0x7e) { invalidCharHit = true; } else { line += (char)c; c = in.get(); ++tempCount; } } if(!invalidCharHit) { line.trim('\t'); line.trim('\n'); line.trim('\r'); line.trim(' '); if(line != "") { tokens = line.split("= \t"); if (tokens.size() > 1) { tokens[1].trim('\"'); tokens.back().trim('\"'); } } } else { tokens.clear(); return tokens; } } if(in.bad()||(tempCount>=MAX_LENGTH)) { tokens.clear(); } return tokens; } bool ossimERS::writeFile(const ossimFilename &file) { if (theDescription.empty()) { theDescription = file; } std::ofstream out(file.c_str(), std::ios_base::out); if (!out) { return false; } print(out); out.close(); return true; } std::ostream& ossimERS::print(std::ostream& out) const { out<< std::setiosflags(std::ios::fixed) << std::setprecision(12); out<<"DatasetHeader Begin" < #include #include #include #include #include #include #include #include #include #include #include typedef std::unary_function, bool> KwlCompareFunctionType; typedef std::pair KwlComparePairType; class KwlKeyCaseInsensitiveEquals : public KwlCompareFunctionType { public: KwlKeyCaseInsensitiveEquals(const ossimString& key):m_key(key){} virtual bool operator()(const KwlComparePairType& rhs)const { return (m_key == rhs.first.downcase()); } ossimString m_key; }; class KwlKeySubStringCaseInsensitive : public KwlCompareFunctionType { public: KwlKeySubStringCaseInsensitive(const ossimString& key):m_key(key){} virtual bool operator()(const KwlComparePairType& rhs)const { return (rhs.first.downcase().contains(m_key)); } ossimString m_key; }; // Define keywords not already found in ossimKeywordNames. static const char HEADER_OFFSET_KW[] = "header_offset"; static const char FILE_TYPE_KW[] = "file_type"; static const char DATA_TYPE_KW[] = "data_type"; static const char SENSOR_TYPE_KW[] = "sensor_type"; static const char X_START_KW[] = "x_start"; static const char Y_START_KW[] = "y_start"; static const char MAP_INFO_KW[] = "map_info"; static const char WAVELENGTH_UNITS_KW[] = "wavelength_units"; static const char BAND_NAME_KW[] = "band_name"; static const char WAVELENGTH_KW[] = "wavelength"; static ossimTrace traceDebug(ossimString("ossimEnviHeader:debug")); ossimEnviHeader::ossimEnviHeader() : m_file(), m_keywords() { // Start the byte order of with the machine byte order. m_keywords[FILE_TYPE_KW] = "ENVI Standard"; setByteorder(ossim::byteOrder()); } ossimEnviHeader::~ossimEnviHeader() { } void ossimEnviHeader::reset() { m_file.string().clear(); m_keywords.clear(); m_keywords[FILE_TYPE_KW] = "ENVI Standard"; setByteorder(ossim::byteOrder()); } const ossimKeywordlist& ossimEnviHeader::getMap() const { return m_keywords; } ossimKeywordlist& ossimEnviHeader::getMap() { return m_keywords; } bool ossimEnviHeader::getValue( const ossimString& key, ossimString& value ) const { bool result = false; value.string() = m_keywords.findKey( key.string()); if( value.size() ) { result = true; } else { result = m_keywords.hasKey( key.string() ); } return result; } bool ossimEnviHeader::findSubStringCaseInsensitive(const ossimString& key, ossimString& value) const { return m_keywords.findValue( value, KwlKeySubStringCaseInsensitive(key)); } bool ossimEnviHeader::open(const ossimFilename& file) { bool result = false; reset(); // Clear the map, file name. std::ifstream in; in.open(file.c_str(), std::ios::in | std::ios::binary); if( in.is_open() ) { result = readStream( in ); if ( result ) { m_file = file; } } return result; } bool ossimEnviHeader::readStream(std::istream& in) { reset(); bool result = isEnviHeader( in ); if ( result ) { m_keywords.clear(); while(!in.eof()&&in.good()) { // read name ossimString name = ""; ossimString value = ""; ossim::skipws(in); int c = static_cast(in.get()); while((c != '=')&&(in.good())&&!in.eof()) { name +=static_cast(c); c = in.get(); } ossim::skipws(in); c = in.get(); if(in.good()&&!in.eof()) { if(c == '{') // continue til '}' { c = in.get(); while((c != '}')&&(in.good())&&!in.eof()) { value +=static_cast(c); c = in.get(); } } else { while(((c != '\n')&&(c!='\r'))&&(in.good())&&!in.eof()) { value +=static_cast(c); c = (in.get()); } } m_keywords.add(name.trim(), value); } } // Test for minimum set of keywords needed. if ( m_keywords.findKey( std::string("samples") ).empty() || m_keywords.findKey( std::string("lines") ).empty() || m_keywords.findKey( std::string("bands") ).empty()) { result = false; } } return result; } bool ossimEnviHeader::writeFile(const ossimFilename& file) { if (m_keywords.findKey( std::string("description") ).empty()) { m_keywords["description"] = file.c_str(); } std::ofstream out(file.c_str(), std::ios_base::out); if (!out) { return false; } print(out); out.close(); return true; } std::ostream& ossimEnviHeader::print(std::ostream& out) const { out << "ENVI" << "\n" << m_keywords << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const ossimEnviHeader& obj) { return obj.print( out ); } ossimString ossimEnviHeader::getDescription() const { return ossimString( m_keywords.findKey( std::string("description") ) ); } void ossimEnviHeader::setDescription(const ossimString& description) { m_keywords["description"] = description.c_str(); } ossim_uint32 ossimEnviHeader::getSamples() const { ossim_uint32 result = 0; ossimString value = m_keywords.findKey( std::string("samples") ); if( value.size() ) { result = value.toUInt32(); } return result; } void ossimEnviHeader::setSamples(ossim_uint32 samples) { m_keywords[ std::string("samples") ] = ossimString::toString(samples).c_str(); } ossim_uint32 ossimEnviHeader::getLines() const { ossim_uint32 result = 0; ossimString value = m_keywords.findKey( std::string("lines") ); if( value.size() ) { result = value.toUInt32(); } return result; } void ossimEnviHeader::setLines(ossim_uint32 lines) { m_keywords["lines"] = ossimString::toString(lines).c_str(); } ossim_uint32 ossimEnviHeader::getBands() const { ossim_uint32 result = 0; ossimString value = m_keywords.findKey( std::string("bands") ); if( value.size() ) { result = value.toUInt32(); } return result; } void ossimEnviHeader::setBands(ossim_uint32 bands) { m_keywords["bands"] = ossimString::toString(bands).c_str(); } bool ossimEnviHeader::getDefaultBands( std::vector& bands ) const { bands.clear(); // Note: We could do a "m_map.downcaseKeywords()". (drb) ossimString value = m_keywords.findKey( std::string("default bands") ); if ( !value.size() ) { value = m_keywords.findKey( std::string("Default bands") ); if ( !value.size() ) { value = m_keywords.findKey( std::string("DEFAULT BANDS") ); } } if ( value.size() ) { std::vector strLst; value.split( strLst, ossimString(",")); if ( strLst.size() ) { std::vector::const_iterator i = strLst.begin(); ossim_uint32 band = 0; while ( i != strLst.end() ) { band = (*i).toUInt32(); if ( band ) { // Assuming "default bands" are one based. Totally a hunch... (drb) --band; bands.push_back(band); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimEnviHeader::getDefaultBands WARN!" << "\nDetected zero based bands in \"default bands\" from header!" << std::endl; } ++i; } } } if ( rangeCheckBands( bands ) == false ) { bands.clear(); } return (bands.size() ? true : false); } ossim_uint32 ossimEnviHeader::getHeaderOffset() const { ossim_uint32 result = 0; ossimString value = m_keywords["header offset"]; if( value.size() ) { result = value.toUInt32(); } return result; } void ossimEnviHeader::setHeaderOffset(ossim_uint32 headerOffset) { m_keywords["header offset"] = ossimString::toString(headerOffset).c_str(); } ossimString ossimEnviHeader::getFileType() const { return m_keywords[FILE_TYPE_KW]; } void ossimEnviHeader::setFileType(const ossimString& fileType) { m_keywords[FILE_TYPE_KW] = fileType.c_str(); } ossim_uint32 ossimEnviHeader::getDataType() const { return ossimString(m_keywords["data type"]).toUInt32(); } ossimScalarType ossimEnviHeader::getOssimScalarType() const { ossim_uint32 dataTypeInt = ossimString(m_keywords["data type"]).toUInt32(); ossimScalarType result = OSSIM_SCALAR_UNKNOWN; switch( dataTypeInt ) { case 1: result = OSSIM_UINT8; break; case 2: result = OSSIM_SINT16; break; case 3: result = OSSIM_SINT32; break; case 4: result = OSSIM_FLOAT32; break; case 5: result = OSSIM_FLOAT64; break; case 6: result = OSSIM_CFLOAT32; break; case 9: result = OSSIM_CFLOAT64; break; case 12: result = OSSIM_UINT16; break; case 13: result = OSSIM_UINT32; break; default: break; } return result; } void ossimEnviHeader::setDataType(ossimScalarType scalar) { ossimString dataTypeString = ""; switch( scalar ) { case OSSIM_UINT8: dataTypeString = "1"; break; case OSSIM_SINT16: dataTypeString = "2"; break; case OSSIM_SINT32: dataTypeString = "3"; break; case OSSIM_FLOAT32: dataTypeString = "4"; break; case OSSIM_FLOAT64: dataTypeString = "5"; break; case OSSIM_CFLOAT32: dataTypeString = "6"; break; case OSSIM_CFLOAT64: dataTypeString = "9"; break; case OSSIM_UINT16: dataTypeString = "12"; break; case OSSIM_UINT32: dataTypeString = "13"; break; default: break; } if(!dataTypeString.empty()) { m_keywords["data type"] = dataTypeString.c_str(); } } ossimString ossimEnviHeader::getInterleaveType() const { return m_keywords["interleave"]; } ossimInterleaveType ossimEnviHeader::getOssimInterleaveType() const { ossimString interleave = getInterleaveType(); if (interleave == "bsq") { return OSSIM_BSQ; } else if (interleave == "bil") { return OSSIM_BIL; } else if (interleave == "bip") { return OSSIM_BIP; } else { return OSSIM_INTERLEAVE_UNKNOWN; } } void ossimEnviHeader::setInterleaveType(ossimInterleaveType interleave) { std::string interleaveString = ""; switch (interleave) { case OSSIM_BIL: interleaveString = "bil"; break; case OSSIM_BSQ: interleaveString = "bsq"; break; case OSSIM_BIP: interleaveString = "bip"; break; default: interleaveString = "Unknown"; break; } m_keywords["interleave"] = interleaveString; } ossimString ossimEnviHeader::getSensorType() const { return m_keywords["sensor type"]; } void ossimEnviHeader::setSensorType(const ossimString& sensorType) { m_keywords["sensor type"] = sensorType.c_str(); } ossimByteOrder ossimEnviHeader::getByteOrder() const { ossimByteOrder result = ossim::byteOrder(); // System byte order. std::string value = m_keywords["byte order"]; if ( value.size() ) { // 0 = LITTLE_ENDIAN // 1 = BIG_ENDIAN ossim_int32 order = ossimString(value).toInt32(); result = order ? OSSIM_BIG_ENDIAN : OSSIM_LITTLE_ENDIAN; } return result; } void ossimEnviHeader::setByteorder(ossimByteOrder byteOrder) { if(byteOrder==OSSIM_LITTLE_ENDIAN) { m_keywords["byte order"] = "0"; } else { m_keywords["byte order"] = "1"; } } ossim_int32 ossimEnviHeader::getXStart() const { ossim_int32 result = 0; std::string s = m_keywords.findKey( std::string("x start") ); if ( !s.size() ) { s = m_keywords.findKey( std::string("sample start") ); } if ( s.size() ) { result = ossimString( s ).toInt32(); } return result; } void ossimEnviHeader::setXStart(ossim_int32 xstart) { m_keywords["x start"] = ossimString::toString(xstart).c_str(); } ossim_int32 ossimEnviHeader::getYStart() const { ossim_int32 result = 0; std::string s = m_keywords.findKey( std::string("y start") ); if ( !s.size() ) { s = m_keywords.findKey( std::string("line start") ); } if ( s.size() ) { result = ossimString( s ).toInt32(); } return result; } void ossimEnviHeader::setYStart(ossim_int32 ystart) { m_keywords["y start"] = ossimString::toString(ystart).c_str(); } ossimString ossimEnviHeader::getMapInfo() const { return m_keywords["map info"]; } void ossimEnviHeader::setMapInfo(const ossimString& mapInfo) { m_keywords["map info"] = mapInfo.c_str(); } void ossimEnviHeader::setMapInfo(const ossimKeywordlist& kwl, const char* prefix) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimEnviHeader::setMapInfo DEBUG:" << "\nkwl:\n" << kwl << std::endl; } ossimString mapInfoString; const char* lookup; // Get the projection type. ossimString projection; lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if (lookup) { projection = lookup; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimEnviHeader::setMapInfo WARNING:" << "\nNo projection type found!\nReturning..." << std::endl; return; // Have to have the projection type! } // Get the datum. ossimString datum = "WGS-84"; lookup = kwl.find(prefix, ossimKeywordNames::DATUM_KW); if (lookup) { ossimString os = lookup; if (os == "WGE") { datum = "WGS-84"; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimEnviHeader::setMapInfo WARNING:" << "\nUnhandled ossim -> envi datum: " << datum << "\nAssuming WGS-84!" << std::endl; } } if ( (projection == "ossimEquDistCylProjection") || (projection == "ossimLlxyProjection") ) { const char* tieLat = NULL; const char* tieLon = NULL; const char* degLat = NULL; const char* degLon = NULL; tieLat = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LAT_KW); tieLon = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LON_KW); degLat = kwl.find(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT); degLon = kwl.find(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON); if (!tieLat || !tieLon || !degLat || !degLon) { return; } mapInfoString = "{Geographic Lat/Lon, 1.0000, 1.0000, "; mapInfoString += tieLon; mapInfoString += ", "; mapInfoString += tieLat; mapInfoString += ", "; mapInfoString += degLon; mapInfoString += ", "; mapInfoString += degLat; mapInfoString += ", "; mapInfoString += datum; mapInfoString += ", units=degrees}"; } m_keywords["map info"] = mapInfoString.c_str(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimEnviHeader::setMapInfo DEBUG:" << "\ntheMapInfo: " << mapInfoString << std::endl; } } ossimString ossimEnviHeader::getWavelengthUnits() const { return m_keywords["wavelength units"]; } void ossimEnviHeader::setWavelengthUnits(const ossimString& waveLengthUnits) { m_keywords["wavelength units"] = waveLengthUnits.c_str(); } void ossimEnviHeader::getBandNames(std::vector& bandNames) const { bandNames.clear(); ossimString bandNamesString = m_keywords["band names"]; bandNamesString.split(bandNames, ","); } void ossimEnviHeader::setBandNames(const std::vector& bandNames) { ossimString value; value.join(bandNames, ","); m_keywords["band names"] = value.c_str(); } void ossimEnviHeader::getWavelengths(std::vector& waveLengths) const { waveLengths.clear(); ossimString bandNamesString = m_keywords[WAVELENGTH_KW]; bandNamesString.split(waveLengths, ","); } void ossimEnviHeader::setWavelengths( const std::vector& wavelengths) { ossimString value; value.join(wavelengths, ","); m_keywords[WAVELENGTH_KW] = value.c_str(); } bool ossimEnviHeader::loadState(const ossimKeywordlist& kwl, const char* prefix) { std::string lookup; std::string pfx = (prefix ? prefix: "" ); ossimString s; reset(); lookup = kwl.findKey(pfx, std::string(ossimKeywordNames::FILENAME_KW)); if (lookup.size()) { m_file.string() = lookup; } lookup = kwl.findKey(pfx, std::string(ossimKeywordNames::DESCRIPTION_KW)); if (lookup.size()) { setDescription(lookup); } lookup = kwl.findKey(pfx, std::string(ossimKeywordNames::NUMBER_SAMPLES_KW)); if (lookup.size()) { m_keywords["samples"] = lookup; } lookup = kwl.findKey(pfx, std::string(ossimKeywordNames::NUMBER_LINES_KW)); if (lookup.size()) { m_keywords["lines"] = lookup; } lookup = kwl.findKey(pfx, std::string(ossimKeywordNames::NUMBER_BANDS_KW)); if (lookup.size()) { m_keywords["bands"] = lookup; } lookup = kwl.findKey(pfx, std::string(HEADER_OFFSET_KW)); if (lookup.size()) { m_keywords["header offset"] = lookup; } lookup = kwl.findKey(pfx, std::string(FILE_TYPE_KW)); if (lookup.size()) { m_keywords["file_type"] = lookup; } lookup = kwl.findKey(pfx, DATA_TYPE_KW); if (lookup.size()) { m_keywords["data type"] = lookup; } lookup = kwl.findKey(pfx, std::string(ossimKeywordNames::INTERLEAVE_TYPE_KW)); if (lookup.size()) { m_keywords["interleave"] = lookup; } lookup = kwl.findKey(pfx, std::string(SENSOR_TYPE_KW)); if (lookup.size()) { m_keywords["sensor type"] = lookup; } lookup = kwl.findKey(pfx, std::string(ossimKeywordNames::BYTE_ORDER_KW)); if (lookup.size()) { s = lookup; s.downcase(); if (s == "little_endian") { m_keywords["byte order"] = "0"; } else if (s == "big_endian") { m_keywords["byte order"] = "1"; } else { m_keywords["byte order"] = lookup; } } lookup = kwl.findKey(pfx, std::string(X_START_KW)); if (lookup.size()) { m_keywords["x start"] = lookup; } lookup = kwl.findKey(pfx, std::string(Y_START_KW)); if (lookup.size()) { m_keywords["y start"] = lookup; } lookup = kwl.findKey(pfx, std::string(MAP_INFO_KW)); if (lookup.size()) { m_keywords["map info"] = lookup; } lookup = kwl.findKey(pfx, std::string(WAVELENGTH_UNITS_KW)); if (lookup.size()) { m_keywords["wavelength units"] = lookup; } ossim_uint32 n; ossim_uint32 count; const ossim_uint32 MAX_TRIES = 1024; // Avoid infinate loop. // Get the band names. n = kwl.numberOf(prefix, BAND_NAME_KW); if (n) { ossimString value = ""; count = 0; while ( (count < n) || (count > MAX_TRIES) ) { s = BAND_NAME_KW; s += ossimString::toString(count); lookup = kwl.findKey(pfx, s.string()); if (lookup.size()) { if(!value.empty()) { value += ossimString(lookup); } else { value += (", " + ossimString(lookup)); } } ++count; } m_keywords["band names"] = value.c_str(); } // Get the band names. n = kwl.numberOf(prefix, WAVELENGTH_KW); if (n) { ossimString value; count = 0; while ( (count < n) || (count > MAX_TRIES) ) { s = WAVELENGTH_KW; s += ossimString::toString(count); lookup = kwl.findKey(pfx, s.string()); if (lookup.size()) { if(!value.empty()) { value += ossimString(lookup); } else { value += (", " + ossimString(lookup)); } } ++count; } m_keywords["wavelength"] = value.c_str(); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimEnviHeader::loadState DEUG\n"; print(ossimNotify(ossimNotifyLevel_DEBUG)); } return true; } bool ossimEnviHeader::isEnviHeader( const ossimFilename& file ) { bool result = false; std::ifstream in; in.open(file.c_str(), std::ios::in | std::ios::binary); if ( in.is_open() ) { result = isEnviHeader( in ); in.close(); } return result; } bool ossimEnviHeader::isEnviHeader( std::istream& in ) { bool result = false; ossim::skipws(in); char eh[5]; in.read(eh, 4); eh[4] = '\0'; std::string s(eh); if ( s == "ENVI" ) { result = true; } return result; } const ossimFilename& ossimEnviHeader::getFile() const { return m_file; } bool ossimEnviHeader::rangeCheckBands( const std::vector& bands ) const { bool result = false; const ossim_uint32 INPUT_BANDS = getBands(); if ( INPUT_BANDS ) { result = true; std::vector::const_iterator i = bands.begin(); while ( i != bands.end() ) { if ( (*i) >= INPUT_BANDS ) { result = false; break; } ++i; } } return result; } ossim-Miami-2.9.1/src/support_data/ossimEnviInfo.cpp000066400000000000000000000031221352751253100225010ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: ENVI Info object. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include ossimEnviInfo::ossimEnviInfo() : ossimInfoBase(), m_file() { } ossimEnviInfo::~ossimEnviInfo() { } bool ossimEnviInfo::open( const ossimFilename& file ) { bool result = false; m_file = file; if ( file.ext().downcase() != "hdr" ) { // Typical case, we were fed the image file. Look for a header file beside image. m_file.setExtension("hdr"); // image.hdr if ( !m_file.exists() ) { m_file.setExtension("HDR"); // image.HDR if ( !m_file.exists() ) { m_file = file; m_file.string() += ".hdr"; // image.ras.hdr } } } if ( m_file.exists() ) { if ( ossimEnviHeader::isEnviHeader( m_file ) ) { result = true; } } if ( !result ) { m_file.clear(); } return result; } std::ostream& ossimEnviInfo::print( std::ostream& out ) const { if ( m_file.size() ) { ossimEnviHeader hdr; if ( hdr.open( m_file ) ) { hdr.getMap().addPrefixToAll( ossimString( "envi." ) ); out << hdr.getMap() << std::endl; } } return out; } ossim-Miami-2.9.1/src/support_data/ossimFfL5.cpp000066400000000000000000000130551352751253100215260ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero (kmelero@imagelinks.com) // Orginally written by Oscar Kramer (SoBe Software) // Description: Container class for LandSat7 Fast Format header files. // // ******************************************************************** // $Id: ossimFfL5.cpp 17501 2010-06-02 11:14:55Z dburken $ // #include #include #include #include #include #include #include using namespace std; #include #include #include #include ossimFfL5::ossimFfL5() : ossimFfL7() { } ossimFfL5::ossimFfL5(const char* headerFile) : ossimFfL7() { // open the header file: readHeaderRevB(headerFile); } ossimFfL5::~ossimFfL5() { } void ossimFfL5::readHeaderRevB(const ossimString& header_name) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; // assume error, prove not at end; theRevb = new ossimFfRevb(header_name); if (theRevb->errorStatus() != ossimFfRevb::OSSIM_OK) return; strcpy(theRequestNumber, theRevb->theProductOrderNumber); strcpy(theLocationCode, theRevb->thePathRowNumber); strcpy(theAcquisitionDate, theRevb->theAcquisitionDate); strcpy(theSatName, theRevb->theSatNumber); strcpy(theSensorName, theRevb->theInstrumentType); strcpy(theSensorMode, ""); theOffNadirAngle = theRevb->theOrientationAngle; strcpy(theProductType, theRevb->theProductType); strcpy(theProductSize, theRevb->theProductSize); strcpy(theProcessingType, theRevb->theProcessingType); strcpy(theResampAlgorithm, theRevb->theResampAlgorithm); thePixelsPerLine = theRevb->thePixelsPerLine; theLinesPerBand = theRevb->theLinesPerImage; theRecordSize = theRevb->theRecordSize; theGsd = theRevb->theGsd; theOutputBitsPerPixel = 8; theAcquiredBitsPerPixel = 8; strcpy(theBandsPresentString, theRevb->theBandsPresentString); //generate band names int i=0; while((theBandsPresentString[i]>='0') && (theBandsPresentString[i]<='9')) { sprintf(theBandFileNames[i],"band%c.dat",theBandsPresentString[i]); ++i; } int nbb=i; std::vector arrayPathRow = ossimString(theLocationCode).split("/"); if(arrayPathRow.size() == 2) { thePathNumber = arrayPathRow[0].toInt(); theRowNumber = arrayPathRow[1].beforePos(3).toInt(); } //extract gains/biases from max/min radiance double min,max; theBias.clear(); theGain.clear(); for(i=0;itheBandRadiance[i]," %lf/%lf",&max,&min) != 2) return; theBias.push_back(min); theGain.push_back(max/254.0-min/255.0); } strcpy(theMapProjectionName ,theRevb->theMapProjName); strcpy(theEllipsoid ,theRevb->theEllipsoid); strcpy(theDatum, "WGS-84"); // added to read in all 15 parameters instead of the first two. for(long parameter=0;parameter < 15; ++parameter) { ossimString temp(theRevb->theUsgsProjParam[parameter]); theProjectionParams[parameter] = temp.gsub('D','E').toDouble(); } theUsgsMapZone = theRevb->theUsgsMapZone; char temps[256]; sprintf(temps,"%s %s",theRevb->theUlLon, theRevb->theUlLat); if (convertGeoPoint(temps, theUL_Corner) != ossimErrorCodes::OSSIM_OK) return; sprintf(temps,"%s %s",theRevb->theUrLon, theRevb->theUrLat); if (convertGeoPoint(temps, theUR_Corner) != ossimErrorCodes::OSSIM_OK) return; sprintf(temps,"%s %s",theRevb->theLrLon, theRevb->theLrLat); if (convertGeoPoint(temps, theLR_Corner) != ossimErrorCodes::OSSIM_OK) return; sprintf(temps,"%s %s",theRevb->theLlLon, theRevb->theLlLat); if (convertGeoPoint(temps, theLL_Corner) != ossimErrorCodes::OSSIM_OK) return; sprintf(temps,"%s %s",theRevb->theCenterLon, theRevb->theCenterLat); if (convertGeoPoint(temps, theCenterGP) != ossimErrorCodes::OSSIM_OK) return; theCenterImagePoint.x = theRevb->theCenterSample; theCenterImagePoint.y = theRevb->theCenterLine; theHorizontalOffset = theRevb->theOffset; theOrientationAngle = theRevb->theOrientationAngle; theSunElevation = theRevb->theSunElevation; theSunAzimuth = theRevb->theSunAzimuth; // The header was successfully extracted: theErrorStatus = ossimErrorCodes::OSSIM_OK; return; } int ossimFfL5::convertGeoPoint(const char* sptr, ossimGpt& geo_point) { int londeg; int lonmin; double lonsec; char lonhem; int latdeg; int latmin; double latsec; char lathem; int converted = sscanf(sptr, "%03d%02d%7lf%c %02d%02d%7lf%c", &londeg, &lonmin, &lonsec, &lonhem, &latdeg, &latmin, &latsec, &lathem); if (converted != 8) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return ossimErrorCodes::OSSIM_ERROR; } geo_point.lat = (double)latdeg + (double)latmin/60.0 + latsec/3600.0; if (lathem == 'S') geo_point.lat *= -1.0; geo_point.lon= (double)londeg + (double)lonmin/60.0 + lonsec/3600.0; if (lonhem == 'W') geo_point.lon *= -1.0; return ossimErrorCodes::OSSIM_OK; } ossimRefPtr ossimFfL5::revb() { return theRevb; } const ossimRefPtr ossimFfL5::revb()const { return theRevb; } ossim-Miami-2.9.1/src/support_data/ossimFfL7.cpp000066400000000000000000000472671352751253100215440ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Ken Melero // Orginally written by Oscar Kramer (SoBe Software) // // Description: Container class for LandSat7 Fast Format header files. // //******************************************************************** // $Id: ossimFfL7.cpp 23231 2015-04-08 00:00:33Z gpotts $ #include #include #include #include #include #include using namespace std; #include #include #include #include #include #include #include static const ossimString ACQUISITION_DATE_KW = "acquisition_date"; static const ossimString PATH_KW = "path"; static const ossimString PATH_ROW_KW = "path_row"; static const ossimString ROW_KW = "row"; static const ossimString SATELLITE_NAME_KW = "satellite_name"; static const ossimString SENSOR_NAME_KW = "sensor_name"; ossimFfL7::ossimFfL7() : ossimErrorStatusInterface() { initialize(); } ossimFfL7::ossimFfL7(const char* headerFile) : ossimErrorStatusInterface() { initialize(); // open the header file: FILE* fptr = fopen(headerFile, "r"); if (!fptr) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } // Begin reading records: if (!theErrorStatus) readAdminRecord(fptr); if (!theErrorStatus) readRadiomRecord(fptr); if (!theErrorStatus) readGeomRecord(fptr); if(fptr) { fclose(fptr); } } ossimFfL7::~ossimFfL7() {} ossimString ossimFfL7::pathRow() const { ossimString tmp = "p"; tmp += theLocationCode; tmp.gsub("/", "r"); tmp.gsub(" ", ""); return tmp; } void ossimFfL7::dump(std::ostream& os) const { os << setiosflags(ios::left | ios::fixed) << "\nAdministrative Record:" << setw(30) << "\ntheRequestNumber: " << theRequestNumber; os << setw(30) << "\nLocationCode: " << theLocationCode << setw(30) << "\nAcquisitionDate: " << theAcquisitionDate << setw(30) << "\nSatelliteName: " << theSatName << setw(30) << "\nSensorName: " << theSensorName << setw(30) << "\nSensorMode: " << theSensorMode << setw(30) << "\nOffNadirAngle: " << setprecision(2) << theOffNadirAngle; os << setw(30) << "\nProductType: " << theProductType << setw(30) << "\nProductSize: " << theProductSize << setw(30) << "\nProcessingType: " << theProcessingType << setw(30) << "\nResampAlgorithm: " << theResampAlgorithm << setw(30) << "\nPixelsPerLine: " << thePixelsPerLine << setw(30) << "\nLinesPerImage: " << theLinesPerBand << setw(30) << "\nRecordSize: " << theRecordSize << setw(30) << "\nGsd: " << setprecision(2) << theGsd << setw(30) << "\nOutputBitsPerPixel: " << theOutputBitsPerPixel << setw(30) << "\nAcquiredBitsPerPixel: " << theAcquiredBitsPerPixel << setw(30) << "\nBandsPresentString: " << theBandsPresentString; for (int i=0; i<6; i++) os << "\nBandFileNames["<::const_iterator bi = theBias.begin(); while (bi != theBias.end()) { os << "band[" << band << "] bias: " << (*bi) << endl; ++bi; ++band; } band = 0; bi = theGain.begin(); while (bi != theGain.end()) { os << "band[" << band << "] gain: " << (*bi) << endl; ++bi; ++band; } os << endl << "Geometric Record:" << setw(30) << "\nMapProjectionName:" << theMapProjectionName << setw(30) << "\nEllipsoid:" << theEllipsoid << setw(30) << "\nDatum:" << theDatum; for (int i = 0; i < 15; i++) { os << "\nProjectionParams[" << setw(2) << i << setw(10) << "]: " << theProjectionParams[i]; } os << setprecision(3) << setw(30) << "\nUL Corner:" << theUL_Corner << setw(30) << "\nUR Corner:" << theUR_Corner << setw(30) << "\nLR Corner:" << theLR_Corner << setw(30) << "\nLL Corner:" << theLL_Corner << setw(30) << "\nCenter Point (Ground):" << theCenterGP << setw(30) << "\nCenter Point (Image):" << theCenterImagePoint << setw(30) << "\nHorizontalOffset:" << theHorizontalOffset << setprecision(2) << setw(30) << "\nOrientationAngle:" << theOrientationAngle << setw(30) << "\nSunElevationAngle:" << setprecision(1) << theSunElevation << setw(30) << "\nSunAzimuth:" << theSunAzimuth << resetiosflags(ios::left) << endl << endl; } void ossimFfL7::writeHeader(std::ostream& os) const { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimFfL7::writeHeader: This method is not yet implemented. Ignoring request..." << std::endl; os << "WARNING ossimFfL7::writeHeader: This method is not yet implemented. Ignoring request..." << std::endl; } void ossimFfL7::readAdminRecord(FILE* fptr) { static const int OFFSET = -1; int converted; theErrorStatus = ossimErrorCodes::OSSIM_ERROR; // assume error, prove not at end; fseek(fptr, OFFSET + 9, SEEK_SET); converted = fscanf(fptr, "%20c", theRequestNumber); if (converted != 1) return; fseek(fptr, OFFSET + 35, SEEK_SET); converted = fscanf(fptr, "%17c", theLocationCode); if (converted != 1) return; fseek(fptr, OFFSET + 71, SEEK_SET); converted = fscanf(fptr, "%8c", theAcquisitionDate); if (converted != 1) return; fseek(fptr, OFFSET + 92, SEEK_SET); converted = fscanf(fptr, "%10c", theSatName); if (converted != 1) return; fseek(fptr, OFFSET + 111, SEEK_SET); converted = fscanf(fptr, "%10c", theSensorName); if (converted != 1) return; fseek(fptr, OFFSET + 135, SEEK_SET); converted = fscanf(fptr, "%6c", theSensorMode); if (converted != 1) return; fseek(fptr, OFFSET + 154, SEEK_SET); converted = fscanf(fptr, "%6lf", &theOffNadirAngle); if (converted != 1) return; fseek(fptr, OFFSET + 655, SEEK_SET); converted = fscanf(fptr, "%18c", theProductType); if (converted != 1) return; fseek(fptr, OFFSET + 688, SEEK_SET); converted = fscanf(fptr, "%10c", theProductSize); if (converted != 1) return; fseek(fptr, OFFSET + 741, SEEK_SET); converted = fscanf(fptr, "%11c", theProcessingType); if (converted != 1) return; fseek(fptr, OFFSET + 765, SEEK_SET); converted = fscanf(fptr, "%2c", theResampAlgorithm); if (converted != 1) return; fseek(fptr, OFFSET + 843, SEEK_SET); converted = fscanf(fptr, "%5d", &thePixelsPerLine); if (converted != 1) return; fseek(fptr, OFFSET + 865, SEEK_SET); converted = fscanf(fptr, "%5d", &theLinesPerBand); if (converted != 1) return; fseek(fptr, OFFSET + 932, SEEK_SET); converted = fscanf(fptr, "%9d", &theRecordSize); if (converted != 1) return; fseek(fptr, OFFSET + 954, SEEK_SET); converted = fscanf(fptr, "%6lf", &theGsd); if (converted != 1) return; fseek(fptr, OFFSET + 984, SEEK_SET); converted = fscanf(fptr, "%2d", &theOutputBitsPerPixel); if (converted != 1) return; fseek(fptr, OFFSET + 1012, SEEK_SET); converted = fscanf(fptr, "%2d", &theAcquiredBitsPerPixel); if (converted != 1) return; fseek(fptr, OFFSET + 1056, SEEK_SET); converted = fscanf(fptr, "%32c", theBandsPresentString); if (converted != 1) return; fseek(fptr, OFFSET + 1131, SEEK_SET); converted = fscanf(fptr, "%29c", theBandFileNames[0]); if (converted != 1) return; fseek(fptr, OFFSET + 1170, SEEK_SET); converted = fscanf(fptr, "%29c", theBandFileNames[1]); if (converted != 1) return; fseek(fptr, OFFSET + 1211, SEEK_SET); converted = fscanf(fptr, "%29c", theBandFileNames[2]); if (converted != 1) return; fseek(fptr, OFFSET + 1250, SEEK_SET); converted = fscanf(fptr, "%29c", theBandFileNames[3]); if (converted != 1) return; fseek(fptr, OFFSET + 1291, SEEK_SET); converted = fscanf(fptr, "%29c", theBandFileNames[4]); if (converted != 1) return; fseek(fptr, OFFSET + 1330, SEEK_SET); converted = fscanf(fptr, "%29c", theBandFileNames[5]); if (converted != 1) return; std::vector arrayPathRow = ossimString(theLocationCode).split("/"); if(arrayPathRow.size() == 2) { thePathNumber = arrayPathRow[0].toInt(); theRowNumber = arrayPathRow[1].beforePos(3).toInt(); } // The Admin record was successfully extracted: theErrorStatus = ossimErrorCodes::OSSIM_OK; return; } int ossimFfL7::path() const { return thePathNumber; } int ossimFfL7::row() const { return theRowNumber; } //*************************************************************************** // PRIVATE METHOD: ossimFfL7::readRadiomRecord() // //*************************************************************************** void ossimFfL7::readRadiomRecord(FILE* fptr) { int converted; char radiom_record[1537]; if (!theErrorStatus) { fseek(fptr, 1536, SEEK_SET); converted = fscanf(fptr, "%1536c", radiom_record); if (converted != 1) theErrorStatus = ossimErrorCodes::OSSIM_ERROR; } // Get the gains and biases. theBias.clear(); theGain.clear(); const ossim_uint32 MAX = 128; char temp_chars[MAX]; std::istringstream is(radiom_record); // Eat the first line. "GAINS AND BIASES IN ASCENDING BAND NUMBER ORDER" is.getline(temp_chars, MAX); const char SPACE = 0x20; const char LINE_FEED = 0x0a; // LS7 header has room for eight bands per spec. for (ossim_uint32 band = 0; band < 8; ++band) { is.getline(temp_chars, MAX); bool blank_line = true; for (ossim_uint32 i = 0; i < MAX; ++i) { if (temp_chars[i] == LINE_FEED) break; // end of line... if (temp_chars[i] != SPACE) { blank_line = false; // has bias and gain... break; } } if (blank_line == true) continue; // go to next line... std::vector splitString; ossimString tempString(temp_chars); tempString.split(splitString, " "); if(splitString.size() > 1) { theBias.push_back(splitString[0].toDouble()); theGain.push_back(splitString[1].toDouble()); } } } //*************************************************************************** // PRIVATE METHOD: ossimFfL7::readGeomRecord() // //*************************************************************************** void ossimFfL7::readGeomRecord(FILE* fptr) { static const int OFFSET = 3071; int converted; theErrorStatus = ossimErrorCodes::OSSIM_ERROR; // assume error, prove not at end; fseek(fptr, OFFSET + 32, SEEK_SET); converted = fscanf(fptr, "%4c", theMapProjectionName); if (converted != 1) return; fseek(fptr, OFFSET + 48, SEEK_SET); converted = fscanf(fptr, "%18c", theEllipsoid); if (converted != 1) return; strcpy(theDatum, "WGS-84"); // added to read in all 15 parameters instead of the first two. long currentOffset = OFFSET + 110; for(long parameter=0;parameter < 15; ++parameter) { fseek(fptr, currentOffset, SEEK_SET); converted = fscanf(fptr, "%24lf", &theProjectionParams[parameter]); if (converted != 1) return; currentOffset +=25; } fseek(fptr, OFFSET + 521, SEEK_SET); converted = fscanf(fptr, "%6d", &theUsgsMapZone); if (converted != 1) return; fseek(fptr, OFFSET + 566, SEEK_SET); if(convertGeoPoint(fptr, theUL_Corner)) return; fseek(fptr, OFFSET + 646, SEEK_SET); if(convertGeoPoint(fptr, theUR_Corner)) return; fseek(fptr, OFFSET + 726, SEEK_SET); if(convertGeoPoint(fptr, theLR_Corner)) return; fseek(fptr, OFFSET + 806, SEEK_SET); if(convertGeoPoint(fptr, theLL_Corner)) return; fseek(fptr, OFFSET + 890, SEEK_SET); if(convertGeoPoint(fptr, theCenterGP)) return; fseek(fptr, OFFSET + 945, SEEK_SET); int x; int y; converted = fscanf(fptr, "%5d %5d", &x, &y); if (converted != 2) return; theCenterImagePoint.x = x; theCenterImagePoint.y = y; fseek(fptr, OFFSET + 969, SEEK_SET); converted = fscanf(fptr, "%6d", &theHorizontalOffset); if (converted != 1) return; fseek(fptr, OFFSET + 995, SEEK_SET); converted = fscanf(fptr, "%6lf", &theOrientationAngle); if (converted != 1) return; fseek(fptr, OFFSET + 1062, SEEK_SET); converted = fscanf(fptr, "%4lf", &theSunElevation); if (converted != 1) return; fseek(fptr, OFFSET + 1086, SEEK_SET); converted = fscanf(fptr, "%5lf", &theSunAzimuth); if (converted != 1) return; // successfully reached the end of Geom record: theErrorStatus = ossimErrorCodes::OSSIM_OK; return; } //*************************************************************************** // PRIVATE METHOD: ossimFfL7::convertGeoPoint(char* buffer); // //*************************************************************************** int ossimFfL7::convertGeoPoint(FILE* fptr, ossimGpt& geo_point) { int londeg; int lonmin; double lonsec; char lonhem; int latdeg; int latmin; double latsec; char lathem; int converted = fscanf(fptr, "%03d%02d%7lf%c %02d%02d%7lf%c", &londeg, &lonmin, &lonsec, &lonhem, &latdeg, &latmin, &latsec, &lathem); if (converted != 8) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; return ossimErrorCodes::OSSIM_ERROR; } geo_point.lat = (double)latdeg + (double)latmin/60.0 + latsec/3600.0; if (lathem == 'S') geo_point.lat *= -1.0; geo_point.lon= (double)londeg + (double)lonmin/60.0 + lonsec/3600.0; if (lonhem == 'W') geo_point.lon *= -1.0; return ossimErrorCodes::OSSIM_OK; } //*************************************************************************** // PRIVATE METHOD: ossimFfL7::initialize() // Initializes all fields to blanks (or 0's) and null terminates strings. //*************************************************************************** void ossimFfL7::initialize() { static const char source[] = ""; // The Admin Record: strncpy(theRequestNumber, source, 21); strncpy(theLocationCode, source, 18); thePathNumber = 0; theRowNumber = 0; strncpy(theAcquisitionDate, source, 20); strncpy(theSatName, source, 11); strncpy(theSensorName, source, 11); strncpy(theSensorMode, source, 7); theOffNadirAngle = 0.0; strncpy(theProductType, source, 19); strncpy(theProductSize, source, 11); strncpy(theProcessingType, source, 12); strncpy(theResampAlgorithm, source, 3); thePixelsPerLine = 0; theLinesPerBand = 0; theRecordSize = 0; theGsd = 0.0; theOutputBitsPerPixel = 0; theAcquiredBitsPerPixel = 0; strncpy(theBandsPresentString, source, 33); strncpy(theBandFileNames[0], source, 30); strncpy(theBandFileNames[1], source, 30); strncpy(theBandFileNames[2], source, 30); strncpy(theBandFileNames[3], source, 30); strncpy(theBandFileNames[4], source, 30); strncpy(theBandFileNames[5], source, 30); // The Radiometry Record: theBias.clear(); theGain.clear(); // The Geometry Record: strncpy(theMapProjectionName, source, 5); strncpy(theEllipsoid, source, 19); strncpy(theDatum, source, 7); for (int i=0; i<15; i++) theProjectionParams[i] = 0.0; theUsgsMapZone = 0; theHorizontalOffset = 0; theOrientationAngle = 0.0; theSunElevation = 0.0; theSunAzimuth = 0.0; return; } void ossimFfL7::getBias(vector& bias) const { bias = theBias; } double ossimFfL7::getBias(long bandIdx)const { return theBias[bandIdx]; } void ossimFfL7::getGain(vector& gain) const { gain = theGain; } double ossimFfL7::getGain(long bandIdx)const { return theGain[bandIdx]; } double ossimFfL7::getParam(ossim_uint32 i)const { if(i < 15) { return theProjectionParams[i]; } return 0.0; } long ossimFfL7::getJulianDay()const { ossimDate date; getAcquisitionDate(date); return static_cast(date.getJulian()); } ossimString ossimFfL7::getAcquisitionDate() const { return ossimString(theAcquisitionDate); } void ossimFfL7::getAcquisitionDate(ossimDate& date)const { ossimString y = ossimString(theAcquisitionDate, theAcquisitionDate+4); ossimString m = ossimString(theAcquisitionDate+4, theAcquisitionDate+6); ossimString d = ossimString(theAcquisitionDate+6, theAcquisitionDate+8); date = ossimDate(m.toInt(), d.toInt(), y.toInt()); } ossimString ossimFfL7::getSatelliteName() const { return ossimString(theSatName); } ossimFilename ossimFfL7::getBandFilename(ossim_uint32 idx)const { ossimFilename result; if (idx < getBandCount()) { result = theBandFileNames[idx]; } return result; } int ossimFfL7::getLinesPerBand() const { return theLinesPerBand; } int ossimFfL7::getPixelsPerLine() const { return thePixelsPerLine; } void ossimFfL7::getSunElevation(double& elevation) const { elevation = theSunElevation; } void ossimFfL7::getSunAzimuth(double& azimuth) const { azimuth = theSunAzimuth; } ossimRefPtr ossimFfL7::getProperty(const ossimString& name)const { ossimRefPtr result = 0; if(name == ACQUISITION_DATE_KW) { ossimDate date; getAcquisitionDate(date); result = new ossimDateProperty(ACQUISITION_DATE_KW, date); } else if (name == PATH_KW) { result = new ossimStringProperty(PATH_KW, ossimString::toString(path()), false); } else if (name == PATH_ROW_KW) { result = new ossimStringProperty(PATH_ROW_KW, pathRow(), false); } else if (name == ROW_KW) { result = new ossimStringProperty(ROW_KW, ossimString::toString(row()), false); } else if (name == SATELLITE_NAME_KW) { result = new ossimStringProperty(SATELLITE_NAME_KW, ossimString(theSatName), false); } else if (name == SENSOR_NAME_KW) { result = new ossimStringProperty(SENSOR_NAME_KW, ossimString(theSensorName), false); } return result; } void ossimFfL7::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back(ACQUISITION_DATE_KW); propertyNames.push_back(PATH_KW); propertyNames.push_back(PATH_ROW_KW); propertyNames.push_back(ROW_KW); propertyNames.push_back(SATELLITE_NAME_KW); propertyNames.push_back(SENSOR_NAME_KW); } unsigned int ossimFfL7::getBandCount()const { ossimString tmp(theBandsPresentString); tmp.trim(); //remove spaces return (unsigned int)tmp.length(); // return strlen(tmp.chars()); //beurk! should implement length in ossimString } //*************************************************************************** // Function: // ostream& operator<<(ostream& os, const ossimFfL7& head) //*************************************************************************** std::ostream& operator<<(std::ostream& os, const ossimFfL7& head) { head.dump(os); return os; } ossim-Miami-2.9.1/src/support_data/ossimFfRevb.cpp000066400000000000000000000777501352751253100221600ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Ken Melero (kmelero@imagelinks.com) // Orginally written by Dave Burken (dburken@imagelinks.com) // Description: This class parses an EOSAT Fast Format rev b header. // //******************************************************************** // $Id$ #include #include #include #include #include #include #include // File scope constants for seek positions. const int RADIANCE_OFFSET [7] = { 300, 317, 334, 351, 368, 385, 402 }; static const int PROJ_PARAM_OFFSET [15] = { 594, 618, 642, 666, 690, 714, 738, 762, 786, 810, 834, 858, 882, 906, 930 }; //*************************************************************************** // CONSTRUCTOR //*************************************************************************** ossimFfRevb::ossimFfRevb() : the1stLineInVolume(1), theLinesPerVolume(0), theOrientationAngle(0.0), theUsgsProjNumber(0), theUsgsMapZone(0), theSemiMajorAxis(0.0), theSemiMinorAxis(0.0), theGsd(0.0), thePixelsPerLine(0), theLinesPerImage(0), theUlEasting(0.0), theUlNorthing(0.0), theUrEasting(0.0), theUrNorthing(0.0), theLrEasting(0.0), theLrNorthing(0.0), theLlEasting(0.0), theLlNorthing(0.0), theBlockingFactor(0), theRecordSize(0), theSunElevation(0), theSunAzimuth(0), theCenterEasting(0.0), theCenterNorthing(0.0), theCenterSample(0), theCenterLine(0), theOffset(0), theErrorStatus(OSSIM_OK) { const char tmpBuff[] = ""; strcpy(theProductOrderNumber, tmpBuff); strcpy(thePathRowNumber, tmpBuff); strcpy(theAcquisitionDate, tmpBuff); strcpy(theSatNumber, tmpBuff); strcpy(theInstrumentType, tmpBuff); strcpy(theProductType, "MAP ORIENTED"); strcpy(theProductSize, tmpBuff); strcpy(theMapSheetName, tmpBuff); strcpy(theProcessingType, "TERRAIN"); strcpy(theResampAlgorithm, "NN"); int i; for (i=0; i is = ossim::StreamFactoryRegistry::instance()-> createIstream(ossimString(headerFile), std::ios_base::in); if (!is) { theErrorStatus = OSSIM_ERROR; ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimFfRevb::ossimFfRevb(header):" << "Cannot open header = " << headerFile << "\n" << "Returning from constructor." << std::endl; return; } loadFromStream( *is ); } //*************************************************************************** // PUBLIC METHOD: // int ossimFfRevb::path(int sceneNbr) const // // Convenience method to parse the path from the path/row string. Returns // zero if stream is not opened. Current loacation field is: // path/row/fraction/subscene in ppp/rrrff format. //*************************************************************************** int ossimFfRevb::path() const { char tmpBuff[4]; int path = 0; std::istringstream is(thePathRowNumber); if (is) { is.get(tmpBuff, 4); tmpBuff[3] = '\0'; path = atoi(tmpBuff); } return path; } //*************************************************************************** // PUBLIC METHOD: // int ossimFfRevb::row(int sceneNbr) const // // Convenience method to parse the row from the path/row string. Returns // zero if stream is not opened. Current loacation field is: // path/row/fraction/subscene in ppp/rrrff format. //*************************************************************************** int ossimFfRevb::row() const { char tmpBuff[4]; int row = 0; std::istringstream is(thePathRowNumber); if (is) { is.seekg(4, std::ios_base::beg); is.get(tmpBuff, 4); tmpBuff[3] = '\0'; row = atoi(tmpBuff); } return row; } //*************************************************************************** // PUBLIC METHOD: // int ossimFfRevb::fraction(int sceneNbr) const // // Convenience method to parse the fraction from the path/row string. Returns // zero if stream is not opened. Current loacation field is: // path/row/fraction/subscene in ppp/rrrff format. //*************************************************************************** int ossimFfRevb::fraction() const { char tmpBuff[3]; int fraction = 0; std::istringstream is(thePathRowNumber); if (is) { is.seekg(7, std::ios_base::beg); is.get(tmpBuff, 3); tmpBuff[2] = '\0'; fraction = atoi(tmpBuff); } return fraction; } //*************************************************************************** // PUBLIC METHOD: // double ossimFfRevb::projParam(int paramNumber) const // // Returns the projection parameter as a double from the string taken from // the header. There are fifteen parameters so the possible range for // paramNumber is 0 to 14. //*************************************************************************** double ossimFfRevb::projParam(int paramNumber) const { if (paramNumber >= NUMBER_OF_PROJECTION_PARAMETERS) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimFfRevb::projParam: " << "Parameter out of range: " << paramNumber << "\nValid range: 0 - 14" << std::endl; return 0.0; } //*** // The USGS Projection Parameters in a rev b header have a "D" to // denote the exponent. This simply substitutes the "D" with an // "E" so that atof works properly. //*** ossimString tmp = theUsgsProjParam[paramNumber]; tmp.gsub("D", "E"); return atof(tmp.chars()); } //*************************************************************************** // PUBLIC METHOD: // void ossimFfRevb::print(ostream& os) const // // Prints data members. //*************************************************************************** void ossimFfRevb::print(std::ostream& os) const { os << std::setiosflags(std::ios_base::left | std::ios_base::fixed) << std::setw(30) << "\nimage_id:" << theProductOrderNumber << std::setw(30) << "\npath_row_number:" << thePathRowNumber << std::setw(30) << "\nacquisition_date:" << theAcquisitionDate << std::setw(30) << "\nsatellite_name:" << theSatNumber << std::setw(30) << "\nsensor_name:" << theInstrumentType << std::setw(30) << "\nproduct_type:" << theProductType << std::setw(30) << "\nproduct_size:" << theProductSize << std::setw(30) << "\nprocessing_type:" << theProcessingType << std::setw(30) << "\nresamp_algorithm:" << theResampAlgorithm; int i; for (i=0; i #include #include #include #include #include #include const int LOCATION_OFFSET [4] = { 23, 183, 343, 503 }; const int PATH_ROW_NUMBER_OFFSET [4] = { 34, 194, 354, 514 }; const int DATE_OFFSET [4] = { 70, 230, 390, 550 }; const int SAT_NAME_OFFSET [4] = { 91, 251, 411, 571 }; const int SENSOR_NAME_OFFSET [4] = { 110, 270, 430, 590 }; const int SENSOR_MODE_OFFSET [4] = { 134, 294, 454, 614 }; const int OFF_NADIR_ANGLE_OFFSET [4] = { 153, 313, 473, 633 }; const int BIAS_OFFSET [8] = { 1616, 1696, 1776, 1856, 1936, 2016, 2096, 2176 }; const int GAIN_OFFSET [8] = { 1641, 1721, 1801, 1881, 1961, 2041, 2121, 2201 }; static const int PROJ_PARAM_OFFSET [15] = { 3181, 3206, 3232, 3257, 3282, 3312, 3337, 3362, 3392, 3417, 3442, 3472, 3497, 3522, 3552 }; static const char BLANK_STRING[] = " "; //*************************************************************************** // CONSTRUCTOR //*************************************************************************** ossimFfRevc::ossimFfRevc() : theAdminRecord(), theRadiomRecord(), theGeoRecord(), theErrorStatus(OSSIM_OK) { } //*************************************************************************** // CONSTRUCTOR: // ossimFfRevc::ossimFfRevc(const char* headerFile) // // Takes a filename representing an IRS-1C Fast Format rev C header. //*************************************************************************** ossimFfRevc::ossimFfRevc(const char* headerFile) : theErrorStatus(OSSIM_OK) { std::shared_ptr is = ossim::StreamFactoryRegistry::instance()-> createIstream(ossimString(headerFile), std::ios_base::in); if (!is) { theErrorStatus = OSSIM_ERROR; ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimFfRevc::ossimFfRevc(header): " << "Cannot open: " << headerFile << "\n" << "Returning from constructor." << std::endl; return; } loadFromStream( *is ); } //*************************************************************************** // PUBLIC METHOD: // int ossimFfRevc::path(int sceneNbr) const // // Convenience method to parse the path from the path/row string. Returns // zero if stream is not opened. Current loacation field is: // path/row/fraction/subscene in ppp/rrrffss format. //*************************************************************************** int ossimFfRevc::path(int sceneNbr) const { char tmpBuff[4]; int path = 0; std::istringstream is(theAdminRecord.thePathRowNumber[sceneNbr]); if (is) { is.get(tmpBuff, 4); path = atoi(tmpBuff); } return path; } //*************************************************************************** // PUBLIC METHOD: // int ossimFfRevc::row(int sceneNbr) const // // Convenience method to parse the row from the path/row string. Returns // zero if stream is not opened. Current loacation field is: // path/row/fraction/subscene in ppp/rrrffss format. //*************************************************************************** int ossimFfRevc::row(int sceneNbr) const { char tmpBuff[4]; int row = 0; std::istringstream is(theAdminRecord.thePathRowNumber[sceneNbr]); if (is) { is.seekg(4, std::ios_base::beg); is.get(tmpBuff, 4); row = atoi(tmpBuff); } return row; } //*************************************************************************** // PUBLIC METHOD: // int ossimFfRevc::fraction(int sceneNbr) const // // Convenience method to parse the fraction from the path/row string. Returns // zero if stream is not opened. Current loacation field is: // path/row/fraction/subscene in ppp/rrrffss format. //*************************************************************************** int ossimFfRevc::fraction(int sceneNbr) const { char tmpBuff[3]; int fraction = 0; std::istringstream is(theAdminRecord.thePathRowNumber[sceneNbr]); if (is) { is.seekg(7, std::ios_base::beg); is.get(tmpBuff, 3); fraction = atoi(tmpBuff); } return fraction; } //*************************************************************************** // PUBLIC METHOD: // int ossimFfRevc::subScene(int sceneNbr) const // // Convenience method to parse the subScene from the path/row string. Returns // zero if stream is not opened. Current loacation field is: // path/row/fraction/subscene in ppp/rrrffss format. //*************************************************************************** ossimString ossimFfRevc::subScene(int sceneNbr) const { char tmpBuff[3]; ossimString subScene; std::istringstream is(theAdminRecord.thePathRowNumber[sceneNbr]); if (is) { is.seekg(9, std::ios_base::beg); is.get(tmpBuff, 3); subScene = tmpBuff; } return subScene; } //*************************************************************************** // ossimFfRevc::pathRow(int sceneNbr) //*************************************************************************** ossimString ossimFfRevc::pathRow(int sceneNbr) const { ossimString tmp = "p"; tmp += theAdminRecord.thePathRowNumber[sceneNbr]; tmp.gsub("/", "r"); tmp.gsub(" ", ""); return tmp; } //*************************************************************************** // PUBLIC METHOD: // void ossimFfRevc::print(ostream& os) const // // Prints data members. //*************************************************************************** void ossimFfRevc::print(std::ostream& os) const { os << std::setiosflags(std::ios_base::left | std::ios_base::fixed) << "Administrative Record:" << std::setw(30) << "\ntheProductOrderNumber:" << theAdminRecord.theProductOrderNumber; int i; for (i = 0; i < NUMBER_OF_SCENES; i++) { os << "\nScene" << (i + 1) << std::setw(23) << " PathRowNumber:" << theAdminRecord.thePathRowNumber[i] << "\nScene" << (i + 1) << std::setw(23) << " AcquisitionDate: " << theAdminRecord.theAcquisitionDate[i] << "\nScene" << (i + 1) << std::setw(23) << " SatelliteName: " << theAdminRecord.theSatName[i] << "\nScene" << (i + 1) << std::setw(23) << " SensorName: " << theAdminRecord.theSensorName[i] << "\nScene" << (i + 1) << std::setw(23) << " SensorMode: " << theAdminRecord.theSensorMode[i] << "\nScene" << (i + 1) << std::setw(23) << " OffNadirAngle: " << std::setprecision(2) << theAdminRecord.theOffNadirAngle[i]; } os << std::setw(30) << "\nProductType:" << theAdminRecord.theProductType << std::setw(30) << "\nProductSize:" << theAdminRecord.theProductSize << std::setw(30) << "\nProcessingType:" << theAdminRecord.theProcessingType << std::setw(30) << "\nResampAlgorithm:" << theAdminRecord.theResampAlgorithm << std::setw(30) << "\nTapeVolumeNumber:" << theAdminRecord.theTapeVolumeNumber << std::setw(30) << "\nNumberVolumesPerTape:" << theAdminRecord.theNumberVolumesPerTape << std::setw(30) << "\nPixelsPerLine:" << theAdminRecord.thePixelsPerLine << std::setw(30) << "\nLinesPerImage:" << theAdminRecord.theLinesPerImage << std::setw(30) << "\n1stLineInVolume:" << theAdminRecord.the1stLineInVolume << std::setw(30) << "\nTapeBlockingFactor:" << theAdminRecord.theTapeBlockingFactor << std::setw(30) << "\nRecordSize:" << theAdminRecord.theRecordSize << std::setw(30) << "\nGsd:" << std::setprecision(2) << theAdminRecord.theGsd << std::setw(30) << "\nOutputBitsPerPixel:" << theAdminRecord.theOutputBitsPerPixel << std::setw(30) << "\nAcquiredBitsPerPixel:" << theAdminRecord.theAcquiredBitsPerPixel << std::setw(30) << "\nBandsPresentString:" << theAdminRecord.theBandsPresentString << std::setw(30) << "\nFormatVersion:" << theAdminRecord.theFormatVersion << "\n" << std::setw(30) << "Radiometric record:"; os << std::setprecision(15); for (i = 0; i < NUMBER_OF_BANDS; i++) { os << "\nBand" << (i + 1) << std::setw(24) << " bias:" << theRadiomRecord.theBias[i] << "\nBand" << (i + 1) << std::setw(24) << " gain:" << theRadiomRecord.theGain[i]; } os << "\n" << "Geometric Record:" << std::setw(30) << "\nMapProjectionName:" << theGeoRecord.theMapProjectionName << std::setw(30) << "\nEllipsoid:" << theGeoRecord.theEllipsoid << std::setw(30) << "\nDatum:" << theGeoRecord.theDatum; for (i = 0; i < 15; i++) { os << "\nProjectionParams[" << std::setw(2) << i << std::setw(10) << "]: " << theGeoRecord.theProjectionParams[i]; } os << std::setprecision(3) << std::setw(30) << "\nUlLon:" << theGeoRecord.theUlLon << std::setw(30) << "\nUlLat:" << theGeoRecord.theUlLat << std::setw(30) << "\nUlEasting:" << theGeoRecord.theUlEasting << std::setw(30) << "\nUlNorthing:" << theGeoRecord.theUlNorthing << std::setw(30) << "\nUrLon:" << theGeoRecord.theUrLon << std::setw(30) << "\nUrLat:" << theGeoRecord.theUrLat << std::setw(30) << "\nUrEasting:" << theGeoRecord.theUrEasting << std::setw(30) << "\nUrNorthing:" << theGeoRecord.theUrNorthing << std::setw(30) << "\nLrLon:" << theGeoRecord.theLrLon << std::setw(30) << "\nLrLat:" << theGeoRecord.theLrLat << std::setw(30) << "\nLrEasting:" << theGeoRecord.theLrEasting << std::setw(30) << "\nLrNorthing:" << theGeoRecord.theLrNorthing << std::setw(30) << "\nLlLon:" << theGeoRecord.theLlLon << std::setw(30) << "\nLlLat:" << theGeoRecord.theLlLat << std::setw(30) << "\nLlEasting:" << theGeoRecord.theLlEasting << std::setw(30) << "\nLlNorthing:" << theGeoRecord.theLlNorthing << std::setw(30) << "\nCenterLon:" << theGeoRecord.theCenterLon << std::setw(30) << "\nCenterLat:" << theGeoRecord.theCenterLat << std::setw(30) << "\nCenterEasting:" << theGeoRecord.theCenterEasting << std::setw(30) << "\nCenterNorthing:" << theGeoRecord.theCenterNorthing << std::setw(30) << "\nCenterSample:" << theGeoRecord.theCenterSample << std::setw(30) << "\nCenterLine:" << theGeoRecord.theCenterLine << std::setw(30) << "\nHorizontalOffset:" << theGeoRecord.theHorizontalOffset << std::setprecision(2) << std::setw(30) << "\nOrientationAngle:" << theGeoRecord.theOrientationAngle << std::setw(30) << "\nSunElevationAngle:" << std::setprecision(1) << theGeoRecord.theSunElevationAngle << std::setw(30) << "\nSunAzimuth:" << theGeoRecord.theSunAzimuth << std::resetiosflags(std::ios_base::left) << "\n\n"; } //*************************************************************************** // PUBLIC METHOD: // void ossimFfRevc::write(ostream& os) const // // Writes data members in EOSAT Fast Format Rev C format. //*************************************************************************** void ossimFfRevc::write(ossim::ostream& os) const { const char PRODUCT_ID_DESC [PRODUCT_ORDER_NUMBER_DESC_SIZE + 1] = "PRODUCT ID ="; const char LOCATION_DESC [LOCATION_DESC_SIZE + 1] = " LOCATION ="; const char DATE_DESC [DATE_DESC_SIZE + 1] = " ACQUISITION DATE ="; const char SATELLITE_NAME_DESC [SAT_NAME_DESC_SIZE + 1] = "SATELLITE ="; const char SENSOR_NAME_DESC [SENSOR_NAME_DESC_SIZE + 1] = " SENSOR ="; const char SENSOR_MODE_DESC [SENSOR_MODE_DESC_SIZE + 1] = " SENSOR MODE ="; const char LOOK_ANGLE_DESC [LOOK_ANGLE_DESC_SIZE + 1] = " LOOK ANGLE ="; const char PRODUCT_TYPE_DESC [PRODUCT_TYPE_DESC_SIZE + 1] = "PRODUCT TYPE ="; const char PRODUCT_SIZE_DESC [PRODUCT_SIZE_DESC_SIZE + 1] = " PRODUCT SIZE ="; const char PROCESSING_TYPE_DESC [PROCESSING_TYPE_DESC_SIZE + 1] = "TYPE OF PROCESSING ="; const char RESAMPLING_ALGO_DESC [RESAMPLING_ALGO_DESC_SIZE + 1] = " RESAMPLING ="; const char TAPE_VOLUME_NUMBER_DESC [TAPE_VOLUME_NUMBER_DESC_SIZE + 1] = "VOLUME #/# IN SET ="; const char PIXELS_PER_LINE_DESC [PIXELS_PER_LINE_DESC_SIZE + 1] = " PIXELS PER LINE ="; const char LINES_PER_IMAGE_DESC [LINES_PER_IMAGE_DESC_SIZE + 1] = " LINES PER BAND ="; const char FIRST_LINE_DESC [FIRST_LINE_DESC_SIZE + 1] = "START LINE # ="; const char BLOCKING_FACTOR_DESC [BLOCKING_FACTOR_DESC_SIZE + 1] = " BLOCKING FACTOR ="; const char RECORD_LENGTH_DESC [RECORD_LENGTH_DESC_SIZE + 1] = " RECORD LENGTH ="; const char PIXEL_GSD_DESC [PIXEL_GSD_DESC_SIZE + 1] = " PIXEL SIZE ="; const char BITS_PER_PIXEL_DESC [BITS_PER_PIXEL_DESC_SIZE + 1] = "OUTPUT BITS PER PIXEL ="; const char AQUIRED_BITS_PER_PIXEL_DESC [AQUIRED_BITS_PER_PIXEL_DESC_SIZE + 1] = " ACQUIRED BITS PER PIXEL ="; const char BANDS_PRESENT_DESC [BANDS_PRESENT_DESC_SIZE + 1] = "BANDS PRESENT ="; const char REV_DESC [REV_DESC_SIZE + 1] = "REV "; const char BIAS_GAIN_DESC [BIAS_GAIN_DESC_SIZE + 1] = "BIASES AND GAINS IN THE BAND ORDER AS ON THIS TAPE"; const char GEO_DESC [GEO_DESC_SIZE + 1] = "GEOMETRIC DATA"; const char MAP_PROJECTION_NAME_DESC [MAP_PROJECTION_NAME_DESC_SIZE + 1] = " MAP PROJECTION ="; const char ELLIPSOID_DESC [ELLIPSOID_DESC_SIZE + 1] = " ELLIPSOID ="; const char DATUM_DESC [DATUM_DESC_SIZE + 1] = " DATUM ="; const char PROJECTION_PARAMETER_DESC [PROJECTION_PARAMETER_DESC_SIZE + 1] = "USGS PROJECTION PARAMETERS ="; const char UL_DESC [CORNER_DESC_SIZE + 1] = "UL ="; const char UR_DESC [CORNER_DESC_SIZE + 1] = "UR ="; const char LR_DESC [CORNER_DESC_SIZE + 1] = "LR ="; const char LL_DESC [CORNER_DESC_SIZE + 1] = "LL ="; const char CENTER_DESC [CENTER_DESC_SIZE + 1] = "CENTER ="; const char HORIZONTAL_OFFSET_DESC [HORIZONTAL_OFFSET_DESC_SIZE + 1] = "OFFSET ="; const char ORIENTATION_ANGLE_DESC [ORIENTATION_ANGLE_DESC_SIZE + 1] = " ORIENTATION ANGLE ="; const char SUN_ELEVATION_DESC [SUN_ELEVATION_DESC_SIZE + 1] = "SUN ELEVATION ANGLE ="; const char SUN_AZIMUTH_DESC [SUN_AZIMUTH_DESC_SIZE + 1] = " SUN AZIMUTH ANGLE ="; const char SPACE[] = " "; //> // NOTE: "seekp's" will be perormed as needed for safety. //< //> // Start at beginning of the stream. //< os.seekp(0, std::ios_base::beg); //> // Start of administrative record. //< os << std::setiosflags(std::ios_base::fixed) // Disable scientific mode. << PRODUCT_ID_DESC << std::setw(PRODUCT_ORDER_NUMBER_SIZE) << theAdminRecord.theProductOrderNumber; //> // The admin record can contain info for up to four scenes. //< int i; for (i = 0; i < 4; i++) { os.seekp(LOCATION_OFFSET[i], std::ios_base::beg); os << LOCATION_DESC << std::setw(PATH_ROW_NUMBER_SIZE) << theAdminRecord.thePathRowNumber[i] << DATE_DESC << std::setw(DATE_SIZE) << theAdminRecord.theAcquisitionDate[i] << std::setw(1) << SPACE << "\n" // End of line. << SATELLITE_NAME_DESC // Start of line. << std::setw(SAT_NAME_SIZE) << theAdminRecord.theSatName[i] << SENSOR_NAME_DESC << std::setw(SENSOR_NAME_SIZE) << theAdminRecord.theSensorName[i] << SENSOR_MODE_DESC << std::setw(SENSOR_MODE_SIZE) << theAdminRecord.theSensorMode[i] << LOOK_ANGLE_DESC << std::setw(OFF_NADIR_ANGLE_SIZE) << std::setiosflags(std::ios_base::right) << std::setprecision(2) << theAdminRecord.theOffNadirAngle[i] // End of scene. << std::resetiosflags(std::ios_base::right) << "\n" << std::setw(23) << SPACE; // End of line. } // End of scene loop. os.seekp(640, std::ios_base::beg); // Start of line. os << PRODUCT_TYPE_DESC << std::setiosflags(std::ios_base::left) << std::setw(PRODUCT_TYPE_SIZE) << theAdminRecord.theProductType << PRODUCT_SIZE_DESC << std::setw(PRODUCT_SIZE_SIZE) << theAdminRecord.theProductSize << std::setw(22) << SPACE << "\n"; // End of line. os.seekp(720, std::ios_base::beg); os << PROCESSING_TYPE_DESC << std::setw(PROCESSING_TYPE_SIZE) << theAdminRecord.theProcessingType << RESAMPLING_ALGO_DESC << std::setw(RESAMPLING_ALGO_SIZE) << theAdminRecord.theResampAlgorithm << std::resetiosflags(std::ios_base::left) << std::setw(33) << SPACE << "\n"; // End of line. os.seekp(800, std::ios_base::beg); // Start of line. os << TAPE_VOLUME_NUMBER_DESC << std::setiosflags(std::ios_base::right) << std::setw(TAPE_VOLUME_NUMBER_SIZE) << theAdminRecord.theTapeVolumeNumber << "/" << std::setw(VOLUMES_PER_TAPE_SIZE) << theAdminRecord.theNumberVolumesPerTape << PIXELS_PER_LINE_DESC << std::setw(PIXELS_PER_LINE_SIZE) << theAdminRecord.thePixelsPerLine << LINES_PER_IMAGE_DESC << std::setw(LINES_PER_IMAGE_SIZE) << theAdminRecord.theLinesPerImage << "/" << std::setw(LINES_PER_IMAGE_SIZE) << theAdminRecord.theLinesPerImage << std::setw(4) << SPACE << "\n"; // End of line. os.seekp(880, std::ios_base::beg); // Start of line. os << std::setiosflags(std::ios_base::right) << FIRST_LINE_DESC << std::setw(LINES_PER_IMAGE_SIZE) << theAdminRecord.the1stLineInVolume << BLOCKING_FACTOR_DESC << std::setw(BLOCKING_FACTOR_SIZE) << theAdminRecord.theTapeBlockingFactor << RECORD_LENGTH_DESC << std::setw(RECORD_LENGTH_SIZE) << theAdminRecord.theRecordSize << PIXEL_GSD_DESC << std::setw(PIXEL_GSD_SIZE) << std::setprecision(2) << theAdminRecord.theGsd << "\n"; // End of line. os.seekp(960, std::ios_base::beg); // Start of line. os << BITS_PER_PIXEL_DESC << std::setw(BITS_PER_PIXEL_SIZE) << theAdminRecord.theOutputBitsPerPixel << AQUIRED_BITS_PER_PIXEL_DESC << std::setw(BITS_PER_PIXEL_SIZE) << theAdminRecord.theAcquiredBitsPerPixel << std::resetiosflags(std::ios_base::right) << std::setw(26) << SPACE << "\n"; // End of line. os.seekp(1040, std::ios_base::beg); // Start of line. os << BANDS_PRESENT_DESC << std::setw(BANDS_PRESENT_SIZE) << theAdminRecord.theBandsPresentString << std::setw(31) << SPACE << "\n" // End of line. << std::setw(79) << SPACE << "\n" << std::setw(79) << SPACE << "\n" << std::setw(79) << SPACE << "\n" << std::setw(79) << SPACE << "\n" << std::setw(79) << SPACE << "\n"; os.seekp(1520, std::ios_base::beg); os << REV_DESC << std::setw(FORMAT_VERSION_SIZE) << theAdminRecord.theFormatVersion; //*** // End of administrative record(bytes 0 to 1535). //*** //*** // Beginning of radiometric record. //*** os.seekp(1536, std::ios_base::beg); os << BIAS_GAIN_DESC << std::setw(29) << SPACE << "\n"; //*** // Loop through the bands and get write out the bias and gain for each // band. //*** os << std::resetiosflags(std::ios_base::left) << std::setiosflags(std::ios_base::right); for (i = 0; i < 8; i++) { os.seekp(BIAS_OFFSET[i], std::ios_base::beg); os << std::setprecision(15) << std::setw(BIAS_SIZE) << theRadiomRecord.theBias[i] << SPACE << std::setw(GAIN_SIZE) << theRadiomRecord.theGain[i] << std::setw(30) << SPACE << "\n"; } // End of loop through the bands. os << std::resetiosflags(std::ios_base::right); os.seekp(2256, std::ios_base::beg); os << std::setw(79) << SPACE << "\n"; os << std::setw(79) << SPACE << "\n"; os << std::setw(79) << SPACE << "\n"; os << std::setw(79) << SPACE << "\n"; os << std::setw(79) << SPACE << "\n"; os << std::setw(79) << SPACE << "\n"; os << std::setw(79) << SPACE << "\n"; os << std::setw(79) << SPACE << "\n"; os << std::setw(79) << SPACE << "\n"; os << std::setw(79) << SPACE << "\n"; os << std::setw(15) << SPACE << "\n"; //*** // End of radiometric record(bytes 1536 to 3071). //*** //** // Start of geometric record(bytes 3072 to 4607). //*** os.seekp(3072, std::ios_base::beg); // Start of record. os << GEO_DESC << MAP_PROJECTION_NAME_DESC << std::setiosflags(std::ios_base::left) // Alpha fields left justified. << std::setw(MAP_PROJECTION_NAME_SIZE) << theGeoRecord.theMapProjectionName << ELLIPSOID_DESC // Looks like this has changed. << std::setw(ELLIPSOID_SIZE) << theGeoRecord.theEllipsoid << DATUM_DESC << std::setw(DATUM_SIZE) << theGeoRecord.theDatum << std::resetiosflags(std::ios_base::left) << "\n" // End of line << PROJECTION_PARAMETER_DESC << SPACE; os.seekp(PROJ_PARAM_OFFSET[0], std::ios_base::beg); os << std::setprecision(15) << std::setiosflags(std::ios_base::right) << std::setw(PROJECTION_PARAMETER_SIZE) << theGeoRecord.theProjectionParams[0] << SPACE; os.seekp(PROJ_PARAM_OFFSET[1], std::ios_base::beg); os << std::setw(PROJECTION_PARAMETER_SIZE) << theGeoRecord.theProjectionParams[1] << std::setw(1) << SPACE << "\n"; //*** // Code is duplicated every three projection parameter four times; // hence, the double loop. //*** for (i = 0; i < 4; i++) { for (int j = i * 3 + 2; j < (i * 3) + 5; j++) { os.seekp(PROJ_PARAM_OFFSET[j], std::ios_base::beg); os << std::setw(PROJECTION_PARAMETER_SIZE) << theGeoRecord.theProjectionParams[j] << std::setw(1) << SPACE; os.seekp(PROJ_PARAM_OFFSET[j], std::ios_base::beg); os << std::setw(PROJECTION_PARAMETER_SIZE) << theGeoRecord.theProjectionParams[j] << std::setw(1) << SPACE; os.seekp(PROJ_PARAM_OFFSET[j], std::ios_base::beg); os << std::setw(PROJECTION_PARAMETER_SIZE) << theGeoRecord.theProjectionParams[j] << std::setw(5) << SPACE << "\n"; } } os.seekp(PROJ_PARAM_OFFSET[14], std::ios_base::beg); os << std::setw(PROJECTION_PARAMETER_SIZE) << theGeoRecord.theProjectionParams[14] << std::setw(55) << SPACE << "\n" << std::resetiosflags(std::ios_base::right); os.seekp(3632, std::ios_base::beg); os << UL_DESC << SPACE << std::setw(LON_SIZE) << theGeoRecord.theUlLon << SPACE << std::setw(LAT_SIZE) << theGeoRecord.theUlLat << SPACE << std::setprecision(3) << std::setw(EASTING_SIZE) << std::setiosflags(std::ios_base::right) << theGeoRecord.theUlEasting << SPACE << std::setw(NORTHING_SIZE) << theGeoRecord.theUlNorthing << std::setw(20) << SPACE << "\n" << std::resetiosflags(std::ios_base::right); os.seekp(3712, std::ios_base::beg); os << UR_DESC << SPACE << std::setw(LON_SIZE) << theGeoRecord.theUrLon << SPACE << std::setw(LAT_SIZE) << theGeoRecord.theUrLat << SPACE << std::setw(EASTING_SIZE) << std::setiosflags(std::ios_base::right) << theGeoRecord.theUrEasting << SPACE << std::setw(NORTHING_SIZE) << theGeoRecord.theUrNorthing << std::setw(20) << SPACE << "\n" << std::resetiosflags(std::ios_base::right); os.seekp(3792, std::ios_base::beg); os << LR_DESC << SPACE << std::setw(LON_SIZE) << theGeoRecord.theLrLon << SPACE << std::setw(LAT_SIZE) << theGeoRecord.theLrLat << SPACE << std::setw(EASTING_SIZE) << std::setiosflags(std::ios_base::right) << theGeoRecord.theLrEasting << SPACE << std::setw(NORTHING_SIZE) << theGeoRecord.theLrNorthing << std::setw(20) << SPACE << "\n" << std::resetiosflags(std::ios_base::right); os.seekp(3872, std::ios_base::beg); os << LL_DESC << SPACE << std::setw(LON_SIZE) << theGeoRecord.theLlLon << SPACE << std::setw(LAT_SIZE) << theGeoRecord.theLlLat << SPACE << std::setw(EASTING_SIZE) << std::setiosflags(std::ios_base::right) << theGeoRecord.theLlEasting << SPACE << std::setw(NORTHING_SIZE) << theGeoRecord.theLlNorthing << std::setw(20) << SPACE << "\n" << std::resetiosflags(std::ios_base::right); os.seekp(3952, std::ios_base::beg); os << CENTER_DESC << SPACE << std::setw(LON_SIZE) << theGeoRecord.theCenterLon << SPACE << std::setw(LAT_SIZE) << theGeoRecord.theCenterLat << SPACE << std::setw(EASTING_SIZE) << std::setiosflags(std::ios_base::right) << theGeoRecord.theCenterEasting << SPACE << std::setw(NORTHING_SIZE) << theGeoRecord.theCenterNorthing << SPACE << std::setw(CENTER_SAMPLE_SIZE) << theGeoRecord.theCenterSample << SPACE << std::setw(CENTER_LINE_SIZE) << theGeoRecord.theCenterLine << std::setw(4) << SPACE << "\n"; os.seekp(4032, std::ios_base::beg); os << HORIZONTAL_OFFSET_DESC << std::setw(HORIZONTAL_OFFSET_SIZE) << theGeoRecord.theHorizontalOffset << ORIENTATION_ANGLE_DESC << std::setw(ORIENTATION_ANGLE_SIZE) << std::setprecision(2) << theGeoRecord.theOrientationAngle << std::setw(39) << SPACE << "\n"; // 41 in spec os.seekp(4112, std::ios_base::beg); os << SUN_ELEVATION_DESC << std::setw(SUN_ELEVATION_SIZE) << std::setprecision(1) << theGeoRecord.theSunElevationAngle << SUN_AZIMUTH_DESC << std::setw(SUN_AZIMUTH_SIZE) << std::setprecision(1) << theGeoRecord.theSunAzimuth // End of data. << std::setw(29) << SPACE << "\n" << std::setw(79) << SPACE << "\n" << std::setw(79) << SPACE << "\n" << std::setw(79) << SPACE << "\n" << std::setw(79) << SPACE << "\n" << std::setw(79) << SPACE << "\n" << std::setw(15) << SPACE << "\n" << std::flush; // ? size //*** // End of geometric record(bytes 3072 to 4607). //*** } //*************************************************************************** // PRIVATE METHOD: // ossimFfRevc::loadFromStream(istream& is) //*************************************************************************** void ossimFfRevc::loadFromStream(ossim::istream& is) { //*** // See .h for enumerations for field sizes and offsets. //*** //*** // NOTE: Because of header inconsistencies all seeks will be relative to // the beginning of the stream. //*** //*** // Temporary buffer for fields that need to be converted to integers or // floats. //*** char tmpBuff[25]; //*** // Start of administrative record. //*** is.seekg(PRODUCT_ORDER_NUMBER_OFFSET, std::ios_base::beg); is.get(theAdminRecord.theProductOrderNumber, PRODUCT_ORDER_NUMBER_SIZE + 1, ' '); if (checkStream(is)) return; //*** // Loop through the four scenes and get the data. //*** int i; for (i = 0; i < NUMBER_OF_SCENES; i++) { is.seekg(PATH_ROW_NUMBER_OFFSET[i], std::ios_base::beg); is.get(theAdminRecord.thePathRowNumber[i], PATH_ROW_NUMBER_SIZE + 1); if (checkStream(is)) return; is.seekg(DATE_OFFSET[i], std::ios_base::beg); is.get(theAdminRecord.theAcquisitionDate[i], DATE_SIZE + 1); if (checkStream(is)) return; is.seekg(SAT_NAME_OFFSET[i], std::ios_base::beg); is.get(theAdminRecord.theSatName[i], SAT_NAME_SIZE + 1); if (checkStream(is)) return; is.seekg(SENSOR_NAME_OFFSET[i], std::ios_base::beg); is.get(theAdminRecord.theSensorName[i], SENSOR_NAME_SIZE + 1); if (checkStream(is)) return; is.seekg(SENSOR_MODE_OFFSET[i], std::ios_base::beg); is.get(theAdminRecord.theSensorMode[i], SENSOR_MODE_SIZE + 1); if (checkStream(is)) return; is.seekg(OFF_NADIR_ANGLE_OFFSET[i], std::ios_base::beg); is.get(tmpBuff, OFF_NADIR_ANGLE_SIZE + 1); if (checkStream(is)) return; theAdminRecord.theOffNadirAngle[i] = atof(tmpBuff); } // End of scene loop. is.seekg(PRODUCT_TYPE_OFFSET, std::ios_base::beg); is.get(theAdminRecord.theProductType, PRODUCT_TYPE_SIZE + 1); if (checkStream(is)) return; is.seekg(PRODUCT_SIZE_OFFSET, std::ios_base::beg); is.get(theAdminRecord.theProductSize, PRODUCT_SIZE_SIZE + 1); if (checkStream(is)) return; is.seekg(PROCESSING_TYPE_OFFSET, std::ios_base::beg); is.get(theAdminRecord.theProcessingType, PROCESSING_TYPE_SIZE + 1); if (checkStream(is)) return; is.seekg(RESAMPLING_ALGO_OFFSET, std::ios_base::beg); is.get(theAdminRecord.theResampAlgorithm, RESAMPLING_ALGO_SIZE + 1); if (checkStream(is)) return; is.seekg(TAPE_VOLUME_NUMBER_OFFSET, std::ios_base::beg); is.get(tmpBuff, TAPE_VOLUME_NUMBER_SIZE + 1, '/'); if (checkStream(is)) return; theAdminRecord.theTapeVolumeNumber = atoi(tmpBuff); is.seekg(VOLUMES_PER_TAPE_OFFSET, std::ios_base::beg); is.get(tmpBuff, VOLUMES_PER_TAPE_SIZE + 1); if (checkStream(is)) return; theAdminRecord.theNumberVolumesPerTape = atoi(tmpBuff); is.seekg(PIXELS_PER_LINE_OFFSET, std::ios_base::beg); is.get(tmpBuff, PIXELS_PER_LINE_SIZE + 1); if (checkStream(is)) return; theAdminRecord.thePixelsPerLine = atoi(tmpBuff); is.seekg(LINES_PER_IMAGE_OFFSET, std::ios_base::beg); is.get(tmpBuff, LINES_PER_IMAGE_SIZE + 1); if (checkStream(is)) return; theAdminRecord.theLinesPerImage = atoi(tmpBuff); is.seekg(FIRST_LINE_IN_VOLUME_OFFSET, std::ios_base::beg); is.get(tmpBuff, FIRST_LINE_IN_VOLUME_SIZE + 1); if (checkStream(is)) return; theAdminRecord.the1stLineInVolume = atoi(tmpBuff); is.seekg(BLOCKING_FACTOR_OFFSET, std::ios_base::beg); is.get(tmpBuff, BLOCKING_FACTOR_SIZE + 1); if (checkStream(is)) return; theAdminRecord.theTapeBlockingFactor = atoi(tmpBuff); is.seekg(RECORD_LENGTH_OFFSET, std::ios_base::beg); is.get(tmpBuff, RECORD_LENGTH_SIZE + 1); if (checkStream(is)) return; theAdminRecord.theRecordSize = atoi(tmpBuff); is.seekg(PIXEL_GSD_OFFSET, std::ios_base::beg); is.get(tmpBuff, PIXEL_GSD_SIZE + 1); if (checkStream(is)) return; theAdminRecord.theGsd = atof(tmpBuff); is.seekg(BITS_PER_PIXEL_OFFSET, std::ios_base::beg); is.get(tmpBuff, BITS_PER_PIXEL_SIZE + 1); if (checkStream(is)) return; theAdminRecord.theOutputBitsPerPixel = atoi(tmpBuff); is.seekg(ACQUIRED_BITS_PER_PIXEL_OFFSET, std::ios_base::beg); is.get(tmpBuff, BITS_PER_PIXEL_SIZE + 1); if (checkStream(is)) return; theAdminRecord.theAcquiredBitsPerPixel = atoi(tmpBuff); is.seekg(BANDS_PRESENT_OFFSET, std::ios_base::beg); is.get(theAdminRecord.theBandsPresentString, BANDS_PRESENT_SIZE + 1); if (checkStream(is)) return; is.seekg(FORMAT_VERSION_OFFSET, std::ios_base::beg); is.get(theAdminRecord.theFormatVersion, FORMAT_VERSION_SIZE + 1); if (checkStream(is)) return; //*** // End of administrative record. //*** //*** // Start of radiometric record. //*** for (i = 0; i < NUMBER_OF_BANDS; i++) { is.seekg(BIAS_OFFSET[i], std::ios_base::beg); is.get(tmpBuff, BIAS_SIZE + 1); if (checkStream(is)) return; theRadiomRecord.theBias[i] = atof(tmpBuff); is.seekg(GAIN_OFFSET[i], std::ios_base::beg); is.get(tmpBuff, GAIN_SIZE + 1); if (checkStream(is)) return; theRadiomRecord.theGain[i] = atof(tmpBuff); } //*** // End of radiometric record. //*** //*** // Start of geometric record. //*** is.seekg(MAP_PROJECTION_NAME_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theMapProjectionName, MAP_PROJECTION_NAME_SIZE + 1); if (checkStream(is)) return; is.seekg(ELLIPSOID_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theEllipsoid, ELLIPSOID_SIZE + 1); if (checkStream(is)) return; is.seekg(DATUM_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theDatum, DATUM_SIZE + 1, ' '); if (checkStream(is)) return; //*** // Get the fifteen projection parameters. //*** for(i = 0; i < 15; i++) { is.seekg(PROJ_PARAM_OFFSET[i], std::ios_base::beg); is.get(tmpBuff, PROJECTION_PARAMETER_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theProjectionParams[i] = atof(tmpBuff); } //*** // Start of upper left data: longitude, latitude, easting, and northing. //*** is.seekg(UL_LON_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theUlLon, LON_SIZE + 1); if (checkStream(is)) return; is.seekg(UL_LAT_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theUlLat, LAT_SIZE + 1); if (checkStream(is)) return; is.seekg(UL_EASTING_OFFSET, std::ios_base::beg); is.get(tmpBuff, EASTING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theUlEasting = atof(tmpBuff); is.seekg(UL_NORTHING_OFFSET, std::ios_base::beg); is.get(tmpBuff, NORTHING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theUlNorthing = atof(tmpBuff); //*** // End of upper left data. //*** //*** // Start of upper right data: longitude, latitude, easting, and northing. //*** is.seekg(UR_LON_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theUrLon, LON_SIZE + 1); if (checkStream(is)) return; is.seekg(UR_LAT_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theUrLat, LAT_SIZE + 1); if (checkStream(is)) return; is.seekg(UR_EASTING_OFFSET, std::ios_base::beg); is.get(tmpBuff, EASTING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theUrEasting = atof(tmpBuff); is.seekg(UR_NORTHING_OFFSET, std::ios_base::beg); is.get(tmpBuff, NORTHING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theUrNorthing = atof(tmpBuff); //*** // End of upper right data. //*** //*** // Start of lower right data: longitude, latitude, easting, and northing. //*** is.seekg(LR_LON_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theLrLon, LON_SIZE + 1); if (checkStream(is)) return; is.seekg(LR_LAT_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theLrLat, LAT_SIZE + 1); if (checkStream(is)) return; is.seekg(LR_EASTING_OFFSET, std::ios_base::beg); is.get(tmpBuff, EASTING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theLrEasting = atof(tmpBuff); is.seekg(LR_NORTHING_OFFSET, std::ios_base::beg); is.get(tmpBuff, NORTHING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theLrNorthing = atof(tmpBuff); //*** // End of lower right data. //*** //*** // Start of lower left data: longitude, latitude, easting, and northing. //*** is.seekg(LL_LON_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theLlLon, LON_SIZE + 1); if (checkStream(is)) return; is.seekg(LL_LAT_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theLlLat, LAT_SIZE + 1); if (checkStream(is)) return; is.seekg(LL_EASTING_OFFSET, std::ios_base::beg); is.get(tmpBuff, EASTING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theLlEasting = atof(tmpBuff); is.seekg(LL_NORTHING_OFFSET, std::ios_base::beg); is.get(tmpBuff, NORTHING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theLlNorthing = atof(tmpBuff); //*** // End of lower left data. //*** //*** // Start of scene center data: longitude, latitude, easting, northing, // sample, line. //*** is.seekg(CENTER_LON_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theCenterLon, LON_SIZE + 1); if (checkStream(is)) return; is.seekg(CENTER_LAT_OFFSET, std::ios_base::beg); is.get(theGeoRecord.theCenterLat, LAT_SIZE + 1); if (checkStream(is)) return; is.seekg(CENTER_EASTING_OFFSET, std::ios_base::beg); is.get(tmpBuff, EASTING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theCenterEasting = atof(tmpBuff); is.seekg(CENTER_NORTHING_OFFSET, std::ios_base::beg); is.get(tmpBuff, NORTHING_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theCenterNorthing = atof(tmpBuff); is.seekg(CENTER_SAMPLE_OFFSET, std::ios_base::beg); is.get(tmpBuff, CENTER_SAMPLE_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theCenterSample = atoi(tmpBuff); is.seekg(CENTER_LINE_OFFSET, std::ios_base::beg); is.get(tmpBuff, CENTER_LINE_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theCenterLine = atoi(tmpBuff); //*** // End of scene center data. //*** is.seekg(HORIZONTAL_OFFSET_OFFSET, std::ios_base::beg); is.get(tmpBuff, HORIZONTAL_OFFSET_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theHorizontalOffset = atoi(tmpBuff); is.seekg(ORIENTATION_ANGLE_OFFSET, std::ios_base::beg); is.get(tmpBuff, ORIENTATION_ANGLE_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theOrientationAngle = atof(tmpBuff); is.seekg(SUN_ELEVATION_OFFSET, std::ios_base::beg); is.get(tmpBuff, SUN_ELEVATION_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theSunElevationAngle = atof(tmpBuff); is.seekg(SUN_AZIMUTH_OFFSET, std::ios_base::beg); is.get(tmpBuff, SUN_AZIMUTH_SIZE + 1); if (checkStream(is)) return; theGeoRecord.theSunAzimuth = atof(tmpBuff); //*** // End of geometric record. //*** } //*************************************************************************** // PRIVATE METHOD: // ossimFfRevc::checkStream(istream& is) // // Checks the stream. If an error has occurred it sets theErrorStatus. // Returns: theErrorStatus ( 0 = OK, 1 = ERROR ) //*************************************************************************** int ossimFfRevc::checkStream(ossim::istream& is) { //*** // istreams set fault bits and the operator! is overloaded to return // true if an error has occurred. //*** if (!is) { theErrorStatus = OSSIM_ERROR; ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimFfRevc::checkStream: " << "Stream corrupted. Returning from method." << std::endl; } return theErrorStatus; } //*************************************************************************** // Function: // ostream& operator<<(ostream& os, const ossimFfRevc& head) //*************************************************************************** std::ostream& operator<<(std::ostream& os, const ossimFfRevc& head) { head.print(os); return os; } //*************************************************************************** // CONSTRUCTOR: // ossimFfRevc::AdminRecord::AdminRecord() // // Default constructor for AdminRecord nested class: //*************************************************************************** ossimFfRevc::AdminRecord::AdminRecord() : theTapeVolumeNumber(1), theNumberVolumesPerTape(1), thePixelsPerLine(0), theLinesPerImage(0), the1stLineInVolume(1), theTapeBlockingFactor(1), theRecordSize(0), theGsd(0.0), theOutputBitsPerPixel(8), theAcquiredBitsPerPixel(6) { const char tmpBuff[] = ""; strcpy(theProductOrderNumber, tmpBuff); //> // There can be four scenes. //< for (int i = 0; i < 4; i++) { strcpy(thePathRowNumber[i], tmpBuff); strcpy(theAcquisitionDate[i], tmpBuff); strcpy(theSatName[i], tmpBuff); strcpy(theSensorName[i], tmpBuff); strcpy(theSensorMode[i], tmpBuff); theOffNadirAngle[i] = 0.0; } strcpy(theProductType, "MAP ORIENTED"); strcpy(theProductSize, tmpBuff); strcpy(theProcessingType, "SYSTEMATIC"); strcpy(theResampAlgorithm, "CC"); strcpy(theBandsPresentString, "P"); strcpy(theFormatVersion, "C"); } //*************************************************************************** // CONSTRUCTOR: // ossimFfRevc::RadiomRecord::RadiomRecord() // // Default constructor for RadiomRecord nested class: //*************************************************************************** ossimFfRevc::RadiomRecord::RadiomRecord() { for (int i = 0; i < 8; i++) { theBias[i] = 0.0; theGain[i] = 0.0; } } //*************************************************************************** // CONSTRUCTOR: // ossimFfRevc::GeoRecord::GeomRecord() // // Default constructor for GeoRecord nested class: //*************************************************************************** ossimFfRevc::GeoRecord::GeoRecord() : theUlEasting(0.0), theUlNorthing(0.0), theUrEasting(0.0), theUrNorthing(0.0), theLrEasting(0.0), theLrNorthing(0.0), theLlEasting(0.0), theLlNorthing(0.0), theCenterEasting(0.0), theCenterNorthing(0.0), theCenterSample(0), theCenterLine(0), theHorizontalOffset(0), theOrientationAngle(0.0), theSunElevationAngle(0.0), theSunAzimuth(0.0) { for (int i = 0; i < 15; i++) { theProjectionParams[i] = 0.0; } const char tmpBuff[] = ""; strcpy(theMapProjectionName, "UTM"); strcpy(theEllipsoid, tmpBuff); strcpy(theDatum, tmpBuff); strcpy(theUlLon, tmpBuff); strcpy(theUlLat, tmpBuff); strcpy(theUrLon, tmpBuff); strcpy(theUrLat, tmpBuff); strcpy(theLrLon, tmpBuff); strcpy(theLrLat, tmpBuff); strcpy(theLlLon, tmpBuff); strcpy(theLlLat, tmpBuff); strcpy(theCenterLon, tmpBuff); strcpy(theCenterLat, tmpBuff); } ossim-Miami-2.9.1/src/support_data/ossimFgdcTxtDoc.cpp000066400000000000000000000177471352751253100227770ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File ossimFgdcTxtDoc.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: ossimFgdcTxtDoc class definition. // // FGDC = "Federal Geographic Data Committee" // // See: http://www.fgdc.gov/ // //---------------------------------------------------------------------------- #include #include #include #include #include #include #include #include #include #include static const std::string ALTITUDE_DISTANCE_UNITS_KW = "altitude_distance_units"; static const std::string FGDC_FILE_KW = "fgdc_file"; static const std::string FGDC_VERSION_KW = "fgdc_version"; static const std::string FGDC_VERSION_001_1998 = "FGDC-STD-001-1998"; ossimFgdcTxtDoc::ossimFgdcTxtDoc() : m_kwl( new ossimKeywordlist() ) { } ossimFgdcTxtDoc::~ossimFgdcTxtDoc() { m_kwl = 0; // Not a leak, m_kwl is a ossimRefPtr. } bool ossimFgdcTxtDoc::open(const ossimFilename& file) { bool result = false; // Open the file: std::ifstream str( file.c_str(), std::ios_base::in ); if ( str.good() ) { std::string key = "Metadata_Standard_Version"; std::string value; if ( findKey( str, true, key, value ) ) { if ( value == FGDC_VERSION_001_1998 ) { result = true; m_kwl->addPair( FGDC_VERSION_KW, value ); m_kwl->addPair( FGDC_FILE_KW, file.string() ); // Store for getAltitudeDistanceUnits() method if key found. key = "Altitude_Distance_Units"; if ( findKey( str, false, key, value ) ) { m_kwl->addPair( ALTITUDE_DISTANCE_UNITS_KW, value ); } } } } return result; } void ossimFgdcTxtDoc::close() { m_kwl->clear(); } void ossimFgdcTxtDoc::getProjection(ossimRefPtr& proj) { static const char M[] = "ossimFgdcTxtDoc::getProjection"; try { // Get the file name: std::string file = m_kwl->findKey( FGDC_FILE_KW ); if ( file.size() ) { // Get the version: std::string version = m_kwl->findKey( FGDC_VERSION_KW ); if ( version.size() ) { // Note: Currently only coded against FGDC-STD-001-1998 if ( version == FGDC_VERSION_001_1998) { // Open the file: std::ifstream str( file.c_str(), std::ios_base::in ); if ( str.good() ) { // Find the Spatial_Reference_Information section: std::string key = "Spatial_Reference_Information:"; if ( findKey( str, key ) ) { getProjectionV1( str, proj ); } } } } } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << M << " caught exception:\n" << e.what() << std::endl; } } void ossimFgdcTxtDoc::getAltitudeDistanceUnits(std::string& units) const { units = m_kwl->findKey( ALTITUDE_DISTANCE_UNITS_KW ); } void ossimFgdcTxtDoc::getProjectionV1(std::ifstream& str, ossimRefPtr& proj) { static const char M[] = "ossimFgdcTxtDoc::getProjectionV1"; std::string fgdcKey; std::string fgdcValue; std::string key; std::string value; ossimKeywordlist projectionKwl; fgdcKey = "Grid_Coordinate_System_Name"; if ( findKey( str, true, fgdcKey, fgdcValue ) ) { if ( fgdcValue == "Universal Transverse Mercator" ) { key = "type"; value = "ossimUtmProjection"; projectionKwl.addPair(key, value); // Get the zone: fgdcKey = "UTM_Zone_Number"; if ( findKey( str, true, fgdcKey, fgdcValue ) ) { key = "zone"; value = fgdcValue; projectionKwl.addPair(key, value); } else { std::string errMsg = M; errMsg += " ERROR: Could not determine utm zone!"; throw ossimException(errMsg); } // Check for Southern hemisphere. fgdcKey = "False_Northing"; if ( findKey( str, true, fgdcKey, fgdcValue ) ) { key = "hemisphere"; // Hemisphere( North false easting = 0.0, South = 10000000): ossim_float64 f = ossimString::toFloat64( fgdcKey.c_str() ); if ( f == 0.0 ) { value = "N"; } else { value = "S"; } projectionKwl.addPair(key, value); } } // UTM section: else { // Exception thrown so that we see that we are not handling a projection. std::string errMsg = M; errMsg += "ERROR: Unhandled projection: "; errMsg += fgdcValue; throw ossimException(errMsg); } fgdcKey = "Horizontal_Datum_Name"; if ( findKey( str, true, fgdcKey, fgdcValue ) ) { getOssimDatum( fgdcValue, value ); key = "datum"; projectionKwl.addPair(key, value); } } // Matches: findKey( Grid_Coordinate_System_Name ) if ( projectionKwl.getSize() ) { proj = ossimMapProjectionFactory::instance()->createProjection(projectionKwl); } else { proj = 0; } } bool ossimFgdcTxtDoc::findKey( std::ifstream& str, const std::string& key) { bool result = false; ossimString line; while ( !str.eof() ) { // Read line: std::getline( str, line.string() ); if ( line.size() ) { // Eat white space. line.trim(); if ( line.string() == key ) { result = true; break; } } } return result; } bool ossimFgdcTxtDoc::findKey( std::ifstream& str, bool seekBack, const std::string& key, std::string& value) { bool result = false; std::vector fgdcKeyValue; ossimString separator = ":"; ossimString line; ossimKeywordlist projectionKwl; std::streampos currentPosition = str.tellg(); while ( !str.eof() ) { // Read line: std::getline( str, line.string() ); if ( line.size() ) { // Eat white space. line.trim(); // Split between ':' fgdcKeyValue.clear(); line.split(fgdcKeyValue, separator, false); if ( fgdcKeyValue.size() == 2 ) { fgdcKeyValue[0].trim(); if ( fgdcKeyValue[0].size() ) { if ( fgdcKeyValue[0] == key ) { // Found it. Initialize value and get out. result = true; fgdcKeyValue[1].trim(); value = fgdcKeyValue[1].string(); break; // from while loop. } } } } } if ( seekBack ) { str.seekg(currentPosition); } return result; } // Could be moved to base class for xml and text doc. void ossimFgdcTxtDoc::getOssimDatum( const std::string& fgdcDatumString, std::string& ossimDatumCode ) const { ossimString horizdn = fgdcDatumString; horizdn.downcase(); if ( horizdn == "north american datum of 1983" ) { ossimDatumCode = "NAR-C"; } else if ( horizdn == "north american datum of 1927" ) { ossimDatumCode = "NAS-C"; } else if ( horizdn == "wgs84") { ossimDatumCode = "WGE"; } else { // Exception thrown so that we see that we are not handling a datum. std::string errMsg = "ossimFgdcTxtDoc::getOssimDatum ERROR: Unhandled datum: "; errMsg += horizdn.string(); throw ossimException(errMsg); } } ossim-Miami-2.9.1/src/support_data/ossimFgdcXmlDoc.cpp000066400000000000000000000361671352751253100227550ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: Utility class to encapsulate parsing projection info in the xml file. // //---------------------------------------------------------------------------- // $Id: ossimFgdcXmlDoc.cpp 2063 2011-01-19 19:38:12Z ming.su $ #include #include #include #include #include #include #include #include #include #include #include #include #include /* for std::fabs */ using namespace std; // Static trace for debugging static ossimTrace traceDebug("ossimFgdcXmlDoc:debug"); ossimFgdcXmlDoc::ossimFgdcXmlDoc() : m_xmlFilename(ossimFilename::NIL), m_xmlDocument(0), m_projection(0), m_boundInDegree(false) { } ossimFgdcXmlDoc::~ossimFgdcXmlDoc() { } bool ossimFgdcXmlDoc::open(const ossimFilename& xmlFileName) { bool result = false; if ( isOpen() ) { close(); } if (xmlFileName.size()) { m_xmlDocument = new ossimXmlDocument(xmlFileName); if ( m_xmlDocument.valid() ) { // May want to add a test for valid FGDC here??? (drb) m_xmlFilename = xmlFileName; result = true; } } return result; } void ossimFgdcXmlDoc::close() { m_xmlFilename = ossimFilename::NIL; m_xmlDocument = 0; m_projection = 0; } ossimRefPtr ossimFgdcXmlDoc::getProjection() { if ( (m_projection.valid() == false) && isOpen() ) { ossimString projName; if ( getProjCsn(projName) ) { if (!projName.empty()) { m_projection = ossimEpsgProjectionFactory::instance()->createProjection(projName); if ( m_projection.valid() ) { ossimDpt gsd; gsd.makeNan(); ossim_float64 d; if ( getXRes(d) ) { gsd.x = std::fabs(d); } if ( getYRes(d) ) { gsd.y = std::fabs(d); } ossimMapProjection* mapProj = dynamic_cast(m_projection.get()); if (mapProj) { ossimDrect rect; getBoundingBox(rect); if (mapProj->isGeographic()) { ossimGpt tie(rect.ul().lat, rect.ul().lon); mapProj->setUlTiePoints(tie); mapProj->setDecimalDegreesPerPixel(gsd); } else { ossimDpt tie(rect.ul().x, rect.ul().y); ossimUnitType unitType = getUnitType(); if ( unitType == OSSIM_US_SURVEY_FEET) { gsd = gsd * US_METERS_PER_FT; tie = tie * US_METERS_PER_FT; } else if ( unitType == OSSIM_FEET ) { gsd = gsd * MTRS_PER_FT; tie = tie * MTRS_PER_FT; } mapProj->setUlTiePoints(tie); mapProj->setMetersPerPixel(gsd); } } } } } } return m_projection; } ossimUnitType ossimFgdcXmlDoc::getUnitType() const { ossimUnitType result = OSSIM_METERS; // default ossimString units; if ( getPlanarDistantUnits(units) ) { units.downcase(); if ( units.contains("feet") ) { if ( units.contains("international") ) { result = OSSIM_FEET; } else { result = OSSIM_US_SURVEY_FEET; // Default for feet. } } } return result; } bool ossimFgdcXmlDoc::isOpen() const { return m_xmlDocument.valid(); } bool ossimFgdcXmlDoc::getGeoCsn(ossimString& s) const { ossimString xpath = "/metadata/spref/horizsys/cordsysn/geogcsn"; return getPath(xpath, s); } bool ossimFgdcXmlDoc::getProjCsn(ossimString& s) const { ossimString xpath = "/metadata/spref/horizsys/cordsysn/projcsn"; return getPath(xpath, s); } bool ossimFgdcXmlDoc::getAltitudeDistantUnits(ossimString& s) const { ossimString xpath = "/metadata/spref/vertdef/altsys/altunits"; return getPath(xpath, s); } bool ossimFgdcXmlDoc::getGridCoordinateSystem(ossimString& s) const { ossimString xpath = "/metadata/spref/horizsys/planar/gridsys/gridsysn"; return getPath(xpath, s); } ossimRefPtr ossimFgdcXmlDoc::getGridCoordSysProjection() { static const char M[] = "ossimFgdcXmlDoc::getGridCoordSysProjection"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if ( m_projection.valid() == false ) { ossimString s; if ( getGridCoordinateSystem(s) ) { ossimString gridsysn = s.downcase(); if ( getHorizontalDatum(s) ) { ossimString horizdn = s.downcase(); const ossimDatum* datum = createOssimDatum(s); // throws exception if ( gridsysn == "universal transverse mercator" ) { // Get the zone: if ( getUtmZone(s) ) { ossim_int32 zone = s.toInt32(); //--- // Note: Contruct with an origin with our datum. // "proj->setDatum" does not change the origin's datum. // This ensures theossimEpsgProjectionDatabase::findProjectionCode // sets the psc code correctly down the line. //--- ossimRefPtr utmProj = new ossimUtmProjection( *(datum->ellipsoid()), ossimGpt(0.0,0.0,0.0,datum) ); utmProj->setDatum(datum); utmProj->setZone(zone); // Hemisphere( North false easting = 0.0, South = 10000000): bool tmpResult = getUtmFalseNorthing(s); if ( tmpResult && ( s != "0.0" ) ) { utmProj->setHemisphere('S'); } else { utmProj->setHemisphere('N'); } utmProj->setPcsCode(0); ossim_float64 xRes = 0.0; ossim_float64 yRes = 0.0; if (getXRes(xRes) && getYRes(yRes)) { ossimDrect rect; getBoundingBox(rect); ossimDpt gsd(std::fabs(xRes), std::fabs(yRes)); ossimUnitType unitType = getUnitType(); if (m_boundInDegree) { ossimGpt tieg(rect.ul().lat, rect.ul().lon); utmProj->setUlTiePoints(tieg); } else { ossimDpt tie(rect.ul().x, rect.ul().y); if ( unitType == OSSIM_US_SURVEY_FEET) { tie = tie * US_METERS_PER_FT; } else if ( unitType == OSSIM_FEET ) { tie = tie * MTRS_PER_FT; } utmProj->setUlTiePoints(tie); } if ( unitType == OSSIM_US_SURVEY_FEET) { gsd = gsd * US_METERS_PER_FT; } else if ( unitType == OSSIM_FEET ) { gsd = gsd * MTRS_PER_FT; } utmProj->setMetersPerPixel(gsd); } m_projection = utmProj.get(); // Capture projection. } else { std::string errMsg = M; errMsg += " ERROR: Could not determine utm zone!"; throw ossimException(errMsg); } } } } } if ( traceDebug() ) { if ( m_projection.valid() ) { m_projection->print(ossimNotify(ossimNotifyLevel_DEBUG)); } ossimNotify(ossimNotifyLevel_DEBUG) << M << " exiting...\n"; } return m_projection; } bool ossimFgdcXmlDoc::getHorizontalDatum(ossimString& s) const { ossimString xpath = "/metadata/spref/horizsys/geodetic/horizdn"; return getPath(xpath, s); } bool ossimFgdcXmlDoc::getPlanarDistantUnits(ossimString& s) const { ossimString xpath = "/metadata/spref/horizsys/planar/planci/plandu"; return getPath(xpath, s); } bool ossimFgdcXmlDoc::getUtmFalseNorthing(ossimString& s) const { ossimString xpath = "/metadata/spref/horizsys/planar/gridsys/utm/transmer/fnorth"; return getPath(xpath, s); } bool ossimFgdcXmlDoc::getUtmZone(ossimString& s) const { ossimString xpath = "/metadata/spref/horizsys/planar/gridsys/utm/utmzone"; return getPath(xpath, s); } bool ossimFgdcXmlDoc::getXRes(ossim_float64& v) const { ossimString xpath = "/metadata/spdoinfo/rastinfo/rastxsz"; if (getPath(xpath, v) == false) { xpath = "/metadata/spref/horizsys/planar/planci/coordrep/absres"; } return getPath(xpath, v); } bool ossimFgdcXmlDoc::getYRes(ossim_float64& v) const { ossimString xpath = "/metadata/spdoinfo/rastinfo/rastysz"; if (getPath(xpath, v) == false) { xpath = "/metadata/spref/horizsys/planar/planci/coordrep/ordres"; } return getPath(xpath, v); } bool ossimFgdcXmlDoc::getImageSize(ossimIpt& size) const { bool result = false; if ( m_xmlDocument.valid() ) { ossimString xpath = "/metadata/spatRepInfo/GridSpatRep/axDimProps/Dimen/dimSize"; vector > xml_nodes; m_xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() > 1) { size.x = xml_nodes[0]->getText().toInt32(); size.y = xml_nodes[1]->getText().toInt32(); result = true; } if (result == false) { xpath = "/metadata/spdoinfo/rastinfo/colcount"; ossim_float64 x = 0.0; result = getPath(xpath, x); if (result) { size.x = (ossim_int32)x; } xpath = "/metadata/spdoinfo/rastinfo/rowcount"; ossim_float64 y = 0.0; result = getPath(xpath, y); if (result) { size.y = (ossim_int32)y; } } } return result; } void ossimFgdcXmlDoc::getBoundingBox(ossimDrect& rect) const { rect.makeNan(); if (isOpen()) { double ll_lat = 0.0; double ll_lon = 0.0; double lr_lat = 0.0; double lr_lon = 0.0; double ul_lat = 0.0; double ul_lon = 0.0; double ur_lat = 0.0; double ur_lon = 0.0; ossimString xpath = "/metadata/idinfo/spdom/lboundng/leftbc"; bool result = getPath(xpath, ul_lon); if (!result) { xpath = "/metadata/idinfo/spdom/bounding/westbc"; result = getPath(xpath, ul_lon); m_boundInDegree = true; } if (result) { ll_lon = ul_lon; } xpath = "/metadata/idinfo/spdom/lboundng/rightbc"; result = getPath(xpath, ur_lon); if (!result) { xpath = "/metadata/idinfo/spdom/bounding/eastbc"; result = getPath(xpath, ur_lon); m_boundInDegree = true; } if (result) { lr_lon = ur_lon; } xpath = "/metadata/idinfo/spdom/lboundng/bottombc"; result = getPath(xpath, ll_lat); if (!result) { xpath = "/metadata/idinfo/spdom/bounding/southbc"; result = getPath(xpath, ll_lat); m_boundInDegree = true; } if (result) { lr_lat = ll_lat; } xpath = "/metadata/idinfo/spdom/lboundng/topbc"; result = getPath(xpath, ul_lat); if (!result) { xpath = "/metadata/idinfo/spdom/bounding/northbc"; result = getPath(xpath, ul_lat); m_boundInDegree = true; } if (result) { ur_lat = ul_lat; } rect = ossimDrect(ossimDpt(ul_lon, ul_lat), ossimDpt(ur_lon, ur_lat), ossimDpt(lr_lon, lr_lat), ossimDpt(ll_lon, ll_lat), OSSIM_RIGHT_HANDED); } } ossim_uint32 ossimFgdcXmlDoc::getNumberOfBands() { ossim_uint32 numOfBands = 0; ossimString s; ossimString xpath = "/metadata/spdoinfo/rastinfo/vrtcount"; if (getPath(xpath, s)) { numOfBands = s.toInt(); } return numOfBands; } bool ossimFgdcXmlDoc::getPath(const ossimString& path, ossimString& s) const { static const char M[] = "ossimFgdcXmlDoc::getPath"; bool result = false; if ( m_xmlDocument.valid() ) { std::vector > xnodes; m_xmlDocument->findNodes(path, xnodes); if ( xnodes.size() == 1 ) // Error if more than one. { if ( xnodes[0].valid() ) { s = xnodes[0]->getText(); result = true; } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << M << " ERROR:\n" << "Node not found: " << path << std::endl; } } } else if ( xnodes.size() == 0 ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << M << " ERROR:\nNode not found: " << path << std::endl; } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << M << " ERROR:\nMultiple nodes found: " << path << std::endl; } } } if (!result) { s.clear(); } return result; } bool ossimFgdcXmlDoc::getPath(const ossimString& path, ossim_float64& v) const { ossimString s; bool result = getPath(path, s); if ( result ) { v = s.toFloat64(); } return result; } const ossimDatum* ossimFgdcXmlDoc::createOssimDatum(const ossimString& s) const { ossimString horizdn = s.downcase(); ossimString datumCode; if ( horizdn == "north american datum of 1983" ) { datumCode = "NAR-C"; } else if ( horizdn == "north american datum of 1927" ) { datumCode = "NAS-C"; } else if ( horizdn == "wgs84") { datumCode = "WGE"; } else { std::string errMsg = "ossimFgdcXmlDoc::createOssimDatum ERROR: Unhandled datum: "; errMsg += horizdn.string(); throw ossimException(errMsg); } return ossimDatumFactoryRegistry::instance()->create(datumCode); } ossim-Miami-2.9.1/src/support_data/ossimGeoTiff.cpp000066400000000000000000002246121352751253100223200ustar00rootroot00000000000000//*************************************************************************** // FILE: ossimGeoTiff.cpp // // License: See top level LICENSE.txt file. // // Description: // // Class definition for ossimGeoTiff which is designed to read and hold tag // information. // //*************************************************************************** // $Id: ossimGeoTiff.cpp 21024 2012-05-30 08:45:13Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static const ossimGeoTiffCoordTransformsLut COORD_TRANS_LUT; static const ossimGeoTiffDatumLut DATUM_LUT; std::mutex ossimGeoTiff::theMutex; #ifdef OSSIM_ID_ENABLED static const char OSSIM_ID[] = "$Id: ossimGeoTiff.cpp 21024 2012-05-30 08:45:13Z dburken $"; #endif //--- // Static trace for debugging //--- static ossimTrace traceDebug("ossimGeoTiff:debug"); // Prototype, defined at bottom of this file. ArcMAP 9.2 bug workaround. ossim_uint16 getMetersEquivalentHarnCode(ossim_uint16 feet_harn_code); //--- // This was created to remove/hide "libgetiff/geo_normalize.h" in ossimGeoTiff.h. //--- class ossimPrivateGtifDef { public: ossimPrivateGtifDef() : m_defs(0) { } ~ossimPrivateGtifDef() { if (m_defs) { delete m_defs; m_defs = 0; } } GTIFDefn *m_defs; }; //************************************************************************************************* // CONSTRUCTOR //************************************************************************************************* ossimGeoTiff::ossimGeoTiff() : theTiffPtr(0), theGeoKeyOffset(0), theGeoKeyLength(0), theGeoKeysPresentFlag(false), theZone(0), theHemisphere("N"), theDoubleParamLength(0), theAsciiParamLength(0), theProjectionName("unknown"), theDatumName("unknown"), theWidth(0), theLength(0), theBitsPerSample(0), theModelType(0), theRasterType(ossimGeoTiff::UNDEFINED), theGcsCode(0), theDatumCode(0), theAngularUnits(0), thePcsCode(0), theCoorTransGeoCode(0), theLinearUnitsCode(ossimGeoTiff::UNDEFINED), theStdPar1(0.0), theStdPar2(0.0), theOriginLon(0.0), theOriginLat(0.0), theFalseEasting(0.0), theFalseNorthing(0.0), theScaleFactor(0.0), thePrivateDefinitions(new ossimPrivateGtifDef()) { } //************************************************************************************************* // CONSTRUCTOR //************************************************************************************************* ossimGeoTiff::ossimGeoTiff(const ossimFilename &file, ossim_uint32 entryIdx) : theTiffPtr(0), theGeoKeyOffset(0), theGeoKeyLength(0), theGeoKeysPresentFlag(false), theZone(0), theHemisphere("N"), theDoubleParamLength(0), theAsciiParamLength(0), theProjectionName("unknown"), theDatumName("unknown"), theWidth(0), theLength(0), theBitsPerSample(0), theModelType(0), theRasterType(ossimGeoTiff::UNDEFINED), theGcsCode(0), theDatumCode(0), theAngularUnits(0), thePcsCode(0), theCoorTransGeoCode(0), theLinearUnitsCode(ossimGeoTiff::UNDEFINED), theStdPar1(0.0), theStdPar2(0.0), theOriginLon(0.0), theOriginLat(0.0), theFalseEasting(0.0), theFalseNorthing(0.0), theScaleFactor(0.0), thePrivateDefinitions(new ossimPrivateGtifDef()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimGeoTiff::ossimGeoTiff: Entered..." << std::endl; #ifdef OSSIM_ID_ENABLED ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimGeoTiff::ossimGeoTiff: OSSIM_ID = " << OSSIM_ID << endl; #endif } if (readTags(file, entryIdx) == false) { theErrorStatus = ossimErrorCodes::OSSIM_ERROR; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimGeoTiff::ossimGeoTiff: " << "Unable to reade tags." << std::endl; } ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimGeoTiff::ossimGeoTiff: " << "Unable to reade tags." << std::endl; } if (traceDebug()) { print(ossimNotify(ossimNotifyLevel_DEBUG)); } } ossimGeoTiff::~ossimGeoTiff() { if (thePrivateDefinitions) { delete thePrivateDefinitions; thePrivateDefinitions = 0; } if (theTiffPtr) { XTIFFClose(theTiffPtr); theTiffPtr = 0; } } int ossimGeoTiff::getPcsUnitType(ossim_int32 pcsCode) { int pcsUnits = ossimGeoTiff::UNDEFINED; ossimUnitType units = OSSIM_UNIT_UNKNOWN; // default // Need to instantiate a projection given the pcs code: ossimMapProjection *proj = PTR_CAST(ossimMapProjection, ossimEpsgProjectionDatabase::instance()->findProjection(pcsCode)); if (proj) units = proj->getProjectionUnits(); else return ossimGeoTiff::UNDEFINED; switch (units) { case OSSIM_METERS: pcsUnits = ossimGeoTiff::LINEAR_METER; break; case OSSIM_FEET: pcsUnits = ossimGeoTiff::LINEAR_FOOT; break; case OSSIM_US_SURVEY_FEET: pcsUnits = ossimGeoTiff::LINEAR_FOOT_US_SURVEY; break; default: break; } return pcsUnits; } #define EPSG_CODE_MAX 32767 bool ossimGeoTiff::writeTags(TIFF *tifPtr, const ossimRefPtr projectionInfo, bool imagineNad27Flag) { std::lock_guard lock(theMutex); const ossimMapProjection *mapProj = projectionInfo->getProjection(); if (!mapProj) return false; GTIF *gtif = GTIFNew(tifPtr); // Get some things we need throughout. ossimGpt origin = mapProj->origin(); double falseEasting = mapProj->getFalseEasting(); double falseNorthing = mapProj->getFalseNorthing(); ossimKeywordlist kwl; mapProj->saveState(kwl); const char *stdParallel1 = kwl.find(ossimKeywordNames::STD_PARALLEL_1_KW); const char *stdParallel2 = kwl.find(ossimKeywordNames::STD_PARALLEL_2_KW); const char *scaleFactor = kwl.find(ossimKeywordNames::SCALE_FACTOR_KW); bool gcsTypeSet = false; //--- // Since using a pcs code is the easiest way to go, look for that first. //--- ossim_int16 pcsCode = mapProj->getPcsCode(); //--- // Get the units now. If user has overriden pcs units then go user defined // projection by setting pcs code to 0. //--- ossimString projName = mapProj->getClassName(); int units = ossimGeoTiff::UNDEFINED; if (mapProj->isGeographic()) units = ossimGeoTiff::ANGULAR_DEGREE; else units = getPcsUnitType(pcsCode); if (units == UNDEFINED) units = LINEAR_METER; if (pcsCode) { if ((units == LINEAR_FOOT_US_SURVEY) || (units == LINEAR_FOOT)) { // ArcMap 9.2 bug workaround (originally implemented by ESH 2008, reworked by OLK 04/2010 ossim_uint16 meter_pcs = getMetersEquivalentHarnCode(pcsCode); if (meter_pcs) pcsCode = meter_pcs; } //int gcs_code = mapProj->getGcsCode(); int datum_code = USER_DEFINED; int ellipsoid_code = USER_DEFINED; const ossimDatum *datum = mapProj->getDatum(); if (datum) { datum_code = (int)datum->epsgCode(); const ossimEllipsoid *ellipsoid = datum->ellipsoid(); if (ellipsoid) ellipsoid_code = ellipsoid->getEpsgCode(); } if (mapProj->isGeographic()) GTIFKeySet(gtif, GeographicTypeGeoKey, TYPE_SHORT, 1, pcsCode); GTIFKeySet(gtif, GeogGeodeticDatumGeoKey, TYPE_SHORT, 1, datum_code); GTIFKeySet(gtif, ProjectionGeoKey, TYPE_SHORT, 1, pcsCode); GTIFKeySet(gtif, GeogEllipsoidGeoKey, TYPE_SHORT, 1, ellipsoid_code); GTIFKeySet(gtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, pcsCode); } else { ossimString datumCode = "WGE"; ossimString datumName = "WGE"; // Attemp to get the datum code const ossimDatum *datum = mapProj->getDatum(); if (datum) { datumCode = datum->code(); datumName = datum->name(); } short gcs = USER_DEFINED; if (datumCode == "WGE") gcs = GCS_WGS_84; else if (datumCode == "WGD") gcs = GCS_WGS_72; else if (datumCode == "NAR-C") gcs = GCS_NAD83; else if (datumCode == "NAR") gcs = GCS_NAD83; else if (datumCode == "NAS-C") gcs = GCS_NAD27; else if (datumCode == "NAS") gcs = GCS_NAD27; else if (datumCode == "ADI-M") gcs = GCS_Adindan; else if (datumCode == "ARF-M") gcs = GCS_Arc_1950; else if (datumCode == "ARS-M") gcs = GCS_Arc_1960; else if (datumCode == "EUR-7" || datumCode == "EUR-M") gcs = GCS_ED50; else if ((datumCode == "OGB-7") || (datumCode == "OGB-M") || (datumCode == "OGB-A") || (datumCode == "OGB-B") || (datumCode == "OGB-C") || (datumCode == "OGB-D")) gcs = GCS_OSGB_1936; else if (datumCode == "TOY-M") gcs = GCS_Tokyo; else if (datumCode == "6055") gcs = 3785; // this is a special google datum so we will give it a gcs code of 3785 else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DATUM = " << datumCode << " tag not written " << std::endl << "Please let us know so we can add it" << std::endl; } } // *** // ERDAS Imagine < v8.7 has a NAD27 Conus Bug. They are not using the // proper GCS code. They use user-defined fields and Geog citation tag to // define. Sucks! It is an open issue at Leica. This is a work around // flag for this issue. // *** if ((datumCode == "NAS-C") && imagineNad27Flag) { gcs = USER_DEFINED; std::ostringstream os; os << "IMAGINE GeoTIFF Support\nCopyright 1991 - 2001 by ERDAS, Inc. All Rights Reserved\n@(#)$RCSfile$ $Revision: 21024 $ $Date: 2012-05-30 04:45:13 -0400 (Wed, 30 May 2012) $\nUnable to match Ellipsoid (Datum) to a GeographicTypeGeoKey value\nEllipsoid = Clarke 1866\nDatum = NAD27 (CONUS)"; GTIFKeySet(gtif, GeogCitationGeoKey, TYPE_ASCII, 1, os.str().c_str()); // User-Defined GTIFKeySet(gtif, GeogGeodeticDatumGeoKey, TYPE_SHORT, 1, KvUserDefined); // User-Defined GTIFKeySet(gtif, GeogEllipsoidGeoKey, TYPE_SHORT, 1, KvUserDefined); } else { GTIFKeySet(gtif, GeographicTypeGeoKey, TYPE_SHORT, 1, gcs); gcsTypeSet = true; } // Write the projection parameters. bool setFalseEastingNorthingFlag = false; if (projName == "ossimUtmProjection") { //--- // UTM tags needed example from the geo tiff spec page: // ModelTiepointTag = (0, 0, 0, 350807.4, 5316081.3, 0.0) // ModelPixelScaleTag = (100.0, 100.0, 0.0) // GeoKeyDirectoryTag: // GTModelTypeGeoKey = 1 (ModelTypeProjected) // GTRasterTypeGeoKey = 1 (RasterPixelIsArea) // ProjectedCSTypeGeoKey = 32660 (PCS_WGS84_UTM_zone_60N) // PCSCitationGeoKey = "UTM Zone 60 N with WGS84" // // NOTE: // The "ProjectedCSTypeGeoKey" can be constructed using the map zone // and the datum. //--- const ossimUtmProjection *utmProjection = dynamic_cast(mapProj); // Attempt to get the pcs key. int mapZone = utmProjection->getZone(); ossimString hemisphere = utmProjection->getHemisphere(); short projSysCode = 0; //--- // Use a projection code that does not imply a datum. // See section "6.3.3.2 Projection Codes" for definition. // // NOTE: The ossim code does not use negative zones to discriminate between // hemispheres. (drb 26 Oct. 2016) //--- if (hemisphere == "N") // Northern hemisphere. { projSysCode = 16000 + mapZone; } else // Southern hemisphere. { projSysCode = 16100 + mapZone; } // Set the Projected Coordinate System Type to be user defined. GTIFKeySet(gtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, USER_DEFINED); if (!gcsTypeSet) { // Set the geographic type to be user defined. GTIFKeySet(gtif, GeographicTypeGeoKey, TYPE_SHORT, 1, USER_DEFINED); } // Set the ProjectionGeoKey in place of the ProjectedCSTypeGeoKey. GTIFKeySet(gtif, ProjectionGeoKey, TYPE_SHORT, 1, projSysCode); std::ostringstream os; os << "UTM Zone " << dec << mapZone << hemisphere.c_str() << " with " << datumName << " datum"; GTIFKeySet(gtif, PCSCitationGeoKey, TYPE_ASCII, 1, os.str().c_str()); } // End of "if ( projName == "ossimUtmProjection" ) else if (projName == "ossimBngProjection") { // User-Defined GTIFKeySet(gtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, PCS_BRITISH_NATIONAL_GRID); //KvUserDefined ); // User-Defined GTIFKeySet(gtif, ProjectionGeoKey, TYPE_SHORT, 1, KvUserDefined); GTIFKeySet(gtif, PCSCitationGeoKey, TYPE_ASCII, 26, "PCS_British_National_Grid"); GTIFKeySet(gtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, (uint16)CT_TransverseMercator); GTIFKeySet(gtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1, origin.lond()); GTIFKeySet(gtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, origin.latd()); setFalseEastingNorthingFlag = true; double scale = ossimString(scaleFactor).toDouble(); GTIFKeySet(gtif, ProjScaleAtNatOriginGeoKey, TYPE_DOUBLE, 1, scale); } else if (projName == "ossimSinusoidalProjection") { GTIFKeySet(gtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, (uint16)CT_Sinusoidal); GTIFKeySet(gtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1, origin.lond()); GTIFKeySet(gtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, origin.latd()); setFalseEastingNorthingFlag = true; } else if ((projName == "ossimEquDistCylProjection") || (projName == "ossimLlxyProjection")) { GTIFKeySet(gtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1, origin.lond()); GTIFKeySet(gtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, origin.latd()); } else if ((projName == "ossimLambertConformalConicProjection") || (projName == "ossimAlbersProjection")) { //--- // Lambert Conformal Conic: // tags needed example from the geo tiff spec page: // ModelTiepointTag = ( 80, 100, 0, 200000, 1500000, 0) // ModelPixelScaleTag = (1000, 1000, 0) // GeoKeyDirectoryTag: // GTModelTypeGeoKey = 1 (ModelTypeProjected) // GTRasterTypeGeoKey = 1 (RasterPixelIsArea) // GeographicTypeGeoKey = 4267 (GCS_NAD27) // ProjectedCSTypeGeoKey = 32767 (user-defined) // ProjectionGeoKey = 32767 (user-defined) // ProjLinearUnitsGeoKey = 9001 (Linear_Meter) // ProjCoordTransGeoKey = 8 (CT_LambertConfConic_2SP) // ProjStdParallel1GeoKey = 41.333 // ProjStdParallel2GeoKey = 48.666 // ProjCenterLongGeoKey =-120.0 // ProjNatOriginLatGeoKey = 45.0 // ProjFalseEastingGeoKey, = 200000.0 // ProjFalseNorthingGeoKey, = 1500000.0 // // NOTE: Albers Same as Lambert with the exception of the // ProjCoordTransGeoKey which is: CT_AlbersEqualArea. //--- if (projName == "ossimLambertConformalConicProjection") { GTIFKeySet(gtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, (uint16)CT_LambertConfConic_2SP); } else // Albers { GTIFKeySet(gtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, (uint16)CT_AlbersEqualArea); } // User-Defined GTIFKeySet(gtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, KvUserDefined); // User-Defined GTIFKeySet(gtif, ProjectionGeoKey, TYPE_SHORT, 1, KvUserDefined); double phi1 = ossimString(stdParallel1).toDouble(); GTIFKeySet(gtif, ProjStdParallel1GeoKey, TYPE_DOUBLE, 1, phi1); // 1st parallel double phi2 = ossimString(stdParallel2).toDouble(); GTIFKeySet(gtif, ProjStdParallel2GeoKey, TYPE_DOUBLE, 1, phi2); // 2nd parallel GTIFKeySet(gtif, ProjCenterLongGeoKey, TYPE_DOUBLE, 1, origin.lond()); // Longitude at the origin. GTIFKeySet(gtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, origin.latd()); // Origin setFalseEastingNorthingFlag = true; } // End of Lambert. else if (projName == "ossimMercatorProjection") { GTIFKeySet(gtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, (uint16)CT_Mercator); GTIFKeySet(gtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1, origin.lond()); GTIFKeySet(gtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, origin.latd()); setFalseEastingNorthingFlag = true; double scale = ossimString(scaleFactor).toDouble(); GTIFKeySet(gtif, ProjScaleAtNatOriginGeoKey, TYPE_DOUBLE, 1, scale); } else if (projName == "ossimTransMercatorProjection") { //--- // Transverse Mercator ( no example in the geo tiff spec. // Requires: // - latitude/longitude of the origin // - easting/northing of some tie point(line/sample 0,0) // - false easting/northing // - The scale factor. //--- //--- // The easting/northing is the distance from the origin plus the // false easting/northing. In other words if line 0 is 5,000 // meters from the origin and the false northing is 5,000 meters, // then the northing would be 10,000. The same goes for the easting. //--- GTIFKeySet(gtif, ProjCoordTransGeoKey, TYPE_SHORT, 1, (uint16)CT_TransverseMercator); // User-Defined GTIFKeySet(gtif, ProjectedCSTypeGeoKey, TYPE_SHORT, 1, KvUserDefined); // User-Defined GTIFKeySet(gtif, ProjectionGeoKey, TYPE_SHORT, 1, KvUserDefined); GTIFKeySet(gtif, ProjNatOriginLongGeoKey, TYPE_DOUBLE, 1, origin.lond()); GTIFKeySet(gtif, ProjNatOriginLatGeoKey, TYPE_DOUBLE, 1, origin.latd()); setFalseEastingNorthingFlag = true; double scale = ossimString(scaleFactor).toDouble(); GTIFKeySet(gtif, ProjScaleAtNatOriginGeoKey, TYPE_DOUBLE, 1, scale); } // End of TM if (setFalseEastingNorthingFlag == true) { GTIFKeySet(gtif, ProjFalseEastingGeoKey, TYPE_DOUBLE, 1, falseEasting); GTIFKeySet(gtif, ProjFalseNorthingGeoKey, TYPE_DOUBLE, 1, falseNorthing); } } //--- // Set the model type and units. //--- if (units == ossimGeoTiff::ANGULAR_DEGREE) { GTIFKeySet(gtif, GTModelTypeGeoKey, TYPE_SHORT, 1, ModelTypeGeographic); // Set the units key. GTIFKeySet(gtif, GeogAngularUnitsGeoKey, TYPE_SHORT, 1, units); } else { GTIFKeySet(gtif, GTModelTypeGeoKey, TYPE_SHORT, 1, ModelTypeProjected); // Set the units key. GTIFKeySet(gtif, ProjLinearUnitsGeoKey, TYPE_SHORT, 1, units); } // Set the ellipsoid major/minor axis. GTIFKeySet(gtif, GeogSemiMajorAxisGeoKey, TYPE_DOUBLE, 1, mapProj->getA()); GTIFKeySet(gtif, GeogSemiMinorAxisGeoKey, TYPE_DOUBLE, 1, mapProj->getB()); // Set the pixel type. if (projectionInfo->getPixelType() == OSSIM_PIXEL_IS_POINT) { // Tie point relative to center of pixel. GTIFKeySet(gtif, GTRasterTypeGeoKey, TYPE_SHORT, 1, RasterPixelIsPoint); } else { // Tie point relative to upper left corner of pixel GTIFKeySet(gtif, GTRasterTypeGeoKey, TYPE_SHORT, 1, RasterPixelIsArea); } GTIFKeySet(gtif, ProjOriginLongGeoKey, TYPE_DOUBLE, 1, origin.lon); GTIFKeySet(gtif, ProjOriginLatGeoKey, TYPE_DOUBLE, 1, origin.lat); GTIFWriteKeys(gtif); // Write out geotiff tags. // Need to decide whether to specify scale and offset tag pair, or the full 4x4 transform if // available, but not both: if (mapProj->isRotated()) { double transform[16]; const NEWMAT::Matrix& m = mapProj->getModelTransform().getData(); for (int i=0; i<16; ++i) transform[i] = m[i/4][i%4]; TIFFSetField(tifPtr, TIFFTAG_GEOTRANSMATRIX, 16, transform); } else { // Set the scale since not implicitely provided in a model transform: double pixScale[3] = {0.0, 0.0, 0.0}; switch (units) { case LINEAR_FOOT: pixScale[0] = ossim::mtrs2ft(projectionInfo->getMetersPerPixel().x); pixScale[1] = ossim::mtrs2ft(projectionInfo->getMetersPerPixel().y); break; case LINEAR_FOOT_US_SURVEY: pixScale[0] = ossim::mtrs2usft(projectionInfo->getMetersPerPixel().x); pixScale[1] = ossim::mtrs2usft(projectionInfo->getMetersPerPixel().y); falseEasting = ossim::mtrs2usft(falseEasting); falseNorthing = ossim::mtrs2usft(falseNorthing); break; case ANGULAR_DEGREE: pixScale[0] = projectionInfo->getDecimalDegreesPerPixel().x; pixScale[1] = projectionInfo->getDecimalDegreesPerPixel().y; break; case LINEAR_METER: default: pixScale[0] = projectionInfo->getMetersPerPixel().x; pixScale[1] = projectionInfo->getMetersPerPixel().y; break; } // End of "switch (units)" TIFFSetField(tifPtr, TIFFTAG_GEOPIXELSCALE, 3, pixScale); } // Set the tie point. double tiePoints[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; switch (units) { case LINEAR_FOOT: tiePoints[3] = ossim::mtrs2ft(projectionInfo->ulEastingNorthingPt().x); tiePoints[4] = ossim::mtrs2ft(projectionInfo->ulEastingNorthingPt().y); break; case LINEAR_FOOT_US_SURVEY: tiePoints[3] = ossim::mtrs2usft(projectionInfo->ulEastingNorthingPt().x); tiePoints[4] = ossim::mtrs2usft(projectionInfo->ulEastingNorthingPt().y); break; case ANGULAR_DEGREE: tiePoints[3] = projectionInfo->ulGroundPt().lond(); tiePoints[4] = projectionInfo->ulGroundPt().latd(); break; case LINEAR_METER: default: tiePoints[3] = projectionInfo->ulEastingNorthingPt().x; tiePoints[4] = projectionInfo->ulEastingNorthingPt().y; break; } // End of "switch (units)" TIFFSetField(tifPtr, TIFFTAG_GEOTIEPOINTS, 6, tiePoints); GTIFFree(gtif); return true; } bool ossimGeoTiff::writeJp2GeotiffBox(const ossimFilename &tmpFile, const ossimIrect &rect, const ossimProjection *proj, std::vector &buf, ossimPixelType pixelType) { //--- // Snip from The "GeoTIFF Box" Specification for JPEG 2000 Metadata: // This box contains a valid GeoTIFF image. The image is "degenerate", in // that it represents a very simple image with specific constraints: // . the image height and width are both 1 // . the datatype is 8-bit // . the colorspace is grayscale // . the (single) pixel must have a value of 0 for its (single) sample // // NOTE: It also states little endian but I think libtiff writes whatever // endianesss the host is. // // Also assuming class tiff for now. Not big tiff. //--- bool result = true; TIFF *tiff = XTIFFOpen(tmpFile.c_str(), "w"); if (tiff) { // Write the projection info out. ossimMapProjection *mapProj = PTR_CAST(ossimMapProjection, proj); if (mapProj) { ossimRefPtr projectionInfo = new ossimMapProjectionInfo(mapProj, ossimDrect(rect)); // Set the pixel type to point of area. projectionInfo->setPixelType(pixelType); // Write the geotiff keys. ossimGeoTiff::writeTags(tiff, projectionInfo, false); } // Basic tiff tags. TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, 1); TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, 1); TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 1); TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, 1); TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); // One pixel image: ossim_uint8 pixel = 0; TIFFWriteEncodedStrip(tiff, 0, (char *)&pixel, 1); TIFFWriteDirectory(tiff); XTIFFClose(tiff); // Get the size. Note 16 bytes added for the JP2 UUID: const std::vector::size_type UUID_SIZE = 16; const std::vector::size_type BOX_SIZE = UUID_SIZE + static_cast::size_type>(tmpFile.fileSize()); // Create the buffer. buf.resize(BOX_SIZE); if (BOX_SIZE == buf.size()) { const ossim_uint8 GEOTIFF_UUID[UUID_SIZE] = { 0xb1, 0x4b, 0xf8, 0xbd, 0x08, 0x3d, 0x4b, 0x43, 0xa5, 0xae, 0x8c, 0xd7, 0xd5, 0xa6, 0xce, 0x03}; // Copy the UUID. std::vector::size_type i; for (i = 0; i < UUID_SIZE; ++i) { buf[i] = GEOTIFF_UUID[i]; } // Copy the tiff. std::ifstream str; str.open(tmpFile.c_str(), ios::in | ios::binary); if (str.is_open()) { char ch; for (; i < BOX_SIZE; ++i) { str.get(ch); buf[i] = static_cast(ch); } } } else { result = false; } // Remove the temp file. tmpFile.remove(); } else { result = false; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimGeoTiff::writeJp2GeotiffBox ERROR:\n" << "Could not open " << tmpFile << std::endl; } } return result; } bool ossimGeoTiff::readTags(const ossimFilename &file, ossim_uint32 entryIdx) { bool result = false; TIFF *tiff = XTIFFOpen(file.c_str(), "r"); if (tiff) { result = readTags(tiff, entryIdx, true); } return result; } bool ossimGeoTiff::readTags(std::shared_ptr state, ossim_uint32 entryIdx) { std::lock_guard lock(theMutex); ossimString value; if (!state) return false; if (!state->checkBool(entryIdx, "is_geotiff")) { return false; } theLength = state->getImageLength(entryIdx); theWidth = state->getImageWidth(entryIdx); theScaleFactor = 0.0; theModelType = state->getModelType(entryIdx); theGcsCode = state->getGcsCode(entryIdx); thePcsCode = state->getPcsCode(entryIdx); theDatumCode = state->getDatumCode(entryIdx); theAngularUnits = state->getAngularUnits(entryIdx); theLinearUnitsCode = state->getLinearUnits(entryIdx); theRasterType = state->getRasterType(entryIdx); theGeoKeysPresentFlag = true; if (theAngularUnits == ANGULAR_DMS_HEMISPHERE || theAngularUnits == 9122) { //--- // Hack for bug, where the libgeotiff funtion GTIFGetDefn sets the angular units // incorrectly to ANGULAR_DMS_HEMISPHERE: if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << " WARNING ossimGeoTiff::addImageGeometry:" << "The angular units (key 2054) is set to ANGULAR_DMS_HEMISPHERE!" << "\nAssuming \"Angular_Degree\"..." << std::endl; } theAngularUnits = ANGULAR_DEGREE; } bool parsedCode = false; if (thePcsCode) { if (parsePcsCode()) { parsedCode = true; } } if (!parsedCode && theGcsCode) { parsedCode = parseGcsCode(); } //--- // ESH 2/2008 -- Handle geotiff's with state plane coordinate systems produced by ERDAS. // They use the citation filed to specify the geometry (complete HACK by Erdas) //--- if (!parsedCode) { ossimString gTCitation; if (state->getCitation(gTCitation, entryIdx)) { // Extract state plane string from the citation key ossimString projStrTemp = gTCitation.afterRegExp("Projection Name = "); ossimString projStr = projStrTemp.beforeRegExp("\n"); if (projStr.empty() == false) { ossimEpsgProjectionFactory *f = ossimEpsgProjectionFactory::instance(); ossimProjection *proj = f->createProjection(projStr); ossimMapProjection *map_proj = PTR_CAST(ossimMapProjection, proj); parseProjection(map_proj); } } // End of "if(GTIFKeyGet(gtif, GTCitationGeoKey..." } theOriginLon = ossim::nan(); theOriginLat = ossim::nan(); state->getValue(thePcsCitation, entryIdx, "pcs_citation"); if (state->getValue(value, entryIdx, "coord_trans_code")) { theCoorTransGeoCode = value.toInt32(); } if (state->getValue(value, entryIdx, ossimKeywordNames::STD_PARALLEL_1_KW)) { theStdPar1 = value.toDouble(); } if (state->getValue(value, entryIdx, ossimKeywordNames::STD_PARALLEL_2_KW)) { theStdPar2 = value.toDouble(); } if (state->getValue(value, entryIdx, "origin_longitude")) { theOriginLon = value.toDouble(); } else if (state->getValue(value, entryIdx, "center_longitude")) { theOriginLon = value.toDouble(); } else if (state->getValue(value, entryIdx, "false_origin_longitude")) { theOriginLon = value.toDouble(); } else if (state->getValue(value, entryIdx, "straight_vert_pole_lon")) { theOriginLon = value.toDouble(); } if (state->getValue(value, entryIdx, "origin_latitude")) { theOriginLat = value.toDouble(); } else if (state->getValue(value, entryIdx, "center_latitude")) { theOriginLat = value.toDouble(); } else if (state->getValue(value, entryIdx, "false_origin_latitude")) { theOriginLat = value.toDouble(); } if (state->getValue(value, entryIdx, "false_easting")) { theFalseEasting = value.toDouble(); } if (state->getValue(value, entryIdx, "false_northing")) { theFalseNorthing = value.toDouble(); } if (state->getValue(value, entryIdx, ossimKeywordNames::SCALE_FACTOR_KW)) { theScaleFactor = value.toDouble(); } theScale.clear(); if (state->getGeoPixelScale(theScale, entryIdx)) { if (theModelType == ModelTypeGeographic) { // The origin latitude must be computed so as to achieve the proper horizontal scaling: theOriginLat = ossim::acosd(theScale[1] / theScale[0]); } } theTiePoint.clear(); state->getGeoTiePoints(theTiePoint, entryIdx); theModelTransformation.clear(); state->getGeoTransMatrix(theModelTransformation, entryIdx); if (!theTiePoint.size()) initTiePointsFromImageModelTransform(); theDoubleParam.clear(); state->getGeoDoubleParams(theDoubleParam, entryIdx); state->getValue(theAsciiParam, entryIdx, "ascii_params"); // std::cout << "theErrorStatus: " << theErrorStatus // << "theScale: " << theScale.size() // << "theTiePoint: " << theTiePoint.size() // << "usingModelTransform:" << usingModelTransform() << "\n"; setOssimProjectionName(state, entryIdx); setOssimDatumName(state, entryIdx); if(theModelType == MODEL_TYPE_GEOGRAPHIC) { if (theAngularUnits == 0) { theAngularUnits = ANGULAR_DEGREE; } } return true; } bool ossimGeoTiff::readTags( TIFF *tiff, ossim_uint32 entryIdx, bool ownTiffPtrFlag) { std::lock_guard lock(theMutex); if (!tiff) { return false; } if (!TIFFSetDirectory(tiff, (ossim_uint16)entryIdx)) { return false; } GTIF *gtif = GTIFNew(tiff); if (!gtif) { return false; } if (theTiffPtr) { XTIFFClose(theTiffPtr); } theTiffPtr = tiff; if (thePrivateDefinitions->m_defs) { delete thePrivateDefinitions->m_defs; ; } thePrivateDefinitions->m_defs = new GTIFDefn; GTIFGetDefn(gtif, thePrivateDefinitions->m_defs); ossim_uint32 idx = 0; theGeoKeysPresentFlag = true; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeoTiff::readTags: Raw Geotiff Tags are\n"; GTIFPrint(gtif, 0, 0); } if (TIFFGetField(theTiffPtr, TIFFTAG_IMAGELENGTH, &theLength)) { } if (TIFFGetField(theTiffPtr, TIFFTAG_IMAGEWIDTH, &theWidth)) { } theScaleFactor = 0.0; theModelType = thePrivateDefinitions->m_defs->Model; theGcsCode = thePrivateDefinitions->m_defs->GCS; thePcsCode = thePrivateDefinitions->m_defs->PCS; theDatumCode = thePrivateDefinitions->m_defs->Datum; theAngularUnits = thePrivateDefinitions->m_defs->UOMAngle; theLinearUnitsCode = thePrivateDefinitions->m_defs->UOMLength; if (theAngularUnits == ANGULAR_DMS_HEMISPHERE || theAngularUnits == 9122) { //--- // Hack for bug, where the libgeotiff funtion GTIFGetDefn sets the angular units // incorrectly to ANGULAR_DMS_HEMISPHERE: if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << " WARNING ossimGeoTiff::addImageGeometry:" << "The angular units (key 2054) is set to ANGULAR_DMS_HEMISPHERE!" << "\nAssuming \"Angular_Degree\"..." << std::endl; } theAngularUnits = ANGULAR_DEGREE; } #if 0 ossim_uint16 modelType; if(GTIFKeyGet(gtif, GTModelTypeGeoKey, &modelType, 0, 1)) { theModelType = (ModelType)modelType; } #endif if (GTIFKeyGet(gtif, GTRasterTypeGeoKey, &theRasterType, 0, 1)) { } #if 0 if(GTIFKeyGet(gtif, GeographicTypeGeoKey, &theGcsCode, 0, 1)) { } if(GTIFKeyGet(gtif, GeogGeodeticDatumGeoKey, &theDatumCode, 0, 1)) { } if(GTIFKeyGet(gtif, GeogAngularUnitsGeoKey, &theAngularUnits, 0, 1)) { } #endif if (GTIFKeyGet(gtif, ProjectedCSTypeGeoKey, &thePcsCode, 0, 1)) parsePcsCode(); //--- // ESH 2/2008 -- Handle geotiff's with state plane coordinate systems produced by ERDAS. // They use the citation filed to specify the geometry (complete HACK by Erdas) //--- else { const int CITATION_STRING_SIZE = 512; char citationStr[CITATION_STRING_SIZE]; if (GTIFKeyGet(gtif, GTCitationGeoKey, &citationStr, 0, CITATION_STRING_SIZE)) { ossimString gTCitation = citationStr; // key 1026 // Extract state plane string from the citation key ossimString projStrTemp = gTCitation.afterRegExp("Projection Name = "); ossimString projStr = projStrTemp.beforeRegExp("\n"); if (projStr.empty() == false) { ossimEpsgProjectionFactory *f = ossimEpsgProjectionFactory::instance(); ossimProjection *proj = f->createProjection(projStr); ossimMapProjection *map_proj = PTR_CAST(ossimMapProjection, proj); parseProjection(map_proj); } } // End of "if(GTIFKeyGet(gtif, GTCitationGeoKey..." } char *buf = 0; theOriginLon = ossim::nan(); theOriginLat = ossim::nan(); if (GTIFKeyGet(gtif, PCSCitationGeoKey, &buf, 0, 1)) { thePcsCitation = ossimString(buf); } GTIFKeyGet(gtif, ProjCoordTransGeoKey, &theCoorTransGeoCode, 0, 1); for (idx = 0; idx < (ossim_uint32)thePrivateDefinitions->m_defs->nParms; ++idx) { switch (thePrivateDefinitions->m_defs->ProjParmId[idx]) { case ProjStdParallel1GeoKey: { theStdPar1 = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjStdParallel2GeoKey: { theStdPar2 = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjOriginLongGeoKey: { theOriginLon = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjOriginLatGeoKey: { theOriginLat = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjFalseEastingGeoKey: { theFalseEasting = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjFalseNorthingGeoKey: { theFalseNorthing = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjCenterLongGeoKey: { theOriginLon = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjCenterLatGeoKey: { theOriginLat = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjFalseOriginLatGeoKey: { theOriginLat = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjFalseOriginLongGeoKey: case ProjStraightVertPoleLongGeoKey: { theOriginLon = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } case ProjScaleAtNatOriginGeoKey: { theScaleFactor = thePrivateDefinitions->m_defs->ProjParm[idx]; break; } } } #if 0 if(GTIFKeyGet(gtif, ProjStdParallel1GeoKey, &theStdPar1, 0, 1)) { } if(GTIFKeyGet(gtif, ProjStdParallel2GeoKey, &theStdPar2, 0, 1)) { } if(GTIFKeyGet(gtif, ProjNatOriginLongGeoKey, &tempDouble, 0, 1)) { theOriginLon = tempDouble; } else if(GTIFKeyGet(gtif, ProjOriginLongGeoKey, &tempDouble, 0, 1)) { theOriginLon = tempDouble; } if(GTIFKeyGet(gtif, ProjNatOriginLatGeoKey, &tempDouble, 0, 1)) { theOriginLat = tempDouble; } else if(GTIFKeyGet(gtif, ProjOriginLatGeoKey, &tempDouble, 0, 1)) { theOriginLat = tempDouble; } if(GTIFKeyGet(gtif, ProjFalseEastingGeoKey, &theFalseEasting, 0, 1)) { } if(GTIFKeyGet(gtif, ProjFalseNorthingGeoKey, &theFalseNorthing, 0, 1)) { } if(GTIFKeyGet(gtif, ProjCenterLongGeoKey, &theCenterLon, 0, 1)) { } if(GTIFKeyGet(gtif, ProjCenterLatGeoKey, &theCenterLat, 0, 1)) { } if(GTIFKeyGet(gtif, ProjScaleAtNatOriginGeoKey, &theScaleFactor, 0, 1)) { } #endif theScale.clear(); ossim_uint16 pixScaleSize = 0; double *pixScale = 0; if (TIFFGetField(theTiffPtr, TIFFTAG_GEOPIXELSCALE, &pixScaleSize, &pixScale)) { theScale.insert(theScale.begin(), pixScale, pixScale + pixScaleSize); if (theModelType == ModelTypeGeographic) { // The origin latitude must be computed so as to achieve the proper horizontal scaling: theOriginLat = ossim::acosd(theScale[1] / theScale[0]); } } theTiePoint.clear(); ossim_uint16 tiePointSize = 0; double *tiepoints = 0; if (TIFFGetField(theTiffPtr, TIFFTAG_GEOTIEPOINTS, &tiePointSize, &tiepoints)) { theTiePoint.insert(theTiePoint.begin(), tiepoints, tiepoints + tiePointSize); // ESH 05/2009 -- If the image is in a projected coordinate system, the // tiepoints will be projected coordinates not lat/lon. Let's avoid setting // the origin lon/lat to projected x/y. Fix for ticket #711. //if ( theModelType == ModelTypeGeographic ) //{ // if(ossim::isnan(theOriginLon) && // (pixScaleSize > 1) && // (tiePointSize > 3)) // { // theOriginLon = tiepoints[3] - tiepoints[0] * pixScale[0]; // } // // if(ossim::isnan(theOriginLat) && (pixScaleSize > 1) && (tiePointSize > 3)) // { // theOriginLat = tiepoints[4] + tiepoints[1] * fabs(pixScale[1]); // } //} } theModelTransformation.clear(); ossim_uint16 transSize = 0; double *trans = 0; if (TIFFGetField(theTiffPtr, TIFFTAG_GEOTRANSMATRIX, &transSize, &trans)) { theModelTransformation.insert(theModelTransformation.begin(), trans, trans + transSize); } if (!theTiePoint.size()) initTiePointsFromImageModelTransform(); ossim_uint16 doubleParamSize = 0; double *tempDoubleParam = 0; theDoubleParam.clear(); if (TIFFGetField(theTiffPtr, TIFFTAG_GEODOUBLEPARAMS, &doubleParamSize, &tempDoubleParam)) { theDoubleParam.insert(theDoubleParam.begin(), tempDoubleParam, tempDoubleParam + doubleParamSize); } char *tempAsciiParam = 0; theAsciiParam = ""; // Note: this tag does not have the setting set to return the size // so this call is only a 3 argument call without a size parameter if (TIFFGetField(theTiffPtr, TIFFTAG_GEOASCIIPARAMS, &tempAsciiParam)) { theAsciiParam = tempAsciiParam; } if (theGeoKeysPresentFlag) { setOssimProjectionName(); // Initialize the ossim projection name. setOssimDatumName(); // Initialize the ossim datum name. } // commenting this out. Frank mentioned the GTIFFGetDefn which in geo_normalize // this should be all we need. // #if 0 /* ESH 05/2009: Replacing badly broken code for making use of TIFFTAG_GEODOUBLEPARAMS. Read the geokey directory tag in order to see how the TIFFTAG_GEODOUBLEPARAMS are defined. For structure of geokey directory, see: http://www.remotesensing.org/geotiff/spec/geotiff2.4.html */ ossim_uint16 gkdParamSize = 0; ossim_uint16* gkdParams = 0; if(TIFFGetField(theTiffPtr, TIFFTAG_GEOKEYDIRECTORY, &gkdParamSize, &gkdParams)) { ossim_uint16 numKeys = gkdParams ? gkdParams[3] : 0; ossim_uint16 key = 0; for( key=0; key= 0 && ind < doubleParamSize ) { double dval = theDoubleParam[ind]; switch( gkdParams[loc] ) { case ProjStdParallel1GeoKey: theStdPar1 = dval; break; case ProjStdParallel2GeoKey: theStdPar2 = dval; break; case ProjNatOriginLongGeoKey: theOriginLon = dval; break; /* case ProjOriginLongGeoKey: theOriginLon = dval; break; (alias) */ case ProjNatOriginLatGeoKey: theOriginLat = dval; break; /* case ProjOriginLatGeoKey: theOriginLat = dval; break; (alias) */ case ProjFalseEastingGeoKey: theFalseEasting = dval; break; case ProjFalseNorthingGeoKey: theFalseNorthing = dval; break; case ProjCenterLongGeoKey: theCenterLon = dval; break; case ProjCenterLatGeoKey: theCenterLat = dval; break; case ProjScaleAtNatOriginGeoKey: theScaleFactor = dval; break; default: if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeoTiff::readTags: Unrecognized geokey directory entry." << "\ngeokey directory index = " << loc << "\ngeokey = " << gkdParams[loc] << "\ndouble array index = " << ind << "\ndval = " << dval << std::endl; } break; } } } } #endif GTIFFree(gtif); if (ownTiffPtrFlag == false) { //--- // Zero out the pointer so the destructor doesn't close it on some // external code. //--- theTiffPtr = 0; } return true; } bool ossimGeoTiff::addImageGeometry(ossimKeywordlist &kwl, const char *prefix) const { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeoTiff::addImageGeometry: Entered............." << std::endl; } // NOT SURE THIS IS A GOOD IDEA HERE. KEPT FOR LEGACY SAKE. (OLK 5/10) // //--- // Sanity check... // NOTE: It takes six doubles to make one tie point ie: // x,y,z,longitude,latitude,height or x,y,z,easting,northing,height //--- if (theErrorStatus || (!usingModelTransform() && ((theScale.size() < 2) && // no scale (theTiePoint.size() < 24)))) //need at least 3 ties if no scale. { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeoTiff::addImageGeometry: Failed sanity check " << std::endl; if (theErrorStatus) { ossimNotify(ossimNotifyLevel_DEBUG) << "for error status" << std::endl; } else if (theTiePoint.size() < 5) { ossimNotify(ossimNotifyLevel_DEBUG) << "for tie points, size = " << theTiePoint.size() << std::endl; } else { ossimNotify(ossimNotifyLevel_DEBUG) << "for scale" << std::endl; } } return false; } double x_tie_point = theTiePoint[3]; double y_tie_point = theTiePoint[4]; ossim_uint32 tieCount = (ossim_uint32)theTiePoint.size() / 6; if ((theScale.size() == 3) && (tieCount == 1)) { //--- // Shift the tie point to the (0, 0) position if it's not already. // // Note: // Some geotiff writers like ERDAS IMAGINE set the "GTRasterTypeGeoKey" // key to RasterPixelIsArea, then set the tie point to (0.5, 0.5). // This really means "RasterPixelIsPoint" with a tie point of (0.0, 0.0). // Anyway we will check for this blunder and attempt to do the right // thing... //--- x_tie_point = theTiePoint[3] - theTiePoint[0] * theScale[0]; y_tie_point = theTiePoint[4] + theTiePoint[1] * theScale[1]; } else if (tieCount > 1) { //--- // Should we check the model type??? (drb) // if (theModelType == ModelTypeGeographic) //--- if (tieCount >= 4) { ossimTieGptSet tieSet; getTieSet(tieSet); if (tieCount > 4) { // create a cubic polynomial model //ossimRefPtr proj = new ossimPolynomProjection; //proj->setupOptimizer("1 x y x2 xy y2 x3 y3 xy2 x2y z xz yz"); ossimRefPtr proj = new ossimBilinearProjection; proj->optimizeFit(tieSet); proj->saveState(kwl, prefix); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeoTiff::addImageGeometry: " << "Creating a Cubic polynomial projection" << std::endl; } return true; } else if (tieCount == 4) { // create a bilinear model // Should we check the model type (drb) // if (theModelType == ModelTypeGeographic) ossimRefPtr proj = new ossimBilinearProjection; proj->optimizeFit(tieSet); proj->saveState(kwl, prefix); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeoTiff::addImageGeometry: " << "Creating a bilinear projection" << std::endl; } return true; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimGeoTiff::addImageGeometry: " << "Not enough tie points to create a interpolation model" << std::endl; } return false; } } if ((theRasterType == PIXEL_IS_AREA)) { // Since the internal pixel representation is "point", shift the // tie point to be relative to the center of the pixel. if (theScale.size() > 1) { x_tie_point += (theScale[0]) / 2.0; y_tie_point -= (theScale[1]) / 2.0; } } if (thePcsCode && (thePcsCode != USER_DEFINED)) { ossimString epsg_spec("EPSG:"); epsg_spec += ossimString::toString(thePcsCode); ossimRefPtr proj = ossimEpsgProjectionFactory::instance()->createProjection(epsg_spec); if (proj.valid()) { proj->saveState(kwl, prefix); } // Should be some else "WARNING" here maybe. (drb) } else if (getOssimProjectionName() == "unknown") { //--- // Get the projection type. If unknown no point going on, so get out. //--- return false; } else { // No PCS code but we do have a projection name // Add these for all projections. kwl.add(prefix, ossimKeywordNames::TYPE_KW, getOssimProjectionName()); kwl.add(prefix, ossimKeywordNames::DATUM_KW, getOssimDatumName()); } // Now set the image-specific projection info (scale and image tiepoint): if (theModelType == MODEL_TYPE_GEOGRAPHIC) { if (theAngularUnits != ANGULAR_DEGREE) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimGeoTiff::addImageGeometry:" << "\nNot coded yet for angular unit type: " << theAngularUnits << endl; return false; } //--- // Tiepoint // Have data with tie points -180.001389 so use ossimGpt::wrap() to handle: //--- ossimGpt tieGpt(y_tie_point, x_tie_point, 0.0); tieGpt.wrap(); ossimDpt tiepoint(tieGpt); kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, tiepoint.toString(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, "degrees", true); // scale or gsd if (theScale.size() > 1) { ossimDpt scale(theScale[0], theScale[1]); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW, scale.toString(), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW, "degrees", true); // origin if (ossim::isnan(theOriginLat)) { //--- // Put the origin lat at the center of the image so the meters per // pixel is somewhat real. //--- double centerY = theLength / 2.0; theOriginLat = tieGpt.lat - theScale[1] * centerY; } } if (ossim::isnan(theOriginLon)) theOriginLon = x_tie_point; if (ossim::isnan(theOriginLat)) theOriginLat = y_tie_point; kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, theOriginLat, true); kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, theOriginLon, true); } else // Projected { // Tiepoint ossimDpt tiepoint(convert2meters(x_tie_point), convert2meters(y_tie_point)); kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, tiepoint.toString(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, "meters", true); // scale or gsd if (theScale.size() > 1) { ossimDpt scale(convert2meters(theScale[0]), convert2meters(theScale[1])); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW, scale.toString(), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW, "meters", true); } // origin if (!ossim::isnan(theOriginLat)) kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, theOriginLat); if (!ossim::isnan(theOriginLon)) kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, theOriginLon); // std paralles for conical projections kwl.add(prefix, ossimKeywordNames::STD_PARALLEL_1_KW, theStdPar1); kwl.add(prefix, ossimKeywordNames::STD_PARALLEL_2_KW, theStdPar2); // false easting and northing. kwl.add(prefix, ossimKeywordNames::FALSE_EASTING_KW, convert2meters(theFalseEasting)); kwl.add(prefix, ossimKeywordNames::FALSE_NORTHING_KW, convert2meters(theFalseNorthing)); // Based on projection type, override/add the appropriate info. if (getOssimProjectionName() == "ossimUtmProjection") { // Check the zone before adding... if (theZone > 0 && theZone < 61) { kwl.add(prefix, ossimKeywordNames::ZONE_KW, theZone); } else { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimGeoTiff::addImageGeometry: " << "UTM zone " << theZone << " out of range!\n" << "Valid range: 1 to 60" << endl; return false; } // Check the hemisphere before adding. if (theHemisphere == "N" || theHemisphere == "S") { kwl.add(prefix, ossimKeywordNames::HEMISPHERE_KW, theHemisphere); } else { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimGeoTiff::addImageGeometry: " << "UTM hemisphere " << theHemisphere << " is invalid!\n" << "Valid hemisphere: N or S" << std::endl; return false; } //--- // Must set the central meridian even though the zone should do it. // (in decimal degrees) //--- double central_meridian = (6.0 * abs(theZone)) - 183.0; kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, central_meridian, true); kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, 0.0, true); } // End of "if (UTM)" else if (getOssimProjectionName() == "ossimTransMercatorProjection") kwl.add(prefix, ossimKeywordNames::SCALE_FACTOR_KW, theScaleFactor, true); } // end of projected CS //--- // Get the model transformation info if it's present. //--- if (usingModelTransform()) { std::vector v = getModelTransformation(); std::ostringstream out; out << std::setprecision(15); // To avoid truncating. ossim_uint32 idx = 0; for (idx = 0; idx < 16; ++idx) { out << v[idx] << " "; } kwl.add(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_MATRIX_KW, out.str().c_str(), true); ossimUnitType modelTransformUnitType = OSSIM_UNIT_UNKNOWN; if (theModelType == ModelTypeGeographic) { switch (theAngularUnits) { case ANGULAR_DEGREE: modelTransformUnitType = OSSIM_DEGREES; break; case ANGULAR_ARC_MINUTE: modelTransformUnitType = OSSIM_MINUTES; break; case ANGULAR_ARC_SECOND: modelTransformUnitType = OSSIM_SECONDS; break; default: return false; } } else if (theModelType == ModelTypeProjected) { switch (theLinearUnitsCode) { case LINEAR_METER: modelTransformUnitType = OSSIM_METERS; break; default: return false; } } kwl.add(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_UNIT_KW, ossimUnitTypeLut::instance()->getEntryString(modelTransformUnitType), true); } if (theScaleFactor > 0.0) { kwl.add(prefix, ossimKeywordNames::SCALE_FACTOR_KW, theScaleFactor, true); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimGeoTiff::addImageGeometry: Keyword list dump:\n" << kwl << std::endl; } return true; } double ossimGeoTiff::convert2meters(double d) const { switch (theLinearUnitsCode) { case LINEAR_METER: return d; case LINEAR_FOOT: return ossim::ft2mtrs(d); case LINEAR_FOOT_US_SURVEY: return ossim::usft2mtrs(d); default: if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimGeoTiff::convert2meters: " << "Linear units code was undefined!\n" << "No conversion was performed." << std::endl; } break; } return d; } ossimString ossimGeoTiff::getOssimProjectionName() const { return theProjectionName; } void ossimGeoTiff::setOssimProjectionName() { //--- // The "parsePcsCode" method can also set the projection name. So check // it prior to looking in the lookup table. //--- if (theProjectionName == "unknown") { ossimString name = COORD_TRANS_LUT.getEntryString(theCoorTransGeoCode); if (name.size()) { theProjectionName = name; } } // If still unknown check for the model type. if (theProjectionName == "unknown") { if (theModelType == ModelTypeGeographic) { theProjectionName = "ossimEquDistCylProjection"; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimGeoTiff::setOssimProjectionName: " << "theProjectionName: " << theProjectionName << std::endl; } } void ossimGeoTiff::setOssimProjectionName(std::shared_ptr state, ossim_int32 entryIdx) { ossimString value; //--- // The "parsePcsCode" method can also set the projection name. So check // it prior to looking in the lookup table. //--- if (theProjectionName == "unknown") { if (state->getValue(value, entryIdx, "coord_trans_code")) { ossimString name = COORD_TRANS_LUT.getEntryString(value.toInt32()); if (name.size()) { theProjectionName = name; } } } // If still unknown check for the model type. if (theProjectionName == "unknown") { if (theModelType == ModelTypeGeographic) { theProjectionName = "ossimEquDistCylProjection"; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimGeoTiff::setOssimProjectionName: " << "theProjectionName: " << theProjectionName << std::endl; } } ossimString ossimGeoTiff::getOssimDatumName() const { return theDatumName; } void ossimGeoTiff::setOssimDatumName() { //--- // The "parsePcsCode" method can also set the datum name. So check // it prior to trying to assign. //--- if (theDatumName == "unknown") { ossimString name = DATUM_LUT.getEntryString(theDatumCode); if (!name.empty()) { theDatumName = name; } else { // Try the GCS code. name = DATUM_LUT.getEntryString(theGcsCode); if (name.size()) { theDatumName = name; } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimGeoTiff::setOssimDatumName: " << "theDatumName: " << theDatumName << std::endl; } } void ossimGeoTiff::setOssimDatumName(std::shared_ptr state, ossim_int32 entryIdx) { ossimString value; //--- // The "parsePcsCode" method can also set the datum name. So check // it prior to trying to assign. //--- if (theDatumName == "unknown") { if (state->getValue(value, entryIdx, "datum_code")) { ossimString name = DATUM_LUT.getEntryString(value.toInt32()); if (!name.empty()) { theDatumName = name; } else { // Try the GCS code. if (state->getValue(value, entryIdx, "gcs_code")) { name = DATUM_LUT.getEntryString(value.toInt32()); if (name.size()) { theDatumName = name; } } } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimGeoTiff::setOssimDatumName: " << "theDatumName: " << theDatumName << std::endl; } } //************************************************************************************************* //! Initializes data members given a projection code. Returns TRUE if valid PCS code specified. //************************************************************************************************* bool ossimGeoTiff::parsePcsCode() { bool result = true; // key 3072 Section 6.3.3.1 codes ossimString epsg_spec(ossimString("EPSG:") + ossimString::toString(thePcsCode)); ossimRefPtr proj = ossimEpsgProjectionFactory::instance()->createProjection(epsg_spec); ossimMapProjection *map_proj = PTR_CAST(ossimMapProjection, proj.get()); if (!parseProjection(map_proj)) { result = false; } return (thePcsCode != 0); } //************************************************************************************************* //! Initializes data members given a projection code. Returns TRUE if valid PCS code specified. //************************************************************************************************* bool ossimGeoTiff::parseGcsCode() { bool result = true; // right now just support WGS84 GCS if (theGcsCode == 4326) { // key 3072 Section 6.3.3.1 codes ossimString epsg_spec(ossimString("EPSG:") + ossimString::toString(theGcsCode)); ossimRefPtr proj = ossimEpsgProjectionFactory::instance()->createProjection(epsg_spec); ossimMapProjection *map_proj = PTR_CAST(ossimMapProjection, proj.get()); if (!parseProjection(map_proj)) { result = false; } } return result; } //************************************************************************************************* //! Initializes data members given a projection. //************************************************************************************************* bool ossimGeoTiff::parseProjection(ossimMapProjection *map_proj) { if (map_proj == NULL) return false; // Initialize parameters from base-class ossimMapProjection: if (map_proj->isGeographic()) { theModelType = ModelTypeGeographic; theAngularUnits = ANGULAR_DEGREE; theLinearUnitsCode = ANGULAR_DEGREE; } else { theModelType = ModelTypeProjected; theAngularUnits = ANGULAR_DEGREE; theLinearUnitsCode = LINEAR_METER; } theProjectionName = map_proj->getProjectionName(); theFalseEasting = map_proj->getFalseEasting(); theFalseNorthing = map_proj->getFalseNorthing(); theStdPar1 = map_proj->getStandardParallel1(); theStdPar2 = map_proj->getStandardParallel2(); thePcsCode = map_proj->getPcsCode(); // GCS code only defined for geographic projections and is basically the same as PCS in OSSIM: theGcsCode = 0; ossimGpt origin(map_proj->origin()); theOriginLat = origin.lat; theOriginLon = origin.lon; const ossimDatum *datum = map_proj->getDatum(); if (datum) { theDatumName = datum->name(); theDatumCode = datum->epsgCode(); } // Now intercept a select few that have additional parameters specific to their derived type: if (map_proj->getProjectionName() == "ossimEquDistCylProjection") { theGcsCode = map_proj->getPcsCode(); } else if (theProjectionName == "ossimUtmProjection") { ossimUtmProjection *utm_proj = PTR_CAST(ossimUtmProjection, map_proj); theHemisphere = utm_proj->getHemisphere(); theScaleFactor = 0.9996; // UTM fixed theZone = utm_proj->getZone(); } else if (theProjectionName == "ossimTransMercatorProjection") { ossimTransMercatorProjection *tm_proj = PTR_CAST(ossimTransMercatorProjection, map_proj); theScaleFactor = tm_proj->getScaleFactor(); } else if (theProjectionName == "ossimBngProjection") { // ### LEGACY HACK ### theDatumName = "OGB-M"; theFalseEasting = 400000.0; theFalseNorthing = -100000.0; theScaleFactor = .9996012717; theOriginLat = 49.0; theOriginLon = -2.0; theHemisphere = "N"; } return true; } int ossimGeoTiff::mapZone() const { return theZone; } void ossimGeoTiff::getScale(std::vector &scale) const { scale = theScale; } void ossimGeoTiff::getTiePoint(std::vector &tie_point) const { tie_point = theTiePoint; } void ossimGeoTiff::getModelTransformation(std::vector &transform) const { transform = theModelTransformation; } const std::vector &ossimGeoTiff::getScale() const { return theScale; } ossimPixelType ossimGeoTiff::getRasterType() const { if (theRasterType == PIXEL_IS_AREA) return OSSIM_PIXEL_IS_AREA; return OSSIM_PIXEL_IS_POINT; } const std::vector &ossimGeoTiff::getTiePoint() const { return theTiePoint; } const std::vector &ossimGeoTiff::getModelTransformation() const { return theModelTransformation; } int ossimGeoTiff::getWidth() const { return theWidth; } int ossimGeoTiff::getLength() const { return theLength; } std::ostream &ossimGeoTiff::print(std::ostream &out) const { // Capture stream flags. std::ios_base::fmtflags f = out.flags(); out << setiosflags(ios::fixed) << setprecision(15) << "ossimGeoTiff::print" << std::endl; if (theScale.size()) { std::vector::const_iterator i = theScale.begin(); ossim_uint32 index = 0; while (i < theScale.end()) { out << "theScale[" << index << "]: " << (*i) << std::endl; ++index; ++i; } } else { out << "theScale is empty..." << endl; } if (theTiePoint.size()) { std::vector::const_iterator i = theTiePoint.begin(); ossim_uint32 index = 0; while (i < theTiePoint.end()) { out << "theTiePoint[" << index << "]: " << (*i) << std::endl; ++index; ++i; } } else { out << "theTiePoint is empty..." << endl; } if (usingModelTransform()) { ossim_uint32 i = 0; out << "theModelTransformation: "< maxX) maxX = theTiePoint[tieIndex]; if (theTiePoint[tieIndex + 1] < minY) minY = theTiePoint[tieIndex + 1]; if (theTiePoint[tieIndex + 1] > maxY) maxY = theTiePoint[tieIndex + 1]; tieIndex += 6; } if ((minX == 1) && (maxX == theWidth) && (minY == 1) && (maxY == theLength)) { result = true; } #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeoTiff::hasOneBasedTiePoints DEBUG:" << "\nminX: " << minX << "\nmaxX: " << maxX << "\nminY: " << minY << "\nmaxY: " << maxY << "\ntheWidth: " << theWidth << "\ntheLength: " << theLength << "\none based: " << (result?"true":"false") << std::endl; } #endif return result; } bool ossimGeoTiff::initTiePointsFromImageModelTransform() { if (!usingModelTransform()) return false; theTiePoint.push_back(0.0); theTiePoint.push_back(0.0); theTiePoint.push_back(0.0); theTiePoint.push_back(theModelTransformation[3]); theTiePoint.push_back(theModelTransformation[7]); theTiePoint.push_back(0.0); return true; } //************************************************************************************************* // ArcMAP 9.2 bug workaround. // ESH 05/2008 -- ArcMap 9.2 compatibility hack // If the PCS code is for a HARN state plane and the implied pcs // code's units is feet (us or intl), we find the equivalent code // for units of meters. We're doing this because ArcMap (9.2 and // less) doesn't understand the non-meters HARN codes. However, // the units are left unchanged in this process, so the units can // be different than the user-specified pcs code. ArcMap 9.2 // seems to understand the mixed definition just fine. // OLK 04/2010 -- Converted to vector scheme after refactoring EPSG factory. //************************************************************************************************* ossim_uint16 getMetersEquivalentHarnCode(ossim_uint16 feet_harn_code) { static const ossim_uint16 harn_feet[] = { 2867, 2868, 2869, 2870, 2871, 2872, 2873, 2874, 2875, 2876, 2877, 2878, 2879, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2887, 2888, 2891, 2892, 2893, 2894, 2895, 2896, 2897, 2898, 2899, 2900, 2901, 2902, 2903, 2904, 2905, 2906, 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2926, 2927, 2928, 2929, 2930, 2967, 2968}; static const ossim_uint16 harn_meters[] = { 2761, 2762, 2763, 2766, 2767, 2768, 2769, 2770, 2771, 2772, 2773, 2774, 2775, 2776, 2777, 2778, 2779, 2780, 2781, 2787, 2788, 2789, 2798, 2799, 2804, 2805, 2806, 2807, 2808, 2809, 2813, 2814, 2818, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2832, 2833, 2836, 2837, 2838, 2839, 2843, 2844, 2845, 2846, 2847, 2848, 2849, 2850, 2851, 2853, 2854, 2855, 2856, 2859, 2860, 2861, 2792, 2793}; ossim_uint16 result = 0; int index = 0; while ((result == 0) && (index < 64)) { if (harn_feet[index] == feet_harn_code) result = harn_meters[index]; ++index; } return result; }; ossim-Miami-2.9.1/src/support_data/ossimGmlSupportData.cpp000066400000000000000000001371641352751253100237100ustar00rootroot00000000000000//--- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: GML support data object. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimGmlSupportData:debug"); #define UNKNOWN_PCSCODE 32767 ossimGmlSupportData::ossimGmlSupportData() : m_xmlDocument(0), // m_use_gmljp2_version2(true), m_pcsCodeMap(UNKNOWN_PCSCODE), m_pcsCodeGeo(UNKNOWN_PCSCODE), m_srsNameStringMap("http://www.opengis.net/def/crs/EPSG/0/32767"), m_srsNameStringGeo("http://www.opengis.net/def/crs/EPSG/0/32767"), m_srsDimensionString("2"), m_axisLabelsStringMap("X Y"), m_axisLabelsStringGeo("Lat Long"), m_uomLabelsStringMap("m m"), m_uomLabelsStringGeo("deg deg") { } ossimGmlSupportData::~ossimGmlSupportData() { } bool ossimGmlSupportData::initialize( std::istream& in ) { bool status = false; if ( in.good() ) { m_xmlDocument = new ossimXmlDocument(); m_xmlDocument->read( in ); status = true; } else { m_xmlDocument = 0; } return status; } bool ossimGmlSupportData::initialize( const ossimImageGeometry* geom, const ossimIrect& rect ) { static const char MODULE[] = "ossimGmlSupportData::initialize(geom)"; bool status = false; if ( geom ) { // ossim_uint32 code = UNKNOWN_PCSCODE; // unknown code ossimRefPtr mapProj = geom->getAsMapProjection(); if ( mapProj.valid() ) { // Get the PCS code: m_pcsCodeMap = mapProj->getPcsCode(); m_pcsCodeGeo = mapProj->getPcsCode(); // Create an SRS Name for the map projection std::ostringstream os; os << "http://www.opengis.net/def/crs/EPSG/0/" << m_pcsCodeMap; m_srsNameStringMap = os.str(); // Create an SRS Name for the projection datum std::ostringstream os2; os2 << "http://www.opengis.net/def/crs/EPSG/0/" << m_pcsCodeGeo; m_srsNameStringGeo = os2.str(); m_xmlDocument = new ossimXmlDocument(ossimFilename::NIL); // if ( m_use_gmljp2_version2 == true ) // { ossimRefPtr rootNode = getGmljp2V2RootNode(); m_xmlDocument->initRoot( rootNode ); status = configureGmljp2V2( rootNode, geom, rect ); // } #if 0 else { ossimRefPtr rootNode = getGmljp2V1RootNode(); m_xmlDocument->initRoot( rootNode ); status = configureGmljp2V1( rootNode, geom, rect ); } #endif // cout << "gmljp2Node: " << *(gmljp2Node.get()) << endl; // cout << "xmlDoc: " << *(m_xmlDocument.get()) << endl; } } if ( status == false ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG Entered...\n"; } return status; } // End: ossimGmlSupportData::initialize( geom, mapProj ) #if 0 bool ossimGmlSupportData::configureGmljp2V1( ossimRefPtr node0, const ossimImageGeometry* geom ) { bool success = true; const ossimString BLANK = ""; ossimString gridHighString; ossimString gridLowString; getLimits( geom, gridHighString, gridLowString ); configureBounds( node0, geom ); ossimString path = "rectifiedGridDomain"; ossimRefPtr node2 = node0->addChildNode( path, BLANK ); path = "RectifiedGrid"; ossimRefPtr node2a = node2->addChildNode( path, BLANK ); ossimRefPtr attr1 = new ossimXmlAttribute(); ossimString name = "dimension"; ossimString value = "2"; attr1->setNameValue( name, value ); node2a->addAttribute( attr1 ); path = "limit"; ossimRefPtr node2a1 = node2a->addChildNode( path, BLANK ); path = "GridEnvelope"; ossimRefPtr node2a1a = node2a1->addChildNode( path, BLANK ); path = "low"; ossimRefPtr node2a1a1 = node2a1a->addChildNode( path, gridLowString ); path = "high"; ossimRefPtr node2a1a2 = node2a1a->addChildNode( path, gridHighString ); return success; } #endif bool ossimGmlSupportData::configureGmljp2V2( ossimRefPtr node0, const ossimImageGeometry* geom, const ossimIrect& rect ) { bool success = false; ossimRefPtr mapProj = geom->getAsMapProjection(); if ( mapProj.valid() ) { bool isGeographic = mapProj->isGeographic(); const ossimString BLANK = ""; ossimRefPtr attr(0); ossimString name; ossimString value; ossimString gridHighString; ossimString gridLowString; getLimits( rect, gridHighString, gridLowString ); configureBounds( node0, geom, rect ); ossimString path = "domainSet"; ossimRefPtr node2 = node0->addChildNode( path, BLANK ); path = "rangeSet"; ossimRefPtr node3 = node0->addChildNode( path, BLANK ); path = "File"; ossimRefPtr node3a = node3->addChildNode( path, BLANK ); path = "rangeParameters"; ossimRefPtr node3a1 = node3a->addChildNode( path, BLANK ); path = "fileName"; ossimRefPtr node3a2 = node3a->addChildNode( path, "gmljp2://codestream" ); path = "fileStructure"; ossimRefPtr node3a3 = node3a->addChildNode( path, "inapplicable" ); path = "gmlcov:rangeType"; ossimRefPtr node4 = node0->addChildNode( path, BLANK ); path = "gmljp2:featureMember"; ossimRefPtr node5 = node0->addChildNode( path, BLANK ); path = "gmljp2:GMLJP2RectifiedGridCoverage"; ossimRefPtr node5a = node5->addChildNode( path, BLANK ); attr = new ossimXmlAttribute(); name = "gml:id"; value = "CodeStream_0"; attr->setNameValue( name, value ); node5a->addAttribute( attr ); path = "domainSet"; ossimRefPtr node5a1 = node5a->addChildNode( path, BLANK ); path = "RectifiedGrid"; ossimRefPtr node5a1a = node5a1->addChildNode( path, BLANK ); attr = new ossimXmlAttribute(); name = "gml:id"; value = "RG0001"; attr->setNameValue( name, value ); node5a1a->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "dimension"; value = "2"; attr->setNameValue( name, value ); node5a1a->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "srsName"; attr->setNameValue( name, m_srsNameStringMap ); node5a1a->addAttribute( attr ); path = "limits"; ossimRefPtr node5a1a1 = node5a1a->addChildNode( path, BLANK ); path = "GridEnvelope"; ossimRefPtr node5a1a1a = node5a1a1->addChildNode( path, BLANK ); path = "low"; ossimRefPtr node5a1a1a1 = node5a1a1a->addChildNode( path, gridLowString ); path = "high"; ossimRefPtr node5a1a1a2 = node5a1a1a->addChildNode( path, gridHighString ); path = "axisLabels"; ossimRefPtr node5a1a2 = node5a1a->addChildNode( path, mapProj->isGeographic() ? m_axisLabelsStringGeo : m_axisLabelsStringMap ); path = "origin"; ossimRefPtr node5a1a3 = node5a1a->addChildNode( path, BLANK ); path = "Point"; ossimRefPtr node5a1a3a = node5a1a3->addChildNode( path, BLANK ); attr = new ossimXmlAttribute(); name = "gml:id"; value = "P0001"; attr->setNameValue( name, value ); node5a1a3a->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "srsName"; attr->setNameValue( name, m_srsNameStringMap ); node5a1a3a->addAttribute( attr ); ossimString originString; ossimString offsetVector1String; ossimString offsetVector2String; if ( isGeographic ) { getGeoOrigin( geom, rect.ul(), originString, offsetVector1String, offsetVector2String ); } else { getMapOrigin( geom, rect.ul(), originString, offsetVector1String, offsetVector2String ); } path = "pos"; ossimRefPtr node5a1a3a1 = node5a1a3a->addChildNode( path, originString ); path = "offsetVector"; ossimRefPtr node5a1a4 = node5a1a->addChildNode( path, offsetVector1String ); attr = new ossimXmlAttribute(); name = "srsName"; attr->setNameValue( name, (isGeographic ? m_srsNameStringGeo : m_srsNameStringMap ) ); node5a1a4->addAttribute( attr ); path = "offsetVector"; ossimRefPtr node5a1a5 = node5a1a->addChildNode( path, offsetVector2String ); attr = new ossimXmlAttribute(); name = "srsName"; attr->setNameValue( name, (isGeographic ? m_srsNameStringGeo : m_srsNameStringMap) ); node5a1a5->addAttribute( attr ); path = "rangeSet"; ossimRefPtr node5a2 = node5a->addChildNode( path, BLANK ); path = "File"; ossimRefPtr node5a2a = node5a2->addChildNode( path, BLANK ); path = "rangeParameters"; ossimRefPtr node5a2a1 = node5a2a->addChildNode( path, BLANK ); path = "fileName"; ossimRefPtr node5a2a2 = node5a2a->addChildNode( path, "gmljp2://codestream" ); path = "fileStructure"; ossimRefPtr node5a2a3 = node5a2a->addChildNode( path, "inapplicable" ); success = true; } return success; } bool ossimGmlSupportData::configureBounds( ossimRefPtr node0, const ossimImageGeometry* geom, const ossimIrect& rect) { bool success = true; const ossimString BLANK = ""; ossimString upperCornerString; ossimString lowerCornerString; getGeoBounds( geom, rect, upperCornerString, lowerCornerString ); ossimString path = "boundedBy"; ossimRefPtr node1 = node0->addChildNode( path, BLANK ); path = "Envelope"; ossimRefPtr node1a = node1->addChildNode( path, BLANK ); ossimRefPtr attr( 0 ); ossimString name; attr = new ossimXmlAttribute(); name = "srsName"; attr->setNameValue( name, m_srsNameStringGeo ); node1a->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "axisLabels"; attr->setNameValue( name, m_axisLabelsStringGeo ); node1a->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "uomLabels"; attr->setNameValue( name, m_uomLabelsStringGeo ); node1a->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "srsDimension"; attr->setNameValue( name, m_srsDimensionString ); node1a->addAttribute( attr ); path = "lowerCorner"; ossimRefPtr node1a1 = node1a->addChildNode( path, lowerCornerString ); path = "upperCorner"; ossimRefPtr node1a2 = node1a->addChildNode( path, upperCornerString ); return success; } ossimRefPtr ossimGmlSupportData::getGmljp2V2RootNode() const { ossimRefPtr node = new ossimXmlNode(); ossimString os = "gmljp2:GMLJP2CoverageCollection"; node->setTag( os ); ossimRefPtr attr( 0 ); ossimString name; ossimString value; attr = new ossimXmlAttribute(); name = "gml:id"; value = "JPEG2000_0"; attr->setNameValue( name, value ); node->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "xmlns"; value = "http://www.opengis.net/gml/3.2"; attr->setNameValue( name, value ); node->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "xmlns:gml"; value = "http://www.opengis.net/gml/3.2"; attr->setNameValue( name, value ); node->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "xmlns:gmlcov"; value = "http://www.opengis.net/gmlcov/1.0"; attr->setNameValue( name, value ); node->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "xmlns:gmljp2"; value = "http://www.opengis.net/gmljp2/2.0"; attr->setNameValue( name, value ); node->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "xmlns:xsi"; value = "http://www.w3.org/2001/XMLSchema-instance"; attr->setNameValue( name, value ); node->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "xsi:schemaLocation"; value = "http://www.opengis.net/gmljp2/2.0 http://schemas.opengis.net/gmljp2/2.0/gmljp2.xsd"; attr->setNameValue( name, value ); node->addAttribute( attr ); return node; } // ossimGmlSupportData::getGmljp2V2Node() ossimRefPtr ossimGmlSupportData::getGmljp2V1RootNode() const { ossimRefPtr node = new ossimXmlNode(); ossimString os = "gml:FeatureCollection"; node->setTag( os ); ossimRefPtr attr(0); ossimString name; ossimString value; attr = new ossimXmlAttribute(); name = "xmlns"; value = "http://www.opengis.net/gml"; attr->setNameValue( name, value ); node->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "xmlns:gml"; value = "http://www.opengis.net/gml"; attr->setNameValue( name, value ); node->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "xmlns:xsi"; value = "http://www.w3.org/2001/XMLSchema-instance"; attr->setNameValue( name, value ); node->addAttribute( attr ); attr = new ossimXmlAttribute(); name = "xsi:schemaLocation"; value = "http://www.opengis.net/gml gmlJP2Profile.xsd"; attr->setNameValue( name, value ); node->addAttribute( attr ); return node; } // ossimGmlSupportData::getGmljp2V1Node() bool ossimGmlSupportData::write(std::ostream& os) { bool status = false; if ( m_xmlDocument.valid() ) { os << *(m_xmlDocument.get()); status = true; } return status; } ossimRefPtr ossimGmlSupportData::getXmlDoc() const { return m_xmlDocument; } bool ossimGmlSupportData::getImageGeometry( ossimKeywordlist& geomKwl ) const { // Try for map projected geometry first... bool success = getImageGeometryFromRectifiedGrid( geomKwl ); if ( !success ) { // Look for sensor model block. getImageGeometryFromSeonsorModel( geomKwl ); } return success; } #if 0 /* Please leave. (drb) */ bool ossimGmlSupportData::getImageGeometry( ossimKeywordlist& geomKwl ) const { if ( m_xmlDocument.valid() ) { vector< ossimRefPtr > xml_nodes; bool gotSensorImage = false; bool gotRectifiedImage = false; ossim_uint32 pcsCodeGrid = 32767; // only applies to rectified // Check the GMLJP2CoverageCollection attributes for the default namespace. ossimString defaultNamespaceStr( "" ); ossimString xpath_root = "/gmljp2:GMLJP2CoverageCollection"; xml_nodes.clear(); m_xmlDocument->findNodes( xpath_root, xml_nodes ); if ( xml_nodes.size() == 0 ) { // check if the default namespace is gmljp2 xpath_root = "/GMLJP2CoverageCollection"; m_xmlDocument->findNodes( xpath_root, xml_nodes ); } if ( xml_nodes.size() >= 1 ) { const ossimString defaultNamespaceIdentifierStr( "xmlns" ); ossimString defaultNamespacePrependStr = defaultNamespaceIdentifierStr + ":"; const ossimRefPtr defaultNamespaceAttribute = xml_nodes[0]->findAttribute( defaultNamespaceIdentifierStr ); ossimString defaultNamespaceSettingStr = defaultNamespaceAttribute->getValue(); // search for the attribute value in the other attributes const ossimXmlNode::AttributeListType& attributeList = xml_nodes[0]->getAttributes(); size_t nAttributes = attributeList.size(); for ( size_t i=0; i attribute = attributeList[i]; const ossimString& attribute_name = attribute->getName(); const ossimString& attribute_value = attribute->getValue(); if ( attribute_name != defaultNamespaceIdentifierStr && attribute_value == defaultNamespaceSettingStr ) { defaultNamespaceStr = attribute_name.after( defaultNamespacePrependStr ); defaultNamespaceStr += ":"; } } } // Check for a sensor image ossimString xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2ReferenceableGridCoverage/gml:domainSet/gmlcov:ReferenceableGridBySensorModel"; xpath0 = xpath0.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xml_nodes.clear(); m_xmlDocument->findNodes( xpath0, xml_nodes ); if ( xml_nodes.size() >= 1 ) { // we've got a sensor model image gotSensorImage = true; } else { const ossimString srsNameStr( "srsName" ); ossimString pcsCodeDefinitionStr( "http://www.opengis.net/def/crs/EPSG/0/" ); xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2RectifiedGridCoverage/gml:domainSet/gml:RectifiedGrid"; xpath0 = xpath0.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xml_nodes.clear(); m_xmlDocument->findNodes( xpath0, xml_nodes ); if ( xml_nodes.size() >= 1 ) { // we've got a rectified image gotRectifiedImage = true; const ossimRefPtr hrefAttribute = xml_nodes[0]->findAttribute( srsNameStr ); const ossimString& originSrsName = hrefAttribute->getValue(); ossimString pcsCodeGridStr = originSrsName.after( pcsCodeDefinitionStr.string() ); pcsCodeGrid = pcsCodeGridStr.toUInt32(); if ( pcsCodeGrid != 32767 ) { //--- // The ossimEpsgProjectionFactory will not pick up the origin latitude if code is // 4326 (geographic) so we use the projection name; else, the origin_latitude will // always be 0. This is so the gsd comes out correct for scale. //--- if ( pcsCodeGrid != 4326 ) // map projection { // Add the pcs code. geomKwl.add( ossimKeywordNames::PCS_CODE_KW, pcsCodeGridStr.c_str() ); } else // geographic { geomKwl.add( ossimKeywordNames::TYPE_KW, ossimString( "ossimEquDistCylProjection" ) ); } } } } // Number of lines & samples, for either sensor or rectified imagery ossimString xpath_limits_low = "/gml:limits/gml:GridEnvelope/gml:low"; ossimString xpath_limits_high = "/gml:limits/gml:GridEnvelope/gml:high"; xpath_limits_low = xpath_limits_low.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xpath_limits_high = xpath_limits_high.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); bool gotLow = false; ossim_int32 lowX, lowY; ossimString xpath = xpath0 + xpath_limits_low; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { const ossimString& lowerCorner = xml_nodes[0]->getText(); size_t spacePos = lowerCorner.find( ' ' ); ossimString lowerXString = lowerCorner.beforePos( spacePos ); ossimString lowerYString = lowerCorner.afterPos ( spacePos ); lowX = lowerXString.toInt32(); lowY = lowerYString.toInt32(); gotLow = true; } bool gotHigh = false; ossim_int32 highX = 0; ossim_int32 highY = 0; xpath = xpath0 + xpath_limits_high; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { const ossimString& higherCorner = xml_nodes[0]->getText(); size_t spacePos = higherCorner.find( ' ' ); ossimString higherXString = higherCorner.beforePos( spacePos ); ossimString higherYString = higherCorner.afterPos ( spacePos ); highX = higherXString.toInt32(); highY = higherYString.toInt32(); gotHigh = true; } if ( gotHigh && gotLow ) { geomKwl.add( ossimKeywordNames::NUMBER_LINES_KW, highY - lowY + 1 ); geomKwl.add( ossimKeywordNames::NUMBER_SAMPLES_KW, highX - lowX + 1 ); } if ( gotSensorImage ) { const ossimString hrefStr( "xlink:href" ); const ossimString codeSpaceStr( "codeSpace" ); ossimString sensorModelHref( "" ); ossimString xpath_sensor_model = "/gmlcov:sensorModel"; xpath_sensor_model = xpath_sensor_model.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xpath = xpath0 + xpath_sensor_model; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { const ossimRefPtr hrefAttribute = xml_nodes[0]->findAttribute( hrefStr ); sensorModelHref = hrefAttribute->getValue(); } ossimString sensorInstanceHref( "" ); ossimString xpath_sensor_typeOf = "/gmlcov:sensorInstance/sml:SimpleProcess/sml:typeOf"; xpath_sensor_typeOf = xpath_sensor_typeOf.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xpath = xpath0 + xpath_sensor_typeOf; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { const ossimRefPtr hrefAttribute = xml_nodes[0]->findAttribute( hrefStr ); sensorInstanceHref = hrefAttribute->getValue(); } ossimRefPtr sensor_model = 0; ossimString xpath_sensor_name = "/gmlcov:sensorInstance/sml:SimpleProcess/gml:name"; xpath_sensor_name = xpath_sensor_name.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xpath = xpath0 + xpath_sensor_name; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); int nSensorNames = (int)xml_nodes.size(); for ( int i=0; igetText(); ossimProjectionFactoryRegistry* registry = ossimProjectionFactoryRegistry::instance(); ossimProjection* proj = registry->createProjection( sensorName ); // Is it a sensor model ? sensor_model = dynamic_cast( proj ); if ( sensor_model.valid() ) { geomKwl.add( ossimKeywordNames::TYPE_KW, sensorName.c_str() ); break; } } if ( !sensor_model.valid() ) { // Add debug message return false; } // Check if the sensor instance is typeOf the sensor model if ( sensorModelHref == sensorInstanceHref ) { const ossimString refStr( "ref" ); // sml:setValue ossimString xpath_setValue = "/gmlcov:sensorInstance/sml:SimpleProcess/sml:configuration/sml:Settings/sml:setValue"; xpath_setValue = xpath_setValue.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xpath = xpath0 + xpath_setValue; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); size_t nXmlNodes = xml_nodes.size(); for( size_t i=0; igetText(); const ossimRefPtr refAttribute = xml_nodes[i]->findAttribute( refStr ); const ossimString& settingsRef = refAttribute->getValue(); bool successSetValue = sensor_model->getImageGeometry( settingsRef, elementValue, geomKwl ); success &= successSetValue; if ( !successSetValue ) { // Add debug message } } /* sml:setArrayValues */ ossimString xpath_setArrayValues = "/gmlcov:sensorInstance/sml:SimpleProcess/sml:configuration/sml:Settings/sml:setArrayValues"; xpath_setArrayValues = xpath_setArrayValues.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xpath = xpath0 + xpath_setArrayValues; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); nXmlNodes = xml_nodes.size(); for( size_t i=0; i refAttribute = xml_nodes[i]->findAttribute( refStr ); const ossimString& settingsRef = refAttribute->getValue(); const ossimXmlNode::ChildListType& children = xml_nodes[i]->getChildNodes(); if ( children.size() > 0 ) { const ossimXmlNode::ChildListType& grandchildren = children[0]->getChildNodes(); if ( (grandchildren.size() > 1) && (grandchildren[1]->getTag() == ossimString( "sml:value")) ) { elementValue = grandchildren[1]->getText(); } } bool successSetArrayValues = sensor_model->getImageGeometry( settingsRef, elementValue, geomKwl ); success &= successSetArrayValues; if ( !successSetArrayValues ) { // Add debug message } } } } else if ( gotRectifiedImage ) { const ossimString srsNameStr( "srsName" ); ossimString pcsCodeDefinitionStr( "http://www.opengis.net/def/crs/EPSG/0/" ); /* axis labels for rectified imagery */ ossimString xpath_axisLabels = "/gml:axisLabels"; xpath_axisLabels = xpath_axisLabels.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); ossimString firstAxisLabelString( "" ); ossimString secondAxisLabelString( "" ); ossimString xpath = xpath0 + xpath_axisLabels; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { ossimString axisLabelsString = xml_nodes[0]->getText(); size_t spacePos = axisLabelsString.find( ' ' ); firstAxisLabelString = axisLabelsString.beforePos( spacePos ); secondAxisLabelString = axisLabelsString.afterPos ( spacePos ); } success = addTieAndScale( geomKwl ); //--- // origin: // Note: In GML the origin is the tie point, NOT the projection origin. //--- ossim_uint32 pcsCodeOrigin = 32767; ossimString xpath_originPoint = "/gml:origin/gml:Point"; xpath_originPoint = xpath_originPoint.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xpath = xpath0 + xpath_originPoint; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { const ossimString& originString = xml_nodes[0]->getChildTextValue( ossimString( "pos" ) ); size_t spacePos = originString.find( ' ' ); ossimString firstOriginString = originString.beforePos( spacePos ); ossimString secondOriginString = originString.afterPos ( spacePos ); const ossimRefPtr hrefAttribute = xml_nodes[0]->findAttribute( srsNameStr ); const ossimString& originSrsName = hrefAttribute->getValue(); ossimString pcsCodeOriginStr = originSrsName.after( pcsCodeDefinitionStr.string() ); pcsCodeOrigin = pcsCodeOriginStr.toUInt32(); if ( pcsCodeOrigin != 32767 ) { std::string tie_point_xy; std::string tie_point_units; if ( pcsCodeOrigin == 4326 ) // map projection { // Longitude first, e.g. (lon,lat) tie_point_units = "degrees"; } else { tie_point_units = "meters"; } if ( ( tie_point_units == "degrees" ) && ( firstAxisLabelString == "Lat" ) ) { tie_point_xy = "("; tie_point_xy += secondOriginString.string(); tie_point_xy += ","; tie_point_xy += firstOriginString.string(); tie_point_xy += ")"; } else { tie_point_xy = "("; tie_point_xy += firstOriginString.string(); tie_point_xy += ","; tie_point_xy += secondOriginString.string(); tie_point_xy += ")"; } geomKwl.add( ossimKeywordNames::TIE_POINT_XY_KW, tie_point_xy.c_str() ); geomKwl.add( ossimKeywordNames::TIE_POINT_UNITS_KW, tie_point_units.c_str() ); } } //--- // offset vector // Note this is the scale: ossimString xpath_offsetVector = "/gml:offsetVector"; xpath_offsetVector = xpath_offsetVector.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" ); xpath = xpath0 + xpath_offsetVector; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() ) { const ossimString& offsetVectorString = xml_nodes[0]->getText(); size_t spacePos = offsetVectorString.find( ' ' ); ossimString firstOffsetVectorString = offsetVectorString.beforePos( spacePos ); ossimString secondOffsetVectorString = offsetVectorString.afterPos ( spacePos ); const ossimRefPtr hrefAttribute = xml_nodes[0]->findAttribute( srsNameStr ); const ossimString& offsetVectorSrsName = hrefAttribute->getValue(); ossimString pcsCodeOffsetVectorStr = offsetVectorSrsName.after( pcsCodeDefinitionStr.string() ); ossim_uint32 pcsCodeOffsetVector = pcsCodeOffsetVectorStr.toUInt32(); if ( pcsCodeOffsetVector != 32767 ) { std::string scale_xy; std::string scale_units; if ( pcsCodeOffsetVector == 4326 ) { scale_units = "degrees"; } else { scale_units = "meters"; } if ( ( scale_units == "degrees" ) && ( firstAxisLabelString == "Lat" ) ) { scale_xy = "("; scale_xy += secondOffsetVectorString.c_str(); scale_xy += ","; scale_xy += firstOffsetVectorString.c_str(); scale_xy += ")"; } else { scale_xy = "("; scale_xy += firstOffsetVectorString.c_str(); scale_xy += ","; scale_xy += secondOffsetVectorString.c_str(); scale_xy += ")"; } geomKwl.add( ossimKeywordNames::PIXEL_SCALE_XY_KW, scale_xy.c_str() ); geomKwl.add( ossimKeywordNames::PIXEL_SCALE_UNITS_KW, scale_units.c_str() ); } } } } return success; } // End: ossimGmlSupportData::getImageGeometry( geomKwl ) #endif void ossimGmlSupportData::getGeoOrigin( const ossimImageGeometry* geom, const ossimIpt& ul, ossimString& originString, ossimString& offsetVector1String, ossimString& offsetVector2String ) const { if ( geom ) { // Get the gsd: ossimDpt gsd; geom->getDegreesPerPixel( gsd ); // Get tie point: ossimGpt tie; geom->localToWorld( ul, tie ); std::ostringstream os; os.precision(15); os << tie.lat << " " << tie.lon; originString = os.str(); std::ostringstream os2; os2.precision(15); os2 << -gsd.y << " " << "0.0"; offsetVector1String = os2.str(); std::ostringstream os3; os3.precision(15); os3 << "0.0" << " " << gsd.x; offsetVector2String = os3.str(); } } // End: ossimGmlSupportData::getGeoOrigin void ossimGmlSupportData::getMapOrigin( const ossimImageGeometry* geom, const ossimIpt& ul, ossimString& originString, ossimString& offsetVector1String, ossimString& offsetVector2String ) const { if ( geom ) { ossimRefPtr mapProj = geom->getAsMapProjection(); if ( mapProj.valid() != 0 ) { // Get the tie point: ossimGpt gpt; geom->localToWorld( ul, gpt ); ossimDpt tie = mapProj->forward( gpt ); std::ostringstream os; os.precision(15); os << tie.x << " " << tie.y; originString = os.str(); } // Get the projected CS gsd: ossimDpt gsdMap; geom->getMetersPerPixel( gsdMap ); std::ostringstream os2; os2.precision(15); os2 << gsdMap.x << " " << "0.0"; offsetVector1String = os2.str(); std::ostringstream os3; os3.precision(15); os3 << "0.0" << " " << -gsdMap.y; offsetVector2String = os3.str(); } } // End: ossimGmlSupportData::getMapBounds void ossimGmlSupportData::getGeoBounds( const ossimImageGeometry* geom, const ossimIrect& rect, ossimString& upperCornerString, ossimString& lowerCornerString ) const { if ( geom ) { ossimRefPtr mapProj = geom->getAsMapProjection(); if ( mapProj.valid() ) { // Get the bounding rect. This assumes North up. ossimGpt ulGpt; ossimGpt lrGpt; geom->localToWorld( rect.ul(), ulGpt ); geom->localToWorld( rect.lr(), lrGpt ); std::ostringstream os; os.precision(15); os << ulGpt.lat << " " << ulGpt.lon; upperCornerString = os.str(); std::ostringstream os2; os2.precision(15); os2 << lrGpt.lat << " " << lrGpt.lon; lowerCornerString = os2.str(); } } } // End: ossimGmlSupportData::getGeoBounds void ossimGmlSupportData::getLimits( const ossimIrect& rect, ossimString& gridHighString, ossimString& gridLowString ) const { if ( rect.hasNans() == false ) { // Zero based image rect. gridLowString = "0 0"; ossim_uint32 w = rect.width(); ossim_uint32 h = rect.height(); std::ostringstream os; os << (w-1) << " " << (h-1); gridHighString = os.str(); } } bool ossimGmlSupportData::getImageGeometryFromSeonsorModel( ossimKeywordlist& /* geomKwl */) const { bool status = false; if ( m_xmlDocument.valid() ) { vector< ossimRefPtr > xml_nodes; ossimString xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2ReferenceableGridCoverage/gml:domainSet/gmlcov:ReferenceableGridBySensorModel"; m_xmlDocument->findNodes( xpath0, xml_nodes ); if ( xml_nodes.size() >= 1 ) { // Put sensor model code here... status = true; } } return status; } bool ossimGmlSupportData::getImageGeometryFromRectifiedGrid( ossimKeywordlist& geomKwl ) const { bool status = false; if ( m_xmlDocument.valid() ) { bool useGmlPrefix = false; vector< ossimRefPtr > xml_nodes; ossimString xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2RectifiedGridCoverage/domainSet/RectifiedGrid"; m_xmlDocument->findNodes( xpath0, xml_nodes ); if ( !xml_nodes.size() ) { xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2RectifiedGridCoverage/gml:domainSet/gml:RectifiedGrid"; m_xmlDocument->findNodes( xpath0, xml_nodes ); if ( xml_nodes.size() ) { useGmlPrefix = true; } } if ( xml_nodes.size() ) { const ossimString SRS_NAME( "srsName" ); const ossimString PCS_CODE_DEFINITION_STR( "http://www.opengis.net/def/crs/EPSG/0/" ); const ossimRefPtr hrefAttribute = xml_nodes[0]->findAttribute( SRS_NAME ); const ossimString& originSrsName = hrefAttribute->getValue(); ossimString pcsCodeStr = originSrsName.after( PCS_CODE_DEFINITION_STR.string() ); ossim_uint32 pcsCode = pcsCodeStr.toUInt32(); if ( pcsCode != 32767 ) { // Add the pcs code. geomKwl.add( ossimKeywordNames::PCS_CODE_KW, pcsCodeStr.c_str() ); if ( pcsCode == 4326 ) { ossimString srsName = "EPSG:"; srsName += pcsCodeStr; geomKwl.add( ossimKeywordNames::SRS_NAME_KW, srsName.c_str() ); geomKwl.add( ossimKeywordNames::TYPE_KW, "ossimEquDistCylProjection"); } if ( addLineSamps( xpath0, useGmlPrefix, geomKwl ) ) { if ( addTie( xpath0, useGmlPrefix, pcsCode, geomKwl ) ) { status = addScale( xpath0, useGmlPrefix, pcsCode, geomKwl ); } } } } } return status; } bool ossimGmlSupportData::addLineSamps( const ossimString& xpath0, bool useGmlPrefix, ossimKeywordlist& geomKwl ) const { bool status = false; if ( m_xmlDocument.valid() ) { vector< ossimRefPtr > xml_nodes; // Number of lines & samples, for either sensor or rectified imagery: ossimString xpath_limits_low; if (useGmlPrefix) { xpath_limits_low = "/gml:limits/gml:GridEnvelope/gml:low"; } else { xpath_limits_low = "/limits/GridEnvelope/low"; } ossimString xpath = xpath0 + xpath_limits_low; m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { const ossimString& lowerCorner = xml_nodes[0]->getText(); size_t spacePos = lowerCorner.find( ' ' ); ossimString lowerXString = lowerCorner.beforePos( spacePos ); ossimString lowerYString = lowerCorner.afterPos ( spacePos ); ossim_uint32 lowX = lowerXString.toInt32(); ossim_uint32 lowY = lowerYString.toInt32(); ossimString xpath_limits_high; if ( useGmlPrefix ) { xpath_limits_high = "/gml:limits/gml:GridEnvelope/gml:high"; } else { xpath_limits_high = "/limits/GridEnvelope/high"; } xpath = xpath0 + xpath_limits_high; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { const ossimString& higherCorner = xml_nodes[0]->getText(); size_t spacePos = higherCorner.find( ' ' ); ossimString higherXString = higherCorner.beforePos( spacePos ); ossimString higherYString = higherCorner.afterPos ( spacePos ); ossim_uint32 highX = higherXString.toInt32(); ossim_uint32 highY = higherYString.toInt32(); geomKwl.add( ossimKeywordNames::NUMBER_LINES_KW, highY - lowY + 1 ); geomKwl.add( ossimKeywordNames::NUMBER_SAMPLES_KW, highX - lowX + 1 ); status = true; } } } return status; } // ossimGmlSupportData::addLineSamps bool ossimGmlSupportData::addTie( const ossimString& xpath0, bool useGmlPrefix, ossim_uint32 pcsCode, ossimKeywordlist& geomKwl ) const { bool status = false; if ( m_xmlDocument.valid() && (pcsCode != 32767 ) ) { vector< ossimRefPtr > xml_nodes; //--- // origin: // Note: In GML the origin is the tie point, NOT the projection origin. //--- // axis labels for rectified imagery: ossimString xpath_axisLabels; if ( useGmlPrefix ) { xpath_axisLabels = "/gml:axisLabels"; } else { xpath_axisLabels = "/axisLabels"; } ossimString xpath = xpath0 + xpath_axisLabels; m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { ossimString axisLabelsString = xml_nodes[0]->getText(); ossimString xpath_originPoint; if ( useGmlPrefix ) { xpath_originPoint = "/gml:origin/gml:Point"; } else { xpath_originPoint = "/origin/Point"; } xpath = xpath0 + xpath_originPoint; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { const ossimString& originString = xml_nodes[0]->getChildTextValue( ossimString( "pos" ) ); size_t spacePos = originString.find( ' ' ); ossimString firstOriginString = originString.beforePos( spacePos ); ossimString secondOriginString = originString.afterPos ( spacePos ); std::string tie_point_xy; std::string tie_point_units; if ( pcsCode == 4326 ) // map projection { // Longitude first, e.g. (lon,lat) tie_point_units = "degrees"; } else { tie_point_units = "meters"; } if ( ( tie_point_units == "degrees" ) && ( axisLabelsString == "Lat Long" ) ) { tie_point_xy = "("; tie_point_xy += secondOriginString.string(); tie_point_xy += ","; tie_point_xy += firstOriginString.string(); tie_point_xy += ")"; } else { tie_point_xy = "("; tie_point_xy += firstOriginString.string(); tie_point_xy += ","; tie_point_xy += secondOriginString.string(); tie_point_xy += ")"; } geomKwl.add( ossimKeywordNames::TIE_POINT_XY_KW, tie_point_xy.c_str() ); geomKwl.add( ossimKeywordNames::TIE_POINT_UNITS_KW, tie_point_units.c_str() ); status = true; } } } // Matches: if ( m_xmlDocument.valid() && (pscCode != 32767 ) ) return status; } // End: ossimGmlSupportData::addTie( ... ) bool ossimGmlSupportData::addScale( const ossimString& xpath0, bool useGmlPrefix, ossim_uint32 pcsCode, ossimKeywordlist& geomKwl ) const { bool status = false; if ( m_xmlDocument.valid() && (pcsCode != 32767 ) ) { vector< ossimRefPtr > xml_nodes; //--- // origin: // Note: In GML the origin is the tie point, NOT the projection origin. //--- // axis labels for rectified imagery: ossimString xpath_axisLabels; if ( useGmlPrefix ) { xpath_axisLabels = "/gml:axisLabels"; } else { xpath_axisLabels = "/axisLabels"; } ossimString xpath = xpath0 + xpath_axisLabels; m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 1 ) { ossimString axisLabelsString = xml_nodes[0]->getText(); ossimString xpath_offsetVector; if ( useGmlPrefix ) { xpath_offsetVector = "/gml:offsetVector"; } else { xpath_offsetVector = "/offsetVector"; } xpath = xpath0 + xpath_offsetVector; xml_nodes.clear(); m_xmlDocument->findNodes( xpath, xml_nodes ); if ( xml_nodes.size() == 2 ) { const ossimString& offsetVectorString0 = xml_nodes[0]->getText(); const ossimString& offsetVectorString1 = xml_nodes[1]->getText(); size_t spacePos0 = offsetVectorString0.find( ' ' ); size_t spacePos1 = offsetVectorString1.find( ' ' ); ossimString firstOffsetVectorString0 = offsetVectorString0.beforePos( spacePos0 ); ossimString secondOffsetVectorString0 = offsetVectorString0.afterPos ( spacePos0 ); ossimString firstOffsetVectorString1 = offsetVectorString1.beforePos( spacePos1 ); ossimString secondOffsetVectorString1 = offsetVectorString1.afterPos ( spacePos1 ); // TODO: Add for rotational matrix: std::string scale_xy; std::string scale_units; if ( pcsCode == 4326 ) { scale_units = "degrees"; } else { scale_units = "meters"; } ossimDpt scale; if ( ( scale_units == "degrees" ) && ( axisLabelsString == "Lat Long" ) ) { scale.x = secondOffsetVectorString1.toFloat64(); scale.y = firstOffsetVectorString0.toFloat64(); } else { scale.x = firstOffsetVectorString0.toFloat64(); scale.y = secondOffsetVectorString1.toFloat64(); } if ( scale.y < 0.0 ) { scale.y *= -1.0; // make positive } if ( ( scale_units == "degrees" ) && ( scale.x != scale.y ) ) { // Compute/add the origin latitude of true scale. ossim_float64 origin_lat = ossim::acosd(scale.y/scale.x); geomKwl.add( ossimKeywordNames::ORIGIN_LATITUDE_KW, origin_lat ); } geomKwl.add( ossimKeywordNames::PIXEL_SCALE_XY_KW, scale.toString().c_str() ); geomKwl.add( ossimKeywordNames::PIXEL_SCALE_UNITS_KW, scale_units.c_str() ); status = true; } } } // Matches: if ( m_xmlDocument.valid() && (pscCode != 32767 ) ) return status; } // End: ossimGmlSupportData::addScale( ... ) ossim-Miami-2.9.1/src/support_data/ossimIkonosMetaData.cpp000066400000000000000000000352031352751253100236340ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Class definition for ossimIkonosMetaData. // // This class parses a Space Imaging Ikonos meta data file. // //******************************************************************** // $Id: ossimIkonosMetaData.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include #include #include RTTI_DEF1(ossimIkonosMetaData, "ossimIkonosMetaData", ossimObject); // Define Trace flags for use within this file: static ossimTrace traceExec ("ossimIkonosMetaData:exec"); static ossimTrace traceDebug ("ossimIkonosMetaData:debug"); ossimIkonosMetaData::ossimIkonosMetaData() : theNominalCollectionAzimuth(0.0), theNominalCollectionElevation(0.0), theSunAzimuth(0.0), theSunElevation(0.0), theNumBands(0), theBandName("Unknown"), theProductionDate("Unknown"), theAcquisitionDate("Unknown"), theAcquisitionTime("Unknown"), theSensorID("Unknown") { } ossimIkonosMetaData::~ossimIkonosMetaData() { } bool ossimIkonosMetaData::open(const ossimFilename& imageFile) { static const char MODULE[] = "ossimIkonosMetaData::open"; clearFields(); //retrieve information from the metadata file //if the ikonos tif is po_2619900_pan_0000000.tif //the metadata file will be po_2619900_metadata.txt ossimString separator("_"); ossimString filenamebase = imageFile.fileNoExtension(); std::vector< ossimString > filenameparts = filenamebase.split(separator); if(filenameparts.size() < 2) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Ikonos filename non standard" << std::endl; } return false; } ossimFilename metadatafile = filenameparts[0]; metadatafile += "_"; metadatafile += filenameparts[1]; metadatafile += "_metadata.txt"; metadatafile.setPath(imageFile.path()); if( parseMetaData(metadatafile) == false ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " errors parsing metadata" << std::endl; } return false; } ossimFilename hdrfile = imageFile; hdrfile.setExtension(ossimString("hdr")); if( parseHdrData(hdrfile) == false ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " errors parsing hdr" << std::endl; } return false; } ossimFilename rpcfile = imageFile.noExtension(); rpcfile += "_rpc.txt"; if (parseRpcData (rpcfile) == false) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " errors parsing rpc" << std::endl; } return false; } return true; } void ossimIkonosMetaData::clearFields() { theNominalCollectionAzimuth = 0.0; theNominalCollectionElevation = 0.0; theSunAzimuth = 0.0; theSunElevation = 0.0; theNumBands = 0; theBandName = "Unknown"; theProductionDate = "Unknown"; theAcquisitionDate = "Unknown"; theAcquisitionTime = "Unknown"; theSensorID = "Unknown"; } std::ostream& ossimIkonosMetaData::print(std::ostream& out) const { out << "\n----------------- Info on Ikonos Image -------------------" << "\n " << "\n Nominal Azimuth: " << theNominalCollectionAzimuth << "\n Nominal Elevation: " << theNominalCollectionElevation << "\n Sun Azimuth: " << theSunAzimuth << "\n Sun Elevation: " << theSunElevation << "\n Number of bands: " << theNumBands << "\n Band name: " << theBandName << "\n Production date: " << theProductionDate << "\n Acquisition date: " << theAcquisitionDate << "\n Acquisition time: " << theAcquisitionTime << "\n Sensor Type: " << theSensorID << "\n" << "\n---------------------------------------------------------" << "\n " << std::endl; return out; } ossimString ossimIkonosMetaData::getSensorID() const { return theSensorID; } bool ossimIkonosMetaData::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimIkonosMetaData", true); kwl.add(prefix, "nominal_collection_azimuth_angle", theNominalCollectionAzimuth, true); kwl.add(prefix, "nominal_collection_elevation_angle", theNominalCollectionElevation, true); kwl.add(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW, theSunAzimuth, true); kwl.add(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW, theSunElevation, true); kwl.add(prefix, ossimKeywordNames::NUMBER_BANDS_KW, theNumBands, true); kwl.add(prefix, "band_name", theBandName, true); kwl.add(prefix, "production_date", theProductionDate, true); kwl.add(prefix, "acquisition_date", theAcquisitionDate, true); kwl.add(prefix, "acquisition_time", theAcquisitionTime, true); kwl.add(prefix, "sensor", theSensorID, true); return true; } bool ossimIkonosMetaData::loadState(const ossimKeywordlist& kwl, const char* prefix) { clearFields(); const char* lookup = 0; ossimString s; lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if (lookup) { s = lookup; if(s != "ossimIkonosMetaData") { return false; } } lookup = kwl.find(prefix, "nominal_collection_azimuth_angle"); if (lookup) { s = lookup; theNominalCollectionAzimuth = s.toFloat64(); } lookup = kwl.find(prefix, "nominal_collection_elevation_angle"); if (lookup) { s = lookup; theNominalCollectionElevation = s.toFloat64(); } lookup = kwl.find(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW); if (lookup) { s = lookup; theSunAzimuth = s.toFloat64(); } lookup = kwl.find(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW); if (lookup) { s = lookup; theSunElevation = s.toFloat64(); } lookup = kwl.find(prefix, ossimKeywordNames::NUMBER_BANDS_KW); if (lookup) { s = lookup; theNumBands = s.toUInt32(); } lookup = kwl.find(prefix, "band_name"); if (lookup) { theBandName = lookup; } lookup = kwl.find(prefix, "production_date"); if (lookup) { theProductionDate = lookup; } lookup = kwl.find(prefix, "acquisition_date"); if (lookup) { theAcquisitionDate = lookup; } lookup = kwl.find(prefix, "acquisition_time"); if (lookup) { theAcquisitionTime = lookup; } lookup = kwl.find(prefix, "sensor"); if (lookup) { theSensorID = lookup; } return true; } //***************************************************************************** // PROTECTED METHOD: ossimIkonosMetaData::parseMetaData() // // Parses the Ikonos metadata file. // //***************************************************************************** bool ossimIkonosMetaData::parseMetaData(const ossimFilename& data_file) { if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel::parseMetaData(data_file): entering..." << std::endl; } FILE* fptr = fopen (data_file, "r"); if (!fptr) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimIkonosRpcModel::parseMetaData(data_file) DEBUG:" << "\nCould not open Meta data file: " << data_file << "\nreturning with error..." << std::endl; } return false; } char* strptr; char dummy[80], name[80]; double value; //--- // Read the file into a buffer: //--- ossim_int32 fileSize = static_cast(data_file.fileSize()); char* filebuf = new char[fileSize]; fread(filebuf, 1, fileSize, fptr); fclose(fptr); //--- // Production date: //--- strptr = strstr(filebuf, "\nCreation Date:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseMetaData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed meta-data file." << std::endl; } delete [] filebuf; return false; } sscanf(strptr, "%15c %s", dummy, name); theProductionDate = name; //*** // Sensor Type: //*** strptr = strstr(strptr, "\nSensor:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseMetaData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed meta-data file." << std::endl; } delete [] filebuf; return false; } sscanf(strptr, "%8c %s", dummy, name); theSensorID = name; //*** // Nominal Azimuth: //*** strptr = strstr(strptr, "\nNominal Collection Azimuth:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseMetaData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed meta-data file." << std::endl; } delete [] filebuf; return false; } sscanf(strptr, "%28c %lf %s", dummy, &value, dummy); theNominalCollectionAzimuth = value; //*** // Nominal Elevation: //*** strptr = strstr(strptr, "\nNominal Collection Elevation:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseMetaData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed meta-data file." << std::endl; } delete [] filebuf; return false; } sscanf(strptr, "%31c %lf %s", dummy, &value, dummy); theNominalCollectionElevation = value; //*** // Sun Azimuth: //*** strptr = strstr(strptr, "\nSun Angle Azimuth:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseMetaData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed meta-data file." << std::endl; } delete [] filebuf; return false; } sscanf(strptr, "%19c %lf %s", dummy, &value, dummy); theSunAzimuth = value; //*** // Sun Elevation: //*** strptr = strstr(strptr, "\nSun Angle Elevation:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseMetaData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed meta-data file." << std::endl; } delete [] filebuf; return false; } sscanf(strptr, "%21c %lf %s", dummy, &value, name); theSunElevation = value; //--- // Acquisition date and time: //--- strptr = strstr(filebuf, "\nAcquisition Date/Time:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimIkonosRpcModel::parseMetaData(data_file): " << "\n\tAborting construction. Error encountered parsing " << "presumed meta-data file." << std::endl; } delete [] filebuf; return false; } char name2[80]; sscanf(strptr, "%23c %s %s", dummy, name, name2); theAcquisitionDate = name; theAcquisitionTime = name2; delete [] filebuf; filebuf = 0; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel::parseMetaData(data_file): returning..." << std::endl; } return true; } //***************************************************************************** // PROTECTED METHOD: ossimIkonosMetaData::parseHdrData() // // Parses the Ikonos hdr file. // //***************************************************************************** bool ossimIkonosMetaData::parseHdrData(const ossimFilename& data_file) { if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel::parseHdrData(data_file): entering..." << std::endl; } FILE* fptr = fopen (data_file, "r"); if (!fptr) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimIkonosRpcModel::parseHdrData(data_file) WARN:" << "\nCould not open hdr data file <" << data_file << ">. " << "returning with error..." << std::endl; } return false; } char* strptr; // char linebuf[80]; char dummy[80]; char name[80]; int value=0; //*** // Read the file into a buffer: //*** char filebuf[5000]; fread(filebuf, 1, 5000, fptr); fclose(fptr); //*** // Band name: //*** strptr = strstr(filebuf, "\nBand:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimIkonosRpcModel::parseHdrData(data_file):" << "\n\tAborting construction. Error encountered parsing " << "presumed hdr file." << std::endl; } return false; } sscanf(strptr, "%6c %s", dummy, name); theBandName = name; //*** // Number of Bands: //*** strptr = strstr(filebuf, "\nNumber of Bands:"); if (!strptr) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimIkonosRpcModel::parseHdrData(data_file):" << "\n\tAborting construction. Error encountered parsing " << "presumed hdr file." << std::endl; } return false; } sscanf(strptr, "%17c %d", dummy, &value); theNumBands = value; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimIkonosRpcModel::parseHdrData(data_file): returning..." << std::endl; } return true; } //***************************************************************************** // PROTECTED METHOD: ossimIkonosMetaData::parseRpcData() // // Parses the Ikonos rpc file. // //***************************************************************************** bool ossimIkonosMetaData::parseRpcData(const ossimFilename& /* data_file */) { return true; } ossim-Miami-2.9.1/src/support_data/ossimImageMetaData.cpp000066400000000000000000000352511352751253100234170ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: // // Contains class definition for ossimImageMetaData. // //******************************************************************* // $Id: ossimImageMetaData.cpp 21745 2012-09-16 15:21:53Z dburken $ #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug("ossimImageMetaData:debug"); ossimImageMetaData::ossimImageMetaData() :theNullPixelArray(0), theMinPixelArray(0), theMaxPixelArray(0), theMinValuesValidFlag(false), theMaxValuesValidFlag(false), theNullValuesValidFlag(false), theScalarType(OSSIM_SCALAR_UNKNOWN), theBytesPerPixel(0), theNumberOfBands(0), theRgbBands() { } ossimImageMetaData::ossimImageMetaData(ossimScalarType aType, ossim_uint32 numberOfBands) :theNullPixelArray(0), theMinPixelArray(0), theMaxPixelArray(0), theMinValuesValidFlag(false), theMaxValuesValidFlag(false), theNullValuesValidFlag(false), theScalarType(aType), theBytesPerPixel(0), theNumberOfBands(numberOfBands), theRgbBands() { if(theNumberOfBands) { theNullPixelArray = new double[theNumberOfBands]; theMinPixelArray = new double[theNumberOfBands]; theMaxPixelArray = new double[theNumberOfBands]; setDefaultsForArrays(); } theBytesPerPixel = ossim::scalarSizeInBytes( aType ); } ossimImageMetaData::ossimImageMetaData(const ossimImageMetaData& rhs) : theNullPixelArray(0), theMinPixelArray(0), theMaxPixelArray(0), theMinValuesValidFlag(rhs.theMinValuesValidFlag), theMaxValuesValidFlag(rhs.theMaxValuesValidFlag), theNullValuesValidFlag(rhs.theNullValuesValidFlag), theScalarType(rhs.theScalarType), theBytesPerPixel(rhs.theBytesPerPixel), theNumberOfBands(rhs.theNumberOfBands), theRgbBands(rhs.theRgbBands) { if(theNumberOfBands) { theNullPixelArray = new double[theNumberOfBands]; theMinPixelArray = new double[theNumberOfBands]; theMaxPixelArray = new double[theNumberOfBands]; std::copy(rhs.theNullPixelArray, rhs.theNullPixelArray+theNumberOfBands, theNullPixelArray); std::copy(rhs.theMinPixelArray, rhs.theMinPixelArray+theNumberOfBands, theMinPixelArray); std::copy(rhs.theMaxPixelArray, rhs.theMaxPixelArray+theNumberOfBands, theMaxPixelArray); } } const ossimImageMetaData& ossimImageMetaData::operator=( const ossimImageMetaData& rhs ) { if( this != &rhs ) { clear(); theMinValuesValidFlag = rhs.theMinValuesValidFlag; theMaxValuesValidFlag = rhs.theMaxValuesValidFlag; theNullValuesValidFlag = rhs.theNullValuesValidFlag; theNumberOfBands = rhs.theNumberOfBands; theScalarType = rhs.theScalarType; theBytesPerPixel = rhs.theBytesPerPixel; if(theNumberOfBands) { theNullPixelArray = new double[theNumberOfBands]; theMinPixelArray = new double[theNumberOfBands]; theMaxPixelArray = new double[theNumberOfBands]; std::copy(rhs.theNullPixelArray, rhs.theNullPixelArray+theNumberOfBands, theNullPixelArray); std::copy(rhs.theMinPixelArray, rhs.theMinPixelArray+theNumberOfBands, theMinPixelArray); std::copy(rhs.theMaxPixelArray, rhs.theMaxPixelArray+theNumberOfBands, theMaxPixelArray); } theRgbBands = rhs.theRgbBands; } return *this; } ossimImageMetaData::~ossimImageMetaData() { clear(); } void ossimImageMetaData::clear() { if(theNullPixelArray) { delete [] theNullPixelArray; theNullPixelArray = 0; } if(theMinPixelArray) { delete [] theMinPixelArray; theMinPixelArray = 0; } if(theMaxPixelArray) { delete [] theMaxPixelArray; theMaxPixelArray = 0; } theScalarType = OSSIM_SCALAR_UNKNOWN; theBytesPerPixel = 0; theNumberOfBands = 0; theRgbBands.clear(); } void ossimImageMetaData::setDefaultsForArrays() { ossim_uint32 i=0; for(i = 0; i < theNumberOfBands; ++i) { theNullPixelArray[i] = ossim::defaultNull(theScalarType); theMinPixelArray[i] = ossim::defaultMin(theScalarType); theMaxPixelArray[i] = ossim::defaultMax(theScalarType); } } void ossimImageMetaData::setNumberOfBands(ossim_uint32 numberOfBands) { if(theNullPixelArray) { delete [] theNullPixelArray; theNullPixelArray = 0; } if(theMinPixelArray) { delete [] theMinPixelArray; theMinPixelArray = 0; } if(theMaxPixelArray) { delete [] theMaxPixelArray; theMaxPixelArray = 0; } theNumberOfBands = numberOfBands; if(theNumberOfBands) { theNullPixelArray = new double[theNumberOfBands]; theMinPixelArray = new double[theNumberOfBands]; theMaxPixelArray = new double[theNumberOfBands]; setDefaultsForArrays(); } } bool ossimImageMetaData::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = false; // return status // Clear the object: clear(); std::string pfx = ( prefix ? prefix : "" ); theRgbBands = kwl.findKey( pfx, std::string("rgb_bands") ); ossim_uint32 bands = getBandCount( kwl, pfx ); if ( bands ) { result = true; setNumberOfBands( bands ); theMinValuesValidFlag = true; theMaxValuesValidFlag = true; theNullValuesValidFlag = true; updateMetaData( kwl, pfx ); // Initializes the rest of object. } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << " ERROR:\n" << "Required keyword not found: " << ossimKeywordNames::NUMBER_BANDS_KW << std::endl; } } if (traceDebug()) { print( ossimNotify(ossimNotifyLevel_DEBUG) ); } return result; } bool ossimImageMetaData::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "type", "ossimImageMetaData", true); if ( theNumberOfBands ) { ossim_uint32 band = 0; for (band=0; band < theNumberOfBands; ++band) { ossimString kwMin = (ossimKeywordNames::BAND_KW + ossimString::toString(band+1) + "." + ossimKeywordNames::MIN_VALUE_KW); ossimString kwMax = (ossimKeywordNames::BAND_KW + ossimString::toString(band+1) + "." + ossimKeywordNames::MAX_VALUE_KW); ossimString kwNull = (ossimKeywordNames::BAND_KW + ossimString::toString(band+1) + "." + ossimKeywordNames::NULL_VALUE_KW); kwl.add(prefix, kwMin.c_str(), theMinPixelArray[band], true); kwl.add(prefix, kwMax.c_str(), theMaxPixelArray[band], true); kwl.add(prefix, kwNull.c_str(), theNullPixelArray[band], true); } // std::cout << "added bands ******************" << std::endl; kwl.add(prefix, ossimKeywordNames::NUMBER_BANDS_KW, theNumberOfBands, true); kwl.add(prefix, ossimKeywordNames::SCALAR_TYPE_KW, (ossimScalarTypeLut::instance()->getEntryString(theScalarType)), true); kwl.add( prefix, "bytes_per_pixel", theBytesPerPixel, true ); } if ( theRgbBands.size() ) { kwl.add( prefix, "rgb_bands", theRgbBands.c_str(), true ); } return true; } ossim_uint32 ossimImageMetaData::getNumberOfBands()const { return theNumberOfBands; } const std::string& ossimImageMetaData::getRgbBands() const { return theRgbBands; } bool ossimImageMetaData::getRgbBands(std::vector& bandList) const { bool result = false; if ( ( theNumberOfBands > 2) && theRgbBands.size() ) { ossim::toSimpleVector( bandList, ossimString(theRgbBands) ); if ( bandList.size() == 3 ) { result = true; } else { bandList.clear(); } } return result; } void ossimImageMetaData::setScalarType(ossimScalarType aType) { theScalarType = aType; theBytesPerPixel = ossim::scalarSizeInBytes( aType ); } ossimScalarType ossimImageMetaData::getScalarType()const { return theScalarType; } ossim_uint32 ossimImageMetaData::getBytesPerPixel() const { return theBytesPerPixel; } void ossimImageMetaData::setMinPix(ossim_uint32 band, double pix) { if((band < theNumberOfBands)&&(theMinPixelArray)) { theMinPixelArray[band] = pix; } } void ossimImageMetaData::setMaxPix(ossim_uint32 band, double pix) { if((band < theNumberOfBands) && theMaxPixelArray) { theMaxPixelArray[band] = pix; } } void ossimImageMetaData::setNullPix(ossim_uint32 band, double pix) { if((band < theNumberOfBands)&&(theNullPixelArray)) { theNullPixelArray[band] = pix; } } double ossimImageMetaData::getMinPix(ossim_uint32 band)const { if(theNumberOfBands&&theMinPixelArray) { ossim_uint32 i = ossim::min(band, (ossim_uint32)(theNumberOfBands-1)); return theMinPixelArray[i]; } return ossim::defaultMin(theScalarType); } double ossimImageMetaData::getMaxPix(ossim_uint32 band)const { if(theNumberOfBands&&theMaxPixelArray) { ossim_uint32 i = ossim::min(band, (ossim_uint32)(theNumberOfBands-1)); return theMaxPixelArray[i]; } return ossim::defaultMax(theScalarType); } double ossimImageMetaData::getNullPix(ossim_uint32 band)const { if(theNumberOfBands&&theNullPixelArray) { ossim_uint32 i = ossim::min(band, (ossim_uint32)(theNumberOfBands-1)); return theNullPixelArray[i]; } return ossim::defaultNull(theScalarType); } const double* ossimImageMetaData::getMinPixelArray()const { return theMinPixelArray; } const double* ossimImageMetaData::getMaxPixelArray()const { return theMaxPixelArray; } const double* ossimImageMetaData::getNullPixelArray()const { return theNullPixelArray; } void ossimImageMetaData::setMinValuesValid(bool flag) { theMinValuesValidFlag = flag; } void ossimImageMetaData::setMaxValuesValid(bool flag) { theMaxValuesValidFlag = flag; } void ossimImageMetaData::setNullValuesValid(bool flag) { theNullValuesValidFlag = flag; } bool ossimImageMetaData::getMinValuesValidFlag()const { return theMinValuesValidFlag; } bool ossimImageMetaData::getMaxValuesValidFlag()const { return theMaxValuesValidFlag; } bool ossimImageMetaData::getNullValuesValidFlag()const { return theNullValuesValidFlag; } bool ossimImageMetaData::isValid()const { return (theNumberOfBands > 0); // return ((theNumberOfBands>0)&& // (theScalarType != OSSIM_SCALAR_UNKNOWN)); } void ossimImageMetaData::updateMetaData( const ossimKeywordlist& kwl, const std::string& prefix ) { ossimString value; std::string key; // Get the bands: if ( !theNumberOfBands ) { ossim_uint32 bands = getBandCount( kwl, prefix ); if ( bands ) { setNumberOfBands( bands ); } } if ( theNumberOfBands ) { //--- // See if bands are zero or one based. Bands are ONE based in the "omd" // file! If band0 is present assume zero based. //--- ossimString regExpression = std::string("^(") + prefix + std::string("band0+.)"); std::vector keys = kwl.getSubstringKeyList( regExpression ); ossim_uint32 startBand = (keys.size() ? 0 : 1); ossim_uint32 limit = theNumberOfBands+startBand; // For for loop: std::string bs = "band"; // band sting std::string base; for ( ossim_uint32 band = startBand; band < limit; ++band ) { base = bs + ossimString::toString( band ).string() + std::string(".") ; // Min: key = base + std::string(ossimKeywordNames::MIN_VALUE_KW); value = kwl.findKey( prefix, key ); if ( value.size() ) { theMinPixelArray[ band - startBand ] = value.toFloat64(); } // Max: key = base + std::string(ossimKeywordNames::MAX_VALUE_KW); value = kwl.findKey( prefix, key ); if ( value.size() ) { theMaxPixelArray[ band - startBand ] = value.toFloat64(); } // Null: key = base + std::string(ossimKeywordNames::NULL_VALUE_KW); value = kwl.findKey( prefix, key ); if ( value.size() ) { theNullPixelArray[ band - startBand ] = value.toFloat64(); } } } // Scalar, only look for if not set. if ( theScalarType == OSSIM_SCALAR_UNKNOWN ) { key = ossimKeywordNames::SCALAR_TYPE_KW; // "scalar_type" value.string() = kwl.findKey( prefix, key ); if ( value.empty() ) { key = "radiometry"; value.string() = kwl.findKey( prefix, key ); } if ( value.size() ) { theScalarType = ossimScalarTypeLut::instance()->getScalarTypeFromString( value ); } if ( theScalarType != OSSIM_SCALAR_UNKNOWN ) { theBytesPerPixel = ossim::scalarSizeInBytes( theScalarType ); } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimImageMetaData::updateMetaData DEBUG" << *this << std::endl; } } std::ostream& ossimImageMetaData::print(std::ostream& out) const { ossimKeywordlist kwl; saveState( kwl, 0 ); out << kwl << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const ossimImageMetaData& obj) { return obj.print( out ); } ossim_uint32 ossimImageMetaData::getBandCount(const ossimKeywordlist& kwl, const std::string& prefix) const { ossim_uint32 result = 0; ossimString value; value.string() = kwl.findKey( prefix, std::string(ossimKeywordNames::NUMBER_BANDS_KW) ); if ( value.size() ) { result = value.toUInt32(); } else { value.string() = std::string("^(") + prefix + std::string("band[0-9]+.)"); std::vector keys = kwl.getSubstringKeyList( value ); result = static_cast( keys.size() ); } return result; } ossim-Miami-2.9.1/src/support_data/ossimInfoBase.cpp000066400000000000000000000033431352751253100224570ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Base class for Info object. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include ossimInfoBase::ossimInfoBase() : theOverviewFlag(true) {} ossimInfoBase::~ossimInfoBase() {} bool ossimInfoBase::open(const ossimFilename& file) { std::string connectionString = file.c_str(); std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( file.c_str(), std::ios_base::in|std::ios_base::binary); if(!str) return false; return open(str, connectionString); } bool ossimInfoBase::open(std::shared_ptr& /* str */, const std::string& /* connectionString */) { return false; } void ossimInfoBase::setProcessOverviewFlag(bool flag) { theOverviewFlag = flag; } bool ossimInfoBase::getProcessOverviewFlag() const { return theOverviewFlag; } bool ossimInfoBase::getKeywordlist(ossimKeywordlist& kwl)const { // Do a print to a memory stream. std::ostringstream out; print(out); std::istringstream in(out.str()); // Give the result to the keyword list. return kwl.parseStream(in); } bool ossimInfoBase::getKeywordlist(ossimKeywordlist& kwl, ossim_uint32 /* entryIndex */ )const { // If this gets hit the specific info object does not support entry indexes. return getKeywordlist( kwl ); } ossim-Miami-2.9.1/src/support_data/ossimInfoFactory.cpp000066400000000000000000000161431352751253100232160ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Factory for info objects. // //---------------------------------------------------------------------------- // $Id: ossimInfoFactory.cpp 22118 2013-01-18 21:05:14Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if OSSIM_HAS_HDF5 # include #endif ossimInfoFactory* ossimInfoFactory::theInstance = 0; ossimInfoFactory::~ossimInfoFactory() {} ossimInfoFactory* ossimInfoFactory::instance() { if ( !theInstance ) { theInstance = new ossimInfoFactory; } return theInstance; } std::shared_ptr ossimInfoFactory::create(std::shared_ptr& str, const std::string& connectionString) const { std::shared_ptr result(0); if ( str ) { str->clear(); str->seekg(0); result = std::make_shared(); if ( result->open(str, connectionString) ) { return result; } else { result.reset(); } str->clear(); str->seekg(0); result = std::make_shared(); if ( result->open(str, connectionString) ) { return result; } else { result.reset(); } str->clear(); str->seekg(0); result = std::make_shared(); if ( result->open(str, connectionString) ) { return result; } else { result.reset(); } str->clear(); str->seekg(0); result = std::make_shared(); if ( result->open(str, connectionString) ) { return result; } else { result.reset(); } str->clear(); str->seekg(0); result = std::make_shared(); if ( result->open(str, connectionString) ) { return result; } else { result.reset(); } str->clear(); str->seekg(0); result = std::make_shared(); if ( result->open(str, connectionString) ) { return result; } else { result.reset(); } str->clear(); str->seekg(0); } return result; } std::shared_ptr ossimInfoFactory::create(const ossimFilename& file) const { std::shared_ptr result(0); result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } #if OSSIM_HAS_HDF5 result = std::make_shared(); if ( result->open( file ) ) { return result; } else { result.reset(); } #endif return result; } #if 0 ossimInfoBase* ossimInfoFactory::create(const ossimFilename& file) const { ossimRefPtr result = 0; result = new ossimTiffInfo(); if ( result->open(file) ) { return result.release(); } result = new ossimJp2Info(); if ( result->open(file) ) { return result.release(); } result = new ossimNitfInfo(); if ( result->open(file) ) { return result.release(); } result = new ossimDemInfo(); if ( result->open(file) ) { return result.release(); } result = new ossimDtedInfo(); if ( result->open(file) ) { return result.release(); } result = new ossimEnviInfo(); if ( result->open(file) ) { return result.release(); } result = new ossimRpfInfo(); if ( result->open(file) ) { return result.release(); } result = new ossimXmpInfo(); if ( result->open(file) ) { return result.release(); } result = new ossimLasInfo(); if ( result->open(file) ) { return result.release(); } result = new ossimDoqq(); if ( result->open(file) ) { return result.release(); } result = new ossimJ2kInfo(); if ( result->open(file) ) { return result.release(); } result = new ossimCcfInfo(); if ( result->open(file) ) { return result.release(); } #if OSSIM_HAS_HDF5 result = new ossimHdf5Info(); if ( result->open(file) ) { return result.release(); } #endif return 0; } #endif ossimInfoFactory::ossimInfoFactory() {} ossimInfoFactory::ossimInfoFactory(const ossimInfoFactory& /* obj */ ) {} const ossimInfoFactory& ossimInfoFactory::operator=( const ossimInfoFactory& /* rhs */) { return *this; } ossim-Miami-2.9.1/src/support_data/ossimInfoFactoryRegistry.cpp000066400000000000000000000066651352751253100247570ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Class definition of registry (singleton) for info factories. // //--- // $Id$ #include #include #include #include #include #include #include #include /* for std::find */ ossimInfoFactoryRegistry* ossimInfoFactoryRegistry::m_instance = 0; ossimInfoFactoryRegistry::~ossimInfoFactoryRegistry() { m_factoryList.clear(); } ossimInfoFactoryRegistry* ossimInfoFactoryRegistry::instance() { if ( !m_instance ) { m_instance = new ossimInfoFactoryRegistry; } return m_instance; } void ossimInfoFactoryRegistry::registerFactory( ossimInfoFactoryInterface* factory) { if (factory) { m_mutex.lock(); m_factoryList.push_back(factory); m_mutex.unlock(); } } void ossimInfoFactoryRegistry::registerFactoryToFront( ossimInfoFactoryInterface* factory) { if (factory) { m_mutex.lock(); m_factoryList.insert( m_factoryList.begin(), factory ); m_mutex.unlock(); } } void ossimInfoFactoryRegistry::unregisterFactory( ossimInfoFactoryInterface* factory) { m_mutex.lock(); std::vector::iterator i = std::find(m_factoryList.begin(), m_factoryList.end(), factory); if( i != m_factoryList.end() ) { m_factoryList.erase(i); } m_mutex.unlock(); } std::shared_ptr ossimInfoFactoryRegistry::create( const ossimFilename& file) const { std::shared_ptr result(0); std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( file.c_str(), std::ios_base::in|std::ios_base::binary ); if ( str ) { std::string connectionString = file.c_str(); result = create( str, connectionString ); str.reset(); } if(!result) { std::vector::const_iterator i = m_factoryList.begin(); while ( i != m_factoryList.end() ) { result = (*i)->create( file ); if ( result ) { break; } ++i; } } return result; } std::shared_ptr ossimInfoFactoryRegistry::create( std::shared_ptr& str, const std::string& connectionString) const { std::shared_ptr result(0); if ( str ) { std::vector::const_iterator i = m_factoryList.begin(); while ( i != m_factoryList.end() ) { result = (*i)->create(str, connectionString); if ( result ) { break; } str->clear(); str->seekg(0); ++i; } } return result; } /** hidden from use default constructor */ ossimInfoFactoryRegistry::ossimInfoFactoryRegistry() : m_factoryList(), m_mutex() { this->registerFactory(ossimInfoFactory::instance()); } /** hidden from use copy constructor */ ossimInfoFactoryRegistry::ossimInfoFactoryRegistry( const ossimInfoFactoryRegistry& /* obj */) {} /** hidden from use operator = */ const ossimInfoFactoryRegistry& ossimInfoFactoryRegistry::operator=( const ossimInfoFactoryRegistry& /* rhs */ ) { return *this; } ossim-Miami-2.9.1/src/support_data/ossimJ2kCodRecord.cpp000066400000000000000000000076471352751253100232170ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Container class for J2K Coding style default (COD) record. // // See document BPJ2K01.00 Table 7-7 Image and tile size (15444-1 Annex A5.1) // //--- // $Id$ #include #include #include #include #include #include ossimJ2kCodRecord::ossimJ2kCodRecord() : m_marker(0xff52), m_lcod(0), m_scod(0), m_progressionOrder(0), m_numberOfLayers(0), m_multipleComponentTransform(0), m_numberOfDecompositionLevels(0), m_codeBlockWidth(0), m_codeBlockHeight(0), m_codeBlockStyle(0), m_transformation(0), m_precinctSize(0) { } ossimJ2kCodRecord::~ossimJ2kCodRecord() { } void ossimJ2kCodRecord::parseStream(std::istream& in) { // Get the stream posistion. std::streamoff pos = in.tellg(); // Note: Marker is not read. in.read((char*)&m_lcod, 2); in.read((char*)&m_scod, 1); in.read((char*)&m_progressionOrder, 1); in.read((char*)&m_numberOfLayers, 2); in.read((char*)&m_multipleComponentTransform, 1); in.read((char*)&m_numberOfDecompositionLevels, 1); in.read((char*)&m_codeBlockWidth, 1); in.read((char*)&m_codeBlockHeight, 1); in.read((char*)&m_codeBlockStyle, 1); in.read((char*)&m_transformation, 1); //--- // SPcod - precinct size (only is defined, Scod = xxxx xxx1) //--- if ( 0 ) { in.read((char*)&m_precinctSize, 1); } if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) { // Stored big endian, must swap. ossimEndian s; s.swap(m_lcod); s.swap(m_numberOfLayers); } //--- // Seek to next record. This is needed because there are sometimes extra // bytes. //--- in.seekg(pos + m_lcod, std::ios_base::beg); } std::ostream& ossimJ2kCodRecord::print(std::ostream& out, const std::string& prefix) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); std::string pfx = prefix; pfx += "cod."; out.setf(std::ios_base::hex, std::ios_base::basefield); out << pfx << "marker: 0xff90\n"; out.setf(std::ios_base::fmtflags(0), std::ios_base::basefield); out << pfx << "Lcod: " << m_lcod << "\n" << pfx << "Scod: " << int(m_scod) << "\n" << pfx << "SGcod_progression_order: " << getProgressionOrderAsString(m_progressionOrder) << "\n" << pfx << "SGcod_number_of_layers: " << m_numberOfLayers << "\n" << pfx << "SGcod_multiple_component_transform: " << int(m_multipleComponentTransform) << "\n" << pfx << "SPcod_mumber_of_decomposition_levels: " << int(m_numberOfDecompositionLevels) << "\n" << pfx << "SPcod_code_block_width: " << int(m_codeBlockWidth) << "\n" << pfx << "SPcod_code_block_height: " << int(m_codeBlockHeight) << "\n" << pfx << "SPcod_code_block_style: " << int(m_codeBlockStyle) << "\n" << pfx << "SPcod_transformation: " << int(m_transformation) << "\n" << pfx << "SPcod_precinct_size: " << int(m_precinctSize) << std::endl; // Reset flags. out.setf(f); return out; } std::string ossimJ2kCodRecord::getProgressionOrderAsString( ossim_uint8 progressionOrder ) const { std::string result; if ( progressionOrder == 0x00 ) { result = "LRCP"; } else if ( progressionOrder == 0x01 ) { result = "RLCP"; } else if ( progressionOrder == 0x02 ) { result = "RPCL"; } else if ( progressionOrder == 0x03 ) { result = "PCRL"; } else if ( progressionOrder == 0x04 ) { result = "CPRL"; } else { result = "unknown"; } return result; } ossim_uint8 ossimJ2kCodRecord::getProgressionOrder() const { return m_progressionOrder; } std::ostream& operator<<(std::ostream& out, const ossimJ2kCodRecord& obj) { return obj.print(out); } ossim-Miami-2.9.1/src/support_data/ossimJ2kInfo.cpp000066400000000000000000000135411352751253100222340ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: J2K Info object. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include // #include #include #include #include #include #include #include #include // Static trace for debugging static ossimTrace traceDebug("ossimJ2kInfo:debug"); static ossimTrace traceDump("ossimJ2kInfo:dump"); // This will dump offsets. ossimJ2kInfo::ossimJ2kInfo() : ossimInfoBase(), m_file(), m_endian(0) { // See if we need to byte swap. J2k, JP2 boxes are big endian. if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) { m_endian = new ossimEndian(); } } ossimJ2kInfo::~ossimJ2kInfo() { if (m_endian) { delete m_endian; m_endian = 0; } } bool ossimJ2kInfo::open(const ossimFilename& file) { bool result = false; //--- // Open the file. //--- std::ifstream str(file.c_str(), std::ios_base::binary|std::ios_base::in); if (str.good()) { //--- // Check for the Start Of Codestream (SOC) and Size (SIZ) markers which // are required as first and second fields in the main header. //--- ossim_uint16 soc; ossim_uint16 siz; readUInt16(soc, str); readUInt16(siz, str); const ossim_uint16 SOC_MARKER = 0xff4f; // start of codestream marker const ossim_uint16 SIZ_MARKER = 0xff51; // size maker if ( (soc == SOC_MARKER) && (siz == SIZ_MARKER) ) { result = true; // Is a j2k... } } if (result) { m_file = file; } else { m_file.clear(); if (m_endian) { delete m_endian; m_endian = 0; } } return result; } std::ostream& ossimJ2kInfo::print(std::ostream& out) const { static const char MODULE[] = "ossimJ2kInfo::print"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG Entered...\n"; } if ( m_file.size() ) { // Open the file. std::ifstream str(m_file.c_str(), std::ios_base::binary|std::ios_base::in); if (str.good()) { ossim_uint16 marker; readUInt16(marker, str); // SOC readUInt16(marker, str); // SIZ std::string prefix = "j2k."; // SIZ marker required next. printSizMarker(out, prefix, str); readUInt16(marker, str); const ossim_uint16 COD_MARKER = 0xff52; // cod maker const ossim_uint16 EOC_MARKER = 0xffd9; // End of codestream marker. const ossim_uint16 SOT_MARKER = 0xff90; // start of tile marker while ( str.good() && (marker != EOC_MARKER) ) { switch(marker) { case COD_MARKER: { printCodMarker(out, prefix, str); break; } case SOT_MARKER: { printSotMarker(out, prefix, str); break; } default: { printUnknownMarker(out, prefix, str, marker); } } readUInt16(marker, str); } } } return out; } void ossimJ2kInfo::readUInt16(ossim_uint16& s, std::ifstream& str) const { str.read((char*)&s, 2); if (m_endian) { m_endian->swap(s); } } std::ostream& ossimJ2kInfo::printCodMarker(std::ostream& out, const std::string& prefix, std::ifstream& str) const { ossimJ2kCodRecord siz; siz.parseStream(str); siz.print(out, prefix); return out; } std::ostream& ossimJ2kInfo::printSizMarker(std::ostream& out, const std::string& prefix, std::ifstream& str) const { ossimJ2kSizRecord siz; siz.parseStream(str); siz.print(out, prefix); return out; } std::ostream& ossimJ2kInfo::printSotMarker(std::ostream& out, const std::string& prefix, std::ifstream& str) const { // Get the stream posistion. std::streamoff pos = str.tellg(); ossimJ2kSotRecord sot; sot.parseStream(str); pos += sot.thePsot - 2; // Seek past the tile to the next marker. str.seekg(pos, std::ios_base::beg); sot.print(out,prefix); return out; } std::ostream& ossimJ2kInfo::printUnknownMarker(std::ostream& out, const std::string& prefix, std::ifstream& str, ossim_uint16 marker) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); ossim_uint16 segmentLength; readUInt16(segmentLength, str); std::string pfx = prefix; pfx += "unknown."; out.setf(std::ios_base::hex, std::ios_base::basefield); out << pfx << "marker: 0x" << std::setfill('0') << std::setw(4) << marker << "\n"; out.setf(std::ios_base::fmtflags(0), std::ios_base::basefield); out << pfx << "length: " << segmentLength << std::endl; // Reset flags. out.setf(f); // Seek to the next marker. str.seekg( (segmentLength-2), std::ios_base::cur); return out; } ossim-Miami-2.9.1/src/support_data/ossimJ2kSizRecord.cpp000066400000000000000000000153531352751253100232500ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Container class for J2K Image and tile size (SIZ) record. // // See document BPJ2K01.00 Table 7-6 Image and tile size (15444-1 Annex A5.1) // //--- // $Id$ #include #include #include #include #include #include #include ossimJ2kSizRecord::ossimJ2kSizRecord() : m_marker(0xff51), m_Lsiz(0), m_Rsiz(0), m_Xsiz(0), m_Ysiz(0), m_XOsiz(0), m_YOsiz(0), m_XTsiz(0), m_YTsiz(0), m_XTOsiz(0), m_YTOsiz(0), m_Csiz(0), m_Ssiz(0), m_XRsiz(0), m_YRsiz(0) { } ossimJ2kSizRecord::~ossimJ2kSizRecord() { } void ossimJ2kSizRecord::parseStream(ossim::istream& in) { // Note: Marker is not read. in.read((char*)&m_Lsiz, 2); in.read((char*)&m_Rsiz, 2); in.read((char*)&m_Xsiz, 4); in.read((char*)&m_Ysiz, 4); in.read((char*)&m_XOsiz, 4); in.read((char*)&m_YOsiz, 4); in.read((char*)&m_XTsiz, 4); in.read((char*)&m_YTsiz, 4); in.read((char*)&m_XTOsiz, 4); in.read((char*)&m_YTOsiz, 4); in.read((char*)&m_Csiz, 2); if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) { // Stored in file big endian, must swap. ossimEndian s; s.swap(m_Lsiz); s.swap(m_Rsiz); s.swap(m_Xsiz); s.swap(m_Ysiz); s.swap(m_XOsiz); s.swap(m_YOsiz); s.swap(m_XTsiz); s.swap(m_YTsiz); s.swap(m_XTOsiz); s.swap(m_YTOsiz); s.swap(m_Csiz); } m_Ssiz.resize( m_Csiz ); in.read((char*)&m_Ssiz.front(), m_Csiz); m_XRsiz.resize( m_Csiz ); in.read((char*)&m_XRsiz.front(), m_Csiz); m_YRsiz.resize( m_Csiz ); in.read((char*)&m_YRsiz.front(), m_Csiz); } void ossimJ2kSizRecord::writeStream(std::ostream& out) { // Length of this marker segment(marker not included): m_Lsiz = 38 + 3*m_Csiz; // Grab component count before swapping: ossim_uint16 components = m_Csiz; ossimEndian* s = 0; if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) { // Stored in file big endian, must swap. s = new ossimEndian(); s->swap(m_Lsiz); s->swap(m_Rsiz); s->swap(m_Xsiz); s->swap(m_Ysiz); s->swap(m_XOsiz); s->swap(m_YOsiz); s->swap(m_XTsiz); s->swap(m_YTsiz); s->swap(m_XTOsiz); s->swap(m_YTOsiz); s->swap(m_Csiz); } out.put( 0xff ); out.put( 0x51 ); // out.write( (char*)&m_marker, 2 ); out.write((char*)&m_Lsiz, 2); out.write((char*)&m_Rsiz, 2); out.write((char*)&m_Xsiz, 4); out.write((char*)&m_Ysiz, 4); out.write((char*)&m_XOsiz, 4); out.write((char*)&m_YOsiz, 4); out.write((char*)&m_XTsiz, 4); out.write((char*)&m_YTsiz, 4); out.write((char*)&m_XTOsiz, 4); out.write((char*)&m_YTOsiz, 4); out.write((char*)&m_Csiz, 2); out.write((char*)&m_Ssiz.front(), components); out.write((char*)&m_XRsiz.front(), components); out.write((char*)&m_YRsiz.front(), components); if ( s ) { // Swap it back to native. s->swap(m_Lsiz); s->swap(m_Rsiz); s->swap(m_Xsiz); s->swap(m_Ysiz); s->swap(m_XOsiz); s->swap(m_YOsiz); s->swap(m_XTsiz); s->swap(m_YTsiz); s->swap(m_XTOsiz); s->swap(m_YTOsiz); s->swap(m_Csiz); // Cleanup: delete s; s = 0; } } ossimScalarType ossimJ2kSizRecord::getScalarType() const { // Currently assumes all components the same scalar type. ossimScalarType result = OSSIM_SCALAR_UNKNOWN; if ( m_Ssiz.size() ) { // Bits per pixel first seven bits plus one. ossim_uint8 bpp = ( m_Ssiz[0] & 0x3f ) + 1; // Signed bit is msb. bool isSigned = ( m_Ssiz[0] & 0x80 ) ? true : false; if ( bpp <= 8 ) { if ( isSigned == 0 ) { result = OSSIM_UINT8; } else if (isSigned == 1) { result = OSSIM_SINT8; } } else if ( bpp == 11 ) { if ( isSigned == 0 ) { result = OSSIM_USHORT11; } else { result = OSSIM_SINT16; } } else if ( bpp == 12 ) { if ( isSigned == 0 ) { result = OSSIM_USHORT12; } else { result = OSSIM_SINT16; } } else if ( bpp == 13 ) { if ( isSigned == 0 ) { result = OSSIM_USHORT13; } else { result = OSSIM_SINT16; } } else if ( bpp == 14 ) { if ( isSigned == 0 ) { result = OSSIM_USHORT14; } else { result = OSSIM_SINT16; } } else if ( bpp == 15 ) { if ( isSigned == 0 ) { result = OSSIM_USHORT15; } else { result = OSSIM_SINT16; } } else if( bpp <= 16 ) { if( isSigned == 0 ) { result = OSSIM_UINT16; } else if( isSigned == 1 ) { result = OSSIM_SINT16; } } } return result; } std::ostream& ossimJ2kSizRecord::print(std::ostream& out, const std::string& prefix) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); std::string pfx = prefix; pfx += "siz."; out.setf(std::ios_base::hex, std::ios_base::basefield); out << pfx << "marker: 0x" << m_marker << "\n"; out.setf(std::ios_base::fmtflags(0), std::ios_base::basefield); out << pfx << "Lsiz: " << m_Lsiz << "\n" << pfx << "Rsiz: " << m_Rsiz << "\n" << pfx << "Xsiz: " << m_Xsiz << "\n" << pfx << "Yziz: " << m_Ysiz << "\n" << pfx << "XOsiz: " << m_XOsiz << "\n" << pfx << "YOsiz: " << m_YOsiz << "\n" << pfx << "XTsiz: " << m_XTsiz << "\n" << pfx << "YTsiz: " << m_YTsiz << "\n" << pfx << "XTOsiz: " << m_XTOsiz << "\n" << pfx << "YTOsiz: " << m_YTOsiz << "\n" << pfx << "Csiz: " << m_Csiz << "\n"; for ( ossim_uint16 i = 0; i < m_Csiz; ++i ) { out << pfx << "Ssiz[" << i << "]: " << int(m_Ssiz[i]) << "\n" << pfx << "XRsiz[" << i << "]: " << int(m_XRsiz[i]) << "\n" << pfx << "YRsiz[" << i << "]: " << int(m_YRsiz[i]) << "\n"; } out.flush(); // Reset flags. out.setf(f); return out; } std::ostream& operator<<(std::ostream& out, const ossimJ2kSizRecord& obj) { return obj.print(out); } ossim-Miami-2.9.1/src/support_data/ossimJ2kSotRecord.cpp000066400000000000000000000054171352751253100232500ustar00rootroot00000000000000//--- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Container class for J2K "Start Of Tile" (SOT) record. // // marker: FF90 // // See document BPJ2K01.00 Table 7-3 Image and tile size (15444-1 Annex A.4.2) // //--- // $Id$ #include #include #include #include #include ossimJ2kSotRecord::ossimJ2kSotRecord() : theLsot(0), theIsot(0), thePsot(0), theTpsot(0), theTnsot(0) { } ossimJ2kSotRecord::~ossimJ2kSotRecord() { } void ossimJ2kSotRecord::parseStream(std::istream& in) { // Note: marker not read... in.read((char*)&theLsot, 2); in.read((char*)&theIsot, 2); in.read((char*)&thePsot, 4); in.read((char*)&theTpsot, 1); in.read((char*)&theTnsot, 1); if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) { // Stored big endian, must swap. ossimEndian endian; endian.swap(theLsot); endian.swap(theIsot); endian.swap(thePsot); } } void ossimJ2kSotRecord::writeStream(std::ostream& out) { ossimEndian* endian = 0; if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) { // Stored in file big endian, must swap. endian = new ossimEndian(); endian->swap( theLsot ); endian->swap( theIsot ); endian->swap( thePsot ); } // Marker 0xff90: out.put( 0xff ); out.put( 0x90 ); out.write( (char*)&theLsot, 2); out.write( (char*)&theIsot, 2); out.write( (char*)&thePsot, 4); out.write( (char*)&theTpsot, 1); out.write( (char*)&theTnsot, 1); if ( endian ) { // Swap back to native: endian->swap(theLsot); endian->swap(theIsot); endian->swap(thePsot); delete endian; endian = 0; } } void ossimJ2kSotRecord::setIsot( ossim_uint16 isot ) { theIsot = isot; } std::ostream& ossimJ2kSotRecord::print(std::ostream& out, const std::string& prefix) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); std::string pfx = prefix; pfx += "sot."; out.setf(std::ios_base::hex, std::ios_base::basefield); out << pfx << "marker: 0xff90\n"; out.setf(std::ios_base::fmtflags(0), std::ios_base::basefield); out << pfx << "Lsot: " << theLsot << "\n" << pfx << "Isot: " << theIsot << "\n" << pfx << "Psot: " << thePsot << "\n" << pfx << "Tpsot: " << int(theTpsot) << "\n" << pfx << "Tnsot: " << int(theTnsot) << std::endl; // Reset flags. out.setf(f); return out; } std::ostream& operator<<(std::ostream& out, const ossimJ2kSotRecord& obj) { return obj.print(out); } ossim-Miami-2.9.1/src/support_data/ossimJ2kTlmRecord.cpp000066400000000000000000000267131352751253100232410ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: Container class definition for J2K Tile-part lengths record. // See document BPJ2K01.10 Table 7-21 for detailed description. // // $Id$ //--- #include #include #include #include #include #include #include #include #include ossimJ2kTlmRecord::ossimJ2kTlmRecord() : m_Ltlm(0), m_Ztlm(0), m_Stlm(0x40), // Tiles in order 32 bit Ptlm m_Ttlm(0), m_Ptlm(0) { } ossimJ2kTlmRecord::~ossimJ2kTlmRecord() { clear(); } void ossimJ2kTlmRecord::clear() { clearTtlm(); clearPtlm(); } void ossimJ2kTlmRecord::clearTtlm() { if ( m_Ttlm ) { ossim_uint8 st = getSt(); if ( st == 1 ) { ossim_uint8* p = (ossim_uint8*)m_Ttlm; delete [] p; } else if ( st == 2 ) { ossim_uint16* p = (ossim_uint16*)m_Ttlm; delete [] p; } m_Ttlm = 0; } } void ossimJ2kTlmRecord::clearPtlm() { if ( m_Ptlm ) { ossim_uint8 sp = getSp(); if ( sp == 0 ) { ossim_uint16* p = (ossim_uint16*)m_Ptlm; delete [] p; } else if ( sp == 1 ) { ossim_uint32* p = (ossim_uint32*)m_Ptlm; delete [] p; } m_Ptlm = 0; } } void ossimJ2kTlmRecord::parseStream(ossim::istream& in) { clear(); // Deletes m_Ttlm and m_Ptlm arrays if they exist. ossimEndian* endian = 0; if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) { // Stored big endian, must swap. endian = new ossimEndian(); } // Get the stream posistion. std::streamoff pos = in.tellg(); // Note: Marker is not read. // Length of segment minus marker. in.read((char*)&m_Ltlm, 2); if ( endian ) { endian->swap(m_Ltlm); } // Index of marker segment relative to all other TLM marker segments. in.read((char*)&m_Ztlm, 1); // Stlm contains two variables in one byte, ST and SP. in.read((char*)&m_Stlm, 1); ossim_uint16 tile_count = getTileCount(); if ( tile_count ) { ossim_uint8 st = getSt(); //--- // Get the Ttlm array if any: // st value of 0 means tiles are in order and no Ttlm array. //--- if ( st == 1 ) // 8 bit { ossim_uint8* p = new ossim_uint8[tile_count]; in.read((char*)p, tile_count); m_Ttlm = p; } else if ( st == 2 ) // 16 bit { ossim_uint16* p = new ossim_uint16[tile_count]; in.read((char*)p, tile_count*2); if ( endian ) { endian->swap(p, tile_count); } m_Ttlm = p; } else if ( st > 2 ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimJ2kTlmRecord::parseStream(...) Bad tlm ST value!" << std::endl; } // Get the Ptlm array: ossim_uint8 sp = getSp(); if ( sp == 0 ) // 16 bit { ossim_uint16* p = new ossim_uint16[tile_count]; in.read((char*)p, tile_count*2); if ( endian ) { endian->swap(p, tile_count); } m_Ptlm = p; } else if ( sp == 1 ) // 32 bit { ossim_uint32* p = new ossim_uint32[tile_count]; in.read((char*)p, tile_count*4); if ( endian ) { endian->swap(p, tile_count); } m_Ptlm = p; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimJ2kTlmRecord::parseStream(...) Bad tlm SP value!" << std::endl; } } // Clean up:: if ( endian ) { delete endian; endian = 0; } //--- // Seek to next record in case there was a parse error and we didn't read // all bytes. //--- in.seekg(pos + m_Ltlm, std::ios_base::beg); } void ossimJ2kTlmRecord::writeStream(std::ostream& out) { ossim_uint16 tileCount = getTileCount(); ossim_uint8 st = getSt(); ossim_uint8 sp = getSp(); ossimEndian* endian = 0; if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) { // Stored in file big endian, must swap. endian = new ossimEndian(); endian->swap( m_Ltlm ); // Conditional ttlm array: if ( st == 2 ) { endian->swap( (ossim_uint16*)m_Ttlm, tileCount ); } // Conditional ptlm array: if (sp == 0 ) { endian->swap( (ossim_uint16*)m_Ptlm, tileCount ); } else if ( sp == 1 ) { endian->swap( (ossim_uint32*)m_Ptlm, tileCount ); } } // Marker 0xff55: out.put( 0xff ); out.put( 0x55 ); out.write( (char*)&m_Ltlm, 2); out.write( (char*)&m_Ztlm, 1); out.write( (char*)&m_Stlm, 1); // Conditional array of tile indexes: if ( st == 1 ) // 8 bit array { out.write( (char*)m_Ttlm, tileCount ); } else if ( st == 2 ) // 16 bit array { out.write( (char*)m_Ttlm, tileCount*2 ); } // Conditional array of tile byte counts: if ( sp == 0 ) // 16 bit array { out.write( (char*)m_Ptlm, tileCount*2 ); } else if ( sp == 1 ) // 32 bit array { out.write( (char*)m_Ptlm, tileCount*4 ); } if ( endian ) { // Swap back to native: endian->swap( m_Ltlm ); // Conditional ttlm array: if ( st == 2 ) { endian->swap( (ossim_uint16*)m_Ttlm, tileCount ); } // Conditional ptlm array: if (sp == 0 ) { endian->swap( (ossim_uint16*)m_Ptlm, tileCount ); } else if ( sp == 1 ) { endian->swap( (ossim_uint32*)m_Ptlm, tileCount ); } // Cleanup: delete endian; endian = 0; } } ossim_uint8 ossimJ2kTlmRecord::getSt() const { // 5th and 6th bits. return (m_Stlm & 0x30) >> 4; } bool ossimJ2kTlmRecord::setSt(ossim_uint8 bits ) { bool result = true; // 5th and 6th bits if ( bits == 0 ) { // Clear both 5th and 6th bit. m_Stlm = m_Stlm & 0xcf; } else if ( bits == 1 ) { // Set the 5th bit clear the 6th bit. m_Stlm = (m_Stlm & 0xdf) | 0x10; } else if ( bits == 2 ) { // Set the 6th bit, clear the 5th bit. m_Stlm = (m_Stlm & 0xef) | 0x20; } else { result = false; } return result; } ossim_uint8 ossimJ2kTlmRecord::getZtlm() const { return m_Ztlm; } ossim_uint8 ossimJ2kTlmRecord::getSp() const { // Last two bits. return m_Stlm >> 6; } bool ossimJ2kTlmRecord::setSp(ossim_uint8 bit ) { bool result = true; // 7th bit if ( bit == 0 ) { // Clear the 7th bit: m_Stlm = m_Stlm & 0xbf; } else if ( bit == 1 ) { // Set the 7th bit. m_Stlm = m_Stlm | 0x40; } else { result = false; } return result; } bool ossimJ2kTlmRecord::initPtlmArray( ossim_uint8 spBit, ossim_uint16 count ) { bool result = setSp( spBit ); clearPtlm(); if ( spBit == 0 ) { m_Ptlm = new ossim_uint16[count]; std::memset( m_Ptlm, 0, count*2 ); } else if ( spBit == 1 ) { m_Ptlm = new ossim_uint32[count]; std::memset( m_Ptlm, 0, count*4 ); } m_Ltlm = computeLength( count ); return result; } ossim_uint16 ossimJ2kTlmRecord::getTileCount() const { // See Table 7-21 BPJ2K01.10: ossim_uint16 result = 0; if ( m_Ltlm ) { ossim_uint8 st = getSt(); ossim_uint8 sp = getSp(); ossim_uint16 x = st + (sp==0?2:4); if ( x ) { result = (m_Ltlm - 4) / x; } } return result; } bool ossimJ2kTlmRecord::getTileLength( ossim_int32 index, ossim_uint32& length ) const { bool status = false; if ( (index >= 0) && ( index < getTileCount() ) ) { ossim_uint8 sp = getSp(); if ( sp == 0 ) { ossim_uint16* p = (ossim_uint16*)m_Ptlm; length = p[index]; status = true; } else if ( sp == 1 ) { ossim_uint32* p = (ossim_uint32*)m_Ptlm; length = p[index]; status = true; } } return status; } bool ossimJ2kTlmRecord::setTileLength( ossim_int32 index, ossim_uint32 length ) { bool status = false; if ( (index >= 0) && ( index < getTileCount() ) ) { ossim_uint8 sp = getSp(); if ( sp == 0 ) { ossim_uint16* p = (ossim_uint16*)m_Ptlm; p[index] = static_cast(length); status = true; } else if ( sp == 1 ) { ossim_uint32* p = (ossim_uint32*)m_Ptlm; p[index] = length; status = true; } } return status; } bool ossimJ2kTlmRecord::accumulate( ossim_int32 first, ossim_int32 last, std::streampos& init ) const { bool status = false; if ( (first >= 0) && (last>first) && (last <= getTileCount()) ) { ossim_uint8 sp = getSp(); if ( sp == 0 ) { ossim_uint16* p = (ossim_uint16*)m_Ptlm; for ( ossim_int32 i = first; i < last; ++i ) { init += p[i]; status = true; } } else if ( sp == 1 ) { ossim_uint32* p = (ossim_uint32*)m_Ptlm; for ( ossim_int32 i = first; i < last; ++i ) { init += p[i]; status = true; } } } return status; } ossim_uint16 ossimJ2kTlmRecord::computeLength( ossim_uint16 tileCount ) const { return 4 + ( getSt() + (getSp()==1?4:2) ) * tileCount; } std::ostream& ossimJ2kTlmRecord::print(std::ostream& out, const std::string& prefix) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); std::string pfx = prefix; pfx += "tlm."; out << pfx << "marker: 0xff55\n" << pfx << "Ltlm: " << m_Ltlm << "\n" << pfx << "Ztlm: " << int(m_Ztlm) << "\n"; out.setf(std::ios_base::hex, std::ios_base::basefield); out << pfx << "Stlm: 0x" << int(m_Stlm) << "\n"; out.setf(std::ios_base::fmtflags(0), std::ios_base::basefield); out << pfx << "Stlm.ST: " << int(getSt()) << "\n" << pfx << "Stlm.SP: " << int(getSp()) << "\n"; ossim_uint16 tile_count = getTileCount(); if ( tile_count ) { ossim_uint8 st = getSt(); if ( m_Ttlm == 0 ) { out << pfx << "Ttlm: null\n"; } else if ( st == 1 ) // 8 bit { ossim_uint8* p = (ossim_uint8*)m_Ttlm; for ( ossim_uint16 i = 0; i < tile_count; ++i ) { out << pfx << "Ttlm[" << i << "]: " << (int)p[i] << "\n"; } } else if ( st == 2 ) // 16 bit { ossim_uint16* p = (ossim_uint16*)m_Ttlm; for ( ossim_uint16 i = 0; i < tile_count; ++i ) { out << pfx << "Ttlm[" << i << "]: " << p[i] << "\n"; } } ossim_uint8 sp = getSp(); if ( sp == 0 ) // 16 bit { ossim_uint16* p = (ossim_uint16*)m_Ptlm; for ( ossim_uint16 i = 0; i < tile_count; ++i ) { out << pfx << "Ptlm[" << i << "]: " << p[i] << "\n"; } } else if ( sp == 1 ) // 32 bit { ossim_uint32* p = (ossim_uint32*)m_Ptlm; for ( ossim_uint16 i = 0; i < tile_count; ++i ) { out << pfx << "Ptlm[" << i << "]: " << p[i] << "\n"; } } } out.flush(); // Reset flags. out.setf(f); return out; } std::ostream& operator<<(std::ostream& out, const ossimJ2kTlmRecord& obj) { return obj.print(out); } ossim-Miami-2.9.1/src/support_data/ossimJp2Info.cpp000066400000000000000000000454711352751253100222500ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: JP2 Info object. // //---------------------------------------------------------------------------- // $Id: ossimJp2Info.cpp 23222 2015-04-05 15:44:57Z dburken $ #include #include #include #include #include #include // #include #include #include #include #include static ossimTrace traceDebug("ossimJp2Info:debug"); ossimJp2Info::ossimJp2Info() : ossimJ2kInfo() { } ossimJp2Info::~ossimJp2Info() { } bool ossimJp2Info::open(const ossimFilename& file) { bool result = false; std::ifstream str; str.open( file.c_str(), std::ios_base::in | std::ios_base::binary); if ( str.is_open() ) { const ossim_uint8 J2K_SIGNATURE_BOX[SIGNATURE_BOX_SIZE] = {0x00,0x00,0x00,0x0c,0x6a,0x50,0x20,0x20,0x0d,0x0a,0x87,0x0a}; ossim_uint8 box[SIGNATURE_BOX_SIZE]; // Read in the box. str.read((char*)box, SIGNATURE_BOX_SIZE); result = true; for (ossim_uint32 i = 0; i < SIGNATURE_BOX_SIZE; ++i) { if (box[i] != J2K_SIGNATURE_BOX[i]) { result = false; break; } } str.close(); } if ( result ) { m_file = file; // Capture file name. } return result; } std::ostream& ossimJp2Info::print(std::ostream& out) const { if ( m_file.size() ) { // Open the file. std::ifstream str( m_file.c_str(), std::ios_base::in | std::ios_base::binary ); if (str.good()) { //--- // ISO/IEC 15444-1:2004 (E) // LBox, Box Length. This field specifies the length of the box, stored // as a 4-byte big endian unsigned integer. This value includes all of // the fields of the box, including the length and type. If the value // of this field is 1, then the XLBox field shall exist and the value // of that field shall be the actual length of the box. If the value // of this field is 0, then the length of the box was not known when // the LBox field was written. In this case, this box contains all // bytes up to the end of the file. If a box of length 0 is contained // within another box (its superbox), then the length of that superbox // shall also be 0. This means that this box is the last box in the // file. The values 2-7 are reserved for ISO use. //--- ossim_uint32 lbox = 0; ossim_uint32 tbox = 0; ossim_uint64 xlbox = 0; const ossim_uint32 UUID_TYPE = 0x75756964; const ossim_uint8 GEOTIFF_UUID[GEOTIFF_UUID_SIZE] = { 0xb1, 0x4b, 0xf8, 0xbd, 0x08, 0x3d, 0x4b, 0x43, 0xa5, 0xae, 0x8c, 0xd7, 0xd5, 0xa6, 0xce, 0x03 }; while ( str.good() ) { std::streamoff boxPos = str.tellg(); readUInt32( lbox, str ); readUInt32( tbox, str ); if ( 1 == lbox ) { readUInt64( xlbox, str ); } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "jp2.lbox: " << std::dec << lbox << "\n" << "jp2.tbox: " << std::hex << tbox << std::dec << "\n"; printTboxType( tbox, ossimNotify(ossimNotifyLevel_DEBUG) ); if ( 1 == lbox ) { ossimNotify(ossimNotifyLevel_DEBUG) << "jp2.xlbox: " << xlbox << std::endl; } } if (tbox == UUID_TYPE) { // Check for GeoTIFF box. ossim_uint8 geotiffUuid[GEOTIFF_UUID_SIZE]; // Read in the id. str.read((char*)geotiffUuid, GEOTIFF_UUID_SIZE); #if 0 bool foundIt = true; for (ossim_uint32 i = 0; i < GEOTIFF_UUID_SIZE; ++i) { if (geotiffUuid[i] != GEOTIFF_UUID[i]) { foundIt = false; break; } } #endif if( memcmp( (char*)geotiffUuid, GEOTIFF_UUID, GEOTIFF_UUID_SIZE) == 0) { //--- // Feed the stream to the tiff info object to get a keyword // list with geometry/projection info. //--- ossimTiffInfo info; //--- // Have geotiff boxes with badly terminated geotiffs. So to keep // the tag parser from walking past the first image file directory // (IFD) into garbage we will set the process overview flag to false. // // Note if we ever get multiple entries we will need to take this out. //--- info.setProcessOverviewFlag(false); // Do a print to a memory stream. std::ostringstream os; info.print(str, os); // Open an input stream to pass to the keyword list. std::istringstream in( os.str() ); ossimKeywordlist kwl; if ( kwl.parseStream(in) ) { kwl.addPrefixToAll( ossimString("jp2.") ); // Print it: out << kwl << std::endl; } // Get out of while loop. // break; } } if (lbox == 0) // last box? { break; } // Seek to the next box. If xlbox is 1 if (lbox == 1) { boxPos += (std::streamoff)xlbox; } else { boxPos += (std::streamoff)lbox; } // Go to next box: str.seekg(boxPos, std::ios_base::beg); } // matches: while ( str.good() ) // Close the stream. str.close(); } // matches: if ( str.is_open() ) } // matches: if ( m_file.size() ) return out; } void ossimJp2Info::readUInt32(ossim_uint32& i, std::ifstream& str) const { str.read((char*)&i, 4); if (m_endian) { m_endian->swap(i); } } void ossimJp2Info::readUInt64(ossim_uint64& i, std::ifstream& str) const { str.read((char*)&i, 8); if (m_endian) { m_endian->swap(i); } } std::streamoff ossimJp2Info::findBoxData( const ossim_uint32& type, std::ifstream& str, ossim_uint32& length ) const { std::streamoff boxPos = 0; std::streamoff dataPosOfType = 0; if ( str.good() ) { ossim_uint32 lbox = 0; ossim_uint32 tbox = 0; ossim_uint64 xlbox = 0; std::streamoff offsetToDbox = 0; while ( str.good() ) { boxPos = str.tellg(); readUInt32( lbox, str ); readUInt32( tbox, str ); if ( lbox == 1 ) { readUInt64( xlbox, str ); offsetToDbox = 16; } else { offsetToDbox = 8; } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "jp2.lbox: " << std::dec << lbox << "\n" << "jp2.tbox: " << std::hex << tbox << std::dec << "\n"; printTboxType( tbox, ossimNotify(ossimNotifyLevel_DEBUG) ); if ( lbox == 1 ) { ossimNotify(ossimNotifyLevel_DEBUG) << "jp2.xlbox: " << xlbox << std::endl; } } if ( tbox == type ) { dataPosOfType = boxPos + offsetToDbox; // set up return value length = lbox; break; // done... } if ( lbox == 0 ) // last box? { break; } // Seek to the next box. std::streamoff nextBoxPos = boxPos; if (lbox == 1) { nextBoxPos+= (std::streamoff)xlbox; } else { nextBoxPos+= (std::streamoff)lbox; } // Go to next box: str.seekg(nextBoxPos, std::ios_base::beg); } // matches: while ( str.good() ) } // matches: if ( str.good() ) return dataPosOfType; } std::streamoff ossimJp2Info::getBox( const ossim_uint32 type, bool includeAll, std::vector& box ) const { std::streamoff boxPos = 0; if ( m_file.size() ) { // Open the file. std::ifstream str( m_file.c_str(), std::ios_base::in | std::ios_base::binary ); if (str.good()) { boxPos = getBox( type, includeAll, str, box ) ; } // matches: if ( str.is_open() ) } // matches: if ( m_file.size() ) return boxPos; } // End: ossimJp2Info::getBox( type, includeAll, box ) const std::streamoff ossimJp2Info::getBox( const ossim_uint32& type, bool includeAll, std::ifstream& str, std::vector& box ) const { std::streamoff boxPos = 0; std::streamoff boxPosOfType = 0; box.clear(); if ( str.good() ) { ossim_uint32 lbox = 0; ossim_uint32 tbox = 0; ossim_uint64 xlbox = 0; std::streamoff offsetToDbox = 0; while ( str.good() ) { boxPos = str.tellg(); readUInt32( lbox, str ); readUInt32( tbox, str ); if ( lbox == 1 ) { readUInt64( xlbox, str ); offsetToDbox = 16; } if ( !includeAll ) { if ( lbox == 1 ) { offsetToDbox = 16; } else { offsetToDbox = 8; } } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "jp2.lbox: " << std::dec << lbox << "\n" << "jp2.tbox: " << std::hex << tbox << std::dec << "\n"; printTboxType( tbox, ossimNotify(ossimNotifyLevel_DEBUG) ); if ( 1 == lbox ) { ossimNotify(ossimNotifyLevel_DEBUG) << "jp2.xlbox: " << xlbox << std::endl; } } if ( tbox == type ) { //--- // This is our box, copy it to box. // Not copying the lbox,tbox or xlbox std::streamoff boxSize = 0; if ( lbox == 0 ) { // Last box, goes to end of file. str.seekg( 0, std::ios_base::end ); boxSize = str.tellg() - boxPos; } else if ( lbox == 1 ) { boxSize = xlbox; } else { boxSize = lbox; } boxSize -= offsetToDbox; // Seek to box data start str.seekg( boxPos + offsetToDbox, std::ios_base::beg ); // std::vector::resize can throw a std::bad_alloc so wrap it... try { box.resize( boxSize ); str.read( (char*)&box.front(), boxSize ); } catch( std::exception& e ) { std::ostringstream errMsg; errMsg << "ossimJp2Info::getBox caught exception on resize:\n" << "Buffer size in bytes: " << boxSize << "\n" << e.what() << std::endl; throw ossimException( errMsg.str() ); } boxPosOfType = boxPos; // set up return value break; // done... } if (lbox == 0) // last box? { break; } // Seek to the next box. std::streamoff nextBoxPos = boxPos; if (lbox == 1) { nextBoxPos+= (std::streamoff)xlbox; } else { nextBoxPos+= (std::streamoff)lbox; } // Go to next box: str.seekg(nextBoxPos, std::ios_base::beg); } // matches: while ( str.good() ) } // matches: if ( str.good() ) return boxPosOfType; } // End: ossimJp2Info::getBox( type, includeAll, str, box ) const std::streamoff ossimJp2Info::getGeotiffBox( std::ifstream& str, std::vector& box ) const { std::streamoff boxPos = 0; if ( str.good() ) { const ossim_uint32 UUID_TYPE = 0x75756964; boxPos = getBox( UUID_TYPE, false, str, box ); if ( boxPos && ( box.size() >= GEOTIFF_UUID_SIZE) ) { const ossim_uint8 GEOTIFF_UUID[GEOTIFF_UUID_SIZE] = { 0xb1, 0x4b, 0xf8, 0xbd, 0x08, 0x3d, 0x4b, 0x43, 0xa5, 0xae, 0x8c, 0xd7, 0xd5, 0xa6, 0xce, 0x03 }; if( memcmp( (char*)&box.front(), GEOTIFF_UUID, GEOTIFF_UUID_SIZE) != 0) { boxPos = 0; box.clear(); } } } return boxPos; } std::streamoff ossimJp2Info::getGmlBox( std::ifstream& str, std::vector& box ) const { std::streamoff boxPos = 0; if ( str.good() ) { const ossim_uint32 ASOC_TBOX_ID = 0x61736F63; const ossim_uint32 LBL_TBOX_ID = 0x6C626C20; const ossim_uint32 XML_TBOX_ID = 0x786D6C20; ossim_uint32 asoc0_data_length = 0; std::streamoff dataPosAsoc0 = findBoxData( ASOC_TBOX_ID, str, asoc0_data_length ); if ( dataPosAsoc0 > 0 && asoc0_data_length > 0 ) { ossim_uint32 lbl0_data_length = 0; std::streamoff dataPosLbl0 = findBoxData( LBL_TBOX_ID, str, lbl0_data_length ); if ( dataPosLbl0 > 0 && lbl0_data_length > 0 ) { std::string gmlDataStr; gmlDataStr.resize( lbl0_data_length ); // Removed c++ 11 call for portablility... // str.read( (char*)&gmlDataStr.front(), lbl0_data_length ); str.read( (char*)&gmlDataStr[0], lbl0_data_length ); // Do we have a GML data asoc ? if ( gmlDataStr.compare( 0, 8, "gml.data" ) == 0 ) { // Seek to asoc 0 start of data str.seekg( dataPosAsoc0, std::ios_base::beg ); ossim_uint32 asoc1_data_length = 0; std::streamoff dataPosAsoc1 = findBoxData( ASOC_TBOX_ID, str, asoc1_data_length ); if ( dataPosAsoc1 > 0 && asoc1_data_length > 0 ) { ossim_uint32 lbl1_data_length = 0; std::streamoff dataPosLbl1 = findBoxData( LBL_TBOX_ID, str, lbl1_data_length ); if ( dataPosLbl1 > 0 && lbl1_data_length > 0 ) { std::string gmlRootInstanceStr; gmlRootInstanceStr.resize( lbl1_data_length ); // Removed c++ 11 call for portablility... // str.read( (char*)&gmlRootInstanceStr.front(), lbl1_data_length ); str.read( (char*)&gmlRootInstanceStr[0], lbl1_data_length ); // Do we have a GML root-instance asoc ? if ( gmlRootInstanceStr.compare( 0, 17, "gml.root-instance" ) == 0 ) { // Seek to asoc 1 start of data str.seekg( dataPosAsoc1, std::ios_base::beg ); boxPos = getBox( XML_TBOX_ID, false, str, box ); } } } } } } } return boxPos; } void ossimJp2Info::printTboxType( ossim_uint32 tbox, std::ostream& out ) const { std::string boxType; const ossim_uint32 JP2_ASSOC_TYPE = 0x61736f63; const ossim_uint32 JP2_LABEL_TYPE = 0x6c626c20; const ossim_uint32 JP2_SIG_TYPE = 0x6A502020; const ossim_uint32 FILE_TYPE = 0x66747970; const ossim_uint32 JP2_HDR_TYPE = 0x6A703268; const ossim_uint32 IMG_HDR_TYPE = 0x69686472; const ossim_uint32 BPCC_TYPE = 0x62706363; const ossim_uint32 COLR_TYPE = 0x636F6C72; const ossim_uint32 PCLR_TYPE = 0x70636C72; const ossim_uint32 CMAP_TYPE = 0x636D6170; const ossim_uint32 CDEF_TYPE = 0x63646566; const ossim_uint32 RES_TYPE = 0x72657320; const ossim_uint32 RESC_TYPE = 0x72657363; const ossim_uint32 RESD_TYPE = 0x72657364; const ossim_uint32 JP2C_TYPE = 0x6A703263; const ossim_uint32 JP2I_TYPE = 0x6A703269; const ossim_uint32 XML_TYPE = 0x786D6C20; const ossim_uint32 UUID_TYPE = 0x75756964; switch( tbox ) { case JP2_ASSOC_TYPE: { boxType = "jp2_assoc"; break; } case JP2_LABEL_TYPE: { boxType = "jp2_label"; break; } case JP2_SIG_TYPE: { boxType = "jp2_sig"; break; } case FILE_TYPE: { boxType = "ftyp"; break; } case JP2_HDR_TYPE: { boxType = "jp2h"; break; } case IMG_HDR_TYPE: { boxType = "ihdr"; break; } case BPCC_TYPE: { boxType = "bpcc"; break; } case COLR_TYPE: { boxType = "colr"; break; } case PCLR_TYPE: { boxType = "pclr"; break; } case CMAP_TYPE: { boxType = "cmap"; break; } case CDEF_TYPE: { boxType = "cdef"; break; } case RES_TYPE: { boxType = "res"; break; } case RESC_TYPE: { boxType = "resc"; break; } case RESD_TYPE: { boxType = "resd"; break; } case JP2C_TYPE: { boxType = "jp2c"; break; } case JP2I_TYPE: { boxType = "jp2i"; break; } case XML_TYPE: { boxType = "xml"; break; } case UUID_TYPE: { boxType = "uuid"; break; } default: { boxType = "unhandled"; break; } } out << "jp2.box_type: " << boxType << "\n"; } ossim-Miami-2.9.1/src/support_data/ossimJpipMessage.cpp000066400000000000000000000013411352751253100231740ustar00rootroot00000000000000#include ossimJpipMessage::ossimJpipMessage() :m_header(new ossimJpipMessageHeader()) { } void ossimJpipMessage::reset() { m_header->reset(); m_messageBody.clear(); m_headerLength = 0; } void ossimJpipMessage::dumpBodyAsHex(std::ostream& out)const { ossim_uint32 idx = 0; for(idx = 0; idx < m_messageBody.size();++idx) { std::cout << std::hex<<(int)m_messageBody[idx]<< " " ; if((idx+1)%16 == 0) { out << "\n"; } } } void ossimJpipMessage::dumpBodyAsText(std::ostream& out)const { ossim_uint32 idx = 0; for(idx = 0; idx < m_messageBody.size();++idx) { out << (char)m_messageBody[idx]; } } ossim-Miami-2.9.1/src/support_data/ossimJpipMessageDecoder.cpp000066400000000000000000000120631352751253100244650ustar00rootroot00000000000000#include ossimJpipMessageDecoder::ossimJpipMessageDecoder() :m_lastClass(0), m_lastCSn(0), m_headerLength(0), m_inputStream(&m_streamBuffer) { } // ossimJpipMessage* ossimJpipMessageDecoder::readMessage() throw(ossimException) ossimJpipMessage* ossimJpipMessageDecoder::readMessage() { ossim_int32 BinIDIndicator = 0; ossim_int64 inClassIdentifier = 0; bool completeDataBin = false; ossim_int64 tempByte = 0; // Initialization m_headerLength = 0; ossimRefPtr jpipMessage = new ossimJpipMessage(); // Bin-ID tempByte = m_inputStream.get(); m_headerLength++; if (tempByte == 0x00) { // EOR is reached jpipMessage = readEORMessage(); jpipMessage->setHeaderLength(m_headerLength); return jpipMessage.release(); } // b bits BinIDIndicator = (tempByte >> 5) & 0x03; if ( (BinIDIndicator < 1) || (BinIDIndicator > 3) ) { throw new ossimException("Wrong server response: impossible to decode it correctly"); } // c bit completeDataBin = (tempByte & 0x10)==0 ? false : true; // d bits (In-Class ID) inClassIdentifier = tempByte & 0x0F; if ((tempByte >> 7) > 0 ) { int numBytesVBAS = 1; do { tempByte = m_inputStream.get(); m_headerLength++; if (tempByte == -1) { throw new ossimException("There is not data available to read the VBAS"); } inClassIdentifier = (inClassIdentifier << 7) | (ossim_int64)(tempByte & 0x7F); numBytesVBAS++; if (numBytesVBAS > 9) { // maximum long value is 2^63 - 1 => 9 bytes VBAS throw new ossimException("VBAS length is larger than 63 bits (which is the maximum of long)"); } } while ( (tempByte & 0x80) != 0 ); } jpipMessage->header()->m_isLastByte = completeDataBin; jpipMessage->header()->m_inClassIdentifier = inClassIdentifier; // Class if ( (BinIDIndicator == 2) || (BinIDIndicator == 3) ) { jpipMessage->header()->m_classIdentifier = (int)readVBAS(); m_lastClass = jpipMessage->header()->m_classIdentifier; } else { jpipMessage->header()->m_classIdentifier = m_lastClass; } if ((jpipMessage->header()->m_classIdentifier < 0) || (jpipMessage->header()->m_classIdentifier > 8) ) throw new ossimException("Wrong server response: invalid value for Class identifier)"); // CSn if ( BinIDIndicator == 3) { jpipMessage->header()->m_CSn = (int)readVBAS(); m_lastCSn = jpipMessage->header()->m_CSn; } else { jpipMessage->header()->m_CSn = m_lastCSn; } // Msg-Offset jpipMessage->header()->m_msgOffset = (int)readVBAS(); // Msg-Length jpipMessage->header()->m_msgLength = (int)readVBAS(); // Aux if ( (jpipMessage->header()->m_classIdentifier % 2) == 1 ) { jpipMessage->header()->m_aux = (int)readVBAS(); } // Read jpip message body if (jpipMessage->header()->m_msgLength > 0) { jpipMessage->messageBody().resize(jpipMessage->header()->m_msgLength); m_inputStream.read((char*)&jpipMessage->messageBody().front(), (int)jpipMessage->header()->m_msgLength); } jpipMessage->setHeaderLength(m_headerLength); return jpipMessage.release(); } // ossim_int64 ossimJpipMessageDecoder::readVBAS() throw(ossimException) ossim_int64 ossimJpipMessageDecoder::readVBAS() { ossim_int64 value = 0; ossim_int64 tempByte; ossim_int32 numBytesVBAS = 0; m_headerLength = 0; do { tempByte = m_inputStream.get(); m_headerLength++; if(tempByte == -1) { throw ossimException("There is not data available to read the VBAS"); } value = (value << 7) | (long) (tempByte & 0x7F); numBytesVBAS++; if (numBytesVBAS > 9) { // maximum long value is 2^63 - 1 => 9 bytes VBAS throw ossimException("VBAS length is larger than 63 bits (which is the maximum of long)"); } } while ( (tempByte & 0x80) != 0 ); return value; } // ossimJpipMessage* ossimJpipMessageDecoder::readEORMessage() throw(ossimException) ossimJpipMessage* ossimJpipMessageDecoder::readEORMessage() { ossimRefPtr jpipMessage; jpipMessage = new ossimJpipMessage(); jpipMessage->header()->m_isEOR = true; // Read EOR code jpipMessage->header()->m_EORCode = m_inputStream.get(); m_headerLength++; // Read EOR body length int EORBodyLength = (int)readVBAS(); jpipMessage->header()->m_msgLength = EORBodyLength; // Read EOR body if (EORBodyLength > 0 ) { jpipMessage->messageBody().resize(EORBodyLength); m_inputStream.read((char*)&jpipMessage->messageBody().front(), EORBodyLength); } return jpipMessage.release(); } ossim-Miami-2.9.1/src/support_data/ossimLasHdr.cpp000066400000000000000000000435671352751253100221620ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasHdr.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Container class for LAS LIDAR format public header block. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include ossimLasHdr::ossimLasHdr() : m_fileSourceId(0), m_globalEncoding(0), m_projectIdGuidData1(0), m_projectIdGuidData2(0), m_projectIdGuidData3(0), m_versionMajor(0), m_versionMinor(0), m_fileCreationDay(0), m_fileCreateionYear(0), m_headerSize(0), m_offsetToPointData(0), m_numberOfVariableLengthRecords(0), m_pointDataFormatId(0), m_pointDataRecordLength(0), m_legacyNumberOfPointRecords(0), m_xScaleFactor(0.0), m_yScaleFactor(0.0), m_zScaleFactor(0.0), m_xOffset(0.0), m_yOffset(0.0), m_zOffset(0.0), m_maxX(0.0), m_minX(0.0), m_maxY(0.0), m_minY(0.0), m_maxZ(0.0), m_minZ(0.0), m_startOfWaveformDataPacket(0), m_startOfExtendedVariableLengthRecords(0), m_numberOfExtendedVariableLengthRecords(0), m_numberOfPointRecords(0) { // Initialize arrays: strncpy(m_fileSignature, "LASF", 4); m_fileSignature[4] = '\0'; memset(m_projectIdGuidData4, 0, 8); memset(m_systemIndentifier, 0, 32); memset(m_generatingSoftware, 0, 32); memset(m_legacyNumberOfPointsByReturn, 0, 20); // 5 uint32s(5 x 4) memset(m_numberOfPointsByReturn, 0, 120); // 15 unint64s(15 x 8) } ossimLasHdr::ossimLasHdr(const ossimLasHdr& hdr) : m_fileSourceId(hdr.m_fileSourceId), m_globalEncoding(hdr.m_globalEncoding), m_projectIdGuidData1(hdr.m_projectIdGuidData1), m_projectIdGuidData2(hdr.m_projectIdGuidData2), m_projectIdGuidData3(hdr.m_projectIdGuidData3), m_versionMajor(hdr.m_versionMajor), m_versionMinor(hdr.m_versionMinor), m_fileCreationDay(hdr.m_fileCreationDay), m_fileCreateionYear(hdr.m_fileCreateionYear), m_headerSize(hdr.m_headerSize), m_offsetToPointData(hdr.m_offsetToPointData), m_numberOfVariableLengthRecords(hdr.m_numberOfVariableLengthRecords), m_pointDataFormatId(hdr.m_pointDataFormatId), m_pointDataRecordLength(hdr.m_pointDataRecordLength), m_legacyNumberOfPointRecords(hdr.m_legacyNumberOfPointRecords), m_xScaleFactor(hdr.m_xScaleFactor), m_yScaleFactor(hdr.m_yScaleFactor), m_zScaleFactor(hdr.m_zScaleFactor), m_xOffset(hdr.m_xOffset), m_yOffset(hdr.m_yOffset), m_zOffset(hdr.m_zOffset), m_maxX(hdr.m_maxX), m_minX(hdr.m_minX), m_maxY(hdr.m_maxY), m_minY(hdr.m_minY), m_maxZ(hdr.m_maxZ), m_minZ(hdr.m_minZ), m_startOfWaveformDataPacket(hdr.m_startOfWaveformDataPacket), m_startOfExtendedVariableLengthRecords(hdr.m_startOfExtendedVariableLengthRecords), m_numberOfExtendedVariableLengthRecords(hdr.m_numberOfExtendedVariableLengthRecords), m_numberOfPointRecords(hdr.m_numberOfPointRecords) { // Copy arrays. memcpy((void*)m_fileSignature, (void*)(hdr.m_fileSignature), 4); memcpy((void*)m_projectIdGuidData4, (void*)(hdr.m_projectIdGuidData4), 8); memcpy((void*)m_systemIndentifier, (void*)(hdr.m_systemIndentifier), 32); memcpy((void*)m_generatingSoftware, (void*)(hdr.m_generatingSoftware), 32); memcpy((void*)m_legacyNumberOfPointsByReturn, (void*)(hdr.m_legacyNumberOfPointsByReturn), 20); memcpy((void*)m_numberOfPointsByReturn, (void*)(hdr.m_numberOfPointsByReturn), 120); } const ossimLasHdr& ossimLasHdr::operator=(const ossimLasHdr& hdr) { if (this != &hdr) { m_fileSourceId = hdr.m_fileSourceId; m_globalEncoding = hdr.m_globalEncoding; m_projectIdGuidData1 = hdr.m_projectIdGuidData1; m_projectIdGuidData2 = hdr.m_projectIdGuidData2; m_projectIdGuidData3 = hdr.m_projectIdGuidData3; m_versionMajor = hdr.m_versionMajor; m_versionMinor = hdr.m_versionMinor; strncpy(m_systemIndentifier, hdr.m_systemIndentifier, 32); strncpy(m_generatingSoftware, hdr.m_generatingSoftware, 32); m_fileCreationDay = hdr.m_fileCreationDay; m_fileCreateionYear = hdr.m_fileCreateionYear; m_headerSize = hdr.m_headerSize; m_offsetToPointData = hdr.m_offsetToPointData; m_numberOfVariableLengthRecords = hdr.m_numberOfVariableLengthRecords; m_pointDataFormatId = hdr.m_pointDataFormatId; m_pointDataRecordLength = hdr.m_pointDataRecordLength; m_legacyNumberOfPointRecords = hdr.m_legacyNumberOfPointRecords; m_xScaleFactor = hdr.m_xScaleFactor; m_yScaleFactor = hdr.m_yScaleFactor; m_zScaleFactor = hdr.m_zScaleFactor; m_xOffset = hdr.m_xOffset; m_yOffset = hdr.m_yOffset; m_zOffset = hdr.m_zOffset; m_maxX = hdr.m_maxX; m_minX = hdr.m_minX; m_maxY = hdr.m_maxY; m_minY = hdr.m_minY; m_maxZ = hdr.m_maxZ; m_minZ = hdr.m_minZ; m_startOfWaveformDataPacket = hdr.m_startOfWaveformDataPacket; m_startOfExtendedVariableLengthRecords = hdr.m_startOfExtendedVariableLengthRecords; m_numberOfExtendedVariableLengthRecords = hdr.m_numberOfExtendedVariableLengthRecords; m_numberOfPointRecords = hdr.m_numberOfPointRecords; // Copy arrays. memcpy((void*)m_fileSignature,(void*)(hdr.m_fileSignature), 4); memcpy((void*)m_projectIdGuidData4, (void*)(hdr.m_projectIdGuidData4), 8); memcpy((void*)m_systemIndentifier, (void*)(hdr.m_systemIndentifier), 32); memcpy((void*)m_generatingSoftware, (void*)(hdr.m_generatingSoftware), 32); memcpy((void*)m_legacyNumberOfPointsByReturn, (void*)(hdr.m_legacyNumberOfPointsByReturn), 20); memcpy((void*)m_numberOfPointsByReturn, (void*)(hdr.m_numberOfPointsByReturn), 120); } return *this; } ossimLasHdr::~ossimLasHdr() { } bool ossimLasHdr::checkSignature(std::istream& in) const { bool result = false; char SIG[4]; in.read(SIG, 4); if ( (SIG[0] == 'L') && (SIG[1] == 'A') && (SIG[2] == 'S') && (SIG[3] == 'F') ) { result = true; } return result; } void ossimLasHdr::readStream(std::istream& in) { in.read(m_fileSignature, 4); in.read((char*)&m_fileSourceId, 2); in.read((char*)&m_globalEncoding, 2); in.read((char*)&m_projectIdGuidData1, 4); in.read((char*)&m_projectIdGuidData2, 2); in.read((char*)&m_projectIdGuidData3, 2); in.read((char*)&m_projectIdGuidData4, 8); in.read((char*)&m_versionMajor, 1); in.read((char*)&m_versionMinor, 1); in.read(m_systemIndentifier, 32); in.read(m_generatingSoftware, 32); in.read((char*)&m_fileCreationDay, 2); in.read((char*)&m_fileCreateionYear, 2); in.read((char*)&m_headerSize, 2); in.read((char*)&m_offsetToPointData, 4); in.read((char*)&m_numberOfVariableLengthRecords, 4); in.read((char*)&m_pointDataFormatId, 1); in.read((char*)&m_pointDataRecordLength, 2); in.read((char*)&m_legacyNumberOfPointRecords, 4); in.read((char*)&m_legacyNumberOfPointsByReturn, 20); in.read((char*)&m_xScaleFactor, 8); in.read((char*)&m_yScaleFactor, 8); in.read((char*)&m_zScaleFactor, 8); in.read((char*)&m_xOffset, 8); in.read((char*)&m_yOffset, 8); in.read((char*)&m_zOffset, 8); in.read((char*)&m_maxX, 8); in.read((char*)&m_minX, 8); in.read((char*)&m_maxY, 8); in.read((char*)&m_minY, 8); in.read((char*)&m_maxZ, 8); in.read((char*)&m_minZ, 8); // Version specific: if ( versionGreaterThan( 1, 2 ) ) { // Added in 1.3: in.read((char*)&m_startOfWaveformDataPacket, 8); } if ( versionGreaterThan( 1, 3 ) ) { // Added in 1.4: in.read((char*)&m_startOfExtendedVariableLengthRecords, 8); in.read((char*)&m_numberOfExtendedVariableLengthRecords, 4); in.read((char*)&m_numberOfPointRecords, 8); in.read((char*)&m_numberOfPointsByReturn, 120); } if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { swap(); } if ( !versionGreaterThan( 1, 3 ) ) // Less than 1.4 { //--- // Copy legacy point count to 64 bit data members. This will allow LAS code // to always go through same methods for point counts. //--- m_numberOfPointRecords = m_legacyNumberOfPointRecords; for ( ossim_uint32 i = 0; i < 5; ++i ) { m_numberOfPointsByReturn[i] = m_legacyNumberOfPointsByReturn[i]; } } } void ossimLasHdr::writeStream(std::ostream& out) { if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Write little endian per spec. swap(); } out.write(m_fileSignature, 4); out.write((char*)&m_fileSourceId, 2); out.write((char*)&m_globalEncoding, 2); out.write((char*)&m_projectIdGuidData1, 4); out.write((char*)&m_projectIdGuidData2, 2); out.write((char*)&m_projectIdGuidData3, 2); out.write((char*)&m_projectIdGuidData4, 8); out.write((char*)&m_versionMajor, 1); out.write((char*)&m_versionMinor, 1); out.write(m_systemIndentifier, 32); out.write(m_generatingSoftware, 32); out.write((char*)&m_fileCreationDay, 2); out.write((char*)&m_fileCreateionYear, 2); out.write((char*)&m_headerSize, 2); out.write((char*)&m_offsetToPointData, 4); out.write((char*)&m_numberOfVariableLengthRecords, 4); out.write((char*)&m_pointDataFormatId, 1); out.write((char*)&m_pointDataRecordLength, 2); out.write((char*)&m_legacyNumberOfPointRecords, 4); out.write((char*)&m_legacyNumberOfPointsByReturn, 20); out.write((char*)&m_xScaleFactor, 8); out.write((char*)&m_yScaleFactor, 8); out.write((char*)&m_zScaleFactor, 8); out.write((char*)&m_xOffset, 8); out.write((char*)&m_yOffset, 8); out.write((char*)&m_zOffset, 8); out.write((char*)&m_maxX, 8); out.write((char*)&m_minX, 8); out.write((char*)&m_maxY, 8); out.write((char*)&m_minY, 8); out.write((char*)&m_maxZ, 8); out.write((char*)&m_minZ, 8); if ( versionGreaterThan( 1, 2 ) ) { // Added in 1.3: out.write((char*)&m_startOfWaveformDataPacket, 8); } if ( versionGreaterThan( 1, 3 ) ) { // Added in 1.4: out.write((char*)&m_startOfExtendedVariableLengthRecords, 8); out.write((char*)&m_numberOfExtendedVariableLengthRecords, 4); out.write((char*)&m_numberOfPointRecords, 8); out.write((char*)&m_numberOfPointsByReturn, 120); } if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Swap back to native byte order if needed: swap(); } } std::ostream& ossimLasHdr::print(std::ostream& out) const { ossimKeywordlist kwl; getKeywordlist( kwl ); return out << kwl; } std::ostream& operator<<(std::ostream& out, const ossimLasHdr& hdr) { return hdr.print(out); } void ossimLasHdr::getKeywordlist(ossimKeywordlist& kwl) const { kwl.add("las.file_source_id", m_fileSourceId); //--- // m_globalEncoding is a bit encoding so we output bit at a time: // At the time of this coding only first four bits used. //--- // 1.2: kwl.add("las.gps_time_type", (getGpsTimeTypeBit()?"1":"0") ); if ( versionGreaterThan( 1, 2 ) ) { // Added in 1.3: kwl.add("las.waveform_data_packets_internal", (getWaveforDataPacketsInternalBit()?"1":"0") ); kwl.add("las.waveform_data_packets_external", (getWaveforDataPacketsExternalBit()?"1":"0") ); kwl.add("las.synthetically_generated", (getReturnsSyntheticallyGeneratedBit()?"1":"0") ); } if ( versionGreaterThan( 1, 3 ) ) { // 1.4: kwl.add("las.wkt", (getWktBit()?"1":"0") ); } kwl.add("las.project_id_guid", getProjectIdGuid().c_str()); kwl.add("las.version", getVersion().c_str()); kwl.add("las.system_indentifier", getSystemIndentifier().c_str()); kwl.add("las.generating_software", getGeneratingSoftware().c_str()); kwl.add("las.file_creation_day", m_fileCreationDay); kwl.add("las.file_creation_year", m_fileCreateionYear); kwl.add("las.header_size", m_headerSize); kwl.add("las.offset_to_point_data", m_offsetToPointData ); kwl.add("las.number_of_variable_length_records", m_numberOfVariableLengthRecords); kwl.add("las.point_data_format_id", m_pointDataFormatId); kwl.add("las.point_data_record_length", m_pointDataRecordLength); kwl.add("las.x_scale_factor", m_xScaleFactor); kwl.add("las.y_scale_factor", m_yScaleFactor); kwl.add("las.z_scale_factor", m_zScaleFactor); kwl.add("las.x_offset", m_xOffset); kwl.add("las.y_offset", m_yOffset); kwl.add("las.z_offset", m_zOffset); kwl.add("las.max_x", m_maxX); kwl.add("las.min_x", m_minX); kwl.add("las.max_y", m_maxY); kwl.add("las.min_y", m_minY); kwl.add("las.max_z", m_maxZ); kwl.add("las.min_z", m_minZ); kwl.add("las.start_of_wave_form_data", m_startOfWaveformDataPacket); if ( versionGreaterThan( 1, 3 ) ) { kwl.add("las.number_of_point_records", m_numberOfPointRecords); for (ossim_uint32 i = 0; i < 15; ++i) { std::ostringstream os; os << "las.number_of_points_return" << (i+1); kwl.add( os.str().c_str(), m_numberOfPointsByReturn[i] ); } } else { // Prior to 1.4: kwl.add("las.number_of_point_records", m_legacyNumberOfPointRecords); for (ossim_uint32 i = 0; i < 5; ++i) { std::ostringstream os; os << "las.number_of_points_return" << (i+1); kwl.add( os.str().c_str(), m_legacyNumberOfPointsByReturn[i] ); } } } bool ossimLasHdr::getGpsTimeTypeBit() const { // Test the first bit: std::bitset<1> bs( m_globalEncoding ); return bs.test(0); } bool ossimLasHdr::getWaveforDataPacketsInternalBit() const { // Test the second bit: std::bitset<2> bs( m_globalEncoding ); return bs.test(1); } bool ossimLasHdr::getWaveforDataPacketsExternalBit() const { // Test the third bit: std::bitset<3> bs( m_globalEncoding ); return bs.test(2); } bool ossimLasHdr::getReturnsSyntheticallyGeneratedBit() const { // Test the fourth bit: std::bitset<4> bs( m_globalEncoding ); return bs.test(3); } bool ossimLasHdr::getWktBit() const { // Test the fith bit: std::bitset<5> bs( m_globalEncoding ); return bs.test(4); } std::string ossimLasHdr::getProjectIdGuid() const { std::ostringstream os; os << std::hex << m_projectIdGuidData1 << "-" << m_projectIdGuidData2 << "-" << m_projectIdGuidData3 << "-"; for (int i=0; i<8; ++i) { ossim_uint16 uid = m_projectIdGuidData4[i]; os << uid; } return os.str(); } std::string ossimLasHdr::getVersion() const { std::ostringstream os; os << int(m_versionMajor) << "." << int(m_versionMinor); return os.str(); } std::string ossimLasHdr::getSystemIndentifier() const { std::string s; s.reserve(32); for (int i=0; i<32; ++i) { s.push_back(m_systemIndentifier[i]); } return s; } std::string ossimLasHdr::getGeneratingSoftware() const { std::string s; s.reserve(32); for (int i=0; i<32; ++i) { s.push_back(m_generatingSoftware[i]); } return s; } ossim_uint16 ossimLasHdr::getHeaderSize() const { return m_headerSize; } ossim_uint32 ossimLasHdr::getOffsetToPointData() const { return m_offsetToPointData; } ossim_uint32 ossimLasHdr::getNumberOfVlrs() const { return m_numberOfVariableLengthRecords; } ossim_uint8 ossimLasHdr::getPointDataFormatId() const { return m_pointDataFormatId; } ossim_uint64 ossimLasHdr::getNumberOfPoints() const { return m_numberOfPointRecords; } ossim_uint64 ossimLasHdr::getNumberOfPoints(ossim_uint32 entry) const { ossim_uint64 result = 0; if ( entry < 15 ) { result = m_numberOfPointsByReturn[entry]; } return result; } const ossim_float64& ossimLasHdr::getScaleFactorX() const { return m_xScaleFactor; } const ossim_float64& ossimLasHdr::getScaleFactorY() const { return m_yScaleFactor; } const ossim_float64& ossimLasHdr::getScaleFactorZ() const { return m_zScaleFactor; } const ossim_float64& ossimLasHdr::getOffsetX() const { return m_xOffset; } const ossim_float64& ossimLasHdr::getOffsetY() const { return m_yOffset; } const ossim_float64& ossimLasHdr::getOffsetZ() const { return m_zOffset; } const ossim_float64& ossimLasHdr::getMinX() const { return m_minX; } const ossim_float64& ossimLasHdr::getMinY() const { return m_minY; } const ossim_float64& ossimLasHdr::getMinZ() const { return m_minZ; } const ossim_float64& ossimLasHdr::getMaxX() const { return m_maxX; } const ossim_float64& ossimLasHdr::getMaxY() const { return m_maxY; } const ossim_float64& ossimLasHdr::getMaxZ() const { return m_maxZ; } void ossimLasHdr::swap() { ossimEndian endian; endian.swap(m_fileSourceId); endian.swap(m_globalEncoding); endian.swap(m_projectIdGuidData1); endian.swap(m_projectIdGuidData2); endian.swap(m_projectIdGuidData3); endian.swap(m_fileCreationDay); endian.swap(m_fileCreateionYear); endian.swap(m_headerSize); endian.swap(m_offsetToPointData); endian.swap(m_numberOfVariableLengthRecords); endian.swap(m_pointDataRecordLength); endian.swap(m_legacyNumberOfPointRecords); endian.swap(m_legacyNumberOfPointsByReturn, 5); endian.swap(m_xScaleFactor); endian.swap(m_yScaleFactor); endian.swap(m_zScaleFactor); endian.swap(m_xOffset); endian.swap(m_yOffset); endian.swap(m_zOffset); endian.swap(m_maxX); endian.swap(m_minX); endian.swap(m_maxY); endian.swap(m_minY); endian.swap(m_maxZ); endian.swap(m_minZ); endian.swap(m_startOfWaveformDataPacket); endian.swap(m_startOfExtendedVariableLengthRecords); endian.swap(m_numberOfExtendedVariableLengthRecords); endian.swap(m_numberOfPointRecords); endian.swap(m_numberOfPointsByReturn, 15); } bool ossimLasHdr::versionGreaterThan( ossim_uint8 major, ossim_uint8 minor ) const { bool result = false; if ( m_versionMajor == major ) { result = m_versionMinor > minor; } else if ( m_versionMajor > major ) { result = true; } return result; } ossim-Miami-2.9.1/src/support_data/ossimLasInfo.cpp000066400000000000000000000023671352751253100223310ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLibLasInfo.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: LAS LIDAR info object. // //---------------------------------------------------------------------------- // $Id$ #include #include #include ossimLasInfo::ossimLasInfo() : m_file() { } ossimLasInfo::~ossimLasInfo() { } bool ossimLasInfo::open(const ossimFilename& file) { bool result = false; std::ifstream istr; istr.open(file.c_str(), std::ios_base::in | std::ios_base::binary); if ( istr.is_open() ) { ossimLasHdr hdr; result = hdr.checkSignature(istr); if (result) m_file = file; } return result; } std::ostream& ossimLasInfo::print(std::ostream& out) const { std::ifstream istr; istr.open(m_file.c_str(), std::ios_base::in | std::ios_base::binary); if ( istr.is_open() ) { ossimLasHdr hdr; if ( hdr.checkSignature(istr) ) { istr.seekg(0, std::ios_base::beg); hdr.readStream(istr); hdr.print(out); } } return out; } ossim-Miami-2.9.1/src/support_data/ossimLasPointRecord0.cpp000066400000000000000000000112331352751253100237360ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord0.cpp // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Container class LAS point record type 1. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include ossimLasPointRecord0::ossimLasPointRecord0Data::ossimLasPointRecord0Data() : m_x(0), m_y(0), m_z(0), m_intensity(0), m_returnByte(0), m_classification(0), m_scanAngleRank(0), m_userData(0), m_pointSourceID(0) { } ossimLasPointRecord0::ossimLasPointRecord0Data::ossimLasPointRecord0Data( const ossimLasPointRecord0::ossimLasPointRecord0Data& obj) : m_x(obj.m_x), m_y(obj.m_y), m_z(obj.m_z), m_intensity(obj.m_intensity), m_returnByte(obj.m_returnByte), m_classification(obj.m_classification), m_scanAngleRank(obj.m_scanAngleRank), m_userData(obj.m_userData), m_pointSourceID(obj.m_pointSourceID) { } const ossimLasPointRecord0::ossimLasPointRecord0Data& ossimLasPointRecord0::ossimLasPointRecord0Data::operator=( const ossimLasPointRecord0::ossimLasPointRecord0Data& obj) { if ( this != &obj ) { m_x = obj.m_x; m_y = obj.m_y; m_z = obj.m_z; m_intensity = obj.m_intensity; m_returnByte = obj.m_returnByte; m_classification = obj.m_classification; m_scanAngleRank = obj.m_scanAngleRank; m_userData = obj.m_userData; m_pointSourceID = obj.m_pointSourceID; } return *this; } ossimLasPointRecord0::ossimLasPointRecord0() : m_record() { } ossimLasPointRecord0::ossimLasPointRecord0(const ossimLasPointRecord0& obj) : m_record(obj.m_record) { } const ossimLasPointRecord0& ossimLasPointRecord0::operator=(const ossimLasPointRecord0& copy_this) { if (this != ©_this) { m_record = copy_this.m_record; } return *this; } ossimLasPointRecord0::~ossimLasPointRecord0() { } void ossimLasPointRecord0::readStream(std::istream& in) { in.read((char*)&m_record, 28); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { swap(); } } void ossimLasPointRecord0::writeStream(std::ostream& out) { if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Write little endian per spec: swap(); } out.write((char*)&m_record, 28); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Swap back to native byte order if needed: swap(); } } ossim_int32 ossimLasPointRecord0::getX() const { return m_record.m_x; } ossim_int32 ossimLasPointRecord0::getY() const { return m_record.m_y; } ossim_int32 ossimLasPointRecord0::getZ() const { return m_record.m_z; } ossim_uint16 ossimLasPointRecord0::getRed() const { return 0; } ossim_uint16 ossimLasPointRecord0::getGreen() const { return 0; } ossim_uint16 ossimLasPointRecord0::getBlue() const { return 0; } ossim_uint16 ossimLasPointRecord0::getIntensity() const { return m_record.m_intensity; } ossim_uint8 ossimLasPointRecord0::getReturnNumber() const { return (0x07 & m_record.m_returnByte); } ossim_uint8 ossimLasPointRecord0::getNumberOfReturns() const { return (0x34 & m_record.m_returnByte); } ossim_uint8 ossimLasPointRecord0::getEdgeFlag() const { return (0x40 & m_record.m_returnByte); } std::ostream& ossimLasPointRecord0::print(std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << std::setiosflags(std::ios_base::fixed) << std::setprecision(8); out << "x: " << m_record.m_x << "\ny: " << m_record.m_y << "\nz: " << m_record.m_z << "\nintensity: " << m_record.m_intensity << "\nreturn: " << int(getReturnNumber()) << "\nnumber_of_returns: " << int(getNumberOfReturns()) << "\nedge: " << (getEdgeFlag()?"true":"false") << "\nclassification: " << m_record.m_classification << "\nscan_angle_rank: " << int(m_record.m_scanAngleRank) << "\nuser_data: " << m_record.m_userData << "\npoint_source_id: " << m_record.m_pointSourceID << std::endl; // Reset flags. out.setf(f); return out; } void ossimLasPointRecord0::swap() { ossimEndian endian; endian.swap(m_record.m_x); endian.swap(m_record.m_y); endian.swap(m_record.m_z); endian.swap(m_record.m_intensity); endian.swap(m_record.m_pointSourceID); } ossim-Miami-2.9.1/src/support_data/ossimLasPointRecord1.cpp000066400000000000000000000115171352751253100237440ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord1.cpp // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Container class LAS point record type 1. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include ossimLasPointRecord1::ossimLasPointRecord1Data::ossimLasPointRecord1Data() : m_x(0), m_y(0), m_z(0), m_intensity(0), m_returnByte(0), m_classification(0), m_scanAngleRank(0), m_userData(0), m_pointSourceID(0), m_gpsTime(0.0) { } ossimLasPointRecord1::ossimLasPointRecord1Data::ossimLasPointRecord1Data( const ossimLasPointRecord1::ossimLasPointRecord1Data& obj) : m_x(obj.m_x), m_y(obj.m_y), m_z(obj.m_z), m_intensity(obj.m_intensity), m_returnByte(obj.m_returnByte), m_classification(obj.m_classification), m_scanAngleRank(obj.m_scanAngleRank), m_userData(obj.m_userData), m_pointSourceID(obj.m_pointSourceID), m_gpsTime(obj.m_gpsTime) { } const ossimLasPointRecord1::ossimLasPointRecord1Data& ossimLasPointRecord1::ossimLasPointRecord1Data::operator=( const ossimLasPointRecord1::ossimLasPointRecord1Data& obj) { if ( this != &obj ) { m_x = obj.m_x; m_y = obj.m_y; m_z = obj.m_z; m_intensity = obj.m_intensity; m_returnByte = obj.m_returnByte; m_classification = obj.m_classification; m_scanAngleRank = obj.m_scanAngleRank; m_userData = obj.m_userData; m_pointSourceID = obj.m_pointSourceID; m_gpsTime = obj.m_gpsTime; } return *this; } ossimLasPointRecord1::ossimLasPointRecord1() : m_record() { } ossimLasPointRecord1::ossimLasPointRecord1(const ossimLasPointRecord1& obj) : m_record(obj.m_record) { } const ossimLasPointRecord1& ossimLasPointRecord1::operator=(const ossimLasPointRecord1& copy_this) { if (this != ©_this) { m_record = copy_this.m_record; } return *this; } ossimLasPointRecord1::~ossimLasPointRecord1() { } void ossimLasPointRecord1::readStream(std::istream& in) { in.read((char*)&m_record, 28); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { swap(); } } void ossimLasPointRecord1::writeStream(std::ostream& out) { if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Write little endian per spec: swap(); } out.write((char*)&m_record, 28); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Swap back to native byte order if needed: swap(); } } ossim_int32 ossimLasPointRecord1::getX() const { return m_record.m_x; } ossim_int32 ossimLasPointRecord1::getY() const { return m_record.m_y; } ossim_int32 ossimLasPointRecord1::getZ() const { return m_record.m_z; } ossim_uint16 ossimLasPointRecord1::getRed() const { return 0; } ossim_uint16 ossimLasPointRecord1::getGreen() const { return 0; } ossim_uint16 ossimLasPointRecord1::getBlue() const { return 0; } ossim_uint16 ossimLasPointRecord1::getIntensity() const { return m_record.m_intensity; } ossim_uint8 ossimLasPointRecord1::getReturnNumber() const { return (0x07 & m_record.m_returnByte); } ossim_uint8 ossimLasPointRecord1::getNumberOfReturns() const { return (0x34 & m_record.m_returnByte); } ossim_uint8 ossimLasPointRecord1::getEdgeFlag() const { return (0x40 & m_record.m_returnByte); } std::ostream& ossimLasPointRecord1::print(std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << std::setiosflags(std::ios_base::fixed) << std::setprecision(8); out << "x: " << m_record.m_x << "\ny: " << m_record.m_y << "\nz: " << m_record.m_z << "\nintensity: " << m_record.m_intensity << "\nreturn: " << int(getReturnNumber()) << "\nnumber_of_returns: " << int(getNumberOfReturns()) << "\nedge: " << (getEdgeFlag()?"true":"false") << "\nclassification: " << m_record.m_classification << "\nscan_angle_rank: " << int(m_record.m_scanAngleRank) << "\nuser_data: " << m_record.m_userData << "\npoint_source_id: " << m_record.m_pointSourceID << "\ngps_time: " << m_record.m_gpsTime << std::endl; // Reset flags. out.setf(f); return out; } void ossimLasPointRecord1::swap() { ossimEndian endian; endian.swap(m_record.m_x); endian.swap(m_record.m_y); endian.swap(m_record.m_z); endian.swap(m_record.m_intensity); endian.swap(m_record.m_pointSourceID); endian.swap(m_record.m_gpsTime); } ossim-Miami-2.9.1/src/support_data/ossimLasPointRecord2.cpp000066400000000000000000000127611352751253100237470ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord2.cpp // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Container class LAS point record type 2. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include ossimLasPointRecord2::ossimLasPointRecord2Data::ossimLasPointRecord2Data() : m_x(0), m_y(0), m_z(0), m_intensity(0), m_bitFlags(0), m_classification(0), m_scanAngleRank(0), m_userData(0), m_pointSourceId(0), m_red(0), m_green(0), m_blue(0) { } ossimLasPointRecord2::ossimLasPointRecord2Data::ossimLasPointRecord2Data( const ossimLasPointRecord2::ossimLasPointRecord2Data& obj) : m_x(obj.m_x), m_y(obj.m_y), m_z(obj.m_z), m_intensity(obj.m_intensity), m_bitFlags(obj.m_bitFlags), m_classification(obj.m_classification), m_scanAngleRank(obj.m_scanAngleRank), m_userData(obj.m_userData), m_pointSourceId(obj.m_pointSourceId), m_red(obj.m_red), m_green(obj.m_green), m_blue(obj.m_blue) { } const ossimLasPointRecord2::ossimLasPointRecord2Data& ossimLasPointRecord2::ossimLasPointRecord2Data::operator=( const ossimLasPointRecord2::ossimLasPointRecord2Data& obj) { if ( this != &obj ) { m_x = obj.m_x; m_y = obj.m_y; m_z = obj.m_z; m_intensity = obj.m_intensity; m_bitFlags = obj.m_bitFlags; m_classification = obj.m_classification; m_scanAngleRank = obj.m_scanAngleRank; m_userData = obj.m_userData; m_pointSourceId = obj.m_pointSourceId; m_red = obj.m_red; m_green = obj.m_green; m_blue = obj.m_blue; } return *this; } ossimLasPointRecord2::ossimLasPointRecord2() : m_record() { } ossimLasPointRecord2::ossimLasPointRecord2(const ossimLasPointRecord2& obj) : m_record(obj.m_record) { } const ossimLasPointRecord2& ossimLasPointRecord2::operator=(const ossimLasPointRecord2& copy_this) { if (this != ©_this) { m_record = copy_this.m_record; } return *this; } ossimLasPointRecord2::~ossimLasPointRecord2() { } void ossimLasPointRecord2::readStream(std::istream& in) { in.read((char*)&m_record, 26); // sizeof reports 28 due to actual space used for STRUCT //sizeof(ossimLasPointRecord2Data)); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { swap(); } } void ossimLasPointRecord2::writeStream(std::ostream& out) { if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Write little endian per spec: swap(); } out.write((char*)&m_record, 26); // sizeof reports 28 due to actual space used for STRUCT //sizeof(ossimLasPointRecord2Data)); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Swap back to native byte order if needed: swap(); } } ossim_int32 ossimLasPointRecord2::getX() const { return m_record.m_x; } ossim_int32 ossimLasPointRecord2::getY() const { return m_record.m_y; } ossim_int32 ossimLasPointRecord2::getZ() const { return m_record.m_z; } ossim_uint16 ossimLasPointRecord2::getRed() const { return m_record.m_red; } ossim_uint16 ossimLasPointRecord2::getGreen() const { return m_record.m_green; } ossim_uint16 ossimLasPointRecord2::getBlue() const { return m_record.m_blue; } ossim_uint16 ossimLasPointRecord2::getIntensity() const { return m_record.m_intensity; } ossim_uint8 ossimLasPointRecord2::getReturnNumber() const { return (m_record.m_bitFlags.m_returnNumber); } ossim_uint8 ossimLasPointRecord2::getNumberOfReturns() const { return (m_record.m_bitFlags.m_numberOfReturns); } ossim_uint8 ossimLasPointRecord2::getEdgeFlag() const { return (m_record.m_bitFlags.m_edgeOfFlightLine); } std::ostream& ossimLasPointRecord2::print(std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << std::setiosflags(std::ios_base::fixed) << std::setprecision(8); out << "x: " << m_record.m_x << "\ny: " << m_record.m_y << "\nz: " << m_record.m_z << "\nintensity: " << m_record.m_intensity << "\nreturn: " << int(getReturnNumber()) << "\nnumber_of_returns: " << int(getNumberOfReturns()) << "\nedge: " << (getEdgeFlag()?"true":"false") << "\nscan_direction: " << int(m_record.m_bitFlags.m_scanDirection) << "\nclassification: " << m_record.m_classification << "\nscan_angle_rank: " << int(m_record.m_scanAngleRank) << "\nuser_data: " << m_record.m_userData << "\npoint_source_id: " << m_record.m_pointSourceId << "\nred: " << m_record.m_red << "\ngreen: " << m_record.m_green << "\nblue: " << m_record.m_blue << std::endl; // Reset flags. out.setf(f); return out; } void ossimLasPointRecord2::swap() { ossimEndian endian; endian.swap(m_record.m_x); endian.swap(m_record.m_y); endian.swap(m_record.m_z); endian.swap(m_record.m_intensity); endian.swap(m_record.m_pointSourceId); endian.swap(m_record.m_red); endian.swap(m_record.m_green); endian.swap(m_record.m_blue); } ossim-Miami-2.9.1/src/support_data/ossimLasPointRecord3.cpp000066400000000000000000000127721352751253100237520ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord3.cpp // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Container class LAS point record type 3. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include ossimLasPointRecord3::ossimLasPointRecord3Data::ossimLasPointRecord3Data() : m_x(0), m_y(0), m_z(0), m_intensity(0), m_bitFlags(0), m_classification(0), m_scanAngleRank(0), m_userData(0), m_pointSourceId(0), m_gpsTime(0.0), m_red(0), m_green(0), m_blue(0) { } ossimLasPointRecord3::ossimLasPointRecord3Data::ossimLasPointRecord3Data( const ossimLasPointRecord3::ossimLasPointRecord3Data& obj) : m_x(obj.m_x), m_y(obj.m_y), m_z(obj.m_z), m_intensity(obj.m_intensity), m_bitFlags(obj.m_bitFlags), m_classification(obj.m_classification), m_scanAngleRank(obj.m_scanAngleRank), m_userData(obj.m_userData), m_pointSourceId(obj.m_pointSourceId), m_gpsTime(obj.m_gpsTime), m_red(obj.m_red), m_green(obj.m_green), m_blue(obj.m_blue) { } const ossimLasPointRecord3::ossimLasPointRecord3Data& ossimLasPointRecord3::ossimLasPointRecord3Data::operator=( const ossimLasPointRecord3::ossimLasPointRecord3Data& obj) { if ( this != &obj ) { m_x = obj.m_x; m_y = obj.m_y; m_z = obj.m_z; m_intensity = obj.m_intensity; m_bitFlags = obj.m_bitFlags; m_classification = obj.m_classification; m_scanAngleRank = obj.m_scanAngleRank; m_userData = obj.m_userData; m_pointSourceId = obj.m_pointSourceId; m_gpsTime = obj.m_gpsTime; m_red = obj.m_red; m_green = obj.m_green; m_blue = obj.m_blue; } return *this; } ossimLasPointRecord3::ossimLasPointRecord3() : m_record() { } ossimLasPointRecord3::ossimLasPointRecord3(const ossimLasPointRecord3& obj) : m_record(obj.m_record) { } const ossimLasPointRecord3& ossimLasPointRecord3::operator=(const ossimLasPointRecord3& copy_this) { if (this != ©_this) { m_record = copy_this.m_record; } return *this; } ossimLasPointRecord3::~ossimLasPointRecord3() { } void ossimLasPointRecord3::readStream(std::istream& in) { in.read((char*)&m_record, sizeof(ossimLasPointRecord3Data)); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { swap(); } } void ossimLasPointRecord3::writeStream(std::ostream& out) { if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Write little endian per spec: swap(); } out.write((char*)&m_record, sizeof(ossimLasPointRecord3Data)); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Swap back to native byte order if needed: swap(); } } ossim_int32 ossimLasPointRecord3::getX() const { return m_record.m_x; } ossim_int32 ossimLasPointRecord3::getY() const { return m_record.m_y; } ossim_int32 ossimLasPointRecord3::getZ() const { return m_record.m_z; } ossim_uint16 ossimLasPointRecord3::getRed() const { return 0; } ossim_uint16 ossimLasPointRecord3::getGreen() const { return 0; } ossim_uint16 ossimLasPointRecord3::getBlue() const { return 0; } ossim_uint16 ossimLasPointRecord3::getIntensity() const { return m_record.m_intensity; } ossim_uint8 ossimLasPointRecord3::getReturnNumber() const { return (m_record.m_bitFlags.m_returnNumber); } ossim_uint8 ossimLasPointRecord3::getNumberOfReturns() const { return (m_record.m_bitFlags.m_numberOfReturns); } ossim_uint8 ossimLasPointRecord3::getEdgeFlag() const { return (m_record.m_bitFlags.m_edgeOfFlightLine); } std::ostream& ossimLasPointRecord3::print(std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << std::setiosflags(std::ios_base::fixed) << std::setprecision(8); out << "x: " << m_record.m_x << "\ny: " << m_record.m_y << "\nz: " << m_record.m_z << "\nintensity: " << m_record.m_intensity << "\nreturn: " << int(getReturnNumber()) << "\nnumber_of_returns: " << int(getNumberOfReturns()) << "\nedge: " << (getEdgeFlag()?"true":"false") << "\nscan_direction: " << int(m_record.m_bitFlags.m_scanDirection) << "\nclassification: " << m_record.m_classification << "\nscan_angle_rank: " << int(m_record.m_scanAngleRank) << "\nuser_data: " << m_record.m_userData << "\npoint_source_id: " << m_record.m_pointSourceId << "\ngrs_time: " << m_record.m_gpsTime << "\nred: " << m_record.m_red << "\ngreen: " << m_record.m_green << "\nblue: " << m_record.m_blue << std::endl; // Reset flags. out.setf(f); return out; } void ossimLasPointRecord3::swap() { ossimEndian endian; endian.swap(m_record.m_x); endian.swap(m_record.m_y); endian.swap(m_record.m_z); endian.swap(m_record.m_intensity); endian.swap(m_record.m_pointSourceId); endian.swap(m_record.m_gpsTime); endian.swap(m_record.m_red); endian.swap(m_record.m_green); endian.swap(m_record.m_blue); } ossim-Miami-2.9.1/src/support_data/ossimLasPointRecord4.cpp000066400000000000000000000155461352751253100237550ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimLasPointRecord4.cpp // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David burken // // Description: Container class LAS point record type 4. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include ossimLasPointRecord4::ossimLasPointRecord4Data::ossimLasPointRecord4Data() : m_x(0), m_y(0), m_z(0), m_intensity(0), m_bitFlags(0), m_classification(0), m_scanAngleRank(0), m_userData(0), m_pointSourceId(0), m_gpsTime(0.0), m_wavePacketDescriptorIndex(0), m_byteOffsetToWaveformData(0), m_waveformPacketSizeInBytes(0), m_returnPointWaveformLocation(0.0), m_red(0), m_green(0), m_blue(0) { } ossimLasPointRecord4::ossimLasPointRecord4Data::ossimLasPointRecord4Data( const ossimLasPointRecord4::ossimLasPointRecord4Data& obj) : m_x(obj.m_x), m_y(obj.m_y), m_z(obj.m_z), m_intensity(obj.m_intensity), m_bitFlags(obj.m_bitFlags), m_classification(obj.m_classification), m_scanAngleRank(obj.m_scanAngleRank), m_userData(obj.m_userData), m_pointSourceId(obj.m_pointSourceId), m_gpsTime(obj.m_gpsTime), m_wavePacketDescriptorIndex(obj.m_wavePacketDescriptorIndex), m_byteOffsetToWaveformData(obj.m_byteOffsetToWaveformData), m_waveformPacketSizeInBytes(obj.m_waveformPacketSizeInBytes), m_returnPointWaveformLocation(obj.m_returnPointWaveformLocation), m_red(obj.m_red), m_green(obj.m_green), m_blue(obj.m_blue) { } const ossimLasPointRecord4::ossimLasPointRecord4Data& ossimLasPointRecord4::ossimLasPointRecord4Data::operator=( const ossimLasPointRecord4::ossimLasPointRecord4Data& obj) { if ( this != &obj ) { m_x = obj.m_x; m_y = obj.m_y; m_z = obj.m_z; m_intensity = obj.m_intensity; m_bitFlags = obj.m_bitFlags; m_classification = obj.m_classification; m_scanAngleRank = obj.m_scanAngleRank; m_userData = obj.m_userData; m_pointSourceId = obj.m_pointSourceId; m_gpsTime = obj.m_gpsTime; m_wavePacketDescriptorIndex = obj.m_wavePacketDescriptorIndex; m_byteOffsetToWaveformData = obj.m_byteOffsetToWaveformData; m_waveformPacketSizeInBytes = obj.m_waveformPacketSizeInBytes; m_returnPointWaveformLocation = obj.m_returnPointWaveformLocation; m_red = obj.m_red; m_green = obj.m_green; m_blue = obj.m_blue; } return *this; } ossimLasPointRecord4::ossimLasPointRecord4() : m_record() { } ossimLasPointRecord4::ossimLasPointRecord4(const ossimLasPointRecord4& obj) : m_record(obj.m_record) { } const ossimLasPointRecord4& ossimLasPointRecord4::operator=(const ossimLasPointRecord4& copy_this) { if (this != ©_this) { m_record = copy_this.m_record; } return *this; } ossimLasPointRecord4::~ossimLasPointRecord4() { } void ossimLasPointRecord4::readStream(std::istream& in) { in.read((char*)&m_record, sizeof(ossimLasPointRecord4Data)); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { swap(); } } void ossimLasPointRecord4::writeStream(std::ostream& out) { if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Write little endian per spec: swap(); } out.write((char*)&m_record, sizeof(ossimLasPointRecord4Data)); if ( ossim::byteOrder() == OSSIM_BIG_ENDIAN ) { // Swap back to native byte order if needed: swap(); } } ossim_int32 ossimLasPointRecord4::getX() const { return m_record.m_x; } ossim_int32 ossimLasPointRecord4::getY() const { return m_record.m_y; } ossim_int32 ossimLasPointRecord4::getZ() const { return m_record.m_z; } ossim_uint16 ossimLasPointRecord4::getRed() const { return 0; } ossim_uint16 ossimLasPointRecord4::getGreen() const { return 0; } ossim_uint16 ossimLasPointRecord4::getBlue() const { return 0; } ossim_uint16 ossimLasPointRecord4::getIntensity() const { return m_record.m_intensity; } ossim_uint8 ossimLasPointRecord4::getReturnNumber() const { return (m_record.m_bitFlags.m_returnNumber); } ossim_uint8 ossimLasPointRecord4::getNumberOfReturns() const { return (m_record.m_bitFlags.m_numberOfReturns); } ossim_uint8 ossimLasPointRecord4::getEdgeFlag() const { return (m_record.m_bitFlags.m_edgeOfFlightLine); } std::ostream& ossimLasPointRecord4::print(std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << std::setiosflags(std::ios_base::fixed) << std::setprecision(8); out << "x: " << m_record.m_x << "\ny: " << m_record.m_y << "\nz: " << m_record.m_z << "\nintensity: " << m_record.m_intensity << "\nreturn: " << int(getReturnNumber()) << "\nnumber_of_returns: " << int(getNumberOfReturns()) << "\nedge: " << (getEdgeFlag()?"true":"false") << "\nscan_direction: " << int(m_record.m_bitFlags.m_scanDirection) << "\nclassification: " << m_record.m_classification << "\nscan_angle_rank: " << int(m_record.m_scanAngleRank) << "\nuser_data: " << m_record.m_userData << "\npoint_source_id: " << m_record.m_pointSourceId << "\ngrs_time: " << m_record.m_gpsTime << "\nwave_packet_descriptor_index: " << m_record.m_wavePacketDescriptorIndex << "\nbyte_offset_to_waveform_data: " << m_record.m_byteOffsetToWaveformData << "\nwaveform_packet_size_in_bytes: " << m_record.m_waveformPacketSizeInBytes << "\nm_returnPointWaveformLocation: " << m_record.m_returnPointWaveformLocation << "\nred: " << m_record.m_red << "\ngreen: " << m_record.m_green << "\nblue: " << m_record.m_blue << std::endl; // Reset flags. out.setf(f); return out; } void ossimLasPointRecord4::swap() { ossimEndian endian; endian.swap(m_record.m_x); endian.swap(m_record.m_y); endian.swap(m_record.m_z); endian.swap(m_record.m_intensity); endian.swap(m_record.m_pointSourceId); endian.swap(m_record.m_gpsTime); endian.swap(m_record.m_byteOffsetToWaveformData); endian.swap(m_record.m_waveformPacketSizeInBytes); endian.swap(m_record.m_returnPointWaveformLocation); endian.swap(m_record.m_red); endian.swap(m_record.m_green); endian.swap(m_record.m_blue); } ossim-Miami-2.9.1/src/support_data/ossimNitfAcftbTag.cpp000066400000000000000000000211441352751253100232640ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: ACFTB - Aircraft Infomation Extension Format tag class // declaration. // // See document STDI-0002 (version 3), Appendix E, Table E-6 for more info. // //---------------------------------------------------------------------------- // $Id #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfAcftbTag, "ossimNitfAcftbTag", ossimNitfRegisteredTag); ossimNitfAcftbTag::ossimNitfAcftbTag() : ossimNitfRegisteredTag(std::string("ACFTB"), CEL_SIZE) { clearFields(); } ossimNitfAcftbTag::~ossimNitfAcftbTag() { } void ossimNitfAcftbTag::parseStream(std::istream& in) { clearFields(); in.read(theAcMsnId, AC_MSN_ID_SIZE); in.read(theAcTailNo, AC_TAIL_NO_SIZE); in.read(theAcTo, AC_TO_SIZE); in.read(theSensorIdType, SENSOR_ID_TYPE_SIZE); in.read(theSensorId, SENSOR_ID_SIZE); in.read(theSceneSource, SCENE_SOURCE_SIZE); in.read(theScNum, SCNUM_SIZE); in.read(thePDate, PDATE_SIZE); in.read(theImHostNo, IMHOSTNO_SIZE); in.read(theImReqID, IMREQID_SIZE); in.read(theMPlan, MPLAN_SIZE); in.read(theEntLoc, ENTLOC_SIZE); in.read(theLocAccy, LOC_ACCY_SIZE); in.read(theEntelv, ENTELV_SIZE); in.read(theElvUnit, ELV_UNIT_SIZE); in.read(theExitLoc, EXITLOC_SIZE); in.read(theExitElev, EXITELV_SIZE); in.read(theTMap, TMAP_SIZE); in.read(theRowSpacing, ROW_SPACING_SIZE); in.read(theRowSpacingUnits, ROW_SPACING_UNITS_SIZE); in.read(theColSpacing, COL_SPACING_SIZE); in.read(theColSpacingUnits, COL_SPACING_UINTS_SIZE); in.read(theFocalLength, FOCAL_LENGTH_SIZE); in.read(theSenserial, SENSERIAL_SIZE); in.read(theAbSwVer, ABSWVER_SIZE); in.read(theCalDate, CAL_DATE_SIZE); in.read(thePatchTot, PATCH_TOT_SIZE); in.read(theMtiTot, MTI_TOT_SIZE); } void ossimNitfAcftbTag::writeStream(std::ostream& out) { out.write(theAcMsnId, AC_MSN_ID_SIZE); out.write(theAcTailNo, AC_TAIL_NO_SIZE); out.write(theAcTo, AC_TO_SIZE); out.write(theSensorIdType, SENSOR_ID_TYPE_SIZE); out.write(theSensorId, SENSOR_ID_SIZE); out.write(theSceneSource, SCENE_SOURCE_SIZE); out.write(theScNum, SCNUM_SIZE); out.write(thePDate, PDATE_SIZE); out.write(theImHostNo, IMHOSTNO_SIZE); out.write(theImReqID, IMREQID_SIZE); out.write(theMPlan, MPLAN_SIZE); out.write(theEntLoc, ENTLOC_SIZE); out.write(theLocAccy, LOC_ACCY_SIZE); out.write(theEntelv, ENTELV_SIZE); out.write(theElvUnit, ELV_UNIT_SIZE); out.write(theExitLoc, EXITLOC_SIZE); out.write(theExitElev, EXITELV_SIZE); out.write(theTMap, TMAP_SIZE); out.write(theRowSpacing, ROW_SPACING_SIZE); out.write(theRowSpacingUnits, ROW_SPACING_UNITS_SIZE); out.write(theColSpacing, COL_SPACING_SIZE); out.write(theColSpacingUnits, COL_SPACING_UINTS_SIZE); out.write(theFocalLength, FOCAL_LENGTH_SIZE); out.write(theSenserial, SENSERIAL_SIZE); out.write(theAbSwVer, ABSWVER_SIZE); out.write(theCalDate, CAL_DATE_SIZE); out.write(thePatchTot, PATCH_TOT_SIZE); out.write(theMtiTot, MTI_TOT_SIZE); } void ossimNitfAcftbTag::clearFields() { // BCS-N's to '0's, BCS-A's to ' '(spaces) // clear memset(theAcMsnId, ' ', AC_MSN_ID_SIZE); memset(theAcTailNo, ' ', AC_TAIL_NO_SIZE); memset(theAcTo, ' ', AC_TO_SIZE); memset(theSensorIdType, ' ', SENSOR_ID_TYPE_SIZE); memset(theSensorId, ' ', SENSOR_ID_SIZE); memset(theSceneSource, ' ', SCENE_SOURCE_SIZE); memset(theScNum, ' ', SCNUM_SIZE); memset(thePDate, ' ', PDATE_SIZE); memset(theImHostNo, ' ', IMHOSTNO_SIZE); memset(theImReqID, ' ', IMREQID_SIZE); memset(theMPlan, ' ', MPLAN_SIZE); memset(theEntLoc, ' ', ENTLOC_SIZE); memset(theLocAccy, ' ', LOC_ACCY_SIZE); memset(theEntelv, ' ', ENTELV_SIZE); memset(theElvUnit, ' ', ELV_UNIT_SIZE); memset(theExitLoc, ' ', EXITLOC_SIZE); memset(theExitElev, ' ', EXITELV_SIZE); memset(theTMap, ' ', TMAP_SIZE); memset(theRowSpacing, ' ', ROW_SPACING_SIZE); memset(theRowSpacingUnits, ' ', ROW_SPACING_UNITS_SIZE); memset(theColSpacing, ' ', COL_SPACING_SIZE); memset(theColSpacingUnits, ' ', COL_SPACING_UINTS_SIZE); memset(theFocalLength, ' ', FOCAL_LENGTH_SIZE); memset(theSenserial, ' ', SENSERIAL_SIZE); memset(theAbSwVer, ' ', ABSWVER_SIZE); memset(theCalDate, ' ', CAL_DATE_SIZE); memset(thePatchTot, ' ', PATCH_TOT_SIZE); memset(theMtiTot, ' ', MTI_TOT_SIZE); // null terminate theAcMsnId[AC_MSN_ID_SIZE] = '\0'; theAcTailNo[AC_TAIL_NO_SIZE] = '\0'; theAcTo[AC_TO_SIZE] = '\0'; theSensorIdType[SENSOR_ID_TYPE_SIZE] = '\0'; theSensorId[SENSOR_ID_SIZE] = '\0'; theSceneSource[SCENE_SOURCE_SIZE] = '\0'; theScNum[SCNUM_SIZE] = '\0'; thePDate[PDATE_SIZE] = '\0'; theImHostNo[IMHOSTNO_SIZE] = '\0'; theImReqID[IMREQID_SIZE] = '\0'; theMPlan[MPLAN_SIZE] = '\0'; theEntLoc[ENTLOC_SIZE] = '\0'; theLocAccy[LOC_ACCY_SIZE] = '\0'; theEntelv[ENTELV_SIZE] = '\0'; theElvUnit[ELV_UNIT_SIZE] = '\0'; theExitLoc[EXITLOC_SIZE] = '\0'; theExitElev[EXITELV_SIZE] = '\0'; theTMap[TMAP_SIZE] = '\0'; theRowSpacing[ROW_SPACING_SIZE] = '\0'; theRowSpacingUnits[ROW_SPACING_UNITS_SIZE] = '\0'; theColSpacing[COL_SPACING_SIZE] = '\0'; theColSpacingUnits[COL_SPACING_UINTS_SIZE] = '\0'; theFocalLength[FOCAL_LENGTH_SIZE] = '\0'; theSenserial[SENSERIAL_SIZE] = '\0'; theAbSwVer[ABSWVER_SIZE] = '\0'; theCalDate[CAL_DATE_SIZE] = '\0'; thePatchTot[PATCH_TOT_SIZE] = '\0'; theMtiTot[MTI_TOT_SIZE] = '\0'; } ossimString ossimNitfAcftbTag::getFocalLength()const { return ossimString(theFocalLength); } ossimString ossimNitfAcftbTag::getColumnSpacing()const { return ossimString(theColSpacing); } ossimString ossimNitfAcftbTag::getColumnSpacingUnits()const { return ossimString(theColSpacingUnits); } ossimString ossimNitfAcftbTag::getRowSpacing()const { return ossimString(theRowSpacing); } ossimString ossimNitfAcftbTag::getRowSpacingUnits()const { return ossimString(theRowSpacingUnits); } std::ostream& ossimNitfAcftbTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "AC_MSN_ID:" << theAcMsnId << "\n" << pfx << std::setw(24) << "AC_TAIL_NO:" << theAcTailNo << "\n" << pfx << std::setw(24) << "AC_TO:" << theAcTo << "\n" << pfx << std::setw(24) << "SENSOR_ID_TYPE:" << theSensorIdType << "\n" << pfx << std::setw(24) << "SENSOR_ID:" << theSensorId << "\n" << pfx << std::setw(24) << "SCENE_SOURCE:" << theSceneSource << "\n" << pfx << std::setw(24) << "SCNUM:" << theScNum << "\n" << pfx << std::setw(24) << "PDATE:" << thePDate << "\n" << pfx << std::setw(24) << "IMHOSTNO:" << theImHostNo << "\n" << pfx << std::setw(24) << "IMREQID:" << theImReqID << "\n" << pfx << std::setw(24) << "MPLAN:" << theMPlan << "\n" << pfx << std::setw(24) << "ENTLOC:" << theEntLoc << "\n" << pfx << std::setw(24) << "LOC_ACCY:" << theLocAccy << "\n" << pfx << std::setw(24) << "ENTELV:" << theEntelv << "\n" << pfx << std::setw(24) << "ELV_UNIT:" << theElvUnit << "\n" << pfx << std::setw(24) << "EXITLOC:" << theExitLoc << "\n" << pfx << std::setw(24) << "EXITELV:" << theExitElev << "\n" << pfx << std::setw(24) << "TMAP:" << theTMap << "\n" << pfx << std::setw(24) << "ROW_SPACING:" << theRowSpacing << "\n" << pfx << std::setw(24) << "ROW_SPACING_UNITS:" << theRowSpacingUnits << "\n" << pfx << std::setw(24) << "COL_SPACING:" << theColSpacing << "\n" << pfx << std::setw(24) << "COL_SPACING_UINTS:" << theColSpacingUnits << "\n" << pfx << std::setw(24) << "FOCAL_LENGTH:" << theFocalLength << "\n" << pfx << std::setw(24) << "SENSERIAL:" << theSenserial << "\n" << pfx << std::setw(24) << "ABSWVER:" << theAbSwVer << "\n" << pfx << std::setw(24) << "CAL_DATE:" << theCalDate << "\n" << pfx << std::setw(24) << "PATCH_TOT:" << thePatchTot << "\n" << pfx << std::setw(24) << "MTI_TOT:" << theMtiTot << "\n"; return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfAimidbTag.cpp000066400000000000000000000137321352751253100234360ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: AIMIDB - Additional Image ID Extension Format tag class // definition. // // See document STDI-0002 (version 3), Appendix E, Table E-3 for more info. // //---------------------------------------------------------------------------- // $Id #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfAimidbTag, "ossimNitfAimidbTag", ossimNitfRegisteredTag); ossimNitfAimidbTag::ossimNitfAimidbTag() : ossimNitfRegisteredTag(std::string("AIMIDB"), CEL_SIZE) { clearFields(); } ossimNitfAimidbTag::~ossimNitfAimidbTag() { } void ossimNitfAimidbTag::parseStream(std::istream& in) { clearFields(); in.read(theAcquisitionDate, ACQUISITION_DATE_SIZE); in.read(theMissionNumber, MISSION_NO_SIZE); in.read(theMissionIdentification, MISSION_IDENTIFICATION_SIZE); in.read(theFlightNo, FLIGHT_NO_SIZE); in.read(theOpNum, OP_NUM_SIZE); in.read(theCurrentSegment, CURRENT_SEGMENT_SIZE); in.read(theReproNum, REPRO_NUM_SIZE); in.read(theReplay, REPLAY_SIZE); in.read(theReserved1, RESERVED_1_SIZE); in.read(theStartTileColumn, START_TILE_COLUMN_SIZE); in.read(theStartTileRow, START_TILE_ROW_SIZE); in.read(theEndSegment, END_SEGMENT_SIZE); in.read(theTileColumn, END_TILE_COLUMN_SIZE); in.read(theTileRow, END_TILE_ROW_SIZE); in.read(theCountry, COUNTRY_SIZE); in.read(theReserved2, RESERVED_2_SIZE); in.read(theLocation, LOCATION_SIZE); in.read(theReserved3, RESERVED_3_SIZE); } void ossimNitfAimidbTag::writeStream(std::ostream& out) { out.write(theAcquisitionDate, ACQUISITION_DATE_SIZE); out.write(theMissionNumber, MISSION_NO_SIZE); out.write(theMissionIdentification, MISSION_IDENTIFICATION_SIZE); out.write(theFlightNo, FLIGHT_NO_SIZE); out.write(theOpNum, OP_NUM_SIZE); out.write(theCurrentSegment, CURRENT_SEGMENT_SIZE); out.write(theReproNum, REPRO_NUM_SIZE); out.write(theReplay, REPLAY_SIZE); out.write(theReserved1, RESERVED_1_SIZE); out.write(theStartTileColumn, START_TILE_COLUMN_SIZE); out.write(theStartTileRow, START_TILE_ROW_SIZE); out.write(theEndSegment, END_SEGMENT_SIZE); out.write(theTileColumn, END_TILE_COLUMN_SIZE); out.write(theTileRow, END_TILE_ROW_SIZE); out.write(theCountry, COUNTRY_SIZE); out.write(theReserved2, RESERVED_2_SIZE); out.write(theLocation, LOCATION_SIZE); out.write(theReserved3, RESERVED_3_SIZE); } void ossimNitfAimidbTag::clearFields() { // BCS-N's to '0's, BCS-A's to ' '(spaces) // clear memset(theAcquisitionDate, ' ', ACQUISITION_DATE_SIZE); memset(theMissionNumber, ' ', MISSION_NO_SIZE); memset(theMissionIdentification, ' ', MISSION_IDENTIFICATION_SIZE); memset(theFlightNo, ' ', FLIGHT_NO_SIZE); memset(theOpNum, ' ', OP_NUM_SIZE); memset(theCurrentSegment, ' ', CURRENT_SEGMENT_SIZE); memset(theReproNum, ' ', REPRO_NUM_SIZE); memset(theReplay, ' ', REPLAY_SIZE); memset(theReserved1, ' ', RESERVED_1_SIZE); memset(theStartTileColumn, ' ', START_TILE_COLUMN_SIZE); memset(theStartTileRow, ' ', START_TILE_ROW_SIZE); memset(theEndSegment, ' ', END_SEGMENT_SIZE); memset(theTileColumn, ' ', END_TILE_COLUMN_SIZE); memset(theTileRow, ' ', END_TILE_ROW_SIZE); memset(theCountry, ' ', COUNTRY_SIZE); memset(theReserved2, ' ', RESERVED_2_SIZE); memset(theLocation, ' ', LOCATION_SIZE); memset(theReserved3, ' ', RESERVED_3_SIZE); // null terminate theAcquisitionDate[ACQUISITION_DATE_SIZE] = '\0'; theMissionNumber[MISSION_NO_SIZE] = '\0'; theMissionIdentification[MISSION_IDENTIFICATION_SIZE] = '\0'; theFlightNo[FLIGHT_NO_SIZE] = '\0'; theOpNum[OP_NUM_SIZE] = '\0'; theCurrentSegment[CURRENT_SEGMENT_SIZE] = '\0'; theReproNum[REPRO_NUM_SIZE] = '\0'; theReplay[REPLAY_SIZE] = '\0'; theReserved1[RESERVED_1_SIZE] = '\0'; theStartTileColumn[START_TILE_COLUMN_SIZE] = '\0'; theStartTileRow[START_TILE_ROW_SIZE] = '\0'; theEndSegment[END_SEGMENT_SIZE] = '\0'; theTileColumn[END_TILE_COLUMN_SIZE] = '\0'; theTileRow[END_TILE_ROW_SIZE] = '\0'; theCountry[COUNTRY_SIZE] = '\0'; theReserved2[RESERVED_2_SIZE] = '\0'; theLocation[LOCATION_SIZE] = '\0'; theReserved3[RESERVED_3_SIZE] = '\0'; } std::ostream& ossimNitfAimidbTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "ACQUISITION_DATE:" << theAcquisitionDate << "\n" << pfx << std::setw(24) << "MISSION_NO:" << theMissionNumber << "\n" << pfx << std::setw(24) << "MISSION_IDENTIFICATION:" << theMissionIdentification<< "\n" << pfx << std::setw(24) << "FLIGHT_NO:" << theFlightNo << "\n" << pfx << std::setw(24) << "OP_NUM:" << theOpNum << "\n" << pfx << std::setw(24) << "CURRENT_SEGMENT:" << theCurrentSegment << "\n" << pfx << std::setw(24) << "REPRO_NUM:" << theReproNum<< "\n" << pfx << std::setw(24) << "REPLAY:" << theReplay<< "\n" << pfx << std::setw(24) << "START_TILE_COLUMN:" << theStartTileColumn << "\n" << pfx << std::setw(24) << "START_TILE_ROW:" << theStartTileRow << "\n" << pfx << std::setw(24) << "END_SEGMENT:" << theEndSegment << "\n" << pfx << std::setw(24) << "END_TILE_COLUMN:" << theTileColumn << "\n" << pfx << std::setw(24) << "END_TILE_ROW:" << theTileRow << "\n" << pfx << std::setw(24) << "COUNTRY:" << theCountry << "\n" << pfx << std::setw(24) << "LOCATION:" << theLocation << "\n"; return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfBlockaTag.cpp000066400000000000000000000231151352751253100234400ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: BLOCKA tag class declaration. // //---------------------------------------------------------------------------- // $Id: ossimNitfBlockaTag.cpp 23245 2015-04-08 20:53:04Z rashadkm $ #include /* for memcpy */ #include #include #include #include #include #include #include #include using namespace std; static const ossimTrace traceDebug(ossimString("ossimNitfBlockaTag:debug")); RTTI_DEF1(ossimNitfBlockaTag, "ossimNitfBlockaTag", ossimNitfRegisteredTag); ossimNitfBlockaTag::ossimNitfBlockaTag() : ossimNitfRegisteredTag(std::string("BLOCKA"), 123) { clearFields(); } void ossimNitfBlockaTag::parseStream(std::istream& in) { clearFields(); in.read(theBlockInstance, BLOCK_INSTANCE_SIZE); in.read(theNGray, N_GRAY_SIZE); in.read(theLLines, L_LINES_SIZE); in.read(theLayoverAngle, LAYOVER_ANGLE_SIZE); in.read(theShadowAngle, SHADOW_ANGLE_SIZE); in.read(theField6, FIELD_6_SIZE); in.read(theFrlcLoc, FRLC_LOC_SIZE); in.read(theLrlcLoc, LRLC_LOC_SIZE); in.read(theLrfcLoc, LRFC_LOC_SIZE); in.read(theFrfcLoc, FRFC_LOC_SIZE); in.read(theField11, FIELD_11_SIZE); } void ossimNitfBlockaTag::writeStream(std::ostream& out) { out.write(theBlockInstance, BLOCK_INSTANCE_SIZE); out.write(theNGray, N_GRAY_SIZE); out.write(theLLines, L_LINES_SIZE); out.write(theLayoverAngle, LAYOVER_ANGLE_SIZE); out.write(theShadowAngle, SHADOW_ANGLE_SIZE); out.write(theField6, FIELD_6_SIZE); out.write(theFrlcLoc, FRLC_LOC_SIZE); out.write(theLrlcLoc, LRLC_LOC_SIZE); out.write(theLrfcLoc, LRFC_LOC_SIZE); out.write(theFrfcLoc, FRFC_LOC_SIZE); out.write(theField11, FIELD_11_SIZE); } void ossimNitfBlockaTag::clearFields() { memcpy(theBlockInstance, "01", BLOCK_INSTANCE_SIZE); memset(theNGray, 0, N_GRAY_SIZE); memset(theLLines, 0, L_LINES_SIZE); memset(theLayoverAngle, ' ', LAYOVER_ANGLE_SIZE); memset(theShadowAngle, ' ', SHADOW_ANGLE_SIZE); memset(theField6, ' ', FIELD_6_SIZE); memset(theFrlcLoc, ' ', FRLC_LOC_SIZE); memset(theLrlcLoc, ' ', LRLC_LOC_SIZE); memset(theLrfcLoc, ' ', LRFC_LOC_SIZE); memset(theFrfcLoc, ' ', FRFC_LOC_SIZE); memcpy(theField11, "010.0", FIELD_11_SIZE); theBlockInstance[BLOCK_INSTANCE_SIZE] = '\0'; theNGray[N_GRAY_SIZE] = '\0'; theLLines[L_LINES_SIZE] = '\0'; theLayoverAngle[LAYOVER_ANGLE_SIZE] = '\0'; theShadowAngle[SHADOW_ANGLE_SIZE] = '\0'; theField6[FIELD_6_SIZE] = '\0'; theFrlcLoc[FRLC_LOC_SIZE] = '\0'; theLrlcLoc[LRLC_LOC_SIZE] = '\0'; theLrfcLoc[LRFC_LOC_SIZE] = '\0'; theFrfcLoc[FRFC_LOC_SIZE] = '\0'; theField11[FIELD_11_SIZE] = '\0'; } std::ostream& ossimNitfBlockaTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; // Grab the corners parsed into points. ossimDpt ulPt; ossimDpt urPt; ossimDpt lrPt; ossimDpt llPt; getFrfcLoc(ulPt); getFrlcLoc(urPt); getLrlcLoc(lrPt); getLrfcLoc(llPt); out << setiosflags(ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "BLOCK_INSTANCE:" << theBlockInstance << "\n" << pfx << std::setw(24) << "N_GRAY:" << theNGray << "\n" << pfx << std::setw(24) << "L_LINES:" << theLLines << "\n" << pfx << std::setw(24) << "LAYOVER_ANGLE:" << theLayoverAngle << "\n" << pfx << std::setw(24) << "SHADOW_ANGLE:" << theShadowAngle << "\n" << pfx << std::setw(24) << "FIELD_6:" << theField6 << "\n" << pfx << std::setw(24) << "FRLC_LOC:" << theFrlcLoc << "\n" << pfx << std::setw(24) << "LRLC_LOC:" << theLrlcLoc << "\n" << pfx << std::setw(24) << "LRFC_LOC:" << theLrfcLoc << "\n" << pfx << std::setw(24) << "FRFC_LOC:" << theFrfcLoc << "\n" << pfx << std::setw(24) << "FIELD_11:" << theField11 << "\n" << pfx << std::setw(24) << "upper left:" << ulPt << "\n" << pfx << std::setw(24) << "upper right:" << urPt << "\n" << pfx << std::setw(24) << "lower right:" << lrPt << "\n" << pfx << std::setw(24) << "lower left:" << llPt << "\n"; return out; } void ossimNitfBlockaTag::setBlockInstance(ossim_uint32 block) { if ( (block > 0) && (block < 100) ) { ossimString os = ossimNitfCommon::convertToIntString(block, BLOCK_INSTANCE_SIZE); memcpy(theBlockInstance, os.c_str(), BLOCK_INSTANCE_SIZE); } } ossimString ossimNitfBlockaTag::getBlockInstance() const { return ossimString(theBlockInstance); } void ossimNitfBlockaTag::setNGray(ossim_uint32 grayCount) { if (grayCount < 100000) { ossimString os = ossimNitfCommon::convertToUIntString(grayCount, N_GRAY_SIZE); memcpy(theNGray, os.c_str(), N_GRAY_SIZE); } } ossimString ossimNitfBlockaTag::getNGray() const { return ossimString(theNGray); } void ossimNitfBlockaTag::setLLines(ossim_uint32 lines) { if (lines < 100000) { ossimString os = ossimNitfCommon::convertToUIntString(lines, L_LINES_SIZE); memcpy(theLLines, os.c_str(), L_LINES_SIZE); } } ossimString ossimNitfBlockaTag::getLLines() const { return ossimString(theLLines); } void ossimNitfBlockaTag::setLayoverAngle(ossim_uint32 angle) { if (angle < 360) { ossimString os = ossimNitfCommon::convertToUIntString(angle, LAYOVER_ANGLE_SIZE); memcpy(theLayoverAngle, os.c_str(), LAYOVER_ANGLE_SIZE); } } ossimString ossimNitfBlockaTag::getLayoverAngle() const { return ossimString(theLayoverAngle); } void ossimNitfBlockaTag::setShadowAngle(ossim_uint32 angle) { if (angle < 360) { ossimString os = ossimNitfCommon::convertToUIntString(angle, SHADOW_ANGLE_SIZE); memcpy(theShadowAngle, os.c_str(), SHADOW_ANGLE_SIZE); } } ossimString ossimNitfBlockaTag::getShadowAngle() const { return ossimString(theShadowAngle); } void ossimNitfBlockaTag::setFrlcLoc(const ossimDpt& pt) { ossimString os = ossimNitfCommon::convertToDdLatLonLocString(pt, 6); memcpy(theFrlcLoc, os.c_str(), FRLC_LOC_SIZE); } ossimString ossimNitfBlockaTag::getFrlcLoc() const { return ossimString(theFrlcLoc); } void ossimNitfBlockaTag::getFrlcLoc(ossimDpt& pt) const { ossimString os = theFrlcLoc; converLocStringToPt(os, pt); } void ossimNitfBlockaTag::setLrlcLoc(const ossimDpt& pt) { ossimString os = ossimNitfCommon::convertToDdLatLonLocString(pt, 6); memcpy(theLrlcLoc, os.c_str(), LRLC_LOC_SIZE); } ossimString ossimNitfBlockaTag::getLrlcLoc() const { return ossimString(theLrlcLoc); } void ossimNitfBlockaTag::getLrlcLoc(ossimDpt& pt) const { ossimString os = theLrlcLoc; converLocStringToPt(os, pt); } void ossimNitfBlockaTag::setLrfcLoc(const ossimDpt& pt) { ossimString os = ossimNitfCommon::convertToDdLatLonLocString(pt, 6); memcpy(theLrfcLoc, os.c_str(), LRFC_LOC_SIZE); } ossimString ossimNitfBlockaTag::getLrfcLoc() const { return ossimString(theLrfcLoc); } void ossimNitfBlockaTag::getLrfcLoc(ossimDpt& pt) const { ossimString os = theLrfcLoc; converLocStringToPt(os, pt); } void ossimNitfBlockaTag::setFrfcLoc(const ossimDpt& pt) { ossimString os = ossimNitfCommon::convertToDdLatLonLocString(pt, 6); memcpy(theFrfcLoc, os.c_str(), FRFC_LOC_SIZE); } ossimString ossimNitfBlockaTag::getFrfcLoc() const { return ossimString(theFrfcLoc); } void ossimNitfBlockaTag::getFrfcLoc(ossimDpt& pt) const { ossimString os = theFrfcLoc; converLocStringToPt(os, pt); } void ossimNitfBlockaTag::converLocStringToPt(const ossimString& locationString, ossimDpt& pt) const { if (locationString.size() != 21) return; std::string s = locationString; std::string lat(s, 0, 10); std::string lon(s, 10, 11); if ( (lat[0] == 'N') || (lat[0] == 'S') ) { // Need to enter spaces for ossimDms to parse correctly std::ostringstream latStream; latStream << lat.substr(0, 3) << " " << lat.substr(3, 2) << " " << lat.substr(5); lat = latStream.str(); // Use the dms class to parse. ossimDms dms(0.0, true); dms.setDegrees(lat.c_str()); pt.y = dms.getDegrees(); } else { ossimString os = lat; pt.y = os.toDouble(); } if ( (lon[0] == 'E') || (lon[0] == 'W') ) { // Need to enter spaces for ossimDms to parse correctly std::ostringstream lonStream; lonStream << lon.substr(0, 4) << " " << lon.substr(4, 2) << " " << lon.substr(6); lon = lonStream.str(); // Use the dms class to parse. ossimDms dms(0.0, false); dms.setDegrees(lon.c_str()); pt.x = dms.getDegrees(); } else { ossimString os = lon; pt.x = os.toDouble(); } } ossim-Miami-2.9.1/src/support_data/ossimNitfCommon.cpp000066400000000000000000000346411352751253100230470ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Utility class for global nitf methods. // //---------------------------------------------------------------------------- // $Id: ossimNitfCommon.cpp 17978 2010-08-24 16:17:00Z dburken $ #include /* for memcpy */ #include #include #include #include #include #include #include #include #include #include #include static const ossimTrace traceDebug(ossimString("ossimNitfCommon:debug")); ossimNitfCommon::ossimNitfCommon(){} ossimNitfCommon::~ossimNitfCommon(){} ossimString ossimNitfCommon::convertToScientificString( const ossim_float64& aValue, ossim_uint32 size) { // Precision cannot hit 0 for this to work... if ( ((aValue < 0.0) && (size < 8)) || ((aValue >= 0.0) && (size < 7)) ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfCommon::convertToScientificString DEBUG:" << "\nsize range error!" << std::endl; } return ossimString(); } //-- // Set the precision to account for size with 1.xxxxxE+01 //--- ossim_uint32 precision = size - 6; if (aValue < 0.0) { --precision; } std::ostringstream s1; s1 << std::setiosflags(std::ios_base::scientific|std::ios_base::internal) << std::setfill('0') // << setw(size) << std::setprecision(precision) << aValue; ossimString result = s1.str(); // Upcase the "e". result.upcase(); if (traceDebug()) { if (result.size() != size) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfCommon::convertToScientificString DEBUG:" << "\nIncorrect output size!" << "\nValue: " << aValue << "\nString: " << result << std::endl; } } return result; } ossimString ossimNitfCommon::convertToDoubleString( const ossim_float64& aValue, ossim_uint32 precision, ossim_uint32 size) { ossim_uint32 width = size; std::ostringstream s1; s1 << std::setiosflags(std::ios_base::fixed| std::ios_base::internal) << std::setprecision(precision) << std::setfill('0') << std::setw(width) << aValue; ossimString result = s1.str(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfCommon::convertToDoubleString DEBUG:" << "\nresult: " << result << std::endl; if (result.size() != size) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfCommon::convertToDoubleString DEBUG:" << "\nIncorrect output size!" << std::endl; } } return result; } ossimString ossimNitfCommon::convertToUIntString(ossim_uint32 aValue, ossim_uint32 size) { ossim_uint32 width = size; std::ostringstream s1; s1 << std::setiosflags(std::ios_base::fixed| std::ios_base::internal) << std::setfill('0') << std::setw(width) << aValue; ossimString result = s1.str(); if (traceDebug()) { if (result.size() != size) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfCommon::convertToUIntString DEBUG:" << "\nIncorrect output size!" << "\nValue: " << aValue << "\nString: " << result << std::endl; } } return result; } ossimString ossimNitfCommon::convertToIntString(ossim_int32 aValue, ossim_uint32 size) { ossim_uint32 width = size; std::ostringstream s1; s1 << std::setiosflags(std::ios_base::fixed| std::ios_base::internal) << std::setfill('0') << std::setw(width) << aValue; ossimString result = s1.str(); if (traceDebug()) { if (result.size() != size) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfCommon::convertToIntString DEBUG:" << "\nIncorrect output size!" << "\nValue: " << aValue << "\nString: " << result << std::endl; } } return result; } ossimString ossimNitfCommon::convertToDdLatLonLocString(const ossimDpt& pt, ossim_uint32 precision) { ossimString lat; ossimString lon; ossim_uint32 latSize = precision+4; // size = precision + "-33." ossim_uint32 lonSize = precision+5; // size = precision + "-122." if (pt.y >= 0.0) { lat = "+"; --latSize; } if (pt.x >= 0.0) { lon = "+"; --lonSize; } lat += convertToDoubleString(pt.y, precision, latSize); lon += convertToDoubleString(pt.x, precision, lonSize); ossimString result = lat+lon; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfCommon::convertToDdLatLonLocString DEBUG:" << "\nresult: " << result << std::endl; } return result; } void ossimNitfCommon::setField(void* fieldDestination, const ossimString& src, std::streamsize width, std::ios_base::fmtflags ioflags, char fill) { std::ostringstream out; out << std::setw(width) << std::setfill(fill) << std::setiosflags(ioflags) << src.trim().c_str(); memcpy(fieldDestination, out.str().c_str(), width); } ossimString ossimNitfCommon::encodeUtm( ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { std::ostringstream out; if(zone > 60) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUTM zone greate than 60!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } ossim_float64 east = ul.x; ossim_float64 north = ul.y; if((ossim_uint32)(east+.5) > 999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUpper left easting too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } if((ossim_uint32)(north+.5) > 9999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUpper left northing too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } out << std::setw(2) << std::setfill('0') << zone << std::setw(6) << std::setfill('0') <<(ossim_uint32)(east+.5) << std::setw(7) << std::setfill('0') <<(ossim_uint32)(north+.5); east = ur.x; north = ur.y; if((ossim_uint32)(east+.5) > 999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUpper right easting too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } if((ossim_uint32)(north+.5) > 9999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUpper right northing too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } out << std::setw(2) << std::setfill('0') << zone << std::setw(6) << std::setfill('0') <<(ossim_uint32)(east+.5) << std::setw(7) << std::setfill('0') <<(ossim_uint32)(north+.5); east = lr.x; north = lr.y; if((ossim_uint32)(east+.5) > 999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nLower right easting too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } if((ossim_uint32)(north+.5) > 9999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nLower right northing too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } out << std::setw(2) << std::setfill('0') << zone << std::setw(6) << std::setfill('0') <<(ossim_uint32)(east+.5) << std::setw(7) << std::setfill('0') <<(ossim_uint32)(north+.5); east = ll.x; north = ll.y; if((ossim_uint32)(east+.5) > 999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nLower left easting too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } if((ossim_uint32)(north+.5) > 9999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nLower left northing too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } out << std::setw(2) << std::setfill('0') << zone << std::setw(6) << std::setfill('0') <<(ossim_uint32)(east+.5) << std::setw(7) << std::setfill('0') <<(ossim_uint32)(north+.5); return out.str().c_str(); } ossimString ossimNitfCommon::encodeGeographicDms(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { std::ostringstream out; out << ossimDms(ul.y, true).toString("ddmmssC").c_str(); out << ossimDms(ul.x, false).toString("dddmmssC").c_str(); out << ossimDms(ur.y, true).toString("ddmmssC").c_str(); out << ossimDms(ur.x, false).toString("dddmmssC").c_str(); out << ossimDms(lr.y, true).toString("ddmmssC").c_str(); out << ossimDms(lr.x, false).toString("dddmmssC").c_str(); out << ossimDms(ll.y, true).toString("ddmmssC").c_str(); out << ossimDms(ll.x, false).toString("dddmmssC").c_str(); return ossimString(out.str()); } ossimString ossimNitfCommon::encodeGeographicDecimalDegrees(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { std::ostringstream out; out << (ul.lat >= 0.0?"+":"") << std::setw(6) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ul.lat << (ul.lon >= 0.0?"+":"") << std::setw(7) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ul.lon; out << (ur.lat >= 0.0?"+":"") << std::setw(6) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ur.lat << (ur.lon >= 0.0?"+":"") << std::setw(7) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ur.lon; out << (lr.lat >= 0.0?"+":"") << std::setw(6) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << lr.lat << (lr.lon >= 0.0?"+":"") << std::setw(7) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << lr.lon; out << (ll.lat >= 0.0?"+":"") << std::setw(6) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ll.lat << (ll.lon >= 0.0?"+":"") << std::setw(7) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ll.lon; return ossimString(out.str()); } ossimString ossimNitfCommon::getNitfPixelType(ossimScalarType scalarType) { ossimString pixelType; switch(scalarType) { case OSSIM_UINT8: case OSSIM_USHORT11: case OSSIM_USHORT12: case OSSIM_USHORT13: case OSSIM_USHORT14: case OSSIM_USHORT15: case OSSIM_UINT16: case OSSIM_UINT32: { pixelType = "INT"; break; } case OSSIM_SINT16: case OSSIM_SINT32: { pixelType = "SI"; break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { pixelType = "R"; break; } default: { ossimNotify(ossimNotifyLevel_DEBUG) << __FILE__ << ":" << __LINE__ << "\nUnhandled scalar type: " << scalarType << std::endl; break; } } return pixelType; } ossimString ossimNitfCommon::getCompressionRate(const ossimIrect& rect, ossim_uint32 bands, ossimScalarType scalar, ossim_uint64 lengthInBytes) { ossimString result(""); ossim_float64 uncompressedSize = ossim::scalarSizeInBytes(scalar) * rect.width() * rect.height() * bands; ossim_float64 bitsPerPix = ossim::getBitsPerPixel(scalar); ossim_float64 rate = ( bitsPerPix * (static_cast(lengthInBytes) / uncompressedSize) ); // Multiply by 100 as there is an implied decimal point. rate *= 100.0; // Convert to string with zero precision. ossimString s = ossimString::toString(rate, 0, 4); if (s.size()) { if (s.size() <= 3) { result = "N"; if (s.size() == 3) { result = "0"; } else if (s.size() == 2) { result = "00"; } result += s; } } return result; } ossim-Miami-2.9.1/src/support_data/ossimNitfCompressionHeader.cpp000066400000000000000000000013371352751253100252250ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2004 Garrett Potts // // LICENSE: LGPL see top level LICENSE.txt for more details // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfCompressionHeader.cpp 18413 2010-11-11 19:56:22Z gpotts $ #include #include #include RTTI_DEF1(ossimNitfCompressionHeader, "ossimNitfCompressionHeader", ossimObject); bool ossimNitfCompressionHeader::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { return ossimObject::saveState(kwl, prefix); } ossim-Miami-2.9.1/src/support_data/ossimNitfCsccgaTag.cpp000066400000000000000000000061101352751253100234240ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: CSCCGA tag source file // //---------------------------------------------------------------------------- // $Id$ #include #include #include using namespace std; ossimNitfCsccgaTag::ossimNitfCsccgaTag() : ossimNitfRegisteredTag(std::string("CSCCGA"), CEL_SIZE) { clearFields(); } void ossimNitfCsccgaTag::parseStream(std::istream& in) { in.read(m_ccgSource, CCG_SOURCE_SIZE); in.read(m_regSensor, REG_SENSOR_SIZE); in.read(m_originLine, ORIGIN_LINE_SIZE); in.read(m_originSample, ORIGIN_SAMPLE_SIZE); in.read(m_asCellSize, AS_CELL_SIZE_SIZE); in.read(m_csCellSize, CS_CELL_SIZE_SIZE); in.read(m_ccgMaxLine, CCG_MAX_LINE_SIZE); in.read(m_ccgMaxSample, CCG_MAX_SAMPLE_SIZE); } void ossimNitfCsccgaTag::writeStream(std::ostream& out) { out.write(m_ccgSource, CCG_SOURCE_SIZE); out.write(m_regSensor, REG_SENSOR_SIZE); out.write(m_originLine, ORIGIN_LINE_SIZE); out.write(m_originSample, ORIGIN_SAMPLE_SIZE); out.write(m_asCellSize, AS_CELL_SIZE_SIZE); out.write(m_csCellSize, CS_CELL_SIZE_SIZE); out.write(m_ccgMaxLine, CCG_MAX_LINE_SIZE); out.write(m_ccgMaxSample, CCG_MAX_SAMPLE_SIZE); } std::ostream& ossimNitfCsccgaTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "CCG_SOURCE:" << m_ccgSource << "\n" << pfx << std::setw(24) << "CCG_SOURCE:" << m_regSensor << "\n" << pfx << std::setw(24) << "ORIGIN_LINE:" << m_originLine << "\n" << pfx << std::setw(24) << "ORIGIN_SAMPLE:" << m_originSample << "\n" << pfx << std::setw(24) << "AS_CELL_SIZE:" << m_asCellSize << "\n" << pfx << std::setw(24) << "CS_CELL_SIZE:" << m_csCellSize << "\n" << pfx << std::setw(24) << "CCG_MAX_LINE:" << m_ccgMaxLine << "\n" << pfx << std::setw(24) << "CCG_MAX_SAMPLE:" << m_ccgMaxSample << "\n"; return out; } void ossimNitfCsccgaTag::clearFields() { memset(m_ccgSource,' ', CCG_SOURCE_SIZE); memset(m_regSensor, ' ', REG_SENSOR_SIZE); memset(m_originLine, 0, ORIGIN_LINE_SIZE); memset(m_originSample, 0, ORIGIN_SAMPLE_SIZE); memset(m_asCellSize, 0, AS_CELL_SIZE_SIZE); memset(m_csCellSize, 0, CS_CELL_SIZE_SIZE); memset(m_ccgMaxLine, 0, CCG_MAX_LINE_SIZE); memset(m_ccgMaxSample, 0, CCG_MAX_SAMPLE_SIZE); m_ccgSource[CCG_SOURCE_SIZE] = '\0'; m_regSensor[REG_SENSOR_SIZE] = '\0'; m_originLine[ORIGIN_LINE_SIZE] = '\0'; m_originSample[ORIGIN_SAMPLE_SIZE] = '\0'; m_asCellSize[AS_CELL_SIZE_SIZE] = '\0'; m_csCellSize[CS_CELL_SIZE_SIZE] = '\0'; m_ccgMaxLine[CCG_MAX_LINE_SIZE] = '\0'; m_ccgMaxSample[CCG_MAX_SAMPLE_SIZE] = '\0'; } ossim-Miami-2.9.1/src/support_data/ossimNitfCscrnaTag.cpp000066400000000000000000000072521352751253100234620ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: CSCRNA tag class definition. // // Corner Footprint TRE. // // See document STDI-0006-NCDRD Table 3.2-13 for more info. // //---------------------------------------------------------------------------- // $Id #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfCscrnaTag, "ossimNitfCscrnaTag", ossimNitfRegisteredTag); ossimNitfCscrnaTag::ossimNitfCscrnaTag() : ossimNitfRegisteredTag(std::string("CSCRNA"), 109) { clearFields(); } ossimNitfCscrnaTag::~ossimNitfCscrnaTag() { } void ossimNitfCscrnaTag::parseStream(std::istream& in) { clearFields(); in.read(thePredictedCornerFlag, 1); in.read(theUlLat, 9); in.read(theUlLon, 10); in.read(theUlHt, 8); in.read(theUrLat, 9); in.read(theUrLon, 10); in.read(theUrHt, 8); in.read(theLrLat, 9); in.read(theLrLon, 10); in.read(theLrHt, 8); in.read(theLlLat, 9); in.read(theLlLon, 10); in.read(theLlHt, 8); } void ossimNitfCscrnaTag::writeStream(std::ostream& out) { out.write(thePredictedCornerFlag, 1); out.write(theUlLat, 9); out.write(theUlLon, 10); out.write(theUlHt, 8); out.write(theUrLat, 9); out.write(theUrLon, 10); out.write(theUrHt, 8); out.write(theLrLat, 9); out.write(theLrLon, 10); out.write(theLrHt, 8); out.write(theLlLat, 9); out.write(theLlLon, 10); out.write(theLlHt, 8); } void ossimNitfCscrnaTag::clearFields() { // BCS-N's to '0's, BCS-A's to ' '(spaces) memset(thePredictedCornerFlag, ' ', 1); memset(theUlLat, 0, 9); memset(theUlLon, 0, 10); memset(theUlHt, 0, 8); memset(theUrLat, 0, 9); memset(theUrLon, 0, 10); memset(theUrHt, 0, 8); memset(theLrLat, 0, 9); memset(theLrLon, 0, 10); memset(theLrHt, 0, 8); memset(theLlLat, 0, 9); memset(theLlLon, 0, 10); memset(theLlHt, 0, 8); thePredictedCornerFlag[1] = '\0'; theUlLat[9] = '\0'; theUlLon[10] = '\0'; theUlHt[8] = '\0'; theUrLat[9] = '\0'; theUrLon[10] = '\0'; theUrHt[8] = '\0'; theLrLat[9] = '\0'; theLrLon[10] = '\0'; theLrHt[8] = '\0'; theLlLat[9] = '\0'; theLlLon[10] = '\0'; theLlHt[8] = '\0'; } std::ostream& ossimNitfCscrnaTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "PREDICT_CORNERS:" << thePredictedCornerFlag << "\n" << pfx << std::setw(24) << "ULCRN_LAT:" << theUlLat << "\n" << pfx << std::setw(24) << "ULCRN_LON:" << theUlLon << "\n" << pfx << std::setw(24) << "ULCRN_HT:" << theUlHt << "\n" << pfx << std::setw(24) << "URCRN_LAT:" << theUrLat << "\n" << pfx << std::setw(24) << "URCRN_LON:" << theUrLon << "\n" << pfx << std::setw(24) << "URCRN_HT:" << theUrHt << "\n" << pfx << std::setw(24) << "LRCRN_LAT:" << theLrLat << "\n" << pfx << std::setw(24) << "LRCRN_LON:" << theLrLon << "\n" << pfx << std::setw(24) << "LRCRN_HT:" << theLrHt << "\n" << pfx << std::setw(24) << "LLCRN_LAT:" << theLlLat << "\n" << pfx << std::setw(24) << "LLCRN_LON:" << theLlLon << "\n" << pfx << std::setw(24) << "LLCRN_HT:" << theLlHt << "\n"; return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfCsdidaTag.cpp000066400000000000000000000104731352751253100234370ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: CSDIDA tag class definition. // // Dataset Indentification TRE. // // See document STDI-0006-NCDRD Table 3.3-14 for more info. // //---------------------------------------------------------------------------- // $Id #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfCsdidaTag, "ossimNitfCsdidaTag", ossimNitfRegisteredTag); ossimNitfCsdidaTag::ossimNitfCsdidaTag() : ossimNitfRegisteredTag(std::string("CSDIDA"), 70) { clearFields(); } ossimNitfCsdidaTag::~ossimNitfCsdidaTag() { } void ossimNitfCsdidaTag::parseStream(std::istream& in) { clearFields(); in.read(theDay, 2); in.read(theMonth, 3); in.read(theYear, 4); in.read(thePlatformCode, 2); in.read(theVehicleId, 2); in.read(thePass, 2); in.read(theOperation, 3); in.read(theSensorId, 2); in.read(theProductId, 2); in.read(theReservedField1, 4); in.read(theTime, 14); in.read(theProcessTime, 14); in.read(theReservedField2, 2); in.read(theReservedField3, 2); in.read(theReservedField4, 1); in.read(theReservedField5, 1); in.read(theSoftwareVersionNumber, 10); } void ossimNitfCsdidaTag::writeStream(std::ostream& out) { out.write(theDay, 2); out.write(theMonth, 3); out.write(theYear, 4); out.write(thePlatformCode, 2); out.write(theVehicleId, 2); out.write(thePass, 2); out.write(theOperation, 3); out.write(theSensorId, 2); out.write(theProductId, 2); out.write(theReservedField1, 4); out.write(theTime, 14); out.write(theProcessTime, 14); out.write(theReservedField2, 2); out.write(theReservedField3, 2); out.write(theReservedField4, 1); out.write(theReservedField5, 1); out.write(theSoftwareVersionNumber, 10); } void ossimNitfCsdidaTag::clearFields() { // BCS-N's to '0's, BCS-A's to ' '(spaces) memset(theDay, '0', 2); memset(theMonth, ' ', 3); memset(theYear, '0', 4); memset(thePlatformCode, ' ', 2); memset(theVehicleId, '0', 2); memset(thePass, '0', 2); memset(theOperation, '0', 3); memset(theSensorId, ' ', 2); memset(theProductId, ' ', 2); memcpy(theReservedField1, "00 ", 4); memset(theTime, '0', 14); memset(theProcessTime, '0', 14); memcpy(theReservedField2, "00", 2); memcpy(theReservedField3, "01", 2); memcpy(theReservedField4, "N", 1); memcpy(theReservedField5, "N", 1); memset(theSoftwareVersionNumber, ' ', 10); theDay[2] = '\0'; theMonth[3] = '\0'; theYear[4] = '\0'; thePlatformCode[2] = '\0'; theVehicleId[2] = '\0'; thePass[2] = '\0'; theOperation[3] = '\0'; theSensorId[2] = '\0'; theProductId[2] = '\0'; theReservedField1[4] = '\0'; theTime[14] = '\0'; theProcessTime[14] = '\0'; theReservedField2[2] = '\0'; theReservedField3[2] = '\0'; theReservedField4[0] = '\0'; theReservedField5[0] = '\0'; theSoftwareVersionNumber[10] = '\0'; } std::ostream& ossimNitfCsdidaTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "DAY:" << theDay << "\n" << pfx << std::setw(24) << "MONTH:" << theMonth << "\n" << pfx << std::setw(24) << "YEAR:" << theYear << "\n" << pfx << std::setw(24) << "PLATFORM_CODE:" << thePlatformCode << "\n" << pfx << std::setw(24) << "VEHICLE_ID:" << theVehicleId << "\n" << pfx << std::setw(24) << "PASS:" << thePass << "\n" << pfx << std::setw(24) << "OPERATION:" << theOperation << "\n" << pfx << std::setw(24) << "SENSOR_ID:" << theSensorId << "\n" << pfx << std::setw(24) << "PRODUCT_ID:" << theProductId << "\n" << pfx << std::setw(24) << "TIME:" << theTime << "\n" << pfx << std::setw(24) << "PROCESS_TIME:" << theProcessTime << "\n" << pfx << std::setw(24) << "SOFTWARE_VERSION_NUMBER:" << theSoftwareVersionNumber << "\n"; return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfCsexraTag.cpp000066400000000000000000000216361352751253100235000ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: CSEXRA tag class definition. // // Exploitation Reference Data TRE. // // See document STDI-0006-NCDRD Table 3.5-16 for more info. // //---------------------------------------------------------------------------- // $Id #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfCsexraTag, "ossimNitfCsexraTag", ossimNitfRegisteredTag); ossimNitfCsexraTag::ossimNitfCsexraTag() : ossimNitfRegisteredTag(std::string("CSEXRA"), 132) { clearFields(); } ossimNitfCsexraTag::~ossimNitfCsexraTag() { } void ossimNitfCsexraTag::parseStream(std::istream& in) { clearFields(); in.read(theSensor, 6); in.read(theTileFirstLine, 12); in.read(theImageTimeDuration, 12); in.read(theMaxGsd, 5); in.read(theAlongScanGsd, 5); in.read(theCrossScanGsd, 5); in.read(theGeoMeanGsd, 5); in.read(theAlongScanVertGsd, 5); in.read(theCrossScanVertGsd, 5); in.read(theGeoMeanVertGsd, 5); in.read(theGeoBetaAngle, 5); in.read(theDynamicRange, 5); in.read(theLine, 7); in.read(theSamples, 5); in.read(theAngleToNorth, 7); in.read(theObliquityAngle, 6); in.read(theAzOfObliquity, 7); in.read(theGrdCover, 1); in.read(theSnowDepthCategory, 1); in.read(theSunAzimuth, 7); in.read(theSunElevation, 7); in.read(thePredictedNiirs, 3); in.read(theCircularError, 3); in.read(theLinearError, 3); } void ossimNitfCsexraTag::writeStream(std::ostream& out) { out.write(theSensor, 6); out.write(theTileFirstLine, 12); out.write(theImageTimeDuration, 12); out.write(theMaxGsd, 5); out.write(theAlongScanGsd, 5); out.write(theCrossScanGsd, 5); out.write(theGeoMeanGsd, 5); out.write(theAlongScanVertGsd, 5); out.write(theCrossScanVertGsd, 5); out.write(theGeoMeanVertGsd, 5); out.write(theGeoBetaAngle, 5); out.write(theDynamicRange, 5); out.write(theLine, 7); out.write(theSamples, 5); out.write(theAngleToNorth, 7); out.write(theObliquityAngle, 6); out.write(theAzOfObliquity, 7); out.write(theGrdCover, 1); out.write(theSnowDepthCategory, 1); out.write(theSunAzimuth, 7); out.write(theSunElevation, 7); out.write(thePredictedNiirs, 3); out.write(theCircularError, 3); out.write(theLinearError, 3); } void ossimNitfCsexraTag::clearFields() { //--- // No attempt made to set to defaults. // BCS-N's to '0's, BCS-A's to ' '(spaces) //--- memset(theSensor, ' ', 6); memset(theTileFirstLine, 0, 12); memset(theImageTimeDuration, 0, 12); memset(theMaxGsd, 0, 5); memset(theAlongScanGsd, ' ', 5); memset(theCrossScanGsd, ' ', 5); memset(theGeoMeanGsd, ' ', 5); memset(theAlongScanVertGsd, ' ', 5); memset(theCrossScanVertGsd, ' ', 5); memset(theGeoMeanVertGsd, ' ', 5); memset(theGeoBetaAngle, ' ', 5); memset(theDynamicRange, 0, 5); memset(theLine, 0, 7); memset(theSamples, 0, 5); memset(theAngleToNorth, 0, 7); memset(theObliquityAngle, 0, 6); memset(theAzOfObliquity, 0, 7); memset(theGrdCover, 0, 1); memset(theSnowDepthCategory, 0, 1); memset(theSunAzimuth, 0, 7); memset(theSunElevation, 0, 7); memset(thePredictedNiirs, ' ', 3); memset(theCircularError, 0, 3); memset(theLinearError, 0, 3); theSensor[6] = '\0'; theTileFirstLine[12] = '\0'; theImageTimeDuration[12] = '\0'; theMaxGsd[5] = '\0'; theAlongScanGsd[5] = '\0'; theCrossScanGsd[5] = '\0'; theGeoMeanGsd[5] = '\0'; theAlongScanVertGsd[5] = '\0'; theCrossScanVertGsd[5] = '\0'; theGeoMeanVertGsd[5] = '\0'; theGeoBetaAngle[5] = '\0'; theDynamicRange[5] = '\0'; theLine[7] = '\0'; theSamples[5] = '\0'; theAngleToNorth[7] = '\0'; theObliquityAngle[6] = '\0'; theAzOfObliquity[7] = '\0'; theGrdCover[1] = '\0'; theSnowDepthCategory[1] = '\0'; theSunAzimuth[7] = '\0'; theSunElevation[7] = '\0'; thePredictedNiirs[3] = '\0'; theCircularError[3] = '\0'; theLinearError[3] = '\0'; } std::ostream& ossimNitfCsexraTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "SENSOR:" << theSensor << "\n" << pfx << std::setw(24) << "TIME_FIRST_LINE_IMAGE:" << theTileFirstLine << "\n" << pfx << std::setw(24) << "TIME_IMAGE_DURATION:" << theImageTimeDuration << "\n" << pfx << std::setw(24) << "MAX_GSD:" << theMaxGsd << "\n" << pfx << std::setw(24) << "ALONG_SCAN_GSD:" << theAlongScanGsd << "\n" << pfx << std::setw(24) << "CROSS_SCAN_GSD:" << theCrossScanGsd << "\n" << pfx << std::setw(24) << "GEO_MEAN_GSD:" << theGeoMeanGsd << "\n" << pfx << std::setw(24) << "A_S_VERT_GSD:" << theAlongScanVertGsd << "\n" << pfx << std::setw(24) << "C_S_VERT_GSD:" << theCrossScanVertGsd << "\n" << pfx << std::setw(24) << "GEO_MEAN_VERT_GSD:" << theGeoMeanVertGsd << "\n" << pfx << std::setw(24) << "GEO_BETA_ANGLE:" << theGeoBetaAngle << "\n" << pfx << std::setw(24) << "DYNAMIC_RANGE:" << theDynamicRange << "\n" << pfx << std::setw(24) << "NUM_LINES:" << theLine << "\n" << pfx << std::setw(24) << "NUM_SAMPLES:" << theSamples << "\n" << pfx << std::setw(24) << "ANGLE_TO_NORTH:" << theAngleToNorth << "\n" << pfx << std::setw(24) << "OBLIQUITY_ANGLE:" << theObliquityAngle << "\n" << pfx << std::setw(24) << "AZ_OF_OBLIQUITY:" << theAzOfObliquity << "\n" << pfx << std::setw(24) << "GRD_COVER:" << theGrdCover << "\n" << pfx << std::setw(24) << "SNOW_DEPTH_CAT:" << theSnowDepthCategory << "\n" << pfx << std::setw(24) << "SUN_AZIMUTH:" << theSunAzimuth << "\n" << pfx << std::setw(24) << "SUN_ELEVATION:" << theSunElevation << "\n" << pfx << std::setw(24) << "PREDICTED_NIIRS:" << thePredictedNiirs << "\n" << pfx << std::setw(24) << "CIRCL_ERR:" << theCircularError << "\n" << pfx << std::setw(24) << "LINEAR_ERR:" << theLinearError<< "\n"; return out; } ossimString ossimNitfCsexraTag::getSensor() const { return ossimString(theSensor); } ossimString ossimNitfCsexraTag::getTimeFirstLineImage() const { return ossimString(theTileFirstLine); } ossimString ossimNitfCsexraTag::getTimeImageDuration() const { return ossimString(theImageTimeDuration); } ossimString ossimNitfCsexraTag::getMaxGsd() const { return ossimString(theMaxGsd); } ossimString ossimNitfCsexraTag::getAlongScanGsd() const { return ossimString(theAlongScanGsd); } ossimString ossimNitfCsexraTag::getCrossScanGsd() const { return ossimString(theCrossScanGsd); } ossimString ossimNitfCsexraTag::getGeoMeanGsd() const { return ossimString(theGeoMeanGsd); } ossimString ossimNitfCsexraTag::getAlongScanVerticalGsd() const { return ossimString(theAlongScanVertGsd); } ossimString ossimNitfCsexraTag::getCrossScanVerticalGsd() const { return ossimString(theCrossScanVertGsd); } ossimString ossimNitfCsexraTag::getGeoMeanVerticalGsd() const { return ossimString(theGeoMeanVertGsd); } ossimString ossimNitfCsexraTag::getGeoBetaAngle() const { return ossimString(theGeoBetaAngle); } ossimString ossimNitfCsexraTag::getDynamicRange() const { return ossimString(theDynamicRange); } ossimString ossimNitfCsexraTag::getNumLines() const { return ossimString(theLine); } ossimString ossimNitfCsexraTag::getNumSamples() const { return ossimString(theSamples); } ossimString ossimNitfCsexraTag::getAngleToNorth() const { return ossimString(theAngleToNorth); } ossimString ossimNitfCsexraTag::getObliquityAngle() const { return ossimString(theObliquityAngle); } ossimString ossimNitfCsexraTag::getAzimuthOfObliquity() const { return ossimString(theAzOfObliquity); } ossimString ossimNitfCsexraTag::getGroundCover() const { return ossimString(theGrdCover); } ossimString ossimNitfCsexraTag::getSnowDepth() const { return ossimString(theSnowDepthCategory); } ossimString ossimNitfCsexraTag::getSunAzimuth() const { return ossimString(theSunAzimuth); } ossimString ossimNitfCsexraTag::getSunElevation() const { return ossimString(theSunElevation); } ossimString ossimNitfCsexraTag::getPredictedNiirs() const { return ossimString(thePredictedNiirs); } ossimString ossimNitfCsexraTag::getCE90() const { return ossimString(theCircularError); } ossimString ossimNitfCsexraTag::getLE90() const { return ossimString(theLinearError); } ossim-Miami-2.9.1/src/support_data/ossimNitfCsproaTag.cpp000066400000000000000000000064571352751253100235060ustar00rootroot00000000000000#include #include #include using namespace std; ossimNitfCsproaTag::ossimNitfCsproaTag() : ossimNitfRegisteredTag(std::string("CSPROA"), 120) { clearFields(); } void ossimNitfCsproaTag::parseStream(std::istream& in) { in.read(m_reserved1, RESERVE1_SIZE); in.read(m_reserved2, RESERVE2_SIZE); in.read(m_reserved3, RESERVE3_SIZE); in.read(m_reserved4, RESERVE4_SIZE); in.read(m_reserved5, RESERVE5_SIZE); in.read(m_reserved6, RESERVE6_SIZE); in.read(m_reserved7, RESERVE7_SIZE); in.read(m_reserved8, RESERVE8_SIZE); in.read(m_reserved9, RESERVE9_SIZE); in.read(m_bwc, BWC_SIZE); } void ossimNitfCsproaTag::writeStream(std::ostream& out) { out.write(m_reserved1, RESERVE1_SIZE); out.write(m_reserved2, RESERVE2_SIZE); out.write(m_reserved3, RESERVE3_SIZE); out.write(m_reserved4, RESERVE4_SIZE); out.write(m_reserved5, RESERVE5_SIZE); out.write(m_reserved6, RESERVE6_SIZE); out.write(m_reserved7, RESERVE7_SIZE); out.write(m_reserved8, RESERVE8_SIZE); out.write(m_reserved9, RESERVE9_SIZE); out.write(m_bwc, BWC_SIZE); } std::ostream& ossimNitfCsproaTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "RESERVED1:" << m_reserved1 << "\n" << pfx << std::setw(24) << "RESERVED2:" << m_reserved2 << "\n" << pfx << std::setw(24) << "RESERVED3:" << m_reserved3 << "\n" << pfx << std::setw(24) << "RESERVED4:" << m_reserved4 << "\n" << pfx << std::setw(24) << "RESERVED5:" << m_reserved5 << "\n" << pfx << std::setw(24) << "RESERVED6:" << m_reserved6 << "\n" << pfx << std::setw(24) << "RESERVED7:" << m_reserved7 << "\n" << pfx << std::setw(24) << "RESERVED8:" << m_reserved8 << "\n" << pfx << std::setw(24) << "RESERVED9:" << m_reserved9 << "\n" << pfx << std::setw(24) << "BWC:" << m_bwc << "\n"; return out; } void ossimNitfCsproaTag::clearFields() { memset(m_reserved1, ' ', RESERVE1_SIZE); memset(m_reserved2, ' ', RESERVE2_SIZE); memset(m_reserved3, ' ', RESERVE3_SIZE); memset(m_reserved4, ' ', RESERVE4_SIZE); memset(m_reserved5, ' ', RESERVE5_SIZE); memset(m_reserved6, ' ', RESERVE6_SIZE); memset(m_reserved7, ' ', RESERVE7_SIZE); memset(m_reserved8, ' ', RESERVE8_SIZE); memset(m_reserved9, ' ', RESERVE9_SIZE); memset(m_bwc, ' ', BWC_SIZE); char reserve1[]="LATESTCAL"; memcpy(m_reserved1, reserve1, 9); char reserve4[] = "MARKANDFIX"; memcpy(m_reserved4, reserve4, 10); char reserve7[] = "SKIPAGM"; memcpy(m_reserved7, reserve7, 7); char reserve8[] = "INTERP"; memcpy(m_reserved8, reserve8, 6); m_reserved1[RESERVE1_SIZE] = '\0'; m_reserved2[RESERVE2_SIZE] = '\0'; m_reserved3[RESERVE3_SIZE] = '\0'; m_reserved4[RESERVE4_SIZE] = '\0'; m_reserved5[RESERVE5_SIZE] = '\0'; m_reserved6[RESERVE6_SIZE] = '\0'; m_reserved7[RESERVE7_SIZE] = '\0'; m_reserved8[RESERVE8_SIZE] = '\0'; m_reserved9[RESERVE9_SIZE] = '\0'; m_bwc[BWC_SIZE] = '\0'; } ossim-Miami-2.9.1/src/support_data/ossimNitfDataExtensionSegment.cpp000066400000000000000000000043661352751253100257110ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDataExtensionSegment.cpp 22418 2013-09-26 15:01:12Z gpotts $ #include #include RTTI_DEF2(ossimNitfDataExtensionSegment, "ossimNitfDataExtensionSegment", ossimObject, ossimPropertyInterface) const ossimString ossimNitfDataExtensionSegment::DE_KW = "de"; const ossimString ossimNitfDataExtensionSegment::DESVER_KW = "desver"; const ossimString ossimNitfDataExtensionSegment::DESOFLW_KW = "desoflw"; const ossimString ossimNitfDataExtensionSegment::DESITEM_KW = "desitem"; const ossimString ossimNitfDataExtensionSegment::DESSHL_KW = "desshl"; const ossimString ossimNitfDataExtensionSegment::DESSHF_KW = "desshf"; const ossimString ossimNitfDataExtensionSegment::DESDATA_KW = "desdata"; const ossimString ossimNitfDataExtensionSegment::DECLAS_KW = "declas"; const ossimString ossimNitfDataExtensionSegment::DESCODE_KW = "descode"; const ossimString ossimNitfDataExtensionSegment::DESCTLH_KW = "desctlh"; const ossimString ossimNitfDataExtensionSegment::DESREL_KW = "desrel"; const ossimString ossimNitfDataExtensionSegment::DESCAUT_KW = "descaut"; const ossimString ossimNitfDataExtensionSegment::DESCTLN_KW = "desctln"; std::ostream& operator <<(std::ostream &out, const ossimNitfDataExtensionSegment &data) { data.print(out); return out; } void ossimNitfDataExtensionSegment::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back(DE_KW); propertyNames.push_back(DESVER_KW); propertyNames.push_back(DESOFLW_KW); propertyNames.push_back(DESITEM_KW); propertyNames.push_back(DESSHL_KW); propertyNames.push_back(DESSHF_KW); propertyNames.push_back(DESDATA_KW); propertyNames.push_back(DECLAS_KW); propertyNames.push_back(DESCODE_KW); propertyNames.push_back(DESCTLH_KW); propertyNames.push_back(DESREL_KW); propertyNames.push_back(DESCAUT_KW); propertyNames.push_back(DESCTLN_KW); } ossim-Miami-2.9.1/src/support_data/ossimNitfDataExtensionSegmentV2_0.cpp000066400000000000000000000245641352751253100263420ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDataExtensionSegmentV2_0.cpp 22429 2013-10-02 12:53:06Z gpotts $ #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfDataExtensionSegmentV2_0, "ossimNitfDataExtensionSegmentV2_0",ossimNitfDataExtensionSegment) const ossimString ossimNitfDataExtensionSegmentV2_0::DESTAG_KW = "destag"; const ossimString ossimNitfDataExtensionSegmentV2_0::DESDWNG_KW = "desdwng"; const ossimString ossimNitfDataExtensionSegmentV2_0::DESDEVT_KW = "desdevt"; std::ostream& operator <<(std::ostream& out, const ossimNitfDataExtIdentSecurityChunkV2_0& data) { out << "theFilePartType: " << data.theFilePartType << "\ntheUniqueDataExtTypeId: " << data.theUniqueDataExtTypeId << "\ntheVersionDataFieldDef: " << data.theVersionDataFieldDef << "\ntheDataExtSecurityClass: " << data.theDataExtSecurityClass << "\ntheDataExtCodewords: " << data.theDataExtCodewords << "\ntheDataExtControlAndHand: " << data.theDataExtControlAndHand << "\ntheDataExtReleasingInst: " << data.theDataExtReleasingInst << "\ntheDataExtClassAuthority: " << data.theDataExtClassAuthority << "\ntheDataExtSecurityConNum: " << data.theDataExtSecurityConNum << "\ntheDataExtSecurityDowngrade: " << data.theDataExtSecurityDowngrade << "\ntheDataExtDowngradingEvent: " << data.theDataExtDowngradingEvent << std::endl; return out; } ossimNitfDataExtensionSegmentV2_0::ossimNitfDataExtensionSegmentV2_0() { clearFields(); } ossimNitfDataExtensionSegmentV2_0::~ossimNitfDataExtensionSegmentV2_0() { } void ossimNitfDataExtensionSegmentV2_0::parseStream(std::istream &in, ossim_uint64 dataLength) { if(in) { clearFields(); in.read(theIdentSecurityChunk.theFilePartType, 2); // 2 byte alpha in.read(theIdentSecurityChunk.theUniqueDataExtTypeId, 25); // 25 byte alpha numeric in.read(theIdentSecurityChunk.theVersionDataFieldDef, 2); // 2 byte numeric in.read(theIdentSecurityChunk.theDataExtSecurityClass, 1); // 1 byte alpha in.read(theIdentSecurityChunk.theDataExtCodewords, 40); // 40 byte alpha numeric in.read(theIdentSecurityChunk.theDataExtControlAndHand, 40); // 40 byte alpha numeric in.read(theIdentSecurityChunk.theDataExtReleasingInst, 40); // 40 byte alpha numeric in.read(theIdentSecurityChunk.theDataExtClassAuthority, 20); // 20 byte alph num in.read(theIdentSecurityChunk.theDataExtSecurityConNum, 20); // 20 byte alpha num in.read(theIdentSecurityChunk.theDataExtSecurityDowngrade, 6); // 6 byte alpha num if(ossimString(theIdentSecurityChunk.theDataExtSecurityDowngrade) == "999998") { in.read(theIdentSecurityChunk.theDataExtDowngradingEvent, 40); // 40 byte alpha num } ossimString desTag = ossimString(theIdentSecurityChunk.theUniqueDataExtTypeId, theIdentSecurityChunk.theUniqueDataExtTypeId+25); desTag = desTag.trim().upcase(); const bool overflow = (desTag == "REGISTERED EXTENSIONS" || desTag == "CONTROLLED EXTENSIONS"); if (overflow&&in.good()) { in.read(theOverflowedHeaderType, 6); in.read(theDataItemOverflowed, 3); } in.read(theLengthOfUserDefinedSubheaderFields, 4); // look to see if there is any data and if so read the tag // to see what it is long length = ossimString(theLengthOfUserDefinedSubheaderFields).toLong(); if (length > 0) { theUserDefinedSubheaderFields.resize(length); in.read(reinterpret_cast(&theUserDefinedSubheaderFields.front()), theUserDefinedSubheaderFields.size()); } if (dataLength != 0) { if (overflow) { istream::pos_type dataBegin = in.tellg(); istream::pos_type endData = dataBegin + static_cast(dataLength); while (in.good()&&(in.tellg() < endData)) { ossimNitfTagInformation tag; tag.parseStream(in); theTagList.push_back(tag); } if(!in.good()) in.clear(); in.seekg(dataBegin); } theData.resize(dataLength); in.read(reinterpret_cast(&theData.front()), theData.size()); } } } void ossimNitfDataExtensionSegmentV2_0::clearFields() { memset(theIdentSecurityChunk.theFilePartType, ' ', 2); // 2 byte alpha memset(theIdentSecurityChunk.theUniqueDataExtTypeId, ' ', 25); // 25 byte alpha numeric memset(theIdentSecurityChunk.theVersionDataFieldDef, ' ', 2); // 2 byte numeric memset(theIdentSecurityChunk.theDataExtSecurityClass, ' ', 1); // 1 byte alpha memset(theIdentSecurityChunk.theDataExtCodewords, ' ', 40); // 40 byte alpha numeric memset(theIdentSecurityChunk.theDataExtControlAndHand, ' ', 40); // 40 byte alpha numeric memset(theIdentSecurityChunk.theDataExtReleasingInst, ' ', 40); // 40 byte alpha numeric memset(theIdentSecurityChunk.theDataExtClassAuthority, ' ', 20); // 20 byte alph num memset(theIdentSecurityChunk.theDataExtSecurityConNum, ' ', 20); // 20 byte alpha num memset(theIdentSecurityChunk.theDataExtSecurityDowngrade, ' ', 6); // 6 byte alpha num memset(theIdentSecurityChunk.theDataExtDowngradingEvent, ' ', 40); // 40 byte alpha num memset(theOverflowedHeaderType, ' ', 6); memset(theDataItemOverflowed, ' ', 3); memset(theLengthOfUserDefinedSubheaderFields, ' ', 4); theIdentSecurityChunk.theFilePartType[2] = '\0'; // 2 byte alpha theIdentSecurityChunk.theUniqueDataExtTypeId[25] = '\0'; // 25 byte alpha numeric theIdentSecurityChunk.theVersionDataFieldDef[2] = '\0'; // 2 byte numeric theIdentSecurityChunk.theDataExtSecurityClass[1] = '\0'; // 1 byte alpha theIdentSecurityChunk.theDataExtCodewords[40] = '\0'; // 40 byte alpha numeric theIdentSecurityChunk.theDataExtControlAndHand[40] = '\0'; // 40 byte alpha numeric theIdentSecurityChunk.theDataExtReleasingInst[40] = '\0'; // 40 byte alpha numeric theIdentSecurityChunk.theDataExtClassAuthority[20] = '\0'; // 20 byte alph num theIdentSecurityChunk.theDataExtSecurityConNum[20] = '\0'; // 20 byte alpha num theIdentSecurityChunk.theDataExtSecurityDowngrade[6] = '\0'; // 6 byte alpha num theIdentSecurityChunk.theDataExtDowngradingEvent[40] = '\0'; // 40 byte alpha num theOverflowedHeaderType[6] = '\0'; theDataItemOverflowed[3] = '\0'; theLengthOfUserDefinedSubheaderFields[4] = '\0'; theUserDefinedSubheaderFields.clear(); theData.clear(); theTagList.clear(); } std::ostream& ossimNitfDataExtensionSegmentV2_0::print(std::ostream& out)const { out << "theIdentSecurityChunk: " << theIdentSecurityChunk << "\ntheOverflowedHeaderType: " << theOverflowedHeaderType << "\ntheDataItemOverflowed: " << theDataItemOverflowed << "\ntheLengthOfUserDefinedSubheaderFields: " << theLengthOfUserDefinedSubheaderFields << "\ntag count: " << theTagList.size() << std::endl; return out; } ossimRefPtr ossimNitfDataExtensionSegmentV2_0::getProperty(const ossimString& name)const { ossimProperty* property = 0; if (name == DE_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theFilePartType).trim()); } else if (name == DESTAG_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theUniqueDataExtTypeId).trim()); } else if (name == DESVER_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theVersionDataFieldDef).trim()); } else if (name == DECLAS_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtSecurityClass).trim()); } else if (name == DESCODE_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtCodewords).trim()); } else if (name == DESCTLH_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtControlAndHand).trim()); } else if (name == DESREL_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtReleasingInst).trim()); } else if (name == DESCAUT_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtClassAuthority).trim()); } else if (name == DESCTLN_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtSecurityConNum).trim()); } else if (name == DESDWNG_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtSecurityDowngrade).trim()); } else if (name == DESDEVT_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtDowngradingEvent).trim()); } else if (name == DESOFLW_KW) { property = new ossimStringProperty(name, ossimString(theOverflowedHeaderType).trim()); } else if (name == DESITEM_KW) { property = new ossimStringProperty(name, ossimString(theDataItemOverflowed).trim()); } else if (name == DESSHL_KW) { property = new ossimStringProperty(name, ossimString(theLengthOfUserDefinedSubheaderFields).trim()); } else if (name == DESSHF_KW) { property = new ossimBinaryDataProperty(name, theUserDefinedSubheaderFields); } else if (name == DESDATA_KW) { // Only valid if setTagList has not been called on this object. property = new ossimBinaryDataProperty(name, theData); } return property; } void ossimNitfDataExtensionSegmentV2_0::getPropertyNames(std::vector& propertyNames)const { ossimNitfDataExtensionSegment::getPropertyNames(propertyNames); propertyNames.push_back(DESTAG_KW); propertyNames.push_back(DESDWNG_KW); propertyNames.push_back(DESDEVT_KW); } ossim-Miami-2.9.1/src/support_data/ossimNitfDataExtensionSegmentV2_1.cpp000066400000000000000000000560611352751253100263400ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDataExtensionSegmentV2_1.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfDataExtensionSegmentV2_1, "ossimNitfDataExtensionSegmentV2_1",ossimNitfDataExtensionSegment) const ossimString ossimNitfDataExtensionSegmentV2_1::DESID_KW = "desid"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESCLSY_KW = "desclsy"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESDCTP_KW = "desdctp"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESDCDT_KW = "desdcdt"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESDCXM_KW = "desdcxm"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESDG_KW = "desdg"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESDGDT_KW = "desdgdt"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESCLTX_KW = "descltx"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESCATP_KW = "descatp"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESCRSN_KW = "descrsn"; const ossimString ossimNitfDataExtensionSegmentV2_1::DESSRDT_KW = "dessrdt"; std::ostream& operator <<(std::ostream& out, const ossimNitfDataExtIdentSecurityChunkV2_1& data) { out << "theFilePartType: " << data.theFilePartType << "\ntheUniqueDataExtTypeId: " << data.theUniqueDataExtTypeId << "\ntheVersionDataFieldDef: " << data.theVersionDataFieldDef << "\ntheDataExtSecurityClass: " << data.theDataExtSecurityClass << "\ntheDataExtClassSystem: " << data.theDataExtClassSystem << "\ntheDataExtCodewords: " << data.theDataExtCodewords << "\ntheDataExtControlAndHand: " << data.theDataExtControlAndHand << "\ntheDataExtReleasingInst: " << data.theDataExtReleasingInst << "\ntheDataExtDeclassType: " << data.theDataExtDeclassType << "\ntheDataExtDeclassDate: " << data.theDataExtDeclassDate << "\ntheDataExtDeclassExempt: " << data.theDataExtDeclassExempt << "\ntheDataExtSecurityDowngrade: " << data.theDataExtSecurityDowngrade << "\ntheDataExtSecurityDowngradeDate:" << data.theDataExtSecurityDowngradeDate << "\ntheDataExtSecurityClassText: " << data.theDataExtSecurityClassText << "\ntheDataExtClassAuthType: " << data.theDataExtClassAuthType << "\ntheDataExtClassAuthority: " << data.theDataExtClassAuthority << "\ntheDataExtClassReason: " << data.theDataExtClassReason << "\ntheDataExtSecuritySourceDate: " << data.theDataExtSecuritySourceDate << "\ntheDataExtSecurityConNum: " << data.theDataExtSecurityConNum << std::endl; return out; } ossimNitfDataExtensionSegmentV2_1::ossimNitfDataExtensionSegmentV2_1() : theUserDefinedSubheaderFields(0), theData(0) { clearFields(); } ossimNitfDataExtensionSegmentV2_1::~ossimNitfDataExtensionSegmentV2_1() { } void ossimNitfDataExtensionSegmentV2_1::parseStream(std::istream &in, ossim_uint64 dataLength) { if(in) { clearFields(); in.read(theIdentSecurityChunk.theFilePartType, 2); // 2 byte alpha in.read(theIdentSecurityChunk.theUniqueDataExtTypeId, 25); // 25 byte alpha numeric in.read(theIdentSecurityChunk.theVersionDataFieldDef, 2); // 2 byte numeric in.read(theIdentSecurityChunk.theDataExtSecurityClass, 1); // 1 byte alpha in.read(theIdentSecurityChunk.theDataExtClassSystem, 2); in.read(theIdentSecurityChunk.theDataExtCodewords, 11); // 11 byte alpha numeric in.read(theIdentSecurityChunk.theDataExtControlAndHand, 2); // 2 byte alpha numeric in.read(theIdentSecurityChunk.theDataExtReleasingInst, 20); // 20 byte alpha numeric in.read(theIdentSecurityChunk.theDataExtDeclassType, 2); // 2 byte alph num in.read(theIdentSecurityChunk.theDataExtDeclassDate, 8); // 8 byte alph num in.read(theIdentSecurityChunk.theDataExtDeclassExempt, 4); // 4 byte alpha num in.read(theIdentSecurityChunk.theDataExtSecurityDowngrade, 1); // 1 byte alpha num in.read(theIdentSecurityChunk.theDataExtSecurityDowngradeDate, 8); // 8 byte alpha num in.read(theIdentSecurityChunk.theDataExtSecurityClassText, 43); // 43 byte alpha num in.read(theIdentSecurityChunk.theDataExtClassAuthType, 1); // 1 byte alpha num in.read(theIdentSecurityChunk.theDataExtClassAuthority, 40); // 40 byte alpha num in.read(theIdentSecurityChunk.theDataExtClassReason, 1); // 1 byte alpha num in.read(theIdentSecurityChunk.theDataExtSecuritySourceDate, 8); // 8 byte alpha num in.read(theIdentSecurityChunk.theDataExtSecurityConNum, 15); // 15 byte alpha num bool overflow = ossimString(theIdentSecurityChunk.theUniqueDataExtTypeId).trim().upcase() == "TRE_OVERFLOW"; if (overflow) { in.read(theOverflowedHeaderType, 6); in.read(theDataItemOverflowed, 3); } in.read(theLengthOfUserDefinedSubheaderFields, 4); // look to see if there is any data and if so read the tag // to see what it is long length = ossimString(theLengthOfUserDefinedSubheaderFields).toLong(); if (length > 0) { theUserDefinedSubheaderFields.resize(length); in.read(reinterpret_cast(&theUserDefinedSubheaderFields.front()), theUserDefinedSubheaderFields.size()); } if (dataLength != 0) { if (overflow) { std::streamoff dataBegin = in.tellg(); std::streamoff dataEnd = dataBegin + static_cast(dataLength); // dataBegin + static_cast(dataLength)) while (in.good() && (in.tellg() < dataEnd) ) { ossimNitfTagInformation tag; tag.clearFields(); tag.parseStream(in); theTagList.push_back(tag); } ossimIFStream64::seekg64(in, dataBegin, ios::beg); in.clear(); } theData.resize(dataLength); in.read(reinterpret_cast(&theData.front()), theData.size()); } } } void ossimNitfDataExtensionSegmentV2_1::writeStream(std::ostream &out) { if (out) { out.write(theIdentSecurityChunk.theFilePartType, 2); out.write(theIdentSecurityChunk.theUniqueDataExtTypeId, 25); out.write(theIdentSecurityChunk.theVersionDataFieldDef, 2); out.write(theIdentSecurityChunk.theDataExtSecurityClass, 1); out.write(theIdentSecurityChunk.theDataExtClassSystem, 2); out.write(theIdentSecurityChunk.theDataExtCodewords, 11); out.write(theIdentSecurityChunk.theDataExtControlAndHand, 2); out.write(theIdentSecurityChunk.theDataExtReleasingInst, 20); out.write(theIdentSecurityChunk.theDataExtDeclassType, 2); out.write(theIdentSecurityChunk.theDataExtDeclassDate, 8); out.write(theIdentSecurityChunk.theDataExtDeclassExempt, 4); out.write(theIdentSecurityChunk.theDataExtSecurityDowngrade, 1); out.write(theIdentSecurityChunk.theDataExtSecurityDowngradeDate, 8); out.write(theIdentSecurityChunk.theDataExtSecurityClassText, 43); out.write(theIdentSecurityChunk.theDataExtClassAuthType, 1); out.write(theIdentSecurityChunk.theDataExtClassAuthority, 40); out.write(theIdentSecurityChunk.theDataExtClassReason, 1); out.write(theIdentSecurityChunk.theDataExtSecuritySourceDate, 8); out.write(theIdentSecurityChunk.theDataExtSecurityConNum, 15); bool overflow = ossimString(theIdentSecurityChunk.theUniqueDataExtTypeId).trim().upcase() == "TRE_OVERFLOW"; if (overflow) { out.write(theOverflowedHeaderType, 6); out.write(theDataItemOverflowed, 3); } out.write(theLengthOfUserDefinedSubheaderFields, 4); for (unsigned int i = 0; i < theUserDefinedSubheaderFields.size(); i++) { out.write(reinterpret_cast(&theUserDefinedSubheaderFields.front()), theUserDefinedSubheaderFields.size()); } if (overflow && theTagList.empty() == false) { for (std::vector::iterator iter = theTagList.begin(); iter != theTagList.end(); ++iter) { iter->writeStream(out); } } else { out.write(reinterpret_cast(&theData.front()), theData.size()); } } } void ossimNitfDataExtensionSegmentV2_1::clearFields() { memset(theIdentSecurityChunk.theFilePartType, ' ', 2); memset(theIdentSecurityChunk.theUniqueDataExtTypeId, ' ', 25); memset(theIdentSecurityChunk.theVersionDataFieldDef, 0, 2); memset(theIdentSecurityChunk.theDataExtSecurityClass, ' ', 1); memset(theIdentSecurityChunk.theDataExtClassSystem, ' ', 2); memset(theIdentSecurityChunk.theDataExtCodewords, ' ', 11); memset(theIdentSecurityChunk.theDataExtControlAndHand, ' ', 2); memset(theIdentSecurityChunk.theDataExtReleasingInst, ' ', 20); memset(theIdentSecurityChunk.theDataExtDeclassType, ' ', 2); memset(theIdentSecurityChunk.theDataExtDeclassDate, ' ', 8); memset(theIdentSecurityChunk.theDataExtDeclassExempt, ' ', 4); memset(theIdentSecurityChunk.theDataExtSecurityDowngrade, ' ', 1); memset(theIdentSecurityChunk.theDataExtSecurityDowngradeDate, ' ', 8); memset(theIdentSecurityChunk.theDataExtSecurityClassText, ' ', 43); memset(theIdentSecurityChunk.theDataExtClassAuthType, ' ', 1); memset(theIdentSecurityChunk.theDataExtClassAuthority, ' ', 40); memset(theIdentSecurityChunk.theDataExtClassReason, ' ', 1); memset(theIdentSecurityChunk.theDataExtSecuritySourceDate, ' ', 8); memset(theIdentSecurityChunk.theDataExtSecurityConNum, ' ', 15); memset(theOverflowedHeaderType, ' ', 6); memset(theDataItemOverflowed, '0', 3); memset(theLengthOfUserDefinedSubheaderFields, '0', 4); theIdentSecurityChunk.theFilePartType[2] = '\0'; theIdentSecurityChunk.theUniqueDataExtTypeId[25] = '\0'; theIdentSecurityChunk.theVersionDataFieldDef[2] = '\0'; theIdentSecurityChunk.theDataExtSecurityClass[1] = '\0'; theIdentSecurityChunk.theDataExtClassSystem[2] = '\0'; theIdentSecurityChunk.theDataExtCodewords[11] = '\0'; theIdentSecurityChunk.theDataExtControlAndHand[2] = '\0'; theIdentSecurityChunk.theDataExtReleasingInst[20] = '\0'; theIdentSecurityChunk.theDataExtDeclassType[2] = '\0'; theIdentSecurityChunk.theDataExtDeclassDate[8] = '\0'; theIdentSecurityChunk.theDataExtDeclassExempt[4] = '\0'; theIdentSecurityChunk.theDataExtSecurityDowngrade[1] = '\0'; theIdentSecurityChunk.theDataExtSecurityDowngradeDate[8] = '\0'; theIdentSecurityChunk.theDataExtSecurityClassText[43] = '\0'; theIdentSecurityChunk.theDataExtClassAuthType[1] = '\0'; theIdentSecurityChunk.theDataExtClassAuthority[40] = '\0'; theIdentSecurityChunk.theDataExtClassReason[1] = '\0'; theIdentSecurityChunk.theDataExtSecuritySourceDate[8] = '\0'; theIdentSecurityChunk.theDataExtSecurityConNum[15] = '\0'; theOverflowedHeaderType[6] = '\0'; theDataItemOverflowed[3] = '\0'; theLengthOfUserDefinedSubheaderFields[4] = '\0'; theUserDefinedSubheaderFields.clear(); theData.clear(); theTagList.clear(); } void ossimNitfDataExtensionSegmentV2_1::setTagList(const std::vector &tagList) { theTagList = tagList; theData.clear(); } void ossimNitfDataExtensionSegmentV2_1::setSecurityMarkings(const ossimNitfFileHeaderV2_1 &fileHeader) { strcpy(theIdentSecurityChunk.theDataExtSecurityClass, fileHeader.getSecurityClassification().c_str()); strcpy(theIdentSecurityChunk.theDataExtClassSystem, fileHeader.getSecurityClassificationSys().c_str()); strcpy(theIdentSecurityChunk.theDataExtCodewords, fileHeader.getCodeWords().c_str()); strcpy(theIdentSecurityChunk.theDataExtControlAndHand, fileHeader.getControlAndHandling().c_str()); strcpy(theIdentSecurityChunk.theDataExtReleasingInst, fileHeader.getReleasingInstructions().c_str()); strcpy(theIdentSecurityChunk.theDataExtDeclassType, fileHeader.getDeclassificationType().c_str()); strcpy(theIdentSecurityChunk.theDataExtDeclassDate, fileHeader.getDeclassificationDate().c_str()); strcpy(theIdentSecurityChunk.theDataExtDeclassExempt, fileHeader.getDeclassificationExemption().c_str()); strcpy(theIdentSecurityChunk.theDataExtSecurityDowngrade, fileHeader.getDowngrade().c_str()); strcpy(theIdentSecurityChunk.theDataExtSecurityDowngradeDate, fileHeader.getDowngradingDate().c_str()); strcpy(theIdentSecurityChunk.theDataExtSecurityClassText, fileHeader.getClassificationText().c_str()); strcpy(theIdentSecurityChunk.theDataExtClassAuthType, fileHeader.getClassificationAuthorityType().c_str()); strcpy(theIdentSecurityChunk.theDataExtClassAuthority, fileHeader.getClassificationAuthority().c_str()); strcpy(theIdentSecurityChunk.theDataExtClassReason, fileHeader.getClassificationReason().c_str()); strcpy(theIdentSecurityChunk.theDataExtSecuritySourceDate, fileHeader.getSecuritySourceDate().c_str()); strcpy(theIdentSecurityChunk.theDataExtSecurityConNum, fileHeader.getSecurityControlNumber().c_str()); } std::ostream& ossimNitfDataExtensionSegmentV2_1::print(std::ostream& out)const { out << "theIdentSecurityChunk: " << theIdentSecurityChunk << "\ntheOverflowedHeaderType: " << theOverflowedHeaderType << "\ntheDataItemOverflowed: " << theDataItemOverflowed << "\ntheLengthOfUserDefinedSubheaderFields: " << theLengthOfUserDefinedSubheaderFields << "\ntag count: " << theTagList.size() << std::endl; return out; } ossim_uint32 ossimNitfDataExtensionSegmentV2_1::getHeaderLength() const { if (ossimString(theIdentSecurityChunk.theUniqueDataExtTypeId).trim().upcase() == "TRE_OVERFLOW") { return 209; } return 200 + theUserDefinedSubheaderFields.size(); } ossim_uint64 ossimNitfDataExtensionSegmentV2_1::getDataLength() const { ossim_uint64 totalDataLength = 0; if (theTagList.empty() == true) { totalDataLength = theData.size(); } else { for (std::vector::const_iterator iter = theTagList.begin(); iter != theTagList.end(); iter++) { totalDataLength += iter->getTotalTagLength(); } } return totalDataLength; } void ossimNitfDataExtensionSegmentV2_1::setProperty(ossimRefPtr property) { if (property.get() == NULL) { return; } const ossimString& name = property->getName(); if (name == DE_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theFilePartType, property->valueToString(), 2); } else if (name == DESID_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theUniqueDataExtTypeId, property->valueToString(), 25); } else if (name == DESVER_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theVersionDataFieldDef, property->valueToString(), 2, ios::right, '0'); } else if (name == DECLAS_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtSecurityClass, property->valueToString(), 1); } else if (name == DESCLSY_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtClassSystem, property->valueToString(), 2); } else if (name == DESCODE_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtCodewords, property->valueToString(), 11); } else if (name == DESCTLH_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtControlAndHand, property->valueToString(), 2); } else if (name == DESREL_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtReleasingInst, property->valueToString(), 20); } else if (name == DESDCTP_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtDeclassType, property->valueToString(), 2); } else if (name == DESDCDT_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtDeclassDate, property->valueToString(), 8); } else if (name == DESDCXM_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtDeclassExempt, property->valueToString(), 4); } else if (name == DESDG_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtSecurityDowngrade, property->valueToString(), 1); } else if (name == DESDGDT_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtSecurityDowngradeDate, property->valueToString(), 8); } else if (name == DESCLTX_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtSecurityClassText, property->valueToString(), 43); } else if (name == DESCATP_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtClassAuthType, property->valueToString(), 1); } else if (name == DESCAUT_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtClassAuthority, property->valueToString(), 40); } else if (name == DESCRSN_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtClassReason, property->valueToString(), 1); } else if (name == DESSRDT_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtSecuritySourceDate, property->valueToString(), 8); } else if (name == DESCTLN_KW) { ossimNitfCommon::setField(theIdentSecurityChunk.theDataExtSecurityConNum, property->valueToString(), 15); } else if (name == DESOFLW_KW) { ossimNitfCommon::setField(theOverflowedHeaderType, property->valueToString(), 6); } else if (name == DESITEM_KW) { ossimNitfCommon::setField(theDataItemOverflowed, property->valueToString(), 3, ios::right, '0'); } else if (name == DESSHL_KW) { ossimNitfCommon::setField(theLengthOfUserDefinedSubheaderFields, property->valueToString(), 4, ios::right, '0'); } else if (name == DESSHF_KW) { ossimBinaryDataProperty* pBinaryData = PTR_CAST(ossimBinaryDataProperty, property.get()); if (pBinaryData != NULL) { theUserDefinedSubheaderFields = pBinaryData->getBinaryData(); } } else if (name == DESDATA_KW) { ossimBinaryDataProperty* pBinaryData = PTR_CAST(ossimBinaryDataProperty, property.get()); if (pBinaryData != NULL) { theData = pBinaryData->getBinaryData(); } } } ossimRefPtr ossimNitfDataExtensionSegmentV2_1::getProperty(const ossimString& name)const { ossimProperty* property = 0; if (name == DE_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theFilePartType).trim()); } else if (name == DESID_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theUniqueDataExtTypeId).trim()); } else if (name == DESVER_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theVersionDataFieldDef).trim()); } else if (name == DECLAS_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtSecurityClass).trim()); } else if (name == DESCLSY_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtClassSystem).trim()); } else if (name == DESCODE_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtCodewords).trim()); } else if (name == DESCTLH_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtControlAndHand).trim()); } else if (name == DESREL_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtReleasingInst).trim()); } else if (name == DESDCTP_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtDeclassType).trim()); } else if (name == DESDCDT_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtDeclassDate).trim()); } else if (name == DESDCXM_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtDeclassExempt).trim()); } else if (name == DESDG_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtSecurityDowngrade).trim()); } else if (name == DESDGDT_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtSecurityDowngradeDate).trim()); } else if (name == DESCLTX_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtSecurityClassText).trim()); } else if (name == DESCATP_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtClassAuthType).trim()); } else if (name == DESCAUT_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtClassAuthority).trim()); } else if (name == DESCRSN_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtClassReason).trim()); } else if (name == DESSRDT_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtSecuritySourceDate).trim()); } else if (name == DESCTLN_KW) { property = new ossimStringProperty(name, ossimString(theIdentSecurityChunk.theDataExtSecurityConNum).trim()); } else if (name == DESOFLW_KW) { property = new ossimStringProperty(name, ossimString(theOverflowedHeaderType).trim()); } else if (name == DESITEM_KW) { property = new ossimStringProperty(name, ossimString(theDataItemOverflowed).trim()); } else if (name == DESSHL_KW) { property = new ossimStringProperty(name, ossimString(theLengthOfUserDefinedSubheaderFields).trim()); } else if (name == DESSHF_KW) { property = new ossimBinaryDataProperty(name, theUserDefinedSubheaderFields); } else if (name == DESDATA_KW) { // Only valid if setTagList has not been called on this object. property = new ossimBinaryDataProperty(name, theData); } return property; } void ossimNitfDataExtensionSegmentV2_1::getPropertyNames(std::vector& propertyNames)const { ossimNitfDataExtensionSegment::getPropertyNames(propertyNames); propertyNames.push_back(DESID_KW); propertyNames.push_back(DESCLSY_KW); propertyNames.push_back(DESDCTP_KW); propertyNames.push_back(DESDCDT_KW); propertyNames.push_back(DESDCXM_KW); propertyNames.push_back(DESDG_KW); propertyNames.push_back(DESDGDT_KW); propertyNames.push_back(DESCLTX_KW); propertyNames.push_back(DESCATP_KW); propertyNames.push_back(DESCRSN_KW); propertyNames.push_back(DESSRDT_KW); } ossim-Miami-2.9.1/src/support_data/ossimNitfDesFactory.cpp000066400000000000000000000011101352751253100236430ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDesFactory.cpp 9094 2006-06-13 19:12:40Z dburken $ #include RTTI_DEF1(ossimNitfDesFactory, "ossimNitfDesFactory", ossimObject) ossimNitfDesFactory::~ossimNitfDesFactory() { } ossimNitfDesFactory::ossimNitfDesFactory() { } ossim-Miami-2.9.1/src/support_data/ossimNitfDesFactoryRegistry.cpp000066400000000000000000000050411352751253100254030ustar00rootroot00000000000000//******************************************************************* // // LICENSE: See top level LICENSE.txt file. // // Author: // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDesFactoryRegistry.cpp 22875 2014-08-27 13:52:03Z dburken $ #include #include #include /* for std::find */ ossimNitfDesFactoryRegistry::ossimNitfDesFactoryRegistry() { initializeDefaults(); } ossimNitfDesFactoryRegistry::~ossimNitfDesFactoryRegistry() { } void ossimNitfDesFactoryRegistry::registerFactory(ossimNitfDesFactory* aFactory) { if(aFactory&&!exists(aFactory)) { theFactoryList.push_back(aFactory); } } void ossimNitfDesFactoryRegistry::unregisterFactory (ossimNitfDesFactory* aFactory) { std::vector::iterator iter = std::find(theFactoryList.begin(), theFactoryList.end(), aFactory); if(iter != theFactoryList.end()) { theFactoryList.erase(iter); } } ossimNitfDesFactoryRegistry* ossimNitfDesFactoryRegistry::instance() { static ossimNitfDesFactoryRegistry inst; return &inst; } ossimRefPtr ossimNitfDesFactoryRegistry::create(const ossimString &desName)const { std::vector::const_iterator factory; ossimRefPtr result = 0; factory = theFactoryList.begin(); while(factory != theFactoryList.end()) { result = (*factory)->create(desName); if(result.valid()) { return result; } ++factory; } return result; //ossimRefPtr des = new ossimNitfUnknownDes; //return des; } void ossimNitfDesFactoryRegistry::initializeDefaults() { theFactoryList.push_back(ossimNitfRegisteredDesFactory::instance()); } bool ossimNitfDesFactoryRegistry::exists(ossimNitfDesFactory* factory)const { std::vector::const_iterator iter = std::find(theFactoryList.begin(), theFactoryList.end(), factory); return (iter != theFactoryList.end()); } ossimNitfDesFactoryRegistry::ossimNitfDesFactoryRegistry( const ossimNitfDesFactoryRegistry&) { } const ossimNitfDesFactoryRegistry& ossimNitfDesFactoryRegistry::operator=( const ossimNitfDesFactoryRegistry&) { return *this; } ossim-Miami-2.9.1/src/support_data/ossimNitfDesInformation.cpp000066400000000000000000000242371352751253100245400ustar00rootroot00000000000000//******************************************************************* // // LICENSE: LGPL see top level LICENSE.txt // // Author: // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfDesInformation.cpp 23569 2015-10-05 19:32:00Z dburken $ #include #include #include #include #include #include #include #include // for memset ossimNitfDesInformation::ossimNitfDesInformation(ossimRefPtr desData) { clearFields(); setDesData(desData); } ossimNitfDesInformation::~ossimNitfDesInformation() { } void ossimNitfDesInformation::parseStream(std::istream &in, ossim_uint64 dataLength) { if(in) { clearFields(); m_desOffset = in.tellg(); in.read(m_de, DE_SIZE); in.read(m_desid, DESID_SIZE); in.read(m_desver, DESVER_SIZE); in.read(m_declas, DECLAS_SIZE); in.read(m_desclsy, DESCLSY_SIZE); in.read(m_descode, DESCODE_SIZE); in.read(m_desctlh, DESCTLH_SIZE); in.read(m_desrel, DESREL_SIZE); in.read(m_desdctp, DESDCTP_SIZE); in.read(m_desdcdt, DESDCDT_SIZE); in.read(m_desdcxm, DESDCXM_SIZE); in.read(m_desdg, DESDG_SIZE); in.read(m_desdgdt, DESDGDT_SIZE); in.read(m_descltx, DESCLTX_SIZE); in.read(m_descatp, DESCATP_SIZE); in.read(m_descaut, DESCAUT_SIZE); in.read(m_descrsn, DESCRSN_SIZE); in.read(m_dessrdt, DESSRDT_SIZE); in.read(m_desctln, DESCTLN_SIZE); if (getDesId() == "TRE_OVERFLOW") { in.read(m_desoflw, DESOFLW_SIZE); in.read(m_desitem, DESITEM_SIZE); } in.read(m_desshl, DESSHL_SIZE); m_desDataOffset = in.tellg(); m_desData = ossimNitfDesFactoryRegistry::instance()->create(getDesId()); if (m_desData.valid()) { /* if (m_desData->getClassName() == "ossimNitfUnknownDes") { // Unknown des doesn't know his des name yet. m_desData->setDesName( getDesId() ); } */ //--- // Dess with dynamic des length construct with 0 length. // Set if 0. //--- if ( m_desData->getDesLength() == 0 ) { m_desData->setDesLength( dataLength ); } // Sanity check fixed length in code with length from CEL field: else if ( m_desData->getDesLength() != getDesLength() ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfDesInformation::parseStream WARNING!" << "\nCEL field length does not match fixed des length for des: " << m_desData->getDesName().c_str() << "\nCEL: " << getDesLength() << "\nDes: " << m_desData->getDesLength() << std::endl; } m_desData->parseStream(in); } else { m_desData = (ossimNitfRegisteredDes*)NULL; } } } void ossimNitfDesInformation::writeStream(std::ostream &out) { m_desOffset = out.tellp(); // Capture the offset. out.write(m_de, DE_SIZE); out.write(m_desid, DESID_SIZE); out.write(m_desver, DESVER_SIZE); out.write(m_declas, DECLAS_SIZE); out.write(m_desclsy, DESCLSY_SIZE); out.write(m_descode, DESCODE_SIZE); out.write(m_desctlh, DESCTLH_SIZE); out.write(m_desrel, DESREL_SIZE); out.write(m_desdctp, DESDCTP_SIZE); out.write(m_desdcdt, DESDCDT_SIZE); out.write(m_desdcxm, DESDCXM_SIZE); out.write(m_desdg, DESDG_SIZE); out.write(m_desdgdt, DESDGDT_SIZE); out.write(m_descltx, DESCLTX_SIZE); out.write(m_descatp, DESCATP_SIZE); out.write(m_descaut, DESCAUT_SIZE); out.write(m_descrsn, DESCRSN_SIZE); out.write(m_dessrdt, DESSRDT_SIZE); out.write(m_desctln, DESCTLN_SIZE); if (getDesId() == "TRE_OVERFLOW") { out.write(m_desoflw, DESOFLW_SIZE); out.write(m_desitem, DESITEM_SIZE); } out.write(m_desshl, DESSHL_SIZE); //out.write(m_desLength, 5); /* if(m_desData.valid()) { m_desData = out.tellp(); m_desData->writeStream(out); } */ } ossim_uint32 ossimNitfDesInformation::getTotalDesLength()const { return (getDesLength() + (ossim_uint32)11); } ossim_uint32 ossimNitfDesInformation::getDesLength()const { return ossimString(m_desLength).toUInt32(); } ossim_uint64 ossimNitfDesInformation::getDesOffset()const { return m_desOffset; } ossim_uint64 ossimNitfDesInformation::getDesDataOffset()const { return m_desDataOffset; } ossimString ossimNitfDesInformation::getDesId()const { return ossimString(m_desid).trim(); } std::ostream& ossimNitfDesInformation::print(std::ostream& out, const std::string& prefix)const { ossimString pfx = prefix; bool typeinfo = ossimString(ossimPreferences::instance()->findPreference("kwl_type_info")).toBool(); out << pfx << "DE:" << ((typeinfo) ? "(string)" : "") << m_de << "\n" << pfx << std::setw(24) << "DESID:" << ((typeinfo) ? "(string)" : "") << m_desid << "\n" << pfx << std::setw(24) << "DESVER:" << ((typeinfo) ? "(string)" : "") << m_desver << "\n" << pfx << std::setw(24) << "DECLAS:" << ((typeinfo) ? "(string)" : "") << m_declas << "\n" << pfx << std::setw(24) << "DESCLSY:" << ((typeinfo) ? "(string)" : "") << m_desclsy << "\n" << pfx << std::setw(24) << "DESCODE:" << ((typeinfo) ? "(string)" : "") << m_descode << "\n" << pfx << std::setw(24) << "DESCTLH:" << ((typeinfo) ? "(string)" : "") << m_desctlh << "\n" << pfx << std::setw(24) << "DESREL:" << ((typeinfo) ? "(string)" : "") << m_desrel << "\n" << pfx << std::setw(24) << "DESDCTP:" << ((typeinfo) ? "(string)" : "") << m_desdctp << "\n" << pfx << std::setw(24) << "DESDCDT:" << ((typeinfo) ? "(string)" : "") << m_desdcdt << "\n" << pfx << std::setw(24) << "DESDCXM:" << ((typeinfo) ? "(string)" : "") << m_desdcxm << "\n" << pfx << std::setw(24) << "DESDG:" << ((typeinfo) ? "(string)" : "") << m_desdg << "\n" << pfx << std::setw(24) << "DESDGDT:" << ((typeinfo) ? "(string)" : "") << m_desdgdt << "\n" << pfx << std::setw(24) << "DESCLTX:" << ((typeinfo) ? "" : "") << m_descltx << "\n" << pfx << std::setw(24) << "DESCATP:" << ((typeinfo) ? "(string)" : "") << m_descatp << "\n" << pfx << std::setw(24) << "DESCAUT:" << ((typeinfo) ? "(string)" : "") << m_descaut << "\n" << pfx << std::setw(24) << "DESCRSN:" << ((typeinfo) ? "(string)" : "") << m_descrsn << "\n" << pfx << std::setw(24) << "DESSRDT:" << ((typeinfo) ? "(string)" : "") << m_dessrdt << "\n" << pfx << std::setw(24) << "DESCTLN:" << ((typeinfo) ? "(string)" : "") << m_desctln << "\n" ; if (getDesId() == "TRE_OVERFLOW") { out << pfx << std::setw(24) << "DESOFLW:" << ((typeinfo) ? "(string)" : "") << m_desoflw << "\n" << pfx << std::setw(24) << "DESITEM:" << ((typeinfo) ? "(string)" : "") << m_desitem << "\n" ; } out << pfx << std::setw(24) << "DESSHL:" << ((typeinfo) ? "(string)" : "") << m_desshl << "\n" ; if (getDesData().valid()) { getDesData()->print(out, prefix); } return out; } void ossimNitfDesInformation::clearFields() { memset(m_de, ' ', DE_SIZE); m_de[DE_SIZE] = '\0'; memset(m_desid, ' ', DESID_SIZE); m_desid[DESID_SIZE] = '\0'; memset(m_desver, ' ', DESVER_SIZE); m_desver[DESVER_SIZE] = '\0'; memset(m_declas, ' ', DECLAS_SIZE); m_declas[DECLAS_SIZE] = '\0'; memset(m_desclsy, ' ', DESCLSY_SIZE); m_desclsy[DESCLSY_SIZE] = '\0'; memset(m_descode, ' ', DESCODE_SIZE); m_descode[DESCODE_SIZE] = '\0'; memset(m_desctlh, ' ', DESCTLH_SIZE); m_desctlh[DESCTLH_SIZE] = '\0'; memset(m_desrel, ' ', DESREL_SIZE); m_desrel[DESREL_SIZE] = '\0'; memset(m_desdctp, ' ', DESDCTP_SIZE); m_desdctp[DESDCTP_SIZE] = '\0'; memset(m_desdcdt, ' ', DESDCDT_SIZE); m_desdcdt[DESDCDT_SIZE] = '\0'; memset(m_desdcxm, ' ', DESDCXM_SIZE); m_desdcxm[DESDCXM_SIZE] = '\0'; memset(m_desdg, ' ', DESDG_SIZE); m_desdg[DESDG_SIZE] = '\0'; memset(m_desdgdt, ' ', DESDGDT_SIZE); m_desdgdt[DESDGDT_SIZE] = '\0'; memset(m_descltx, ' ', DESCLTX_SIZE); m_descltx[DESCLTX_SIZE] = '\0'; memset(m_descatp, ' ', DESCATP_SIZE); m_descatp[DESCATP_SIZE] = '\0'; memset(m_descaut, ' ', DESCAUT_SIZE); m_descaut[DESCAUT_SIZE] = '\0'; memset(m_descrsn, ' ', DESCRSN_SIZE); m_descrsn[DESCRSN_SIZE] = '\0'; memset(m_dessrdt, ' ', DESSRDT_SIZE); m_dessrdt[DESSRDT_SIZE] = '\0'; memset(m_desctln, ' ', DESCTLN_SIZE); m_desctln[DESCTLN_SIZE] = '\0'; memset(m_desoflw, ' ', DESOFLW_SIZE); m_desoflw[DESOFLW_SIZE] = '\0'; memset(m_desitem, ' ', DESITEM_SIZE); m_desitem[DESITEM_SIZE] = '\0'; memset(m_desshl, ' ', DESSHL_SIZE); m_desshl[DESSHL_SIZE] = '\0'; m_desOffset = 0; m_desDataOffset = 0; } void ossimNitfDesInformation::setDesName(const ossimString& desName) { memset(m_desid, ' ', DESID_SIZE); std::ostringstream out; out << std::setw(DESID_SIZE) << std::setfill(' ') << m_desid; memcpy(m_desid, out.str().c_str(), DESID_SIZE); } void ossimNitfDesInformation::setDesLength(ossim_uint32 desLength) { /* memset(m_desLength, 0, 5); if(desLength > 99999) { desLength = 99999; } std::ostringstream out; out << std::setw(5) << std::setfill('0') << desLength; memcpy(m_desLength, out.str().c_str(), 5); */ } ossimRefPtr ossimNitfDesInformation::getDesData() { return m_desData; } const ossimRefPtr ossimNitfDesInformation::getDesData()const { return m_desData; } void ossimNitfDesInformation::setDesData(ossimRefPtr desData) { m_desData = desData; /* memset(m_desid, ' ', DESID_SIZE); memset(m_desLength, ' ', 5); if(m_desData.valid()) { setDesName(m_desData->getRegisterDesName()); setDesLength(m_desData->getSizeInBytes()); } */ } ossim-Miami-2.9.1/src/support_data/ossimNitfEmbeddedRpfDes.cpp000066400000000000000000000016341352751253100244100ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfEmbeddedRpfDes.cpp 22013 2012-12-19 17:37:20Z dburken $ #include #include #include RTTI_DEF1(ossimNitfEmbeddedRpfDes, "ossimNitfEmbeddedRpfDes", ossimNitfRegisteredTag) ossimNitfEmbeddedRpfDes::ossimNitfEmbeddedRpfDes() : ossimNitfRegisteredTag(std::string("RPFDES"), 0) { } ossimNitfEmbeddedRpfDes::~ossimNitfEmbeddedRpfDes() { } void ossimNitfEmbeddedRpfDes::parseStream(std::istream& /* in */ ) { } std::ostream& ossimNitfEmbeddedRpfDes::print(std::ostream& out, const std::string& /* prefix */)const { return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfEngrdaTag.cpp000066400000000000000000000161541352751253100234520ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: ENGRDA - Engineering Data tag class declaration. // // See document STDI-0002 (version 3), Appendix N for more info. // //---------------------------------------------------------------------------- // $Id #include #include #include #include #include #include #include #include using namespace std; static const ossimTrace traceDebug(ossimString("ossimNitfEngrda:debug")); RTTI_DEF1(ossimNitfEngrdaTag, "ossimNitfEngrdaTag", ossimNitfRegisteredTag); ossimNitfEngrdaTag::ossimNitfEngrdaTag() : ossimNitfRegisteredTag(std::string("ENGRDA"), 0) { clearFields(); } ossimNitfEngrdaTag::~ossimNitfEngrdaTag() { } void ossimNitfEngrdaTag::parseStream(std::istream& in) { clearFields(); in.read(m_reSrc, RESRC_SIZE); in.read(m_reCnt, RECNT_SIZE); const ossim_uint16 ELEMENT_COUNT = ossimString(m_reCnt).toUInt16(); for (ossim_uint16 i = 0; i < ELEMENT_COUNT; ++i) { ossimString os; ossim_uint32 size(0); char buf[TMP_BUF_SIZE]; ossimEngDataElement element; // ENGLN - label length field in.read(element.m_engLn, ENGLN_SIZE); element.m_engLn[ENGLN_SIZE] = '\0'; // ENGLBL - label field os = element.m_engLn; size = os.toUInt16(); in.read(buf, size); buf[size] = '\0'; element.m_engLbl = buf; // ENGMTXC - data column count in.read(element.m_engMtxC, ENGMTXC_SIZE); element.m_engMtxC[ENGMTXC_SIZE] = '\0'; // ENGMTXR - data row count in.read(element.m_engMtxR, ENGMTXR_SIZE); element.m_engMtxR[ENGMTXR_SIZE] = '\0'; // ENGTYP - Value Type of Engineering Data Element. in.get( element.m_engTyp ); // ENGDTS - Engineering Data Element Size in.get( element.m_engDts ); os = element.m_engDts; ossim_uint32 engDataElementSize = os.toUInt32(); // ENGDATU - Engineering Data Units. in.read( element.m_engDatU, ENGDATU_SIZE ); element.m_engDatU[ENGDATU_SIZE] = '\0'; // ENGDATC - Engineering Data Count in.read(element.m_engDatC, ENGDATC_SIZE); element.m_engDatC[ENGDATC_SIZE] = '\0'; os = element.m_engDatC; ossim_uint32 engDataCount = os.toUInt32(); // ENGDATA - Engineering Data size = engDataElementSize * engDataCount; element.m_engDat.resize(size); in.read((char*)&(element.m_engDat.front()), size); m_data.push_back(element); } // Matches: for (ossim_uint16 i = 0; i < ELEMENT_COUNT; ++i) } void ossimNitfEngrdaTag::writeStream(std::ostream& out) { //out.write(theAcMsnId, AC_MSN_ID_SIZE); // out.write(theAcTailNo, AC_TAIL_NO_SIZE); out.write(m_reSrc, RESRC_SIZE); out.write(m_reCnt, RECNT_SIZE); const ossim_uint16 ELEMENT_COUNT = ossimString(m_reCnt).toUInt16(); for (ossim_uint16 i = 0; i < ELEMENT_COUNT; ++i) { // ENGLN - label length field out.write(m_data[i].m_engLn, ENGLN_SIZE); // ENGLBL - label field out.write(m_data[i].m_engLbl.data(), (std::streamsize)m_data[i].m_engLbl.size()); // ENGMTXC - data column count out.write(m_data[i].m_engMtxC, ENGMTXC_SIZE ); // ENGMTXR - data row count out.write(m_data[i].m_engMtxR, ENGMTXR_SIZE ); // ENGTYP - Value Type of Engineering Data Element. out.write( (char*)(&m_data[i].m_engTyp), ENGTYP_SIZE ); // ENGDTS - Engineering Data Element Size out.write((char*)(&m_data[i].m_engDts), ENGDTS_SIZE ); // ENGDATU - Engineering Data Units. out.write( m_data[i].m_engDatU, ENGDATU_SIZE ); // ENGDATC - Engineering Data Count out.write( m_data[i].m_engDatC, ENGDATC_SIZE ); // ENGDATA - Engineering Data NOTE: should be big endian... out.write((char*)&(m_data[i].m_engDat.front()), (std::streamsize)m_data[i].m_engDat.size()); } // Matches: for (ossim_uint16 i = 0; i < ELEMENT_COUNT; ++i) } void ossimNitfEngrdaTag::clearFields() { // BCS-N's to '0's, BCS-A's to ' '(spaces) // clear memset(m_reSrc, ' ', RESRC_SIZE); memset(m_reCnt, ' ', RECNT_SIZE); m_data.clear(); // null terminate m_reSrc[RESRC_SIZE] = '\0'; m_reCnt[RECNT_SIZE] = '\0'; } std::ostream& ossimNitfEngrdaTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; const ossim_uint32 W = 17; out << setiosflags(std::ios::left) << pfx << std::setw(W) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(W) << "CEL:" << getSizeInBytes() << "\n" << pfx << std::setw(W) << "RESRC:" << m_reSrc << "\n" << pfx << std::setw(W) << "RECNT:" << m_reCnt << "\n"; for (ossim_uint32 i = 0; i < m_data.size(); ++i) { out << pfx << "ENGLN[" << i << std::setw(W-7) << "]:" << m_data[i].m_engLn << "\n" << pfx << "ENGLBL[" << i << std::setw(W-8) << "]:" << m_data[i].m_engLbl << "\n" << pfx << "ENGMTXC[" << i << std::setw(W-9) << "]:" << m_data[i].m_engMtxC << "\n" << pfx << "ENGMTXR[" << i << std::setw(W-9) << "]:" << m_data[i].m_engMtxR << "\n" << pfx << "ENGTYP[" << i << std::setw(W-8) << "]:" << std::string(1, m_data[i].m_engTyp) << "\n" << pfx << "ENGDTS[" << i << std::setw(W-8) << "]:" << std::string(1, m_data[i].m_engDts) << "\n" << pfx << "ENGDATU[" << i << std::setw(W-9) << "]:" << m_data[i].m_engDatU << "\n" << pfx << "ENGDATC[" << i << std::setw(W-9) << "]:" << m_data[i].m_engDat.size() << "\n"; printData(out, m_data[i], i, pfx); } return out; } std::ostream& ossimNitfEngrdaTag::printData( std::ostream& out, const ossimEngDataElement& element, ossim_uint32 elIndex, const std::string& prefix ) const { if (element.m_engTyp == 'A') { out << prefix << "ENGDATA[" << elIndex << std::setw(8) << "]:"; std::vector::const_iterator i = element.m_engDat.begin(); while (i != element.m_engDat.end()) { out << static_cast(*i); ++i; } out << "\n"; } else { out << prefix << "ENGDATA[" << elIndex << std::setw(8) << "]: NOT DISPLAYED\n"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfEngrdaTag::printData WARNING unhandled data type." << "Data type = " << (char)element.m_engTyp << "\n" << std::endl; } } return out; } template void ossimNitfEngrdaTag::getValueAsString( T v, ossim_uint16 w, std::string& s) const { std::ostringstream os; os << std::setw(w) << std::setfill('0') << setiosflags(ios::right) << v; s = os.str(); } ossim-Miami-2.9.1/src/support_data/ossimNitfExoptaTag.cpp000066400000000000000000000117601352751253100235100ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: EXOPTA tag class definition // //---------------------------------------------------------------------------- // $Id$ #include #include #include using namespace std; ossimNitfExoptaTag::ossimNitfExoptaTag() : ossimNitfRegisteredTag(std::string("EXOPTA"), CEL_SIZE) { clearFields(); } void ossimNitfExoptaTag::parseStream(std::istream& in) { clearFields(); in.read(m_angleToNorth,ANGLE_TO_NORTH_SIZE); in.read(m_meanGsd, MEAN_GSD_SIZE); in.read(m_reserved1, EXOPTA_RESERVED1_SIZE); in.read(m_dynamicRange, DYNAMIC_RANGE_SIZE); in.read(m_reserved2, EXOPTA_RESERVED2_SIZE); in.read(m_oblAng, OBL_ANG_SIZE); in.read(m_rollAng, ROLL_ANG_SIZE); in.read(m_primeId, PRIME_ID_SIZE); in.read(m_primeBe, PRIME_BE_SIZE); in.read(m_reserved3, EXOPTA_RESERVED3_SIZE); in.read(m_nSec, N_SEC_SIZE); in.read(m_reserved4, EXOPTA_RESERVED4_SIZE); in.read(m_reserved5, EXOPTA_RESERVED5_SIZE); in.read(m_nSeg, N_SEG_SIZE); in.read(m_maxLpSeg, MAX_LP_SEG_SIZE); in.read(m_reserved6, EXOPTA_RESERVED6_SIZE); in.read(m_sunEl, SUN_EL_SIZE); in.read(m_sunAz, SUN_AZ_SIZE); } void ossimNitfExoptaTag::writeStream(std::ostream& out) { out.write(m_angleToNorth,ANGLE_TO_NORTH_SIZE); out.write(m_meanGsd, MEAN_GSD_SIZE); out.write(m_reserved1, EXOPTA_RESERVED1_SIZE); out.write(m_dynamicRange, DYNAMIC_RANGE_SIZE); out.write(m_reserved2, EXOPTA_RESERVED2_SIZE); out.write(m_oblAng, OBL_ANG_SIZE); out.write(m_rollAng, ROLL_ANG_SIZE); out.write(m_primeId, PRIME_ID_SIZE); out.write(m_primeBe, PRIME_BE_SIZE); out.write(m_reserved3, EXOPTA_RESERVED3_SIZE); out.write(m_nSec, N_SEC_SIZE); out.write(m_reserved4, EXOPTA_RESERVED4_SIZE); out.write(m_reserved5, EXOPTA_RESERVED5_SIZE); out.write(m_nSeg, N_SEG_SIZE); out.write(m_maxLpSeg, MAX_LP_SEG_SIZE); out.write(m_reserved6, EXOPTA_RESERVED6_SIZE); out.write(m_sunEl, SUN_EL_SIZE); out.write(m_sunAz, SUN_AZ_SIZE); } std::ostream& ossimNitfExoptaTag::print(std::ostream& out, const std::string& prefix )const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "ANGLE_TO_NORTH:" << m_angleToNorth<< "\n" << pfx << std::setw(24) << "DYNAMIC_RANGE:" << m_dynamicRange<< "\n" << pfx << std::setw(24) << "OBL_ANG:" << m_oblAng<< "\n" << pfx << std::setw(24) << "ROLL_ANG:" << m_rollAng<< "\n" << pfx << std::setw(24) << "PRIME_ID:" << m_primeId<< "\n" << pfx << std::setw(24) << "PRIME_BE:" << m_primeBe<< "\n" << pfx << std::setw(24) << "N_SEC" << m_nSec<< "\n" << pfx << std::setw(24) << "N_SEG:" << m_nSeg<< "\n" << pfx << std::setw(24) << "MAX_LP_SEG:" << m_maxLpSeg<< "\n" << pfx << std::setw(24) << "SUN_EL:" << m_sunEl<< "\n" << pfx << std::setw(24) << "SUN_AZ:" << m_sunAz<< "\n"; return out; } void ossimNitfExoptaTag::clearFields() { memset(m_angleToNorth, '0', ANGLE_TO_NORTH_SIZE); memset(m_meanGsd, '0', MEAN_GSD_SIZE); m_meanGsd[3] = '.'; m_reserved1[0] = '1'; memset(m_dynamicRange, '0', DYNAMIC_RANGE_SIZE); memset(m_reserved2, ' ', EXOPTA_RESERVED2_SIZE); memset(m_oblAng, '0', OBL_ANG_SIZE); m_oblAng[2] = '.'; memset(m_rollAng, '0',ROLL_ANG_SIZE); m_rollAng[0]='+'; m_rollAng[3]='.'; memset(m_primeId, ' ', PRIME_ID_SIZE); memset(m_primeBe, ' ', PRIME_BE_SIZE); memset(m_reserved3, ' ', EXOPTA_RESERVED3_SIZE); memset(m_nSec, '0', N_SEC_SIZE); memset(m_reserved4, ' ', EXOPTA_RESERVED4_SIZE); memset(m_reserved5, '0', EXOPTA_RESERVED5_SIZE); m_reserved5[6] = '1'; memset(m_nSeg, '0', N_SEG_SIZE); m_nSeg[2] = '1'; memset(m_maxLpSeg, '0', MAX_LP_SEG_SIZE); m_maxLpSeg[5] = '1'; memset(m_reserved6, ' ', EXOPTA_RESERVED6_SIZE); memset(m_sunEl, '0', SUN_EL_SIZE); m_sunEl[0] = '+'; m_sunEl[3] = '.'; memset(m_sunAz, '0', SUN_AZ_SIZE); m_sunAz[3] = '.'; m_angleToNorth[ANGLE_TO_NORTH_SIZE] = '\0'; m_meanGsd[MEAN_GSD_SIZE]='\0'; m_reserved1[EXOPTA_RESERVED1_SIZE]='\0'; m_dynamicRange[DYNAMIC_RANGE_SIZE]='\0'; m_reserved2[EXOPTA_RESERVED2_SIZE]='\0'; m_oblAng[OBL_ANG_SIZE]='\0'; m_rollAng[ROLL_ANG_SIZE]='\0'; m_primeId[PRIME_ID_SIZE]='\0'; m_primeBe[PRIME_BE_SIZE]='\0'; m_reserved3[EXOPTA_RESERVED3_SIZE]='\0'; m_nSec[N_SEC_SIZE]='\0'; m_reserved4[EXOPTA_RESERVED4_SIZE]='\0'; m_reserved5[EXOPTA_RESERVED5_SIZE]='\0'; m_nSeg[N_SEG_SIZE]='\0'; m_maxLpSeg[MAX_LP_SEG_SIZE]='\0'; m_reserved6[EXOPTA_RESERVED6_SIZE]='\0'; m_sunEl[SUN_EL_SIZE]='\0'; m_sunAz[SUN_AZ_SIZE]='\0'; } ossim-Miami-2.9.1/src/support_data/ossimNitfFile.cpp000066400000000000000000000333111352751253100224670ustar00rootroot00000000000000//--- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Static trace for debugging static ossimTrace traceDebug("ossimNitfFile:debug"); std::ostream& operator <<(std::ostream& out, const ossimNitfFile& data) { return data.print(out); } std::ostream& ossimNitfFile::print(std::ostream& out, const std::string& prefix, bool printOverviews) const { if(theNitfFileHeader.valid()) { std::string pfx = prefix; pfx += "nitf."; theNitfFileHeader->print(out, pfx); ossim_int32 n = theNitfFileHeader->getNumberOfImages(); for(ossim_int32 idx = 0; idx < n; ++idx) { ossimRefPtr ih = getNewImageHeader(idx); if(ih) { bool printIt = true; if ( !printOverviews ) { // Check the IMAG field. ossim_float64 imag; ih->getDecimationFactor(imag); if ( !ossim::isnan(imag) ) { if ( imag < 1.0) { printIt = false; } } } if (printIt) { // Add our prefix onto prefix. std::string s = pfx; s += "image"; s += ossimString::toString(idx).string(); s += "."; ih->print(out, s); } ih = 0; } } //--- // Check for RPF stuff: //--- ossimNitfTagInformation info; theNitfFileHeader->getTag(info, "RPFHDR"); if(info.getTagName() == "RPFHDR") { // Open of the a.toc. ossimRefPtr toc = new ossimRpfToc; if ( toc->parseFile(getFilename()) == ossimErrorCodes::OSSIM_OK ) { pfx += "rpf."; toc->print(out, pfx, printOverviews); } } } // matches: if(theNitfFileHeader.valid()) return out; } std::ostream& ossimNitfFile::print(std::ostream& out, ossim_uint32 entryIndex, const std::string& prefix, bool printOverviews) const { if(theNitfFileHeader.valid()) { std::string pfx = prefix; pfx += "nitf."; theNitfFileHeader->print(out, pfx); if ( entryIndex < (ossim_uint32)theNitfFileHeader->getNumberOfImages() ) { ossimRefPtr ih = getNewImageHeader(entryIndex); if ( ih.valid() == true ) { bool printIt = true; if ( !printOverviews ) { // Check the IMAG field. ossim_float64 imag; ih->getDecimationFactor(imag); if ( !ossim::isnan(imag) ) { if ( imag < 1.0) { printIt = false; } } //--- // Now see if it's a cloud mask image. Do not print // cloud mask images if the printOverviews is false. //--- if ( printIt ) { if ( (ih->getCategory().trim(ossimString(" ")) == "CLOUD") && (ih->getRepresentation().trim(ossimString(" ")) == "NODISPLY") ) { printIt = false; } } } if (printIt) { // Add our prefix onto prefix. std::string s = pfx; s += "image"; s += ossimString::toString(entryIndex).string(); s += "."; ih->print(out, s); } ih = 0; } } //--- // Check for RPF stuff: //--- ossimNitfTagInformation info; theNitfFileHeader->getTag(info, "RPFHDR"); if(info.getTagName() == "RPFHDR") { // Open of the a.toc. ossimRefPtr toc = new ossimRpfToc; if ( toc->parseFile(getFilename()) == ossimErrorCodes::OSSIM_OK ) { pfx += "rpf."; toc->printHeader(out, pfx); toc->printTocEntry( out, entryIndex, pfx, printOverviews ); } } } // matches: if(theNitfFileHeader.valid()) return out; } bool ossimNitfFile::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = theNitfFileHeader.valid(); if(theNitfFileHeader.valid()) { theNitfFileHeader->saveState(kwl, prefix); } ossim_int32 n = theNitfFileHeader->getNumberOfImages(); for(ossim_int32 idx = 0; idx < n; ++idx) { ossimRefPtr ih = getNewImageHeader(idx); ossimString newPrefix = prefix + "image" + ossimString::toString(idx) + "."; #if 1 ih->saveState(kwl, newPrefix); #else if ( (ih->getCategory().trim(ossimString(" ")) != "CLOUD") || (ih->getRepresentation().trim(ossimString(" ")) != "NODISPLY") ) { ih->saveState(kwl, newPrefix); } #endif } return result; } ossimNitfFile::ossimNitfFile() : theFilename(""), theNitfFileHeader(0) { } ossimNitfFile::~ossimNitfFile() { theNitfFileHeader = 0; } bool ossimNitfFile::parseFile(const ossimFilename& file) { bool result = false; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfFile::parseFile: entered...\n"; } //if( file.exists() ) { // Open up a stream to the file. std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( file, std::ios_base::in | std::ios_base::binary ); if ( str ) { result = parseStream( file, *str ); } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfFile::parseFile: " << "Could not open file: " << file.c_str() << "\n"; } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfFile::parseFile: " << "exit status: " << (result?"true":"false") << "\n"; } return result; } bool ossimNitfFile::parseStream( const ossimFilename& file, ossim::istream& in ) { bool result = false; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfFile::parseStream: DEBUG entered...\n"; } if(theNitfFileHeader.valid()) { theNitfFileHeader = 0; } char temp[10]; in.read(temp, 9); in.seekg(0, std::ios::beg); temp[9] ='\0'; theFilename = file; ossimString s(temp); if(s == "NITF02.00") { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: NITF Version 2.0" << std::endl; } theNitfFileHeader = new ossimNitfFileHeaderV2_0; } else if ( (s == "NITF02.10") || (s == "NSIF01.00") ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: NITF Version 2.1" << std::endl; } theNitfFileHeader = new ossimNitfFileHeaderV2_1; } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimNitfFile::parseFile: " << "Not an NITF file!\n"; } } if( theNitfFileHeader.valid() ) { try { theNitfFileHeader->parseStream(in); result = true; } catch( const ossimException& e ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfFile::parseStream caught exception:\n" << e.what() << std::endl; } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfFile::parseStream: DEBUG\n" << "exit status: " << (result?"true":"false") << "\n"; } return result; } const ossimNitfFileHeader* ossimNitfFile::getHeader() const { return theNitfFileHeader.get(); } ossimNitfFileHeader* ossimNitfFile::getHeader() { return theNitfFileHeader.get(); } ossimIrect ossimNitfFile::getImageRect()const { if(theNitfFileHeader.valid()) { return theNitfFileHeader->getImageRect(); } return ossimIrect(ossimIpt(0,0), ossimIpt(0,0)); } ossimNitfImageHeader* ossimNitfFile::getNewImageHeader( ossim_uint32 imageNumber)const { ossimNitfImageHeader* result = 0; if(theNitfFileHeader.valid()) { std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream(theFilename, std::ios::in|std::ios::binary); if ( in ) { result = getNewImageHeader( *in, imageNumber ); } } return result; } ossimNitfImageHeader* ossimNitfFile::getNewImageHeader( ossim::istream& in, ossim_uint32 imageNumber)const { ossimNitfImageHeader* result = 0; if(theNitfFileHeader.valid()) { try // getNewImageHeader can throw exception on parse. { result = theNitfFileHeader->getNewImageHeader(imageNumber, in); } catch( const ossimException& e ) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfFile::getNewImageHeader caught exception:\n" << e.what() << std::endl; } result = 0; } } return result; } ossimNitfSymbolHeader* ossimNitfFile::getNewSymbolHeader( ossim_uint32 symbolNumber)const { ossimNitfSymbolHeader* result = 0; if(theNitfFileHeader.valid()) { std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream(theFilename, std::ios::in|std::ios::binary); if ( in ) { result = getNewSymbolHeader( *in, symbolNumber ); } } return result; } ossimNitfSymbolHeader* ossimNitfFile::getNewSymbolHeader( ossim::istream& in, ossim_uint32 symbolNumber)const { ossimNitfSymbolHeader* result = 0; if(theNitfFileHeader.valid()) { result = theNitfFileHeader->getNewSymbolHeader(symbolNumber, in); } return result; } ossimNitfLabelHeader* ossimNitfFile::getNewLabelHeader( ossim_uint32 labelNumber)const { ossimNitfLabelHeader* result = 0; if(theNitfFileHeader.valid()) { std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream(theFilename, std::ios::in|std::ios::binary); if ( in ) { result = getNewLabelHeader( *in, labelNumber ); } } return result; } ossimNitfLabelHeader* ossimNitfFile::getNewLabelHeader( ossim::istream& in, ossim_uint32 labelNumber)const { ossimNitfLabelHeader* result = 0; if(theNitfFileHeader.valid()) { result = theNitfFileHeader->getNewLabelHeader(labelNumber, in); } return result; } ossimNitfTextHeader* ossimNitfFile::getNewTextHeader( ossim_uint32 textNumber)const { ossimNitfTextHeader* result = 0; if(theNitfFileHeader.valid()) { std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream(theFilename, std::ios::in|std::ios::binary); if ( in ) { result = getNewTextHeader( *in, textNumber ); } } return result; } ossimNitfTextHeader* ossimNitfFile::getNewTextHeader( ossim::istream& in, ossim_uint32 textNumber)const { ossimNitfTextHeader* result = 0; if(theNitfFileHeader.valid()) { result = theNitfFileHeader->getNewTextHeader(textNumber, in); } return result; } ossimNitfDataExtensionSegment* ossimNitfFile::getNewDataExtensionSegment( ossim_uint32 dataExtNumber)const { ossimNitfDataExtensionSegment* result = 0; if(theNitfFileHeader.valid()) { std::shared_ptr in = ossim::StreamFactoryRegistry::instance()-> createIstream(theFilename, std::ios::in|std::ios::binary); if ( in ) { result = getNewDataExtensionSegment( *in, dataExtNumber ); } } return result; } ossimNitfDataExtensionSegment* ossimNitfFile::getNewDataExtensionSegment( ossim::istream& in, ossim_uint32 dataExtNumber)const { ossimNitfDataExtensionSegment* result = 0; if(theNitfFileHeader.valid()) { result = theNitfFileHeader->getNewDataExtensionSegment(dataExtNumber, in); } return result; } ossimString ossimNitfFile::getVersion()const { if(theNitfFileHeader.valid()) { return ossimString(theNitfFileHeader->getVersion()); } return ossimString(""); } ossimFilename ossimNitfFile::getFilename() const { return theFilename; } ossim-Miami-2.9.1/src/support_data/ossimNitfFileHeader.cpp000066400000000000000000000154131352751253100236030ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #include #include #include static const char* TAGS_KW = "tags"; RTTI_DEF2(ossimNitfFileHeader, "ossimNitfFileHeader", ossimObject, ossimPropertyInterface); std::ostream& ossimNitfImageOffsetInformation::print(std::ostream& out) const { return out << "theImageHeaderOffset: " << theImageHeaderOffset << std::endl << "theImageDataOffset: " << theImageDataOffset; } ossimNitfFileHeader::ossimNitfFileHeader() { } ossimNitfFileHeader::~ossimNitfFileHeader() { } bool ossimNitfFileHeader::getTag(ossimNitfTagInformation& tagInfo, const ossimString& tagName)const { if(theTagList.size()) { for(ossim_uint32 i = 0; i < theTagList.size(); ++i) { if(theTagList[i].getTagName() == tagName) { tagInfo = theTagList[i]; return true; } } } return false; } bool ossimNitfFileHeader::getDesInformation(ossimNitfDesInformation &desInfo, const ossimString &desId, bool exactMatch) { if (theDesList.size()) { for (ossim_uint32 i = 0; i < theDesList.size(); ++i) { if(exactMatch) { if (theDesList[i].getDesId() == desId) { desInfo = theDesList[i]; return true; } } else { if(theDesList[i].getDesId().contains(desId)) { desInfo = theDesList[i]; return true; } } } } return false; } bool ossimNitfFileHeader::hasImages()const { return (getNumberOfImages() > 0); } bool ossimNitfFileHeader::hasSymbols()const { return (getNumberOfSymbols() > 0); } bool ossimNitfFileHeader::hasGraphics()const { return (getNumberOfGraphics() > 0); } bool ossimNitfFileHeader::hasText()const { return (getNumberOfTextSegments() > 0); } bool ossimNitfFileHeader::hasLabels()const { return (getNumberOfLabels() > 0); } bool ossimNitfFileHeader::hasDataExtSegments()const { return (getNumberOfDataExtSegments() > 0); } void ossimNitfFileHeader::removeTag(const ossimString& tagName) { ossim_uint32 idx = 0; for(idx = 0; idx < theTagList.size(); ++idx) { if(theTagList[idx].getTagName() == tagName) { theTagList.erase(theTagList.begin() + idx); return; } } } void ossimNitfFileHeader::addTag(const ossimNitfTagInformation& tag, bool unique) { if(unique) { removeTag(tag.getTagName()); } theTagList.push_back(tag); } bool ossimNitfFileHeader::getTagInformation(ossimNitfTagInformation& tag, int idx) const { bool result = false; if(static_cast(idx) < theTagList.size()) { tag = theTagList[idx]; result = true; } return result; } int ossimNitfFileHeader::getNumberOfTags()const { return (int)theTagList.size(); } const std::vector &ossimNitfFileHeader::getDesInfoList() const { return theDesList; } ossim_uint32 ossimNitfFileHeader::getTotalTagLength() const { ossim_uint32 tagLength = 0; for(ossim_uint32 i = 0; i < theTagList.size(); ++i) { tagLength += theTagList[i].getTotalTagLength(); } return tagLength; } void ossimNitfFileHeader::setProperty(ossimRefPtr /* property */) { } ossimRefPtr ossimNitfFileHeader::getProperty(const ossimString& name)const { ossimRefPtr result = 0; if(name == TAGS_KW) { ossim_uint32 idxMax = (ossim_uint32)theTagList.size(); if(idxMax > 0) { ossimContainerProperty* containerProperty = new ossimContainerProperty; containerProperty->setName(name); ossim_uint32 idx = 0; result = containerProperty; for(idx = 0; idx < idxMax; ++idx) { ossimNitfTagInformation tagInfo; getTagInformation(tagInfo, idx); const ossimRefPtr tagData = tagInfo.getTagData(); if(tagData.valid()) { ossimContainerProperty* containerPropertyTag = new ossimContainerProperty; containerPropertyTag->setName(tagInfo.getTagName()); std::vector > propertyList; tagData->getPropertyList(propertyList); containerPropertyTag->addChildren(propertyList); containerProperty->addChild(containerPropertyTag); } else { containerProperty->addStringProperty(tagInfo.getTagName(), "", true); } } } } return result; } void ossimNitfFileHeader::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back(TAGS_KW); } bool ossimNitfFileHeader::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { ossimObject::saveState(kwl, prefix); bool result = true; ossimString tagsPrefix = prefix; ossim_uint32 i = 0; for(; i < theTagList.size(); ++i) { ossimRefPtr tag = theTagList[i].getTagData(); if (tag.valid()) { // we eventually need to do our own prefix for this object and not let the calling object do any prefix definitions // ossimString newPrefix = tagsPrefix + tag->getRegisterTagName() + "."; tag->saveState(kwl, tagsPrefix); } } i = 0; ossimString desPrefix = prefix + "des"; for (auto des : theDesList) { des.saveState(kwl, desPrefix+ossimString(i) + "."); } return result; } std::ostream& ossimNitfFileHeader::print(std::ostream& out, const std::string& prefix ) const { return printTags(out, prefix); } std::ostream& ossimNitfFileHeader::printTags(std::ostream& out, const std::string& prefix) const { ossim_uint32 i = 0; for (; i < theTagList.size(); ++i) { ossimRefPtr tag = theTagList[i].getTagData(); if (tag.valid()) { tag->print(out, prefix); } } ossimString desPrefix = prefix + "des"; for (i = 0; i < theDesList.size(); ++i) { theDesList[i].print(out, desPrefix + ossimString::toString(i) + "."); } return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfFileHeaderV2_0.cpp000066400000000000000000001427331352751253100242400ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // for memset #include #include #include using namespace std; const ossimString ossimNitfFileHeaderV2_0::FSDWNG_KW = "fsdwng"; const ossimString ossimNitfFileHeaderV2_0::FSDEVT_KW = "fsdevt"; static const ossimTrace traceDebug("ossimNitfFileHeaderV2_0:debug"); RTTI_DEF1(ossimNitfFileHeaderV2_0, "ossimNitfFileHeaderV2_0", ossimNitfFileHeaderV2_X) std::ostream& operator <<(std::ostream& out, const ossimNitfImageInfoRecordV2_0 &data) { return out << "theImageSubheaderLength: " << data.theImageSubheaderLength << std::endl << "theImageLength: " << data.theImageLength; } ossim_uint32 ossimNitfImageInfoRecordV2_0::getHeaderLength()const { return ossimString(theImageSubheaderLength).toInt32(); } ossim_uint64 ossimNitfImageInfoRecordV2_0::getImageLength()const { return ossimString(theImageLength).toInt32(); } ossim_uint64 ossimNitfImageInfoRecordV2_0::getTotalLength()const { return (getHeaderLength() + getImageLength()); } void ossimNitfImageInfoRecordV2_0::setSubheaderLength(ossim_uint32 length) { std::ostringstream out; out << std::setw(6) << std::setfill('0') << std::setiosflags(ios::right) << length; memcpy(theImageSubheaderLength, out.str().c_str(), 6); theImageSubheaderLength[6] = '\0'; } void ossimNitfImageInfoRecordV2_0::setImageLength(ossim_uint64 length) { std::ostringstream out; out << std::setw(10) << std::setfill('0') << std::setiosflags(ios::right) << length; memcpy(theImageLength, out.str().c_str(), 10); theImageLength[10] = '\0'; } std::ostream& operator <<(std::ostream& out, const ossimNitfSymbolInfoRecordV2_0 &data) { return out << "theSymbolSubheaderLength: " << data.theSymbolSubheaderLength << std::endl << "theSymbolLength: " << data.theSymbolLength; } ossim_int32 ossimNitfSymbolInfoRecordV2_0::getHeaderLength()const { return ossimString(theSymbolSubheaderLength).toInt32(); } ossim_int32 ossimNitfSymbolInfoRecordV2_0::getImageLength()const { return ossimString(theSymbolLength).toInt32(); } ossim_int32 ossimNitfSymbolInfoRecordV2_0::getTotalLength()const { return (getHeaderLength() + getImageLength()); } std::ostream& operator <<(std::ostream& out, const ossimNitfLabelInfoRecordV2_0 &data) { return out << "theLabelSubheaderLength: " << data.theLabelSubheaderLength << std::endl << "theLabelLength: " << data.theLabelLength; } ossim_int32 ossimNitfLabelInfoRecordV2_0::getHeaderLength()const { return ossimString(theLabelSubheaderLength).toInt32(); } ossim_int32 ossimNitfLabelInfoRecordV2_0::getImageLength()const { return ossimString(theLabelLength).toInt32(); } ossim_int32 ossimNitfLabelInfoRecordV2_0::getTotalLength()const { return (getHeaderLength() + getImageLength()); } std::ostream& operator <<(std::ostream& out, const ossimNitfTextInfoRecordV2_0 &data) { return out << "theTextSubheaderLength: " << data.theTextSubheaderLength << std::endl << "theTextLength: " << data.theTextLength; } ossim_int32 ossimNitfTextInfoRecordV2_0::getHeaderLength()const { return ossimString(theTextSubheaderLength).toInt32(); } ossim_int32 ossimNitfTextInfoRecordV2_0::getImageLength()const { return ossimString(theTextLength).toInt32(); } ossim_int32 ossimNitfTextInfoRecordV2_0::getTotalLength()const { return (getHeaderLength() + getImageLength()); } std::ostream& operator <<(std::ostream& out, const ossimNitfDataExtSegInfoRecordV2_0 &data) { return out << "theDataExtSegSubheaderLength: " << data.theDataExtSegSubheaderLength << std::endl << "theDataExtSegLength: " << data.theDataExtSegLength; } ossim_int32 ossimNitfDataExtSegInfoRecordV2_0::getHeaderLength()const { return ossimString(theDataExtSegSubheaderLength).toInt32(); } ossim_int32 ossimNitfDataExtSegInfoRecordV2_0::getImageLength()const { return ossimString(theDataExtSegLength).toInt32(); } ossim_int32 ossimNitfDataExtSegInfoRecordV2_0::getTotalLength()const { return (getHeaderLength() + getImageLength()); } std::ostream& operator <<(std::ostream& out, const ossimNitfResExtSegInfoRecordV2_0 &data) { return out << "theResExtSegSubheaderLength: " << data.theResExtSegSubheaderLength << std::endl << "theResExtSegLength: " << data.theResExtSegLength; } ossimNitfFileHeaderV2_0::ossimNitfFileHeaderV2_0() :ossimNitfFileHeaderV2_X() { clearFields(); } ossimNitfFileHeaderV2_0::~ossimNitfFileHeaderV2_0() { } bool ossimNitfFileHeaderV2_0::isValid()const { bool result = ossimNitfFileHeaderV2_X::isValid(); if(result) { } return result; } void ossimNitfFileHeaderV2_0::parseStream(ossim::istream& in) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfFileHeaderV2_0::parseStream: entered ......." << std::endl; } clearFields(); // identification and origination group in.read(theFileTypeVersion, 9); theHeaderSize+=9; in.read(theComplexityLevel, 2); theHeaderSize+=2; in.read(theSystemType, 4); theHeaderSize+=4; in.read(theOriginatingStationId, 10); theHeaderSize+=10; in.read(theDateTime, 14); theHeaderSize+=14; in.read(theFileTitle, 80); theHeaderSize+=80; // read security group in.read(theSecurityClassification, 1); theHeaderSize++; in.read(theCodewords, 40); theHeaderSize+=40; in.read(theControlAndHandling, 40); theHeaderSize+=40; in.read(theReleasingInstructions, 40); theHeaderSize+=40; in.read(theClassificationAuthority, 20); theHeaderSize+=20; in.read(theSecurityControlNumber, 20); theHeaderSize+=20; in.read(theSecurityDowngrade, 6); theHeaderSize+=6; if(ossimString(theSecurityDowngrade) == "999998") { in.read(theDowngradingEvent, 40); theHeaderSize+=40; } in.read(theCopyNumber, 5); theHeaderSize+=5; in.read(theNumberOfCopies, 5); theHeaderSize+=5; in.read(theEncryption, 1); theHeaderSize++; in.read(theOriginatorsName, 27); theHeaderSize+=27; in.read(theOriginatorsPhone, 18); theHeaderSize+=18; in.read(theFileLength, 12); theHeaderSize+=12; in.read(theHeaderLength, 6); theHeaderSize+=6; // image description group in.read(theNumberOfImageInfoRecords, 3); theHeaderSize+=3; readImageInfoRecords(in); // symbol description group in.read(theNumberOfSymbolInfoRecords, 3); theHeaderSize+=3; readSymbolInfoRecords(in); // label description group in.read(theNumberOfLabelInfoRecords, 3); theHeaderSize+=3; readLabelInfoRecords(in); // text file information group in.read(theNumberOfTextFileInfoRecords, 3); theHeaderSize+=3; readTextFileInfoRecords(in); // Data extension group in.read(theNumberOfDataExtSegInfoRecords, 3); theHeaderSize+=3; readDataExtSegInfoRecords(in); // Reserve Extension Segment group in.read(theNumberOfResExtSegInfoRecords, 3); theHeaderSize+=3; readResExtSegInfoRecords(in); in.read(theUserDefinedHeaderDataLength, 5); theHeaderSize+=5; theTagList.clear(); // only get the header overflow if there even exists // user defined data. ossim_int32 userDefinedHeaderLength = ossimString(theUserDefinedHeaderDataLength).toInt32(); ossimNitfTagInformation headerTag; std::streampos start = in.tellg(); std::streampos current = in.tellg(); theHeaderSize+=userDefinedHeaderLength; if(userDefinedHeaderLength > 0) { in.read(theUserDefinedHeaderOverflow, 3); current = in.tellg(); while((current - start) < userDefinedHeaderLength) { headerTag.parseStream(in); headerTag.setTagType("UDHD"); theTagList.push_back(headerTag); // in.ignore(headerTag.getTagLength()); // headerTag.clearFields(); //--- // We will check the stream here as there have been instances of // rpf's with bad stream offsets. //--- if (!in) { std::string e = "ossimNitfFileHeaderV2_0::parseStream stream error!"; throw ossimException(e); } current = in.tellg(); } } in.read(theExtendedHeaderDataLength, 5); theHeaderSize+=5; ossim_int32 extendedHeaderDataLength = ossimString(theExtendedHeaderDataLength).toInt32(); theHeaderSize+=extendedHeaderDataLength; start = in.tellg(); current = in.tellg(); // for now let's just ignore it if(extendedHeaderDataLength > 0) { in.read(theExtendedHeaderOverflow, 3); current = in.tellg(); while((current - start) < extendedHeaderDataLength) { headerTag.parseStream(in); headerTag.setTagType("XHD"); theTagList.push_back(headerTag); in.ignore(headerTag.getTagLength()); headerTag.clearFields(); current = in.tellg(); } } // this need to be re-thought initializeAllOffsets(); readOverflowTags(in); if(traceDebug()) { ossimNitfFileHeader::print( ossimNotify(ossimNotifyLevel_DEBUG) ); } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfFileHeaderV2_0::parseStream: Leaving......." << std::endl; } // initializeDisplayLevels(in); } void ossimNitfFileHeaderV2_0::readOverflowTags(ossim::istream& in) { ossim_int32 overflow = ossimString(theUserDefinedHeaderOverflow).toInt32(); if (overflow != 0) { ossimRefPtr des = getNewDataExtensionSegment(overflow-1, in); if (des.valid()) { const vector &desTags = des->getTagList(); for (vector::const_iterator iter = desTags.begin(); iter != desTags.end(); ++iter) { iter->setTagType("UDHD"); theTagList.push_back(*iter); } des = 0; } } overflow = ossimString(theExtendedHeaderOverflow).toInt32(); if (overflow != 0) { ossimRefPtr des = getNewDataExtensionSegment(overflow-1, in); if (des.valid()) { const vector &desTags = des->getTagList(); for (vector::const_iterator iter = desTags.begin(); iter != desTags.end(); ++iter) { iter->setTagType("XHD"); theTagList.push_back(*iter); } des = 0; } } } void ossimNitfFileHeaderV2_0::writeStream(ossim::ostream& out) { // identification and origination group out.write(theFileTypeVersion, 9); out.write(theComplexityLevel, 2); out.write(theSystemType, 4); out.write(theOriginatingStationId, 10); out.write(theDateTime, 14); out.write(theFileTitle, 80); // read security group out.write(theSecurityClassification, 1); out.write(theCodewords, 40); out.write(theControlAndHandling, 40); out.write(theReleasingInstructions, 40); out.write(theClassificationAuthority, 20); out.write(theSecurityControlNumber, 20); out.write(theSecurityDowngrade, 6); if(ossimString(theSecurityDowngrade) == "999998") { out.write(theDowngradingEvent, 40); } out.write(theCopyNumber, 5); out.write(theNumberOfCopies, 5); out.write(theEncryption, 1); out.write(theOriginatorsName, 27); out.write(theOriginatorsPhone, 18); out.write(theFileLength, 12); out.write(theHeaderLength, 6); ossim_uint32 idx = 0; { std::ostringstream outString; outString << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << theNitfImageInfoRecords.size(); out.write(outString.str().c_str(), 3); for(idx = 0; idx < theNitfImageInfoRecords.size(); ++idx) { out.write(theNitfImageInfoRecords[idx].theImageSubheaderLength, 6); out.write(theNitfImageInfoRecords[idx].theImageLength, 10); } } { std::ostringstream outString; outString << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << theNitfSymbolInfoRecords.size(); out.write(outString.str().c_str(), 3); for(idx = 0; idx < theNitfSymbolInfoRecords.size(); ++idx) { out.write(theNitfSymbolInfoRecords[idx].theSymbolSubheaderLength, 4); out.write(theNitfSymbolInfoRecords[idx].theSymbolLength, 6); } } { std::ostringstream outString; outString << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << theNitfLabelInfoRecords.size(); out.write(outString.str().c_str(), 3); for(idx = 0; idx < theNitfLabelInfoRecords.size(); ++idx) { out.write(theNitfLabelInfoRecords[idx].theLabelSubheaderLength, 4); out.write(theNitfLabelInfoRecords[idx].theLabelLength, 3); } } { std::ostringstream outString; outString << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << theNitfTextInfoRecords.size(); out.write(outString.str().c_str(), 3); for(idx = 0; idx < theNitfTextInfoRecords.size(); ++idx) { out.write(theNitfTextInfoRecords[idx].theTextSubheaderLength, 4); out.write(theNitfTextInfoRecords[idx].theTextLength, 5); } } { std::ostringstream outString; outString << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << theNitfDataExtSegInfoRecords.size(); out.write(outString.str().c_str(), 3); for(idx = 0; idx < theNitfDataExtSegInfoRecords.size(); ++idx) { out.write(theNitfDataExtSegInfoRecords[idx].theDataExtSegSubheaderLength, 4); out.write(theNitfDataExtSegInfoRecords[idx].theDataExtSegLength, 9); } } { std::ostringstream outString; outString << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << theNitfResExtSegInfoRecords.size(); out.write(outString.str().c_str(), 3); for(idx = 0; idx < theNitfResExtSegInfoRecords.size(); ++idx) { out.write(theNitfResExtSegInfoRecords[idx].theResExtSegSubheaderLength, 4); out.write(theNitfResExtSegInfoRecords[idx].theResExtSegLength, 7); } } out.write(theUserDefinedHeaderDataLength, 5); if(ossimString(theUserDefinedHeaderDataLength).toInt32() > 0) { out.write(theUserDefinedHeaderOverflow, 3); } ossim_uint32 totalLength = getTotalTagLength(); if(totalLength <= 99999) { std::ostringstream tempOut; tempOut << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << totalLength; memcpy(theExtendedHeaderDataLength, tempOut.str().c_str(), 5); out.write(theExtendedHeaderDataLength, 5); // for now we hard code te 000 for we do not currently support writing to the DES if the total tag length is // larger than supported // memset(theExtendedHeaderOverflow, '0', 3); if(totalLength > 0) { ossim_uint32 i = 0; out.write(theExtendedHeaderOverflow, 3); for(i = 0; i < theTagList.size(); ++i) { theTagList[i].writeStream(out); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimNitfFileHeaderV2_0::writeStream: Only support writing of total tag length < 99999" << std::endl; } } std::ostream& ossimNitfFileHeaderV2_0::print(std::ostream& out, const std::string& prefix) const { out << setiosflags(std::ios::left) << prefix << std::setw(24) << "FHDR:" << theFileTypeVersion << "\n" << prefix << std::setw(24) << "CLEVEL:" << theComplexityLevel << "\n" << prefix << std::setw(24) << "STYPE:" << theSystemType << "\n" << prefix << std::setw(24) << "OSTAID:" << theOriginatingStationId << "\n" << prefix << std::setw(24) << "FDT:" << theDateTime << "\n" << prefix << std::setw(24) << "FTITLE:" << theFileTitle << "\n" << prefix << std::setw(24) << "FSCLAS:" << theSecurityClassification << "\n" << prefix << std::setw(24) << "FSCODE:" << theCodewords << "\n" << prefix << std::setw(24) << "FSCTLH:" << theControlAndHandling << "\n" << prefix << std::setw(24) << "FSREL:" << theReleasingInstructions << "\n" << prefix << std::setw(24) << "FSCAUT:" << theClassificationAuthority << "\n" << prefix << std::setw(24) << "FSCTLN:" << theSecurityControlNumber << "\n" << prefix << std::setw(24) << "FSDWNG:" << theSecurityDowngrade << "\n" << prefix << std::setw(24) << "FSDEVT:" << theDowngradingEvent << "\n" << prefix << std::setw(24) << "FSCOP:" << theCopyNumber << "\n" << prefix << std::setw(24) << "FSCPYS:" << theNumberOfCopies << "\n" << prefix << std::setw(24) << "ENCRYP:" << theEncryption << "\n" << prefix << std::setw(24) << "ONAME:" << theOriginatorsName << "\n" << prefix << std::setw(24) << "OPHONE:" << theOriginatorsPhone << "\n" << prefix << std::setw(24) << "FL:" << theFileLength << "\n" << prefix << std::setw(24) << "HL:" << theHeaderLength << "\n" << prefix << std::setw(24) << "NUMI:" << theNumberOfImageInfoRecords << "\n"; ossim_uint32 index; for (index = 0; index < theNitfImageInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LISH"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfImageInfoRecords[index].theImageSubheaderLength << "\n"; tmpStr = "LI"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfImageInfoRecords[index].theImageLength << "\n"; } out << prefix << std::setw(24) << "NUMS:" << theNumberOfSymbolInfoRecords << "\n"; for (index = 0; index < theNitfSymbolInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LSSH"; tmpStr += os.str(); out << tmpStr << theNitfSymbolInfoRecords[index].theSymbolSubheaderLength << "\n"; tmpStr = "LS"; tmpStr += os.str(); out << tmpStr << theNitfSymbolInfoRecords[index].theSymbolLength << "\n"; } out << prefix << std::setw(24) << "NUML:" << theNumberOfLabelInfoRecords << "\n"; for (index = 0; index < theNitfLabelInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LLSH"; tmpStr += os.str(); out << tmpStr << theNitfLabelInfoRecords[index].theLabelSubheaderLength << "\n"; tmpStr = "LL"; tmpStr += os.str(); out << tmpStr << theNitfLabelInfoRecords[index].theLabelLength << "\n"; } out << prefix << std::setw(24) << "NUMT:" << theNumberOfTextFileInfoRecords << "\n"; for (index = 0; index < theNitfTextInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LTSH"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfTextInfoRecords[index].theTextSubheaderLength << "\n"; tmpStr = "LT"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfTextInfoRecords[index].theTextLength<< "\n"; } out << prefix << std::setw(24) << "NUMDES:" << theNumberOfDataExtSegInfoRecords << "\n"; for (index = 0; index < theNitfDataExtSegInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LDSH"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfDataExtSegInfoRecords[index].theDataExtSegSubheaderLength << "\n"; tmpStr = "LD"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfDataExtSegInfoRecords[index].theDataExtSegLength << "\n"; } out << prefix << std::setw(24) << "NUMRES:" << theNumberOfResExtSegInfoRecords << "\n"; for (index = 0; index < theNitfResExtSegInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LRSH"; tmpStr += os.str(); out << tmpStr << theNitfResExtSegInfoRecords[index].theResExtSegSubheaderLength << "\n"; tmpStr = "LR"; tmpStr += os.str(); out << tmpStr << theNitfResExtSegInfoRecords[index].theResExtSegLength << "\n"; } out << prefix << std::setw(24) << "UDHDL:" << theUserDefinedHeaderDataLength << "\n" << prefix << std::setw(24) << "UDHOFL:" << theUserDefinedHeaderOverflow << "\n" << prefix << std::setw(24) << "XHDL:" << theExtendedHeaderDataLength << "\n"; return ossimNitfFileHeader::print(out, prefix); } bool ossimNitfFileHeaderV2_0::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = ossimNitfFileHeaderV2_X::saveState(kwl, prefix); if(result) { kwl.add(prefix, "FSCODE",theCodewords); kwl.add(prefix, "FSCTLH",theControlAndHandling); kwl.add(prefix, "FSREL",theReleasingInstructions); kwl.add(prefix, "FSCAUT",theClassificationAuthority); kwl.add(prefix, "FSCTLN",theSecurityControlNumber); kwl.add(prefix, "FSDWNG",theSecurityDowngrade); kwl.add(prefix, "FSDEVT",theDowngradingEvent); kwl.add(prefix, "ONAME",theOriginatorsName); kwl.add(prefix, "OPHONE",theOriginatorsPhone); kwl.add(prefix, "FL",theFileLength); kwl.add(prefix, "HL",theHeaderLength); kwl.add(prefix, "NUMI",theNumberOfImageInfoRecords); kwl.add(prefix, "UDHDL",theUserDefinedHeaderDataLength); kwl.add(prefix, "UDHOFL",theUserDefinedHeaderDataLength); kwl.add(prefix, "XHDL",theExtendedHeaderDataLength); std::ostringstream out; ossim_uint32 index; for (index = 0; index < theNitfImageInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LISH"; tmpStr += os.str(); out << tmpStr << theNitfImageInfoRecords[index].theImageSubheaderLength << "\n"; tmpStr = "LI"; tmpStr += os.str(); out << tmpStr << theNitfImageInfoRecords[index].theImageLength << "\n"; } out <<"NUMS:" << theNumberOfSymbolInfoRecords << "\n"; for (index = 0; index < theNitfSymbolInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LSSH"; tmpStr += os.str(); out << tmpStr << theNitfSymbolInfoRecords[index].theSymbolSubheaderLength << "\n"; tmpStr = "LS"; tmpStr += os.str(); out << tmpStr << theNitfSymbolInfoRecords[index].theSymbolLength << "\n"; } out << "NUML:" << theNumberOfLabelInfoRecords << "\n"; for (index = 0; index < theNitfLabelInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LLSH"; tmpStr += os.str(); out << tmpStr << theNitfLabelInfoRecords[index].theLabelSubheaderLength << "\n"; tmpStr = "LL"; tmpStr += os.str(); out << tmpStr << theNitfLabelInfoRecords[index].theLabelLength << "\n"; } out << "NUMT:" << theNumberOfTextFileInfoRecords << "\n"; for (index = 0; index < theNitfTextInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LTSH"; tmpStr += os.str(); out << tmpStr << theNitfTextInfoRecords[index].theTextSubheaderLength << "\n"; tmpStr = "LT"; tmpStr += os.str(); out << tmpStr << theNitfTextInfoRecords[index].theTextLength<< "\n"; } out << "NUMDES:" << theNumberOfDataExtSegInfoRecords << "\n"; for (index = 0; index < theNitfDataExtSegInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LDSH"; tmpStr += os.str(); out << tmpStr << theNitfDataExtSegInfoRecords[index].theDataExtSegSubheaderLength << "\n"; tmpStr = "LD"; tmpStr += os.str(); out << tmpStr << theNitfDataExtSegInfoRecords[index].theDataExtSegLength << "\n"; } out << "NUMRES:" << theNumberOfResExtSegInfoRecords << "\n"; for (index = 0; index < theNitfResExtSegInfoRecords.size(); ++index) { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (index+1) << ":"; ossimString tmpStr = "LRSH"; tmpStr += os.str(); out << tmpStr << theNitfResExtSegInfoRecords[index].theResExtSegSubheaderLength << "\n"; tmpStr = "LR"; tmpStr += os.str(); out << tmpStr << theNitfResExtSegInfoRecords[index].theResExtSegLength << "\n"; } { std::istringstream in(out.str()); ossimKeywordlist tempKwl; if(tempKwl.parseStream(in)) { result = true; kwl.add(prefix, tempKwl); } } } return result; } ossimDrect ossimNitfFileHeaderV2_0::getImageRect()const { return theImageRect; } void ossimNitfFileHeaderV2_0::addImageInfoRecord(const ossimNitfImageInfoRecordV2_0& recordInfo) { theNitfImageInfoRecords.push_back(recordInfo); setNumberOfImageInfoRecords(theNitfImageInfoRecords.size()); } void ossimNitfFileHeaderV2_0::replaceImageInfoRecord(ossim_uint32 i, const ossimNitfImageInfoRecordV2_0& recordInfo) { theNitfImageInfoRecords[i]=recordInfo; } ossimNitfImageHeader* ossimNitfFileHeaderV2_0::getNewImageHeader(ossim_uint32 imageNumber, ossim::istream& in)const { ossimNitfImageHeader *result = 0; if( (getNumberOfImages() > 0) && (imageNumber < theImageOffsetList.size()) ) { result = allocateImageHeader(); in.seekg(theImageOffsetList[imageNumber].theImageHeaderOffset, std::ios::beg); result->parseStream(in); } else { #if 0 ossimNotify(ossimNotifyLevel_FATAL) << "ossimNitfFileHeaderV2_0::getNewImageHeader ERROR:" << "\nNo images in file or image number (" << imageNumber << ") is out of range!\n"; #endif } return result; } ossimNitfSymbolHeader *ossimNitfFileHeaderV2_0::getNewSymbolHeader( ossim_uint32 symbolNumber, ossim::istream& in)const { ossimNitfSymbolHeader *result = 0; if( (getNumberOfSymbols() > 0) && (symbolNumber < theSymbolOffsetList.size()) ) { result = allocateSymbolHeader(); in.seekg(theSymbolOffsetList[symbolNumber].theSymbolHeaderOffset, std::ios::beg); result->parseStream(in); } return result; } ossimNitfLabelHeader *ossimNitfFileHeaderV2_0::getNewLabelHeader( ossim_uint32 labelNumber, ossim::istream& in)const { ossimNitfLabelHeader *result = 0; if( (getNumberOfLabels() > 0) && (labelNumber < theLabelOffsetList.size()) ) { result = allocateLabelHeader(); in.seekg(theLabelOffsetList[labelNumber].theLabelHeaderOffset, std::ios::beg); result->parseStream(in); } return result; } ossimNitfTextHeader *ossimNitfFileHeaderV2_0::getNewTextHeader( ossim_uint32 textNumber, ossim::istream& in)const { ossimNitfTextHeader *result = 0; if( (getNumberOfTextSegments() > 0) && (textNumber < theTextOffsetList.size()) ) { result = allocateTextHeader(); in.seekg(theTextOffsetList[textNumber].theTextHeaderOffset, std::ios::beg); result->parseStream(in); } return result; } ossimNitfDataExtensionSegment* ossimNitfFileHeaderV2_0::getNewDataExtensionSegment(ossim_int32 dataExtNumber, ossim::istream& in)const { ossimNitfDataExtensionSegment *result = 0; if((getNumberOfDataExtSegments() > 0) && (dataExtNumber < (ossim_int32)theNitfDataExtSegInfoRecords.size()) && (dataExtNumber >= 0)) { result = allocateDataExtSegment(); in.seekg(theDataExtSegOffsetList[dataExtNumber].theDataExtSegHeaderOffset, std::ios::beg); result->parseStream(in, theNitfDataExtSegInfoRecords[dataExtNumber].getImageLength()); } return result; } void ossimNitfFileHeaderV2_0::initializeDisplayLevels(ossim::istream& in) { // we will need to temporarily save the get pointer since // initializeDisplayLevels changes it. std::streampos saveTheGetPointer = in.tellg(); std::vector::iterator imageOffsetList = theImageOffsetList.begin(); // allocate temporary space to store image headers ossimNitfImageHeader* imageHeader = allocateImageHeader(); // clear the list theDisplayInformationList.clear(); theImageRect = ossimDrect(0,0,0,0); if(!imageHeader) { return; } ossim_uint32 idx = 0; while(imageOffsetList != theImageOffsetList.end()) { // position the get pointer in the input // stream to the start of the image header in.seekg((*imageOffsetList).theImageHeaderOffset, std::ios::beg); // get the data imageHeader->parseStream(in); // create a union of rects. The result should be the image rect. ossimDrect tempRect = imageHeader->getImageRect(); if((tempRect.width() > 1) && (tempRect.height() > 1)) { theImageRect = theImageRect.combine(tempRect); } insertIntoDisplayInfoList(ossimNitfDisplayInfo(ossimString("IM"), imageHeader->getDisplayLevel(), idx)); ++imageOffsetList; ++idx; } delete imageHeader; imageHeader = 0; // finally we reset the saved get state back // to its original position in.seekg(saveTheGetPointer, std::ios::beg); } void ossimNitfFileHeaderV2_0::insertIntoDisplayInfoList(const ossimNitfDisplayInfo &displayInformation) { std::vector::iterator displayList = theDisplayInformationList.begin(); while(displayList != theDisplayInformationList.end()) { if(displayInformation.theDisplayLevel < (*displayList).theDisplayLevel) { theDisplayInformationList.insert(displayList, displayInformation); return; } ++displayList; } // If we get here it means it's larger than all others // and we push onto the end theDisplayInformationList.push_back(displayInformation); } void ossimNitfFileHeaderV2_0::initializeAllOffsets() { // this will be a running tally ossim_uint64 tally = theHeaderSize; ossim_uint32 idx = 0; // clear out all offset inforamtion and begin populating them theImageOffsetList.clear(); theSymbolOffsetList.clear(); theLabelOffsetList.clear(); theLabelOffsetList.clear(); for(idx = 0; idx < theNitfImageInfoRecords.size(); ++idx) { theImageOffsetList.push_back(ossimNitfImageOffsetInformation(tally, tally + theNitfImageInfoRecords[idx].getHeaderLength())); tally += theNitfImageInfoRecords[idx].getTotalLength(); } for(idx = 0; idx < theNitfSymbolInfoRecords.size(); ++idx) { theSymbolOffsetList.push_back(ossimNitfSymbolOffsetInformation(tally, tally + theNitfSymbolInfoRecords[idx].getHeaderLength())); tally += theNitfSymbolInfoRecords[idx].getTotalLength(); } for(idx = 0; idx < theNitfLabelInfoRecords.size(); ++idx) { theLabelOffsetList.push_back(ossimNitfLabelOffsetInformation(tally, tally + theNitfLabelInfoRecords[idx].getHeaderLength())); tally += theNitfLabelInfoRecords[idx].getTotalLength(); } for(idx = 0; idx < theNitfTextInfoRecords.size(); ++idx) { theTextOffsetList.push_back(ossimNitfTextOffsetInformation(tally, tally + theNitfTextInfoRecords[idx].getHeaderLength())); tally += theNitfTextInfoRecords[idx].getTotalLength(); } for(idx = 0; idx < theNitfDataExtSegInfoRecords.size(); ++idx) { theDataExtSegOffsetList.push_back(ossimNitfDataExtSegOffsetInformation(tally, tally + theNitfDataExtSegInfoRecords[idx].getHeaderLength())); tally += theNitfDataExtSegInfoRecords[idx].getTotalLength(); } } ossimNitfImageHeader *ossimNitfFileHeaderV2_0::allocateImageHeader()const { return new ossimNitfImageHeaderV2_0; } ossimNitfSymbolHeader *ossimNitfFileHeaderV2_0::allocateSymbolHeader()const { return new ossimNitfSymbolHeaderV2_0; } ossimNitfLabelHeader *ossimNitfFileHeaderV2_0::allocateLabelHeader()const { return new ossimNitfLabelHeaderV2_0; } ossimNitfTextHeader *ossimNitfFileHeaderV2_0::allocateTextHeader()const { return new ossimNitfTextHeaderV2_0; } ossimNitfDataExtensionSegment* ossimNitfFileHeaderV2_0::allocateDataExtSegment()const { return new ossimNitfDataExtensionSegmentV2_0(); } bool ossimNitfFileHeaderV2_0::isEncrypted()const { return (theEncryption[0] == '1'); } ossim_int32 ossimNitfFileHeaderV2_0::getNumberOfImages()const { return (ossim_int32)theNitfImageInfoRecords.size(); } ossim_int32 ossimNitfFileHeaderV2_0::getNumberOfLabels()const { return ((ossim_int32)theNitfLabelInfoRecords.size()); } ossim_int32 ossimNitfFileHeaderV2_0::getNumberOfSymbols()const { return ((ossim_int32)theNitfSymbolInfoRecords.size()); } ossim_int32 ossimNitfFileHeaderV2_0::getNumberOfGraphics()const { return 0; } ossim_int32 ossimNitfFileHeaderV2_0::getNumberOfTextSegments()const { return (ossim_int32)theNitfTextInfoRecords.size(); } ossim_int32 ossimNitfFileHeaderV2_0::getNumberOfDataExtSegments()const { return (ossim_int32)theNitfDataExtSegInfoRecords.size(); } ossim_int32 ossimNitfFileHeaderV2_0::getHeaderSize()const { return theHeaderSize; } ossim_int32 ossimNitfFileHeaderV2_0::getNumberOfReservedExtSegments()const { return theNitfResExtSegInfoRecords.size(); } ossim_int64 ossimNitfFileHeaderV2_0::getFileSize()const { ossimString temp = theFileLength; if(temp == "999999999999") { return -1; } else { return temp.toInt64(); } } const char* ossimNitfFileHeaderV2_0::getVersion()const { return &theFileTypeVersion[4]; } const char* ossimNitfFileHeaderV2_0::getDateTime()const { return theDateTime; } ossimString ossimNitfFileHeaderV2_0::getSecurityClassification()const { return theSecurityClassification; } void ossimNitfFileHeaderV2_0::clearFields() { theDisplayInformationList.clear(); theImageOffsetList.clear(); theSymbolOffsetList.clear(); theLabelOffsetList.clear(); theTextOffsetList.clear(); theDataExtSegOffsetList.clear(); theNitfSymbolInfoRecords.clear(); theNitfLabelInfoRecords.clear(); theNitfTextInfoRecords.clear(); theNitfDataExtSegInfoRecords.clear(); theNitfResExtSegInfoRecords.clear(); theFilename = ""; memcpy(theFileTypeVersion, "NITF02.00", 9); memset(theComplexityLevel, ' ', 2); memset(theSystemType, ' ', 4); memset(theOriginatingStationId, ' ', 10); memset(theDateTime, ' ', 14); memset(theFileTitle, ' ', 80); memset(theSecurityClassification, ' ', 1); memset(theCodewords, ' ', 40); memset(theControlAndHandling, ' ', 40); memset(theReleasingInstructions, ' ', 40); memset(theClassificationAuthority, ' ', 20); memset(theSecurityControlNumber, ' ', 20); memset(theSecurityDowngrade, ' ', 6); memset(theDowngradingEvent, ' ', 40); memset(theCopyNumber, ' ', 5); memset(theNumberOfCopies, ' ', 5); memset(theEncryption, ' ', 1); memset(theOriginatorsName, ' ', 27); memset(theOriginatorsPhone, ' ', 18); memset(theFileLength, ' ', 12); memset(theHeaderLength, ' ', 6); memset(theNumberOfImageInfoRecords, ' ', 3); memset(theNumberOfSymbolInfoRecords, ' ', 3); memset(theNumberOfLabelInfoRecords, ' ', 3); memset(theNumberOfTextFileInfoRecords, ' ', 3); memset(theNumberOfDataExtSegInfoRecords, ' ', 3); memset(theNumberOfResExtSegInfoRecords, ' ', 3); memset(theUserDefinedHeaderDataLength, '0', 5); memset(theUserDefinedHeaderOverflow, ' ', 3); memset(theExtendedHeaderDataLength, '0', 5); memset(theExtendedHeaderOverflow, ' ', 3); theFileTypeVersion[9] = '\0'; theComplexityLevel[2] = '\0'; theSystemType[4] = '\0'; theOriginatingStationId[10] = '\0'; theDateTime[14] = '\0'; theFileTitle[80] = '\0'; theSecurityClassification[1] = '\0'; theCodewords[40] = '\0'; theControlAndHandling[40] = '\0'; theReleasingInstructions[40] = '\0'; theClassificationAuthority[20] = '\0'; theSecurityControlNumber[20] = '\0'; theSecurityDowngrade[6] = '\0'; theDowngradingEvent[40] = '\0'; theCopyNumber[5] = '\0'; theNumberOfCopies[5] = '\0'; theEncryption[1] = '\0'; theOriginatorsName[27] = '\0'; theOriginatorsPhone[18] = '\0'; theFileLength[12] = '\0'; theHeaderLength[6] = '\0'; theNumberOfImageInfoRecords[3] = '\0'; theNumberOfSymbolInfoRecords[3] = '\0'; theNumberOfLabelInfoRecords[3] = '\0'; theNumberOfTextFileInfoRecords[3] = '\0'; theNumberOfDataExtSegInfoRecords[3] = '\0'; theNumberOfResExtSegInfoRecords[3] = '\0'; theUserDefinedHeaderDataLength[5] = '\0'; theUserDefinedHeaderOverflow[3] = '\0'; theExtendedHeaderDataLength[5] = '\0'; theExtendedHeaderOverflow[3] = '\0'; theHeaderSize = 0; } void ossimNitfFileHeaderV2_0::setNumberOfImageInfoRecords(ossim_uint64 num) { if (num < 1000) { std::ostringstream out; out << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << num; memcpy(theNumberOfImageInfoRecords, out.str().c_str(), 3); } else { std::string s = "ossimNitfFileHeaderV2_0::setNumberOfImageInfoRecords:"; s += " ERROR\nExceeded max image info number of 999!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } } void ossimNitfFileHeaderV2_0::readImageInfoRecords(ossim::istream& in) { ossim_int32 numberOfImages = ossimString(theNumberOfImageInfoRecords).toInt32(); ossim_int32 index; theNitfImageInfoRecords.clear(); for(index=0; index < numberOfImages; index++) { ossimNitfImageInfoRecordV2_0 temp; in.read(temp.theImageSubheaderLength, 6); in.read(temp.theImageLength, 10); theHeaderSize+=16; temp.theImageSubheaderLength[6] = '\0'; temp.theImageLength[10] = '\0'; theNitfImageInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_0::readSymbolInfoRecords(ossim::istream& in) { ossim_int32 numberOfSymbols = ossimString(theNumberOfSymbolInfoRecords).toInt32(); ossim_int32 index; theNitfSymbolInfoRecords.clear(); for(index=0; index < numberOfSymbols; index++) { ossimNitfSymbolInfoRecordV2_0 temp; in.read(temp.theSymbolSubheaderLength, 4); in.read(temp.theSymbolLength, 6); theHeaderSize+=10; temp.theSymbolSubheaderLength[4] = '\0'; temp.theSymbolLength[6] = '\0'; theNitfSymbolInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_0::readLabelInfoRecords(ossim::istream& in) { ossim_int32 numberOfLabels = ossimString(theNumberOfLabelInfoRecords).toInt32(); ossim_int32 index; theNitfLabelInfoRecords.clear(); for(index=0; index < numberOfLabels; index++) { ossimNitfLabelInfoRecordV2_0 temp; in.read(temp.theLabelSubheaderLength, 4); in.read(temp.theLabelLength, 3); theHeaderSize+=7; temp.theLabelSubheaderLength[4] = '\0'; temp.theLabelLength[3] = '\0'; theNitfLabelInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_0::readTextFileInfoRecords(ossim::istream& in) { ossim_int32 numberOfTextFiles = ossimString(theNumberOfTextFileInfoRecords).toInt32(); ossim_int32 index; theNitfTextInfoRecords.clear(); for(index=0; index < numberOfTextFiles; index++) { ossimNitfTextInfoRecordV2_0 temp; in.read(temp.theTextSubheaderLength, 4); in.read(temp.theTextLength, 5); theHeaderSize+=9; temp.theTextSubheaderLength[4] = '\0'; temp.theTextLength[5] = '\0'; theNitfTextInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_0::readDataExtSegInfoRecords(ossim::istream& in) { ossim_int32 numberOfDataExtSegs = ossimString(theNumberOfDataExtSegInfoRecords).toInt32(); ossim_int32 index; theNitfDataExtSegInfoRecords.clear(); for(index=0; index < numberOfDataExtSegs; index++) { ossimNitfDataExtSegInfoRecordV2_0 temp; in.read(temp.theDataExtSegSubheaderLength, 4); in.read(temp.theDataExtSegLength, 9); theHeaderSize+=13; temp.theDataExtSegSubheaderLength[4] = '\0'; temp.theDataExtSegLength[9] = '\0'; theNitfDataExtSegInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_0::readResExtSegInfoRecords(ossim::istream& in) { ossim_int32 numberOfResExtSegs = ossimString(theNumberOfResExtSegInfoRecords).toInt32(); ossim_int32 index; theNitfResExtSegInfoRecords.clear(); for(index=0; index < numberOfResExtSegs; index++) { ossimNitfResExtSegInfoRecordV2_0 temp; in.read(temp.theResExtSegSubheaderLength, 4); in.read(temp.theResExtSegLength, 7); theHeaderSize+=11; temp.theResExtSegSubheaderLength[4] = '\0'; temp.theResExtSegLength[7] = '\0'; theNitfResExtSegInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_0::setComplianceLevel(const ossimString& complianceLevel) { ossimNitfCommon::setField(theComplexityLevel, complianceLevel, 2); } void ossimNitfFileHeaderV2_0::setCodeWords(const ossimString& codeWords) { ossimNitfCommon::setField(theCodewords, codeWords, 40); } void ossimNitfFileHeaderV2_0::setControlAndHandling(const ossimString& controlAndHandling) { ossimNitfCommon::setField(theControlAndHandling, controlAndHandling, 40); } void ossimNitfFileHeaderV2_0::setReleasingInstructions(const ossimString& releasingInstructions) { ossimNitfCommon::setField(theReleasingInstructions, releasingInstructions, 40); } void ossimNitfFileHeaderV2_0::setClassificationAuthority(const ossimString& classAuth) { ossimNitfCommon::setField(theClassificationAuthority, classAuth, 20); } void ossimNitfFileHeaderV2_0::setSecurityControlNumber(const ossimString& controlNo) { ossimNitfCommon::setField(theSecurityControlNumber, controlNo, 20); } void ossimNitfFileHeaderV2_0::setOriginatorsName(const ossimString& originatorName) { ossimNitfCommon::setField(theOriginatorsName, originatorName, 27); } void ossimNitfFileHeaderV2_0::setOriginatorsPhone(const ossimString& originatorPhone) { ossimNitfCommon::setField(theOriginatorsPhone, originatorPhone, 18); } void ossimNitfFileHeaderV2_0::setSecurityDowngrade(const ossimString& securityDowngrade) { ossimNitfCommon::setField(theSecurityDowngrade, securityDowngrade, 6); } void ossimNitfFileHeaderV2_0::setDowngradingEvent(const ossimString& downgradeEvent) { ossimNitfCommon::setField(theDowngradingEvent, downgradeEvent, 40); } void ossimNitfFileHeaderV2_0::setFileLength(ossim_uint64 fileLength) { std::ostringstream out; out << std::setw(12) << std::setfill('0') << std::setiosflags(ios::right) << fileLength; memcpy(theFileLength, out.str().c_str(), 12); } void ossimNitfFileHeaderV2_0::setHeaderLength(ossim_uint64 headerLength) { std::ostringstream out; out << std::setw(6) << std::setfill('0') << std::setiosflags(ios::right) << headerLength; memcpy(theHeaderLength, out.str().c_str(), 6); } ossimString ossimNitfFileHeaderV2_0::getComplianceLevel()const { return theComplexityLevel; } ossimString ossimNitfFileHeaderV2_0::getSecurityDowngrade()const { return theSecurityDowngrade; } ossimString ossimNitfFileHeaderV2_0::getDowngradingEvent()const { return theDowngradingEvent; } ossimString ossimNitfFileHeaderV2_0::getCodeWords()const { return theCodewords; } ossimString ossimNitfFileHeaderV2_0::getControlAndHandling()const { return theControlAndHandling; } ossimString ossimNitfFileHeaderV2_0::getReleasingInstructions()const { return theReleasingInstructions; } ossimString ossimNitfFileHeaderV2_0::getClassificationAuthority()const { return theClassificationAuthority; } ossimString ossimNitfFileHeaderV2_0::getSecurityControlNumber()const { return theSecurityControlNumber; } ossimString ossimNitfFileHeaderV2_0::getOriginatorsName()const { return theOriginatorsName; } ossimString ossimNitfFileHeaderV2_0::getOriginatorsPhone()const { return theOriginatorsPhone; } void ossimNitfFileHeaderV2_0::setProperty(ossimRefPtr property) { const ossimString& name = property->getName(); if(name == CLEVEL_KW) { setComplianceLevel(property->valueToString()); } else if(name == FSDWNG_KW) { setSecurityDowngrade(property->valueToString()); } else if(name == FSDEVT_KW) { setDowngradingEvent(property->valueToString()); } else if(name == ONAME_KW) { setOriginatorsName(property->valueToString()); } else if(name == OPHONE_KW) { setOriginatorsPhone(property->valueToString()); } else { ossimNitfFileHeaderV2_X::setProperty(property); } } ossimRefPtr ossimNitfFileHeaderV2_0::getProperty(const ossimString& name)const { ossimProperty* property = 0; if(name == CLEVEL_KW) { property = new ossimStringProperty(name, ossimString(theComplexityLevel).trim()); } else if(name == FSDWNG_KW) { property = new ossimStringProperty(name, ossimString(theSecurityDowngrade).trim()); } else if(name == FSDEVT_KW) { property = new ossimStringProperty(name, ossimString(theDowngradingEvent).trim()); } else if(name == ONAME_KW) { property = new ossimStringProperty(name, ossimString(theOriginatorsName).trim()); } else if(name == OPHONE_KW) { property = new ossimStringProperty(name, ossimString(theOriginatorsPhone).trim()); } else { return ossimNitfFileHeaderV2_X::getProperty(name); } return property; } void ossimNitfFileHeaderV2_0::getPropertyNames(std::vector& propertyNames)const { ossimNitfFileHeaderV2_X::getPropertyNames(propertyNames); propertyNames.push_back(CLEVEL_KW); propertyNames.push_back(STYPE_KW); propertyNames.push_back(OSTAID_KW); propertyNames.push_back(FDT_KW); propertyNames.push_back(FTITLE_KW); propertyNames.push_back(FSCLAS_KW); propertyNames.push_back(FSCODE_KW); propertyNames.push_back(FSCTLH_KW); propertyNames.push_back(FSREL_KW); propertyNames.push_back(FSCAUT_KW); propertyNames.push_back(FSCTLN_KW); propertyNames.push_back(FSCOP_KW); propertyNames.push_back(FSCPYS_KW); propertyNames.push_back(ENCRYP_KW); propertyNames.push_back(ONAME_KW); propertyNames.push_back(OPHONE_KW); } ossim-Miami-2.9.1/src/support_data/ossimNitfFileHeaderV2_1.cpp000066400000000000000000001745661352751253100242520ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include // ??? drb #include #include #include #include // for memset using namespace std; RTTI_DEF1(ossimNitfFileHeaderV2_1, "ossimNitfFileHeaderV2_1", ossimNitfFileHeaderV2_X) const ossimString ossimNitfFileHeaderV2_1::FSCLSY_KW = "FSCLSY"; const ossimString ossimNitfFileHeaderV2_1::FSDCTP_KW = "FSDCTP"; const ossimString ossimNitfFileHeaderV2_1::FSDCDT_KW = "FSDCDT"; const ossimString ossimNitfFileHeaderV2_1::FSDCXM_KW = "FSDCXM"; const ossimString ossimNitfFileHeaderV2_1::FSDG_KW = "FSDG"; const ossimString ossimNitfFileHeaderV2_1::FSDGDT_KW = "FSDGDT"; const ossimString ossimNitfFileHeaderV2_1::FSCLTX_KW = "FSCLTX"; const ossimString ossimNitfFileHeaderV2_1::FSCATP_KW = "FSCATP"; const ossimString ossimNitfFileHeaderV2_1::FSCRSN_KW = "FSCRSN"; const ossimString ossimNitfFileHeaderV2_1::FSSRDT_KW = "FSSRDT"; const ossimString ossimNitfFileHeaderV2_1::FBKGC_KW = "FBKGC"; const ossimString FL_KW = "FL"; const ossimString HL_KW = "HL"; const ossimString NUMI_KW = "NUMI"; static const ossimTrace traceDebug(ossimString("ossimNitfFileHeaderV2_1:debug")); std::ostream& operator <<(std::ostream& out, const ossimNitfImageInfoRecordV2_1 &data) { return out << "theImageSubheaderLength: " << data.theImageSubheaderLength << "\ntheImageLength: " << data.theImageLength << std::endl; } ossim_uint64 ossimNitfImageInfoRecordV2_1::getHeaderLength()const { return ossimString(theImageSubheaderLength).toUInt64(); } ossim_uint64 ossimNitfImageInfoRecordV2_1::getImageLength()const { return ossimString(theImageLength).toUInt64(); } ossim_uint64 ossimNitfImageInfoRecordV2_1::getTotalLength()const { return (getHeaderLength() + getImageLength()); } std::ostream& operator <<(std::ostream& out, const ossimNitfGraphicInfoRecordV2_1 &data) { return out << "theGraphicSubheaderLength: " << data.theGraphicSubheaderLength << "\ntheGraphicLength: " << data.theGraphicLength << std::endl; } std::ostream& operator <<(std::ostream& out, const ossimNitfTextFileInfoRecordV2_1 &data) { return out << "theTextFileSubheaderLength: " << data.theTextFileSubheaderLength << "\ntheTextFileLength: " << data.theTextFileLength << std::endl; } ossim_uint64 ossimNitfGraphicInfoRecordV2_1::getHeaderLength()const { return ossimString(theGraphicSubheaderLength).toUInt64(); } ossim_uint64 ossimNitfGraphicInfoRecordV2_1::getGraphicLength()const { return ossimString(theGraphicLength).toUInt64(); } ossim_uint64 ossimNitfGraphicInfoRecordV2_1::getTotalLength()const { return getGraphicLength() + getHeaderLength(); } void ossimNitfTextFileInfoRecordV2_1::setSubheaderLength(ossim_uint64 length) { std::ostringstream out; out << std::setw(4) << std::setfill('0') << std::setiosflags(ios::right) << length; memcpy(theTextFileSubheaderLength, out.str().c_str(), 4); theTextFileSubheaderLength[4] = '\0'; } void ossimNitfTextFileInfoRecordV2_1::setTextLength(ossim_uint64 length) { std::ostringstream out; out << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << length; memcpy(theTextFileLength, out.str().c_str(), 5); theTextFileLength[5] = '\0'; } ossim_uint64 ossimNitfTextFileInfoRecordV2_1::getHeaderLength()const { return ossimString(theTextFileSubheaderLength).toUInt64(); } ossim_uint64 ossimNitfTextFileInfoRecordV2_1::getTextLength()const { return ossimString(theTextFileLength).toUInt64(); } ossim_uint64 ossimNitfTextFileInfoRecordV2_1::getTotalLength()const { return (getHeaderLength() + getTextLength()); } std::ostream& operator <<(std::ostream& out, const ossimNitfDataExtSegInfoRecordV2_1 &data) { return out << "theDataExtSegSubheaderLength: " << data.theDataExtSegSubheaderLength << "\ntheDataExtSegLength: " << data.theDataExtSegLength << std::endl; } ossim_uint64 ossimNitfDataExtSegInfoRecordV2_1::getHeaderLength()const { return ossimString(theDataExtSegSubheaderLength).toUInt64(); } ossim_uint64 ossimNitfDataExtSegInfoRecordV2_1::getDataExtSegLength()const { return ossimString(theDataExtSegLength).toUInt64(); } ossim_uint64 ossimNitfDataExtSegInfoRecordV2_1::getTotalLength()const { return getDataExtSegLength() + getHeaderLength(); } std::ostream& operator <<(std::ostream& out, const ossimNitfResExtSegInfoRecordV2_1 &data) { return out << "theResExtSegSubheaderLength: " << data.theResExtSegSubheaderLength << "\ntheResExtSegLength: " << data.theResExtSegLength << std::endl; } ossim_uint64 ossimNitfResExtSegInfoRecordV2_1::getHeaderLength()const { return ossimString(theResExtSegSubheaderLength).toUInt64(); } ossim_uint64 ossimNitfResExtSegInfoRecordV2_1::getResExtSegLength()const { return ossimString(theResExtSegLength).toUInt64(); } ossim_uint64 ossimNitfResExtSegInfoRecordV2_1::getTotalLength()const { return getResExtSegLength() + getHeaderLength(); } void ossimNitfImageInfoRecordV2_1::setSubheaderLength(ossim_uint32 length) { std::ostringstream out; out << std::setw(6) << std::setfill('0') << std::setiosflags(ios::right) << length; memcpy(theImageSubheaderLength, out.str().c_str(), 6); theImageSubheaderLength[6] = '\0'; } void ossimNitfImageInfoRecordV2_1::setImageLength(ossim_uint64 length) { std::ostringstream out; out << std::setw(10) << std::setfill('0') << std::setiosflags(ios::right) << length; memcpy(theImageLength, out.str().c_str(), 10); theImageLength[10] = '\0'; } // ossimNitfFileHeaderV2_1::ossimNitfFileHeaderV2_1() :ossimNitfFileHeaderV2_X() { clearFields(); } ossimNitfFileHeaderV2_1::~ossimNitfFileHeaderV2_1() { } void ossimNitfFileHeaderV2_1::parseStream(ossim::istream& in) { clearFields(); // identification and origination group in.read(theFileTypeVersion, 9); theHeaderSize += 9; in.read(theComplexityLevel, 2); theHeaderSize += 2; in.read(theSystemType, 4); theHeaderSize += 4; in.read(theOriginatingStationId, 10); theHeaderSize += 10; in.read(theDateTime, 14); theHeaderSize += 14; in.read(theFileTitle, 80); theHeaderSize += 80; // read security group in.read(theSecurityClassification, 1); theHeaderSize ++; in.read(theSecurityClassificationSys, 2); theHeaderSize += 2; in.read(theCodewords, 11); theHeaderSize += 11; in.read(theControlAndHandling, 2); theHeaderSize += 2; in.read(theReleasingInstructions, 20); theHeaderSize += 20; in.read(theDeclassificationType, 2); theHeaderSize += 2; in.read(theDeclassificationDate, 8); theHeaderSize += 8; in.read(theDeclassificationExemption, 4); theHeaderSize += 4; in.read(theDowngrade, 1); theHeaderSize ++; in.read(theDowngradingDate, 8); theHeaderSize += 8; in.read(theClassificationText, 43); theHeaderSize += 43; in.read(theClassificationAuthorityType, 1); theHeaderSize ++; in.read(theClassificationAuthority, 40); theHeaderSize += 40; in.read(theClassificationReason, 1); theHeaderSize ++; in.read(theSecuritySourceDate, 8); theHeaderSize += 8; in.read(theSecurityControlNumber, 15); theHeaderSize += 15; in.read(theCopyNumber, 5); theHeaderSize += 5; in.read(theNumberOfCopies, 5); theHeaderSize += 5; in.read(theEncryption, 1); theHeaderSize ++; in.read((char*)theFileBackgroundColor, 3); theHeaderSize += 3; in.read(theOriginatorsName, 24); theHeaderSize += 24; in.read(theOriginatorsPhone, 18); theHeaderSize += 18; in.read(theFileLength, 12); theHeaderSize += 12; in.read(theHeaderLength, 6); theHeaderSize += 6; // image description group in.read(theNumberOfImageInfoRecords, 3); theHeaderSize += 3; readImageInfoRecords(in); // symbol description group in.read(theNumberOfGraphicInfoRecords, 3); theHeaderSize += 3; readGraphicInfoRecords(in); in.read(theReservedForFutureUse1, 3); theHeaderSize += 3; // text file information group in.read(theNumberOfTextFileInfoRecords, 3); theHeaderSize += 3; readTextFileInfoRecords(in); // Data extension group in.read(theNumberOfDataExtSegInfoRecords, 3); theHeaderSize += 3; readDataExtSegInfoRecords(in); // Reserve Extension Segment group in.read(theNumberOfResExtSegInfoRecords, 3); theHeaderSize += 3; readResExtSegInfoRecords(in); in.read(theUserDefinedHeaderDataLength, 5); theHeaderSize += 5; // only get the header overflow if there even exists // user defined data. std::streampos userDefinedHeaderLength = ossimString(theUserDefinedHeaderDataLength).toInt32(); ossimNitfTagInformation headerTag; std::streampos start = in.tellg(); std::streampos current = in.tellg(); if(userDefinedHeaderLength > 0) { in.read(theUserDefinedHeaderOverflow, 3); current = in.tellg(); while((current - start) < userDefinedHeaderLength) { headerTag.parseStream(in); headerTag.setTagType("UDHD"); theTagList.push_back(headerTag); // in.ignore(headerTag.getTagLength()); // headerTag.clearFields(); current = in.tellg(); } //in.seekg(start + userDefinedHeaderLength); theHeaderSize += (userDefinedHeaderLength); } in.read(theExtendedHeaderDataLength, 5); theHeaderSize += 5; std::streampos extendedHeaderDataLength = ossimString(theExtendedHeaderDataLength).toInt32(); start = in.tellg(); current = in.tellg(); // for now let's just ignore it if(extendedHeaderDataLength > 0) { in.read(theExtendedHeaderDataOverflow, 3); current = in.tellg(); while((current - start) < extendedHeaderDataLength) { headerTag.parseStream(in); headerTag.setTagType("XHD"); theTagList.push_back(headerTag); // in.ignore(headerTag.getTagLength()); // headerTag.clearFields(); current = in.tellg(); } theHeaderSize += extendedHeaderDataLength; in.seekg(start + extendedHeaderDataLength); } // this need to be re-thought initializeAllOffsets(); readOverflowTags(in); // custom DES parsers bool parseDes = ossimString(ossimPreferences::instance()->findPreference("des_parser")).toBool(); if (parseDes) readDes(in); } bool ossimNitfFileHeaderV2_1::isValid()const { bool result = ossimNitfFileHeaderV2_X::isValid(); if(result) { } return result; } void ossimNitfFileHeaderV2_1::readOverflowTags(ossim::istream& in) { ossim_int32 overflow = ossimString(theUserDefinedHeaderOverflow).toInt32(); if (overflow != 0) { ossimNitfDataExtensionSegment *des = getNewDataExtensionSegment(overflow-1, in); if (des != NULL) { const vector &desTags = des->getTagList(); for (vector::const_iterator iter = desTags.begin(); iter != desTags.end(); ++iter) { iter->setTagType("UDHD"); theTagList.push_back(*iter); } } delete des; } overflow = ossimString(theExtendedHeaderDataOverflow).toInt32(); if (overflow != 0) { ossimNitfDataExtensionSegment *des = getNewDataExtensionSegment(overflow-1, in); if (des != NULL) { const vector &desTags = des->getTagList(); for (vector::const_iterator iter = desTags.begin(); iter != desTags.end(); ++iter) { iter->setTagType("XHD"); theTagList.push_back(*iter); } } delete des; } } void ossimNitfFileHeaderV2_1::readDes(istream& in) { ossimNitfDesInformation des; for (int i=0; i 0) { out.write(theUserDefinedHeaderOverflow, 3); } ossim_uint32 totalLength = getTotalTagLength(); if(totalLength <= 99999) { std::ostringstream tempOut; tempOut << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << totalLength; memcpy(theExtendedHeaderDataLength, tempOut.str().c_str(), 5); out.write(theExtendedHeaderDataLength, 5); // for now we hard code the 000 for we do not currently support writing to the DES if the total tag length is // larger than supported // memset(theExtendedHeaderDataOverflow, '0', 3); if(totalLength > 0) { out.write(theExtendedHeaderDataOverflow, 3); ossim_uint32 i = 0; for(i = 0; i < theTagList.size(); ++i) { theTagList[i].writeStream(out); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimNitfFileHeaderV2_1::writeStream: Only support writing of total tag length < 99999" << std::endl; } */ ossim_uint32 totalLength = ossimString(theUserDefinedHeaderDataLength).toUInt32(); if (totalLength > 0) { totalLength += 3; } // Scope tempOut { std::ostringstream tempOut; tempOut << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << totalLength; out.write(tempOut.str().c_str(), 5); } if (totalLength > 0) { if(totalLength <= 99999) { out.write(theUserDefinedHeaderOverflow, 3); for (unsigned int i = 0; i < theTagList.size(); ++i) { if (theTagList[i].getTagType() == "UDHD") { theTagList[i].writeStream(out); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimNitfFileHeaderV2_1::writeStream: Only support writing of total tag length <= 99999" << std::endl; } } totalLength = ossimString(theExtendedHeaderDataLength).toUInt32(); if (totalLength > 0) { totalLength += 3; } // Scope tempOut { std::ostringstream tempOut; tempOut << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << totalLength; out.write(tempOut.str().c_str(), 5); } if (totalLength > 0) { if(totalLength <= 99999) { out.write(theExtendedHeaderDataOverflow, 3); for(unsigned int i = 0; i < theTagList.size(); ++i) { if (theTagList[i].getTagType() == "XHD") { theTagList[i].writeStream(out); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimNitfFileHeaderV2_1::writeStream: Only support writing of total tag length <= 99999" << std::endl; } } } std::ostream& ossimNitfFileHeaderV2_1::print(std::ostream& out, const std::string& prefix) const { out << setiosflags(ios::left) << prefix << std::setw(24) << "FHDR:" << theFileTypeVersion << "\n" << prefix << std::setw(24) << "CLEVEL:" << theComplexityLevel << "\n" << prefix << std::setw(24) << "STYPE:" << theSystemType << "\n" << prefix << std::setw(24) << "OSTAID:" << theOriginatingStationId << "\n" << prefix << std::setw(24) << "FDT:" << theDateTime << "\n" << prefix << std::setw(24) << "FTITLE:" << theFileTitle << "\n" << prefix << std::setw(24) << "FSCLAS:" << theSecurityClassification<< "\n" << prefix << std::setw(24) << "FSCLSY:" << theSecurityClassificationSys<< "\n" << prefix << std::setw(24) << "FSCODE:" << theCodewords << "\n" << prefix << std::setw(24) << "FSCTLH:" << theControlAndHandling << "\n" << prefix << std::setw(24) << "FSREL:" << theReleasingInstructions << "\n" << prefix << std::setw(24) << "FSDCTP:" << theDeclassificationType << "\n" << prefix << std::setw(24) << "FSDCDT:" << theDeclassificationDate << "\n" << prefix << std::setw(24) << "FSDCXM:" << theDeclassificationExemption << "\n" << prefix << std::setw(24) << "FSDG:" << theDowngrade << "\n" << prefix << std::setw(24) << "FSDGDT:" << theDowngradingDate << "\n" << prefix << std::setw(24) << "FSCLTX:" << theClassificationText << "\n" << prefix << std::setw(24) << "FSCATP:" << theClassificationAuthorityType << "\n" << prefix << std::setw(24) << "FSCAUT:" << theClassificationAuthority << "\n" << prefix << std::setw(24) << "FSCRSN:" << theClassificationReason << "\n" << prefix << std::setw(24) << "FSSRDT:" << theSecuritySourceDate << "\n" << prefix << std::setw(24) << "FSCTLN:" << theSecurityControlNumber << "\n" << prefix << std::setw(24) << "FSCOP:" << theCopyNumber << "\n" << prefix << std::setw(24) << "FSCOPYS:" << theNumberOfCopies << "\n" << prefix << std::setw(24) << "ENCRYP:" << theEncryption << "\n" << prefix << std::setw(24) << "FBKGC[0]:" << (int)theFileBackgroundColor[0] << "\n" << prefix << std::setw(24) << "FBKGC[1]:" << (int)theFileBackgroundColor[1] << "\n" << prefix << std::setw(24) << "FBKGC[2]:" << (int)theFileBackgroundColor[2] << "\n" << prefix << std::setw(24) << "ONAME:" << theOriginatorsName<< "\n" << prefix << std::setw(24) << "OPHONE:" << theOriginatorsPhone << "\n" << prefix << std::setw(24) << "FL:" << theFileLength << "\n" << prefix << std::setw(24) << "HL:" << theHeaderLength << "\n" << prefix << std::setw(24) << "NUMI:" << theNumberOfImageInfoRecords << "\n"; ossim_uint32 index; for (index = 0; index < theNitfImageInfoRecords.size(); ++index) { std::ostringstream os; os << setw(3) << setfill('0') << (index+1) << ":"; ossimString tmpStr = "LISH"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfImageInfoRecords[index].theImageSubheaderLength << "\n"; tmpStr = "LI"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfImageInfoRecords[index].theImageLength << "\n"; } out << prefix << std::setw(24) << "NUMS:" << theNumberOfGraphicInfoRecords << "\n"; for (index = 0; index < theNitfGraphicInfoRecords.size(); ++index) { std::ostringstream os; os << setw(3) << setfill('0') << (index+1) << ":"; ossimString tmpStr = "LSSH"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfGraphicInfoRecords[index].theGraphicSubheaderLength << "\n"; tmpStr = "LS"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfGraphicInfoRecords[index].theGraphicLength << "\n"; } out << prefix << std::setw(24) << "NUMX:" << theReservedForFutureUse1 << "\n" << prefix << std::setw(24) << "NUMT:" << theNumberOfTextFileInfoRecords << "\n"; for (index = 0; index < theNitfTextFileInfoRecords.size(); ++index) { std::ostringstream os; os << setw(3) << setfill('0') << (index+1) << ":"; ossimString tmpStr = "LTSH"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfTextFileInfoRecords[index].theTextFileSubheaderLength << "\n"; tmpStr = "LT"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfTextFileInfoRecords[index].theTextFileLength << "\n"; } out << prefix << std::setw(24) << "NUMDES:" << theNumberOfDataExtSegInfoRecords << "\n"; for (index = 0; index < theNitfDataExtSegInfoRecords.size(); ++index) { std::ostringstream os; os << setw(3) << setfill('0') << (index+1) << ":"; ossimString tmpStr = "LDSH"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfDataExtSegInfoRecords[index].theDataExtSegSubheaderLength << "\n"; tmpStr = "LD"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfDataExtSegInfoRecords[index].theDataExtSegLength << "\n"; } out << prefix << std::setw(24) << "NUMRES:" << theNumberOfResExtSegInfoRecords << "\n"; for (index = 0; index < theNitfResExtSegInfoRecords.size(); ++index) { std::ostringstream os; os << setw(3) << setfill('0') << (index+1) << ":"; ossimString tmpStr = "LRESSH"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfResExtSegInfoRecords[index].theResExtSegSubheaderLength << "\n"; tmpStr = "LRE"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theNitfResExtSegInfoRecords[index].theResExtSegLength << "\n"; } out << prefix << std::setw(24) << "UDHDL:" << theUserDefinedHeaderDataLength << "\n" << prefix << std::setw(24) << "UDHOFL:" << theUserDefinedHeaderOverflow << "\n" << prefix << std::setw(24) << "XHDL:" << theExtendedHeaderDataLength << "\n" << prefix << std::setw(24) << "XHDLOFL:" << theExtendedHeaderDataOverflow << "\n"; return ossimNitfFileHeaderV2_X::print(out, prefix); } ossimNitfImageHeader* ossimNitfFileHeaderV2_1::allocateImageHeader()const { return new ossimNitfImageHeaderV2_1; } ossimNitfTextHeader *ossimNitfFileHeaderV2_1::allocateTextHeader()const { return new ossimNitfTextHeaderV2_0; } ossimNitfDataExtensionSegment* ossimNitfFileHeaderV2_1::allocateDataExtSegment()const { return new ossimNitfDataExtensionSegmentV2_1; } bool ossimNitfFileHeaderV2_1::isEncrypted()const { return (theEncryption[0]=='1'); } ossim_int32 ossimNitfFileHeaderV2_1::getNumberOfImages()const { return (ossim_int32)theNitfImageInfoRecords.size(); } ossim_int32 ossimNitfFileHeaderV2_1::getNumberOfTextSegments()const { return static_cast(theNitfTextFileInfoRecords.size()); } ossim_int32 ossimNitfFileHeaderV2_1::getHeaderSize()const { return theHeaderSize; } ossim_int64 ossimNitfFileHeaderV2_1::getFileSize()const { ossimString temp = theFileLength; if(temp == "999999999999") { return -1; } else { return temp.toInt64(); } } const char* ossimNitfFileHeaderV2_1::getVersion()const { return &theFileTypeVersion[4]; } void ossimNitfFileHeaderV2_1::clearFields() { memcpy(theFileTypeVersion, "NITF02.10", 9); memcpy(theComplexityLevel, "01", 2); memcpy(theSystemType, "BF01", 4); memset(theOriginatingStationId, ' ', 10); memset(theDateTime, ' ', 14); memset(theFileTitle, ' ', 80); memset(theSecurityClassification, ' ', 1); memset(theSecurityClassificationSys, ' ', 2); memset(theCodewords, ' ', 11); memset(theControlAndHandling, ' ', 2); memset(theReleasingInstructions, ' ', 20); memset(theDeclassificationType, ' ', 2); memset(theDeclassificationDate, ' ', 8); memset(theDeclassificationExemption, ' ', 4); memset(theDowngrade, ' ', 1); memset(theDowngradingDate, ' ', 8); memset(theClassificationText, ' ', 43); memset(theClassificationAuthorityType, ' ', 1); memset(theClassificationAuthority, ' ', 40); memset(theClassificationReason, ' ', 1); memset(theSecuritySourceDate, ' ', 8); memset(theSecurityControlNumber, ' ', 15); memset(theCopyNumber, '0', 5); memset(theNumberOfCopies, '0', 5); memset(theEncryption, ' ', 1); memset(theFileBackgroundColor, 0, 3); memset(theOriginatorsName, ' ', 24); memset(theOriginatorsPhone, ' ', 18); memset(theFileLength, ' ', 12); memset(theHeaderLength, ' ', 6); memset(theNumberOfImageInfoRecords, '0', 3); memset(theNumberOfGraphicInfoRecords, '0', 3); memset(theReservedForFutureUse1, '0', 3); memset(theNumberOfTextFileInfoRecords, '0', 3); memset(theNumberOfDataExtSegInfoRecords, '0', 3); memset(theNumberOfResExtSegInfoRecords, '0', 3); memset(theUserDefinedHeaderDataLength, '0', 5); memset(theUserDefinedHeaderOverflow, '0',3); memset(theExtendedHeaderDataLength, '0',5); memset(theExtendedHeaderDataOverflow, '0', 3); theFileTypeVersion[9] = '\0'; theComplexityLevel[2] = '\0'; theSystemType[4] = '\0'; theOriginatingStationId[10] = '\0'; theDateTime[14] = '\0'; theFileTitle[80] = '\0'; theSecurityClassification[1] = '\0'; theSecurityClassificationSys[2] = '\0'; theCodewords[11] = '\0'; theControlAndHandling[2] = '\0'; theReleasingInstructions[20] = '\0'; theDeclassificationType[2] = '\0'; theDeclassificationDate[8] = '\0'; theDeclassificationExemption[4] = '\0'; theDowngrade[1] = '\0'; theDowngradingDate[8] = '\0'; theClassificationText[43] = '\0'; theClassificationAuthorityType[1] = '\0'; theClassificationAuthority[40] = '\0'; theClassificationReason[1] = '\0'; theSecuritySourceDate[8] = '\0'; theSecurityControlNumber[15] = '\0'; theCopyNumber[5] = '\0'; theNumberOfCopies[5] = '\0'; theEncryption[1] = '\0'; theOriginatorsName[24] = '\0'; theOriginatorsPhone[18] = '\0'; theFileLength[12] = '\0'; theHeaderLength[6] = '\0'; theNumberOfImageInfoRecords[3] = '\0'; theNumberOfGraphicInfoRecords[3] = '\0'; theReservedForFutureUse1[3] = '\0'; theNumberOfTextFileInfoRecords[3] = '\0'; theNumberOfDataExtSegInfoRecords[3] = '\0'; theNumberOfResExtSegInfoRecords[3] = '\0'; theUserDefinedHeaderDataLength[5] = '\0'; theUserDefinedHeaderOverflow[3] = '\0'; theExtendedHeaderDataLength[5] = '\0'; theExtendedHeaderDataOverflow[3] = '\0'; theHeaderSize = 0; } void ossimNitfFileHeaderV2_1::readImageInfoRecords(ossim::istream& in) { ossim_int32 numberOfImages = ossimString(theNumberOfImageInfoRecords).toInt32(); ossim_int32 index; theNitfImageInfoRecords.clear(); for(index=0; index < numberOfImages; index++) { ossimNitfImageInfoRecordV2_1 temp; in.read(temp.theImageSubheaderLength, 6); in.read(temp.theImageLength, 10); theHeaderSize += 16; temp.theImageSubheaderLength[6] = '\0'; temp.theImageLength[10] = '\0'; theNitfImageInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_1::readGraphicInfoRecords(ossim::istream& in) { ossim_int32 numberOfGraphics = ossimString(theNumberOfGraphicInfoRecords).toInt32(); ossim_int32 index; theNitfGraphicInfoRecords.clear(); for(index=0; index < numberOfGraphics; index++) { ossimNitfGraphicInfoRecordV2_1 temp; in.read(temp.theGraphicSubheaderLength, 4); in.read(temp.theGraphicLength, 6); theHeaderSize += 10; temp.theGraphicSubheaderLength[4] = '\0'; temp.theGraphicLength[6] = '\0'; theNitfGraphicInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_1::readTextFileInfoRecords(ossim::istream& in) { ossim_int32 numberOfTextFiles = ossimString(theNumberOfTextFileInfoRecords).toInt32(); ossim_int32 index; theNitfTextFileInfoRecords.clear(); for(index=0; index < numberOfTextFiles; index++) { ossimNitfTextFileInfoRecordV2_1 temp; in.read(temp.theTextFileSubheaderLength, 4); in.read(temp.theTextFileLength, 5); theHeaderSize += 9; temp.theTextFileSubheaderLength[4] = '\0'; temp.theTextFileLength[5] = '\0'; theNitfTextFileInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_1::readDataExtSegInfoRecords(ossim::istream& in) { ossim_int32 numberOfDataExtSegs = ossimString(theNumberOfDataExtSegInfoRecords).toInt32(); ossim_int32 index; theNitfDataExtSegInfoRecords.clear(); for(index=0; index < numberOfDataExtSegs; index++) { ossimNitfDataExtSegInfoRecordV2_1 temp; in.read(temp.theDataExtSegSubheaderLength, 4); in.read(temp.theDataExtSegLength, 9); theHeaderSize += 13; temp.theDataExtSegSubheaderLength[4] = '\0'; temp.theDataExtSegLength[9] = '\0'; theNitfDataExtSegInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_1::deleteLastDataExtSegInfoRecord() { if (theNitfDataExtSegInfoRecords.size()) theNitfDataExtSegInfoRecords.pop_back(); setNumberOfDataExtSegInfoRecords(theNitfDataExtSegInfoRecords.size()); } void ossimNitfFileHeaderV2_1::readResExtSegInfoRecords(ossim::istream& in) { ossim_int32 numberOfResExtSegs = ossimString(theNumberOfResExtSegInfoRecords).toInt32(); ossim_int32 index; theNitfResExtSegInfoRecords.clear(); for(index=0; index < numberOfResExtSegs; index++) { ossimNitfResExtSegInfoRecordV2_1 temp; in.read(temp.theResExtSegSubheaderLength, 4); in.read(temp.theResExtSegLength, 7); theHeaderSize += 11; temp.theResExtSegSubheaderLength[4] = '\0'; temp.theResExtSegLength[7] = '\0'; theNitfResExtSegInfoRecords.push_back(temp); } } void ossimNitfFileHeaderV2_1::deleteLastImageInfoRecord() { if (theNitfImageInfoRecords.size()) theNitfImageInfoRecords.pop_back(); setNumberOfImageInfoRecords(theNitfImageInfoRecords.size()); } ossim_int32 ossimNitfFileHeaderV2_1::getNumberOfLabels()const { return 0; } ossim_int32 ossimNitfFileHeaderV2_1::getNumberOfSymbols()const { return 0; } ossim_int32 ossimNitfFileHeaderV2_1::getNumberOfGraphics()const { return theNitfGraphicInfoRecords.size(); } ossim_int32 ossimNitfFileHeaderV2_1::getNumberOfDataExtSegments()const { return theNitfDataExtSegInfoRecords.size(); } ossim_int32 ossimNitfFileHeaderV2_1::getNumberOfReservedExtSegments()const { return theNitfResExtSegInfoRecords.size(); } const char* ossimNitfFileHeaderV2_1::getDateTime()const { return theDateTime; } ossimDrect ossimNitfFileHeaderV2_1::getImageRect()const { return theImageRect; } void ossimNitfFileHeaderV2_1::addImageInfoRecord(const ossimNitfImageInfoRecordV2_1& recordInfo) { theNitfImageInfoRecords.push_back(recordInfo); setNumberOfImageInfoRecords(theNitfImageInfoRecords.size()); } void ossimNitfFileHeaderV2_1::addTextInfoRecord(const ossimNitfTextFileInfoRecordV2_1& recordInfo) { theNitfTextFileInfoRecords.push_back(recordInfo); setNumberOfTextInfoRecords(theNitfTextFileInfoRecords.size()); } bool ossimNitfFileHeaderV2_1::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = ossimNitfFileHeaderV2_X::saveState(kwl, prefix); if(result) { kwl.add(prefix, FSCLSY_KW.c_str(), theSecurityClassificationSys); kwl.add(prefix, FSCODE_KW.c_str(), theCodewords); kwl.add(prefix, FSCTLH_KW.c_str(), theControlAndHandling); kwl.add(prefix, FSREL_KW.c_str(), theReleasingInstructions); kwl.add(prefix, FSDCTP_KW.c_str(), theDeclassificationType); kwl.add(prefix, FSDCDT_KW.c_str(), theDeclassificationDate); kwl.add(prefix, FSDCXM_KW.c_str(), theDeclassificationExemption); kwl.add(prefix, FSDG_KW.c_str(), theDowngrade); kwl.add(prefix, FSDGDT_KW.c_str(), theDowngradingDate); kwl.add(prefix, FSCLTX_KW.c_str(), theClassificationText); kwl.add(prefix, FSCATP_KW.c_str(), theClassificationAuthorityType); kwl.add(prefix, FSCAUT_KW.c_str(), theClassificationAuthorityType); kwl.add(prefix, FSCRSN_KW.c_str(), theClassificationReason); kwl.add(prefix, FSSRDT_KW.c_str(), theSecuritySourceDate); kwl.add(prefix, FSCTLN_KW.c_str(), theSecurityControlNumber); //kwl.add(prefix, FBKGC_KW.c_str(), theFileBackgroundColor); kwl.add(prefix, ONAME_KW.c_str(), theOriginatorsName); kwl.add(prefix, OPHONE_KW.c_str(), theOriginatorsPhone); kwl.add(prefix, FL_KW.c_str(), theFileLength); kwl.add(prefix, HL_KW.c_str(), theHeaderLength); kwl.add(prefix, NUMI_KW.c_str(), theNumberOfImageInfoRecords); } return result; } void ossimNitfFileHeaderV2_1::addDataExtSegInfoRecord(const ossimNitfDataExtSegInfoRecordV2_1& recordInfo) { theNitfDataExtSegInfoRecords.push_back(recordInfo); setNumberOfDataExtSegInfoRecords(theNitfDataExtSegInfoRecords.size()); } void ossimNitfFileHeaderV2_1::replaceImageInfoRecord(int i, const ossimNitfImageInfoRecordV2_1& recordInfo) { if ( i < static_cast(theNitfImageInfoRecords.size()) ) { theNitfImageInfoRecords[i] = recordInfo; } } ossimNitfSymbolHeader *ossimNitfFileHeaderV2_1::allocateSymbolHeader()const { return 0; } ossimNitfLabelHeader *ossimNitfFileHeaderV2_1::allocateLabelHeader()const { return 0; } void ossimNitfFileHeaderV2_1::initializeAllOffsets() { // this will be a running tally ossim_uint64 tally = theHeaderSize; ossim_uint64 idx = 0; // clear out all offset inforamtion and begin populating them theImageOffsetList.clear(); theGraphicOffsetList.clear(); theTextFileOffsetList.clear(); theDataExtSegOffsetList.clear(); for(idx = 0; idx < theNitfImageInfoRecords.size(); ++idx) { theImageOffsetList.push_back(ossimNitfImageOffsetInformation(tally, tally + theNitfImageInfoRecords[idx].getHeaderLength())); tally += theNitfImageInfoRecords[idx].getTotalLength(); } for(idx = 0; idx < theNitfGraphicInfoRecords.size(); ++idx) { theGraphicOffsetList.push_back(ossimNitfGraphicOffsetInformation(tally, tally + theNitfGraphicInfoRecords[idx].getHeaderLength())); tally += theNitfGraphicInfoRecords[idx].getTotalLength(); } for(idx = 0; idx < theNitfTextFileInfoRecords.size(); ++idx) { theTextFileOffsetList.push_back(ossimNitfTextOffsetInformation(tally, tally + theNitfTextFileInfoRecords[idx].getHeaderLength())); tally += theNitfTextFileInfoRecords[idx].getTotalLength(); } for(idx = 0; idx < theNitfDataExtSegInfoRecords.size(); ++idx) { theDataExtSegOffsetList.push_back(ossimNitfDataExtSegOffsetInformation(tally, tally + theNitfDataExtSegInfoRecords[idx].getHeaderLength())); tally += theNitfDataExtSegInfoRecords[idx].getTotalLength(); } } ossimNitfImageHeader* ossimNitfFileHeaderV2_1::getNewImageHeader(ossim_uint32 imageNumber, ossim::istream& in)const { ossimNitfImageHeader *result = 0; if( (getNumberOfImages() > 0) && (imageNumber < theImageOffsetList.size()) ) { result = allocateImageHeader(); in.seekg(theImageOffsetList[imageNumber].theImageHeaderOffset, ios::beg); ((ossimNitfImageHeaderV2_1*)result)->parseStream(in, this); } else { #if 0 ossimNotify(ossimNotifyLevel_FATAL) << "FATAL ossimNitfFileHeaderV2_1::getNewImageHeader: " << "\nNo images in file or image number (" << imageNumber << ") is out of range!\n"; #endif } return result; } ossimNitfSymbolHeader* ossimNitfFileHeaderV2_1::getNewSymbolHeader(ossim_uint32 /* symbolNumber */, ossim::istream& /* in */)const { // Currently not implemented... ossimNitfSymbolHeader *result = 0; return result; } ossimNitfLabelHeader* ossimNitfFileHeaderV2_1::getNewLabelHeader(ossim_uint32 /* labelNumber */, ossim::istream& /* in */)const { // Currently not implemented... ossimNitfLabelHeader *result = 0; return result; } ossimNitfTextHeader* ossimNitfFileHeaderV2_1::getNewTextHeader(ossim_uint32 /* textNumber */, ossim::istream& /* in */)const { // Currently not implemented... ossimNitfTextHeader *result = 0; return result; } ossimNitfDataExtensionSegment* ossimNitfFileHeaderV2_1::getNewDataExtensionSegment( ossim_int32 dataExtNumber, ossim::istream& in )const { ossimNitfDataExtensionSegment *result = 0; if((getNumberOfDataExtSegments() > 0) && (dataExtNumber < (ossim_int32)theNitfDataExtSegInfoRecords.size()) && (dataExtNumber >= 0)) { result = allocateDataExtSegment(); // ossimIFStream64::seekg64(in, theDataExtSegOffsetList[dataExtNumber].theDataExtSegHeaderOffset, ios::beg); in.seekg(theDataExtSegOffsetList[dataExtNumber].theDataExtSegHeaderOffset, ios::beg); result->parseStream(in, theNitfDataExtSegInfoRecords[dataExtNumber].getDataExtSegLength()); } return result; } ossimString ossimNitfFileHeaderV2_1::getSecurityClassificationSys()const { return theSecurityClassificationSys; } ossimString ossimNitfFileHeaderV2_1::getCodeWords()const { return theCodewords; } ossimString ossimNitfFileHeaderV2_1::getControlAndHandling()const { return theControlAndHandling; } ossimString ossimNitfFileHeaderV2_1::getReleasingInstructions()const { return theReleasingInstructions; } ossimString ossimNitfFileHeaderV2_1::getDeclassificationType()const { return theDeclassificationType; } ossimString ossimNitfFileHeaderV2_1::getDeclassificationDate()const { return theDeclassificationDate; } ossimString ossimNitfFileHeaderV2_1::getDeclassificationExemption()const { return theDeclassificationExemption; } ossimString ossimNitfFileHeaderV2_1::getDowngrade()const { return theDowngrade; } ossimString ossimNitfFileHeaderV2_1::getDowngradingDate()const { return theDowngradingDate; } ossimString ossimNitfFileHeaderV2_1::getClassificationText()const { return theClassificationText; } ossimString ossimNitfFileHeaderV2_1::getClassificationAuthorityType()const { return theClassificationAuthorityType; } ossimString ossimNitfFileHeaderV2_1::getClassificationAuthority()const { return theClassificationAuthority; } ossimString ossimNitfFileHeaderV2_1::getClassificationReason()const { return theClassificationReason; } ossimString ossimNitfFileHeaderV2_1::getSecuritySourceDate()const { return theSecuritySourceDate; } ossimString ossimNitfFileHeaderV2_1::getSecurityControlNumber()const { return theSecurityControlNumber; } void ossimNitfFileHeaderV2_1::getBackgroundColor(ossim_uint8& r, ossim_uint8& g, ossim_uint8& b)const { r = theFileBackgroundColor[0]; g = theFileBackgroundColor[1]; b = theFileBackgroundColor[2]; } ossimString ossimNitfFileHeaderV2_1::getOriginatorsName()const { return theOriginatorsName; } ossimString ossimNitfFileHeaderV2_1::getOriginatorsPhone()const { return theOriginatorsPhone; } void ossimNitfFileHeaderV2_1::setFileLength(ossim_uint64 fileLength) { std::ostringstream out; out << std::setw(12) << std::setfill('0') << std::setiosflags(ios::right) << fileLength; memcpy(theFileLength, out.str().c_str(), 12); } void ossimNitfFileHeaderV2_1::setNumberOfGraphicInfoRecords(ossim_uint64 num) { if (num < 1000) { std::ostringstream out; out << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << num; memcpy(theNumberOfGraphicInfoRecords, out.str().c_str(), 3); } else { std::string s = "ossimNitfFileHeaderV2_1::setNumberOfGraphicInfoRecords:"; s += " ERROR\nExceeded max number of 999!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } } void ossimNitfFileHeaderV2_1::setNumberOfDataExtSegInfoRecords(ossim_uint64 num) { if (num < 1000) { std::ostringstream out; out << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << num; memcpy(theNumberOfDataExtSegInfoRecords, out.str().c_str(), 3); } else { std::string s = "ossimNitfFileHeaderV2_1::setNumberOfDataExtSegInfoRecords:"; s += " ERROR\nExceeded max number of 999!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } } void ossimNitfFileHeaderV2_1::setNumberOfTextInfoRecords(ossim_uint64 num) { if (num < 1000) { std::ostringstream out; out << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << num; memcpy(theNumberOfTextFileInfoRecords, out.str().c_str(), 3); } else { std::string s = "ossimNitfFileHeaderV2_1::setNumberOfTextRecords:"; s += " ERROR\nExceeded max number of 999!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } } void ossimNitfFileHeaderV2_1::setNumberOfImageInfoRecords(ossim_uint64 num) { if (num < 1000) { std::ostringstream out; out << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << num; memcpy(theNumberOfImageInfoRecords, out.str().c_str(), 3); } else { std::string s = "ossimNitfFileHeaderV2_1::setNumberOfImageInfoRecords:"; s += " ERROR\nExceeded max image info number of 999!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } } void ossimNitfFileHeaderV2_1::setHeaderLength(ossim_uint64 headerLength) { std::ostringstream out; out << std::setw(6) << std::setfill('0') << std::setiosflags(ios::right) << headerLength; memcpy(theHeaderLength, out.str().c_str(), 6); } void ossimNitfFileHeaderV2_1::setSecurityClassificationSys(const ossimString& value) { std::ostringstream out; out << std::setw(2) << std::setfill(' ') << std::setiosflags(ios::left) << ossimString(value).trim(); memcpy(theSecurityClassificationSys, out.str().c_str(), 2); } void ossimNitfFileHeaderV2_1::setCodeWords(const ossimString& codeWords) { std::ostringstream out; out << std::setw(11) << std::setfill(' ') << std::setiosflags(ios::left) << ossimString(codeWords).trim(); memcpy(theCodewords, out.str().c_str(), 11); } void ossimNitfFileHeaderV2_1::setControlAndHandling(const ossimString& controlAndHandling) { std::ostringstream out; out << std::setw(2) << std::setfill(' ') << std::setiosflags(ios::left) << ossimString(controlAndHandling).trim(); memcpy(theControlAndHandling, out.str().c_str(), 2); } void ossimNitfFileHeaderV2_1::setReleasingInstructions(const ossimString& releasingInstructions) { std::ostringstream out; out << std::setw(20) << std::setfill(' ') << std::setiosflags(ios::left) << ossimString(releasingInstructions).trim(); memcpy(theReleasingInstructions, out.str().c_str(), 20); } void ossimNitfFileHeaderV2_1::setDeclassificationType(const ossimString& declassType) { std::ostringstream out; out << std::setw(2) << std::setfill(' ') << std::setiosflags(ios::left) << declassType.trim(); memcpy(theDeclassificationType, out.str().c_str(), 2); } void ossimNitfFileHeaderV2_1::setDeclassificationDate(const ossimLocalTm& d) { memcpy(theDeclassificationDate, formatDate(getVersion(), d).c_str(), 8); } void ossimNitfFileHeaderV2_1::setDeclassificationDate(const ossimString& d) { if(d.size() >=8) { memcpy(theDeclassificationDate, d.c_str(), 8); } } void ossimNitfFileHeaderV2_1::setDeclassificationExemption(const ossimString& exemption) { std::ostringstream out; out << std::setw(4) << std::setfill(' ') << std::setiosflags(ios::left) << exemption.trim(); memcpy(theDeclassificationExemption, out.str().c_str(), 4); } void ossimNitfFileHeaderV2_1::setDowngrade(const ossimString& downgrade) { std::ostringstream out; out << std::setw(1) << std::setfill(' ') << std::setiosflags(ios::left) << downgrade.trim(); memcpy(theDowngrade, out.str().c_str(), 1); } void ossimNitfFileHeaderV2_1::setDowngradingDate(const ossimLocalTm& d) { memcpy(theDowngradingDate, formatDate(getVersion(), d).c_str(), 8); } void ossimNitfFileHeaderV2_1::setDowngradingDate(const ossimString& d) { if(d.size() >=8) { memcpy(theDowngradingDate, d.c_str(), 8); } } void ossimNitfFileHeaderV2_1::setClassificationText(const ossimString& classificationText) { std::ostringstream out; out << std::setw(43) << std::setfill(' ') << std::setiosflags(ios::left) << classificationText.trim(); memcpy(theClassificationText, out.str().c_str(), 43); } void ossimNitfFileHeaderV2_1::setClassificationAuthorityType(const ossimString& authorityType) { std::ostringstream out; out << std::setw(1) << std::setfill(' ') << std::setiosflags(ios::left) << authorityType.trim(); memcpy(theClassificationAuthorityType, out.str().c_str(), 1); } void ossimNitfFileHeaderV2_1::setClassificationAuthority(const ossimString& authority) { std::ostringstream out; out << std::setw(40) << std::setfill(' ') << std::setiosflags(ios::left) << authority.trim(); memcpy(theClassificationAuthority, out.str().c_str(), 40); } void ossimNitfFileHeaderV2_1::setClassificationReason(const ossimString& reason) { std::ostringstream out; out << std::setw(1) << std::setfill(' ') << std::setiosflags(ios::left) << reason.trim(); memcpy(theClassificationReason, out.str().c_str(), 1); } void ossimNitfFileHeaderV2_1::setSecuritySourceDate(const ossimLocalTm& d) { memcpy(theSecuritySourceDate, formatDate(getVersion(), d).c_str(), 8); } void ossimNitfFileHeaderV2_1::setSecuritySourceDate(const ossimString& d) { if(d.size() >=8) { memcpy(theSecuritySourceDate, d.c_str(), 8); } } void ossimNitfFileHeaderV2_1::setSecurityControlNumber(const ossimString& number) { std::ostringstream out; out << std::setw(15) << std::setfill(' ') << std::setiosflags(ios::left) << number.trim(); memcpy(theSecurityControlNumber, out.str().c_str(), 15); } void ossimNitfFileHeaderV2_1::setFileBackgroundColor(ossim_uint8 r, ossim_uint8 g, ossim_uint8 b) { theFileBackgroundColor[0] = r; theFileBackgroundColor[1] = g; theFileBackgroundColor[2] = b; } void ossimNitfFileHeaderV2_1::setOriginatorsName(const ossimString& name) { std::ostringstream out; out << std::setw(24) << std::setfill(' ') << std::setiosflags(ios::left) << name.trim(); memcpy(theOriginatorsName, out.str().c_str(), 24); } void ossimNitfFileHeaderV2_1::setOriginatorsPhone(const ossimString& phone) { std::ostringstream out; out << std::setw(18) << std::setfill(' ') << std::setiosflags(ios::left) << phone.trim(); memcpy(theOriginatorsPhone, out.str().c_str(), 18); } bool ossimNitfFileHeaderV2_1::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Note: Currently not looking up all fieds only ones that make sense. const char* lookup; lookup = kwl.find( prefix, FSCLSY_KW); if ( lookup ) { setSecurityClassificationSys( ossimString(lookup) ); } lookup = kwl.find( prefix, FSDCTP_KW); if ( lookup ) { setDeclassificationType( ossimString(lookup) ); } lookup = kwl.find( prefix, FSDCDT_KW); if ( lookup ) { setDeclassificationDate( ossimString(lookup) ); } lookup = kwl.find( prefix, FSDCXM_KW); if ( lookup ) { setDeclassificationExemption( ossimString(lookup) ); } lookup = kwl.find( prefix, FSDG_KW); if ( lookup ) { setDowngrade( ossimString(lookup) ); } lookup = kwl.find( prefix, FSDGDT_KW); if ( lookup ) { setDowngradingDate( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCLTX_KW ); if ( lookup ) { setClassificationText( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCATP_KW ); if ( lookup ) { setClassificationAuthorityType( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCRSN_KW ); if ( lookup ) { setClassificationReason( ossimString(lookup) ); } lookup = kwl.find( prefix, FSSRDT_KW); if ( lookup ) { setSecuritySourceDate( ossimString(lookup) ); } lookup = kwl.find( prefix, FBKGC_KW ); if ( lookup ) { ossimString value = lookup; std::vector splitString; value = value.trim(); value.split(splitString, " "); if(splitString.size() == 3) { setFileBackgroundColor((ossim_uint8)splitString[0].toUInt32(), (ossim_uint8)splitString[1].toUInt32(), (ossim_uint8)splitString[2].toUInt32()); } } return ossimNitfFileHeaderV2_X::loadState(kwl, prefix); } void ossimNitfFileHeaderV2_1::setProperty(ossimRefPtr property) { if(!property.valid()) return; ossimString name = property->getName(); // Make case insensitive: name.upcase(); if(name == FSCLSY_KW) { setSecurityClassificationSys(property->valueToString()); } else if(name == FSDCTP_KW) { setDeclassificationType(property->valueToString()); } else if(name == FSDCDT_KW) { setDeclassificationDate(property->valueToString()); } else if(name == FSDCXM_KW) { setDeclassificationExemption(property->valueToString()); } else if(name == FSDG_KW) { setDowngrade(property->valueToString()); } else if(name == FSDGDT_KW) { setDowngradingDate(property->valueToString()); } else if(name == FSCLTX_KW) { setClassificationText(property->valueToString()); } else if(name == FSCATP_KW) { setClassificationAuthorityType(property->valueToString()); } else if(name == FSCRSN_KW) { setClassificationReason(property->valueToString()); } else if(name == FSSRDT_KW) { setSecuritySourceDate(property->valueToString()); } else if(name == FBKGC_KW) { ossimColorProperty* colorProp = PTR_CAST(ossimColorProperty, property.get()); if (colorProp) { ossim_uint8 r = colorProp->getRed(); ossim_uint8 g = colorProp->getGreen(); ossim_uint8 b = colorProp->getBlue(); setFileBackgroundColor(r, g, b); } else { ossimString value = property->valueToString(); std::vector splitString; value = value.trim(); value.split(splitString, " "); if(splitString.size() == 3) { setFileBackgroundColor((ossim_uint8)splitString[0].toUInt32(), (ossim_uint8)splitString[1].toUInt32(), (ossim_uint8)splitString[2].toUInt32()); } } } else { ossimNitfFileHeaderV2_X::setProperty(property); } } ossimRefPtr ossimNitfFileHeaderV2_1::getProperty(const ossimString& name)const { ossimProperty* property = 0; ossimStringProperty* stringProperty = 0; ossimColorProperty* colorProperty = 0; if(name == CLEVEL_KW) { property = new ossimStringProperty(name, getComplexityLevel().trim()); } else if(name == FSCLSY_KW) { property = new ossimStringProperty(name, getSecurityClassificationSys().trim()); } else if(name == FSDCTP_KW) { property = new ossimStringProperty(name, getDeclassificationType().trim()); } else if(name == FSDCDT_KW) { property = new ossimStringProperty(name, getDeclassificationDate().trim()); } else if(name == FSDCXM_KW) { property = new ossimStringProperty(name, getDeclassificationExemption().trim()); } else if(name == FSDG_KW) { stringProperty = new ossimStringProperty(name, getDowngrade().trim(), false); stringProperty->addConstraint(""); stringProperty->addConstraint("S"); stringProperty->addConstraint("C"); stringProperty->addConstraint("R"); property = stringProperty; } else if(name == FSDGDT_KW) { property = new ossimStringProperty(name, getDowngradingDate().trim()); } else if(name == FSCLTX_KW) { property = new ossimStringProperty(name, getClassificationText().trim()); } else if(name == FSCATP_KW) { stringProperty = new ossimStringProperty(name, getClassificationAuthorityType().trim(), false); stringProperty->addConstraint(""); stringProperty->addConstraint("O"); stringProperty->addConstraint("D"); stringProperty->addConstraint("M"); property = stringProperty; } else if(name == FSCRSN_KW) { stringProperty = new ossimStringProperty(name, getClassificationReason().trim(), false); stringProperty->addConstraint(""); stringProperty->addConstraint("A"); stringProperty->addConstraint("B"); stringProperty->addConstraint("C"); stringProperty->addConstraint("D"); stringProperty->addConstraint("E"); stringProperty->addConstraint("F"); stringProperty->addConstraint("G"); property = stringProperty; } else if(name == FSSRDT_KW) { property = new ossimStringProperty(name, getSecuritySourceDate().trim()); } else if(name == FBKGC_KW) { ossim_uint8 r, g, b; getBackgroundColor(r, g, b); colorProperty = new ossimColorProperty(name, ossimRgbVector(r, g, b)); property = colorProperty; } else if(name == ONAME_KW) { property = new ossimStringProperty(name, ossimString(theOriginatorsName).trim()); } else if(name == OPHONE_KW) { property = new ossimStringProperty(name, ossimString(theOriginatorsPhone).trim()); } else { return ossimNitfFileHeaderV2_X::getProperty(name); } return property; } void ossimNitfFileHeaderV2_1::getPropertyNames(std::vector& propertyNames)const { ossimNitfFileHeaderV2_X::getPropertyNames(propertyNames); propertyNames.push_back(FSCLSY_KW); propertyNames.push_back(FSDCTP_KW); propertyNames.push_back(FSDCDT_KW); propertyNames.push_back(FSDCXM_KW); propertyNames.push_back(FSDG_KW); propertyNames.push_back(FSDGDT_KW); propertyNames.push_back(FSCLTX_KW); propertyNames.push_back(FSCATP_KW); propertyNames.push_back(FSCRSN_KW); propertyNames.push_back(FSSRDT_KW); propertyNames.push_back(FBKGC_KW); } void ossimNitfFileHeaderV2_1::addTag(ossimNitfTagInformation tag, bool unique) { if (unique) { removeTag(tag.getTagName()); } theTagList.push_back(tag); } void ossimNitfFileHeaderV2_1::removeTag(const ossimString& tagName) { ossim_uint32 idx = 0; for(idx = 0; idx < theTagList.size(); ++idx) { if(theTagList[idx].getTagName() == tagName) { theTagList.erase(theTagList.begin() + idx); return; } } } bool ossimNitfFileHeaderV2_1::takeOverflowTags(std::vector &overflowTags, ossim_uint32 potentialDesIndex, bool userDefinedTags) { overflowTags.clear(); std::vector::iterator iter; std::vector specifiedTags; const ossimString tagType(userDefinedTags ? "UDHD" : "XHD"); for (iter = theTagList.begin(); iter != theTagList.end(); ++iter) { if (iter->getTagType() == tagType) { specifiedTags.push_back(*iter); } } std::sort(specifiedTags.begin(), specifiedTags.end()); ossim_uint32 totalSize = 0; const ossim_uint32 maxSize = 9996; for (iter = specifiedTags.begin(); iter != specifiedTags.end() && totalSize + iter->getTotalTagLength() <= maxSize; ++iter) { totalSize += iter->getTotalTagLength(); } for (; iter != specifiedTags.end(); ++iter) { overflowTags.push_back(*iter); removeTag(iter->getTagName()); } // If there are no overflow tags, then no DES is required if (overflowTags.empty() == true) { potentialDesIndex = 0; } std::ostringstream overflowDes; overflowDes << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << potentialDesIndex; std::ostringstream tagLength; tagLength << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << totalSize; // Even if no overflow tags exist, update the fields if (userDefinedTags) { strcpy(theUserDefinedHeaderOverflow, overflowDes.str().c_str()); strcpy(theUserDefinedHeaderDataLength, tagLength.str().c_str()); } else { strcpy(theExtendedHeaderDataOverflow, overflowDes.str().c_str()); strcpy(theExtendedHeaderDataLength, tagLength.str().c_str()); } return (overflowTags.empty() == false); } ossim-Miami-2.9.1/src/support_data/ossimNitfFileHeaderV2_X.cpp000066400000000000000000000352551352751253100243100ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id: ossimNitfFileHeaderV2_X.cpp 23245 2015-04-08 20:53:04Z rashadkm $ #include #include #include #include #include /* for ossimLocalTm */ #include #include #include #include #include RTTI_DEF1(ossimNitfFileHeaderV2_X, "ossimNitfFileHeaderV2_X", ossimNitfFileHeader); static ossimString monthConversionTable[] = {" ", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}; const ossimString ossimNitfFileHeaderV2_X::FILE_TYPE_KW = "FILE_TYPE"; const ossimString ossimNitfFileHeaderV2_X::VERSION_KW = "VERSION"; const ossimString ossimNitfFileHeaderV2_X::FHDR_KW = "FHDR"; const ossimString ossimNitfFileHeaderV2_X::CLEVEL_KW = "CLEVEL"; const ossimString ossimNitfFileHeaderV2_X::STYPE_KW = "STYPE"; const ossimString ossimNitfFileHeaderV2_X::OSTAID_KW = "OSTAID"; const ossimString ossimNitfFileHeaderV2_X::FDT_KW = "FDT"; const ossimString ossimNitfFileHeaderV2_X::FTITLE_KW = "FTITLE"; const ossimString ossimNitfFileHeaderV2_X::FSCLAS_KW = "FSCLAS"; const ossimString ossimNitfFileHeaderV2_X::FSCODE_KW = "FSCODE"; const ossimString ossimNitfFileHeaderV2_X::FSCTLH_KW = "FSCTLH"; const ossimString ossimNitfFileHeaderV2_X::FSREL_KW = "FSREL"; const ossimString ossimNitfFileHeaderV2_X::FSCAUT_KW = "FSCAUT"; const ossimString ossimNitfFileHeaderV2_X::FSCTLN_KW = "FSCTLN"; const ossimString ossimNitfFileHeaderV2_X::FSCOP_KW = "FSCOP"; const ossimString ossimNitfFileHeaderV2_X::FSCPYS_KW = "FSCPYS"; const ossimString ossimNitfFileHeaderV2_X::ENCRYP_KW = "ENCRYP"; const ossimString ossimNitfFileHeaderV2_X::ONAME_KW = "ONAME"; const ossimString ossimNitfFileHeaderV2_X::OPHONE_KW = "OPHONE"; ossimNitfFileHeaderV2_X::ossimNitfFileHeaderV2_X() { } void ossimNitfFileHeaderV2_X::setComplexityLevel(const ossimString& level) { ossimNitfCommon::setField(theComplexityLevel, level, 2, std::ios::right, '0'); } void ossimNitfFileHeaderV2_X::setSystemType(const ossimString& systemType) { ossimNitfCommon::setField(theSystemType, systemType, 4); } void ossimNitfFileHeaderV2_X::setOriginatingStationId(const ossimString& originationId) { ossimNitfCommon::setField(theOriginatingStationId, originationId, 10); } ossimString ossimNitfFileHeaderV2_X::formatDate(const ossimString& version, const ossimLocalTm& d) { // Convert to ZULU as per spec for both versions. ossimLocalTm d1 = d.convertToGmt(); std::ostringstream out; if(version.contains("2.1")) { out << std::setw(4) << std::setfill('0') << d1.getYear() << std::setw(2) << std::setfill('0') << d1.getMonth() << std::setw(2) << std::setfill('0') << d1.getDay() << std::setw(2) << std::setfill('0') << d1.getHour() << std::setw(2) << std::setfill('0') << d1.getMin() << std::setw(2) << std::setfill('0') << d1.getSec(); } else { out << std::setw(2) << std::setfill('0') << d1.getDay() << std::setw(2) << std::setfill('0') << d1.getHour() << std::setw(2) << std::setfill('0') << d1.getMin() << std::setw(2) << std::setfill('0') << d1.getSec() << "Z" < property) { if(!property.valid()) return; ossimString name = property->getName(); // Make case insensitive: name.upcase(); if(name == FHDR_KW) { } else if(name == STYPE_KW) { setSystemType(property->valueToString()); } else if(name == OSTAID_KW) { setOriginatingStationId(property->valueToString()); } else if(name == FDT_KW) { setDate(property->valueToString()); } else if(name == FTITLE_KW) { setTitle(property->valueToString()); } else if(name == FSCLAS_KW) { setFileSecurityClassification(property->valueToString()); } else if(name == FSCODE_KW) { setCodeWords(property->valueToString()); } else if(name == FSCTLH_KW) { setControlAndHandling(property->valueToString()); } else if(name == FSREL_KW) { setReleasingInstructions(property->valueToString()); } else if(name == FSCAUT_KW) { setClassificationAuthority(property->valueToString()); } else if(name == FSCTLN_KW) { setSecurityControlNumber(property->valueToString()); } else if(name == FSCOP_KW) { setCopyNumber(property->valueToString()); } else if(name == FSCPYS_KW) { setNumberOfCopies(property->valueToString()); } else if(name == ENCRYP_KW) { setEncryption(property->valueToString()); } else if(name == ONAME_KW) { setOriginatorsName(property->valueToString()); } else if(name == OPHONE_KW) { setOriginatorsPhone(property->valueToString()); } else { ossimNitfFileHeader::setProperty(property); } } ossimRefPtr ossimNitfFileHeaderV2_X::getProperty(const ossimString& name)const { ossimRefPtr property = 0; if(name == FHDR_KW) { property = new ossimStringProperty(name, ossimString(theFileTypeVersion)); } else if(name == VERSION_KW) { property = new ossimStringProperty(name, ossimString(getVersion())); } else if(name == FILE_TYPE_KW) { property = new ossimStringProperty(name, "NITF"); } else if(name == CLEVEL_KW) { ossimNumericProperty* numericProperty = new ossimNumericProperty(name, getComplexityLevel(), 1, 99); numericProperty->setNumericType(ossimNumericProperty::ossimNumericPropertyType_INT); property = numericProperty; } else if(name == STYPE_KW) { property = new ossimStringProperty(name, getSystemType().trim()); } else if(name == OSTAID_KW) { property = new ossimStringProperty(name, getOriginatingStationId().trim()); } else if(name == FDT_KW) { property = new ossimStringProperty(name, getDate()); } else if(name == FTITLE_KW) { property = new ossimStringProperty(name, getTitle().trim()); } else if(name == FSCLAS_KW) { ossimStringProperty* stringProperty = new ossimStringProperty(name, getSecurityClassification().trim(), false); stringProperty->addConstraint(""); stringProperty->addConstraint("T"); stringProperty->addConstraint("S"); stringProperty->addConstraint("C"); stringProperty->addConstraint("R"); stringProperty->addConstraint("U"); property = stringProperty; } else if(name == FSCODE_KW) { property = new ossimStringProperty(name, getCodeWords().trim()); } else if(name == FSCTLH_KW) { property = new ossimStringProperty(name, getControlAndHandling().trim()); } else if(name == FSREL_KW) { property = new ossimStringProperty(name, getReleasingInstructions().trim()); } else if(name == FSCAUT_KW) { property = new ossimStringProperty(name, getClassificationAuthority().trim()); } else if(name == FSCTLN_KW) { property = new ossimStringProperty(name, getSecurityControlNumber().trim()); } else if(name == FSCOP_KW) { property = new ossimStringProperty(name, getCopyNumber().trim()); } else if(name == FSCPYS_KW) { property = new ossimStringProperty(name, getNumberOfCopies().trim()); } else if(name == ENCRYP_KW) { property = new ossimStringProperty(name, getEncryption().trim(), false); } else { property = ossimNitfFileHeader::getProperty(name).get(); } return property; } bool ossimNitfFileHeaderV2_X::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = ossimNitfFileHeader::saveState(kwl, prefix); if(result) { kwl.add(prefix, FHDR_KW.c_str(), theFileTypeVersion); kwl.add(prefix, CLEVEL_KW.c_str(), theComplexityLevel); kwl.add(prefix, STYPE_KW.c_str(), theSystemType); kwl.add(prefix, OSTAID_KW.c_str(), theOriginatingStationId); kwl.add(prefix, FDT_KW.c_str(), theDateTime); kwl.add(prefix, FTITLE_KW.c_str(), theFileTitle); kwl.add(prefix, FSCLAS_KW.c_str(), theSecurityClassification); kwl.add(prefix, FSCOP_KW.c_str(), theCopyNumber); kwl.add(prefix, FSCPYS_KW.c_str(), theNumberOfCopies); kwl.add(prefix, ENCRYP_KW.c_str(), theEncryption); } return result; } bool ossimNitfFileHeaderV2_X::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Note: Currently not looking up all fieds only ones that make sense. const char* lookup; lookup = kwl.find( prefix, CLEVEL_KW); if ( lookup ) { setComplexityLevel( ossimString(lookup) ); } lookup = kwl.find( prefix, STYPE_KW); if ( lookup ) { setSystemType( ossimString(lookup) ); } lookup = kwl.find( prefix, OSTAID_KW); if ( lookup ) { setOriginatingStationId( ossimString(lookup) ); } lookup = kwl.find( prefix, FDT_KW); if ( lookup ) { setDate( ossimString(lookup) ); } lookup = kwl.find( prefix, FTITLE_KW); if ( lookup ) { setTitle( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCLAS_KW); if ( lookup ) { setFileSecurityClassification( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCODE_KW); if ( lookup ) { setCodeWords( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCTLH_KW); if ( lookup ) { setControlAndHandling( ossimString(lookup) ); } lookup = kwl.find( prefix, FSREL_KW); if ( lookup ) { setReleasingInstructions( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCAUT_KW); if ( lookup ) { setClassificationAuthority( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCTLN_KW); if ( lookup ) { setSecurityControlNumber( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCOP_KW); if ( lookup ) { setCopyNumber( ossimString(lookup) ); } lookup = kwl.find( prefix, FSCPYS_KW); if ( lookup ) { setNumberOfCopies( ossimString(lookup) ); } lookup = kwl.find( prefix, ENCRYP_KW); if ( lookup ) { setEncryption( ossimString(lookup) ); } lookup = kwl.find( prefix, ONAME_KW); if ( lookup ) { setOriginatorsName( ossimString(lookup) ); } lookup = kwl.find( prefix, OPHONE_KW); if ( lookup ) { setOriginatorsPhone( ossimString(lookup) ); } return true; } void ossimNitfFileHeaderV2_X::getPropertyNames(std::vector& propertyNames)const { ossimNitfFileHeader::getPropertyNames(propertyNames); propertyNames.push_back(FILE_TYPE_KW); propertyNames.push_back(VERSION_KW); propertyNames.push_back(FHDR_KW); propertyNames.push_back(CLEVEL_KW); propertyNames.push_back(STYPE_KW); propertyNames.push_back(OSTAID_KW); propertyNames.push_back(FDT_KW); propertyNames.push_back(FTITLE_KW); propertyNames.push_back(FSCLAS_KW); propertyNames.push_back(FSCODE_KW); propertyNames.push_back(FSCTLH_KW); propertyNames.push_back(FSREL_KW); propertyNames.push_back(FSCAUT_KW); propertyNames.push_back(FSCTLN_KW); propertyNames.push_back(FSCOP_KW); propertyNames.push_back(FSCPYS_KW); propertyNames.push_back(ENCRYP_KW); propertyNames.push_back(ONAME_KW); propertyNames.push_back(OPHONE_KW); } ossim-Miami-2.9.1/src/support_data/ossimNitfGeoPositioningTag.cpp000066400000000000000000000116561352751253100252110ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfGeoPositioningTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfGeoPositioningTag, "ossimNitfGeoPositioningTag", ossimNitfRegisteredTag); ossimNitfGeoPositioningTag::ossimNitfGeoPositioningTag() : ossimNitfRegisteredTag(std::string("GEOPSB"), 443) { clearFields(); } ossimNitfGeoPositioningTag::~ossimNitfGeoPositioningTag() { } void ossimNitfGeoPositioningTag::parseStream(std::istream& in) { clearFields(); in.read(theType, 3); in.read(theCoordinateUnits, 3); in.read(theGeodeticDatumName, 80); in.read(theGeodeticDatumCode, 4); in.read(theEllipsoidName, 80); in.read(theEllipsoidCode, 3); in.read(theVerticalDatumReference, 80); in.read(theVerticalReferenceCode, 4); in.read(theSoundingDatumName, 80); in.read(theSoundingDatumCode, 4); in.read(theZFalseOrigin, 15); in.read(theGridCode, 3); in.read(theGridDescription, 80); in.read(theGridZoneNumber, 4); } void ossimNitfGeoPositioningTag::writeStream(std::ostream& out) { out.write(theType, 3); out.write(theCoordinateUnits, 3); out.write(theGeodeticDatumName, 80); out.write(theGeodeticDatumCode, 4); out.write(theEllipsoidName, 80); out.write(theEllipsoidCode, 3); out.write(theVerticalDatumReference, 80); out.write(theVerticalReferenceCode, 4); out.write(theSoundingDatumName, 80); out.write(theSoundingDatumCode, 4); out.write(theZFalseOrigin, 15); out.write(theGridCode, 3); out.write(theGridDescription, 80); out.write(theGridZoneNumber, 4); } void ossimNitfGeoPositioningTag::clearFields() { memset(theType, ' ', 3); memset(theCoordinateUnits, ' ', 3); memset(theGeodeticDatumName, ' ', 80); memset(theGeodeticDatumCode, ' ', 4); memset(theEllipsoidName, ' ', 80); memset(theEllipsoidCode, ' ', 3); memset(theVerticalDatumReference, ' ', 80); memset(theVerticalReferenceCode, ' ', 4); memset(theSoundingDatumName, ' ', 80); memset(theSoundingDatumCode, ' ', 4); memset(theZFalseOrigin, '0', 15); memset(theGridCode, ' ', 3); memset(theGridDescription, ' ', 80); memset(theGridZoneNumber, '0', 4); memcpy(theType, "MAP", 3); memcpy(theCoordinateUnits, "M ", 3); memcpy(theGeodeticDatumName, "World Geodetic System 1984", 26); memcpy(theGeodeticDatumCode, "WGE", 3); memcpy(theEllipsoidName, "World Geodetic System 1984", 26); memcpy(theEllipsoidCode, "WE", 2); memcpy(theVerticalDatumReference, "Geodetic", 8); memcpy(theVerticalReferenceCode, "GEOD", 4); memcpy(theSoundingDatumName, "Mean Sea", 8); memcpy(theSoundingDatumCode, "MSL", 3); theType[3] = '\0'; theCoordinateUnits[3] = '\0'; theGeodeticDatumName[80] = '\0'; theGeodeticDatumCode[4] = '\0'; theEllipsoidName[80] = '\0'; theEllipsoidCode[3] = '\0'; theVerticalDatumReference[80] = '\0'; theVerticalReferenceCode[4] = '\0'; theSoundingDatumName[80] = '\0'; theSoundingDatumCode[4] = '\0'; theZFalseOrigin[15] = '\0'; theGridCode[3] = '\0'; theGridDescription[80] = '\0'; theGridZoneNumber[4] = '\0'; } std::ostream& ossimNitfGeoPositioningTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "TYP:" << theType << "\n" << pfx << std::setw(24) << "UNI:" << theCoordinateUnits << "\n" << pfx << std::setw(24) << "DAG:" << theGeodeticDatumName << "\n" << pfx << std::setw(24) << "DCD:" << theGeodeticDatumCode << "\n" << pfx << std::setw(24) << "ELL:" << theEllipsoidName << "\n" << pfx << std::setw(24) << "ELC:" << theEllipsoidCode << "\n" << pfx << std::setw(24) << "DVR:" << theVerticalDatumReference << "\n" << pfx << std::setw(24) << "VDCDVR:" << theVerticalReferenceCode << "\n" << pfx << std::setw(24) << "SDA:" << theSoundingDatumName << "\n" << pfx << std::setw(24) << "VDCSDA:" << theSoundingDatumCode << "\n" << pfx << std::setw(24) << "ZOR:" << theZFalseOrigin << "\n" << pfx << std::setw(24) << "GRD:" << theGridCode << "\n" << pfx << std::setw(24) << "GRN:" << theGridDescription << "\n" << pfx << std::setw(24) << "ZNA:" << theGridZoneNumber << "\n"; return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfGeolobTag.cpp000066400000000000000000000125401352751253100234540ustar00rootroot00000000000000//--- // // License: MIT // // Author: David Burken // // Description: GEOLOB tag class definition. // // References: // // 1) DIGEST 2.1 Part 2 - Annex D // Appendix 1 - NSIF Standard Geospatial Support Data Extension // // 2) STDI-0006 // //--- // $Id: ossimNitfBlockaTag.cpp 23245 2015-04-08 20:53:04Z rashadkm $ #include /* for memcpy */ #include #include #include #include #include #include #include #include using namespace std; static const ossimTrace traceDebug(ossimString("ossimNitfBlockaTag:debug")); RTTI_DEF1(ossimNitfGeolobTag, "ossimNitfGeolobTag", ossimNitfRegisteredTag); ossimNitfGeolobTag::ossimNitfGeolobTag() : ossimNitfRegisteredTag(std::string("GEOLOB"), ossimNitfGeolobTag::TAG_SIZE), m_tagData(ossimNitfGeolobTag::TAG_SIZE, '0') { } void ossimNitfGeolobTag::parseStream(std::istream& in) { in.read((char*)m_tagData.data(), ossimNitfGeolobTag::TAG_SIZE); } void ossimNitfGeolobTag::writeStream(std::ostream& out) { out.write(m_tagData.data(), ossimNitfGeolobTag::TAG_SIZE); } std::ostream& ossimNitfGeolobTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "ARV:" << getArvString() << "\n" << pfx << std::setw(24) << "BRV:" << getBrvString() << "\n" << pfx << std::setw(24) << "LSO:" << getLsoString() << "\n" << pfx << std::setw(24) << "PSO:" << getPsoString() << "\n"; return out; } // Longitude density: std::string ossimNitfGeolobTag::getArvString() const { return m_tagData.substr(0, ossimNitfGeolobTag::ARV_SIZE); } ossim_uint32 ossimNitfGeolobTag::getArv() const { ossim_uint32 result = 0; std::string s = getArvString(); if ( s.size() ) { result = ossimString(s).toUInt32(); } return result; } ossim_float64 ossimNitfGeolobTag::getDegreesPerPixelLon() const { ossim_float64 result = 0.0; ossim_uint32 arv = getArv(); if ( arv > 0 ) { result = 360.0 / arv; } return result; } void ossimNitfGeolobTag::setArv(ossim_uint32 arv) { if ( (arv >= 2) && (arv <= 999999999) ) { std::ostringstream s; s.fill('0'); s << std::setw(ossimNitfGeolobTag::ARV_SIZE) << arv; m_tagData.replace( 0, ossimNitfGeolobTag::ARV_SIZE, s.str() ); } } void ossimNitfGeolobTag::setDegreesPerPixelLon(const ossim_float64& deltaLon) { if ( deltaLon > 0.0 ) { ossim_uint32 pixels = (ossim_uint32)((1.0/deltaLon)*360.0 + .5); setArv(pixels); } } // Latitude density: std::string ossimNitfGeolobTag::getBrvString() const { return m_tagData.substr(9, ossimNitfGeolobTag::BRV_SIZE); } ossim_float64 ossimNitfGeolobTag::getDegreesPerPixelLat() const { ossim_float64 result = 0.0; ossim_uint32 brv = getBrv(); if ( brv > 0 ) { result = 360.0 / brv; } return result; } ossim_uint32 ossimNitfGeolobTag::getBrv() const { ossim_uint32 result = 0; std::string s = getBrvString(); if ( s.size() ) { result = ossimString(s).toUInt32(); } return result; } void ossimNitfGeolobTag::setBrv(ossim_uint32 brv) { if ( (brv >= 2) && (brv <= 999999999) ) { std::ostringstream s; s.fill('0'); s << std::setw(ossimNitfGeolobTag::BRV_SIZE) << brv; m_tagData.replace( 9, ossimNitfGeolobTag::BRV_SIZE, s.str() ); } } void ossimNitfGeolobTag::setDegreesPerPixelLat(const ossim_float64& deltaLat) { if ( deltaLat > 0.0 ) { ossim_uint32 pixels = (ossim_uint32)((1.0/deltaLat)*360.0 + .5); setBrv(pixels); } } // Longitude of Reference Origin: std::string ossimNitfGeolobTag::getLsoString() const { return m_tagData.substr(18, ossimNitfGeolobTag::LSO_SIZE); } ossim_float64 ossimNitfGeolobTag::getLso() const { ossim_float64 result = 0; std::string s = getLsoString(); if ( s.size() ) { result = ossimString(s).toFloat64(); } return result; } void ossimNitfGeolobTag::setLso(const ossim_float64& lso) { if ( (lso >= -180.0) && (lso <= 180.0) ) { std::ostringstream s; s.precision(10); s.fill('0'); s << std::left << std::showpos << std::fixed << std::setw(ossimNitfGeolobTag::LSO_SIZE) << lso; m_tagData.replace( 18, ossimNitfGeolobTag::LSO_SIZE, s.str() ); } } // Latitude of Reference Origin: std::string ossimNitfGeolobTag::getPsoString() const { return m_tagData.substr(33, ossimNitfGeolobTag::PSO_SIZE); } ossim_float64 ossimNitfGeolobTag::getPso() const { ossim_float64 result = 0; std::string s = getPsoString(); if ( s.size() ) { result = ossimString(s).toFloat64(); } return result; } void ossimNitfGeolobTag::setPso(const ossim_float64& pso) { if ( (pso >= -180.0) && (pso <= 180.0) ) { std::ostringstream s; s.precision(10); s.fill('0'); s << std::left << std::showpos << std::fixed << std::setw(ossimNitfGeolobTag::PSO_SIZE) << pso; m_tagData.replace( 33, ossimNitfGeolobTag::PSO_SIZE, s.str() ); } } ossim-Miami-2.9.1/src/support_data/ossimNitfHistoaTag.cpp000066400000000000000000000331751352751253100235030ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: HISTOA tag class definition. // //---------------------------------------------------------------------------- // $Id: ossimNitfHistoaTag.cpp 23245 2015-04-08 20:53:04Z rashadkm $ #include #include #include #include using namespace std; ossimNitfHistoaProcessingEvent::ossimNitfHistoaProcessingEvent() { clearFields(); } ossim_uint32 ossimNitfHistoaProcessingEvent::getSizeInBytes()const { ossim_uint32 sizeInBytes = (PDATE_SIZE + PSITE_SIZE + PAS_SIZE + NIPCOM_SIZE); if ( (*m_nIpcom != '0') && m_comment.size() ) { sizeInBytes += ( m_comment.size() * IPCOM_SIZE ); } sizeInBytes += (IBPP_SIZE + IPVTYPE_SIZE + INBWC_SIZE + DISP_FLAG_SIZE + ROT_FLAG_SIZE); if(*m_rotFlag == '1') { sizeInBytes += ROT_ANGLE_SIZE; } sizeInBytes += ASYM_FLAG_SIZE; if(*m_asymFlag == '1') { sizeInBytes += (ZOOMROW_SIZE + ZOOMCOL_SIZE); } sizeInBytes += ( PROJ_FLAG_SIZE + SHARP_FLAG_SIZE ); if(*m_sharpFlag == '1') { sizeInBytes += (SHARPFAM_SIZE + SHARPMEM_SIZE); } sizeInBytes += MAG_FLAG_SIZE; if(*m_magFlag == '1') { sizeInBytes += MAG_LEVEL_SIZE; } sizeInBytes += DRA_FLAG_SIZE; if(*m_draFlag == '1') { sizeInBytes += (DRA_MULT_SIZE + DRA_SUB_SIZE); } sizeInBytes += TTC_FLAG_SIZE; if(*m_ttcFlag == '1') { sizeInBytes += (TTCFAM_SIZE + TTCMEM_SIZE); } sizeInBytes += DEVLUT_FLAG_SIZE + OBPP_SIZE + OPVTYPE_SIZE + OUTBWC_SIZE; return sizeInBytes; } void ossimNitfHistoaProcessingEvent::parseStream(std::istream& in) { clearFields(); in.read(m_pdate, PDATE_SIZE); in.read(m_psite, PSITE_SIZE); in.read(m_pas, PAS_SIZE); in.read(m_nIpcom, NIPCOM_SIZE); ossim_uint32 nIpcom = ossimString(m_nIpcom).toUInt32(); if(nIpcom < 10) { ossim_uint32 idx = 0; for(;idx < nIpcom;++idx) { char tempBuf[IPCOM_SIZE+1]; in.read(tempBuf, IPCOM_SIZE); tempBuf[IPCOM_SIZE] = '\0'; // m_comment += std::string(tempBuf, tempBuf + 80); m_comment.push_back( std::string(tempBuf) ); } } in.read(m_ibpp, IBPP_SIZE); in.read(m_ipvType, IPVTYPE_SIZE); in.read(m_inbwc, INBWC_SIZE); in.read(m_dispFlag, DISP_FLAG_SIZE); in.read(m_rotFlag, ROT_FLAG_SIZE); if(*m_rotFlag =='1') { in.read(m_rotAngle, ROT_ANGLE_SIZE); } in.read(m_asymFlag, ASYM_FLAG_SIZE); if(ossimString(m_asymFlag).toBool()) { in.read(m_zoomRow, ZOOMROW_SIZE); in.read(m_zoomCol, ZOOMCOL_SIZE); } in.read(m_projFlag, PROJ_FLAG_SIZE); in.read(m_sharpFlag, SHARP_FLAG_SIZE); if(ossimString(m_sharpFlag).toBool()) { in.read(m_sharpFam, SHARPFAM_SIZE); in.read(m_sharpMem, SHARPMEM_SIZE); } in.read(m_magFlag, MAG_FLAG_SIZE); if(ossimString(m_magFlag).toBool()) { in.read(m_magLevel, MAG_LEVEL_SIZE); } in.read(m_draFlag, DRA_FLAG_SIZE); if(ossimString(m_draFlag).toBool()) { in.read(m_draMult, DRA_MULT_SIZE); in.read(m_draSub, DRA_SUB_SIZE); } in.read(m_ttcFlag, TTC_FLAG_SIZE); if(ossimString(m_ttcFlag).toBool()) { in.read(m_ttcFam, TTCFAM_SIZE); in.read(m_ttcMem, TTCMEM_SIZE); } in.read(m_devLutFlag, DEVLUT_FLAG_SIZE); in.read(m_obpp, OBPP_SIZE); in.read(m_opvType, OPVTYPE_SIZE); in.read(m_outBwc, OUTBWC_SIZE); } void ossimNitfHistoaProcessingEvent::writeStream(std::ostream& out) { out.write(m_pdate, PDATE_SIZE); out.write(m_psite, PSITE_SIZE); out.write(m_pas, PAS_SIZE); out.write(m_nIpcom, NIPCOM_SIZE); ossim_uint32 nIpcom = ossimString(m_nIpcom).toUInt32(); if( (nIpcom > 0) && (nIpcom < 10) ) { for( ossim_uint32 i = 0; i < nIpcom; ++i ) { // Should size check std::string or make set method that ensures 80 chars. out.write( m_comment[i].data(), IPCOM_SIZE ); } } out.write(m_ibpp, IBPP_SIZE); out.write(m_ipvType, IPVTYPE_SIZE); out.write(m_inbwc, INBWC_SIZE); out.write(m_dispFlag, DISP_FLAG_SIZE); out.write(m_rotFlag, ROT_FLAG_SIZE); if(*m_rotFlag =='1') { out.write(m_rotAngle, ROT_ANGLE_SIZE); } out.write(m_asymFlag, ASYM_FLAG_SIZE); if(*m_asymFlag == '1') { out.write(m_zoomRow, ZOOMROW_SIZE); out.write(m_zoomCol, ZOOMCOL_SIZE); } out.write(m_projFlag, PROJ_FLAG_SIZE); out.write(m_sharpFlag, SHARP_FLAG_SIZE); if(*m_sharpFlag == '1') { out.write(m_sharpFam, SHARPFAM_SIZE); out.write(m_sharpMem, SHARPMEM_SIZE); } out.write(m_magFlag, MAG_FLAG_SIZE); if(*m_magFlag == '1') { out.write(m_magLevel, MAG_LEVEL_SIZE); } out.write(m_draFlag, DRA_FLAG_SIZE); if(*m_draFlag == '1') { out.write(m_draMult, DRA_MULT_SIZE); out.write(m_draSub, DRA_SUB_SIZE); } out.write(m_ttcFlag, TTC_FLAG_SIZE); if(*m_ttcFlag == '1') { out.write(m_ttcFam, TTCFAM_SIZE); out.write(m_ttcMem, TTCMEM_SIZE); } out.write(m_devLutFlag, DEVLUT_FLAG_SIZE); out.write(m_obpp, OBPP_SIZE); out.write(m_opvType, OPVTYPE_SIZE); out.write(m_outBwc, OUTBWC_SIZE); } std::ostream& ossimNitfHistoaProcessingEvent::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "PDATE:" << m_pdate << "\n" << pfx << std::setw(24) << "PSITE:" << m_psite << "\n" << pfx << std::setw(24) << "PAS:" << m_pas << "\n" << pfx << std::setw(24) << "NIPCOM:" << m_nIpcom << "\n"; ossim_uint32 nIpcom = ossimString(m_nIpcom).toUInt32(); if( ( nIpcom > 0 ) && ( nIpcom < 10 ) ) { for( ossim_uint32 i = 0; i < nIpcom; ++i ) { std::string s = "IPCOM"; //--- // NOTE: // Doing s += ossimString::toString( i ).string() core dumping linux gcc version 4.7.0. //--- std::string s2 = ossimString::toString( i ).string(); s += s2; s += ":"; out << pfx << std::setw(24) << s.c_str(); out.write( m_comment[i].data(), IPCOM_SIZE ); out << "\n"; } } out << setiosflags(std::ios::left) << pfx << std::setw(24) << "IBPP:" << m_ibpp << "\n" << pfx << std::setw(24) << "IPVTYPE:" << m_ipvType << "\n" << pfx << std::setw(24) << "INBWC:" << m_inbwc << "\n" << pfx << std::setw(24) << "DISP_FLAG:" << m_dispFlag << "\n" << pfx << std::setw(24) << "ROT_FLAG:" << m_rotFlag << "\n"; if(*m_rotFlag == '1') { out<< pfx << std::setw(24) << "ROT_ANGLE:" << m_rotAngle << "\n"; } out<< pfx << std::setw(24) << "ASYM_FLAG:" << m_asymFlag << "\n"; if(*m_asymFlag=='1') { out<< pfx << std::setw(24) << "ZOOMROW:" << m_zoomRow << "\n"; out<< pfx << std::setw(24) << "ZOOMCOL:" << m_zoomCol << "\n"; } out<< pfx << std::setw(24) << "PROJ_FLAG:" << m_projFlag << "\n"; out<< pfx << std::setw(24) << "SHARP_FLAG:" << *m_sharpFlag << "\n"; if(*m_sharpFlag == '1') { out<< pfx << std::setw(24) << "SHARPFAM:" << m_sharpFam << "\n"; out<< pfx << std::setw(24) << "SHARPMEM:" << m_sharpMem << "\n"; } out<< pfx << std::setw(24) << "MAG_FLAG:" << *m_magFlag << "\n"; if(*m_magFlag == '1') { out<< pfx << std::setw(24) << "MAG_LEVEL:" << m_magLevel << "\n"; } out<< pfx << std::setw(24) << "DRA_FLAG:" << *m_draFlag << "\n"; if(*m_draFlag=='1') { out<< pfx << std::setw(24) << "DRA_MULT:" << m_draMult << "\n"; out<< pfx << std::setw(24) << "DRA_SUB:" << m_draSub << "\n"; } out<< pfx << std::setw(24) << "TTC_FLAG:" << *m_ttcFlag << "\n"; if(*m_ttcFlag == '1') { out<< pfx << std::setw(24) << "TTCFAM:" << m_ttcFam << "\n"; out<< pfx << std::setw(24) << "TTCMEM:" << m_ttcMem << "\n"; } out<< pfx << std::setw(24) << "DEVLUT_FLAG:" << *m_devLutFlag << "\n"; out<< pfx << std::setw(24) << "OBPP:" << m_obpp << "\n"; out<< pfx << std::setw(24) << "OPVTYPE:" << m_opvType << "\n"; out<< pfx << std::setw(24) << "OUTBWC:" << m_outBwc << "\n"; return out; } void ossimNitfHistoaProcessingEvent::clearFields() { memset(m_pdate, ' ', PDATE_SIZE+1); memset(m_psite, ' ', PSITE_SIZE+1); memset(m_pas, ' ', PAS_SIZE+1); memset(m_nIpcom, ' ', NIPCOM_SIZE+1); memset(m_ibpp, ' ', IBPP_SIZE+1); memset(m_ipvType, ' ', IPVTYPE_SIZE+1); memset(m_inbwc, ' ', INBWC_SIZE); memset(m_dispFlag, 0, DISP_FLAG_SIZE); memset(m_rotFlag, 0, DISP_FLAG_SIZE); memset(m_rotAngle, 0, ROT_ANGLE_SIZE); m_rotAngle[3]='.'; memset(m_projFlag, 0, PROJ_FLAG_SIZE); memset(m_asymFlag, 0, ASYM_FLAG_SIZE); memset(m_zoomRow, 0, ZOOMROW_SIZE); m_zoomRow[2]='.'; memset(m_zoomCol, 0, ZOOMCOL_SIZE); m_zoomCol[2]='.'; memset(m_sharpFlag, 0, SHARP_FLAG_SIZE); memset(m_sharpFam, ' ', SHARPFAM_SIZE); memset(m_sharpMem, ' ', SHARPMEM_SIZE); memset(m_magFlag, 0, MAG_FLAG_SIZE); memset(m_magLevel, ' ', MAG_LEVEL_SIZE); memset(m_draFlag, 0, DRA_FLAG_SIZE); memset(m_draMult, ' ', DRA_MULT_SIZE); memset(m_draSub, ' ', DRA_SUB_SIZE); memset(m_ttcFlag, 0, TTC_FLAG_SIZE); memset(m_ttcFam, ' ', TTCFAM_SIZE); memset(m_ttcMem, ' ', TTCMEM_SIZE); memset(m_obpp, ' ', OBPP_SIZE); memset(m_opvType, ' ', OPVTYPE_SIZE); memset(m_outBwc, ' ', OUTBWC_SIZE); m_pdate[PDATE_SIZE] = '\0'; m_psite[PSITE_SIZE] = '\0'; m_pas[PAS_SIZE] = '\0'; m_nIpcom[NIPCOM_SIZE] = '\0'; m_ibpp[IBPP_SIZE] = '\0'; m_ipvType[IPVTYPE_SIZE] = '\0'; m_comment.clear(); m_inbwc[INBWC_SIZE] = '\0'; m_dispFlag[DISP_FLAG_SIZE] = '\0'; m_rotFlag[ROT_FLAG_SIZE] = '\0'; m_rotAngle[ROT_ANGLE_SIZE] = '\0'; m_projFlag[PROJ_FLAG_SIZE] = '\0'; m_asymFlag[ASYM_FLAG_SIZE] = '\0'; m_zoomRow[ZOOMROW_SIZE] = '\0'; m_zoomCol[ZOOMCOL_SIZE] = '\0'; m_sharpFlag[SHARP_FLAG_SIZE] = '\0'; m_sharpFam[SHARPFAM_SIZE] = '\0'; m_sharpMem[SHARPMEM_SIZE] = '\0'; m_magFlag[MAG_FLAG_SIZE] = '\0'; m_magLevel[MAG_LEVEL_SIZE] = '\0'; m_draFlag[DRA_FLAG_SIZE] = '\0'; m_draMult[DRA_MULT_SIZE] = '\0'; m_draSub[DRA_SUB_SIZE] = '\0'; m_ttcFlag[TTC_FLAG_SIZE] = '\0'; m_ttcFam[TTCFAM_SIZE] = '\0'; m_ttcMem[TTCMEM_SIZE] = '\0'; m_obpp[OBPP_SIZE] = '\0'; m_opvType[OPVTYPE_SIZE] = '\0'; m_outBwc[OUTBWC_SIZE] = '\0'; } ossimNitfHistoaTag::ossimNitfHistoaTag() : ossimNitfRegisteredTag( std::string("HISTOA"), 0 ) { } void ossimNitfHistoaTag::parseStream(std::istream& in) { clearFields(); in.read(m_systype, SYSTYPE_SIZE); in.read(m_pc, PC_SIZE); in.read(m_pe, PE_SIZE); in.read(m_remapFlag, REMAP_FLAG_SIZE); in.read(m_lutid, LUTID_SIZE); in.read(m_nEvents, NEVENTS_SIZE); ossim_uint32 nEvents = ossimString(m_nEvents).toUInt32(); if(nEvents < 100) { for(ossim_uint32 idx = 0; idx < nEvents; ++idx) { ossimNitfHistoaProcessingEvent evt; evt.parseStream(in); m_eventList.push_back(evt); } } // Set the tag length in base for the getTagLenth method. setTagLength( getSizeInBytes() ); } void ossimNitfHistoaTag::writeStream(std::ostream& out) { out.write(m_systype, SYSTYPE_SIZE); out.write(m_pc, PC_SIZE); out.write(m_pe, PE_SIZE); out.write(m_remapFlag, REMAP_FLAG_SIZE); out.write(m_lutid, LUTID_SIZE); out.write(m_nEvents, NEVENTS_SIZE); ossim_uint32 idx = 0; ossim_uint32 nEvents = ossimString(m_nEvents).toUInt32(); if(nEvents < 100) { for(;idx < nEvents; ++idx) { m_eventList[idx].writeStream(out); } } } ossim_uint32 ossimNitfHistoaTag::getSizeInBytes()const { // Make this dynamic for constructed HISTOA tags instead of using theTagLength. ossim_uint32 sizeInBytes = (SYSTYPE_SIZE + PC_SIZE + PE_SIZE + REMAP_FLAG_SIZE + LUTID_SIZE + NEVENTS_SIZE); for ( ossim_uint32 idx = 0; idx < m_eventList.size(); ++idx) { sizeInBytes += m_eventList[idx].getSizeInBytes(); } return sizeInBytes; } void ossimNitfHistoaTag::clearFields() { memset(m_systype, ' ', SYSTYPE_SIZE); memset(m_pc, ' ', PC_SIZE); memset(m_pe, ' ', PE_SIZE); memset(m_remapFlag, ' ', REMAP_FLAG_SIZE); memset(m_lutid, '0', LUTID_SIZE); memset(m_nEvents, '0', NEVENTS_SIZE); m_systype[SYSTYPE_SIZE] = '\0'; m_pc[PC_SIZE] = '\0'; m_pe[PE_SIZE] = '\0'; m_remapFlag[REMAP_FLAG_SIZE] = '\0'; m_lutid[LUTID_SIZE] = '\0'; m_nEvents[NEVENTS_SIZE] = '\0'; m_eventList.clear(); // Clear the tag length in base. setTagLength(0); } std::ostream& ossimNitfHistoaTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getSizeInBytes() << "\n" << pfx << std::setw(24) << "SYSTYPE:" << m_systype << "\n" << pfx << std::setw(24) << "PC:" << m_pc << "\n" << pfx << std::setw(24) << "PE:" << m_pe << "\n" << pfx << std::setw(24) << "REMAP_FLAG:" << m_remapFlag << "\n" << pfx << std::setw(24) << "LUTID:" << m_lutid << "\n" << pfx << std::setw(24) << "NEVENTS:" << m_nEvents << "\n"; for ( ossim_uint32 idx = 0; idx < m_eventList.size(); ++idx ) { m_eventList[idx].print(out, pfx+"EVENT"+ossimString::toString(idx)); } return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfIchipbTag.cpp000066400000000000000000000441011352751253100234410ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: ICHIPB tag class declaration. // // See document STDI-0002 Table 5-2 for more info. // // http://164.214.2.51/ntb/baseline/docs/stdi0002/final.pdf // //---------------------------------------------------------------------------- // $Id: ossimNitfIchipbTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include /* for memcpy */ #include #include #include #include #include #include #include #include using namespace std; static const ossimString XFRM_FLAG_KW = "XFRM_FLAG"; static const ossimString SCALE_FACTOR_KW = "SCALE_FACTOR"; static const ossimString ANAMRPH_CORR_KW = "ANAMRPH_CORR"; static const ossimString SCANBLK_NUM_KW = "SCANBLK_NUM"; static const ossimString OP_ROW_11_KW = "OP_ROW_11"; static const ossimString OP_COL_11_KW = "OP_COL_11"; static const ossimString OP_ROW_12_KW = "OP_ROW_12"; static const ossimString OP_COL_12_KW = "OP_COL_12"; static const ossimString OP_ROW_21_KW = "OP_ROW_21"; static const ossimString OP_COL_21_KW = "OP_COL_21"; static const ossimString OP_ROW_22_KW = "OP_ROW_22"; static const ossimString OP_COL_22_KW = "OP_COL_22"; static const ossimString FI_ROW_11_KW = "FI_ROW_11"; static const ossimString FI_COL_11_KW = "FI_COL_11"; static const ossimString FI_ROW_12_KW = "FI_ROW_12"; static const ossimString FI_COL_12_KW = "FI_COL_12"; static const ossimString FI_ROW_21_KW = "FI_ROW_21"; static const ossimString FI_COL_21_KW = "FI_COL_21"; static const ossimString FI_ROW_22_KW = "FI_ROW_22"; static const ossimString FI_COL_22_KW = "FI_COL_22"; static const ossimString FI_ROW_KW = "FI_ROW"; static const ossimString FI_COL_KW = "FI_COL"; RTTI_DEF1(ossimNitfIchipbTag, "ossimNitfIchipbTag", ossimNitfRegisteredTag); ossimNitfIchipbTag::ossimNitfIchipbTag() : ossimNitfRegisteredTag(std::string("ICHIPB"), 224) { clearFields(); } void ossimNitfIchipbTag::parseStream(std::istream& in) { clearFields(); in.read(theXfrmFlag, XFRM_FLAG_SIZE); in.read(theScaleFactor, SCALE_FACTOR_SIZE); in.read(theAnamrphCorr, ANAMRPH_CORR_SIZE); in.read(theScanBlock, SCANBLK_NUM_SIZE); in.read(theOpRow11, OP_ROW_11_SIZE); in.read(theOpCol11, OP_COL_11_SIZE); in.read(theOpRow12, OP_ROW_12_SIZE); in.read(theOpCol12, OP_COL_12_SIZE); in.read(theOpRow21, OP_ROW_21_SIZE); in.read(theOpCol21, OP_COL_21_SIZE); in.read(theOpRow22, OP_ROW_22_SIZE); in.read(theOpCol22, OP_COL_22_SIZE); in.read(theFiRow11, FI_ROW_11_SIZE); in.read(theFiCol11, FI_COL_11_SIZE); in.read(theFiRow12, FI_ROW_12_SIZE); in.read(theFiCol12, FI_COL_12_SIZE); in.read(theFiRow21, FI_ROW_21_SIZE); in.read(theFiCol21, FI_COL_21_SIZE); in.read(theFiRow22, FI_ROW_22_SIZE); in.read(theFiCol22, FI_COL_22_SIZE); in.read(theFullImageRow, FI_ROW_SIZE); in.read(theFullImageCol, FI_COL_SIZE); } void ossimNitfIchipbTag::writeStream(std::ostream& out) { out.write(theXfrmFlag, XFRM_FLAG_SIZE); out.write(theScaleFactor, SCALE_FACTOR_SIZE); out.write(theAnamrphCorr, ANAMRPH_CORR_SIZE); out.write(theScanBlock, SCANBLK_NUM_SIZE); out.write(theOpRow11, OP_ROW_11_SIZE); out.write(theOpCol11, OP_COL_11_SIZE); out.write(theOpRow12, OP_ROW_12_SIZE); out.write(theOpCol12, OP_COL_12_SIZE); out.write(theOpRow21, OP_ROW_21_SIZE); out.write(theOpCol21, OP_COL_21_SIZE); out.write(theOpRow22, OP_ROW_22_SIZE); out.write(theOpCol22, OP_COL_22_SIZE); out.write(theFiRow11, FI_ROW_11_SIZE); out.write(theFiCol11, FI_COL_11_SIZE); out.write(theFiRow12, FI_ROW_12_SIZE); out.write(theFiCol12, FI_COL_12_SIZE); out.write(theFiRow21, FI_ROW_21_SIZE); out.write(theFiCol21, FI_COL_21_SIZE); out.write(theFiRow22, FI_ROW_22_SIZE); out.write(theFiCol22, FI_COL_22_SIZE); out.write(theFullImageRow, FI_ROW_SIZE); out.write(theFullImageCol, FI_COL_SIZE); } void ossimNitfIchipbTag::clearFields() { memset(theXfrmFlag, '0', XFRM_FLAG_SIZE); memset(theScaleFactor, '0', SCALE_FACTOR_SIZE); memset(theAnamrphCorr, '0', ANAMRPH_CORR_SIZE); memset(theScanBlock, '0', SCANBLK_NUM_SIZE); memset(theOpRow11, '0', OP_ROW_11_SIZE); memset(theOpCol11, '0', OP_COL_11_SIZE); memset(theOpRow12, '0', OP_ROW_12_SIZE); memset(theOpCol12, '0', OP_COL_12_SIZE); memset(theOpRow21, '0', OP_ROW_21_SIZE); memset(theOpCol21, '0', OP_COL_21_SIZE); memset(theOpRow22, '0', OP_ROW_22_SIZE); memset(theOpCol22, '0', OP_COL_22_SIZE); memset(theFiRow11, '0', FI_ROW_11_SIZE); memset(theFiCol11, '0', FI_COL_11_SIZE); memset(theFiRow12, '0', FI_ROW_12_SIZE); memset(theFiCol12, '0', FI_COL_12_SIZE); memset(theFiRow21, '0', FI_ROW_21_SIZE); memset(theFiCol21, '0', FI_COL_21_SIZE); memset(theFiRow22, '0', FI_ROW_22_SIZE); memset(theFiCol22, '0', FI_COL_22_SIZE); memset(theFullImageRow, '0', FI_ROW_SIZE); memset(theFullImageCol, '0', FI_COL_SIZE); theXfrmFlag[XFRM_FLAG_SIZE] = '\0'; theScaleFactor[SCALE_FACTOR_SIZE] = '\0'; theAnamrphCorr[ANAMRPH_CORR_SIZE] = '\0'; theScanBlock[SCANBLK_NUM_SIZE] = '\0'; theOpRow11[OP_ROW_11_SIZE] = '\0'; theOpCol11[OP_COL_11_SIZE] = '\0'; theOpRow12[OP_ROW_12_SIZE] = '\0'; theOpCol12[OP_COL_12_SIZE] = '\0'; theOpRow21[OP_ROW_21_SIZE] = '\0'; theOpCol21[OP_COL_21_SIZE] = '\0'; theOpRow22[OP_ROW_22_SIZE] = '\0'; theOpCol22[OP_COL_22_SIZE] = '\0'; theFiRow11[FI_ROW_11_SIZE] = '\0'; theFiCol11[FI_COL_11_SIZE] = '\0'; theFiRow12[FI_ROW_12_SIZE] = '\0'; theFiCol12[FI_COL_12_SIZE] = '\0'; theFiRow21[FI_ROW_21_SIZE] = '\0'; theFiCol21[FI_COL_21_SIZE] = '\0'; theFiRow22[FI_ROW_22_SIZE] = '\0'; theFiCol22[FI_COL_22_SIZE] = '\0'; theFullImageRow[FI_ROW_SIZE] = '\0'; theFullImageCol[FI_COL_SIZE] = '\0'; } std::ostream& ossimNitfIchipbTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "XFRM_FLAG:" << theXfrmFlag << "\n" << pfx << std::setw(24) << "SCALE_FACTOR:" << theScaleFactor << "\n" << pfx << std::setw(24) << "ANAMRPH_CORR:" << theAnamrphCorr << "\n" << pfx << std::setw(24) << "SCANBLK_NUM:" << theScanBlock << "\n" << pfx << std::setw(24) << "OP_ROW_11:" << theOpRow11 << "\n" << pfx << std::setw(24) << "OP_COL_11:" << theOpCol11 << "\n" << pfx << std::setw(24) << "OP_ROW_12:" << theOpRow12 << "\n" << pfx << std::setw(24) << "OP_COL_12:" << theOpCol12 << "\n" << pfx << std::setw(24) << "OP_ROW_21:" << theOpRow21 << "\n" << pfx << std::setw(24) << "OP_COL_21:" << theOpCol21 << "\n" << pfx << std::setw(24) << "OP_ROW_22:" << theOpRow22 << "\n" << pfx << std::setw(24) << "OP_COL_22:" << theOpCol22 << "\n" << pfx << std::setw(24) << "FI_ROW_11:" << theFiRow11 << "\n" << pfx << std::setw(24) << "FI_COL_11:" << theFiCol11 << "\n" << pfx << std::setw(24) << "FI_ROW_12:" << theFiRow12 << "\n" << pfx << std::setw(24) << "FI_COL_12:" << theFiCol12 << "\n" << pfx << std::setw(24) << "FI_ROW_21:" << theFiRow21 << "\n" << pfx << std::setw(24) << "FI_COL_21:" << theFiCol21 << "\n" << pfx << std::setw(24) << "FI_ROW_22:" << theFiRow22 << "\n" << pfx << std::setw(24) << "FI_COL_22:" << theFiCol22 << "\n" << pfx << std::setw(24) << "FI_ROW:" << theFullImageRow << "\n" << pfx << std::setw(24) << "FI_COL:" << theFullImageCol << std::endl; return out; } bool ossimNitfIchipbTag::getXfrmFlag() const { return ossimString::toBool(theXfrmFlag); } ossim_float64 ossimNitfIchipbTag::getScaleFactor() const { return ossimString::toFloat64(theScaleFactor); } bool ossimNitfIchipbTag::getAnamrphCorrFlag() const { return ossimString::toBool(theAnamrphCorr); } ossim_uint32 ossimNitfIchipbTag::getScanBlock() const { return ossimString::toUInt32(theScanBlock); } ossim_float64 ossimNitfIchipbTag::getOpRow11() const { return ossimString::toFloat64(theOpRow11); } ossim_float64 ossimNitfIchipbTag::getOpCol11() const { return ossimString::toFloat64(theOpCol11); } ossim_float64 ossimNitfIchipbTag::getOpRow12() const { return ossimString::toFloat64(theOpRow12); } ossim_float64 ossimNitfIchipbTag::getOpCol12() const { return ossimString::toFloat64(theOpCol12); } ossim_float64 ossimNitfIchipbTag::getOpRow21() const { return ossimString::toFloat64(theOpRow21); } ossim_float64 ossimNitfIchipbTag::getOpCol21() const { return ossimString::toFloat64(theOpCol21); } ossim_float64 ossimNitfIchipbTag::getOpRow22() const { return ossimString::toFloat64(theOpRow22); } ossim_float64 ossimNitfIchipbTag::getOpCol22() const { return ossimString::toFloat64(theOpCol22); } ossim_float64 ossimNitfIchipbTag::getFiRow11() const { return ossimString::toFloat64(theFiRow11); } ossim_float64 ossimNitfIchipbTag::getFiCol11() const { return ossimString::toFloat64(theFiCol11); } ossim_float64 ossimNitfIchipbTag::getFiRow12() const { return ossimString::toFloat64(theFiRow12); } ossim_float64 ossimNitfIchipbTag::getFiCol12() const { return ossimString::toFloat64(theFiCol12); } ossim_float64 ossimNitfIchipbTag::getFiRow21() const { return ossimString::toFloat64(theFiRow21); } ossim_float64 ossimNitfIchipbTag::getFiCol21() const { return ossimString::toFloat64(theFiCol21); } ossim_float64 ossimNitfIchipbTag::getFiRow22() const { return ossimString::toFloat64(theFiRow22); } ossim_float64 ossimNitfIchipbTag::getFiCol22() const { return ossimString::toFloat64(theFiCol22); } ossim_uint32 ossimNitfIchipbTag::getFullImageRows() const { return ossimString::toUInt32(theFullImageRow); } ossim_uint32 ossimNitfIchipbTag::getFullImageCols() const { return ossimString::toUInt32(theFullImageCol); } #if 0 void ossimNitfIchipbTag::getImageRect(ossimDrect& rect) const { ossimDpt pt; pt.x = getOpCol11() - 0.5; pt.y = getOpRow11() - 0.5; rect.set_ul(pt); pt.x = getOpCol22() - 0.5; pt.y = getOpRow22() - 0.5; rect.set_lr(pt); } void ossimNitfIchipbTag::getFullImageRect(ossimDrect& rect) const { ossimDpt pt; ossim_float64 minX = ossim::min(getFiCol11(), getFiCol22()); ossim_float64 maxX = ossim::max(getFiCol11(), getFiCol22()); ossim_float64 minY = ossim::min(getFiRow11(), getFiRow22()); ossim_float64 maxY = ossim::max(getFiRow11(), getFiRow22()); pt.x = minX - 0.5; pt.y = minY - 0.5; rect.set_ul(pt); pt.x = maxX - 0.5; pt.y = maxY - 0.5; rect.set_lr(pt); } void ossimNitfIchipbTag::getSubImageOffset(ossimDpt& pt) const { ossimDrect rect; getFullImageRect(rect); pt = rect.ul(); } #endif ossim2dTo2dTransform* ossimNitfIchipbTag::newTransform()const { return new ossim2dBilinearTransform(ossimDpt(getOpCol11(), getOpRow11()), ossimDpt(getOpCol12(), getOpRow12()), ossimDpt(getOpCol21(), getOpRow21()), ossimDpt(getOpCol22(), getOpRow22()), ossimDpt(getFiCol11(), getFiRow11()), ossimDpt(getFiCol12(), getFiRow12()), ossimDpt(getFiCol21(), getFiRow21()), ossimDpt(getFiCol22(), getFiRow22())); } void ossimNitfIchipbTag::setProperty(ossimRefPtr property) { ossimNitfRegisteredTag::setProperty(property); } ossimRefPtr ossimNitfIchipbTag::getProperty(const ossimString& name)const { ossimProperty* result = 0; if(name == XFRM_FLAG_KW) { result = new ossimStringProperty(name, theXfrmFlag); } else if(name == SCALE_FACTOR_KW) { result = new ossimStringProperty(name, theScaleFactor); } else if(name == ANAMRPH_CORR_KW) { result = new ossimStringProperty(name, theAnamrphCorr); } else if(name == SCANBLK_NUM_KW) { result = new ossimStringProperty(name, theScanBlock); } else if(name == OP_ROW_11_KW) { result = new ossimStringProperty(name, theOpRow11); } else if(name == OP_COL_11_KW) { result = new ossimStringProperty(name, theOpCol11); } else if(name == OP_ROW_12_KW) { result = new ossimStringProperty(name,theOpRow12 ); } else if(name == OP_COL_12_KW) { result = new ossimStringProperty(name, theOpCol12); } else if(name == OP_ROW_21_KW) { result = new ossimStringProperty(name,theOpRow21); } else if(name == OP_COL_21_KW) { result = new ossimStringProperty(name, theOpCol21); } else if(name == OP_ROW_22_KW) { result = new ossimStringProperty(name, theOpRow22); } else if(name == OP_COL_22_KW) { result = new ossimStringProperty(name, theOpCol22); } else if(name == FI_ROW_11_KW) { result = new ossimStringProperty(name, theFiRow11); } else if(name == FI_COL_11_KW) { result = new ossimStringProperty(name, theFiCol11); } else if(name == FI_ROW_12_KW) { result = new ossimStringProperty(name, theFiRow12); } else if(name == FI_COL_12_KW) { result = new ossimStringProperty(name, theFiCol12); } else if(name == FI_ROW_21_KW) { result = new ossimStringProperty(name, theFiRow21); } else if(name == FI_COL_21_KW) { result = new ossimStringProperty(name, theFiCol21); } else if(name == FI_ROW_22_KW) { result = new ossimStringProperty(name, theFiRow22); } else if(name == FI_COL_22_KW) { result = new ossimStringProperty(name, theFiCol22); } else if(name == FI_ROW_KW) { result = new ossimStringProperty(name, theFullImageRow); } else if(name == FI_COL_KW) { result = new ossimStringProperty(name, theFullImageCol); } else { return ossimNitfRegisteredTag::getProperty(name); } return result; } void ossimNitfIchipbTag::getPropertyNames(std::vector& propertyNames)const { ossimNitfRegisteredTag::getPropertyNames(propertyNames); propertyNames.push_back(XFRM_FLAG_KW); propertyNames.push_back(SCALE_FACTOR_KW); propertyNames.push_back(ANAMRPH_CORR_KW); propertyNames.push_back(SCANBLK_NUM_KW); propertyNames.push_back(OP_ROW_11_KW); propertyNames.push_back(OP_COL_11_KW); propertyNames.push_back(OP_ROW_12_KW); propertyNames.push_back(OP_COL_12_KW); propertyNames.push_back(OP_ROW_21_KW); propertyNames.push_back(OP_COL_21_KW); propertyNames.push_back(OP_ROW_22_KW); propertyNames.push_back(OP_COL_22_KW); propertyNames.push_back(FI_ROW_11_KW); propertyNames.push_back(FI_COL_11_KW); propertyNames.push_back(FI_ROW_12_KW); propertyNames.push_back(FI_COL_12_KW); propertyNames.push_back(FI_ROW_21_KW); propertyNames.push_back(FI_COL_21_KW); propertyNames.push_back(FI_ROW_22_KW); propertyNames.push_back(FI_COL_22_KW); propertyNames.push_back(FI_ROW_KW); propertyNames.push_back(FI_COL_KW); } bool ossimNitfIchipbTag::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup; lookup = kwl.find(prefix, XFRM_FLAG_KW); if(lookup) { strcpy(theXfrmFlag, lookup); } lookup = kwl.find(prefix, SCALE_FACTOR_KW); if(lookup) { strcpy(theScaleFactor, lookup); } lookup = kwl.find(prefix, ANAMRPH_CORR_KW); if(lookup) { strcpy(theAnamrphCorr, lookup); } lookup = kwl.find(prefix, SCANBLK_NUM_KW); if(lookup) { strcpy(theScanBlock, lookup); } lookup = kwl.find(prefix, OP_ROW_11_KW); if(lookup) { strcpy(theOpRow11, lookup); } lookup = kwl.find(prefix, OP_COL_11_KW); if(lookup) { strcpy(theOpCol11, lookup); } lookup = kwl.find(prefix, OP_ROW_12_KW); if(lookup) { strcpy(theOpRow12, lookup); } lookup = kwl.find(prefix, OP_COL_12_KW); if(lookup) { strcpy(theOpCol12, lookup); } lookup = kwl.find(prefix, OP_ROW_21_KW); if(lookup) { strcpy(theOpRow21, lookup); } lookup = kwl.find(prefix, OP_COL_21_KW); if(lookup) { strcpy(theOpCol21, lookup); } lookup = kwl.find(prefix, OP_ROW_22_KW); if(lookup) { strcpy(theOpRow22, lookup); } lookup = kwl.find(prefix, OP_COL_22_KW); if(lookup) { strcpy(theOpCol22, lookup); } lookup = kwl.find(prefix, FI_ROW_11_KW); if(lookup) { strcpy(theFiRow11, lookup); } lookup = kwl.find(prefix, FI_COL_11_KW); if(lookup) { strcpy(theFiCol11, lookup); } lookup = kwl.find(prefix, FI_ROW_12_KW); if(lookup) { strcpy(theFiRow12, lookup); } lookup = kwl.find(prefix, FI_COL_12_KW); if(lookup) { strcpy(theFiCol12, lookup); } lookup = kwl.find(prefix, FI_ROW_21_KW); if(lookup) { strcpy(theFiRow21, lookup); } lookup = kwl.find(prefix, FI_COL_21_KW); if(lookup) { strcpy(theFiCol21, lookup); } lookup = kwl.find(prefix, FI_ROW_22_KW); if(lookup) { strcpy(theFiRow22, lookup); } lookup = kwl.find(prefix, FI_COL_22_KW); if(lookup) { strcpy(theFiCol22, lookup); } lookup = kwl.find(prefix, FI_ROW_KW); if(lookup) { strcpy(theFullImageRow, lookup); } lookup = kwl.find(prefix, FI_COL_KW); if(lookup) { strcpy(theFullImageCol, lookup); } return true; } ossim-Miami-2.9.1/src/support_data/ossimNitfImageBand.cpp000066400000000000000000000012371352751253100234210ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfImageBand.cpp 14241 2009-04-07 19:59:23Z dburken $ #include #include #include RTTI_DEF1(ossimNitfImageBand, "ossimNitfImageBand", ossimObject); ossimNitfImageBand::ossimNitfImageBand() { } ossimNitfImageBand::~ossimNitfImageBand() { } ossim-Miami-2.9.1/src/support_data/ossimNitfImageBandV2_0.cpp000066400000000000000000000127331352751253100240530ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfImageBandV2_0.cpp 23245 2015-04-08 20:53:04Z rashadkm $ #include #include #include #include #include ossimNitfImageBandV2_0::ossimNitfImageBandV2_0() { clearFields(); } ossimNitfImageBandV2_0::~ossimNitfImageBandV2_0() { } void ossimNitfImageBandV2_0::parseStream(std::istream& in) { theLookupTables.clear(); if(in) { theLookupTables.clear(); in.read(theBandRepresentation, 2); in.read(theBandSignificance, 6); in.read(theBandImageFilterCondition, 1); in.read(theBandStandardImageFilterCode, 3); in.read(theBandNumberOfLuts, 1); long numberOfLuts = ossimString(theBandNumberOfLuts).toLong(); if(numberOfLuts > 0) { theLookupTables.resize(numberOfLuts); in.read(theBandNumberOfLutEntries, 5); ossim_uint32 numberOfLutsIndex = numberOfLuts; ossim_uint32 numberOfLutEntries = ossimString(theBandNumberOfLutEntries).toLong(); ossim_uint32 idx = 0; while(idx < numberOfLutsIndex) { theLookupTables[idx] = new ossimNitfImageLutV2_0; theLookupTables[idx]->setNumberOfEntries(numberOfLutEntries); theLookupTables[idx]->parseStream(in); ++idx; } } } } void ossimNitfImageBandV2_0::writeStream(std::ostream& out) { out.write(theBandRepresentation, 2); out.write(theBandSignificance, 6); out.write(theBandImageFilterCondition, 1); out.write(theBandStandardImageFilterCode, 3); out.write(theBandNumberOfLuts, 1); if(ossimString(theBandNumberOfLuts).toUInt32() > 0) { // lut output not supported currently } } std::ostream& ossimNitfImageBandV2_0::print(std::ostream& out, const std::string& prefix, ossim_uint32 band)const { std::ostringstream os; os << std::setw(3) << std::setfill('0') << (band+1) << ":"; ossimString tmpStr = "IREPBAND"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theBandRepresentation << "\n"; tmpStr = "ISUBCAT"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theBandSignificance << "\n"; tmpStr = "IFC"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theBandImageFilterCondition << "\n"; tmpStr = "IMFLT"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theBandStandardImageFilterCode << "\n"; tmpStr = "NLUTS"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theBandNumberOfLuts << "\n"; tmpStr = "NELUTS"; tmpStr += os.str(); out << prefix << std::setw(24) << tmpStr << theBandNumberOfLutEntries << "\n"; for(ossim_uint32 idx = 0; idx < theLookupTables.size(); ++idx) { out << *theLookupTables[idx] << std::endl; } return out; } ossim_uint32 ossimNitfImageBandV2_0::getNumberOfLuts()const { return static_cast(theLookupTables.size()); } const ossimRefPtr ossimNitfImageBandV2_0::getLut(ossim_uint32 idx)const { if(idx < getNumberOfLuts()) { return theLookupTables[idx]; } return NULL; } ossimRefPtr ossimNitfImageBandV2_0::getLut(ossim_uint32 idx) { if(idx < getNumberOfLuts()) { return theLookupTables[idx]; } return NULL; } ossimString ossimNitfImageBandV2_0::getBandRepresentation()const { return ossimString(theBandRepresentation); } void ossimNitfImageBandV2_0::setBandRepresentation(const ossimString& rep) { std::ostringstream out; out << std::setw(2) << std::setfill(' ') << std::setiosflags(std::ios::left) << rep.c_str(); memcpy(theBandRepresentation, out.str().c_str(), 2); } ossimString ossimNitfImageBandV2_0::getBandSignificance()const { return ossimString(theBandSignificance); } void ossimNitfImageBandV2_0::setBandSignificance(const ossimString& rep) { std::ostringstream out; out << std::setw(6) << std::setfill(' ') << rep.c_str(); memcpy(theBandSignificance, out.str().c_str(), 6); } void ossimNitfImageBandV2_0::clearFields() { memset(theBandRepresentation, ' ', 2); memset(theBandSignificance, ' ', 6); memset(theBandImageFilterCondition, 'N', 1); memset(theBandStandardImageFilterCode, ' ', 3); memset(theBandNumberOfLutEntries, ' ', 5); theLookupTables.clear(); theBandRepresentation[2] = '\0'; theBandSignificance[6] = '\0'; theBandImageFilterCondition[1] = '\0'; theBandStandardImageFilterCode[3] = '\0'; theBandNumberOfLuts[0] = 0x30; theBandNumberOfLuts[1] = '\0'; theBandNumberOfLutEntries[5] = '\0'; } void ossimNitfImageBandV2_0::printLookupTables(std::ostream& out)const { std::vector >::const_iterator tables; tables = theLookupTables.begin(); while(tables != theLookupTables.end()) { if((*tables).valid()) { out << *((*tables).get()); } ++tables; if(tables != theLookupTables.end()) { out << std::endl; } } } ossim-Miami-2.9.1/src/support_data/ossimNitfImageBandV2_1.cpp000066400000000000000000000010251352751253100240440ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Nitf support class. Copied from ossimNitfImageBandV2_0. // //******************************************************************** // $Id: ossimNitfImageBandV2_1.cpp 9147 2006-06-20 14:17:50Z dburken $ #include ossimNitfImageBandV2_1::ossimNitfImageBandV2_1() { } ossimNitfImageBandV2_1::~ossimNitfImageBandV2_1() { } ossim-Miami-2.9.1/src/support_data/ossimNitfImageDataMaskV2_1.cpp000066400000000000000000000043351352751253100246740ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2007 Ball Aerspace & Technologies Corp // // LICENSE: See top level LICENSE.txt file. // // Author: Lucas Eckels // // Description: Nitf support class // //******************************************************************** // $Id: $ #include #include ossimNitfImageDataMaskV2_1::ossimNitfImageDataMaskV2_1() : theBlockLength(0) { } void ossimNitfImageDataMaskV2_1::setBlockCount(ossim_uint32 blockCount) { theIncludedBlocks.resize(blockCount, true); } void ossimNitfImageDataMaskV2_1::setBlockLengthInBytes(ossim_uint32 blockLength) { theBlockLength = blockLength; } void ossimNitfImageDataMaskV2_1::setIncludeBlock(ossim_uint32 blockNumber, bool included) { if (blockNumber < theIncludedBlocks.size()) { theIncludedBlocks[blockNumber] = included; } } void ossimNitfImageDataMaskV2_1::writeStream(std::ostream &out) { ossimEndian endian; ossim_uint32 imdatoff = 4 + 2 + 2 + 2 + 4 * theIncludedBlocks.size(); ossim_uint16 bmrlnth = 4; // only support band mask ossim_uint16 tmrlnth = 0; ossim_uint16 tpxcdlnth = 0; if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(imdatoff); endian.swap(bmrlnth); endian.swap(tmrlnth); endian.swap(tpxcdlnth); } out.write(reinterpret_cast(&imdatoff), sizeof(imdatoff)); out.write(reinterpret_cast(&bmrlnth), sizeof(bmrlnth)); out.write(reinterpret_cast(&tmrlnth), sizeof(tmrlnth)); out.write(reinterpret_cast(&tpxcdlnth), sizeof(tpxcdlnth)); ossim_uint32 position = 0; // Band Masks for (std::vector::const_iterator iter = theIncludedBlocks.begin(); iter != theIncludedBlocks.end(); ++iter) { ossim_uint32 offset = 0xFFFFFFFF; if (*iter) { offset = position; position += theBlockLength; } if (endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(offset); } out.write(reinterpret_cast(&offset), sizeof(offset)); } // Pad pixels not supported, always set to length 0, so don't need to write anything } ossim-Miami-2.9.1/src/support_data/ossimNitfImageHeader.cpp000066400000000000000000000252561352751253100237540ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #include #include #include #include #include #include /* for fmod */ #include #include #include RTTI_DEF2(ossimNitfImageHeader, "ossimNitfImageHeader", ossimObject, ossimPropertyInterface) static const char* TAGS_KW = "tags"; ossimNitfImageHeader::ossimNitfImageHeader() { } ossimNitfImageHeader::~ossimNitfImageHeader() { } bool ossimNitfImageHeader::getTagInformation(ossimNitfTagInformation& tagInfo, const ossimString& tagName)const { if(theTagList.size()) { for(ossim_uint32 idx = 0; idx < theTagList.size(); ++idx) { if(theTagList[idx].getTagName() == tagName) { tagInfo = theTagList[idx]; return true; } } } return false; } bool ossimNitfImageHeader::getTagInformation( ossimNitfTagInformation& tagInfo, ossim_uint32 idx) const { bool result = false; if(idx < theTagList.size()) { tagInfo = theTagList[idx]; result = true; } return result; } ossimRefPtr ossimNitfImageHeader::getTagData( const ossimString& tagName) { if(theTagList.size()) { for(ossim_uint32 idx = 0; idx < theTagList.size(); ++idx) { if(theTagList[idx].getTagName() == tagName) { return theTagList[idx].getTagData(); } } } return ossimRefPtr(); } const ossimRefPtr ossimNitfImageHeader::getTagData( const ossimString& tagName) const { if(theTagList.size()) { for(ossim_uint32 idx = 0; idx < theTagList.size(); ++idx) { if(theTagList[idx].getTagName() == tagName) { return theTagList[idx].getTagData(); } } } return ossimRefPtr(); } void ossimNitfImageHeader::getTagData( const ossimString& tagName, std::vector< const ossimNitfRegisteredTag* > &tags ) const { tags.clear(); if(theTagList.size()) { for(ossim_uint32 idx = 0; idx < theTagList.size(); ++idx) { if(theTagList[idx].getTagName() == tagName) { tags.push_back( theTagList[idx].getTagData().get() ); } } } } ossim_uint32 ossimNitfImageHeader::getNumberOfTags()const { return static_cast(theTagList.size()); } void ossimNitfImageHeader::addTag(const ossimNitfTagInformation& tag, bool unique) { if(unique) { removeTag(tag.getTagName()); } theTagList.push_back(tag); } void ossimNitfImageHeader::removeTag(const ossimString& tagName) { ossim_uint32 idx = 0; for(idx = 0; idx < theTagList.size(); ++idx) { if(theTagList[idx].getTagName() == tagName) { theTagList.erase(theTagList.begin() + idx); return; } } } bool ossimNitfImageHeader::isSameAs(const ossimNitfImageHeader* hdr) const { if (!hdr) return false; return ( (isCompressed() == hdr->isCompressed()) && (getNumberOfRows() == hdr->getNumberOfRows()) && (getNumberOfBands() == hdr->getNumberOfBands()) && (getNumberOfCols() == hdr->getNumberOfCols()) && (getNumberOfBlocksPerRow() == hdr->getNumberOfBlocksPerRow()) && (getNumberOfBlocksPerCol() == hdr->getNumberOfBlocksPerCol()) && (getNumberOfPixelsPerBlockHoriz() == hdr->getNumberOfPixelsPerBlockHoriz()) && (getNumberOfPixelsPerBlockVert() == hdr->getNumberOfPixelsPerBlockVert()) && (getBitsPerPixelPerBand() == hdr->getBitsPerPixelPerBand()) && (getImageRect() == hdr->getImageRect()) && (getIMode() == hdr->getIMode()) && (getCoordinateSystem() == hdr->getCoordinateSystem()) && (getGeographicLocation() == hdr->getGeographicLocation()) ); } void ossimNitfImageHeader::setProperty(ossimRefPtr /* property */) { } ossimRefPtr ossimNitfImageHeader::getProperty(const ossimString& name)const { ossimProperty* result = 0; if(name == TAGS_KW) { ossim_uint32 idxMax = getNumberOfTags(); if(idxMax > 0) { ossimContainerProperty* containerProperty = new ossimContainerProperty; containerProperty->setName(name); ossim_uint32 idx = 0; result = containerProperty; for(idx = 0; idx < idxMax; ++idx) { ossimNitfTagInformation tagInfo; getTagInformation(tagInfo, idx); const ossimRefPtr tagData = tagInfo.getTagData(); if(tagData.valid()) { ossimContainerProperty* containerPropertyTag = new ossimContainerProperty; containerPropertyTag->setName(tagInfo.getTagName()); std::vector > propertyList; tagData->getPropertyList(propertyList); containerPropertyTag->addChildren(propertyList); containerProperty->addChild(containerPropertyTag); } else { containerProperty->addStringProperty(tagInfo.getTagName(), "", true); } } } } return result; } void ossimNitfImageHeader::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back(TAGS_KW); } ossim_uint32 ossimNitfImageHeader::getTotalTagLength()const { ossim_uint32 tagLength = 0; for(ossim_uint32 i = 0; i < theTagList.size(); ++i) { tagLength += theTagList[i].getTotalTagLength(); } return tagLength; } std::ostream& ossimNitfImageHeader::printTags(std::ostream& out, const std::string& prefix)const { for(ossim_uint32 i = 0; i < theTagList.size(); ++i) { ossimRefPtr tag = theTagList[i].getTagData(); if (tag.valid()) { tag->print(out, prefix); } } return out; } void ossimNitfImageHeader::getMetadata(ossimKeywordlist& kwl, const char* prefix) const { kwl.add(prefix, "source", getImageSource().c_str(), false); kwl.add(prefix, "image_date", getAcquisitionDateMonthDayYear().c_str(), false); kwl.add(prefix, "image_title", getTitle().c_str(), false); } bool ossimNitfImageHeader::hasLut() const { bool result = false; const ossim_uint32 BANDS = static_cast(getNumberOfBands()); for (ossim_uint32 band = 0; band < BANDS; ++band) { const ossimRefPtr imgBand = getBandInformation(band); if(imgBand.valid()) { ossim_uint32 luts = imgBand->getNumberOfLuts(); if(luts > 0) { if(imgBand->getLut(0).valid()) { result = true; break; } } } } return result; } ossimRefPtr ossimNitfImageHeader::createLut( ossim_uint32 bandIdx)const { ossimRefPtr result; if(bandIdx < (ossim_uint32)getNumberOfBands()) { const ossimRefPtr band = getBandInformation(bandIdx); if(band.valid()) { ossim_uint32 bands = band->getNumberOfLuts(); if(bands > 0) { if(band->getLut(0).valid()) { ossim_uint32 entries = band->getLut(0)->getNumberOfEntries(); result = new ossimNBandLutDataObject(); result->create(entries, band->getNumberOfLuts()); ossim_uint32 bIdx; ossim_uint32 entryIdx; for(bIdx = 0; bIdx < bands; ++bIdx) { const ossimRefPtr lut = band->getLut(bIdx); if(lut.valid()) { for(entryIdx = 0; entryIdx < entries; ++entryIdx) { (*result)[entryIdx][bIdx] = (ossimNBandLutDataObject::LUT_ENTRY_TYPE)(lut->getValue(entryIdx)); } } } } } } } return result; } void ossimNitfImageHeader::checkForGeographicTiePointTruncation( const ossimDpt& tie) const { // One arc second in decimal degrees. const ossim_float64 ARC_SECOND = 1.0/3600.0; // Very small number. const ossim_float64 FUDGE_FACTOR = 0.000000001; // Remainder portion of latitude divided by an arc second. ossim_float64 y = std::fmod(tie.y, ARC_SECOND); // Remainder portion of longitue divided by an arc second. ossim_float64 x = std::fmod(tie.x, ARC_SECOND); if ( (std::fabs(y) > FUDGE_FACTOR) || (std::fabs(x) > FUDGE_FACTOR) ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfImageHeader WARNING:\n" << "Tie point will be truncated in image header: " << tie << std::endl; } } void ossimNitfImageHeader::getDecimationFactor(ossim_float64& result) const { //--- // Look for string like: // // "/2" = 1/2 // "/4 = 1/4 // ... // "/16 = 1/16 // // If it is full resolution it should be "1.0" // // or // // "0.5" which is the same as "/2" // "0.25" which is the same as "/4" //--- ossimString os = getImageMagnification(); // Spec says to fill with spaces so strip them. os.trim(ossimString(" ")); if (os.size()) { if ( os.contains("/") ) { os = os.after("/"); result = os.toFloat64(); if (result) { result = 1.0 / result; } } else { result = os.toFloat64(); } } else { result = ossim::nan(); } } bool ossimNitfImageHeader::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { if(!ossimObject::saveState(kwl, prefix)) return false; ossimString tagsPrefix = prefix; for(ossim_uint32 i = 0; i < theTagList.size(); ++i) { ossimRefPtr tag = theTagList[i].getTagData(); if (tag.valid()) { if(!tag->saveState(kwl, tagsPrefix)) { return false; } } } return true; } ossim-Miami-2.9.1/src/support_data/ossimNitfImageHeaderV2_0.cpp000066400000000000000000000763601352751253100244050ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfImageHeaderV2_0.cpp 21518 2012-08-22 21:15:56Z dburken $ #include #include #include #include #include #include #include #include #include #include #include //for memset #include #include #include using namespace std; static const ossimTrace traceDebug(ossimString("ossimNitfImageHeaderV2_0:debug")); RTTI_DEF1(ossimNitfImageHeaderV2_0, "ossimNitfImageHeaderV2_0", ossimNitfImageHeaderV2_X); const ossimString ossimNitfImageHeaderV2_0::ISCODE_KW = "iscode"; const ossimString ossimNitfImageHeaderV2_0::ISCTLH_KW = "isctlh"; const ossimString ossimNitfImageHeaderV2_0::ISREL_KW = "isrel"; const ossimString ossimNitfImageHeaderV2_0::ISCAUT_KW = "iscaut"; const ossimString ossimNitfImageHeaderV2_0::CTLN_KW = "ctln"; const ossimString ossimNitfImageHeaderV2_0::ISDWNG_KW = "isdwng"; const ossimString ossimNitfImageHeaderV2_0::ISDEVT_KW = "isdevt"; ossimNitfImageHeaderV2_0::ossimNitfImageHeaderV2_0() { clearFields(); } ossimNitfImageHeaderV2_0::~ossimNitfImageHeaderV2_0() { } void ossimNitfImageHeaderV2_0::parseStream(ossim::istream& in) { clearFields(); theImageBands.clear(); in.read(theType, 2); if(ossimString(theType) != "IM") { // error } in.read(theImageId, 10); in.read(theDateTime, 14); in.read(theTargetId, 17); in.read(theTitle, 80); in.read(theSecurityClassification, 1); in.read(theCodewords, 40); in.read(theControlAndHandling, 40); in.read(theReleasingInstructions, 40); in.read(theClassificationAuthority, 20); in.read(theSecurityControlNumber, 20); in.read(theSecurityDowngrade, 6); if(ossimString(theSecurityDowngrade) == "999998") { in.read(theDowngradingEvent, 40); } in.read(theEncryption, 1); in.read(theImageSource, 42); in.read(theSignificantRows, 8); in.read(theSignificantCols, 8); in.read(thePixelValueType, 3); in.read(theRepresentation, 8); in.read(theCategory, 8); in.read(theActualBitsPerPixelPerBand, 2); in.read(theJustification, 1); in.read(theCoordinateSystem, 1); if(theCoordinateSystem[0] != 'N') { in.read(theGeographicLocation, 60); } in.read(theNumberOfComments, 1); ossim_uint32 numberOfComments = ossimString(theNumberOfComments).toInt32(); // for now let's ignore the comments if(numberOfComments > 0) { theImageComments.resize(numberOfComments); for (ossim_uint32 i=0; i < numberOfComments; ++i) { char comment[81]; memset(comment, ' ', 80); comment[80] = '\0'; in.read(comment, 80); theImageComments[i] = ossimString(comment).trim(); } } in.read(theCompression, 2); // check to see if there is compression ossimString temp = theCompression; if((temp != "NC") && (temp != "NM")) { // get the rate if compression exists. in.read(theCompressionRateCode, 4); } in.read(theNumberOfBands, 1); ossim_uint32 numberOfBands = ossimString(theNumberOfBands).toUInt32(); theImageBands.resize(numberOfBands); ossim_uint32 idx = 0; while(idx < numberOfBands) { theImageBands[idx] = new ossimNitfImageBandV2_0; theImageBands[idx]->parseStream(in); ++idx; } in.read(theImageSyncCode, 1); in.read(theImageMode, 1); in.read(theNumberOfBlocksPerRow, 4); in.read(theNumberOfBlocksPerCol, 4); in.read(theNumberOfPixelsPerBlockHoriz, 4); in.read(theNumberOfPixelsPerBlockVert, 4); in.read(theNumberOfBitsPerPixelPerBand, 2); in.read(theDisplayLevel, 3); in.read(theAttachmentLevel, 3); in.read(theImageLocation, 10); in.read(theImageMagnification, 4); in.read(theUserDefinedImageDataLength, 5); std::streampos userDefinedDataLen = (std::streampos)ossimString(theUserDefinedImageDataLength).toUInt32(); theTagList.clear(); ossimNitfTagInformation headerTag; std::streampos start = in.tellg(); std::streampos current = in.tellg(); if(userDefinedDataLen > 0) { in.read(theUserDefinedOverflow, 3); while((current - start) < userDefinedDataLen) { headerTag.parseStream(in); theTagList.push_back(headerTag); // in.ignore(headerTag.getTagLength()); // headerTag.clearFields(); current = in.tellg(); } } in.read(theExtendedSubheaderDataLen, 5); std::streampos extSubHeadLen = (std::streampos)ossimString(theExtendedSubheaderDataLen).toUInt32(); start = in.tellg(); current = in.tellg(); if(extSubHeadLen > 0) { in.read(theExtendedSubheaderOverflow, 3); // ossim_uint32 test = 0; while((current - start) < extSubHeadLen) { headerTag.parseStream(in); theTagList.push_back(headerTag); // test = headerTag.getTagLength()+in.tellg(); // in.ignore(headerTag.getTagLength()); // headerTag.clearFields(); current = in.tellg(); } } ossimString compressionType = theCompression; compressionType = compressionType.trim().upcase(); ossimEndian endian; ossim_uint64 locationBefore = in.tellg(); //--- // Note: "C4" added to skip over the image data mask subheader. // See MIL-STD-2500A paragraph 5.5.1.5 // // Seems like CIB data does not have. Could not find a hard and fast // rule in the specs. Need a better was to detect if this needs to be // read. (drb - 20100317) //--- if( (compressionType == "NM") || (compressionType == "M0") || (compressionType == "M3") || (compressionType == "M4") || ( (compressionType == "C4") && ( !getImageId().contains("CIB")) ) ) { in.read((char*)(&theBlockedImageDataOffset), 4); in.read((char*)(&theBlockMaskRecordLength),2); in.read((char*)(&thePadPixelMaskRecordLength), 2); in.read((char*)(&theTransparentOutputPixelCodeLength), 2); if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(theBlockedImageDataOffset); endian.swap(theBlockMaskRecordLength); endian.swap(thePadPixelMaskRecordLength); endian.swap(theTransparentOutputPixelCodeLength); } if(theTransparentOutputPixelCodeLength <9) { if(theTransparentOutputPixelCodeLength != 0) { ossim_uint8 padOutputPixelCode; in.read((char*)(&padOutputPixelCode), 1); thePadOutputPixelCode = padOutputPixelCode; } } else { in.read((char*)(&thePadOutputPixelCode), 2); if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(thePadOutputPixelCode); } // I need to add code here to check for justification when its 2 bytes // but the code length is less than 16 bits. // } if(theBlockMaskRecordLength>0) { ossim_uint32 totalNumber = 0; if(theImageMode[0] == 'S') { totalNumber = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol()*getNumberOfBands(); } else { totalNumber = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol(); } ossim_uint32 *blockRead = new ossim_uint32[totalNumber]; ossim_uint32 idx = 0; theBlockMaskRecords.resize(totalNumber); in.read((char*)(blockRead), totalNumber*4); for(idx = 0; idx < totalNumber; ++idx) { if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(blockRead[idx]); } theBlockMaskRecords[idx] = blockRead[idx]; } delete [] blockRead; } if((thePadPixelMaskRecordLength > 0)|| (( (getCompressionCode().upcase() == "M3"))&& (thePadPixelMaskRecordLength == 0))) { ossim_uint32 totalNumber = 0; if(theImageMode[0] == 'S') { totalNumber = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol()*getNumberOfBands(); } else { totalNumber = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol(); } ossim_uint32 *blockRead = new ossim_uint32[totalNumber]; ossim_uint32 idx = 0; thePadPixelMaskRecords.resize(totalNumber); in.read((char*)(blockRead), totalNumber*4); for(idx = 0; idx < totalNumber; ++idx) { if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(blockRead[idx]); } thePadPixelMaskRecords[idx] = blockRead[idx]; } delete [] blockRead; } } theCompressionHeader = 0; if((getCompressionCode() == "C4")|| (getCompressionCode() == "M4")) { ossimRefPtr compressionHeader = new ossimNitfVqCompressionHeader; compressionHeader->parseStream(in); // do a check to see if the compression header is good // if( compressionHeader->getCompressionAlgorithmId()!= 1 ) { compressionHeader = 0; } theCompressionHeader = compressionHeader.get(); } ossim_uint64 delta = (ossim_uint64)in.tellg() - locationBefore; if(delta < theBlockedImageDataOffset) { in.ignore(theBlockedImageDataOffset-delta); } // // The stream should now be at the start of the data location so capture // it. // theDataLocation = in.tellg(); } void ossimNitfImageHeaderV2_0::writeStream(ossim::ostream &out) { out.write(theType, 2); out.write(theImageId, 10); out.write(theDateTime, 14); out.write(theTargetId, 17); out.write(theTitle, 80); out.write(theSecurityClassification, 1); out.write(theCodewords, 40); out.write(theControlAndHandling, 40); out.write(theReleasingInstructions, 40); out.write(theClassificationAuthority, 20); out.write(theSecurityControlNumber, 20); out.write(theSecurityDowngrade, 6); if(ossimString(theSecurityDowngrade) == "999998") { out.write(theDowngradingEvent, 40); } out.write(theEncryption, 1); out.write(theImageSource, 42); out.write(theSignificantRows, 8); out.write(theSignificantCols, 8); out.write(thePixelValueType, 3); out.write(theRepresentation, 8); out.write(theCategory, 8); out.write(theActualBitsPerPixelPerBand, 2); out.write(theJustification, 1); out.write(theCoordinateSystem, 1); if(theCoordinateSystem[0] != 'N') { out.write(theGeographicLocation, 60); } out.write(theNumberOfComments, 1); out.write(theCompression, 2); if(ossimString(theCompression) != "NC") { out.write(theCompressionRateCode, 4); } out.write(theNumberOfBands, 1); ossim_uint32 bandIdx = 0; for(bandIdx=0;bandIdxwriteStream(out); } out.write(theImageSyncCode, 1); out.write(theImageMode, 1); out.write(theNumberOfBlocksPerRow, 4); out.write(theNumberOfBlocksPerCol, 4); out.write(theNumberOfPixelsPerBlockHoriz, 4); out.write(theNumberOfPixelsPerBlockVert, 4); out.write(theNumberOfBitsPerPixelPerBand, 2); out.write(theDisplayLevel, 3); out.write(theAttachmentLevel, 3); out.write(theImageLocation, 10); out.write(theImageMagnification, 4); out.write(theUserDefinedImageDataLength, 5); if(ossimString(theUserDefinedImageDataLength).toInt32() > 0) { out.write(theUserDefinedOverflow, 3); } ossim_uint32 totalLength = getTotalTagLength(); if(totalLength == 0) { //memcpy(theExtendedSubheaderDataLen, "00000", 5); out.write(theExtendedSubheaderDataLen, 5); } else { totalLength += 3; // per Table A-3 of MIL-STD-2500B if(totalLength <= 99999) { std::ostringstream tempOut; tempOut << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << totalLength; memcpy(theExtendedSubheaderDataLen, tempOut.str().c_str(), 5); out.write(theExtendedSubheaderDataLen, 5); memset(theExtendedSubheaderOverflow, '0', 3); if(totalLength > 0) { out.write(theExtendedSubheaderOverflow, 3); ossim_uint32 i = 0; for(i = 0; i < theTagList.size(); ++i) { theTagList[i].writeStream(out); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimNitfFileHeaderV2_0::writeStream: Only support writing of total tag length < 99999" << std::endl; } } } bool ossimNitfImageHeaderV2_0::isValid()const { bool result = ossimNitfImageHeaderV2_X::isValid(); if(result) { } return result; } std::ostream& ossimNitfImageHeaderV2_0::print(std::ostream& out, const std::string& prefix) const { out << setiosflags(std::ios::left) << prefix << std::setw(24) << "IM:" << theType << "\n" << prefix << std::setw(24) << "IID:" << theImageId << "\n" << prefix << std::setw(24) << "IDATIM:" << theDateTime << "\n" << prefix << std::setw(24) << "TGTID:" << theTargetId << "\n" << prefix << std::setw(24) << "ITITLE:" << theTitle << "\n" << prefix << std::setw(24) << "ISCLAS:" << theSecurityClassification << "\n" << prefix << std::setw(24) << "ISCODE:" << theCodewords << "\n" << prefix << std::setw(24) << "ISCTLH:" << theControlAndHandling << "\n" << prefix << std::setw(24) << "ISREL:" << theReleasingInstructions << "\n" << prefix << std::setw(24) << "ISCAUT:" << theClassificationAuthority << "\n" << prefix << std::setw(24) << "ISCTLN:" << theSecurityControlNumber << "\n" << prefix << std::setw(24) << "ISDWNG:" << theSecurityDowngrade << "\n" << prefix << std::setw(24) << "ISDEBT:" << theDowngradingEvent << "\n" << prefix << std::setw(24) << "ENCRYP:" << theEncryption << "\n" << prefix << std::setw(24) << "ISORCE:" << theImageSource << "\n" << prefix << std::setw(24) << "NROWS:" << theSignificantRows << "\n" << prefix << std::setw(24) << "NCOLS:" << theSignificantCols << "\n" << prefix << std::setw(24) << "PVTYPE:" << thePixelValueType << "\n" << prefix << std::setw(24) << "IREP:" << theRepresentation << "\n" << prefix << std::setw(24) << "ICAT:" << theCategory << "\n" << prefix << std::setw(24) << "ABPP:" << theActualBitsPerPixelPerBand << "\n" << prefix << std::setw(24) << "PJUST:" << theJustification << "\n" << prefix << std::setw(24) << "ICORDS:" << theCoordinateSystem << "\n" << prefix << std::setw(24) << "IGEOLO:" << theGeographicLocation << "\n" << prefix << std::setw(24) << "NICOM:" << theNumberOfComments << "\n"; ossim_uint32 idx = 0; for(idx = 0; idx < theImageComments.size(); ++idx) { ossimString icpre = "ICOM" + ossimString::toString(idx) + ":"; out << prefix << std::setw(24) << icpre << theImageComments[idx].trim() << "\n"; } out << prefix << std::setw(24) << "IC:" << theCompression << "\n" << prefix << std::setw(24) << "COMRAT:" << theCompressionRateCode << "\n" << prefix << std::setw(24) << "NBANDS:" << theNumberOfBands << "\n"; for(idx = 0; idx < theImageBands.size(); ++idx) { if(theImageBands[idx].valid()) { theImageBands[idx]->print(out, prefix, idx); } } out << prefix << std::setw(24) << "ISYNC:" << theImageSyncCode << "\n" << prefix << std::setw(24) << "IMODE:" << theImageMode << "\n" << prefix << std::setw(24) << "NBPR:" << theNumberOfBlocksPerRow << "\n" << prefix << std::setw(24) << "NBPC:" << theNumberOfBlocksPerCol << "\n" << prefix << std::setw(24) << "NPPBH:" << theNumberOfPixelsPerBlockHoriz << "\n" << prefix << std::setw(24) << "NPPBV:" << theNumberOfPixelsPerBlockVert << "\n" << prefix << std::setw(24) << "NBPP:" << theNumberOfBitsPerPixelPerBand << "\n" << prefix << std::setw(24) << "IDLVL:" << theDisplayLevel << "\n" << prefix << std::setw(24) << "IALVL:" << theAttachmentLevel << "\n" << prefix << std::setw(24) << "ILOC:" << theImageLocation << "\n" << prefix << std::setw(24) << "IMAG:" << theImageMagnification << "\n" << prefix << std::setw(24) << "UDIDL:" << theUserDefinedImageDataLength << "\n" << prefix << std::setw(24) << "UDOFL:" << theUserDefinedOverflow << "\n" << prefix << std::setw(24) << "IXSHDL:" << theExtendedSubheaderDataLen << "\n" << prefix << std::setw(24) << "IXSOFL:" << theExtendedSubheaderOverflow << "\n"; if ( traceDebug() ) { out << prefix << std::setw(24) << "theDataLocation:" << theDataLocation << "\n" << prefix << std::setw(24) << "theBlockedImageDataOffset:" << theBlockedImageDataOffset << "\n" << prefix << std::setw(24) << "theBlockMaskRecordLength:" << theBlockMaskRecordLength << "\n" << prefix << std::setw(24) << "thePadPixelMaskRecordLength:" << thePadPixelMaskRecordLength << "\n" << prefix << std::setw(24) << "theTransparentOutputPixelCodeLength:" << theTransparentOutputPixelCodeLength << "\n" << prefix << std::setw(24) << "thePadOutputPixelCode:" << thePadOutputPixelCode << "\n"; } if(theCompressionHeader.valid()) { theCompressionHeader->print(out, prefix); } out << std::endl; return printTags(out, prefix); } bool ossimNitfImageHeaderV2_0::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { ossimNitfImageHeaderV2_X::saveState(kwl, prefix); std::ostringstream out; kwl.add(prefix, "ITITLE", theTitle); ossim_uint32 idx = 0; if(theCompressionHeader.valid()) { theCompressionHeader->saveState(kwl, prefix + "compression_header."); } for(idx = 0; idx < theImageBands.size(); ++idx) { if(theImageBands[idx].valid()) { theImageBands[idx]->print(out, "", idx); } } out << std::endl; ossimKeywordlist kwlTemp; std::istringstream in(out.str()); if(kwlTemp.parseStream(in)) { kwl.add(prefix, kwlTemp); } return true; } bool ossimNitfImageHeaderV2_0::isCompressed()const { ossimString temp = theCompression; temp = temp.trim(); return ((temp != "NC") && (temp != "NM")); } bool ossimNitfImageHeaderV2_0::isEncrypted()const { return (theEncryption[0] == '1'); } ossim_int32 ossimNitfImageHeaderV2_0::getNumberOfBands()const { return ossimString(theNumberOfBands).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_0::getNumberOfRows()const { return ossimString(theSignificantRows).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_0::getNumberOfCols()const { return ossimString(theSignificantCols).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_0::getNumberOfBlocksPerRow()const { return ossimString(theNumberOfBlocksPerRow).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_0::getNumberOfBlocksPerCol()const { return ossimString(theNumberOfBlocksPerCol).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_0::getNumberOfPixelsPerBlockHoriz()const { return ossimString(theNumberOfPixelsPerBlockHoriz).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_0::getNumberOfPixelsPerBlockVert()const { return ossimString(theNumberOfPixelsPerBlockVert).toInt32(); } ossimString ossimNitfImageHeaderV2_0::getImageId()const { return theImageId; } ossim_int32 ossimNitfImageHeaderV2_0::getBitsPerPixelPerBand()const { return ossimString(theNumberOfBitsPerPixelPerBand).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_0::getActualBitsPerPixelPerBand()const { return ossimString(theActualBitsPerPixelPerBand).toInt32(); } ossimString ossimNitfImageHeaderV2_0::getIMode() const { return ossimString(theImageMode).trim(); } ossimString ossimNitfImageHeaderV2_0::getSecurityClassification()const { return ossimString(theSecurityClassification); } ossimString ossimNitfImageHeaderV2_0::getImageDateAndTime() const { return ossimString(theDateTime); } ossimString ossimNitfImageHeaderV2_0::getAcquisitionDateMonthDayYear(ossim_uint8 separationChar)const { ossimString result; ossimString month(theDateTime+9, theDateTime+12); month = month.downcase(); if(month == "jan") { result += "01"; } else if(month == "feb") { result += "02"; } else if(month == "mar") { result += "03"; } else if(month == "apr") { result += "04"; } else if(month == "may") { result += "05"; } else if(month == "jun") { result += "06"; } else if(month == "jul") { result += "07"; } else if(month == "aug") { result += "08"; } else if(month == "sep") { result += "09"; } else if(month == "oct") { result += "10"; } else if(month == "nov") { result += "11"; } else if(month == "dec") { result += "12"; } result += ossimString(separationChar); result += ossimString(theDateTime, theDateTime + 2); result += ossimString(separationChar); ossimString year(theDateTime+12, theDateTime+14); if(year.toUInt32() < 70) { result += "20"; } else { result += "19"; } result += ossimString(theDateTime+12, theDateTime+14); return result; } ossimString ossimNitfImageHeaderV2_0::getCategory()const { return theCategory; } ossimString ossimNitfImageHeaderV2_0::getImageSource()const { return theImageSource; } ossimString ossimNitfImageHeaderV2_0::getRepresentation()const { return theRepresentation; } ossimString ossimNitfImageHeaderV2_0::getCoordinateSystem()const { return theCoordinateSystem; } ossimString ossimNitfImageHeaderV2_0::getPixelValueType()const { return ossimString(thePixelValueType).trim(); } bool ossimNitfImageHeaderV2_0::hasBlockMaskRecords()const { return (theBlockMaskRecords.size() > 0); } bool ossimNitfImageHeaderV2_0::hasPadPixelMaskRecords()const { return (thePadPixelMaskRecords.size() > 0); } bool ossimNitfImageHeaderV2_0::hasTransparentCode()const { return (theTransparentOutputPixelCodeLength > 0); } ossim_uint32 ossimNitfImageHeaderV2_0::getTransparentCode()const { return thePadOutputPixelCode; } ossim_uint32 ossimNitfImageHeaderV2_0::getBlockMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const { ossim_uint32 maxBlock = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol(); ossim_uint32 result = 0xffffffff; if((hasBlockMaskRecords())&& (blockNumber < maxBlock)) { if(theImageMode[0] == 'S') { if(bandNumber < (ossim_uint32)getNumberOfBands()) { result = theBlockMaskRecords[bandNumber*maxBlock + blockNumber]; } } else { result = theBlockMaskRecords[blockNumber]; } } return result; } ossim_uint32 ossimNitfImageHeaderV2_0::getPadPixelMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const { ossim_uint32 maxBlock = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol(); ossim_uint32 result = 0xffffffff; if((hasPadPixelMaskRecords())&& (blockNumber < maxBlock)) { if(theImageMode[0] == 'S') { if(bandNumber < (ossim_uint32)getNumberOfBands()) { result = thePadPixelMaskRecords[bandNumber*maxBlock + blockNumber]; } } else { result = thePadPixelMaskRecords[blockNumber]; } } return result; } void ossimNitfImageHeaderV2_0::clearFields() { theTagList.clear(); memcpy(theType, "IM", 2); memset(theImageId, ' ', 10); memset(theDateTime, ' ', 14); memset(theTargetId, ' ', 17); memset(theTitle, ' ', 80); memset(theSecurityClassification, ' ', 1); memset(theCodewords, ' ', 40); memset(theControlAndHandling, ' ', 40); memset(theReleasingInstructions, ' ', 40); memset(theClassificationAuthority, ' ', 20); memset(theSecurityControlNumber, ' ', 20); memset(theSecurityDowngrade, ' ', 6); memset(theDowngradingEvent, ' ', 40); memset(theEncryption, '0', 1); memset(theImageSource, ' ', 42); memset(theSignificantRows, ' ', 8); memset(theSignificantCols, ' ', 8); memset(thePixelValueType, ' ', 3); memset(theRepresentation, ' ', 8); memset(theCategory, ' ', 8); memset(theActualBitsPerPixelPerBand, '0', 2); memset(theJustification, ' ', 1); memset(theCoordinateSystem, 'N', 1); memset(theGeographicLocation, ' ', 60); memset(theNumberOfComments, '0', 1); memcpy(theCompression, "NC", 2); memset(theCompressionRateCode, ' ', 4); memset(theNumberOfBands, ' ', 1); memset(theImageSyncCode, '0', 1); memset(theImageMode, ' ', 1); memset(theNumberOfBlocksPerRow, ' ', 4); memset(theNumberOfBlocksPerCol, ' ', 4); memset(theNumberOfPixelsPerBlockHoriz, ' ', 4); memset(theNumberOfPixelsPerBlockVert, ' ', 4); memset(theNumberOfBitsPerPixelPerBand, '0', 2); memset(theDisplayLevel, ' ', 3); memset(theAttachmentLevel, ' ', 3); memcpy(theImageLocation, "0000000000", 10); memcpy(theImageMagnification, "1.00", 4); memset(theUserDefinedImageDataLength, '0', 5); memset(theUserDefinedOverflow, '0', 3); memset(theExtendedSubheaderDataLen, '0', 5); memset(theExtendedSubheaderOverflow, ' ', 3); theBlockMaskRecords.clear(); thePadPixelMaskRecords.clear(); theBlockedImageDataOffset = 0; theBlockMaskRecordLength = 0; thePadPixelMaskRecordLength = 0; theTransparentOutputPixelCodeLength = 0; thePadOutputPixelCode = 0; theCompressionHeader = 0; theType[2] = '\0'; theImageId[10] = '\0'; theDateTime[14] = '\0'; theTargetId[17] = '\0'; theTitle[80] = '\0'; theSecurityClassification[1] = '\0'; theCodewords[40] = '\0'; theControlAndHandling[40] = '\0'; theReleasingInstructions[40] = '\0'; theClassificationAuthority[20] = '\0'; theSecurityControlNumber[20] = '\0'; theSecurityDowngrade[6] = '\0'; theDowngradingEvent[40] = '\0'; theEncryption[1] = '\0'; theImageSource[42] = '\0'; theSignificantRows[8] = '\0'; theSignificantCols[8] = '\0'; thePixelValueType[3] = '\0'; theRepresentation[8] = '\0'; theCategory[8] = '\0'; theActualBitsPerPixelPerBand[2] = '\0'; theJustification[1] = '\0'; theCoordinateSystem[1] = '\0'; theGeographicLocation[60] = '\0'; theNumberOfComments[1] = '\0'; theCompression[2] = '\0'; theCompressionRateCode[4] = '\0'; theNumberOfBands[1] = '\0'; theImageSyncCode[1] = '\0'; theImageMode[1] = '\0'; theNumberOfBlocksPerRow[4] = '\0'; theNumberOfBlocksPerCol[4] = '\0'; theNumberOfPixelsPerBlockHoriz[4] = '\0'; theNumberOfPixelsPerBlockVert[4] = '\0'; theNumberOfBitsPerPixelPerBand[2] = '\0'; theDisplayLevel[3] = '\0'; theAttachmentLevel[3] = '\0'; theImageLocation[10] = '\0'; theImageMagnification[4] = '\0'; theUserDefinedImageDataLength[5] = '\0'; theUserDefinedOverflow[3] = '\0'; theExtendedSubheaderDataLen[5] = '\0'; theExtendedSubheaderOverflow[3] = '\0'; theDataLocation = 0; } const ossimRefPtr ossimNitfImageHeaderV2_0::getCompressionHeader()const { return theCompressionHeader; } const ossimRefPtr ossimNitfImageHeaderV2_0::getBandInformation(ossim_uint32 idx)const { if(idx < theImageBands.size()) { return (ossimNitfImageBand*)theImageBands[idx].get(); } return NULL; } void ossimNitfImageHeaderV2_0::setNumberOfBands(ossim_uint32 nbands) { std::ostringstream out; if(nbands > 9) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfImageHeaderV2_0::setNumberOfBands: NBANDS is too large. For 2.0 spec we can only have up to 9 bands\n"; } std::string s = "ossimNitfImageHeaderV2_0::setNumberOfBands:"; s += " ERROR\nExceeded max number of bands of 9!"; throw std::out_of_range(s); } else { out << nbands; theNumberOfBands[0] = out.str().c_str()[0]; } theImageBands.resize(getNumberOfBands()); } void ossimNitfImageHeaderV2_0::setBandInfo(ossim_uint32 idx, const ossimNitfImageBandV2_0& info) { if(idx < theImageBands.size()) { if(!theImageBands[idx].valid()) { theImageBands[idx] = new ossimNitfImageBandV2_0; } (*theImageBands[idx]) = info; } } void ossimNitfImageHeaderV2_0::setNumberOfRows(ossim_uint32 rows) { std::ostringstream out; if(rows > 99999999) rows = 99999999; out << rows; ossimNitfCommon::setField(theSignificantRows, out.str(), 8, ios::right, '0'); } void ossimNitfImageHeaderV2_0::setNumberOfCols(ossim_uint32 cols) { std::ostringstream out; if(cols > 99999999) cols = 99999999; out << cols; ossimNitfCommon::setField(theSignificantCols, out.str(), 8, ios::right, '0'); } void ossimNitfImageHeaderV2_0::setProperty(ossimRefPtr property) { ossimNitfImageHeaderV2_X::setProperty(property); } ossimRefPtr ossimNitfImageHeaderV2_0::getProperty(const ossimString& name)const { ossimRefPtr property = 0; if(name == ISCODE_KW) { property = new ossimStringProperty(name, theCodewords); } else if(name == ISCTLH_KW) { property = new ossimStringProperty(name, theControlAndHandling); } else if(name == ISREL_KW) { property = new ossimStringProperty(name, theReleasingInstructions); } else if(name == ISCAUT_KW) { property = new ossimStringProperty(name, theClassificationAuthority); } else if(name == CTLN_KW) { property = new ossimStringProperty(name, theSecurityControlNumber); } else if(name == ISDWNG_KW) { property = new ossimStringProperty(name, theSecurityDowngrade); } else if(name == ISDEVT_KW) { property = new ossimStringProperty(name, theDowngradingEvent); } else { property = ossimNitfImageHeaderV2_X::getProperty(name); } return property; } void ossimNitfImageHeaderV2_0::getPropertyNames(std::vector& propertyNames)const { ossimNitfImageHeaderV2_X::getPropertyNames(propertyNames); propertyNames.push_back(ISCODE_KW); propertyNames.push_back(ISCTLH_KW); propertyNames.push_back(ISREL_KW); propertyNames.push_back(ISCAUT_KW); propertyNames.push_back(CTLN_KW); propertyNames.push_back(ISDWNG_KW); propertyNames.push_back(ISDEVT_KW); } ossim-Miami-2.9.1/src/support_data/ossimNitfImageHeaderV2_1.cpp000066400000000000000000001603121352751253100243750ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // for memset using namespace std; RTTI_DEF1(ossimNitfImageHeaderV2_1, "ossimNitfImageHeaderV2_1", ossimNitfImageHeaderV2_X) const ossimString ossimNitfImageHeaderV2_1::ISCLSY_KW = "isclsy"; const ossimString ossimNitfImageHeaderV2_1::ISCODE_KW = "iscode"; const ossimString ossimNitfImageHeaderV2_1::ISCTLH_KW = "isctlh"; const ossimString ossimNitfImageHeaderV2_1::ISREL_KW = "isrel"; const ossimString ossimNitfImageHeaderV2_1::ISDCTP_KW = "isdctp"; const ossimString ossimNitfImageHeaderV2_1::ISDCDT_KW = "isdcdt"; const ossimString ossimNitfImageHeaderV2_1::ISDCXM_KW = "isdcxm"; const ossimString ossimNitfImageHeaderV2_1::ISDG_KW = "isdg"; const ossimString ossimNitfImageHeaderV2_1::ISDGDT_KW = "isdgdt"; const ossimString ossimNitfImageHeaderV2_1::ISCLTX_KW = "iscltx"; const ossimString ossimNitfImageHeaderV2_1::ISCATP_KW = "iscatp"; const ossimString ossimNitfImageHeaderV2_1::ISCAUT_KW = "iscaut"; const ossimString ossimNitfImageHeaderV2_1::ISCRSN_KW = "iscrsn"; const ossimString ossimNitfImageHeaderV2_1::ISSRDT_KW = "issrdt"; const ossimString ossimNitfImageHeaderV2_1::ISCTLN_KW = "isctln"; const ossimString ossimNitfImageHeaderV2_1::XBANDS_KW = "xbands"; const ossimString NBANDS_KW = "nbands"; static const ossimTrace traceDebug(ossimString("ossimNitfImageHeaderV2_1:debug")); ossimNitfImageHeaderV2_1::ossimNitfImageHeaderV2_1() { clearFields(); } ossimNitfImageHeaderV2_1::~ossimNitfImageHeaderV2_1() { } void ossimNitfImageHeaderV2_1::parseStream(ossim::istream& in) { parseStream(in, NULL); } void ossimNitfImageHeaderV2_1::parseStream(ossim::istream& in, const ossimNitfFileHeaderV2_1 *file) { if (!in) { return; } clearFields(); theTagList.clear(); in.read(theType, 2); in.read(theImageId, 10); in.read(theDateTime,14); in.read(theTargetId, 17); in.read(theTitle, 80); in.read(theSecurityClassification, 1); in.read(theSecurityClassificationSys, 2); in.read(theCodewords, 11); in.read(theControlAndHandling, 2); in.read(theReleasingInstructions, 20); in.read(theDeclassificationType, 2); in.read(theDeclassificationDate, 8); in.read(theDeclassificationExempt, 4); in.read(theDowngrade, 1); in.read(theDowngradeDate, 8); in.read(theClassificationText, 43); in.read(theClassificationAuthType, 1); in.read(theClassificationAuthority, 40); in.read(theClassificationReason, 1); in.read(theSecuritySourceDate, 8); in.read(theSecurityControlNumber, 15); in.read(theEncryption, 1); in.read(theImageSource, 42); in.read(theSignificantRows, 8); in.read(theSignificantCols, 8); in.read(thePixelValueType, 3); in.read(theRepresentation, 8); in.read(theCategory, 8); in.read(theActualBitsPerPixelPerBand, 2); in.read(theJustification, 1); in.read(theCoordinateSystem, 1); // if it's not blank then read coordinates if(theCoordinateSystem[0] != ' ') { in.read(theGeographicLocation, 60); } // Up to 3 80 character comments treated as a single comment. in.read(theNumberOfComments, 1); ossim_int32 numberOfComments = ossimString(theNumberOfComments).toInt32(); if(numberOfComments > 0) { theImageComments.resize(numberOfComments); for (ossim_uint32 i=0; i < numberOfComments; ++i) { char comment[81]; memset(comment, ' ', 80); comment[80] = '\0'; in.read(comment, 80); theImageComments[i] = ossimString(comment).trim(); } } in.read(theCompression, 2); // only need the Rate code if its not // NC (No compression) ossimString temp = theCompression; if((temp != "NC") && (temp != "NM")) { in.read(theCompressionRateCode, 4); } in.read(theNumberOfBands, 1); // check to see if multi spectral bands // exceed 9. A value of 0 indicates this ossim_int32 numberOfBands = ossimString(theNumberOfBands).toInt32(); if (numberOfBands == 0) { in.read(theNumberOfMultispectralBands, 5); numberOfBands = ossimString(theNumberOfMultispectralBands).toInt32(); } theImageBands.clear(); theImageBands.resize(numberOfBands); for (ossim_int32 band = 0; band < numberOfBands; ++band) { theImageBands[band] = new ossimNitfImageBandV2_1; theImageBands[band]->parseStream(in); } in.read(theImageSyncCode, 1); in.read(theImageMode, 1); in.read(theNumberOfBlocksPerRow, 4); in.read(theNumberOfBlocksPerCol, 4); in.read(theNumberOfPixelsPerBlockHoriz, 4); in.read(theNumberOfPixelsPerBlockVert, 4); in.read(theNumberOfBitsPerPixelPerBand, 2); in.read(theDisplayLevel, 3); in.read(theAttachmentLevel, 3); in.read(theImageLocation, 10); in.read(theImageMagnification, 4); in.read(theUserDefinedImageDataLength, 5); ossimNitfTagInformation headerTag; std::streampos start = in.tellg(); std::streampos current = in.tellg(); std::streampos userDefinedDataLen = ossimString(theUserDefinedImageDataLength).toInt32(); if(userDefinedDataLen > 0) { in.read(theUserDefinedOverflow, 3); current = in.tellg(); while((current - start) < userDefinedDataLen) { headerTag.parseStream(in); theTagList.push_back(headerTag); headerTag.setTagType("UDID"); // in.ignore(headerTag.getTagLength()); // headerTag.clearFields(); current = in.tellg(); } // in.seekg(start + userDefinedDataLen); ossim_int32 overflow = ossimString(theUserDefinedOverflow).toLong(); if (overflow != 0 && file != NULL) { ossimNitfDataExtensionSegment *des = file->getNewDataExtensionSegment(overflow-1, in); if (des != NULL) { const vector &desTags = des->getTagList(); for (vector::const_iterator iter = desTags.begin(); iter != desTags.end(); ++iter) { iter->setTagType("UDID"); theTagList.push_back(*iter); } } delete des; } ossimIFStream64::seekg64(in, start + userDefinedDataLen, ios::beg); } in.read(theExtendedSubheaderDataLen, 5); std::streampos extSubHeadLen = ossimString(theExtendedSubheaderDataLen).toInt32(); start = in.tellg(); current = in.tellg(); if(extSubHeadLen > 0) { in.read(theExtendedSubheaderOverflow, 3); current = in.tellg(); while((current - start) < extSubHeadLen) { headerTag.parseStream(in); headerTag.setTagType("IXSHD"); theTagList.push_back(headerTag); // in.ignore(headerTag.getTagLength()); // headerTag.clearFields(); current = in.tellg(); } // in.seekg(start + extSubHeadLen); ossim_int32 overflow = ossimString(theExtendedSubheaderOverflow).toLong(); if (overflow != 0 && file != NULL) { ossimNitfDataExtensionSegment *des = file->getNewDataExtensionSegment(overflow-1, in); if (des != NULL) { const vector &desTags = des->getTagList(); for (vector::const_iterator iter = desTags.begin(); iter != desTags.end(); ++iter) { iter->setTagType("IXSHD"); theTagList.push_back(*iter); } delete des; } } ossimIFStream64::seekg64(in, start + extSubHeadLen, ios::beg); } ossimString compressionType = theCompression; compressionType = compressionType.trim().upcase(); ossimEndian endian; //--- // Note: "C4" added to skip over the image data mask subheader. // See MIL-STD-2500C paragraph 5.4.3.2 //--- if((compressionType == "NM")|| (compressionType == "M1")|| (compressionType == "M3")|| (compressionType == "M4")|| (compressionType == "M5")|| (compressionType == "C4")) { ossim_uint64 locationBefore = in.tellg(); in.read((char*)(&theBlockedImageDataOffset), 4); in.read((char*)(&theBlockMaskRecordLength),2); in.read((char*)(&thePadPixelMaskRecordLength), 2); in.read((char*)(&theTransparentOutputPixelCodeLength), 2); if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(theBlockedImageDataOffset); endian.swap(theBlockMaskRecordLength); endian.swap(thePadPixelMaskRecordLength); endian.swap(theTransparentOutputPixelCodeLength); } if(theTransparentOutputPixelCodeLength <9) { if(theTransparentOutputPixelCodeLength != 0) { ossim_uint8 padOutputPixelCode; in.read((char*)(&padOutputPixelCode), 1); thePadOutputPixelCode = padOutputPixelCode; } } else { in.read((char*)(&thePadOutputPixelCode), 2); if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(thePadOutputPixelCode); } // I need to add code here to check for justification when its 2 bytes // but the code length is less than 16 bits. // } if(theBlockMaskRecordLength>0) { ossim_uint32 totalNumber = 0; if(theImageMode[0] == 'S') { totalNumber = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol()*getNumberOfBands(); } else { totalNumber = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol(); } ossim_uint32 *blockRead = new ossim_uint32[totalNumber]; ossim_uint32 idx = 0; theBlockMaskRecords.resize(totalNumber); in.read((char*)(blockRead), totalNumber*4); for(idx = 0; idx < totalNumber; ++idx) { if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(blockRead[idx]); } theBlockMaskRecords[idx] = blockRead[idx]; } delete [] blockRead; } if( (thePadPixelMaskRecordLength > 0) || ( (getCompressionCode().upcase() == "M3") && (thePadPixelMaskRecordLength == 0) ) ) { ossim_uint32 totalNumber = 0; if(theImageMode[0] == 'S') { totalNumber = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol()*getNumberOfBands(); } else { totalNumber = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol(); } ossim_uint32 *blockRead = new ossim_uint32[totalNumber]; ossim_uint32 idx = 0; thePadPixelMaskRecords.resize(totalNumber); in.read((char*)(blockRead), totalNumber*4); for(idx = 0; idx < totalNumber; ++idx) { if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(blockRead[idx]); } thePadPixelMaskRecords[idx] = blockRead[idx]; } delete [] blockRead; } theCompressionHeader = 0; if((getCompressionCode() == "C4")|| (getCompressionCode() == "M4")) { ossimRefPtr compressionHeader = new ossimNitfVqCompressionHeader; compressionHeader->parseStream(in); // do a check to see if the compression header is good // if(compressionHeader->getCompressionAlgorithmId()!= 1) { compressionHeader = 0; } theCompressionHeader = compressionHeader.get(); } ossim_uint64 delta = (ossim_uint64)in.tellg() - locationBefore; if(delta < theBlockedImageDataOffset) { in.ignore(theBlockedImageDataOffset-delta); } } //*** // The stream should now be at the start of the data location so capture // it. //*** theDataLocation = in.tellg(); } void ossimNitfImageHeaderV2_1::writeStream(ossim::ostream &out) { out.write(theType, 2); out.write(theImageId, 10); out.write(theDateTime,14); out.write(theTargetId, 17); out.write(theTitle, 80); out.write(theSecurityClassification, 1); out.write(theSecurityClassificationSys, 2); out.write(theCodewords, 11); out.write(theControlAndHandling, 2); out.write(theReleasingInstructions, 20); out.write(theDeclassificationType, 2); out.write(theDeclassificationDate, 8); out.write(theDeclassificationExempt, 4); out.write(theDowngrade, 1); out.write(theDowngradeDate, 8); out.write(theClassificationText, 43); out.write(theClassificationAuthType, 1); out.write(theClassificationAuthority, 40); out.write(theClassificationReason, 1); out.write(theSecuritySourceDate, 8); out.write(theSecurityControlNumber, 15); out.write(theEncryption, 1); out.write(theImageSource, 42); out.write(theSignificantRows, 8); out.write(theSignificantCols, 8); out.write(thePixelValueType, 3); out.write(theRepresentation, 8); out.write(theCategory, 8); out.write(theActualBitsPerPixelPerBand, 2); out.write(theJustification, 1); out.write(theCoordinateSystem, 1); if(theCoordinateSystem[0] != ' ') { out.write(theGeographicLocation, 60); } out.write(theNumberOfComments, 1); if (ossimString(theNumberOfComments).toUInt32() > 0) { for (ossim_uint32 i=0; i < theImageComments.size(); ++i) { char icom[81]; memset(icom, ' ', 80); icom[80] = '\0'; strcpy(icom, theImageComments[i].c_str()); out.write(icom, 80); } } out.write(theCompression, 2); ossimString compressionTest = theCompression; if(compressionTest != "NC" && compressionTest != "NM") { out.write(theCompressionRateCode, 4); } out.write(theNumberOfBands, 1); if(ossimString(theNumberOfBands).toInt32() == 0) { out.write(theNumberOfMultispectralBands, 5); } if(theImageBands.size()) { ossim_uint32 idx = 0; for(idx = 0; idx < theImageBands.size(); ++idx) { if (theImageBands[idx].valid() == false) { theImageBands[idx] = new ossimNitfImageBandV2_1; } theImageBands[idx]->writeStream(out); } } out.write(theImageSyncCode, 1); out.write(theImageMode, 1); out.write(theNumberOfBlocksPerRow, 4); out.write(theNumberOfBlocksPerCol, 4); out.write(theNumberOfPixelsPerBlockHoriz, 4); out.write(theNumberOfPixelsPerBlockVert, 4); out.write(theNumberOfBitsPerPixelPerBand, 2); out.write(theDisplayLevel, 3); out.write(theAttachmentLevel, 3); out.write(theImageLocation, 10); out.write(theImageMagnification, 4); out.write(theUserDefinedImageDataLength, 5); if(ossimString(theUserDefinedImageDataLength).toInt32() > 0) { out.write(theUserDefinedOverflow, 3); } // need to output tagged data // here // ossim_uint32 totalLength = getTotalTagLength(); if (totalLength == 0) { out.write(theExtendedSubheaderDataLen, 5); } else { totalLength += 3; // per Table A-3 of MIL-STD-2500B if(totalLength <= 99999) { std::ostringstream tempOut; tempOut << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << totalLength; memcpy(theExtendedSubheaderDataLen, tempOut.str().c_str(), 5); out.write(theExtendedSubheaderDataLen, 5); ossim_uint32 theExtendedSubheaderDataLenBytes = ossimString(theExtendedSubheaderDataLen).toUInt32(); if (theExtendedSubheaderDataLenBytes > 0) { strcpy(theExtendedSubheaderOverflow, ossimString("001").c_str()); } else { memset(theExtendedSubheaderOverflow, '0', 3); } if(totalLength > 0) { out.write(theExtendedSubheaderOverflow, 3); ossim_uint32 i = 0; for(i = 0; i < theTagList.size(); ++i) { theTagList[i].writeStream(out); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimNitfFileHeaderV2_1::writeStream: Only support writing of total tag length < 99999" << std::endl; } } } std::ostream& ossimNitfImageHeaderV2_1::print(std::ostream& out, const std::string& prefix) const { out << setiosflags(ios::left) << prefix << setw(24) << "IM:" << theType << "\n" << prefix << setw(24) << "IID1:" << theImageId << "\n" << prefix << setw(24) << "IDATIM:" << theDateTime << "\n" << prefix << setw(24) << "TGTID:" << theTargetId << "\n" << prefix << setw(24) << "IID2:" << theTitle << "\n" << prefix << setw(24) << "ISCLAS:" << theSecurityClassification << "\n" << prefix << setw(24) << "ISCLSY:" << theSecurityClassificationSys << "\n" << prefix << setw(24) << "ISCODE:" << theCodewords << "\n" << prefix << setw(24) << "ISCTLH:" << theControlAndHandling << "\n" << prefix << setw(24) << "ISREL:" << theReleasingInstructions << "\n" << prefix << setw(24) << "ISDCTP:" << theDeclassificationType << "\n" << prefix << setw(24) << "ISDCDT:" << theDeclassificationDate << "\n" << prefix << setw(24) << "ISDCXM:" << theDeclassificationExempt << "\n" << prefix << setw(24) << "ISDG:" << theDowngrade << "\n" << prefix << setw(24) << "ISDGDT:" << theDowngradeDate << "\n" << prefix << setw(24) << "ISCLTX:" << theClassificationText << "\n" << prefix << setw(24) << "ISCATP:" << theClassificationAuthType << "\n" << prefix << setw(24) << "ISCAUT:" << theClassificationAuthority << "\n" << prefix << setw(24) << "ISCRSN:" << theClassificationReason << "\n" << prefix << setw(24) << "ISSRDT:" << theSecuritySourceDate << "\n" << prefix << setw(24) << "ISCTLN:" << theSecurityControlNumber << "\n" << prefix << setw(24) << "ENCRYP:" << theEncryption << "\n" << prefix << setw(24) << "ISORCE:" << theImageSource << "\n" << prefix << setw(24) << "NROWS:" << theSignificantRows << "\n" << prefix << setw(24) << "NCOLS:" << theSignificantCols << "\n" << prefix << setw(24) << "PVTYPE:" << thePixelValueType << "\n" << prefix << setw(24) << "IREP:" << theRepresentation << "\n" << prefix << setw(24) << "ICAT:" << theCategory << "\n" << prefix << setw(24) << "ABPP:" << theActualBitsPerPixelPerBand << "\n" << prefix << setw(24) << "PJUST:" << theJustification << "\n" << prefix << setw(24) << "ICORDS:" << theCoordinateSystem << "\n" << prefix << setw(24) << "IGEOLO:" << theGeographicLocation << "\n" << prefix << setw(24) << "NICOM:" << theNumberOfComments << "\n"; ossim_uint32 idx = 0; for(idx = 0; idx < theImageComments.size(); ++idx) { ossimString icpre = "ICOM" + ossimString::toString(idx) + ":"; out << prefix << std::setw(24) << icpre << theImageComments[idx].trim() << "\n"; } out << prefix << setw(24) << "IC:" << theCompression << "\n" << prefix << setw(24) << "COMRAT:" << theCompressionRateCode << "\n" << prefix << setw(24) << "NBANDS:" << theNumberOfBands << "\n" << prefix << setw(24) << "XBANDS:" << theNumberOfMultispectralBands << "\n"; for(idx = 0; idx < theImageBands.size(); ++idx) { if(theImageBands[idx].valid()) { theImageBands[idx]->print(out, prefix, idx); } } out << prefix << setw(24) << "ISYNC:" << theImageSyncCode << "\n" << prefix << setw(24) << "IMODE:" << theImageMode << "\n" << prefix << setw(24) << "NBPR:" << theNumberOfBlocksPerRow << "\n" << prefix << setw(24) << "NBPC:" << theNumberOfBlocksPerCol << "\n" << prefix << setw(24) << "NPPBH:" << theNumberOfPixelsPerBlockHoriz << "\n" << prefix << setw(24) << "NPPBV:" << theNumberOfPixelsPerBlockVert << "\n" << prefix << setw(24) << "NBPP:" << theNumberOfBitsPerPixelPerBand << "\n" << prefix << setw(24) << "IDLVL:" << theDisplayLevel << "\n" << prefix << setw(24) << "IALVL:" << theAttachmentLevel << "\n" << prefix << setw(24) << "ILOC:" << theImageLocation << "\n" << prefix << setw(24) << "IMAG:" << theImageMagnification << "\n" << prefix << setw(24) << "UDIDL:" << theUserDefinedImageDataLength << "\n" << prefix << setw(24) << "UDOFL:" << theUserDefinedOverflow << "\n" << prefix << setw(24) << "IXSHDL:" << theExtendedSubheaderDataLen << "\n" << prefix << setw(24) << "IXSOFL:" << theExtendedSubheaderOverflow << "\n" << prefix << setw(24) << "IMDATOFF:" << theBlockedImageDataOffset << "\n" << prefix << setw(24) << "BMRLNTH:" << theBlockMaskRecordLength << "\n" << prefix << setw(24) << "TMRLNTH:" << thePadPixelMaskRecordLength << "\n" << prefix << setw(24) << "TPXCDLNTH:" << theTransparentOutputPixelCodeLength << "\n" << prefix << setw(24) << "TPXCD:" << thePadOutputPixelCode << "\n"; if ( traceDebug() ) { out << prefix << setw(24) << "theDataLocation:" << theDataLocation << "\n"; } out << std::endl; return printTags(out, prefix); } bool ossimNitfImageHeaderV2_1::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { ossimNitfImageHeaderV2_X::saveState(kwl, prefix); kwl.add(prefix, "ISCLSY", theSecurityClassificationSys); kwl.add(prefix, "ISCODE", theCodewords); kwl.add(prefix, "ISCTLH", theControlAndHandling); kwl.add(prefix, "ISREL", theReleasingInstructions); kwl.add(prefix, "ISDCTP", theDeclassificationType); kwl.add(prefix, "ISDCDT", theDeclassificationDate); kwl.add(prefix, "ISDCXM", theDeclassificationExempt); kwl.add(prefix, "ISDG", theDowngrade); kwl.add(prefix, "ISDGDT", theDowngradeDate); kwl.add(prefix, "ISCLTX", theClassificationText); kwl.add(prefix, "ISCATP", theClassificationAuthType); kwl.add(prefix, "ISCAUT", theClassificationAuthority); kwl.add(prefix, "ISCRSN", theClassificationReason); kwl.add(prefix, "ISSRDT", theSecuritySourceDate); kwl.add(prefix, "ISCTLN", theSecurityControlNumber); kwl.add(prefix, "XBANDS", theNumberOfMultispectralBands); ossim_uint32 idx = 0; std::ostringstream out; if(theCompressionHeader.valid()) { theCompressionHeader->saveState(kwl, prefix); } for(idx = 0; idx < theImageBands.size(); ++idx) { if(theImageBands[idx].valid()) { theImageBands[idx]->print(out, "", idx); } } out << std::endl; ossimKeywordlist kwlTemp; std::istringstream in(out.str()); if(kwlTemp.parseStream(in)) { kwl.add(prefix, kwlTemp); } return true; } bool ossimNitfImageHeaderV2_1::isValid()const { bool result = ossimNitfImageHeaderV2_X::isValid(); if(result) { } return result; } bool ossimNitfImageHeaderV2_1::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Note: Currently not looking up all fieds only ones that make sense. const char* lookup; lookup = kwl.find( prefix, ISCLSY_KW ); if ( lookup ) { setSecurityClassificationSystem( ossimString(lookup) ); } lookup = kwl.find( prefix, ISCODE_KW ); if ( lookup ) { setCodewords( ossimString(lookup) ); } lookup = kwl.find( prefix, ISCTLH_KW ); if ( lookup ) { setControlAndHandling( ossimString(lookup) ); } lookup = kwl.find( prefix, ISREL_KW); if ( lookup ) { setReleasingInstructions( ossimString(lookup) ); } lookup = kwl.find( prefix, ISDCTP_KW ); if ( lookup ) { setDeclassificationType( ossimString(lookup) ); } lookup = kwl.find( prefix, ISDCDT_KW ); if ( lookup ) { setDeclassificationDate( ossimString(lookup) ); } lookup = kwl.find( prefix, ISDCXM_KW ); if ( lookup ) { setDeclassificationExempt( ossimString(lookup) ); } lookup = kwl.find( prefix, ISDG_KW ); if ( lookup ) { setDowngrade( ossimString(lookup) ); } lookup = kwl.find( prefix, ISDGDT_KW ); if ( lookup ) { setDowngradeDate( ossimString(lookup) ); } lookup = kwl.find( prefix, ISCLTX_KW ); if ( lookup ) { setClassificationText( ossimString(lookup) ); } lookup = kwl.find( prefix, ISCATP_KW ); if ( lookup ) { setClassificationAuthorityType( ossimString(lookup) ); } lookup = kwl.find( prefix, ISCAUT_KW ); if ( lookup ) { setClassificationAuthority( ossimString(lookup) ); } lookup = kwl.find( prefix, ISCRSN_KW ); if ( lookup ) { setClassificationReason( ossimString(lookup) ); } lookup = kwl.find( prefix, ISSRDT_KW ); if ( lookup ) { setSecuritySourceDate( ossimString(lookup) ); } lookup = kwl.find( prefix, ISCTLN_KW ); if ( lookup ) { setSecurityControlNumber( ossimString(lookup) ); } lookup = kwl.find( prefix, NBANDS_KW ); if ( lookup ) { setNumberOfBands( ossimString(lookup).toUInt32() ); } /* Setting this in the writer versus loadstate right now for (int i=0; i < theImageBands.size(); ++i) { theImageBands[i]->loadState(kwl, prefix, i); } */ return ossimNitfImageHeaderV2_X::loadState(kwl, prefix); } bool ossimNitfImageHeaderV2_1::isCompressed()const { ossimString temp = theCompression; temp = temp.trim(); return ((temp != "NC") && (temp != "NM")); } bool ossimNitfImageHeaderV2_1::isEncrypted()const { return (theEncryption[0] == '1'); } ossim_int32 ossimNitfImageHeaderV2_1::getNumberOfBands()const { if(theNumberOfBands[0] == '0') { return ossimString(theNumberOfMultispectralBands).toInt32(); } else { return ossimString(theNumberOfBands).toInt32(); } } ossim_int32 ossimNitfImageHeaderV2_1::getNumberOfRows()const { return ossimString(theSignificantRows).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_1::getNumberOfCols()const { return ossimString(theSignificantCols).toInt32(); } ossimString ossimNitfImageHeaderV2_1::getImageId()const { return theImageId; } ossim_int32 ossimNitfImageHeaderV2_1::getBitsPerPixelPerBand()const { return ossimString(theNumberOfBitsPerPixelPerBand).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_1::getActualBitsPerPixelPerBand()const { return ossimString(theActualBitsPerPixelPerBand).toInt32(); } ossimString ossimNitfImageHeaderV2_1::getIMode() const { return ossimString(theImageMode).trim(); } ossimString ossimNitfImageHeaderV2_1::getSecurityClassification()const { return theSecurityClassification; } ossimString ossimNitfImageHeaderV2_1::getImageDateAndTime() const { return ossimString(theDateTime); } ossimString ossimNitfImageHeaderV2_1::getAcquisitionDateMonthDayYear(ossim_uint8 separationChar)const { ossimString result; result += ossimString(theDateTime + 4, theDateTime + 6); result += ossimString(separationChar); result += ossimString(theDateTime + 6, theDateTime + 8); result += ossimString(separationChar); result += ossimString(theDateTime, theDateTime + 4); return result; } ossimString ossimNitfImageHeaderV2_1::getCategory()const { return theCategory; } ossimString ossimNitfImageHeaderV2_1::getImageSource()const { return theImageSource; } ossimString ossimNitfImageHeaderV2_1::getRepresentation()const { return theRepresentation; } ossimString ossimNitfImageHeaderV2_1::getCoordinateSystem()const { return theCoordinateSystem; } ossimString ossimNitfImageHeaderV2_1::getGeographicLocation()const { return theGeographicLocation; } bool ossimNitfImageHeaderV2_1::hasBlockMaskRecords()const { return (theBlockMaskRecords.size() > 0); } bool ossimNitfImageHeaderV2_1::hasPadPixelMaskRecords()const { return (thePadPixelMaskRecords.size()>0); } bool ossimNitfImageHeaderV2_1::hasTransparentCode()const { return (theTransparentOutputPixelCodeLength > 0); } ossim_uint32 ossimNitfImageHeaderV2_1::getTransparentCode()const { return thePadOutputPixelCode; } ossim_uint32 ossimNitfImageHeaderV2_1::getBlockMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const { ossim_uint32 maxBlock = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol(); ossim_uint32 result = 0xffffffff; if((hasBlockMaskRecords())&& (blockNumber < maxBlock)) { if(theImageMode[0] == 'S') { if(bandNumber < (ossim_uint32)getNumberOfBands()) { result = theBlockMaskRecords[bandNumber*maxBlock + blockNumber]; } } else { result = theBlockMaskRecords[blockNumber]; } } return result; } ossim_uint32 ossimNitfImageHeaderV2_1::getPadPixelMaskRecordOffset(ossim_uint32 blockNumber, ossim_uint32 bandNumber)const { ossim_uint32 maxBlock = getNumberOfBlocksPerRow()*getNumberOfBlocksPerCol(); ossim_uint32 result = 0xffffffff; if((hasPadPixelMaskRecords())&& (blockNumber < maxBlock)) { if(theImageMode[0] == 'S') { if(bandNumber < (ossim_uint32)getNumberOfBands()) { result = thePadPixelMaskRecords[bandNumber*maxBlock + blockNumber]; } } else { result = thePadPixelMaskRecords[blockNumber]; } } return result; } void ossimNitfImageHeaderV2_1::clearFields() { memcpy(theType, "IM", 2); memset(theImageId, ' ',10); memset(theDateTime, '-',14); memset(theTargetId, ' ',17); memset(theTitle, ' ',80); memset(theSecurityClassification, ' ',1); memset(theSecurityClassificationSys, ' ',2); memset(theCodewords, ' ',11); memset(theControlAndHandling, ' ',2); memset(theReleasingInstructions, ' ',20); memset(theDeclassificationType, ' ',2); memset(theDeclassificationDate, ' ',8); memset(theDeclassificationExempt, ' ',4); memset(theDowngrade, ' ',1); memset(theDowngradeDate, ' ',8); memset(theClassificationText, ' ',43); memset(theClassificationAuthType, ' ',1); memset(theClassificationAuthority, ' ',40); memset(theClassificationReason, ' ',1); memset(theSecuritySourceDate, ' ',8); memset(theSecurityControlNumber, ' ',15); memset(theEncryption, '0',1); memset(theImageSource, ' ',42); memset(theSignificantRows, '0',8); memset(theSignificantCols, '0',8); memset(thePixelValueType, ' ',3); memset(theRepresentation, ' ',8); memset(theCategory, ' ',8); memset(theActualBitsPerPixelPerBand, ' ',2); memset(theJustification, 'R',1); memset(theCoordinateSystem, ' ',1); memset(theGeographicLocation, ' ',60); memset(theNumberOfComments, '0', 1); theImageComments.clear(); memcpy(theCompression, "NC",2); memset(theCompressionRateCode, ' ',4); memset(theNumberOfBands, '0',1); memset(theNumberOfMultispectralBands, ' ',5); memset(theImageSyncCode, '0', 1); memset(theImageMode, 'B', 1); memset(theNumberOfBlocksPerRow, '0', 4); memset(theNumberOfBlocksPerCol, '0', 4); memset(theNumberOfPixelsPerBlockHoriz, '0', 4); memset(theNumberOfPixelsPerBlockVert, '0', 4); memset(theNumberOfBitsPerPixelPerBand, '0', 2); memcpy(theDisplayLevel, "001", 3); memset(theAttachmentLevel, '0', 3); memset(theImageLocation, '0', 10); memcpy(theImageMagnification, "1.0 ", 4); memset(theUserDefinedImageDataLength,'0', 5); memset(theUserDefinedOverflow, '0', 3); memset(theExtendedSubheaderDataLen, '0', 5); memset(theExtendedSubheaderOverflow, '0', 3); theBlockMaskRecords.clear(); thePadPixelMaskRecords.clear(); theBlockedImageDataOffset = 0; theBlockMaskRecordLength = 0; thePadPixelMaskRecordLength = 0; theTransparentOutputPixelCodeLength = 0; thePadOutputPixelCode = 0; theCompressionHeader = 0; theType[2] = '\0'; theImageId[10] = '\0'; theDateTime[14] = '\0'; theTargetId[17] = '\0'; theTitle[80] = '\0'; theSecurityClassification[1] = '\0'; theSecurityClassificationSys[2] = '\0'; theCodewords[11] = '\0'; theControlAndHandling[2] = '\0'; theReleasingInstructions[20] = '\0'; theDeclassificationType[2] = '\0'; theDeclassificationDate[8] = '\0'; theDeclassificationExempt[4] = '\0'; theDowngrade[1] = '\0'; theDowngradeDate[8] = '\0'; theClassificationText[43] = '\0'; theClassificationAuthType[1] = '\0'; theClassificationAuthority[40] = '\0'; theClassificationReason[1] = '\0'; theSecuritySourceDate[8] = '\0'; theSecurityControlNumber[15] = '\0'; theEncryption[1] = '\0'; theImageSource[42] = '\0'; theSignificantRows[8] = '\0'; theSignificantCols[8] = '\0'; thePixelValueType[3] = '\0'; theRepresentation[8] = '\0'; theCategory[8] = '\0'; theActualBitsPerPixelPerBand[2] = '\0'; theJustification[1] = '\0'; theCoordinateSystem[1] = '\0'; theGeographicLocation[60] = '\0'; theNumberOfComments[1] = '\0'; theCompression[2] = '\0'; theCompressionRateCode[4] = '\0'; theNumberOfBands[1] = '\0'; theNumberOfMultispectralBands[5] = '\0'; theImageSyncCode[1] = '\0'; theImageMode[1] = '\0'; theNumberOfBlocksPerRow[4] = '\0'; theNumberOfBlocksPerCol[4] = '\0'; theNumberOfPixelsPerBlockHoriz[4] = '\0'; theNumberOfPixelsPerBlockVert[4] = '\0'; theNumberOfBitsPerPixelPerBand[2] = '\0'; theDisplayLevel[3] = '\0'; theAttachmentLevel[3] = '\0'; theImageLocation[10] = '\0'; theImageMagnification[4] = '\0'; theUserDefinedImageDataLength[5] = '\0'; theUserDefinedOverflow[3] = '\0'; theExtendedSubheaderDataLen[5] = '\0'; theExtendedSubheaderOverflow[3] = '\0'; theDataLocation = 0; } ossim_int32 ossimNitfImageHeaderV2_1::getNumberOfBlocksPerRow()const { return ossimString(theNumberOfBlocksPerRow).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_1::getNumberOfBlocksPerCol()const { return ossimString(theNumberOfBlocksPerCol).toInt32(); } ossim_int32 ossimNitfImageHeaderV2_1::getNumberOfPixelsPerBlockHoriz()const { // return ossimString(theNumberOfPixelsPerBlockHoriz).toInt32(); ossim_int32 rval = ossimString(theNumberOfPixelsPerBlockHoriz).toInt32(); if ((rval == 0) && (getNumberOfBlocksPerCol() == 1)) { rval = getNumberOfCols(); } return rval; } ossim_int32 ossimNitfImageHeaderV2_1::getNumberOfPixelsPerBlockVert()const { // return ossimString(theNumberOfPixelsPerBlockVert).toInt32(); ossim_int32 rval = ossimString(theNumberOfPixelsPerBlockVert).toInt32(); if ((rval == 0) && (getNumberOfBlocksPerRow() == 1)) { rval = getNumberOfRows(); } return rval; } ossimIrect ossimNitfImageHeaderV2_1::getImageRect()const { // ossimDpt ul(ossimString((char*)(&theImageLocation[5])).toDouble(), // ossimString((char*)theImageLocation, // (char*)(&theImageLocation[5])).toDouble()); ossimDpt ul(0.0,0.0); double rows = ossimString(theSignificantRows).toDouble(); double cols = ossimString(theSignificantCols).toDouble(); // ossimDpt lr(ul.x + cols-1, // ul.y + rows-1); ossimDpt lr(cols-1, rows-1); return ossimIrect(ul, lr); } ossimIrect ossimNitfImageHeaderV2_1::getBlockImageRect()const { // ossimDpt ul(ossimString((char*)(&theImageLocation[5])).toDouble(), // ossimString((char*)theImageLocation, //g (char*)(&theImageLocation[5])).toDouble()); ossimDpt ul(0.0,0.0); double rows = getNumberOfPixelsPerBlockVert()*getNumberOfBlocksPerCol(); double cols = getNumberOfPixelsPerBlockHoriz()*getNumberOfBlocksPerRow();; // ossimDpt lr(ul.x + cols-1, // ul.y + rows-1); ossimDpt lr(cols-1, rows-1); return ossimIrect(ul, lr); } ossimString ossimNitfImageHeaderV2_1::getPixelValueType()const { return ossimString(thePixelValueType).trim(); } void ossimNitfImageHeaderV2_1::setNumberOfBands(ossim_uint32 nbands) { std::ostringstream out; if(nbands > 9) { out << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << nbands; theNumberOfBands[0] = '0'; memcpy(theNumberOfMultispectralBands, out.str().c_str(), 5); } else { out << nbands; theNumberOfBands[0] = out.str().c_str()[0]; } theImageBands.resize(getNumberOfBands()); } void ossimNitfImageHeaderV2_1::setBandInfo(ossim_uint32 idx, const ossimNitfImageBandV2_1& info) { if(idx < theImageBands.size()) { if(!theImageBands[idx].valid()) { theImageBands[idx] = new ossimNitfImageBandV2_1; } (*theImageBands[idx]) = info; } } void ossimNitfImageHeaderV2_1::setNumberOfRows(ossim_uint32 rows) { std::ostringstream out; if(rows > 99999999) rows = 99999999; out << rows; ossimNitfCommon::setField(theSignificantRows, out.str(), 8, ios::right, '0'); } void ossimNitfImageHeaderV2_1::setNumberOfCols(ossim_uint32 cols) { std::ostringstream out; if(cols > 99999999) cols = 99999999; out << cols; ossimNitfCommon::setField(theSignificantCols, out.str(), 8, ios::right, '0'); } void ossimNitfImageHeaderV2_1::setGeographicLocationDms(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << ossimDms(ul.y, true).toString("ddmmss.ssssC").c_str() << ossimDms(ul.x, false).toString("dddmmss.ssssC").c_str() << ossimDms(ur.y, true).toString("ddmmss.ssssC").c_str() << ossimDms(ur.x, false).toString("dddmmss.ssssC").c_str() << ossimDms(lr.y, true).toString("ddmmss.ssssC").c_str() << ossimDms(lr.x, false).toString("dddmmss.ssssC").c_str() << ossimDms(ll.y, true).toString("ddmmss.ssssC").c_str() << ossimDms(ll.x, false).toString("dddmmss.ssssC").c_str() << std::endl; checkForGeographicTiePointTruncation(ul); checkForGeographicTiePointTruncation(ur); checkForGeographicTiePointTruncation(lr); checkForGeographicTiePointTruncation(ll); } theCoordinateSystem[0] = 'G'; std::ostringstream out; out << ossimDms(ul.y, true).toString("ddmmssC").c_str(); out << ossimDms(ul.x, false).toString("dddmmssC").c_str(); out << ossimDms(ur.y, true).toString("ddmmssC").c_str(); out << ossimDms(ur.x, false).toString("dddmmssC").c_str(); out << ossimDms(lr.y, true).toString("ddmmssC").c_str(); out << ossimDms(lr.x, false).toString("dddmmssC").c_str(); out << ossimDms(ll.y, true).toString("ddmmssC").c_str(); out << ossimDms(ll.x, false).toString("dddmmssC").c_str(); memcpy(theGeographicLocation, out.str().c_str(), 60); } void ossimNitfImageHeaderV2_1::setGeographicLocationDecimalDegrees( const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { theCoordinateSystem[0] = 'D'; ostringstream out; out << (ul.lat >= 0.0?"+":"") << std::setw(6) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ul.lat << (ul.lon >= 0.0?"+":"") << std::setw(7) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ul.lon; out << (ur.lat >= 0.0?"+":"") << std::setw(6) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ur.lat << (ur.lon >= 0.0?"+":"") << std::setw(7) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ur.lon; out << (lr.lat >= 0.0?"+":"") << std::setw(6) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << lr.lat << (lr.lon >= 0.0?"+":"") << std::setw(7) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << lr.lon; out << (ll.lat >= 0.0?"+":"") << std::setw(6) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ll.lat << (ll.lon >= 0.0?"+":"") << std::setw(7) << std::setfill('0') << std::setprecision(3) << std::setiosflags(std::ios::fixed) << ll.lon; memcpy(theGeographicLocation, out.str().c_str(), 60); } void ossimNitfImageHeaderV2_1::setUtmNorth(ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { theCoordinateSystem[0] = 'N'; memcpy(theGeographicLocation, encodeUtm(zone, ul, ur, lr, ll).c_str(), 60); } void ossimNitfImageHeaderV2_1::setUtmSouth(ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { theCoordinateSystem[0] = 'S'; memcpy(theGeographicLocation, encodeUtm(zone, ul, ur, lr, ll).c_str(), 60); } void ossimNitfImageHeaderV2_1::setSecurityClassificationSystem(const ossimString& value) { ossimNitfCommon::setField(theSecurityClassificationSys, value, 2); } void ossimNitfImageHeaderV2_1::setCodewords(const ossimString& value) { ossimNitfCommon::setField(theCodewords, value, 11); } void ossimNitfImageHeaderV2_1::setControlAndHandling(const ossimString& value) { ossimNitfCommon::setField(theControlAndHandling, value, 2); } void ossimNitfImageHeaderV2_1::setReleasingInstructions(const ossimString& value) { ossimNitfCommon::setField(theReleasingInstructions, value, 20); } void ossimNitfImageHeaderV2_1::setDeclassificationType(const ossimString& value) { ossimNitfCommon::setField(theDeclassificationType, value, 2); } void ossimNitfImageHeaderV2_1::setDeclassificationDate(const ossimString& value) { ossimNitfCommon::setField(theDeclassificationDate, value, 8); } void ossimNitfImageHeaderV2_1::setDeclassificationExempt(const ossimString& value) { ossimNitfCommon::setField(theDeclassificationExempt, value, 4); } void ossimNitfImageHeaderV2_1::setDowngrade(const ossimString& value) { ossimNitfCommon::setField(theDowngrade, value, 1); } void ossimNitfImageHeaderV2_1::setDowngradeDate(const ossimString& value) { ossimNitfCommon::setField(theDowngradeDate, value, 8); } void ossimNitfImageHeaderV2_1::setClassificationText(const ossimString& value) { ossimNitfCommon::setField(theClassificationText, value, 43); } void ossimNitfImageHeaderV2_1::setClassificationAuthorityType(const ossimString& value) { ossimNitfCommon::setField(theClassificationAuthType, value, 1); } void ossimNitfImageHeaderV2_1::setClassificationAuthority(const ossimString& value) { ossimNitfCommon::setField(theClassificationAuthority, value, 40); } void ossimNitfImageHeaderV2_1::setClassificationReason(const ossimString& value) { ossimNitfCommon::setField(theClassificationReason, value, 1); } void ossimNitfImageHeaderV2_1::setSecuritySourceDate(const ossimString& value) { ossimNitfCommon::setField(theSecuritySourceDate, value, 8); } void ossimNitfImageHeaderV2_1::setSecurityControlNumber(const ossimString& value) { ossimNitfCommon::setField(theSecurityControlNumber, value, 15); } void ossimNitfImageHeaderV2_1::setImageMagnification(const ossimString& value) { ossimNitfCommon::setField(theImageMagnification, value, 4); } void ossimNitfImageHeaderV2_1::setProperty(ossimRefPtr property) { ossimString name = property->getName(); // Make case insensitive: name.downcase(); std::ostringstream out; if(!property) return; if(name.contains(ISCLSY_KW)) { setSecurityClassificationSystem(property->valueToString()); } else if(name.contains(ISCODE_KW)) { setCodewords(property->valueToString()); } else if(name.contains(ISCTLH_KW)) { setControlAndHandling(property->valueToString()); } else if(name.contains(ISREL_KW)) { setReleasingInstructions(property->valueToString()); } else if(name.contains(ISDCTP_KW)) { setDeclassificationType(property->valueToString()); } else if(name.contains(ISDCDT_KW)) { setDeclassificationDate(property->valueToString()); } else if(name.contains(ISDCXM_KW)) { setDeclassificationExempt(property->valueToString()); } else if(name.contains(ISDGDT_KW)) // Must be before: "ISDG_KW" { setDowngradeDate(property->valueToString()); } else if(name.contains(ISDG_KW)) { setDowngrade(property->valueToString()); } else if(name.contains(ISCLTX_KW)) { setClassificationText(property->valueToString()); } else if(name.contains(ISCATP_KW)) { setClassificationAuthorityType(property->valueToString()); } else if(name.contains(ISCAUT_KW)) { setClassificationAuthority(property->valueToString()); } else if(name.contains(ISCRSN_KW)) { setClassificationReason(property->valueToString()); } else if(name == ISCRSN_KW) { property = new ossimStringProperty(name, ossimString(theClassificationReason).trim()); } else if(name.contains(ISSRDT_KW)) { setSecuritySourceDate(property->valueToString()); } else if(name.contains(ISCTLN_KW)) { setSecurityControlNumber(property->valueToString()); } else { ossimNitfImageHeaderV2_X::setProperty(property); } } ossimRefPtr ossimNitfImageHeaderV2_1::getProperty(const ossimString& name)const { ossimProperty* property = 0; if(name == ISCLSY_KW) { property = new ossimStringProperty(name, ossimString(theSecurityClassificationSys).trim()); } else if(name == ISCODE_KW) { property = new ossimStringProperty(name, ossimString(theCodewords).trim()); } else if(name == ISCTLH_KW) { property = new ossimStringProperty(name, ossimString(theControlAndHandling).trim()); } else if(name == ISREL_KW) { property = new ossimStringProperty(name, ossimString(theReleasingInstructions).trim()); } else if(name == ISDCTP_KW) { property = new ossimStringProperty(name, ossimString(theDeclassificationType).trim()); } else if(name == ISDCDT_KW) { property = new ossimStringProperty(name, ossimString(theDeclassificationDate).trim()); } else if(name == ISDCXM_KW) { property = new ossimStringProperty(name, ossimString(theDeclassificationExempt).trim()); } else if(name == ISDG_KW) { property = new ossimStringProperty(name, ossimString(theDowngrade).trim()); } else if(name == ISDGDT_KW) { property = new ossimStringProperty(name, ossimString(theDowngradeDate).trim()); } else if(name == ISCLTX_KW) { property = new ossimStringProperty(name, ossimString(theClassificationText).trim()); } else if(name == ISCATP_KW) { property = new ossimStringProperty(name, ossimString(theClassificationAuthType).trim()); } else if(name == ISCAUT_KW) { property = new ossimStringProperty(name, ossimString(theClassificationAuthority).trim()); } else if(name == ISCRSN_KW) { property = new ossimStringProperty(name, ossimString(theClassificationReason).trim()); } else if(name == ISSRDT_KW) { property = new ossimStringProperty(name, ossimString(theSecuritySourceDate).trim()); } else if(name == ISCTLN_KW) { property = new ossimStringProperty(name, ossimString(theSecurityControlNumber).trim()); } else { return ossimNitfImageHeaderV2_X::getProperty(name); } return property; } void ossimNitfImageHeaderV2_1::getPropertyNames(std::vector& propertyNames)const { ossimNitfImageHeaderV2_X::getPropertyNames(propertyNames); propertyNames.push_back(ISCLSY_KW); propertyNames.push_back(ISCODE_KW); propertyNames.push_back(ISCTLH_KW); propertyNames.push_back(ISREL_KW); propertyNames.push_back(ISDCTP_KW); propertyNames.push_back(ISDCDT_KW); propertyNames.push_back(ISDCXM_KW); propertyNames.push_back(ISDG_KW); propertyNames.push_back(ISDGDT_KW); propertyNames.push_back(ISCLTX_KW); propertyNames.push_back(ISCATP_KW); propertyNames.push_back(ISCAUT_KW); propertyNames.push_back(ISCRSN_KW); propertyNames.push_back(ISSRDT_KW); propertyNames.push_back(ISCTLN_KW); propertyNames.push_back(XBANDS_KW); } const ossimRefPtr ossimNitfImageHeaderV2_1::getCompressionHeader()const { return theCompressionHeader; } const ossimRefPtr ossimNitfImageHeaderV2_1::getBandInformation(ossim_uint32 idx)const { if(idx < theImageBands.size()) { return (ossimNitfImageBand*)theImageBands[idx].get(); } return 0; } ossimString ossimNitfImageHeaderV2_1::encodeUtm( ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) const { ostringstream out; if(zone > 60) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUTM zone greate than 60!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } ossim_float64 east = ul.x; ossim_float64 north = ul.y; if((ossim_uint32)(east+.5) > 999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUpper left easting too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } if((ossim_uint32)(north+.5) > 9999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUpper left northing too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } out << setw(2) << setfill('0') << zone << setw(6) << setfill('0') <<(ossim_uint32)(east+.5) << setw(7) << setfill('0') <<(ossim_uint32)(north+.5); east = ur.x; north = ur.y; if((ossim_uint32)(east+.5) > 999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUpper right easting too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } if((ossim_uint32)(north+.5) > 9999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nUpper right northing too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } out << setw(2) << setfill('0') << zone << setw(6) << setfill('0') <<(ossim_uint32)(east+.5) << setw(7) << setfill('0') <<(ossim_uint32)(north+.5); east = lr.x; north = lr.y; if((ossim_uint32)(east+.5) > 999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nLower right easting too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } if((ossim_uint32)(north+.5) > 9999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nLower right northing too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } out << setw(2) << setfill('0') << zone << setw(6) << setfill('0') <<(ossim_uint32)(east+.5) << setw(7) << setfill('0') <<(ossim_uint32)(north+.5); east = ll.x; north = ll.y; if((ossim_uint32)(east+.5) > 999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nLower left easting too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } if((ossim_uint32)(north+.5) > 9999999) { std::string s = "ossimNitfImageHeaderV2_1::encodeUtm: ERROR\nLower left northing too large for NITF field!"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << s << std::endl; } throw std::out_of_range(s); } out << setw(2) << setfill('0') << zone << setw(6) << setfill('0') <<(ossim_uint32)(east+.5) << setw(7) << setfill('0') <<(ossim_uint32)(north+.5); return out.str().c_str(); } bool ossimNitfImageHeaderV2_1::takeOverflowTags(std::vector &overflowTags, ossim_uint32 potentialDesIndex, bool userDefinedTags) { overflowTags.clear(); std::vector::iterator iter; std::vector specifiedTags; const ossimString tagType(userDefinedTags ? "UDID" : "IXSHD"); for (iter = theTagList.begin(); iter != theTagList.end(); ++iter) { if (iter->getTagType() == tagType) { specifiedTags.push_back(*iter); } } std::sort(specifiedTags.begin(), specifiedTags.end()); ossim_uint32 totalSize = 0; const ossim_uint32 maxSize = 9996; for (iter = specifiedTags.begin(); iter != specifiedTags.end() && totalSize + iter->getTotalTagLength() <= maxSize; ++iter) { totalSize += iter->getTotalTagLength(); } for (; iter != specifiedTags.end(); ++iter) { overflowTags.push_back(*iter); removeTag(iter->getTagName()); } // If there are no overflow tags, then no DES is required if (overflowTags.empty() == true) { potentialDesIndex = 0; } std::ostringstream overflowDes; overflowDes << std::setw(3) << std::setfill('0') << std::setiosflags(ios::right) << potentialDesIndex; std::ostringstream tagLength; tagLength << std::setw(5) << std::setfill('0') << std::setiosflags(ios::right) << totalSize; if (userDefinedTags) { strcpy(theUserDefinedOverflow, overflowDes.str().c_str()); strcpy(theUserDefinedImageDataLength, tagLength.str().c_str()); } else { strcpy(theExtendedSubheaderOverflow, overflowDes.str().c_str()); strcpy(theExtendedSubheaderDataLen, tagLength.str().c_str()); } return (overflowTags.empty() == false); } ossim-Miami-2.9.1/src/support_data/ossimNitfImageHeaderV2_X.cpp000066400000000000000000000767111352751253100244550ustar00rootroot00000000000000#include #include /* for fmod */ #include #include #include #include #include #include #include #include #include #include #include static const ossimTrace traceDebug( ossimString("ossimNitfImageHeaderV2_X:debug")); const ossimString ossimNitfImageHeaderV2_X::IM_KW = "IM"; const ossimString ossimNitfImageHeaderV2_X::IID1_KW = "IID1"; const ossimString ossimNitfImageHeaderV2_X::IDATIM_KW = "IDATIM"; const ossimString ossimNitfImageHeaderV2_X::TGTID_KW = "TGTID"; const ossimString ossimNitfImageHeaderV2_X::IID2_KW = "IID2"; const ossimString ossimNitfImageHeaderV2_X::ITITLE_KW = "ITITLE"; const ossimString ossimNitfImageHeaderV2_X::ISCLAS_KW = "ISCLAS"; const ossimString ossimNitfImageHeaderV2_X::ENCRYP_KW = "ENCRYP"; const ossimString ossimNitfImageHeaderV2_X::ISORCE_KW = "ISORCE"; const ossimString ossimNitfImageHeaderV2_X::NROWS_KW = "NROWS"; const ossimString ossimNitfImageHeaderV2_X::NCOLS_KW = "NCOLS"; const ossimString ossimNitfImageHeaderV2_X::PVTYPE_KW = "PVTYPE"; const ossimString ossimNitfImageHeaderV2_X::IREP_KW = "IREP"; const ossimString ossimNitfImageHeaderV2_X::ICAT_KW = "ICAT"; const ossimString ossimNitfImageHeaderV2_X::ABPP_KW = "ABPP"; const ossimString ossimNitfImageHeaderV2_X::PJUST_KW = "PJUST"; const ossimString ossimNitfImageHeaderV2_X::ICORDS_KW = "ICORDS"; const ossimString ossimNitfImageHeaderV2_X::IGEOLO_KW = "IGEOLO"; const ossimString ossimNitfImageHeaderV2_X::NICOM_KW = "NICOM"; const ossimString ossimNitfImageHeaderV2_X::ICOM_KW = "ICOM"; const ossimString ossimNitfImageHeaderV2_X::IC_KW = "IC"; const ossimString ossimNitfImageHeaderV2_X::COMRAT_KW = "COMRAT"; const ossimString ossimNitfImageHeaderV2_X::NBANDS_KW = "NBANDS"; const ossimString ossimNitfImageHeaderV2_X::ISYNC_KW = "ISYNC"; const ossimString ossimNitfImageHeaderV2_X::IMODE_KW = "IMODE"; const ossimString ossimNitfImageHeaderV2_X::NBPR_KW = "NBPR"; const ossimString ossimNitfImageHeaderV2_X::NBPC_KW = "NBPC"; const ossimString ossimNitfImageHeaderV2_X::NPPBH_KW = "NPPBH"; const ossimString ossimNitfImageHeaderV2_X::NPPBV_KW = "NPPBV"; const ossimString ossimNitfImageHeaderV2_X::NBPP_KW = "NBPP"; const ossimString ossimNitfImageHeaderV2_X::IDLVL_KW = "IDLVL"; const ossimString ossimNitfImageHeaderV2_X::IALVL_KW = "IALVL"; const ossimString ossimNitfImageHeaderV2_X::ILOC_KW = "ILOC"; const ossimString ossimNitfImageHeaderV2_X::IMAG_KW = "IMAG"; const ossimString ossimNitfImageHeaderV2_X::UDIDL_KW = "UDIDL"; const ossimString ossimNitfImageHeaderV2_X::UDOFL_KW = "UDOFL"; const ossimString ossimNitfImageHeaderV2_X::IXSHDL_KW = "IXSHDL"; const ossimString ossimNitfImageHeaderV2_X::IXSOFL_KW = "IXSOFL"; const ossimString ossimNitfImageHeaderV2_X::IMDATOFF_KW = "IMDATOFF"; const ossimString ossimNitfImageHeaderV2_X::BMRLNTH_KW = "BMRLNTH"; RTTI_DEF1(ossimNitfImageHeaderV2_X, "ossimNitfImageHeaderV2_X", ossimNitfImageHeader); ossimNitfImageHeaderV2_X::ossimNitfImageHeaderV2_X() :theImageComments() { } ossimIrect ossimNitfImageHeaderV2_X::getImageRect()const { ossimIpt ul(0, 0); ossimIpt lr(getNumberOfCols()-1, getNumberOfRows()-1); return ossimIrect(ul, lr); #if 0 //--- // Changed to not include offset 20100619 (drb). // Use void getImageLocation(ossimIpt& loc)const to get offset. //--- ossimDpt ul(ossimString((char*)(&theImageLocation[5])).toDouble(), ossimString((char*)theImageLocation, (char*)(&theImageLocation[5])).toDouble()); double rows = ossimString(theSignificantRows).toDouble(); double cols = ossimString(theSignificantCols).toDouble(); ossimDpt lr(ul.x + cols-1, ul.y + rows-1); return ossimDrect(ul, lr); #endif } ossimIrect ossimNitfImageHeaderV2_X::getBlockImageRect()const { ossimIpt ul(0, 0); ossimIpt lr( (getNumberOfPixelsPerBlockHoriz()*getNumberOfBlocksPerRow())-1, (getNumberOfPixelsPerBlockVert() *getNumberOfBlocksPerCol())-1); return ossimIrect(ul, lr); #if 0 //--- // Changed to not include offset 20100619 (drb). // Use void getImageLocation(ossimIpt& loc)const to get offset. //--- ossimDpt ul(ossimString((char*)(&theImageLocation[5])).toDouble(), ossimString((char*)theImageLocation, (char*)(&theImageLocation[5])).toDouble()); double rows = getNumberOfPixelsPerBlockVert()*getNumberOfBlocksPerCol(); double cols = getNumberOfPixelsPerBlockHoriz()*getNumberOfBlocksPerRow();; ossimDpt lr(ul.x + cols-1, ul.y + rows-1); return ossimDrect(ul, lr); #endif } void ossimNitfImageHeaderV2_X::setImageId(const ossimString& value) { ossimNitfCommon::setField(theImageId, value, 10); } void ossimNitfImageHeaderV2_X::setAquisitionDateTime(const ossimString& value) { ossimNitfCommon::setField(theDateTime, value, 14); } void ossimNitfImageHeaderV2_X::setTargetId(const ossimString& value) { ossimNitfCommon::setField(theTargetId, value, 17); } void ossimNitfImageHeaderV2_X::setTitle(const ossimString& value) { ossimNitfCommon::setField(theTitle, value, 80); } void ossimNitfImageHeaderV2_X::setSecurityClassification(const ossimString& value) { ossimNitfCommon::setField(theSecurityClassification, value, 1); } void ossimNitfImageHeaderV2_X::setEncryption(const ossimString& value) { ossimNitfCommon::setField(theEncryption, value, 1); } void ossimNitfImageHeaderV2_X::setImageSource(const ossimString& value) { ossimNitfCommon::setField(theImageSource, value, 42); } void ossimNitfImageHeaderV2_X::setJustification(const ossimString& value) { ossimNitfCommon::setField(theJustification, value, 1); } void ossimNitfImageHeaderV2_X::setCoordinateSystem(const ossimString& value) { ossimNitfCommon::setField(theCoordinateSystem, value, 1); } void ossimNitfImageHeaderV2_X::setGeographicLocation(const ossimString& value) { ossimNitfCommon::setField(theGeographicLocation, value, 60); } void ossimNitfImageHeaderV2_X::setNumberOfComments(const ossimString& value) { ossimNitfCommon::setField(theNumberOfComments, value, 1); } void ossimNitfImageHeaderV2_X::setCompression(const ossimString& value) { ossimNitfCommon::setField(theCompression, value, 2); } void ossimNitfImageHeaderV2_X::setCompressionRateCode(const ossimString& value) { ossimNitfCommon::setField(theCompressionRateCode, value, 4); } void ossimNitfImageHeaderV2_X::setDisplayLevel(const ossimString& value) { ossimNitfCommon::setField(theDisplayLevel, value, 3, std::ios::right, '0'); } void ossimNitfImageHeaderV2_X::setAttachmentLevel(const ossimString& value) { ossimNitfCommon::setField(theAttachmentLevel, value, 3); } void ossimNitfImageHeaderV2_X::setPixelType(const ossimString& pixelType) { ossimNitfCommon::setField(thePixelValueType, pixelType, 3); } void ossimNitfImageHeaderV2_X::setBitsPerPixel(ossim_uint32 bitsPerPixel) { std::stringstream strm; strm << bitsPerPixel; ossimNitfCommon::setField(theNumberOfBitsPerPixelPerBand, strm.str(), 2, std::ios::right, '0'); } void ossimNitfImageHeaderV2_X::setActualBitsPerPixel(ossim_uint32 bitsPerPixel) { std::stringstream strm; strm << bitsPerPixel; ossimNitfCommon::setField(theActualBitsPerPixelPerBand, strm.str(), 2, std::ios::right, '0'); } void ossimNitfImageHeaderV2_X::setImageMode(char mode) { theImageMode[0] = mode; } void ossimNitfImageHeaderV2_X::setCategory(const ossimString& category) { ossimNitfCommon::setField(theCategory, category, 8); } void ossimNitfImageHeaderV2_X::setRepresentation(const ossimString& rep) { ossimNitfCommon::setField(theRepresentation, rep, 8); } void ossimNitfImageHeaderV2_X::setBlocksPerRow(ossim_uint32 blocks) { std::stringstream strm; strm << blocks; ossimNitfCommon::setField(theNumberOfBlocksPerRow, strm.str(), 4, std::ios::right, '0'); } void ossimNitfImageHeaderV2_X::setBlocksPerCol(ossim_uint32 blocks) { std::stringstream strm; strm << blocks; ossimNitfCommon::setField(theNumberOfBlocksPerCol, strm.str(), 4, std::ios::right, '0'); } void ossimNitfImageHeaderV2_X::setNumberOfPixelsPerBlockRow(ossim_uint32 pixels) { std::stringstream strm; strm << pixels; ossimNitfCommon::setField(theNumberOfPixelsPerBlockHoriz, strm.str(), 4, std::ios::right, '0'); } void ossimNitfImageHeaderV2_X::setNumberOfPixelsPerBlockCol(ossim_uint32 pixels) { std::stringstream strm; strm << pixels; ossimNitfCommon::setField(theNumberOfPixelsPerBlockVert, strm.str(), 4, std::ios::right, '0'); } ossim_uint64 ossimNitfImageHeaderV2_X::getDataLocation() const { return theDataLocation; } ossimString ossimNitfImageHeaderV2_X::getImageId()const { return theImageId; } ossimString ossimNitfImageHeaderV2_X::getAquisitionDateTime()const { return theDateTime; } ossimString ossimNitfImageHeaderV2_X::getTargetId()const { return ossimString(theTargetId).trim(); } ossimString ossimNitfImageHeaderV2_X::getTitle()const { return ossimString(theTitle).trim(); } ossimString ossimNitfImageHeaderV2_X::getSecurityClassification()const { return ossimString(theSecurityClassification).trim(); } ossimString ossimNitfImageHeaderV2_X::getEncryption()const { return ossimString(theEncryption).trim(); } ossimString ossimNitfImageHeaderV2_X::getImageSource()const { return ossimString(theImageSource).trim(); } ossimString ossimNitfImageHeaderV2_X::getJustification()const { return ossimString(theJustification).trim(); } ossimString ossimNitfImageHeaderV2_X::getCoordinateSystem()const { return ossimString(theCoordinateSystem).trim(); } ossimString ossimNitfImageHeaderV2_X::getGeographicLocation()const { return ossimString(theGeographicLocation).trim(); } ossimString ossimNitfImageHeaderV2_X::getNumberOfComments()const { return ossimString(theNumberOfComments).trim(); } ossimString ossimNitfImageHeaderV2_X::getCompressionCode()const { return ossimString(theCompression).trim(); } ossimString ossimNitfImageHeaderV2_X::getCompressionRateCode()const { return theCompressionRateCode; } ossim_uint32 ossimNitfImageHeaderV2_X::getDisplayLevel()const { return ossimString(theDisplayLevel).toUInt32(); } ossim_uint32 ossimNitfImageHeaderV2_X::getAttachmentLevel()const { return ossimString(theAttachmentLevel).toUInt32(); } ossimString ossimNitfImageHeaderV2_X::getPixelType()const { return thePixelValueType; } ossim_uint32 ossimNitfImageHeaderV2_X::getBitsPerPixel()const { return ossimString(theNumberOfBitsPerPixelPerBand).toUInt32(); } ossim_uint32 ossimNitfImageHeaderV2_X::getActualBitsPerPixel()const { return ossimString(theActualBitsPerPixelPerBand).toUInt32(); } char ossimNitfImageHeaderV2_X::getImageMode()const { return theImageMode[0]; } ossimString ossimNitfImageHeaderV2_X::getCategory()const { return theCategory; } ossimString ossimNitfImageHeaderV2_X::getRepresentation()const { return theRepresentation; } ossim_uint32 ossimNitfImageHeaderV2_X::getBlocksPerRow()const { return ossimString(theNumberOfBlocksPerRow).toUInt32(); } ossim_uint32 ossimNitfImageHeaderV2_X::getBlocksPerCol()const { return ossimString(theNumberOfBlocksPerCol).toUInt32(); } ossim_uint32 ossimNitfImageHeaderV2_X::getNumberOfPixelsPerBlockRow()const { return ossimString(theNumberOfPixelsPerBlockVert).toUInt32(); } ossim_uint32 ossimNitfImageHeaderV2_X::getNumberOfPixelsPerBlockCol()const { return ossimString(theNumberOfPixelsPerBlockHoriz).toUInt32(); } bool ossimNitfImageHeaderV2_X::isValid()const { if((theType[0] != 'I') || theType[1] != 'M') { return false; } ossim_uint32 actualBitsPerPixel = getActualBitsPerPixel(); ossim_uint32 bitsPerPixel = getBitsPerPixel(); if(actualBitsPerPixel>bitsPerPixel) { return false; } return true; } bool ossimNitfImageHeaderV2_X::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Note: Currently not looking up all fieds only ones that make sense. const char* lookup; lookup = kwl.find( prefix, IID1_KW); if ( lookup ) { setImageId( ossimString(lookup) ); } lookup = kwl.find( prefix, IDATIM_KW); if ( lookup ) { setAquisitionDateTime( ossimString(lookup) ); } lookup = kwl.find( prefix, TGTID_KW); if ( lookup ) { setTargetId( ossimString(lookup) ); } lookup = kwl.find( prefix, IID2_KW); if ( lookup ) { setTitle( ossimString(lookup) ); } lookup = kwl.find( prefix, ITITLE_KW); // duplicate of above if ( lookup ) { setTitle( ossimString(lookup) ); } lookup = kwl.find( prefix, ISCLAS_KW); if ( lookup ) { setSecurityClassification( ossimString(lookup) ); } lookup = kwl.find( prefix, ENCRYP_KW); if ( lookup ) { setEncryption( ossimString(lookup) ); } lookup = kwl.find( prefix, ISORCE_KW); if ( lookup ) { setImageSource( ossimString(lookup) ); } lookup = kwl.find( prefix, NROWS_KW); if ( lookup ) { ossimNitfCommon::setField(theSignificantRows, ossimString(lookup), 8); } lookup = kwl.find( prefix, NCOLS_KW); if ( lookup ) { ossimNitfCommon::setField(theSignificantCols, ossimString(lookup), 8); } lookup = kwl.find( prefix, PVTYPE_KW); if ( lookup ) { ossimNitfCommon::setField(thePixelValueType, ossimString(lookup), 3); } lookup = kwl.find( prefix, IREP_KW); if ( lookup ) { ossimNitfCommon::setField(theRepresentation, ossimString(lookup), 8); } lookup = kwl.find( prefix, ICAT_KW); if ( lookup ) { setCategory( ossimString(lookup) ); } lookup = kwl.find( prefix, ABPP_KW); if ( lookup ) { ossimNitfCommon::setField(theActualBitsPerPixelPerBand, ossimString(lookup), 2); } lookup = kwl.find( prefix, NBPP_KW); if ( lookup ) { setBitsPerPixel(ossimString(lookup).toUInt32()); } lookup = kwl.find( prefix, PJUST_KW); if ( lookup ) { setJustification(ossimString(lookup)); } lookup = kwl.find( prefix, ICORDS_KW); if ( lookup ) { setCoordinateSystem(ossimString(lookup)); } lookup = kwl.find( prefix, IGEOLO_KW); if ( lookup ) { setGeographicLocation(ossimString(lookup)); } lookup = kwl.find( prefix, NICOM_KW); if ( lookup ) { setNumberOfComments(ossimString(lookup)); } ossim_uint32 numberOfComments = ossimString(theNumberOfComments).toUInt32(); if (numberOfComments > 0) { theImageComments.resize(numberOfComments); for(ossim_uint32 i=0; i < numberOfComments; ++i) { ossimString icpre = ossimString(ICOM_KW) + ossimString::toString(i); lookup = kwl.find( prefix, icpre ); theImageComments[i] = ossimString(lookup); } } lookup = kwl.find( prefix, IC_KW); if ( lookup ) { setCompression(ossimString(lookup)); } lookup = kwl.find( prefix, COMRAT_KW); if ( lookup ) { setCompressionRateCode(ossimString(lookup)); } lookup = kwl.find( prefix, IMODE_KW); if ( lookup ) { setImageMode(lookup[0]); } lookup = kwl.find( prefix, ISYNC_KW); if ( lookup ) { ossimNitfCommon::setField(theImageSyncCode, ossimString(lookup), 1); } lookup = kwl.find( prefix, IALVL_KW); if ( lookup ) { setAttachmentLevel(ossimString(lookup)); } lookup = kwl.find( prefix, IDLVL_KW); if ( lookup ) { setDisplayLevel(ossimString(lookup)); } return true; } void ossimNitfImageHeaderV2_X::setProperty(ossimRefPtr property) { ossimString name = property->getName(); // Make case insensitive: name.upcase(); std::ostringstream out; if(!property) return; if(name.contains(IID1_KW)) { setImageId(property->valueToString()); } else if(name.contains(IDATIM_KW)) { setAquisitionDateTime(property->valueToString()); } else if(name.contains(TGTID_KW)) { setTargetId(property->valueToString()); } else if(name.contains(IID2_KW)|| name.contains(ITITLE_KW)) { setTitle(property->valueToString()); } else if(name.contains(ISCLAS_KW)) { setSecurityClassification(property->valueToString()); } else if(name.contains(ENCRYP_KW)) { setEncryption(property->valueToString()); } else if(name.contains(ISORCE_KW)) { setImageSource(property->valueToString()); } else if(name.contains(PVTYPE_KW)) { setPixelType(property->valueToString()); } else if(name.contains(IREP_KW)) { setRepresentation(property->valueToString()); } else if(name.contains(ICAT_KW)) { setCategory(property->valueToString()); } else if(name.contains(ABPP_KW)) { setActualBitsPerPixel(property->valueToString().toUInt32()); } else if(name.contains(PJUST_KW)) { setJustification(property->valueToString()); } else if(name.contains(ICORDS_KW)) { setCoordinateSystem(property->valueToString()); } else if(name.contains(IGEOLO_KW)) { setGeographicLocation(property->valueToString()); } else if(name.contains(NICOM_KW)) { setNumberOfComments(property->valueToString()); } else if(name.contains(IC_KW)) { setCompression(property->valueToString()); } else if(name.contains(COMRAT_KW)) { setCompressionRateCode(property->valueToString()); } else if(name.contains(ISYNC_KW)) { } else if(name.contains(IMODE_KW)) { setImageMode(*(property->valueToString().trim().begin())); } else if(name.contains(NBPR_KW)) { setBlocksPerRow(property->valueToString().toUInt32()); } else if(name.contains(NBPC_KW)) { setBlocksPerCol(property->valueToString().toUInt32()); } else if(name.contains(NPPBH_KW)) { setNumberOfPixelsPerBlockRow(property->valueToString().toUInt32()); } else if(name.contains(NPPBV_KW)) { setNumberOfPixelsPerBlockCol(property->valueToString().toUInt32()); } else if(name.contains(NBPP_KW)) { setBitsPerPixel(property->valueToString().toUInt32()); } else if(name.contains(IDLVL_KW)) { setDisplayLevel(property->valueToString()); } else if(name.contains(IALVL_KW)) { setAttachmentLevel(property->valueToString()); } else if(name.contains(ILOC_KW)) { } else if(name.contains(IMAG_KW)) { } else { ossimNitfImageHeader::setProperty(property); } } ossimRefPtr ossimNitfImageHeaderV2_X::getProperty(const ossimString& name)const { ossimProperty* property = 0; if(name == IID1_KW) { property = new ossimStringProperty(name, ossimString(theImageId).trim()); } else if(name == IDATIM_KW) { property = new ossimStringProperty(name, ossimString(theDateTime).trim()); } else if(name == TGTID_KW) { property = new ossimStringProperty(name, ossimString(theTargetId).trim()); } else if((name == IID2_KW)|| (name == ITITLE_KW)) { property = new ossimStringProperty(name, ossimString(theTitle).trim()); } else if(name == ISCLAS_KW) { property = new ossimStringProperty(name, ossimString(theSecurityClassification).trim()); } else if(name == ENCRYP_KW) { property = new ossimStringProperty(name, ossimString(theEncryption).trim()); } else if(name == ISORCE_KW) { property = new ossimStringProperty(name, ossimString(theImageSource).trim()); } else if(name == PVTYPE_KW) { property = new ossimStringProperty(name, ossimString(thePixelValueType).trim()); } else if(name == IREP_KW) { property = new ossimStringProperty(name, ossimString(theRepresentation).trim()); } else if(name == ICAT_KW) { property = new ossimStringProperty(name, ossimString(theCategory).trim()); } else if(name == ABPP_KW) { property = new ossimStringProperty(name, ossimString(theActualBitsPerPixelPerBand).trim()); } else if(name == PJUST_KW) { property = new ossimStringProperty(name, ossimString(theJustification).trim()); } else if(name == ICORDS_KW) { property = new ossimStringProperty(name, ossimString(theCoordinateSystem).trim()); } else if(name == IGEOLO_KW) { property = new ossimStringProperty(name, ossimString(theGeographicLocation).trim()); } else if(name == NICOM_KW) { property = new ossimStringProperty(name, ossimString(theNumberOfComments).trim()); } else if(name == IC_KW) { property = new ossimStringProperty(name, ossimString(theCompression).trim()); } else if(name == COMRAT_KW) { property = new ossimStringProperty(name, ossimString(theCompressionRateCode).trim()); } else if(name == ISYNC_KW) { property = new ossimStringProperty(name, ossimString(theImageSyncCode).trim()); } else if(name == IMODE_KW) { property = new ossimStringProperty(name, ossimString(theImageMode).trim()); } else if(name == NBPR_KW) { property = new ossimStringProperty(name, ossimString(theNumberOfBlocksPerRow).trim()); } else if(name == NBPC_KW) { property = new ossimStringProperty(name, ossimString(theNumberOfBlocksPerCol).trim()); } else if(name == NPPBH_KW) { property = new ossimStringProperty(name, ossimString(theNumberOfPixelsPerBlockHoriz).trim()); } else if(name == NPPBV_KW) { property = new ossimStringProperty(name, ossimString(theNumberOfPixelsPerBlockVert).trim()); } else if(name == NBPP_KW) { property = new ossimStringProperty(name, ossimString(theNumberOfBitsPerPixelPerBand).trim()); } else if(name == IDLVL_KW) { property = new ossimStringProperty(name, ossimString(theDisplayLevel).trim()); } else if(name == IALVL_KW) { property = new ossimStringProperty(name, ossimString(theAttachmentLevel).trim()); } else if(name == ILOC_KW) { property = new ossimStringProperty(name, ossimString(theImageLocation).trim()); } else if(name == IMAG_KW) { property = new ossimStringProperty(name, ossimString(theImageMagnification).trim()); } else if(name == "source") { property = new ossimStringProperty(name, getImageSource()); } else if(name == "image_date") { property = new ossimStringProperty(name, getAcquisitionDateMonthDayYear()); } else if(name == "image_title") { property = new ossimStringProperty(name, getTitle()); } else { return ossimNitfImageHeader::getProperty(name); } return property; } void ossimNitfImageHeaderV2_X::getPropertyNames(std::vector& propertyNames)const { ossimNitfImageHeader::getPropertyNames(propertyNames); propertyNames.push_back(IID1_KW); propertyNames.push_back(IDATIM_KW); propertyNames.push_back(TGTID_KW); propertyNames.push_back(IID2_KW); propertyNames.push_back(ISCLAS_KW); propertyNames.push_back(ENCRYP_KW); propertyNames.push_back(ISORCE_KW); propertyNames.push_back(PVTYPE_KW); propertyNames.push_back(IREP_KW); propertyNames.push_back(ICAT_KW); propertyNames.push_back(ABPP_KW); propertyNames.push_back(PJUST_KW); propertyNames.push_back(ICORDS_KW); propertyNames.push_back(IGEOLO_KW); propertyNames.push_back(NICOM_KW); propertyNames.push_back(IC_KW); propertyNames.push_back(COMRAT_KW); propertyNames.push_back(ISYNC_KW); propertyNames.push_back(IMODE_KW); propertyNames.push_back(NBPR_KW); propertyNames.push_back(NBPC_KW); propertyNames.push_back(NPPBH_KW); propertyNames.push_back(NPPBV_KW); propertyNames.push_back(NBPP_KW); propertyNames.push_back(IDLVL_KW); propertyNames.push_back(IALVL_KW); propertyNames.push_back(ILOC_KW); propertyNames.push_back(IMAG_KW); // Temp addition (drb) propertyNames.push_back(ossimString("source")); propertyNames.push_back(ossimString("image_date")); propertyNames.push_back(ossimString("image_title")); } ossimString ossimNitfImageHeaderV2_X::getImageMagnification()const { return ossimString(theImageMagnification).trim(); } void ossimNitfImageHeaderV2_X::getImageLocation(ossimIpt& loc)const { loc.x = ossimString((char*)(&theImageLocation[5])).toInt32(); loc.y = ossimString((char*)theImageLocation, (char*)(&theImageLocation[5])).toInt32(); } void ossimNitfImageHeaderV2_X::setGeographicLocationDms(const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << ossimDms(ul.y, true).toString("ddmmss.ssssC").c_str() << ossimDms(ul.x, false).toString("dddmmss.ssssC").c_str() << ossimDms(ur.y, true).toString("ddmmss.ssssC").c_str() << ossimDms(ur.x, false).toString("dddmmss.ssssC").c_str() << ossimDms(lr.y, true).toString("ddmmss.ssssC").c_str() << ossimDms(lr.x, false).toString("dddmmss.ssssC").c_str() << ossimDms(ll.y, true).toString("ddmmss.ssssC").c_str() << ossimDms(ll.x, false).toString("dddmmss.ssssC").c_str() << std::endl; checkForGeographicTiePointTruncation(ul); checkForGeographicTiePointTruncation(ur); checkForGeographicTiePointTruncation(lr); checkForGeographicTiePointTruncation(ll); } theCoordinateSystem[0] = 'G'; memcpy(theGeographicLocation, ossimNitfCommon::encodeGeographicDms(ul,ur,lr,ll).c_str(), 60); } void ossimNitfImageHeaderV2_X::setGeographicLocationDecimalDegrees( const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { theCoordinateSystem[0] = 'D'; memcpy(theGeographicLocation, ossimNitfCommon::encodeGeographicDecimalDegrees( ul, ur, lr, ll).c_str(), 60); } void ossimNitfImageHeaderV2_X::setUtmNorth(ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { theCoordinateSystem[0] = 'N'; memcpy(theGeographicLocation, ossimNitfCommon::encodeUtm(zone, ul, ur, lr, ll).c_str(), 60); } void ossimNitfImageHeaderV2_X::setUtmSouth(ossim_uint32 zone, const ossimDpt& ul, const ossimDpt& ur, const ossimDpt& lr, const ossimDpt& ll) { theCoordinateSystem[0] = 'S'; memcpy(theGeographicLocation, ossimNitfCommon::encodeUtm(zone, ul, ur, lr, ll).c_str(), 60); } bool ossimNitfImageHeaderV2_X::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = ossimNitfImageHeader::saveState(kwl, prefix); kwl.add(prefix, IM_KW.c_str(), theType); kwl.add(prefix, IID1_KW.c_str(), theImageId); kwl.add(prefix, IDATIM_KW.c_str(), theDateTime); kwl.add(prefix, TGTID_KW.c_str(), theTargetId); kwl.add(prefix, IID2_KW.c_str(), theTitle); kwl.add(prefix, ISCLAS_KW.c_str(), theSecurityClassification); kwl.add(prefix, ENCRYP_KW.c_str(), theEncryption); kwl.add(prefix, ISORCE_KW.c_str(), theImageSource); kwl.add(prefix, NROWS_KW.c_str(), theSignificantRows); kwl.add(prefix, NCOLS_KW.c_str(), theSignificantCols); kwl.add(prefix, PVTYPE_KW.c_str(), thePixelValueType); kwl.add(prefix, IREP_KW.c_str(), theRepresentation); kwl.add(prefix, ABPP_KW.c_str(), theActualBitsPerPixelPerBand); kwl.add(prefix, ICAT_KW.c_str(), theCategory); kwl.add(prefix, PJUST_KW.c_str(), theJustification); kwl.add(prefix, ICORDS_KW.c_str(), theCoordinateSystem); kwl.add(prefix, NICOM_KW.c_str(), theNumberOfComments); for (ossim_uint32 i=0; i < ossimString(theNumberOfComments).toUInt32(); ++i) { ossimString icpre = ossimString(ICOM_KW) + ossimString::toString(i); kwl.add(prefix, icpre.c_str(), theImageComments[i]); } kwl.add(prefix, IGEOLO_KW.c_str(), theGeographicLocation); kwl.add(prefix, IC_KW.c_str(), theCompression); kwl.add(prefix, COMRAT_KW.c_str(), theCompressionRateCode); kwl.add(prefix, NBANDS_KW.c_str(), theNumberOfBands); kwl.add(prefix, ISYNC_KW.c_str(), theImageSyncCode); kwl.add(prefix, IMODE_KW.c_str(), theImageMode); kwl.add(prefix, NBPR_KW.c_str(), theNumberOfBlocksPerRow); kwl.add(prefix, NBPC_KW.c_str(), theNumberOfBlocksPerCol); kwl.add(prefix, NPPBH_KW.c_str(), theNumberOfPixelsPerBlockHoriz); kwl.add(prefix, NPPBV_KW.c_str(), theNumberOfPixelsPerBlockVert); kwl.add(prefix, NBPP_KW.c_str(), theNumberOfBitsPerPixelPerBand); kwl.add(prefix, IDLVL_KW.c_str(), theDisplayLevel); kwl.add(prefix, IALVL_KW.c_str(), theAttachmentLevel); kwl.add(prefix, ILOC_KW.c_str(), theImageLocation); kwl.add(prefix, IMAG_KW.c_str(), theImageMagnification); kwl.add(prefix, UDIDL_KW.c_str(), theUserDefinedImageDataLength); kwl.add(prefix, UDOFL_KW.c_str(), theUserDefinedOverflow); kwl.add(prefix, IXSHDL_KW.c_str(), theExtendedSubheaderDataLen); kwl.add(prefix, IXSOFL_KW.c_str(), theExtendedSubheaderOverflow); kwl.add(prefix, IMDATOFF_KW.c_str(), theBlockedImageDataOffset); kwl.add(prefix, BMRLNTH_KW.c_str(), theBlockMaskRecordLength); return result; } ossim-Miami-2.9.1/src/support_data/ossimNitfImageLut.cpp000066400000000000000000000012431352751253100233160ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #include // memcpy #include #include std::ostream& operator <<(std::ostream& out, const ossimNitfImageLut &data) { data.print(out); return out; } RTTI_DEF1(ossimNitfImageLut, "ossimNitfImageLut", ossimObject); ossimNitfImageLut::ossimNitfImageLut() { } ossimNitfImageLut::~ossimNitfImageLut() { } ossim-Miami-2.9.1/src/support_data/ossimNitfImageLutV2_0.cpp000066400000000000000000000024601352751253100237470ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfImageLutV2_0.cpp 9094 2006-06-13 19:12:40Z dburken $ #include // memcpy #include #include #include ossimNitfImageLutV2_0::ossimNitfImageLutV2_0() { } ossimNitfImageLutV2_0::~ossimNitfImageLutV2_0() { } void ossimNitfImageLutV2_0::parseStream(std::istream &in) { if (!in) return; ossim_uint32 count = 0; while(count < theNumberOfEntries) { in.read((char*)&theData[count], 1); ++count; } } std::ostream& ossimNitfImageLutV2_0::print(std::ostream& out)const { out << "theNumberOfEntries: " << theNumberOfEntries; return out; } ossim_uint32 ossimNitfImageLutV2_0::getNumberOfEntries()const { return theNumberOfEntries; } void ossimNitfImageLutV2_0::setNumberOfEntries(ossim_uint32 numberOfEntries) { theData.resize(numberOfEntries); theNumberOfEntries = numberOfEntries; } ossim_uint8 ossimNitfImageLutV2_0::getValue(ossim_uint32 index)const { return theData[index]; } ossim-Miami-2.9.1/src/support_data/ossimNitfImageLutV2_1.cpp000066400000000000000000000010661352751253100237510ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2002 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Nitf support class. Copied from ossimNitfImageLutV2_0. // //******************************************************************** // $Id: ossimNitfImageLutV2_1.cpp 9094 2006-06-13 19:12:40Z dburken $ #include ossimNitfImageLutV2_1::ossimNitfImageLutV2_1() { } ossimNitfImageLutV2_1::~ossimNitfImageLutV2_1() { } ossim-Miami-2.9.1/src/support_data/ossimNitfInfo.cpp000066400000000000000000000032361352751253100225060ustar00rootroot00000000000000//--- // // License: MIT // // Description: NITF Info object. // //--- // $Id$ #include #include #include #include #include #include #include ossimNitfInfo::ossimNitfInfo() : m_nitfFile(0) { } ossimNitfInfo::~ossimNitfInfo() { m_nitfFile.reset(); } bool ossimNitfInfo::open(const ossimFilename& file) { bool result = false; std::string connectionString = file.c_str(); std::shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( file.c_str(), std::ios_base::in|std::ios_base::binary); if ( str ) { result = open(str, connectionString); } return result; } bool ossimNitfInfo::open(std::shared_ptr& str, const std::string& connectionString) { bool result = false; if ( str ) { m_nitfFile = std::make_shared(); result = m_nitfFile->parseStream(ossimFilename(connectionString), *str); } return result; } std::ostream& ossimNitfInfo::print(std::ostream& out) const { if ( m_nitfFile ) { std::string prefix; m_nitfFile->print(out, prefix, getProcessOverviewFlag()); } return out; } bool ossimNitfInfo::getKeywordlist(ossimKeywordlist& kwl, ossim_uint32 entryIndex)const { // Do a print to a memory stream. std::ostringstream out; m_nitfFile->print( out, entryIndex ); std::istringstream in( out.str() ); // Give the result to the keyword list. return kwl.parseStream( in ); } ossim-Miami-2.9.1/src/support_data/ossimNitfJ2klraTag.cpp000066400000000000000000000215071352751253100233750ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimNitfJ2klraTag.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: NITF J2KLRA tag. // // See: ISO/IEC BIIF Profile BPJ2K01.00 Table 9-3. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include /* for memcpy */ #include #include #include using namespace std; RTTI_DEF1(ossimNitfJ2klraTag, "ossimNitfJ2klraTag", ossimNitfRegisteredTag); ossimNitfJ2klraTag::ossimNitfJ2klraTag() : ossimNitfRegisteredTag(std::string("J2KLRA"), 0), m_layer(1) { clearFields(); } void ossimNitfJ2klraTag::parseStream(std::istream& in) { clearFields(); in.read(m_orig, ORIG_SIZE); in.read(m_levels_o, NLEVELS_O_SIZE); in.read(m_bands_o, NBANDS_O_SIZE); in.read(m_layers_o, NLAYERS_O_SIZE); ossim_uint32 layers = getNumberOfLayersOriginal(); if ( layers && (layers < 1000) ) // 999 max { m_layer.resize(layers); for ( ossim_uint32 i = 0; i < layers; ++i ) { in.read(m_layer[i].m_layer_id, LAYER_ID_SIZE); in.read(m_layer[i].m_bitrate, BITRATE_SIZE); m_layer[i].m_layer_id[LAYER_ID_SIZE] = '\0'; m_layer[i].m_bitrate[BITRATE_SIZE] = '\0'; } } else { m_layer.clear(); } // Conditional: if ( isParsed() ) { in.read(m_nlevels_i, NLEVELS_I_SIZE); in.read(m_nbands_i, NBANDS_I_SIZE); in.read(m_nlayers_i, NLAYERS_I_SIZE); } // Set the base tag length. setTagLength( getSizeInBytes() ); } void ossimNitfJ2klraTag::writeStream(std::ostream& out) { out.write(m_orig, ORIG_SIZE); out.write(m_levels_o, NLEVELS_O_SIZE); out.write(m_bands_o, NBANDS_O_SIZE); out.write(m_layers_o, NLAYERS_O_SIZE); ossim_uint32 size = m_layer.size(); for ( ossim_uint32 i = 0; i < size; ++i ) { out.write(m_layer[i].m_layer_id, LAYER_ID_SIZE); out.write(m_layer[i].m_bitrate, BITRATE_SIZE); } // Conditional: if ( isParsed() ) { out.write(m_nlevels_i, NLEVELS_I_SIZE); out.write(m_nbands_i, NBANDS_I_SIZE); out.write(m_nlayers_i, NLAYERS_I_SIZE); } } ossim_uint32 ossimNitfJ2klraTag::getSizeInBytes()const { ossim_uint32 result = 11 + (m_layer.size() * 12); // Conditional: ossim_uint32 orig = getOriginNumber(); if ( orig ) { if ( orig % 2 ) // Odd origins are "parsed". { result += 10; } } return result; } void ossimNitfJ2klraTag::clearFields() { memset(m_orig, 0, ORIG_SIZE); memset(m_levels_o, 0, NLEVELS_O_SIZE); memset(m_bands_o, 0, NBANDS_O_SIZE); memset(m_layers_o, 0, NLAYERS_O_SIZE); m_layer.clear(); memset(m_nlevels_i, 0, NLEVELS_I_SIZE); memset(m_nbands_i, 0, NBANDS_I_SIZE); memset(m_nlayers_i, 0, NLAYERS_I_SIZE); m_orig[ORIG_SIZE]= '\0'; m_levels_o[NLEVELS_O_SIZE]= '\0'; m_bands_o[NBANDS_O_SIZE]= '\0'; m_layers_o[NLAYERS_O_SIZE]= '\0'; m_nlevels_i[NLEVELS_I_SIZE]= '\0'; m_nbands_i[NBANDS_I_SIZE] = '\0'; m_nlayers_i[NLAYERS_I_SIZE] = '\0'; // Set the base tag length. setTagLength( 0 ); } std::ostream& ossimNitfJ2klraTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "ORIG:" << m_orig << "\n" << pfx << std::setw(24) << "NLEVELS_O:" << m_levels_o << "\n" << pfx << std::setw(24) << "NBANDS_O:" << m_bands_o << "\n" << pfx << std::setw(24) << "NLAYERS_O:" << m_layers_o << "\n"; ossim_uint32 size = m_layer.size(); for ( ossim_uint32 i = 0; i < size; ++i ) { out << pfx << "LAYER_ID[" << i << std::setw(14) << "]:" << m_layer[i].m_layer_id << "\n" << pfx << "BITRATE[" << i << std::setw(15) << "]:" << m_layer[i].m_bitrate << "\n"; } // Conditional: if ( isParsed() ) { out << pfx << std::setw(24) << "NLEVELS_I:" << m_nlevels_i << "\n" << pfx << std::setw(24) << "NBANDS_I_SIZE:" << m_nbands_i << "\n" << pfx << std::setw(24) << "NLAYERS_I:" << m_nlayers_i << "\n"; } return out; } ossim_uint32 ossimNitfJ2klraTag::getOriginNumber() const { return ossimString(m_orig).toUInt32(); } ossim_uint32 ossimNitfJ2klraTag::getNumberOfLayersOriginal() const { return ossimString(m_layers_o).toUInt32(); } bool ossimNitfJ2klraTag::setOrigin( ossim_uint32 origin ) { bool result = true; if ( origin <= 9 ) { // Ascii 0 to 9 m_orig[0] = 0x30 + origin; } else { result = false; } return result; } bool ossimNitfJ2klraTag::setLevelsO( ossim_uint32 levels ) { bool result = false; if ( levels <= 32 ) { ossimString os = ossimNitfCommon::convertToUIntString( levels, NLEVELS_O_SIZE ); if ( os.size() == NLEVELS_O_SIZE ) { strncpy( m_levels_o, os.string().c_str(), NLEVELS_O_SIZE ); result = true; } } return result; } bool ossimNitfJ2klraTag::setBandsO( ossim_uint32 bands ) { bool result = false; if ( ( bands >= 1 ) && ( bands <= 16384 ) ) { ossimString os = ossimNitfCommon::convertToUIntString( bands, NBANDS_O_SIZE ); if ( os.size() == NBANDS_O_SIZE ) { strncpy( m_bands_o, os.string().c_str(), NBANDS_O_SIZE ); result = true; } } return result; } bool ossimNitfJ2klraTag::setLayersO( ossim_uint32 layers ) { bool result = false; if ( ( layers >= 1 ) && ( layers <= 999 ) ) { ossimString os = ossimNitfCommon::convertToUIntString( layers, NLAYERS_O_SIZE ); if ( os.size() == NLAYERS_O_SIZE ) { strncpy( m_layers_o, os.string().c_str(), NLAYERS_O_SIZE ); // Conditional repeating field: m_layer.resize( layers ); result = true; } } return result; } bool ossimNitfJ2klraTag::setLevelsI( ossim_uint32 levels ) { bool result = false; if ( levels <= 32 ) { ossimString os = ossimNitfCommon::convertToUIntString( levels, NLEVELS_I_SIZE ); if ( os.size() == NLEVELS_I_SIZE ) { strncpy( m_nlevels_i, os.string().c_str(), NLEVELS_I_SIZE ); result = true; } } return result; } bool ossimNitfJ2klraTag::setBandsI( ossim_uint32 bands ) { bool result = false; if ( ( bands >= 1 ) && ( bands <= 16384 ) ) { ossimString os = ossimNitfCommon::convertToUIntString( bands, NBANDS_I_SIZE ); if ( os.size() == NBANDS_I_SIZE ) { strncpy( m_nbands_i, os.string().c_str(), NBANDS_I_SIZE ); result = true; } } return result; } bool ossimNitfJ2klraTag::setLayersI( ossim_uint32 layers ) { bool result = false; if ( ( layers >= 1 ) && ( layers <= 999 ) ) { ossimString os = ossimNitfCommon::convertToUIntString( layers, NLAYERS_I_SIZE ); if ( os.size() == NLAYERS_I_SIZE ) { strncpy( m_nlayers_i, os.string().c_str(), NLAYERS_I_SIZE ); result = true; } } return result; } bool ossimNitfJ2klraTag::setLayerId( ossim_uint32 index, ossim_uint32 id ) { bool result = false; if ( index < m_layer.size() && ( id <= 998 ) ) { ossimString os = ossimNitfCommon::convertToUIntString( id, LAYER_ID_SIZE ); if ( os.size() == LAYER_ID_SIZE) { strncpy( m_layer[index].m_layer_id, os.string().c_str(), LAYER_ID_SIZE ); result = true; } } return result; } bool ossimNitfJ2klraTag::setLayerBitRate( ossim_uint32 index, ossim_float64 bitRate ) { bool result = false; if ( index < m_layer.size() && ( bitRate >= 0.0 ) && ( bitRate <= 37.0 ) ) { // 00.000000 – 37.000000 ossimString os = ossimNitfCommon::convertToDoubleString( bitRate, 6, BITRATE_SIZE ); if ( os.size() == BITRATE_SIZE) { strncpy( m_layer[index].m_bitrate, os.string().c_str(), BITRATE_SIZE); result = true; } } return result; } bool ossimNitfJ2klraTag::isParsed() const { bool result = false; ossim_uint32 orig = getOriginNumber(); if ( orig ) { /* * 0 - Original NPJE * 1 – Parsed NPJE * 2 – Original EPJE * 3 – Parsed EPJE* * 4 - Original TPJE * 5 - Parsed TPJE * 6 - Original LPJE * 7 - Parsed LPJE * 8 – Original other * 9 – Parsed other */ if ( orig % 2 ) // Odd origins are "parsed". { result = true; } } return result; } ossim-Miami-2.9.1/src/support_data/ossimNitfLabelHeader.cpp000066400000000000000000000007531352751253100237440ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfLabelHeader.cpp 9094 2006-06-13 19:12:40Z dburken $ #include RTTI_DEF1(ossimNitfLabelHeader, "ossimNitfLabelHeader", ossimObject) ossim-Miami-2.9.1/src/support_data/ossimNitfLabelHeaderV2_0.cpp000066400000000000000000000141261352751253100243720ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfLabelHeaderV2_0.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include // for memset #include RTTI_DEF1(ossimNitfLabelHeaderV2_0, "ossimNitfLabelHeaderV2_0", ossimNitfLabelHeader) ossimNitfLabelHeaderV2_0::ossimNitfLabelHeaderV2_0() { clearFields(); } void ossimNitfLabelHeaderV2_0::parseStream(std::istream &in) { if(in) { clearFields(); in.read(theFilePartType, 2); in.read(theLabelId, 10); in.read(theLabelSecurityClassification, 1); in.read(theLabelCodewords, 40); in.read(theLabelControlAndHandling, 40); in.read(theLabelReleasingInstructions, 40); in.read(theLabelClassificationAuthority, 20); in.read(theLabelSecurityControlNumber, 20); in.read(theLabelSecurityDowngrade, 6); if(ossimString(theLabelSecurityDowngrade) == "999998") { in.read(theLabelDowngradingEvent, 40); } in.read(theLabelEncryption, 1); in.read(theLabelFontStyle, 1); in.read(theLabelCellWidth, 2); in.read(theLabelCellHeight, 2); in.read(theLabelDisplayLevel, 3); in.read(theLabelAttachmentLevel, 3); in.read(theLabelLocation, 10); in.read(theLabelTextColor, 3); in.read(theLabelBackgroundColor, 3); in.read(theExtendedHeaderDataLength, 5); long dataLength = ossimString(theExtendedHeaderDataLength).toLong(); if(dataLength > 0) { in.read(theExtendedSubheaderOverflow, 3); // for now just ignore the extended header data in.ignore(dataLength-3); } } } std::ostream& ossimNitfLabelHeaderV2_0::print(std::ostream &out)const { out << "theFilePartType: " << theFilePartType << std::endl << "theLabelId: " << theLabelId << std::endl << "theLabelSecurityClassification: " << theLabelSecurityClassification << std::endl << "theLabelCodewords: " << theLabelCodewords << std::endl << "theLabelControlAndHandling: " << theLabelControlAndHandling << std::endl << "theLabelReleasingInstructions: " << theLabelReleasingInstructions << std::endl << "theLabelClassificationAuthority: " << theLabelClassificationAuthority << std::endl << "theLabelSecurityControlNumber: " << theLabelSecurityControlNumber << std::endl << "theLabelSecurityDowngrade: " << theLabelSecurityDowngrade << std::endl << "theLabelEncryption: " << theLabelEncryption << std::endl << "theLabelFontStyle: " << theLabelFontStyle << std::endl << "theLabelCellWidth: " << theLabelCellWidth << std::endl << "theLabelCellHeight: " << theLabelCellHeight << std::endl << "theLabelDisplayLevel: " << theLabelDisplayLevel << std::endl << "theLabelAttachmentLevel: " << theLabelAttachmentLevel << std::endl << "theLabelLocation: " << theLabelLocation << std::endl << "theLabelTextColor: " << theLabelTextColor << std::endl << "theLabelBackgroundColor: " << theLabelBackgroundColor << std::endl << "theExtendedHeaderDataLength: " << theExtendedHeaderDataLength << std::endl << "theExtendedSubheaderOverflow: " << theExtendedSubheaderOverflow; return out; } ossim_int32 ossimNitfLabelHeaderV2_0::getDisplayLevel()const { return ossimString(theLabelDisplayLevel).toInt32(); } ossimDrect ossimNitfLabelHeaderV2_0::getImageRect()const { double ulx = ossimString((const char*)(&theLabelLocation[5]), (const char*)(&theLabelLocation[10])).toDouble(); double uly = ossimString((const char*)theLabelLocation, (const char*)(&theLabelLocation[5])).toDouble(); return ossimDrect(ulx, uly, ulx + ossimString(theLabelCellWidth).toDouble(), uly + ossimString(theLabelCellHeight).toDouble()); } void ossimNitfLabelHeaderV2_0::clearFields() { memset(theFilePartType, ' ', 2); memset(theLabelId, ' ', 10); memset(theLabelSecurityClassification, ' ', 1); memset(theLabelCodewords, ' ', 40); memset(theLabelControlAndHandling, ' ', 40); memset(theLabelReleasingInstructions, ' ', 40); memset(theLabelClassificationAuthority, ' ', 20); memset(theLabelSecurityControlNumber, ' ', 20); memset(theLabelSecurityDowngrade, ' ', 6); memset(theLabelDowngradingEvent, ' ', 40); memset(theLabelEncryption, ' ', 1); memset(theLabelFontStyle, ' ', 1); memset(theLabelCellWidth, ' ', 2); memset(theLabelCellHeight, ' ', 2); memset(theLabelDisplayLevel, ' ', 3); memset(theLabelAttachmentLevel, ' ', 3); memset(theLabelLocation, ' ', 10); memset(theLabelTextColor, ' ', 3); memset(theLabelBackgroundColor, ' ', 3); memset(theExtendedHeaderDataLength, ' ', 5); memset(theExtendedSubheaderOverflow, ' ', 3); theFilePartType[2] = '\0'; theLabelId[10] = '\0'; theLabelSecurityClassification[1] = '\0'; theLabelCodewords[40] = '\0'; theLabelControlAndHandling[40] = '\0'; theLabelReleasingInstructions[40] = '\0'; theLabelClassificationAuthority[20] = '\0'; theLabelSecurityControlNumber[20] = '\0'; theLabelSecurityDowngrade[6] = '\0'; theLabelDowngradingEvent[40] = '\0'; theLabelEncryption[1] = '\0'; theLabelFontStyle[1] = '\0'; theLabelCellWidth[2] = '\0'; theLabelCellHeight[2] = '\0'; theLabelDisplayLevel[3] = '\0'; theLabelAttachmentLevel[3] = '\0'; theLabelLocation[10] = '\0'; theLabelTextColor[3] = '\0'; theLabelBackgroundColor[3] = '\0'; theExtendedHeaderDataLength[5] = '\0'; theExtendedSubheaderOverflow[3] = '\0'; } ossim-Miami-2.9.1/src/support_data/ossimNitfLocalCartographicTag.cpp000066400000000000000000000065211352751253100256300ustar00rootroot00000000000000//******************************************************************* // // LICENSE: LGPL // // see top level LICENSE.txt // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfLocalCartographicTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include #include #include #include RTTI_DEF1(ossimNitfLocalCartographicTag, "ossimNitfLocalCartographicTag", ossimNitfRegisteredTag); ossimNitfLocalCartographicTag::ossimNitfLocalCartographicTag() : ossimNitfRegisteredTag(std::string("MAPLOB"), 43) { } ossimNitfLocalCartographicTag::~ossimNitfLocalCartographicTag() { } void ossimNitfLocalCartographicTag::parseStream(std::istream& in) { clearFields(); in.read(theLengthUnits, 3); in.read(theEastingInterval, 5); in.read(theNorthingInterval, 5); in.read(theEastingReferenceOrigin, 15); in.read(theNorthingReferenceOrigin, 15); } void ossimNitfLocalCartographicTag::writeStream(std::ostream& out) { out.write(theLengthUnits, 3); out.write(theEastingInterval, 5); out.write(theNorthingInterval, 5); out.write(theEastingReferenceOrigin, 15); out.write(theNorthingReferenceOrigin, 15); } void ossimNitfLocalCartographicTag::clearFields() { memset(theLengthUnits, ' ', 3); memset(theEastingInterval, '0', 5); memset(theNorthingInterval, '0', 5); memset(theEastingReferenceOrigin, '0', 15); memset(theNorthingReferenceOrigin, '0', 15); theLengthUnits[3] = '\0'; theEastingInterval[5] = '\0'; theNorthingInterval[5] = '\0'; theEastingReferenceOrigin[15] = '\0'; theNorthingReferenceOrigin[15] = '\0'; } void ossimNitfLocalCartographicTag::setLengthUnits(const ossimString& units) { ossimString temp = ossimString(units).trim().upcase(); std::ostringstream out; out << std::setw(3) << std::setfill(' ') << temp.c_str(); memcpy(theLengthUnits, out.str().c_str(), 3); } void ossimNitfLocalCartographicTag::setEastingInterval(ossim_uint32 eastingInterval) { ossim_uint32 temp = eastingInterval; if(temp > 99999) { temp = 99999; } std::ostringstream out; out << std::setw(5) << std::setfill('0') << temp; memcpy(theEastingInterval, out.str().c_str(), 5); } void ossimNitfLocalCartographicTag::setNorthingInterval(ossim_uint32 northingInterval) { ossim_uint32 temp = northingInterval; if(temp > 99999) { temp = 99999; } std::ostringstream out; out << std::setw(5) << std::setfill('0') << temp; memcpy(theNorthingInterval, out.str().c_str(), 5); } void ossimNitfLocalCartographicTag::setEastingReferenceOrigin(ossim_float64 east) { std::ostringstream out; out << std::setw(15) << std::setfill(' ') << std::setprecision(1) << std::setiosflags(std::ios::fixed) << east; memcpy(theEastingReferenceOrigin, out.str().c_str(), 15); } void ossimNitfLocalCartographicTag::setNorthingReferenceOrigin(ossim_float64 north) { std::ostringstream out; out << std::setw(15) << std::setfill(' ') << std::setprecision(1) << std::setiosflags(std::ios::fixed) << north; memcpy(theNorthingReferenceOrigin, out.str().c_str(), 15); } ossim-Miami-2.9.1/src/support_data/ossimNitfMstgtaTag.cpp000066400000000000000000000104571352751253100235110ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: MSTGTA Mission Target Information Extension Format // tag class definition. // // See document STDI-0002 Table 8-16 for more info. // //---------------------------------------------------------------------------- // $Id #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfMstgtaTag, "ossimNitfMstgtaTag", ossimNitfRegisteredTag); ossimNitfMstgtaTag::ossimNitfMstgtaTag() : ossimNitfRegisteredTag(std::string("MSTGTA"), 101) { clearFields(); } ossimNitfMstgtaTag::~ossimNitfMstgtaTag() { } void ossimNitfMstgtaTag::parseStream(std::istream& in) { clearFields(); in.read(theTgtNum, TGT_NUM_SIZE); in.read(theTgtId, TGT_ID_SIZE); in.read(theTgtBe, TGT_BE_SIZE); in.read(theTgtPri, TGT_PRI_SIZE); in.read(theTgtReq, TGT_REQ_SIZE); in.read(theTgtLtiov, TGT_LTIOV_SIZE); in.read(theTgtType, TGT_TYPE_SIZE); in.read(theTgtColl, TGT_COLL_SIZE); in.read(theTgtCat, TGT_CAT_SIZE); in.read(theTgtUtc, TGT_UTC_SIZE); in.read(theTgtElev, TGT_ELEV_SIZE); in.read(theTgtElevUnit, TGT_ELEV_UNIT_SIZE); in.read(theTgtLoc, TGT_LOC_SIZE); } void ossimNitfMstgtaTag::writeStream(std::ostream& out) { out.write(theTgtNum, TGT_NUM_SIZE); out.write(theTgtId, TGT_ID_SIZE); out.write(theTgtBe, TGT_BE_SIZE); out.write(theTgtPri, TGT_PRI_SIZE); out.write(theTgtReq, TGT_REQ_SIZE); out.write(theTgtLtiov, TGT_LTIOV_SIZE); out.write(theTgtType, TGT_TYPE_SIZE); out.write(theTgtColl, TGT_COLL_SIZE); out.write(theTgtCat, TGT_CAT_SIZE); out.write(theTgtUtc, TGT_UTC_SIZE); out.write(theTgtElev, TGT_ELEV_SIZE); out.write(theTgtElevUnit, TGT_ELEV_UNIT_SIZE); out.write(theTgtLoc, TGT_LOC_SIZE); } void ossimNitfMstgtaTag::clearFields() { // BCS-N's to '0's, BCS-A's to ' '(spaces) // clear memset(theTgtNum, '0', TGT_NUM_SIZE); memset(theTgtId, ' ', TGT_ID_SIZE); memset(theTgtBe, ' ', TGT_BE_SIZE); memset(theTgtPri, ' ', TGT_PRI_SIZE); memset(theTgtReq, ' ', TGT_REQ_SIZE); memset(theTgtLtiov, ' ', TGT_LTIOV_SIZE); memset(theTgtType, ' ', TGT_TYPE_SIZE); memset(theTgtColl, '0', TGT_COLL_SIZE); memset(theTgtCat, ' ', TGT_CAT_SIZE); memset(theTgtUtc, ' ', TGT_UTC_SIZE); memset(theTgtElev, ' ', TGT_ELEV_SIZE); memset(theTgtElevUnit, ' ', TGT_ELEV_UNIT_SIZE); memset(theTgtLoc, ' ', TGT_LOC_SIZE); // null terminate theTgtNum[TGT_NUM_SIZE] = '\0'; theTgtId[TGT_ID_SIZE] = '\0'; theTgtBe[TGT_BE_SIZE] = '\0'; theTgtPri[TGT_PRI_SIZE] = '\0'; theTgtReq[TGT_REQ_SIZE] = '\0'; theTgtLtiov[TGT_LTIOV_SIZE] = '\0'; theTgtType[TGT_TYPE_SIZE] = '\0'; theTgtColl[TGT_COLL_SIZE] = '\0'; theTgtCat[TGT_CAT_SIZE] = '\0'; theTgtUtc[TGT_UTC_SIZE] = '\0'; theTgtElev[TGT_ELEV_SIZE] = '\0'; theTgtElevUnit[TGT_ELEV_UNIT_SIZE] = '\0'; theTgtLoc[TGT_LOC_SIZE] = '\0'; } std::ostream& ossimNitfMstgtaTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "TGT_NUM:" << theTgtNum << "\n" << pfx << std::setw(24) << "TGT_ID:" << theTgtId << "\n" << pfx << std::setw(24) << "TGT_BE:" << theTgtBe << "\n" << pfx << std::setw(24) << "TGT_PRI:" << theTgtPri << "\n" << pfx << std::setw(24) << "TGT_REQ:" << theTgtReq << "\n" << pfx << std::setw(24) << "TGT_LTIOV:" << theTgtLtiov << "\n" << pfx << std::setw(24) << "TGT_TYPE:" << theTgtType << "\n" << pfx << std::setw(24) << "TGT_COLL:" << theTgtColl << "\n" << pfx << std::setw(24) << "TGT_CAT:" << theTgtCat << "\n" << pfx << std::setw(24) << "TGT_UTC:" << theTgtUtc << "\n" << pfx << std::setw(24) << "TGT_ELEV:" << theTgtElev << "\n" << pfx << std::setw(24) << "TGT_ELEV_UNIT:" << theTgtElevUnit << "\n" << pfx << std::setw(24) << "TGT_LOC:" << theTgtLoc << "\n"; return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfNameConversionTables.cpp000066400000000000000000000112761352751253100256770ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2004 Garrett Potts. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimNitfNameConversionTables.cpp 13219 2008-07-23 19:27:49Z dburken $ #include #include #include struct ossimNitfMapProjectionCodeToOssimName { const char* nitfProjCode; // nitf code name const char* projectionName; // ossim projection name }; struct ossimNitfMapProjectionCodeToNitfName { const char* nitfProjCode; // nitf code name const char* projectionName; // ossim projection name }; static const ossimNitfMapProjectionCodeToOssimName mapProjectiontable[]= { {"AC", "ossimAlbersProjection"}, {"AL", "ossimAzimEquDistProjection"}, {"BF", "ossimBonneProjection"}, {"CP", "ossimEquDistCylProjection"}, {"CP", "ossimLlxyProjection"}, {"CS", "ossimCassiniProjection"}, {"ED", "ossimEckert6Projection"}, {"EF", "ossimEckert4Projection"}, {"GN", "ossimGnomonicProjection"}, {"LE", "ossimLambertConformalConicProjection"}, {"LI", "ossimCylEquAreaProjection"}, {"MC", "ossimMercatorProjection"}, {"MH", "ossimMillerProjection"}, {"MP", "ossimMollweidProjection"}, {"NT", "ossimNewZealandMapGridProjection"}, {"OD", "ossimOrthoGraphicProjection"}, {"PG", "ossimPolarStereoProjection"}, {"PH", "ossimPolyconicProjection"}, {"SA", "ossimSinusoidalProjection"}, {"SX", "ossimSpaceObliqueMercatorProjection"}, {"TC", "ossimTransMercatorProjection"}, {"TX", "ossimTransCylEquAreaProjection"}, {"VA", "ossimVanDerGrintenProjection"}, { 0, 0 } }; static const ossimNitfMapProjectionCodeToNitfName nitfMapProjectiontable[]= { {"AC", "Albers Equal-Area Conic"}, {"AK", "(Lambert) Azimuthal Equal-Area"}, {"AL", "Azimuthal Equidistant"}, {"BF", "Bonne"}, {"CC", "Equidistant Conic with 1 Standard Parallel"}, {"CP", "Equirectangular"}, {"CS", "Cassini-Soldner"}, {"ED", "Eckert VI"}, {"EF", "Eckert IV"}, {"GN", "Gnomonic"}, {"HX", "Hotine Oblique Mercator based on 2 Points"}, {"KA", " Equidistant Conic with 2 Standard Parallels"}, {"LA", "Laborde"}, {"LE", "Lambert Conformal Conic"}, {"LI", "Cylindrical Equal Area"}, {"LJ", " Lambert Equal-Area Meridional"}, {"MC", "Mercator"}, {"MH", "Miller Cylindrical"}, {"MJ", "French Lambert"}, {"MP", "Mollweide"}, {"NT", "New Zealand Map Grid"}, {"OC", "Oblique Mercator"}, {"OD", "Orthographic"}, {"PG", "Polar Stereographic"}, {"PH", "Polyconic"}, {"RS", "Hotine Oblique Mercator (Rectified Skew Orthomorphic)"}, {"RB", "Hotine Oblique Mercator (Rectified Skew Orthomorphic)"}, {"RX", "Robinson"}, {"SA", "Sinusoidal"}, {"SD", "Oblique Stereographic"}, {"SX", "Space Oblique Mercator"}, {"TC", " Transverse Mercator"}, {"TX", "Transverse Cylindrical Equal Area"}, {"VA", "Van der Grinten"}, {"VX", "General Vertical NearSide Perspective"}, { 0, 0 } }; ossimNitfNameConversionTables::ossimNitfNameConversionTables() { } ossimString ossimNitfNameConversionTables::convertMapProjectionNameToNitfCode(const ossimString& mapProjectionName)const { ossim_uint32 idx = 0; while(mapProjectiontable[idx].nitfProjCode) { if(mapProjectionName == mapProjectiontable[idx].projectionName) { return mapProjectiontable[idx].nitfProjCode; } ++idx; } return ""; } ossimString ossimNitfNameConversionTables::convertNitfCodeToOssimProjectionName(const ossimString& nitfProjectionCode)const { ossim_uint32 idx = 0; while(mapProjectiontable[idx].nitfProjCode) { if(nitfProjectionCode == mapProjectiontable[idx].nitfProjCode) { return mapProjectiontable[idx].projectionName; } ++idx; } return ""; } ossimString ossimNitfNameConversionTables::convertNitfCodeToNitfProjectionName(const ossimString& nitfProjectionCode)const { ossim_uint32 idx = 0; while(nitfMapProjectiontable[idx].nitfProjCode) { if(nitfProjectionCode == nitfMapProjectiontable[idx].nitfProjCode) { return nitfMapProjectiontable[idx].projectionName; } ++idx; } return ""; } ossimString ossimNitfNameConversionTables::convertNitfProjectionNameToNitfCode(const ossimString& nitfProjectionName)const { ossim_uint32 idx = 0; while(nitfMapProjectiontable[idx].nitfProjCode) { if(nitfProjectionName == nitfMapProjectiontable[idx].projectionName) { return nitfMapProjectiontable[idx].nitfProjCode; } ++idx; } return ""; } ossim-Miami-2.9.1/src/support_data/ossimNitfPiaimcTag.cpp000066400000000000000000000303421352751253100234470ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: PIAIMC tag class declaration. // // "Profile for Imagery Access Image Support Extensions" // // See document STDI-0002 Table 6-1 for more info. // // http://164.214.2.51/ntb/baseline/docs/stdi0002/final.pdf // //---------------------------------------------------------------------------- // $Id: ossimNitfPiaimcTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include /* for memcpy */ #include #include #include #include #include #include using namespace std; static const ossimString CLOUDCVR_KW = "CLOUDCVR"; static const ossimString SRP_KW = "SRP"; static const ossimString SENSMODE_KW = "SENSMODE"; static const ossimString SENSNAME_KW = "SENSNAME"; static const ossimString SOURCE_KW = "SOURCE"; static const ossimString COMGEN_KW = "COMGEN"; static const ossimString SUBQUAL_KW = "SUBQUAL"; static const ossimString PIAMSNNUM_KW = "PIAMSNNUM"; static const ossimString CAMSPECS_KW = "CAMSPECS"; static const ossimString PROJID_KW = "PROJID"; static const ossimString GENERATION_KW = "GENERATION"; static const ossimString ESD_KW = "ESD"; static const ossimString OTHERCOND_KW = "OTHERCOND"; static const ossimString MEANGSD_KW = "MEANGSD"; static const ossimString IDATUM_KW = "IDATUM"; static const ossimString IELLIP_KW = "IELLIP"; static const ossimString PREPROC_KW = "PREPROC"; static const ossimString IPROJ_KW = "IPROJ"; static const ossimString SATTRACK_KW = "SATTRACK"; RTTI_DEF1(ossimNitfPiaimcTag, "ossimNitfPiaimcTag", ossimNitfRegisteredTag); ossimNitfPiaimcTag::ossimNitfPiaimcTag() : ossimNitfRegisteredTag(std::string("PIAIMC"), 362) { clearFields(); } void ossimNitfPiaimcTag::parseStream(std::istream& in) { clearFields(); in.read(theCloudcvr, CLOUDCVR_SIZE); in.read(theSrp, SRP_SIZE); in.read(thesSensmode, SENSMODE_SIZE); in.read(theSensname, SENSNAME_SIZE); in.read(theSource, SOURCE_SIZE); in.read(theComgen, COMGEN_SIZE); in.read(theSubqual, SUBQUAL_SIZE); in.read(thePiamsnnum, PIAMSNNUM_SIZE); in.read(theCamspecs, CAMSPECS_SIZE); in.read(theProjid, PROJID_SIZE); in.read(theGeneration, GENERATION_SIZE); in.read(theEsd, ESD_SIZE); in.read(theOthercond, OTHERCOND_SIZE); in.read(theMeanGsd, MEANGSD_SIZE); in.read(theIdatum, IDATUM_SIZE); in.read(theIellip, IELLIP_SIZE); in.read(thePreproc, PREPROC_SIZE); in.read(theIproj, IPROJ_SIZE); in.read(theSattrack, SATTRACK_SIZE); } void ossimNitfPiaimcTag::writeStream(std::ostream& out) { out.write(theCloudcvr, CLOUDCVR_SIZE); out.write(theSrp, SRP_SIZE); out.write(thesSensmode, SENSMODE_SIZE); out.write(theSensname, SENSNAME_SIZE); out.write(theSource, SOURCE_SIZE); out.write(theComgen, COMGEN_SIZE); out.write(theSubqual, SUBQUAL_SIZE); out.write(thePiamsnnum, PIAMSNNUM_SIZE); out.write(theCamspecs, CAMSPECS_SIZE); out.write(theProjid, PROJID_SIZE); out.write(theGeneration, GENERATION_SIZE); out.write(theEsd, ESD_SIZE); out.write(theOthercond, OTHERCOND_SIZE); out.write(theMeanGsd, MEANGSD_SIZE); out.write(theIdatum, IDATUM_SIZE); out.write(theIellip, IELLIP_SIZE); out.write(thePreproc, PREPROC_SIZE); out.write(theIproj, IPROJ_SIZE); out.write(theSattrack, SATTRACK_SIZE); } void ossimNitfPiaimcTag::clearFields() { memcpy(theCloudcvr, "999", CLOUDCVR_SIZE); memset(theSrp, ' ', SRP_SIZE); memset(thesSensmode, ' ', SENSMODE_SIZE); memset(theSensname, ' ', SENSNAME_SIZE); memset(theSource, ' ', SOURCE_SIZE); memset(theComgen, ' ', COMGEN_SIZE); memset(theSubqual, ' ', SUBQUAL_SIZE); memset(thePiamsnnum, ' ', PIAMSNNUM_SIZE); memset(theCamspecs, ' ', CAMSPECS_SIZE); memset(theProjid, ' ', PROJID_SIZE); memset(theGeneration, ' ', GENERATION_SIZE); memset(theEsd, ' ', ESD_SIZE); memset(theOthercond, ' ', OTHERCOND_SIZE); memset(theMeanGsd, ' ', MEANGSD_SIZE); memset(theIdatum, ' ', IDATUM_SIZE); memset(theIellip, ' ', IELLIP_SIZE); memset(thePreproc, ' ', PREPROC_SIZE); memset(theIproj, ' ', IPROJ_SIZE); memset(theSattrack, ' ', SATTRACK_SIZE); theCloudcvr[CLOUDCVR_SIZE] = '\0'; theSrp[SRP_SIZE] = '\0'; thesSensmode[SENSMODE_SIZE] = '\0'; theSensname[SENSNAME_SIZE] = '\0'; theSource[SOURCE_SIZE] = '\0'; theComgen[COMGEN_SIZE] = '\0'; theSubqual[SUBQUAL_SIZE] = '\0'; thePiamsnnum[PIAMSNNUM_SIZE] = '\0'; theCamspecs[CAMSPECS_SIZE] = '\0'; theProjid[PROJID_SIZE] = '\0'; theGeneration[GENERATION_SIZE] = '\0'; theEsd[ESD_SIZE] = '\0'; theOthercond[OTHERCOND_SIZE] = '\0'; theMeanGsd[MEANGSD_SIZE] = '\0'; theIdatum[IDATUM_SIZE] = '\0'; theIellip[IELLIP_SIZE] = '\0'; thePreproc[PREPROC_SIZE] = '\0'; theIproj[IPROJ_SIZE] = '\0'; theSattrack[SATTRACK_SIZE] = '\0'; } std::ostream& ossimNitfPiaimcTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "CLOUDCVR:" << theCloudcvr << "\n" << pfx << std::setw(24) << "SRP:" << theSrp << "\n" << pfx << std::setw(24) << "SENSMODE:" << thesSensmode << "\n" << pfx << std::setw(24) << "SENSNAME:" << theSensname << "\n" << pfx << std::setw(24) << "SOURCE:" << theSource << "\n" << pfx << std::setw(24) << "COMGEN:" << theComgen << "\n" << pfx << std::setw(24) << "SUBQUAL:" << theSubqual << "\n" << pfx << std::setw(24) << "PIAMSNNUM:" << thePiamsnnum << "\n" << pfx << std::setw(24) << "CAMSPECS:" << theCamspecs << "\n" << pfx << std::setw(24) << "PROJID:" << theProjid << "\n" << pfx << std::setw(24) << "GENERATION:" << theGeneration << "\n" << pfx << std::setw(24) << "ESD:" << theEsd << "\n" << pfx << std::setw(24) << "OTHERCOND:" << theOthercond << "\n" << pfx << std::setw(24) << "MEANGSD:" << theMeanGsd << "\n" << pfx << std::setw(24) << "IDATUM:" << theIdatum << "\n" << pfx << std::setw(24) << "IELLIP:" << theIellip << "\n" << pfx << std::setw(24) << "PREPROC:" << thePreproc << "\n" << pfx << std::setw(24) << "IPROJ:" << theIproj << "\n" << pfx << std::setw(24) << "SATTRACK:" << theSattrack << "\n"; return out; } ossimString ossimNitfPiaimcTag::getCloudcvrString() const { return ossimString(theCloudcvr); } ossimString ossimNitfPiaimcTag::getSrpString() const { return ossimString(theSrp); } ossimString ossimNitfPiaimcTag::getSensmodeString() const { return ossimString(thesSensmode); } ossimString ossimNitfPiaimcTag::getSensnameString() const { return ossimString(theSensname); } ossimString ossimNitfPiaimcTag::getSourceString() const { return ossimString(theSource); } ossimString ossimNitfPiaimcTag::getComgenString() const { return ossimString(theComgen); } ossimString ossimNitfPiaimcTag::getSubqualString() const { return ossimString(theSubqual); } ossimString ossimNitfPiaimcTag::getPiamsnnumString() const { return ossimString(thePiamsnnum); } ossimString ossimNitfPiaimcTag::getCamspecsString() const { return ossimString(theCamspecs); } ossimString ossimNitfPiaimcTag::getProjidString() const { return ossimString(theProjid); } ossimString ossimNitfPiaimcTag::getGenerationString() const { return ossimString(theGeneration); } ossimString ossimNitfPiaimcTag::getEsdString() const { return ossimString(theEsd); } ossimString ossimNitfPiaimcTag::getOthercondString() const { return ossimString(theOthercond); } ossimString ossimNitfPiaimcTag::getMeadGsdString() const { return ossimString(theMeanGsd); } ossim_float64 ossimNitfPiaimcTag::getMeanGsdInMeters() const { ossim_float64 gsd = 0.0; ossimString s = theMeanGsd; if (s.size()) { ossim_float64 d = s.toFloat64(); if ( (d != 0.0) && (ossim::isnan(d) == false) ) { gsd = d / 12.0 * MTRS_PER_FT; } } return gsd; } ossimString ossimNitfPiaimcTag::getIdatumString() const { return ossimString(theIdatum); } ossimString ossimNitfPiaimcTag::getIellipString() const { return ossimString(theIellip); } ossimString ossimNitfPiaimcTag::getPreprocString() const { return ossimString(thePreproc); } ossimString ossimNitfPiaimcTag::getIprojString() const { return ossimString(theIproj); } ossimString ossimNitfPiaimcTag::getSattrackString() const { return ossimString(theSattrack); } void ossimNitfPiaimcTag::setProperty(ossimRefPtr property) { ossimNitfRegisteredTag::setProperty(property); } ossimRefPtr ossimNitfPiaimcTag::getProperty(const ossimString& name)const { ossimProperty* result = 0; if(name == CLOUDCVR_KW) { result = new ossimStringProperty(name, theCloudcvr); } else if(name == SRP_KW) { result = new ossimStringProperty(name, theSrp); } else if(name == SENSMODE_KW) { result = new ossimStringProperty(name, thesSensmode); } else if(name == SENSNAME_KW) { result = new ossimStringProperty(name, theSensname); } else if(name == SOURCE_KW) { result = new ossimStringProperty(name, theSource); } else if(name == COMGEN_KW) { result = new ossimStringProperty(name, theComgen); } else if(name == SUBQUAL_KW) { result = new ossimStringProperty(name, theSubqual); } else if(name == PIAMSNNUM_KW) { result = new ossimStringProperty(name, thePiamsnnum); } else if(name == CAMSPECS_KW) { result = new ossimStringProperty(name, theCamspecs); } else if(name == PROJID_KW) { result = new ossimStringProperty(name, theProjid); } else if(name == GENERATION_KW) { result = new ossimStringProperty(name, theGeneration); } else if(name == ESD_KW) { result = new ossimStringProperty(name, theEsd); } else if(name == OTHERCOND_KW) { result = new ossimStringProperty(name, theOthercond); } else if(name == MEANGSD_KW) { result = new ossimStringProperty(name, theMeanGsd); } else if(name == IDATUM_KW) { result = new ossimStringProperty(name, theIdatum); } else if(name == IELLIP_KW) { result = new ossimStringProperty(name, theIellip); } else if(name == PREPROC_KW) { result = new ossimStringProperty(name, thePreproc); } else if(name == IPROJ_KW) { result = new ossimStringProperty(name, theIproj); } else if(name == SATTRACK_KW) { result = new ossimStringProperty(name, theSattrack); } else { return ossimNitfRegisteredTag::getProperty(name); } return result; } void ossimNitfPiaimcTag::getPropertyNames(std::vector& propertyNames)const { ossimNitfRegisteredTag::getPropertyNames(propertyNames); propertyNames.push_back(CLOUDCVR_KW); propertyNames.push_back(SRP_KW); propertyNames.push_back(SENSMODE_KW); propertyNames.push_back(SENSNAME_KW); propertyNames.push_back(SOURCE_KW); propertyNames.push_back(COMGEN_KW); propertyNames.push_back(SUBQUAL_KW); propertyNames.push_back(PIAMSNNUM_KW); propertyNames.push_back(CAMSPECS_KW); propertyNames.push_back(PROJID_KW); propertyNames.push_back(GENERATION_KW); propertyNames.push_back(ESD_KW); propertyNames.push_back(OTHERCOND_KW); propertyNames.push_back(MEANGSD_KW); propertyNames.push_back(IDATUM_KW); propertyNames.push_back(IELLIP_KW); propertyNames.push_back(PREPROC_KW); propertyNames.push_back(IPROJ_KW); propertyNames.push_back(SATTRACK_KW); } ossim-Miami-2.9.1/src/support_data/ossimNitfProjectionParameterTag.cpp000066400000000000000000000127711352751253100262300ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfProjectionParameterTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include #include #include using namespace std; ossimNitfProjectionParameterTag::ossimNitfProjectionParameterTag() :ossimNitfRegisteredTag(std::string("PRJPSB"), 0 ) { clearFields(); } ossimNitfProjectionParameterTag::~ossimNitfProjectionParameterTag() { } void ossimNitfProjectionParameterTag::parseStream(std::istream& in) { clearFields(); in.read(theProjectionName, 80); in.read(theProjectionCode, 2); in.read(theNumberOfParameters, 1); ossim_uint32 numberOfParameters = ossimString(theNumberOfParameters).toUInt32(); for(ossim_uint32 i = 0; i < numberOfParameters; ++i) { char param[15]; in.read(param, 15); theProjectionParameters.push_back(ossimString(param, param + 15)); } in.read(theFalseXOrigin, 15); in.read(theFalseYOrigin, 15); // Set the base tag length. setTagLength( getSizeInBytes() ); } void ossimNitfProjectionParameterTag::writeStream(std::ostream& out) { out.write(theProjectionName, 80); out.write(theProjectionCode, 2); { std::ostringstream tempOut; tempOut << std::setw(1) << theProjectionParameters.size(); theNumberOfParameters[0] = *(tempOut.str().c_str()); } out.write(theNumberOfParameters, 1); ossim_uint32 numberOfParameters = ossimString(theNumberOfParameters).toUInt32(); for(ossim_uint32 i = 0; i < numberOfParameters; ++i) { out.write(theProjectionParameters[i].c_str(), 15); } out.write(theFalseXOrigin, 15); out.write(theFalseYOrigin, 15); } ossim_uint32 ossimNitfProjectionParameterTag::getSizeInBytes()const { return (113 + (ossim_uint32)theProjectionParameters.size()*15); } std::ostream& ossimNitfProjectionParameterTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getRegisterTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getRegisterTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "PRN:" << theProjectionName << "\n" << pfx << std::setw(24) << "PCO:" << theProjectionCode << "\n" << pfx << std::setw(24) << "NUM_PRJ:" << theNumberOfParameters << "\n"; for (ossim_uint32 i = 0; i < theProjectionParameters.size(); ++i) { ossimString s = "PRJ"; s += ossimString::toString(i); s += ":"; out << pfx << std::setw(24) << s << theProjectionParameters[i] << "\n"; } out << pfx << std::setw(24) << "XOR:" < #include #include #include #include RTTI_DEF2(ossimNitfRegisteredDes, "ossimNitfRegisteredDes", ossimObject, ossimPropertyInterface) ossimNitfRegisteredDes::ossimNitfRegisteredDes() : ossimObject(), ossimPropertyInterface(), m_desName(), m_desLength(0) {} ossimNitfRegisteredDes::ossimNitfRegisteredDes(const std::string& desName, ossim_uint32 desLength) : ossimObject(), ossimPropertyInterface(), m_desName(desName), m_desLength(desLength) {} ossimNitfRegisteredDes::~ossimNitfRegisteredDes() {} std::string ossimNitfRegisteredDes::getRegisterDesName() const { // Deprecated: return m_desName; } const std::string& ossimNitfRegisteredDes::getDesName() const { return m_desName; } void ossimNitfRegisteredDes::setDesName(const std::string& desName) { m_desName = desName; } ossim_uint32 ossimNitfRegisteredDes::getSizeInBytes() const { // Deprecated: return getDesLength(); } const std::vector &ossimNitfRegisteredDes::getDesDataBuffer() const { return m_desData; } ossim_uint32 ossimNitfRegisteredDes::getDesLength() const { return m_desLength; } void ossimNitfRegisteredDes::setDesLength(ossim_uint32 length) { m_desLength = length; } void ossimNitfRegisteredDes::setProperty(ossimRefPtr /* property */) { } ossimRefPtr ossimNitfRegisteredDes::getProperty(const ossimString& /* name */)const { return 0; } void ossimNitfRegisteredDes::getPropertyNames(std::vector& /* propertyNames */)const { } void ossimNitfRegisteredDes::getMetadata(ossimKeywordlist& /* kwl */, const char* /* prefix */ ) const { } std::ostream& ossimNitfRegisteredDes::print( std::ostream& out, const std::string& /* prefix */) const { // return print(out); return out; } bool ossimNitfRegisteredDes::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = false; // by default we will use the already implemented print method as backup // std::ostringstream out; print(out); ossimKeywordlist kwlTemp; std::istringstream in(out.str()); if(kwlTemp.parseStream(in)) { result = true; kwl.add(prefix, kwlTemp); } return result; } ossim-Miami-2.9.1/src/support_data/ossimNitfRegisteredDesFactory.cpp000066400000000000000000000026451352751253100256770ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRegisteredDesFactory.cpp 23113 2015-01-28 17:04:17Z gpotts $ #include #include RTTI_DEF1(ossimNitfRegisteredDesFactory, "ossimNitfRegisteredDesFactory", ossimNitfDesFactory); static const char XML_DATA_CONTENT_DES[] = "XML_DATA_CONTENT"; static const char SICD_XML[] = "SICD_XML"; ossimNitfRegisteredDesFactory::ossimNitfRegisteredDesFactory() { } ossimNitfRegisteredDesFactory::~ossimNitfRegisteredDesFactory() { } ossimNitfRegisteredDesFactory* ossimNitfRegisteredDesFactory::instance() { static ossimNitfRegisteredDesFactory inst; return &inst; } ossimRefPtr ossimNitfRegisteredDesFactory::create( const ossimString& desName)const { ossimString name = ossimString(desName).trim().upcase(); ossimRefPtr result; if (desName == XML_DATA_CONTENT_DES || desName == SICD_XML) { result = new ossimNitfSicdXmlDataContentDes; result->setDesName(desName); } return result; } ossim-Miami-2.9.1/src/support_data/ossimNitfRegisteredTag.cpp000066400000000000000000000051131352751253100243400ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRegisteredTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include #include #include #include #include RTTI_DEF2(ossimNitfRegisteredTag, "ossimNitfRegisteredTag", ossimObject, ossimPropertyInterface) ossimNitfRegisteredTag::ossimNitfRegisteredTag() : ossimObject(), ossimPropertyInterface(), m_tagName(), m_tagLength(0) {} ossimNitfRegisteredTag::ossimNitfRegisteredTag(const std::string& tagName, ossim_uint32 tagLength) : ossimObject(), ossimPropertyInterface(), m_tagName(tagName), m_tagLength(tagLength) {} ossimNitfRegisteredTag::~ossimNitfRegisteredTag() {} std::string ossimNitfRegisteredTag::getRegisterTagName() const { // Deprecated: return m_tagName; } const std::string& ossimNitfRegisteredTag::getTagName() const { return m_tagName; } void ossimNitfRegisteredTag::setTagName(const std::string& tagName) { m_tagName = tagName; } ossim_uint32 ossimNitfRegisteredTag::getSizeInBytes() const { // Deprecated: return getTagLength(); } ossim_uint32 ossimNitfRegisteredTag::getTagLength() const { return m_tagLength; } void ossimNitfRegisteredTag::setTagLength(ossim_uint32 length) { m_tagLength = length; } void ossimNitfRegisteredTag::setProperty(ossimRefPtr /* property */) { } ossimRefPtr ossimNitfRegisteredTag::getProperty(const ossimString& /* name */)const { return 0; } void ossimNitfRegisteredTag::getPropertyNames(std::vector& /* propertyNames */)const { } void ossimNitfRegisteredTag::getMetadata(ossimKeywordlist& /* kwl */, const char* /* prefix */ ) const { } std::ostream& ossimNitfRegisteredTag::print( std::ostream& out, const std::string& /* prefix */) const { // return print(out); return out; } bool ossimNitfRegisteredTag::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = false; // by default we will use the already implemented print method as backup // std::ostringstream out; print(out); ossimKeywordlist kwlTemp; std::istringstream in(out.str()); if(kwlTemp.parseStream(in)) { result = true; kwl.add(prefix, kwlTemp); } return result; } ossim-Miami-2.9.1/src/support_data/ossimNitfRegisteredTagFactory.cpp000066400000000000000000000154071352751253100256770ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRegisteredTagFactory.cpp 23113 2015-01-28 17:04:17Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include #include #include // #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimNitfRegisteredTagFactory, "ossimNitfRegisteredTagFactory", ossimNitfTagFactory); static const char ACFTB_TAG[] = "ACFTB"; static const char AIMIDB_TAG[] = "AIMIDB"; static const char BLOCKA_TAG[] = "BLOCKA"; static const char CSCRNA_TAG[] = "CSCRNA"; static const char CSDIDA_TAG[] = "CSDIDA"; static const char CSEXRA_TAG[] = "CSEXRA"; static const char ENGRDA_TAG[] = "ENGRDA"; static const char GEOLOB_TAG[] = "GEOLOB"; static const char GEO_POSITIONING_TAG[] = "GEOPSB"; static const char ICHIPB_TAG[] = "ICHIPB"; static const char J2KLRA_TAG[] = "J2KLRA"; static const char LOCAL_GEOGRAPHIC_TAG[] = "GEOLOB"; static const char LOCAL_CARTOGRAPHIC_TAG[] = "MAPLOB"; static const char MSTGTA_TAG[] = "MSTGTA"; static const char PIAIMC_TAG[] = "PIAIMC"; static const char PROJECTION_PARAMETER_TAG[] = "PRJPSB"; static const char RPCB_TAG[] = "RPC00B"; static const char RPCA_TAG[] = "RPC00A"; static const char SENSRA_TAG[] = "SENSRA"; static const char STDIDC_TAG[] = "STDIDC"; static const char STREOB_TAG[] = "STREOB"; static const char USE00A_TAG[] = "USE00A"; static const char HISTOA_TAG[] = "HISTOA"; static const char CSCCGA_TAG[] = "CSCCGA"; static const char CSPROA_TAG[] = "CSPROA"; static const char EXOPTA_TAG[] = "EXOPTA"; static const char RSMECA_TAG[] = "RSMECA"; static const char RSMIDA_TAG[] = "RSMIDA"; static const char RSMPCA_TAG[] = "RSMPCA"; static const char RSMPIA_TAG[] = "RSMPIA"; ossimNitfRegisteredTagFactory::ossimNitfRegisteredTagFactory() { } ossimNitfRegisteredTagFactory::~ossimNitfRegisteredTagFactory() { } ossimNitfRegisteredTagFactory* ossimNitfRegisteredTagFactory::instance() { static ossimNitfRegisteredTagFactory inst; return &inst; } ossimRefPtr ossimNitfRegisteredTagFactory::create( const ossimString& tagName)const { ossimString name = ossimString(tagName).trim().upcase(); if(tagName == ACFTB_TAG) { return new ossimNitfAcftbTag; } else if(tagName == AIMIDB_TAG) { return new ossimNitfAimidbTag; } else if(tagName == BLOCKA_TAG) { return new ossimNitfBlockaTag; } else if(tagName == CSCRNA_TAG) { return new ossimNitfCscrnaTag; } else if(tagName == CSDIDA_TAG) { return new ossimNitfCsdidaTag; } else if(tagName == CSEXRA_TAG) { return new ossimNitfCsexraTag; } else if(tagName == ENGRDA_TAG) { return new ossimNitfEngrdaTag; } else if(tagName == GEOLOB_TAG) { return new ossimNitfGeolobTag; } else if(tagName == GEO_POSITIONING_TAG) { return new ossimNitfGeoPositioningTag; } else if(tagName == ICHIPB_TAG) { return new ossimNitfIchipbTag; } else if(tagName == J2KLRA_TAG) { return new ossimNitfJ2klraTag; } #if 0 /* ossimNitfGeolobTag */ else if(tagName == LOCAL_GEOGRAPHIC_TAG) { return new ossimNitfLocalGeographicTag; } #endif else if(tagName == LOCAL_CARTOGRAPHIC_TAG) { return new ossimNitfLocalCartographicTag; } else if(tagName == MSTGTA_TAG) { return new ossimNitfMstgtaTag; } else if(tagName == PIAIMC_TAG) { return new ossimNitfPiaimcTag; } else if(tagName == PROJECTION_PARAMETER_TAG) { return new ossimNitfProjectionParameterTag; } else if(tagName == RPCB_TAG) { return new ossimNitfRpcBTag(); } else if(tagName == RPCA_TAG) { return new ossimNitfRpcATag(); } else if (tagName == SENSRA_TAG) { return new ossimNitfSensraTag(); } else if (tagName == STDIDC_TAG) { return new ossimNitfStdidcTag(); } else if (tagName == STREOB_TAG) { return new ossimNitfStreobTag(); } else if (tagName == USE00A_TAG) { return new ossimNitfUse00aTag(); } else if(tagName == HISTOA_TAG) { return new ossimNitfHistoaTag(); } else if(tagName == CSCCGA_TAG) { return new ossimNitfCsccgaTag(); } else if(tagName == CSPROA_TAG) { return new ossimNitfCsproaTag(); } else if(tagName == EXOPTA_TAG) { return new ossimNitfExoptaTag(); } else if(tagName == RSMECA_TAG) { return new ossimNitfRsmecaTag(); } else if(tagName == RSMIDA_TAG) { return new ossimNitfRsmidaTag(); } else if(tagName == RSMPCA_TAG) { return new ossimNitfRsmpcaTag(); } else if(tagName == RSMPIA_TAG) { return new ossimNitfRsmpiaTag(); } return NULL; } ossim-Miami-2.9.1/src/support_data/ossimNitfRpcATag.cpp000066400000000000000000000012021352751253100230630ustar00rootroot00000000000000//******************************************************************* // // LICENSE: LGPL // // see top level LICENSE.txt // // Author: Garrett Potts // // Description: Nitf support class for RPC00A - // Rational Polynomial Coefficient extension. // //******************************************************************** // $Id: ossimNitfRpcATag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include RTTI_DEF1(ossimNitfRpcATag, "ossimNitfRpcATag", ossimNitfRpcBase); ossimNitfRpcATag::ossimNitfRpcATag() : ossimNitfRpcBase() { // Set the tag name in base. setTagName(std::string("RPC00A")); } ossim-Miami-2.9.1/src/support_data/ossimNitfRpcBTag.cpp000066400000000000000000000011051352751253100230660ustar00rootroot00000000000000//******************************************************************* // // LICENSE: LGPL // // see top level LICENSE.txt // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRpcBTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include RTTI_DEF1(ossimNitfRpcBTag, "ossimNitfRpcBTag", ossimNitfRpcBase); ossimNitfRpcBTag::ossimNitfRpcBTag() : ossimNitfRpcBase() { // Set the tag name in base. setTagName(std::string("RPC00B")); } ossim-Miami-2.9.1/src/support_data/ossimNitfRpcBase.cpp000066400000000000000000001016251352751253100231330ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class for RPC00A - // Rational Polynomial Coefficient extension. // //******************************************************************** // $Id: ossimNitfRpcBase.cpp 22013 2012-12-19 17:37:20Z dburken $ #include #include #include #include #include #include #include #include #include using namespace std; static const ossimTrace traceDebug(ossimString("ossimNitfRpcBase:debug")); static const ossimString ERR_BIAS_KW = "ERR_BIAS"; static const ossimString ERR_RAND_KW = "ERR_RAND"; static const ossimString LINE_OFF_KW = "LINE_OFF"; static const ossimString SAMP_OFF_KW = "SAMP_OFF"; static const ossimString LAT_OFF_KW = "LAT_OFF"; static const ossimString LONG_OFF_KW = "LONG_OFF"; static const ossimString HEIGHT_OFF_KW = "HEIGHT_OFF"; static const ossimString LINE_SCALE_KW = "LINE_SCALE"; static const ossimString SAMP_SCALE_KW = "SAMP_SCALE"; static const ossimString LAT_SCALE_KW = "LAT_SCALE"; static const ossimString LONG_SCALE_KW = "LONG_SCALE"; static const ossimString HEIGHT_SCALE_KW = "HEIGHT_SCALE"; static const ossimString LINE_NUM_COEFF_KW = "LINE_NUM_COEFF_"; static const ossimString LINE_DEN_COEFF_KW = "LINE_DEN_COEFF_"; static const ossimString SAMP_NUM_COEFF_KW = "SAMP_NUM_COEFF_"; static const ossimString SAMP_DEN_COEFF_KW = "SAMP_DEN_COEFF_"; RTTI_DEF1(ossimNitfRpcBase, "ossimNitfRpcBase", ossimNitfRegisteredTag); ossimNitfRpcBase::ossimNitfRpcBase() : ossimNitfRegisteredTag() { // Set the tag length in base. setTagLength(1041); clearFields(); } void ossimNitfRpcBase::parseStream(std::istream& in) { clearFields(); in.read(theSuccess, SUCCESS_SIZE); in.read(theErrorBias, ERROR_BIAS_SIZE); in.read(theErrRand, ERR_RAND_SIZE); in.read(theLineOffset, LINE_OFFSET_SIZE); in.read(theSampleOffset, SAMPLE_OFFSET_SIZE); in.read(theGeodeticLatOffset, GEODETIC_LAT_OFFSET_SIZE); in.read(theGeodeticLonOffset, GEODETIC_LON_OFFSET_SIZE); in.read(theGeodeticHeightOffset, GEODETIC_HEIGHT_OFFSET_SIZE); in.read(theLineScale, LINE_SCALE_SIZE); in.read(theSampleScale, SAMPLE_SCALE_SIZE); in.read(theGeodeticLatScale, GEODETIC_LAT_SCALE_SIZE); in.read(theGeodeticLonScale, GEODETIC_LON_SCALE_SIZE); in.read(theGeodeticHeightScale, GEODETIC_HEIGHT_SCALE_SIZE); ossim_uint32 idx = 0; char temp1[LINE_NUMERATOR_COEFFICIENT_SIZE+1]; temp1[LINE_NUMERATOR_COEFFICIENT_SIZE] = '\0'; for(idx = 0; idx < LINE_NUMERATOR_COEFFICIENT_COUNT; ++idx) { in.read(temp1, LINE_NUMERATOR_COEFFICIENT_SIZE); theLineNumeratorCoefficient[idx] = temp1; } char temp2[LINE_DENOMINATOR_COEFFICIENT_SIZE+1]; temp2[LINE_DENOMINATOR_COEFFICIENT_SIZE] = '\0'; for(idx = 0; idx < LINE_DENOMINATOR_COEFFICIENT_COUNT; ++idx) { in.read(temp2, LINE_DENOMINATOR_COEFFICIENT_SIZE); theLineDenominatorCoefficient[idx] = temp2; } char temp3[SAMPLE_NUMERATOR_COEFFICIENT_SIZE+1]; temp3[SAMPLE_NUMERATOR_COEFFICIENT_SIZE] = '\0'; for(idx = 0; idx < SAMPLE_NUMERATOR_COEFFICIENT_COUNT; ++idx) { in.read(temp3, SAMPLE_NUMERATOR_COEFFICIENT_SIZE); theSampleNumeratorCoefficient[idx] = temp3; } char temp4[SAMPLE_DENOMINATOR_COEFFICIENT_SIZE+1]; temp4[SAMPLE_DENOMINATOR_COEFFICIENT_SIZE] = '\0'; for(idx = 0; idx < SAMPLE_DENOMINATOR_COEFFICIENT_COUNT; ++idx) { in.read(temp4, SAMPLE_DENOMINATOR_COEFFICIENT_SIZE); theSampleDenominatorCoefficient[idx] = temp4; } } void ossimNitfRpcBase::writeStream(std::ostream& out) { ossim_uint32 idx = 0; out.write(theSuccess, SUCCESS_SIZE); out.write(theErrorBias, ERROR_BIAS_SIZE); out.write(theErrRand, ERR_RAND_SIZE); out.write(theLineOffset, LINE_OFFSET_SIZE); out.write(theSampleOffset, SAMPLE_OFFSET_SIZE); out.write(theGeodeticLatOffset, GEODETIC_LAT_OFFSET_SIZE); out.write(theGeodeticLonOffset, GEODETIC_LON_OFFSET_SIZE); out.write(theGeodeticHeightOffset, GEODETIC_HEIGHT_OFFSET_SIZE); out.write(theLineScale, LINE_SCALE_SIZE); out.write(theSampleScale, SAMPLE_SCALE_SIZE); out.write(theGeodeticLatScale, GEODETIC_LAT_SCALE_SIZE); out.write(theGeodeticLonScale, GEODETIC_LON_SCALE_SIZE); out.write(theGeodeticHeightScale, GEODETIC_HEIGHT_SCALE_SIZE); for(idx = 0; idx < LINE_NUMERATOR_COEFFICIENT_COUNT; ++idx) { out.write(theLineNumeratorCoefficient[idx].c_str(), LINE_NUMERATOR_COEFFICIENT_SIZE); } for(idx = 0; idx < LINE_DENOMINATOR_COEFFICIENT_COUNT; ++idx) { out.write(theLineDenominatorCoefficient[idx].c_str(), LINE_DENOMINATOR_COEFFICIENT_SIZE); } for(idx = 0; idx < SAMPLE_NUMERATOR_COEFFICIENT_COUNT; ++idx) { out.write(theSampleNumeratorCoefficient[idx].c_str(), SAMPLE_NUMERATOR_COEFFICIENT_SIZE); } for(idx = 0; idx < SAMPLE_DENOMINATOR_COEFFICIENT_COUNT; ++idx) { out.write(theSampleDenominatorCoefficient[idx].c_str(), SAMPLE_DENOMINATOR_COEFFICIENT_SIZE); } } void ossimNitfRpcBase::clearFields() { theSuccess[0] = '1'; memcpy(theErrorBias, "0000.00", 7); memcpy(theErrRand, "0000.00", 7); memcpy(theLineOffset, "000000", 6); memcpy(theSampleOffset, "00000", 5); memcpy(theGeodeticLatOffset, "+00.0000", 8); memcpy(theGeodeticLonOffset, "+000.0000", 9); memcpy(theGeodeticHeightOffset, "+0000", 5); memcpy(theLineScale, "000001", 6); memcpy(theSampleScale, "00001", 5); memcpy(theGeodeticLatScale, "+00.0000", 8); memcpy(theGeodeticLonScale, "+000.0000", 9); memcpy(theGeodeticHeightScale, "+0000", 5); theSuccess[1] = '\0'; theErrorBias[7] = '\0'; theErrRand[7] = '\0'; theLineOffset[6] = '\0'; theSampleOffset[5] = '\0'; theGeodeticLatOffset[8]='\0'; theGeodeticLonOffset[9]='\0'; theGeodeticHeightOffset[5]='\0'; theLineScale[6]='\0'; theSampleScale[5]='\0'; theGeodeticLatScale[8]='\0'; theGeodeticLonScale[9]='\0'; theGeodeticHeightScale[5]='\0'; theLineNumeratorCoefficient.resize(20); theLineDenominatorCoefficient.resize(20); theSampleNumeratorCoefficient.resize(20); theSampleDenominatorCoefficient.resize(20); ossim_uint32 idx = 0; const char* zeroString = "+0.000000E+0"; for(idx = 0; idx < theLineNumeratorCoefficient.size();++idx) { theLineNumeratorCoefficient[idx] = zeroString; theLineDenominatorCoefficient[idx] = zeroString;; theSampleNumeratorCoefficient[idx] = zeroString;; theSampleDenominatorCoefficient[idx] = zeroString;; } } void ossimNitfRpcBase::setRpcModelParams(ossimRefPtr rpc) { theSuccess[0] = '0'; if (!rpc) return; theSuccess[0] = '1'; setErrorBias(rpc->theBiasError); setErrorRand(rpc->theRandError); setLineOffset((int) rpc->theLineOffset); setSampleOffset((int) rpc->theSampOffset); setGeodeticLatOffset(rpc->theLatOffset); setGeodeticLonOffset(rpc->theLonOffset); setGeodeticHeightOffset(rpc->theHgtOffset); setLineScale((int) rpc->theLineScale); setSampleScale((int) rpc->theSampScale); setGeodeticLatScale(rpc->theLatScale); setGeodeticLonScale(rpc->theLonScale); setGeodeticHeightScale(rpc->theHgtScale); int idx; vector coef (20); for(idx = 0; idx < 20; ++idx) coef.push_back(rpc->theLineNumCoef[idx]); setLineNumeratorCoeff(coef); for(idx = 0; idx < 20; ++idx) coef[idx] = rpc->theLineDenCoef[idx]; setLineDenominatorCoeff(coef); for(idx = 0; idx < 20; ++idx) coef[idx] = rpc->theSampNumCoef[idx]; setSampleNumeratorCoeff(coef); for(idx = 0; idx < 20; ++idx) coef[idx] = rpc->theSampDenCoef[idx]; setSampleDenominatorCoeff(coef); } bool ossimNitfRpcBase::getSuccess()const { return (theSuccess[0] == '1'); } void ossimNitfRpcBase::setSuccess(bool success) { theSuccess[0] = success?'1':'0'; } ossimString ossimNitfRpcBase::getErrorBias()const { return theErrorBias; } void ossimNitfRpcBase::setErrorBias(const ossim_float64& errorBias) { ossimString os = ossimNitfCommon::convertToDoubleString(errorBias, 2, ERROR_BIAS_SIZE); setErrorBias(os); } void ossimNitfRpcBase::setErrorBias(const ossimString& errorBias) { memset(theErrorBias, ' ', ERROR_BIAS_SIZE); memcpy(theErrorBias, errorBias.c_str(), std::min((size_t)ERROR_BIAS_SIZE, errorBias.length())); } ossimString ossimNitfRpcBase::getErrorRand()const { return theErrRand; } void ossimNitfRpcBase::setErrorRand(const ossim_float64& errorRand) { ossimString os = ossimNitfCommon::convertToDoubleString(errorRand, 2, ERROR_BIAS_SIZE); setErrorRand(os); } void ossimNitfRpcBase::setErrorRand(const ossimString& errorRand) { memset(theErrRand, ' ', ERR_RAND_SIZE); memcpy(theErrRand, errorRand.c_str(), std::min((size_t)ERR_RAND_SIZE, errorRand.length())); } ossimString ossimNitfRpcBase::getLineOffset()const { return theLineOffset; } void ossimNitfRpcBase::setLineOffset(ossim_uint32 lineOffset) { ossimString os = ossimNitfCommon::convertToUIntString(lineOffset, LINE_OFFSET_SIZE); setLineOffset(os); } void ossimNitfRpcBase::setLineOffset(const ossimString& lineOffset) { memset(theLineOffset, ' ', LINE_OFFSET_SIZE); memcpy(theLineOffset, lineOffset.c_str(), std::min((size_t)LINE_OFFSET_SIZE, lineOffset.length())); } ossimString ossimNitfRpcBase::getSampleOffset()const { return theSampleOffset; } void ossimNitfRpcBase::setSampleOffset(ossim_uint32 sampleOffset) { ossimString os = ossimNitfCommon::convertToUIntString(sampleOffset, SAMPLE_OFFSET_SIZE); setSampleOffset(os); } void ossimNitfRpcBase::setSampleOffset(const ossimString& sampleOffset) { memset(theSampleOffset, ' ', SAMPLE_OFFSET_SIZE); memcpy(theSampleOffset, sampleOffset.c_str(), std::min((size_t)SAMPLE_OFFSET_SIZE, sampleOffset.length())); } ossimString ossimNitfRpcBase::getGeodeticLatOffset()const { return theGeodeticLatOffset; } void ossimNitfRpcBase::setGeodeticLatOffset( const ossim_float64& geodeticLatOffset) { if ( (geodeticLatOffset >= -90.0) && (geodeticLatOffset <= 90.0) ) { ossimString os = ossimNitfCommon::convertToDoubleString(geodeticLatOffset, 4, GEODETIC_LAT_OFFSET_SIZE); setGeodeticLatOffset(os); } } void ossimNitfRpcBase::setGeodeticLatOffset( const ossimString& geodeticLatOffset) { memset(theGeodeticLatOffset, ' ', GEODETIC_LAT_OFFSET_SIZE); memcpy(theGeodeticLatOffset, geodeticLatOffset.c_str(), std::min((size_t)GEODETIC_LAT_OFFSET_SIZE, geodeticLatOffset.length())); } ossimString ossimNitfRpcBase::getGeodeticLonOffset()const { return theGeodeticLonOffset; } void ossimNitfRpcBase::setGeodeticLonOffset( const ossim_float64& geodeticLonOffset) { if ( (geodeticLonOffset >= -180.0) && (geodeticLonOffset <= 180.0) ) { ossimString os = ossimNitfCommon::convertToDoubleString(geodeticLonOffset, 4, GEODETIC_LON_OFFSET_SIZE); setGeodeticLonOffset(os); } } void ossimNitfRpcBase::setGeodeticLonOffset(const ossimString& geodeticLonOffset) { memset(theGeodeticLonOffset, ' ', GEODETIC_LON_OFFSET_SIZE); memcpy(theGeodeticLonOffset, geodeticLonOffset.c_str(), std::min((size_t)GEODETIC_LON_OFFSET_SIZE, geodeticLonOffset.length())); } ossimString ossimNitfRpcBase::getGeodeticHeightOffset()const { return theGeodeticHeightOffset; } void ossimNitfRpcBase::setGeodeticHeightOffset( ossim_int32 geodeticHeightOffset) { ossimString os = ossimNitfCommon::convertToIntString(geodeticHeightOffset, GEODETIC_HEIGHT_OFFSET_SIZE); setGeodeticHeightOffset(os); } void ossimNitfRpcBase::setGeodeticHeightOffset(const ossimString& geodeticHeightOffset) { memset(theGeodeticHeightOffset, ' ', GEODETIC_HEIGHT_OFFSET_SIZE); memcpy(theGeodeticHeightOffset, geodeticHeightOffset.c_str(), std::min((size_t)GEODETIC_HEIGHT_OFFSET_SIZE, geodeticHeightOffset.length())); } ossimString ossimNitfRpcBase::getLineScale()const { return theLineScale; } void ossimNitfRpcBase::setLineScale(ossim_uint32 lineScale) { ossimString os = ossimNitfCommon::convertToUIntString(lineScale, LINE_SCALE_SIZE); setLineScale(os); } void ossimNitfRpcBase::setLineScale(const ossimString& lineScale) { memset(theLineScale, ' ', LINE_SCALE_SIZE); memcpy(theLineScale, lineScale.c_str(), std::min((size_t)LINE_SCALE_SIZE, lineScale.length())); } ossimString ossimNitfRpcBase::getSampleScale()const { return theSampleScale; } void ossimNitfRpcBase::setSampleScale(ossim_uint32 sampleScale) { ossimString os = ossimNitfCommon::convertToUIntString(sampleScale, SAMPLE_SCALE_SIZE); setSampleScale(os); } void ossimNitfRpcBase::setSampleScale(const ossimString& sampleScale) { memset(theSampleScale, ' ', SAMPLE_SCALE_SIZE); memcpy(theSampleScale, sampleScale.c_str(), std::min((size_t)SAMPLE_SCALE_SIZE, sampleScale.length())); } ossimString ossimNitfRpcBase::getGeodeticLatScale()const { return theGeodeticLatScale; } void ossimNitfRpcBase::setGeodeticLatScale( const ossim_float64& geodeticLatScale) { if (geodeticLatScale == 0.0) { // Error scale cannot be zero. return; } if ( (geodeticLatScale >= -90.0) && (geodeticLatScale <= 90.0) ) { ossimString os = ossimNitfCommon::convertToDoubleString(geodeticLatScale, 4, GEODETIC_LAT_SCALE_SIZE); setGeodeticLatScale(os); } } void ossimNitfRpcBase::setGeodeticLatScale(const ossimString& geodeticLatScale) { memset(theGeodeticLatScale, ' ', GEODETIC_LAT_SCALE_SIZE); memcpy(theGeodeticLatScale, geodeticLatScale.c_str(), std::min((size_t)GEODETIC_LAT_SCALE_SIZE, geodeticLatScale.length())); } ossimString ossimNitfRpcBase::getGeodeticLonScale()const { return theGeodeticLonScale; } void ossimNitfRpcBase::setGeodeticLonScale( const ossim_float64& geodeticLonScale) { if (geodeticLonScale == 0.0) { // Error scale cannot be zero. return; } if ( (geodeticLonScale >= -180.0) && (geodeticLonScale <= 180.0) ) { ossimString os = ossimNitfCommon::convertToDoubleString(geodeticLonScale, 4, GEODETIC_LON_SCALE_SIZE); setGeodeticLonScale(os); } } void ossimNitfRpcBase::setGeodeticLonScale(const ossimString& geodeticLonScale) { memset(theGeodeticLonScale, ' ', GEODETIC_LON_SCALE_SIZE); memcpy(theGeodeticLonScale, geodeticLonScale.c_str(), std::min((size_t)GEODETIC_LON_SCALE_SIZE, geodeticLonScale.length())); } ossimString ossimNitfRpcBase::getGeodeticHeightScale()const { return theGeodeticHeightScale; } void ossimNitfRpcBase::setGeodeticHeightScale(ossim_int32 geodeticHeightScale) { ossimString os = ossimNitfCommon::convertToIntString(geodeticHeightScale, GEODETIC_HEIGHT_SCALE_SIZE); setGeodeticHeightScale(os); } void ossimNitfRpcBase::setGeodeticHeightScale( const ossimString& geodeticHeightScale) { memset(theGeodeticHeightScale, ' ', GEODETIC_HEIGHT_SCALE_SIZE); memcpy(theGeodeticHeightScale, geodeticHeightScale.c_str(), std::min((size_t)GEODETIC_HEIGHT_SCALE_SIZE, geodeticHeightScale.length())); } /* Temp comment out until range error handling is decided.*/ #if 0 // The assert here will be ignored when compiled with -DNDEBUG so ossimSetError and fix the index #define ASSERT_ARRAY_CONSTRAINT(expression, idx, correctedValue, module) \ assert(expression); \ ossimSetError(getClassName().c_str(), ossimErrorCodes::OSSIM_ERROR, \ "File %s line %d Module %s Error:\nArray index constraint error.\n", \ __FILE__, __LINE__, module); \ if (! (expression) ) idx = correctedValue; #endif ossimString ossimNitfRpcBase::getLineNumeratorCoeff(ossim_uint32 idx)const { //ASSERT_ARRAY_CONSTRAINT(idx >= 0 && idx < LINE_NUMERATOR_COEFFICIENT_COUNT,idx,0,"ossimNitfRpcBase::getLineNumeratorCoeff"); if (idx >= LINE_NUMERATOR_COEFFICIENT_COUNT) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfRpcBase::getLineNumeratorCoeff range error!" << std::endl; } return ossimString(); } return theLineNumeratorCoefficient[idx]; } void ossimNitfRpcBase::setLineNumeratorCoeff( const std::vector& coeff) { if (coeff.size() != LINE_NUMERATOR_COEFFICIENT_COUNT) { // Error... if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcBase::setLineNumeratorCoeff WARNING:" << "\nArray not of correct size!" << std::endl; } return; } for (ossim_uint32 i = 0; i < LINE_NUMERATOR_COEFFICIENT_COUNT; ++i) { ossimString os = ossimNitfCommon::convertToScientificString( coeff[i], LINE_NUMERATOR_COEFFICIENT_SIZE); setLineNumeratorCoeff(i, os); } } void ossimNitfRpcBase::setLineNumeratorCoeff(ossim_uint32 idx, const ossimString& coeff) { // ASSERT_ARRAY_CONSTRAINT(idx >= 0 && idx < LINE_NUMERATOR_COEFFICIENT_COUNT,idx,0,"ossimNitfRpcBase::setLineNumeratorCoeff"); if (idx >= LINE_NUMERATOR_COEFFICIENT_COUNT) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfRpcBase::setLineNumeratorCoeff range error!" << std::endl; return; } std::string s(coeff, 0, LINE_NUMERATOR_COEFFICIENT_SIZE); theLineNumeratorCoefficient[idx] = s; } ossimString ossimNitfRpcBase::getLineDenominatorCoeff(ossim_uint32 idx)const { // ASSERT_ARRAY_CONSTRAINT(idx >= 0 && idx < LINE_DENOMINATOR_COEFFICIENT_COUNT,idx,0,"ossimNitfRpcBase::getLineDenominatorCoeff"); if (idx >= LINE_DENOMINATOR_COEFFICIENT_COUNT) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfRpcBase::getLineDenominatorCoeff range error!" << std::endl; return ossimString(); } return theLineDenominatorCoefficient[idx]; } void ossimNitfRpcBase::setLineDenominatorCoeff( const std::vector& coeff) { if (coeff.size() != LINE_DENOMINATOR_COEFFICIENT_COUNT) { // Error... if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcBase::setLineDenominatorCoeff WARNING:" << "\nArray not of correct size!" << std::endl; } return; } for (ossim_uint32 i = 0; i < LINE_DENOMINATOR_COEFFICIENT_COUNT; ++i) { ossimString os = ossimNitfCommon::convertToScientificString( coeff[i], LINE_DENOMINATOR_COEFFICIENT_SIZE); setLineDenominatorCoeff(i, os); } } void ossimNitfRpcBase::setLineDenominatorCoeff(ossim_uint32 idx, const ossimString& coeff) { // ASSERT_ARRAY_CONSTRAINT(idx >= 0 && idx < LINE_DENOMINATOR_COEFFICIENT_COUNT,idx,0,"ossimNitfRpcBase::setLineDenominatorCoeff"); if (idx >= LINE_DENOMINATOR_COEFFICIENT_COUNT) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfRpcBase::setLineDenominatorCoeff range error!" << std::endl; return; } std::string s(coeff, 0, LINE_DENOMINATOR_COEFFICIENT_SIZE); theLineDenominatorCoefficient[idx] = s; } ossimString ossimNitfRpcBase::getSampleNumeratorCoeff(ossim_uint32 idx)const { // ASSERT_ARRAY_CONSTRAINT(idx >= 0 && idx < SAMPLE_NUMERATOR_COEFFICIENT_COUNT,idx,0,"ossimNitfRpcBase::getSampleNumeratorCoeff"); if (idx >= SAMPLE_NUMERATOR_COEFFICIENT_COUNT) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfRpcBase::getSampleNumeratorCoeff range error!" << std::endl; return ossimString(); } return theSampleNumeratorCoefficient[idx]; } void ossimNitfRpcBase::setSampleNumeratorCoeff( const std::vector& coeff) { if (coeff.size() != SAMPLE_NUMERATOR_COEFFICIENT_COUNT) { // Error... if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcBase::setSampleNumeratorCoeff WARNING:" << "\nArray not of correct size!" << std::endl; } return; } for (ossim_uint32 i = 0; i < SAMPLE_NUMERATOR_COEFFICIENT_COUNT; ++i) { ossimString os = ossimNitfCommon::convertToScientificString( coeff[i], SAMPLE_NUMERATOR_COEFFICIENT_SIZE); setSampleNumeratorCoeff(i, os); } } void ossimNitfRpcBase::setSampleNumeratorCoeff(ossim_uint32 idx, const ossimString& coeff) { // ASSERT_ARRAY_CONSTRAINT(idx >= 0 && idx < SAMPLE_NUMERATOR_COEFFICIENT_COUNT,idx,0,"ossimNitfRpcBase::setSampleNumeratorCoeff"); if (idx >= SAMPLE_NUMERATOR_COEFFICIENT_COUNT) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfRpcBase::setSampleNumeratorCoeff range error!" << std::endl; return; } std::string s(coeff, 0, SAMPLE_NUMERATOR_COEFFICIENT_SIZE); theSampleNumeratorCoefficient[idx] = s; } ossimString ossimNitfRpcBase::getSampleDenominatorCoeff(ossim_uint32 idx)const { // ASSERT_ARRAY_CONSTRAINT(idx >= 0 && idx < SAMPLE_DENOMINATOR_COEFFICIENT_COUNT,idx,0,"ossimNitfRpcBase::getSampleDenominatorCoeff"); if (idx >= SAMPLE_DENOMINATOR_COEFFICIENT_COUNT) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfRpcBase::getSampleDenominatorCoeff range error!" << std::endl; return ossimString(); } return theSampleDenominatorCoefficient[idx]; } void ossimNitfRpcBase::setSampleDenominatorCoeff( const std::vector& coeff) { if (coeff.size() != SAMPLE_DENOMINATOR_COEFFICIENT_COUNT) { // Error... if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimNitfRpcBase::setSampleDenominatorCoeff WARNING:" << "\nArray not of correct size!" << std::endl; } return; } for (ossim_uint32 i = 0; i < SAMPLE_DENOMINATOR_COEFFICIENT_COUNT; ++i) { ossimString os = ossimNitfCommon::convertToScientificString( coeff[i], SAMPLE_DENOMINATOR_COEFFICIENT_SIZE); setSampleDenominatorCoeff(i, os); } } void ossimNitfRpcBase::setSampleDenominatorCoeff( ossim_uint32 idx, const ossimString& coeff) { // ASSERT_ARRAY_CONSTRAINT(idx >= 0 && idx < SAMPLE_DENOMINATOR_COEFFICIENT_COUNT,idx,0,"ossimNitfRpcBase::setSampleDenominatorCoeff"); if (idx >= SAMPLE_DENOMINATOR_COEFFICIENT_COUNT) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfRpcBase::setSampleDenominatorCoeff range error!" << std::endl; return; } std::string s(coeff, 0, SAMPLE_DENOMINATOR_COEFFICIENT_SIZE); s.resize(SAMPLE_DENOMINATOR_COEFFICIENT_SIZE, ' '); theSampleDenominatorCoefficient[idx] = s; } std::ostream& ossimNitfRpcBase::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getSizeInBytes() << "\n" << pfx << std::setw(24) << "SUCCESS:" << theSuccess << "\n" << pfx << std::setw(24) << "ERR_BIAS:" << theErrorBias << "\n" << pfx << std::setw(24) << "ERR_RAND:" < /* property */) { } ossimRefPtr ossimNitfRpcBase::getProperty(const ossimString& name)const { ossimProperty* result = 0; if(name == ERR_BIAS_KW) { result = new ossimStringProperty(name, theErrorBias); } else if(name == ERR_RAND_KW) { result = new ossimStringProperty(name, theErrRand); } else if(name == LINE_OFF_KW) { result = new ossimStringProperty(name, theLineOffset); } else if(name == SAMP_OFF_KW) { result = new ossimStringProperty(name, theSampleOffset); } else if(name == LAT_OFF_KW) { result = new ossimStringProperty(name, theGeodeticLatOffset); } else if(name == LONG_OFF_KW) { result = new ossimStringProperty(name, theGeodeticLonOffset); } else if(name == HEIGHT_OFF_KW) { result = new ossimStringProperty(name, theGeodeticHeightOffset); } else if(name == LINE_SCALE_KW) { result = new ossimStringProperty(name, theLineScale); } else if(name == SAMP_SCALE_KW) { result = new ossimStringProperty(name,theSampleScale ); } else if(name == LAT_SCALE_KW) { result = new ossimStringProperty(name, theGeodeticLatScale); } else if(name == LONG_SCALE_KW) { result = new ossimStringProperty(name, theGeodeticLonScale); } else if(name == HEIGHT_SCALE_KW) { result = new ossimStringProperty(name, theGeodeticHeightScale); } else if(name.contains(LINE_NUM_COEFF_KW)) { ossim_uint32 idx = 0; idx = ossimString(name.begin()+LINE_NUM_COEFF_KW.length(), name.end()).toUInt32(); --idx; if(idx < theLineNumeratorCoefficient.size()) { result = new ossimStringProperty(name, theLineNumeratorCoefficient[idx]); } } else if(name.contains(LINE_DEN_COEFF_KW)) { ossim_uint32 idx = 0; idx = ossimString(name.begin()+LINE_DEN_COEFF_KW.length(), name.end()).toUInt32(); --idx; if(idx < theLineDenominatorCoefficient.size()) { result = new ossimStringProperty(name, theLineDenominatorCoefficient[idx]); } } else if(name.contains(SAMP_NUM_COEFF_KW)) { ossim_uint32 idx = 0; idx = ossimString(name.begin()+SAMP_NUM_COEFF_KW.length(), name.end()).toUInt32(); --idx; if(idx < theSampleNumeratorCoefficient.size()) { result = new ossimStringProperty(name, theSampleNumeratorCoefficient[idx]); } } else if(name.contains(SAMP_DEN_COEFF_KW)) { ossim_uint32 idx = 0; idx = ossimString(name.begin()+SAMP_DEN_COEFF_KW.length(), name.end()).toUInt32(); --idx; if(idx < theSampleDenominatorCoefficient.size()) { result = new ossimStringProperty(name, theSampleDenominatorCoefficient[idx]); } } return result; } void ossimNitfRpcBase::getPropertyNames(std::vector& propertyNames)const { ossim_uint32 idx = 0; propertyNames.push_back(ERR_BIAS_KW); propertyNames.push_back(ERR_RAND_KW); propertyNames.push_back(LINE_OFF_KW); propertyNames.push_back(SAMP_OFF_KW); propertyNames.push_back(LAT_OFF_KW); propertyNames.push_back(LONG_OFF_KW); propertyNames.push_back(HEIGHT_OFF_KW); propertyNames.push_back(LINE_SCALE_KW); propertyNames.push_back(SAMP_SCALE_KW); propertyNames.push_back(LAT_SCALE_KW); propertyNames.push_back(LONG_SCALE_KW); propertyNames.push_back(HEIGHT_SCALE_KW); for(idx = 1; idx <= 20; ++idx) { propertyNames.push_back(LINE_NUM_COEFF_KW+ossimString::toString(idx)); } for(idx = 1; idx <= 20; ++idx) { propertyNames.push_back(LINE_DEN_COEFF_KW+ossimString::toString(idx)); } for(idx = 1; idx <= 20; ++idx) { propertyNames.push_back(SAMP_NUM_COEFF_KW+ossimString::toString(idx)); } for(idx = 1; idx <= 20; ++idx) { propertyNames.push_back(SAMP_DEN_COEFF_KW+ossimString::toString(idx)); } } bool ossimNitfRpcBase::loadState(const ossimKeywordlist& kwl, const char* prefix) { bool result = ossimNitfRegisteredTag::loadState(kwl, prefix); const char* lookup; if(!result) return result; lookup = kwl.find(prefix, "SUCCESS"); if(lookup) { strcpy(theSuccess, lookup); } lookup = kwl.find(prefix, "ERR_BIAS"); if(lookup) { strcpy(theErrorBias, lookup); } lookup = kwl.find(prefix, "ERR_RAND"); if(lookup) { strcpy(theErrRand, lookup); } lookup = kwl.find(prefix, "LINE_OFF"); if(lookup) { strcpy(theLineOffset, lookup); } lookup = kwl.find(prefix, "SAMP_OFF"); if(lookup) { strcpy(theSampleOffset, lookup); } lookup = kwl.find(prefix, "LAT_OFF"); if(lookup) { strcpy(theGeodeticLatOffset, lookup); } lookup = kwl.find(prefix, "LONG_OFF"); if(lookup) { strcpy(theGeodeticLonOffset, lookup); } lookup = kwl.find(prefix, "HEIGHT_OFF"); if(lookup) { strcpy(theGeodeticHeightOffset, lookup); } lookup = kwl.find(prefix, "LINE_SCALE"); if(lookup) { strcpy(theLineScale, lookup); } lookup = kwl.find(prefix, "SAMP_SCALE"); if(lookup) { strcpy(theSampleScale, lookup); } lookup = kwl.find(prefix, "LAT_SCALE"); if(lookup) { strcpy(theGeodeticLatScale, lookup); } lookup = kwl.find(prefix, "LONG_SCALE"); if(lookup) { strcpy(theGeodeticLonScale, lookup); } lookup = kwl.find(prefix, "HEIGHT_SCALE"); if(lookup) { strcpy(theGeodeticHeightScale, lookup); } for (ossim_uint32 i = 0; i < 20; ++i) { ossimString line_num_coeff = "LINE_NUM_COEFF_" + ossimString::toString(i); lookup = kwl.find(prefix, line_num_coeff); if(lookup) { theLineNumeratorCoefficient[i] = ossimString(lookup); //temp.substr(0,1) + "0." + temp.substr(1,6) + "E" + temp.substr(7,2); } } for (ossim_uint32 i = 0; i < 20; ++i) { ossimString line_den_coeff = "LINE_DEN_COEFF_" + ossimString::toString(i); lookup = kwl.find(prefix, line_den_coeff); if(lookup) { theLineDenominatorCoefficient[i] = ossimString(lookup); //temp.substr(0,1) + "0." + temp.substr(1,6) + "E" + temp.substr(7,2); } } for (ossim_uint32 i = 0; i < 20; ++i) { ossimString samp_num_coeff = "SAMP_NUM_COEFF_" + ossimString::toString(i); lookup = kwl.find(prefix, samp_num_coeff); if(lookup) { theSampleNumeratorCoefficient[i] = ossimString(lookup); //temp.substr(0,1) + "0." + temp.substr(1,6) + "E" + temp.substr(7,2); } } for (ossim_uint32 i = 0; i < 20; ++i) { ossimString samp_den_coeff = "SAMP_DEN_COEFF_" + ossimString::toString(i); lookup = kwl.find(prefix, samp_den_coeff); if(lookup) { theSampleDenominatorCoefficient[i] = ossimString(lookup); //temp.substr(0,1) + "0." + temp.substr(1,6) + "E" + temp.substr(7,2); } } return result; } ossim-Miami-2.9.1/src/support_data/ossimNitfRpfTagFactory.cpp000066400000000000000000000027761352751253100243360ustar00rootroot00000000000000//******************************************************************* // // LICENSE: LGPL see top level LICENSE.txt // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRpfTagFactory.cpp 22875 2014-08-27 13:52:03Z dburken $ #include #include #include #include RTTI_DEF1(ossimNitfRpfTagFactory, "ossimNitfRpfTagFactory", ossimNitfTagFactory); static const ossimString REGISTERED_RPF_HEADER_TAG = "RPFHDR"; static const ossimString REGISTERED_RPF_DES_TAG = "RPFDES"; static ossimTrace traceDebug = ossimTrace("ossimNitfRpfTagFactory:debug"); ossimNitfRpfTagFactory::ossimNitfRpfTagFactory() { } ossimNitfRpfTagFactory::~ossimNitfRpfTagFactory() { } ossimNitfRpfTagFactory* ossimNitfRpfTagFactory::instance() { static ossimNitfRpfTagFactory inst; return &inst; } ossimRefPtr ossimNitfRpfTagFactory::create(const ossimString &tagName)const { ossimString temp(ossimString(tagName).trim().upcase()); if(temp == REGISTERED_RPF_HEADER_TAG) { return new ossimRpfHeader; } if(temp == REGISTERED_RPF_DES_TAG) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimNitfRpfTagFactory::create: Reader for REGISTERED_RPF_DES_TAG not implemented yet" << std::endl; } } return 0; } ossim-Miami-2.9.1/src/support_data/ossimNitfRsmecaTag.cpp000066400000000000000000000707251352751253100234700ustar00rootroot00000000000000//--- // File: ossimNitfRsmecaTag.cpp //--- #include #include #include #include #include #include #include using namespace std; static const ossimTrace traceDebug(ossimString("ossimNitfRsmecaTag:debug")); static const ossimString RNPCF_KW = "RNPCF"; static const ossimString RDPCF_KW = "RDPCF"; // "0 1 2"; // "123456789012345678901"; static const ossimString FILL21 = " "; ossimNitfRsmecaIsg::ossimNitfRsmecaIsg() : m_numopg(), m_errcvg(), m_tcdf(), m_ncseg(), m_corseg(), m_tauseg(), m_errCovNum(0), m_opgNum(0), m_corSegNum(0) { } ossimNitfRsmecaIsg::ossimNitfRsmecaIsg(const ossimNitfRsmecaIsg& obj) : m_numopg(), m_errcvg(obj.m_errcvg), m_tcdf(), m_ncseg(), m_corseg(obj.m_corseg), m_tauseg(obj.m_tauseg), m_errCovNum(obj.m_errCovNum), m_opgNum(obj.m_opgNum), m_corSegNum(obj.m_corSegNum) { strncpy( m_numopg, obj.m_numopg, (NUMOPG_SIZE+1) ); strncpy( m_tcdf, obj.m_tcdf, (TCDF_SIZE+1) ); strncpy( m_ncseg, obj.m_ncseg, (NCSEG_SIZE+1) ); } const ossimNitfRsmecaIsg& ossimNitfRsmecaIsg::operator=(const ossimNitfRsmecaIsg& rhs) { if (this != &rhs) { strncpy( m_numopg, rhs.m_numopg, (NUMOPG_SIZE+1) ); m_errcvg = rhs.m_errcvg; strncpy( m_tcdf, rhs.m_tcdf, (TCDF_SIZE+1) ); strncpy( m_ncseg, rhs.m_ncseg, (NCSEG_SIZE+1) ); m_corseg = rhs.m_corseg; m_tauseg = rhs.m_tauseg; m_errCovNum = rhs.m_errCovNum; m_opgNum = rhs.m_opgNum; m_corSegNum = rhs.m_corSegNum; } return *this; } void ossimNitfRsmecaIsg::parseStream(std::istream& in) { clearFields(); in.read(m_numopg, NUMOPG_SIZE); m_opgNum = ossimString(m_numopg).toUInt32(); m_errCovNum = (m_opgNum * (m_opgNum + 1)) / 2; ossim_uint32 i = 0; char temp1[FLOAT21_SIZE+1]; temp1[FLOAT21_SIZE] = '\0'; m_errcvg.resize(m_errCovNum); for (i=0; i < m_errCovNum; ++i) { in.read(temp1, FLOAT21_SIZE); m_errcvg[i] = FILL21; m_errcvg[i] = temp1; } in.read(m_tcdf, TCDF_SIZE); in.read(m_ncseg, NCSEG_SIZE); m_corSegNum = ossimString(m_ncseg).toUInt32(); m_corseg.resize(m_corSegNum); m_tauseg.resize(m_corSegNum); for (i=0; i < m_corSegNum; ++i) { in.read(temp1, FLOAT21_SIZE); m_corseg[i] = FILL21; m_corseg[i] = temp1; in.read(temp1, FLOAT21_SIZE); m_tauseg[i] = FILL21; m_tauseg[i] = temp1; } } void ossimNitfRsmecaIsg::writeStream(std::ostream& out) { out.write(m_numopg, NUMOPG_SIZE); ossim_uint32 i = 0; for (i=0; i < m_errCovNum; ++i) { out.write(m_errcvg[i], FLOAT21_SIZE); } out.write(m_tcdf, TCDF_SIZE); out.write(m_ncseg, NCSEG_SIZE); for (i=0; i < m_corSegNum; ++i) { out.write(m_corseg[i], FLOAT21_SIZE); out.write(m_tauseg[i], FLOAT21_SIZE); } } void ossimNitfRsmecaIsg::clearFields() { memset(m_numopg, ' ', NUMOPG_SIZE); memset(m_tcdf, ' ', TCDF_SIZE); memset(m_ncseg, ' ', NCSEG_SIZE); m_numopg[NUMOPG_SIZE] = '\0'; m_tcdf[TCDF_SIZE] = '\0'; m_ncseg[NCSEG_SIZE] = '\0'; } std::ostream& ossimNitfRsmecaIsg::print( std::ostream& out, const std::string& prefix, ossim_uint32 index) const { std::string pfx = prefix; pfx += "RSMECA"; pfx += ".ISG"; pfx += ossimString::toString(index).c_str(); pfx += "."; ossim_uint32 i = 0; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "NUMOPG:" << m_numopg << "\n"; for(i=0;i #include #include using namespace std; RTTI_DEF1(ossimNitfRsmidaTag, "ossimNitfRsmidaTag", ossimNitfRegisteredTag); ossimNitfRsmidaTag::ossimNitfRsmidaTag() : ossimNitfRegisteredTag(std::string("RSMIDA"), CEL_SIZE), m_iid(), m_edition(), m_isid(), m_sid(), m_stid(), m_year(), m_month(), m_day(), m_hour(), m_minute(), m_second(), m_nrg(), m_ncg(), m_trg(), m_tcg(), m_grndd(), m_xuor(), m_yuor(), m_zuor(), m_xuxr(), m_xuyr(), m_xuzr(), m_yuxr(), m_yuyr(), m_yuzr(), m_zuxr(), m_zuyr(), m_zuzr(), m_v1x(), m_v1y(), m_v1z(), m_v2x(), m_v2y(), m_v2z(), m_v3x(), m_v3y(), m_v3z(), m_v4x(), m_v4y(), m_v4z(), m_v5x(), m_v5y(), m_v5z(), m_v6x(), m_v6y(), m_v6z(), m_v7x(), m_v7y(), m_v7z(), m_v8x(), m_v8y(), m_v8z(), m_grpx(), m_grpy(), m_grpz(), m_fullr(), m_fullc(), m_minr(), m_maxr(), m_minc(), m_maxc(), m_ie0(), m_ier(), m_iec(), m_ierr(), m_ierc(), m_iecc(), m_ia0(), m_iar(), m_iac(), m_iarr(), m_iarc(), m_iacc(), m_spx(), m_svx(), m_sax(), m_spy(), m_svy(), m_say(), m_spz(), m_svz(), m_saz() { clearFields(); } void ossimNitfRsmidaTag::parseStream(std::istream& in) { in.read(m_iid, IID_SIZE); in.read(m_edition, EDITION_SIZE); in.read(m_isid, ISID_SIZE); in.read(m_sid, SID_SIZE); in.read(m_stid, STID_SIZE); in.read(m_year, YEAR_SIZE); in.read(m_month, MONTH_SIZE); in.read(m_day, DAY_SIZE); in.read(m_hour, HOUR_SIZE); in.read(m_minute, MINUTE_SIZE); in.read(m_second, SECOND_SIZE); in.read(m_nrg, NRG_SIZE); in.read(m_ncg, NCG_SIZE); in.read(m_trg, FLOAT21_SIZE); in.read(m_tcg, FLOAT21_SIZE); in.read(m_grndd, GRNDD_SIZE); in.read(m_xuor, FLOAT21_SIZE); in.read(m_yuor, FLOAT21_SIZE); in.read(m_zuor, FLOAT21_SIZE); in.read(m_xuxr, FLOAT21_SIZE); in.read(m_xuyr, FLOAT21_SIZE); in.read(m_xuzr, FLOAT21_SIZE); in.read(m_yuxr, FLOAT21_SIZE); in.read(m_yuyr, FLOAT21_SIZE); in.read(m_yuzr, FLOAT21_SIZE); in.read(m_zuxr, FLOAT21_SIZE); in.read(m_zuyr, FLOAT21_SIZE); in.read(m_zuzr, FLOAT21_SIZE); in.read(m_v1x, FLOAT21_SIZE); in.read(m_v1y, FLOAT21_SIZE); in.read(m_v1z, FLOAT21_SIZE); in.read(m_v2x, FLOAT21_SIZE); in.read(m_v2y, FLOAT21_SIZE); in.read(m_v2z, FLOAT21_SIZE); in.read(m_v3x, FLOAT21_SIZE); in.read(m_v3y, FLOAT21_SIZE); in.read(m_v3z, FLOAT21_SIZE); in.read(m_v4x, FLOAT21_SIZE); in.read(m_v4y, FLOAT21_SIZE); in.read(m_v4z, FLOAT21_SIZE); in.read(m_v5x, FLOAT21_SIZE); in.read(m_v5y, FLOAT21_SIZE); in.read(m_v5z, FLOAT21_SIZE); in.read(m_v6x, FLOAT21_SIZE); in.read(m_v6y, FLOAT21_SIZE); in.read(m_v6z, FLOAT21_SIZE); in.read(m_v7x, FLOAT21_SIZE); in.read(m_v7y, FLOAT21_SIZE); in.read(m_v7z, FLOAT21_SIZE); in.read(m_v8x, FLOAT21_SIZE); in.read(m_v8y, FLOAT21_SIZE); in.read(m_v8z, FLOAT21_SIZE); in.read(m_grpx, FLOAT21_SIZE); in.read(m_grpy, FLOAT21_SIZE); in.read(m_grpz, FLOAT21_SIZE); in.read(m_fullr, FULL_SIZE); in.read(m_fullc, FULL_SIZE); in.read(m_minr, MIN_SIZE); in.read(m_maxr, MAX_SIZE); in.read(m_minc, MIN_SIZE); in.read(m_maxc, MAX_SIZE); in.read(m_ie0, FLOAT21_SIZE); in.read(m_ier, FLOAT21_SIZE); in.read(m_iec, FLOAT21_SIZE); in.read(m_ierr, FLOAT21_SIZE); in.read(m_ierc, FLOAT21_SIZE); in.read(m_iecc, FLOAT21_SIZE); in.read(m_ia0, FLOAT21_SIZE); in.read(m_iar, FLOAT21_SIZE); in.read(m_iac, FLOAT21_SIZE); in.read(m_iarr, FLOAT21_SIZE); in.read(m_iarc, FLOAT21_SIZE); in.read(m_iacc, FLOAT21_SIZE); in.read(m_spx, FLOAT21_SIZE); in.read(m_svx, FLOAT21_SIZE); in.read(m_sax, FLOAT21_SIZE); in.read(m_spy, FLOAT21_SIZE); in.read(m_svy, FLOAT21_SIZE); in.read(m_say, FLOAT21_SIZE); in.read(m_spz, FLOAT21_SIZE); in.read(m_svz, FLOAT21_SIZE); in.read(m_saz, FLOAT21_SIZE); } void ossimNitfRsmidaTag::writeStream(std::ostream& out) { out.write(m_iid, IID_SIZE); out.write(m_edition, EDITION_SIZE); out.write(m_isid, ISID_SIZE); out.write(m_sid, SID_SIZE); out.write(m_stid, STID_SIZE); out.write(m_year, YEAR_SIZE); out.write(m_month, MONTH_SIZE); out.write(m_day, DAY_SIZE); out.write(m_hour, HOUR_SIZE); out.write(m_minute, MINUTE_SIZE); out.write(m_second, SECOND_SIZE); out.write(m_nrg, NRG_SIZE); out.write(m_ncg, NCG_SIZE); out.write(m_trg, FLOAT21_SIZE); out.write(m_tcg, FLOAT21_SIZE); out.write(m_grndd, GRNDD_SIZE); out.write(m_xuor, FLOAT21_SIZE); out.write(m_yuor, FLOAT21_SIZE); out.write(m_zuor, FLOAT21_SIZE); out.write(m_xuxr, FLOAT21_SIZE); out.write(m_xuyr, FLOAT21_SIZE); out.write(m_xuzr, FLOAT21_SIZE); out.write(m_yuxr, FLOAT21_SIZE); out.write(m_yuyr, FLOAT21_SIZE); out.write(m_yuzr, FLOAT21_SIZE); out.write(m_zuxr, FLOAT21_SIZE); out.write(m_zuyr, FLOAT21_SIZE); out.write(m_zuzr, FLOAT21_SIZE); out.write(m_v1x, FLOAT21_SIZE); out.write(m_v1y, FLOAT21_SIZE); out.write(m_v1z, FLOAT21_SIZE); out.write(m_v2x, FLOAT21_SIZE); out.write(m_v2y, FLOAT21_SIZE); out.write(m_v2z, FLOAT21_SIZE); out.write(m_v3x, FLOAT21_SIZE); out.write(m_v3y, FLOAT21_SIZE); out.write(m_v3z, FLOAT21_SIZE); out.write(m_v4x, FLOAT21_SIZE); out.write(m_v4y, FLOAT21_SIZE); out.write(m_v4z, FLOAT21_SIZE); out.write(m_v5x, FLOAT21_SIZE); out.write(m_v5y, FLOAT21_SIZE); out.write(m_v5z, FLOAT21_SIZE); out.write(m_v6x, FLOAT21_SIZE); out.write(m_v6y, FLOAT21_SIZE); out.write(m_v6z, FLOAT21_SIZE); out.write(m_v7x, FLOAT21_SIZE); out.write(m_v7y, FLOAT21_SIZE); out.write(m_v7z, FLOAT21_SIZE); out.write(m_v8x, FLOAT21_SIZE); out.write(m_v8y, FLOAT21_SIZE); out.write(m_v8z, FLOAT21_SIZE); out.write(m_grpx, FLOAT21_SIZE); out.write(m_grpy, FLOAT21_SIZE); out.write(m_grpz, FLOAT21_SIZE); out.write(m_fullr, FULL_SIZE); out.write(m_fullc, FULL_SIZE); out.write(m_minr, MIN_SIZE); out.write(m_maxr, MAX_SIZE); out.write(m_minc, MIN_SIZE); out.write(m_maxc, MAX_SIZE); out.write(m_ie0, FLOAT21_SIZE); out.write(m_ier, FLOAT21_SIZE); out.write(m_iec, FLOAT21_SIZE); out.write(m_ierr, FLOAT21_SIZE); out.write(m_ierc, FLOAT21_SIZE); out.write(m_iecc, FLOAT21_SIZE); out.write(m_ia0, FLOAT21_SIZE); out.write(m_iar, FLOAT21_SIZE); out.write(m_iac, FLOAT21_SIZE); out.write(m_iarr, FLOAT21_SIZE); out.write(m_iarc, FLOAT21_SIZE); out.write(m_iacc, FLOAT21_SIZE); out.write(m_spx, FLOAT21_SIZE); out.write(m_svx, FLOAT21_SIZE); out.write(m_sax, FLOAT21_SIZE); out.write(m_spy, FLOAT21_SIZE); out.write(m_svy, FLOAT21_SIZE); out.write(m_say, FLOAT21_SIZE); out.write(m_spz, FLOAT21_SIZE); out.write(m_svz, FLOAT21_SIZE); out.write(m_saz, FLOAT21_SIZE); } std::ostream& ossimNitfRsmidaTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "IID:" << m_iid << "\n" << pfx << std::setw(24) << "EDITION:" << m_edition << "\n" << pfx << std::setw(24) << "ISID:" << m_isid << "\n" << pfx << std::setw(24) << "SID:" << m_sid << "\n" << pfx << std::setw(24) << "STID:" << m_stid << "\n" << pfx << std::setw(24) << "YEAR:" << m_year << "\n" << pfx << std::setw(24) << "MONTH:" << m_month << "\n" << pfx << std::setw(24) << "DAY:" << m_day << "\n" << pfx << std::setw(24) << "HOUR:" << m_hour << "\n" << pfx << std::setw(24) << "MINUTE:" << m_minute << "\n" << pfx << std::setw(24) << "SECOND:" << m_second << "\n" << pfx << std::setw(24) << "NRG:" << m_nrg << "\n" << pfx << std::setw(24) << "NCG:" << m_ncg << "\n" << pfx << std::setw(24) << "TRG:" << m_trg << "\n" << pfx << std::setw(24) << "TCG:" << m_tcg << "\n" << pfx << std::setw(24) << "GRNDD:" << m_grndd << "\n" << pfx << std::setw(24) << "XUOR:" << m_xuor << "\n" << pfx << std::setw(24) << "YUOR:" << m_yuor << "\n" << pfx << std::setw(24) << "ZUOR:" << m_zuor << "\n" << pfx << std::setw(24) << "XUXR:" << m_xuxr << "\n" << pfx << std::setw(24) << "XUYR:" << m_xuyr << "\n" << pfx << std::setw(24) << "XUZR:" << m_xuzr << "\n" << pfx << std::setw(24) << "YUXR:" << m_yuxr << "\n" << pfx << std::setw(24) << "YUYR:" << m_yuyr << "\n" << pfx << std::setw(24) << "YUZR:" << m_yuzr << "\n" << pfx << std::setw(24) << "ZUXR:" << m_zuxr << "\n" << pfx << std::setw(24) << "ZUYR:" << m_zuyr << "\n" << pfx << std::setw(24) << "ZUZR:" << m_zuzr << "\n" << pfx << std::setw(24) << "V1X:" << m_v1x << "\n" << pfx << std::setw(24) << "V1Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V1Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V2X:" << m_v1x << "\n" << pfx << std::setw(24) << "V2Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V2Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V3X:" << m_v1x << "\n" << pfx << std::setw(24) << "V3Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V3Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V4X:" << m_v1x << "\n" << pfx << std::setw(24) << "V4Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V4Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V5X:" << m_v1x << "\n" << pfx << std::setw(24) << "V5Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V5Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V6X:" << m_v1x << "\n" << pfx << std::setw(24) << "V6Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V6Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V7X:" << m_v1x << "\n" << pfx << std::setw(24) << "V7Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V7Z:" << m_v1x << "\n" << pfx << std::setw(24) << "V8X:" << m_v1x << "\n" << pfx << std::setw(24) << "V8Y:" << m_v1x << "\n" << pfx << std::setw(24) << "V8Z:" << m_v1x << "\n" << pfx << std::setw(24) << "GRPX:" << m_grpx << "\n" << pfx << std::setw(24) << "GRPY:" << m_grpy << "\n" << pfx << std::setw(24) << "GRPZ:" << m_grpz << "\n" << pfx << std::setw(24) << "FULLR:" << m_fullr << "\n" << pfx << std::setw(24) << "FULLC:" << m_fullc << "\n" << pfx << std::setw(24) << "MINR:" << m_minr << "\n" << pfx << std::setw(24) << "MAXR:" << m_maxr << "\n" << pfx << std::setw(24) << "MINC:" << m_minc << "\n" << pfx << std::setw(24) << "MAXC:" << m_maxc << "\n" << pfx << std::setw(24) << "IE0:" << m_ie0 << "\n" << pfx << std::setw(24) << "IER:" << m_ier << "\n" << pfx << std::setw(24) << "IEC:" << m_iec << "\n" << pfx << std::setw(24) << "IERR:" << m_ierr << "\n" << pfx << std::setw(24) << "IERC:" << m_ierc << "\n" << pfx << std::setw(24) << "IECC:" << m_iecc << "\n" << pfx << std::setw(24) << "IA0:" << m_ia0 << "\n" << pfx << std::setw(24) << "IAR:" << m_iar << "\n" << pfx << std::setw(24) << "IAC:" << m_iac << "\n" << pfx << std::setw(24) << "IARR:" << m_iarr << "\n" << pfx << std::setw(24) << "IARC:" << m_iarc << "\n" << pfx << std::setw(24) << "IACC:" << m_iacc << "\n" << pfx << std::setw(24) << "SPX:" << m_spx << "\n" << pfx << std::setw(24) << "SVX:" << m_svx << "\n" << pfx << std::setw(24) << "SAX:" << m_sax << "\n" << pfx << std::setw(24) << "SPY:" << m_spy << "\n" << pfx << std::setw(24) << "SVY:" << m_svy << "\n" << pfx << std::setw(24) << "SAY:" << m_say << "\n" << pfx << std::setw(24) << "SPZ:" << m_spz << "\n" << pfx << std::setw(24) << "SVZ:" << m_svz << "\n" << pfx << std::setw(24) << "SAZ:" << m_saz << "\n"; return out; } void ossimNitfRsmidaTag::clearFields() { memset(m_iid,' ', IID_SIZE); memset(m_edition, ' ', EDITION_SIZE); memset(m_isid, ' ', ISID_SIZE); memset(m_sid, ' ', SID_SIZE); memset(m_stid, ' ', STID_SIZE); memset(m_year, ' ', YEAR_SIZE); memset(m_month, ' ', MONTH_SIZE); memset(m_day, ' ', DAY_SIZE); memset(m_hour,' ', HOUR_SIZE); memset(m_minute, ' ', MINUTE_SIZE); memset(m_second, ' ', SECOND_SIZE); memset(m_nrg, ' ', NRG_SIZE); memset(m_ncg, ' ', NCG_SIZE); memset(m_trg, ' ', FLOAT21_SIZE); memset(m_tcg, ' ', FLOAT21_SIZE); memset(m_grndd, ' ', GRNDD_SIZE); memset(m_xuor, ' ', FLOAT21_SIZE); memset(m_yuor, ' ', FLOAT21_SIZE); memset(m_zuor, ' ', FLOAT21_SIZE); memset(m_xuxr, ' ', FLOAT21_SIZE); memset(m_xuyr, ' ', FLOAT21_SIZE); memset(m_xuzr, ' ', FLOAT21_SIZE); memset(m_yuxr, ' ', FLOAT21_SIZE); memset(m_yuyr, ' ', FLOAT21_SIZE); memset(m_yuzr, ' ', FLOAT21_SIZE); memset(m_zuxr, ' ', FLOAT21_SIZE); memset(m_zuyr, ' ', FLOAT21_SIZE); memset(m_zuzr, ' ', FLOAT21_SIZE); memset(m_v1x, ' ', FLOAT21_SIZE); memset(m_v1y, ' ', FLOAT21_SIZE); memset(m_v1z, ' ', FLOAT21_SIZE); memset(m_v2x, ' ', FLOAT21_SIZE); memset(m_v2y, ' ', FLOAT21_SIZE); memset(m_v2z, ' ', FLOAT21_SIZE); memset(m_v3x, ' ', FLOAT21_SIZE); memset(m_v3y, ' ', FLOAT21_SIZE); memset(m_v3z, ' ', FLOAT21_SIZE); memset(m_v4x, ' ', FLOAT21_SIZE); memset(m_v4y, ' ', FLOAT21_SIZE); memset(m_v4z, ' ', FLOAT21_SIZE); memset(m_v5x, ' ', FLOAT21_SIZE); memset(m_v5y, ' ', FLOAT21_SIZE); memset(m_v5z, ' ', FLOAT21_SIZE); memset(m_v6x, ' ', FLOAT21_SIZE); memset(m_v6y, ' ', FLOAT21_SIZE); memset(m_v6z, ' ', FLOAT21_SIZE); memset(m_v7x, ' ', FLOAT21_SIZE); memset(m_v7y, ' ', FLOAT21_SIZE); memset(m_v7z, ' ', FLOAT21_SIZE); memset(m_v8x, ' ', FLOAT21_SIZE); memset(m_v8y, ' ', FLOAT21_SIZE); memset(m_v8z, ' ', FLOAT21_SIZE); memset(m_grpx, ' ', FLOAT21_SIZE); memset(m_grpy, ' ', FLOAT21_SIZE); memset(m_grpz, ' ', FLOAT21_SIZE); memset(m_fullr, ' ', FULL_SIZE); memset(m_fullc, ' ', FULL_SIZE); memset(m_minr, ' ', MIN_SIZE); memset(m_maxr, ' ', MAX_SIZE); memset(m_minc, ' ', MIN_SIZE); memset(m_maxc, ' ', MAX_SIZE); memset(m_ie0, ' ', FLOAT21_SIZE); memset(m_ier, ' ', FLOAT21_SIZE); memset(m_iec, ' ', FLOAT21_SIZE); memset(m_ierr, ' ', FLOAT21_SIZE); memset(m_ierc, ' ', FLOAT21_SIZE); memset(m_iecc, ' ', FLOAT21_SIZE); memset(m_ia0, ' ', FLOAT21_SIZE); memset(m_iar, ' ', FLOAT21_SIZE); memset(m_iac, ' ', FLOAT21_SIZE); memset(m_iarr, ' ', FLOAT21_SIZE); memset(m_iarc, ' ', FLOAT21_SIZE); memset(m_iacc, ' ', FLOAT21_SIZE); memset(m_spx, ' ', FLOAT21_SIZE); memset(m_svx, ' ', FLOAT21_SIZE); memset(m_sax, ' ', FLOAT21_SIZE); memset(m_spy, ' ', FLOAT21_SIZE); memset(m_svy, ' ', FLOAT21_SIZE); memset(m_say, ' ', FLOAT21_SIZE); memset(m_spz, ' ', FLOAT21_SIZE); memset(m_svz, ' ', FLOAT21_SIZE); memset(m_saz, ' ', FLOAT21_SIZE); m_iid[IID_SIZE] = '\0'; m_edition[EDITION_SIZE] = '\0'; m_isid[ISID_SIZE] = '\0'; m_sid[SID_SIZE] = '\0'; m_stid[STID_SIZE] = '\0'; m_year[YEAR_SIZE] = '\0'; m_month[MONTH_SIZE] = '\0'; m_day[DAY_SIZE] = '\0'; m_hour[HOUR_SIZE] = '\0'; m_minute[MINUTE_SIZE] = '\0'; m_second[SECOND_SIZE] = '\0'; m_nrg[NRG_SIZE] = '\0'; m_ncg[NCG_SIZE] = '\0'; m_trg[FLOAT21_SIZE] = '\0'; m_tcg[FLOAT21_SIZE] = '\0'; m_grndd[GRNDD_SIZE] = '\0'; m_xuor[FLOAT21_SIZE] = '\0'; m_yuor[FLOAT21_SIZE] = '\0'; m_zuor[FLOAT21_SIZE] = '\0'; m_xuxr[FLOAT21_SIZE] = '\0'; m_xuyr[FLOAT21_SIZE] = '\0'; m_xuzr[FLOAT21_SIZE] = '\0'; m_yuxr[FLOAT21_SIZE] = '\0'; m_yuyr[FLOAT21_SIZE] = '\0'; m_yuzr[FLOAT21_SIZE] = '\0'; m_zuxr[FLOAT21_SIZE] = '\0'; m_zuyr[FLOAT21_SIZE] = '\0'; m_zuzr[FLOAT21_SIZE] = '\0'; m_v1x[FLOAT21_SIZE] = '\0'; m_v1y[FLOAT21_SIZE] = '\0'; m_v1z[FLOAT21_SIZE] = '\0'; m_v2x[FLOAT21_SIZE] = '\0'; m_v2y[FLOAT21_SIZE] = '\0'; m_v2z[FLOAT21_SIZE] = '\0'; m_v3x[FLOAT21_SIZE] = '\0'; m_v3y[FLOAT21_SIZE] = '\0'; m_v3z[FLOAT21_SIZE] = '\0'; m_v4x[FLOAT21_SIZE] = '\0'; m_v4y[FLOAT21_SIZE] = '\0'; m_v4z[FLOAT21_SIZE] = '\0'; m_v5x[FLOAT21_SIZE] = '\0'; m_v5y[FLOAT21_SIZE] = '\0'; m_v5z[FLOAT21_SIZE] = '\0'; m_v6x[FLOAT21_SIZE] = '\0'; m_v6y[FLOAT21_SIZE] = '\0'; m_v6z[FLOAT21_SIZE] = '\0'; m_v7x[FLOAT21_SIZE] = '\0'; m_v7y[FLOAT21_SIZE] = '\0'; m_v7z[FLOAT21_SIZE] = '\0'; m_v8x[FLOAT21_SIZE] = '\0'; m_v8y[FLOAT21_SIZE] = '\0'; m_v8z[FLOAT21_SIZE] = '\0'; m_grpx[FLOAT21_SIZE] = '\0'; m_grpy[FLOAT21_SIZE] = '\0'; m_grpz[FLOAT21_SIZE] = '\0'; m_fullr[FULL_SIZE] = '\0'; m_fullc[FULL_SIZE] = '\0'; m_minr[MIN_SIZE] = '\0'; m_maxr[MAX_SIZE] = '\0'; m_minc[MIN_SIZE] = '\0'; m_maxc[MAX_SIZE] = '\0'; m_ie0[FLOAT21_SIZE] = '\0'; m_ier[FLOAT21_SIZE] = '\0'; m_iec[FLOAT21_SIZE] = '\0'; m_ierr[FLOAT21_SIZE] = '\0'; m_ierc[FLOAT21_SIZE] = '\0'; m_iecc[FLOAT21_SIZE] = '\0'; m_ia0[FLOAT21_SIZE] = '\0'; m_iar[FLOAT21_SIZE] = '\0'; m_iac[FLOAT21_SIZE] = '\0'; m_iarr[FLOAT21_SIZE] = '\0'; m_iarc[FLOAT21_SIZE] = '\0'; m_iacc[FLOAT21_SIZE] = '\0'; m_spx[FLOAT21_SIZE] = '\0'; m_svx[FLOAT21_SIZE] = '\0'; m_sax[FLOAT21_SIZE] = '\0'; m_spy[FLOAT21_SIZE] = '\0'; m_svy[FLOAT21_SIZE] = '\0'; m_say[FLOAT21_SIZE] = '\0'; m_spz[FLOAT21_SIZE] = '\0'; m_svz[FLOAT21_SIZE] = '\0'; m_saz[FLOAT21_SIZE] = '\0'; } ossimString ossimNitfRsmidaTag::getIid() const { return ossimString(m_iid); } ossimString ossimNitfRsmidaTag::getEdition() const { return ossimString(m_edition); } ossimString ossimNitfRsmidaTag::getIsid() const { return ossimString(m_isid); } ossimString ossimNitfRsmidaTag::getSid() const { return ossimString(m_sid); } ossimString ossimNitfRsmidaTag::getStid() const { return ossimString(m_stid); } ossimString ossimNitfRsmidaTag::getYear() const { return ossimString(m_year); } ossimString ossimNitfRsmidaTag::getMonth() const { return ossimString(m_month); } ossimString ossimNitfRsmidaTag::getDay() const { return ossimString(m_day); } ossimString ossimNitfRsmidaTag::getHour() const { return ossimString(m_hour); } ossimString ossimNitfRsmidaTag::getMinute() const { return ossimString(m_minute); } ossimString ossimNitfRsmidaTag::getSecond() const { return ossimString(m_second); } ossimString ossimNitfRsmidaTag::getNrg() const { return ossimString(m_nrg); } ossimString ossimNitfRsmidaTag::getNcg() const { return ossimString(m_ncg); } ossimString ossimNitfRsmidaTag::getTrg() const { return ossimString(m_trg); } ossimString ossimNitfRsmidaTag::getTcg() const { return ossimString(m_tcg); } ossimString ossimNitfRsmidaTag::getGrndd() const { return ossimString(m_grndd); } ossimString ossimNitfRsmidaTag::getXuor() const { return ossimString(m_xuor); } ossimString ossimNitfRsmidaTag::getYuor() const { return ossimString(m_yuor); } ossimString ossimNitfRsmidaTag::getZuor() const { return ossimString(m_zuor); } ossimString ossimNitfRsmidaTag::getXuxr() const { return ossimString(m_xuxr); } ossimString ossimNitfRsmidaTag::getXuyr() const { return ossimString(m_xuyr); } ossimString ossimNitfRsmidaTag::getXuzr() const { return ossimString(m_xuzr); } ossimString ossimNitfRsmidaTag::getYuxr() const { return ossimString(m_yuxr); } ossimString ossimNitfRsmidaTag::getYuyr() const { return ossimString(m_yuyr); } ossimString ossimNitfRsmidaTag::getYuzr() const { return ossimString(m_yuzr); } ossimString ossimNitfRsmidaTag::getZuxr() const { return ossimString(m_zuxr); } ossimString ossimNitfRsmidaTag::getZuyr() const { return ossimString(m_zuyr); } ossimString ossimNitfRsmidaTag::getZuzr() const { return ossimString(m_zuzr); } ossimString ossimNitfRsmidaTag::getV1x() const { return ossimString(m_v1x); } ossimString ossimNitfRsmidaTag::getV1y() const { return ossimString(m_v1y); } ossimString ossimNitfRsmidaTag::getV1z() const { return ossimString(m_v1z); } ossimString ossimNitfRsmidaTag::getV2x() const { return ossimString(m_v2x); } ossimString ossimNitfRsmidaTag::getV2y() const { return ossimString(m_v2y); } ossimString ossimNitfRsmidaTag::getV2z() const { return ossimString(m_v2z); } ossimString ossimNitfRsmidaTag::getV3x() const { return ossimString(m_v3x); } ossimString ossimNitfRsmidaTag::getV3y() const { return ossimString(m_v3y); } ossimString ossimNitfRsmidaTag::getV3z() const { return ossimString(m_v3z); } ossimString ossimNitfRsmidaTag::getV4x() const { return ossimString(m_v4x); } ossimString ossimNitfRsmidaTag::getV4y() const { return ossimString(m_v4y); } ossimString ossimNitfRsmidaTag::getV4z() const { return ossimString(m_v4z); } ossimString ossimNitfRsmidaTag::getV5x() const { return ossimString(m_v5x); } ossimString ossimNitfRsmidaTag::getV5y() const { return ossimString(m_v5y); } ossimString ossimNitfRsmidaTag::getV5z() const { return ossimString(m_v5z); } ossimString ossimNitfRsmidaTag::getV6x() const { return ossimString(m_v6x); } ossimString ossimNitfRsmidaTag::getV6y() const { return ossimString(m_v6y); } ossimString ossimNitfRsmidaTag::getV6z() const { return ossimString(m_v6z); } ossimString ossimNitfRsmidaTag::getV7x() const { return ossimString(m_v7x); } ossimString ossimNitfRsmidaTag::getV7y() const { return ossimString(m_v7y); } ossimString ossimNitfRsmidaTag::getV7z() const { return ossimString(m_v7z); } ossimString ossimNitfRsmidaTag::getV8x() const { return ossimString(m_v8x); } ossimString ossimNitfRsmidaTag::getV8y() const { return ossimString(m_v8y); } ossimString ossimNitfRsmidaTag::getV8z() const { return ossimString(m_v8z); } ossimString ossimNitfRsmidaTag::getGrpx() const { return ossimString(m_grpx); } ossimString ossimNitfRsmidaTag::getGrpy() const { return ossimString(m_grpy); } ossimString ossimNitfRsmidaTag::getGrpz() const { return ossimString(m_grpz); } ossimString ossimNitfRsmidaTag::getFullr() const { return ossimString(m_fullr); } ossimString ossimNitfRsmidaTag::getFullc() const { return ossimString(m_fullc); } ossimString ossimNitfRsmidaTag::getMinr() const { return ossimString(m_minr); } ossimString ossimNitfRsmidaTag::getMaxr() const { return ossimString(m_maxr); } ossimString ossimNitfRsmidaTag::getMinc() const { return ossimString(m_minc); } ossimString ossimNitfRsmidaTag::getMaxc() const { return ossimString(m_maxc); } ossimString ossimNitfRsmidaTag::getIe0() const { return ossimString(m_ie0); } ossimString ossimNitfRsmidaTag::getIer() const { return ossimString(m_ier); } ossimString ossimNitfRsmidaTag::getIec() const { return ossimString(m_iec); } ossimString ossimNitfRsmidaTag::getIerr() const { return ossimString(m_ierr); } ossimString ossimNitfRsmidaTag::getIerc() const { return ossimString(m_ierc); } ossimString ossimNitfRsmidaTag::getIecc() const { return ossimString(m_iecc); } ossimString ossimNitfRsmidaTag::getIa0() const { return ossimString(m_ia0); } ossimString ossimNitfRsmidaTag::getIar() const { return ossimString(m_iar); } ossimString ossimNitfRsmidaTag::getIac() const { return ossimString(m_iac); } ossimString ossimNitfRsmidaTag::getIarr() const { return ossimString(m_iarr); } ossimString ossimNitfRsmidaTag::getIarc() const { return ossimString(m_iarc); } ossimString ossimNitfRsmidaTag::getIacc() const { return ossimString(m_iacc); } ossimString ossimNitfRsmidaTag::getSpx() const { return ossimString(m_spx); } ossimString ossimNitfRsmidaTag::getSvx() const { return ossimString(m_svx); } ossimString ossimNitfRsmidaTag::getSax() const { return ossimString(m_sax); } ossimString ossimNitfRsmidaTag::getSpy() const { return ossimString(m_spy); } ossimString ossimNitfRsmidaTag::getSvy() const { return ossimString(m_svy); } ossimString ossimNitfRsmidaTag::getSay() const { return ossimString(m_say); } ossimString ossimNitfRsmidaTag::getSpz() const { return ossimString(m_spz); } ossimString ossimNitfRsmidaTag::getSvz() const { return ossimString(m_svz); } ossimString ossimNitfRsmidaTag::getSaz() const { return ossimString(m_saz); } ossim-Miami-2.9.1/src/support_data/ossimNitfRsmpcaTag.cpp000066400000000000000000000365031352751253100234770ustar00rootroot00000000000000//--- // File: ossimNitfRsmpcaTag.cpp //--- #include #include #include #include #include #include #include using namespace std; static const ossimTrace traceDebug(ossimString("ossimNitfRsmpcaTag:debug")); static const ossimString CNPCF_KW = "CNPCF"; static const ossimString CDPCF_KW = "CDPCF"; static const ossimString RNPCF_KW = "RNPCF"; static const ossimString RDPCF_KW = "RDPCF"; static const ossimString POLYFILL = " "; RTTI_DEF1(ossimNitfRsmpcaTag, "ossimNitfRsmpcaTag", ossimNitfRegisteredTag); ossimNitfRsmpcaTag::ossimNitfRsmpcaTag() : ossimNitfRegisteredTag(std::string("RSMPCA"), 0), m_iid(), m_edition(), m_rsn(), m_csn(), m_rfep(), m_cfep(), m_rnrmo(), m_cnrmo(), m_xnrmo(), m_ynrmo(), m_znrmo(), m_rnrmsf(), m_cnrmsf(), m_xnrmsf(), m_ynrmsf(), m_znrmsf(), m_rnpwrx(), m_rnpwry(), m_rnpwrz(), m_rntrms(), m_rnpcf(), m_rdpwrx(), m_rdpwry(), m_rdpwrz(), m_rdtrms(), m_rdpcf(), m_cnpwrx(), m_cnpwry(), m_cnpwrz(), m_cntrms(), m_cnpcf(), m_cdpwrx(), m_cdpwry(), m_cdpwrz(), m_cdtrms(), m_cdpcf(), m_rowNumNumTerms(0), m_rowDenNumTerms(0), m_colNumNumTerms(0), m_colDenNumTerms(0) { } void ossimNitfRsmpcaTag::parseStream(std::istream& in) { clearFields(); in.read(m_iid, IID_SIZE); in.read(m_edition, EDITION_SIZE); in.read(m_rsn, RSN_SIZE); in.read(m_csn, CSN_SIZE); in.read(m_rfep, FLOAT21_SIZE); in.read(m_cfep, FLOAT21_SIZE); in.read(m_rnrmo, FLOAT21_SIZE); in.read(m_cnrmo, FLOAT21_SIZE); in.read(m_xnrmo, FLOAT21_SIZE); in.read(m_ynrmo, FLOAT21_SIZE); in.read(m_znrmo, FLOAT21_SIZE); in.read(m_rnrmsf, FLOAT21_SIZE); in.read(m_cnrmsf, FLOAT21_SIZE); in.read(m_xnrmsf, FLOAT21_SIZE); in.read(m_ynrmsf, FLOAT21_SIZE); in.read(m_znrmsf, FLOAT21_SIZE); in.read(m_rnpwrx, MAXPOWER_SIZE); in.read(m_rnpwry, MAXPOWER_SIZE); in.read(m_rnpwrz, MAXPOWER_SIZE); in.read(m_rntrms, NUMTERMS_SIZE); ossim_uint32 idx = 0; m_rowNumNumTerms = ossimString(m_rntrms).toUInt32(); m_rnpcf.resize(m_rowNumNumTerms); char temp1[FLOAT21_SIZE+1]; temp1[FLOAT21_SIZE] = '\0'; for(idx = 0; idx < m_rowNumNumTerms; ++idx) { in.read(temp1, FLOAT21_SIZE); m_rnpcf[idx] = POLYFILL; m_rnpcf[idx] = temp1; } in.read(m_rdpwrx, MAXPOWER_SIZE); in.read(m_rdpwry, MAXPOWER_SIZE); in.read(m_rdpwrz, MAXPOWER_SIZE); in.read(m_rdtrms, NUMTERMS_SIZE); m_rowDenNumTerms = ossimString(m_rdtrms).toUInt32(); m_rdpcf.resize(m_rowDenNumTerms); char temp2[FLOAT21_SIZE+1]; temp2[FLOAT21_SIZE] = '\0'; for(idx = 0; idx < m_rowDenNumTerms; ++idx) { in.read(temp2, FLOAT21_SIZE); m_rdpcf[idx] = POLYFILL; m_rdpcf[idx] = temp2; } in.read(m_cnpwrx, MAXPOWER_SIZE); in.read(m_cnpwry, MAXPOWER_SIZE); in.read(m_cnpwrz, MAXPOWER_SIZE); in.read(m_cntrms, NUMTERMS_SIZE); m_colNumNumTerms = ossimString(m_cntrms).toUInt32(); m_cnpcf.resize(m_colNumNumTerms); char temp3[FLOAT21_SIZE+1]; temp3[FLOAT21_SIZE] = '\0'; for(idx = 0; idx < m_colNumNumTerms; ++idx) { in.read(temp3, FLOAT21_SIZE); m_cnpcf[idx] = POLYFILL; m_cnpcf[idx] = temp3; } in.read(m_cdpwrx, MAXPOWER_SIZE); in.read(m_cdpwry, MAXPOWER_SIZE); in.read(m_cdpwrz, MAXPOWER_SIZE); in.read(m_cdtrms, NUMTERMS_SIZE); m_colDenNumTerms = ossimString(m_cdtrms).toUInt32(); m_cdpcf.resize(m_colDenNumTerms); char temp4[FLOAT21_SIZE+1]; temp4[FLOAT21_SIZE] = '\0'; for(idx = 0; idx < m_colDenNumTerms; ++idx) { in.read(temp4, FLOAT21_SIZE); m_cdpcf[idx] = POLYFILL; m_cdpcf[idx] = temp4; } } void ossimNitfRsmpcaTag::writeStream(std::ostream& out) { out.write(m_iid, IID_SIZE); out.write(m_edition, EDITION_SIZE); out.write(m_rsn, RSN_SIZE); out.write(m_csn, CSN_SIZE); out.write(m_rfep, FLOAT21_SIZE); out.write(m_cfep, FLOAT21_SIZE); out.write(m_rnrmo, FLOAT21_SIZE); out.write(m_cnrmo, FLOAT21_SIZE); out.write(m_xnrmo, FLOAT21_SIZE); out.write(m_ynrmo, FLOAT21_SIZE); out.write(m_znrmo, FLOAT21_SIZE); out.write(m_rnrmsf, FLOAT21_SIZE); out.write(m_cnrmsf, FLOAT21_SIZE); out.write(m_xnrmsf, FLOAT21_SIZE); out.write(m_ynrmsf, FLOAT21_SIZE); out.write(m_znrmsf, FLOAT21_SIZE); out.write(m_rnpwrx, MAXPOWER_SIZE); out.write(m_rnpwry, MAXPOWER_SIZE); out.write(m_rnpwrz, MAXPOWER_SIZE); out.write(m_rntrms, NUMTERMS_SIZE); ossim_uint32 idx = 0; for(idx = 0; idx < m_rowNumNumTerms; ++idx) { out.write(m_rnpcf[idx], FLOAT21_SIZE); } out.write(m_rdpwrx, MAXPOWER_SIZE); out.write(m_rdpwry, MAXPOWER_SIZE); out.write(m_rdpwrz, MAXPOWER_SIZE); out.write(m_rdtrms, NUMTERMS_SIZE); for(idx = 0; idx < m_rowDenNumTerms; ++idx) { out.write(m_rdpcf[idx], FLOAT21_SIZE); } out.write(m_cnpwrx, MAXPOWER_SIZE); out.write(m_cnpwry, MAXPOWER_SIZE); out.write(m_cnpwrz, MAXPOWER_SIZE); out.write(m_cntrms, NUMTERMS_SIZE); for(idx = 0; idx < m_colNumNumTerms; ++idx) { out.write(m_cnpcf[idx], FLOAT21_SIZE); } out.write(m_cdpwrx, MAXPOWER_SIZE); out.write(m_cdpwry, MAXPOWER_SIZE); out.write(m_cdpwrz, MAXPOWER_SIZE); out.write(m_cdtrms, NUMTERMS_SIZE); for(idx = 0; idx < m_colDenNumTerms; ++idx) { out.write(m_cdpcf[idx], FLOAT21_SIZE); } } void ossimNitfRsmpcaTag::clearFields() { memset(m_iid, ' ', IID_SIZE); memset(m_edition, ' ', EDITION_SIZE); memset(m_rsn, ' ', RSN_SIZE); memset(m_csn, ' ', CSN_SIZE); memset(m_rfep, ' ', FLOAT21_SIZE); memset(m_cfep, ' ', FLOAT21_SIZE); memset(m_rnrmo, ' ', FLOAT21_SIZE); memset(m_cnrmo, ' ', FLOAT21_SIZE); memset(m_xnrmo, ' ', FLOAT21_SIZE); memset(m_ynrmo, ' ', FLOAT21_SIZE); memset(m_znrmo, ' ', FLOAT21_SIZE); memset(m_rnrmsf, ' ', FLOAT21_SIZE); memset(m_cnrmsf, ' ', FLOAT21_SIZE); memset(m_xnrmsf, ' ', FLOAT21_SIZE); memset(m_ynrmsf, ' ', FLOAT21_SIZE); memset(m_znrmsf, ' ', FLOAT21_SIZE); memset(m_rnpwrx, ' ', MAXPOWER_SIZE); memset(m_rnpwry, ' ', MAXPOWER_SIZE); memset(m_rnpwrz, ' ', MAXPOWER_SIZE); memset(m_rntrms, ' ', NUMTERMS_SIZE); memset(m_rdpwrx, ' ', MAXPOWER_SIZE); memset(m_rdpwry, ' ', MAXPOWER_SIZE); memset(m_rdpwrz, ' ', MAXPOWER_SIZE); memset(m_rdtrms, ' ', NUMTERMS_SIZE); memset(m_cnpwrx, ' ', MAXPOWER_SIZE); memset(m_cnpwry, ' ', MAXPOWER_SIZE); memset(m_cnpwrz, ' ', MAXPOWER_SIZE); memset(m_cntrms, ' ', NUMTERMS_SIZE); memset(m_cdpwrx, ' ', MAXPOWER_SIZE); memset(m_cdpwry, ' ', MAXPOWER_SIZE); memset(m_cdpwrz, ' ', MAXPOWER_SIZE); memset(m_cdtrms, ' ', NUMTERMS_SIZE); m_iid[IID_SIZE] = '\0'; m_edition[EDITION_SIZE] = '\0'; m_rsn[RSN_SIZE] = '\0'; m_csn[CSN_SIZE] = '\0'; m_rfep[FLOAT21_SIZE] = '\0'; m_cfep[FLOAT21_SIZE] = '\0'; m_rnrmo[FLOAT21_SIZE] = '\0'; m_cnrmo[FLOAT21_SIZE] = '\0'; m_xnrmo[FLOAT21_SIZE] = '\0'; m_ynrmo[FLOAT21_SIZE] = '\0'; m_znrmo[FLOAT21_SIZE] = '\0'; m_rnrmsf[FLOAT21_SIZE] = '\0'; m_cnrmsf[FLOAT21_SIZE] = '\0'; m_xnrmsf[FLOAT21_SIZE] = '\0'; m_ynrmsf[FLOAT21_SIZE] = '\0'; m_znrmsf[FLOAT21_SIZE] = '\0'; m_rnpwrx[MAXPOWER_SIZE] = '\0'; m_rnpwry[MAXPOWER_SIZE] = '\0'; m_rnpwrz[MAXPOWER_SIZE] = '\0'; m_rntrms[NUMTERMS_SIZE] = '\0'; m_rdpwrx[MAXPOWER_SIZE] = '\0'; m_rdpwry[MAXPOWER_SIZE] = '\0'; m_rdpwrz[MAXPOWER_SIZE] = '\0'; m_rdtrms[NUMTERMS_SIZE] = '\0'; m_cnpwrx[MAXPOWER_SIZE] = '\0'; m_cnpwry[MAXPOWER_SIZE] = '\0'; m_cnpwrz[MAXPOWER_SIZE] = '\0'; m_cntrms[NUMTERMS_SIZE] = '\0'; m_cdpwrx[MAXPOWER_SIZE] = '\0'; m_cdpwry[MAXPOWER_SIZE] = '\0'; m_cdpwrz[MAXPOWER_SIZE] = '\0'; m_cdtrms[NUMTERMS_SIZE] = '\0'; } std::ostream& ossimNitfRsmpcaTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getSizeInBytes() << "\n" << pfx << std::setw(24) << "IID:" << m_iid << "\n" << pfx << std::setw(24) << "EDITION:" << m_edition << "\n" << pfx << std::setw(24) << "RSN:" << m_rsn << "\n" << pfx << std::setw(24) << "CSN:" << m_csn << "\n" << pfx << std::setw(24) << "RFEP:" << m_rfep << "\n" << pfx << std::setw(24) << "CFEP:" << m_cfep << "\n" << pfx << std::setw(24) << "RNRMO:" << m_rnrmo << "\n" << pfx << std::setw(24) << "CNRMO:" << m_cnrmo << "\n" << pfx << std::setw(24) << "XNRMO:" << m_xnrmo << "\n" << pfx << std::setw(24) << "YNRMO:" << m_ynrmo << "\n" << pfx << std::setw(24) << "ZNRMO:" << m_znrmo << "\n" << pfx << std::setw(24) << "RNRMSF:" << m_rnrmsf << "\n" << pfx << std::setw(24) << "CNRMSF:" << m_cnrmsf << "\n" << pfx << std::setw(24) << "XNRMSF:" << m_xnrmsf << "\n" << pfx << std::setw(24) << "YNRMSF:" << m_ynrmsf << "\n" << pfx << std::setw(24) << "ZNRMSF:" << m_znrmsf << "\n" << pfx << std::setw(24) << "RNPWRX:" << m_rnpwrx << "\n" << pfx << std::setw(24) << "RNPWRY:" << m_rnpwry << "\n" << pfx << std::setw(24) << "RNPWRZ:" << m_rnpwrz << "\n" << pfx << std::setw(24) << "RNTRMS:" << m_rntrms << "\n" << pfx << std::setw(24) << "RDPWRX:" << m_rdpwrx << "\n" << pfx << std::setw(24) << "RDPWRY:" << m_rdpwry << "\n" << pfx << std::setw(24) << "RDPWRZ:" << m_rdpwrz << "\n" << pfx << std::setw(24) << "RDTRMS:" << m_rdtrms << "\n" << pfx << std::setw(24) << "CNPWRX:" << m_rnpwrx << "\n" << pfx << std::setw(24) << "CNPWRY:" << m_rnpwry << "\n" << pfx << std::setw(24) << "CNPWRZ:" << m_rnpwrz << "\n" << pfx << std::setw(24) << "CNTRMS:" << m_rntrms << "\n" << pfx << std::setw(24) << "CDPWRX:" << m_rdpwrx << "\n" << pfx << std::setw(24) << "CDPWRY:" << m_rdpwry << "\n" << pfx << std::setw(24) << "CDPWRZ:" << m_rdpwrz << "\n" << pfx << std::setw(24) << "CDTRMS:" << m_rdtrms << "\n"; ossim_uint32 i; ossimString s; for (i=0; i #include #include using namespace std; RTTI_DEF1(ossimNitfRsmpiaTag, "ossimNitfRsmpiaTag", ossimNitfRegisteredTag); ossimNitfRsmpiaTag::ossimNitfRsmpiaTag() : ossimNitfRegisteredTag(std::string("RSMPIA"), CEL_SIZE), m_iid(), m_edition(), m_r0(), m_rx(), m_ry(), m_rz(), m_rxx(), m_rxy(), m_rxz(), m_ryy(), m_ryz(), m_rzz(), m_c0(), m_cx(), m_cy(), m_cz(), m_cxx(), m_cxy(), m_cxz(), m_cyy(), m_cyz(), m_czz(), m_rnis(), m_cnis(), m_tnis(), m_rssiz(), m_cssiz() { clearFields(); } void ossimNitfRsmpiaTag::parseStream(std::istream& in) { in.read(m_iid, IID_SIZE); in.read(m_edition, EDITION_SIZE); in.read(m_r0, FLOAT21_SIZE); in.read(m_rx, FLOAT21_SIZE); in.read(m_ry, FLOAT21_SIZE); in.read(m_rz, FLOAT21_SIZE); in.read(m_rxx, FLOAT21_SIZE); in.read(m_rxy, FLOAT21_SIZE); in.read(m_rxz, FLOAT21_SIZE); in.read(m_ryy, FLOAT21_SIZE); in.read(m_ryz, FLOAT21_SIZE); in.read(m_rzz, FLOAT21_SIZE); in.read(m_c0, FLOAT21_SIZE); in.read(m_cx, FLOAT21_SIZE); in.read(m_cy, FLOAT21_SIZE); in.read(m_cz, FLOAT21_SIZE); in.read(m_cxx, FLOAT21_SIZE); in.read(m_cxy, FLOAT21_SIZE); in.read(m_cxz, FLOAT21_SIZE); in.read(m_cyy, FLOAT21_SIZE); in.read(m_cyz, FLOAT21_SIZE); in.read(m_czz, FLOAT21_SIZE); in.read(m_rnis, NIS_SIZE); in.read(m_cnis, NIS_SIZE); in.read(m_tnis, NIS_SIZE); in.read(m_rssiz, FLOAT21_SIZE); in.read(m_cssiz, FLOAT21_SIZE); } void ossimNitfRsmpiaTag::writeStream(std::ostream& out) { out.write(m_iid, IID_SIZE); out.write(m_edition, EDITION_SIZE); out.write(m_r0, FLOAT21_SIZE); out.write(m_rx, FLOAT21_SIZE); out.write(m_ry, FLOAT21_SIZE); out.write(m_rz, FLOAT21_SIZE); out.write(m_rxx, FLOAT21_SIZE); out.write(m_rxy, FLOAT21_SIZE); out.write(m_rxz, FLOAT21_SIZE); out.write(m_ryy, FLOAT21_SIZE); out.write(m_ryz, FLOAT21_SIZE); out.write(m_rzz, FLOAT21_SIZE); out.write(m_c0, FLOAT21_SIZE); out.write(m_cx, FLOAT21_SIZE); out.write(m_cy, FLOAT21_SIZE); out.write(m_cz, FLOAT21_SIZE); out.write(m_cxx, FLOAT21_SIZE); out.write(m_cxy, FLOAT21_SIZE); out.write(m_cxz, FLOAT21_SIZE); out.write(m_cyy, FLOAT21_SIZE); out.write(m_cyz, FLOAT21_SIZE); out.write(m_czz, FLOAT21_SIZE); out.write(m_rnis, NIS_SIZE); out.write(m_cnis, NIS_SIZE); out.write(m_tnis, NIS_SIZE); out.write(m_rssiz, FLOAT21_SIZE); out.write(m_cssiz, FLOAT21_SIZE); } std::ostream& ossimNitfRsmpiaTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "IID:" << m_iid << "\n" << pfx << std::setw(24) << "EDITION:" << m_edition << "\n" << pfx << std::setw(24) << "R0:" << m_r0 << "\n" << pfx << std::setw(24) << "RX:" << m_rx << "\n" << pfx << std::setw(24) << "RY:" << m_ry << "\n" << pfx << std::setw(24) << "RZ:" << m_rz << "\n" << pfx << std::setw(24) << "RXX:" << m_rxx << "\n" << pfx << std::setw(24) << "RXY:" << m_rxy << "\n" << pfx << std::setw(24) << "RXZ:" << m_rxz << "\n" << pfx << std::setw(24) << "RYY:" << m_ryy << "\n" << pfx << std::setw(24) << "RYZ:" << m_ryz << "\n" << pfx << std::setw(24) << "RZZ:" << m_rzz << "\n" << pfx << std::setw(24) << "C0:" << m_c0 << "\n" << pfx << std::setw(24) << "CX:" << m_cx << "\n" << pfx << std::setw(24) << "CY:" << m_cy << "\n" << pfx << std::setw(24) << "CZ:" << m_cz << "\n" << pfx << std::setw(24) << "CXX:" << m_cxx << "\n" << pfx << std::setw(24) << "CXY:" << m_cxy << "\n" << pfx << std::setw(24) << "CXZ:" << m_cxz << "\n" << pfx << std::setw(24) << "CYY:" << m_cyy << "\n" << pfx << std::setw(24) << "CYZ:" << m_cyz << "\n" << pfx << std::setw(24) << "CZZ:" << m_czz << "\n" << pfx << std::setw(24) << "RNIS:" << m_rnis << "\n" << pfx << std::setw(24) << "CNIS:" << m_cnis << "\n" << pfx << std::setw(24) << "TNIS:" << m_tnis << "\n" << pfx << std::setw(24) << "RSSIZ:" << m_rssiz << "\n" << pfx << std::setw(24) << "CSSIZ:" << m_cssiz << "\n"; return out; } void ossimNitfRsmpiaTag::clearFields() { memset(m_iid,' ', IID_SIZE); memset(m_edition, ' ', EDITION_SIZE); memset(m_r0, ' ', FLOAT21_SIZE); memset(m_rx, ' ', FLOAT21_SIZE); memset(m_ry, ' ', FLOAT21_SIZE); memset(m_rz, ' ', FLOAT21_SIZE); memset(m_rxx, ' ', FLOAT21_SIZE); memset(m_rxy, ' ', FLOAT21_SIZE); memset(m_rxz, ' ', FLOAT21_SIZE); memset(m_ryy, ' ', FLOAT21_SIZE); memset(m_ryz, ' ', FLOAT21_SIZE); memset(m_rzz, ' ', FLOAT21_SIZE); memset(m_c0, ' ', FLOAT21_SIZE); memset(m_cx, ' ', FLOAT21_SIZE); memset(m_cy, ' ', FLOAT21_SIZE); memset(m_cz, ' ', FLOAT21_SIZE); memset(m_cxx, ' ', FLOAT21_SIZE); memset(m_cxy, ' ', FLOAT21_SIZE); memset(m_cxz, ' ', FLOAT21_SIZE); memset(m_cyy, ' ', FLOAT21_SIZE); memset(m_cyz, ' ', FLOAT21_SIZE); memset(m_czz, ' ', FLOAT21_SIZE); memset(m_rnis, ' ', NIS_SIZE); memset(m_cnis, ' ', NIS_SIZE); memset(m_tnis, ' ', NIS_SIZE); memset(m_rssiz, ' ', FLOAT21_SIZE); memset(m_cssiz, ' ', FLOAT21_SIZE); m_iid[IID_SIZE] = '\0'; m_edition[EDITION_SIZE] = '\0'; m_r0[FLOAT21_SIZE] = '\0'; m_rx[FLOAT21_SIZE] = '\0'; m_ry[FLOAT21_SIZE] = '\0'; m_rz[FLOAT21_SIZE] = '\0'; m_rxx[FLOAT21_SIZE] = '\0'; m_rxy[FLOAT21_SIZE] = '\0'; m_rxz[FLOAT21_SIZE] = '\0'; m_ryy[FLOAT21_SIZE] = '\0'; m_ryz[FLOAT21_SIZE] = '\0'; m_rzz[FLOAT21_SIZE] = '\0'; m_c0[FLOAT21_SIZE] = '\0'; m_cx[FLOAT21_SIZE] = '\0'; m_cy[FLOAT21_SIZE] = '\0'; m_cz[FLOAT21_SIZE] = '\0'; m_cxx[FLOAT21_SIZE] = '\0'; m_cxy[FLOAT21_SIZE] = '\0'; m_cxz[FLOAT21_SIZE] = '\0'; m_cyy[FLOAT21_SIZE] = '\0'; m_cyz[FLOAT21_SIZE] = '\0'; m_czz[FLOAT21_SIZE] = '\0'; m_rnis[NIS_SIZE] = '\0'; m_cnis[NIS_SIZE] = '\0'; m_tnis[NIS_SIZE] = '\0'; m_rssiz[FLOAT21_SIZE] = '\0'; m_cssiz[FLOAT21_SIZE] = '\0'; } ossimString ossimNitfRsmpiaTag::getIid() const { return ossimString(m_iid); } ossimString ossimNitfRsmpiaTag::getEdition() const { return ossimString(m_edition); } ossimString ossimNitfRsmpiaTag::getR0() const { return ossimString(m_r0); } ossimString ossimNitfRsmpiaTag::getRx() const { return ossimString(m_rx); } ossimString ossimNitfRsmpiaTag::getRy() const { return ossimString(m_ry); } ossimString ossimNitfRsmpiaTag::getRz() const { return ossimString(m_rz); } ossimString ossimNitfRsmpiaTag::getRxx() const { return ossimString(m_rxx); } ossimString ossimNitfRsmpiaTag::getRxy() const { return ossimString(m_rxy); } ossimString ossimNitfRsmpiaTag::getRxz() const { return ossimString(m_rxz); } ossimString ossimNitfRsmpiaTag::getRyy() const { return ossimString(m_ryy); } ossimString ossimNitfRsmpiaTag::getRyz() const { return ossimString(m_ryz); } ossimString ossimNitfRsmpiaTag::getRzz() const { return ossimString(m_rzz); } ossimString ossimNitfRsmpiaTag::getC0() const { return ossimString(m_c0); } ossimString ossimNitfRsmpiaTag::getCx() const { return ossimString(m_cx); } ossimString ossimNitfRsmpiaTag::getCy() const { return ossimString(m_cy); } ossimString ossimNitfRsmpiaTag::getCz() const { return ossimString(m_cz); } ossimString ossimNitfRsmpiaTag::getCxx() const { return ossimString(m_cxx); } ossimString ossimNitfRsmpiaTag::getCxy() const { return ossimString(m_cxy); } ossimString ossimNitfRsmpiaTag::getCxz() const { return ossimString(m_cxz); } ossimString ossimNitfRsmpiaTag::getCyy() const { return ossimString(m_cyy); } ossimString ossimNitfRsmpiaTag::getCyz() const { return ossimString(m_cyz); } ossimString ossimNitfRsmpiaTag::getCzz() const { return ossimString(m_czz); } ossimString ossimNitfRsmpiaTag::getRnis() const { return ossimString(m_rnis); } ossimString ossimNitfRsmpiaTag::getCnis() const { return ossimString(m_cnis); } ossimString ossimNitfRsmpiaTag::getTnis() const { return ossimString(m_tnis); } ossimString ossimNitfRsmpiaTag::getRssiz() const { return ossimString(m_rssiz); } ossimString ossimNitfRsmpiaTag::getCssiz() const { return ossimString(m_cssiz); } ossim-Miami-2.9.1/src/support_data/ossimNitfSensraTag.cpp000066400000000000000000000350101352751253100234750ustar00rootroot00000000000000//******************************************************************* // LICENSE: LGPL // // see top level LICENSE.txt // // Author: Walt Bunch // // Description: Nitf support class for SENSRA - Sensor parameters extension. // //******************************************************************** // $Id: ossimNitfSensraTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include #include #include RTTI_DEF1(ossimNitfSensraTag, "ossimNitfSensraTag", ossimNitfRegisteredTag); ossimNitfSensraTag::ossimNitfSensraTag() : ossimNitfRegisteredTag(std::string("SENSRA"), 132) { clearFields(); } ossimNitfSensraTag::~ossimNitfSensraTag() { } void ossimNitfSensraTag::parseStream(std::istream& in) { clearFields(); in.read(theRefRow, REF_ROW_SIZE); in.read(theRefCol, REF_COL_SIZE); in.read(theSensorModel, SENSOR_MODEL_SIZE); in.read(theSensorMount, SENSOR_MOUNT_SIZE); in.read(theSensorLoc, SENSOR_LOC_SIZE); in.read(theSensorAltSrc, SENSOR_ALT_SRC_SIZE); in.read(theSensorAlt, SENSOR_ALT_SIZE); in.read(theSensorAltUnit, SENSOR_ALT_UNIT_SIZE); in.read(theSensorAgl, SENSOR_AGL_SIZE); in.read(theSensorPitch, SENSOR_PITCH_SIZE); in.read(theSensorRoll, SENSOR_ROLL_SIZE); in.read(theSensorYaw, SENSOR_YAW_SIZE); in.read(thePlatformPitch, PLATFORM_PITCH_SIZE); in.read(thePlatformRoll, PLATFORM_ROLL_SIZE); in.read(thePlatformHdg, PLATFORM_HDG_SIZE); in.read(theGroundSpdSrc, GROUND_SPD_SRC_SIZE); in.read(theGroundSpeed, GROUND_SPEED_SIZE); in.read(theGroundSpdUnit, GROUND_SPD_UNIT_SIZE); in.read(theGroundTrack, GROUND_TRACK_SIZE); in.read(theVerticalVel, VERTICAL_VEL_SIZE); in.read(theVertVelUnit, VERT_VEL_UNIT_SIZE); in.read(theSwathFrames, SWATH_FRAMES_SIZE); in.read(theNSwaths, N_SWATHS_SIZE); in.read(theSpotNum, SPOT_NUM_SIZE); } void ossimNitfSensraTag::writeStream(std::ostream& out) { out.write(theRefRow, REF_ROW_SIZE); out.write(theRefCol, REF_COL_SIZE); out.write(theSensorModel, SENSOR_MODEL_SIZE); out.write(theSensorMount, SENSOR_MOUNT_SIZE); out.write(theSensorLoc, SENSOR_LOC_SIZE); out.write(theSensorAltSrc, SENSOR_ALT_SRC_SIZE); out.write(theSensorAlt, SENSOR_ALT_SIZE); out.write(theSensorAltUnit, SENSOR_ALT_UNIT_SIZE); out.write(theSensorAgl, SENSOR_AGL_SIZE); out.write(theSensorPitch, SENSOR_PITCH_SIZE); out.write(theSensorRoll, SENSOR_ROLL_SIZE); out.write(theSensorYaw, SENSOR_YAW_SIZE); out.write(thePlatformPitch, PLATFORM_PITCH_SIZE); out.write(thePlatformRoll, PLATFORM_ROLL_SIZE); out.write(thePlatformHdg, PLATFORM_HDG_SIZE); out.write(theGroundSpdSrc, GROUND_SPD_SRC_SIZE); out.write(theGroundSpeed, GROUND_SPEED_SIZE); out.write(theGroundSpdUnit, GROUND_SPD_UNIT_SIZE); out.write(theGroundTrack, GROUND_TRACK_SIZE); out.write(theVerticalVel, VERTICAL_VEL_SIZE); out.write(theVertVelUnit, VERT_VEL_UNIT_SIZE); out.write(theSwathFrames, SWATH_FRAMES_SIZE); out.write(theNSwaths, N_SWATHS_SIZE); out.write(theSpotNum, SPOT_NUM_SIZE); } void ossimNitfSensraTag::clearFields() { memset(theRefRow, ' ', REF_ROW_SIZE); memset(theRefCol, ' ', REF_COL_SIZE); memset(theSensorModel, ' ', SENSOR_MODEL_SIZE); memset(theSensorMount, ' ', SENSOR_MOUNT_SIZE); memset(theSensorLoc, ' ', SENSOR_LOC_SIZE); memset(theSensorAltSrc, ' ', SENSOR_ALT_SRC_SIZE); memset(theSensorAlt, ' ', SENSOR_ALT_SIZE); memset(theSensorAltUnit, ' ', SENSOR_ALT_UNIT_SIZE); memset(theSensorAgl, ' ', SENSOR_AGL_SIZE); memset(theSensorPitch, ' ', SENSOR_PITCH_SIZE); memset(theSensorRoll, ' ', SENSOR_ROLL_SIZE); memset(theSensorYaw, ' ', SENSOR_YAW_SIZE); memset(thePlatformPitch, ' ', PLATFORM_PITCH_SIZE); memset(thePlatformRoll, ' ', PLATFORM_ROLL_SIZE); memset(thePlatformHdg, ' ', PLATFORM_HDG_SIZE); memset(theGroundSpdSrc, ' ', GROUND_SPD_SRC_SIZE); memset(theGroundSpeed, ' ', GROUND_SPEED_SIZE); memset(theGroundSpdUnit, ' ', GROUND_SPD_UNIT_SIZE); memset(theGroundTrack, ' ', GROUND_TRACK_SIZE); memset(theVerticalVel, ' ', VERTICAL_VEL_SIZE); memset(theVertVelUnit, ' ', VERT_VEL_UNIT_SIZE); memset(theSwathFrames, ' ', SWATH_FRAMES_SIZE); memset(theNSwaths, ' ', N_SWATHS_SIZE); memset(theSpotNum, ' ', SPOT_NUM_SIZE); theRefRow[REF_ROW_SIZE] = '\0'; theRefCol[REF_COL_SIZE] = '\0'; theSensorModel[SENSOR_MODEL_SIZE] = '\0'; theSensorMount[SENSOR_MOUNT_SIZE] = '\0'; theSensorLoc[SENSOR_LOC_SIZE] = '\0'; theSensorAltSrc[SENSOR_ALT_SRC_SIZE] = '\0'; theSensorAlt[SENSOR_ALT_SIZE] = '\0'; theSensorAltUnit[SENSOR_ALT_UNIT_SIZE] = '\0'; theSensorAgl[SENSOR_AGL_SIZE] = '\0'; theSensorPitch[SENSOR_PITCH_SIZE] = '\0'; theSensorRoll[SENSOR_ROLL_SIZE] = '\0'; theSensorYaw[SENSOR_YAW_SIZE] = '\0'; thePlatformPitch[PLATFORM_PITCH_SIZE] = '\0'; thePlatformRoll[PLATFORM_ROLL_SIZE] = '\0'; thePlatformHdg[PLATFORM_HDG_SIZE] = '\0'; theGroundSpdSrc[GROUND_SPD_SRC_SIZE] = '\0'; theGroundSpeed[GROUND_SPEED_SIZE] = '\0'; theGroundSpdUnit[GROUND_SPD_UNIT_SIZE] = '\0'; theGroundTrack[GROUND_TRACK_SIZE] = '\0'; theVerticalVel[VERTICAL_VEL_SIZE] = '\0'; theVertVelUnit[VERT_VEL_UNIT_SIZE] = '\0'; theSwathFrames[SWATH_FRAMES_SIZE] = '\0'; theNSwaths[N_SWATHS_SIZE] = '\0'; theSpotNum[SPOT_NUM_SIZE] = '\0'; } std::ostream& ossimNitfSensraTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << std::setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "REFROW:" << theRefRow << "\n" << pfx << std::setw(24) << "REFCOL:" << theRefCol << "\n" << pfx << std::setw(24) << "SENSORMODEL:" << theSensorModel<< "\n" << pfx << std::setw(24) << "SENSORMOUNT:" << theSensorMount << "\n" << pfx << std::setw(24) << "SENSORLOC:" << theSensorLoc << "\n" << pfx << std::setw(24) << "SENSORALTSRC:" << theSensorAltSrc<< "\n" << pfx << std::setw(24) << "SENSORALT:" << theSensorAlt << "\n" << pfx << std::setw(24) << "SENSORALTUNIT:" << theSensorAltUnit << "\n" << pfx << std::setw(24) << "SENSORAGL:" << theSensorAgl << "\n" << pfx << std::setw(24) << "SENSORPITCH:" << theSensorPitch << "\n" << pfx << std::setw(24) << "SENSORROLL:" << theSensorRoll<< "\n" << pfx << std::setw(24) << "SENSORYAW:" << theSensorYaw << "\n" << pfx << std::setw(24) << "PLATFORMPITCH:" << thePlatformPitch << "\n" << pfx << std::setw(24) << "PLATFORMROLL:" << thePlatformRoll << "\n" << pfx << std::setw(24) << "PLATFORMHDG:" << thePlatformHdg << "\n" << pfx << std::setw(24) << "GROUNDSPDSRC:" << theGroundSpdSrc << "\n" << pfx << std::setw(24) << "GROUNDSPEED:" << theGroundSpeed << "\n" << pfx << std::setw(24) << "GROUNDSPDUNIT:" << theGroundSpdUnit << "\n" << pfx << std::setw(24) << "GROUNDTRACK:" << theGroundTrack << "\n" << pfx << std::setw(24) << "VERTICALVEL:" << theVerticalVel<< "\n" << pfx << std::setw(24) << "VERTVELUNIT:" << theVertVelUnit << "\n" << pfx << std::setw(24) << "SWATHFRAMES:" << theSwathFrames<< "\n" << pfx << std::setw(24) << "NSWATHS:" << theNSwaths << "\n" << pfx << std::setw(24) << "SPOTNUM:" << theSpotNum << "\n"; return out; } ossimString ossimNitfSensraTag::getRefRow()const { return theRefRow; } void ossimNitfSensraTag::setRefRow(ossimString refRow) { memset(theRefRow, ' ', REF_ROW_SIZE); memcpy(theRefRow, refRow.c_str(), std::min((size_t)REF_ROW_SIZE, refRow.length())); } ossimString ossimNitfSensraTag::getRefCol()const { return theRefCol; } void ossimNitfSensraTag::setRefCol(ossimString refCol) { memset(theRefCol, ' ', REF_COL_SIZE); memcpy(theRefCol, refCol.c_str(), std::min((size_t)REF_COL_SIZE, refCol.length())); } ossimString ossimNitfSensraTag::getSensorModel()const { return theSensorModel; } void ossimNitfSensraTag::setSensorModel(ossimString sensorModel) { memset(theSensorModel, ' ', SENSOR_MODEL_SIZE); memcpy(theSensorModel, sensorModel.c_str(), std::min((size_t)SENSOR_MODEL_SIZE, sensorModel.length())); } ossimString ossimNitfSensraTag::getSensorMount()const { return theSensorMount; } void ossimNitfSensraTag::setSensorMount(ossimString sensorMount) { memset(theSensorMount, ' ', SENSOR_MOUNT_SIZE); memcpy(theSensorMount, sensorMount.c_str(), std::min((size_t)SENSOR_MOUNT_SIZE, sensorMount.length())); } ossimString ossimNitfSensraTag::getSensorLoc()const { return theSensorLoc; } void ossimNitfSensraTag::setSensorLoc(ossimString sensorLoc) { memset(theSensorLoc, ' ', SENSOR_LOC_SIZE); memcpy(theSensorLoc, sensorLoc.c_str(), std::min((size_t)SENSOR_LOC_SIZE, sensorLoc.length())); } ossimString ossimNitfSensraTag::getSensorAltSrc()const { return theSensorAltSrc; } void ossimNitfSensraTag::setSensorAltSrc(ossimString sensorAltSrc) { memset(theSensorAltSrc, ' ', SENSOR_ALT_SRC_SIZE); memcpy(theSensorAltSrc, sensorAltSrc.c_str(), std::min((size_t)SENSOR_ALT_SRC_SIZE, sensorAltSrc.length())); } ossimString ossimNitfSensraTag::getSensorAlt()const { return theSensorAlt; } void ossimNitfSensraTag::setSensorAlt(ossimString sensorAlt) { memset(theSensorAlt, ' ', SENSOR_ALT_SIZE); memcpy(theSensorAlt, sensorAlt.c_str(), std::min((size_t)SENSOR_ALT_SIZE, sensorAlt.length())); } ossimString ossimNitfSensraTag::getSensorAltUnit()const { return theSensorAltUnit; } void ossimNitfSensraTag::setSensorAltUnit(ossimString sensorAltUnit) { memset(theSensorAltUnit, ' ', SENSOR_ALT_UNIT_SIZE); memcpy(theSensorAltUnit, sensorAltUnit.c_str(), std::min((size_t)SENSOR_ALT_UNIT_SIZE, sensorAltUnit.length())); } ossimString ossimNitfSensraTag::getSensorAgl()const { return theSensorAgl; } void ossimNitfSensraTag::setSensorAgl(ossimString sensorAgl) { memset(theSensorAgl, ' ', SENSOR_AGL_SIZE); memcpy(theSensorAgl, sensorAgl.c_str(), std::min((size_t)SENSOR_AGL_SIZE, sensorAgl.length())); } ossimString ossimNitfSensraTag::getSensorPitch()const { return theSensorPitch; } void ossimNitfSensraTag::setSensorPitch(ossimString sensorPitch) { memset(theSensorPitch, ' ', SENSOR_PITCH_SIZE); memcpy(theSensorPitch, sensorPitch.c_str(), std::min((size_t)SENSOR_PITCH_SIZE, sensorPitch.length())); } ossimString ossimNitfSensraTag::getSensorRoll()const { return theSensorRoll; } void ossimNitfSensraTag::setSensorRoll(ossimString sensorRoll) { memset(theSensorRoll, ' ', SENSOR_ROLL_SIZE); memcpy(theSensorRoll, sensorRoll.c_str(), std::min((size_t)SENSOR_ROLL_SIZE, sensorRoll.length())); } ossimString ossimNitfSensraTag::getSensorYaw()const { return theSensorYaw; } void ossimNitfSensraTag::setSensorYaw(ossimString sensorYaw) { memset(theSensorYaw, ' ', SENSOR_YAW_SIZE); memcpy(theSensorYaw, sensorYaw.c_str(), std::min((size_t)SENSOR_YAW_SIZE, sensorYaw.length())); } ossimString ossimNitfSensraTag::getPlatformPitch()const { return thePlatformPitch; } void ossimNitfSensraTag::setPlatformPitch(ossimString platformPitch) { memset(thePlatformPitch, ' ', PLATFORM_PITCH_SIZE); memcpy(thePlatformPitch, platformPitch.c_str(), std::min((size_t)PLATFORM_PITCH_SIZE, platformPitch.length())); } ossimString ossimNitfSensraTag::getPlatformRoll()const { return thePlatformRoll; } void ossimNitfSensraTag::setPlatformRoll(ossimString platformRoll) { memset(thePlatformRoll, ' ', PLATFORM_ROLL_SIZE); memcpy(thePlatformRoll, platformRoll.c_str(), std::min((size_t)PLATFORM_ROLL_SIZE, platformRoll.length())); } ossimString ossimNitfSensraTag::getPlatformHdg()const { return thePlatformHdg; } void ossimNitfSensraTag::setPlatformHdg(ossimString platformHdg) { memset(thePlatformHdg, ' ', PLATFORM_HDG_SIZE); memcpy(thePlatformHdg, platformHdg.c_str(), std::min((size_t)PLATFORM_HDG_SIZE, platformHdg.length())); } ossimString ossimNitfSensraTag::getGroundSpdSrc()const { return theGroundSpdSrc; } void ossimNitfSensraTag::setGroundSpdSrc(ossimString groundSpdSrc) { memset(theGroundSpdSrc, ' ', GROUND_SPD_SRC_SIZE); memcpy(theGroundSpdSrc, groundSpdSrc.c_str(), std::min((size_t)GROUND_SPD_SRC_SIZE, groundSpdSrc.length())); } ossimString ossimNitfSensraTag::getGroundSpeed()const { return theGroundSpeed; } void ossimNitfSensraTag::setGroundSpeed(ossimString groundSpeed) { memset(theGroundSpeed, ' ', GROUND_SPEED_SIZE); memcpy(theGroundSpeed, groundSpeed.c_str(), std::min((size_t)GROUND_SPEED_SIZE, groundSpeed.length())); } ossimString ossimNitfSensraTag::getGroundSpdUnit()const { return theGroundSpdUnit; } void ossimNitfSensraTag::setGroundSpdUnit(ossimString groundSpdUnit) { memset(theGroundSpdUnit, ' ', GROUND_SPD_UNIT_SIZE); memcpy(theGroundSpdUnit, groundSpdUnit.c_str(), std::min((size_t)GROUND_SPD_UNIT_SIZE, groundSpdUnit.length())); } ossimString ossimNitfSensraTag::getGroundTrack()const { return theGroundTrack; } void ossimNitfSensraTag::setGroundTrack(ossimString groundTrack) { memset(theGroundTrack, ' ', GROUND_TRACK_SIZE); memcpy(theGroundTrack, groundTrack.c_str(), std::min((size_t)GROUND_TRACK_SIZE, groundTrack.length())); } ossimString ossimNitfSensraTag::getVerticalVel()const { return theVerticalVel; } void ossimNitfSensraTag::setVerticalVel(ossimString verticalVel) { memset(theVerticalVel, ' ', VERTICAL_VEL_SIZE); memcpy(theVerticalVel, verticalVel.c_str(), std::min((size_t)VERTICAL_VEL_SIZE, verticalVel.length())); } ossimString ossimNitfSensraTag::getVertVelUnit()const { return theVertVelUnit; } void ossimNitfSensraTag::setVertVelUnit(ossimString vertVelUnit) { memset(theVertVelUnit, ' ', VERT_VEL_UNIT_SIZE); memcpy(theVertVelUnit, vertVelUnit.c_str(), std::min((size_t)VERT_VEL_UNIT_SIZE, vertVelUnit.length())); } ossimString ossimNitfSensraTag::getSwathFrames()const { return theSwathFrames; } void ossimNitfSensraTag::setSwathFrames(ossimString swathFrames) { memset(theSwathFrames, ' ', SWATH_FRAMES_SIZE); memcpy(theSwathFrames, swathFrames.c_str(), std::min((size_t)SWATH_FRAMES_SIZE, swathFrames.length())); } ossimString ossimNitfSensraTag::getNSwaths()const { return theNSwaths; } void ossimNitfSensraTag::setNSwaths(ossimString nSwaths) { memset(theNSwaths, ' ', N_SWATHS_SIZE); memcpy(theNSwaths, nSwaths.c_str(), std::min((size_t)N_SWATHS_SIZE, nSwaths.length())); } ossimString ossimNitfSensraTag::getSpotNum()const { return theSpotNum; } void ossimNitfSensraTag::setSpotNum(ossimString spotNum) { memset(theSpotNum, ' ', SPOT_NUM_SIZE); memcpy(theSpotNum, spotNum.c_str(), std::min((size_t)SPOT_NUM_SIZE, spotNum.length())); } ossim-Miami-2.9.1/src/support_data/ossimNitfSicdXmlDataContentDes.cpp000066400000000000000000000176761352751253100257540ustar00rootroot00000000000000#include #include #include #include #include using namespace std; // ossimNitfSicdXmlDataContentDes::ossimNitfSicdXmlDataContentDes() : ossimNitfRegisteredDes(std::string("XML_DATA_CONTENT"), 0) { clearFields(); } void ossimNitfSicdXmlDataContentDes::parseStream(std::istream& in) { clearFields(); if (m_desName.contains("XML_DATA_CONTENT")) { in.read(m_descrc, DESCRC_SIZE); in.read(m_desshft, DESSHFT_SIZE); in.read(m_desshdt, DESSHDT_SIZE); in.read(m_desshrp, DESSHRP_SIZE); in.read(m_desshsi, DESSHSI_SIZE); in.read(m_desshsv, DESSHSV_SIZE); in.read(m_desshsd, DESSHSD_SIZE); in.read(m_desshtn, DESSHTN_SIZE); in.read(m_desshlpg, DESSHLPG_SIZE); in.read(m_desshlpt, DESSHLPT_SIZE); in.read(m_desshli, DESSHLI_SIZE); in.read(m_desshlin, DESSHLIN_SIZE); in.read(m_desshabs, DESSHABS_SIZE); } if(getSizeInBytes()) { m_desData.resize(getSizeInBytes()); char* bufStart = &m_desData.front(); in.read(bufStart, getSizeInBytes()); } } void ossimNitfSicdXmlDataContentDes::writeStream(std::ostream& out) { if (m_desName.contains("XML_DATA_CONTENT")) { out.write(m_desshl, DESSHL_SIZE); out.write(m_descrc, DESCRC_SIZE); out.write(m_desshft, DESSHFT_SIZE); out.write(m_desshdt, DESSHDT_SIZE); out.write(m_desshrp, DESSHRP_SIZE); out.write(m_desshsi, DESSHSI_SIZE); out.write(m_desshsv, DESSHSV_SIZE); out.write(m_desshsd, DESSHSD_SIZE); out.write(m_desshtn, DESSHTN_SIZE); out.write(m_desshlpg, DESSHLPG_SIZE); out.write(m_desshlpt, DESSHLPT_SIZE); out.write(m_desshli, DESSHLI_SIZE); out.write(m_desshlin, DESSHLIN_SIZE); out.write(m_desshabs, DESSHABS_SIZE); } if (!m_desData.empty()) { out.write(&m_desData.front(), m_desData.size()); } } std::ostream& ossimNitfSicdXmlDataContentDes::print(std::ostream& out, const std::string& prefix) const { bool typeinfo = ossimString(ossimPreferences::instance()->findPreference("kwl_type_info")).toBool(); std::string pfx = prefix; // pfx += getDesName() + "."; ossimString desData; getDesDataAsString(desData); out << setiosflags(ios::left) << pfx << std::setw(24) << "DESCRC:" << ((typeinfo) ? "(string)" : "") << m_descrc << "\n" << pfx << std::setw(24) << "DESSHFT:" << ((typeinfo) ? "(string)" : "") << m_desshft << "\n" << pfx << std::setw(24) << "DESSHDT:" << ((typeinfo) ? "(string)" : "") << m_desshdt << "\n" << pfx << std::setw(24) << "DESSHRP:" << ((typeinfo) ? "(string)" : "") << m_desshrp << "\n" << pfx << std::setw(24) << "DESSHSI:" << ((typeinfo) ? "(string)" : "") << m_desshsi << "\n" << pfx << std::setw(24) << "DESSHSV:" << ((typeinfo) ? "(string)" : "") << m_desshsv << "\n" << pfx << std::setw(24) << "DESSHSD:" << ((typeinfo) ? "(string)" : "") << m_desshsd << "\n" << pfx << std::setw(24) << "DESSHTN:" << ((typeinfo) ? "(string)" : "") << m_desshtn << "\n" << pfx << std::setw(24) << "DESSHLPG:" << ((typeinfo) ? "(string)" : "") << m_desshlpg << "\n" << pfx << std::setw(24) << "DESSHLPT:" << ((typeinfo) ? "(string)" : "") << m_desshlpt << "\n" << pfx << std::setw(24) << "DESSHLI:" << ((typeinfo) ? "(string)" : "") << m_desshli << "\n" << pfx << std::setw(24) << "DESSHABS:" << ((typeinfo) ? "(string)" : "") << m_desshabs << "\n" << pfx << std::setw(24) << "DESDATA:" << ((typeinfo) ? "(string)" : "") << "\"\"\"" << desData << "\"\"\"\n" ; // might be better to leave it as the raw XML under the DESDATA value #if 0 if (desData) { ossimXmlDocument doc; if(doc.readString(desData)) { ossimKeywordlist kwl; doc.toKwl(kwl, pfx); out << kwl << "\n"; } } #endif return out; } void ossimNitfSicdXmlDataContentDes::clearFields() { memset(m_descrc, ' ', DESCRC_SIZE); m_descrc[DESCRC_SIZE] = '\0'; memset(m_desshft, ' ', DESSHFT_SIZE); m_desshft[DESSHFT_SIZE] = '\0'; memset(m_desshdt, ' ', DESSHDT_SIZE); m_desshdt[DESSHDT_SIZE] = '\0'; memset(m_desshrp, ' ', DESSHRP_SIZE); m_desshrp[DESSHRP_SIZE] = '\0'; memset(m_desshsi, ' ', DESSHSI_SIZE); m_desshsi[DESSHSI_SIZE] = '\0'; memset(m_desshsv, ' ', DESSHSV_SIZE); m_desshsv[DESSHSV_SIZE] = '\0'; memset(m_desshsd, ' ', DESSHSD_SIZE); m_desshsd[DESSHSD_SIZE] = '\0'; memset(m_desshtn, ' ', DESSHTN_SIZE); m_desshtn[DESSHTN_SIZE] = '\0'; memset(m_desshlpg, ' ', DESSHLPG_SIZE); m_desshlpg[DESSHLPG_SIZE] = '\0'; memset(m_desshlpt, ' ', DESSHLPT_SIZE); m_desshlpt[DESSHLPT_SIZE] = '\0'; memset(m_desshli, ' ', DESSHLI_SIZE); m_desshli[DESSHLI_SIZE] = '\0'; memset(m_desshlin, ' ', DESSHLIN_SIZE); m_desshlin[DESSHLIN_SIZE] = '\0'; memset(m_desshabs, ' ', DESSHABS_SIZE); m_desshabs[DESSHABS_SIZE] = '\0'; m_desData.clear(); } bool ossimNitfSicdXmlDataContentDes::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString lookup; clearFields(); lookup = kwl.find(prefix, "DESCRC"); if (lookup) { strcpy(m_descrc, lookup); } lookup = kwl.find(prefix, "DESSHFT"); if (lookup) { strcpy(m_desshft, lookup); } lookup = kwl.find(prefix, "DESSHDT"); if (lookup) { strcpy(m_desshdt, lookup); } lookup = kwl.find(prefix, "DESSHRP"); if (lookup) { strcpy(m_desshrp, lookup); } lookup = kwl.find(prefix, "DESSHSI"); if (lookup) { strcpy(m_desshsi, lookup); } lookup = kwl.find(prefix, "DESSHSV"); if (lookup) { strcpy(m_desshsv, lookup); } lookup = kwl.find(prefix, "DESSHSD"); if (lookup) { strcpy(m_desshsd, lookup); } lookup = kwl.find(prefix, "DESSHTN"); if (lookup) { strcpy(m_desshtn, lookup); } lookup = kwl.find(prefix, "DESDATA"); if(lookup) { ossimString value = lookup; m_desData.insert(m_desData.begin(), value.begin(), value.end()); } return true; } bool ossimNitfSicdXmlDataContentDes::saveState(ossimKeywordlist &kwl, const char *prefix)const { ossimString copyPrefix = prefix; ossimString desData; ossimNitfRegisteredDes::saveState(kwl, prefix); kwl.add(copyPrefix + "DESCRC", m_descrc); kwl.add(copyPrefix + "DESSHFT", m_desshft); kwl.add(copyPrefix + "DESSHDT", m_desshdt); kwl.add(copyPrefix + "DESSHRP", m_desshrp); kwl.add(copyPrefix + "DESSHSI", m_desshsi); kwl.add(copyPrefix + "DESSHSV", m_desshsv); kwl.add(copyPrefix + "DESSHSD", m_desshsd); kwl.add(copyPrefix + "DESSHTN", m_desshtn); getDesDataAsString(desData); kwl.add(copyPrefix + "DESDATA", desData); return true; } // bool ossimNitfSicdXmlDataContentDes::loadValueFromXml(const ossimRefPtr xml, const ossimString &xpath, ossimString &target) const // { // bool result = false; // if (xml->getErrorStatus()) return result; // std::vector > xml_nodes; // xml->findNodes(xpath, xml_nodes); // if (xml_nodes.size()) // { // target = xml_nodes[0]->getText(); // result = true; // } // return result; // } ossimString ossimNitfSicdXmlDataContentDes::getDescrc() const { return ossimString(m_descrc); } ossimString ossimNitfSicdXmlDataContentDes::getDesshft() const { return ossimString(m_desshft); } ossimString ossimNitfSicdXmlDataContentDes::getDesshdt() const { return ossimString(m_desshdt); } ossimString ossimNitfSicdXmlDataContentDes::getDesshrp() const { return ossimString(m_desshrp); } ossimString ossimNitfSicdXmlDataContentDes::getDesshsi() const { return ossimString(m_desshsi); } ossimString ossimNitfSicdXmlDataContentDes::getDesshsv() const { return ossimString(m_desshsv); } ossimString ossimNitfSicdXmlDataContentDes::getDesshsd() const { return ossimString(m_desshsd); } ossimString ossimNitfSicdXmlDataContentDes::getDesshtn() const { return ossimString(m_desshtn); } void ossimNitfSicdXmlDataContentDes::getDesDataAsString(ossimString& result) const { if(!m_desData.empty()) { const char* bufStart = &m_desData.front(); result = ossimString(bufStart, bufStart + m_desData.size()); } else { result = ""; } } ossim-Miami-2.9.1/src/support_data/ossimNitfStdidcTag.cpp000066400000000000000000000346411352751253100234650ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Walt Bunch // // Description: NITF support data class for STDIDC - Standard ID extension. // // See: STDI-000_v2.1 Table 7-3 for detailed description. // //******************************************************************** // $Id: ossimNitfStdidcTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfStdidcTag, "ossimNitfStdidcTag", ossimNitfRegisteredTag); static const ossimString ACQDATE_KW = "ACQDATE"; static const ossimString MISSION_KW = "MISSION"; static const ossimString PASS_KW = "PASS"; static const ossimString OPNUM_KW = "OPNUM"; static const ossimString STARTSEGMENT_KW = "STARTSEGMENT"; static const ossimString REPRONUM_KW = "REPRONUM"; static const ossimString REPLAYREGEN_KW = "REPLAYREGEN"; static const ossimString BLANKFILL_KW = "BLANKFILL"; static const ossimString STARTCOLUMN_KW = "STARTCOLUMN"; static const ossimString STARTROW_KW = "STARTROW"; static const ossimString ENDSEGMENT_KW = "ENDSEGMENT"; static const ossimString ENDCOLUMN_KW = "ENDCOLUMN"; static const ossimString ENDROW_KW = "ENDROW"; static const ossimString COUNTRY_KW = "COUNTRY"; static const ossimString WAC_KW = "WAC"; static const ossimString LOCATION_KW = "LOCATION"; ossimNitfStdidcTag::ossimNitfStdidcTag() : ossimNitfRegisteredTag(std::string("STDIDC"), 89) { clearFields(); } ossimNitfStdidcTag::~ossimNitfStdidcTag() { } void ossimNitfStdidcTag::parseStream(std::istream& in) { clearFields(); in.read(theAcqDate, ACQ_DATE_SIZE); in.read(theMission, MISSION_SIZE); in.read(thePass, PASS_SIZE); in.read(theOpNum, OP_NUM_SIZE); in.read(theStartSegment, START_SEGMENT_SIZE); in.read(theReproNum, REPRO_NUM_SIZE); in.read(theReplayRegen, REPLAY_REGEN_SIZE); in.read(theBlankFill, BLANK_FILL_SIZE); in.read(theStartColumn, START_COLUMN_SIZE); in.read(theStartRow, START_ROW_SIZE); in.read(theEndSegment, END_SEGMENT_SIZE); in.read(theEndColumn, END_COLUMN_SIZE); in.read(theEndRow, END_ROW_SIZE); in.read(theCountry, COUNTRY_SIZE); in.read(theWac, WAC_SIZE); in.read(theLocation, LOCATION_SIZE); in.read(theField17, FIELD17_SIZE); in.read(theField18, FIELD18_SIZE); } void ossimNitfStdidcTag::writeStream(std::ostream& out) { out.write(theAcqDate, ACQ_DATE_SIZE); out.write(theMission, MISSION_SIZE); out.write(thePass, PASS_SIZE); out.write(theOpNum, OP_NUM_SIZE); out.write(theStartSegment, START_SEGMENT_SIZE); out.write(theReproNum, REPRO_NUM_SIZE); out.write(theReplayRegen, REPLAY_REGEN_SIZE); out.write(theBlankFill, BLANK_FILL_SIZE); out.write(theStartColumn, START_COLUMN_SIZE); out.write(theStartRow, START_ROW_SIZE); out.write(theEndSegment, END_SEGMENT_SIZE); out.write(theEndColumn, END_COLUMN_SIZE); out.write(theEndRow, END_ROW_SIZE); out.write(theCountry, COUNTRY_SIZE); out.write(theWac, WAC_SIZE); out.write(theLocation, LOCATION_SIZE); out.write(theField17, FIELD17_SIZE); out.write(theField18, FIELD18_SIZE); } void ossimNitfStdidcTag::clearFields() { memset(theAcqDate, ' ', ACQ_DATE_SIZE); memset(theMission, ' ', MISSION_SIZE); memset(thePass, ' ', PASS_SIZE); memset(theOpNum, ' ', OP_NUM_SIZE); memset(theStartSegment, ' ', START_SEGMENT_SIZE); memset(theReproNum, ' ', REPRO_NUM_SIZE); memset(theReplayRegen, ' ', REPLAY_REGEN_SIZE); memset(theBlankFill, ' ', BLANK_FILL_SIZE); memset(theStartColumn, ' ', START_COLUMN_SIZE); memset(theStartRow, ' ', START_ROW_SIZE); memset(theEndSegment, ' ', END_SEGMENT_SIZE); memset(theEndColumn, ' ', END_COLUMN_SIZE); memset(theEndRow, ' ', END_ROW_SIZE); memset(theCountry, ' ', COUNTRY_SIZE); memset(theWac, ' ', WAC_SIZE); memset(theLocation, ' ', LOCATION_SIZE); memset(theField17, ' ', FIELD17_SIZE); memset(theField18, ' ', FIELD18_SIZE); theAcqDate[ACQ_DATE_SIZE] = '\0'; theMission[MISSION_SIZE] = '\0'; thePass[PASS_SIZE] = '\0'; theOpNum[OP_NUM_SIZE] = '\0'; theStartSegment[START_SEGMENT_SIZE] = '\0'; theReproNum[REPRO_NUM_SIZE] = '\0'; theReplayRegen[REPLAY_REGEN_SIZE] = '\0'; theBlankFill[BLANK_FILL_SIZE] = '\0'; theStartColumn[START_COLUMN_SIZE] = '\0'; theStartRow[START_ROW_SIZE] = '\0'; theEndSegment[END_SEGMENT_SIZE] = '\0'; theEndColumn[END_COLUMN_SIZE] = '\0'; theEndRow[END_ROW_SIZE] = '\0'; theCountry[COUNTRY_SIZE] = '\0'; theWac[WAC_SIZE] = '\0'; theLocation[LOCATION_SIZE] = '\0'; theField17[FIELD17_SIZE] = '\0'; theField18[FIELD18_SIZE] = '\0'; } ossimString ossimNitfStdidcTag::getAcqDate()const { return ossimString(theAcqDate); } void ossimNitfStdidcTag::setAcqDate(ossimString acqDate) { memset(theAcqDate, ' ', ACQ_DATE_SIZE); memcpy(theAcqDate, acqDate.c_str(), std::min((size_t)ACQ_DATE_SIZE, acqDate.length())); } ossimString ossimNitfStdidcTag::getMission()const { return ossimString(theMission); } void ossimNitfStdidcTag::setMission(ossimString mission) { memset(theMission, ' ', MISSION_SIZE); memcpy(theMission, mission.c_str(), std::min((size_t)MISSION_SIZE, mission.length())); } ossimString ossimNitfStdidcTag::getPass()const { return ossimString(thePass); } void ossimNitfStdidcTag::setPass(ossimString pass) { memset(thePass, ' ', PASS_SIZE); memcpy(thePass, pass.c_str(), std::min((size_t)PASS_SIZE, pass.length())); } ossimString ossimNitfStdidcTag::getOpNum()const { return ossimString(theOpNum); } void ossimNitfStdidcTag::setOpNum(ossimString opNum) { memset(theOpNum, ' ', OP_NUM_SIZE); memcpy(theOpNum, opNum.c_str(), std::min((size_t)OP_NUM_SIZE, opNum.length())); } ossimString ossimNitfStdidcTag::getStartSegment()const { return ossimString(theStartSegment); } void ossimNitfStdidcTag::setStartSegment(ossimString startSegment) { memset(theStartSegment, ' ', START_SEGMENT_SIZE); memcpy(theStartSegment, startSegment.c_str(), std::min((size_t)START_SEGMENT_SIZE, startSegment.length())); } ossimString ossimNitfStdidcTag::getReproNum()const { return ossimString(theReproNum); } void ossimNitfStdidcTag::setReproNum(ossimString reproNum) { memset(theReproNum, ' ', REPRO_NUM_SIZE); memcpy(theReproNum, reproNum.c_str(), std::min((size_t)REPRO_NUM_SIZE, reproNum.length())); } ossimString ossimNitfStdidcTag::getReplayRegen()const { return ossimString(theReplayRegen); } void ossimNitfStdidcTag::setReplayRegen(ossimString replayRegen) { memset(theReplayRegen, ' ', REPLAY_REGEN_SIZE); memcpy(theReplayRegen, replayRegen.c_str(), std::min((size_t)REPLAY_REGEN_SIZE, replayRegen.length())); } ossimString ossimNitfStdidcTag::getBlankFill()const { return ossimString(theBlankFill); } void ossimNitfStdidcTag::setBlankFill(ossimString blankFill) { memset(theBlankFill, ' ', BLANK_FILL_SIZE); memcpy(theBlankFill, blankFill.c_str(), std::min((size_t)BLANK_FILL_SIZE, blankFill.length())); } ossimString ossimNitfStdidcTag::getStartColumn()const { return ossimString(theStartColumn); } void ossimNitfStdidcTag::setStartColumn(ossimString startColumn) { memset(theStartColumn, ' ', START_COLUMN_SIZE); memcpy(theStartColumn, startColumn.c_str(), std::min((size_t)START_COLUMN_SIZE, startColumn.length())); } ossimString ossimNitfStdidcTag::getStartRow()const { return ossimString(theStartRow); } void ossimNitfStdidcTag::setStartRow(ossimString startRow) { memset(theStartRow, ' ', START_ROW_SIZE); memcpy(theStartRow, startRow.c_str(), std::min((size_t)START_ROW_SIZE, startRow.length())); } ossimString ossimNitfStdidcTag::getEndSegment()const { return ossimString(theEndSegment); } void ossimNitfStdidcTag::setEndSegment(ossimString endSegment) { memset(theEndSegment, ' ', END_SEGMENT_SIZE); memcpy(theEndSegment, endSegment.c_str(), std::min((size_t)END_SEGMENT_SIZE, endSegment.length())); } ossimString ossimNitfStdidcTag::getEndColumn()const { return ossimString(theEndColumn); } void ossimNitfStdidcTag::setEndColumn(ossimString endColumn) { memset(theEndColumn, ' ', END_COLUMN_SIZE); memcpy(theEndColumn, endColumn.c_str(), std::min((size_t)END_COLUMN_SIZE, endColumn.length())); } ossimString ossimNitfStdidcTag::getEndRow()const { return ossimString(theEndRow); } void ossimNitfStdidcTag::setEndRow(ossimString endRow) { memset(theEndRow, ' ', END_ROW_SIZE); memcpy(theEndRow, endRow.c_str(), std::min((size_t)END_ROW_SIZE, endRow.length())); } ossimString ossimNitfStdidcTag::getCountry()const { return ossimString(theCountry); } void ossimNitfStdidcTag::setCountry(ossimString country) { memset(theCountry, ' ', COUNTRY_SIZE); memcpy(theCountry, country.c_str(), std::min((size_t)COUNTRY_SIZE, country.length())); } ossimString ossimNitfStdidcTag::getWac()const { return ossimString(theWac); } void ossimNitfStdidcTag::setWac(ossimString wac) { memset(theWac, ' ', WAC_SIZE); memcpy(theWac, wac.c_str(), std::min((size_t)WAC_SIZE, wac.length())); } ossimString ossimNitfStdidcTag::getLocation()const { return ossimString(theLocation); } void ossimNitfStdidcTag::setLocation(ossimString location) { memset(theLocation, ' ', LOCATION_SIZE); memcpy(theLocation, location.c_str(), std::min((size_t)LOCATION_SIZE, location.length())); } ossimString ossimNitfStdidcTag::getField17()const { return ossimString(theField17); } void ossimNitfStdidcTag::setField17(ossimString field17) { memset(theField17, ' ', FIELD17_SIZE); memcpy(theField17, field17.c_str(), std::min((size_t)FIELD17_SIZE, field17.length())); } ossimString ossimNitfStdidcTag::getField18()const { return ossimString(theField18); } void ossimNitfStdidcTag::setField18(ossimString field18) { memset(theField18, ' ', FIELD18_SIZE); memcpy(theField18, field18.c_str(), std::min((size_t)FIELD18_SIZE, field18.length())); } std::ostream& ossimNitfStdidcTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "ACQDATE:" << theAcqDate << "\n" << pfx << std::setw(24) << "MISSION:" << theMission << "\n" << pfx << std::setw(24) << "PASS:" << thePass << "\n" << pfx << std::setw(24) << "OPNUM:" << theOpNum << "\n" << pfx << std::setw(24) << "STARTSEGMENT:" << theStartSegment << "\n" << pfx << std::setw(24) << "REPRONUM:" << theReproNum << "\n" << pfx << std::setw(24) << "REPLAYREGEN:" << theReplayRegen << "\n" << pfx << std::setw(24) << "STARTCOLUMN:" << theStartColumn << "\n" << pfx << std::setw(24) << "STARTROW:" << theStartRow << "\n" << pfx << std::setw(24) << "ENDSEGMENT:" << theEndSegment << "\n" << pfx << std::setw(24) << "ENDCOLUMN:" << theEndColumn << "\n" << pfx << std::setw(24) << "ENDROW:" << theEndRow << "\n" << pfx << std::setw(24) << "COUNTRY:" << theCountry << "\n" << pfx << std::setw(24) << "WAC:" << theWac << "\n" << pfx << std::setw(24) << "LOCATION:" << theLocation << "\n"; return out; } void ossimNitfStdidcTag::setProperty(ossimRefPtr property) { ossimNitfRegisteredTag::setProperty(property); } ossimRefPtr ossimNitfStdidcTag::getProperty(const ossimString& name)const { ossimProperty* result = 0; if(name == ACQDATE_KW) { result = new ossimStringProperty(name, theAcqDate); } else if(name == MISSION_KW) { result = new ossimStringProperty(name, theMission); } else if(name == PASS_KW) { result = new ossimStringProperty(name, thePass); } else if(name == OPNUM_KW) { result = new ossimStringProperty(name, theOpNum); } else if(name == STARTSEGMENT_KW) { result = new ossimStringProperty(name, theStartSegment); } else if(name == REPRONUM_KW) { result = new ossimStringProperty(name, theReproNum); } else if(name == REPLAYREGEN_KW) { result = new ossimStringProperty(name, theReplayRegen); } else if(name == BLANKFILL_KW) { result = new ossimStringProperty(name, theBlankFill); } else if(name == STARTCOLUMN_KW) { result = new ossimStringProperty(name, theStartColumn); } else if(name == STARTROW_KW) { result = new ossimStringProperty(name, theStartRow); } else if(name == ENDSEGMENT_KW) { result = new ossimStringProperty(name, theEndSegment); } else if(name == ENDCOLUMN_KW) { result = new ossimStringProperty(name, theEndColumn); } else if(name == ENDROW_KW) { result = new ossimStringProperty(name, theEndRow); } else if(name == COUNTRY_KW) { result = new ossimStringProperty(name,theCountry ); } else if(name == WAC_KW) { result = new ossimStringProperty(name, theWac); } else if(name == LOCATION_KW) { result = new ossimStringProperty(name, theLocation); } else { return ossimNitfRegisteredTag::getProperty(name); } return result; } void ossimNitfStdidcTag::getPropertyNames(std::vector& propertyNames)const { ossimNitfRegisteredTag::getPropertyNames(propertyNames); propertyNames.push_back(ACQDATE_KW); propertyNames.push_back(MISSION_KW); propertyNames.push_back(PASS_KW); propertyNames.push_back(OPNUM_KW); propertyNames.push_back(STARTSEGMENT_KW); propertyNames.push_back(REPRONUM_KW); propertyNames.push_back(REPLAYREGEN_KW); propertyNames.push_back(BLANKFILL_KW); propertyNames.push_back(STARTCOLUMN_KW); propertyNames.push_back(STARTROW_KW); propertyNames.push_back(ENDSEGMENT_KW); propertyNames.push_back(ENDCOLUMN_KW); propertyNames.push_back(ENDROW_KW); propertyNames.push_back(COUNTRY_KW); propertyNames.push_back(WAC_KW); propertyNames.push_back(LOCATION_KW); } ossim-Miami-2.9.1/src/support_data/ossimNitfStreobTag.cpp000066400000000000000000000047121352751253100235050ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // // Description: STREOB tag class definition. // // Dataset Indentification TRE. // //---------------------------------------------------------------------------- // $Id #include #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfStreobTag, "ossimNitfStreobTag", ossimNitfRegisteredTag); ossimNitfStreobTag::ossimNitfStreobTag() : ossimNitfRegisteredTag(std::string("STREOB"), 94) { clearFields(); } ossimNitfStreobTag::~ossimNitfStreobTag() { } void ossimNitfStreobTag::parseStream(std::istream& in) { clearFields(); in.read(m_stdId, 60); in.read(n_nMates, 1); in.read(m_mateInstance, 1); in.read(m_bConv, 5); in.read(m_eConv, 5); in.read(m_bAsym, 5); in.read(m_eAsym, 5); in.read(m_bBie, 6); in.read(m_eBie, 6); } void ossimNitfStreobTag::writeStream(std::ostream& out) { out.write(m_stdId, 60); out.write(n_nMates, 1); out.write(m_mateInstance, 1); out.write(m_bConv, 5); out.write(m_eConv, 5); out.write(m_bAsym, 5); out.write(m_eAsym, 5); out.write(m_bBie, 6); out.write(m_eBie, 6); } void ossimNitfStreobTag::clearFields() { // BCS-N's to '0's, BCS-A's to ' '(spaces) memset(m_stdId, '\0', 61); memset(n_nMates, '\0', 2); memset(m_mateInstance, '\0', 2); memset(m_bConv, '\0', 6); memset(m_eConv, '\0', 6); memset(m_bAsym, '\0', 6); memset(m_eAsym, '\0', 7); memset(m_bBie, '\0', 7); } std::ostream& ossimNitfStreobTag::print( std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "ST_ID:" << m_stdId << "\n" << pfx << std::setw(24) << "N_MATES:" << n_nMates << "\n" << pfx << std::setw(24) << "MATE_INSTANCE:" << m_mateInstance << "\n" << pfx << std::setw(24) << "B_CONV:" << m_bConv << "\n" << pfx << std::setw(24) << "E_CONV:" << m_eConv << "\n" << pfx << std::setw(24) << "B_ASYM:" << m_bAsym << "\n" << pfx << std::setw(24) << "E_ASYM:" << m_eAsym << "\n" << pfx << std::setw(24) << "B_BIE:" << m_bBie << "\n"; return out; } ossim-Miami-2.9.1/src/support_data/ossimNitfSymbolHeader.cpp000066400000000000000000000007571352751253100241760ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfSymbolHeader.cpp 9094 2006-06-13 19:12:40Z dburken $ #include RTTI_DEF1(ossimNitfSymbolHeader, "ossimNitfSymbolHeader", ossimObject) ossim-Miami-2.9.1/src/support_data/ossimNitfSymbolHeaderV2_0.cpp000066400000000000000000000166541352751253100246300ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfSymbolHeaderV2_0.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include // for memset #include RTTI_DEF1(ossimNitfSymbolHeaderV2_0, "ossimNitfSymbolHeaderV2_0", ossimNitfSymbolHeader) ossimNitfSymbolHeaderV2_0::ossimNitfSymbolHeaderV2_0() { clearFields(); } void ossimNitfSymbolHeaderV2_0::parseStream(std::istream &in) { if(in) { clearFields(); in.read(theFilePartType, 2); in.read(theSymbolId, 10); in.read(theSymbolName, 20); in.read(theSymbolSecurityClass, 1); in.read(theSymbolCodewords, 40); in.read(theSymbolControlAndHandling, 40); in.read(theSymbolReleasingInstructions, 40); in.read(theSymbolClassificationAuthority, 20); in.read(theSymbolSecurityControlNum, 20); in.read(theSymbolSecurityDowngrade, 6); if(ossimString(theSymbolSecurityDowngrade) == "999998") { in.read(theSymbolDowngradingEvent, 40); } in.read(theSymbolEncryption, 1); in.read(theSymbolType, 1); in.read(theNumberLinesPerSymbol, 4); in.read(theSymbolNumberPixelsPerLine, 4); in.read(theSymbolLineWidth, 4); in.read(theSymbolNumberBitsPerPixel, 1); in.read(theSymbolDisplayLevel, 3); in.read(theSymbolAttachmentLevel, 3); in.read(theSymbolLocation, 10); in.read(theSecondSymbolLocation, 10); in.read(theSymbolColor, 1); in.read(theSymbolNumber, 6); in.read(theSymbolRotation, 3); in.read(theSymbolNumberOfLutEntries, 3); // do lut here. we will temporarily ignore in.ignore(ossimString(theSymbolNumberOfLutEntries).toLong()); in.read(theSymbolExtendedSubheaderDataLength, 5); in.read(theSymbolSubheaderOverflow, 3); } } std::ostream& ossimNitfSymbolHeaderV2_0::print(std::ostream &out)const { out << "theFilePartType: " << theFilePartType << std::endl << "theSymbolId: " << theSymbolId << std::endl << "theSymbolName: " << theSymbolName << std::endl << "theSymbolSecurityClass: " << theSymbolSecurityClass << std::endl << "theSymbolCodewords: " << theSymbolCodewords << std::endl << "theSymbolControlAndHandling: " << theSymbolControlAndHandling << std::endl << "theSymbolReleasingInstructions: " << theSymbolReleasingInstructions << std::endl << "theSymbolClassificationAuthority: " << theSymbolClassificationAuthority << std::endl << "theSymbolSecurityControlNum: " << theSymbolSecurityControlNum << std::endl << "theSymbolSecurityDowngrade: " << theSymbolSecurityDowngrade << std::endl << "theSymbolDowngradingEvent: " << theSymbolDowngradingEvent << std::endl << "theSymbolEncryption: " << theSymbolEncryption << std::endl << "theSymbolType: " << theSymbolType << std::endl << "theNumberLinesPerSymbol: " << theNumberLinesPerSymbol << std::endl << "theSymbolNumberPixelsPerLine: " << theSymbolNumberPixelsPerLine << std::endl << "theSymbolLineWidth: " << theSymbolLineWidth << std::endl << "theSymbolNumberBitsPerPixel: " << theSymbolNumberBitsPerPixel << std::endl << "theSymbolDisplayLevel: " << theSymbolDisplayLevel << std::endl << "theSymbolAttachmentLevel: " << theSymbolAttachmentLevel << std::endl << "theSymbolLocation: " << theSymbolLocation << std::endl << "theSecondSymbolLocation: " << theSecondSymbolLocation << std::endl << "theSymbolColor: " << theSymbolColor << std::endl << "theSymbolNumber: " << theSymbolNumber << std::endl << "theSymbolRotation: " << theSymbolRotation << std::endl << "theSymbolNumberOfLutEntries: " << theSymbolNumberOfLutEntries << std::endl << "theSymbolExtendedSubheaderDataLength: " << theSymbolExtendedSubheaderDataLength << std::endl << "theSymbolSubheaderOverflow: " << theSymbolSubheaderOverflow << std::endl; return out; } ossim_int32 ossimNitfSymbolHeaderV2_0::getDisplayLevel() const { return ossimString(theSymbolDisplayLevel).toInt32(); } ossimDrect ossimNitfSymbolHeaderV2_0::getImageRect()const { // for now we will return an empty rect. This will be more // complicated to compute a symbol bound. The origin depends // on the symbol and is different for different symbols. // We will implement this one last. return ossimDrect(0,0,0,0); } void ossimNitfSymbolHeaderV2_0::clearFields() { memset(theFilePartType, ' ', 2); memset(theSymbolId, ' ', 10); memset(theSymbolName, ' ', 20); memset(theSymbolSecurityClass, ' ', 1); memset(theSymbolCodewords, ' ', 40); memset(theSymbolControlAndHandling, ' ', 40); memset(theSymbolReleasingInstructions, ' ', 40); memset(theSymbolClassificationAuthority, ' ', 20); memset(theSymbolSecurityControlNum, ' ', 20); memset(theSymbolSecurityDowngrade, ' ', 6); memset(theSymbolDowngradingEvent, ' ', 40); memset(theSymbolEncryption, ' ', 1); memset(theSymbolType, ' ', 1); memset(theNumberLinesPerSymbol, ' ', 4); memset(theSymbolNumberPixelsPerLine, ' ', 4); memset(theSymbolLineWidth, ' ', 4); memset(theSymbolNumberBitsPerPixel, ' ', 1); memset(theSymbolDisplayLevel, ' ', 3); memset(theSymbolAttachmentLevel, ' ', 3); memset(theSymbolLocation, ' ', 10); memset(theSecondSymbolLocation, ' ', 10); memset(theSymbolColor, ' ', 1); memset(theSymbolNumber, ' ', 6); memset(theSymbolRotation, ' ', 3); memset(theSymbolNumberOfLutEntries, ' ', 3); memset(theSymbolExtendedSubheaderDataLength, ' ', 5); memset(theSymbolSubheaderOverflow, ' ', 3); theFilePartType[2] = '\0'; theSymbolId[10] = '\0'; theSymbolName[20] = '\0'; theSymbolSecurityClass[1] = '\0'; theSymbolCodewords[40] = '\0'; theSymbolControlAndHandling[40] = '\0'; theSymbolReleasingInstructions[40] = '\0'; theSymbolClassificationAuthority[20] = '\0'; theSymbolSecurityControlNum[20] = '\0'; theSymbolSecurityDowngrade[6] = '\0'; theSymbolDowngradingEvent[40] = '\0'; theSymbolEncryption[1] = '\0'; theSymbolType[1] = '\0'; theNumberLinesPerSymbol[4] = '\0'; theSymbolNumberPixelsPerLine[4] = '\0'; theSymbolLineWidth[4] = '\0'; theSymbolNumberBitsPerPixel[1] = '\0'; theSymbolDisplayLevel[3] = '\0'; theSymbolAttachmentLevel[3] = '\0'; theSymbolLocation[10] = '\0'; theSecondSymbolLocation[10] = '\0'; theSymbolColor[1] = '\0'; theSymbolNumber[6] = '\0'; theSymbolRotation[3] = '\0'; theSymbolNumberOfLutEntries[3] = '\0'; theSymbolExtendedSubheaderDataLength[5] = '\0'; theSymbolSubheaderOverflow[3] ='\0'; } ossim-Miami-2.9.1/src/support_data/ossimNitfTagFactory.cpp000066400000000000000000000011101352751253100236430ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfTagFactory.cpp 9094 2006-06-13 19:12:40Z dburken $ #include RTTI_DEF1(ossimNitfTagFactory, "ossimNitfTagFactory", ossimObject) ossimNitfTagFactory::~ossimNitfTagFactory() { } ossimNitfTagFactory::ossimNitfTagFactory() { } ossim-Miami-2.9.1/src/support_data/ossimNitfTagFactoryRegistry.cpp000066400000000000000000000053011352751253100254020ustar00rootroot00000000000000//******************************************************************* // // LICENSE: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfTagFactoryRegistry.cpp 22875 2014-08-27 13:52:03Z dburken $ #include #include #include #include #include /* for std::find */ ossimNitfTagFactoryRegistry::ossimNitfTagFactoryRegistry() { initializeDefaults(); } ossimNitfTagFactoryRegistry::~ossimNitfTagFactoryRegistry() { } void ossimNitfTagFactoryRegistry::registerFactory(ossimNitfTagFactory* aFactory) { if(aFactory&&!exists(aFactory)) { theFactoryList.push_back(aFactory); } } void ossimNitfTagFactoryRegistry::unregisterFactory (ossimNitfTagFactory* aFactory) { std::vector::iterator iter = std::find(theFactoryList.begin(), theFactoryList.end(), aFactory); if(iter != theFactoryList.end()) { theFactoryList.erase(iter); } } ossimNitfTagFactoryRegistry* ossimNitfTagFactoryRegistry::instance() { static ossimNitfTagFactoryRegistry inst; return &inst; } ossimRefPtr ossimNitfTagFactoryRegistry::create(const ossimString &tagName)const { std::vector::const_iterator factory; ossimRefPtr result = 0; factory = theFactoryList.begin(); while(factory != theFactoryList.end()) { result = (*factory)->create(tagName); if(result.valid()) { return result; } ++factory; } ossimRefPtr tag = new ossimNitfUnknownTag; return tag; } void ossimNitfTagFactoryRegistry::initializeDefaults() { theFactoryList.push_back(ossimNitfRegisteredTagFactory::instance()); theFactoryList.push_back(ossimNitfRpfTagFactory::instance()); } bool ossimNitfTagFactoryRegistry::exists(ossimNitfTagFactory* factory)const { std::vector::const_iterator iter = std::find(theFactoryList.begin(), theFactoryList.end(), factory); return (iter != theFactoryList.end()); } ossimNitfTagFactoryRegistry::ossimNitfTagFactoryRegistry( const ossimNitfTagFactoryRegistry&) { } const ossimNitfTagFactoryRegistry& ossimNitfTagFactoryRegistry::operator=( const ossimNitfTagFactoryRegistry&) { return *this; } ossim-Miami-2.9.1/src/support_data/ossimNitfTagInformation.cpp000066400000000000000000000121071352751253100245310ustar00rootroot00000000000000//******************************************************************* // // LICENSE: MIT // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include // for memset ossimNitfTagInformation::ossimNitfTagInformation(ossimRefPtr tagData) { clearFields(); setTagData(tagData); } ossimNitfTagInformation::~ossimNitfTagInformation() { } void ossimNitfTagInformation::parseStream(ossim::istream& in) { if(in) { clearFields(); theTagOffset = in.tellg(); in.read(theTagName, 6); in.read(theTagLength, 5); theTagDataOffset = in.tellg(); theTagData = ossimNitfTagFactoryRegistry::instance()->create(getTagName()); if (theTagData.valid()) { if (theTagData->getClassName() == "ossimNitfUnknownTag") { // Unknown tag doesn't know his tag name yet. theTagData->setTagName( getTagName() ); } //--- // Tags with dynamic tag length construct with 0 length. // Set if 0. //--- if ( theTagData->getTagLength() == 0 ) { theTagData->setTagLength( getTagLength() ); } // Sanity check fixed length in code with length from CEL field: else if ( theTagData->getTagLength() != getTagLength() ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimNitfTagInformation::parseStream WARNING!" << "\nCEL field length does not match fixed tag length for tag: " << theTagData->getTagName().c_str() << "\nCEL: " << getTagLength() << "\nTag: " << theTagData->getTagLength() << std::endl; } theTagData->parseStream(in); } else { theTagData = (ossimNitfRegisteredTag*)NULL; } } } void ossimNitfTagInformation::writeStream(ossim::ostream &out) { theTagOffset = out.tellp(); // Capture the offset. out.write(theTagName, 6); out.write(theTagLength, 5); if(theTagData.valid()) { theTagDataOffset = out.tellp(); theTagData->writeStream(out); } } ossim_uint32 ossimNitfTagInformation::getTotalTagLength()const { return (getTagLength() + (ossim_uint32)11); } ossim_uint32 ossimNitfTagInformation::getTagLength()const { return ossimString(theTagLength).toUInt32(); } ossim_uint64 ossimNitfTagInformation::getTagOffset()const { return theTagOffset; } ossim_uint64 ossimNitfTagInformation::getTagDataOffset()const { return theTagDataOffset; } ossimString ossimNitfTagInformation::getTagName()const { return ossimString(theTagName).trim(); } std::ostream& ossimNitfTagInformation::print(std::ostream& out)const { out << "theTagName: " << theTagName << "\ntheTagLength: " << theTagLength << "\ntheTagType: " << theTagType << "\ntheTagOffset: " << theTagOffset << "\ntheTagDataOffset: " << theTagDataOffset << std::endl; return out; } void ossimNitfTagInformation::clearFields() { memset(theTagName, ' ', 6); memset(theTagLength, 0, 5); strcpy(theTagType, "IXSHD "); theTagName[6] = '\0'; theTagLength[5] = '\0'; theTagOffset = 0; theTagDataOffset = 0; } void ossimNitfTagInformation::setTagName(const ossimString& tagName) { memset(theTagName, ' ', 6); std::ostringstream out; out << std::setw(6) << std::setfill(' ') << tagName; memcpy(theTagName, out.str().c_str(), 6); } void ossimNitfTagInformation::setTagLength(ossim_uint32 tagLength) { memset(theTagLength, 0, 5); if(tagLength > 99999) { tagLength = 99999; } std::ostringstream out; out << std::setw(5) << std::setfill('0') << tagLength; memcpy(theTagLength, out.str().c_str(), 5); } ossimRefPtr ossimNitfTagInformation::getTagData() { return theTagData; } const ossimRefPtr ossimNitfTagInformation::getTagData()const { return theTagData; } void ossimNitfTagInformation::setTagData(ossimRefPtr tagData) { theTagData = tagData; memset(theTagName, ' ', 6); memset(theTagLength, ' ', 5); if(theTagData.valid()) { setTagName(theTagData->getRegisterTagName()); setTagLength(theTagData->getSizeInBytes()); } } ossimString ossimNitfTagInformation::getTagType() const { return ossimString(theTagType).trim(); } void ossimNitfTagInformation::setTagType(const ossimString& tagType) const { std::ostringstream out; out << std::setw(6) << std::setfill(' ') << std::setiosflags(std::ios::left) << tagType; memcpy(theTagType, out.str().c_str(), 6); theTagType[6] = 0; } ossim-Miami-2.9.1/src/support_data/ossimNitfTextHeader.cpp000066400000000000000000000007471352751253100236540ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfTextHeader.cpp 9094 2006-06-13 19:12:40Z dburken $ #include RTTI_DEF1(ossimNitfTextHeader, "ossimNitfTextHeader", ossimObject) ossim-Miami-2.9.1/src/support_data/ossimNitfTextHeaderV2_0.cpp000066400000000000000000000103371352751253100242770ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfTextHeaderV2_0.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include // for memset #include RTTI_DEF1(ossimNitfTextHeaderV2_0, "ossimNitfTextHeaderV2_0", ossimNitfTextHeader) ossimNitfTextHeaderV2_0::ossimNitfTextHeaderV2_0() { clearFields(); } void ossimNitfTextHeaderV2_0::parseStream(std::istream &in) { if(in) { clearFields(); in.read(theFilePartType, 2); in.read(theTextId, 10); in.read(theDataAndTime, 14); in.read(theTextTitle, 80); in.read(theTextSecurityClassification, 1); in.read(theTextCodewords, 40); in.read(theTextControlAndHandling, 40); in.read(theTextReleasingInstructions, 40); in.read(theTextClassificationAuthority, 20); in.read(theTextSecurityControlNumber, 20); in.read(theTextSecurityDowngrade, 6); if(ossimString(theTextSecurityDowngrade) == "999998") { in.read(theTextSecurityDowngradeEvent, 40); } in.read(theTextEncyption, 1); in.read(theTextFormat, 3); in.read(theExtSubheaderDataLength, 5); long dataLength = ossimString(theExtSubheaderDataLength).toLong(); if(dataLength > 0) { in.read(theExtSubheaderOverflow, 3); // ignore the data for now in.ignore(dataLength - 3); } } } std::ostream& ossimNitfTextHeaderV2_0::print(std::ostream &out)const { out << "theFilePartType: " << theFilePartType << "\ntheTextId: " << theTextId << "\ntheDataAndTime: " << theDataAndTime << "\ntheTextTitle: " << theTextTitle << "\ntheTextSecurityClassification: " << theTextSecurityClassification << "\ntheTextCodewords: " << theTextCodewords << "\ntheTextControlAndHandling: " << theTextControlAndHandling << "\ntheTextReleasingInstructions: " << theTextReleasingInstructions << "\ntheTextClassificationAuthority: " << theTextClassificationAuthority << "\ntheTextSecurityControlNumber: " << theTextSecurityControlNumber << "\ntheTextSecurityDowngrade: " << theTextSecurityDowngrade << "\ntheTextSecurityDowngradeEvent: " << theTextSecurityDowngradeEvent << "\ntheTextEncyption: " << theTextEncyption << "\ntheTextFormat: " << theTextFormat << "\ntheExtSubheaderDataLength: " << theExtSubheaderDataLength << "\ntheExtSubheaderOverflow: " << theExtSubheaderOverflow << std::endl; return out; } void ossimNitfTextHeaderV2_0::clearFields() { memset(theFilePartType, ' ', 2); memset(theTextId, ' ', 10); memset(theDataAndTime, ' ', 14); memset(theTextTitle, ' ', 80); memset(theTextSecurityClassification, ' ', 1); memset(theTextCodewords, ' ', 40); memset(theTextControlAndHandling, ' ', 40); memset(theTextReleasingInstructions, ' ', 40); memset(theTextClassificationAuthority, ' ', 20); memset(theTextSecurityControlNumber, ' ', 20); memset(theTextSecurityDowngrade, ' ', 6); memset(theTextSecurityDowngradeEvent, ' ', 40); memset(theTextEncyption, ' ', 1); memset(theTextFormat, ' ', 3); memset(theExtSubheaderDataLength, ' ', 5); memset(theExtSubheaderOverflow, ' ', 3); theFilePartType[2] = '\0'; theTextId[10] = '\0'; theDataAndTime[14] = '\0'; theTextTitle[80] = '\0'; theTextSecurityClassification[1] = '\0'; theTextCodewords[40] = '\0'; theTextControlAndHandling[40] = '\0'; theTextReleasingInstructions[40] = '\0'; theTextClassificationAuthority[20] = '\0'; theTextSecurityControlNumber[20] = '\0'; theTextSecurityDowngrade[6] = '\0'; theTextSecurityDowngradeEvent[40] = '\0'; theTextEncyption[1] = '\0'; theTextFormat[3] = '\0'; theExtSubheaderDataLength[5] = '\0'; theExtSubheaderOverflow[3] = '\0'; } ossim-Miami-2.9.1/src/support_data/ossimNitfTextHeaderV2_1.cpp000066400000000000000000000260311352751253100242760ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id$ #include #include #include #include #include #include // for memset #include RTTI_DEF1(ossimNitfTextHeaderV2_1, "ossimNitfTextHeaderV2_1", ossimNitfTextHeader) const ossimString ossimNitfTextHeaderV2_1::TE_KW = "te"; const ossimString ossimNitfTextHeaderV2_1::TEXTID_KW = "textid"; const ossimString ossimNitfTextHeaderV2_1::TXTALVL_KW = "txtalvl"; const ossimString ossimNitfTextHeaderV2_1::TXTDT_KW = "txtdt"; const ossimString ossimNitfTextHeaderV2_1::TXTITL_KW = "txtitl"; const ossimString ossimNitfTextHeaderV2_1::TSCLAS_KW = "tsclas"; const ossimString ossimNitfTextHeaderV2_1::TSCLSY_KW = "tsclsy"; const ossimString ossimNitfTextHeaderV2_1::TSCODE_KW = "tscode"; const ossimString ossimNitfTextHeaderV2_1::TSCTLH_KW = "tsctlh"; const ossimString ossimNitfTextHeaderV2_1::TSREL_KW = "tsrel"; const ossimString ossimNitfTextHeaderV2_1::TSDCTP_KW = "tsdctp"; const ossimString ossimNitfTextHeaderV2_1::TSDCDT_KW = "tsdcdt"; const ossimString ossimNitfTextHeaderV2_1::TSDCXM_KW = "tsdcxm"; const ossimString ossimNitfTextHeaderV2_1::TSDG_KW = "tsdg"; const ossimString ossimNitfTextHeaderV2_1::TSDGDT_KW = "tsdgdt"; const ossimString ossimNitfTextHeaderV2_1::TSCLTX_KW = "tscltx"; const ossimString ossimNitfTextHeaderV2_1::TSCATP_KW = "tscatp"; const ossimString ossimNitfTextHeaderV2_1::TSCAUT_KW = "tscaut"; const ossimString ossimNitfTextHeaderV2_1::TSCRSN_KW = "tscrsn"; const ossimString ossimNitfTextHeaderV2_1::TSSRDT_KW = "tssrdt"; const ossimString ossimNitfTextHeaderV2_1::TSCTLN_KW = "tsctln"; const ossimString ossimNitfTextHeaderV2_1::ENCRYP_KW = "encryp"; const ossimString ossimNitfTextHeaderV2_1::TXTFMT_KW = "txtfmt"; const ossimString ossimNitfTextHeaderV2_1::TXSHDL_KW = "txshdl"; const ossimString ossimNitfTextHeaderV2_1::TXSOFL_KW = "txsofl"; const ossimString ossimNitfTextHeaderV2_1::TXSHD_KW = "txshd"; ossimNitfTextHeaderV2_1::ossimNitfTextHeaderV2_1() { clearFields(); } ossimNitfTextHeaderV2_1::~ossimNitfTextHeaderV2_1() { } void ossimNitfTextHeaderV2_1::parseStream(std::istream &in) { if(in) { clearFields(); in.read(theFilePartType, 2); in.read(theTextId, 7); in.read(theTextAttLevel, 3); in.read(theDataAndTime, 14); in.read(theTextTitle, 80); in.read(theTextSecurityClassification, 1); // If text class is T,S,C, or R, need to have TSCLSY populated with valid code in.read(theTextSecuritySystem, 2); in.read(theTextCodewords, 11); in.read(theTextControlAndHandling, 2); in.read(theTextReleasingInstructions, 20); in.read(theTextDeclassificationType, 2); in.read(theTextDeclassificationDate, 8); in.read(theTextDeclassificationExemption, 4); in.read(theTextSecurityDowngrade, 2); in.read(theTextSecurityDowngradeDate, 8); in.read(theTextClassificationText, 43); // TSCLTX in.read(theTextClassificationAthorityType, 1); // TSCATP in.read(theTextClassificationAthority, 40); // TSCAUT in.read(theTextClassificationReason, 1); // TSCRSN in.read(theTextSecuritySourceDate, 8); // TSSRDT in.read(theTextSecurityControlNumber, 15); // TSCTLN in.read(theTextEncyption, 1); in.read(theTextFormat, 3); in.read(theExtSubheaderDataLength, 5); long dataLength = ossimString(theExtSubheaderDataLength).toLong(); if(dataLength > 0) { in.read(theExtSubheaderOverflow, 3); // ignore the data for now in.ignore(dataLength - 3); } } } std::ostream& ossimNitfTextHeaderV2_1::print(std::ostream &out)const { out << "theFilePartType: " << theFilePartType << "\ntheTextId: " << theTextId << "\ntheTextAttLevel: " << theTextAttLevel << "\ntheDataAndTime: " << theDataAndTime << "\ntheTextTitle: " << theTextTitle << "\ntheTextSecurityClassification: " << theTextSecurityClassification << "\ntheTextSecuritySystem: " << theTextSecuritySystem << "\ntheTextCodewords: " << theTextCodewords << "\ntheTextControlAndHandling: " << theTextControlAndHandling << "\ntheTextReleasingInstructions: " << theTextReleasingInstructions << "\ntheTextDeclassificationType: " << theTextDeclassificationType << "\ntheTextDeclassificationDate: " << theTextDeclassificationDate << "\ntheTextDeclassificationExemption: " << theTextDeclassificationExemption << "\ntheTextSecurityDowngrade: " << theTextSecurityDowngrade << "\ntheTextSecurityDowngradeDate: " << theTextSecurityDowngradeDate << "\ntheTextClassificationText: " << theTextClassificationText << "\ntheTextClassificationAthorityType: " << theTextClassificationAthorityType << "\ntheTextClassificationAthority: " << theTextClassificationAthority << "\ntheTextClassificationReason: " << theTextClassificationReason << "\ntheTextSecuritySourceDate: " << theTextSecuritySourceDate << "\ntheTextSecurityControlNumber: " << theTextSecurityControlNumber << "\ntheTextEncyption: " << theTextEncyption << "\ntheTextFormat: " << theTextFormat << "\ntheExtSubheaderDataLength: " << theExtSubheaderDataLength << "\ntheExtSubheaderOverflow: " << theExtSubheaderOverflow << std::endl; return out; } void ossimNitfTextHeaderV2_1::clearFields() { memset(theFilePartType,' ', 2); memset(theTextId,' ', 7); memset(theTextAttLevel,' ', 3); memset(theDataAndTime,' ', 14); memset(theTextTitle,' ', 80); memset(theTextSecurityClassification, ' ',1); // If text class is T,S,C, or R, need to have TSCLSY populated with valid code memset(theTextSecuritySystem, ' ', 2); memset(theTextCodewords, ' ',11); memset(theTextControlAndHandling,' ', 2); memset(theTextReleasingInstructions,' ', 20); memset(theTextDeclassificationType,' ', 2); memset(theTextDeclassificationDate, ' ',8); memset(theTextDeclassificationExemption,' ', 4); memset(theTextSecurityDowngrade, ' ',2); memset(theTextSecurityDowngradeDate, ' ',8); memset(theTextClassificationText, ' ',43); // TSCLTX memset(theTextClassificationAthorityType, ' ',1); // TSCATP memset(theTextClassificationAthority, ' ',40); // TSCAUT memset(theTextClassificationReason, ' ',1); //TSCRSN memset(theTextSecuritySourceDate,' ', 8); //TSSRDT memset(theTextSecurityControlNumber, ' ',15); // TSCTLN memset(theTextEncyption, ' ',1); memset(theTextFormat, ' ',3); memset(theExtSubheaderDataLength, ' ',5); memset(theExtSubheaderOverflow, ' ',3); theFilePartType[2] = '\0'; theTextId[7] = '\0'; theTextAttLevel[3] = '\0'; theDataAndTime[14] = '\0'; theTextTitle[80] = '\0'; theTextSecurityClassification[1] = '\0'; theTextSecuritySystem[2] = '\0'; theTextCodewords[11] = '\0'; theTextControlAndHandling[2] = '\0'; theTextReleasingInstructions[20] = '\0'; theTextDeclassificationType[2] = '\0'; theTextDeclassificationDate[8] = '\0'; theTextDeclassificationExemption[4] = '\0'; theTextSecurityDowngrade[1] = '\0'; theTextSecurityDowngradeDate[8] = '\0';; theTextClassificationText[43] = '\0';; theTextClassificationAthorityType[1] = '\0'; theTextClassificationAthority[40] = '\0'; theTextClassificationReason[1] = '\0'; theTextSecuritySourceDate[8] = '\0'; theTextSecurityControlNumber[15] = '\0'; theTextEncyption[1] = '\0'; theTextFormat[3] = '\0'; theExtSubheaderDataLength[5] = '\0'; theExtSubheaderOverflow[3] = '\0'; } void ossimNitfTextHeaderV2_1::writeStream(std::ostream &out) { out.write(theFilePartType, 2); out.write(theTextId, 7); out.write(theTextAttLevel, 3); out.write(theDataAndTime, 14); out.write(theTextTitle, 80); out.write(theTextSecurityClassification, 1); // If text class is T,S,C, or R, need to have TSCLSY populated with valid code out.write(theTextSecuritySystem, 2); out.write(theTextCodewords, 11); out.write(theTextControlAndHandling, 2); out.write(theTextReleasingInstructions, 20); out.write(theTextDeclassificationType, 2); out.write(theTextDeclassificationDate, 8); out.write(theTextDeclassificationExemption, 4); out.write(theTextSecurityDowngrade, 2); out.write(theTextSecurityDowngradeDate, 8); out.write(theTextClassificationText, 43); // TSCLTX out.write(theTextClassificationAthorityType, 1); // TSCATP out.write(theTextClassificationAthority, 40); // TSCAUT out.write(theTextClassificationReason, 1); // TSCRSN out.write(theTextSecuritySourceDate, 8); // TSSRDT out.write(theTextSecurityControlNumber, 15); // TSCTLN out.write(theTextEncyption, 1); out.write(theTextFormat, 3); out.write(theExtSubheaderDataLength, 5); long dataLength = ossimString(theExtSubheaderDataLength).toLong(); if(dataLength > 0) { out.write(theExtSubheaderOverflow, 3); } } /* void ossimNitfTextHeaderV2_1::getPropertyNames(std::vector& propertyNames)const { propertyNames.push_back(ISCLSY_KW); propertyNames.push_back(ISCODE_KW); propertyNames.push_back(ISCTLH_KW); propertyNames.push_back(ISREL_KW); propertyNames.push_back(ISDCTP_KW); propertyNames.push_back(ISDCDT_KW); propertyNames.push_back(ISDCXM_KW); propertyNames.push_back(ISDG_KW); propertyNames.push_back(ISDGDT_KW); propertyNames.push_back(ISCLTX_KW); propertyNames.push_back(ISCATP_KW); propertyNames.push_back(ISCAUT_KW); propertyNames.push_back(ISCRSN_KW); propertyNames.push_back(ISSRDT_KW); propertyNames.push_back(ISCTLN_KW); propertyNames.push_back(XBANDS_KW); } */ void ossimNitfTextHeaderV2_1::setSecurityClassification(const ossimString& value) { ossimNitfCommon::setField(theTextSecurityClassification, value, 1); } void ossimNitfTextHeaderV2_1::setSecurityClassificationSystem(const ossimString& value) { ossimNitfCommon::setField(theTextSecuritySystem, value, 2); } void ossimNitfTextHeaderV2_1::setCodewords(const ossimString& value) { ossimNitfCommon::setField(theTextCodewords, value, 11); } void ossimNitfTextHeaderV2_1::setControlAndHandling(const ossimString& value) { ossimNitfCommon::setField(theTextControlAndHandling, value, 2); } void ossimNitfTextHeaderV2_1::setReleasingInstructions(const ossimString& value) { ossimNitfCommon::setField(theTextReleasingInstructions, value, 20); } void ossimNitfTextHeaderV2_1::setDeclassificationType(const ossimString& value) { ossimNitfCommon::setField(theTextDeclassificationType, value, 2); } ossim-Miami-2.9.1/src/support_data/ossimNitfUnknownTag.cpp000066400000000000000000000057051352751253100237110ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Unknown tag class declaration. // // Note: By "unknown" this means that the tag name was not found in any of // the tag factories. // //---------------------------------------------------------------------------- // $Id: ossimNitfUnknownTag.cpp 22013 2012-12-19 17:37:20Z dburken $ #include #include #include /* for isascii */ #include #include using namespace std; RTTI_DEF1(ossimNitfUnknownTag, "ossimNitfUnknownTag", ossimNitfRegisteredTag); ossimNitfUnknownTag::ossimNitfUnknownTag() : m_tagData(0) { } ossimNitfUnknownTag::~ossimNitfUnknownTag() { if (m_tagData) { delete [] m_tagData; m_tagData = 0; } } void ossimNitfUnknownTag::parseStream(std::istream& in) { if (m_tagLength) { if (m_tagData) { delete [] m_tagData; } m_tagData = new char[m_tagLength+1]; in.read(m_tagData, m_tagLength); m_tagData[m_tagLength] = '\0'; } } void ossimNitfUnknownTag::writeStream(std::ostream& out) { if (m_tagLength && m_tagData) { out.write(m_tagData, m_tagLength); } } void ossimNitfUnknownTag::clearFields() { if (m_tagData) { delete [] m_tagData; m_tagData = 0; } } std::ostream& ossimNitfUnknownTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "unformatted_tag_data: "; if (tagDataIsAscii()) { if (tagDataIsXml()) out << "" << "\n"; else out << m_tagData << "\n"; } else { out << "binary not displayed\n"; } return out; } bool ossimNitfUnknownTag::tagDataIsXml() const { ossimString xmlTest = " #include #include #include #include using namespace std; RTTI_DEF1(ossimNitfUse00aTag, "ossimNitfUse00aTag", ossimNitfRegisteredTag); static const ossimString ANGLETONORTH_KW = "ANGLETONORTH"; static const ossimString MEANGSD_KW = "MEANGSD"; static const ossimString DYNAMICRANGE_KW = "DYNAMICRANGE"; static const ossimString OBLANG_KW = "OBLANG"; static const ossimString ROLLANG_KW = "ROLLANG"; static const ossimString NREF_KW = "NREF"; static const ossimString REVNUM_KW = "REVNUM"; static const ossimString NSEG_KW = "NSEG"; static const ossimString MAXLPSEG_KW = "MAXLPSEG"; static const ossimString SUNEL_KW = "SUNEL"; static const ossimString SUNAZ_KW = "SUNAZ"; ossimNitfUse00aTag::ossimNitfUse00aTag() : ossimNitfRegisteredTag(std::string("USE00A"), 107) { clearFields(); } ossimNitfUse00aTag::~ossimNitfUse00aTag() { } void ossimNitfUse00aTag::parseStream(std::istream& in) { clearFields(); in.read(theAngleToNorth, ANGLE_TO_NORTH_SIZE); in.read(theMeanGsd, MEAN_GSD_SIZE); in.read(theField3, FIELD3_SIZE); in.read(theDynamicRange, DYNAMIC_RANGE_SIZE); in.read(theField5, FIELD5_SIZE); in.read(theField6, FIELD6_SIZE); in.read(theField7, FIELD7_SIZE); in.read(theOblAng, OBL_ANG_SIZE); in.read(theRollAng, ROLL_ANG_SIZE); in.read(theField10, FIELD10_SIZE); in.read(theField11, FIELD11_SIZE); in.read(theField12, FIELD12_SIZE); in.read(theField13, FIELD13_SIZE); in.read(theField14, FIELD14_SIZE); in.read(theField15, FIELD15_SIZE); in.read(theField16, FIELD16_SIZE); in.read(theNRef, N_REF_SIZE); in.read(theRevNum, REV_NUM_SIZE); in.read(theNSeg, N_SEG_SIZE); in.read(theMaxLpSeg, MAX_LP_SEG_SIZE); in.read(theField20, FIELD20_SIZE); in.read(theField21, FIELD21_SIZE); in.read(theSunEl, SUN_EL_SIZE); in.read(theSunAz, SUN_AZ_SIZE); } void ossimNitfUse00aTag::writeStream(std::ostream& out) { out.write(theAngleToNorth, ANGLE_TO_NORTH_SIZE); out.write(theMeanGsd, MEAN_GSD_SIZE); out.write(theField3, FIELD3_SIZE); out.write(theDynamicRange, DYNAMIC_RANGE_SIZE); out.write(theField5, FIELD5_SIZE); out.write(theField6, FIELD6_SIZE); out.write(theField7, FIELD7_SIZE); out.write(theOblAng, OBL_ANG_SIZE); out.write(theRollAng, ROLL_ANG_SIZE); out.write(theField10, FIELD10_SIZE); out.write(theField11, FIELD11_SIZE); out.write(theField12, FIELD12_SIZE); out.write(theField13, FIELD13_SIZE); out.write(theField14, FIELD14_SIZE); out.write(theField15, FIELD15_SIZE); out.write(theField16, FIELD16_SIZE); out.write(theNRef, N_REF_SIZE); out.write(theRevNum, REV_NUM_SIZE); out.write(theNSeg, N_SEG_SIZE); out.write(theMaxLpSeg, MAX_LP_SEG_SIZE); out.write(theField20, FIELD20_SIZE); out.write(theField21, FIELD21_SIZE); out.write(theSunEl, SUN_EL_SIZE); out.write(theSunAz, SUN_AZ_SIZE); } void ossimNitfUse00aTag::clearFields() { memset(theAngleToNorth, ' ', ANGLE_TO_NORTH_SIZE); memset(theMeanGsd, ' ', MEAN_GSD_SIZE); memset(theField3, ' ', FIELD3_SIZE); memset(theDynamicRange, ' ', DYNAMIC_RANGE_SIZE); memset(theField5, ' ', FIELD5_SIZE); memset(theField6, ' ', FIELD6_SIZE); memset(theField7, ' ', FIELD7_SIZE); memset(theOblAng, ' ', OBL_ANG_SIZE); memset(theRollAng, ' ', ROLL_ANG_SIZE); memset(theField10, ' ', FIELD10_SIZE); memset(theField11, ' ', FIELD11_SIZE); memset(theField12, ' ', FIELD12_SIZE); memset(theField13, ' ', FIELD13_SIZE); memset(theField14, ' ', FIELD14_SIZE); memset(theField15, ' ', FIELD15_SIZE); memset(theField16, ' ', FIELD16_SIZE); memset(theNRef, ' ', N_REF_SIZE); memset(theRevNum, ' ', REV_NUM_SIZE); memset(theNSeg, ' ', N_SEG_SIZE); memset(theMaxLpSeg, ' ', MAX_LP_SEG_SIZE); memset(theField20, ' ', FIELD20_SIZE); memset(theField21, ' ', FIELD21_SIZE); memset(theSunEl, ' ', SUN_EL_SIZE); memset(theSunAz, ' ', SUN_AZ_SIZE); theAngleToNorth[ANGLE_TO_NORTH_SIZE] = '\0'; theMeanGsd[MEAN_GSD_SIZE] = '\0'; theField3[FIELD3_SIZE] = '\0'; theDynamicRange[DYNAMIC_RANGE_SIZE] = '\0'; theField5[FIELD5_SIZE] = '\0'; theField6[FIELD6_SIZE] = '\0'; theField7[FIELD7_SIZE] = '\0'; theOblAng[OBL_ANG_SIZE] = '\0'; theRollAng[ROLL_ANG_SIZE] = '\0'; theField10[FIELD10_SIZE] = '\0'; theField11[FIELD11_SIZE] = '\0'; theField12[FIELD12_SIZE] = '\0'; theField13[FIELD13_SIZE] = '\0'; theField14[FIELD14_SIZE] = '\0'; theField15[FIELD15_SIZE] = '\0'; theField16[FIELD16_SIZE] = '\0'; theNRef[N_REF_SIZE] = '\0'; theRevNum[REV_NUM_SIZE] = '\0'; theNSeg[N_SEG_SIZE] = '\0'; theMaxLpSeg[MAX_LP_SEG_SIZE] = '\0'; theField20[FIELD20_SIZE] = '\0'; theField21[FIELD21_SIZE] = '\0'; theSunEl[SUN_EL_SIZE] = '\0'; theSunAz[SUN_AZ_SIZE] = '\0'; } ossimString ossimNitfUse00aTag::getAngleToNorth()const { return theAngleToNorth; } void ossimNitfUse00aTag::setAngleToNorth(const ossimString& angleToNorth) { memset(theAngleToNorth, ' ', ANGLE_TO_NORTH_SIZE); memcpy(theAngleToNorth, angleToNorth.c_str(), std::min((size_t)ANGLE_TO_NORTH_SIZE, angleToNorth.length())); } ossimString ossimNitfUse00aTag::getMeanGsd()const { return theMeanGsd; } ossim_float64 ossimNitfUse00aTag::getMeanGsdInMeters() const { ossim_float64 gsd = 0.0; ossimString s = theMeanGsd; if (s.size()) { ossim_float64 d = s.toFloat64(); if ( (d != 0.0) && (ossim::isnan(d) == false) ) { gsd = d / 12.0 * MTRS_PER_FT; } } return gsd; } void ossimNitfUse00aTag::setMeanGsd(const ossimString& meanGsd) { memset(theMeanGsd, ' ', MEAN_GSD_SIZE); memcpy(theMeanGsd, meanGsd.c_str(), std::min((size_t)MEAN_GSD_SIZE, meanGsd.length())); } ossimString ossimNitfUse00aTag::getField3()const { return theField3; } void ossimNitfUse00aTag::setField3(const ossimString& field3) { memset(theField3, ' ', FIELD3_SIZE); memcpy(theField3, field3.c_str(), std::min((size_t)FIELD3_SIZE, field3.length())); } ossimString ossimNitfUse00aTag::getDynamicRange()const { return theDynamicRange; } void ossimNitfUse00aTag::setDynamicRange(const ossimString& dynamicRange) { memset(theDynamicRange, ' ', DYNAMIC_RANGE_SIZE); memcpy(theDynamicRange, dynamicRange.c_str(), std::min((size_t)DYNAMIC_RANGE_SIZE, dynamicRange.length())); } ossimString ossimNitfUse00aTag::getField5()const { return theField5; } void ossimNitfUse00aTag::setField5(const ossimString& field5) { memset(theField5, ' ', FIELD5_SIZE); memcpy(theField5, field5.c_str(), std::min((size_t)FIELD5_SIZE, field5.length())); } ossimString ossimNitfUse00aTag::getField6()const { return theField6; } void ossimNitfUse00aTag::setField6(const ossimString& field6) { memset(theField6, ' ', FIELD6_SIZE); memcpy(theField6, field6.c_str(), std::min((size_t)FIELD6_SIZE, field6.length())); } ossimString ossimNitfUse00aTag::getField7()const { return theField7; } void ossimNitfUse00aTag::setField7(const ossimString& field7) { memset(theField7, ' ', FIELD7_SIZE); memcpy(theField7, field7.c_str(), std::min((size_t)FIELD7_SIZE, field7.length())); } ossimString ossimNitfUse00aTag::getOblAng()const { return theOblAng; } void ossimNitfUse00aTag::setOblAng(const ossimString& oblAng) { memset(theOblAng, ' ', OBL_ANG_SIZE); memcpy(theOblAng, oblAng.c_str(), std::min((size_t)OBL_ANG_SIZE, oblAng.length())); } ossimString ossimNitfUse00aTag::getRollAng()const { return theRollAng; } void ossimNitfUse00aTag::setRollAng(const ossimString& rollAng) { memset(theRollAng, ' ', ROLL_ANG_SIZE); memcpy(theRollAng, rollAng.c_str(), std::min((size_t)ROLL_ANG_SIZE, rollAng.length())); } ossimString ossimNitfUse00aTag::getField10()const { return theField10; } void ossimNitfUse00aTag::setField10(const ossimString& field10) { memset(theField10, ' ', FIELD10_SIZE); memcpy(theField10, field10.c_str(), std::min((size_t)FIELD10_SIZE, field10.length())); } ossimString ossimNitfUse00aTag::getField11()const { return theField11; } void ossimNitfUse00aTag::setField11(const ossimString& field11) { memset(theField11, ' ', FIELD11_SIZE); memcpy(theField11, field11.c_str(), std::min((size_t)FIELD11_SIZE, field11.length())); } ossimString ossimNitfUse00aTag::getField12()const { return theField12; } void ossimNitfUse00aTag::setField12(const ossimString& field12) { memset(theField12, ' ', FIELD12_SIZE); memcpy(theField12, field12.c_str(), std::min((size_t)FIELD12_SIZE, field12.length())); } ossimString ossimNitfUse00aTag::getField13()const { return theField13; } void ossimNitfUse00aTag::setField13(const ossimString& field13) { memset(theField13, ' ', FIELD13_SIZE); memcpy(theField13, field13.c_str(), std::min((size_t)FIELD13_SIZE, field13.length())); } ossimString ossimNitfUse00aTag::getField14()const { return theField14; } void ossimNitfUse00aTag::setField14(const ossimString& field14) { memset(theField14, ' ', FIELD14_SIZE); memcpy(theField14, field14.c_str(), std::min((size_t)FIELD14_SIZE, field14.length())); } ossimString ossimNitfUse00aTag::getField15()const { return theField15; } void ossimNitfUse00aTag::setField15(const ossimString& field15) { memset(theField15, ' ', FIELD15_SIZE); memcpy(theField15, field15.c_str(), std::min((size_t)FIELD15_SIZE, field15.length())); } ossimString ossimNitfUse00aTag::getField16()const { return theField16; } void ossimNitfUse00aTag::setField16(const ossimString& field16) { memset(theField16, ' ', FIELD16_SIZE); memcpy(theField16, field16.c_str(), std::min((size_t)FIELD16_SIZE, field16.length())); } ossimString ossimNitfUse00aTag::getNRef()const { return theNRef; } void ossimNitfUse00aTag::setNRef(const ossimString& nRef) { memset(theNRef, ' ', N_REF_SIZE); memcpy(theNRef, nRef.c_str(), std::min((size_t)N_REF_SIZE, nRef.length())); } ossimString ossimNitfUse00aTag::getRevNum()const { return theRevNum; } void ossimNitfUse00aTag::setRevNum(const ossimString& revNum) { memset(theRevNum, ' ', REV_NUM_SIZE); memcpy(theRevNum, revNum.c_str(), std::min((size_t)REV_NUM_SIZE, revNum.length())); } ossimString ossimNitfUse00aTag::getNSeg()const { return theNSeg; } void ossimNitfUse00aTag::setNSeg(const ossimString& nSeg) { memset(theNSeg, ' ', N_SEG_SIZE); memcpy(theNSeg, nSeg.c_str(), std::min((size_t)N_SEG_SIZE, nSeg.length())); } ossimString ossimNitfUse00aTag::getMaxLpSeg()const { return theMaxLpSeg; } void ossimNitfUse00aTag::setMaxLpSeg(const ossimString& maxLpSeg) { memset(theMaxLpSeg, ' ', MAX_LP_SEG_SIZE); memcpy(theMaxLpSeg, maxLpSeg.c_str(), std::min((size_t)MAX_LP_SEG_SIZE, maxLpSeg.length())); } ossimString ossimNitfUse00aTag::getField20()const { return theField20; } void ossimNitfUse00aTag::setField20(const ossimString& field20) { memset(theField20, ' ', FIELD20_SIZE); memcpy(theField20, field20.c_str(), std::min((size_t)FIELD20_SIZE, field20.length())); } ossimString ossimNitfUse00aTag::getField21()const { return theField21; } void ossimNitfUse00aTag::setField21(const ossimString& field21) { memset(theField21, ' ', FIELD21_SIZE); memcpy(theField21, field21.c_str(), std::min((size_t)FIELD21_SIZE, field21.length())); } ossimString ossimNitfUse00aTag::getSunEl()const { return theSunEl; } void ossimNitfUse00aTag::setSunEl(const ossimString& sunEl) { memset(theSunEl, ' ', SUN_EL_SIZE); memcpy(theSunEl, sunEl.c_str(), std::min((size_t)SUN_EL_SIZE, sunEl.length())); } ossimString ossimNitfUse00aTag::getSunAz()const { return theSunAz; } void ossimNitfUse00aTag::setSunAz(const ossimString& sunAz) { memset(theSunAz, ' ', SUN_AZ_SIZE); memcpy(theSunAz, sunAz.c_str(), std::min((size_t)SUN_AZ_SIZE, sunAz.length())); } std::ostream& ossimNitfUse00aTag::print(std::ostream& out, const std::string& prefix) const { std::string pfx = prefix; pfx += getTagName(); pfx += "."; out << setiosflags(std::ios::left) << pfx << std::setw(24) << "CETAG:" << getTagName() << "\n" << pfx << std::setw(24) << "CEL:" << getTagLength() << "\n" << pfx << std::setw(24) << "ANGLETONORTH:" << theAngleToNorth << "\n" << pfx << std::setw(24) << "MEANGSD:" << theMeanGsd << "\n" << pfx << std::setw(24) << "DYNAMICRANGE:" << theDynamicRange << "\n" << pfx << std::setw(24) << "OBLANG:" << theOblAng << "\n" << pfx << std::setw(24) << "ROLLANG:" << theRollAng << "\n" << pfx << std::setw(24) << "NREF:" << theNRef << "\n" << pfx << std::setw(24) << "REVNUM:" << theRevNum << "\n" << pfx << std::setw(24) << "NSEG:" << theNSeg << "\n" << pfx << std::setw(24) << "MAXLPSEG:" << theMaxLpSeg << "\n" << pfx << std::setw(24) << "SUNEL:" << theSunEl << "\n" << pfx << std::setw(24) << "SUNAZ:" << theSunAz << "\n"; return out; } void ossimNitfUse00aTag::setProperty(ossimRefPtr property) { ossimNitfRegisteredTag::setProperty(property); } ossimRefPtr ossimNitfUse00aTag::getProperty(const ossimString& name)const { ossimProperty* result = 0; if(name == ANGLETONORTH_KW) { result = new ossimStringProperty(name, theAngleToNorth); } else if(name == MEANGSD_KW) { result = new ossimStringProperty(name, theMeanGsd); } else if(name == DYNAMICRANGE_KW) { result = new ossimStringProperty(name, theDynamicRange); } else if(name == OBLANG_KW) { result = new ossimStringProperty(name, theOblAng); } else if(name == ROLLANG_KW) { result = new ossimStringProperty(name, theRollAng); } else if(name == NREF_KW) { result = new ossimStringProperty(name, theNRef); } else if(name == REVNUM_KW) { result = new ossimStringProperty(name, theRevNum); } else if(name == NSEG_KW) { result = new ossimStringProperty(name, theNSeg); } else if(name == MAXLPSEG_KW) { result = new ossimStringProperty(name, theMaxLpSeg); } else if(name == SUNEL_KW) { result = new ossimStringProperty(name, theSunEl); } else if(name == SUNAZ_KW) { result = new ossimStringProperty(name, theSunAz); } else { return ossimNitfRegisteredTag::getProperty(name); } return result; } void ossimNitfUse00aTag::getPropertyNames(std::vector& propertyNames)const { ossimNitfRegisteredTag::getPropertyNames(propertyNames); propertyNames.push_back(ANGLETONORTH_KW); propertyNames.push_back(MEANGSD_KW); propertyNames.push_back(DYNAMICRANGE_KW); propertyNames.push_back(OBLANG_KW); propertyNames.push_back(ROLLANG_KW); propertyNames.push_back(NREF_KW); propertyNames.push_back(REVNUM_KW); propertyNames.push_back(NSEG_KW); propertyNames.push_back(MAXLPSEG_KW); propertyNames.push_back(SUNEL_KW); propertyNames.push_back(SUNAZ_KW); } ossim-Miami-2.9.1/src/support_data/ossimNitfVqCompressionHeader.cpp000066400000000000000000000266011352751253100255350ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2004 Garrett Potts // // LICENSE: LGPL see top level LICENSE.txt for more details // // Author: Garrett Potts // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfVqCompressionHeader.cpp 19682 2011-05-31 14:21:20Z dburken $ #include #include #include #include #include #include #include RTTI_DEF1(ossimNitfVqCompressionHeader, "ossimNitfVqCompressionHeader", ossimNitfCompressionHeader); #if 0 std::ostream& operator<<(std::ostream& out, const ossimNitfVqCompressionOffsetTableData& data) { out << "theTableId: " << data.theTableId << std::endl << "theNumberOfCompressionLookupRecords: " << data.theNumberOfCompressionLookupRecords << std::endl << "theNumberOfValuesPerCompressionLookup: " << data.theNumberOfValuesPerCompressionLookup << std::endl << "theCompressionLookupValueBitLength: " << data.theCompressionLookupValueBitLength<< std::endl << "theCompressionLookupTableOffset: " << data.theCompressionLookupTableOffset; return out; } #endif ossimNitfVqCompressionOffsetTableData::ossimNitfVqCompressionOffsetTableData() :theData(NULL) { clearFields(); } ossimNitfVqCompressionOffsetTableData::ossimNitfVqCompressionOffsetTableData(const ossimNitfVqCompressionOffsetTableData& rhs) :theTableId(rhs.theTableId), theNumberOfCompressionLookupRecords(rhs.theNumberOfCompressionLookupRecords), theNumberOfValuesPerCompressionLookup(rhs.theNumberOfValuesPerCompressionLookup), theCompressionLookupValueBitLength(rhs.theCompressionLookupValueBitLength), theCompressionLookupTableOffset(rhs.theCompressionLookupTableOffset), theData(NULL) { ossim_uint32 size = (theNumberOfValuesPerCompressionLookup* theNumberOfCompressionLookupRecords* theCompressionLookupValueBitLength)/8; if(size > 0) { theData = new unsigned char[size]; if(rhs.theData) { memcpy(theData, rhs.theData, size); } } } ossimNitfVqCompressionOffsetTableData::~ossimNitfVqCompressionOffsetTableData() { if(theData) { delete [] theData; theData = NULL; } } const ossimNitfVqCompressionOffsetTableData& ossimNitfVqCompressionOffsetTableData::operator =(const ossimNitfVqCompressionOffsetTableData& rhs) { if(this != &rhs) { if(theData) { delete [] theData; theData = NULL; } theTableId = rhs.theTableId; theNumberOfCompressionLookupRecords = rhs.theNumberOfCompressionLookupRecords; theCompressionLookupValueBitLength = rhs.theCompressionLookupValueBitLength; theNumberOfValuesPerCompressionLookup = rhs.theNumberOfValuesPerCompressionLookup; theCompressionLookupTableOffset = rhs.theCompressionLookupTableOffset; if(rhs.theData) { ossim_uint32 size = (theNumberOfValuesPerCompressionLookup* theNumberOfCompressionLookupRecords* theCompressionLookupValueBitLength)/8; if(size > 0) { theData = new unsigned char[size]; memcpy(theData, rhs.theData, size); } } } return *this; } ossim_uint32 ossimNitfVqCompressionOffsetTableData::getDataLengthInBytes()const { return (theNumberOfValuesPerCompressionLookup* theNumberOfCompressionLookupRecords* theCompressionLookupValueBitLength)/8; } void ossimNitfVqCompressionOffsetTableData::parseStream(std::istream& in) { ossimEndian endian; in.read((char*)(&theTableId), 2); in.read((char*)(&theNumberOfCompressionLookupRecords),4); in.read((char*)(&theNumberOfValuesPerCompressionLookup), 2); in.read((char*)(&theCompressionLookupValueBitLength),2); in.read((char*)(&theCompressionLookupTableOffset), 4); if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(theTableId); endian.swap(theNumberOfCompressionLookupRecords); endian.swap(theNumberOfValuesPerCompressionLookup); endian.swap(theCompressionLookupValueBitLength); endian.swap(theCompressionLookupTableOffset); } } void ossimNitfVqCompressionOffsetTableData::clearFields() { theTableId = 0; theNumberOfCompressionLookupRecords = 0; theNumberOfValuesPerCompressionLookup = 0; theCompressionLookupValueBitLength = 0; theCompressionLookupTableOffset = 0; if(theData) { delete [] theData; theData = NULL; } } ossimNitfVqCompressionHeader::ossimNitfVqCompressionHeader() { clearFields(); } void ossimNitfVqCompressionHeader::parseStream(std::istream &in) { ossimEndian endian; in.read((char*)(&theNumberOfImageRows), 4); in.read((char*)(&theNumberOfImageCodesPerRow), 4); in.read((char*)(&theImageCodeBitLength), 1); in.read((char*)(&theCompressionAlgorithmId), 2); in.read((char*)(&theNumberOfCompressionLookupOffsetRecords), 2); in.read((char*)(&theNumberOfCompressionParameterOffsetRecords), 2); in.read((char*)(&theCompressionLookupOffsetTableOffset), 4); in.read((char*)(&theCompressionLookupTableOffsetRecordLength), 2); if(endian.getSystemEndianType() == OSSIM_LITTLE_ENDIAN) { endian.swap(theNumberOfImageRows); endian.swap(theNumberOfImageCodesPerRow); endian.swap(theCompressionAlgorithmId); endian.swap(theNumberOfCompressionLookupOffsetRecords); endian.swap(theNumberOfCompressionParameterOffsetRecords); endian.swap(theCompressionLookupOffsetTableOffset); endian.swap(theCompressionLookupTableOffsetRecordLength); } if((theNumberOfCompressionLookupOffsetRecords > 0)&& (theCompressionAlgorithmId == 1)) { theTable.clear(); theTable.resize(theNumberOfCompressionLookupOffsetRecords); ossim_uint32 idx = 0; for(idx = 0; idx < theNumberOfCompressionLookupOffsetRecords; ++idx) { theTable[idx].parseStream(in); } for(idx = 0; idx < theTable.size(); ++idx) { if(theTable[idx].theData) { delete [] theTable[idx].theData; theTable[idx].theData = 0; } if(theTable[idx].getDataLengthInBytes()>0) { theTable[idx].theData = new ossim_uint8[theTable[idx].getDataLengthInBytes()]; in.read((char*)(theTable[idx].theData), theTable[idx].getDataLengthInBytes()); } } } } std::ostream& ossimNitfVqCompressionHeader::print(std::ostream& out) const { return this->print(out, std::string("")); } std::ostream& ossimNitfVqCompressionHeader::print( std::ostream& out, const std::string& prefix ) const { std::string pfx = prefix; pfx += "vq_header."; out << std::setiosflags(std::ios::left) << pfx << std::setw(24) << "image_rows:" << theNumberOfImageRows << "\n" << pfx << std::setw(24) << "codes_per_row:" << theNumberOfImageCodesPerRow << "\n" << pfx << std::setw(24) << "codebit_length:" << (ossim_uint32)theImageCodeBitLength << "\n" << pfx << std::setw(24) << "algorithm_id:" << theCompressionAlgorithmId << "\n" << pfx << std::setw(24) << "offset_records:" << theNumberOfCompressionLookupOffsetRecords << "\n" << pfx << std::setw(24) << "offset_record_length:" << theCompressionLookupTableOffsetRecordLength << "\n"; if(theTable.size() > 0) { for(ossim_uint32 idx = 0; idx < theTable.size()-1; ++idx) { std::string tblPfx = pfx; tblPfx += "table"; tblPfx += ossimString::toString(idx).string(); tblPfx += "."; out << tblPfx << std::setw(24) << "id:" << theTable[idx].theTableId << "\n" << tblPfx << std::setw(24) << "lookup_records:" << theTable[idx].theNumberOfCompressionLookupRecords << "\n" << tblPfx << std::setw(24) << "values_per_lookup:" << theTable[idx].theNumberOfValuesPerCompressionLookup << "\n" << tblPfx << std::setw(24) << "lookup_bit_length:" << theTable[idx].theCompressionLookupValueBitLength << "\n" << tblPfx << std::setw(24) << "lookup_table_offset:" << theTable[idx].theCompressionLookupTableOffset << "\n"; } } return out; } bool ossimNitfVqCompressionHeader::saveState(ossimKeywordlist& kwl, const ossimString& prefix)const { bool result = ossimNitfCompressionHeader::saveState(kwl, prefix); if(result) { std::ostringstream out; out << std::setiosflags(std::ios::left) << "image_rows:" << theNumberOfImageRows << "\n" << "codes_per_row:" << theNumberOfImageCodesPerRow << "\n" << "codebit_length:" << (ossim_uint32)theImageCodeBitLength << "\n" << "algorithm_id:" << theCompressionAlgorithmId << "\n" << "offset_records:" << theNumberOfCompressionLookupOffsetRecords << "\n" << "offset_record_length:" << theCompressionLookupTableOffsetRecordLength << "\n"; if(theTable.size() > 0) { for(ossim_uint32 idx = 0; idx < theTable.size()-1; ++idx) { std::string tblPfx = "table"; tblPfx += ossimString::toString(idx).string(); tblPfx += "."; out << tblPfx<< "id:" << theTable[idx].theTableId << "\n" << tblPfx << "lookup_records:"<< theTable[idx].theNumberOfCompressionLookupRecords << "\n" << tblPfx <<"values_per_lookup:"<< theTable[idx].theNumberOfValuesPerCompressionLookup << "\n" << tblPfx << "lookup_bit_length:"<< theTable[idx].theCompressionLookupValueBitLength << "\n" << tblPfx << "lookup_table_offset:"<< theTable[idx].theCompressionLookupTableOffset << "\n"; } } ossimKeywordlist kwlTemp; std::istringstream in(out.str()); if(kwlTemp.parseStream(in)) { kwl.add(prefix, kwlTemp); } } return result; } ossim_uint32 ossimNitfVqCompressionHeader::getBlockSizeInBytes()const { return (getNumberOfImageRows()* getNumberOfImageCodesPerRow()* getImageCodeBitLength())/8; } ossim_uint32 ossimNitfVqCompressionHeader::getNumberOfImageRows()const { return theNumberOfImageRows; } ossim_uint32 ossimNitfVqCompressionHeader::getNumberOfImageCodesPerRow()const { return theNumberOfImageCodesPerRow; } ossim_uint32 ossimNitfVqCompressionHeader::getCompressionAlgorithmId()const { return theCompressionAlgorithmId; } ossim_uint32 ossimNitfVqCompressionHeader::getImageCodeBitLength()const { return theImageCodeBitLength; } ossim_uint32 ossimNitfVqCompressionHeader::getNumberOfTables()const { return (ossim_uint32)theTable.size(); } const std::vector& ossimNitfVqCompressionHeader::getTable()const { return theTable; } void ossimNitfVqCompressionHeader::clearFields() { theNumberOfImageRows = 0; theNumberOfImageCodesPerRow = 0; theImageCodeBitLength = 0; theCompressionAlgorithmId = 0; theNumberOfCompressionLookupOffsetRecords = 0; theCompressionLookupTableOffsetRecordLength = 0; } ossim-Miami-2.9.1/src/support_data/ossimNmeaMessage.cpp000066400000000000000000000051461352751253100231610ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL See top level LICENSE.txt file. // // File: ossimNmeaMessage.h // // Author: Garrett Potts // // Description: Contains a general parser for NMEA messages. // // // $Id$ //---------------------------------------------------------------------------- #include #include #include ossim_uint32 ossimNmeaMessage::checksum(std::string::const_iterator start, std::string::const_iterator end) { ossim_uint32 sum = 0; while(start!=end&&((*start)!='*')) { sum ^= ((*start)%128); ++start; } return sum; } void ossimNmeaMessage::setFields(std::string::const_iterator start, std::string::const_iterator end) { m_fields.clear(); ossim_uint32 idx = 0; while(start != end) { m_fields.push_back(""); while((start!=end)&& (*start!=',')) { m_fields[idx]+=*start; ++start; } if(start!=end) { ++start; } ++idx; } } bool ossimNmeaMessage::isValidStartChar(char c)const { std::string::const_iterator iter = std::find(m_startChars.begin(), m_startChars.end(), c); return (iter != m_startChars.end()); } void ossimNmeaMessage::parseMessage(std::istream& in)throw(ossimException) { ossim::skipws(in); m_validCheckSum = false; m_message = ""; if(!isValidStartChar(static_cast(in.peek()))) { throw ossimException(ossimString("Starting NMEA message indicator not found, expected one of ") + m_startChars + " but found " + ossimString((char)in.peek())); } char c = static_cast(in.get()); while(((c!='\n')&&(c!='\r'))&& !in.eof()&&!in.bad()) { m_message += c; c = static_cast(in.get()); } std::string::iterator iter = std::find(m_message.begin(), m_message.end(), '*'); if(iter != m_message.end()) { setFields(m_message.begin()+1, m_message.end()); ossim_uint32 check = checksum(m_message.begin()+1, iter); std::ostringstream out; out << std::setw(2) << std::setfill('0') << std::hex << check; std::string::iterator endChecksumIter = iter+1; while((endChecksumIter!= m_message.end())&&(*endChecksumIter!=',')) ++endChecksumIter; if(out.str() == ossimString(iter+1, endChecksumIter).downcase()) { m_validCheckSum = true; } } else { throw ossimException("Terminating * indicator for cbecksum not found in NMEA message format"); } } ossim-Miami-2.9.1/src/support_data/ossimNmeaMessageSequencer.cpp000066400000000000000000000026511352751253100250320ustar00rootroot00000000000000#include #include #include ossimNmeaMessageSequencer::ossimNmeaMessageSequencer() :m_inputStream(0) { } ossimNmeaMessageSequencer::ossimNmeaMessageSequencer(const ossimFilename& file) :m_inputStream(0) { initialize(file); } ossimNmeaMessageSequencer::ossimNmeaMessageSequencer(const std::string& str) :m_inputStream(0) { initialize(str); } ossimNmeaMessageSequencer::~ossimNmeaMessageSequencer() { destroy(); } void ossimNmeaMessageSequencer::initialize(const ossimFilename& file) { destroy(); m_inputStream = new std::ifstream(file.c_str()); } void ossimNmeaMessageSequencer::initialize(const std::string& str) { destroy(); m_inputStream = new std::istringstream(str); } void ossimNmeaMessageSequencer::destroy() { if(m_inputStream) { delete m_inputStream; m_inputStream = 0; } } bool ossimNmeaMessageSequencer::next(ossimNmeaMessage& msg) { bool result = false; try { msg.parseMessage(*m_inputStream); result = true; } catch (...) { result = false; } return result; } bool ossimNmeaMessageSequencer::valid()const { bool result = false; if(m_inputStream) { result = m_inputStream->good(); } return result; } void ossimNmeaMessageSequencer::reset() { if(m_inputStream) { m_inputStream->clear(); m_inputStream->seekg(0); } } ossim-Miami-2.9.1/src/support_data/ossimPpjFrameSensorFile.cpp000066400000000000000000000256441352751253100244770ustar00rootroot00000000000000#include #include #include #include #include ossimPpjFrameSensorFile::ossimPpjFrameSensorFile() :m_radialDistortion(2), m_tangentialDistortion(2), m_averageProjectedHeight(0.0) { reset(); } const ossimString& ossimPpjFrameSensorFile::getBaseName()const { return m_fileBaseName; } ossim_int64 ossimPpjFrameSensorFile::getImageNumber()const { return m_imageNumber; } const ossimDpt& ossimPpjFrameSensorFile::getPrincipalPoint()const { return m_principalPoint; } const ossimGpt& ossimPpjFrameSensorFile::getPlatformPosition()const { return m_platformPosition; } const NEWMAT::Matrix& ossimPpjFrameSensorFile::getExtrinsic()const { return m_extrinsicMatrix; } const NEWMAT::Matrix& ossimPpjFrameSensorFile::getIntrinsic()const { return m_intrinsicMatrix; } const ossimDpt& ossimPpjFrameSensorFile::getImageSize()const { return m_imageSize; } const ossimPpjFrameSensorFile::DoubleArrayType& ossimPpjFrameSensorFile::getRadialDistortion()const { return m_radialDistortion; } const ossimPpjFrameSensorFile::DoubleArrayType& ossimPpjFrameSensorFile::getTangentialDistortion()const { return m_tangentialDistortion; } double ossimPpjFrameSensorFile::getAverageProjectedHeight()const { return m_averageProjectedHeight; } void ossimPpjFrameSensorFile::reset() { m_ppjXml = 0; m_principalPoint = ossimDpt(0.0,0.0); m_platformPosition = ossimGpt(0.0,0.0); m_fileBaseName = ""; m_imageNumber = -1; m_radialDistortion[0] = 0.0; m_radialDistortion[1] = 0.0; m_tangentialDistortion[0] = 0.0; m_tangentialDistortion[1] = 0.0; m_intrinsicMatrix = NEWMAT::Matrix(3,3); m_extrinsicMatrix = NEWMAT::Matrix(4,4); std::fill(m_intrinsicMatrix.Store(), m_intrinsicMatrix.Store() + 9, 0.0); std::fill(m_extrinsicMatrix.Store(), m_extrinsicMatrix.Store() + 16, 0.0); m_extrinsicMatrix[0][0] = 1.0; m_extrinsicMatrix[1][1] = 1.0; m_extrinsicMatrix[2][2] = 1.0; m_extrinsicMatrix[3][3] = 1.0; m_imageSize.makeNan(); m_averageProjectedHeight = 0.0; m_pointMapList.clear(); } bool ossimPpjFrameSensorFile::readFile(const ossimFilename& file) { bool result = false; std::ifstream in(file.c_str(), std::ios::in|std::ios::binary); if(in.good()&&readStream(in)) { result = true; } return result; } bool ossimPpjFrameSensorFile::readStream(std::istream& is) { reset(); m_ppjXml = new ossimXmlDocument; if(m_ppjXml->read(is)) { ossimRefPtr root = m_ppjXml->getRoot(); if(root.valid()&&(root->getTag() == "pearlProjectionFile")) { ossimRefPtr image = root->findFirstNode("image"); if(image.valid()) { ossimRefPtr sensorData = image->findFirstNode("sensorData"); ossimRefPtr namingData = image->findFirstNode("namingData"); ossimRefPtr projectionData = image->findFirstNode("projectionData"); if(namingData.valid()) { ossimRefPtr fileBaseName = namingData->findFirstNode("fileBaseName"); ossimRefPtr imageNumber = namingData->findFirstNode("imageNumber"); if(fileBaseName.valid()) { m_fileBaseName = fileBaseName->getText(); } if(imageNumber.valid()) { m_imageNumber = imageNumber->getText().toInt64(); } } if(projectionData.valid()) { const ossimXmlNode::ChildListType& childNodes = projectionData->getChildNodes(); ossim_uint32 nNodes = childNodes.size(); ossim_uint32 idx = 0; ossim_uint32 averageHeightDivisor = 0; for(idx = 0; idx < nNodes; ++idx) { if(childNodes[idx]->getAttributeValue("type").downcase() == "basic") { ossimRefPtr pixelPointX = childNodes[idx]->findFirstNode("pixelPointX"); ossimRefPtr pixelPointY = childNodes[idx]->findFirstNode("pixelPointY"); ossimRefPtr ecefX = childNodes[idx]->findFirstNode("ecefX"); ossimRefPtr ecefY = childNodes[idx]->findFirstNode("ecefY"); ossimRefPtr ecefZ = childNodes[idx]->findFirstNode("ecefZ"); if(pixelPointX.valid()&&pixelPointY.valid()&ecefX.valid()&&ecefY.valid()&&ecefZ.valid()) { PointMap pointMap; pointMap.m_type = BASIC_POINT_TYPE; pointMap.m_point = ossimDpt3d(ecefX->getText().toDouble(), ecefY->getText().toDouble(), ecefZ->getText().toDouble()); pointMap.m_pixelPoint = ossimDpt(pixelPointX->getText().toDouble(),pixelPointY->getText().toDouble()); ossimGpt gpt(ossimEcefPoint(pointMap.m_point.x, pointMap.m_point.y, pointMap.m_point.z)); m_averageProjectedHeight += gpt.height(); ++averageHeightDivisor; m_pointMapList.push_back(pointMap); } } } if(averageHeightDivisor > 0) m_averageProjectedHeight /= static_cast(averageHeightDivisor); } if(sensorData.valid()) { ossimRefPtr sensorSize = sensorData->findFirstNode("sensorSize"); ossimRefPtr cameraIntrinsic = sensorData->findFirstNode("cameraIntrinsic"); ossimRefPtr cameraExtrinsic = sensorData->findFirstNode("cameraExtrinsic"); if(sensorSize.valid()) { ossimRefPtr width = sensorSize->findFirstNode("SensorWidth"); ossimRefPtr height = sensorSize->findFirstNode("SensorHeight"); if(width.valid()&&height.valid()) { m_imageSize.x = width->getText().toDouble(); m_imageSize.y = height->getText().toDouble(); } else { m_ppjXml = 0; } } else { m_ppjXml = 0; } if(m_ppjXml.valid()&&cameraExtrinsic.valid()) { if(cameraExtrinsic->getChildNodes().size() == 4) { m_extrinsicMatrix = NEWMAT::Matrix(4,4); std::vector inRow1 = cameraExtrinsic->getChildNodes()[0]->getText().split(" "); std::vector inRow2 = cameraExtrinsic->getChildNodes()[1]->getText().split(" "); std::vector inRow3 = cameraExtrinsic->getChildNodes()[2]->getText().split(" "); std::vector inRow4 = cameraExtrinsic->getChildNodes()[3]->getText().split(" "); if((inRow1.size() ==4)&& (inRow2.size() ==4)&& (inRow3.size() ==4)&& (inRow4.size() ==4)) { m_extrinsicMatrix << inRow1[0].toDouble() << inRow1[1].toDouble() << inRow1[2].toDouble() << inRow1[3].toDouble() << inRow2[0].toDouble() << inRow2[1].toDouble() << inRow2[2].toDouble() << inRow2[3].toDouble() << inRow3[0].toDouble() << inRow3[1].toDouble() << inRow3[2].toDouble() << inRow3[3].toDouble() << inRow4[0].toDouble() << inRow4[1].toDouble() << inRow4[2].toDouble() << inRow4[3].toDouble(); NEWMAT::ColumnVector v(4); v[0] = v[1] = v[2] = 0.0; v[3] = 1.0; NEWMAT::ColumnVector result = m_extrinsicMatrix*v; m_platformPosition = ossimEcefPoint(result[0], result[1], result[2]); //m_platformPosition; } else { m_ppjXml = 0; } } // end if(cameraExtrinsic->getChildNodes().size() == 4) else { m_ppjXml = 0; } if(m_ppjXml.valid()) { if(cameraIntrinsic.valid()) { m_intrinsicMatrix = NEWMAT::Matrix(3,3); std::vector inRow1 = cameraIntrinsic->getChildNodes()[0]->getText().split(" "); std::vector inRow2 = cameraIntrinsic->getChildNodes()[1]->getText().split(" "); std::vector inRow3 = cameraIntrinsic->getChildNodes()[2]->getText().split(" "); if((inRow1.size() ==3)&& (inRow2.size() ==3)&& (inRow3.size() ==3)) { m_principalPoint.x = inRow1[2].toDouble(); m_principalPoint.y = inRow2[2].toDouble(); m_intrinsicMatrix << inRow1[0].toDouble() << inRow1[1].toDouble() << m_principalPoint.x << inRow2[0].toDouble() << inRow2[1].toDouble() << m_principalPoint.y << inRow3[0].toDouble() << inRow3[1].toDouble() << inRow3[2].toDouble(); } else { m_ppjXml = 0; } } // end if(cameraIntrinsic .....) else { m_ppjXml = 0; } } // end if m_ppjXml ... } // end if(m_ppjXml.valid()&&cameraExtrinsic.valid()) else { m_ppjXml = 0; } } else { m_ppjXml = 0; } } else { m_ppjXml = 0; } } else { m_ppjXml = 0; } } else { m_ppjXml = 0; } return m_ppjXml.valid(); } // Hidden from use... ossimPpjFrameSensorFile::ossimPpjFrameSensorFile(const ossimPpjFrameSensorFile& /* src */) { } ossimPpjFrameSensorFile& ossimPpjFrameSensorFile::operator=( const ossimPpjFrameSensorFile& /* src */) { return *this; } ossim-Miami-2.9.1/src/support_data/ossimQuickbirdMetaData.cpp000066400000000000000000000744531352751253100243210ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Class definition for ossimQuickbirdMetaData. // // This class parses a Space Imaging Quickbird meta data file. // //******************************************************************** // $Id: ossimQuickbirdMetaData.cpp 14431 2009-04-30 21:58:33Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include RTTI_DEF1(ossimQuickbirdMetaData, "ossimQuickbirdMetaData", ossimObject); // Define Trace flags for use within this file: static ossimTrace traceExec ("ossimQuickbirdMetaData:exec"); static ossimTrace traceDebug ("ossimQuickbirdMetaData:debug"); class QbMetadataParser { public: bool openConnection(const ossimString &connectionString) { m_inputStream = ossim::StreamFactoryRegistry::instance()->createIstream(connectionString); return m_inputStream != nullptr; } bool nextLine(ossimString &line) { std::ostringstream out; line = ""; if (m_inputStream->good()) { char c = static_cast(m_inputStream->get()); while (!m_inputStream->eof() && m_inputStream->good() && c != '\n') { out.write(&c, 1); c = static_cast(m_inputStream->get()); } line = out.str(); } return !line.empty(); } bool parseConnection(const ossimString &connectionString) { bool result = false; if (openConnection(connectionString)) { return parse(); } return result; } bool parse(); void splitKeyValue(const ossimString &input, ossimString &key, ossimString &value) const { key = input.before("="); value = input.after("="); key = key.trim(); value = value.trim(); } const std::shared_ptr &getKwl() const { return m_kwl; } std::shared_ptr m_inputStream; std::shared_ptr m_kwl; ossimString m_currentPrefix; }; bool QbMetadataParser::parse() //std::istream& in, ossimKeywordlist& kwl, const ossimString& prefix) { bool result = true; std::stack prefixStack; std::stack currentIdxStack; ossimString line; ossimString kwlString; ossim_int32 bandIdx = -1; ossim_int32 imageIdx = -1; ossimString fullKeyValue; ossimString key; ossimString value; prefixStack.push(""); ossimString bandNames; m_kwl = std::make_shared(); while (result && !prefixStack.empty() && nextLine(line)) { ossimString tempLine = line; tempLine = tempLine.trim(); if (tempLine.startsWith("BEGIN_GROUP")) { ossimString currentPrefix = prefixStack.top(); splitKeyValue(tempLine, key, value); ossimString test = value; test = test.downcase(); if (test.startsWith("band")) { ossimString bandNameValue = value.after("_").downcase(); if (bandNames.empty()) { bandNames = bandNameValue; } else { bandNames += " " + bandNameValue; } } prefixStack.push(currentPrefix + value.downcase().trim() + "."); } else if (tempLine.startsWith("END_GROUP")) { prefixStack.pop(); if (prefixStack.empty()) { result = false; } } else if (tempLine.endsWith(";")) { if (!tempLine.startsWith("END")) { fullKeyValue += line; fullKeyValue = fullKeyValue.trim(); splitKeyValue(fullKeyValue, key, value); value = value.trim().trim(";").trim("\""); key = prefixStack.top() + key.trim(); m_kwl->add(key, value); } fullKeyValue = ""; } else { fullKeyValue += line; } } if (!bandNames.empty()) { m_kwl->add("band_name_list", bandNames); } return result; } ossimQuickbirdMetaData::ossimQuickbirdMetaData() : theGenerationDate("Unknown"), theBandId("Unknown"), theBitsPerPixel(0), theSatID("Unknown"), theTLCDate("Unknown"), theSunAzimuth(0.0), theSunElevation(0.0), theSatAzimuth(0.0), theSatElevation(0.0), theTDILevel(0), theAbsCalFactors(), theBandNameList("Unknown"), theImageSize(), thePNiirs(-1), theCloudCoverage(0.0) { theImageSize.makeNan(); theAbsCalFactors.clear(); } ossimQuickbirdMetaData::~ossimQuickbirdMetaData() { } bool ossimQuickbirdMetaData::open(const ossimFilename& imageFile, ossim_int32 qbParseTypes) { static const char MODULE[] = "ossimQuickbirdMetaData::open"; clearFields(); //retrieve information from the metadata file //if the Quickbird tif is 02APR01105228-M1BS-000000128955_01_P001.TIF //the metadata file will be 02APR01105228-M1BS-000000128955_01_P001.IMD ossimFilename file = imageFile; if(qbParseTypes & QB_PARSE_TYPE_IMD) { file.setExtension(ossimString("IMD")); if (parseMetaData(file) == false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " errors parsing metadata" << std::endl; } return false; } } if (qbParseTypes & QB_PARSE_TYPE_ATT) { file.setExtension(ossimString("ATT")); if(!parse(m_attKwl, file)) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " errors parsing att" << std::endl; } return false; } } if (qbParseTypes & QB_PARSE_TYPE_EPH) { file.setExtension(ossimString("EPH")); if (!parse(m_ephKwl, file)) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " errors parsing eph" << std::endl; } return false; } } if (qbParseTypes & QB_PARSE_TYPE_GEO) { file.setExtension(ossimString("GEO")); if (!parse(m_geoKwl, file)) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " errors parsing geo" << std::endl; } return false; } } if (qbParseTypes & QB_PARSE_TYPE_RPB) { file.setExtension(ossimString("RPB")); if (!parse(m_rpbKwl, file)) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " errors parsing rpb" << std::endl; } return false; } } if (qbParseTypes & QB_PARSE_TYPE_TIL) { file.setExtension(ossimString("TIL")); if (!parse(m_tilKwl, file)) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " errors parsing til" << std::endl; } return false; } } return true; } void ossimQuickbirdMetaData::clearFields() { theGenerationDate = "Unknown"; theBitsPerPixel = 0; theBandId = "Unknown"; theSatID = "Unknown"; theTLCDate = "Unknown"; theSunAzimuth = 0.0; theSunElevation = 0.0; theSatAzimuth = 0.0; theSatElevation = 0.0; theTDILevel = 0; theAbsCalFactors.clear(); theBandNameList = "Unknown"; theImageSize.makeNan(); m_attKwl = nullptr; m_imdKwl = nullptr; m_ephKwl = nullptr; m_rpbKwl = nullptr; m_geoKwl = nullptr; m_tilKwl = nullptr; m_steKwl = nullptr; } std::ostream& ossimQuickbirdMetaData::print(std::ostream& out) const { out << "\n----------------- Info on Quickbird Image -------------------" << "\n " << "\n Generation date: " << theGenerationDate << "\n Band Id: " << theBandId << "\n Bits per pixel: " << theBitsPerPixel << "\n Sat Id: " << theSatID << "\n TLC date: " << theTLCDate << "\n Sun Azimuth: " << theSunAzimuth << "\n Sun Elevation: " << theSunElevation << "\n Sat Azimuth: " << theSatAzimuth << "\n Sat Elevation: " << theSatElevation << "\n Band name list: " << theBandNameList << "\n TDI Level: " << theTDILevel << "\n abs Calibration Factors: " << std::endl; for(unsigned int i=0; i -1) { kwl.add(prefix, "niirs", thePNiirs, true); } kwl.add(prefix, "cloud_cover", theCloudCoverage, true); if (theBandId == "Multi") { std::vector bandNameList = theBandNameList.split(" "); for (unsigned int i = 0; i < bandNameList.size(); ++i) { kwl.add(prefix, bandNameList[i] + "_band_absCalFactor", theAbsCalFactors[i], true); } } else if (!theAbsCalFactors.empty()) { kwl.add(prefix, "absCalFactor", theAbsCalFactors[0], true); } ossimString testBandId = theBandId; testBandId = testBandId.upcase(); if (testBandId == "MULTI") { kwl.add(prefix, "irep", "MULTI"); kwl.add(prefix, "icat", "MS"); } else if (testBandId == "P") { kwl.add(prefix, "irep", "MONO"); kwl.add(prefix, "icat", "VIS"); } else if( !testBandId.empty()) { kwl.add(prefix, "irep", testBandId); } kwl.add(ossimString(prefix) + "imd.", *m_imdKwl); } if (m_attKwl) { kwl.add(ossimString(prefix) + "att.", *m_attKwl); } if (m_ephKwl) { kwl.add(ossimString(prefix) + "eph.", *m_ephKwl); } if (m_geoKwl) { kwl.add(ossimString(prefix) + "geo.", *m_geoKwl); } if (m_rpbKwl) { kwl.add(ossimString(prefix) + "rpb.", *m_rpbKwl); } if (m_steKwl) { kwl.add(ossimString(prefix) + "ste.", *m_rpbKwl); } if (m_tilKwl) { kwl.add(ossimString(prefix) + "til.", *m_tilKwl); } kwl.add(prefix, "organization", "DigitalGlobe", true); return true; } bool ossimQuickbirdMetaData::loadState(const ossimKeywordlist& kwl, const char* prefix) { clearFields(); const char* lookup = 0; ossimString s; lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if (lookup) { s = lookup; if(s != "ossimQuickbirdMetaData") { return false; } } lookup = kwl.find(prefix, "generation_date"); if (lookup) { theGenerationDate = lookup; } lookup = kwl.find(prefix, "band_id"); if (lookup) { theBandId = lookup; } lookup = kwl.find(prefix, "bits_per_pixel"); if (lookup) { s = lookup; theBitsPerPixel = s.toInt();; } lookup = kwl.find(prefix, "sat_id"); if (lookup) { theSatID = lookup; } lookup = kwl.find(prefix, "tlc_date"); if (lookup) { theTLCDate= lookup; } lookup = kwl.find(prefix, "TDI_level"); if (lookup) { s = lookup; theTDILevel = s.toInt(); } lookup = kwl.find(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW); if (lookup) { s = lookup; theSunAzimuth = s.toFloat64(); } lookup = kwl.find(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW); if (lookup) { s = lookup; theSunElevation = s.toFloat64(); } lookup = kwl.find(prefix, "sat_azimuth_angle"); if (lookup) { s = lookup; theSatAzimuth = s.toFloat64(); } lookup = kwl.find(prefix, "sat_elevation_angle"); if (lookup) { s = lookup; theSatElevation = s.toFloat64(); } lookup = kwl.find(prefix, "sun_azimuth"); if (lookup) { s = lookup; theSunAzimuth = s.toFloat64(); } lookup = kwl.find(prefix, "sun_elevation"); if (lookup) { s = lookup; theSunElevation = s.toFloat64(); } lookup = kwl.find(prefix, "band_name_list"); if (lookup) { theBandNameList= lookup; } lookup = kwl.find(prefix, "niirs"); if (lookup) { thePNiirs = ossimString(lookup).toFloat64(); } lookup = kwl.find(prefix, "cloud_cover"); if(lookup) { theCloudCoverage = ossimString(lookup).toFloat64(); } if(theBandId=="Multi") { std::vector bandNameList = theBandNameList.split(" "); theAbsCalFactors = std::vector(bandNameList.size(), 1.); for(unsigned int i = 0 ; i < bandNameList.size() ; ++i) { lookup = kwl.find(prefix, bandNameList[i] + "_band_absCalFactor"); if (lookup) { s = lookup; theAbsCalFactors[i] = s.toDouble(); } } } else if (theBandId=="P") { theAbsCalFactors = std::vector(1, 1.); lookup = kwl.find(prefix, "absCalFactor"); if (lookup) { s = lookup; theAbsCalFactors[0] = s.toDouble(); } } if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "imd.")) { m_imdKwl = std::make_shared(); m_imdKwl->add(kwl , ossimString(prefix) + "imd."); } if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "att.")) { m_attKwl = std::make_shared(); m_attKwl->add(kwl, ossimString(prefix) + "att."); } if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "geo.")) { m_geoKwl = std::make_shared(); m_geoKwl->add(kwl, ossimString(prefix) + "geo."); } if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "rpb.")) { m_rpbKwl = std::make_shared(); m_rpbKwl->add(kwl, ossimString(prefix) + "rpb."); } if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "ste.")) { m_steKwl = std::make_shared(); m_steKwl->add(kwl, ossimString(prefix) + "ste."); } return true; } //***************************************************************************** // PROTECTED METHOD: ossimQuickbirdMetaData::parseMetaData() // // Parses the Quickbird IMD file. // //***************************************************************************** bool ossimQuickbirdMetaData::parseMetaData(const ossimFilename& data_file) { bool result = false; if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimQuickbirdMetaData::parseMetaData(data_file): entering..." << std::endl; if( !data_file.exists() ) { if (traceExec()) ossimNotify(ossimNotifyLevel_WARN) << "ossimQuickbirdMetaData::parseMetaData(data_file) WARN:" << "\nmetadate data file <" << data_file << ">. " << "doesn't exist..." << std::endl; return result; } m_imdKwl = nullptr; // std::shared_ptr // qbMetadataParser = std::make_shared(); // if (qbMetadataParser->parseConnection(data_file)) if(parse(m_imdKwl, data_file)) { // m_imdKwl = std::make_shared(*qbMetadataParser->getKwl()); ossimString value = m_imdKwl->find("generationTime"); if(!value.empty()) { theGenerationDate = value; } theBandId = m_imdKwl->find("bandId"); value = m_imdKwl->find("numRows"); if(!value.empty()) { theImageSize.y = value.toInt64(); } value = m_imdKwl->find("numColumns"); if (!value.empty()) { theImageSize.x = value.toInt64(); } theBandId = m_imdKwl->find("bandId"); value = m_imdKwl->find("nbitsPerPixel"); if(!value.empty()) { theBitsPerPixel = value.toInt32(); } theBandNameList = m_imdKwl->find("band_name_list"); std::vector bandList; theBandNameList.split(bandList, " "); if(bandList.size()>0) { ossim_uint32 idx = 0; theAbsCalFactors = std::vector(bandList.size(), 1.0); for(auto band:bandList) { value = m_imdKwl->find("band_"+band+".absCalFactor"); if(!value.empty()) { theAbsCalFactors[idx] = value.toFloat64(); } ++idx; } } theSatID = m_imdKwl->find("image_1.satId"); theTLCDate = m_imdKwl->find("image_1.TLCTime"); if(theTLCDate.empty()) { theTLCDate = m_imdKwl->find("image_1.firstLineTime"); } value = m_imdKwl->find("sunAz"); if (!value.empty()) { theSunAzimuth = value.toFloat64(); } else { value = m_imdKwl->find("image_1.meanSunAz"); if (!value.empty()) { theSunAzimuth = value.toFloat64(); } } value = m_imdKwl->find("sunEl"); if (!value.empty()) { theSunElevation = value.toFloat64(); } else { value = m_imdKwl->find("image_1.meanSunEl"); if (!value.empty()) { theSunElevation = value.toFloat64(); } } value = m_imdKwl->find("image_1.satAz"); if (!value.empty()) { theSatAzimuth = value.toFloat64(); } else { value = m_imdKwl->find("image_1.meanSatAz"); if (!value.empty()) { theSatAzimuth = value.toFloat64(); } } value = m_imdKwl->find("image_1.cloudCover"); if (!value.empty()) { theCloudCoverage = value.toFloat64(); } value = m_imdKwl->find("image_1.PNIIRS"); if (!value.empty()) { thePNiirs = value.toFloat64(); } result = true; } return result; } bool ossimQuickbirdMetaData::parse(std::shared_ptr &kwl, const ossimFilename &file) { bool result = false; if (!file.exists()) { if (traceExec()) ossimNotify(ossimNotifyLevel_WARN) << "ossimQuickbirdMetaData::parse(file) WARN:" << "\ndata file <" << file << ">. " << "doesn't exist..." << std::endl; return result; } std::shared_ptr qbMetadataParser = std::make_shared(); if (qbMetadataParser->parseConnection(file)) { kwl = std::make_shared(*qbMetadataParser->getKwl()); result = kwl->getSize() > 0; } return result; } ossimString ossimQuickbirdMetaData::getSatID() const { return theSatID; } bool ossimQuickbirdMetaData::getMapProjectionKwl( const ossimFilename& imd_file, ossimKeywordlist& kwl ) { static const char MODULE[] = "ossimQuickbirdMetaData::getMapProjectionKwl"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool result = false; if( imd_file.exists() ) { FILE* fptr = fopen (imd_file.c_str(), "r"); if (fptr) { char* strptr(NULL); //--- // Read the file into a buffer: //--- ossim_int32 fileSize = static_cast(imd_file.fileSize()); char* filebuf = new char[fileSize]; fread(filebuf, 1, fileSize, fptr); strptr = filebuf; fclose(fptr); ossimString imd_key; ossimString tempStr; std::string key; std::string value; // Loop until we find all our keys or bust out with error. while ( 1 ) { // Verify map projected. imd_key = "BEGIN_GROUP = MAP_PROJECTED_PRODUCT"; if ( strstr( filebuf, imd_key.c_str() ) == NULL ) { break; // Not a map projected product. } // Get datum: if( getEndOfLine( strptr, ossimString("\n\tdatumName = "), "%13c %s", tempStr) ) { if ( tempStr.contains("WE") ) { key = "dataum"; value = "WGE"; kwl.addPair(key, value); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Unhandled datum: " << tempStr << "\n"; } } } // Get projection: if( getEndOfLine( strptr, ossimString("\n\tmapProjName = "), "%15c %s", tempStr) ) { if ( tempStr.contains("UTM") ) { key = "type"; value = "ossimUtmProjection"; kwl.addPair(key, value); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Unhandled projection name: " << tempStr << "\n"; } } } // Get projection: if( getEndOfLine( strptr, ossimString("\n\tmapProjName = "), "%15c %s", tempStr) ) { if ( tempStr.contains("UTM") ) { key = "type"; value = "ossimUtmProjection"; kwl.addPair(key, value); // Get UTM zone: if( getEndOfLine( strptr, ossimString("\n\tmapZone = "), "%11c %s", tempStr) ) { key = "zone"; value = tempStr.trim(";").string(); kwl.addPair(key, value); } else { break; } // Get UTM hemisphere: if( getEndOfLine( strptr, ossimString("\n\tmapHemi = "), "%11c %s", tempStr) ) { key = "hemisphere"; tempStr = tempStr.trim(";"); tempStr = tempStr.trim("\""); value = tempStr.string(); kwl.addPair(key, value); } else { break; } } // End UTM: } // Get projection units: std::string units; if( getEndOfLine( strptr, ossimString("\n\tproductUnits = "), "%16c %s", tempStr) ) { if ( tempStr == "\"M\";" ) { key = "units"; units = "meters"; kwl.addPair(key, units); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Unhandled units: " << tempStr << "\n"; } } } // Get projection tie point: ossimDpt dpt; dpt.makeNan(); if( getEndOfLine( strptr, ossimString("\n\toriginX = "), "%11c %s", tempStr) ) { tempStr = tempStr.trim(";"); dpt.x = tempStr.toFloat64(); } else { break; } if( getEndOfLine( strptr, ossimString("\n\toriginY = "), "%11c %s", tempStr) ) { tempStr = tempStr.trim(";"); dpt.y = tempStr.toFloat64(); } else { break; } if ( dpt.hasNans() == false ) { key = "tie_point_units"; kwl.addPair(key, units); key = "tie_point_xy"; value = dpt.toString().string(); kwl.addPair( key, value ); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "tie point has nans!"; } break; } // Get projection scale: dpt.makeNan(); if( getEndOfLine( strptr, ossimString("\n\tcolSpacing = "), "%14c %s", tempStr) ) { tempStr = tempStr.trim(";"); dpt.x = tempStr.toFloat64(); } else { break; } if( getEndOfLine( strptr, ossimString("\n\trowSpacing = "), "%14c %s", tempStr) ) { tempStr = tempStr.trim(";"); dpt.y = tempStr.toFloat64(); } else { break; } if ( dpt.hasNans() == false ) { key = "pixel_scale_units"; kwl.addPair(key, units); key = "pixel_scale_xy"; value = dpt.toString().string(); kwl.addPair( key, value ); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "scale has nans!"; } break; } //--- // End of key look up. If we get here set the status to true and // bust out of loop. //--- result = true; break; } if ( result == false ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ERROR: Missing or unhandled key in metadat: " << imd_key << "\n"; } } delete [] filebuf; filebuf = 0; } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdRpcModel::parseMetaData(imd_file) DEBUG:" << "\nCould not open Meta data file: " << imd_file << "\nreturning with error...\n"; } } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exit status = " << (result?"true":"false") << "\n"; } return result; } const std::shared_ptr ossimQuickbirdMetaData::getImdKwl() const { return m_imdKwl; } const std::shared_ptr ossimQuickbirdMetaData::getAttKwl() const { return m_attKwl; } const std::shared_ptr ossimQuickbirdMetaData::getGeoKwl() const { return m_geoKwl; } const std::shared_ptr ossimQuickbirdMetaData::getEphKwl() const { return m_ephKwl; } const std::shared_ptr ossimQuickbirdMetaData::getRpbKwl() const { return m_rpbKwl; } //***************************************************************************** // PROTECTED METHOD: ossimQuickbirdMetaData::getEndOfLine // // // Parse a char * to find another char *. Change the pointer only if the second char * is found. // //***************************************************************************** bool ossimQuickbirdMetaData::getEndOfLine( char * fileBuf, ossimString lineBeginning, const char * format, ossimString & name) { //char * res = strstr(fileBuf, lineBeginning.c_str()); //if (!res) //{ // return false; // } //// if the lineBeginning is found, update the start pointer adress //fileBuf = res; //char dummy[80], nameChar[80]; //sscanf(res, format, dummy, nameChar); //name = ossimString(nameChar); char * res = strstr(fileBuf, lineBeginning.c_str()); if(!res) { return false; } fileBuf = strstr(fileBuf, lineBeginning.c_str()); char dummy[80], nameChar[80]; sscanf(fileBuf, format, dummy, nameChar); name = ossimString(nameChar); return true; } const ossimIpt& ossimQuickbirdMetaData::getImageSize() const { return theImageSize; } ossim-Miami-2.9.1/src/support_data/ossimQuickbirdRpcHeader.cpp000066400000000000000000000247571352751253100245000ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id: ossimQuickbirdRpcHeader.cpp 9094 2006-06-13 19:12:40Z dburken $ #include #include #include #include #include #include #include using namespace std; std::ostream& operator << (std::ostream& out, const ossimQuickbirdRpcHeader& data) { out << "theSatId = " << data.theSatId << std::endl << "theBandId = " << data.theBandId << std::endl << "theSpecId = " << data.theSpecId << std::endl << "theErrBias = " << data.theErrBias << std::endl << "theLineOffset = " << data.theLineOffset << std::endl << "theSampOffset = " << data.theSampOffset << std::endl << "theLatOffset = " << data.theLatOffset << std::endl << "theLonOffset = " << data.theLonOffset << std::endl << "theHeightOffset = " << data.theHeightOffset << std::endl << "theLineScale = " << data.theLineScale << std::endl << "theSampScale = " << data.theSampScale << std::endl << "theLatScale = " << data.theLatScale << std::endl << "theLonScale = " << data.theLonScale << std::endl << "theHeightScale = " << data.theHeightScale << std::endl; out << "lineNumCoef = " << std::endl; std::copy(data.theLineNumCoeff.begin(), data.theLineNumCoeff.end(), std::ostream_iterator(out, "\n")); out << "lineDenCoef = " << std::endl; std::copy(data.theLineDenCoeff.begin(), data.theLineDenCoeff.end(), std::ostream_iterator(out, "\n")); out << "sampNumCoef = " << std::endl; std::copy(data.theSampNumCoeff.begin(), data.theSampNumCoeff.end(), std::ostream_iterator(out, "\n")); out << "sampDenCoef = " << std::endl; std::copy(data.theSampDenCoeff.begin(), data.theSampDenCoeff.end(), std::ostream_iterator(out, "\n")); return out; } ossimQuickbirdRpcHeader::ossimQuickbirdRpcHeader() : theErrBias(0), theErrRand(0), theLineOffset(0), theSampOffset(0), theLatOffset(0), theLonOffset(0), theHeightOffset(0), theLineScale(0), theSampScale(0), theLatScale(0), theLonScale(0), theHeightScale(0) { } bool ossimQuickbirdRpcHeader::open(const ossimFilename& file) { theFilename = file; if (theFilename.ext().upcase() == "XML") return parseXml(); std::ifstream in(file.c_str(), std::ios::in|std::ios::binary); char test[64]; in.read((char*)test, 63); test[63] = '\0'; in.seekg(0); ossimString line = test; line = line.upcase(); if(parseNameValue(line)) { theErrorStatus = ossimErrorCodes::OSSIM_OK; getline(in, line); while((in)&&(theErrorStatus == ossimErrorCodes::OSSIM_OK)) { line = line.upcase(); if(line.contains("LINENUMCOEF")) { if(!readCoeff(in, theLineNumCoeff)) { setErrorStatus(); break; } } else if(line.contains("LINEDENCOEF")) { if(!readCoeff(in, theLineDenCoeff)) { setErrorStatus(); break; } } else if(line.contains("SAMPNUMCOEF")) { if(!readCoeff(in, theSampNumCoeff)) { setErrorStatus(); break; } } else if(line.contains("SAMPDENCOEF")) { if(!readCoeff(in, theSampDenCoeff)) { setErrorStatus(); break; } } else if(!parseNameValue(line)) { setErrorStatus(); break; } getline(in, line); } } else { setErrorStatus(); } return (theErrorStatus == ossimErrorCodes::OSSIM_OK); } bool ossimQuickbirdRpcHeader::parseXml () { ossimXmlDocument document; if (!document.openFile(theFilename)) return false; ossimRefPtr root = document.getRoot(); ossimRefPtr rpcNode = root->findFirstNode("RPB"); if (!rpcNode) return false; ossimString dataString; bool success = false; // Assume we're gonna screw this up... while (1) { theSatId = rpcNode->getChildTextValue("SATID"); if (theSatId.empty()) break; theBandId = rpcNode->getChildTextValue("BANDID"); if (theBandId.empty()) break; theSpecId = rpcNode->getChildTextValue("SPECID"); if (theSpecId.empty()) break; rpcNode = rpcNode->findFirstNode("IMAGE"); if (!rpcNode) break; dataString = rpcNode->getChildTextValue("ERRBIAS"); if (dataString.empty()) break; theErrBias = dataString.toDouble(); dataString = rpcNode->getChildTextValue("ERRRAND"); if (dataString.empty()) break; theErrRand = dataString.toDouble(); dataString = rpcNode->getChildTextValue("LINEOFFSET"); if (dataString.empty()) break; theLineOffset = dataString.toInt(); dataString = rpcNode->getChildTextValue("SAMPOFFSET"); if (dataString.empty()) break; theSampOffset = dataString.toInt(); dataString = rpcNode->getChildTextValue("LATOFFSET"); if (dataString.empty()) break; theLatOffset = dataString.toDouble(); dataString = rpcNode->getChildTextValue("LONGOFFSET"); if (dataString.empty()) break; theLonOffset = dataString.toDouble(); dataString = rpcNode->getChildTextValue("HEIGHTOFFSET"); if (dataString.empty()) break; theHeightOffset = dataString.toDouble(); dataString = rpcNode->getChildTextValue("LINESCALE"); if (dataString.empty()) break; theLineScale = dataString.toDouble(); dataString = rpcNode->getChildTextValue("SAMPSCALE"); if (dataString.empty()) break; theSampScale = dataString.toDouble(); dataString = rpcNode->getChildTextValue("LATSCALE"); if (dataString.empty()) break; theLatScale = dataString.toDouble(); dataString = rpcNode->getChildTextValue("LONGSCALE"); if (dataString.empty()) break; theLonScale = dataString.toDouble(); dataString = rpcNode->getChildTextValue("HEIGHTSCALE"); if (dataString.empty()) break; theHeightScale = dataString.toDouble(); vector ln, ld, sn, sd; rpcNode->getChildTextValue("LINENUMCOEFList/LINENUMCOEF").split(ln, " ", true); rpcNode->getChildTextValue("LINEDENCOEFList/LINEDENCOEF").split(ld, " ", true); rpcNode->getChildTextValue("SAMPNUMCOEFList/SAMPNUMCOEF").split(sn, " ", true); rpcNode->getChildTextValue("SAMPDENCOEFList/SAMPDENCOEF").split(sd, " ", true); if ( (ln.size() != 20) || (ld.size() != 20) || (sn.size() != 20) || (sd.size() != 20)) break; for (int i=0; i<20; ++i) { theLineNumCoeff.emplace_back(ln[i].toDouble()); theLineDenCoeff.emplace_back(ld[i].toDouble()); theSampNumCoeff.emplace_back(sn[i].toDouble()); theSampDenCoeff.emplace_back(sd[i].toDouble()); } success = true; // Well waddaya know! } return success; } bool ossimQuickbirdRpcHeader::readCoeff(std::istream& in, std::vector& coeff) { coeff.clear(); bool done = false; ossimString line; while(!in.eof()&&!in.bad()&&!done) { getline(in, line); line.trim(); line.trim(','); if(line.contains(");")) { done = true; line.trim(';'); line.trim(')'); } coeff.push_back(line.toDouble()); } return done; } bool ossimQuickbirdRpcHeader::isGlobal() const { ossimRegExp regex("R[0-9]*C[0-9]*"); return !regex.find(theFilename.c_str()); } bool ossimQuickbirdRpcHeader::parseNameValue(const ossimString& line) { bool result = true; ossimString lineCopy = line; if(lineCopy.contains("SATID")) { theSatId = lineCopy.after("\""); theSatId = theSatId.before("\""); } else if(lineCopy.contains("BANDID")) { theBandId = lineCopy.after("\""); theBandId = theBandId.before("\""); } else if(lineCopy.contains("SPECID")) { theSpecId = lineCopy.after("\""); theSpecId = theSpecId.before("\""); } else if(lineCopy.contains("BEGIN_GROUP")) { } else if(lineCopy.contains("ERRBIAS")) { lineCopy = lineCopy.after("="); theErrBias = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("ERRRAND")) { lineCopy = lineCopy.after("="); theErrRand = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LINEOFFSET")) { lineCopy = lineCopy.after("="); theLineOffset = lineCopy.before(";").toInt(); } else if(lineCopy.contains("SAMPOFFSET")) { lineCopy = lineCopy.after("="); theSampOffset = lineCopy.before(";").toInt(); } else if(lineCopy.contains("LATOFFSET")) { lineCopy = lineCopy.after("="); theLatOffset = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LONGOFFSET")) { lineCopy = lineCopy.after("="); theLonOffset = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("HEIGHTOFFSET")) { lineCopy = lineCopy.after("="); theHeightOffset = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LINESCALE")) { lineCopy = lineCopy.after("="); theLineScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("SAMPSCALE")) { lineCopy = lineCopy.after("="); theSampScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LATSCALE")) { lineCopy = lineCopy.after("="); theLatScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("LONGSCALE")) { lineCopy = lineCopy.after("="); theLonScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("HEIGHTSCALE")) { lineCopy = lineCopy.after("="); theHeightScale = lineCopy.before(";").toDouble(); } else if(lineCopy.contains("END_GROUP")) { } else if(lineCopy.contains("END")) { } else { result = false; } return result; } ossim-Miami-2.9.1/src/support_data/ossimQuickbirdTile.cpp000066400000000000000000000230721352751253100235250ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimQuickbirdTile.cpp 19682 2011-05-31 14:21:20Z dburken $ #include #include #include #include static const ossimTrace traceDebug(ossimString("ossimQuickbirdTile:debug")); ossimQuickbirdTile::ossimQuickbirdTile() { } bool ossimQuickbirdTile::open(const ossimFilename tileFile) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdTile::open entered:" << "\ntileFile: " << tileFile << std::endl; } std::ifstream in(tileFile.c_str(), std::ios::in|std::ios::binary); if(!in) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Could not open!" << std::endl; } return false; } char testBuf[512]; in.read((char*)testBuf, 50); testBuf[511] = '\0'; ossimString testString = testBuf; testString = testString.upcase(); if(testString.contains("BEGIN_GROUP")|| testString.contains("BANDID")) { in.seekg(0); ossimString line; ossimString name; ossimString value; std::getline(in, line.string()); while(!in.eof()&&!in.bad()&&(in.good())&& (theErrorStatus==ossimErrorCodes::OSSIM_OK)) { parseNameValue(name, value, line); name = name.upcase(); name = name.trim(); if(name == "BEGIN_GROUP") { parseTileGroup(in, value); } else if(name == "BANDID") { theBandId = value.after("\"").before("\""); } else if(name == "NUMTILES") { theNumberOfTiles = value.before(";").toInt32(); } else if(name == "TILESIZE") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Key " << name << " not parsed!" << std::endl; } } else if(name == "TILESIZEX") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Key " << name << " not parsed!" << std::endl; } } else if(name == "TILESIZEY") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Key " << name << " not parsed!" << std::endl; } } else if(name == "TILEOVERLAP") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Key " << name << " not parsed!" << std::endl; } } else if(name == "TILEUNITS") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Key " << name << " not parsed!" << std::endl; } } else if (name == "END;") { break; } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed! Exiting with error..." << std::endl; } setErrorStatus(); } std::getline(in, line.string()); } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdTile::open return value:" << ((theErrorStatus == ossimErrorCodes::OSSIM_OK)?"true":"false") << std::endl; } return (theErrorStatus == ossimErrorCodes::OSSIM_OK); } void ossimQuickbirdTile::parseTileGroup(std::istream& in, const ossimString& tileName) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimQuickbirdTile::parseTileGroup entered:" << std::endl; } ossimQuickbirdTileInfo info; ossimString line; ossimString name; ossimString value; info.theTileGroup = tileName; while(!in.eof()&&!in.bad()&& (theErrorStatus==ossimErrorCodes::OSSIM_OK)&& (name != "END_GROUP")) { line = ""; std::getline(in, line.string()); parseNameValue(name, value, line); name = name.upcase(); if(name == "FILENAME") { ossimString filename = value.after("\"").before("\""); info.theFilename = filename.upcase(); } else if(name == "COLOFFSET") { info.theUlXOffset = value.before(";").toInt32(); } else if(name == "ROWOFFSET") { info.theUlYOffset = value.before(";").toInt32(); } else if(name == "ULCOLOFFSET") { info.theUlXOffset = value.before(";").toInt32(); } else if(name == "ULROWOFFSET") { info.theUlYOffset = value.before(";").toInt32(); } else if(name == "URCOLOFFSET") { info.theUrXOffset = value.before(";").toInt32(); } else if(name == "URROWOFFSET") { info.theUrYOffset = value.before(";").toInt32(); } else if(name == "LRCOLOFFSET") { info.theLrXOffset = value.before(";").toInt32(); } else if(name == "LRROWOFFSET") { info.theLrYOffset = value.before(";").toInt32(); } else if(name == "LLCOLOFFSET") { info.theLlXOffset = value.before(";").toInt32(); } else if(name == "LLROWOFFSET") { info.theLlYOffset = value.before(";").toInt32(); } else if(name == "ULLON") { info.theUlLon = value.before(";").toDouble(); } else if(name == "ULLAT") { info.theUlLat = value.before(";").toDouble(); } else if(name == "URLON") { info.theUrLon = value.before(";").toDouble(); } else if(name == "URLAT") { info.theUrLat = value.before(";").toDouble(); } else if(name == "LRLON") { info.theLrLon = value.before(";").toDouble(); } else if(name == "LRLAT") { info.theLrLat = value.before(";").toDouble(); } else if(name == "LLLON") { info.theLlLon = value.before(";").toDouble(); } else if(name == "LLLAT") { info.theLlLat = value.before(";").toDouble(); } else if(name == "END_GROUP") { break; } else if (name == "ULX") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed!" << std::endl; } } else if (name == "ULY") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed!" << std::endl; } } else if (name == "URX") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed!" << std::endl; } } else if (name == "URY") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed!" << std::endl; } } else if (name == "LRX") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed!" << std::endl; } } else if (name == "LRY") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed!" << std::endl; } } else if (name == "LLX") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed!" << std::endl; } } else if (name == "LLY") { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed!" << std::endl; } } else if(name == "END;") { break; } else { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "key " << name << " not parsed! Exiting with error..." << std::endl; } setErrorStatus(); break; } } if(theErrorStatus == ossimErrorCodes::OSSIM_OK) { theTileMap.insert(std::make_pair(info.theFilename.string(), info)); } } void ossimQuickbirdTile::parseNameValue(ossimString& name, ossimString& value, const ossimString& line)const { name = ossimString(line).before("="); name = name.trim(); value = ossimString(line).after("="); value = value.trim(); } bool ossimQuickbirdTile::getInfo(ossimQuickbirdTileInfo& result, const ossimFilename& filename)const { std::map::const_iterator iter = theTileMap.find(filename.string()); if(iter != theTileMap.end()) { result = (*iter).second; return true; } return false; } ossim-Miami-2.9.1/src/support_data/ossimRpfAttributeOffsetRecord.cpp000066400000000000000000000031471352751253100257140ustar00rootroot00000000000000#include #include #include #include std::ostream& operator <<( std::ostream& out, const ossimRpfAttributeOffsetRecord& data) { data.print(out); return out; } ossimRpfAttributeOffsetRecord::ossimRpfAttributeOffsetRecord() { clearFields(); } ossimErrorCode ossimRpfAttributeOffsetRecord::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { if(in) { in.read((char*)&theAttributeId, 2); in.read((char*)&theParameterId, 1); in.read((char*)&theArealCoverageSequenceNumber, 1); in.read((char*)&theAttributeRecordOffset, 4); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theAttributeId); anEndian.swap(theAttributeRecordOffset); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfAttributeOffsetRecord::print(std::ostream& out)const { out << "theAttributeId: " << theAttributeId << "\ntheParameterId: " << theParameterId << "\ntheArealCoverageSequenceNumber: " << theArealCoverageSequenceNumber << "\ntheAttributeRecordOffset: " << theAttributeRecordOffset; } void ossimRpfAttributeOffsetRecord::clearFields() { theAttributeId = 0; theParameterId = 0; theArealCoverageSequenceNumber = 0; theAttributeRecordOffset = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfAttributeSectionSubheader.cpp000066400000000000000000000053331352751253100265550ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: Rpf support class // //******************************************************************** // $Id$ #include #include #include #include std::ostream& operator <<( std::ostream& out, const ossimRpfAttributeSectionSubheader& data) { data.print(out); return out; } ossimRpfAttributeSectionSubheader::ossimRpfAttributeSectionSubheader() { clearFields(); } ossimErrorCode ossimRpfAttributeSectionSubheader::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { theAttributeSectionSubheaderStart = 0; theAttributeSectionSubheaderEnd = 0; if(in) { theAttributeSectionSubheaderStart = in.tellg(); in.read((char*)&theNumberOfAttributeOffsetRecords, 2); in.read((char*)&theNumberOfExplicitArealCoverageRecords, 2); in.read((char*)&theAttributeOffsetTableOffset, 4); in.read((char*)&theAttribteOffsetRecordLength, 2); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theNumberOfAttributeOffsetRecords); anEndian.swap(theNumberOfExplicitArealCoverageRecords); anEndian.swap(theAttributeOffsetTableOffset); anEndian.swap(theAttribteOffsetRecordLength); } theAttributeSectionSubheaderEnd = in.tellg(); } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfAttributeSectionSubheader::print(std::ostream& out)const { out << "theNumberOfAttributeOffsetRecords: " << theNumberOfAttributeOffsetRecords << "\ntheNumberOfExplicitArealCoverageRecords: " << theNumberOfExplicitArealCoverageRecords << "\ntheAttributeOffsetTableOffset: " << theAttributeOffsetTableOffset << "\ntheAttribteOffsetRecordLength: " << theAttribteOffsetRecordLength; } void ossimRpfAttributeSectionSubheader::clearFields() { theNumberOfAttributeOffsetRecords = 0; theNumberOfExplicitArealCoverageRecords = 0; theAttributeOffsetTableOffset = 0; theAttribteOffsetRecordLength = 0; theAttributeSectionSubheaderStart = 0; theAttributeSectionSubheaderEnd = 0; } ossim_uint64 ossimRpfAttributeSectionSubheader::getSubheaderStart()const { return theAttributeSectionSubheaderStart; } ossim_uint64 ossimRpfAttributeSectionSubheader::getSubheaderEnd()const { return theAttributeSectionSubheaderEnd; } ossim-Miami-2.9.1/src/support_data/ossimRpfAttributes.cpp000066400000000000000000000130271352751253100235670ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id: ossimRpfAttributes.cpp 14241 2009-04-07 19:59:23Z dburken $ #include #include std::ostream& operator<<(std::ostream& out, const ossimRpfAttributes& data) { data.print(out); return out; } ossimRpfAttributes::ossimRpfAttributes() { clearFields(); } ossimRpfAttributes::~ossimRpfAttributes() { } std::ostream& ossimRpfAttributes::print(std::ostream& out, const std::string& prefix) const { out << prefix << "CurrencyDate: " << theCurrencyDate << "\n" << prefix << "ProductionDate: " << theProductionDate << "\n" << prefix << "SignificantDate: " << theSignificantDate << "\n" << prefix << "ChartSeriesCode: " << theChartSeriesCode << "\n" << prefix << "MapDesignationCode: " << theMapDesignationCode << "\n" << prefix << "OldHorDatum: " << theOldHorDatum << "\n" << prefix << "Edition: " << theEdition << "\n" << prefix << "ProjectionCode: " << theProjectionCode << "\n" << prefix << "ProjectionA: " << theProjectionA << "\n" << prefix << "ProjectionB: " << theProjectionB << "\n" << prefix << "ProjectionC: " << theProjectionC << "\n" << prefix << "ProjectionD: " << theProjectionD << "\n" << prefix << "VertDatumCode: " << theVertDatumCode<< "\n" << prefix << "HorDatumCode: " << theHorDatumCode << "\n" << prefix << "VertAbsAccuracy: " << theVertAbsAccuracy << "\n" << prefix << "VertAbsUnits: " << theVertAbsUnits << "\n" << prefix << "HorAbsAccuracy: " << theHorAbsAccuracy << "\n" << prefix << "HorAbsUnits: " << theHorAbsUnits << "\n" << prefix << "VertRelAccuracy: " << theVertRelAccuracy << "\n" << prefix << "VertRelUnits: " << theVertRelUnits << "\n" << prefix << "HorRelAccuracy: " << theHorRelAccuracy << "\n" << prefix << "HorRelUnits: " << theHorRelUnits << "\n" << prefix << "ellipsoidCode: " << ellipsoidCode << "\n" << prefix << "SoundingDatumCode: " << theSoundingDatumCode << "\n" << prefix << "NavSystemCode: " << theNavSystemCode << "\n" << prefix << "GridCode: " << theGridCode << "\n" << prefix << "EeasterlyMagChange: " << theEeasterlyMagChange << "\n" << prefix << "EasterlyMagChangeUnits: " << theEasterlyMagChangeUnits << "\n" << prefix << "WesterlyMagChange: " << theWesterlyMagChange << "\n" << prefix << "WesterlyMagChangeUnits: " << theWesterlyMagChangeUnits << "\n" << prefix << "MagAngle: " << theMagAngle << "\n" << prefix << "GridConver: " << theGridConver << "\n" << prefix << "GridConverUnits: " << theGridConverUnits << "\n" << prefix << "HighElevation: " << theHighElevation << "\n" << prefix << "HighElevationUnits: " << theHighElevationUnits << "\n" << prefix << "HighLat: " << theHighLat << "\n" << prefix << "HighLon: " << theHighLon << "\n" << prefix << "LegendFileName: " << theLegendFileName << "\n" << prefix << "DataSource: " << theDataSource << "\n" << prefix << "gsd: " << theGsd << "\n" << prefix << "DataLevel: " << theDataLevel << std::endl; return out; } bool ossimRpfAttributes::isEmpty()const { for(std::map::const_iterator iter= theAttributeIdBoolMap.begin(); iter != theAttributeIdBoolMap.end();++iter) { if(iter->second!=false) { return false; } } return true; } void ossimRpfAttributes::clearFields() { theCurrencyDate = ""; theProductionDate = ""; theSignificantDate = ""; theChartSeriesCode = ""; theMapDesignationCode = ""; theOldHorDatum = ""; theEdition = ""; theProjectionCode = ""; theProjectionA = 0.0; theProjectionB = 0.0; theProjectionC = 0.0; theProjectionD = 0.0; theVertDatumCode = ""; theHorDatumCode = ""; theVertAbsAccuracy = 0; theVertAbsUnits = 0; theHorAbsAccuracy = 0; theHorAbsUnits = 0; theVertRelAccuracy = 0; theVertRelUnits = 0; theHorRelAccuracy = 0; theHorRelUnits = 0; ellipsoidCode = ""; theSoundingDatumCode = ""; theNavSystemCode = 0; theGridCode = ""; theEeasterlyMagChange = 0.0; theEasterlyMagChangeUnits = 0; theWesterlyMagChange = 0.0; theWesterlyMagChangeUnits = 0; theMagAngle = 0.0; theMagAngleUnits = 0; theGridConver = 0.0; theGridConverUnits = 0; theHighElevation = 0.0; theHighElevationUnits = 0; theHighLat = 0.0; theHighLon = 0.0; theLegendFileName = ""; theDataSource = ""; theGsd = 0; theDataLevel = 0; theAttributeIdBoolMap.clear(); } void ossimRpfAttributes::setAttributeFlag(ossim_uint32 id, bool flag) { std::map::iterator iter = theAttributeIdBoolMap.find(id); if(iter != theAttributeIdBoolMap.end()) { if(flag) { iter->second = flag; } else { theAttributeIdBoolMap.erase(iter); } } else if(flag) { theAttributeIdBoolMap.insert(std::make_pair(id, flag)); } } bool ossimRpfAttributes::getAttributeFlag(ossim_uint32 id)const { std::map::const_iterator iter = theAttributeIdBoolMap.find(id); if(iter != theAttributeIdBoolMap.end()) { return iter->second; } return false; } ossim-Miami-2.9.1/src/support_data/ossimRpfBoundaryRectRecord.cpp000066400000000000000000000130601352751253100251760ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfBoundaryRectRecord.cpp 17815 2010-08-03 13:23:14Z dburken $ #include /* for memset/memcpy */ #include #include #include #include #include /* ossim::byteOrder() */ #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfBoundaryRectRecord& data) { return data.print( out, std::string() ); } ossimRpfBoundaryRectRecord::ossimRpfBoundaryRectRecord() : m_zone(), m_coverage(), m_numberOfFramesNorthSouth(0), m_numberOfFramesEastWest(0) { clearFields(); } ossimRpfBoundaryRectRecord::ossimRpfBoundaryRectRecord(const ossimRpfBoundaryRectRecord& obj) : m_zone(obj.m_zone), m_coverage(obj.m_coverage), m_numberOfFramesNorthSouth(obj.m_numberOfFramesNorthSouth), m_numberOfFramesEastWest(obj.m_numberOfFramesEastWest) { memcpy(m_productDataType, obj.m_productDataType, 6); memcpy(m_compressionRatio, obj.m_compressionRatio, 6); memcpy(m_scale, obj.m_scale, 13); memcpy(m_producer, obj.m_producer, 6); } const ossimRpfBoundaryRectRecord& ossimRpfBoundaryRectRecord::operator=( const ossimRpfBoundaryRectRecord& rhs) { if ( this != & rhs ) { memcpy(m_productDataType, rhs.m_productDataType, 6); memcpy(m_compressionRatio, rhs.m_compressionRatio, 6); memcpy(m_scale, rhs.m_scale, 13); memcpy(m_producer, rhs.m_producer, 6); m_coverage = rhs.m_coverage; m_numberOfFramesNorthSouth = rhs.m_numberOfFramesNorthSouth; m_numberOfFramesEastWest = rhs.m_numberOfFramesEastWest; } return *this; } ossimRpfBoundaryRectRecord::~ossimRpfBoundaryRectRecord() { } ossimErrorCode ossimRpfBoundaryRectRecord::parseStream(std::istream& in, ossimByteOrder byteOrder) { if(in) { clearFields(); in.read((char*)&m_productDataType, 5); in.read((char*)&m_compressionRatio, 5); in.read((char*)&m_scale, 12); in.read((char*)&m_zone, 1); in.read((char*)&m_producer, 5); ossimString tmpScale(m_scale); tmpScale.trim(); if (!tmpScale.empty()) { if (tmpScale.beforePos(2) != "1:") { if (tmpScale.afterPos(tmpScale.size()-2)!="M" && tmpScale.afterPos(tmpScale.size()-2)!="K") { int tmpScaleValue = tmpScale.toInt(); if (tmpScaleValue > 0) { tmpScale = ossimString("1:" + tmpScale); memset(m_scale, ' ', 12); memcpy(m_scale, tmpScale.c_str(), 12); } } } } m_coverage.parseStream(in, byteOrder); in.read((char*)&m_numberOfFramesNorthSouth, 4); in.read((char*)&m_numberOfFramesEastWest, 4); if( ossim::byteOrder() != byteOrder ) { ossimEndian anEndian; anEndian.swap(m_numberOfFramesNorthSouth); anEndian.swap(m_numberOfFramesEastWest); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfBoundaryRectRecord::writeStream(std::ostream& out) { ossimEndian anEndian; if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Always write out big endian. anEndian.swap(m_numberOfFramesNorthSouth); anEndian.swap(m_numberOfFramesEastWest); } out.write((char*)&m_productDataType, 5); out.write((char*)&m_compressionRatio, 5); out.write((char*)&m_scale, 12); out.write((char*)&m_zone, 1); out.write((char*)&m_producer, 5); m_coverage.writeStream(out); out.write((char*)&m_numberOfFramesNorthSouth, 4); out.write((char*)&m_numberOfFramesEastWest, 4); if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Swap back to native byte order. anEndian.swap(m_numberOfFramesNorthSouth); anEndian.swap(m_numberOfFramesEastWest); } } void ossimRpfBoundaryRectRecord::clearFields() { memset(m_productDataType, ' ', 5); memset(m_compressionRatio, ' ', 5); memset(m_scale, ' ', 12); memset(m_producer, ' ', 5); m_numberOfFramesNorthSouth = 0; m_numberOfFramesEastWest = 0; m_coverage.clearFields(); m_productDataType[5] = '\0'; m_compressionRatio[5] = '\0'; m_scale[12] = '\0'; m_producer[5] = '\0'; m_zone = ' '; } void ossimRpfBoundaryRectRecord::setCoverage(const ossimRpfCoverageSection& coverage) { m_coverage = coverage; } std::ostream& ossimRpfBoundaryRectRecord::print(std::ostream& out, ossimString prefix) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << std::setiosflags(std::ios_base::fixed) << std::setprecision(12) << prefix << "ProductDataType: " << m_productDataType << "\n" << prefix << "CompressionRatio: " << m_compressionRatio << "\n" << prefix << "Scale: " << m_scale << "\n" << prefix << "Zone: " << m_zone << "\n" << prefix << "Producer: " << m_producer << "\n"; m_coverage.print(out, prefix); out << prefix << "NumberOfFramesNorthSouth: " << m_numberOfFramesNorthSouth << "\n" << prefix << "NumberOfFramesEastWest: " << m_numberOfFramesEastWest << "\n"; // Reset flags. out.setf(f); return out; } ossim-Miami-2.9.1/src/support_data/ossimRpfBoundaryRectSectionSubheader.cpp000066400000000000000000000102261352751253100272100ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfBoundaryRectSectionSubheader.cpp 16997 2010-04-12 18:53:48Z dburken $ #include #include #include #include /* ossim::byteOrder() */ #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfBoundaryRectSectionSubheader &data) { return data.print(out); } ossimRpfBoundaryRectSectionSubheader::ossimRpfBoundaryRectSectionSubheader() : m_rectangleTableOffset(0), m_numberOfEntries(0), m_lengthOfEachEntry(0) { } ossimRpfBoundaryRectSectionSubheader::ossimRpfBoundaryRectSectionSubheader( const ossimRpfBoundaryRectSectionSubheader& obj) : m_rectangleTableOffset(obj.m_rectangleTableOffset), m_numberOfEntries(obj.m_numberOfEntries), m_lengthOfEachEntry(obj.m_lengthOfEachEntry) { } const ossimRpfBoundaryRectSectionSubheader& ossimRpfBoundaryRectSectionSubheader::operator=( const ossimRpfBoundaryRectSectionSubheader& rhs) { if ( this != &rhs ) { m_rectangleTableOffset = rhs.m_rectangleTableOffset; m_numberOfEntries = rhs.m_numberOfEntries; m_lengthOfEachEntry = rhs.m_lengthOfEachEntry; } return *this; } ossimRpfBoundaryRectSectionSubheader::~ossimRpfBoundaryRectSectionSubheader() { } ossimErrorCode ossimRpfBoundaryRectSectionSubheader::parseStream(std::istream& in, ossimByteOrder byteOrder) { if(in) { clearFields(); in.read((char*)&m_rectangleTableOffset, 4); in.read((char*)&m_numberOfEntries, 2); in.read((char*)&m_lengthOfEachEntry, 2); if( ossim::byteOrder() != byteOrder ) { ossimEndian anEndian; anEndian.swap(m_rectangleTableOffset); anEndian.swap(m_numberOfEntries); anEndian.swap(m_lengthOfEachEntry); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfBoundaryRectSectionSubheader::writeStream(std::ostream& out) { ossimEndian anEndian; if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Always write out big endian. anEndian.swap(m_rectangleTableOffset); anEndian.swap(m_numberOfEntries); anEndian.swap(m_lengthOfEachEntry); } out.write((char*)&m_rectangleTableOffset, 4); out.write((char*)&m_numberOfEntries, 2); out.write((char*)&m_lengthOfEachEntry, 2); if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Swap back to native. anEndian.swap(m_rectangleTableOffset); anEndian.swap(m_numberOfEntries); anEndian.swap(m_lengthOfEachEntry); } } std::ostream& ossimRpfBoundaryRectSectionSubheader::print(std::ostream& out) const { out << "RectangleTableOffset: " << m_rectangleTableOffset << "\nNumberOfEntries: " << m_numberOfEntries << "\nLengthOfEachEntry: " << m_lengthOfEachEntry << std::endl; return out; } ossim_uint16 ossimRpfBoundaryRectSectionSubheader::getNumberOfEntries() const { return m_numberOfEntries; } ossim_uint32 ossimRpfBoundaryRectSectionSubheader::getTableOffset() const { return m_rectangleTableOffset; } ossim_uint16 ossimRpfBoundaryRectSectionSubheader::getLengthOfEachEntry() const { return m_lengthOfEachEntry; } void ossimRpfBoundaryRectSectionSubheader::setNumberOfEntries(ossim_uint16 entries) { m_numberOfEntries = entries; } void ossimRpfBoundaryRectSectionSubheader::setTableOffset(ossim_uint32 offset) { m_rectangleTableOffset = offset; } void ossimRpfBoundaryRectSectionSubheader::setLengthOfEachEntry(ossim_uint16 length) { m_lengthOfEachEntry = length; } void ossimRpfBoundaryRectSectionSubheader::clearFields() { m_rectangleTableOffset = 0; m_numberOfEntries = 0; m_lengthOfEachEntry = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfBoundaryRectTable.cpp000066400000000000000000000047721352751253100250210ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfBoundaryRectTable.cpp 16997 2010-04-12 18:53:48Z dburken $ #include #include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfBoundaryRectTable& data) { return data.print(out); } ossimRpfBoundaryRectTable::ossimRpfBoundaryRectTable(ossim_uint32 numberOfEntries) : m_table(numberOfEntries) { } ossimRpfBoundaryRectTable::ossimRpfBoundaryRectTable(const ossimRpfBoundaryRectTable& obj) : m_table(obj.m_table) { } const ossimRpfBoundaryRectTable& ossimRpfBoundaryRectTable::operator=( const ossimRpfBoundaryRectTable& rhs) { if ( this != &rhs ) { m_table = rhs.m_table; } return *this; } ossimRpfBoundaryRectTable::~ossimRpfBoundaryRectTable() {} ossimErrorCode ossimRpfBoundaryRectTable::parseStream(std::istream& in, ossimByteOrder byteOrder) { if(in) { std::vector::iterator entry = m_table.begin(); while(entry != m_table.end()) { (*entry).parseStream(in, byteOrder); ++entry; } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfBoundaryRectTable::writeStream(std::ostream& out) { std::vector::iterator entry = m_table.begin(); while ( entry != m_table.end() ) { (*entry).writeStream(out); ++entry; } } void ossimRpfBoundaryRectTable::setNumberOfEntries(ossim_uint32 numberOfEntries) { m_table.resize(numberOfEntries); } ossim_uint32 ossimRpfBoundaryRectTable::getNumberOfEntries() const { return static_cast(m_table.size()); } bool ossimRpfBoundaryRectTable::getEntry( ossim_uint32 entry, ossimRpfBoundaryRectRecord& record) const { bool result = true; if ( entry < m_table.size() ) { record = m_table[entry]; } else { result = false; } return result; } std::ostream& ossimRpfBoundaryRectTable::print(std::ostream& out)const { std::copy(m_table.begin(), m_table.end(), std::ostream_iterator(out, "\n")); return out; } ossim-Miami-2.9.1/src/support_data/ossimRpfColorConverterOffsetRecord.cpp000066400000000000000000000042561352751253100267210ustar00rootroot00000000000000#include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfColorConverterOffsetRecord& data) { out << "theColorConverterTableId: " << data.theColorConverterTableId << "\ntheNumberOfColorConverterRecords: " << data.theNumberOfColorConverterRecords << "\ntheColorConverterTableOffset: " << data.theColorConverterTableOffset << "\ntheSourceColorGrayscaleOffsetTableOffset: " << data.theSourceColorGrayscaleOffsetTableOffset << "\ntheTargetColorGrayscaleOffsetTableOffset: " << data.theTargetColorGrayscaleOffsetTableOffset; return out; } ossimRpfColorConverterOffsetRecord::ossimRpfColorConverterOffsetRecord() { clearFields(); } ossimErrorCode ossimRpfColorConverterOffsetRecord::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { if(in) { in.read((char*)&theColorConverterTableId, 2); in.read((char*)&theNumberOfColorConverterRecords, 4); in.read((char*)&theColorConverterTableOffset, 4); in.read((char*)&theSourceColorGrayscaleOffsetTableOffset, 4); in.read((char*)&theTargetColorGrayscaleOffsetTableOffset, 4); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theColorConverterTableId); anEndian.swap(theNumberOfColorConverterRecords); anEndian.swap(theColorConverterTableOffset); anEndian.swap(theSourceColorGrayscaleOffsetTableOffset); anEndian.swap(theTargetColorGrayscaleOffsetTableOffset); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfColorConverterOffsetRecord::clearFields() { theColorConverterTableId = 0; theNumberOfColorConverterRecords = 0; theColorConverterTableOffset = 0; theSourceColorGrayscaleOffsetTableOffset = 0; theTargetColorGrayscaleOffsetTableOffset = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfColorConverterSubsection.cpp000066400000000000000000000076611352751253100264550ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************** // $Id$ #include #include #include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfColorConverterSubsection& data) { data.print(out); return out; } ossimRpfColorConverterSubsection::ossimRpfColorConverterSubsection() { theNumberOfColorConverterOffsetRecords = 0; clearFields(); } void ossimRpfColorConverterSubsection::clearFields() { theColorConverterOffsetTableOffset = 0; theColorConverterOffsetRecordLength = 0; theConverterRecordLength = 0; theTableList.clear(); } const ossimRpfColorConverterTable* ossimRpfColorConverterSubsection::getColorConversionTable(ossim_uint32 givenThisNumberOfEntires)const { std::vector::const_iterator listElement = theTableList.begin(); while(listElement != theTableList.end()) { if((*listElement).getNumberOfEntries() == givenThisNumberOfEntires) { return &(*listElement); } } return NULL; } ossimErrorCode ossimRpfColorConverterSubsection::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { if(in) { clearFields(); // this is the start of the subsection theStartOffset = in.tellg(); in.read((char*)&theColorConverterOffsetTableOffset, 4); in.read((char*)&theColorConverterOffsetRecordLength, 2); in.read((char*)&theConverterRecordLength, 2); // this grabs the end of the subsection theEndOffset = in.tellg(); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theColorConverterOffsetTableOffset); anEndian.swap(theColorConverterOffsetRecordLength); anEndian.swap(theConverterRecordLength); } theTableList.resize(theNumberOfColorConverterOffsetRecords); for(unsigned long index = 0; index < theNumberOfColorConverterOffsetRecords; ++index) { ossimRpfColorConverterOffsetRecord recordInfo; if(recordInfo.parseStream(in, byteOrder) == ossimErrorCodes::OSSIM_OK) { unsigned long rememberGet = in.tellg(); theTableList[index].setNumberOfEntries(recordInfo.theNumberOfColorConverterRecords); theTableList[index].setTableId(recordInfo.theColorConverterTableId); in.seekg(theStartOffset + recordInfo.theColorConverterTableOffset, std::ios_base::beg); theTableList[index].parseStream(in, byteOrder); in.seekg(rememberGet, std::ios_base::beg); } else { return ossimErrorCodes::OSSIM_ERROR; } } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfColorConverterSubsection::setNumberOfColorConverterOffsetRecords(ossim_uint16 numberOfRecords) { theNumberOfColorConverterOffsetRecords = numberOfRecords; } void ossimRpfColorConverterSubsection::print(std::ostream& out)const { out << "theColorConverterOffsetTableOffset: " << theColorConverterOffsetTableOffset << "\ntheColorConverterOffsetRecordLength: " << theColorConverterOffsetRecordLength << "\ntheConverterRecordLength: " << theConverterRecordLength << "\n"; copy(theTableList.begin(), theTableList.end(), std::ostream_iterator(out, "\n")); } ossim-Miami-2.9.1/src/support_data/ossimRpfColorConverterTable.cpp000066400000000000000000000045571352751253100253670ustar00rootroot00000000000000#include #include #include #include std::ostream& operator <<( std::ostream& out, const ossimRpfColorConverterTable& data) { data.print(out); return out; } ossimRpfColorConverterTable::ossimRpfColorConverterTable() { theTableId = 0; theNumberOfEntries = 0; theColorGrayscaleTableEntryList = NULL; } ossimRpfColorConverterTable::~ossimRpfColorConverterTable() { if(theColorGrayscaleTableEntryList) { delete [] theColorGrayscaleTableEntryList; theColorGrayscaleTableEntryList = NULL; } } ossimErrorCode ossimRpfColorConverterTable::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { if(in) { if(theNumberOfEntries > 0) { in.read((char*)theColorGrayscaleTableEntryList, 4*theNumberOfEntries); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { for(ossim_uint32 index = 0; index < theNumberOfEntries; ++index) { anEndian.swap(theColorGrayscaleTableEntryList[index]); } } } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfColorConverterTable::print(std::ostream& out)const { out << "theTableId: " << theTableId << "\n" << "theNumberOfEntries: " << theNumberOfEntries << "\n"; if(theColorGrayscaleTableEntryList) { out << "Values:\n"; for(ossim_uint32 index=0; index < theNumberOfEntries; index++) { out<< theColorGrayscaleTableEntryList[index] << "\n"; } } } void ossimRpfColorConverterTable::setNumberOfEntries(ossim_uint32 entries) { if(theColorGrayscaleTableEntryList) { delete [] theColorGrayscaleTableEntryList; theColorGrayscaleTableEntryList = NULL; } theColorGrayscaleTableEntryList = new ossim_uint32[entries]; theNumberOfEntries = entries; for(ossim_uint32 index=0; index < theNumberOfEntries; ++index) { theColorGrayscaleTableEntryList[index] = 0; } } void ossimRpfColorConverterTable::setTableId(ossim_uint16 id) { theTableId = id; } ossim-Miami-2.9.1/src/support_data/ossimRpfColorGrayscaleOffsetRecord.cpp000066400000000000000000000045141352751253100266610ustar00rootroot00000000000000#include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfColorGrayscaleOffsetRecord& data) { data.print(out); return out; } ossimRpfColorGrayscaleOffsetRecord::ossimRpfColorGrayscaleOffsetRecord() { clearFields(); } ossimErrorCode ossimRpfColorGrayscaleOffsetRecord::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { if(in) { clearFields(); in.read((char*)&theColorGrayscaleTableId, 2); in.read((char*)&theNumberOfColorGrayscaleRecords, 4); in.read((char*)&theColorGrayscaleElementLength, 1); in.read((char*)&theHistogramRecordLength, 2); in.read((char*)&theColorGrayscaleTableOffset, 4); in.read((char*)&theHistogramTableOffset, 4); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theColorGrayscaleTableId); anEndian.swap(theNumberOfColorGrayscaleRecords); anEndian.swap(theHistogramRecordLength); anEndian.swap(theColorGrayscaleTableOffset); anEndian.swap(theHistogramTableOffset); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfColorGrayscaleOffsetRecord::print(std::ostream& out)const { out << "theColorGrayscaleTableId: " << theColorGrayscaleTableId << "\ntheNumberOfColorGrayscaleRecords: " << theNumberOfColorGrayscaleRecords << "\ntheColorGrayscaleElementLength: " << (unsigned long)theColorGrayscaleElementLength << "\ntheHistogramRecordLength: " << theHistogramRecordLength << "\ntheColorGrayscaleTableOffset: " << theColorGrayscaleTableOffset << "\ntheHistogramTableOffset: " << theHistogramTableOffset; } void ossimRpfColorGrayscaleOffsetRecord::clearFields() { theColorGrayscaleTableId = 0; theNumberOfColorGrayscaleRecords = 0; theColorGrayscaleElementLength = 0; theHistogramRecordLength = 0; theColorGrayscaleTableOffset = 0; theHistogramTableOffset = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfColorGrayscaleSubheader.cpp000066400000000000000000000033011352751253100261670ustar00rootroot00000000000000#include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfColorGrayscaleSubheader& data) { data.print(out); return out; } ossimRpfColorGrayscaleSubheader::ossimRpfColorGrayscaleSubheader() { clearFields(); } ossimErrorCode ossimRpfColorGrayscaleSubheader::parseStream(ossim::istream& in, ossimByteOrder /* byteOrder */) { if(in) { clearFields(); theStartOffset = in.tellg(); in.read((char*)&theNumberOfColorGreyscaleOffsetRecords, 1); in.read((char*)&theNumberOfColorConverterOffsetRecords, 1); char tempString[12]; in.read(tempString, 12); theColorGrayscaleFilename = ossimString(tempString, (char*)(&tempString[12])); theEndOffset = in.tellg(); } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfColorGrayscaleSubheader::print(std::ostream& out)const { out << "theNumberOfColorGreyscaleOffsetRecords: " << (int)theNumberOfColorGreyscaleOffsetRecords << "\ntheNumberOfColorConverterOffsetRecords: " << (int)theNumberOfColorConverterOffsetRecords << "\ntheColorGrayscaleFilename: " << theColorGrayscaleFilename; } void ossimRpfColorGrayscaleSubheader::clearFields() { theStartOffset = 0; theEndOffset = 0; theNumberOfColorGreyscaleOffsetRecords = 0; theNumberOfColorConverterOffsetRecords = 0; theColorGrayscaleFilename = ""; } ossim-Miami-2.9.1/src/support_data/ossimRpfColorGrayscaleTable.cpp000066400000000000000000000063651352751253100253310ustar00rootroot00000000000000#include #include // for memcpy #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfColorGrayscaleTable& data) { out << "theNumberOfElements: " << data.theNumberOfElements << "\ntheTotalNumberOfBytes: " << data.theTotalNumberOfBytes << "\ntheTableId: " << data.theTableId; return out; } ossimRpfColorGrayscaleTable::ossimRpfColorGrayscaleTable() :theNumberOfElements(0), theTotalNumberOfBytes(0), theTableId(0), theData(NULL) { } ossimRpfColorGrayscaleTable::ossimRpfColorGrayscaleTable(const ossimRpfColorGrayscaleTable& rhs) :theNumberOfElements(0), theTotalNumberOfBytes(0), theTableId(0), theData(NULL) { *this = rhs; } ossimRpfColorGrayscaleTable::~ossimRpfColorGrayscaleTable() { if(theData) { delete [] theData; theData = NULL; } } ossimErrorCode ossimRpfColorGrayscaleTable::parseStream(ossim::istream& in, ossimByteOrder /* byteOrder */) { if(in) { if((theTotalNumberOfBytes > 0)&&theData) { in.read((char*)theData, theTotalNumberOfBytes); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } const unsigned char* ossimRpfColorGrayscaleTable::getStartOfData(unsigned long entry)const { unsigned long offset = 0; switch(theTableId) { case 1: // this is in format RGB { offset = 3*entry; break; } case 2: // format RGBM case 4: // format CMYK { offset = 4*entry; break; } case 3: // format M { offset = entry; break; } } return (const unsigned char*)(theData + offset); } void ossimRpfColorGrayscaleTable::setTableData(unsigned short id, unsigned long numberOfElements) { if(theData) { delete theData; theData = NULL; } unsigned long totalBytes = 0; switch(id) { case 1: // this is in format RGB { totalBytes = 3*numberOfElements; break; } case 2: // format RGBM case 4: // format CMYK { totalBytes = 4*numberOfElements; break; } case 3: // format M { totalBytes = numberOfElements; break; } } if(totalBytes > 0) { theTableId = id; theNumberOfElements = numberOfElements; theTotalNumberOfBytes = totalBytes; theData = new unsigned char[totalBytes]; } } const ossimRpfColorGrayscaleTable& ossimRpfColorGrayscaleTable::operator =(const ossimRpfColorGrayscaleTable& rhs) { if(&rhs != this) { theNumberOfElements = rhs.theNumberOfElements; theTotalNumberOfBytes = rhs.theTotalNumberOfBytes; theTableId = rhs.theTableId; if(theData) { delete theData; theData = NULL; } if(theTotalNumberOfBytes&&rhs.theData) { theData = new unsigned char[theTotalNumberOfBytes]; memcpy(theData, rhs.theData, theTotalNumberOfBytes); } } return *this; } ossim-Miami-2.9.1/src/support_data/ossimRpfComponentIdLut.cpp000066400000000000000000000110261352751253100243420ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimRpfComponentIdLut.cpp // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Lookup table for mapping RPF component ID's to strings. // // See MIL-STD-2411-1, section 5.1.1 for detailed information. // //---------------------------------------------------------------------------- // $Id: ossimRpfComponentIdLut.cpp 20324 2011-12-06 22:25:23Z dburken $ #include ossimRpfComponentIdLut* ossimRpfComponentIdLut::theInstance = 0; ossimRpfComponentIdLut* ossimRpfComponentIdLut::instance() { if (!theInstance) { theInstance = new ossimRpfComponentIdLut; } return theInstance; } ossimRpfComponentIdLut::ossimRpfComponentIdLut() { //--- // Complete initialization of data member "theTable". // Note: ID's defined in ossimRpfConstants.h file. //--- ossimKeyValueMap entry; entry.init(OSSIM_RPF_HEADER_COMPONENT, "RPF_HEADER_COMPONENT"); theTable.push_back(entry); entry.init(OSSIM_RPF_LOCATION_COMPONENT, "RPF_LOCATION_COMPONENT"); theTable.push_back(entry); entry.init(OSSIM_RPF_COVERAGE_SECTION_SUBHEADER, "RPF_COVERAGE_SECTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_COMPRESSION_SECTION_SUBHEADER, "RPF_COMPRESSION_SECTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_COMPRESION_LOOKUP_SUBSECTION, "RPF_COMPRESION_LOOKUP_SUBSECTION"); theTable.push_back(entry); entry.init(OSSIM_RPF_COMPRESION_PARAMETER_SUBSECTION, "RPF_COMPRESION_PARAMETER_SUBSECTION"); theTable.push_back(entry); entry.init(OSSIM_RPF_COLOR_GRAYSCALE_SECTION_SUBHEADER, "RPF_COLOR_GRAYSCALE_SECTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_COLORMAP_SUBSECTION, "RPF_COLORMAP_SUBSECTION"); theTable.push_back(entry); entry.init(OSSIM_RPF_IMAGE_DESCRIPTION_SUBHEADER, "RPF_IMAGE_DESCRIPTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_IMAGE_DISPLAY_PARAMETERS_SUBHEADER, "RPF_IMAGE_DISPLAY_PARAMETERS_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_MASK_SUBSECTION, "RPF_MASK_SUBSECTION"); theTable.push_back(entry); entry.init(OSSIM_RPF_COLOR_CONVERTER_SUBSECTION, "RPF_COLOR_CONVERTER_SUBSECTION"); theTable.push_back(entry); entry.init(OSSIM_RPF_SPATIAL_DATA_SUBSECTION, "RPF_SPATIAL_DATA_SUBSECTION"); theTable.push_back(entry); entry.init(OSSIM_RPF_ATTRIBUTE_SECTION_SUBHEADER, "RPF_ATTRIBUTE_SECTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_ATTRIBUTE_SUBSECTION, "RPF_ATTRIBUTE_SUBSECTION"); theTable.push_back(entry); entry.init(OSSIM_RPF_EXPLICIT_AREAL_COVERAGE_TABLE, "RPF_EXPLICIT_AREAL_COVERAGE_TABLE"); theTable.push_back(entry); entry.init(OSSIM_RPF_RELATED_IMAGES_SECTION_SUBHEADER, "RPF_RELATED_IMAGES_SECTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_RELATED_IMAGES_SUBSECTION, "RPF_RELATED_IMAGES_SUBSECTION"); theTable.push_back(entry); entry.init(OSSIM_RPF_REPLACE_UPDATE_SECTION_SUBHEADER, "RPF_REPLACE_UPDATE_SECTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_REPLACE_UPDATE_TABLE, "RPF_REPLACE_UPDATE_TABLE"); theTable.push_back(entry); entry.init(OSSIM_RPF_BOUNDARY_RECT_SECTION_SUBHEADER, "RPF_BOUNDARY_RECT_SECTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_BOUNDARY_RECT_TABLE, "RPF_BOUNDARY_RECT_TABLE"); theTable.push_back(entry); entry.init(OSSIM_RPF_FRAME_FILE_INDEX_SECTION_SUBHEADER, "RPF_FRAME_FILE_INDEX_SECTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_FRAME_FILE_INDEX_SUBSECTION, "RPF_FRAME_FILE_INDEX_SUBSECTION"); theTable.push_back(entry); entry.init(OSSIM_RPF_COLOR_TABLE_INDEX_SECTION_SUBHEADER, "RPF_COLOR_TABLE_INDEX_SECTION_SUBHEADER"); theTable.push_back(entry); entry.init(OSSIM_RPF_COLOR_TABLE_INDEX_RECORD, "RPF_COLOR_TABLE_INDEX_RECORD"); theTable.push_back(entry); } ossimRpfComponentIdLut::~ossimRpfComponentIdLut() { theInstance = 0; } ossimKeyword ossimRpfComponentIdLut::getKeyword() const { return ossimKeyword("rpf_component_id", ""); } ossim-Miami-2.9.1/src/support_data/ossimRpfCompressionLookupOffsetRecord.cpp000066400000000000000000000045011352751253100274370ustar00rootroot00000000000000#include #include #include #include std::ostream& operator <<(std::ostream &out, const ossimRpfCompressionLookupOffsetRecord& data) { data.print(out); return out; } ossimRpfCompressionLookupOffsetRecord::ossimRpfCompressionLookupOffsetRecord() { clearFields(); } ossimErrorCode ossimRpfCompressionLookupOffsetRecord::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { if(in) { ossimEndian anEndian; in.read((char*)&theCompressionLookupTableId, 2); in.read((char*)&theNumberOfCompressionLookupRecords, 4); in.read((char*)&theNumberOfValuesPerCompressionLookupRecord, 2); in.read((char*)&theCompressionLookupValueBitLength, 2); in.read((char*)&theCompressionLookupTableOffset, 4); if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theCompressionLookupTableId); anEndian.swap(theNumberOfCompressionLookupRecords); anEndian.swap(theNumberOfValuesPerCompressionLookupRecord); anEndian.swap(theCompressionLookupValueBitLength); anEndian.swap(theCompressionLookupTableOffset); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfCompressionLookupOffsetRecord::print(std::ostream& out)const { out << "theCompressionLookupTableId: " << theCompressionLookupTableId << "\ntheNumberOfCompressionLookupRecords: " << theNumberOfCompressionLookupRecords << "\ntheNumberOfValuesPerCompressionLookupRecord: " << theNumberOfValuesPerCompressionLookupRecord << "\ntheCompressionLookupValueBitLength: " << theCompressionLookupValueBitLength << "\ntheCompressionLookupTableOffset: " << theCompressionLookupTableOffset; } void ossimRpfCompressionLookupOffsetRecord::clearFields() { theCompressionLookupTableId = 0; theNumberOfCompressionLookupRecords = 0; theNumberOfValuesPerCompressionLookupRecord = 0; theCompressionLookupValueBitLength = 0; theCompressionLookupTableOffset = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfCompressionSection.cpp000066400000000000000000000145171352751253100252740ustar00rootroot00000000000000#include #include #include #include #include #include #include // for memset #include std::ostream& operator<<(std::ostream& out, const ossimRpfCompressionOffsetTableData& data) { unsigned long size = (data.theNumberOfValuesPerLookup*data.theNumberOfLookupValues* data.theCompressionLookupValueBitLength)/8; out << "theTableId: " << data.theTableId << "\ntheNumberOfLookupValues: " << data.theNumberOfLookupValues << "\ntheCompressionLookupValueBitLength: " << data.theCompressionLookupValueBitLength << "\ntheNumberOfValuesPerLookup: " << data.theNumberOfValuesPerLookup << "\nData Size in bytes: " << size; return out; } ossimRpfCompressionOffsetTableData::ossimRpfCompressionOffsetTableData() :theTableId(0), theNumberOfLookupValues(0), theCompressionLookupValueBitLength(0), theNumberOfValuesPerLookup(0), theData(NULL) { } ossimRpfCompressionOffsetTableData::ossimRpfCompressionOffsetTableData( const ossimRpfCompressionOffsetTableData& rhs) :theNumberOfLookupValues(0), theCompressionLookupValueBitLength(0), theNumberOfValuesPerLookup(0), theData(NULL) { *this = rhs; } const ossimRpfCompressionOffsetTableData& ossimRpfCompressionOffsetTableData::operator = ( const ossimRpfCompressionOffsetTableData& rhs) { if(this != &rhs) { if(theData) { delete [] theData; theData = 0; } if(rhs.theData) { theTableId = rhs.theTableId; theNumberOfLookupValues = rhs.theNumberOfLookupValues; theCompressionLookupValueBitLength = rhs.theCompressionLookupValueBitLength; theNumberOfValuesPerLookup = rhs.theNumberOfValuesPerLookup; unsigned long size = (theNumberOfValuesPerLookup* theNumberOfLookupValues* theCompressionLookupValueBitLength)/8; if(size > 0) { theData = new unsigned char[size]; memcpy(theData, rhs.theData, size); } } else { theTableId = 0; theNumberOfLookupValues = 0; theCompressionLookupValueBitLength = 0; theNumberOfValuesPerLookup = 0; } } return *this; } ossimRpfCompressionOffsetTableData::~ossimRpfCompressionOffsetTableData() { if(theData) { delete [] theData; theData = 0; } } std::ostream& operator << ( std::ostream& out, const ossimRpfCompressionSection& data) { data.print(out); return out; } ossimRpfCompressionSection::ossimRpfCompressionSection() :theSubheader(NULL) { theSubheader = new ossimRpfCompressionSectionSubheader; } ossimRpfCompressionSection::~ossimRpfCompressionSection() { if(theSubheader) { delete theSubheader; theSubheader = NULL; } } ossimErrorCode ossimRpfCompressionSection::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { ossimErrorCode result = ossimErrorCodes::OSSIM_OK; if(in&&theSubheader) { result = theSubheader->parseStream(in, byteOrder); if(result == ossimErrorCodes::OSSIM_OK) { ossimEndian anEndian; ossimRpfCompressionLookupOffsetRecord record; in.read((char*)&theCompressionLookupOffsetTableOffset, 4); in.read((char*)&theCompressionLookupTableOffsetRecordLength, 2); if(byteOrder != anEndian.getSystemEndianType()) { anEndian.swap(theCompressionLookupOffsetTableOffset); anEndian.swap(theCompressionLookupTableOffsetRecordLength); } if(theSubheader->getNumberOfCompressionLookupOffsetRecords() > 0) { // clear the table theTable.clear(); // resize it theTable.resize(theSubheader->getNumberOfCompressionLookupOffsetRecords()); // now populate it for(long index = 0; index < theSubheader->getNumberOfCompressionLookupOffsetRecords(); ++index) { record.parseStream(in, byteOrder); unsigned long rememberLocation = in.tellg(); in.seekg(record.getCompressionLookupTableOffset()+ theSubheader->getEndOffset(), std::ios_base::beg); theTable[index].theTableId = record.getCompressionLookupTableId(); theTable[index].theNumberOfLookupValues = record.getNumberOfCompressionLookupRecords(); theTable[index].theCompressionLookupValueBitLength = record.getCompressionLookupValueBitLength(); theTable[index].theNumberOfValuesPerLookup = record.getNumberOfValuesPerCompressionLookupRecord(); // store the information about this compress/decompress algorithm // I am not sure but I will assume that the bit length can be // arbitrary. In other words if someone says that the bit length of // the lookup value is 12 this should be handled ok. // unsigned long size = (theTable[index].theNumberOfValuesPerLookup* theTable[index].theNumberOfLookupValues* theTable[index].theCompressionLookupValueBitLength)/8; theTable[index].theData = new unsigned char[size]; in.read( (char*)theTable[index].theData, size); in.seekg(rememberLocation, std::ios_base::beg); } } } } else { result = ossimErrorCodes::OSSIM_ERROR; } return result; } void ossimRpfCompressionSection::print(std::ostream& out)const { if(theSubheader) { out << *theSubheader << "\n"; copy(theTable.begin(), theTable.end(), std::ostream_iterator(out, "\n")); } } ossim-Miami-2.9.1/src/support_data/ossimRpfCompressionSectionSubheader.cpp000066400000000000000000000037361352751253100271200ustar00rootroot00000000000000#include #include #include #include ossimRpfCompressionSectionSubheader::ossimRpfCompressionSectionSubheader() { clearFields(); } std::ostream& operator<<(std::ostream& out, const ossimRpfCompressionSectionSubheader& data) { data.print(out); return out; } ossimErrorCode ossimRpfCompressionSectionSubheader::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { if(in) { theStartOffset = in.tellg(); in.read((char*)&theCompressionAlgorithmId, 2); in.read((char*)&theNumberOfCompressionLookupOffsetRecords, 2); in.read((char*)&theNumberOfCompressionParameterOffsetRecords, 2); theEndOffset = in.tellg(); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theCompressionAlgorithmId); anEndian.swap(theNumberOfCompressionLookupOffsetRecords); anEndian.swap(theNumberOfCompressionParameterOffsetRecords); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfCompressionSectionSubheader::print(std::ostream& out)const { out << "theCompressionAlgorithmId: " << theCompressionAlgorithmId << "\ntheNumberOfCompressionLookupOffsetRecords: " << theNumberOfCompressionLookupOffsetRecords << "\ntheNumberOfCompressionParameterOffsetRecords: " << theNumberOfCompressionParameterOffsetRecords; } void ossimRpfCompressionSectionSubheader::clearFields() { theStartOffset = 0; theEndOffset = 0; theCompressionAlgorithmId = 0; theNumberOfCompressionLookupOffsetRecords = 0; theNumberOfCompressionParameterOffsetRecords = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfCoverageSection.cpp000066400000000000000000000202721352751253100245210ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfCoverageSection.cpp 16997 2010-04-12 18:53:48Z dburken $ #include #include #include #include /* ossim::byteOrder */ #include std::ostream& operator <<(std::ostream &out, const ossimRpfCoverageSection &data) { return data.print(out); } ossimRpfCoverageSection::ossimRpfCoverageSection() : theUpperLeftLat(0.0), theUpperLeftLon(0.0), theLowerLeftLat(0.0), theLowerLeftLon(0.0), theUpperRightLat(0.0), theUpperRightLon(0.0), theLowerRightLat(0.0), theLowerRightLon(0.0), theVerticalResolution(0.0), theHorizontalResolution(0.0), theVerticalInterval(0.0), theHorizontalInterval(0.0) { } ossimRpfCoverageSection::ossimRpfCoverageSection(const ossimRpfCoverageSection& obj) : theUpperLeftLat(obj.theUpperLeftLat), theUpperLeftLon(obj.theUpperLeftLon), theLowerLeftLat(obj.theLowerLeftLat), theLowerLeftLon(obj.theLowerLeftLon), theUpperRightLat(obj.theUpperRightLat), theUpperRightLon(obj.theUpperRightLon), theLowerRightLat(obj.theLowerRightLat), theLowerRightLon(obj.theLowerRightLon), theVerticalResolution(obj.theVerticalResolution), theHorizontalResolution(obj.theHorizontalResolution), theVerticalInterval(obj.theVerticalInterval), theHorizontalInterval(obj.theHorizontalInterval) { } const ossimRpfCoverageSection& ossimRpfCoverageSection::operator=( const ossimRpfCoverageSection& rhs) { if ( this != & rhs ) { theUpperLeftLat = rhs.theUpperLeftLat; theUpperLeftLon = rhs.theUpperLeftLon; theLowerLeftLat = rhs.theLowerLeftLat; theLowerLeftLon = rhs.theLowerLeftLon; theUpperRightLat = rhs.theUpperRightLat; theUpperRightLon = rhs.theUpperRightLon; theLowerRightLat = rhs.theLowerRightLat; theLowerRightLon = rhs.theLowerRightLon; theVerticalResolution = rhs.theVerticalResolution; theHorizontalResolution = rhs.theHorizontalResolution; theVerticalInterval = rhs.theVerticalInterval; theHorizontalInterval = rhs.theHorizontalInterval; } return *this; } ossimErrorCode ossimRpfCoverageSection::parseStream(std::istream &in, ossimByteOrder byteOrder) { if(in) { in.read((char*)&theUpperLeftLat, 8); in.read((char*)&theUpperLeftLon, 8); in.read((char*)&theLowerLeftLat, 8); in.read((char*)&theLowerLeftLon, 8); in.read((char*)&theUpperRightLat, 8); in.read((char*)&theUpperRightLon, 8); in.read((char*)&theLowerRightLat, 8); in.read((char*)&theLowerRightLon, 8); in.read((char*)&theVerticalResolution, 8); in.read((char*)&theHorizontalResolution, 8); in.read((char*)&theVerticalInterval, 8); in.read((char*)&theHorizontalInterval, 8); if( ossim::byteOrder() != byteOrder ) { ossimEndian anEndian; anEndian.swap(theUpperLeftLat); anEndian.swap(theUpperLeftLon); anEndian.swap(theLowerLeftLat); anEndian.swap(theLowerLeftLon); anEndian.swap(theUpperRightLat); anEndian.swap(theUpperRightLon); anEndian.swap(theLowerRightLat); anEndian.swap(theLowerRightLon); anEndian.swap(theVerticalResolution); anEndian.swap(theHorizontalResolution); anEndian.swap(theVerticalInterval); anEndian.swap(theHorizontalInterval); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfCoverageSection::writeStream(std::ostream& out) { ossimEndian anEndian; if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Always write out big endian. anEndian.swap(theUpperLeftLat); anEndian.swap(theUpperLeftLon); anEndian.swap(theLowerLeftLat); anEndian.swap(theLowerLeftLon); anEndian.swap(theUpperRightLat); anEndian.swap(theUpperRightLon); anEndian.swap(theLowerRightLat); anEndian.swap(theLowerRightLon); anEndian.swap(theVerticalResolution); anEndian.swap(theHorizontalResolution); anEndian.swap(theVerticalInterval); anEndian.swap(theHorizontalInterval); } out.write((char*)&theUpperLeftLat, 8); out.write((char*)&theUpperLeftLon, 8); out.write((char*)&theLowerLeftLat, 8); out.write((char*)&theLowerLeftLon, 8); out.write((char*)&theUpperRightLat, 8); out.write((char*)&theUpperRightLon, 8); out.write((char*)&theLowerRightLat, 8); out.write((char*)&theLowerRightLon, 8); out.write((char*)&theVerticalResolution, 8); out.write((char*)&theHorizontalResolution, 8); out.write((char*)&theVerticalInterval, 8); out.write((char*)&theHorizontalInterval, 8); if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Swap back to native byte order. anEndian.swap(theUpperLeftLat); anEndian.swap(theUpperLeftLon); anEndian.swap(theLowerLeftLat); anEndian.swap(theLowerLeftLon); anEndian.swap(theUpperRightLat); anEndian.swap(theUpperRightLon); anEndian.swap(theLowerRightLat); anEndian.swap(theLowerRightLon); anEndian.swap(theVerticalResolution); anEndian.swap(theHorizontalResolution); anEndian.swap(theVerticalInterval); anEndian.swap(theHorizontalInterval); } } std::ostream& ossimRpfCoverageSection::print( std::ostream& out, const std::string& prefix) const { out << prefix << "ul_lat: " << theUpperLeftLat << "\n" << prefix << "ul_lon: " << theUpperLeftLon << "\n" << prefix << "ll_lat: " << theLowerLeftLat << "\n" << prefix << "ll_lon: " << theLowerLeftLon << "\n" << prefix << "ur_lat: " << theUpperRightLat << "\n" << prefix << "ur_lon: " << theUpperRightLon << "\n" << prefix << "lr_lat: " << theLowerRightLat << "\n" << prefix << "lr_lon: " << theLowerRightLon << "\n" << prefix << "vertical_resolution: " << theVerticalResolution << "\n" << prefix << "horizontal_resolution: " << theHorizontalResolution << "\n" << prefix << "vertical_interval: " << theVerticalInterval << "\n" << prefix << "horizontal_interval: " << theHorizontalInterval << std::endl; return out; } void ossimRpfCoverageSection::clearFields() { theUpperLeftLat = 0.0; theUpperLeftLon = 0.0; theLowerLeftLat = 0.0; theLowerLeftLon = 0.0; theUpperRightLat = 0.0; theUpperRightLon = 0.0; theLowerRightLat = 0.0; theLowerRightLon = 0.0; theVerticalResolution = 0.0; theHorizontalResolution = 0.0; theVerticalInterval = 0.0; theHorizontalInterval = 0.0; } void ossimRpfCoverageSection::setUlLat(ossim_float64 value) { theUpperLeftLat = value; } void ossimRpfCoverageSection::setUlLon(ossim_float64 value) { theUpperLeftLon = value; } void ossimRpfCoverageSection::setLlLat(ossim_float64 value) { theLowerLeftLat = value; } void ossimRpfCoverageSection::setLlLon(ossim_float64 value) { theLowerLeftLon = value; } void ossimRpfCoverageSection::setLrLat(ossim_float64 value) { theLowerRightLat = value; } void ossimRpfCoverageSection::setLrLon(ossim_float64 value) { theLowerRightLon = value; } void ossimRpfCoverageSection::setUrLat(ossim_float64 value) { theUpperRightLat = value; } void ossimRpfCoverageSection::setUrLon(ossim_float64 value) { theUpperRightLon = value; } void ossimRpfCoverageSection::setVerticalResolution(ossim_float64 value) { theVerticalResolution = value; } void ossimRpfCoverageSection::setHorizontalResolution(ossim_float64 value) { theHorizontalResolution = value; } void ossimRpfCoverageSection::setVerticalInterval(ossim_float64 value) { theVerticalInterval = value; } void ossimRpfCoverageSection::setHorizontalInterval(ossim_float64 value) { theHorizontalInterval = value; } ossim-Miami-2.9.1/src/support_data/ossimRpfFrame.cpp000066400000000000000000001206711352751253100224770ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This class give the capability to access tiles from an // rpf file. // //******************************************************************** // $Id: ossimRpfFrame.cpp 23345 2015-05-29 13:05:51Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static const ossimTrace traceDebug("ossimRpfFrame:debug"); std::ostream& operator <<(std::ostream& out, const ossimRpfFrame& data) { data.print(out); return out; } ossimRpfFrame::ossimRpfFrame() :theHeader(0), theFilename(""), theCoverage(0), theAttributes(0), theImageDescriptionSubheader(0), theMaskSubheader(0), theImageDisplayParameterSubheader(0), theCompressionSection(0), theColorGrayscaleSubheader(0), theColorConverterSubsection(0), theNitfFile(0), theSubframeMaskTable(0), theSubframeTransparencyMaskTable(0), theReplaceUpdateTable(0) { } ossimRpfFrame::~ossimRpfFrame() { deleteAll(); } std::ostream& ossimRpfFrame::print(std::ostream& out, const std::string& prefix) const { if (traceDebug()) { out << "begin_rpf_frame_print:\n"; } if(theHeader) { theHeader->print(out, prefix); } out << prefix << "filename: " << theFilename << "\n"; if ( theReplaceUpdateTable.valid() ) { theReplaceUpdateTable->print(out, prefix); } if (traceDebug()) { if(theCoverage) { theCoverage->print(out, prefix); } } //--- // Derived series code from first two characters of file extension. // Note ChartSeriesCode from RPF Frame attributes may or may not be // present. //--- if ( theFilename.size() ) { ossimString ext = theFilename.ext(); if ( ext.size() > 1 ) { ext.upcase(); out << prefix << "SeriesCode: " << ext.string().substr(0, 2) << "\n"; } } if(theAttributes) { theAttributes->print(out, prefix); } if (traceDebug()) { if(theImageDescriptionSubheader) { theImageDescriptionSubheader->print(out, prefix); } if(theMaskSubheader) { out << *theMaskSubheader << endl; } if(theImageDisplayParameterSubheader) { out << *theImageDisplayParameterSubheader << endl; } if(theCompressionSection) { out << *theCompressionSection << endl; } if(theColorGrayscaleSubheader) { out << *theColorGrayscaleSubheader << endl; } if(theColorConverterSubsection) { out << *theColorConverterSubsection << endl; } copy(theColorGrayscaleTable.begin(), theColorGrayscaleTable.end(), ostream_iterator(out, "\n")); if(theImageDescriptionSubheader&& !(theImageDescriptionSubheader->isSubframeMaskTableOffsetNull())) { out << "Subframe Mask Table:" << endl; unsigned long spectralIndex; unsigned long rowIndex; unsigned long colIndex; // first loop through the Mask table and allocate while we do it for(spectralIndex = 0; spectralIndex < theImageDescriptionSubheader->getNumberOfSpectralGroups(); ++spectralIndex) { for(rowIndex = 0; rowIndex < theImageDescriptionSubheader->getNumberOfSubframesVertical(); ++rowIndex) { for(colIndex = 0; colIndex < theImageDescriptionSubheader->getNumberOfSubframesHorizontal(); ++colIndex) { if( theSubframeMaskTable[spectralIndex][rowIndex][colIndex] == OSSIM_RPF_ULONG_NULL) { out << "NULL "; } else { out << theSubframeMaskTable[spectralIndex][rowIndex][colIndex] << " "; } } out << endl; } } } if(theImageDescriptionSubheader&& !(theImageDescriptionSubheader->isTransparencyMaskTableOffsetNull())) { out << "Transparency Mask Table:" << endl; unsigned long spectralIndex; unsigned long rowIndex; unsigned long colIndex; // first loop through the Mask table and allocate while we do it for(spectralIndex = 0; spectralIndex < theImageDescriptionSubheader->getNumberOfSpectralGroups(); ++spectralIndex) { for(rowIndex = 0; rowIndex < theImageDescriptionSubheader->getNumberOfSubframesVertical(); ++rowIndex) { for(colIndex = 0; colIndex < theImageDescriptionSubheader->getNumberOfSubframesHorizontal(); ++colIndex) { if( theSubframeTransparencyMaskTable[spectralIndex][rowIndex][colIndex] == OSSIM_RPF_ULONG_NULL) { out << "NULL "; } else { out << theSubframeTransparencyMaskTable[spectralIndex][rowIndex][colIndex] << " "; } } } } } out << "end_rpf_frame_print:\n"; } // matches: if (traceDebug()) out << std::endl; return out; } ossimErrorCode ossimRpfFrame::parseFile(const ossimFilename& filename, bool minimalParse) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::parseFile: entered......" << std::endl; } ossimErrorCode result = ossimErrorCodes::OSSIM_OK; //Make sure any fileds have beend cleared clearFields(); // Make sure all data is deleted. The initialize call the // populate methods. These methods will re-allocate the information deleteAll(); theNitfFile = new ossimNitfFile; theNitfFile->parseFile(filename); const ossimRefPtr nitfFileHeader = theNitfFile.valid() ? theNitfFile->getHeader() : 0; if(!nitfFileHeader) { theNitfFile = 0; return ossimErrorCodes::OSSIM_ERROR; } ossimNitfTagInformation info; nitfFileHeader->getTag(info, "RPFHDR"); theFilename = filename; if(info.getTagName() == "RPFHDR") { ifstream in(filename.c_str(), ios::in|ios::binary); // set the get pointer for the stream to the start // of the Rpf header data in.seekg(info.getTagDataOffset(), ios::beg); if(theHeader) delete theHeader; theHeader = new ossimRpfHeader; // if(theHeader->parseStream(in) != ossimErrorCodes::OSSIM_OK) theHeader->parseStream(in); if ( in.fail() ) { deleteAll(); return ossimErrorCodes::OSSIM_ERROR; } else // if(!in.fail()&&theHeader) { result = populateAttributeSection(in); // This is needed for ossim-rpf --list-frames so NOT put in full parse section. if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateReplaceUpdateTable(in); } if ( minimalParse == false ) { if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { populateCompressionSection(in); } if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateCoverageSection(in); } if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateImageSection(in); } if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateColorGrayscaleSection(in); } if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateMasks(in); } } } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } bool ossimRpfFrame::hasSubframeMaskTable()const { if(theImageDescriptionSubheader) { return (!theImageDescriptionSubheader->isSubframeMaskTableOffsetNull()); } return false; } bool ossimRpfFrame::fillSubFrameBuffer(ossim_uint8* buffer, ossim_uint32 /* spectralGroup */, ossim_uint32 row, ossim_uint32 col)const { if(theImageDescriptionSubheader && theImageDisplayParameterSubheader&& theHeader&& (col < theImageDescriptionSubheader->getNumberOfSubframesHorizontal()) && (row < theImageDescriptionSubheader->getNumberOfSubframesVertical())) { ossimRpfComponentLocationRecord info; if(!theHeader->getLocationSection()->getComponent(OSSIM_RPF_SPATIAL_DATA_SUBSECTION, info)) { return false; } ossim_uint32 offset = info.m_componentLocation; ossim_uint32 bytesPerSubframe = 0; // note that the code length is bit encoded so we must devide by 8 // in order to get the byte offset instead of the bit offset. We // then add that to the start of the spatial data section which is // the current value of offset. bytesPerSubframe = (theImageDisplayParameterSubheader->getNumberOfImageRows()* theImageDisplayParameterSubheader->getNumberOfImageCodesPerRow()* theImageDisplayParameterSubheader->getImageCodeLength())/8; if(hasSubframeMaskTable()) { // check to see if the offset is NULL. If it is // then just return false to let the caller know that the // buffer did not exist. if(theSubframeMaskTable[0][row][col] != OSSIM_RPF_ULONG_NULL) { offset += theSubframeMaskTable[0][row][col]; } else { return false; } } else { ossim_uint32 bytes = bytesPerSubframe*(row*theImageDescriptionSubheader->getNumberOfSubframesHorizontal()+ col); offset += bytes; } // now since we have the adjustment and we got to this point then // we can read in the data into the destination buffer. ifstream in(theFilename.c_str(), ios::in|ios::binary); if(!in.fail()) { in.seekg(offset, ios::beg); in.read((char*)buffer, bytesPerSubframe); if(in.fail()) { return false; } } else { return false; } } else { // this is if it was not within the rows and cols of // the subframe or if the image description header didn't exist return false; } return true; } void ossimRpfFrame::clearFields() { theFilename = ""; } void ossimRpfFrame::deleteAll() { if(theHeader) { delete theHeader; theHeader = 0; } if(theAttributes) { delete theAttributes; theAttributes = 0; } if(theCoverage) { delete theCoverage; theCoverage = 0; } if(theImageDescriptionSubheader) { delete theImageDescriptionSubheader; theImageDescriptionSubheader = 0; } if(theMaskSubheader) { delete theMaskSubheader; theMaskSubheader = 0; } if(theImageDisplayParameterSubheader) { delete theImageDisplayParameterSubheader; theImageDisplayParameterSubheader = 0; } if(theCompressionSection) { delete theCompressionSection; theCompressionSection = 0; } if(theColorGrayscaleSubheader) { delete theColorGrayscaleSubheader; theColorGrayscaleSubheader = 0; } if(theColorConverterSubsection) { delete theColorConverterSubsection; theColorConverterSubsection = 0; } if (theNitfFile.valid()) { theNitfFile = 0; } } ossimErrorCode ossimRpfFrame::populateCoverageSection(istream& in) { if(theCoverage) delete theCoverage; theCoverage = 0; if(theHeader) { theCoverage = theHeader->getNewCoverageSection(in); } return ossimErrorCodes::OSSIM_OK; } ossimErrorCode ossimRpfFrame::populateCompressionSection(istream& in) { if(theCompressionSection) delete theCompressionSection; theCompressionSection = 0; if(theHeader) { theCompressionSection = theHeader->getNewCompressionSection(in); } return ossimErrorCodes::OSSIM_OK; } ossimErrorCode ossimRpfFrame::populateColorGrayscaleSection(istream& in) { ossimErrorCode resultError = ossimErrorCodes::OSSIM_OK; if(theColorGrayscaleSubheader) delete theColorGrayscaleSubheader; theColorGrayscaleSubheader = 0; if(theHeader) { theColorGrayscaleSubheader = theHeader->getNewColorGrayscaleSubheader(in); if(theColorGrayscaleSubheader) { const ossimRpfLocationSection* location = theHeader->getLocationSection(); if(location) { ossimRpfComponentLocationRecord component; if(location->getComponent(OSSIM_RPF_COLOR_CONVERTER_SUBSECTION, component)) { in.seekg(component.m_componentLocation,ios::beg); if(theColorConverterSubsection) delete theColorConverterSubsection; theColorConverterSubsection = new ossimRpfColorConverterSubsection; theColorConverterSubsection->setNumberOfColorConverterOffsetRecords( theColorGrayscaleSubheader->getNumberOfColorConverterOffsetRecords()); resultError = theColorConverterSubsection->parseStream(in, theHeader->getByteOrder()); } if(location->getComponent(OSSIM_RPF_COLORMAP_SUBSECTION, component)) { in.seekg(component.m_componentLocation, ios::beg); theColorGrayscaleTable.clear(); theColorGrayscaleTable.resize(theColorGrayscaleSubheader->getNumberOfColorGreyscaleOffsetRecords()); // we will ignore the offset table offset which is a 4 byte value // and ignore the offset record length which is a 2 byte value. // This is suppose to put us at the beginning of the // [color/grayscale offset record]. The total number of // these offset records is found in the [color/grayscale section // subheader. in.ignore(6); for(ossim_uint32 index = 0; index < theColorGrayscaleSubheader->getNumberOfColorGreyscaleOffsetRecords(); ++index) { ossimRpfColorGrayscaleOffsetRecord grayscaleOffsetRecord; if(grayscaleOffsetRecord.parseStream(in, theHeader->getByteOrder()) == ossimErrorCodes::OSSIM_OK) { ossim_uint32 rememberLocation = in.tellg(); in.seekg(grayscaleOffsetRecord.getColorGrayscaleTableOffset()+component.m_componentLocation, ios::beg); theColorGrayscaleTable[index].setTableData(grayscaleOffsetRecord.getColorGrayscaleTableId(), grayscaleOffsetRecord.getNumberOfColorGrayscaleRecords()); theColorGrayscaleTable[index].parseStream(in, theHeader->getByteOrder()); in.seekg(rememberLocation, ios::beg); } else { return ossimErrorCodes::OSSIM_ERROR; } } } } } } return resultError; } ossimErrorCode ossimRpfFrame::populateImageSection(istream& in) { ossimErrorCode result = ossimErrorCodes::OSSIM_OK; if(theImageDescriptionSubheader) delete theImageDescriptionSubheader; theImageDescriptionSubheader = 0; if(theHeader&&in) { // get the subheader information. theImageDescriptionSubheader = theHeader->getNewImageDescriptionSubheader(in); // need to do something with the table before going to the display. if(theImageDescriptionSubheader &&(!theImageDescriptionSubheader->isSubframeMaskTableOffsetNull())) { if(theMaskSubheader) delete theMaskSubheader; // need to get the mask subheader theMaskSubheader = new ossimRpfMaskSubheader; // seek to the start of the subheader in.seekg(theImageDescriptionSubheader->getEndOffset() + theImageDescriptionSubheader->getSubframeMaskTableOffset(), ios::beg); // get the information result = theMaskSubheader->parseStream(in, theHeader->getByteOrder()); } if(theImageDisplayParameterSubheader) delete theImageDisplayParameterSubheader; // Get the display parameter header theImageDisplayParameterSubheader = theHeader->getNewImageDisplayParameterSubheader(in); } return result; } ossimErrorCode ossimRpfFrame::populateAttributeSection(istream& in) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::populateAttributeSection: entered ..." << std::endl; } ossimRpfAttributeSectionSubheader* temp = 0; const ossimRpfLocationSection* location = theHeader->getLocationSection(); if(location) { ossimRpfComponentLocationRecord component; if(location->getComponent(OSSIM_RPF_ATTRIBUTE_SECTION_SUBHEADER, component)) { temp = new ossimRpfAttributeSectionSubheader; in.seekg(component.m_componentLocation, std::ios::beg); if(temp->parseStream(in, theHeader->getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete temp; temp =0; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::populateAttributeSection: leaving 1 ..." << std::endl; } return ossimErrorCodes::OSSIM_ERROR; } } } if(!in.fail()&&temp) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Has attribute section" << std::endl; } if(theAttributes) delete theAttributes; theAttributes = new ossimRpfAttributes; ossimRpfAttributeOffsetRecord record; ossim_uint64 locationAttributeSubsection = in.tellg(); ossim_uint64 absoluteAddresToTable = locationAttributeSubsection + temp->getAttributeOffsetTableOffset(); ossimEndian anEndian; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Number of attributes = " << temp->getNumberOfAttributeOffsetRecords() << std::endl; } in.seekg(absoluteAddresToTable, ios::beg); for(ossim_uint32 index = 0; index < temp->getNumberOfAttributeOffsetRecords(); index++) { if((!in.fail())&& record.parseStream(in, theHeader->getByteOrder()) == ossimErrorCodes::OSSIM_OK) { // make sure we save the current position. The attribute // parser in the switch/case will change the location and // we must come back to the start of the next record. ossim_uint64 currentLocation = in.tellg(); // go to the location of the start of the attribute. in.seekg(locationAttributeSubsection + record.getAttributeRecordOffset(), ios::beg); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Parsing attribute number " << index << " with id = " << record.getAttributeId() << std::endl; } // allocate some temporary space for the string type // attributes. char tempString[50]; if(!theAttributes->getAttributeFlag(record.getAttributeId())) { theAttributes->setAttributeFlag(record.getAttributeId(), true); switch(record.getAttributeId()) { case 1: { in.read((char*)tempString, 8); tempString[8] = '\0'; theAttributes->theCurrencyDate = tempString; break; } case 2: { in.read((char*)tempString, 8); tempString[8] = '\0'; theAttributes->theProductionDate = tempString; break; } case 3: { in.read((char*)tempString, 8); tempString[8] = '\0'; theAttributes->theSignificantDate = tempString; break; } case 4: { in.read((char*)tempString, 10); theAttributes->theChartSeriesCode = ossimString(tempString, &tempString[10]); in.read((char*)tempString, 8); theAttributes->theMapDesignationCode = ossimString(tempString, &tempString[8]); in.read((char*)tempString, 4); theAttributes->theOldHorDatum = ossimString(tempString, &tempString[4]); in.read((char*)tempString, 7); theAttributes->theEdition = ossimString(tempString, &tempString[7]); break; } case 5: { in.read((char*)tempString, 2); theAttributes->theProjectionCode = ossimString(tempString, &tempString[2]); theAttributes->theProjectionCode = theAttributes->theProjectionCode.upcase(); if((theAttributes->theProjectionCode == "AC") || (theAttributes->theProjectionCode == "LE") || (theAttributes->theProjectionCode == "PG")) { in.read((char*)&(theAttributes->theProjectionA), 4); in.read((char*)&(theAttributes->theProjectionB), 4); in.read((char*)&(theAttributes->theProjectionC), 4); in.read((char*)&(theAttributes->theProjectionD), 4); } else if((theAttributes->theProjectionCode == "RB") || (theAttributes->theProjectionCode == "OC") || (theAttributes->theProjectionCode == "TC")) { in.read((char*)&(theAttributes->theProjectionA), 4); in.read((char*)&(theAttributes->theProjectionB), 4); in.read((char*)&(theAttributes->theProjectionC), 4); } else if((theAttributes->theProjectionCode == "AL") || (theAttributes->theProjectionCode == "MC") || (theAttributes->theProjectionCode == "OD") || (theAttributes->theProjectionCode == "PH")) { in.read((char*)&(theAttributes->theProjectionA), 4); in.read((char*)&(theAttributes->theProjectionB), 4); } else if((theAttributes->theProjectionCode == "UT")) { in.read((char*)&(theAttributes->theProjectionA), 4); } if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theProjectionA); anEndian.swap(theAttributes->theProjectionB); anEndian.swap(theAttributes->theProjectionC); anEndian.swap(theAttributes->theProjectionD); } break; } case 6: { in.read((char*)tempString, 4); theAttributes->theVertDatumCode = ossimString(tempString, &tempString[4]); break; } case 7: { in.read((char*)tempString, 4); theAttributes->theHorDatumCode = ossimString(tempString, &tempString[4]); break; } case 8: { in.read((char*)&(theAttributes->theVertAbsAccuracy), 4); in.read((char*)&(theAttributes->theVertAbsUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theVertAbsAccuracy); anEndian.swap(theAttributes->theVertAbsUnits); } break; } case 9: { in.read((char*)&(theAttributes->theHorAbsAccuracy), 4); in.read((char*)&(theAttributes->theHorAbsUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theHorAbsAccuracy); anEndian.swap(theAttributes->theHorAbsUnits); } break; } case 10: { in.read((char*)&(theAttributes->theVertRelAccuracy), 4); in.read((char*)&(theAttributes->theVertRelUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theVertRelAccuracy); anEndian.swap(theAttributes->theVertRelUnits); } break; } case 11: { in.read((char*)&(theAttributes->theHorRelAccuracy), 4); in.read((char*)&(theAttributes->theHorRelUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theHorRelAccuracy); anEndian.swap(theAttributes->theHorRelUnits); } break; } case 12: { in.read((char*)tempString, 3); theAttributes->ellipsoidCode = ossimString(tempString, &tempString[3]); break; } case 13: { in.read((char*)tempString, 4); theAttributes->theSoundingDatumCode = ossimString(tempString, &tempString[4]); break; } case 14: { in.read((char*)&(theAttributes->theNavSystemCode), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theNavSystemCode); } break; } case 15: { in.read((char*)tempString, 2); theAttributes->theGridCode = ossimString(tempString, &tempString[2]); break; } case 16: { in.read((char*)&(theAttributes->theEeasterlyMagChange), 4); in.read((char*)&(theAttributes->theEasterlyMagChangeUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theEeasterlyMagChange); anEndian.swap(theAttributes->theEasterlyMagChangeUnits); } break; } case 17: { in.read((char*)&(theAttributes->theWesterlyMagChange), 4); in.read((char*)&(theAttributes->theWesterlyMagChangeUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theWesterlyMagChange); anEndian.swap(theAttributes->theWesterlyMagChangeUnits); } break; } case 18: { in.read((char*)&(theAttributes->theMagAngle), 4); in.read((char*)&(theAttributes->theMagAngleUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theMagAngle); anEndian.swap(theAttributes->theMagAngleUnits); } break; } case 19: { in.read((char*)&(theAttributes->theGridConver), 4); in.read((char*)&(theAttributes->theGridConverUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theGridConver); anEndian.swap(theAttributes->theGridConverUnits); } break; } case 20: { in.read((char*)&(theAttributes->theHighElevation), 8); in.read((char*)&(theAttributes->theHighElevationUnits), 2); in.read((char*)&(theAttributes->theHighLat), 8); in.read((char*)&(theAttributes->theHighLon), 8); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theHighElevation); anEndian.swap(theAttributes->theHighElevationUnits); anEndian.swap(theAttributes->theHighLat); anEndian.swap(theAttributes->theHighLon); } break; } case 21: { in.read((char*)tempString, 12); theAttributes->theLegendFileName = ossimString(tempString, &tempString[12]); break; } case 22: { in.read((char*)tempString, 12); tempString[12] = '\0'; theAttributes->theDataSource = tempString; in.read((char*)&(theAttributes->theGsd), 4); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theGsd); } break; } case 23: { in.read((char*)&(theAttributes->theDataLevel), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theDataLevel); } break; } } } in.seekg(currentLocation, ios::beg); } else { delete temp; temp = 0; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::populateAttributeSection: leaving 2 ..." << std::endl; } return ossimErrorCodes::OSSIM_ERROR; } } } if(temp) delete temp; temp = 0; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::populateAttributeSection: leaving OK ..." << std::endl; } return ossimErrorCodes::OSSIM_OK; } ossimErrorCode ossimRpfFrame::populateMasks(istream& in) { theSubframeMaskTable.clear(); theSubframeTransparencyMaskTable.clear(); if(!in) { return ossimErrorCodes::OSSIM_ERROR; } if(theImageDescriptionSubheader) { const ossimRpfLocationSection* location = theHeader->getLocationSection(); if(location) { ossimRpfComponentLocationRecord component; if(location->getComponent(OSSIM_RPF_MASK_SUBSECTION, component)) { // now allocate the space we need and then reader the table in theSubframeMaskTable.resize(theImageDescriptionSubheader->getNumberOfSpectralGroups()); theSubframeTransparencyMaskTable.resize(theImageDescriptionSubheader->getNumberOfSpectralGroups()); ossim_uint32 spectralIndex; ossim_uint32 rowIndex; ossim_uint32 colIndex; if(!theImageDescriptionSubheader->isSubframeMaskTableOffsetNull()) { // move get to the first byte of the Mask table. This is the offset from the // start of the maskSubsection. in.seekg(component.m_componentLocation + theImageDescriptionSubheader->getSubframeMaskTableOffset(), ios::beg); // first loop through the Mask table and allocate while we do it for(spectralIndex = 0; spectralIndex < theImageDescriptionSubheader->getNumberOfSpectralGroups(); ++spectralIndex) { // reserve space for the number of rows theSubframeMaskTable[spectralIndex].resize(theImageDescriptionSubheader->getNumberOfSubframesVertical()); for(rowIndex = 0; rowIndex < theImageDescriptionSubheader->getNumberOfSubframesVertical(); ++rowIndex) { // allocate the columns theSubframeMaskTable[spectralIndex][rowIndex].resize(theImageDescriptionSubheader->getNumberOfSubframesHorizontal()); for(colIndex = 0; colIndex < theImageDescriptionSubheader->getNumberOfSubframesHorizontal(); ++colIndex) { ossim_uint32 value; in.read((char*)&value, 4); ossimEndian anEndian; if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(value); } theSubframeMaskTable[spectralIndex][rowIndex][colIndex] = value; } } } } if(!theImageDescriptionSubheader->isTransparencyMaskTableOffsetNull()) { // move get to the first byte of the Mask table. This is the offset from the // start of the maskSubsection. in.seekg(component.m_componentLocation + theImageDescriptionSubheader->getTransparencyMaskTableOffset(),ios::beg); for(spectralIndex = 0; spectralIndex < theImageDescriptionSubheader->getNumberOfSpectralGroups(); ++spectralIndex) { // reserve space for the number of rows theSubframeTransparencyMaskTable[spectralIndex].resize(theImageDescriptionSubheader->getNumberOfSubframesVertical()); for(rowIndex = 0; rowIndex < theImageDescriptionSubheader->getNumberOfSubframesVertical(); ++rowIndex) { // allocate the columns theSubframeTransparencyMaskTable[spectralIndex][rowIndex].resize(theImageDescriptionSubheader->getNumberOfSubframesHorizontal()); for(colIndex = 0; colIndex < theImageDescriptionSubheader->getNumberOfSubframesHorizontal(); ++colIndex) { ossim_uint32 value; in.read((char*)&value, 4); ossimEndian anEndian; if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(value); } theSubframeTransparencyMaskTable[spectralIndex][rowIndex][colIndex] = value; } } } } } } } return ossimErrorCodes::OSSIM_OK; } ossimErrorCode ossimRpfFrame::populateReplaceUpdateTable(std::istream& in) { ossimErrorCode result = ossimErrorCodes::OSSIM_OK; const ossimRpfLocationSection* location = theHeader->getLocationSection(); if( location ) { if ( location->hasComponent(OSSIM_RPF_REPLACE_UPDATE_SECTION_SUBHEADER) ) { ossimRpfComponentLocationRecord component; if( location->getComponent(OSSIM_RPF_REPLACE_UPDATE_SECTION_SUBHEADER, component) ) { ossimRefPtr hdr = new ossimRpfReplaceUpdateSectionSubheader(); in.seekg(component.m_componentLocation, ios::beg); if( hdr->parseStream( in, theHeader->getByteOrder() ) == ossimErrorCodes::OSSIM_OK ) { ossim_uint16 count = hdr->getNumberOfRecords(); if ( count ) { if ( theReplaceUpdateTable.valid() ) { theReplaceUpdateTable->clear(); } else { theReplaceUpdateTable = new ossimRpfReplaceUpdateTable(); } ossimRpfReplaceUpdateRecord record; for ( ossim_uint16 i = 0; i < count; ++i ) { if ( record.parseStream(in) == ossimErrorCodes::OSSIM_OK ) { theReplaceUpdateTable->addRecord( record ); } else { break; } } } } } } } if ( in.fail() ) { theReplaceUpdateTable = 0; result = ossimErrorCodes::OSSIM_ERROR; } return result; } // End: ossimRpfFrame::populateReplaceUpdateTable(std::istream& in) ossimRefPtr ossimRpfFrame::getRpfReplaceUpdateTable() const { return theReplaceUpdateTable; } ossim-Miami-2.9.1/src/support_data/ossimRpfFrameEntry.cpp000066400000000000000000000067601352751253100235230ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfFrameEntry.cpp 18052 2010-09-06 14:33:08Z dburken $ #include #include std::ostream& operator<<(std::ostream& out, const ossimRpfFrameEntry& data) { return data.print(out); } ossimRpfFrameEntry::ossimRpfFrameEntry(const ossimFilename& rootDirectory, const ossimFilename& pathToFrameFileFromRoot) :m_exists(false), m_rootDirectory(rootDirectory), m_pathToFrameFileFromRoot(pathToFrameFileFromRoot), m_fullValidPath() { setEntry(rootDirectory, pathToFrameFileFromRoot); } ossimRpfFrameEntry::ossimRpfFrameEntry(const ossimRpfFrameEntry& obj) :m_exists(obj.m_exists), m_rootDirectory(obj.m_rootDirectory), m_pathToFrameFileFromRoot(obj.m_pathToFrameFileFromRoot), m_fullValidPath(obj.m_fullValidPath) {} const ossimRpfFrameEntry& ossimRpfFrameEntry::operator=(const ossimRpfFrameEntry& rhs) { if (this != &rhs) { m_exists = rhs.m_exists; m_rootDirectory = rhs.m_rootDirectory; m_pathToFrameFileFromRoot = rhs.m_pathToFrameFileFromRoot; m_fullValidPath = rhs.m_fullValidPath; } return *this; } void ossimRpfFrameEntry::setEntry(const ossimFilename& rootDirectory, const ossimFilename& pathToFrameFileFromRoot) { //--- // We must check for case combinations: //--- m_rootDirectory = rootDirectory; m_pathToFrameFileFromRoot = pathToFrameFileFromRoot; m_fullValidPath = m_rootDirectory.dirCat(m_pathToFrameFileFromRoot); // Check as supplied: if(m_fullValidPath.exists()) { m_exists = true; } else // Check root/downcased_path { m_pathToFrameFileFromRoot = m_pathToFrameFileFromRoot.downcase(); m_fullValidPath = m_rootDirectory.dirCat(m_pathToFrameFileFromRoot); if(m_fullValidPath.exists()) { m_exists = true; } else // Check root/upcased_path { m_pathToFrameFileFromRoot = m_pathToFrameFileFromRoot.upcase(); m_fullValidPath = m_rootDirectory.dirCat(m_pathToFrameFileFromRoot); if(m_fullValidPath.exists()) { m_exists = true; } else { m_pathToFrameFileFromRoot = pathToFrameFileFromRoot; m_fullValidPath = m_rootDirectory.dirCat(m_pathToFrameFileFromRoot); m_exists = false; } } } } std::ostream& ossimRpfFrameEntry::print( std::ostream& out, const std::string& prefix) const { out << prefix << "exists: " << m_exists << "\n" << prefix << "root_directory: " << m_rootDirectory << "\n" << prefix << "relative_path: " << m_pathToFrameFileFromRoot << "\n" << prefix << "full_path: " << m_fullValidPath << "\n"; return out; } bool ossimRpfFrameEntry::exists() const { return m_exists; } const ossimFilename& ossimRpfFrameEntry::getFullPath() const { return m_fullValidPath; } const ossimString& ossimRpfFrameEntry::getRootDirectory() const { return m_rootDirectory; } const ossimString ossimRpfFrameEntry::getPathToFrameFileFromRoot() const { return m_pathToFrameFileFromRoot; } ossim-Miami-2.9.1/src/support_data/ossimRpfFrameFileIndexRecord.cpp000066400000000000000000000145201352751253100254210ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfFrameFileIndexRecord.cpp 17501 2010-06-02 11:14:55Z dburken $ #include /* for memset, memcpy */ #include #include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfFrameFileIndexRecord& data) { return data.print(out); } ossimRpfFrameFileIndexRecord::ossimRpfFrameFileIndexRecord() : m_boundaryRectRecordNumber(0), m_locationRowNumber(0), m_locationColumnNumber(0), m_pathnameRecordOffset(0) { clearFields(); } ossimRpfFrameFileIndexRecord::ossimRpfFrameFileIndexRecord(const ossimRpfFrameFileIndexRecord& obj) : m_boundaryRectRecordNumber(obj.m_boundaryRectRecordNumber), m_locationRowNumber(obj.m_locationRowNumber), m_locationColumnNumber(obj.m_locationColumnNumber), m_pathnameRecordOffset(obj.m_pathnameRecordOffset), m_securityClassification(obj.m_securityClassification) { memcpy(m_filename, obj.m_filename, 13); memcpy(m_geographicLocation, obj.m_geographicLocation, 7); memcpy(m_fileSecurityCountryCode, obj.m_fileSecurityCountryCode, 3); memcpy(m_fileSecurityReleaseMarking, obj.m_fileSecurityReleaseMarking, 3); } const ossimRpfFrameFileIndexRecord& ossimRpfFrameFileIndexRecord::operator=( const ossimRpfFrameFileIndexRecord& rhs) { if ( this != &rhs ) { m_boundaryRectRecordNumber = rhs.m_boundaryRectRecordNumber; m_locationRowNumber = rhs.m_locationRowNumber; m_locationColumnNumber = rhs.m_locationColumnNumber; m_pathnameRecordOffset = rhs.m_pathnameRecordOffset; m_securityClassification = rhs.m_securityClassification; memcpy(m_filename, rhs.m_filename, 13); memcpy(m_geographicLocation, rhs.m_geographicLocation, 7); memcpy(m_fileSecurityCountryCode, rhs.m_fileSecurityCountryCode, 3); memcpy(m_fileSecurityReleaseMarking, rhs.m_fileSecurityReleaseMarking, 3); } return *this; } ossimErrorCode ossimRpfFrameFileIndexRecord::parseStream( std::istream& in, ossimByteOrder byteOrder) { if(in) { ossimEndian anEndian; clearFields(); in.read((char*)&m_boundaryRectRecordNumber, 2); in.read((char*)&m_locationRowNumber, 2); in.read((char*)&m_locationColumnNumber, 2); in.read((char*)&m_pathnameRecordOffset, 4); in.read((char*)m_filename, 12); in.read((char*)m_geographicLocation, 6); in.read((char*)&m_securityClassification, 1); in.read((char*)m_fileSecurityCountryCode, 2); in.read((char*)m_fileSecurityReleaseMarking, 2); if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(m_boundaryRectRecordNumber); anEndian.swap(m_locationRowNumber); anEndian.swap(m_locationColumnNumber); anEndian.swap(m_pathnameRecordOffset); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfFrameFileIndexRecord::writeStream(std::ostream& out) { ossimEndian anEndian; if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Always write out big endian. anEndian.swap(m_boundaryRectRecordNumber); anEndian.swap(m_locationRowNumber); anEndian.swap(m_locationColumnNumber); anEndian.swap(m_pathnameRecordOffset); } out.write((char*)&m_boundaryRectRecordNumber, 2); out.write((char*)&m_locationRowNumber, 2); out.write((char*)&m_locationColumnNumber, 2); out.write((char*)&m_pathnameRecordOffset, 4); out.write((char*)m_filename, 12); out.write((char*)m_geographicLocation, 6); out.write((char*)&m_securityClassification, 1); out.write((char*)m_fileSecurityCountryCode, 2); out.write((char*)m_fileSecurityReleaseMarking, 2); if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Swap back to native. anEndian.swap(m_boundaryRectRecordNumber); anEndian.swap(m_locationRowNumber); anEndian.swap(m_locationColumnNumber); anEndian.swap(m_pathnameRecordOffset); } } std::ostream& ossimRpfFrameFileIndexRecord::print(std::ostream& out)const { out << "BoundaryRectRecordNumber: " << m_boundaryRectRecordNumber << "\nLocationRowNumber: " << m_locationRowNumber << "\nLocationColumnNumber: " << m_locationColumnNumber << "\nPathnameRecordOffset: " << m_pathnameRecordOffset << "\nFilename: " << m_filename << "\nGeographicLocation: " << m_geographicLocation << "\nSecurityClassification: " << m_securityClassification << "\nFileSecurityCountryCode: " << m_fileSecurityCountryCode << "\nFileSecurityReleaseMarking: " << m_fileSecurityReleaseMarking << std::endl; return out; } ossim_uint16 ossimRpfFrameFileIndexRecord::getBoundaryRecNumber()const { return m_boundaryRectRecordNumber; } ossim_uint16 ossimRpfFrameFileIndexRecord::getLocationRowNumber()const { return m_locationRowNumber; } ossim_uint16 ossimRpfFrameFileIndexRecord::getLocationColNumber()const { return m_locationColumnNumber; } ossim_uint32 ossimRpfFrameFileIndexRecord::getPathnameRecordOffset()const { return m_pathnameRecordOffset; } ossimFilename ossimRpfFrameFileIndexRecord::getFilename()const { return ossimFilename(m_filename); } void ossimRpfFrameFileIndexRecord::setBoundaryRecNumber(ossim_uint16 entry) { m_boundaryRectRecordNumber = entry; } void ossimRpfFrameFileIndexRecord::setPathnameRecordOffset(ossim_uint32 offset) { m_pathnameRecordOffset = offset; } void ossimRpfFrameFileIndexRecord::clearFields() { m_boundaryRectRecordNumber = 0; m_locationRowNumber = 0; m_locationColumnNumber= 0; m_pathnameRecordOffset = 0; memset(m_filename, ' ', 12); memset(m_geographicLocation, ' ', 6); m_securityClassification = ' '; memset(m_fileSecurityCountryCode, ' ', 2); memset(m_fileSecurityReleaseMarking, ' ', 2); m_filename[12] = '\0'; m_geographicLocation[6] = '\0'; m_fileSecurityCountryCode[2] = '\0'; m_fileSecurityReleaseMarking[2] = '\0'; } ossim-Miami-2.9.1/src/support_data/ossimRpfFrameFileIndexSectionSubheader.cpp000066400000000000000000000130151352751253100274300ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfFrameFileIndexSectionSubheader.cpp 16997 2010-04-12 18:53:48Z dburken $ #include #include #include #include /* ossim::byteOrder() */ #include #include // Static trace for debugging static ossimTrace traceDebug("ossimRpfFrameFileIndexSectionSubheader:debug"); std::ostream& operator <<(std::ostream& out, const ossimRpfFrameFileIndexSectionSubheader& data) { return data.print(out); } ossimRpfFrameFileIndexSectionSubheader::ossimRpfFrameFileIndexSectionSubheader() : m_highestSecurityClassification(' '), m_indexTableOffset(0), m_numberOfIndexRecords(0), m_numberOfPathnameRecords(0), m_indexRecordLength(0) { } ossimRpfFrameFileIndexSectionSubheader::ossimRpfFrameFileIndexSectionSubheader( const ossimRpfFrameFileIndexSectionSubheader& obj) : m_highestSecurityClassification(obj.m_highestSecurityClassification), m_indexTableOffset(obj.m_indexTableOffset), m_numberOfIndexRecords(obj.m_numberOfIndexRecords), m_numberOfPathnameRecords(obj.m_numberOfPathnameRecords), m_indexRecordLength(obj.m_indexRecordLength) { } const ossimRpfFrameFileIndexSectionSubheader& ossimRpfFrameFileIndexSectionSubheader::operator=( const ossimRpfFrameFileIndexSectionSubheader& rhs) { if ( this != &rhs ) { m_highestSecurityClassification = rhs.m_highestSecurityClassification; m_indexTableOffset = rhs.m_indexTableOffset; m_numberOfIndexRecords = rhs.m_numberOfIndexRecords; m_numberOfPathnameRecords = rhs.m_numberOfPathnameRecords; m_indexRecordLength = rhs.m_indexRecordLength; } return *this; } ossimRpfFrameFileIndexSectionSubheader::~ossimRpfFrameFileIndexSectionSubheader() { } ossimErrorCode ossimRpfFrameFileIndexSectionSubheader::parseStream(std::istream& in, ossimByteOrder byteOrder) { if(in) { in.read((char*)&m_highestSecurityClassification, 1); in.read((char*)&m_indexTableOffset, 4); in.read((char*)&m_numberOfIndexRecords, 4); in.read((char*)&m_numberOfPathnameRecords, 2); in.read((char*)&m_indexRecordLength, 2); if( ossim::byteOrder() != byteOrder ) { ossimEndian anEndian; anEndian.swap(m_indexTableOffset); anEndian.swap(m_numberOfIndexRecords); anEndian.swap(m_numberOfPathnameRecords); anEndian.swap(m_indexRecordLength); } } else { return ossimErrorCodes::OSSIM_ERROR; } if ( traceDebug() ) { print( ossimNotify(ossimNotifyLevel_NOTICE) ); } return ossimErrorCodes::OSSIM_OK; } void ossimRpfFrameFileIndexSectionSubheader::writeStream(std::ostream& out) { if( ossim::byteOrder() != OSSIM_BIG_ENDIAN) { // Swap to big endian. ossimEndian anEndian; anEndian.swap(m_indexTableOffset); anEndian.swap(m_numberOfIndexRecords); anEndian.swap(m_numberOfPathnameRecords); anEndian.swap(m_indexRecordLength); } out.write((char*)&m_highestSecurityClassification, 1); out.write((char*)&m_indexTableOffset, 4); out.write((char*)&m_numberOfIndexRecords, 4); out.write((char*)&m_numberOfPathnameRecords, 2); out.write((char*)&m_indexRecordLength, 2); if( ossim::byteOrder() != OSSIM_BIG_ENDIAN) { // Swap back to native byte order. ossimEndian anEndian; anEndian.swap(m_indexTableOffset); anEndian.swap(m_numberOfIndexRecords); anEndian.swap(m_numberOfPathnameRecords); anEndian.swap(m_indexRecordLength); } } std::ostream& ossimRpfFrameFileIndexSectionSubheader::print(std::ostream& out) const { out << "ossimRpfFrameFileIndexSectionSubheader DEBUG:" << "\nHighestSecurityClassification: " << m_highestSecurityClassification << "\nIndexTableOffset: " << m_indexTableOffset << "\nNumberOfIndexRecords: " << m_numberOfIndexRecords << "\nNumberOfPathnameRecords: " << m_numberOfPathnameRecords << "\nIndexRecordLength: " << m_indexRecordLength << std::endl; return out; } ossim_uint32 ossimRpfFrameFileIndexSectionSubheader::getOffset() const { return m_indexTableOffset; } ossim_uint32 ossimRpfFrameFileIndexSectionSubheader::getNumberOfIndexRecords() const { return m_numberOfIndexRecords; } ossim_uint16 ossimRpfFrameFileIndexSectionSubheader::getNumberOfPathnameRecords() const { return m_numberOfPathnameRecords; } ossim_uint16 ossimRpfFrameFileIndexSectionSubheader::getIndexRecordLength() const { return m_indexRecordLength; } void ossimRpfFrameFileIndexSectionSubheader::setNumberOfIndexRecords(ossim_uint32 count) { m_numberOfIndexRecords = count; } void ossimRpfFrameFileIndexSectionSubheader::setNumberOfPathnameRecords(ossim_uint16 count) { m_numberOfPathnameRecords = count; } void ossimRpfFrameFileIndexSectionSubheader::setIndexRecordLength(ossim_uint16 length) { m_indexRecordLength = length; } void ossimRpfFrameFileIndexSectionSubheader::clearFields() { m_highestSecurityClassification = ' '; m_indexTableOffset = 0; m_numberOfIndexRecords = 0; m_numberOfPathnameRecords = 0; m_indexRecordLength = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfFrameFileIndexSubsection.cpp000066400000000000000000000101161352751253100263160ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class. // //******************************************************************** // $Id: ossimRpfFrameFileIndexSubsection.cpp 16997 2010-04-12 18:53:48Z dburken $ #include /* for memset */ #include #include #include #include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfFrameFileIndexSubsection& data) { return data.print(out); } ossimRpfFrameFileIndexSubsection::ossimRpfFrameFileIndexSubsection() : m_indexTable(0), m_pathnameTable(0) { } ossimRpfFrameFileIndexSubsection::ossimRpfFrameFileIndexSubsection( const ossimRpfFrameFileIndexSubsection& obj) : m_indexTable(obj.m_indexTable), m_pathnameTable(obj.m_pathnameTable) { } const ossimRpfFrameFileIndexSubsection& ossimRpfFrameFileIndexSubsection::operator=( const ossimRpfFrameFileIndexSubsection& rhs) { if ( this != &rhs ) { m_indexTable = rhs.m_indexTable; m_pathnameTable = rhs.m_pathnameTable; } return *this; } ossimRpfFrameFileIndexSubsection::~ossimRpfFrameFileIndexSubsection() { } ossimErrorCode ossimRpfFrameFileIndexSubsection::parseStream(std::istream &in, ossimByteOrder byteOrder) { ossimErrorCode result = ossimErrorCodes::OSSIM_OK; if(in && (m_indexTable.size()>0)) { ossim_uint32 index; for(index = 0; (index < m_indexTable.size()) && (result == ossimErrorCodes::OSSIM_OK); ++index) { result = m_indexTable[index].parseStream(in, byteOrder); } for(index = 0; (index < m_pathnameTable.size()) && (result ==ossimErrorCodes::OSSIM_OK); ++index) { result = m_pathnameTable[index].parseStream(in, byteOrder); } } else { result = ossimErrorCodes::OSSIM_ERROR; } return result; } void ossimRpfFrameFileIndexSubsection::writeStream(std::ostream& out) { std::vector::iterator indexIter = m_indexTable.begin(); while ( indexIter != m_indexTable.end() ) { (*indexIter).writeStream(out); ++indexIter; } std::vector::iterator pathIter = m_pathnameTable.begin(); while ( pathIter != m_pathnameTable.end() ) { (*pathIter).writeStream(out); ++pathIter; } } void ossimRpfFrameFileIndexSubsection::clearFields() { m_indexTable.clear(); m_pathnameTable.clear(); } std::ostream& ossimRpfFrameFileIndexSubsection::print(std::ostream& out)const { copy(m_indexTable.begin(), m_indexTable.end(), std::ostream_iterator(out, "\n")); copy(m_pathnameTable.begin(), m_pathnameTable.end(), std::ostream_iterator(out, "\n")); return out; } void ossimRpfFrameFileIndexSubsection::setNumberOfFileIndexRecords( ossim_uint32 numberOfIndexRecords) { m_indexTable.resize(numberOfIndexRecords); } void ossimRpfFrameFileIndexSubsection::setNumberOfPathnames(ossim_uint32 numberOfPathnames) { m_pathnameTable.resize(numberOfPathnames); } const std::vector& ossimRpfFrameFileIndexSubsection::getIndexTable()const { return m_indexTable; } const std::vector& ossimRpfFrameFileIndexSubsection::getPathnameTable() const { return m_pathnameTable; } bool ossimRpfFrameFileIndexSubsection::getFrameFileIndexRecordFromFile( const ossimFilename& file, ossimRpfFrameFileIndexRecord& record) const { bool result = false; std::vector::const_iterator i = m_indexTable.begin(); while ( i != m_indexTable.end() ) { if ( (*i).getFilename() == file ) { record = (*i); result = true; break; } ++i; } return result; } ossim-Miami-2.9.1/src/support_data/ossimRpfFrameFileReader.cpp000066400000000000000000000053201352751253100244130ustar00rootroot00000000000000//******************************************************************* // // LICENSE: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfFrameFileReader.cpp 19682 2011-05-31 14:21:20Z dburken $ #include #include #include #include #include #include #include using namespace std; std::ostream& operator<<(std::ostream& out, const ossimRpfFrameFileReader& data) { return data.print(out); } ossimRpfFrameFileReader::ossimRpfFrameFileReader() :theRpfHeader(0), theFilename("") { } ossimRpfFrameFileReader::~ossimRpfFrameFileReader() { theRpfHeader = 0; } ossimErrorCode ossimRpfFrameFileReader::parseFile(const ossimFilename& fileName) { std::ifstream in(fileName.c_str(), ios::in | ios::binary); ossimRefPtr nitfFile = new ossimNitfFile; if(!in) { return ossimErrorCodes::OSSIM_ERROR; } clearAll(); nitfFile->parseFile(fileName); const ossimRefPtr nitfFileHeader = nitfFile->getHeader(); if(!nitfFileHeader) { nitfFile = 0; return ossimErrorCodes::OSSIM_ERROR; } ossimNitfTagInformation info; nitfFileHeader->getTag(info, "RPFHDR"); // we no longer need access to the nitf header. We got what we needed nitfFile = 0; theFilename = fileName; if(info.getTagName() == "RPFHDR") { theRpfHeader = new ossimRpfHeader; // set the get pointer for the stream to the start // of the Rpf header data in.seekg(info.getTagDataOffset()); // now get the header data. We do not need to pass in the byte order. // this is grabbed from the first byte of the stream. To see this, // Look at the RpfHeader implementation. theRpfHeader->parseStream(in); // ==ossimErrorCodes::OSSIM_OK) if ( in.fail() ) { theRpfHeader = 0; } } else { return ossimErrorCodes::OSSIM_ERROR; } if( !theRpfHeader.valid() ) { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } std::ostream& ossimRpfFrameFileReader::print(std::ostream& out)const { if( theRpfHeader.valid() ) { theRpfHeader->print(out, std::string("")); } return out; } const ossimRpfHeader* ossimRpfFrameFileReader::getRpfHeader()const { return theRpfHeader.get(); } void ossimRpfFrameFileReader::clearAll() { theRpfHeader = 0; theFilename = ""; } ossim-Miami-2.9.1/src/support_data/ossimRpfHeader.cpp000066400000000000000000000566141352751253100226420ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This class extends the stl's string class. // //******************************************************************** // $Id: ossimRpfHeader.cpp 22702 2014-04-02 13:50:02Z gpotts $ #include #include #include #include #include /* ossim::byteOrder() */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; // Static trace for debugging static ossimTrace traceDebug("ossimRpfHeader:debug"); // Keywords: static const ossimString HEADER_SECTION_LENGTH_KW = "HeaderSectionLength"; static const ossimString NEW_REP_UP_INDICATOR_KW = "NewRepUpIndicator"; static const ossimString GOV_SPEC_NUMBER_KW = "GovSpecNumber"; static const ossimString GOV_SPEC_DATE_KW = "GovSpecDate"; static const ossimString SECURITY_CLASSIFICATION_KW = "SecurityClassification"; static const ossimString COUNTRY_CODE_KW = "CountryCode"; static const ossimString SECURITY_RELEASE_MARKING_KW = "SecurityReleaseMarking"; ossimRpfHeader::ossimRpfHeader() : ossimNitfRegisteredTag(std::string("RPFHDR"), 48), m_littleBigEndianIndicator(0x00), m_headerSectionLength(48), m_fileName(), m_newRepUpIndicator(0), m_govSpecNumber(), m_govSpecDate(), m_securityClassification(), m_countryCode(), m_securityReleaseMarking(), m_locSectionLoc(0), m_locationSection(new ossimRpfLocationSection) { memset(m_fileName, ' ' , 12); memset(m_govSpecNumber, ' ', 15); memset(m_govSpecDate, ' ', 8); memset(m_securityClassification, ' ', 1); memset(m_countryCode, ' ', 2); memset(m_securityReleaseMarking, ' ', 2); m_fileName[12] = '\0'; m_govSpecNumber[15] = '\0'; m_govSpecDate[8] = '\0'; m_securityClassification[1] = '\0'; m_countryCode[2] = '\0'; m_securityReleaseMarking[2] = '\0'; } ossimRpfHeader::ossimRpfHeader(const ossimRpfHeader& obj) : ossimNitfRegisteredTag(std::string("RPFHDR"), 48), m_littleBigEndianIndicator(obj.m_littleBigEndianIndicator), m_headerSectionLength(obj.m_headerSectionLength), m_fileName(), m_newRepUpIndicator(obj.m_newRepUpIndicator), m_govSpecNumber(), m_govSpecDate(), m_securityClassification(), m_countryCode(), m_securityReleaseMarking(), m_locSectionLoc(obj.m_locSectionLoc), m_locationSection( new ossimRpfLocationSection( *(obj.m_locationSection) ) ) { memcpy(m_fileName, obj.m_fileName, 13); memcpy(m_govSpecNumber, obj.m_govSpecNumber, 16); memcpy(m_govSpecDate, obj.m_govSpecDate, 9); memcpy(m_securityClassification, obj.m_securityClassification, 2); memcpy(m_countryCode, obj.m_countryCode, 3); memcpy(m_securityReleaseMarking, obj.m_securityReleaseMarking, 3); } const ossimRpfHeader& ossimRpfHeader::operator=(const ossimRpfHeader& rhs) { if ( this != &rhs ) { m_littleBigEndianIndicator = rhs.m_littleBigEndianIndicator; m_headerSectionLength = rhs.m_headerSectionLength; memcpy(m_fileName, rhs.m_fileName, 13); m_newRepUpIndicator = rhs.m_newRepUpIndicator; memcpy(m_govSpecNumber, rhs.m_govSpecNumber, 16); memcpy(m_govSpecDate, rhs.m_govSpecDate, 9); memcpy(m_securityClassification, rhs.m_securityClassification, 2); memcpy(m_countryCode, rhs.m_countryCode, 3); memcpy(m_securityReleaseMarking, rhs.m_securityReleaseMarking, 3); m_locSectionLoc = rhs.m_locSectionLoc; m_locationSection = new ossimRpfLocationSection( *(rhs.m_locationSection) ); } return *this; } ossimRpfHeader::~ossimRpfHeader() { if(m_locationSection) { delete m_locationSection; m_locationSection = 0; } } void ossimRpfHeader::parseStream(std::istream& in) { if(in) { in.read((char*)&m_littleBigEndianIndicator, 1); in.read((char*)&m_headerSectionLength, 2); in.read((char*)m_fileName, 12); in.read((char*)&m_newRepUpIndicator, 1); in.read((char*)m_govSpecNumber, 15); in.read((char*)m_govSpecDate, 8); in.read((char*)m_securityClassification, 1); in.read((char*)m_countryCode, 2); in.read((char*)m_securityReleaseMarking, 2); in.read((char*)&m_locSectionLoc, 4); m_fileName[12] = '\0'; m_govSpecNumber[15] = '\0'; m_govSpecDate[8] = '\0'; m_securityClassification[1] = '\0'; m_countryCode[2] = '\0'; m_securityReleaseMarking[2] = '\0'; //--- // From spec: MIL-PRF-89038CARDG m_littleBigEndianIndicator shall // be 0x00 for all data denoting big endian storage. We will test // anyway just in case... //--- ossimByteOrder dataByteOrder = getByteOrder(); if( ossim::byteOrder() != dataByteOrder ) { ossimEndian anEndian; anEndian.swap(m_headerSectionLength); anEndian.swap(m_locSectionLoc); } std::streamoff saveGet = in.tellg(); in.seekg(m_locSectionLoc, ios::beg); m_locationSection->parseStream(in, dataByteOrder); in.seekg(saveGet, ios::beg); } } void ossimRpfHeader::writeStream(std::ostream& out) { // Always write in big endian. if (m_littleBigEndianIndicator != 0x00) { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimRpfHeader::writeStream writing in big endian even though" << " the m_littleBigEndianIndicator is set to little endian." << std::endl; m_littleBigEndianIndicator = 0x00; } ossimByteOrder dataByteOrder = getByteOrder(); if( ossim::byteOrder() != dataByteOrder ) { ossimEndian anEndian; anEndian.swap(m_headerSectionLength); anEndian.swap(m_locSectionLoc); } out.write((char*)&m_littleBigEndianIndicator, 1); out.write((char*)&m_headerSectionLength, 2); out.write((char*)m_fileName, 12); out.write((char*)&m_newRepUpIndicator, 1); out.write((char*)m_govSpecNumber, 15); out.write((char*)m_govSpecDate, 8); out.write((char*)m_securityClassification, 1); out.write((char*)m_countryCode, 2); out.write((char*)m_securityReleaseMarking, 2); out.write((char*)&m_locSectionLoc, 4); if( ossim::byteOrder() != dataByteOrder ) { // Must swap things back or we will seek to a bad location. ossimEndian anEndian; anEndian.swap(m_headerSectionLength); anEndian.swap(m_locSectionLoc); } if (m_locSectionLoc) // May or may not be set. { std::streampos pos = out.tellp(); out.seekp(m_locSectionLoc, ios::beg); m_locationSection->writeStream(out); out.seekp(pos); } } std::ostream& ossimRpfHeader::print(std::ostream& out, const std::string& prefix) const { out << prefix << "byte_order: " << (m_littleBigEndianIndicator==0x00?"big_endian\n":"little_endian\n") << prefix << HEADER_SECTION_LENGTH_KW << ": " << m_headerSectionLength << "\n" << prefix << ossimKeywordNames::FILENAME_KW << ": " << m_fileName << "\n" << prefix << NEW_REP_UP_INDICATOR_KW << ": " << int(m_newRepUpIndicator) << "\n" << prefix << GOV_SPEC_NUMBER_KW << ": " << m_govSpecNumber << "\n" << prefix << GOV_SPEC_DATE_KW << ": " << m_govSpecDate << "\n" << prefix << SECURITY_CLASSIFICATION_KW << ": " << m_securityClassification << "\n" << prefix << COUNTRY_CODE_KW << ": " << m_countryCode << "\n" << prefix << SECURITY_RELEASE_MARKING_KW << ": " << m_securityReleaseMarking << "\n"; if ( traceDebug() ) { out << prefix << "LocSectionLoc: " << m_locSectionLoc << "\n"; if (m_locationSection) { m_locationSection->print(out, prefix); } } return out; } ossimByteOrder ossimRpfHeader::getByteOrder()const { return ( (m_littleBigEndianIndicator==0x00) ? OSSIM_BIG_ENDIAN : OSSIM_LITTLE_ENDIAN); } const ossimRpfLocationSection* ossimRpfHeader::getLocationSection() const { return m_locationSection; } ossimRpfLocationSection* ossimRpfHeader::getLocationSection() { return m_locationSection; } bool ossimRpfHeader::hasComponent(ossimRpfComponentId componentId)const { if(m_locationSection) { return m_locationSection->hasComponent(componentId); } return false; } ossimString ossimRpfHeader::getSecurityClassification()const { return m_securityClassification; } ossimRpfCoverageSection* ossimRpfHeader::getNewCoverageSection(std::istream& in)const { ossimRpfCoverageSection* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_COVERAGE_SECTION_SUBHEADER, component)) { result = new ossimRpfCoverageSection; in.seekg(component.m_componentLocation, ios::beg); if(in) { result->parseStream(in, getByteOrder()); } else { delete result; result = 0; } } } return result; } ossimRpfMaskSubsection* ossimRpfHeader::getNewMaskSubsection(std::istream& in)const { ossimRpfMaskSubsection* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_MASK_SUBSECTION, component)) { result = new ossimRpfMaskSubsection; in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } } return result; } ossimRpfAttributeSectionSubheader* ossimRpfHeader::getNewAttributeSectionSubheader(std::istream& in)const { ossimRpfAttributeSectionSubheader* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_ATTRIBUTE_SECTION_SUBHEADER, component)) { result = new ossimRpfAttributeSectionSubheader; in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } } return result; } ossimRpfColorGrayscaleSubheader* ossimRpfHeader::getNewColorGrayscaleSubheader(std::istream& in)const { ossimRpfColorGrayscaleSubheader* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_COLOR_GRAYSCALE_SECTION_SUBHEADER, component)) { result = new ossimRpfColorGrayscaleSubheader; in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } } return result; } ossimRpfCompressionSection* ossimRpfHeader::getNewCompressionSection(std::istream& in)const { ossimRpfCompressionSection* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_COMPRESSION_SECTION_SUBHEADER, component)) { result = new ossimRpfCompressionSection; in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } } return result; } ossimRpfCompressionSectionSubheader* ossimRpfHeader::getNewCompressionSectionSubheader(std::istream& in)const { ossimRpfCompressionSectionSubheader* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_COMPRESSION_SECTION_SUBHEADER, component)) { result = new ossimRpfCompressionSectionSubheader; in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } } return result; } ossimRpfImageDisplayParameterSubheader* ossimRpfHeader::getNewImageDisplayParameterSubheader(std::istream& in)const { ossimRpfImageDisplayParameterSubheader* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_IMAGE_DISPLAY_PARAMETERS_SUBHEADER, component)) { result = new ossimRpfImageDisplayParameterSubheader; in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } } return result; } ossimRpfImageDescriptionSubheader* ossimRpfHeader::getNewImageDescriptionSubheader(std::istream& in)const { ossimRpfImageDescriptionSubheader* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_IMAGE_DESCRIPTION_SUBHEADER, component)) { result = new ossimRpfImageDescriptionSubheader; in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } } return result; } ossimRpfBoundaryRectTable* ossimRpfHeader::getNewBoundaryRectTable(std::istream &in)const { ossimRpfBoundaryRectTable* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; ossimRpfBoundaryRectSectionSubheader* tempSubheader = getNewBoundaryRectSectSubheader(in); if(tempSubheader) { if(m_locationSection->getComponent(OSSIM_RPF_BOUNDARY_RECT_TABLE, component)) { result = new ossimRpfBoundaryRectTable; result->setNumberOfEntries(tempSubheader->getNumberOfEntries()); in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } delete tempSubheader; tempSubheader = 0; } } return result; } ossimRpfBoundaryRectSectionSubheader* ossimRpfHeader::getNewBoundaryRectSectSubheader(std::istream &in)const { ossimRpfBoundaryRectSectionSubheader* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_BOUNDARY_RECT_SECTION_SUBHEADER, component)) { result = new ossimRpfBoundaryRectSectionSubheader; in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } } return result; } ossimRpfFrameFileIndexSectionSubheader* ossimRpfHeader::getNewFrameFileIndexSectionSubheader(std::istream &in)const { ossimRpfFrameFileIndexSectionSubheader* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; if(m_locationSection->getComponent(OSSIM_RPF_FRAME_FILE_INDEX_SECTION_SUBHEADER, component)) { result = new ossimRpfFrameFileIndexSectionSubheader; in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } } return result; } ossimRpfFrameFileIndexSubsection* ossimRpfHeader::getNewFileIndexSubsection(std::istream& in)const { ossimRpfFrameFileIndexSubsection* result = 0; if(in&&m_locationSection) { ossimRpfComponentLocationRecord component; ossimRpfFrameFileIndexSectionSubheader* tempSubheader = getNewFrameFileIndexSectionSubheader(in); if(m_locationSection->getComponent(OSSIM_RPF_FRAME_FILE_INDEX_SUBSECTION, component)) { result = new ossimRpfFrameFileIndexSubsection; result->setNumberOfFileIndexRecords(tempSubheader->getNumberOfIndexRecords()); result->setNumberOfPathnames(tempSubheader->getNumberOfPathnameRecords()); in.seekg(component.m_componentLocation, ios::beg); if(in) { if(result->parseStream(in, getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete result; result = 0; } } else { delete result; result = 0; } } if(tempSubheader) { delete tempSubheader; tempSubheader = 0; } } return result; } ossimRpfCompressionSection* ossimRpfHeader::getNewCompressionSection(const ossimFilename& file)const { ifstream in(file.c_str(), ios::in|ios::binary); return getNewCompressionSection(in); } ossimRpfCoverageSection* ossimRpfHeader::getNewCoverageSection(const ossimFilename& file)const { ifstream in(file.c_str(), ios::in|ios::binary); return getNewCoverageSection(in); } ossimRpfBoundaryRectTable* ossimRpfHeader::getNewBoundaryRectTable(const ossimFilename &file)const { ifstream in(file.c_str(), ios::in|ios::binary); return getNewBoundaryRectTable(in); } ossimRpfBoundaryRectSectionSubheader* ossimRpfHeader::getNewBoundaryRectSectSubheader(const ossimFilename &file)const { ifstream in(file.c_str(), ios::in|ios::binary); return getNewBoundaryRectSectSubheader(in); } ossimRpfFrameFileIndexSectionSubheader* ossimRpfHeader::getNewFrameFileIndexSectionSubheader(const ossimFilename &file)const { ifstream in(file.c_str(), ios::in|ios::binary); return getNewFrameFileIndexSectionSubheader(in); } ossimRpfFrameFileIndexSubsection* ossimRpfHeader::getNewFileIndexSubsection(const ossimFilename& file)const { ifstream in(file.c_str(), ios::in|ios::binary); return getNewFileIndexSubsection(in); } ossimString ossimRpfHeader::getDate()const { return m_govSpecDate; } ossim_uint32 ossimRpfHeader::getLocationSectionLocation() const { return m_locSectionLoc; } void ossimRpfHeader::setFilename(const ossimString& file) { ossimNitfCommon::setField(m_fileName, file, 12); } void ossimRpfHeader::setNewRepUpIndicator(const ossimString& s) { if (s.size()) { // Range check maybe??? (drb) m_newRepUpIndicator = static_cast(*s.begin()); } } void ossimRpfHeader::setGovSpecNumber(const ossimString& s) { ossimNitfCommon::setField(m_govSpecNumber, s, 15); } void ossimRpfHeader::setGovSpecDate(const ossimString& s) { ossimNitfCommon::setField(m_govSpecDate, s, 8); } void ossimRpfHeader::setSecurityClassification(const ossimString& s) { ossimNitfCommon::setField(m_securityClassification, s, 1); } void ossimRpfHeader::setCountryCode(const ossimString& s) { ossimNitfCommon::setField(m_countryCode, s, 2); } void ossimRpfHeader::setSecurityReleaseMarking(const ossimString& s) { ossimNitfCommon::setField(m_securityReleaseMarking, s, 2); } void ossimRpfHeader::setLocationSectionPos(std::streamoff off) { m_locSectionLoc = static_cast(off); } bool ossimRpfHeader::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* lookup = 0; ossimString s; lookup = kwl.find(prefix, NEW_REP_UP_INDICATOR_KW); if (lookup) { s = lookup; setNewRepUpIndicator(s); } lookup = kwl.find(prefix, GOV_SPEC_NUMBER_KW); if (lookup) { s = lookup; setGovSpecNumber(s); } lookup = kwl.find(prefix, GOV_SPEC_DATE_KW); if (lookup) { s = lookup; setGovSpecDate(s); } lookup = kwl.find(prefix, SECURITY_CLASSIFICATION_KW); if (lookup) { s = lookup; setSecurityClassification(s); } lookup = kwl.find(prefix, COUNTRY_CODE_KW); if (lookup) { s = lookup; setCountryCode(s); } lookup = kwl.find(prefix, SECURITY_RELEASE_MARKING_KW); if (lookup) { s = lookup; setSecurityReleaseMarking(s); } return true; } ossim-Miami-2.9.1/src/support_data/ossimRpfImageDescriptionSubheader.cpp000066400000000000000000000101001352751253100264770ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This class extends the stl's string class. // //******************************************************************** // $Id: ossimRpfImageDescriptionSubheader.cpp 14241 2009-04-07 19:59:23Z dburken $ #include #include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfImageDescriptionSubheader& data) { return data.print(out); } ossimRpfImageDescriptionSubheader::ossimRpfImageDescriptionSubheader() { clearFields(); } ossimErrorCode ossimRpfImageDescriptionSubheader::parseStream( std::istream& in, ossimByteOrder byteOrder) { if(in) { theStartOffset = in.tellg(); in.read((char*)&theNumberOfSpectralGroups, 2); in.read((char*)&theNumberOfSubframeTables, 2); in.read((char*)&theNumberOfSpectralBandTables, 2); in.read((char*)&theNumberOfSpectralBandLinesPerImageRow, 2); in.read((char*)&theNumberOfSubframesHorizontal, 2); in.read((char*)&theNumberOfSubframesVertical, 2); in.read((char*)&theNumberOfOutputColumnsPerSubframe, 4); in.read((char*)&theNumberOfOutputRowsPerSubframe, 4); in.read((char*)&theSubframeMaskTableOffset, 4); in.read((char*)&theTransparencyMaskTableOffset, 4); theEndOffset = in.tellg(); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theNumberOfSpectralGroups); anEndian.swap(theNumberOfSubframeTables); anEndian.swap(theNumberOfSpectralBandTables); anEndian.swap(theNumberOfSpectralBandLinesPerImageRow); anEndian.swap(theNumberOfSubframesHorizontal); anEndian.swap(theNumberOfSubframesVertical); anEndian.swap(theNumberOfOutputColumnsPerSubframe); anEndian.swap(theNumberOfOutputRowsPerSubframe); anEndian.swap(theSubframeMaskTableOffset); anEndian.swap(theTransparencyMaskTableOffset); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } std::ostream& ossimRpfImageDescriptionSubheader::print( std::ostream& out, const std::string& prefix) const { out << prefix << "NumberOfSpectralGroups: " << theNumberOfSpectralGroups << "\n" << prefix << "NumberOfSubframeTables: " << theNumberOfSubframeTables << "\n" << prefix << "NumberOfSpectralBandTables: " << theNumberOfSpectralBandTables << "\n" << prefix << "NumberOfSpectralBandLinesPerImageRow: " << theNumberOfSpectralBandLinesPerImageRow << "\n" << prefix << "NumberOfSubframesHorizontal: " << theNumberOfSubframesHorizontal << "\n" << prefix << "NumberOfSubframesVertical: " << theNumberOfSubframesVertical << "\n" << prefix << "NumberOfOutputColumnsPerSubframe: " << theNumberOfOutputColumnsPerSubframe << "\n" << prefix << "NumberOfOutputRowsPerSubframe: " << theNumberOfOutputRowsPerSubframe << "\n" << prefix << "SubframeMaskTableOffset: " << theSubframeMaskTableOffset << "\n" << prefix << "TransparencyMaskTableOffset: " << theTransparencyMaskTableOffset << std::endl; return out; } void ossimRpfImageDescriptionSubheader::clearFields() { theStartOffset = 0; theEndOffset = 0; theNumberOfSpectralGroups = 0; theNumberOfSubframeTables = 0; theNumberOfSpectralBandTables = 0; theNumberOfSpectralBandLinesPerImageRow = 0; theNumberOfSubframesHorizontal = 0; theNumberOfSubframesVertical = 0; theNumberOfOutputColumnsPerSubframe = 0; theNumberOfOutputRowsPerSubframe = 0; theSubframeMaskTableOffset = 0; theTransparencyMaskTableOffset = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfImageDisplayParameterSubheader.cpp000066400000000000000000000036411352751253100274760ustar00rootroot00000000000000//******************************************************************* // License: MIT // // Author: Garrett Potts // // Description: This class extends the stl's string class. // //******************************************************************** // $Id$ #include #include #include #include std::ostream& operator<<(std::ostream& out, const ossimRpfImageDisplayParameterSubheader& data) { data.print(out); return out; } ossimRpfImageDisplayParameterSubheader::ossimRpfImageDisplayParameterSubheader() { clearFields(); } ossimErrorCode ossimRpfImageDisplayParameterSubheader::parseStream(ossim::istream& in, ossimByteOrder byteOrder) { clearFields(); if(in) { theStartOffset = in.tellg(); in.read((char*)&theNumberOfImageRows, 4); in.read((char*)&theNumberOfImageCodesPerRow, 4); in.read((char*)&theImageCodeBitLength, 1); theEndOffset = in.tellg(); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theNumberOfImageRows); anEndian.swap(theNumberOfImageCodesPerRow); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfImageDisplayParameterSubheader::print(std::ostream& out)const { out << "theNumberOfImageRows: " << theNumberOfImageRows << "\n" << "theNumberOfImageCodesPerRow: " << theNumberOfImageCodesPerRow << "\n" << "theImageCodeBitLength: " << (unsigned long)theImageCodeBitLength; } void ossimRpfImageDisplayParameterSubheader::clearFields() { theNumberOfImageRows = 0; theNumberOfImageCodesPerRow = 0; theImageCodeBitLength = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfInfo.cpp000066400000000000000000000035021352751253100223310ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Mingjie Su // // Description: Rpf Info object. // //---------------------------------------------------------------------------- // $Id: ossimRpfInfo.cpp 1237 2010-08-05 19:50:27Z ming.su $ //ossim includes #include #include #include // Static trace for debugging static ossimTrace traceDebug("ossimRpfInfo:debug"); static ossimTrace traceDump("ossimRpfInfo:dump"); // This will dump offsets. ossimRpfInfo::ossimRpfInfo() : ossimInfoBase(), theFile(), m_infoFile() { } ossimRpfInfo::~ossimRpfInfo() { } bool ossimRpfInfo::open(const ossimFilename& file) { theFile = file; if (isOpen()) { std::ifstream in((theFile).c_str() ); std::string line; int index = 0; while(in.good()) { // Read in a line. std::getline(in, line); ossimString tmpStr = ossimString(line); if (index > 0) { if (!tmpStr.empty()) { std::vector tmpVector = tmpStr.split("|"); if (tmpVector.size() > 0) { m_infoFile = tmpVector[0]; break; } } } index++; } in.close(); return true; } return false; } bool ossimRpfInfo::isOpen() { ossimString ext = theFile.ext().downcase(); if(ext == "rpf") { return true; } else { return false; } } std::ostream& ossimRpfInfo::print(std::ostream& out) const { std::shared_ptr info = ossimInfoFactory::instance()->create(m_infoFile); if (info) { info->print(out); } return out; }ossim-Miami-2.9.1/src/support_data/ossimRpfLocationSection.cpp000066400000000000000000000215451352751253100245420ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id: ossimRpfLocationSection.cpp 20324 2011-12-06 22:25:23Z dburken $ #include #include /* ossim::byteOrder() */ #include #include #include #include #include #include #include static const ossimTrace traceDebug("ossimRpfLocationSection:debug"); std::ostream& operator<<(std::ostream& out, const ossimRpfComponentLocationRecord& data) { return data.print(out); } ossimRpfComponentLocationRecord::ossimRpfComponentLocationRecord() : m_componentId(0), m_componentLength(0), m_componentLocation(0) { } ossimRpfComponentLocationRecord::ossimRpfComponentLocationRecord( const ossimRpfComponentLocationRecord& record) : m_componentId(record.m_componentId), m_componentLength(record.m_componentLength), m_componentLocation(record.m_componentLocation) { } const ossimRpfComponentLocationRecord& ossimRpfComponentLocationRecord::operator=( const ossimRpfComponentLocationRecord& rhs) { if (this != &rhs) { m_componentId = rhs.m_componentId; m_componentLength = rhs.m_componentLength; m_componentLocation = rhs.m_componentLocation; } return *this; } std::ostream& ossimRpfComponentLocationRecord::print( std::ostream& out, const std::string& prefix) const { out << prefix << "ComponentId: " << m_componentId << "\n" << prefix << "ComponentIdString: " << ossimRpfComponentIdLut::instance()->getEntryString(m_componentId) << "\n" << prefix << "ComponentLength: " << m_componentLength << "\n" << prefix << "ComponentLocation: " << m_componentLocation << "\n"; return out; } std::ostream& operator <<(std::ostream& out, const ossimRpfLocationSection &data) { return data.print(out); } ossimErrorCode ossimRpfComponentLocationRecord::parseStream( std::istream& in, ossimByteOrder byteOrder) { if(in) { in.read((char*)&m_componentId, 2); in.read((char*)&m_componentLength, 4); in.read((char*)&m_componentLocation, 4); if( ossim::byteOrder() != byteOrder) { // swap to native ossimEndian anEndian; anEndian.swap(m_componentId); anEndian.swap(m_componentLength); anEndian.swap(m_componentLocation); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfComponentLocationRecord::writeStream(std::ostream& out) { if( ossim::byteOrder() != OSSIM_BIG_ENDIAN) { ossimEndian endian; endian.swap(m_componentId); endian.swap(m_componentLength); endian.swap(m_componentLocation); } out.write((char*)&m_componentId, 2); out.write((char*)&m_componentLength, 4); out.write((char*)&m_componentLocation, 4); if( ossim::byteOrder() != OSSIM_BIG_ENDIAN) { // Swap back to native byte order. ossimEndian endian; endian.swap(m_componentId); endian.swap(m_componentLength); endian.swap(m_componentLocation); } } ossimRpfLocationSection::ossimRpfLocationSection() { clearFields(); } ossimErrorCode ossimRpfLocationSection::parseStream(std::istream& in, ossimByteOrder byteOrder) { ossimErrorCode result = ossimErrorCodes::OSSIM_OK; if(in) { clearFields(); in.read((char*)&m_locationSectionLength, 2); in.read((char*)&m_locationTableOffset, 4); in.read((char*)&m_numberOfComponentLocationRecords, 2); in.read((char*)&m_locationRecordLength, 2); in.read((char*)&m_componentAggregateLength, 4); if( ossim::byteOrder() != byteOrder ) { ossimEndian anEndian; anEndian.swap(m_locationSectionLength); anEndian.swap(m_locationTableOffset); anEndian.swap(m_numberOfComponentLocationRecords); anEndian.swap(m_locationRecordLength); anEndian.swap(m_componentAggregateLength); } if(traceDebug()) { print(ossimNotify(ossimNotifyLevel_DEBUG)); ossimNotify(ossimNotifyLevel_DEBUG) << std::endl; } m_componentLocationList.resize(m_numberOfComponentLocationRecords); for(ossim_uint32 index = 0; (index < m_componentLocationList.size())&& (result == ossimErrorCodes::OSSIM_OK); ++index) { result = m_componentLocationList[index].parseStream(in, byteOrder); } } else { result = ossimErrorCodes::OSSIM_ERROR; } return result; } void ossimRpfLocationSection::writeStream(std::ostream& out) { if( ossim::byteOrder() != OSSIM_BIG_ENDIAN) { // Always write in big endian. ossimEndian endian; endian.swap(m_locationSectionLength); endian.swap(m_locationTableOffset); endian.swap(m_numberOfComponentLocationRecords); endian.swap(m_locationRecordLength); endian.swap(m_componentAggregateLength); } out.write((char*)&m_locationSectionLength, 2); out.write((char*)&m_locationTableOffset, 4); out.write((char*)&m_numberOfComponentLocationRecords, 2); out.write((char*)&m_locationRecordLength, 2); out.write((char*)&m_componentAggregateLength, 4); if( ossim::byteOrder() != OSSIM_BIG_ENDIAN) { // Swap back to native byte order. ossimEndian endian; endian.swap(m_locationSectionLength); endian.swap(m_locationTableOffset); endian.swap(m_numberOfComponentLocationRecords); endian.swap(m_locationRecordLength); endian.swap(m_componentAggregateLength); } for(ossim_uint32 i = 0; i < m_componentLocationList.size(); ++i) { m_componentLocationList[i].writeStream(out); } } std::ostream& ossimRpfLocationSection::print( std::ostream& out, const std::string& prefix) const { out << prefix << "LocationSectionLength: " << m_locationSectionLength << "\n" << prefix << "LocationTableOffset: " << m_locationTableOffset << "\n" << prefix << "NumberOfComponentLocationRecords: " << m_numberOfComponentLocationRecords << "\n" << prefix << "LocationRecordLength: " << m_locationRecordLength << "\n" << prefix << "ComponentAggregateLength: " << m_componentAggregateLength << "\n"; if(m_numberOfComponentLocationRecords > 0) { std::vector::const_iterator i = m_componentLocationList.begin(); while (i != m_componentLocationList.end()) { (*i).print(out, prefix); ++i; } } return out; } bool ossimRpfLocationSection::hasComponent(ossimRpfComponentId componentId)const { ossimRpfComponentLocationRecord result; return getComponent(componentId, result); } bool ossimRpfLocationSection::getComponent(ossimRpfComponentId componentId, ossimRpfComponentLocationRecord &result)const { std::vector::const_iterator component = m_componentLocationList.begin(); while(component != m_componentLocationList.end()) { if((*component).m_componentId == static_cast(componentId)) { result = *component; return true; } ++component; } return false; } void ossimRpfLocationSection::addComponentRecord(const ossimRpfComponentLocationRecord& record) { m_componentLocationList.push_back(record); } void ossimRpfLocationSection::setLocationSectionLength(ossim_uint16 length) { m_locationSectionLength = length; } void ossimRpfLocationSection::setLocationTableOffset(ossim_uint32 offset) { m_locationTableOffset = offset; } void ossimRpfLocationSection::setNumberOfComponentLocationRecords(ossim_uint16 count) { m_numberOfComponentLocationRecords = count; } void ossimRpfLocationSection::setLocationRecordLength(ossim_uint16 length) { m_locationRecordLength = length; } void ossimRpfLocationSection::setComponentAggregateLength(ossim_uint32 length) { m_componentAggregateLength = length; } void ossimRpfLocationSection::clearFields() { m_locationSectionLength = 0; m_locationTableOffset = 0; m_numberOfComponentLocationRecords = 0; m_locationRecordLength = 0; m_componentAggregateLength = 0; m_componentLocationList.clear(); } std::vector& ossimRpfLocationSection::getLocationRecordList() { return m_componentLocationList; } ossim-Miami-2.9.1/src/support_data/ossimRpfMaskSubheader.cpp000066400000000000000000000057461352751253100241700ustar00rootroot00000000000000#include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfMaskSubheader& data) { data.print(out); return out; } ossimRpfMaskSubheader::ossimRpfMaskSubheader() :theSubframeSequenceRecordLength(0), theTransparencySequenceRecordLength(0), theTransparentOutputPixelCodeLength(0), theOutputPixelCodeBitString(0), theNumberOfBytes(0) { clearFields(); } ossimRpfMaskSubheader::~ossimRpfMaskSubheader() { if (theOutputPixelCodeBitString) { delete [] theOutputPixelCodeBitString; theOutputPixelCodeBitString = 0; } } ossimErrorCode ossimRpfMaskSubheader::parseStream(std::istream& in, ossimByteOrder byteOrder) { if(in) { clearFields(); in.read((char*)&theSubframeSequenceRecordLength, 2); in.read((char*)&theTransparencySequenceRecordLength, 2); in.read((char*)&theTransparentOutputPixelCodeLength, 2); ossimEndian anEndian; if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(theSubframeSequenceRecordLength); anEndian.swap(theTransparencySequenceRecordLength); anEndian.swap(theTransparentOutputPixelCodeLength); } if(theTransparentOutputPixelCodeLength>0) { theNumberOfBytes = (long)std::ceil(theTransparentOutputPixelCodeLength/8.0); theOutputPixelCodeBitString = new unsigned char[theNumberOfBytes]; in.read((char*)theOutputPixelCodeBitString, theNumberOfBytes); } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfMaskSubheader::print(std::ostream& out)const { out << "theSubframeSequenceRecordLength: " << theSubframeSequenceRecordLength << "\ntheTransparencySequenceRecordLength: " << theTransparencySequenceRecordLength << "\ntheTransparentOutputPixelCodeLength: " << theTransparentOutputPixelCodeLength << "\ntheNumberOfBytes: " << theNumberOfBytes << "\ntheOutputPixelCodeBitString: "; // display the pixel code as a bit pattern. for(long index = theNumberOfBytes-1; index >=0; --index) { unsigned long temp = theOutputPixelCodeBitString[index]; out << ((temp>>7)&1) << ((temp>>6)&1) << ((temp>>5)&1) << ((temp>>4)&1) << ((temp>>3)&1) << ((temp>>2)&1) << ((temp>>1)&1) << (temp&1); } out << std::endl; } void ossimRpfMaskSubheader::clearFields() { theSubframeSequenceRecordLength = 0; theTransparencySequenceRecordLength = 0; theTransparentOutputPixelCodeLength = 0; theNumberOfBytes = 0; if(theOutputPixelCodeBitString) { delete [] theOutputPixelCodeBitString; theOutputPixelCodeBitString = 0; } } ossim-Miami-2.9.1/src/support_data/ossimRpfMaskSubsection.cpp000066400000000000000000000021061352751253100243670ustar00rootroot00000000000000#include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfMaskSubsection& data) { data.print(out); return out; } ossimRpfMaskSubsection::ossimRpfMaskSubsection() :theMaskSubheader(0) { theMaskSubheader = new ossimRpfMaskSubheader; } ossimRpfMaskSubsection::~ossimRpfMaskSubsection() { if(theMaskSubheader) { delete theMaskSubheader; theMaskSubheader = 0; } } ossimErrorCode ossimRpfMaskSubsection::parseStream(std::istream& in, ossimByteOrder byteOrder) { ossimErrorCode result = ossimErrorCodes::OSSIM_OK; if(in&&theMaskSubheader) { result = theMaskSubheader->parseStream(in, byteOrder); } else { result = ossimErrorCodes::OSSIM_ERROR; } return result; } void ossimRpfMaskSubsection::print(std::ostream& out)const { if(theMaskSubheader) { out << *theMaskSubheader; } } ossim-Miami-2.9.1/src/support_data/ossimRpfPathnameRecord.cpp000066400000000000000000000051401352751253100243320ustar00rootroot00000000000000//******************************************************************* // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Rpf support class. // //******************************************************************** // $Id: ossimRpfPathnameRecord.cpp 16997 2010-04-12 18:53:48Z dburken $ #include #include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfPathnameRecord& data) { return data.print(out); } ossimRpfPathnameRecord::ossimRpfPathnameRecord() : m_length(0), m_pathname("") { } ossimRpfPathnameRecord::ossimRpfPathnameRecord(const ossimRpfPathnameRecord& obj) : m_length(obj.m_length), m_pathname(obj.m_pathname) { } const ossimRpfPathnameRecord& ossimRpfPathnameRecord::operator=(const ossimRpfPathnameRecord& rhs) { if ( this != &rhs ) { m_length = rhs.m_length; m_pathname = rhs.m_pathname; } return *this; } void ossimRpfPathnameRecord::clearFields() { m_length = 0; m_pathname = ""; } ossimErrorCode ossimRpfPathnameRecord::parseStream(std::istream& in, ossimByteOrder byteOrder) { if(in) { ossimEndian anEndian; clearFields(); in.read((char*)&m_length, 2); if(anEndian.getSystemEndianType() != byteOrder) { anEndian.swap(m_length); } char *temp = new char[m_length+1]; in.read((char*)temp, m_length); temp[m_length] = '\0'; m_pathname = temp; delete [] temp; } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfPathnameRecord::writeStream(std::ostream& out) { ossimEndian anEndian; if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Always write big endian. anEndian.swap(m_length); } out.write((char*)&m_length, 2); if( anEndian.getSystemEndianType() != OSSIM_BIG_ENDIAN ) { // Swap back to native. anEndian.swap(m_length); } if(m_pathname.size() >= m_length) { out.write(m_pathname.c_str(), m_length); } } std::ostream& ossimRpfPathnameRecord::print(std::ostream& out)const { out << "length: " << m_length << "\npathname: " << m_pathname << std::endl; return out; } ossimString ossimRpfPathnameRecord::getPathname() const { return m_pathname; } void ossimRpfPathnameRecord::setPathName(const ossimString& path) { m_pathname = path; m_length = static_cast( path.size() ); } ossim-Miami-2.9.1/src/support_data/ossimRpfReplaceUpdateRecord.cpp000066400000000000000000000066151352751253100253230ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimRpfReplaceUpdateRecord.cpp // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // RPF replace/update section subheader record. // // See MIL-STD-2411 for detailed information. // //---------------------------------------------------------------------------- // $Id: ossimRpfReplaceUpdateRecord.cpp 20324 2011-12-06 22:25:23Z dburken $ #include #include #include /* for memset, memcpy */ #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfReplaceUpdateRecord& data) { return data.print(out); } ossimRpfReplaceUpdateRecord::ossimRpfReplaceUpdateRecord() : m_updateStatus(0) { clearFields(); } ossimRpfReplaceUpdateRecord::ossimRpfReplaceUpdateRecord(const ossimRpfReplaceUpdateRecord& obj) : m_updateStatus(obj.m_updateStatus) { memcpy(m_newFile, obj.m_newFile, 13); memcpy(m_oldFile, obj.m_oldFile, 13); } const ossimRpfReplaceUpdateRecord& ossimRpfReplaceUpdateRecord::operator=( const ossimRpfReplaceUpdateRecord& rhs) { if ( this != &rhs ) { memcpy(m_newFile, rhs.m_newFile, 13); memcpy(m_oldFile, rhs.m_oldFile, 13); m_updateStatus = rhs.m_updateStatus; } return *this; } ossimErrorCode ossimRpfReplaceUpdateRecord::parseStream( std::istream& in ) { ossimErrorCode status = ossimErrorCodes::OSSIM_OK; if( in.good() ) { clearFields(); in.read((char*)&m_newFile, 12); in.read((char*)&m_oldFile, 12); in.read((char*)&m_updateStatus, 1); } if ( in.fail() ) { status = ossimErrorCodes::OSSIM_ERROR; } return status; } void ossimRpfReplaceUpdateRecord::writeStream(std::ostream& out) { out.write((char*)&m_newFile, 12); out.write((char*)&m_oldFile, 12); out.write((char*)&m_updateStatus, 1); } std::ostream& ossimRpfReplaceUpdateRecord::print(std::ostream& out, const std::string& prefix, ossim_uint32 recordNumber)const { std::string pfx = prefix; pfx += "replace_update_record"; pfx += ossimString::toString(recordNumber).string(); pfx += "."; out << pfx << "new_file: " << m_newFile << "\n" << pfx << "old_file: " << m_oldFile << "\n" << pfx << "update_status: " << int(m_updateStatus) << std::endl; return out; } void ossimRpfReplaceUpdateRecord::getNewFilename(std::string& file) const { file = m_newFile; } void ossimRpfReplaceUpdateRecord::getOldFilename(std::string& file) const { file = m_oldFile; } ossim_uint8 ossimRpfReplaceUpdateRecord::getUpdateStatus() const { return m_updateStatus; } void ossimRpfReplaceUpdateRecord::setNewFilename(const std::string& file) { ossimNitfCommon::setField( m_newFile, ossimString(file), 12 ); } void ossimRpfReplaceUpdateRecord::setOldFilename(const std::string& file) { ossimNitfCommon::setField( m_oldFile, ossimString(file), 12 ); } void ossimRpfReplaceUpdateRecord::setUpdateStatus(ossim_uint8 status) { m_updateStatus = status; } void ossimRpfReplaceUpdateRecord::clearFields() { memset(m_newFile, ' ', 12); memset(m_oldFile, ' ', 12); m_updateStatus = 0; m_newFile[12] = '\0'; m_oldFile[12] = '\0'; } ossim-Miami-2.9.1/src/support_data/ossimRpfReplaceUpdateSectionSubheader.cpp000066400000000000000000000102571352751253100273310ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimRpfReplaceUpdateSectionSubheader.cpp // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // RPF replace/update section subheader record. // // See MIL-STD-2411 for detailed information. // //---------------------------------------------------------------------------- // $Id: ossimRpfReplaceUpdateSectionSubheader.cpp 20324 2011-12-06 22:25:23Z dburken $ #include #include /* ossim::byteOrder() */ #include #include #include #include // Static trace for debugging static ossimTrace traceDebug("ossimRpfReplaceUpdateSectionSubheader:debug"); std::ostream& operator <<(std::ostream& out, const ossimRpfReplaceUpdateSectionSubheader& data) { return data.print(out); } ossimRpfReplaceUpdateSectionSubheader::ossimRpfReplaceUpdateSectionSubheader() : m_tableOffset(0), m_numberOfRecords(0), m_recordLength(0) { } ossimRpfReplaceUpdateSectionSubheader::ossimRpfReplaceUpdateSectionSubheader( const ossimRpfReplaceUpdateSectionSubheader& obj) : m_tableOffset(obj.m_tableOffset), m_numberOfRecords(obj.m_numberOfRecords), m_recordLength(obj.m_recordLength) { } const ossimRpfReplaceUpdateSectionSubheader& ossimRpfReplaceUpdateSectionSubheader::operator=( const ossimRpfReplaceUpdateSectionSubheader& rhs) { if ( this != &rhs ) { m_tableOffset = rhs.m_tableOffset; m_numberOfRecords = rhs.m_numberOfRecords; m_recordLength = rhs.m_recordLength; } return *this; } ossimRpfReplaceUpdateSectionSubheader::~ossimRpfReplaceUpdateSectionSubheader() { } ossimErrorCode ossimRpfReplaceUpdateSectionSubheader::parseStream(std::istream& in, ossimByteOrder byteOrder) { if(in) { in.read((char*)&m_tableOffset, 4); in.read((char*)&m_numberOfRecords, 2); in.read((char*)&m_recordLength, 2); if( ossim::byteOrder() != byteOrder ) { ossimEndian anEndian; anEndian.swap(m_tableOffset); anEndian.swap(m_numberOfRecords); anEndian.swap(m_recordLength); } } else { return ossimErrorCodes::OSSIM_ERROR; } if ( traceDebug() ) { print( ossimNotify(ossimNotifyLevel_NOTICE) ); } return ossimErrorCodes::OSSIM_OK; } void ossimRpfReplaceUpdateSectionSubheader::writeStream(std::ostream& out) { if( ossim::byteOrder() != OSSIM_BIG_ENDIAN) { // Swap to big endian. ossimEndian anEndian; anEndian.swap(m_tableOffset); anEndian.swap(m_numberOfRecords); anEndian.swap(m_recordLength); } out.write((char*)&m_tableOffset, 4); out.write((char*)&m_numberOfRecords, 2); out.write((char*)&m_recordLength, 2); if( ossim::byteOrder() != OSSIM_BIG_ENDIAN) { // Swap back to native byte order. ossimEndian anEndian; anEndian.swap(m_tableOffset); anEndian.swap(m_numberOfRecords); anEndian.swap(m_recordLength); } } std::ostream& ossimRpfReplaceUpdateSectionSubheader::print(std::ostream& out) const { out << "ossimRpfReplaceUpdateSectionSubheader DEBUG:" << "\ntable_offset: " << m_tableOffset << "\nnumber_of_records: " << m_numberOfRecords << "\nrecord_length: " << m_recordLength << std::endl; return out; } ossim_uint32 ossimRpfReplaceUpdateSectionSubheader::getOffset() const { return m_tableOffset; } ossim_uint16 ossimRpfReplaceUpdateSectionSubheader::getNumberOfRecords() const { return m_numberOfRecords; } ossim_uint16 ossimRpfReplaceUpdateSectionSubheader::getRecordLength() const { return m_recordLength; } void ossimRpfReplaceUpdateSectionSubheader::setNumberOfRecords(ossim_uint16 count) { m_numberOfRecords = count; } void ossimRpfReplaceUpdateSectionSubheader::setRecordLength(ossim_uint16 length) { m_recordLength = length; } void ossimRpfReplaceUpdateSectionSubheader::clearFields() { m_tableOffset = 0; m_numberOfRecords = 0; m_recordLength = 0; } ossim-Miami-2.9.1/src/support_data/ossimRpfReplaceUpdateTable.cpp000066400000000000000000000027441352751253100251330ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimRpfReplaceUpdateTable.cpp // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Holds a table of RPF replace/update section subheader records. // // See MIL-STD-2411 for detailed information. // //---------------------------------------------------------------------------- // $Id: ossimRpfReplaceUpdateTable.cpp 20324 2011-12-06 22:25:23Z dburken $ #include #include ossimRpfReplaceUpdateTable::ossimRpfReplaceUpdateTable() : m_table(0) { } ossimRpfReplaceUpdateTable::ossimRpfReplaceUpdateTable(const ossimRpfReplaceUpdateTable& obj) : m_table(obj.m_table) { } const ossimRpfReplaceUpdateTable& ossimRpfReplaceUpdateTable::operator=( const ossimRpfReplaceUpdateTable& rhs) { if ( this != &rhs ) { m_table = rhs.m_table; } return *this; } void ossimRpfReplaceUpdateTable::addRecord(const ossimRpfReplaceUpdateRecord& record) { m_table.push_back(record); } void ossimRpfReplaceUpdateTable::clear() { m_table.clear(); } std::ostream& ossimRpfReplaceUpdateTable::print( std::ostream& out, const std::string& prefix ) const { ossim_uint32 size = static_cast( m_table.size() ); for (ossim_uint32 i = 0; i < size; ++i) { m_table[i].print(out, prefix, i); } return out; } ossim-Miami-2.9.1/src/support_data/ossimRpfToc.cpp000066400000000000000000001114371352751253100221720ustar00rootroot00000000000000//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Rpf support class // //******************************************************************** // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimRpfToc:debug"); std::ostream& operator <<(std::ostream& out, const ossimRpfToc& data) { return data.print(out); } ossimRpfToc::ossimRpfToc() :m_tocEntryList(), m_filename(), m_nitfFileHeader(0), m_rpfHeader(0) { } ossimRpfToc::~ossimRpfToc() { deleteAll(); } ossimErrorCode ossimRpfToc::parseFile(const ossimFilename &fileName, bool keepFileHeader) { static const char MODULE[] = "ossimRpfToc::parseFile"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered....." << std::endl; } ossimRefPtr nitfFile = new ossimNitfFile; clearAll(); nitfFile->parseFile(fileName); m_nitfFileHeader = nitfFile->getHeader(); m_rpfHeader = 0; // ossimRefPtr if( !m_nitfFileHeader.valid() ) { nitfFile = 0; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " leaving with no nitf header found....." << std::endl; } return ossimErrorCodes::OSSIM_ERROR; } ossimNitfTagInformation info; m_nitfFileHeader->getTag(info, "RPFHDR"); if(traceDebug() && (info.getTagName() == "RPFHDR") ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " nitf file header print\n"; m_nitfFileHeader->print( ossimNotify(ossimNotifyLevel_DEBUG) ); } if ( !keepFileHeader ) { // we no longer need access to the nitf header. We got what we needed. m_nitfFileHeader = 0; } nitfFile = 0; m_filename = fileName; if(info.getTagName() == "RPFHDR") { m_rpfHeader = new ossimRpfHeader; std::ifstream in(m_filename.c_str(), std::ios::in|std::ios::binary); // set the get pointer for the stream to the start // of the Rpf header data in.seekg(info.getTagDataOffset(), std::ios::beg); // now get the header data. We do not need to pass in the byte order. // this is grabbed from the first byte of the stream. To see this, // Look at the RpfHeader implementation. m_rpfHeader->parseStream(in); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG: Found RPF HEADER tag\n"; m_rpfHeader->print( ossimNotify(ossimNotifyLevel_DEBUG) ); } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfToc::parseFile: Leaving No RPFHDR tag found" << "\n"; } return ossimErrorCodes::OSSIM_ERROR; } if( m_rpfHeader.valid() ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Building toc list" << "\n"; } buildTocEntryList( m_rpfHeader.get() ); } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfToc::parseFile: Leaving no RPFHDR " << __LINE__ << "\n"; } return ossimErrorCodes::OSSIM_ERROR; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfToc::parseFile: Returning with OK." << std::endl; } return ossimErrorCodes::OSSIM_OK; } void ossimRpfToc::createTocAndCopyFrames( const ossimFilename& dotRpfFile, const ossimFilename& outputDir ) { static const char MODULE[] = "ossimRpfToc::createTocAndCopyFrames"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << "\ndot rpf file: " << dotRpfFile << "\noutput directory: " << outputDir << "\n"; } if ( outputDir.expand().exists() == false ) { if ( !outputDir.createDirectory(true, 0775) ) { std::string e = MODULE; e += " ERROR:\nCould not create directory: "; e+= outputDir.c_str(); throw ossimException(e); } } // Open the dot rpf file. std::ifstream* dotRpfStr = new std::ifstream; dotRpfStr->open(dotRpfFile.c_str(), ios_base::in); if ( !dotRpfStr->good() ) { delete dotRpfStr; dotRpfStr = 0; std::string e = MODULE; e += " ERROR:\nCould not open: "; e += dotRpfFile.c_str(); throw ossimException(e); } ossimFilename sourceADotTocFile = getSourceTocFile(*dotRpfStr); if ( sourceADotTocFile.empty() ) { delete dotRpfStr; dotRpfStr = 0; std::string e = MODULE; e += " ERROR:\nCould not deduce source a.toc file!"; throw ossimException(e); } // Open the source a.toc file. Note the true flag is to keep the file header. ossimRefPtr sourceADotToc = new ossimRpfToc; if ( sourceADotToc->parseFile(sourceADotTocFile, true) != ossimErrorCodes::OSSIM_OK ) { delete dotRpfStr; dotRpfStr = 0; std::string e = MODULE; e += " ERROR:\nCould not open: "; e += sourceADotTocFile.c_str(); throw ossimException(e); } ossimRefPtr sourceNitfFileHdr = sourceADotToc->getNitfFileHeader(); if ( !sourceNitfFileHdr.valid() ) { delete dotRpfStr; dotRpfStr = 0; std::string e = MODULE; e += " ERROR:\nCould not get nitf file header from: "; e += sourceADotTocFile.c_str(); throw ossimException(e); } ossimRefPtr sourceRpfHdr = sourceADotToc->getRpfHeader(); if ( !sourceRpfHdr.valid() ) { delete dotRpfStr; dotRpfStr = 0; std::string e = MODULE; e += " ERROR:\nCould not get rpf header from: "; e += sourceADotTocFile.c_str(); throw ossimException(e); } // Get the boundary rect sub header from the source a.toc. ossimRefPtr boundaryRectSectionSubheader = sourceRpfHdr->getNewBoundaryRectSectSubheader(sourceADotTocFile); if ( !boundaryRectSectionSubheader.valid() ) { delete dotRpfStr; dotRpfStr = 0; std::string e = MODULE; e += " ERROR:\nCould not pull boundary rect sub header from source file: "; e += sourceADotTocFile.c_str(); throw ossimException(e); } // Get the boundary rect table from the source a.toc. ossimRefPtr boundaryRectTable = sourceRpfHdr->getNewBoundaryRectTable(sourceADotTocFile); if ( !boundaryRectTable.valid() ) { delete dotRpfStr; dotRpfStr = 0; std::string e = MODULE; e += " ERROR:\nCould not pull boundary rect table from source file: "; e += sourceADotTocFile.c_str(); throw ossimException(e); } // Get the frame file subheader from the source a.toc. ossimRefPtr frameFileSubHeader = sourceRpfHdr->getNewFrameFileIndexSectionSubheader(sourceADotTocFile); if ( !frameFileSubHeader.valid() ) { delete dotRpfStr; dotRpfStr = 0; std::string e = MODULE; e += " ERROR:\nCould not pull frame file sub header from source file: "; e += sourceADotTocFile.c_str(); throw ossimException(e); } // Get the frame file subsection from the source a.toc. ossimRefPtr frameFileSubSection = sourceRpfHdr->getNewFileIndexSubsection(sourceADotTocFile); if ( !frameFileSubSection.valid() ) { delete dotRpfStr; dotRpfStr = 0; std::string e = MODULE; e += " ERROR:\nCould not pull frame file sub section from source file: "; e += sourceADotTocFile.c_str(); throw ossimException(e); } // Open the output file to write to. const ossimFilename A_DOT_TOC_FILE = "a.toc"; ossimFilename dotTocFile = outputDir.dirCat(A_DOT_TOC_FILE); std::ofstream* dotTocStr = new std::ofstream; dotTocStr->open( dotTocFile.c_str(), ios::out|ios::binary ); if ( !dotTocStr->good() ) { delete dotRpfStr; dotRpfStr = 0; delete dotTocStr; dotTocStr =0; std::string e = MODULE; e += " ERROR:\nCould not open: "; e += dotTocFile.c_str(); throw ossimException(e); } // Variables used throughout: ossimRefPtr prop = new ossimStringProperty(); ossimString field; ossimString s; // std::streampos fileHeaderLength = 0; // std::streampos fileLength = 0; ossimRefPtr fileHdr = new ossimNitfFileHeaderV2_0(); // Set the CLEVEL: s = "01"; fileHdr->setComplexityLevel(s); // Set the OSTAID: prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::OSTAID_KW); fileHdr->setProperty(prop); // Set the FDT (date): fileHdr->setDate(); // Set the FTITLE: s = "a.toc"; fileHdr->setTitle(s); // Set the FSCLAS: prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCLAS_KW); fileHdr->setProperty(prop); // Set the FSCODE: prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCODE_KW); fileHdr->setProperty(prop); // Set the FSCTLH: prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCTLH_KW); fileHdr->setProperty(prop); // Set the ONAME: prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::ONAME_KW); fileHdr->setProperty(prop); // Set the OPHONE: prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::OPHONE_KW); fileHdr->setProperty(prop); // Add the rpf header. ossimRpfHeader* rpfHdr = new ossimRpfHeader( *(sourceRpfHdr.get()) ); ossimRefPtr rpfHdrRp = rpfHdr; ossimNitfTagInformation rpfHdrInfo(rpfHdrRp); fileHdr->addTag(rpfHdrInfo); //--- // Write it out... // The first write will be with an rpfheader with no location sections just // to see where the end of the file header is. //--- fileHdr->writeStream(*dotTocStr); //--- // End of file header. Get the header length. This will also be the // start of the location section. //--- std::streampos pos = dotTocStr->tellp(); std::streamoff locationSectionOffset = pos; // Set the header length: fileHdr->setHeaderLength( static_cast(locationSectionOffset) ); // Set the location of the location section. rpfHdr->setLocationSectionPos(locationSectionOffset); // Set the file name. rpfHdr->setFilename(A_DOT_TOC_FILE); // Add the component location records to the header. ossimRpfLocationSection* locSec = rpfHdr->getLocationSection(); // Clear the records copied from the source a.toc. locSec->clearFields(); //--- // Set the length of the locSec to 74. The record itself is 14 bytes plus // an additional 60 bytes for six location records ten bytes each. //--- const ossim_uint16 LOCATION_SECTION_SIZE = 74; locSec->setLocationSectionLength(LOCATION_SECTION_SIZE); // Set the offset which 14 bytes to get to the first record. locSec->setLocationTableOffset(14); // Six records: locSec->setNumberOfComponentLocationRecords(6); // Each record 10 bytes: locSec->setLocationRecordLength(10); // Don't know the aggregate length yet. ossimRpfComponentLocationRecord locRec; // Note: See ossimRpfConstants for enum ossimRpfComponentId const ossim_uint32 RPFHDR_SIZE = 48; const ossim_uint32 LOCATION_SECTION_OFFSET = static_cast(locationSectionOffset); const ossim_uint32 BOUNDARY_SUBHEADER_SIZE = 8; const ossim_uint32 BOUNDARY_RECORD_SIZE = 132; const ossim_uint32 FILE_SUBHEADER_SIZE = 13; // const ossim_uint32 = ; // Record 1 RPFHDR location: ossim_uint32 rpfHdrOffset = 0; if ( fileHdr->getTag(rpfHdrInfo, "RPFHDR") ) { rpfHdrOffset = rpfHdrInfo.getTagDataOffset(); } locRec.m_componentId = OSSIM_RPF_HEADER_COMPONENT; // 128 locRec.m_componentLength = RPFHDR_SIZE; locRec.m_componentLocation = static_cast(rpfHdrInfo.getTagDataOffset()); locSec->addComponentRecord(locRec); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG)<< "rpf hdr offset: " << rpfHdrOffset << "\n"; locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) ); } // Record 2 location section: locRec.m_componentId = OSSIM_RPF_LOCATION_COMPONENT; // 129 locRec.m_componentLength = LOCATION_SECTION_SIZE; locRec.m_componentLocation = LOCATION_SECTION_OFFSET; locSec->addComponentRecord(locRec); if ( traceDebug() ) { locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) ); } // Record 3 boundary rect sub header section: locRec.m_componentId = OSSIM_RPF_BOUNDARY_RECT_SECTION_SUBHEADER; // 148 locRec.m_componentLength = BOUNDARY_SUBHEADER_SIZE; locRec.m_componentLocation = locRec.m_componentLocation + LOCATION_SECTION_SIZE; locSec->addComponentRecord(locRec); if ( traceDebug() ) { locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) ); } // Capture the location. std::streamoff boundaryRectPosition = locRec.m_componentLocation; // Record 4 boundary rect table: locRec.m_componentId = OSSIM_RPF_BOUNDARY_RECT_TABLE; // 149 locRec.m_componentLength = BOUNDARY_RECORD_SIZE; locRec.m_componentLocation = locRec.m_componentLocation + BOUNDARY_SUBHEADER_SIZE; locSec->addComponentRecord(locRec); if ( traceDebug() ) { locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) ); } // Record 5 file index sub header: locRec.m_componentId = OSSIM_RPF_FRAME_FILE_INDEX_SECTION_SUBHEADER; // 150 locRec.m_componentLength = FILE_SUBHEADER_SIZE; locRec.m_componentLocation = locRec.m_componentLocation + BOUNDARY_RECORD_SIZE; locSec->addComponentRecord(locRec); if ( traceDebug() ) { locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) ); } // Record 6 file index sub header: locRec.m_componentId = OSSIM_RPF_FRAME_FILE_INDEX_SUBSECTION; // 151 locRec.m_componentLength = 0; // need to calculate. locRec.m_componentLocation = locRec.m_componentLocation + FILE_SUBHEADER_SIZE; locSec->addComponentRecord(locRec); if ( traceDebug() ) { locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) ); } // Seek back and re-write... dotTocStr->seekp(0, ios::beg); fileHdr->writeStream(*dotTocStr); dotTocStr->seekp(boundaryRectPosition, ios::beg); // Only writing one entry: boundaryRectSectionSubheader->setNumberOfEntries(1); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "writing boundaryRectSectionSubheader:\n" << *(boundaryRectSectionSubheader.get()) << "\n"; } //--- // Write the boundary rectangle section. This includes the subheader and subsection. // These coorespond to location records 3 and 4 above. //--- boundaryRectSectionSubheader->writeStream(*dotTocStr); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Original boundaryRectTable:\n" << *(boundaryRectTable.get()) << "\n"; } ossim_uint32 entry; if ( getCorespondingEntry( frameFileSubSection.get(), *dotRpfStr, entry ) ) { ossimRpfBoundaryRectRecord boundaryRectRecord; if ( boundaryRectTable->getEntry( entry, boundaryRectRecord) ) { if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "writing boundaryRectTable:\n" << boundaryRectRecord << "\n"; } boundaryRectRecord.writeStream(*dotTocStr); } else { std::string e = MODULE; e += " ERROR:\nCould not get bounding rect record for entry: "; e += ossimString::toString(entry).c_str(); throw ossimException(e); } } else { std::string e = MODULE; e += " ERROR:\nCould not deduce entry from frame list!"; throw ossimException(e); } frameFileSubHeader->setNumberOfIndexRecords( getNumberOfFrames(*dotRpfStr) ); frameFileSubHeader->setNumberOfPathnameRecords(1); const ossim_uint16 FRAME_FILE_INDEX_RECORD_LENGTH = 33; frameFileSubHeader->setIndexRecordLength( FRAME_FILE_INDEX_RECORD_LENGTH ); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "writing frameFileSubHeader:\n" << *(frameFileSubHeader.get()) << "\n"; } frameFileSubHeader->writeStream( *dotTocStr ); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "writing frameFileSubSection:\n"; } std::streamoff frameFileIndexSectionStartPos = dotTocStr->tellp(); writeFrameFileIndexSection(frameFileSubSection.get(), *dotRpfStr, *dotTocStr); std::streamoff endOfFilePos = dotTocStr->tellp(); // Update the location section length for the frame file index section. locSec->getLocationRecordList()[5].m_componentLength = static_cast(endOfFilePos - frameFileIndexSectionStartPos); // Update the length of all location sections. locSec->setComponentAggregateLength( static_cast(endOfFilePos) - rpfHdr->getLocationSectionLocation() ); fileHdr->setFileLength(static_cast(endOfFilePos)); dotTocStr->seekp(0, ios::beg); fileHdr->writeStream(*dotTocStr); ossimNotify(ossimNotifyLevel_DEBUG) << "Wrote file: " << dotTocFile << "\n"; // Copy the frames to the output directory. copyFrames(*dotRpfStr, outputDir); // Cleanup: delete dotRpfStr; dotRpfStr = 0; delete dotTocStr; dotTocStr =0; } std::ostream& ossimRpfToc::print(std::ostream& out, const std::string& prefix, bool printOverviews) const { printHeader( out, prefix ); //--- // Go through the entries... We're going to skip overviews here. //--- for ( ossim_uint32 entryIndex = 0; entryIndex < m_tocEntryList.size(); ++entryIndex ) { printTocEntry( out, entryIndex, prefix, printOverviews ); } return out; } std::ostream& ossimRpfToc::printHeader( std::ostream& out, const std::string& prefix ) const { if( m_rpfHeader.valid() ) { m_rpfHeader->print(out, prefix); } return out; } std::ostream& ossimRpfToc::printTocEntry( std::ostream& out, ossim_uint32 entryIndex, const std::string& prefix, bool printOverviews ) const { const ossimRpfTocEntry* tocEntry = getTocEntry( entryIndex ); if ( tocEntry ) { if ( traceDebug() ) { tocEntry->print(out, prefix); } const ossimRpfBoundaryRectRecord REC = tocEntry->getBoundaryInformation(); ossimString scale = REC.getScale(); if ( (scale.contains("OVERVIEW") == false) || printOverviews ) { ossimString entryPrefix = prefix; entryPrefix += "image"; entryPrefix += ossimString::toString(entryIndex); entryPrefix += "."; REC.print(out, entryPrefix); //--- // Get the first frame that exists so we can get to // the attributes. //--- ossimRpfFrameEntry frameEntry; getFirstEntry( tocEntry, frameEntry); if (frameEntry.exists()) { ossimRpfFrame rpfFrame; if ( rpfFrame.parseFile(frameEntry.getFullPath()) == ossimErrorCodes::OSSIM_OK ) { rpfFrame.print(out, entryPrefix); } } } } return out; } ossim_uint32 ossimRpfToc::getNumberOfEntries()const { return static_cast(m_tocEntryList.size()); } const ossimRpfTocEntry* ossimRpfToc::getTocEntry(ossim_uint32 index)const { if(index < m_tocEntryList.size()) { return m_tocEntryList[index]; } return 0; } ossim_int32 ossimRpfToc::getTocEntryIndex(const ossimRpfTocEntry* entry) { for(ossim_int32 i = 0; i < (ossim_int32)m_tocEntryList.size(); ++i) { if(m_tocEntryList[i] == entry) { return i; } } return -1; } const ossimNitfFileHeader* ossimRpfToc::getNitfFileHeader()const { return m_nitfFileHeader.get(); } const ossimRpfHeader* ossimRpfToc::getRpfHeader()const { return m_rpfHeader.get(); } ossim_uint32 ossimRpfToc::getNumberOfFramesHorizontal(ossim_uint32 idx) const { ossim_uint32 nFrames = 0; const ossimRpfTocEntry* pEntry = getTocEntry( idx ); if ( pEntry != NULL ) { nFrames = pEntry->getNumberOfFramesHorizontal(); } return nFrames; } ossim_uint32 ossimRpfToc::getNumberOfFramesVertical(ossim_uint32 idx) const { ossim_uint32 nFrames = 0; const ossimRpfTocEntry* pEntry = getTocEntry( idx ); if ( pEntry != NULL ) { nFrames = pEntry->getNumberOfFramesVertical(); } return nFrames; } bool ossimRpfToc::getRpfFrameEntry(ossim_uint32 entryIdx, ossim_uint32 row, ossim_uint32 col, ossimRpfFrameEntry& result)const { const ossimRpfTocEntry* pEntry = getTocEntry( entryIdx ); if ( pEntry != NULL ) { return pEntry->getEntry( row, col, result ); } return false; } const ossimString ossimRpfToc::getRelativeFramePath( ossim_uint32 entryIdx, ossim_uint32 row, ossim_uint32 col) const { ossimRpfFrameEntry frameEntry; bool bResult = getRpfFrameEntry( entryIdx, row, col, frameEntry ); if ( bResult == true ) { return frameEntry.getPathToFrameFileFromRoot(); } return ossimString(""); } void ossimRpfToc::deleteAll() { m_rpfHeader = 0; deleteTocEntryList(); } void ossimRpfToc::clearAll() { deleteTocEntryList(); m_filename = ""; } void ossimRpfToc::deleteTocEntryList() { std::vector< ossimRpfTocEntry*>::iterator tocEntry = m_tocEntryList.begin(); while(tocEntry != m_tocEntryList.end()) { if(*tocEntry) { delete (*tocEntry); *tocEntry = NULL; } ++tocEntry; } m_tocEntryList.clear(); } void ossimRpfToc::buildTocEntryList(ossimRpfHeader* rpfHeader) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfToc::buildTocEntryList: entered.....\n"; } std::ifstream in(m_filename.c_str(), std::ios::in | std::ios::binary); if(!in) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfToc::buildTocEntryList: invalid input leaving..... " << std::endl; } return; } if(rpfHeader) { if(traceDebug()) { rpfHeader->print(ossimNotify(ossimNotifyLevel_DEBUG)); } deleteTocEntryList(); ossimRpfBoundaryRectSectionSubheader *boundaryRect = rpfHeader->getNewBoundaryRectSectSubheader(in); if(boundaryRect) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Got boundary rect\n"; } std::streamoff current = in.tellg(); // they give the offset from the // end of the boundary subheader to the start of the // entry table. We have to create an absolute // offset. current += boundaryRect->getTableOffset(); // take to the start of the table entries in.seekg(current, ios::beg); allocateTocEntryList(boundaryRect->getNumberOfEntries()); // now we can read the entries if(m_tocEntryList.size() > 0) { for(ossim_uint32 index = 0; index < m_tocEntryList.size(); index++) { m_tocEntryList[index]->parseStream(in, rpfHeader->getByteOrder()); } } ossimRpfFrameFileIndexSectionSubheader* frameFileIndexHead = rpfHeader->getNewFrameFileIndexSectionSubheader(in); // get the offset to the table long offsetToIndexSubsection = in.tellg(); if(frameFileIndexHead) { ossimRpfFrameFileIndexRecord tempIndexRec; ossimRpfPathnameRecord tempPathNameRec; ossim_int32 count = frameFileIndexHead->getNumberOfIndexRecords(); while(count > 0) { tempIndexRec.parseStream(in, rpfHeader->getByteOrder() ); // get the path information. we must seek to a different location // within the file. So we must remember where we currently are at std::streamoff currentPosition = in.tellg(); in.seekg(offsetToIndexSubsection + tempIndexRec.getPathnameRecordOffset(), ios::beg); tempPathNameRec.parseStream(in, rpfHeader->getByteOrder()); // We have the root directory where all frame files are subfiles of // ossimString rootDirectory(ossimFilename(m_filename.path())+ // ossimFilename(ossimFilename::thePathSeparator)); ossimFilename rootDirectory; getRootDirectory(rootDirectory); // we have the actual path from the root directory to the // frame file. We must separate the two. There have been // occurrences where the path in the A.TOC file // is upper case but the path in the directory on the file // system is lower case. This // will fool the system in thinking the file does not exist // when it actually does. ossimString pathToFrameFile( ossimFilename(tempPathNameRec.getPathname()) + tempIndexRec.getFilename()); ossimRpfFrameEntry entry(rootDirectory, pathToFrameFile); m_tocEntryList[tempIndexRec.getBoundaryRecNumber()]->setEntry(entry, tempIndexRec.getLocationRowNumber(), tempIndexRec.getLocationColNumber()); // now go back to where we were in.seekg(currentPosition, ios::beg); --count; } delete frameFileIndexHead; frameFileIndexHead = 0; } } delete boundaryRect; boundaryRect = NULL; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfToc::buildTocEntryList: leaving....." << std::endl; } } void ossimRpfToc::allocateTocEntryList(ossim_uint32 numberOfEntries) { if(m_tocEntryList.size() > 0) { deleteTocEntryList(); } for(ossim_uint32 index = 0; index < numberOfEntries; index++) { m_tocEntryList.push_back(new ossimRpfTocEntry); } } void ossimRpfToc::getRootDirectory(ossimFilename& dir) const { dir = m_filename.expand().path(); } void ossimRpfToc::getFirstEntry(const ossimRpfTocEntry* rpfTocEntry, ossimRpfFrameEntry& frameEntry) const { if (rpfTocEntry) { ossim_int32 framesHorizontal = rpfTocEntry->getNumberOfFramesHorizontal(); ossim_int32 framesVertical = rpfTocEntry->getNumberOfFramesVertical(); bool foundEntry = false; for (ossim_int32 v = 0; v < framesVertical; ++v) { for (ossim_int32 h = 0; h < framesHorizontal; ++h) { rpfTocEntry->getEntry(v, h, frameEntry); if (frameEntry.exists()) { foundEntry = true; break; } } if (foundEntry) { break; } } } } void ossimRpfToc::writeFrameFileIndexSection(ossimRpfFrameFileIndexSubsection* frameFileSubSection, std::ifstream& dotRpfStr, std::ofstream& dotTocStr) { static const char MODULE[] = "ossimRpfToc::writeFrameFileIndexSection"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } const ossim_uint16 FRAME_FILE_INDEX_RECORD_LENGTH = 33; ossim_uint32 frames = getNumberOfFrames(dotRpfStr); ossim_uint32 pathnameRecordOffset = FRAME_FILE_INDEX_RECORD_LENGTH * frames; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "frames: " << frames << "\n"; } if ( !dotRpfStr.good() ) { // see if we can clear it. Someone might have hit end of file(eof). dotRpfStr.clear(); } dotRpfStr.seekg(0, ios_base::beg); std::string line; ossimFilename file; ossimRpfFrameFileIndexRecord record; ossim_uint32 framesWritten = 0; // Eat the first line which is the bounding rect line std::getline(dotRpfStr, line); while( dotRpfStr.good() ) { std::getline(dotRpfStr, line); if ( dotRpfStr.good() ) { if ( getFile(line, file) ) { if ( frameFileSubSection->getFrameFileIndexRecordFromFile(file.file(), record) ) { // Always single entry. record.setBoundaryRecNumber(0); record.setPathnameRecordOffset(pathnameRecordOffset); record.writeStream(dotTocStr); ++framesWritten; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "wrote record:\n" << record << "\n"; } } } } } // Now set the path record. ossimFilename d = file.path(); ossimString s = "./"; s += d.file(); s += "/"; ossimRpfPathnameRecord pathRecord; pathRecord.setPathName(s); pathRecord.writeStream(dotTocStr); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "frames written: " << framesWritten << "\nwrote record:\n" << pathRecord << "\n"; } dotRpfStr.clear(); dotRpfStr.seekg(0, ios_base::beg); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited..." << std::endl; } } void ossimRpfToc::copyFrames(std::ifstream& dotRpfStr, const ossimFilename& outputDir) { static const char MODULE[] = "ossimRpfToc::copyFrames"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossim_uint32 frames = getNumberOfFrames(dotRpfStr); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "frames to copy: " << frames << "\n"; } if ( !dotRpfStr.good() ) { // see if we can clear it. Someone might have hit end of file(eof). dotRpfStr.clear(); } dotRpfStr.seekg(0, ios_base::beg); std::string line; ossimFilename file; ossimFilename destinationFile; ossimFilename subDir; ossim_uint32 framesCopied = 0; // Eat the first line which is the bounding rect line std::getline(dotRpfStr, line); // Get the second line which is first file. std::getline(dotRpfStr, line); // Get the file name and make the sub directory if needed. if ( getFile(line, file) ) { destinationFile = outputDir; subDir = file.path(); subDir = subDir.file(); destinationFile = destinationFile.dirCat( subDir ); // This is output_dir/subdir. See if subdir exist: if ( !destinationFile.exists() ) { destinationFile.createDirectory(); } } // Start over: if ( !dotRpfStr.good() ) { // see if we can clear it. Someone might have hit end of file(eof). dotRpfStr.clear(); } dotRpfStr.seekg(0, ios_base::beg); // Eat the first line which is the bounding rect line std::getline(dotRpfStr, line); while( dotRpfStr.good() ) { std::getline(dotRpfStr, line); if ( dotRpfStr.good() ) { if ( getFile(line, file) ) { destinationFile = outputDir; subDir = file.path(); subDir = subDir.file(); destinationFile = destinationFile.dirCat( subDir ); destinationFile = destinationFile.dirCat( file.file() ); if ( file.copyFileTo(destinationFile) ) { ++framesCopied; } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Copied frame: " << destinationFile << "\n"; } } } } ossimNotify(ossimNotifyLevel_NOTICE) << "Frames copied: " << framesCopied << std::endl; dotRpfStr.clear(); dotRpfStr.seekg(0, ios_base::beg); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited..." << std::endl; } } ossim_uint32 ossimRpfToc::getNumberOfFrames(std::ifstream& dotRpfStr) const { ossim_uint32 result = 0; if ( !dotRpfStr.good() ) { // see if we can clear it. Someone might have hit end of file(eof). dotRpfStr.clear(); } dotRpfStr.seekg(0, ios_base::beg); // Eat the first line which is the bounding rect. std::string line; std::getline(dotRpfStr, line); while( dotRpfStr.good() ) { std::getline(dotRpfStr, line); if ( dotRpfStr.good() ) { ++result; } } dotRpfStr.clear(); dotRpfStr.seekg(0, ios_base::beg); return result; } ossimFilename ossimRpfToc::getSourceTocFile(std::ifstream& dotRpfStr) const { ossimFilename tocFile; if ( !dotRpfStr.good() ) { dotRpfStr.clear(); } dotRpfStr.seekg(0, ios_base::beg); // Eat the first line which is the bounding rect. std::string line; std::getline(dotRpfStr, line); // Get the second line which is first file. std::getline(dotRpfStr, line); // Get the file name and make the sub directory if needed. ossimFilename file; if ( getFile(line, file) ) { ossimFilename subDir = file.path(); tocFile = subDir.dirCat("a.toc"); if ( !tocFile.exists() ) { tocFile = subDir.dirCat("A.TOC"); if ( !tocFile.exists() ) { subDir = subDir.path(); tocFile = subDir.dirCat("a.toc"); if ( !tocFile.exists() ) { tocFile = subDir.dirCat("A.TOC"); if ( !tocFile.exists() ) { tocFile.clear(); } } } } } if ( !dotRpfStr.good() ) { dotRpfStr.clear(); } dotRpfStr.seekg(0, ios_base::beg); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfToc::getSourceTocFile result: " << tocFile << "\n"; } return tocFile; } bool ossimRpfToc::getCorespondingEntry( ossimRpfFrameFileIndexSubsection* frameFileSubSection, std::ifstream& dotRpfStr, ossim_uint32& entry) const { bool result = false; if ( !dotRpfStr.good() ) { // see if we can clear it. Someone might have hit end of file(eof). dotRpfStr.clear(); } dotRpfStr.seekg(0, ios_base::beg); std::string line; ossimFilename file; ossimRpfFrameFileIndexRecord record; // Eat the first line which is the bounding rect line std::getline(dotRpfStr, line); std::getline(dotRpfStr, line); if ( getFile(line, file) ) { if ( frameFileSubSection->getFrameFileIndexRecordFromFile(file.file(), record) ) { entry = record.getBoundaryRecNumber(); result = true; } } if ( !dotRpfStr.good() ) { dotRpfStr.clear(); } dotRpfStr.seekg(0, ios_base::beg); return result; } bool ossimRpfToc::getFile(const std::string& line, ossimFilename& file) const { //--- // line form: // /some_path/N03E030/006EZC1B.I21|30.4654240835311,3.59074642049858|30.5401678385356,3.65984532949882 // //--- bool result = false; if ( line.size() ) { ossimString os(line); std::vector lineArray; os.split(lineArray, "|"); if ( lineArray.size() ) { file = lineArray[0]; result = true; } } return result; } ossim-Miami-2.9.1/src/support_data/ossimRpfTocEntry.cpp000066400000000000000000000165701352751253100232160ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimRpfTocEntry.cpp 19900 2011-08-04 14:19:57Z dburken $ #include #include #include #include #include #include #include #include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimRpfTocEntry& data) { data.print(out); return out; } ossimRpfTocEntry::ossimRpfTocEntry() { } ossimErrorCode ossimRpfTocEntry::parseStream( std::istream &in, ossimByteOrder byteOrder) { ossimErrorCode result = ossimErrorCodes::OSSIM_OK; result = theBoundaryInformation.parseStream(in, byteOrder); if(result == ossimErrorCodes::OSSIM_OK) { allocateFrameEntryArray(); } // Fetch the number of samples as data member since it may need to be adjusted due to // wrap (OLK 10/10): theNumSamples = theBoundaryInformation.getNumberOfFramesHorizontal() * 1536; ossimDpt ddpp; getDecimalDegreesPerPixel(ddpp); ossim_float64 width_in_deg = theNumSamples*ddpp.x; if (width_in_deg >= 360.0) theNumSamples -= (width_in_deg - 360.0)/ddpp.x; return result; } std::ostream& ossimRpfTocEntry::print(std::ostream& out, const std::string& prefix) const { theBoundaryInformation.print(out, prefix); std::vector< std::vector >::const_iterator frameEntry = theFrameEntryArray.begin(); while( frameEntry != theFrameEntryArray.end() ) { std::vector::const_iterator i = (*frameEntry).begin(); while ( i != (*frameEntry).end() ) { (*i).print(out, prefix); ++i; } ++frameEntry; } return out; } ossim_uint32 ossimRpfTocEntry::getNumberOfFramesHorizontal()const { return theBoundaryInformation.getNumberOfFramesHorizontal(); } ossim_uint32 ossimRpfTocEntry::getNumberOfFramesVertical()const { return theBoundaryInformation.getNumberOfFramesVertical(); } ossim_uint32 ossimRpfTocEntry::getNumberOfLines() const { return theBoundaryInformation.getNumberOfFramesVertical() * 1536; } ossim_uint32 ossimRpfTocEntry::getNumberOfSamples() const { return theNumSamples; } ossim_uint32 ossimRpfTocEntry::getNumberOfBands() const { ossim_uint32 result = 0; ossimString productType = getProductType().trim().upcase(); if( productType == "CIB" ) { result = 1; } else if ( productType == "CADRG" ) { result = 3; } return result; } void ossimRpfTocEntry::getBoundingRect(ossimIrect& rect) const { rect = ossimIrect(0, 0, getNumberOfSamples()-1, getNumberOfLines()-1); } const ossimRpfBoundaryRectRecord& ossimRpfTocEntry::getBoundaryInformation() const { return theBoundaryInformation; } void ossimRpfTocEntry::setEntry(const ossimRpfFrameEntry& entry, long row, long col) { if(row < (long)theFrameEntryArray.size() && row >= 0) { if(col < (long)theFrameEntryArray[row].size() && col >= 0) { theFrameEntryArray[row][col] = entry; } } } bool ossimRpfTocEntry::getEntry(long row, long col, ossimRpfFrameEntry& result)const { if(row < (long)theFrameEntryArray.size() && row >= 0) { if(col < (long)theFrameEntryArray[row].size() && col >= 0) { result = theFrameEntryArray[row][col]; } else { return false; } } else { return false; } return true; } ossimString ossimRpfTocEntry::getProductType() const { return theBoundaryInformation.getProductType(); } /*! * If there is an entry and all the files don't exist we will return * true. */ bool ossimRpfTocEntry::isEmpty()const { long rows = (long)theFrameEntryArray.size(); long cols = 0; if(rows > 0) { cols = (long)theFrameEntryArray[0].size(); for(long rowIndex = 0; rowIndex < rows; ++ rowIndex) { for(long colIndex = 0; colIndex < cols; ++colIndex) { if(theFrameEntryArray[rowIndex][colIndex].exists()) { return false; } } } } return true; } ossimRefPtr ossimRpfTocEntry::getImageGeometry() const { ossimGpt ul(theBoundaryInformation.getCoverage().getUlLat(), theBoundaryInformation.getCoverage().getUlLon()); // Decimal degrees per pixel: ossimDpt ddpp; getDecimalDegreesPerPixel(ddpp); // Tie point - Shifted to pixel-is-point: ossimGpt tie( (ul.latd() - (ddpp.y/2.0)), (ul.lond() + (ddpp.x/2.0)), 0.0 ); // Origin - Use the center latitude for horizontal scale, and the left edge as origin longitude // (OLK 10/10) ossimGpt origin ((ul.lat + theBoundaryInformation.getCoverage().getLlLat())/2.0, tie.lon); #if 0 /* Please leave for debug. (drb) */ std::cout << "boundaryInfo:\n" << boundaryInfo << std::endl; #endif int z = theBoundaryInformation.getZone(); if (z == 74) z--; // Fix J to a zone. if (z > 64) z -= 64; // Below the equator else z -= 48; // Above the equator ossimRefPtr mapProj = 0; if ( z != 9 ) { mapProj = new ossimEquDistCylProjection; } else { mapProj = new ossimAzimEquDistProjection; } // Set the origin: mapProj->setOrigin(origin); // Set the scale: mapProj->setDecimalDegreesPerPixel(ddpp); // Set the tie: mapProj->setUlTiePoints(tie); // Give projection to the geometry object. ossimRefPtr geom = new ossimImageGeometry; geom->setProjection( mapProj.get() ); return geom; } void ossimRpfTocEntry::getDecimalDegreesPerPixel(ossimDpt& scale) const { #if 1 scale.x = theBoundaryInformation.getCoverage().getHorizontalInterval(); scale.y = theBoundaryInformation.getCoverage().getVerticalInterval(); #else ossim_float64 ulLat = theBoundaryInformation.getCoverage().getUlLat(); ossim_float64 ulLon = theBoundaryInformation.getCoverage().getUlLon(); ossim_float64 urLon = theBoundaryInformation.getCoverage().getUrLon(); ossim_float64 llLat = theBoundaryInformation.getCoverage().getLrLat(); ossim_float64 lines = getNumberOfLines(); ossim_float64 samps = getNumberOfSamples(); scale.x = (urLon - ulLon) / samps; scale.y = (ulLat - llLat) / lines; #endif } void ossimRpfTocEntry::getMetersPerPixel(ossimDpt& scale) const { scale.x = theBoundaryInformation.getCoverage().getVerticalResolution(); scale.y = theBoundaryInformation.getCoverage().getHorizontalResolution(); } void ossimRpfTocEntry::allocateFrameEntryArray() { theFrameEntryArray.resize(theBoundaryInformation.getNumberOfFramesVertical()); ossim_uint32 horizontalSize = theBoundaryInformation.getNumberOfFramesHorizontal(); for(ossim_uint32 index = 0; index < theFrameEntryArray.size(); index++) { theFrameEntryArray[index].resize(horizontalSize); } } ossim-Miami-2.9.1/src/support_data/ossimRsmida.cpp000066400000000000000000001056131352751253100222130ustar00rootroot00000000000000//--- // File: ossimRsmida.cpp // // License: MIT // // See LICENSE.txt file in the top level directory for more details. //--- #include #include #include #include #include static const ossimTrace traceDebug("ossimRsmida:debug"); static std::string IID_KW = "iid"; static std::string EDITION_KW = "edition"; static std::string ISID_KW = "isid"; static std::string SID_KW = "sid"; static std::string STID_KW = "stid"; static std::string YEAR_KW = "year"; static std::string MONTH_KW = "month"; static std::string DAY_KW = "day"; static std::string HOUR_KW = "hour"; static std::string MINUTE_KW = "minute"; static std::string SECOND_KW = "second"; static std::string NRG_KW = "nrg"; static std::string NCG_KW = "ncg"; static std::string TRG_KW = "trg"; static std::string TCG_KW = "tcg"; static std::string GRNDD_KW = "grndd"; static std::string XUOR_KW = "xuor"; static std::string YUOR_KW = "yuor"; static std::string ZUOR_KW = "zuor"; static std::string XUXR_KW = "xuxr"; static std::string XUYR_KW = "xuyr"; static std::string XUZR_KW = "xuzr"; static std::string YUXR_KW = "yuxr"; static std::string YUYR_KW = "yuyr"; static std::string YUZR_KW = "yuzr"; static std::string ZUXR_KW = "zuxr"; static std::string ZUYR_KW = "zuyr"; static std::string ZUZR_KW = "zuzr"; static std::string V1X_KW = "v1x"; static std::string V1Y_KW = "v1y"; static std::string V1Z_KW = "v1z"; static std::string V2X_KW = "v2x"; static std::string V2Y_KW = "v2y"; static std::string V2Z_KW = "v2z"; static std::string V3X_KW = "v3x"; static std::string V3Y_KW = "v3y"; static std::string V3Z_KW = "v3z"; static std::string V4X_KW = "v4x"; static std::string V4Y_KW = "v4y"; static std::string V4Z_KW = "v4z"; static std::string V5X_KW = "v5x"; static std::string V5Y_KW = "v5y"; static std::string V5Z_KW = "v5z"; static std::string V6X_KW = "v6x"; static std::string V6Y_KW = "v6y"; static std::string V6Z_KW = "v6z"; static std::string V7X_KW = "v7x"; static std::string V7Y_KW = "v7y"; static std::string V7Z_KW = "v7z"; static std::string V8X_KW = "v8x"; static std::string V8Y_KW = "v8y"; static std::string V8Z_KW = "v8z"; static std::string GRPX_KW = "grpx"; static std::string GRPY_KW = "grpy"; static std::string GRPZ_KW = "grpz"; static std::string FULLR_KW = "fullr"; static std::string FULLC_KW = "fullc"; static std::string MINR_KW = "minr"; static std::string MAXR_KW = "maxr"; static std::string MINC_KW = "minc"; static std::string MAXC_KW = "maxc"; static std::string IE0_KW = "ie0"; static std::string IER_KW = "ier"; static std::string IEC_KW = "iec"; static std::string IERR_KW = "ierr"; static std::string IERC_KW = "ierc"; static std::string IECC_KW = "iecc"; static std::string IA0_KW = "ia0"; static std::string IAR_KW = "iar"; static std::string IAC_KW = "iac"; static std::string IARR_KW = "iarr"; static std::string IARC_KW = "iarc"; static std::string IACC_KW = "iacc"; static std::string SPX_KW = "spx"; static std::string SVX_KW = "svx"; static std::string SAX_KW = "sax"; static std::string SPY_KW = "spy"; static std::string SVY_KW = "svy"; static std::string SAY_KW = "say"; static std::string SPZ_KW = "spz"; static std::string SVZ_KW = "svz"; static std::string SAZ_KW = "saz"; ossimRsmida::ossimRsmida() : m_iid(), m_edition(), m_isid(), m_sid(), m_stid(), m_year(0), m_month(0), m_day(0), m_hour(0), m_minute(0), m_second(0.0), m_nrg(0), m_ncg(0), m_trg(0.0), m_tcg(0.0), m_grndd('\0'), m_xuor(0.0), m_yuor(0.0), m_zuor(0.0), m_xuxr(0.0), m_xuyr(0.0), m_xuzr(0.0), m_yuxr(0.0), m_yuyr(0.0), m_yuzr(0.0), m_zuxr(0.0), m_zuyr(0.0), m_zuzr(0.0), m_v1x(0.0), m_v1y(0.0), m_v1z(0.0), m_v2x(0.0), m_v2y(0.0), m_v2z(0.0), m_v3x(0.0), m_v3y(0.0), m_v3z(0.0), m_v4x(0.0), m_v4y(0.0), m_v4z(0.0), m_v5x(0.0), m_v5y(0.0), m_v5z(0.0), m_v6x(0.0), m_v6y(0.0), m_v6z(0.0), m_v7x(0.0), m_v7y(0.0), m_v7z(0.0), m_v8x(0.0), m_v8y(0.0), m_v8z(0.0), m_grpx(0.0), m_grpy(0.0), m_grpz(0.0), m_fullr(0), m_fullc(0), m_minr(0), m_maxr(0), m_minc(0), m_maxc(0), m_ie0(0.0), m_ier(0.0), m_iec(0.0), m_ierr(0.0), m_ierc(0.0), m_iecc(0.0), m_ia0(0.0), m_iar(0.0), m_iac(0.0), m_iarr(0.0), m_iarc(0.0), m_iacc(0.0), m_spx(0.0), m_svx(0.0), m_sax(0.0), m_spy(0.0), m_svy(0.0), m_say(0.0), m_spz(0.0), m_svz(0.0), m_saz(0.0) { } ossimRsmida::ossimRsmida( const ossimRsmida& obj ) : m_iid( obj.m_iid ), m_edition( obj.m_edition ), m_isid( obj.m_isid ), m_sid( obj.m_sid ), m_stid( obj.m_stid ), m_year( obj.m_year ), m_month( obj.m_month ), m_day( obj.m_day ), m_hour( obj.m_hour ), m_minute( obj.m_minute ), m_second( obj.m_second ), m_nrg( obj.m_nrg ), m_ncg( obj.m_ncg ), m_trg( obj.m_trg ), m_tcg( obj.m_tcg ), m_grndd( obj.m_grndd ), m_xuor( obj.m_xuor ), m_yuor( obj.m_yuor ), m_zuor( obj.m_zuor ), m_xuxr( obj.m_xuxr ), m_xuyr( obj.m_xuyr ), m_xuzr( obj.m_xuzr ), m_yuxr( obj.m_yuxr ), m_yuyr( obj.m_yuyr ), m_yuzr( obj.m_yuzr ), m_zuxr( obj.m_zuxr ), m_zuyr( obj.m_zuyr ), m_zuzr( obj.m_zuzr ), m_v1x( obj.m_v1x ), m_v1y( obj.m_v1y ), m_v1z( obj.m_v1z ), m_v2x( obj.m_v2x ), m_v2y( obj.m_v2y ), m_v2z( obj.m_v2z ), m_v3x( obj.m_v3x ), m_v3y( obj.m_v3y ), m_v3z( obj.m_v3z ), m_v4x( obj.m_v4x ), m_v4y( obj.m_v4y ), m_v4z( obj.m_v4z ), m_v5x( obj.m_v5x ), m_v5y( obj.m_v5y ), m_v5z( obj.m_v5z ), m_v6x( obj.m_v6x ), m_v6y( obj.m_v6y ), m_v6z( obj.m_v6z ), m_v7x( obj.m_v7x ), m_v7y( obj.m_v7y ), m_v7z( obj.m_v7z ), m_v8x( obj.m_v8x ), m_v8y( obj.m_v8y ), m_v8z( obj.m_v8z ), m_grpx( obj.m_grpx ), m_grpy( obj.m_grpy ), m_grpz( obj.m_grpz ), m_fullr( obj.m_fullr ), m_fullc( obj.m_fullc ), m_minr( obj.m_minr ), m_maxr( obj.m_maxr ), m_minc( obj.m_minc ), m_maxc( obj.m_maxc ), m_ie0( obj.m_ie0 ), m_ier( obj.m_ier ), m_iec( obj.m_iec ), m_ierr( obj.m_ierr ), m_ierc( obj.m_ierc ), m_iecc( obj.m_iecc ), m_ia0( obj.m_ia0 ), m_iar( obj.m_iar ), m_iac( obj.m_iac ), m_iarr( obj.m_iarr ), m_iarc( obj.m_iarc ), m_iacc( obj.m_iacc ), m_spx( obj.m_spx ), m_svx( obj.m_svx ), m_sax( obj.m_sax ), m_spy( obj.m_spy ), m_svy( obj.m_svy ), m_say( obj.m_say ), m_spz( obj.m_spz ), m_svz( obj.m_svz ), m_saz( obj.m_saz ) { } const ossimRsmida& ossimRsmida::operator=( const ossimRsmida& rhs ) { if (this != &rhs) { m_iid = rhs.m_iid; m_edition = rhs.m_edition; m_isid = rhs.m_isid; m_sid = rhs.m_sid; m_stid = rhs.m_stid; m_year = rhs.m_year; m_month = rhs.m_month; m_day = rhs.m_day; m_hour = rhs.m_hour; m_minute = rhs.m_minute; m_second = rhs.m_second; m_nrg = rhs.m_nrg; m_ncg = rhs.m_ncg; m_trg = rhs.m_trg; m_tcg = rhs.m_tcg; m_grndd = rhs.m_grndd; m_xuor = rhs.m_xuor; m_yuor = rhs.m_yuor; m_zuor = rhs.m_zuor; m_xuxr = rhs.m_xuxr; m_xuyr = rhs.m_xuyr; m_xuzr = rhs.m_xuzr; m_yuxr = rhs.m_yuxr; m_yuyr = rhs.m_yuyr; m_yuzr = rhs.m_yuzr; m_zuxr = rhs.m_zuxr; m_zuyr = rhs.m_zuyr; m_zuzr = rhs.m_zuzr; m_v1x = rhs.m_v1x; m_v1y = rhs.m_v1y; m_v1z = rhs.m_v1z; m_v2x = rhs.m_v2x; m_v2y = rhs.m_v2y; m_v2z = rhs.m_v2z; m_v3x = rhs.m_v3x; m_v3y = rhs.m_v3y; m_v3z = rhs.m_v3z; m_v4x = rhs.m_v4x; m_v4y = rhs.m_v4y; m_v4z = rhs.m_v4z; m_v5x = rhs.m_v5x; m_v5y = rhs.m_v5y; m_v5z = rhs.m_v5z; m_v6x = rhs.m_v6x; m_v6y = rhs.m_v6y; m_v6z = rhs.m_v6z; m_v7x = rhs.m_v7x; m_v7y = rhs.m_v7y; m_v7z = rhs.m_v7z; m_v8x = rhs.m_v8x; m_v8y = rhs.m_v8y; m_v8z = rhs.m_v8z; m_grpx = rhs.m_grpx; m_grpy = rhs.m_grpy; m_grpz = rhs.m_grpz; m_fullr = rhs.m_fullr; m_fullc = rhs.m_fullc; m_minr = rhs.m_minr; m_maxr = rhs.m_maxr; m_minc = rhs.m_minc; m_maxc = rhs.m_maxc; m_ie0 = rhs.m_ie0; m_ier = rhs.m_ier; m_iec = rhs.m_iec; m_ierr = rhs.m_ierr; m_ierc = rhs.m_ierc; m_iecc = rhs.m_iecc; m_ia0 = rhs.m_ia0; m_iar = rhs.m_iar; m_iac = rhs.m_iac; m_iarr = rhs.m_iarr; m_iarc = rhs.m_iarc; m_iacc = rhs.m_iacc; m_spx = rhs.m_spx; m_svx = rhs.m_svx; m_sax = rhs.m_sax; m_spy = rhs.m_spy; m_svy = rhs.m_svy; m_say = rhs.m_say; m_spz = rhs.m_spz; m_svz = rhs.m_svz; m_saz = rhs.m_saz; } return *this; } void ossimRsmida::saveState( ossimKeywordlist& kwl, const std::string& prefix ) const { std::string pfx = prefix + std::string("rsmida."); kwl.add(pfx.c_str(), IID_KW.c_str(), m_iid.c_str()); kwl.add(pfx.c_str(), EDITION_KW.c_str(), m_edition.c_str()); kwl.add(pfx.c_str(), ISID_KW.c_str(), m_isid.c_str()); kwl.add(pfx.c_str(), SID_KW.c_str(), m_sid.c_str()); kwl.add(pfx.c_str(), STID_KW.c_str(), m_stid.c_str()); kwl.add(pfx.c_str(), YEAR_KW.c_str(), m_year); kwl.add(pfx.c_str(), MONTH_KW.c_str(), m_month); kwl.add(pfx.c_str(), DAY_KW.c_str(), m_day); kwl.add(pfx.c_str(), HOUR_KW.c_str(), m_hour); kwl.add(pfx.c_str(), MINUTE_KW.c_str(), m_minute); kwl.add(pfx.c_str(), SECOND_KW.c_str(), m_second); kwl.add(pfx.c_str(), NRG_KW.c_str(), m_nrg); kwl.add(pfx.c_str(), NCG_KW.c_str(), m_ncg); kwl.add(pfx.c_str(), TRG_KW.c_str(), m_trg); kwl.add(pfx.c_str(), TCG_KW.c_str(), m_tcg); kwl.add(pfx.c_str(), GRNDD_KW.c_str(), m_grndd); kwl.add(pfx.c_str(), XUOR_KW.c_str(), m_xuor); kwl.add(pfx.c_str(), YUOR_KW.c_str(), m_yuor); kwl.add(pfx.c_str(), ZUOR_KW.c_str(), m_zuor); kwl.add(pfx.c_str(), XUXR_KW.c_str(), m_xuxr); kwl.add(pfx.c_str(), XUYR_KW.c_str(), m_xuyr); kwl.add(pfx.c_str(), XUZR_KW.c_str(), m_xuzr); kwl.add(pfx.c_str(), YUXR_KW.c_str(), m_yuxr); kwl.add(pfx.c_str(), YUYR_KW.c_str(), m_yuyr); kwl.add(pfx.c_str(), YUZR_KW.c_str(), m_yuzr); kwl.add(pfx.c_str(), ZUXR_KW.c_str(), m_zuxr); kwl.add(pfx.c_str(), ZUYR_KW.c_str(), m_zuyr); kwl.add(pfx.c_str(), ZUZR_KW.c_str(), m_zuzr); kwl.add(pfx.c_str(), V1X_KW.c_str(), m_v1x); kwl.add(pfx.c_str(), V1Y_KW.c_str(), m_v1y); kwl.add(pfx.c_str(), V1Z_KW.c_str(), m_v1z); kwl.add(pfx.c_str(), V2X_KW.c_str(), m_v2x); kwl.add(pfx.c_str(), V2Y_KW.c_str(), m_v2y); kwl.add(pfx.c_str(), V2Z_KW.c_str(), m_v2z); kwl.add(pfx.c_str(), V3X_KW.c_str(), m_v3x); kwl.add(pfx.c_str(), V3Y_KW.c_str(), m_v3y); kwl.add(pfx.c_str(), V3Z_KW.c_str(), m_v3z); kwl.add(pfx.c_str(), V4X_KW.c_str(), m_v4x); kwl.add(pfx.c_str(), V4Y_KW.c_str(), m_v4y); kwl.add(pfx.c_str(), V4Z_KW.c_str(), m_v4z); kwl.add(pfx.c_str(), V5X_KW.c_str(), m_v5x); kwl.add(pfx.c_str(), V5Y_KW.c_str(), m_v5y); kwl.add(pfx.c_str(), V5Z_KW.c_str(), m_v5z); kwl.add(pfx.c_str(), V6X_KW.c_str(), m_v6x); kwl.add(pfx.c_str(), V6Y_KW.c_str(), m_v6y); kwl.add(pfx.c_str(), V6Z_KW.c_str(), m_v6z); kwl.add(pfx.c_str(), V7X_KW.c_str(), m_v7x); kwl.add(pfx.c_str(), V7Y_KW.c_str(), m_v7y); kwl.add(pfx.c_str(), V7Z_KW.c_str(), m_v7z); kwl.add(pfx.c_str(), V8X_KW.c_str(), m_v8x); kwl.add(pfx.c_str(), V8Y_KW.c_str(), m_v8y); kwl.add(pfx.c_str(), V8Z_KW.c_str(), m_v8z); kwl.add(pfx.c_str(), GRPX_KW.c_str(), m_grpx); kwl.add(pfx.c_str(), GRPY_KW.c_str(), m_grpy); kwl.add(pfx.c_str(), GRPZ_KW.c_str(), m_grpz); kwl.add(pfx.c_str(), FULLR_KW.c_str(), m_fullr); kwl.add(pfx.c_str(), FULLC_KW.c_str(), m_fullc); kwl.add(pfx.c_str(), MINR_KW.c_str(), m_minr); kwl.add(pfx.c_str(), MAXR_KW.c_str(), m_maxr); kwl.add(pfx.c_str(), MINC_KW.c_str(), m_minc); kwl.add(pfx.c_str(), MAXC_KW.c_str(), m_maxc); kwl.add(pfx.c_str(), IE0_KW.c_str(), m_ie0); kwl.add(pfx.c_str(), IER_KW.c_str(), m_ier); kwl.add(pfx.c_str(), IEC_KW.c_str(), m_iec); kwl.add(pfx.c_str(), IERR_KW.c_str(), m_ierr); kwl.add(pfx.c_str(), IERC_KW.c_str(), m_ierc); kwl.add(pfx.c_str(), IECC_KW.c_str(), m_iecc); kwl.add(pfx.c_str(), IA0_KW.c_str(), m_ie0); kwl.add(pfx.c_str(), IAR_KW.c_str(), m_ier); kwl.add(pfx.c_str(), IAC_KW.c_str(), m_iec); kwl.add(pfx.c_str(), IARR_KW.c_str(), m_ie0); kwl.add(pfx.c_str(), IARC_KW.c_str(), m_ier); kwl.add(pfx.c_str(), IACC_KW.c_str(), m_iec); kwl.add(pfx.c_str(), SPX_KW.c_str(), m_spx); kwl.add(pfx.c_str(), SVX_KW.c_str(), m_svx); kwl.add(pfx.c_str(), SAX_KW.c_str(), m_sax); kwl.add(pfx.c_str(), SPY_KW.c_str(), m_spy); kwl.add(pfx.c_str(), SVY_KW.c_str(), m_svy); kwl.add(pfx.c_str(), SAY_KW.c_str(), m_say); kwl.add(pfx.c_str(), SPZ_KW.c_str(), m_spz); kwl.add(pfx.c_str(), SVZ_KW.c_str(), m_svz); kwl.add(pfx.c_str(), SAZ_KW.c_str(), m_saz); } // End: ossimRsmida::saveState( ... ) bool ossimRsmida::loadState( const ossimKeywordlist& kwl, const std::string& prefix ) { static const char MODULE[] = "ossimRsmida::loadState"; std::string pfx = prefix + std::string("rsmida."); std::string key; std::string value; bool result = false; // Set to true on last key. while( 1 ) // Break out on error. { key = IID_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_iid = value; } else { break; } key = EDITION_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_edition = value; } else { break; } key = ISID_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_isid = value; } else // Not required at this time. Blank in nitf test data. { m_isid.clear(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_NOTICE) << MODULE << " NOTICE: " << ISID_KW << "was not found or is blank.\n"; } } key = SID_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_sid = value; } else // Not required at this time. Blank in nitf test data. { m_sid.clear(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_NOTICE) << MODULE << " NOTICE: " << ISID_KW << "was not found or is blank.\n"; } } key = STID_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_stid = value; } else { break; } key = YEAR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_year = ossimString(value).toUInt32(); } else { break; } key = MONTH_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_month = ossimString(value).toUInt32(); } else { break; } key = DAY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_day = ossimString(value).toUInt32(); } else { break; } key = HOUR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_hour = ossimString(value).toUInt32(); } else { break; } key = MINUTE_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_minute = ossimString(value).toUInt32(); } else { break; } key = SECOND_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_second = ossimString(value).toFloat64(); } else { break; } key = NRG_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_nrg = ossimString(value).toInt32(); } else { break; } key = NCG_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_ncg = ossimString(value).toInt32(); } else { break; } key = TRG_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_trg = ossimString(value).toFloat64(); } else { break; } key = TCG_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_tcg = ossimString(value).toFloat64(); } else { break; } key = GRNDD_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_grndd = value[0]; } else { break; } key = XUOR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_xuor = ossimString(value).toFloat64(); } else { break; } key = YUOR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_yuor = ossimString(value).toFloat64(); } else { break; } key = ZUOR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_zuor = ossimString(value).toFloat64(); } else { break; } key = XUXR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_xuxr = ossimString(value).toFloat64(); } else { break; } key = XUYR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_xuyr = ossimString(value).toFloat64(); } else { break; } key = XUZR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_xuzr = ossimString(value).toFloat64(); } else { break; } key = YUXR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_yuxr = ossimString(value).toFloat64(); } else { break; } key = YUYR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_yuyr = ossimString(value).toFloat64(); } else { break; } key = YUZR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_yuzr = ossimString(value).toFloat64(); } else { break; } key = ZUXR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_zuxr = ossimString(value).toFloat64(); } else { break; } key = ZUYR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_zuyr = ossimString(value).toFloat64(); } else { break; } key = ZUZR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_zuzr = ossimString(value).toFloat64(); } else { break; } key = V1X_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v1x = ossimString(value).toFloat64(); } else { break; } key = V1Y_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v1y = ossimString(value).toFloat64(); } else { break; } key = V1Z_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v1z = ossimString(value).toFloat64(); } else { break; } key = V2X_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v2x = ossimString(value).toFloat64(); } else { break; } key = V2Y_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v2y = ossimString(value).toFloat64(); } else { break; } key = V2Z_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v2z = ossimString(value).toFloat64(); } else { break; } key = V3X_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v3x = ossimString(value).toFloat64(); } else { break; } key = V3Y_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v3y = ossimString(value).toFloat64(); } else { break; } key = V3Z_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v3z = ossimString(value).toFloat64(); } else { break; } key = V4X_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v4x = ossimString(value).toFloat64(); } else { break; } key = V4Y_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v4y = ossimString(value).toFloat64(); } else { break; } key = V4Z_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v4z = ossimString(value).toFloat64(); } else { break; } key = V5X_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v5x = ossimString(value).toFloat64(); } else { break; } key = V5Y_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v5y = ossimString(value).toFloat64(); } else { break; } key = V5Z_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v5z = ossimString(value).toFloat64(); } else { break; } key = V6X_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v6x = ossimString(value).toFloat64(); } else { break; } key = V6Y_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v6y = ossimString(value).toFloat64(); } else { break; } key = V6Z_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v6z = ossimString(value).toFloat64(); } else { break; } key = V7X_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v7x = ossimString(value).toFloat64(); } else { break; } key = V7Y_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v7y = ossimString(value).toFloat64(); } else { break; } key = V7Z_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v7z = ossimString(value).toFloat64(); } else { break; } key = V8X_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v8x = ossimString(value).toFloat64(); } else { break; } key = V8Y_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v8y = ossimString(value).toFloat64(); } else { break; } key = V8Z_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_v8z = ossimString(value).toFloat64(); } else { break; } key = GRPX_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_grpx = ossimString(value).toFloat64(); } else { break; } key = GRPY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_grpy = ossimString(value).toFloat64(); } else { break; } key = GRPZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_grpz = ossimString(value).toFloat64(); } else { break; } key = FULLR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_fullr = ossimString(value).toFloat64(); } else { break; } key = FULLC_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_fullc = ossimString(value).toFloat64(); } else { break; } key = MINR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_minr = ossimString(value).toFloat64(); } else { break; } key = MAXR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_maxr = ossimString(value).toFloat64(); } else { break; } key = MINC_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_minc = ossimString(value).toFloat64(); } else { break; } key = MAXC_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_maxc = ossimString(value).toFloat64(); } else { break; } key = IE0_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_ie0 = ossimString(value).toFloat64(); } else { break; } key = IER_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_ier = ossimString(value).toFloat64(); } else { break; } key = IEC_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_iec = ossimString(value).toFloat64(); } else { break; } key = IERR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_ierr = ossimString(value).toFloat64(); } else { break; } key = IERC_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_ierc = ossimString(value).toFloat64(); } else { break; } key = IECC_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_iecc = ossimString(value).toFloat64(); } else { break; } key = IA0_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_ia0 = ossimString(value).toFloat64(); } else { break; } key = IAR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_iar = ossimString(value).toFloat64(); } else { break; } key = IAC_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_iac = ossimString(value).toFloat64(); } else { break; } key = IARR_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_iarr = ossimString(value).toFloat64(); } else { break; } key = IARC_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_iarc = ossimString(value).toFloat64(); } else { break; } key = IACC_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_iacc = ossimString(value).toFloat64(); } else { break; } key = SPX_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_spx = ossimString(value).toFloat64(); } else { break; } key = SVX_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_svx = ossimString(value).toFloat64(); } else { break; } key = SAX_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_sax = ossimString(value).toFloat64(); } else { break; } key = SPY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_spy = ossimString(value).toFloat64(); } else { break; } key = SVY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_svy = ossimString(value).toFloat64(); } else { break; } key = SAY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_say = ossimString(value).toFloat64(); } else { break; } key = SPZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_spz = ossimString(value).toFloat64(); } else { break; } key = SVZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_svz = ossimString(value).toFloat64(); } else { break; } key = SAZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_saz = ossimString(value).toFloat64(); } else { break; } // If we get here we're good, so set the status for downstream code. result = true; // Final break from while forever loop. break; } // Matches: while( FOREVER ) if ( result == false ) { // Find on key failed... ossimNotify(ossimNotifyLevel_WARN) << MODULE << " WARNING:\n" << "Error encountered parsing the following required keyword: " << key << "\nCheck the keywordlist for required key:value pairs." << std::endl; } return result; } // End: ossimRsmida::loadState( ... ) bool ossimRsmida::initialize( const ossimNitfRsmidaTag* rsmidaTag ) { bool status = false; if ( rsmidaTag ) { m_iid = rsmidaTag->getIid().trim().string(); m_edition = rsmidaTag->getEdition().trim().string(); m_isid = rsmidaTag->getIsid().trim().string(); m_sid = rsmidaTag->getSid().trim().string(); m_stid = rsmidaTag->getStid().trim().string(); m_year = rsmidaTag->getYear().toUInt32(); m_month = rsmidaTag->getMonth().toUInt32(); m_day = rsmidaTag->getDay().toUInt32(); m_hour = rsmidaTag->getHour().toUInt32(); m_minute = rsmidaTag->getMinute().toUInt32(); m_second = rsmidaTag->getSecond().toFloat64(); m_nrg = rsmidaTag->getNrg().toUInt32(); m_ncg = rsmidaTag->getNcg().toUInt32(); m_trg = rsmidaTag->getTrg().toFloat64(); m_tcg = rsmidaTag->getTcg().toFloat64(); std::string s = rsmidaTag->getGrndd().string(); if ( s.size() ) { m_grndd = s[0]; } else { m_grndd = '\0'; // This should not happen. return false??? (drb) } m_xuor = rsmidaTag->getXuor().toFloat64(); m_yuor = rsmidaTag->getYuor().toFloat64(); m_zuor = rsmidaTag->getZuor().toFloat64(); m_xuxr = rsmidaTag->getXuxr().toFloat64(); m_xuyr = rsmidaTag->getXuyr().toFloat64(); m_xuzr = rsmidaTag->getXuzr().toFloat64(); m_yuxr = rsmidaTag->getYuxr().toFloat64(); m_yuyr = rsmidaTag->getYuyr().toFloat64(); m_yuzr = rsmidaTag->getYuzr().toFloat64(); m_zuxr = rsmidaTag->getZuxr().toFloat64(); m_zuyr = rsmidaTag->getZuyr().toFloat64(); m_zuzr = rsmidaTag->getZuzr().toFloat64(); m_v1x = rsmidaTag->getV1x().toFloat64(); m_v1y = rsmidaTag->getV1y().toFloat64(); m_v1z = rsmidaTag->getV1z().toFloat64(); m_v2x = rsmidaTag->getV2x().toFloat64(); m_v2y = rsmidaTag->getV2y().toFloat64(); m_v2z = rsmidaTag->getV2z().toFloat64(); m_v3x = rsmidaTag->getV3x().toFloat64(); m_v3y = rsmidaTag->getV3y().toFloat64(); m_v3z = rsmidaTag->getV3z().toFloat64(); m_v4x = rsmidaTag->getV4x().toFloat64(); m_v4y = rsmidaTag->getV4y().toFloat64(); m_v4z = rsmidaTag->getV4z().toFloat64(); m_v5x = rsmidaTag->getV5x().toFloat64(); m_v5y = rsmidaTag->getV5y().toFloat64(); m_v5z = rsmidaTag->getV5z().toFloat64(); m_v6x = rsmidaTag->getV6x().toFloat64(); m_v6y = rsmidaTag->getV6y().toFloat64(); m_v6z = rsmidaTag->getV6z().toFloat64(); m_v7x = rsmidaTag->getV7x().toFloat64(); m_v7y = rsmidaTag->getV7y().toFloat64(); m_v7z = rsmidaTag->getV7z().toFloat64(); m_v8x = rsmidaTag->getV8x().toFloat64(); m_v8y = rsmidaTag->getV8y().toFloat64(); m_v8z = rsmidaTag->getV8z().toFloat64(); m_grpx = rsmidaTag->getGrpx().toFloat64(); m_grpy = rsmidaTag->getGrpy().toFloat64(); m_grpz = rsmidaTag->getGrpz().toFloat64(); m_fullr = rsmidaTag->getFullr().toUInt32(); m_fullc = rsmidaTag->getFullc().toUInt32(); m_minr = rsmidaTag->getMinr().toUInt32(); m_maxr = rsmidaTag->getMaxr().toUInt32(); m_minc = rsmidaTag->getMinc().toUInt32(); m_maxc = rsmidaTag->getMaxc().toUInt32(); m_ie0 = rsmidaTag->getIe0().toFloat64(); m_ier = rsmidaTag->getIer().toFloat64(); m_iec = rsmidaTag->getIec().toFloat64(); m_ierr = rsmidaTag->getIerr().toFloat64(); m_ierc = rsmidaTag->getIerc().toFloat64(); m_iecc = rsmidaTag->getIecc().toFloat64(); m_ia0 = rsmidaTag->getIa0().toFloat64(); m_iar = rsmidaTag->getIar().toFloat64(); m_iac = rsmidaTag->getIac().toFloat64(); m_iarr = rsmidaTag->getIarr().toFloat64(); m_iarc = rsmidaTag->getIarc().toFloat64(); m_iacc = rsmidaTag->getIacc().toFloat64(); m_spx = rsmidaTag->getSpx().toFloat64(); m_svx = rsmidaTag->getSvx().toFloat64(); m_sax = rsmidaTag->getSax().toFloat64(); m_spy = rsmidaTag->getSpy().toFloat64(); m_svy = rsmidaTag->getSvy().toFloat64(); m_say = rsmidaTag->getSay().toFloat64(); m_spz = rsmidaTag->getSpz().toFloat64(); m_svz = rsmidaTag->getSvz().toFloat64(); m_saz = rsmidaTag->getSaz().toFloat64(); status = true; } // Matches: if ( rsmidaTag ) return status; } // End: ossimRsmida::initializeModel( rsmidaTag ) ossim-Miami-2.9.1/src/support_data/ossimRsmpca.cpp000066400000000000000000000466631352751253100222320ustar00rootroot00000000000000//--- // File: ossimRsmpca.cpp // // License: MIT // // See LICENSE.txt file in the top level directory for more details. //--- #include #include #include #include static std::string IID_KW = "iid"; static std::string EDITION_KW = "edition"; static std::string RSN_KW = "rsn"; static std::string CSN_KW = "csn"; static std::string RFEP_KW = "rfep"; static std::string CFEP_KW = "cfep"; static std::string RNRMO_KW = "rnrmo"; static std::string CNRMO_KW = "cnrmo"; static std::string XNRMO_KW = "xnrmo"; static std::string YNRMO_KW = "ynrmo"; static std::string ZNRMO_KW = "znrmo"; static std::string RNRMSF_KW = "rnrmsf"; static std::string CNRMSF_KW = "cnrmsf"; static std::string XNRMSF_KW = "xnrmsf"; static std::string YNRMSF_KW = "ynrmsf"; static std::string ZNRMSF_KW = "znrmsf"; static std::string RNPWRX_KW = "rnpwrx"; static std::string RNPWRY_KW = "rnpwry"; static std::string RNPWRZ_KW = "rnpwrz"; static std::string RNTRMS_KW = "rntrms"; static std::string RNPCF_KW = "rnpcf"; static std::string RDPWRX_KW = "rdpwrx"; static std::string RDPWRY_KW = "rdpwry"; static std::string RDPWRZ_KW = "rdpwrz"; static std::string RDTRMS_KW = "rdtrms"; static std::string RDPCF_KW = "rdpcf"; static std::string CNPWRX_KW = "cnpwrx"; static std::string CNPWRY_KW = "cnpwry"; static std::string CNPWRZ_KW = "cnpwrz"; static std::string CNTRMS_KW = "cntrms"; static std::string CNPCF_KW = "cnpcf"; static std::string CDPWRX_KW = "cdpwrx"; static std::string CDPWRY_KW = "cdpwry"; static std::string CDPWRZ_KW = "cdpwrz"; static std::string CDTRMS_KW = "cdtrms"; static std::string CDPCF_KW = "cdpcf"; ossimRsmpca::ossimRsmpca() : m_iid(), m_edition(), m_rsn(0), m_csn(0), m_rfep(0.0), m_cfep(0.0), m_rnrmo(0.0), m_cnrmo(0.0), m_xnrmo(0.0), m_ynrmo(0.0), m_znrmo(0.0), m_rnrmsf(0.0), m_cnrmsf(0.0), m_xnrmsf(0.0), m_ynrmsf(0.0), m_znrmsf(0.0), m_rnpwrx(0), m_rnpwry(0), m_rnpwrz(0), m_rntrms(0), m_rnpcf(), m_rdpwrx(0), m_rdpwry(0), m_rdpwrz(0), m_rdtrms(0), m_rdpcf(), m_cnpwrx(0), m_cnpwry(0), m_cnpwrz(0), m_cntrms(0), m_cnpcf(), m_cdpwrx(0), m_cdpwry(0), m_cdpwrz(0), m_cdtrms(0), m_cdpcf() { } ossimRsmpca::ossimRsmpca( const ossimRsmpca& obj ) : m_iid( obj.m_iid ), m_edition( obj.m_edition ), m_rsn( obj.m_rsn ), m_csn( obj.m_csn ), m_rfep( obj.m_rfep ), m_cfep( obj.m_cfep ), m_rnrmo( obj.m_rnrmo ), m_cnrmo( obj.m_cnrmo ), m_xnrmo( obj.m_xnrmo ), m_ynrmo( obj.m_ynrmo ), m_znrmo( obj.m_znrmo ), m_rnrmsf( obj.m_rnrmsf ), m_cnrmsf( obj.m_cnrmsf ), m_xnrmsf( obj.m_xnrmsf ), m_ynrmsf( obj.m_ynrmsf ), m_znrmsf( obj.m_znrmsf ), m_rnpwrx( obj.m_rnpwrx ), m_rnpwry( obj.m_rnpwry ), m_rnpwrz( obj.m_rnpwrz ), m_rntrms( obj.m_rntrms ), m_rnpcf( obj.m_rnpcf ), m_rdpwrx( obj.m_rdpwrx ), m_rdpwry( obj.m_rdpwry ), m_rdpwrz( obj.m_rdpwrz ), m_rdtrms( obj.m_rdtrms ), m_rdpcf( obj.m_rdpcf ), m_cnpwrx( obj.m_cnpwrx ), m_cnpwry( obj.m_cnpwry ), m_cnpwrz( obj.m_cnpwrz ), m_cntrms( obj.m_cntrms ), m_cnpcf( obj.m_cnpcf ), m_cdpwrx( obj.m_cdpwrx ), m_cdpwry( obj.m_cdpwry ), m_cdpwrz( obj.m_cdpwrz ), m_cdtrms( obj.m_cdtrms ), m_cdpcf( obj.m_cdpcf ) { } const ossimRsmpca& ossimRsmpca::operator=( const ossimRsmpca& rhs ) { if (this != &rhs) { m_iid = rhs.m_iid; m_edition = rhs.m_edition; m_rsn = rhs.m_rsn; m_csn = rhs.m_csn; m_rfep = rhs.m_rfep; m_cfep = rhs.m_cfep; m_rnrmo = rhs.m_rnrmo; m_cnrmo = rhs.m_cnrmo; m_xnrmo = rhs.m_xnrmo; m_ynrmo = rhs.m_ynrmo; m_znrmo = rhs.m_znrmo; m_rnrmsf = rhs.m_rnrmsf; m_cnrmsf = rhs.m_cnrmsf; m_xnrmsf = rhs.m_xnrmsf; m_ynrmsf = rhs.m_ynrmsf; m_znrmsf = rhs.m_znrmsf; m_rnpwrx = rhs.m_rnpwrx; m_rnpwry = rhs.m_rnpwry; m_rnpwrz = rhs.m_rnpwrz; m_rntrms = rhs.m_rntrms; m_rnpcf = rhs.m_rnpcf; m_rdpwrx = rhs.m_rdpwrx; m_rdpwry = rhs.m_rdpwry; m_rdpwrz = rhs.m_rdpwrz; m_rdtrms = rhs.m_rdtrms; m_rdpcf = rhs.m_rdpcf; m_cnpwrx = rhs.m_cnpwrx; m_cnpwry = rhs.m_cnpwry; m_cnpwrz = rhs.m_cnpwrz; m_cntrms = rhs.m_cntrms; m_cnpcf = rhs.m_cnpcf; m_cdpwrx = rhs.m_cdpwrx; m_cdpwry = rhs.m_cdpwry; m_cdpwrz = rhs.m_cdpwrz; m_cdtrms = rhs.m_cdtrms; m_cdpcf = rhs.m_cdpcf; } return *this; } void ossimRsmpca::saveState( ossimKeywordlist& kwl, const std::string& prefix, ossim_uint32 index ) const { std::string pfx = prefix + std::string("rsmpca"); pfx += ossimString::toString( index ).string(); pfx += std::string("."); kwl.add( pfx.c_str(), IID_KW.c_str(), m_iid.c_str() ); kwl.add(pfx.c_str(), EDITION_KW.c_str(), m_edition.c_str()); kwl.add(pfx.c_str(), RSN_KW.c_str(), m_rsn); kwl.add(pfx.c_str(), CSN_KW.c_str(), m_csn); kwl.add(pfx.c_str(), RFEP_KW.c_str(), m_rfep); kwl.add(pfx.c_str(), CFEP_KW.c_str(), m_cfep); kwl.add(pfx.c_str(), RNRMO_KW.c_str(), m_rnrmo); kwl.add(pfx.c_str(), CNRMO_KW.c_str(), m_cnrmo); kwl.add(pfx.c_str(), XNRMO_KW.c_str(), m_xnrmo); kwl.add(pfx.c_str(), YNRMO_KW.c_str(), m_ynrmo); kwl.add(pfx.c_str(), ZNRMO_KW.c_str(), m_znrmo); kwl.add(pfx.c_str(), RNRMSF_KW.c_str(), m_rnrmsf); kwl.add(pfx.c_str(), CNRMSF_KW.c_str(), m_cnrmsf); kwl.add(pfx.c_str(), XNRMSF_KW.c_str(), m_xnrmsf); kwl.add(pfx.c_str(), YNRMSF_KW.c_str(), m_ynrmsf); kwl.add(pfx.c_str(), ZNRMSF_KW.c_str(), m_znrmsf); kwl.add(pfx.c_str(), RNPWRX_KW.c_str(), m_rnpwrx); kwl.add(pfx.c_str(), RNPWRY_KW.c_str(), m_rnpwry); kwl.add(pfx.c_str(), RNPWRZ_KW.c_str(), m_rnpwrz); kwl.add(pfx.c_str(), RNTRMS_KW.c_str(), m_rntrms); for (ossim_uint32 i=0; i. Check the keywordlist for proper syntax." << std::endl; } return result; } // End: ossimRsmpca::loadState( ... ) bool ossimRsmpca::initialize( const ossimNitfRsmpcaTag* rsmpcaTag ) { bool status = false; if ( rsmpcaTag ) { m_iid = rsmpcaTag->getIid().trim().string(); m_edition = rsmpcaTag->getEdition().trim().string(); m_rsn = rsmpcaTag->getRsn().toUInt32(); m_csn = rsmpcaTag->getCsn().toUInt32(); m_rfep = rsmpcaTag->getRfep().toFloat64(); m_cfep = rsmpcaTag->getCfep().toFloat64(); m_rnrmo = rsmpcaTag->getRnrmo().toFloat64(); m_cnrmo = rsmpcaTag->getCnrmo().toFloat64(); m_xnrmo = rsmpcaTag->getXnrmo().toFloat64(); m_ynrmo = rsmpcaTag->getYnrmo().toFloat64(); m_znrmo = rsmpcaTag->getZnrmo().toFloat64(); m_rnrmsf = rsmpcaTag->getRnrmsf().toFloat64(); m_cnrmsf = rsmpcaTag->getCnrmsf().toFloat64(); m_xnrmsf = rsmpcaTag->getXnrmsf().toFloat64(); m_ynrmsf = rsmpcaTag->getYnrmsf().toFloat64(); m_znrmsf = rsmpcaTag->getZnrmsf().toFloat64(); m_rnpwrx = rsmpcaTag->getRnpwrx().toUInt32(); m_rnpwry = rsmpcaTag->getRnpwry().toUInt32(); m_rnpwrz = rsmpcaTag->getRnpwrz().toUInt32(); m_rntrms = rsmpcaTag->getRntrms().toUInt32(); m_rnpcf.resize(m_rntrms); for (ossim_uint32 i = 0; i < m_rntrms; ++i) { m_rnpcf[i] = rsmpcaTag->getRnpcf(i).toFloat64(); } m_rdpwrx = rsmpcaTag->getRdpwrx().toUInt32(); m_rdpwry = rsmpcaTag->getRdpwry().toUInt32(); m_rdpwrz = rsmpcaTag->getRdpwrz().toUInt32(); m_rdtrms = rsmpcaTag->getRdtrms().toUInt32(); m_rdpcf.resize(m_rdtrms); for (ossim_uint32 i = 0; i < m_rdtrms; ++i) { m_rdpcf[i] = rsmpcaTag->getRdpcf(i).toFloat64(); } m_cnpwrx = rsmpcaTag->getCnpwrx().toUInt32(); m_cnpwry = rsmpcaTag->getCnpwry().toUInt32(); m_cnpwrz = rsmpcaTag->getCnpwrz().toUInt32(); m_cntrms = rsmpcaTag->getCntrms().toUInt32(); m_cnpcf.resize(m_cntrms); for (ossim_uint32 i = 0; i < m_cntrms; ++i) { m_cnpcf[i] = rsmpcaTag->getCnpcf(i).toFloat64(); } m_cdpwrx = rsmpcaTag->getCdpwrx().toUInt32(); m_cdpwry = rsmpcaTag->getCdpwry().toUInt32(); m_cdpwrz = rsmpcaTag->getCdpwrz().toUInt32(); m_cdtrms = rsmpcaTag->getCdtrms().toUInt32(); m_cdpcf.resize(m_cdtrms); for (ossim_uint32 i = 0; i < m_cdtrms; ++i) { m_cdpcf[i] = rsmpcaTag->getCdpcf(i).toFloat64(); } status = true; } // Matches: if ( rsmpcaTag ) return status; } // End: ossimRsmpca::initializeModel( rsmpcaTag ) ossim-Miami-2.9.1/src/support_data/ossimRsmpia.cpp000066400000000000000000000304401352751253100222220ustar00rootroot00000000000000//--- // File: ossimRsmpia.cpp // // License: MIT // // See LICENSE.txt file in the top level directory for more details. //--- #include #include #include #include static std::string IID_KW = "iid"; static std::string EDITION_KW = "edition"; static std::string R0_KW = "r0"; static std::string RX_KW = "rx"; static std::string RY_KW = "ry"; static std::string RZ_KW = "rz"; static std::string RXX_KW = "rxx"; static std::string RXY_KW = "rxy"; static std::string RXZ_KW = "rxz"; static std::string RYY_KW = "ryy"; static std::string RYZ_KW = "ryz"; static std::string RZZ_KW = "rzz"; static std::string C0_KW = "c0"; static std::string CX_KW = "cx"; static std::string CY_KW = "cy"; static std::string CZ_KW = "cz"; static std::string CXX_KW = "cxx"; static std::string CXY_KW = "cxy"; static std::string CXZ_KW = "cxz"; static std::string CYY_KW = "cyy"; static std::string CYZ_KW = "cyz"; static std::string CZZ_KW = "czz"; static std::string RNIS_KW = "rnis"; static std::string CNIS_KW = "cnis"; static std::string TNIS_KW = "tnis"; static std::string RSSIZ_KW = "rssiz"; static std::string CSSIZ_KW = "cssiz"; ossimRsmpia::ossimRsmpia() : m_iid(), m_edition(), m_r0(0.0), m_rx(0.0), m_ry(0.0), m_rz(0.0), m_rxx(0.0), m_rxy(0.0), m_rxz(0.0), m_ryy(0.0), m_ryz(0.0), m_rzz(0.0), m_c0(0.0), m_cx(0.0), m_cy(0.0), m_cz(0.0), m_cxx(0.0), m_cxy(0.0), m_cxz(0.0), m_cyy(0.0), m_cyz(0.0), m_czz(0.0), m_rnis(0), m_cnis(0), m_tnis(0), m_rssiz(0.0), m_cssiz(0.0) { } ossimRsmpia::ossimRsmpia( const ossimRsmpia& obj ) : m_iid( obj.m_iid ), m_edition( obj.m_edition ), m_r0( obj.m_r0 ), m_rx( obj.m_rx ), m_ry( obj.m_ry ), m_rz( obj.m_rz ), m_rxx( obj.m_rxx ), m_rxy( obj.m_rxy ), m_rxz( obj.m_rxz ), m_ryy( obj.m_ryy ), m_ryz( obj.m_ryz ), m_rzz( obj.m_rzz ), m_c0( obj.m_c0 ), m_cx( obj.m_cx ), m_cy( obj.m_cy ), m_cz( obj.m_cz ), m_cxx( obj.m_cxx ), m_cxy( obj.m_cxy ), m_cxz( obj.m_cxz ), m_cyy( obj.m_cyy ), m_cyz( obj.m_cyz ), m_czz( obj.m_czz ), m_rnis( obj.m_rnis ), m_cnis( obj.m_cnis ), m_tnis( obj.m_tnis ), m_rssiz( obj.m_rssiz ), m_cssiz( obj.m_cssiz ) { } const ossimRsmpia& ossimRsmpia::operator=( const ossimRsmpia& rhs ) { if (this != &rhs) { m_iid = rhs.m_iid; m_edition = rhs.m_edition; m_r0 = rhs.m_r0; m_rx = rhs.m_rx; m_ry = rhs.m_ry; m_rz = rhs.m_rz; m_rxx = rhs.m_rxx; m_rxy = rhs.m_rxy; m_rxz = rhs.m_rxz; m_ryy = rhs.m_ryy; m_ryz = rhs.m_ryz; m_rzz = rhs.m_rzz; m_c0 = rhs.m_c0; m_cx = rhs.m_cx; m_cy = rhs.m_cy; m_cz = rhs.m_cz; m_cxx = rhs.m_cxx; m_cxy = rhs.m_cxy; m_cxz = rhs.m_cxz; m_cyy = rhs.m_cyy; m_cyz = rhs.m_cyz; m_czz = rhs.m_czz; m_rnis = rhs.m_rnis; m_cnis = rhs.m_cnis; m_tnis = rhs.m_tnis; m_rssiz = rhs.m_rssiz; m_cssiz = rhs.m_cssiz; } return *this; } void ossimRsmpia::saveState( ossimKeywordlist& kwl, const std::string& prefix ) const { std::string pfx = prefix + std::string("rsmpia."); kwl.add(pfx.c_str(), IID_KW.c_str(), m_iid.c_str()); kwl.add(pfx.c_str(), EDITION_KW.c_str(), m_edition.c_str()); kwl.add(pfx.c_str(), R0_KW.c_str(), m_r0); kwl.add(pfx.c_str(), RX_KW.c_str(), m_rx); kwl.add(pfx.c_str(), RY_KW.c_str(), m_ry); kwl.add(pfx.c_str(), RZ_KW.c_str(), m_rz); kwl.add(pfx.c_str(), RXX_KW.c_str(), m_rxx); kwl.add(pfx.c_str(), RXY_KW.c_str(), m_rxy); kwl.add(pfx.c_str(), RXZ_KW.c_str(), m_rxz); kwl.add(pfx.c_str(), RYY_KW.c_str(), m_ryy); kwl.add(pfx.c_str(), RYZ_KW.c_str(), m_ryz); kwl.add(pfx.c_str(), RZZ_KW.c_str(), m_rzz); kwl.add(pfx.c_str(), C0_KW.c_str(), m_c0); kwl.add(pfx.c_str(), CX_KW.c_str(), m_cx); kwl.add(pfx.c_str(), CY_KW.c_str(), m_cy); kwl.add(pfx.c_str(), CZ_KW.c_str(), m_cz); kwl.add(pfx.c_str(), CXX_KW.c_str(), m_cxx); kwl.add(pfx.c_str(), CXY_KW.c_str(), m_cxy); kwl.add(pfx.c_str(), CXZ_KW.c_str(), m_cxz); kwl.add(pfx.c_str(), CYY_KW.c_str(), m_cyy); kwl.add(pfx.c_str(), CYZ_KW.c_str(), m_cyz); kwl.add(pfx.c_str(), CZZ_KW.c_str(), m_czz); kwl.add(pfx.c_str(), RNIS_KW.c_str(), m_rnis); kwl.add(pfx.c_str(), CNIS_KW.c_str(), m_cnis); kwl.add(pfx.c_str(), TNIS_KW.c_str(), m_tnis); kwl.add(pfx.c_str(), RSSIZ_KW.c_str(), m_rssiz); kwl.add(pfx.c_str(), CSSIZ_KW.c_str(), m_cssiz); } // End: ossimRsmpia::saveState( ... ) bool ossimRsmpia::loadState( const ossimKeywordlist& kwl, const std::string& prefix ) { std::string pfx = prefix + std::string("rsmpia."); std::string key; std::string value; bool result = false; // Set to true on last key. while( 1 ) // Break out on error. { key = IID_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_iid = value; } else { break; } key = EDITION_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_edition = value; } else { break; } key = R0_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_r0 = ossimString(value).toFloat64(); } else { break; } key = RX_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_rx = ossimString(value).toFloat64(); } else { break; } key = RY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_ry = ossimString(value).toFloat64(); } else { break; } key = RZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_rz = ossimString(value).toFloat64(); } else { break; } key = RXX_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_rxx = ossimString(value).toFloat64(); } else { break; } key = RXY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_rxy = ossimString(value).toFloat64(); } else { break; } key = RXZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_rxz = ossimString(value).toFloat64(); } else { break; } key = RYY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_ryy = ossimString(value).toFloat64(); } else { break; } key = RYZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_ryz = ossimString(value).toFloat64(); } else { break; } key = RZZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_rzz = ossimString(value).toFloat64(); } else { break; } key = C0_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_c0 = ossimString(value).toFloat64(); } else { break; } key = CX_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cx = ossimString(value).toFloat64(); } else { break; } key = CY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cy = ossimString(value).toFloat64(); } else { break; } key = CZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cz = ossimString(value).toFloat64(); } else { break; } key = CXX_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cxx = ossimString(value).toFloat64(); } else { break; } key = CXY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cxy = ossimString(value).toFloat64(); } else { break; } key = CXZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cxz = ossimString(value).toFloat64(); } else { break; } key = CYY_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cyy = ossimString(value).toFloat64(); } else { break; } key = CYZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cyz = ossimString(value).toFloat64(); } else { break; } key = CZZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_czz = ossimString(value).toFloat64(); } else { break; } key = RNIS_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_rnis = ossimString(value).toUInt32(); } else { break; } key = CNIS_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cnis = ossimString(value).toUInt32(); } else { break; } key = TNIS_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_tnis = ossimString(value).toUInt32(); } else { break; } key = RSSIZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_rssiz = ossimString(value).toUInt32(); } else { break; } key = CSSIZ_KW; value = kwl.findKey( pfx, key ); if ( value.size() ) { m_cssiz = ossimString(value).toUInt32(); } else { break; } // If we get here we're good, so set the status for downstream code. result = true; // Final break from while forever loop. break; } // Matches: while( FOREVER ) if ( result == false ) { // Find on key failed... ossimNotify(ossimNotifyLevel_WARN) << "ossimRsmpia::loadState WARNING:\n" << "Error encountered parsing the following required keyword: " << "<" << key << ">. Check the keywordlist for proper syntax." << std::endl; } return result; } // End: ossimRsmpia::loadState( ... ) bool ossimRsmpia::initialize( const ossimNitfRsmpiaTag* rsmpiaTag ) { bool status = false; if ( rsmpiaTag ) { m_iid = rsmpiaTag->getIid().trim().string(); m_edition = rsmpiaTag->getEdition().trim().string(); m_r0 = rsmpiaTag->getR0().toFloat64(); m_rx = rsmpiaTag->getRx().toFloat64(); m_ry = rsmpiaTag->getRy().toFloat64(); m_rz = rsmpiaTag->getRz().toFloat64(); m_rxx = rsmpiaTag->getRxx().toFloat64(); m_rxy = rsmpiaTag->getRxy().toFloat64(); m_rxz = rsmpiaTag->getRxz().toFloat64(); m_ryy = rsmpiaTag->getRyy().toFloat64(); m_ryz = rsmpiaTag->getRyz().toFloat64(); m_rzz = rsmpiaTag->getRzz().toFloat64(); m_c0 = rsmpiaTag->getC0().toFloat64(); m_cx = rsmpiaTag->getCx().toFloat64(); m_cy = rsmpiaTag->getCy().toFloat64(); m_cz = rsmpiaTag->getCz().toFloat64(); m_cxx = rsmpiaTag->getCxx().toFloat64(); m_cxy = rsmpiaTag->getCxy().toFloat64(); m_cxz = rsmpiaTag->getCxz().toFloat64(); m_cyy = rsmpiaTag->getCyy().toFloat64(); m_cyz = rsmpiaTag->getCyz().toFloat64(); m_czz = rsmpiaTag->getCzz().toFloat64(); m_rnis = rsmpiaTag->getRnis().toUInt32(); m_cnis = rsmpiaTag->getCnis().toUInt32(); m_tnis = rsmpiaTag->getTnis().toUInt32(); m_rssiz = rsmpiaTag->getRssiz().toFloat64(); m_cssiz = rsmpiaTag->getCssiz().toFloat64(); status = true; } // Matches: if ( rsmpiaTag ) return status; } // End: ossimRsmpia::initializeModel( rsmpiaTag ) ossim-Miami-2.9.1/src/support_data/ossimSpaceImagingGeom.cpp000066400000000000000000000202321352751253100241240ustar00rootroot00000000000000//******************************************************************* // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This class extends the stl's string class. // //******************************************************************** // $Id: ossimSpaceImagingGeom.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include #include #include using namespace std; const char* ossimSpaceImagingGeom::SIG_PRODUCER_KW = "Producer"; const char* ossimSpaceImagingGeom::SIG_PROJECT_NAME_KW = "Project Name"; const char* ossimSpaceImagingGeom::SIG_FILENAME_KW = "Filename"; const char* ossimSpaceImagingGeom::SIG_BAND_KW = "Band"; const char* ossimSpaceImagingGeom::SIG_BITS_PER_PIXEL_KW = "Bits/Pixel"; const char* ossimSpaceImagingGeom::SIG_NUMBER_OF_BANDS_KW = "Number of Bands"; const char* ossimSpaceImagingGeom::SIG_DATUM_KW = "Datum"; const char* ossimSpaceImagingGeom::SIG_PROJECTION_KW = "Projection"; const char* ossimSpaceImagingGeom::SIG_SELECTED_PROJECTION_KW = "Selected Projection"; const char* ossimSpaceImagingGeom::SIG_ZONE_KW = "Zone"; const char* ossimSpaceImagingGeom::SIG_UL_EASTING_KW = "UL Map X (Easting)"; const char* ossimSpaceImagingGeom::SIG_UL_NORTHING_KW = "UL Map Y (Northing)"; const char* ossimSpaceImagingGeom::SIG_PIXEL_SIZE_X_KW = "Pixel Size X"; const char* ossimSpaceImagingGeom::SIG_PIXEL_SIZE_Y_KW = "Pixel Size Y"; const char* ossimSpaceImagingGeom::SIG_COLUMNS_KW = "Columns"; const char* ossimSpaceImagingGeom::SIG_ROWS_KW = "Rows"; ossimSpaceImagingGeom::ossimSpaceImagingGeom() { } ossimSpaceImagingGeom::ossimSpaceImagingGeom(const ossimFilename& file, const char* prefix) { setGeometry(file); thePrefix = prefix; } void ossimSpaceImagingGeom::setGeometry(const ossimFilename& file) { theSpaceImagingGeometry.clear(); theSpaceImagingGeometry.addFile(file.c_str()); } void ossimSpaceImagingGeom::setGeometry(const ossimKeywordlist& kwl) { theSpaceImagingGeometry.clear(); theSpaceImagingGeometry = kwl; } void ossimSpaceImagingGeom::exportToOssim(ossimKeywordlist& kwl, const char* prefix)const { const ossimKeywordlist::KeywordMap& geomMap = theSpaceImagingGeometry.getMap(); ossimKeywordlist::KeywordMap::const_iterator node = geomMap.begin(); while(node != geomMap.end()) { ossimString keyword = spaceImagingToOssimKeyword((*node).first); ossimString value = spaceImagingToOssimValue((*node).first, (*node).second); if(keyword != "") { kwl.add(prefix, keyword.c_str(), value.c_str(), true); } ++node; } } ossimString ossimSpaceImagingGeom::spaceImagingToOssimKeyword(const ossimString& spaceImagingKeyword)const { if(spaceImagingKeyword == SIG_NUMBER_OF_BANDS_KW) { return ossimString (ossimKeywordNames::NUMBER_BANDS_KW); } else if(spaceImagingKeyword == SIG_DATUM_KW) { return ossimString(ossimKeywordNames::DATUM_KW); } else if((spaceImagingKeyword == SIG_PROJECTION_KW)|| (spaceImagingKeyword == SIG_SELECTED_PROJECTION_KW)) { return ossimString(ossimKeywordNames::TYPE_KW); } else if(spaceImagingKeyword == SIG_ZONE_KW) { return ossimString(ossimKeywordNames::ZONE_KW); } else if(spaceImagingKeyword == SIG_UL_EASTING_KW) { return ossimString(ossimKeywordNames::TIE_POINT_EASTING_KW); } else if(spaceImagingKeyword == SIG_UL_NORTHING_KW) { return ossimString(ossimKeywordNames::TIE_POINT_NORTHING_KW); } else if(spaceImagingKeyword == SIG_PIXEL_SIZE_X_KW) { return ossimString(ossimKeywordNames::METERS_PER_PIXEL_X_KW); } else if(spaceImagingKeyword == SIG_PIXEL_SIZE_Y_KW) { return ossimString(ossimKeywordNames::METERS_PER_PIXEL_Y_KW); } else if(spaceImagingKeyword == SIG_COLUMNS_KW) { return ossimString(ossimKeywordNames::NUMBER_SAMPLES_KW); } else if(spaceImagingKeyword == SIG_ROWS_KW) { return ossimString(ossimKeywordNames::NUMBER_LINES_KW); } return ossimString(""); } ossimString ossimSpaceImagingGeom::spaceImagingToOssimValue( const ossimString& spaceImagingKeyword, const ossimString& /* spaceImagingValue */)const { const char* value = theSpaceImagingGeometry.find(thePrefix.c_str(), spaceImagingKeyword.c_str()); if(!value) return ossimString(""); if(spaceImagingKeyword == SIG_DATUM_KW) { // better to have a lut for this. For now I'll put it // here. As the list gets larger let's move it to a // lut then. ossimString datum = value; datum = datum.trim().upcase(); if( datum == "WGS84") { return ossimString("WGE"); } } else if((spaceImagingKeyword == SIG_PROJECTION_KW)|| (spaceImagingKeyword == SIG_SELECTED_PROJECTION_KW)) { ossimString proj = value; proj = proj.trim().upcase(); if(proj == "UNIVERSAL TRANSVERSE MERCATOR") { return ossimString("ossimUtmProjection"); } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimSpaceImagingGeom::spaceImagingToOssimValue: Projection " << value << " doesn't have a converter yet!" << endl << "Please add it" << endl; } } else if(spaceImagingKeyword == SIG_UL_EASTING_KW) { ossimString easting = value; easting = easting.trim(); ostringstream os; os << easting; ossimString eastingValue; ossimString eastingUnits; istringstream is(os.str()); is >> eastingValue >> eastingUnits; eastingUnits = eastingUnits.trim().upcase(); if(eastingUnits!= "METERS") { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimSpaceImagingGeom::spaceImagingToOssimValue: units " << eastingUnits << " not supported yet!" << endl; } return eastingValue; } else if(spaceImagingKeyword == SIG_UL_NORTHING_KW) { ossimString northing = value; northing = northing.trim(); ostringstream os; os << northing; ossimString northingValue; ossimString northingUnits; istringstream is(os.str()); is >> northingValue >> northingUnits; northingUnits = northingUnits.trim().upcase(); if(northingUnits!= "METERS") { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimSpaceImagingGeom::spaceImagingToOssimValue: units " << northingUnits << " not supported yet!" << endl; } return northingValue; } else if(spaceImagingKeyword == SIG_PIXEL_SIZE_X_KW) { ossimString gsd = value; gsd = gsd.trim(); ostringstream os; os << gsd; ossimString gsdValue; ossimString gsdUnits; istringstream is(os.str()); is >> gsdValue >> gsdUnits; gsdUnits = gsdUnits.trim().upcase(); if(gsdUnits!= "METERS") { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimSpaceImagingGeom::spaceImagingToOssimValue: units " << gsdUnits << " not supported yet!" << endl; } return gsdValue; } else if(spaceImagingKeyword == SIG_PIXEL_SIZE_Y_KW) { ossimString gsd = value; gsd = gsd.trim(); ostringstream os; os << gsd; ossimString gsdValue; ossimString gsdUnits; istringstream is(os.str()); is >> gsdValue >> gsdUnits; gsdUnits = gsdUnits.trim().upcase(); if(gsdUnits!= "METERS") { ossimNotify(ossimNotifyLevel_WARN) << "WARNING ossimSpaceImagingGeom::spaceImagingToOssimValue: units " << gsdUnits << " not supported yet!" << endl; } return gsdValue; } return ossimString(value); } ossimString ossimSpaceImagingGeom::getBandName()const { return theSpaceImagingGeometry.find(SIG_BAND_KW); } ossimFilename ossimSpaceImagingGeom::getFilename()const { return theSpaceImagingGeometry.find(SIG_FILENAME_KW); } ossimString ossimSpaceImagingGeom::getProducer()const { return theSpaceImagingGeometry.find(SIG_PRODUCER_KW); } ossim-Miami-2.9.1/src/support_data/ossimSpotDimapSupportData.cpp000066400000000000000000002326451352751253100250710ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer (ossim port by D. Burken) // // Description: // // Contains definition of class ossimSpotDimapSupportData. // //***************************************************************************** // $Id: ossimSpotDimapSupportData.cpp 20609 2012-02-27 12:05:13Z gpotts $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; // Define Trace flags for use within this file: static ossimTrace traceDebug ("ossimSpotDimapSupportData:debug"); static const ossim_uint32 LAGRANGE_FILTER_SIZE = 8; // num samples considered ossimSpotDimapSupportData::ossimSpotDimapSupportData () : ossimErrorStatusInterface(), theMetadataVersion(OSSIM_SPOT_METADATA_VERSION_UNKNOWN), theImageID(), theMetadataFile(), theProductionDate(), theInstrument(), theInstrumentIndex(0), theSunAzimuth(0.0), theSunElevation(0.0), theIncidenceAngle(0.0), theViewingAngle(0.0), theSceneOrientation(0.0), theImageSize(0.0, 0.0), theRefGroundPoint(0.0, 0.0, 0.0), theRefImagePoint(0.0, 0.0), theSubImageOffset(0.0, 0.0), theRefLineTime(0.0), theRefLineTimeLine(0.0), theLineSamplingPeriod(0.0), theDetectorCount(0), thePixelLookAngleX(), thePixelLookAngleY(), theAttitudeSamples(), theAttSampTimes(), thePosEcfSamples(), theVelEcfSamples(), theEphSampTimes(), theStarTrackerUsed(false), theSwirDataFlag(false), theNumBands(0), theAcquisitionDate(), theStepCount(0), theUlCorner(), theUrCorner(), theLrCorner(), theLlCorner(), theGeoPosImagePoints(), theGeoPosGroundPoints() { } ossimSpotDimapSupportData::ossimSpotDimapSupportData(const ossimSpotDimapSupportData& rhs) :ossimErrorStatusInterface(rhs), theMetadataVersion(rhs.theMetadataVersion), theImageID(rhs.theImageID), theMetadataFile (rhs.theMetadataFile), theProductionDate(rhs.theProductionDate), theInstrument(rhs.theInstrument), theInstrumentIndex(rhs.theInstrumentIndex), theSunAzimuth(rhs.theSunAzimuth), theSunElevation(rhs.theSunElevation), theIncidenceAngle(rhs.theIncidenceAngle), theViewingAngle(rhs.theViewingAngle), theSceneOrientation(rhs.theSceneOrientation), theImageSize(rhs.theImageSize), theRefGroundPoint(rhs.theRefGroundPoint), theRefImagePoint(rhs.theRefImagePoint), theSubImageOffset(rhs.theSubImageOffset), theRefLineTime(rhs.theRefLineTime), theRefLineTimeLine(rhs.theRefLineTimeLine), theLineSamplingPeriod(rhs.theLineSamplingPeriod), theDetectorCount(rhs.theDetectorCount), thePixelLookAngleX(rhs.thePixelLookAngleX), thePixelLookAngleY(rhs.thePixelLookAngleY), theAttitudeSamples(rhs.theAttitudeSamples), theAttSampTimes(rhs.theAttSampTimes), thePosEcfSamples(rhs.thePosEcfSamples), theVelEcfSamples(rhs.theVelEcfSamples), theEphSampTimes(rhs.theEphSampTimes), theStarTrackerUsed(rhs.theStarTrackerUsed), theSwirDataFlag (rhs.theSwirDataFlag), theNumBands(rhs.theNumBands), theAcquisitionDate(rhs.theAcquisitionDate), theStepCount(rhs.theStepCount), theUlCorner(rhs.theUlCorner), theUrCorner(rhs.theUrCorner), theLrCorner(rhs.theLrCorner), theLlCorner(rhs.theLlCorner), theGeoPosImagePoints(rhs.theGeoPosImagePoints), theGeoPosGroundPoints(rhs.theGeoPosGroundPoints) { } ossimSpotDimapSupportData::ossimSpotDimapSupportData (const ossimFilename& dimapFile, bool processSwir) : ossimErrorStatusInterface(), theMetadataVersion(OSSIM_SPOT_METADATA_VERSION_UNKNOWN), theImageID(), theMetadataFile (dimapFile), theProductionDate(), theInstrument(), theInstrumentIndex(0), theSunAzimuth(0.0), theSunElevation(0.0), theIncidenceAngle(0.0), theViewingAngle(0.0), theSceneOrientation(0.0), theImageSize(0.0, 0.0), theRefGroundPoint(0.0, 0.0, 0.0), theRefImagePoint(0.0, 0.0), theSubImageOffset(0.0, 0.0), theRefLineTime(0.0), theRefLineTimeLine(0.0), theLineSamplingPeriod(0.0), theDetectorCount(0), thePixelLookAngleX(), thePixelLookAngleY(), theAttitudeSamples(), theAttSampTimes(), thePosEcfSamples(), theVelEcfSamples(), theEphSampTimes(), theStarTrackerUsed(false), theSwirDataFlag (processSwir), theNumBands(0), theAcquisitionDate(), theStepCount(0), theUlCorner(), theUrCorner(), theLrCorner(), theLlCorner(), theGeoPosImagePoints(), theGeoPosGroundPoints() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSpotDimapSupportData::ossimSpotDimapSupportData: entering..." << std::endl; } loadXmlFile(dimapFile, processSwir); // Finished successful parse: if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSpotDimapSupportData::ossimSpotDimapSupportData: leaving..." << std::endl; } } ossimSpotDimapSupportData::~ossimSpotDimapSupportData () { } ossimObject* ossimSpotDimapSupportData::dup()const { return new ossimSpotDimapSupportData(*this); } void ossimSpotDimapSupportData::clearFields() { clearErrorStatus(); //theSensorID="Spot 5"; theSensorID=""; theMetadataVersion = OSSIM_SPOT_METADATA_VERSION_UNKNOWN; theImageID = ""; theMetadataFile = ""; theProductionDate = ""; theInstrument = ""; theInstrumentIndex = 0; theSunAzimuth = 0.0; theSunElevation = 0.0; theIncidenceAngle = 0.0; theViewingAngle = 0.0; theSceneOrientation = 0.0; theImageSize.makeNan(); theRefGroundPoint.makeNan(); theRefImagePoint.makeNan(); theSubImageOffset.makeNan(); theRefLineTime = ossim::nan(); theRefLineTimeLine = ossim::nan(); theLineSamplingPeriod = ossim::nan(); theDetectorCount = 0; thePixelLookAngleX.clear(); thePixelLookAngleY.clear(); theAttitudeSamples.clear(); // x=pitch, y=roll, z=yaw theAttSampTimes.clear(); thePosEcfSamples.clear(); theVelEcfSamples.clear(); theEphSampTimes.clear(); theStarTrackerUsed = false; theSwirDataFlag = false; theNumBands = 0; theAcquisitionDate = ""; theStepCount = 0; //--- // Corner points: //--- theUlCorner.makeNan(); theUrCorner.makeNan(); theLrCorner.makeNan(); theLlCorner.makeNan(); //--- // Geoposition Points: //--- theGeoPosImagePoints.clear(); theGeoPosGroundPoints.clear(); } bool ossimSpotDimapSupportData::loadXmlFile(const ossimFilename& file, bool processSwir) { static const char MODULE[] = "ossimSpotDimapSupportData::loadXmlFile"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nFile: " << file << std::endl; } clearFields(); theSwirDataFlag = processSwir; theMetadataFile = file; ossim_int64 fileSize = file.fileSize(); std::ifstream in(file.c_str(), std::ios::binary|std::ios::in); std::vector fullBuffer; ossimString bufferedIo; if(in.good()&&(fileSize > 0)) { char buf[100]; fullBuffer.resize(fileSize); in.read(buf, ossim::min((ossim_int64)100, fileSize)); if(!in.fail()) { ossimString testString = ossimString(buf, buf + in.gcount()); if(testString.contains("xml")) { in.seekg(0); in.read(&fullBuffer.front(), (std::streamsize)fullBuffer.size()); if(!in.fail()) { bufferedIo = ossimString(fullBuffer.begin(), fullBuffer.begin()+in.gcount()); } } } } else { return false; } //--- // Instantiate the XML parser: //--- ossimRefPtr xmlDocument; if(bufferedIo.empty()) { xmlDocument = new ossimXmlDocument(file); } else { xmlDocument = new ossimXmlDocument; std::istringstream inStringStream(bufferedIo.string()); if(!xmlDocument->read(inStringStream)) { return false; } } if (xmlDocument->getErrorStatus()) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " DEBUG:" << "ossimSpotDimapSupportData::loadXmlFile:" << "\nUnable to parse xml file" << std::endl; } setErrorStatus(); return false; } //--- // Check that it is a SPOT DIMAP file format //--- vector > xml_nodes; xml_nodes.clear(); ossimString xpath = "/Dimap_Document/Dataset_Sources/Source_Information/Scene_Source/MISSION"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\n Not a SPOT DIMAP file format."<< std::endl; } return false; } if ( xml_nodes[0]->getText() != "SPOT" && xml_nodes[0]->getText() != "Spot" && xml_nodes[0]->getText() != "spot" ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\n Not a SPOT DIMAP file format."<< std::endl; } return false; } //--- // Get the version string. This must be performed first as it is used // as a key for parsing different versions. //--- if (initMetadataVersion(xmlDocument) == false) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " DEBUG:" << "ossimSpotDimapSupportData::loadXmlFile:" << "\nMetadata initialization failed. Returning false" << std::endl; } return false; } // Get the image id. if (initImageId(xmlDocument) == false) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " DEBUG:" << "ossimSpotDimapSupportData::loadXmlFile:" << "\nImageId initialization failed. Returning false" << std::endl; } return false; } // Get data from "Scene_Source" section. if (initSceneSource(xmlDocument) == false) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " DEBUG:" << "ossimSpotDimapSupportData::loadXmlFile:" << "\nScene source initialization failed. Returning false" << std::endl; return false; } if (initFramePoints(xmlDocument) == false) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " DEBUG:" << "ossimSpotDimapSupportData::loadXmlFile:" << "\nFrame point initialization failed. Returning false" << std::endl; return false; } if (parsePart1(xmlDocument) == false) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " DEBUG:" << "ossimSpotDimapSupportData::loadXmlFile:" << "\nPart 1 initialization failed. Returning false" << std::endl; return false; } if (parsePart2(xmlDocument) == false) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " DEBUG:" << "ossimSpotDimapSupportData::loadXmlFile:" << "\nPart 2 initialization failed. Returning false" << std::endl; return false; } if (parsePart3(xmlDocument) == false) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " DEBUG:" << "ossimSpotDimapSupportData::loadXmlFile:" << "\nPart 3 initialization failed. Returning false" << std::endl; return false; } if (parsePart4(xmlDocument) == false) { ossimNotify(ossimNotifyLevel_FATAL) << MODULE << " DEBUG:" << "ossimSpotDimapSupportData::loadXmlFile:" << "\nPart 4 initialization failed. Returning false" << std::endl; return false; } if (traceDebug()) { printInfo(ossimNotify(ossimNotifyLevel_DEBUG)); ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG: exited..." << std::endl; } return true; } void ossimSpotDimapSupportData::getPositionEcf(ossim_uint32 sample, ossimEcefPoint& pe) const { pe.makeNan(); if (thePosEcfSamples.size() < theDetectorCount) { if(theImageSize.samp > 0) { double t = 0.0; double tempIdx = 0.0; double tempIdxFraction = 0.0; t = static_cast(sample)/ static_cast(theDetectorCount-1); tempIdx = (thePosEcfSamples.size()-1)*t; tempIdxFraction = tempIdx - (ossim_int32)tempIdx; ossim_uint32 idxStart = (ossim_uint32)tempIdx; ossim_uint32 idxEnd = (ossim_uint32)ceil(tempIdx); if(idxEnd >= thePosEcfSamples.size()) { idxEnd = (ossim_uint32)thePosEcfSamples.size()-1; } if(idxStart > idxEnd) { idxStart = idxEnd; } pe = ossimEcefPoint(thePosEcfSamples[idxStart].x +tempIdxFraction*( thePosEcfSamples[idxEnd].x - thePosEcfSamples[idxStart].x), thePosEcfSamples[idxStart].y +tempIdxFraction*( thePosEcfSamples[idxEnd].y - thePosEcfSamples[idxStart].y), thePosEcfSamples[idxStart].z +tempIdxFraction*( thePosEcfSamples[idxEnd].z - thePosEcfSamples[idxStart].z)); } } else if(thePosEcfSamples.size() == theDetectorCount) { pe = ossimEcefPoint(thePosEcfSamples[sample].x, thePosEcfSamples[sample].y, thePosEcfSamples[sample].z); } } void ossimSpotDimapSupportData::getPositionEcf(const ossim_float64& time, ossimEcefPoint& pe) const { ossimDpt3d tempPt; if((thePosEcfSamples.size() < 8)|| (theEphSampTimes.size() < 8)) { getBilinearInterpolation(time, thePosEcfSamples, theEphSampTimes, tempPt); } else { getLagrangeInterpolation(time, thePosEcfSamples, theEphSampTimes, tempPt); } pe = ossimEcefPoint(tempPt.x, tempPt.y, tempPt.z); } void ossimSpotDimapSupportData::getVelocityEcf(ossim_uint32 sample, ossimEcefPoint& ve) const { ve.makeNan(); if (theVelEcfSamples.size() < theDetectorCount) { if(theImageSize.samp > 0) { double t = 0.0; double tempIdx = 0.0; double tempIdxFraction = 0.0; t = static_cast(sample)/ static_cast(theDetectorCount-1); tempIdx = (theVelEcfSamples.size()-1)*t; tempIdxFraction = tempIdx - (ossim_int32)tempIdx; ossim_uint32 idxStart = (ossim_uint32)tempIdx; ossim_uint32 idxEnd = (ossim_uint32)ceil(tempIdx); if(idxEnd >= theVelEcfSamples.size()) { idxEnd = (ossim_uint32)theVelEcfSamples.size()-1; } if(idxStart > idxEnd) { idxStart = idxEnd; } ve = ossimEcefPoint(theVelEcfSamples[idxStart].x +tempIdxFraction*( theVelEcfSamples[idxEnd].x - theVelEcfSamples[idxStart].x), theVelEcfSamples[idxStart].y +tempIdxFraction*( theVelEcfSamples[idxEnd].y - theVelEcfSamples[idxStart].y), theVelEcfSamples[idxStart].z +tempIdxFraction*( theVelEcfSamples[idxEnd].z - theVelEcfSamples[idxStart].z)); } } else if(theVelEcfSamples.size() == theDetectorCount) { ve = ossimEcefPoint(theVelEcfSamples[sample].x, theVelEcfSamples[sample].y, theVelEcfSamples[sample].z); } } void ossimSpotDimapSupportData::getVelocityEcf(const ossim_float64& time, ossimEcefPoint& ve) const { ossimDpt3d tempPt; if((theVelEcfSamples.size() < 8) || (theEphSampTimes.size() < 8)) { getBilinearInterpolation (time, theVelEcfSamples, theEphSampTimes, tempPt); } else { getLagrangeInterpolation (time, theVelEcfSamples, theEphSampTimes, tempPt); } ve = ossimEcefPoint(tempPt.x, tempPt.y, tempPt.z); } void ossimSpotDimapSupportData::getEphSampTime(ossim_uint32 sample, ossim_float64& et) const { et = ossim::nan(); if(theEphSampTimes.size() < theImageSize.samp) { if(theImageSize.samp > 0) { double t = 0.0; double tempIdx = 0.0; double tempIdxFraction = 0.0; t = (double)sample/(double)(theImageSize.samp-1); tempIdx = (theEphSampTimes.size()-1)*t; tempIdxFraction = tempIdx - (ossim_int32)tempIdx; ossim_uint32 idxStart = (ossim_uint32)tempIdx; ossim_uint32 idxEnd = (ossim_uint32)ceil(tempIdx); if(idxEnd >= theEphSampTimes.size()) { idxEnd = (ossim_uint32)theEphSampTimes.size()-1; } if(idxStart > idxEnd) { idxStart = idxEnd; } et = (theEphSampTimes[idxStart] +tempIdxFraction*(theEphSampTimes[idxEnd] - theEphSampTimes[idxStart])); } } else if(theEphSampTimes.size() == theImageSize.samp) { et = theEphSampTimes[sample]; } } void ossimSpotDimapSupportData::getAttitude(ossim_uint32 sample, ossimDpt3d& at) const { if (sample >= theAttitudeSamples.size()) { at.makeNan(); return; } at = theAttitudeSamples[sample]; } void ossimSpotDimapSupportData::getAttitude(const ossim_float64& time, ossimDpt3d& at) const { if (theAttSampTimes.empty()) { at.makeNan(); return; } if ((time < theAttSampTimes.front()) || (time >= theAttSampTimes.back() )) { extrapolateAttitude(time, at); return; } //*** // Search the attitude sampling time array for surrounding samples: //*** int i=0; while ((i < (int)theAttSampTimes.size()) && (theAttSampTimes[i] < time)) ++i; --i; //*** // Linearly interpolate attitudes angles: //*** ossim_float64 dt1 = time - theAttSampTimes[i]; ossim_float64 dt0 = theAttSampTimes[i+1] - time; ossim_float64 dt = theAttSampTimes[i+1] - theAttSampTimes[i]; at = (theAttitudeSamples[i+1]*dt1 + theAttitudeSamples[i]*dt0)/dt; } void ossimSpotDimapSupportData::extrapolateAttitude(const ossim_float64& time, ossimDpt3d& at) const { at.makeNan(); int last_samp = (int) theAttSampTimes.size() - 1; if (last_samp < 1) return; ossimDpt3d dAtt, dAtt_dt; double dt, delta_t; // Determine whether extrapolating at the front or the back of the range: if (time < theAttSampTimes.front()) { dt = theAttSampTimes[1] - theAttSampTimes[0]; dAtt = theAttitudeSamples[1] - theAttitudeSamples[0]; dAtt_dt = dAtt/dt; delta_t = time - theAttSampTimes[0]; at = theAttitudeSamples[0] + (dAtt_dt*delta_t); } else if (time >= theAttSampTimes.back()) { dt = theAttSampTimes[last_samp] - theAttSampTimes[last_samp-1]; dAtt = theAttitudeSamples[last_samp] - theAttitudeSamples[last_samp-1]; dAtt_dt = dAtt/dt; delta_t = time - theAttSampTimes[last_samp]; at = theAttitudeSamples[last_samp] + (dAtt_dt*delta_t); } return; } void ossimSpotDimapSupportData::getAttSampTime(ossim_uint32 sample, ossim_float64& at) const { if (sample >= theAttSampTimes.size()) { at = ossim::nan(); return; } at = theAttSampTimes[sample]; } void ossimSpotDimapSupportData::getPixelLookAngleX(ossim_uint32 sample, ossim_float64& pa) const { if (sample >= thePixelLookAngleX.size()) { setErrorStatus(); pa = ossim::nan(); return; } pa = thePixelLookAngleX[sample]; } void ossimSpotDimapSupportData::getPixelLookAngleX(const ossim_float64& sample, ossim_float64& pa) const { ossim_uint32 s = static_cast(sample); getInterpolatedLookAngle(s, thePixelLookAngleX, pa); } void ossimSpotDimapSupportData::getPixelLookAngleY(ossim_uint32 sample, ossim_float64& pa) const { if (sample >= thePixelLookAngleY.size()) { setErrorStatus(); pa = ossim::nan(); return; } pa = thePixelLookAngleY[sample]; } void ossimSpotDimapSupportData::getPixelLookAngleY(const ossim_float64& sample, ossim_float64& pa) const { ossim_uint32 s = static_cast(sample); getInterpolatedLookAngle(s, thePixelLookAngleY, pa); } void ossimSpotDimapSupportData::getInterpolatedLookAngle( const ossim_float64& p, const std::vector& angles, ossim_float64& la) const { if ((p < 0.0) || (p >= (ossim_float64) angles.size())) { setErrorStatus(); la = ossim::nan(); return; } ossim_float64 p0 = floor(p); ossim_float64 p1 = ceil (p); if (p0 == p1) { la = angles[(int) p0]; } else { ossim_float64 angle_0 = angles[(int) p0]; ossim_float64 angle_1 = angles[(int) p1]; la = (angle_0*(p1-p) + angle_1*(p-p0))/(p1-p0); } } void ossimSpotDimapSupportData::getBilinearInterpolation( const ossim_float64& time, const std::vector& V, const std::vector& T, ossimDpt3d& li) const { ossim_uint32 samp0 = 0; while ((samp0 < T.size()) && (T[samp0] < time)) ++samp0; if(samp0==0) { li = V[0]; } else if(samp0 == T.size()) { li = V[1]; } else { double t = (T[samp0-1]-time)/(T[samp0-1] - T[samp0]); li = V[samp0-1] + (V[samp0]-V[samp0-1])*t; } } void ossimSpotDimapSupportData::getLagrangeInterpolation( const ossim_float64& time, const std::vector& V, const std::vector& T, ossimDpt3d& li) const { // std::cout << "V size = " << V.size() << std::endl // << "T size = " << T.size() << std::endl; ossim_uint32 filter_size = 8; // // Verify that t is within allowable range: // ossim_uint32 lagrange_half_filter = 4; if(T.size() <= filter_size) { filter_size = (ossim_uint32)T.size()/2; lagrange_half_filter = filter_size/2; } if ((time < T[lagrange_half_filter]) || (time >= T[T.size()-lagrange_half_filter] )) { setErrorStatus(); li.makeNan(); return; } //*** // Search the sampling time array for surrounding samples: //*** ossim_uint32 samp0 = lagrange_half_filter; while ((samp0 < T.size()) && (T[samp0] < time)) ++samp0; //*** // Do not use sample if it falls in neighborhood of desired time: //*** ossim_uint32 bump = 0; if (fabs(T[samp0] - time) < theLineSamplingPeriod/2.0) bump = 1; samp0 -= lagrange_half_filter; // adjust to first sample in window //*** // Outer summation loop: //*** ossimDpt3d S (0, 0, 0); for (ossim_uint32 j=samp0; j<(samp0+filter_size+bump); ++j) { ossim_float64 numerator = 1.0; ossim_float64 denominator = 1.0; //*** // Skip this sample if too close to desired time: //*** if (bump && (j == (samp0+lagrange_half_filter) )) ++j; //*** // Inner loop for product series: //*** for (ossim_uint32 i=samp0; i<(samp0+filter_size+bump); ++i) { //*** // Skip this sample if too close to desired time: //*** if (bump && (i == (samp0+lagrange_half_filter) )) ++i; if (i != j) { numerator *= time - T[i]; denominator *= T[j] - T[i]; } } ossimDpt3d p = V[j]; p = p * numerator; p = p / denominator; S += p; } li = S; } ossim_float64 ossimSpotDimapSupportData::convertTimeStamp(const ossimString& time_stamp) const { double ti; convertTimeStamp(time_stamp, ti); return ti; } void ossimSpotDimapSupportData::convertTimeStamp(const ossimString& time_stamp, ossim_float64& ti) const { int year, month, day, hour, minute; double second; //*** // Time stamps are in the format: "yyyy-mm-ddThh:mm:ss.ssssss" //*** int converted = sscanf(time_stamp, "%4d-%2d-%2dT%2d:%2d:%9lf", &year, &month, &day, &hour, &minute, &second); if (converted != 6) { setErrorStatus(); ti = ossim::nan(); } else { ti = (((((year-2002.0)*12.0 + month - 1.0)*365.0 + day - 1.0)*24.0 + hour)*60.0 + minute)*60.0 + second; } } void ossimSpotDimapSupportData::getGeoPosPoint (ossim_uint32 point, ossimDpt& ip, ossimGpt& gp) const { if (point < theGeoPosImagePoints.size()) { ip = theGeoPosImagePoints [point]; gp = theGeoPosGroundPoints[point]; } } void ossimSpotDimapSupportData::printInfo(ostream& os) const { ossimString corr_att = "NO"; if (theStarTrackerUsed) corr_att = "YES"; os << "\n----------------- Info on SPOT5 Image -------------------" << "\n " << "\n Job Number (ID): " << theImageID << "\n Acquisition Date: " << theAcquisitionDate << "\n Instrument: " << theInstrument << "\n Instrument Index: " << theInstrumentIndex << "\n Production Date: " << theProductionDate << "\n Number of Bands: " << theNumBands << "\n Geo Center Point: " << theRefGroundPoint << "\n Detector count: " << theDetectorCount << "\n Image Size: " << theImageSize << "\n Incidence Angle: " << theIncidenceAngle << "\n Viewing Angle: " << theViewingAngle << "\n Scene Orientation: " << theSceneOrientation << "\n Corrected Attitude: " << corr_att << "\n Sun Azimuth: " << theSunAzimuth << "\n Sun Elevation: " << theSunElevation << "\n Sub image offset: " << theSubImageOffset << "\n Step Count: " << theStepCount << "\n PixelLookAngleX size: " << thePixelLookAngleX.size() << "\n thePosEcfSamples size:" << thePosEcfSamples.size() << "\n Corner Points:" << "\n UL: " << theUlCorner << "\n UR: " << theUrCorner << "\n LR: " << theLrCorner << "\n LL: " << theLlCorner << "\n" << "\n---------------------------------------------------------" << "\n " << std::endl; } ossimString ossimSpotDimapSupportData::getSensorID() const { return theSensorID; } ossimString ossimSpotDimapSupportData::getMetadataVersionString() const { if (theMetadataVersion == OSSIM_SPOT_METADATA_VERSION_1_1) { return ossimString("1.1"); } else if (theMetadataVersion == OSSIM_SPOT_METADATA_VERSION_1_0) { return ossimString("1.0"); } return ossimString("unknown"); } ossimString ossimSpotDimapSupportData::getAcquisitionDate() const { return theAcquisitionDate; } ossimString ossimSpotDimapSupportData::getProductionDate() const { return theProductionDate; } ossimString ossimSpotDimapSupportData::getImageID() const { return theImageID; } ossimFilename ossimSpotDimapSupportData::getMetadataFile() const { return theMetadataFile; } ossimString ossimSpotDimapSupportData::getInstrument() const { return theInstrument; } ossim_uint32 ossimSpotDimapSupportData::getInstrumentIndex() const { return theInstrumentIndex; } void ossimSpotDimapSupportData::getSunAzimuth(ossim_float64& az) const { az = theSunAzimuth; } void ossimSpotDimapSupportData::getSunElevation(ossim_float64& el) const { el = theSunElevation; } void ossimSpotDimapSupportData::getImageSize(ossimDpt& sz) const { sz = theImageSize; } void ossimSpotDimapSupportData::getLineSamplingPeriod(ossim_float64& pe) const { pe = theLineSamplingPeriod; } bool ossimSpotDimapSupportData::isStarTrackerUsed() const { return theStarTrackerUsed; } bool ossimSpotDimapSupportData::isSwirDataUsed() const { return theSwirDataFlag; } ossim_uint32 ossimSpotDimapSupportData::getNumberOfBands() const { return theNumBands; } ossim_uint32 ossimSpotDimapSupportData::getStepCount() const { return theStepCount; } void ossimSpotDimapSupportData::getIncidenceAngle(ossim_float64& ia) const { ia = theIncidenceAngle; } void ossimSpotDimapSupportData::getViewingAngle(ossim_float64& va) const { va = theViewingAngle; } void ossimSpotDimapSupportData::getSceneOrientation(ossim_float64& so) const { so = theSceneOrientation; } void ossimSpotDimapSupportData::getRefGroundPoint(ossimGpt& gp) const { gp = theRefGroundPoint; } void ossimSpotDimapSupportData::getRefImagePoint(ossimDpt& rp) const { rp = theRefImagePoint; } void ossimSpotDimapSupportData::getRefLineTime(ossim_float64& rt) const { rt = theRefLineTime; } void ossimSpotDimapSupportData::getRefLineTimeLine(ossim_float64& rtl) const { rtl = theRefLineTimeLine; } ossim_uint32 ossimSpotDimapSupportData::getNumEphSamples() const { return (ossim_uint32)theEphSampTimes.size(); } ossim_uint32 ossimSpotDimapSupportData::getNumAttSamples() const { return (ossim_uint32)theAttSampTimes.size(); } ossim_uint32 ossimSpotDimapSupportData::getNumGeoPosPoints() const { return (ossim_uint32)theGeoPosImagePoints.size(); } void ossimSpotDimapSupportData::getUlCorner(ossimGpt& pt) const { pt = theUlCorner; } void ossimSpotDimapSupportData::getUrCorner(ossimGpt& pt) const { pt = theUrCorner; } void ossimSpotDimapSupportData::getLrCorner(ossimGpt& pt) const { pt = theLrCorner; } void ossimSpotDimapSupportData::getLlCorner(ossimGpt& pt) const { pt = theLlCorner; } void ossimSpotDimapSupportData::getImageRect(ossimDrect& rect)const { rect = ossimDrect(0.0, 0.0, theImageSize.x-1.0, theImageSize.y-1.0); } void ossimSpotDimapSupportData::getSubImageOffset(ossimDpt& offset) const { offset = theSubImageOffset; } bool ossimSpotDimapSupportData::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimSpotDimapSupportData", true); kwl.add(prefix, "metadata_file", theMetadataFile, true); kwl.add(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW, theSunAzimuth, true); kwl.add(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW, theSunElevation, true); //--- // Note: since this is a new keyword, use the point.toString as there is // no backwards compatibility issues. //--- kwl.add(prefix, "detector_count", theDetectorCount, true); kwl.add(prefix, "image_size", ossimString::toString(theImageSize.x) + " " + ossimString::toString(theImageSize.y), true); kwl.add(prefix, "reference_ground_point", ossimString::toString(theRefGroundPoint.latd()) + " " + ossimString::toString(theRefGroundPoint.lond()) + " " + ossimString::toString(theRefGroundPoint.height()) + " " + theRefGroundPoint.datum()->code(), true); kwl.add(prefix, "reference_image_point", ossimString::toString(theRefImagePoint.x) + " " + ossimString::toString(theRefImagePoint.y), true); kwl.add(prefix, "sub_image_offset", ossimString::toString(theSubImageOffset.x) + " " + ossimString::toString(theSubImageOffset.y), true); kwl.add(prefix, "reference_line_time", theRefLineTime, true); kwl.add(prefix, "reference_line_time_line", theRefLineTimeLine, true); kwl.add(prefix, "line_sampling_period", theLineSamplingPeriod, true); ossimString tempString; ossim_uint32 idx = 0; tempString = ""; for(idx = 0; idx < thePixelLookAngleX.size(); ++idx) { tempString += (ossimString::toString(thePixelLookAngleX[idx]) + " "); } kwl.add(prefix, "pixel_lookat_angle_x", tempString, true); kwl.add(prefix, "number_of_pixel_lookat_angle_x", static_cast(thePixelLookAngleX.size()), true); tempString = ""; for(idx = 0; idx < thePixelLookAngleY.size(); ++idx) { tempString += (ossimString::toString(thePixelLookAngleY[idx]) + " "); } kwl.add(prefix, "pixel_lookat_angle_y", tempString, true); kwl.add(prefix, "number_of_pixel_lookat_angle_y", static_cast(thePixelLookAngleY.size()), true); tempString = ""; for(idx = 0; idx < theAttitudeSamples.size(); ++idx) { tempString += (ossimString::toString(theAttitudeSamples[idx].x) + " " + ossimString::toString(theAttitudeSamples[idx].y) + " " + ossimString::toString(theAttitudeSamples[idx].z) + " "); } kwl.add(prefix, "attitude_samples", tempString, true); kwl.add(prefix, "number_of_attitude_samples", static_cast(theAttitudeSamples.size()), true); tempString = ""; for(idx = 0; idx < theAttSampTimes.size(); ++idx) { tempString += (ossimString::toString(theAttSampTimes[idx]) + " "); } kwl.add(prefix, "attitude_sample_times", tempString, true); kwl.add(prefix, "number_of_attitude_sample_times", static_cast(theAttSampTimes.size()), true); tempString = ""; for(idx = 0; idx < thePosEcfSamples.size(); ++idx) { tempString += (ossimString::toString(thePosEcfSamples[idx].x) + " " + ossimString::toString(thePosEcfSamples[idx].y) + " " + ossimString::toString(thePosEcfSamples[idx].z) + " "); } kwl.add(prefix, "position_ecf_samples", tempString, true); kwl.add(prefix, "number_of_position_ecf_samples", static_cast(thePosEcfSamples.size()), true); tempString = ""; for(idx = 0; idx < theVelEcfSamples.size(); ++idx) { tempString += (ossimString::toString(theVelEcfSamples[idx].x) + " " + ossimString::toString(theVelEcfSamples[idx].y) + " " + ossimString::toString(theVelEcfSamples[idx].z) + " "); } kwl.add(prefix, "velocity_ecf_samples", tempString, true); kwl.add(prefix, "number_of_velocity_ecf_samples", static_cast(thePosEcfSamples.size()), true); tempString = ""; for(idx = 0; idx < theEphSampTimes.size(); ++idx) { tempString += (ossimString::toString(theEphSampTimes[idx]) + " "); } kwl.add(prefix, "ephemeris_sample_times", tempString, true); kwl.add(prefix, "number_of_ephemeris_sample_times", static_cast(theEphSampTimes.size()), true); kwl.add(prefix, "star_tracker_used_flag", static_cast(theStarTrackerUsed), true); kwl.add(prefix, "swir_data_flag", static_cast(theSwirDataFlag), true); kwl.add(prefix, ossimKeywordNames::NUMBER_BANDS_KW, theNumBands, true); kwl.add(prefix, "image_id", theImageID, true); kwl.add(prefix, "instrument", theInstrument, true); kwl.add(prefix, "instrument_index", theInstrumentIndex, true); kwl.add(prefix, ossimKeywordNames::IMAGE_DATE_KW, theAcquisitionDate, true); kwl.add(prefix, "production_date", theProductionDate, true); kwl.add(prefix, "incident_angle", theIncidenceAngle, true); kwl.add(prefix, "viewing_angle", theViewingAngle, true); kwl.add(prefix, "scene_orientation", theSceneOrientation, true); kwl.add(prefix, "step_count", theStepCount, true); kwl.add(prefix, "ul_ground_point", ossimString::toString(theUlCorner.latd()) + " " + ossimString::toString(theUlCorner.lond()) + " " + ossimString::toString(theUlCorner.height()) + " " + theUlCorner.datum()->code(), true); kwl.add(prefix, "ur_ground_point", ossimString::toString(theUrCorner.latd()) + " " + ossimString::toString(theUrCorner.lond()) + " " + ossimString::toString(theUrCorner.height()) + " " + theUrCorner.datum()->code(), true); kwl.add(prefix, "lr_ground_point", ossimString::toString(theLrCorner.latd()) + " " + ossimString::toString(theLrCorner.lond()) + " " + ossimString::toString(theLrCorner.height()) + " " + theLrCorner.datum()->code(), true); kwl.add(prefix, "ll_ground_point", ossimString::toString(theLlCorner.latd()) + " " + ossimString::toString(theLlCorner.lond()) + " " + ossimString::toString(theLlCorner.height()) + " " + theLlCorner.datum()->code(), true); kwl.add(prefix, "sensorID", theSensorID, true); tempString = ""; for(idx = 0; idx < thePhysicalBias.size(); ++idx) { tempString += (ossimString::toString(thePhysicalBias[idx]) + " "); } kwl.add(prefix, "physical_bias", tempString, true); tempString = ""; for(idx = 0; idx < thePhysicalGain.size(); ++idx) { tempString += (ossimString::toString(thePhysicalGain[idx]) + " "); } kwl.add(prefix, "physical_gain", tempString, true); tempString = ""; for(idx = 0; idx < theSolarIrradiance.size(); ++idx) { tempString += (ossimString::toString(theSolarIrradiance[idx]) + " "); } kwl.add(prefix, "solar_irradiance", tempString, true); return true; } bool ossimSpotDimapSupportData::loadState(const ossimKeywordlist& kwl, const char* prefix) { clearFields(); ossimString type = kwl.find(prefix, ossimKeywordNames::TYPE_KW); if(type != "ossimSpotDimapSupportData") { return false; } theMetadataFile = kwl.find(prefix, "metadata_file"); theSunAzimuth = ossimString(kwl.find(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW)).toDouble(); theSunElevation = ossimString(kwl.find(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW)).toDouble(); const char* lookup = kwl.find(prefix, "detector_count"); if (lookup) { theDetectorCount = ossimString(lookup).toUInt32(); } theImageSize = createDpt(kwl.find(prefix, "image_size")); theRefGroundPoint = createGround(kwl.find(prefix, "reference_ground_point")); theRefImagePoint = createDpt(kwl.find(prefix, "reference_image_point")); theSubImageOffset = createDpt(kwl.find(prefix, "sub_image_offset")); theRefLineTime = ossimString(kwl.find(prefix, "reference_line_time")).toDouble(); lookup = kwl.find(prefix, "reference_line_time_line"); if (lookup) { theRefLineTimeLine = ossimString(lookup).toDouble(); } theLineSamplingPeriod = ossimString(kwl.find(prefix, "line_sampling_period")).toDouble(); ossim_uint32 idx = 0; ossim_uint32 total = ossimString(kwl.find(prefix,"number_of_pixel_lookat_angle_x")).toUInt32(); ossimString tempString; thePixelLookAngleX.resize(total); tempString = kwl.find(prefix,"pixel_lookat_angle_x"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString tempValue; for(idx = 0; idx < thePixelLookAngleX.size();++idx) { in >> tempValue.string(); thePixelLookAngleX[idx] = tempValue.toDouble(); } } total = ossimString(kwl.find(prefix,"number_of_pixel_lookat_angle_y")).toUInt32(); thePixelLookAngleY.resize(total); tempString = kwl.find(prefix,"pixel_lookat_angle_y"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString tempValue; for(idx = 0; idx < thePixelLookAngleY.size();++idx) { in >> tempValue.string(); thePixelLookAngleY[idx] = tempValue.toDouble(); } } total = ossimString(kwl.find(prefix,"number_of_attitude_samples")).toUInt32(); theAttitudeSamples.resize(total); tempString = kwl.find(prefix,"attitude_samples"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString x, y, z; for(idx = 0; idx < theAttitudeSamples.size();++idx) { in >> x.string() >> y.string() >> z.string(); theAttitudeSamples[idx] =ossimDpt3d(x.toDouble(), y.toDouble(), z.toDouble()); } } total = ossimString(kwl.find(prefix,"number_of_attitude_sample_times")).toUInt32(); theAttSampTimes.resize(total); tempString = kwl.find(prefix,"attitude_sample_times"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString tempValue; for(idx = 0; idx < theAttSampTimes.size();++idx) { in >> tempValue.string(); theAttSampTimes[idx] = tempValue.toDouble(); } } total = ossimString(kwl.find(prefix,"number_of_position_ecf_samples")).toUInt32(); thePosEcfSamples.resize(total); tempString = kwl.find(prefix,"position_ecf_samples"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString x, y, z; for(idx = 0; idx < thePosEcfSamples.size();++idx) { in >> x.string() >> y.string() >> z.string(); thePosEcfSamples[idx] = ossimDpt3d(x.toDouble(), y.toDouble(), z.toDouble()); } } total = ossimString(kwl.find(prefix,"number_of_velocity_ecf_samples")).toUInt32(); theVelEcfSamples.resize(total); tempString = kwl.find(prefix,"velocity_ecf_samples"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString x, y, z; for(idx = 0; idx < theVelEcfSamples.size();++idx) { in >> x.string() >> y.string() >> z.string(); theVelEcfSamples[idx] = ossimDpt3d(x.toDouble(), y.toDouble(), z.toDouble()); } } total = ossimString(kwl.find(prefix,"number_of_ephemeris_sample_times")).toUInt32(); theEphSampTimes.resize(total); tempString = kwl.find(prefix,"ephemeris_sample_times"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString tempValue; for(idx = 0; idx < theEphSampTimes.size();++idx) { in >> tempValue.string(); theEphSampTimes[idx] = tempValue.toDouble(); } } tempString = ""; for(idx = 0; idx < theEphSampTimes.size(); ++idx) { tempString += (ossimString::toString(theEphSampTimes[idx]) + " "); } theStarTrackerUsed = ossimString(kwl.find(prefix, "star_tracker_used_flag")).toBool(); theSwirDataFlag = ossimString(kwl.find(prefix, "swir_data_flag")).toBool(); theNumBands = ossimString(kwl.find(prefix, ossimKeywordNames::NUMBER_BANDS_KW)).toUInt32(); theAcquisitionDate = kwl.find(prefix, ossimKeywordNames::IMAGE_DATE_KW); theProductionDate = kwl.find(prefix, "production_date"); theImageID = kwl.find(prefix, "image_id"); theInstrument = kwl.find(prefix, "instrument"); theInstrumentIndex = ossimString(kwl.find(prefix, "instrument_index")).toUInt32(); theStepCount = ossimString(kwl.find(prefix, "step_count")).toInt32(); theIncidenceAngle = ossimString(kwl.find(prefix, "incident_angle")).toDouble(); theViewingAngle = ossimString(kwl.find(prefix, "viewing_angle")).toDouble(); theSceneOrientation= ossimString(kwl.find(prefix, "scene_orientation")).toDouble(); theUlCorner =createGround( kwl.find(prefix, "ul_ground_point")); theUrCorner =createGround( kwl.find(prefix, "ur_ground_point")); theLrCorner =createGround( kwl.find(prefix, "lr_ground_point")); theLlCorner =createGround( kwl.find(prefix, "ll_ground_point")); theSensorID = ossimString(kwl.find(prefix, "sensorID")); thePhysicalBias.resize(theNumBands); tempString = kwl.find(prefix,"physical_bias"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString tempValue; for(idx = 0; idx < thePhysicalBias.size();++idx) { in >> tempValue.string(); thePhysicalBias[idx] = tempValue.toDouble(); } } thePhysicalGain.resize(theNumBands); tempString = kwl.find(prefix,"physical_gain"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString tempValue; for(idx = 0; idx < thePhysicalGain.size();++idx) { in >> tempValue.string(); thePhysicalGain[idx] = tempValue.toDouble(); } } theSolarIrradiance.resize(theNumBands); tempString = kwl.find(prefix,"solar_irradiance"); if(tempString != "") { std::istringstream in(tempString.string()); ossimString tempValue; for(idx = 0; idx < theSolarIrradiance.size();++idx) { in >> tempValue.string(); theSolarIrradiance[idx] = tempValue.toDouble(); } } return true; } ossimGpt ossimSpotDimapSupportData::createGround(const ossimString& s)const { std::istringstream in(s.string()); ossimString lat, lon, height; ossimString code; in >> lat.string() >> lon.string() >> height.string() >> code.string(); return ossimGpt(lat.toDouble(), lon.toDouble(), height.toDouble(), ossimDatumFactory::instance()->create(code)); } ossimDpt ossimSpotDimapSupportData::createDpt(const ossimString& s)const { std::istringstream in(s.string()); ossimString x, y; ossimString code; in >> x.string() >> y.string(); return ossimDpt(x.toDouble(), y.toDouble()); } bool ossimSpotDimapSupportData::parsePart1( ossimRefPtr xmlDocument) { static const char MODULE[] = "ossimSpotDimapSupportData::parsePart1"; ossimString xpath; vector > xml_nodes; //--- // Fetch the ImageSize: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Raster_Dimensions/NCOLS"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } theImageSize.samp = xml_nodes[0]->getText().toDouble(); xml_nodes.clear(); xpath = "/Dimap_Document/Raster_Dimensions/NROWS"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } theImageSize.line = xml_nodes[0]->getText().toDouble(); if (theSwirDataFlag) { theImageSize.line /= 2.0; theImageSize.samp /= 2.0; } //--- // We will make the RefImagePoint the zero base center of the image. This // is used by the ossimSensorModel::worldToLineSample iterative loop as // the starting point. Since the ossimSensorModel does not know of the // sub image we make it zero base. //--- theRefImagePoint.line = theImageSize.line / 2.0; theRefImagePoint.samp = theImageSize.samp / 2.0; xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Sensor_Configuration/Time_Stamp/SCENE_CENTER_LINE"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } // Relative to full image frame. theRefLineTimeLine = xml_nodes[0]->getText().toDouble() - 1.0; // See if there's a sub image offset... xml_nodes.clear(); xpath = "/Dimap_Document/Data_Processing/Regions_Of_Interest/Region_Of_Interest/COL_MIN"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { theSubImageOffset.samp = 0.0; } else { theSubImageOffset.samp = xml_nodes[0]->getText().toDouble() - 1.0; } xml_nodes.clear(); xpath = "/Dimap_Document/Data_Processing/Regions_Of_Interest/Region_Of_Interest/ROW_MIN"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { theSubImageOffset.line = 0.0; } else { theSubImageOffset.line = xml_nodes[0]->getText().toDouble() - 1.0; } if (theSwirDataFlag) { theRefImagePoint.line /= 2.0; theRefImagePoint.samp /= 2.0; } //--- // Fetch the RefLineTime: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Sensor_Configuration/Time_Stamp/SCENE_CENTER_TIME"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } theAcquisitionDate = xml_nodes[0]->getText(); convertTimeStamp(theAcquisitionDate, theRefLineTime); //--- // Fetch the ProductionDate: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Production/DATASET_PRODUCTION_DATE"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } theProductionDate = xml_nodes[0]->getText(); //--- // Fetch the Instrument: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Sources/Source_Information/Scene_Source/INSTRUMENT"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } theInstrument = xml_nodes[0]->getText(); //--- // Fetch the Instrument Index: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Sources/Source_Information/Scene_Source/INSTRUMENT_INDEX"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } theInstrumentIndex = xml_nodes[0]->getText().toUInt32(); return true; } bool ossimSpotDimapSupportData::parsePart2( ossimRefPtr xmlDocument) { static const char MODULE[] = "ossimSpotDimapSupportData::parsePart2"; ossimString xpath; std::vector > xml_nodes; std::vector > sub_nodes; std::vector >::iterator node; unsigned int band_index; //--- // Fetch the LineSamplingPeriod: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Sensor_Configuration/Time_Stamp/LINE_PERIOD"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } theLineSamplingPeriod = xml_nodes[0]->getText().toDouble(); if (theSwirDataFlag) { theLineSamplingPeriod *= 2.0; } //--- // Fetch number of bands //--- xml_nodes.clear(); xpath = "/Dimap_Document/Raster_Dimensions/NBANDS"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } theNumBands = atoi(xml_nodes[0]->getText()); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nNumber of bands: " << theNumBands << std::endl; } if (theNumBands == 1) { if (theSwirDataFlag) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nSWIR band error..." << std::endl; } return false; } band_index = 0; } else if (theNumBands == 3) { band_index = 0; // using green band for PSI angles } else if (theNumBands == 4) { if (theSwirDataFlag) { band_index = 3; } else { band_index = 1; // using green band for PSI angles } } else { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nBand ERROR!" << std::endl; } return false; } //--- // Fetch the PixelLookAngleX and PixelLookAngleY arrays. If MS, then the // green band PSI angles are used unless SWIR requested: //--- thePixelLookAngleX.clear(); xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Sensor_Configuration/" "Instrument_Look_Angles_List/Instrument_Look_Angles/"; xmlDocument->findNodes(xpath, xml_nodes); // if (xml_nodes.size() != theNumBands) // { if(xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\nCould not find: " << xpath << std::endl; } return false; } // else // { // } // } xpath = "Look_Angles_List/Look_Angles/PSI_X"; sub_nodes.clear(); xml_nodes[band_index]->findChildNodes(xpath, sub_nodes); theDetectorCount = (ossim_uint32)sub_nodes.size(); if (theMetadataVersion == OSSIM_SPOT_METADATA_VERSION_1_1) { for (ossim_uint32 i=0; igetText().toDouble()); } } else if (sub_nodes.size() != theImageSize.samp) { // theFullImageSize.samp = sub_nodes.size(); // if ((theSubImageOffset.samp + theImageSize.samp - 1)<= sub_nodes.size()) // { // ossim_uint32 i = theSubImageOffset.samp; // for (ossim_uint32 idx 0; idxgetText().toDouble()); // ++i; // } // } // else // { std::vector tempV(sub_nodes.size()); double t = 0.0; double tempIdx = 0.0; double tempIdxFraction = 0.0; ossim_int32 idxStart = 0; ossim_int32 idxEnd = 0; ossim_uint32 idx = 0; for(idx = 0; idx < sub_nodes.size();++idx) { tempV[idx] = sub_nodes[idx]->getText().toDouble(); } for(idx = 0; idx < theImageSize.samp; ++idx) { t = (double)idx/(double)(theImageSize.samp); tempIdx = (sub_nodes.size()-1)*t; tempIdxFraction = tempIdx - (ossim_int32)tempIdx; idxStart = (ossim_int32)tempIdx; idxEnd = (ossim_int32)ceil(tempIdx); if(idxEnd >= (ossim_int32)sub_nodes.size()) { idxEnd = (ossim_int32)sub_nodes.size()-1; } thePixelLookAngleX.push_back(tempV[idxStart] + tempIdxFraction*(tempV[idxEnd] - tempV[idxStart])); } } else { for (ossim_uint32 i=0; igetText().toDouble()); } } thePixelLookAngleY.clear(); xpath = "Look_Angles_List/Look_Angles/PSI_Y"; sub_nodes.clear(); xml_nodes[band_index]->findChildNodes(xpath, sub_nodes); if (theMetadataVersion == OSSIM_SPOT_METADATA_VERSION_1_1) { for (ossim_uint32 i=0; igetText().toDouble()); } } else if (sub_nodes.size() != theImageSize.samp) { // if ((theSubImageOffset.samp + theImageSize.samp - 1)<= sub_nodes.size()) // { // ossim_uint32 i = theSubImageOffset.samp; // for (ossim_uint32 idx 0; idxgetText().toDouble()); // ++i; // } // } std::vector tempV(sub_nodes.size()); double t = 0.0; double tempIdx = 0.0; double tempIdxFraction = 0.0; ossim_int32 idxStart = 0; ossim_int32 idxEnd = 0; ossim_uint32 idx = 0; for(idx = 0; idx < sub_nodes.size();++idx) { tempV[idx] = sub_nodes[idx]->getText().toDouble(); } for(idx = 0; idx < theImageSize.samp; ++idx) { t = (double)idx/(double)(theImageSize.samp-1); tempIdx = (sub_nodes.size()-1)*t; tempIdxFraction = tempIdx - (ossim_int32)tempIdx; idxStart = (ossim_int32)tempIdx; idxEnd = (ossim_int32)ceil(tempIdx); if(idxEnd >= (ossim_int32)sub_nodes.size()) { idxEnd = (ossim_int32)sub_nodes.size()-1; } if(idxStart > idxEnd) { idxStart = idxEnd; } thePixelLookAngleY.push_back(tempV[idxStart] + tempIdxFraction*(tempV[idxEnd] - tempV[idxStart])); } } else { for (ossim_uint32 i=0; igetText().toDouble()); } } //--- // Fetch the Attitude Samples: //--- theAttitudeSamples.clear(); theAttSampTimes.clear(); xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Satellite_Attitudes/Corrected_Attitudes/" "Corrected_Attitude/Angles"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { xpath = "/Dimap_Document/Data_Strip/Satellite_Attitudes/Raw_Attitudes/Aocs_Attitude/Angles_List/Angles"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); return false; } } node = xml_nodes.begin(); while (node != xml_nodes.end()) { ossimDpt3d V; sub_nodes.clear(); xpath = "OUT_OF_RANGE"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } if (sub_nodes[0]->getText() == "N") { sub_nodes.clear(); xpath = "PITCH"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } V.x = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "ROLL"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } V.y = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "YAW"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } V.z = sub_nodes[0]->getText().toDouble(); theAttitudeSamples.push_back(V); sub_nodes.clear(); xpath = "TIME"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } theAttSampTimes.push_back(convertTimeStamp(sub_nodes[0]->getText())); } ++node; } return true; } bool ossimSpotDimapSupportData::parsePart3( ossimRefPtr xmlDocument) { ossimString xpath; std::vector > xml_nodes; std::vector > sub_nodes; std::vector >::iterator node; //--- // Fetch the ephemeris samples: //--- thePosEcfSamples.clear(); theVelEcfSamples.clear(); theEphSampTimes.clear(); xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Ephemeris/Points/Point"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); return false; } node = xml_nodes.begin(); while (node != xml_nodes.end()) { ossimDpt3d VP; sub_nodes.clear(); xpath = "Location/X"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } VP.x = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "Location/Y"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } VP.y = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "Location/Z"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } VP.z = sub_nodes[0]->getText().toDouble(); thePosEcfSamples.push_back(VP); ossimDpt3d VV; sub_nodes.clear(); xpath = "Velocity/X"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } VV.x = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "Velocity/Y"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } VV.y = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "Velocity/Z"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } VV.z = sub_nodes[0]->getText().toDouble(); theVelEcfSamples.push_back(VV); sub_nodes.clear(); xpath = "TIME"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } theEphSampTimes.push_back(convertTimeStamp(sub_nodes[0]->getText())); ++node; } //--- // Fetch the star tracker flag: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Satellite_Attitudes/Corrected_Attitudes/" "STAR_TRACKER_USED"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { theStarTrackerUsed = false; // setErrorStatus(); // return false; } else { if (xml_nodes[0]->getText() == "Y") theStarTrackerUsed = true; else theStarTrackerUsed = false; } //--- // Geoposition points: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Geoposition/Geoposition_Points/Tie_Point"; xmlDocument->findNodes(xpath, xml_nodes); node = xml_nodes.begin(); while (node != xml_nodes.end()) { ossimGpt gpt; ossimDpt ipt; sub_nodes.clear(); xpath = "TIE_POINT_DATA_Y"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } ipt.line = sub_nodes[0]->getText().toDouble() - 1.0; sub_nodes.clear(); xpath = "TIE_POINT_DATA_X"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } ipt.samp = sub_nodes[0]->getText().toDouble() - 1.0; sub_nodes.clear(); xpath = "TIE_POINT_CRS_Y"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } gpt.lat = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "TIE_POINT_CRS_X"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } gpt.lon = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "TIE_POINT_CRS_Z"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } gpt.hgt = sub_nodes[0]->getText().toDouble(); theGeoPosImagePoints.push_back(ipt); theGeoPosGroundPoints.push_back(gpt); ++node; } return true; } bool ossimSpotDimapSupportData::parsePart4(ossimRefPtr xmlDocument) { ossimString xpath; std::vector > xml_nodes; std::vector > sub_nodes; std::vector >::iterator node; //--- // Fetch the gain and bias for each spectral band: //--- thePhysicalGain.assign(theNumBands, 1.000); thePhysicalBias.assign(theNumBands, 0.000); xml_nodes.clear(); xpath = "/Dimap_Document/Image_Interpretation/Spectral_Band_Info"; xmlDocument->findNodes(xpath, xml_nodes); node = xml_nodes.begin(); while (node != xml_nodes.end()) { sub_nodes.clear(); xpath = "BAND_INDEX"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } ossim_int32 bandIndex = sub_nodes[0]->getText().toInt32() - 1; if( (bandIndex >= static_cast(theNumBands) ) || (bandIndex<0) ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimSpotDimapSupportData::parsePart4 ERROR: Band index outside of range\n"; return false; } sub_nodes.clear(); xpath = "PHYSICAL_BIAS"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } thePhysicalBias[bandIndex] = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "PHYSICAL_GAIN"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } thePhysicalGain[bandIndex] = sub_nodes[0]->getText().toDouble(); ++node; } theSolarIrradiance.assign(theNumBands, 0.000); xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Sensor_Calibration/Solar_Irradiance/Band_Solar_Irradiance"; xmlDocument->findNodes(xpath, xml_nodes); node = xml_nodes.begin(); while (node != xml_nodes.end()) { sub_nodes.clear(); xpath = "BAND_INDEX"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } ossim_int32 bandIndex = sub_nodes[0]->getText().toInt32() - 1; if((bandIndex >= static_cast(theNumBands) ) || (bandIndex<0)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimSpotDimapSupportData::parsePart4 ERROR: Band index outside of range\n"; return false; } sub_nodes.clear(); xpath = "SOLAR_IRRADIANCE_VALUE"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } theSolarIrradiance[bandIndex] = sub_nodes[0]->getText().toDouble(); ++node; } return true; } bool ossimSpotDimapSupportData::initMetadataVersion(ossimRefPtr xmlDocument) { ossimString xpath; std::vector > xml_nodes; //--- // Get the version string which can be used as a key for parsing. //--- xpath = "/Dimap_Document/Metadata_Id/METADATA_FORMAT"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << endl; } return false; } ossimString attribute = "version"; ossimString value; xml_nodes[0]->getAttributeValue(value, attribute); if (value == "1.0") { theMetadataVersion = OSSIM_SPOT_METADATA_VERSION_1_0; } else if (value == "1.1") { theMetadataVersion = OSSIM_SPOT_METADATA_VERSION_1_1; } if (theMetadataVersion == OSSIM_SPOT_METADATA_VERSION_UNKNOWN) { setErrorStatus(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: metadata version not found!" << std::endl; } return false; } return true; } bool ossimSpotDimapSupportData::initImageId( ossimRefPtr xmlDocument) { ossimString xpath; vector > xml_nodes; //--- // Fetch the Image ID: //--- xpath = "/Dimap_Document/Production/JOB_ID"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << endl; } return false; } theImageID = xml_nodes[0]->getText(); return true; } bool ossimSpotDimapSupportData::initSceneSource( ossimRefPtr xmlDocument) { ossimString xpath; vector > xml_nodes; //--- // Fetch the mission index (Spot 1, 4 or 5): // and generate theSensorID //--- xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Sources/Source_Information/Scene_Source/MISSION_INDEX"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << std::endl; } return false; } if (xml_nodes[0]->getText() == "1") theSensorID = "Spot 1"; if (xml_nodes[0]->getText() == "2") theSensorID = "Spot 2"; if (xml_nodes[0]->getText() == "4") theSensorID = "Spot 4"; if (xml_nodes[0]->getText() == "5") theSensorID = "Spot 5"; //--- // Fetch the Sun Azimuth: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Sources/Source_Information/Scene_Source/SUN_AZIMUTH"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << std::endl; } return false; } theSunAzimuth = xml_nodes[0]->getText().toDouble(); //--- // Fetch the Sun Elevation: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Sources/Source_Information/Scene_Source/SUN_ELEVATION"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << std::endl; } return false; } theSunElevation = xml_nodes[0]->getText().toDouble(); //--- // Fetch incidence angle: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Sources/Source_Information/Scene_Source/INCIDENCE_ANGLE"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << std::endl; } return false; } theIncidenceAngle = xml_nodes[0]->getText().toDouble(); //--- // Fetch viewing angle: // // From the SPOT Dimap documentation (Dimap Generic 1.0), VIEWING_ANGLE // (the scene instrumental viewing angle) is ONLY available for SPOT5 data. // FROM SPOT: You can use use incidence angle to calculate viewing angle // (called look direction as well). // FIX (see below): need theSatelliteAltitude and theIncidenceAngle. The // equation is shown below where RT is the mean value of WGS84 ellipsoid // semi-axis. //--- if(this->theSensorID == "Spot 5") { xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Sources/Source_Information/Scene_Source/VIEWING_ANGLE"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << std::endl; } return false; } theViewingAngle = xml_nodes[0]->getText().toDouble(); } else { xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Ephemeris/SATELLITE_ALTITUDE"; theViewingAngle = -1.0; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << std::endl; } return false; } //compute VIEWING_ANGLE double theSatelliteAltitude = xml_nodes[0]->getText().toDouble(); double RT = 63710087714.0; theViewingAngle = asin((RT/(RT+theSatelliteAltitude))*sin(theIncidenceAngle)); } //--- // Fetch Step Count: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Data_Strip/Sensor_Configuration/Mirror_Position/STEP_COUNT"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << std::endl; } return false; } theStepCount = xml_nodes[0]->getText().toInt(); return true; } bool ossimSpotDimapSupportData::initFramePoints( ossimRefPtr xmlDocument) { ossimString xpath; vector > xml_nodes; //--- // Corner points: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Frame/Vertex"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() != 4) { setErrorStatus(); return false; } std::vector >::iterator node = xml_nodes.begin(); while (node != xml_nodes.end()) { ossimGpt gpt; ossimDpt ipt; std::vector > sub_nodes; xpath = "FRAME_LAT"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } gpt.lat = sub_nodes[0]->getText().toDouble(); sub_nodes.clear(); xpath = "FRAME_LON"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } gpt.lon = sub_nodes[0]->getText().toDouble(); gpt.hgt = 0.0; // assumed sub_nodes.clear(); xpath = "FRAME_ROW"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } ipt.line = sub_nodes[0]->getText().toDouble() - 1.0; sub_nodes.clear(); xpath = "FRAME_COL"; (*node)->findChildNodes(xpath, sub_nodes); if (sub_nodes.size() == 0) { setErrorStatus(); return false; } ipt.samp = sub_nodes[0]->getText().toDouble() - 1.0; if (ipt.line < 1.0) if (ipt.samp < 1.0) theUlCorner = gpt; else theUrCorner = gpt; else if (ipt.samp < 1.0) theLlCorner = gpt; else theLrCorner = gpt; ++node; } //--- // Center of frame. //--- theRefGroundPoint.hgt = 0.0; // needs to be looked up xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Frame/Scene_Center/FRAME_LON"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() != 1) { setErrorStatus(); return false; } theRefGroundPoint.lon = xml_nodes[0]->getText().toDouble(); xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Frame/Scene_Center/FRAME_LAT"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() != 1) { setErrorStatus(); return false; } theRefGroundPoint.lat = xml_nodes[0]->getText().toDouble(); //--- // Fetch scene orientation: //--- xml_nodes.clear(); xpath = "/Dimap_Document/Dataset_Frame/SCENE_ORIENTATION"; xmlDocument->findNodes(xpath, xml_nodes); if (xml_nodes.size() == 0) { setErrorStatus(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:\nCould not find: " << xpath << std::endl; } return false; } theSceneOrientation = xml_nodes[0]->getText().toDouble(); return true; } ossim-Miami-2.9.1/src/support_data/ossimSrcRecord.cpp000066400000000000000000000241071352751253100226600ustar00rootroot00000000000000//************************************************************************************************* // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // AUTHOR: Oscar Kramer // // CLASS DESCRIPTION: //! Class used for parsing the command line *.src files. This is a scheme for providing input //! file information to am ossim app such as ossim-orthoigen. //************************************************************************************************* // $Id$ #include #include #include //************************************************************************************************* // Default constructor //************************************************************************************************* ossimSrcRecord::ossimSrcRecord() : m_entryIndex(-1), m_weight(0.0), m_isVectorData(false), m_isRgbData(false), m_autoMinMaxBiasFactor(1.0), m_gamma(1.0) {} //************************************************************************************************* // Constructs given an in-memory KWL and entry index. //************************************************************************************************* ossimSrcRecord::ossimSrcRecord(const ossimKeywordlist& src_kwl, ossim_uint32 index, ossimString prefix_str) : m_entryIndex(-1), m_weight(0.0), m_isVectorData(false), m_isRgbData(false), m_autoMinMaxBiasFactor(1.0), m_gamma(1.0) { prefix_str += ossimString::toString(index) + "."; const char* prefix = prefix_str.chars(); loadState(src_kwl, prefix); } //************************************************************************************************* // METHOD //************************************************************************************************* bool ossimSrcRecord::loadState(const ossimKeywordlist& kwl, const char* prefix) { // Read image filename entry (required): m_rgbFilenames.clear(); m_rgbHistogramPaths.clear(); m_rgbHistogramOps.clear(); m_rgbOverviewPaths.clear(); ossimString lookup = kwl.find(prefix, "r"); if (!lookup.empty()) { m_filename = lookup; m_isRgbData = true; m_rgbFilenames.push_back(lookup); lookup = kwl.find(prefix, "r.hist"); m_rgbHistogramPaths.push_back(lookup.downcase()); lookup = kwl.find(prefix, "r.hist-op"); m_rgbHistogramOps.push_back(lookup.downcase()); lookup = kwl.find(prefix, "r.ovr"); m_rgbOverviewPaths.push_back(lookup); lookup = kwl.find(prefix, "g"); m_rgbFilenames.push_back(lookup); lookup = kwl.find(prefix, "g.hist"); m_rgbHistogramPaths.push_back(lookup.downcase()); lookup = kwl.find(prefix, "g.ovr"); m_rgbOverviewPaths.push_back(lookup); lookup = kwl.find(prefix, "g.hist-op"); m_rgbHistogramOps.push_back(lookup.downcase()); lookup = kwl.find(prefix, "b"); m_rgbFilenames.push_back(lookup); lookup = kwl.find(prefix, "b.hist"); m_rgbHistogramPaths.push_back(lookup.downcase()); lookup = kwl.find(prefix, "b.hist-op"); m_rgbHistogramOps.push_back(lookup.downcase()); lookup = kwl.find(prefix, "b.ovr"); m_rgbOverviewPaths.push_back(lookup); return true; } lookup = kwl.find(prefix, "file"); if (!lookup.empty()) { m_filename = lookup; m_attributesKwl.add(ossimKeywordNames::FILENAME_KW, m_filename.chars()); } else { m_filename.clear(); return false; } // Read image entry index: lookup = kwl.find(prefix, "entry"); if (!lookup.empty()) { m_entryIndex = lookup.toInt32(); m_attributesKwl.add(ossimKeywordNames::ENTRY_KW, m_entryIndex); } else { m_entryIndex = -1; } // Establish supplementary directory containing overview: lookup = kwl.find(prefix, "ovr"); if (!lookup.empty()) { setOverview(ossimFilename(lookup)); } else { m_overviewPath.clear(); } lookup = kwl.find(prefix, "geom"); if (!lookup.empty()) { setGeom(ossimFilename(lookup)); } else { m_geomPath.clear(); } lookup = kwl.find(prefix, "mask"); if (!lookup.empty()) { m_maskPath = ossimFilename(lookup); } else { m_maskPath.clear(); } // Histogram operation for this image: lookup = kwl.find(prefix, "hist"); if (!lookup.empty()) { m_histogramPath = lookup.downcase(); } else { m_histogramPath.clear(); } // Histogram operation for this image: lookup = kwl.find(prefix, "hist-op"); if (!lookup.empty()) { m_histogramOp = lookup.downcase(); } else { m_histogramOp.clear(); } // Newer more generic spec of supp dir since more than just ovrs may reside there: lookup = kwl.find(prefix, "support"); if (!lookup.empty()) { setSupportDir(lookup); } else { m_supportDir.clear(); } // Establish selected bands: lookup = kwl.find(prefix, "rgb"); if (!lookup.empty()) { m_bandList.clear(); //--- // Multiple bands delimited by comma: // // NOTE: Keyword list ONE based. // ossimBandSelector list ZERO based. //--- std::vector bandsStr = lookup.split(","); for (ossim_uint32 i = 0; i < bandsStr.size(); i++) { int band = bandsStr[i].toInt32() - 1; if (band >= 0) m_bandList.push_back((ossim_uint32) band); } } else { m_bandList.clear(); } lookup = kwl.find(prefix, "opacity"); if (!lookup.empty()) m_weight = lookup.toDouble(); lookup = kwl.find(prefix, "gamma"); if(!lookup.empty()) { m_gamma = lookup.toFloat64(); } lookup = kwl.find(prefix, "auto-minmax-bias-factor"); if(!lookup.empty()) { m_autoMinMaxBiasFactor = lookup.toFloat64(); } // Look for vector data info: m_isVectorData = false; ossimString vector_prefix (prefix); vector_prefix += "vector."; ossimKeywordlist vectorKwl; #define DIRECT_KW_MAPPING false if (DIRECT_KW_MAPPING) { // This method of stuffing the attributes KWL is presented here as an example of the way we // should do it: m_attributesKwl.add(kwl, vector_prefix.chars()); } else { // Need to translate SRC keywords to KWs expected by OSSIM: lookup = kwl.find(vector_prefix, "line.color"); if (!lookup.empty()) vectorKwl.add(ossimKeywordNames::PEN_COLOR_KW, lookup); lookup = kwl.find(vector_prefix, "line.width"); if (!lookup.empty()) vectorKwl.add(ossimKeywordNames::THICKNESS_KW, lookup); lookup = kwl.find(vector_prefix, "fill.color"); if (!lookup.empty()) { vectorKwl.add(ossimKeywordNames::FILL_FLAG_KW, true); vectorKwl.add(ossimKeywordNames::BRUSH_COLOR_KW, lookup); } lookup = kwl.find(vector_prefix, "query"); if (!lookup.empty()) vectorKwl.add(ossimKeywordNames::QUERY_KW, lookup); } if (vectorKwl.getSize()) { m_isVectorData = true; m_attributesKwl.add(0, vectorKwl); } // Read keywords associated with special pixel remapping (pixel flipping, clamping, and // clipping): lookup = kwl.find(prefix, "replacement_mode"); if (!lookup.empty()) m_pixelFlipParams.replacementMode = lookup; lookup = kwl.find(prefix, "clamp.min"); if (!lookup.empty()) m_pixelFlipParams.clampMin = lookup.toDouble(); lookup = kwl.find(prefix, "clamp.max"); if (!lookup.empty()) m_pixelFlipParams.clampMax = lookup.toDouble(); lookup = kwl.find(prefix, "clip.min"); if (!lookup.empty()) m_pixelFlipParams.clipMin = lookup.toDouble(); lookup = kwl.find(prefix, "clip.max"); if (!lookup.empty()) m_pixelFlipParams.clipMax = lookup.toDouble(); return true; } //************************************************************************************************* // Sets supplementary data files dir. If the OVR and/or hist dirs are undefined, they are also // set to this path. //************************************************************************************************* void ossimSrcRecord::setSupportDir(const ossimFilename& f) { m_supportDir = f; m_attributesKwl.add("supplementary_directory", f.c_str()); // if (m_overviewPath.empty()) // setOverview(m_supportDir); if (m_histogramPath.empty()) m_histogramPath = m_supportDir; if (m_maskPath.empty()) m_maskPath = m_supportDir; // if(m_geomPath.empty()) // m_geomPath = m_supportDir; } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimSrcRecord::setFilename(const ossimFilename& f) { m_filename = f; m_attributesKwl.add(ossimKeywordNames::FILENAME_KW, m_filename.chars()); } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimSrcRecord::setEntryIndex(ossim_int32 i) { m_entryIndex = i; m_attributesKwl.add(ossimKeywordNames::ENTRY_KW, m_entryIndex); } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimSrcRecord::setOverview(const ossimFilename& f) { m_overviewPath = f; m_attributesKwl.add(ossimKeywordNames::OVERVIEW_FILE_KW, m_overviewPath.chars()); } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimSrcRecord::setGeom(const ossimFilename& f) { m_geomPath = f; m_attributesKwl.add(ossimKeywordNames::GEOM_FILE_KW, m_overviewPath.chars()); } ossim-Miami-2.9.1/src/support_data/ossimSrtmFilename.cpp000066400000000000000000000140371352751253100233610ustar00rootroot00000000000000#include #include ossimSrtmFilename::ossimSrtmFilename(const ossimFilename& srtmFilename) { setFilename(srtmFilename); } ossimGpt ossimSrtmFilename::ul()const { ossimGpt result; if((ossim::isnan(theSouthwestLongitude)) || (ossim::isnan(theSouthwestLatitude))) { result.makeNan(); } else { result.latd(theSouthwestLatitude+1.0); result.lond(theSouthwestLongitude); } return result; } ossimGpt ossimSrtmFilename::ur()const { ossimGpt result; if((ossim::isnan(theSouthwestLongitude)) || (ossim::isnan(theSouthwestLatitude)) ) { result.makeNan(); } else { result.latd(theSouthwestLatitude+1.0); result.lond(theSouthwestLongitude+1.0); } return result; } ossimGpt ossimSrtmFilename::lr()const { ossimGpt result; if((ossim::isnan(theSouthwestLongitude)) || (ossim::isnan(theSouthwestLatitude)) ) { result.makeNan(); } else { result.latd(theSouthwestLatitude); result.lond(theSouthwestLongitude+1.0); } return result; } ossimGpt ossimSrtmFilename::ll()const { ossimGpt result; if((ossim::isnan(theSouthwestLongitude)) || (ossim::isnan(theSouthwestLatitude)) ) { result.makeNan(); } else { result.latd(theSouthwestLatitude); result.lond(theSouthwestLongitude); } return result; } bool ossimSrtmFilename::setFilename(const ossimFilename& srtmFilename) { theFilename = srtmFilename; theSouthwestLongitude = ossim::nan(); theSouthwestLatitude = ossim::nan(); if(srtmFilename == "") return false; ossimFilename f = theFilename.fileNoExtension(); ossimString regularExp1 = "[N|S][0-9][0-9][E|W][0-9][0-9][0-9]"; ossimString regularExp2 = "[E|W][0-9][0-9][0-9][N|S][0-9][0-9]"; ossimRegExp regEx; bool latLonOrderFlag = true; bool foundFlag = false; f = f.upcase(); regEx.compile(regularExp1.c_str()); foundFlag = regEx.find(f.c_str()); if(!foundFlag) { regEx.compile(regularExp2.c_str()); foundFlag = regEx.find(f.c_str()); if(foundFlag) { latLonOrderFlag = false; f = ossimFilename(ossimString(f.begin()+regEx.start(), f.begin()+regEx.end())); } } if(foundFlag) { f = ossimFilename(ossimString(f.begin()+regEx.start(), f.begin()+regEx.end())); } if (f.size() != 7) { return false; } // ossimString s; if(latLonOrderFlag) { // s.push_back(f[1]); // s.push_back(f[2]); theSouthwestLatitude = ossimString(f.begin()+1, f.begin()+3).toDouble();//s.toDouble(); // Get the latitude. if (f[static_cast(0)] == 'S') { theSouthwestLatitude *= -1; } else if (f[static_cast(0)] != 'N') { return false; // Must be either 's' or 'n'. } // Get the longitude. // s.clear(); // s.push_back(f[4]); // s.push_back(f[5]); // s.push_back(f[6]); theSouthwestLongitude = ossimString(f.begin()+4, f.begin()+7).toDouble();//s.toDouble(); if (f[static_cast(3)] == 'W') { theSouthwestLongitude *= -1; } else if (f[static_cast(3)] != 'E') { return false; // Must be either 'e' or 'w'. } } else { // Get the longitude. // s.clear(); // s.push_back(f[1]); // s.push_back(f[2]); // s.push_back(f[3]); theSouthwestLongitude = ossimString(f.begin()+1, f.begin()+4).toDouble();//s.toDouble(); if (f[static_cast(0)] == 'W') { theSouthwestLongitude *= -1; } else if (f[static_cast(0)] != 'E') { return false; // Must be either 'e' or 'w'. } // s.clear(); // s.push_back(f[5]); // s.push_back(f[6]); theSouthwestLatitude = ossimString(f.begin()+5, f.begin()+7).toDouble();//s.toDouble(); // Get the latitude. if (f[static_cast(4)] == 'S') { theSouthwestLatitude *= -1; } else if (f[static_cast(4)] != 'N') { return false; // Must be either 's' or 'n'. } } // if(latLonOrderFlag) // { // s.push_back(f[1]); // s.push_back(f[2]); // theSouthwestLatitude = s.toDouble(); // // Get the latitude. // if (f[0] == 'S') // { // theSouthwestLatitude *= -1; // } // else if (f[0] != 'N') // { // return false; // Must be either 's' or 'n'. // } // // Get the longitude. // s.clear(); // s.push_back(f[4]); // s.push_back(f[5]); // s.push_back(f[6]); // theSouthwestLongitude = s.toDouble(); // if (f[3] == 'W') // { // theSouthwestLongitude *= -1; // } // else if (f[3] != 'E') // { // return false; // Must be either 'e' or 'w'. // } // } // else // { // // Get the longitude. // s.clear(); // s.push_back(f[1]); // s.push_back(f[2]); // s.push_back(f[3]); // theSouthwestLongitude = s.toDouble(); // if (f[0] == 'W') // { // theSouthwestLongitude *= -1; // } // else if (f[0] != 'E') // { // return false; // Must be either 'e' or 'w'. // } // s.clear(); // s.push_back(f[5]); // s.push_back(f[6]); // theSouthwestLatitude = s.toDouble(); // // Get the latitude. // if (f[4] == 'S') // { // theSouthwestLatitude *= -1; // } // else if (f[4] != 'N') // { // return false; // Must be either 's' or 'n'. // } // } return true; } ossim-Miami-2.9.1/src/support_data/ossimSrtmSupportData.cpp000066400000000000000000000545451352751253100241170ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: // // Support data class for a Shuttle Radar Topography Mission (SRTM) file. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Static trace for debugging static ossimTrace traceDebug("ossimSrtmSupportData:debug"); //--- // Start with the min and max at some default setting. // Mt. Everest highest elev point on Earth 8850 meters. //--- static const ossim_float64 DEFAULT_MIN = -8850.0; static const ossim_float64 DEFAULT_MAX = 8850.0; ossimSrtmSupportData::ossimSrtmSupportData() : m_file(), m_numberOfLines(0), m_numberOfSamples(0), m_southwestLatitude(ossim::nan()), m_southwestLongitude(ossim::nan()), m_latSpacing(ossim::nan()), m_lonSpacing(ossim::nan()), m_minPixelValue(DEFAULT_MIN), m_maxPixelValue(DEFAULT_MAX), m_scalarType(OSSIM_SCALAR_UNKNOWN), m_str(0) { } ossimSrtmSupportData::~ossimSrtmSupportData() { } bool ossimSrtmSupportData::setFilename(const ossimFilename& srtmFile, bool scanForMinMax) { m_file = srtmFile; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSrtmSupportData::setFilename: entered:" << "\nsrtmFile: " << srtmFile << "\nscanForMinMax flag: " << scanForMinMax << std::endl; } m_str = ossim::StreamFactoryRegistry::instance()-> createIstream(m_file); if (m_str) { if(m_str->fail()) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << m_file << " does not exist: leaving ..." << std::endl; } clear(); return false; } } else { return false; } // Start with default. m_minPixelValue = DEFAULT_MIN; m_maxPixelValue = DEFAULT_MAX; // See if we have an ossim metadata file to initialize from. bool outputOmd = false; bool loadedFromOmd = false; ossimFilename omdFile = m_file; omdFile.setExtension(ossimString("omd")); if (omdFile.exists()) { //--- // The loadOmd is called instead of loadState so m_file is not // overwrote. //--- ossimKeywordlist kwl(omdFile); loadedFromOmd = loadOmd(kwl); } if (!loadedFromOmd) { if (!setCornerPoints()) { clear(); return false; } if (!setSize()) { clear(); return false; } outputOmd = true; } if (scanForMinMax) { // These could have been picked up in the loadOmd. if ( (m_minPixelValue == DEFAULT_MIN) || (m_maxPixelValue == DEFAULT_MAX) ) { if ( computeMinMax() ) { outputOmd = true; } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Unable to compute min max: leaving ..." << std::endl; } clear(); return false; } } } //--- // NOTE: The outputOmd flag should probably be set if !loadedFromOmd. // Leaving as is for now (only set if scanForMinMax). //--- if (outputOmd) { ossimKeywordlist kwl; saveState(kwl); kwl.write(omdFile); } m_str = 0; // if(m_str->is_open()) // { // m_str->close(); // } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << *this << std::endl; } return true; } ossimFilename ossimSrtmSupportData::getFilename() const { return m_file; } ossim_uint32 ossimSrtmSupportData::getNumberOfLines() const { return m_numberOfLines; } ossim_uint32 ossimSrtmSupportData::getNumberOfSamples() const { return m_numberOfSamples; } bool ossimSrtmSupportData::getImageGeometry(ossimKeywordlist& kwl, const char* prefix) { if (m_file == ossimFilename::NIL) { return false; } kwl.add(prefix, ossimKeywordNames::TYPE_KW, "ossimEquDistCylProjection", true); kwl.add(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW, 0.0, true); kwl.add(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW, m_southwestLongitude, true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LAT_KW, (m_southwestLatitude+1.0), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LON_KW, m_southwestLongitude, true); // Add the pixel scale. kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, m_latSpacing, true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, m_lonSpacing, true); // Add the datum. (always WGS-84 per spec) kwl.add(prefix, ossimKeywordNames::DATUM_KW, ossimDatumFactory::instance()->wgs84()->code(), true); // Add the number of lines and samples. kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, m_numberOfLines, true); kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, m_numberOfSamples, true); return true; } ossimRefPtr ossimSrtmSupportData::getProjection() const { //--- // Make an Equidistant Cylindrical projection with a origin at the equator // since the DTED post spacing is considered to be square. //--- const ossimDatum* datum = ossimDatumFactory::instance()->wgs84(); ossimRefPtr eq = new ossimEquDistCylProjection(*(datum->ellipsoid())); //--- // Set the tie point. // NOTE: Latitude southwest corner we need northwest; hence, the +1. //--- eq->setUlTiePoints( ossimGpt(m_southwestLatitude+1.0, m_southwestLongitude, 0.0, datum) ); // Set the scale: eq->setDecimalDegreesPerPixel( ossimDpt(m_lonSpacing, m_latSpacing) ); ossimRefPtr proj = eq.get(); return proj; } bool ossimSrtmSupportData::saveState(ossimKeywordlist& kwl, const char* prefix) const { if (m_file == ossimFilename::NIL) { return false; } ossimString bandPrefix; if (prefix) { bandPrefix = prefix; } bandPrefix += "band1."; kwl.add(prefix, ossimKeywordNames::FILENAME_KW, m_file.c_str(), true); kwl.add(prefix, ossimKeywordNames::NUMBER_BANDS_KW, 1, true); kwl.add(prefix, ossimKeywordNames::NUMBER_LINES_KW, m_numberOfLines, true); kwl.add(prefix, ossimKeywordNames::NUMBER_SAMPLES_KW, m_numberOfSamples, true); //--- // Special case, store the tie point as the upper left lat so add one. //--- kwl.add(prefix, ossimKeywordNames::TIE_POINT_LAT_KW, (m_southwestLatitude + 1.0), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LON_KW, m_southwestLongitude, true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, m_latSpacing, true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, m_lonSpacing, true); // User can opt out of scanning for this so don't save if it is still nan. if (m_minPixelValue != DEFAULT_MIN) { kwl.add(bandPrefix, ossimKeywordNames::MIN_VALUE_KW, m_minPixelValue, true); } // User can opt out of scanning for this so don't save if it is still nan. if (m_maxPixelValue != DEFAULT_MAX) { kwl.add(bandPrefix.c_str(), ossimKeywordNames::MAX_VALUE_KW, m_maxPixelValue, true); } // constant kwl.add(bandPrefix, ossimKeywordNames::NULL_VALUE_KW, "-32768", true); // constant kwl.add(prefix, ossimKeywordNames::BYTE_ORDER_KW, "big_endian", true); // constant kwl.add(prefix, ossimKeywordNames::SCALAR_TYPE_KW, ossimScalarTypeLut::instance()->getEntryString(m_scalarType), true); return true; } bool ossimSrtmSupportData::loadState(const ossimKeywordlist& kwl, const char* prefix) { ossimString bandPrefix; if (prefix) { bandPrefix = prefix; } bandPrefix += "band1."; ossimString s; // For numeric conversions. const char* lookup; // Look for "filename" then look for deprecated "image_file" next. lookup = kwl.find(prefix, ossimKeywordNames::FILENAME_KW); if (lookup) { m_file = lookup; } else { // Deprecated... lookup = kwl.find(prefix, ossimKeywordNames::IMAGE_FILE_KW); if (lookup) { m_file = lookup; } else { return false; } } return loadOmd(kwl, prefix); } bool ossimSrtmSupportData::loadOmd(const ossimKeywordlist& kwl, const char* prefix) { std::string pfx; std::string bandPrefix; if (prefix) // Cannot give null to std::string. { pfx = prefix; bandPrefix = prefix; } bandPrefix += "band1."; ossimString value; //--- // Look for the min and max first since they could have been populated by // "cmm" (compute min max). Min and Max are not required by this method // as they are handled elsewhere if they are not found here. //--- // Not an error if not present. value.string() = kwl.findKey(bandPrefix, std::string(ossimKeywordNames::MIN_VALUE_KW)); if ( value.size() ) { m_minPixelValue = value.toFloat64(); } // Not an error if not present. value.string() = kwl.findKey(bandPrefix.c_str(), std::string(ossimKeywordNames::MAX_VALUE_KW)); if ( value.size() ) { m_maxPixelValue = value.toFloat64(); } value.string() = kwl.findKey(pfx, std::string(ossimKeywordNames::NUMBER_LINES_KW)); if ( value.size() ) { m_numberOfLines = value.toUInt32(); } else { return false; } value.string() = kwl.findKey(pfx, std::string(ossimKeywordNames::NUMBER_SAMPLES_KW)); if ( value.size() ) { m_numberOfSamples = value.toUInt32(); } else { return false; } //--- // Special case the tie point was stored as the upper left so we must // subtract one. //--- value.string() = kwl.findKey(pfx, std::string(ossimKeywordNames::TIE_POINT_LAT_KW)); if ( value.size() ) { m_southwestLatitude = value.toFloat64() - 1.0; } else { return false; } value.string() = kwl.findKey(pfx, std::string(ossimKeywordNames::TIE_POINT_LON_KW)); if ( value.size() ) { m_southwestLongitude = value.toFloat64(); } else { return false; } int scalar = ossimScalarTypeLut::instance()->getEntryNumber(kwl, prefix); if (scalar != ossimLookUpTable::NOT_FOUND) { m_scalarType = (ossimScalarType)scalar; if((m_scalarType != OSSIM_FLOAT32) && (m_scalarType != OSSIM_SINT16)) { return false; } } else { return false; } m_latSpacing = 1.0 / (m_numberOfLines - 1); m_lonSpacing = 1.0 / (m_numberOfSamples - 1); return true; } ossim_float64 ossimSrtmSupportData::getSouthwestLatitude() const { return m_southwestLatitude; } ossim_float64 ossimSrtmSupportData::getSouthwestLongitude() const { return m_southwestLongitude; } ossim_float64 ossimSrtmSupportData::getLatitudeSpacing() const { return m_latSpacing; } ossim_float64 ossimSrtmSupportData::getLongitudeSpacing() const { return m_lonSpacing; } void ossimSrtmSupportData::clear() { m_file = ossimFilename::NIL; m_numberOfLines = 0; m_numberOfSamples = 0; m_southwestLatitude = ossim::nan(); m_southwestLongitude = ossim::nan(); m_latSpacing = ossim::nan(); m_lonSpacing = ossim::nan(); m_minPixelValue = DEFAULT_MIN; m_maxPixelValue = DEFAULT_MAX; } bool ossimSrtmSupportData::setCornerPoints() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSrtmSupportData::setCornerPoints(): entered..." << std::endl; } ossimFilename f = m_file.fileNoExtension(); ossimString regularExp1 = "[N|S][0-9][0-9][E|W][0-9][0-9][0-9]"; ossimString regularExp2 = "[E|W][0-9][0-9][0-9][N|S][0-9][0-9]"; ossimRegExp regEx; bool latLonOrderFlag = true; bool foundFlag = false; f = f.upcase(); regEx.compile(regularExp1.c_str()); foundFlag = regEx.find(f.c_str()); if(!foundFlag) { regEx.compile(regularExp2.c_str()); foundFlag = regEx.find(f.c_str()); if(foundFlag) { latLonOrderFlag = false; f = ossimFilename(ossimString(f.begin()+regEx.start(), f.begin()+regEx.end())); } } if(foundFlag) { f = ossimFilename(ossimString(f.begin()+regEx.start(), f.begin()+regEx.end())); } if (f.size() != 7) { return false; } // ossimString s; if(latLonOrderFlag) { // s.push_back(f[1]); // s.push_back(f[2]); m_southwestLatitude = ossimString(f.begin()+1, f.begin()+3).toDouble();//s.toDouble(); // Get the latitude. if (f[static_cast(0)] == 'S') { m_southwestLatitude *= -1; } else if (f[static_cast(0)] != 'N') { return false; // Must be either 's' or 'n'. } // Get the longitude. // s.clear(); // s.push_back(f[4]); // s.push_back(f[5]); // s.push_back(f[6]); m_southwestLongitude = ossimString(f.begin()+4, f.begin()+7).toDouble();//s.toDouble(); if (f[static_cast(3)] == 'W') { m_southwestLongitude *= -1; } else if (f[static_cast(3)] != 'E') { return false; // Must be either 'e' or 'w'. } } else { // Get the longitude. // s.clear(); // s.push_back(f[1]); // s.push_back(f[2]); // s.push_back(f[3]); m_southwestLongitude = ossimString(f.begin()+1, f.begin()+4).toDouble();//s.toDouble(); if (f[static_cast(0)] == 'W') { m_southwestLongitude *= -1; } else if (f[static_cast(0)] != 'E') { return false; // Must be either 'e' or 'w'. } // s.clear(); // s.push_back(f[5]); // s.push_back(f[6]); m_southwestLatitude = ossimString(f.begin()+5, f.begin()+7).toDouble();//s.toDouble(); // Get the latitude. if (f[static_cast(4)] == 'S') { m_southwestLatitude *= -1; } else if (f[static_cast(4)] != 'N') { return false; // Must be either 's' or 'n'. } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSrtmSupportData::setCornerPoints(): leaving with true..." << std::endl; } return true; } bool ossimSrtmSupportData::setSize() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSrtmSupportData::setSize(): entered..." << std::endl; } if(!m_str) { m_str = ossim::StreamFactoryRegistry::instance()->createIstream( m_file); } if (!m_str) { return false; } if(m_str->fail()) { return false; } ossim_float64 size = 0.0; m_str->seekg(0, std::ios::beg); #if 0 /* tmp drb */ if(m_str->isCompressed()) { ossimFilename tmp = m_file; tmp.setExtension("hgt"); if(!tmp.exists()) { ossimOFStream out(tmp.c_str(), std::ios::out|std::ios::binary); if(!out.fail()) { bool done = false; char buf[1024]; while(!done&&!m_str->fail()) { m_str->read(buf, 1024); if(m_str->gcount() < 1024) { done = true; } if(m_str->gcount() > 0) { out.write(buf, m_str->gcount()); } } out.close(); size = tmp.fileSize(); tmp.remove(); } } } else { size = m_file.fileSize(); } #endif /* tmp drb */ size = m_file.fileSize(); if (!size) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSrtmSupportData::setSize(): leaving with false at line " << __LINE__ << std::endl; } return false; } m_scalarType = OSSIM_SCALAR_UNKNOWN; //--- // Assuming square for now. Have to check the spec for this. //--- if (size == 25934402) // 2 * 3601 * 3601 three arc second { m_numberOfLines = 3601; m_numberOfSamples = 3601; m_scalarType = OSSIM_SINT16; } else if(size == 51868804) // 4*3601*3601 { m_numberOfLines = 3601; m_numberOfSamples = 3601; m_scalarType = OSSIM_FLOAT32; } else if (size == 2884802) // 2 * 1201 * 1201 one arc second { m_numberOfLines = 1201; m_numberOfSamples = 1201; m_scalarType = OSSIM_SINT16; } else if (size == 5769604) { m_numberOfLines = 1201; m_numberOfSamples = 1201; m_scalarType = OSSIM_FLOAT32; } else // try to get a square width and height { ossim_uint64 lines = (ossim_uint64)sqrt((ossim_float64)(size / 2)); ossim_uint64 samples = (ossim_uint64)sqrt((ossim_float64)(size / 2)); // check square if(lines*samples*2 == size) { m_numberOfLines = lines; m_numberOfSamples = samples; m_scalarType = OSSIM_SINT16; } else { ossim_uint64 lines = (ossim_uint64)sqrt((ossim_float64)(size / 4)); ossim_uint64 samples = (ossim_uint64)sqrt((ossim_float64)(size / 4)); // check square if(lines*samples*4 == size) { m_numberOfLines = lines; m_numberOfSamples = samples; m_scalarType = OSSIM_FLOAT32; } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSrtmSupportData::setSize(): leaving with false at line " << __LINE__ << std::endl; } return false; } } } m_latSpacing = 1.0 / (m_numberOfLines - 1); m_lonSpacing = 1.0 / (m_numberOfSamples - 1); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimSrtmSupportData::setSize(): leaving with true..." << std::endl; } m_str=0; return true; } bool ossimSrtmSupportData::computeMinMax() { if(m_scalarType == OSSIM_FLOAT32) { return computeMinMaxTemplate((ossim_float32)0, -32768.0); } return computeMinMaxTemplate((ossim_sint16)0, -32768.0); } template bool ossimSrtmSupportData::computeMinMaxTemplate(T /* dummy */, double defaultNull) { if(!m_str) { m_str = ossim::StreamFactoryRegistry::instance()->createIstream( m_file); } if (!m_str) { return false; } if(m_str->fail()) { return false; } const size_t BYTES_IN_LINE = m_numberOfSamples * 2; const T NULL_PIX = (T)defaultNull; double minValue = 1.0/FLT_EPSILON; double maxValue = -1.0/FLT_EPSILON; T* line_buf = new T[m_numberOfSamples]; char* char_buf = (char*)line_buf; ossimEndian swapper; ossimByteOrder endianType = ossim::byteOrder(); for (ossim_uint32 line = 0; line < m_numberOfLines; ++line) { m_str->read(char_buf, (std::streamsize)BYTES_IN_LINE); if(endianType == OSSIM_LITTLE_ENDIAN) { swapper.swap(line_buf, m_numberOfSamples); } for (ossim_uint32 sample = 0; sample < m_numberOfSamples; ++sample) { if (line_buf[sample] == NULL_PIX) continue; if (line_buf[sample] > maxValue) maxValue = line_buf[sample]; if (line_buf[sample] < minValue) minValue = line_buf[sample]; } } delete [] line_buf; m_minPixelValue = minValue; m_maxPixelValue = maxValue; m_str = 0; return true; } ossim_float64 ossimSrtmSupportData::getMinPixelValue() const { return m_minPixelValue; } ossim_float64 ossimSrtmSupportData::getMaxPixelValue() const { return m_maxPixelValue; } ossimScalarType ossimSrtmSupportData::getScalarType()const { return m_scalarType; } std::ostream& ossimSrtmSupportData::print(std::ostream& out) const { out << std::setprecision(15) << "ossimSrtmSupportData data members:" << "\nFile: " << m_file << "\nLines: " << m_numberOfLines << "\nSamples: " << m_numberOfSamples << "\nSouth West Latitude: " << m_southwestLatitude << "\nSouth West Longitude: " << m_southwestLongitude << "\nLatitude spacing: " << m_latSpacing << "\nLongitude spacing: " << m_lonSpacing << "\nMin post value: " << m_minPixelValue << "\nMax post value: " << m_maxPixelValue << std::endl; return out; } ossim-Miami-2.9.1/src/support_data/ossimSupportFilesList.cpp000066400000000000000000000030151352751253100242600ustar00rootroot00000000000000//************************************************************************************************** // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // // Description: Singleton class for logging all support data files opened during a session. // //************************************************************************************************** // $Id$ #include #include ossimSupportFilesList* ossimSupportFilesList::m_instance = 0; //************************************************************************************************* // Implements singleton pattern //************************************************************************************************* ossimSupportFilesList* ossimSupportFilesList::instance() { if (!m_instance) m_instance = new ossimSupportFilesList; return m_instance; } //************************************************************************************************* // Saves the list to a KWL //************************************************************************************************* void ossimSupportFilesList::save(ossimKeywordlist& kwl, const char* prefix) const { ossimString baseName ("support_file"); for (unsigned int i=0; i< (unsigned int) m_list.size(); i++) { ossimString key = baseName + ossimString::toString(i); kwl.add(prefix, key.chars(), m_list[i]); } } ossim-Miami-2.9.1/src/support_data/ossimTiffInfo.cpp000066400000000000000000003351261352751253100225040ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: TIFF Info object. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Static trace for debugging static ossimTrace traceDebug("ossimTiffInfo:debug"); static ossimTrace traceDump("ossimTiffInfo:dump"); // This will dump offsets. static const std::string PHOTO_INTERP[] = { "MINISWHITE", "MINISBLACK", "RGB", "PALETTE", "MASK", "SEPARATED", "YCBCR", "CIELAB", "ICCLAB", "ITULAB" }; static const std::string ANGULAR_UNITS_KW = "angular_units"; static const std::string CENTER_LATITUDE__KW = "center_latitude"; static const std::string CENTER_LONGITUDE_KW = "center_longitude"; static const std::string COORD_TRANS_CODE_KW = "coord_trans_code"; static const std::string FALSE_ORIGIN_LONGITUDE_KW = "false_origin_longitude"; static const std::string FALSE_ORIGIN_LATITUDE_KW = "false_origin_latitude"; static const std::string FALSE_ORIGIN_EASTING_KW = "false_origin_easting"; static const std::string FALSE_ORIGIN_NORTHING_KW = "false_origin_northing"; static const std::string GEODETIC_DATUM_KW = "geodetic_datum"; static const std::string IMAGE_LENGTH_KW = "image_length"; static const std::string IMAGE_WIDTH_KW = "image_width"; static const std::string LINEAR_UNITS_KW = "linear_units"; static const std::string MODEL_PIXEL_SCALE_KW = "model_pixel_scale"; static const std::string MODEL_TIE_POINT_KW = "model_tie_point"; static const std::string MODEL_TRANSFORM_KW = "model_transform"; static const std::string MODEL_TYPE_KW = "model_type"; static const std::string ORIGIN_LATITUDE_KW = "origin_latitude"; static const std::string ORIGIN_LONGITUDE_KW = "origin_longitude"; static const std::string RASTER_TYPE_KW = "raster_type"; static const std::string VERTICAL_UNITS_KW = "vertical_units"; ossimTiffInfo::ossimTiffInfo() : ossimInfoBase(), m_connectionString(), m_endian(0) { } ossimTiffInfo::~ossimTiffInfo() { if (m_endian) { delete m_endian; m_endian = 0; } } bool ossimTiffInfo::open(const ossimFilename &file) { std::shared_ptr inStream = ossim::StreamFactoryRegistry::instance()->createIstream(file.c_str()); if (!inStream) return false; return open(inStream, file.c_str()); } bool ossimTiffInfo::open(std::shared_ptr &str, const std::string &connectionString) { bool result = false; //--- // Open the tif file. //--- //std::ifstream str(file.c_str(), std::ios_base::binary|std::ios_base::in); if (str && str->good()) { //--- // Get the byte order. First two byte should be "II" or "MM". //--- char byteOrder[2]; str->read(byteOrder, 2); // Read the byte order. ossimByteOrder sysByteOrder = ossim::byteOrder(); ossimByteOrder tifByteOrder = OSSIM_LITTLE_ENDIAN; if (byteOrder[0] == 'M') { tifByteOrder = OSSIM_BIG_ENDIAN; } if (sysByteOrder != tifByteOrder) { if (!m_endian) { m_endian = new ossimEndian(); } } else if (m_endian) { delete m_endian; m_endian = 0; } //-- // Get the version. Note m_endian must be set/unset before calling // "readShort". //--- ossim_uint16 version; readShort(version, *str); if (((byteOrder[0] == 'M') || (byteOrder[0] == 'I')) && ((version == 42) || (version == 43))) { result = true; // is a tif... } } if (result) { m_connectionString = connectionString; m_inputStream = str; } else { m_connectionString.clear(); if (m_endian) { delete m_endian; m_endian = 0; } } return result; } std::ostream &ossimTiffInfo::print(std::ostream &out) const { static const char MODULE[] = "ossimTiffInfo::print"; // std::cout << "-------------------------------\n"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG Entered...\n"; } //--- // Open the tif file. //--- // std::ifstream str(theFile.c_str(), std::ios_base::binary|std::ios_base::in); if (!m_inputStream) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " Cannot open file: " << m_connectionString << std::endl; } return out; } //--- // Get the byte order. First two byte should be "II" or "MM". //--- char byteOrder[2]; m_inputStream->seekg(0); m_inputStream->clear(); m_inputStream->read(byteOrder, 2); // Read the byte order. ossimByteOrder sysByteOrder = ossim::byteOrder(); ossimByteOrder tifByteOrder = OSSIM_LITTLE_ENDIAN; if (byteOrder[0] == 'M') { tifByteOrder = OSSIM_BIG_ENDIAN; } if (sysByteOrder != tifByteOrder) { if (!m_endian) { m_endian = new ossimEndian(); } } else if (m_endian) { delete m_endian; m_endian = 0; } //-- // Get the version. Note m_endian must be set/unset before calling // "readShort". //--- ossim_uint16 version; readShort(version, *m_inputStream); // Set the tag value length. ossim_uint64 tagValueLength; if (version == 42) { tagValueLength = 4; } else { tagValueLength = 8; } out << "tiff.version: " << int(version) << ((version == 42) ? "(classic)\n" : "(big)\n") << "tiff.byte_order: "; if (byteOrder[0] == 'M') { out << "big_endian\n"; } else // OSSIM_LITTLE_ENDIAN { out << "little_endian\n"; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "system_byte_order: "; if (ossim::byteOrder() == OSSIM_BIG_ENDIAN) { ossimNotify(ossimNotifyLevel_DEBUG) << "big_endian\n"; } else // OSSIM_LITTLE_ENDIAN { ossimNotify(ossimNotifyLevel_DEBUG) << "little_endian\n"; } ossimNotify(ossimNotifyLevel_DEBUG) << "tiff.tag_value_length: " << tagValueLength << "\n"; } //--- // Variables used within the loop. //--- std::streamoff seekOffset; // used throughout std::streampos streamPosition; // used throughout if (version == 43) { // We must skip the first four bytes. ossim_uint32 offsetSize; readLong(offsetSize, *m_inputStream); } // Get the offset. if (getOffset(seekOffset, *m_inputStream, version) == false) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL ERROR - " << "No offset to an image file directory found.\n" << "Returning with error." << std::endl; return out; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG: " << "Offset to first ifd: " << seekOffset << "\n"; } // Capture the original flags then set float output to full precision. std::ios_base::fmtflags f = out.flags(); out << std::setprecision(15); // Image File Directory (IFD) loop. ossim_int32 ifdIndex = 0; while (seekOffset) { // directory prefix for prints. std::string prefix = "tiff."; getDirPrefix(ifdIndex, prefix); out << prefix << "directory_offset: " << seekOffset << "\n"; // Seek to the image file directory. m_inputStream->seekg(seekOffset, std::ios_base::beg); //--- // Things we need to save for printGeoKeys: //--- ossim_uint16 *geoKeyBlock = 0; ossim_uint64 geoKeyLength = 0; ossim_float64 *geoDoubleBlock = 0; ossim_uint64 geoDoubleLength = 0; ossim_int8 *geoAsciiBlock = 0; ossim_uint64 geoAsciiLength = 0; //--- // Get the number of directories within the IFD. //--- ossim_uint64 nTags; // Number of tags in an IFD. if (getValue(nTags, *m_inputStream, TWO_OR_EIGHT, version) == false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL error reading number of directories." << std::endl; } m_inputStream.reset(); return out; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:\n" << "ifd: " << seekOffset << "\ntags in directory: " << nTags << "\n"; } // Tag loop: for (ossim_uint64 tagIdx = 0; tagIdx < nTags; ++tagIdx) { // Variables used within the loop. ossim_uint16 tag = 0; // Tag number ossim_uint16 type = 0; // Type(short, long...) ossim_uint64 count = 0; ossim_uint64 arraySizeInBytes = 0; // ossim_uint8 *valueArray = 0; // To hold value. //--- // Get the tag. //--- readShort(tag, *m_inputStream); if (!m_inputStream->good()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL error reading tag number." << std::endl; } return out; } //--- // Get the type (byte, ascii, short...) //--- readShort(type, *m_inputStream); if (!m_inputStream->good()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL error reading type number." << std::endl; } m_inputStream.reset(); return out; } //--- // Get the count. This is not in bytes. It is based on the // type. So if the type is a short and the count is one then // read "sizeof(short"(2) bytes. //--- getValue(count, *m_inputStream, FOUR_OR_EIGHT, version); if (!m_inputStream->good()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL error reading count." << std::endl; } m_inputStream.reset(); return out; } // Get the array size in bytes. arraySizeInBytes = getArraySizeInBytes(count, type); if (arraySizeInBytes == 0) { // Could be an unhandle type. Gobble the value. eatValue(*m_inputStream, version); } else { // Allocate array. if (valueArray) delete[] valueArray; valueArray = new ossim_uint8[arraySizeInBytes]; if (arraySizeInBytes <= tagValueLength) { // Read in the value(s). m_inputStream->read((char *)valueArray, arraySizeInBytes); // Skip any byes left in the field. if (arraySizeInBytes < tagValueLength) { // Skip these bytes. m_inputStream->ignore(tagValueLength - arraySizeInBytes); } } else // Data to big for field. Stored elsewhere... { // Get the offset to the data. getOffset(seekOffset, *m_inputStream, version); // Capture the seek position to come back to. streamPosition = m_inputStream->tellg(); // Seek to the data. m_inputStream->seekg(seekOffset, std::ios_base::beg); // Read in the value(s). m_inputStream->read((char *)valueArray, arraySizeInBytes); // Seek back. m_inputStream->seekg(streamPosition); } // Swap the bytes if needed. swapBytes(valueArray, type, count); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\ntag[" << tagIdx << "]:" << tag << "\ntype: " << type << "\ncount: " << count << "\narray size in bytes: " << arraySizeInBytes << "\n"; } if (tag == ossim::OGEO_KEY_DIRECTORY_TAG) { // tag 34735 save for printGeoKeys if (geoKeyBlock) { delete[] geoKeyBlock; } geoKeyBlock = reinterpret_cast(valueArray); geoKeyLength = count; } else if (tag == ossim::OGEO_DOUBLE_PARAMS_TAG) { // tag 34736 save for printGeoKeys if (geoDoubleBlock) { delete[] geoDoubleBlock; } geoDoubleBlock = reinterpret_cast(valueArray); geoDoubleLength = count; } else if (tag == ossim::OGEO_ASCII_PARAMS_TAG) { // tag 34737 save for printGeoKeys if (geoAsciiBlock) { delete[] geoAsciiBlock; } geoAsciiBlock = reinterpret_cast(valueArray); geoAsciiLength = count; } else { print(out, prefix, tagIdx, tag, type, count, arraySizeInBytes, valueArray); // Free memory if allocated... if (valueArray) { delete[] valueArray; valueArray = 0; } } } // End of tag loop. //--- // If Geotiff Keys read them. // This had to done last since the keys could // have references to tags GEO_DOUBLE_PARAMS_TAG and // GEO_ASCII_PARAMS_TAG. //--- if (geoKeyBlock) { out << prefix << "is_geotiff: " << "true" << "\n"; printGeoKeys(out, prefix, geoKeyLength, geoKeyBlock, geoDoubleLength, geoDoubleBlock, geoAsciiLength, geoAsciiBlock); delete[] geoKeyBlock; geoKeyBlock = 0; } else { out << prefix << "is_geotiff: " << "false" << "\n"; } if (geoDoubleBlock) { delete[] geoDoubleBlock; geoDoubleBlock = 0; } if (geoAsciiBlock) { delete[] geoAsciiBlock; geoAsciiBlock = 0; } geoKeyLength = 0; geoDoubleLength = 0; geoAsciiLength = 0; //--- // Get the next IFD offset. Continue this loop until the offset is // zero. //--- if (getOffset(seekOffset, *m_inputStream, version) == false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " No offset to an image file directory found.\n" << "Returning with error." << std::endl; } m_inputStream.reset(); return out; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTiffInfo::readTags: " << "Next Image File Directory(IFD) offset = " << seekOffset << "\n"; } ++ifdIndex; // next ifd //--- // Note this does NOT check to see if sub_file_type is '1' simply // skips all directories past the first if theOverviewFlag is false. //--- if (ifdIndex && !theOverviewFlag) // Don't process overviews... { break; } } // End of loop through the IFD's. out << "tiff.number_of_directories: " << ifdIndex << "\n"; out << std::endl; m_inputStream.reset(); // Reset flags. out.setf(f); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG Exited..." << std::endl; } printDigitalGlobe(out, "tiff."); return out; } std::ostream &ossimTiffInfo::print(std::istream &inStr, std::ostream &outStr) const { static const char MODULE[] = "ossimTiffInfo::print(std::istream&, std::ostream&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG Entered...\n"; } std::streampos startPosition = inStr.tellg(); //--- // Get the byte order. First two byte should be "II" or "MM". //--- char byteOrder[2]; inStr.read(byteOrder, 2); // Read the byte order. ossimByteOrder sysByteOrder = ossim::byteOrder(); ossimByteOrder tifByteOrder = OSSIM_LITTLE_ENDIAN; if (byteOrder[0] == 'M') { tifByteOrder = OSSIM_BIG_ENDIAN; } if (sysByteOrder != tifByteOrder) { if (!m_endian) { m_endian = new ossimEndian(); } } else if (m_endian) // No swapping required. { delete m_endian; m_endian = 0; } //-- // Get the version. Note m_endian must be set/unset before calling // "readShort". //--- ossim_uint16 version; readShort(version, inStr); // Set the tag value length. ossim_uint64 tagValueLength; if (version == 42) { tagValueLength = 4; } else { tagValueLength = 8; } outStr << "tiff.version: " << int(version) << ((version == 42) ? "(classic)\n" : "(big)\n") << "tiff.byte_order: "; if (byteOrder[0] == 'M') { outStr << "big_endian\n"; } else // OSSIM_LITTLE_ENDIAN { outStr << "little_endian\n"; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "system_byte_order: "; if (ossim::byteOrder() == OSSIM_BIG_ENDIAN) { ossimNotify(ossimNotifyLevel_DEBUG) << "big_endian\n"; } else // OSSIM_LITTLE_ENDIAN { ossimNotify(ossimNotifyLevel_DEBUG) << "little_endian\n"; } ossimNotify(ossimNotifyLevel_DEBUG) << "tiff.tag_value_length: " << tagValueLength << "\n"; } //--- // Variables used within the loop. //--- std::streamoff seekOffset; // used throughout std::streampos streamPosition; // used throughout if (version == 43) { // We must skip the first four bytes. ossim_uint32 offsetSize; readLong(offsetSize, inStr); } // Get the offset. if (getOffset(seekOffset, inStr, version) == false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL ERROR - " << "No offset to an image file directory found.\n" << "Returning with error." << std::endl; } return outStr; } if (traceDebug()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG: " << "Offset to first ifd: " << seekOffset << "\n"; } } // Capture the original flags then set float output to full precision. std::ios_base::fmtflags f = outStr.flags(); outStr << std::setprecision(15); // Image File Directory (IFD) loop. ossim_int32 ifdIndex = 0; while (seekOffset) { // directory prefix for prints. std::string prefix = "tiff."; getDirPrefix(ifdIndex, prefix); outStr << prefix << "directory_offset: " << seekOffset << "\n"; // Seek to the image file directory. inStr.seekg(startPosition + seekOffset, std::ios_base::beg); //--- // Things we need to save for printGeoKeys: //--- ossim_uint16 *geoKeyBlock = 0; ossim_uint64 geoKeyLength = 0; ossim_float64 *geoDoubleBlock = 0; ossim_uint64 geoDoubleLength = 0; ossim_int8 *geoAsciiBlock = 0; ossim_uint64 geoAsciiLength = 0; //--- // Get the number of directories within the IFD. //--- ossim_uint64 nTags; // Number of tags in an IFD. if (getValue(nTags, inStr, TWO_OR_EIGHT, version) == false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL error reading number of directories." << std::endl; } return outStr; } if (traceDebug()) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:\n" << "ifd: " << seekOffset << "\ntags in directory: " << nTags << "\n"; } } // Tag loop: for (ossim_uint64 tagIdx = 0; tagIdx < nTags; ++tagIdx) { // Variables used within the loop. ossim_uint16 tag = 0; // Tag number ossim_uint16 type = 0; // Type(short, long...) ossim_uint64 count = 0; ossim_uint64 arraySizeInBytes = 0; // ossim_uint8 *valueArray = 0; // To hold value. //--- // Get the tag. //--- readShort(tag, inStr); if (!inStr) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL error reading tag number." << std::endl; } return outStr; } //--- // Get the type (byte, ascii, short...) //--- readShort(type, inStr); if (!inStr) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL error reading type number." << std::endl; } return outStr; } //--- // Get the count. This is not in bytes. It is based on the // type. So if the type is a short and the count is one then // read "sizeof(short"(2) bytes. //--- getValue(count, inStr, FOUR_OR_EIGHT, version); if (!inStr) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " FATAL error reading count." << std::endl; } return outStr; } // Get the array size in bytes. arraySizeInBytes = getArraySizeInBytes(count, type); if (arraySizeInBytes == 0) { // Could be an unhandle type. Gobble the value. eatValue(inStr, version); } else { // Allocate array. if (valueArray) delete[] valueArray; valueArray = new ossim_uint8[arraySizeInBytes]; if (arraySizeInBytes <= tagValueLength) { // Read in the value(s). inStr.read((char *)valueArray, arraySizeInBytes); // Skip any byes left in the field. if (arraySizeInBytes < tagValueLength) { // Skip these bytes. inStr.ignore(tagValueLength - arraySizeInBytes); } } else // Data to big for field. Stored elsewhere... { // Get the offset to the data. getOffset(seekOffset, inStr, version); // Capture the seek position to come back to. streamPosition = inStr.tellg(); // Seek to the data. inStr.seekg(startPosition + seekOffset, std::ios_base::beg); // Read in the value(s). inStr.read((char *)valueArray, arraySizeInBytes); // Seek back. inStr.seekg(streamPosition); } // Swap the bytes if needed. swapBytes(valueArray, type, count); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG:" << "\ntag[" << tagIdx << "]:" << tag << "\ntype: " << type << "\ncount: " << count << "\narray size in bytes: " << arraySizeInBytes << "\n"; } if (tag == ossim::OGEO_KEY_DIRECTORY_TAG) { // tag 34735 save for printGeoKeys geoKeyBlock = reinterpret_cast(valueArray); geoKeyLength = count; } else if (tag == ossim::OGEO_DOUBLE_PARAMS_TAG) { // tag 34736 save for printGeoKeys geoDoubleBlock = reinterpret_cast(valueArray); geoDoubleLength = count; } else if (tag == ossim::OGEO_ASCII_PARAMS_TAG) { // tag 34737 save for printGeoKeys geoAsciiBlock = reinterpret_cast(valueArray); geoAsciiLength = count; } else { print(outStr, prefix, tagIdx, tag, type, count, arraySizeInBytes, valueArray); // Free memory if allocated... if (valueArray) { delete[] valueArray; valueArray = 0; } } } // End of tag loop. //--- // If Geotiff Keys read them. // This had to done last since the keys could // have references to tags GEO_DOUBLE_PARAMS_TAG and // GEO_ASCII_PARAMS_TAG. //--- if (geoKeyBlock) { outStr << prefix << "is_geotiff: " << "true" << "\n"; printGeoKeys(outStr, prefix, geoKeyLength, geoKeyBlock, geoDoubleLength, geoDoubleBlock, geoAsciiLength, geoAsciiBlock); delete[] geoKeyBlock; geoKeyBlock = 0; } else { outStr << prefix << "is_geotiff: " << "false" << "\n"; } if (geoDoubleBlock) { delete[] geoDoubleBlock; geoDoubleBlock = 0; } if (geoAsciiBlock) { delete[] geoAsciiBlock; geoAsciiBlock = 0; } geoKeyLength = 0; geoDoubleLength = 0; geoAsciiLength = 0; //--- // Get the next IFD offset. Continue this loop until the offset is // zero. //--- if (getOffset(seekOffset, inStr, version) == false) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " No offset to an image file directory found.\n" << "Returning with error." << std::endl; } return outStr; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTiffInfo::readTags: " << "Next Image File Directory(IFD) offset = " << seekOffset << "\n"; } ++ifdIndex; // next ifd //--- // Note this does NOT check to see if sub_file_type is '1' simply // skips all directories past the first if theOverviewFlag is false. //--- if (ifdIndex && !theOverviewFlag) // Don't process overviews... { break; } } // End of loop through the IFD's. outStr << "tiff.number_of_directories: " << ifdIndex << "\n"; outStr << std::endl; // Reset flags. outStr.setf(f); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " DEBUG Exited..." << std::endl; } return outStr; } bool ossimTiffInfo::getImageGeometry(ossimKeywordlist &geomKwl, ossim_uint32 entryIndex) const { static const char MODULE[] = "ossimTiffInfo::getImageGeometry #1"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << " entered...\n"; } bool result = false; // Open the file. // std::ifstream str; // m_inputStream->open(theFile.c_str(), ios::in | ios::binary); if (m_inputStream->good()) { m_inputStream->seekg(0); m_inputStream->clear(); result = getImageGeometry(*m_inputStream, geomKwl, entryIndex); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "geomKwl:\n" << geomKwl << MODULE << " exit status = " << (result ? "true" : "false") << "\n"; } return result; } bool ossimTiffInfo::getImageGeometry(std::istream &inStr, ossimKeywordlist &geomKwl, ossim_uint32 entryIndex) const { static const char M[] = "ossimTiffInfo::getImageGeometry #2"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } bool result = false; // Do a print to a memory stream. std::ostringstream out; print(inStr, out); // Open an input stream to pass to the keyword list. std::istringstream in(out.str()); // Since the print is in key:value format we can pass to a keyword list. ossimKeywordlist gtiffKwl; if (gtiffKwl.parseStream(in)) { result = getImageGeometry(gtiffKwl, geomKwl, entryIndex); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "geomKwl:\n" << geomKwl << M << " exit status = " << (result ? "true" : "false") << "\n"; } return result; } void ossimTiffInfo::getImageGeometry(ossim_uint64 geoKeyLength, ossim_uint16 *geoKeyBlock, ossim_uint64 geoDoubleLength, ossim_float64 *geoDoubleBlock, ossim_uint64 geoAsciiLength, ossim_int8 *geoAsciiBlock, ossimKeywordlist &geomKwl) const { static const char M[] = "ossimTiffInfo::getImageGeometry #3"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } // Dump the geotiff keys to memory. std::ostringstream out; printGeoKeys(out, std::string("tiff.image0."), geoKeyLength, geoKeyBlock, geoDoubleLength, geoDoubleBlock, geoAsciiLength, geoAsciiBlock); // Open an input stream to pass to the keyword list. std::istringstream in(out.str()); // Since the print is in key:value format we can pass to a keyword list. ossimKeywordlist gtiffKwl; if (gtiffKwl.parseStream(in)) { getImageGeometry(gtiffKwl, geomKwl, 0); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n"; } } // Private method: bool ossimTiffInfo::getImageGeometry(const ossimKeywordlist >iffKwl, ossimKeywordlist &geomKwl, ossim_uint32 entryIndex) const { static const char M[] = "ossimTiffInfo::getImageGeometry #4"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } //--- // Start with a return status of true and set to false if something bad // happens. //--- bool result = true; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "tiffinfo dump to kwl:\n" << gtiffKwl << "\n"; } ossimString gtiffPrefix = "tiff.image"; gtiffPrefix += ossimString::toString(entryIndex); gtiffPrefix += "."; ossimString geomPrefix = "image"; geomPrefix += ossimString::toString(entryIndex); geomPrefix += "."; // Get the pixel type. ossimString pixelType; if (getPixelType(gtiffPrefix, gtiffKwl, pixelType) == false) { pixelType = "pixel_is_point"; // Not an error we'll make assumption? } geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::PIXEL_TYPE_KW, pixelType.c_str()); // Get the lines. ossim_uint32 height = getLines(gtiffPrefix, gtiffKwl); if (height) { geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::NUMBER_LINES_KW, height); } else { result = false; } // Get the samples. ossim_uint32 width = getSamples(gtiffPrefix, gtiffKwl); if (width) { geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::NUMBER_SAMPLES_KW, width); } else { result = false; } // Add the pixel type. geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::PIXEL_TYPE_KW, pixelType.c_str()); // Set the projection type. bool isGeographic = false; ossimString pcsCode; ossimString ossimProjectionName = ""; bool hasPcsCode = getPcsCode(gtiffPrefix, gtiffKwl, pcsCode); //--- // The ossimEpsgProjectionFactory will not pick up the origin latitude if code is // 4326 (geographic) so we use the projection name; else, the origin_latitude will // always be 0. This is so the gsd comes out correct for scale. //--- if (hasPcsCode && (pcsCode != "4326")) { // Add the pcs code. geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::PCS_CODE_KW, pcsCode.c_str()); } else { if (getOssimProjectionName(gtiffPrefix, gtiffKwl, ossimProjectionName) == false) { ossimProjectionName = "ossimEquDistCylProjection"; } geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::TYPE_KW, ossimProjectionName); if (ossimProjectionName == "ossimEquDistCylProjection") { isGeographic = true; } } // Get the units. ossimString units = ""; getUnits(gtiffPrefix, gtiffKwl, units); if (units.empty() || (units.contains("unknown"))) { // HACK: Encountered JP2 with geotiff info that did not specify units, so using projection // type to discern units if none explicitly specified. (OLK 05/11) if (ossimProjectionName == "ossimEquDistCylProjection") units = "degrees"; } ossimDpt scale; bool hasScale = false; // Get the model transform if provided. std::vector xfrm; getModelTransform(gtiffPrefix, gtiffKwl, xfrm); if (xfrm.size() == 16) { std::ostringstream out; out << std::setprecision(15); // To avoid truncating. for (const double& m : xfrm) out << m << " "; geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::IMAGE_MODEL_TRANSFORM_MATRIX_KW, out.str().c_str(), true); geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::ORIGINAL_MAP_UNITS_KW, units.c_str(), true); } else // Use tie points and scale. { // Get the pixel scale. hasScale = getPixelScale(gtiffPrefix, gtiffKwl, scale); // Get the tie point. std::vector ties; getTiePoint(gtiffPrefix, gtiffKwl, ties); // Tie count: // NOTE: It takes six doubles to make one tie point ie: // x,y,z,longitude,latitude,height or x,y,z,easting,northing,height ossim_uint32 tieCount = (ossim_uint32)ties.size() / 6; if (hasScale && (tieCount == 1)) { // Shift the tile to 0,0 pixel of image if not already there. ossimDpt tie; tie.x = ties[3] - ties[0] * scale.x; tie.y = ties[4] + ties[1] * scale.y; geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::TIE_POINT_XY_KW, tie.toString().c_str()); geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::TIE_POINT_UNITS_KW, units.c_str()); // Add the scale. geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::PIXEL_SCALE_XY_KW, scale.toString().c_str()); geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::PIXEL_SCALE_UNITS_KW, units.c_str()); } else if (tieCount > 1) // four or better tie points. { ossimTieGptSet tieSet; getTieSets(ties, width, height, tieSet); if (tieCount >= 4) { ossimRefPtr proj = new ossimBilinearProjection; proj->optimizeFit(tieSet); proj->saveState(geomKwl, geomPrefix.c_str()); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Creating a bilinear projection\n"; } } else // Need at least four ties. { result = false; } } else { result = false; } } // matches: else Use tie points block. ossimString tmpStr; if (getStdParallelOne(gtiffPrefix, gtiffKwl, tmpStr)) { geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::STD_PARALLEL_1_KW, tmpStr); } if (getStdParallelTwo(gtiffPrefix, gtiffKwl, tmpStr)) { geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::STD_PARALLEL_2_KW, tmpStr); } ossimDpt eastingNorthing; if (getFalseEastingNorthing(gtiffPrefix, gtiffKwl, eastingNorthing)) { geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::FALSE_EASTING_NORTHING_KW, eastingNorthing.toString()); geomKwl.add(geomPrefix.c_str(), ossimKeywordNames:: FALSE_EASTING_NORTHING_UNITS_KW, units); } ossim_float64 tmpDbl = ossim::nan(); if (getOriginLat(gtiffPrefix, gtiffKwl, tmpDbl) == false) { if (isGeographic && hasScale && scale.x) { //--- // ossimEquDistCylProjection uses the origin_latitude for meters per pixel (gsd) // computation. So is not set in tiff tags, compute to achieve the proper // horizontal scaling. //--- tmpDbl = ossim::acosd(scale.y / scale.x); } } if (!ossim::isnan(tmpDbl)) { geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::ORIGIN_LATITUDE_KW, tmpDbl); } if (getCentralMeridian(gtiffPrefix, gtiffKwl, tmpDbl)) { geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::CENTRAL_MERIDIAN_KW, tmpDbl); } if (getScaleFactor(gtiffPrefix, gtiffKwl, tmpDbl)) { geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::SCALE_FACTOR_KW, tmpDbl); } if (getDatumCode(gtiffPrefix, gtiffKwl, tmpStr)) { geomKwl.add(geomPrefix.c_str(), ossimKeywordNames::DATUM_KW, tmpStr.c_str()); } //--- // Linear and vertical units not read by projection factories but added so external user could // query. //--- if (getLinearUnits(gtiffPrefix, gtiffKwl, tmpStr)) { geomKwl.add(geomPrefix.c_str(), LINEAR_UNITS_KW.c_str(), tmpStr.c_str()); } if (getVerticalUnits(gtiffPrefix, gtiffKwl, tmpStr)) { geomKwl.add(geomPrefix.c_str(), VERTICAL_UNITS_KW.c_str(), tmpStr.c_str()); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "geomKwl:\n" << geomKwl << "\n" << M << " exit status = " << (result ? "true" : "false") << "\n"; } return result; } void ossimTiffInfo::readShort(ossim_uint16 &s, std::istream &str) const { str.read((char *)&s, sizeof(s)); if (m_endian) { m_endian->swap(s); } } void ossimTiffInfo::readLong(ossim_uint32 &l, std::istream &str) const { str.read((char *)&l, sizeof(l)); if (m_endian) { m_endian->swap(l); } } void ossimTiffInfo::readLongLong(ossim_uint64 &l, std::istream &str) const { str.read((char *)&l, sizeof(l)); if (m_endian) { m_endian->swap(l); } } bool ossimTiffInfo::getOffset( std::streamoff &offset, std::istream &str, ossim_uint16 version) const { bool status = true; if (version == 42) { ossim_uint32 littleOffset; readLong(littleOffset, str); offset = littleOffset; } else { ossim_uint64 bigOffset; readLongLong(bigOffset, str); offset = bigOffset; } if (!str) { status = false; } return status; } bool ossimTiffInfo::getValue(ossim_uint64 &value, std::istream &str, WordType type, ossim_uint16 version) const { bool status = true; if (version == 42) { if (type == TWO_OR_EIGHT) { ossim_uint16 i; readShort(i, str); value = i; } else { ossim_uint32 i; readLong(i, str); value = i; } } else { ossim_uint64 i; readLongLong(i, str); value = i; } if (!str) { status = false; } return status; } ossim_uint64 ossimTiffInfo::getArraySizeInBytes(ossim_uint64 length, ossim_uint16 type) const { return length * getTypeByteSize(type); } ossim_uint16 ossimTiffInfo::getTypeByteSize(ossim_uint16 type) const { ossim_uint16 result = 0; switch (type) { case ossim::OTIFF_BYTE: case ossim::OTIFF_ASCII: case ossim::OTIFF_SBYTE: case ossim::OTIFF_UNDEFINED: { result = 1; break; } case ossim::OTIFF_SHORT: case ossim::OTIFF_SSHORT: { result = 2; break; } case ossim::OTIFF_LONG: case ossim::OTIFF_SLONG: case ossim::OTIFF_IFD: case ossim::OTIFF_FLOAT: { result = 4; break; } case ossim::OTIFF_RATIONAL: case ossim::OTIFF_SRATIONAL: case ossim::OTIFF_DOUBLE: case 16: // TIFF_LONG8 defined in big tiff only. case 17: // TIFF_SLONG8 defined in big tiff only. case 18: // TIFF_IFD8 defined in big tiff only. { result = 8; break; } default: { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffInfo::getTypeByteSize DEBUG:" << "\nUnhandled type: " << int(type) << "\n"; } break; } } return result; } void ossimTiffInfo::eatValue(std::istream &str, ossim_uint16 version) const { if (version == 42) { ossim_uint32 dummy; readLong(dummy, str); } else { ossim_uint64 dummy; readLongLong(dummy, str); } } void ossimTiffInfo::swapBytes(ossim_uint8 *v, ossim_uint16 type, ossim_uint64 count) const { if (m_endian) { ossim_uint32 byteSize = getTypeByteSize(type); switch (byteSize) { case 2: m_endian->swapTwoBytes(v, count); break; case 4: m_endian->swapFourBytes(v, count); break; case 8: m_endian->swapEightBytes(v, count); break; default: break; } } } template void ossimTiffInfo::getArrayValue( T &v, ossim_uint8 *array, ossim_uint64 position) const { T *p = (T *)array; v = p[position]; } std::ostream &ossimTiffInfo::print(std::ostream &out, const std::string &prefix, ossim_uint64 tagIdx, ossim_uint16 tag, ossim_uint16 type, ossim_uint64 count, ossim_uint64 arraySizeInBytes, ossim_uint8 *valueArray) const { switch (tag) { case ossim::OTIFFTAG_SUBFILETYPE: // tag 254 { out << prefix << "sub_file_type: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_IMAGEWIDTH: // tag 256 { out << prefix << IMAGE_WIDTH_KW << ": "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_IMAGELENGTH: // tag 257 { out << prefix << IMAGE_LENGTH_KW << ": "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_BITSPERSAMPLE: // tag 258 { out << prefix << "bits_per_sample: "; if (count == 1) { printValue(out, type, valueArray); } else if (valueArray) { printArray(out, type, count, valueArray); } break; } case ossim::OTIFFTAG_COMPRESSION: // tag 259 { if ((count == 1) && (type == ossim::OTIFF_SHORT)) { out << prefix << "compression: "; ossim_uint16 s; getArrayValue(s, valueArray, 0); out << s << "\n"; out << prefix << "compression_flag: "; if (s == 1) { out << "false\n"; } else { out << "true\n"; } } break; } case ossim::OTIFFTAG_PHOTOMETRIC: // tag 262 { out << prefix << "photo_interpretation: "; if ((count == 1) && (type == ossim::OTIFF_SHORT)) { ossim_uint16 s; getArrayValue(s, valueArray, 0); if (s < ossim::OPHOTO_LAST) { out << PHOTO_INTERP[s] << "\n"; } else if (s == ossim::OPHOTO_LOGL) { out << "LOGL\n"; } else if (s == ossim::OPHOTO_LOGLUV) { out << "LOGLUV \n"; } else { out << "range error!\n"; } } break; } case ossim::OTIFFTAG_FILLORDER: // tag 266 { if ((count == 1) && (type == ossim::OTIFF_SHORT)) { out << prefix << "fill_order: "; ossim_uint16 s; getArrayValue(s, valueArray, 0); out << s << "\n"; } break; } case ossim::OTIFFTAG_IMAGEDESCRIPTION: // tag 270 { out << prefix << "image_description: "; printArray(out, type, count, valueArray); break; } case ossim::OTIFFTAG_MAKE: // tag 271 { out << prefix << "make: "; printArray(out, type, count, valueArray); break; } case ossim::OTIFFTAG_MODEL: // tag 272 { out << prefix << "model: "; printArray(out, type, count, valueArray); break; } case ossim::OTIFFTAG_STRIPOFFSETS: // tag 273 { if (traceDump()) { out << prefix << "bytes_per_strip: "; if (count == 1) { printValue(out, type, valueArray); } else { printArray(out, type, count, valueArray); } } break; } case ossim::OTIFFTAG_ORIENTATION: // tag 274 { ossim_uint16 code; getArrayValue(code, valueArray, 0); printOrientation(out, prefix, code); break; } case ossim::OTIFFTAG_SAMPLESPERPIXEL: // tag 277 { out << prefix << "samples_per_pixel: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_ROWSPERSTRIP: // tag 278 { out << prefix << "rows_per_strip: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_STRIPBYTECOUNTS: // tag 279 { if (traceDump()) { out << prefix << "bytes_per_strip: "; if (count == 1) { printValue(out, type, valueArray); } else { printArray(out, type, count, valueArray); } } break; } case ossim::OTIFFTAG_MINSAMPLEVALUE: // tag 280 { out << prefix << "min_sample_value: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_MAXSAMPLEVALUE: // tag 281 { out << prefix << "max_sample_value: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_XRESOLUTION: // tag 282 { out << prefix << "xresolution: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_YRESOLUTION: // tag 283 { out << prefix << "yresolution: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_PLANARCONFIG: // tag 284 { if ((count == 1) && (type == ossim::OTIFF_SHORT)) { out << prefix << "planar_configuration: "; ossim_uint16 v; getArrayValue(v, valueArray, 0); if (v == 1) { out << "single image plane\n"; } else if (v == 2) { out << "separate image planes\n"; } else { out << "unknown planar value!\n"; } } break; } case ossim::OTIFFTAG_RESOLUTIONUNIT: // tag 296 { out << prefix << "resolution_units: "; ossim_uint16 v; getArrayValue(v, valueArray, 0); if (v == 2) { out << "inch\n"; } else if (v == 3) { out << "cm\n"; } else { out << "none\n"; } break; } case ossim::OTIFFTAG_PAGENUMBER: // tag 297 { if ((count == 2) && (type == ossim::OTIFF_SHORT)) { out << prefix << "page_number: "; ossim_uint16 s; getArrayValue(s, valueArray, 0); out << s << "\n"; out << prefix << "total_pages: "; getArrayValue(s, valueArray, 1); out << s << "\n"; } break; } case ossim::OTIFFTAG_SOFTWARE: // tag 305 { out << prefix << "software: "; printArray(out, type, count, valueArray); break; } case ossim::OTIFFTAG_DATETIME: // tag 306 { out << prefix << "date_time: "; printArray(out, type, count, valueArray); break; } case ossim::OTIFFTAG_ARTIST: // tag 315 { out << prefix << "artist: "; printArray(out, type, count, valueArray); break; } case ossim::OTIFFTAG_PREDICTOR: // tag 317 { out << prefix << "predictor: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_COLORMAP: // tag 320 { out << prefix << "colormap: "; printArray(out, type, count, valueArray); break; } case ossim::OTIFFTAG_TILEWIDTH: // tag 322 { out << prefix << "tile_width: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_TILELENGTH: // tag 323 { out << prefix << "tile_length: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_TILEOFFSETS: // tag 324 { if (traceDump()) { out << prefix << "tile_offsets: "; if (count == 1) { printValue(out, type, valueArray); } else { printArray(out, type, count, valueArray); } } break; } case ossim::OTIFFTAG_TILEBYTECOUNTS: // tag 325 { if (traceDump()) { out << prefix << "tile_byte_counts: "; if (count == 1) { printValue(out, type, valueArray); } else { printArray(out, type, count, valueArray); } } break; } case ossim::OTIFFTAG_SUBIFD: // tag 330 { if ((count == 1) && (type == ossim::OTIFF_IFD8)) { out << prefix << "subimage_descriptor: "; ossim_uint64 v; getArrayValue(v, valueArray, 0); out << v << "\n"; } else { out << prefix << "tag 330 unhandled condition.\n"; } break; } case ossim::OTIFFTAG_EXTRASAMPLES: // tag 338 { out << prefix << "extra_samples: "; ossim_uint16 v; getArrayValue(v, valueArray, 0); switch (v) { case 1: { out << "associated_alpha_data\n"; break; } case 2: { out << "unassociated_alpha_data\n"; break; } default: { out << "unspecified_data\n"; break; } } break; } case ossim::OTIFFTAG_SAMPLEFORMAT: // tag 339 { out << prefix << "sample_format: "; if (count == 1) { printValue(out, type, valueArray); } else if (valueArray) { printArray(out, type, count, valueArray); } for (ossim_uint64 i = 0; i < count; ++i) { std::ostringstream s; s << "sample_format_string"; if (count > 1) { s << i; } out << prefix << s.str() << ": "; ossim_uint16 v; getArrayValue(v, valueArray, i); switch (v) { case ossim::OSAMPLEFORMAT_UINT: out << "unsigned integer data\n"; break; case ossim::OSAMPLEFORMAT_INT: out << "signed integer data\n"; break; case ossim::OSAMPLEFORMAT_IEEEFP: out << "IEEE floating point data\n"; break; case ossim::OSAMPLEFORMAT_COMPLEXINT: out << "complex signed int\n"; break; case ossim::OSAMPLEFORMAT_COMPLEXIEEEFP: out << "complex ieee floating\n"; break; case ossim::OSAMPLEFORMAT_VOID: default: out << "untyped data\n"; break; } } break; } case ossim::OTIFFTAG_SMINSAMPLEVALUE: // tag 340 { out << prefix << "smin_sample_value: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_SMAXSAMPLEVALUE: // tag 341 { out << prefix << "smax_sample_value: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_YCBCRSUBSAMPLING: { out << prefix << "ycbcr_sub_sampling: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_YCBCRPOSITIONING: { out << prefix << "ycbcr_positioning: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_REFERENCEBLACKWHITE: { out << prefix << "reference_black_white: "; printValue(out, type, valueArray); break; } case ossim::OTIFFTAG_XMLPACKET: // tag 700 { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << prefix << "xml: "; printArray(ossimNotify(ossimNotifyLevel_DEBUG), ossim::OTIFF_BYTE, count, valueArray); } printXmpMetadata(out, prefix, count, valueArray); break; } case ossim::OTIFFTAG_COPYRIGHT: // tag 33432 { out << prefix << "copyright: "; printArray(out, type, count, valueArray); break; } case ossim::OMODEL_PIXEL_SCALE_TAG: // tag 33550 { out << prefix << MODEL_PIXEL_SCALE_KW << ": "; printArray(out, type, count, valueArray); break; } case ossim::OMODEL_TIE_POINT_TAG: // tag 33992 { out << prefix << MODEL_TIE_POINT_KW << ": "; printArray(out, type, count, valueArray); break; } case ossim::OMODEL_TRANSFORM_TAG: // tag 34264 { out << prefix << MODEL_TRANSFORM_KW << ": "; printArray(out, type, count, valueArray); break; } case ossim::OTIFFTAG_PHOTOSHOP: // tag 34377 { out << prefix << "photoshop_image_resource_blocks: found\n"; break; } case ossim::OGEO_DOUBLE_PARAMS_TAG: // tag 34736 { out << prefix << "double_params: "; printArray(out, type, count, valueArray); break; } case ossim::OGEO_ASCII_PARAMS_TAG: // tag 34737 { out << prefix << "ascii_params: "; printArray(out, type, count, valueArray); break; } case ossim::OGDAL_METADATA_TAG: // tag 42112 { printGdalMetadata(out, prefix, count, valueArray); break; } case ossim::OGDAL_NODATA: // tag 42113 { out << prefix << "gdal_nodata: "; printArray(out, type, count, valueArray); break; } case ossim::ORPC_COEFFICIENT_TAG: // tag 50844 { printRpcs(out, prefix, type, count, valueArray); break; } default: { out << prefix << "unhandled_tag: " << tag << "\n"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "generic:" << "\ntag[" << tagIdx << "]: " << tag << "\ntype: " << type << "\ncount: " << count << "\narray size in bytes: " << arraySizeInBytes << "\n"; printArray(out, type, count, valueArray); } break; } } // end of switch on tag... return out; } // end of print std::ostream &ossimTiffInfo::printValue(std::ostream &out, ossim_uint16 type, ossim_uint8 *valueArray) const { switch (type) { case ossim::OTIFF_BYTE: { ossim_uint8 v; getArrayValue(v, valueArray, 0); out << (ossim_uint16)v << "\n"; break; } case ossim::OTIFF_SHORT: { ossim_uint16 v; getArrayValue(v, valueArray, 0); out << v << "\n"; break; } case ossim::OTIFF_SSHORT: { ossim_sint16 v; getArrayValue(v, valueArray, 0); out << v << "\n"; break; } case ossim::OTIFF_LONG: { ossim_uint32 v; getArrayValue(v, valueArray, 0); out << v << "\n"; break; } case ossim::OTIFF_RATIONAL: // two longs first=numerator, second=denominator { ossim_uint32 num; ossim_uint32 den; getArrayValue(num, valueArray, 0); getArrayValue(den, valueArray, 1); if (den) { out << (num / den) << "\n"; } else { out << num << " / " << den << "\n"; } break; } case ossim::OTIFF_SLONG: { ossim_sint32 v; getArrayValue(v, valueArray, 0); out << v << "\n"; break; } case ossim::OTIFF_FLOAT: { ossim_float32 v; getArrayValue(v, valueArray, 0); out << v << "\n"; break; } case ossim::OTIFF_DOUBLE: { ossim_float64 v; getArrayValue(v, valueArray, 0); out << v << "\n"; break; } default: { out << "print_value_unhandled type: " << type << "\n"; break; } } return out; } std::ostream &ossimTiffInfo::printArray(std::ostream &out, ossim_uint16 type, ossim_uint64 arraySizeInBytes, ossim_uint8 *valueArray) const { if (valueArray) { switch (type) { case ossim::OTIFF_BYTE: { for (ossim_uint64 i = 0; i < arraySizeInBytes; ++i) { out << ((ossim_uint8)valueArray[i]); } out << "\n"; break; } case ossim::OTIFF_ASCII: { //--- // Add tripple quotes front and back for ossimKeywordlist to handle multi-line // comments. //--- out << "\"\"\""; for (ossim_uint64 i = 0; i < arraySizeInBytes; ++i) { //--- // Test to avoid putting nulls in the ascii string out. Added to fix // ossimKeywordlist::parseStream returning false on trailing null Where array was // tagged as 11 bytes and ascii string was OrthoVista(10 bytes) and 11 byte was // ascii NUL '\0'. //--- if (valueArray[i] != 0) { out << ((char)valueArray[i]); } } out << "\"\"\"\n"; break; } case ossim::OTIFF_SHORT: { ossim_uint16 *p = (ossim_uint16 *)valueArray; for (ossim_uint64 i = 0; i < arraySizeInBytes; ++i) { out << p[i] << " "; } out << "\n"; break; } case ossim::OTIFF_LONG: { ossim_uint32 *p = (ossim_uint32 *)valueArray; for (ossim_uint64 i = 0; i < arraySizeInBytes; ++i) { out << p[i] << " "; } out << "\n"; break; } case ossim::OTIFF_LONG8: { ossim_uint64 *p = (ossim_uint64 *)valueArray; for (ossim_uint64 i = 0; i < arraySizeInBytes; ++i) { out << p[i] << " "; } out << "\n"; break; } case ossim::OTIFF_DOUBLE: { ossim_float64 *p = (ossim_float64 *)valueArray; for (ossim_uint64 i = 0; i < arraySizeInBytes; ++i) { out << p[i] << " "; } out << "\n"; break; } default: { out << "print_array_unhandled type: " << type << "\n"; break; } } } else { out << "null array passed to ossimTiffInfo::printArray method." << "\n"; } return out; } std::ostream &ossimTiffInfo::printGdalMetadata(std::ostream &out, const std::string &prefix, ossim_uint64 count, ossim_uint8 *valueArray) const { ossimString xmlString(valueArray, valueArray + count); ossimRefPtr xmlNode = new ossimXmlNode(); std::istringstream in(xmlString); if (xmlNode->read(in)) { const ossimXmlNode::ChildListType &children = xmlNode->getChildNodes(); ossim_uint32 idx = 0; for (idx = 0; idx < children.size(); ++idx) { out << prefix << "gdalmetadata." << ossimString(children[idx]->getAttributeValue("name")).downcase() << ":" << children[idx]->getText() << std::endl; } } return out; } std::ostream &ossimTiffInfo::printXmpMetadata(std::ostream &out, const std::string &prefix, ossim_uint64 count, ossim_uint8 *valueArray) const { ossimString xmlString(valueArray, valueArray + count); ossimRefPtr xmlNode = new ossimXmlNode(); std::istringstream in(xmlString); ossimRefPtr xdoc = new ossimXmlDocument(); // Read the xml document: if (xdoc->read(in)) { std::vector> xnodes; // Wavelength: ossimString path = "/x:xmpmeta/rdf:RDF/rdf:Description/Camera:CentralWavelength"; ossimString result; xdoc->findNodes(path, xnodes); if (xnodes.size() == 1) // Error if more than one. { if (xnodes[0].valid()) { result = xnodes[0]->getText(); if (result.size()) { out << prefix << "xmp.camera.central_wavelength: " << result << "\n"; } } } xnodes.clear(); path = "/x:xmpmeta/rdf:RDF/rdf:Description/Camera:BandName"; xdoc->findNodes(path, xnodes); if (xnodes.size() == 1) // Error if more than one. { if (xnodes[0].valid()) { result = xnodes[0]->getText(); if (result.size()) { out << prefix << "xmp.camera.band_name: " << result << "\n"; } } } xnodes.clear(); path = "/x:xmpmeta/rdf:RDF/rdf:Description/Camera:WavelengthFWHM"; xdoc->findNodes(path, xnodes); if (xnodes.size() == 1) // Error if more than one. { if (xnodes[0].valid()) { result = xnodes[0]->getText(); if (result.size()) { out << prefix << "xmp.camera.wavelength_fwhm: " << result << "\n"; } } } xnodes.clear(); path = "/x:xmpmeta/rdf:RDF/rdf:Description/Camera:BandSensitivity"; xdoc->findNodes(path, xnodes); if (xnodes.size() == 1) // Error if more than one. { if (xnodes[0].valid()) { result = xnodes[0]->getText(); if (result.size()) { out << prefix << "xmp.camera.band_sensitivity: " << result << "\n"; } } } xnodes.clear(); path = "/x:xmpmeta/rdf:RDF/rdf:Description/Camera:RigCameraIndex"; xdoc->findNodes(path, xnodes); if (xnodes.size() == 1) // Error if more than one. { if (xnodes[0].valid()) { result = xnodes[0]->getText(); if (result.size()) { out << prefix << "xmp.camera.rig_camera_index: " << result << "\n"; } } } xnodes.clear(); path = "/x:xmpmeta/rdf:RDF/rdf:Description/Camera:Yaw"; xdoc->findNodes(path, xnodes); if (xnodes.size() == 1) // Error if more than one. { if (xnodes[0].valid()) { result = xnodes[0]->getText(); if (result.size()) { out << prefix << "xmp.camera.yaw: " << result << "\n"; } } } xnodes.clear(); path = "/x:xmpmeta/rdf:RDF/rdf:Description/Camera:Pitch"; xdoc->findNodes(path, xnodes); if (xnodes.size() == 1) // Error if more than one. { if (xnodes[0].valid()) { result = xnodes[0]->getText(); if (result.size()) { out << prefix << "xmp.camera.pitch: " << result << "\n"; } } } xnodes.clear(); path = "/x:xmpmeta/rdf:RDF/rdf:Description/Camera:Roll"; xdoc->findNodes(path, xnodes); if (xnodes.size() == 1) // Error if more than one. { if (xnodes[0].valid()) { result = xnodes[0]->getText(); if (result.size()) { out << prefix << "xmp.camera.roll: " << result << "\n"; } } } } return out; } std::ostream &ossimTiffInfo::printGeoKeys( std::ostream &out, const std::string &prefix, ossim_uint64 geoKeyLength, ossim_uint16 *geoKeyBlock, ossim_uint64 geoDoubleLength, ossim_float64 *geoDoubleBlock, ossim_uint64 geoAsciiLength, ossim_int8 *geoAsciiBlock) const { if (geoKeyLength && geoKeyBlock) { //--- // Length passed in is the total number of shorts in the geo key // directory. Each key has four short values; hence, "length/4". //--- ossim_int32 index = 0; ossim_int32 tagCount = static_cast(geoKeyLength / 4); for (ossim_int32 i = 0; i < tagCount; ++i) { //--- // Each key contains four unsigned shorts: // GeoKey ID // TIFF Tag ID or 0 // GeoKey value count // value or tag offset //--- ossim_uint16 key = geoKeyBlock[index++]; ossim_uint16 tag = geoKeyBlock[index++]; ossim_uint16 count = geoKeyBlock[index++]; ossim_uint16 code = geoKeyBlock[index++]; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimTiffInfo::printGeoKeys" << "\nKey index: " << i << "\ngeo key: " << key << "\ntag: " << tag << "\ncount: " << count << "\ncode: " << code << "\n"; } //--- // NOTE: Add tripple quotes front and back of ascii blocks for // ossimKeywordlist to handle multi-line comments. //--- switch (key) { case ossim::OGT_MODEL_TYPE_GEO_KEY: // key 1024 Section 6.3.1.1 Codes { printModelType(out, prefix, code); break; } case ossim::OGT_RASTER_TYPE_GEO_KEY: // key 1025 Section 6.3.1.2 Code { printRasterType(out, prefix, code); break; } case ossim::OGT_CITATION_GEO_KEY: // key 1026 { if (tag == 34737) // using ascii array { if (geoAsciiBlock && ((code + count) <= geoAsciiLength)) { std::string s; int i = 0; while (i < count) { s.push_back(geoAsciiBlock[code + i]); ++i; } out << prefix << "citation: \"\"\"" << s << "\"\"\"\n"; } } break; } case ossim::OGEOGRAPHIC_TYPE_GEO_KEY: // key 2048 Section 6.3.2.1 Codes { out << prefix << ossimKeywordNames::GCS_CODE_KW << ": " << code << "\n"; break; } case ossim::OGEOG_CITATION_GEO_KEY: // key 2049 { if (tag == 34737) // using ascii array { if (geoAsciiBlock && ((code + count) <= geoAsciiLength)) { std::string s; int i = 0; while (i < count) { s.push_back(geoAsciiBlock[code + i]); ++i; } out << prefix << "geographic_citation: \"\"\"" << s << "\"\"\"\n"; } } break; } case ossim::OGEOG_GEODETIC_DATUM_GEO_KEY: // key 2050 Section 6.3.2.2 Codes { out << prefix << GEODETIC_DATUM_KW << ": " << code << "\n"; break; } case ossim::OGEOG_PRIME_MERIDIAN_GEOKEY: // key 2051 Section 6.3.2.4 Codes { out << prefix << "prime_meridian_code: " << code << "\n"; break; } case ossim::OGEOG_LINEAR_UNITS_GEO_KEY: // key 2052 Section 6.3.1.3 Codes { out << prefix << "linear_units_code: " << code << "\n"; printLinearUnits(out, prefix, LINEAR_UNITS_KW, code); break; } case ossim::OGEOG_ANGULAR_UNITS_GEO_KEY: // key 2054 Section 6.3.1.4 Codes { out << prefix << "angular_units_code: " << code << "\n"; printAngularUnits(out, prefix, code); break; } case ossim::OGEOG_ANGULAR_UNIT_SIZE_GEO_KEY: // key 2055 Size in radians Section 6.2.2 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << "angular_units_size_radians: " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OGEOG_ELLIPSOID_GEO_KEY: // key 2056 Section 6.3.23 Codes { out << prefix << "ellipsoid_code: " << code << "\n"; break; } case ossim::OGEOG_SEMI_MAJOR_AXIS: // key 2057 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << "semi_major_axis: " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OGEOG_SEMI_MINOR_AXIS: // key 2058 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << "semi_minor_axis: " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OGEOG_INV_FLATTENING_GEO_KEY: // key 2059 ratio Section 6.2.2 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << "inverse_flattening_ratio: " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OGEOG_PRIME_MERIDIAN_LONG_GEO_KEY: // key 2061 GeogAngularUnit Section 6.2.2 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << "prime_meridian_longitude: " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJECTED_CS_TYPE_GEO_KEY: // key 3072 Section 6.3.3.1 codes { out << prefix << "pcs_code: " << code << "\n"; break; } case ossim::OPCS_CITATION_GEO_KEY: // key 3073 ascii { if (tag == 34737) // using ascii array { if (geoAsciiBlock && ((code + count) <= geoAsciiLength)) { std::string s; int i = 0; while (i < count) { s.push_back(geoAsciiBlock[code + i]); ++i; } out << prefix << "pcs_citation: \"\"\"" << s << "\"\"\"\n"; } } break; } case ossim::OPROJECTION_GEO_KEY: // key 3074 Section 6.3.3.2 codes { out << prefix << "proj_code: " << code << "\n"; break; } case ossim::OPROJ_COORD_TRANS_GEO_KEY: // key 3075 Section 6.3.3.3 codes { out << prefix << COORD_TRANS_CODE_KW << ": " << code << "\n"; printCoordTrans(out, prefix, code); break; } case ossim::OPROJ_LINEAR_UNITS_GEO_KEY: // key 3076 Section 6.3.1.3 codes { out << prefix << "linear_units_code: " << code << "\n"; printLinearUnits(out, prefix, std::string("linear_units"), code); break; } case ossim::OPROJ_LINEAR_UNIT_SIZE_GEO_KEY: // key 3077 meters Section 6.2.3 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << "linear_units_size: " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_STD_PARALLEL1_GEO_KEY: // key 3078 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << ossimKeywordNames::STD_PARALLEL_1_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_STD_PARALLEL2_GEO_KEY: // key 3079 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << ossimKeywordNames::STD_PARALLEL_2_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_NAT_ORIGIN_LONG_GEO_KEY: // key 3080 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << ORIGIN_LONGITUDE_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_NAT_ORIGIN_LAT_GEO_KEY: // key 3081 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << ORIGIN_LATITUDE_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_FALSE_EASTING_GEO_KEY: // key 3082 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << ossimKeywordNames::FALSE_EASTING_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_FALSE_NORTHING_GEO_KEY: // key 3083 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << ossimKeywordNames::FALSE_NORTHING_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_FALSE_ORIGIN_LONG_GEO_KEY: // key 3084 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << FALSE_ORIGIN_LONGITUDE_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_FALSE_ORIGIN_LAT_GEO_KEY: // key 3085 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << FALSE_ORIGIN_LATITUDE_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_FALSE_ORIGIN_EASTING_GEO_KEY: // key 3086 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << FALSE_ORIGIN_EASTING_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_FALSE_ORIGIN_NORTHING_GEO_KEY: // key 3087 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << FALSE_ORIGIN_NORTHING_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_CENTER_LONG_GEO_KEY: // key 3088 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << "center_longitude: " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_CENTER_LAT_GEO_KEY: // key 3089 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << "center_latitude: " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_SCALE_AT_NAT_ORIGIN_GEO_KEY: // key 3092 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << ossimKeywordNames::SCALE_FACTOR_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OPROJ_SCALE_AT_CENTER_GEO_KEY: // key 3093 { if (tag == 34736) // using double array { // Code is index into array. if (geoDoubleBlock && (code < geoDoubleLength)) { // Always count of one. out << prefix << ossimKeywordNames::SCALE_FACTOR_KW << ": " << geoDoubleBlock[code] << "\n"; } } break; } case ossim::OVERTICAL_CITATION_GEO_KEY: // key 4097 { if (tag == 34737) // using ascii array { if (geoAsciiBlock && ((code + count) <= geoAsciiLength)) { std::string s; int i = 0; while (i < count) { s.push_back(geoAsciiBlock[code + i]); ++i; } out << prefix << "vertical_citation: \"\"\"" << s << "\"\"\"\n"; } } break; } case ossim::OVERTICAL_UNITS_GEO_KEY: // key 4099 Section 6.3.1.3 Codes { out << prefix << "vertical_units_code: " << code << "\n"; printLinearUnits(out, prefix, VERTICAL_UNITS_KW, code); break; } default: { if (key > 1) { if (tag == 34737) // using ascii array { if (geoAsciiBlock && ((code + count) <= geoAsciiLength)) { std::string s; int i = 0; while (i < count) { s.push_back(geoAsciiBlock[code + i]); ++i; } out << prefix << "key_" << key << ": \"\"\"" << s << "\"\"\"\n"; } } else { out << prefix << "unhandle_key: " << key << "\n"; } } break; } } // matches: switch(key) } // for (ossim_int32 i = 0; i < tagCount; ++i) if (traceDebug()) { if (geoAsciiBlock && geoAsciiLength) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimTiffInfo::printGeoKeys DEBUG: geo ascii block: "; std::string s(geoAsciiBlock, static_cast(geoAsciiLength)); ossimNotify(ossimNotifyLevel_DEBUG) << s << "\n"; } } } // if (geoKeyLength && geoKeyBlock) return out; } std::ostream &ossimTiffInfo::printRpcs(std::ostream &out, const std::string &prefix, ossim_uint16 type, ossim_uint64 count, ossim_uint8 *valueArray) const { if (valueArray) { if (count == 92) { switch (type) { case ossim::OTIFF_DOUBLE: { ossim_float64 *p = (ossim_float64 *)valueArray; out << prefix << "rpc.bias_error: " << p[0] << "\n" << prefix << "rpc.rand_error: " << p[1] << "\n" << prefix << "rpc.line_off: " << p[2] << "\n" << prefix << "rpc.samp_off: " << p[3] << "\n" << prefix << "rpc.lat_off: " << p[4] << "\n" << prefix << "rpc.long_off: " << p[5] << "\n" << prefix << "rpc.height_off: " << p[6] << "\n" << prefix << "rpc.line_scale: " << p[7] << "\n" << prefix << "rpc.samp_scale: " << p[8] << "\n" << prefix << "rpc.lat_scale: " << p[9] << "\n" << prefix << "rpc.long_scale: " << p[10] << "\n" << prefix << "rpc.height_scale: " << p[11] << "\n"; ossim_int32 i = 12; ossim_int32 coeff = 0; for (coeff = 0; coeff < 20; ++coeff) { out << prefix << "rpc.line_num_coeff_" << std::setfill('0') << std::setw(2) << coeff << ": " << p[i] << "\n"; ++i; } for (coeff = 0; coeff < 20; ++coeff) { out << prefix << "rpc.line_den_coeff_" << std::setfill('0') << std::setw(2) << coeff << ": " << p[i] << "\n"; ++i; } for (coeff = 0; coeff < 20; ++coeff) { out << prefix << "rpc.samp_num_coeff_" << std::setfill('0') << std::setw(2) << coeff << ": " << p[i] << "\n"; ++i; } for (coeff = 0; coeff < 20; ++coeff) { out << prefix << "rpc.samp_den_coeff_" << std::setfill('0') << std::setw(2) << coeff << ": " << p[i] << "\n"; ++i; } break; } default: { out << "print_rpcs_unhandled_type: " << type << "\n"; break; } } } else { out << "print_rpcs_invalid_count: " << count << "\n"; } } else { out << "print_rpcs_error: null_array\n"; } return out; } std::ostream &ossimTiffInfo::printModelType(std::ostream &out, const std::string &prefix, ossim_uint16 code) const { // key 1024 Section 6.3.1.1 Codes out << prefix << MODEL_TYPE_KW << ": "; if (code == 1) { out << "projected\n"; } else if (code == 2) { out << "geographic\n"; } else if (code == 2) { out << "geocentric\n"; } else { out << "unknown\n"; } return out; } std::ostream &ossimTiffInfo::printRasterType(std::ostream &out, const std::string &prefix, ossim_uint16 code) const { // key 1025 Section 6.3.1.2 Codes out << prefix << RASTER_TYPE_KW << ": "; if (code == 1) { out << "pixel_is_area\n"; } else if (code == 2) { out << "pixel_is_point\n"; } else { out << "unknown\n"; } return out; } std::ostream &ossimTiffInfo::printAngularUnits(std::ostream &out, const std::string &prefix, ossim_uint16 code) const { // key 2054 Section 6.3.1.4 Codes out << prefix << ANGULAR_UNITS_KW << ": "; switch (code) { case 9101: { out << "radians\n"; break; } case 9102: { out << "degrees\n"; break; } case 9103: { out << "arc_minutes\n"; break; } case 9104: { out << "arc_seconds\n"; break; } case 9105: { out << "grad\n"; break; } case 9106: { out << "gon\n"; break; } case 9107: { out << "dms\n"; break; } case 9108: { out << "dms_hemisphere\n"; break; } default: { out << "unknown\n"; break; } } return out; } std::ostream &ossimTiffInfo::printDigitalGlobe(std::ostream &out, const std::string &prefix) const { ossimFilename connection = m_connectionString; bool isDigitalGlobe = false; ossimString copyright; ossimRegExp regex("m1bs|p1bs"); ossimString drivePart; ossimString pathPart; ossimString filePart; ossimString extPart; connection.split(drivePart, pathPart, filePart, extPart); if (!filePart.empty()) { ossimString downcaseFilePart = filePart.downcase(); if (regex.find(downcaseFilePart.c_str())) { out << prefix << "is_digital_globe: true\n"; connection.setExtension("IMD"); if(connection.exists()) { ossimQuickbirdMetaData md; if (md.open(connection, ossimQuickbirdMetaData::QB_PARSE_TYPE_IMD)) { ossimKeywordlist kwl; ossimString tempPrefix = (prefix); md.saveState(kwl, tempPrefix.c_str()); out << kwl << "\n"; } } } } return out; } std::ostream &ossimTiffInfo::printCoordTrans(std::ostream &out, const std::string &prefix, ossim_uint16 code) const { // key 3075 Section 6.3.3.3 Codes out << prefix << "coord_trans: "; switch (code) { case 1: { out << "TransverseMercator\n"; break; } case 2: { out << "TransvMercator_Modified_Alaska\n"; break; } case 3: { out << "ObliqueMercator\n"; break; } case 4: { out << "ObliqueMercator_Laborde\n"; break; } case 5: { out << "ObliqueMercator_Rosenmund\n"; break; } case 6: { out << "ObliqueMercator_Spherical\n"; break; } case 7: { out << "Mercator\n"; break; } case 8: { out << "LambertConfConic_2SP\n"; break; } case 9: { out << "LambertConfConic_Helmert\n"; break; } case 10: { out << "LambertAzimEqualArea\n"; break; } case 11: { out << "AlbersEqualArea\n"; break; } case 12: { out << "AzimuthalEquidistant\n"; break; } case 13: { out << "EquidistantConic\n"; break; } case 14: { out << "Stereographic\n"; break; } case 15: { out << "PolarStereographic\n"; break; } case 16: { out << "ObliqueStereographic\n"; break; } case 17: { out << "Equirectangular\n"; break; } case 18: { out << "CassiniSoldner\n"; break; } case 19: { out << "Gnomonic\n"; break; } case 20: { out << "MillerCylindrical\n"; break; } case 21: { out << "Orthographic\n"; break; } case 22: { out << "Polyconic\n"; break; } case 23: { out << "Robinson\n"; break; } case 24: { out << "Sinusoidal\n"; break; } case 25: { out << "VanDerGrinten\n"; break; } case 26: { out << "NewZealandMapGrid\n"; break; } case 27: { out << "TransvMercator_SouthOriented\n"; break; } default: { out << code << " unknown\n"; break; } } return out; } std::ostream &ossimTiffInfo::printLinearUnits(std::ostream &out, const std::string &prefix, const std::string &key, ossim_uint16 code) const { // key 3076 Section 6.3.1.3 Codes out << prefix << key << ": "; switch (code) { case 9001: { out << "meters\n"; break; } case 9002: { out << "feet\n"; break; } case 9003: { out << "us_survey_feet\n"; break; } case 9004: { out << "foot_modified_american\n"; break; } case 9005: { out << "foot_clarke\n"; break; } case 9006: { out << "foot_indian\n"; break; } case 9007: { out << "link\n"; break; } case 9008: { out << "link_benoit\n"; break; } case 9009: { out << "link_sears\n"; break; } case 9010: { out << "chain_benoit\n"; break; } case 9011: { out << "chain_sears\n"; break; } case 9012: { out << "yard_sears\n"; break; } case 9013: { out << "yard_indian\n"; break; } case 9014: { out << "fathom\n"; break; } case 9015: { out << "mile_international_nautical\n"; break; } default: { out << code << " unknown\n"; break; } } return out; } std::ostream &ossimTiffInfo::printOrientation(std::ostream &out, const std::string &prefix, ossim_uint16 code) const { // Tag 274: out << prefix << "orientation: "; switch (code) { case 1: { out << "top_left\n"; break; } case 2: { out << "top_right\n"; break; } case 3: { out << "bottom_right\n"; break; } case 4: { out << "bottom_left\n"; break; } case 5: { out << "left_top\n"; break; } case 6: { out << "right_top\n"; break; } case 7: { out << "right_bottom\n"; break; } case 8: { out << "left_bottom\n"; break; } default: { out << code << " unknown\n"; break; } } return out; } void ossimTiffInfo::getDirPrefix(ossim_int32 index, std::string &prefix) const { prefix += "image"; std::ostringstream s; s << index; prefix += s.str(); prefix += "."; } bool ossimTiffInfo::getPixelScale(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimDpt &scale) const { bool result = false; std::vector floats; if (getFloats(gtiffPrefix, MODEL_PIXEL_SCALE_KW, gtiffKwl, floats)) { if (floats.size() == 3) { scale.x = floats[0]; scale.y = floats[1]; result = true; } } return result; } bool ossimTiffInfo::getTiePoint(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, std::vector &ties) const { return getFloats(gtiffPrefix, MODEL_TIE_POINT_KW, gtiffKwl, ties); } bool ossimTiffInfo::getModelTransform(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, std::vector &xfrm) const { return getFloats(gtiffPrefix, MODEL_TRANSFORM_KW, gtiffKwl, xfrm); } bool ossimTiffInfo::getFloats(const ossimString >iffPrefix, const ossimString &key, const ossimKeywordlist >iffKwl, std::vector &floats) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), key.c_str()); if (lookup) { ossimString line = lookup; result = getFloats(line, floats); } return result; } bool ossimTiffInfo::getFloats(const ossimString &line, std::vector &floats) const { bool result = false; floats.clear(); if (line.size()) { ossim_float64 f; std::istringstream is(line); is >> f; // Get the first double. while (!is.fail()) { floats.push_back(f); is >> f; } } if (floats.size()) { result = true; } return result; } bool ossimTiffInfo::getDatumCode(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &datumCode) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), GEODETIC_DATUM_KW.c_str()); // There is some ambiguity in the definition of EPSG GCS code. Here both the datum code (6000- // series) and projection code (4000-series) are tested to get to the datum's native ascii code: // Look for GEODETIC_DATUM_KW code first: if (lookup) { ossim_int32 code = ossimString(lookup).toInt32(); result = getDatumCode(code, datumCode); } if (!result) { // Try GCS_CODE_KW: lookup = gtiffKwl.find(gtiffPrefix.c_str(), ossimKeywordNames::GCS_CODE_KW); if (lookup) { ossim_int32 code = ossimString(lookup).toInt32(); result = getDatumCode(code, datumCode); } } return result; } bool ossimTiffInfo::getDatumCode(ossim_int32 code, ossimString &datumCode) const { bool result = false; datumCode.clear(); switch (code) { case 4267: case 6267: { datumCode = "NAS-C"; break; } case 4269: case 6269: { datumCode = "NAR-C"; break; } case 4322: case 6322: { datumCode = "WGD"; break; } case 4326: case 6326: { datumCode = "WGE"; break; } } // matches: switch(code) if (datumCode.size()) { result = true; } return result; } bool ossimTiffInfo::getPcsCode(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &pcsCode) const { bool result = false; // Check for key "pcs_code": const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), ossimKeywordNames::PCS_CODE_KW); if (lookup) { pcsCode = lookup; ossim_uint32 code = pcsCode.toUInt32(); if (code != 32767) { // See if we handle this code in our projection factories. ossimRefPtr proj = ossimEpsgProjectionFactory::instance()->createProjection(pcsCode); if (proj.valid()) { proj = 0; result = true; } } } if (result == false) { // Check for key "pcs_citation": lookup = gtiffKwl.find(gtiffPrefix.c_str(), "pcs_citation"); if (lookup) { ossimString spec = lookup; // Strip commonly found or bar '|' from end if present. spec.trim(ossimString("|")); // See if we handle this code in our projection factories. ossimRefPtr proj = ossimEpsgProjectionFactory::instance()->createProjection(spec); if (proj.valid()) { ossimMapProjection *mapProj = dynamic_cast(proj.get()); if (mapProj) { ossim_uint32 intCode = mapProj->getPcsCode(); if (intCode != 32767) { proj = 0; pcsCode = ossimString::toString(intCode); result = true; } } } } } return result; } bool ossimTiffInfo::getUnits(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &units) const { bool result = true; ossimString linearUnits = ""; getLinearUnits(gtiffPrefix, gtiffKwl, linearUnits); ossimString angularUnits = ""; getAngularUnits(gtiffPrefix, gtiffKwl, angularUnits); ossimString modelType; getModelType(gtiffPrefix, gtiffKwl, modelType); if (modelType == "geographic") { if (angularUnits.size()) { units = angularUnits; } else { units = "degrees"; } } else if (modelType == "projected") { if (linearUnits.size()) { units = linearUnits; } else { units = "meters"; } } else { units = "meters"; } return result; } bool ossimTiffInfo::getLinearUnits(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &linearUnits) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), LINEAR_UNITS_KW.c_str()); if (lookup) { linearUnits = lookup; result = true; } return result; } bool ossimTiffInfo::getVerticalUnits(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &verticalUnits) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), VERTICAL_UNITS_KW.c_str()); if (lookup) { verticalUnits = lookup; result = true; } return result; } bool ossimTiffInfo::getAngularUnits(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &angularUnits) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), ANGULAR_UNITS_KW.c_str()); if (lookup) { angularUnits = lookup; result = true; } return result; } bool ossimTiffInfo::getPixelType(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &pixelType) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), RASTER_TYPE_KW.c_str()); if (lookup) { pixelType = lookup; result = true; } return result; } bool ossimTiffInfo::getModelType(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &modelType) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), MODEL_TYPE_KW.c_str()); if (lookup) { modelType = lookup; result = true; } return result; } bool ossimTiffInfo::getOssimProjectionName(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &ossimProj) const { bool result = false; ossimProj.clear(); const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), COORD_TRANS_CODE_KW.c_str()); if (lookup) { ossim_uint32 code = ossimString(lookup).toUInt32(); ossimGeoTiffCoordTransformsLut lut; ossimProj = lut.getEntryString(code); if (ossimProj.size()) { result = true; } } return result; } ossim_uint32 ossimTiffInfo::getLines(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl) const { ossim_uint32 result = 0; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), IMAGE_LENGTH_KW.c_str()); if (lookup) { result = ossimString(lookup).toUInt32(); } return result; } ossim_uint32 ossimTiffInfo::getSamples(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl) const { ossim_uint32 result = 0; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), IMAGE_WIDTH_KW.c_str()); if (lookup) { result = ossimString(lookup).toUInt32(); } return result; } bool ossimTiffInfo::getStdParallelOne(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &value) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), ossimKeywordNames::STD_PARALLEL_1_KW); if (lookup) { value = lookup; result = true; } return result; } bool ossimTiffInfo::getStdParallelTwo(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &value) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), ossimKeywordNames::STD_PARALLEL_2_KW); if (lookup) { value = lookup; result = true; } return result; } bool ossimTiffInfo::getFalseEasting(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &value) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), ossimKeywordNames::FALSE_EASTING_KW); if (lookup) { value = lookup; result = true; } return result; } bool ossimTiffInfo::getFalseNorthing(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimString &value) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), ossimKeywordNames::FALSE_NORTHING_KW); if (lookup) { value = lookup; result = true; } return result; } bool ossimTiffInfo::getFalseEastingNorthing(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossimDpt &eastingNorthing) const { bool result = false; ossimString value; if (getFalseEasting(gtiffPrefix, gtiffKwl, value)) { eastingNorthing.x = value.toFloat64(); if (getFalseNorthing(gtiffPrefix, gtiffKwl, value)) { eastingNorthing.y = value.toFloat64(); result = true; } } return result; } bool ossimTiffInfo::getScaleFactor(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossim_float64 &value) const { bool result = false; const char *lookup = gtiffKwl.find(gtiffPrefix.c_str(), ossimKeywordNames::SCALE_FACTOR_KW); if (lookup) { value = ossimString(lookup).toFloat64(); result = true; } return result; } bool ossimTiffInfo::getOriginLat(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossim_float64 &value) const { bool result = false; //--- // Not sure of the order of precedence here. //--- const char *projOriginLatGeoKey = gtiffKwl.find(gtiffPrefix.c_str(), ORIGIN_LATITUDE_KW.c_str()); //--- // Go for this key first as it is used in geotiff spec example: // http://www.remotesensing.org/geotiff/spec/geotiff3.html#3.1.3. //--- if (projOriginLatGeoKey) { value = ossimString(projOriginLatGeoKey).toFloat64(); result = true; } else { const char *projCenterLatGeoKey = gtiffKwl.find(gtiffPrefix.c_str(), CENTER_LATITUDE__KW.c_str()); if (projCenterLatGeoKey) { value = ossimString(projCenterLatGeoKey).toFloat64(); result = true; } else { const char *projFalseOriginLatGeoKey = gtiffKwl.find(gtiffPrefix.c_str(), FALSE_ORIGIN_LATITUDE_KW.c_str()); if (projFalseOriginLatGeoKey) { //--- // Seems the term "false" implies it should be added to the real // origin? //--- value = ossimString(projFalseOriginLatGeoKey).toFloat64(); result = true; } } } return result; } bool ossimTiffInfo::getCentralMeridian(const ossimString >iffPrefix, const ossimKeywordlist >iffKwl, ossim_float64 &value) const { bool result = false; //--- // Not sure of the order of precedence here. //--- const char *projCenterLongGeoKey = gtiffKwl.find(gtiffPrefix.c_str(), CENTER_LONGITUDE_KW.c_str()); //--- // Go for this key first as it is used in geotiff spec example: // http://www.remotesensing.org/geotiff/spec/geotiff3.html#3.1.3. //--- if (projCenterLongGeoKey) { value = ossimString(projCenterLongGeoKey).toFloat64(); result = true; } else { const char *projOriginLongGeoKey = gtiffKwl.find(gtiffPrefix.c_str(), ORIGIN_LONGITUDE_KW.c_str()); if (projOriginLongGeoKey) { value = ossimString(projOriginLongGeoKey).toFloat64(); result = true; } else { const char *projFalseOriginLongGeoKey = gtiffKwl.find(gtiffPrefix.c_str(), FALSE_ORIGIN_LONGITUDE_KW.c_str()); if (projFalseOriginLongGeoKey) { //--- // Seems the term "false" implies it should be added to the real // origin? //--- value = ossimString(projFalseOriginLongGeoKey).toFloat64(); result = true; } } } return result; } void ossimTiffInfo::getTieSets(const std::vector &ties, ossim_uint32 width, ossim_uint32 height, ossimTieGptSet &tieSet) const { ossim_uint32 idx = 0; ossim_uint32 tieCount = (ossim_uint32)ties.size() / 6; const double *tiePointsPtr = &ties.front(); double offset = 0; if (hasOneBasedTiePoints(ties, width, height)) { offset = -1.0; } for (idx = 0; idx < tieCount; ++idx) { ossimDpt xyPixel(tiePointsPtr[0] + offset, tiePointsPtr[1] + offset); // tie[3] = x, tie[4] ossimGpt gpt(tiePointsPtr[4], tiePointsPtr[3], tiePointsPtr[5]); tieSet.addTiePoint(new ossimTieGpt(gpt, xyPixel, .5)); tiePointsPtr += 6; } } bool ossimTiffInfo::hasOneBasedTiePoints( const std::vector &ties, ossim_uint32 width, ossim_uint32 height) const { bool result = false; // Assuming ties of (x,y,z,lat,lon,hgt) so size should be divide by 3. if (ties.size() % 6) { return result; } ossim_float64 minX = 999999.0; ossim_float64 minY = 999999.0; ossim_float64 maxX = 0.0; ossim_float64 maxY = 0.0; const ossim_uint32 SIZE = (ossim_uint32)ties.size(); ossim_uint32 tieIndex = 0; while (tieIndex < SIZE) { if (ties[tieIndex] < minX) minX = ties[tieIndex]; if (ties[tieIndex] > maxX) maxX = ties[tieIndex]; if (ties[tieIndex + 1] < minY) minY = ties[tieIndex + 1]; if (ties[tieIndex + 1] > maxY) maxY = ties[tieIndex + 1]; tieIndex += 6; } if ((minX == 1) && (maxX == width) && (minY == 1) && (maxY == height)) { result = true; } #if 0 if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimGeoTiff::hasOneBasedTiePoints DEBUG:" << "\nminX: " << minX << "\nmaxX: " << maxX << "\nminY: " << minY << "\nmaxY: " << maxY << "\ntheWidth: " << theWidth << "\ntheLength: " << theLength << "\none based: " << (result?"true":"false") << std::endl; } #endif return result; } ossim-Miami-2.9.1/src/support_data/ossimTiffWorld.cpp000066400000000000000000000170671352751253100227010ustar00rootroot00000000000000//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Ken Melero // // Description: Container class for a tiff world file data. // //******************************************************************** // $Id: ossimTiffWorld.cpp 19682 2011-05-31 14:21:20Z dburken $ #include #include #include #include #include #include #include #include #include #include #include using namespace std; //************************************************************************** // ossimTiffWorld::ossimTiffWorld() //*************************************************************************** ossimTiffWorld::ossimTiffWorld() : theXform1(1.0), theXform2(0.0), theXform3(0.0), theXform4(-1.0), theTranslation(0.0,0.0), thePixelType(OSSIM_PIXEL_IS_AREA), theUnit(OSSIM_METERS), theComputedScale(0.0, 0.0), theComputedRotation(0.0) {} //************************************************************************** // ossimTiffWorld::ossimTiffWorld(const char* file, PixelType ptype) //*************************************************************************** ossimTiffWorld::ossimTiffWorld(const char* file, ossimPixelType ptype, ossimUnitType scaleUnits) : theXform1(1.0), theXform2(0.0), theXform3(0.0), theXform4(-1.0), theTranslation(0.0,0.0), thePixelType(ptype), theUnit(scaleUnits), theComputedScale(0.0, 0.0), theComputedRotation(0.0) { open(ossimFilename(file), ptype, scaleUnits); } bool ossimTiffWorld::open(const ossimFilename& file, ossimPixelType ptype, ossimUnitType unit) { bool result = false; ifstream is; is.open(file.c_str()); if( !is.is_open() ) { // ESH 07/2008, Trac #234: OSSIM is case sensitive // when using worldfile templates during ingest // -- If first you don't succeed with the user-specified // filename, try again with the results of a case insensitive search. ossimFilename fullName(file); ossimDirectory directory(fullName.path()); ossimFilename filename(fullName.file()); std::vector result; bool bSuccess = directory.findCaseInsensitiveEquivalents( filename, result ); if ( bSuccess == true ) { int numResults = (int)result.size(); int i; for ( i=0; i> theXform1 >> theXform2 >> theXform3 >> theXform4 >> x >> y; theTranslation = ossimDpt(x,y); // Compute the affine parameters from the transform: theComputedRotation = atan2(theXform2,theXform1); /* * Commented out warning. * Used all the time for tie and scale, NOT for affine. We could wrap around trace * if we added trace to class. (drb - 20110115) */ #if 0 double angle2 = atan2(theXform4,theXform3); if (fabs(theComputedRotation - angle2) > 0.00001) { ossimNotify(ossimNotifyLevel_WARN) << "ossimTiffWorld -- Non-affine transform encountered." << " Use of an affine transform to represent this world file geometry will result in errors." << endl; } #endif double cos_rot = cos(theComputedRotation); if (cos_rot != 0.0) { theComputedScale.x = theXform1/cos_rot; theComputedScale.y = theXform4/cos_rot; } else { theComputedScale.x = theXform4; theComputedScale.y = theXform1; } thePixelType = ptype; theUnit = unit; is.close(); result = true; } return result; } ossimTiffWorld::~ossimTiffWorld() { } void ossimTiffWorld::forward(const ossimDpt& ip, ossimDpt& transformedPoint) { transformedPoint.x = ip.x*theXform1 + ip.y*theXform2 + theTranslation.x; transformedPoint.y = ip.x*theXform3 + ip.y*theXform4 + theTranslation.y; } bool ossimTiffWorld::saveToOssimGeom(ossimKeywordlist& kwl, const char* prefix)const { ossimDpt scale(fabs(theXform1), fabs(theXform4)); ossimDpt tie(theTranslation.x, theTranslation.y); if ( (theUnit == OSSIM_FEET) || (theUnit == OSSIM_US_SURVEY_FEET) ) { // Convert to meters. scale.x = ossimUnitConversionTool(scale.x, theUnit).getMeters(); scale.y = ossimUnitConversionTool(scale.y, theUnit).getMeters(); tie.x = ossimUnitConversionTool(tie.x, theUnit).getMeters(); tie.y = ossimUnitConversionTool(tie.y, theUnit).getMeters(); } // Shift the tie point to be relative to the center of the pixel. if(thePixelType == OSSIM_PIXEL_IS_AREA) { tie.x += (scale.x/2.0); tie.y -= (scale.y/2.0); // Adjust the keyword list to reflect pixel is point. kwl.add(prefix, ossimKeywordNames::PIXEL_TYPE_KW, "pixel_is_point", true); } // Units in feet converted to meters up above. ossimString units = "meters"; if(theUnit == OSSIM_DEGREES) { units = "degrees"; } kwl.add(prefix, ossimKeywordNames::TIE_POINT_XY_KW, tie.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW, units.c_str(), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW, scale.toString().c_str(), true); kwl.add(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW, units.c_str(), true); return true; } bool ossimTiffWorld::loadFromOssimGeom(const ossimKeywordlist& kwl, const char* prefix) { theXform2 = 0.0; theXform3 = 0.0; const char* lookup; // Get the scale... lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW); if (lookup) { ossimDpt scale; scale.toPoint(std::string(lookup)); theXform1 = scale.x; theXform4 = -(scale.y); } else // BACKWARDS COMPATIBILITY LOOKUPS... { ossimString xscale = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_X_KW); ossimString yscale = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW); theXform1 = xscale.toDouble(); theXform4 = -(yscale.toDouble()); } // Get the tie... lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_XY_KW); if (lookup) { ossimDpt tie; tie.toPoint(std::string(lookup)); theTranslation.x = tie.x; theTranslation.y = tie.y; } else // BACKWARDS COMPATIBILITY LOOKUPS... { ossimString easting = kwl.find(prefix, ossimKeywordNames::TIE_POINT_EASTING_KW); ossimString northing = kwl.find(prefix, ossimKeywordNames::TIE_POINT_NORTHING_KW); theTranslation.x = easting.toDouble(); theTranslation.y = northing.toDouble(); } return true; } std::ostream& ossimTiffWorld::print(std::ostream& out) const { out << setiosflags(ios::fixed) << setprecision(15) << theXform1 << "\n" << theXform2 << "\n" << theXform3 << "\n" << theXform4 << "\n" << theTranslation << endl; return out; } std::ostream& operator<<(std::ostream& out, const ossimTiffWorld& obj) { return obj.print(out); } ossim-Miami-2.9.1/src/support_data/ossimWavelength.cpp000066400000000000000000000133041352751253100230730ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Class definition for ossimWavelength. // //---------------------------------------------------------------------------- #include #include #include #include ossimWavelength::ossimWavelength() : m_map() {} ossimWavelength::ossimWavelength( const ossimWavelength& obj ) : m_map( obj.m_map ) {} const ossimWavelength& ossimWavelength::operator=( const ossimWavelength& rhs ) { if ( this != &rhs ) { m_map = rhs.m_map; } return *this; } ossimWavelength::~ossimWavelength() { } const ossimWavelength::WavelengthMap& ossimWavelength::getMap() const { return m_map; } ossimWavelength::WavelengthMap& ossimWavelength::getMap() { return m_map; } bool ossimWavelength::initialize( const ossimEnviHeader& hdr ) { //--- // Example envi wavelength format: // wavelength = { 374.323608, 382.530487, 390.737427 } //--- ossimString value; // Check the units... ossimString key = "wavelength units"; if ( hdr.getValue( key, value ) ) { if ( value.downcase() == "nanometers" ) { // Check for wavelength key: key = "wavelength"; if ( hdr.getValue( key, value ) ) { if ( value.size() ) { // Split into array. value.trim( ossimString("{}") ); std::vector list; value.split( list, ossimString(","), true ); if ( list.size() ) { // Initialize the map: std::vector::const_iterator i = list.begin(); ossim_uint32 band = 0; ossim_float32 wavelength = 0.0; while ( i != list.end() ) { wavelength = (*i).toFloat64(); m_map.insert( std::make_pair( wavelength, band ) ); ++band; ++i; } } } } } } return ( m_map.size() ? true : false); } // End: bool ossimWavelength::initialize(const ossimEnviHeader&) using namespace std; ossimWavelength::WavelengthMap::const_iterator ossimWavelength::findClosestIterator( const ossim_float64& requestedWavelength, const ossim_float64& thresholdFromCenter ) const { WavelengthMap::const_iterator result = m_map.lower_bound( requestedWavelength ); if ( result != m_map.end() ) { if ( result != m_map.begin() ) // && (result->first > requestedWavelength) ) { // Somewhere in the middle. WavelengthMap::const_iterator lower = result; --lower; ossim_float64 t = (requestedWavelength - lower->first) / (result->first -lower->first); if ( t < 0.5 ) { result = lower; } } } else { --result; } if ( result != m_map.end() ) { // Within threshold check. if ( std::fabs( result->first - requestedWavelength) > thresholdFromCenter ) { result = m_map.end(); } } // if ( result != m_map.end() ) return result; } // End: WavelengthMap::const_iterator ossimWavelength::findClosestIterator ossim_int32 ossimWavelength::findClosestIndex( const ossim_float64& requestedWavelength, const ossim_float64& thresholdFromCenter ) const { ossim_int32 result = -1; WavelengthMap::const_iterator i = findClosestIterator( requestedWavelength, thresholdFromCenter ); if ( i != m_map.end() ) { result = (*i).second; } return result; } // End: ossim_int32 ossimWavelength::findClosestIndex(... bool ossimWavelength::getRgbBands( std::vector& bands ) const { bool result = false; if ( m_map.size() ) { //--- // Attempt to find bands with closest rgb wavelengths. // red: 620 - 750 nm // green: 495 - 570 nm // blue: 450 - 495 nm //--- //const ossim_float32 RED_WAVELENGTH = 439.978577; // 442.0; //const ossim_float32 GREEN_WAVELENGTH = 546.666504; // 546.0; //const ossim_float32 BLUE_WAVELENGTH = 636.941406; // 637.0; const ossim_float32 RED_WAVELENGTH = 685.0; const ossim_float32 GREEN_WAVELENGTH = 532.5; const ossim_float32 BLUE_WAVELENGTH = 472.5; const ossim_float32 RED_THRESHOLD_FROM_CENTER = 65.0; const ossim_float32 GREEN_THRESHOLD_FROM_CENTER = 37.5; const ossim_float32 BLUE_THRESHOLD_FROM_CENTER = 22.5; WavelengthMap::const_iterator r = findClosestIterator( RED_WAVELENGTH, RED_THRESHOLD_FROM_CENTER ); WavelengthMap::const_iterator g = findClosestIterator( GREEN_WAVELENGTH, GREEN_THRESHOLD_FROM_CENTER ); WavelengthMap::const_iterator b = findClosestIterator( BLUE_WAVELENGTH, BLUE_THRESHOLD_FROM_CENTER ); if ( (r != m_map.end()) && (g != m_map.end()) && (b != m_map.end()) ) { bands.resize(3); bands[0] = (*r).second; bands[1] = (*g).second; bands[2] = (*b).second; result = true; } } return result; } // bool ossimWavelength::getRgbBands( std::vector& ) const ossimWavelength::WavelengthMap::const_iterator ossimWavelength::end() const { return m_map.end(); } ossimWavelength::WavelengthMap::iterator ossimWavelength::end() { return m_map.end(); } ossim-Miami-2.9.1/src/support_data/ossimWkt.cpp000066400000000000000000000144111352751253100215340ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // ossimWkt class definition. A well known text(WKT) utility class. // //---------------------------------------------------------------------------- // $Id$ /************************************************************************************************* * Sample WKT string (for reference, line feeds and spaces added for human readability) * * PROJCS["NAD_1983_HARN_Lambert_Conformal_Conic", * GEOGCS["GCS_North_American_1983_HARN", * DATUM["NAD83_High_Accuracy_Regional_Network", * SPHEROID["GRS_1980",6378137,298.257222101, AUTHORITY["EPSG","7019"]], * AUTHORITY["EPSG","6152"]], * PRIMEM["Greenwich",0], * UNIT["degree",0.0174532925199433]], * PROJECTION["Lambert_Conformal_Conic_2SP"], * PARAMETER["standard_parallel_1",43], * PARAMETER["standard_parallel_2",45.5], * PARAMETER["latitude_of_origin",41.75], * PARAMETER["central_meridian",-120.5], * PARAMETER["false_easting",1312335.958005249], * PARAMETER["false_northing",0], * UNIT["foot",0.3048, AUTHORITY["EPSG","9002"]]] * **************************************************************************************************/ #include #include #include #include using namespace std; // tmp drb... ossimWkt::ossimWkt() : m_kwl() { } ossimWkt::~ossimWkt() { } bool ossimWkt::parse( const std::string& wkt ) { bool result = false; if ( wkt.size() ) { std::istringstream is( wkt ); result = parseWktGroup( is, m_kwl ); } return result; } const ossimKeywordlist& ossimWkt::getKwl() const { return m_kwl; } bool ossimWkt::parseWktGroup( std::istringstream& is, ossimKeywordlist& kwl ) { bool result = false; if ( is.good() ) { char c; // Get the wkt group name up to '[', e.g. "PROJCS[". std::string prefix = ""; std::string object; // std::string v; while ( is.good() ) { is.get(c); if ( is.good() ) { // Look for parens or square brackets. if ( (c != '[') && (c != '(') ) { object.push_back(c); } else { result = parseObject( is, prefix, object, kwl ); } } else { break; } } } return result; } bool ossimWkt::parseObject( std::istringstream& is, const std::string& prefix, const std::string& object, ossimKeywordlist& kwl ) { bool result = false; result = parseName( is, prefix, object, kwl ); if ( result && is.good() ) { char c; ossim_uint32 myObjectIndex = 0; ossim_uint32 paramIndex = 0; while ( is.good() ) { is.get(c); if ( is.good() ) { if ( c == ',' ) { parseParam( is, prefix, object, myObjectIndex, paramIndex, kwl ); } else if ( (c == ']') || (c == ')') ) { break; // End of object. } } } } return result; } bool ossimWkt::parseName( std::istringstream& is, const std::string& prefix, const std::string& object, ossimKeywordlist& kwl ) { bool result = false; char c; std::string name; // Find the first quote: while ( is.good() ) { is.get(c); if ( is.good() ) { if ( c == '"' ) { break; } } } // Get the name: while ( is.good() ) { is.get(c); if ( is.good() ) { if ( c != '"' ) { name.push_back(c); } else { break; // End quote: } } } if ( name.size() ) { // Add to keyword list. std::string key; if ( prefix.size() ) { key += prefix; } key += object; key += ".name"; kwl.addPair( key, name ); result = true; } return result; } bool ossimWkt::parseParam( std::istringstream& is, const std::string& prefix, const std::string& object, ossim_uint32& objectIndex, ossim_uint32& paramIndex, ossimKeywordlist& kwl ) { bool result = false; char c; std::string name; // Get the name: while ( is.good() ) { int i = is.peek(); // Don't gobble the trailing comma or bracket. if ( (i == ',') || (i == ']') || (i == ')') ) { // End of param. if ( name.size() ) { // Add to keyword list. std::string key; if ( prefix.size() ) { key += prefix; } key += object; key += ".param"; key += ossimString::toString(paramIndex).string(); kwl.addPair( key, name ); name = ""; ++paramIndex; result = true; } break; // Next param or at end of object. } is.get(c); if ( is.good() ) { // Look nexted object. if ( (c == '[') || (c == '(') ) { std::string myPrefix; if ( prefix.size() ) { myPrefix += prefix; } myPrefix += object; myPrefix += "."; //--- // Special hack for duplicated keyword "PARAMETER" //--- if ( name == "PARAMETER" ) { name += ossimString::toString(objectIndex).string(); ++objectIndex; } result = parseObject( is, myPrefix, name, kwl ); name = ""; } else { name.push_back(c); } } } return result; } ossim-Miami-2.9.1/src/support_data/ossimXmpInfo.cpp000066400000000000000000000461471352751253100223620ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Extensible Metadata Platform (XMP) Info object. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Static trace for debugging. static const ossimTrace traceDebug( ossimString("ossimXmpInfo:debug") ); ossimXmpInfo::ossimXmpInfo() : ossimInfoBase(), m_file(), m_xmpApp1XmlBlock() { } ossimXmpInfo::~ossimXmpInfo() { } bool ossimXmpInfo::open(const ossimFilename& file) { //--- // NOTE: // This parser was written for a specific aerial camera. If something more generic is // needed please provide sample to the group. D. Burken, 17 January 2013. //--- bool result = false; //--- // Open the file. //--- std::ifstream str(file.c_str(), std::ios_base::binary|std::ios_base::in); if ( str.good() ) { // Parse for XMP APP1 XML block. Currently only case. std::string xmlString; result = getXmpApp1XmlBlock( str, xmlString ); if ( result ) { m_file = file; m_xmpApp1XmlBlock = xmlString; } else { m_file.clear(); m_xmpApp1XmlBlock.clear(); } } return result; } bool ossimXmpInfo::getXmpApp1XmlBlock( std::ifstream& str, std::string& xmpApp1XmlBlock ) const { bool result = false; if ( str.good() ) { ossim_uint8 c; // Look for Start Of Image (SOI) marker 0xFFD8: str.read( (char*)&c, 1); if ( c == 0xff ) { str.read( (char*)&c, 1); if ( c == 0xd8 ) { // Found SOI marker. // Now find APP1 marker 0xffe1. Only do 24 iterations max: for ( ossim_uint32 i = 0; i < 24; ++i ) { str.read( (char*)&c, 1); if ( c == 0xff ) { str.read( (char*)&c, 1); if ( c == 0xe1 ) { // Found APP1 marker. //--- // Next two bytes are the length, MSB first (big endian) per jpeg spec. // length = 2 + 29 + length_of_xmp_packet //--- ossim_uint16 xpacketLength = 0; str.read( (char*)&xpacketLength, 2 ); // See if system is not big endian and swap if needed. if ( ossim::byteOrder() != OSSIM_BIG_ENDIAN ) { ossimEndian swapper; swapper.swap( xpacketLength ); } if ( xpacketLength > 31 ) { //--- // XMP namepsace URI, used as unique ID: // Null terminated ascii string: "http://ns.adobe.com/xap/1.0/" // (29 bytes) // Not using getline until ID verified. //--- const ossim_uint32 XMP_ID_SIZE = 29; std::vector v( XMP_ID_SIZE ); // Read the next 29 bytes. (string + null) str.read( &v.front(), XMP_ID_SIZE ); // Copy. v.push_back( '\0' ); // Just in case string is bad. std::string s = &v.front(); if ( s == "http://ns.adobe.com/xap/1.0/" ) { //--- // Now read header to determine encoding: // Note: Currently hard coded for UTF-8. //--- //--- // Look for " 31 ) } // Matches: if ( c == 0xd8 ) } // Matches: if ( c == 0xff ) } // Matches: for ( ossim_uint32 i; i < 24; ++i ) } // Matches: if ( c == 0xd8 ) } // Matches: if ( c == 0xff ) } // Matches: if ( str.good() ) return result; } // End: ossimXmpInfo::getXmpApp1XmlBlock std::ostream& ossimXmpInfo::print(std::ostream& out) const { if ( getXmpApp1XmlBlock().size() ) { std::string prefix = ""; std::string ext = m_file.ext().downcase().string(); if ( ( ext == "jpg" ) || ( ext == "jpeg" ) ) { prefix = "jpeg."; } std::string s; // Date: getDate( s ); if ( s.size() ) { out << prefix << "acquisitionDate: " << s << std::endl; } // Mission ID: getMissionId( s ); if ( s.size() ) { out << prefix << "missionId: " << s << std::endl; } // Sensor ID: getSensorId( s ); if ( s.size() ) { out << prefix << "sensorId: " << s << std::endl; } out << prefix << "xmp.app1.xml: " << getXmpApp1XmlBlock() << std::endl; } return out; } // End: std::ostream& ossimXmpInfo::print(std::ostream& out) const const std::string& ossimXmpInfo::getXmpApp1XmlBlock() const { return m_xmpApp1XmlBlock; } ossimRefPtr ossimXmpInfo::getProjection( const ossimDrect& imageRect ) const { ossimRefPtr result = 0; if ( getXmpApp1XmlBlock().size() && ( imageRect.hasNans() == false ) ) { // Open a stream to the xml block. std::istringstream is; is.str( m_xmpApp1XmlBlock ); ossimXmlDocument xmlDoc; // Read the xml document: if ( xmlDoc.read( is ) ) { // Find the four corner ground points. ossimString s; ossimString path; ossimGpt ulg; ossimGpt urg; ossimGpt lrg; ossimGpt llg; bool foundAll = false; while ( 1 ) { // Upper left: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:UL_Latitude"; if ( getPath( path, xmlDoc, s ) ) { ulg.lat = s.toFloat64(); } else { break; } path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:UL_Longitude"; if ( getPath( path, xmlDoc, s ) ) { ulg.lon = s.toFloat64(); } else { break; } // Upper right: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:UR_Latitude"; if ( getPath( path, xmlDoc, s ) ) { urg.lat = s.toFloat64(); } else { break; } path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:UR_Longitude"; if ( getPath( path, xmlDoc, s ) ) { urg.lon = s.toFloat64(); } else { break; } // Lower right: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:LR_Latitude"; if ( getPath( path, xmlDoc, s ) ) { lrg.lat = s.toFloat64(); } else { break; } path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:LR_Longitude"; if ( getPath( path, xmlDoc, s ) ) { lrg.lon = s.toFloat64(); } else { break; } // Lower left: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:LL_Latitude"; if ( getPath( path, xmlDoc, s ) ) { llg.lat = s.toFloat64(); } else { break; } path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:LL_Longitude"; if ( getPath( path, xmlDoc, s ) ) { llg.lon = s.toFloat64(); // If we get here mark the status good: foundAll = true; } else { break; } //--- // Final trailing break out of infinite loop. // No code past this point if while loop. //--- break; } if ( foundAll ) { result = new ossimBilinearProjection( imageRect.ul(), imageRect.ur(), imageRect.lr(), imageRect.ll(), ulg, urg, lrg, llg ); } } // Matches: if ( xmlDoc.read( is ) ) } // Matches: if ( getXmpApp1XmlBlock().size() ) return result; } // End: ossimXmpInfo::getProjection void ossimXmpInfo::getDate( std::string& date ) const { date.clear(); if ( getXmpApp1XmlBlock().size() ) { // Open a stream to the xml block. std::istringstream is; is.str( m_xmpApp1XmlBlock ); ossimXmlDocument xmlDoc; // Read the xml document: if ( xmlDoc.read( is ) ) { //--- // ISO8601 date in the form of: YYYY-MM-DDThh:mm:ss.sssZ // Find the four corner ground points. //--- ossimString s; ossimString path; std::string year; std::string month; std::string dayOfMonth; std::string hour; std::string minute; std::string second; std::string milliSecond; bool foundAll = false; while ( 1 ) { // year: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:IRIG_Year"; if ( getPath( path, xmlDoc, s ) ) { year = s.string(); } else { break; } // month: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:IRIG_Month"; if ( getPath( path, xmlDoc, s ) ) { month = s.string(); } else { break; } // day of month: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:IRIG_Day_of_Month"; if ( getPath( path, xmlDoc, s ) ) { dayOfMonth = s.string(); } else { break; } // hour: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:IRIG_Hour"; if ( getPath( path, xmlDoc, s ) ) { hour = s.string(); } else { break; } // minute: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:IRIG_Min"; if ( getPath( path, xmlDoc, s ) ) { minute = s.string(); } else { break; } // second: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:IRIG_Sec"; if ( getPath( path, xmlDoc, s ) ) { second = s.string(); } else { break; } // millisecond: path = "/x:xmpmeta/rdf:RDF/rdf:Description/dc:IRIG_Msec"; if ( getPath( path, xmlDoc, s ) ) { milliSecond = s.string(); } else { break; } // If we get here mark the status good for downstream code. foundAll = true; //--- // Final trailing break out of infinite loop. // No code past this point if while loop. //--- break; } // End: while ( 1 ) if ( foundAll ) { date = year + "-"; // Assuming year in 4 digit form, e.g. 2013. // Month two digit wide. std::ostringstream os1; os1 << std::setiosflags(std::ios_base::fixed|std::ios_base::right) << std::setfill('0') << std::setw(2) << month; date += os1.str() + "-"; // Day two digit wide. std::ostringstream os2; os2 << std::setiosflags(std::ios_base::fixed|std::ios_base::right) << std::setfill('0') << std::setw(2) << dayOfMonth; date += os2.str() + "T"; // Hour two digit wide. std::ostringstream os3; os3 << std::setiosflags(std::ios_base::fixed|std::ios_base::right) << std::setfill('0') << std::setw(2) << hour; date += os3.str() + ":"; // Minute two digit wide. std::ostringstream os4; os4 << std::setiosflags(std::ios_base::fixed|std::ios_base::right) << std::setfill('0') << std::setw(2) << minute; date += os4.str() + ":"; // Second two digit wide. std::ostringstream os5; os5 << std::setiosflags(std::ios_base::fixed|std::ios_base::right) << std::setfill('0') << std::setw(2) << second; date += os5.str() + "."; // Milli second three digit wide. std::ostringstream os6; os6 << std::setiosflags(std::ios_base::fixed|std::ios_base::right) << std::setfill('0') << std::setw(3) << milliSecond; date += os6.str() + "Z"; // Assumption... } } // Matches: if ( xmlDoc.read( is ) ) } // Matches: if ( getXmpApp1XmlBlock().size() ) } // End: void ossimXmpInfo::getDate( std::string& date ) const void ossimXmpInfo::getMissionId( std::string& mission ) const { // Currently nothing in sample data to grab so using mission "x". mission = "x"; } void ossimXmpInfo::getSensorId( std::string& sensor ) const { // Currently nothing in sample data to grab so using sensor "x". sensor = "x"; } bool ossimXmpInfo::getPath( const ossimString& path, const ossimXmlDocument& xdoc, ossimString& s) const { bool result = false; std::vector > xnodes; xdoc.findNodes(path, xnodes); if ( xnodes.size() == 1 ) // Error if more than one. { if ( xnodes[0].valid() ) { s = xnodes[0]->getText(); result = true; } else if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimXmpInfo::getPath ERROR:\n" << "Node not found: " << path << std::endl; } } else if ( xnodes.size() == 0 ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimXmpInfo::getPath ERROR:\n" << "Node not found: " << path << std::endl; } } else { if(traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimXmpInfo::getPath ERROR:\n" << "Multiple nodes found: " << path << std::endl; } } if (!result) { s.clear(); } return result; } // bool ossimXmpInfo::getPath ossim-Miami-2.9.1/src/util/000077500000000000000000000000001352751253100154575ustar00rootroot00000000000000ossim-Miami-2.9.1/src/util/Notes.txt000066400000000000000000000005771352751253100173210ustar00rootroot00000000000000X AutoReg X Equation U FileWalker U Info X OrthoIgen CP PointCloud --pc CP Slope --dem|BB CP Viewshed --dem|BB --image CP Hillshade --dem|BB [--image] CP HLZ [--pc] --dem|BB [--image] CP 2CMV --imageA --imageB CP ColorRelief --dem|BB --lut CP Ortho --image [--dem] CP Chip --image CP PSM --image_pan --image_ms ossim-Miami-2.9.1/src/util/ossimAutRegUtil.cpp000077500000000000000000001513531352751253100212760ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimAutRegUtil.cpp // // License: LGPL // // License: See top level LICENSE.txt file. // // Author: David Hicks // // Description: Utility class for autonomous registration operations. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug ("ossimAutRegUtil:debug"); static ossimTrace traceLog("ossimAutRegUtil:log"); static ossimTrace traceOptions("ossimAutRegUtil:options"); static const std::string APPLICATION_NAME_KW = "application_name"; static const std::string ADJ_DESC_LABEL_KW = "adj_desc_label"; static const std::string FALSE_KW = "false"; static const std::string IMG_1_KW = "img_1"; static const std::string IMG_2_KW = "img_2"; static const std::string IMG_M_KW = "img_m"; // master static const std::string IMG_S_KW = "img_s"; // slave static const std::string OP_KW = "operation"; static const std::string SRC_FILE_KW = "src_file"; static const std::string TRUE_KW = "true"; static const std::string ROI_CENTER_LAT_KW = "roi_center_lat"; static const std::string ROI_CENTER_LON_KW = "roi_center_lon"; static const std::string ROI_RADIUS_KW = "roi_radius"; // meters static const std::string ROI_HEIGHT_KW = "roi_height"; // pixels static const std::string ROI_MAX_LAT_KW = "roi_max_lat"; static const std::string ROI_MAX_LON_KW = "roi_max_lon"; static const std::string ROI_MIN_LAT_KW = "roi_min_lat"; static const std::string ROI_MIN_LON_KW = "roi_min_lon"; static const std::string ROI_WIDTH_KW = "roi_width"; // pixels static const std::string REPORT_FILE_KW = "report_file"; static const std::string FILE_KW = "file"; static const std::string IMG_KW = "image"; static const std::string READER_PROPERTY_KW = "reader_property"; static const std::string OCV_CONFIG_FILE_KW = "ocv_config_file"; static const std::string OCV_DETECTOR_NAME_KW = "ocv_detector_name"; static const std::string OCV_DRAW_MATCHES_FLAG_KW = "ocv_draw_matches_flag"; static const std::string OCV_EXTRACTOR_NAME_KW = "ocv_extractor_name"; static const std::string OCV_MATCHER_NAME_KW = "ocv_matcher_name"; static const std::string OCV_MAX_MATCHES_KW = "ocv_max_matches"; static const std::string OCV_USE_CROSS_CHECK_KW = "ocv_use_cross_check"; static const std::string OCV_USE_GRID_ADAPTED_DETECT_KW = "ocv_use_grid_adapted_detect"; static const std::string OCV_RESULTS_WINDOW_SHOW_KW = "ocv_results_window_show";//???? static const std::string OAX_CONFIG_FILE_KW = "oax_config_file"; static const std::string OAX_CONVERGENCE_CRITERIA_KW = "oax_convergence_criteria"; static const std::string OAX_GROUND_SIGMA_KW = "oax_ground_sigma"; static const std::string OAX_LAT_SIGMA_KW = "oax_lat_sigma"; static const std::string OAX_LON_SIGMA_KW = "oax_lon_sigma"; static const std::string OAX_HGT_SIGMA_KW = "oax_hgt_sigma"; static const std::string OAX_CONTROL_SIGMA_KW = "oax_control_sigma"; static const std::string OAX_MAX_ITERATIONS_KW = "oax_max_iterations"; //***************************************************************************** // METHOD: ossimAutRegUtil::ossimAutRegUtil() // // Constructor. //***************************************************************************** ossimAutRegUtil::ossimAutRegUtil() : ossimReferenced(), m_tGen(0), m_tGenObj(0), m_roiRects(), m_showMatchWindow(false), m_adjExec(0), m_obsSet(0), m_LatLonHgtSigmas(), m_LatLonHgtControlSigmas(), m_rep(0), m_imgLayer(0), m_kwl(new ossimKeywordlist()), m_ocvKwl(0), m_oaxKwl(0), m_srcKwl(0), m_operation(OSSIM_AUTREG_OP_UNKNOWN) { // traceDebug.setTraceFlag(true); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimAutRegUtil::ossimAutRegUtil 1 DEBUG:" << std::endl; } // Default tie point ground sigmas m_LatLonHgtSigmas[0] = 50.0; m_LatLonHgtSigmas[1] = 50.0; m_LatLonHgtSigmas[2] = 50.0; // Default control point ground sigmas m_LatLonHgtControlSigmas[0] = 1.0; m_LatLonHgtControlSigmas[1] = 1.0; m_LatLonHgtControlSigmas[2] = 1.0; // ossimImageGeometry m_geom[0] = 0; m_geom[1] = 0; // Default control image flags m_controlImage[0] = false; m_controlImage[1] = false; m_kwl->setExpandEnvVarsFlag(true); } // Private/hidden ossimAutRegUtil::ossimAutRegUtil( const ossimAutRegUtil& /* obj */ ) { } // Private/hidden const ossimAutRegUtil& ossimAutRegUtil::operator=( const ossimAutRegUtil& /* rhs */) { return *this; } //***************************************************************************** // DESTRUCTOR: ~ossimAutRegUtil() //***************************************************************************** ossimAutRegUtil::~ossimAutRegUtil() { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: ~ossimAutRegUtil(): entered..." << std::endl; clear(); *m_rep << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; *m_rep << endl; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: ~ossimAutRegUtil(): returning..." << std::endl; } void ossimAutRegUtil::addArguments(ossimArgumentParser& ap) { ossimString usageString = ap.getApplicationName(); usageString += " [option]... [input-option]... -img_1 -img_2 \n\nAvailable traces:\n-T \"ossimAutRegUtil:debug\" - General debug trace to standard out.\n-T \"ossimAutRegUtil:log\" - Writes a log file to output-file.log.\n-T \"ossimAutRegUtil:options\" - Writes the options to output-file-options.kwl."; ossimApplicationUsage* au = ap.getApplicationUsage(); au->setCommandLineUsage(usageString); au->setDescription(ap.getApplicationName()+": Utility application for autonomous image registration."); au->addCommandLineOption("-h or --help", "Display this help and exit."); au->addCommandLineOption("--quality", "\nNOT WORKING... Desired quality of tiepoint collection.\nRange: 1 to 5, Default = 3"); au->addCommandLineOption("--roi-center-llwh"," \nSpecify the center ROI in latitude longitude space with width and height in pixels."); au->addCommandLineOption("--roi-center-llr"," \nSpecify the center ROI in latitude longitude space with radius in meters."); au->addCommandLineOption("--ocv_config_file","\nSpecify a keyword list OpenCV configuration file."); au->addCommandLineOption("--oax_config_file","\nSpecify a keyword list oax configuration file."); } // End: ossimAutRegUtil::addArguments void ossimAutRegUtil::clear() { // Must disconnect chains so that they destroy. std::vector< ossimRefPtr >::iterator i = m_imgLayer.begin(); while ( i != m_imgLayer.end() ) { (*i)->disconnect(); (*i) = 0; ++i; } m_imgLayer.clear(); // i = m_demLayer.begin(); // while ( i != m_demLayer.end() ) // { // (*i)->disconnect(); // (*i) = 0; // ++i; // } // m_demLayer.clear(); } bool ossimAutRegUtil::initialize(ossimArgumentParser& ap) { static const char MODULE[] = "ossimAutRegUtil::initialize(ossimArgumentParser&)"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } clear(); if( ap.read("-h") || ap.read("--help") || (ap.argc() == 1) ) { usage(ap); return false; // Indicates process should be terminated to caller. } // Start with clean options keyword list. m_kwl->clear(); std::string tempString1; ossimArgumentParser::ossimParameter stringParam1(tempString1); std::string tempString2; ossimArgumentParser::ossimParameter stringParam2(tempString2); std::string tempString3; ossimArgumentParser::ossimParameter stringParam3(tempString3); std::string tempString4; ossimArgumentParser::ossimParameter stringParam4(tempString4); double tempDouble1; ossimArgumentParser::ossimParameter doubleParam1(tempDouble1); double tempDouble2; ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); ossimString key = ""; // Extract arguments and stuff them in a keyword list. if( ap.read("--report_file", stringParam1) ) { m_kwl->addPair( std::string(REPORT_FILE_KW), tempString1 ); } // report file if( ap.read("--quality", stringParam1) ) { m_kwl->addPair( std::string(ossimKeywordNames::QUALITY_KW), tempString1 ); } // operation if( ap.read("--op", stringParam1) ) { m_kwl->addPair( OP_KW, tempString1 ); } // image 1 if( ap.read("--img_1", stringParam1)) { m_kwl->addPair( std::string(IMG_1_KW), tempString1 ); } // image 2 if( ap.read("--img_2", stringParam1)) { m_kwl->addPair( std::string(IMG_2_KW), tempString1 ); } // master image if( ap.read("--img_m", stringParam1)) { m_kwl->addPair( std::string(IMG_M_KW), tempString1 ); } // slave image if( ap.read("--img_s", stringParam1)) { m_kwl->addPair( std::string(IMG_S_KW), tempString1 ); } // OpenCV config if( ap.read("--ocv_config_file", stringParam1)) { m_kwl->addPair( std::string(OCV_CONFIG_FILE_KW), tempString1 ); } // oax config if( ap.read("--oax_config_file", stringParam1)) { m_kwl->addPair( std::string(OAX_CONFIG_FILE_KW), tempString1 ); } // llwh chipping parameters if( ap.read("--roi-center-llwh", stringParam1, stringParam2, stringParam3, stringParam4) ) { m_kwl->addPair( ROI_CENTER_LAT_KW, tempString1 ); m_kwl->addPair( ROI_CENTER_LON_KW, tempString2 ); m_kwl->addPair( ROI_WIDTH_KW, tempString3 ); m_kwl->addPair( ROI_HEIGHT_KW, tempString4 ); } // llr chipping parameters if( ap.read("--roi-center-llr", stringParam1, stringParam2, stringParam3) ) { m_kwl->addPair( ROI_CENTER_LAT_KW, tempString1 ); m_kwl->addPair( ROI_CENTER_LON_KW, tempString2 ); m_kwl->addPair( ROI_RADIUS_KW, tempString3 ); } // TODO Necessary??? if( ap.read("--input-src", stringParam1) ) { m_kwl->addPair( SRC_FILE_KW, tempString1 ); } // TODO For now, just an example of using ossimKeywordNames content if( ap.read("--quality", stringParam1) ) { m_kwl->addPair( std::string(ossimKeywordNames::QUALITY_KW), tempString1 ); } //--- // Deprecated: "--options-keyword-list" //--- if( ap.read("--options", stringParam1) ) { ossimFilename optionsKwl = tempString1; if ( optionsKwl.exists() ) { if ( m_kwl->addFile(optionsKwl) == false ) { std::string errMsg = "ERROR could not open options keyword list file: "; errMsg += optionsKwl.string(); throw ossimException(errMsg); } } else { std::string errMsg = "ERROR options keyword list file does not exists: "; errMsg += optionsKwl.string(); throw ossimException(errMsg); } } // End of arg parsing. ap.reportRemainingOptionsAsUnrecognized(); if ( ap.errors() ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); std::string errMsg = "Unknown option..."; throw ossimException(errMsg); } if ( ap.argc() >= 2 ) { // Output file is last arg: m_kwl->add( ossimKeywordNames::OUTPUT_FILE_KW, ap[ap.argc()-1]); } else { if ( !m_kwl->find(ossimKeywordNames::OUTPUT_FILE_KW) ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); std::string errMsg = "Must supply an output file."; throw ossimException(errMsg); } } if ( ap.argc() > 2 ) // User passed inputs in front of output file. { int pos = 1; // ap.argv[0] is application name. while ( pos < (ap.argc()-1) ) { ossimFilename file = ap[pos]; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "argv[" << pos << "]: " << file << "\n"; } if ( isSrcFile(file) ) { if ( m_kwl->find( SRC_FILE_KW.c_str() ) ) // --input-src used also { std::string errMsg = MODULE; errMsg += "ERROR Multiple src files passed in. Please combine into one."; throw ossimException(errMsg); } m_kwl->addPair( SRC_FILE_KW, file.string() ); } else // Add as an input image. { // key = IMG_KW; // key += ossimString::toString(imgIdx); // key += "."; // key += FILE_KW; // m_kwl->addPair(key.string(), file.string() ); // ++imgIdx; } ++pos; // Go to next arg... } // End: while ( pos < (ap.argc()-1) ) } // End: if ( ap.argc() > 2 ) initialize(); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited..." << std::endl; } return true; } // End: void ossimAutRegUtil::initialize(ossimArgumentParser& ap) void ossimAutRegUtil::initialize( const ossimKeywordlist& kwl ) { clear(); // Start with clean options keyword list. m_kwl->clear(); m_kwl->addList( kwl, true ); initialize(); } void ossimAutRegUtil::initialize() { static const char MODULE[] = "ossimAutRegUtil::initialize()"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } if ( traceOptions() ) { ossimFilename optionsFile; getOutputFilename(optionsFile); optionsFile = optionsFile.noExtension(); optionsFile += "-options.kwl"; ossimString comment = " Can be use for --options argument."; m_kwl->write( optionsFile.c_str(), comment.c_str() ); } // Determine the operation to do. std::string op = m_kwl->findKey( OP_KW ); if ( op.size() ) { ossimString s = op; s.downcase(); if ( s == "coreg" ) { m_operation = OSSIM_AUTREG_OP_COREG; } else if ( s == "masreg" ) { m_operation = OSSIM_AUTREG_OP_MASREG; } else { std::string errMsg = "unknown operation: "; errMsg += s.string(); throw ossimException(errMsg); } } else { std::string errMsg = "keyword not found: "; errMsg += OP_KW; errMsg += "\nUse --op option to specify operation.\n"; throw ossimException(errMsg); } //--- // Report file //--- ossimFilename repFile = m_kwl->findKey( REPORT_FILE_KW ); if (repFile.size()) { m_rep = new ofstream( repFile.c_str(), ios::out ); } else { m_rep = &std::cout; } *m_rep << "\n ossimAutRegUtil Summary..."<saveStateOfAllInputs(logKwl); ossimFilename logFile; getOutputFilename(logFile); logFile.setExtension("log"); logKwl.write( logFile.c_str() ); } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "options keyword list:\n" << *(m_kwl.get()) << "\n"; if ( m_srcKwl.valid() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "support record keyword list:\n" << *(m_srcKwl.get()) << "\n"; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Instantiate ossimTieMeasurementGenerator //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ m_tGenObj = ossimObjectFactoryRegistry::instance()-> createObject(ossimString("ossimTieMeasurementGenerator")); if(m_tGenObj.valid()) { m_tGen = dynamic_cast (m_tGenObj.get()); } else { throw ossimException("ossimTieMeasurementGenerator createObject failed..."); } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } // End: void ossimAutRegUtil::initialize() //***************************************************************************** // METHOD: ossimAutRegUtil::loadImages() // // Load image pair. // //***************************************************************************** bool ossimAutRegUtil::loadImages() { static const char MODULE[] = "ossimAutRegUtil::loadImages"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool isGoodLoad = false; ossimFilename inputFile; ossimString key; // Load 1st image if (m_operation == OSSIM_AUTREG_OP_COREG) { key = IMG_1_KW; } else // Load master image { key = IMG_M_KW; m_controlImage[0] = true; } inputFile = m_kwl->findKey(key.string()); if (addImgSource(inputFile, 0 )) { ossimImageHandler *ih1 = m_imgLayer[0]->getImageHandler().get(); if (!ih1) { *m_rep << " open for image 1 failed..."<getNumberOfDecimationLevels(); ossimIrect bounds = ih1->getBoundingRect(0); // ossimScalarType scalarType = ih1->getOutputScalarType(); ossimScalarTypeLut* lut = ossimScalarTypeLut::instance(); *m_rep << "-----------------" << endl << "filename = " << ih1->getFilename() << endl << "width = " << bounds.width() << endl << "height = " << bounds.height() << endl << "overview count = " << (overviews-1) << endl << "scalar type = " << lut->getEntryString(ih1->getOutputScalarType()) << endl << "Handler used = " << ih1->getClassName() << endl; // Load 2nd image if (m_operation == OSSIM_AUTREG_OP_COREG) { key = IMG_2_KW; } else // Load slave image { key = IMG_S_KW; m_controlImage[1] = false; } inputFile = m_kwl->findKey(key.string()); if (addImgSource(inputFile, 0 )) { ossimImageHandler *ih2 = m_imgLayer[1]->getImageHandler().get(); if (!ih2) { *m_rep << " open for image 2 failed"<getNumberOfDecimationLevels(); ossimIrect bounds = ih2->getBoundingRect(0); // ossimScalarType scalarType = ih2->getOutputScalarType(); ossimScalarTypeLut* lut = ossimScalarTypeLut::instance(); *m_rep << "-----------------" << endl << "filename = " << ih2->getFilename() << endl << "width = " << bounds.width() << endl << "height = " << bounds.height() << endl << "overview count = " << (overviews-1) << endl << "scalar type = " << lut->getEntryString(ih2->getOutputScalarType()) << endl << "Handler used = " << ih2->getClassName() << endl; *m_rep << "-----------------" << endl; isGoodLoad = true; } } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return isGoodLoad; } //***************************************************************************** // METHOD: ossimAutRegUtil::delineateROIs() // // Determine correlation region of interest. // //***************************************************************************** bool ossimAutRegUtil::delineateROIs() { static const char MODULE[] = "ossimAutRegUtil::delineateROIs"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool isGoodOp = false; for (int img=0; img<2; ++img) { ossimIrect rect; rect.makeNan(); ossimImageSource* source = m_imgLayer[img].get(); if ( source ) { if ( m_geom[img].valid() ) { if ( m_kwl->find( ROI_CENTER_LAT_KW.c_str() ) ) { // "ROI Center" with: --roi-center-llwh or --roi-center-llr: ossimString latStr = m_kwl->findKey( ROI_CENTER_LAT_KW ); ossimString lonStr = m_kwl->findKey( ROI_CENTER_LON_KW ); if ( latStr.size() && lonStr.size() ) { ossimGpt centerGpt; //--- // Want the height nan going into worldToLocal call so it gets picked // up by the elevation manager. //--- centerGpt.makeNan(); centerGpt.lat = latStr.toFloat64(); centerGpt.lon = lonStr.toFloat64(); if ( !centerGpt.isLatNan() && !centerGpt.isLonNan() ) { // Ground "cut center" to view: ossimDpt centerDpt(0.0, 0.0); m_geom[img]->worldToLocal(centerGpt, centerDpt); if ( !centerDpt.hasNans() ) { // if ( isIdentity() && m_ivt.valid() ) // Chipping in image space. if ( m_ivt[img].valid() ) // Chipping in image space. { // Transform image center point to view: ossimDpt ipt = centerDpt; m_ivt[img]->imageToView( ipt, centerDpt ); } // --roi-center-llwh: ossimString widthStr = m_kwl->findKey( ROI_WIDTH_KW ); ossimString heightStr = m_kwl->findKey( ROI_HEIGHT_KW ); if ( widthStr.size() && heightStr.size() ) { ossim_int32 width = widthStr.toInt32(); ossim_int32 height = heightStr.toInt32(); if ( width && height ) { ossimIpt ul( ossim::round(centerDpt.x - (width/2)), ossim::round(centerDpt.y - (height/2)) ); ossimIpt lr( (ul.x + width - 1), ul.y + height - 1); rect = ossimIrect(ul, lr); } } else // --roi-center-llr: { ossimString radiusStr = m_kwl->findKey( ROI_RADIUS_KW ); if ( radiusStr.size() ) { ossim_float64 radius = radiusStr.toFloat64(); if ( radius ) { ossimDpt mpp; m_geom[0]->getMetersPerPixel( mpp ); if ( !mpp.hasNans() ) { ossim_float64 rx = radius/mpp.x; ossim_float64 ry = radius/mpp.y; ossimIpt ul( ossim::round( centerDpt.x - rx ), ossim::round( centerDpt.y - ry ) ); ossimIpt lr( ossim::round( centerDpt.x + rx ), ossim::round( centerDpt.y + ry ) ); rect = ossimIrect(ul, lr); } } } } } } // Matches: if ( !centerGpt.hasNans() ) } // Matches: if ( latStr && lonStr ) } // Matches: if ( m_kwl->find( ROI_CENTER_LAT_KW ) ) } // if ( igeom.valid() ) else { // Should never happen... std::string errMsg = MODULE; if ( !source ) { errMsg += " image source null!"; } throw( ossimException(errMsg) ); } // rect.print(*m_rep); m_roiRects.push_back(rect); } // if ( source ) } isGoodOp = true; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return isGoodOp; } //***************************************************************************** // METHOD: ossimAutRegUtil::populateObsSet() // // Transfer tie points from generator to observation set. // //***************************************************************************** bool ossimAutRegUtil::populateObsSet() { static const char MODULE[] = "ossimAutRegUtil::populateObsSet"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool isGoodLoad = true; ossimString id; ossimGpt gp; for (int m=0; mnumMeasurements(); ++m) { id = ossimString::toString(m+1); // Initialize ground point gp.makeNan(); ossimPointObservation *pt = new ossimPointObservation(gp, id, m_LatLonHgtSigmas); for (int img=0; img<2; ++img) { ossimDpt imgPt = m_tGen->pointIndexedAt(img,m); // If control, set ground coordinates and reset sigmas if (m_controlImage[img]) { // Point drop to get control coordinates ossimGpt worldPt; m_geom[img]->localToWorld(imgPt, worldPt); if (worldPt.isHgtNan()) { ossim_float64 hgt = ossimElevManager::instance()->getHeightAboveEllipsoid(worldPt); worldPt.height(hgt); } pt->Gpt() = worldPt; // Set control sigmas pt->setGroundSigmas (m_LatLonHgtControlSigmas[0],m_LatLonHgtControlSigmas[1],m_LatLonHgtControlSigmas[2]); } else { // Get image filename ossimFilename filename = m_imgLayer[img]->getImageHandler()->getFilename(); // Add measurement to point observation pt->addMeasurement(imgPt, filename); } } // Add point observation to set if (pt->numMeas() > 0) { m_obsSet->addObservation(pt); } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return isGoodLoad; } //***************************************************************************** // METHOD: ossimAutRegUtil::configureTieMeasGenerator() // // Configure the tie measurement generator using m_ocvKwl // //***************************************************************************** void ossimAutRegUtil::configureTieMeasGenerator() { static const char MODULE[] = "ossimAutRegUtil::configureTieMeasGenerator"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } if ( m_ocvKwl.valid() ) { // Draw OpenCV match window m_showMatchWindow = keyIsTrue(m_ocvKwl, OCV_DRAW_MATCHES_FLAG_KW); m_tGen->setShowCvWindow(m_showMatchWindow); // OpenCV detector if (m_ocvKwl->find(OCV_DETECTOR_NAME_KW.c_str())) { m_tGen->setFeatureDetector(m_ocvKwl->findKey(OCV_DETECTOR_NAME_KW)); } // OpenCV descriptor/extractor if (m_ocvKwl->find(OCV_EXTRACTOR_NAME_KW.c_str())) { m_tGen->setDescriptorExtractor(m_ocvKwl->findKey(OCV_EXTRACTOR_NAME_KW)); } // OpenCV matcher if (m_ocvKwl->find(OCV_MATCHER_NAME_KW.c_str())) { m_tGen->setDescriptorMatcher(m_ocvKwl->findKey(OCV_MATCHER_NAME_KW)); } // OpenCV maximum number of matches if (m_ocvKwl->find(OCV_MAX_MATCHES_KW.c_str())) { ossimString maxMatches = m_ocvKwl->findKey(OCV_MAX_MATCHES_KW); if (maxMatches.size()) { ossim_int32 max = maxMatches.toInt32(); m_tGen->setMaxMatches(max); } } // TODO: set crossCheck currently commented out in ossimTieMeasurementGenerator // m_tGen->setUseCrossCheck(keyIsTrue(m_ocvKwl, OCV_USE_CROSS_CHECK_KW)); // Use OpenCV GridAdaptedFeatureDetector m_tGen->setUseGrid(keyIsTrue(m_ocvKwl, OCV_USE_GRID_ADAPTED_DETECT_KW)); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } //***************************************************************************** // METHOD: ossimAutRegUtil::configureAdjustmentExecutive() // // Configure the adjustment executive using m_oaxKwl // //***************************************************************************** void ossimAutRegUtil::configureAdjustmentExecutive() { static const char MODULE[] = "ossimAutRegUtil::configureAdjustmentExecutive"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } if ( m_oaxKwl.valid() ) { if (m_oaxKwl->find(OAX_MAX_ITERATIONS_KW.c_str())) { ossimString maxIter = m_oaxKwl->findKey(OAX_MAX_ITERATIONS_KW); if (maxIter.size()) { ossim_int32 max = maxIter.toInt32(); m_adjExec->setMaxIter(max); } } if (m_oaxKwl->find(OAX_CONVERGENCE_CRITERIA_KW.c_str())) { ossimString conv = m_oaxKwl->findKey(OAX_CONVERGENCE_CRITERIA_KW); if (conv.size()) { ossim_float64 convPerc = conv.toFloat64(); m_adjExec->setConvCriteria(convPerc); } } if (m_oaxKwl->find(OAX_GROUND_SIGMA_KW.c_str())) { ossimString conv = m_oaxKwl->findKey(OAX_GROUND_SIGMA_KW); if (conv.size()) { ossim_float64 gndSigma = conv.toFloat64(); m_LatLonHgtSigmas[0] = gndSigma; m_LatLonHgtSigmas[1] = gndSigma; m_LatLonHgtSigmas[2] = gndSigma; } } if (m_oaxKwl->find(OAX_CONTROL_SIGMA_KW.c_str())) { ossimString conv = m_oaxKwl->findKey(OAX_CONTROL_SIGMA_KW); if (conv.size()) { ossim_float64 gndSigma = conv.toFloat64(); m_LatLonHgtControlSigmas[0] = gndSigma; m_LatLonHgtControlSigmas[1] = gndSigma; m_LatLonHgtControlSigmas[2] = gndSigma; } } if (m_oaxKwl->find(OAX_LAT_SIGMA_KW.c_str())) { ossimString conv = m_oaxKwl->findKey(OAX_LAT_SIGMA_KW); if (conv.size()) { ossim_float64 gndLatSigma = conv.toFloat64(); m_LatLonHgtSigmas[0] = gndLatSigma; } } if (m_oaxKwl->find(OAX_LON_SIGMA_KW.c_str())) { ossimString conv = m_oaxKwl->findKey(OAX_LON_SIGMA_KW); if (conv.size()) { ossim_float64 gndLonSigma = conv.toFloat64(); m_LatLonHgtSigmas[1] = gndLonSigma; } } if (m_oaxKwl->find(OAX_HGT_SIGMA_KW.c_str())) { ossimString conv = m_oaxKwl->findKey(OAX_HGT_SIGMA_KW); if (conv.size()) { ossim_float64 gndHgtSigma = conv.toFloat64(); m_LatLonHgtSigmas[2] = gndHgtSigma; } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } //***************************************************************************** // METHOD: ossimAutRegUtil::execute() // // Execute registration operation. //***************************************************************************** void ossimAutRegUtil::execute() { static const char MODULE[] = "ossimAutRegUtil::execute"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Initialize the measurement generator //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *m_rep<<"\n\n >> Tie point collection follows...\n"<init(*m_rep); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Configure the measurement generator //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ configureTieMeasGenerator(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Load ossimImageSource vector //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ std::vector src; src.push_back(m_imgLayer[0].get()); src.push_back(m_imgLayer[1].get()); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Set correlation areas //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ m_tGen->setImageList(src); m_tGen->setROIs(m_roiRects); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Run the OpenCV detector/extractor/matcher to collect tiepoints //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (m_tGen->run()) { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Close match window if active //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (m_showMatchWindow) { bool waitKey = true; m_tGen->closeCvWindow(waitKey); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Check for adjustable parameter interface before adjustment //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ossimAdjustableParameterInterface* iface1 = m_geom[0]->getAdjustableParameterInterface(); ossimAdjustableParameterInterface* iface2 = m_geom[1]->getAdjustableParameterInterface(); if (iface1 && iface2) { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Create observation set //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ m_obsSet = new ossimObservationSet; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Create adjustment executive //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ m_adjExec = new ossimAdjustmentExecutive(*m_rep); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Configure adjustment executive //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ configureAdjustmentExecutive(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Load measurements into the observation set //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (populateObsSet()) { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Perform adjustment //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ bool solutionOK = false; *m_rep<<"\n\n >> Adjustment summary follows...\n"<initializeSolution(*m_obsSet)) { solutionOK = m_adjExec->runSolution(); m_adjExec->summarizeSolution(); if (solutionOK) { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Write updated geometry files //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ saveAdjustment(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "Solution complete...\n"; } } else { throw ossimException("m_adjExec->runSolution() failed..."); } //end if m_adjExec->runSolution() } else { throw ossimException("m_adjExec->initializeSolution() failed..."); } //end if m_adjExec->initializeSolution() } else { throw ossimException("populateObsSet() failed..."); } //end if (populateObsSet()) } else { throw ossimException("ossimAdjustableParameterInterface missing..."); } //end if (iface1 && iface2) } else { throw ossimException( "m_tGen->run() failed..."); } //end if (m_tGen->run()) if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } void ossimAutRegUtil::saveAdjustment() { ossimString ts; ossim::getFormattedTime("ossim-autreg_%a_%m.%d.%y_%H:%M:%S", false, ts); ossimAdjustmentInfo* adjInfo = new ossimAdjustmentInfo; for (int img=0; img<2; ++img) { if (!m_controlImage[img]) { // Get the adjustment info from the bundle adjustment via m_obsSet ossimFilename filename = m_imgLayer[img]->getImageHandler()->getFilename(); // Oscar, should this be a ref ptr? drb - 20160810 ossimAdjustableParameterInterface* adjParIface = 0; for (ossim_uint32 ii=0; iinumImages(); ++ii) { if (filename == m_obsSet->imageFile(ii)) adjParIface = m_obsSet->getImageGeom(ii)->getAdjustableParameterInterface(); } if ( adjParIface ) { adjParIface->setAdjustmentDescription(ts); adjParIface->getAdjustment(*adjInfo); // Grab adjustable parameter interface and update it with the adjustment info ossimAdjustableParameterInterface* iface = m_geom[img]->getAdjustableParameterInterface(); if ( iface ) { iface->setAdjustment(*adjInfo, true); ossimFilename fn = m_imgLayer[img]->getImageHandler()->createDefaultGeometryFilename(); // TODO *********** // dirty flag???? // fn += "_test"; // TODO *********** ossimKeywordlist kwl; iface->getBaseObject()->saveState(kwl); kwl.write(fn); } } } } delete adjInfo; } void ossimAutRegUtil::getOutputFilename(ossimFilename& f) const { f.string() = m_kwl->findKey( std::string(ossimKeywordNames::OUTPUT_FILE_KW) ); } bool ossimAutRegUtil::isSrcFile(const ossimFilename& file) const { bool result = false; ossimString ext = file.ext(); ext.downcase(); if ( ext == "src" ) { result = true; } return result; } void ossimAutRegUtil::usage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); // Set app name. std::string appName = ap.getApplicationName(); ap.getApplicationUsage()->setApplicationName( ossimString( appName ) ); // Add options. addArguments(ap); // Write usage. ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); // Keeping single line in tact for examples for cut and paste purposes. ossimNotify(ossimNotifyLevel_INFO) << "NOTES:\n" << "1) Note 1 content\n" << " Note 1 place holder continued...\n" << "2) Note 2 content\n" << " Note 2 place holder continued...\n" << "\nExample commands:\n" << "\n// Co-register image1 and image2 with 512x512 ROIs centered on point:\n" << appName << " --op coreg --img_1 image1.ntf --img_2 image2.ntf --roi-center-llwh 28.097255037664400 -80.630762190246145 512 512\n" << "\n// Register image2 to control image1 (master): (TBD... not working)\n" << appName << " --op masreg -img_m image1.ntf -img_s image2.ntf -cfg configFile.kwl\n" << "\n// Above command where all options are in a keyword list:\n" << appName << " --options autreg-options.kwl\n" << std::endl; } void ossimAutRegUtil::initializeSrcKwl() { static const char MODULE[] = "ossimAutRegUtil::initializeSrcKwl"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::string value = m_kwl->findKey(std::string(SRC_FILE_KW)); if ( value.size() ) { m_srcKwl = new ossimKeywordlist(); m_srcKwl->setExpandEnvVarsFlag(true); if ( m_srcKwl->addFile( value.c_str() ) == false ) { m_srcKwl = 0; } } else { m_srcKwl = 0; } if ( traceDebug() ) { if ( m_srcKwl.valid() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "src keyword list:\n" << *(m_srcKwl.get()) << "\n"; } ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } void ossimAutRegUtil::initializeOcvKwl() { static const char MODULE[] = "ossimAutRegUtil::initializeOcvKwl"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::string value = m_kwl->findKey(std::string(OCV_CONFIG_FILE_KW)); if ( value.size() ) { m_ocvKwl = new ossimKeywordlist(); m_ocvKwl->setExpandEnvVarsFlag(true); if ( m_ocvKwl->addFile( value.c_str() ) == false ) { m_ocvKwl = 0; } } else { m_ocvKwl = 0; } if ( traceDebug() ) { if ( m_ocvKwl.valid() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "ocv keyword list:\n" << *(m_ocvKwl.get()) << "\n"; } ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } void ossimAutRegUtil::initializeOaxKwl() { static const char MODULE[] = "ossimAutRegUtil::initializeOaxKwl"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::string value = m_kwl->findKey(std::string(OAX_CONFIG_FILE_KW)); if ( value.size() ) { m_oaxKwl = new ossimKeywordlist(); m_oaxKwl->setExpandEnvVarsFlag(true); if ( m_oaxKwl->addFile( value.c_str() ) == false ) { m_oaxKwl = 0; } } else { m_oaxKwl = 0; } if ( traceDebug() ) { if ( m_oaxKwl.valid() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "oax keyword list:\n" << *(m_oaxKwl.get()) << "\n"; } ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } bool ossimAutRegUtil::addImgSource(const ossimFilename& file, ossim_uint32 entryIndex) { static const char MODULE[] = "ossimAutRegUtil::addImgSource"; bool addOK = false; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\nFile: " << file << "\n"; } ossimRefPtr ic = createChain(file, entryIndex); if ( ic.valid() ) { m_imgLayer.push_back(ic); addOK = true; } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exiting...\n"; } return addOK; } void ossimAutRegUtil::setReaderProps( ossimImageHandler* ih ) const { if ( ih && m_kwl.valid() ) { ossim_uint32 count = m_kwl->numberOf( READER_PROPERTY_KW.c_str() ); for (ossim_uint32 i = 0; i < count; ++i) { ossimString key = READER_PROPERTY_KW; key += ossimString::toString(i); ossimString value = m_kwl->findKey( key.string() ); if ( value.size() ) { std::vector splitArray; value.split(splitArray, "="); if(splitArray.size() == 2) { ossimRefPtr prop = new ossimStringProperty(splitArray[0], splitArray[1]); ih->setProperty( prop ); } } } } } bool ossimAutRegUtil::setChainEntry( ossimRefPtr& chain, ossim_uint32 entryIndex ) const { bool result = false; if ( chain.valid() ) { ossimRefPtr ih = chain->getImageHandler(); if ( ih.valid() ) { result = ih->setCurrentEntry( entryIndex ); } } return result; } ossimRefPtr ossimAutRegUtil::createChain(const ossimFilename& file, ossim_uint32 entryIndex) const { static const char MODULE[] = "ossimAutRegUtil::createChain(const ossimFilename&"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << "\nfile: " << file << "\nentry: " << entryIndex << "\n"; } ossimRefPtr ic = 0; if ( file.size() ) { if ( file.exists() ) { ic = new ossimSingleImageChain; if ( ic->open( file ) ) { // Set any reader props: setReaderProps( ic->getImageHandler().get() ); // we can't guarantee the state of the image handler at this point so // let's make sure that the entry is always set to the requested location // On Cib/Cadrg we were having problems. Removed the compare for entry 0 // if ( setChainEntry( ic, entryIndex ) == false ) { std::ostringstream errMsg; errMsg << MODULE << " ERROR:\nEntry " << entryIndex << " out of range!" << std::endl; throw ossimException( errMsg.str() ); } // Always have resampler cache. ic->setAddResamplerCacheFlag(true); //--- // Don't need a chain cache as we're doing a sequential write. So the same tile // should never be visited more than once. //--- ic->setAddChainCacheFlag(false); // // Brightness, contrast. Note in same filter. // if ( hasBrightnesContrastOperation() ) // { // ic->setBrightnessContrastFlag(true); // } // std::string sharpnessMode = getSharpenMode(); // if ( sharpnessMode.size() ) // { // ic->setSharpenFlag(true); // } // Create the chain. ic->createRenderedChain(); // // Histogram setup. // if ( hasHistogramOperation() ) // { // setupChainHistogram( ic ); // } // // Brightness contrast setup: // if ( hasBrightnesContrastOperation() ) // { // // Assumption bright contrast filter in chain: // ossim_float64 value = getBrightness(); // ic->getBrightnessContrast()->setBrightness( value ); // value = getContrast(); // ic->getBrightnessContrast()->setContrast( value ); // } // // Sharpness: // if ( sharpnessMode.size() ) // { // if ( sharpnessMode == "light" ) // { // ic->getSharpenFilter()->setWidthAndSigma( 3, 0.5 ); // } // else if ( sharpnessMode == "heavy" ) // { // ic->getSharpenFilter()->setWidthAndSigma( 5, 1.0 ); // } // } } } } if ( ic.valid() == false ) { std::string errMsg = "Could not open: "; errMsg += file.string(); throw ossimException(errMsg); } if ( traceDebug() ) { ossimKeywordlist kwl; ic->saveState(kwl, 0); ossimNotify(ossimNotifyLevel_DEBUG) << "chain:\n" << kwl << "\n" << MODULE << " exiting...\n"; } return ic; } void ossimAutRegUtil::createIdentityProjection(int idx) { static const char MODULE[] = "ossimAutRegUtil::createIdentityProjection"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } // Get the singe image chain. Should be only one. ossimRefPtr sic = 0; if ( m_imgLayer.size() ) { sic = m_imgLayer[idx]; } if ( sic.valid() ) { // Get the image handler. ossimRefPtr ih = sic->getImageHandler(); // Resampler: ossimRefPtr resampler = sic->getImageRenderer(); if ( ih.valid() ) { //--- // Get the geometry from the image handler. Since we're in "identity" // mode use the inputs for the outputs. //--- m_geom[idx] = ih->getImageGeometry(); if ( m_geom[idx].valid() ) { // Get the image projection. ossimRefPtr proj = m_geom[idx]->getProjection(); if ( proj.valid() ) { ossim_float64 rotation = 0.0; ossimDrect rect; m_geom[idx]->getBoundingRect(rect); ossimDpt midPt = rect.midPoint(); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "\nAffine transform parameters:" << "\nrotation: " << rotation << "\nmid point: " << midPt << std::endl; } m_ivt[idx] = new ossimImageViewAffineTransform(-rotation, 1.0, 1.0, // image space scale x and y 1.0, 1.0, //scale x and y 0.0, 0.0, // translate x,y midPt.x, midPt.y); // pivot point resampler->setImageViewTransform( m_ivt[idx].get() ); } } // Matches: if ( m_geom.valid() ) } // Matches: if ( ih.valid() ) } // Matches: if ( sic.valid() } // End: createIdentityProjection() bool ossimAutRegUtil::keyIsTrue(ossimRefPtr kwl, const std::string& key ) const { bool result = false; if ( kwl.valid() ) { std::string value = kwl->findKey( key ); if ( value.size() ) { result = ossimString(value).toBool(); } } return result; } ossim-Miami-2.9.1/src/util/ossimBandMergeTool.cpp000066400000000000000000000132161352751253100217230ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; const char* ossimBandMergeTool::DESCRIPTION = "Merges multiple band files into a single RGB image."; static const std::string HISTO_STRETCH_KW = "histo_stretch"; ossimBandMergeTool::ossimBandMergeTool() : m_stretchProduct(false) { } ossimBandMergeTool::~ossimBandMergeTool() { } void ossimBandMergeTool::setUsage(ossimArgumentParser& ap) { // Add options. ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " bandmerge --red --green --blue [--stretch] "; au->setCommandLineUsage(usageString); // Set the command line options: au->setDescription(DESCRIPTION); // Base class has its own: ossimChipProcTool::setUsage(ap); au->addCommandLineOption("--red", " Filename of red band. "); au->addCommandLineOption("--green", " Filename of green band. "); au->addCommandLineOption("--blue", " Filename of blue band. "); au->addCommandLineOption("--stretch", "Optionally histogram-stretch the product image. "); } bool ossimBandMergeTool::initialize(ossimArgumentParser& ap) { if (!ossimChipProcTool::initialize(ap)) return false; if (m_helpRequested) return true; ostringstream xmsg; std::string ts1; ossimArgumentParser::ossimParameter sp1 (ts1); int band_count = 0; if ( ap.read("--red", sp1)) { ostringstream key; key< combiner = new ossimBandMergeSource(bandList); m_procChain->add(combiner.get()); } void ossimBandMergeTool::initHistogramStretch(ossimSingleImageChain* image) { ostringstream errMsg; // Check if this image already has a histogram file associated with it: ossimRefPtr handler = image->getImageHandler(); if (!handler.valid()) { errMsg<<"ERROR ossimBandMergeUtil:"<<__LINE__<<" Bad handler returned for image chain."; throw ossimException(errMsg.str()); } ossimRefPtr histogram = handler->getImageHistogram(); if (!histogram.valid()) { errMsg<<"ERROR ossimBandMergeUtil:"<<__LINE__<<" Bad histogram returned from image handler."; throw ossimException(errMsg.str()); } ossimRefPtr histogramRemapper = new ossimHistogramRemapper(); histogramRemapper->setEnableFlag(true); histogramRemapper->setStretchMode( ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX ); histogramRemapper->setHistogram(histogram); image->add(histogramRemapper.get()); } bool ossimBandMergeTool::execute() { return ossimChipProcTool::execute(); } void ossimBandMergeTool::getKwlTemplate(ossimKeywordlist& kwl) { ossimChipProcTool::getKwlTemplate(kwl); ossimString keybase (ossimKeywordNames::IMAGE_FILE_KW ); ossimString key = keybase + "0"; kwl.add(key.chars(), "", true); key = keybase + "1"; kwl.add(key.chars(), "", true); key = keybase + "2"; kwl.add(key.chars(), "", true); kwl.add(HISTO_STRETCH_KW.c_str(), "true|false", true); } ossim-Miami-2.9.1/src/util/ossimBatchTest.cpp000066400000000000000000001323041352751253100211220ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File ossim-batch-test.cpp // // License: See top level LICENSE.txt file. // // Author: David Burken, Oscar Kramer // // Description: Test code application ossim batch test. // //---------------------------------------------------------------------------- // $Id: ossim-batch-test.cpp 3112 2012-01-26 17:28:00Z david.burken $ #include #include #include #include #include #include #include #include #include #include #include /* for system() */ #include #include #include #include #include using namespace std; //************************************************************************************************** // Constructor //************************************************************************************************** ossimBatchTest::ossimBatchTest() : m_acceptTestList(), m_cleanTestList(), m_preprocessTestList(), m_runTestList(), m_templateModeActive(false), m_configFileName(), m_outDir(), m_expDir(), m_logStr() { typedef std::map::value_type map_item; m_statusLabels.insert(map_item(TEST_TBD, "UNKNOWN")); m_statusLabels.insert(map_item(TEST_PASSED, "PASSED")); m_statusLabels.insert(map_item(TEST_FAILED, "FAILED")); m_statusLabels.insert(map_item(TEST_ERROR, "ERROR")); m_statusLabels.insert(map_item(TEST_DISABLED, "DISABLED")); m_statusLabels.insert(map_item(TEST_PASSED|TEST_FAILED, "FAILURE ENCOUNTERED")); m_statusLabels.insert(map_item(TEST_PASSED|TEST_ERROR, "ERROR ENCOUNTERED")); m_statusLabels.insert(map_item(TEST_FAILED|TEST_ERROR, "FAILURE AND ERROR ENCOUNTERED")); m_statusLabels.insert(map_item(TEST_PASSED|TEST_FAILED|TEST_ERROR, "FAILURE AND ERROR ENCOUNTERED")); } //************************************************************************************************** // Initialize parses the command line. Returns true if status OK. //************************************************************************************************** bool ossimBatchTest::initialize(ossimArgumentParser& ap) { if ( (ap.argc() == 1) || ap.read("-h") || ap.read("--help") ) { usage(ap); // continue_after_init to false return false; } // Initialize environment: #if defined(_WIN32) || defined(_MSC_VER) && !defined(__CYGWIN__) && !defined(__MWERKS__) _putenv("DEL_CMD=del /Q"); // For backwards compatiblity. _putenv("DIFF_CMD=fc /W"); _putenv("COPY_CMD=copy /Y"); _putenv("MKDIR_CMD=mkdir"); _putenv("RM_CMD=del /Q"); _putenv("RMDIR_CMD=rmdir /S /Q"); #else setenv("DEL_CMD", "rm -rf", 1); // For backwards compatiblity. setenv("DIFF_CMD", "diff -w", 1); setenv("COPY_CMD", "cp", 1); setenv("MKDIR_CMD", "mkdir -p", 1); setenv("RM_CMD", "rm -f", 1); setenv("RMDIR_CMD", "rm -rf", 1); #endif std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); if (ap.read("-W", stringParam) || ap.read("-W")) { ossimFilename templateFile (tempString.c_str()); if (templateFile.empty()) templateFile = "obt_config_long_template.kwl"; m_templateModeActive = true; writeTemplate(templateFile, true); return true; } if (ap.read("-w", stringParam) || ap.read("-w")) { ossimFilename templateFile(tempString.c_str()); if (templateFile.empty()) templateFile = "obt_config_short_template.kwl"; m_templateModeActive = true; writeTemplate(templateFile, false); return true; } while ( ap.read("-a", stringParam) || ap.read("--accept-test", stringParam) ) { if ( tempString.size() ) { ossimString os = tempString; ossimString separatorList = " "; std::vector result; os.split(result, separatorList); std::vector::const_iterator i = result.begin(); while ( i != result.end() ) { m_acceptTestList.push_back((*i)); ++i; } } } while ( ap.read("-c", stringParam) || ap.read("--clean-test", stringParam) ) { if ( tempString.size() ) { ossimString os = tempString; ossimString separatorList = " "; std::vector result; os.split(result, separatorList); std::vector::const_iterator i = result.begin(); while ( i != result.end() ) { m_cleanTestList.push_back((*i)); ++i; } } } while ( ap.read("-p", stringParam) || ap.read("--preprocess-test", stringParam) ) { if ( tempString.size() ) { ossimString os = tempString; ossimString separatorList = " "; std::vector result; os.split(result, separatorList); std::vector::const_iterator i = result.begin(); while ( i != result.end() ) { m_preprocessTestList.push_back((*i)); ++i; } } } while ( ap.read("-r", stringParam) || ap.read("--run-test", stringParam) ) { if ( tempString.size() ) { ossimString os = tempString; ossimString separatorList = " "; std::vector result; os.split(result, separatorList); std::vector::const_iterator i = result.begin(); while ( i != result.end() ) { m_runTestList.push_back((*i)); ++i; } } } // End of arg parsing. ap.reportRemainingOptionsAsUnrecognized(); if ( ap.errors() ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); return false; } if (ap.argc() > 1 ) { m_configFileName = ap.argv()[1]; } else { usage(ap); // continue_after_init to false return false; } // Special command line case: When only a config filename is provided, this implies "run all // tests". if (m_cleanTestList.empty() && m_preprocessTestList.empty() && m_acceptTestList.empty() && m_runTestList.empty() && m_configFileName.size()) { m_runTestList.push_back("all"); } return true; } //--- // Writes a template (either long form or short) to the file name specified. //--- void ossimBatchTest::writeTemplate(const ossimFilename& templateFile, bool write_long_form) { if (templateFile.exists()) { ossimString del_cmd ("$(RM_CMD) "); del_cmd += templateFile; del_cmd = del_cmd.expandEnvironmentVariable(); if (system(del_cmd.chars()) != 0) { cerr << "ERROR: Could not delete existing template file before writing new template." " Please delete the existing and rerun the command."<< endl; return; } } std::ofstream out(templateFile.c_str()); if ( !out.good() ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Could not open: " << templateFile.c_str() << std::endl; return; } if (write_long_form) { out<< "//===================================================================================\n" << "// \n" << "// File: " << templateFile.c_str() << "\n" << "// Generated by command: ossim-batch-test -W " << templateFile.c_str() << "\n" << "// Description: ossim-batch-test template config file.\n" << "// \n" << "// Control flags:\n" << "// Use 1 or true, 0 or false to turn on and off sections.\n" << "// Typically preprocess and expected results only turned on for first run.\n" << "// Clean commands should erase anything created by this test.\n" << "// Command order if flag turned on:\n" << "// 1) clean, 2) pre-process, 3) expected, 4) test, 5) post-process\n" << "// \n" << "// NOTES:\n" << "// * The following environment variables must be set before running batch test:\n" << "// OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data\n" << "// OSSIM_BATCH_TEST_EXPECTED Top-level dir containing all test expected results \n" << "// OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results and logging output \n" << "// \n" << "// * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during run-time to\n" << "// the proper paths according to the config filename. It isn't required to replace\n" << "// these nor predefine them in the environment. You can leave them as is or modify\n" << "// the paths to your unconventional file paths.\n" << "// \n" << "// * In order to preserve platform independence, please utilize the following \n" << "// variables for the common OS commands when adding new commands to the test\n" << "// configuration KWL file. Examples are provided in this template\n" << "// $(DIFF_CMD) Use this var for windows \"fc\" or linux \"diff\"\n" << "// $(COPY_CMD) Use this var for windows \"copy\" or linux \"cp\"\n" << "// $(MKDIR_CMD) Use this var for windows \"mkdir\" or linux \"mkdir\"\n" << "// $(RM_CMD) Use this var for windows \"del /Q\" or linux \"rm -f\"\n" << "// $(RMDIR_CMD) Use this var for windows \"rmdir /S /Q\" or linux \"rm -rf\"\n" << "// This application will set the environment variables to the proper values at \n" << "// runtime, so no need to worry about defining these.\n" << "// \n" << "// * Use forward slashes \"//\", at beginning of line for comments.\n" << "// \n" << "// * You can use existing environment variables as $(YOUR_VARIABLE). They will be \n" << "// expanded at run time if valid.\n" << "// \n" << "// * Clean, preprocess, run, and accept test sections can be switched on or off\n" << "// at run time. These override config file flags. Optional arguments are the \n" << "// the following: \n" << "// -c or --clean-test \n" << "// -p or --preprocess-test\n" << "// -r or --run-test \n" << "// -a or --accept-test \n" << "// Multiple tests can be entered by quoting string of space-separated\n" << "// test names, e.g. \"test1 test2\". To do all tests use \"all\" or leave blank.\n" << "// \n" << "//===================================================================================\n" << "\n" << "// If the config file will contain only a list of subordinate config files to be\n" << "// run as one consolidated \"super-test\", then use only the following suffixed\n" << "// keywords. Otherwise, REMOVE THESE:\n" << "test_config_file1: \n" << "test_config_file2: \n" << "// ... etc.\n" << "\n" << "// The remaining keywords are used exclusive of \"test_config_fileX\" above. The\n" << "// config files must be either a list of subordinate configs, or a concrete, \n" << "// low-level config file.\n" << "\n" << "// Where you want the top-level (inter-test) log files to go:\n" << "log_directory: $(OBT_OUT_DIR)\\..\\log\n" << "\n" << "//===================================================================================\n" << "// Begin Test 1\n" << "// NOTE: If the config file contains just a single test, then the use of the \"test1\"\n" << "// prefix is optional. Make sure the results directory spec reflects the proper path.\n" << "\n" << "test1.name: \n" << "test1.description: Test height for the center of the image for test2 and test3.\n" << "\n" << "// Controls/turns on/off whole test (all sections):\n" << "test1.enabled: 1\n" << "\n" << "// Individual control flags:\n" << "test1.run_clean_commands: 0\n" << "test1.run_preprocessing_commands: 0\n" << "test1.run_expected_results_commands: 0\n" << "test1.run_test_commands: 1\n" << "test1.run_postprocessing_commands: 1\n" << "\n" << "// Temp file to catch diff output.\n" << "test1.temp_file: $(TEMP)\\tmp.txt\n" << "\n" << "// Clean up commands\n" << "test1.clean_command1: $(RMDIR_CMD) $(OBT_OUT_DIR)\n" << "\n" << "// Pre-process commands\n" << "test1.preprocess_command1: $(MKDIR_CMD) $(OBT_OUT_DIR)\n" << "test1.preprocess_command1: $(MKDIR_CMD) $(OBT_OUT_DIR)\\..\\log\n" << "\n" << "//---------------------------------------\n" << "// Commands to generate expected results\n" << "//---------------------------------------\n" << "// Since test2 and test3 are dependent on elevation test the center of the image.\n" << "test1.expected_results_command0: ossim-info --height -42.8508 147.2537 > $(OBT_EXP_DIR)\\height.txt\n" << "test1.expected_results_command1: $(COPY_CMD) $(OBT_OUT_DIR)\\height.txt $(OBT_EXP_DIR)\\height.txt\n" << "\n" << "//---------------------------------------\n" << "// The actual commands to test\n" << "//---------------------------------------\n" << "test1.test_command0: ossim-info --height -42.8508 147.2537 > $(OBT_OUT_DIR)\\height.txt\n" << "\n" << "//-------------------------------------------\n" << "// Post process commands for diffs, etc.\n" << "//-------------------------------------------\n" << "test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)\\height.txt $(OBT_OUT_DIR)\\height.txt\n" << " \n" << "\n" << "// End \n" << "//===================================================================================\n" << "// Begin ...\n" << "\n" << "// You can specify additional tests by copying the test1 keywords and changing the\n" << "// prefix indices to be unique. It is not necessary to be consecutive.\n" << "\n" << std::endl; } else { out<< "//===================================================================================\n" << "// \n" << "// File: " << templateFile.c_str() << "\n" << "// Generated by command: ossim-batch-test -w " << templateFile.c_str() << "\n" << "// Description: ossim-batch-test template config file.\n" << "// \n" << "// NOTES:\n" << "// * The following environment variables must be set before running batch test:\n" << "// OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data\n" << "// OSSIM_BATCH_TEST_EXPECTED Top-level dir containing all test expected results \n" << "// OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results and logging output \n" << "// \n" << "// * You can use existing environment variables as $(YOUR_VARIABLE). They will be \n" << "// expanded at run time if valid.\n" << "// \n" << "// * If the config file contains more than a single test, then it will be necessary \n" << "// to prefix all test-specific keywords with \"testN.\"\n" << "// \n" << "// * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during runtime to\n" << "// the proper paths according to the config filename. It isn't required to replace\n" << "// these nor predefine them in the environment. You can leave them as is or modify\n" << "// the paths to your unconventional file paths.\n" << "// \n" << "//===================================================================================\n" << "\n" << "description: Test height for the center of the image for test2 and test3.\n" << "\n" << "//---------------------------------------\n" << "// Commands to generate expected results.\n" << "//---------------------------------------\n" << "expected_results_command0: ossim-info --height -42.8508 147.2537 > $(OBT_OUT_DIR)\\height.txt\n" << "expected_results_command1: $(COPY_CMD) $(OBT_OUT_DIR)\\height.txt $(OBT_EXP_DIR)\\height.txt\n" << "\n" << "//---------------------------------------\n" << "// The actual commands to test.\n" << "//---------------------------------------\n" << "test_command0: ossim-info --height -42.8508 147.2537 > $(OBT_OUT_DIR)\\height.txt\n" << "\n" << "//---------------------------------------\n" << "// The post-processing (comparison) commands. Typically these involve a file \n" << "// comparison of last run command against expected results.\n" << "//---------------------------------------\n" << "postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)\\height.txt $(OBT_OUT_DIR)\\height.txt\n" << std::endl; } out.close(); ossimNotify(ossimNotifyLevel_NOTICE) << "Wrote file: " << templateFile.c_str() << std::endl; } //************************************************************************************************** // Processes a test config file //************************************************************************************************** ossim_uint8 ossimBatchTest::execute() { if (m_templateModeActive) { return TEST_PASSED; } ossim_uint8 status = TEST_TBD; ossimString configName (m_configFileName.fileNoExtension()); cout << "\nExecuting batch test for config: <" << configName << ">" << endl; try { ossimEnvironmentUtility* ossimEnv = ossimEnvironmentUtility::instance(); // Fetch possible existing env vars for the expected and output directories: ossimFilename base_output_dir = ossimEnv->getEnvironmentVariable(ossimString("OSSIM_BATCH_TEST_RESULTS")); if (base_output_dir.empty()) { // Need to establish the top-level test directory that will contain log and out subdirs: cout<<"\nossimBatchTest WARNING: The environment variable OSSIM_BATCH_TEST_RESULTS is not " "defined. Results will be written relative to the current working directory."<getCurrentWorkingDir(); } // The base output directory is appended with the name of the test config file. Need to export // the corresponding env var so that the KeywordList class can expand the same env var used // in the config file: base_output_dir = base_output_dir.dirCat(configName); m_outDir = base_output_dir.dirCat("out"); ossimEnv->setEnvironmentVariable("OBT_OUT_DIR", m_outDir.chars()); m_expDir = ossimEnv->getEnvironmentVariable(ossimString("OSSIM_BATCH_TEST_EXPECTED")); if (m_expDir.empty()) { // Need to establish the top-level test directory that will contain expected results: m_expDir = base_output_dir.dirCat("exp"); } else { m_expDir = m_expDir.dirCat(configName); } ossimEnv->setEnvironmentVariable("OBT_EXP_DIR", m_expDir.chars()); // Turn expansion of for like: $(OBT_TEST_RESULTS) ossimKeywordlist kwl; kwl.setExpandEnvVarsFlag(true); if (!kwl.addFile(m_configFileName)) { ostringstream errmsg; errmsg << "Error encountered reading test config at <"<."< with overall status = " <."<< endl; throw ossimException(errmsg.str()); } // Establish path to and active stream for the log file: ossimFilename logFile; getLogFilename(logFile); logFile = logDir.dirCat(logFile); ossimSetLogFilename(logFile); m_logStr.open(logFile.c_str()); if ( m_logStr.fail() ) { status = TEST_ERROR; ostringstream errmsg; errmsg << "Could not open: <" << logFile << ">."<< endl; throw ossimException(errmsg.str()); } cout << "Logging to file: " << logFile << "\n"; ossimString date; getDateString(date); m_logStr << "// ---\n" << "// ossim-batch-test log:\n" << "// date format = yyyymmddhhmmss\n" << "//---\n" << "start_time: " << date << "\n" << "config_file: " << m_configFileName<< "\n"; // Start the timer. ossimTimer::instance()->setStartTick(); double startTime = ossimTimer::instance()->time_s(); ossimString regExpStr = "test[0-9]+\\."; std::vector prefixes; kwl.getSubstringKeyList(prefixes, regExpStr); // If no test prefix is used, this implies a single test: if (prefixes.empty()) prefixes.push_back(""); status = TEST_TBD; for(ossim_uint32 idx = 0; idx < prefixes.size(); ++idx) { ossim_uint8 individual_test_status = processTest( prefixes[idx], kwl); status |= individual_test_status; } getDateString(date); m_logStr << "\nstop_time: " << date << "\n"; double stopTime = ossimTimer::instance()->time_s(); m_logStr << "total elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(4) << (stopTime-startTime) << endl; // flush m_logStr.close(); cout << "\ntotal elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(4) << (stopTime-startTime) << "\nWrote log: " << logFile << "\n" << endl; } catch (ossimException& e) { status = TEST_ERROR; cerr << "\nossimBatchTest::execute() caught exception: " << e.what() << endl; } catch ( ... ) { cerr << "\nossimBatchTest::execute() caught unhandled exception: " << endl; } cout<<"ossimBatchTest: Exiting <"< with status = " < keywords; kwl.getSubstringKeyList(keywords, keywordRegEx); for(ossim_uint32 idx=0;idx < (ossim_uint32)keywords.size(); ++idx) { // Looping over each config file listed, performing an execute() on each: m_configFileName = kwl.findKey(keywords[idx]); if (!m_configFileName.empty()) { // Expand any environment variable: if (m_configFileName.contains("$(")) m_configFileName = m_configFileName.expand(); // Handle paths relative to the master config list file: if (m_configFileName.path().empty()) m_configFileName = m_configFileName.setPath(config_list_path); } // Execute this config file: if (m_configFileName.isReadable()) { overall_test_status |= execute(); } } return overall_test_status; } //************************************************************************************************ //! Fetches string from OS for naming and tagging the log file. //************************************************************************************************ void ossimBatchTest::getDateString(ossimString& date) { time_t t; time(&t); tm* lt; lt = localtime(&t); std::string frmt = "%Y%m%d%H%M%S"; // yyyymmddhhmmss char s[15]; size_t count = strftime(s, 15, frmt.c_str(), lt); if ( count && (count < 15) ) date = s; else date.clear(); } //************************************************************************************************** //! Establishes name of output log file. //************************************************************************************************** void ossimBatchTest::getLogFilename(ossimFilename& logFile) { logFile = "obt-log-"; ossimString date; getDateString(date); logFile += date; logFile += ".txt"; } //************************************************************************************************** //! Within a single config file can be multiple tests, distinguished by the "test*." prefix. This //! method manages the execution of a single test. //************************************************************************************************** ossim_uint8 ossimBatchTest::processTest(const ossimString& prefix, const ossimKeywordlist& kwl) { ossim_uint8 testStatus = TEST_TBD; // Determine first if this test prefix is represented in the KWL: if (kwl.getNumberOfSubstringKeys(prefix) == 0) return testStatus; ossimString testName; const char* lookup = kwl.find( prefix, "name" ); if ( lookup ) { testName = lookup; } if (testName.empty()) { if (prefix.empty()) testName = m_configFileName.fileNoExtension(); else testName = prefix.trim("."); } m_logStr << "\n----------------------------------------------------------------------\n"; // See if test is disabled/enabled: bool enabled = true; lookup = kwl.find( prefix, "enabled" ); if ( lookup ) { enabled = ossimString(lookup).toBool(); } if ( !enabled ) { testStatus = TEST_DISABLED; ossimString statusString; if ( prefix.size() ) { statusString = prefix.trim(ossimString(".")) + ossimString(": disabled"); } else { statusString = "test: disabled"; } cout << "test_name: " << testName << "\n" << statusString << endl; m_logStr << "test_name: " << testName << "\n" << statusString << endl; return testStatus; } cout << "\n\nbegin_test:\n" << prefix << "name: " << testName << "\n"; m_logStr << "\n\nbegin_test:\n" << prefix << "name: " << testName << "\n"; lookup = kwl.find( prefix, "description" ); if ( lookup ) m_logStr << "description: " << lookup << "\n"; bool preProcessFlag = false; bool expectedFlag = false; bool testFlag = false; bool postProcessFlag = false; bool cleanFlag = false; std::string date; lookup = kwl.find(prefix.c_str(), "run_clean_commands"); if ( lookup ) { cleanFlag = ossimString(lookup).toBool(); } lookup = kwl.find(prefix.c_str(), "run_preprocessing_commands"); if ( lookup ) { preProcessFlag = ossimString(lookup).toBool(); } lookup = kwl.find(prefix.c_str(), "run_expected_results_commands"); if ( lookup ) { expectedFlag = ossimString(lookup).toBool(); } lookup = kwl.find(prefix.c_str(), "run_test_commands"); if ( lookup ) { testFlag = ossimString(lookup).toBool(); } lookup = kwl.find(prefix.c_str(), "run_postprocessing_commands"); if ( lookup ) { postProcessFlag = ossimString(lookup).toBool(); } m_logStr << "preProcessFlag: " << preProcessFlag << "\nexpectedFlag: " <time_s(); } // Launch the command: int status = system(command_line.chars()); if (status == 0) result |= TEST_PASSED; else if (postprocessing) result |= TEST_FAILED; else result |= TEST_ERROR; if ( logTime ) { // Log the time and status: stopTime = ossimTimer::instance()->time_s(); getDateString(date); m_logStr << "end: " << date << "\n" << testName << "[" << index << "]: elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(4) << (stopTime-startTime) << "\n"; } m_logStr << "return status: " << status << "\n"; // Output the status. // If failed write the temp file to the log. This should have the diffs in it. ostringstream statusString; if ( prefixBase.size() ) { statusString << prefixBase; } else { statusString << "test"; } statusString << "[" << index << "]: "; if ( status != 0 ) { // A bad return status can be a test fail if the command was a postprocess: if ( postprocessing ) { statusString << "FAILED"; } else { statusString << "ERROR"; } cout << statusString.str() << endl; m_logStr << statusString.str() << endl; m_logStr << command << "\noutput follows:\n"; std::ifstream in; if (!tempFileName.empty()) { in.open(tempFileName.c_str(), ios::in | ios::binary); if ( in.is_open() ) { char ch; while ( in.get(ch) ) m_logStr.put(ch); m_logStr << "\n"; in.close(); } } } else { statusString << "PASSED"; cout << statusString.str() << endl; m_logStr << statusString.str() << endl; } ++processedIndexes; } ++index; if ( index >= MAX_INDEX ) break; // Config file has bad numbering... } return result; } //************************************************************************************************** void ossimBatchTest::preprocessKwl(const std::vector& testList, const std::string& testCommand, ossimKeywordlist& kwl) { if ( testList.empty() || testCommand.empty() || (kwl.getSize()==0) ) return; // Check for user passed in "all" to option. std::vector::const_iterator testIter = testList.begin(); bool enableAllTestFlag = false; ossimString firstTest(*testIter); firstTest.downcase(); if ( firstTest == "all" ) { enableAllTestFlag = true; } while ( testIter != testList.end() ) { // Get the number of test: ossimString regExpStr = "test[0-9]+\\."; ossim_uint32 num_tests = kwl.getNumberOfSubstringKeys(regExpStr); const ossim_uint32 MAX_INDEX = num_tests + 1000; ossimString prefixBase = "test"; ossim_uint32 index = 0; ossim_uint32 processedIndexes = 0; // A count of 0 may indicate that the config file consists of a single, unprefixed test spec: bool is_single_test = false; if (num_tests == 0) { regExpStr = "test_command[0-9]+"; const ossim_uint32 cmd_count = kwl.getNumberOfSubstringKeys(regExpStr); if (cmd_count != 0) { ++num_tests; is_single_test = true; } else break; // Nothing to do here: } while ( processedIndexes < num_tests ) { ossimString prefix (""); bool test_name_matches = true; bool test_exists = true; if (!is_single_test) { // The tests are prefixed with "test*". Assign the prefix for this test set: prefix = prefixBase + ossimString::toString(index); test_name_matches = (prefix == (*testIter).c_str()); prefix += "."; // With a valid prefix, check if this test even exists before doing any more // preprocessing: regExpStr = prefix + "test_command[0-9]+"; const ossim_uint32 cmd_count = kwl.getNumberOfSubstringKeys(regExpStr); test_exists = cmd_count > 0; } if ( test_exists ) { if ( test_name_matches || enableAllTestFlag ) { //--- // Removed adjustment of "enable" flag. Let the config file "enable" key // control this. drb - 20151202 // kwl.add(prefix.c_str(), "enabled", "1", true); //--- kwl.add(prefix.c_str(), testCommand.c_str(), "1", true); if ( testCommand == "run_expected_results_commands" ) { // Need pre-processing if clean performed. kwl.add(prefix.c_str(), "run_preprocessing_commands", "1", true); } if ( testCommand == "run_test_commands" ) { // Need pre/post-processing: kwl.add(prefix.c_str(), "run_preprocessing_commands", "1", true); kwl.add(prefix.c_str(), "run_postprocessing_commands", "1", true); } } ++processedIndexes; } ++index; if ( index >= MAX_INDEX ) break; } ++testIter; } // End: while ( testIter != testList.end() ) } // End: preprocessKwl method //************************************************************************************************** //! Default preprocessing step makes expected and output results directories. Returns TRUE if //! successful. //************************************************************************************************** bool ossimBatchTest::makeDefaultResultsDir() { if ( !m_outDir.exists() && !m_outDir.createDirectory() ) { cerr << "Could not create: " << m_outDir << endl; return false; } if ( !m_expDir.exists() && !m_expDir.createDirectory() ) { cerr << "Could not create: " << m_expDir << endl; return false; } return true; } //************************************************************************************************** //! Default clean step deletes all files in out and exp dirs. Returns TRUE if successful. //************************************************************************************************** bool ossimBatchTest::doDefaultClean() { bool result = true; ossimString del_cmd = ossimEnvironmentUtility::instance()->getEnvironmentVariable( ossimString("RMDIR_CMD") ); ossimString command_line; if ( m_outDir.exists() ) { command_line = del_cmd + " " + m_outDir; m_logStr << "executing command: " << command_line << "\n"; if (system(command_line) != 0) { m_logStr << "ERROR: execution failed!\n"; cerr << "ERROR: Could not delete <"<. Clean operation failed."<< endl; result = false; } } ossimFilename tmpDir; if ( getDefaultTempFileDir( tmpDir ) ) { if ( tmpDir.exists() ) { command_line = del_cmd + " " + tmpDir; m_logStr << "executing command: " << command_line << "\n"; if (system(command_line) != 0) { m_logStr << "ERROR: execution failed!\n"; cerr << "ERROR: Could not delete <"<. Clean operation failed."<< endl; result = false; } } } return result; } bool ossimBatchTest::getTempFileName( const ossimString& prefix, const ossimKeywordlist& kwl, ossimFilename& tempFile ) const { const char* lookup = kwl.find(prefix.c_str(), "temp_file"); if ( lookup ) { tempFile = ossimFilename(lookup); if (tempFile.contains("$(")) tempFile = tempFile.expand(); } else { if ( getDefaultTempFileDir( tempFile ) ) { if ( tempFile.createDirectory( true, 0775 ) ) { // Tack on the file name. tempFile = tempFile.dirCat("tmp.txt"); } else { tempFile.clear(); } } } return ( tempFile.size() > 0 ); } bool ossimBatchTest::getDefaultTempFileDir( ossimFilename& tempFile ) const { // Create a default tmp directory under OSSIM_BATCH_TEST_RESULTS. tempFile = ossimEnvironmentUtility::instance()->getEnvironmentVariable( ossimString("OSSIM_BATCH_TEST_RESULTS") ); if (!tempFile.empty()) tempFile = tempFile.dirCat("tmp"); else tempFile = ossimEnvironmentUtility::instance()->getEnvironmentVariable(ossimString("TEMP")); return ( tempFile.size() > 0 ); } void ossimBatchTest::usage(ossimArgumentParser& ap) { ossimApplicationUsage* au = ap.getApplicationUsage(); au->addCommandLineOption("-a or --accept-test", " Runs \"run_expected_results_commands\" portion from test configuration file for " "testX where X is some test number, i.e. 1, 2, 3... This will turn off all other test in " "the test config file. Notes: Multiple tests can be entered by quoting string of space " "separated test, e.g. \"test1 test2\". To accept all tests use \"all\" for test."); au->addCommandLineOption("-c or --clean-test", " Runs \"run_clean_commands\" portion " "from test configuration file for testX where X is some test number, i.e. 1, 2, 3... This " "will turn off all other test in the test config file. Notes: Multiple tests can be entered " "by quoting string of space separated test, e.g. \"test1 test2\". To clean all tests use " "\"all\" for test."); au->addCommandLineOption("-p or --preprocess-test", " Runs \"run_preprocessing_commands\" portion from test configuration file for testX " "where X is some test number, i.e. 1, 2, 3... This will turn off all other test in the test " "config file. Notes: Multiple tests can be entered by quoting string of space separated " "test, e.g. \"test1 test2\". To preprocess all tests use \"all\" for test."); au->addCommandLineOption("-r or --run-test", " Runs \"run_test_commands\" portion from test configuration file for testX where X " "is some test number, i.e. 1, 2, 3... This will turn off all other test in the test config " "file. Notes: Multiple tests can be entered by quoting string of space separated test, e.g. " "\"test1 test2\". To run all tests use \"all\" for test."); au->addCommandLineOption("-h or --help", "Display usage."); au->addCommandLineOption("-W or -w", " Writes a long-form (-W) or a short-form (-w) template test " "configuration file."); // Write usage. au->write(ossimNotify(ossimNotifyLevel_INFO)); } std::string ossimBatchTest::convertToNative( const char* lookup ) const { std::string s; if ( lookup ) { s = lookup; const std::string::size_type SIZE = s.size(); std::string::size_type i = 0; #if defined(_WIN32) //--- // Must not convert slashes for: "del /Q", "fc /W", and "copy /Y" //--- while( i < SIZE ) { if( s[i] == '/' ) { bool replace = true; if ( (i+2) < SIZE ) // Could fit a window command and space like: "/Y " { if ( (s[i+1] == 'Q') || (s[i+1] == 'W') || (s[i+1] == 'Y') ) { if ( s[i+2] == ' ' ) // Check for space after "/Q". { replace = false; } } } if ( replace ) { s[i] = '\\'; } } ++i; } #else while( i < SIZE ) { if( s[i] == '\\' ) { s[i] = '/'; } ++i; } #endif } // Matches: if ( lookup ) return s; } ossim-Miami-2.9.1/src/util/ossimChipProcTool.cpp000077500000000000000000001534541352751253100216220ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static const std::string AOI_GEO_RECT_KW = "aoi_geo_rect"; static const std::string AOI_MAP_RECT_KW = "aoi_map_rect"; static const std::string AOI_GEO_CENTER_KW = "aoi_geo_center"; static const std::string AOI_SIZE_METERS_KW = "aoi_size_meters"; static const std::string AOI_SIZE_PIXELS_KW = "aoi_size_pixels"; static const std::string CLIP_POLY_LAT_LON_KW = "clip_poly_lat_lon"; static const std::string LUT_FILE_KW = "lut_file"; static const std::string GSD_KW = "gsd"; static const std::string OUTPUT_RADIOMETRY_KW = "output_radiometry"; static const std::string READER_PROPERTY_KW = "reader_property"; static const std::string SNAP_TIE_TO_ORIGIN_KW = "snap_tie_to_origin"; static const std::string SRS_KW = "srs"; static const std::string TILE_SIZE_KW = "tile_size"; // pixels static const std::string TRUE_KW = "true"; static const std::string WRITER_KW = "writer"; static const std::string WRITER_PROPERTY_KW = "writer_property"; ossimChipProcTool::ossimChipProcTool( const ossimChipProcTool& /* obj */) : m_projIsIdentity(false), m_geoScaled (false), m_productScalarType(OSSIM_SCALAR_UNKNOWN), m_needCutRect(false) {} ossimChipProcTool::ossimChipProcTool() : m_projIsIdentity(false), m_geoScaled(false), m_productScalarType(OSSIM_SCALAR_UNKNOWN), m_needCutRect(false) { m_kwl.setExpandEnvVarsFlag(true); m_gsd.makeNan(); m_geom = new ossimImageGeometry; m_procChain = new ossimImageChain; } ossimChipProcTool::~ossimChipProcTool() { clear(); } void ossimChipProcTool::clear() { m_gsd.makeNan(); m_procChain = 0; m_imgLayers.clear(); m_writer = 0; m_geom = 0; m_needCutRect = false; } bool ossimChipProcTool::initialize(ossimArgumentParser& ap) { if (!ossimTool::initialize(ap)) return false; if (m_helpRequested) return true; std::string tempString1; ossimArgumentParser::ossimParameter stringParam1(tempString1); std::string tempString2; ossimArgumentParser::ossimParameter stringParam2(tempString2); std::string tempString3; ossimArgumentParser::ossimParameter stringParam3(tempString3); std::string tempString4; ossimArgumentParser::ossimParameter stringParam4(tempString4); double tempDouble1; ossimArgumentParser::ossimParameter doubleParam1(tempDouble1); double tempDouble2; ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); vector paramList; ossim_uint32 readerPropIdx = 0; ossim_uint32 writerPropIdx = 0; ostringstream keys; if ( ap.read("--load-options", stringParam1)) { if (!m_kwl.addFile(tempString1.c_str())) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); throw ossimException("Must supply an output file."); } } if ( ap.read("--aoi-geo-bbox", stringParam1, stringParam2, stringParam3, stringParam4)) { ostringstream ostr; ostr< imageFnames; if (ap.read("--image", imageFnames) || ap.read("-i", imageFnames)) { if (imageFnames.size() == 1) m_kwl.add(ossimKeywordNames::IMAGE_FILE_KW, imageFnames[0].chars() ); else for(ossim_uint32 idx=0; idx= 2 ) { // Output file is last arg: m_kwl.add( ossimKeywordNames::OUTPUT_FILE_KW, ap[ap.argc()-1]); } else { if ( !m_kwl.find(ossimKeywordNames::OUTPUT_FILE_KW) ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); throw ossimException("Must supply an output file."); } } if ( ap.argc() > 2 ) // User passed inputs in front of output file. { int pos = 1; // ap.argv[0] is application name. int idx = 0; while ( pos < (ap.argc()-1) ) { ostringstream key; key< 2 ) // End of arg parsing. ap.reportRemainingOptionsAsUnrecognized(); if ( ap.errors() ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); throw ossimException("Unknown option..."); } if (dumpKwl) { ossimFilename f = getClassName(); f.setExtension("kwl"); if (!m_kwl.write(f.chars())) { ostringstream xmsg; xmsg<<"ossimChipProcUtil:"<<__LINE__<<" Error encountered writing options file to <"<"; throw ossimException(xmsg.str()); } ossimNotify(ossimNotifyLevel_NOTICE)<<"\nWrote options file to <"<"< getScalarTypeFromString( m_kwl.findKey( OUTPUT_RADIOMETRY_KW ) ); m_productFilename = m_kwl.findKey( std::string(ossimKeywordNames::OUTPUT_FILE_KW) ); // Create chains for input sources. loadImageFiles(); // Load any specified DEMs: loadDemFiles(); // Initialize projection and propagate to chains. createOutputProjection(); // Pass control to derived class so it can add its specific processing to the chain(s). This // should return an initialized m_procChain. initProcessingChain(); finalizeChain(); } void ossimChipProcTool::finalizeChain() { ostringstream errMsg; // See if an LUT is requested: ossimFilename lutFile = m_kwl.findKey( LUT_FILE_KW ); if (!lutFile.empty()) { if ( !lutFile.exists() ) { errMsg<<"ERROR ossimChipProcUtil ["<<__LINE__<<"] Color table <"< does not exists: "< lut = new ossimIndexToRgbLutFilter(); lut->setLut(lutFile); m_procChain->add(lut.get()); } if (m_needCutRect) { // Add a cut filter. This will: // 1) Null out/clip any data pulled in. // 2) Speed up by not propagating get tile request outside the cut or "aoi" // to the left hand side(input). m_cutRectFilter = new ossimRectangleCutFilter(); m_cutRectFilter->setRectangle( m_aoiViewRect ); m_cutRectFilter->setCutType( ossimRectangleCutFilter::OSSIM_RECTANGLE_NULL_OUTSIDE ); m_procChain->add(m_cutRectFilter.get()); } // Set the image size here. Note must be set after combineLayers. This is needed for // the ossimImageGeometry::worldToLocal call for a geographic projection to handle wrapping // accross the date line. m_geom->setImageSize( m_aoiViewRect.size() ); // Reset the source bounding rect if it changed. m_procChain->initialize(); } bool ossimChipProcTool::execute() { if (m_helpRequested) return true; ostringstream xmsg; if ( !m_procChain.valid() ) { xmsg << "ossimChipProcUtil:"<<__LINE__<<"Null pointer encountered for m_procChain!"; throw ossimException(xmsg.str()); } if (m_geom->getImageSize().hasNans()) { xmsg << "ossimChipProcUtil:"<<__LINE__<<"Image size is NaN!"; throw ossimException(xmsg.str()); } // Set up the writer. m_writer = newWriter(); // Connect the writer to the processing chain. m_writer->connectMyInputTo(0, m_procChain.get()); // Set the area of interest. NOTE: This must be called after the writer->connectMyInputTo as // ossimImageFileWriter::initialize incorrectly resets AOI back to the bounding rect. m_writer->setAreaOfInterest(m_aoiViewRect); if (m_writer->getErrorStatus() != ossimErrorCodes::OSSIM_OK) throw ossimException( "Unable to initialize writer for execution" ); // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); m_writer->addListener(&prog); // Write the file: m_writer->execute(); m_writer->removeListener(&prog); if(m_writer->isAborted()) { xmsg << "ossimChipProcUtil:"<<__LINE__<<"Writer Process aborted!"; throw ossimException(xmsg.str()); } ossimNotify(ossimNotifyLevel_INFO)<<"Wrote product image to <"<"<abort(); } } ossimRefPtr ossimChipProcTool::getChip(const ossimDrect& map_bounding_rect, const ossimDpt& gsd) { ostringstream xmsg; if (!m_geom.valid()) return 0; ossimMapProjection* proj = m_geom->getAsMapProjection(); if (proj == 0) return 0; proj->setMetersPerPixel(gsd); ossimGpt ulGpt = proj->inverse(map_bounding_rect.ul()); ossimGpt lrGpt = proj->inverse(map_bounding_rect.lr()); m_aoiGroundRect = ossimGrect(ulGpt, lrGpt); ossimDrect view_rect; m_geom->worldToLocal(m_aoiGroundRect, view_rect); m_aoiViewRect = view_rect; m_geom->setImageSize( m_aoiViewRect.size() ); return getChip(m_aoiViewRect); } ossimRefPtr ossimChipProcTool::getChip(const ossimGrect& geo_bounding_grect) { ossimRefPtr chip = 0; if (!m_geom.valid()) return chip; // Set the new cut rectangle. Note that a NaN rect passed in implies the full AOI: if (!geo_bounding_grect.hasNans()) { ossimNotify(ossimNotifyLevel_INFO) <<"\nossimChipProcUtil::getChip(grect) -- NaN rect " "provided. Using full AOI."< ossimChipProcTool::getChip(const ossimIrect& bounding_irect) { ossimRefPtr chip = 0; if(!m_procChain.valid()) return chip; m_aoiViewRect = bounding_irect; m_geom->setImageSize( m_aoiViewRect.size() ); // There should not be a chipper filter in the chain for getImage() calls since the chipping // is implied by the requested rect to getTile(), but if present, make sure it covers // the requested AOI to avoid masking out the tile. if (!m_cutRectFilter.valid()) { m_cutRectFilter = new ossimRectangleCutFilter; m_cutRectFilter->setCutType( ossimRectangleCutFilter::OSSIM_RECTANGLE_NULL_OUTSIDE ); m_procChain->add(m_cutRectFilter.get()); } m_cutRectFilter->setRectangle( m_aoiViewRect ); return m_procChain->getTile( m_aoiViewRect, 0 ); } ossimRefPtr ossimChipProcTool::getChip() { ossimRefPtr chip = 0; if(m_procChain.valid()) { chip = m_procChain->getTile( m_aoiViewRect, 0 ); } return chip; } ossimListenerManager* ossimChipProcTool::getManager() { return this; }; ossimObject* ossimChipProcTool::getObject() { return this; } const ossimObject* ossimChipProcTool::getObject() const { return this; } void ossimChipProcTool::loadImageFiles() { ossim_uint32 numImages = m_kwl.numberOf( ossimKeywordNames::IMAGE_FILE_KW ); ossim_uint32 count = numImages; ossim_uint32 entryIndex = 0; // Returns 0 if no entry found. This is default anyway. ossim_uint32 globalEntryValue = ossimString(m_kwl.find(ossimKeywordNames::ENTRY_KW)).toUInt32(); for (ossim_uint32 i=0; count > 0; ++i) { ossimFilename f; if (numImages == 1) { ostringstream key; key << ossimKeywordNames::IMAGE_FILE_KW; // Try non-indexed first f = m_kwl.findKey( key.str() ); } if (f.empty()) { ostringstream key; key << ossimKeywordNames::IMAGE_FILE_KW << i ; f = m_kwl.findKey( key.str() ); } if ( f.empty() ) continue; // Look for the entry key, e.g. image_source0.entry: 10 ostringstream entryKey; entryKey << ossimKeywordNames::IMAGE_FILE_KW << i << "." << ossimKeywordNames::ENTRY_KW; ossimString os = m_kwl.findKey(entryKey.str()); if (!os.empty()) entryIndex = os.toUInt32(); else entryIndex = globalEntryValue; // Add it: ossimRefPtr ic = createInputChain(f, entryIndex); if (!ic.valid()) { ostringstream errMsg; errMsg<<"ERROR: ossimChipProcUtil ["<<__LINE__<<"] Could not open <"<"< bandList(0); getBandList(i, bandList ); if ( bandList.size() ) ic->setBandSelection( bandList ); m_imgLayers.push_back(ic); --count; } } ossimRefPtr ossimChipProcTool::createInputChain(const ossimFilename& fname, ossim_uint32 entry_index) { // Init chain with handler: ossimRefPtr chain = new ossimSingleImageChain; if (!chain->open(fname)) { ostringstream errMsg; errMsg<<"ERROR: ossimChipProcUtil ["<<__LINE__<<"] Could not open <"<"<getImageHandler().get(); setReaderProps( handler ); if (!handler->setCurrentEntry( entry_index )) { std::ostringstream errMsg; errMsg << " ERROR: ossimChipProcUtil ["<<__LINE__<<"] Entry " << entry_index << " out of range!" << std::endl; throw ossimException( errMsg.str() ); } // Set up the remapper: if ( ( m_productScalarType != OSSIM_SCALAR_UNKNOWN) && ( m_procChain->getOutputScalarType() != m_productScalarType ) ) { ossimRefPtr remapper = new ossimScalarRemapper(); remapper->setOutputScalarType(m_productScalarType); chain->add(remapper.get()); } // Set up the renderer with cache: chain->addResampler(); chain->addCache(); // Add geo polygon cutter if specifried: ossimString param = m_kwl.findKey(CLIP_POLY_LAT_LON_KW); if (!param.empty()) { std::vector points; ossim::toVector(points, param); if(points.size() >= 3) { ossimGeoPolygon polygon(points); chain->addGeoPolyCutterPolygon(polygon); } } chain->initialize(); return chain; } void ossimChipProcTool::loadDemFiles() { ossim_uint32 numDems = m_kwl.numberOf( ossimKeywordNames::ELEVATION_SOURCE_KW ); if (numDems == 0) return; cout< 0; ++i) { ossimFilename f; if (numDems == 1) { ostringstream key; key << ossimKeywordNames::ELEVATION_SOURCE_KW; // Try non-indexed first f = m_kwl.findKey( key.str() ); } if (f.empty()) { ostringstream key; key << ossimKeywordNames::ELEVATION_SOURCE_KW << i ; cout<"; throw ossimException(errMsg.str()); } m_demSources.push_back(f); ossimElevManager::instance()->loadElevationPath(f, true); --count; } } void ossimChipProcTool::createOutputProjection() { static const char* MODULE = "ossimChipProcUtil::createOutputProjection()"; ossimString op = m_kwl.findKey( std::string(ossimKeywordNames::PROJECTION_KW) ); ossimString srs = m_kwl.findKey( SRS_KW ); if ( op.size() && srs.size() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " WARNING:" << "\nBoth " << SRS_KW << " and " << ossimKeywordNames::PROJECTION_KW << " keywords are set!" << "\nsrs: " << srs << "\noutput_projection: " << op << "\nTaking " << srs << " over " << op << "\n"; } ossimRefPtr proj = 0; m_geoScaled = false; op.downcase(); if (op.contains("epsg")) srs = op; if ( (op == "geo") || (srs.contains("4326"))) proj = new ossimEquDistCylProjection(); else if (srs.size()) { proj = PTR_CAST(ossimMapProjection, ossimProjectionFactoryRegistry::instance()->createProjection(srs)); if (!proj.valid()) throw ossimException("ossimChipProcUtil::createOutputProjection() -- Bad EPSG code passed."); } else if (op == "geo-scaled") { m_geoScaled = true; // used later when reference latitude is known proj = new ossimEquDistCylProjection(); } else if ( ( op == "input" ) || (op == "identity") || (op == "none") ) proj = newIdentityProjection(); else if ( (op == "utm") || (op == "ossimutmprojection") ) proj = newUtmProjection(); else { m_geoScaled = true; // used later when reference latitude is known proj = new ossimEquDistCylProjection(); } // Create our ossimImageGeometry with projection (no transform). proj->setElevationLookupFlag(true); m_geom->setProjection(proj.get()); // Set the scale and AOI. initializeProjectionGsd(); initializeAOI(); // also sets the tie point to AOI UL and geoscaling to origin. // Setup the view in all the chains. propagateGeometryToChains(); } ossimRefPtr ossimChipProcTool::newIdentityProjection() { ossimRefPtr sic = 0; ossimProjection* input_proj = 0; ossimRefPtr output_proj = 0; ossimRefPtr resampler = 0; if ( m_imgLayers.size() ) { sic = m_imgLayers[0]; if (sic.valid()) { ossimRefPtr ih = sic->getImageHandler(); if (ih.valid()) { ossimRefPtr geom = ih->getImageGeometry(); if (geom.valid()) { input_proj = geom->getProjection(); // Check if input is UTM, need to copy zone and hemisphere if so: ossimUtmProjection* input_utm = dynamic_cast(input_proj); if ( input_utm ) { ossimRefPtr output_utm = new ossimUtmProjection; output_utm->setZone(input_utm->getZone()); output_utm->setHemisphere(input_utm->getHemisphere()); output_proj = output_utm.get(); } else { input_proj = dynamic_cast( geom->getProjection() ); if (input_proj) { output_proj = (ossimMapProjection*) input_proj->dup(); m_projIsIdentity = true; } } } } } } // try input dem "image" if specified: if (!output_proj.valid() && (m_demSources.size())) { ossimImageGeometry geom; if (geom.open(m_demSources[0])) { input_proj = dynamic_cast(geom.getProjection()); if (input_proj) { output_proj = (ossimMapProjection*) input_proj->dup(); m_projIsIdentity = true; } } } return output_proj; } ossimRefPtr ossimChipProcTool::newUtmProjection() { // Make projection: ossimRefPtr utm = new ossimUtmProjection; // Set the zone from keyword option: bool setZone = false; ossim_int32 zone = 0; std::string value = m_kwl.findKey( std::string( ossimKeywordNames::ZONE_KW ) ); if ( value.size() ) zone = ossimString(value).toUInt32(); if ( (zone > 0 ) && ( zone < 61 ) ) { utm->setZone( zone ); setZone = true; } // Set the hemisphere from keyword option: bool setHemisphere = false; ossimString h = m_kwl.findKey( std::string( ossimKeywordNames::HEMISPHERE_KW ) ); if ( h.size() ) { h.upcase(); if ( ( h == "N" ) || ( h == "NORTH" ) || ( h == "S" ) || ( h == "SOUTH" ) ) { utm->setHemisphere( h.string()[0] ); setHemisphere = true; } } if ( !setZone || !setHemisphere ) { // Check for user set "central_meridian" and "origin_latitude": ossimGpt origin; getProjectionOrigin(origin); if ( !setZone ) utm->setZone(origin); if ( !setHemisphere ) utm->setHemisphere(origin); } return ossimRefPtr(utm.get()); } void ossimChipProcTool::initializeProjectionGsd() { // The GSD computation may be a chicken-and-egg problem. Need to try different methods depending // on information available in KWL including specified input images and DEMs. ossimRefPtr mapProj = dynamic_cast(m_geom->getProjection()); ossimString lookup = m_kwl.findKey( GSD_KW ); if ( lookup.size() ) m_gsd.y = m_gsd.x = lookup.toFloat64(); if (m_gsd.hasNans() && m_projIsIdentity && m_geom.valid()) m_geom->getMetersPerPixel(m_gsd); if (m_gsd.hasNans()) { // No GSD specified, use minimum among all input images: ossimGpt chainTiePoint; std::vector< ossimRefPtr >::iterator chainIdx = m_imgLayers.begin(); while ( chainIdx != m_imgLayers.end() ) { ossimRefPtr geom = (*chainIdx)->getImageGeometry(); if (geom.valid()) { ossimDpt gsd; geom->getMetersPerPixel(gsd); gsd.y = gsd.x = gsd.mean(); if (m_gsd.hasNans() || ( m_gsd.x > gsd.x)) m_gsd = gsd; } ++chainIdx; } } if (m_gsd.hasNans()) { // Still no GSD established, try using minimum among all input DEMs (the operation possibly // involves DEMs as inputs): std::vector::iterator demFile = m_demSources.begin(); while ( demFile != m_demSources.end() ) { ossimImageGeometry geom; if (geom.open(*demFile)) { ossimDpt gsd; geom.getMetersPerPixel(gsd); gsd.y = gsd.x = gsd.mean(); if (m_gsd.hasNans() || ( m_gsd.x > gsd.x)) m_gsd = gsd; } ++demFile; } } if (m_gsd.hasNans()) { // Still no GSD specified. As a last resort, use the elevation database nominal GSD at center // as output GSD. This is valid since most operations without input images depend on DEM data. // Requires that the center point be given in input spec: ossimGpt centerGpt; findCenterGpt(centerGpt); if (!centerGpt.hasNans()) { ossimElevManager::instance()->getHeightAboveEllipsoid(centerGpt); m_gsd.y = m_gsd.x = ossimElevManager::instance()->getMeanSpacingMeters(); if (m_gsd.x == 0) // getMeanSpacing unfortunately return 0 for unknown GSD m_gsd.makeNan(); } } if (!m_gsd.hasNans()) mapProj->setMetersPerPixel(m_gsd); } void ossimChipProcTool::initializeAOI() { // Nan rect for starters. m_aoiViewRect.makeNan(); m_aoiGroundRect.makeNan(); ossimString lookup; // Image size: ossimIpt imageSize(0,0); if (m_kwl.hasKey(AOI_SIZE_PIXELS_KW)) { lookup = m_kwl.findKey( AOI_SIZE_PIXELS_KW ); lookup.trim(); imageSize.x = lookup.before(" ").toUInt32(); imageSize.y = lookup.after(" ").toUInt32(); } // The AOI rect can be specified in different ways: if ( m_kwl.hasKey( AOI_GEO_CENTER_KW.c_str() ) ) { // A center point was given: ossimGpt centerGpt; findCenterGpt(centerGpt); // A center point spec can be accompanied by a width/height (in meters or pixels): ossimDpt sizeMeters; sizeMeters.makeNan(); if (m_kwl.hasKey(AOI_SIZE_METERS_KW)) { lookup = m_kwl.findKey( AOI_SIZE_METERS_KW ); lookup.trim(); sizeMeters.x = lookup.before(" ").toDouble(); sizeMeters.y = lookup.after(" ").toDouble(); } else if (m_kwl.hasKey(AOI_SIZE_PIXELS_KW)) { if ( (imageSize.x > 0)&& (imageSize.y > 0 ) ) { sizeMeters.x = imageSize.x*m_gsd.x; sizeMeters.y = imageSize.y*m_gsd.y; } } if (!sizeMeters.hasNans()) { ossimDpt metersPerDegree (centerGpt.metersPerDegree()); double dlat = sizeMeters.y/metersPerDegree.y/2.0; double dlon = sizeMeters.x/metersPerDegree.x/2.0; ossimGpt ulgpt (centerGpt.lat + dlat, centerGpt.lon - dlon); ossimGpt lrgpt (centerGpt.lat - dlat, centerGpt.lon + dlon); m_aoiGroundRect = ossimGrect(ulgpt, lrgpt); sizeMeters.x = imageSize.x*m_gsd.x; sizeMeters.y = imageSize.y*m_gsd.y; } if (!sizeMeters.hasNans()) { ossimDpt metersPerDegree (centerGpt.metersPerDegree()); double dlat = sizeMeters.y/metersPerDegree.y/2.0; double dlon = sizeMeters.x/metersPerDegree.x/2.0; ossimGpt ulgpt (centerGpt.lat + dlat, centerGpt.lon - dlon); ossimGpt lrgpt (centerGpt.lat - dlat, centerGpt.lon + dlon); m_aoiGroundRect = ossimGrect(ulgpt, lrgpt); m_needCutRect = true; } } else if ( m_kwl.hasKey( AOI_GEO_RECT_KW ) ) { ossimString lookup = m_kwl.findKey(AOI_GEO_RECT_KW); lookup.trim(); vector substrings = lookup.split(" "); if (substrings.size() != 4) { ostringstream errMsg; errMsg << "ossimChipProcUtil ["<<__LINE__<<"] Incorrect number of values specified for " "aoi_geo_rect!"; throw( ossimException(errMsg.str()) ); } ossim_float64 minLatF = substrings[0].toFloat64(); ossim_float64 minLonF = substrings[1].toFloat64(); ossim_float64 maxLatF = substrings[2].toFloat64(); ossim_float64 maxLonF = substrings[3].toFloat64(); // Check for swap so we don't get a negative height. // Note no swap check for longitude as box could cross date line. if ( minLatF > maxLatF ) { ossim_float64 tmpF = minLatF; minLatF = maxLatF; maxLatF = tmpF; } // Assume cut box is edge to edge or "Pixel Is Area". Our // AOI(area of interest) uses center of pixel or "Pixel Is Point" // so get the degrees per pixel and shift AOI to center. ossimGpt ulgpt (maxLatF, minLonF); ossimGpt lrgpt (minLatF , maxLonF); m_aoiGroundRect = ossimGrect(ulgpt, lrgpt); m_needCutRect = true; if ( (imageSize.x > 0) && (imageSize.y > 0) ) { ossimRefPtr mapProj = dynamic_cast(m_geom->getProjection()); if (mapProj.valid()) { ossimDpt gsd; gsd.x = std::fabs( maxLonF - minLonF ) / imageSize.x; gsd.y = std::fabs( maxLatF - minLatF ) / imageSize.y; mapProj->setDecimalDegreesPerPixel(gsd); } } } else if ( m_kwl.hasKey( AOI_MAP_RECT_KW ) ) { ossimRefPtr mapProj = dynamic_cast(m_geom->getProjection()); if (mapProj.valid()) { ossimString lookup = m_kwl.findKey(AOI_MAP_RECT_KW); lookup.trim(); vector substrings = lookup.split(", ", true); if (substrings.size() != 4) { ostringstream errMsg; errMsg << "ossimChipProcUtil ["<<__LINE__<<"] Incorrect number of values specified for " "aoi_geo_rect!"; throw( ossimException(errMsg.str()) ); } ossim_float64 minX = substrings[0].toFloat64(); ossim_float64 minY = substrings[1].toFloat64(); ossim_float64 maxX = substrings[2].toFloat64(); ossim_float64 maxY = substrings[3].toFloat64(); // Check for swap so we don't get a negative height. // Note no swap check for longitude as box could cross date line. if ( minX > maxX ) { ossim_float64 tmpF = minX; minX = maxX; maxX = tmpF; } if ( minY > maxY ) { ossim_float64 tmpF = minY; minY = maxY; maxY = tmpF; } ossimDpt ulMap (minX, maxY); ossimDpt lrMap (maxX , minY); ossimGpt ulGeo = mapProj->inverse(ulMap); ossimGpt lrGeo = mapProj->inverse(lrMap); m_aoiGroundRect = ossimGrect(ulGeo, lrGeo); m_needCutRect = true; if ( (imageSize.x > 0) && (imageSize.y > 0) ) { ossimRefPtr mapProj = dynamic_cast(m_geom->getProjection()); if (mapProj.valid()) { ossimDpt gsd; gsd.x = std::fabs( maxX - minX ) / imageSize.x; gsd.y = std::fabs( maxY - minY ) / imageSize.y; mapProj->setMetersPerPixel(gsd); } } } } // If no user defined rect set to scene bounding rect. if ( m_aoiGroundRect.hasNans() ) setAoiToInputs(); // If AOI established, we can set projection TP and origin if applicable: ossimRefPtr mapProj = dynamic_cast(m_geom->getProjection()); if (!m_aoiGroundRect.hasNans() && mapProj.valid()) { // Geo-scaled projection needs to know the reference latitude: if (m_geoScaled) { // The origin may have ben explicitly specified,or just use midpoint of AOI: ossimGpt origin; if (!getProjectionOrigin(origin)) origin = m_aoiGroundRect.midPoint(); mapProj->setOrigin(origin); m_geom->getMetersPerPixel(m_gsd); } // Set the tie-point of the projection to the AOI's UL. // Adjust it to be on an even pixel distance from projection origin if desired: mapProj->setUlTiePoints(m_aoiGroundRect.ul()); bool snapToTP = false; m_kwl.getBoolKeywordValue(snapToTP, SNAP_TIE_TO_ORIGIN_KW.c_str()); if ( snapToTP ) mapProj->snapTiePointToOrigin(); // Re-establish the AOI view rect based on updated projection: computeAdjustedViewFromGrect(); } } bool ossimChipProcTool::getProjectionOrigin(ossimGpt& gpt) { gpt = ossimGpt(0,0,0); bool found_spec = false; ossimString lookup = m_kwl.find(ossimKeywordNames::ORIGIN_LATITUDE_KW); if ( lookup.size() ) { gpt.lat = lookup.toFloat64(); if ( (gpt.lat < -90) || (gpt.lat > 90.0) ) { std::string errMsg = "origin latitude range error! Valid range: -90 to 90"; throw ossimException(errMsg); } m_geoScaled = true; found_spec = true; } lookup = m_kwl.find(ossimKeywordNames::CENTRAL_MERIDIAN_KW); if ( lookup.size() ) { gpt.lon = lookup.toFloat64(); if ( (gpt.lon < -180.0) || (gpt.lon > 180.0) ) { std::string errMsg = "central meridian range error! Valid range: -180 to 180"; throw ossimException(errMsg); } found_spec = true; } return found_spec; } void ossimChipProcTool::findCenterGpt(ossimGpt& gpt) { gpt.hgt = 0.0; ossimString lookup = m_kwl.findKey( AOI_GEO_CENTER_KW ); if (lookup.size()) { lookup.trim(); vector substrings = lookup.split(", "); if (substrings.size() != 2) { ostringstream errMsg; errMsg << "ossimChipProcUtil ["<<__LINE__<<"] Incorrect number of values specified for " "aoi_geo_center!"; throw( ossimException(errMsg.str()) ); } gpt.lat = substrings[0].toDouble(); gpt.lon = substrings[1].toDouble(); return; } lookup = m_kwl.findKey(AOI_GEO_RECT_KW); if (lookup.size()) { lookup.trim(); vector substrings = lookup.split(", "); if (substrings.size() != 4) { ostringstream errMsg; errMsg << "ossimChipProcUtil ["<<__LINE__<<"] Incorrect number of values specified for " "aoi_geo_rect!"; throw( ossimException(errMsg.str()) ); } ossim_float64 minLatF = substrings[0].toDouble(); ossim_float64 minLonF = substrings[1].toDouble(); ossim_float64 maxLatF = substrings[2].toDouble(); ossim_float64 maxLonF = substrings[3].toDouble(); gpt.lat = 0.5*(minLatF + maxLatF); gpt.lon = 0.5*(minLonF + maxLonF); return; } gpt.makeNan(); } void ossimChipProcTool::setAoiToInputs() { ossimRefPtr geom; ossimGrect bbox_i; m_aoiGroundRect.makeNan(); // Assign the AOI to be the bounding rect of the union of all inputs. Start with image inputs: std::vector< ossimRefPtr >::iterator chain = m_imgLayers.begin(); while (chain != m_imgLayers.end()) { geom = (*chain)->getImageGeometry(); if (geom.valid()) { geom->getBoundingGroundRect(bbox_i); if (!bbox_i.hasNans()) { if (m_aoiGroundRect.hasNans()) m_aoiGroundRect = bbox_i; else m_aoiGroundRect.expandToInclude(bbox_i); } } ++chain; } // Now determine DEM inputs coverage: ossimGrect bbox_dems; bbox_dems.makeNan(); std::vector::iterator dem_file = m_demSources.begin(); while (dem_file != m_demSources.end()) { ossimRefPtr geom = new ossimImageGeometry; if (!geom->open(*dem_file)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimHLZUtil::initialize ERR: Cannot open DEM file <" << *dem_file << "> " "as image handler. Ignoring entry for bounding box computation.\n" << std::endl; } geom->getBoundingGroundRect(bbox_i); if (!bbox_i.hasNans()) { if (bbox_dems.hasNans()) bbox_dems = bbox_i; else bbox_dems.expandToInclude(bbox_i); } ++dem_file; } // Finally compute the AOI as the intersection of the image and DEM inputs: if (m_aoiGroundRect.hasNans()) m_aoiGroundRect = bbox_dems; else if (!bbox_dems.hasNans()) m_aoiGroundRect = m_aoiGroundRect.clipToRect(bbox_dems); } void ossimChipProcTool::computeAdjustedViewFromGrect() { // Nan rect for starters. m_aoiViewRect.makeNan(); if (m_aoiGroundRect.hasNans()) return; // Assume cut box is edge to edge or "Pixel Is Area". Our // AOI(area of interest) uses center of pixel or "Pixel Is Point" // so get the degrees per pixel and shift AOI to center. ossimDpt halfDpp; m_geom->getDegreesPerPixel( halfDpp ); halfDpp = halfDpp/2.0; ossimGpt gpt(0.0, 0.0, 0.0); ossimDpt ulPt; ossimDpt lrPt; // Upper left: gpt.lat = m_aoiGroundRect.ul().lat - halfDpp.y; gpt.lon = m_aoiGroundRect.ul().lon + halfDpp.x; m_geom->worldToLocal(gpt, ulPt); // Lower right: gpt.lat = m_aoiGroundRect.lr().lat + halfDpp.y; gpt.lon = m_aoiGroundRect.lr().lon - halfDpp.x; m_geom->worldToLocal(gpt, lrPt); m_aoiViewRect = ossimIrect( ossimIpt(ulPt), ossimIpt(lrPt) ); // If no user defined rect set to scene bounding rect. if ( m_aoiViewRect.hasNans() ) m_aoiViewRect = m_procChain->getBoundingRect(0); } void ossimChipProcTool::propagateGeometryToChains() { // we need to make sure the outputs are refreshed so they can reset themselves // Needed when we are doing interactive update to the GSD and clip window ossimRefPtr refreshEvent = new ossimRefreshEvent(); ossimEventVisitor eventVisitor(refreshEvent.get()); ossimViewInterfaceVisitor viewVisitor(m_geom.get()); std::vector< ossimRefPtr >::iterator chainIdx = m_imgLayers.begin(); while ( chainIdx != m_imgLayers.end() ) { viewVisitor.reset(); eventVisitor.reset(); (*chainIdx)->accept(viewVisitor); (*chainIdx)->accept(eventVisitor); ossimRefPtr resampler = (*chainIdx)->getImageRenderer(); if (resampler.valid()) { resampler->setView( m_geom.get() ); resampler->propagateEventToOutputs(*refreshEvent); } ++chainIdx; } } void ossimChipProcTool::setReaderProps( ossimImageHandler* ih ) const { if ( ih ) { ossim_uint32 count = m_kwl.numberOf( READER_PROPERTY_KW.c_str() ); for (ossim_uint32 i = 0; i < count; ++i) { ossimString key = READER_PROPERTY_KW; key += ossimString::toString(i); ossimString value = m_kwl.findKey( key.string() ); if ( value.size() ) { std::vector splitArray; value.split(splitArray, "="); if(splitArray.size() == 2) { ossimRefPtr prop = new ossimStringProperty(splitArray[0], splitArray[1]); ih->setProperty( prop ); } } } } } void ossimChipProcTool::getBandList(ossim_uint32 image_idx, std::vector& bandList ) const { bandList.clear(); ostringstream key; key << ossimKeywordNames::IMAGE_FILE_KW << image_idx << "." << ossimKeywordNames::BANDS_KW; ossimString os = m_kwl.findKey(key.str()); if (os.empty()) { // Look for possible global bands selection: os = m_kwl.find(ossimKeywordNames::BANDS_KW); } if ( os.size() ) { std::vector band_list(0); os.split( band_list, ossimString(", "), false ); if ( band_list.size() ) { std::vector::const_iterator i = band_list.begin(); while ( i != band_list.end() ) { ossim_uint32 band = (*i).toUInt32(); if ( band ) // One based so we need to subtract. { bandList.push_back( band - 1 ); } ++i; } } } } // End: ossimChipProcUtil::getBandList ossimRefPtr ossimChipProcTool::mosaicDemSources() { ostringstream xmsg; ossimRefPtr demMosaic = 0; if (m_demSources.empty()) { // Establish connection to DEM posts directly as raster "images" versus using the OSSIM elev // manager that performs interpolation of DEM posts for arbitrary locations. These elev images // feed into a combiner in order to have a common tap for elev pixels: ossimElevManager* elevMgr = ossimElevManager::instance(); elevMgr->getCellsForBounds(m_aoiGroundRect, m_demSources); } // Open a raster image for each elevation source being considered: ossimConnectableObject::ConnectableObjectList elevChains; vector::iterator fname_iter = m_demSources.begin(); while (fname_iter != m_demSources.end()) { ossimRefPtr chain = createInputChain(*fname_iter).get(); if (!chain.valid() || !chain->getImageRenderer().valid() ) { xmsg<<"ossimChipProcUtil:"<<__LINE__<<" Cannot open DEM file at <"<<*fname_iter<<">"; throw(xmsg.str()); } // Set up the input chain with proper renderer IVT: ossimRefPtr ivt = new ossimImageViewProjectionTransform (chain->getImageHandler()->getImageGeometry().get(), m_geom.get()); chain->getImageRenderer()->setImageViewTransform(ivt.get()); ossimRefPtr connectable = chain.get(); elevChains.push_back(connectable); ++fname_iter; } if (elevChains.size() == 1) demMosaic = (ossimImageSource*) elevChains[0].get(); else demMosaic = new ossimImageMosaic(elevChains); return demMosaic; } ossimRefPtr ossimChipProcTool::combineLayers(std::vector< ossimRefPtr >& layers) const { ossimRefPtr combiner = 0; ossim_uint32 layerCount = (ossim_uint32) layers.size(); if ( layerCount == 1 ) { combiner = layers[0].get(); } else if (layerCount > 1) { combiner = new ossimImageMosaic; std::vector< ossimRefPtr >::iterator chainIdx = layers.begin(); while ( chainIdx != layers.end() ) { combiner->connectMyInputTo( (*chainIdx).get() ); ++chainIdx; } } return combiner; } ossimRefPtr ossimChipProcTool::newWriter() { ossimRefPtr writer = 0; ossimString lookup = m_kwl.findKey( WRITER_KW ); if ( lookup.size() ) { writer = ossimImageWriterFactoryRegistry::instance()->createWriter( lookup ); if ( !writer.valid() ) { ostringstream errMsg; errMsg << "ossimChipProcUtil ["<<__LINE__<<"] ERROR creating writer for <"<" < createWriterFromExtension( m_productFilename.ext() ); if ( !writer.valid() ) { ostringstream errMsg; errMsg << "ossimChipProcUtil ["<<__LINE__<<"] ERROR creating writer from extension <" <"<setFilename( m_productFilename ); // Add any writer props. ossim_uint32 count = m_kwl.numberOf( WRITER_PROPERTY_KW.c_str() ); for (ossim_uint32 i = 0; i < count; ++i) { ossimString key = WRITER_PROPERTY_KW; key += ossimString::toString(i); lookup = m_kwl.findKey( key.string() ); if ( lookup.size() ) { std::vector splitArray; lookup.split(splitArray, "="); if(splitArray.size() == 2) { ossimRefPtr prop = new ossimStringProperty(splitArray[0], splitArray[1]); writer->setProperty( prop ); } } } // Output tile size: lookup = m_kwl.findKey( TILE_SIZE_KW ); if ( lookup.size() ) { ossimIpt tileSize; tileSize.x = lookup.toInt32(); if ( (tileSize.x % 16) == 0 ) { tileSize.y = tileSize.x; writer->setTileSize( tileSize ); } } return writer; } void ossimChipProcTool::setUsage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); // Set app name. std::string appName = ap.getApplicationName(); ossimApplicationUsage* au = ap.getApplicationUsage(); // Base class has some: ossimTool::setUsage(ap); // Add options. au->addCommandLineOption("--aoi-geo-bbox", " \nSpecify a comma-separated list for the lower-left and upper-right corners of the scene rect in decimal degrees."); au->addCommandLineOption("--aoi-geo-center", " \nCenter of AOI in decimal degrees."); au->addCommandLineOption("--aoi-map-bbox", " \nSpecify a space-separated list for the upper-left and lower-right corners of the scene rect in decimal degrees."); au->addCommandLineOption("--aoi-map-center", " \nCenter of AOI in map coordinates."); au->addCommandLineOption("--aoi-size-pixels", " ,\nSize of AOI in output product pixels."); au->addCommandLineOption("--aoi-size-meters", " ,\nSize of AOI in meters."); au->addCommandLineOption( "-b or --bands ", "Use the specified bands in given order: e.g. \"3,2,1\" will select bands 3, 2 and 1 of the input image.\nNote: it is 1 based" ); au->addCommandLineOption("--central-meridian","\nNote if set this will be used for the central meridian of the projection. This can be used to lock the utm zone."); au->addCommandLineOption("--color-table | --lut","\nKeyword list containing color table for color-relief option."); au->addCommandLineOption("--deg-per-pixel"," | \nSpecifies an override for degrees per pixel. Takes either a single value applied equally to x and y directions, or two values applied correspondingly to x then y. This option takes precedence over the \"--meters\" option."); au->addCommandLineOption("--dem", "[,...]\n Input DEM file(s) (comma-separated) to process."); au->addCommandLineOption("--dump-options","The current state of the utility (after the entire command line is parsed) is written to the file $PWD/.kwl, where is the name of the operation being performed. See \"--load-options\"."); au->addCommandLineOption("-e or --entry", " For multi image handlers which entry do you wish to extract. For list of entries use: \"ossim-info -i \" "); au->addCommandLineOption("--gsd", "\nSpecifies an override for the meters per pixel"); au->addCommandLineOption("-h or --help", "Display this help and exit."); au->addCommandLineOption("--hemisphere", "\nSpecify a projection hemisphere if supported. E.g. UTM projection. This will lock the hemisphere even if input scene center is the other hemisphere. Valid values for UTM are \"N\" and \"S\""); au->addCommandLineOption("--image | -i", "[, ...] Input image file(s) (comma-separated) to process."); au->addCommandLineOption("--load-options","[]\nThe contents of (keyword-value pairs) are loaded as command options. The command-line options take precedence. See \"--load-options\" and \"--write-template\" options."); au->addCommandLineOption("--output-file | -o","\nThe product output file name. The format is dictated by the extension."); au->addCommandLineOption("--origin-latitude","\nNote if set this will be used for the origin latitude of the projection. Setting this to something other than 0.0 with a geographic projection creates a scaled geographic projection."); au->addCommandLineOption("--output-radiometry", "\nSpecifies the desired product's pixel radiometry type. Possible values for are: U8, U11, U16, S16, F32. Note this overrides the deprecated option \"scale-to-8-bit\"."); au->addCommandLineOption("--projection", " Valid projections: geo, geo-scaled, input or utm\ngeo = Equidistant Cylindrical, origin latitude = 0.0\ngeo-scaled = Equidistant Cylindrical, origin latitude = image center\ninput Use first images projection. Must be a map projecion.\nutm = Universal Tranverse Mercator\nIf input and multiple sources the projection of the first image will be used.\nIf utm the zone will be set from the scene center of first image.\nNOTE: --srs takes precedence over this option."); au->addCommandLineOption("--reader-prop", "Adds a property to send to the reader. format is name=value"); au->addCommandLineOption("--scale-to-8-bit", "Scales the output to unsigned eight bits per band. This option has been deprecated by the newer \"--output-radiometry\" option."); au->addCommandLineOption("--snap-tie-to-origin", "Snaps tie point to projection origin so that (tie-origin)/gsd come out on an even integer boundary."); au->addCommandLineOption("--srs","\nSpecify a spatial reference system(srs) code for the output projection. Example: --srs EPSG:4326"); au->addCommandLineOption("-t or --thumbnail", "\nSpecify a thumbnail resolution.\nScale will be adjusted so the maximum dimension = argument given."); au->addCommandLineOption("--tile-size", "\nSets the output tile size if supported by writer. Notes: This sets both dimensions. Must be a multiple of 16, e.g. 1024."); au->addCommandLineOption("-w or --writer","\nSpecifies the output writer. Default uses output file extension to determine writer. For valid output writer types use: \"ossim-info --writers\"\n"); au->addCommandLineOption("--writer-prop", "\nPasses a name=value pair to the writer for setting it's property. Any number of these can appear on the line."); au->addCommandLineOption("--write-template", "\nWrites a keywrd list template to the filename specified."); au->addCommandLineOption("--zone", "\nSpecify a projection zone if supported. E.g. UTM projection. This will lock the zone even if input scene center is in another zone. Valid values for UTM are \"1\" to \"60\""); } ossim-Miami-2.9.1/src/util/ossimChipperUtil.cpp000066400000000000000000005663501352751253100215050ustar00rootroot00000000000000//--- // // File: ossimChipperUtil.cpp // // License: MIT // // Author: David Burken // // Description: Utility class definition processing digital elevation // models(dems). // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimChipperUtil:debug"); static ossimTrace traceLog("ossimChipperUtil:log"); static ossimTrace traceOptions("ossimChipperUtil:options"); static const std::string BRIGHTNESS_KW = "brightness"; static const std::string COLOR_BLUE_KW = "color_blue"; static const std::string COLOR_GREEN_KW = "color_green"; static const std::string COLOR_RED_KW = "color_red"; static const std::string CONTRAST_KW = "contrast"; static const std::string CLIP_WMS_BBOX_LL_KW = "clip_wms_bbox_ll"; static const std::string CLIP_POLY_LAT_LON_KW = "clip_poly_lat_lon"; static const std::string CUT_BBOX_XYWH_KW = "cut_bbox_xywh"; static const std::string CUT_WMS_BBOX_KW = "cut_wms_bbox"; static const std::string CUT_WMS_BBOX_LL_KW = "cut_wms_bbox_ll"; static const std::string CUT_CENTER_LAT_KW = "cut_center_lat"; static const std::string CUT_CENTER_LON_KW = "cut_center_lon"; static const std::string CUT_RADIUS_KW = "cut_radius"; // meters static const std::string CUT_HEIGHT_KW = "cut_height"; // pixels static const std::string CUT_MAX_LAT_KW = "cut_max_lat"; static const std::string CUT_MAX_LON_KW = "cut_max_lon"; static const std::string CUT_MIN_LAT_KW = "cut_min_lat"; static const std::string CUT_MIN_LON_KW = "cut_min_lon"; static const std::string CUT_WIDTH_KW = "cut_width"; // pixels static const std::string DEM_KW = "dem"; static const std::string GAIN_KW = "gain"; static const std::string GAMMA_KW = "gamma"; static const std::string FILE_KW = "file"; static const std::string FULLRES_XYS_KW = "fullres_xys"; static const std::string HIST_AOI_KW = "hist_aoi"; static const std::string HIST_CENTER_KW = "hist_center"; static const std::string HIST_LLWH_KW = "hist_llwh"; static const std::string HIST_OP_KW = "hist_op"; static const std::string HIST_LINEAR_CLIP_KW = "hist_linear_clip"; static const std::string HIST_LINEAR_NORM_CLIP_KW = "hist_linear_norm_clip"; static const std::string HIST_CENTER_CLIP_KW = "hist_center_clip"; static const std::string HIST_BIAS_FACTOR_KW = "hist_bias_factor"; static const std::string IMAGE_SPACE_SCALE_X_KW = "image_space_scale_x"; static const std::string IMAGE_SPACE_SCALE_Y_KW = "image_space_scale_y"; static const std::string IMG_KW = "image"; static const std::string LUT_FILE_KW = "lut_file"; static const std::string DEGREES_X_KW = "degrees_x"; static const std::string DEGREES_Y_KW = "degrees_y"; static const std::string METERS_KW = "meters"; static const std::string NORTH_UP_KW = "north_up"; // bool static const std::string OP_KW = "operation"; static const std::string OUTPUT_RADIOMETRY_KW = "output_radiometry"; static const std::string PAD_THUMBNAIL_KW = "pad_thumbnail"; // bool static const std::string READER_PROPERTY_KW = "reader_property"; static const std::string RESAMPLER_FILTER_KW = "resampler_filter"; static const std::string ROTATION_KW = "rotation"; static const std::string ROTATE_TO_INPUT = "rotate_to_input"; static const std::string RRDS_KW = "rrds"; static const std::string SCALE_2_8_BIT_KW = "scale_2_8_bit"; static const std::string SHARPEN_MODE_KW = "sharpen_mode"; static const std::string SHARPEN_PERCENT_KW = "sharpen_percent"; static const std::string SNAP_TIE_TO_ORIGIN_KW = "snap_tie_to_origin"; static const std::string SRC_FILE_KW = "src_file"; static const std::string SRS_KW = "srs"; static const std::string THREE_BAND_OUT_KW = "three_band_out"; // bool static const std::string THUMBNAIL_RESOLUTION_KW = "thumbnail_resolution"; // pixels static const std::string TILE_SIZE_KW = "tile_size"; // pixels static const std::string TRUE_KW = "true"; static const std::string UP_IS_UP_KW = "up_is_up"; // bool static const std::string WRITER_KW = "writer"; static const std::string WRITER_PROPERTY_KW = "writer_property"; static const std::string COMBINER_TYPE_KW = "combiner_type"; static const std::string NULL_PIXEL_FLIP_KW = "null_pixel_flip"; static const std::string TWOCMV_OLD_INPUT_BAND_KW = "2cmv_old_input_band"; static const std::string TWOCMV_NEW_INPUT_BAND_KW = "2cmv_new_input_band"; static const std::string TWOCMV_RED_OUTPUT_SOURCE_KW = "2cmv_red_output_source"; static const std::string TWOCMV_GREEN_OUTPUT_SOURCE_KW = "2cmv_green_output_source"; static const std::string TWOCMV_BLUE_OUTPUT_SOURCE_KW = "2cmv_blue_output_source"; ossimChipperUtil::ossimChipperUtil() : ossimReferenced(), m_operation(OSSIM_CHIPPER_OP_UNKNOWN), m_kwl(new ossimKeywordlist()), m_srcKwl(0), m_geom(0), m_ivt(0), m_demLayer(0), m_imgLayer(0), m_viewPortStretchEnabled(false) { // traceDebug.setTraceFlag(true); m_kwl->setExpandEnvVarsFlag(true); } // Private/hidden from use. ossimChipperUtil::ossimChipperUtil(const ossimChipperUtil & /* obj */) : m_operation(OSSIM_CHIPPER_OP_UNKNOWN) { } // Private/hidden from use. const ossimChipperUtil &ossimChipperUtil::operator=(const ossimChipperUtil & /* rhs */) { return *this; } ossimRefPtr ossimChipperUtil::createCombiner() const { ossimRefPtr result; ossimString combinerType = m_kwl->find(COMBINER_TYPE_KW.c_str()); if (combinerType.empty()) { combinerType = "ossimImageMosaic"; } result = ossimImageSourceFactoryRegistry::instance()->createImageSource(combinerType); if (!result.valid()) { result = new ossimImageMosaic(); } return result; } ossimChipperUtil::~ossimChipperUtil() { clear(); } void ossimChipperUtil::addArguments(ossimArgumentParser &ap) { ossimString usageString = ap.getApplicationName(); usageString += " [option]... [input-option]... \nNote at least one input is required either from one of the input options, e.g. --input-dem or adding to command line in front of the output file in which case the code will try to ascertain what type of input it is.\n\nAvailable traces:\n-T \"ossimChipperUtil:debug\" - General debug trace to standard out.\n-T \"ossimChipperUtil:log\" - Writes a log file to output-file.log.\n-T \"ossimChipperUtil:options\" - Writes the options to output-file-options.kwl."; ossimApplicationUsage *au = ap.getApplicationUsage(); au->setCommandLineUsage(usageString); au->setDescription(ap.getApplicationName() + " Utility application for generating elevation products from dem data."); au->addCommandLineOption("--azimuth", "\nhillshade option - Light source azimuth angle for bump shade.\nRange: 0 to 360, Default = 180.0"); au->addCommandLineOption("-b or --bands ", "Use the specified bands in given order: e.g. \"3,2,1\" will select bands 3, 2 and 1 of the input image.\nNote: it is 1 based"); au->addCommandLineOption("--brightness", "\nApply brightness to input image(s). Valid range: -1.0 to 1.0"); au->addCommandLineOption("--central-meridian", "\nNote if set this will be used for the central meridian of the projection. This can be used to lock the utm zone."); au->addCommandLineOption("--color", " \nhillshade option - Set the red, green and blue color values to be used with hillshade.\nThis option can be used with or without an image source for color.\nRange 0 to 255, Default r=255, g=255, b=255"); au->addCommandLineOption("--color-table", "\nhillshade or color-relief option - Keyword list containing color table for color-relief option."); au->addCommandLineOption("--contrast", "\nApply contrast to input image(s). Valid range: -1.0 to 1.0"); au->addCommandLineOption("--cut-bbox-xywh", ",,,\nSpecify a comma separated bounding box."); au->addCommandLineOption("--cut-wms-bbox", ",,,\nSpecify a comma separated list in the format of a WMS BBOX.\nThe units are in the units of the projector defined by the --srs key"); au->addCommandLineOption("--cut-wms-bbox-ll", ",,,\nSpecify a comma separated list in the format of a WMS BBOX.\nThe units are always decimal degrees"); au->addCommandLineOption("--cut-width", "\nSpecify the cut width in pixel"); au->addCommandLineOption("--cut-height", "\nSpecify the cut height in pixel"); au->addCommandLineOption("--clip-wms-bbox-ll", ",,,\nSpecify a comma separated list in the format of a WMS BBOX.\nThe units are always decimal degrees"); au->addCommandLineOption("--clip-poly-lat-lon", "Polygon in the form of a string: (lat,lon),(lat,lon),...(lat,lon)"); au->addCommandLineOption("--cut-bbox-ll", " \nSpecify a bounding box with the minimum latitude/longitude and max latitude/longitude in decimal degrees.\nNote coordinates are edge to edge."); au->addCommandLineOption("--cut-bbox-llwh", " \nSpecify a bounding box with the minimum latitude/longitude, max latitude/longitude in decimal degrees and width/height in pixels.\nNote coordinates are edge to edge."); au->addCommandLineOption("--cut-center-llwh", " \nSpecify the center cut in latitude longitude space with width and height in pixels."); au->addCommandLineOption("--cut-center-llr", " \nSpecify the center cut in latitude longitude space with radius in meters."); au->addCommandLineOption("--degrees", " | \nSpecifies an override for degrees per pixel. Takes either a single value applied equally to x and y directions, or two values applied correspondingly to x then y. This option takes precedence over the \"--meters\" option."); au->addCommandLineOption("--enable-null-pixel-flip", "Will add to the start of the chain and will flip interior pixels that are null to valid."); au->addCommandLineOption("--elevation", "\nhillshade option - Light source elevation angle for bumb shade.\nRange: 0 to 90, Default = 45.0"); au->addCommandLineOption("-e or --entry", " For multi image handlers which entry do you wish to extract. For list of entries use: \"ossim-info -i \" "); au->addCommandLineOption("--exaggeration", "\nMultiplier for elevation values when computing surface normals. Has the effect of lengthening shadows for oblique lighting.\nRange: .0001 to 50000, Default = 1.0"); au->addCommandLineOption("--fullres-xys", ",,[,]\nSpecify a full resolution x,y point (Used as pivot and center cut) and scale, comma separated with no spaces. If two scales are specified then first is x and second is y else x and y are set to equal scales"); au->addCommandLineOption("--gamma", "Good ranges are between .1 and 6. Probably try about .7, A value of 1 will not apply anything"); au->addCommandLineOption("-h or --help", "Display this help and exit."); au->addCommandLineOption("--hemisphere", "\nSpecify a projection hemisphere if supported. E.g. UTM projection. This will lock the hemisphere even if input scene center is the other hemisphere. Valid values for UTM are \"N\" and \"S\""); au->addCommandLineOption("--histogram-aoi", ",,,\nSets single image region of interest(roi) to compute histogram from. Coordinates are zero based image space. Single image operation only. Comma separated, no spaces."); au->addCommandLineOption("--histogram-center-tile", "Will compute histogram from center tile of image."); au->addCommandLineOption("--histogram-llwh", ",,,\nSpecify the region of interest(roi) to compute histogram from. Latitude and longitude will be roi center space with width and height in pixels. Comma separated, no spaces."); au->addCommandLineOption("--histogram-op", "\nHistogram operation to perform. Valid operations are \"linear\" \"auto-minmax\", \"auto-percentile\", \"std-stretch-1\", \"std-stretch-2\" and \"std-stretch-3\"."); au->addCommandLineOption("--histogram-linear-clip", ", in actual DN value. If it's 8 bit then it will be values between 0 and 255"); au->addCommandLineOption("--histogram-linear-norm-clip", ", normalized value that range from 0 to 1. Example .2,.85"); au->addCommandLineOption("--histogram-center-clip", "

normalized value that range from 0 to 1. Default is 0.5 which is the center of the min max clip points."); au->addCommandLineOption("--histogram-bias-factor", " values are typically between 0 to 2. Allows small adjustments to the auto clip points. Currently only works for auto min max."); au->addCommandLineOption("--image-space-scale", " \nSpecifies an image space scale for x and y direction. \"chip\" operation only."); au->addCommandLineOption("--input-dem", " Input dem to process."); au->addCommandLineOption("--input-img", " Input image to process."); au->addCommandLineOption("--input-src", " Input source file list keyword list with list of dems or images or both to process."); au->addCommandLineOption("--meters", "\nSpecifies an override for the meters per pixel"); au->addCommandLineOption("-n or --north-up", "Rotates image North up. \"chip\" operation only."); au->addCommandLineOption("--op", "\nOperation to perform. Valid operations are \"chip\", \"color-relief\", \"hillshade\", \"psm\"(pan sharpened multispectral), \"2cmv\"(two color multi view) and \"ortho\".\nchip = input projection = output projection(image space), single image operation only."); au->addCommandLineOption("--options", " This can be all or part of the application options. To get a template you can turn on trace to the ossimChipperUtil class by adding \"-T ossimChipperUtil\" to your command."); au->addCommandLineOption("--origin-latitude", "\nNote if set this will be used for the origin latitude of the projection. Setting this to something other than 0.0 with a geographic projection creates a scaled geographic projection."); au->addCommandLineOption("--output-radiometry", "\nSpecifies the desired product's pixel radiometry type. Possible values for are: U8, U11, U16, S16, F32. Note this overrides the deprecated option \"scale-to-8-bit\"."); au->addCommandLineOption("--pad-thumbnail", "\nIf true, output thumbnail dimensions will be padded in width or height to make square; else, it will have the aspect ratio of input, Default=false"); au->addCommandLineOption("--projection", " Valid projections: geo, geo-scaled, input or utm\ngeo = Equidistant Cylindrical, origin latitude = 0.0\ngeo-scaled = Equidistant Cylindrical, origin latitude = image center\ninput Use first images projection. Must be a map projecion.\nutm = Universal Tranverse Mercator\nIf input and multiple sources the projection of the first image will be used.\nIf utm the zone will be set from the scene center of first image.\nNOTE: --srs takes precedence over this option."); au->addCommandLineOption("--resample-filter", "\nSpecify what resampler filter to use, e.g. nearest neighbor, bilinear, cubic, sinc.\nSee ossim-info --resampler-filters"); au->addCommandLineOption("-r or --rotate", "\nRotate image by degrees. \"chip\" operation only."); au->addCommandLineOption("--reader-prop", "Adds a property to send to the reader. format is name=value"); au->addCommandLineOption("--rotate-to-input", "\nOnly if the operation is \"ortho\", output a rotated map so that the top edge is oriented with the input image top edge. Only available for single-image products in GeoTIFF output format."); au->addCommandLineOption("--rrds", " Reduced resolution data set where 0 is full resolution. \"chip\" operation only."); au->addCommandLineOption("--scale-to-8-bit", "Scales the output to unsigned eight bits per band. This option has been deprecated by the newer \"--output-radiometry\" option."); au->addCommandLineOption("--sharpen-mode", " Applies sharpness to image chain(s). Valid modes: \"light\", \"medium\",\"heavy\""); au->addCommandLineOption("--sharpen-percent", " Applies sharpness to image chain(s). Valid percentage is between 0 and 1"); au->addCommandLineOption("--snap-tie-to-origin", "Snaps tie point to projection origin so that (tie-origin)/gsd come out on an even integer boundary."); au->addCommandLineOption("--srs", "\nSpecify a spatial reference system(srs) code for the output projection. Example: --srs EPSG:4326"); au->addCommandLineOption("-t or --thumbnail", "\nSpecify a thumbnail resolution.\nScale will be adjusted so the maximum dimension = argument given."); au->addCommandLineOption("--three-band-out", "Force three band output even if input is not. Attempts to map bands to RGB if possible."); au->addCommandLineOption("--tile-size", "\nSets the output tile size if supported by writer. Notes: This sets both dimensions. Must be a multiple of 16, e.g. 1024."); au->addCommandLineOption("-u or --up-is-up", "Rotates image to up is up. \"chip\" operation only."); au->addCommandLineOption("-w or --writer", "\nSpecifies the output writer. Default uses output file extension to determine writer. For valid output writer types use: \"ossim-info --writers\"\n"); au->addCommandLineOption("--writer-prop", "\nPasses a name=value pair to the writer for setting it's property. Any number of these can appear on the line."); au->addCommandLineOption("--zone", "\nSpecify a projection zone if supported. E.g. UTM projection. This will lock the zone even if input scene center is in another zone. Valid values for UTM are \"1\" to \"60\""); au->addCommandLineOption("--2cmv-old-input-band", "\nBand to use for two color multi view old input.\n"); au->addCommandLineOption("--2cmv-new-input-band", "\nBand to use for two color multi view new input.\n"); au->addCommandLineOption("--2cmv-red-output-source", "\nTwo color multi view source input for red output. Either, old, new, or mp(min pix). Default=old.\n"); au->addCommandLineOption("--2cmv-green-output-source", "\nTwo color multi view source input for green output. Either, old, new, or mp(min pix). Default=new.\n"); au->addCommandLineOption("--2cmv-blue-output-source", "\nTwo color multi view source input for blue output. Either, old, new, or mp(min pix). Default=new.\n"); au->addCommandLineOption("--combiner-type", "\nossimBlendMosaic, ossimFeatherMosaic, ossimImageMosaic. Default: ossimImageMosaic. Example --combiner-type ossimImageMosaic\n"); } // End: ossimChipperUtil::addArguments void ossimChipperUtil::clear() { // Must disonnect chains so that they destroy. std::vector>::iterator i = m_imgLayer.begin(); while (i != m_imgLayer.end()) { (*i)->disconnect(); (*i) = 0; ++i; } m_imgLayer.clear(); i = m_demLayer.begin(); while (i != m_demLayer.end()) { (*i)->disconnect(); (*i) = 0; ++i; } m_demLayer.clear(); if (m_writer.valid()) { m_writer->disconnect(); m_writer = 0; } } bool ossimChipperUtil::initialize(ossimArgumentParser &ap) { static const char MODULE[] = "ossimChipperUtil::initialize(ossimArgumentParser&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } clear(); if (ap.read("-h") || ap.read("--help") || (ap.argc() == 1)) { usage(ap); return false; // Indicates process should be terminated to caller. } // Start with clean options keyword list. m_kwl->clear(); std::string tempString1; ossimArgumentParser::ossimParameter stringParam1(tempString1); std::string tempString2; ossimArgumentParser::ossimParameter stringParam2(tempString2); std::string tempString3; ossimArgumentParser::ossimParameter stringParam3(tempString3); std::string tempString4; ossimArgumentParser::ossimParameter stringParam4(tempString4); std::string tempString5; ossimArgumentParser::ossimParameter stringParam5(tempString5); std::string tempString6; ossimArgumentParser::ossimParameter stringParam6(tempString6); double tempDouble1; ossimArgumentParser::ossimParameter doubleParam1(tempDouble1); double tempDouble2; ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); ossim_uint32 demIdx = 0; ossim_uint32 imgIdx = 0; ossim_uint32 readerPropIdx = 0; ossim_uint32 writerPropIdx = 0; ossimString key = ""; // Extract optional arguments and stuff them in a keyword list. if (ap.read("--azimuth", stringParam1)) { m_kwl->addPair(std::string(ossimKeywordNames::AZIMUTH_ANGLE_KW), tempString1); } if (ap.read("-b", stringParam1) || ap.read("--bands", stringParam1)) { m_kwl->addPair(std::string(ossimKeywordNames::BANDS_KW), tempString1); } if (ap.read("--brightness", stringParam1)) { m_kwl->addPair(BRIGHTNESS_KW, tempString1); } if (ap.read("--central-meridian", stringParam1)) { m_kwl->addPair(std::string(ossimKeywordNames::CENTRAL_MERIDIAN_KW), tempString1); } if (ap.read("--color", stringParam1, stringParam2, stringParam3)) { m_kwl->addPair(COLOR_RED_KW, tempString1); m_kwl->addPair(COLOR_GREEN_KW, tempString2); m_kwl->addPair(COLOR_BLUE_KW, tempString3); } if (ap.read("--color-table", stringParam1)) { m_kwl->addPair(LUT_FILE_KW, tempString1); } if (ap.read("--contrast", stringParam1)) { m_kwl->addPair(CONTRAST_KW, tempString1); } if (ap.read("--cut-width", stringParam1)) { m_kwl->addPair(CUT_WIDTH_KW, tempString1); } if (ap.read("--cut-height", stringParam1)) { m_kwl->addPair(CUT_HEIGHT_KW, tempString1); } if (ap.read("--cut-bbox-xywh", stringParam1)) { m_kwl->addPair(CUT_BBOX_XYWH_KW, tempString1); } if (ap.read("--cut-wms-bbox", stringParam1)) { m_kwl->addPair(CUT_WMS_BBOX_KW, tempString1); } if (ap.read("--cut-wms-bbox-ll", stringParam1)) { m_kwl->addPair(CUT_WMS_BBOX_LL_KW, tempString1); } if (ap.read("--clip-wms-bbox-ll", stringParam1)) { m_kwl->addPair(CLIP_WMS_BBOX_LL_KW, tempString1); } if (ap.read("--clip-poly-lat-lon", stringParam1)) { //std::vector result; //ossim::toVector(result, ossimString(tempString1)); //std::cout << result[0] << std::endl; //std::cout <addPair(CLIP_POLY_LAT_LON_KW, tempString1); } if (ap.read("--cut-bbox-ll", stringParam1, stringParam2, stringParam3, stringParam4)) { m_kwl->addPair(CUT_MIN_LAT_KW, tempString1); m_kwl->addPair(CUT_MIN_LON_KW, tempString2); m_kwl->addPair(CUT_MAX_LAT_KW, tempString3); m_kwl->addPair(CUT_MAX_LON_KW, tempString4); } if (ap.read("--cut-bbox-llwh", stringParam1, stringParam2, stringParam3, stringParam4, stringParam5, stringParam6)) { m_kwl->addPair(CUT_MIN_LAT_KW, tempString1); m_kwl->addPair(CUT_MIN_LON_KW, tempString2); m_kwl->addPair(CUT_MAX_LAT_KW, tempString3); m_kwl->addPair(CUT_MAX_LON_KW, tempString4); m_kwl->addPair(CUT_WIDTH_KW, tempString5); m_kwl->addPair(CUT_HEIGHT_KW, tempString6); } if (ap.read("--cut-center-llwh", stringParam1, stringParam2, stringParam3, stringParam4)) { m_kwl->addPair(CUT_CENTER_LAT_KW, tempString1); m_kwl->addPair(CUT_CENTER_LON_KW, tempString2); m_kwl->addPair(CUT_WIDTH_KW, tempString3); m_kwl->addPair(CUT_HEIGHT_KW, tempString4); } if (ap.read("--cut-center-llr", stringParam1, stringParam2, stringParam3)) { m_kwl->addPair(CUT_CENTER_LAT_KW, tempString1); m_kwl->addPair(CUT_CENTER_LON_KW, tempString2); m_kwl->addPair(CUT_RADIUS_KW, tempString3); } int num_params = ap.numberOfParams("--degrees", doubleParam1); if (num_params == 1) { ap.read("--degrees", doubleParam1); m_kwl->add(DEGREES_X_KW.c_str(), tempDouble1); m_kwl->add(DEGREES_Y_KW.c_str(), tempDouble1); } else if (num_params == 2) { ap.read("--degrees", doubleParam1, doubleParam2); m_kwl->add(DEGREES_X_KW.c_str(), tempDouble1); m_kwl->add(DEGREES_Y_KW.c_str(), tempDouble2); } if (ap.read("--elevation", stringParam1)) { m_kwl->addPair(std::string(ossimKeywordNames::ELEVATION_ANGLE_KW), tempString1); } if (ap.read("-e", stringParam1) || ap.read("--entry", stringParam1)) { m_kwl->addPair(std::string(ossimKeywordNames::ENTRY_KW), tempString1); } if(ap.read("--gamma", stringParam1)) { m_kwl->addPair(GAMMA_KW, tempString1); } if (ap.read("--exaggeration", stringParam1)) { m_kwl->addPair(GAIN_KW, tempString1); } if (ap.read("--fullres-xys", stringParam1)) { m_kwl->addPair(FULLRES_XYS_KW, tempString1); std::vector values; ossimString(tempString1).split(values, ","); double sx, sy; if (values.size() > 2) { sx = values[2].toDouble(); sy = sx; if (values.size() > 3) { sy = values[3].toDouble(); } m_kwl->add(IMAGE_SPACE_SCALE_X_KW.c_str(), sx); m_kwl->add(IMAGE_SPACE_SCALE_Y_KW.c_str(), sy); } } if (ap.read("--hemisphere", stringParam1)) { m_kwl->addPair(std::string(ossimKeywordNames::HEMISPHERE_KW), tempString1); } if (ap.read("--histogram-aoi", stringParam1)) { m_kwl->addPair(HIST_AOI_KW, tempString1); } if (ap.read("--enable-null-pixel-flip")) { m_kwl->addPair(NULL_PIXEL_FLIP_KW, TRUE_KW); } if (ap.read("--histogram-center-tile")) { m_kwl->addPair(HIST_CENTER_KW, TRUE_KW); } if (ap.read("--histogram-llwh", stringParam1)) { m_kwl->addPair(HIST_LLWH_KW, tempString1); } if (ap.read("--histogram-op", stringParam1)) { m_kwl->addPair(HIST_OP_KW, tempString1); } if (ap.read("--histogram-bias-factor", stringParam1)) { m_kwl->addPair(HIST_BIAS_FACTOR_KW, tempString1); } if (ap.read("--histogram-linear-clip", stringParam1)) { m_kwl->addPair(HIST_LINEAR_CLIP_KW, tempString1); } if (ap.read("--histogram-linear-norm-clip", stringParam1)) { m_kwl->addPair(HIST_LINEAR_NORM_CLIP_KW, tempString1); } if (ap.read("--histogram-center-clip", stringParam1)) { m_kwl->addPair(HIST_CENTER_CLIP_KW, tempString1); } if (ap.read("--image-space-scale", doubleParam1, doubleParam2)) { m_kwl->add(IMAGE_SPACE_SCALE_X_KW.c_str(), tempDouble1); m_kwl->add(IMAGE_SPACE_SCALE_Y_KW.c_str(), tempDouble2); } while (ap.read("--input-dem", stringParam1)) { key = DEM_KW; key += ossimString::toString(demIdx); key += "."; key += FILE_KW; m_kwl->addPair(key.string(), tempString1); ++demIdx; } while (ap.read("--input-img", stringParam1)) { key = IMG_KW; key += ossimString::toString(imgIdx); key += "."; key += FILE_KW; m_kwl->addPair(key.string(), tempString1); ++imgIdx; } if (ap.read("--input-src", stringParam1)) { m_kwl->addPair(SRC_FILE_KW, tempString1); } if (ap.read("--meters", stringParam1)) { m_kwl->addPair(METERS_KW, tempString1); } if (ap.read("-n") || ap.read("--north-up")) { m_kwl->addPair(NORTH_UP_KW, TRUE_KW); } if (ap.read("--op", stringParam1)) { m_kwl->addPair(OP_KW, tempString1); } //--- // Deprecated: "--options-keyword-list" //--- if (ap.read("--options", stringParam1)) { ossimFilename optionsKwl = tempString1; if (optionsKwl.exists()) { if (m_kwl->addFile(optionsKwl) == false) { std::string errMsg = "ERROR could not open options keyword list file: "; errMsg += optionsKwl.string(); throw ossimException(errMsg); } } else { std::string errMsg = "ERROR options keyword list file does not exists: "; errMsg += optionsKwl.string(); throw ossimException(errMsg); } } if (ap.read("--origin-latitude", stringParam1)) { m_kwl->addPair(std::string(ossimKeywordNames::ORIGIN_LATITUDE_KW), tempString1); } if (ap.read("--output-radiometry", stringParam1)) { m_kwl->addPair(OUTPUT_RADIOMETRY_KW, tempString1); } if (ap.read("--pad-thumbnail", stringParam1)) { m_kwl->addPair(PAD_THUMBNAIL_KW, tempString1); } if (ap.read("--projection", stringParam1)) { m_kwl->addPair(std::string(ossimKeywordNames::PROJECTION_KW), tempString1); } if (ap.read("--resample-filter", stringParam1)) { m_kwl->addPair(RESAMPLER_FILTER_KW, tempString1); } if (ap.read("-r", stringParam1) || ap.read("--rotate", stringParam1)) { m_kwl->addPair(ROTATION_KW, tempString1); } if (ap.read("--rotate-to-input")) { m_kwl->addPair(ROTATE_TO_INPUT, "true"); } while (ap.read("--reader-prop", stringParam1)) { key = READER_PROPERTY_KW; key += ossimString::toString(readerPropIdx); m_kwl->addPair(key.string(), tempString1); ++readerPropIdx; } if (ap.read("--rrds", stringParam1)) { m_kwl->addPair(RRDS_KW, tempString1); } if (ap.read("--scale-to-8-bit")) { m_kwl->addPair(SCALE_2_8_BIT_KW, TRUE_KW); } if (ap.read("--sharpen-mode", stringParam1)) { m_kwl->addPair(SHARPEN_MODE_KW, tempString1); } if (ap.read("--sharpen-percent", stringParam1)) { m_kwl->addPair(SHARPEN_PERCENT_KW, tempString1); } if (ap.read("--snap-tie-to-origin")) { m_kwl->addPair(SNAP_TIE_TO_ORIGIN_KW, TRUE_KW); } if (ap.read("--srs", stringParam1)) { ossimString os = tempString1; if (os.contains("EPSG:")) { os.gsub(ossimString("EPSG:"), ossimString("")); } m_kwl->addPair(SRS_KW, os.string()); } if (ap.read("-t", stringParam1) || ap.read("--thumbnail", stringParam1)) { m_kwl->addPair(THUMBNAIL_RESOLUTION_KW, tempString1); } if (ap.read("--three-band-out")) { m_kwl->addPair(THREE_BAND_OUT_KW, TRUE_KW); } if (ap.read("--tile-size", stringParam1)) { m_kwl->addPair(TILE_SIZE_KW, tempString1); } if (ap.read("-u") || ap.read("--up-is-up")) { m_kwl->addPair(UP_IS_UP_KW, TRUE_KW); } if (ap.read("-w", stringParam1) || ap.read("--writer", stringParam1)) { m_kwl->addPair(WRITER_KW, tempString1); } while (ap.read("--writer-prop", stringParam1)) { key = WRITER_PROPERTY_KW; key += ossimString::toString(writerPropIdx); m_kwl->addPair(key.string(), tempString1); ++writerPropIdx; } if (ap.read("--zone", stringParam1)) { m_kwl->addPair(std::string(ossimKeywordNames::ZONE_KW), tempString1); } if (ap.read("--2cmv-old-input-band", stringParam1)) { m_kwl->addPair(TWOCMV_OLD_INPUT_BAND_KW, tempString1); } if (ap.read("--2cmv-new-input-band", stringParam1)) { m_kwl->addPair(TWOCMV_NEW_INPUT_BAND_KW, tempString1); } if (ap.read("--2cmv-red-output-source", stringParam1)) { m_kwl->addPair(TWOCMV_RED_OUTPUT_SOURCE_KW, tempString1); } if (ap.read("--2cmv-green-output-source", stringParam1)) { m_kwl->addPair(TWOCMV_GREEN_OUTPUT_SOURCE_KW, tempString1); } if (ap.read("--2cmv-blue-output-source", stringParam1)) { m_kwl->addPair(TWOCMV_BLUE_OUTPUT_SOURCE_KW, tempString1); } if (ap.read("--combiner-type", stringParam1)) { m_kwl->addPair(COMBINER_TYPE_KW, tempString1); } // End of arg parsing. ap.reportRemainingOptionsAsUnrecognized(); if (ap.errors()) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); std::string errMsg = "Unknown option..."; throw ossimException(errMsg); } if (ap.argc() >= 2) { // Output file is last arg: m_kwl->add(ossimKeywordNames::OUTPUT_FILE_KW, ap[ap.argc() - 1]); } else { if (!m_kwl->find(ossimKeywordNames::OUTPUT_FILE_KW)) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); std::string errMsg = "Must supply an output file."; throw ossimException(errMsg); } } if (ap.argc() > 2) // User passed inputs in front of output file. { int pos = 1; // ap.argv[0] is application name. while (pos < (ap.argc() - 1)) { ossimFilename file = ap[pos]; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "argv[" << pos << "]: " << file << "\n"; } if (isDemFile(file)) { key = DEM_KW; key += ossimString::toString(demIdx); key += "."; key += FILE_KW; m_kwl->addPair(key, file.string()); ++demIdx; } else if (isSrcFile(file)) { if (m_kwl->find(SRC_FILE_KW.c_str())) // --input-src used also { std::string errMsg = MODULE; errMsg += "ERROR Multiple src files passed in. Please combine into one."; throw ossimException(errMsg); } m_kwl->addPair(SRC_FILE_KW, file.string()); } else // Add as an input image. { key = IMG_KW; key += ossimString::toString(imgIdx); key += "."; key += FILE_KW; m_kwl->addPair(key.string(), file.string()); ++imgIdx; } ++pos; // Go to next arg... } // End: while ( pos < (ap.argc()-1) ) } // End: if ( ap.argc() > 2 ) initialize(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited..." << std::endl; } return true; } // End: void ossimChipperUtil::initialize(ossimArgumentParser& ap) void ossimChipperUtil::initialize(const ossimKeywordlist &kwl) { clear(); // Start with clean options keyword list. m_kwl->clear(); m_kwl->addList(kwl, true); initialize(); } void ossimChipperUtil::initialize() { static const char MODULE[] = "ossimChipperUtil::initialize()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } if (traceOptions()) { ossimFilename optionsFile; getOutputFilename(optionsFile); optionsFile = optionsFile.noExtension(); optionsFile += "-options.kwl"; ossimString comment = " Can be use for --options argument."; m_kwl->write(optionsFile.c_str(), comment.c_str()); } // Determine the operation to do. std::string op = m_kwl->findKey(OP_KW); if (op.size()) { ossimString s = op; s.downcase(); if (s == "chip") { m_operation = OSSIM_CHIPPER_OP_CHIP; } else if (s == "hillshade") { m_operation = OSSIM_CHIPPER_OP_HILL_SHADE; } else if (s == "color-relief") { m_operation = OSSIM_CHIPPER_OP_COLOR_RELIEF; } else if (s == "ortho") { m_operation = OSSIM_CHIPPER_OP_ORTHO; } else if (s == "psm") { m_operation = OSSIM_CHIPPER_OP_PSM; } else if (s == "2cmv") { m_operation = OSSIM_CHIPPER_OP_2CMV; } else { std::string errMsg = "unknown operation: "; errMsg += s.string(); throw ossimException(errMsg); } } else { std::string errMsg = "keyword not found: "; errMsg += OP_KW; errMsg += "\nUse --op option to specify operation.\n"; throw ossimException(errMsg); } //--- // Populate the m_srcKwl if --src option was set. // Note do this before creating chains. //--- initializeSrcKwl(); // Check for required inputs. Do this after initializeSrcKwl. if (m_operation == OSSIM_CHIPPER_OP_CHIP) { if (getNumberOfInputs() != 1) { std::ostringstream errMsg; errMsg << op << " operation takes one input."; throw ossimException(errMsg.str()); } } if ((m_operation == OSSIM_CHIPPER_OP_2CMV) || (m_operation == OSSIM_CHIPPER_OP_PSM)) { if (getNumberOfInputs() != 2) { std::ostringstream errMsg; errMsg << op << " operation requires two inputs."; throw ossimException(errMsg.str()); } } // Sanity check rotation options. if (upIsUp() || northUp() || hasRotation()) { std::string option; ossim_uint32 rotationOptionCount = 0; if (upIsUp()) { option = UP_IS_UP_KW; ++rotationOptionCount; } if (northUp()) { option = NORTH_UP_KW; ++rotationOptionCount; } if (hasRotation()) { option = ROTATION_KW; ++rotationOptionCount; } // Can only do ONE rotation option. if (rotationOptionCount > 1) { std::ostringstream errMsg; if (upIsUp()) { errMsg << UP_IS_UP_KW << " is on.\n"; } if (northUp()) { errMsg << NORTH_UP_KW << " is on.\n"; } if (hasRotation()) { errMsg << ROTATION_KW << " is on.\n"; } errMsg << "Multiple rotation options do not make sense!"; throw ossimException(errMsg.str()); } // One input, chip operation only. if (getNumberOfInputs() != 1) { std::ostringstream errMsg; errMsg << option << " option takes one input."; throw ossimException(errMsg.str()); } if (m_operation != OSSIM_CHIPPER_OP_CHIP) { std::ostringstream errMsg; errMsg << option << " option only valid with \"chip\" operation."; throw ossimException(errMsg.str()); } } // Create chains for any dem sources. addDemSources(); // Create chains for any image sources. addImgSources(); // Initialize projection and propagate to chains. initializeOutputProjection(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "options keyword list:\n" << *(m_kwl.get()) << "\n"; if (m_srcKwl.valid()) { ossimNotify(ossimNotifyLevel_DEBUG) << "support record keyword list:\n" << *(m_srcKwl.get()) << "\n"; } ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } // End: void ossimChipperUtil::initialize() ossimRefPtr ossimChipperUtil::initializeChain(ossimIrect &aoi) { static const char MODULE[] = "ossimChipperUtil::initializeChain"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimString lookup; // used throughout... ossimRefPtr source = 0; if (hasBumpShadeArg()) { // Create chain: source = initializeBumpShadeChain(); } else if (m_operation == OSSIM_CHIPPER_OP_COLOR_RELIEF) { source = initializeColorReliefChain(); } else if ((m_operation == OSSIM_CHIPPER_OP_CHIP) || (m_operation == OSSIM_CHIPPER_OP_ORTHO)) { source = combineLayers(); } else if (m_operation == OSSIM_CHIPPER_OP_2CMV) { source = initialize2CmvChain(); // Two Color Multiview. } else if (m_operation == OSSIM_CHIPPER_OP_PSM) { source = initializePsmChain(); // Pan sharpened multispectral. } if (source.valid()) { //--- // This is conditional. Output radiometry may of may not be set. This can also be set at // the ossimSingleImageChain level. //--- if ((getOutputScalarType() != OSSIM_SCALAR_UNKNOWN) && (source->getOutputScalarType() != getOutputScalarType())) { // source = addScalarRemapper(source, getOutputScalarType()); } //--- // Get the area of interest. This will be the scene bounding rect if not // explicitly set by user with one of the --cut options. // Need to get this before the thumbnail code. //--- getAreaOfInterest(source.get(), aoi); //--- // Set the image size here. Note must be set after combineLayers. This is needed for // the ossimImageGeometry::worldToLocal call for a geographic projection to handle wrapping // accross the date line. //--- if (m_geom.valid()) { m_geom->setImageSize(aoi.size()); } if (hasThumbnailResolution()) { //--- // Adjust the projection scale and get the new rect. // Note this will resize the ossimImageGeometry::m_imageSize is scale changes. //--- initializeThumbnailProjection(aoi, aoi); // Reset the source bounding rect if it changed. source->initialize(); } // GP 2019: we will add cutters at the end // Will remove temporarily bt leave the code hear just in // case I messed something up if (source.valid() && !aoi.hasNans()) { //--- // Add a cut filter. This will: // 1) Null out/clip any data pulled in. // 2) Speed up by not propagating get tile request outside the cut or "aoi" // to the left hand side(input). //--- // ossimRefPtr cutter = new ossimRectangleCutFilter(); // // Set the cut rectangle: // cutter->setRectangle(aoi); // // Null outside. // cutter->setCutType(ossimRectangleCutFilter::OSSIM_RECTANGLE_NULL_OUTSIDE); // // Connect cutter input to source chain. // cutter->connectMyInputTo(0, source.get()); // source = cutter.get(); // // Dependent on correct aoi so place after the cutter. // if (hasAnnotations()) // { // // Put annotations after scalar remapper. // ossimRefPtr result = addAnnotations(source); // if (result.valid()) // { // source = result.get(); // } // } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return source; } void ossimChipperUtil::setOptionsToChain( ossimIrect &aoi, const ossimKeywordlist & /* kwl */) { getAreaOfInterest(m_source.get(), aoi); } ossimRefPtr ossimChipperUtil::initializeBumpShadeChain() { static const char MODULE[] = "ossimChipperUtil::initializeBumpShadeChain"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimString lookup; ossimRefPtr source = 0; // Combine the dems. ossimRefPtr demSource = combineLayers(m_demLayer); // Set up the normal source. ossimRefPtr normSource = new ossimImageToPlaneNormalFilter; //--- // Set the track scale flag to true. This enables scaling the surface // normals by the GSD in order to maintain terrain proportions. //--- normSource->setTrackScaleFlag(true); // Connect to dems. normSource->connectMyInputTo(demSource.get()); // Set the smoothness factor. ossim_float64 gain = 1.0; lookup = m_kwl->findKey(GAIN_KW); if (lookup.size()) { gain = lookup.toFloat64(); } normSource->setSmoothnessFactor(gain); ossimRefPtr colorSource = 0; if (hasLutFile()) { if (m_imgLayer.size()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " WARNING:" << "\nBoth a color table and image(s) have been provided for a color source.\n" << "Choosing color table of image(s).\n"; } colorSource = addIndexToRgbLutFilter(demSource); } else { // Combine the images and set as color source for bump shade. colorSource = combineLayers(m_imgLayer); } // Create the bump shade. ossimRefPtr bumpShade = new ossimBumpShadeTileSource; // Set the azimuth angle. ossim_float64 azimuthAngle = 180; lookup = m_kwl->findKey(ossimKeywordNames::AZIMUTH_ANGLE_KW); if (lookup.size()) { ossim_float64 f = lookup.toFloat64(); if ((f >= 0) && (f <= 360)) { azimuthAngle = f; } } bumpShade->setAzimuthAngle(azimuthAngle); // Set the elevation angle. ossim_float64 elevationAngle = 45.0; lookup = m_kwl->findKey(ossimKeywordNames::ELEVATION_ANGLE_KW); if (lookup.size()) { ossim_float64 f = lookup.toFloat64(); if ((f >= 0.0) && (f <= 90)) { elevationAngle = f; } } bumpShade->setElevationAngle(elevationAngle); if (!hasLutFile()) { // Set the color. ossim_uint8 r = 0xff; ossim_uint8 g = 0xff; ossim_uint8 b = 0xff; lookup = m_kwl->findKey(COLOR_RED_KW); if (lookup.size()) { r = lookup.toUInt8(); } lookup = m_kwl->findKey(COLOR_GREEN_KW); if (lookup.size()) { g = lookup.toUInt8(); } lookup = m_kwl->findKey(COLOR_BLUE_KW); if (lookup.size()) { b = lookup.toUInt8(); } bumpShade->setRgbColorSource(r, g, b); } // Connect the two sources. bumpShade->connectMyInputTo(0, normSource.get()); bumpShade->connectMyInputTo(1, colorSource.get()); if (traceDebug()) { ossim_uint8 r = 0xff; ossim_uint8 g = 0xff; ossim_uint8 b = 0xff; bumpShade->getRgbColorSource(r, g, b); ossimNotify(ossimNotifyLevel_DEBUG) << "\nazimuthAngle: " << azimuthAngle << "\nelevation angle: " << elevationAngle << "\ngain factor: " << gain << "\nr: " << int(r) << "\ng: " << int(g) << "\nb: " << int(b) << "\n"; } // Capture the pointer to give to the writer. source = bumpShade.get(); return source; } // End: ossimChipperUtil::initializeBumpShadeChain() ossimRefPtr ossimChipperUtil::initializeColorReliefChain() { ossimRefPtr result = combineLayers(); if (hasLutFile()) { result = addIndexToRgbLutFilter(result); } else { // No LUT file provided, so doing the default 8-bit linear stretch: if (result->getOutputScalarType() != OSSIM_UINT8) { //result = addScalarRemapper(result, OSSIM_UINT8); } } return result; } ossimRefPtr ossimChipperUtil::initializePsmChain() { ossimRefPtr result = 0; ossim_uint32 layerCount = (ossim_uint32)(m_demLayer.size() + m_imgLayer.size()); // Must have two and only two inputs. if (layerCount == 2) { ossimRefPtr input1 = 0; // First input should be color. ossimRefPtr input2 = 0; // Second input should be pan. // Most likely case, two image layers. if (m_imgLayer.size()) { input1 = m_imgLayer[0].get(); if (m_imgLayer.size() == 2) { input2 = m_imgLayer[1].get(); } } if (m_demLayer.size()) { if (!input1.valid()) { input1 = m_demLayer[0].get(); } if (!input2.valid()) { if (m_demLayer.size() == 1) { input2 = m_demLayer[0].get(); } else if (m_demLayer.size() == 2) { input2 = m_demLayer[1].get(); } } } if (input1.valid() && input2.valid()) { // Make the color input the first connection to the combiner. if (input1->getNumberOfOutputBands() == 1) { // Swap: ossimRefPtr tmpChain = input1; input1 = input2; input2 = tmpChain; } //--- // Check the pan source for one band: // This really shouldn't happen, i.e. caller should typically pass a // one band pan image that is higher resolution than the color source. //--- if (input2->getNumberOfOutputBands() > 1) { // Note this will add a band selector if there isn't one in chain. std::vector bandList(1); bandList[0] = 0; input2->setBandSelection(bandList); } // TODO: Make dynamic by type. ossimRefPtr psm = new ossimSFIMFusion(); psm->connectMyInputTo(0, input1.get()); psm->connectMyInputTo(1, input2.get()); psm->initialize(); result = dynamic_cast(psm.get()); } } // Matches: if ( layerCount == 2 ) return result; } // End: ossimChipperUtil::initializePsmChain() void ossimChipperUtil::initializeOutputProjection() { if (isChipMode()) { createIdentityProjection(); } else { // Create the output projection. createOutputProjection(); // Setup the view in all the chains. propagateOutputProjectionToChains(); } } ossimIrect clampViewportStretch(const ossimIrect &viewRect) { ossimIrect result = viewRect; if (result.width() > 1024 || result.height() > 1024) { ossim_int64 w = ossim::min(static_cast(result.width()), static_cast(1024)); ossim_int64 h = ossim::min(static_cast(result.height()), static_cast(1024)); if (w < 256) w = 256; if (h < 256) h = 256; result = ossimIrect(ossimIpt(result.midPoint()), w, h); } return result; } void ossimChipperUtil::setStretch(ossimRefPtr remapper)const { ossim_int32 mode = getHistoMode(); ossimString value; if (mode == ossimHistogramRemapper::LINEAR_ONE_PIECE) { value = m_kwl->findKey(HIST_LINEAR_CLIP_KW); std::vector splitValues; if (!value.empty()) { splitValues = value.split(","); if(splitValues.size() == 2) { remapper->setLowClipPoint(splitValues[0].toFloat32()); remapper->setHighClipPoint(splitValues[1].toFloat32()); } } else { value = m_kwl->findKey(HIST_LINEAR_NORM_CLIP_KW); if(!value.empty()) { splitValues = value.split(","); if (splitValues.size() == 2) { ossim_float32 low = splitValues[0].toFloat32(); ossim_float32 high = splitValues[1].toFloat32(); remapper->setLowNormalizedClipPoint(low); remapper->setHighNormalizedClipPoint(high); } } } } value = m_kwl->findKey(HIST_BIAS_FACTOR_KW); if(!value.empty()) { remapper->setBiasFactor(value.toDouble()); } value = m_kwl->findKey(HIST_CENTER_CLIP_KW); if (!value.empty()) { remapper->setMidPoint(value.toFloat64()); } } ossimRefPtr ossimChipperUtil::getFinalInput(const ossimIrect& aoi, ossimRefPtr currentSource) { ossimRefPtr result = currentSource; if(m_container.valid()) { m_container->deleteAllChildren(); m_container->disconnect(); } else { m_container = new ossimConnectableContainer(); } ossimRefPtr cut = new ossimRectangleCutFilter(); cut->connectMyInputTo(result.get()); cut->setRectangle(aoi); m_container->addChild(cut.get()); result = cut.get(); if(m_viewPortStretchEnabled) { if(m_geom) { ossimDpt iptCenter; ossimDrect histogramSourceRect; ossimRefPtr histoSource = new ossimImageHistogramSource(); // ossimTypeNameVisitor imageRendererVisitor("ossimImageRenderer", true); // currentSource->accept(imageRendererVisitor); ossim_float64 cutWidth = ossim::clamp(aoi.width(), 256, 1024); ossim_float64 cutHeight = ossim::clamp(aoi.height(), 256, 1024); ossimRefPtr viewportCut = new ossimRectangleCutFilter(); ossimIrect cutRect = ossimIrect(ossimIpt(aoi.midPoint()), cutWidth, cutHeight); m_container->addChild(viewportCut.get()); viewportCut->connectMyInputTo(currentSource.get()); viewportCut->setRectangle(cutRect); histoSource->connectMyInputTo(viewportCut.get()); // ossimRefPtr rendererObj = imageRendererVisitor.getObjectAs(0); // imageRendererVisitor.reset(); // need a rectangle cut that we will connect to an input source that is before the resampling // process so we will need to invert the view window center and then expand the sample rect to a // fixed size. Probably like 256x256 for now // // bool setupOk=false; // if (rendererObj) // { // ossimRefPtr trans = rendererObj->getImageViewTransform(); // if(trans) // { // m_container->addChild(viewportCut.get()); // trans->viewToImage(aoi.midPoint(), iptCenter); // histogramSourceRect = ossimIrect(ossimIpt(iptCenter), 1024, 1024); // viewportCut->connectMyInputTo(rendererObj->getInput(0)); // viewportCut->setRectangle(histogramSourceRect); // histoSource->connectMyInputTo(viewportCut.get()); // // ossimKeywordlist kwl; // // histoSource->getHistogram()->saveState(kwl); // //std::cout << "KWL: " << kwl << "\n"; // setupOk = true; // } // } // if(!setupOk) // { // histoSource->connectMyInputTo(result.get()); // } ossimRefPtr remapper = new ossimHistogramRemapper(); remapper->connectMyInputTo(result.get()); remapper->connectMyInputTo(histoSource.get()); remapper->setStretchMode(static_cast(getHistoMode())); remapper->setEnableFlag(true); result = remapper.get(); m_container->addChild(histoSource.get()); m_container->addChild(remapper.get()); setStretch(remapper); } } if(scaleToEightBit()) { if(result->getOutputScalarType() != OSSIM_UINT8) { ossimRefPtr scalarRemapper = new ossimScalarRemapper(); scalarRemapper->setOutputScalarType(OSSIM_UINT8); scalarRemapper->connectMyInputTo(result.get()); m_container->addChild(scalarRemapper.get()); result = scalarRemapper.get(); } } return result; } void ossimChipperUtil::execute() { static const char MODULE[] = "ossimChipperUtil::execute"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimIrect aoi; ossimRefPtr chain = initializeChain(aoi); // ossimRefPtr container = new ossimConnectableContainer(); ossimRefPtr source = getFinalInput(aoi, chain);//chain.get(); if (source.valid() && !aoi.hasNans()) { // Set up the writer. m_writer = createNewWriter(); // Connect the writer to the cutter. m_writer->connectMyInputTo(0, source.get()); //--- // Set the area of interest. // NOTE: This must be called after the writer->connectMyInputTo as // ossimImageFileWriter::initialize incorrectly resets theAreaOfInterest // back to the bounding rect. //--- // m_writer->setAreaOfInterest(aoi); if (m_writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK) { // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); m_writer->addListener(&prog); if (traceLog()) { ossimKeywordlist logKwl; m_writer->saveStateOfAllInputs(logKwl); ossimFilename logFile; getOutputFilename(logFile); logFile.setExtension("log"); logKwl.write(logFile.c_str()); } // Write the file: m_writer->execute(); m_writer->removeListener(&prog); if (m_writer->isAborted()) { throw ossimException("Writer Process aborted!"); } m_writer->disconnect(); m_container->deleteAllChildren(); m_container->disconnect(); } else { throw ossimException("Unable to initialize writer for execution"); } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } void ossimChipperUtil::abort() { if (m_writer.valid()) { m_writer->abort(); } } ossimRefPtr ossimChipperUtil::getChip(const ossimKeywordlist &optionsKwl) { ossimRefPtr result = 0; ossimIrect aoi; if (optionsKwl.getSize() > 0) { m_kwl->addList(optionsKwl, true); } // (GP) // Until we add more ellaborate code to check for scale changes // as well as moving windows we will just always initialize // the output projection // initializeOutputProjection(); if (!m_source.valid()) { m_source = initializeChain(aoi); } if (optionsKwl.getSize() > 0) { //--- // Only do this if new options were passed in. This was causing an off by // one error when now options were passed in using thumbnail option. // The m_source->getBoundingRect(...) was returning 257 instead of 256. // Need to hunt that down but for right now this fixes problem. // (drb 20151222) //--- getAreaOfInterest(m_source.get(), aoi); m_geom->setImageSize(aoi.size()); } else { getAreaOfInterest(m_source.get(), aoi); } if (m_source.valid()) { ossimRefPtr source = getFinalInput(aoi, m_source.get()); result = source->getTile(aoi); } return result; } void ossimChipperUtil::addDemSources() { static const char MODULE[] = "ossimChipperUtil::addDemSources"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::vector sortedList; m_kwl->getSortedList(sortedList, DEM_KW); for (auto record : sortedList) { ossimString key = record + "."; ossimString file = key + FILE_KW; ossimString entry = key + ossimKeywordNames::ENTRY_KW; ossimFilename f = m_kwl->findKey(file.string()); if (f.size()) { // Look for the entry key, e.g. dem0.entry: 10 ossim_uint32 entryIndex = 0; std::string value = m_kwl->findKey(entry.string()); if (value.size()) { entryIndex = ossimString(value).toUInt32(); } else { // Get global entry. Set by "-e" on command line apps. entryIndex = getEntryNumber(); } ossimSrcRecord srcRecord; srcRecord.setFilename(f); srcRecord.setEntryIndex(entryIndex); // addDemSource( f, entryIndex ); addDemSource(srcRecord); } } sortedList.clear(); if (m_srcKwl.valid()) { // Add stuff from src keyword list. m_srcKwl->getSortedList(sortedList, DEM_KW); for (auto record : sortedList) { ossimString prefix = record + "."; ossimSrcRecord src; if (src.loadState(*(m_srcKwl.get()), prefix)) { addDemSource(src); } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } void ossimChipperUtil::addDemSource(const ossimFilename &file, ossim_uint32 entryIndex) { static const char MODULE[] = "ossimChipperUtil::addDemSource(const ossimFilename&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr ic = createChain(file, entryIndex, true); if (ic.valid()) { m_demLayer.push_back(ic); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exiting...\n"; } } void ossimChipperUtil::addDemSource(const ossimSrcRecord &rec) { static const char MODULE[] = "ossimChipperUtil::addDemSource(const ossimSrcRecord&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr ic = createChain(rec, true); if (ic.valid()) { m_demLayer.push_back(ic); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exiting...\n"; } } void ossimChipperUtil::addImgSources() { static const char MODULE[] = "ossimChipperUtil::addImgSources"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::vector sortedList; m_kwl->getSortedList(sortedList, IMG_KW); for (auto record : sortedList) { ossimString fileKey = record + "." + FILE_KW; ossimFilename f = m_kwl->findKey(fileKey.string()); if (!f.empty()) { ossimString imagePrefix = record + "."; std::shared_ptr srcRecord = std::make_shared(); if (srcRecord->loadState(*m_kwl, imagePrefix.c_str())) { addImgSource(*srcRecord); } } } sortedList.clear(); if (m_srcKwl.valid()) { m_srcKwl->getSortedList(sortedList, IMG_KW); for (auto record : sortedList) { ossimString prefix = record + "."; std::shared_ptr src = std::make_shared(); if (src->loadState(*(m_srcKwl.get()), prefix)) { addImgSource(*src); } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } void ossimChipperUtil::addImgSource(const ossimFilename &file, ossim_uint32 entryIndex) { static const char MODULE[] = "ossimChipperUtil::addImgSource"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\nFile: " << file << "\n"; } ossimRefPtr ic = createChain(file, entryIndex, false); if (ic.valid()) { m_imgLayer.push_back(ic); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exiting...\n"; } } void ossimChipperUtil::addImgSource(const ossimSrcRecord &rec) { static const char MODULE[] = "ossimChipperUtil::addImgSource(const ossimSrcRecord&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr ic = createChain(rec, false); if (ic.valid()) { m_imgLayer.push_back(ic); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exiting...\n"; } } ossimRefPtr ossimChipperUtil::createChain(const ossimFilename &file, ossim_uint32 entryIndex, bool isDemSource) const { static const char MODULE[] = "ossimChipperUtil::createChain(const ossimFilename&"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << "\nfile: " << file << "\nentry: " << entryIndex << "\nisDemSource: " << (isDemSource ? "true" : "false") << "\n"; } ossimRefPtr ic = 0; if (!file.empty() && file.exists()) { ic = new ossimSingleImageChain; if (ic->open(file)) { // Set any reader props: setReaderProps(ic->getImageHandler().get()); // we can't guarantee the state of the image handler at this point so // let's make sure that the entry is always set to the requested location // On Cib/Cadrg we were having problems. Removed the compare for entry 0 // if (setChainEntry(ic, entryIndex) == false) { std::ostringstream errMsg; errMsg << MODULE << " ERROR:\nEntry " << entryIndex << " out of range!" << std::endl; throw ossimException(errMsg.str()); } //--- // If PSM (pan sharpening) operation and this input is one band, don't // mess with its bands. //--- bool psmPanInput = false; if ((m_operation == OSSIM_CHIPPER_OP_PSM) && (ic->getNumberOfOutputBands() == 1)) { psmPanInput = true; } // Bands selection. Note: Not performed on PSM pan band. if (!psmPanInput) { if (isThreeBandOut()) { //--- // This will guarantee three bands out. Will put band // selector at the end of the chain if input is one band. If input image // handler has implemented a getRgbBandlist(...) it will also set the // rgb band order. //--- ic->setThreeBandFlag(true); } if (hasBandSelection()) { // User entered band list. std::vector bandList(0); getBandList(bandList); if (bandList.size()) { ic->setBandSelection(bandList); } else { ic->setDefaultBandSelection(); } } } ossimString nullPixelFlip = m_kwl->find(NULL_PIXEL_FLIP_KW.c_str()); if (nullPixelFlip.toBool()) { ic->setAddNullPixelFlipFlag(true); } //--- // If multiple inputs and scaleToEightBit do it at the end of the processing // chain to alleviate un-even stretches between inputs. // // GP 2019: Going to move this to the end of the chain. Should always be full bit depth until the end //--- // const ossim_uint32 INPUT_COUNT = getNumberOfInputs(); // bool scaleFlag = (scaleToEightBit() && (INPUT_COUNT == 1)); //ic->setRemapToEightBitFlag(scaleFlag); // Always have resampler cache. ic->setAddResamplerCacheFlag(true); //--- // Don't need a chain cache as we're doing a sequential write. So the same tile // should never be visited more than once. //--- ic->setAddChainCacheFlag(false); //--- // Histogram: // Don't apply histogram stretch to dem sources for hill shade // operation. //--- if ((isDemSource == false) || (isDemSource && (m_operation != OSSIM_CHIPPER_OP_HILL_SHADE))) { ic->setAddHistogramFlag(hasHistogramOperation()); } if(hasGammaCorrection()) { ic->setAddGammaFlag(true); } // Brightness, contrast. Note in same filter. if (hasBrightnesContrastOperation()) { ic->setBrightnessContrastFlag(true); } std::string sharpnessMode = getSharpenMode(); std::string sharpenPercent = getSharpenPercent(); if (sharpnessMode.size()|| sharpenPercent.size()) { ic->setSharpenFlag(true); } // Create the chain. ic->createRenderedChain(); if(hasGammaCorrection()) { ic->getGammaRemapper()->setGamma(getGamma()); } // Set the filter type if needed. ossimString lookup = m_kwl->findKey(RESAMPLER_FILTER_KW); if (lookup.size()) { // Assumption image renderer is in chain: ic->getImageRenderer()->getResampler()->setFilterType(lookup); } // Histogram setup. if (hasHistogramOperation()) { setupChainHistogram(ic); } // Brightness contrast setup: if (hasBrightnesContrastOperation()) { // Assumption bright contrast filter in chain: ossim_float64 value = getBrightness(); ic->getBrightnessContrast()->setBrightness(value); value = getContrast(); ic->getBrightnessContrast()->setContrast(value); } // Sharpness: if (sharpnessMode.size()) { if (sharpnessMode == "light") { ic->getSharpenFilter()->setSharpenPercent(0.2); // ic->getSharpenFilter()->setWidthAndSigma(3, 0.5); } else if (sharpnessMode == "medium") { ic->getSharpenFilter()->setSharpenPercent(0.5); } else if (sharpnessMode == "heavy") { ic->getSharpenFilter()->setSharpenPercent(0.8); } } else if(sharpenPercent.size()) { ic->getSharpenFilter()->setSharpenPercent(ossimString(sharpenPercent).toDouble()); } if (hasGeoPolyCutterOption()) { ossimGeoPolygon polygon; getClipPolygon(polygon); if (polygon.size() > 0) { ic->addGeoPolyCutterPolygon(polygon); } } } else { ic = 0; } } if (!ic.valid()) { std::string errMsg = "Could not open: "; errMsg += file.string(); throw ossimException(errMsg); } if (traceDebug()) { ossimKeywordlist kwl; ic->saveState(kwl, 0); ossimNotify(ossimNotifyLevel_DEBUG) << "chain:\n" << kwl << "\n" << MODULE << " exiting...\n"; } return ic; } ossimRefPtr ossimChipperUtil::createChain(const ossimSrcRecord &rec, bool isDemSource) const { static const char MODULE[] = "ossimChipperUtil::createChain(const ossimSrcRecord&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr ic = new ossimSingleImageChain; if (ic->open(rec)) { // Set any reader props: setReaderProps(ic->getImageHandler().get()); // Entry is set in ossimSingleImageChain::open(src) //--- // If PSM (pan sharpening) operation and this input is one band, don't // mess with its bands. //--- bool psmPanInput = false; if ((m_operation == OSSIM_CHIPPER_OP_PSM) && (ic->getNumberOfOutputBands() == 1)) { psmPanInput = true; } // Bands selection. Note: Not performed on PSM pan band. if (!psmPanInput) { if (isThreeBandOut()) { //--- // This will guarantee three bands out. Will put band // selector at the end of the chain if input is one band. If input image // handler has implemented a getRgbBandlist(...) it will also set the // rgb band order. //--- ic->setThreeBandFlag(true); } if (hasBandSelection()) { // User entered band list. std::vector bandList(0); getBandList(bandList); if (bandList.size()) { ic->setBandSelection(bandList); } else { ic->setDefaultBandSelection(); } } } ossimString nullPixelFlip = m_kwl->find(NULL_PIXEL_FLIP_KW.c_str()); if (nullPixelFlip.toBool()) { ic->setAddNullPixelFlipFlag(true); } //--- // If multiple inputs and scaleToEightBit do it at the end of the processing // chain to alleviate un-even stretches between inputs. // // GP 2019: Going to move this to the end of the chain. Should always be full bit depth until the end //--- // const ossim_uint32 INPUT_COUNT = getNumberOfInputs(); // bool scaleFlag = (scaleToEightBit() && (INPUT_COUNT == 1)); //ic->setRemapToEightBitFlag(scaleFlag); // Always have resampler cache. ic->setAddResamplerCacheFlag(true); //--- // Don't need a chain cache as we're doing a sequential write. So the same tile // should never be visited more than once. //--- ic->setAddChainCacheFlag(false); //--- // Histogram: // Don't apply histogram stretch to dem sources for hill shade // operation. //--- if ((isDemSource == false) || (isDemSource && (m_operation != OSSIM_CHIPPER_OP_HILL_SHADE))) { ic->setAddHistogramFlag(hasHistogramOperation()); } if(hasGammaCorrection()) { ic->setAddGammaFlag(true); } // Brightness, contrast. Note in same filter. if (hasBrightnesContrastOperation()) { ic->setBrightnessContrastFlag(true); } std::string sharpnessMode = getSharpenMode(); std::string sharpenPercent = getSharpenPercent(); if (sharpnessMode.size() || sharpenPercent.size()) { ic->setSharpenFlag(true); } //--- // Create the chain. // // NOTE: Histogram and band selector can be set in ic->createRenderedChain(rec) // if the right keywords are there. //--- ic->createRenderedChain(rec); // Set the filter type if needed. ossimString lookup = m_kwl->findKey(RESAMPLER_FILTER_KW); if (lookup.size()) { // Assumption image renderer is in chain: ic->getImageRenderer()->getResampler()->setFilterType(lookup); } // Histogram setup. if (hasHistogramOperation()) { setupChainHistogram(ic, std::make_shared(rec)); } if(hasGammaCorrection()) { ic->getGammaRemapper()->setGamma(getGamma()); } // Brightness contrast setup: if (hasBrightnesContrastOperation()) { // Assumption bright contrast filter in chain: ossim_float64 value = getBrightness(); ic->getBrightnessContrast()->setBrightness(value); value = getContrast(); ic->getBrightnessContrast()->setContrast(value); } // Sharpness: if (sharpnessMode.size()) { if (sharpnessMode == "light") { ic->getSharpenFilter()->setSharpenPercent(0.2); } else if(sharpnessMode == "medium") { ic->getSharpenFilter()->setSharpenPercent(0.5); } else if (sharpnessMode == "heavy") { ic->getSharpenFilter()->setSharpenPercent(0.8); } } else if(sharpenPercent.size()) { ic->getSharpenFilter()->setSharpenPercent(ossimString(sharpenPercent).toDouble()); } if (hasGeoPolyCutterOption()) { ossimGeoPolygon polygon; getClipPolygon(polygon); if (polygon.size() > 0) { ic->addGeoPolyCutterPolygon(polygon); } } } else // Open failed. { std::string errMsg = "Could not open from src record!"; throw ossimException(errMsg); } if (traceDebug()) { ossimKeywordlist kwl; ic->saveState(kwl, 0); ossimNotify(ossimNotifyLevel_DEBUG) << "chain:\n" << kwl << "\n" << MODULE << " exiting...\n"; } return ic; } void ossimChipperUtil::createOutputProjection() { static const char MODULE[] = "ossimChipperUtil::createOutputProjection"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::string op = m_kwl->findKey(std::string(ossimKeywordNames::PROJECTION_KW)); std::string srs = m_kwl->findKey(SRS_KW); if (op.size() && srs.size()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " WARNING:" << "\nBoth " << SRS_KW << " and " << ossimKeywordNames::PROJECTION_KW << " keywords are set!" << "\nsrs: " << srs << "\noutput_projection: " << op << "\nTaking " << srs << " over " << op << "\n"; } bool usingInput = false; ossimChipperOutputProjection projType = getOutputProjectionType(); ossimRefPtr proj = 0; // If an srs code use that first. if (srs.size()) { proj = getNewProjectionFromSrsCode(srs); } else if (op.size()) { switch (projType) { case ossimChipperUtil::OSSIM_CHIPPER_PROJ_GEO: { proj = getNewGeoProjection(); break; } case ossimChipperUtil::OSSIM_CHIPPER_PROJ_GEO_SCALED: { proj = getNewGeoScaledProjection(); break; } case ossimChipperUtil::OSSIM_CHIPPER_PROJ_INPUT: { proj = getFirstInputProjection(); usingInput = true; break; } case ossimChipperUtil::OSSIM_CHIPPER_PROJ_UTM: { proj = getNewUtmProjection(); break; } default: { break; // Just for un-handled type warning. } } } // Check for identity projection: ossimRefPtr inputProj = getFirstInputProjection(); if (proj.valid() && inputProj.valid()) { if (*(inputProj.get()) == *(proj.get())) { if (projType == OSSIM_CHIPPER_PROJ_GEO_SCALED) { // Get the origin used for scaling. ossimGpt origin = proj->getOrigin(); // Copy the input projection to our projection. Has the tie and scale we need. proj = inputProj; // Set the origin for scaling. proj->setOrigin(origin); } else { proj = inputProj; } usingInput = true; } } if (!proj.valid()) { // Try first input. If map projected use that. if (inputProj.valid()) { proj = inputProj; usingInput = true; if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: No projection set!" << "\nDefaulting to first input's projection.\n"; } } else { proj = getNewGeoScaledProjection(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: No projection set!" << "\nDefaulting to scaled geographic at scene center.\n"; } } } // Create our ossimImageGeometry with projection (no transform). m_geom = new ossimImageGeometry(0, proj.get()); //--- // If the input is the same as output projection do not modify; else, set // the gsd to user selected "METERS_KW" or the best resolution of the inputs, // set the tie and then snap it to the projection origin. //--- if (!usingInput || hasScaleOption()) { // Set the scale. initializeProjectionGsd(); } // Set the tie. initializeProjectionTiePoint(); if (snapTieToOrigin()) { // Adjust the projection tie to the origin. proj->snapTiePointToOrigin(); } // May need to rotate the output map if requested: bool rotateMap=false; m_kwl->getBoolKeywordValue(rotateMap, ROTATE_TO_INPUT.c_str()); if (rotateMap) { rotateMapToInput(); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "using input projection: " << (usingInput ? "true" : "false") << "\noutput image geometry:\n"; m_geom->print(ossimNotify(ossimNotifyLevel_DEBUG)); ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } // End: ossimChipperUtil::createOutputProjection() void ossimChipperUtil::rotateMapToInput() { static const char MODULE[] = "ossimChipperUtil::rotateMapToInput"; if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; try { if (!m_geom) throw ossimException("Null projection geometry encountered."); ossimRefPtr mapProj = dynamic_cast(m_geom->getProjection()); if (!mapProj) throw ossimException("Output projection must be a map projection."); if (m_imgLayer.size() != 1) throw ossimException("Optimal rotation output requested but this feature is not available for mosaics."); ossimRefPtr ih = m_imgLayer[0]->getImageHandler(); if (!ih) throw ossimException("Null image handler encountered."); ossimRefPtr inputGeom = ih->getImageGeometry(); if (!inputGeom) throw ossimException("Null image geometry encountered."); // Determine azimuth of +X axis: ossimIpt inputImgSize (inputGeom->getImageSize()); if (inputImgSize.x == 0) throw ossimException("Image size is zero."); ossimDpt pUL (0,0); ossimDpt pUR (inputImgSize.x-1, 0); ossimDpt pLR (inputImgSize.x-1, inputImgSize.y-1); ossimDpt pLL (0, inputImgSize.y-1); ossimGpt gUL, gUR, gLR, gLL; inputGeom->localToWorld(pUL, gUL); inputGeom->localToWorld(pUR, gUR); inputGeom->localToWorld(pLR, gLR); inputGeom->localToWorld(pLL, gLL); // The -y axis relative to North is the number we need to rotate, so subtract 90 deg from // x-axis orientation. double mapRotation = gLL.azimuthTo(gUL); cout << "\n Rotating map by "<applyRotation(mapRotation); // Not sure where the UL of the rotated map will be, so assume it will coincide with the image // UL for now, then scan for corners outside: mapProj->setUlGpt(gUL); mapProj->worldToLineSample(gUR, pUR); mapProj->worldToLineSample(gLR, pLR); mapProj->worldToLineSample(gLL, pLL); ossimDrect drect (pUL, pUR, pLR, pLL); // A new output image rect has been established, find the corresponding UL ground point // and set projection's tiepoint: mapProj->lineSampleToWorld(drect.ul(), gUL); mapProj->setUlGpt(gUL); } catch (ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "ossimChipperUtil::rotateMapToInput() -- Exception: " << e.what() <<" Ignoring request.\n"; } return; } void ossimChipperUtil::createIdentityProjection() { static const char MODULE[] = "ossimChipperUtil::createIdentityProjection"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } // Get the singe image chain. Sould be only one. ossimRefPtr sic = 0; if (m_demLayer.size()) { sic = m_demLayer[0]; } else if (m_imgLayer.size()) { sic = m_imgLayer[0]; } if (sic.valid()) { // Get the image handler. ossimRefPtr ih = sic->getImageHandler(); // Resampler: ossimRefPtr resampler = sic->getImageRenderer(); if (ih.valid()) { //--- // Get the geometry from the image handler. Since we're in "identity" // mode use the inputs for the outputs. //--- m_geom = ih->getImageGeometry(); if (m_geom.valid()) { ossim_float64 rotation = 0.0; if (upIsUp()) { ossimRefPtr proj = m_geom->getProjection(); if (proj.valid()) { rotation = m_geom->upIsUpAngle(); } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: No projection to compute the up is up angle!" << std::endl; } } else if (northUp()) { ossimRefPtr proj = m_geom->getProjection(); if (proj.valid()) { rotation = m_geom->northUpAngle(); } else { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: No projection to compute the North up angle!" << std::endl; } } else if (hasRotation()) { rotation = getRotation(); } if (ossim::isnan(rotation)) { rotation = 0.0; } ossimDpt imageSpaceScale; getImageSpaceScale(imageSpaceScale); //ossimDrect rect; //m_geom->getBoundingRect(rect); ossimDpt midPt; // = rect.midPoint(); getImageSpacePivot(midPt); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << "\nAffine transform parameters:" << "\nrotation: " << rotation << "\nmid point: " << midPt << std::endl; } m_ivt = new ossimImageViewAffineTransform(-rotation, imageSpaceScale.x, // image space scale x imageSpaceScale.y, // image space scale y 1.0, 1.0, //scale x and y 0.0, 0.0, // translate x,y midPt.x * imageSpaceScale.x, midPt.y * imageSpaceScale.y); // pivot point if (m_kwl->hasKey(METERS_KW) || m_kwl->hasKey(DEGREES_X_KW) || m_kwl->hasKey(RRDS_KW)) { // Set the image view transform scale. initializeIvtScale(); } resampler->setImageViewTransform(m_ivt.get()); } // Matches: if ( m_geom.valid() ) } // Matches: if ( ih.valid() ) } // Matches: if ( sic.valid() } // End: createIdentityProjection() void ossimChipperUtil::initializeIvtScale() { if (isChipMode() && m_ivt.valid() && m_geom.valid()) { ossimDpt scale; scale.makeNan(); // Check for GSD spec. Degrees/pixel takes priority over meters/pixel: ossimString lookup; lookup.string() = m_kwl->findKey(DEGREES_X_KW); if (lookup.size()) { ossimDpt outputDpp; outputDpp.makeNan(); outputDpp.x = lookup.toFloat64(); lookup.string() = m_kwl->findKey(DEGREES_Y_KW); if (lookup.size()) { outputDpp.y = lookup.toFloat64(); } if (!outputDpp.hasNans()) { // Input degress per pixel. Consider this a scale of 1.0. ossimDpt inputDpp; m_geom->getDegreesPerPixel(inputDpp); if (!inputDpp.hasNans()) { scale.x = inputDpp.x / outputDpp.x; scale.y = inputDpp.y / outputDpp.y; } } } if (scale.hasNans()) { lookup = m_kwl->findKey(METERS_KW); if (lookup.size()) { ossimDpt outputMpp; outputMpp.makeNan(); outputMpp.x = lookup.toFloat64(); outputMpp.y = outputMpp.x; if (!outputMpp.hasNans()) { // Input meters per pixel. Consider this a scale of 1.0. ossimDpt inputMpp; m_geom->getMetersPerPixel(inputMpp); if (!inputMpp.hasNans()) { scale.x = inputMpp.x / outputMpp.x; scale.y = inputMpp.y / outputMpp.y; } } } } if (scale.hasNans()) { lookup = m_kwl->findKey(RRDS_KW); if (lookup.size()) { ossim_float64 d = lookup.toInt32(); if (d == 0.0) { scale.x = 1.0; } else { scale.x = 1.0 / std::pow(2.0, d); } scale.y = scale.x; } } if (!scale.hasNans()) { m_ivt->scale(scale.x, scale.y); } else { std::string errMsg = "ossimChipperUtil::initializeIvtScale failed!"; throw ossimException(errMsg); } } // Matches: if ( isChipMode() && ... ) } // End: ossimChipperUtil::initializeIvtScale() void ossimChipperUtil::initializeProjectionTiePoint () { static const char MODULE[] = "ossimChipperUtil::initializeProjectionTiePoint()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } // Get the map projection from the output geometry: ossimRefPtr mapProj = getMapProjection(); if (mapProj.valid()) { //--- // If the output is geographic of there are sensor model inputs, get the tie // using the ground point. //--- if (mapProj->isGeographic() || hasSensorModelInput()) { ossimGpt tiePoint; tiePoint.makeNan(); getTiePoint(tiePoint); if (!tiePoint.hasNans()) { //--- // The tie point coordinates currently reflect the UL edge of the UL pixel. // We'll need to shift the tie point bac from the edge to the center base on the // output gsd. //--- ossimDpt half_pixel_shift = m_geom->getDegreesPerPixel() * 0.5; tiePoint.lat -= half_pixel_shift.lat; tiePoint.lon += half_pixel_shift.lon; mapProj->setUlTiePoints(tiePoint); } else { std::string errMsg = MODULE; errMsg += " tie point has nans!"; throw(ossimException(errMsg)); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "projection tie point: " << tiePoint << "\n" << MODULE << " exited...\n"; } } else { //--- // TODO: Add test for like input projections and use above geographic tie // code if not. //--- ossimDpt tiePoint; tiePoint.makeNan(); getTiePoint(tiePoint); if (!tiePoint.hasNans()) { //--- // The tie point coordinates currently reflect the UL edge of the UL pixel. // We'll need to shift the tie point bac from the edge to the center base on the // output gsd. //--- ossimDpt half_pixel_shift = m_geom->getMetersPerPixel() * 0.5; tiePoint.y -= half_pixel_shift.y; tiePoint.x += half_pixel_shift.x; mapProj->setUlTiePoints(tiePoint); } else { std::string errMsg = MODULE; errMsg += " tie point has nans!"; throw(ossimException(errMsg)); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "projection tie point: " << tiePoint << "\n" << MODULE << " exited...\n"; } } } // Matches: if ( mapProj.valid() ) else { std::string errMsg = MODULE; errMsg += "m_projection is null!"; throw(ossimException(errMsg)); } } void ossimChipperUtil::initializeProjectionGsd() { static const char MODULE[] = "ossimChipperUtil::initializeProjectionGsd()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr mapProj = getMapProjection(); if (!mapProj.valid()) { std::string errMsg = MODULE; errMsg += " projection is null!"; throw(ossimException(errMsg)); } ossimDpt gsd; gsd.makeNan(); ossimString degreesX; ossimString degreesY; ossimString meters; degreesX.string() = m_kwl->findKey(DEGREES_X_KW); degreesY.string() = m_kwl->findKey(DEGREES_Y_KW); meters.string() = m_kwl->findKey(METERS_KW); if (hasCutBoxWidthHeight()) { // --cut-bbox-llwh Implies a scale... if (degreesX.size() || degreesY.size() || meters.size()) { std::ostringstream errMsg; errMsg << MODULE << " ERROR: Ambiguous scale keywords!\n" << "Do not combine meters or degrees with cut box with a width and height.\n"; throw(ossimException(errMsg.str())); } ossimString cutMinLat; ossimString cutMinLon; ossimString cutMaxLat; ossimString cutMaxLon; ossimString cutWidth; ossimString cutHeight; cutMinLat.string() = m_kwl->findKey(CUT_MIN_LAT_KW); cutMinLon.string() = m_kwl->findKey(CUT_MIN_LON_KW); cutMaxLat.string() = m_kwl->findKey(CUT_MAX_LAT_KW); cutMaxLon.string() = m_kwl->findKey(CUT_MAX_LON_KW); cutWidth.string() = m_kwl->findKey(CUT_WIDTH_KW); cutHeight.string() = m_kwl->findKey(CUT_HEIGHT_KW); if (cutMinLat.size() && cutMinLon.size() && cutMaxLat.size() && cutMaxLon.size() && cutWidth.size() && cutHeight.size()) { ossim_float64 minLat = cutMinLat.toFloat64(); ossim_float64 minLon = cutMinLon.toFloat64(); ossim_float64 maxLat = cutMaxLat.toFloat64(); ossim_float64 maxLon = cutMaxLon.toFloat64(); ossim_float64 width = cutWidth.toFloat64(); ossim_float64 height = cutHeight.toFloat64(); if (!ossim::isnan(minLat) && !ossim::isnan(minLon) && !ossim::isnan(maxLat) && !ossim::isnan(maxLon) && !ossim::isnan(width) && !ossim::isnan(height)) { gsd.x = std::fabs(maxLon - minLon) / width; gsd.y = std::fabs(maxLat - minLat) / height; mapProj->setDecimalDegreesPerPixel(gsd); } } } else if (hasWmsBboxCutWidthHeight()) { ossimString cutWidth; ossimString cutHeight; ossimString cutWmsBbox; cutWidth.string() = m_kwl->findKey(CUT_WIDTH_KW); cutHeight.string() = m_kwl->findKey(CUT_HEIGHT_KW); cutWmsBbox.string() = m_kwl->findKey(CUT_WMS_BBOX_KW); cutWmsBbox = cutWmsBbox.upcase().replaceAllThatMatch("BBOX:", ""); std::vector cutBox = cutWmsBbox.split(","); if (cutBox.size() == 4) { ossim_float64 minx = cutBox[0].toFloat64(); ossim_float64 miny = cutBox[1].toFloat64(); ossim_float64 maxx = cutBox[2].toFloat64(); ossim_float64 maxy = cutBox[3].toFloat64(); ossim_float64 width = cutWidth.toFloat64(); ossim_float64 height = cutHeight.toFloat64(); gsd.x = std::fabs(maxx - minx) / width; gsd.y = std::fabs(maxy - miny) / height; // bbox is in the units of the projector if (mapProj->isGeographic()) { mapProj->setDecimalDegreesPerPixel(gsd); } else { mapProj->setMetersPerPixel(gsd); } } else { std::ostringstream errMsg; errMsg << MODULE << " ERROR: cut box does not have 4 values!\n"; throw(ossimException(errMsg.str())); } } else { if (meters.size() && (degreesX.size() || degreesY.size())) { std::ostringstream errMsg; errMsg << MODULE << " ERROR: Ambiguous scale keywords!\n" << "Do not combine meters with degrees.\n"; throw(ossimException(errMsg.str())); } if (degreesX.size()) { // --degrees gsd.x = degreesX.toFloat64(); if (degreesY.size()) { gsd.y = degreesY.toFloat64(); } if (!gsd.hasNans()) { mapProj->setDecimalDegreesPerPixel(gsd); } } else if (meters.size()) { // --meters gsd.x = meters.toFloat64(); gsd.y = gsd.x; if (!gsd.hasNans()) { mapProj->setMetersPerPixel(gsd); } } } if (gsd.hasNans()) { // Get the best resolution from the inputs. getMetersPerPixel(gsd); // See if the output projection is geo-scaled; if so, make the pixels square in meters. if (getOutputProjectionType() == ossimChipperUtil::OSSIM_CHIPPER_PROJ_GEO_SCALED) { // Pick the best resolution and make them both the same. gsd.x = ossim::min(gsd.x, gsd.y); gsd.y = gsd.x; } // Set to input gsd. mapProj->setMetersPerPixel(gsd); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "projection gsd: " << gsd << "\n" << MODULE << " exited...\n"; } } void ossimChipperUtil::getTiePoint(ossimGpt &tie) { static const char MODULE[] = "ossimChipperUtil::getTiePoint(ossimGpt&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::vector>::iterator chainIdx; tie.lat = ossim::nan(); tie.lon = ossim::nan(); tie.hgt = 0.0; // Loop through dem layers. ossimGpt chainTiePoint; chainIdx = m_demLayer.begin(); while (chainIdx != m_demLayer.end()) { getTiePoint((*chainIdx).get(), chainTiePoint); if (tie.hasNans()) { tie = chainTiePoint; } else { if (chainTiePoint.lat > tie.lat) { tie.lat = chainTiePoint.lat; } if (chainTiePoint.lon < tie.lon) { tie.lon = chainTiePoint.lon; } } ++chainIdx; } // Loop through image layers. chainIdx = m_imgLayer.begin(); while (chainIdx != m_imgLayer.end()) { getTiePoint((*chainIdx).get(), chainTiePoint); if (tie.hasNans()) { tie = chainTiePoint; } else { if (chainTiePoint.lat > tie.lat) { tie.lat = chainTiePoint.lat; } if (chainTiePoint.lon < tie.lon) { tie.lon = chainTiePoint.lon; } } ++chainIdx; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "tie point: " << tie << "\n" << MODULE << " exited...\n"; } } void ossimChipperUtil::getTiePoint(ossimSingleImageChain *chain, ossimGpt &tie) { static const char MODULE[] = "ossimChipperUtil::getTiePoint(ossimSingleImageChain*,ossimGpt&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } if (chain && m_geom.valid()) { //--- // The view is not set yet in the chain so we get the tie point from the // image handler geometry not from the chain which will come from the // ossimImageRenderer. //--- ossimRefPtr ih = chain->getImageHandler(); if (ih.valid()) { ossimRefPtr geom = ih->getImageGeometry(); if (geom.valid()) { geom->getTiePoint(tie, true); } // Set height to 0.0 even though it's not used so hasNans test works. tie.hgt = 0.0; if (tie.hasNans()) { std::string errMsg = MODULE; errMsg += "\ngeom->localToWorld returned nan for chain."; errMsg += "\nChain: "; errMsg += chain->getFilename().string(); throw ossimException(errMsg); } } else { std::string errMsg = MODULE; errMsg += "\nNo geometry for chain: "; errMsg += chain->getFilename().string(); throw ossimException(errMsg); } } else { std::string errMsg = MODULE; errMsg += " ERROR: Null chain passed to method!"; throw ossimException(errMsg); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "chain name: " << chain->getFilename() << "\ntie point: " << tie << "\n" << MODULE << " exited...\n"; } } void ossimChipperUtil::getTiePoint(ossimDpt &tie) { static const char MODULE[] = "ossimChipperUtil::getTiePoint(ossimDpt&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::vector>::iterator chainIdx; tie.makeNan(); // Loop through dem layers. ossimDpt chainTiePoint; chainIdx = m_demLayer.begin(); while (chainIdx != m_demLayer.end()) { getTiePoint((*chainIdx).get(), chainTiePoint); if (tie.hasNans()) { tie = chainTiePoint; } else { if (chainTiePoint.y > tie.y) { tie.y = chainTiePoint.y; } if (chainTiePoint.x < tie.x) { tie.x = chainTiePoint.x; } } ++chainIdx; } // Loop through image layers. chainIdx = m_imgLayer.begin(); while (chainIdx != m_imgLayer.end()) { getTiePoint((*chainIdx).get(), chainTiePoint); if (tie.hasNans()) { tie = chainTiePoint; } else { if (chainTiePoint.y > tie.y) { tie.y = chainTiePoint.y; } if (chainTiePoint.x < tie.x) { tie.x = chainTiePoint.x; } } ++chainIdx; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "tie point: " << tie << "\n" << MODULE << " exited...\n"; } } void ossimChipperUtil::getTiePoint(ossimSingleImageChain *chain, ossimDpt &tie) { static const char MODULE[] = "ossimChipperUtil::getTiePoint(ossimSingleImageChain*,ossimDpt&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } if (chain && m_geom.valid()) { //--- // The view is not set yet in the chain so we get the tie point from the // image handler geometry not from the chain which will come from the // ossimImageRenderer. //--- ossimRefPtr ih = chain->getImageHandler(); if (ih.valid()) { ossimRefPtr geom = ih->getImageGeometry(); if (geom.valid()) { geom->getTiePoint(tie, true); } if (tie.hasNans()) { std::string errMsg = MODULE; errMsg += "\ngeom->localToWorld returned nan for chain."; errMsg += "\nChain: "; errMsg += chain->getFilename().string(); throw ossimException(errMsg); } } else { std::string errMsg = MODULE; errMsg += "\nNo geometry for chain: "; errMsg += chain->getFilename().string(); throw ossimException(errMsg); } } else { std::string errMsg = MODULE; errMsg += " ERROR: Null chain passed to method!"; throw ossimException(errMsg); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "chain name: " << chain->getFilename() << "\ntie point: " << tie << "\n" << MODULE << " exited...\n"; } } void ossimChipperUtil::getMetersPerPixel(ossimDpt &gsd) { static const char MODULE[] = "ossimChipperUtil::getMetersPerPixel(ossimDpt&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } gsd.makeNan(); ossimDpt chainGsd; std::vector>::iterator chainIdx; // Loop through dem layers. chainIdx = m_demLayer.begin(); while (chainIdx != m_demLayer.end()) { getMetersPerPixel((*chainIdx).get(), chainGsd); if (gsd.hasNans() || (chainGsd.x < gsd.x)) { gsd = chainGsd; } ++chainIdx; } // Loop through image layers. chainIdx = m_imgLayer.begin(); while (chainIdx != m_imgLayer.end()) { getMetersPerPixel((*chainIdx).get(), chainGsd); if (gsd.hasNans() || (chainGsd.x < gsd.x)) { gsd = chainGsd; } ++chainIdx; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "gsd: " << gsd << "\n" << MODULE << " exited...\n"; } } void ossimChipperUtil::getMetersPerPixel(ossimSingleImageChain *chain, ossimDpt &gsd) { static const char MODULE[] = "ossimChipperUtil::getMetersPerPixel(ossimSingleImageChain*,ossimDpt&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } if (chain) { ossimRefPtr geom = chain->getImageGeometry(); if (geom.valid()) { geom->getMetersPerPixel(gsd); if (gsd.hasNans()) { std::string errMsg = MODULE; errMsg += "\ngeom->getMetersPerPixel returned nan for chain."; errMsg += "\nChain: "; errMsg += chain->getFilename().string(); throw ossimException(errMsg); } } else { std::string errMsg = MODULE; errMsg += "\nNo geometry for chain: "; errMsg += chain->getFilename().string(); throw ossimException(errMsg); } } else { std::string errMsg = MODULE; errMsg += " ERROR: Null chain passed to method!"; throw ossimException(errMsg); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "chain name: " << chain->getFilename() << "\nmeters per pixel: " << gsd << "\n" << MODULE << " exited...\n"; } } ossim_float64 ossimChipperUtil::getCentralMeridian() const { ossim_float64 result = ossim::nan(); ossimString lookup = m_kwl->findKey(std::string(ossimKeywordNames::CENTRAL_MERIDIAN_KW)); if (lookup.size()) { result = lookup.toFloat64(); if ((result < -180.0) || (result > 180.0)) { std::string errMsg = "central meridian range error!"; errMsg += " Valid range: -180 to 180"; throw ossimException(errMsg); } } return result; } ossim_float64 ossimChipperUtil::getOriginLatitude() const { ossim_float64 result = ossim::nan(); ossimString lookup = m_kwl->find(ossimKeywordNames::ORIGIN_LATITUDE_KW); if (lookup.size()) { result = lookup.toFloat64(); if ((result < -90) || (result > 90.0)) { std::string errMsg = "origin latitude range error!"; errMsg += " Valid range: -90 to 90"; throw ossimException(errMsg); } } return result; } void ossimChipperUtil::getSceneCenter(ossimGpt &gpt) { static const char MODULE[] = "ossimChipperUtil::getSceneCenter(ossimGpt&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::vector centerGptArray; ossimGpt centerGpt; std::vector>::iterator chainIdx; // Loop through dem layers. chainIdx = m_demLayer.begin(); while (chainIdx != m_demLayer.end()) { getSceneCenter((*chainIdx).get(), centerGpt); if (!centerGpt.hasNans()) { centerGptArray.push_back(centerGpt); } ++chainIdx; } // Loop through image layers. chainIdx = m_imgLayer.begin(); while (chainIdx != m_imgLayer.end()) { getSceneCenter((*chainIdx).get(), centerGpt); if (!centerGpt.hasNans()) { centerGptArray.push_back(centerGpt); } ++chainIdx; } ossim_float64 lat = 0.0; ossim_float64 lon = 0.0; std::vector::const_iterator pointIdx = centerGptArray.begin(); while (pointIdx != centerGptArray.end()) { lat += (*pointIdx).lat; lon += (*pointIdx).lon; ++pointIdx; } lat /= centerGptArray.size(); lon /= centerGptArray.size(); if ((lat >= -90.0) && (lat <= 90.0) && (lon >= -180.0) && (lon <= 180.0)) { gpt.lat = lat; gpt.lon = lon; } else { std::ostringstream errMsg; errMsg << MODULE << " range error!\nlatitude = " << ossimString::toString(lat).string() << "\nlongitude = " << ossimString::toString(lon).string(); throw ossimException(errMsg.str()); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "scene center: " << gpt << "\n" << MODULE << " exited...\n"; } } void ossimChipperUtil::getSceneCenter(ossimSingleImageChain *chain, ossimGpt &gpt) { static const char MODULE[] = "ossimChipperUtil::getSceneCenter(const ossimSingleImageChain*,ossimGpt&)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } if (chain) { ossimRefPtr geom = chain->getImageGeometry(); if (geom.valid()) { ossimIrect boundingRect = chain->getBoundingRect(); ossimDpt midPoint = boundingRect.midPoint(); geom->localToWorld(midPoint, gpt); gpt.hgt = 0.0; if (gpt.hasNans()) { std::string errMsg = MODULE; errMsg += "\ngeom->localToWorld returned nan for chain."; errMsg += "\nChain: "; errMsg += chain->getFilename().string(); throw ossimException(errMsg); } } else { std::string errMsg = MODULE; errMsg += "\nNo geometry for chain: "; errMsg += chain->getFilename().string(); throw ossimException(errMsg); } } else { std::string errMsg = MODULE; errMsg += " ERROR: Null chain passed to method!"; throw ossimException(errMsg); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "chain name: " << chain->getFilename() << "\nscene center: " << gpt << "\n" << MODULE << " exited...\n"; } } ossimRefPtr ossimChipperUtil::getFirstInputProjection() { static const char MODULE[] = "ossimChipperUtil::getFirstInputProjection"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr ih = 0; ossimRefPtr result = 0; // Get the first image handler. if (m_demLayer.size()) { ih = m_demLayer[0]->getImageHandler(); } else if (m_imgLayer.size()) { ih = m_imgLayer[0]->getImageHandler(); } if (ih.valid()) { // Get the geometry from the first image handler. ossimRefPtr geom = ih->getImageGeometry(); if (geom.valid()) { // Get the image projection. ossimRefPtr proj = geom->getProjection(); if (proj.valid()) { // Cast and assign to result. ossimMapProjection *mapProj = PTR_CAST(ossimMapProjection, proj.get()); if (mapProj) { // Must duplicate in case the output projection gets modified. result = (ossimMapProjection *)mapProj->dup(); } if (!result.valid() && traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "Could not cast to map projection.\n"; } } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "No projection in first chain...\n"; } } } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "No image handler in first chain...\n"; } if (traceDebug()) { if (result.valid()) { result->print(ossimNotify(ossimNotifyLevel_DEBUG)); } ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return result; } ossimRefPtr ossimChipperUtil::getNewGeoProjection() { return ossimRefPtr(new ossimEquDistCylProjection()); } ossimRefPtr ossimChipperUtil::getNewGeoScaledProjection() { // Make projection: ossimRefPtr result = getNewGeoProjection(); // Set the origin for scaling: // First check for user set "central_meridian" and "origin_latitude": ossimGpt origin; origin.lat = getOriginLatitude(); origin.lon = getCentralMeridian(); origin.hgt = 0.0; if (origin.hasNans()) { // Use the scene center from the input. getSceneCenter(origin); //--- // Note only latitude used for scaling, origin kept at 0.0. // This is a fix/hack for ossimEquDistCylProjection wrapping issues. //--- origin.lon = 0.0; } if (!origin.hasNans()) { result->setOrigin(origin); } else { std::string errMsg = "ossimChipperUtil::getNewGeoScaledProjection ERROR"; errMsg += "\nOrigin has nans!"; throw ossimException(errMsg); } return result; } ossimRefPtr ossimChipperUtil::getNewProjectionFromSrsCode( const std::string &code) { ossimRefPtr result = 0; ossimString os = code; os.downcase(); if ((os == "epsg:4326") || (code == "4326")) { // Avoid factory call for this. result = new ossimEquDistCylProjection(); } else { ossimRefPtr proj = ossimProjectionFactoryRegistry::instance()->createProjection(code); if (proj.valid()) { result = PTR_CAST(ossimMapProjection, proj.get()); } } return result; } ossimRefPtr ossimChipperUtil::getNewUtmProjection() { // Make projection: ossimRefPtr utm = new ossimUtmProjection; // Set the zone from keyword option: bool setZone = false; ossim_int32 zone = getZone(); if ((zone > 0) && (zone < 61)) { utm->setZone(zone); setZone = true; } // Set the hemisphere from keyword option: bool setHemisphere = false; std::string hemisphere = getHemisphere(); if (hemisphere.size()) { ossimString h(hemisphere); h.upcase(); if ((h == "N") || (h == "NORTH")) { char c = 'N'; utm->setHemisphere(c); setHemisphere = true; } if ((h == "S") || (h == "SOUTH")) { char c = 'S'; utm->setHemisphere(c); setHemisphere = true; } } if (!setZone || !setHemisphere) { // First check for user set "central_meridian" and "origin_latitude": ossimGpt origin; origin.lat = getOriginLatitude(); origin.lon = getCentralMeridian(); origin.hgt = 0.0; if (origin.hasNans()) { // Use the scene center from the input. getSceneCenter(origin); } if (!origin.hasNans()) { if (!setZone) { utm->setZone(origin); } if (!setHemisphere) { utm->setHemisphere(origin); } } else { std::string errMsg = "ossimChipperUtil::getNewUtmProjection ERROR"; errMsg += "\nOrigin has nans!"; throw ossimException(errMsg); } } return ossimRefPtr(utm.get()); } ossimRefPtr ossimChipperUtil::getMapProjection() { ossimRefPtr mp = 0; if (m_geom.valid()) { mp = dynamic_cast(m_geom->getProjection()); } return mp; } ossimRefPtr ossimChipperUtil::createNewWriter() const { static const char MODULE[] = "ossimChipperUtil::createNewWriter()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimFilename outputFile; getOutputFilename(outputFile); if (outputFile == ossimFilename::NIL) { std::string errMsg = MODULE; errMsg += " ERROR no output file name!"; throw ossimException(errMsg); } ossimRefPtr writer = 0; ossimString lookup = m_kwl->findKey(WRITER_KW); if (lookup.size()) { writer = ossimImageWriterFactoryRegistry::instance()->createWriter(lookup); if (!writer.valid()) { std::string errMsg = MODULE; errMsg += " ERROR creating writer: "; errMsg += lookup.string(); throw ossimException(errMsg); } } else // Create from output file extension. { writer = ossimImageWriterFactoryRegistry::instance()->createWriterFromExtension(outputFile.ext()); if (!writer.valid()) { std::string errMsg = MODULE; errMsg += " ERROR creating writer from extension: "; errMsg += outputFile.ext().string(); throw ossimException(errMsg); } } // Set the output name. writer->setFilename(outputFile); // Add any writer props. ossim_uint32 count = m_kwl->numberOf(WRITER_PROPERTY_KW.c_str()); for (ossim_uint32 i = 0; i < count; ++i) { ossimString key = WRITER_PROPERTY_KW; key += ossimString::toString(i); lookup = m_kwl->findKey(key.string()); if (lookup.size()) { std::vector splitArray; lookup.split(splitArray, "="); if (splitArray.size() == 2) { ossimRefPtr prop = new ossimStringProperty(splitArray[0], splitArray[1]); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Setting writer prop: " << splitArray[0] << "=" << splitArray[1] << "\n"; } writer->setProperty(prop); } } } // Output tile size: lookup = m_kwl->findKey(TILE_SIZE_KW); if (lookup.size()) { ossimIpt tileSize; tileSize.x = lookup.toInt32(); if ((tileSize.x % 16) == 0) { tileSize.y = tileSize.x; writer->setTileSize(tileSize); } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_NOTICE) << MODULE << " NOTICE:" << "\nTile width must be a multiple of 16! Using default.." << std::endl; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "writer name: " << writer->getClassName() << "\n" << MODULE << " exited...\n"; } return writer; } ossimIrect viewToImage(ossimRefPtr ivt, const ossimIrect& viewRect) { ossimIrect result; ossimDpt ul,ur,lr,ll; ivt->viewToImage(viewRect.ul(), ul); ivt->viewToImage(viewRect.ur(), ur); ivt->viewToImage(viewRect.lr(), lr); ivt->viewToImage(viewRect.ll(), ll); result = ossimDrect(ul, ur, lr, ll); if(result.width() > 1024 || result.height() > 1024) { ossim_int64 w = ossim::min(static_cast(result.width()), static_cast(1024)); ossim_int64 h = ossim::min(static_cast(result.height()), static_cast(1024)); if(w < 64) w = 64; if(h < 64) h = 64; result = ossimIrect(ossimIpt(result.midPoint()), w, h); } return result; } void ossimChipperUtil::propagateViewportStretch(const ossimIrect& rect) { //for now we will do it on each image chaing std::vector >::iterator chainIdx; // Loop through dem layers. chainIdx = m_demLayer.begin(); while (chainIdx != m_demLayer.end()) { ossimRefPtr remapper = (*chainIdx)->getHistogramRemapper(); ossimRefPtr resampler = (*chainIdx)->getImageRenderer(); if (resampler.valid()) { ossimRefPtr ivt = resampler->getImageViewTransform(); if (ivt.valid() && remapper.valid()) { ossimIrect imageRect = viewToImage(ivt, rect); remapper->setEnableFlag(true); remapper->computeHistogram(imageRect); } } ++chainIdx; } // Loop through image layers. chainIdx = m_imgLayer.begin(); while (chainIdx != m_imgLayer.end()) { ossimRefPtr remapper = (*chainIdx)->getHistogramRemapper(); ossimRefPtr resampler = (*chainIdx)->getImageRenderer(); if (resampler.valid()) { ossimRefPtr ivt = resampler->getImageViewTransform(); if (ivt.valid()&&remapper.valid()) { ossimIrect imageRect = viewToImage(ivt, rect); remapper->setEnableFlag(true); remapper->computeHistogram(imageRect); } } ++chainIdx; } } void ossimChipperUtil::propagateOutputProjectionToChains() { static const char MODULE[] = "ossimChipperUtil::propagateOutputProjectionToChains()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::vector>::iterator chainIdx; // we need to make sure the outputs are refreshed so they can reset themselves // Needed when we are doing interactive update to the GSD and clip window ossimRefPtr refreshEvent = new ossimRefreshEvent(); ossimEventVisitor eventVisitor(refreshEvent.get()); ossimViewInterfaceVisitor viewVisitor(m_geom.get()); // Loop through dem layers. chainIdx = m_demLayer.begin(); while (chainIdx != m_demLayer.end()) { viewVisitor.reset(); eventVisitor.reset(); (*chainIdx)->accept(viewVisitor); (*chainIdx)->accept(eventVisitor); ossimRefPtr resampler = (*chainIdx)->getImageRenderer(); if (resampler.valid()) { //resampler->setView( m_geom.get() ); // resampler->propagateEventToOutputs(refreshEvent); } else { std::string errMsg = MODULE; errMsg += " chain has no resampler!"; throw(ossimException(errMsg)); } ++chainIdx; } // Loop through image layers. chainIdx = m_imgLayer.begin(); while (chainIdx != m_imgLayer.end()) { ossimRefPtr resampler = (*chainIdx)->getImageRenderer(); eventVisitor.reset(); viewVisitor.reset(); (*chainIdx)->accept(viewVisitor); (*chainIdx)->accept(eventVisitor); if (resampler.valid()) { //resampler->setView( m_geom.get() ); //resampler->propagateEventToOutputs(refreshEvent); } else { std::string errMsg = MODULE; errMsg += " chain has no resampler!"; throw(ossimException(errMsg)); } ++chainIdx; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } ossimRefPtr ossimChipperUtil::combineLayers( std::vector> &layers) const { static const char MODULE[] = "ossimChipperUtil::combineLayers(layers)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr result = 0; if (layers.size() == 1) { result = layers[0].get(); } else if (layers.size() > 1) { result = createCombiner(); //new ossimImageMosaic; std::vector>::iterator chainIdx = layers.begin(); while (chainIdx != layers.end()) { result->connectMyInputTo((*chainIdx).get()); ++chainIdx; } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return result; } ossimRefPtr ossimChipperUtil::combineLayers() { static const char MODULE[] = "ossimChipperUtil::combineLayers()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr result = 0; ossim_uint32 layerCount = (ossim_uint32)(m_demLayer.size() + m_imgLayer.size()); if (layerCount) { if (layerCount == 1) { if (m_imgLayer.size()) { result = m_imgLayer[0].get(); } else { result = m_demLayer[0].get(); } } else { result = createCombiner(); //new ossimImageMosaic; // Combine the images. Note we'll put the images on top of the dems. if (m_imgLayer.size()) { std::vector>::iterator chainIdx = m_imgLayer.begin(); while (chainIdx != m_imgLayer.end()) { result->connectMyInputTo((*chainIdx).get()); ++chainIdx; } } if (m_demLayer.size()) // Combine any dem layers. { std::vector>::iterator chainIdx = m_demLayer.begin(); while (chainIdx != m_demLayer.end()) { result->connectMyInputTo((*chainIdx).get()); ++chainIdx; } } } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return result; } // End: ossimChipperUtil::combineLayers ossimRefPtr ossimChipperUtil::initialize2CmvChain() { ossimRefPtr result = 0; ossim_uint32 layerCount = (ossim_uint32)(m_demLayer.size() + m_imgLayer.size()); // Must have two and only two inputs. if (layerCount == 2) { ossimRefPtr oldImg = 0; ossimRefPtr newImg = 0; //--- // Expecting two image layers. We'll code it for flexabilty though... // - Take old and new from m_imgLayer if present. // - Use m_demLayer only if missing. // - Using first image found as old, second new. //--- // Most likely case, two image layers. if (m_imgLayer.size()) { oldImg = m_imgLayer[0].get(); if (m_imgLayer.size() == 2) { newImg = m_imgLayer[1].get(); } } if (m_demLayer.size()) { if (!oldImg.valid()) { oldImg = m_demLayer[0].get(); } if (!newImg.valid()) { if (m_demLayer.size() == 1) { newImg = m_demLayer[0].get(); } else if (m_demLayer.size() == 2) { newImg = m_demLayer[1].get(); } } } if (newImg.valid() && oldImg.valid()) { // Input 0 is old, 1 is new. ossimRefPtr tcmv = new ossimTwoColorView; tcmv->connectMyInputTo(0, oldImg.get()); tcmv->connectMyInputTo(1, newImg.get()); // Look for 2cmv options. ossim_uint32 oldInputBandIndex = 0; ossim_uint32 newInputBandIndex = 0; ossimTwoColorView::ossimTwoColorMultiViewOutputSource redOutputSource = ossimTwoColorView::OLD; ossimTwoColorView::ossimTwoColorMultiViewOutputSource grnOutputSource = ossimTwoColorView::NEW; ossimTwoColorView::ossimTwoColorMultiViewOutputSource bluOutputSource = ossimTwoColorView::NEW; ossimString os; std::string key = TWOCMV_OLD_INPUT_BAND_KW; std::string val = m_kwl->findKey(key); if (val.size()) { os = val; oldInputBandIndex = os.toUInt32(); } key = TWOCMV_NEW_INPUT_BAND_KW; val = m_kwl->findKey(key); if (val.size()) { os = val; newInputBandIndex = os.toUInt32(); } key = TWOCMV_RED_OUTPUT_SOURCE_KW; val = m_kwl->findKey(key); if (val.size()) { os = val; os.downcase(); if (os == "new") { redOutputSource = ossimTwoColorView::NEW; } else if (os == "MIN") { redOutputSource = ossimTwoColorView::MIN; } } key = TWOCMV_GREEN_OUTPUT_SOURCE_KW; val = m_kwl->findKey(key); if (val.size()) { os = val; os.downcase(); if (os == "old") { grnOutputSource = ossimTwoColorView::OLD; } else if (os == "MIN") { grnOutputSource = ossimTwoColorView::MIN; } } key = TWOCMV_BLUE_OUTPUT_SOURCE_KW; val = m_kwl->findKey(key); if (val.size()) { os = val; os.downcase(); if (os == "old") { bluOutputSource = ossimTwoColorView::OLD; } else if (os == "MIN") { bluOutputSource = ossimTwoColorView::MIN; } } // Set options. tcmv->setBandIndexMapping(oldInputBandIndex, newInputBandIndex, redOutputSource, grnOutputSource, bluOutputSource); tcmv->initialize(); result = tcmv.get(); } } return result; } // ossimChipperUtil::initialize2CmvChain() ossimRefPtr ossimChipperUtil::addIndexToRgbLutFilter( ossimRefPtr &source) const { static const char MODULE[] = "ossimChipperUtil::addIndexToRgbLutFilter(source)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr result = 0; if (source.valid()) { ossimRefPtr lut = new ossimIndexToRgbLutFilter(); ossimFilename lutFile; lutFile.string() = m_kwl->findKey(LUT_FILE_KW); if (lutFile.exists()) { //--- // Connect to dems: // Must do this first so that the min and max get set from the input // connection prior to initializing the lut. //--- lut->connectMyInputTo(source.get()); // Note sure about this. Make option maybe? (drb) lut->setMode(ossimIndexToRgbLutFilter::REGULAR); lut->setLut(lutFile); // Set as color source for bump shade. result = lut.get(); } else { std::string errMsg = MODULE; errMsg += " color table does not exists: "; errMsg += lutFile.string(); throw ossimException(errMsg); } } else { std::string errMsg = MODULE; errMsg += " ERROR: Null source passed to method!"; throw ossimException(errMsg); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return result; } ossimRefPtr ossimChipperUtil::addScalarRemapper( ossimRefPtr &source, ossimScalarType scalar) const { static const char MODULE[] = "ossimChipperUtil::addScalarRemapper(source)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr result = 0; if (source.valid()) { if ((scalar != OSSIM_SCALAR_UNKNOWN) && (source->getOutputScalarType() != scalar)) { ossimRefPtr remapper = new ossimScalarRemapper(); remapper->setOutputScalarType(scalar); remapper->connectMyInputTo(source.get()); result = remapper.get(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nOutput remapped to: " << ossimScalarTypeLut::instance()->getEntryString(scalar) << "\n"; } } else { result = source; } } else { std::string errMsg = MODULE; errMsg += " ERROR: Null source passed to method!"; throw ossimException(errMsg); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return result; } ossimRefPtr ossimChipperUtil::addAnnotations( ossimRefPtr &source) const { static const char MODULE[] = "ossimChipperUtil::addAnnotations(source)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } ossimRefPtr result = 0; if (source.valid() & m_geom.valid()) { ossimString regularExpression = "annotation[0-9]*\\.type"; const ossim_uint32 COUNT = m_kwl->getNumberOfKeysThatMatch(regularExpression); if (COUNT > 0) { // Create annotator: ossimRefPtr annotator = new ossimAnnotationSource(); // Connect it up: annotator->connectMyInputTo(source.get()); // Loop through keyword list and add all annotation objects. ossim_uint32 i = 0; ossim_uint32 found = 0; std::string prefixBase = "annotation"; std::string prefix; std::string key; std::string value; while ((found < COUNT) && (i < (COUNT + 100))) { prefix = prefixBase + ossimString::toString(i).string() + "."; key = "type"; value = m_kwl->findKey(prefix, key); if (value.size()) { ++found; if (value == "cross_hair") { addCrossHairAnnotation(annotator, prefix); } } ++i; } annotator->initialize(); // Assign return result: result = annotator.get(); } } else { std::string errMsg = MODULE; errMsg += " ERROR: Null source passed to method!"; throw ossimException(errMsg); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return result; } void ossimChipperUtil::addCrossHairAnnotation( ossimRefPtr annotator, const std::string &prefix) const { if (annotator.valid() && prefix.size()) { std::string linePrefix = prefix + std::string("line."); std::string textPrefix = prefix + std::string("text."); ossimDpt centerPt; centerPt.makeNan(); ossim_float64 lineSize = 8.0; ossimDpt start; ossimDpt end; // Cross hair line location: std::string key = "location"; std::string value = m_kwl->findKey(linePrefix, key); if (value.size()) { if (value == "scene_center") { ossimIrect boundingRect = annotator->getBoundingRect(0); centerPt = boundingRect.midPoint(); } } else { key = "location.gpt"; value = m_kwl->findKey(linePrefix, key); if (value.size()) { ossimGpt gpt; gpt.toPoint(value); if (gpt.hasNans() == false) { // Convert to view coordinate. ossimDpt imgPt; m_geom->worldToLocal(gpt, imgPt); if (m_ivt.valid()) { m_ivt->imageToView(imgPt, centerPt); } else { centerPt = imgPt; } } } } if (centerPt.hasNans() == false) { // Cross hair size: key = "size"; value = m_kwl->findKey(linePrefix, key); if (value.size()) { lineSize = ossimString::toInt32(ossimString(value)); } ossim_float64 halfLine = lineSize / 2.0; // Create lines. ossimRefPtr line1 = new ossimAnnotationLineObject(); // Pick up r,g,b,thickness. line1->loadState(*(m_kwl.get()), linePrefix.c_str()); start.x = centerPt.x; start.y = centerPt.y - halfLine; end.x = centerPt.x; end.y = centerPt.y + halfLine; // ossimAnnotationLineObject::setLine recomputes the bounding box. line1->setLine(start, end); annotator->addObject(line1.get()); ossimRefPtr line2 = new ossimAnnotationLineObject(); // This will pick up r,g,b,thickness. line2->loadState(*(m_kwl.get()), linePrefix.c_str()); start.x = centerPt.x - halfLine; start.y = centerPt.y; end.x = centerPt.x + halfLine; end.y = centerPt.y; // ossimAnnotationLineObject::setLine recomputes the bounding box. line2->setLine(start, end); annotator->addObject(line2.get()); // Set text if any: key = "string"; value = m_kwl->findKey(textPrefix, key); if (value.size()) { ossimRefPtr text = new ossimAnnotationFontObject(); text->loadState(*(m_kwl.get()), textPrefix.c_str()); text->setString(ossimString(value)); // text scale: key = "scale"; value = m_kwl->findKey(textPrefix, key); if (value.size()) { ossimDpt scale; scale.toPoint(value); text->setScale(scale); } // text point size: key = "point_size"; value = m_kwl->findKey(textPrefix, key); if (value.size()) { ossimIpt ptSize; ptSize.toPoint(value); text->setPointSize(ptSize); } // text location: key = "location"; value = m_kwl->findKey(textPrefix, key); if (value.size()) { if (value == "bottom") { ossimIpt ipt; ipt.x = (ossim_int32)centerPt.x; ipt.y = (ossim_int32)(centerPt.y + halfLine + 10); text->setUpperLeftPosition(ipt); ossimDrect rect; text->getBoundingRect(rect); ipt.x = ipt.x - rect.width() / 2; text->setUpperLeftPosition(ipt); } } annotator->addObject(text.get()); } } } } // End: ossimChipperUtil::addCrossHairAnnotations( ... ) bool ossimChipperUtil::setupChainHistogram(ossimRefPtr &chain, std::shared_ptr srcRecordPtr) const { static const char MODULE[] = "ossimChipperUtil::setupChainHistogram(chain)"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } bool result = false; ossimHistogramRemapper::StretchMode mode = (ossimHistogramRemapper::StretchMode)getHistoMode(); if (chain.valid()) { ossimRefPtr ih = chain->getImageHandler(); ossimRefPtr remapper = chain->getHistogramRemapper(); if (ih.valid() && remapper.valid() && (mode != ossimHistogramRemapper::STRETCH_UNKNOWN)) { result = true; ossimString histCenterKw = m_kwl->findKey(HIST_CENTER_KW); if (histCenterKw.empty()) { histCenterKw = "false"; } bool roiStretch = (m_kwl->hasKey(HIST_AOI_KW) || m_kwl->hasKey(HIST_LLWH_KW) || histCenterKw.toBool()); if (!roiStretch) { bool openedHistogram = false; if (remapper->getHistogramFile() == ossimFilename::NIL) { ossimFilename f; if (srcRecordPtr) { f = srcRecordPtr->getHistogramPath(); } // Open histogram file. if (f.empty() || !f.exists()) { f = ih->getFilenameWithThisExtension(ossimString("his")); if (f.empty() || (f.exists() == false)) { // For backward compatibility check if single entry and _e0.his f = ih->getFilenameWithThisExtension(ossimString("his"), true); if (!f.exists()) f.clear(); } } if (!f.empty()) { openedHistogram = remapper->openHistogram(f); if (!openedHistogram && traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " WARNING:" << "\nCould not open: " << f << "\n"; } } if (!openedHistogram) { //--- // User requested a histogram operation but does not have // external histogram file. This will cause downstream code // to computer from center tile of image. //--- roiStretch = true; } } } // Enable and set mode: remapper->setEnableFlag(true); remapper->setStretchMode(mode); if (roiStretch) { ossimIrect aoi; std::string value = m_kwl->findKey(HIST_AOI_KW); if (value.size()) { result = getIrect(value, aoi); } else { value = m_kwl->findKey(HIST_LLWH_KW); if (value.size()) { result = getIrect(chain, value, aoi); } else // Use center of image. { // Will need to mark it to do a true computation later // for each chain. We do not set the request rect yet. // m_viewPortStretchEnabled = true; result = false;//getIrect(chain, aoi); } } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ROI of histogram: " << aoi << std::endl; } if (result) { ossimIrect newAoi = aoi; ossimDpt centerPoint; // we will clamp the region of interest if too large if ( aoi.width() > 2048 || aoi.height() > 2048) { ossim_int64 w = ossim::min(static_cast(aoi.width()), static_cast(2048)); ossim_int64 h = ossim::min(static_cast(aoi.height()), static_cast(2048)); aoi.getCenter(centerPoint); newAoi = ossimIrect(ossimIpt(centerPoint), w, h); } //--- // Note: both of these sections work. // Going with separate connection for now. drb - 20 Feb. 2016 // //--- #if 1 ossimRefPtr ihist = new ossimImageHistogramSource(); ihist->setAreaOfInterest(aoi); ihist->connectMyInputTo(remapper->getInput()); //ih.get()); remapper->connectMyInputTo(ihist.get()); #else remapper->computeHistogram(newAoi); #endif } } if (!result) { remapper->setEnableFlag(false); } setStretch(remapper); } // Matches: if ( ih.valid() && remapper.valid() && mode... ) } // Matches: if ( chain.valid() ) if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } return result; } bool ossimChipperUtil::setChainEntry( ossimRefPtr &chain, ossim_uint32 entryIndex) const { bool result = false; if (chain.valid()) { ossimRefPtr ih = chain->getImageHandler(); if (ih.valid()) { result = ih->setCurrentEntry(entryIndex); } } return result; } void ossimChipperUtil::getOutputFilename(ossimFilename &f) const { f.string() = m_kwl->findKey(std::string(ossimKeywordNames::OUTPUT_FILE_KW)); } void ossimChipperUtil::getAreaOfInterest(ossimImageSource *source, ossimIrect &rect) const { static const char MODULE[] = "ossimChipperUtil::getAreaOfInterest()"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } // Nan rect for starters. rect.makeNan(); if (source) { source->initialize(); // Ensure all bounding rectangles are set. if (m_kwl->hasKey(CUT_BBOX_XYWH_KW)) { // ,,, std::string cutBbox = m_kwl->findKey(CUT_BBOX_XYWH_KW); getIrect(cutBbox, rect); } if (rect.hasNans() && m_kwl->hasKey(FULLRES_XYS_KW) && m_kwl->hasKey(CUT_WIDTH_KW) && m_kwl->hasKey(CUT_HEIGHT_KW)) { ossimString tempFullXys = m_kwl->findKey(FULLRES_XYS_KW); ossimString tempWidth = m_kwl->findKey(CUT_WIDTH_KW); ossimString tempHeight = m_kwl->findKey(CUT_HEIGHT_KW); if (m_geom && m_ivt) { std::vector values; tempFullXys.split(values, ","); ossimDpt scale; ossimDpt location; scale.makeNan(); location.makeNan(); double w = tempWidth.toDouble(); double h = tempHeight.toDouble(); if (values.size() > 2) { location.x = values[0].toDouble(); location.y = values[1].toDouble(); ossimDpt mid; m_ivt->imageToView(location, mid); ossimIpt ul(ossim::round(mid.x - (w / 2)), ossim::round(mid.y - (h / 2))); ossimIpt lr((ul.x + w - 1), ul.y + h - 1); rect = ossimIrect(ul, lr); } } } if (rect.hasNans()) { if (m_geom.valid()) { if (m_kwl->find(CUT_CENTER_LAT_KW.c_str())) { // "Cut Center" with: --cut-center-llwh or --cut-center-llr: ossimString latStr = m_kwl->findKey(CUT_CENTER_LAT_KW); ossimString lonStr = m_kwl->findKey(CUT_CENTER_LON_KW); if (latStr.size() && lonStr.size()) { ossimGpt centerGpt; //--- // Want the height nan going into worldToLocal call so it gets picked // up by the elevation manager. //--- centerGpt.makeNan(); centerGpt.lat = latStr.toFloat64(); centerGpt.lon = lonStr.toFloat64(); if (!centerGpt.isLatNan() && !centerGpt.isLonNan()) { // Ground "cut center" to view: ossimDpt centerDpt(0.0, 0.0); m_geom->worldToLocal(centerGpt, centerDpt); if (!centerDpt.hasNans()) { if (isChipMode() && m_ivt.valid()) // Chipping in image space. { // Tranform image center point to view: ossimDpt ipt = centerDpt; m_ivt->imageToView(ipt, centerDpt); } // --cut-center-llwh: ossimString widthStr = m_kwl->findKey(CUT_WIDTH_KW); ossimString heightStr = m_kwl->findKey(CUT_HEIGHT_KW); if (widthStr.size() && heightStr.size()) { ossim_int32 width = widthStr.toInt32(); ossim_int32 height = heightStr.toInt32(); if (width && height) { ossimIpt ul(ossim::round(centerDpt.x - (width / 2)), ossim::round(centerDpt.y - (height / 2))); ossimIpt lr((ul.x + width - 1), ul.y + height - 1); rect = ossimIrect(ul, lr); } } else // --cut-center-llr: { ossimString radiusStr = m_kwl->findKey(CUT_RADIUS_KW); if (radiusStr.size()) { ossim_float64 radius = radiusStr.toFloat64(); if (radius) { ossimDpt mpp; m_geom->getMetersPerPixel(mpp); if (!mpp.hasNans()) { ossim_float64 rx = radius / mpp.x; ossim_float64 ry = radius / mpp.y; ossimIpt ul(ossim::round(centerDpt.x - rx), ossim::round(centerDpt.y - ry)); ossimIpt lr(ossim::round(centerDpt.x + rx), ossim::round(centerDpt.y + ry)); rect = ossimIrect(ul, lr); } } } } } } // Matches: if ( !centerGpt.hasNans() ) } // Matches: if ( latStr && lonStr ) } // Matches: if ( m_kwl->find( CUT_CENTER_LAT_KW ) ) else if (m_kwl->find(CUT_MAX_LAT_KW.c_str()) || m_kwl->find(CUT_WMS_BBOX_LL_KW.c_str())) { ossimString maxLat; ossimString maxLon; ossimString minLat; ossimString minLon; // --cut-bbox-ll or --cut-bbox-llwh if (m_kwl->find(CUT_MAX_LAT_KW.c_str())) { maxLat = m_kwl->findKey(CUT_MAX_LAT_KW); maxLon = m_kwl->findKey(CUT_MAX_LON_KW); minLat = m_kwl->findKey(CUT_MIN_LAT_KW); minLon = m_kwl->findKey(CUT_MIN_LON_KW); } else { ossimString cutBbox = m_kwl->findKey(CUT_WMS_BBOX_LL_KW); cutBbox = cutBbox.upcase().replaceAllThatMatch("BBOX:"); std::vector cutBox = cutBbox.split(","); if (cutBox.size() > 3) { minLon = cutBox[0]; minLat = cutBox[1]; maxLon = cutBox[2]; maxLat = cutBox[3]; } } if (maxLat.size() && maxLon.size() && minLat.size() && minLon.size()) { ossim_float64 minLatF = minLat.toFloat64(); ossim_float64 maxLatF = maxLat.toFloat64(); ossim_float64 minLonF = minLon.toFloat64(); ossim_float64 maxLonF = maxLon.toFloat64(); //--- // Check for swap so we don't get a negative height. // Note no swap check for longitude as box could cross date line. //--- if (minLatF > maxLatF) { ossim_float64 tmpF = minLatF; minLatF = maxLatF; maxLatF = tmpF; } //--- // Assume cut box is edge to edge or "Pixel Is Area". Our // AOI(area of interest) uses center of pixel or "Pixel Is Point" // so get the degrees per pixel and shift AOI to center. //--- ossimDpt halfDpp; m_geom->getDegreesPerPixel(halfDpp); halfDpp = halfDpp / 2.0; ossimGpt gpt(0.0, 0.0, 0.0); ossimDpt ulPt; ossimDpt lrPt; // Upper left: gpt.lat = maxLatF - halfDpp.y; gpt.lon = minLonF + halfDpp.x; m_geom->worldToLocal(gpt, ulPt); // Lower right: gpt.lat = minLatF + halfDpp.y; gpt.lon = maxLonF - halfDpp.x; m_geom->worldToLocal(gpt, lrPt); if (isChipMode() && m_ivt.valid()) { // Chipping in image space: // Tranform image ul point to view: ossimDpt ipt = ulPt; m_ivt->imageToView(ipt, ulPt); // Tranform image lr point to view: ipt = lrPt; m_ivt->imageToView(ipt, lrPt); } rect = ossimIrect(ossimIpt(ulPt), ossimIpt(lrPt)); } } else if (m_kwl->find(CUT_WMS_BBOX_KW.c_str())) { ossimString cutBbox = m_kwl->findKey(CUT_WMS_BBOX_KW); cutBbox = cutBbox.upcase().replaceAllThatMatch("BBOX:"); std::vector cutBox = cutBbox.split(","); if (cutBox.size() == 4) { ossim_float64 minx = cutBox[0].toFloat64(); ossim_float64 miny = cutBox[1].toFloat64(); ossim_float64 maxx = cutBox[2].toFloat64(); ossim_float64 maxy = cutBox[3].toFloat64(); const ossimMapProjection *mapProj = m_geom->getAsMapProjection(); if (mapProj) { std::vector pts(4); ossimDpt *ptsArray = &pts.front(); if (mapProj->isGeographic()) { ossimDpt halfDpp; m_geom->getDegreesPerPixel(halfDpp); halfDpp = halfDpp / 2.0; ossimGpt gpt(0.0, 0.0, 0.0); ossimDpt ulPt; ossimDpt lrPt; // Upper left: gpt.lat = maxy - halfDpp.y; gpt.lon = minx + halfDpp.x; m_geom->worldToLocal(gpt, ptsArray[0]); // Upper right: gpt.lat = maxy - halfDpp.y; gpt.lon = maxx - halfDpp.x; m_geom->worldToLocal(gpt, ptsArray[1]); // Lower right: gpt.lat = miny + halfDpp.y; gpt.lon = maxx - halfDpp.x; m_geom->worldToLocal(gpt, ptsArray[2]); //Lower left gpt.lat = miny + halfDpp.y; gpt.lon = minx + halfDpp.x; m_geom->worldToLocal(gpt, ptsArray[3]); } else { ossimDpt halfMpp; ossimDpt eastingNorthing; m_geom->getMetersPerPixel(halfMpp); halfMpp = halfMpp / 2.0; eastingNorthing.x = minx + halfMpp.x; eastingNorthing.y = miny + halfMpp.y; mapProj->eastingNorthingToLineSample(eastingNorthing, ptsArray[0]); eastingNorthing.x = minx + halfMpp.x; eastingNorthing.y = maxy - halfMpp.y; mapProj->eastingNorthingToLineSample(eastingNorthing, ptsArray[1]); eastingNorthing.x = maxx - halfMpp.x; eastingNorthing.y = maxy - halfMpp.y; mapProj->eastingNorthingToLineSample(eastingNorthing, ptsArray[2]); eastingNorthing.x = maxx - halfMpp.x; eastingNorthing.y = miny + halfMpp.y; mapProj->eastingNorthingToLineSample(eastingNorthing, ptsArray[3]); } rect = ossimIrect(pts); } } } } // if ( m_getOutputGeometry.valid() ) else { // Should never happer... std::string errMsg = MODULE; if (!source) { errMsg += " image source null!"; throw(ossimException(errMsg)); } // do not have to have a projection to output in image space // So commenting out here // // else // { // errMsg += " output projection null!"; // } } // If no user defined rect set to scene bounding rect. if (rect.hasNans()) { // Get the rectangle from the input chain: rect = source->getBoundingRect(0); } } // if ( rect.hasNans() ) } // if ( source ) if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "aoi: " << rect << "\n" << MODULE << " exited...\n"; } } // End: ossimChipperUtil::getAreaOfInterest bool ossimChipperUtil::getIrect(const std::string &s, ossimIrect &rect) const { bool result = false; if (s.size()) { // ,,, ossimString cutBbox = s; std::vector keys; cutBbox.split(keys, ","); if (keys.size() > 3) { ossimIpt ul; ossimIpt lr; ul.x = keys[0].toInt32(); ul.y = keys[1].toInt32(); lr.x = ul.x + keys[2].toInt32() - 1; lr.y = ul.y + keys[3].toInt32() - 1; rect = ossimIrect(ul, lr); result = true; } } return result; } bool ossimChipperUtil::getIrect(ossimRefPtr &chain, const std::string &s, ossimIrect &rect) const { bool result = false; if (chain.valid()) { ossimRefPtr ih = chain->getImageHandler(); if (ih.valid()) { // Get the geometry from the image handler. ossimRefPtr geom = ih->getImageGeometry(); if (geom.valid()) { // ,,, ossimString cutBbox = s; std::vector keys; cutBbox.split(keys, ","); if (keys.size() > 3) { ossimGpt gpt; gpt.lat = keys[0].toFloat64(); gpt.lon = keys[1].toFloat64(); ossim_int32 w = keys[2].toInt32(); ossim_int32 h = keys[3].toInt32(); ossimDpt dpt; geom->worldToLocal(gpt, dpt); ossimIpt ul = dpt; ul.x -= w / 2; ul.y -= h / 2; ossimIpt lr(ul.x + w - 1, ul.y + h - 1); rect = ossimIrect(ul, lr); result = true; } } } } return result; } bool ossimChipperUtil::getIrect(ossimRefPtr &chain, ossimIrect &rect) const { bool result = false; if (chain.valid()) { ossimRefPtr ih = chain->getImageHandler(); if (ih.valid()) { const ossim_int32 MAX = 512; ossimIrect r = ih->getImageRectangle(); ossimIpt size = r.size(); ossim_int32 w = ossim::min(MAX, size.x); ossim_int32 h = ossim::min(MAX, size.y); ossimIpt ul = r.midPoint(); ul.x -= w / 2; ul.y -= h / 2; ossimIpt lr(ul.x + w - 1, ul.y + h - 1); rect = ossimIrect(ul, lr); result = true; } } return result; } void ossimChipperUtil::initializeThumbnailProjection(const ossimIrect &originalRect, ossimIrect &adjustedRect) { static const char MODULE[] = "ossimChipperUtil::initializeThumbnailProjection"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n" << "origial rect: " << originalRect << "\n"; if (m_geom.valid()) { m_geom->print(ossimNotify(ossimNotifyLevel_DEBUG)); } } if (!originalRect.hasNans() && m_geom.valid()) { //--- // Thumbnail setup: //--- ossimString thumbRes = m_kwl->findKey(THUMBNAIL_RESOLUTION_KW); if (thumbRes.size()) { ossim_float64 thumbSize = thumbRes.toFloat64(); ossim_float64 maxRectDimension = ossim::max(originalRect.width(), originalRect.height()); ossim_uint32 tw = originalRect.width(); ossim_uint32 th = originalRect.height(); ossim_float64 scale = 1.0; if (maxRectDimension > thumbSize) { // Need to adjust scale: // Get the corners before the scale change: ossimGpt ulGpt; ossimGpt lrGpt; m_geom->localToWorld(ossimDpt(originalRect.ul()), ulGpt); m_geom->localToWorld(ossimDpt(originalRect.lr()), lrGpt); if (isChipMode() && m_ivt.valid()) // Chipping in image space.) { scale = thumbSize / maxRectDimension; if (m_ivt->getScale().hasNans()) { m_ivt->scale(scale, scale); } else { m_ivt->scale(m_ivt->getScale().x * scale, m_ivt->getScale().y * scale); } tw *= scale; th *= scale; } else { scale = maxRectDimension / thumbSize; //--- // Adjust the projection scale. Note the "true" is to recenter // the tie point so it falls relative to the projection origin. // // This call also scales: ossimImageGeometry::m_imageSize //--- m_geom->applyScale(ossimDpt(scale, scale), true); tw /= scale; th /= scale; } if (tw < 1) tw = 1; if (th < 1) th = 1; // Must call to reset the ossimImageRenderer's bounding rect for each input. propagateOutputProjectionToChains(); // Get the new upper left in view space. ossimDpt dpt; m_geom->worldToLocal(ulGpt, dpt); ossimIpt ul(dpt); // Get the new lower right in view space. m_geom->worldToLocal(lrGpt, dpt); ossimIpt lr(dpt); //--- // Clamp to thumbnail bounds with padding if turned on. // Padding is optional. If padding turned on alway make square. //--- ossim_int32 ts = thumbSize; bool pad = padThumbnail(); if (pad) { lr.x = ul.x + ts - 1; lr.y = ul.y + ts - 1; } else // let it vary { lr.x = ul.x + tw - 1; lr.y = ul.y + th - 1; } adjustedRect = ossimIrect(ul, lr); } } } // if ( !originalRect.hasNans() && m_geom.valid() ) else { // Should never happer... std::string errMsg = MODULE; if (originalRect.hasNans()) { errMsg += " passed in rect has nans!"; } else { errMsg += " output projection null!"; } throw(ossimException(errMsg)); } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nadjusted rect: " << adjustedRect << "\n"; if (m_geom.valid()) { m_geom->print(ossimNotify(ossimNotifyLevel_DEBUG)); } ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } bool ossimChipperUtil::hasBandSelection() const { bool result = false; if (m_kwl.valid()) { result = m_kwl->hasKey(std::string(ossimKeywordNames::BANDS_KW)); } return result; } bool ossimChipperUtil::hasWmsBboxCutWidthHeight() const { bool result = false; if (m_kwl.valid()) { result = (m_kwl->hasKey(CUT_HEIGHT_KW) && m_kwl->hasKey(CUT_WIDTH_KW) && (m_kwl->hasKey(CUT_WMS_BBOX_KW) || m_kwl->hasKey(CUT_WMS_BBOX_LL_KW))); } return result; } bool ossimChipperUtil::hasCutBoxWidthHeight() const { bool result = false; if (m_kwl.valid()) { if (m_kwl->hasKey(CUT_HEIGHT_KW)) { if (m_kwl->hasKey(CUT_WIDTH_KW)) { if (m_kwl->hasKey(CUT_MIN_LAT_KW)) { if (m_kwl->hasKey(CUT_MIN_LON_KW)) { if (m_kwl->hasKey(CUT_MAX_LAT_KW)) { if (m_kwl->hasKey(CUT_MAX_LON_KW)) { result = true; } } } } // if lat and lon WMS style bbox is specified then we will behave the same as above else if (m_kwl->hasKey(CUT_WMS_BBOX_LL_KW)) { result = true; } } } } return result; } bool ossimChipperUtil::hasScaleOption() const { bool result = false; if (m_kwl.valid()) { if (m_kwl->hasKey(METERS_KW.c_str()) || m_kwl->hasKey(DEGREES_X_KW.c_str()) || hasCutBoxWidthHeight() || hasWmsBboxCutWidthHeight()) { result = true; } } return result; } bool ossimChipperUtil::isThreeBandOut() const { return keyIsTrue(THREE_BAND_OUT_KW); } bool ossimChipperUtil::padThumbnail() const { return keyIsTrue(PAD_THUMBNAIL_KW); } void ossimChipperUtil::setReaderProps(ossimImageHandler *ih) const { if (ih && m_kwl.valid()) { ossim_uint32 count = m_kwl->numberOf(READER_PROPERTY_KW.c_str()); for (ossim_uint32 i = 0; i < count; ++i) { ossimString key = READER_PROPERTY_KW; key += ossimString::toString(i); ossimString value = m_kwl->findKey(key.string()); if (value.size()) { std::vector splitArray; value.split(splitArray, "="); if (splitArray.size() == 2) { ossimRefPtr prop = new ossimStringProperty(splitArray[0], splitArray[1]); ih->setProperty(prop); } } } } } void ossimChipperUtil::getBandList(std::vector &bandList) const { bandList.clear(); if (m_kwl.valid()) { ossimString os; os.string() = m_kwl->findKey(std::string(ossimKeywordNames::BANDS_KW)); if (os.size() && (os != "default")) { std::vector band_list(0); os.split(band_list, ossimString(","), false); if (band_list.size()) { std::vector::const_iterator i = band_list.begin(); while (i != band_list.end()) { ossim_uint32 band = (*i).toUInt32(); if (band) // One based so we need to subtract. { bandList.push_back(band - 1); } ++i; } } } } } // End: ossimChipperUtil::getBandList bool ossimChipperUtil::hasAnnotations() const { bool result = false; if (m_kwl.valid()) { ossimString regularExpression = "annotation[0-9]*\\.type"; ossim_uint32 count = m_kwl->getNumberOfKeysThatMatch(regularExpression); if (count > 0) { result = true; } } return result; } bool ossimChipperUtil::hasLutFile() const { bool result = false; if (m_kwl.valid()) { result = (m_kwl->find(LUT_FILE_KW.c_str()) != 0); } return result; } bool ossimChipperUtil::hasBrightnesContrastOperation() const { bool result = false; std::string value = m_kwl->findKey(BRIGHTNESS_KW); if (value.size()) { result = true; } else { value = m_kwl->findKey(CONTRAST_KW); if (value.size()) { result = true; } } return result; } bool ossimChipperUtil::hasGeoPolyCutterOption() const { bool result = (m_kwl->find(CLIP_WMS_BBOX_LL_KW.c_str()) || m_kwl->find(CLIP_POLY_LAT_LON_KW.c_str())); return result; } bool ossimChipperUtil::hasBumpShadeArg() const { bool result = (m_operation == OSSIM_CHIPPER_OP_HILL_SHADE); if (!result && m_kwl.valid()) { result = (m_kwl->find(ossimKeywordNames::AZIMUTH_ANGLE_KW) || m_kwl->find(COLOR_RED_KW.c_str()) || m_kwl->find(COLOR_GREEN_KW.c_str()) || m_kwl->find(COLOR_BLUE_KW.c_str()) || m_kwl->find(ossimKeywordNames::ELEVATION_ANGLE_KW) || m_kwl->find(GAIN_KW.c_str())); } return result; } bool ossimChipperUtil::hasThumbnailResolution() const { bool result = false; if (m_kwl.valid()) { result = (m_kwl->find(THUMBNAIL_RESOLUTION_KW.c_str()) != 0); } return result; } bool ossimChipperUtil::hasHistogramOperation() const { bool result = false; if (m_kwl.valid()) { result = m_kwl->hasKey(HIST_OP_KW); } return result; } bool ossimChipperUtil::hasGammaCorrection() const { bool result = false; if (m_kwl.valid()) { result = m_kwl->hasKey(GAMMA_KW); } return result; } bool ossimChipperUtil::isDemFile(const ossimFilename &file) const { bool result = false; ossimString ext = file.ext(); if (ext.size() >= 2) { ext.downcase(); if ((ext == "hgt") || (ext == "dem") || (((*ext.begin()) == 'd') && ((*(ext.begin() + 1)) == 't'))) { result = true; } } return result; } bool ossimChipperUtil::isSrcFile(const ossimFilename &file) const { bool result = false; ossimString ext = file.ext(); ext.downcase(); if (ext == "src") { result = true; } return result; } ossimScalarType ossimChipperUtil::getOutputScalarType() const { ossimScalarType scalar = OSSIM_SCALAR_UNKNOWN; ossimString lookup = m_kwl->findKey(OUTPUT_RADIOMETRY_KW); if (lookup.size()) { scalar = ossimScalarTypeLut::instance()->getScalarTypeFromString(lookup); } if (scalar == OSSIM_SCALAR_UNKNOWN) { // deprecated keyword... if (keyIsTrue(std::string(SCALE_2_8_BIT_KW))) { scalar = OSSIM_UINT8; } } return scalar; } bool ossimChipperUtil::scaleToEightBit() const { bool result = false; if (getOutputScalarType() == OSSIM_UINT8) { result = true; } return result; } bool ossimChipperUtil::snapTieToOrigin() const { return keyIsTrue(SNAP_TIE_TO_ORIGIN_KW); } void ossimChipperUtil::getImageSpaceScale(ossimDpt &imageSpaceScale) const { imageSpaceScale.x = 1.0; imageSpaceScale.y = 1.0; ossimString lookup; if (m_kwl->hasKey(FULLRES_XYS_KW)) { lookup = m_kwl->findKey(FULLRES_XYS_KW); std::vector values; lookup.trim().split(values, ","); if (values.size() > 2) { imageSpaceScale.x = values[2].toDouble(); imageSpaceScale.y = imageSpaceScale.x; if (values.size() > 3) { imageSpaceScale.y = values[3].toDouble(); } } } else { std::string value = m_kwl->findKey(IMAGE_SPACE_SCALE_X_KW); if (value.size()) { imageSpaceScale.x = ossimString(value).toFloat64(); } else { imageSpaceScale.x = 1.0; } value = m_kwl->findKey(IMAGE_SPACE_SCALE_Y_KW); if (value.size()) { imageSpaceScale.y = ossimString(value).toFloat64(); } else { imageSpaceScale.y = 1.0; } } } void ossimChipperUtil::getImageSpacePivot(ossimDpt &imageSpacePivot) const { ossimString lookup; imageSpacePivot.makeNan(); if (m_kwl->hasKey(FULLRES_XYS_KW)) { lookup = m_kwl->findKey(FULLRES_XYS_KW); std::vector values; lookup.trim().split(values, ","); if (values.size() > 1) { imageSpacePivot.x = values[0].toDouble(); imageSpacePivot.y = values[1].toDouble(); } } else { if (m_geom) { ossimDrect rect; m_geom->getBoundingRect(rect); imageSpacePivot = rect.midPoint(); } } } ossim_float64 ossimChipperUtil::getRotation() const { ossim_float64 result = ossim::nan(); if (m_kwl.valid()) { std::string value = m_kwl->findKey(ROTATION_KW); if (value.size()) { result = ossimString(value).toFloat64(); if (result < 0) { result += 360.0; } // Range check: if ((result < 0.0) || (result > 360.0)) { std::ostringstream errMsg; errMsg << "ossimChipperUtil::getRotation range error!\n" << "rotation = " << result << "\nMust be between 0 and 360."; throw ossimException(errMsg.str()); } } } return result; } bool ossimChipperUtil::upIsUp() const { return keyIsTrue(std::string(UP_IS_UP_KW)); } bool ossimChipperUtil::hasRotation() const { bool result = false; std::string value = m_kwl->findKey(std::string(ROTATION_KW)); if (value.size()) { result = true; } return result; } bool ossimChipperUtil::northUp() const { return keyIsTrue(std::string(NORTH_UP_KW)); } bool ossimChipperUtil::isChipMode() const { return (m_operation == OSSIM_CHIPPER_OP_CHIP); } bool ossimChipperUtil::keyIsTrue(const std::string &key) const { bool result = false; if (m_kwl.valid()) { std::string value = m_kwl->findKey(key); if (value.size()) { result = ossimString(value).toBool(); } } return result; } ossim_uint32 ossimChipperUtil::getEntryNumber() const { ossim_uint32 result = 0; if (m_kwl.valid()) { std::string value = m_kwl->findKey(std::string(ossimKeywordNames::ENTRY_KW)); if (value.size()) { result = ossimString(value).toUInt32(); } } return result; } ossim_int32 ossimChipperUtil::getZone() const { ossim_int32 result = 0; if (m_kwl.valid()) { std::string value = m_kwl->findKey(std::string(ossimKeywordNames::ZONE_KW)); if (value.size()) { result = ossimString(value).toUInt32(); } } return result; } std::string ossimChipperUtil::getHemisphere() const { std::string result; if (m_kwl.valid()) { result = m_kwl->findKey(std::string(ossimKeywordNames::HEMISPHERE_KW)); } return result; } bool ossimChipperUtil::hasSensorModelInput() { bool result = false; // Test image layers. std::vector>::iterator chainIdx = m_imgLayer.begin(); while (chainIdx != m_imgLayer.end()) { // Get the image handler: ossimRefPtr ih = (*chainIdx)->getImageHandler(); if (ih.valid()) { // Get the geometry from the first image handler. ossimRefPtr geom = ih->getImageGeometry(); if (geom.valid()) { // Get the image projection. ossimRefPtr proj = geom->getProjection(); if (proj.valid()) { // Cast and assign to result. ossimMapProjection *mapProj = PTR_CAST(ossimMapProjection, proj.get()); if (!mapProj) { result = true; break; } } } } ++chainIdx; } if (!result) { // Test dem layers. chainIdx = m_demLayer.begin(); while (chainIdx != m_demLayer.end()) { // Get the image handler: ossimRefPtr ih = (*chainIdx)->getImageHandler(); if (ih.valid()) { // Get the geometry from the first image handler. ossimRefPtr geom = ih->getImageGeometry(); if (geom.valid()) { // Get the image projection. ossimRefPtr proj = geom->getProjection(); if (proj.valid()) { // Cast and assign to result. ossimMapProjection *mapProj = PTR_CAST(ossimMapProjection, proj.get()); if (!mapProj) { result = true; break; } } } } ++chainIdx; } } return result; } void ossimChipperUtil::initializeSrcKwl() { static const char MODULE[] = "ossimChipperUtil::initializeSrcKwl"; if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n"; } std::string value = m_kwl->findKey(std::string(SRC_FILE_KW)); if (value.size()) { m_srcKwl = new ossimKeywordlist(); m_srcKwl->setExpandEnvVarsFlag(true); if (m_srcKwl->addFile(value.c_str()) == false) { m_srcKwl = 0; } } else { m_srcKwl = 0; } if (traceDebug()) { if (m_srcKwl.valid()) { ossimNotify(ossimNotifyLevel_DEBUG) << "src keyword list:\n" << *(m_srcKwl.get()) << "\n"; } ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exited...\n"; } } ossim_uint32 ossimChipperUtil::getNumberOfInputs() const { ossim_uint32 result = 0; ossimString demRegExpr = "dem[0-9]*\\.file"; ossimString imgRegExpr = "image[0-9]*\\.file"; if (m_kwl.valid()) { // Look for dems, e.g. dem0.file: foo.tif result = m_kwl->getNumberOfKeysThatMatch(demRegExpr); // Look for images, e.g. image0.file: foo.tif result += m_kwl->getNumberOfKeysThatMatch(imgRegExpr); } if (m_srcKwl.valid()) { // Look for dems, e.g. dem0.file: foo.tif result += m_srcKwl->getNumberOfKeysThatMatch(demRegExpr); // Look for images, e.g. image0.file: foo.tif result += m_srcKwl->getNumberOfKeysThatMatch(imgRegExpr); } return result; } ossimChipperUtil::ossimChipperOutputProjection ossimChipperUtil::getOutputProjectionType() const { ossimChipperOutputProjection result = ossimChipperUtil::OSSIM_CHIPPER_PROJ_UNKNOWN; const char *op = m_kwl->find(ossimKeywordNames::PROJECTION_KW); if (op) { ossimString os = op; os.downcase(); if (os == "geo") { result = ossimChipperUtil::OSSIM_CHIPPER_PROJ_GEO; } else if (os == "geo-scaled") { result = ossimChipperUtil::OSSIM_CHIPPER_PROJ_GEO_SCALED; } else if (os == "input") { result = ossimChipperUtil::OSSIM_CHIPPER_PROJ_INPUT; } else if ((os == "utm") || (os == "ossimutmprojection")) { result = ossimChipperUtil::OSSIM_CHIPPER_PROJ_UTM; } } return result; } void ossimChipperUtil::getClipPolygon(ossimGeoPolygon &polygon) const { ossimString param = m_kwl->find(CLIP_WMS_BBOX_LL_KW.c_str()); if (!param.empty()) { if (!polygon.addWmsBbox(param)) { polygon.clear(); } } else { param = m_kwl->find(CLIP_POLY_LAT_LON_KW.c_str()); if (!param.empty()) { std::vector points; ossim::toVector(points, param); if (!points.empty()) { polygon = points; } } } } ossim_float64 ossimChipperUtil::getBrightness() const { ossim_float64 brightness = 0.0; std::string value = m_kwl->findKey(BRIGHTNESS_KW); if (value.size()) { brightness = ossimString(value).toFloat64(); // Range check it: if ((brightness < -1.0) || (brightness > 1.0)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimChipperUtil::getBrightness range error!" << "\nbrightness: " << brightness << "\nvalid range: -1.0 to 1.0" << "\nReturned brightness has been reset to: 0.0" << std::endl; brightness = 0.0; } } return brightness; } ossim_float64 ossimChipperUtil::getContrast() const { ossim_float64 contrast = 1.0; std::string value = m_kwl->findKey(CONTRAST_KW); if (value.size()) { contrast = ossimString(value).toFloat64(); // Range check it: if ((contrast < 0.0) || (contrast > 20.0)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimChipperUtil::getContrast range error!" << "\ncontrast: " << contrast << "\nvalid range: 0 to 20.0" << "\nReturned contrast has been reset to: 1.0" << std::endl; contrast = 1.0; } } return contrast; } ossim_float64 ossimChipperUtil::getGamma() const { ossim_float64 gamma = 1.0; std::string value = m_kwl->findKey(GAMMA_KW); if (value.size()) { gamma = ossimString(value).toFloat64(); // Range check it: } return gamma; } std::string ossimChipperUtil::getSharpenMode() const { ossimString mode = m_kwl->findKey(SHARPEN_MODE_KW); if (mode.size()) { mode.downcase(); if ((mode != "light") && (mode != "heavy") && (mode != "medium") && (mode != "none")) { ossimNotify(ossimNotifyLevel_WARN) << "ossimChipperUtil::getSharpnessMode WARNING!" << "\nInvalid sharpness mode: " << mode << "\nValid modes: \"light\", \"medium\", and \"heavy\"" << std::endl; mode = ""; } if (mode == "none") mode = ""; } return mode.string(); } std::string ossimChipperUtil::getSharpenPercent() const { ossimString percent = m_kwl->findKey(SHARPEN_PERCENT_KW); if (percent.size()) { ossim_float64 value = percent.toDouble(); if (value < 0 || value > 1) { ossimNotify(ossimNotifyLevel_WARN) << "ossimChipperUtil::getSharpenPercent WARNING!" << "\nInvalid sharpen percent: " << percent << "\nValid percent: Between 0 and 1\n"; percent = ""; } } return percent; } int ossimChipperUtil::getHistoMode() const { int result = ossimHistogramRemapper::STRETCH_UNKNOWN; ossimString op = m_kwl->findKey(HIST_OP_KW); op.downcase(); if ((op.string() == "auto-minmax")) { result = ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX; } else if ((op.string() == "auto-percentile")) { result = ossimHistogramRemapper::LINEAR_AUTO_PERCENTILE; } else if ((op == "std-stretch-1") || (op == "std-stretch 1")) { result = ossimHistogramRemapper::LINEAR_1STD_FROM_MEAN; } else if ((op == "std-stretch-2") || (op == "std-stretch 2")) { result = ossimHistogramRemapper::LINEAR_2STD_FROM_MEAN; } else if ((op == "std-stretch-3") || (op == "std-stretch 3")) { result = ossimHistogramRemapper::LINEAR_3STD_FROM_MEAN; } else if((op == "linear")) { result = ossimHistogramRemapper::LINEAR_ONE_PIECE; } else if (traceDebug()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimChipperUtil::getHistoMode: Unhandled operation: " << op << "\n"; } return result; } void ossimChipperUtil::usage(ossimArgumentParser &ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); // Set app name. std::string appName = ap.getApplicationName(); ap.getApplicationUsage()->setApplicationName(ossimString(appName)); // Add options. addArguments(ap); // Write usage. ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); // Keeping single line in tact for examples for cut and paste purposes. ossimNotify(ossimNotifyLevel_INFO) << "NOTES:\n" << "1) Never use same base name in the same directory! Example is you have a Chicago.tif\n" << " and you want a Chicago.jp2, output Chicago.jp2 to its own directory.\n" << "\nExample commands:\n" << "\n// File conversion: Convert geotiff to a jp2 file.\n" << appName << " --op chip -w ossim_kakadu_jp2 Chicago.tif outputs/Chicago.jp2\n" << "\n// Orthorectification: Orthorectify a nitf with RPC model out to a geotiff.\n" << appName << " --op ortho 5V090205P0001912264B220000100282M_001508507.ntf outputs/ortho.tif\n" << "\n// Mosaic: Mosaic multiple images together and output to a geotiff.\n" << appName << " --combiner-type ossimImageMosaic --op ortho f1.tif f2.tif f3.tif outputs/mosaic.tif\n" << "\n// Mosaic: Feather Mosaic multiple images together and output to a geotiff.\n" << appName << " --combiner-type ossimFeatherMosaic --op ortho f1.tif f2.tif f3.tif outputs/feather.tif\n" << "\n// Color relief: Colorize two DEMs from a lut, output to a geotiff.\n" << appName << " --op color-relief --color-table ossim-dem-color-table-template.kwl N37W123.hgt N38W123.hgt outputs/color-relief.tif\n" << "\n// Color relief: Colorize two DEMs from a lut, output to a png thumbnail.\n" << appName << " --op color-relief --color-table ossim-dem-color-table-template.kwl -t 1024 -w ossim_png N37W123.hgt N38W123.hgt outputs/color-relief.png\n" << "\n// Hill shade: Hill shade two DEMs, output to a geotiff.\n" << appName << " --color 255 255 255 --azimuth 270 --elevation 45 --exaggeration 2.0 --op hillshade N37W123.hgt N38W123.hgt outputs/hillshade.tif\n" << "\n// Two color multi view with cut box. First image is old, second image is new:\n" << appName << " --cut-bbox-ll 28.092885092033352 -80.664539599998633 28.109128691071547 -80.626914963229325 --op 2cmv oldMLB.tif newMLB.tif outputs/2cmv-test1.tif\n" << "\n// Ortho about point, 512x512, with histogram stretch, and 3,2,1 band order:\n" << appName << " --op ortho -b 3,2,1 --histogram-op auto-minmax --cut-center-llwh -42.819784401784275 147.265811350983 512 512 5V090205M0001912264B220000100072M_001508507.ntf orth.tif\n" << "\n// Chip, in image space, about point, 512x512, with histogram stretch, and 3,2,1 band order:\n" << appName << " --op chip -b 3,2,1 --histogram-op auto-minmax --cut-center-llwh -42.819784401784275 147.265811350983 512 512 5V090205M0001912264B220000100072M_001508507.ntf chip.tif\n" << "\n// Chip in image space, rotate \"up is up\"(-u option) about point, 512x512 with histogram stretch and 3,2,1 band order:\n" << appName << " --op chip -u -b 3,2,1 --histogram-op auto-minmax --cut-center-llwh -42.819784401784275 147.265811350983 512 512 5V090205M0001912264B220000100072M_001508507.ntf up-is-up-chip.tif\n" << "\n// Chip in image space, rotate 39 degrees (-r option) about point, 1024x1024, scaled to eight bit:\n" << appName << " --op chip -r 39 --histogram-op auto-minmax --cut-center-llwh -42.883809539602893 147.331984112985765 1024 1024 --output-radiometry ossim_uint8 5V090205P0001912264B220000100282M_001508507.ntf outputs/r39.png\n" << "\n// Above command where all options are in a keyword list:\n" << appName << " --options r39-options.kwl\n" << std::endl; } ossim-Miami-2.9.1/src/util/ossimEquationUtil.cpp000066400000000000000000000350151352751253100216650ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static ossimTrace traceDebug(ossimString("mosaic:main")); // Copied from ossimEquationCombiner.h: static const char* EQ_SPEC = "\nEquation Specification:\n\ \n\ sin(x) takes the sine of the input \n\ sind(x) takes the sin of the input and assumes degree input \n\ cos(x) takes cosine of input \n\ cosd(x) takes the cosine of input and assumes input in degrees \n\ sqrt(x) takes square root of input \n\ log(x) takes the natural log of input \n\ log10(x) takes the log base 10 of the input \n\ exp(x) takes the e raised to the passed in argument \n\ abs(x) takes the absolute value of the passed in value \n\ min(x1, x2, ... xn) takes the min of all values in the list \n\ max(x1, x2, ... xn) takes the max of all values in the list. \n\ \n\ clamp(image_data, min, max) \n\ will clamp all data to be between the min max values. \n\ will set anything less than min to min and anythin \n\ larger than max to max \n\ \n\ band(image_data, num) returns a single band image object \n\ by selecting band num from input image i1. Note \n\ the first argument must be an image \n\ and the second argument must be a number \n\ \n\ shift(index, num_x, num_y) \n\ currently, the first argument must be an image \n\ variable(i1, i2, ... in) and x, and y must b numbers \n\ indicating the delta in that direction to shift the \n\ input. \n\ \n\ blurr(index, rows, cols) \n\ Will blurr the input image i with a \n\ rows-by-cols kernel. All values are equal \n\ weight. Note the fist argument must by an image \n\ variable (ex: i1, i2,....in). \n\ \n\ conv(index, rows, cols, ) \n\ this allows you to define an arbitrary matrix. The \n\ is a comma separated \n\ list of constant values. \n\ \n\ assign_band(image_data, num1, data2, num2) \n\ will take band num2 from image data2 and assign it to \n\ band num1 in data 1. \n\ \n\ assign_band(image_data, num1, data2) \n\ will take band 1 from image data2 and assign it to \n\ band num1 in data 1. \n\ \n\ assign_band(image_data, num1, num2) \n\ will assin to band num1 of data 1 the value of num2 \n\ \n\ x1 * x2 will multiply x1 and x2 \n\ x1 + x2 will add x1 and x2 \n\ x1 - x2 will subtract x1 and x2 \n\ x1 / x2 will divide x1 and x2 \n\ x1 ^ x2 will do a power, raises x1 to x2 \n\ x1 | x2 will do a bitwise or operation \n\ ( will do it in unisgned char precision) \n\ \n\ x1 & x2 will do a bitwise and operation \n\ ( will do it in unsigned char precision) \n\ \n\ ~x1 will do the ones complement of the input \n\ \n\ x1 xor x2 will do an xclusive or operation \n\ (will do it in unsigned char precision) \n\ \n\ - x1 will negative of x1 \n\ \n\ Boolean ops: 1=true, 0=false \n\ x1 > x2 \n\ x1 >= x2 \n\ x1 == x2 \n\ x1 <= x2 \n\ x1 < x2 \n\ x1 <> x2 \n\ \n\ Note: \n\ \n\ Currently an image input is reference by the variable in[] where \n\ is the input image index beginning at 0. So 1 referes to the second image \n\ in the input list. \n\ \n\ (in[0] + in[1])/2 \n\ Will take image 1 and add it to image 2 and average them. \n\ \n\ exp(sqrt(in[0])/4) \n\ Will take the root of the image and divide by 4 and then raise e to that \n\ amount. \n\ \n\ 128 \n\ Will return a constant value of 128 for all input bands. \n\ \n\ min(1,in[2],in[3], max(in[1],in[0])) \n\ \n\ shift(0, 1, 1) - i1 \n\ Will shift input 0 by 1 pixel along the diagonal and then subtract it \n\ from input 1. \n\ \n\ assign_band(in[0], 1, blurr(in[0], 5, 5), 2) \n\ Will assign to the first band of i1 the 2nd band of the 5x5 blurr of i1. \n\ \n\ conv(0, 3, 3, -1, -2, -1, 0, 0, 0, 1, 2, 1) \n\ Will convolve the first input connection with a 3x3 matrix. \n\ The args are row ordered: \n\ -1, -2, -1 \n\ 0, 0, 0 \n\ 1, 2, 1 \n\ \n\ NDVI: \n\ N=(in[0]-in[1])/(in[0]+in[1]) \n\ \n\ For indexed-type values,like NDVI, (with limited values) it is better \n\ to rescale between 0.0 and 1.0 and use type NormalizedFloat. \n\ \n\ Rescaled NDVI between 0 and 1: \n\ (N+1)/2 = in[0]/(in[0]+in[1]) \n\ \n"; ossimEquationUtil::ossimEquationUtil(ossimArgumentParser& ap) : m_argumentParser(new ossimArgumentParser(ap)) { m_usage.setApplicationName(ap.getApplicationName()); m_usage.setDescription(ap.getApplicationName() + " Takes a list of images and performs the specified equation. The inputs" "must be in the same projection as the operations are done at the pixel" "level with no renderer in th chain. The output file will contain the same" "geospatial header info as the first image in the input list."); m_usage.setCommandLineUsage(ap.getApplicationName()+ " \"\" "); m_usage.addCommandLineOption("-h or --help","Display this information"); m_usage.addCommandLineOption("-k ", "keyword list to load from"); m_usage.addCommandLineOption("-w ", "Writer type (tiff_strip, jpeg, etc... see ossim-info --writers) (default=tiff_strip)"); m_usage.addCommandLineOption("--writer-prop ", "Adds a property to send to the writer. format is name=value"); m_usage.addCommandLineOption("-t ", "output a keyword list template"); } bool ossimEquationUtil::execute() { // Allocate some stuff up front for use later ossimString writerType = "tiff_strip"; ossimString equationSpec; std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); std::map writerPropertyMap; vector infiles; ossimFilename outfile; // Display Help if (m_argumentParser->read("-h") || m_argumentParser->read("--help") || (m_argumentParser->argc() < 4)) { m_usage.write(ossimNotify(ossimNotifyLevel_INFO)); ossimNotify(ossimNotifyLevel_INFO)<read("-t", stringParam)) { ossimFilename templateFilename = tempString.c_str(); outputTemplateKeywordlist(templateFilename); return false; } // Keyword list to load from if (m_argumentParser->read("-k", stringParam)) { if (!parseKwl(tempString.c_str(), infiles, equationSpec, outfile, writerType)) return false; } else { // Everything on command line: // user input writer props, should use those while(m_argumentParser->read("--writer-prop", stringParam)) { std::vector nameValue; ossimString(tempString).split(nameValue, "="); if(nameValue.size() == 2) writerPropertyMap.insert(std::make_pair(nameValue[0], nameValue[1])); } // User input a writer type if (m_argumentParser->read("-w", stringParam)) writerType = tempString; int argCount = m_argumentParser->argc(); if (argCount < 4) { m_usage.write(ossimNotify(ossimNotifyLevel_INFO)); ossimNotify(ossimNotifyLevel_INFO)<argv()[1]; // Get the input files. for (int i=2; i< (argCount-1); ++i) infiles.push_back(ossimFilename(m_argumentParser->argv()[i])); // Get the output file. outfile = m_argumentParser->argv()[argCount-1]; } if (!initInputSources(infiles)) return false; // Create combiner object ossimRefPtr combiner = new ossimEquationCombiner(m_inputSources); combiner->setEquation(equationSpec); // Create writer: ossimRefPtr writer; writer = ossimImageWriterFactoryRegistry::instance()->createWriter(writerType); if(!writer.valid()) { ossimNotify(ossimNotifyLevel_FATAL)<<"Could not create writer of type <"<"<connectMyInputTo(combiner.get()); writer->setFilename(outfile); ossimIrect bounding_irect; m_prodGeometry->getBoundingRect(bounding_irect); writer->setAreaOfInterest(bounding_irect); writer->initialize(); if ( writerPropertyMap.size() ) { ossimPropertyInterface* propInterface = (ossimPropertyInterface*) writer.get(); std::map::iterator iter = writerPropertyMap.begin(); while(iter!=writerPropertyMap.end()) { propInterface->setProperty(iter->first, iter->second); ++iter; } } // Execute: ossimStdOutProgress listener; writer->addListener(&listener); if (!writer->execute()) { ossimNotify(ossimNotifyLevel_WARN)<< "Error encountered writing file..."<close(); return true; } void ossimEquationUtil::outputTemplateKeywordlist(const ossimFilename &templateFilename) { ofstream out(templateFilename.c_str()); out << "file1.filename: " << endl << "file2.filename: " << endl << "// :\n" << "// :\n" << "// fileN.filename:: " << endl << "\n// currently this option has been tested\n" << "// with ossimTiffWriter and ossimJpegWriter\n" << "writer.type: tiff_strip" << endl << "writer.filename: " << endl << "\n// Equation specification:\n" << "equation: "<& inputs, ossimString& equationSpec, ossimFilename& output, ossimString& writerType) { ossimKeywordlist kwl; if (!kwl.addFile(kwl_file)) return false; ossim_int32 index = 0; ossim_int32 result = kwl.getNumberOfSubstringKeys("file[0-9]+\\.filename"); const char* lookup = NULL; ossim_int32 numberOfMatches = 0; while(numberOfMatches < result) { ossimString searchValue = "file" + ossimString::toString(index); ossimString filename = searchValue + ".filename"; lookup = kwl.find(filename.c_str()); if(lookup) { inputs.push_back(ossimFilename(lookup)); ++numberOfMatches; } ++index; } equationSpec = kwl.find("equation"); if (equationSpec.empty()) { ossimNotify(ossimNotifyLevel_FATAL)<<"No equation specified in KWL"<& fileList) { bool result = true; m_inputSources.clear(); ossimRefPtr input_geom; for(ossim_int32 index = 0; index < (ossim_int32)fileList.size();++index) { ossimRefPtr handler = ossimImageHandlerRegistry::instance()->open(fileList[index]); if(!handler.valid()) { cerr << "Error: Unable to load image " << fileList[index] << endl; result = false; break; } input_geom = handler->getImageGeometry(); if (index == 0) { m_prodGeometry = (ossimImageGeometry*) input_geom->dup(); ossimGpt origin; m_prodGeometry->getTiePoint(origin, false); ossimDpt gsd (m_prodGeometry->getMetersPerPixel()); if (m_prodGeometry->isAffectedByElevation()) { // Need to ortho to UTM, so define output geometry shared by all input chains: ossimMapProjection* prod_proj = new ossimUtmProjection; prod_proj->setOrigin(origin); prod_proj->setMetersPerPixel(m_prodGeometry->getMetersPerPixel()); m_prodGeometry->setProjection(prod_proj); } } // Set up the IVT for this input's renderer: ossimRefPtr transform = new ossimImageViewProjectionTransform; transform->setImageGeometry(input_geom.get()); transform->setViewGeometry(m_prodGeometry.get()); ossimRefPtr renderer = new ossimImageRenderer; renderer->connectMyInputTo(0, handler.get()); renderer->setImageViewTransform(transform.get()); renderer->initialize(); m_inputSources.push_back(renderer.get()); } return result; } ossim-Miami-2.9.1/src/util/ossimFileWalker.cpp000066400000000000000000000343471352751253100212760ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossimFileWalker.h // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: // // Utility class to walk through directories and get a list of files to // process. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include static ossimTrace traceDebug(ossimString("ossimFileWalker:debug")); ossimFileWalker::ossimFileWalker() : m_fileProcessor(0), m_jobQueue(std::make_shared(std::make_shared(), 1)), m_filteredExtensions(0), m_recurseFlag(true), m_waitOnDirFlag(false), m_abortFlag(false), m_mutex() { } ossimFileWalker::~ossimFileWalker() { m_jobQueue = 0; // Not a leak, ref pointer. } void ossimFileWalker::walk(const std::vector& files) { static const char M[] = "ossimFileWalker::walk"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered\n"; } if ( files.size() ) { std::vector::const_iterator i = files.begin(); while ( i != files.end() ) { // Must have call back set at this point. if ( !m_abortFlag && m_fileProcessor ) { ossimFilename file = (*i).expand(); if ( file.size() && file.exists() ) { if ( file.isDir() ) // Directory: { walkDir(file); } else // File: { if ( isFiltered(file) == false ) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Making the job for: " << (*i) << std::endl; } // Make the job: std::shared_ptr job = std::make_shared( m_fileProcessor, file ); job->setName( ossimString( file.string() ) ); job->setCallback( std::make_shared() ); // Set the state to ready: job->ready(); // Add job to the queue: m_jobQueue->getJobQueue()->add( job ); m_mutex.lock(); if ( m_abortFlag ) { // Clear out the queue. m_jobQueue->getJobQueue()->clear(); break; // Callee set our abort flag so break out of loop. } m_mutex.unlock(); } } } else { ossimNotify(ossimNotifyLevel_WARN) << M << " WARNING: file: \""<< file << "\" does not exist" << std::endl; } } ++i; } // while ( i != files.end() ) // FOREVER loop until all jobs are completed. while (1) { ossim::Thread::sleepInMicroSeconds(250); if ( m_jobQueue->hasJobsToProcess() == false ) { break; } } } // if ( files.size() ) if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exiting...\n"; } } void ossimFileWalker::walk(const ossimFilename& root) { static const char M[] = "ossimFileWalker::walk"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered root=" << root << "\n"; } // Must have call back set at this point. if ( !m_abortFlag && m_fileProcessor ) { ossimFilename rootFile = root.expand(); if ( rootFile.size() && rootFile.exists() ) { if ( rootFile.isDir() ) { walkDir(rootFile); // FOREVER loop until all jobs are completed. while (1) { ossim::Thread::sleepInMicroSeconds(250); if ( m_jobQueue->hasJobsToProcess() == false ) { break; } } } else { // Single file no job queue needed. if ( isFiltered( rootFile ) == false ) { m_fileProcessor->processFile( rootFile ); } } } else { ossimNotify(ossimNotifyLevel_WARN) << M << " WARNING: file: \""<< rootFile << "\" does not exist" << std::endl; } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exiting...\n"; } } void ossimFileWalker::walkDir(const ossimFilename& dir) { static const char M[] = "ossimFileWalker::walkDir"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n" << "processing dir: " << dir << "\n"; } // List of directories in this directory... std::vector dirs; // List of files in this directory... std::vector files; m_mutex.lock(); ossimDirectory d; bool ossimDirectoryStatus = d.open(dir); m_mutex.unlock(); if ( ossimDirectoryStatus ) { // Loop to get the list of files and directories in this directory. m_mutex.lock(); ossimFilename f; bool valid_file = d.getFirst(f); while ( valid_file ) { if ( isFiltered(f) == false ) { if (f.isDir()) { dirs.push_back(f); } else { files.push_back(f); } } valid_file = d.getNext(f); } m_mutex.unlock(); //--- // Process files first before recursing directories. If a file is a directory base image, // e.g. RPF, then the callee should call ossimFileWalker::setRecurseFlag to false to // stop us from going into sub directories. //--- std::vector::const_iterator i = files.begin(); while (i != files.end()) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Making the job for: " << (*i) << std::endl; } // Make the job: std::shared_ptr job = std::make_shared( m_fileProcessor, (*i) ); job->setName( ossimString( (*i).string() ) ); job->setCallback( std::make_shared() ); // Set the state to ready: job->ready(); // Add job to the queue: m_jobQueue->getJobQueue()->add( job ); m_mutex.lock(); if ( m_abortFlag ) { // Clear out the queue. m_jobQueue->getJobQueue()->clear(); break; // Callee set our abort flag so break out of loop. } m_mutex.unlock(); ++i; } if ( m_waitOnDirFlag ) { // FOREVER loop until all jobs are completed. while (1) { ossim::Thread::sleepInMicroSeconds(250); if ( m_jobQueue->hasJobsToProcess() == false ) { break; } } } m_mutex.lock(); if ( !m_abortFlag && m_recurseFlag ) { // Process sub directories... i = dirs.begin(); while (i != dirs.end()) { m_mutex.unlock(); walkDir( (*i) ); m_mutex.lock(); if ( m_abortFlag ) { break; // Callee set our abort flag so break out of loop. } ++i; } } m_mutex.unlock(); } // if ( ossimDirectoryOpenStatus ) // Reset the m_recurseFlag. m_mutex.lock(); m_recurseFlag = true; m_mutex.unlock(); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n"; } } bool ossimFileWalker::isFiltered(const ossimFilename& file) const { bool result = false; if ( file.size() ) { if ( isDotFile(file) ) { result = true; } else if ( file[file.size()-1] == '~' ) { result = true; } else { std::string ext = file.ext().downcase().c_str(); if ( ext.size() ) { std::vector::const_iterator i = m_filteredExtensions.begin(); while ( i != m_filteredExtensions.end() ) { if ( ext == (*i) ) { result = true; break; } ++i; } } } } #if 0 /* Please leave for debug. (drb) */ if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimFileWalker::isFiltered file " << (result?"filtered: ":"not filtered: ") << file << "\n"; } #endif return result; } bool ossimFileWalker::isDotFile(const ossimFilename& f) const { bool result = false; // Get the size in bytes. if ( f.size() ) { std::string::size_type firstDotPos = f.find('.'); if ( firstDotPos == 0 ) { result = true; } else if ( firstDotPos != std::string::npos ) // Dot in file. { // Get the position of first dot from the end. std::string::size_type lastDotPos = f.find_last_of('.'); if ( lastDotPos != std::string::npos ) { // Make copy. ossimFilename f2 = f; // Convert an '\'s to '/'s. // f2.convertBackToForwardSlashes(); // Find the first slash from end. std::string::size_type lastSlashPos = f2.find_last_of('/'); if (lastSlashPos != std::string::npos) // Found a slash. { if ( (lastSlashPos+1) == lastDotPos ) { // dot in front of slash like /home/foo/.xemacs result = true; } } } } } return result; } const std::vector& ossimFileWalker::getFilteredExtensions() const { return m_filteredExtensions; } std::vector& ossimFileWalker::getFilteredExtensions() { return m_filteredExtensions; } void ossimFileWalker::dumpFilteredExtensionList() const { ossimNotify(ossimNotifyLevel_NOTICE) << "Filtered extension list:\n"; std::vector::const_iterator i = m_filteredExtensions.begin(); while ( i != m_filteredExtensions.end() ) { ossimNotify(ossimNotifyLevel_NOTICE) << (*i) << "\n"; ++i; } ossimNotify(ossimNotifyLevel_NOTICE) << std::endl; } void ossimFileWalker::initializeDefaultFilterList() { m_mutex.lock(); // Common extensions to filter out, most common first. m_filteredExtensions.push_back(std::string("ovr")); m_filteredExtensions.push_back(std::string("omd")); m_filteredExtensions.push_back(std::string("his")); m_filteredExtensions.push_back(std::string("geom")); // The rest alphabetical. m_filteredExtensions.push_back(std::string("aux")); m_filteredExtensions.push_back(std::string("bin")); m_filteredExtensions.push_back(std::string("dbf")); m_filteredExtensions.push_back(std::string("h5")); m_filteredExtensions.push_back(std::string("hdr")); m_filteredExtensions.push_back(std::string("jgw")); m_filteredExtensions.push_back(std::string("jpw")); m_filteredExtensions.push_back(std::string("kwl")); m_filteredExtensions.push_back(std::string("log")); m_filteredExtensions.push_back(std::string("man")); m_filteredExtensions.push_back(std::string("ocg")); m_filteredExtensions.push_back(std::string("out")); m_filteredExtensions.push_back(std::string("prj")); m_filteredExtensions.push_back(std::string("save")); m_filteredExtensions.push_back(std::string("sdw")); m_filteredExtensions.push_back(std::string("sh")); m_filteredExtensions.push_back(std::string("shp")); m_filteredExtensions.push_back(std::string("shx")); m_filteredExtensions.push_back(std::string("spec")); m_filteredExtensions.push_back(std::string("statistics")); m_filteredExtensions.push_back(std::string("tar")); m_filteredExtensions.push_back(std::string("til")); m_filteredExtensions.push_back(std::string("tfw")); m_filteredExtensions.push_back(std::string("tgz")); m_filteredExtensions.push_back(std::string("tmp")); m_filteredExtensions.push_back(std::string("txt")); m_mutex.unlock(); } void ossimFileWalker::setRecurseFlag(bool flag) { m_mutex.lock(); m_recurseFlag = flag; m_mutex.unlock(); } void ossimFileWalker::setWaitOnDirFlag(bool flag) { m_mutex.lock(); m_waitOnDirFlag = flag; m_mutex.unlock(); } void ossimFileWalker::setAbortFlag(bool flag) { m_mutex.lock(); m_abortFlag = flag; m_mutex.unlock(); } void ossimFileWalker::setNumberOfThreads(ossim_uint32 nThreads) { m_mutex.lock(); m_jobQueue->setNumberOfThreads(nThreads); m_mutex.unlock(); } void ossimFileWalker::setFileProcessor(ossimFileProcessorInterface* fpi) { m_mutex.lock(); m_fileProcessor = fpi; m_mutex.unlock(); } ossimFileWalker::ossimFileWalkerJob::ossimFileWalkerJob( ossimFileProcessorInterface* fpi, const ossimFilename& file) : m_fileProcessor( fpi ), m_file( file ) { } void ossimFileWalker::ossimFileWalkerJob::run() { if ( m_fileProcessor && m_file.size() ) { m_fileProcessor->processFile( m_file ); } } ossimFileWalker::ossimFileWalkerJobCallback::ossimFileWalkerJobCallback() : ossimJobCallback() { } void ossimFileWalker::ossimFileWalkerJobCallback::started(std::shared_ptr job) { ossimJobCallback::started(job); } void ossimFileWalker::ossimFileWalkerJobCallback::finished(std::shared_ptr job) { ossimJobCallback::finished(job); } void ossimFileWalker::ossimFileWalkerJobCallback::canceled(std::shared_ptr job) { ossimJobCallback::canceled(job); } ossim-Miami-2.9.1/src/util/ossimHillshadeTool.cpp000066400000000000000000000230361352751253100217750ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug("ossimHillshadeUtil:debug"); static const std::string COLOR_BLUE_KW = "color_blue"; static const std::string COLOR_GREEN_KW = "color_green"; static const std::string COLOR_RED_KW = "color_red"; static const std::string COLOR_SOURCE_KW = "color_source"; const char* ossimHillshadeTool::DESCRIPTION = "Computes shaded representation of input elevation surface with specified lighting parameters."; ossimHillshadeTool::ossimHillshadeTool() { m_kwl.setExpandEnvVarsFlag(true); } // Private/hidden from use. ossimHillshadeTool::ossimHillshadeTool( const ossimHillshadeTool& /* obj */ ) { } // Private/hidden from use. const ossimHillshadeTool& ossimHillshadeTool::operator=( const ossimHillshadeTool& /* rhs */) { return *this; } ossimHillshadeTool::~ossimHillshadeTool() { clear(); } bool ossimHillshadeTool::initialize(ossimArgumentParser& ap) { // Permit base class to pull out common options first. if (!ossimChipProcTool::initialize(ap)) return false; if (m_helpRequested) return true; std::string tempString1; ossimArgumentParser::ossimParameter stringParam1(tempString1); std::string tempString2; ossimArgumentParser::ossimParameter stringParam2(tempString2); std::string tempString3; ossimArgumentParser::ossimParameter stringParam3(tempString3); std::string tempString4; ossimArgumentParser::ossimParameter stringParam4(tempString4); std::string tempString5; ossimArgumentParser::ossimParameter stringParam5(tempString5); std::string tempString6; ossimArgumentParser::ossimParameter stringParam6(tempString6); double tempDouble1; ossimArgumentParser::ossimParameter doubleParam1(tempDouble1); double tempDouble2; ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); // Extract optional arguments and stuff them in a keyword list. if( ap.read("--azimuth", stringParam1) ) { m_kwl.addPair( std::string(ossimKeywordNames::AZIMUTH_ANGLE_KW), tempString1 ); } if( ap.read("--color", stringParam1, stringParam2, stringParam3) ) { m_kwl.addPair( COLOR_RED_KW, tempString1 ); m_kwl.addPair( COLOR_GREEN_KW, tempString2 ); m_kwl.addPair( COLOR_BLUE_KW, tempString3 ); } int color_source_idx = 0; while( ap.read("--color-source", stringParam1) ) { ossimString key = COLOR_SOURCE_KW; key += ossimString::toString(color_source_idx++); key += "."; key += ossimKeywordNames::FILE_KW; m_kwl.addPair(key.string(), tempString1 ); } if ( ap.read("--elevation", stringParam1) ) { m_kwl.addPair( std::string(ossimKeywordNames::ELEVATION_ANGLE_KW), tempString1 ); } processRemainingArgs(ap); return true; } void ossimHillshadeTool::initProcessingChain() { // Need a mosaic of DEM over the AOI as an image mosaic: ossimRefPtr demMosaic = mosaicDemSources(); m_procChain->add(demMosaic.get()); // Set up the normal source. ossimRefPtr normSource = new ossimImageToPlaneNormalFilter; normSource->setTrackScaleFlag(true); m_procChain->add( normSource.get() ); // Set the smoothness factor. ossim_float64 gain = 1.0; normSource->setSmoothnessFactor(gain); // Create the bump shade. ossimRefPtr bumpShade = new ossimBumpShadeTileSource; m_procChain->add(bumpShade.get()); // Set the azimuth angle. ossim_float64 azimuthAngle = 180; ossimString lookup = m_kwl.findKey( ossimKeywordNames::AZIMUTH_ANGLE_KW ); if ( lookup.size() ) { ossim_float64 f = lookup.toFloat64(); if ( (f >= 0) && (f <= 360) ) { azimuthAngle = f; } } bumpShade->setAzimuthAngle(azimuthAngle); // Set the elevation angle. ossim_float64 elevationAngle = 45.0; lookup = m_kwl.findKey( ossimKeywordNames::ELEVATION_ANGLE_KW ); if ( lookup.size() ) { ossim_float64 f = lookup.toFloat64(); if ( (f >= 0.0) && (f <= 90) ) { elevationAngle = f; } } bumpShade->setElevationAngle(elevationAngle); // Color can be added via color image source: if (!m_imgLayers.empty()) { // A color source image (or list) is provided. Add them as input to bump shade: ossimRefPtr colorSource = combineLayers( m_imgLayers ); bumpShade->connectMyInputTo(1, colorSource.get()); } else { // Default colors are grey: ossim_uint8 r = 0xff; ossim_uint8 g = 0xff; ossim_uint8 b = 0xff; lookup = m_kwl.findKey( COLOR_RED_KW ); if ( lookup.size() ) r = lookup.toUInt8(); lookup = m_kwl.findKey( COLOR_GREEN_KW ); if ( lookup.size() ) g = lookup.toUInt8(); lookup = m_kwl.findKey( COLOR_BLUE_KW ); if ( lookup.size() ) b = lookup.toUInt8(); bumpShade->setRgbColorSource(r, g, b); } } void ossimHillshadeTool::setUsage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); // Set app name. ossimString appName = ap.getApplicationName(); ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = appName; usageString += " hillshade [option]... [input-option]... \nNote at least one input is required either from one of the input options, e.g. --input-dem or adding to command line in front of the output file in which case the code will try to ascertain what type of input it is.\n\nAvailable traces:\n-T \"ossimChipperUtil:debug\" - General debug trace to standard out.\n-T \"ossimChipperUtil:log\" - Writes a log file to output-file.log.\n-T \"ossimChipperUtil:options\" - Writes the options to output-file-options.kwl."; au->setCommandLineUsage(usageString); // Add arguments. au->addCommandLineOption("--azimuth", "\nLight source azimuth angle for bump shade.\nRange: 0 to 360, Default = 180.0"); au->addCommandLineOption("--color"," \nSet the red, green and blue color values to be used with hillshade.\nRange 0 to 255, Default r=255, g=255, b=255"); au->addCommandLineOption("--color-source","\nSpecifies the image file to use as a color source instead of a fixed RGB value."); au->addCommandLineOption("--elevation", "\nhillshade option - Light source elevation angle for bumb shade.\nRange: 0 to 90, Default = 45.0"); // Base class has its own: ossimChipProcTool::setUsage(ap); ostringstream description; description << DESCRIPTION << "\n\nNOTES:\n" << "1) Never use same base name in the same directory! Example is you have a Chicago.tif\n" << " and you want a Chicago.jp2, output Chicago.jp2 to its own directory.\n" << "\nExample command to Hill shade: Hill shade two DEMs, output to a geotiff.\n" << appName << " --color 255 255 255 --azimuth 270 --elevation 45 --exaggeration 2.0 N37W123.hgt N38W123.hgt outputs/hillshade.tif\n" << "\n// Above command where all options are in a keyword list:\n" << appName << " --options r39-options.kwl\n" << std::endl; au->setDescription(description.str()); } ossim-Miami-2.9.1/src/util/ossimHlzTool.cpp000066400000000000000000000613151352751253100206370ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static const string MASK_EXCLUDE_KW = "exclude_regions"; static const string MASK_INCLUDE_KW = "include_regions"; static const string SLOPE_OUTPUT_FILE_KW = "slope_output_file"; static const string POINT_CLOUD_FILE_KW = "point_clouds"; static const string HLZ_CODING_KW = "hlz_coding"; static const string LZ_MIN_RADIUS_KW = "min_lz_radius"; static const string ROUGHNESS_THRESHOLD_KW = "max_roughness"; static const string SLOPE_THRESHOLD_KW = "max_slope"; const char* ossimHlzTool::DESCRIPTION = "Computes bitmap of helicopter landing zones given ROI and DEM."; ossimHlzTool::ossimHlzTool() : m_slopeThreshold(7.0), m_roughnessThreshold(0.5), m_hlzMinRadius(25.0), m_outBuffer(NULL), m_badLzValue(255), m_marginalLzValue(128), m_goodLzValue(64), m_useLsFitMethod(true), m_numThreads(1), d_accumT(0) { } ossimHlzTool::~ossimHlzTool() { } void ossimHlzTool::setUsage(ossimArgumentParser& ap) { // Add global usage options. ossimChipProcTool::setUsage(ap); // Set the general usage: ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " hlz [options] "; au->setCommandLineUsage(usageString); // Set the command line options: au->addCommandLineOption("--exclude-regions [, ...]", "List of raster image(s) representing mask files that defines regions to be excluded from " "HLZ solutions. Any non-zero pixel is excluded Multiple filenames must be comma-separated."); au->addCommandLineOption("--hlz-coding ", "Specifies the pixel values (0-255) for the output product corresponding to bad, marginal, " "and good landing zones, respectively. Defaults to bad=255 (null), marginal=128, and " "good=64."); au->addCommandLineOption("--include-regions [, ...]", "List of raster image(s) representing mask files that defines regions where the HLZs ." "identified must overlap. Any non-zero pixel represents an inclusion zone. Multiple " "filenames must be comma-separated."); au->addCommandLineOption("--output-slope ", "Generates a slope byproduct image (floating point degrees) to the specified filename. " "Only valid if normal-vector method used (i.e., --ls-fit option NOT specified)"); au->addCommandLineOption("--point-clouds [, ...]", "Specifies ancillary point-cloud data file(s) for level-2 search for obstructions. " "Must be comma-separated file names."); au->addCommandLineOption("--min-lz-radius ", "Specifies minimum radius of landing zone. Defaults to 25 m. "); au->addCommandLineOption("--max-roughness ", "Specifies the terrain roughness threshold (meters). This is the maximum deviation from a " "flat plane permitted. Defaults to 0.5 m. Valid only with --ls-fit specified."); au->addCommandLineOption("--max-slope ", "Threshold for acceptable landing zone terrain slope. Defaults to 7 deg."); au->addCommandLineOption("--threads ", "Number of threads. Defaults to use single core. For engineering/debug purposes."); au->addCommandLineOption("--use-slope", "Slope is computed from the normal vector using neighboring posts instead of " "least-squares fit to a plane (preferred). For engineering/debug purposes."); } bool ossimHlzTool::initialize(ossimArgumentParser& ap) { if (!ossimChipProcTool::initialize(ap)) return false; if (m_helpRequested) return true; string ts1; ossimArgumentParser::ossimParameter sp1(ts1); string ts2; ossimArgumentParser::ossimParameter sp2(ts2); string ts3; ossimArgumentParser::ossimParameter sp3(ts3); ossimString key ; vector maskFnames; ap.read("--exclude-regions", maskFnames); for(ossim_uint32 idx=0; idx pcFnames; ap.read("--point-clouds", pcFnames); for(ossim_uint32 idx=0; idx values = value.split(" "); if (values.size() == 3) { m_badLzValue = values[0].toUInt8(); m_marginalLzValue = values[1].toUInt8(); m_goodLzValue = values[2].toUInt8(); } else { xmsg<<"ossimHlzUtil:"<<__LINE__<<" Unexpected number of values encountered for keyword <" <."; throw(xmsg.str()); } } ossimChipProcTool::initialize(kwl); } void ossimHlzTool::initProcessingChain() { ostringstream xmsg; if (m_aoiGroundRect.hasNans() || m_aoiViewRect.hasNans()) { xmsg<<"ossimHlzUtil:"<<__LINE__<<" Encountered NaNs in AOI."<create(0, OSSIM_UINT8, 1, m_aoiViewRect.width(), m_aoiViewRect.height()); if (!m_outBuffer.valid()) { xmsg<<"ossimHlzUtil:"<<__LINE__<<" Error encountered allocating output image buffer."; throw(xmsg.str()); } m_memSource = new ossimMemoryImageSource; m_memSource->setImage(m_outBuffer); m_memSource->setImageGeometry(m_geom.get()); // If input image(s) provided, need to combine them with the product: if (m_imgLayers.empty()) { m_procChain->add(m_memSource.get()); } else { ossimRefPtr combiner = combineLayers(m_imgLayers); combiner->connectMyInputTo(m_memSource.get()); m_procChain->add(combiner.get()); } if (!m_useLsFitMethod) { // Add the slope computation engine on the elevation source. // Set up processing chain with plane to normal filter, equation combiner, and band selector. ossimRefPtr slope_filter = new ossimSlopeFilter; slope_filter->connectMyInputTo(m_combinedElevSource.get()); slope_filter->setSlopeType(ossimSlopeFilter::DEGREES); m_combinedElevSource = slope_filter.get(); m_combinedElevSource->initialize(); m_slopeFile = m_kwl.findKey(SLOPE_OUTPUT_FILE_KW); if (!m_slopeFile.empty()) writeSlopeImage(); } // Determine number of posts (in one dimension) needed to cover the specified LZ radius: if ((m_gsd.x == 0) || (m_gsd.y == 0) || m_gsd.hasNans()) { ostringstream xmsg; xmsg<<"ossimHlzUtil:"<<__LINE__<<" Invalid GSD: "< pc_handler = registry->open(pc_file); if (!pc_handler.valid()) { xmsg<<"ossimHlzUtil:"<<__LINE__<<" Error loading point cloud file <"<."; throw(xmsg.str()); } // Verify that PC bounding rect overlaps the output bounding rect: pc_handler->getBounds(pc_bbox); if (m_aoiGroundRect.intersects(pc_bbox)) { m_pcSources.push_back(pc_handler); } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimHLZUtil::loadPcFile() WARNING: point-cloud file <" << pc_file << "> " << "does not overlap the output ROI." << endl; } } } void ossimHlzTool::loadMaskFiles() { ostringstream xmsg; ossimString key; ossimFilename mask_file; // Exclusion masks: for(ossim_uint32 idx=0; true; ++idx) { key = MASK_EXCLUDE_KW; key += ossimString::toString(idx++); mask_file = m_kwl.find(key.chars()); if (mask_file.empty()) break; MaskSource mask_image (this, mask_file, true); if (mask_image.image.valid()) m_maskSources.push_back(mask_image); } // Inclusion masks: for(ossim_uint32 idx=0; true; ++idx) { key = MASK_INCLUDE_KW; key += ossimString::toString(idx++); mask_file = m_kwl.find(key.chars()); if (mask_file.empty()) break; // First check if the filename specified is an image file: MaskSource mask_image (this, mask_file, false); if (mask_image.image.valid()) m_maskSources.push_back(mask_image); } } ossimRefPtr ossimHlzTool::getChip(const ossimIrect& bounding_irect) { ostringstream xmsg; if (!m_geom.valid()) return 0; m_aoiViewRect = bounding_irect; m_geom->setImageSize( m_aoiViewRect.size() ); m_geom->localToWorld(m_aoiViewRect, m_aoiGroundRect); if (computeHLZ()) { // The memory source has been populated, now do the getTile on the full chain to pick up // other filters inserted after the memsource: return m_procChain->getTile( m_aoiViewRect, 0 ); } // else: return 0; } bool ossimHlzTool::execute() { if (m_helpRequested) return true; getChip(m_aoiViewRect); return ossimChipProcTool::execute(); } bool ossimHlzTool::computeHLZ() { // To help with multithreading, just load entire AOI of DEM into memory: m_demBuffer = m_combinedElevSource->getTile(m_aoiViewRect); if (!m_demBuffer.valid()) return false; // Allocate the output image buffer: m_outBuffer = ossimImageDataFactory::instance()->create(0, OSSIM_UINT8, 1, m_aoiViewRect.width(), m_aoiViewRect.height()); ostringstream xmsg; if (!m_outBuffer.valid() || !m_memSource.valid()) { xmsg<<"ossimHlzUtil:"<<__LINE__<<" Error encountered allocating output image buffer."; throw(xmsg.str()); } // Initialize the image with all points hidden: m_outBuffer->initialize(); m_outBuffer->setImageRectangle(m_aoiViewRect); m_outBuffer->fill(0); m_memSource->setImage(m_outBuffer); d_accumT = 0; // Establish loop limits in input DEM raster coordinate space: ossim_int32 min_x = m_aoiViewRect.ul().x; ossim_int32 min_y = m_aoiViewRect.ul().y; ossim_int32 max_x = m_aoiViewRect.lr().x - m_demFilterSize.x; ossim_int32 max_y = m_aoiViewRect.lr().y - m_demFilterSize.y; ossimIpt chip_origin; ossim_uint32 numPatches = (max_x-min_x)*(max_y-min_y); // Determine the DEM step size as a fraction of the LZ radius: const double CHIP_STEP_FACTOR = 0.25; // chip position increment as fraction of chip width ossim_int32 dem_step = (ossim_int32) floor(4*CHIP_STEP_FACTOR*m_hlzMinRadius/(m_gsd.x+m_gsd.y)); if (dem_step <= 0) dem_step = 1; // Hack: degrading to single thread when slope-image scheme is used. Runs extremely slow in // multithread mode, but much faster as single thread than multithreaded ls-fit if ((m_numThreads == 1) || !m_useLsFitMethod) { // Not threaded (or slope-image scheme): setPercentComplete(0); ossim_uint32 chipId = 0; for (chip_origin.y = min_y; chip_origin.y <= max_y; chip_origin.y += dem_step) { for (chip_origin.x = min_x; chip_origin.x <= max_x; chip_origin.x += dem_step) { std::shared_ptr job = 0; if (m_useLsFitMethod) job = std::make_shared(this, chip_origin, chipId++); else job = std::make_shared(this, chip_origin, chipId++); job->start(); } setPercentComplete(100*chipId/numPatches); } } else { if (m_numThreads == 0) m_numThreads = ossim::getNumberOfThreads(); // Loop over input DEM, creating a thread job for each filter window: std::shared_ptr jobMtQueue = std::make_shared(nullptr, m_numThreads); std::shared_ptr jobQueue = jobMtQueue->getJobQueue(); ossimNotify(ossimNotifyLevel_INFO) << "\nPreparing " << numPatches << " jobs..." << endl; // TODO: DEBUG setPercentComplete(0); ossim_int32 qsize = 0; ossimIpt chip_origin; ossim_uint32 chipId = 0; for (chip_origin.y = min_y; chip_origin.y <= max_y; ++chip_origin.y) { for (chip_origin.x = min_x; chip_origin.x <= max_x; ++chip_origin.x) { //ossimNotify(ossimNotifyLevel_INFO) << "Submitting " << chipId << endl; std::shared_ptr job = 0; if (m_useLsFitMethod) job = std::make_shared(this, chip_origin, chipId++); else job = std::make_shared(this, chip_origin, chipId++); jobQueue->add(job, false); } qsize = jobQueue->size(); setPercentComplete(100*(chipId-qsize)/numPatches); } // Wait until all chips have been processed before proceeding: ossimNotify(ossimNotifyLevel_INFO) << "All jobs queued. Waiting for job threads to finish..." << endl; while (jobMtQueue->hasJobsToProcess() || jobMtQueue->numberOfBusyThreads()) { qsize = jobMtQueue->getJobQueue()->size(); setPercentComplete(100*(numPatches-qsize)/numPatches); ossim::Thread::sleepInMicroSeconds(10000); } jobMtQueue = 0; } ossimNotify(ossimNotifyLevel_INFO) << "Finished processing chips." << endl; return true; } void ossimHlzTool::writeSlopeImage() { // Set up the writer: ossimRefPtr writer = 0; ossimTiffWriter* tif_writer = new ossimTiffWriter(); tif_writer->setGeotiffFlag(true); tif_writer->setFilename(m_slopeFile); writer = tif_writer; writer->connectMyInputTo(0, m_combinedElevSource.get()); writer->setAreaOfInterest(m_aoiViewRect); if (writer->execute()) ossimNotify(ossimNotifyLevel_INFO)<<"Wrote slope image to <"<."<."<m_demBuffer->getNullPix(0)) { m_demPatchLR.x = m_demPatchUL.x + m_hlzUtil->m_demFilterSize.x; m_demPatchLR.y = m_demPatchUL.y + m_hlzUtil->m_demFilterSize.y; } void ossimHlzTool::PatchProcessorJob::run() { bool passed = level1Test() && level2Test() && maskTest(); ossimIpt p; std::lock_guard lock (m_bufMutex); for (p.y = m_demPatchUL.y; p.y < m_demPatchLR.y; ++p.y) { for (p.x = m_demPatchUL.x; p.x < m_demPatchLR.x; ++p.x) { if (passed && (m_status == 2)) m_hlzUtil->m_outBuffer->setValue(p.x, p.y, m_hlzUtil->m_goodLzValue); else if (passed && (m_status == 1)) m_hlzUtil->m_outBuffer->setValue(p.x, p.y, m_hlzUtil->m_marginalLzValue); else m_hlzUtil->m_outBuffer->setValue(p.x, p.y, m_hlzUtil->m_badLzValue); } } } bool ossimHlzTool::LsFitPatchProcessorJob::level1Test() { // Start with computing best-fit plane: ossimIpt p; double z; double y_meters; for (p.y = m_demPatchUL.y; p.y < m_demPatchLR.y; ++p.y) { y_meters = p.y*m_hlzUtil->m_gsd.y; for (p.x = m_demPatchUL.x; p.x < m_demPatchLR.x; ++p.x) { z = m_hlzUtil->m_demBuffer->getPix(p, 0); if ((z == m_nullValue) || ossim::isnan(z)) return false; m_plane->addSample(p.x*m_hlzUtil->m_gsd.x, y_meters, z); } } if (!m_plane->solveLS()) return false; // The slope is derived from the normal unit vector. Extract that from the solution and test // against threshold: double a, b, c; m_plane->getLSParms(a, b, c); double z_proj = 1.0 / sqrt(a*a + b*b + 1.0); double theta = fabs(ossim::acosd(z_proj)); if (theta > m_hlzUtil->m_slopeThreshold) return false; // Passed the slope test. Now measure the roughness as peak deviation from the plane: double distance; for (p.y = m_demPatchUL.y; (p.y < m_demPatchLR.y); ++p.y) { for (p.x = m_demPatchUL.x; (p.x < m_demPatchLR.x); ++p.x) { z = m_hlzUtil->m_demBuffer->getPix(p, 0); distance = fabs(z_proj * (a*p.x + b*p.y + c - z)); if (distance > m_hlzUtil->m_roughnessThreshold) return false; } } m_status = 1; // indicates passed level 1 return true; } bool ossimHlzTool::NormPatchProcessorJob::level1Test() { // The processing chain is outputing slope values in degrees from vertical. // Scan the data tile for slopes outside the threshold: ossimIpt p; float theta; for (p.y = m_demPatchUL.y; p.y < m_demPatchLR.y; ++p.y) { for (p.x = m_demPatchUL.x; p.x < m_demPatchLR.x; ++p.x) { theta = m_hlzUtil->m_demBuffer->getPix(p, 0); if ((theta == m_nullValue) || ossim::isnan(theta) || (theta > m_hlzUtil->m_slopeThreshold)) return false; } } m_status = 1; // indicates passed level 1 return true; } bool ossimHlzTool::PatchProcessorJob::level2Test() { // Level 2 only valid if a point cloud dataset is available: if (m_hlzUtil->m_pcSources.empty()) { ++m_status; // assumes level2 passes return true; } // Need to convert DEM file coordinate bounds to geographic. ossimGpt chipUlGpt, chipLrGpt; m_hlzUtil->m_geom->localToWorld(ossimDpt(m_demPatchUL), chipUlGpt); m_hlzUtil->m_geom->localToWorld(ossimDpt(m_demPatchLR), chipLrGpt); chipUlGpt.hgt = ossim::nan(); chipLrGpt.hgt = ossim::nan(); ossimGrect grect (chipUlGpt, chipLrGpt); // TODO: LIMITATION: Only a single point cloud source is considered. Need to expand to handle // a list: const ossimPointCloudHandler* pc_src = m_hlzUtil->m_pcSources[0].get(); // First check if there is even any coverage: m_status = 0; // reset assumes no coverage ossimGrect bb; pc_src->getBounds(bb); if (!bb.intersects(grect)) return false; ossimPointBlock pc_block(0, ossimPointRecord::ReturnNumber|ossimPointRecord::NumberOfReturns); pc_src->getBlock(grect, pc_block); if (pc_block.empty()) return false; bool found_obstruction = false; // Scan the block for obstructions: ossimGpt point_plh; ossimDpt point_xy; ossim_uint32 numPoints = pc_block.size(); for (ossim_uint32 i=0; (igetField(ossimPointRecord::NumberOfReturns); if (num_returns > 1) { found_obstruction = true; break; } } if (!found_obstruction) m_status = 2; return true; } bool ossimHlzTool::PatchProcessorJob::maskTest() { // Threat dome only valid if a mask source is available: if (m_hlzUtil->m_maskSources.empty()) return true; ossimIrect chipRect (m_demPatchUL, m_demPatchLR); vector::iterator mask_source = m_hlzUtil->m_maskSources.begin(); bool test_passed = true; ossimIpt p; ossim_uint8 mask_value; while ((mask_source != m_hlzUtil->m_maskSources.end()) && test_passed) { ossimRefPtr mask_data = mask_source->image->getTile(chipRect); for (p.y = m_demPatchUL.y; (p.y < m_demPatchLR.y) && test_passed; ++p.y) { for (p.x = m_demPatchUL.x; (p.x < m_demPatchLR.x) && test_passed; ++p.x) { mask_value = mask_data->getPix(p); if (( mask_value && mask_source->exclude) || (!mask_value && !mask_source->exclude)) test_passed = false; } } ++mask_source; } return test_passed; } ossimHlzTool::MaskSource::MaskSource(ossimHlzTool* hlzUtil, const ossimFilename& mask_image, bool exclusion) : exclude (exclusion) { image = hlzUtil->createInputChain(mask_image); } ossim-Miami-2.9.1/src/util/ossimImageUtil.cpp000066400000000000000000002167571352751253100211400ustar00rootroot00000000000000//---------------------------------------------------------------------------- // File: ossimImageUtil.cpp // // License: MIT // // Author: David Burken // // Description: ossimImageUtil class definition // // Utility class for processing image recursively. This is for doing things like: // building overview, histograms, compute min/max, extract vertices. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static std::string CMM_MAX_KW = "cmm_max"; // CMM(ComputeMinMax) static std::string CMM_MIN_KW = "cmm_min"; static std::string CMM_NULL_KW = "cmm_null"; static std::string COPY_ALL_FLAG_KW = "copy_all_flag"; static std::string CREATE_HISTOGRAM_KW = "create_histogram"; static std::string CREATE_HISTOGRAM_FAST_KW = "create_histogram_fast"; static std::string CREATE_HISTOGRAM_R0_KW = "create_histogram_r0"; static std::string CREATE_OVERVIEWS_KW = "create_overviews"; static std::string CREATE_THUMBNAILS_KW = "create_thumbnails"; static std::string DUMP_FILTERED_IMAGES_KW = "dump_filter_image"; static std::string FALSE_KW = "false"; static std::string FILE_KW = "file"; static std::string INTERNAL_OVERVIEWS_FLAG_KW = "internal_overviews_flag"; static std::string OUTPUT_DIRECTORY_KW = "output_directory"; static std::string OUTPUT_FILENAMES_KW = "output_filenames"; static std::string OVERRIDE_FILTERED_IMAGES_KW = "override_filtered_images"; static std::string OVERVIEW_STOP_DIM_KW = "overview_stop_dimension"; static std::string OVERVIEW_TYPE_KW = "overview_type"; static std::string READER_PROP_KW = "reader_prop"; static std::string REBUILD_HISTOGRAM_KW = "rebuild_histogram"; static std::string REBUILD_OVERVIEWS_KW = "rebuild_overviews"; static std::string SCAN_MIN_MAX_KW = "scan_for_min_max"; static std::string SCAN_MIN_MAX_NULL_KW = "scan_for_min_max_null"; static std::string THREADS_KW = "threads"; static std::string THUMBNAIL_SIZE_KW = "thumbnail_size"; static std::string THUMBNAIL_STRETCH_TYPE_KW = "thumbnail_stretch_type"; static std::string THUMBNAIL_TYPE_KW = "thumbnail_type"; static std::string TILE_SIZE_KW = "tile_size"; static std::string TRUE_KW = "true"; static std::string WRITER_PROP_KW = "writer_prop"; // Static trace for debugging. Use -T ossimImageUtil to turn on. static ossimTrace traceDebug = ossimTrace("ossimImageUtil:debug"); ossimImageUtil::ossimImageUtil() : ossimReferenced(), ossimFileProcessorInterface(), m_kwl( new ossimKeywordlist() ), m_fileWalker(0), m_mutex(), m_errorStatus(0), m_filteredImages(0) { } ossimImageUtil::~ossimImageUtil() { if ( m_fileWalker ) { delete m_fileWalker; m_fileWalker = 0; } } void ossimImageUtil::addOptions(ossimApplicationUsage* au) { // Set the command line options: au->addCommandLineOption("-a or --include-fullres", "Copy full res dataset to overview file as well as building reduced res sets. Option only valid with tiff overview builder. Requires -o option."); au->addCommandLineOption("--ch or --create-histogram", "Computes full histogram alongside overview."); au->addCommandLineOption("--chf or --create-histogram-fast", "Computes a histogram in fast mode which samples partial tiles."); au->addCommandLineOption("--ct or --create-thumbnail", "computes a thumbnail of the image"); au->addCommandLineOption("--tt or --thumbnail-type", "Can be of of values png or jpeg"); au->addCommandLineOption("--tst or --thumbnail-stretch-type", "Can be of values none,auto-minmax,auto-percentile,std-stretch-1,std-stretch-2,std-stretch-3"); au->addCommandLineOption("--compression-quality", "Compression quality for TIFF JPEG takes values from 0 to 100, where 100 is best. For J2K plugin, numerically_lossless, visually_lossless, lossy"); au->addCommandLineOption("--compute-min-max", "Turns on min, max scanning when reading tiles and writes a dot omd file. This option assumes the null is known."); au->addCommandLineOption("--compute-min-max-null", "Turns on min, max, null scanning when reading tiles and write a dot omd file. This option tries to find a null value which is useful for float data."); au->addCommandLineOption("--compression-type", "Compression type can be: deflate, jpeg, lzw, none or packbits"); au->addCommandLineOption("--create-histogram-r0", "Forces create-histogram code to compute a histogram using r0 instead of the starting resolution for the overview builder. Can require a separate pass of R0 layer if the base image has built in overviews."); au->addCommandLineOption("-d", " Write overview to output directory specified."); au->addCommandLineOption("--dump-filtered-image-list", "Outputs list of filtered images and extensions."); au->addCommandLineOption("-h", "Display this information"); au->addCommandLineOption("-i or --internal-overviews", "Builds internal overviews. Requires -o option. Option only valid with tiff input image and tiff overview builder. WARNING: Modifies source image and cannot be undone!"); au->addCommandLineOption("--list-entries", "Lists the entries within the image"); au->addCommandLineOption("--max","Overrides max value for compute-min-max option."); au->addCommandLineOption("--min","Overrides min value for compute-min-max option."); au->addCommandLineOption("--null", " Overrides null value for compute-min-max option. e.g. -9999.0 for float data"); au->addCommandLineOption("-o", "Creates overviews. (default=ossim_tiff_box)"); au->addCommandLineOption("--of or --output-files", "Output image files we can open, exluding overviews."); au->addCommandLineOption("--options"," This can be all or part of the application options. Also used for custom prep, per file and post system commands. To get a template you can turn on trace to the ossimImageUtil class by adding \"-T ossimImageUtil\" to your command."); au->addCommandLineOption("--ot", " Overview type. see list at bottom for valid types. (default=ossim_tiff_box)"); au->addCommandLineOption("--override-filtered-images", "Allows processing of file that is in the filtered image list."); au->addCommandLineOption("-r or --rebuild-overviews", "Rebuild overviews even if they are already present."); au->addCommandLineOption("--rebuild-histogram", "Rebuild histogram even if they are already present."); au->addCommandLineOption("--reader-prop", "Adds a property to send to the reader. format is name=value"); au->addCommandLineOption("-s", "Stop dimension for overviews. This controls how \nmany layers will be built. If set to 64 then the builder will stop when height and width for current level are less than or equal to 64. Note a default can be set in the ossim preferences file by setting the keyword \"overview_stop_dimension\"."); au->addCommandLineOption("--tile-size", " Defines the tile size for overview builder. Tiff option only. Must be a multiple of 16. Size will be used in both x and y directions. Note a default can be set in your ossim preferences file by setting the key \"tile_size\"."); au->addCommandLineOption("--threads", " The number of threads to use. (default=1) Note a default can be set in your ossim preferences file by setting the key \"ossim_threads\"."); au->addCommandLineOption("--writer-prop", "Adds a property to send to the writer. format is name=value"); } void ossimImageUtil::addArguments(ossimArgumentParser& ap) { // Set the general usage: ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " [options] "; au->setCommandLineUsage(usageString); addOptions(au); } // void ossimImageUtil::addArguments(ossimArgumentParser& ap) bool ossimImageUtil::initialize(ossimArgumentParser& ap) { static const char M[] = "ossimImageUtil::initialize(ossimArgumentParser&)"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } bool result = true; if ( (ap.argc() == 1) || ap.read("-h") || ap.read("--help") ) { usage(ap); // continue_after_init to false result = false; } else { // Start with clean options keyword list. m_kwl->clear(); // Used throughout below: std::string ts1; ossimArgumentParser::ossimParameter sp1(ts1); std::string ts2; ossimArgumentParser::ossimParameter sp2(ts2); while ( 1 ) // While forever loop... { if( ap.read("-a") || ap.read("--include-fullres") ) { setCopyAllFlag( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--compression-quality", sp1) ) { if ( ts1.size() ) { setCompressionQuality( ts1 ); } if ( ap.argc() < 2 ) { break; } } if( ap.read("--compression-type", sp1) ) { if ( ts1.size() ) { setCompressionType( ts1 ); } if ( ap.argc() < 2 ) { break; } } if( ap.read("--ch") || ap.read("--create-histogram") ) { setCreateHistogramFlag( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--chf") || ap.read("--create-histogram-fast") ) { setCreateHistogramFastFlag( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--compute-min-max") ) { setScanForMinMax( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--compute-min-max-null") ) { setScanForMinMaxNull( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--create-histogram-r0") ) { setCreateHistogramR0Flag( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-d", sp1) ) { setOutputDirectory( ts1 ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--dump-filtered-image-list") ) { setDumpFilteredImageListFlag( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-i") || ap.read("--internal-overviews") ) { setInternalOverviewsFlag( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--max", sp1) ) { addOption( CMM_MAX_KW, ts1 ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--min", sp1) ) { addOption( CMM_MIN_KW, ts1 ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--null", sp1) ) { addOption( CMM_NULL_KW, ts1 ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--options", sp1) ) { ossimFilename optionsKwl = ts1; if ( optionsKwl.exists() ) { if ( m_kwl->addFile(optionsKwl) == false ) { std::string errMsg = "ERROR could not open options keyword list file: "; errMsg += optionsKwl.string(); throw ossimException(errMsg); } } else { std::string errMsg = "ERROR options keyword list file does not exists: "; errMsg += optionsKwl.string(); throw ossimException(errMsg); } } if( ap.read("--of") || ap.read("--output-files") ) { setOutputFileNamesFlag( true ); if ( ap.argc() < 2 ) { break; } } if (ap.read("-o")) { setCreateOverviewsFlag(true); if (ap.argc() < 2) { break; } } if (ap.read("--ct")) { setCreateThumbnailsFlag(true); if (ap.argc() < 2) { break; } } if (ap.read("--tt", sp1) || ap.read("--thumbnail-type", sp1)) { setThumbnailType(ts1); if (ap.argc() < 2) { break; } } if (ap.read("--tst", sp1) || ap.read("--thumbnail-stretch-type", sp1)) { setThumbnailStretchType(ts1); if (ap.argc() < 2) { break; } } if (ap.read("--ot", sp1)) { setOverviewType( ts1 ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--override-filtered-images") ) { setOverrideFilteredImagesFlag( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-r") || ap.read("--rebuild-overviews") ) { setRebuildOverviewsFlag( true ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--rebuild-histogram") ) { setRebuildHistogramFlag( true ); if ( ap.argc() < 2 ) { break; } } while(ap.read("--reader-prop", sp1)) { if (ts1.size()) { std::string key = READER_PROP_KW; key += ossimString::toString( getNextReaderPropIndex() ).string(); addOption( key, ts1 ); } } if ( ap.argc() < 2 ) { break; } if( ap.read("-s", sp1) ) { setOverviewStopDimension( ts1 ); if ( ap.argc() < 2 ) { break; } } if ( ap.read("--tile-size", sp1)) { setTileSize( ossimString(ts1).toInt32() ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--threads", sp1) ) { m_kwl->addPair( THREADS_KW, ts1 ); if ( ap.argc() < 2 ) { break; } } while(ap.read("--writer-prop", sp1)) { if (ts1.size()) { std::string key = WRITER_PROP_KW; key += ossimString::toString( getNextWriterPropIndex() ).string(); addOption( key, ts1 ); } } if ( ap.argc() < 2 ) { break; } // End of arg parsing. ap.reportRemainingOptionsAsUnrecognized(); if ( ap.errors() ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); std::string errMsg = "Unknown option..."; throw ossimException(errMsg); } break; // Break from while forever. } // End while (forever) loop. if(ap.argc() > 1) { for (ossim_int32 i = 0; i < (ap.argc()-1); ++i) { ossimString kw = FILE_KW; kw += ossimString::toString(i); std::string value = ap[i+1]; m_kwl->addPair(kw.string(), value, true); } } else { if ( getDumpFilterImagesFlag() ) { // Caller wants to see filtered image names: if ( m_filteredImages.empty() ) { initializeDefaultFilterList(); } // Dump our filtered images. dumpFilteredImageList(); if ( !m_fileWalker ) { m_fileWalker = new ossimFileWalker(); m_fileWalker->initializeDefaultFilterList(); } // Dump the file walker's filtered extensions. m_fileWalker->dumpFilteredExtensionList(); } else { usage(ap); } // continue_after_init to false result = false; } } // not usage if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "m_kwl:\n" << *(m_kwl.get()) << "\n" << M << " exit result = " << (result?"true":"false") << "\n"; } return result; } ossim_int32 ossimImageUtil::execute() { static const char M[] = "ossimImageUtil::execute()"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } // Launch any prep system commands: executePrepCommands(); // Get the number of "file*" keywords. ossim_uint32 fileCount = m_kwl->numberOf("file"); if ( fileCount ) { if ( !m_fileWalker ) { m_fileWalker = new ossimFileWalker(); } m_fileWalker->setNumberOfThreads( getNumberOfThreads() ); // Must set this so we can stop recursion on directory based images. m_fileWalker->setWaitOnDirFlag( true ); // This links the file walker back to our "processFile" method. m_fileWalker->setFileProcessor( this ); // Wrap in try catch block as excptions can be thrown under the hood. try { // Get the list of files passed to us: std::vector files; ossim_uint32 processedFiles = 0;; ossim_uint32 i = 0; while ( processedFiles < fileCount ) { ossimString key = FILE_KW; key += ossimString::toString(i); std::string lookup = m_kwl->findKey( key.string() ); if ( lookup.size() ) { files.push_back( ossimFilename(lookup) ); ++processedFiles; } ++i; if ( i > (fileCount + 100) ) break; } //--- // If the file count is one and it is not a directory, we will assume // the caller wanted to process that file. So leave the filter list // blank. //--- if ( (getOverrideFilteredImagesFlag() == false) && files.size() && ( (files.size() > 1) || (files[0].isDir() == true) ) ) { if ( m_filteredImages.empty() ) { initializeDefaultFilterList(); } if ( m_fileWalker->getFilteredExtensions().empty() ) { m_fileWalker->initializeDefaultFilterList(); } } // Process the files: m_fileWalker->walk( files ); } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << "Caught exception: " << e.what() << endl; setErrorStatus( ossimErrorCodes::OSSIM_ERROR ); } } // if ( fileCount ) // Launch any post system commands: executePostCommands(); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exit status: " << m_errorStatus << std::endl; } // Zero is good, non zero is bad. return m_errorStatus; } //--- // This method is called back by the ossimFileWalker::walk method for each file it finds that it // deems can be processed. //--- void ossimImageUtil::processFile(const ossimFilename& file) { static const char M[] = "ossimImageUtil::processFile"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n" << "file: " << file << "\n"; } bool processFileFlag = true; if ( !getOverrideFilteredImagesFlag() ) { processFileFlag = !isFiltered( file ); } if ( processFileFlag ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Processing file: " << file << std::endl; m_mutex.lock(); ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(file, true, true); m_mutex.unlock(); if ( ih.valid() && !ih->hasError() ) { // Check for output directory: if ( m_kwl->hasKey( OUTPUT_DIRECTORY_KW ) ) { ossimFilename outputDir; outputDir.string() = m_kwl->findKey( OUTPUT_DIRECTORY_KW ); if ( outputDir.exists() && outputDir.isDir() ) { ih->setSupplementaryDirectory( outputDir ); } } if ( isDirectoryBasedImage( ih.get() ) ) { // Tell the walker not to recurse this directory. m_mutex.lock(); m_fileWalker->setRecurseFlag(false); m_mutex.unlock(); } // Set any reader props: ossimPropertyInterface* pi = dynamic_cast(ih.get()); if ( pi ) setProps(pi); bool consumedHistogramOptions = false; bool consumedCmmOptions = false; if ( getOutputFileNamesFlag() ) { // Simply output the file name of any images we can open: ossimNotify(ossimNotifyLevel_NOTICE) << ih->getFilename().expand(); } // Compute/Scan for min, max. Note the overview sequencer may have computed for us. if ( ( scanForMinMax() || scanForMinMaxNull() ) && !consumedCmmOptions ) { computeMinMax( ih ); } if ( createOverviews() ) { // Skip shape files... if ( ih->getClassName() != "ossimOgrGdalTileSource" ) { createOverview(ih, consumedHistogramOptions, consumedCmmOptions); } } if (createThumbnails()) { for (ossim_uint32 idx = 0; idx < ih->getNumberOfEntries(); ++idx) { ih->setCurrentEntry(idx); if (ih->getNumberOfDecimationLevels() <= 1) { ih->setState(0); ih->openOverview(); } createThumbnail(ih); } } // Build stand alone histogram. Note the overview sequencer may have computed for us. if ( hasHistogramOption() && !consumedHistogramOptions) { createHistogram( ih ); } // Launch any file system commands. executeFileCommands( file ); } else { ossimNotify(ossimNotifyLevel_WARN) << M << "\nCould not open: " << file << std::endl; } } else // Matches: if ( processFileFlag ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Filtered file, not processing: " << file << std::endl; } if(traceDebug()) { // Since ossimFileWalker is threaded output the file so we know which job exited. ossimNotify(ossimNotifyLevel_DEBUG) << M << "\nfile: " << file << "\nexited...\n"; } } // Create overview for image: void ossimImageUtil::createOverview( ossimRefPtr& ih, bool& consumedHistogramOptions, bool& consumedCmmOptions ) { static const char M[] = "ossimImageUtil::createOverview #1"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if ( ih.valid() ) { // Get the entry list: std::vector entryList; ih->getEntryList(entryList); bool useEntryIndex = false; if ( entryList.size() ) { if ( (entryList.size() > 1) || (entryList[0] != 0) ) useEntryIndex = true; } // Create the overview builder: ossimString overviewType; getOverviewType( overviewType.string() ); ossimRefPtr ob = ossimOverviewBuilderFactoryRegistry::instance()->createBuilder(overviewType); if ( ob.valid() ) { // Set up any overview builder options that don't involve histograms. ossimPropertyInterface* pi = dynamic_cast( ob.get() ); if ( pi ) setProps(pi); ossim_uint32 stopDimension = getOverviewStopDimension(); if ( stopDimension ) ob->setOverviewStopDimension(stopDimension); if ( ( scanForMinMax() || scanForMinMaxNull() ) && !hasCmmOption() ) { //--- // If scan is set and we don't have any min, max, null overrides let the // overview builder scan for min, max. // // If min, max, or null option is set, scan will be performed in // separate function. //--- ob->setScanForMinMax( scanForMinMax() ); ob->setScanForMinMaxNull( scanForMinMaxNull() ); consumedCmmOptions = true; } for(ossim_uint32 idx = 0; idx < entryList.size(); ++idx) { createOverview(ih, ob, entryList[idx], useEntryIndex, consumedHistogramOptions); } } else { ossimNotify(ossimNotifyLevel_WARN) << "ERROR:\nCould not create builder for: "<< overviewType << std::endl; outputOverviewWriterTypes(); } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n"; } } // Create overview for entry: void ossimImageUtil::createOverview(ossimRefPtr& ih, ossimRefPtr& ob, ossim_uint32 entry, bool useEntryIndex, bool& consumedHistogramOptions) { static const char M[] = "ossimImageUtil::createOverview #2"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if ( ih.valid() && ob.valid() ) { if (useEntryIndex) { // Set entry before deriving file name. ih->setCurrentEntry(entry); ossimNotify(ossimNotifyLevel_NOTICE) << "entry number: "<< entry << std::endl; } ossimFilename outputFile = ih->getFilenameWithThisExtension(ossimString(".ovr"), useEntryIndex); if ( rebuildOverviews() ) { ih->closeOverview(); if ( outputFile.exists() ) { outputFile.remove(); } } if ( getInternalOverviewsFlag() ) { if ( ih->getClassName() == "ossimTiffTileSource") { //--- // INTERNAL_OVERVIEWS_FLAG_KW is set to true: // Tiff reader can handle internal overviews. Set the output file to // input file. Do it after the above remove so that if there were // external overviews they will get removed. //--- outputFile = ih->getFilename(); } else { ossimNotify(ossimNotifyLevel_NOTICE) << "Internal overviews not supported for reader type: " <getClassName() << "\nIgnoring option..." << endl; } } if ( hasRequiredOverview( ih, ob ) == false ) { //--- // Set create histogram code... // // Notes: // 1) Must put this logic after any removal of external overview file. // // 2) Base file could have built in overviews, e.g. jp2 files. So the sequensor could // start at R6 even if there is no external overview file. // // 3) If user want the histogram from R0 the overview builder can do as long as // ossimImageHandler::getNumberOfDecimationLevels returns 1. If we are starting // overview building at R6 then we must do the create histogram in a separate path. //--- ossimHistogramMode histoMode = OSSIM_HISTO_MODE_UNKNOWN; if ( createHistogram() || ( createHistogramR0() && ( ih->getNumberOfDecimationLevels() == 1 ) ) ) { histoMode = OSSIM_HISTO_MODE_NORMAL; } else if ( createHistogramFast() ) { histoMode = OSSIM_HISTO_MODE_FAST; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Histogram mode: " << histoMode << "\n"; } if ( histoMode != OSSIM_HISTO_MODE_UNKNOWN ) { consumedHistogramOptions = true; ob->setHistogramMode(histoMode); ossimNotify(ossimNotifyLevel_NOTICE) << "Creating overviews with histogram for file: " << ih->getFilename() << std::endl; } else { if ( histoMode != OSSIM_HISTO_MODE_UNKNOWN ) { consumedHistogramOptions = false; ossimNotify(ossimNotifyLevel_NOTICE) << "Creating overviews for file: " << ih->getFilename() << std::endl; } } //--- // Set properties, e.g. tile size. Must be set before the call to // ob->setInputSource(...) //--- std::vector< ossimRefPtr > propertyList(0); ossimIpt tileSize; if ( getTileSize( tileSize ) == true ) { propertyList.push_back(new ossimStringProperty(ossimKeywordNames::OUTPUT_TILE_SIZE_KW, tileSize.toString())); ob->setProperties(propertyList); } ob->setOutputFile(outputFile); ob->setInputSource(ih.get()); // Create the overview for this entry in this file: if ( ob->execute() == false ) { setErrorStatus( ossimErrorCodes::OSSIM_ERROR ); ossimNotify(ossimNotifyLevel_WARN) << "Error returned creating overviews for file: " << ih->getFilename() << std::endl; } } else { consumedHistogramOptions = false; ossimNotify(ossimNotifyLevel_NOTICE) << "Image has required reduced resolution data sets." << std::endl; } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n"; } } void ossimImageUtil::createThumbnail(ossimRefPtr &ih) { ossimKeywordlist bandsKeywordList; bandsKeywordList.add("type", "ossimBandSelector"); bandsKeywordList.add(ossimKeywordNames::BANDS_KW, "default"); ossimRefPtr bs = ossimImageSourceFactoryRegistry::instance()->createImageSource(bandsKeywordList); if (!bs) return; ossimIrect cutRect; ossimRefPtr renderer = new ossimImageRenderer(); ossimRefPtr scalarRemapper = new ossimScalarRemapper(); ossimRefPtr cutFilter = new ossimRectangleCutFilter(); ossimRefPtr trans = new ossimImageViewAffineTransform(); ossimDrect bounds = ih->getBoundingRect(); ossim_float64 maxSize = ossim::max(bounds.width(), bounds.height()); ossim_float64 thumbnailSize = getThumbnailSize(); ossim_float64 scale = thumbnailSize / maxSize; ossimFilename thumbnailFilename = getThumbnailFilename(ih.get()); ossimHistogramRemapper::StretchMode thumbnailStretchType = static_cast (getThumbnailStretchType()); if (scale > 1.0) { scale = 1.0; cutRect = bounds; } else { cutRect = bounds * scale; } cutFilter->setRectangle(cutRect); if ((scale < .5) && (ih->getNumberOfDecimationLevels() < 2)) { return; } trans->scale(scale, scale); renderer->setImageViewTransform(trans.get()); if (!bs.valid()) return; bs->connectMyInputTo(ih.get()); bs->initialize(); ossim_uint32 bandCount = bs->getNumberOfInputBands(); if ((bandCount == 2) || (bandCount > 3)) { ossimBandSelector *tempBs = dynamic_cast(bs.get()); if (tempBs) { tempBs->setThreeBandRgb(); } } ossimRefPtr stretch = new ossimHistogramRemapper(); stretch->setStretchMode(thumbnailStretchType); ossimFilename histogramFilename = ih->createDefaultHistogramFilename(); //if (!histogramFilename.empty()) //{ // histogramFile = m_histogramFilename; // } stretch->connectMyInputTo(bs.get()); stretch->openHistogram(histogramFilename); renderer->connectMyInputTo(stretch.get()); scalarRemapper->connectMyInputTo(renderer.get()); cutFilter->connectMyInputTo(scalarRemapper.get()); ossimKeywordlist writerKwl; ossimString ext = thumbnailFilename.ext(); ext = ext.downcase(); writerKwl.add("type", "image/" + ext); writerKwl.add("filename", thumbnailFilename.c_str()); writerKwl.add("create_external_geometry", "false"); if (ext == "png") { writerKwl.add("add_alpha_channel", "true"); } ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriter(writerKwl); if (writer) { writer->connectMyInputTo(cutFilter.get()); writer->execute(); writer->disconnect(); writer = 0; } scalarRemapper->disconnect(); scalarRemapper = 0; cutFilter->disconnect(); cutFilter = 0; renderer->disconnect(); renderer = 0; stretch->disconnect(); stretch = 0; bs->disconnect(); bs = 0; } bool ossimImageUtil::hasRequiredOverview( ossimRefPtr& ih, ossimRefPtr& ob ) { bool result = false; if ( ih.valid() && ob.valid() && ( getCopyAllFlag() == false ) ) { if ( ih->getClassName() == "ossimCcfTileSource" ) { // CCF reader does not use external overviews. result = true; } else { // Note we always have one rset ossim_uint32 required = 1; ossim_uint32 startingResLevel = ih->getNumberOfDecimationLevels(); ossim_uint32 overviewStopDimension = ob->getOverviewStopDimension(); ossim_uint32 largestImageDimension = ih->getNumberOfSamples(0) > ih->getNumberOfLines(0) ? ih->getNumberOfSamples(0) : ih->getNumberOfLines(0); while(largestImageDimension > overviewStopDimension) { largestImageDimension /= 2; ++required; } if ( startingResLevel >= required ) { result = true; } } } return result; } void ossimImageUtil::createHistogram(ossimRefPtr& ih) { static const char M[] = "ossimImageUtil::createHistogram #1"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if ( ih.valid() ) { // Get the entry list: std::vector entryList; ih->getEntryList(entryList); bool useEntryIndex = false; if ( entryList.size() ) { if ( (entryList.size() > 1) || (entryList[0] != 0) ) useEntryIndex = true; } for(ossim_uint32 idx = 0; idx < entryList.size(); ++idx) { createHistogram(ih, entryList[idx], useEntryIndex); } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n"; } } // Create histogram for entry: void ossimImageUtil::createHistogram(ossimRefPtr& ih, ossim_uint32 entry, bool useEntryIndex) { static const char M[] = "ossimImageUtil::createHistogram #2"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if ( ih.valid() ) { if (useEntryIndex) { // Set entry before deriving file name. ih->setCurrentEntry(entry); ossimNotify(ossimNotifyLevel_NOTICE) << "entry number: "<< entry << std::endl; } ossimFilename outputFile = ih->getFilenameWithThisExtension(ossimString(".his"), useEntryIndex); // Only build if needed: if ( (outputFile.exists() == false) || rebuildHistogram() ) { ossimNotify(ossimNotifyLevel_NOTICE) << "Computing histogram for file: " << ih->getFilename() << std::endl; // Check handler to see if it's filtering bands. std::vector originalBandList(0); if ( ih->isBandSelector() ) { // Capture for finalize method. ih->getOutputBandList( originalBandList ); // Set output list to input. ih->setOutputToInputBandList(); } ossimRefPtr histoSource = new ossimImageHistogramSource; ossimRefPtr writer = new ossimHistogramWriter; histoSource->setMaxNumberOfRLevels(1); // Currently hard coded... #if 0 /* TODO tmp drb */ if( !ossim::isnan(histoMin) ) { histoSource->setMinValueOverride(histoMin); } if( !ossim::isnan(histoMax) ) { histoSource->setMaxValueOverride(histoMax); } if(histoBins > 0) { histoSource->setNumberOfBinsOverride(histoBins); } #endif if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "Histogram mode: " << getHistogramMode() << "\n"; } // Connect histogram source to image handler. histoSource->setComputationMode( getHistogramMode() ); histoSource->connectMyInputTo(0, ih.get() ); histoSource->enableSource(); // Connect writer to histogram source. writer->connectMyInputTo(0, histoSource.get()); writer->setFilename(outputFile); theStdOutProgress.setFlushStreamFlag(true); writer->addListener(&theStdOutProgress); // Compute... writer->execute(); writer=0; // Reset the band list. if ( ih->isBandSelector() && originalBandList.size() ) { ih->setOutputBandList( originalBandList ); } } // Matches: if ( (outputFile.exists() == false) || rebuildHistogram() ) } // Matches: if ( ih.valid() ) if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n"; } } // End: ossimImageUtil::createHistogram #2 void ossimImageUtil::computeMinMax(ossimRefPtr& ih) { static const char M[] = "ossimImageUtil::computeMinMax #1"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if ( ih.valid() ) { // Get the entry list: std::vector entryList; ih->getEntryList(entryList); bool useEntryIndex = false; if ( entryList.size() ) { if ( (entryList.size() > 1) || (entryList[0] != 0) ) useEntryIndex = true; } for(ossim_uint32 idx = 0; idx < entryList.size(); ++idx) { computeMinMax(ih, entryList[idx], useEntryIndex); } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n"; } } // End: ossimImageUtil::computeMinMax( ih ) void ossimImageUtil::computeMinMax( ossimRefPtr& ih, ossim_uint32 entry, bool useEntryIndex ) { static const char M[] = "ossimImageUtil::computeMinMax #2"; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if ( ih.valid() ) { // Get any min, max, null overrides; double maxValue = ossim::nan(); double minValue = ossim::nan(); double nullValue = ossim::nan(); ossimString value = m_kwl->findKey( CMM_MAX_KW ); if ( value.size() ) { maxValue = value.toDouble(); } value = m_kwl->findKey( CMM_MIN_KW ); if ( value.size() ) { minValue = value.toDouble(); } bool hasNull = false; value = m_kwl->findKey( CMM_NULL_KW ); if ( value.size() ) { nullValue = value.toDouble(); if ( !ossim::isnan(nullValue) ) { hasNull = true; } } // Select the entry. ih->setCurrentEntry( entry ); // Build the .omd file name. ossimFilename omd_file = ih->getFilename();; // Check for output directory: if ( m_kwl->hasKey( OUTPUT_DIRECTORY_KW ) ) { ossimFilename outputDir; outputDir.string() = m_kwl->findKey( OUTPUT_DIRECTORY_KW ); if ( outputDir.exists() && outputDir.isDir() ) { omd_file = outputDir.dirCat( omd_file.file() ); } } if ( useEntryIndex ) { ossim_uint32 currentEntry = ih->getCurrentEntry(); omd_file.setExtension(""); omd_file += "_e"; omd_file += ossimString::toString(currentEntry); //--- // Note: Set extension was not used here deliberately to avoid // messing // up a MODIS file in hdf format with multiple '.'s in the file // name. //--- omd_file += ".omd"; } else { omd_file.setExtension("omd"); } ossimRefPtr is = new ossimImageSourceSequencer(ih.get()); //--- // Note: getImageTileWidth/Height will return zero if the image is not // intenally tiles. //--- ossimIpt tileWidthHeight( ih->getImageTileWidth(), ih->getImageTileHeight() ); if (!tileWidthHeight.x) { //--- // Make the sequencer read entire strips from the image handler // at a time. This will speed up access time for strip images //--- tileWidthHeight.x = ih->getBoundingRect().width(); } if(!tileWidthHeight.y) { tileWidthHeight.y = ih->getTileHeight(); } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Sequencer tile size: " << tileWidthHeight << endl; } is->setTileSize(tileWidthHeight); //--- // Make arrays of doubles to hold the min/max values. // Initialize mins to default maxes and maxes to default mins to be // safe. //--- ossim_uint32 i; // for numerous iterations... const ossimScalarType ST = ih->getOutputScalarType(); const double DEFAULT_MIN = ossim::defaultMin(ST); const double DEFAULT_MAX = ossim::defaultMax(ST); const ossim_uint32 BANDS = ih->getNumberOfInputBands(); vector tmin(BANDS); vector tmax(BANDS); vector tnull(BANDS); for (i = 0; i < BANDS; ++i) { tmin[i] = DEFAULT_MAX; tmax[i] = DEFAULT_MIN; if ( hasNull ) { // User passed in with --null option so set here. tnull[i] = nullValue; } else { tnull[i] = ih->getNullPixelValue(i); } } // Scan the image and compute the min and max. const double TOTAL_TILES = is->getNumberOfTiles(); double tile_count = 0.0; ossimNotify(ossimNotifyLevel_INFO) << setiosflags(ios::fixed) << setprecision(0); if( (ossim::isnan(minValue) ) || (ossim::isnan(maxValue) ) ) { ossimRefPtr id = is->getNextTile(); while(id.valid()) { if ( hasNull ) { // Pass null to image data object so it doesn't get picked up as "min". id->setNullPix( nullValue ); } id->computeMinMaxPix(tmin, tmax); id = is->getNextTile(); ++tile_count; ossimNotify(ossimNotifyLevel_INFO) << "\r" << setw(3) << (tile_count / TOTAL_TILES * 100.0) << "%" << flush; } } if(!ossim::isnan(minValue)) { std::fill(tmin.begin(), tmin.end(), minValue); } if(!ossim::isnan(maxValue)) { std::fill(tmax.begin(), tmax.end(), maxValue); } ossimNotify(ossimNotifyLevel_WARN) << "\r100%\nFinished..." << endl; ossimKeywordlist okwl(omd_file); for(i = 0; i < BANDS; ++i) { //--- // Check to see if values got assigned. If not flip to default and // issue a warning. //--- if (tmin[i] == DEFAULT_MAX) { tmin[i] = DEFAULT_MIN; ossimNotify(ossimNotifyLevel_WARN) << "cmm scan for min failed! Using default min." << std::endl; } if (tmax[i] == DEFAULT_MIN) { tmax[i] = DEFAULT_MAX; ossimNotify(ossimNotifyLevel_WARN) << "cmm scan for max failed! Using default max." << std::endl; } ossimString band = ossimString("band")+ossimString::toString(i+1)+"."; if (tmin[i] == DEFAULT_MAX) { tmin[i] = DEFAULT_MIN; } // if (tmax[i] == DEFAULT_MIN){} okwl.add(band + "min_value", tmin[i], true); okwl.add(band + "max_value", tmax[i], true); okwl.add(band + "null_value", tnull[i], true); if( traceDebug() ) { ossimNotify(ossimNotifyLevel_INFO) << setiosflags(ios::fixed) << setprecision(16) << "band" << ossimString::toString(i+1) << ".min_value: " << tmin[i] << "\nband" << ossimString::toString(i+1) << ".max_value: " << tmax[i] << "\nband" << ossimString::toString(i+1) << ".null_value: " << tnull[i] << endl; } } // End of band loop. // Add missing info (number of bands, scalar type) to the .omd file okwl.add("bytes_per_pixel", ossim::scalarSizeInBytes(ST), true); okwl.add("number_bands", BANDS, true); okwl.add("scalar_type", (ossimScalarTypeLut::instance()->getEntryString(ST)), true); // Write the file to disk: okwl.write(omd_file); ossimNotify(ossimNotifyLevel_INFO) << "wrote file: " << omd_file << endl; ih->loadMetaData(); } // Matches: if ( ih.valid() ) if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n"; } } // End: ossimImageUtil::computeMinMax( ih, entry, ... ) void ossimImageUtil::usage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); // Set app name. ap.getApplicationUsage()->setApplicationName(ap.getApplicationName()); // Add options. addArguments(ap); // Write usage. ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); outputOverviewWriterTypes(); ossimNotify(ossimNotifyLevel_INFO) << "\nExample commands:\n" << "\n// A single image standard tiff overviews, histogram:\n" << "ossim-preproc -o --ch \n" << "\n// A single image with j2k overviews(requires kakadu plugin), histogram:\n" << "ossim-preproc --ot ossim_kakadu_nitf_j2k --ch \n" << "\n// j2k, histogram, 4 threads\n" << "\n// standard tiff overviews, full histogram, 4 threads:\n" << "ossim-preproc -r -o --ch --threads 4 \n" << "\n// j2k, histogram (fast mode), 4 threads\n" << "ossim-preproc -r --ot ossim_kakadu_nitf_j2k --chf --threads 4 " << "\n" << "\n// tiff, jpeg compression, histogram, 4 threads\n" << "ossim-preproc -r --ch --compression-quality 75 --compression-type " << "jpeg --threads 4 \n" << "ossim-preproc -r --ch --compression-quality 75 --compression-type " << "jpeg --threads 4 \n" << "\n// Process all the tiffs in a directory feeding \"prep\", \"file\", \"post\" system commands via the --options option which includes indexing file into the omar database via omar-data-mgr app:\n" << "ossim-preproc --options preproc-options.kwl -r -o --ch *.tif\n" << "\n// Contents of preproc-options.kwl used in above command:\n" << "prep.command0: echo start_time: %{date}\n" << "prep.command0.strf_time_format: %Y%m%d%H%M%S\n" << "prep.command1: mkdir -p %{date}\n" << "file.command0: mv %{file_no_ext}.* %{date}/.\n" << "file.command1: omar-data-mgr -u http://localhost:8080/omar add %{date}/%{basename}\n" << "post.command0: echo end_time: %{date}\n" << "post.command0.strf_time_format: %Y%m%d%H%M%S\n" << "\nNOTES:\n" << "\n --ch equals --create-histogram" << "\n --chf equals --create-histogram-fast" << "\n\nExpanded command option variables:\n\n" << "%{basename} = filename without path\n" << "%{basename_no_ext} = filename without path and without extension\n" << "%{date} = Expanded to current zulu time. Default format=yyyymmdd\n" << " output format controlled by command0.strf_time_format key.\n" << "%{dirname} = path of filename\n" << "%{file} = filename being processed\n" << "%{file_no_ext} = filename with no extension\n" << std::endl; } // Private method: void ossimImageUtil::outputOverviewWriterTypes() const { ossimNotify(ossimNotifyLevel_NOTICE) << "\nValid overview types: " << std::endl; std::vector outputType; ossimOverviewBuilderFactoryRegistry::instance()->getTypeNameList(outputType); std::copy(outputType.begin(), outputType.end(), std::ostream_iterator(ossimNotify(ossimNotifyLevel_NOTICE), "\t\n")); } // Private method: bool ossimImageUtil::isDirectoryBasedImage(const ossimImageHandler* ih) const { bool result = false; if ( ih ) { // Get the image handler name. ossimString imageHandlerName = ih->getClassName(); if ( (imageHandlerName == "ossimAdrgTileSource") || (imageHandlerName == "ossimCibCadrgTileSource") ) { result = true; } } return result; } void ossimImageUtil::setCreateOverviewsFlag( bool flag ) { addOption( CREATE_OVERVIEWS_KW, ( flag ? TRUE_KW : FALSE_KW ) ); } bool ossimImageUtil::createOverviews() const { return keyIsTrue( CREATE_OVERVIEWS_KW ); } void ossimImageUtil::setCreateThumbnailsFlag(bool flag) { addOption(CREATE_THUMBNAILS_KW, (flag ? TRUE_KW : FALSE_KW)); } bool ossimImageUtil::createThumbnails() const { return keyIsTrue(CREATE_THUMBNAILS_KW); } void ossimImageUtil::setRebuildOverviewsFlag( bool flag ) { addOption( REBUILD_OVERVIEWS_KW, ( flag ? TRUE_KW : FALSE_KW ) ); if ( flag ) { setCreateOverviewsFlag( true ); // Turn on overview building. } } bool ossimImageUtil::rebuildOverviews() const { return keyIsTrue( REBUILD_OVERVIEWS_KW ); } void ossimImageUtil::setRebuildHistogramFlag( bool flag ) { addOption( REBUILD_HISTOGRAM_KW, ( flag ? TRUE_KW : FALSE_KW ) ); if ( flag ) { setCreateHistogramFlag( true ); // Turn on histogram building. } } bool ossimImageUtil::rebuildHistogram() const { return keyIsTrue( REBUILD_HISTOGRAM_KW ); } void ossimImageUtil::setScanForMinMax( bool flag ) { addOption( SCAN_MIN_MAX_KW, ( flag ? TRUE_KW : FALSE_KW ) ); } bool ossimImageUtil::scanForMinMax() const { return keyIsTrue( SCAN_MIN_MAX_KW ); } void ossimImageUtil::setScanForMinMaxNull( bool flag ) { addOption( SCAN_MIN_MAX_NULL_KW, ( flag ? TRUE_KW : FALSE_KW ) ); } bool ossimImageUtil::scanForMinMaxNull() const { return keyIsTrue( SCAN_MIN_MAX_NULL_KW ); } void ossimImageUtil::setCompressionQuality( const std::string& quality ) { if ( quality.size() ) { std::string key = WRITER_PROP_KW; key += ossimString::toString( getNextWriterPropIndex() ).string(); std::string value = ossimKeywordNames::COMPRESSION_QUALITY_KW; value += "="; value += quality; addOption( key, value ); } } void ossimImageUtil::setCompressionType(const std::string& type) { if ( type.size() ) { std::string key = WRITER_PROP_KW; key += ossimString::toString( getNextWriterPropIndex() ).string(); std::string value = ossimKeywordNames::COMPRESSION_TYPE_KW; value += "="; value += type; addOption( key, value ); } } void ossimImageUtil::setCopyAllFlag( bool flag ) { // Add this for hasRequiredOverview method. std::string key = COPY_ALL_FLAG_KW; std::string value = ( flag ? TRUE_KW : FALSE_KW ); addOption( key, value ); // Add as a writer prop: key = WRITER_PROP_KW; key += ossimString::toString( getNextWriterPropIndex() ).string(); value = COPY_ALL_FLAG_KW; value += "="; value += ( flag ? TRUE_KW : FALSE_KW ); addOption( key, value ); } bool ossimImageUtil::getCopyAllFlag() const { return keyIsTrue( COPY_ALL_FLAG_KW ); } void ossimImageUtil::setDumpFilteredImageListFlag( bool flag ) { std::string key = DUMP_FILTERED_IMAGES_KW; std::string value = ( flag ? TRUE_KW : FALSE_KW ); addOption( key, value ); } bool ossimImageUtil::getDumpFilterImagesFlag() const { return keyIsTrue( DUMP_FILTERED_IMAGES_KW ); } void ossimImageUtil::setInternalOverviewsFlag( bool flag ) { // Add this for hasRequiredOverview method. std::string key = INTERNAL_OVERVIEWS_FLAG_KW; std::string value = ( flag ? TRUE_KW : FALSE_KW ); addOption( key, value ); // Add as a writer prop: key = WRITER_PROP_KW; key += ossimString::toString( getNextWriterPropIndex() ).string(); value = INTERNAL_OVERVIEWS_FLAG_KW; value += "="; value += ( flag ? TRUE_KW : FALSE_KW ); addOption( key, value ); } bool ossimImageUtil::getInternalOverviewsFlag() const { return keyIsTrue( INTERNAL_OVERVIEWS_FLAG_KW ); } void ossimImageUtil::setOutputFileNamesFlag( bool flag ) { std::string key = OUTPUT_FILENAMES_KW; std::string value = ( flag ? TRUE_KW : FALSE_KW ); addOption( key, value ); } bool ossimImageUtil::getOutputFileNamesFlag() const { return keyIsTrue( OUTPUT_FILENAMES_KW ); } void ossimImageUtil::setOverrideFilteredImagesFlag( bool flag ) { std::string key = OVERRIDE_FILTERED_IMAGES_KW; std::string value = ( flag ? TRUE_KW : FALSE_KW ); addOption( key, value ); } bool ossimImageUtil::getOverrideFilteredImagesFlag() const { return keyIsTrue( OVERRIDE_FILTERED_IMAGES_KW ); } void ossimImageUtil::setOutputDirectory( const std::string& directory ) { std::string key = OUTPUT_DIRECTORY_KW; addOption( key, directory ); } void ossimImageUtil::setOverviewType( const std::string& type ) { std::string key = OVERVIEW_TYPE_KW; addOption( key, type ); setCreateOverviewsFlag( true ); // Assume caller wants overviews. } void ossimImageUtil::getOverviewType(std::string& type) const { std::string lookup = m_kwl->findKey(OVERVIEW_TYPE_KW); if ( lookup.size() ) { type = lookup; } else { type = "ossim_tiff_box"; // default } } void ossimImageUtil::setProps(ossimPropertyInterface* pi) const { if ( pi ) { ossimString baseKey; if ( dynamic_cast(pi) ) { baseKey = READER_PROP_KW; } else { baseKey = WRITER_PROP_KW; } ossim_uint32 propCount = m_kwl->numberOf( baseKey.c_str() ); if ( propCount ) { ossim_uint32 foundProps = 0; ossim_uint32 index = 0; // (propCount+100) is to allow for holes like reader_prop0, reader_prop2... while ( (foundProps < propCount) && (index < (propCount+100) ) ) { ossimString key = baseKey; key += ossimString::toString(index); std::string lookup = m_kwl->findKey( key.string() ); if ( lookup.size() ) { ossimString value = lookup; std::vector v = value.split("="); if (v.size() == 2) { ossimString propertyName = v[0]; ossimString propertyValue = v[1]; ossimRefPtr p = new ossimStringProperty(propertyName, propertyValue); pi->setProperty( p ); } ++foundProps; } ++index; } } } } void ossimImageUtil::setOverviewStopDimension( ossim_uint32 dimension ) { addOption( OVERVIEW_STOP_DIM_KW, dimension ); } void ossimImageUtil::setOverviewStopDimension( const std::string& dimension ) { addOption( OVERVIEW_STOP_DIM_KW, dimension ); } void ossimImageUtil::setTileSize( ossim_uint32 tileSize ) { if ((tileSize % 16) == 0) { addOption( TILE_SIZE_KW, tileSize ); } else { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimImageUtil::setTileSize NOTICE:" << "\nTile width must be a multiple of 16!" << std::endl; } } bool ossimImageUtil::getTileSize( ossimIpt& tileSize ) const { bool result = false; std::string lookup = m_kwl->findKey( TILE_SIZE_KW ); if ( lookup.size() ) { ossim_int32 i = ossimString(lookup).toInt32(); if ( (i % 16) == 0 ) { tileSize.x = i; tileSize.y = i; result = true; } } return result; } ossim_uint32 ossimImageUtil::getOverviewStopDimension() const { ossim_uint32 result = 0; std::string lookup = m_kwl->findKey( OVERVIEW_STOP_DIM_KW ); if ( lookup.size() ) { result = ossimString(lookup).toUInt32(); } return result; } void ossimImageUtil::setCreateHistogramFlag( bool flag ) { addOption( CREATE_HISTOGRAM_KW, ( flag ? TRUE_KW : FALSE_KW ) ); } bool ossimImageUtil::createHistogram() const { return keyIsTrue( CREATE_HISTOGRAM_KW ); } void ossimImageUtil::setCreateHistogramFastFlag( bool flag ) { addOption( CREATE_HISTOGRAM_FAST_KW, ( flag ? TRUE_KW : FALSE_KW ) ); } bool ossimImageUtil::createHistogramFast() const { return keyIsTrue( CREATE_HISTOGRAM_FAST_KW ); } void ossimImageUtil::setCreateHistogramR0Flag( bool flag ) { addOption( CREATE_HISTOGRAM_R0_KW, ( flag ? TRUE_KW : FALSE_KW ) ); } bool ossimImageUtil::createHistogramR0() const { return keyIsTrue( CREATE_HISTOGRAM_R0_KW ); } bool ossimImageUtil::hasHistogramOption() const { return ( createHistogram() || createHistogramFast() || createHistogramR0() ); } bool ossimImageUtil::hasCmmOption() const { return ( keyIsTrue( CMM_MAX_KW ) || keyIsTrue( CMM_MIN_KW )|| keyIsTrue( CMM_NULL_KW ) ); } ossimHistogramMode ossimImageUtil::getHistogramMode() const { ossimHistogramMode result = OSSIM_HISTO_MODE_UNKNOWN; if ( createHistogram() || createHistogramR0() ) { result = OSSIM_HISTO_MODE_NORMAL; } else if ( createHistogramFast() ) { result = OSSIM_HISTO_MODE_FAST; } return result; } void ossimImageUtil::setNumberOfThreads( ossim_uint32 threads ) { addOption( THREADS_KW, threads ); } void ossimImageUtil::setNumberOfThreads( const std::string& threads ) { addOption( THREADS_KW, threads ); } ossim_uint32 ossimImageUtil::getNumberOfThreads() const { ossim_uint32 result; std::string lookup = m_kwl->findKey( THREADS_KW ); if ( lookup.size() ) { result = ossimString(lookup).toUInt32(); } else { result = ossim::getNumberOfThreads(); } return result; } ossim_uint32 ossimImageUtil::getNextWriterPropIndex() const { ossim_uint32 result = m_kwl->numberOf( WRITER_PROP_KW.c_str() ); if ( result ) { ossim_uint32 foundProps = 0; ossim_uint32 index = 0; //--- // Loop until we find the last index used for WRITER_PROP_KW. // (result+100) is to allow for holes like writer_prop0, writer_prop2... //--- while ( (foundProps < result) && (index < (result+100) ) ) { ossimString key = WRITER_PROP_KW; key += ossimString::toString(index); std::string lookup = m_kwl->findKey( key.string() ); if ( lookup.size() ) { ++foundProps; } ++index; } result = index; } return result; } ossim_uint32 ossimImageUtil::getNextReaderPropIndex() const { ossim_uint32 result = m_kwl->numberOf( READER_PROP_KW.c_str() ); if ( result ) { ossim_uint32 foundProps = 0; ossim_uint32 index = 0; //--- // Loop until we find the last index used for WRITER_PROP_KW. // (result+100) is to allow for holes like reader_prop0, reader_prop2... //--- while ( (foundProps < result) && (index < (result+100) ) ) { ossimString key = READER_PROP_KW; key += ossimString::toString(index); std::string lookup = m_kwl->findKey( key.string() ); if ( lookup.size() ) { ++foundProps; } ++index; } result = index; } return result; } ossim_uint32 ossimImageUtil::getThumbnailSize() const { ossim_uint32 result; std::string lookup = m_kwl->findKey(THUMBNAIL_SIZE_KW); if (lookup.size()) { result = ossimString(lookup).toUInt32(); } else { result = 256; } return result; } void ossimImageUtil::setThumbnailStretchType(const std::string &value) { addOption(THUMBNAIL_STRETCH_TYPE_KW, value); } int ossimImageUtil::getThumbnailStretchType()const { int result = ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX; ossimString typeString = m_kwl->findKey(THUMBNAIL_STRETCH_TYPE_KW); if (typeString.empty()) { typeString = "auto-minmax"; } typeString = typeString.downcase(); if ((typeString == "auto-minmax")) { result = ossimHistogramRemapper::StretchMode::LINEAR_AUTO_MIN_MAX; } else if ((typeString == "auto-percentile")) { result = ossimHistogramRemapper::StretchMode::LINEAR_AUTO_PERCENTILE; } else if ((typeString == "std-stretch-1") || (typeString == "std-stretch 1")) { result = ossimHistogramRemapper::StretchMode::LINEAR_1STD_FROM_MEAN; } else if ((typeString == "std-stretch-2") || (typeString == "std-stretch 2")) { result = ossimHistogramRemapper::StretchMode::LINEAR_2STD_FROM_MEAN; } else if ((typeString == "std-stretch-3") || (typeString == "std-stretch 3")) { result = ossimHistogramRemapper::StretchMode::LINEAR_3STD_FROM_MEAN; } else if (typeString == "auto-minmax") { result = ossimHistogramRemapper::StretchMode::STRETCH_UNKNOWN; } return result; } void ossimImageUtil::setThumbnailType(const std::string& value) { addOption(THUMBNAIL_TYPE_KW, value); } std::string ossimImageUtil::getThumbnailType() const { ossimString typeString = m_kwl->findKey(THUMBNAIL_TYPE_KW); std::string result = "jpeg"; typeString = typeString.downcase(); if(typeString != "png" && typeString != "jpeg") { typeString = "jpeg"; } result = typeString.string(); return result; } std::string ossimImageUtil::getThumbnailFilename(ossimImageHandler* ih) const { ossimFilename thumbnailFilename = ih->getFilenameWithThisExtension(""); std::string thumbnailType = getThumbnailType(); if (thumbnailType == "png") { thumbnailFilename = ossimFilename(thumbnailFilename + "thumb.png"); } else { thumbnailFilename = ossimFilename(thumbnailFilename + "thumb.jpg"); } return thumbnailFilename.string(); } void ossimImageUtil::addOption(const std::string &key, ossim_uint32 value) { addOption(key, ossimString::toString(value).string()); } void ossimImageUtil::addOption( const std::string& key, const std::string& value ) { m_mutex.lock(); if ( m_kwl.valid() ) { if ( key.size() && value.size() ) { m_kwl->addPair( key, value ); } } m_mutex.unlock(); } void ossimImageUtil::setErrorStatus( ossim_int32 status ) { m_mutex.lock(); m_errorStatus = status; m_mutex.unlock(); } bool ossimImageUtil::isFiltered(const ossimFilename& file) const { bool result = false; if ( file.size() ) { // Strip full path to base name. std::string baseName = file.file().string(); if ( baseName.size() ) { std::vector::const_iterator i = m_filteredImages.begin(); while ( i != m_filteredImages.end() ) { if ( baseName == (*i) ) { result = true; break; } ++i; } } } #if 0 /* Please leave for debug. (drb) */ if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimFileWalker::isFiltered file " << (result?"filtered: ":"not filtered: ") << file << "\n"; } #endif return result; } bool ossimImageUtil::keyIsTrue( const std::string& key ) const { bool result = false; if ( m_kwl.valid() ) { std::string value = m_kwl->findKey( key ); if ( value.size() ) { result = ossimString(value).toBool(); } } return result; } const std::vector& ossimImageUtil::getFilteredImages() const { return m_filteredImages; } std::vector& ossimImageUtil::getFilteredImages() { return m_filteredImages; } void ossimImageUtil::initializeDefaultFilterList() { m_mutex.lock(); // Common images to filter out, put most common first. m_filteredImages.push_back(std::string("icon.jpg")); m_filteredImages.push_back(std::string("logo.jpg")); m_filteredImages.push_back(std::string("preview.jpg")); m_mutex.unlock(); } void ossimImageUtil::dumpFilteredImageList() const { ossimNotify(ossimNotifyLevel_NOTICE) << "Filtered image list:\n"; std::vector::const_iterator i = m_filteredImages.begin(); while ( i != m_filteredImages.end() ) { ossimNotify(ossimNotifyLevel_NOTICE) << (*i) << "\n"; ++i; } ossimNotify(ossimNotifyLevel_NOTICE) << std::endl; } void ossimImageUtil::executePrepCommands() const { std::string prefix = "prep."; ossimFilename file = ""; executeCommands( prefix, file ); } void ossimImageUtil::executeFileCommands( const ossimFilename& file ) const { std::string prefix = "file."; executeCommands( prefix, file ); } void ossimImageUtil::executePostCommands() const { std::string prefix = "post."; ossimFilename file = ""; executeCommands( prefix, file ); } void ossimImageUtil::executeCommands( const std::string& prefix, const ossimFilename& file ) const { const std::string BASE_KEY = "command"; // Get the number of test: const std::string REG_EXP_STR = prefix + BASE_KEY + std::string("[0-9]+"); const ossim_uint32 NUM_COMMANDS = m_kwl->getNumberOfSubstringKeys(REG_EXP_STR); if ( NUM_COMMANDS ) { const ossim_uint32 MAX_INDEX = NUM_COMMANDS + 1000; // for skipage... ossim_uint32 index = 0; ossim_uint32 processedIndexes = 0; std::string commandKey; ossimString command; while ( processedIndexes < MAX_INDEX ) { commandKey = prefix + BASE_KEY + ossimString::toString( index++ ).string(); command.string() = m_kwl->findKey( commandKey ); if ( command.size() ) { substituteCommandString( file, prefix, commandKey, command ); ossimNotify( ossimNotifyLevel_NOTICE ) << "executing_command: " << command << std::endl; // Launch the command: int status = system( command.c_str() ); ossimNotify( ossimNotifyLevel_NOTICE ) << "return_status: " << status << std::endl; ++processedIndexes; if ( processedIndexes == NUM_COMMANDS ) { break; } } } } } void ossimImageUtil::substituteCommandString( const ossimFilename& file, const std::string& prefix, const std::string& commandKey, ossimString& command ) const { // Expand any environment vars, e.g. $(env_var_name): command.expandEnvironmentVariable(); gsubDate( commandKey, command ); if ( prefix == "file." ) { substituteFileStrings( file, command ); } } void ossimImageUtil::substituteFileStrings( const ossimFilename& file, ossimString& command ) const { const std::string BASENAME_VARIABLE = "%{basename}"; command.gsub( BASENAME_VARIABLE, file.file().string() ); const std::string BASENAME_NO_EXT_VARIABLE = "%{basename_no_ext}"; command.gsub( BASENAME_NO_EXT_VARIABLE, file.file().string() ); const std::string DIRNAME_VARIABLE = "%{dirname}"; command.gsub( DIRNAME_VARIABLE, file.path().string() ); const std::string FILE_VARIABLE = "%{file}"; command.gsub( FILE_VARIABLE, file.string(), true ); const std::string FILE_NO_EXT_VARIABLE = "%{file_no_ext}"; command.gsub( FILE_NO_EXT_VARIABLE, file.noExtension().string(), true ); } void ossimImageUtil::gsubDate( const std::string& commandKey, ossimString& command ) const { // Date: const std::string DATE_VARIABLE = "%{date}"; if ( command.find( DATE_VARIABLE ) ) { std::string key = ".strf_time_format"; std::string strfTimeFormat = m_kwl->findKey( commandKey, key ); if ( strfTimeFormat.empty() ) { // yyyymmdd strfTimeFormat = "%Y%m%d"; } //--- // Get the date as a string, e.g 20150411. // true for gmt time. //--- std::string date; ossim::getFormattedTime( strfTimeFormat, true, date ); if ( date.size() ) { // Sustitute: command.gsub( DATE_VARIABLE, date, true ); } } } ossim-Miami-2.9.1/src/util/ossimInfo.cpp000066400000000000000000002622471352751253100201460ustar00rootroot00000000000000//--- // File: ossimInfo.cpp // // License: MIT // // Author: David Burken // // Description: ossimInfo class definition // // Utility class for getting information from the ossim library. // //--- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static const char BUILD_DATE_KW[] = "build_date"; static const char CAN_OPEN_KW[] = "can_open"; static const char CENTER_GROUND_KW[] = "center_ground"; static const char CENTER_IMAGE_KW[] = "center_image"; static const char CONFIGURATION_KW[] = "configuration"; static const char DATUMS_KW[] = "datums"; static const char DEG2RAD_KW[] = "deg2rad"; static const char DUMP_KW[] = "dump"; static const char DUMP_NO_OVERVIEWS_KW[] = "dump_no_overviews"; static const char EXTENSIONS_KW[] = "extensions"; static const char FACTORIES_KW[] = "factories"; static const char FACTORY_KEYWORD_LIST_KW[] = "factory_keyword_list"; static const char FONTS_KW[] = "fonts"; static const char FORMAT_KW[] = "format"; static const char FT2MTRS_KW[] = "ft2mtrs"; static const char FT2MTRS_US_SURVEY_KW[] = "ft2mtrs_us_survey"; static const char GEOM_INFO_KW[] = "geometry_info"; static const char HEIGHT_KW[] = "height"; static const char IMAGE_BOUNDS_KW[] = "image_bounds"; static const char IMAGE_CENTER_KW[] = "image_center"; static const char IMAGE_FILE_KW[] = "image_file"; static const char IMAGE_INFO_KW[] = "image_info"; static const char IMAGE_RECT_KW[] = "image_rect"; static const char IMG2GRD_KW[] = "img2grd"; static const char GRD2IMG_KW[] = "grd2img"; static const char METADATA_KW[] = "metadata"; static const char MTRS2FT_KW[] = "mtrs2ft"; static const char MTRS2FT_US_SURVEY_KW[] = "mtrs2ft_us_survey"; static const char MTRSPERDEG_KW[] = "mtrs_per_deg"; static const char NORTH_UP_KW[] = "north_up_angle"; static const char OUTPUT_FILE_KW[] = "output_file"; static const char OVERVIEW_TYPES_KW[] = "overview_types"; static const char OVERWRITE_KW[] = "overwrite"; static const char PALETTE_KW[] = "palette"; static const char PLUGINS_KW[] = "plugins"; static const char PLUGIN_TEST_KW[] = "plugin_test"; static const char PRETTY_PRINT_KW[] = "pretty_print"; static const char PROJECTIONS_KW[] = "projections"; static const char RAD2DEG_KW[] = "rad2deg"; static const char READER_PROPS_KW[] = "reader_props"; static const char RESAMPLER_FILTERS_KW[] = "resampler_filters"; static const char REVISION_NUMBER_KW[] = "revision_number"; static const char UP_IS_UP_KW[] = "up_is_up"; static const char UP_IS_UP_GPT_KW[] = "up_is_up_gpt"; static const char UP_IS_UP_IPT_KW[] = "up_is_up_ipt"; static const char VERSION_KW[] = "version"; static const char WRITERS_KW[] = "writers_kw"; static const char WRITER_PROPS_KW[] = "writer_props"; static const char ZOOM_LEVEL_GSDS_KW[] = "zoom_level_gsds"; static const char ECEF2LLH_KW[] = "ecef2llh"; static const char DUMP_STATE_KW[] = "dump_state"; static const char STATE_KW[] = "state"; const char* ossimInfo::DESCRIPTION = "Dumps metadata information about input image and OSSIM in general."; // Static trace for debugging. Use -T ossimInfo to turn on. static ossimTrace traceDebug = ossimTrace("ossimInfo:debug"); ossimInfo::ossimInfo() : m_img(0) { } ossimInfo::~ossimInfo() { } void ossimInfo::setUsage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); // Set the general usage: ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " [options] "; au->setCommandLineUsage(usageString); // Set the command line options: au->addCommandLineOption("--bounds", "Will print out the edge to edge image bounds."); au->addCommandLineOption("--build-date", "Build date of code."); au->addCommandLineOption("-c", "Will print ground and image center."); au->addCommandLineOption("--can-open", "return can_open: true or can_open: false"); au->addCommandLineOption("--cg", "Will print out ground center."); au->addCommandLineOption("--ci", "Will print out image center."); au->addCommandLineOption("--config", "Displays configuration info."); au->addCommandLineOption("-D", "A human-readable (i.e., not necessarily key:value pairs) dump of the image."); au->addCommandLineOption("-d", "A generic dump if one is available."); au->addCommandLineOption("--datums", "Prints datum list."); au->addCommandLineOption("--deg2rad", " Gives radians from degrees."); au->addCommandLineOption("--dno", "A generic dump if one is available. This option ignores overviews."); au->addCommandLineOption("--dump-state", "If the image supports a state object then the state object will be dumped."); au->addCommandLineOption("--ecef2llh", " in ECEF coordinates and returns latitude longitude height position."); au->addCommandLineOption("--extensions", "Prints list of supported image extensions."); au->addCommandLineOption("-f", " Will output the information specified format [KWL | XML]. Default is KWL."); au->addCommandLineOption("--factories", " Prints factory list. If keyword_list_flag is true, the result of a saveState will be output for each object."); au->addCommandLineOption("--fonts", "Prints available fonts."); au->addCommandLineOption("--ft2mtrs", " Gives meters from feet (0.3048 meters per foot)."); au->addCommandLineOption("--ft2mtrs-us-survey", " Gives meters from feet (0.3048006096 meters per foot)."); au->addCommandLineOption("-h", "Display this information"); au->addCommandLineOption("--height", " Returns the MSL and ellipoid height given a latitude longitude position."); au->addCommandLineOption("-i", "Will print out the general image information."); au->addCommandLineOption("--img2grd", " Gives ground point from zero based image point. Returns \"nan\" if point is outside of image area."); au->addCommandLineOption("--grd2img", " Gives full res image point from lat lon height."); au->addCommandLineOption("-m", "Will print out meta data image information."); au->addCommandLineOption("--mtrsPerDeg", " Gives meters per degree and meters per minute for a given latitude."); au->addCommandLineOption("--mtrs2ft", " Gives feet from meters (0.3048 meters per foot)."); au->addCommandLineOption("--mtrs2ft-us-survey", " Gives feet from meters (0.3048006096 meters per foot)."); au->addCommandLineOption("-n or --north-up", "Rotation angle to North for an image."); au->addCommandLineOption("-o", " Will output the information to the file specified. Default is to standard out."); au->addCommandLineOption("--overview-types", "Prints overview builder types."); au->addCommandLineOption("-p", "Will print out the image projection information."); au->addCommandLineOption("--palette", "Will print out the color palette if one exists."); au->addCommandLineOption("--plugins", "Prints plugin list."); au->addCommandLineOption("--plugin-test", "Test plugin passed to option."); au->addCommandLineOption("--projections", "Prints projections."); au->addCommandLineOption("-r", "Will print image rectangle."); au->addCommandLineOption("--rad2deg", " Gives degrees from radians."); au->addCommandLineOption("--reader-props", "Prints readers and properties."); au->addCommandLineOption("--resampler-filters", "Prints resampler filter list."); au->addCommandLineOption("--revision", "Revision of code."); au->addCommandLineOption("-s", "Force the ground rect to be the specified datum"); au->addCommandLineOption("--up-is-up or -u", "Rotation angle to \"up is up\" for an image.\nWill return 0 if image's projection is not affected by elevation."); au->addCommandLineOption("--up-is-up-gpt", "Computes up angle given gpt: "); au->addCommandLineOption("--up-is-up-ipt", "Computes up angle given full res image point: "); au->addCommandLineOption("-v", "Overwrite existing geometry."); au->addCommandLineOption("-V or --vesion", "Version of code, e.g. 1.8.20"); au->addCommandLineOption("--writer-props", "Prints writers and properties."); au->addCommandLineOption("--writers", "Prints list of available writers."); au->addCommandLineOption("--zoom-level-gsds", "Prints zoom level gsds for projections EPSG:4326 and EPSG:3857."); ostringstream description; description << DESCRIPTION << "\n\n Examples:\n\n" << " ossim-info --version\n" << " ossim-info -i ./myfile.tif\n" << " prints out only general image information\n\n" << " ossim-info -p ./myfile.tif\n" << " prints out only image projection information\n\n" << " ossim-info -p -s wge ./myfile.tif\n" << " prints out only image projection information and shifts to wgs84\n\n" << " ossim-info -p -i ./myfile.tif\n" << " prints out both image and projection information\n\n" << " ossim-info -p -i ./myfile.tif -o ./myfile.geom\n" << " writes geometry file with both image and projection information\n\n" << " ossim-info -p -i ./myfile.tif -v -o ./myfile.geom\n" << " writes geometry file with both image and projection information\n" << " while overwriting existing .geom file.\n\n" << " ossim-info -f XML ./myfile.tif\n" << " prints out image and projection information as an XML document\n\n" << " ossim-info -d myfile.ntf\n" << " Dumps all data available, in this case, all nitf tags, from file.\n\n" << " ossim-info -d a.toc\n" << " Dumps all data available, in this case, all nitf and rpf tags, from file.\n\n" << " ossim-info --dno a.toc\n" << " \"dno\" for \"dump no overviews\" Dumps all data available,\n" << " in this case, all nitf and rpf tags, from file ignoring overviews.\n\n" << " ossim-info -d -i -p myfile.ntf\n" << " Typical usage case, i.e. do a dump of tags and print out image and\n" << " projection information.\n\n" << std::endl; au->setDescription(description.str()); } // void ossimInfo::addArguments(ossimArgumentParser& ap) bool ossimInfo::initialize(ossimArgumentParser& ap) { static const char M[] = "ossimInfo::initialize(ossimArgumentParser&)"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n"; } if (!ossimTool::initialize(ap)) return false; if (m_helpRequested) return true; bool result = true; //--- // Start with clean options keyword list. //--- m_kwl.clear(); bool requiresInputImage = false; while ( 1 ) // While forever loop... { // Used throughout below: std::string ts1; ossimArgumentParser::ossimParameter sp1(ts1); std::string ts2; ossimArgumentParser::ossimParameter sp2(ts2); std::string ts3; ossimArgumentParser::ossimParameter sp3(ts3); const char TRUE_KW[] = "true"; if( ap.read("--bounds") ) { m_kwl.add( IMAGE_BOUNDS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--build-date") ) { m_kwl.add( BUILD_DATE_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-c") ) { m_kwl.add( IMAGE_CENTER_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--can-open") ) { m_kwl.add( CAN_OPEN_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("--cg") ) { m_kwl.add( CENTER_GROUND_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--ci") ) { m_kwl.add( CENTER_IMAGE_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--config") || ap.read("--configuration") ) { m_kwl.add( CONFIGURATION_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--datums") ) { m_kwl.add( DATUMS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--deg2rad", sp1) ) { m_kwl.add( DEG2RAD_KW, ts1.c_str() ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-D") ) { m_kwl.add( PRETTY_PRINT_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("-d") ) { m_kwl.add( DUMP_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("--dump-state") ) { m_kwl.add( DUMP_STATE_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("--dno") ) { m_kwl.add( DUMP_KW, TRUE_KW ); m_kwl.add( DUMP_NO_OVERVIEWS_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("--extensions") ) { m_kwl.add( EXTENSIONS_KW, TRUE_KW ); if ( ap.argc() < 2 ) break; } if( ap.read("-f", sp1) ) { m_kwl.add( FORMAT_KW, ts1.c_str()); if ( ap.argc() < 2 ) { break; } } if( ap.read("--factories", sp1) ) { m_kwl.add( FACTORIES_KW, TRUE_KW); m_kwl.add( FACTORY_KEYWORD_LIST_KW, ts1.c_str()); if ( ap.argc() < 2 ) { break; } } if( ap.read("--fonts") ) { m_kwl.add( FONTS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--ft2mtrs", sp1) ) { m_kwl.add( FT2MTRS_KW, ts1.c_str()); if ( ap.argc() < 2 ) { break; } } if( ap.read("--ft2mtrs-us-survey", sp1) ) { m_kwl.add( FT2MTRS_KW, ts1.c_str()); m_kwl.add( FT2MTRS_US_SURVEY_KW, TRUE_KW); if ( ap.argc() < 2 ) { break; } } if( ap.read("--height", sp1, sp2) ) { ossimString lat = ts1; ossimString lon = ts2; ossimGpt gpt; gpt.lat = lat.toFloat64(); gpt.lon = lon.toFloat64(); m_kwl.add( HEIGHT_KW, gpt.toString().c_str() ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--ecef2llh", sp1, sp2, sp3)) { ossimString x = ts1; ossimString y = ts2; ossimString z = ts3; ossimEcefPoint ecefPoint(x.toFloat64(), y.toFloat64(), z.toFloat64()); m_kwl.add( ECEF2LLH_KW, ecefPoint.toString().c_str() ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-i") ) { m_kwl.add( IMAGE_INFO_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("--img2grd", sp1, sp2) ) { requiresInputImage = true; ossimString x = ts1; ossimString y = ts2; ossimDpt dpt; dpt.x = x.toFloat64(); dpt.y = y.toFloat64(); m_kwl.add( IMG2GRD_KW, dpt.toString().c_str() ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--grd2img", sp1, sp2, sp3) ) { requiresInputImage = true; ossimString lat = ts1; ossimString lon = ts2; ossimString hgt = ts3; ossimGpt gpt; gpt.makeNan(); gpt.latd(lat.toFloat64()); gpt.lond(lon.toFloat64()); if(hgt != "nan") { gpt.height(hgt.toFloat64()); } m_kwl.add( GRD2IMG_KW, gpt.toString().c_str() ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-m") ) { m_kwl.add( METADATA_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("--mtrs2ft", sp1) ) { m_kwl.add( MTRS2FT_KW, ts1.c_str()); if ( ap.argc() < 2 ) { break; } } if( ap.read("--mtrs2ft-us-survey", sp1) ) { m_kwl.add( MTRS2FT_KW, ts1.c_str()); m_kwl.add( MTRS2FT_US_SURVEY_KW, TRUE_KW); if ( ap.argc() < 2 ) { break; } } if( ap.read("--mtrsPerDeg", sp1) ) { m_kwl.add( MTRSPERDEG_KW, ts1.c_str()); if ( ap.argc() < 2 ) { break; } } if( ap.read("-n") || ap.read("--north-up") ) { m_kwl.add( NORTH_UP_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-o", sp1) ) { m_kwl.add( OUTPUT_FILE_KW, ts1.c_str()); if ( ap.argc() < 2 ) { break; } } if( ap.read("--overview-types") ) { m_kwl.add( OVERVIEW_TYPES_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-p") ) { m_kwl.add( GEOM_INFO_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("--palette") ) { m_kwl.add( PALETTE_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("--plugins") ) { m_kwl.add( PLUGINS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--plugin-test", sp1) ) { m_kwl.add( PLUGIN_TEST_KW, ts1.c_str()); if ( ap.argc() < 2 ) { break; } } if( ap.read("--projections") ) { m_kwl.add( PROJECTIONS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-r") ) { m_kwl.add( IMAGE_RECT_KW, TRUE_KW ); requiresInputImage = true; if ( ap.argc() < 2 ) { break; } } if( ap.read("--rad2deg", sp1) ) { m_kwl.add( RAD2DEG_KW, ts1.c_str()); if ( ap.argc() < 2 ) { break; } } if( ap.read("--reader-props") ) { m_kwl.add( READER_PROPS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--resampler-filters") ) { m_kwl.add( RESAMPLER_FILTERS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--revision") || ap.read("--revision-number") ) // backwards compat { m_kwl.add( REVISION_NUMBER_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-u") || ap.read("--up-is-up") ) { requiresInputImage = true; m_kwl.add( UP_IS_UP_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--up-is-up-ipt", sp1, sp2)) { requiresInputImage = true; m_kwl.add( UP_IS_UP_KW, TRUE_KW); m_kwl.add( UP_IS_UP_IPT_KW, (ts1 +" "+ts2).c_str() ); if ( ap.argc() < 2 ) { break; } } if(ap.read("--up-is-up-gpt",sp1, sp2)) { requiresInputImage = true; m_kwl.add( UP_IS_UP_KW, TRUE_KW); m_kwl.add( UP_IS_UP_GPT_KW, (ts1 +" "+ ts2).c_str() ); if ( ap.argc() < 2 ) { break; } } if( ap.read("-v") ) { m_kwl.add( OVERWRITE_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--version") || ap.read("-V") ) { m_kwl.add( VERSION_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--writer-props") ) { m_kwl.add( WRITER_PROPS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--writers") ) { m_kwl.add( WRITERS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } if( ap.read("--zoom-level-gsds") ) { m_kwl.add( ZOOM_LEVEL_GSDS_KW, TRUE_KW ); if ( ap.argc() < 2 ) { break; } } // End of arg parsing. ap.reportRemainingOptionsAsUnrecognized(); if ( ap.errors() ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); std::string errMsg = "Unknown option..."; throw ossimException(errMsg); } break; // Break from while forever. } // End while (forever) loop. if ( ap.argc() == 2 ) { m_kwl.add( IMAGE_FILE_KW, ap[1] ); } if ( (( ap.argc() == 1 ) && requiresInputImage) || (m_kwl.getSize() == 0) ) { if ( requiresInputImage ) { ossimNotify(ossimNotifyLevel_NOTICE) << "\nError: Option requires input image!\n\n"; } setUsage(ap); ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); result = false; } if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "m_kwl:\n" << m_kwl << "\n" << M << " exit result = " << (result?"true":"false") << "\n"; } return result; } bool ossimInfo::execute() { static const char M[] = "ossimInfo::execute()"; const ossim_uint32 KEY_COUNT = m_kwl.getSize(); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered..." << "\nMap size: " << KEY_COUNT << "\n"; } if ( KEY_COUNT ) { ossim_uint32 consumedKeys = 0; const char* lookup; lookup = m_kwl.find(IMAGE_FILE_KW); if ( lookup ) { ++consumedKeys; ossimFilename image = lookup; consumedKeys += executeImageOptions(image); } if ( consumedKeys < KEY_COUNT ) { ossimString value; if ( keyIsTrue( std::string(BUILD_DATE_KW)) ) { getBuildDate( value.string() ); ossimNotify(ossimNotifyLevel_INFO) << BUILD_DATE_KW << ": " << value << "\n"; } lookup = m_kwl.find(CONFIGURATION_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printConfiguration(); } } lookup = m_kwl.find(DATUMS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printDatums(); } } lookup = m_kwl.find(DEG2RAD_KW); if ( lookup ) { ++consumedKeys; value = lookup; deg2rad( value.toFloat64() ); } lookup = m_kwl.find(ECEF2LLH_KW); if(lookup) { ++consumedKeys; ossimEcefPoint ecefPoint; ecefPoint.toPoint(lookup); ecef2llh(ecefPoint, ossimNotify(ossimNotifyLevel_INFO)); } lookup = m_kwl.find(EXTENSIONS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printExtensions(); } } lookup = m_kwl.find(FACTORIES_KW); if ( lookup ) { ++consumedKeys; ossimString factories = lookup; bool keywordListFlag = false; lookup = m_kwl.find(FACTORY_KEYWORD_LIST_KW); if ( lookup ) { ++consumedKeys; keywordListFlag = ossimString(lookup).toBool(); } printFactories(keywordListFlag); } lookup = m_kwl.find(FONTS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printFonts(); } } lookup = m_kwl.find(FT2MTRS_KW); if ( lookup ) { ++consumedKeys; value = lookup; bool us_survey = false; lookup = m_kwl.find(FT2MTRS_US_SURVEY_KW); if ( lookup ) { ++consumedKeys; us_survey = ossimString(lookup).toBool(); } ft2mtrs( value.toFloat64(), us_survey); } lookup = m_kwl.find(HEIGHT_KW); if ( lookup ) { ++consumedKeys; value = lookup; ossimGpt gpt; gpt.toPoint(value); outputHeight(gpt); } lookup = m_kwl.find(MTRS2FT_KW); if ( lookup ) { ++consumedKeys; value = lookup; bool us_survey = false; lookup = m_kwl.find(MTRS2FT_US_SURVEY_KW); if ( lookup ) { ++consumedKeys; us_survey = ossimString(lookup).toBool(); } mtrs2ft( value.toFloat64(), us_survey); } lookup = m_kwl.find(MTRSPERDEG_KW); if ( lookup ) { ++consumedKeys; value = lookup; mtrsPerDeg( value.toFloat64() ); } lookup = m_kwl.find(OVERVIEW_TYPES_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printOverviewTypes(); } } lookup = m_kwl.find(PLUGINS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printPlugins(); } } lookup = m_kwl.find(PLUGIN_TEST_KW); if ( lookup ) { ++consumedKeys; value = lookup; testPlugin(value); } lookup = m_kwl.find(PROJECTIONS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printProjections(); } } lookup = m_kwl.find(RAD2DEG_KW); if ( lookup ) { ++consumedKeys; value = lookup; rad2deg( value.toFloat64() ); } lookup = m_kwl.find(READER_PROPS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printReaderProps(); } } lookup = m_kwl.find(RESAMPLER_FILTERS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printResamplerFilters(); } } if ( keyIsTrue( std::string(REVISION_NUMBER_KW) ) ) { getRevisionNumber( value.string() ); ossimNotify(ossimNotifyLevel_INFO) << REVISION_NUMBER_KW << ": " << value << "\n"; } if ( keyIsTrue( std::string(VERSION_KW) ) ) { getVersion( value.string() ); ossimNotify(ossimNotifyLevel_INFO) << VERSION_KW << ": " << value << "\n"; } lookup = m_kwl.find(WRITERS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printWriters(); } } lookup = m_kwl.find(WRITER_PROPS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printWriterProps(); } } lookup = m_kwl.find(ZOOM_LEVEL_GSDS_KW); if ( lookup ) { ++consumedKeys; value = lookup; if ( value.toBool() ) { printZoomLevelGsds(); } } } // if ( consumedKeys < KEY_COUNT ) if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "KEY_COUNT: " << KEY_COUNT << "\nconsumedKeys: " << consumedKeys << "\n"; } } // if ( KEY_COUNT ) if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " exited...\n"; } return true; } ossim_uint32 ossimInfo::executeImageOptions(const ossimFilename& file) { static const char M[] = "ossimInfo::executeImageOptions()"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\nfile: " << file << "\n"; } // Output keyword list. ossimKeywordlist okwl; ossim_uint32 consumedKeys = 0; const char* lookup = 0; ossimString value = ""; bool dnoFlag = false; bool overwriteFlag = false; bool xmlOutFlag = false; lookup = m_kwl.find( OVERWRITE_KW ); if ( lookup ) { ++consumedKeys; value = lookup; overwriteFlag = value.toBool(); } // Check for xml format option. lookup = m_kwl.find( FORMAT_KW ); if ( lookup ) { ++consumedKeys; ossimString format = lookup; if ( format.upcase() == "XML" ) { xmlOutFlag = true; } } lookup = m_kwl.find( OUTPUT_FILE_KW ); ossimFilename outputFile; if ( lookup ) { ++consumedKeys; outputFile = lookup; } lookup = m_kwl.find( PRETTY_PRINT_KW ); if ( lookup ) { ++consumedKeys; prettyPrint(file); } // Check for dump. Does not require image to be opened. lookup = m_kwl.find( DUMP_KW ); if ( lookup ) { ++consumedKeys; lookup = m_kwl.find( DUMP_NO_OVERVIEWS_KW ); if ( lookup ) { ++consumedKeys; value = lookup; dnoFlag = value.toBool(); } if ( !xmlOutFlag && ( outputFile == ossimFilename::NIL ) ) { //--- // Write to standard out: // This dump will come out in order so is preferred over going to // okwl(output keyword list) which will come out alphabetical. //--- ossimKeywordlist kwl; dumpImage(file, dnoFlag, kwl); kwl.print(ossimNotify(ossimNotifyLevel_INFO)); } else { // Save to output keyword list. Will be output later. dumpImage(file, dnoFlag, okwl); } } bool centerGroundFlag = false; bool centerImageFlag = false; bool imageBoundsFlag = false; bool imageCenterFlag = false; bool imageGeomFlag = false; bool imageInfoFlag = false; bool imageRectFlag = false; bool img2grdFlag = false; bool grd2imgFlag = false; bool metaDataFlag = false; bool northUpFlag = false; bool paletteFlag = false; bool upIsUpFlag = false; bool imageToGroundFlag = false; bool groundToImageFlag = false; bool dumpState = false; bool canOpenFlag = false; lookup = m_kwl.find( DUMP_STATE_KW ); if ( lookup ) { ++consumedKeys; value = lookup; dumpState = value.toBool(); } // Center Ground: lookup = m_kwl.find( CENTER_GROUND_KW ); if ( lookup ) { ++consumedKeys; value = lookup; centerGroundFlag = value.toBool(); } // Center Image: lookup = m_kwl.find( CENTER_IMAGE_KW ); if ( lookup ) { ++consumedKeys; value = lookup; centerImageFlag = value.toBool(); } // Metadata: lookup = m_kwl.find( METADATA_KW ); if ( lookup ) { ++consumedKeys; value = lookup; metaDataFlag = value.toBool(); } // Palette: lookup = m_kwl.find( PALETTE_KW ); if ( lookup ) { ++consumedKeys; value = lookup; paletteFlag = value.toBool(); } // Image bounds: lookup = m_kwl.find( IMAGE_BOUNDS_KW ); if ( lookup ) { ++consumedKeys; value = lookup; imageBoundsFlag = value.toBool(); } // Image center: lookup = m_kwl.find( IMAGE_CENTER_KW ); if ( lookup ) { ++consumedKeys; value = lookup; imageCenterFlag = value.toBool(); } // Image rect: lookup = m_kwl.find( IMAGE_RECT_KW ); if ( lookup ) { ++consumedKeys; value = lookup; imageRectFlag = value.toBool(); } //--- // General image info: // Defaulted ON if no image options set. //--- lookup = m_kwl.find( IMAGE_INFO_KW ); if ( lookup ) { ++consumedKeys; value = lookup; imageInfoFlag = value.toBool(); } lookup = m_kwl.find( IMG2GRD_KW ); if ( lookup ) { ++consumedKeys; img2grdFlag = true; } lookup = m_kwl.find( GRD2IMG_KW ); if ( lookup ) { ++consumedKeys; grd2imgFlag = true; } //--- // Image geometry info: // Defaulted on if no image options set. //--- lookup = m_kwl.find( GEOM_INFO_KW ); if ( lookup ) { ++consumedKeys; value = lookup; imageGeomFlag = value.toBool(); } // North up: lookup = m_kwl.find( NORTH_UP_KW ); if ( lookup ) { ++consumedKeys; value = lookup; northUpFlag = value.toBool(); } // Up is up: lookup = m_kwl.find( UP_IS_UP_KW ); if ( lookup ) { ++consumedKeys; value = lookup; upIsUpFlag = value.toBool(); } // Up is up: lookup = m_kwl.find( CAN_OPEN_KW ); if ( lookup ) { ++consumedKeys; value = lookup; canOpenFlag = value.toBool(); } // If no options consumed default is image info and geom info: if ( consumedKeys == 0 ) { imageInfoFlag = true; imageGeomFlag = true; } if ( centerGroundFlag || centerImageFlag || imageBoundsFlag || imageCenterFlag || imageRectFlag || img2grdFlag || grd2imgFlag || metaDataFlag || paletteFlag || imageInfoFlag || imageGeomFlag || northUpFlag || upIsUpFlag || dumpState || imageToGroundFlag || groundToImageFlag || canOpenFlag) { // Requires open image. if ( ! m_img ) { openImage(file); } if( canOpenFlag ) { if(m_img) { okwl.add("can_open", "true", true); } else { okwl.add("can_open", "false", true); } } if ( centerGroundFlag ) { getCenterGround(okwl); } if ( centerImageFlag ) { getCenterImage(okwl); } if ( imageCenterFlag ) { // -c option prints both ground and image point of center. getCenterGround(okwl); getCenterImage(okwl); } if ( imageBoundsFlag ) { getImageBounds(okwl); } if ( imageRectFlag ) { getImageRect(okwl); } if ( img2grdFlag ) { getImg2grd(okwl); } if ( grd2imgFlag ) { getGrd2img(okwl); } if ( metaDataFlag ) { getImageMetadata(okwl); } if ( paletteFlag ) { getImagePalette(okwl); } if ( imageInfoFlag ) { getImageInfo(okwl, dnoFlag); } if ( imageGeomFlag ) { getImageGeometryInfo(okwl, dnoFlag); } if ( imageRectFlag ) { getImageRect(okwl); } if ( northUpFlag ) { getNorthUpAngle( okwl ); } if ( upIsUpFlag ) { getUpIsUpAngle( okwl ); } if(dumpState) { if(m_img) { if(m_img->getState()) { m_img->getState()->save(okwl); } } } } // if ( metaDataFlag || paletteFlag || imageInfoFlag || imageGeomFlag ) if ( okwl.getSize() ) // Output section: { if ( outputFile == ossimFilename::NIL ) { // Write to standard out: if ( !xmlOutFlag ) { ossimNotify(ossimNotifyLevel_INFO) << okwl << std::endl; } else { outputXml( okwl ); } } else { // Write to file: if ( !overwriteFlag && outputFile.exists() ) { ossimNotify(ossimNotifyLevel_INFO) << "ERROR: File already exists: " << outputFile << "\nUse -v option to overwrite." << std::endl; } else { if ( !xmlOutFlag ) { okwl.write( outputFile ); } else { outputXml( okwl, outputFile ); } } } } // if ( okwl ) if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "consumedKeys: " << consumedKeys << "\n" << M << " exited...\n"; } return consumedKeys; } // ossim_uint32 ossimInfo::executeImageOptions(const ossimFilename& file) void ossimInfo::getImageInfo( const ossimFilename& file, bool dumpFlag, bool dnoFlag, bool imageGeomFlag, bool imageInfoFlag, bool metaDataFlag, bool paletteFlag, ossimKeywordlist& kwl ) const { if ( dumpFlag || dnoFlag ) { dumpImage(file, dnoFlag, kwl); } // These flags requires open image. if ( imageGeomFlag || imageInfoFlag || metaDataFlag || paletteFlag ) { // Note: openImageHandler throws ossimException if it can't open. ossimRefPtr ih = openImageHandler( file ); if ( ih.valid() ) { if ( metaDataFlag ) { getImageMetadata( ih.get(), kwl ); } if ( paletteFlag ) { getImagePalette( ih.get(), kwl ); } if ( imageInfoFlag ) { getImageInfo( ih.get(), kwl, dnoFlag ); } if ( imageGeomFlag ) { getImageGeometryInfo( ih.get(), kwl, dnoFlag) ; } } } } bool ossimInfo::getImageInfo( const ossimFilename& file, ossim_uint32 entry, ossimKeywordlist& kwl ) const { bool result = false; // Note: openImageHandler throws ossimException if it can't open. ossimRefPtr ih = openImageHandler( file ); if ( ih.valid() ) { if ( ih->setCurrentEntry( entry ) ) { if ( getImageInfo( ih.get(), entry, kwl, false ) ) { result = getImageGeometryInfo( ih.get(), entry, kwl, false ); } } else { std::ostringstream errMsg; errMsg << "ossimInfo::getImageInfo ERROR:\nInvalid entry: " << entry << "\n"; throw ossimException( errMsg.str() ); } } return result; } void ossimInfo::openImage(const ossimFilename& file) { if(file.ext().downcase()=="kwl") { openImageFromState(file); } else { m_img = openImageHandler( file ); } } void ossimInfo::openImageFromState(const ossimFilename& file) { std::shared_ptr state; ossimKeywordlist kwl; if(kwl.addFile(file)) { state = ossim::ImageHandlerStateRegistry::instance()->createState(kwl); if(state) { m_img = ossimImageHandlerRegistry::instance()->open(state); } } } ossimRefPtr ossimInfo::openImageHandler(const ossimFilename& file) const { ossimRefPtr result; if(file.ext().downcase()=="kwl") { std::shared_ptr state; ossimKeywordlist kwl; if(kwl.addFile(file)) { state = ossim::ImageHandlerStateRegistry::instance()->createState(kwl); if(state) { result = ossimImageHandlerRegistry::instance()->open(state); } } } else { // Go through new interface that passes a stream around. (drb 10 Nov. 2016) // ossimRefPtr result = ossimImageHandlerRegistry::instance()->open(file); result = ossimImageHandlerRegistry::instance()-> openConnection(file); } // only throw an exception if the can-open option // is not specified ossimString canOpenFlag = m_kwl.find("can_open"); if ( !result.valid() && !canOpenFlag.toBool()) { std::string errMsg = "ossimInfo::openImage ERROR:\nCould not open: "; errMsg += file.string(); throw ossimException(errMsg); } return result; } void ossimInfo::closeImage() { m_img = 0; } ossimRefPtr ossimInfo::getImageHandler() { return m_img; } void ossimInfo::prettyPrint(const ossimFilename& file) const { std::shared_ptr info = ossimInfoFactoryRegistry::instance()->create(file); if (info) { //--- // Old -d behavior was to dump all unless the dump no overview flag // was set. Need to see tiff tags in file order for all image file // directories(ifd's) so commenting out hard coded // info->setProcessOverviewFlag(false) that used to be settable with -d // + --dno options. Note the old -d option used to do file order for // tiffs but now dumps to a keyword list that prints alphabetical(not // file order) so can't use that anymore. // // drb - 15 Dec. 2016 //--- // info->setProcessOverviewFlag(false); info->print(ossimNotify(ossimNotifyLevel_INFO)); info.reset(); } else { ossimNotify(ossimNotifyLevel_INFO) << "No print available for: " << file.c_str() << std::endl; } } void ossimInfo::dumpImage(const ossimFilename& file, bool dnoFlag, ossimKeywordlist& kwl) const { std::shared_ptr info = ossimInfoFactoryRegistry::instance()->create(file); if (info) { if (dnoFlag) // Default info processes overviews. { info->setProcessOverviewFlag(false); } info->getKeywordlist(kwl); info.reset(); } else { ossimNotify(ossimNotifyLevel_INFO) << "No dump available for: " << file.c_str() << std::endl; } } void ossimInfo::getImageMetadata(ossimKeywordlist& kwl) const { if ( m_img.valid() ) { getImageMetadata( m_img.get(), kwl); } } void ossimInfo::getImageMetadata(const ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { std::vector< ossimRefPtr< ossimProperty > > list; ih->getPropertyList(list); std::vector< ossimRefPtr< ossimProperty > >::const_iterator i = list.begin(); while (i != list.end()) { if ( (*i).valid() ) { ossimString key; ossimString value; // Check for one level of nested container. if ((*i)->getClassName() == "ossimContainerProperty") { ossimContainerProperty* ptr = PTR_CAST(ossimContainerProperty, (*i).get()); if (ptr) { std::vector< ossimRefPtr< ossimProperty > > list2; ptr->getPropertyList(list2); std::vector< ossimRefPtr< ossimProperty > >::const_iterator i2 = list2.begin(); while (i2 != list2.end()) { key = (*i2)->getName(); value = (*i2)->valueToString(); kwl.add(key.c_str(), value.c_str(), true); ++i2; } } } else // Not a container. { key = (*i)->getName(); value = (*i)->valueToString(); kwl.add(key.c_str(), value.c_str(), true); } } ++i; } } // if ( ih ) } // End: getImageMetadata(ossimImageHandler* ih, ossimKeywordlist& kwl) void ossimInfo::getImagePalette(ossimKeywordlist& kwl) { if ( m_img.valid() ) { getImagePalette( m_img.get(), kwl ); } } void ossimInfo::getImagePalette(ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { if(ih->getLut().valid()) { ossim_uint32 entryIdx = 0; std::vector entryList; ih->getEntryList(entryList); for(entryIdx = 0; entryIdx < ih->getNumberOfEntries();++entryIdx) { ih->setCurrentEntry(entryList[entryIdx]); ossimString prefix = "image"; prefix = prefix + ossimString::toString(entryList[entryIdx]) + ".lut."; if(ih->getLut().valid()) { ih->getLut()->saveState(kwl, prefix); } } } } // if ( ih ) } void ossimInfo::getImageInfo(ossimKeywordlist& kwl, bool dnoFlag) { if ( m_img.valid() ) { getImageInfo( m_img.get(), kwl, dnoFlag ); } } void ossimInfo::getImageInfo( ossimImageHandler* ih, ossimKeywordlist& kwl, bool dnoFlag ) const { if ( ih ) { ossim_uint32 numEntries = 0; std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { if ( getImageInfo( ih, (*i), kwl, dnoFlag ) ) { ++numEntries; } ++i; } kwl.add(ossimKeywordNames::NUMBER_ENTRIES_KW, numEntries, true); } // if ( ih ) } bool ossimInfo::getImageInfo( ossim_uint32 entry, ossimKeywordlist& kwl, bool dnoFlag ) { bool result = false; if ( m_img.valid() ) { result = getImageInfo( m_img.get(), entry, kwl, dnoFlag ); } return result; } bool ossimInfo::getImageInfo( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl, bool dnoFlag ) const { bool result = false; if ( ih ) { if ( ih->setCurrentEntry(entry) ) { bool outputEntry = true; if ( dnoFlag ) { if ( isImageEntryOverview() ) { outputEntry = false; } } if ( outputEntry ) { result = true; // Entry number: ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + "."; kwl.add(prefix.c_str(), ossimKeywordNames::ENTRY_KW, entry, true); // Get the entry_name (specialized multi-entry readers only): std::string entryName; ih->getEntryName( entry, entryName ); if ( entryName.size() ) { kwl.add(prefix.c_str(), "entry_name", entryName.c_str(), true); } // Type/class of reader: kwl.add(prefix, "type", ih->getClassName().c_str(), true); // Add RGB bands if available: getRgbBands( ih, entry, kwl ); // Driver name if different from class name: if ( ih->getClassName() != ih->getShortName() ) { kwl.add(prefix, "driver", ih->getShortName().c_str(), true); } // Type/class of overview reader: if (ih->getOverview()) { kwl.add(prefix, "overview.type", ih->getOverview()->getClassName().c_str(), true); } ossimDrect boundingRect = ih->getBoundingRect(); kwl.add(prefix,ossimKeywordNames::UL_X_KW, boundingRect.ul().x, true); kwl.add(prefix,ossimKeywordNames::UL_Y_KW, boundingRect.ul().y, true); kwl.add(prefix,ossimKeywordNames::LR_X_KW, boundingRect.lr().x, true); kwl.add(prefix,ossimKeywordNames::LR_Y_KW, boundingRect.lr().y, true); const ossim_uint32 BANDS = ih->getNumberOfInputBands(); kwl.add(prefix,ossimKeywordNames::NUMBER_INPUT_BANDS_KW, BANDS, true); kwl.add(prefix,ossimKeywordNames::NUMBER_OUTPUT_BANDS_KW, ih->getNumberOfOutputBands(), true); kwl.add(prefix,ossimKeywordNames::NUMBER_LINES_KW, boundingRect.height(), true); kwl.add(prefix,ossimKeywordNames::NUMBER_SAMPLES_KW, boundingRect.width(), true); ossimScalarType scalar = ih->getOutputScalarType(); for(ossim_uint32 i = 0; i < BANDS; ++i) { ossimString band = ossimString("band") + ossimString::toString(i) + "."; kwl.add(prefix, band+"null_value", ih->getNullPixelValue(i), true); kwl.add(prefix, band+"min_value", ih->getMinPixelValue(i), true); kwl.add(prefix, band+"max_value", ih->getMaxPixelValue(i), true); } // Output Radiometry. std::string rad; getRadiometry(scalar, rad); kwl.add(prefix, "radiometry", rad.c_str(), true); kwl.add(prefix,"number_decimation_levels", ih->getNumberOfDecimationLevels(), true); } // if ( outputEntry ) } // if ( ih->setCurrentEntry(entry) ) } // if ( ih ) return result; } // End: ossimInfo::getImageInfo( ih, entry... void ossimInfo::getImageGeometryInfo(ossimKeywordlist& kwl, bool dnoFlag) { if ( m_img.valid() ) { getImageGeometryInfo( m_img.get(), kwl, dnoFlag ); } } void ossimInfo::getImageGeometryInfo( ossimImageHandler* ih, ossimKeywordlist& kwl, bool dnoFlag) const { if ( ih ) { ossim_uint32 numEntries = 0; std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { if ( getImageGeometryInfo( ih, (*i), kwl, dnoFlag ) ) { ++numEntries; } ++i; } kwl.add(ossimKeywordNames::NUMBER_ENTRIES_KW, numEntries, true); } // if ( ih ) } bool ossimInfo::getImageGeometryInfo(ossim_uint32 entry, ossimKeywordlist& kwl, bool dnoFlag) { bool result = false; if ( m_img.valid() ) { getImageGeometryInfo( m_img.get(), entry, kwl, dnoFlag ); } return result; } bool ossimInfo::getImageGeometryInfo( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl, bool dnoFlag) const { bool result = false; if ( ih ) { if ( ih->setCurrentEntry(entry) ) { bool outputEntry = true; if ( dnoFlag ) { if ( isImageEntryOverview() ) { outputEntry = false; } } if ( outputEntry ) { ossimRefPtr geom = ih->getImageGeometry(); if(geom.valid()) { result = true; ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + ossimString(".geometry."); geom->saveState(kwl, prefix); // Output support files list: ossimSupportFilesList::instance()->save(kwl, prefix); ossimGpt ulg; ossimGpt llg; ossimGpt lrg; ossimGpt urg; ossimDrect outputRect = ih->getBoundingRect(); geom->localToWorld(outputRect.ul(), ulg); geom->localToWorld(outputRect.ll(), llg); geom->localToWorld(outputRect.lr(), lrg); geom->localToWorld(outputRect.ur(), urg); //--- // *** HACK *** // Encountered CADRG RPF imagery where the left edge was longitude -180 and // right edge +180. The projection code above reasonably maps all -180 to +180. // This however breaks the image footprint since it would appear that the left // and right edges were coincident instead of 360 degrees apart, i.e., a line // segment instead of a rect. So added check here for coincident left and right // edges and remapping left edge to -180. //--- if ((ulg.lon == 180.0) && (urg.lon == 180.0)) { ulg.lon = -180.0; } if ((llg.lon == 180.0) && (lrg.lon == 180.0)) { llg.lon = -180.0; } kwl.add(prefix, "ul_lat", ulg.latd(), true); kwl.add(prefix, "ul_lon", ulg.lond(), true); kwl.add(prefix, "ll_lat", llg.latd(), true); kwl.add(prefix, "ll_lon", llg.lond(), true); kwl.add(prefix, "lr_lat", lrg.latd(), true); kwl.add(prefix, "lr_lon", lrg.lond(), true); kwl.add(prefix, "ur_lat", urg.latd(), true); kwl.add(prefix, "ur_lon", urg.lond(), true); if(!kwl.find(ossimKeywordNames::TIE_POINT_LAT_KW)) { kwl.add(prefix, ossimKeywordNames::TIE_POINT_LAT_KW, ulg.latd(), true); kwl.add(prefix, ossimKeywordNames::TIE_POINT_LON_KW, ulg.lond(), true); } ossimDpt dpp; geom->getDegreesPerPixel( dpp ); if ( dpp.hasNans() == false ) { kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT, dpp.lat, true); kwl.add(prefix, ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON, dpp.lon, true); } ossimDpt gsd = geom->getMetersPerPixel(); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_X_KW, gsd.x, true); kwl.add(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW, gsd.y, true); } // if(geom.valid()) } // if ( outputEntry ) } // if ( ih->setCurrentEntry(entry) ) if ( !result ) { ossimNotify(ossimNotifyLevel_WARN) << "No geometry for file " << ih->getFilename() << std::endl; } } // if ( ih ) return result; } // End: ossimInfo::getImageGeometryInfo( ih, entry... void ossimInfo::getCenterImage(ossimKeywordlist& kwl) { if ( m_img.valid() ) { getCenterImage( m_img.get(), kwl ); } } void ossimInfo::getCenterImage( ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { getCenterImage( ih, (*i), kwl ); ++i; } } } void ossimInfo::getCenterImage( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl ) const { if ( ih ) { if ( ih->setCurrentEntry(entry) ) { ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + "."; ossimDrect bounds = ih->getBoundingRect(); if( !bounds.hasNans() ) { ossimDpt iPt = bounds.midPoint(); kwl.add(prefix, "center_image", iPt.toString().c_str(), true); } } // if ( ih->setCurrentEntry(entry) ) else { ossimNotify(ossimNotifyLevel_WARN) << "Could not get image center for: " << ih->getFilename() << std::endl; } } // if ( ih ) } void ossimInfo::getCenterGround(ossimKeywordlist& kwl) { if ( m_img.valid() ) { getCenterGround( m_img.get(), kwl ); } } void ossimInfo::getCenterGround( ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { getCenterGround( ih, (*i), kwl ); ++i; } } } void ossimInfo::getCenterGround( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl ) const { if ( ih ) { if ( ih->setCurrentEntry(entry) ) { ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + "."; ossimRefPtr geom = ih->getImageGeometry(); if(geom.valid()) { ossimDrect bounds; geom->getBoundingRect( bounds ); if( !bounds.hasNans() ) { ossimDpt iPt = bounds.midPoint(); ossimGpt gPt; geom->localToWorld(iPt, gPt); kwl.add(prefix, "center_ground", gPt.toString().c_str(), true); } } } // if ( ih->setCurrentEntry(entry) ) else { ossimNotify(ossimNotifyLevel_WARN) << "Could not get ground center for: " << ih->getFilename() << std::endl; } } // if ( ih ) } void ossimInfo::getImageBounds(ossimKeywordlist& kwl) { if ( m_img.valid() ) { getImageBounds( m_img.get(), kwl ); } } void ossimInfo::getImageBounds( ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { getImageBounds( ih, (*i), kwl ); ++i; } } } void ossimInfo::getImageBounds( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl ) const { if ( ih ) { if ( ih->setCurrentEntry(entry) ) { ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + ".bounds."; ossimRefPtr geom = ih->getImageGeometry(); if(geom.valid()) { ossimDrect bounds; geom->getBoundingRect( bounds ); // Make edge to edge. bounds.expand( ossimDpt(0.5, 0.5) ); if( !bounds.hasNans() ) { ossimGpt gPt; geom->localToWorld(bounds.ul(), gPt); kwl.add(prefix, "ul", gPt.toString().c_str(), true); geom->localToWorld(bounds.ur(), gPt); kwl.add(prefix, "ur", gPt.toString().c_str(), true); geom->localToWorld(bounds.lr(), gPt); kwl.add(prefix, "lr", gPt.toString().c_str(), true); geom->localToWorld(bounds.ll(), gPt); kwl.add(prefix, "ll", gPt.toString().c_str(), true); } } } // if ( ih->setCurrentEntry(entry) ) else { ossimNotify(ossimNotifyLevel_WARN) << "Could not get image bounds for: " << ih->getFilename() << std::endl; } } // if ( ih ) } void ossimInfo::getImg2grd(ossimKeywordlist& kwl) { if ( m_img.valid() ) { getImg2grd( m_img.get(), kwl ); } } void ossimInfo::getImg2grd( ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { getImg2grd( ih, (*i), kwl ); ++i; } } } void ossimInfo::getImg2grd( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl ) const { if ( ih ) { if ( ih->setCurrentEntry(entry) ) { ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + "."; ossimRefPtr geom = ih->getImageGeometry(); if(geom.valid()) { ossimDrect bounds; geom->getBoundingRect( bounds ); if( !bounds.hasNans() ) { //--- // Expand the bounds out to edge of image so caller can do: // ossim-info --img2grd -0.5 -0.5 //--- bounds.expand( ossimDpt(0.5, 0.5) ); std::string value = m_kwl.findKey( IMG2GRD_KW ); if ( value.size() ) { ossimDpt ipt; ipt.toPoint( value ); if ( bounds.pointWithin( ipt ) ) { ossimGpt gpt; gpt.makeNan(); geom->localToWorld(ipt, gpt); kwl.add(prefix, "ground_point", gpt.toString().c_str(), true); } else { kwl.add(prefix, "ground_point", "nan", true); } } } } } // if ( ih->setCurrentEntry(entry) ) else { ossimNotify(ossimNotifyLevel_WARN) << "Could not get ground center for: " << ih->getFilename() << std::endl; } } // if ( ih ) } void ossimInfo::getGrd2img(ossimKeywordlist& kwl) { if ( m_img.valid() ) { getGrd2img( m_img.get(), kwl ); } } void ossimInfo::getGrd2img( ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { getGrd2img( ih, (*i), kwl ); ++i; } } } void ossimInfo::getGrd2img( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl ) const { if ( ih ) { if ( ih->setCurrentEntry(entry) ) { ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + "."; ossimRefPtr geom = ih->getImageGeometry(); if(geom.valid()) { std::string value = m_kwl.findKey( GRD2IMG_KW ); if ( value.size() ) { ossimGpt gpt; ossimDpt dpt; gpt.toPoint( value ); dpt.makeNan(); geom->worldToLocal(gpt, dpt); kwl.add(prefix, "image_point", dpt.toString().c_str(), true); } } } // if ( ih->setCurrentEntry(entry) ) else { ossimNotify(ossimNotifyLevel_WARN) << "Could not get ground center for: " << ih->getFilename() << std::endl; } } // if ( ih ) } void ossimInfo::getUpIsUpAngle(ossimKeywordlist& kwl) { if ( m_img.valid() ) { getUpIsUpAngle( m_img.get(), kwl ); } } void ossimInfo::getUpIsUpAngle( ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { getUpIsUpAngle( ih, (*i), kwl ); ++i; } } } void ossimInfo::getUpIsUpAngle(ossim_uint32 entry, ossimKeywordlist& kwl) { if ( m_img.valid() ) { getUpIsUpAngle( m_img.get(), entry, kwl ); } } void ossimInfo::getUpIsUpAngle( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl ) const { if ( ih ) { bool result = false; if ( ih->setCurrentEntry(entry) ) { ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + "."; ossimRefPtr geom = ih->getImageGeometry(); if(geom.valid()) { ossim_float64 upIsUp = 0.0; if ( geom->isAffectedByElevation() ) { ossimDpt imagePt; imagePt.makeNan(); ossimString lookup = m_kwl.find(UP_IS_UP_GPT_KW); if(!lookup.empty()) { std::istringstream in(lookup.c_str()); ossim_float64 lat,lon; in>>lat>>lon; ossimGpt gpt(lat,lon); geom->worldToLocal(gpt, imagePt); } else { lookup = m_kwl.find(UP_IS_UP_IPT_KW); if(!lookup.empty()) { std::istringstream in(lookup.c_str()); ossim_float64 x,y; in>>x>>y; imagePt = ossimDpt(x,y); } } upIsUp = geom->upIsUpAngle(imagePt); kwl.add(prefix, UP_IS_UP_KW, upIsUp, true); } } result = true; } // if ( ih->setCurrentEntry(entry) ) if ( !result ) { ossimNotify(ossimNotifyLevel_WARN) << "Could not get up is up angle for: " << ih->getFilename() << std::endl; } } // if ( ih ) } void ossimInfo::getNorthUpAngle(ossimKeywordlist& kwl) { if ( m_img.valid() ) { getNorthUpAngle( m_img.get(), kwl ); } } void ossimInfo::getNorthUpAngle( ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { getNorthUpAngle( ih, (*i), kwl ); ++i; } } } void ossimInfo::getNorthUpAngle(ossim_uint32 entry, ossimKeywordlist& kwl) { if ( m_img.valid() ) { getNorthUpAngle( m_img.get(), entry, kwl ); } } void ossimInfo::getNorthUpAngle( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl ) const { if ( ih ) { bool result = false; if ( ih->setCurrentEntry(entry) ) { ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + "."; ossimRefPtr geom = ih->getImageGeometry(); if(geom.valid()) { ossim_float64 northUp = geom->northUpAngle(); kwl.add(prefix, NORTH_UP_KW, northUp, true); } result = true; } // if ( ih->setCurrentEntry(entry) ) if ( !result ) { ossimNotify(ossimNotifyLevel_WARN) << "Could not get north up angle for: " << ih->getFilename() << std::endl; } } // if ( ih ) } void ossimInfo::getImageRect(ossimKeywordlist& kwl) { if ( m_img.valid() ) { getImageRect( m_img.get(), kwl ); } } void ossimInfo::getImageRect( ossimImageHandler* ih, ossimKeywordlist& kwl) const { if ( ih ) { std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator i = entryList.begin(); while ( i != entryList.end() ) { getImageRect( ih, (*i), kwl ); ++i; } } // if ( ih ) } bool ossimInfo::getRgbBands( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl ) const { bool result = false; if ( ih ) { std::vector bandList; result = ih->getRgbBandList( bandList ); if ( result && ( bandList.size() == 3 ) ) { ossimString os; ossim::toSimpleStringList(os, bandList); if ( os.size() ) { ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + "."; kwl.add(prefix, "rgb_bands", os.c_str(), true); } } } return result; } // End: ossimInfo::getRgbBands( ... ) void ossimInfo::getImageRect(ossim_uint32 entry, ossimKeywordlist& kwl) { if ( m_img.valid() ) { getImageRect( m_img.get(), entry, kwl ); } } void ossimInfo::getImageRect( ossimImageHandler* ih, ossim_uint32 entry, ossimKeywordlist& kwl ) const { if ( ih ) { if ( ih->setCurrentEntry(entry) ) { ossimString prefix = "image"; prefix = prefix + ossimString::toString(entry) + "."; ossimIrect outputRect = ih->getBoundingRect(); kwl.add(prefix, "image_rectangle", outputRect.toString().c_str(), true); } // if ( ih->setCurrentEntry(entry) ) else { ossimNotify(ossimNotifyLevel_WARN) << "Could not get image rectangle for: " << ih->getFilename() << std::endl; } } // if ( ih ) } // End: getImageRect( ih, entry... // Note be sure to m_img->setCurrentEntry before calling. bool ossimInfo::isImageEntryOverview() const { bool result = false; // Have to prove it. if ( m_img.valid() ) { result = isImageEntryOverview( m_img.get() ); } return result; } bool ossimInfo::isImageEntryOverview( const ossimImageHandler* ih ) const { bool result = false; // Have to prove it. if ( ih ) { ossimString s = "imag"; ossimRefPtr prop = ih->getProperty(s); if (prop.valid()) { ossimString s; prop->valueToString(s); if (s.toFloat32() < 1.0) { result = true; } } } return result; } void ossimInfo::printConfiguration() const { printConfiguration( ossimNotify(ossimNotifyLevel_INFO) ); } std::ostream& ossimInfo::printConfiguration(std::ostream& out) const { out << "\npreferences_keyword_file: " << ossimPreferences::instance()->getPreferencesFilename() << "\n" << "preferences_keyword_list:\n" << ossimPreferences::instance()->preferencesKWL() << std::endl; return out; } void ossimInfo::printFactories(bool keywordListFlag)const { std::vector typeList; ossimObjectFactoryRegistry::instance()->getTypeNameList(typeList); for(int i = 0; i < (int)typeList.size(); ++i) { if(keywordListFlag) { ossimObject* obj = ossimObjectFactoryRegistry::instance()->createObject(typeList[i]); if(obj) { cout << typeList[i] << endl; cout << "______________________________________________________" << endl; ossimKeywordlist kwl; obj->saveState(kwl); cout << kwl << endl; cout << "______________________________________________________" << endl; delete obj; } } else { cout << typeList[i] << endl; } } } void ossimInfo::printDatums() const { ossimInfo::printDatums( ossimNotify(ossimNotifyLevel_INFO) ); } std::ostream& ossimInfo::printDatums(std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); std::vector datumList; ossimDatumFactoryRegistry::instance()->getList(datumList); std::vector::const_iterator i = datumList.begin(); while ( i != datumList.end() ) { const ossimDatum* datum = ossimDatumFactoryRegistry::instance()->create(*i); if (datum) { if ( datum->ellipsoid() ) { out << setiosflags(ios::left) << setw(7) << datum->code().c_str() << setw(7) << datum->epsgCode() << setw(48) << datum->name().c_str() << setw(10) << "Ellipse:" << datum->ellipsoid()->name() << std::endl; } else { out << "No ellipsoid for code: " << (*i) << std::endl; } } else { out << "No datum for code: " << (*i) << std::endl; } ++i; } // Reset flags. out.setf(f); return out; } void ossimInfo::printFonts() const { ossimInfo::printFonts( ossimNotify(ossimNotifyLevel_INFO) ); } std::ostream& ossimInfo::printFonts(std::ostream& out) const { std::vector fontInfoList; ossimFontFactoryRegistry::instance()->getFontInformation( fontInfoList ); std::vector::const_iterator i = fontInfoList.begin(); while ( i != fontInfoList.end() ) { out << *(i) << endl; ++i; } // Get the default: ossimRefPtr defaultFont = ossimFontFactoryRegistry::instance()->getDefaultFont(); if ( defaultFont.valid() ) { out << "default_font: " << defaultFont->getFamilyName() << std::endl; } return out; } void ossimInfo::deg2rad(const ossim_float64& degrees) const { deg2rad( degrees, ossimNotify(ossimNotifyLevel_INFO) ); } std::ostream& ossimInfo::deg2rad(const ossim_float64& degrees, std::ostream& out) const { double radians = degrees * RAD_PER_DEG; // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << std::setiosflags(std::ios::fixed) << std::setprecision(15) << "\n" << degrees << " degrees = " << radians << " radians.\n" << std::endl; // Reset flags. out.setf(f); return out; } std::ostream& ossimInfo::ecef2llh(const ossimEcefPoint& ecefPoint, std::ostream& out) const { out << "ECEF: " << ecefPoint.toString() << "\n" << "lat_lon_height: " << ossimGpt(ecefPoint).toString() << "\n"; return out; } void ossimInfo::rad2deg(const ossim_float64& radians) const { rad2deg(radians, ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::rad2deg(const ossim_float64& radians, std::ostream& out) const { double degrees = radians * DEG_PER_RAD; // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << std::setiosflags(std::ios::fixed) << std::setprecision(15) << "\n" << radians << " radians = " << degrees << " degrees.\n" << std::endl; // Reset flags. out.setf(f); return out; } void ossimInfo::ft2mtrs(const ossim_float64& feet, bool us_survey) const { ft2mtrs( feet, us_survey, ossimNotify(ossimNotifyLevel_INFO) ); } std::ostream& ossimInfo::ft2mtrs(const ossim_float64& feet, bool us_survey, std::ostream& out) const { ossim_float64 meters = 0.0; std::string conversionString; if (us_survey) { meters = feet * US_METERS_PER_FT; conversionString = "0.3048006096"; } else { meters = feet * MTRS_PER_FT; conversionString = "0.3048"; } // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << setiosflags(ios::fixed) << setprecision(15) << feet << " * " << conversionString << " = " << meters << " meters." << std::endl; // Reset flags. out.setf(f); return out; } void ossimInfo::mtrs2ft(const ossim_float64& meters, bool us_survey) const { mtrs2ft(meters, us_survey, ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::mtrs2ft(const ossim_float64& meters, bool us_survey, std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); double feet = 0.0; std::string conversionString; if (us_survey) { feet = meters / US_METERS_PER_FT; conversionString = "0.3048006096"; } else { feet = meters / MTRS_PER_FT; conversionString = "0.3048"; } out << setiosflags(ios::fixed) << setprecision(15) << meters << " / " << conversionString << " = " << feet << " feet." << std::endl; // Reset flags. out.setf(f); return out; } void ossimInfo::mtrsPerDeg(const ossim_float64& latitude) const { mtrsPerDeg(latitude, ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::mtrsPerDeg(const ossim_float64& latitude, std::ostream& out) const { ossimGpt gpt(latitude, 0.0); ossimDpt mpd = gpt.metersPerDegree(); ossim_float64 radius = gpt.datum()->ellipsoid()->geodeticRadius(latitude); ossim_float64 arcLengthLat = mpd.y/60.0; ossim_float64 arcLengthLon = mpd.x/60.0; out << setiosflags(ios::fixed) << setprecision(15) << "Meters per degree and minute at latitude of " << latitude << ":\n" << "Meters per degree latitude: " << setw(20) << mpd.y << "\n" << "Meters per degree longitude: " << setw(20) << mpd.x << "\n" << "Meters per minute latitude: " << setw(20) << arcLengthLat << "\n" << "Meters per minute longitude: " << setw(20) << arcLengthLon << "\n" << "Geodetic radius: " << setw(20) << radius << "\n" << std::endl; return out; } void ossimInfo::outputHeight(const ossimGpt& gpt) const { outputHeight(gpt, ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::outputHeight(const ossimGpt& gpt, std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); // Handle wrap conditions. ossimGpt copyGpt = gpt; copyGpt.wrap(); ossim_float64 hgtAboveMsl = ossimElevManager::instance()->getHeightAboveMSL(copyGpt); ossim_float64 hgtAboveEllipsoid = ossimElevManager::instance()->getHeightAboveEllipsoid(copyGpt); ossim_float64 geoidOffset = ossimGeoidManager::instance()->offsetFromEllipsoid(copyGpt); ossim_float64 mslOffset = 0.0; if(ossim::isnan(hgtAboveEllipsoid)||ossim::isnan(hgtAboveMsl)) { mslOffset = ossim::nan(); } else { mslOffset = hgtAboveEllipsoid - hgtAboveMsl; } std::vector cellList; ossimElevManager::instance()->getOpenCellList(cellList); if (!cellList.empty()) { out << "Opened cell: " << cellList[0] << "\n"; } else { out << "Did not find cell for point: " << gpt << "\n"; } out << "MSL to ellipsoid delta: "; if (!ossim::isnan(mslOffset)) { out << std::setprecision(15) << mslOffset; } else { out << "nan"; } out << "\nHeight above MSL: "; if (!ossim::isnan(hgtAboveMsl)) { out << std::setprecision(15) << hgtAboveMsl; } else { out << "nan"; } out << "\nHeight above ellipsoid: "; if (!ossim::isnan(hgtAboveEllipsoid)) { out << std::setprecision(15) << hgtAboveEllipsoid << "\n"; } else { out << "nan" << "\n"; } out << "Geoid value: "; if (!ossim::isnan(geoidOffset)) { out << std::setprecision(15) << geoidOffset << std::endl; } else { out << "nan" << std::endl; } // Reset flags. out.setf(f); return out; } void ossimInfo::printExtensions() const { printExtensions(ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::printExtensions(std::ostream& out) const { ossimImageHandlerFactoryBase::UniqueStringList extList; ossimImageHandlerRegistry::instance()->getSupportedExtensions(extList); const vector& list = extList.getList(); if (list.empty()) { out << "No image file extensions handled. This should never happen!" << std::endl; return out; } out<<"\nImage Entensions Supported:"<< endl; for (const auto& extension : list) out<<" "<getNumberOfPlugins() > 0) { ossimSharedPluginRegistry::instance()->printAllPluginInformation(out); } else { out << "No plugins loaded in the OSSIM core library" << std::endl; } return out; } void ossimInfo::testPlugin(const ossimFilename& plugin) const { testPlugin(plugin, ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::testPlugin(const ossimFilename& plugin, std::ostream& out) const { if( ossimSharedPluginRegistry::instance()->registerPlugin(plugin.expand()) ) { out << "Plugin loaded: " << plugin << std::endl; } else { out << "Unable to load plugin: " << plugin << std::endl; } return out; } void ossimInfo::printOverviewTypes() const { printOverviewTypes(ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::printOverviewTypes(std::ostream& out) const { out << "\nValid overview types: " << std::endl; std::vector outputType; ossimOverviewBuilderFactoryRegistry::instance()->getTypeNameList(outputType); std::copy(outputType.begin(), outputType.end(), std::ostream_iterator(out, "\t\n")); return out; } void ossimInfo::printProjections() const { printProjections(ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::printProjections(std::ostream& out) const { out << "Projections:\n"; std::vector list; ossimProjectionFactoryRegistry::instance()-> getAllTypeNamesFromRegistry(list); std::vector::const_iterator i = list.begin(); while ( i != list.end() ) { out << *i << "\n"; ++i; } out << std::endl; return out; } void ossimInfo::printReaderProps() const { printReaderProps(ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::printReaderProps(std::ostream& out) const { return ossimImageHandlerRegistry::instance()->printReaderProps( out ); } void ossimInfo::printResamplerFilters() const { printResamplerFilters(ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::printResamplerFilters(std::ostream& out) const { std::vector list; ossimFilterResampler f; f.getFilterTypes(list); std::vector::const_iterator i = list.begin(); while ( i != list.end() ) { out << *i << "\n"; ++i; } out << std::endl; return out; } void ossimInfo::printWriters() const { printWriters(ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::printWriters(std::ostream& out) const { return ossimImageWriterFactoryRegistry::instance()->printImageTypeList( out ); } void ossimInfo::printZoomLevelGsds() const { printZoomLevelGsds(ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::printZoomLevelGsds(std::ostream& out) const { // Capture the original flags. std::ios_base::fmtflags f = out.flags(); out << setprecision(15)<< setiosflags(std::ios_base::fixed|std::ios_base::right); const int MAX_LEVEL = 24; const double TILE_SIZE = 256.0; const double EPSG_4326_BOUNDS = 180.0; const double EPSG_3857_BOUNDS = 40075016.685578488; // From: ossim-info --mtrsPerDeg 0.0 const double MTRS_PER_DEGREE_AT_EQUATOR = 111319.490793273565941; out << "Notes:\n" << "tile size: 256\n" << "dpp = \"degrees per pixel\"\n" << "mpp = \"meters per pixel\"\n\n"; // Assuming square pixels, level 0 having (2 x 1) tiles. double level_0_gsd = EPSG_4326_BOUNDS / TILE_SIZE; double level_gsd = 0.0; int i = 0; int tilesX = 2; int tilesY = 1; out << "EPSG:4326 level info:\n" << "Note: Assuming square pixels, level 0 having (2x1) tiles.\n" << "bounds: 360.0 X 180.0\n" << "level[" << std::setw(2) << std::setfill('0') << i << "] dpp:" << std::setw(18) << std::setfill(' ') << level_0_gsd << " equivalent mpp:" << std::setw(22) << (level_0_gsd * MTRS_PER_DEGREE_AT_EQUATOR) << " (" << tilesX << "x" << tilesY << ")" << "\n"; for ( i = 1; i <= MAX_LEVEL; ++i ) { tilesX = tilesX << 1; tilesY = tilesY << 1; level_gsd = level_0_gsd / std::pow( 2.0, i ); out << "level[" << std::setw(2) << std::setfill('0') << i << "] dpp:" << std::setw(18) << std::setfill(' ') << level_gsd << " equivalent mpp:" << std::setw(22) << (level_gsd * MTRS_PER_DEGREE_AT_EQUATOR) << " (" << tilesX << "x" << tilesY << ")"<< "\n"; } // Assuming square pixels, level 0 having (1 x 1) tiles. level_0_gsd = EPSG_3857_BOUNDS / TILE_SIZE; level_gsd = 0.0; i = 0; tilesX = 1; // X and y the same. out << "\n\nEPSG:3857 level info:\n" << "Note: Assuming square pixels, level 0 having (1x1) tile.\n" << "bounds: 40075016.685578488 X 40075016.685578488\n" << "level[" << std::setw(2) << std::setfill('0') << i << "] mpp:" << std::setw(23) << std::setfill(' ') << level_0_gsd << " (" << tilesX << "x" << tilesX << ")" << "\n"; for ( i = 1; i <= MAX_LEVEL; ++i ) { tilesX = tilesX << 1; level_gsd = level_0_gsd / std::pow( 2.0, i ); out << "level[" << std::setw(2) << std::setfill('0') << i << "] mpp:" << std::setw(23) << std::setfill(' ') << level_gsd << " (" << tilesX << "x" << tilesX << ")" << "\n"; } // Reset flags. out.setf(f); return out; } // End: ossimInfo::printZoomLevelGsds(std::ostream& out) void ossimInfo::printWriterProps() const { printWriterProps(ossimNotify(ossimNotifyLevel_INFO)); } std::ostream& ossimInfo::printWriterProps(std::ostream& out) const { return ossimImageWriterFactoryRegistry::instance()->printWriterProps( out ); } void ossimInfo::getRadiometry(ossimScalarType scalar, std::string& s) const { // Output Radiometry. switch(scalar) { case OSSIM_UINT8: { s = "8-bit"; break; } case OSSIM_USHORT11: { s = "11-bit"; break; } case OSSIM_USHORT12: { s = "12-bit"; break; } case OSSIM_USHORT13: { s = "13-bit"; break; } case OSSIM_USHORT14: { s = "14-bit"; break; } case OSSIM_USHORT15: { s = "15-bit"; break; } case OSSIM_UINT16: { s = "16-bit unsigned"; break; } case OSSIM_SINT16: { s = "16-bit signed"; break; } case OSSIM_UINT32: { s = "32-bit unsigned"; break; } case OSSIM_SINT32: { s = "32-bit signed"; break; } case OSSIM_FLOAT32: { s = "32-bit float"; break; } case OSSIM_DOUBLE: { s = "64-bit double float"; break; } case OSSIM_NORMALIZED_FLOAT: { s = "normalized 32-bit float"; break; } case OSSIM_NORMALIZED_DOUBLE: { s = "normalized 64-bit double float"; break; } default: { s = "unknown"; break; } } } void ossimInfo::getBuildDate(std::string& s) const { #ifdef OSSIM_BUILD_DATE s = OSSIM_BUILD_DATE; #else s = "unknown"; #endif } void ossimInfo::getRevisionNumber(std::string& s) const { #ifdef OSSIM_REVISION s = OSSIM_REVISION; #else s = "unknown"; #endif } void ossimInfo::getVersion(std::string& s) const { #ifdef OSSIM_VERSION s = OSSIM_VERSION; #else s = "unknown"; #endif } void ossimInfo::outputXml( const ossimKeywordlist& kwl ) const { ossimXmlDocument document; document.fromKwl( kwl ); ossimNotify(ossimNotifyLevel_INFO) << document << std::endl; } void ossimInfo::outputXml( const ossimKeywordlist& kwl, const ossimFilename& file ) const { ossimXmlDocument document; document.fromKwl( kwl ); document.write( file ); } bool ossimInfo::keyIsTrue( const std::string& key ) const { bool result = false; std::string value = m_kwl.findKey( key ); if ( value.size() ) { result = ossimString(value).toBool(); } return result; } ossim-Miami-2.9.1/src/util/ossimOrthoIgen.cpp000066400000000000000000003527551352751253100211550ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id: ossimOrthoIgen.cpp 22813 2014-06-04 19:52:08Z okramer $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; // In Windows, standard output is ASCII by default. // Let's include the following in case we have // to change it over to binary mode. #if defined(_WIN32) # include # include #endif static ossimTrace traceDebug("ossimOrthoIgen:debug"); static ossimTrace traceLog("ossimOrthoIgen:log"); static const char* AUTOGENERATE_HISTOGRAM_KW = "autogenerate_histogram"; using namespace ossim; //************************************************************************************************* // Parses the file info as specified in the command line or src file. The file info is a '|'- // delimited string with filename and additional attributes such as entry and band numbers. //************************************************************************************************* bool ossimOrthoIgen::parseFilename(const ossimString& file_spec, bool decodeEntry) { ossimSrcRecord src_record; std::vector fileInfos = file_spec.split("|"); unsigned int num_fields = (unsigned int) fileInfos.size(); unsigned int field_idx = 0; if (num_fields == 0) return false; // First field is the actual filename: src_record.setFilename(fileInfos[field_idx]); ++field_idx; // Next field depends on whether an entry is being decoded: if ((field_idx < num_fields) && decodeEntry) { src_record.setEntryIndex(fileInfos[field_idx].trim().toInt32()); ++field_idx; } // The rest of the fields can appear in any order: while (field_idx < num_fields) { ossimString active_field (fileInfos[field_idx].trim()); ossimString downcased_field (active_field); downcased_field.downcase(); ++field_idx; // Check for overview file spec: ossimFilename filename (active_field); if (filename.contains(".ovr") || filename.isDir()) { src_record.setSupportDir(filename.path()); } else if (filename.contains(".mask") || filename.isDir()) { src_record.setSupportDir(filename.path()); } // else check for auto-minmax histogram stretch: else if ((downcased_field == "auto-minmax") || downcased_field.contains("std-stretch")) { src_record.setHistogramOp(downcased_field); } // Otherwise, this must be a band specification. Band numbers begin with 1: else { // multiple bands delimited by comma: std::vector bandsStr = active_field.split(","); std::vector bands; for (unsigned int i = 0; i < bandsStr.size(); i++) { int band = bandsStr[i].toInt32() - 1; if (band >= 0) bands.push_back((ossim_uint32)band); } src_record.setBands(bands); } } // end of while loop parsing fileInfos spec theSrcRecords.push_back(src_record); return true; } //************************************************************************************************* // Constructor //************************************************************************************************* ossimOrthoIgen::ossimOrthoIgen() : ossimIgen(), theDeltaPerPixelUnit(OSSIM_UNIT_UNKNOWN), theDeltaPerPixelOverride(ossim::nan(), ossim::nan()), theProjectionType(OSSIM_UNKNOWN_PROJECTION), theProjectionName(""), theGeoScalingLatitude(ossim::nan()), theCombinerType("ossimImageMosaic"), theResamplerType("nearest neighbor"), theWriterType(""), theTemplateView(""), theTilingTemplate(""), theTilingFilename(""), theChainTemplate(""), theCombinerTemplate(""), theAnnotationTemplate(""), theWriterTemplate(""), theSupplementaryDirectory(""), theSlaveBuffers("2"), theCutOriginType(ossimOrthoIgen::OSSIM_CENTER_ORIGIN), theCutOrigin(ossim::nan(), ossim::nan()), theCutDxDy(ossim::nan(), ossim::nan()), theCutOriginUnit(OSSIM_UNIT_UNKNOWN), theCutDxDyUnit(OSSIM_UNIT_UNKNOWN), theLowPercentClip(ossim::nan()), theHighPercentClip(ossim::nan()), theStdDevClip(-1), theUseAutoMinMaxFlag(false), theClipToValidRectFlag(false), theReaderProperties(), theWriterProperties(), theTargetHistoFileName(), theProductFilename(), theReferenceProj(0), theMaskShpFile(""), theCacheExcludedFlag(false), theOutputRadiometry(""), thePixelAlignment(OSSIM_PIXEL_IS_AREA) // will revert to "point" upon first occurrence in source list { // Determine default behavior of clip from preferences: ossimString flag = ossimPreferences::instance()->findPreference("orthoigen.clip_to_valid_rect"); if (!flag.empty()) theClipToValidRectFlag = flag.toBool(); thePixelReplacementMode = ossimPreferences::instance()->findPreference("orthoigen.flip_null_pixels"); return; } //************************************************************************************************* // Initializes the argument parser //************************************************************************************************* void ossimOrthoIgen::addArguments(ossimArgumentParser& argumentParser) { // These are in ALPHABETIC ORDER. Please keep it that way. argumentParser.getApplicationUsage()->addCommandLineOption( "--annotate", "annotation keyword list"); argumentParser.getApplicationUsage()->addCommandLineOption( "--chain-template","Specify an external file that contains chain information"); argumentParser.getApplicationUsage()->addCommandLineOption( "--clamp-pixels ","Specify the min and max allowed pixel values. All values " "outside of this get mapped to their corresponding clamp value."); argumentParser.getApplicationUsage()->addCommandLineOption( "--clip-pixels ","Causes all pixel values between min and max (inclusive)" " to be mapped to the null pixel value. Min and max can be equal for mapping a single value." " See also related option \"--replacement-mode\" for additional explanation."); argumentParser.getApplicationUsage()->addCommandLineOption( "--clip-to-valid-rect ","When true, any requested cut rect is clipped by the " "valid image bounding rect to minimize null border pixels. If false, the output will " "correspond to the cut rect as close as possible given the product projection. This option " "overrides the ossim_preferences setting. If no cut options are supplied, this option is " "ignored."); argumentParser.getApplicationUsage()->addCommandLineOption( "--combiner-template","Specify an external file that contains combiner information"); argumentParser.getApplicationUsage()->addCommandLineOption( "--combiner-type","Specify what mosaic to use, ossimImageMosiac or ossimFeatherMosaic or " "osimBlendMosaic ... etc"); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-bbox-en","Specify the min easting, min northing, max easting, max northing"); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-bbox-ll","Specify the min lat and min lon and max lat and maxlon " " "); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-center-ll","Specify the center cut in lat lon space. Takes two argument "); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-pixel-width-height","Specify cut box's width and height in pixels"); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-radius-meters","Specify the cut distance in meters. A bounding box for the cut will " "be produced"); argumentParser.getApplicationUsage()->addCommandLineOption( "--degrees","Specifies an override for degrees per pixel. Takes either a single value " "applied equally to x and y directions, or two values applied correspondingly to x then y."); argumentParser.getApplicationUsage()->addCommandLineOption( "--geo","Defaults to a geographic image chain with GSD = to the input. Origin of latitude is" "on the equator."); argumentParser.getApplicationUsage()->addCommandLineOption( "--geo-auto-scaled","Computes the mosaic center latitude for purpose of scaling in the " "longitude direction so that the pixels will appear nearly square in ground space at " "specified latitude. Implies a geographic projection."); argumentParser.getApplicationUsage()->addCommandLineOption( "--geo-scaled","Takes latitude as an argument for purpose of scaling in the " "longitude direction so that the pixels will appear nearly square in ground space at " "specified latitude. Implies a geographic projection."); argumentParser.getApplicationUsage()->addCommandLineOption( "--hist-auto-minmax","uses the automatic search for the best min and max clip values." " Incompatible with other histogram options."); argumentParser.getApplicationUsage()->addCommandLineOption( "--hist-match","Takes one image filename argument for target histogram to match." " Incompatible with other histogram options."); argumentParser.getApplicationUsage()->addCommandLineOption( "--hist-std-stretch","Specify histogram stretch as a standard deviation from the mean as" " , where is 1, 2, or 3." " Incompatible with other histogram options."); argumentParser.getApplicationUsage()->addCommandLineOption( "--hist-stretch","Specify in normalized percent the low clip and then the high clip value" " as ." " Incompatible with other histogram options."); argumentParser.getApplicationUsage()->addCommandLineOption( "--input-proj","Makes the view equal to the input. If more than one file then the first is " "taken"); argumentParser.getApplicationUsage()->addCommandLineOption( "--mask","Specify the ESRI shape file with polygons to clip the image"); argumentParser.getApplicationUsage()->addCommandLineOption( "--meters","Specifies an override for the meters per pixel. Takes either a single value " "applied equally to x and y directions, or two values applied correspondingly to x then y."); argumentParser.getApplicationUsage()->addCommandLineOption( "--no-cache","Excludes the cache from the input image chain(s). Necessary as a workaround " " for inconsistent cache behavior for certain image types."); argumentParser.getApplicationUsage()->addCommandLineOption( "--output-radiometry","Specifies the desired product's pixel radiometry type. Possible " "values are: U8, U11, U16, S16, F32. Note this overrides the deprecated option \"scale-to" "-8-bit\"."); argumentParser.getApplicationUsage()->addCommandLineOption( "--reader-prop","Passes a name=value pair to the reader(s) for setting it's property. Any " "number of these can appear on the line."); argumentParser.getApplicationUsage()->addCommandLineOption( "--replacement-mode ","Specify how to treat multi-band imagery when providing " "clip-pixels and/or clamp-pixels settings. Possible values are: REPLACE_BAND_IF_TARGET | " "REPLACE_BAND_IF_PARTIAL_TARGET | REPLACE_ALL_BANDS_IF_ANY_TARGET | " "REPLACE_ONLY_FULL_TARGETS."); argumentParser.getApplicationUsage()->addCommandLineOption( "--resample-type","Specify what resampler to use, nearest neighbor, bilinear, cubic"); argumentParser.getApplicationUsage()->addCommandLineOption( "--scale-to-8-bit","Scales the output to unsigned eight bits per band. This option has been" " deprecated by the newer \"--output-radiometry\" option."); argumentParser.getApplicationUsage()->addCommandLineOption( "--slave-buffers","number of slave tile buffers for mpi processing (default = 2)"); argumentParser.getApplicationUsage()->addCommandLineOption( "--srs","specify an output reference frame/projection. Example: --srs EPSG:4326"); argumentParser.getApplicationUsage()->addCommandLineOption( "--stdout","Output the image to standard out. This will return an error if writer does not " "support writing to standard out. Callers should combine this with the --ossim-logfile " "option to ensure output image stream does not get corrupted. You must still pass an output " "file so the writer type can be determined like \"dummy.png\"."); argumentParser.getApplicationUsage()->addCommandLineOption( "--supplementary-directory or --support","Specify the supplementary directory path where " "overviews, histograms and external geometries are located"); argumentParser.getApplicationUsage()->addCommandLineOption( "-t or --thumbnail", "thumbnail size"); argumentParser.getApplicationUsage()->addCommandLineOption( "--tiling-template","Specify an external file that contains tiling information"); argumentParser.getApplicationUsage()->addCommandLineOption( "--threads [n]","Indicates multi-threaded process using optionally-specified number of threads"); argumentParser.getApplicationUsage()->addCommandLineOption( "--utm","Defaults to a utm image chain with GSD = to the input"); argumentParser.getApplicationUsage()->addCommandLineOption( "--view-template","Specify an external file that contains view information"); argumentParser.getApplicationUsage()->addCommandLineOption( "-w or --writer","Specifies the output writer. Default uses output file extension to " "determine writer."); argumentParser.getApplicationUsage()->addCommandLineOption( "--wkt","specify an output reference frame/projection that is in a wkt format. Must have the" " ossimgdal_plugin compiled"); argumentParser.getApplicationUsage()->addCommandLineOption( "--writer-prop","Passes a name=value pair to the writer for setting it's property. Any " "number of these can appear on the line."); argumentParser.getApplicationUsage()->addCommandLineOption( "--writer-template","Specify an external file that contains tiling information"); } //************************************************************************************************* // Initializes this objects data members given the command line args //************************************************************************************************* void ossimOrthoIgen::initialize(ossimArgumentParser& argumentParser) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::initialize DEBUG:" << "Entered..... " << std::endl; } double tempDouble; double tempDouble2; double tempDouble3; double tempDouble4; ossimString tempString; unsigned int tempUint; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser::ossimParameter doubleParam(tempDouble); ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); ossimArgumentParser::ossimParameter doubleParam3(tempDouble3); ossimArgumentParser::ossimParameter doubleParam4(tempDouble4); ossimArgumentParser::ossimParameter uintParam(tempUint); theCutOriginType = ossimOrthoIgen::OSSIM_CENTER_ORIGIN; theCutOrigin.makeNan(); theCutDxDy.makeNan(); theCutOriginUnit = OSSIM_UNIT_UNKNOWN; theCutDxDyUnit = OSSIM_UNIT_UNKNOWN; theLowPercentClip = ossim::nan(); theHighPercentClip = ossim::nan(); double minX=ossim::nan(), minY=ossim::nan(), maxX=ossim::nan(), maxY=ossim::nan(); theUseAutoMinMaxFlag = false; theDeltaPerPixelOverride.makeNan(); theDeltaPerPixelUnit = OSSIM_UNIT_UNKNOWN; theCacheExcludedFlag = false; theClampPixelMin = ossim::nan(); theClampPixelMax = ossim::nan(); theClipPixelMin = ossim::nan(); theClipPixelMax = ossim::nan(); if(argumentParser.read("--annotate", stringParam)) { theAnnotationTemplate = ossimFilename(tempString); } if(argumentParser.read("-t", stringParam) || argumentParser.read("--thumbnail", stringParam)) { ossimString comma (","); if (tempString.contains(comma)) { theThumbnailSize.x = tempString.before(comma).toInt(); theThumbnailSize.y = tempString.after(comma).toInt(); } else { theThumbnailSize.x = tempString.toInt(); theThumbnailSize.y = 0; } theBuildThumbnailFlag = true; } theReaderProperties.clear(); while(argumentParser.read("--reader-prop", stringParam)) { std::vector splitArray; tempString.split(splitArray, "="); if(splitArray.size() == 2) { theReaderProperties.insert(std::make_pair(splitArray[0], splitArray[1])); } } if(argumentParser.read("-w", stringParam) || argumentParser.read("--writer", stringParam)) { theWriterType = tempString; } theWriterProperties.clear(); while(argumentParser.read("--writer-prop", stringParam)) { std::vector splitArray; tempString.split(splitArray, "="); if(splitArray.size() == 2) { theWriterProperties.insert(std::make_pair(splitArray[0], splitArray[1])); } } if(argumentParser.read("--slave-buffers", stringParam)) { theSlaveBuffers = tempString; } if(argumentParser.read("--cut-center-ll", doubleParam, doubleParam2)) { theCutOrigin.lat = tempDouble; theCutOrigin.lon = tempDouble2; theCutOriginUnit = OSSIM_DEGREES; theCutOriginType = ossimOrthoIgen::OSSIM_CENTER_ORIGIN; } if(argumentParser.read("--cut-radius-meters", doubleParam)) { theCutDxDy.x = tempDouble; theCutDxDy.y = tempDouble; theCutDxDyUnit = OSSIM_METERS; } if(argumentParser.read("--cut-bbox-ll", doubleParam, doubleParam2, doubleParam3, doubleParam4)) { minY = tempDouble; minX = tempDouble2; maxY = tempDouble3; maxX = tempDouble4; theCutOriginUnit = OSSIM_DEGREES; theCutOriginType = ossimOrthoIgen::OSSIM_UPPER_LEFT_ORIGIN; theCutOrigin.lat = maxY; theCutOrigin.lon = minX; theCutDxDy.lat = (maxY-minY); if ( (maxX < 0.0) && (minX >= 0.0) ) { //--- // Min is eastern hemisphere, max is western. Crossed the international date line. // Add 360 to make it positive. // // Note no check for just max < min here??? Perhaps throw exception.(drb) //--- maxX += 360.0; } theCutDxDy.lon = (maxX-minX); theCutDxDyUnit = OSSIM_DEGREES; } if(argumentParser.read("--cut-bbox-en", doubleParam, doubleParam2, doubleParam3, doubleParam4)) { minX = tempDouble; minY = tempDouble2; maxX = tempDouble3; maxY = tempDouble4; theCutOriginUnit = OSSIM_METERS; theCutOriginType = ossimOrthoIgen::OSSIM_UPPER_LEFT_ORIGIN; theCutOrigin.x = minX; theCutOrigin.y = maxY; theCutDxDy.x = (maxX-minX); theCutDxDy.y = (maxY-minY); theCutDxDyUnit = OSSIM_METERS; } if(argumentParser.read("--cut-pixel-width-height", doubleParam, doubleParam2)) { if((ossim::isnan(minX) == false)&& (ossim::isnan(minY) == false)&& (ossim::isnan(maxX) == false)&& (ossim::isnan(maxY) == false)) { theDeltaPerPixelOverride = ossimDpt(theCutDxDy.x/(tempDouble-1), theCutDxDy.y/(tempDouble2-1)); theDeltaPerPixelUnit = theCutDxDyUnit; } else { theCutOrigin.makeNan(); ossimNotify(ossimNotifyLevel_WARN) << "Can't have option --cut-pixel-width-height without --cut-bbox-ll" << std::endl; } } int num_params = argumentParser.numberOfParams("--degrees", doubleParam); if (num_params == 1) { argumentParser.read("--degrees", doubleParam); theDeltaPerPixelUnit = OSSIM_DEGREES; theDeltaPerPixelOverride.x = tempDouble; theDeltaPerPixelOverride.y = tempDouble; } else if (num_params == 2) { argumentParser.read("--degrees", doubleParam, doubleParam2); theDeltaPerPixelUnit = OSSIM_DEGREES; theDeltaPerPixelOverride.x = tempDouble; theDeltaPerPixelOverride.y = tempDouble2; } // The three histogram options are mutually exclusive: bool histo_op_selected = false; if(argumentParser.read("--hist-match", stringParam)) { ossimFilename target_image (tempString); histo_op_selected = true; // Check for histogram matching request and initialize for that: if (target_image.isReadable()) { // Establish target histogram file: theTargetHistoFileName = target_image; theTargetHistoFileName.setExtension("his"); if (!theTargetHistoFileName.isReadable()) { ossimNotify(ossimNotifyLevel_NOTICE)<<"Target histogram file <" << theTargetHistoFileName << "> not found. Cannot perform histogram matching." << std::endl; theTargetHistoFileName.clear(); } } } if(argumentParser.read("--hist-stretch", doubleParam, doubleParam2)) { if (histo_op_selected) { ossimNotify(ossimNotifyLevel_WARN) << "Cannot specify nore than one histogram operation. " " Ignoring --hist-stretch option." << std::endl; } else { theLowPercentClip = tempDouble; theHighPercentClip = tempDouble2; histo_op_selected = true; } } if(argumentParser.read("--hist-std-stretch", stringParam)) { if (histo_op_selected) { ossimNotify(ossimNotifyLevel_WARN) << "Cannot specify nore than one histogram operation. " " Ignoring --hist-stretch option." << std::endl; } else { theStdDevClip = tempString.toInt32(); histo_op_selected = true; if ((theStdDevClip < 1) || (theStdDevClip > 3)) { ossimNotify(ossimNotifyLevel_WARN) << "Invalid standard deviation value provided with" " --hist-std-stretch option. Only 1,2, or 3 allowed. Ignoring option."<< std::endl; } } } if(argumentParser.read("--hist-auto-minmax")) { if (histo_op_selected) { ossimNotify(ossimNotifyLevel_WARN) << "Cannot specify nore than one histogram operation. " " Ignoring --hist-auto-minmax option." << std::endl; } else theUseAutoMinMaxFlag = true; } num_params = argumentParser.numberOfParams("--meters", doubleParam); if (num_params == 1) { argumentParser.read("--meters", doubleParam); theDeltaPerPixelUnit = OSSIM_METERS; theDeltaPerPixelOverride.x = tempDouble; theDeltaPerPixelOverride.y = tempDouble; } else if (num_params == 2) { argumentParser.read("--meters", doubleParam, doubleParam2); theDeltaPerPixelUnit = OSSIM_METERS; theDeltaPerPixelOverride.x = tempDouble; theDeltaPerPixelOverride.y = tempDouble2; } if(argumentParser.read("--no-cache")) { theCacheExcludedFlag = true; } if(argumentParser.read("--output-radiometry", stringParam)) { theOutputRadiometry = tempString; } if(argumentParser.read("--scale-to-8-bit")) { if (theOutputRadiometry.empty()) theOutputRadiometry = "U8"; } if (argumentParser.read("--stdout")) { #if defined(_WIN32) // In Windows, cout is ASCII by default. // Let's change it over to binary mode. int result = _setmode( _fileno(stdout), _O_BINARY ); if( result == -1 ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::initialize WARNING:" << "\nCannot set standard output mode to binary." << std::endl; return; } #endif theStdoutFlag = true; } if(argumentParser.read("--writer-template", stringParam)) { theWriterTemplate = tempString; } if(argumentParser.read("--tiling-template", stringParam)) { theTilingTemplate = ossimFilename(tempString); } if(argumentParser.read("--chain-template", stringParam)) { theChainTemplate = ossimFilename(tempString); } if(argumentParser.read("--combiner-template", stringParam)) { theCombinerTemplate = ossimFilename(tempString); } theGeoScalingLatitude = ossim::nan(); if (argumentParser.read("--utm")) { theProjectionType = OSSIM_UTM_PROJECTION; theProjectionName = "ossimUtmProjection"; } else if(argumentParser.read("--geo")) { theProjectionType = OSSIM_GEO_PROJECTION; theProjectionName = "ossimEquDistCylProjection"; theGeoScalingLatitude = 0.0; } else if(argumentParser.read("--input-proj")) { theProjectionType = OSSIM_INPUT_PROJECTION; } else if (argumentParser.read("--srs", stringParam)) { theCrsString=tempString; theProjectionType = OSSIM_SRS_PROJECTION; } if(argumentParser.read("--view-template", stringParam)) { theTemplateView = ossimFilename(tempString); theProjectionType = OSSIM_EXTERNAL_PROJECTION; } if(argumentParser.read("--geo-scaled", doubleParam)) { theProjectionType = OSSIM_GEO_PROJECTION; theProjectionName = "ossimEquDistCylProjection"; if ( (tempDouble < 90.0) && (tempDouble > -90.0) ) { theGeoScalingLatitude = tempDouble; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::initialize WARNING:" << "\nLatitude out of range! Must be between -90 and 90." << std::endl; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::initialize DEBUG:" << "\ngeographicOriginOfLatitude: " << theGeoScalingLatitude << std::endl; } } if(argumentParser.read("--geo-auto-scaled")) { theProjectionType = OSSIM_GEO_PROJECTION; theProjectionName = "ossimEquDistCylProjection"; theGeoScalingLatitude = 999.0; // Flags computation of center lat for scaling } if(argumentParser.read("--combiner-type", stringParam)) theCombinerType = tempString; if(argumentParser.read("--resample-type", stringParam)) { theResamplerType = tempString; } if(argumentParser.read("--supplementary-directory", stringParam) || argumentParser.read("--support", stringParam)) { theSupplementaryDirectory = ossimFilename(tempString); } if (argumentParser.read("--clip-to-valid-rect", stringParam)) { theClipToValidRectFlag = tempString.toBool(); } if(argumentParser.read("--mask", stringParam)) { theMaskShpFile = tempString; } // Pixel flipper control options: if (argumentParser.read("--clip-pixels", doubleParam, doubleParam2)) { theClipPixelMin = tempDouble; theClipPixelMax = tempDouble2; } if (argumentParser.read("--clamp-pixels", doubleParam, doubleParam2)) { theClampPixelMin = tempDouble; theClampPixelMax = tempDouble2; } if (argumentParser.read("--replacement-mode", stringParam)) { thePixelReplacementMode = tempString; } // Threading: num_params = argumentParser.numberOfParams("--threads", uintParam); if (num_params == 0) // No param means system decides optimal thread count { argumentParser.read("--threads"); theThreadCount = 0; // Flags system-resolved } else if (num_params == 1) { argumentParser.read("--threads", uintParam); theThreadCount = (ossim_uint32) tempUint; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::initialize DEBUG:" << "Leaving..... " << std::endl; } } //************************************************************************************************* // Adds any file specifications to the files list //************************************************************************************************* void ossimOrthoIgen::addFiles(ossimArgumentParser& argumentParser, bool withDecoding, ossim_uint32 startIdx) { ossim_uint32 idx = startIdx; ossim_uint32 last_idx = argumentParser.argc()-1; while(argumentParser.argv()[idx] && (idx < last_idx)) { ossimString file_spec = argumentParser.argv()[idx]; if (file_spec.contains(".src")) { // input file spec provided via src file. Need to parse it: addSrcFile(ossimFilename(file_spec)); } else { // Filename with optional switches explicitly provided on command line: parseFilename(file_spec, withDecoding); } ++idx; } // The last filename left on the command line should be the product filename: theProductFilename = argumentParser.argv()[last_idx]; } //************************************************************************************************* // Performs the top-level management of image generation //************************************************************************************************* bool ossimOrthoIgen::execute() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::execute DEBUG: Entered ..." << std::endl; } // double start=0, stop=0; if(theSrcRecords.size() < 1) { ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::execute WARNING: No filenames to process" << std::endl; return false; } if (!theCrsString.empty() && !theProductFilename.empty()) { if ((theProductFilename.ext().upcase() == "KMZ" || theProductFilename.ext().upcase() == "KML") && theCrsString.upcase() != "EPSG:4326") { ossimNotify(ossimNotifyLevel_FATAL) << "ossimOrthoIgen::execute ERROR: Unsupported projection for kmz or kml" << std::endl; return false; } } //if(ossimMpi::instance()->getRank() == 0) //{ try { setupIgenChain(); } catch (const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << e.what() << std::endl; } throw; // re-throw exception } if (traceLog()) { generateLog(); } //} try { // theProductProjection->print(cout) << endl; outputProduct(); } catch(const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << e.what() << std::endl; } throw; // re-throw } return true; } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::clearFilenameList() { theSrcRecords.clear(); } //************************************************************************************************* // Parses the .src file specified in the command line. These contain an alternate specification // of input file and associated attributes as a KWL. //************************************************************************************************* void ossimOrthoIgen::addSrcFile(const ossimFilename& src_file) { if (!src_file.isReadable()) return; ossimKeywordlist src_kwl; src_kwl.setExpandEnvVarsFlag(true); if ( src_kwl.addFile(src_file) == false ) return; unsigned int image_idx = 0; // int entry = -1; // Loop to read all image file entries: double sum_weights = 0; while (true) { ossimSrcRecord src_record(src_kwl, image_idx++); if (!src_record.valid()) break; // Check for the presence of separate RGB file specs in this SRC record. This indicates // special processing. (comment added OLK 01/11) if (src_record.isRgbData()) { for (ossim_uint32 rgb_index = 0; rgb_index < 3; rgb_index++) { // This call creates another band-specific ossimSrcRecord that is pushed onto // theSrcRecords vector data member. (comment added OLK 01/11) if (parseFilename(src_record.getRgbFilename(rgb_index), true)) { // The parseFilename call pushes the R, G, or B band onto the back of theSrcRecords // vector. Set some additional attributes on this last entry. (OLK 01/11) theSrcRecords.back().setRgbDataBool(true); theSrcRecords.back().setHistogramOp(src_record.getRgbHistogramOp(rgb_index)); theSrcRecords.back().setHistogram(src_record.getRgbHistogramPath(rgb_index)); theSrcRecords.back().setOverview(src_record.getRgbOverviewPath(rgb_index)); } } } else { // Not RGB data, so treat as conventional image: (comment added OLK 01/11) theSrcRecords.push_back(src_record); sum_weights += src_record.getWeight(); //if the vector file exists, set the mosaic combiner type to ossimBlendMosaic if (src_record.isVectorData()) theCombinerType = "ossimBlendMosaic"; } } double max_weight = (sum_weights > 100.0 ? sum_weights : 100.0); double num_entries = (double)theSrcRecords.size(); double weight; vector::iterator iter = theSrcRecords.begin(); while (iter != theSrcRecords.end()) { if (sum_weights > 0.0) { // Somebody declared opacity, so need to share the remaining contributions among // other images: theCombinerType = "ossimBlendMosaic"; if (iter->getWeight() == 0.0) { // No weight has been assigned for this image, so use default remaining partial if (num_entries == 1.0) weight = 1.0; // This is the only image, so full weight else { // share remaining contributions: weight = (1.0 - sum_weights/max_weight)/(num_entries - 1); if (weight < 0.01) weight = 0.01; } } else { // An opacity value was specified for this weight = iter->getWeight()/max_weight; } } else { // No opacity values were specified, so simply use the default equal share. Note that the // mosaic may not even be of type ossimBlendMosaic: weight = 100.0/num_entries; // default if no opacity specified } iter->setWeight(weight); iter++; } } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::setDefaultValues() { theBuildThumbnailFlag = false; theDeltaPerPixelUnit = OSSIM_UNIT_UNKNOWN; theDeltaPerPixelOverride.makeNan(); theTemplateView = ""; theProjectionType = OSSIM_UNKNOWN_PROJECTION; theGeoScalingLatitude = ossim::nan(); theCombinerType = "ossimImageMosaic"; theResamplerType = "nearest neighbor"; theTilingTemplate = ""; theTilingFilename = ""; theSupplementaryDirectory = ""; theSlaveBuffers = "2"; clearFilenameList(); theLowPercentClip = ossim::nan(); theHighPercentClip = ossim::nan(); theCutOrigin.makeNan(); theCutDxDy.makeNan(); theCutOriginUnit = OSSIM_UNIT_UNKNOWN; theCutDxDyUnit = OSSIM_UNIT_UNKNOWN; // PIXEL_IS_AREA HACK -- Set the assumed pixel alignment type to "area". Upon the first occurrence // of a pixel-is-point entry, this property will revert to point. THIS NEEDS TO BE // REMOVED WHEN THE EW GUI PROVIDES FOR THE USER TO SET THIS PROPERTY (OLK 09/11): thePixelAlignment = OSSIM_PIXEL_IS_AREA; // not a default, but necessary for later logic } //************************************************************************************************* // Initializes the processing chain from the information on the command line //************************************************************************************************* void ossimOrthoIgen::setupIgenChain() { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimOrthoIgen::setupIgenChain DEBUG: Entered ..."<< std::endl; setupTiling(); if (theSlaveBuffers == "") theNumberOfTilesToBuffer = 2; else theNumberOfTilesToBuffer = theSlaveBuffers.toLong(); if(theProductFilename.empty()) throw(ossimException(std::string("Must supply an output file."))); // Create the output mosaic object, to be connected to its inputs later: ossimKeywordlist templateKwl; templateKwl.clear(); ossimRefPtr mosaicObject = 0; ossimRefPtr bandMergeObject = 0; if(theCombinerTemplate.exists()) { templateKwl.addFile(theCombinerTemplate); mosaicObject = PTR_CAST(ossimImageCombiner, ossimObjectFactoryRegistry::instance()->createObject(templateKwl)); } if (!mosaicObject.valid()) { mosaicObject = PTR_CAST(ossimImageCombiner, ossimObjectFactoryRegistry::instance()->createObject(theCombinerType)); if(!mosaicObject.valid()) { mosaicObject = PTR_CAST(ossimImageMosaic, ossimObjectFactoryRegistry::instance()-> createObject(ossimString("ossimImageMosaic"))); } } // Keep this pointer around for special processing if blend mosaic: ossimBlendMosaic* obm = PTR_CAST(ossimBlendMosaic, mosaicObject.get()); // An orthomosaic implies that all input images are already orthorectified to a common projection // so the input chains do not require a renderer: bool orthoMosaic = (PTR_CAST(ossimOrthoImageMosaic, mosaicObject.get()) != 0); // Establish default individual input chain from template, if any: templateKwl.clear(); ossimRefPtr default_single_image_chain = 0; if(theChainTemplate.exists()) { templateKwl.addFile(theChainTemplate); ossimObject* obj = 0; if(templateKwl.find("type")) obj = ossimObjectFactoryRegistry::instance()->createObject(templateKwl); else if(templateKwl.find("object1.type")) obj = ossimObjectFactoryRegistry::instance()->createObject(templateKwl, "object1."); default_single_image_chain = PTR_CAST(ossimImageChain, obj); } if(!default_single_image_chain.valid()) // then create a default rendering chain { default_single_image_chain = new ossimImageChain; { // Only need a renderer if an output projection or an explicit GSD was specified. if(!orthoMosaic) { ossimImageRenderer* renderer = new ossimImageRenderer; if (renderer->getResampler()) renderer->getResampler()->setFilterType(theResamplerType); default_single_image_chain->addChild(renderer); } } } ossim_uint32 num_inputs = (ossim_uint32)theSrcRecords.size(); ossim_uint32 idx; ossimString prefix ("object1.object"); theReferenceProj = 0; // Loop over each input image file to establish a single image chain that will be added to the // output mosaic: ossimImageSource* current_source = 0; for(idx = 0; idx < num_inputs; ++idx) { // first lets add an input handler to the chain: ossimFilename input = theSrcRecords[idx].getFilename(); ossimRefPtr handler = ossimImageHandlerRegistry::instance()->open(input); if(!handler.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "Could not open input file <" << input << ">. " << "Skipping this entry." << std::endl; continue; } // Pass on any reader properties if there are any. ossimPropertyInterface* propInterface = (ossimPropertyInterface*)handler.get(); PropertyMap::iterator iter = theReaderProperties.begin(); while(iter != theReaderProperties.end()) { propInterface->setProperty(iter->first, iter->second); ++iter; } // Presently, handler->loadState() is called only on vector data, though in the future we // should stuff many of the members in ossimSrcRecord in a KWL (similar to what is currently // done with vector properties) so that the handler is initialized via loadState() instead of // individual calls to set methods. OLK 10/10 if (theSrcRecords[idx].isVectorData()) handler->loadState(theSrcRecords[idx].getAttributesKwl()); std::vector entryList; if(theSrcRecords[idx].getEntryIndex() > -1 ) entryList.push_back(theSrcRecords[idx].getEntryIndex()); else handler->getEntryList(entryList); // Input image file may have multiple entries. Loop over each and establish single image // chains for each: ossim_uint32 entryIdx = 0; for(entryIdx = 0; entryIdx < entryList.size(); ++entryIdx) { // Instantiate the chain for one input image source. Copy existing default chain // which may already possess a renderer (so don't do any addFirst()!): ossimImageChain* singleImageChain = (ossimImageChain*) default_single_image_chain->dup(); // Establish the image handler for this particular frame. This may be just // the handler already opened in the case of single image per file: ossimImageHandler* img_handler = 0; if (entryList.size() == 1) img_handler = handler.get(); else img_handler = (ossimImageHandler*)handler->dup(); // The user can specify an external "support" (a.k.a. supplementary directory) several ways if ( theSupplementaryDirectory.empty() == false ) { img_handler->setSupplementaryDirectory( theSupplementaryDirectory ); } else if (theSrcRecords[idx].getSupportDir().empty() == false) { img_handler->setSupplementaryDirectory(theSrcRecords[idx].getSupportDir()); } else if (theSrcRecords[idx].getOverviewPath().empty() == false) { if (theSrcRecords[idx].getOverviewPath().isDir()) img_handler->setSupplementaryDirectory(theSrcRecords[idx].getOverviewPath()); else img_handler->setSupplementaryDirectory(theSrcRecords[idx].getOverviewPath().path()); } img_handler->setCurrentEntry(entryList[entryIdx]); if ( img_handler->hasOverviews() ) { img_handler->openOverview(); } if (theSrcRecords[idx].isRgbData() && theSrcRecords[idx].getBands().size() > 0 && theSrcRecords[idx].getOverviewPath().empty()) { img_handler->setOutputBandList(theSrcRecords[idx].getBands()); } // Image handler is ready to insert on the input side of the chain: singleImageChain->addLast(img_handler); current_source = img_handler; // PIXEL_IS_AREA HACK -- Scan the pixel alignment to see if all inputs are "area", // in which case we override the command-line writer property setting. THIS NEEDS TO BE // REMOVED WHEN THE EW GUI PROVIDES FOR THE USER TO SET THIS PROPERTY (OLK 09/11): if (img_handler->getPixelType() == OSSIM_PIXEL_IS_POINT) thePixelAlignment = OSSIM_PIXEL_IS_POINT; // This call will check for the presence of a raster mask file alongside the image, // and insert the mask filter in the chain if present: current_source = setupRasterMask(singleImageChain, theSrcRecords[idx]); // If this is the first input chain, use it as the reference projection to help with // the instantiation of the product projection (the view): if (!theReferenceProj.valid()) { ossimRefPtr geom = img_handler->getImageGeometry(); if ( geom.valid() ) theReferenceProj = geom->getProjection(); } // Insert a partial-pixel flipper to remap null-valued pixels to min. // This is set via preference keyword "orthoigen.flip_null_pixels" current_source = setupPixelFlipper(singleImageChain, theSrcRecords[idx]); // Install a band selector if needed: if (theSrcRecords[idx].getBands().size() && (img_handler->getNumberOfOutputBands() > 1)) { ossim_uint32 bands = img_handler->getNumberOfOutputBands(); bool validBand = true; for (ossim_uint32 i = 0; i < theSrcRecords[idx].getBands().size(); ++i) { if (theSrcRecords[idx].getBands()[i] >= bands) { validBand = false; ossimNotify(ossimNotifyLevel_FATAL) << " ERROR:" << "\nBand list range error!" << "\nHighest available band: " << bands << std::endl; } } if (validBand) { ossimRefPtr bs = new ossimBandSelector(); singleImageChain->insertRight(bs.get(), current_source); bs->setOutputBandList(theSrcRecords[idx].getBands()); current_source = bs.get(); } } // Install a histogram object if needed. This inserts just to the left of the resampler. setupHistogram(singleImageChain, theSrcRecords[idx]); // Add a cache just to the left of the resampler. if (!theCacheExcludedFlag) addChainCache(singleImageChain); // Add the single image chain to the mosaic and save it to the product spec file: singleImageChain->makeUniqueIds(); if (theSrcRecords[idx].isRgbData()) { if (!bandMergeObject) { bandMergeObject = new ossimBandMergeSource(); } bandMergeObject->connectMyInputTo(singleImageChain); singleImageChain->changeOwner(bandMergeObject.get()); } else { mosaicObject->connectMyInputTo(singleImageChain); singleImageChain->changeOwner(mosaicObject.get()); } //theContainer->addChild(singleImageChain); // Set the weight for this image when doing a blend mosaic: if (obm) obm->setWeight(idx, theSrcRecords[idx].getWeight()); } } // Finished initializing the inputs to the mosaic. Add the mosaic to the product chain. theProductChain = new ossimImageChain; if (bandMergeObject) { theProductChain->addFirst(bandMergeObject.get()); } theProductChain->addFirst(mosaicObject.get()); // Now need to pass the product chain through the histogram setup for possible remapper given // target histogram (used when histo-matching selected): setupHistogram(); // When mosaicking common input projections without rendering each, need to add a renderer to the // mosaic for reprojecting to output projection: if(orthoMosaic) { ossimImageRenderer* renderer = new ossimImageRenderer; renderer->getResampler()->setFilterType(theResamplerType); theProductChain->addFirst(current_source); } //--- // Now that "theProductChain" is initialized we must initialize elevation if needed as it can // affect the tie point of the output projection. //--- if ( isAffectedByElevation() ) { ossimInit::instance()->initializeElevation(); // Chain gsd's affected by elevation so recompute. reComputeChainGsds(); } // Set up the output product's projection: setupProjection(); // Annotation setup... setupAnnotation(); // Output rect cutter: setupCutter(); // Output radiometry filter: setupOutputRadiometry(); // After all the connections have been established, add the product chain to the overall // product container. This container will also hold the writer object. theContainer->addChild(theProductChain.get()); // Lastly, set up the write object (object2): setupWriter(); } //************************************************************************************************* // Initializes the Cut Rect filter to crop the mosaic to specified rectangle. // This method assumes that the view (theProductProjection) has already been propagated to all // the renderers (via call to setView()). This was done by prior call to setupProjection(). //************************************************************************************************* void ossimOrthoIgen::setupCutter() { // The command line accepts cut rect specification in several formats. Consolidate them to // a common form (UL tiepoint and distance to LR pixel center . This // method also updates the product projection with new bounds: consolidateCutRectSpec(); ossimImageSource* input_source = theProductChain->getFirstSource(); if((theCutDxDy.hasNans()&&theMaskShpFile.empty())||!theProductProjection.valid()||!input_source) return; //user may pass the shape filename with an query (e.g C:/myshp.shp|select * from myshp), //parse the name of mask shape file here ossimString query = ""; if (!theMaskShpFile.empty()) { if (theMaskShpFile.contains("|")) { ossimString fileName = theMaskShpFile; std::vector fileList = fileName.split("|"); if (fileList.size() > 1) { theMaskShpFile = fileList[0]; query = fileList[1]; } } } if (!theMaskShpFile.exists()) { if (theCutOriginUnit == OSSIM_METERS) // projection in meters... { ossimEastingNorthingCutter* cutter = new ossimEastingNorthingCutter; ossimDpt mpp (theProductProjection->getMetersPerPixel()); ossimDpt lr (theCutOrigin.x + theCutDxDy.x - mpp.x, theCutOrigin.y - theCutDxDy.y + mpp.y); cutter->setView(theProductProjection.get()); cutter->setEastingNorthingRectangle(theCutOrigin, lr); theProductChain->addFirst(cutter); } else // geographic projection, units = decimal degrees. { ossimGeoPolyCutter* cutter = new ossimGeoPolyCutter; std::vector polygon; ossimDpt dpp (theProductProjection->getDecimalDegreesPerPixel()); ossimGpt ul(theCutOrigin.lat, theCutOrigin.lon ); ossimGpt ur(theCutOrigin.lat, theCutOrigin.lon + theCutDxDy.x - dpp.x); ossimGpt lr(theCutOrigin.lat - theCutDxDy.y + dpp.y, theCutOrigin.lon + theCutDxDy.x - dpp.x); ossimGpt ll(theCutOrigin.lat - theCutDxDy.y + dpp.y, theCutOrigin.lon ); polygon.push_back(ul); polygon.push_back(ur); polygon.push_back(lr); polygon.push_back(ll); cutter->setView(theProductProjection.get()); cutter->setNumberOfPolygons(1); cutter->setPolygon(polygon); theProductChain->addFirst(cutter); } } else { ossimIrect inputRect = input_source->getBoundingRect(); ossimGeoPolyCutter* exteriorCutter = new ossimGeoPolyCutter; exteriorCutter->setView(theProductProjection.get()); ossimGeoPolyCutter* interiorCutter = NULL; ossimRefPtr shpHandler = ossimImageHandlerRegistry::instance()->open(theMaskShpFile); ossimEsriShapeFileInterface* shpInterface = PTR_CAST(ossimEsriShapeFileInterface, shpHandler.get()); if (shpInterface != NULL) { if (!query.empty()) { shpInterface->setQuery(query); } std::multimap features = shpInterface->getFeatureTable(); if (features.size() > 0) { std::multimap::iterator it = features.begin(); while (it != features.end()) { ossimAnnotationObject* anno = it->second; if (anno != NULL) { ossimGeoAnnotationPolyObject* annoPoly = PTR_CAST(ossimGeoAnnotationPolyObject, anno); ossimGeoAnnotationMultiPolyObject* annoMultiPoly = NULL; if (annoPoly == NULL) { annoMultiPoly = PTR_CAST(ossimGeoAnnotationMultiPolyObject, anno); } if (annoPoly != NULL) { std::vector polygon; //get the points of a polygon std::vector points = annoPoly->getPoints(); for (ossim_uint32 i = 0; i < points.size(); i++) { polygon.push_back(points[i]); } //get polygon type, if it is an internal polygon, initialize the internal cutter ossimGeoAnnotationPolyObject::ossimPolyType polyType = annoPoly->getPolyType(); if (polyType == ossimGeoAnnotationPolyObject::OSSIM_POLY_INTERIOR_RING) { if (interiorCutter == NULL) { interiorCutter = new ossimGeoPolyCutter; interiorCutter->setView(theProductProjection.get()); interiorCutter->setCutType(ossimPolyCutter::OSSIM_POLY_NULL_INSIDE); } interiorCutter->addPolygon(polygon); } else { exteriorCutter->addPolygon(polygon); } } else if (annoMultiPoly != NULL) { std::vector multiPolys = annoMultiPoly->getMultiPolygon(); for (ossim_uint32 i = 0; i < multiPolys.size(); i++) { ossimGeoPolygon geoPoly = multiPolys[i]; std::vector holePolys = geoPoly.getHoleList(); if (holePolys.size() > 0) { if (interiorCutter == NULL) { interiorCutter = new ossimGeoPolyCutter; interiorCutter->setView(theProductProjection.get()); interiorCutter->setCutType(ossimPolyCutter::OSSIM_POLY_NULL_INSIDE); } for (ossim_uint32 j = 0; j < holePolys.size(); j++) { interiorCutter->addPolygon(holePolys[j]); } } exteriorCutter->addPolygon(multiPolys[i]); } } else { throw(ossimException(std::string("The geometry type of the mask shape file is not polygon."))); } } it++; } } } //if user define the cut box, add it to the image chain ossimGeoPolyCutter* boundCutter = NULL; if (!theCutDxDy.hasNans() && !theCutOrigin.hasNans()) { std::vector bound; if (theCutOriginUnit == OSSIM_METERS) { ossimDpt mpp (theProductProjection->getMetersPerPixel()); ossimGpt ul = theProductProjection->inverse(ossimDpt(theCutOrigin.x, theCutOrigin.y)); ossimGpt ur = theProductProjection->inverse(ossimDpt(theCutOrigin.x + theCutDxDy.x - mpp.x, theCutOrigin.y)); ossimGpt lr = theProductProjection->inverse(ossimDpt(theCutOrigin.x + theCutDxDy.x - mpp.x, theCutOrigin.y - theCutDxDy.y + mpp.y)); ossimGpt ll = theProductProjection->inverse(ossimDpt(theCutOrigin.x, theCutOrigin.y - theCutDxDy.y + mpp.y)); bound.push_back(ul); bound.push_back(ur); bound.push_back(lr); bound.push_back(ll); } else { ossimDpt dpp (theProductProjection->getDecimalDegreesPerPixel()); ossimGpt ul(theCutOrigin.lat, theCutOrigin.lon ); ossimGpt ur(theCutOrigin.lat, theCutOrigin.lon + theCutDxDy.x - dpp.x); ossimGpt lr(theCutOrigin.lat - theCutDxDy.y + dpp.y, theCutOrigin.lon + theCutDxDy.x - dpp.x); ossimGpt ll(theCutOrigin.lat - theCutDxDy.y + dpp.y, theCutOrigin.lon ); bound.push_back(ul); bound.push_back(ur); bound.push_back(lr); bound.push_back(ll); } boundCutter = new ossimGeoPolyCutter; boundCutter->setView(theProductProjection.get()); boundCutter->setNumberOfPolygons(1); boundCutter->setPolygon(bound); } if (boundCutter == NULL) { ossimIrect shpRect = shpHandler->getBoundingRect(); if (shpRect.width() > inputRect.width() && shpRect.height() > inputRect.height()) { exteriorCutter->setRectangle(inputRect); } } theProductChain->addFirst(exteriorCutter); if (interiorCutter != NULL) { theProductChain->addFirst(interiorCutter); } if (boundCutter != NULL) { theProductChain->addFirst(boundCutter); } } } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::setupWriter() { if (!theProductChain.valid()) return; ossimRefPtr writer = 0; if (theWriterType.size()) { // User selected writer with -w or --writer option. writer = ossimImageWriterFactoryRegistry::instance()->createWriter(theWriterType); } else if ( theWriterTemplate.size() && theWriterTemplate.exists() ) { // User sent us a writer template. ossimKeywordlist kwlTemplate; kwlTemplate.addFile(theWriterTemplate); // Try first with no prefix. writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwlTemplate); if ( !writer.valid() ) writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwlTemplate, "object2."); } else if ( theTilingFilename == "%SRTM%") { ossimKeywordlist kwlWriter; kwlWriter.add("type", "ossimGeneralRasterWriter", true); kwlWriter.add("byte_order", "big_endian"); writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwlWriter); theProductFilename = theProductFilename.path(); } else if (!theTilingFilename.empty()) { if (theProductFilename.isDir()) { theProductFilename = theProductFilename + "/" + theTilingFilename; } } try { //--- // Set the output file name if not already set. // NOTE: Could be outputing to stdout in which case outputFilename does not // make sense. Leaving here though to not break code downstream. (drb) //--- if ( theProductFilename == ossimFilename::NIL ) { throw(ossimException(std::string("Writer output filename not set."))); } //--- // Final check for writer. //--- if ( !writer.valid() ) { // Derive writer from the extension. ossimFilename ext = theProductFilename.ext(); if ( ext.size() ) writer = ossimImageWriterFactoryRegistry::instance()->createWriterFromExtension(ext); //--- // Lastly default to tiff. Perhaps throw exception here instead. (drb) //--- if( !writer.valid() ) { writer = new ossimTiffWriter; theProductFilename.setExtension("tif"); } } // PIXEL_IS_AREA HACK: Temporary patch to override command line alignment type with source // image's alignment type. TO BE REMOVED ONCE EW GUI PROVIDES FOR USER-SETTING OF THIS // PROPERTY (OLK 09/11): if (thePixelAlignment == OSSIM_PIXEL_IS_AREA) { ossimString pixelType ("pixel_type"); theWriterProperties.erase(pixelType); theWriterProperties.insert(std::make_pair(pixelType, ossimString("area"))); } //--- // Set writer filename, connect and add to writer to keyword list. //--- if ( writer.valid() ) { writer->setFilename(theProductFilename); writer->connectMyInputTo(0, theProductChain.get()); ossimPropertyInterface* propInterface = (ossimPropertyInterface*)writer.get(); PropertyMap::iterator iter = theWriterProperties.begin(); while(iter != theWriterProperties.end()) { propInterface->setProperty(iter->first, iter->second); ++iter; } theContainer->addChild(writer.get()); } else { throw(ossimException(std::string("Unable to create writer."))); } } catch (const ossimException& e) { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << e.what() << std::endl; throw; // re-throw exception } } //************************************************************************************************* // This method establishes the output (view) projection of the product. // NOTE: Completely rewritten to simplify and reduce redundancy. OLK 3/10 //************************************************************************************************* void ossimOrthoIgen::setupProjection() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<<"Entering ossimOrthoIgen::setupProjection():"< productObj = ofr->createObject(templateKwl, "product.projection."); if(!productObj.valid()) productObj = ofr->createObject(templateKwl); theProductProjection = PTR_CAST(ossimMapProjection, productObj.get()); } // Geographic? (Assuming WGS 84 for now.) else if (theProjectionType == OSSIM_GEO_PROJECTION) { theProductProjection = new ossimEquDistCylProjection(); ossimGpt gpt(0.0, 0.0); if (theGeoScalingLatitude == 999.0) // flags that lat is to be computed { computeGeoScalingLatitude(); gpt = ossimGpt(theGeoScalingLatitude, 0.0); } else if (!ossim::isnan(theGeoScalingLatitude)) gpt = ossimGpt(theGeoScalingLatitude, 0.0); theProductProjection->setOrigin(gpt); } // CRS code specified on the command line else if (theProjectionType == OSSIM_SRS_PROJECTION) { ossimProjection* base_proj = ossimEpsgProjectionFactory::instance()->createProjection(theCrsString); theProductProjection = PTR_CAST(ossimMapProjection, base_proj); if(theProductProjection.valid()) { // Reassign the type for geographic. Now we know if (theProductProjection->isGeographic()) { theProjectionType = OSSIM_GEO_PROJECTION; ossimGpt gpt(0.0, 0.0); if (!ossim::isnan(theGeoScalingLatitude)) gpt = ossimGpt(theGeoScalingLatitude, 0.0); theProductProjection->setOrigin(gpt); } } else { theProjectionType = OSSIM_UNKNOWN_PROJECTION; ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::setupProjection() WARNING:" << " Unsupported spatial reference system." << " Will default to the projection from the input image." << std::endl; } } // UTM? else if (theProjectionType == OSSIM_UTM_PROJECTION) { ossimUtmProjection* utm = new ossimUtmProjection; ossimGpt refGpt; theReferenceProj->lineSampleToWorld(ossimDpt(0,0), refGpt); utm->setZone(refGpt); utm->setHemisphere(refGpt); theProductProjection = utm; } // None of the above? else { // Either OSSIM_INPUT_PROJECTION or OSSIM_UNKNOWN_PROJECTION. In both cases // just use the first image's input projection for the output. Need to make // sure the input_proj is a map projection though: if (ref_map) { theProductProjection = PTR_CAST(ossimMapProjection, ref_map->dup()); theProjectionType = OSSIM_INPUT_PROJECTION; // just in case it was unknown before } else { theProjectionType = OSSIM_GEO_PROJECTION; theProductProjection = new ossimEquDistCylProjection(); ossimGpt gpt(0.0, 0.0); if (!ossim::isnan(theGeoScalingLatitude)) gpt = ossimGpt(theGeoScalingLatitude, 0.0); theProductProjection->setOrigin(gpt); } } // At this point there should be a valid output projection defined: if (!theProductProjection.valid()) { std::string errMsg = "ossimOrthoIgen::setupProjection() -- Could not establish valid output " "projection"; throw(ossimException(errMsg)); } // HACK (OLK 06/10): The projection may not have had the PCS code initialized even though it // is an EPSG projection, so take this opportunity to identify a PCS for output: ossim_uint32 pcs_code = theProductProjection->getPcsCode(); if (pcs_code == 0) { pcs_code = ossimEpsgProjectionDatabase::instance()-> findProjectionCode(*(theProductProjection.get())); theProductProjection->setPcsCode(pcs_code); } // Bootstrap the process of establishing the mosaic tiepoint by setting it to the reference proj. if (ref_map) theProductProjection->setUlGpt(ref_map->getUlGpt()); // cout << "ref_map->getUlGpt(): " << ref_map->getUlGpt() << endl; // Base class makes sure the product view projection is properly wired into the chain. setView(); // Set the desired image GSD. This is nontrivial due to the many ways GSD can be implied and/or // explicitly provided. This method also does a setView before returning: setProductGsd(); theProjectionName = theProductProjection->getProjectionName(); // At this point, the product projection will not have a tiepoint (UL corner coordinates) // defined unless it is the same projection as the input reference. Need to set it now. Note that // if a cut-rect is specified, the tie-point will be modified later in setupCutter() establishMosaicTiePoint(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::setupProjection DEBUG:" << "Leaving...." << __LINE__ << std::endl; } } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::setupAnnotation() { ossimImageSource* input_source = theProductChain->getFirstSource(); if (!input_source) return; if(theAnnotationTemplate.exists() == false) return; ossimKeywordlist templateKwl; if (templateKwl.addFile(theAnnotationTemplate) == false) return; ossimRefPtr obj = ossimObjectFactoryRegistry::instance()-> createObject(templateKwl, "object1."); if (obj.valid()) { ossimGeoAnnotationSource* oga = PTR_CAST(ossimGeoAnnotationSource, obj.get()); if (oga) { if (theProductProjection.valid()) oga->setGeometry(new ossimImageGeometry(0, theProductProjection.get())); theProductChain->addFirst(oga); } } return; } //************************************************************************************************* // Set up multi-file tiling if indicated on the command line. //************************************************************************************************* bool ossimOrthoIgen::setupTiling() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimOrthoIgen::setupTiling: Entered......" << std::endl; } ossimKeywordlist templateKwl; ossimFilename outputFilename = theProductFilename; theTilingEnabled = false; if ((theTilingTemplate == "")||(!templateKwl.addFile(theTilingTemplate))) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimOrthoIgen::setupTiling: Leaving......" << __LINE__ << std::endl; } return false; } ossimString prefix ("igen.tiling."); while (1) { if(outputFilename.isDir()) { if(templateKwl.find(prefix.chars(), "type")) { theTilingFilename = templateKwl.find(prefix.chars(),"tile_name_mask"); theTilingEnabled = true; break; } else if (templateKwl.find(prefix.chars(), "tile_size") || templateKwl.find(prefix.chars(), "tile_source")) { theTilingFilename = templateKwl.find(prefix.chars(),"output_file_name"); theTilingEnabled = true; break; } } else { theTilingFilename = outputFilename.file(); if (!theTilingFilename.contains("%")) { ossimString fileNoExt = theTilingFilename.fileNoExtension(); ossimString ext = theTilingFilename.ext(); theTilingFilename = fileNoExt + "_%r%_%c%." + ext; } if(templateKwl.find(prefix.chars(), "type")) { templateKwl.add(prefix.chars(), "tile_name_mask", theTilingFilename.c_str(), true); ossimFilename path (outputFilename.path()); theProductFilename = path; theTilingEnabled = true; break; } else if (templateKwl.find(prefix.chars(), "tile_size") || templateKwl.find(prefix.chars(), "tile_source")) { templateKwl.add(prefix.chars(), "output_file_name", theTilingFilename.c_str(), true); ossimFilename path (outputFilename.path()); theProductFilename = path; theTilingEnabled = true; break; } } // If we got here, then no matches were found in the template. Try again but without a prefix: if (prefix.empty()) break; prefix.clear(); } // Initialize the tiling object if enabled: if (templateKwl.find(prefix.chars(), "tile_size")) { theTiling = 0; theTiling = new ossimTilingRect; } if (templateKwl.find(prefix.chars(), "tile_source")) { theTiling = 0; theTiling = new ossimTilingPoly; } if (theTilingEnabled && !theTiling->loadState(templateKwl, prefix)) theTilingEnabled = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::setupTiling: templateKwl = \n" << templateKwl << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimOrthoIgen::setupTiling: Leaving......" << __LINE__ << std::endl; } return true; } //************************************************************************************************* // Consolidates specification of bounding rect given various ways of specifying on the command // line. This avoids multiple, redundant checks scattered throughout the code. On exit: // // 1. theCutOriginType is converted to OSSIM_UPPER_LEFT_ORIGIN // 2. theCutOrigin is converted to the proper coordinates (lat/lon or easting/northing) and // associated theCutOriginUnits is assigned accordingly. // 3. theCutDxDy reflects the full size of the rect, in the units corresponding to the projection // and associated theCutDxDyUnit is set to METERS for UTM, DEGREES for geographic // 4. The product projection's origin (image center) and tie point are updated to reflect the // output rectangle. // //************************************************************************************************* void ossimOrthoIgen::consolidateCutRectSpec() { if (!theProductProjection.valid() || theCutDxDy.hasNans() || theCutOrigin.hasNans()) return; if ((theCutDxDyUnit != OSSIM_METERS) && (theCutDxDyUnit != OSSIM_DEGREES) && (theCutDxDyUnit != OSSIM_UNIT_UNKNOWN)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::consolidateCutRectSpec: An unhandled" " type of units was encountered. The cut rect needs to be specified in either meters or" " degrees. The resulting cut rect and origin may be incorrect." << std::endl; return; } ossimGpt originPLH; ossimDpt resolution; // Geographic Projection (lat/lon cut rect) requested? if(theProductProjection->isGeographic()) { // geographic projection; units need to be decimal degrees. First check for consistent origin: if (theCutOriginUnit == OSSIM_METERS) { originPLH = theProductProjection->inverse(theCutOrigin); theCutOrigin.x = originPLH.lon; theCutOrigin.y = originPLH.lat; } else { originPLH.lat = theCutOrigin.y; originPLH.lon = theCutOrigin.x; } // Check for consistent rect size: if (theCutDxDyUnit == OSSIM_METERS) { ossimDpt mtrs_per_deg (originPLH.metersPerDegree()); theCutDxDy.x = theCutDxDy.x/mtrs_per_deg.x; theCutDxDy.y = theCutDxDy.y/mtrs_per_deg.y; } // Set these to the correct units. May already be correct, but just in case... theCutOriginUnit = OSSIM_DEGREES; theCutDxDyUnit = OSSIM_DEGREES; if (theClipToValidRectFlag) { // Now we need to clip the cut rect by the valid image footprint for the entire mosaic: ossimDrect boundingRect = theProductChain->getBoundingRect(); // in view coordinates // The bounding rect is in image space. Since pixel-is-point, the actual valid area on the // ground will extend 1/2 pixel beyond the centers, so grow the bounding rect by 1/2 p: boundingRect.expand(ossimDpt(0.5, 0.5)); ossimGpt mosaic_ul, mosaic_lr; theProductProjection->lineSampleHeightToWorld(boundingRect.ul(), 0, mosaic_ul); theProductProjection->lineSampleHeightToWorld(boundingRect.lr(), 0, mosaic_lr); // Establish the LR bound defined by the cut-rect and clip the cut-rect if necessary: ossimGpt cutrect_lr (theCutOrigin.lat - theCutDxDy.lat, theCutOrigin.lon + theCutDxDy.lon); if (mosaic_ul.lat < theCutOrigin.lat) theCutOrigin.lat = mosaic_ul.lat; if (mosaic_lr.lat > cutrect_lr.lat) theCutDxDy.lat = theCutOrigin.lat - mosaic_lr.lat; if (mosaic_ul.lon > theCutOrigin.lon) theCutOrigin.lon = mosaic_ul.lon; if (mosaic_lr.lon < cutrect_lr.lon) theCutDxDy.lon = mosaic_lr.lon - theCutOrigin.lon; } resolution = theProductProjection->getDecimalDegreesPerPixel(); } // Map Projection (easting, northing cut rect) requested? else { // Special case code to account for origin and delta being specified in geographic, leading to // offset error due to northing difference between UL and UR corners at constant lat: if ((theCutOriginType == OSSIM_UPPER_LEFT_ORIGIN) && (theCutOriginUnit == OSSIM_DEGREES) && (theCutDxDyUnit == OSSIM_DEGREES)) { ossimGpt ulgp (theCutOrigin.lat , theCutOrigin.lon , 0); ossimGpt urgp (theCutOrigin.lat , theCutOrigin.lon + theCutDxDy.lon, 0); ossimGpt llgp (theCutOrigin.lat - theCutDxDy.lat, theCutOrigin.lon , 0); ossimGpt lrgp (theCutOrigin.lat - theCutDxDy.lat, theCutOrigin.lon + theCutDxDy.lon, 0); ossimDpt ulen (theProductProjection->forward(ulgp)); ossimDpt uren (theProductProjection->forward(urgp)); ossimDpt llen (theProductProjection->forward(llgp)); ossimDpt lren (theProductProjection->forward(lrgp)); double n_top = (ulen.y > uren.y ? ulen.y : uren.y); double n_bottom = (llen.y < lren.y ? llen.y : lren.y); double e_left = (ulen.x < llen.x ? ulen.x : llen.x); double e_right = (uren.x > lren.x ? uren.x : lren.x); theCutOrigin.x = e_left; theCutOrigin.y = n_top; theCutDxDy.x = e_right - e_left; theCutDxDy.y = n_top - n_bottom; if (theClipToValidRectFlag) { // Now we need to clip the cut rect by the valid image footprint for the entire mosaic: ossimDrect boundingRect = theProductChain->getBoundingRect(); // in view coordinates boundingRect.expand(ossimDpt(0.5, 0.5)); ossimDpt mosaic_ul, mosaic_lr; theProductProjection->lineSampleToEastingNorthing(boundingRect.ul(), mosaic_ul); theProductProjection->lineSampleToEastingNorthing(boundingRect.lr(), mosaic_lr); // Establish the LR bound defined by the cut-rect and clip the cut-rect if necessary: ossimDpt cutrect_lr (theCutOrigin.x + theCutDxDy.x, theCutOrigin.y - theCutDxDy.y); if (mosaic_ul.y < theCutOrigin.y) theCutOrigin.y = mosaic_ul.y; if (mosaic_lr.y > cutrect_lr.y) theCutDxDy.y = theCutOrigin.y - mosaic_lr.y; if (mosaic_ul.x > theCutOrigin.x) theCutOrigin.x = mosaic_ul.x; if (mosaic_lr.x < cutrect_lr.x) theCutDxDy.x = mosaic_lr.x - theCutOrigin.x; } } else { // Just map the geographic coordinates to easting/northing, without regard to corner // mismatch: if (theCutOriginUnit == OSSIM_DEGREES) { originPLH.lat = theCutOrigin.y; originPLH.lon = theCutOrigin.x; theCutOrigin = theProductProjection->forward(originPLH); } else { // Determine the geographic position that might be needed for scaling below: originPLH = theProductProjection->inverse(theCutOrigin); } // Check for consistent rect size: if (theCutDxDyUnit == OSSIM_DEGREES) { // POTENTIAL BUG: conversion from degrees longitude to meters should be a function // of latitude here. Implemented here but needs testing: ossimDpt mtrs_per_deg (originPLH.metersPerDegree()); theCutDxDy.x = theCutDxDy.x * mtrs_per_deg.x; theCutDxDy.y = theCutDxDy.y * mtrs_per_deg.y; } } // Set these to the correct units. May already be correct, but just in case... theCutOriginUnit = OSSIM_METERS; theCutDxDyUnit = OSSIM_METERS; resolution = theProductProjection->getMetersPerPixel(); } // The cut rect corresponds to the edges of the pixel ("edge-to-edge"), while OSSIM considers // coordinates to correspond to the pixel centers. Need to shift the origin to the SE by 1/2p: ossimDpt half_pixel = resolution * 0.5; theCutOrigin.y -= half_pixel.y; theCutOrigin.x += half_pixel.x; // The size of the cutrect needs to be an integral number of pixels in output space: theCutDxDy.x = (floor(theCutDxDy.x/resolution.x + 0.5))* resolution.x; theCutDxDy.y = (floor(theCutDxDy.y/resolution.y + 0.5))* resolution.y; // Adjust a center origin specification to be Upper Left corner: if (theCutOriginType == OSSIM_CENTER_ORIGIN) { theCutOrigin.y += theCutDxDy.y; theCutOrigin.x -= theCutDxDy.x; // theCutDxDy in this case represented a radius. This needs to be converted to // OSSIM_UPPER_LEFT_ORIGIN form: theCutDxDy.x *= 2.0; theCutDxDy.y *= 2.0; theCutOriginType = OSSIM_UPPER_LEFT_ORIGIN; } // Finally, update the product projection with new rectangle: ossimDpt cutCenter (theCutOrigin.x + theCutDxDy.x/2.0, theCutOrigin.y - theCutDxDy.y/2.0); ossimGpt gpt; if (theCutDxDyUnit == OSSIM_METERS) { // Set the E/N values for the cut origin as the tie point: theProductProjection->setUlTiePoints(theCutOrigin); } else { // Set the projection center (origin) latitude at the center of the cut rect: gpt.lat = cutCenter.y; gpt.lon = 0.0; theProductProjection->setOrigin(gpt); // Set the lat/lon values for the cut origin as the tie point: gpt.lat = theCutOrigin.y; gpt.lon = theCutOrigin.x; theProductProjection->setUlTiePoints(gpt); } // cout << "\n**************** proj 2:\n"; // theProductProjection->print(cout); // Propagates changes to the projection to the processing chain: setView(); } //************************************************************************************************* //! Sets up the histogram operation requested for the image chain passed in. //************************************************************************************************* void ossimOrthoIgen::setupHistogram(ossimImageChain* input_chain, const ossimSrcRecord& src_record) { // Check if the source passed in is the output mosaic object, because the target // histogram remapper needs to be connected to it (only valid when histo matching is requested): if (input_chain == NULL) { if (!theTargetHistoFileName.isReadable()) return; ossimHistogramRemapper* remapper = new ossimHistogramRemapper; remapper->openHistogram(theTargetHistoFileName); theProductChain->addFirst(remapper); return; } // Check if any histo operation was requested on individual image: if ((ossim::isnan(theHighPercentClip) || ossim::isnan(theLowPercentClip)) && !theUseAutoMinMaxFlag && (theStdDevClip < 0) && src_record.getHistogramOp().empty() && theTargetHistoFileName.empty()) { return; // no histo op requested } // Remaining operations require a histogram on the input image source: ossimImageHandler* handler = PTR_CAST(ossimImageHandler, input_chain->getLastSource()); if (handler == NULL) { ossimNotify(ossimNotifyLevel_FATAL)<<"Could not locate an image handler object in the image" << "chain provided. This should not happen. Ignoring histogram request." << std::endl; return; } // Establish the ideal filename for this histogram. The following do-block is all for testing // different histogram file naming schemes since alternate directory and entry-indexing might be // used: ossimFilename histoFilename (src_record.getHistogramPath()); ossimFilename candidateHistoFilename; ossimFilename defaultHistoFilename (handler->createDefaultHistogramFilename()); ossimFilename entryName (handler->getFilenameWithThisExtension(ossimString(".his"), true)); do { if (!histoFilename.empty()) { // Try histogram filename based on specified name in the .src file: if (histoFilename.isDir()) histoFilename = histoFilename.dirCat(defaultHistoFilename.file()); if (histoFilename.exists()) break; // Try specified name with entry index: if (src_record.getEntryIndex() >= 0) { histoFilename = histoFilename.path().dirCat(entryName.file()); if (histoFilename.exists()) break; } // Not found so set the candidate filename in case we need to generate it: candidateHistoFilename = histoFilename; } // Next try looking for a histogram based on the default name: histoFilename = defaultHistoFilename; if (histoFilename.exists()) break; //--- // Last possibility is the default name with entry index. We will test // even if there is only one entry, like "file_e0.his". //--- histoFilename = entryName; if (histoFilename.exists()) break; // If not already set, set the candidate filename in case we need to generate it: if (candidateHistoFilename.empty()) candidateHistoFilename = histoFilename; } while (false); // only pass through once // If the histogram was still not located, look into creating one: if (!histoFilename.exists()) { // Check the preferences for histogram autogeneration: ossimString lookup = ossimPreferences::instance()->findPreference(AUTOGENERATE_HISTOGRAM_KW); if (lookup.toBool()) { // No histogram available for this image, need to create one: histoFilename = candidateHistoFilename; ossimNotify(ossimNotifyLevel_WARN) <<"Histogram file <" << histoFilename << "> not found. Creating one now..." << std::endl; bool success = createHistogram(input_chain, histoFilename); if (!success) { ossimNotify(ossimNotifyLevel_WARN) <<"Error encountered creating histogram file <" << histoFilename << ">. Ignoring histogram request." << std::endl; return; } } } // Need to insert any histogram object to the left of the renderer in the chain. Search for a // renderer and save for later: // ossimConnectableObject* renderer = PTR_CAST(ossimConnectableObject, // input_chain->findFirstObjectOfType(ossimString("ossimImageRenderer"))); ossimTypeNameVisitor visitor( ossimString("ossimImageRenderer"), true, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); input_chain->accept( visitor ); ossimRefPtr renderer = visitor.getObjectAs(0); // Histo Match? if (theTargetHistoFileName.isReadable()) { // A histogram match was requested. This involves applying a histo equalization to the input // chain and then applying an inverted equalization using the target histogram: ossimRefPtr forwardEq = new ossimHistogramEqualization; ossimRefPtr inverseEq = new ossimHistogramEqualization; // Init equalizers with the source and target histogram files: forwardEq->setInverseFlag(false); forwardEq->setHistogram(histoFilename); inverseEq->setInverseFlag(true); inverseEq->setHistogram(theTargetHistoFileName); // Need check that source and target histograms are compatible: ossimRefPtr sourceHisto = forwardEq->getHistogram(); ossimRefPtr targetHisto = inverseEq->getHistogram(); bool are_incompatible = false; if (!sourceHisto.valid() || !targetHisto.valid()) { are_incompatible = true; } else { ossim_uint32 num_source_bands = sourceHisto->getNumberOfBands(); if (num_source_bands != targetHisto->getNumberOfBands()) { are_incompatible = true; } else { for (ossim_uint32 band=0; band sourceBandHisto = sourceHisto->getHistogram(band); ossimRefPtr targetBandHisto = targetHisto->getHistogram(band); if (!sourceBandHisto.valid() || !targetBandHisto.valid() || (sourceBandHisto->GetRes() != targetBandHisto->GetRes())) { are_incompatible = true; break; } } } } if (are_incompatible) { // Error was encountered establishing histograms for match operation: ossimNotify(ossimNotifyLevel_WARN)<<"Error encountered setting up histogram match " "operation. Check that source and target histograms are compatible. No histogram " "operations will be performed on this image." << std::endl; return; } // The source and target histos are compatible, insert to the left of renderer if one exists: if ( renderer.valid() ) input_chain->insertLeft( forwardEq.get(), renderer.get() ); else input_chain->addFirst(forwardEq.get()); input_chain->insertRight(inverseEq.get(), forwardEq.get()); return; } // Remaining possibilities (clip or stretch) require a remapper. // Insert to the left of renderer if one exists: ossimRefPtr remapper = new ossimHistogramRemapper; if ( renderer.valid() ) input_chain->insertLeft( remapper.get(), renderer.get() ); else input_chain->addFirst(remapper.get()); // Fetch the input histogram: bool histo_read_ok = remapper->openHistogram(histoFilename); if (!histo_read_ok) { // No histogram available for this image, need to create one (TODO): ossimNotify(ossimNotifyLevel_WARN)<<"Error encountered loading histogram file <" << histoFilename << ">. No histogram operations will be performed on this image." << std::endl; return; } // Set values to construct remap table: if (!ossim::isnan(theHighPercentClip) && !ossim::isnan(theLowPercentClip)) { // Hi/Lo clip requested remapper->setHighNormalizedClipPoint(1.0-theHighPercentClip); remapper->setLowNormalizedClipPoint(theLowPercentClip); } else { // Consider histogram stretch operations. These can be on a per-image basis or global for all // input images. Give priority to the img_histo_op (per-image spec) over general flags below: ossimHistogramRemapper::StretchMode mode = ossimHistogramRemapper::STRETCH_UNKNOWN; ossimString img_histo_op (src_record.getHistogramOp()); if (img_histo_op=="auto-minmax") mode = ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX; else if (img_histo_op.contains("std-stretch")) { if (img_histo_op.contains("1")) mode = ossimHistogramRemapper::LINEAR_1STD_FROM_MEAN; else if (img_histo_op.contains("2")) mode = ossimHistogramRemapper::LINEAR_2STD_FROM_MEAN; else if (img_histo_op.contains("3")) mode = ossimHistogramRemapper::LINEAR_3STD_FROM_MEAN; } else if (theUseAutoMinMaxFlag) mode = ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX; else if (theStdDevClip > 0) mode = (ossimHistogramRemapper::StretchMode) theStdDevClip; // Finally init the remapper with proper stretch mode: if (mode != ossimHistogramRemapper::STRETCH_UNKNOWN) remapper->setStretchMode(mode, true); } return; } //************************************************************************************************* //! Utility method for creating a histogram for an input image. Returns TRUE if successful. //************************************************************************************************* bool ossimOrthoIgen::createHistogram(ossimImageChain* chain, const ossimFilename& histo_filename) { ossimRefPtr histoSource = new ossimImageHistogramSource; ossimRefPtr writer = new ossimHistogramWriter; histoSource->connectMyInputTo(chain); histoSource->enableSource(); histoSource->setComputationMode(OSSIM_HISTO_MODE_FAST); writer->connectMyInputTo(histoSource.get()); writer->setFilename(histo_filename); writer->addListener(&theStdOutProgress); bool success = writer->execute(); writer=0; histoSource=0; if (success) { ossimNotify(ossimNotifyLevel_NOTICE)<. No histogram operations will be performed on this image." << std::endl; } return success; } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::addChainCache(ossimImageChain* chain) const { if (chain) { //ossimConnectableObject* renderer = // PTR_CAST(ossimConnectableObject, // chain->findFirstObjectOfType(ossimString("ossimImageRenderer"))); ossimTypeNameVisitor visitor( ossimString("ossimImageRenderer"), true, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); chain->accept( visitor ); ossimRefPtr renderer = visitor.getObjectAs(0); if ( renderer.valid() ) { ossimCacheTileSource* cache = new ossimCacheTileSource(); chain->insertLeft( cache, renderer.get() ); } } } //************************************************************************************************* // Generates a log KWL file that could be fed directly to Igen. Used for verifying chain. //************************************************************************************************* void ossimOrthoIgen::generateLog() { if (!theSrcRecords.size() || !theProductChain.valid() || theProductFilename.empty()) return; // Establish output filename: ossimFilename logFile = theProductFilename; logFile.setExtension("log"); // Fill a KWL with all info: ossimKeywordlist kwl; theContainer->saveState(kwl); if (theProductProjection.valid()) theProductProjection->saveState(kwl, "product.projection."); kwl.write(logFile.chars()); } //************************************************************************************************* //! Determines the UL corner tiepoint of the product projection as the overall UL corner of the //! mosaic. This may not be the final tiepoint, since a cut origin may have been specified, and the //************************************************************************************************* void ossimOrthoIgen::establishMosaicTiePoint() { if (!theProductChain.valid()) return; // Need to find all image handlers to query for their UL ground point: #if 0 ossimConnectableObject::ConnectableObjectList clientList; theProductChain->findAllInputsOfType(clientList, STATIC_TYPE_INFO(ossimImageHandler), true, true); if (clientList.size() == 0) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimOrthoIgen::establishMosaicTiePoint() WARNING -- " "Expected to find image handler in the chain but none was identified."<accept( visitor ); if ( visitor.getObjects().empty() ) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimOrthoIgen::establishMosaicTiePoint() WARNING -- " "Expected to find image handler in the chain but none was identified."<( i ); if (!handler) break; ossimRefPtr geom = handler->getImageGeometry(); if (!geom.valid()) continue; // Skip over any non geometry inputs (e.g., masks) if ( theProductProjection->isGeographic() ) { geom->getTiePoint( tie_gpt_i, true ); // True to get edge of tie. if ( tie_gpt_i.hasNans() == false ) { if (tie_gpt.hasNans()) tie_gpt = tie_gpt_i; else { if (tie_gpt_i.lat > tie_gpt.lat) tie_gpt.lat = tie_gpt_i.lat; if (tie_gpt_i.lon < tie_gpt.lon) tie_gpt.lon = tie_gpt_i.lon; } } } else { geom->getTiePoint( tie_dpt_i, true ); // True to get edge of tie. if ( tie_dpt_i.hasNans() == false ) { if (tie_dpt.hasNans()) tie_dpt = tie_dpt_i; else { if (tie_dpt_i.y > tie_dpt.y) tie_dpt.y = tie_dpt_i.y; if (tie_dpt_i.x < tie_dpt.x) tie_dpt.x = tie_dpt_i.x; } } } } #if 0 // Establish input image bounding rect, making sure to expand to include the FULL pixel since // pixel is point -- i.e. the pixel coordinate corresponds to the center of the pixel area, // not the edge. Therefore shift the image point by 1/2 pixel to correspond to edges: // (OLK 09/11) ossimDrect boundingRect (handler->getBoundingRect()); vector img_vertices; img_vertices.push_back(boundingRect.ul() + ossimDpt(-0.5, -0.5)); img_vertices.push_back(boundingRect.ur() + ossimDpt( 0.5, -0.5)); img_vertices.push_back(boundingRect.lr() + ossimDpt( 0.5, 0.5)); img_vertices.push_back(boundingRect.ll() + ossimDpt(-0.5, 0.5)); // The tie point will be in easting/northing or lat/lon depending on the type of projection // used for the product. Need to consider all image corners since the orientation of the image // is not known: for (int j=0; j<4; j++) { geom->localToWorld(img_vertices[j], tie_gpt_i); if (theProductProjection->isGeographic()) { tie_gpt.height(0.0); if (tie_gpt.hasNans()) tie_gpt = tie_gpt_i; else { if (tie_gpt_i.lat > tie_gpt.lat) tie_gpt.lat = tie_gpt_i.lat; if (tie_gpt_i.lon < tie_gpt.lon) tie_gpt.lon = tie_gpt_i.lon; } } else { tie_dpt_i = theProductProjection->forward(tie_gpt_i); if (tie_dpt.hasNans()) tie_dpt = tie_dpt_i; else { if (tie_dpt_i.y > tie_dpt.y) tie_dpt.y = tie_dpt_i.y; if (tie_dpt_i.x < tie_dpt.x) tie_dpt.x = tie_dpt_i.x; } } } } #endif // The tie point coordinates currently reflect the UL edge of the UL pixel. We'll need to shift // the tie point from the edge to the center. (OLK 09/11) ossimDpt half_pixel_shift(0,0); if (theProductProjection->isGeographic()) { half_pixel_shift = theProductProjection->getDecimalDegreesPerPixel() * 0.5; if (!tie_gpt.hasNans()) { tie_gpt.lat -= half_pixel_shift.lat; tie_gpt.lon += half_pixel_shift.lon; theProductProjection->setUlTiePoints(tie_gpt); } } else { half_pixel_shift = theProductProjection->getMetersPerPixel() * 0.5; tie_dpt.y -= half_pixel_shift.y; tie_dpt.x += half_pixel_shift.x; theProductProjection->setUlTiePoints(tie_dpt); } // Propagates changes to the projection to the processing chain: setView(); } //************************************************************************************************* //! Computes the center latitude of the mosaic for use as the geographic scaling latitude //************************************************************************************************* void ossimOrthoIgen::computeGeoScalingLatitude() { if (!theProductChain.valid()) return; // Need to find all image handlers to query for their UL ground point: ossimTypeNameVisitor visitor( ossimString("ossimImageHandler"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); if ( visitor.getObjects().empty() ) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimOrthoIgen::establishMosaicTiePoint() WARNING -- " "Expected to find image handler in the chain but none was identified."<(i); if (!handler) break; ossimRefPtr geom = handler->getImageGeometry(); if (!geom.valid()) continue; // Skip over any non geometry inputs (e.g., masks) geom->getCornerGpts(ul_i, ur_i, lr_i, ll_i); ossimGrect bbox_i(ul_i, ur_i, lr_i, ll_i); bbox = bbox.combine(bbox_i); } // Fetch midpoint and assign scaling latitude: ossimGpt midPoint (bbox.midPoint()); if (!midPoint.isLatNan()) theGeoScalingLatitude = midPoint.lat; else theGeoScalingLatitude = 0.0; } //************************************************************************************************* // Initialize the pixel flipper in the source chain if one is called for //************************************************************************************************* ossimImageSource* ossimOrthoIgen::setupPixelFlipper(ossimImageChain* singleImageChain, const ossimSrcRecord& src_record) { if (singleImageChain == NULL) return NULL; // Fetch the image handler that should be the last (left-most) source in the chain: ossimImageSource* current_source = singleImageChain->getLastSource(); if (current_source == NULL) return NULL; // There are two possibilities for specifying pixel flipping -- either as a command line option // that applies to all input imagery, or specified for a particular input via the .src file. // The .src file takes precedence: const ossimSrcRecord::PixelFlipParams& flipParams = src_record.getPixelFlipParams(); // The replacement can be specified globally in the preferences if none found in the src record: ossimString replaceModeStr = flipParams.replacementMode; if (replaceModeStr.empty()) replaceModeStr = thePixelReplacementMode; // First consider if a range of clipped pixels was specified: ossim_float64 clip_min = flipParams.clipMin; if (ossim::isnan(clip_min)) clip_min = theClipPixelMin; ossim_float64 clip_max = flipParams.clipMax; if (ossim::isnan(clip_max)) clip_max = theClipPixelMax; ossimPixelFlipper* flipper = 0; if (!ossim::isnan(clip_min) && !ossim::isnan(clip_max)) { // A clip within a range of pixel values was requested. All pixels within the specified range // are mapped to NULL. Create the remapper and insert it into the chain just after the handler flipper = new ossimPixelFlipper(); flipper->setTargetRange(clip_min, clip_max); flipper->setReplacementValue(current_source->getNullPixelValue()); flipper->setReplacementMode(replaceModeStr); singleImageChain->insertRight(flipper, current_source); current_source = flipper; } // The user can also specify a clamping similar to the pixel clipping above. This would be a // second flipper object in the chain: ossim_float64 clamp_min = flipParams.clampMin; if (ossim::isnan(clamp_min)) clamp_min = theClampPixelMin; ossim_float64 clamp_max = flipParams.clampMax; if (ossim::isnan(clamp_max)) clamp_max = theClampPixelMax; flipper = 0; // no leak since chain assumes ownership of prior instance. if (!ossim::isnan(clamp_min)) { // A bottom clamping was requested. All pixels below this value are set to this value: flipper = new ossimPixelFlipper(); flipper->setClampValue(clamp_min, false); // false = clamp bottom } if (!ossim::isnan(clamp_max)) { // A top clamping was requested. All pixels above this value are set to this value. // The same flipper object can be used as the bottom clamp (if created): if (!flipper) flipper = new ossimPixelFlipper(); flipper->setClampValue(clamp_max, true); // true = clamp top } if (flipper) { // Common code for top and bottom clamping: flipper->setReplacementMode(replaceModeStr); singleImageChain->insertRight(flipper, current_source); current_source = flipper; } return current_source; } //************************************************************************************************* // Checks for the presence of a raster mask file alongside the image, and inserts the mask // filter in the chain if mask file exists. Returns pointer to the "current (last added) source // in the single image chain. //************************************************************************************************* ossimImageSource* ossimOrthoIgen::setupRasterMask(ossimImageChain* singleImageChain, const ossimSrcRecord& src_record) { if (singleImageChain == NULL) return NULL; // Search for the image handler in the chain: ossimImageHandler* img_handler = dynamic_cast(singleImageChain->getLastSource()); if (img_handler == NULL) return NULL; // See if a raster mask was specified in the SRC record: ossimFilename mask_file = src_record.getMaskPath(); if (!mask_file.exists()) return img_handler; // Open up the mask file and verify it is good: ossimImageHandler* mask_handler = ossimImageHandlerRegistry::instance()->open(mask_file); if (mask_handler == NULL) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimOrthoIgen::setupRasterMask() -- Could not open " "raster mask file <"<. Maske request will be ignored."<deleteLast(); // Remove the handler // ossimImageSource* nextInChain = singleImageChain->getLastSource(); ossimRefPtr mask_filter = new ossimMaskFilter; singleImageChain->insertRight(mask_filter.get(), img_handler); mask_filter->setMaskSource(mask_handler); // assumes ownership of object //--- // Set the mode to SELECT_CLAMP_MIN. This clamps data to min pixel value in the valid image // area if the input pixel is null(essentially a pixel flip). //--- mask_filter->setMaskType(ossimMaskFilter::OSSIM_MASK_TYPE_SELECT_CLAMP_MIN); return mask_filter.get(); } //************************************************************************************************* // Adds a scalar remapper to the extreme right of the chain is specified by the // --output-radiometry option. //************************************************************************************************* void ossimOrthoIgen::setupOutputRadiometry() { if (theOutputRadiometry.empty()) return; // Map the specified radiometry to a valid type: ossimScalarType scalar_type = ossimScalarTypeLut::instance()->getScalarTypeFromString(theOutputRadiometry); if (scalar_type == OSSIM_SCALAR_UNKNOWN) return; // Add a scalar remapper to the product chain: if(theProductChain->getOutputScalarType() != scalar_type) { ossimScalarRemapper* remapper = new ossimScalarRemapper; remapper->setOutputScalarType(scalar_type); theProductChain->addFirst(remapper); } } //************************************************************************************************* // Private method to see if any image chain input projections are affected by elevation. //************************************************************************************************* bool ossimOrthoIgen::isAffectedByElevation() { bool result = false; // Get a list of all the image handlers. // ossimConnectableObject::ConnectableObjectList clientList; // theProductChain->findAllInputsOfType(clientList, STATIC_TYPE_INFO(ossimImageHandler), // true, true); ossimTypeNameVisitor visitor( ossimString("ossimImageHandler"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); // Loop over all input handlers and see if affected by elevation. // ossimConnectableObject::ConnectableObjectList::iterator iter = clientList.begin(); // while (iter != clientList.end()) for( ossim_uint32 i = 0; i < visitor.getObjects().size(); ++i ) { // ossimRefPtr handler = PTR_CAST(ossimImageHandler, (*iter).get()); ossimRefPtr handler = visitor.getObjectAs( i ); if ( handler.valid() ) { ossimRefPtr geom = handler->getImageGeometry(); if (geom.valid()) { ossimRefPtr proj = geom->getProjection(); if ( proj.valid() ) { if ( proj->isAffectedByElevation() ) { result = true; break; } } } } // ++iter; } return result; } //************************************************************************************************* // Private method to recompute the gsd on all image handlers that have projections affected by // elevation. //************************************************************************************************* void ossimOrthoIgen::reComputeChainGsds() { // Get a list of all the image handlers. // ossimConnectableObject::ConnectableObjectList clientList; // theProductChain->findAllInputsOfType(clientList, STATIC_TYPE_INFO(ossimImageHandler), // true, true); // Loop over all input handlers and see if affected by elevation. // ossimConnectableObject::ConnectableObjectList::iterator iter = clientList.begin(); // while (iter != clientList.end()) ossimTypeNameVisitor visitor( ossimString("ossimImageHandler"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); for( ossim_uint32 i = 0; i < visitor.getObjects().size(); ++i ) { // ossimRefPtr handler = PTR_CAST(ossimImageHandler, (*iter).get()); ossimRefPtr handler = visitor.getObjectAs( i ); if ( handler.valid() ) { ossimRefPtr geom = handler->getImageGeometry(); if (geom.valid()) { ossimRefPtr proj = geom->getProjection(); if ( proj.valid() ) { if ( proj->isAffectedByElevation() ) proj->getMetersPerPixel(); } } } // ++iter; } } //************************************************************************************************* // GSD Determination is nontrivial since there are various command-line options that control // this quantity. This method considers all information before setting the product's GSD. //************************************************************************************************* void ossimOrthoIgen::setProductGsd() { if (!theProductChain.valid()) return; // Fetch the reference input projection first. Settings may be copied to the product projection: ossimMapProjection* ref_map = PTR_CAST(ossimMapProjection, theReferenceProj.get()); ossimGpt origin; // The geo-scaling latitude effectively specifies the map projection's origin latitude, which // may affect the scaling of GSD in x-direction. This is only relevant for geographic projections if (theProductProjection->isGeographic()) { ossimGpt origin (0.0, theProductProjection->getOrigin().lon, 0.0); if (ossim::isnan(theGeoScalingLatitude)) { // Loop over all input handlers and accumulate the geographic centers. This will allow // computing mosaic center point (approximate) for purposes of establishing reference // latitude for scale: origin.lat = 0.0; origin.lon = theProductProjection->getOrigin().lon; // ossimConnectableObject::ConnectableObjectList clientList; // theProductChain->findAllInputsOfType(clientList, STATIC_TYPE_INFO(ossimImageHandler), 1, 1); // ossimConnectableObject::ConnectableObjectList::iterator iter = clientList.begin(); ossimTypeNameVisitor visitor( ossimString("ossimImageHandler"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); ossimDpt center_pt; ossimGpt geocenter; int num_contributors = 0; // while (iter != clientList.end()) for( ossim_uint32 i = 0; i < visitor.getObjects().size(); ++i ) { // ossimImageHandler* handler = PTR_CAST(ossimImageHandler, (*iter).get()); ossimRefPtr handler = visitor.getObjectAs( i ); if ( handler.valid() ) { // iter++; ossimRefPtr geom = handler->getImageGeometry(); if (!geom.valid()) continue; // Skip over any non geometry inputs (e.g., masks) handler->getBoundingRect().getCenter(center_pt); if (!geom->localToWorld(center_pt, geocenter)) continue; if (num_contributors == 0) origin.lat = geocenter.lat; else origin.lat += geocenter.lat; ++num_contributors; } else { break; } } // Compute average latitude among all contributors: if (num_contributors) origin.lat /= (double)num_contributors; } else { // A geo-scaling reference latitude was provided on the command line: origin.lat = theGeoScalingLatitude; } // Set the latitude of origin to the reference latitude (either specified on command line or // computed as scene center): theProductProjection->setOrigin(origin); // proj now can handle meters and degrees correctly } // Establish the resolution based on either command line option or reference proj if no values // provided on command line (--degrees or --meters): ossimDpt resolution (theDeltaPerPixelOverride); ossimUnitType resUnits = theDeltaPerPixelUnit; if (resolution.hasNans()) { // No GSD specified, so copy it from the input projection: if (ref_map && ref_map->isGeographic()) { resolution = ref_map->getDecimalDegreesPerPixel(); resUnits = OSSIM_DEGREES; } else { resolution = theReferenceProj->getMetersPerPixel(); resUnits = OSSIM_METERS; } } // Set the desired image GSD, accounting for possible mixing of units: if (resUnits == OSSIM_DEGREES) { // Need to adjust the resolution in the longitude direction if the user requested geo-scaling: if (!ossim::isnan(theGeoScalingLatitude)) resolution.lon = resolution.lat/ossim::cosd(theGeoScalingLatitude); theProductProjection->setDecimalDegreesPerPixel(resolution); } else theProductProjection->setMetersPerPixel(resolution); // Propagates changes to the projection to the processing chain: setView(); } ossim-Miami-2.9.1/src/util/ossimOrthoTool.cpp000066400000000000000000000047531352751253100212000ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; const char* ossimOrthoTool::DESCRIPTION = "Utility for orthorectifying and reprojecting image data."; ossimOrthoTool::ossimOrthoTool() { } ossimOrthoTool::~ossimOrthoTool() { } void ossimOrthoTool::setUsage(ossimArgumentParser& ap) { // Add options. ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " ortho [options] [] "; au->setCommandLineUsage(usageString); // Set the command line options: au->setDescription(DESCRIPTION); // Base class has its own: ossimChipProcTool::setUsage(ap); } bool ossimOrthoTool::initialize(ossimArgumentParser& ap) { if (!ossimChipProcTool::initialize(ap)) return false; if (m_helpRequested) return true; processRemainingArgs(ap); return true; } void ossimOrthoTool::initialize(const ossimKeywordlist& kwl) { // Base class does the heavy work: ossimChipProcTool::initialize(kwl); } void ossimOrthoTool::initProcessingChain() { ossimRefPtr input_mosaic = combineLayers(m_imgLayers); m_procChain->add(input_mosaic.get()); } ossim-Miami-2.9.1/src/util/ossimPointCloudTool.cpp000066400000000000000000000176411352751253100221650ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Oscar Kramer // //******************************************************************* // $Id$ #include #include #include #include #include #include #include #include #include #include #include using namespace std; const char* ossimPointCloudTool::DESCRIPTION = "Utility class for generating point-cloud-derived image products."; ossimPointCloudTool::ossimPointCloudTool() : m_operation (LOWEST_DEM), m_gsd (0) { } ossimPointCloudTool::~ossimPointCloudTool() { m_pcHandler = 0; m_prodGeom = 0; m_pcuFilter = 0; } void ossimPointCloudTool::addArguments(ossimArgumentParser& ap) { // Set the general usage: ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " [options] "; au->setCommandLineUsage(usageString); // Set the command line options: au->addCommandLineOption( "--gsd ", "Specifies output GSD in meters. Defaults to the same " "resolution as input DEM."); au->addCommandLineOption( "--dem ", "Specifies the input DEM filename. If none provided, the elevation database is " "referenced as specified in prefs file"); au->addCommandLineOption( "--lut ", "Specifies the optional lookup table filename for " "mapping the single-band output image to an RGB. The LUT provided must be " "in the ossimIndexToRgbLutFilter format and must handle the three output " "viewshed values (see --values option)."); au->addCommandLineOption( "--method", "Specify the desired operation. Possible values are:\n" " \"highest-dem\", \"lowest-dem\" (default), or \"highest-lowest\". \n" "Alternatively can be specified in shorthand as \"h-d\", \"l-d\", or \"h-l\", " "respectively."); au->addCommandLineOption( "--request-api", "Causes applications API to be output as JSON to stdout." " Accepts optional filename to store JSON output."); au->addCommandLineOption( "--threads ", "Number of threads. Defaults to use all available cores. " "For engineering/debug purposes "); } void ossimPointCloudTool::usage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); // Add options. addArguments(ap); // Write usage. ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); ossimNotify(ossimNotifyLevel_INFO) <<"\nPerforms specified processing on point-cloud.\n\n" << std::endl; } bool ossimPointCloudTool::initialize(ossimArgumentParser& ap) { if ( (ap.argc() == 1) || ap.read("-h") || ap.read("--help") ) { usage(ap); return false; } ossimString ts1; ossimArgumentParser::ossimParameter sp1(ts1); if ( ap.read("--dem", sp1) ) m_demFile = ts1; if ( ap.read("--gsd", sp1) ) m_gsd = ossimString(ts1).toDouble(); if ( ap.read("--lut", sp1) ) m_lutFile = ts1; if ( ap.read("--method", sp1) ) { if (ts1.contains("highest-dem") || ts1.contains("h-d")) m_operation = HIGHEST_DEM; else if (ts1.contains("highest-lowest") || ts1.contains("h-l")) m_operation = HIGHEST_LOWEST; } if ( ap.read("--pc", sp1) ) m_demFile = ts1; /* if ( ap.read("--request-api", sp1)) { ofstream ofs ( ts1.c_str() ); printApiJson(ofs); ofs.close(); return false; } if ( ap.read("--request-api")) { printApiJson(cout); return false; } */ // There should only be the required command line args left: if (ap.argc() < 3) { usage(ap); return false; } // Parse the required command line params: m_pcFile = ap[1]; m_prodFile = ap[2]; return initialize(); } void ossimPointCloudTool::loadJSON(const Json::Value &json_request) { } bool ossimPointCloudTool::initialize() { if (loadPC()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimPointCloudTool::initialize ERR: Cannot open PC file at <"<\n"<< endl; return false; } if (!m_demFile.empty() && !loadDem()) return false; m_pcuFilter = new ossimPointCloudUtilityFilter(this); return true; } bool ossimPointCloudTool::loadPC() { // DEM provided as file on command line, reset the elev manager to use only this: m_pcHandler = ossimPointCloudHandlerRegistry::instance()->open(m_pcFile); if(!m_pcHandler.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "ossimPointCloudTool::initialize ERR: Cannot open PC file at <"<\n" << std::endl; return false; } // Use "rasterized" PC to establish best output image geometry: m_pciHandler = new ossimPointCloudImageHandler; m_pciHandler->setPointCloudHandler(m_pcHandler.get()); m_prodGeom = m_pciHandler->getImageGeometry(); if (!m_prodGeom.valid() || !m_prodGeom->getAsMapProjection()) return false; if (m_gsd != 0) m_prodGeom->getAsMapProjection()->setMetersPerPixel(ossimDpt(m_gsd, m_gsd)); return true; } bool ossimPointCloudTool::loadDem() { // DEM provided as file on command line, reset the elev manager to use only this: ossimElevManager* elevMgr = ossimElevManager::instance(); elevMgr->clear(); ossimRefPtr ied = new ossimImageElevationDatabase; if(!ied->open(m_demFile)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimViewshedUtil::initialize ERR: Cannot open DEM file at <"<\n" << std::endl; return false; } elevMgr->addDatabase(ied.get()); // When DEM file specified, need to turn off all defaulting to ellipsoid/geoid to make sure // only the DEM file data is processed: elevMgr->setDefaultHeightAboveEllipsoid(ossim::nan()); elevMgr->setUseGeoidIfNullFlag(false); return true; } void ossimPointCloudTool::setGSD(const double& meters_per_pixel) { if (m_prodGeom->getAsMapProjection() && (meters_per_pixel > 0)) { m_gsd = meters_per_pixel; m_prodGeom->getAsMapProjection()->setMetersPerPixel(ossimDpt(m_gsd, m_gsd)); } } bool ossimPointCloudTool::execute() { // See if an LUT is requested: ossimImageSource* last_source = m_pcuFilter.get(); ossimRefPtr lutSource = 0; if (!m_lutFile.empty()) { ossimKeywordlist lut_kwl; lut_kwl.addFile(m_lutFile); lutSource = new ossimIndexToRgbLutFilter; if (!lutSource->loadState(lut_kwl)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimPointCloudTool::writeFile() ERROR: The LUT " "file <"< could not be read. Ignoring remap request.\n"<< std::endl; lutSource = 0; } else { lutSource->connectMyInputTo(last_source); lutSource->initialize(); last_source = lutSource.get(); } } // Set up the writer: ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriter(m_prodFile); bool success = false; if (writer.valid()) { writer->connectMyInputTo(0, last_source); success = writer->execute(); } return success; } void ossimPointCloudTool::saveJSON(Json::Value &json_request) const { } ossim-Miami-2.9.1/src/util/ossimRemapTool.cpp000066400000000000000000000204711352751253100211440ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // // Author: oscar.kramer@maxar.com // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; const char* ossimRemapTool::DESCRIPTION = "Performs remap to 8-bit including optional histogram stretch and saves the corresponding external geometry file."; ossimRemapTool::ossimRemapTool() : m_doHistoStretch(true), m_entry(0) { theStdOutProgress.setFlushStreamFlag(true); } ossimRemapTool::ossimRemapTool(const ossimFilename& inputFile, int entryIndex, bool doHistoStretch, ossimFilename outputFile) : m_inputFilename (inputFile), m_entry (entryIndex), m_doHistoStretch(doHistoStretch), m_gsd(-1.0) { m_productFilename = outputFile; theStdOutProgress.setFlushStreamFlag(true); initProcessingChain(); if (!execute()) throw ossimException("Error encountered writing remap image."); } ossimRemapTool::~ossimRemapTool() { } void ossimRemapTool::setUsage(ossimArgumentParser& ap) { // Add options. ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " remap [options] []"; au->setCommandLineUsage(usageString); // Set the command line options: au->setDescription(DESCRIPTION); // Base class has its own: ossimTool::setUsage(ap); au->addCommandLineOption("-e, --entry", " For multi image handlers which entry do you wish to extract. For list of entries use: \"ossim-info -i \" "); au->addCommandLineOption("-n, --no-histo", "Optionally bypass histogram-stretch. "); au->addCommandLineOption("-g, --gsd", "Set the output resolution, in meters. Default is same as input resolution (no resampling)."); } bool ossimRemapTool::initialize(ossimArgumentParser& ap) { if (!ossimTool::initialize(ap)) return false; if (m_helpRequested) return true; ossimString ts1; ossimArgumentParser::ossimParameter sp1 (ts1); if ( ap.read("-e", sp1) || ap.read("--entry", sp1) ) m_entry = ts1.toUInt32(); if ( ap.read("--no-histo") || ap.read("-n")) m_doHistoStretch = false; if ( ap.read("--gsd", sp1) || ap.read("-g", sp1)) m_gsd = ts1.toDouble(); // Determine input filename: if ( ap.argc() > 1 ) m_inputFilename = ap[1]; if (!m_inputFilename.isReadable()) { ossimNotify(ossimNotifyLevel_FATAL)<<"ossimRemapTool::initialize() Input filename <" < was not specified or is not " <<"readable. Try again.\n"< 2 ) { m_productFilename = ap[2]; cout< handler = ossimImageHandlerRegistry::instance()->open(m_inputFilename); if (!handler) { errMsg<<"Could not open input image file at <"<."; throw ossimException(errMsg.str()); } if (m_entry) handler->setCurrentEntry(m_entry); m_procChain->add(handler.get()); m_geom = handler->getImageGeometry(); // Add histogram remapper if requested: if (m_doHistoStretch) { ossimRefPtr histogram = handler->getImageHistogram(); if (!histogram) { // Need to create a histogram: ossimRefPtr histoSource = new ossimImageHistogramSource; ossimRefPtr writer = new ossimHistogramWriter; histoSource->connectMyInputTo(0, handler.get()); histoSource->enableSource(); writer->connectMyInputTo(0, histoSource.get()); ossimFilename histoFile; histoFile = handler->getFilenameWithThisExtension(ossimString("his")); writer->setFilename(histoFile); writer->addListener(&theStdOutProgress); writer->execute(); histogram = handler->getImageHistogram(); if (!histogram) { errMsg<<"Could not create histogram from <"<."; throw ossimException(errMsg.str()); } } // Ready the histogram object in the processing chain: ossimRefPtr histogramRemapper = new ossimHistogramRemapper(); histogramRemapper->setEnableFlag(true); histogramRemapper->setStretchMode( ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX ); histogramRemapper->setHistogram(histogram); m_procChain->add(histogramRemapper.get()); } // Add scalar remapper: ossimRefPtr scalarRemapper = new ossimScalarRemapper(); scalarRemapper->setOutputScalarType(OSSIM_UINT8); m_procChain->add(scalarRemapper.get()); // Check for scaling, need a resampler if non-zero: if (m_gsd > 0) { // First the IVT: ossimDpt inGsd = m_geom->getMetersPerPixel(); if (inGsd.x == 0 || inGsd.y == 0 || inGsd.hasNans()) { errMsg<<"Input GSD = "<getImageSize()); ossimIpt outSize (inSize.x/scale.x, inSize.y/scale.y); ossimRefPtr transform = new ossimAffineTransform; transform->setScale(scale); ossimRefPtr outGeom = new ossimImageGeometry(transform.get(), m_geom->getProjection()); outGeom->setImageSize(outSize); ossimRefPtr ivt = new ossimImageViewProjectionTransform(m_geom.get(), outGeom.get()); ossimRefPtr renderer = new ossimImageRenderer; renderer->setImageViewTransform(ivt.get()); renderer->getResampler()->setFilterType(ossimFilterResampler::ossimFilterResampler_TRIANGLE, ossimFilterResampler::ossimFilterResampler_TRIANGLE); m_procChain->add(renderer.get()); } m_procChain->initialize(); } bool ossimRemapTool::execute() { if (m_productFilename.empty()) { m_productFilename = m_inputFilename.fileNoExtension() + "-remap"; m_productFilename.setExtension(m_inputFilename.ext()); } m_geom->getBoundingRect(m_aoiViewRect); // Parent class has service to create writer: m_writer = newWriter(); m_writer->connectMyInputTo(0, m_procChain.get()); // Add a listener to get percent complete. m_writer->addListener(&theStdOutProgress); // Write the file and external geometry: if(!m_writer->execute()) return false; if (!m_writer->writeExternalGeometryFile()) return false; ossimNotify(ossimNotifyLevel_INFO)<<"Wrote product image to <"<"<"< #include #include #include #include #include #include #include #include #include using namespace std; static ossimTrace traceDebug = ossimTrace("ossimRpfUtil:debug"); ossimRpfUtil::ossimRpfUtil() { } ossimRpfUtil::~ossimRpfUtil() { } // Note: throws ossimException on error. void ossimRpfUtil::writeDotRpfFiles( const ossimFilename& aDotTocFile, const ossimFilename& outputDir ) { static const char MODULE[] = "ossimRpfUtil::writeDotRpfFiles"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << "\na.toc file: " << aDotTocFile << "\noutput directory: " << outputDir << "\n"; } // Parse the a.toc file: ossimRefPtr toc = new ossimRpfToc(); if ( toc->parseFile(aDotTocFile) != ossimErrorCodes::OSSIM_OK ) { std::string e = MODULE; e += " ERROR:\nCould not open: "; e+= aDotTocFile.string(); throw ossimException(e); } if ( outputDir.expand().exists() == false ) { if ( !outputDir.createDirectory(true, 0775) ) { std::string e = MODULE; e += " ERROR:\nCould not create directory: "; e+= outputDir.c_str(); throw ossimException(e); } } //--- // Go through the entries... //--- ossim_uint32 entries = toc->getNumberOfEntries(); for (ossim_uint32 entry = 0; entry < entries; ++entry) { const ossimRpfTocEntry* tocEntry = toc->getTocEntry(entry); if (tocEntry) { if ( tocEntry->isEmpty() == false ) { writeDotRpfFile(toc.get(), tocEntry, outputDir, entry); } } else { std::string e = MODULE; e += " ERROR: Null entry: "; e += ossimString::toString(entry).string(); throw ossimException(e); } } } // End: ossimRpfUtil::writeDotRpfFiles //--- // Writer a dot rpf file for entry to output directory. // // NOTES: // // 1) All coordinate written out in AREA or edge to edge format. // 2) Throws ossimException on error. //--- void ossimRpfUtil::writeDotRpfFile( const ossimRpfToc* toc, const ossimRpfTocEntry* tocEntry, const ossimFilename& outputDir, ossim_uint32 entry) { static const char MODULE[] = "ossimRpfUtil::writeDotRpfFile"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered..." << "\noutput directory: " << outputDir << "\nentry: " << entry << "\n"; } if ( !toc ) { std::string errMsg = MODULE; errMsg += " ERROR toc pointer null!"; throw ossimException(errMsg); } if ( !tocEntry ) { std::string errMsg = MODULE; errMsg += " ERROR toc entry pointer null!"; throw ossimException(errMsg); } // Get the file name. ossimFilename outFile; if ( outputDir.expand().isDir() ) { getDotRfpFilenameForEntry(outputDir, entry, outFile); } else { outFile = outputDir; } // Open the file to write. std::ofstream os; os.open(outFile.c_str(), ios::out); if ( os.good() == false ) { std::string errMsg = MODULE; errMsg += "ERROR could not open: "; errMsg += outFile.string(); throw ossimException(errMsg); } // Set up the output stream fix with full precision for ground points. os << setiosflags(std::ios_base::fixed) << setprecision(15); //--- // Overall TOC entry bounds: // // Write the first line which is the bounding box of the entry in the form of: // "89.9850464205332, 23.9892538162654|90.5085823882692, 24.5002602501599|1" // lr-lon lr-lat ul-lon ul-lat //--- ossimRefPtr geom = tocEntry->getImageGeometry(); if( geom.valid() == false) { std::string errMsg = "ERROR could not get geometry."; errMsg += outFile.string(); throw ossimException(errMsg); } // Rectangle in image space. ossimIrect outputRect; tocEntry->getBoundingRect(outputRect); // bands: ossim_uint32 bands = tocEntry->getNumberOfBands(); // scale: ossimDpt scale; tocEntry->getDecimalDegreesPerPixel(scale); ossimDpt halfPix = scale / 2.0; ossimGpt llg; ossimGpt urg; geom->localToWorld(outputRect.ur(), urg); geom->localToWorld(outputRect.ll(), llg); if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "outputRect: " << outputRect << "\nbands: " << bands << "\nscale: " << scale << "\nllg: " << llg << "\nurg: " << urg << std::endl; } // Expand coordinates to edge: llg.lon -= halfPix.x; llg.lat -= halfPix.y; urg.lon += halfPix.x; urg.lat += halfPix.y; // Test for 360 degrees apart. checkLongitude(llg, urg); os << llg.lon << "," // lower left longitude << llg.lat << "|" // lower left latitude << urg.lon << "," // upper right longitude << urg.lat << "|" // upper right latitude << bands << "\n"; // Frame loop: const ossim_int32 FRAMESIZE = 1536; const ossim_int32 ROWS = static_cast(tocEntry->getNumberOfFramesVertical()); if( ROWS == 0 ) { std::string errMsg = MODULE; errMsg += " ERROR no rows!"; throw ossimException(errMsg); } const ossim_int32 COLS = static_cast(tocEntry->getNumberOfFramesHorizontal()); if( COLS == 0 ) { std::string errMsg = MODULE; errMsg += " ERROR no columns!"; throw ossimException(errMsg); } // Set the initial lower left and upper right image points for localToWorld call. //ossimDpt urd( ( (ROWS-1)*FRAMESIZE) -1, 0.0); //ossimDpt lld(0.0, (ROWS*FRAMESIZE)-1); ossimDpt urd( FRAMESIZE-1, 0.0); ossimDpt lld(0.0, FRAMESIZE-1); for (ossim_int32 row = ROWS-1; row > -1; --row) { for (ossim_int32 col = 0; col < COLS; ++col) { //--- // Example format (only with 15 digit precision): // /data/spadac/rpf/world/cb01/ng467a1/0xslpk1a.i41|90.0448,24.3621|90.0598,24.3750 //--- // Get the path to the frame. ossimFilename path; toc->getRootDirectory(path); path = path.dirCat( toc->getRelativeFramePath(entry, row, col) ); // Not sure if this is backwards: geom->localToWorld(urd, urg); geom->localToWorld(lld, llg); // Expand coordinates to edge: llg.lon -= halfPix.x; llg.lat -= halfPix.y; urg.lon += halfPix.x; urg.lat += halfPix.y; // Test for 360 degrees apart. checkLongitude(llg, urg); os << path.c_str() << "|" << llg.lon << "," // lower left longitude << llg.lat << "|" // lower left latitude << urg.lon << "," // upper right longitude << urg.lat // upper right latitude << "\n"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "row[" << row << "]col[" << col << "]path: " << path << "\nlld: " << lld << "\nllg: " << llg << "\nurd: " << urd << "\nurg: " << urg << std::endl; } // Go to next col. urd.x += FRAMESIZE; lld.x += FRAMESIZE; } // End column loop. // Go to nex row. urd.y += FRAMESIZE; urd.x = FRAMESIZE-1; lld.y += FRAMESIZE; lld.x = 0; } // End row loop. // Close the file. os.close(); ossimNotify(ossimNotifyLevel_DEBUG) << "wrote file: " << outFile << std::endl; } // End: ossimRpfUtil::writeDotRpfFile void ossimRpfUtil::checkLongitude(ossimGpt& left, ossimGpt& right) const { //--- // Test for scene coordinates being 180 to 180 (360 degree spread) and // adjust leftLon to -180 if so. // // NOTE: // Setting tolerance to 1/7200 about 15 meters. // Not sure if this is too loose or not. (drb) //--- const ossim_float64 TOLERANCE = 0.000138889; // 1/7200 about 15 meters. if ( ossim::almostEqual(left.lon, 180.0, TOLERANCE) ) { if ( ossim::almostEqual(right.lon, 180.0, TOLERANCE) ) { left.lon = -180.0; right.lon = 180.0; } } } void ossimRpfUtil::getDotRfpFilenameForEntry(const ossimFilename& outputDir, ossim_uint32 entry, ossimFilename& outFile) const { // Get the build date in the format of (yyyymmddhhmmss). char s[15]; s[14] = '\0'; time_t t; time(&t); tm* lt = localtime(&t); strftime(s, 15, "%Y%m%d%H%M%S", lt); std::string date = s; outFile = outputDir.dirCat(s); outFile += "_e"; outFile += ossimString::toString(entry); outFile += ".rpf"; } ossim-Miami-2.9.1/src/util/ossimShorelineTool.cpp000066400000000000000000000524441352751253100220350ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static const string COLOR_CODING_KW = "color_coding"; static const string SMOOTHING_KW = "smoothing"; static const string THRESHOLD_KW = "threshold"; static const string TMODE_KW = "tmode"; static const string TOLERANCE_KW = "tolerance"; static const string ALGORITHM_KW = "algorithm"; static const ossimFilename DUMMY_OUTPUT_FILENAME = "@@NEVER_USE_THIS@@"; static const ossimFilename TEMP_INDEX_FILENAME = "temp_shoreline_index.tif"; static const ossimFilename TEMP_THRESHOLD_FILENAME = "temp_shoreline_threshold.tif"; static const ossimFilename TEMP_MASK_FILENAME = "temp_shoreline_mask.tif"; const char* ossimShorelineTool::DESCRIPTION = "Computes bitmap of water versus land areas in an input image."; ossimShorelineTool::ossimShorelineTool() : m_waterValue (0), m_marginalValue (128), m_landValue (255), m_sensor ("ls8"), m_threshold (-1.0), // Flags auto-thresholding m_tolerance(0.0), m_algorithm(NDWI), m_thresholdMode(SIGMA), m_smoothing(0), m_noVector(false) { } ossimShorelineTool::~ossimShorelineTool() { } void ossimShorelineTool::setUsage(ossimArgumentParser& ap) { // Add global usage options. ossimChipProcTool::setUsage(ap); // Set the general usage: ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " shoreline [options] []"; au->setCommandLineUsage(usageString); au->setDescription("Computes vector shoreline from raster imagery. The vectors are output " "in GeoJSON format. If an output filename is specified, the JSON is written to it. " "Otherwise it is written to the console. The supported algorithms are (where A, B, etc are ordered input band files): \n" " NDWI = (A - B) / (A + B) \n" " AWEI = 4*(A + B) - 0.25*C - 2.75*D \n" " PAN-THRESHOLD = A (no equation applied). The input single-band image is thresholded directly. \n"); // Set the command line options: au->addCommandLineOption("--algorithm ", "Specifies detection algorithm to apply. Supported names are: " "\"ndwi\", \"aewi\", \"pan-threshold\""); au->addCommandLineOption("--color-coding ", "Specifies the pixel values (0-255) for the output product corresponding to water, marginal, " "and land zones. Defaults to 0, 128, and 255, respectively."); au->addCommandLineOption("--no-vector", "Outputs the raster, thresholded indexed image instead of a vector product. For engineering purposes."); au->addCommandLineOption("--sensor ", "Sensor used to compute Modified Normalized Difference Water Index. Currently only " "\"ls8\" supported (default)."); au->addCommandLineOption("--smooth ", "Applies gaussian filter to index raster file. The filter sigma must be specified (0.2 is good). Sigma=0 " "indicates no smoothing."); au->addCommandLineOption("--threshold <0.0-1.0>", "Normalized threshold for converting the image to bitmap. Defaults to 0.55. If none specified, an optimized threshold" " is computed."); au->addCommandLineOption("--tmode <1|2|3>", "Mode to use for computing threshold from k-means statistics, where:\n" " 0 = no auto-thresholding,\n" " 1 = unweighted mean of means,\n" " 2 = sigma-weighted mean of means (default),\n" " 3 = variance-weighted mean of means." "If \"--threshold\" option is specified, this option is ignored.\n"); au->addCommandLineOption("--tolerance ", "tolerance +- deviation from threshold for marginal classifications. Defaults to 0.01."); } bool ossimShorelineTool::initialize(ossimArgumentParser& ap) { if (!ossimChipProcTool::initialize(ap)) return false; if (m_helpRequested) return true; ossimString ts1; ossimArgumentParser::ossimParameter sp1(ts1); ossimString ts2; ossimArgumentParser::ossimParameter sp2(ts2); ossimString ts3; ossimArgumentParser::ossimParameter sp3(ts3); if ( ap.read("--algorithm", sp1)) m_kwl.addPair(ALGORITHM_KW, ts1); if (ap.read("--color-coding", sp1, sp2, sp3)) { ostringstream value; value<(ts1.before(":"), ts1.after(":"))); } // Fake the base class into thinking there is a default output filename to avoid it complaining, // since this utility will stream vector output to console if no output file name provided: m_kwl.add( ossimKeywordNames::OUTPUT_FILE_KW, DUMMY_OUTPUT_FILENAME.c_str()); processRemainingArgs(ap); return true; } void ossimShorelineTool::initialize(const ossimKeywordlist& kwl) { ossimString value; ostringstream xmsg; // Don't copy KWL if member KWL passed in: if (&kwl != &m_kwl) { // Start with clean options keyword list. m_kwl.clear(); m_kwl.addList( kwl, true ); } value = m_kwl.findKey(ALGORITHM_KW); if (!value.empty()) { if (value=="ndwi") m_algorithm = NDWI; else if (value=="awei") m_algorithm = AWEI; else if (value=="pan-threshold") m_algorithm = PAN_THRESHOLD; else { xmsg<<"ossimShorelineUtil:"<<__LINE__<<" Bad value encountered for keyword <" <."; throw ossimException(xmsg.str()); } } value = m_kwl.findKey(COLOR_CODING_KW); if (!value.empty()) { vector values = value.split(" "); if (values.size() == 3) { m_waterValue = values[0].toUInt8(); m_marginalValue = values[1].toUInt8(); m_landValue = values[2].toUInt8(); } else { xmsg<<"ossimShorelineUtil:"<<__LINE__<<" Unexpected number of values encountered for keyword <" <."; throw ossimException(xmsg.str()); } } value = m_kwl.find(ossimKeywordNames::SENSOR_ID_KW); if (!value.empty()) m_sensor = value; value = m_kwl.findKey(SMOOTHING_KW); if (!value.empty()) m_smoothing = value.toDouble(); value = m_kwl.findKey(TMODE_KW); if (!value.empty()) { int tmode = value.toInt(); if ((tmode >= 0) && (tmode <= 4)) m_thresholdMode = (ThresholdMode) tmode; } value = m_kwl.findKey(THRESHOLD_KW); if (!value.empty()) { m_threshold = value.toDouble(); m_thresholdMode = VALUE; } value = m_kwl.findKey(TOLERANCE_KW); if (!value.empty()) m_tolerance = value.toDouble(); // Output filename specifies the vector output, while base class interprets as raster, correct: m_vectorFilename = m_kwl.find(ossimKeywordNames::OUTPUT_FILE_KW); if (m_vectorFilename == DUMMY_OUTPUT_FILENAME) { m_vectorFilename = ""; m_indexFilename = TEMP_INDEX_FILENAME; m_threshFilename = TEMP_THRESHOLD_FILENAME; m_maskFilename = TEMP_MASK_FILENAME; } else { m_indexFilename = m_vectorFilename.fileNoExtension() + "_index.tif"; m_threshFilename = m_vectorFilename.fileNoExtension() + "_thresh.tif"; m_maskFilename = m_vectorFilename.fileNoExtension() + "_mask.tif"; } m_kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, m_indexFilename.chars()); // Unless an output projection was specifically requested, use the input: m_kwl.add(ossimKeywordNames::PROJECTION_KW, "identity", false); ossimChipProcTool::initialize(kwl); } void ossimShorelineTool::initProcessingChain() { // The processing chain to produce the index image is assembled here. The thresholding part is // done during execute(). ostringstream xmsg; if (m_aoiGroundRect.hasNans() || m_aoiViewRect.hasNans()) { xmsg<<"ossimShorelineUtil:"<<__LINE__<<" Encountered NaNs in AOI."< eqFilter = new ossimEquationCombiner(connectable_list); eqFilter->setOutputScalarType(OSSIM_NORMALIZED_DOUBLE); eqFilter->setEquation(equationSpec); m_procChain->add(eqFilter.get()); } else { // Just add input connection for pan thresholding: m_procChain->add(m_imgLayers[0].get()); } if (m_smoothing > 0) { // Set up gaussian filter: ossimRefPtr smoother = new ossimImageGaussianFilter; smoother->setGaussStd(m_smoothing); m_procChain->add(smoother.get()); } return; } ossimRefPtr ossimShorelineTool::getChip(const ossimIrect& bounding_irect) { // NOTE: // getChip only performs the index and thresholding (and possibly edge). For vector output, // execute must be called. ostringstream xmsg; if (!m_geom.valid()) return 0; m_aoiViewRect = bounding_irect; m_geom->setImageSize( m_aoiViewRect.size() ); m_geom->localToWorld(m_aoiViewRect, m_aoiGroundRect); return m_procChain->getTile( m_aoiViewRect, 0 ); } bool ossimShorelineTool::execute() { if (m_helpRequested) return true; bool status = true; // Base class handles the thresholded image generation. May throw exception. Output written to // m_productFilename. Note that if PAN mode selected, there is no intermediate index file: m_productFilename = m_indexFilename; if ((m_algorithm != PAN_THRESHOLD) && !ossimChipProcTool::execute()) return false; if (m_thresholdMode != NONE) doThreshold(); else return true; if (m_noVector) return status; // Now for vector product, need services of a plugin utility. Check if available: ossimRefPtr potrace = ossimToolRegistry::instance()->createTool(string("potrace")); if (!potrace.valid()) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimShorelineUtil:"<<__LINE__<<" Need the " "ossim-potrace plugin to perform vectorization. Only the thresholded image is " "available at <"<."<add(m_imgLayers[0].get()); if (m_smoothing > 0) { // Set up gaussian filter: ossimRefPtr smoother = new ossimImageGaussianFilter; smoother->setGaussStd(m_smoothing); m_procChain->add(smoother.get()); } ossimRefPtr eroder = new ossimErosionFilter; eroder->setWindowSize(10); m_procChain->add(eroder.get()); m_procChain->initialize(); m_productFilename = m_maskFilename; status = ossimChipProcTool::execute(); // generates mask if (m_productFilename.ext() != "JSON") m_productFilename = m_vectorFilename.setExtension("json"); // Convey possible redirection of console out: potrace->setOutputStream(m_consoleStream); ossimKeywordlist potrace_kwl; potrace_kwl.add("image_file0", m_threshFilename.chars()); potrace_kwl.add("image_file1", m_maskFilename.chars()); potrace_kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, m_productFilename.chars()); potrace_kwl.add("mode", "linestring"); potrace_kwl.add("alphamax", "1.0"); potrace_kwl.add("turdsize", "4"); potrace->initialize(potrace_kwl); status = potrace->execute(); #if OSSIM_HAS_JSONCPP if (status) status = addPropsToJSON(); #endif if (status) ossimNotify(ossimNotifyLevel_INFO)<<"Wrote vector product to <"<"<"< indexImage = ossimImageHandlerRegistry::instance()->open(m_indexFilename); if (!indexImage.valid()) { xmsg<<"ossimShorelineUtil:"<<__LINE__<<" Error encountered reading index image at <" <."; throw ossimException(xmsg.str()); } m_procChain->add(indexImage.get()); } // Some form of auto-thresholding was specified: if (m_thresholdMode != VALUE) autoComputeThreshold(); // Set up threshold filter using a simple LUT remapper: double del = FLT_EPSILON; ossimString landValue = ossimString::toString(m_landValue).chars(); ossimString waterValue = ossimString::toString(m_waterValue).chars(); ossimString marginalValue = ossimString::toString(m_marginalValue).chars(); ossimString thresholdValueLo1 = ossimString::toString(m_threshold-m_tolerance, 9).chars(); ossimString thresholdValueLo2 = ossimString::toString(m_threshold-m_tolerance+del, 9).chars(); ossimString thresholdValueHi1 = ossimString::toString(m_threshold+m_tolerance, 9).chars(); ossimString thresholdValueHi2 = ossimString::toString(m_threshold+m_tolerance+del, 9).chars(); ossimKeywordlist remapper_kwl; remapper_kwl.add("type", "ossimBandLutFilter"); remapper_kwl.add("enabled", "1"); remapper_kwl.add("mode", "interpolated"); remapper_kwl.add("scalar_type", "U8"); remapper_kwl.add("entry0.in", "0.0"); remapper_kwl.add("entry0.out", landValue.chars()); remapper_kwl.add("entry1.in", thresholdValueLo1.chars()); remapper_kwl.add("entry1.out", landValue.chars()); if (m_tolerance == 0) { remapper_kwl.add("entry2.in", thresholdValueLo2.chars()); remapper_kwl.add("entry2.out", waterValue.chars()); remapper_kwl.add("entry3.in", "1.0"); remapper_kwl.add("entry3.out", waterValue.chars()); } else { remapper_kwl.add("entry2.in", thresholdValueLo2.chars()); remapper_kwl.add("entry2.out", marginalValue.chars()); remapper_kwl.add("entry3.in", thresholdValueHi1.chars()); remapper_kwl.add("entry3.out", marginalValue.chars()); remapper_kwl.add("entry4.in", thresholdValueHi2.chars()); remapper_kwl.add("entry4.out", waterValue.chars()); remapper_kwl.add("entry5.in", "1.0"); remapper_kwl.add("entry5.out", waterValue.chars()); } ossimRefPtr remapper = new ossimBandLutFilter; remapper->loadState(remapper_kwl); m_procChain->add(remapper.get()); m_productFilename = m_threshFilename; if (!ossimChipProcTool::execute()) { xmsg<<"ossimShorelineUtil:"<<__LINE__<<" Error encountered creating threshold image at <" <."; throw ossimException(xmsg.str()); } } void ossimShorelineTool::autoComputeThreshold() { // Use the K-means classifier to determine the threshold point based on the histogram clustering // into two groups: land and water. // If an input histogram was provided, use it. Otherwise compute one: ossimImageHandler* handler = dynamic_cast(m_procChain->getFirstSource()); ostringstream xmsg; if (!handler) { xmsg<<"ossimShorelineUtil:"<<__LINE__<<" No input handler in procession chain."; throw ossimException(xmsg.str()); } ossimRefPtr multi_histo = handler->getImageHistogram(); if (!multi_histo.valid()) { xmsg<<"ossimShorelineUtil:"<<__LINE__<<" Could not establish an index histogram."; throw ossimException(xmsg.str()); } ossimRefPtr band_histo = multi_histo->getHistogram(0); if (!band_histo.valid()) { xmsg<<"ossimShorelineUtil:"<<__LINE__<<" Null band histogram returned!"; throw ossimException(xmsg.str()); } ossimRefPtr classifier = new ossimKMeansClustering; //classifier->setVerbose(); // TODO: Remove verbose mode classifier->setNumClusters(2); classifier->setSamples(band_histo->GetVals(), band_histo->GetRes()); classifier->setPopulations(band_histo->GetCounts(), band_histo->GetRes()); if (!classifier->computeKmeans()) { xmsg<<"ossimShorelineUtil:"<<__LINE__<<" K-means clustering of histogram failed. Cannot " "auto-compute threshold point."; throw ossimException(xmsg.str()); } double mean0 = classifier->getMean(0); double mean1 = classifier->getMean(1); double sigma0 = classifier->getSigma(0); double sigma1 = classifier->getSigma(1); switch (m_thresholdMode) { case MEAN: m_threshold = (mean0 + mean1)/2.0; break; case SIGMA: m_threshold = (sigma1*mean0 + sigma0*mean1)/(sigma0 + sigma1); break; case VARIANCE: m_threshold = (sigma1*sigma1*mean0 + sigma0*sigma0*mean1)/(sigma0*sigma0 + sigma1*sigma1); break; default: break; } cout.precision(8); cout<<"ossimShorelineUtil::autoComputeThreshold(): Using threshold = "< bool ossimShorelineTool::addPropsToJSON() { // Read existing JSON file as output by potrace: Json::Value root; std::ifstream jsonFile (m_vectorFilename.chars(), std::ifstream::binary); if (jsonFile.fail() || jsonFile.eof()) return false; jsonFile >> root; jsonFile.close(); // Add OSSIM-specific properties: Json::Value properties(Json::objectValue); properties["ossim-version"] = OSSIM_VERSION; properties["commit"] = OSSIM_REVISION; properties["build_date"] = OSSIM_BUILD_DATE; switch (m_algorithm) { case NDWI: properties["algorithm"] = "NDWI"; break; case AWEI: properties["algorithm"] = "AWEI"; break; default: properties["algorithm"] = "UNKNOWN"; } Json::Value fnames(Json::arrayValue); for (ossim_uint32 f=0; fgetFilename().chars()); fnames.append(fname); } properties["input_files"] = fnames; // Add additional properties provided in the command line: map::iterator prop = m_geoJsonProps.begin(); while (prop != m_geoJsonProps.end()) { properties[prop->first.chars()] = prop->second.chars(); ++prop; } Json::Value& features = root["features"]; int n = features.size(); for (int i=0; i #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; const char* ossimSlopeTool::DESCRIPTION = "Utility for computing the slope at each elevation post and generating " "a corresponding slope image."; ossimSlopeTool::ossimSlopeTool() : m_recursiveCall (false) { } ossimSlopeTool::~ossimSlopeTool() { } void ossimSlopeTool::setUsage(ossimArgumentParser& ap) { // Add options. ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " slope [options] "; au->setCommandLineUsage(usageString); // Set the command line options: au->setDescription(DESCRIPTION); // Base class has its own: ossimChipProcTool::setUsage(ap); } bool ossimSlopeTool::initialize(ossimArgumentParser& ap) { if (!ossimChipProcTool::initialize(ap)) return false; if (m_helpRequested) return true; processRemainingArgs(ap); return true; } void ossimSlopeTool::initialize(const ossimKeywordlist& kwl) { // Base class does the heavy work: ossimChipProcTool::initialize(kwl); } void ossimSlopeTool::initProcessingChain() { ostringstream key; // Reinitialization needs to skip this method if called recursively: if (m_recursiveCall) return; // Need to establish list of DEM cells given either the bounding rect or explicit DEM cells: if (m_demSources.empty()) { // Query elevation manager for cells providing needed coverage: std::vector cells; ossimElevManager::instance()->getCellsForBounds(m_aoiGroundRect, cells); // Insert the list of DEM cells into the KWL as input images: ossimConnectableObject::ConnectableObjectList elevChains; for(ossim_uint32 idx=0; idx combiner = combineLayers(m_imgLayers); m_procChain->add(combiner.get()); // Finally add the slope filter: ossimRefPtr slope_filter = new ossimSlopeFilter; slope_filter->setSlopeType(ossimSlopeFilter::NORMALIZED); m_procChain->add(slope_filter.get()); } ossim-Miami-2.9.1/src/util/ossimSubImageTool.cpp000066400000000000000000000223401352751253100215710ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; const char* ossimSubImageTool::DESCRIPTION = "Tool for extracting a sub-image from a full image." " No reprojection is done. Presently, the subimage geometry is represented by an RPC " "replacement model until generic models can support subimage chipping."; const char* BBOX_KW = "bbox"; ossimSubImageTool::ossimSubImageTool() : m_geomFormat (OGEOM) { } ossimSubImageTool::~ossimSubImageTool() { } void ossimSubImageTool::setUsage(ossimArgumentParser& ap) { // Add options. ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " subimage [options] "; au->setCommandLineUsage(usageString); // Set the command line options: au->setDescription(DESCRIPTION); // Base class has its own. Skip the ossimChipProcTool usage as that adds a lot of view-space // specific stuff not used in this tool: ossimTool::setUsage(ap); au->addCommandLineOption( "--bbox ", "Specify upper-left and lower-right bounds the image rect (in pixels)."); au->addCommandLineOption( "-e | --entry ", "For multi image entries which entry do you wish to extract. For list " "of entries use: \"ossim-info -i \" "); au->addCommandLineOption( "--geom ", "Specifies format of the subimage RPC geometry file." " Possible values are: \"OGEOM\" (OSSIM geometry, default), \"DG\" (DigitalGlobe WV/QB " ".RPB format), \"JSON\" (MSP-style JSON), or \"XML\". Case insensitive."); } bool ossimSubImageTool::initialize(ossimArgumentParser& ap) { if (!ossimTool::initialize(ap)) return false; if (m_helpRequested) return true; string tempString1; ossimArgumentParser::ossimParameter stringParam1(tempString1); string tempString2; ossimArgumentParser::ossimParameter stringParam2(tempString2); string tempString3; ossimArgumentParser::ossimParameter stringParam3(tempString3); string tempString4; ossimArgumentParser::ossimParameter stringParam4(tempString4); double tempDouble1; ossimArgumentParser::ossimParameter doubleParam1(tempDouble1); double tempDouble2; ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); vector paramList; ossim_uint32 readerPropIdx = 0; ossim_uint32 writerPropIdx = 0; ostringstream keys; if ( ap.read("--bbox", stringParam1, stringParam2, stringParam3, stringParam4)) { ostringstream ostr; ostr< specified. Aborting." << endl; throw ossimException( errMsg.str() ); } } processRemainingArgs(ap); return true; } void ossimSubImageTool::initialize(const ossimKeywordlist& kwl) { m_productFilename = m_kwl.find(ossimKeywordNames::OUTPUT_FILE_KW); // Init chain with handler: ostringstream key; key< handler = ossimImageHandlerRegistry::instance()->open(fname, true, false); if (!handler) { ostringstream errMsg; errMsg<<"ERROR: ossimSubImageTool ["<<__LINE__<<"] Could not open <"<"<setCurrentEntry( entryIndex )) { ostringstream errMsg; errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] Entry " << entryIndex << " out of range!" << endl; throw ossimException( errMsg.str() ); } m_procChain->add(handler.get()); // And finally the bounding rect: ossimString lookup = m_kwl.find(BBOX_KW); lookup.trim(); vector substrings = lookup.split(", ", true); if (substrings.size() != 4) { ostringstream errMsg; errMsg << "ossimSubImageTool ["<<__LINE__<<"] Incorrect number of values specified for bbox!"; throw( ossimException(errMsg.str()) ); } int ulx = substrings[0].toInt32(); int uly = substrings[1].toInt32(); int lrx = substrings[2].toInt32(); int lry = substrings[3].toInt32(); // Check for swap: if ( ulx > lrx ) { int tmpF = ulx; ulx = lrx; lrx = tmpF; } if ( uly > lry ) { int tmpF = uly; uly = lry; lry = tmpF; } // Use of view rect here is same as image space since there is no renderer: m_aoiViewRect.set_ul(ossimIpt(ulx, uly)); m_aoiViewRect.set_lr(ossimIpt(lrx, lry)); m_needCutRect = true; finalizeChain(); } bool ossimSubImageTool::execute() { // Compute RPC representation of subimage: ossimRefPtr inputGeom = m_procChain->getImageGeometry(); if (!inputGeom || !inputGeom->getProjection()) { ostringstream errMsg; errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] Null projection returned for input " "image!" << endl; throw ossimException( errMsg.str() ); } ossimRefPtr inputProj = inputGeom->getProjection(); ossimRefPtr rpc; ossimRefPtr solver = new ossimRpcSolver(false); bool converged = false; // If the input projection itself is an RPC, just copy it. No solving required: ossimRpcModel* inputRpc = dynamic_cast(inputGeom->getProjection()); if (inputRpc) rpc = inputRpc; else { converged = solver->solve(m_aoiViewRect, inputGeom.get()); rpc = solver->getRpcModel(); } // The RPC needs to be shifted in image space so that it will work in the subimage coordinates: rpc->setImageOffset(m_aoiViewRect.ul()); m_geom = new ossimImageGeometry(nullptr, rpc.get()); m_geom->setImageSize(m_aoiViewRect.size()); ossimKeywordlist kwl; m_geom->saveState(kwl); bool success = ossimChipProcTool::execute(); if (!success) return false; // Need to save the subimage RPC data: bool write_ok = false; ossimFilename geomFile (m_productFilename); if (m_geomFormat == OGEOM) // Default case if none specified { geomFile.setExtension("geom"); write_ok = kwl.write(geomFile); } else if (m_geomFormat == JSON) { #if OSSIM_HAS_JSONCPP geomFile.setExtension("json"); ofstream jsonStream (geomFile.string()); if (!jsonStream.fail()) { // Note that only the model/projection is saved here, not the full ossimImageGeometry that // contains the subimage shift transform. So need to cheat and add the shift to the RPC // line and sample offsets: write_ok = rpc->toJSON(jsonStream); jsonStream.close(); } #else ostringstream errMsg; errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] JSON geometry output requested but JSON is not " "available in this build! <" << endl; throw ossimException( errMsg.str() ); #endif } else if (m_geomFormat == DG) { geomFile.setExtension("RPB"); ofstream rpbStream (geomFile.string()); if (!rpbStream.fail()) { write_ok = rpc->toRPB(rpbStream); rpbStream.close(); } } else if (m_geomFormat == XML) { geomFile.setExtension("xml"); ossimXmlDocument xmlDocument; xmlDocument.fromKwl(kwl); write_ok = xmlDocument.write(geomFile); } if (write_ok) ossimNotify(ossimNotifyLevel_INFO) << "Wrote geometry file to <"<.\n" << endl; else { ossimNotify(ossimNotifyLevel_FATAL) << "Error encountered writing output RPC geometry file." << std::endl; return false; } return true; } ossim-Miami-2.9.1/src/util/ossimTool.cpp000066400000000000000000000102231352751253100201510ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include using namespace std; ossimTool::ossimTool() : m_kwl(), m_consoleStream (&cout), m_helpRequested (false) { } ossimTool::~ossimTool() { } void ossimTool::clear() { } void ossimTool::abort() { } ossimString ossimTool::getClassName() const { return "ossimTool"; } void ossimTool::setUsage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); std::string appName = ap.getApplicationName(); ossimApplicationUsage* au = ap.getApplicationUsage(); au->setApplicationName( ossimString( appName ) ); au->addCommandLineOption( "--write-api ", "Writes a JSON API specification to the specified filename."); au->addCommandLineOption( "--write-template ", "Writes a template keyword-list to the specified filename."); } bool ossimTool::initialize(ossimArgumentParser& ap) { m_helpRequested = false; setUsage(ap); if (ap.read("-h") || ap.read("--help") ) { // Write usage. ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); m_helpRequested = true; return true; } std::string ts1; ossimArgumentParser::ossimParameter sp1(ts1); if ( ap.read("--write-api", sp1)) { ofstream ofs ( ts1.c_str() ); ossimString json_str; getAPI(json_str); ofs << json_str < preferencesKWL().findKey( std::string( "ossim_share_directory" ) ); ossimFilename classTemplate = "util/" + getClassName() + ".kwl"; ossimFilename kwl_path = share_dir.dirCat( classTemplate ); if (!kwl.addFile(kwl_path)) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimTool::getKwlTemplate() -- Could not find <" <. Ignoring"< preferencesKWL().findKey( std::string( "ossim_share_directory" ) ); ossimFilename classJson = "util/" + getClassName() + ".json"; ossimFilename json_path = share_dir.dirCat( classJson ); readTextFile(json_path, json); } string ossimTool::getAPI() const { string result; getAPI(result); return result; } bool ossimTool::readTextFile(const ossimFilename& filename, string& contents) const { contents.clear(); std::ifstream is(filename.chars()); if (!is) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimTool::readTextFile() -- Could not find <" <. Ignoring."< #include #include #include #include #include #include #include #include #include #include #include #include #include #if OSSIM_HAS_HDF5 #include #endif using namespace std; ossimToolFactory* ossimToolFactory::s_Instance = 0; ossimToolFactory* ossimToolFactory::instance() { if (!s_Instance) s_Instance = new ossimToolFactory; return s_Instance; } ossimToolFactory::ossimToolFactory() { } ossimToolFactory::~ossimToolFactory() { ossimToolRegistry::instance()->unregisterFactory(this); } ossimTool* ossimToolFactory::createTool(const std::string& argName) const { ossimString utilName (argName); utilName.downcase(); if ((utilName == "info") || (argName == "ossimInfo")) return new ossimInfo; if ((utilName == "hillshade") || (argName == "ossimHillshadeTool")) return new ossimHillshadeTool; if ((utilName == "viewshed") || (argName == "ossimViewshedTool")) return new ossimViewshedTool; if ((utilName == "slope") || (argName == "ossimSlopeTool")) return new ossimSlopeTool; if ((utilName == "hlz") || (argName == "ossimHlzTool")) return new ossimHlzTool; if ((utilName == "shoreline") || (argName == "ossimShorelineTool")) return new ossimShorelineTool; if ((utilName == "ortho") || (argName == "ossimOrthoTool")) return new ossimOrthoTool; if ((utilName == "vertices") || (argName == "ossimVerticesFinderTool")) return new ossimVerticesFinderTool; if ((utilName == "bandmerge") || (argName == "ossimBandMergeTool")) return new ossimBandMergeTool; if ((utilName == "subimage") || (argName == "ossimSubImageTool")) return new ossimSubImageTool; if ((utilName == "pointcloud") || (argName == "ossimPointCloudTool")) return new ossimPointCloudTool; if ((utilName == "remap") || (argName == "ossimRemapTool")) return new ossimRemapTool; #if OSSIM_HAS_HDF5 if ((utilName == "hdf5") || (argName == "ossimHdf5Tool")) return new ossimHdf5Tool; #endif return 0; } void ossimToolFactory::getCapabilities(std::map& capabilities) const { capabilities.insert(pair("info", ossimInfo::DESCRIPTION)); capabilities.insert(pair("hillshade", ossimHillshadeTool::DESCRIPTION)); capabilities.insert(pair("viewshed", ossimViewshedTool::DESCRIPTION)); capabilities.insert(pair("slope", ossimSlopeTool::DESCRIPTION)); capabilities.insert(pair("hlz", ossimHlzTool::DESCRIPTION)); capabilities.insert(pair("shoreline", ossimShorelineTool::DESCRIPTION)); capabilities.insert(pair("ortho", ossimOrthoTool::DESCRIPTION)); capabilities.insert(pair("vertices", ossimVerticesFinderTool::DESCRIPTION)); capabilities.insert(pair("bandmerge", ossimBandMergeTool::DESCRIPTION)); capabilities.insert(pair("subimage", ossimSubImageTool::DESCRIPTION)); capabilities.insert(pair("pointcloud", ossimPointCloudTool::DESCRIPTION)); capabilities.insert(pair("remap", ossimRemapTool::DESCRIPTION)); #if OSSIM_HAS_HDF5 capabilities.insert(pair("hdf5", ossimHdf5Tool::DESCRIPTION)); #endif } std::map ossimToolFactory::getCapabilities() const { std::map result; getCapabilities(result); return result; } void ossimToolFactory::getTypeNameList(vector& typeList) const { typeList.push_back("ossimInfo"); typeList.push_back("ossimHillshadeUtil"); typeList.push_back("ossimViewshedUtil"); typeList.push_back("ossimSlopeUtil"); typeList.push_back("ossimHLZUtil"); typeList.push_back("ossimShorelineUtil"); typeList.push_back("ossimOrthoUtil"); typeList.push_back("ossimVerticesFinderUtil"); typeList.push_back("ossimBandMergeUtil"); typeList.push_back("ossimSubImageTool"); typeList.push_back("ossimPointCloudTool"); typeList.push_back("ossimRemapTool"); #if OSSIM_HAS_HDF5 typeList.push_back("ossimHdf5Tool"); #endif } ossim-Miami-2.9.1/src/util/ossimToolRegistry.cpp000066400000000000000000000040341352751253100217050ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include using namespace std; ossimToolRegistry* ossimToolRegistry::s_instance = 0; ossimToolRegistry* ossimToolRegistry::instance() { if (!s_instance) s_instance = new ossimToolRegistry; return s_instance; } ossimToolRegistry::ossimToolRegistry() { registerFactory(ossimToolFactory::instance(), true); } ossimToolRegistry::~ossimToolRegistry() { } bool ossimToolRegistry::initialize() { return false; } void ossimToolRegistry::getCapabilities(map& capabilities) const { capabilities.clear(); ossimString name, descr; // Loop over all factories and get capabilities which is list of (name, descr) pairs for all // registered operations: vector::const_iterator iter = m_factoryList.begin(); while (iter != m_factoryList.end()) { (*iter)->getCapabilities(capabilities); ++iter; } } std::map ossimToolRegistry::getCapabilities() const { std::map result; getCapabilities(result); return result; } ossimTool* ossimToolRegistry::createTool(const std::string& argName) const { ossimTool* result = 0; vector::const_iterator iter = m_factoryList.begin(); while ((iter != m_factoryList.end()) && (!result)) { result = (*iter)->createTool(argName); ++iter; } return result; } void ossimToolRegistry::getTypeNameList(vector& typeList) const { typeList.clear(); vector::const_iterator iter = m_factoryList.begin(); while (iter != m_factoryList.end()) { (*iter)->getTypeNameList(typeList); ++iter; } } ossim-Miami-2.9.1/src/util/ossimVerticesFinderTool.cpp000066400000000000000000000121101352751253100230030ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; const char* ossimVerticesFinderTool::DESCRIPTION = "Utility for determining the active image corner vertices inside larger null-filled image " "rectangle."; ossimVerticesFinderTool::ossimVerticesFinderTool() : m_entryIndex (0) { } ossimVerticesFinderTool::~ossimVerticesFinderTool() { } void ossimVerticesFinderTool::setUsage(ossimArgumentParser& ap) { // Add options. ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " vertices [options] []"; au->setCommandLineUsage(usageString); // Set the command line options: au->setDescription(DESCRIPTION); // Base class has its own: ossimTool::setUsage(ap); au->addCommandLineOption("-e or --entry", " For multi image handlers which entry do you wish to extract. " "For list of entries use: \"ossim-info -i \" "); } bool ossimVerticesFinderTool::initialize(ossimArgumentParser& ap) { if (!ossimTool::initialize(ap)) return false; if (m_helpRequested) return true; std::string tempString1; ossimArgumentParser::ossimParameter stringParam1(tempString1); if ( ap.read("-e", stringParam1) || ap.read("--entry", stringParam1) ) m_kwl.addPair( std::string(ossimKeywordNames::ENTRY_KW), tempString1 ); cout< 1 ) { m_kwl.add( ossimKeywordNames::IMAGE_FILE_KW, ap[1]); ap.remove(1); } if ( ap.argc() > 1 ) { m_kwl.add( ossimKeywordNames::OUTPUT_FILE_KW, ap[1]); ap.remove(1); } if ( ap.argc() > 1 ) { ossimNotify(ossimNotifyLevel_NOTICE)<<"ossimVerticesFinderUtil:"<<__LINE__<<" Too many " "arguments provided on command line. Ignoring superfluous entries."; } initialize(m_kwl); return true; } void ossimVerticesFinderTool::initialize(const ossimKeywordlist& kwl) { ostringstream errMsg; // Don't copy KWL if member KWL passed in: if (&kwl != &m_kwl) { // Start with clean options keyword list. m_kwl.clear(); m_kwl.addList( kwl, true ); } m_inputFile = m_kwl.find( ossimKeywordNames::IMAGE_FILE_KW); m_outputFile = m_kwl.find( ossimKeywordNames::OUTPUT_FILE_KW); ossimString value = m_kwl.find( ossimKeywordNames::ENTRY_KW); if (!value.empty()) m_entryIndex = value.toUInt32(); // See if an LUT is requested: if (m_inputFile.empty() || !m_inputFile.isReadable()) { errMsg<<"ERROR ossimVerticesFinderUtil:"<<__LINE__<<" Input filename was not provided or " " file <"< is not readable. "< ih = ossimImageHandlerRegistry::instance()->open(m_inputFile); if (ih.valid()) { ih->setCurrentEntry(m_entryIndex); } else { errMsg<<"ERROR ossimVerticesFinderUtil:"<<__LINE__<<" Unsupported image file format for <" << m_inputFile<<">. Cannot open file."; throw ossimException(errMsg.str()); } // Give the image handler to the vertex extractor as an input source. ossimRefPtr ve = new ossimVertexExtractor(ih.get()); // Set the file name. ve->setOutputName(m_outputFile); // Set the area of interest to the full bounding rect of the source. ve->setAreaOfInterest(ih->getBoundingRect(0)); // Add a listener for the percent complete to standard output. ossimStdOutProgress prog(0, true); ve->addListener(&prog); // Start the extraction... bool success = ve->execute(); return success; } void ossimVerticesFinderTool::getKwlTemplate(ossimKeywordlist& kwl) { kwl.add(ossimKeywordNames::ENTRY_KW, ""); kwl.add(ossimKeywordNames::IMAGE_FILE_KW, ""); kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, ""); } ossim-Miami-2.9.1/src/util/ossimViewshedTool.cpp000066400000000000000000001040001352751253100216450ustar00rootroot00000000000000//***************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //***************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; const char* ossimViewshedTool::DESCRIPTION = "Computes bitmap image representing the viewshed from specified location using only " "DEM information."; static const string FOV_KW = "fov"; static const string HEIGHT_OF_EYE_KW = "height_of_eye"; static const string HORIZON_FILE_KW = "horizon_file"; static const string OBSERVER_KW = "observer"; static const string VISIBILITY_RADIUS_KW = "visibility_radius"; static const string RETICLE_SIZE_KW = "reticle_size"; static const string VIEWSHED_CODING_KW = "viewshed_coding"; static const string AOI_SIZE_METERS_KW = "aoi_size_meters"; static const string THREADS_KW = "threads"; ossimViewshedTool::ossimViewshedTool() : m_obsHgtAbvTer (1.5), m_visRadius (0.0), m_radials (0), m_obsInsideAoi (true), m_displayAsRadar (false), m_halfWindow (0), m_outBuffer (NULL), m_visibleValue (1), m_hiddenValue (128), m_overlayValue (255), m_reticleSize(25), m_simulation (false), m_numThreads(1), m_startFov(0), m_stopFov(0), m_threadBySector(false), d_accumT(0) { m_observerGpt.makeNan(); } ossimViewshedTool::~ossimViewshedTool() { if (m_radials) { for (int i=0; i<4; ++i) delete [] m_radials[i]; delete [] m_radials; } } void ossimViewshedTool::setUsage(ossimArgumentParser& ap) { // Set the general usage: ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString appName = ap.getApplicationName(); ossimString usageString = appName; usageString += " viewshed [options] "; au->setCommandLineUsage(usageString); // Set the command line options: au->addCommandLineOption( "--fov ", "Optional arguments specifying the field-of" "-view boundary azimuths (in degrees). By default, a 360 deg FOV is" " computed. The arc is taken clockwise from start to end, so for a" " FOV of 225 deg from W, through N to SE, start=270 and end=135"); au->addCommandLineOption( "--height-of-eye ", "Specifies the observers height-of-eye above the " "terrain in meters. Defaults to 1.5 m."); au->addCommandLineOption( "--horizon ", "Experimental. Outputs the max elevation angles " "for all azimuths to , for horizon profiling."); au->addCommandLineOption( "--radius ", "Specifies max visibility in meters. Required " "unless --size is specified. This option constrains output to a circle, " "similar to a radar display"); au->addCommandLineOption( "--reticle ", "Specifies the size of the reticle at the observer" "location in pixels from the center (i.e., the radius of the reticle). " "Defaults to 2. A value of 0 hides the reticle. See --values option for " "setting reticle color."); au->addCommandLineOption( "--simulation", "For engineering/debug purposes "); au->addCommandLineOption( "--tbs", "\"Thread By Sector\". For engineering/debug purposes "); au->addCommandLineOption( "--threads ", "Number of threads. Defaults to use all available cores. " "For engineering/debug purposes "); au->addCommandLineOption( "--viewshed-coding ", "Specifies the pixel values (0-255) for the visible," " hidden and overlay pixels, respectively. Defaults to visible=null (0), " "hidden=128, and overlay (observer position, reticle, and circumference) is " "highlighted with 255."); // Base class has its own: ossimChipProcTool::setUsage(ap); ostringstream description; description << DESCRIPTION << "\n\nExamples:\n\n" " "<setDescription(description.str()); } bool ossimViewshedTool::initialize(ossimArgumentParser& ap) { ostringstream xmsg; xmsg<<"ossimViewshedUtil::initialize(ossimArgumentParser) -- "; int numArgsExpected = 4; // Base class first: if (!ossimChipProcTool::initialize(ap)) return false; if (m_helpRequested) return true; string ts1; ossimArgumentParser::ossimParameter sp1(ts1); string ts2; ossimArgumentParser::ossimParameter sp2(ts2); string ts3; ossimArgumentParser::ossimParameter sp3(ts3); if ( ap.read("--fov", sp1, sp2) ) { double startFov = ossimString(ts1).toDouble(); if (startFov < 0) startFov += 360.0; ostringstream value; value< coordstr; value.split(coordstr, ossimString(" ,"), false); if (coordstr.size() == 2) { m_startFov = coordstr[0].toDouble(); m_stopFov = coordstr[1].toDouble(); if (m_startFov < 0) m_startFov += 360.0; } } value = kwl.findKey(HEIGHT_OF_EYE_KW); if (!value.empty()) m_obsHgtAbvTer = value.toDouble(); m_horizonFile = kwl.findKey(HORIZON_FILE_KW); value = kwl.findKey(OBSERVER_KW); if (!value.empty()) { vector coordstr; value.split(coordstr, ossimString(" ,"), false); if (coordstr.size() == 2) { m_observerGpt.lat = coordstr[0].toDouble(); m_observerGpt.lon = coordstr[1].toDouble(); m_observerGpt.hgt = 0.0; } } value = kwl.findKey(RETICLE_SIZE_KW); if (!value.empty()) m_reticleSize = value.toInt32(); value = kwl.findKey(VIEWSHED_CODING_KW); if (!value.empty()) { vector coordstr; value.split(coordstr, ossimString(" ,"), false); if (coordstr.size() == 3) { m_visibleValue = coordstr[0].toUInt8(); m_hiddenValue = coordstr[1].toUInt8(); m_overlayValue = coordstr[2].toUInt8(); } } value = kwl.findKey(VISIBILITY_RADIUS_KW); if (!value.empty()) { m_visRadius = value.toDouble(); m_displayAsRadar = true; } // If running simulation, clear out all pre-loaded elevation databases: if (m_simulation) { ossimElevManager::instance()->clear(); ossimElevManager::instance()->setUseGeoidIfNullFlag(false); } // Base class does most work: ossimChipProcTool::initialize(kwl); } void ossimViewshedTool::clear() { m_observerGpt.makeNan(); m_visRadius = 0; m_outBuffer = 0; m_horizonMap.clear(); m_jobMtQueue = 0; ossimChipProcTool::clear(); } void ossimViewshedTool::initializeProjectionGsd() { // First try normal base class initialization. If that doesn't work, then probably no DEM // or input images were provided, so need to use elev manager resoltion at observer point. ossimChipProcTool::initializeProjectionGsd(); if (!m_gsd.hasNans() || m_observerGpt.hasNans()) return; ossimMapProjection* proj = dynamic_cast(m_geom->getProjection()); if (!proj) return; ossimElevManager* elevMgr = ossimElevManager::instance(); elevMgr->getHeightAboveEllipsoid(m_observerGpt); m_gsd.x = m_gsd.y = ossimElevManager::instance()->getMeanSpacingMeters(); if (m_geoScaled) proj->setOrigin(m_observerGpt); proj->setMetersPerPixel(m_gsd); } void ossimViewshedTool::initializeAOI() { ossimChipProcTool::initializeAOI(); if (!m_aoiGroundRect.hasNans()) { // AOI established by base class, nothing to do except take this opportunity to set the // observer location to AOI center if not already defined: if (m_observerGpt.hasNans()) m_observerGpt = m_aoiGroundRect.midPoint(); return; } // Not enough info available to base class to determine AOI, maybe can determine from observer // position and radius: if ((m_visRadius == 0) && m_kwl.hasKey(AOI_SIZE_METERS_KW)) { ossimString lookup = m_kwl.findKey( AOI_SIZE_METERS_KW ); lookup.trim(); m_visRadius = 0.5*(lookup.before(" ").toDouble() + lookup.after(" ").toDouble()); m_displayAsRadar = true; } if (m_observerGpt.hasNans()) findCenterGpt(m_observerGpt); if ((m_visRadius != 0) && !m_observerGpt.hasNans()) { ossimMapProjection* proj = dynamic_cast(m_geom->getProjection()); if (!proj) return; ossimDpt metersPerDegree (m_observerGpt.metersPerDegree()); double dlat = m_visRadius/metersPerDegree.y; double dlon = m_visRadius/metersPerDegree.x; ossimGpt ulg (m_observerGpt.lat + dlat, m_observerGpt.lon - dlon); ossimGpt lrg (m_observerGpt.lat - dlat, m_observerGpt.lon + dlon); m_aoiGroundRect = ossimGrect(ulg, lrg); proj->setUlTiePoints(ulg); computeAdjustedViewFromGrect(); } } void ossimViewshedTool::initProcessingChain() { ostringstream xmsg; if (m_observerGpt.hasNans()) { xmsg<<"ossimViewshedUtil:"<<__LINE__<<" Observer ground position has not been set."<getHeightAboveEllipsoid(m_observerGpt); m_observerGpt.hgt += m_obsHgtAbvTer; m_geom->worldToLocal(m_observerGpt, m_observerVpt); ossimRefPtr mapProj = dynamic_cast(m_geom->getProjection()); // If no radius specified, need to compute R large enough to cover the requested AOI: if (m_visRadius == 0) computeRadius(); if (m_halfWindow == 0) m_halfWindow = ossim::round(m_visRadius/m_gsd.x); ossim_uint32 size = 2*m_halfWindow + 1; // If no AOI defined, just use the visibility rectangle: ossimIrect visRect (ossimIpt(m_observerVpt), size, size); if (m_aoiViewRect.hasNans()) { m_aoiViewRect = visRect; m_geom->localToWorld(ossimDrect(m_aoiViewRect), m_aoiGroundRect); m_geom->setImageSize(m_aoiViewRect.size()); } // Allocate the output image buffer: ossimIrect bufViewRect = visRect.clipToRect(m_aoiViewRect); if (bufViewRect.area() == 0) { xmsg<<"ossimViewshedUtil:"<<__LINE__<<" The requested AOI rect is outside the visibility range." << ends; throw ossimException(xmsg.str()); } m_outBuffer = ossimImageDataFactory::instance()-> create(0, OSSIM_UINT8, 1, m_aoiViewRect.width(), m_aoiViewRect.height()); if(!m_outBuffer.valid()) { xmsg<<"ossimViewshedUtil:"<<__LINE__<<" Output buffer allocation failed." << ends; throw ossimException(xmsg.str()); } m_outBuffer->setImageRectangle(m_aoiViewRect); // The processing chain for this class is simply a memory source containing the output buffer: m_memSource = new ossimMemoryImageSource; m_memSource->setImage(m_outBuffer); m_memSource->setImageGeometry(m_geom.get()); // If input image(s) provided, need to combine them with the product: if (m_imgLayers.empty()) { m_procChain->add(m_memSource.get()); } else { ossimRefPtr combiner = combineLayers(m_imgLayers); combiner->connectMyInputTo(m_memSource.get()); m_procChain->add(combiner.get()); } } ossimRefPtr ossimViewshedTool::getChip(const ossimIrect& bounding_irect) { cerr<<"ossimViewshedUtil:"<<__LINE__<setImageSize( m_aoiViewRect.size() ); m_geom->localToWorld(m_aoiViewRect, m_aoiGroundRect); cerr<<"ossimViewshedUtil:"<<__LINE__<getTile( m_aoiViewRect, 0 ); } // else: return 0; } bool ossimViewshedTool::execute() { if (m_helpRequested) return true; if (!computeViewshed()) return false; if (!m_horizonFile.empty() && writeHorizonProfile()) ossimNotify(ossimNotifyLevel_INFO) << "Wrote horizon profile to <"<" <create(0, OSSIM_UINT8, 1, m_aoiViewRect.width(), m_aoiViewRect.height()); ostringstream xmsg; if (!m_outBuffer.valid() || !m_memSource.valid()) { xmsg<<"ossimViewshedUtil:"<<__LINE__<<" Error encountered allocating output image buffer."; throw ossimException(xmsg.str()); } // Initialize the image with all points hidden: m_outBuffer->initialize(); m_outBuffer->setImageRectangle(m_aoiViewRect); m_outBuffer->fill(m_procChain->getNullPixelValue()); m_memSource->setImage(m_outBuffer); // Initialize the radials after intersecting the requested FOV with the FOV required to see the // full AOI (not applicable if observer inside AOI). Skip radial init if no intersection found: if (!optimizeFOV()) return false; initRadials(); // The viewshed process necessarily first fills the output buffer with the complete result before // the writer requests a tile. Control is passed later to the base class execute() for writing. d_accumT = 0; if (m_numThreads == 0) m_numThreads = ossim::getNumberOfThreads(); if (m_numThreads > 1) { std::shared_ptr jobQueue = std::make_shared(); for (int sector=0; sector<8; ++sector) { if (m_radials[sector] == 0) continue; if (m_threadBySector) { std::shared_ptr job = std::make_shared(this, sector, m_halfWindow); jobQueue->add(job, false); } else { for (ossim_uint32 r=0; r<=m_halfWindow; ++r) { std::shared_ptr job = std::make_shared(this, sector, r, m_halfWindow); jobQueue->add(job, false); } } if (needsAborting()) return 0; } ossimNotify(ossimNotifyLevel_INFO) << "\nSubmitting "<size()<<" jobs..."<(jobQueue, m_numThreads); // Wait until all radials have been processed before proceeding: ossimNotify(ossimNotifyLevel_INFO) << "Waiting for job threads to finish..."<hasJobsToProcess() || m_jobMtQueue->numberOfBusyThreads()) ossim::Thread::sleepInMicroSeconds(250); } else { // Unthreaded processing: ossimNotify(ossimNotifyLevel_INFO) << "\nProcessing radials (non-threaded)..."< spj = std::make_shared(this, sector, m_halfWindow); spj->start(); if (needsAborting()) return false; } // end loop over sectors } ossimNotify(ossimNotifyLevel_INFO) << "Finished processing radials."< m_aoiGroundRect.ul().lat) direction = (int) N; else if (m_observerGpt.lat < m_aoiGroundRect.ll().lat) direction = (int) S; if (m_observerGpt.lon < m_aoiGroundRect.ul().lon) direction += (int) W; else if (m_observerGpt.lon > m_aoiGroundRect.ur().lon) direction += (int) E; // Calculate start and stop FOV depending on region: double start, stop; switch ((CardinalDirections) direction) { case N: start = m_observerGpt.azimuthTo(m_aoiGroundRect.ur()); stop = m_observerGpt.azimuthTo(m_aoiGroundRect.ul()); break; case NE: start = m_observerGpt.azimuthTo(m_aoiGroundRect.lr()); stop = m_observerGpt.azimuthTo(m_aoiGroundRect.ul()); break; case E: start = m_observerGpt.azimuthTo(m_aoiGroundRect.lr()); stop = m_observerGpt.azimuthTo(m_aoiGroundRect.ur()); break; case SE: start = m_observerGpt.azimuthTo(m_aoiGroundRect.ll()); stop = m_observerGpt.azimuthTo(m_aoiGroundRect.ur()); break; case S: start = m_observerGpt.azimuthTo(m_aoiGroundRect.ll()); stop = m_observerGpt.azimuthTo(m_aoiGroundRect.lr()); break; case SW: start = m_observerGpt.azimuthTo(m_aoiGroundRect.ul()); stop = m_observerGpt.azimuthTo(m_aoiGroundRect.lr()); break; case W: start = m_observerGpt.azimuthTo(m_aoiGroundRect.ul()); stop = m_observerGpt.azimuthTo(m_aoiGroundRect.ll()); break; case NW: default: start = m_observerGpt.azimuthTo(m_aoiGroundRect.ur()); stop = m_observerGpt.azimuthTo(m_aoiGroundRect.ll()); break; } // Now need to intersect this arc with the requested FOV: if (m_startFov == m_stopFov) { // There was no requested FOV (i.e, FOV = 360). So use the optimized FOV straight away: m_startFov = start; m_stopFov = stop; intersects = true; } else { // Pick m_startFov as reference, and make sure all others are greater: double a1 = m_stopFov; double a2 = start; double a3 = stop; if (m_startFov > m_stopFov) a1 += 360; if (m_startFov > start) a2 += 360; if (m_startFov > stop) a3 += 360; // Map to sort remaining azimuths by increasing angle clockwise: map angle_map; angle_map.insert(pair(a1, 1)); angle_map.insert(pair(a2, 2)); angle_map.insert(pair(a3, 3)); map::iterator iter = angle_map.begin(); if (iter->second == 1) { ++iter; if (iter->second == 3) intersects = true; } else if (iter->second == 2) { m_startFov = start; intersects = true; ++iter; if (iter->second == 3) m_stopFov = stop; } else { intersects = true; m_stopFov = stop; } } if (!intersects) { ossimNotify(ossimNotifyLevel_INFO)<< "ossimViewshedUtil::optimizeFOV() -- No FOV intersection found. Nothing to do."< " < m_visRadius) m_visRadius = d; d = m_observerGpt.distanceTo(m_aoiGroundRect.lr()); if (d > m_visRadius) m_visRadius = d; d = m_observerGpt.distanceTo(m_aoiGroundRect.ll()); if (d > m_visRadius) m_visRadius = d; } void ossimViewshedTool::initRadials() { // All eaight sectors' radials have the same azimuths except that the abscissa and ordinate are // reversed between the N-S and E-W sectors, i.e., the N and S sectors use the y-axis as the // abscissa (u) and the x-axis is the ordinate (v). The azimuth (dv/du) is therefore DX/DY for // the north and south, while the azimuth is DY/DX for the east and west sectors. Nevertheless, // each sectors radials must be maintained separately as they contain the max elevation angle. // First determine which sectors are involved given the desired FOV: bool* sectorInFov = new bool[8]; memset(sectorInFov, false, 8); bool crossed_north = true; if (m_stopFov <= m_startFov) // Crosses 0 azimuth crossed_north = false; double azimuth = m_startFov; for (int i=0; (i < 8) && ((azimuth < m_stopFov) || !crossed_north); ++i) { if ((azimuth >= 0) && (azimuth < 45.0)) sectorInFov[0] = true; else if (azimuth < 90.0) sectorInFov[1] = true; else if (azimuth < 135.0) sectorInFov[2] = true; else if (azimuth < 180.0) sectorInFov[3] = true; else if (azimuth < 225.0) sectorInFov[4] = true; else if (azimuth < 270.0) sectorInFov[5] = true; else if (azimuth < 315.0) sectorInFov[6] = true; else if (azimuth < 360.0) sectorInFov[7] = true; azimuth += 45.0; if (azimuth > 360.0) { azimuth -= 360.0; crossed_north = true; } } // Compute the azimuth slopes for each radial in the sector. m_radials = new Radial* [8]; double du = m_halfWindow; for (int sector=0; sector<8; ++sector) { if (!sectorInFov[sector]) { m_radials[sector] = 0; continue; } ossim_uint32 ridx = 0; m_radials[sector] = new Radial [m_halfWindow+1]; for (ossim_int32 dv = 0; dv <= (ossim_int32) m_halfWindow; ++dv) { if (sector & 1) // odd-numbered sector, azimuths computed in reverse order m_radials[sector][m_halfWindow-ridx].azimuth = ((double)dv)/du; else m_radials[sector][ridx].azimuth = ((double)dv)/du; ++ridx; } } // Cleanup: delete [] sectorInFov; sectorInFov = 0; } void ossimViewshedTool::paintReticle() { if (m_reticleSize == 0) return; // Highlight the observer position with X reticle: ossimDpt obsViewPt; m_geom->worldToLocal(m_observerGpt, obsViewPt); if (m_aoiViewRect.pointWithin(ossimIpt(obsViewPt))) { for (int i=-m_reticleSize; i<=m_reticleSize; ++i) { if (m_aoiViewRect.pointWithin(ossimIpt(m_observerVpt.x + i, m_observerVpt.y))) m_outBuffer->setValue(m_observerVpt.x + i, m_observerVpt.y , m_overlayValue); if (m_aoiViewRect.pointWithin(ossimIpt(m_observerVpt.x, m_observerVpt.y + i))) m_outBuffer->setValue(m_observerVpt.x , m_observerVpt.y + i, m_overlayValue); } } // Paint boundary rectangle if no visibility radius painted: if (!m_displayAsRadar) { for (int y=m_aoiViewRect.ul().y; y<=m_aoiViewRect.lr().y; y++) { m_outBuffer->setValue(m_aoiViewRect.ul().x, y, m_overlayValue); m_outBuffer->setValue(m_aoiViewRect.lr().x, y, m_overlayValue); } for (int x=m_aoiViewRect.ul().x; x<=m_aoiViewRect.lr().x; x++) { m_outBuffer->setValue(x, m_aoiViewRect.ul().y, m_overlayValue); m_outBuffer->setValue(x, m_aoiViewRect.lr().y, m_overlayValue); } } } bool ossimViewshedTool::writeHorizonProfile() { // Store the max elevation angles for horizon profiling: double az_deg, arctan; for (ossim_uint32 sector=0; sector<8; ++sector) { if (m_radials[sector] == 0) continue; for (ossim_uint32 radial = 0; radial <= m_halfWindow; ++radial) { arctan = ossim::atand(m_radials[sector][radial].azimuth); switch (sector) { case 0: // 0 - 45 az_deg = arctan; break; case 1: // 45 - 90 az_deg = 90 - arctan; break; case 2: // 90 - 135 az_deg = 90 + arctan; break; case 3: // 135 - 180 az_deg = 180 - arctan; break; case 4: // 180 - 225 az_deg = 180 + arctan; break; case 5: // 225 - 270 az_deg = 270 - arctan; break; case 6: // 270 - 315 az_deg = 270 + arctan; break; case 7: // 315 - 360 az_deg = 360 - arctan; break; default: break; } m_horizonMap.insert(pair(az_deg, m_radials[sector][radial].elevation)); } } // Open output file and write the map: ofstream fstr (m_horizonFile.chars()); if (!fstr.is_open()) return false; map::iterator iter = m_horizonMap.begin(); while (iter != m_horizonMap.end()) { fstr << iter->first << ", " << iter->second << endl; ++iter; } fstr.close(); return true; } void SectorProcessorJob::run() { // Loop over all the sector's radials and walk over each one. for (ossim_uint32 r=0; r<=m_numRadials; ++r) { RadialProcessor::doRadial(m_vsUtil, m_sector, r); } } void RadialProcessorJob::run() { RadialProcessor::doRadial(m_vsUtil, m_sector, m_radial); } std::mutex RadialProcessor::m_bufMutex; void RadialProcessor::doRadial(ossimViewshedTool* vsUtil, ossim_uint32 sector_idx, ossim_uint32 radial_idx) { double u, v; ossimDpt pt_i, vpt_i; ossimGpt gpt_i; double elev_i, elev; double r2_max = vsUtil->m_halfWindow*vsUtil->m_halfWindow; // Establish shorthand access to radial: ossimViewshedTool::Radial& radial = vsUtil->m_radials[sector_idx][radial_idx]; // Walk along the radial using the appropriate coordinate abscissa for that sector and // compute ordinate using the radials azimuth: for (u=1.0; u <= (double) vsUtil->m_halfWindow; u += 1.0) { // Compute ordinate from abscissa and slope of this radial: v = radial.azimuth*(u); switch (sector_idx) { case 0: // N-NE, (u, v) = (-y, x) pt_i.y = -u; pt_i.x = v; break; case 1: // NE-E, (u, v) = (x, -y) pt_i.x = u; pt_i.y = -v; break; case 2: // E-SE, (u, v) = (x, y) pt_i.x = u; pt_i.y = v; break; case 3: // SE-S, (u, v) = (y, x) pt_i.y = u; pt_i.x = v; break; case 4: // S-SW, (u, v) = (y, -x) pt_i.y = u; pt_i.x = -v; break; case 5: // SW-W, (u, v) = (-x, y) pt_i.x = -u; pt_i.y = v; break; case 6: // W-NW, (u, v) = (-x, -y) pt_i.x = -u; pt_i.y = -v; break; case 7: // NW-N, (u, v) = (-y, -x) pt_i.y = -u; pt_i.x = -v; break; default: break; } // Shift to actual view coordinates: vpt_i = pt_i + vsUtil->m_observerVpt; ossimIpt ipt (vpt_i); // Check if alread accounted for at this location: //if (!vsUtil->m_outBuffer->isNull(vpt_i)) // continue; // Check if we are exiting the AOI (no more processing required for this radial): bool pointInsideAoi = vsUtil->m_aoiViewRect.pointWithin(ipt); if (radial.insideAoi && !pointInsideAoi) break; // Alternatively, check if we were OUTSIDE and now moving INSIDE: if (!radial.insideAoi && pointInsideAoi) radial.insideAoi = true; // Check if we passed beyong the visibilty radius, and exit loop if so: if (vsUtil->m_displayAsRadar && ((u*u + v*v) >= r2_max)) { vsUtil->m_outBuffer->setValue(ipt.x, ipt.y, vsUtil->m_overlayValue); break; } // Fetch the pixel value as the elevation value and compute elevation angle from // the observer pt as dz/dx vsUtil->m_geom->localToWorld(vpt_i, gpt_i); if (vsUtil->m_simulation && ossim::isnan(gpt_i.hgt)) gpt_i.hgt = vsUtil->m_observerGpt.hgt-vsUtil->m_obsHgtAbvTer; // ground level if (!gpt_i.hasNans()) { // Compare elev angle to max angle latched so far along this radial: elev_i = (gpt_i.hgt - vsUtil->m_observerGpt.hgt) / u; elev = radial.elevation; if (elev_i > elev) { // point is visible, latch this line-of-sight as the new max elevation angle for this // radial, and mark the output pixel as visible: radial.elevation = elev_i; vsUtil->m_outBuffer->setValue(ipt.x, ipt.y, vsUtil->m_visibleValue); } else { vsUtil->m_outBuffer->setValue(ipt.x, ipt.y, vsUtil->m_hiddenValue); } } } // end loop over radial's abscissas } void ossimViewshedTool::test() { m_aoiGroundRect = ossimGrect(1.0, 0.0, 0.0, 1.0); m_observerGpt = ossimGpt(1.5, 0.5); m_startFov = 180; m_stopFov = 270; cout<<"Before: m_startFov="< ossimVpfBoundingRecordTable::ossimVpfBoundingRecordTable() :ossimVpfTable() { } bool ossimVpfBoundingRecordTable::openTable(const ossimFilename& tableName) { bool result = false; theExtent = ossimVpfExtent(0,0,0,0); bool firstOneSetFlag = false; if(ossimVpfTable::openTable(tableName)) { ossim_int32 xminIdx = getColumnPosition("XMIN"); ossim_int32 yminIdx = getColumnPosition("YMIN"); ossim_int32 xmaxIdx = getColumnPosition("XMAX"); ossim_int32 ymaxIdx = getColumnPosition("YMAX"); if((xminIdx < 0)|| (yminIdx < 0)|| (xmaxIdx < 0)|| (ymaxIdx < 0)) { closeTable(); } else { if(getNumberOfRows() > 0) { result = true; reset(); ossim_int32 n = 1; ossim_float32 xmin; ossim_float32 ymin; ossim_float32 xmax; ossim_float32 ymax; row_type row; for(int rowIdx = 1; rowIdx < getNumberOfRows(); ++rowIdx) { if(rowIdx == 1) { row = read_row(rowIdx, *theTableInformation); } else { row = read_next_row(*theTableInformation); } get_table_element(xminIdx, row, *theTableInformation, &xmin, &n); get_table_element(yminIdx, row, *theTableInformation, &ymin, &n); get_table_element(xmaxIdx, row, *theTableInformation, &xmax, &n); get_table_element(ymaxIdx, row, *theTableInformation, &ymax, &n); if(!is_vpf_null_float(xmin)&& !is_vpf_null_float(ymin)&& !is_vpf_null_float(xmax)&& !is_vpf_null_float(ymax)) { if(!firstOneSetFlag) { theExtent = ossimVpfExtent(xmin, ymin, xmax, ymax); firstOneSetFlag = true; } else { theExtent = theExtent + ossimVpfExtent(xmin, ymin, xmax, ymax); } } free_row(row, *theTableInformation); } } } } return result; } void ossimVpfBoundingRecordTable::getExtent(ossimVpfExtent& extent)const { extent = theExtent; } ossim-Miami-2.9.1/src/vec/ossimVpfCoverage.cpp000066400000000000000000000116161352751253100212520ustar00rootroot00000000000000//******************************************************************* // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This class extends the stl's string class. // //******************************************************************** // $Id: ossimVpfCoverage.cpp 23244 2015-04-08 20:48:34Z rashadkm $ #include using namespace std; #include #include #include #include #include ossimVpfCoverage::ossimVpfCoverage() :theLibrary(NULL), theCoverageName(""), theCoverageNameFullPath("") { } ossimVpfCoverage::~ossimVpfCoverage() { theLibrary = NULL; } bool ossimVpfCoverage::openCoverage(ossimVpfLibrary* library, const ossimString& name, const ossimFilename& fullPath) { bool result = true; theCoverageName = name; theCoverageNameFullPath = fullPath; theLibrary = library; if(!theCoverageNameFullPath.dirCat("fcs").exists()) { result = false; } return result; } const ossimFilename& ossimVpfCoverage::getPath()const { return theCoverageNameFullPath; } const ossimString& ossimVpfCoverage::getName()const { return theCoverageName; } void ossimVpfCoverage::print(ostream& out)const { ossimVpfTable table; if(table.openTable(theCoverageNameFullPath.dirCat("fcs"))) { table.print(out); } } bool ossimVpfCoverage::getExtent(ossimVpfExtent& extent)const { bool result = false; bool firstOneSetFlag = false; ossimVpfExtent resultExtent; ossimVpfExtent tempExtent; if(theLibrary) { if(theCoverageNameFullPath.dirCat("ebr").exists()) { ossimVpfBoundingRecordTable boundingRecord; if(boundingRecord.openTable(theCoverageNameFullPath.dirCat("ebr"))) { boundingRecord.getExtent(tempExtent); resultExtent = tempExtent; firstOneSetFlag = true; result = true; } } if(theCoverageNameFullPath.dirCat("fbr").exists()) { ossimVpfBoundingRecordTable boundingRecord; if(boundingRecord.openTable(theCoverageNameFullPath.dirCat("fbr"))) { boundingRecord.getExtent(tempExtent); if(!firstOneSetFlag) { resultExtent = tempExtent; firstOneSetFlag = true; } else { resultExtent = resultExtent + tempExtent; } result = true; } } std::vector tileNames; theLibrary->getTileNames(tileNames); for(int i = 0; i < (int)tileNames.size(); ++i) { ossimFilename tileName = tileNames[0]; ossimFilename tileDir; if(theCoverageNameFullPath.dirCat(tileName).exists()) { tileDir = theCoverageNameFullPath.dirCat(tileName); } else if(theCoverageNameFullPath.dirCat(tileName.downcase()).exists()) { tileDir = theCoverageNameFullPath.dirCat(tileName.downcase()); } if(tileDir != "") { if(tileDir.dirCat("ebr").exists()) { ossimVpfBoundingRecordTable boundingRecord; if(boundingRecord.openTable(tileDir.dirCat("ebr"))) { boundingRecord.getExtent(tempExtent); if(!firstOneSetFlag) { resultExtent = tempExtent; firstOneSetFlag = true; } else { resultExtent = resultExtent + tempExtent; } result = true; } } if(tileDir.dirCat("fbr").exists()) { ossimVpfBoundingRecordTable boundingRecord; if(boundingRecord.openTable(tileDir.dirCat("fbr"))) { boundingRecord.getExtent(tempExtent); if(!firstOneSetFlag) { resultExtent = tempExtent; firstOneSetFlag = true; } else { resultExtent = resultExtent + tempExtent; } result = true; } } } } } extent = resultExtent; return result; } ossimVpfLibrary* ossimVpfCoverage::getLibrary() { return theLibrary; } bool ossimVpfCoverage::openFeatureClassSchema(ossimVpfFeatureClassSchema& schema) { if(!schema.isClosed()) schema.closeTable(); return schema.openSchema(this); } ossim-Miami-2.9.1/src/vec/ossimVpfDatabase.cpp000066400000000000000000000110031352751253100212110ustar00rootroot00000000000000//******************************************************************* // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This class extends the stl's string class. // //******************************************************************** // $Id: ossimVpfDatabase.cpp 19636 2011-05-24 16:48:45Z gpotts $ #include #include #include #include #include #include #include using namespace std; ossimVpfDatabase::ossimVpfDatabase() :theDatabaseHeaderTable(""), theLibraryAttributeTable(""), theOpenedFlag(false) { } ossimVpfDatabase::~ossimVpfDatabase() { deleteLibraryList(); closeDatabase(); } bool ossimVpfDatabase::openDatabase(const ossimFilename& filename) { bool result = true; ossimFilename tempFilename = filename; // tempFilename.convertBackToForwardSlashes(); // we should have two table to look at for the database. // 1) database header (dht) 2) and the Library attribute (lat) theDatabaseHeaderTable = ossimFilename(tempFilename.path()).dirCat("dht"); theLibraryAttributeTable = ossimFilename(tempFilename.path()).dirCat("lat"); if(theDatabaseHeaderTable.exists() && theLibraryAttributeTable.exists()) { ossimVpfTable table; // now lets see if they are valid tables result = table.openTable(theDatabaseHeaderTable); if(result&& !ossimVpfDatabaseHeaderTableValidator().isValid(table)) { result = false; } result = table.openTable(theLibraryAttributeTable); if((result) &&!ossimVpfLibraryAttributeTableValidator().isValid(table)) { result = false; } } else { result = false; } if(result) { theOpenedFlag = true; initializeLibraryList(); } return result; } void ossimVpfDatabase::closeDatabase() { theLibraryAttributeTable = ""; theDatabaseHeaderTable = ""; theOpenedFlag = false; deleteLibraryList(); } ossimFilename ossimVpfDatabase::getPath()const { // we can use either table name since all we need is the path return theLibraryAttributeTable.path(); } long ossimVpfDatabase::getNumberOfLibraries()const { return (long)theVpfLibraryList.size(); } ossimVpfLibrary* ossimVpfDatabase::getLibrary(unsigned long libraryNumber) { if(libraryNumber < theVpfLibraryList.size()) { return theVpfLibraryList[libraryNumber]; } return NULL; } ossimVpfLibrary* ossimVpfDatabase::getLibrary(const ossimString& name) { for(long index = 0; index < (long)theVpfLibraryList.size(); ++index) { if(theVpfLibraryList[index]->getName() == name) { return theVpfLibraryList[index]; } } return NULL; } bool ossimVpfDatabase::isOpened()const { return theOpenedFlag; } vector ossimVpfDatabase::getLibraryNames()const { ossimVpfTable table; if(table.openTable(theLibraryAttributeTable)) { return table.getColumnValues("LIBRARY_NAME"); } return vector(); } vector ossimVpfDatabase::getLibraryNamesFullPath()const { vector result; ossimVpfTable table; if(table.openTable(theLibraryAttributeTable)) { result = table.getColumnValues("LIBRARY_NAME"); } for(long index=0; index < (long)result.size();index++) { result[index] = ossimString(theLibraryAttributeTable.path()) + ossimString("/") + result[index]; } return result; } ossimFilename ossimVpfDatabase::getLibraryAttributeTable()const { return theLibraryAttributeTable; } void ossimVpfDatabase::initializeLibraryList() { // make sure the library list is deleted deleteLibraryList(); vector libraryNames = getLibraryNames(); for(long index = 0; index < (long)libraryNames.size(); index++) { ossimVpfLibrary *library = new ossimVpfLibrary; library->openLibrary(this, libraryNames[index], getPath().dirCat(libraryNames[index])); theVpfLibraryList.push_back(library); } } void ossimVpfDatabase::deleteLibraryList() { for(long idx = 0; idx <(long)theVpfLibraryList.size(); idx++) { delete theVpfLibraryList[idx]; theVpfLibraryList[idx] = 0; } theVpfLibraryList.clear(); } ossim-Miami-2.9.1/src/vec/ossimVpfDatabaseHeader.cpp000066400000000000000000000024631352751253100223340ustar00rootroot00000000000000//******************************************************************* // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This class extends the stl's string class. // //******************************************************************** // $Id: ossimVpfDatabaseHeader.cpp 17206 2010-04-25 23:20:40Z dburken $ #include #include #include ossimVpfDatabaseHeader::ossimVpfDatabaseHeader() { } ossimVpfDatabaseHeader::~ossimVpfDatabaseHeader() { } ossimErrorCode ossimVpfDatabaseHeader::open(const ossimFilename& databaseHeaderTable) { vpf_table_type tableTypeData; if( is_vpf_table( databaseHeaderTable.c_str() ) ) { tableTypeData = vpf_open_table(databaseHeaderTable.c_str(), (storage_type)DISK, "rb", NULL); if(isDatabaseHeaderTable(tableTypeData)) { } else { return ossimErrorCodes::OSSIM_ERROR; } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } bool ossimVpfDatabaseHeader::isDatabaseHeaderTable(vpf_table_type& /* tableType */) { return true; } ossim-Miami-2.9.1/src/vec/ossimVpfDatabaseHeaderTableValidator.cpp000066400000000000000000000052451352751253100251530ustar00rootroot00000000000000//----------------------------------------------------------------- // License: LGPL // // See LICENSE.txt file in the top level directory for more details. //----------------------------------------------------------------- #include #include ossimVpfDatabaseHeaderTableValidator::~ossimVpfDatabaseHeaderTableValidator() { } bool ossimVpfDatabaseHeaderTableValidator::isValid(ossimVpfTable& aTable)const { // make sure the table is not null if(&aTable == NULL) { return false; } // and make sure that the table is not closed if(aTable.isClosed()) { return false; } // get the table data defined in vpf_util/vpftable.h" const vpf_table_type* data = aTable.getVpfTableData(); if(!data) { return false; } // if the file is not open then we can't validate if(!data->fp) { return false; } // The way that we will validate is to see if the columns of a dht // exist. if the column didn't exist then the position // will be negative long column = table_pos("ID", *data); if(column < 0) { return false; } column = table_pos("VPF_VERSION", *data); if(column < 0) { return false; } column = table_pos("DATABASE_NAME", *data); if(column < 0) { return false; } column = table_pos("DATABASE_DESC", *data); if(column < 0) { return false; } column = table_pos("MEDIA_STANDARD", *data); if(column < 0) { return false; } column = table_pos("ORIGINATOR", *data); if(column < 0) { return false; } column = table_pos("ADDRESSEE", *data); if(column < 0) { return false; } column = table_pos("MEDIA_VOLUMES", *data); if(column < 0) { return false; } column = table_pos("SEQ_NUMBERS", *data); if(column < 0) { return false; } column = table_pos("NUM_DATA_SETS", *data); if(column < 0) { return false; } column = table_pos("SECURITY_CLASS", *data); if(column < 0) { return false; } column = table_pos("DOWNGRADING", *data); if(column < 0) { return false; } column = table_pos("DOWNGRADE_DATE", *data); if(column < 0) { return false; } column = table_pos("RELEASABILITY", *data); if(column < 0) { return false; } column = table_pos("TRANSMITTAL_ID", *data); if(column < 0) { return false; } column = table_pos("EDITION_NUMBER", *data); if(column < 0) { return false; } column = table_pos("EDITION_DATE", *data); if(column < 0) { return false; } return true; } ossim-Miami-2.9.1/src/vec/ossimVpfExtent.cpp000066400000000000000000000057641352751253100207750ustar00rootroot00000000000000/* * Copyright 1994, 1995 Vectaport Inc., Cartoactive Systems * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the names of the copyright holders not be used in * advertising or publicity pertaining to distribution of the software * without specific, written prior permission. The copyright holders make * no representations about the suitability of this software for any purpose. * It is provided "as is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. * IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include #include #include using namespace std; /*****************************************************************************/ ostream& operator <<(ostream& out, const ossimVpfExtent& data) { out << "x1: " << data.theExtentType.x1 << endl << "y1: " << data.theExtentType.y1 << endl << "x2: " << data.theExtentType.x2 << endl << "y2: " << data.theExtentType.y2; return out; } ossimVpfExtent::ossimVpfExtent (double x1, double y1, double x2, double y2) { this->theExtentType.x1 = x1; this->theExtentType.y1 = y1; this->theExtentType.x2 = x2; this->theExtentType.y2 = y2; } ossimVpfExtent::ossimVpfExtent () { theExtentType.x1 = 0.0; theExtentType.y1 = 0.0; theExtentType.x2 = 0.0; theExtentType.y2 = 0.0; } ossimVpfExtent::ossimVpfExtent(const extent_type& etype) { theExtentType.x1 = etype.x1; theExtentType.y1 = etype.y1; theExtentType.x2 = etype.x2; theExtentType.y2 = etype.y2; } int ossimVpfExtent::contained (ossimVpfExtent& extent2) { return ::contained( theExtentType, extent2.theExtentType ); } int ossimVpfExtent::completely_within (ossimVpfExtent& extent2) { return ::completely_within( theExtentType, extent2.theExtentType ); } int ossimVpfExtent::within (double x, double y) { return ::fwithin( x, y, theExtentType ); } ossimVpfExtent ossimVpfExtent::operator+ (const ossimVpfExtent& b)const { ossimVpfExtent m; m.theExtentType.x1 = ossim::min(theExtentType.x1, b.theExtentType.x1); m.theExtentType.y1 = ossim::min(theExtentType.y1, b.theExtentType.y1); m.theExtentType.x2 = ossim::max(theExtentType.x2, b.theExtentType.x2); m.theExtentType.y2 = ossim::max(theExtentType.y2, b.theExtentType.y2); return m; } ossim-Miami-2.9.1/src/vec/ossimVpfFeatureClass.cpp000066400000000000000000000070201352751253100220720ustar00rootroot00000000000000#include using namespace std; #include #include #include #include #include #include #ifndef NULL #include #endif ossimVpfFeatureClass::ossimVpfFeatureClass() { } bool ossimVpfFeatureClass::openFeatureClass(const ossimString& featureClassName, const ossimFilename& featureClassFullPath, const ossimFilename& table1, const ossimString& columnNameIdTable1, const ossimFilename& table2, const ossimString& columnNameIdTable2) { theFeatureClassFullPath = featureClassFullPath; theFeatureClassName = featureClassName; theTableName1 = table1; theColumnNameId1 = columnNameIdTable1; theTableName2 = table2; theColumnNameId2 = columnNameIdTable2; ossimVpfTable t1; ossimVpfTable t2; ossimFilename t1Name = getTable1(); ossimFilename t2Name = getTable2(); if((!t1.openTable(t1Name))|| (!t2.openTable(t2Name))) { return false; } return true; } const ossimString& ossimVpfFeatureClass::getName()const { return theFeatureClassName; } bool ossimVpfFeatureClass::isPrimitive(const ossimString& featureName) { // make sure we have forward slashes ossimFilename filename(featureName.trim()); // filename.convertBackToForwardSlashes(); ossimString copyOfFeature = filename; // find const char* temp = strrchr(copyOfFeature.c_str(), '/'); ossimString value; if(temp) { ++temp; value = temp; } else { value = copyOfFeature; } value = value.downcase(); return( (value == "end") || (value == "cnd") || (value == "edg") || (value == "fac") || (value == "txt") ); } bool ossimVpfFeatureClass::isSimpleFeature(const ossimString& featureName) { // find the suffix ossimString value = strrchr(featureName.trim().c_str(), '.'); // the suffix will be null or empty string if not found. if(value == "") { return false; } // make case insensitive value = value.downcase(); return ( (value == ".pft")|| (value == ".lft")|| (value == ".aft")|| (value == ".tft")); } bool ossimVpfFeatureClass::isComplexFeature(const ossimString& featureName) { const char* suffix = strrchr(featureName.trim(), '.'); if (!suffix) { return false; } ossimString value = ossimString(suffix).downcase(); return (value == ".cft"); } bool ossimVpfFeatureClass::isFeature(const ossimString& featureName) { return (isSimpleFeature(featureName) || isComplexFeature(featureName)); } bool ossimVpfFeatureClass::isJoin(const ossimString& featureName) { ossimString value = strrchr(featureName.c_str(), '.'); if(value == "") { return false; } value = value.downcase(); return ( (value == ".cjt")|| (value == ".pjt")|| (value == ".ljt")|| (value == ".ajt")|| (value == ".tjt")); } ossimFilename ossimVpfFeatureClass::getTable1()const { return theFeatureClassFullPath.dirCat(theTableName1); } ossimFilename ossimVpfFeatureClass::getTable2()const { return theFeatureClassFullPath.dirCat(theTableName2); } ossim-Miami-2.9.1/src/vec/ossimVpfFeatureClassSchema.cpp000066400000000000000000000113241352751253100232150ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************** // $Id: ossimVpfFeatureClassSchema.cpp 20936 2012-05-18 14:45:00Z oscarkramer $ #include #include #include #include using namespace std; ossimVpfFeatureClassSchema::ossimVpfFeatureClassSchema() :theCoverage(NULL) { } bool ossimVpfFeatureClassSchema::openSchema(ossimVpfCoverage* coverage) { theCoverage = coverage; bool result = false; if(theCoverage) { theSchemaTableName = theCoverage->getPath().dirCat("fcs"); if(theSchemaTableName.exists()) { result = openTable(theSchemaTableName); if(result) { result = validateColumnNames(); } if(result) { setFeatureClassMapping(); } } } return result; } void ossimVpfFeatureClassSchema::closeTable() { ossimVpfTable::closeTable(); theFeatureClassMap.clear(); } void ossimVpfFeatureClassSchema::getFeatureClasses(std::vector& featureClassArray)const { featureClassArray.clear(); std::map::const_iterator featureClassIter = theFeatureClassMap.begin(); while(featureClassIter != theFeatureClassMap.end()) { featureClassArray.push_back((*featureClassIter).first); ++featureClassIter; } } bool ossimVpfFeatureClassSchema::getFeatureClassNode(const ossimString& featureClass, ossimVpfFeatureClassSchemaNode& featureClassNode)const { std::map::const_iterator fIter = theFeatureClassMap.find(featureClass); if(fIter != theFeatureClassMap.end()) { featureClassNode = (*fIter).second; return true; } return false; } ossim_int32 ossimVpfFeatureClassSchema::getNumberOfFeatureClasses()const { return (ossim_int32)theFeatureClassMap.size(); } bool ossimVpfFeatureClassSchema::validateColumnNames()const { if(isClosed()) return false; return ((getColumnPosition("feature_class")>=0)&& (getColumnPosition("table1")>=0)&& (getColumnPosition("table1_key")>=0)&& (getColumnPosition("table2")>=0)&& (getColumnPosition("table2_key")>=0)); } void ossimVpfFeatureClassSchema::setFeatureClassMapping() { if(!isClosed()) { ossim_int32 featureIdx = getColumnPosition("feature_class"); ossim_int32 table1Idx = getColumnPosition("table1"); ossim_int32 table1KeyIdx = getColumnPosition("table1_key"); ossim_int32 table2Idx = getColumnPosition("table2"); ossim_int32 table2KeyIdx = getColumnPosition("table2_key"); reset(); if(getNumberOfRows() > 0) { row_type row; const int ROWS = getNumberOfRows(); for(int rowIdx = 1; rowIdx <= ROWS; ++rowIdx) { if(rowIdx == 1) { row = read_row(rowIdx, *theTableInformation); } else { row = read_next_row(*theTableInformation); } ossimFilename primitiveTable = getColumnValueAsString(row, table2Idx); if(ossimVpfFeatureClass::isPrimitive(primitiveTable)) { ossimString primitiveTableKey = getColumnValueAsString(row, table2KeyIdx); ossimFilename table = getColumnValueAsString(row, table1Idx); ossimString tableKey = getColumnValueAsString(row, table1KeyIdx); ossimString featureClass = getColumnValueAsString(row, featureIdx); ossimVpfFeatureClassSchemaNode node(table, tableKey, primitiveTable, primitiveTableKey); theFeatureClassMap.insert(make_pair(featureClass, node)); } free_row(row, *theTableInformation); } } } } ossim-Miami-2.9.1/src/vec/ossimVpfLibrary.cpp000066400000000000000000000163101352751253100211170ustar00rootroot00000000000000//******************************************************************* // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This class extends the stl's string class. // //******************************************************************** // $Id: ossimVpfLibrary.cpp 15833 2009-10-29 01:41:53Z eshirschorn $ #include #include #include #include #include #include #include #include using namespace std; ossimVpfLibrary::ossimVpfLibrary() :theDatabase(0), theLibraryName(""), theLibraryNameFullPath(""), theNumberOfCoverages(0) { } ossimVpfLibrary::~ossimVpfLibrary() { theDatabase = 0; } bool ossimVpfLibrary::openLibrary(ossimVpfDatabase* database, const ossimString& name, const ossimFilename& libraryPath) { bool returnCode = true; theNumberOfCoverages = 0; theLibraryName = ""; theLibraryNameFullPath = ""; theLibraryName = name; theLibraryNameFullPath = libraryPath; theDatabase = database; if(!ossimFilename(theLibraryNameFullPath).exists()) { returnCode = false; } if(returnCode) { setCoverageNames(); ossimVpfTable table; theNumberOfCoverages = (ossim_uint32)theCoverageNames.size(); returnCode = (theNumberOfCoverages> 0); } return returnCode; } bool ossimVpfLibrary::getCoverage(long coverageNumber, ossimVpfCoverage& coverage) { bool result = false; if((coverageNumber >=0) && (coverageNumber < (int)theCoverageNames.size())) { result = coverage.openCoverage(this, theCoverageNames[coverageNumber], theLibraryNameFullPath.dirCat(theCoverageNames[coverageNumber])); } return result; } bool ossimVpfLibrary::getCoverage(const ossimString& name, ossimVpfCoverage& coverage) { for(int idx = 0; idx < (int)theCoverageNames.size(); ++idx) { if(theCoverageNames[idx] == name) { return getCoverage(idx, coverage); } } return false; } bool ossimVpfLibrary::getExtent(ossimVpfExtent& extent)const { bool result = false; ossimVpfTable tempTable; // this code was basically cut paste from vhcl with just // a couple modifications. /* Get library extent from Library Attribute Table (LAT) */ /* char* buf;*/ /* long int n;*/ /* double xmin,ymin,xmax,ymax;*/ int libraryNamePosition, xminPosition, yminPosition; int xmaxPosition, ymaxPosition; int i; bool found; row_type row; extent_type libextent; if(!theDatabase) { return false; } ossimFilename file(theDatabase->getLibraryAttributeTable()); if(!tempTable.openTable(file)) { return result; } vpf_table_type *table = tempTable.getVpfTableData(); libraryNamePosition = table_pos( "LIBRARY_NAME", *table ); found = false; for (i=1;(i<=tempTable.getNumberOfRows())&&(!found);i++) { row = read_row( i, *table ); ossimString libraryName = tempTable.getColumnValueAsString(row, libraryNamePosition); libraryName = libraryName.trim(); if (libraryName == theLibraryName) { xminPosition = table_pos( "XMIN", *table ); yminPosition = table_pos( "YMIN", *table ); xmaxPosition = table_pos( "XMAX", *table ); ymaxPosition = table_pos( "YMAX", *table ); libextent.x1 = tempTable.getColumnValueAsString(row, xminPosition).toDouble(); libextent.y1 = tempTable.getColumnValueAsString(row, yminPosition).toDouble(); libextent.x2 = tempTable.getColumnValueAsString(row, xmaxPosition).toDouble(); libextent.y2 = tempTable.getColumnValueAsString(row, ymaxPosition).toDouble(); found = true; } else { result = false; } free_row( row, *table ); } extent = ossimVpfExtent(libextent); return result; } ossimFilename ossimVpfLibrary::getPath()const { return theLibraryNameFullPath; } ossimString ossimVpfLibrary::getName()const { return theLibraryName; } bool ossimVpfLibrary::getCoverageNames(std::vector& coverageNames)const { bool result = true; coverageNames = theCoverageNames; return result; } int ossimVpfLibrary::getNumberOfCoverages()const { return theNumberOfCoverages; } bool ossimVpfLibrary::hasCoverage(const ossimString& coverageName)const { return (std::find(theCoverageNames.begin(), theCoverageNames.end(), coverageName)!=theCoverageNames.end()); } ossimString ossimVpfLibrary::getTileName(ossim_int32 id)const { ossimString result; if(theLibraryNameFullPath.dirCat("tileref").exists()) { if(theTileNameMap.size() <1) { setTileNames(); } std::map::iterator tileNameIter = theTileNameMap.find(id); if(tileNameIter != theTileNameMap.end()) { result = (*tileNameIter).second; } } return result; } void ossimVpfLibrary::getTileNames(std::vector& tileNames)const { if(theLibraryNameFullPath.dirCat("tileref").exists()) { if(theTileNameMap.size() <1) { setTileNames(); } std::map::iterator tileNameIter = theTileNameMap.begin(); while(tileNameIter != theTileNameMap.end()) { tileNames.push_back((*tileNameIter).second); ++tileNameIter; } } } void ossimVpfLibrary::setCoverageNames() { ossimVpfTable table; theCoverageNames.clear(); // open up the coverage attribute table for this library if(table.openTable(theLibraryNameFullPath.dirCat("cat"))) { // we need to have a coverage attribute table validator before // we proceed but for now assume that it is a good table. // theCoverageNames = table.getColumnValues("COVERAGE_NAME"); } } void ossimVpfLibrary::setTileNames()const { ossimVpfTable table; theTileNameMap.clear(); row_type row; if(table.openTable(theLibraryNameFullPath.dirCat("tileref").dirCat("tileref.aft"))) { table.reset(); const int ROWS = table.getNumberOfRows(); for (int rowIdx = 1; rowIdx <= ROWS; ++rowIdx) { // Note: read_row takes a "one based" index. row = read_row( rowIdx, *(table.getVpfTableData()) ); ossim_int32 namePosition = table.getColumnPosition("TILE_NAME"); ossim_int32 tileIdPosition = table.getColumnPosition("ID"); ossimString tileName = table.getColumnValueAsString(row, namePosition);; ossimString tileId = table.getColumnValueAsString(row, tileIdPosition); theTileNameMap.insert(make_pair(tileId.toInt32(), tileName.trim())); free_row( row, *(table.getVpfTableData()) ); } } } ossim-Miami-2.9.1/src/vec/ossimVpfLibraryAttributeTableValidator.cpp000066400000000000000000000023361352751253100256240ustar00rootroot00000000000000#include #include bool ossimVpfLibraryAttributeTableValidator::isValid(ossimVpfTable& aTable)const { // and make sure that the table is not closed if(aTable.isClosed()) { return false; } // get the table data defined in vpf_util/vpftable.h" const vpf_table_type* data = aTable.getVpfTableData(); if(!data) { return false; } // if the file is not open then we can't validate if(!data->fp) { return false; } // The way that we will validate is to see if the columns of a dht // exist. if the column didn't exist then the position // will be negative long column = table_pos("ID", *data); if(column < 0) { return false; } column = table_pos("LIBRARY_NAME", *data); if(column < 0) { return false; } column = table_pos("XMIN", *data); if(column < 0) { return false; } column = table_pos("YMIN", *data); if(column < 0) { return false; } column = table_pos("XMAX", *data); if(column < 0) { return false; } column = table_pos("YMAX", *data); if(column < 0) { return false; } return true; } ossim-Miami-2.9.1/src/vec/ossimVpfTable.cpp000066400000000000000000000616141352751253100205510ustar00rootroot00000000000000//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: This class give the capability to access tiles from an // vpf file. // //******************************************************************** // $Id: ossimVpfTable.cpp 23205 2015-03-25 13:54:42Z gpotts $ #include #include #include #include #include std::ostream& operator <<(std::ostream& out, const ossimVpfTable& data) { data.print(out); return out; } ossimVpfTable::ossimVpfTable() :theTableInformation(NULL) { } ossimVpfTable::~ossimVpfTable() { if(theTableInformation) { closeTable(); delete theTableInformation; theTableInformation = NULL; } } bool ossimVpfTable::openTable(const ossimFilename& tableName) { closeTable(); if(is_vpf_table(const_cast(tableName.c_str()))) { if(theTableInformation) { delete theTableInformation; theTableInformation = NULL; } theTableInformation = new vpf_table_type; memset(theTableInformation, 0, sizeof(vpf_table_type)); theTableName = tableName; *theTableInformation = vpf_open_table(const_cast(tableName.c_str()), disk, "rb", NULL); } else { delete theTableInformation; theTableInformation = NULL; return false; } return true; } void ossimVpfTable::closeTable() { if(theTableInformation&&(theTableInformation->status!=CLOSED)) { vpf_close_table(theTableInformation); } } int ossimVpfTable::getNumberOfRows()const { if(theTableInformation) return theTableInformation->nrows; return 0; } int ossimVpfTable::getNumberOfColumns()const { if(theTableInformation) return theTableInformation->nfields; return 0; } ossimString ossimVpfTable::getColumnName(int idx)const { if((idx < 0) || idx > getNumberOfColumns()) { return ossimString(""); } return ossimString(theTableInformation->header[idx].name); } bool ossimVpfTable::isClosed()const { return (theTableInformation && (theTableInformation->status==CLOSED)); } void ossimVpfTable::reset()const { if(theTableInformation && (theTableInformation->status!=CLOSED)) { long fpos; fpos = index_pos(0, *theTableInformation); fseek(theTableInformation->fp, fpos, SEEK_SET); } } bool ossimVpfTable::goToRow(long row)const { if(theTableInformation && (theTableInformation->status!=CLOSED)) { long fpos; fpos = index_pos(row, *theTableInformation); if(fpos < 0) { return false; } fseek(theTableInformation->fp, fpos, SEEK_SET); } return true; } std::vector ossimVpfTable::getColumnValues(const ossimString& columnName)const { std::vector result; if(theTableInformation && theTableInformation->status == OPENED) { long int columnNumber = table_pos(const_cast(columnName.c_str()), *theTableInformation); if(columnNumber >=0 && (columnNumber < theTableInformation->nfields)) { row_type row; // start at the first row of the table reset(); for (int rowIndex = 1; rowIndex <= theTableInformation->nrows; ++rowIndex) { row = read_next_row(*theTableInformation); ossimString value = getColumnValueAsString(row, columnNumber); value.trim(); result.push_back(value); free_row(row, *theTableInformation); } } } return result; } std::vector ossimVpfTable::getColumnValues(long columnNumber)const { std::vector result; if(theTableInformation && theTableInformation->status == OPENED) { if(columnNumber >=0 && (columnNumber < theTableInformation->nfields)) { row_type row; // start at the first row of the table reset(); for (int rowIndex = 0; rowIndex < theTableInformation->nrows; ++rowIndex) { row = read_next_row(*theTableInformation); ossimString value = getColumnValueAsString(row, columnNumber); // value = value.downcase(); value = value.trim(); result.push_back(value); free_row(row, *theTableInformation); } } } return result; } ossimString ossimVpfTable::getColumnValueAsString(row_type& row, long columnNumber)const { ossimString result; ossim_int32 n=1; switch(theTableInformation->header[columnNumber].type) { case 'T': // it's of type text so { char c; char *buf = (char *)get_table_element(columnNumber, row, *theTableInformation, &c, &n); if(buf) { result = buf; free(buf); } else { result = c; } break; } case 'I': { ossim_int32 value; ossim_int32* v = (ossim_int32*)get_table_element(columnNumber, row, *theTableInformation, &value, &n); if(v) { result = ossimString::toString(v[0]); free(v); } else { result = ossimString::toString(value); } break; } case 'S': { short int value; short int* v = (short int*)get_table_element(columnNumber, row, *theTableInformation, &value, &n); if(v) { result = ossimString::toString(v[0]); free(v); } else { result = ossimString::toString(value); } break; } case 'F': { float value; float* v = (float*)get_table_element(columnNumber, row, *theTableInformation, &value, &n); if(v) { value = v[0]; free(v); } if (!is_vpf_null_float(value)) { result = ossimString::toString(value); } else { result = "nan"; } break; } case 'B': { double value; double* tempBuf = (double*)get_table_element(columnNumber, row, *theTableInformation, &value, &n); if(tempBuf) { value = tempBuf[0]; free(tempBuf); } if (!is_vpf_null_double(value)) { result = ossimString::toString(value); } else { result = "nan"; } break; } case 'C': { coordinate_type coordType; coordinate_type* temp = (coordinate_type*)get_table_element(columnNumber, row, *theTableInformation, &coordType, &n); if(temp) { coordType = temp[0]; free(temp); } result = ossimString::toString(coordType.x)+ ossimString(" ") + ossimString::toString(coordType.y); break; } case 'K': { id_triplet_type idTripletType; id_triplet_type* tempType = (id_triplet_type*)get_table_element(columnNumber, row, *theTableInformation, &idTripletType, &n); if(tempType) { idTripletType = tempType[0]; free (tempType); } result = ossimString(idTripletType.type) + ossimString(" ") + ossimString::toString(static_cast(idTripletType.id)) + ossimString(" ") + ossimString::toString(static_cast(idTripletType.tile))+ ossimString(" ") + ossimString::toString(static_cast(idTripletType.exid)); break; } case 'D': { date_type date, formatDate; date_type* temp = (date_type*)get_table_element(columnNumber, row, *theTableInformation, &date, &n); if(temp) { free(temp); } format_date(date, formatDate); result = formatDate; break; } case 'Z': // tri coordinate types x, y, z { tri_coordinate_type *tcptr=NULL; tcptr = (tri_coordinate_type *) get_table_element(columnNumber,row, *theTableInformation, NULL,&n); result = ""; for (int k=0;kstatus!=CLOSED)) { long int columnNumber = table_pos(const_cast(columnName.c_str()), *theTableInformation); row_type row = read_next_row(*theTableInformation); ossimString result = getColumnValueAsString(row, columnNumber); free_row(row, *theTableInformation); return result; } return ""; } ossim_int32 ossimVpfTable::getColumnPosition(const ossimString& columnName)const { return ((ossim_int32)table_pos(const_cast(columnName.c_str()), *theTableInformation)); } void ossimVpfTable::print(std::ostream& out)const { if(theTableInformation && (theTableInformation->status!=CLOSED)) { // make sure we are at the beginning of the table. this->reset(); // the rest of this code is from the vpfutil. The vpfutil // was grabbed from the vhcl map server software. vpf_table_type& table = *theTableInformation; ossim_int32 i,j,k,n; ossim_int16 ival=0,*iptr=NULL; ossim_int32 lval=0,*lptr=NULL; ossim_float32 fval=0,*fptr=NULL; date_type dval,*dptr=NULL; id_triplet_type kval={0,0,0}, *kptr=NULL; coordinate_type cval={0,0}, *cptr=NULL; char *buf, ch, date[40]; row_type row; out << "table name: " << theTableName << std::endl << "desciption: " << table.description << std::endl << std::endl; out << "Definition:" << std::endl; for (i=0;i80) { out << std::endl; n = 0; } } out << std::endl; free(buf); } break; case 'I': // long if (table.header[j].count==1) { get_table_element(j,row,table,&lval,&n); if (!is_vpf_null_float(lval)) { out << lval << std::endl; } else { out << "null" << std::endl; } } else { lptr = (ossim_int32*)get_table_element(j,row,table,NULL,&n); for (k=0;k #include #include #include /** * @brief main application for getting version / date and generating the * ossimVersion.h file. * * @param argv[1] Path to ossim/include/ossim/ossimVersion.h * * @param argv[2] Version number string like "1.7.11" */ int main(int argc, char* argv[]) { enum { OK=0, ERROR=1 }; if (argc != 3) { return ERROR; } std::ofstream os(argv[1]); if (!os) { return ERROR; } // Get the version. This is now passed in from the make file. std::string versionString = "Version "; versionString += argv[2]; std::string versionNumber = argv[2]; std::string majorVersion; std::string minorVersion = "0"; std::string releaseVersion = "0"; std::string::size_type pos1 = std::string::npos; std::string::size_type pos2 = std::string::npos; pos1 = versionNumber.find(".", 0); if(pos1 != std::string::npos) { majorVersion = std::string(versionNumber.begin(), versionNumber.begin()+pos1); pos2 = versionNumber.find(".", pos1+1); if(pos2 != std::string::npos) { minorVersion = std::string(versionNumber.begin()+pos1+1, versionNumber.begin()+pos2); releaseVersion = std::string(versionNumber.begin()+pos2+1, versionNumber.end()); } } else { majorVersion = versionNumber; } // Get the build date in the format of (yyyymmdd). char s[11]; s[10] = '\0'; time_t t; time(&t); tm* lt = localtime(&t); strftime(s, 11, "(%Y%m%d)", lt); std::string date = s; // Write the header file. os << "// Auto generated by version-config - DO NOT EDIT\n" << "#ifndef ossimVersion_HEADER\n" << "#define ossimVersion_HEADER\n" << "\n" << "#include \n" << "\n" << "#ifndef OSSIM_VERSION\n" << "# define OSSIM_VERSION " << "\"" << versionString << "\"\n" << "# define OSSIM_VERSION_NUMBER " << "\"" << versionNumber << "\"\n" << "# define OSSIM_MAJOR_VERSION_NUMBER " << majorVersion << "\n" << "# define OSSIM_MINOR_VERSION_NUMBER " << minorVersion << "\n" << "# define OSSIM_RELEASE_NUMBER " << releaseVersion << "\n" << "#endif\n" << "\n" << "// date format = (yyyymmdd)\n" << "#ifndef OSSIM_BUILD_DATE\n" << "# define OSSIM_BUILD_DATE " << "\"" << date << "\"\n" << "#endif\n" << "\n" << "#endif /* End of #ifndef ossimVersion_HEADER */" << std::endl; os.close(); std::cout << "wrote file: " << argv[1] << std::endl; return OK; } ossim-Miami-2.9.1/src/video/000077500000000000000000000000001352751253100156105ustar00rootroot00000000000000ossim-Miami-2.9.1/src/video/ossimVideoGeometry.cpp000066400000000000000000000015731352751253100221570ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer, SPADAC Inc. // // DESCRIPTION: Defines base class for full video geometry // //************************************************************************************************** // $Id: ossimVideoGeometry.cpp 2665 2011-06-03 20:16:45Z oscar.kramer $ #include //************************************************************************************************* // Default constructor. This is a pure virtual base class with protected default constructor //************************************************************************************************* // EVENTUALLY POPULATE WITH COMMON VIDEO GEOMETRY CODE ossim-Miami-2.9.1/src/video/ossimVideoHandler.cpp000066400000000000000000000033441352751253100217370ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer, SPADAC Inc. // // DESCRIPTION: Interface for all ossim Video types // //************************************************************************************************** // $Id: ossimVideoHandler.cpp 2644 2011-05-26 15:20:11Z oscar.kramer $ #include RTTI_DEF1(ossimVideoHandler, "ossimVideoHandler", ossimVideoSource) //************************************************************************************************* // Protected constructor. This is a pure virtual base class with protected default constructor //************************************************************************************************* ossimVideoHandler::ossimVideoHandler() : m_currentFrameTime (0), m_videoDuration (0), m_frameRate (ossim::nan()) { } //************************************************************************************************* // Protected constructor. This is a pure virtual base class with protected default constructor //************************************************************************************************* void ossimVideoHandler::rewind() { seek(0, SEEK_ABSOLUTE); } //************************************************************************************************* //! Returns TRUE if video file named is successfully opened. //************************************************************************************************* bool ossimVideoHandler::open(const ossimFilename& videoFile) { m_videoFilename = videoFile; return open(); } ossim-Miami-2.9.1/src/video/ossimVideoImageHandler.cpp000066400000000000000000000115121352751253100226760ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer, SPADAC Inc. // // DESCRIPTION: // //************************************************************************************************** // $Id$ #include #include #include RTTI_DEF1(ossimVideoImageHandler, "ossimVideoImageHandler", ossimImageHandler) //************************************************************************************************* // Constructor //************************************************************************************************* ossimVideoImageHandler::ossimVideoImageHandler() : m_currentFrameNumber (-1) { } //************************************************************************************************* // Closes "image" by detaching from the video //************************************************************************************************* void ossimVideoImageHandler::close() { m_video = 0; m_videoGeometry = 0; } //************************************************************************************************* // Returns list of all frames available in the video. //************************************************************************************************* void ossimVideoImageHandler::getEntryList(std::vector& entryList) const { entryList.clear(); ossim_uint32 num_frames = getNumberOfEntries(); for (ossim_uint32 i=0; icomputeFrameTime(frame_number); if (m_video->seek(frameTime, ossimVideoSource::SEEK_ABSOLUTE)) { m_currentFrameNumber = frame_number; return true; } return false; } //************************************************************************************************* // Converts frame time to frame index using frame rate: //************************************************************************************************* ossim_uint32 ossimVideoImageHandler::getCurrentEntry() const { if (m_currentFrameNumber < 0 ) return 0; return m_currentFrameNumber; } //************************************************************************************************* // Determines total number of frames using frame rate and video duration: //************************************************************************************************* ossim_uint32 ossimVideoImageHandler::getNumberOfEntries() const { if (!m_video.valid()) return 0; ossim_uint32 num_frames = (ossim_uint32) m_video->computeFrameNumber(m_video->duration()); return num_frames; } //************************************************************************************************* // Returns number of lines per video frame. //************************************************************************************************* ossim_uint32 ossimVideoImageHandler::getNumberOfLines(ossim_uint32 resLevel) const { // Only full-image res level = 0 presently supported: if (!m_video.valid() || (resLevel != 0)) return 0; return m_video->frameSize().line; } //************************************************************************************************* // Returns number of lines per video frame. //************************************************************************************************* ossim_uint32 ossimVideoImageHandler::getNumberOfSamples(ossim_uint32 resLevel) const { // Only full-image res level = 0 presently supported: if (!m_video.valid() || (resLevel != 0)) return 0; return m_video->frameSize().samp; } //************************************************************************************************* // Returns Image Geometry for current frame. //************************************************************************************************* ossimRefPtr ossimVideoImageHandler::getImageGeometry() { if (theGeometry.valid()) return theGeometry; // Only full-image res level = 0 presently supported: if (!m_video.valid() || !m_videoGeometry.valid()) return NULL; theGeometry = m_videoGeometry->getImageGeometry(m_video->computeFrameTime(m_currentFrameNumber)); return theGeometry; } ossim-Miami-2.9.1/src/video/ossimVideoImageSource.cpp000066400000000000000000000205731352751253100225700ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer, SPADAC Inc. // // DESCRIPTION: Defines pure virtual base class for individual video frame image handler // //************************************************************************************************** // $Id: ossimVideoImageSource.cpp 2695 2011-06-08 21:12:15Z oscar.kramer $ #include #include #include #include #include RTTI_DEF1(ossimVideoImageSource, "ossimVideoImageSource", ossimImageSource) //************************************************************************************************* //! Default Constructor //************************************************************************************************* ossimVideoImageSource::ossimVideoImageSource() : m_frameTime (-1.0) { } //************************************************************************************************* //! Constructor used when accessing a common video object (versus instantiating a new video for //! each frame. //************************************************************************************************* ossimVideoImageSource::ossimVideoImageSource(ossimVideoSource* /* video */, const double& frame_time_seconds) : m_frameTime (-1.0) { initialize(); setFrameTime(frame_time_seconds); } //************************************************************************************************* //! Common initialization code for all construction methods. //************************************************************************************************* void ossimVideoImageSource::initialize() { ossimVideoSource* video = dynamic_cast(getInput()); if (!video) return; // Establish the frame rect: ossimIpt frame_size (video->frameSize()); m_frameRect = ossimIrect(0, 0, frame_size.x-1, frame_size.y-1); // Initialize the tile data buffer: m_tile = ossimImageDataFactory::instance()->create(this, this); m_tile->setWidth(frame_size.x); m_tile->setHeight(frame_size.y); m_tile->initialize(); } #if 0 /* GARRETT: this is from when I derived this class from ossimImageHandler instead of ossimImageSource. I'm leaving these out but it may be convenient to allow OSSIM to consider a video as a multi-entry file. Give some thought to the merits of deriving from ossimImageHandler. What about reader factory and registry? If a user specifies a video file, should the image handler registry pick it up? */ //************************************************************************************************* // Indirectly sets the frame time given a frame index from the start frame. //! Returns false if frame time is outside of allowable range. //************************************************************************************************* bool ossimVideoImageSource::setCurrentEntry(ossim_uint32 frame_number) { if (!m_video) return false; ossim_float64 frame_rate = m_video->videoFrameRate(); ossim_float64 frameTime = frame_number / frame_rate; return setFrameTime(frameTime); } //************************************************************************************************* // Converts frame time to frame index using frame rate: //************************************************************************************************* ossim_uint32 ossimVideoImageSource::getCurrentEntry() const { if (!m_video) return 0; ossim_float64 frame_rate = m_video->videoFrameRate(); if (frame_rate == 0.0) return 0; ossim_uint32 current_frame = m_frameTime/frame_rate; return current_frame; } //************************************************************************************************* // Determines total number of frames using frame rate and video duration: //************************************************************************************************* ossim_uint32 ossimVideoImageSource::getNumberOfEntries() const { if (!m_video) return 0; ossim_float64 frames_per_sec = m_video->videoFrameRate(); if (frames_per_sec == 0.0) return 0; ossim_float64 duration = m_video->duration(); ossim_uint32 num_frames = (ossim_uint32) (duration * frames_per_sec); return num_frames; } #endif //************************************************************************************************* // Sets the time stamp (in seconds from start of video) for the frame of interest. //! Returns false if frame time is outside of allowable range. //************************************************************************************************* bool ossimVideoImageSource::setFrameTime(const double& frameTime) { ossimVideoSource* video = dynamic_cast(getInput()); if (!video) return false; // If the requested frame number corresponds with the current active frame, we're done: if (frameTime == m_frameTime) return true; // Check that it is not past the last frame. Use video geometry's duration as it is more accurate m_frameTime = frameTime; if (m_frameTime > video->duration()) { m_frameTime = 0; return false; } // Seek to that frame: video->seek(m_frameTime, ossimVideoSource::SEEK_ABSOLUTE); return true; } //************************************************************************************************* // Returns number of lines per video frame. //************************************************************************************************* ossim_uint32 ossimVideoImageSource::getNumberOfLines(ossim_uint32 resLevel) const { // Only full-image res level = 0 presently supported: if (resLevel != 0) return 0; return m_frameRect.height(); } //************************************************************************************************* // Returns number of lines per video frame. //************************************************************************************************* ossim_uint32 ossimVideoImageSource::getNumberOfSamples(ossim_uint32 resLevel) const { // Only full-image res level = 0 presently supported: if (resLevel != 0) return 0; return m_frameRect.width(); } //************************************************************************************************* // Returns the populated geometry for this frame //************************************************************************************************* ossimRefPtr ossimVideoImageSource::getImageGeometry() { ossimVideoSource* video = dynamic_cast(getInput()); if (!video) return NULL; ossimRefPtr video_geometry = video->getVideoGeometry(); if (!video_geometry.valid()) return NULL; return video_geometry->getImageGeometry(m_frameTime); } //************************************************************************************************* // From ossimConnectableObject base class. Returns true if object is an ossimVideoSource. //************************************************************************************************* bool ossimVideoImageSource::canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object) const { return ( (!object || PTR_CAST(ossimVideoSource, object)) && (inputIndex == 0) ); } //************************************************************************************************* //! Video frames have no overviews, only full-res. //************************************************************************************************* void ossimVideoImageSource::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { result = ossimDpt(0.0, 0.0); if (resLevel == 0) result = ossimDpt(1.0, 1.0); } //************************************************************************************************* //! Video frames have no overviews, only full-res. //************************************************************************************************* void ossimVideoImageSource::getDecimationFactors(std::vector& decimations) const { decimations.clear(); decimations.push_back(ossimDpt(1.0, 1.0)); } ossim-Miami-2.9.1/src/video/ossimVideoSource.cpp000066400000000000000000000164711352751253100216270ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // // AUTHOR: Oscar Kramer, SPADAC Inc. // // DESCRIPTION: Interface for all ossim Video types // //************************************************************************************************** // $Id: ossimVideoSource.cpp 2695 2011-06-08 21:12:15Z oscar.kramer $ #include #include #include #include RTTI_DEF1(ossimVideoSource, "ossimVideoSource", ossimSource) //************************************************************************************************* // Protected constructor. This is a pure virtual base class with protected default constructor //************************************************************************************************* ossimVideoSource::ossimVideoSource() { } //************************************************************************************************* // Rewind command is passed down the chain until a video handler can process it. //************************************************************************************************* void ossimVideoSource::rewind() { ossimVideoSource* inter = PTR_CAST(ossimVideoSource, getInput(0)); if (inter) inter->rewind(); } //************************************************************************************************* //! Seeks to the frame at time specified, according to the seekType (relative to active frame or //! absolute time from start of video). Returns TRUE if successful. //************************************************************************************************* bool ossimVideoSource::seek(ossim_float64 reference_time_sec, SeekType seekType) { ossimVideoSource* inter = PTR_CAST(ossimVideoSource, getInput(0)); if (inter) return inter->seek(reference_time_sec, seekType); return false; } //************************************************************************************************* //! Seeks to start of next frame. Returns TRUE if successful. //************************************************************************************************* bool ossimVideoSource::nextFrame() { ossimVideoSource* inter = PTR_CAST(ossimVideoSource, getInput(0)); if (inter) return inter->nextFrame(); return false; } //************************************************************************************************* //! Total length of video in seconds. //************************************************************************************************* ossim_float64 ossimVideoSource::duration() const { ossimVideoSource* inter = PTR_CAST(ossimVideoSource, getInput(0)); if (inter) return inter->duration(); return 0.0; } //************************************************************************************************* //! Time in seconds from start of video of the current active frame, or NAN if no active frame. //************************************************************************************************* ossim_float64 ossimVideoSource::currentFrameTime() const { ossimVideoSource* inter = PTR_CAST(ossimVideoSource, getInput(0)); if (inter) return inter->currentFrameTime(); return 0.0; } //************************************************************************************************* //! Nominal frames per second. //************************************************************************************************* ossim_float64 ossimVideoSource::videoFrameRate() const { ossimVideoSource* inter = PTR_CAST(ossimVideoSource, getInput(0)); if (inter) return inter->videoFrameRate(); return 0.0; } //************************************************************************************************* //! Access to video geometry object. //************************************************************************************************* const ossimRefPtr ossimVideoSource::getVideoGeometry() const { ossimVideoSource* inter = PTR_CAST(ossimVideoSource, getInput(0)); if (inter) return inter->getVideoGeometry(); return NULL; } //************************************************************************************************* //! Access to current active frame. //************************************************************************************************* const ossimRefPtr ossimVideoSource::getCurrentFrame() const { //STUB return NULL; } //************************************************************************************************* //! Total number of frames in video. //************************************************************************************************* ossim_uint32 ossimVideoSource::getNumberOfFrames() const { // Base class implementation just computes number of frames from duration: ossim_uint32 num_frames = (ossim_uint32) computeFrameNumber(duration()); return num_frames; } //************************************************************************************************* //! Utility method for computing frame number from frame time. //************************************************************************************************* int ossimVideoSource::computeFrameNumber(double seconds_from_start) const { double frame_rate = videoFrameRate(); if (frame_rate > 0.0) return (int) seconds_from_start*frame_rate; // else return -1; } //************************************************************************************************* //! Utility method for computing frame time from frame number. //************************************************************************************************* double ossimVideoSource::computeFrameTime(ossim_uint32 frame_count) const { double frame_rate = videoFrameRate(); if (frame_rate > 0.0) return frame_count/frame_rate; // else return ossim::nan(); } //************************************************************************************************* //! Connections only to other video sources are allowed. //************************************************************************************************* bool ossimVideoSource::canConnectMyInputTo(ossim_int32 index, const ossimConnectableObject* object) const { if (object && (index == 0) && PTR_CAST(ossimVideoSource, object)) return true; // else return false; } //************************************************************************************************* //! Presently can only connect into an image chain via an ossimVideoImageSource bridge, or //! to another video source for video chains. Returns TRUE if connection possible. //************************************************************************************************* bool ossimVideoSource::canConnectMyOutputTo(ossim_int32 index, const ossimConnectableObject* object) const { if (!object || (index != 0)) return false; if (PTR_CAST(ossimVideoSource, object)) return true; if (PTR_CAST(ossimVideoImageSource, object)) return true; if (PTR_CAST(ossimVideoImageHandler, object)) return true; return false; } ossim-Miami-2.9.1/src/vpfutil/000077500000000000000000000000001352751253100161735ustar00rootroot00000000000000ossim-Miami-2.9.1/src/vpfutil/bitarray.c000066400000000000000000001010601352751253100201520ustar00rootroot00000000000000/****************************************************************************** * *N Module BITARRAY.C * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Bit manipulation of virtual 2-dimensional arrays. These arrays are * stored in a 1-dimensional bit array (MAP). * Some notes on problems with this code: * 1. all bit mapping must be with your mapextents-2. ie, if you * declare a bitarray 200 by 200, only 198 by 198 is usable. * 2. when drawing/manipulating lines, you must use a delta of 0 for * the x or y. If you do not, the line will not be straight. In * other words, use coordinate geometry. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October, 1990, Kernighan/Richie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions: *F * void SETROW( ArrayOfBits MAP, int XMIN, int XMAX, int Y ); * void CLEARROW( ArrayOfBits MAP, int XMIN, int XMAX, int Y ); * void TOGGLEROW( ArrayOfBits MAP, int XMIN, int XMAX, int Y ); * void SETCOLUMN( ArrayOfBits MAP, int X, in YMIN, int YMAX ); * void CLEARCOLUMN( ArrayOfBits MAP, int X, int YMIN, int YMAX ); * void TOGGLECOLUMN(ArrayOfBits MAP, int X, int YMIN, int YMAX ); * ArrayOfBits MakeArrayOfBits( int deltaX, int deltaY ); * int FreeArrayOfBits( ArrayOfBits map ); * int PointGetBit( ArrayOfBits map, IPoint point ); * int PointSetBit( ArrayOfBits map, IPoint at, int value ); * int LineSetBit( ArrayOfBits map, ISegment seg, int value ); * int LineXorBit( ArrayOfBits map, ISegment seg, int value ); * int TrapezoidXorBit( ArrayOfBits map, Isegment seg, int value ); *****************************************************************************/ #ifndef __MSDOS__ #ifndef _WIN32 #include #endif #endif #include #include #include /****************************************************************************** * *N SETROW * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Set bits in row Y of 2-d array MAP from XMIN to XMAX. * This procedure sets bits in MAP based on XMIN, XMAX, and Y. If XMIN and * XMAX are equal, it is assumed that there is a 1bit array in MAP, and this * bit is set to ~(255>>(8-(XMIN MOD 8))) && ~(255<<(1+(XMAX MOD 8))). * The index is calculated by: Y*MAP.rowcount+ (XMAX >> 3) or * Y*MAP.rowcount +(XMIN >> 3). Note that >> is rightshift the bits, * no carry. * If XMAX and XMIN are different values, a for loop is used to go from * the above index values, moving a string of 1's into each location, * except for the first location, which gets ~(255>>8-(XMIN MOD 8)) and the * last location, which gets ~(255<<1+(XMAX MOD 8)). As the name suggests * a row is set referenced by y. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * MAP == (ArrayOfBits) 2-d array to be modified * XMIN == (int) bottom of refence * XMAX == (int) top of reference * Y == (int) row to be modified *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990, Kernighan&Ritchie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Macros Called: *M * LEFTBITS(INDEX) BITARRAY.C * RIGHTBITS(INDEX) BITARRAY.C *E *****************************************************************************/ void SETROW( ArrayOfBits MAP, int XMIN, int XMAX, int Y ) { register int start /*= (((Y)*(MAP.rowcount))+((XMIN)>>3))*/; register int end /*= (((Y)*(MAP.rowcount))+((XMAX)>>3))*/; register int sbit /*= ((XMIN)%8)*/; register int ebit /*= ((XMAX)%8)*/; if (XMIN < 0) XMIN = 0; start = (((Y)*(MAP.rowcount))+((XMIN)>>3)); if (XMAX > MAP.bounding.x) XMAX = MAP.bounding.x-1; end = (((Y)*(MAP.rowcount))+((XMAX)>>3)); sbit = ((XMIN) % 8); ebit = ((XMAX) % 8); if ((0 > Y) || (Y > MAP.bounding.y) || (MAP.array == NULL) || (XMAX < XMIN)) return; if (start == end) MAP.array[start] |= ((RIGHTBITS(sbit))&LEFTBITS(ebit)); else { MAP.array[start] |= (RIGHTBITS(sbit)); for(start++;start>(8-(XMIN MOD 8))) && ~(255<<(1+(XMAX MOD 8)))). The index is * calculated as in the previous procedure. * If XMAX and XMIN are different values, a for loop is used to go from * the above index values, moving a string of 0's into each location. The * first location gets ~(~(255>>(8-(XMIN MOD 8)))) and the last location * gets ~(~(255<<1+(XMAX MOD 8))). As the name suggest, a row is erased * referenced by y. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * MAP == (ArrayOfBits) 2-d array of bits to be modified * XMIN == (int) bottom of reference * XMAX == (int) top of reference * Y == (int) row to be modified in the 2 d array *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990, Kernighan&Ritchie C * Updated August 1991, ANSI C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Macros Called: *M * LEFTBITS(INDEX) BITARRAY.C * RIGHTBITS(INDEX) BITARRAY.C *E ****************************************************************************/ void CLEARROW( ArrayOfBits MAP, int XMIN, int XMAX, int Y ) { register int start /*= (((Y)*(MAP.rowcount))+((XMIN)>>3))*/; register int end /*= (((Y)*(MAP.rowcount))+((XMAX)>>3))*/; register int sbit /*= ((XMIN)%8)*/; register int ebit /*= ((XMAX)%8)*/; if (XMIN < 0) XMIN=0; start = (((Y)*(MAP.rowcount))+((XMIN)>>3)); if (XMAX > MAP.bounding.x) XMAX = MAP.bounding.x-1; end = (((Y)*(MAP.rowcount))+((XMAX)>>3)); sbit = ((XMIN)%8); ebit = ((XMAX)%8); if ((0 > Y) || (Y > MAP.bounding.y) || (MAP.array == NULL) || (XMAX < XMIN)) return; if (start == end) MAP.array[start] &= ~((RIGHTBITS(sbit))&LEFTBITS(ebit)); else { MAP.array[start] &= ~(RIGHTBITS(sbit)); for(start++;start == (ArrayOfBits) 2 dimensional array of bits to be modified * XMIN == (int) low bit to begin modification * XMAX == (int) high bit to end modification * Y == (int) row to be modified in the 2-d array *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October, 1990, Kernighan&Ritchie C * Updated August 1991, ANSI C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Macros Called: *M * LEFTBITS(INDEX) BITARRAY.C * RIGHTBITS(INDEX) BITARRAY.C *E ****************************************************************************/ void TOGGLEROW( ArrayOfBits MAP, int XMIN, int XMAX, int Y ) { register int start /*= (((Y)*(MAP.rowcount))+((XMIN)>>3))*/; register int end /*= (((Y)*(MAP.rowcount))+((XMAX)>>3))*/; register int sbit /*= ((XMIN)%8)*/; register int ebit /*= ((XMAX)%8)*/; if (XMIN <= 0) XMIN = 0; start = (((Y)*(MAP.rowcount))+((XMIN)>>3)); if (XMAX > MAP.bounding.x) XMAX = MAP.bounding.x-1; end = (((Y)*(MAP.rowcount))+((XMAX)>>3)); sbit = ((XMIN)%8); ebit = ((XMAX)%8); if ((0 > Y) || (Y > MAP.bounding.y) || (MAP.array == NULL) || (XMAX < XMIN)) return; if (start == end) MAP.array[start] ^= ((RIGHTBITS(sbit))&LEFTBITS(ebit)); else { MAP.array[start] ^= (RIGHTBITS(sbit)); for(start++;start == (ArrayOfBits) two dimensional array of bits to be modified * X == (int) column to be modified in the 2-d array * YMIN == (int) low bit to begin modification * YMAX == (int) high bit to end modification *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * History: *H * Thomas Wood October 1990, Original Version Kernghan&Ritchie C * Updated August 1991, ANSI C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E ****************************************************************************/ void SETCOLUMN( ArrayOfBits MAP, int X, int YMIN, int YMAX ) { register int yymax /*= YMAX*/; register int yymin /*= YMIN*/; register int start /*= (((yymin)*(MAP.rowcount))+((X)>>3))*/; register int mask = (1 << ((X) % 8)); if (YMIN < 0) YMIN = 0; yymin = YMIN; start = (((yymin)*(MAP.rowcount))+((X)>>3)); if (YMAX > MAP.bounding.y) YMAX = MAP.bounding.y; yymax = YMAX; if ((0 > X) || (X > MAP.bounding.x) || (MAP.array == NULL) || (YMAX < YMIN)) return; MAP.array[start] |= mask; start += MAP.rowcount; for(;yymin == (ArrayOfBits) 2-d array to be modified * X == (int) column to be modified * YMIN == (int) starting bit * YMAX == (int) ending bit *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990 Original Version Kernighan&Ritchie C * Updated August 1991, ANSI C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions/Macros Called: *FM * None *E ****************************************************************************/ void CLEARCOLUMN( ArrayOfBits MAP, int X, int YMIN, int YMAX ) { register int yymax /*= YMAX*/; register int yymin /*= YMIN*/; register int start /*= (((yymin)*(MAP.rowcount))+((X)>>3))*/; register int mask = ~(1<<((X)%8)); if (YMIN < 0) YMIN = 0; yymin = YMIN; start = (((yymin) * (MAP.rowcount)) + ((X) >> 3)); if (YMAX > MAP.bounding.y) YMAX = MAP.bounding.y; yymax = YMAX; if ((0 > X) || (X > MAP.bounding.x) || (MAP.array == NULL) || (YMAX < YMIN)) return; MAP.array[start] &= mask; start += MAP.rowcount; for(;yymin == (ArrayOfBits) 2-d array to be modified * X == (int) column to be modified * YMIN == (int) starting bit * YMAX == (int) ending bit *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * XORs bits in column X of 2-d array MAP from bits YMIN to YMAX. * Mask is 1's, index is YMIN through YMAX. *E *****************************************************************************/ void TOGGLECOLUMN( ArrayOfBits MAP, int X, int YMIN, int YMAX ) { register int yymax /*= YMAX*/; register int yymin /*= YMIN*/; register int start /*= (((yymin)*(MAP.rowcount))+((X)>>3))*/; register int mask = (1<<((X)%8)); if (YMIN < 0) YMIN = 1; yymin = YMIN; start = (((yymin) * (MAP.rowcount)) + ((X) >> 3)); if (YMAX > MAP.bounding.y) YMAX = MAP.bounding.y; yymax = YMAX; if ((0 > X) || (X > MAP.bounding.x) || (MAP.array == NULL) || (YMAX < YMIN)) return; MAP.array[start] ^= mask; start += MAP.rowcount; for(;yymin> 3. The array allocation is: * (unsigned char *) calloc((deltaY+1), rowcount). *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * deltaX == (int) x width of 2-d bit array * deltaY == (int) y width of 2-d bit array * MakeArrayOfBits == (ArrayOfBits) empty 2-d bit array *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990 Original Version Kernighan&Ritchie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions/Macros Called: *FM * Xmark() XMEMORY.H * Xclear() XMEMORY.H * Xcalloc(nelem, elsize) *E *****************************************************************************/ ArrayOfBits MakeArrayOfBits( int deltaX, int deltaY ) { ArrayOfBits value; int temp; temp = deltaX + 1; temp += 7; value.rowcount = temp >> 3; value.bounding.x = deltaX; value.bounding.y = deltaY; Xmark(); value.array = (unsigned char *)Xcalloc( (deltaY + 1), value.rowcount); Xclear(); return value; } /****************************************************************************** * *N FreeArrayOfBits * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Erases a map, then returns 0. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * map == (ArrayOfBits) map to be erased * FreeArrayOfBits == (int) value of map *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990, Original Version Kernighan&Ritchie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Macros Called: *FM * Xfree *E *****************************************************************************/ int FreeArrayOfBits ( ArrayOfBits map ) { Xfree(map.array); return 0; } /****************************************************************************** * *N PointGetBit * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Tells the user whether the bit at point(x,y) is set to 0 or 1.(error * checking: will return 0 if the point sent is outside of the range of * the map). *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * map == (ArrayOfBits) 2-d array to be checked * point == (IPoint) coordinated to check * PointGetBit == (int) results of check *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990, Original Version Kernighan&Ritchie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions/Modules Called: *FM * OUTISDE(MAP,POINT) BITARRAY.C * GETBIT(MAP,POINT) BITARRAY.C *E *****************************************************************************/ int PointGetBit ( ArrayOfBits map, IPoint point ) { if (map.array == NULL) return 0; if (OUTSIDE(map,point)) return 0; return GETBIT(map,point); } /***************************************************************************** * *N PointSetBit * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Sets a bit to value at point at in map. value must be 1 or 0 *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * map == (ArrayOfBits) 2-d array to be modified * at == (IPoint) coordinates to set set * value == (int) value to set coordinates to * PointSetBit == (int) value that coordinates were set to *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990, Original Version Kernighan&Ritchie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions/Modules Called: *FM * OUTSIDE(MAP,POINT) BITARRAY.C * SETBIT(MAP,POINT) BITARRAY.C * CLEARBIT(MAP,POINT) BITARRAY.C *E *****************************************************************************/ int PointSetBit ( ArrayOfBits map, IPoint at, int value) { if (map.array == NULL) return 0; if (OUTSIDE(map,at)) return 0; if (value) return SETBIT(map,at); return CLEARBIT(map,at); } /****************************************************************************** * *N LineSetBit * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Sets bit in a line with coordinates from set in map. Lines can be * sloping, vertical, or horizontal, but the beginning coordinates * must be less than the ending coordinates, and all coordinates should * be within map (there is error checking for this, basically nothing is * done). Sets the bits for value=1, clears the bits for value=0. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * map == (ArrayOfBits) 2-d array to be modified * seg == (ISegment) line coordinates(to,from) for the line * value == (int) 0 to clear bits, 1 to set bits * LineSetBit == (int) value that bits were set to *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990, Original Version Kernighan&Ritchie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions/Macros Called: *FM * OUTSIDE(MAP,POINT) BITARRAY.C * SETBIT(MAP,POINT) BITARRAY.C * CLEARBIT(MAP,POINT) BITARRAY.C * MAXIMUM(X,Y) BITARRAY.C * MINIMUM(X,Y) BITARRAY.C * OUTSIDE_X(MAP,Value) BITARRAY.C * OUTSIDE_Y(MAP,Value) BITARRAY.C * FILLBRESSEG(bseg,seg) BITARRAY.C * STEP(bseg) BITARRAY.C * SETROW(ArrayOfBits MAP, int XMIN, int XMAX, int Y ) BITARRAY.C * CLEARROW(ArrayOfBits MAP, int XMIN, int XMAX, int Y ) BITARRAY.C * SETCOLUMN(ArrayOfBits MAP, int X, int YMIN, int YMAX ) BITARRAY.C * CLEARCOLUMN(ArrayOfBits MAP, int X, int YMIN, int YMAX ) BITARRAY.C *E ******************************************************************************/ int LineSetBit ( ArrayOfBits map, ISegment seg, int value ) { BresSegment bseg; unsigned int from,to; if (map.array == NULL) return 0; if ((!seg.delta.x)&&(!seg.delta.y)) { if (OUTSIDE(map,seg.origin)) return 0; if (value) SETBIT(map,seg.origin); else CLEARBIT(map,seg.origin); return 0; } /* horizontal line */ if (seg.delta.y == 0) { if (OUTSIDE_Y(map,seg.origin.y)) return 0; if (seg.delta.x < 0) { from = MAXIMUM(seg.origin.x + seg.delta.x, 0); to = MINIMUM(seg.origin.x, map.bounding.x); } else { from = MAXIMUM(seg.origin.x, 0); to = MINIMUM(seg.origin.x + seg.delta.x, map.bounding.x); } if (from > to) return 0; if (from == to) { if (value) { seg.origin.x = from; SETBIT(map,seg.origin); } else { seg.origin.x = from; CLEARBIT(map,seg.origin); } } if (value) { SETROW(map,from,to,seg.origin.y); } else { CLEARROW(map,from,to,seg.origin.y); } return 0; } /* vertical line */ if (seg.delta.x == 0) { if (OUTSIDE_X(map,seg.origin.x)) return 0; if (seg.delta.y < 0) { from = MAXIMUM(seg.origin.y + seg.delta.y ,0); to = MINIMUM(seg.origin.y, map.bounding.y); } else { from = MAXIMUM(seg.origin.y, 0); to = MINIMUM(seg.origin.y + seg.delta.y, map.bounding.y); } if (from > to) return 0; if (from == to) { if (value) { seg.origin.y = from; SETBIT(map,seg.origin); } else { seg.origin.y = from; CLEARBIT(map,seg.origin); } } if (value) { SETCOLUMN(map,seg.origin.x,from,to); } else { CLEARCOLUMN(map,seg.origin.x,from,to); } return 0; } /* sloping line */ FILLBRESSEG(bseg,seg); for(;bseg.maximum;) { if (!OUTSIDE(map,bseg.at)) { if (value) { SETBIT(map,bseg.at); } else { CLEARBIT(map,bseg.at); } } STEP(bseg); } if (!OUTSIDE(map,bseg.at)) { if (value) SETBIT(map,bseg.at); else CLEARBIT(map,bseg.at); } return 0; } /****************************************************************************** * *N LineXorBit * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * If value=1, an XOR is done on all bits(actually, just a toggle of off bits * to on and on bits to off. If value=0, nothing is done *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * map == (ArrayOfBits) 2-d array to be modified * seg == (ISegment) line coords for modification * value == (int) tell whether to XOR or not * LineXorBit == (int) tell whether XORed or not *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990, Kernighan&Ritchie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions/Macros Called: *FM * OUTSIDE(MAP,POINT) BITARRAY.C * SETBIT(MAP,POINT) BITARRAY.C * MAXIMUM(x,y) BITARRAY.C * MINIMUM(x,y) BITARRAY.C * OUTSIDE_Y(MAP,value) BITARRAY.C * OUTSIDE_X(MAP,value) BITARRAY.C * FILLBRESSEG(bseg,seg) BITARRAY.C * STEP(bseg) BITARRAY.C * SETROW(ArrayOfBits MAP, int XMIN, int XMAX, int Y) BITARRAY.C * SETCOLUMN(ArrayOfBits MAP, int X, int YMIN, int YMAX) BITARRAY.C *E ******************************************************************************/ int LineXorBit ( ArrayOfBits map, ISegment seg, int value ) { BresSegment bseg; unsigned int from,to; if (!value) return 0; if (map.array == NULL) return 0; if ((!seg.delta.x)&&(!seg.delta.y)) { if (OUTSIDE(map,seg.origin)) return 0; TOGGLEBIT(map,seg.origin); return 0; } if (seg.delta.y == 0) { if (OUTSIDE_Y(map,seg.origin.y)) return 0; if (seg.delta.x < 0) { from = MAXIMUM(seg.origin.x + seg.delta.x, 0); to = MINIMUM(seg.origin.x, map.bounding.x); } else { from = MAXIMUM(seg.origin.x, 0); to = MINIMUM(seg.origin.x + seg.delta.x, map.bounding.x); } if (from > to) return 0; if (from == to) { seg.origin.x = from; TOGGLEBIT(map,seg.origin); } TOGGLEROW(map,from,to,seg.origin.y); return 0; } if (seg.delta.x == 0) { if (OUTSIDE_X(map,seg.origin.x)) return 0; if (seg.delta.y < 0) { from = MAXIMUM(seg.origin.y + seg.delta.y ,0); to = MINIMUM(seg.origin.y, map.bounding.y); } else { from = MAXIMUM(seg.origin.y, 0); to = MINIMUM(seg.origin.y + seg.delta.y, map.bounding.y); } if (from > to) return 0; if (from == to) { seg.origin.y = from; TOGGLEBIT(map,seg.origin); } TOGGLECOLUMN(map,seg.origin.x,from,to); return 0; } /* sloping line */ FILLBRESSEG(bseg,seg); for(;bseg.maximum;) { if (!OUTSIDE(map,bseg.at)) TOGGLEBIT(map,bseg.at); STEP(bseg); } if (!OUTSIDE(map,bseg.at)) TOGGLEBIT(map,bseg.at); return 0; } /****************************************************************************** * *N TrapezoidXorBit * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Turns off any bit that was on, turns on any bit that was of in the line * designated by coordinates in seg. This is only done if value=1, else * 0 is returned and nothing is done *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * map == (ArrayOfBits) 2-d array to be modified * seg == (ISegment) line designated by 2 coords * value == (int) if 0, returns 0, else swaps bits * TrapezoidXorBit == (int) returns 0 *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990 Original Version Kernighan&Ritchie C * Updated August 1991 ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions/Macros Called: *FM * OUTSIDE_X(MAP,value) BITARRAY.C * MINUMUM(x,y) BITARRAY.C * MAXIMUM(x,y) BITARRAY.C * FILLBRESSEG(bseg,seg) BITARRAY.C * TOGGLEROW(ArrayOfBits MAP,int XMIN,int XMAX,int Y) BITARRAY.C * TOGGLECOLUMN(ArrayOfBits MAP,int X,int YMIN,int YMAX) BITARRAY.C *E *****************************************************************************/ int TrapezoidXorBit( ArrayOfBits map, ISegment seg, int value ) { BresSegment bseg; int xmin,xmax,to /*,temp*/; if (map.array == NULL) return 0; if (!value) return 0; if (seg.delta.x == 0) { if (OUTSIDE_X(map,seg.origin.x)) return 0; if (seg.delta.y < 0) to = MINIMUM(seg.origin.y, map.bounding.y); else to = MINIMUM(seg.origin.y + seg.delta.y, map.bounding.y); if (0 > to) return 0; TOGGLECOLUMN(map,seg.origin.x,0,to); return 0; } if (seg.delta.y == 0) { if (seg.origin.y < 0) return 0; if (seg.origin.y > map.bounding.y) to = map.bounding.y; else to = seg.origin.y; if (seg.delta.x < 0) { xmin = MAXIMUM(seg.origin.x + seg.delta.x, 0); xmax = MINIMUM(seg.origin.x, map.bounding.x); } else { /* temp = seg.origin.x + seg.delta.x;*/ xmin = MAXIMUM(seg.origin.x, 0); xmax = MINIMUM(seg.origin.x + seg.delta.x, map.bounding.x); } if (xmin > xmax) return 0; for(; 0 <= to; to--) { TOGGLEROW(map,xmin,xmax,to); } return 0; } /* sloping line */ FILLBRESSEG(bseg,seg); for(;bseg.maximum;) { if (bseg.toggle) { if ((bseg.Eprim>=0) && ((bseg.at.y>=0) && ((bseg.at.x>=0) &&(bseg.at.x<=map.bounding.x)))) { to = MINIMUM(bseg.at.y, map.bounding.y); { TOGGLECOLUMN(map,bseg.at.x,0,to); } } } else if ((bseg.at.y>=0) && ((bseg.at.x>=0)&&(bseg.at.x<=map.bounding.x))) { to = MINIMUM(bseg.at.y, map.bounding.y); { TOGGLECOLUMN(map,bseg.at.x,0,to); } } STEP(bseg); } if ((bseg.at.y>=0) && ((bseg.at.x>=0)&&(bseg.at.x<=map.bounding.x))) { to = MINIMUM(bseg.at.y, map.bounding.y); { TOGGLECOLUMN(map,bseg.at.x,0,to); } } return 0; } ossim-Miami-2.9.1/src/vpfutil/distance.c000066400000000000000000000057561352751253100201460ustar00rootroot00000000000000#include /************************************************************************* * *N distance * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function computes the distance between two points on the * surface of the (spherical) earth. The points are specified in * geographic coordinates (lat1,lon1) and (lat2,lon2). The algorithm * used here is taken directly from ELEMENTS OF CARTOGRAPHY, 4e. - * Robinson, Sale, Morrison - John Wiley & Sons, Inc. - pp. 44-45. * Geometrically, the function computes the arc distance dtheta on * the sphere between two points A and B by the following formula: * * cos dtheta = (sin a sin b) + (cos a cos b cos p) * * where: * * dtheta = arc distance between A and B * a = latitude of A * b = latitude of B * p = degrees of longitude between A and B * * Once the arc distance is determined, it is converted into miles by * taking the ratio between the circumference of the earth (2*PI*R) and * the number of degrees in a circle (360): * * distance in miles (d) arc distance in degrees (dtheta) * ------------------------------ = -------------------------------- * earth's circumference in miles earth's circumference in degrees * * or * * d = (dtheta * (2*PI*R)) / 360 => * d = (dtheta*PI*R)/180 * * The calculated distance is also referred to as the Great Circle. * *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * lat1 == (double) latitude of point A. * lon1 == (double) longitude of point A. * lat2 == (double) latitude of point B. * lon2 == (double) longitude of point B. * units == (int) flag to indicate output distance units. * 0 -> Miles, 1 -> Kilometers *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels November 1990 Original Version DOS Turbo C * Added kilometers option - May 1991 - BJM *E *************************************************************************/ float distance(double lat1, double lon1, double lat2, double lon2, int units ) { double a,b,p,dtheta,d; double R[2] = { 3958.754, 6370.997 } #ifndef PI , PI=3.141592654 #endif ; double DEG2RAD=(PI/180.0), RAD2DEG=(180.0/PI); if ((units<0)||(units>1)) units = 0; if (lat1 > 90.0) lat1 -= 180.0; if (lat2 > 90.0) lat2 -= 180.0; a = lat1*DEG2RAD; /* Degrees must be converted to radians */ b = lat2*DEG2RAD; p = fabs(lon1-lon2)*DEG2RAD; dtheta = (sin(a)*sin(b)) + (cos(a)*cos(b)*cos(p)); dtheta = acos(dtheta)*RAD2DEG; /* Compute arc distance in degrees */ d = (dtheta*PI*R[units])/180.0; /* Compute distance in miles or km */ return (float)d; } ossim-Miami-2.9.1/src/vpfutil/linklist.c000066400000000000000000000442071352751253100201770ustar00rootroot00000000000000/************************************************************************* * *N Module LINKLIST.C * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions that make up a singly linked list * data structure. It is generic in the sense that it can hold any * type of data, including user-defined types and structures. That * is why you must treat the data element as a void pointer and pass * in its size when inserting into the list. These routines are * assured of working with "non-pointer" types of data elements. * If you try storing other lists, or structures with pointers hanging * off of them, the results will become unpredictable. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * linked_list_type ll_init(); * int ll_empty( linked_list_type list ); * position_type ll_first( linked_list_type list ); * position_type ll_last( linked_list_type list ); * position_type ll_next( position_type position ); * position_type ll_previous( position_type position, linked_list_type * list ); * int ll_end( position_type position ); * void ll_element( position_type position, void *element ); * void ll_insert( void *element, unsigned size, position_type position ); * void ll_delete( position_type position ); * void ll_reset( linked_list_type list ); * position_type ll_locate( void *element, linked_list_type list ); * void ll_replace( void *element, position_type position ); *E *************************************************************************/ #ifdef __MSDOS__ #include #include #else #ifdef __APPLE__ #include #include #else #if !defined(__OpenBSD__) && !defined( __FreeBSD__) #include #include #endif #endif #endif #include #include #include #include #ifndef __MSDOS__ #define farmalloc malloc #define farfree free #define movmem(a,b,c) memmove(b,a,c) #endif /************************************************************************* * *N ll_init * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function allocates and initializes a new linked list structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * ll_init == (linked_list_type) initialized head of the list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ linked_list_type ll_init() { linked_list_type list; if ((list = (linked_list_type) farmalloc( sizeof(cell_type) ))==NULL) { printf("Out of memory in ll_init()\n"); exit(1); } list->element = NULL; list->element_size = 0; list->next = NULL; return list; } /************************************************************************* * *N ll_empty * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function TRUE if the list is empty and FALSE if it is not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * list == (linked_list_type) linked list being checked. * ll_empty == (int) boolean function result. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ int ll_empty( linked_list_type list ) { if (list == NULL) return TRUE; if (list->next == NULL) return TRUE; else return FALSE; } /************************************************************************* * *N ll_first * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the head of the list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * list == (linked_list_type) linked list. * ll_first == (position_type) head of the list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ position_type ll_first( linked_list_type list ) { return ((position_type) list); } /************************************************************************* * *N ll_last * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns *THE* last position in the list, which is * not useable. Use ll_previous to get to the las USEABLE link in * the list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * list == (linked_list_type) linked list. * ll_last == (position_type) tail of the list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ position_type ll_last( linked_list_type list ) { position_type p; p = (position_type) list; while (p->next != NULL) p = p->next; return p; } /************************************************************************* * *N ll_next * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the next position in the list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * position == (position_type) current position in the list. * ll_next == (position_type) next position in the list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ position_type ll_next( position_type position ) { return(position->next); } /************************************************************************* * *N ll_previous * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the previous position in the list. Note: * This is a singly linked list -> no backward pointer -> this * operation is relatively inefficient. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * position == (position_type) current position. * list == (linked_list_type) linked list. * ll_previous == (position_type) previous position in the list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ position_type ll_previous( position_type position, linked_list_type list ) { position_type p; if (position==list) return(position); p = list; while (p->next != position) p = p->next; return(p); } /************************************************************************* * *N ll_end * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines if the given position is at the end of the * list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * position == (position_type) current position in the list. * ll_end == (int) TRUE -- if position is the end of the list. * FALSE -- if not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ int ll_end( position_type position ) { if (position == NULL) return(TRUE); else { if (position->next == NULL) return(TRUE); else return(FALSE); } } /************************************************************************* * *N ll_element * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function copies the element at position in the list into the * contents of element. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * position == (position_type) position in the list. * element == (void *) pointer to the element data. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ void ll_element( position_type position, void *element ) { movmem(position->next->element,element,position->next->element_size); } /************************************************************************* * *N ll_insert * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function inserts a new cell into the list at position that will * contain the data pointed to by element. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * element == (void *) pointer to the data element to insert. * size == (unsigned) size of the data element. * position == (position_type) position to insert the new cell. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ void ll_insert( void *element, unsigned size, position_type position ) { position_type temp; if ((temp = (position_type) farmalloc( sizeof(cell_type) )) == NULL) { printf("out of memory\n"); abort(); } temp->next = position->next; position->next = temp; temp->element_size = size; if ((temp->element = farmalloc( size ))==NULL) { printf("out of memory\n"); abort(); } movmem(element,temp->element,size); } /************************************************************************* * *N ll_delete * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function deletes and disposes of a cell from the linked list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * position == (position_type) position in the list to delete. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ void ll_delete( position_type position ) { position_type p; if (position != NULL) { /* Cut the element out of the chain */ p = position->next; position->next = p->next; farfree( p->element ); farfree( p ); } } /************************************************************************* * *N ll_reset * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function empties out a linked list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * list == (linked_list_type) linked list to be emptied. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void ll_delete( position_type position ); * int ll_empty( linked_list_type list ); *E *************************************************************************/ void ll_reset( linked_list_type list ) { while (! ll_empty(list)) ll_delete(ll_first(list)); farfree(list); list = NULL; } /************************************************************************* * *N ll_locate * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function locates a position in the list by comparing data. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * element == (void *) pointer to the data element to locate. * list == (linked_list_type) linked list. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ position_type ll_locate( void *element, linked_list_type list ) { position_type p; p = list; while (p->next != NULL) { if ( memcmp(p->next->element,element,p->next->element_size) == 0 ) return p; else p = p->next; } return NULL; } /************************************************************************* * *N ll_replace * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function replaces an element in the linked list at the given * position. WARNING: The new data element must be the same size as * the previous data element or you will get some rather INTERESTING * results. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * element == (void *) data element to replace existing data. * position == (position_type) position in the list to replace * the data. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb. 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ void ll_replace( void *element, position_type position ) { movmem(element,position->next->element,position->next->element_size); } ossim-Miami-2.9.1/src/vpfutil/polygrf.c000066400000000000000000000230201352751253100200160ustar00rootroot00000000000000/****************************************************************************** * *N Module POLYGRF.C * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Coordinate transformations of points. Can create and manipulate * sets of x,y coords *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October, 1990, Kurnigan/Ritchie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions: *F * ISegment MakeISegment( IPoint from, IPoint to ); * ITransform MakeITransform( IBox from, IBox to ); * IPoint TranslateIPoint( ITransform transform, IPoint a, int flag ); * IBox AndIBox( IBox a, IBox b ); *E *****************************************************************************/ #include #include /****************************************************************************** * *N MakeISegment * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Called with two sets of xy coordinates, from and to. Returns from and * the delta of from and to. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * from == (IPoint) originating xy coordinates. * to == (IPoint) ending xy coordinates. * MakeISegment == (ISegement) origin and delta *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October 1990 Original Kurnigan/Ritchie C * Updated August 1991, ANSI C *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *****************************************************************************/ ISegment MakeISegment( IPoint from, IPoint to ) { ISegment current; current.origin = from; current.delta.x = to.x - from.x; current.delta.y = to.y - from.y; return current; } /***************************************************************************** * *N MakeITransform * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Inputs two sets of origin coordinates plus their delta coordinates. * Calculates and returns offset of the origins and if the deltas are * different, the new scale. (if deltas are the same, scale is 1.0). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * from == (IBox) originating coordinates & delta * to == (IBOX) ending coordinates and delta * MakeITransform == (ITransform) offset and scale *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood, October 1990, Original version Kurnigan/Ritchie C * Updated August 1991, ANSI C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E ****************************************************************************/ ITransform MakeITransform( IBox from, IBox to ) { ITransform current; register float temp; current.scale.x = current.scale.y = 1.0; if ((to.delta.x == 0.0)|| (from.delta.x == 0.0)) to.delta.x = from.delta.x = 1; if ((to.delta.y == 0.0)|| (from.delta.y == 0.0)) to.delta.y = from.delta.y = 1; if (to.delta.x == from.delta.x) current.offset.x = to.origin.x - from.origin.x; else { current.scale.x = (float)to.delta.x / (float)from.delta.x; temp = (float)(to.origin.x * from.delta.x); temp = temp / to.delta.x; temp += (float)((temp < 0)? -.05: 0.5); current.offset.x = (int)(temp - from.origin.x); } if (to.delta.y == from.delta.y) current.offset.y = to.origin.y - from.origin.y; else { current.scale.y = (float)to.delta.y / (float)from.delta.y; temp = (float)(to.origin.y * from.delta.y); temp = temp / to.delta.y; temp += (float)((temp < 0)? -.05: 0.5); current.offset.y = (int)(temp - from.origin.y); } return current; } /***************************************************************************** * *N TranslateIPoint * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Rescales 'a' based on flag and transform. If flag is 1, scales down, * else up. Scaling factor based on transform.scale and transform.offset *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * transform == (ITransform) tranformation index/ratio * a == (IPoint) coordinates to be transformed * flag == (int) scale index (up=0,down=1) * TranslateIPoint == (IPoint) scaled coordinates *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood, October 1990, Original Version Kurnigan/Ritchie C * Updated August 1991, ANSI C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E ****************************************************************************/ IPoint TranslateIPoint( ITransform transform, IPoint a, int flag ) { IPoint output; register float temp; output = a; if ((transform.scale.x == 1.0)||(transform.scale.x == 0.0)) output.x += ((flag)? -1: 1) * transform.offset.x; else { if (flag) { temp = (float)output.x; temp /= transform.scale.x; temp += (float)((temp < 0)? -.05: 0.5); temp -= transform.offset.x; output.x = (int)temp; } else { temp = (float)(output.x + transform.offset.x); temp *= transform.scale.x; temp += (float)((temp < 0)? -.05: 0.5); output.x = (int)temp; } } if ((transform.scale.y == 1)||(transform.scale.y == 0.0)) output.y += ((flag)? -1: 1) * transform.offset.y; else { if (flag) { temp = (float)output.y; temp /= transform.scale.y; temp += (float)((temp < 0)? -.05: 0.5); temp -= transform.offset.y; output.y = (int)temp; } else { temp = (float)(output.y + transform.offset.y); temp *= transform.scale.y; temp += (float)((temp < 0)? -.05: 0.5); output.y = (int)temp; } } return output; } /***************************************************************************** * *N AndIBox * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Inputs two sets of coordinates and deltas, checks if coords are proper. * If not, returns IBox=-1. Calculates origin values plus delta. IF 'a' * origin values < 'b' origin values, returns -1. Finally, the higher origin * values and lower delta values are calculated and returned *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * a == (IBox) set of coords plus deltas * b == (IBox) set of coords plus deltas * AndIBox == (IBox) set of highest values of above *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Thomas Wood October, 1990, Kurnigan/Ritchie C * Updated August 1991, ANSI C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * isBox *E ****************************************************************************/ IBox AndIBox( IBox a, IBox b ) { IBox output; IPoint acorner,bcorner; output.origin.x = output.delta.x = output.origin.y = output.delta.y = -1; if (!isBox(a)) return output; if (!isBox(b)) return output; acorner.x = a.origin.x + a.delta.x; acorner.y = a.origin.y + a.delta.y; bcorner.x = b.origin.x + b.delta.x; bcorner.y = b.origin.y + b.delta.y; if (acorner.x < b.origin.x) return output; if (acorner.y < b.origin.y) return output; if (bcorner.x < a.origin.x) return output; if (bcorner.y < a.origin.y) return output; if (a.origin.x < b.origin.x) output.origin.x = b.origin.x; else output.origin.x = a.origin.x; if (a.origin.y < b.origin.y) output.origin.y = b.origin.y; else output.origin.y = a.origin.y; if (acorner.x < bcorner.x) output.delta.x = acorner.x - output.origin.x; else output.delta.x = bcorner.x - output.origin.x; if (acorner.y < bcorner.y) output.delta.y = acorner.y - output.origin.y; else output.delta.y = bcorner.y - output.origin.y; return output; } ossim-Miami-2.9.1/src/vpfutil/set.c000066400000000000000000000767221352751253100171500ustar00rootroot00000000000000/************************************************************************* * *N Module SET.C * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions that make up an abstract data type * "set". The data structures and algorithms herein allow programs * to perform basic manipulations defined in the mathematics of set * theory. These operations are fundamental to relational database * theory, as well. * * This version allows sets too large to fit in memory to be swapped * out to disk. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C * Nov 1991 - Embedded bit manipulation routines instead of using a * separate module (speed & size). * Nov 1991 - Added disk swapping capabilities. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * set_type set_init( long int n ); * int set_empty( set_type set ); * void set_insert( long int element, set_type set ); * void set_delete( long int element, set_type set ); * int set_member( long int element, set_type set ); * long int set_min( set_type set ); * long int set_max( set_type set ); * int num_in_set( set_type set ); * void set_on( set_type set ); * void set_off( set_type set ); * int set_equal( set_type a, set_type b ); * void set_assign( set_type *a, set_type b ); * set_type set_union( set_type a, set_type b ); * set_type set_intersection( set_type a, set_type b ); * set_type set_difference( set_type a, set_type b ); * void set_nuke( set_type *set ); *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * These functions are all ANSI C compatible. *E *************************************************************************/ #if defined(__MSDOS__) || defined(__MINGW32__) # include # include # include # include #else #ifndef _WIN32 #include #endif #endif #include #include #include #include #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif static char chkmask[] = {254,253,251,247,239,223,191,127}; static char setmask[] = {1,2,4,8,16,32,64,128}; #define BITSET(bit,byte) ((byte | chkmask[bit]) ^ chkmask[bit]) #define SET_BIT(bit,byte) (byte | setmask[bit]) #define UNSET_BIT(bit,byte) (byte ^ setmask[bit]) #define NBYTES(set) ((set.size>>3L) + 1L) /* #define BOUNDSCHECK 1 */ static char set_byte( long int nbyte, set_type set ) { char byte; if ( (nbyte < 0) || (nbyte > NBYTES(set)) ) return 0; if (set.diskstorage) { fseek(set.fp,nbyte,SEEK_SET); fread(&byte,1,1,set.fp); } else { byte = set.buf[nbyte]; } return byte; } #define SET_BYTE( nbyte, set, byte )\ if ( (nbyte < 0) || (nbyte > NBYTES(set)) ) byte = 0; \ if (set.diskstorage) { \ fseek(set.fp,nbyte,SEEK_SET); \ fread(&byte,1,1,set.fp); \ } else { \ byte = set.buf[nbyte]; \ } /************************************************************************* * *N set_off * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Turns each element in the set 'off'. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * set == (set_type) set to be acted upon. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Nov 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ void set_off( set_type set ) { register long int nbytes, nbyte, bufsize; char byte=0, *buf; if (set.diskstorage) { rewind(set.fp); nbytes = NBYTES(set); /* Use buffered reads and writes to set blocks of bits at a time */ nbyte = 0; while (nbyte < nbytes) { #ifdef __MSDOS__ bufsize = (long int)min(nbytes-nbyte,farcoreleft()/2L); #else bufsize = (long int)(nbytes-nbyte); #endif buf = (char *)malloc(bufsize); memset(buf,byte,bufsize); fwrite(buf,bufsize,1,set.fp); free(buf); nbyte += bufsize; } rewind(set.fp); } else { SET_OFF(set); } } /************************************************************************* * *N set_on * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Turns each element in the set 'on'. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * set == (set_type) set to be acted upon. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Nov 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ void set_on( set_type set ) { register long int nbytes,i, bufsize, nbyte; #if !defined(__MSDOS__) unsigned #endif char byte=255, *buf; if (set.diskstorage) { rewind(set.fp); nbytes = NBYTES(set); /* Use buffered reads and writes to set blocks of bits */ nbyte = 0; while (nbyte < nbytes) { #ifdef __MSDOS__ bufsize = (long int)min(nbytes-nbyte,farcoreleft()/2L); buf = (char*)malloc(bufsize); #else bufsize = (long int)(nbytes-nbyte); buf = (unsigned char*)malloc(bufsize); #endif memset(buf,byte,bufsize); fwrite(buf,bufsize,1,set.fp); free(buf); nbyte += bufsize; } } else { /* Turn on all bits up through set.size. */ /* All but the last byte. */ memset(set.buf,byte,set.size>>3L); /* The valid bits of the last byte. */ for (i=(set.size>>3L)*8L;i<=set.size;i++) set_insert(i,set); } } #if __MSDOS__ static long int available_space( char *drive ) { struct dfree disktable; int disknum; if (!drive) return 0; disknum=toupper(drive[0])-'A'+1; getdfree(disknum,&disktable); return (long int) disktable.df_avail * (long int) disktable.df_sclus * (long int) disktable.df_bsec; } #endif /************************************************************************* * *N set_init * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Initialize the set for 'n' elements. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * n == (long int) maximum number of elements in the set. * return == (set_type) initialized set. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ set_type set_init( long int n ) { set_type s; long int nbytes; s.size = n; nbytes = NBYTES(s); s.fp = 0; // initialize variable #ifdef __MSDOS__ if (nbytes < (farcoreleft()/2L)-4096L) { #endif s.buf = (char *)malloc(nbytes); s.diskstorage = 0; #ifdef __MSDOS__ } else { s.diskstorage = 1; s.buf = (char *)malloc(20); /* If the user has specified a RAM disk, use it (faster) */ if (getenv("TMP") && nbytes < available_space(getenv("TMP"))) sprintf(s.buf,"%s\\%s",getenv("TMP"),tmpnam(NULL)); else tmpnam(s.buf); s.fp = fopen(s.buf,"w+b"); if (!s.fp) { perror("set_init: "); exit(1); } } #endif set_off(s); return s; } /************************************************************************* * *N set_empty * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns TRUE if the given set is empty; else it * returns FALSE. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * set == (set_type) set. * return == (int) TRUE[1] or FALSE[0]. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ int set_empty( set_type set ) { register long int i, nbytes; nbytes = NBYTES(set); for (i=0;i == (long int) element to insert into the set. * set == (set_type) set. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ void set_insert( long int element, set_type set ) { long int nbyte,bit; char byte; if ((element<0)||(element>set.size)) { #ifdef BOUNDSCHECK printf("Invalid call to set_insert! (%ld, %ld)\n", element,set.size); exit(1); #endif return; } nbyte = element>>3L; /* element/8 */ bit = element%8L; SET_BYTE(nbyte,set,byte); byte = SET_BIT(bit,byte); if (set.diskstorage) { fseek(set.fp,nbyte,SEEK_SET); fwrite(&byte,1,1,set.fp); } else { set.buf[nbyte] = byte; } } /************************************************************************* * *N set_delete * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function deletes the given element from the specified set. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * element == (long int) element to delete from the set. * set == (set_type) set. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void unset_bit() BITSTUFF.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ void set_delete( long int element, set_type set ) { long int nbyte,bit; char byte; if ((element<0)||(element>set.size)) { #ifdef BOUNDSCHECK printf("Invalid call to set_delete!\n"); exit(1); #endif return; } nbyte = element>>3L; /* element/8 */ bit = element%8L; SET_BYTE(nbyte,set,byte); if (!BITSET(bit,byte)) return; byte = UNSET_BIT(bit,byte); if (set.diskstorage) { fseek(set.fp,nbyte,SEEK_SET); fwrite(&byte,1,1,set.fp); } else { set.buf[nbyte] = byte; } } /************************************************************************* * *N set_member * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether a given element is a member of * the specified set. It returns either TRUE or FALSE. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * element == (long int) element to check in the set. * set == (set_type) set. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void bitset() BITSTUFF.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ int set_member( long int element, set_type set ) { long int nbyte,bit; char byte; if ((element < 0)||(element > set.size)) return FALSE; nbyte = element>>3L; /* element/8L */ bit = element%8L; SET_BYTE(nbyte,set,byte); return BITSET(bit,byte); } /************************************************************************* * *N set_min * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the minimum element in the given set. * If the set is empty, the return value is -1. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * set == (set_type) set. * return == (long int) minimum element in the set. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void bitset() BITSTUFF.C * int set_empty( set_type set ) SET.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ long int set_min( set_type set ) { register long int nbyte, bit, element, nbytes, bufsize, i; char byte='\0', *buf, on; /* Find the first byte with a bit set */ nbytes = NBYTES(set); if (set.diskstorage) { /* Set is stored on disk, use block reads to get set into */ /* memory one chunk at a time */ nbyte = 0; on = 0; rewind(set.fp); while (nbyte < nbytes) { #ifdef __MSDOS__ bufsize = (long int)min(nbytes-nbyte,farcoreleft()/2L); #else bufsize = (long int)(nbytes-nbyte); #endif buf = (char *)malloc(bufsize); fread(buf,bufsize,1,set.fp); for (i=0;i set.size) return -1; if (BITSET(bit,byte)) return element; } return -1; } /************************************************************************* * *N set_max * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the maximum element in the given set. * If the set is empty, the return value is 0. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * set == (set_type) set. * return == (long int) maximum element in the set. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ long int set_max( set_type set ) { register long int nbyte, bit, element, nbytes, bufsize, i; char byte='\0', *buf=0, on='\0'; /* Find the last byte with a bit set */ nbytes = NBYTES(set); if (set.diskstorage) { /* Set is stored on disk, use block reads to get set into */ /* memory one chunk at a time */ nbyte = nbytes-1L; on = 0; while (nbyte > 0) { #ifdef __MSDOS__ bufsize = (long int)min(nbyte+1L,farcoreleft()/2L); #else bufsize = (long int)(nbyte+1L); #endif buf = (char *)malloc(bufsize); fseek(set.fp,nbyte-bufsize+1L,SEEK_SET); fread(buf,bufsize,1,set.fp); for (i=bufsize-1L;i>0;i--,nbyte--) { if (buf[i]) { on = 1; byte = buf[i]; break; } } free(buf); if (on) break; } } else { for (nbyte = nbytes-1; nbyte >= 0; nbyte--) { if (set.buf[nbyte]) { byte = set.buf[nbyte]; break; } } if (nbyte < 0) return 0L; } /* Now find last bit set in the byte */ element = nbyte*8L + 7L; for (bit=7; bit >= 0; bit--,element--) { if (BITSET(bit,byte)) { return element; } } return 0L; } /************************************************************************* * *N num_in_set * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the number of elements in the given set. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * set == (set_type) set. * return == (long int) number of elements in the set. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void bitset() BITSTUFF.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ long int num_in_set( set_type set ) { register long int nbyte,bit,n=0, nbytes; char byte; nbytes = NBYTES(set); for (nbyte=0;nbyte == (set_type) first set to compare. * b == (set_type) second set to compare. * return == (int) TRUE if (a==b) or FALSE if (a!=b). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ int set_equal( set_type a, set_type b ) { long int i, nbytes; if (a.size != b.size) return FALSE; if ((!a.diskstorage)&&(!b.diskstorage)) { if (memcmp(a.buf,b.buf,NBYTES(a))==0) return TRUE; else return FALSE; } else { nbytes = NBYTES(a); for (i=0;i == (set_type *) set to be assigned. * b == (set_type) set to assign to a. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ void set_assign( set_type *a, set_type b ) { register long int nbytes, nbyte, bufsize; char *buf; nbytes = NBYTES(b); if (!a->diskstorage && !b.diskstorage) { if (a->size == b.size) { memcpy(a->buf,b.buf,nbytes); } else { /* a and b are different sizes */ a->buf = (char *)realloc(a->buf,nbytes); if (a->buf==NULL) { a->diskstorage = 1; a->fp = tmpfile(); fwrite(b.buf,1,nbytes,a->fp); } else { memcpy(a->buf,b.buf,nbytes); } a->size = b.size; } } else { /* Either a or b or both are stored on disk */ if (a->diskstorage && !b.diskstorage) { rewind(a->fp); fwrite(b.buf,1,nbytes,a->fp); a->size = b.size; } else { /* b.diskstorage must be true to get here */ if (!a->diskstorage) { /* Force a->diskstorage */ a->diskstorage = 1; if (a->size > 0) free(a->buf); a->fp = tmpfile(); } /* Block copy file from b.fp to a->fp */ nbyte = 0; rewind(b.fp); rewind(a->fp); while (nbyte < nbytes) { #ifdef __MSDOS__ bufsize = (long int)min(nbytes-nbyte,farcoreleft()/2L); #else bufsize = (long int)(nbytes-nbyte); #endif buf = (char *)malloc(bufsize); fread(buf,bufsize,1,b.fp); fwrite(buf,bufsize,1,a->fp); free(buf); nbyte += bufsize; } a->size = b.size; } } } #if 0 /************************************************************************* * *N set_union * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Return the set C such that C = (A U B). C is initialized within * this function, and should be nuked when no longer needed. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * a == (set_type) set to be unioned. * b == (set_type) set to be unioned. * return == (set_type) (A U B). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * set_type set_init() SET.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ set_type set_union( set_type a, set_type b ) { register long int i, nbytes; set_type c; char byte; c = set_init( (long int)max(a.size,b.size) ); nbytes = NBYTES(c); for (i=0;i == (set_type) set to be intersectioned. * b == (set_type) set to be intersectioned. * return == (set_type) (A o B). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * set_type set_init() SET.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ set_type set_intersection( set_type a, set_type b ) { register long int i, nbytes; set_type c; char byte; #ifdef __MSDOS__ c = set_init( (long int)max(a.size,b.size) ); #else c = set_init( a.size > b.size ? a.size : b.size ); #endif if (c.diskstorage) rewind(c.fp); nbytes = NBYTES(c); for (i=0;i == (set_type) set to subtract from. * b == (set_type) set to be subtracted. * return == (set_type) (A - B). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * set_type set_init() SET.C * int set_member() SET.C * void set_insert() SET.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ set_type set_difference( set_type a, set_type b ) { register long int i; set_type c; c = set_init( a.size ); for (i=0;i<=a.size;i++) { if ( i > b.size ) { if (set_member(i,a)) set_insert( i, c ); } else { if ((set_member(i,a)) && (!set_member(i,b))) set_insert(i,c); } } return c; } #endif /************************************************************************* * *N set_nuke * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Nucleate a set from existence. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * set == (set_type *) set to be nuked. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This function conforms to ANSI C standards. *E *************************************************************************/ void set_nuke( set_type *set ) { if (set->diskstorage) { fclose(set->fp); unlink(set->buf); } free( set->buf ); set->size = -1; set->diskstorage = 0; } ossim-Miami-2.9.1/src/vpfutil/vpfclip.c000066400000000000000000000173341352751253100200120ustar00rootroot00000000000000/************************************************************************* * *N Module VPFCLIP * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module geometrically clips an edge table to a given map * extent and creates a new edge table. It does not attempt to * maintain topology, nor does it maintain its relationship to * any feature tables associated with it. Its intent is to be * used only for the Library Reference coverage. It may also serve * as a basic starting point for a complete GIS clipping algorithm. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Dec 1991 DOS Turbo C *E *************************************************************************/ #include #include #include #if defined(__MSDOS__) || defined(__MINGW32__) # include # include #else # ifdef __APPLE__ # include # include # else #if !defined(__OpenBSD__) && !defined( __FreeBSD__) # include # include # endif # endif #endif #include #include #include # ifndef min # define min(a,b) ((a) <= (b) ? (a) : (b)) # endif # ifndef max # define max(a,b) ((a) <= (b) ? (b) : (a)) # endif typedef struct { float x1, y1, x2, y2; } line_segment_type; /* Defined in VPFPTPLY.C */ int intersect( line_segment_type l1, line_segment_type l2, float *xint, float *yint ); edge_rec_type create_edge_rec( row_type row, vpf_table_type edge_table ); /* Determine if a line segment intersects a box. */ /* If so return the intersection coordinate in the parameter list. */ static int box_intersection( line_segment_type lseg, extent_type extent, coordinate_type *coord ) { line_segment_type boxseg; float xint, yint; boxseg.x1 = extent.x1; boxseg.y1 = extent.y1; boxseg.x2 = extent.x2; boxseg.y2 = extent.y1; if (intersect(lseg,boxseg,&xint,&yint)) { coord->x = xint; coord->y = yint; return TRUE; } boxseg.x1 = extent.x2; boxseg.y1 = extent.y1; boxseg.x2 = extent.x2; boxseg.y2 = extent.y2; if (intersect(lseg,boxseg,&xint,&yint)) { coord->x = xint; coord->y = yint; return TRUE; } boxseg.x1 = extent.x2; boxseg.y1 = extent.y2; boxseg.x2 = extent.x1; boxseg.y2 = extent.y2; if (intersect(lseg,boxseg,&xint,&yint)) { coord->x = xint; coord->y = yint; return TRUE; } boxseg.x1 = extent.x1; boxseg.y1 = extent.y2; boxseg.x2 = extent.x1; boxseg.y2 = extent.y1; if (intersect(lseg,boxseg,&xint,&yint)) { coord->x = xint; coord->y = yint; return TRUE; } return FALSE; } /* Replace the given coordinate string into the given edge row */ /* and write the new row to the specified edge table. */ static void write_edge_record( ossim_int32 id, coordinate_type *coord, ossim_int32 ncoord, row_type row, vpf_table_type *table ) { int ID_, COORD_; ID_ = table_pos("ID",*table); COORD_ = table_pos("COORDINATES",*table); put_table_element(ID_, row, *table, &id, 1); put_table_element(COORD_, row, *table, coord, ncoord); write_next_row(row,table); } #define WITHIN(x,y,ext) ((x>=ext.x1)&&(x<=ext.x2)&&(y>=ext.y1)&&(y<=ext.y2)) /************************************************************************* * *N vpf_edge_clip * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function clips an edge table to the given extent and writes * the clipped table to the specified output path. * NOTE: If a segment of an edge in the EDG table has both a beginning * point and ending point outside of the given extent, and the line * segment passes through the extent, the segment will not be written * out to the new edge table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * covpath == (char *) path to the coverage of the edge table. * extent == (extent_type) clipping extent. * outpath == (char *) output path for the clipped edge table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Dec 1991 Original Version DOS Turbo C *E *************************************************************************/ void vpf_edge_clip( char *covpath, extent_type extent, char *outpath ) { vpf_table_type in, out; row_type row; edge_rec_type inedge, outedge; ossim_int32 i,j,n,id; line_segment_type lseg; coordinate_type coord; char path[255], *def; float xmin, xmax, ymin, ymax; /* Standardize extent, Lower Left, Upper Right */ xmin = (float)min(extent.x1,extent.x2); xmax = (float)max(extent.x1,extent.x2); ymin = (float)min(extent.y1,extent.y2); ymax = (float)max(extent.y1,extent.y2); extent.x1 = xmin; extent.y1 = ymin; extent.x2 = xmax; extent.y2 = ymax; sprintf(path,"%sedg",covpath); in = vpf_open_table(path,disk,"rb",NULL); rewind(in.fp); fread(&n,sizeof(n),1,in.fp); def = (char *)vpfmalloc((n+1)*sizeof(char)); fread(def,sizeof(char),n,in.fp); def[n] = '\0'; sprintf(path,"%sedg",outpath); out = vpf_open_table(path,disk,"wb",def); for (i=1,id=1;i<=in.nrows;i++) { row = get_row( i, in ); inedge = create_edge_rec( row, in ); if (!inedge.coord) { free_row(row,in); continue; } outedge.coord = (coordinate_type *)malloc(inedge.npts*sizeof( coordinate_type)); if (!outedge.coord) { free(inedge.coord); free_row(row,in); continue; } n = 0; for (j=0;j 0) { if (!WITHIN(inedge.coord[j-1].x,inedge.coord[j-1].y, extent)) { /* Previous coordinate was not in the extent - */ /* create an intersection vertex */ lseg.x1 = inedge.coord[j-1].x; lseg.y1 = inedge.coord[j-1].y; lseg.x2 = inedge.coord[j].x; lseg.y2 = inedge.coord[j].y; if (box_intersection(lseg,extent,&coord)) { outedge.coord[n].x = coord.x; outedge.coord[n].y = coord.y; } else { outedge.coord[n].x = lseg.x1; outedge.coord[n].y = lseg.y1; } n++; } } outedge.coord[n].x = inedge.coord[j].x; outedge.coord[n].y = inedge.coord[j].y; n++; } else { if (j > 0) { if (WITHIN(inedge.coord[j-1].x,inedge.coord[j-1].y,extent)) { /* The coordinate is not within the extent and */ /* the previous one was - Create an intersection */ /* vertex point and write the current edge record. */ lseg.x1 = inedge.coord[j-1].x; lseg.y1 = inedge.coord[j-1].y; lseg.x2 = inedge.coord[j].x; lseg.y2 = inedge.coord[j].y; if (box_intersection(lseg,extent,&coord)) { outedge.coord[n].x = coord.x; outedge.coord[n].y = coord.y; } else { outedge.coord[n].x = lseg.x2; outedge.coord[n].y = lseg.y2; } /* Break the edge in (at least) two */ n++; write_edge_record( id, outedge.coord, n, row, &out ); id++; n=0; } } } } free(inedge.coord); if (n > 0) { write_edge_record( id, outedge.coord, n, row, &out ); id++; } free(outedge.coord); free_row(row,in); } vpf_close_table(&in); vpf_close_table(&out); } ossim-Miami-2.9.1/src/vpfutil/vpfcntnt.c000066400000000000000000000323321352751253100202040ustar00rootroot00000000000000/*************************************************************************** * *N VPFCNTNT.C - VPF Contents * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions to display the contents of VPF tables * and VPF databases and libraries. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels November 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E **************************************************************************/ #if defined(__CYGWIN__) || defined(__APPLE__)|| defined(_WIN32) || defined(__FreeBSD__) || defined(__OpenBSD__) # include "ossim/vpfutil/values.h" #else # include #endif #include #ifdef __MSDOS__ # include # include # include # include #else # ifndef _WIN32 # include # endif # ifdef __APPLE__ # include # include # define MAXINT INT_MAX # ifndef MAXSHORT # define MAXSHORT SHORT_MAX # endif # define MAXLONG LONG_MAX # else #if !defined(__OpenBSD__) && !defined( __FreeBSD__) # include # endif # endif #endif #ifdef _MSC_VER # include #endif #include #include #include #include #include #include #include /************************************************************************** * *N vpf_dump_table * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Dump the contents of a VPF table into an ASCII file *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * tablename == (char *) VPF table to dump. * outname == (char *) name of ASCII dump file. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ void vpf_dump_table( char *tablename, char *outname ) { vpf_table_type table; ossim_int32 i,j,k,n; int ival,*iptr; ossim_int32 lval,*lptr; float fval,*fptr; date_type dval,*dptr; id_triplet_type kval, *kptr; coordinate_type cval, *cptr; char *buf, ch, date[40]; row_type row; FILE *fp; fp = fopen(outname,"w"); table = vpf_open_table(tablename,disk,"rb",NULL); fprintf(fp,"%s\n%s\n\n",tablename,table.description); fprintf(fp,"Definition:\n"); for (i=0;i80) { fprintf(fp,"\n"); n = 0; } } fprintf(fp,"\n"); free(buf); } break; case 'I': if (table.header[j].count==1) { get_table_element(j,row,table,&lval,&n); if (lval != MAXFLOAT) fprintf(fp,"%d\n",lval); else fprintf(fp,"(null)\n"); } else { lptr = (ossim_int32*)get_table_element(j,row,table,NULL,&n); for (k=0;k == (char *) narrative-style .DOC VPF table to dump. * outname == (char *) name of ASCII dump file. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ void vpf_dump_doc_table( char *tablename, char *outname ) { vpf_table_type table; ossim_int32 i,n; char *buf; row_type row; FILE *fp; fp = fopen(outname,"w"); table = vpf_open_table(tablename,disk,"rb",NULL); /* Check header to make sure the table is a narrative table */ if ((ossim_strcasecmp(table.header[1].name,"TEXT") != 0) || (table.nfields != 2)) { /* Not a real narrative table -> normal VPF table dump */ vpf_close_table(&table); vpf_dump_table(tablename,outname); return; } fprintf(fp,"%s\n%s\n\n",tablename,table.description); for (i=1;i<=table.nrows;i++) { row = read_next_row(table); buf = (char *)get_table_element(1,row,table,NULL,&n); fprintf(fp,"%s\n",buf); free(buf); free_row(row,table); } fclose(fp); vpf_close_table( &table ); } #if 0 static void not_a_vpf_table( char *path ) { char *buf,*filename,*tempstr,ch; buf = (char *)vpfmalloc(255); filename = (char *)vpfmalloc(255); /* Not a VPF table - try to determine what type of file it is */ if (strstr(path,"\\asi") || strstr(path,"\\lsi") || strstr(path,"\\nsi") || strstr(path,"\\csi") || strstr(path,"\\tsi")) { sprintf(filename,"%s is a spatial index file.",path); displaymessage(filename, "It is not a VPF table and cannot be viewed directly", NULL); } else if (strstr(path,".ati") || strstr(path,".lti") || strstr(path,".pti") || strstr(path,".tti")) { sprintf(filename,"%s is a thematic index file.",path); displaymessage(filename, "It is not a VPF table and cannot be viewed directly", NULL); } else if (path[strlen(path)-1] == 'x') { /* Need to determine what file it is the index for */ sprintf(buf,"%s is a variable-length index file",path); strcpy(filename,path); for (ch='a';ch <= 'z';ch++) { if (ch=='x') continue; filename[strlen(path)-1] = ch; if (access(filename,0) == 0) { tempstr = strdup(filename); sprintf(filename,"for %s.",tempstr); free(tempstr); break; } } if (strcmp(path,filename)==0) { displaymessage(buf, "It is not a VPF table and cannot be viewed directly.", NULL); } else { displaymessage(buf, filename, "It is not a VPF table and cannot be viewed directly.", NULL); } } else { /* Not a VPF type of file */ sprintf(filename,"%s: Not a VPF table",path); display_message(filename); } free(filename); free(buf); } #endif #if 0 /************************************************************************** * *N display_database_contents * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * List the tables in the Database level directory and display their * contents if selected. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * database == (database_type) VPF database. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ void display_database_contents( database_type database ) { char *filename, *dbpath, *path, *dbstr; dbstr = (char *)vpfmalloc(128); dbpath = (char *)vpfmalloc(255); filename = (char *)vpfmalloc(128); path = (char *)vpfmalloc(255); strcpy( dbstr, "Database: " ); strcat( dbstr, database.name ); strcpy(dbpath,database.path); strcat(dbpath,"*.*"); do { strcpy(filename,pickfile(dbpath,0,dbstr)); if (strcmp(filename,"")==0) break; strcpy( path, database.path ); strcat( path, filename ); rightjust(path); strlwr(path); if (is_vpf_table(path)) { if (strstr(path,".doc")) vpf_dump_doc_table(path,"temp.out"); else vpf_dump_table(path,"temp.out"); viewfile("temp.out", getmaxy()/3); unlink("temp.out"); } else { not_a_vpf_table(path); } } while (strcmp(filename,"") != 0); free(path); free(filename); free(dbpath); free(dbstr); } /************************************************************************** * *N display_library_contents * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * List the tables in the Library level directory and display their * contents if selected. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * library == (library_type) VPF library structure. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ void display_library_contents( library_type library ) { char *filename, *libpath, *path, *libstr; libstr = (char *)vpfmalloc(128); libpath = (char *)vpfmalloc(255); filename = (char *)vpfmalloc(128); path = (char *)vpfmalloc(255); strcpy( libstr, "Library: " ); strcat( libstr, library.name ); strcpy(libpath,library.path); strcat(libpath,"*.*"); do { strcpy(filename,pickfile(libpath,0,libstr)); if (strcmp(filename,"")==0) break; strcpy( path, library.path ); strcat( path, filename ); rightjust(path); leftjust(path); strlwr(path); if (is_vpf_table(path)) { strlwr(path); if (strstr(path,".doc")) vpf_dump_doc_table(path,"temp.out"); else vpf_dump_table(path,"temp.out"); viewfile("temp.out", getmaxy()/3); unlink("temp.out"); } else { not_a_vpf_table(path); } } while (strcmp(filename,"") != 0); free(path); free(filename); free(libpath); free(libstr); } #endif ossim-Miami-2.9.1/src/vpfutil/vpfdict.c000066400000000000000000000144661352751253100200110ustar00rootroot00000000000000#include #include #ifdef __MSDOS__ #include #endif #ifdef __MSDOS__ #include #include #else #ifdef __APPLE__ #include #include #else #if !defined(__OpenBSD__) && !defined( __FreeBSD__) #include #include #endif #endif #endif #include #include #include extern color_type menutextcolor,menubordercolor,menucolor; #if 0 /************************************************************************* * *N feature_class_dictionary * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function displays the data dictionary for a feature class. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * fc == (int) feature class number. * lib == (library_type) VPF library structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Mody Buchbinder May 1991 Original Version DOS Turbo C * Barry Michaels July 1991 - Separated into two routines * Barry Michaels Oct 1991 - Modified narrative table read *E *************************************************************************/ void feature_class_dictionary( int fc, library_type lib ) { int i,j,k, it_pos,val_pos,des_pos,att_pos; char *outfile,*line,temp[128],temp2[128], *item_buf, *att_buf, *des_buf, *tval; vpf_table_type ft,table,nar; storage_type stor = disk; FILE *out; row_type row; float fval; ossim_int32 ival,n; hidemousecursor(); time_cursor(); showmousecursor(); /** prepare temporary display file **/ outfile = (char *)malloc(L_tmpnam + 2); outfile = tmpnam(outfile); out = fopen(outfile,"w"); /** start to write to display file **/ fprintf(out,"FEATURE CLASS: %s \n",lib.fc[fc].description); fprintf(out,"COVERAGE : %s \n", lib.cover[lib.fc[fc].coverage].description); ft = vpf_open_table(lib.fc[fc].table,stor,"rb",NULL); fprintf(out,"ATTRIBUTES:\n"); for(i=0;i == (library_type) VPF library structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Mody Buchbinder May 1991 Original Version DOS Turbo C * Barry Michaels June 1991 - Separated into two routines. * Barry Michaels Oct 1991 - Feature class selection from a panel. * Barry Michaels Jan 1992 - Select FCs by coverage first. *E *************************************************************************/ void display_data_dictionary(library_type lib) { int fc,cov; view_type dummyview; char title[80]; dummyview.nthemes = 0; cov = 0; while (cov >= 0) { sprintf(title,"%s COVERAGES",lib.name); cov = select_coverage(&dummyview,&lib,title); if (cov < 0) break; fc = 0; while (fc >= 0) { sprintf(title,"%s Feature Classes",lib.cover[cov].description); fc = select_feature_class(&dummyview,&lib,title,cov); if (fc < 0) break; feature_class_dictionary( fc, lib ); } } } #endif ossim-Miami-2.9.1/src/vpfutil/vpfdisp.c000066400000000000000000000314411352751253100200150ustar00rootroot00000000000000/************************************************************************* * *N Module VPFDISP - Display VPF records * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions used to display VPF records in * human readable format. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ #include #include #if defined(__MINGW32__) # include # include # include # include # ifdef __MSDOS__ # include # include # include # include # include # endif # ifdef _MSC_VER # include # endif # ifndef _WIN32 # include # endif # ifdef __APPLE__ # include # include # define MAXSHORT 255 # define MAXLONG LONG_MAX # else # include # endif #endif #include #include #include #if defined(__CYGWIN__) || defined(__APPLE__)|| defined(_WIN32) #include #else #include #endif #include #include #include #if (!defined(_WIN32)||defined(__CYGWIN__)) # include /* For "access" function. */ #endif extern color_type menucolor, menubordercolor, menutextcolor; #ifndef __MSDOS__ void strupr2(char* str) { char* s = str; while (*s) { *s = toupper(*s); ++s; } } #endif /************************************************************************* * *N format_date * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function converts a VPF date value into a string of the * form mm/dd/yyyy with time displayed as hh:mm:ss if non-zero. * 'fmtdate' must be a character string with at least 18 bytes * allocated. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * date ==(date_type) VPF date type value. * fmtdate ==(char *) output formatted date string. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Sept 1991 DOS Turbo C *E *************************************************************************/ void format_date( date_type date, char *fmtdate ) { char year[8], month[8], day[8], hour[8], min[8], sec[8]; date[20]='\0'; strncpy(year, date, 4); year[4]='\0'; strncpy(month, &date[4], 2); month[2]='\0'; strncpy(day, &date[6], 2); day[2]='\0'; strncpy(hour, &date[8], 2); hour[2]='\0'; strncpy(min, &date[10], 2); min[2]='\0'; strncpy(sec, &date[12], 2); sec[2]='\0'; if ( (strcmp(hour,"00") == 0) && (strcmp(min,"00")==0) && (strcmp(sec,"00") == 0) ) sprintf(fmtdate,"%s/%s/%s",month,day,year); else sprintf(fmtdate,"%s/%s/%s %s:%s:%s",month,day,year,hour,min,sec); } /************************************************************************* * *N vpf_display_record * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function displays all of the fields of a particular VPF * record, including the descriptions of the fields and their * values. It accesses the online data dictionary metadata * contained in the specified Value Description Tables. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row == (row_type) vpf table row structure. * table == (vpf_table_type) vpf table. * fp == (FILE *) pointer to the output file. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Sept 1991 DOS Turbo C *E *************************************************************************/ void vpf_display_record( row_type row, vpf_table_type table, FILE *fp ) { register int i,j; char *buf,*num, path[128], *tablename; char *attr,*val,*descr, vdtpath[128], fmtdate[40]; vpf_table_type vdt; row_type vdtrow; int found; ossim_int32 l, lval, count, *lptr; short int s,sval,*sptr; float f,*fptr; date_type date; int TABLE_ = 1, ATTR_ = 2, VAL_ = 3, DESCR_ = 4; vdt.status = CLOSED; num = (char *)vpfmalloc(20*sizeof(char)); strcpy( vdtpath, "" ); /* Display all secondary attributes */ for (i=0;i == (int) feature class number. * row == (ossim_int32) row of the attribute table. * library == (library_type *) VPF library structure. * fp == (FILE *) pointer to the output file. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void display_attributes( int fc, ossim_int32 row, library_type *library, FILE *fp ) { vpf_table_type feature_table; row_type vpfrow; feature_table = vpf_open_table(library->fc[fc].table,disk,"rb",NULL); vpfrow = read_row( row, feature_table ); vpf_display_record( vpfrow, feature_table, fp ); free_row(vpfrow,feature_table); vpf_close_table(&feature_table); } ossim-Miami-2.9.1/src/vpfutil/vpfdraw.c000066400000000000000000001272321352751253100200170ustar00rootroot00000000000000/************************************************************************* * *N Module VPFDRAW - DRAW VPF FEATURES * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions for drawing selected VPF * features. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Nov 1991 DOS Turbo C *E *************************************************************************/ #include #ifdef __MSDOS__ #include #endif #include #include #ifdef __MSDOS__ #include #include #endif #include #if defined(__CYGWIN__) || defined(__APPLE__) || defined(_WIN32) #include #else #include #endif #ifdef __MSDOS__ #include #endif #include #include #include #ifdef __MSDOS__ #include #include #endif #include #ifdef __MSDOS__ #include "grprim.h" #endif #include #include extern char home[255]; typedef struct { float x1,y1,x2,y2; } line_segment_type; #ifdef __MSDOS__ /************************************************************************* * *N draw_edge_coordinates * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws the coordinates of an edge record. * It tries its darndest to detect and get rid of projection * "zingers" - lines that dart across the screen because of * lines projected onto the map that wrap around behind the * globe or change hemispheres. The ability to handle these * projection artifacts is what turns what should be a very * simple function into a very ugly piece of code. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * edge_rec ==(edge_rec_type *) pointer to an edge record. * return ==(int) 0 if the user escapes, 1 upon successful * completion. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Feb 1992 DOS Turbo C *E *************************************************************************/ int draw_edge_coordinates( edge_rec_type *edge_rec ) { int xscr,yscr, xprev,yprev, x1,y1,x2,y2, mbrx2, wrap; register ossim_int32 i; extent_type mbr; coordinate_type coord; /* First compute the MBR from the coordinates. */ coord = first_edge_coordinate(edge_rec); mbr.x1 = coord.x; mbr.y1 = coord.y; mbr.x2 = coord.x; mbr.y2 = coord.y; for (i=1;inpts;i++) { coord = next_edge_coordinate(edge_rec); if (coord.x < mbr.x1) mbr.x1 = coord.x; if (coord.y < mbr.y1) mbr.y1 = coord.y; if (coord.x > mbr.x2) mbr.x2 = coord.x; if (coord.y > mbr.y2) mbr.y2 = coord.y; } screen_bounds(mbr.x1,mbr.y1,mbr.x2,mbr.y2,&x1,&y1,&x2,&y2); if ( (x1 < 0 && x2 < 0) || (x1 > gpgetmaxx() && x2 > gpgetmaxx()) || (y1 < 0 && y2 < 0) || (y1 > gpgetmaxy() && y2 > gpgetmaxy()) ) return 1; if (x1 > gpgetmaxx() && x2 < 0) return 1; wrap = 0; mbrx2 = x2; if (x2 < x1) { /* The box wraps around the screen */ /* (or at least wraps off the edge of the screen) */ wrap = gpgetmaxx(); if (x2 < 0) wrap -= x2; /* Adjust the maximum screen value */ x2 += wrap; } coord = first_edge_coordinate(edge_rec); screenxy(coord.x,coord.y,&xscr,&yscr); if (wrap && xscr < x1) xscr += wrap; gpmoveto(xscr,yscr); xprev = xscr; yprev = yscr; for (i=1;inpts;i++) { coord = next_edge_coordinate(edge_rec); screenxy(coord.x,coord.y,&xscr,&yscr); if (xscr == MAXINT || yscr == MAXINT) { xprev = xscr; yprev = yscr; continue; } if (wrap && xscr < x1) xscr += wrap; if (xscr==xprev && yscr==yprev) continue; if (xprev == MAXINT || yprev == MAXINT) gpmoveto(xscr,yscr); hidemousecursor(); gplineto( xscr, yscr ); showmousecursor(); xprev = xscr; yprev = yscr; while (kbhit()) { if (getch()==27) { return 0; } } } if (wrap && mbrx2 > 0) { /* The edge wraps around and is displayed on the other */ /* edge of the screen. */ x2 -= wrap; coord = first_edge_coordinate(edge_rec); screenxy(coord.x,coord.y,&xscr,&yscr); if (xscr > x2) xscr -= wrap; gpmoveto(xscr,yscr); xprev = xscr; yprev = yscr; for (i=1;inpts;i++) { coord = next_edge_coordinate(edge_rec); screenxy(coord.x,coord.y,&xscr,&yscr); if (xscr == MAXINT || yscr == MAXINT) { xprev = xscr; yprev = yscr; continue; } if (xscr > x2) xscr -= wrap; if (xscr==xprev && yscr==yprev) continue; if (xprev == MAXINT || yprev == MAXINT) gpmoveto(xscr,yscr); hidemousecursor(); gplineto( xscr, yscr ); showmousecursor(); xprev = xscr; yprev = yscr; while (kbhit()) { if (getch()==27) { return 0; } } } } return 1; } /************************************************************************* * *N draw_edge_row * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws the selected edge for a given row in * the edge primitive table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row ==(row_type)row in the edge primitive table. * table ==(vpf_table_type) edge table. * return ==(int) 0 if the user escapes, 1 upon successful * completion. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels August 1991 DOS Turbo C *E *************************************************************************/ int draw_edge_row( row_type row, vpf_table_type table ) { edge_rec_type edge_rec; int stat; edge_rec = create_edge_rec(row,table); stat = draw_edge_coordinates(&edge_rec); if (edge_rec.coord) free(edge_rec.coord); gpstroke(); while (kbhit()) { if (getch()==27) { return 0; } } return stat; } /************************************************************************* * *N draw_edge * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws the selected edge for a given row number in * the edge primitive table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * rownum ==(ossim_int32)row number of the edge primitive table. * table ==(vpf_table_type) edge table. * return ==(int) 0 if the user escapes, 1 upon successful * completion. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels August 1991 DOS Turbo C *E *************************************************************************/ int draw_edge( ossim_int32 rownum, vpf_table_type table ) { int stat; row_type row; row = get_row( rownum, table ); stat = draw_edge_row(row,table); free_row(row,table); return stat; } /************************************************************************* * *N draw_point_row * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws an entity node for the row in the given * entity node primitive table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row ==(row_type) row of the entity node * primitive table. * table ==(vpf_table_type) entity node primitive table. * return ==(int) 0 if the user escapes, 1 upon successful * completion. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels August 1991 DOS Turbo C *E *************************************************************************/ int draw_point_row( row_type row, vpf_table_type table ) { int xscr,yscr, coord_pos; ossim_int32 n; coordinate_type pnt; coord_pos = table_pos("COORDINATE",table); get_table_element(coord_pos,row,table,&pnt,&n); screenxy(pnt.x,pnt.y,&xscr,&yscr); hidemousecursor(); gpmarker(xscr,yscr); showmousecursor(); while (kbhit()) { if (getch()==27) { return 0; } } return 1; } /************************************************************************* * *N draw_point * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws an entity node for the row number of the given * entity node primitive table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * rownum ==(ossim_int32) row number of the entity node * primitive table. * table ==(vpf_table_type) entity noe primitive table. * return ==(int) 0 if the user escapes, 1 upon successful * completion. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels August 1991 DOS Turbo C *E *************************************************************************/ int draw_point( ossim_int32 rownum, vpf_table_type table ) { int stat; row_type row; row = get_row( rownum, table ); stat = draw_point_row(row,table); free_row(row,table); return stat; } /************************************************************************* * *N draw_text_row * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws annotation for a given row in the text * pseudo-primitive table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row ==(row_type) row of the text table. * table ==(vpf_table_type) text primitive table. * return ==(int) 0 if the user escapes, 1 upon successful * completion. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels August 1991 DOS Turbo C *E *************************************************************************/ int draw_text_row( row_type row, vpf_table_type table ) { int xscr,yscr, shape_pos, text_pos; ossim_int32 n, nshape; coordinate_type *shape_line; char *text; struct viewporttype vp; shape_pos = table_pos("SHAPE_LINE",table); /**** MUST CHECK FOR 'Z', 'B', AND 'Y' TYPES - SEE VPFPRIM.C ****/ shape_line = (coordinate_type *)get_table_element(shape_pos,row,table, NULL,&nshape); text_pos = table_pos("STRING",table); text = (char *)get_table_element(text_pos,row,table,NULL,&n); screenxy(shape_line[0].x,shape_line[0].y,&xscr,&yscr); getviewsettings(&vp); if ((gpgetfont() != DEFAULT_FONT) || (yscr > gptextheight(text))) { hidemousecursor(); gptext(xscr,yscr,text); showmousecursor(); } free(shape_line); free(text); while (kbhit()) { if (getch()==27) { return 0; } } return 1; } /************************************************************************* * *N draw_text * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws annotation for a given row number in the text * pseudo-primitive table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * rownum ==(ossim_int32) row number of the text table. * table ==(vpf_table_type) text primitive table. * return ==(int) 0 if the user escapes, 1 upon successful * completion. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels August 1991 DOS Turbo C *E *************************************************************************/ int draw_text( ossim_int32 rownum, vpf_table_type table ) { int stat; row_type row; row = get_row( rownum, table ); stat = draw_text_row(row,table); free_row(row,table); return stat; } static IPoint make_ipoint( int x, int y ) { IPoint point; point.x = x; point.y = y; return point; } static IBox make_ibox( int x1, int y1, int x2, int y2 ) { IBox box; if (x1 < x2) box.origin.x = x1; else box.origin.x = x2; if (y1 < y2) box.origin.y = y1; else box.origin.y = y2; box.delta.x = abs(x2-x1); box.delta.y = abs(y2-y1); return box; } /************************************************************************* * *N screen_bounds * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines the screen bounds of a rectangular * map area, independent of any projection that may distort the * boundaries. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * x1 ==(double) lower left x map coordinate. * y1 ==(double) lower left y map coordinate. * x2 ==(double) upper right x map coordinate. * y2 ==(double) upper right y map coordinate. * xmin ==(int *) lower left x screen coordinate. * ymin ==(int *) lower left y screen coordinate. * xmax ==(int *) upper right x screen coordinate. * ymax ==(int *) upper right y screen coordinate. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void screen_bounds( double x1, double y1, double x2, double y2, int *xmin, int *ymin, int *xmax, int *ymax ) { int xscr,yscr; double xc,yc; /* x center and y center */ xc = (x1+x2)/2.0; yc = (y1+y2)/2.0; /* Find xmin from x1 */ screenxy(x1,y1,&xscr,&yscr); *xmin = xscr; screenxy(x1,yc,&xscr,&yscr); if (xscr < (*xmin)) *xmin = xscr; screenxy(x1,y2,&xscr,&yscr); if (xscr < (*xmin)) *xmin = xscr; /* Find xmax from x2 */ screenxy(x2,y2,&xscr,&yscr); *xmax = xscr; screenxy(x2,yc,&xscr,&yscr); if (xscr > (*xmax)) *xmax = xscr; screenxy(x2,y1,&xscr,&yscr); if (xscr > (*xmax)) *xmax = xscr; /* Find ymin from y2 (seems backwards - but so is the screen) */ screenxy(x1,y2,&xscr,&yscr); *ymin = yscr; screenxy(xc,y2,&xscr,&yscr); if (yscr < (*ymin)) *ymin = yscr; screenxy(x2,y2,&xscr,&yscr); if (yscr < (*ymin)) *ymin = yscr; /* Find ymax from y1 */ screenxy(x1,y1,&xscr,&yscr); *ymax = yscr; screenxy(xc,y1,&xscr,&yscr); if (yscr > (*ymax)) *ymax = yscr; screenxy(x2,y1,&xscr,&yscr); if (yscr > (*ymax)) *ymax = yscr; } /************************************************************************* * *N gen_polygon_edge * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function generates a polygon edge in the Shademap structure * given an edge record structure. * It is complicated by having to check whether this polygon * has wrapped around the screen from the projection and adjusting * the coordinates, if so. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * edge_rec ==(edge_rec_type) input edge record. * poly ==(Shademap *) polygon structure being updated. * wrap ==(int) amount of wrap around if the polygon * wraps around the screen. If this number * is positive, the coordinates will be * adjusted out to the right. If negative, * they will adjusted to the left. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void gen_polygon_edge( edge_rec_type edge_rec, Shademap *poly, int wrap ) { register ossim_int32 i,start,end,inc; int xscr,yscr; IPoint pnt, make_ipoint(); coordinate_type coord; if (edge_rec.left == edge_rec.right) return; if (edge_rec.dir == '-') { start = edge_rec.npts-1; end = 0; inc = -1; } else { start = 0; end = edge_rec.npts-1; inc = 1; } for (i=start;i!=end;i+=inc) { coord = get_edge_coordinate(i,&edge_rec); screenxy(coord.x,coord.y,&xscr,&yscr); if (wrap > 0 && xscr < poly->bounding.origin.x) xscr += wrap; if (wrap < 0 && xscr > poly->bounding.origin.x+poly->bounding.delta.x) xscr += wrap; pnt = make_ipoint(xscr,yscr); gpwriteshade( poly, pnt ); } coord = get_edge_coordinate(i,&edge_rec); screenxy(coord.x,coord.y,&xscr,&yscr); if (wrap > 0 && xscr < poly->bounding.origin.x) xscr += wrap; if (wrap < 0 && xscr > poly->bounding.origin.x+poly->bounding.delta.x) xscr += wrap; pnt = make_ipoint(xscr,yscr); gpwriteshade( poly, pnt ); } /************************************************************************* * *N draw_polygon_edge * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws an edge of a polygon. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * edge_rec ==(edge_rec_type) input edge record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void draw_polygon_edge( edge_rec_type edge_rec ) { if (edge_rec.left == edge_rec.right) return; draw_edge_coordinates(&edge_rec); } #ifdef TRACE /************************************************************************* * *N trace_polygon_loop * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function traces a loop (or ring) of a polygon by chaining * through the right and/or left edges of the edge table, including * tracing through all dangles. This is winged-edge topology in action. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * face_id ==(ossim_int32) row id of the specified face. * start_edge ==(ossim_int32) row id of the edge that starts the * loop. * edgetable ==(vpf_table_type) VPF edge primitive table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void trace_polygon_loop(ossim_int32 face_id, ossim_int32 start_edge, vpf_table_type edgetable ) { edge_rec_type edge_rec; ossim_int32 next, prevnode; boolean done=FALSE; IPoint make_ipoint(); edge_rec = read_edge( start_edge, edgetable ); #ifdef WATCH gotoxy(1,17); printf("edge: %5ld left: %5ld edge:%5ld right: %5ld edge: %5ld", edge_rec.id,edge_rec.left,edge_rec.leftfwd,edge_rec.right, edge_rec.rightfwd); #endif #ifdef STEP getch(); #endif edge_rec.dir = '+'; prevnode = edge_rec.start; if (edge_rec.start != edge_rec.end) { if ( (edge_rec.right == face_id) && (edge_rec.left == face_id) ) { /* Dangle */ if (prevnode == edge_rec.start) { edge_rec.dir = '+'; next = edge_rec.rightfwd; prevnode = edge_rec.end; } else if (prevnode == edge_rec.end) { edge_rec.dir = '-'; next = edge_rec.leftfwd; prevnode = edge_rec.start; } else next = -1; } else if (edge_rec.right == face_id) { next = edge_rec.rightfwd; edge_rec.dir = '+'; prevnode = edge_rec.end; } else if (edge_rec.left == face_id) { next = edge_rec.leftfwd; edge_rec.dir = '-'; prevnode = edge_rec.start; } else next = -1; } else { done = TRUE; } draw_polygon_edge( edge_rec ); if (edge_rec.coord) free(edge_rec.coord); while (!done) { if (next < 0) { #ifdef WATCH gotoxy(1,18); printf(" Aaargh(r)! Edge: %ld face: %ld left: %ld right: %ld", edge_rec.id,face_id,edge_rec.left,edge_rec.right); getch(); gotoxy(1,18); printf(" "); #endif done = TRUE; } if (next==0) { #ifdef WATCH gotoxy(1,19); printf("Next edge(%d) = 0 ",edge_rec.id); #endif done = TRUE; } if (next == start_edge) done = TRUE; if (!done) { edge_rec = read_edge( next, edgetable ); #ifdef WATCH gotoxy(1,17); printf("edge: %5ld left: %5ld edge:%5ld right: %5ld edge: %5ld", next,edge_rec.left,edge_rec.leftfwd,edge_rec.right, edge_rec.rightfwd); gotoxy(1,18); printf("node: %5ld start: %5ld end: %5ld", prevnode,edge_rec.start,edge_rec.end); #endif #ifdef STEP getch(); #endif if ( (edge_rec.right == face_id) && (edge_rec.left == face_id) ) { /* Dangle */ if (prevnode == edge_rec.start) { edge_rec.dir = '+'; next = edge_rec.rightfwd; prevnode = edge_rec.end; } else if (prevnode == edge_rec.end) { edge_rec.dir = '-'; next = edge_rec.leftfwd; prevnode = edge_rec.start; } else next = -1; } else if (edge_rec.right == face_id) { edge_rec.dir = '+'; next = edge_rec.rightfwd; prevnode = edge_rec.end; } else if (edge_rec.left == face_id) { edge_rec.dir = '-'; next = edge_rec.leftfwd; prevnode = edge_rec.start; } else next = -1; draw_polygon_edge( edge_rec ); if (edge_rec.coord) free(edge_rec.coord); } } } #endif #endif /************************************************************************* * *N next_polygon_edge * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines the next polygon edge id for a specified * face from the given edge record and face id. It follows the rules * of winged-edge topology. It does not follow the network through * dangles (see trace_polygon_loop above). It skips over them to * stay along the ring boundary. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * edge_rec ==(edge_rec_type *) VPF edge record. * prev_node ==(ossim_int32 *) the previous node visited. This * value is updated by this function. * face_id ==(ossim_int32) row id of the specified face. * next_polygon_edge ==(ossim_int32) the next edge id. A value of -1 * indicates a topology error. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ ossim_int32 next_polygon_edge( edge_rec_type *edge_rec, ossim_int32 *prevnode, ossim_int32 face_id ) { ossim_int32 next; if ( (edge_rec->right == face_id) && (edge_rec->left == face_id) ) { /* Dangle - go the opposite direction to continue along the boundary */ if (*prevnode == edge_rec->start) { edge_rec->dir = '-'; next = edge_rec->leftfwd; *prevnode = edge_rec->start; } else if (*prevnode == edge_rec->end) { edge_rec->dir = '+'; next = edge_rec->rightfwd; *prevnode = edge_rec->end; } else next = -1; } else if (edge_rec->right == face_id) { /* The face is on the right - take the right forward edge */ next = edge_rec->rightfwd; edge_rec->dir = '+'; *prevnode = edge_rec->end; } else if (edge_rec->left == face_id) { /* The face is on the left - take the left forward edge */ next = edge_rec->leftfwd; edge_rec->dir = '-'; *prevnode = edge_rec->start; } else next = -1; return next; } #ifdef __MSDOS__ /************************************************************************* * *N draw_polygon_loop * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws a loop (or ring) of a polygon by chaining * through the right and/or left edges of the edge table. Dangles * are skipped to stay along the outer boundary. * This is a good example of winged-edge topology. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * face_id ==(ossim_int32) row id of the specified face. * start_edge ==(ossim_int32) row id of the edge that starts the * loop. * edgetable ==(vpf_table_type) VPF edge primitive table. * poly ==(Shademap *) polygon shade structure. * wrap ==(int) wrap around if the polygon wraps * around the screen. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void draw_polygon_loop(ossim_int32 face_id, ossim_int32 start_edge, vpf_table_type edgetable, Shademap *poly, int wrap ) { edge_rec_type edge_rec; ossim_int32 next, prevnode; boolean done=FALSE; IPoint make_ipoint(); int xscr,yscr, color; coordinate_type coord; edge_rec = read_edge( start_edge, edgetable ); edge_rec.dir = '+'; prevnode = edge_rec.start; if (edge_rec.start != edge_rec.end) { next = next_polygon_edge( &edge_rec, &prevnode, face_id ); } else { done = TRUE; } gpgetlinecolor(&color); if (gpgetdevice()==SCREEN && color>=0) draw_polygon_edge( edge_rec ); if (edge_rec.dir == '-') coord = get_edge_coordinate(edge_rec.npts-1,&edge_rec); else coord = get_edge_coordinate(0,&edge_rec); screenxy(coord.x,coord.y,&xscr,&yscr); gpmoveto(xscr,yscr); gen_polygon_edge( edge_rec, poly, wrap ); if (edge_rec.coord) free(edge_rec.coord); while (!done) { if (next < 0) { gotoxy(1,18); printf(" VPF topology error! Edge: %ld face: %ld left: %ld right: %ld", edge_rec.id,face_id,edge_rec.left,edge_rec.right); getch(); gotoxy(1,18); printf(" "); done = TRUE; } if (next==0) { gotoxy(1,19); printf("Next edge(%d) = 0 ",edge_rec.id); done = TRUE; } if (next == start_edge) done = TRUE; if (!done) { edge_rec = read_edge( next, edgetable ); next = next_polygon_edge( &edge_rec, &prevnode, face_id ); if (gpgetdevice() == SCREEN && color>=0) draw_polygon_edge( edge_rec ); gen_polygon_edge( edge_rec, poly, wrap ); if (edge_rec.coord) free(edge_rec.coord); } } } /************************************************************************* * *N draw_polygon * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws a polygon for VPF face structure tables. * It is complicated by the fact that it checks to see whether * enough memory is available to draw the entire polygon in a * Shademap structure, or whether the face must be broken up into * smaller chunks so the bit arrays can fit into memory. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * mbrx1 == (int) mbr corner 1 x coordinate. * mbry1 == (int) mbr corner 1 y coordinate. * mbrx2 == (int) mbr corner 2 x coordinate. * mbry2 == (int) mbr corner 2 y coordinate. * face_rec == (face_rec_type) * ringtable == (vpf_table_type) VPF ring table. * edgetable == (vpf_table_type) VPF edge table. * outline == (color_type) polygon outline color. * pattern == (Pattern) polygon fill pattern. * wrap == (int) wrap around if the polygon wraps around * the screen. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void draw_polygon( int mbrx1, int mbry1, int mbrx2, int mbry2, face_rec_type face_rec, vpf_table_type ringtable, vpf_table_type edgetable, color_type outline, Pattern pattern, int wrap ) { int x1,y1,x2,y2, nchunks,chunk,delta, ok, k; Shademap *poly; IBox bounding,wdw,make_ibox(); ring_rec_type ring_rec; x1 = mbrx1-2; y1 = mbry1-2; x2 = mbrx2+2; y2 = mbry2+2; delta = x2-x1; nchunks=1; wdw = make_ibox(0,0,gpgetmaxx()+1,gpgetmaxy()); bounding = make_ibox(x1,y1,x2,y2); poly = OpenShade( bounding, wdw, outline, pattern); if (!poly) return; if (gpgetdevice() == SCREEN) { /* wdw = make_ibox(0,0,getmaxx()+1,getmaxy()); bounding = make_ibox(x1,y1,x2,y2); poly = OpenShade( bounding, wdw, outline, pattern); if (!poly) return; */ ok = TRUE; if (!poly->Bordermap.array || !poly->Maskmap.array) { /* Not enough memory - Split polygon up */ if (poly->Bordermap.array) FreeArrayOfBits(poly->Bordermap); if (poly->Maskmap.array) FreeArrayOfBits(poly->Maskmap); free(poly); poly = (Shademap *)NULL; k = 2; delta = gpgetmaxx()/k; nchunks = (mbrx2-mbrx1)/delta + 1; ok = FALSE; while (!ok) { ok = TRUE; bounding = make_ibox(0,y1,delta,y2); poly = OpenShade( bounding, wdw, outline, pattern); if (!poly) return; if (!poly->Bordermap.array || !poly->Maskmap.array) { ok = FALSE; if (poly->Bordermap.array) FreeArrayOfBits(poly->Bordermap); if (poly->Maskmap.array) FreeArrayOfBits(poly->Maskmap); free(poly); k++; delta = gpgetmaxx()/k; if (delta < 5) return; nchunks = (mbrx2-mbrx1)/delta + 1; } else { FreeArrayOfBits(poly->Bordermap); FreeArrayOfBits(poly->Maskmap); free(poly); poly = (Shademap *)NULL; } } x2 = x1 + delta; bounding = make_ibox(x1,y1,x2,y2); poly = OpenShade(bounding,wdw,outline,pattern); } } for (chunk=0;chunkBordermap); FreeArrayOfBits(poly->Maskmap); free(poly); } } } /************************************************************************* * *N draw_face_row * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws the specified face from the given row of * the given face table. * It is complicated by the fact that it checks to see whether a * face has wrapped around the screen due to projection effects. * If so, it first adjusts the coordinates off the right edge of the * screen to fill that portion of the face. Then, if the face * wraps around to the other edge of the screen, it adjusts the * coordinates to the left edge of the screen and refills to * display that portion of the face. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row ==(row_type) row of the specified face table. * facetable ==(vpf_table_type) VPF face primitive table. * ringtable ==(vpf_table_type) VPF ring primitive table. * edgetable ==(vpf_table_type) VPF edge primitive table. * fbr ==(vpf_table_type) VPF face bounding rectangle table. * outline ==(color_type) outline color. * c1 ==(color_type) 1st color in the fill pattern. * c2 ==(color_type) 2nd color in the fill pattern. * c3 ==(color_type) 3rd color in the fill pattern. * c4 ==(color_type) 4th color in the fill pattern. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void draw_face_row( row_type row, vpf_table_type facetable, vpf_table_type ringtable, vpf_table_type edgetable, vpf_table_type fbr, color_type outline, color_type c1, color_type c2, color_type c3, color_type c4 ) { ossim_int32 count; int spx1,spy1,spx2,spy2, rowid,ring; extent_type shade_box; Pattern pattern; face_rec_type face_rec; int wrap, mbrx2; row_type fbrrow; int XMIN_,YMIN_,XMAX_,YMAX_; rowid = table_pos( "ID", facetable ); ring = table_pos( "RING_PTR", facetable ); get_table_element( rowid, row, facetable, &(face_rec.id), &count ); get_table_element( ring, row, facetable, &(face_rec.ring), &count ); gpsetlinecolor(outline); gpsetlinestyle(SOLID_LINE); gpsetlinewidth(NORM_WIDTH); wrap = 0; if (gpgetdevice()==SCREEN) { pattern = MakePattern(c1,c2,c3,c4); /* Read bounding box */ fbrrow = read_row( face_rec.id, fbr ); XMIN_ = table_pos( "XMIN", fbr ); YMIN_ = table_pos( "YMIN", fbr ); XMAX_ = table_pos( "XMAX", fbr ); YMAX_ = table_pos( "YMAX", fbr ); get_table_element(XMIN_,fbrrow,fbr,&shade_box.x1,&count); get_table_element(YMIN_,fbrrow,fbr,&shade_box.y1,&count); get_table_element(XMAX_,fbrrow,fbr,&shade_box.x2,&count); get_table_element(YMAX_,fbrrow,fbr,&shade_box.y2,&count); free_row(fbrrow,fbr); screen_bounds(shade_box.x1,shade_box.y1, shade_box.x2,shade_box.y2, &spx1,&spy1,&spx2,&spy2); mbrx2 = spx2; if (spx2 0) { /* The polygon has wrapped around to the other side of the */ /* screen. Must redraw the part left off on the first pass. */ if (gpgetdevice()==SCREEN) { spx1 -= wrap; spx2 -= wrap; } else { gpstartpoly(); } wrap *= -1; draw_polygon( spx1,spy1,spx2,spy2, face_rec, ringtable, edgetable, outline, pattern, wrap ); } } /************************************************************************* * *N draw_face * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws the specified face from the given face table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row_num ==(ossim_int32) row id of the specified face. * facetable ==(vpf_table_type) VPF face primitive table. * ringtable ==(vpf_table_type) VPF ring primitive table. * edgetable ==(vpf_table_type) VPF edge primitive table. * fbr ==(vpf_table_type) VPF face bounding rectangle table. * outline ==(color_type) outline color. * c1 ==(color_type) 1st color in the fill pattern. * c2 ==(color_type) 2nd color in the fill pattern. * c3 ==(color_type) 3rd color in the fill pattern. * c4 ==(color_type) 4th color in the fill pattern. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void draw_face( ossim_int32 rownum, vpf_table_type facetable, vpf_table_type ringtable, vpf_table_type edgetable, vpf_table_type fbr, color_type outline, color_type c1, color_type c2, color_type c3, color_type c4 ) { row_type row; row = get_row( rownum, facetable ); draw_face_row(row,facetable, ringtable, edgetable, fbr, outline,c1,c2,c3,c4); free_row(row,facetable); } /************************************************************************* * *N outline_polygon_loop * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function outlines a loop (or ring) of a polygon by chaining * through the right forward and/or left forward edges of the edge * table. It does not fill a polygon. * *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * face_id ==(ossim_int32) row id of the specified face. * start_edge ==(ossim_int32) row id of the edge that starts the * loop. * edgetable ==(vpf_table_type) VPF edge primitive table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void outline_polygon_loop(ossim_int32 face_id, ossim_int32 start_edge, vpf_table_type edgetable) { edge_rec_type edge_rec; ossim_int32 next, prevnode; boolean done=FALSE; IPoint make_ipoint(); edge_rec = read_edge( start_edge, edgetable ); edge_rec.dir = '+'; prevnode = edge_rec.start; if (edge_rec.start != edge_rec.end) { next = next_polygon_edge( &edge_rec, &prevnode, face_id ); } else { done = TRUE; } draw_polygon_edge( edge_rec ); if (edge_rec.coord) free(edge_rec.coord); while (!done) { if (next < 0) { gotoxy(1,18); printf(" VPF topology error! Edge: %ld face: %ld left: %ld right: %ld", edge_rec.id,face_id,edge_rec.left,edge_rec.right); getch(); gotoxy(1,18); printf(" "); done = TRUE; } if (next==0) { gotoxy(1,19); printf("Next edge(%d) = 0 ",edge_rec.id); done = TRUE; } if (next == start_edge) done = TRUE; if (!done) { edge_rec = read_edge( next, edgetable ); next = next_polygon_edge( &edge_rec, &prevnode, face_id ); draw_polygon_edge( edge_rec ); if (edge_rec.coord) free(edge_rec.coord); } } } /************************************************************************* * *N outline_face * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function outlines (without filling) the specified face from * the given face table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * face_id ==(ossim_int32) row id of the specified face. * facetable ==(vpf_table_type) VPF facemitive table. * ringtable ==(vpf_table_type) VPF ringmitive table. * edgetable ==(vpf_table_type) VPF edge primitive table. * outline ==(color_type) outline color. * inner ==(int) if TRUE, draw inner rings; * if FALSE, only draw outer ring. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void outline_face( ossim_int32 face_id, vpf_table_type facetable, vpf_table_type ringtable, vpf_table_type edgetable, color_type outline, int inner ) { face_rec_type face_rec; ring_rec_type ring_rec; gpsetlinecolor(outline); gpsetlinestyle(SOLID_LINE); gpsetlinewidth(NORM_WIDTH); face_rec = read_face( face_id, facetable ); ring_rec = read_ring( face_rec.ring, ringtable ); outline_polygon_loop( face_id, ring_rec.edge, edgetable ); if (!inner) return; while (ring_rec.face == face_id ) { ring_rec = read_next_ring( ringtable ); if (feof(ringtable.fp)) { break; } if (ring_rec.face == face_id) { outline_polygon_loop( face_id, ring_rec.edge, edgetable ); } } } /************************************************************************* * *N outline_face_table * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function outlines the specified face from a previously unopened * face primitive table in the given color. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * face_id ==(ossim_int32) id of the face to be outlined. * fname ==(char *) file name of the face primitive table. * color ==(int) color to outline the face. * inner ==(int) if TRUE, draw inner rings; * if FALSE, only draw outer ring. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void outline_face_table( ossim_int32 face_id, char *fname, int color, int inner ) { vpf_table_type facetable, ringtable, edgetable; char *name; name = (char *)vpfmalloc( 255*sizeof(char) ); gpsetlinecolor( color ); facetable = vpf_open_table(fname,disk, "rb", (char *)NULL); strupr(fname); strcpy( name, facetable.path ); strcat( name, "RNG" ); ringtable = vpf_open_table( name, disk, "rb", (char *)NULL ); strcpy( name, facetable.path ); strcat( name, "EDG" ); edgetable = vpf_open_table( name, disk, "rb", (char *)NULL ); free( name ); hidemousecursor(); outline_face( face_id, facetable, ringtable, edgetable, color, inner ); showmousecursor(); vpf_close_table(&facetable); vpf_close_table(&ringtable); vpf_close_table(&edgetable); } #endif ossim-Miami-2.9.1/src/vpfutil/vpfmisc.c000066400000000000000000001352761352751253100200240ustar00rootroot00000000000000/************************************************************************* * *N Module VPFMISC * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains miscellaneous routines used (potentially) by * several other VPF modules. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ #ifdef __MSDOS__ # include # include #else # ifdef __APPLE__ # include # include # else #if !defined(__OpenBSD__) && !defined( __FreeBSD__) # include # include # endif # endif #endif #include /* For toupper function. */ #include #include #include #include #include #ifdef __MSDOS__ # include # include # include # include # include #else # include #endif #include #include #include #ifdef __MSDOS__ # include # include # include "gui.h" #endif #include #include #include #ifdef __MSDOS__ extern color_type menucolor, menubordercolor, menutextcolor; #endif #if !defined(__MSDOS__) && !defined(_MSC_VER) char* strrev(char* str) { register int i,len; char *copy; len = strlen(str); copy = (char *) malloc(sizeof(char)*(len+1)); (void) strcpy(copy,str); for(i=0;i == (unsigned long) number of bytes to allocate. * return == (void *) pointer to the allocated memory. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1990 Original Version DOS Turbo C * Ronald Rozensky Sept 1991 check for no memory, graphics mode *E *************************************************************************/ void *vpfmalloc( unsigned long size ) { void *p; #ifdef __MSDOS__ p = farmalloc( size ); if (!p) { printf("Out of memory %ld %ld\n",size,farcoreleft()); getch(); if (graphic_mode()) closegraph(); exit(1); } #else p = malloc(size); if (!p) { printf("Out of memory %ld\n", size); exit(1); } #endif return p; } #ifdef __MSDOS__ /************************************************************************* * *N get_display_position * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function finds a suitable position to display a new window on * the screen. If the window fits, its upper left hand corner will be * the current mouse position. If not, it will be adjusted so that it * will fit on the screen. Should be in graphics mode to call this * function. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * x == (int *) pointer to the x display position. * y == (int *) pointer to the y display position. * window == (window_type) window to be displayed. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1990 Original Version DOS Turbo C *E *************************************************************************/ void get_display_position( int *x, int *y, window_type window ) { int mbutton, delta; getmouseposition( x, y, &mbutton ); delta = window.x2 - window.x1; if ((*x) + delta > getmaxx()-2) (*x) = getmaxx()-delta-10; if ((*x) < 2) (*x) = 2; delta = window.y2 - window.y1; if ((*y) + delta > getmaxy()-2) (*y) = getmaxy()-delta-10; if ((*y) < 2) (*y) = 2; } /************************************************************************* * *N displayinfo * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function displays an array of text strings in a * popup text window. Must be in graphics mode to call this function. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * text[] == (char *) array of text strings to be displayed. * nlines == (int) number of text lines. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels June 1990 Original Version DOS Turbo C *E *************************************************************************/ void displayinfo( char *text[], int nlines ) { int i,maxw,height,x,y,pad; panel_type panel; arrow_cursor(); settextstyle( SMALL_FONT, HORIZ_DIR, 4 ); maxw = 0; height = 0; for (i=0;i maxw) maxw = textwidth(text[i]); height = height + textheight(text[i]) + 5; } if (maxw < (textwidth("Continue") + 10)) maxw = textwidth("Continue") + 10; pad = (maxw*10)/100; maxw = maxw + (2*pad); if (maxw > getmaxx()) maxw = getmaxx() - 8; height = height + 2*(textheight("Continue") + 10); create_panel( &panel, maxw, height, menucolor, menubordercolor ); x = pad; y = 0; for (i=0;i == (char *) first text string to be displayed. * ... == (char *) variable list of text strings to be displayed. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels August 1991 DOS Turbo C *E *************************************************************************/ void displaymessage( char *string, ... ) { int i,maxw,height,x,y,pad, nlines; panel_type panel; char **text; va_list arglist; va_start(arglist,string); nlines = 1; while (va_arg(arglist,char *)) nlines++; va_end(arglist); text = (char **)vpfmalloc((nlines+1)*sizeof(char *)); text[0] = string; va_start(arglist,string); for (i=1;i maxw) maxw = textwidth(text[i]); height = height + textheight(text[i]) + 5; } if (maxw < (textwidth("Continue") + 10)) maxw = textwidth("Continue") + 10; pad = (maxw*10)/100; maxw = maxw + (2*pad); if (maxw > getmaxx()) maxw = getmaxx() - 8; height = height + 2*(textheight("Continue") + 5) + 5; create_panel( &panel, maxw, height, menucolor, menubordercolor ); x = pad; y = 0; for (i=0;i == (char *) message to be displayed. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 Original Version DOS Turbo C *E *************************************************************************/ void display_message(char *str) { char **txt; txt = (char **)vpfmalloc( (unsigned long)(1*sizeof(char **)) ); txt[0] = strdup(str); displayinfo( txt, 1 ); free(txt[0]); free(txt); } #else void displaymessage( char *s, ... ) { int i, nlines; char **text; va_list arglist; va_start(arglist,s); nlines = 1; while (va_arg(arglist,char *)) nlines++; va_end(arglist); text = (char **)vpfmalloc((nlines+1)*sizeof(char *)); text[0] = s; va_start(arglist,s); for (i=1;i == (double) floating point lat lon coordinate. * return == (dms_type) degrees-minutes-seconds coordinate. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1990 Original Version DOS Turbo C *E *************************************************************************/ dms_type float_to_dms( double coord ) { dms_type dms_coord; dms_coord.degrees = (int)coord; dms_coord.minutes = (int)((double)(coord-(int)coord)*60.0); dms_coord.seconds = (float)((((double)(coord-(int)coord)* 60.0) - (double)dms_coord.minutes) * 60.0); dms_coord.minutes = abs(dms_coord.minutes); dms_coord.seconds = (float)(fabs(dms_coord.seconds)); if (dms_coord.minutes == 60) { if (dms_coord.degrees > 0) dms_coord.degrees++; else dms_coord.degrees--; dms_coord.minutes = 0; } if ((dms_coord.degrees == 0)&&(coord < 0.0)) dms_coord.minutes *= -1; return dms_coord; } /************************************************************************* * *N dms_to_float * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function converts a coordinate in degrees-minutes-seconds format * to a floating point coordinate. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * coord == (dms_type) degrees-minutes-seconds coordinate. * return == (double) floating point lat lon coordinate. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1990 Original Version DOS Turbo C *E *************************************************************************/ double dms_to_float( dms_type coord ) { return ( (double)coord.degrees + ((double)coord.minutes / 60.0) + (coord.seconds/3600.0) ); } /************************************************************************* * *N dms_string * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function converts a coordinate in degrees-minutes-seconds format * to a character string. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * coord == (dms_type) degrees-minutes-seconds coordinate. * seconds == (int) flag to indicate if seconds are to be * displayed. * return == (char *) character string. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1990 Original Version DOS Turbo C *E *************************************************************************/ char *dms_string( dms_type coord, int seconds ) { char *str,deg[5],min[3],sec[3]; str = (char *)vpfmalloc( (20*sizeof(char))+ sizeof(deg)+sizeof(min)+sizeof(sec) ); itoa( coord.degrees, deg, 10 ); itoa( abs(coord.minutes), min, 10 ); if (seconds) itoa( ((int)floor(coord.seconds)), sec, 10 ); if ((coord.degrees==0)&&(coord.minutes < 0)) { strcpy(str,"-0"); coord.minutes *= -1; } else { strcpy(str,deg); } strcat(str," deg "); strcat(str,min); strcat(str," min "); if (seconds) { strcat(str,sec); strcat(str," sec"); } return(str); } #ifdef __MSDOS__ /************************************************************************* * *N out_dms * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function displays the given degree-minutes-seconds coordinate * at the specified location on the screen. The direction is given * for placement along the edges of the screen. Must be in graphics * mode to call this function. User must make sure that all text will * fit on the screen; this program will not adjust size, but will adjust * location to make sure that all text that CAN fit on the screen WILL * fit on the screen. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * coord == (dms_type) degrees-minutes-seconds coordinate. * x == (int) x location. * y == (int) y location. * dir == (int) dir. HORIZ_DIR=0, VERT_DIR=1 * seconds == (int) flag indicating whether to display seconds. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels October 1990 Original Version DOS Turbo C * Ronald Rozensky Sept 1991 x,y adjustments to make text fit on screen *E *************************************************************************/ void out_dms( dms_type coord, int x, int y, int dir, int seconds ) { char deg[8],min[8],sec[8]; int x1,x2,y1,y2, width, adjust, minutes; settextjustify(LEFT_TEXT,BOTTOM_TEXT); itoa( coord.degrees, deg, 10 ); if ((coord.seconds >= 30.0)&&(!seconds)) { /* Round up */ minutes = abs(coord.minutes)+1; if (minutes == 60) { /* Rounded up to next degree */ strcpy(min,"0"); if (coord.degrees > 0) coord.degrees++; else if (coord.degrees < 0) coord.degrees--; else { if (coord.minutes < 0 || coord.seconds < 0.0) coord.degrees++; else coord.degrees--; } } else { itoa( minutes, min, 10 ); } itoa( coord.degrees, deg, 10 ); } else { itoa( abs(coord.minutes), min, 10 ); } if (seconds) itoa( floor(abs(coord.seconds+0.5)), sec, 10 ); if ((coord.degrees==0)&&(coord.minutes < 0)) { strcpy(deg,"-0"); } if ((coord.degrees==0)&&(coord.minutes==0)&&(coord.seconds<0)) { strcpy(deg,"-0"); } strcat(min,"'"); if (seconds) strcat(sec,"''"); if (dir==HORIZ_DIR) { width = textwidth(deg)+3; if ((coord.minutes > 0)||(seconds)) { width += textwidth(min)+3; } if (seconds) { width += textwidth(sec)+3; } x1 = x - width/2; x2 = x1 + width; y1 = y-textheight(deg)-1; y2 = y+1; } else { width = textwidth(deg)+3; if ((coord.minutes > 0)||(seconds)) { width += textwidth(min)+3; } if (seconds) { width += textwidth(sec)+3; } x1 = x; x2 = x1 + width; y1 = y - (textheight(deg)+4)/2; y2 = y + (textheight(deg)+4)/2; } setfillstyle(SOLID_FILL,DARKGRAY); if (x1 <0) { adjust = 0-x1; x1 = 0; x2 = x2 += adjust; } if (y1 <0) { adjust = 0-y1; y1 = 0; y2 = y2 += adjust; } if ((y1-y2 < getmaxy()) && (y2 > getmaxy())) { adjust = y2-getmaxy(); y2 = getmaxy(); y1 -= adjust; } if ((x1-x2 < getmaxx()) && (x2 > getmaxx())) { adjust = x2-getmaxx(); x2 = getmaxx(); x1 -= adjust; } bar(x1,y1,x2,y2); outtextxy(x1,y2,deg); circle(x1+textwidth(deg)+1, y2-textheight(deg), 2); if ((coord.minutes > 0)||(seconds)) outtextxy(x1+textwidth(deg)+5,y2-1,min); if (seconds) outtextxy(x1+textwidth(deg)+3+textwidth(min)+3,y2-1,sec); } #endif /************************************************************************* * *N strpos * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the character array position of the first * occurrence of the given character. (-1 if not present) *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * str == (char *) character string to be searched. * ch == (char) character to search for. * return == (int) position of character (-1 if not present). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1990 Original Version DOS Turbo C *E *************************************************************************/ int strpos( char *str, char ch ) { register int i; for (i=0;(unsigned int)i == (float) x coordinate of the test point. * y == (float) y coordinate of the test point. * extent == (extent_type) rectangular area to be tested. * fwithin == (VPF_BOOLEAN) VPF_BOOLEAN: * TRUE if (x,y) lies within area * FALSE if (x,y) lies outside of area *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1990 Original Version DOS Turbo C *E *************************************************************************/ VPF_BOOLEAN fwithin( float x, float y, extent_type extent ) { if ((x >= extent.x1) && (x <= extent.x2) && (y >= extent.y1) && (y <= extent.y2)) return TRUE; else return FALSE; } /************************************************************************* * *N contained * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether an input rectangular 'extent1' is * contained within another rectangular 'extent2'. It returns either * TRUE or FALSE. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * extent1 == (extent_type) rectangular area to be tested within. * extent2 == (extent_type) rectangular area to be tested against. * contained == (VPF_BOOLEAN) VPF_BOOLEAN: * TRUE if extent2 contains extent1 * FALSE if extent2 does not contain extent1 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1990 Original Version DOS Turbo C *E *************************************************************************/ VPF_BOOLEAN contained( extent_type extent1, extent_type extent2 ) { /* Test each of the four corners of extent1 */ /* ____________ | | | 2 | | ______+___ | | | | | | | | 1 | | | | ------------ | | */ if ((extent1.x1 >= extent2.x1) && (extent1.x1 <= extent2.x2) && (extent1.y1 >= extent2.y1) && (extent1.y1 <= extent2.y2)) return TRUE; /* ____________ | | | 2 | | | ---+------ | | | | | 1 | | | | | ------------ | | */ if ((extent1.x2 >= extent2.x1) && (extent1.x2 <= extent2.x2) && (extent1.y1 >= extent2.y1) && (extent1.y1 <= extent2.y2)) return TRUE; /* | _____|______ | | | | 1 | | | | | --+----- | | | | 2 | |__________| */ if ((extent1.x2 >= extent2.x1) && (extent1.x2 <= extent2.x2) && (extent1.y2 >= extent2.y1) && (extent1.y2 <= extent2.y2)) return TRUE; /* | | ______|_____ | | | | | 1 | | | | | 2 -----+-- | | | | ------------ */ if ((extent1.x1 >= extent2.x1) && (extent1.x1 <= extent2.x2) && (extent1.y2 >= extent2.y1) && (extent1.y2 <= extent2.y2)) return TRUE; /* Test for overlaps */ /* ________ -------------- | | | 2 | | 1 | | ---------- | ----+------+---- | | | | | 2 | | | | | | | | | | | | | 1 | | ----+------+---- | | | | | | | | | | | | | ---------- | -------- | | -------------- */ if ((extent1.y1 >= extent2.y1) && (extent1.y2 <= extent2.y2) && (extent1.x1 <= extent2.x2) && (extent1.x2 >= extent2.x1)) return TRUE; /* ________ -------------- | | | 1 | | 2 | | ---------- | ----+------+---- | | | | | 1 | | | | | | | | | | | | | 2 | | ----+------+---- | | | | | | | | | | | | | ---------- | -------- | | -------------- */ if ((extent1.x1 >= extent2.x1) && (extent1.x2 <= extent2.x2) && (extent1.y1 <= extent2.y2) && (extent1.y2 >= extent2.y1)) return TRUE; return FALSE; } #ifdef __MSDOS__ /************************************************************************* * *N info_window * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function displays a temporary window to the screen with a * single string of text. Must be in graphics mode to call this * function. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * text == (char *)message to display. * return == (window_type) window created and displayed. * [Will need to be deleted] *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 Original Version DOS Turbo C *E *************************************************************************/ window_type info_window( char *text ) { window_type w; int x,y; settextstyle(SMALL_FONT,HORIZ_DIR,4); settextjustify(LEFT_TEXT,BOTTOM_TEXT); if (textwidth(text) > getmaxx()) x = getmaxx()-20; else x = textwidth(text) + 20; create_window( &w, x, textheight(text)+10, menucolor,menubordercolor ); get_display_position( &x, &y, w ); open_window( &w, x,y ); setcolor(menutextcolor); hidemousecursor(); outtextxy( 10,textheight(text)+5,text ); showmousecursor(); return w; } #endif /************************************************************************* * *N rightjust * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function right justifies the given string and removes the * trailing newline character (if one exists). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * str == (char *) string to be justified. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels November 1990 Original Version DOS Turbo C *E *************************************************************************/ char *rightjust( char *str ) { return strrev(leftjust(strrev(str))); } /************************************************************************* * *N leftjust * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function left justifies the given string and removes the * trailing newline character (if one exists) *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * str == (char *) string to be justified. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels November 1990 Original Version DOS Turbo C *E *************************************************************************/ char *leftjust(char * str) { register char * eol; strcpy(str, str + strspn(str, " \t\n\b")); if ((eol = strchr(str, '\n')) != NULL) *eol = 0; return str; } #ifdef __MSDOS__ /************************************************************************* * *N displayerror * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function displays an error message when a disk error is detected. * It displays the given lines of text in a popup panel and waits for * the user to click on either retry or cancel. It returns 1 for retry * and 0 for cancel. Must be in graphics mode to call this function. * * text strings may contain embedded newlines, in which case text to the * right of the newline will be displayed on (what else?) a new line. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * text[] == (char *) array of text strings to be displayed. * nlines == (int) number of lines of text (this count ignores * newline characters embedded in the text * strings * return == (VPF_BOOLEAN) 1 => retry, * 0 => cancel. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1990 Prototype 3 DOS Turbo C *E *************************************************************************/ VPF_BOOLEAN displayerror( char *text[], int nlines ) { register int i; int maxw, height, x, y, pad, choice, n_real_lines; panel_type panel; int retry_button = 'r', cancel_button = 'c', msg_ar_sz = 10; char * walker, ** msgs; struct viewporttype view; getviewsettings( &view ); setviewport(0,0,getmaxx(),getmaxy(),1); settextstyle( SMALL_FONT, HORIZ_DIR, 4 ); msgs = (char **) vpfmalloc(msg_ar_sz * sizeof(char *)); maxw = height = 0; for (n_real_lines = i = 0; i < nlines; i++) { walker = text[i]; while (1) { size_t substr_len = strcspn(walker, "\n"); char plug; maxw = max(maxw, textwidth(walker)); height = height + textheight(walker) + 5; plug = walker[substr_len]; walker[substr_len] = '\0'; msgs[n_real_lines++] = strdup(walker); if (n_real_lines == msg_ar_sz) msgs = (char **) realloc(msgs, (msg_ar_sz += 5) * sizeof(char *)); if (plug == 0) break; walker[substr_len] = plug; walker += substr_len + 1; } } if (maxw < (textwidth("Retry") + textwidth("Cancel") + 20)) maxw = textwidth("Retry") + textwidth("Cancel") + 20; pad = (maxw*10)/100; maxw = maxw + (2*pad); height = height + 2*(textheight("Retry") + 5) + 1; maxw = min(getmaxx(), maxw); height = min(getmaxy()-10, height); create_panel( &panel, maxw, height, menucolor, menubordercolor ); for (y = i = 0; i < n_real_lines; i++) { create_label(msgs[i], pad, y, SMALL_FONT, 4, menutextcolor, &panel ); y += textheight(msgs[i]) + 3; } y = height-15; create_button( retry_button, "Retry", 3, y, SMALL_FONT, 4, menutextcolor, menucolor, menubordercolor, RELIEVED, &panel ); create_button( cancel_button, "Cancel", maxw - (textwidth("Cancel") + 13), y, SMALL_FONT, 4, menutextcolor, menucolor, menubordercolor, RELIEVED, &panel ); get_display_position( &x, &y, panel.window ); display_panel( &panel, x,y ); showmousecursor(); arrow_cursor(); choice = process_panel( &panel, 0 ); hidemousecursor(); destroy_panel( &panel ); close_panel( &panel ); setviewport(view.left,view.top,view.right,view.bottom,view.clip); for (i = 0; i < n_real_lines; i++) free(msgs[i]); free(msgs); return (choice == retry_button) ? 1 : 0; } /************************************************************************* * *N getcursorposition * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the cursor position when either the mouse * has been moved or an arrow key has been pressed. Must have called * showmousecursor() before calling this routine. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * x == (int *) x position of the cursor. * y == (int *) y position of the cursor. * button == (int *) mouse button pressed (or simulated with * the keyboard). * return == (int) escape status: * FALSE -> escape pressed * TRUE -> escape not pressed *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels November 1990 Original Version DOS Turbo C *E *************************************************************************/ int getcursorposition( int *x, int *y, int *button ) { char ch,ch2; int xpos,ypos, ok = TRUE; if (kbhit()) { xpos = *x; ypos = *y; ch = getch(); switch (ch) { case 13: /* Enter key */ *button = LEFT_BUTTON_DOWN; break; case '8': ypos -= 10; break; case '2': ypos += 10; break; case '4': xpos -= 10; break; case '6': xpos += 10; break; case 27: ok = FALSE; break; } if (ch==0) { ch2 = getch(); switch (ch2) { case 72: ypos--; break; case 80: ypos++; break; case 75: xpos--; break; case 77: xpos++; break; case 59: /* F1 key */ *button = RIGHT_BUTTON_DOWN; break; } } setmouseposition(xpos,ypos); *x = xpos; *y = ypos; } else getmouseposition(x,y,button); return ok; } /************************************************************************* * *N yes_no * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function displays a panel asking the user a yes or no * question and returns the response. Must be in graphics mode to call * this function. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * text ==(char *) question string. * return ==(int) yes (TRUE) or no (FALSE). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ int yes_no( char *text ) { panel_type panel; int no_id = 27; int yes_id = 13; int x,y,width,height,maxheight,id=0; settextstyle( SMALL_FONT, HORIZ_DIR, 4 ); width = 0; maxheight = 0; width = textwidth(text); maxheight = textheight(text); width = width + 50; if (width > getmaxx()) width = getmaxx()-10; height = maxheight * 5; create_panel( &panel,width,height,menucolor,menubordercolor ); y = maxheight; create_label( text,CENTER,y,SMALL_FONT,4,menutextcolor,&panel ); y += maxheight; create_button( yes_id, "Yes", 3, height-textheight("Y")-6, SMALL_FONT, 4, menutextcolor, menucolor, menubordercolor, RELIEVED, &panel ); create_button( no_id, "No", width-textwidth("No")-13, height-textheight("No")-6, SMALL_FONT, 4, menutextcolor, menucolor, menubordercolor, RELIEVED, &panel ); get_display_position( &x, &y, panel.window ); display_panel( &panel, x,y ); id = process_panel(&panel, id); destroy_panel( &panel ); close_panel( &panel ); if (id == yes_id) return TRUE; else return FALSE; } /************************************************************************* * *N printer_ready * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether or not the attached * printer is ready. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * return == (int) TRUE if ready, FALSE if not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels November 1990 Original Version DOS Turbo C *E *************************************************************************/ int printer_ready( void ) { union REGS reg; reg.h.ah = 2; reg.x.dx = 0; int86(0x17, ®, ®); /* this is not busy not an io error not out of paper */ return (reg.h.ah & 0x80) && (!(reg.h.ah & 8)) && (!(reg.h.ah & 32)); } /************************************************************************* * *N printer_ok * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether the printer is ready and allows * the user to keep retrying or cancel. Must be in graphics mode to call * this function. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * return == (int) TRUE if ready, FALSE if cancel. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels November 1990 Original Version DOS Turbo C *E *************************************************************************/ int printer_ok( void ) { int retry; char *msg[] = {"Printer not ready"}; while (!printer_ready()) { hidemousecursor(); retry = displayerror(msg,1); showmousecursor(); if (!retry) return FALSE; } return TRUE; } /************************************************************************* * *N coprocessor_present * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether a math coprocessor chip is present * on the current computer configuration. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * return == (int) TRUE if present, FALSE if not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels July 1991 DOS Turbo C *E *************************************************************************/ int coprocessor_present( void ) { int stat; stat = biosequip(); /* If bit 1 of stat is on, a coprocessor is present */ if (stat & 2) return TRUE; else return FALSE; } #endif /************************************************************************* * *N is_primitive * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether the given file name specifies a * VPF primitive table (Edge, Face, Entity Node, or Text). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * name == (char *) file name to be tested. * return == (int) TRUE if primitive, FALSE if not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ int is_primitive( char *name ) { strupr(name); if (strstr(name,"END")) return TRUE; if (strstr(name,"CND")) return TRUE; if (strstr(name,"EDG")) return TRUE; if (strstr(name,"FAC")) return TRUE; if (strstr(name,"TXT")) return TRUE; return FALSE; } /************************************************************************* * *N is_simple_feature * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether the given file name specifies a * VPF simple feature table (Point, Line, or Area feature table). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * name == (char *) file name to be tested. * return == (int) TRUE if simple feature, FALSE if not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ int is_simple_feature( char *name ) { strupr(name); if (strstr(name,"PFT")) return TRUE; if (strstr(name,"LFT")) return TRUE; if (strstr(name,"AFT")) return TRUE; return FALSE; } /************************************************************************* * *N is_complex_feature * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether the given file name specifies a * VPF complex feature table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * name == (char *) file name to be tested. * return == (int) TRUE if complex feature, FALSE if not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ int is_complex_feature( char *name ) { strupr(name); if (strstr(name,"CFT")) return TRUE; return FALSE; } /************************************************************************* * *N is_feature * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether the given file name specifies a * VPF feature table (Point, Line, Area, or Complex feature table). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * name == (char *) file name to be tested. * return == (int) TRUE if feature, FALSE if not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ int is_feature( char *name ) { strupr(name); if (strstr(name,"PFT")) return TRUE; if (strstr(name,"LFT")) return TRUE; if (strstr(name,"AFT")) return TRUE; if (strstr(name,"TFT")) return TRUE; if (strstr(name,"CFT")) return TRUE; return FALSE; } /************************************************************************* * *N feature_type * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the type of feature the given table name * refers to (POINT, LINE, AREA, ANNO, or COMPLEX_FEATURE). If the table * name does not specify a feature type, the function returns FALSE. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * name == (char *) file name to be tested. * return == (int) feature type (FALSE if invalid name). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ int feature_type( char *name ) { strupr(name); if (strstr(name,"PFT")) return VPF_POINT; if (strstr(name,"LFT")) return VPF_LINE; if (strstr(name,"AFT")) return VPF_AREA; if (strstr(name,"TXT")) return VPF_ANNO; if (strstr(name,"TFT")) return VPF_ANNO; if (strstr(name,"CFT")) return VPF_COMPLEX_FEATURE; return FALSE; } /************************************************************************* * *N is_join * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether the given file name specifies a * VPF join table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * name == (char *) file name to be tested. * return == (int) TRUE if join, FALSE if not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ int is_join( char *name ) { char *ptr; strupr(name); ptr = strstr(name,"."); if (strstr(ptr,"JT")) return TRUE; return FALSE; } /************************************************************************* * *N primitive_class * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the feature type the given primitive table * name refers to (POINT, LINE, AREA, or ANNO). If the table * name is not a valid primitive table name, the function returns NULL. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * name == (char *) file name to be tested. * return == (int) feature type (NULL if invalid primitive * name). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ int primitive_class( char *name ) { strupr(name); if (strstr(name,"END")) return VPF_ENTITY_NODE; if (strstr(name,"CND")) return VPF_CONNECTED_NODE; if (strstr(name,"EDG")) return VPF_EDGE; if (strstr(name,"FAC")) return VPF_FACE; if (strstr(name,"TXT")) return VPF_TEXT; #ifdef __MSDOS__ return NULL; #else return 0; #endif } int ossim_strcasecmp(const char *s1, const char *s2) { size_t s1_size; size_t s2_size; unsigned int i; /* Check for one string being null, one not. */ if (!s1 && s2) { return -1; } else if (s1 && !s2) { return 1; } /* Check for both strings being null. Consider this equal? */ if (!s1 && !s2) { return 0; } /* Check for size differences. */ s1_size = strlen(s1); s2_size = strlen(s2); if (s1_size < s2_size) { return -1; } else if (s1_size > s2_size) { return 1; } /* Check the strings. */ for (i=0; i s1_size) { return -1; } else if (n > s2_size ) { return 1; } /* Check the strings. */ for (i=0; i #include #ifdef __MSDOS__ #include #endif #include #if defined(__CYGWIN__) || defined(__APPLE__)|| defined(_WIN32) #include #else #include #endif #ifdef __MSDOS__ #include #endif #include #include #include #include #include # ifndef min # define min(a,b) ((a) <= (b) ? (a) : (b)) # endif # ifndef max # define max(a,b) ((a) <= (b) ? (b) : (a)) # endif typedef struct { float x1; float y1; float x2; float y2; } line_segment_type; /************************************************************************** * *N perpendicular_intersection * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Test whether a perpendicular to a line segment intersects a search * point. lseg must be of a type similar to line_segment_type. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * lseg == (line_segment_type) line segment. * xsearch == (float) search point x coordinate. * ysearch == (float) search point y coordinate. * xint == (float *) intersection point x coordinate. * yint == (float *) intersection point y coordinate. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels, DOS Turbo C 1991 * Ronald Rozensky, vertical and horizontal line handlers. *E *************************************************************************/ int perpendicular_intersection( line_segment_type lseg, float xsearch, float ysearch, float *xint, float *yint ) { float m1=0,mp=0,b1=0,bp=0; /* m's are for slopes, b's are for y intersections */ /* for the old y=mx+b point slope formula. */ if (lseg.y1 == lseg.y2) if (((lseg.x1 <= xsearch) && (xsearch <= lseg.x2)) || ((lseg.x2 <= xsearch) && (xsearch <= lseg.x1))) { *xint = xsearch; *yint = lseg.y1; return 1; } if (lseg.x1 == lseg.x2) if (((lseg.y1 <= ysearch) && (ysearch <= lseg.y2)) || ((lseg.y2 <= ysearch) && (ysearch <= lseg.y1))) { *xint = lseg.x1; *yint = ysearch; return 1; } if ( (lseg.x1==xsearch) && (lseg.y1==ysearch) ) { *xint = xsearch; *yint = ysearch; return 1; } if ( (lseg.x2==xsearch) && (lseg.y2==ysearch) ) { *xint = xsearch; *yint = ysearch; return 1; } if (lseg.x1 != lseg.x2) { m1 = (lseg.y2-lseg.y1)/(lseg.x2-lseg.x1); b1 = -1*m1*lseg.x1 + lseg.y1; if (m1 != 0.0) { mp = (float)(-1.0/m1); /* perpendicular */ } else { mp = MAXFLOAT; } } else { m1 = MAXFLOAT; mp = 0.0; } if (fabs(mp) < 1000000.0) { bp = ysearch - mp*xsearch; } else { bp = MAXFLOAT; } /* Find intersection point of lseg and its perpendicular */ if ( (m1 != MAXFLOAT) && (mp != MAXFLOAT) ) { *xint = (bp-b1)/(m1-mp); *yint = m1*(*xint)+b1; } else { /* At least one vertical line */ if (m1==MAXFLOAT) { /* lseg is vertical */ *yint = ysearch; *xint = lseg.x1; } else { /* perp is vertical */ *yint = lseg.y1; *xint = xsearch; } } /* See if intersection point lies on both line segments */ return ( (*xint >= (float)min(lseg.x1,lseg.x2)) && (*xint <= (float)max(lseg.x1,lseg.x2)) && (*yint >= (float)min(lseg.y1,lseg.y2)) && (*yint <= (float)max(lseg.y1,lseg.y2)) ); } /* In VPFMISC.C for the VPFVIEW application */ float distance( double lat1, double lon1, double lat2, double lon2, int units ); /************************************************************************** * *N distance_to_edge_rec * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function computes the minimum distance from the given point * to the given edge record by looking at each segment in the line. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * x == (float) given point x coordinate. * y == (float) given point y coordinate * edge_rec == (edge_rec_type) given edge record. * dec_degrees == (int) flag to indicate if coordinates are * in decimal degrees. * distance_to_edge_rec == (float) minimum distance to the * edge record. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels, DOS Turbo C 1991 *E *************************************************************************/ float distance_to_edge_rec( float x, float y, edge_rec_type edge_rec, int dec_degrees ) { register ossim_int32 i; line_segment_type lseg; float xint,yint, d, dseg, d1, d2; coordinate_type coord1, coord2; d = MAXFLOAT; coord1 = first_edge_coordinate(&edge_rec); for (i=1;i == (float) given point x coordinate. * y == (float) given point y coordinate * edge_id == (ossim_int32) specified edge. * edgetable == (vpf_table_type) given edge table. * dec_degrees == (float) flag to indicate if coordinates are * in decimal degrees. * distance_to_edge == (float) minimum distance to the given * edge from the given point. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels, DOS Turbo C 1991 *E *************************************************************************/ float distance_to_edge( float x, float y, ossim_int32 edge_id, vpf_table_type edgetable, int dec_degrees ) { edge_rec_type edge_rec; float result; edge_rec = read_edge( edge_id, edgetable ); result = distance_to_edge_rec( x, y, edge_rec, dec_degrees ); if (edge_rec.coord) free( edge_rec.coord ); return result; } /************************************************************************** * *N distance_to_edge_table * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads the specified edge from the named edge table * and computes the minimum distance from the given point to the * specified edge. 'edge_id' must be contained in the edge table. * 'fname' must be a valid path to a VPF edge table. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * x == (float) given point x coordinate. * y == (float) given point y coordinate * edge_id == (ossim_int32) specified edge id. * fname == (char *) path to valid VPF edge table. * dec_degrees == (int) flag to indicate if coordinates are * in decimal degrees. * distance_to_edge_table == (float) distance from the given * point to the specified edge. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels, DOS Turbo C 1991 *E *************************************************************************/ float distance_to_edge_table( float x, float y, ossim_int32 edge_id, char *fname, int dec_degrees ) { vpf_table_type edgetable; float result; char *defstr=" "; edgetable = vpf_open_table(fname,disk, "rb", defstr); result = distance_to_edge( x, y, edge_id, edgetable, dec_degrees ); vpf_close_table(&edgetable); return result; } ossim-Miami-2.9.1/src/vpfutil/vpfprim.c000066400000000000000000000733231352751253100200320ustar00rootroot00000000000000/************************************************************************* * *N Module VPFPRIM - VPF Primitives * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions for handling VPF primitives *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ #include #ifdef __MSDOS__ #include #include #include #else #ifndef _WIN32 #include #endif #endif #include #include #if defined(__CYGWIN__) || defined(__APPLE__)|| defined(_WIN32) #include #else #include #endif #ifdef __MSDOS__ #include #else #ifdef __APPLE__ #include #include #else #if !defined(__OpenBSD__) && !defined( __FreeBSD__) #include #include #endif #endif #endif #include #include #include /* Compute the offset from the start of the row to the given field */ static ossim_int32 row_offset( int field, row_type row, vpf_table_type table) { ossim_int32 offset,n,size; int i; id_triplet_type key; int keysize[] = {0,sizeof(char),sizeof(short int),sizeof(ossim_int32)}; if (field < 0 || field >= table.nfields) return -1; offset = 0L; for (i=0;i == (row_type) VPF table row. * edge_table == (vpf_table_type) opened VPF table to read. * return == (edge_rec_type) returned edge record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ edge_rec_type create_edge_rec( row_type row, vpf_table_type edge_table ) { edge_rec_type edge; ossim_int32 count,i; int rowid,start,end,right,left,rightfwd,leftfwd,coord; id_triplet_type key; tri_coordinate_type *Zcoord; double_coordinate_type *Bcoord; double_tri_coordinate_type *Ycoord; rowid = table_pos( "ID", edge_table ); start = table_pos( "START_NODE", edge_table ); end = table_pos( "END_NODE", edge_table ); right = table_pos( "RIGHT_FACE", edge_table ); left = table_pos( "LEFT_FACE", edge_table ); rightfwd = table_pos( "RIGHT_EDGE", edge_table ); leftfwd = table_pos( "LEFT_EDGE", edge_table ); coord = table_pos( "COORDINATES", edge_table ); get_table_element( rowid, row, edge_table, &(edge.id), &count ); if (start >= 0) get_table_element( start, row, edge_table, &(edge.start), &count ); else edge.start = 0; if (end >= 0) get_table_element( end, row, edge_table, &(edge.end), &count ); else edge.end = 0; if (right >= 0) { if (edge_table.header[right].type=='K') { get_table_element( right, row, edge_table, &key, &count ); edge.right = key.id; } else if (edge_table.header[right].type=='I') { get_table_element( right, row, edge_table, &(edge.right), &count ); } else { edge.right=1; } } else { edge.right = 1; } if (left >= 0) { if (edge_table.header[right].type=='K') { get_table_element( left, row, edge_table, &key, &count ); edge.left = key.id; } else if (edge_table.header[left].type=='I') { get_table_element( right, row, edge_table, &(edge.left), &count ); } else { edge.left=1; } } else { edge.left = 1; } if (edge_table.header[rightfwd].type=='K') { get_table_element( rightfwd, row, edge_table, &key, &count ); edge.rightfwd = key.id; } else if (edge_table.header[rightfwd].type=='I') { get_table_element( rightfwd, row, edge_table, &(edge.rightfwd), &count ); } else { edge.rightfwd=0; } if (edge_table.header[leftfwd].type=='K') { get_table_element( leftfwd, row, edge_table, &key, &count ); edge.leftfwd = key.id; } else if (edge_table.header[leftfwd].type=='I') { get_table_element( leftfwd, row, edge_table, &(edge.leftfwd), &count ); } else { edge.leftfwd=0; } switch (edge_table.header[coord].type) { case 'C': edge.coord = (coordinate_type *)get_table_element( coord, row, edge_table, NULL, &count ); break; case 'Z': Zcoord = (tri_coordinate_type *)get_table_element( coord, row, edge_table, NULL, &count ); edge.coord = (coordinate_type *)malloc(count* sizeof(coordinate_type)); if (edge.coord) { for (i=0;i == (ossim_int32) edge id number. * edge_table == (vpf_table_type) opened VPF table to read. * return == (edge_rec_type) returned edge record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ edge_rec_type read_edge( ossim_int32 id, vpf_table_type edge_table ) { edge_rec_type edge; row_type row; row = get_row( id, edge_table ); edge = create_edge_rec( row, edge_table ); free_row( row, edge_table ); return edge; } /************************************************************************* * *N read_next_edge * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads the next VPF edge record from the input VPF table. * NOTE: This function allocates memory for "edge_rec.coord". * This array should be freed when no longer needed. * Must have called vpf_open_table with DISK as the storage type, * since this function accesses the disk to read the next row. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * edge_table == (vpf_table_type) opened VPF table to read. * return == (edge_rec_type) returned edge record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ edge_rec_type read_next_edge( vpf_table_type edge_table ) { edge_rec_type edge; row_type row; row = read_next_row( edge_table ); edge = create_edge_rec( row, edge_table ); free_row( row, edge_table ); return edge; } coordinate_type first_edge_coordinate( edge_rec_type *edge_rec ) { coordinate_type coord; tri_coordinate_type Zcoord; double_coordinate_type Bcoord; double_tri_coordinate_type Ycoord; int size; edge_rec->current_coordinate = 0; if (edge_rec->coord) { /* Coordinate array is in memory */ return edge_rec->coord[0]; } /* Read coordinate from table */ fseek(edge_rec->fp,edge_rec->startpos,SEEK_SET); switch (edge_rec->coord_type) { case 'C': fread(&coord,sizeof(coord),1,edge_rec->fp); size = sizeof(coord); break; case 'Z': fread(&Zcoord,sizeof(Zcoord),1,edge_rec->fp); coord.x = Zcoord.x; coord.y = Zcoord.y; size = sizeof(Zcoord); break; case 'B': fread(&Bcoord,sizeof(Bcoord),1,edge_rec->fp); coord.x = (float)Bcoord.x; coord.y = (float)Bcoord.y; size = sizeof(Bcoord); break; case 'Y': fread(&Ycoord,sizeof(Ycoord),1,edge_rec->fp); coord.x = (float)Ycoord.x; coord.y = (float)Ycoord.y; size = sizeof(Ycoord); break; default: coord.x = MAXFLOAT/2.0; coord.y = MAXFLOAT/2.0; size = 0; break; } edge_rec->pos = edge_rec->startpos + size; return coord; } coordinate_type next_edge_coordinate( edge_rec_type *edge_rec ) { coordinate_type coord; tri_coordinate_type Zcoord; double_coordinate_type Bcoord; double_tri_coordinate_type Ycoord; int size; if (edge_rec->current_coordinate < 0) return first_edge_coordinate(edge_rec); edge_rec->current_coordinate++; if (edge_rec->current_coordinate >= edge_rec->npts) { edge_rec->current_coordinate = edge_rec->npts-1L; if (!edge_rec->coord) fseek(edge_rec->fp,edge_rec->startpos + (edge_rec->npts-1L)*sizeof(coord), SEEK_SET); } if (edge_rec->coord) { /* Coordinate array is in memory */ return edge_rec->coord[edge_rec->current_coordinate]; } /* Read coordinate from table */ switch (edge_rec->coord_type) { case 'C': fread(&coord,sizeof(coord),1,edge_rec->fp); size = sizeof(coord); break; case 'Z': fread(&Zcoord,sizeof(Zcoord),1,edge_rec->fp); coord.x = Zcoord.x; coord.y = Zcoord.y; size = sizeof(Zcoord); break; case 'B': fread(&Bcoord,sizeof(Bcoord),1,edge_rec->fp); coord.x = (float)Bcoord.x; coord.y = (float)Bcoord.y; size = sizeof(Bcoord); break; case 'Y': fread(&Ycoord,sizeof(Ycoord),1,edge_rec->fp); coord.x = (float)Ycoord.x; coord.y = (float)Ycoord.y; size = sizeof(Ycoord); break; default: coord.x = MAXFLOAT/2.0; coord.y = MAXFLOAT/2.0; size = 0; break; } edge_rec->pos = edge_rec->startpos + size; return coord; } coordinate_type get_edge_coordinate( ossim_int32 n, edge_rec_type *edge_rec ) { coordinate_type coord; tri_coordinate_type Zcoord; double_coordinate_type Bcoord; double_tri_coordinate_type Ycoord; ossim_int32 size; if (n < 0) return first_edge_coordinate(edge_rec); if (n >= edge_rec->npts) n = edge_rec->npts-1L; edge_rec->current_coordinate = n; if (edge_rec->coord) { /* Coordinate array is in memory */ return edge_rec->coord[n]; } /* Read coordinate from table */ switch (edge_rec->coord_type) { case 'C': size = sizeof(coord); break; case 'Z': size = sizeof(Zcoord); break; case 'B': size = sizeof(Bcoord); break; case 'Y': size = sizeof(Ycoord); break; default: size = 0; break; } edge_rec->pos = edge_rec->startpos + (n*size); fseek(edge_rec->fp,edge_rec->pos,SEEK_SET); switch (edge_rec->coord_type) { case 'C': fread(&coord,sizeof(coord),1,edge_rec->fp); break; case 'Z': fread(&Zcoord,sizeof(Zcoord),1,edge_rec->fp); coord.x = Zcoord.x; coord.y = Zcoord.y; break; case 'B': fread(&Bcoord,sizeof(Bcoord),1,edge_rec->fp); coord.x = (float)Bcoord.x; coord.y = (float)Bcoord.y; break; case 'Y': fread(&Ycoord,sizeof(Ycoord),1,edge_rec->fp); coord.x = (float)Ycoord.x; coord.y = (float)Ycoord.y; break; default: coord.x = MAXFLOAT/2.0; coord.y = MAXFLOAT/2.0; break; } return coord; } /************************************************************************* * *N read_face * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads a VPF face record from the input VPF table. * It performs a search for the specified face number, and, if found, * reads and returns the face record. If id is out of range, * either the lowest or highest id numbered face record type will be * returned. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * id == (ossim_int32) face id number. * face_table == (vpf_table_type) opened VPF table to read. * return == (face_rec_type) returned face record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ face_rec_type read_face( ossim_int32 id, vpf_table_type face_table ) { face_rec_type face; int rowid,ring; ossim_int32 count; row_type row; rowid = table_pos( "ID", face_table ); ring = table_pos( "RING_PTR", face_table ); row = get_row( id, face_table ); get_table_element( rowid, row, face_table, &(face.id), &count ); get_table_element( ring, row, face_table, &(face.ring), &count ); free_row( row, face_table ); return face; } /************************************************************************* * *N read_next_face * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads the next VPF face record from the input VPF * table. Must have used vpf_open_table with DISK as the storage type. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * face_table == (vpf_table_type) opened VPF table to read. * return == (face_rec_type) returned face record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ face_rec_type read_next_face( vpf_table_type face_table ) { face_rec_type face; int rowid,ring; ossim_int32 count; row_type row; rowid = table_pos( "ID", face_table ); ring = table_pos( "RING_PTR", face_table ); row = read_next_row( face_table ); get_table_element( rowid, row, face_table, &(face.id), &count ); get_table_element( ring, row, face_table, &(face.ring), &count ); free_row( row, face_table ); return face; } /************************************************************************* * *N read_ring * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads a VPF ring record from the input VPF table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * id == (ossim_int32) ring id number. * ring_table == (vpf_table_type) opened VPF table to read. * return == (ring_rec_type) returned ring record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ ring_rec_type read_ring( ossim_int32 id, vpf_table_type ring_table ) { ring_rec_type ring; int rowid,face,edge; ossim_int32 count; row_type row; rowid = table_pos( "ID", ring_table ); face = table_pos( "FACE_ID", ring_table ); edge = table_pos( "START_EDGE", ring_table ); row = get_row( id, ring_table ); get_table_element( rowid, row, ring_table, &(ring.id), &count ); get_table_element( face, row, ring_table, &(ring.face), &count ); get_table_element( edge, row, ring_table, &(ring.edge), &count ); free_row( row, ring_table ); return ring; } /************************************************************************* * *N read_next_ring * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads the next VPF ring record from the input VPF table. * If read_next_ring goes past the end of the vpftable, ring_rec_type * id will be a garbage number. The programmer must ensure that this * does NOT happen. Must have called vpf_open_table with DISK as the * storage type. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * ring_table == (vpf_table_type) opened VPF table to read. * return == (ring_rec_type) returned ring record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ ring_rec_type read_next_ring( vpf_table_type ring_table ) { ring_rec_type ring; int rowid,face,edge; ossim_int32 count; row_type row; rowid = table_pos( "ID", ring_table ); face = table_pos( "FACE_ID", ring_table ); edge = table_pos( "START_EDGE", ring_table ); row = read_next_row( ring_table ); get_table_element( rowid, row, ring_table, &(ring.id), &count ); get_table_element( face, row, ring_table, &(ring.face), &count ); get_table_element( edge, row, ring_table, &(ring.edge), &count ); free_row( row, ring_table ); return ring; } /************************************************************************* * *N read_point * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads a VPF point record from the input VPF table. * It performs a search for the specified point number, and, if found, * reads and returns the point record. If read_point is given an * invalid id (eg 1000000) it will return garbage. It is the programmers * responsibility to ensure that this does NOT happen. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * id == (ossim_int32) point id number. * point_table == (vpf_table_type) opened VPF table to read. * return == (point_rec_type) returned point record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ point_rec_type read_point( ossim_int32 id, vpf_table_type point_table ) { point_rec_type point; int rowid,face,coord; ossim_int32 count; coordinate_type c; tri_coordinate_type Zcoord; double_coordinate_type Bcoord; double_tri_coordinate_type Ycoord; row_type row; rowid = table_pos( "ID", point_table ); face = table_pos( "CONTAINING_FACE", point_table ); coord = table_pos( "COORDINATE", point_table ); row = get_row( id, point_table ); get_table_element( rowid, row, point_table, &(point.id), &count ); if (face == -1) point.face = -1; else get_table_element( face, row, point_table, &(point.face), &count ); switch (point_table.header[coord].type) { case 'C': get_table_element( coord, row, point_table, &c, &count ); point.x = c.x; point.y = c.y; break; case 'Z': get_table_element( coord, row, point_table, &Zcoord, &count ); point.x = Zcoord.x; point.y = Zcoord.y; break; case 'B': get_table_element( coord, row, point_table, &Bcoord, &count ); point.x = (float)Bcoord.x; point.y = (float)Bcoord.y; break; case 'Y': get_table_element( coord, row, point_table, &Ycoord, &count ); point.x = (float)Ycoord.x; point.y = (float)Ycoord.y; break; default: point.x = MAXFLOAT/2.0; point.y = MAXFLOAT/2.0; break; } free_row( row, point_table ); return point; } /************************************************************************* * *N read_next_point * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads the next VPF point record from the input * VPF table. Must have called vpf_open_table with DISK as the * storage type. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * point_table == (vpf_table_type) opened VPF table to read. * return == (point_rec_type) returned point record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ point_rec_type read_next_point( vpf_table_type point_table ) { point_rec_type point; int rowid,face,coord; ossim_int32 count; coordinate_type c; tri_coordinate_type Zcoord; double_coordinate_type Bcoord; double_tri_coordinate_type Ycoord; row_type row; rowid = table_pos( "ID", point_table ); face = table_pos( "CONTAINING_FACE", point_table ); coord = table_pos( "COORDINATE", point_table ); row = read_next_row( point_table ); get_table_element( rowid, row, point_table, &(point.id), &count ); get_table_element( face, row, point_table, &(point.face), &count ); switch (point_table.header[coord].type) { case 'C': get_table_element( coord, row, point_table, &c, &count ); point.x = c.x; point.y = c.y; break; case 'Z': get_table_element( coord, row, point_table, &Zcoord, &count ); point.x = Zcoord.x; point.y = Zcoord.y; break; case 'B': get_table_element( coord, row, point_table, &Bcoord, &count ); point.x = (float)Bcoord.x; point.y = (float)Bcoord.y; break; case 'Y': get_table_element( coord, row, point_table, &Ycoord, &count ); point.x = (float)Ycoord.x; point.y = (float)Ycoord.y; break; default: point.x = MAXFLOAT/2.0; point.y = MAXFLOAT/2.0; break; } free_row( row, point_table ); return point; } /************************************************************************* * *N read_anno * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads a VPF annotation record from the input VPF table. * It performs a search for the specified annotation id, and, if * found, reads and returns the annotation record. NOTE: This function * allocates memory for "anno.text". This must be freed when no * longer needed. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * id == (ossim_int32) annotation id. * anno_table == (vpf_table_type) opened VPF table to read. * return == (anno_rec_type) returned annotation record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ anno_rec_type read_anno( ossim_int32 id, vpf_table_type anno_table ) { anno_rec_type anno; int rowid,text,coord; ossim_int32 count; coordinate_type *c; tri_coordinate_type *Zcoord; double_coordinate_type *Bcoord; double_tri_coordinate_type *Ycoord; row_type row; rowid = table_pos( "ID", anno_table ); text = table_pos( "STRING", anno_table ); coord = table_pos( "SHAPE_LINE", anno_table ); row = get_row( id, anno_table ); get_table_element( rowid, row, anno_table, &(anno.id), &count ); anno.text = (char*)get_table_element( text, row, anno_table, NULL, &count ); switch (anno_table.header[coord].type) { case 'C': c = (coordinate_type *)get_table_element( coord, row, anno_table, NULL, &count ); anno.x = c[0].x; anno.y = c[0].y; free(c); break; case 'Z': Zcoord = (tri_coordinate_type *)get_table_element( coord, row, anno_table, NULL, &count ); anno.x = Zcoord[0].x; anno.y = Zcoord[0].y; free(Zcoord); break; case 'B': Bcoord = (double_coordinate_type *)get_table_element( coord, row, anno_table, NULL, &count ); anno.x = (float)Bcoord[0].x; anno.y = (float)Bcoord[0].y; free(Bcoord); break; case 'Y': Ycoord = (double_tri_coordinate_type *)get_table_element( coord, row, anno_table, NULL, &count ); anno.x = (float)Ycoord[0].x; anno.y = (float)Ycoord[0].y; free(Ycoord); break; default: anno.x = MAXFLOAT/2.0; anno.y = MAXFLOAT/2.0; break; } free_row( row, anno_table ); return anno; } /************************************************************************* * *N read_next_anno * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads the next VPF annotation record from the input * VPF table. Must have called vpf_open_table with DISK as the storage * type. NOTE: This function allocates memory for "anno.text". This * must be freed when no longer needed. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * anno_table == (vpf_table_type) opened VPF table to read. * return == (anno_rec_type) returned annotation record. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C *E *************************************************************************/ anno_rec_type read_next_anno( vpf_table_type anno_table ) { anno_rec_type anno; int rowid,text,coord; ossim_int32 count; coordinate_type *c; tri_coordinate_type *Zcoord; double_coordinate_type *Bcoord; double_tri_coordinate_type *Ycoord; row_type row; rowid = table_pos( "ID", anno_table ); text = table_pos( "STRING", anno_table ); coord = table_pos( "SHAPE_LINE", anno_table ); row = read_next_row( anno_table ); get_table_element( rowid, row, anno_table, &(anno.id), &count ); anno.text = (char*)get_table_element( text, row, anno_table, NULL, &count ); switch (anno_table.header[coord].type) { case 'C': c = (coordinate_type *)get_table_element( coord, row, anno_table, NULL, &count ); anno.x = c[0].x; anno.y = c[0].y; free(c); break; case 'Z': Zcoord = (tri_coordinate_type *)get_table_element( coord, row, anno_table, NULL, &count ); anno.x = Zcoord[0].x; anno.y = Zcoord[0].y; free(Zcoord); break; case 'B': Bcoord = (double_coordinate_type *)get_table_element( coord, row, anno_table, NULL, &count ); anno.x = (float)Bcoord[0].x; anno.y = (float)Bcoord[0].y; free(Bcoord); break; case 'Y': Ycoord = (double_tri_coordinate_type *)get_table_element( coord, row, anno_table, NULL, &count ); anno.x = (float)Ycoord[0].x; anno.y = (float)Ycoord[0].y; free(Ycoord); break; default: anno.x = MAXFLOAT/2.0; anno.y = MAXFLOAT/2.0; break; } free_row( row, anno_table ); return anno; } ossim-Miami-2.9.1/src/vpfutil/vpfptply.c000066400000000000000000000350271352751253100202320ustar00rootroot00000000000000/*************************************************************************** * *N VPFPTPLY.C * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions to test whether a given point lies * inside of a VPF representation of a face (or polygon, geometrically). * The method used is to create a plum line from the given test point * out to basically infinity and count the number of intersections * with all of the line segements of the outer and inner rings of the * face. An odd count indicates that the test point is inside of * the face; an even count (0 is even) indicates that the point lies * outside of the polygon (including inside of a hole). * There are two main interface routines: * point_in_face() if you already have the Face primitive tables open. * point_in_face_table() if you want to just specify the path. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions: *F * int intersect( line_segment_type l1, line_segment_type l2, * float *xint, float *yint ); * int intersect_polygon_edge( float x, float y, edge_rec_type edge_rec ); * int intersect_polygon_loop( float x, float y, * int face_id, ossim_int32 start_edge, * vpf_table_type edgetable ); * int point_in_face( float x, float y, * ossim_int32 face_id, * vpf_table_type facetable, * vpf_table_type ringtable, * vpf_table_type edgetable ); * int point_in_face_table( float x, float y, * ossim_int32 face_id, * char *fname ); *E **************************************************************************/ #include #include #include #ifdef __MSDOS__ #include #endif #include #if defined(__CYGWIN__)||defined(__APPLE__)|| defined(_WIN32) #include #else #include #endif #ifdef __MSDOS__ #include #endif #include #include #include #include #include #include # ifndef min # define min(a,b) ((a) <= (b) ? (a) : (b)) # endif # ifndef max # define max(a,b) ((a) <= (b) ? (b) : (a)) # endif typedef struct { float x1; float y1; float x2; float y2; } line_segment_type; /************************************************************************** * *N intersect * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Test whether line segment l1 intersects line segment l2 *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * l1 == (line_segment_type) line segment one. * l2 == (line_segment_type) line segment two. * xint == (float *) intersection point x coordinate. * yint == (float *) intersection point y coordinate. * intersect == (int) VPF_BOOLEAN: * 1 --> line segments intersect * 0 --> line segments do not intersect *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ int intersect( line_segment_type l1, line_segment_type l2, float *xint, float *yint ) { double m1,m2,b1=0,b2=0; float tempy1,tempy2; if ( (l1.x1==l1.x2) && (l2.y1==l2.y2) ) { /* l1 is vertical and l2 is horizontal */ if ( ( ((l2.x1 <= l1.x1) && (l1.x1 <= l2.x2)) || /* X coordinate */ ((l2.x2 <= l1.x1) && (l1.x1 <= l2.x1)) ) && /* intersects */ ( ((l1.y1 <= l2.y1) && (l2.y1 <= l1.y2)) || /* Y coordinate */ ((l1.y2 <= l2.y1) && (l2.y1 <= l1.y1)) ) ) /* intersects */ { *xint = l1.x1; *yint = l2.y1; return 1; } else { return 0; } } if ( (l2.x1==l2.x2) && (l1.y1==l1.y2) ) { /* l2 is vertical and l1 is horizontal */ if ( ( ((l1.x1 <= l2.x1) && (l2.x1 <= l1.x2)) || /* X coordinate */ ((l1.x2 <= l2.x1) && (l2.x1 <= l1.x1)) ) && /* intersects */ ( ((l2.y1 <= l1.y1) && (l1.y1 <= l2.y2)) || /* Y coordinate */ ((l2.y2 <= l1.y1) && (l1.y1 <= l2.y1)) ) ) /* intersects */ { *xint = l2.x1; *yint = l1.y1; return 1; } else { return 0; } } if ( (l1.x1==l2.x1) && (l1.y1==l2.y1) ) { *xint = l1.x1; *yint = l1.y1; return 1; } if ( (l1.x2==l2.x2) && (l1.y2==l2.y2) ) { *xint = l1.x2; *yint = l1.y2; return 1; } if ( (l1.x1==l2.x2) && (l1.y1==l2.y2) ) { *xint = l1.x1; *yint = l1.y1; return 1; } if ( (l1.x2==l2.x1) && (l1.y2==l2.y1) ) { *xint = l1.x2; *yint = l1.y2; return 1; } if (l1.x1 != l1.x2) { m1 = (l1.y2-l1.y1)/(l1.x2-l1.x1); b1 = -1.0*m1*l1.x1 + l1.y1; } else { /* l1 is a vertical line */ m1 = MAXFLOAT; } if (l2.x1 != l2.x2) { m2 = (l2.y2-l2.y1)/(l2.x2-l2.x1); b2 = -1.0*m2*l2.x1 + l2.y1; } else { /* l2 is a vertical line */ m2 = MAXFLOAT; } /* Find intersection point of lines */ if ((m1 == m2) && (m1 != MAXFLOAT)) return 0; if ( (m1 != MAXFLOAT) && (m2 != MAXFLOAT) ) { /* neither line is a vertical line */ *xint = (float)((b2-b1)/(m1-m2)); if (m1 == 0) /* if l1 is a horizontal line */ *yint = l1.y1; else { if (m2 == 0) /* if l2 is a horizontal line */ *yint = l2.y1; else *yint = (float)(m1*(*xint)+b1); } } else { /* At least one vertical line */ if (m1==m2) { /* Both vertical lines */ if (l1.x1==l2.x1) { /* Coincident vertical lines */ *xint = l1.x1; tempy1 = (float) min( l1.y1, l1.y2 ); tempy2 = (float) min( l2.y1, l2.y2 ); *yint = (float) max( tempy1, tempy2 ); } else { /* Non-coincident vertical lines */ return 0; } } else if (m1==MAXFLOAT) { /* l1 is vertical */ if ( ((l2.x1 <= l1.x1) && (l2.x2 >= l1.x1)) || ((l2.x2 <= l1.x1) && (l2.x1 >= l1.x1)) ) { *yint = (float)(m2*l1.x1 + b2); /* l2 intersects l1 */ *xint = l1.x1; } else return 0; /* l2 does not intersect l1 */ } else { /* l2 is vertical */ if ( ((l1.x1 <= l2.x1) && (l1.x2 >= l2.x1)) || ((l1.x2 <= l2.x1) && (l1.x1 >= l2.x1)) ) { *yint = (float)(m1*l2.x1 + b1); /* l1 intersects l2 */ *xint = l2.x1; } else return 0; /* l1 does not intersect l2 */ } } /* See if intersection point lies on both line segments */ return ( (*xint >= (float)min(l1.x1,l1.x2)) && (*xint <= (float)max(l1.x1,l1.x2)) && (*yint >= (float)min(l1.y1,l1.y2)) && (*yint <= (float)max(l1.y1,l1.y2)) && (*xint >= (float)min(l2.x1,l2.x2)) && (*xint <= (float)max(l2.x1,l2.x2)) && (*yint >= (float)min(l2.y1,l2.y2)) && (*yint <= (float)max(l2.y1,l2.y2)) ); } /*************************************************************************** * *N intersect_polygon_edge * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Count the number of intersections between a plum line from the * test point and infinity and the vertices of the given edge. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * x == (float) test point x coordinate. * y == (float) test point y coordinate. * edge_rec == (edge_rec_type) given edge. * intersect_polygon_edge == (int) number of intersection points. *E **************************************************************************/ int intersect_polygon_edge( float x, float y, edge_rec_type edge_rec ) { register ossim_int32 i; line_segment_type lseg, pseg; int n; float xint,yint; coordinate_type coord1,coord2; lseg.x1 = x; lseg.y1 = y; lseg.x2 = MAXFLOAT/2.0; lseg.y2 = y; n = 0; coord1 = first_edge_coordinate(&edge_rec); for (i=1;i == (float) test point x coordinate. * y == (float) test point y coordinate. * face_id == (int) given polygon loop. * start_edge == (ossim_int32) one edge of the polygon loop. * edge_table == (vpf_table_type) VPF edge table. * intersect_polygon_loop == (int) number of intersections. *E **************************************************************************/ int intersect_polygon_loop( float x, float y, int face_id, ossim_int32 start_edge, vpf_table_type edgetable ) { edge_rec_type edge_rec; ossim_int32 next, prevnode; VPF_BOOLEAN done = FALSE; int n; edge_rec = read_edge( start_edge, edgetable ); edge_rec.dir = '+'; n = intersect_polygon_edge( x, y, edge_rec ); prevnode = edge_rec.start; next = next_polygon_edge(&edge_rec,&prevnode,face_id); if (edge_rec.coord) free(edge_rec.coord); while (!done) { if (next <= 0) done = TRUE; if (next == start_edge) done = TRUE; if (!done) { edge_rec = read_edge( next, edgetable ); next = next_polygon_edge(&edge_rec,&prevnode,face_id); n += intersect_polygon_edge( x, y, edge_rec ); if (edge_rec.coord) free(edge_rec.coord); } } return n; } /*************************************************************************** * *N point_in_face * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Test whether a line (x,y through infinity) intersects a face (which * itself is multiple polygon_loop or ring structures). Returns a 0 * if outside, 1 if inside. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * x == (float) x coordinate of given point. * y == (float) y coordinate of given point. * face_id == (ossim_int32) given face. * facetable == (vpf_table_type) VPF face table. * ringtable == (vpf_table_type) VPF ring table. * edgetable == (vpf_table_type) VPF edge table. * point_in_face == (int) VPF_BOOLEAN: * 1 --> inside * 0 --> outside *E **************************************************************************/ int point_in_face( float x, float y, ossim_int32 face_id, vpf_table_type facetable, vpf_table_type ringtable, vpf_table_type edgetable ) { face_rec_type face_rec; ring_rec_type ring_rec; int n; face_rec = read_face( face_id, facetable ); ring_rec = read_ring( face_rec.ring, ringtable ); n = intersect_polygon_loop( x, y, face_id, ring_rec.edge, edgetable ); while (ring_rec.face == face_id ) { ring_rec = read_next_ring( ringtable ); if (feof(ringtable.fp)) { break; } if (ring_rec.face == face_id) { n += intersect_polygon_loop( x, y, face_id, ring_rec.edge, edgetable ); } } if (n%2 == 0) /* Even number of intersections */ return 0; /* Not inside polygon */ else /* Odd number of intersections */ return 1; /* Inside polygon */ } static void dirpath( char *path ) { register unsigned int i; i = (int)strlen(path)-1; while ( (i>0) && (path[i] != '\\') ) i--; if (i<(strlen(path)-1)) i++; path[i] = '\0'; } /*************************************************************************** * *N point_in_face_table * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Test whether a point is inside a face or not. Must have a valid path- * name to a valid VPF Face file, or else be in graphics mode for the error * message that will result. Filename must have all directory seperators * escapes; eg. c:\\vpf NOT c:\vpf *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * Parameters: *A * x == (float) given point x coordinate. * y == (float) given point y coordinate. * face_id == (ossim_int32) face. * fname == (char *) pathname to VPF face file. * point_in_face_table == VPF_BOOLEAN: * 1 --> point is inside * 0 --> point is not inside *E **************************************************************************/ int point_in_face_table( float x, float y, ossim_int32 face_id, char *fname ) { vpf_table_type facetable, ringtable, edgetable; char *name; int result; name = (char *)vpfmalloc( 255*sizeof(char) ); facetable = vpf_open_table(fname,disk, "rb", NULL ); strupr(fname); strcpy( name, fname ); dirpath( name ); strcat( name, "RNG" ); ringtable = vpf_open_table( name, disk , "rb", NULL ); strcpy( name, fname ); dirpath( name ); strcat( name, "EDG" ); edgetable = vpf_open_table( name, disk , "rb", NULL ); free( name ); result = point_in_face( x, y, face_id, facetable, ringtable, edgetable ); vpf_close_table(&facetable); vpf_close_table(&ringtable); vpf_close_table(&edgetable); return result; } ossim-Miami-2.9.1/src/vpfutil/vpfquery.c000066400000000000000000000571421352751253100202310ustar00rootroot00000000000000/************************************************************************* * *N Module VPFQUERY * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions for querying a VPF table with a * selection expression. It has one main entry point - query_table(). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions: *F * set_type query_table( char *expression, vpf_table_type table ); *E *************************************************************************/ #include #include #if defined(__MSDOS__) #include #include #include #else #ifdef __APPLE__ #include #include #else #if !defined(__OpenBSD__) && !defined( __FreeBSD__) #include #include #endif #endif #endif #ifndef __MSDOS__ #ifndef _WIN32 #include #endif #endif #include #include #include #include #include #include /* Delimiter tokens */ typedef enum { EQ, NE, LE, GE, LT, GT, AND, OR, QUOTE } delim_type; /*static delim_type delim;*/ /* Valid delimeter strings */ char *delimstr[] = { "=", "<>", "<=", ">=", "<", ">", " AND ", " OR ", "\"" }; int ndelim = 9; char **fieldname; int *fieldcol; int nfields; /* Token types */ #define DELIMETER 1 #define FIELD 2 #define VALUE 3 #define QUOTE 4 #define STRING 5 #define EOL 6 #define FINISHED 7 #define LOP 8 /* Logical Operator */ #define JOIN 9 #define ERROR 10 #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif typedef struct { int field; char op; char value[255]; char join; } expr_type; static void *memalloc( ossim_uint32 size ) { void *ptr; ptr = malloc(size); if (!ptr) { #ifdef __MSDOS__ printf("Memory allocation error in VPFQUERY (%d)(%d)\n",size, farcoreleft()); #else printf("Memory allocation error in VPFQUERY (%d)\n",(int)size); #endif exit(1); } return ptr; } int is_white( char c ) { if (c==' ' || c=='\t') return 1; return 0; } /************************************************************************* * *N return_token * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the first token string found in the * expression string. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * expr ==(char *) selection expression string. * token ==(char *) first token in the string. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ static void return_token( char *expr, char *token ) { register int i,j,n,found=0,stopflag; n = 0; stopflag=0; while (expr[0] == ' ') { for (i=0;i0) token[i] = '\0'; else token[strlen(delimstr[j])] = '\0'; found = 1; break; } } if ((found) || (!is_white(*expr))) n++; if ((!found)&&(*expr)) expr++; /* if (!is_white(*expr)) n++; */ /* if ((found) || (!is_white(*expr))) n++; */ if (found) break; } } /************************************************************************* * *N get_token * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function gets the first token, token type, and token value of * the expression string, and then advances the expression string * past the token. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * expression ==(char *) selection expression string. * token ==(char *) first token in the string. * token_type ==(int *) token type. * token_value ==(int *) token_value. * return ==(char *) new selection expression. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * static void return_token( char *expr, char *token ) VPFQUERY.C *E *************************************************************************/ static char *get_token( char *expression, char *token, int *token_type, int *token_value ) { register int i, stopflag; *token_type = 0; if (*expression == '\0') { *token_type = FINISHED; *token_value = 0; return expression; } if (*expression=='\r') { /* crlf */ ++expression; ++expression; *token = '\r'; token[1] = '\n'; token[2] = 0; *token_type = DELIMETER; } stopflag = 0; while ((expression[0] == '\"') || (expression[0] == ' ')) { for (i=0;i==(char *) selection expression string. * table ==(vpf_table_type) VPF table structure. * return ==(linked_list_type) list of expression clauses. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * char *get_token( char *expression, char *token, int *token_type, * int *token_value) VPFQUERY.C * void display_message( char *input) USER DEFINED * linked_list_type ll_init() LINKLIST.C * void ll_reset( linked_list_type list ) LINKLIST.C * void ll_insert( void *element, unsigned size, * position_type position ) LINKLIST.C *E *************************************************************************/ static linked_list_type parse_expression( char *expression, vpf_table_type table ) { linked_list_type exprlist; position_type pos; expr_type expr; int i, token_type, token_value; char token[260]; exprlist = ll_init(); pos = exprlist; /* Set up static globals */ nfields = table.nfields; fieldname = (char **)memalloc( (nfields+2) * sizeof(char *) ); fieldcol = (int *)memalloc( (nfields+2) * sizeof(int) ); for (i=0;inext; expression = get_token( expression, token, &token_type, &token_value ); } else if (token_type == FINISHED) { expr.join = '\0'; ll_insert( &expr, sizeof(expr), pos ); } else { display_message("Expression syntax error"); ll_reset(exprlist); exprlist = NULL; break; } } for (i=0;i 255 should not be * compared with this function. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * val1 ==(void *) first buffer to compare. * val2 ==(void *) second buffer to compare. * size ==(int) number of bytes to compare. * op ==(char) logical operator. * return ==(int) TRUE or FALSE. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ static int comp( void *val1, void *val2, int size, char op ) { int result; result = memcmp(val1,val2,size); switch (op) { case EQ: result = !result; break; case NE: break; case LT: if (result < 0) result = TRUE; else result = FALSE; break; case LE: if (result <= 0) result = TRUE; else result = FALSE; break; case GT: if (result > 0) result = TRUE; else result = FALSE; break; case GE: if (result >= 0) result = TRUE; else result = FALSE; break; default: printf("Invalid logical operator (%d)\n",op); result = FALSE; break; } return result; } /************************************************************************* * *N strcompare * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function compares two strings with the given logical operator. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * val1 ==(char *) first buffer to compare. * val2 ==(char *) second buffer to compare. * op ==(char) logical operator. * return ==(int) TRUE or FALSE. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ static int strcompare( char *val1, char *val2, char op ) { int result; char str1[300], str2[300]; strcpy(str1,val1); rightjust(str1); strcpy(str2,val2); rightjust(val2); result = ossim_strcasecmp(str1,str2); switch (op) { case EQ: result = !result; break; case NE: break; case LT: if (result < 0) result = TRUE; else result = FALSE; break; case LE: if (result <= 0) result = TRUE; else result = FALSE; break; case GT: if (result > 0) result = TRUE; else result = FALSE; break; case GE: if (result >= 0) result = TRUE; else result = FALSE; break; default: printf("Invalid logical operator (%d)\n",op); result = FALSE; break; } return result; } /************************************************************************* * *N icompare * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function compares two ossim_int32 integers with the given logical * operator. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * val1 ==(ossim_int32) first buffer to compare. * val2 ==(ossim_int32) second buffer to compare. * op ==(char) logical operator. * return ==(int) TRUE or FALSE. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ static int icompare( ossim_int32 val1, ossim_int32 val2, char op ) { int result; switch (op) { case EQ: result = (val1 == val2); break; case NE: result = (val1 != val2); break; case LT: result = (val1 < val2); break; case LE: result = (val1 <= val2); break; case GT: result = (val1 > val2); break; case GE: result = (val1 >= val2); break; default: printf("Invalid logical operator (%d)\n",op); result = FALSE; break; } return result; } /************************************************************************* * *N fcompare * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function compares two floating point numbers with the given * logical operator. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * val1 ==(ossim_int32) first buffer to compare. * val2 ==(ossim_int32) second buffer to compare. * op ==(char) logical operator. * return ==(int) TRUE or FALSE. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *************************************************************************/ static int fcompare( float val1, float val2, char op ) { int result; switch (op) { case EQ: result = (val1 == val2); break; case NE: result = (val1 != val2); break; case LT: result = (val1 < val2); break; case LE: result = (val1 <= val2); break; case GT: result = (val1 > val2); break; case GE: result = (val1 >= val2); break; default: printf("Invalid logical operator (%d)\n",op); result = FALSE; break; } return result; } /************************************************************************* * *N query_table * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the set of selected rows of a VPF table * based upon the evaluation of the given selection expression string. * * The expression is strictly evaluated left to right. No nesting * is supported, so parentheses are not allowed. The expression * must match the form: * [ ] * where, * is a valid field name of the table. * is one of the following: =, <, >, <=, >=, <> (not equal). * is a valid value for the field. * is either " AND " or " OR ". * Any number of clauses () may be joined * together with AND or OR to form the expression. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * expression ==(char *) selection expression string. * table ==(vpf_table_type) VPF table structure. * return ==(set_type) set of selected rows. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * set_type set_init( ossim_int32 n ) SET.C * void set_insert( ossim_int32 element, set_type set ) SET.C * linked_list_type parse_expression( char *expression, * vpf_table_type table ) VPFQUERY.C * row_type read_next_row( vpf_table_type table ) VPFREAD.C * position_type ll_first( linked_list_type list ) LINKLIST.C * int ll_end( position_type position ) LINKLIST.C * void ll_element( position_type position, void *element ) LINKLIST.C * void *get_table_element( ossim_int32 field_number, * row_type row, * vpf_table_type table, * void *value, * ossim_int32 *count ) VPFREAD.C * void display_message( char *info ) USER DEFINED * static int strcompare( char *val1, char *val2, char op ) VPFQUERY.C * static int icompare( ossim_int32 val1, ossim_int32 val2, char op ) VPFQUERY.C * static int fcompare( float val1, float val2, char op ) VPFQUERY.C * void ll_reset( linked_list_type list ) LINKLIST.C void free_row( row_type row, vpf_table_type table) VPFREAD.C *E *************************************************************************/ set_type query_table( char *expression, vpf_table_type table ) { row_type row; position_type pos; expr_type expr; register ossim_int32 i; int boolval=FALSE, booltemp=0, join = OR; ossim_int32 lval, lval2, count; float fval, fval2; char tval, tval2, *tptr; linked_list_type exprlist; set_type select_set; select_set = set_init(table.nrows+1); if (strcmp(expression,"*")==0) { set_on(select_set); return select_set; } exprlist = parse_expression( expression, table ); if (!exprlist) return select_set; if (table.storage == DISK) fseek( table.fp, index_pos(1,table), SEEK_SET ); for (i=1;i<=table.nrows;i++) { if (table.storage == DISK) row = read_next_row(table); else row = get_row( i, table ); pos = ll_first(exprlist); while (!ll_end(pos)) { ll_element( pos, &expr ); switch (table.header[expr.field].type) { case 'I': if (table.header[expr.field].count == 1) { get_table_element( expr.field, row, table, &lval, &count ); lval2 = atol(expr.value); booltemp = icompare( lval, lval2, expr.op ); } else { display_message( "Selection may not be performed upon arrays"); i=table.nrows+1; } break; case 'T': if (table.header[expr.field].count == 1) { get_table_element( expr.field, row, table, &tval, &count ); tval2 = expr.value[0]; booltemp = comp( &tval, &tval2, sizeof(tval), expr.op ); } else { tptr = (char *)get_table_element( expr.field, row, table, NULL, &count ); booltemp = strcompare( tptr, expr.value, expr.op ); free(tptr); } break; case 'F': if (table.header[expr.field].count == 1) { get_table_element( expr.field, row, table, &fval, &count ); if (!is_vpf_null_float(fval)) { fval2 = (float)atof(expr.value); booltemp = fcompare( fval, fval2, expr.op ); } else booltemp = FALSE; } else { display_message( "Selection may not be performed upon arrays"); i=table.nrows+3; } break; default: display_message("Field type not supported for query"); i=table.nrows+3; break; } if (i>table.nrows) break; if (join==OR) boolval = boolval || booltemp; else boolval = boolval && booltemp; join = expr.join; pos = pos->next; } free_row( row, table ); if (boolval) set_insert(i,select_set); boolval = FALSE; join = OR; if (i==table.nrows+3) break; } ll_reset(exprlist); return select_set; } ossim-Miami-2.9.1/src/vpfutil/vpfread.c000066400000000000000000001322741352751253100177770ustar00rootroot00000000000000/************************************************************************* * *N Module VPFREAD.C * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions for reading VPF tables. It, along * with VPFTABLE.C and VPFWRITE.C (and VPFIO.C for UNIX), comprises a * fairly extensive set of functions for handling VPF tables. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 Original Version DOS Turbo C * David Flinn Jul 1991 Merged with Barry & Mody's code for UNIX * Jim TenBrink Oct 1991 Split this module off from vpftable and * merged converter and vpfview branches * for the functions included here.. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. It includes #ifdefs for * all system dependencies, so that it will work efficiently with * either Turbo C in DOS or (at least) GNU C in UNIX. *E * *************************************************************************/ #include #ifdef __MSDOS__ #include #include #include #include #include #else #ifndef _WIN32 #include #endif #endif #if UNIX #include #define SEEK_SET 0 /* Turbo C fseek value */ #define SEEK_CUR 1 #define farmalloc malloc /* no farmallocs on UNIX */ #endif #include #include #include #include #include #include # ifndef min # define min(a,b) ((a) <= (b) ? (a) : (b)) # endif # ifndef max # define max(a,b) ((a) <= (b) ? (b) : (a)) # endif extern int STORAGE_BYTE_ORDER; /* Repeat functions statically to reduce external module dependencies */ /* * currently being used by the converter routines, not by the vpfview * routines */ static char * get_line (FILE *fp) { ossim_int32 CurrentChar, /* This is an int because fgetc returns an int */ count , NextBlock = 256 , LineAllocation = 0 ; char *CurrentLine = (char *) NULL ; /* This forever loop searches past all lines beginning with #, indicating comments. */ for (;;) { CurrentChar = fgetc(fp); if ( CurrentChar == COMMENT ) /* skip past comment line */ for (;CurrentChar != NEW_LINE; ) { if (CurrentChar == EOF) return (char *) NULL ; CurrentChar = fgetc (fp) ; } else break ; } /* end of forever loop */ if (CurrentChar == EOF ) return (char *) NULL ; for(count = 0; CurrentChar != EOF; CurrentChar = fgetc(fp), count++) { /* Allocate space for output line, if needed */ if (! ( count < LineAllocation )) { LineAllocation += NextBlock ; if ( CurrentLine ) CurrentLine = (char *) realloc ( CurrentLine, LineAllocation ); else CurrentLine = (char *) vpfmalloc ( LineAllocation ); if (!CurrentLine) { return (char *) NULL ; } } if ( CurrentChar == (ossim_int32) LINE_CONTINUE ) { CurrentChar = fgetc(fp ) ; /* read character after backslash */ /* A newline will be ignored and thus skipped over */ if ( CurrentChar == (ossim_int32) SPACE ) /* Assume line continue error */ while ( fgetc (fp) != (ossim_int32) SPACE ) ; else if (CurrentChar != (ossim_int32) NEW_LINE ) { /* copy it if not new line */ CurrentLine[count++] = (char) LINE_CONTINUE ; CurrentLine[count] = (char) CurrentChar ; } else count -- ; /* Decrement the counter on a newline character */ } else if (CurrentChar == (ossim_int32) NEW_LINE ) /* We're done */ break; else CurrentLine[count] = (char)CurrentChar; } /* end of for count */ CurrentLine[count] = '\0'; /* terminate string */ return CurrentLine ; } /* #if UNIX */ ossim_int32 VpfRead ( void *to, VpfDataType type, ossim_int32 count, FILE *from ) { ossim_int32 retval=0 , i ; switch ( type ) { case VpfChar: retval = (long)fread ( to, sizeof (char), count, from ) ; break ; case VpfShort: { short int stemp , *sptr = (short *) to ; for ( i=0; i < count; i++ ) { retval = (long)fread ( &stemp, sizeof (short), 1, from ) ; if (STORAGE_BYTE_ORDER != MACHINE_BYTE_ORDER) swap_two ( (char*)&stemp, (char*)sptr ) ; else *sptr = stemp; sptr++ ; } } break ; case VpfInteger: { if (STORAGE_BYTE_ORDER != MACHINE_BYTE_ORDER) { ossim_int32 itemp, *iptr = (ossim_int32 *) to ; for ( i=0; i < count; i++ ) { retval = (long)fread ( &itemp, sizeof (ossim_int32), 1, from ) ; swap_four ( (char*)&itemp, (char*)iptr ) ; iptr++ ; } } else { retval = (long)fread ( to, sizeof (ossim_int32), count, from ) ; } } break ; case VpfFloat: { float ftemp , *fptr = (float *) to ; for ( i=0; i < count; i++ ) { retval = (long)fread ( &ftemp, sizeof (float), 1, from ) ; if (STORAGE_BYTE_ORDER != MACHINE_BYTE_ORDER) swap_four ( (char*)&ftemp, (char*)fptr ) ; else *fptr = ftemp; fptr++ ; } } break ; case VpfDouble: { double dtemp , *dptr = (double *) to ; for ( i=0; i < count; i++ ) { retval = (long)fread ( &dtemp, sizeof (double), 1, from ) ; if (STORAGE_BYTE_ORDER != MACHINE_BYTE_ORDER) swap_eight ( (char*)&dtemp, (char*)dptr ) ; else *dptr = dtemp; dptr++ ; } } break ; case VpfDate: { date_type *dp = (date_type *) to ; retval = (long)fread(dp,sizeof(date_type)-1,count,from); } break ; case VpfCoordinate: { if (STORAGE_BYTE_ORDER != MACHINE_BYTE_ORDER) { coordinate_type ctemp , *cptr = (coordinate_type *) to ; for ( i=0; i < count; i++ ) { retval = (long)fread ( &ctemp, sizeof (coordinate_type), 1, from ) ; swap_four ( (char*)&ctemp.x, (char*)&cptr->x ) ; swap_four ( (char*)&ctemp.y, (char*)&cptr->y ) ; cptr++ ; } } else { retval = (long)fread ( to, sizeof (coordinate_type), count, from ) ; } } break ; case VpfDoubleCoordinate: { double_coordinate_type dctemp , *dcptr = (double_coordinate_type *) to ; for ( i=0; i < count; i++ ) { retval = (long)fread ( &dctemp, sizeof (double_coordinate_type), 1, from ) ; if (STORAGE_BYTE_ORDER != MACHINE_BYTE_ORDER) { swap_eight ( (char*)&dctemp.x, (char*)&dcptr->x ) ; swap_eight ( (char*)&dctemp.y, (char*)&dcptr->y ) ; } else { dcptr->x = dctemp.x; dcptr->y = dctemp.y; } dcptr++ ; } } break ; case VpfTriCoordinate: { tri_coordinate_type ttemp , *tptr = (tri_coordinate_type *) to ; for ( i=0; i < count; i++ ) { retval = (long)fread ( &ttemp, sizeof (tri_coordinate_type), 1, from ) ; if (STORAGE_BYTE_ORDER != MACHINE_BYTE_ORDER) { swap_four ( (char*)&ttemp.x, (char*)&tptr->x ) ; swap_four ( (char*)&ttemp.y, (char*)&tptr->y ) ; swap_four ( (char*)&ttemp.z, (char*)&tptr->z ) ; } else { tptr->x = ttemp.x; tptr->y = ttemp.y; tptr->z = ttemp.z; } tptr++ ; } } break ; case VpfDoubleTriCoordinate: { double_tri_coordinate_type dttemp , *dtptr = (double_tri_coordinate_type *) to ; for ( i=0; i < count; i++ ) { retval = (long)fread ( &dttemp, sizeof (double_tri_coordinate_type), 1, from); if (STORAGE_BYTE_ORDER != MACHINE_BYTE_ORDER) { swap_eight ( (char*)&dttemp.x, (char*)&dtptr->x ) ; swap_eight ( (char*)&dttemp.y, (char*)&dtptr->y ) ; swap_eight ( (char*)&dttemp.z, (char*)&dtptr->z ) ; } else { dtptr->x = dttemp.x; dtptr->y = dttemp.y; dtptr->z = dttemp.z; } dtptr++ ; } } break ; case VpfNull: /* Do Nothing */ break ; default: break ; } /* end of switch */ return retval ; /* whatever fread returns */ } /* #endif */ /************************************************************************* * *N read_text_defstr * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads the definition string from an input file for * creating a VPF table. * Currently being used by converter routines, not by vpfview routines. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * infile == (FILE *) file pointer to the input file. * outerr == (FILE *) file pointer to the error file. * return == (char *) definition string of the file. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn July 1991 Original version developed for UNIX *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * get_line() *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ char *read_text_defstr ( FILE *infile, FILE * outerr ) { char *definition ; rewind ( infile ); if (( (definition = get_line (infile )) == NULL ) || ( definition[strlen(definition)-1] != ';' )) { return (char *) NULL ; } return definition ; } #if UNIX /* * currently being used by converter routines, not by vpfview * routines */ int add_null_values ( char *name, vpf_table_type table, FILE * fpout ) { FILE *nullfp=0; ossim_int32 i , ptr ; char *cval=0, *line=0, *field=0 ; nullfp = fopen( name, "r"); if ( !nullfp ) return 0; /* Now read nulls from file and populate table structure */ while ( (line = get_line ( nullfp )) ) { ptr = 0 ; field = get_string ( &ptr, line, FIELD_SEPERATOR ) ; i = table_pos ( field, table ) ; switch ( table.header[i].type ) { case 'T': cval = get_string ( &ptr, line, FIELD_SEPERATOR ) ; free ( table.header[i].nullval.Char ) ; /* get rid of default */ table.header[i].nullval.Char = (char *) vpfmalloc ( (unsigned long)strlen (cval)+1) ; strcpy ( table.header[i].nullval.Char, cval ) ; free (cval) ; break ; case 'I': table.header[i].nullval.Int = get_number ( &ptr, line, FIELD_SEPERATOR ); break ; case 'S': table.header[i].nullval.Short = (short int) get_number ( &ptr, line, FIELD_SEPERATOR ); break ; case 'R': cval = get_string ( &ptr, line, FIELD_SEPERATOR ) ; table.header[i].nullval.Double = atof ( cval ) ; free ( cval ) ; break ; case 'F': cval = get_string ( &ptr, line, FIELD_SEPERATOR ) ; table.header[i].nullval.Float = (float) atof ( cval ) ; free ( cval ) ; break ; default: free(field);fclose(nullfp); return 0 ; break ; } free(field); free(line); } fclose(nullfp); return 1 ; } #endif /************************************************************************* * *N index_length * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the length of a specified row from the table * index. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row_number == (ossim_int32) row number in the table. * table == (vpf_table_type) VPF table structure. * return == (ossim_int32) length of the table row or 0 on error. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 Original Version DOS Turbo C * Dave Flinn July 1991 UNIX extensions * JTB 10/91 removed aborts() *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ ossim_int32 index_length( ossim_int32 row_number, vpf_table_type table ) { ossim_int32 recsize,len=0; ossim_uint32 ulen; long int pos; STORAGE_BYTE_ORDER = table.byte_order; if (row_number < 1) row_number = 1; if (row_number > table.nrows) row_number = table.nrows; switch (table.xstorage) { case COMPUTE: len = table.reclen; break; case DISK: recsize = sizeof(index_cell); fseek( table.xfp, (ossim_int32)(row_number*recsize), SEEK_SET ); if ( ! Read_Vpf_Int(&pos,table.xfp,1) ) { len = (ossim_int32)0 ; } if ( ! Read_Vpf_Int(&ulen,table.xfp,1) ) { return (ossim_int32)0 ; } len = ulen; break; case RAM: len = table.index[row_number-1].length; break; default: if ( table.mode == Write && table.nrows != row_number ) { /* Just an error check, should never get here in writing */ fprintf(stderr,"\nindex_length: error trying to access row %d", (int)row_number ) ; len = (ossim_int32)0 ; } break; } return len; } /************************************************************************* * *N index_pos * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the position of a specified row from the table * index. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row_number == (ossim_int32) row number in the table. * table == (vpf_table_type) VPF table structure. * return == (ossim_int32) position of the table row * or zero on error. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 Original Version DOS Turbo C * Dave Flinn July 1991 Updated for UNIX * JTB 10/91 removed aborts() *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ ossim_int32 index_pos( ossim_int32 row_number, vpf_table_type table ) { ossim_int32 recsize; ossim_uint32 pos=0; STORAGE_BYTE_ORDER = table.byte_order; if (row_number < 1) row_number = 1; if (row_number > table.nrows) row_number = table.nrows; switch (table.xstorage) { case COMPUTE: pos = table.ddlen + ((row_number-1) * table.reclen); break; case DISK: recsize = sizeof(index_cell); fseek( table.xfp, (ossim_int32)(row_number*recsize), SEEK_SET ); if ( ! Read_Vpf_Int(&pos,table.xfp,1) ) { pos = (ossim_uint32)0 ; } break; case RAM: pos = table.index[row_number-1].pos; break; default: if ( table.mode == Write && table.nrows != row_number ) { /* Just an error check, should never get here in writing */ fprintf(stderr,"\nindex_length: error trying to access row %d", (int)row_number ) ; pos = (ossim_uint32)0; } break; } return pos; } #if 0 /* Compute the offset from the start of the row to the given field */ static ossim_int32 row_offset( int field, row_type row, vpf_table_type table) { ossim_int32 offset,n,size; int i; id_triplet_type key; int keysize[] = {0,sizeof(char),sizeof(short int),sizeof(ossim_int32)}; if (field < 0 || field >= table.nfields) return -1; offset = 0L; for (i=0;i == (vpf_table_type) VPF table. * read_key == (id_triplet_type) id triplet key. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 Original Version DOS Turbo C * Dave Flinn July 1991 Updated for UNIX *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ id_triplet_type read_key( vpf_table_type table ) { id_triplet_type key; unsigned char ucval; unsigned short int uival; STORAGE_BYTE_ORDER = table.byte_order; key.id = 0L; key.tile = 0L; key.exid = 0L; /* just doing this to be consistent */ Read_Vpf_Char (&(key.type),table.fp,1); switch (TYPE0(key.type)) { case 0: break; case 1: Read_Vpf_Char (&ucval, table.fp, 1 ) ; key.id = (ossim_int32)ucval; break; case 2: Read_Vpf_Short (&uival, table.fp, 1 ) ; key.id = (ossim_int32)uival; break; case 3: Read_Vpf_Int (&(key.id), table.fp, 1 ) ; break; } switch (TYPE1(key.type)) { case 0: break; case 1: Read_Vpf_Char (&ucval, table.fp, 1 ) ; key.tile = (ossim_int32)ucval; break; case 2: Read_Vpf_Short (&uival, table.fp, 1 ) ; key.tile = (ossim_int32)uival; break; case 3: Read_Vpf_Int (&(key.tile), table.fp, 1 ) ; break; } switch (TYPE2(key.type)) { case 0: break; case 1: Read_Vpf_Char (&ucval, table.fp, 1 ) ; key.exid = (ossim_int32)ucval; break; case 2: Read_Vpf_Short (&uival, table.fp, 1 ) ; key.exid = (ossim_int32)uival; break; case 3: Read_Vpf_Int (&(key.exid), table.fp, 1 ) ; break; } return key; } /************************************************************************* * *N read_next_row * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads the next row of the table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * table == (vpf_table_type) vpf table structure. * return == (row_type) the next row in the table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 Original Version DOS Turbo C * Dave Flinn July 1991 Updated for UNIX *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void *vpfmalloc() *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ row_type read_next_row( vpf_table_type table ) { register ossim_int32 i,j; ossim_int32 status; char *tptr; ossim_int32 size,count; row_type row; id_triplet_type * keys; coordinate_type dummycoord; if (feof(table.fp)) { return NULL; } STORAGE_BYTE_ORDER = table.byte_order; row = (row_type)vpfmalloc((table.nfields+1) * sizeof(column_type)); for (i=0;i>> read_next_row: no such type < %c >", table.path,table.name,table.header[i].type ) ; status = 1; break ; } /* end of switch */ if (status == 1) { free_row ( row, table ) ; return (row_type) NULL; } } return row; } /************************************************************************* * *N rowcpy * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns a copy of the specified row. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * origrow == (row_type) row to copy. * table == (vpf_table_type) vpf table structure. * return == (row_type) copy of the row. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void *vpfmalloc() VPFMISC.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ row_type rowcpy( row_type origrow, vpf_table_type table ) { register ossim_int32 i; ossim_int32 count; ossim_int32 size; row_type row; row = (row_type)vpfmalloc(table.nfields * sizeof(column_type)); for (i=0;i", table.header[i].type ) ; abort () ; break ; } /* end of switch */ } /* end of table.nfields */ return row; } /************************************************************************* * *N read_row * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads a specified row from the table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row_number == (ossim_int32) row number. * table == (vpf_table_type) vpf table structure. * return == (row_type) row that was read in. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * ossim_int32 index_pos() VPFTABLE.C * row_type read_next_row() VPFTABLE.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ row_type read_row( ossim_int32 row_number, vpf_table_type table ) { ossim_int32 fpos; fpos = index_pos(row_number,table); fseek(table.fp,fpos,SEEK_SET); return read_next_row(table); } /************************************************************************* * *N free_row * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function frees the memory that was dynamically allocated for the * specified row. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row == (row_type) row to be freed. * table == (vpf_table_type) vpf table structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ void free_row( row_type row, vpf_table_type table) { register ossim_int32 i; if (!row) return; for (i=0;i == (ossim_int32) row number in range [1 .. table.nrows]. * table == (vpf_table_type) vpf table structure. * return == (row_type) returned row. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * row_type rowcpy VPFREAD.C * row_type read_row VPFREAD.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ row_type get_row( ossim_int32 row_number, vpf_table_type table ) { row_type row; row_number = max(min(row_number, table.nrows), 1); if (table.storage == RAM) { row = rowcpy(table.row[row_number-1],table); return row; } else { return read_row( row_number, table ); } } /************************************************************************* * *N table_pos * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the column offset of the specified field name *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * field_name == (char *) field name. * table == (vpf_table_type) VPF table structure. * table_pos == (ossim_int32) returned column number. * UNIX returns -1 if not exists *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ ossim_int32 table_pos( const char* field_name, vpf_table_type table ) { register ossim_int32 i; ossim_int32 col; char altfn[256]; col = -1; for (i = 0; i < table.nfields; i++) { strcpy(altfn, ",:"); strcat(altfn, field_name); if (ossim_strcasecmp(field_name,table.header[i].name) == 0 || ossim_strcasecmp(altfn,table.header[i].name) == 0) { col = i; break; } } return col; } /************************************************************************* * *N get_table_element * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the element in the given row in the given * column. If the element is a single element (count=1), the value * is passed back via the void pointer *value; otherwise, an array * is allocated and passed back as the return value. * NOTE: If an array is allocated in this function, it should be freed * when no longer needed. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * field_number == (ossim_int32) field column number. * row == (row_type) vpf table row. * table == (vpf_table_type) VPF table structure. * value == (void *) pointer to a single element value. * count == (ossim_int32 *) pointer to the array size for a * multiple element value. * return == (void *) returned multiple element value. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void *vpfmalloc() *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ void *get_table_element( ossim_int32 field_number, row_type row, vpf_table_type table, void *value, ossim_int32 *count ) { ossim_int32 col; char * tptr; void * retvalue; retvalue = NULL; col = field_number; if ((col < 0) || (col >= table.nfields)) { fprintf(stderr,"%s: Invalid field number %d\n", table.name,(int)field_number); return NULL; } if (!row) return NULL; switch (table.header[col].type) { case 'X': retvalue = NULL; break; case 'T': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(char)); } else { retvalue = (char *)vpfmalloc((row[col].count+1)*sizeof(char)); tptr = (char *)vpfmalloc((row[col].count+1)*sizeof(char)); memcpy(tptr,row[col].ptr,row[col].count*sizeof(char)); tptr[row[col].count] = '\0'; strcpy((char *)retvalue,tptr); free(tptr); } break; case 'I': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(ossim_int32)); } else { retvalue = (ossim_int32 *)vpfmalloc(row[col].count* sizeof(ossim_int32)); memcpy(retvalue,row[col].ptr,row[col].count*sizeof(ossim_int32)); } break; case 'S': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(short int)); } else { retvalue = (short int *)vpfmalloc(row[col].count* sizeof(short int)); memcpy(retvalue,row[col].ptr,row[col].count*sizeof(short int)); } break; case 'F': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(float)); } else { retvalue = (float *)vpfmalloc(row[col].count*sizeof(float)); memcpy(retvalue,row[col].ptr,row[col].count*sizeof(float)); } break; case 'R': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(double)); } else { retvalue = (double *)vpfmalloc(row[col].count*sizeof(double)); memcpy(retvalue,row[col].ptr,row[col].count*sizeof(double)); } break; case 'C': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(coordinate_type)); } else { if (row[col].ptr) { retvalue = (coordinate_type *)malloc(row[col].count* sizeof(coordinate_type)); if (retvalue) memcpy(retvalue,row[col].ptr,row[col].count* sizeof(coordinate_type)); } else { retvalue = NULL; } } break; case 'Z': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(tri_coordinate_type)); } else { retvalue = (tri_coordinate_type *)vpfmalloc(row[col].count* sizeof(tri_coordinate_type)); memcpy(retvalue,row[col].ptr,row[col].count* sizeof(tri_coordinate_type)); } break; case 'B': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(double_coordinate_type)); } else { retvalue = (double_coordinate_type *)vpfmalloc(row[col].count* sizeof(double_coordinate_type)); memcpy(retvalue,row[col].ptr,row[col].count* sizeof(double_coordinate_type)); } break; case 'Y': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(double_tri_coordinate_type)); } else { retvalue = (double_tri_coordinate_type *)vpfmalloc(row[col].count* sizeof(double_tri_coordinate_type)); memcpy(retvalue,row[col].ptr,row[col].count* sizeof(double_tri_coordinate_type)); } break ; case 'D': if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(date_type)); } else { retvalue = (date_type *)vpfmalloc(row[col].count* sizeof(date_type)); memcpy(retvalue,row[col].ptr,row[col].count* sizeof(date_type)); } break; case 'K': /* ID Triplet */ if (table.header[col].count == 1) { memcpy(value,row[col].ptr,sizeof(id_triplet_type)); } else { retvalue = (id_triplet_type *)vpfmalloc(row[col].count* sizeof(id_triplet_type)); memcpy(retvalue,row[col].ptr,row[col].count* sizeof(id_triplet_type)); } break; } *count = row[col].count; return retvalue; } /************************************************************************* * *N named_table_element * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the element in the specified row in the column * matching the given field name. If the element is a single element * (count=1), the value is passed back via the void pointer *value; * otherwise, an array is allocated and passed back as the return value. * NOTE: If an array is allocated in this function, it should be freed * when no longer needed. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * field_name == (char *) field name. * row_number == (ossim_int32) row_number. * table == (vpf_table_type) VPF table structure. * value == (void *) pointer to a single element value. * count == (ossim_int32 *) pointer to the array size for a multiple * element value. * return == (void *) returned multiple element value. * or NULL if field_name could not be found * as a column *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void *vpfmalloc() VPFREAD.C * row_type get_row() VPFREAD.C * void free_row() VPFREAD.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ void *named_table_element( char * field_name, ossim_int32 row_number, vpf_table_type table, void * value, ossim_int32 * count ) { ossim_int32 col; row_type row; void * retvalue; col = table_pos(field_name, table); if (col < 0) { fprintf(stderr,"%s: Invalid field name <%s>\n",table.name,field_name); return NULL; } row = get_row(row_number,table); retvalue = get_table_element( col, row, table, value, count ); free_row(row, table); return retvalue; } /************************************************************************* * *N table_element * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function returns the element in the specified row in the column * matching the given field number. If the element is a single element * (count=1), the value is passed back via the void pointer *value; * otherwise, an array is allocated and passed back as the return value. * NOTE: If an array is allocated in this function, it should be freed * when no longer needed. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * field_number == (ossim_int32) field number (offset from * first field in table). * row_number == (ossim_int32) row_number. * table == (vpf_table_type) VPF table structure. * value == (void *) pointer to a single element value. * count == (ossim_int32 *) pointer to the array size for a multiple * element value. * return == (void *) returned multiple element value or * NULL of the field number is invalid *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * row_type get_row() VPFREAD.C * void free_row() VPFREAD.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ void *table_element( ossim_int32 field_number, ossim_int32 row_number, vpf_table_type table, void * value, ossim_int32 * count ) { row_type row; void * retvalue; row = get_row(row_number, table); retvalue = get_table_element(field_number, row, table, value, count); free_row(row,table); return retvalue; } ossim-Miami-2.9.1/src/vpfutil/vpfrelat.c000066400000000000000000000604221352751253100201660ustar00rootroot00000000000000/*************************************************************************** * *N Module VPFRELAT.C * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions supporting relates between VPF * feature classes and primitives (and vice versa). It relies * upon the information provided by the Feature Class Schema table. * This table is used to generate a feature class relationship (fcrel) * data structure for a feature class. This structure contains all * of the tables and their primary and foreign keys for the * relationships between a feature table and its primitive, or * from a primitive to its feature table (each relate chain is one way). * This module tries to be as much of a black box as it can to * enable a programmer to simply return the corresponding primitive * row of a feature record, or the corresponding feature row of a * primitive record. * * This is one of the most difficult modules required to support * a truly 'generic' VPF application, since VPF allows so many * variations of feature-primitive relationships. The final version * of this module must support every allowed relationship. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels * * Added one-to-many relates 3/2/92 - BJM *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E **************************************************************************/ #include #include #ifdef __MSDOS__ #include #include #else #ifdef __APPLE__ #include #include #else #if !defined(__OpenBSD__) && !defined( __FreeBSD__) #include #include #endif #endif #endif #if defined(__CYGWIN__)||defined(__APPLE__)|| defined(_WIN32) #include #else #include #endif #include #include #include #include #include #include /* Determine if the given table name is in the given list of */ /* vpf relate structures. */ static int table_in_list( char *tablename, linked_list_type rlist ) { position_type p; vpf_relate_struct rcell; p = ll_first(rlist); while (!ll_end(p)) { ll_element(p,&rcell); if (strcmp(rcell.table1,tablename)==0) return 1; p = ll_next(p); } return 0; } /************************************************************************** * *N fcs_relate_list * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Read the feature class schema table and create the list of * tables to chain through. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * fcname == (char *) feature class name. * start_table == (char *) table to start from. * end_table == (char *) table to end with. * fcs == (vpf_table_type) feature class schema table. * fcs_relate_list == (linked_list_type) list of tables to * chain through. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ linked_list_type fcs_relate_list( char *fcname, char *start_table, char *end_table, vpf_table_type fcs ) { linked_list_type rlist; vpf_relate_struct rstruct; set_type fcset, set1, set2; char tablename[255], *buf, expr[255]; row_type row; ossim_int32 rownum,n; int TABLE1_, KEY1_, TABLE2_, KEY2_; rlist = ll_init(); sprintf(expr,"FEATURE_CLASS = %s",fcname); fcset = query_table(expr,fcs); if (set_empty(fcset)) { set_nuke(&fcset); return rlist; } TABLE1_ = table_pos("TABLE1",fcs); KEY1_ = table_pos("FOREIGN_KEY",fcs); if (KEY1_ < 0) KEY1_ = table_pos("TABLE1_KEY",fcs); TABLE2_ = table_pos("TABLE2",fcs); KEY2_ = table_pos("PRIMARY_KEY",fcs); if (KEY2_ < 0) KEY2_ = table_pos("TABLE2_KEY",fcs); strcpy( tablename, start_table ); while (1) { sprintf(expr,"TABLE1 = %s",tablename); set1 = query_table(expr,fcs); set2 = set_intersection(set1,fcset); set_nuke(&set1); if (set_empty(set2)) { set_nuke(&fcset); set_nuke(&set2); return rlist; } rownum = set_min(set2); set_nuke(&set2); row = get_row(rownum,fcs); buf = (char *)get_table_element(TABLE1_,row,fcs,NULL,&n); strcpy(rstruct.table1,buf); rightjust(rstruct.table1); free(buf); buf = (char *)get_table_element(KEY1_,row,fcs,NULL,&n); strcpy(rstruct.key1,buf); rightjust(rstruct.key1); free(buf); buf = (char *)get_table_element(TABLE2_,row,fcs,NULL,&n); strcpy(rstruct.table2,buf); rightjust(rstruct.table2); free(buf); buf = (char *)get_table_element(KEY2_,row,fcs,NULL,&n); strcpy(rstruct.key2,buf); rightjust(rstruct.key2); free(buf); rstruct.degree = R_ONE; /* Default */ free_row( row, fcs ); if (table_in_list(rstruct.table1, rlist)) break; ll_insert( &rstruct, sizeof(rstruct), ll_last(rlist) ); strcpy( tablename, rstruct.table2 ); if (ossim_strcasecmp(tablename,end_table)==0) break; } set_nuke(&fcset); return rlist; } /************************************************************************** * *N vpf_binary_search * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function performs a binary search on a VPF table for the * specified integer value. Only VPF data type 'I' is supported. * The table must be sorted on the specified field, or this function * will give unpredictable results. The table must have been * successfully opened. If more than one row matches the search * value, only the first encountered will be returned. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * srchval == (ossim_int32) specified search value. * field == (int) table sort field. * table == (vpf_table_type) VPF table. * vpf_binary_search == (ossim_int32) first matching row. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ ossim_int32 vpf_binary_search( ossim_int32 srchval, int field, vpf_table_type table ) { ossim_int32 left,right, ival, rowid, n; row_type row; left = 1; right = table.nrows; do { rowid = (left+right)/2; row = get_row(rowid,table); get_table_element(field,row,table,&ival,&n); free_row(row,table); if (ival < srchval) right = rowid-1; else left = rowid+1; } while ((srchval != ival) && (left <= right)); if (srchval != ival) rowid = 0; return rowid; } /************************************************************************** * *N related_row * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Return the related row of table2 based upon the value of table 1's key * Table 2 must be the '1' side of an n:1 relationship -- If it isn't, * use 'related_rows()'. * Supported data types - I and T. * Binary search supported only for data type I. (column must be sorted) *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ ossim_int32 related_row( void *keyval1, vpf_table_type table2, char *key2, int sort_flag ) { ossim_int32 rowid, i, ival, kval, n; row_type row; int KEY2_; char cval, *tval; if (ossim_strcasecmp(key2,"ID")==0) { memcpy( &rowid, keyval1, sizeof(rowid) ); return rowid; } rowid = 0; KEY2_ = table_pos(key2,table2); if ((table2.header[KEY2_].type != 'I')&& (table2.header[KEY2_].type != 'T')) return rowid; if ((table2.header[KEY2_].type == 'I')&& (table2.header[KEY2_].count != 1)) return rowid; if ((table2.header[KEY2_].type == 'T')&&(sort_flag)) sort_flag = 0; if (table2.header[KEY2_].type == 'I') memcpy(&kval,keyval1,sizeof(kval)); if (!sort_flag) { /* Sequential search */ for (i=1;i<=table2.nrows;i++) { row = get_row(i,table2); if (table2.header[KEY2_].type == 'I') { get_table_element(KEY2_,row,table2,&ival,&n); if (ival == kval) rowid = i; } else { if (table2.header[KEY2_].count==1) { get_table_element(KEY2_,row,table2,&cval,&n); if (memcmp(&cval,keyval1,sizeof(ival))==0) rowid = i; } else { tval = (char*)get_table_element(KEY2_,row,table2,NULL,&n); if (strcmp(tval,(char *)keyval1)==0) rowid = i; } } free_row(row,table2); if (rowid > 0) break; } } else { /* Binary search */ memcpy(&kval,keyval1,sizeof(kval)); rowid = vpf_binary_search( kval, KEY2_, table2 ); } return rowid; } /************************************************************************** * *N related_rows * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Return the list of related rows of table2 based upon the value of * table 1's key. * Supported data types - I and T. * Binary search supported only for data type I. (column must be sorted) * Thematic index used, if present on key column. * NOTE: A sequential search operation will search the entire * table ...zzz... *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ linked_list_type related_rows( void *keyval1, vpf_table_type table2, char *key2, int sort_flag, ThematicIndex *idx ) { linked_list_type rowlist; set_type rowset; ossim_int32 rowid, i, ival, kval, n, start,end; row_type row = 0; int KEY2_; char cval, *tval; rowlist = ll_init(); if (ossim_strcasecmp(key2,"ID")==0) { memcpy( &rowid, keyval1, sizeof(rowid) ); ll_insert(&rowid,sizeof(rowid),rowlist); return rowlist; } KEY2_ = table_pos(key2,table2); if ((table2.header[KEY2_].type != 'I')&& (table2.header[KEY2_].type != 'T')) return rowlist; if ((table2.header[KEY2_].type == 'I')&& (table2.header[KEY2_].count != 1)) return rowlist; if ((table2.header[KEY2_].type == 'T')&&(sort_flag)) sort_flag = 0; if (idx) { if (idx->fp) { rowset = search_thematic_index(idx,(char *)keyval1); start = set_min(rowset); end = set_max(rowset); for (i=start;i<=end;i++) if (set_member(i,rowset)) { ll_insert(&i,sizeof(i),ll_last(rowlist)); } set_nuke(&rowset); return rowlist; } } if (!sort_flag) { /* Sequential search */ for (i=1;i<=table2.nrows;i++) { row = get_row(i,table2); if (table2.header[KEY2_].type == 'I') { get_table_element(KEY2_,row,table2,&ival,&n); if (memcmp(&ival,keyval1,sizeof(ival))==0) ll_insert(&i,sizeof(i),ll_last(rowlist)); } else { if (table2.header[KEY2_].count==1) { get_table_element(KEY2_,row,table2,&cval,&n); if (memcmp(&cval,keyval1,sizeof(ival))==0) ll_insert(&i,sizeof(i),ll_last(rowlist)); } else { tval = (char*)get_table_element(KEY2_,row,table2,NULL,&n); if (strcmp(tval,(char *)keyval1)==0) ll_insert(&i,sizeof(i),ll_last(rowlist)); } } free_row(row,table2); } } else { /* Binary search */ memcpy(&kval,keyval1,sizeof(kval)); rowid = vpf_binary_search( kval, KEY2_, table2 ); if (rowid > 0) { ll_insert(&rowid,sizeof(rowid),ll_last(rowlist)); i = rowid-1L; do { row = get_row(i,table2); get_table_element(KEY2_,row,table2,&ival,&n); if (ival == kval) ll_insert(&i,sizeof(i),ll_last(rowlist)); i--; free_row(row, table2); } while ((ival==kval)&&(i>0)); i = rowid+1L; do { row = get_row(i,table2); get_table_element(KEY2_,row,table2,&ival,&n); if (ival == kval) ll_insert(&i,sizeof(i),ll_last(rowlist)); i++; free_row(row, table2); } while ((ival==kval)&&(i<=table2.nrows)); } } return rowlist; } /************************************************************************** * *N vpf_nullify_table * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Nullify the given VPF table structure. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ void vpf_nullify_table( vpf_table_type *table ) { strcpy(table->name,""); table->path = NULL; table->nfields = 0; strcpy(table->description,""); strcpy(table->narrative,""); table->header = NULL; table->xfp = NULL; table->index = NULL; table->xstorage = (storage_type)0; table->fp = NULL; table->nrows = 0; table->row = NULL; table->reclen = 0; table->ddlen = 0; table->defstr = NULL; table->storage = (storage_type)0; table->mode = (file_mode)0; table->status = CLOSED; } /************************************************************************** * *N select_feature_class_relate * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Set up the relationships between features and primitives or between * primitives and features (one way only) for a specified feature class. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ fcrel_type select_feature_class_relate( int fcnum, library_type *library, char *start_table, char *end_table ) { int storage, cov; vpf_table_type fcs; ossim_int32 i; char path[255], covpath[255]; position_type p; vpf_relate_struct rcell; fcrel_type fcrel; fcrel.nchain = 0; fcrel.table = NULL; fcrel.relate_list = NULL; cov = library->fc[fcnum].coverage; strcpy(covpath,library->cover[cov].path); rightjust(covpath); sprintf( path, "%sfcs", covpath ); /* Feature Class Schema table */ fcs = vpf_open_table( path, disk, "rb", NULL ); fcrel.relate_list = fcs_relate_list( library->fc[fcnum].name, start_table,end_table, fcs ); if (ll_empty(fcrel.relate_list)) { ll_reset(fcrel.relate_list); displaymessage("ERROR in feature class relationship!", start_table,end_table,NULL); return fcrel; } /* Find the number of tables in the relate chain */ p = ll_first(fcrel.relate_list); fcrel.nchain = 0; while (!ll_end(p)) { fcrel.nchain++; p = ll_next(p); } /* Allow for last table2 */ fcrel.nchain++; fcrel.table = (vpf_table_type *) vpfmalloc((fcrel.nchain+1)* sizeof(vpf_table_type)); for (i=0;i 0) ll_insert(&keyval,sizeof(keyval),ll_last(keylist)); prow = ll_next(prow); free_row(relrow,fcrel.table[n]); } ll_reset(rowlist); } rowlist = ll_init(); p = ll_first(keylist); while (!ll_end(p)) { ll_element(p,&keyval); templist = related_rows(&keyval,fcrel.table[n],rcell.key2,0,idx); prow = ll_first(templist); while (!ll_end(prow)) { ll_element(prow,&rownum); if (!ll_locate(&rownum,rowlist)) ll_insert(&rownum,sizeof(rownum),ll_last(rowlist)); prow = ll_next(prow); } ll_reset(templist); p = ll_next(p); } ll_reset(keylist); return rowlist; } /************************************************************************** * *N deselect_feature_class_relate * *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Clear out a previously allocated feature class relate structure * from memory. *E *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels DOS Turbo C *E *************************************************************************/ void deselect_feature_class_relate( fcrel_type *fcrel ) { register int i; if (fcrel->nchain > 0) { for (i=0;inchain;i++) { if (fcrel->table[i].status == OPENED) { vpf_close_table(&(fcrel->table[i])); } } free(fcrel->table); ll_reset(fcrel->relate_list); } fcrel->nchain = 0; } ossim-Miami-2.9.1/src/vpfutil/vpfselec.c000066400000000000000000001112601352751253100201470ustar00rootroot00000000000000/************************************************************************* * *N Module VPFSELEC - VPF SELECTED FEATURES * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions for selecting VPF features and * primitives. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Nov 1991 DOS Turbo C * Feb 1992 - Optimized for CD-ROM performance. *E *************************************************************************/ #ifdef __MSDOS__ #include #include #else #ifdef __APPLE__ #include #include #else #if !defined(__OpenBSD__) && !defined( __FreeBSD__) #include #include #endif #endif #endif #ifdef __MSDOS__ #include #endif #include #include #include #ifdef __MSDOS__ #include #include #else #include #include #endif #include #include #include #include #include #include #include #include extern char home[255]; /* Defined in VPFSPX.C */ set_type spatial_index_search( char *fname, float x1, float y1, float x2, float y2 ); #ifdef __MSDOS__ /************************************************************************* * *N read_selected_features * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads a saved selection set for a given theme of the * specified view. * * NOTE: This function has "special knowledge" about the structure of * a set. If that structure is changed, this function must account * for those changes. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * view ==(view_type *) view structure. * themenum ==(int) theme number. * return ==(set_type) set of selected features. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ set_type read_selected_features( view_type *view, int themenum ) { set_type selset; char path[255], *num = " ", byte; FILE *fp; register int i; /* Determine path name from theme number */ strcpy(path,home); strcat(path,view->name); strcat(path,"\\sel"); num = itoa(themenum,num,10); for (i=0;i<(4-strlen(num));i++) strcat(path,"0"); strcat(path,num); if (access(path,0) != 0) { selset.size = 0; selset.buf = NULL; return selset; } /* Read the set */ if ((fp = fopen(path,"rb")) == NULL) { selset.size = 0; selset.buf = NULL; return selset; } fread( &selset.size, sizeof(ossim_int32), 1, fp ); selset.buf = (char *)malloc( ((selset.size/8L)+1L) * sizeof(char) ); if (selset.buf) { fread( selset.buf, sizeof(char), (selset.size/8L)+1L, fp ); selset.diskstorage = 0; } else { selset.diskstorage = 1; /* Can speed this up by buffering */ selset.fp = tmpfile(); if (!selset.fp) { selset.diskstorage=0; selset.size=0; selset.buf=NULL; return selset; } fread(&byte,1,1,selset.fp); while (!feof(fp)) { fwrite(&byte,1,1,selset.fp); fread(&byte,1,1,fp); } } fclose(fp); return selset; } /************************************************************************* * *N save_selected_features * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function saves the selection set for a given theme of the * specified view to a file in the view directory. * * NOTE: This function has "special knowledge" about the structure of * a set. If that structure is changed, this function must account * for those changes. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * view ==(view_type *) view structure. * themenum ==(int) theme number. * selset ==(set_type) set of selected features. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void save_selected_features( view_type *view, int themenum, set_type selset ) { char path[80], *num=" ", byte; FILE *fp; register int i; /* Determine the path name from the theme number */ strcpy(path,home); strcat(path,view->name); strcat(path,"\\sel"); num = itoa(themenum,num,10); for (i=0;i<(4-strlen(num));i++) strcat(path,"0"); strcat(path,num); /* Write the set */ fp = fopen(path,"wb"); if (!fp) return; fwrite( &(selset.size), sizeof(ossim_int32), 1, fp ); if (!selset.diskstorage) { fwrite( selset.buf, sizeof(char), (selset.size/8L)+1L, fp ); } else { rewind(selset.fp); fread(&byte,1,1,selset.fp); while (!feof(selset.fp)) { fwrite(&byte,1,1,fp); fread(&byte,1,1,selset.fp); } } fclose(fp); } /************************************************************************* * *N get_selected_features * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function gets the selection set for a given theme of the * specified view, either by querying the table, or by reading a * previously saved selection set file. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * view ==(view_type *) view structure. * themenum ==(int) theme number. * library ==(library-type) VPF library structure. * return ==(set_type) set of selected features. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ set_type get_selected_features( view_type *view, int themenum, library_type library ) { set_type selset; vpf_table_type ft; register int i; /* Read a selection set, if present */ if (strcmp(view->name,"") != 0) { selset = read_selected_features( view, themenum ); if (selset.size > 0) return selset; } /* No selection set... */ /* Find the feature class for the theme */ for (i=0;itheme[themenum].fc)==0) break; if (i>=library.nfc) { display_message("Invalid theme in view"); return selset; } /* Query the feature table */ ft = vpf_open_table( library.fc[i].table, disk, "rb", NULL ); selset = query_table( view->theme[themenum].expression, ft ); vpf_close_table( &ft ); /* Save the selection set so we don't have to query again */ if (strcmp(view->name,"") != 0) { save_selected_features( view, themenum, selset ); } return selset; } /************************************************************************* * *N bounding_select * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function reads the bounding rectangle table to weed out the * local primitives. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * path == (char *) path to the bounding rectangle table. * mapextent == (extent_type) map extent to compare. * dec_degrees == (int) flag to indicate if data is in decimal * degrees. * bounding_select == (set_type) set of bounding rectangle ids. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ set_type bounding_select( char *path, extent_type mapextent, int dec_degrees ) { vpf_table_type table; set_type set; ossim_int32 i, count; extent_type box, pextent; double x1,y1,x2,y2; row_type row; int XMIN_,YMIN_,XMAX_,YMAX_; /* Project all extents to plate-carree for cartesian comparisons */ /* (decimal degree coordinate systems) */ x1 = mapextent.x1; y1 = mapextent.y1; x2 = mapextent.x2; y2 = mapextent.y2; if (dec_degrees) { set_plate_carree_parameters( central_meridian(x1,x2), 0.0, 1.0 ); pcarree_xy(&x1,&y1); pcarree_xy(&x2,&y2); } pextent.x1 = x1; pextent.y1 = y1; pextent.x2 = x2; pextent.y2 = y2; table = vpf_open_table(path,disk,"rb",NULL); XMIN_ = table_pos("XMIN",table); YMIN_ = table_pos("YMIN",table); XMAX_ = table_pos("XMAX",table); YMAX_ = table_pos("YMAX",table); set = set_init(table.nrows+1); for (i=1;i<=table.nrows;i++) { row = read_next_row(table); get_table_element(XMIN_,row,table,&box.x1,&count); get_table_element(YMIN_,row,table,&box.y1,&count); get_table_element(XMAX_,row,table,&box.x2,&count); get_table_element(YMAX_,row,table,&box.y2,&count); free_row(row,table); x1 = box.x1; y1 = box.y1; x2 = box.x2; y2 = box.y2; if (dec_degrees) { pcarree_xy(&x1,&y1); pcarree_xy(&x2,&y2); } box.x1 = x1; box.y1 = y1; box.x2 = x2; box.y2 = y2; if ( contained(box,pextent) || contained(pextent,box) ) { set_insert(i,set); } } vpf_close_table(&table); return set; } /************************************************************************* * *N tile_thematic_index_name * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines the name of the tile thematic index for * the given table. If the table does not have a "TILE_ID" field, * the name is set to null. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * table ==(vpf_table_type) opened VPF table. * path ==(char *) name of the thematic index file. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ void tile_thematic_index_name( vpf_table_type table, char *path ) { int i; i = table_pos("TILE_ID",table); if (i<0) { strcpy(path,""); } else { /* Thematic index name from the table header */ sprintf(path,"%s%s",table.path,table.header[i].tdx); } } #endif /************************************************************************* * *N completely_within * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines whether extent1 is completely within * extent2. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * extent1 ==(extent_type) first extent to compare. * extent2 ==(extent_type) second extent to compare. * return ==(int) 1 if extent1 is completely within extent2, * 0 if not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ int completely_within( extent_type extent1, extent_type extent2 ) { if (extent1.x1 < extent2.x1) return 0; if (extent1.y1 < extent2.y1) return 0; if (extent1.x2 > extent2.x2) return 0; if (extent1.y2 > extent2.y2) return 0; return 1; } #ifdef __MSDOS__ /************************************************************************* * *N get_selected_primitives * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines all of the selected primitive rows from * the selected features. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * view == (view_type *) view structure. * themenum == (int) theme number. * library == (library_type *) VPF library structure. * mapenv == (map_environment_type *) map environment. * status == (int *) status of the function: * 1 if completed, 0 if user escape. * get_selected_primitives == (set_type *) array of sets, each position * representing the set of primitives for the * corresponding tile in the tileref.aft table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ set_type *get_selected_primitives( view_type *view, int themenum, library_type *library, map_environment_type *mapenv, int *status ) { int fcnum, finished, found, cov, tilecover, TILEPATH_, degree; int feature, prim; vpf_table_type tile_table; row_type row; char *ptable[] = {"","edg","fac","txt","end","cnd"}; char *spxname[] = {"","esi","fsi","tsi","nsi","csi"}; char *brname[] = {"","ebr","fbr","tbr","nbr","cbr"}; set_type feature_rows, primitive_rows, tile_features; set_type *primitives; ossim_int32 prim_rownum, count, tile; register ossim_int32 i,j, pclass, start,end; char path[255], covpath[255], tiledir[255], *buf, str[255]; fcrel_type fcrel; linked_list_type primlist; position_type p; vpf_relate_struct rcell; ThematicIndex idx; primitives = (set_type *)vpfmalloc((library->ntiles+1)*sizeof(set_type)); for (i=0;i<=library->ntiles;i++) { primitives[i].size = 0; primitives[i].buf = NULL; } fcnum = view->theme[themenum].fcnum; feature_rows = get_selected_features( view, themenum, *library ); /* Open the tile reference table, if present */ sprintf(path,"%stileref\\tileref.aft",library->path); if (access(path,0) != 0) { tilecover = FALSE; } else { tile_table = vpf_open_table(path,disk,"rb",NULL); TILEPATH_ = table_pos("TILE_NAME",tile_table); tilecover = TRUE; } for (pclass=EDGE;pclass<=CONNECTED_NODE;pclass++) { if ((pclass != library->fc[fcnum].primclass) && (library->fc[fcnum].primclass != COMPLEX_FEATURE)) continue; /* Set up the feature class table relate chain. */ /* The feature table is fcrel.table[0]. */ /* The primitive table is the last table in the chain: */ /* fcrel.table[ fcrel.nchain-1 ]. */ j = 0; for (i=0;ifc[fcnum].table);i++) if (library->fc[fcnum].table[i] == '\\') j = i+1; strcpy( str, &(library->fc[fcnum].table[j])); fcrel = select_feature_class_relate(fcnum, library, str, ptable[pclass]); feature = 0; prim = fcrel.nchain-1; p = ll_previous(ll_last(fcrel.relate_list),fcrel.relate_list); ll_element(p,&rcell); degree = rcell.degree; /*** 'Tile' number 1 is the universe polygon for the tileref cover ***/ for (tile = 2; tile <= library->ntiles; tile++ ) { if (!set_member(tile,library->tile_set)) continue; if (tilecover) { row = get_row(tile,tile_table); buf = (char *)get_table_element(TILEPATH_,row,tile_table, NULL,&count); free_row(row,tile_table); strcpy(tiledir,buf); rightjust(tiledir); strcat(tiledir,"\\"); free(buf); } else { strcpy(tiledir,""); } cov = library->fc[fcnum].coverage; strcpy( covpath, library->cover[cov].path ); finished = 1; found = 0; /* Open primitive table in tile */ sprintf(path,"%s%s%s",covpath,tiledir,ptable[pclass]); if (access(path,0) != 0) continue; found = 1; fcrel.table[prim] = vpf_open_table(path,disk,"rb",NULL); if (primitives[tile].size > 0) { printf("Oops! size = %ld\n",primitives[tile].size); exit(1); } primitives[tile] = set_init(fcrel.table[prim].nrows+1); /* Get the set of primitive rows within the map extent */ /* Look for spatial index file */ primitive_rows.size = 0; if (mapenv->projection == PLATE_CARREE && mapenv->mapextent.x1 < mapenv->mapextent.x2) { sprintf(path,"%s%s%s",covpath,tiledir,spxname[pclass]); if ((access(path,0)==0)&&(fcrel.table[prim].nrows > 20)) { primitive_rows = spatial_index_search(path, mapenv->mapextent.x1,mapenv->mapextent.y1, mapenv->mapextent.x2,mapenv->mapextent.y2); } else { /* Next best thing - bounding rectangle table */ sprintf(path,"%s%s%s",covpath,tiledir,brname[pclass]); if (access(path,0)==0) { primitive_rows = bounding_select(path,mapenv->mapextent, library->dec_degrees); } } } /* projection check */ if (primitive_rows.size == 0) { /* Search through all the primitives */ primitive_rows=set_init(fcrel.table[prim].nrows+1); set_on(primitive_rows); } tile_thematic_index_name(fcrel.table[feature], path); if ( (strcmp(path,"") != 0) && (access(path,4)==0) ) { /* Tile thematic index for feature table present, */ tile_features = read_thematic_index( path, (char *)&tile ); } else { tile_features = set_init(fcrel.table[feature].nrows+1); set_on(tile_features); } idx.fp = NULL; i = table_pos(rcell.key2,fcrel.table[prim]); if (i >= 0) { if (fcrel.table[prim].header[i].tdx) { sprintf(path,"%s%s",fcrel.table[prim].path, fcrel.table[prim].header[i].tdx); if (access(path,0)==0) idx = open_thematic_index(path); } if (fcrel.table[prim].header[i].keytype == 'U') degree = R_ONE; if (fcrel.table[prim].header[i].keytype == 'N') degree = R_MANY; if (fcrel.table[prim].header[i].keytype == 'P') degree = R_ONE; } finished = 1; start = set_min(tile_features); end = set_max(tile_features); fseek(fcrel.table[feature].fp, index_pos(start,fcrel.table[feature]), SEEK_SET); for (i=start;i<=end;i++) { row = read_next_row(fcrel.table[feature]); if (!set_member( i, feature_rows )) { free_row(row,fcrel.table[feature]); continue; } if (!set_member( i, tile_features )) { free_row(row,fcrel.table[feature]); continue; } if (degree == R_ONE) { prim_rownum = fc_row_number( row, fcrel, tile ); primlist = NULL; p = NULL; } else { primlist = fc_row_numbers( row, fcrel, tile, &idx ); } free_row( row, fcrel.table[feature] ); if (!primlist) { if ((prim_rownum<1)|| (prim_rownum>fcrel.table[prim].nrows)) continue; if (set_member( prim_rownum, primitive_rows )) { set_insert(prim_rownum,primitives[tile]); } } else { p = ll_first(primlist); while (!ll_end(p)) { ll_element(p,&prim_rownum); if ((prim_rownum<1)|| (prim_rownum>fcrel.table[prim].nrows)) continue; if (set_member( prim_rownum, primitive_rows )) { set_insert(prim_rownum,primitives[tile]); } p = ll_next(p); } } if (kbhit()) { if (getch()==27) { *status = 0; finished = 0; break; } } } if (idx.fp) close_thematic_index(&idx); vpf_close_table(&(fcrel.table[prim])); set_nuke(&primitive_rows); set_nuke(&tile_features); if (set_empty(primitives[tile])) { set_nuke(&primitives[tile]); primitives[tile].size = 0; primitives[tile].buf = NULL; } if (!finished) { *status = 0; break; } } if (!finished) { *status = 0; deselect_feature_class_relate( &fcrel ); break; } if (found) *status = 1; if (kbhit()) { if (getch()==27) { *status = 0; deselect_feature_class_relate( &fcrel ); break; } } deselect_feature_class_relate( &fcrel ); } set_nuke(&feature_rows); if (tilecover) { vpf_close_table(&tile_table); } return primitives; } /************************************************************************* * *N get_selected_tile_primitives * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function determines all of the selected primitive rows from * the selected features of a given tile. * * This function expects a feature class relationship structure that * has been successfully created with select_feature_class_relate() * from the feature table to the primitive. The primitive table in * the feature class relate structure must have been successfully * opened for the given tile. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * library ==(library_type *) VPF library structure. * fcnum ==(int) feature class number of the feature table. * fcrel ==(fcrel_type) feature class relate structure. * feature_rows ==(set_type) set of selected features. * mapenv ==(map_environment_type *) map environment. * tile ==(ossim_int32) tile number. * tiledir ==(char *) path to the tile directory. * status ==(int *) status of the function: * 1 if completed, 0 if user escape. * return ==(set_type) set of primitives for the features * in the corresponding tile. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *************************************************************************/ set_type get_selected_tile_primitives( library_type *library, int fcnum, fcrel_type fcrel, set_type feature_rows, map_environment_type *mapenv, ossim_int32 tile, char *tiledir, int *status ) { int cov, degree; int feature, prim; row_type row; char *spxname[] = {"","esi","fsi","tsi","nsi","csi"}; char *brname[] = {"","ebr","fbr","tbr","nbr","cbr"}; set_type primitive_rows, tile_features; set_type primitives; ossim_int32 prim_rownum; register ossim_int32 i,pclass, start,end; char path[255], covpath[255]; linked_list_type primlist; position_type p; vpf_relate_struct rcell; ThematicIndex idx; feature = 0; prim = fcrel.nchain-1; /* Assume that fcrel.table[prim] has been opened */ primitives.size = 0; primitives.buf = NULL; cov = library->fc[fcnum].coverage; strcpy( covpath, library->cover[cov].path ); p = ll_previous(ll_last(fcrel.relate_list),fcrel.relate_list); ll_element(p,&rcell); degree = rcell.degree; for (pclass=EDGE;pclass<=CONNECTED_NODE;pclass++) { if ((pclass != library->fc[fcnum].primclass) && (library->fc[fcnum].primclass != COMPLEX_FEATURE)) continue; primitives = set_init(fcrel.table[prim].nrows+1); /* Get the set of primitive rows within the map extent */ /* Look for the spatial index file to weed out primitives in the */ /* given tile but outside of the viewing area. If a projection */ /* other than plate-carree (rectangular) is on, or if the extent */ /* crosses the meridian, the quick check is no longer valid. */ primitive_rows.size = 0; if (mapenv->projection == PLATE_CARREE && mapenv->mapextent.x1 < mapenv->mapextent.x2) { sprintf(path,"%s%s%s",covpath,tiledir,spxname[pclass]); /* 20 (below) is a fairly arbitrary cutoff of the number of */ /* primitives that make a spatial index search worth while. */ if ((access(path,0)==0)&&(fcrel.table[prim].nrows > 20)) { primitive_rows = spatial_index_search(path, mapenv->mapextent.x1,mapenv->mapextent.y1, mapenv->mapextent.x2,mapenv->mapextent.y2); } else { /* Next best thing - bounding rectangle table */ sprintf(path,"%s%s%s",covpath,tiledir,brname[pclass]); if ((access(path,0)==0)&&(fcrel.table[prim].nrows > 20)) { primitive_rows = bounding_select(path,mapenv->mapextent, library->dec_degrees); } } } if (primitive_rows.size == 0) { /* Search through all the primitives */ primitive_rows=set_init(fcrel.table[prim].nrows+1); set_on(primitive_rows); } if (strcmp(tiledir,"") != 0) { tile_thematic_index_name(fcrel.table[feature], path); if ((strcmp(path,"")!=0) && (access(path,4)==0)) { /* Tile thematic index for feature table present, */ tile_features = read_thematic_index( path, (char *)&tile ); } else { tile_features = set_init(fcrel.table[feature].nrows+1); set_on(tile_features); } } else { tile_features = set_init(fcrel.table[feature].nrows+1); set_on(tile_features); } set_delete(0,tile_features); idx.fp = NULL; i = table_pos(rcell.key2,fcrel.table[prim]); if (i >= 0) { if (fcrel.table[prim].header[i].tdx) { sprintf(path,"%s%s",fcrel.table[prim].path, fcrel.table[prim].header[i].tdx); if (access(path,0)==0) idx = open_thematic_index(path); } if (fcrel.table[prim].header[i].keytype == 'U') degree = R_ONE; if (fcrel.table[prim].header[i].keytype == 'N') degree = R_MANY; if (fcrel.table[prim].header[i].keytype == 'P') degree = R_ONE; } start = set_min(tile_features); end = set_max(tile_features); /* It turns out to be MUCH faster off of a CD-ROM to */ /* read each row and discard unwanted ones than to */ /* forward seek past them. It's about the same off */ /* of a hard disk. */ fseek(fcrel.table[feature].fp,index_pos(start,fcrel.table[feature]), SEEK_SET); for (i=start;i<=end;i++) { row = read_next_row(fcrel.table[feature]); if (!set_member( i, feature_rows )) { free_row(row,fcrel.table[feature]); continue; } if (!set_member( i, tile_features )) { free_row(row,fcrel.table[feature]); continue; } if (degree == R_ONE) { prim_rownum = fc_row_number( row, fcrel, tile ); primlist = NULL; p = NULL; } else { primlist = fc_row_numbers( row, fcrel, tile, &idx ); } free_row( row, fcrel.table[feature] ); if (!primlist) { if ((prim_rownum<1)||(prim_rownum>fcrel.table[prim].nrows)) continue; if (set_member( prim_rownum, primitive_rows )) { set_insert(prim_rownum,primitives); } } else { p = ll_first(primlist); while (!ll_end(p)) { ll_element(p,&prim_rownum); if ((prim_rownum<1)|| (prim_rownum>fcrel.table[prim].nrows)) continue; if (set_member( prim_rownum, primitive_rows )) { set_insert(prim_rownum,primitives); } p = ll_next(p); } } if (primlist) ll_reset(primlist); if (kbhit()) { if (getch()==27) { *status = 0; break; } } } set_nuke(&primitive_rows); set_nuke(&tile_features); if (idx.fp) close_thematic_index(&idx); *status = 1; if (kbhit()) { if (getch()==27) { *status = 0; break; } } } return primitives; } #endif #if __MSDOS__ static ossim_int32 filesize( char *file ) { struct stat s; stat(file,&s); return (ossim_int32)s.st_size; } static ossim_int32 available_space( char *drive ) { struct dfree disktable; int disknum; if (!drive) return 0; disknum=toupper(drive[0])-'A'+1; getdfree(disknum,&disktable); return (ossim_int32) disktable.df_avail * (ossim_int32) disktable.df_sclus * (ossim_int32) disktable.df_bsec; } #endif #ifdef __MSDOS__ /************************************************************************* * *N draw_selected_features * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function draws the selected features from a specified feature * class based upon a query (either an expression or the pre-compiled * results of an expression). *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * view ==(view_type *) view structure. * themenum ==(int) theme number. * library ==(library_type *) VPF library structure. * mapenv ==(map_environment_type *) map environment structure. * return ==(int) completion status: * 1 if completed successfully, * 0 if an error occurred. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels August 1991 DOS Turbo C *E *************************************************************************/ int draw_selected_features( view_type *view, int themenum, library_type *library, map_environment_type *mapenv ) { int status, fcnum, finished, cov, tilecover, TILEPATH_, prim; int outline, color1, color2, color3, color4; vpf_table_type rngtable,edgtable,fbrtable, tile_table; row_type row; char *ptable[] = {"","edg","fac","txt","end","cnd"}; register ossim_int32 i, j, p, pclass, tile; int display_order[] = {FACE,EDGE,ENTITY_NODE,CONNECTED_NODE,TEXT}; register ossim_int32 starttile, endtile, startprim, endprim; ossim_int32 count; char path[255], covpath[255], tiledir[255], *buf, str[255]; char *drive, rngpath[255],edgpath[255],edxpath[255],fbrpath[255]; boolean rng_rdisk,edg_rdisk,fbr_rdisk; set_type primitives, feature_rows; fcrel_type fcrel; window_type info; struct viewporttype vp; getviewsettings(&vp); fcnum = view->theme[themenum].fcnum; sprintf(path,"%stileref\\tileref.aft",library->path); if (access(path,0) != 0) { tilecover = FALSE; } else { tile_table = vpf_open_table(path,disk,"rb",NULL); TILEPATH_ = table_pos("TILE_NAME",tile_table); tilecover = TRUE; } feature_rows = get_selected_features( view, themenum, *library ); for (p=0;p<5;p++) { pclass = display_order[p]; if ((pclass != library->fc[fcnum].primclass) && (library->fc[fcnum].primclass != COMPLEX_FEATURE)) continue; if ((library->fc[fcnum].primclass == COMPLEX_FEATURE) && (!library->fc[fcnum].cprim[pclass])) continue; /* Set up the feature class table relate chain. */ /* The feature table is fcrel.table[0]. */ /* The primitive table is the last table in the chain: */ /* fcrel.table[ fcrel.nchain-1 ]. */ j = 0; for (i=0;ifc[fcnum].table);i++) if (library->fc[fcnum].table[i] == '\\') j = i+1; strcpy( str, &(library->fc[fcnum].table[j])); fcrel = select_feature_class_relate(fcnum, library, str, ptable[pclass]); prim = fcrel.nchain-1; /*** 'Tile' number 1 is the universe polygon for the tileref cover ***/ starttile = set_min(library->tile_set); if (starttile < 2) starttile = 2; endtile = set_max(library->tile_set); if (endtile < 2) endtile = 2; for (tile = starttile; tile <= endtile; tile++ ) { if (!set_member(tile,library->tile_set)) continue; if (tilecover) { row = get_row(tile,tile_table); buf = (char *)get_table_element(TILEPATH_,row,tile_table, NULL,&count); free_row(row,tile_table); strcpy(tiledir,buf); rightjust(tiledir); strcat(tiledir,"\\"); free(buf); } else { strcpy(tiledir,""); } cov = library->fc[fcnum].coverage; strcpy( covpath, library->cover[cov].path ); finished = TRUE; sprintf(path,"%s%s%s",covpath,tiledir,ptable[pclass]); if (access(path,0) != 0) continue; fcrel.table[prim] = vpf_open_table(path,disk,"rb",NULL); info = info_window("Searching..."); primitives = get_selected_tile_primitives( library, fcnum, fcrel, feature_rows, mapenv, tile, tiledir, &status ); delete_window(&info); setviewport(vp.left,vp.top,vp.right,vp.bottom,vp.clip); /* Reset plate-carree parameters (changed in */ /* get_selected_tile_primitives() ) */ if (mapenv->projection == PLATE_CARREE) set_plate_carree_parameters( central_meridian( mapenv->mapextent.x1, mapenv->mapextent.x2), 0.0, 1.0 ); if (primitives.size < 1) { vpf_close_table(&fcrel.table[prim]); continue; } if (!status) { set_nuke(&primitives); vpf_close_table(&fcrel.table[prim]); break; } if (pclass == FACE) { /* Must also open RNG, EDG, and FBR for drawing faces. */ /* If a RAM disk is specified, copy these to it and open */ /* them there. */ rng_rdisk = FALSE; edg_rdisk = FALSE; fbr_rdisk = FALSE; drive = getenv("TMP"); buf = (char *)vpfmalloc(255); sprintf(path,"%s%srng",covpath,tiledir); strcpy(rngpath,path); if (drive && filesize(path) < available_space(drive)) { sprintf(rngpath,"%s\\RNG",drive); sprintf(buf,"COPY %s %s > NUL",path,rngpath); system(buf); rng_rdisk = TRUE; } rngtable = vpf_open_table(rngpath,disk,"rb",NULL); sprintf(path,"%s%sedg",covpath,tiledir); strcpy(edgpath,path); sprintf(edxpath,"%s%sedx",covpath,tiledir); if (drive && (filesize(path)+filesize(edxpath)) NUL",path,edgpath); system(buf); sprintf(edxpath,"%s\\EDX",drive); sprintf(buf,"COPY %s%sedx %s > NUL",covpath,tiledir,edxpath); system(buf); edg_rdisk = TRUE; } edgtable = vpf_open_table(edgpath,disk,"rb",NULL); sprintf(path,"%s%sfbr",covpath,tiledir); strcpy(fbrpath,path); if (drive && filesize(path) < available_space(drive)) { sprintf(fbrpath,"%s\\FBR",drive); sprintf(buf,"COPY %s %s > NUL",path,fbrpath); system(buf); fbr_rdisk = TRUE; } fbrtable = vpf_open_table(fbrpath,disk,"rb",NULL); free(buf); } finished = 1; startprim = set_min(primitives); endprim = set_max(primitives); /* It turns out to be MUCH faster off of a CD-ROM to */ /* read each row and discard unwanted ones than to */ /* forward seek past them. It's about the same off */ /* of a hard disk. */ fseek(fcrel.table[prim].fp, index_pos(startprim,fcrel.table[prim]), SEEK_SET); for (i=startprim;i<=endprim;i++) { row = read_next_row(fcrel.table[prim]); if (set_member( i, primitives )) { /* Draw the primitive */ switch (pclass) { case EDGE: finished = draw_edge_row(row,fcrel.table[prim]); break; case ENTITY_NODE: case CONNECTED_NODE: finished = draw_point_row(row,fcrel.table[prim]); break; case FACE: gpgetlinecolor( &outline ); gpgetpattern( &color1, &color2, &color3, &color4 ); hidemousecursor(); draw_face_row( row,fcrel.table[prim], rngtable, edgtable, fbrtable, outline, color1, color2, color3, color4 ); showmousecursor(); finished = 1; if (kbhit()) { if (getch()==27) finished = 0; } break; case TEXT: finished = draw_text_row(row,fcrel.table[prim]); break; } } free_row(row,fcrel.table[prim]); if (!finished) { status = 0; break; } } if (pclass == FACE) { vpf_close_table(&rngtable); if (rng_rdisk) remove(rngpath); vpf_close_table(&edgtable); if (edg_rdisk) { remove(edgpath); remove(edxpath); } vpf_close_table(&fbrtable); if (fbr_rdisk) remove(fbrpath); } vpf_close_table(&fcrel.table[prim]); set_nuke(&primitives); if (!finished) { status = 0; break; } } if (!finished) { status = 0; deselect_feature_class_relate( &fcrel ); break; } status = 1; if (kbhit()) { if (getch()==27) { status = 0; deselect_feature_class_relate( &fcrel ); break; } } deselect_feature_class_relate(&fcrel); } if (tilecover) { vpf_close_table(&tile_table); } set_nuke(&feature_rows); return status; } #endif ossim-Miami-2.9.1/src/vpfutil/vpfspx.c000066400000000000000000000242661352751253100176770ustar00rootroot00000000000000/************************************************************************* * *N Module VPFSPX.C * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions for reading the VPF spatial index * file. A VPF spatial index is a modified quad-tree index with a * cross-over bin for features spanning more than one spatial cell. * There is one interface function in this module - * spatial_index_search(). The spatial index creation function is * not included. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Mody Buchbinder Jul 1991 Original coding * Barry Michaels Aug 1991 Customized for VPFVIEW *E *************************************************************************/ #include #include #include #include #ifdef __MSDOS__ # include # include # include # include #else # include #endif #include #ifdef __MSDOS__ # include #endif #ifdef _MSC_VER # include #endif #ifndef _MSDOS__ #ifndef _WIN32 #include #endif #endif #include #include /******* cellmap definitions **/ #define START 0 #define NUMFEAT 1 #define OUT 0 #define IN 1 #define ID 1 #define BOUND 0 #define TOTAL_NUMBER 0 #define BOUND_START 1 #define CELLMAP_SIZE 5 #define XMIN 0 #define YMIN 1 #define XMAX 2 #define YMAX 3 typedef struct { int fd; /* File descriptor */ ossim_int32 maplen; /* Number of cells in the tree */ ossim_int32 cellmap[1023][2]; /* The tree of cells */ ossim_int32 buf[1023][2]; /* Buffer for one cell */ ossim_int32 shift; /* Size of data before real cell records */ unsigned char box[4]; /* Search box */ } spx_type; /************************************************************************* * *N is_over * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Determine if two boxes overlap. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * box1 ==(unsigned char[4]) first box to check. * box2 ==(unsigned char[4]) second box to check. * return ==(int) 1 if the boxes overlap, * 0 if the boxes do not. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Mody Buchbinder Jul 1991 *E *************************************************************************/ static int is_over( unsigned char box1[4], unsigned char box2[4] ) { int xmin,xmax,ymin,ymax; if(box2[XMIN] >= box1[XMIN] && box2[XMIN] <= box1[XMAX]) xmin = IN; else xmin = OUT; if(box2[XMAX] >= box1[XMIN] && box2[XMAX] <= box1[XMAX]) xmax = IN; else xmax = OUT; if(box2[YMIN] >= box1[YMIN] && box2[YMIN] <= box1[YMAX]) ymin = IN; else ymin = OUT; if(box2[YMAX] >= box1[YMIN] && box2[YMAX] <= box1[YMAX]) ymax = IN; else ymax = OUT; /* complete overlap */ if(xmin == OUT && xmax == OUT && box2[XMIN] <= box1[XMIN] && box2[XMAX] >= box1[XMAX]) xmin = IN; if(ymin == OUT && ymax == OUT && box2[YMIN] <= box1[YMIN] && box2[YMAX] >= box1[YMAX]) ymin = IN; if((xmin == IN || xmax == IN) && (ymin == IN || ymax == IN)) return 1; return 0; } /************************************************************************* * *N get_record * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Read spatial index record 'num'. Insert the record into the search * set if it falls within the search box. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * num ==(ossim_int32) record number. * spx ==(spx_type *) spatial index record structure. * set ==(set_type) search set to be updated. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Mody Buchbinder Jul 1991 *E *************************************************************************/ static void get_record(ossim_int32 num, spx_type *spx, set_type set ) { long offset; int j,index; unsigned char box[4]; index = num -1; offset = spx->cellmap[index][0] + spx->shift; lseek(spx->fd,offset,SEEK_SET); read(spx->fd,spx->buf,2*spx->cellmap[index][NUMFEAT]*sizeof(ossim_int32)); for(j=0;jcellmap[index][NUMFEAT];j++) { memcpy(&box,&(spx->buf[j][BOUND]),4*sizeof(unsigned char)); if (is_over(box,spx->box)) { set_insert(spx->buf[j][ID],set); } } } /************************************************************************* * *N search_cell * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Search the current cell for local records and, if the box is in the * search area, search the cell's children. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * record ==(ossim_int32) record number. * level ==(int) level of the index tree. * bnd ==(unsigned char[4]) bounding box. * spx ==(spx_type *) spatial index record structure. * set ==(set_type) search set to be updated. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Mody Buchbinder Jul 1991 *E *************************************************************************/ static void search_cell( ossim_int32 record, int level, unsigned char bnd[4], spx_type *spx, set_type set ) { int i; unsigned char locbnd[4],cut; for(i=0;i<4;i++) locbnd[i] = bnd[i]; if(level != 0) { /* level even -> cut on x , level odd -> cut on y */ if(level%2 == 1) cut = bnd[0] + ((bnd[2] - bnd[0]) >> 1); else cut = bnd[1] + ((bnd[3] - bnd[1]) >> 1); /* cut on x right cell */ if(level%2 == 1 && record%2 == 0) locbnd[0] = cut; /* cut on x left cell */ if(level%2 == 1 && record%2 == 1) locbnd[2] = cut; /* cut on y upper cell */ if(level%2 == 0 && record%2 == 0) locbnd[1] = cut; /* cut on y lower cell */ if(level%2 == 0 && record%2 == 1) locbnd[3] = cut; } if(is_over(locbnd,spx->box) == 1) { get_record(record,spx,set); if(record*2 <= spx->maplen) { search_cell(record*2, level+1,locbnd, spx, set); search_cell(record*2+1,level+1,locbnd, spx, set); } } } /************************************************************************* * *N spatial_index_search * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Search the named spatial index file to find all records falling * within the specified extent. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * fname ==(char *) path name to a VPF spatial index file. * x1 ==(float) left coordinate of the search box. * y1 ==(float) bottom coordinate of the search box. * x2 ==(float) right coordinate of the search box. * y2 ==(float) top coordinate of the search box. * set ==(set_type) search set to be filled. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Mody Buchbinder Jul 1991 *E *************************************************************************/ set_type spatial_index_search( char *fname, float x1, float y1, float x2, float y2 ) { long head[6]; float bnd[4],xf,yf; unsigned char tempbox[4]; set_type set; spx_type spx; #ifdef __MSDOS__ spx.fd = open(fname,O_RDONLY | O_BINARY); #else spx.fd = open(fname,O_RDONLY); #endif if(spx.fd == -1) { printf("Cannot open spatial index file (%s) \n",fname); perror("spatial_index_search: "); set.size = 0; set.buf = NULL; set.diskstorage = 0; set.fp = NULL; return set; } /* read basic header - int 0 -> number of features in coverage */ /* int 1 - 4 -> boundaries of coverage */ /* int 5 -> size of tree in records - each */ /* record = 2 integers (8 byte) */ read(spx.fd,head,6*sizeof(ossim_int32)); spx.shift = 6*sizeof(ossim_int32); spx.maplen = head[CELLMAP_SIZE]; set = set_init(head[TOTAL_NUMBER]+1L); memcpy(&bnd[0],&head[BOUND_START],4*sizeof(float)); /* If the boundaries of the cellmap are completely within the */ /* search area, all features are on */ if ( (x1 <= bnd[XMIN]) && (x2 >= bnd[XMAX]) && (y1 <= bnd[YMIN]) && (y2 >= bnd[YMAX]) ) { set_on(set); close(spx.fd); return set; } /* read the cell tree */ if( (size_t)read(spx.fd,spx.cellmap,2*spx.maplen*sizeof(ossim_int32)) != (2*spx.maplen*sizeof(ossim_int32)) ) { close(spx.fd); return set; } spx.shift += 2*spx.maplen*sizeof(ossim_int32); /* translate search box to 1 byte numbers */ xf = (float)(255.0 / (bnd[XMAX] - bnd[XMIN])); yf = (float)(255.0 / (bnd[YMAX] - bnd[YMIN])); spx.box[XMIN] = (char)((x1 - bnd[XMIN]) * xf); if (x1 <= bnd[XMIN]) spx.box[XMIN] = 0; if (x1 >= bnd[XMAX]) spx.box[XMIN] = 255; spx.box[YMIN] = (char)((y1 - bnd[YMIN]) * yf); if (y1 <= bnd[YMIN]) spx.box[YMIN] = 0; if (y1 >= bnd[YMAX]) spx.box[YMIN] = 255; spx.box[XMAX] = (char)(((x2 - bnd[XMIN]) * xf) + 1); if (x2 <= bnd[XMIN]) spx.box[XMAX] = 0; if (x2 >= bnd[XMAX]) spx.box[XMAX] = 255; spx.box[YMAX] = (char)(((y2 - bnd[YMIN]) * yf) + 1); if (y2 <= bnd[YMIN]) spx.box[YMAX] = 0; if (y2 >= bnd[YMAX]) spx.box[YMAX] = 255; /** start search **/ tempbox[XMIN] = 0; tempbox[YMIN] = 0; tempbox[XMAX] = 0xff; tempbox[YMAX] = 0xff; search_cell(1,0,tempbox,&spx,set); close(spx.fd); return set; } ossim-Miami-2.9.1/src/vpfutil/vpftable.c000066400000000000000000000722211352751253100201460ustar00rootroot00000000000000/************************************************************************* * * Environmental Systems Research Institute (ESRI) Applications Programming * *N Module VPFTABLE.C * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This module contains functions to open, close and parse VPF relational * tables. VPF tables are defined as being a set of rows and columns. * Each column may contain a single value, a fixed array of values, * or a variable number of values. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 - DOS Turbo C. * Mody Buchbinder May 1991 - Modified parse_data_def for new table * header structure. * Dave Flinn July 1991 - Updated file for UNIX. * JTB 10/91 - split off read routines into vpfread.c * merged view and converter branches of * this module; replaced various aborts() * and exits with return codes *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * (function) displayerror(char *text[], int nlines) - function * specified by the application to display a message to the user. * It should return an integer indicating whether to retry (1) or * not (0). * FILE *errorfp - file pointer to error file. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. * Updated to port to UNIX platforms with big-endian architectures *E *************************************************************************/ #include #ifdef CARBON #define MACHINE_BYTE_ORDER 0 #endif #ifdef __MSDOS__ #include #include #include #include #include #else #ifndef _WIN32 #define UNIX 1 #include #endif #endif #if UNIX #include #include #define getch() /* Make this a null function */ #define farcoreleft() " " #endif #include #include #include #include #include #include #include #include #ifndef __64K #define __64K 65536 #endif /* * per heap block byte overhead */ #define HEAP_OVERHEAD 4 /* Global variable shared by VPFTABLE.C, VPFREAD.C, and VPFWRITE.C */ /* The above modules are logically one, only separated by file size */ /* constraints. */ int STORAGE_BYTE_ORDER = LEAST_SIGNIFICANT; /* default */ int vpfutilMachineByteOrder() { unsigned short test = 0x0001; unsigned char* testPtr=NULL; testPtr = (unsigned char*)(&test); return (testPtr[0] ? LEAST_SIGNIFICANT : MOST_SIGNIFICANT); } /* Include these to decrease external module dependencies */ #if 0 /* Defined in vpfmisc??? (drb) */ static char *rightjust( char *str ) { register int len,i; len = strlen(str); i = len - 1; while ((i>0) && ((str[i]==0) || (str[i]==' '))) i--; if (i < (len-1)) str[i+1] = '\0'; for (i=0;i == (vpf_table_type *) vpf table structure. * ddlen == (ossim_int32) length of the table's data definition. * * return value is the record length if all items are fixed length, or * -1 if the record contains variable length items *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C * Mody Buchbinder May 1991 - Modified for new table header. * Dave Flinn July 1991 - updated for UNIX *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void *vpfmalloc() VPFMISC.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ ossim_int32 parse_data_def( vpf_table_type *table ) { register ossim_int32 n,i; ossim_int32 p, k; char *buf,*des,*nar,*vdt, *tdx, *doc, byte ;/*temporary storage */ char end_of_rec; int status; ossim_int32 ddlen; ossim_int32 reclen = 0; #if UNIX /* just for backward compat check */ ossim_int32 bkcompat = 1 ; #endif if ( table->mode == Read ) { fread(&ddlen,sizeof(ddlen),1,table->fp); /* Check the next byte to see if the byte order is specified */ fread(&byte,1,1,table->fp); p=0; table->byte_order = LEAST_SIGNIFICANT; /* default */ switch (toupper(byte)) { case 'L': p++; break; case 'M': table->byte_order = MOST_SIGNIFICANT; p++; break; } if (MACHINE_BYTE_ORDER != table->byte_order) { k = ddlen; swap_four((char *)&k,(char *)&ddlen); } if ( ddlen < 0 ) { return (ossim_int32)0 ; } STORAGE_BYTE_ORDER = table->byte_order; /* header without first 4 bytes */ table->ddlen = ddlen + sizeof (ossim_int32) ; buf = (char *)vpfmalloc((ddlen+3)*sizeof(char)); buf[0] = byte; /* already have the first byte of the buffer */ Read_Vpf_Char(&buf[1],table->fp,ddlen-1) ; } else { table->ddlen = (long)strlen ( table->defstr ) ; ddlen = table->ddlen ; buf = (char *)vpfmalloc((ddlen+3)*sizeof(char)); strncpy ( buf, table->defstr, ddlen ) ; p=0; table->byte_order = LEAST_SIGNIFICANT; /* default */ byte = buf[0]; switch (toupper(byte)) { case 'L': p++; break; case 'M': table->byte_order = MOST_SIGNIFICANT; p++; break; } STORAGE_BYTE_ORDER = table->byte_order; } buf[ddlen-1] = '\0'; /* mark end of string for reading functions */ if ( buf[p] == ';' ) p++; /* buf[p] is semi-colon */ des = get_string(&p,buf,COMPONENT_SEPERATOR ); strncpy(table->description,des,80); free(des); nar = get_string(&p,buf,COMPONENT_SEPERATOR ); strncpy(table->narrative ,nar,12); free(nar); n = 0 ; /* get number of fields */ for (i=p; i < ddlen;i++) if ( buf[i] == LINE_CONTINUE ) i++ ; /* skip past line continue, and next character */ else if (buf[i] == END_OF_FIELD ) /* Found end of field */ n++; /* increment nfields */ else if (buf[i] == COMMENT ) /* skip past comments */ while ( buf[i] != LINE_CONTINUE && buf[i] != END_OF_FIELD && buf[i] != '\0') i++ ; /* increment i */ table->nfields = n ; table->header = (header_type)vpfmalloc((n+1)*sizeof(header_cell)); for(i=0;iheader[i].name = get_string(&p,buf, FIELD_COUNT); /*****/ rightjust(table->header[i].name); table->header[i].type = toupper(vpf_get_char (&p,buf)); table->header[i].count = get_number(&p,buf,FIELD_SEPERATOR ); if ( i == 0 ) if ( ossim_strcasecmp ( table->header[0].name, "ID" ) ) { free(buf); return (ossim_int32)0 ; } if(table->header[i].count == -1) reclen = -1; /* set reclen to variable len flag */ /* Now set null values and add up record length, if fixed length */ status = 0; switch (table->header[i].type) { case 'I': if ( reclen >= 0 ) reclen += (sizeof(ossim_int32)*table->header[i].count); table->header[i].nullval.Int = NULLINT ; break; case 'S': if ( reclen >= 0 ) reclen += (sizeof(short int)*table->header[i].count); table->header[i].nullval.Short = NULLSHORT ; break; case 'F': if ( reclen >= 0 ) reclen += (sizeof(float)*table->header[i].count); table->header[i].nullval.Float = NULLFLOAT ; break; case 'R': if ( reclen >= 0 ) reclen += (sizeof(double)*table->header[i].count); table->header[i].nullval.Double = NULLDOUBLE ; break; case 'T': if ( reclen >= 0 ) { /* if fixed length */ reclen += (sizeof(char)*table->header[i].count); table->header[i].nullval.Char = (char *) vpfmalloc ( table->header[i].count + 1 ) ; for ( k=0; k < table->header[i].count; k++ ) table->header[i].nullval.Char[k] = NULLCHAR ; table->header[i].nullval.Char[k] = '\0'; } else { /* variable length */ table->header[i].nullval.Char = (char *) vpfmalloc ( VARIABLE_STRING_NULL_LENGTH + 1 ) ; for ( k=0; k < VARIABLE_STRING_NULL_LENGTH ; k++ ) table->header[i].nullval.Char[k] = NULLCHAR ; table->header[i].nullval.Char[k] = '\0'; } break; case 'C': if ( reclen >= 0 ) reclen += (sizeof(coordinate_type)*table->header[i].count); table->header[i].nullval.Other = '\0'; break; case 'Z': if ( reclen >= 0 ) reclen += (sizeof(tri_coordinate_type)*table->header[i].count); table->header[i].nullval.Other = '\0' ; break; case 'B': if ( reclen >= 0 ) reclen += (sizeof(double_coordinate_type)*table->header[i].count); table->header[i].nullval.Other = '\0' ; break; case 'Y': if ( reclen >= 0 ) reclen += (sizeof(double_tri_coordinate_type)*table->header[i].count); table->header[i].nullval.Other ='\0'; break; case 'D': if ( reclen >= 0 ) reclen += ((sizeof(date_type)-1)*table->header[i].count); strcpy ( table->header[i].nullval.Date, NULLDATE ) ; break; case 'K': reclen = -1; table->header[i].nullval.Other = '\0' ; break; case 'X': /* do nothing */ table->header[i].nullval.Other = '\0' ; break ; default: status = 1; break ; } /** switch type **/ if (status) { free(buf); return (ossim_int32)0; } table->header[i].keytype = vpf_get_char (&p,buf); des = get_string(&p,buf, FIELD_SEPERATOR ); rightjust(des); strncpy(table->header[i].description,des,80); free(des); vdt = get_string(&p,buf, FIELD_SEPERATOR ); strncpy(table->header[i].vdt,vdt,12); free(vdt); #if UNIX /* This is for backward compatability qc checking */ if ( bkcompat && buf[p] == END_OF_FIELD ) { bkcompat= 0 ; } #endif tdx = get_string(&p,buf, FIELD_SEPERATOR ) ; if ( ! strcmp ( tdx, "" ) ) { table->header[i].tdx = (char *) NULL ; if (buf[p] == ':') end_of_rec = TRUE; } else { if (strcmp(tdx,"-") != 0) { table->header[i].tdx =(char*) vpfmalloc ( (unsigned long)strlen ( tdx ) +1 ) ; strcpy (table->header[i].tdx, tdx ); } else table->header[i].tdx = (char *)NULL; } free(tdx); if (!end_of_rec) { doc = get_string(&p,buf, FIELD_SEPERATOR ) ; if ( ! strcmp ( doc, "" ) ) { table->header[i].narrative = (char *) NULL ; end_of_rec = TRUE; } else { if (strcmp(doc,"-") != 0) { table->header[i].narrative = (char*)vpfmalloc ( (unsigned long)strlen(doc) +1) ; strcpy (table->header[i].narrative, doc ); } else table->header[i].narrative = (char *)NULL; } free(doc); } else table->header[i].narrative = (char *)NULL; p += 1; /** eat semicolon **/ } free(buf); return reclen; } /************************************************************************* * *N vpfhandler * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function temporarily takes the place of the DOS hard error * handler. It is needed when 'vpfopencheck' replaces the DOS error * handler for disk operations, so that the disk errors may be handled * more suitably for our environment. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C * Dave Flinn July 1991 Updated for UNIX, basically commented * the subroutine out *E *************************************************************************/ /*static int disk_error;*/ #define IGNORE 0 #define RETRY 1 #define ABORT 2 #define DISPLAY_STRING 0x09 #ifdef __MSDOS__ static int vpfhandler(ossim_int32 errval, ossim_int32 ax, ossim_int32 bp, ossim_int32 si) { if (ax < 0) { bdosptr(DISPLAY_STRING,"device error$", 0); hardretn(-1); } disk_error = errval; si++; bp++; /* get rid of compiler warning */ return(IGNORE); } #endif /************************************************************************* * *N vpfopencheck * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function tries its darndest to open a file. It initially calls * fopen with the given filename and mode. If that doesn't work and * the file is not on the hard disk, it displays a message asking the * user to enter the correct disk in the drive, waits for either a retry * or a cancel response, and, if told to retry, tries again. This * process is repeated until either the file is opened or the user * requests cancel. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * filename == (char *) full path name of the file to be opened. * mode == (char *) mode of the file. * diskname == (char *) descriptive name of the disk the file is * on. * return == (FILE *) file pointer newly associated with * filename. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C * Dave Flinn July 1991 Updated for UNIX *E *************************************************************************/ FILE *vpfopencheck( const char *filename, const char *mode, const char * diskname ) { FILE *fp; char* tmpFilename = (char*) malloc ( strlen(filename) + 1 ); /* char *text[] = {"Please insert", " ", "in data drive", " "}; */ ossim_int32 retry = 0; #ifdef __MSDOS__ extern char home[255]; void interrupt (*doshandler)(); doshandler = getvect(36); harderr(vpfhandler); strncpy(text[1],diskname,strlen(text[1])); strcpy(text[3],filename); #endif fp = NULL; /* copy the filename because we might modify it. */ tmpFilename[strlen(filename)] = '\0'; /* just in case */ strcpy(tmpFilename, filename); while (fp == NULL) { fp = fopen(tmpFilename,mode); if (fp == NULL) { #ifdef __MSDOS__ if ( toupper(home[0]) != toupper(tmpFilename[0]) ) retry = displayerror(text, 4); else #else /* give names ending in dot another chance without the dot */ if (tmpFilename[strlen(tmpFilename)-1] == '.') { tmpFilename[strlen(tmpFilename)-1] = '\0'; retry = TRUE; } else #endif retry = FALSE; if (!retry) break; } } free(tmpFilename); tmpFilename = 0; #ifdef __MSDOS__ setvect(36,doshandler); #endif return fp; } /************************************************************************* * *N vpf_open_table * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function opens a vpf table and either loads it into RAM or sets * up the structure to read off of disk. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * tablename == (const char *) file name of the table. * storage == (storage_type) table storage mode - * either ram or disk. * mode == (const char *) file mode for opening the table - * same as fopen() mode in C. * defstr == (char *) table definition string used for * creating a writable table. * vpf_open_table == (vpf_table_type) VPF table structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C * Dave Flinn July 1991 UNIX compatable *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ vpf_table_type vpf_open_table( const char * tablename, storage_type storage , const char * mode, char * defstr ) { vpf_table_type table; char tablepath[255], * idxname; ossim_int32 i, j; ossim_int32 tablesize, idxsize, memsize; ossim_uint32 ulval; char * diskname = "VPF data disc"; strcpy(tablepath,tablename); rightjust(tablepath); /* Parse out name and path */ j = -1; i=(long)strlen(tablepath); while (i>0) { #ifdef __MSDOS__ if (tablepath[i] == '\\') { #else if (tablepath[i] == '/') { #endif j = i; break; } i--; } strncpy(table.name,&(tablepath[j+1]),12); rightjust(table.name); strupr(table.name); table.path = (char *)vpfmalloc(((unsigned long)strlen(tablepath)+5)*(unsigned long)sizeof(char)); strcpy(table.path, tablepath); table.path[j+1] = '\0'; /* Establish a read or write table operation */ if ( mode[0] == 'r' ) table.mode = Read ; else table.mode = Write ; /*fprintf(stderr, "vpf_open_table opening %s\n", tablepath);*/ table.fp = vpfopencheck(tablepath,mode,diskname); if (table.fp == NULL) { perror(tablepath); /* #if __MSDOS__ perror(tablepath); getch(); if (getgraphmode() >= 0) closegraph(); exit(0); #endif */ free(table.path); if (table.fp) { fclose(table.fp); table.fp = NULL; } return table; } /* If file is to be created, copy the def string ptr into header for now */ if ( table.mode == Write ) table.defstr = defstr ; #ifdef __MSDOS__ tablesize = (filelength(fileno(table.fp))); #else { /* UNIX doesn't have a filelength function, so this is the best */ struct stat statbuf ; if ( stat ( tablepath, &statbuf ) < 0 ) { fprintf (stderr, "vpf_open_table: can't stat file\n" ) ; free(table.path); fclose(table.fp); table.fp = NULL; return table; } tablesize = statbuf.st_size ; } #endif /* Populate table structure with correct data, either for read or write */ table.reclen = parse_data_def(&table); if ( table.mode == Write ) { /* write out header */ rewind ( table.fp ) ; Write_Vpf_Int ( &table.ddlen, table.fp, 1 ) ; Write_Vpf_Char ( table.defstr, table.fp, table.ddlen ) ; free ( table.defstr ) ; table.defstr = (char *) NULL ; table.nrows = 0 ; } if (table.reclen > 0) { /* Index file */ table.xstorage = (storage_type)COMPUTE; if (table.mode != Write) table.nrows = (tablesize - table.ddlen)/table.reclen; table.xfp = (FILE *) NULL ; } else { idxname = strdup( tablepath ); #ifdef __MSDOS__ idxname[strlen(tablepath)-1] = 'x'; #else if (idxname[strlen(tablepath)-1] == '.') idxname[strlen(tablepath)-2] = 'x'; else idxname[strlen(tablepath)-1] = 'x'; #endif table.xfp = fopen(idxname, mode); if ((!table.xfp) && (table.mode == Read)) { perror(idxname); fprintf(stderr, "hit RETURN to continue..."); i=getc(stdin); free(idxname); for (i = 0; i < table.nfields; i++) free(table.header[i].name); free(table.header); free(table.path); fclose(table.fp); table.fp = NULL; return table; } free(idxname); /*#ifdef __MSDOS__*/ table.xstorage = (storage_type)DISK; /* Worst case default */ /*#endif*/ /* Only read in index if file is read only */ if (table.xfp && ( table.mode == Read ) ) { Read_Vpf_Int (&(table.nrows), table.xfp, 1 ) ; Read_Vpf_Int (&ulval, table.xfp, 1 ) ; idxsize = table.nrows*sizeof(index_cell) + 10L; #ifdef __MSDOS__ if ( (idxsize < (farcoreleft()/2)) && (idxsize < __64K) ) #else if (0) #endif { table.xstorage = (storage_type)RAM; table.index = (index_type)vpfmalloc(idxsize); for (i=0;i == (vpf_table_type) VPF table structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ void vpf_close_table( vpf_table_type *table ) { register ossim_int32 i; if (table->status != OPENED) { return; } /*fprintf(stderr, "vpf_close_table closing %s%s\n", table->path, table->name);*/ /* If the table is writable, write out the final record count */ if ( table->mode == Write && table->xfp ) { rewind ( table->xfp ) ; Write_Vpf_Int ( &table->nrows, table->xfp, 1 ) ; Write_Vpf_Int ( &table->ddlen, table->xfp, 1 ) ; } for (i=0;infields;i++) { free(table->header[i].name); /* free up null text string */ if ( table->header[i].type == 'T') free(table->header[i].nullval.Char); /* free up index file string */ if (table->header[i].tdx!=(char *)NULL) free ( table->header[i].tdx ) ; /* free up narrative table string */ if (table->header[i].narrative!=(char *)NULL) { free ( table->header[i].narrative ) ; } } free(table->header); switch (table->storage) { case RAM: for (i=0;inrows;i++) free_row(table->row[i],*table); free(table->row); break; case DISK: fclose(table->fp); break; default: printf("%s%s: unknown storage flag: %d\n",table->path,table->name, table->storage); break; } switch (table->xstorage) { case RAM: free(table->index); break; case DISK: fclose(table->xfp); break; case COMPUTE: break; default: printf("%s%s: unknown index storage flag: %d\n", table->path,table->name,table->storage); break; } table->nfields = 0; free(table->path); table->status = CLOSED; } ossim_int32 is_vpf_table( const char *fname ) { FILE *fp; ossim_int32 n, ok; fp = fopen( fname, "rb" ); if (!fp) { return FALSE; } Read_Vpf_Int ( &n, fp, 1 ) ; fseek( fp, n-1, SEEK_CUR ); if (fgetc(fp) == ';') ok = TRUE; else ok = FALSE; fclose(fp); return ok; } ossim-Miami-2.9.1/src/vpfutil/vpftidx.c000066400000000000000000001466761352751253100200470ustar00rootroot00000000000000/************************************************************************* * * Environmental Systems Research Institute (ESRI) Applications Programming * *N Module VPFTIDX * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * *P * Purpose: Subroutines to create and read both the thematic index * or a gazeteer index on a VPF table column. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn September/October 1991 * Barry Michaels January 1992 A few adjustments for DOS. * Added sets to create function to * take advantage of SET's disk- * swapping ability when low on memory. *E * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions: *F * * set_type read_thematic_index ( char *tablename, * char *value ) ; * * ThematicIndex open_thematic_index ( char *tablename ); * * set_type search_thematic_index ( ThematicIndex *themindex, * char *value ) ; * * void close_thematic_index ( ThematicIndex *themindex ); * * set_type read_gazetteer_index (char * vpfname, char * query_str ) ; * * set_type search_gazetteer_index (ThematicIndex *idx, * char * query_str ) ; * * ossim_int32 read_gazetteer_index_directory ( * ThematicIndexDirectory ** gid, * ThematicIndexHeader * gi, * FILE * idx_fp); * * ossim_int32 write_thematic_index_header ( ThematicIndexHeader h , * FILE *fp ) ; * * ossim_int32 read_thematic_index_header ( ThematicIndexHeader *h , * FILE *fp ) ; * * ossim_int32 write_thematic_index_directory ( * ThematicIndexHeader h , * ThematicIndexDirectory *d, * ossim_int32 size, * FILE *fp ) ; * * ossim_int32 write_gazetteer_index_directory ( * ThematicIndexHeader h , * ThematicIndexDirectory *d, * ossim_int32 size, * FILE *fp ) ; * * ossim_int32 create_thematic_index ( char indextype, * char *tablename, * char *idxname , * char *columnname, * char *idx_set ); * * ossim_int32 create_gazetteer_index (char *tablename, * char *idx_fname , * char *columnname, * char *idx_set); * *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * * Portability: *O * This module should be ANSI C compatible. Created on UNIX first *E *************************************************************************/ #include #include #include #include #include #include #include #include #ifndef __MSDOS__ # ifndef _WIN32 # include # endif #endif void *vpfmalloc(unsigned long size); #define Whimper(str) {\ return ((ossim_int32)0) ; } #define SWhimper(str) {\ set_type err; err = set_init (1) ;\ printf("\nvpftidx: < %s >\n", str ) ;\ return err ; } #define OWhimper(str) {\ printf("\nvpftidx: < %s >\n", str ) ;\ return idx ; } /* * an index file directory entry takes up a different amount * of space in memory than it does on disk; the following constant * should be used to calculate the starting offset for * index data * * example: if the number of items to be indexed is t, and each item is * s bytes long, then use * * sizeof(ThematicIndexHeader) + t * (s + DIR_ON_DISK_INCR) * * to find out where the first byte of indexing data will be placed. * * That first byte is what must be stored as the value of Header.nbytes */ #define DIR_ON_DISK_INCR (2 * sizeof(ossim_int32)) /************************************************************************* * *N create_thematic_index * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: * * Create a thematic index file on a given vpf table. *P * *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * indextype == (char) either 'T' for thematic index or * 'G' for gazetteer. * tablename == (char *) path name of the vpf table. * idxname == (char *) name of the index file to be created. * columnname == (char *) name of column to create index on * if the column is a triplet id, the columnname * should be as such: EDG_ID\ID * EDG_ID\TILE_ID * EDG_ID\EXT_ID * idxset == (char *) array of character values to index on * if the index type is gazetteer. Not used for * index type = 'T'. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * void *vpfmalloc VPFMISC.C * vpf_open_table VPFTABLE.C * table_pos * table_element * vpf_close_table * write_thematic_index_header see below * write_thematic_index_directory see below * Vpf_Write_* macros * set_init SET.C * set_insert *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. developed on UNIX *E *************************************************************************/ ossim_int32 create_thematic_index ( char indextype, char *tablename, char *idxname , char *columnname, char *idx_set ) { unsigned int i; unsigned int column_length; FILE *ifp ; ossim_int32 j,tablepos,k, keycolumn = 0 , /* 1 if key column */ itemp , n, idsize , /* either 2 or 4 bytes */ datasize ; /* Directory value data size */ char *buf , hack[80] ; vpf_table_type table ; ThematicIndexHeader h ; ThematicIndexDirectory *d ; short int stemp ; float ftemp ; double dtemp ; id_triplet_type key ; if ( indextype == 'G' ) { return ( create_gazetteer_index ( tablename, idxname,columnname,idx_set)) ; } /* convert columnname to uppercase and check for id triplet */ column_length = (unsigned int)strlen(columnname); for ( i=0 ; i < column_length; i++ ) { /* copy into header structure */ h.vpf_column_name[i] = toupper ( columnname[i] ) ; } h.vpf_column_name[i] = '\0'; h.index_type = 'T' ; /* default */ h.type_count = 1 ; for (i=0 ; i < column_length; i++ ) { columnname[i] = toupper ( columnname[i] ) ; #if 0 /* check if request is on a triplet id field */ if ( columnname[i] == '\\' ) { columnname[i+1] = toupper ( columnname[i+1] ) ; switch ( columnname[i+1] ) { /* locate sub-column key */ case 'I': /* ID of triplet id */ keycolumn = 1 ; break ; case 'T': /* TILE_ID of triplet id */ keycolumn = 2 ; break ; case 'E': /* EXT_ID of triplet id */ keycolumn = 3 ; break ; default: Whimper ("error in key column request") ; /* break ; Whimper contains a return */ } /* end of switch */ strcpy( h.vpf_column_name, strupr ( columnname )) ; columnname[i] = (char) NULL ; } /* end of if columnname == \ */ #endif } /* end of for loop */ table = vpf_open_table ( tablename, disk, "rb", NULL ) ; /* Determine the id_data_size. This will save 50% of file size */ if ( table.nrows > MAX_ID ) { h.id_data_type = 'I' ; /* ossim_int32s */ idsize = sizeof ( ossim_int32 ) ; } else { h.id_data_type = 'S' ; /* ossim_int32s */ idsize = sizeof ( short int ) ; } /* Find position of column in input table */ tablepos = table_pos ( columnname, table ) ; /* Now check data type */ switch (table.header[tablepos].type) { case 'X': Whimper ("Cannot make index on Null Column") ; /* A return is in Whimper - break statement cannot be reached */ case 'T': /* Don't bother with variable length, it's too hard for now */ if ( table.header[tablepos].count <= 0 ) Whimper ("Cannot make index on variable length text column") ; datasize = table.header[tablepos].count ; h.type_count = datasize ; /* the special case */ break; case 'D': datasize = sizeof ( date_type ) ; Whimper ("Not implemented yet") ; case 'I': datasize = sizeof ( ossim_int32 ) ; break ; case 'K': /* treat keys like integers */ Whimper ("Cannot make index on key column") ; case 'S': datasize = sizeof ( short int ) ; break ; case 'F': datasize = sizeof ( float ) ; break ; case 'R': datasize = sizeof ( double ) ; break ; case 'C': case 'Z': case 'B': case 'Y': Whimper ("Cannot make index on Coordinate Column") ; default: sprintf (hack,"No such type < %c >", table.header[tablepos].type ) ; Whimper ( hack ) ; } /* end of switch */ /* open output index file */ if (( ifp = fopen ( idxname, "wb" )) == NULL ) Whimper ( idxname ) ; /* Create directory size as big as table, for worst case */ d = (ThematicIndexDirectory *) vpfmalloc(sizeof(ThematicIndexDirectory)) ; h.nbins = 0 ; /* initialize the directory counter */ #define REALLOC_DIRECTORY(loc) {\ if ((d = (ThematicIndexDirectory *) \ realloc(d,sizeof(ThematicIndexDirectory) * (loc+1))) == NULL )\ Whimper ("error in reallocing directory") ; \ d[loc].num_items = 0 ;\ d[loc].idset = set_init(table.nrows+1); } #define INSERT_ID(loc,val) {\ d[loc].num_items++ ; \ set_insert(val,d[loc].idset); } /* Fill up id sets */ switch ( table.header[tablepos].type ) { case 'I': for ( i=1; (int)i <= table.nrows; i++ ) { /* read in record from disk */ table_element ( tablepos,i,table,&itemp,&n); for ( k=0; k < h.nbins; k++ ) /* Search directory for value*/ if ( d[k].value.ival == itemp ) break ;/* Found a match */ if ( k == h.nbins ) { /* New value in column */ REALLOC_DIRECTORY ( k ) ; d[k].value.ival = itemp ; h.nbins++ ; } INSERT_ID(k,i) ; } /* end of for i loop */ break ; case 'T': /* initialize */ buf = (char *) table_element (tablepos,1,table,NULL,&n); REALLOC_DIRECTORY ( 0 ) ; d[0].value.strval = (char *) vpfmalloc ( (unsigned long)strlen ( buf ) +1) ; memcpy( d[0].value.strval, buf, (unsigned long)strlen(buf) ) ; free (buf) ; h.nbins++ ; for ( i=1; (int)i <= table.nrows; i++ ) { /* read in record from disk */ buf = (char *) table_element (tablepos,i,table,NULL,&n); /* strlen ( buf ) should equal datasize */ for ( k=0; k < h.nbins; k++ ) /* Search directory for value*/ if ( ! strcmp ( d[k].value.strval, buf ) ) break ;/* Found a match */ if ( k == h.nbins ) { /* New value in column */ REALLOC_DIRECTORY ( k ) ; d[k].value.strval = (char *) vpfmalloc ( (unsigned long)strlen ( buf ) +1) ; memcpy( d[0].value.strval, buf, strlen(buf) ) ; h.nbins++ ; } INSERT_ID(k,i) ; free(buf); } /* end of for i loop */ break ; case 'S': for ( i=1; (int)i <= table.nrows; i++ ) { /* read in record from disk */ table_element ( tablepos,i,table,&stemp,&n); for ( k=0; k < h.nbins; k++ ) /* Search directory for value*/ if ( d[k].value.sval == stemp ) break ;/* Found a match */ if ( k == h.nbins ) { /* New value in column */ REALLOC_DIRECTORY ( k ) ; d[k].value.sval = stemp ; h.nbins++ ; } INSERT_ID (k,i) ; } /* end of for i loop */ break ; case 'F': for ( i=1; (int)i <= table.nrows; i++ ) { /* read in record from disk */ table_element ( tablepos,i,table,&ftemp,&n); for ( k=0; k < h.nbins; k++ ) /* Search directory for value*/ if ( d[k].value.fval == ftemp ) break ;/* Found a match */ if ( k == h.nbins ) { /* New value in column */ REALLOC_DIRECTORY ( k ) ; d[k].value.fval = ftemp ; h.nbins++ ; } INSERT_ID (k,i) ; } /* end of for i loop */ break ; case 'R': for ( i=1; (int)i <= table.nrows; i++ ) { /* read in record from disk */ table_element ( tablepos,i,table,&dtemp,&n); for ( k=0; k < h.nbins; k++ ) /* Search directory for value*/ if ( d[k].value.dval == dtemp ) break ;/* Found a match */ if ( k == h.nbins ) { /* New value in column */ REALLOC_DIRECTORY ( k ) ; d[k].value.dval = dtemp ; h.nbins++ ; } INSERT_ID (k,i) ; } /* end of for i loop */ break ; case 'K': for ( i=1; (int)i <= table.nrows; i++ ) { /* read in record from disk */ table_element ( tablepos,i,table,&key,&n); if ( keycolumn == 1 ) itemp = key.id ; else if ( keycolumn == 2 ) itemp = key.tile ; else itemp = key.exid ; for ( k=0; k < h.nbins; k++ ) /* Search directory for value*/ if ( d[k].value.ival == itemp ) break ;/* Found a match */ if ( k == h.nbins ) { /* New value in column */ REALLOC_DIRECTORY ( k ) ; d[k].value.ival = itemp ; h.nbins++ ; } INSERT_ID (k,i) ; } /* end of for i loop */ break ; default: Whimper ("error in table reading switch, no such type") ; } /* end of switch */ /* set up header and write it out */ /* h.id_data_size and columnname set up above */ /* h.type_count set above */ h.nbytes = THEMATIC_INDEX_HEADER_SIZE + h.nbins * ( datasize + DIRECTORY_SIZE ) ; h.column_type = table.header[tablepos].type ; if ( h.column_type == 'K' ) /* It's really an I */ h.column_type = 'I' ; for ( i=0; i < 4; i++ ) h.padding[i] = '\0' ; /* only write the table name, no pathname */ for ( i = (unsigned int)strlen ( tablename ); i > 0; i-- ) if ( tablename[i] == '/' ) break ; if ( i && i < strlen (tablename) ) strcpy ( h.vpf_table_name, strupr ( &tablename[i+1] ) ) ; else strcpy( h.vpf_table_name, strupr ( tablename) ); for ( i=(unsigned int)strlen(h.vpf_table_name); i < 12 ; i++ ) h.vpf_table_name[i] = ' ' ; h.vpf_table_name[11] = '\0'; /* columname setup above */ h.table_nrows = table.nrows ; if ( write_thematic_index_header ( h, ifp ) == (ossim_int32)0 ) Whimper ( "error writing index header" ) ; /* Now write out the rest of the header directory */ if ( write_thematic_index_directory ( h, d, idsize, ifp ) == (ossim_int32)0 ) Whimper ( "error writing index directory" ) ; /* now write the data */ if ( h.id_data_type == 'I' ) { for ( i=0; (int)i < h.nbins; i++ ) for ( j=1; j <= table.nrows; j++ ) if (set_member(j,d[i].idset)) Write_Vpf_Int ( &j, ifp, 1 ) ; } else { for ( i=0; (int)i < h.nbins; i++ ) for ( j=1; j <= table.nrows; j++ ) if (set_member(j,d[i].idset)) { stemp = (short int)j; Write_Vpf_Short ( &stemp, ifp, 1 ) ; } } /* close up shop and exit */ vpf_close_table ( &table ); fclose ( ifp ) ; for ( i=0; (int)i < h.nbins; i++ ) set_nuke(&d[i].idset); free ( d ) ; return ( h.nbins ) ; } /************************************************************************* * *N read_thematic_index * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To read an index file, regardless of its type ( T or G ) and * return a set type array *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * idxname == (char *) name of index file * value == (char *) address of value to search on. * THE PROGRAMMER MUST INSURE THAT THIS ADDRESS * CORRESPONDS TO THE TABLE COLUMN AND INDEX FILE. * * Returns: * * set_type a set corresponding to the vpf table, where each * bit relates to the ID in the table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * read_thematic_index_header see below * set_init SET.C * set_insert * Vpf_Read_* VPFREAD.C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ set_type read_thematic_index ( char *idxname, char *value ) { ossim_int32 i , ival = 0, Match = -1; short int sval = 0; float fval = 0.0 ; double dval = 0.0 , atof () ; FILE *ifp ; char hack[80] , *buf = (char *) NULL, bufalloc=0 ; ThematicIndexHeader h ; ThematicIndexDirectory d ; set_type s ; /* open output index file */ if (( ifp = fopen ( idxname, "rb" )) == NULL ) { sprintf ( hack, "No such index < %s >", idxname ) ; SWhimper ( hack ) ; } if ( read_thematic_index_header ( &h, ifp ) == (ossim_int32)0 ) { fclose(ifp); SWhimper ( "error reading index header" ) ; } if ( h.index_type == 'G' ) { fclose ( ifp ) ; s = read_gazetteer_index ( idxname, value ) ; return s ; } if ( value ) /* search for pattern */ switch ( h.column_type ) { /* using address */ case 'I': memcpy ( &ival, value, sizeof (ossim_int32)) ; break ; case 'S': memcpy ( &sval, value, sizeof (short int)) ; break ; case 'F': memcpy ( &fval, value, sizeof (float)) ; break ; case 'R': memcpy ( &dval, value, sizeof (double)) ; break ; case 'T': buf = (char *) vpfmalloc ( h.type_count ) ; /* leave value as is */ bufalloc = 1; break ; } else{ fclose ( ifp ) ; SWhimper ( "require a value to search on.") ; } /* create set */ s = set_init ( h.table_nrows ) ; /* Look for a matching directory entry */ for ( i=0; i < h.nbins; i++ ) { switch ( h.column_type ) { case 'I': Read_Vpf_Int ( &d.value.ival, ifp, 1) ; if ( ival == d.value.ival ) { /* found the match */ Match = i ; i = h.nbins ; /* exit */ } break ; case 'S': Read_Vpf_Short ( &d.value.sval, ifp, 1) ; if ( sval == d.value.sval ) { /* found the match */ Match = i ; i = h.nbins ; /* exit */ } break ; case 'F': Read_Vpf_Float ( &d.value.fval, ifp, 1) ; if ( fval == d.value.fval ) { /* found the match */ Match = i ; i = h.nbins ; /* exit */ } break ; case 'R': Read_Vpf_Float ( &d.value.dval, ifp, 1) ; if ( dval == d.value.dval ) { /* found the match */ Match = i ; i = h.nbins ; /* exit */ } break ; case 'T': Read_Vpf_Char ( buf, ifp, h.type_count ) ; bufalloc = 1; if ( ! strcmp ( value, buf ) ) { /* found the match */ Match = i ; i = h.nbins ; /* exit */ } break ; } /* end of switch */ Read_Vpf_Int ( &d.start_offset, ifp, 1) ; Read_Vpf_Int ( &d.num_items, ifp, 1) ; } /* end of i loop */ if ( bufalloc ) free ( buf ) ; if ( Match < 0 ) { fclose(ifp); return s; } /* We've got a match, so now read the ids in */ if ( fseek ( ifp, d.start_offset, 0 ) != 0 ) { fclose ( ifp ) ; SWhimper ( "error in fseek") ; } /* read data into user-defined pointer. User must free this pointer */ if ( h.id_data_type == 'I' ) for ( i=0 ; i < d.num_items; i++ ) { Read_Vpf_Int ( &ival, ifp, 1 ) ; set_insert ( ival, s ) ; /* set the id in the set */ } else for ( i=0 ; i < d.num_items; i++ ) { Read_Vpf_Short ( &sval, ifp, 1 ) ; set_insert ( (ossim_int32) sval, s ) ; } fclose ( ifp ) ; return s ; /* also return set */ } /*end of read_index */ /************************************************************************* * *N open_thematic_index * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Open and initialize a thematic index. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * idxname == (char *) name of index file * * Returns: * * ThematicIndex Thematic index structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * read_thematic_index_header see below * set_init SET.C * set_insert * Vpf_Read_* macros *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ ThematicIndex open_thematic_index ( char *idxname ) { char hack[80]; ThematicIndex idx ; idx.d = NULL; idx.gid = NULL; /* open output index file */ if (( idx.fp = fopen ( idxname, "rb" )) == NULL ) { sprintf ( hack, "No such index < %s >", idxname ) ; OWhimper ( hack ) ; } if ( read_thematic_index_header ( &idx.h, idx.fp ) == (ossim_int32)0 ) OWhimper ( "error reading index header" ) ; if ( idx.h.index_type == 'G' ) { /* gazetteer_index */ if (read_gazetteer_index_directory(&idx.gid,&idx.h,idx.fp) == (ossim_int32)0) { fclose(idx.fp); idx.fp = NULL; } } return idx; } /************************************************************************* * *N search_thematic_index * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To search an index file, regardless of its type ( T or G ) and * return a set type array *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * idx == (ThematicIndex) thematic index * value == (char *) address of value to search on. * THE PROGRAMMER MUST INSURE THAT THIS ADDRESS * CORRESPONDS TO THE TABLE COLUMN AND INDEX FILE. * * Returns: * * set_type a set corresponding to the vpf table, where each * bit relates to the ID in the table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * read_thematic_index_header see below * set_init SET.C * set_insert * Vpf_Read_* macros *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ set_type search_thematic_index ( ThematicIndex *idx, char *value ) { ossim_int32 i , ival = 0, Match = -1; short int sval = 0; float fval = 0.0 ; double dval = 0.0 , atof () ; char *buf = (char *) NULL, bufalloc=0 ; ThematicIndexDirectory d ; set_type s ; /* open output index file */ if (!idx->fp) { s = set_init(1); return s; } if ( idx->h.index_type == 'G' ) { s = search_gazetteer_index ( idx, value ) ; return s ; } if ( value ) /* search for pattern */ switch ( idx->h.column_type ) { /* using address */ case 'I': memcpy ( &ival, value, sizeof (ossim_int32)) ; break ; case 'S': memcpy ( &sval, value, sizeof (short int)) ; break ; case 'F': memcpy ( &fval, value, sizeof (float)) ; break ; case 'R': memcpy ( &dval, value, sizeof (double)) ; break ; case 'T': buf = (char *) vpfmalloc ( idx->h.type_count ) ; /* leave value as is */ bufalloc = 1; break ; } else SWhimper ( "require a value to search on.") ; /* create set */ s = set_init ( idx->h.table_nrows ) ; /* Look for a matching directory entry */ fseek(idx->fp,THEMATIC_INDEX_HEADER_SIZE,SEEK_SET); for ( i=0; i < idx->h.nbins; i++ ) { switch ( idx->h.column_type ) { case 'I': Read_Vpf_Int ( &d.value.ival, idx->fp, 1) ; if ( ival == d.value.ival ) { /* found the match */ Match = i ; i = idx->h.nbins ; /* exit */ } break ; case 'S': Read_Vpf_Short ( &d.value.sval, idx->fp, 1) ; if ( sval == d.value.sval ) { /* found the match */ Match = i ; i = idx->h.nbins ; /* exit */ } break ; case 'F': Read_Vpf_Float ( &d.value.fval, idx->fp, 1) ; if ( fval == d.value.fval ) { /* found the match */ Match = i ; i = idx->h.nbins ; /* exit */ } break ; case 'R': Read_Vpf_Float ( &d.value.dval, idx->fp, 1) ; if ( dval == d.value.dval ) { /* found the match */ Match = i ; i = idx->h.nbins ; /* exit */ } break ; case 'T': Read_Vpf_Char ( buf, idx->fp, idx->h.type_count ) ; bufalloc = 1; if ( ! strcmp ( value, buf ) ) { /* found the match */ Match = i ; i = idx->h.nbins ; /* exit */ } break ; } /* end of switch */ Read_Vpf_Int ( &d.start_offset, idx->fp, 1) ; Read_Vpf_Int ( &d.num_items, idx->fp, 1) ; } /* end of i loop */ if ( bufalloc ) free ( buf ) ; if ( Match < 0 ) { return s; } /* We've got a match, so now read the ids in */ if ( fseek ( idx->fp, d.start_offset, 0 ) != 0 ) SWhimper ( "error in fseek") ; /* read data into user-defined pointer. User must free this pointer */ if ( idx->h.id_data_type == 'I' ) for ( i=0 ; i < d.num_items; i++ ) { Read_Vpf_Int ( &ival, idx->fp, 1 ) ; set_insert ( ival, s ) ; /* set the id in the set */ } else for ( i=0 ; i < d.num_items; i++ ) { Read_Vpf_Short ( &sval, idx->fp, 1 ) ; set_insert ( (ossim_int32) sval, s ) ; } return s ; /* also return set */ } /*end of search_index */ /************************************************************************* * *N close_thematic_index * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Close a thematic index. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * idx == (ThematicIndex *) thematic index *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * read_thematic_index_header see below * set_init SET.C * set_insert * Vpf_Read_* macros *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ void close_thematic_index ( ThematicIndex *idx ) { fclose ( idx->fp ) ; if (idx->d) free(idx->d); if (idx->gid) free(idx->gid); } /************************************************************************* * *N create_gazetteer_index * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To create a gazetteer file *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * * tablename == (char *) the name of an existing file * <= 11 chars long * idx_fname == (char *) name of index file * columnname == (char *) is a column existing in tablename * <= 24 chars long * * idx_set == (char *) is an array of printable ASCII characters * with no duplicates * * return value < 0 * * -1 some OS error, check errno for something more exact * -2 tablename is not a vpf table * -3 columnname is not in the vpf table * -4 column type not text * * return value = 0 * an index record for each character in index_set has been created * * the index file name is the same as tablename but with .?ti *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Jim Tenbrink * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * read_thematic_index_header see below * set_init SET.C * set_insert * Vpf_Read_* macros *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ ossim_int32 create_gazetteer_index (char *tablename, char *idx_fname , char *columnname, char *idx_set) { vpf_table_type t; row_type r; ossim_int32 c; FILE * idx_fp; ThematicIndexHeader gi; ThematicIndexDirectory * gid; set_type * idx_bit_sets; register ossim_int32 i, j; ossim_uint32 l, set_byte_size; t = vpf_open_table(tablename, disk, "rb", NULL); c = table_pos(strupr(columnname), t); if (t.header[c].type != 'T') { vpf_close_table(&t); return -4; } idx_fp = fopen(idx_fname, "wb"); if (idx_fp == NULL) return -1; /* only write out the table name, not the rest */ for ( i = (long)strlen ( tablename ); i > 0; i-- ) if ( tablename[i] == '/' ) break ; if ( i && (unsigned int)i < strlen (tablename) ) strcpy ( gi.vpf_table_name, strupr ( &tablename[i+1] ) ) ; else strcpy(gi.vpf_table_name, strupr ( tablename) ); strcpy(gi.vpf_column_name, columnname); gi.column_type = 'T'; gi.index_type = 'G'; gi.type_count = 1 ; gi.id_data_type = 'S' ; gi.nbins = (long)strlen(idx_set); gi.table_nrows = t.nrows; set_byte_size = (unsigned int)ceil(t.nrows/8.0); /* force input string to lower case , rdf */ for ( i=0; i < gi.nbins; i++ ) idx_set[i] = tolower ( idx_set[i] ) ; /* * ti.nbytes is the offset into the index file at which the * bit arrays start */ gi.nbytes = THEMATIC_INDEX_HEADER_SIZE + gi.nbins * ( sizeof (char) + DIRECTORY_SIZE ) ; gid = (ThematicIndexDirectory *) malloc(sizeof(ThematicIndexDirectory) * gi.nbins); idx_bit_sets = (set_type *) malloc(sizeof(set_type) * gi.nbins); for (i = 0; i < gi.nbins; i++) { idx_bit_sets[i] = set_init(t.nrows); gid[i].value.cval = idx_set[i]; gid[i].num_items = 1; } /* * lets suck up some CPU cycles here */ for (l = 0; (int)l < t.nrows; l++) { r = get_row(l+1, t); for (i = 0; i < gi.nbins; i++) for (j = 0; j < r[c].count; j++) /* No matter the input character, make it lower case , rdf added */ if ( tolower (*((char *) r[c].ptr + j)) == idx_set[i]) { set_insert(l, idx_bit_sets[i]); break; } free_row(r, t); } vpf_close_table(&t); if (write_thematic_index_header(gi, idx_fp) == (ossim_int32)0) { fclose(idx_fp); for (i = 0; i < gi.nbins; i++) set_nuke(&idx_bit_sets[i]); return -1; } if (write_gazetteer_index_directory(gi, gid, set_byte_size, idx_fp) == 0 ) { fclose(idx_fp); for (i = 0; i < gi.nbins; i++) set_nuke(&idx_bit_sets[i]); return -1; } for (i = 0; i < gi.nbins; i++) { if ( ! Write_Vpf_Char(idx_bit_sets[i].buf, idx_fp, set_byte_size) ) { fclose(idx_fp); for (i = 0; i < gi.nbins; i++) set_nuke(&idx_bit_sets[i]); return -1; } } fclose(idx_fp); for (i = 0; i < gi.nbins; i++) set_nuke(&idx_bit_sets[i]); free(idx_bit_sets); return 0; } /************************************************************************* * *N read_gazetteer_index * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To read an gazeeteer index file, and return a set type array *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * idx_fname == (char *) the name of a vpf gazetteer index * created with a call to to create_gaz_index. * * query_str == (char *) string that contains only characters * which form a subset of the characters passed * to create_gaz_index when idx_fname was created. * * the vpf table from which the file idx_fname was derived must * exist in the same directory as idx_fname * * out: case the returned set size > 0 * a bit array which can be used as a rough filter for the * vpf table from which the index file idx_fname was derived. * * bits which are set in the array are the record numbers in the vpf table * (from which idx_fname was derived) which may contain query_string * * case the returned set size = 0 * some system error occurred * most likely the indexed vpf table couldn't be found in the * same directory * * note: query_str is treated as a set, so duplicate occurrences * of the same character are ignored. I need a way of flagging * those duplicate occurrences. Instead of sorting the string * and removing duplicates, I use the num_items field in each * element of the directory array. * * Returns: * * set_type a set corresponding to the vpf table, where each * bit relates to the ID in the table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Jim Tenbrink * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * read_thematic_index_header see below * set_init SET.C * set_insert * Vpf_Read_* macros *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ set_type read_gazetteer_index (char *idx_fname, char *query_str ) { ThematicIndexHeader gi; ThematicIndexDirectory * gid; FILE * idx_fp; set_type query_set = {0, 0}, xsect_set, result_set; register int query_len = (int)strlen(query_str), i, j; unsigned long set_byte_size; char query_char; idx_fp = fopen(idx_fname, "rb"); if (idx_fp == NULL) return query_set; if (read_thematic_index_header (&gi, idx_fp) == (ossim_int32)0) { fclose(idx_fp); return query_set; } if (read_gazetteer_index_directory (&gid, &gi, idx_fp) == (ossim_int32)0) { fclose(idx_fp); return query_set; } for (j = 0; j < gi.nbins; j++) gid[j].num_items = 0; query_set = set_init(gi.table_nrows); xsect_set = set_init(gi.table_nrows); set_on(query_set); set_byte_size = (unsigned int)ceil(gi.table_nrows/8.0); for (i = 0; i < query_len; i++) { query_char = tolower(query_str[i]); for (j = 0; j < gi.nbins; j++) if (gid[j].value.cval == query_char) { gid[j].num_items++; break; } if (gid[j].num_items > 1) continue; fseek(idx_fp, gid[j].start_offset, 0); if ( ! Read_Vpf_Char(xsect_set.buf, idx_fp, set_byte_size) ) { set_type err = set_init ( 0 ) ; fclose(idx_fp); return err ; } result_set = set_intersection(query_set, xsect_set); set_assign(&query_set, result_set); set_nuke(&result_set); } fclose(idx_fp); free(gid); set_nuke(&xsect_set); return query_set; } /************************************************************************* * *N search_gazetteer_index * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To search an gazeeteer index file, and return a set type array *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * in : idx is the gazetteer index opened with open_thematic_index * * query_str contains only characters which form a subset of * the characters passed to create_gaz_index when idx_fname * was created * * the vpf table from which the file idx_fname was derived must * exist in the same directory as idx_fname * * out: case the returned set size > 0 * a bit array which can be used as a rough filter for the * vpf table from which the index file idx_fname was derived. * * bits which are set in the array are the record numbers in the vpf table * (from which idx_fname was derived) which may contain query_string * * case the returned set size = 0 * some system error occurred * most likely the indexed vpf table couldn't be found in the * same directory * * note: query_str is treated as a set, so duplicate occurrences * of the same character are ignored. I need a way of flagging * those duplicate occurrences. Instead of sorting the string * and removing duplicates, I use the num_items field in each * element of the directory array. * * Returns: * * set_type a set corresponding to the vpf table, where each * bit relates to the ID in the table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Jim Tenbrink * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * read_thematic_index_header see below * set_init SET.C * set_insert * Vpf_Read_* macros *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ set_type search_gazetteer_index (ThematicIndex *idx, char *query_str ) { set_type query_set = {0, 0, 0, 0}, xsect_set, result_set; register int query_len = (int)strlen(query_str), i, j; unsigned long set_byte_size; char query_char; if (idx->fp == NULL) return query_set; for (j = 0; j < idx->h.nbins; j++) idx->gid[j].num_items = 0; query_set = set_init(idx->h.table_nrows); xsect_set = set_init(idx->h.table_nrows); set_on(query_set); set_byte_size = (unsigned int)ceil(idx->h.table_nrows/8.0); for (i = 0; i < query_len; i++) { query_char = tolower(query_str[i]); for (j = 0; j < idx->h.nbins; j++) if (idx->gid[j].value.cval == query_char) { idx->gid[j].num_items++; break; } if (idx->gid[j].num_items > 1) continue; fseek(idx->fp, idx->gid[j].start_offset, 0); if ( ! Read_Vpf_Char(xsect_set.buf, idx->fp, set_byte_size) ) { set_type err = set_init ( 1 ) ; return err ; } result_set = set_intersection(query_set, xsect_set); set_assign(&query_set, result_set); set_nuke(&result_set); } set_nuke(&xsect_set); return query_set; } /************************************************************************* * *N read_gazetteer_index_directory * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To read an index file, regardless of its type ( T or G ) and * return a set type array *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * in : *gid is undefined * * *gi is the gazetteer index header for the open index file * referenced by idx_fp * * out: case return value is one * *gid is an array of directory entries with gi->nbin elements * * the sval member of the value union contains the indexed character * * the start_offset member of the directory structure contains the * disk offset for the start of the indexed characters bit array * * case zero return value * an error was probably encountered during the read * *gid is undefined *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * read_thematic_index_header see below * set_init SET.C * set_insert * Vpf_Read_* macros *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ ossim_int32 read_gazetteer_index_directory( ThematicIndexDirectory **gid, ThematicIndexHeader *gi, FILE *idx_fp) { int i; #if UNIX if ( fseek ( idx_fp,sizeof (ThematicIndexHeader)-sizeof(ossim_int32), 0 )!= 0 ) #else if (fseek(idx_fp, sizeof (ThematicIndexHeader), 0) != 0) #endif return 0 ; *gid = (ThematicIndexDirectory *) malloc(sizeof(ThematicIndexDirectory) * gi->nbins); if (*gid == NULL) return 0; for (i = 0; i < gi->nbins; i++) { if ( ( ! Read_Vpf_Char( &( (*gid)[i].value.cval ), idx_fp, 1) ) || ( ! Read_Vpf_Int( &( (*gid)[i].start_offset ), idx_fp, 1) ) || ( ! Read_Vpf_Int( &( (*gid)[i].num_items ), idx_fp, 1) )) { return (ossim_int32)0 ; } } return 1; } /************************************************************************* * *N read_thematic_index_header * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To read the thematic index header in a standard way *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * h < in/out > == (ThematicIndexHeader *) header structure to be filled * ifp == ( FILE *ifp ) index file pointer *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * Read_Vpf_Int * Read_Vpf_Char *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ #define RWhimper() {\ return (ossim_int32)0 ; } ossim_int32 read_thematic_index_header ( ThematicIndexHeader *h, FILE *ifp ) { if ( fseek ( ifp, 0, 0 ) != 0 ) /* rewind, just in case */ return 0 ; /* error */ if ( ! Read_Vpf_Int ( &h->nbytes, ifp, 1 ) ) RWhimper(); if ( ! Read_Vpf_Int ( &h->nbins, ifp, 1 ) ) RWhimper() ; if ( ! Read_Vpf_Int ( &h->table_nrows, ifp, 1 ) ) RWhimper() ; if ( ! Read_Vpf_Char ( &h->index_type, ifp, 1 ) ) RWhimper() ; if ( ! Read_Vpf_Char ( &h->column_type, ifp, 1 ) ) RWhimper() ; if ( ! Read_Vpf_Int ( &h->type_count, ifp, 1 ) ) RWhimper() ; if ( ! Read_Vpf_Char ( &h->id_data_type, ifp, 1 ) ) RWhimper() ; if ( ! Read_Vpf_Char ( &h->vpf_table_name, ifp, 12 ) ) RWhimper() ; if ( ! Read_Vpf_Char ( &h->vpf_column_name, ifp, 25 ) ) RWhimper() ; if ( ! Read_Vpf_Char ( &h->padding, ifp, 4 ) ) RWhimper() ; return 1 ; } /************************************************************************* * *N write_thematic_index_header * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To write the thematic index header in a standard way *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * h < input > == (ThematicIndexHeader) header structure to write from * ifp == ( FILE *ifp ) index file pointer *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * Write_Vpf_Int * Write_Vpf_Char *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ #define WWhimper() {\ return (ossim_int32)0 ; } ossim_int32 write_thematic_index_header ( ThematicIndexHeader h, FILE *ifp ) { if ( fseek ( ifp, 0, 0 ) != 0 ) /* rewind, just in case */ WWhimper() ; /* error */ if ( ! Write_Vpf_Int ( &h.nbytes, ifp, 1 ) ) WWhimper() ; if ( ! Write_Vpf_Int ( &h.nbins, ifp, 1 ) ) WWhimper() ; if ( ! Write_Vpf_Int ( &h.table_nrows, ifp, 1 ) ) WWhimper() ; if ( ! Write_Vpf_Char ( &h.index_type, ifp, 1 ) ) WWhimper() ; if ( ! Write_Vpf_Char ( &h.column_type, ifp, 1 ) ) WWhimper() ; if ( ! Write_Vpf_Int ( &h.type_count, ifp, 1 ) ) WWhimper() ; if ( ! Write_Vpf_Char ( &h.id_data_type, ifp, 1 ) ) WWhimper() ; if ( ! Write_Vpf_Char ( &h.vpf_table_name, ifp, 12 ) ) WWhimper() ; if ( ! Write_Vpf_Char ( &h.vpf_column_name, ifp, 25 ) ) WWhimper() ; if ( ! Write_Vpf_Char ( &h.padding, ifp, 4 ) ) WWhimper() ; return 1 ; } /************************************************************************* * *N write_thematic_index_directory * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To write the thematic index header in a standard way *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * h < input > == (ThematicIndexHeader) header structure * d < input > == (ThematicIndexDirectory *) directory array structure * idsize < input > == (ossim_int32) size of each data element. * for T indexes, this is either 2 bytes or 4 bytes * for G indexes, it will be num_in_set (set) * or the size of the bit array. * ifp == ( FILE *ifp ) index file pointer *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * Vpf_Write_* *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ #define WTWhimper() {\ return (ossim_int32)0 ; } ossim_int32 write_thematic_index_directory ( ThematicIndexHeader h, ThematicIndexDirectory *d, ossim_int32 idsize , /* size of data */ FILE *ifp ) { long int offset = h.nbytes , i ; /* rewind, just in case */ #if UNIX if ( fseek ( ifp, sizeof (ThematicIndexHeader)-sizeof(ossim_int32), 0 ) != 0 ) #else if ( fseek ( ifp, sizeof (ThematicIndexHeader), 0 ) != 0 ) #endif WTWhimper() ; for ( i=0; i < h.nbins; i++ ) { switch ( h.column_type ) { case 'I': if ( ! Write_Vpf_Int ( &d[i].value.ival, ifp, 1 ) ) WTWhimper() ; break ; case 'T': /* Not tested for text strings */ if ( ! Write_Vpf_Char ( &d[i].value.strval, ifp, h.type_count ) ) WTWhimper() ; break ; case 'S': if ( ! Write_Vpf_Short ( &d[i].value.sval, ifp, 1 ) ) WTWhimper() ; break ; case 'F': if ( ! Write_Vpf_Float ( &d[i].value.fval, ifp, 1 ) ) WTWhimper() ; break ; case 'R': if ( ! Write_Vpf_Double ( &d[i].value.dval, ifp, 1 ) ) WTWhimper() ; break ; } /* end of switch */ if ( ! Write_Vpf_Int ( &offset, ifp, 1 ) ) WTWhimper() ; if ( ! Write_Vpf_Int ( &d[i].num_items, ifp, 1 ) ) WTWhimper() ; /* this offset is constant, no matter the data type */ offset += ( idsize * d[i].num_items ) ; } /* end of i loop */ return 1 ; } /* end of write_directory */ /************************************************************************* * *N write_gazetteer_index_directory * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * To write the gazetteer thematic index header in a standard way *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * h < input > == (ThematicIndexHeader) header structure * d < input > == (ThematicIndexDirectory *) directory array structure * idsize < input > == (ossim_int32) size of each data element. * for T indexes, this is either 2 bytes or 4 bytes * for G indexes, it will be num_in_set (set) * or the size of the bit array. * ifp == ( FILE *ifp ) index file pointer *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn October 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * Vpf_Write_* *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ #define WTGWhimper() {\ return (ossim_int32)0 ; } ossim_int32 write_gazetteer_index_directory ( ThematicIndexHeader h, ThematicIndexDirectory *d, ossim_int32 idsize , /* size of data */ FILE *ifp ) { long int offset = h.nbytes , i ; /* rewind, just in case */ if ( fseek ( ifp, THEMATIC_INDEX_HEADER_SIZE, 0 )!= 0 ) WTWhimper() ; for ( i=0; i < h.nbins; i++ ) { if ( ! Write_Vpf_Char ( &d[i].value.cval, ifp, 1 ) ) WTGWhimper() ; if ( ! Write_Vpf_Int ( &offset, ifp, 1 ) ) WTGWhimper() ; if ( ! Write_Vpf_Int ( &d[i].num_items, ifp, 1 ) ) WTGWhimper() ; /* this offset is constant, no matter the data type */ offset += ( idsize * d[i].num_items ) ; } /* end of i loop */ return 1 ; } /* end of write_directory */ ossim-Miami-2.9.1/src/vpfutil/vpfwrite.c000066400000000000000000000562171352751253100202200ustar00rootroot00000000000000/************************************************************************* * *N Module VPFWRITE.C * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This contains functions for writing data to VPF tables. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * N/A *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Original Coding: Tom Wood Fall 1990 * Modifications: David Flinn January 1991 * July 1991 * Barry Michaels October 1991 * Modified from converter * software (UNIX) for * VPFVIEW software (DOS). * Jim TenBrink October 1991 * Made vpfread.c and vpfwrite.c * disjoint *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ #include #ifdef CARBON #define MACHINE_BYTE_ORDER 0 #endif #if __MSDOS__ #include #include #include #include #else #ifndef _WIN32 #include #endif #endif #if UNIX #include #define SEEK_SET 0 /* Turbo C fseek value */ #define SEEK_CUR 1 #define farmalloc malloc /* no farmallocs on UNIX */ #endif #include #include #include #include #include #include #include # ifndef min # define min(a,b) ((a) <= (b) ? (a) : (b)) # endif # ifndef max # define max(a,b) ((a) <= (b) ? (b) : (a)) # endif extern int STORAGE_BYTE_ORDER; /* Include statically to reduce external module dependencies */ /************************************************************************* * *N write_key * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function writes an id triplet key from the specified file. * It is assumed that there is enough free disk space to write to the * file. It is also assumed that the file pointer (fp) is already opened * for writing. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * key == (id_triplet_type) id triplet key. * fp == (FILE *) input file pointer. * return == (ossim_int32) size of the key. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn July 1991 Based on read_key in vpftable.c *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ ossim_int32 write_key( id_triplet_type key, FILE *fp ) { ossim_int32 size = 0 ; /* to count size of key write */ unsigned char tint ; ossim_int16 tshort ; /* Assume that any count value has been written before this */ /* Only write one key in this subroutine, do not write more */ Write_Vpf_Char (&(key.type),fp,1); size += sizeof ( char ) ; switch (TYPE0(key.type)) { case 0: break; case 1: tint = (unsigned char) key.id ; Write_Vpf_Char ( &tint, fp, 1 ) ; size += sizeof ( char ) ; break; case 2: tshort = (short) key.id ; Write_Vpf_Short ( &tshort, fp, 1 ) ; size += sizeof ( ossim_int16 ) ; break; case 3: Write_Vpf_Int (&(key.id), fp, 1 ) ; size += sizeof ( ossim_int32 ) ; break; } switch (TYPE1(key.type)) { case 0: break; case 1: tint = (unsigned char) key.tile ; Write_Vpf_Char ( &tint, fp, 1 ) ; size += sizeof ( char ) ; break; case 2: tshort = (short) key.tile ; Write_Vpf_Short ( &tshort, fp, 1 ) ; size += sizeof ( ossim_int16 ) ; break; case 3: Write_Vpf_Int (&(key.tile), fp, 1 ) ; size += sizeof ( ossim_int32 ) ; break; } switch (TYPE2(key.type)) { case 0: break; case 1: tint = (unsigned char) key.exid ; Write_Vpf_Char ( &tint, fp, 1 ) ; size += sizeof ( char ) ; break; case 2: tshort = (short) key.exid ; Write_Vpf_Short ( &tshort, fp, 1 ) ; size += sizeof ( ossim_int16 ) ; break; case 3: Write_Vpf_Int (&(key.exid), fp, 1 ) ; size += sizeof ( ossim_int32 ) ; break; } return size ; } /************************************************************************* * *N write_next_row * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function writes the next row of the table. * The parameter row must be initialized prior to this functional, either * by being read in from an existing table or set to valid values. * A row with any empty columns should not be written out. * The parameter table must be a valid table and initialized prior to * this function, by vpf_open_table. It is assumed that there is * enough free disk space to write to the file. It is also assumed that * the file pointer (table->fp) is already opened for writing. The * variable count, set to the values in row, must be greater than 0, * otherwise, if count is -1 the vpf_write functions will lock up * (row[].count should never have a value of 0). Note that if errorfp * is used, it must be opened prior to this function. * *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * row == (row_type) the row to write to the table. * table == (vpf_table_type *) vpf table structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Dave Flinn July 1991 Based on read_next_row. * Barry Michaels Oct 1991 Added row as a parameter. * JTB 10/91 guaranteed function always * returns a value: * 0: record written * -1: unknown field type *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ ossim_int32 write_next_row(row_type row, vpf_table_type * table ) { register ossim_int32 i, j; char * tptr, * output ; ossim_int32 recordsize = 0; ossim_int32 count; id_triplet_type * keys; ossim_uint32 pos_for_ndx, length; int retn_val = 0; coordinate_type dummycoord = {0.0,0.0}; STORAGE_BYTE_ORDER = table->byte_order; table->nrows++; fseek(table->fp, 0L, SEEK_END); pos_for_ndx = ftell(table->fp); /* begining of new row */ for (i = 0; i < table->nfields; i++) { /* for each column */ count = row[i].count ; /* Retrieve count from row. Should be 0 if variable length null */ /* In case this column is variable length, write out count */ if (count == 0) count = 1; if ( table->header[i].count < 0 ) { Write_Vpf_Int ( &count, table->fp, 1 ) ; recordsize += sizeof ( ossim_int32 ) ; } /* Now write out the data type */ switch (table->header[i].type) { case 'T': if ( count == 0 ) /* Assume this is variable length text and don't do anything */ break ; /* This loop insures that the exact number of characters are written out to disk. */ output = (char *) vpfmalloc ( count + 1 ) ; /* include null byte */ for (j = 0, tptr = (char*)row[i].ptr; j < count; j++, tptr++) if ( *tptr ) output[j] = *tptr ; else output[j] = SPACE ; output[count] = '\0' ; Write_Vpf_Char( output ,table->fp, count) ; free ( output ) ; recordsize += sizeof ( char ) * count ; break; case 'I': Write_Vpf_Int (row[i].ptr, table->fp, count ) ; recordsize += sizeof ( ossim_int32 ) * count ; break; case 'S': Write_Vpf_Short (row[i].ptr, table->fp, count ) ; recordsize += sizeof ( ossim_int16 ) * count ; break; case 'F': Write_Vpf_Float (row[i].ptr, table->fp, count ) ; recordsize += sizeof ( float ) * count ; break; case 'R': Write_Vpf_Double (row[i].ptr, table->fp, count ) ; recordsize += sizeof ( double ) * count ; break; case 'D': /* date has 21 chars in memory, not on disk */ Write_Vpf_Date (row[i].ptr, table->fp, count ) ; recordsize += ( sizeof ( date_type ) - 1 ) * count ; break; case 'C': if (row[i].ptr) { Write_Vpf_Coordinate(row[i].ptr,table->fp,count); } else { for (j=0;jfp,count); } recordsize += sizeof ( coordinate_type ) * count ; break; case 'B': Write_Vpf_DoubleCoordinate(row[i].ptr,table->fp,count); recordsize += sizeof ( double_coordinate_type ) * count ; break; case 'Z': Write_Vpf_CoordinateZ(row[i].ptr,table->fp,count); recordsize += sizeof ( tri_coordinate_type ) * count ; break; case 'Y': Write_Vpf_DoubleCoordinateZ(row[i].ptr,table->fp,count); recordsize += sizeof ( double_tri_coordinate_type ) * count ; break; case 'K': keys = (id_triplet_type *) vpfmalloc (count*sizeof(id_triplet_type)) ; memcpy ( keys, row[i].ptr, count*sizeof(id_triplet_type) ) ; for (j=0;jfp); free ( keys ) ; break; case 'X': /* do nothing */ break; default: return(-1); } } if ( table->xfp ) { /* only for variable length columns */ length = recordsize ; fseek( table->xfp, 0, SEEK_END ); Write_Vpf_Int ( &pos_for_ndx, table->xfp, 1 ) ; Write_Vpf_Int ( &length, table->xfp, 1 ) ; } return retn_val; } /************************************************************************* * *N create_row * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function creates a null row for the given table. * The parameter table must be a valid table and initialized prior to * this function, by vpf_open_table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * table == (vpf_table_type) vpf table structure. * return == (row_type) row of the table. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels Oct 1991 *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ row_type create_row( vpf_table_type table ) { ossim_int32 i; row_type row; row = (row_type)vpfmalloc(table.nfields*sizeof(column_type)); for (i=0;i == (ossim_int32) column offset. * row == (row_type) row containing element to be removed. * table == (vpf_table_type) VPF table owning row. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * RDF 7/91 original * JTB 10/91 removed call to exit(); *E *************************************************************************/ void nullify_table_element( ossim_int32 field, row_type row, vpf_table_type table ) { if (field < 0 || field >= table.nfields) return; if (row[field].ptr) { free(row[field].ptr); row[field].ptr = NULL; row[field].count = table.header[field].count; } } /************************************************************************* * *N put_table_element * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * Copies one element into the designated field. * The parameter row must be initialized prior to this functional, either * buy being read in from an existing table or set to valid values. The * parameter table must be a valid table and initialized prior to this * function, by vpf_open_table. Note that if errorfp is used, it must * be opened prior to this function. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * field == (ossim_int32) column offset. * row == (row_type) row containing target field. * table == (vpf_table_type) VPF table owning row. * value == (void *) source field element. * count == (ossim_int32) number of items in value. * put_table_element == (ossim_int32) * 0 --> element write succeeded * 1 --> unknown element type or * invalid column offset *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * RDF 7/91 original * JTB 10/91 removed call to exit(); * guaranteed function always returns value * 0: element write succeeded * -1: unknown element type or invalid column (field) offset *E *************************************************************************/ ossim_int32 put_table_element( ossim_int32 field, row_type row, vpf_table_type table, void * value, ossim_int32 count ) { ossim_int32 i, len, stat; char *str; stat=0; if ((count != table.header[field].count) && (table.header[field].count > 0)) { printf("Invalid element count! (%d, %d)\n", count,table.header[field].count); return -1; } if (field < 0 || field >= table.nfields) return -1; row[field].count = count; if (row[field].ptr) { free(row[field].ptr); row[field].ptr = NULL; } switch ( table.header[field].type ) { case 'T': len = (ossim_int32)max(count,table.header[field].count); str = (char *) vpfmalloc( len + 1 ); row[field].ptr = (char *) vpfmalloc ( len + 1 ) ; strcpy( (char*)str, (char*)value ); for ( i = (long)strlen((char*)value) ; i < table.header[field].count; i++ ) str[i] = SPACE ; str[len] = '\0'; memcpy(row[field].ptr, str, len+1); free(str); break ; case 'D': row[field].ptr = (date_type *) vpfmalloc (count*sizeof(date_type)); memcpy ( row[field].ptr, value, sizeof (date_type) * count ) ; break; case 'I' : row[field].ptr = (ossim_int32 *) vpfmalloc (count*sizeof(ossim_int32)); memcpy ( row[field].ptr, value, sizeof (ossim_int32) * count ) ; break; case 'S' : row[field].ptr = (ossim_int16 *) vpfmalloc (count*sizeof(ossim_int16)); memcpy ( row[field].ptr, value, sizeof (ossim_int16) * count ) ; break; case 'F': row[field].ptr = (float *) vpfmalloc (count*sizeof(float)); memcpy ( row[field].ptr, value, sizeof (float) * count ) ; break; case 'R': row[field].ptr = (double *) vpfmalloc (count*sizeof(double)); memcpy ( row[field].ptr, value, sizeof (double) * count ) ; break; case 'K': row[field].ptr = (id_triplet_type *) vpfmalloc ( count*sizeof(id_triplet_type )); memcpy ( row[field].ptr, value, sizeof(id_triplet_type)*count ) ; break; case 'C': if (value) { row[field].ptr = (coordinate_type *) malloc ( count * sizeof( coordinate_type )); if (row[field].ptr) memcpy ( row[field].ptr, value, sizeof(coordinate_type)*count ) ; } else { row[field].ptr = NULL; } break; case 'Z': if (value) { row[field].ptr = (tri_coordinate_type *) malloc ( count * sizeof( tri_coordinate_type )); if (row[field].ptr) memcpy ( row[field].ptr, value, sizeof(tri_coordinate_type)*count ) ; } else { row[field].ptr = NULL; } break; case 'B': if (value) { row[field].ptr = (double_coordinate_type *) malloc ( count * sizeof( double_coordinate_type )); if (row[field].ptr) memcpy ( row[field].ptr, value, sizeof(double_coordinate_type)*count ) ; } else { row[field].ptr = NULL; } break; case 'Y': if (value) { row[field].ptr = (double_tri_coordinate_type *) malloc ( count * sizeof( double_tri_coordinate_type )); if (row[field].ptr) memcpy( row[field].ptr, value, sizeof(double_tri_coordinate_type)*count); } else { row[field].ptr = NULL; } break; default: stat = -1; break ; } return stat; } /* ======================================================================== Environmental Systems Research Institute (ESRI) Applications Programming Project: Conversion from ARC/INFO to VPF Original Coding: Tom Wood Fall 1990 Modifications: David Flinn January 1991 July 1991 JTB 10/91 The following functions are used when writing from a big-endian machine. VPF requires little-endian words, so byte-swapping must be performed. ======================================================================== */ /* #ifdef UNIX */ ossim_int32 VpfWrite ( void *from, VpfDataType type, ossim_int32 count, FILE *to ) { ossim_int32 retval=0 , i ; switch ( type ) { case VpfChar: retval = (long)fwrite ( from, sizeof (char), count, to ) ; break ; case VpfShort: { if (MACHINE_BYTE_ORDER != STORAGE_BYTE_ORDER) { ossim_int16 stemp , *sptr = (short *) from ; for ( i=0; i < count; i++, sptr++ ) { swap_two ( (char*)sptr, (char*)&stemp ) ; retval = (long)fwrite ( &stemp, sizeof (short), 1, to ) ; } } else { retval = (long)fwrite ( from, sizeof (short), count, to ) ; } } break ; case VpfInteger: { if (MACHINE_BYTE_ORDER != STORAGE_BYTE_ORDER) { ossim_int32 itemp, *iptr = (ossim_int32 *) from ; for ( i=0; i < count; i++, iptr++ ) { swap_four ( (char*)iptr, (char*)&itemp ) ; retval = (long)fwrite ( &itemp, sizeof (ossim_int32), 1, to ) ; } } else { retval = (long)fwrite ( from, sizeof (ossim_int32), count, to ) ; } } break ; case VpfFloat: { if (MACHINE_BYTE_ORDER != STORAGE_BYTE_ORDER) { float ftemp , *fptr = (float *) from ; for ( i=0; i < count; i++, fptr++ ) { swap_four ( (char*)fptr, (char*)&ftemp ) ; retval = (long)fwrite ( &ftemp, sizeof (float), 1, to ) ; } } else { retval = (long)fwrite ( from, sizeof (ossim_int32), count, to ) ; } } break ; case VpfDouble: { if (MACHINE_BYTE_ORDER != STORAGE_BYTE_ORDER) { double dtemp , *dptr = (double *) from ; for ( i=0; i < count; i++, dptr++ ) { swap_eight ( (char*)dptr, (char*)&dtemp ) ; retval = (long)fwrite ( &dtemp, sizeof (double), 1, to ) ; } } else { retval = (long)fwrite ( from, sizeof (double), count, to ) ; } } break ; case VpfDate: /* only write out 20, not 21 chars */ retval = (long)fwrite ( from, sizeof ( date_type ) - 1, count, to ) ; break ; case VpfCoordinate: { if (MACHINE_BYTE_ORDER != STORAGE_BYTE_ORDER) { coordinate_type ctemp , *cptr = (coordinate_type *) from ; for ( i=0; i < count; i++, cptr++ ) { swap_four ( (char*)&cptr->x, (char*)&ctemp.x ) ; swap_four ( (char*)&cptr->y, (char*)&ctemp.y ) ; retval = (long)fwrite ( &ctemp, sizeof (coordinate_type), 1, to ) ; } } else { retval = (long)fwrite ( from, sizeof (coordinate_type), count, to ) ; } } break ; case VpfDoubleCoordinate: { if (MACHINE_BYTE_ORDER != STORAGE_BYTE_ORDER) { double_coordinate_type dctemp , *dcptr = (double_coordinate_type *) from ; for ( i=0; i < count; i++, dcptr++ ) { swap_eight ( (char*)&dcptr->x, (char*)&dctemp.x ) ; swap_eight ( (char*)&dcptr->y, (char*)&dctemp.y ) ; retval = (long)fwrite ( &dctemp, sizeof (double_coordinate_type), 1, to ) ; } } else { retval = (long)fwrite ( from, sizeof (double_coordinate_type), count, to ) ; } } break ; case VpfTriCoordinate: { if (MACHINE_BYTE_ORDER != STORAGE_BYTE_ORDER) { tri_coordinate_type ttemp , *tptr = (tri_coordinate_type *) from ; for ( i=0; i < count; i++, tptr++ ) { swap_four ( (char*)&tptr->x, (char*)&ttemp.x ) ; swap_four ( (char*)&tptr->y, (char*)&ttemp.y ) ; swap_four ( (char*)&tptr->z, (char*)&ttemp.z ) ; retval = (long)fwrite ( &ttemp, sizeof (tri_coordinate_type), 1, to ) ; } } else { retval = (long)fwrite ( from, sizeof (tri_coordinate_type), count, to ) ; } } break ; case VpfDoubleTriCoordinate: { if (MACHINE_BYTE_ORDER != STORAGE_BYTE_ORDER) { double_tri_coordinate_type dttemp , *dtptr = (double_tri_coordinate_type *) from ; for ( i=0; i < count; i++, dtptr++ ) { swap_eight ( (char*)&dtptr->x, (char*)&dttemp.x ) ; swap_eight ( (char*)&dtptr->y, (char*)&dttemp.y ) ; swap_eight ( (char*)&dtptr->z, (char*)&dttemp.z ) ; retval = (long)fwrite ( &dttemp,sizeof (double_tri_coordinate_type), 1, to); } } else { retval = (long)fwrite ( from,sizeof (double_tri_coordinate_type), count, to); } } break ; case VpfNull: /* Do Nothing */ break ; default: break ; } return retval; } /* #endif */ ossim-Miami-2.9.1/support/000077500000000000000000000000001352751253100154275ustar00rootroot00000000000000ossim-Miami-2.9.1/support/linux/000077500000000000000000000000001352751253100165665ustar00rootroot00000000000000ossim-Miami-2.9.1/support/linux/etc/000077500000000000000000000000001352751253100173415ustar00rootroot00000000000000ossim-Miami-2.9.1/support/linux/etc/ld.so.conf.d/000077500000000000000000000000001352751253100215265ustar00rootroot00000000000000ossim-Miami-2.9.1/support/linux/etc/ld.so.conf.d/ossim.conf000066400000000000000000000001141352751253100235230ustar00rootroot00000000000000# Add lib path for ossim for non-standard install: # /usr/local/ossim/lib64 ossim-Miami-2.9.1/support/linux/etc/profile.d/000077500000000000000000000000001352751253100212235ustar00rootroot00000000000000ossim-Miami-2.9.1/support/linux/etc/profile.d/ossim.csh000066400000000000000000000010261352751253100230530ustar00rootroot00000000000000#--- # Open Source Software Image Map(OSSIM) csh initialization script (csh). # This file is installed by ossim rpm in: /etc/profile.d/ossim.csh #--- if ( ! $?OSSIM_INSTALL_PREFIX ) then setenv OSSIM_INSTALL_PREFIX "/usr" endif if ( ( ! $?OSSIM_PREFS_FILE ) then setenv OSSIM_PREFS_FILE $OSSIM_INSTALL_PREFIX/share/ossim/ossim-site-preferences endif #--- # Stub to set path for non-standard install: #--- # set ossim_bin=/usr/local/ossim/bin # if ( "${path}" !~ *$ossim_bin* ) then # set path = ( $ossim_bin $path ) # endif ossim-Miami-2.9.1/support/linux/etc/profile.d/ossim.sh000066400000000000000000000010361352751253100227110ustar00rootroot00000000000000#--- # Open Source Software Image Map(OSSIM) bash initialization script (sh). # This file is installed by ossim rpm in: /etc/profile.d/ossim.sh #--- if [ -z "$OSSIM_INSTALL_PREFIX" ]; then export OSSIM_INSTALL_PREFIX=/usr fi if [ -z "$OSSIM_PREFS_FILE" ]; then export OSSIM_PREFS_FILE=$OSSIM_INSTALL_PREFIX/share/ossim/ossim-site-preferences fi #--- # Stub to set path for non-standard install: #--- # ossim_bin=/usr/local/ossim/bin # if ! echo ${PATH} | /bin/grep -q $ossim_bin ; then # PATH=$ossim_bin:${PATH} # fi # export PATH ossim-Miami-2.9.1/support/linux/rpm_specs/000077500000000000000000000000001352751253100205615ustar00rootroot00000000000000ossim-Miami-2.9.1/support/linux/rpm_specs/ossim-all-el6.spec000066400000000000000000000367201352751253100240310ustar00rootroot00000000000000#--- # File: ossim-all-el6.spec # # Spec file for building ossim rpms with rpmbuild. # # NOTE: This files differs from ossim-all-el7.spec in that it needs libtiff4 # to pick up bigtiff support. # # Example usage: # rpmbuild -ba --define 'RPM_OSSIM_VERSION 1.9.0' --define 'BUILD_RELEASE 1' ossim-el7.spec # # Caveats: # 1) Builder/user needs "groovy" in their search path. # 2) Use "archive.sh" script in ossim/scripts/archive.sh to generate the source # tar ball, e.g. ossim-1.9.0.tar.gz, from appropriate git branch. #--- Name: ossim Version: %{RPM_OSSIM_VERSION} Release: %{BUILD_RELEASE}%{?dist} Summary: Open Source Software Image Map library and command line applications Group: System Environment/Libraries #TODO: Which version? License: LGPLv2+ URL: https://github.com/orgs/ossimlabs/dashboard Source0: http://download.osgeo.org/ossim/source/%{name}-%{version}.tar.gz BuildRequires: ant BuildRequires: cmake BuildRequires: ffmpeg-devel BuildRequires: gdal-devel BuildRequires: geos-devel # BuildRequires: hdf4-devel BuildRequires: hdf5a-devel BuildRequires: java-devel BuildRequires: libcurl-devel BuildRequires: libgeotiff-devel BuildRequires: libjpeg-devel BuildRequires: libpng-devel BuildRequires: libtiff4-devel #BuildRequires: libRaw-devel BuildRequires: minizip-devel BuildRequires: opencv-devel BuildRequires: OpenSceneGraph-devel BuildRequires: OpenThreads-devel BuildRequires: podofo-devel BuildRequires: qt4-devel BuildRequires: sqlite-devel BuildRequires: gpstk-devel BuildRequires: openjpeg2-devel #BuildRequires: swig Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description OSSIM is a powerful suite of geospatial libraries and applications used to process remote sensing imagery, maps, terrain, and vector data. %package devel Summary: Develelopment files for ossim Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description devel Development files for ossim. %package libs Summary: Develelopment files for ossim Group: System Environment/Libraries %description libs Libraries for ossim. %package geocell Summary: Desktop electronic light table Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description geocell Desktop electronic light table for geospatial image processing. Has 2D, 2 1/2D and 3D viewer with image chain editing capabilities. %package oms Summary: Wrapper library/java bindings for interfacing with ossim. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description oms This sub-package contains the oms wrapper library with java bindings for interfacing with the ossim library from java. %package oms-devel Summary: Development files for ossim oms wrapper library. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description oms-devel This sub-package contains the development files for oms. %package planet Summary: 3D ossim library interface via OpenSceneGraph Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description planet 3D ossim library interface via OpenSceneGraph. %package planet-devel Summary: Development files for ossim planet. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description planet-devel This sub-package contains development files for ossim planet. %package test-apps Summary: Ossim test apps. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description test-apps A suite of ossim test apps. %package video Summary: Ossim vedeo library. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description video Ossim vedeo library. %package video-devel Summary: Development files for ossim planet. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description video-devel This sub-package contains development files for ossim planet. # libwms does not depend on ossim %package wms Summary: wms ossim library Group: System Environment/Libraries %description wms This sub-package contains the web mapping service (wms) library. %package wms-devel Summary: Development files libwms Group: System Environment/Libraries Requires: libwms%{?_isa} = %{version}-%{release} %description wms-devel This sub-package contains the development files for libwms. #--- # ossim plugins: #--- %package cnes-plugin Summary: Plugin with various sensor models Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description cnes-plugin This sub-package contains the ossim plugin which has various SAR sensor models, readers, and support data parsers. Most of this code was provided by the ORFEO Toolbox (OTB) group / Centre national d'études spatiales. %package gdal-plugin Summary: GDAL ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description gdal-plugin This sub-package contains the Geospatial Data Abstraction Library(gdal) ossim plugin for reading/writing images supported by the gdal library. %package geopdf-plugin Summary: geopdf ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description geopdf-plugin This sub-package contains the geopdf ossim plugin for reading geopdf files via the podofo library. %package hdf5-plugin Summary: HDF5 ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description hdf5-plugin This sub-package contains the Hierarchical Data Format(hdf) ossim plugin for reading hdf5 images via the hdf5 libraries %package jpip-server Summary: ossim kakadu jpip server Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} Requires: kakadu-plugin%{?_isa} = %{version}-%{release} %description jpip-server This sub-package contains the ossim kakadu jpip server for streaming J2K compressed data to via the Kakadu library. %package kml-plugin Summary: kml ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description kml-plugin This sub-package contains the kmlsuperoverlay ossim plugin for reading/writing kml super overlays. %package kakadu-plugin Summary: kakadu ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description kakadu-plugin This sub-package contains the kakadu ossim plugin for reading/writing J2K compressed data via the Kakadu library. %package mrsid-plugin Summary: mrsid ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description mrsid-plugin This sub-package contains the mrsid ossim plugin for reading/writing mrsid compressed data via the MrSID library. %package opencv-plugin Summary: OSSIM OpenCV plugin, contains registration code. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description opencv-plugin This sub-package contains the ossim opencv plugin with various pieces of image registration code. %package openjpeg-plugin Summary: OpenJPEG ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description openjpeg-plugin This sub-package contains the OpenJPEG ossim plugin for reading/writing J2K compressed images via the OpenJPEG library. %package png-plugin Summary: PNG ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description png-plugin This sub-package contains the Portable Network Graphic(png) ossim plugin for reading/writing png images via the png library. %package sqlite-plugin Summary: OSSIM sqlite plugin, contains GeoPackage reader/writer. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description sqlite-plugin This sub-package contains GeoPackage reader/writer. %package web-plugin Summary: web ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description web-plugin This sub-package contains the web ossim plugin for interfacing with http via curl library. %prep #--- # Notes for debugging: # Using the "%setup -q -D -T" is handy debugging. # -D on setup = Do not delete the directory before unpacking. # -T on setup = Disable the automatic unpacking of the archives. #--- # %setup -q -D -T # %setup -q -D %setup -q # Delete bundled libraw rm -rf ossim_plugins/libraw/LibRaw-0.9.0/ %build # Exports for ossim abuild: export OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo export OSSIM_INSTALL_PREFIX=/usr export OSSIM_VERSION=%{RPM_OSSIM_VERSION} mkdir -p build pushd build %cmake \ -DOSSIM_BUILD_ADDITIONAL_DIRECTORIES=$OSSIM_DEV_HOME/ossim-private/ossim-kakadu-jpip-server \ -DBUILD_CSMAPI=OFF \ -DBUILD_OMS=ON \ -DBUILD_OSSIM=ON \ -DBUILD_OSSIM_APPS=ON \ -DBUILD_OSSIM_CURL_APPS=ON \ -DBUILD_OSSIM_GUI=ON \ -DBUILD_OSSIM_TESTS=ON \ -DBUILD_OSSIM_MPI_SUPPORT=OFF \ -DBUILD_OSSIM_PLANET=ON \ -DBUILD_OSSIM_PLANET_QT=OFF \ -DBUILD_OSSIM_VIDEO=ON \ \ -DBUILD_CNES_PLUGIN=ON \ -DBUILD_CONTRIB_PLUGIN=OFF \ -DBUILD_CSM_PLUGIN=OFF \ -DBUILD_GDAL_PLUGIN=ON \ -DBUILD_GEOPDF_PLUGIN=ON \ -DBUILD_HDF5_PLUGIN=ON \ -DBUILD_KAKADU_PLUGIN=ON \ -DBUILD_KML_PLUGIN=ON \ -DBUILD_LIBRAW_PLUGIN=OFF \ -DBUILD_MRSID_PLUGIN=ON \ -DBUILD_OSSIMMRSID_PLUGIN=ON \ -DBUILD_NDF_PLUGIN=OFF \ -DBUILD_OPENCV_PLUGIN=ON \ -DBUILD_OPENJPEG_PLUGIN=ON \ -DBUILD_PDAL_PLUGIN=OFF \ -DBUILD_PNG_PLUGIN=ON \ -DBUILD_REGISTRATION_PLUGIN=OFF \ -DBUILD_SQLITE_PLUGIN=ON \ -DBUILD_WEB_PLUGIN=ON \ \ -DBUILD_RUNTIME_DIR=bin \ -DBUILD_SHARED_LIBS=ON \ -DBUILD_WMS=ON \ \ -DOSSIMPLANET_ENABLE_EPHEMERIS=OFF \ \ -DCMAKE_BUILD_TYPE=$OSSIM_BUILD_TYPE \ -DCMAKE_MODULE_PATH=$OSSIM_DEV_HOME/ossim_package_support/cmake/CMakeModules \ -DCMAKE_PREFIX_PATH=/usr \ \ -DKAKADU_ROOT_SRC=/opt/kakadu/latest \ -DKAKADU_AUX_LIBRARY=/opt/kakadu/latest/lib/Linux-x86-64-gcc/libkdu_aux.a \ -DKAKADU_LIBRARY=/opt/kakadu/latest/lib/Linux-x86-64-gcc/libkdu.a \ \ -DMRSID_DIR=/opt/mrsid/latest \ \ ../ossim/cmake make VERBOSE=1 %{?_smp_mflags} popd # Exports for java builds: export JAVA_HOME=/usr/lib/jvm/java #export JAVA_HOME=/usr/java/latest # Build c++ jni bindings and java side of oms module: pushd ossim-oms/joms cp local.properties.template local.properties ant popd %install # Exports for ossim install: export OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo export OSSIM_VERSION=%{RPM_OSSIM_VERSION} pushd build make install DESTDIR=%{buildroot} popd install -p -m644 -D ossim/support/linux/etc/profile.d/ossim.sh %{buildroot}%{_sysconfdir}/profile.d/ossim.sh install -p -m644 -D ossim/support/linux/etc/profile.d/ossim.csh %{buildroot}%{_sysconfdir}/profile.d/ossim.csh install -p -m644 -D ossim/share/ossim/templates/ossim_preferences_template %{buildroot}%{_datadir}/ossim/ossim-preferences-template # Exports for java builds: export JAVA_HOME=/usr/lib/jvm/java #export JAVA_HOME=/usr/java/latest export OSSIM_INSTALL_PREFIX=%{buildroot}/usr # mrsid libraries: # Need to replace /opt/mrsid/latest with variable later install -p -m755 -D /opt/mrsid/latest/Lidar_DSDK/lib/liblti_lidar_dsdk.so %{buildroot}%{_libdir} install -p -m755 -D /opt/mrsid/latest/Raster_DSDK/lib/libltidsdk.so %{buildroot}%{_libdir} # oms "ant" build: pushd ossim-oms/joms ant dist ant install # ant mvn-install # Fix bad perms: chmod 755 %{buildroot}%{_libdir}/libjoms.so popd %post /sbin/ldconfig # First time through create the site preferences. if [ ! -f %{_datadir}/ossim/ossim-site-preferences ]; then cp %{_datadir}/ossim/ossim-preferences-template %{_datadir}/ossim/ossim-site-preferences fi %post oms /sbin/ldconfig rm -f %{_javadir}/joms.jar ln -s %{_javadir}/joms-%{version}.jar %{_javadir}/joms.jar %post planet /sbin/ldconfig %post wms /sbin/ldconfig %postun /sbin/ldconfig %postun oms /sbin/ldconfig rm -f %{_javadir}/joms.jar %postun planet /sbin/ldconfig %postun wms /sbin/ldconfig %files %{_bindir}/* # Weed out apps: %exclude %{_bindir}/ossim-*-test %exclude %{_bindir}/ossim-adrg-dump %exclude %{_bindir}/ossim-btoa %exclude %{_bindir}/ossim-computeSrtmStats %exclude %{_bindir}/ossim-correl %exclude %{_bindir}/ossim-create-bitmask %exclude %{_bindir}/ossim-dump-ocg %exclude %{_bindir}/ossim-image-compare %exclude %{_bindir}/ossim-modopt %exclude %{_bindir}/ossimplanetklv %exclude %{_bindir}/ossimplanet-chip %exclude %{_bindir}/ossimplanettest %exclude %{_bindir}/ossim-rejout %exclude %{_bindir}/ossim-rpf %exclude %{_bindir}/ossim-senint %exclude %{_bindir}/ossim-space-imaging %exclude %{_bindir}/ossim-src2src %exclude %{_bindir}/ossim-swapbytes %exclude %{_bindir}/ossim-ws-cmp # These are in the geocell package: %exclude %{_bindir}/ossim-geocell %exclude %{_bindir}/ossimplanetviewer # In jpip-server package: %exclude %{_bindir}/ossim-jpip-server %files devel %{_includedir}/ossim %files libs %{_datadir}/ossim/ %doc ossim/LICENSE.txt %{_libdir}/libossim.so* %{_libdir}/pkgconfig/ossim.pc %{_sysconfdir}/profile.d/ossim.sh %{_sysconfdir}/profile.d/ossim.csh %files geocell %{_bindir}/ossim-geocell %{_libdir}/libossimGui.so* %files oms %{_javadir}/joms-%{version}.jar %{_libdir}/libjoms.so %{_libdir}/liboms.so* %files oms-devel %{_includedir}/oms/ %files planet # %{_bindir}/ossimplanet %{_bindir}/ossimplanetviewer %{_libdir}/libossim-planet.so* # %{_libdir}/libossimPlanetQt.so* %files planet-devel %{_includedir}/ossimPlanet %files test-apps %{_bindir}/ossim-*-test %files video %{_libdir}/libossim-video.so* %files video-devel %{_includedir}/ossimPredator %files wms %{_includedir}/wms/ %{_libdir}/libossim-wms.so* #--- # ossim plugins #--- %files cnes-plugin %{_libdir}/ossim/plugins/libossim_cnes_plugin.so %files gdal-plugin %{_libdir}/ossim/plugins/libossim_gdal_plugin.so %files geopdf-plugin %{_libdir}/ossim/plugins/libossim_geopdf_plugin.so %files hdf5-plugin %{_libdir}/ossim/plugins/libossim_hdf5_plugin.so %files jpip-server %{_bindir}/ossim-jpip-server %files kml-plugin %{_libdir}/ossim/plugins/libossim_kml_plugin.so %files kakadu-plugin %{_libdir}/ossim/plugins/libossim_kakadu_plugin.so %{_libdir}/libkdu_a75R.so %{_libdir}/libkdu_v75R.so %files mrsid-plugin %{_libdir}/ossim/plugins/libossim_mrsid_plugin.so %{_libdir}/liblti_lidar_dsdk.so %{_libdir}/libltidsdk.so %files opencv-plugin %{_libdir}/ossim/plugins/libossim_opencv_plugin.so %files openjpeg-plugin %{_libdir}/ossim/plugins/libossim_openjpeg_plugin.so %files png-plugin %{_libdir}/ossim/plugins/libossim_png_plugin.so %files sqlite-plugin %{_libdir}/ossim/plugins/libossim_sqlite_plugin.so %files web-plugin %{_libdir}/ossim/plugins/libossim_web_plugin.so %changelog * Sun Dec 29 2013 Volker Fröhlich - yes-1 - Initial package ossim-Miami-2.9.1/support/linux/rpm_specs/ossim-all-el7.spec000066400000000000000000000370011352751253100240230ustar00rootroot00000000000000#--- # File: ossim-all-el7.spec # # Spec file for building ossim rpms with rpmbuild. # # NOTE: This files differs from ossim-all-el6.spec in that it does not need # libtiff4 to pick up bigtiff support as libtiff is version 4.x. # # Example usage: # rpmbuild -ba --define 'RPM_OSSIM_VERSION 1.9.0' --define 'BUILD_RELEASE 1' ossim-el7.spec # # Caveats: # 1) Builder/user needs "groovy" in their search path. # 2) Use "archive.sh" script in ossim/scripts/archive.sh to generate the source # tar ball, e.g. ossim-1.9.0.tar.gz, from appropriate git branch. #--- Name: ossim Version: %{RPM_OSSIM_VERSION} Release: %{BUILD_RELEASE}%{?dist} Summary: Open Source Software Image Map library and command line applications Group: System Environment/Libraries #TODO: Which version? License: LGPLv2+ URL: https://github.com/orgs/ossimlabs/dashboard Source0: http://download.osgeo.org/ossim/source/%{name}-%{version}.tar.gz BuildRequires: ant BuildRequires: cmake BuildRequires: ffmpeg-devel BuildRequires: gdal-devel BuildRequires: geos-devel # BuildRequires: hdf4-devel BuildRequires: hdf5a-devel BuildRequires: java-devel BuildRequires: libcurl-devel BuildRequires: libgeotiff-devel BuildRequires: libjpeg-devel BuildRequires: libpng-devel BuildRequires: libtiff-devel #BuildRequires: libRaw-devel BuildRequires: minizip-devel BuildRequires: opencv-devel BuildRequires: OpenSceneGraph-devel BuildRequires: OpenThreads-devel BuildRequires: podofo-devel BuildRequires: qt4-devel BuildRequires: sqlite-devel BuildRequires: gpstk-devel BuildRequires: openjpeg2-devel #BuildRequires: swig Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description OSSIM is a powerful suite of geospatial libraries and applications used to process remote sensing imagery, maps, terrain, and vector data. %package devel Summary: Develelopment files for ossim Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description devel Development files for ossim. %package libs Summary: Develelopment files for ossim Group: System Environment/Libraries %description libs Libraries for ossim. %package geocell Summary: Desktop electronic light table Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description geocell Desktop electronic light table for geospatial image processing. Has 2D, 2 1/2D and 3D viewer with image chain editing capabilities. %package oms Summary: Wrapper library/java bindings for interfacing with ossim. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description oms This sub-package contains the oms wrapper library with java bindings for interfacing with the ossim library from java. %package oms-devel Summary: Development files for ossim oms wrapper library. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description oms-devel This sub-package contains the development files for oms. %package planet Summary: 3D ossim library interface via OpenSceneGraph Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description planet 3D ossim library interface via OpenSceneGraph. %package planet-devel Summary: Development files for ossim planet. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description planet-devel This sub-package contains development files for ossim planet. %package test-apps Summary: Ossim test apps. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description test-apps A suite of ossim test apps. %package video Summary: Ossim vedeo library. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description video Ossim vedeo library. %package video-devel Summary: Development files for ossim planet. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description video-devel This sub-package contains development files for ossim planet. # libwms does not depend on ossim %package wms Summary: wms ossim library Group: System Environment/Libraries %description wms This sub-package contains the web mapping service (wms) library. %package wms-devel Summary: Development files libwms Group: System Environment/Libraries Requires: libwms%{?_isa} = %{version}-%{release} %description wms-devel This sub-package contains the development files for libwms. #--- # ossim plugins: #--- %package cnes-plugin Summary: Plugin with various sensor models Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description cnes-plugin This sub-package contains the ossim plugin which has various SAR sensor models, readers, and support data parsers. Most of this code was provided by the ORFEO Toolbox (OTB) group / Centre national d'études spatiales. %package gdal-plugin Summary: GDAL ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description gdal-plugin This sub-package contains the Geospatial Data Abstraction Library(gdal) ossim plugin for reading/writing images supported by the gdal library. %package geopdf-plugin Summary: geopdf ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description geopdf-plugin This sub-package contains the geopdf ossim plugin for reading geopdf files via the podofo library. %package hdf5-plugin Summary: HDF5 ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description hdf5-plugin This sub-package contains the Hierarchical Data Format(hdf) ossim plugin for reading hdf5 images via the hdf5 libraries %package jpip-server Summary: ossim kakadu jpip server Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} Requires: kakadu-plugin%{?_isa} = %{version}-%{release} %description jpip-server This sub-package contains the ossim kakadu jpip server for streaming J2K compressed data to via the Kakadu library. %package kml-plugin Summary: kml ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description kml-plugin This sub-package contains the kmlsuperoverlay ossim plugin for reading/writing kml super overlays. %package kakadu-plugin Summary: kakadu ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description kakadu-plugin This sub-package contains the kakadu ossim plugin for reading/writing J2K compressed data via the Kakadu library. %package mrsid-plugin Summary: mrsid ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description mrsid-plugin This sub-package contains the mrsid ossim plugin for reading/writing mrsid compressed data via the MrSID library. %package opencv-plugin Summary: OSSIM OpenCV plugin, contains registration code. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description opencv-plugin This sub-package contains the ossim opencv plugin with various pieces of image registration code. %package openjpeg-plugin Summary: OpenJPEG ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description openjpeg-plugin This sub-package contains the OpenJPEG ossim plugin for reading/writing J2K compressed images via the OpenJPEG library. %package png-plugin Summary: PNG ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description png-plugin This sub-package contains the Portable Network Graphic(png) ossim plugin for reading/writing png images via the png library. %package sqlite-plugin Summary: OSSIM sqlite plugin, contains GeoPackage reader/writer. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description sqlite-plugin This sub-package contains GeoPackage reader/writer. %package web-plugin Summary: web ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description web-plugin This sub-package contains the web ossim plugin for interfacing with http via curl library. %prep #--- # Notes for debugging: # Using the "%setup -q -D -T" is handy debugging. # -D on setup = Do not delete the directory before unpacking. # -T on setup = Disable the automatic unpacking of the archives. #--- # %setup -q -D -T # %setup -q -D %setup -q # Delete bundled libraw rm -rf ossim_plugins/libraw/LibRaw-0.9.0/ %build # Exports for ossim abuild: export OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo export OSSIM_INSTALL_PREFIX=/usr export OSSIM_VERSION=%{RPM_OSSIM_VERSION} # Need to ensure ossim-private branch on kak_v7_7 pushd $OSSIM_DEV_HOME/ossim-private git checkout kak_v7_7 popd mkdir -p build pushd build %cmake \ -DOSSIM_BUILD_ADDITIONAL_DIRECTORIES=$OSSIM_DEV_HOME/ossim-private/ossim-kakadu-jpip-server \ -DBUILD_CSMAPI=OFF \ -DBUILD_OMS=ON \ -DBUILD_OSSIM=ON \ -DBUILD_OSSIM_APPS=ON \ -DBUILD_OSSIM_CURL_APPS=ON \ -DBUILD_OSSIM_GUI=ON \ -DBUILD_OSSIM_TESTS=ON \ -DBUILD_OSSIM_MPI_SUPPORT=OFF \ -DBUILD_OSSIM_PLANET=ON \ -DBUILD_OSSIM_PLANET_QT=OFF \ -DBUILD_OSSIM_VIDEO=ON \ \ -DBUILD_CNES_PLUGIN=ON \ -DBUILD_CONTRIB_PLUGIN=OFF \ -DBUILD_CSM_PLUGIN=OFF \ -DBUILD_GDAL_PLUGIN=ON \ -DBUILD_GEOPDF_PLUGIN=ON \ -DBUILD_HDF5_PLUGIN=ON \ -DBUILD_KAKADU_PLUGIN=ON \ -DBUILD_KML_PLUGIN=ON \ -DBUILD_LIBRAW_PLUGIN=OFF \ -DBUILD_MRSID_PLUGIN=ON \ -DBUILD_OSSIMMRSID_PLUGIN=ON \ -DBUILD_NDF_PLUGIN=OFF \ -DBUILD_OPENCV_PLUGIN=ON \ -DBUILD_OPENJPEG_PLUGIN=ON \ -DBUILD_PDAL_PLUGIN=OFF \ -DBUILD_PNG_PLUGIN=ON \ -DBUILD_REGISTRATION_PLUGIN=OFF \ -DBUILD_SQLITE_PLUGIN=ON \ -DBUILD_WEB_PLUGIN=ON \ \ -DBUILD_RUNTIME_DIR=bin \ -DBUILD_SHARED_LIBS=ON \ -DBUILD_WMS=ON \ \ -DOSSIMPLANET_ENABLE_EPHEMERIS=OFF \ \ -DCMAKE_BUILD_TYPE=$OSSIM_BUILD_TYPE \ -DCMAKE_MODULE_PATH=$OSSIM_DEV_HOME/ossim_package_support/cmake/CMakeModules \ -DCMAKE_PREFIX_PATH=/usr \ \ -DKAKADU_ROOT_SRC=/opt/kakadu/latest \ -DKAKADU_AUX_LIBRARY=/opt/kakadu/latest/lib/Linux-x86-64-gcc/libkdu_a77R.so \ -DKAKADU_LIBRARY=/opt/kakadu/latest/lib/Linux-x86-64-gcc/libkdu_v77R.so \ \ -DMRSID_DIR=/opt/mrsid/latest \ \ ../ossim/cmake make VERBOSE=1 %{?_smp_mflags} popd # Exports for java builds: export JAVA_HOME=/usr/lib/jvm/java #export JAVA_HOME=/usr/java/latest # Build c++ jni bindings and java side of oms module: pushd ossim-oms/joms cp local.properties.template local.properties ant popd %install # Exports for ossim install: export OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo export OSSIM_VERSION=%{RPM_OSSIM_VERSION} pushd build make install DESTDIR=%{buildroot} popd install -p -m644 -D ossim/support/linux/etc/profile.d/ossim.sh %{buildroot}%{_sysconfdir}/profile.d/ossim.sh install -p -m644 -D ossim/support/linux/etc/profile.d/ossim.csh %{buildroot}%{_sysconfdir}/profile.d/ossim.csh install -p -m644 -D ossim/share/ossim/templates/ossim_preferences_template %{buildroot}%{_datadir}/ossim/ossim-preferences-template # Shared Kakadu libs. install -p -m775 /opt/kakadu/latest/lib/Linux-x86-64-gcc/libkdu_a77R.so %{buildroot}%{_libdir}/. install -p -m775 /opt/kakadu/latest/lib/Linux-x86-64-gcc/libkdu_v77R.so %{buildroot}%{_libdir}/. # Exports for java builds: export JAVA_HOME=/usr/lib/jvm/java #export JAVA_HOME=/usr/java/latest export OSSIM_INSTALL_PREFIX=%{buildroot}/usr # oms "ant" build: pushd ossim-oms/joms ant dist ant install # ant mvn-install # Fix bad perms: chmod 755 %{buildroot}%{_libdir}/libjoms.so popd %post /sbin/ldconfig # First time through create the site preferences. if [ ! -f %{_datadir}/ossim/ossim-site-preferences ]; then cp %{_datadir}/ossim/ossim-preferences-template %{_datadir}/ossim/ossim-site-preferences fi %post oms /sbin/ldconfig rm -f %{_javadir}/joms.jar ln -s %{_javadir}/joms-%{version}.jar %{_javadir}/joms.jar %post planet /sbin/ldconfig %post wms /sbin/ldconfig %postun /sbin/ldconfig %postun oms /sbin/ldconfig rm -f %{_javadir}/joms.jar %postun planet /sbin/ldconfig %postun wms /sbin/ldconfig %files %{_bindir}/* # Weed out apps: %exclude %{_bindir}/ossim-*-test %exclude %{_bindir}/ossim-adrg-dump %exclude %{_bindir}/ossim-btoa %exclude %{_bindir}/ossim-computeSrtmStats %exclude %{_bindir}/ossim-correl %exclude %{_bindir}/ossim-create-bitmask %exclude %{_bindir}/ossim-dump-ocg %exclude %{_bindir}/ossim-image-compare %exclude %{_bindir}/ossim-modopt %exclude %{_bindir}/ossimplanetklv %exclude %{_bindir}/ossimplanet-chip %exclude %{_bindir}/ossimplanettest %exclude %{_bindir}/ossim-rejout %exclude %{_bindir}/ossim-rpf %exclude %{_bindir}/ossim-senint %exclude %{_bindir}/ossim-space-imaging %exclude %{_bindir}/ossim-src2src %exclude %{_bindir}/ossim-swapbytes %exclude %{_bindir}/ossim-ws-cmp # These are in the geocell package: %exclude %{_bindir}/ossim-geocell %exclude %{_bindir}/ossimplanetviewer # In jpip-server package: %exclude %{_bindir}/ossim-jpip-server %files devel %{_includedir}/ossim %files libs %{_datadir}/ossim/ %doc ossim/LICENSE.txt %{_libdir}/libossim.so* %{_libdir}/pkgconfig/ossim.pc %{_sysconfdir}/profile.d/ossim.sh %{_sysconfdir}/profile.d/ossim.csh %files geocell %{_bindir}/ossim-geocell %{_libdir}/libossimGui.so* %files oms %{_javadir}/joms-%{version}.jar %{_libdir}/libjoms.so %{_libdir}/liboms.so* %files oms-devel %{_includedir}/oms/ %files planet # %{_bindir}/ossimplanet %{_bindir}/ossimplanetviewer %{_libdir}/libossim-planet.so* # %{_libdir}/libossimPlanetQt.so* %files planet-devel %{_includedir}/ossimPlanet %files test-apps %{_bindir}/ossim-*-test %files video %{_libdir}/libossim-video.so* %files video-devel %{_includedir}/ossimPredator %files wms %{_includedir}/wms/ %{_libdir}/libossim-wms.so* #--- # ossim plugins #--- %files cnes-plugin %{_libdir}/ossim/plugins/libossim_cnes_plugin.so %files gdal-plugin %{_libdir}/ossim/plugins/libossim_gdal_plugin.so %files geopdf-plugin %{_libdir}/ossim/plugins/libossim_geopdf_plugin.so %files hdf5-plugin %{_libdir}/ossim/plugins/libossim_hdf5_plugin.so %files jpip-server %{_bindir}/ossim-jpip-server %files kml-plugin %{_libdir}/ossim/plugins/libossim_kml_plugin.so %files kakadu-plugin %{_libdir}/ossim/plugins/libossim_kakadu_plugin.so %{_libdir}/libkdu_a77R.so %{_libdir}/libkdu_v77R.so %files mrsid-plugin %{_libdir}/ossim/plugins/libossim_mrsid_plugin.so %files opencv-plugin %{_libdir}/ossim/plugins/libossim_opencv_plugin.so %files openjpeg-plugin %{_libdir}/ossim/plugins/libossim_openjpeg_plugin.so %files png-plugin %{_libdir}/ossim/plugins/libossim_png_plugin.so %files sqlite-plugin %{_libdir}/ossim/plugins/libossim_sqlite_plugin.so %files web-plugin %{_libdir}/ossim/plugins/libossim_web_plugin.so %changelog * Sun Dec 29 2013 Volker Fröhlich - yes-1 - Initial package ossim-Miami-2.9.1/support/linux/rpm_specs/ossim-el6.spec000066400000000000000000000330531352751253100232570ustar00rootroot00000000000000#--- # File: ossim-el7.spec # # Spec file for building ossim rpms with rpmbuild. # # NOTE: This files differs from ossim-el6.spec on in el6 need libtiff4 to pick # up bigtiff support. # # Example usage: # rpmbuild -ba --define 'RPM_OSSIM_VERSION 1.9.0' --define 'BUILD_RELEASE 1' ossim-el7.spec # # Caveats: # 1) Builder/user needs "groovy" in their search path. # 2) Use "archive.sh" script in ossim/scripts/archive.sh to generate the source # tar ball, e.g. ossim-1.9.0.tar.gz, from appropriate git branch. #--- Name: ossim Version: %{RPM_OSSIM_VERSION} Release: %{BUILD_RELEASE}%{?dist} Summary: Open Source Software Image Map library and command line applications Group: System Environment/Libraries #TODO: Which version? License: LGPLv2+ URL: https://github.com/orgs/ossimlabs/dashboard Source0: http://download.osgeo.org/ossim/source/%{name}-%{version}.tar.gz BuildRequires: ant BuildRequires: cmake BuildRequires: ffmpeg-devel BuildRequires: gdal-devel BuildRequires: geos-devel # BuildRequires: hdf4-devel BuildRequires: hdf5a-devel BuildRequires: java-devel BuildRequires: libcurl-devel BuildRequires: libgeotiff-devel BuildRequires: libjpeg-devel BuildRequires: libpng-devel BuildRequires: libtiff4-devel #BuildRequires: libRaw-devel BuildRequires: minizip-devel BuildRequires: opencv-devel BuildRequires: OpenSceneGraph-devel BuildRequires: OpenThreads-devel BuildRequires: podofo-devel BuildRequires: qt4-devel BuildRequires: sqlite-devel BuildRequires: gpstk-devel BuildRequires: openjpeg2-devel #BuildRequires: swig Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description OSSIM is a powerful suite of geospatial libraries and applications used to process remote sensing imagery, maps, terrain, and vector data. %package devel Summary: Develelopment files for ossim Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description devel Development files for ossim. %package libs Summary: Develelopment files for ossim Group: System Environment/Libraries %description libs Libraries for ossim. %package geocell Summary: Desktop electronic light table Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description geocell Desktop electronic light table for geospatial image processing. Has 2D, 2 1/2D and 3D viewer with image chain editing capabilities. %package oms Summary: Wrapper library/java bindings for interfacing with ossim. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description oms This sub-package contains the oms wrapper library with java bindings for interfacing with the ossim library from java. %package oms-devel Summary: Development files for ossim oms wrapper library. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description oms-devel This sub-package contains the development files for oms. %package planet Summary: 3D ossim library interface via OpenSceneGraph Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description planet 3D ossim library interface via OpenSceneGraph. %package planet-devel Summary: Development files for ossim planet. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description planet-devel This sub-package contains development files for ossim planet. %package test-apps Summary: Ossim test apps. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description test-apps A suite of ossim test apps. %package video Summary: Ossim vedeo library. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description video Ossim vedeo library. %package video-devel Summary: Development files for ossim planet. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description video-devel This sub-package contains development files for ossim planet. # libwms does not depend on ossim %package wms Summary: wms ossim library Group: System Environment/Libraries %description wms This sub-package contains the web mapping service (wms) library. %package wms-devel Summary: Development files libwms Group: System Environment/Libraries Requires: libwms%{?_isa} = %{version}-%{release} %description wms-devel This sub-package contains the development files for libwms. #--- # ossim plugins: #--- %package cnes-plugin Summary: Plugin with various sensor models Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description cnes-plugin This sub-package contains the ossim plugin which has various SAR sensor models, readers, and support data parsers. Most of this code was provided by the ORFEO Toolbox (OTB) group / Centre national d'études spatiales. %package gdal-plugin Summary: GDAL ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description gdal-plugin This sub-package contains the Geospatial Data Abstraction Library(gdal) ossim plugin for reading/writing images supported by the gdal library. %package geopdf-plugin Summary: geopdf ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description geopdf-plugin This sub-package contains the geopdf ossim plugin for reading geopdf files via the podofo library. %package hdf5-plugin Summary: HDF5 ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description hdf5-plugin This sub-package contains the Hierarchical Data Format(hdf) ossim plugin for reading hdf5 images via the hdf5 libraries %package kml-plugin Summary: kml ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description kml-plugin This sub-package contains the kmlsuperoverlay ossim plugin for reading/writing kml super overlays. %package opencv-plugin Summary: OSSIM OpenCV plugin, contains registration code. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description opencv-plugin This sub-package contains the ossim opencv plugin with various pieces of image registration code. %package openjpeg-plugin Summary: OpenJPEG ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description openjpeg-plugin This sub-package contains the OpenJPEG ossim plugin for reading/writing J2K compressed images via the OpenJPEG library. %package png-plugin Summary: PNG ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description png-plugin This sub-package contains the Portable Network Graphic(png) ossim plugin for reading/writing png images via the png library. %package sqlite-plugin Summary: OSSIM sqlite plugin, contains GeoPackage reader/writer. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description sqlite-plugin This sub-package contains GeoPackage reader/writer. %package web-plugin Summary: web ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description web-plugin This sub-package contains the web ossim plugin for interfacing with http via curl library. %prep #--- # Notes for debugging: # Using the "%setup -q -D -T" is handy debugging. # -D on setup = Do not delete the directory before unpacking. # -T on setup = Disable the automatic unpacking of the archives. #--- # %setup -q -D -T # %setup -q -D %setup -q # Delete bundled libraw rm -rf ossim_plugins/libraw/LibRaw-0.9.0/ %build # Exports for ossim abuild: export OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo export OSSIM_INSTALL_PREFIX=/usr export OSSIM_VERSION=%{RPM_OSSIM_VERSION} mkdir -p build pushd build %cmake \ -DBUILD_CSMAPI=OFF \ -DBUILD_OMS=ON \ -DBUILD_OSSIM=ON \ -DBUILD_OSSIM_APPS=ON \ -DBUILD_OSSIM_CURL_APPS=ON \ -DBUILD_OSSIM_GUI=ON \ -DBUILD_OSSIM_TESTS=ON \ -DBUILD_OSSIM_MPI_SUPPORT=OFF \ -DBUILD_OSSIM_PLANET=ON \ -DBUILD_OSSIM_PLANET_QT=OFF \ -DBUILD_OSSIM_VIDEO=ON \ \ -DBUILD_CNES_PLUGIN=ON \ -DBUILD_CONTRIB_PLUGIN=OFF \ -DBUILD_CSM_PLUGIN=OFF \ -DBUILD_GDAL_PLUGIN=ON \ -DBUILD_GEOPDF_PLUGIN=ON \ -DBUILD_HDF5_PLUGIN=ON \ -DBUILD_KAKADU_PLUGIN=OFF \ -DBUILD_KML_PLUGIN=ON \ -DBUILD_LIBRAW_PLUGIN=OFF \ -DBUILD_MRSID_PLUGIN=OFF \ -DBUILD_OSSIMMRSID_PLUGIN=ON \ -DBUILD_NDF_PLUGIN=OFF \ -DBUILD_OPENCV_PLUGIN=ON \ -DBUILD_OPENJPEG_PLUGIN=ON \ -DBUILD_PDAL_PLUGIN=OFF \ -DBUILD_PNG_PLUGIN=ON \ -DBUILD_REGISTRATION_PLUGIN=OFF \ -DBUILD_SQLITE_PLUGIN=ON \ -DBUILD_WEB_PLUGIN=ON \ \ -DBUILD_RUNTIME_DIR=bin \ -DBUILD_SHARED_LIBS=ON \ -DBUILD_WMS=ON \ \ -DOSSIMPLANET_ENABLE_EPHEMERIS=OFF \ \ -DCMAKE_BUILD_TYPE=$OSSIM_BUILD_TYPE \ -DCMAKE_MODULE_PATH=$OSSIM_DEV_HOME/ossim_package_support/cmake/CMakeModules \ -DCMAKE_PREFIX_PATH=/usr \ ../ossim/cmake make VERBOSE=1 %{?_smp_mflags} popd # Exports for java builds: export JAVA_HOME=/usr/lib/jvm/java #export JAVA_HOME=/usr/java/latest # Build c++ jni bindings and java side of oms module: pushd ossim-oms/joms cp local.properties.template local.properties ant popd %install # Exports for ossim install: export OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo export OSSIM_VERSION=%{RPM_OSSIM_VERSION} pushd build make install DESTDIR=%{buildroot} popd install -p -m644 -D ossim/support/linux/etc/profile.d/ossim.sh %{buildroot}%{_sysconfdir}/profile.d/ossim.sh install -p -m644 -D ossim/support/linux/etc/profile.d/ossim.csh %{buildroot}%{_sysconfdir}/profile.d/ossim.csh install -p -m644 -D ossim/share/ossim/templates/ossim_preferences_template %{buildroot}%{_datadir}/ossim/ossim-preferences-template # Exports for java builds: export JAVA_HOME=/usr/lib/jvm/java #export JAVA_HOME=/usr/java/latest export OSSIM_INSTALL_PREFIX=%{buildroot}/usr # oms "ant" build: pushd ossim-oms/joms ant dist ant install # ant mvn-install # Fix bad perms: chmod 755 %{buildroot}%{_libdir}/libjoms.so popd %post /sbin/ldconfig # First time through create the site preferences. if [ ! -f %{_datadir}/ossim/ossim-site-preferences ]; then cp %{_datadir}/ossim/ossim-preferences-template %{_datadir}/ossim/ossim-site-preferences fi %post oms /sbin/ldconfig rm -f %{_javadir}/joms.jar ln -s %{_javadir}/joms-%{version}.jar %{_javadir}/joms.jar %post planet /sbin/ldconfig %post wms /sbin/ldconfig %postun /sbin/ldconfig %postun oms /sbin/ldconfig rm -f %{_javadir}/joms.jar %postun planet /sbin/ldconfig %postun wms /sbin/ldconfig %files %{_bindir}/* # Weed out apps: %exclude %{_bindir}/ossim-*-test %exclude %{_bindir}/ossim-adrg-dump %exclude %{_bindir}/ossim-btoa %exclude %{_bindir}/ossim-computeSrtmStats %exclude %{_bindir}/ossim-correl %exclude %{_bindir}/ossim-create-bitmask %exclude %{_bindir}/ossim-dump-ocg %exclude %{_bindir}/ossim-image-compare %exclude %{_bindir}/ossim-modopt %exclude %{_bindir}/ossimplanetklv %exclude %{_bindir}/ossimplanet-chip %exclude %{_bindir}/ossimplanettest %exclude %{_bindir}/ossim-rejout %exclude %{_bindir}/ossim-rpf %exclude %{_bindir}/ossim-senint %exclude %{_bindir}/ossim-space-imaging %exclude %{_bindir}/ossim-src2src %exclude %{_bindir}/ossim-swapbytes %exclude %{_bindir}/ossim-ws-cmp # These are in the geocell package: %exclude %{_bindir}/ossim-geocell %exclude %{_bindir}/ossimplanetviewer %files devel %{_includedir}/ossim %files libs %{_datadir}/ossim/ %doc ossim/LICENSE.txt %{_libdir}/libossim.so* %{_libdir}/pkgconfig/ossim.pc %{_sysconfdir}/profile.d/ossim.sh %{_sysconfdir}/profile.d/ossim.csh %files geocell %{_bindir}/ossim-geocell %{_libdir}/libossimGui.so* %files oms %{_javadir}/joms-%{version}.jar %{_libdir}/libjoms.so %{_libdir}/liboms.so* %files oms-devel %{_includedir}/oms/ %files planet # %{_bindir}/ossimplanet %{_bindir}/ossimplanetviewer %{_libdir}/libossim-planet.so* # %{_libdir}/libossimPlanetQt.so* %files planet-devel %{_includedir}/ossimPlanet %files test-apps %{_bindir}/ossim-*-test %files video %{_libdir}/libossim-video.so* %files video-devel %{_includedir}/ossimPredator %files wms %{_includedir}/wms/ %{_libdir}/libossim-wms.so* #--- # ossim plugins #--- %files cnes-plugin %{_libdir}/ossim/plugins/libossim_cnes_plugin.so %files gdal-plugin %{_libdir}/ossim/plugins/libossim_gdal_plugin.so %files geopdf-plugin %{_libdir}/ossim/plugins/libossim_geopdf_plugin.so %files hdf5-plugin %{_libdir}/ossim/plugins/libossim_hdf5_plugin.so %files kml-plugin %{_libdir}/ossim/plugins/libossim_kml_plugin.so %files opencv-plugin %{_libdir}/ossim/plugins/libossim_opencv_plugin.so %files openjpeg-plugin %{_libdir}/ossim/plugins/libossim_openjpeg_plugin.so %files png-plugin %{_libdir}/ossim/plugins/libossim_png_plugin.so %files sqlite-plugin %{_libdir}/ossim/plugins/libossim_sqlite_plugin.so %files web-plugin %{_libdir}/ossim/plugins/libossim_web_plugin.so %changelog * Sun Dec 29 2013 Volker Fröhlich - yes-1 - Initial package ossim-Miami-2.9.1/support/linux/rpm_specs/ossim-el7.spec000066400000000000000000000330521352751253100232570ustar00rootroot00000000000000#--- # File: ossim-el7.spec # # Spec file for building ossim rpms with rpmbuild. # # NOTE: This files differs from ossim-el6.spec on in el6 need libtiff4 to pick # up bigtiff support. # # Example usage: # rpmbuild -ba --define 'RPM_OSSIM_VERSION 1.9.0' --define 'BUILD_RELEASE 1' ossim-el7.spec # # Caveats: # 1) Builder/user needs "groovy" in their search path. # 2) Use "archive.sh" script in ossim/scripts/archive.sh to generate the source # tar ball, e.g. ossim-1.9.0.tar.gz, from appropriate git branch. #--- Name: ossim Version: %{RPM_OSSIM_VERSION} Release: %{BUILD_RELEASE}%{?dist} Summary: Open Source Software Image Map library and command line applications Group: System Environment/Libraries #TODO: Which version? License: LGPLv2+ URL: https://github.com/orgs/ossimlabs/dashboard Source0: http://download.osgeo.org/ossim/source/%{name}-%{version}.tar.gz BuildRequires: ant BuildRequires: cmake BuildRequires: ffmpeg-devel BuildRequires: gdal-devel BuildRequires: geos-devel # BuildRequires: hdf4-devel BuildRequires: hdf5a-devel BuildRequires: java-devel BuildRequires: libcurl-devel BuildRequires: libgeotiff-devel BuildRequires: libjpeg-devel BuildRequires: libpng-devel BuildRequires: libtiff-devel #BuildRequires: libRaw-devel BuildRequires: minizip-devel BuildRequires: opencv-devel BuildRequires: OpenSceneGraph-devel BuildRequires: OpenThreads-devel BuildRequires: podofo-devel BuildRequires: qt4-devel BuildRequires: sqlite-devel BuildRequires: gpstk-devel BuildRequires: openjpeg2-devel #BuildRequires: swig Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description OSSIM is a powerful suite of geospatial libraries and applications used to process remote sensing imagery, maps, terrain, and vector data. %package devel Summary: Develelopment files for ossim Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description devel Development files for ossim. %package libs Summary: Develelopment files for ossim Group: System Environment/Libraries %description libs Libraries for ossim. %package geocell Summary: Desktop electronic light table Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description geocell Desktop electronic light table for geospatial image processing. Has 2D, 2 1/2D and 3D viewer with image chain editing capabilities. %package oms Summary: Wrapper library/java bindings for interfacing with ossim. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description oms This sub-package contains the oms wrapper library with java bindings for interfacing with the ossim library from java. %package oms-devel Summary: Development files for ossim oms wrapper library. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description oms-devel This sub-package contains the development files for oms. %package planet Summary: 3D ossim library interface via OpenSceneGraph Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description planet 3D ossim library interface via OpenSceneGraph. %package planet-devel Summary: Development files for ossim planet. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description planet-devel This sub-package contains development files for ossim planet. %package test-apps Summary: Ossim test apps. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description test-apps A suite of ossim test apps. %package video Summary: Ossim vedeo library. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description video Ossim vedeo library. %package video-devel Summary: Development files for ossim planet. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description video-devel This sub-package contains development files for ossim planet. # libwms does not depend on ossim %package wms Summary: wms ossim library Group: System Environment/Libraries %description wms This sub-package contains the web mapping service (wms) library. %package wms-devel Summary: Development files libwms Group: System Environment/Libraries Requires: libwms%{?_isa} = %{version}-%{release} %description wms-devel This sub-package contains the development files for libwms. #--- # ossim plugins: #--- %package cnes-plugin Summary: Plugin with various sensor models Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description cnes-plugin This sub-package contains the ossim plugin which has various SAR sensor models, readers, and support data parsers. Most of this code was provided by the ORFEO Toolbox (OTB) group / Centre national d'études spatiales. %package gdal-plugin Summary: GDAL ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description gdal-plugin This sub-package contains the Geospatial Data Abstraction Library(gdal) ossim plugin for reading/writing images supported by the gdal library. %package geopdf-plugin Summary: geopdf ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description geopdf-plugin This sub-package contains the geopdf ossim plugin for reading geopdf files via the podofo library. %package hdf5-plugin Summary: HDF5 ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description hdf5-plugin This sub-package contains the Hierarchical Data Format(hdf) ossim plugin for reading hdf5 images via the hdf5 libraries %package kml-plugin Summary: kml ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description kml-plugin This sub-package contains the kmlsuperoverlay ossim plugin for reading/writing kml super overlays. %package opencv-plugin Summary: OSSIM OpenCV plugin, contains registration code. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description opencv-plugin This sub-package contains the ossim opencv plugin with various pieces of image registration code. %package openjpeg-plugin Summary: OpenJPEG ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description openjpeg-plugin This sub-package contains the OpenJPEG ossim plugin for reading/writing J2K compressed images via the OpenJPEG library. %package png-plugin Summary: PNG ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description png-plugin This sub-package contains the Portable Network Graphic(png) ossim plugin for reading/writing png images via the png library. %package sqlite-plugin Summary: OSSIM sqlite plugin, contains GeoPackage reader/writer. Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description sqlite-plugin This sub-package contains GeoPackage reader/writer. %package web-plugin Summary: web ossim plugin Group: System Environment/Libraries Requires: %{name}-libs%{?_isa} = %{version}-%{release} %description web-plugin This sub-package contains the web ossim plugin for interfacing with http via curl library. %prep #--- # Notes for debugging: # Using the "%setup -q -D -T" is handy debugging. # -D on setup = Do not delete the directory before unpacking. # -T on setup = Disable the automatic unpacking of the archives. #--- # %setup -q -D -T # %setup -q -D %setup -q # Delete bundled libraw rm -rf ossim_plugins/libraw/LibRaw-0.9.0/ %build # Exports for ossim abuild: export OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo export OSSIM_INSTALL_PREFIX=/usr export OSSIM_VERSION=%{RPM_OSSIM_VERSION} mkdir -p build pushd build %cmake \ -DBUILD_CSMAPI=OFF \ -DBUILD_OMS=ON \ -DBUILD_OSSIM=ON \ -DBUILD_OSSIM_APPS=ON \ -DBUILD_OSSIM_CURL_APPS=ON \ -DBUILD_OSSIM_GUI=ON \ -DBUILD_OSSIM_TESTS=ON \ -DBUILD_OSSIM_MPI_SUPPORT=OFF \ -DBUILD_OSSIM_PLANET=ON \ -DBUILD_OSSIM_PLANET_QT=OFF \ -DBUILD_OSSIM_VIDEO=ON \ \ -DBUILD_CNES_PLUGIN=ON \ -DBUILD_CONTRIB_PLUGIN=OFF \ -DBUILD_CSM_PLUGIN=OFF \ -DBUILD_GDAL_PLUGIN=ON \ -DBUILD_GEOPDF_PLUGIN=ON \ -DBUILD_HDF5_PLUGIN=ON \ -DBUILD_KAKADU_PLUGIN=OFF \ -DBUILD_KML_PLUGIN=ON \ -DBUILD_LIBRAW_PLUGIN=OFF \ -DBUILD_MRSID_PLUGIN=OFF \ -DBUILD_OSSIMMRSID_PLUGIN=ON \ -DBUILD_NDF_PLUGIN=OFF \ -DBUILD_OPENCV_PLUGIN=ON \ -DBUILD_OPENJPEG_PLUGIN=ON \ -DBUILD_PDAL_PLUGIN=OFF \ -DBUILD_PNG_PLUGIN=ON \ -DBUILD_REGISTRATION_PLUGIN=OFF \ -DBUILD_SQLITE_PLUGIN=ON \ -DBUILD_WEB_PLUGIN=ON \ \ -DBUILD_RUNTIME_DIR=bin \ -DBUILD_SHARED_LIBS=ON \ -DBUILD_WMS=ON \ \ -DOSSIMPLANET_ENABLE_EPHEMERIS=OFF \ \ -DCMAKE_BUILD_TYPE=$OSSIM_BUILD_TYPE \ -DCMAKE_MODULE_PATH=$OSSIM_DEV_HOME/ossim_package_support/cmake/CMakeModules \ -DCMAKE_PREFIX_PATH=/usr \ ../ossim/cmake make VERBOSE=1 %{?_smp_mflags} popd # Exports for java builds: export JAVA_HOME=/usr/lib/jvm/java #export JAVA_HOME=/usr/java/latest # Build c++ jni bindings and java side of oms module: pushd ossim-oms/joms cp local.properties.template local.properties ant popd %install # Exports for ossim install: export OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo export OSSIM_VERSION=%{RPM_OSSIM_VERSION} pushd build make install DESTDIR=%{buildroot} popd install -p -m644 -D ossim/support/linux/etc/profile.d/ossim.sh %{buildroot}%{_sysconfdir}/profile.d/ossim.sh install -p -m644 -D ossim/support/linux/etc/profile.d/ossim.csh %{buildroot}%{_sysconfdir}/profile.d/ossim.csh install -p -m644 -D ossim/share/ossim/templates/ossim_preferences_template %{buildroot}%{_datadir}/ossim/ossim-preferences-template # Exports for java builds: export JAVA_HOME=/usr/lib/jvm/java #export JAVA_HOME=/usr/java/latest export OSSIM_INSTALL_PREFIX=%{buildroot}/usr # oms "ant" build: pushd ossim-oms/joms ant dist ant install # ant mvn-install # Fix bad perms: chmod 755 %{buildroot}%{_libdir}/libjoms.so popd %post /sbin/ldconfig # First time through create the site preferences. if [ ! -f %{_datadir}/ossim/ossim-site-preferences ]; then cp %{_datadir}/ossim/ossim-preferences-template %{_datadir}/ossim/ossim-site-preferences fi %post oms /sbin/ldconfig rm -f %{_javadir}/joms.jar ln -s %{_javadir}/joms-%{version}.jar %{_javadir}/joms.jar %post planet /sbin/ldconfig %post wms /sbin/ldconfig %postun /sbin/ldconfig %postun oms /sbin/ldconfig rm -f %{_javadir}/joms.jar %postun planet /sbin/ldconfig %postun wms /sbin/ldconfig %files %{_bindir}/* # Weed out apps: %exclude %{_bindir}/ossim-*-test %exclude %{_bindir}/ossim-adrg-dump %exclude %{_bindir}/ossim-btoa %exclude %{_bindir}/ossim-computeSrtmStats %exclude %{_bindir}/ossim-correl %exclude %{_bindir}/ossim-create-bitmask %exclude %{_bindir}/ossim-dump-ocg %exclude %{_bindir}/ossim-image-compare %exclude %{_bindir}/ossim-modopt %exclude %{_bindir}/ossimplanetklv %exclude %{_bindir}/ossimplanet-chip %exclude %{_bindir}/ossimplanettest %exclude %{_bindir}/ossim-rejout %exclude %{_bindir}/ossim-rpf %exclude %{_bindir}/ossim-senint %exclude %{_bindir}/ossim-space-imaging %exclude %{_bindir}/ossim-src2src %exclude %{_bindir}/ossim-swapbytes %exclude %{_bindir}/ossim-ws-cmp # These are in the geocell package: %exclude %{_bindir}/ossim-geocell %exclude %{_bindir}/ossimplanetviewer %files devel %{_includedir}/ossim %files libs %{_datadir}/ossim/ %doc ossim/LICENSE.txt %{_libdir}/libossim.so* %{_libdir}/pkgconfig/ossim.pc %{_sysconfdir}/profile.d/ossim.sh %{_sysconfdir}/profile.d/ossim.csh %files geocell %{_bindir}/ossim-geocell %{_libdir}/libossimGui.so* %files oms %{_javadir}/joms-%{version}.jar %{_libdir}/libjoms.so %{_libdir}/liboms.so* %files oms-devel %{_includedir}/oms/ %files planet # %{_bindir}/ossimplanet %{_bindir}/ossimplanetviewer %{_libdir}/libossim-planet.so* # %{_libdir}/libossimPlanetQt.so* %files planet-devel %{_includedir}/ossimPlanet %files test-apps %{_bindir}/ossim-*-test %files video %{_libdir}/libossim-video.so* %files video-devel %{_includedir}/ossimPredator %files wms %{_includedir}/wms/ %{_libdir}/libossim-wms.so* #--- # ossim plugins #--- %files cnes-plugin %{_libdir}/ossim/plugins/libossim_cnes_plugin.so %files gdal-plugin %{_libdir}/ossim/plugins/libossim_gdal_plugin.so %files geopdf-plugin %{_libdir}/ossim/plugins/libossim_geopdf_plugin.so %files hdf5-plugin %{_libdir}/ossim/plugins/libossim_hdf5_plugin.so %files kml-plugin %{_libdir}/ossim/plugins/libossim_kml_plugin.so %files opencv-plugin %{_libdir}/ossim/plugins/libossim_opencv_plugin.so %files openjpeg-plugin %{_libdir}/ossim/plugins/libossim_openjpeg_plugin.so %files png-plugin %{_libdir}/ossim/plugins/libossim_png_plugin.so %files sqlite-plugin %{_libdir}/ossim/plugins/libossim_sqlite_plugin.so %files web-plugin %{_libdir}/ossim/plugins/libossim_web_plugin.so %changelog * Sun Dec 29 2013 Volker Fröhlich - yes-1 - Initial package ossim-Miami-2.9.1/support/linux/rpm_specs/ossim-kakadu-plugin-el6.spec000066400000000000000000000041621352751253100260100ustar00rootroot00000000000000#--- # File: ossim-kakadu-el7.spec # # Spec file for building ossim rpms with rpmbuild. # # NOTE: This files differs from ossim-el6.spec on in el6 need libtiff4 to pick # up bigtiff support. # # Example usage: # rpmbuild -ba --define 'RPM_OSSIM_VERSION 1.9.0' --define 'BUILD_RELEASE 1' ossim-kakadu-el7.spec #--- Name: ossim-kakadu-plugin Version: %{RPM_OSSIM_VERSION} Release: %{BUILD_RELEASE}%{?dist} Summary: OSSIM Kakadu Plugin Group: System Environment/Libraries #TODO: Which version? License: Kakadu license restrictions. URL: http://trac.osgeo.org/ossim/wiki Source0: http://download.osgeo.org/ossim/source/%{name}-%{version}.tar.gz BuildRequires: cmake BuildRequires: java-devel BuildRequires: libcurl-devel BuildRequires: libtiff4-devel BuildRequires: ossim-devel # Kakadu version used: # %define KAKADU_VERSION v7_7-01123C %define KAKADU_VERSION kakadu_src %description OSSIM Kakadu Plugin %prep #--- # Notes for debugging: # -D on setup = Do not delete the directory before unpacking. # -T on setup = Disable the automatic unpacking of the archives. #--- # %setup -q -D -T %setup -q %build OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} #export JAVA_HOME=/usr/java/latest export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo # Build kakadu: pushd %{KAKADU_VERSION}/make make -f Makefile-Linux-x86-64-gcc popd #build plugin: mkdir -p build pushd build # Note: Linking static libs. %cmake \ -DCMAKE_BUILD_TYPE=${OSSIM_BUILD_TYPE} \ -DCMAKE_MODULE_PATH=$OSSIM_DEV_HOME/CMakeModules \ -DKAKADU_ROOT_SRC=$OSSIM_DEV_HOME/%{KAKADU_VERSION} \ -DKAKADU_AUX_LIBRARY=$OSSIM_DEV_HOME/%{KAKADU_VERSION}/lib/Linux-x86-64-gcc/libkdu_aux.a \ -DKAKADU_LIBRARY=$OSSIM_DEV_HOME/%{KAKADU_VERSION}/lib/Linux-x86-64-gcc/libkdu.a \ ../kakadu make VERBOSE=1 %{?_smp_mflags} popd %install pushd build make install DESTDIR=%{buildroot} popd %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %{_libdir}/ossim/plugins/libossim_kakadu_plugin.so %changelog * Mon Jan 6 2013 David Burken 1.8.18-1 - Initial package ossim-Miami-2.9.1/support/linux/rpm_specs/ossim-kakadu-plugin-el7.spec000066400000000000000000000041611352751253100260100ustar00rootroot00000000000000#--- # File: ossim-kakadu-el7.spec # # Spec file for building ossim rpms with rpmbuild. # # NOTE: This files differs from ossim-el6.spec on in el6 need libtiff4 to pick # up bigtiff support. # # Example usage: # rpmbuild -ba --define 'RPM_OSSIM_VERSION 1.9.0' --define 'BUILD_RELEASE 1' ossim-kakadu-el7.spec #--- Name: ossim-kakadu-plugin Version: %{RPM_OSSIM_VERSION} Release: %{BUILD_RELEASE}%{?dist} Summary: OSSIM Kakadu Plugin Group: System Environment/Libraries #TODO: Which version? License: Kakadu license restrictions. URL: http://trac.osgeo.org/ossim/wiki Source0: http://download.osgeo.org/ossim/source/%{name}-%{version}.tar.gz BuildRequires: cmake BuildRequires: java-devel BuildRequires: libcurl-devel BuildRequires: libtiff-devel BuildRequires: ossim-devel # Kakadu version used: # %define KAKADU_VERSION v7_7-01123C %define KAKADU_VERSION kakadu_src %description OSSIM Kakadu Plugin %prep #--- # Notes for debugging: # -D on setup = Do not delete the directory before unpacking. # -T on setup = Disable the automatic unpacking of the archives. #--- # %setup -q -D -T %setup -q %build OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} #export JAVA_HOME=/usr/java/latest export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo # Build kakadu: pushd %{KAKADU_VERSION}/make make -f Makefile-Linux-x86-64-gcc popd #build plugin: mkdir -p build pushd build # Note: Linking static libs. %cmake \ -DCMAKE_BUILD_TYPE=${OSSIM_BUILD_TYPE} \ -DCMAKE_MODULE_PATH=$OSSIM_DEV_HOME/CMakeModules \ -DKAKADU_ROOT_SRC=$OSSIM_DEV_HOME/%{KAKADU_VERSION} \ -DKAKADU_AUX_LIBRARY=$OSSIM_DEV_HOME/%{KAKADU_VERSION}/lib/Linux-x86-64-gcc/libkdu_aux.a \ -DKAKADU_LIBRARY=$OSSIM_DEV_HOME/%{KAKADU_VERSION}/lib/Linux-x86-64-gcc/libkdu.a \ ../kakadu make VERBOSE=1 %{?_smp_mflags} popd %install pushd build make install DESTDIR=%{buildroot} popd %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %{_libdir}/ossim/plugins/libossim_kakadu_plugin.so %changelog * Mon Jan 6 2013 David Burken 1.8.18-1 - Initial package ossim-Miami-2.9.1/support/linux/rpm_specs/ossim-mrsid-plugin-el6.spec000066400000000000000000000032361352751253100256670ustar00rootroot00000000000000Name: ossim-mrsid-plugin Version: %{RPM_OSSIM_VERSION} Release: %{BUILD_RELEASE}%{?dist} Summary: OSSIM MrSID Plugin Group: System Environment/Libraries #TODO: Which version? License: Mrsid license restrictions. URL: http://trac.osgeo.org/ossim/wiki Source0: http://download.osgeo.org/ossim/source/%{name}-%{version}.tar.gz BuildRequires: cmake BuildRequires: java-devel BuildRequires: libcurl-devel BuildRequires: libtiff4-devel BuildRequires: ossim-devel %description OSSIM Mrsid Plugin %prep #--- # Notes for debugging: # -D on setup = Do not delete the directory before unpacking. # -T on setup = Disable the automatic unpacking of the archives. #--- # %setup -q -D -T %setup -q %build OSSIM_DEV_HOME=%{_builddir}/%{name}-%{version} export OSSIM_BUILD_DIR=%{_builddir}/%{name}-%{version}/build export OSSIM_BUILD_TYPE=RelWithDebInfo #build plugin: mkdir -p build pushd build # Note: Linking static libs. %cmake \ -DCMAKE_BUILD_TYPE=$OSSIM_BUILD_TYPE \ -DCMAKE_MODULE_PATH=$OSSIM_DEV_HOME/CMakeModules \ -DMRSID_DIR=$OSSIM_DEV_HOME/mrsid_code \ ../mrsid make VERBOSE=1 %{?_smp_mflags} popd %install # ossim mrsid plugin: pushd build make install DESTDIR=%{buildroot} popd # mrsid libraries: install -p -m755 -D mrsid_code/Lidar_DSDK/lib/liblti_lidar_dsdk.so %{buildroot}%{_libdir} install -p -m755 -D mrsid_code/Raster_DSDK/lib/libltidsdk.so %{buildroot}%{_libdir} %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %{_libdir}/ossim/plugins/libossim_mrsid_plugin.so %{_libdir}/liblti_lidar_dsdk.so %{_libdir}/libltidsdk.so %changelog * Mon Jan 9 2013 David Burken &1; then echo $"$PROG process is already running..." return 1 echo_failure else echo "Lock file found but no $PROG process running for (pid $PID)" echo "Removing old lock file..." rm -rf $PROG_PID fi fi echo -ne $"Starting $PROG: " echo $RUN_PROGRAM /bin/su - $PROG_USER $RUN_PROGRAM >> $PROG_ERROR_LOG 2>&1 RETVAL="$?" if [ "$RETVAL" -eq 0 ]; then echo_success echo -en "\n" else echo_failure echo -en "\n" exit 1 fi else echo "$RUN_PROGRAM does not exist..." echo_failure echo -en "\n" exit 1 fi } stop() { COUNT=0 WAIT=10 if [ -e "$PROG_PID" ]; then read PID < $PROG_PID #echo ${PID} if checkpid $PID 2>&1; then echo -ne $"Stopping $PROG: " kill $PID >> $PROG_ERROR_LOG 2>&1 RETVAL="$?" sleep 2 # if [ "$RETVAL" -eq 0 ]; then # echo_successss # echo -en "\n" # else while [ "$(ps -p $PID | grep -c $PID)" -eq "1" -a "$COUNT" -lt "$WAIT" ]; do echo -ne "\nWaiting on $PROG process to exit..." COUNT=`expr $COUNT + 1` sleep .3 # echo $COUNT done # if [ "$COUNT" -gt "$WAIT" ]; then if [ "$(ps -p $PID | grep -c $PID)" == "1" ] ; then echo -ne "\nCouldn't shutdown, forcing shutdown of $PROG process" kill -9 $PID fi echo_success echo -en "\n" # fi fi else echo -ne $"Stopping $PROG: " echo_failure echo -en "\n" fi } status() { RETVAL="1" if [ -e "$PROG_PID" ]; then read PID < $PROG_PID if checkpid $PID 2>&1; then echo "$PROG (pid $PID) is running..." RETVAL="0" else echo "Lock file found but no process running for (pid $PID)" fi else PID="$(pgrep -u $PROG_USER java)" if [ -n "$PID" ]; then echo "$PROG running (pid $PID) but no PID file exists" RETVAL="0" else echo "$PROG is stopped" RETVAL="1" fi fi return $RETVAL } # Check if pid is running checkpid() { local PID for PID in $* ; do [ -d "/proc/$PID" ] && return 0 done return 1 } echo_success() { if [ -e "/etc/redhat-release" ]; then echo -en "\\033[60G" echo -n "[ " echo -en "\\033[0;32m" echo -n $"OK" echo -en "\\033[0;39m" echo -n " ]" echo -en "\r" elif [ -e "/etc/SuSE-release" ]; then echo -en "\\033[60G" echo -en "\\033[1;32m" echo -n $"done" echo -en "\\033[0;39m" echo -en "\r" else echo -en "\\033[60G" echo "OK" echo -en "\r" fi return 0 } echo_failure() { if [ -e "/etc/redhat-release" ]; then echo -en "\\033[60G" echo -n "[" echo -en "\\033[0;31m" echo -n $"FAILED" echo -en "\\033[0;39m" echo -n "]" echo -en "\r" elif [ -e "/etc/SuSE-release" ]; then echo -en "\\033[60G" echo -en "\\033[0;31m" echo -n $"failed" echo -en "\\033[0;39m" echo -en "\r" else echo -en "\\033[60G" echo "FAILED" echo -en "\r" fi return 1 } # See how we were called. case "$1" in start) start ;; stop) stop ;; restart) stop sleep 2 start ;; status) status ;; *) echo $"Usage: $PROG {start|stop|restart|status}" exit 1 ;; esac exit $RETVALossim-Miami-2.9.1/support/linux/service-wrapper-systemd-template000066400000000000000000000006171352751253100251320ustar00rootroot00000000000000[Service] PermissionsStartOnly=true Type=forking PIDFile=/var/run/{{program_name}}/{{program_name}}.pid ExecStart=/bin/bash -c "/usr/share/omar/{{program_name}}/{{program_name}}.sh /var/run/{{program_name}}/{{program_name}}.pid >> /var/log/{{program_name}}/{{program_name}}.log 2>&1" & User={{program_user}} Group={{program_group}} WorkingDirectory=/usr/share/omar/{{program_name}} Restart=on-abort ossim-Miami-2.9.1/test/000077500000000000000000000000001352751253100146725ustar00rootroot00000000000000ossim-Miami-2.9.1/test/README.md000066400000000000000000000010611352751253100161470ustar00rootroot00000000000000# Testing Currently all testing in OSSIM is done via the ossim-batch-test executable with configuration files as input. The `config` subdirectory contains the keyword lists that define each test. See the [readme](config/README.md) file for more information. The src directory contains individual standalone test executables that serve as unit and functional tests for various components of OSSIM core. The directory heirarchy parallels that of ossim/src. Any new tests should be located in the subdirectory that reflects the highest level class being tested. ossim-Miami-2.9.1/test/config/000077500000000000000000000000001352751253100161375ustar00rootroot00000000000000ossim-Miami-2.9.1/test/config/README.md000066400000000000000000000022371352751253100174220ustar00rootroot00000000000000# OSSIM Batch Test Scripts The *.kwl files in this directory are configuration scripts for the ossim-batch-test executable. The format for the command line is ``` ossim-batch-test ``` There are two required environment variables referenced by ossim-batch-test and associated config scripts, namely, `OSSIM_BATCH_TEST_DATA` -- top-level (read-only) directory containing all source test data used by batch tests, and `OSSIM_BATCH_TEST_RESULTS` -- location (read-write) where expected results, actual results, and log files are written. These env vars must be set before running ossim-batch-test. There is a collection of public data (including expected results) available [here](https://github.com/ossimlabs/ossim-test-data). The expected results need to be populated the first time through for your platform. This is accomplished by running ossim-batch-test with the option to save ("accept") the results as the new, expected results: `ossim-batch-test --accept-test ` There is one composite configuration called `super-test.kwl` that instructs ossim-batch-test to run all individual tests found in this directory. ossim-Miami-2.9.1/test/config/applanix-test.kwl000066400000000000000000000227161352751253100214570ustar00rootroot00000000000000//============================================================================= // File: applanix-test.kwl // // Description: ossim-batch-test config file. // // Test applanix data with UTM and ECEF support data format. // // Control flags: // Use 1 or true, 0 or false to turn on and off sections. // Typically preprocess and expected results only turned on for first run. // Clean commands should erase anything created by this test. // Command order if flag turned on: // 1) clean, 2) pre-process, 3) expected, 4) test, 5) post-process // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during run-time to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // // * In order to preserve platform independence, please utilize the following // variables for the common OS commands when adding new commands to the test // configuration KWL file. Examples are provided in this template // $(DIFF_CMD) Use this var for windows "fc" or linux "diff" // $(COPY_CMD) Use this var for windows "copy" or linux "cp" // $(MKDIR_CMD) Use this var for windows "mkdir" or linux "mkdir" // $(RM_CMD) Use this var for windows "del /Q" or linux "rm -f" // $(RMDIR_CMD) Use this var for windows "rmdir /S /Q" or linux "rm -rf" // This application will set the environment variables to the proper values at // runtime, so no need to worry about defining these. // // * Use forward slashes "//", at beginning of line for comments. // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * Clean, preprocess, run, and accept test sections can be switched on or off // at run time. These override config file flags. Optional arguments are: // -c or --clean-test // -p or --preprocess-test // -r or --run-test // -a or --accept-test // Multiple tests can be entered by quoting string of space separated // test, e.g. "test1 test2". To accept all tests use "all" for test. // //=================================================================================== // --- // Begin test1: // --- test1.name: test1 test1.description: Test height for center of image from test2 as it is affected by height. // Clean up commands. test1.clean_command0: $(RMDIR_CMD) $(OBT_OUT_DIR)/test1-info-height.txt // Commands to generate expected results: // Height center of image for test2 test1.expected_results_command0: ossim-info --height 46.5518724502617 -87.3832426544229 > $(OBT_EXP_DIR)/test1-info-height.txt // The actual commands to test: test1.test_command0: ossim-info --height 46.5518724502617 -87.3832426544229 > $(OBT_OUT_DIR)/test1-info-height.txt // Post process commands for diffs and stuff: test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/test1-info-height.txt $(OBT_OUT_DIR)/test1-info-height.txt // --- // End test1: // --- // --- // Begin test2: // --- test2.name: test2 test2.description: Test applanix data with UTM support data and a tiff with embedded thumbnail. // Clean up commands. test2.clean_command0: $(RM_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.geom test2.clean_command1: $(RM_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.his test2.clean_command2: $(RM_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.ovr test2.clean_command3: $(RMDIR_CMD) $(OBT_OUT_DIR)/test2 // Pre-process commands: test2.preprocess_command0: $(MKDIR_CMD) $(OBT_EXP_DIR)/test2 test2.preprocess_command1: $(MKDIR_CMD) $(OBT_OUT_DIR)/test2 // Commands to generate expected results: // Reduced res sets with histogram. test2.expected_results_command0: ossim-preproc -r --ch $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.tif test2.expected_results_command1: $(COPY_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.his $(OBT_EXP_DIR)/test2/17657707.his // Geometry file: test2.expected_results_command2: ossim-applanix2ogeom $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/sn0085D_25Jan2011_camfile.txt $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/event1_eo_110625_1.txt $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.tif test2.expected_results_command3: $(COPY_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.geom $(OBT_EXP_DIR)/test2/17657707.geom // ossim-info: test2.expected_results_command4: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.tif > $(OBT_EXP_DIR)/test2/17657707-info.txt // The actual commands to test: test2.test_command0: ossim-preproc -r --ch $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.tif test2.test_command1: $(COPY_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.his $(OBT_OUT_DIR)/test2/17657707.his // Geometry file: test2.test_command2: ossim-applanix2ogeom $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/sn0085D_25Jan2011_camfile.txt $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/event1_eo_110625_1.txt $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.tif test2.test_command3: $(COPY_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.geom $(OBT_OUT_DIR)/test2/17657707.geom // ossim-info: test2.test_command4: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.tif > $(OBT_OUT_DIR)/test2/17657707-info.txt // Post process commands for diffs and stuff: test2.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/test2/17657707.geom $(OBT_OUT_DIR)/test2/17657707.geom test2.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/test2/17657707.his $(OBT_OUT_DIR)/test2/17657707.his test2.postprocess_command2: $(DIFF_CMD) $(OBT_EXP_DIR)/test2/17657707-info.txt $(OBT_OUT_DIR)/test2/17657707-info.txt // --- // End test2: // --- // --- // Begin test3: // --- test3.name: test3 test3.description: Test height for center of image from test 4 as it is affected by height. // Clean up commands. test3.clean_command0: $(RMDIR_CMD) $(OBT_OUT_DIR)/test3-info-height.txt // Commands to generate expected results: // Height center of image for test4. test3.expected_results_command0: ossim-info --height 33.7519522209528 -117.013690129189 > $(OBT_EXP_DIR)/test3-info-height.txt // The actual commands to test: test3.test_command0: ossim-info --height 33.7519522209528 -117.013690129189 > $(OBT_OUT_DIR)/test3-info-height.txt // Post process commands for diffs and stuff: test3.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/test3-info-height.txt $(OBT_OUT_DIR)/test3-info-height.txt // --- // End test3: // --- // --- // Begin test4: // --- test4.name: test4 test4.description: Test applanix data with ECEF support data. // Clean up commands. test4.clean_command0: $(RM_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.geom test4.clean_command1: $(RM_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.his test4.clean_command2: $(RM_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/utm/17657707.ovr test4.clean_command3: $(RMDIR_CMD) $(OBT_OUT_DIR)/test4 // Pre-process commands: test4.preprocess_command0: $(MKDIR_CMD) $(OBT_EXP_DIR)/test4 test4.preprocess_command1: $(MKDIR_CMD) $(OBT_OUT_DIR)/test4 // Commands to generate expected results: // Reduced res sets with histogram. test4.expected_results_command0: ossim-preproc -r --ch --compute-min-max $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.tif test4.expected_results_command1: $(COPY_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.his $(OBT_EXP_DIR)/test4/18056119.his // Geometry file: test4.expected_results_command2: ossim-applanix2ogeom $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/sn0056.kwl $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/eo_ECEF_050629.txt $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.tif test4.expected_results_command3: $(COPY_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.geom $(OBT_EXP_DIR)/test4/18056119.geom // ossim-info: test4.expected_results_command4: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.tif > $(OBT_EXP_DIR)/test4/18056119-info.txt // The actual commands to test: test4.test_command0: ossim-preproc -r --ch --compute-min-max $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.tif test4.test_command1: $(COPY_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.his $(OBT_OUT_DIR)/test4/18056119.his // Geometry file: test4.test_command2: ossim-applanix2ogeom $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/sn0056.kwl $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/eo_ECEF_050629.txt $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.tif test4.test_command3: $(COPY_CMD) $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.geom $(OBT_OUT_DIR)/test4/18056119.geom // ossim-info: test4.test_command4: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/applanix/ecef/18056119.tif > $(OBT_OUT_DIR)/test4/18056119-info.txt // Post process commands for diffs and stuff: test4.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/test4/18056119.geom $(OBT_OUT_DIR)/test4/18056119.geom test4.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/test4/18056119.his $(OBT_OUT_DIR)/test4/18056119.his test4.postprocess_command2: $(DIFF_CMD) $(OBT_EXP_DIR)/test4/18056119-info.txt $(OBT_OUT_DIR)/test4/18056119-info.txt // --- // End test4: // --- ossim-Miami-2.9.1/test/config/dot1.kwl000066400000000000000000000111531352751253100175260ustar00rootroot00000000000000//=================================================================================== // // File: do-test1.kwl // Generated by command: ossim-batch-test -W test1.kwl // Description: ossim-batch-test template config file. // // Control flags: // Use 1 or true, 0 or false to turn on and off sections. // Typically preprocess and expected results only turned on for first run. // Clean commands should erase anything created by this test. // Command order if flag turned on: // 1) clean, 2) pre-process, 3) expected, 4) test, 5) post-process // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during run-time to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // // * In order to preserve platform independence, please utilize the following // variables for the common OS commands when adding new commands to the test // configuration KWL file. Examples are provided in this template // $(DIFF_CMD) Use this var for windows "fc" or linux "diff" // $(COPY_CMD) Use this var for windows "copy" or linux "cp" // $(MKDIR_CMD) Use this var for windows "mkdir" or linux "mkdir" // $(RM_CMD) Use this var for windows "del /Q" or linux "rm -f" // $(RMDIR_CMD) Use this var for windows "rmdir /S /Q" or linux "rm -rf" // This application will set the environment variables to the proper values at // runtime, so no need to worry about defining these. // // * Use forward slashes "//", at beginning of line for comments. // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * Clean, preprocess, run, and accept test sections can be switched on or off // at run time. These override config file flags. Optional arguments are the // the following: // -c or --clean-test // -p or --preprocess-test // -r or --run-test // -a or --accept-test // Multiple tests can be entered by quoting string of space-separated // test names, e.g. "test1 test2". To do all tests use "all" or leave blank. // //=================================================================================== // --- // Begin test1: // // Note: // // This assumes liboms.so and libjoms.so are in your LD_LIBRARY_PATH. // If not you must add java arg "-Djava.library.path=/path/to/libs". // // --- test1.name: Java org.ossim.jni.apps.DataInfoTest test1.description: Test oms/joms DataInfoTest and associated bindings. test1.enabled: 1 // Commands to generate expected results: test1.expected_results_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.DataInfoTest $(OSSIM_BATCH_TEST_DATA)/public/tif/Iowa-utm.tif > $(OBT_EXP_DIR)/info.txt // The actual commands to test: test1.test_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.DataInfoTest $(OSSIM_BATCH_TEST_DATA)/public/tif/Iowa-utm.tif > $(OBT_OUT_DIR)/info.txt // Post process commands for diffs and stuff: test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/info.txt $(OBT_OUT_DIR)/info.txt // End test1: // Begin test2: test2.name: Java org.ossim.jni.apps.ImageModelTest test2.description: Test oms/joms ImageModelTest and associated bindings. test2.enabled: 1 // Commands to generate expected results: test2.expected_results_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.ImageModelTest $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205M0001912264B220000100072M_001508507/Volume1/5V090205M0001912264B220000100072M_001508507.ntf > $(OBT_EXP_DIR)/test2-info.txt // The actual commands to test: test2.test_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.ImageModelTest $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205M0001912264B220000100072M_001508507/Volume1/5V090205M0001912264B220000100072M_001508507.ntf > $(OBT_OUT_DIR)/test2-info.txt // Post process commands for diffs and stuff: test2.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/info.txt $(OBT_OUT_DIR)/info.txt // End test2: // Begin test2: test2.name: Java org.ossim.jni.apps.ImageModelTest test2.description: Test oms/joms ImageModelTest and associated bindings. test2.enabled: 1 ossim-Miami-2.9.1/test/config/dot2.kwl000066400000000000000000000126761352751253100175420ustar00rootroot00000000000000//=================================================================================== // // File: do-test1.kwl // Generated by command: ossim-batch-test -W test1.kwl // Description: ossim-batch-test template config file. // // Control flags: // Use 1 or true, 0 or false to turn on and off sections. // Typically preprocess and expected results only turned on for first run. // Clean commands should erase anything created by this test. // Command order if flag turned on: // 1) clean, 2) pre-process, 3) expected, 4) test, 5) post-process // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during run-time to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // // * In order to preserve platform independence, please utilize the following // variables for the common OS commands when adding new commands to the test // configuration KWL file. Examples are provided in this template // $(DIFF_CMD) Use this var for windows "fc" or linux "diff" // $(COPY_CMD) Use this var for windows "copy" or linux "cp" // $(MKDIR_CMD) Use this var for windows "mkdir" or linux "mkdir" // $(RM_CMD) Use this var for windows "del /Q" or linux "rm -f" // $(RMDIR_CMD) Use this var for windows "rmdir /S /Q" or linux "rm -rf" // This application will set the environment variables to the proper values at // runtime, so no need to worry about defining these. // // * Use forward slashes "//", at beginning of line for comments. // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * Clean, preprocess, run, and accept test sections can be switched on or off // at run time. These override config file flags. Optional arguments are the // the following: // -c or --clean-test // -p or --preprocess-test // -r or --run-test // -a or --accept-test // Multiple tests can be entered by quoting string of space-separated // test names, e.g. "test1 test2". To do all tests use "all" or leave blank. // //=================================================================================== // --- // Begin test1: // // Note: // // This assumes liboms.so and libjoms.so are in your LD_LIBRARY_PATH. // If not you must add java arg "-Djava.library.path=/path/to/libs". // // --- test1.name: Java org.ossim.jni.apps.DataInfoTest test1.description: Test oms/joms DataInfoTest and associated bindings. test1.enabled: 1 // Commands to generate expected results: test1.expected_results_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.DataInfoTest $(OSSIM_BATCH_TEST_DATA)/public/tif/Iowa-utm.tif > $(OBT_EXP_DIR)/info.txt // The actual commands to test: test1.test_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.DataInfoTest $(OSSIM_BATCH_TEST_DATA)/public/tif/Iowa-utm.tif > $(OBT_OUT_DIR)/info.txt // Post process commands for diffs and stuff: test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/info.txt $(OBT_OUT_DIR)/info.txt // End test1: // Begin test2: test2.name: Java org.ossim.jni.apps.ImageModelTest test2.description: Test oms/joms ImageModelTest and associated bindings. test2.enabled: 1 // Commands to generate expected results: test2.expected_results_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.ImageModelTest $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205M0001912264B220000100072M_001508507/Volume1/5V090205M0001912264B220000100072M_001508507.ntf > $(OBT_EXP_DIR)/test2-info.txt // The actual commands to test: test2.test_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.ImageModelTest $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205M0001912264B220000100072M_001508507/Volume1/5V090205M0001912264B220000100072M_001508507.ntf > $(OBT_OUT_DIR)/test2-info.txt // Post process commands for diffs and stuff: test2.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/info.txt $(OBT_OUT_DIR)/info.txt // End test2: // Begin test3: test3.name: Java org.ossim.jni.apps.ImageModelTest test3.description: Test oms/joms ImageModelTest and associated bindings. test3.enabled: 1 // Commands to generate expected results: test3.expected_results_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.ImageModelTest $(OSSIM_BATCH_TEST_DATA)http://71.43.98.140/omar/ogc/wms?request=GetMap&layers=3699&bbox=63.5129,27.0062,63.7034,27.1442&srs=EPSG:4326&width=1024&height=702&format=image/jpeg > $(OBT_EXP_DIR)/test3-info.txt // The actual commands to test: test3.test_command0: java -cp $(OSSIM_DEV_HOME)/oms/lib/joms.jar org.ossim.oms.apps.ImageModelTest $(OSSIM_BATCH_TEST_DATA)http://71.43.98.140/omar/ogc/wms?request=GetMap&layers=3699&bbox=63.5129,27.0062,63.7034,27.1442&srs=EPSG:4326&width=1024&height=702&format=image/jpeg > $(OBT_OUT_DIR)/test3-info.txt // Post process commands for diffs and stuff: test3.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/info.txt $(OBT_OUT_DIR)/info.txt // End test3: ossim-Miami-2.9.1/test/config/eq-test.kwl000066400000000000000000000011731352751253100202420ustar00rootroot00000000000000//--- // File ossim-eq-test.kwl //--- // --- // Begin test1: // --- test1.name: test1 test1.description: Test ossimEquDistCylProjection // Clean up commands. test1.clean_command0: $(RMDIR_CMD) $(OBT_OUT_DIR)/t1-info.txt // Commands to generate expected results: test1.expected_results_command0: ossim-eq-projection-test > $(OBT_EXP_DIR)/t1-info.txt // The actual commands to test: test1.test_command0: ossim-eq-projection-test > $(OBT_OUT_DIR)/t1-info.txt // Post process commands for diffs and stuff: test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t1-info.txt $(OBT_OUT_DIR)/t1-info.txt // --- // End test1: // --- ossim-Miami-2.9.1/test/config/fusion-test1.kwl000066400000000000000000000111431352751253100212170ustar00rootroot00000000000000//=================================================================================== // // File: test1.kwl // Description: Contains assorted tests. // // Control flags: // Use 1 or true, 0 or false to turn on and off sections. // Typically preprocess and expected results only turned on for first run. // Clean commands should erase anything created by this test. // Command order if flag turned on: // 1) clean, 2) pre-process, 3) expected, 4) test, 5) post-process // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during run-time to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // // * In order to preserve platform independence, please utilize the following // variables for the common OS commands when adding new commands to the test // configuration KWL file. Examples are provided in this template // $(DIFF_CMD) Use this var for windows "fc" or linux "diff" // $(COPY_CMD) Use this var for windows "copy" or linux "cp" // $(MKDIR_CMD) Use this var for windows "mkdir" or linux "mkdir" // $(RM_CMD) Use this var for windows "del /Q" or linux "rm -f" // $(RMDIR_CMD) Use this var for windows "rmdir /S /Q" or linux "rm -rf" // This application will set the environment variables to the proper values at // runtime, so no need to worry about defining these. // // * Use forward slashes "//", at beginning of line for comments. // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * Clean, preprocess, run, and accept test sections can be switched on or off // at run time. These override config file flags. Optional arguments are: // -c or --clean-test // -p or --preprocess-test // -r or --run-test // -a or --accept-test // Multiple tests can be entered by quoting string of space separated // test, e.g. "test1 test2". To accept all tests use "all" for test. // //=================================================================================== // --- // Begin test1: // --- test1.name: test1 test1.description: Test Landsat 7 fast format geometry. test1.enabled: 1 // Commands to generate expected results: test1.expected_results_command0: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/ls7/p24r31/l71024031_03119990929_hpn.fst > $(OBT_EXP_DIR)/ls7-ff-pan-info.txt // The actual commands to test: test1.test_command0: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/ls7/p24r31/l71024031_03119990929_hpn.fst > $(OBT_OUT_DIR)/ls7-ff-pan-info.txt // Post process commands for diffs and stuff: test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/ls7-ff-pan-info.txt $(OBT_OUT_DIR)/ls7-ff-pan-info.txt // --- // Begin test2: // --- test2.name: test2 test2.description: Test fusion output of Landsat 7 fast format data: test2.enabled: 1 // Commands to generate expected results: // igen: test2.expected_results_command0: ossim-igen $(OSSIM_BATCH_TEST_DATA)/public/ls7/p24r31/fusion-test-exp.spec // Make overviews and histogram: test2.expected_results_command1: ossim-preproc -r -o --create-histogram $(OBT_OUT_DIR)/ls7-ff-fusion-exp.tif // Capture info dump of output: test2.expected_results_command2: ossim-info -d -i -p $(OBT_OUT_DIR)/ls7-ff-fusion-exp.tif > $(OBT_EXP_DIR)/ls7-ff-fusion-exp-info.txt // Put the histogram in the expected output dir. test2.expected_results_command3: $(COPY_CMD) $(OBT_OUT_DIR)/ls7-ff-fusion-exp.his $(OBT_EXP_DIR)/ls7-ff-fusion-exp.his // The actual commands to test: // igen: test2.test_command0: ossim-igen $(OSSIM_BATCH_TEST_DATA)/public/ls7/p24r31/fusion-test-out.spec // Make overviews and histogram: test2.test_command1: ossim-preproc -r -o --create-histogram $(OBT_OUT_DIR)/ls7-ff-fusion-out.tif // Capture info dump of output: test2.test_command2: ossim-info -d -i -p $(OBT_OUT_DIR)/ls7-ff-fusion-out.tif > $(OBT_OUT_DIR)/ls7-ff-fusion-out-info.txt // Post process commands for diffs and stuff: // Test info dump: test2.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/ls7-ff-fusion-exp-info.txt $(OBT_OUT_DIR)/ls7-ff-fusion-out-info.txt // Test for histogram diffs: test2.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/ls7-ff-fusion-exp.his $(OBT_OUT_DIR)/ls7-ff-fusion-out.his ossim-Miami-2.9.1/test/config/genras-writer-test.kwl000066400000000000000000000166121352751253100224320ustar00rootroot00000000000000//=================================================================================== // // File: rbt-test1.kwl // Description: Contains assorted tests. // // Control flags: // Use 1 or true, 0 or false to turn on and off sections. // Typically preprocess and expected results only turned on for first run. // Clean commands should erase anything created by this test. // Command order if flag turned on: // 1) clean, 2) pre-process, 3) expected, 4) test, 5) post-process // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during run-time to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // // * In order to preserve platform independence, please utilize the following // variables for the common OS commands when adding new commands to the test // configuration KWL file. Examples are provided in this template // $(DIFF_CMD) Use this var for windows "fc" or linux "diff" // $(COPY_CMD) Use this var for windows "copy" or linux "cp" // $(MKDIR_CMD) Use this var for windows "mkdir" or linux "mkdir" // $(RM_CMD) Use this var for windows "del /Q" or linux "rm -f" // $(RMDIR_CMD) Use this var for windows "rmdir /S /Q" or linux "rm -rf" // This application will set the environment variables to the proper values at // runtime, so no need to worry about defining these. // // * Use forward slashes "//", at beginning of line for comments. // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * Clean, preprocess, run, and accept test sections can be switched on or off // at run time. These override config file flags. Optional arguments are: // -c or --clean-test // -p or --preprocess-test // -r or --run-test // -a or --accept-test // Multiple tests can be entered by quoting string of space separated // test, e.g. "test1 test2". To accept all tests use "all" for test. // //=================================================================================== // --- // Begin test1: // --- test1.name: test1 test1.description: ossimGeneralRasterWriter bip test test1.enabled: 1 // --- // Commands to generate expected results: // --- // Write the image: test1.expected_results_command0: ossim-icp general_raster_bip $(OSSIM_BATCH_TEST_DATA)/public/tif/ls7-ff-fusion.tif $(OBT_OUT_DIR)/Clinton-bip-exp.ras // Build overviews: test1.expected_results_command1: ossim-preproc -r -o --ch $(OBT_OUT_DIR)/Clinton-bip-exp.ras // Info dump to expected results dir: test1.expected_results_command2: ossim-info -i -p $(OBT_OUT_DIR)/Clinton-bip-exp.ras > $(OBT_EXP_DIR)/test1-info.txt // Copy histogram to expected results dir: test1.expected_results_command3: $(COPY_CMD) $(OBT_OUT_DIR)/Clinton-bip-exp.his $(OBT_EXP_DIR)/test1-his.txt // --- // The actual commands to test: // --- // Write the image: test1.test_command0: ossim-icp general_raster_bip $(OSSIM_BATCH_TEST_DATA)/public/tif/ls7-ff-fusion.tif $(OBT_OUT_DIR)/Clinton-bip-out.ras // Build overviews: test1.test_command1: ossim-preproc -r -o --ch $(OBT_OUT_DIR)/Clinton-bip-out.ras // Info dump to expected results dir: test1.test_command2: ossim-info -i -p $(OBT_OUT_DIR)/Clinton-bip-out.ras > $(OBT_OUT_DIR)/test1-info.txt // Copy histogram to expected results dir: test1.test_command3: $(COPY_CMD) $(OBT_OUT_DIR)/Clinton-bip-out.his $(OBT_OUT_DIR)/test1-his.txt // --- // Post process commands for diffs and stuff: // --- // Test for info dump diffs: test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/test1-info.txt $(OBT_OUT_DIR)/test1-info.txt // Test for histogram diffs: test1.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/test1-his.txt $(OBT_OUT_DIR)/test1-his.txt // --- // Begin test2: // --- test2.name: test2 test2.description: ossimGeneralRasterWriter bil test test2.enabled: 1 // --- // Commands to generate expected results: // --- // Write the image: test2.expected_results_command0: ossim-icp general_raster_bil $(OSSIM_BATCH_TEST_DATA)/public/tif/ls7-ff-fusion.tif $(OBT_OUT_DIR)/Clinton-bil-exp.ras // Build overviews: test2.expected_results_command1: ossim-preproc -r -o --ch $(OBT_OUT_DIR)/Clinton-bil-exp.ras // Info dump to expected results dir: test2.expected_results_command2: ossim-info -i -p $(OBT_OUT_DIR)/Clinton-bil-exp.ras > $(OBT_EXP_DIR)/test2-info.txt // Copy histogram to expected results dir: test2.expected_results_command3: $(COPY_CMD) $(OBT_OUT_DIR)/Clinton-bil-exp.his $(OBT_EXP_DIR)/test2-his.txt // --- // The actual commands to test: // --- // Write the image: test2.test_command0: ossim-icp general_raster_bil $(OSSIM_BATCH_TEST_DATA)/public/tif/ls7-ff-fusion.tif $(OBT_OUT_DIR)/Clinton-bil-out.ras // Build overviews: test2.test_command1: ossim-preproc -r -o --ch $(OBT_OUT_DIR)/Clinton-bil-out.ras // Info dump to expected results dir: test2.test_command2: ossim-info -i -p $(OBT_OUT_DIR)/Clinton-bil-out.ras > $(OBT_OUT_DIR)/test2-info.txt // Copy histogram to expected results dir: test2.test_command3: $(COPY_CMD) $(OBT_OUT_DIR)/Clinton-bil-out.his $(OBT_OUT_DIR)/test2-his.txt // --- // Post process commands for diffs and stuff: // --- // Test for info dump diffs: test2.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/test2-info.txt $(OBT_OUT_DIR)/test2-info.txt // Test for histogram diffs: test2.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/test2-his.txt $(OBT_OUT_DIR)/test2-his.txt // --- // Begin test3: // --- test3.name: test3 test3.description: ossimGeneralRasterWriter bsq test test3.enabled: 1 // --- // Commands to generate expected results: // --- // Write the image: test3.expected_results_command0: ossim-icp general_raster_bsq $(OSSIM_BATCH_TEST_DATA)/public/tif/ls7-ff-fusion.tif $(OBT_OUT_DIR)/Clinton-bsq-exp.ras // Build overviews: test3.expected_results_command1: ossim-preproc -r -o --ch $(OBT_OUT_DIR)/Clinton-bsq-exp.ras // Info dump to expected results dir: test3.expected_results_command2: ossim-info -i -p $(OBT_OUT_DIR)/Clinton-bsq-exp.ras > $(OBT_EXP_DIR)/test3-info.txt // Copy histogram to expected results dir: test3.expected_results_command3: $(COPY_CMD) $(OBT_OUT_DIR)/Clinton-bsq-exp.his $(OBT_EXP_DIR)/test3-his.txt // --- // The actual commands to test: // --- // Write the image: test3.test_command0: ossim-icp general_raster_bsq $(OSSIM_BATCH_TEST_DATA)/public/tif/ls7-ff-fusion.tif $(OBT_OUT_DIR)/Clinton-bsq-out.ras // Build overviews: test3.test_command1: ossim-preproc -r -o --ch $(OBT_OUT_DIR)/Clinton-bsq-out.ras // Info dump to expected results dir: test3.test_command2: ossim-info -i -p $(OBT_OUT_DIR)/Clinton-bsq-out.ras > $(OBT_OUT_DIR)/test3-info.txt // Copy histogram to expected results dir: test3.test_command3: $(COPY_CMD) $(OBT_OUT_DIR)/Clinton-bsq-out.his $(OBT_OUT_DIR)/test3-his.txt // --- // Post process commands for diffs and stuff: // --- // Test for info dump diffs: test3.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/test3-info.txt $(OBT_OUT_DIR)/test3-info.txt // Test for histogram diffs: test3.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/test3-his.txt $(OBT_OUT_DIR)/test3-his.txt ossim-Miami-2.9.1/test/config/height-info-test.kwl000066400000000000000000000040611352751253100220350ustar00rootroot00000000000000//=================================================================================== // // File: height-info-test.kwl // Generated by command: ossim-batch-test -w height-info-test.kwl // Description: ossim-batch-test template config file. // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * If the config file contains more than a single test, then it will be necessary // to prefix all test-specific keywords with "testN." // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during runtime to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // //=================================================================================== description: Test height for the center of the image for test2 and test3. //--------------------------------------- // Commands to generate expected results. //--------------------------------------- expected_results_command0: ossim-info --height -42.8508 147.2537 > $(OBT_OUT_DIR)\height.txt expected_results_command1: $(COPY_CMD) $(OBT_OUT_DIR)\height.txt $(OBT_EXP_DIR)\height.txt //--------------------------------------- // The actual commands to test. //--------------------------------------- test_command0: ossim-info --height -42.8508 147.2537 > $(OBT_OUT_DIR)\height.txt //--------------------------------------- // The post-processing (comparison) commands. Typically these involve a file // comparison of last run command against expected results. //--------------------------------------- postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)\height.txt $(OBT_OUT_DIR)\height.txt ossim-Miami-2.9.1/test/config/hlz-test.kwl000066400000000000000000000041701352751253100204320ustar00rootroot00000000000000//=================================================================================== // // File: hlz-test.kwl // // Description: ossim-batch-test template config file. // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * If the config file contains more than a single test, then it will be necessary // to prefix all test-specific keywords with "testN." // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during runtime to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // //=================================================================================== test1.name: hlz-test-pattern test1.description: HLZ test using synthesized test pattern as input DEM test1.enabled: 1 //--------------------------------------- // Commands to generate expected results. //--------------------------------------- test1.expected_results_command0: ossim-hlz --dem $OSSIM_BATCH_TEST_DATA/public/HLZ/test-dem.tif --lut $OSSIM_BATCH_TEST_DATA/public/HLZ/hlz2.lut --rlz 8 $(OBT_EXP_DIR)/hlz-test.tif //--------------------------------------- // The actual commands to test. //--------------------------------------- test1.test_command0: ossim-hlz --dem $OSSIM_BATCH_TEST_DATA/public/HLZ/test-dem.tif --lut $OSSIM_BATCH_TEST_DATA/public/HLZ/hlz2.lut --rlz 8 $(OBT_OUT_DIR)/hlz-test.tif //--------------------------------------- // The post-processing (comparison) commands. Typically these involve a file // comparison of last run command against expected results. //--------------------------------------- test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/hlz-test.tif $(OBT_OUT_DIR)/hlz-test.tif ossim-Miami-2.9.1/test/config/index-to-rgb-lut.kwl000066400000000000000000000041011352751253100217530ustar00rootroot00000000000000//=================================================================================== // // File: index-to-rgb-lut.kwl // // Description: ossim-batch-test template config file. // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * If the config file contains more than a single test, then it will be necessary // to prefix all test-specific keywords with "testN." // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during runtime to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // //=================================================================================== test1.description: Test various modes of index to RGB loook-up-table remapper class //--------------------------------------- // Commands to generate expected results. //--------------------------------------- test1.expected_results_command0: ossim-index-to-rgb-lut-test $(OBT_EXP_DIR)/lut-test.tif > $(OBT_EXP_DIR)/lut-test.txt //--------------------------------------- // The actual commands to test. //--------------------------------------- test1.test_command0: ossim-index-to-rgb-lut-test $(OBT_OUT_DIR)/lut-test.tif > $(OBT_OUT_DIR)/lut-test.txt //--------------------------------------- // The post-processing (comparison) commands. Typically these involve a file // comparison of last run command against expected results. //--------------------------------------- test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/lut-test.txt $(OBT_OUT_DIR)/lut-test.txt test1.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/lut-test.tif $(OBT_OUT_DIR)/lut-test.tif ossim-Miami-2.9.1/test/config/lut-test.kwl000066400000000000000000000054071352751253100204450ustar00rootroot00000000000000//=================================================================================== // // File: lut-test.kwl // // Description: ossim-batch-test template config file. // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * If the config file contains more than a single test, then it will be necessary // to prefix all test-specific keywords with "testN." // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during runtime to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // //=================================================================================== test1.description: Test various modes of index to RGB loook-up-table remapper class // Commands to generate expected results. test1.expected_results_command0: ossim-index-to-rgb-lut-test $(OSSIM_BATCH_TEST_DATA)/public/lut/lut-test.tif > $(OBT_EXP_DIR)/index-rgb-lut-test.txt // The actual commands to test. test1.test_command0: ossim-index-to-rgb-lut-test $(OSSIM_BATCH_TEST_DATA)/public/lut/lut-test.tif > $(OBT_OUT_DIR)/index-rgb-lut-test.txt // The post-processing (comparison) commands. Typically these involve a file // comparison of last run command against expected results. test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/index-rgb-lut-test.txt $(OBT_OUT_DIR)/index-rgb-lut-test.txt test2.description: Test various modes of band-separate LUT remapper class //--------------------------------------- // Commands to generate expected results. //--------------------------------------- test2.expected_results_command0: ossim-band-lut-test $(OBT_EXP_DIR) > $(OBT_EXP_DIR)/band-lut-test.txt //--------------------------------------- // The actual commands to test. //--------------------------------------- test2.test_command0: ossim-band-lut-test $(OBT_OUT_DIR) > $(OBT_OUT_DIR)/band-lut-test.txt //--------------------------------------- // The post-processing (comparison) commands. Typically these involve a file // comparison of last run command against expected results. //--------------------------------------- test2.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/bandLutTest-literal.tif $(OBT_OUT_DIR)/bandLutTest-literal.tif test2.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/bandLutTest-interpolated.tif $(OBT_OUT_DIR)/bandLutTest-interpolated.tif ossim-Miami-2.9.1/test/config/ossim-chipper-test.kwl000066400000000000000000000330001352751253100224110ustar00rootroot00000000000000//--- // File ossim-chipper-test.kwl //--- // --- // Begin test1: // --- test1.name: test1 test1.description: Test height for center of image from test2 as it is affected by height. // Clean up commands. test1.clean_command0: $(RMDIR_CMD) $(OBT_OUT_DIR)/t1-info-height.txt // Commands to generate expected results: // Height center of image for test2 test1.expected_results_command0: ossim-info --height -42.8612076379401 147.259269295413,253.262469256983 > $(OBT_EXP_DIR)/t1-info-height.txt // The actual commands to test: test1.test_command0: ossim-info --height -42.8612076379401 147.259269295413,253.262469256983 > $(OBT_OUT_DIR)/t1-info-height.txt // Post process commands for diffs and stuff: test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t1-info-height.txt $(OBT_OUT_DIR)/t1-info-height.txt // --- // End test1: // --- // --- // Begin test2: // --- test2.name: test2 test2.description: Test ossim-chipper ortho mode on rpc image. test2.enabled: 1 // Commands to generate expected results: test2.expected_results_command0: ossim-chipper --op ortho --histogram-op auto-minmax --cut-center-llwh -42.883986392005788 147.331309643650911 512 512 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_EXP_DIR)/t2.tif test2.expected_results_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram $(OBT_EXP_DIR)/t2.tif test2.expected_results_command2: ossim-info -d -i -p $(OBT_EXP_DIR)/t2.tif > $(OBT_EXP_DIR)/t2-info.txt // The actual commands to test: test2.test_command0: ossim-chipper --op ortho --histogram-op auto-minmax --cut-center-llwh -42.883986392005788 147.331309643650911 512 512 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_OUT_DIR)/t2.tif test2.test_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram-fast $(OBT_OUT_DIR)/t2.tif test2.test_command2: ossim-info -d -i -p $(OBT_OUT_DIR)/t2.tif > $(OBT_OUT_DIR)/t2-info.txt // Post process commands for diffs and stuff: test2.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t2-info.txt $(OBT_OUT_DIR)/t2-info.txt test2.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/t2.his $(OBT_OUT_DIR)/t2.his // --- // End test2: // --- // --- // Begin test3: // Note no geometry with "chip" mode so no -p in ossim-info. // --- test3.name: test3 test3.description: Test ossim-chipper chip mode, with up is up, on rpc image. test3.enabled: 1 // Commands to generate expected results: test3.expected_results_command0: ossim-chipper --op chip -u --histogram-op auto-minmax --cut-center-llwh -42.883986392005788 147.331309643650911 512 512 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_EXP_DIR)/t3.tif test3.expected_results_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram $(OBT_EXP_DIR)/t3.tif test3.expected_results_command2: ossim-info -d -i $(OBT_EXP_DIR)/t3.tif > $(OBT_EXP_DIR)/t3-info.txt // The actual commands to test: test3.test_command0: ossim-chipper --op chip -u --histogram-op auto-minmax --cut-center-llwh -42.883986392005788 147.331309643650911 512 512 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_OUT_DIR)/t3.tif test3.test_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram-fast $(OBT_OUT_DIR)/t3.tif test3.test_command2: ossim-info -d -i $(OBT_OUT_DIR)/t3.tif > $(OBT_OUT_DIR)/t3-info.txt // Post process commands for diffs and stuff: test3.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t3-info.txt $(OBT_OUT_DIR)/t3-info.txt test3.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/t3.his $(OBT_OUT_DIR)/t3.his // --- // End test3: // --- // --- // Begin test4: // Note no geometry with "chip" mode so no -p in ossim-info. // --- test4.name: test4 test4.description: Test ossim-chipper chip mode, with north up, on rpc image. test4.enabled: 1 // Commands to generate expected results: test4.expected_results_command0: ossim-chipper --op chip -n --histogram-op auto-minmax --cut-center-llwh -42.883986392005788 147.331309643650911 512 512 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_EXP_DIR)/t4.tif test4.expected_results_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram $(OBT_EXP_DIR)/t4.tif test4.expected_results_command2: ossim-info -d -i $(OBT_EXP_DIR)/t4.tif > $(OBT_EXP_DIR)/t4-info.txt // The actual commands to test: test4.test_command0: ossim-chipper --op chip -n --histogram-op auto-minmax --cut-center-llwh -42.883986392005788 147.331309643650911 512 512 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_OUT_DIR)/t4.tif test4.test_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram-fast $(OBT_OUT_DIR)/t4.tif test4.test_command2: ossim-info -d -i $(OBT_OUT_DIR)/t4.tif > $(OBT_OUT_DIR)/t4-info.txt // Post process commands for diffs and stuff: test4.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t4-info.txt $(OBT_OUT_DIR)/t4-info.txt test4.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/t4.his $(OBT_OUT_DIR)/t4.his // --- // End test4: // --- // --- // Begin test5: // Note no geometry with "chip" mode so no -p in ossim-info. // --- test5.name: test5 test5.description: Test ossim-chipper chip mode, with rotation, on rpc image. test5.enabled: 1 // Commands to generate expected results: test5.expected_results_command0: ossim-chipper --op chip -r 45.0 --histogram-op auto-minmax --cut-center-llwh -42.883986392005788 147.331309643650911 512 512 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_EXP_DIR)/t5.tif test5.expected_results_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram $(OBT_EXP_DIR)/t5.tif test5.expected_results_command2: ossim-info -d -i $(OBT_EXP_DIR)/t5.tif > $(OBT_EXP_DIR)/t5-info.txt // The actual commands to test: test5.test_command0: ossim-chipper --op chip -r 45.0 --histogram-op auto-minmax --cut-center-llwh -42.883986392005788 147.331309643650911 512 512 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_OUT_DIR)/t5.tif test5.test_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram-fast $(OBT_OUT_DIR)/t5.tif test5.test_command2: ossim-info -d -i $(OBT_OUT_DIR)/t5.tif > $(OBT_OUT_DIR)/t5-info.txt // Post process commands for diffs and stuff: test5.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t5-info.txt $(OBT_OUT_DIR)/t5-info.txt test5.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/t5.his $(OBT_OUT_DIR)/t5.his // --- // End test5: // --- // --- // Begin test6: // --- test6.name: test6 test6.description: Test ossim-chipper ortho mode on, rpc image, with polygon remapper in chain. test6.enabled: 1 // Commands to generate expected results: test6.expected_results_command0: ossim-chipper --op ortho --clip-poly-lat-lon "(-42.826019566439,147.293941362084468),(-42.822529953243581,147.297524165910716),(-42.822242150093437,147.308125338875925),(-42.826271394195437,147.311757222206637),(-42.828501868609038,147.306898351264209),(-42.834042079249286,147.307192828291022),(-42.833358546767698,147.297229688883874),(-42.829113450303090,147.292518056454895),(-42.826019566439,147.293941362084468)" --histogram-op auto-minmax --cut-center-llwh -42.828034188490058 147.304419836288560 4096 4096 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_EXP_DIR)/t6.tif test6.expected_results_command1: ossim-preproc -r -o --ch $(OBT_EXP_DIR)/t6.tif test6.expected_results_command2: ossim-info -d -i -p $(OBT_EXP_DIR)/t6.tif > $(OBT_EXP_DIR)/t6-info.txt // The actual commands to test: test6.test_command0: ossim-chipper --op ortho --clip-poly-lat-lon "(-42.826019566439,147.293941362084468),(-42.822529953243581,147.297524165910716),(-42.822242150093437,147.308125338875925),(-42.826271394195437,147.311757222206637),(-42.828501868609038,147.306898351264209),(-42.834042079249286,147.307192828291022),(-42.833358546767698,147.297229688883874),(-42.829113450303090,147.292518056454895),(-42.826019566439,147.293941362084468)" --histogram-op auto-minmax --cut-center-llwh -42.828034188490058 147.304419836288560 4096 4096 --scale-to-8-bit -w tiff_tiled_band_separate $(OSSIM_BATCH_TEST_DATA)/geoeye1/GE1_Hobart_GeoStereo_NITF-NCD/001508507_01000SP00332258/5V090205P0001912264B220000100282M_001508507/Volume1/5V090205P0001912264B220000100282M_001508507.ntf $(OBT_OUT_DIR)/t6.tif test6.test_command1: ossim-preproc -r -o --ch $(OBT_OUT_DIR)/t6.tif test6.test_command2: ossim-info -d -i -p $(OBT_OUT_DIR)/t6.tif > $(OBT_OUT_DIR)/t6-info.txt // Post process commands for diffs and stuff: test6.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t6-info.txt $(OBT_OUT_DIR)/t6-info.txt test6.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/t6.his $(OBT_OUT_DIR)/t6.his // --- // End test6: // --- // --- // Begin test7: // --- test7.name: test7 test7.description: Test ossim-chipper --op hillshade mode: test7.enabled: 1 // Commands to generate expected results: test7.expected_results_command0: ossim-chipper --op hillshade --color 240 210 180 $(OSSIM_BATCH_TEST_DATA)/public/elevation/srtm/1arc/N37W123.hgt $(OBT_EXP_DIR)/t7.tif test7.expected_results_command1: ossim-preproc -r -o --ch $(OBT_EXP_DIR)/t7.tif test7.expected_results_command2: ossim-info -d -i -p $(OBT_EXP_DIR)/t7.tif > $(OBT_EXP_DIR)/t7-info.txt // The actual commands to test: test7.test_command0: ossim-chipper --op hillshade --color 240 210 180 $(OSSIM_BATCH_TEST_DATA)/public/elevation/srtm/1arc/N37W123.hgt $(OBT_OUT_DIR)/t7.tif test7.test_command1: ossim-preproc -r -o --ch $(OBT_OUT_DIR)/t7.tif test7.test_command2: ossim-info -d -i -p $(OBT_OUT_DIR)/t7.tif > $(OBT_OUT_DIR)/t7-info.txt // Post process commands for diffs and stuff: test7.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t7-info.txt $(OBT_OUT_DIR)/t7-info.txt test7.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/t7.his $(OBT_OUT_DIR)/t7.his // --- // End test7: // --- // --- // Begin test8: // --- test8.name: test8 test8.description: Test ossim-chipper --op hillshade mode with color lut. test8.enabled: 1 // Commands to generate expected results: test8.expected_results_command0: ossim-chipper --op hillshade --azimuth 270 --elevation 45 --exaggeration 10 --color-table color-relief-lut1.kwl $(OSSIM_BATCH_TEST_DATA)/public/elevation/srtm/1arc/N37W123.hgt $(OBT_EXP_DIR)/t8.tif test8.expected_results_command1: ossim-preproc -r -o --ch $(OBT_EXP_DIR)/t8.tif test8.expected_results_command2: ossim-info -d -i -p $(OBT_EXP_DIR)/t8.tif > $(OBT_EXP_DIR)/t8-info.txt // The actual commands to test: test8.test_command0: ossim-chipper --op hillshade --azimuth 270 --elevation 45 --exaggeration 10 --color-table color-relief-lut1.kwl $(OSSIM_BATCH_TEST_DATA)/public/elevation/srtm/1arc/N37W123.hgt $(OBT_OUT_DIR)/t8.tif test8.test_command1: ossim-preproc -r -o --ch $(OBT_OUT_DIR)/t8.tif test8.test_command2: ossim-info -d -i -p $(OBT_OUT_DIR)/t8.tif > $(OBT_OUT_DIR)/t8-info.txt // Post process commands for diffs and stuff: test8.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t8-info.txt $(OBT_OUT_DIR)/t8-info.txt test8.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/t8.his $(OBT_OUT_DIR)/t8.his // --- // End test8: // --- // --- // Begin test9: // --- test9.name: test9 test9.description: "Test ossimChipper::getChip() through ossim-chipper-test app." test9.enabled: 1 // Commands to generate expected results: // Write chip to file: test9.expected_results_command0: ossim-chipper-test chipper-test-options-001.kwl $(OBT_EXP_DIR)/t9.ras // Make a histogram: test9.expected_results_command1: ossim-preproc --ch $(OBT_EXP_DIR)/t9.ras // Make an info file: test9.expected_results_command2: ossim-info -i $(OBT_EXP_DIR)/t9.ras > $(OBT_EXP_DIR)/t9-info.txt // The actual commands to test: // Write chip to file: test9.test_command0: ossim-chipper-test chipper-test-options-001.kwl $(OBT_OUT_DIR)/t9.ras // Make a histogram: test9.test_command1: ossim-preproc --ch $(OBT_OUT_DIR)/t9.ras // Make an info file: test9.test_command2: ossim-info -i $(OBT_OUT_DIR)/t9.ras > $(OBT_OUT_DIR)/t9-info.txt // Post process commands for diffs and stuff: test9.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t9-info.txt $(OBT_OUT_DIR)/t9-info.txt test9.postprocess_command1: $(DIFF_CMD) $(OBT_EXP_DIR)/t9.his $(OBT_OUT_DIR)/t9.his // --- // End test9: // --- ossim-Miami-2.9.1/test/config/potrace-test.kwl000066400000000000000000000035461352751253100213000ustar00rootroot00000000000000//=================================================================================== // // File: potrace-test.kwl // // Description: ossim-batch-test template config file. // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * If the config file contains more than a single test, then it will be necessary // to prefix all test-specific keywords with "testN." // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during runtime to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // //=================================================================================== test1.description: Test of potrace plugin // Commands to generate expected results. test1.expected_results_command0: ossim-potrace $(OSSIM_BATCH_TEST_DATA)/public/potrace/simulated.tif > $(OBT_EXP_DIR)/potrace-plugin-test.txt // The actual commands to test. test1.test_command0: ossim-potrace $(OSSIM_BATCH_TEST_DATA)/public/potrace/simulated.tif > $(OBT_OUT_DIR)/potrace-plugin-test.txt // The post-processing (comparison) commands. Typically these involve a file // comparison of last run command against expected results. test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/simulated.geojson $(OBT_OUT_DIR)/simulated.geojson test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/potrace-plugin-test.txt $(OBT_OUT_DIR)/potrace-plugin-test.txt ossim-Miami-2.9.1/test/config/super-test.kwl000066400000000000000000000061441352751253100207760ustar00rootroot00000000000000//=================================================================================== // // File: super-test.kwl // Generated by command: ossim-batch-test -W super-test.kwl // Description: ossim-batch-test template config file. // // Control flags: // Use 1 or true, 0 or false to turn on and off sections. // Typically preprocess and expected results only turned on for first run. // Clean commands should erase anything created by this test. // Command order if flag turned on: // 1) clean, 2) pre-process, 3) expected, 4) test, 5) post-process // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during run-time to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // // * In order to preserve platform independence, please utilize the following // variables for the common OS commands when adding new commands to the test // configuration KWL file. Examples are provided in this template // $(DIFF_CMD) Use this var for windows "fc" or linux "diff" // $(COPY_CMD) Use this var for windows "copy" or linux "cp" // $(MKDIR_CMD) Use this var for windows "mkdir" or linux "mkdir" // $(RM_CMD) Use this var for windows "del /Q" or linux "rm -f" // $(RMDIR_CMD) Use this var for windows "rmdir /S /Q" or linux "rm -rf" // This application will set the environment variables to the proper values at // runtime, so no need to worry about defining these. // // * Use forward slashes "//", at beginning of line for comments. // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * Clean, preprocess, run, and accept test sections can be switched on or off // at run time. These override config file flags. Optional arguments are the // the following: // -c or --clean-test // -p or --preprocess-test // -r or --run-test // -a or --accept-test // Multiple tests can be entered by quoting string of space-separated // test names, e.g. "test1 test2". To do all tests use "all" or leave blank. // //=================================================================================== // If the config file will contain only a list of subordinate config files to be // run as one consolidated "super-test", then use only the following suffixed // keywords. Otherwise, REMOVE THESE: test_config_file0: applanix-test.kwl test_config_file1: eq-test.kwl test_config_file2: fusion-test1.kw1 test_config_file3: genras-writer-test.kwl test_config_file4: height-info-test.kwl test_config_file5: index-to-rgb-lut.kwl test_config_file6: test1.kwl test_config_file7: wrap-test.kwl test_config_file8: hlz-test.kwl test_config_file9: viewshed-test.kwl ossim-Miami-2.9.1/test/config/test1.kwl000066400000000000000000000114621352751253100177220ustar00rootroot00000000000000//=================================================================================== // // File: test1.kwl // Description: Contains assorted tests. // // Control flags: // Use 1 or true, 0 or false to turn on and off sections. // Typically preprocess and expected results only turned on for first run. // Clean commands should erase anything created by this test. // Command order if flag turned on: // 1) clean, 2) pre-process, 3) expected, 4) test, 5) post-process // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during run-time to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // // * In order to preserve platform independence, please utilize the following // variables for the common OS commands when adding new commands to the test // configuration KWL file. Examples are provided in this template // $(DIFF_CMD) Use this var for windows "fc" or linux "diff" // $(COPY_CMD) Use this var for windows "copy" or linux "cp" // $(MKDIR_CMD) Use this var for windows "mkdir" or linux "mkdir" // $(RM_CMD) Use this var for windows "del /Q" or linux "rm -f" // $(RMDIR_CMD) Use this var for windows "rmdir /S /Q" or linux "rm -rf" // This application will set the environment variables to the proper values at // runtime, so no need to worry about defining these. // // * Use forward slashes "//", at beginning of line for comments. // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * Clean, preprocess, run, and accept test sections can be switched on or off // at run time. These override config file flags. Optional arguments are: // -c or --clean-test // -p or --preprocess-test // -r or --run-test // -a or --accept-test // Multiple tests can be entered by quoting string of space separated // test, e.g. "test1 test2". To accept all tests use "all" for test. // //=================================================================================== // --- // Begin test1: // --- test1.name: test1 test1.description: Test geographic projection with nitf format. test1.enabled: 1 // Commands to generate expected results: test1.expected_results_command0: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/ntf/Clinton_IA.ntf > $(OBT_EXP_DIR)/nitf-info.txt // The actual commands to test: test1.test_command0: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/ntf/Clinton_IA.ntf > $(OBT_OUT_DIR)/nitf-info.txt // Post process commands for diffs and stuff: test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/nitf-info.txt $(OBT_OUT_DIR)/nitf-info.txt // --- // Begin test3: // --- test3.name: test3 test3.description: Test geographic projection with tiff format. test3.enabled: 1 // Commands to generate expected results: test3.expected_results_command0: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/tif/Clinton_IA.tif > $(OBT_EXP_DIR)/tif-geo-info.txt // The actual commands to test: test3.test_command0: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/tif/Clinton_IA.tif > $(OBT_OUT_DIR)/tif-geo-info.txt // Post process commands for diffs and stuff: test3.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/tif-geo-info.txt $(OBT_OUT_DIR)/tif-geo-info.txt // --- // Begin test4: // --- test4.name: test4 test4.description: Test utm projection with tiff format. test4.enabled: 1 // Commands to generate expected results: test4.expected_results_command0: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/tif/Iowa-utm.tif > $(OBT_EXP_DIR)/tif-utm-info.txt // The actual commands to test: test4.test_command0: ossim-info -d -i -p $(OSSIM_BATCH_TEST_DATA)/public/tif/Iowa-utm.tif > $(OBT_OUT_DIR)/tif-utm-info.txt // Post process commands for diffs and stuff: test4.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/tif-utm-info.txt $(OBT_OUT_DIR)/tif-utm-info.txt // --- // Begin: test5 // --- test5.name: test5 test5.description: Test ossimImageData::loadTile from 16 to 8. Test histogram dropping last bin. test5.enabled: 1 // Commands to generate expected results: test5.expected_results_command0: ossim-loadtile-test > $(OBT_EXP_DIR)/test5.txt // The actual commands to test: test5.test_command0: ossim-loadtile-test > $(OBT_OUT_DIR)/test5.txt // Post process commands for diffs and stuff: test5.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/test5.txt $(OBT_OUT_DIR)/test5.txt // --- // End: test5 // --- ossim-Miami-2.9.1/test/config/viewshed-test.kwl000066400000000000000000000042631352751253100214560ustar00rootroot00000000000000//=================================================================================== // // File: viewshed-test.kwl // // Description: ossim-batch-test template config file. // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * If the config file contains more than a single test, then it will be necessary // to prefix all test-specific keywords with "testN." // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during runtime to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // //=================================================================================== test1.name: viewshed-test-pattern test1.description: Viewshed test using synthesized test pattern as input DEM test1.enabled: 1 //--------------------------------------- // Commands to generate expected results. //--------------------------------------- test1.expected_results_command0: ossim-viewshed --dem $OSSIM_BATCH_TEST_DATA/public/viewshed/vs-test-dem.tif --lut $OSSIM_BATCH_TEST_DATA/public/viewshed/vs.lut 0 0 $(OBT_EXP_DIR)/viewshed-test.tif //--------------------------------------- // The actual commands to test. //--------------------------------------- test1.test_command0: ossim-viewshed --dem $OSSIM_BATCH_TEST_DATA/public/viewshed/vs-test-dem.tif --lut $OSSIM_BATCH_TEST_DATA/public/viewshed/vs.lut 0 0 $(OBT_OUT_DIR)/viewshed-test.tif //--------------------------------------- // The post-processing (comparison) commands. Typically these involve a file // comparison of last run command against expected results. //--------------------------------------- test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/viewshed-test.tif $(OBT_OUT_DIR)/viewshed-test.tif ossim-Miami-2.9.1/test/config/wrap-test.kwl000066400000000000000000000067661352751253100206230ustar00rootroot00000000000000//=================================================================================== // // File: wrap-test.kwl // Description: Test output of edge to edge world scene. // // Control flags: // Use 1 or true, 0 or false to turn on and off sections. // Typically preprocess and expected results only turned on for first run. // Clean commands should erase anything created by this test. // Command order if flag turned on: // 1) clean, 2) pre-process, 3) expected, 4) test, 5) post-process // // NOTES: // * The following environment variables must be set before running batch test: // OSSIM_BATCH_TEST_DATA Top-level dir containing all test source data // OSSIM_BATCH_TEST_RESULTS Top-level dir containing all test results (exp, // out and log), // // * The variables OBT_EXP_DIR and OBT_OUT_DIR are assigned during run-time to // the proper paths according to the config filename. It isn't required to replace // these nor predefine them in the environment. You can leave them as is or modify // the paths to your unconventional file paths. // // * In order to preserve platform independence, please utilize the following // variables for the common OS commands when adding new commands to the test // configuration KWL file. Examples are provided in this template // $(DIFF_CMD) Use this var for windows "fc" or linux "diff" // $(COPY_CMD) Use this var for windows "copy" or linux "cp" // $(MKDIR_CMD) Use this var for windows "mkdir" or linux "mkdir" // $(RM_CMD) Use this var for windows "del /Q" or linux "rm -f" // $(RMDIR_CMD) Use this var for windows "rmdir /S /Q" or linux "rm -rf" // This application will set the environment variables to the proper values at // runtime, so no need to worry about defining these. // // * Use forward slashes "//", at beginning of line for comments. // // * You can use existing environment variables as $(YOUR_VARIABLE). They will be // expanded at run time if valid. // // * Clean, preprocess, run, and accept test sections can be switched on or off // at run time. These override config file flags. Optional arguments are: // -c or --clean-test // -p or --preprocess-test // -r or --run-test // -a or --accept-test // Multiple tests can be entered by quoting string of space separated // test, e.g. "test1 test2". To accept all tests use "all" for test. // //=================================================================================== // --- // Begin test1: // --- test1.name: test1 test1.description: Test output of edge to edge world scene. test1.enabled: 1 // Commands to generate expected results: test1.expected_results_command0: ossim-orthoigen $(OSSIM_BATCH_TEST_DATA)/public/bmng/july/world.200407.3x5400x2700.jpg $(OBT_OUT_DIR)/t1.tif //test1.expected_results_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram-fast $(OBT_OUT_DIR)/t1.tif test1.expected_results_command1: ossim-info -d -i -p $(OBT_OUT_DIR)/t1.tif > $(OBT_EXP_DIR)/t1-info.txt // The actual commands to test: test1.test_command0: ossim-orthoigen $(OSSIM_BATCH_TEST_DATA)/public/bmng/july/world.200407.3x5400x2700.jpg $(OBT_OUT_DIR)/t1.tif //test1.test_command1: ossim-preproc -r --ot ossim_kakadu_nitf_j2k --create-histogram-fast $(OBT_OUT_DIR)/t1.tif test1.test_command1: ossim-info -d -i -p $(OBT_OUT_DIR)/t1.tif > $(OBT_OUT_DIR)/t1-info.txt // Post process commands for diffs and stuff: test1.postprocess_command0: $(DIFF_CMD) $(OBT_EXP_DIR)/t1-info.txt $(OBT_OUT_DIR)/t1-info.txt ossim-Miami-2.9.1/test/src/000077500000000000000000000000001352751253100154615ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/CMakeLists.txt000066400000000000000000000015551352751253100202270ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ # Only "install" the following. OSSIM_SETUP_APPLICATION(ossim-batch-test INSTALL COMPONENT_NAME ossim SOURCE_FILES ossim-batch-test.cpp) # Remainder to be built but not installed OSSIM_SETUP_APPLICATION(ossim-foo COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-foo.cpp) OSSIM_SETUP_APPLICATION(ossim-test COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-test.cpp) OSSIM_SETUP_APPLICATION(ossim-helloworld COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-helloworld.cpp) add_subdirectory(base) add_subdirectory(elevation) add_subdirectory(gsoc) add_subdirectory(imaging) add_subdirectory(parallel) add_subdirectory(point_cloud) add_subdirectory(projection) add_subdirectory(support_data) add_subdirectory(util) add_subdirectory(vec) if (OSSIM_HAS_HDF5) add_subdirectory(hdf5) endif (OSSIM_HAS_HDF5) ossim-Miami-2.9.1/test/src/base/000077500000000000000000000000001352751253100163735ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/base/CMakeLists.txt000066400000000000000000000066751352751253100211510ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ # Remainder to be built but not installed OSSIM_SETUP_APPLICATION(ossim-byte-stream-buffer-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-byte-stream-buffer-test.cpp) OSSIM_SETUP_APPLICATION(ossim-csv-file-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-csv-file-test.cpp) OSSIM_SETUP_APPLICATION(ossim-date-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-date-test.cpp) OSSIM_SETUP_APPLICATION(ossim-datum-shift INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-datum-shift.cpp) OSSIM_SETUP_APPLICATION(ossim-directory-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-directory-test.cpp) OSSIM_SETUP_APPLICATION(ossim-dms-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-dms-test.cpp) OSSIM_SETUP_APPLICATION(ossim-duration-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-duration-test.cpp) OSSIM_SETUP_APPLICATION(ossim-filename-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-filename-test.cpp) OSSIM_SETUP_APPLICATION(ossim-gpt-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-gpt-test.cpp) OSSIM_SETUP_APPLICATION(ossim-histo-compare INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-histo-compare.cpp) OSSIM_SETUP_APPLICATION(ossim-irect64-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-irect64-test.cpp) OSSIM_SETUP_APPLICATION(ossim-keywordlist-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-keywordlist-test.cpp) OSSIM_SETUP_APPLICATION(ossim-kmeans-clustering-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-kmeans-clustering-test.cpp) OSSIM_SETUP_APPLICATION(ossim-least-squares-plane-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-least-squares-plane-test.cpp) OSSIM_SETUP_APPLICATION(ossim-lsr-space-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-lsr-space-test.cpp) OSSIM_SETUP_APPLICATION(ossim-notify-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-notify-test.cpp) OSSIM_SETUP_APPLICATION(ossim-obj-allocate INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-obj-allocate.cpp) OSSIM_SETUP_APPLICATION(ossim-point-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-point-test.cpp) OSSIM_SETUP_APPLICATION(ossim-rect-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-rect-test.cpp) OSSIM_SETUP_APPLICATION(ossim-ref-ptr-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-ref-ptr-test.cpp) OSSIM_SETUP_APPLICATION(ossim-stream-factory-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-stream-factory-test.cpp) OSSIM_SETUP_APPLICATION(ossim-string-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-string-test.cpp) OSSIM_SETUP_APPLICATION(ossim-thin-plate-spline-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-thin-plate-spline-test.cpp) OSSIM_SETUP_APPLICATION(ossim-threaded-logfile-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-threaded-logfile-test.cpp) OSSIM_SETUP_APPLICATION(ossim-threaded-polyarea2d-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-threaded-polyarea2d-test.cpp) OSSIM_SETUP_APPLICATION(ossim-visitor-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-visitor-test.cpp) OSSIM_SETUP_APPLICATION(ossim-xml-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-xml-test.cpp) ossim-Miami-2.9.1/test/src/base/ossim-argument-parser-test.cpp000066400000000000000000000036051352751253100243240ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test code for ossimGpt class. // //---------------------------------------------------------------------------- // $Id: ossim-gpt-test.cpp 19751 2011-06-13 15:13:07Z dburken $ #include #include #include #include #include using namespace std; template size_t SizeOfArray( const T(&)[ N ] ) { return N; } #define DO_TEST true void fail() { #if DO_TEST cout<<"\nFAILED ossimArgumentParser TEST"< param_list; if ( !ap.read("-c", param_list) || (param_list.size() != 4) || (param_list[0] != "C1") || (param_list[1] != "C2") || (param_list[2] != "C3") || (param_list[3] != "C4")) { fail(); } if (( ap.argc() != 3 ) || (strcmp(ap[1], "arg1") != 0) || (strcmp(ap[2], "arg2") != 0)) fail(); cout<<"\nPASSED ossimArgumentParser TEST"< #include #include // ossim contants... #include #include #include #include #include // ossim contants... #include #include #include // Put your includes here: #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); try { { // testing shared buffer access and writing // char sharedBuf[] = "ABC"; ossimByteStreamBuffer buf(sharedBuf, 3, true); buf.setBuf(sharedBuf, 3, true); std::istream in(&buf); std::cout << "Read single byte test? " << (((char)in.get()=='A')?"Passed":"Failed") << std::endl; in.seekg(3); std::cout << "Read passed input? " << ((in.get()==-1)?"Passed":"Failed") << std::endl; } { // dynamic buffer I/O ossimByteStreamBuffer buf; std::iostream inout(&buf); inout.put(0x00); std::cout << "Read dynamically added byte? " << ((inout.get()==0x00)?"Passed":"Failed") << std::endl; inout << "ABCDEF" << std::endl; inout.seekg(1); std::cout << "Read after << operation? " << (((char)inout.get()=='A')?"Passed":"Failed") << std::endl; inout.seekg(1); std::cout << "Tellg? " << (((ossim_int64)inout.tellg()==1)?"Passed":"Failed") << std::endl; } { // test copy construction ossimByteStreamBuffer buf; std::iostream inout(&buf); inout << "ABCDEFG"; ossimByteStreamBuffer buf2(buf); std::iostream inout2(&buf2); std::cout << "Test read after copy constructor? " << ((inout.get() == inout2.get())?"Passed":"Failed") << std::endl; } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; return 1; } return 0; } ossim-Miami-2.9.1/test/src/base/ossim-csv-file-test.cpp000066400000000000000000000020721352751253100227150ustar00rootroot00000000000000#include // ossim contants... #include #include #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if(argc == 1) { std::cout << "Usage: " << argv[0] << " " << std::endl; return 0; } ossimRefPtr csvFile = new ossimCsvFile; ossimRefPtr record; if(csvFile->open(ossimFilename(argv[1]))) { if(csvFile->readHeader()) { std::copy(csvFile->fieldHeaderList().begin(), csvFile->fieldHeaderList().end(), std::ostream_iterator(std::cout, " ")); while((record = csvFile->nextRecord()).valid()) { // you can print by index or by header field name // std::cout << (*record)[0] << std::endl; std::cout << (*record)[csvFile->fieldHeaderList()[0]] << std::endl; } } } return 0; } ossim-Miami-2.9.1/test/src/base/ossim-date-test.cpp000066400000000000000000000022721352751253100221240ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test code for generic ossim test. // // //---------------------------------------------------------------------------- // $Id: ossim-date-test.cpp 19751 2011-06-13 15:13:07Z dburken $ #include using namespace std; #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); std::string s1 = "2009-02-05T11:26:13.458650Z"; ossimLocalTm d1; d1.setIso8601(s1); std::string s2 = "2009-01-11T09:06:05.606000Z"; ossimLocalTm d2; d2.setIso8601(s2); cout << "s1: " << s1 << "\n"; d1.dump(std::cout); cout << "s2: " << s2 << "\n"; d2.dump(std::cout); ossimLocalTm d4; cout << "local time:\n"; d4.dump(cout); ossimLocalTm d5 = d4.convertToGmt(); cout << "local time converted to GMT:\n"; d5.dump(cout); ossimDate d6; cout << "Date:\n"; d6.print(cout); cout << "\n"; d6.dump(cout); cout << endl; return 0; } ossim-Miami-2.9.1/test/src/base/ossim-datum-shift.cpp000066400000000000000000000066671352751253100224730ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Contains application for simple datum shift test. // // $Id: ossim-datum-shift.cpp 19900 2011-08-04 14:19:57Z dburken $ //---------------------------------------------------------------------------- #include #include #include #include using namespace std; #include #include #include #include // Future use registry. // #include int main() { clock_t time_start = clock(); // To initialize factories. ossimInit::instance()->initialize(); clock_t time_init = clock(); // WGS 84 datum: const ossimDatum* wgeDatum = ossimDatumFactory::instance()->create(ossimString("WGE")); if (!wgeDatum) { ossimNotify(ossimNotifyLevel_WARN) << "WGE datum create failed! Exiting..." << std::endl; exit(1); } // HARN NORTH AMERICAN 1983 NADCON datum code = NAR const ossimDatum* narDatum = ossimDatumFactory::instance()->create(ossimString("NAR")); if (!narDatum) { ossimNotify(ossimNotifyLevel_WARN) << "HARN NAD 83 datum create failed! Exiting..." << std::endl; exit(1); } // NORTH AMERICAN 1927 NADCON datum code = NAR const ossimDatum* nascDatum = ossimDatumFactory::instance()->create(ossimString("NAS-C")); if (!nascDatum) { ossimNotify(ossimNotifyLevel_WARN) << "NAS C datum create failed! Exiting..." << std::endl; exit(1); } //--- // Input point: // 41°51'14.6290" N, 090°11'06.0498" W // 41.854063625169729 -90.185013857895839 149.6 //--- ossimGpt wgePt(41.854063625169729, -90.185013857895839, 149.6, wgeDatum); // Copy it. ossimGpt narPt = wgePt; ossimGpt nascPt = wgePt; // Shift to new datum. narPt.changeDatum(narDatum); nascPt.changeDatum(nascDatum); ossimNotify(ossimNotifyLevel_NOTICE) << "WGS84 pt: " << wgePt << "\nHARN NAD83 pt: " << narPt << "\nNAS-C pt: " << nascPt << std::endl; double lat = 0.0; double lon = 0.0; do { // Walk the ellipsoid test. ossimGpt gp1 = ossimGpt(lat, lon, 0.0); ossimGpt gp2 = gp1; gp2.changeDatum(nascDatum); // Clark ellipsoid. double shiftLat = gp1.latd() - gp2.latd(); double shiftLon = gp1.lond() - gp2.lond(); ossimNotify(ossimNotifyLevel_NOTICE) << setiosflags(ios::fixed) << setprecision(15) << "\nWGS84 pt: " << gp1 << "\nNAS-C pt: " << gp2 << "\nShift lat (WGS8 - NASC): " << setiosflags(ios::fixed) << setprecision(15) << shiftLat << "\nShift lon (WGS8 - NASC): " << shiftLon << std::endl; lat += 5.0; } while (lat < 65.0); clock_t time_end = clock(); double init_time = (time_init - time_start)/(double)CLOCKS_PER_SEC; double exec_time = (time_end - time_start)/(double)CLOCKS_PER_SEC; cout <<"\nTiming (in seconds):\n" <<" Initialization: "< #include #include #include #include using namespace std; static void usage() { cout << "ossim-directory-test " << "\nDumps files in directory..." << endl; } int main(int argc, char *argv[]) { int result = 0; ossimInit::instance()->initialize(argc, argv); if (argc == 2) { try // Exceptions can be thrown so { ossimFilename directory = argv[1]; cout << "directory: " << directory << "\n"; directory = directory.expand(); ossimDirectory d; if ( d.open(directory) ) { ossimFilename f; if ( d.getFirst(f) ) { do { if ( f.size() ) { cout << "file: " << f << endl; } else { cout << "file is empty!" << endl; } } while ( d.getNext(f) ); } else { cout << "ossimDirectory::getFirst() returned false!" << endl; } } } catch( const ossimException& e ) { cout << e.what() << endl; result = 1; } } else { usage(); } return result; } ossim-Miami-2.9.1/test/src/base/ossim-dms-test.cpp000066400000000000000000000046761352751253100220040ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Contains application for simple ossimDms class code examples. // // $Id: ossim-dms-test.cpp 23494 2015-08-28 15:11:03Z okramer $ //---------------------------------------------------------------------------- #include #include using namespace std; int main() { // Test default constructor. ossimDms dms; cout << "dms using default constuctor:" << "\ndms.getDegrees(): " << dms.getDegrees() << "\ndms.toString(): " << dms.toString() << endl; const ossimString LAT_FORMAT = "dd@ mm' ss.ssss\" C"; const ossimString LON_FORMAT = "ddd@ mm' ss.ssss\" C"; ossimDms d(0.0); ossimString dmsstr = "S30 20 20"; if (d.setDegrees(dmsstr) == true) { cout << "dmsstr: " << dmsstr << "\nd.getDegrees(): " << d.getDegrees() << "\nd.toString(): " << d.toString(LAT_FORMAT) << endl; } else { cout << "setDegrees failed..." << endl; } dmsstr = " N30 20 20"; if (d.setDegrees(dmsstr)) { cout << "dmsstr: " << dmsstr << "\nd.getDegrees(): " << d.getDegrees() << "\nd.toString(): " << d.toString(LAT_FORMAT) << endl; } else { cout << "setDegrees failed..." << endl; } dmsstr = "/some/one/punched/in/a/file/name..."; if (d.setDegrees(dmsstr)) { cout << "dmsstr: " << dmsstr << "\nd.getDegrees(): " << d.getDegrees() << "\nd.toString(): " << d.toString(LAT_FORMAT) << endl; } else { cout << "setDegrees failed..." << endl; } dmsstr = "32 59 00 N"; d.setLatFlag(true); if (d.setDegrees(dmsstr)) { cout << "dmsstr: " << dmsstr << "\nd.getDegrees(): " << d.getDegrees() << "\nd.toString(): " << d.toString(LAT_FORMAT) << endl; } else { cout << "setDegrees failed..." << endl; } dmsstr = "085 00 00 E"; d.setLatFlag(false); if (d.setDegrees(dmsstr)) { cout << "dmsstr: " << dmsstr << "\nd.getDegrees(): " << d.getDegrees() << "\nd.toString(): " << d.toString(LAT_FORMAT) << endl; } else { cout << "setDegrees failed..." << endl; } return 0; } ossim-Miami-2.9.1/test/src/base/ossim-duration-test.cpp000066400000000000000000000023531352751253100230340ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Garrett Potts // // Description: Test app for ossimString class. // // $Id: ossim-duration-test.cpp 19751 2011-06-13 15:13:07Z dburken $ //---------------------------------------------------------------------------- #include #include #include int main(int argc, char *argv[]) { ossimDuration duration; ossimString convertBack; ossimString testString("-P1DT25S"); duration.setByIso8601DurationString(testString); duration.toIso8601DurationString(convertBack); if(testString != convertBack) { std::cout << "ERROR: " << testString << " != " << convertBack << std::endl; } if(!ossim::almostEqual(duration.toSeconds(), -86425.0, .000000001)) { std::cout << "Seconds calculation is bad for " << testString << std::endl; } testString = "P12Y1M1DT10M25.5S"; duration.setByIso8601DurationString(testString); duration.toIso8601DurationString(convertBack); if(testString != convertBack) { std::cout << "ERROR: " << testString << " != " << convertBack << std::endl; } return 0; } ossim-Miami-2.9.1/test/src/base/ossim-filename-test.cpp000066400000000000000000000141171352751253100227700ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // ossimFilename class test app. // //---------------------------------------------------------------------------- // $Id: ossim-filename-test.cpp 20097 2011-09-14 17:03:00Z dburken $ #include #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); ossimFilename directoryToDelete; if ( argc == 2 ) { ossimString osArg1 = argv[1]; osArg1.downcase(); if ( (osArg1 == "-h") || (osArg1 == "--help") ) { cout << "\nUsage: ossim-filename-test \n" << "Runs various test on ossimFilename class.\n" << "If optional_directory_to_delete is set calls ossimFilename::remove on it.\n" << "Options: -h --help Gives this usage.\n" << endl; return 0; } else { directoryToDelete = argv[1]; } } ossimFilename a = "c:\\foo\\you"; ossimFilename a2 = "\\foo\\you"; ossimFilename b = "/foo/you"; ossimFilename c = "foo/you"; ossimFilename d1 = "~/docs"; ossimFilename d2 = "./foo"; ossimFilename d3 = "../../foo"; ossimFilename d4 = "."; ossimFilename d5 = "ab"; ossimFilename d6 = "a"; // Environment var WORK must be set. ossimFilename d7 = "$(WORK)/ossim"; ossimFilename d8 = "~/tmp/$(WORK)/ossim"; // Test windows x$ ossimFilename d9 = "//kiosk/x$/SourceImagery/foo.ntf"; ossimFilename e = "/foo/you.xxx"; ossimString ext1 = ".tif"; ossimString ext2 = "jpg"; ossimString ext3; cout << "\na: " << a << "\na.expand(): " << a.expand() << "\na.isRelative(): " << a.isRelative() << "\n" << "\na2: " << a2 << "\na2.expand(): " << a2.expand() << "\na2.isRelative(): " << a2.isRelative() << "\n" << "\nb: " << b << "\nb.expand(): " << b.expand() << "\nb.isRelative(): " << b.isRelative() << "\n" << "\nc: " << c << "\nc.expand(): " << c.expand() << "\nc.isRelative(): " << c.isRelative() << "\n" << "\nd1: " << d1 << "\nd1.expand(): " << d1.expand() << "\nd1.isRelative(): " << d1.isRelative() << "\n" << "\nd2: " << d2 << "\nd2.expand(): " << d2.expand() << "\nd2.isRelative(): " << d2.isRelative() << "\n" << "\nd3: " << d3 << "\nd3.expand(): " << d3.expand() << "\nd3.isRelative(): " << d3.isRelative() << "\n" << "\nd4: " << d4 << "\nd4.expand(): " << d4.expand() << "\nd4.isRelative(): " << d4.isRelative() << "\n" << "\nd5: " << d5 << "\nd5.expand(): " << d5.expand() << "\nd5.isRelative(): " << d5.isRelative() << "\n" << "\nd6: " << d6 << "\nd6.expand(): " << d6.expand() << "\nd6.isRelative(): " << d6.isRelative() << "\n"; cout << "\nNOTE: d7 and d8 output require variable WORK be set in your " << "environment.\n" << "\nd7: " << d7 << "\nd7.expand(): " << d7.expand() << "\nd7.isRelative(): " << d7.isRelative() << "\n" << "\nd8: " << d8 << "\nd8.expand(): " << d8.expand() << "\nd8.isRelative(): " << d8.isRelative() << "\n" << "\nd9: " << d9 << "\nd9.expand(): " << d9.expand() << "\nd9.isRelative(): " << d9.isRelative() << "\n" << "\next1: " << ext1 << "\next2: " << ext2 << "\next3: " << ext3 << "\n"; cout << "e: " << e << "\n"; cout << "e.setExtension(ext1): " << e.setExtension(ext1) << "\n"; cout << "e.setExtension(ext2): " << e.setExtension(ext2) << "\n"; cout << "e.setExtension(ext3): " << e.setExtension(ext3) << "\n"; // Test dir cat. a = "/foo/"; b = "you"; c = a.dirCat(b); cout << "\na: " << a << "\nb: " << b << "\nc = a.dirCat(b): " << c << "\n"; a = "/foo"; b = "you"; c = a.dirCat(b); cout << "\na: " << a << "\nb: " << b << "\nc = a.dirCat(b): " << c << "\n"; a = "/foo"; b = "./you"; c = a.dirCat(b); cout << "\na: " << a << "\nb: " << b << "\nc = a.dirCat(b): " << c << "\n"; a = "/foo"; b = "/you"; c = a.dirCat(b); cout << "\na: " << a << "\nb: " << b << "\nc = a.dirCat(b): " << c << "\n"; a = "/foo"; b = ""; c = a.dirCat(b); cout << "\na: " << a << "\nb: " << b << "\nc = a.dirCat(b): " << c << "\n"; a = ""; b = "you"; c = a.dirCat(b); cout << "\na: " << a << "\nb: " << b << "\nc = a.dirCat(b): " << c << "\n"; a = "/data/images/t1.tif"; cout << "\na: " << a << "\na.fileNoExtension(): " << a.fileNoExtension() << "\na.noExtension(): " << a.noExtension() << "\n"; // Test a file with two dots. a = "/data/ascii_dems/dtm_v1.5_5mp_3141.asc"; cout << "\n// Test a file with two dots." << "\na: " << a << "\na.fileNoExtension(): " << a.fileNoExtension() << "\na.noExtension(): " << a.noExtension() << "\n"; std::string s = "abc"; ossimFilename f = s; // Used to not compile. cout << "ossimFilename f = std::string(abc): " << f << "\n"; // Test a if ( directoryToDelete.size() ) { cout << "ossimFilename::remove on " << directoryToDelete << " was "; if ( directoryToDelete.remove() ) { cout << "successful...\n"; } else { cout << "unsuccessful...\n"; } } cout << endl; return 0; } ossim-Miami-2.9.1/test/src/base/ossim-gpt-test.cpp000066400000000000000000000062101352751253100217750ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test code for ossimGpt class. // //---------------------------------------------------------------------------- // $Id: ossim-gpt-test.cpp 19751 2011-06-13 15:13:07Z dburken $ #include using namespace std; #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); cout << "ossimGpt::wrap test:\n"; ossimGpt gpt(0.0, 0.0, 0.0); cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = 45.0; gpt.lon = 45.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = 90.0; gpt.lon = 180.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = 91.0; gpt.lon = 181.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = 179.0; gpt.lon = 359.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = 181.0; gpt.lon = 361.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = 271.0; gpt.lon = 361.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = 359.0; gpt.lon = 361.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = 361.0; gpt.lon = 721.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = 451.0; gpt.lon = 901.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = -45.0; gpt.lon = -45.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = -90.0; gpt.lon = -180.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = -91.0; gpt.lon = -181.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = -179.0; gpt.lon = -359.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = -181.0; gpt.lon = -361.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = -271.0; gpt.lon = -361.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = -359.0; gpt.lon = -361.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = -361.0; gpt.lon = -721.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; gpt.lat = -451.0; gpt.lon = -901.0; cout << "gpt: " << gpt << "\n"; gpt.wrap(); cout << "gpt::wrap: " << gpt << "\n\n"; return 0; } ossim-Miami-2.9.1/test/src/base/ossim-histo-compare.cpp000066400000000000000000000211611352751253100230020ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // Description: // // Command line application "ossim-histo-compare" to evaluate differences between histograms. // //---------------------------------------------------------------------------- // $Id: ossim-histo-compare.cpp 19751 2011-06-13 15:13:07Z dburken $ #include #include #include #include #include #include #include #include #include #include /* for exit */ using namespace std; //************************************************************************************************* // FINALIZE -- Convenient location for placing debug breakpoint for catching program exit. //************************************************************************************************* void finalize(int code) { exit (code); } //************************************************************************************************* // MAIN //************************************************************************************************* int main(int argc, char* argv[]) { ossimString tempString; double tempDouble, tempDouble2; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser::ossimParameter doubleParam(tempDouble); ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+ " compares two ossim histogram files and presents statistics about differences. The return " "value is 0 if histograms are within difference tolerances and 1 if not."); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+ " [options] "); argumentParser.getApplicationUsage()->addCommandLineOption("--tolerance | -t ", "Tolerance (0.0 - 100.0) as percent of difference to total bin population. If any bin's " "count difference is found to exceed , the comparison will fail."); argumentParser.getApplicationUsage()->addCommandLineOption("--max-sigma | -s ", "Tolerance in standard deviation from 0 mean difference. If the mean RSS of all" "differences is greater that , the comparison will fail."); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help", "Shows help"); if(argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(std::cout); finalize(0); } if ( argumentParser.read("--version") || argumentParser.read("-v")) { ossimNotify(ossimNotifyLevel_NOTICE)<< argumentParser.getApplicationName().c_str() << " " << ossimInit::instance()->instance()->version().c_str()<< std::endl; finalize(0); } // Fetch command line options: double tolerance = .5; // % default (= 0.005) if (argumentParser.read("--tolerance", doubleParam) || argumentParser.read("-t", doubleParam)) tolerance = tempDouble/100.0; double max_sigma = 0.05; if (argumentParser.read("--max-sigma", doubleParam) || argumentParser.read("-s", doubleParam)) max_sigma = tempDouble; // Handle bad command line: argumentParser.reportRemainingOptionsAsUnrecognized(); if (argumentParser.errors()) { argumentParser.writeErrorMessages(std::cout); finalize(1); } if(argumentParser.argc() < 3) { argumentParser.getApplicationUsage()->write(std::cout); finalize(1); } // Establish the two histogram objects from files: ossimFilename histofile1(argv[1]); ossimRefPtr mrl_histo1 = new ossimMultiResLevelHistogram; bool success = mrl_histo1->importHistogram(histofile1); if (!success) { ossimNotify(ossimNotifyLevel_FATAL)<< argumentParser.getApplicationName().c_str() << ": Error encountered establishing histogram from <"<. Failed."< mrl_histo2 = new ossimMultiResLevelHistogram; success = mrl_histo2->importHistogram(histofile2); if (!success) { ossimNotify(ossimNotifyLevel_FATAL)<< argumentParser.getApplicationName().c_str() << ": Error encountered establishing histogram from <"<. FAILED."<getNumberOfResLevels(); ossim_uint32 nlevels2 = mrl_histo2->getNumberOfResLevels(); if (nlevels1 != nlevels2) { ossimNotify(ossimNotifyLevel_FATAL)<< argumentParser.getApplicationName().c_str() << ": Number of resolution levels does not match. FAILED."<getNumberOfBands(); ossim_uint32 nbands2 = mrl_histo2->getNumberOfBands(); if (nbands1 != nbands2) { ossimNotify(ossimNotifyLevel_FATAL)<< argumentParser.getApplicationName().c_str() << ": Number of bands does not match. FAILED."< histo1 = mrl_histo1->getHistogram(band, rlevel); const ossimRefPtr histo2 = mrl_histo2->getHistogram(band, rlevel); float min_val = histo1->GetMinVal(); float max_val = histo1->GetMaxVal(); float del_val = histo1->GetBucketSize(); std::vector norm_diffs; ossim_uint32 diff, count1, count2; double norm_diff; // Loop over all bins to collect all differences: for (float val=min_val; val<=max_val; val+=del_val) { count1 = (ossim_uint32) histo1->GetCount(val); count2 = (ossim_uint32) histo2->GetCount(val); diff = abs((int)(count1 - count2)); if (count1 != 0) norm_diff = (double) diff / count1; else if (count2 != 0) norm_diff = (double) diff / count2; else norm_diff = 0.0; norm_diffs.push_back(100.0 * norm_diff); } // Check trivial case: if (norm_diffs.size() == 0) { ossimNotify(ossimNotifyLevel_FATAL)<< argumentParser.getApplicationName().c_str() << ": No samples found!. FAILED."<< endl; finalize(1); } // Compute statistics on differences: double accum=0; std::vector::iterator i = norm_diffs.begin(); while (i != norm_diffs.end()) { accum += *i; ++i; } double mean = accum / (double) norm_diffs.size(); accum=0; i = norm_diffs.begin(); while (i != norm_diffs.end()) { accum += (*i - mean) * (*i - mean); ++i; } double sigma = sqrt(accum) / (double) norm_diffs.size(); // Output mean and sigma for this histo comparison: ossimNotify(ossimNotifyLevel_FATAL)<<" Mean normalized difference: "< tolerance) { ossimNotify(ossimNotifyLevel_FATAL)<<" Found mean difference of "< max_sigma) { ossimNotify(ossimNotifyLevel_FATAL)<<" Computed sigma of "< #include #include #include #include // Put your includes here: // System includes: #include #include #include #include using namespace std; int main(int argc, char *argv[]) { int returnCode = 0; // ossimArgumentParser ap(&argc, argv); // ossimInit::instance()->addOptions(ap); // ossimInit::instance()->initialize(ap); try { std::string s0 = "(16, 18, 20, 20, LH)"; // endpt = (35, 37) ossimIrect64 r0; r0.toRect(s0); ossimIpt64 endPt0; r0.end( endPt0 ); cout << "\ns0: " << s0 << "\nr0: " << r0 << "\nr0 end pt: " << endPt0 << endl; ossimIrect64 r1( ossimIpt64(32, 32), ossimIpt64(20, 20)); // endpt = (51,51) ossimIpt64 endPt1; r1.end( endPt1 ); cout << "\nr1: " << r1 << "\nr1 end pt: " << endPt1 << endl; cout << "\nr0 intersects r1: " << (r0.intersects(r1)?"true":"false") << endl; cout << "\nr1 clipped to r0: " << r1.clipToRect(r0) << endl; cout << "\nr1 combined with r0: " << r1.combine(r0) << endl; ossimIrect64 r2(65, 65, 18, 18); ossimIpt64 endPt2; r2.end( endPt2 ); cout << "\nr2: " << r2 << "\nr2 end pt: " << endPt2 << endl; cout << "\nr2 clipped to r0: " << r2.clipToRect(r0) << endl; cout << "\nr2 combined with r0: " << r2.combine(r0) << endl; ossimIrect64 r3( 123, OSSIM_INT64_NAN, 456, OSSIM_INT64_NAN ); ossimString s3 = r3.toString(); ossimIrect64 r4; r4.toRect(s3); cout << "\nr3: " << r3 << "\ns3: " << s3 << "\nr4: " << r4 << endl; ossimIrect64 r5(82, 82, 10, 10); cout << "\nr5: " << r5 << "\nr5.clipped to r2" << r5.clipToRect(r2) << "\nr5.clipped to r1" << r5.clipToRect(r1) << endl; ossimIrect64 r6(1024, 1024, 256, 256); ossimIrect64 r7(0, 0, 2024, 2048); ossimIrect64 r8(1000, 1000, 256, 256); cout << "\nr6: " << r6 << "\nr7: " << r7 << "\nr8: " << r8 << "\nr6 completely within r7: " << r6.completely_within( r7 ) << "\nr6 completely within r8: " << r6.completely_within( r8 ) << endl; ossimIrect64 r9(553, -553, 950, 950); ossimIpt64 tileWidthHeight(64,64); cout << "\nr9: " << r9 << " end: " << r9.end(); r9.stretchToTileBoundary(tileWidthHeight); cout << "\nr9.stretchToTileBoundary(64,64): " << r9 << " end: " << r9.end() << endl; } catch(const ossimException& e) { // ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } catch( ... ) { // ossimNotify(ossimNotifyLevel_WARN) // << "ossim-pt caught unhandled exception!" << std::endl; returnCode = 1; } return returnCode; } ossim-Miami-2.9.1/test/src/base/ossim-keywordlist-test.cpp000066400000000000000000000265671352751253100236040ustar00rootroot00000000000000#include #include #include #include #include using namespace std; bool runTestForFileVariations() { cout << "------------------ Running tests on different file variations ---------------- \n"; bool test_failed = false; ossimTempFilename tempFile(".", "temp","txt",true,false); tempFile.generateRandomFile(); { ofstream out(tempFile.c_str()); out<< ""; out.close(); ossimKeywordlist kwl; cout << "Empty File Test? "; if(kwl.addFile(tempFile)) { cout << "PASSED" << endl; } else { cout << "FAILED" << endl; test_failed = false; } } { ossimTempFilename tempFileDos(".", "tempDos","txt",true,false); tempFileDos.generateRandomFile(); ofstream outUnix(tempFile.c_str()); ofstream outDos(tempFileDos.c_str()); outUnix<< "key1: value1\n"; outUnix<< "key2: value2\n"; outUnix<< "key3: value3\n"; outUnix<< "key4: value4\n"; outUnix<< "key5: value5\n"; outUnix.close(); outDos<< "key1: value1\r"; outDos<< "key2: value2\r"; outDos<< "key3: value3\r"; outDos<< "key4: value4\r"; outDos<< "key5: value5\r"; outDos.close(); ossimKeywordlist kwlUnix; ossimKeywordlist kwlDos; cout << "Dos carriage returns and unix returns? "; if((kwlUnix.addFile(tempFile)&&kwlDos.addFile(tempFileDos))&& (kwlUnix.getMap() == kwlDos.getMap())) { cout << "PASSED" << endl; } else { cout << "FAILED" << endl; test_failed = true; } } { ofstream out(tempFile.c_str()); out<< "/adfakdfhkadkjh\n"; out.close(); ossimKeywordlist kwl; cout << "bad comment? "; if(kwl.addFile(tempFile)) { cout << "PASSED" << endl; } else { cout << "FAILED" << endl; test_failed = true; } } { ofstream out(tempFile.c_str()); out<< "//adfakdfhkadkjh\n"; out.close(); ossimKeywordlist kwl; cout << "good comment? "; if(kwl.addFile(tempFile)) { cout << "PASSED" << endl; } else { cout << "FAILED" << endl; test_failed = true; } } { ofstream out(tempFile.c_str()); out<< "//adfakdfhkadkjh"; out.close(); ossimKeywordlist kwl; cout << "good comment no end of line? "; if(kwl.addFile(tempFile)) { cout << "PASSED" << endl; } else { cout << "FAILED" << endl; test_failed = true; } } { ofstream out(tempFile.c_str()); out<< "/test:"; out.close(); ossimKeywordlist kwl; cout << "----------- 1 token lookahead problem, single slash start of line with valid key but no value ------------ \n"; cout << "Accepted file? "; if(kwl.addFile(tempFile)) { cout << "PASSED" << endl; } else { cout << "FAILED" << endl; test_failed = true; } cout << "Verify key? "; const char* value = kwl.find("/test"); if (value) { cout << "PASSED" << endl; } else { cout << "FAILED" << endl; test_failed = true; } } { ofstream out(tempFile.c_str()); out<< "test :"; out.close(); cout << "----------- trailing spaces for key trimmed ------------ \n"; ossimKeywordlist kwl; cout << "Accepted file? "; if(kwl.addFile(tempFile)) { cout << "PASSED" << endl; } else { cout << "FAILED" << endl; test_failed = true; } cout << "Verify key? "; const char* value = kwl.find("test"); if (value) { cout << "PASSED" << endl; } else { cout << "FAILED" << endl; test_failed = true; } } { ossimKeywordlist kwl; ossimString value1 =" --leading and trailing--- "; ossimString value2 =" --trailing---"; ossimString value3 ="--leading--- "; kwl.add("","key1", value1); kwl.add("","key2", value2); kwl.add("","key3", value3); kwl.trimAllValues(); cout << "----------- Testing utility method trimAll values ------------ \n"; cout << "Verify value1? "; if (value1.trim() == ossimString(kwl.find("key1"))) cout << "PASSED" << endl; else { cout << "FAILED" << endl; test_failed = true; } cout << "Verify value2? "; if (value2.trim() == ossimString(kwl.find("key2"))) cout << "PASSED" << endl; else { cout << "FAILED" << endl; test_failed = true; } cout << "Verify value3? "; if (value3.trim() == ossimString(kwl.find("key3"))) cout << "PASSED" << endl; else { cout << "FAILED" << endl; test_failed = true; } } return test_failed; } bool runIncludeTest() { cout << "----------- Testing #include directive handling ------------ \n"; ossimTempFilename t1(".", "f1","kwl",true,false); ossimTempFilename t2(".", "f2","kwl",true,false); ossimTempFilename t3(".", "f3","kwl",true,false); ossimTempFilename t4(".", "f4","kwl",true,false); t1.generateRandomFile(); t2.generateRandomFile(); t3.generateRandomFile(); t4.generateRandomFile(); ofstream f1 (t1.chars()); ofstream f2 (t2.chars()); ofstream f3 (t3.chars()); ofstream f4 (t4.chars()); f1<<"f1k1: f1v1\nf1k2: f1v2\n#include "<initialize(argc, argv); ossimString complicatedHtmlEmbed = "\n\ \n\ OMAR Login\n\ \n\ \n\ \ \n\ \n\ \n\ \n\ \n\ \n\ \n\ \n\ "; ossimString testValueAllBlanks = " "; ossimString testValueLeftBlanks = " blanks are to the left"; ossimString testValueRightBlanks = "blanks are to the right "; ossimString testValueRightBlanksEol = "\n\n\n\n\nblanks are to the right \n\n "; ossimKeywordlist kwl; ossimKeywordlist kwl2; kwl.add("test1.", "value", "value no new line", true); kwl.add("test2.", "value", "value \n\n\non separate\nlines", true); kwl.add("test3.", "value", "value no new line", true); kwl.add("test4.", "value", "", true); kwl.add("testAllBlanks.", "value", testValueAllBlanks, true); kwl.add("testLeftBlanks.", "value", testValueLeftBlanks, true); kwl.add("testRightBlanks.", "value", testValueRightBlanks, true); kwl.add("testRightBlanks.", "value", testValueRightBlanks, true); kwl.add("testRightBlanksEol.", "value", testValueRightBlanksEol, true); kwl.add("testZ.", "value", "", true); kwl.add("complicatedHtmlEmbed.", "value", complicatedHtmlEmbed, true); ossimTempFilename tempFile(".", "temp","txt",true,false); tempFile.generateRandomFile(); cout << "tempFile === " << tempFile << endl; ofstream out(tempFile.c_str()); out << kwl << endl; out.close(); kwl2.addFile(tempFile.c_str()); cout << "---------------------- Original KWL --------------------\n"; cout << kwl << endl; cout << "---------------------- Testing Original KWL Read back in from file --------------------\n"; cout << kwl2 << endl; cout << "---------------------- Testing Original KWL toString no arguments--------------------\n"; cout << kwl.toString() << endl; cout << "---------------------- Testing Original KWL toString with arguments--------------------\n"; ossimString result; kwl.toString(result); cout << result << endl; cout << "---------------------- Testing environment variable expand for add variable--------------------\n"; ossimKeywordlist kwl3; kwl3.setExpandEnvVarsFlag(true); kwl3.add("test1.", "value", "$(HOME) no new line", true); kwl3.add("test1.", "value", "$(HOME) no $(HOME) new line", true); cout << kwl3 << endl; cout << "------------------ Running sanity tests to make sure that triple quotes are retained ---------------- \n"; cout << "kwl1 == kwl2? " << ((kwl.getMap() == kwl2.getMap())?"PASSED":"FAILED") << endl; cout << "testValueAllBlanks preserved? " << ((ossimString(kwl2.find("testAllBlanks.value"))==testValueAllBlanks)?"PASSED":"FAILED") << endl; cout << "testValueLeftBlanks preserved? " << ((ossimString(kwl2.find("testLeftBlanks.value"))==testValueLeftBlanks)?"PASSED":"FAILED") << endl; cout << "testValueRightBlanks preserved? " << ((ossimString(kwl2.find("testRightBlanks.value"))==testValueRightBlanks)?"PASSED":"FAILED") << endl; cout << "testRightBlanksEol preserved? " << ((ossimString(kwl2.find("testRightBlanksEol.value"))==testValueRightBlanksEol)?"PASSED":"FAILED") << endl; cout << "complicatedHtmlEmbed preserved? " << ((ossimString(kwl2.find("complicatedHtmlEmbed.value"))==complicatedHtmlEmbed)?"PASSED":"FAILED") << endl; bool test_failed = runTestForFileVariations(); test_failed |= runIncludeTest(); if (!test_failed) cout<<"\nAll tests PASSED.\n"< #include #include #include #include #ifdef WIN32 #define MY_POPEN(arg1, arg2) _popen(arg1, arg2) #else #define MY_POPEN(arg1, arg2) popen(arg1, arg2) #endif using namespace std; void usage(char* appName) { cout << "\nUsage: "<\n"< mrlh = new ossimMultiResLevelHistogram; bool result = mrlh->importHistogram(histoFile); if (!result) { cout << "Could not open datafile at <"<. Aborting."< band_histo = mrlh->getHistogram(0); if (!band_histo.valid()) { xmsg<<"ossimKMeansFilter:"<<__LINE__<<" Null band histogram returned!"; throw ossimException(xmsg.str()); } ossimRefPtr classifier = new ossimKMeansClustering; classifier->setNumClusters(2); const double* x = band_histo->GetVals(); const ossim_int64* y = band_histo->GetCounts(); ossim_uint32 N = (ossim_uint32) band_histo->GetRes(); classifier->setSamples(x, N); classifier->setPopulations(y, N); if (!classifier->computeKmeans()) { cout<<"ossimKMeansFilter:"<<__LINE__<<" No K-means clustering data available."<getMean(0); double a = classifier->getSigma(0); double B = classifier->getMean(1); double b = classifier->getSigma(1); double T1 = classifier->getMaxValue(0); double T2 = (b*A + a*B)/(a+b); double T3 = (b*b*A + a*a*B)/(a*a+b*b); ostringstream xtics; xtics << "0.2, 0.8, " << "\"-a\" "< #include using namespace std; #include #include //#include int main(int argc, char *argv[]) { //ossimInit::instance()->initialize(argc, argv); ossimLeastSquaresPlane lsp; lsp.addSample(0, 0, 4.5); lsp.addSample(1, 0, 5.5); lsp.addSample(0, 1, 7.5); lsp.addSample(1, 1, 7.5); lsp.addSample(-1, 0, 2.5); lsp.addSample(0, -1, 0.5); lsp.addSample(-1, -1, -0.5); lsp.solveLS(); double a, b, c; lsp.getLSParms(a, b, c); cout << "\n a = "< using namespace std; #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); ossimFilename logFile; ossimGetLogFilename(logFile); cout << "log file after ossimInit::instance()->initialize: " << logFile << endl; if (logFile.size() == 0) { logFile = "/tmp/ossim-log.txt"; ossimSetLogFilename(logFile); } ossimGetLogFilename(logFile); cout << "set logFile end of test: " << logFile << endl; // ossimSetError was hanging: cout << "Calling ossimSetError(...) ..." << endl; ossimSetError( ossimString("ossimTiffOverviewBuilder"), ossimErrorCodes::OSSIM_WRITE_FILE_ERROR, "%s file %s line %d\nError creating reduced res set!", "MODULE", __FILE__, __LINE__); cout << "ossimSetError(...) returned..." << endl; return 0; } ossim-Miami-2.9.1/test/src/base/ossim-obj-allocate.cpp000066400000000000000000000037271352751253100225740ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-foo.cpp // // Author: David Burken // // Description: Contains application definition "ossim-foo" app. // // NOTE: This is supplied for simple quick test. DO NOT checkin your test to // the svn repository. Simply edit ossim-foo.cpp and run your test. // After completion you can do a "svn revert foo.cpp" if you want to // keep your working repository up to snuff. // // $Id: ossim-foo.cpp 20095 2011-09-14 14:37:26Z dburken $ //---------------------------------------------------------------------------- #include #include #include // ossim contants... #include #include #include #include // Put your includes here: #include #include using namespace std; static void usage() { cout << "ossim-obj-allocate " << endl; } int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); try { if(argc == 1) { usage(); return 0; } ossimKeywordlist kwl; if(!kwl.addFile(argv[1])) { std::cout << "FILE '" << argv[1] << "' is not a keywordlist with a type: keyword\n"; } ossimRefPtr obj = ossimObjectFactoryRegistry::instance()->createObject(kwl); ossimKeywordlist kwl2; if(obj.valid()) { obj->saveState(kwl2); std::cout << kwl2 << std::endl; } else { std::cout << "Unable to allocate object with passed in keywordlist file\n"; } // Put your code here. } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; return 1; } return 0; }ossim-Miami-2.9.1/test/src/base/ossim-point-test.cpp000066400000000000000000000106711352751253100223420ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id: ossim-point-test.cpp 19751 2011-06-13 15:13:07Z dburken $ #include #include #include #include #include #include #include #include #include int main() { //--- // Test ossiIpt::operator>> //--- std::string is1(" ( 0, 1 )"); std::string is2(" (2,3)"); std::string is3(" ( 4, 5 )"); std::string is4_5_6_7(" ( 6, 7 )(8, 9) ( 10, 11 ) ( 12, 13) 9876"); ossimIpt ip1; ossimIpt ip2; ossimIpt ip3; ossimIpt ip4; ossimIpt ip5; ossimIpt ip6; ossimIpt ip7; ip1.toPoint(is1); ip2.toPoint(is2); ip3.toPoint(is3); int i; std::istringstream istr(is4_5_6_7); istr >> ip4 >> ip5 >> ip6 >> ip7 >> i; //--- // Test ossiDpt::operator>> //--- std::string ds1(" ( 0.0, 1.1 )"); std::string ds2(" (2.2,3.3)"); std::string ds3(" ( 4.4, 5.5 )"); std::string ds4_5_6_7(" ( 6.6, 7.7 )(8.8, 9.9) ( 10.0, 11.0 ) ( 12.0, 13.0) 9876.12345678"); std::string ds8("12 20"); ossimDpt dp1; ossimDpt dp2; ossimDpt dp3; ossimDpt dp4; ossimDpt dp5; ossimDpt dp6; ossimDpt dp7; ossimDpt dp8; dp1.toPoint(ds1); dp2.toPoint(ds2); dp3.toPoint(ds3); double d; std::istringstream istr2(ds4_5_6_7); istr2 >> dp4 >> dp5 >> dp6 >> dp7 >> d; dp8.toPoint(ds8); // Test an invalid string "12 20" //--- // Test ossiDpt3d //--- std::string ds3d1 = " ( 0.0, 1.1, 2.2 )"; std::string ds3d2 = "(1.0,2.0,3.0)"; ossimDpt3d dp3d1; ossimDpt3d dp3d2; dp3d1.toPoint(ds3d1); dp3d2.toPoint(ds3d2); //--- // Test ossiGpt::operator>> //--- std::string gs1("(0.0,0.0,0.0,WGE)"); std::string gs2("(1.1,2.2,3.3,NAR-C)"); std::string gs3(" (4.4,5.5,6.6,NAS-C )"); std::string gs4_5_6_7(" (4.4,5.5,6.6,NAS-C )( 10.0, 10.0 ,5.0, TOY-C ) (17, -89, 50.0, xxx) (28.2, -44.5, 10000.0, NAS-B) 12345.6789"); ossimGpt gp1; ossimGpt gp2; ossimGpt gp3; ossimGpt gp4; ossimGpt gp5; ossimGpt gp6; ossimGpt gp7; double d2; gp1.toPoint(gs1); gp2.toPoint(gs2); gp3.toPoint(gs3); std::istringstream istr4(gs4_5_6_7); istr4 >> gp4 >> gp5 >> gp6 >> gp7 >> d2; //--- // Test ossimEcefPoint toString and toPoint methods. //--- std::string es1("(1.0,2.0,3.0)"); ossimEcefPoint ep1; ep1.toPoint(es1); std::string es2 = ep1.toString(10).string(); //--- // Test ossimEcefPoint toString and toPoint methods. //--- ossimEcefVector ev1; ev1.toPoint(es1); std::string es3 = ev1.toString(10).string(); std::cout << "\nis1: " << is1 << "\nip1: " << ip1 << "\nis2: " << is2 << "\nip2: " << ip2 << "\nis3: " << is3 << "\nip3: " << ip3 << "\nis4_5_6_7: " << is4_5_6_7 << "\nip4: " << ip4 << "\nip5: " << ip5 << "\nip6: " << ip6 << "\nip7: " << ip7 << "\ni: " << i << "\n\n\nds1: " << ds1 << "\ndp1: " << dp1 << "\nds2: " << ds2 << "\ndp2: " << dp2 << "\nds3: " << ds3 << "\ndp3: " << dp3 << "\nds4_5_6_7: " << ds4_5_6_7 << "\ndp4: " << dp4 << "\ndp5: " << dp5 << "\ndp6: " << dp6 << "\ndp7: " << dp7 << "\nds8: " << ds8 << "\ndp8: " << dp8 << "\nd: " << d << "\n\nds3d1: " << ds3d1 << "\nds3d2: " << ds3d2 << "\ndp3d1: " << dp3d1 << "\ndp3d2: " << dp3d2 << "\n\n\ngs1: " << gs1 << "\ngp1: " << gp1 << "\ngs2: " << gs2 << "\ngp2: " << gp2 << "\ngs3: " << gs3 << "\ngp3: " << gp3 << "\ngs4_5_6_7: " << gs4_5_6_7 << "\ngp4: " << gp4 << "\ngp5: " << gp5 << "\ngp6: " << gp6 << "\ngp7: " << gp7 << "\nd2: " << d2 << "\n\n\nes1: " << es1 << "\nep1: " << ep1 << "\nes2: " << es2 << "\nev1: " << ev1 << "\nes3: " << es3 << std::endl; return 0; } ossim-Miami-2.9.1/test/src/base/ossim-rect-test.cpp000066400000000000000000000155751352751253100221560ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossim-rect-test.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Test app for ossimIrect and ossimDrect classes. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include using namespace std; int main() { // IRECTS: // left handed irects ossimIrect ir1(0, 0, 10, 10); ossimIrect ir2(1, 1, 9, 9); ossimIrect ir3 = ir1.clipToRect(ir2); cout << "ossimIrect Left Handed:" << "\nrect ir1: " << ir1 << "\nrect ir2: " << ir2 << "\nir1.clipToRect(ir2): " << ir3 << "\nexpected: ul=(1,1), ur=(9,1), lr=(9,9), ll=(1,9)\n\n"; // right handed irects ossimIrect ir4(0,10, 10,0,OSSIM_RIGHT_HANDED); ossimIrect ir5(-5,8,14,1,OSSIM_RIGHT_HANDED); ossimIrect ir6 = ir4.clipToRect(ir5); cout << "ossimIrect Right Handed:" << "\nrect ir4: " << ir4 << "\nrect ir5: " << ir5 << "\nd.clipToRect(e): " << ir6 << "\nexpected: ul=(0,8), ur=(10,8), lr=(10,1), ll=(0,1)\n\n"; // DRECTS: // left handed irects ossimDrect dr1(0, 0, 10, 10); ossimDrect dr2(1, 1, 9, 9); ossimDrect dr3 = dr1.clipToRect(dr2); cout << "ossimDrect Left Handed:" << "\nrect dr1: " << dr1 << "\nrect dr2: " << dr2 << "\ndr1.clipToRect(dr2): " << dr3 << "\nexpected: ul=(1,1), ur=(9,1), lr=(9,9), ll=(1,9)\n\n"; // right handed drects ossimDrect dr4(0,10, 10,0,OSSIM_RIGHT_HANDED); ossimDrect dr5(-5,8,14,1,OSSIM_RIGHT_HANDED); ossimDrect dr6 = dr4.clipToRect(dr5); cout << "ossimDrect Right Handed:" << "\nrect dr4: " << dr4 << "\nrect dr5: " << dr5 << "\nd.clipToRect(e): " << dr6 << "\nexpected: ul=(0,8), ur=(10,8), lr=(10,1), ll=(0,1)\n" << endl; ossimDrect dComletelyWithinSource(0,0,10,10); ossimDrect dWithinEqual(0,0,10,10); ossimDrect dWithinLess(5,5,8,8); ossimDrect dWithinTop(0,-1,10,9); ossimDrect dWithinLeft(-1,0,9,10); ossimDrect dWithinRight(10,0,20,20); ossimDrect dWithinBottom(0,10,20,20); ossimIrect dWithinWayOut(50000,50000,100000,100000); std::cout << "ossimDrect completely within tests:" << "\nrect source: " << dComletelyWithinSource << "\nrect dWithinEqual: " << dWithinEqual << "\nrect dWithinLess: " << dWithinLess << "\nrect dWithinTop: " << dWithinTop << "\nrect dWithinLeft: " << dWithinLeft << "\nrect dWithinRight: " << dWithinRight << "\nrect dWithinBottom: " << dWithinBottom << "\nrect dWithinWayOut: " << dWithinWayOut << "\nrect dWithinEqual " << dWithinEqual.completely_within(dComletelyWithinSource) << "\nrect dWithinLess " << dWithinLess.completely_within(dComletelyWithinSource) << "\nrect dWithinTop " << dWithinTop.completely_within(dComletelyWithinSource) << "\nrect dWithinLeft " << dWithinLeft.completely_within(dComletelyWithinSource) << "\nrect dWithinRight " << dWithinRight.completely_within(dComletelyWithinSource) << "\nrect dWithinBottom " << dWithinBottom.completely_within(dComletelyWithinSource) << "\nrect dWithinWayOut " << dWithinWayOut.completely_within(dComletelyWithinSource) << "\nexpected: 1, 1, 0, 0, 0, 0, 0\n" << endl; ossimIrect iComletelyWithinSource(0,0,10,10); ossimIrect iWithinEqual(0,0,10,10); ossimIrect iWithinLess(5,5,8,8); ossimIrect iWithinTop(0,-1,10,9); ossimIrect iWithinLeft(-1,0,9,10); ossimIrect iWithinRight(10,0,20,20); ossimIrect iWithinBottom(0,10,20,20); ossimIrect iWithinWayOut(50000,50000,100000,100000); std::cout << "ossimIrect completely within tests:" << "\nrect source: " << iComletelyWithinSource << "\nrect iWithinEqual: " << iWithinEqual << "\nrect iWithinLess: " << iWithinLess << "\nrect iWithinTop: " << iWithinTop << "\nrect iWithinLeft: " << iWithinLeft << "\nrect iWithinRight: " << iWithinRight << "\nrect iWithinBottom: " << iWithinBottom << "\nrect iWithinWayOut: " << iWithinWayOut << "\nrect iWithinEqual " << iWithinEqual.completely_within(iComletelyWithinSource) << "\nrect iWithinLess " << iWithinLess.completely_within(iComletelyWithinSource) << "\nrect iWithinTop " << iWithinTop.completely_within(iComletelyWithinSource) << "\nrect iWithinLeft " << iWithinLeft.completely_within(iComletelyWithinSource) << "\nrect iuWithinRight " << iWithinRight.completely_within(iComletelyWithinSource) << "\nrect uWithinBottom " << iWithinBottom.completely_within(iComletelyWithinSource) << "\nrect iWithinWayOut " << iWithinWayOut.completely_within(iComletelyWithinSource) << "\nexpected: 1, 1, 0, 0, 0, 0, 0\n" << endl; ossimGrect gComletelyWithinSource(ossimGpt(0,0),ossimGpt(10,10)); ossimGrect gWithinEqual(ossimGpt(0,0),ossimGpt(10,10)); ossimGrect gWithinLess(ossimGpt(5,5),ossimGpt(8,8)); ossimGrect gWithinTop(ossimGpt(0,-1),ossimGpt(10,9)); ossimGrect gWithinLeft(ossimGpt(-1,0),ossimGpt(9,10)); ossimGrect gWithinRight(ossimGpt(10,0),ossimGpt(20,20)); ossimGrect gWithinBottom(ossimGpt(0,10),ossimGpt(20,20)); ossimGrect gWithinWayOut(ossimGpt(45,45),ossimGpt(50,50)); std::cout << "ossimGrect completely within tests:" << "\nrect source: " << gComletelyWithinSource << "\nrect gWithinEqual: " << gWithinEqual << "\nrect gWithinLess: " << gWithinLess << "\nrect gWithinTop: " << gWithinTop << "\nrect gWithinLeft: " << gWithinLeft << "\nrect gWithinRight: " << gWithinRight << "\nrect gWithinBottom: " << gWithinBottom << "\nrect gWithinWayOut: " << gWithinWayOut << "\nrect gWithinEqual " << gWithinEqual.completely_within(gComletelyWithinSource) << "\nrect gWithinLess " << gWithinLess.completely_within(gComletelyWithinSource) << "\nrect gWithinTop " << gWithinTop.completely_within(gComletelyWithinSource) << "\nrect gWithinLeft " << gWithinLeft.completely_within(gComletelyWithinSource) << "\nrect gWithinRight " << gWithinRight.completely_within(gComletelyWithinSource) << "\nrect gWithinBottom " << gWithinBottom.completely_within(gComletelyWithinSource) << "\nrect gWithinWayOut " << gWithinWayOut.completely_within(gComletelyWithinSource) << "\nexpected: 1, 1, 0, 0, 0, 0, 0\n" << endl; return 0; } ossim-Miami-2.9.1/test/src/base/ossim-ref-ptr-test.cpp000066400000000000000000000044231352751253100225660ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test application for ossimRefPtr class. // //---------------------------------------------------------------------------- // $Id: ossim-ref-ptr-test.cpp 19980 2011-08-17 20:14:46Z dburken $ #include using namespace std; #include #include #include // Referenced object. class Obj : public ossimReferenced { public: Obj(){} virtual ~Obj(){ cout << "~Obj..." << endl; } }; // Owns a ref ptr. class Foo { public: Foo() : m_refPtr(new Obj) {} ~Foo() { m_refPtr = 0; } ossimRefPtr& getRefPtr() { return m_refPtr; } private: ossimRefPtr m_refPtr; }; static void assignRefPtr(ossimRefPtr& rp) { rp = new Obj; } static ossimRefPtr getRefPtr() { return ossimRefPtr(new Obj); } // Test app int main( /* int argc, char* argv[] */ ) { ossimInit::instance()->initialize(); int rtn_status = 0; Foo* f = new Foo; cout << "count(1): " << f->getRefPtr()->referenceCount() << endl; ossimRefPtr rp = f->getRefPtr(); cout << "count(2): " << f->getRefPtr()->referenceCount() << endl; delete f; f = 0; cout << "count(1): " << rp->referenceCount() << endl; rp = 0; // Should destroy here... rp = 0; assignRefPtr(rp); if ( rp.valid() ) { cout << "assignRefPtr rp count(1): " << rp->referenceCount() << endl; } rp = 0; rp = getRefPtr(); if ( rp.valid() ) { cout << "getRefPtr rp count(1): " << rp->referenceCount() << endl; } // Test boolean operations: ossimRefPtr p0; ossimRefPtr p1 = new Obj; ossimRefPtr p1c = p1; ossimRefPtr p2 = new Obj; if (p0) { cout<<"bool operator (p) FAILED"< #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { int returnCode = 0; ossimArgumentParser ap(&argc, argv); ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " [options]"; au->setCommandLineUsage(usageString); au->addCommandLineOption("--in", " open ossim::istream"); au->addCommandLineOption("--out", " open ossim::ostream"); au->addCommandLineOption("--io", " open ossim::iostream"); ossimInit::instance()->initialize(ap); if ( ap.argc() > 1) { try { std::string ts1; ossimArgumentParser::ossimParameter sp1(ts1); if( ap.read("--in", sp1) ) { ossimString connnectionString(ts1); shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIstream( connnectionString, std::ios_base::in|std::ios_base::binary ); if ( str ) { ossimNotify(ossimNotifyLevel_INFO) << "Opened ossim::istream (str) for " << connnectionString << "\nInitial use_count: " << str.use_count() << endl; shared_ptr str2 = std::dynamic_pointer_cast( str ); if ( str2 ) { ossimNotify(ossimNotifyLevel_INFO) << "cast to ossim::ifstream (srt2) successful." << "\nstr use_count: " << str.use_count() << "\nstr2 use_count: " << str2.use_count() << endl; } else { ossimNotify(ossimNotifyLevel_INFO) << "cast to ossim::ifstream failed!" << endl; } } else { ossimNotify(ossimNotifyLevel_INFO) << "Could not open ossim::istream for " << connnectionString << endl; } } if( ap.read("--out", sp1) ) { ossimString connnectionString(ts1); shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createOstream( connnectionString, std::ios_base::in|std::ios_base::binary ); if ( str ) { ossimNotify(ossimNotifyLevel_INFO) << "Opened ossim::ostream for " << connnectionString << endl; } else { ossimNotify(ossimNotifyLevel_INFO) << "Could not open ossim::ostream for " << connnectionString << endl; } } if( ap.read("--io", sp1) ) { ossimString connnectionString(ts1); shared_ptr str = ossim::StreamFactoryRegistry::instance()-> createIOstream( connnectionString, std::ios_base::in|std::ios_base::binary ); if ( str ) { ossimNotify(ossimNotifyLevel_INFO) << "Opened ossim::iostream for " << connnectionString << endl; } else { ossimNotify(ossimNotifyLevel_INFO) << "Could not open iossim::ostream for " << connnectionString << endl; } } } catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } catch( ... ) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-foo caught unhandled exception!" << std::endl; returnCode = 1; } } else { ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); } return returnCode; } ossim-Miami-2.9.1/test/src/base/ossim-string-test.cpp000066400000000000000000000231261352751253100225160ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Test app for ossimString class. // // $Id: ossim-string-test.cpp 19871 2011-07-26 11:27:01Z gpotts $ //---------------------------------------------------------------------------- #include #include #include #include #include using namespace std; #include #include void testString() { std::cout << "Testing string\n"; ossim_float64 d = 0.123456789012345; cout << setiosflags(std::ios::scientific) << "\nd = 0.123456789012345" << "\nossimString::toString(d, 15) " << ossimString::toString(d, 15) << "\nossimString::toString(d, 15, true) " << ossimString::toString(d, 15, true) << "\n"; d = -32767; cout << "\nd = -32767" << "\nossimString::toString(d, 0) " << ossimString::toString(d, 0) << "\nossimString::toString(d, 0, true) " << ossimString::toString(d, 0, true) << "\nossimString::toString(d, 2) " << ossimString::toString(d, 2) << "\nossimString::toString(d, 2, true) " << ossimString::toString(d, 2, true) << "\n"; d = 123.123; cout << "\nd = 123.123\n" << "\nossimString::toString(d) " << ossimString::toString(d) << "\nossimString::toString(d, 0) " << ossimString::toString(d, 0) << "\nossimString::toString(d, 0, true) " << ossimString::toString(d, 0, true) << "\nossimString::toString(d, 3) " << ossimString::toString(d, 3) << "\nossimString::toString(d, 3, true) " << ossimString::toString(d, 3, true) << "\nossimString::toString(d, 4) " << ossimString::toString(d, 4) << "\nossimString::toString(d, 4, true) " << ossimString::toString(d, 4, true); d = 123; cout << "\nd = 123\n" << "\nossimString::toString(d, 0) " << ossimString::toString(d, 0) << "\nossimString::toString(d, 0, true) " << ossimString::toString(d, 0, true) << "\nossimString::toString(d, 3) " << ossimString::toString(d, 3) << "\nossimString::toString(d, 3, true) " << ossimString::toString(d, 3, true); // ossimString os1("1.23456E-10"); // ossim_float64 f1 = os1.toFloat64(); ossim_float64 f1 = 1.12345678e-10; // ossimString os2 = ossimString::toString(f1, // 10, // precision // true, // trim flag // true); // scientific flag ossimString os2 = ossimString::toString(f1, 10); // precision cout << setiosflags(std::ios::scientific) << setprecision(10) << "\nf1 = " << f1 << "\nossimString::toString(f1,10,true,true): " << os2 << endl; d = 0; cout << setiosflags(std::ios::fixed) << "\nd = 0" << "\nossimString::toString(d, 12, true): " // << ossimString::toString(d, 12, true) << ossimString::toString(d, 12) << std::endl; d = 0.1; cout << setiosflags(std::ios::fixed) << "\nd = 0.1" << "\nossimString::toString(d, true): " << ossimString::toString(d, true) << std::endl; d = 0.123; cout << setiosflags(std::ios::fixed) << "\nd = 0.123" << "\nossimString::toString(d, 12, true): " // << ossimString::toString(d, 12, true) << ossimString::toString(d, 12) << std::endl; d = 123.0; cout << setiosflags(std::ios::fixed) << "\nd = 123.0" << "\nossimString::toString(d, 12, true): " // << ossimString::toString(d, 12, true) << ossimString::toString(d, 12) << std::endl; d = 123.456; cout << setiosflags(std::ios::fixed) << "\nd = 123.456" << "\nossimString::toString(d, 12, true): " // << ossimString::toString(d, 12, true) << ossimString::toString(d, 12) << "\n" << std::endl; ossimString os1 = "LE7116034000502150.H1"; os2 = os1.substitute(ossimString("."), ossimString("_"), false); cout << "os1: " << os1 << "\ncommand: ossimString os2 = os1.substitute(ossimString(\".\"), ossimString(\"_\"), false);" << "\nos2: " << os2 << endl; std::string s3 = "abc"; ossimString os3(s3); cout << "ossimString constructed with std::string abc: " << os3 << endl; const char* nullCharStr = 0; ossimString os4(nullCharStr); cout << "ossimString constructed with null char string: " << os4 << endl; const char* abcCharStr = "abc"; ossimString os5(abcCharStr); cout << "ossimString constructed with abc char string: " << os5 << endl; char a = 'a'; ossimString os6(a); cout << "ossimString constructed with char a: " << os6 << endl; ossimString os7(5, a); cout << "ossimString constructed with 5 char a: " << os7 << endl; os7 = a; cout << "ossimString assigned char a: " << os7 << endl; os7 = nullCharStr; cout << "ossimString assigned null string: " << os7 << endl; os7 = abcCharStr; cout << "ossimString assigned abc char string: " << os7 << endl; os7 = s3; cout << "ossimString assigned std::string abc: " << os7 << endl; os7 = os5; cout << "ossimString assigned ossimString abc: " << os7 << endl; cout << "ossimString -> numeric test:\n"; os7 = "240"; ossim_uint8 pix = os7.toUInt8(); cout << "toUInt8 test: string = 240, result: " << int(pix) << endl; ossimString A ("NAD83_Michigan_South_ft"); ossimString B ("NAD83 / Michigan South (ft)"); ossimString separators ("_ /()"); vector AS = A.split(separators,true); vector BS = B.split(separators,true); if (AS == BS) cout << "split test 1: PASSED"< sliptTestBlankResult = splitTestBlank.split(" ", false); std::vector sliptTestBlankResultCompare; sliptTestBlankResultCompare.push_back("A"); sliptTestBlankResultCompare.push_back("B"); sliptTestBlankResultCompare.push_back(""); sliptTestBlankResultCompare.push_back("C"); if(sliptTestBlankResult==sliptTestBlankResultCompare) { cout << "split test blank: PASSED"< sliptTestEndResult = splitTestEnd.split(" C", false); std::vector sliptTestEndCompare; sliptTestEndCompare.push_back("A"); sliptTestEndCompare.push_back("B"); sliptTestEndCompare.push_back(""); if(sliptTestEndResult==sliptTestEndCompare) { cout << "split test end: PASSED"<\n"; std::map testMap; testMap.insert( std::make_pair(ossimString("red"), ossimString("1")) ); testMap.insert( std::make_pair(ossimString("green"), ossimString("2")) ); testMap.insert( std::make_pair(ossimString("blue"), ossimString("3")) ); std::map::const_iterator i = testMap.find(ossimString("green")); if ( i != testMap.end() ) { cout << "Found green in map." << "\n(*i).first: " << (*i).first << "\n(*i).second: " << (*i).second << endl; } else { cout << "test of std::map FAILED\n"; } ossimString testCompare = "test"; bool compareEquals1 = testCompare == "test"; bool compareEquals2 = "test" == testCompare; if(!compareEquals1) { std::cout<<"test of ossimString == const char* FAILED\n"; } if(!compareEquals2) { std::cout<<"test of const char* == ossimString FAILED\n"; } ossimString s0; ossimString s1 = "foo"; if (s0) cout<<"bool operator (s) FAILED"< // ossim contants... #include // ossim contants... #include // ossim contants... #include #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); ossimThinPlateSpline spline(2); ossimThinPlateSpline splineinv(2); ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(ossimFilename(argv[1])); if(argc <2) { std::cout << "Please pass an image to fit a polynomial" << std::endl; } if(!ih.valid()) { std::cout << "The input image is not a valid handler: " << argv[1] << std::endl; return 0; } ossimRefPtr geom = ih->getImageGeometry(); double pt[3]; double ptinv[3]; ossimDrect rect(ih->getBoundingRect()); ossim_int32 x = 0; ossim_int32 y = 0; ossimGpt gpt; pt[0] = -180; pt[1] = 90; for(y = 0; y < 10; ++y) { for(x = 0; x < 10; ++x) { double localx = x*.1 * rect.width(); double localy = y*.1 * rect.height(); geom->localToWorld(ossimDpt(localx, localy), gpt); pt[0] = gpt.latd(); pt[1] = gpt.lond(); ptinv[0] = localx; ptinv[1] = localy; spline.addPoint(localx,localy,pt); splineinv.addPoint(gpt.latd(),gpt.lond(),ptinv); } } spline.solve(); splineinv.solve(); for(y = -10; y < 10; ++y) { for(x = -10; x < 10; ++x) { double localx = x*.1 * rect.width(); double localy = y*.1 * rect.height(); spline.getPoint(localx, localy, pt); geom->localToWorld(ossimDpt(localx, localy), gpt); std::cout << "WORLD POINT = " << gpt << std::endl; std::cout << "LOCAL POINT = " << localx << ", " << localy << std::endl; std::cout << "fit point = " << pt[0] << ", " << pt[1] << std::endl; std::cout << "model point = " << gpt.latd() << ", " << gpt.lond() << std::endl; splineinv.getPoint(gpt.latd(), gpt.lond(), pt); std::cout << "INVERSE = " << pt[0] << ", " << pt[1] << std::endl; } } return 0; } ossim-Miami-2.9.1/test/src/base/ossim-threaded-logfile-test.cpp000066400000000000000000000064151352751253100244110ustar00rootroot00000000000000#include /* for exit */ #include #include #include #include #include #include #include #include #include std::shared_ptr startBarrier; std::shared_ptr endBarrier; class LogThread : public ossim::Thread { public: LogThread(const ossimString& threadName) :m_threadName(threadName) { m_numberOfStringsToLog = 1000000; } void setNumberOfStringsToLog(ossim_uint32 nStrings) { m_numberOfStringsToLog = nStrings; } virtual void run() { // let all threads start at the same time startBarrier->block(); ossim_uint32 idx = 0; for(idx = 0; idx < m_numberOfStringsToLog; ++idx) { ossimNotify() << m_threadName << std::endl; // ossimGpt gpt(m_minLat + yt*m_latDelta, m_minLon + xt*m_lonDelta); } // let all threads end at the same time endBarrier->block(); } ossimString m_threadName; ossim_uint32 m_numberOfStringsToLog; }; int main(int argc, char* argv[]) { ossimString tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); ossim_uint32 threads = 10; ossim_uint32 nvalues = 10; ossim_uint32 randomSeed = 0; argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("--threads","Specify the number of threads to test simultaneus access to elevation"); argumentParser.getApplicationUsage()->addCommandLineOption("--nvalues","Specify the number of random values"); if (argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_WARN)); exit(0); } if(argumentParser.read("--threads", stringParam)) { threads = tempString.toUInt32(); } if(argumentParser.read("--nvalues", stringParam)) { nvalues = tempString.toUInt32(); } std::vector threadList(threads); startBarrier = std::make_shared(threads+1); // include the main thread for synching endBarrier = std::make_shared(threads+1); // include the main thread for synching ossim_uint32 idx = 0; for(idx = 0; idx < threads; ++ idx) { threadList[idx] = new LogThread("Thread " + ossimString::toString(idx)); threadList[idx]->setNumberOfStringsToLog(nvalues); threadList[idx]->start(); } startBarrier->block(); ossimTimer::Timer_t t1 = ossimTimer::instance()->tick(); // synch all threads to start at the same time std::cout << "Number of threads: " << threads << "\n"; // startBarrier->block(); endBarrier->block(); std::cout << "All threads finished\n"; ossimTimer::Timer_t t2 = ossimTimer::instance()->tick(); std::cout << "Time elapsed: " << ossimTimer::instance()->delta_s(t1, t2) << " seconds" << "\n"; return 0; } ossim-Miami-2.9.1/test/src/base/ossim-threaded-polyarea2d-test.cpp000066400000000000000000000076161352751253100250360ustar00rootroot00000000000000#include /* for exit */ #include #include #include #include #include #include #include #include #include #include std::shared_ptr startBarrier; std::shared_ptr endBarrier; class Polyarea2dThread : public ossim::Thread { public: Polyarea2dThread(const ossimString& threadName) :m_threadName(threadName) { m_numberOfPointsToQuery = 1000000; } void setNumberOfPointsToQuery(ossim_uint32 nPoints) { m_numberOfPointsToQuery = nPoints; } virtual void run() { // let all threads start at the same time startBarrier->block(); ossim_uint32 idx = 0; for(idx = 0; idx < m_numberOfPointsToQuery; ++idx) { ossim_float32 t = static_cast(rand())/static_cast(RAND_MAX); ossim_float32 centerx = 10000.0*t; ossim_float32 centery = 10000.0*t; ossimPolyArea2d polyArea1(ossimDrect(centerx-1000,centery-1000,centerx+2000,centery+2000)); ossimPolyArea2d polyArea2(ossimDrect(centerx-500,centery-500,centerx+2000,centery+2000)); ossimPolyArea2d temp1 = polyArea1&polyArea2; ossimPolyArea2d temp2 = polyArea1+polyArea2; ossimPolyArea2d temp3(polyArea1); ossimPolyArea2d temp4(polyArea2); temp3+=temp1; temp4&=temp3; // ossimGpt gpt(m_minLat + yt*m_latDelta, m_minLon + xt*m_lonDelta); } // let all threads end at the same time endBarrier->block(); } ossimString m_threadName; ossim_uint32 m_numberOfPointsToQuery; }; int main(int argc, char* argv[]) { ossimString tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); //ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); ossim_uint32 threads = 10; ossim_uint32 nvalues = 10; ossim_uint32 randomSeed = 0; argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("--threads","Specify the number of threads to test simultaneus access to elevation"); argumentParser.getApplicationUsage()->addCommandLineOption("--nvalues","Specify the number of random values"); if (argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_WARN)); exit(0); } if(argumentParser.read("--threads", stringParam)) { threads = tempString.toUInt32(); } if(argumentParser.read("--nvalues", stringParam)) { nvalues = tempString.toUInt32(); } std::vector threadList(threads); startBarrier = std::make_shared(threads+1); // include the main thread for synching endBarrier = std::make_shared(threads+1); // include the main thread for synching ossim_uint32 idx = 0; for(idx = 0; idx < threads; ++ idx) { threadList[idx] = new Polyarea2dThread("Thread " + ossimString::toString(idx)); threadList[idx]->setNumberOfPointsToQuery(nvalues); threadList[idx]->start(); } startBarrier->block(); ossimTimer::Timer_t t1 = ossimTimer::instance()->tick(); // synch all threads to start at the same time std::cout << "Number of threads: " << threads << "\n"; // startBarrier->block(); endBarrier->block(); std::cout << "All threads finished\n"; ossimTimer::Timer_t t2 = ossimTimer::instance()->tick(); std::cout << "Time elapsed: " << ossimTimer::instance()->delta_s(t1, t2) << " seconds" << "\n"; return 0; } ossim-Miami-2.9.1/test/src/base/ossim-visitor-test.cpp000066400000000000000000000073371352751253100227150ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-foo.cpp // // Author: David Burken // // Description: Contains application definition "foo" app. // // NOTE: This is supplied for simple quick test. Makefile links with // libossim so you don't have to muck with that. // DO NOT checkin your test to the svn repository. Simply // edit foo.cc (Makefile if needed) and run your test. // After completion you can do a "svn revert foo.cpp" if you want to // keep your working repository up to snuff. Enjoy! // // $Id: ossim-visitor-test.cpp 22790 2014-05-16 19:19:30Z gpotts $ //---------------------------------------------------------------------------- #include #include #include // ossim contants... #include // ossim contants... #include #include #include #include #include #include // Put your includes here: #include #include #include #include #include static const char* kwl1String = "type: ossimImageChain\n" "object1.type: ossimRectangleCutFilter\n"; static const char* kwl2String = "type: ossimImageChain\n" "object2.type: ossimBrightnessContrastSource\n"; static const char* kwl3NestedString = "type: ossimImageChain\n" "object10.type: ossimScalarRemapper\n" "object30.type: ossimImageChain\n" "object30.object1.type: ossimImageRenderer\n"; int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); ossimKeywordlist kwl1; ossimKeywordlist kwl2; ossimKeywordlist kwl3; if(kwl1.parseString(kwl1String)&& kwl2.parseString(kwl2String)&& kwl3.parseString(kwl3NestedString)) { ossimRefPtr obj1 = ossimObjectFactoryRegistry::instance()->createObject(kwl1); ossimRefPtr obj2 = ossimObjectFactoryRegistry::instance()->createObject(kwl2); ossimRefPtr obj3 = ossimObjectFactoryRegistry::instance()->createObject(kwl3); ossimRefPtr connectable1 = dynamic_cast (obj1.get()); ossimRefPtr connectable2 = dynamic_cast (obj2.get()); ossimRefPtr connectable3 = dynamic_cast (obj3.get()); if(connectable1.valid()&&connectable2.valid()&&connectable3.valid()) { connectable2->connectMyInputTo(connectable1.get()); connectable3->connectMyInputTo(connectable2.get()); ossimTypeNameVisitor visitor("ossimConnectableObject", false, ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS); connectable3->accept(visitor); ossimCollectionVisitor::ListRef& collection = visitor.getObjects(); if(collection.size() == 8) { std::cout << "PASSED..." << std::endl; } else { std::cout << "FAILED..." << std::endl; } ossimCollectionVisitor::ListRef::iterator iter=collection.begin(); // while(iter != collection.end()) // { // std::cout << (*iter)->getClassName() << std::endl; // ++iter; // } ossimSourceInitializeVisitor sourceInitVisitor; obj1->accept(sourceInitVisitor); } } return 0; } ossim-Miami-2.9.1/test/src/base/ossim-xml-test.cpp000066400000000000000000000017651352751253100220150ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // XML functions test. // //---------------------------------------------------------------------------- // $Id: ossim-xml-test.cpp 23285 2015-04-28 19:45:07Z dburken $ #include using namespace std; #include #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if (argc != 2) { cout << "usage: " << argv[0] << " " << endl; return 0; } ossimFilename f = argv[1]; cout << "file: " << f << endl; ossimXmlDocument* xdoc = new ossimXmlDocument(); if ( xdoc->openFile(f) ) { cout << "opened..." << endl; } else { cout << "not opened..." << endl; } delete xdoc; return 0; } ossim-Miami-2.9.1/test/src/elevation/000077500000000000000000000000001352751253100174475ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/elevation/CMakeLists.txt000066400000000000000000000014341352751253100222110ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ # Remainder to be built but not installed OSSIM_SETUP_APPLICATION(ossim-dted-handler-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-dted-handler-test.cpp) OSSIM_SETUP_APPLICATION(ossim-elevation-manager-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-elevation-manager-test.cpp) OSSIM_SETUP_APPLICATION(ossim-image-elevation-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-image-elevation-test.cpp) OSSIM_SETUP_APPLICATION(ossim-threaded-elevation-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-threaded-elevation-test.cpp) OSSIM_SETUP_APPLICATION(ossim-tiled-elevation-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-tiled-elevation-test.cpp) ossim-Miami-2.9.1/test/src/elevation/ossim-dted-handler-test.cpp000066400000000000000000000045771352751253100246300ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (C) 2005 David Burken, all rights reserved. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test application / example code of opening a dted handler // and using it. // // $Id: ossim-dted-handler-test.cpp 23495 2015-08-28 15:25:19Z okramer $ //---------------------------------------------------------------------------- #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); //--- // Note: You must tweak the next three variables... // This is a 3601x3601 cell. //--- ossimFilename dtedCell = "/work/drb/image_formats/dted/1arc/w092/n40.dt1"; double neLat = 41.0; double neLon = -92.0; ossimDtedHandler* dh = new ossimDtedHandler(dtedCell); double p00 = dh->getPostValue(ossimIpt(0, 3599)); double p01 = dh->getPostValue(ossimIpt(0, 3600)); double p10 = dh->getPostValue(ossimIpt(1, 3599)); double p11 = dh->getPostValue(ossimIpt(1, 3600)); double ps = 1.0/3601.0; // post spacing double hps = ps/2.0; // half post spacing ossimGpt gp00( (neLat-ps), neLon, 0.0 ); ossimGpt gp01( neLat, neLon, 0.0 ); ossimGpt gp10( (neLat-ps), (neLon+ps), 0.0); ossimGpt gp11( neLat, (neLon+ps), 0.0 ); ossimGpt gpMid( (neLat-hps), (neLon+hps), 0.0 ); double hp00 = dh->getHeightAboveMSL(gp00); double hp01 = dh->getHeightAboveMSL(gp01); double hp10 = dh->getHeightAboveMSL(gp10); double hp11 = dh->getHeightAboveMSL(gp11); double hpMid = dh->getHeightAboveMSL(gpMid); cout << "\ngp00: " << gp00 << "\np00: " << p00 << "\nhp00: " << hp00 << "\ngp01: " << gp01 << "\np01: " << p01 << "\nhp01: " << hp01 << "\ngp10: " << gp10 << "\np10: " << p10 << "\nhp10: " << hp10 << "\ngp11: " << gp11 << "\np11: " << p11 << "\nhp11: " << hp11 << "\ngpMid: " << gpMid << "\nhpMid: " << hpMid << endl; delete dh; return 0; } ossim-Miami-2.9.1/test/src/elevation/ossim-elevation-manager-test.cpp000066400000000000000000000025421352751253100256610ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Test code for ossimElevManger. // // $Id: ossim-elevation-manager-test.cpp 22751 2014-04-25 17:54:56Z dburken $ //---------------------------------------------------------------------------- #include using namespace std; #include #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); #if 1 if (argc != 2) { cout << "usage: " << argv[0] << " " << endl; return 0; } ossimFilename dir = argv[1]; cout << "dir: " << dir << endl; if (ossimElevManager::instance()->loadElevationPath(dir)) { cout << "ossimElevManager::openDirectory worked for: " << dir << endl; } else { cout << "ossimElevManager::openDirectory failed for: " << dir << endl; } #endif #if 1 std::vector cells; ossimElevManager::instance()->getCellsForBounds( 24.0, -83.0, 28.0, -80.0, cells ); std::vector::const_iterator i = cells.begin(); while ( i != cells.end() ) { cout << "cell: " << (*i) << endl; ++i; } #endif return 0; } ossim-Miami-2.9.1/test/src/elevation/ossim-image-elevation-test.cpp000066400000000000000000000056121352751253100253320ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossim-tiled-elevation-test.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Test application for ossimImageElevationDatabase class. // //---------------------------------------------------------------------------- // $Id: ossim-image-elevation-test.cpp 22197 2013-03-12 02:00:55Z dburken $ #include #include #include #include #include #include #include #include #include #include using namespace std; static void usage() { cout << "ossim-image-elevation-test " << "\nCreates a ossimImageElevationDatabase from elev-dir." << endl; } int main(int argc, char *argv[]) { int result = 0; ossimTimer::instance()->setStartTick(); // Turn off elevation initialization as we want to use ours. ossimInit::instance()->setElevEnabledFlag(false); ossimInit::instance()->initialize(argc, argv); cout << std::setiosflags(ios::fixed) << std::setprecision(3) << "elapsed time after initialize: " << ossimTimer::instance()->time_s() << "\n"; if (argc == 2) { try // Exceptions can be thrown so { ossimString elevDir = argv[1]; cout << "elev-dir: " << elevDir << "\n"; ossimRefPtr elevdb = new ossimImageElevationDatabase(); if ( elevdb->open(elevDir) ) { std::vector pts(10); pts[0] = ossimGpt(3.5, -67.5); pts[1] = ossimGpt(7.5, -79.5); pts[2] = ossimGpt(35.694166666666668, 51.598333333333336); pts[3] = ossimGpt(35.821992089329882, 51.437673634967858); pts[4] = ossimGpt(35.843333333333334, 51.373333333333335); pts[5] = ossimGpt(3.25, -67.25); pts[6] = ossimGpt(7.5, -79.5); pts[7] = ossimGpt(35.821992089329882, 51.437673634967858); pts[8] = ossimGpt(7, -80); pts[9] = ossimGpt(7.9, -79.1); std::vector::iterator i = pts.begin(); while ( i != pts.end() ) { cout << "getHeightAboveEllipsoid(" << (*i) << "): " << elevdb->getHeightAboveEllipsoid( (*i) ) << endl; ++i; } } else { cout << "Could not open: " << elevDir << endl; } } catch( const ossimException& e ) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; result = 1; } } else { usage(); } return result; } ossim-Miami-2.9.1/test/src/elevation/ossim-threaded-elevation-test.cpp000066400000000000000000000163451352751253100260350ustar00rootroot00000000000000#include /* for exit */ #include #include #include #include #include #include #include #include #include #include #include std::shared_ptr startBarrier; std::shared_ptr endBarrier; std::mutex accumMutex; ossimRefPtr dtedDatabase = new ossimDtedElevationDatabase; double accumH = 0.0; class ElevationThread : public ossim::Thread { public: ElevationThread(const ossimString& threadName="", double minLon=-180.0, double minLat=-90.0, double maxLon=180.0, double maxLat=90.0) :m_threadName(threadName), m_minLat(minLat), m_minLon(minLon), m_maxLat(maxLat), m_maxLon(maxLon) { m_numberOfPointsToQuery = 1000; m_lonDelta = m_maxLon-m_minLon; m_latDelta = m_maxLat-m_minLat; m_mslTest = false; } void setNumberOfPointsToQuery(ossim_uint32 nPoints) { m_numberOfPointsToQuery = nPoints; } virtual void run() { // let all threads start at the same time startBarrier->block(); ossim_uint32 idx = 0; double hs=0.0; for(idx = 0; idx < m_numberOfPointsToQuery; ++idx) { ossim_float32 xt = static_cast(rand())/static_cast(RAND_MAX); ossim_float32 yt = static_cast(rand())/static_cast(RAND_MAX); ossimGpt gpt(m_minLat + yt*m_latDelta, m_minLon + xt*m_lonDelta); double h; #if 0 h = ossimElevManager::instance()->getHeightAboveEllipsoid(gpt);// << "==" << ossimElevManager::instance()->getHeightAboveMSL(gpt) << "\n"; std::cout << h << "\n"; #else if(m_mslTest) { h = ossimElevManager::instance()->getHeightAboveMSL(gpt); } else { h = ossimElevManager::instance()->getHeightAboveEllipsoid(gpt); } std::cout << h << "\n"; #endif if(!ossim::isnan(h)) { hs += h; } } accumMutex.lock(); accumH += hs / m_numberOfPointsToQuery; accumMutex.unlock(); // let all threads end at the same time endBarrier->block(); } ossimString m_threadName; ossim_uint32 m_numberOfPointsToQuery; double m_minLat; double m_minLon; double m_maxLat; double m_maxLon; double m_latDelta; double m_lonDelta; bool m_mslTest; }; int main(int argc, char* argv[]) { ossimString tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); //ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); ossim_uint32 num_threads = 10; ossim_uint32 round_robin = 10; ossim_uint32 num_posts = 1000; ossim_uint32 randomSeed = 0; double minLon = -110.0; double minLat = -90.0; double maxLon = -80.0; double maxLat = 90.0; argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("--threads"," Specify the number of threads to test simultaneus access to elevation"); argumentParser.getApplicationUsage()->addCommandLineOption("--elev-post-queries"," Number of elevation post queries per thread"); argumentParser.getApplicationUsage()->addCommandLineOption("--posts","Same as elev-post-queries option"); argumentParser.getApplicationUsage()->addCommandLineOption("--random-seed", " Value to use as the seed for the random elevation post generator"); argumentParser.getApplicationUsage()->addCommandLineOption("--use-geoid-if-null", " Specify true or false to use the geoid if the elevation post is null"); argumentParser.getApplicationUsage()->addCommandLineOption("--bbox", " Ground rect to constrain the random values to"); argumentParser.getApplicationUsage()->addCommandLineOption("--round-robin", " Specifies size of round robin list used by elevation manager."); if (argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_WARN)); exit(0); } if(argumentParser.read("--threads", stringParam)) { num_threads = tempString.toUInt32(); round_robin = num_threads; } if(argumentParser.read("--round-robin", stringParam)) { round_robin = tempString.toUInt32(); } if (argumentParser.read("--elev-post-queries", stringParam) || argumentParser.read("--posts", stringParam)) { num_posts = tempString.toUInt32(); } if(argumentParser.read("--random-seed", stringParam)) { randomSeed = tempString.toUInt32(); } if(argumentParser.read("--use-geoid-if-null", stringParam)) { ossimElevManager::instance()->setUseGeoidIfNullFlag(tempString.toBool()); } if(argumentParser.read("--bbox", stringParam)) { std::vector splitArray; tempString.split(splitArray, ","); if(splitArray.size()==4) { minLon = splitArray[0].toDouble(); minLat = splitArray[1].toDouble(); maxLon = splitArray[2].toDouble(); maxLat = splitArray[3].toDouble(); std::cout << "minlon = " << minLon << "\n"; std::cout << "minlat = " << minLat << "\n"; std::cout << "maxlon = " << maxLon << "\n"; std::cout << "maxlat = " << maxLat << "\n"; } } ossimElevManager::instance()->setRoundRobinMaxSize(round_robin); ossimKeywordlist kwl; // kwl.add("connection_string", "/data/elevation/dted/1k"); // kwl.add("type", "ossimDtedElevationDatabase"); // std::cout << "Loaded database? " << dtedDatabase->loadState(kwl) << std::endl; srand(randomSeed); std::vector threadList(num_threads); startBarrier = std::make_shared(num_threads+1); // include the main thread for synching endBarrier = std::make_shared(num_threads+1); // include the main thread for synching ossim_uint32 idx = 0; for(idx = 0; idx < num_threads; ++ idx) { threadList[idx] = new ElevationThread("Thread " + ossimString::toString(idx), minLon, minLat, maxLon, maxLat); threadList[idx]->setNumberOfPointsToQuery(num_posts); threadList[idx]->start(); } startBarrier->block(); ossimTimer::Timer_t t1 = ossimTimer::instance()->tick(); // synch all threads to start at the same time std::cout << "Number of threads: " << num_threads << "\n"; std::cout << "Posts to query per thread: " << num_posts << "\n"; // startBarrier->block(); endBarrier->block(); std::cout << "All threads finished\n"; ossimTimer::Timer_t t2 = ossimTimer::instance()->tick(); std::cout << "Time elapsed: " << ossimTimer::instance()->delta_s(t1, t2) << " seconds" << "\n"; std::cout << "mean elevation: " << accumH/num_threads << "\n"; return 0; } ossim-Miami-2.9.1/test/src/elevation/ossim-tiled-elevation-test.cpp000066400000000000000000000203441352751253100253500ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossim-tiled-elevation-test.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Test application for ossimTiledElevationDatabase class. // //---------------------------------------------------------------------------- // $Id: ossim-tiled-elevation-test.cpp 22384 2013-08-30 14:09:08Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static void usage() { cout << "ossim-tiled-elevation-test " << "\n\nCreates a ossimTiledElevationDatabase from elev-dir for the bounding box of\ninput-image and writes output-image in tiff format.\n\nThis test the ossimTiledElevationDatabase ability to map a region of interest\nand serve it up as an elevation source. Since this is testing elevation, the\n\"input-image\" should have a projection affected by elevation. In other words,\nsome type of sensor model." << endl; } int main(int argc, char *argv[]) { int result = 0; ossimTimer::instance()->setStartTick(); // Turn off elevation initialization as we want to use ours. ossimInit::instance()->setElevEnabledFlag(false); ossimInit::instance()->initialize(argc, argv); cout << std::setiosflags(ios::fixed) << std::setprecision(3) << "elapsed time after initialize: " << ossimTimer::instance()->time_s() << "\n"; if (argc == 4) { try // Exceptions can be thrown so { ossimFilename elevDir = argv[1]; ossimFilename inputImage = argv[2]; ossimFilename outputImage = argv[3]; cout << "elev-dir: " << elevDir << "\ninput-image: " << inputImage << "\noutput-image: " << outputImage << "\n"; ossimTiledElevationDatabase* elevdb = new ossimTiledElevationDatabase(); ossimKeywordlist kwl; kwl.setExpandEnvVarsFlag(true); // kwl.add("connection_string", "$(OSSIM_DATA)/elevation/srtm/3arc"); kwl.add("connection_string", elevDir.c_str()); kwl.add("geoid.type", "geoid1996"); kwl.add("max_open_cells", "50"); kwl.add("memory_map_cells", "false"); kwl.add("min_open_cells", "25"); kwl.add("type", "ossimTiledElevationDatabase"); if ( elevdb->loadState(kwl, 0) ) { ossimRefPtr sic1 = new ossimSingleImageChain(); sic1->setAddResamplerCacheFlag(true); sic1->setAddChainCacheFlag(true); // Open: if ( sic1->open( inputImage ) ) { // Get the geometry: ossimRefPtr geom = sic1->getImageGeometry(); // Get the bounding rectangle: ossimGrect boundingRect; std::vector corner(4); if ( geom->getCornerGpts(corner[0], corner[1], corner[2], corner[3]) ) { ossimGpt ulGpt(corner[0]); ossimGpt lrGpt(corner[0]); cout << "corner[0]: " << corner[0] << endl; for ( ossim_uint32 i = 1; i < 4; ++i ) { cout << "corner[" << i << "]: " << corner[i] << endl; if ( corner[i].lon < ulGpt.lon ) ulGpt.lon = corner[i].lon; if ( corner[i].lat > ulGpt.lat ) ulGpt.lat = corner[i].lat; if ( corner[i].lon > lrGpt.lon ) lrGpt.lon = corner[i].lon; if ( corner[i].lat < lrGpt.lat ) lrGpt.lat = corner[i].lat; } //--- // Add a padding to ensure no nans on edges: // Should check for wrap here but just test code. //--- const ossim_float64 PADDING = 1.0/60.0; // one minute. ulGpt.lon -= PADDING; ulGpt.lat += PADDING; lrGpt.lon += PADDING; lrGpt.lat -= PADDING; cout << "ulGpt: " << ulGpt << "\nlrGpt: " << lrGpt << endl; boundingRect = ossimGrect(ulGpt, lrGpt); } else { boundingRect.makeNan(); } if ( boundingRect.isLonLatNan() == false ) { // Create the chain: sic1->createRenderedChain(); cout << "boundingRect: " << boundingRect << endl; elevdb->mapRegion(boundingRect); cout << std::setiosflags(ios::fixed) << std::setprecision(3) << "elapsed time after mapping elevation: " << ossimTimer::instance()->time_s() << "\n"; cout << "ossimTiledElevationDatabase::getMeanSpacingMeters: " << elevdb->getMeanSpacingMeters() << "\n"; cout << "mappedRect: " << elevdb->getBoundingGndRect() << endl; ossimElevManager::instance()->setDefaultHeightAboveEllipsoid(0.0); ossimElevManager::instance()->setUseGeoidIfNullFlag(true); ossimElevManager::instance()->addDatabase(elevdb); #if 0 // 35.821992089329882, 51.437673634967858 // Height: 1874.649761970292 MSL: 1871.642024320508 ossimGpt pt1(35.821992089329882, 51.437673634967858); ossimGpt pt2(35.843333333333334, 51.373333333333335); ossimGpt pt3(35.694166666666668, 51.598333333333336); cout << "getHeightAboveEllipsoid(35.821992089329882, 51.437673634967858): " << ossimElevManager::instance()->getHeightAboveEllipsoid(pt1) << "\ngetHeightAboveEllipsoid(35.843333333333334, 51.373333333333335): " << ossimElevManager::instance()->getHeightAboveEllipsoid(pt2) << "\ngetHeightAboveEllipsoid(35.694166666666668, 51.598333333333336): " << ossimElevManager::instance()->getHeightAboveEllipsoid(pt3) << endl; #endif ossimRefPtr writer = new ossimTiffWriter(); if ( writer->open( outputImage ) ) { // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); writer->connectMyInputTo(0, sic1.get()); writer->execute(); cout << std::setiosflags(ios::fixed) << std::setprecision(3) << "elapsed time in seconds: " << ossimTimer::instance()->time_s() << "\n"; } else { cout << "Could not open: " << outputImage << endl; } } else { cout << "bounding box for " << inputImage << " has nans...\n"; } } // if ( sic1->open( inputImage) ) ) else { cout << "Could not open: " << inputImage << endl; } // ossimDrect boundingRect = elevdb->getBounding } } catch( const ossimException& e ) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; result = 1; } } else { usage(); } return result; } ossim-Miami-2.9.1/test/src/gsoc/000077500000000000000000000000001352751253100164145ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/gsoc/CMakeLists.txt000066400000000000000000000002401352751253100211500ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ OSSIM_SETUP_APPLICATION(ossim-gsoc1 COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-gsoc1.cpp) ossim-Miami-2.9.1/test/src/gsoc/ossim-gsoc1.cpp000066400000000000000000000066431352751253100212750ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-foo.cpp // // Author: David Burken // // Description: Contains application definition "ossim-foo" app. // // NOTE: This is supplied for simple quick test. DO NOT checkin your test to // the svn repository. Simply edit ossim-foo.cpp and run your test. // After completion you can do a "svn revert foo.cpp" if you want to // keep your working repository up to snuff. // // $Id: ossim-gsoc1.cpp 23420 2015-07-12 11:58:34Z dburken $ //---------------------------------------------------------------------------- // ossim includes: These are here just to save time/typing... #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); // TODO: Read your ECEF points from your input file here: vector ecef_points; // Need to fill this vector array ossimEcefPoint Pt1( 4347158.78960514, 848070.80152498, 4573989.32558993); ossimEcefPoint Pt2( 4347158.78960514, 853070.80152498, 4573927.96772204); ossimEcefPoint Pt3( 4347158.78960514, 858070.80152498, 4573866.60985415); ossimEcefPoint Pt4( 4352158.78960514, 848070.80152498, 4569848.07121407); ossimEcefPoint Pt5( 4352158.78960514, 853070.80152498, 4569786.71334618); ossimEcefPoint Pt6( 4352158.78960514, 858070.80152498, 4569725.35547829); ossimEcefPoint Pt7( 4357158.78960514, 848070.80152498, 4565706.81683821); ossimEcefPoint Pt8( 4357158.78960514, 853070.80152498, 4565645.45897032); ossimEcefPoint Pt9( 4357158.78960514, 858070.80152498, 4565584.10110243); ecef_points.push_back(Pt1); ecef_points.push_back(Pt2); ecef_points.push_back(Pt3); ecef_points.push_back(Pt4); ecef_points.push_back(Pt5); ecef_points.push_back(Pt6); ecef_points.push_back(Pt7); ecef_points.push_back(Pt8); ecef_points.push_back(Pt9); ossimRefPtr pc_handler = new ossimGenericPointCloudHandler(ecef_points); ossimRefPtr ih = new ossimPointCloudImageHandler; ih->setCurrentEntry((ossim_uint32)ossimPointCloudImageHandler::HIGHEST); ih->setPointCloudHandler(pc_handler.get()); // TODO: This sets the resolution of the output file. There is a default value computed but you // may either adjust it or set it manually here: ossimDpt gsd; ih->getGSD(gsd, 0); ossimString gsdstr = ossimString::toString((gsd.x + gsd.y)/2.0); // I use 1/6th of default ossimRefPtr gsd_prop = new ossimStringProperty(ossimKeywordNames::METERS_PER_PIXEL_KW, gsdstr); ih->setProperty(gsd_prop); // Set up the writer: ossimRefPtr tif_writer = new ossimTiffWriter(); tif_writer->setGeotiffFlag(true); ossimFilename outfile ("output.tif"); tif_writer->setFilename(outfile); if (tif_writer.valid()) { tif_writer->connectMyInputTo(0, ih.get()); tif_writer->execute(); } cout << "Output written to <"<"<close(); tif_writer = 0; ih = 0; pc_handler = 0; return 0; } ossim-Miami-2.9.1/test/src/hdf5/000077500000000000000000000000001352751253100163075ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/hdf5/CMakeLists.txt000066400000000000000000000003501352751253100210450ustar00rootroot00000000000000OSSIM_SETUP_APPLICATION(ossim-hdf5-info INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-hdf5-info.cpp) OSSIM_SETUP_APPLICATION(ossim-hdf5-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-hdf5-test.cpp) ossim-Miami-2.9.1/test/src/hdf5/ossim-hdf5-info.cpp000066400000000000000000000035361352751253100217310ustar00rootroot00000000000000/***************************************************************************** * * * O S S I M * * Open Source, Geospatial Image Processing Project * * License: MIT, see LICENSE at the top-level directory * * * *****************************************************************************/ #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { int returnCode = 0; try { std::shared_ptr info = ossimInfoFactoryRegistry::instance()->create(argv[1]); if (info) { std::cout<getKeywordlist(kwl); kwl.print(std::cout); } else { ossimNotify(ossimNotifyLevel_WARN) << "The info factory failed to create an hdf5 info object. Check that hdf5 is enabled " "via the BUILD_OSSIM_HDF5_SUPPORT environment variable before running cmake, and that " "the hdf5 library is discoverable." << std::endl; returnCode = 1; } } catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } catch( ... ) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-foo caught unhandled exception!" << std::endl; returnCode = 1; } std::cout< #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { int returnCode = 0; ossimInit::instance()->initialize(argc, argv); try { ossimRefPtr handler = ossimImageHandlerRegistry::instance()->open(ossimFilename(argv[1])); if (!handler.valid()) { throw ossimException("The handler factory failed to create an hdf5 image handler object. Check that hdf5 is enabled " "via the BUILD_OSSIM_HDF5_SUPPORT environment variable before running cmake, and that " "the hdf5 library is discoverable."); } cout<<"\n Successfully created an instance of "<getClassName()< geom = handler->getImageGeometry(); if (!geom.valid()) throw ossimException("Could not create geometry object."); geom->print(cout); } catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } catch( ... ) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-foo caught unhandled exception!" << std::endl; returnCode = 1; } cout< using namespace std; #include // ossim contants... #include #include #include #include #include #include void initKwl1(ossimKeywordlist& kwl) { kwl.add("type", "ossimBandLutFilter"); kwl.add("scalar_type", "F32"); // Entry 0 (1,1,1) --> (1,1,0.1) yellow kwl.add("band0.entry0.in", "1"); kwl.add("band1.entry0.in", "1"); kwl.add("band2.entry0.in", "1"); kwl.add("band0.entry0.out", "1.0"); kwl.add("band1.entry0.out", "1.0"); kwl.add("band2.entry0.out", "0.1"); // Entry 1 (128,128,128) --> (1,0.5,0.5) red kwl.add("band0.entry1.in", "128"); kwl.add("band1.entry1.in", "128"); kwl.add("band2.entry1.in", "128"); kwl.add("band0.entry1.out", "0.1"); kwl.add("band1.entry1.out", "0.1"); kwl.add("band2.entry1.out", "1.0"); // Entry 2 (255,255,255) --> (1,0.1,1.0) violet kwl.add("band0.entry2.in", "255"); kwl.add("band1.entry2.in", "255"); kwl.add("band2.entry2.in", "255"); kwl.add("band0.entry2.out", "1.0"); kwl.add("band1.entry2.out", "0.1"); kwl.add("band2.entry2.out", "1.0"); } void initKwl2(ossimKeywordlist& kwl) { kwl.add("type", "ossimBandLutFilter"); kwl.add("enabled", "1"); kwl.add("mode", "interpolated"); kwl.add("scalar_type", "U8"); kwl.add("entry0.in", "0.0"); kwl.add("entry0.out", "64"); kwl.add("entry1.in", "0.45"); kwl.add("entry1.out", "64"); kwl.add("entry2.in", "0.450001"); kwl.add("entry2.out", "128"); kwl.add("entry3.in", "0.55"); kwl.add("entry3.out", "128"); kwl.add("entry4.in", "0.550001"); kwl.add("entry4.out", "255"); kwl.add("entry5.in", "1.0"); kwl.add("entry5.out", "255"); } bool writeTile(ossimFilename& fname, ossimImageSource* source) { ossimRefPtr writer = new ossimTiffWriter; writer->setFilename(fname); writer->connectMyInputTo(0, source); writer->setGeotiffFlag(false); if ( !writer->execute() ) return false; cout << "Wrote result tile to <"<."<& lutFilter) { lutFilter->loadState(kwl); lutFilter->initialize(); return writeTile(fname, lutFilter.get()); } int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); ossimKeywordlist kwl; initKwl1(kwl); // Accept test directory on command line: ossimFilename outputPath; if (argc > 1) { outputPath = argv[1]; if (!outputPath.isDir()) { cout << "Bad destination directory <"< specified on command line. Ignoring," << endl; outputPath = ""; } } // Initialize the input index buffer: ossimRefPtr indexTile = ossimImageDataFactory::instance()->create(0, OSSIM_UINT8, 3, 256, 256); if(!indexTile.valid()) return -1; indexTile->initialize(); for (int band=0; band<3; ++band) { ossim_uint8 p = 0; ossim_uint8* bandBuf = indexTile->getUcharBuf(band); ossim_uint32 pixel = 0; for (int y=0; y<256; ++y) { for (int x=0; x<256; ++x) bandBuf[pixel++] = p; p += 1; } } indexTile->validate(); // Create output image chain: ossimRefPtr memSource = new ossimMemoryImageSource; memSource->setImage(indexTile); memSource->setRect(0, 0, 256, 256); ossimRefPtr lutFilter = new ossimBandLutFilter(); lutFilter->connectMyInputTo(memSource.get()); // Test 1: LITERAL mode cout << "\nTEST 1 -- Running LITERAL mode test...\n"< floatTile = ossimImageDataFactory::instance()->create(0, OSSIM_FLOAT32, 1, 256, 256); if(!floatTile.valid()) return -1; floatTile->initialize(); float dp = 1.0/256.0; float p = 0; float* floatBuf = floatTile->getFloatBuf(); ossim_uint32 pixel = 0; for (int y=0; y<256; ++y) { for (int x=0; x<256; ++x) floatBuf[pixel++] = p; p += dp; } floatTile->validate(); // Create output image chain: ossimRefPtr memSource2 = new ossimMemoryImageSource; memSource2->setImage(floatTile); memSource2->setRect(0, 0, 256, 256); // ossimFilename tempFile ("float_tile.tif"); // writeTile(tempFile, memSource2.get()); ossimRefPtr lutFilter2 = new ossimBandLutFilter(); lutFilter2->connectMyInputTo(memSource2.get()); cout << "\nTEST 3 -- Running threshold test...\n"< #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; void usage(char* appName) { cout << "\nUsage: "< [-p ] [-z]"< -y \n"< mapProj = new ossimEquDistCylProjection(); mapProj->setOrigin(observerGpt); mapProj->setMetersPerPixel(gsd); ossimDpt degPerPixel (mapProj->getDecimalDegreesPerPixel()); mapProj->setElevationLookupFlag(false); ossimGpt ulTiePt (observerGpt); ulTiePt.lat += degPerPixel.lat * (image_size.y-1)/2.0; ulTiePt.lon -= degPerPixel.lon * (image_size.x-1)/2.0; mapProj->setUlTiePoints(ulTiePt); ossimRefPtr geometry = new ossimImageGeometry(0, mapProj.get()); geometry->setImageSize(image_size); // Create output image chain: ossimRefPtr memSource = new ossimMemoryImageSource; memSource->setImage(tile); memSource->setImageGeometry(geometry.get()); ossimImageSource* last_source = memSource.get(); // if (memSource->getOutputScalarType() != OSSIM_UINT8) // { // ossimRefPtr remapper = new ossimScalarRemapper; // remapper->connectMyInputTo(memSource.get()); // remapper->setOutputScalarType(OSSIM_UINT8); // last_source = remapper.get(); // } ossimRefPtr writer = new ossimTiffWriter(); writer->connectMyInputTo(0, last_source); writer->setFilename(fname); writer->setGeotiffFlag(false); bool success = writer->execute(); if (success) { writer->writeExternalGeometryFile(); cout<<"Wrote <"<"<"< outImage = ossimImageDataFactory::instance()->create(0, OSSIM_UINT8, 1, image_size.x, image_size.y); outImage->initialize(); double A = 128; // amplitude outImage->fill(A); if ((dx != 0) || (dy != 0)) { ossim_uint8* buffer = (ossim_uint8*) outImage->getBuf(0); ossim_uint32 i = 0; double phase = 0; // Chip always starts at 0 phase angle double dpy = 0; if (dy != 0) dpy = 2*M_PI/dy; // phase rate (radians per pixel) double dpx = 0; if (dx != 0) dpx = 2*M_PI/dx; // phase rate (radians per pixel) // Loops to fill one n x n chip with a single freq (1/lambda) component: for (int y=0; y inputImage = ossimImageHandlerRegistry::instance()->open(inputFname); if (!inputImage.valid()) { cout<< "Could not load image <"<."< geom = inputImage->getImageGeometry(); ossimIpt image_size = geom->getImageSize(); // Set up FFT filter. Will first try to use the FFTW3 library if plugin was loaded, otherwise // will fallback to use the core newmat implementation: ossimImageSourceFactoryRegistry* isf = ossimImageSourceFactoryRegistry::instance(); ossimString name ("ossimFftw3Filter"); ossimRefPtr fft = (ossimFftFilter*) isf->createImageSource(name); if (!fft.valid()) { ossimNotify(ossimNotifyLevel_INFO)<<"FFTW3 plugin was not available. Using core ossimFftFilter."<setDirectionType(ossimFftFilter::FORWARD); else fft->setDirectionType(ossimFftFilter::INVERSE); fft->connectMyInputTo(inputImage.get()); ossimImageSource* last_source = fft.get(); // Allocate output image buffer: ossimRefPtr outImage; ossimImageDataFactory* idf = ossimImageDataFactory::instance(); if (forward) outImage = idf->create(0, fft->getOutputScalarType(), 3, image_size.x, image_size.y); else outImage = idf->create(0, fft->getOutputScalarType(), 1, image_size.x, image_size.y); outImage->initialize(); outImage->setNullPix(0.0); // Loop over input data chips (n x n): if (chip_size == 0) chip_size = 256; for (int y=0; y fft_chip = fft->getTile(chipRect); if (forward) { outImage->loadBand(fft_chip->getBuf(0), chipRect, 0); outImage->loadBand(fft_chip->getBuf(1), chipRect, 1); } else { outImage->loadTile(fft_chip.get()); } } } return writeFile(outImage.get(), fname); } int main(int argc, char *argv[]) { int returnCode = 0; ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); ossimString tempString; ossimArgumentParser::ossimParameter stringParam(tempString); if ( ap.read("-h") || ap.read("--help") || (argc < 2)) { usage(ap[0]); return 0; } bool generate_image = true; ossimFilename inputFilename; if ( ap.read("-i", stringParam)) { inputFilename = tempString; generate_image = false; } int dx = 0; if ( ap.read("-x", stringParam)) dx = tempString.toInt(); int dy = 0; if ( ap.read("-y", stringParam)) dy = tempString.toInt(); int chip_size = 256; if ( ap.read("-p", stringParam)) chip_size = tempString.toInt(); bool inverse_only = false; if ( ap.read("-z")) inverse_only = true; ostringstream f0, f1, f2; ossimFilename fftFilename, invFilename; if (generate_image) { f0 << "gen-" << dx << "-" << dy << ".tif"; inputFilename = f0.str(); } f1 << inputFilename.fileNoExtension() << "-FFT.tif"; fftFilename = f1.str(); f2 << inputFilename.fileNoExtension() << "-INV.tif"; invFilename = f2.str(); ap.reportRemainingOptionsAsUnrecognized(); if ( ap.errors() ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); return -1; } if (generate_image && !synthesizeInput(dx, dy, inputFilename)) { cout<< "Could not load input image <"<."< #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static void usage(ossimArgumentParser& ap) { // Add global usage options. ossimInit::instance()->addOptions(ap); ossimApplicationUsage* au = ap.getApplicationUsage(); // Set app name. au->setApplicationName(ap.getApplicationName()); au->setDescription(ossimString("Returns pixel value at the given sample and line.\nNotes:\nBand, line and sample are zero based.\nUse an \"a\" for if you want to see all bands.\n")); ossimString usageString = ap.getApplicationName(); usageString += " [options] \n"; au->setCommandLineUsage(usageString); au->addCommandLineOption("-e"," Entry index to get pixel from. Only significant with multi entry data only."); au->addCommandLineOption("--reader-prop","Passes a name=value pair to the reader(s) for setting it's property. Any number of these can appear on the line."); // Write usage. au->write(ossimNotify(ossimNotifyLevel_INFO)); } struct readerProp { ossimString name; ossimString value; }; /** * @brief Adds band to bandList returning true on success, false on range error * with error message to standard out. */ static bool addBand( ossim_uint32 band, ossim_uint32 bandCount, vector& bandList ); int main(int argc, char *argv[]) { // Initialize: ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); // Argument check: if ( (ap.argc() < 5) || ap.read("-h") || ap.read("--help") ) { usage(ap); return 1; } // Read options: // For argument parser reads. ossimString ts1; ossimArgumentParser::ossimParameter sp1(ts1); // Entry index: ossim_uint32 entryIndex = 0; if ( ap.read("-e", sp1) ) { entryIndex = ts1.toUInt32(); } // Set the reader properties if any. std::vector readerProps; while(ap.read("--reader-prop", sp1)) { std::vector splitArray; ts1.split(splitArray, "="); if(splitArray.size() == 2) { readerProp prop; prop.name = splitArray[0]; prop.value = splitArray[1]; readerProps.push_back(prop); } } ap.reportRemainingOptionsAsUnrecognized(); // Check the input file: ossimFilename imageFile = argv[1]; if ( !imageFile.exists() ) { usage(ap); return 1; } // Open up an image handler. ossimRefPtr ih = (ossimImageHandler*)ossimImageHandlerRegistry::instance()->open( imageFile ); if ( ih.valid() == false ) { cerr << "Could not open: " << imageFile << endl; return 1; } if ( entryIndex ) { if ( ih->setCurrentEntry( entryIndex ) == false ) { cerr << "Invalid entry: " << entryIndex << endl; return 1; } } // Set the reader properties if any. if ( readerProps.size() ) { std::vector::const_iterator i = readerProps.begin(); while( i != readerProps.end() ) { ossimRefPtr prop = new ossimStringProperty( (*i).name, (*i).value ); ih->setProperty(prop); ++i; } } vector bandList; ossimString bandString = argv[2]; const ossim_uint32 BANDS = ih->getNumberOfOutputBands(); if ( bandString.downcase() == "a" ) { for ( ossim_uint32 band = 0; band < BANDS; ++band) { if ( addBand( band, BANDS, bandList ) == false ) { return 1; } } } else { ossim_int32 band = bandString.toUInt32(); if ( addBand( band, BANDS, bandList ) == false ) { return 1; } } ossimIpt pt; pt.x = ossimString::toInt32(argv[3]); pt.y = ossimString::toInt32(argv[4]); ossimIrect rect(pt.x, pt.y, pt.x+1, pt.y+1); ossimRefPtr id = ih->getTile(rect, 0); if ( id.valid() ) { cout << "image_file: " << imageFile << "\nsample: " << pt.x << "\nline: " << pt.y; vector::const_iterator i = bandList.begin(); while ( i != bandList.end() ) { cout << "\nvalue[" << (*i) << "]: " << id->getPix( pt, (*i) ); ++i; } cout << endl; } else { cerr << "getTile request failed!" << endl; return 1; } return 0; } bool addBand( ossim_uint32 band, ossim_uint32 bandCount, vector& bandList ) { bool result = true; if ( band < bandCount ) { bandList.push_back(band); } else { cerr << "Band number " << band << " is out of range!" << endl; result = false; } return result; } ossim-Miami-2.9.1/test/src/imaging/ossim-gpkg-writer-test.cpp000066400000000000000000000166101352751253100241530ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // File: ossim-gpkg-writer-test.cpp // // Description: Test class for ossimGpkgWriter. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char* argv[]) { int status = 0; ossimInit::instance()->initialize(argc, argv); if (argc == 2 ) { ossimFilename outputFile = argv[1]; ossimString writerClass = "ossimGpkgWriter"; ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriter( writerClass ); if ( writer.valid() ) { ossimGpkgWriterInterface* gpkgWriter = dynamic_cast( writer.get() ); if ( gpkgWriter ) { ossimKeywordlist kwl; std::string key; std::string value; key = "zoom_levels"; // value = "(0,1,2,3,4,5,6,7,8,9,10,11)"; value = "(2,3,4,5)"; kwl.addPair( key, value ); key = "epsg"; value = "3857"; kwl.addPair( key, value ); key = "filename"; value = outputFile.string(); kwl.addPair( key, value ); if ( gpkgWriter->openFile( kwl ) ) { gpkgWriter->beginTileProcessing(); // Write some tiles: ossimRefPtr id = new ossimU8ImageData(0, 3, 256, 256); id->initialize(); id->createTestTile(); // Valid tile: if ( gpkgWriter->writeTile( id, 2, 0, 0 ) ) // tile, level, row, col { cout << "writeTile id, 2, 0, 0 success..." << endl; } else { cout << "writeTile id, 2, 0, 0 failed..." << endl; } if ( gpkgWriter->writeTile( id, 2, 0, 1 ) ) // tile, level, row, col { cout << "writeTile id, 2, 0, 1 success..." << endl; } else { cout << "writeTile id, 2, 0, 1 failed..." << endl; } if ( gpkgWriter->writeTile( id, 2, 1, 0 ) ) // tile, level, row, col { cout << "writeTile id, 2, 1, 0 success..." << endl; } else { cout << "writeTile id, 2, 1, 0 failed..." << endl; } if ( gpkgWriter->writeTile( id, 2, 1, 1 ) ) // tile, level, row, col { cout << "writeTile id, 2, 1, 1 success..." << endl; } else { cout << "writeTile id, 2, 1, 1 failed..." << endl; } if ( gpkgWriter->writeTile( id, 3, 0, 0 ) ) // tile, level, row, col { cout << "writeTile id, 3, 0, 0 success..." << endl; } else { cout << "writeTile id, 3, 0, 0 failed..." << endl; } if ( gpkgWriter->writeTile( id, 4, 0, 0 ) ) // tile, level, row, col { cout << "writeTile id, 4, 0, 0 success..." << endl; } else { cout << "writeTile id, 4, 0, 0 failed..." << endl; } if ( gpkgWriter->writeTile( id, 5, 0, 0 ) ) // tile, level, row, col { cout << "writeTile id, 5, 0, 0 success..." << endl; } else { cout << "writeTile id, 5, 0, 0 failed..." << endl; } // Invalid level if ( gpkgWriter->writeTile( id, 20, 0, 0 ) ) // tile, level, row, col { cout << "writeTile id, 20, 0, 0 success..." << endl; } else { cout << "writeTile id, 20, 0, 0 failed..." << endl; } // Invalid row if ( gpkgWriter->writeTile( id, 4, 10000, 0 ) ) // tile, level, row, col { cout << "writeTile id, 4, 10000, 0success..." << endl; } else { cout << "writeTile id, 4, 10000, 0 failed..." << endl; } // Invalid col if ( gpkgWriter->writeTile( id, 4, 0, 10000 ) ) // tile, level, row, col { cout << "writeTile id, 4, 0, 10000 success..." << endl; } else { cout << "writeTile id, 4, 0, 10000 failed..." << endl; } gpkgWriter->finalizeTileProcessing(); // Close this writer and test append mode: writer->close(); gpkgWriter = 0; writer = 0; // ref ptr cout << "Testing append mode..." << endl; writer = ossimImageWriterFactoryRegistry::instance()->createWriter( writerClass ); if ( writer.valid() ) { ossimGpkgWriterInterface* gpkgWriter = dynamic_cast( writer.get() ); if ( gpkgWriter ) { // Add append to options: key = "append"; value = "true"; kwl.addPair( key, value ); if ( gpkgWriter->openFile( kwl ) ) { gpkgWriter->beginTileProcessing(); if ( gpkgWriter->writeTile( id, 3, 0, 1 ) ) // tile, level, row, col { cout << "writeTile id, 3, 0, 1 success..." << endl; } else { cout << "writeTile id, 3, 0, 1 failed..." << endl; } } gpkgWriter->finalizeTileProcessing(); writer->close(); gpkgWriter = 0; } writer = 0; } } } else { cerr << "Could not cast!" << endl; } writer = 0; } else // Matches: { cerr << "ossimImageWriterFactoryRegistry::instance()->createWriter( ossimGpkgWriter ) failed!" << endl; } } else // Matches: if (argc == 2 ){ ... } { cout << argv[0] << " " << "\n\nGeoPackage writer test code.\n" << endl; } return status; } ossim-Miami-2.9.1/test/src/imaging/ossim-gsd-test.cpp000066400000000000000000000063761352751253100224760ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossim-gsd-test.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Test to output gsd from image geometry and then compute the gsd from center // latitude of the image if the projecion is geographic, i.e. scale is in // decimal degrees. // //---------------------------------------------------------------------------- // $Id: ossim-gsd-test.cpp 19751 2011-06-13 15:13:07Z dburken $ #include #include #include #include #include #include #include #include #include #include #include using namespace std; static void usage() { cout << "ossim-gsd-test " << "\nThis will compute meters per pixel from the center latitude if the\n" << "underlying projection scale units are in degrees." << endl; } int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if (argc != 2) { usage(); return 0; } ossimFilename imageFile = argv[argc - 1]; if ( !imageFile.exists() ) { usage(); return 1; } // Open up an image handler. ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open( ossimFilename(argv[argc - 1])); if ( ih.valid() == false ) { cerr << "Could not open: " << imageFile << endl; return 1; } cout << "image_file: " << imageFile << "\n"; ossimRefPtr geom = ih->getImageGeometry(); if ( geom.valid() ) { ossimDpt imageGeomGsd = geom->getMetersPerPixel(); cout << "image_geometry_meters_per_pixel: " << imageGeomGsd << "\n"; ossimDrect rect = ih->getImageRectangle(0); ossimKeywordlist kwl; geom->saveState(kwl); ossimDpt ipt = rect.midPoint(); cout << "center_image_point: " << ipt << "\n"; ossimGpt wpt; geom->localToWorld(ipt, wpt); cout << "center_world_point: " << wpt << "\n"; ossimDpt scale; bool scaleDegrees = false; const char* lookup = kwl.find("projection.pixel_scale_xy"); if ( lookup ) { ossimString s = lookup; scale.toPoint(s); cout << "projection.pixel_scale_xy: " << scale << "\n"; const char* lookup = kwl.find("projection.pixel_scale_units"); if ( lookup ) { s = lookup; scaleDegrees = (s == "degrees"); cout << "projection.scale_units: " << s << "\n"; } if ( scaleDegrees ) { ossimDpt mpd = wpt.metersPerDegree(); cout << "meters_per_degree_for_center: " << mpd << "\n"; ossimDpt computeGsd; computeGsd.x = mpd.x * scale.x; computeGsd.y = mpd.y * scale.y; cout << "computed_meters_per_pixel_for_center_lat: " << computeGsd << "\n"; } } } else { cout << "null geometry!\n"; } cout << endl; return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-histogram-test.cpp000066400000000000000000000075331352751253100237120ustar00rootroot00000000000000//--- // License: MIT // // File: ossim-quickbird-metadata-test.cpp // // Description: Test code for ossim histogram stuff. //--- // $Id$ #include #include #include #include #include #include #include #include #include #include using namespace std; static void usage() { cout << "ossim-histogram-test " << endl; } int main(int argc, char *argv[]) { int returnCode = 0; ossimInit::instance()->initialize(argc, argv); if (argc == 2) { try { ossimFilename file = argv[argc - 1]; if ( file.exists() ) { ossimRefPtr mrh = new ossimMultiResLevelHistogram(); if ( mrh.valid() ) { if ( mrh->importHistogram(file) == true ) { cout << "opened histogram: " << file << "\n"; ossimRefPtr mbh = mrh->getMultiBandHistogram(0); if ( mbh.valid() ) { const ossim_uint32 BANDS = mbh->getNumberOfBands(); cout << "bands: " << BANDS << "\n"; for ( ossim_uint32 band = 0; band < BANDS; ++band) { ossimRefPtr h = mbh->getHistogram(band); if ( h.valid() ) { ossim_uint32 min_idx = std::floor(h->GetMinVal()); ossim_uint32 max_idx = std::floor(h->GetMaxVal()); cout << "band: " << band << "\n" << "buckets: " << h->GetRes() << "\n" << "min_val: " << h->GetMinVal() << "\n" << "max_val: " << h->GetMaxVal() << "\n" << "max_count: " << h->GetMaxCount() << "\n" << "min_val_count: " << h->GetCounts()[min_idx] << "\n" << "max_val_count: " << h->GetCounts()[max_idx] << "\n" << "vmin: " << h->GetRangeMin() << "\n" << "vmax: " << h->GetRangeMax() << "\n" << "low_clip(0%): " << std::floor( h->LowClipVal(0.0) ) << "\n" << "high_clip(0%): " << std::floor( h->HighClipVal(0.0) ) << "\n" << "low_clip(0.1%): " << std::floor( h->LowClipVal(0.001) ) << "\n" << "high_clip(0.1%): " << std::floor( h->HighClipVal(0.001) ) << "\n" << "low_clip(1%): " << std::floor( h->LowClipVal(0.01) ) << "\n" << "high_clip(1%): " << std::floor( h->HighClipVal(0.01) ) << "\n\n"; } } cout << endl; } } } else { cout << "could not open: " << file << endl; } } else { usage(); returnCode = 1; } } catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } catch( ... ) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-foo caught unhandled exception!" << std::endl; returnCode = 1; } } else { usage(); } return returnCode; } ossim-Miami-2.9.1/test/src/imaging/ossim-image-chain-test.cpp000066400000000000000000000037631352751253100240600ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossim-image-chain-test.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Test application for ossimImageChain class. // //---------------------------------------------------------------------------- // $Id: ossim-image-chain-test.cpp 19751 2011-06-13 15:13:07Z dburken $ #include #include #include #include #include #include #include #include using namespace std; static void usage() { cout << "ossim-image-chain-test " << endl; } int main(int argc, char *argv[]) { int result = 0; ossimInit::instance()->initialize(argc, argv); if (argc == 2) { try // In case exceptions is thrown. { ossimFilename image = argv[1]; ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(image); if ( ih.valid() ) { cout << "Opened image: " << image << endl; ossimRefPtr ic = new ossimImageChain(); ic->addLast( ih.get() ); cout << "Added to image chain via ossimImageChain::addLast" << endl; cout << "Calling ossimImageChain::removeChild" << endl; if ( ic->removeChild( ih.get() ) ) { cout << "Removed from chain..." << endl; ih = 0; } ic = 0; } else { cout << "Could not open: " << image << endl; result = 1; } } catch( const ossimException& e ) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; result = 1; } } else { usage(); } return result; } ossim-Miami-2.9.1/test/src/imaging/ossim-image-handler-state-test.cpp000066400000000000000000000151511352751253100255230ustar00rootroot00000000000000//--- // // License: MIT // // File: ossim-foo.cpp // // Description: Contains application definition "ossim-foo" app. // // NOTE: This is supplied for simple quick test. DO NOT checkin your test to // the svn repository. Simply edit ossim-foo.cpp and run your test. // After completion you can do a "git checkout -- ossimfoo.cpp" if // you want to keep your working repository up to snuff. // // $Id$ //--- // ossim includes: These are here just to save time/typing... #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Put your includes here: // System includes: #include #include #include #include int main(int argc, char *argv[]) { int returnCode = 0; ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); ap.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); ap.getApplicationUsage()->addCommandLineOption("--max-time-to-open-state","specify the time in seconds. Example: 1.234"); ap.getApplicationUsage()->addCommandLineOption("--min-speedup","specify the minumum speedup for state open versus normal open. For min-speedup = 2.5 means that we must be at least 2.5 times faster with the state"); ap.getApplicationUsage()->addCommandLineOption("--geom-test","Will enable geometry tests. Will load the file the with and without the state and make sure the geometry remains the same"); std::string ts1; ossimArgumentParser::ossimParameter sp1(ts1); try { ossim_float64 maxTimeForStateOpen = -1; ossim_float64 minSpeedup = 0.0; bool geomTestFlag = false; // argumentParser.getApplicationUsage()->addCommandLineOption("--random-seed", "value to use as the seed for the random elevation post generator"); if (ap.argc() == 1 || ap.read("-h") || ap.read("--help")) { ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); exit(0); } if(ap.read("--max-time-to-open-state", sp1)) { maxTimeForStateOpen = ossimString(ts1).toFloat64(); } if(ap.read("--min-speedup", sp1)) { minSpeedup = ossimString(ts1).toFloat64(); } if(ap.read("--geom-test")) { geomTestFlag = true; } if(ap.argc() == 2) { ossimTimer::Timer_t t1; ossimTimer::Timer_t t2; std::shared_ptr state; ossim_float64 deltaNoState = 0.0; //std::cout << "maxTimeForStateOpen: " << maxTimeForStateOpen << "\n"; t1 = ossimTimer::instance()->tick(); ossimRefPtr h = ossimImageHandlerRegistry::instance()->open(ossimFilename(ap[1])); t2 = ossimTimer::instance()->tick(); deltaNoState = ossimTimer::instance()->delta_s(t1,t2); std::cout << "open-image-delta: " << deltaNoState << "\n"; if(h) { state = h->getState(); t1 = ossimTimer::instance()->tick(); ossimRefPtr hState = ossimImageHandlerRegistry::instance()->open(state); t2 = ossimTimer::instance()->tick(); if(hState) { ossim_float64 deltaState = ossimTimer::instance()->delta_s(t1,t2); std::cout << "open-image-state-delta: " << deltaState << "\n"; if(maxTimeForStateOpen > 0.0) { std::cout << "max-time-to-open-state: " << maxTimeForStateOpen << "\n"; if(deltaState>maxTimeForStateOpen) { throw ossimException("Took too long for state open!"); } } ossim_float64 r = deltaNoState/deltaState; if(minSpeedup > 0.0) { std::cout << "speedup: " << r << "\n"; if(r < minSpeedup) { throw ossimException("Took too long for state open!"); } } if(geomTestFlag) { t1 = ossimTimer::instance()->tick(); ossimRefPtr geomNoState = h->getImageGeometry(); t2 = ossimTimer::instance()->tick(); std::cout << "geometry-no-state-delta: " << ossimTimer::instance()->delta_s(t1,t2) << "\n"; t1 = ossimTimer::instance()->tick(); ossimRefPtr geomState = hState->getImageGeometry(); t2 = ossimTimer::instance()->tick(); std::cout << "geometry-state-delta: " << ossimTimer::instance()->delta_s(t1,t2) << "\n"; if(geomNoState&&geomState) { ossimKeywordlist kwl1,kwl2; geomNoState->saveState(kwl1); geomState->saveState(kwl2); if(kwl1 != kwl2) { std::cout << "GEOMETRY from No State Load: \n" << kwl1 << "\n"; std::cout << "GEOMETRY from State Load: \n" << kwl2 << "\n"; throw ossimException("Geometries are not equal"); } } else { throw ossimException("Unable to create geometry for geom test"); } } } else { throw ossimException(ossimString("Unable to open image from state")+ ap[1]); } } else { throw ossimException(ossimString("Unable to open file") + ap[1]); } } else { throw ossimException("Image not specified"); } // add code } catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } catch( ... ) { ossimNotify(ossimNotifyLevel_WARN) << argv[0] << " caught unhandled exception!" << std::endl; returnCode = 1; } return returnCode; } ossim-Miami-2.9.1/test/src/imaging/ossim-image-handler-test.cpp000066400000000000000000000056101352751253100244040ustar00rootroot00000000000000#include #include #include #include #include #include int main(int argc, char *argv[]) { ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help", "Shows help"); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] "); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); if(argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(std::cout); exit(0); } ossimString extensions = "gif,j2k,jp2,jpg,jpeg,tif,tiff,nitf,ntf,ccf,til,img,toc,rpf,doq,doqq,dt0,dt1,dt2,dt3,dt4,dt5,dt6,hgt,dem,fst,ras"; ossimString mimeTypes = "image/gif,image/jpg,image/jpx,image/jp2,image/jpeg,image/tiff,image/nitf,image/ntf,image/doq,image/doqq,image/dted,image/hgt,image/dem"; std::vector extensionArray; std::vector mimeArray; extensions.split(extensionArray, ","); mimeTypes.split(mimeArray, ","); ossim_uint32 idx = 0; for(idx = 0; idx < extensionArray.size(); ++idx) { std::vector > result; ossimImageHandlerRegistry::instance()->getImageHandlersBySuffix(result, extensionArray[idx]); std::cout << "extension " << extensionArray[idx] << ": "; if(!result.empty()) { for(ossim_uint32 resultIdx = 0; resultIdx < result.size(); ++resultIdx) { std::cout << result[resultIdx]->getClassName() << (((resultIdx+1)==result.size())?"":", "); } } std::cout << "\n"; } for(idx = 0; idx < mimeArray.size(); ++idx) { std::vector > result; ossimImageHandlerRegistry::instance()->getImageHandlersByMimeType(result, mimeArray[idx]); std::cout << "mimeType " << mimeArray[idx] << ": "; if(!result.empty()) { for(ossim_uint32 resultIdx = 0; resultIdx < result.size(); ++resultIdx) { std::cout << result[resultIdx]->getClassName() << (((resultIdx+1)==result.size())?"":", "); } } std::cout << "\n"; } if(argc > 1) { for(idx = 1; idx < static_cast(argc); ++idx) { ossimRefPtr handler = ossimImageHandlerRegistry::instance()->openBySuffix(ossimFilename(argv[idx])); if(handler.valid()) { std::cout << "Opened by extension for file " << argv[idx] << std::endl; } } } return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-image-writer-test.cpp000066400000000000000000000056511352751253100243100ustar00rootroot00000000000000#include /* for exit */ #include #include #include #include #include int main(int argc, char *argv[]) { ossimArgumentParser argumentParser(&argc, argv); ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help", "Shows help"); argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] "); argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName()); if(argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(std::cout); exit(0); } ossimString extensions = "png,gif,j2k,jp2,jpg,jpeg,tif,tiff,nitf,ntf,ccf,til,img,toc,rpf,doq,doqq,dt0,dt1,dt2,dt3,dt4,dt5,dt6,hgt,dem,fst,ras"; ossimString mimeTypes = "image/gif,image/jpg,image/png,image/jpx,image/jp2,image/jpeg,image/tiff,image/nitf,image/ntf,image/doq,image/doqq,image/dted,image/hgt,image/dem"; std::vector extensionArray; std::vector mimeArray; extensions.split(extensionArray, ","); mimeTypes.split(mimeArray, ","); ossim_uint32 idx = 0; for(idx = 0; idx < extensionArray.size(); ++idx) { ossimImageWriterFactoryBase::ImageFileWriterList result; ossimImageWriterFactoryRegistry::instance()->getImageFileWritersBySuffix(result, extensionArray[idx]); std::cout << "extension " << extensionArray[idx] << ": "; if(!result.empty()) { for(ossim_uint32 resultIdx = 0; resultIdx < result.size(); ++resultIdx) { std::cout << result[resultIdx]->getClassName() << (((resultIdx+1)==result.size())?"":", "); } } std::cout << "\n"; } for(idx = 0; idx < mimeArray.size(); ++idx) { ossimImageWriterFactoryBase::ImageFileWriterList result; ossimImageWriterFactoryRegistry::instance()->getImageFileWritersByMimeType(result, mimeArray[idx]); std::cout << "mimeType " << mimeArray[idx] << ": "; if(!result.empty()) { for(ossim_uint32 resultIdx = 0; resultIdx < result.size(); ++resultIdx) { std::cout << result[resultIdx]->getClassName() << (((resultIdx+1)==result.size())?"":", "); } } std::cout << "\n"; } if(argc > 1) { for(idx = 1; static_cast(idx) < argc; ++idx) { ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriter(ossimFilename(argv[idx])); if(writer.valid()) { std::cout << writer->getClassName() << ": Opened by extension for file " << argv[idx] << std::endl; } } } return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-index-to-rgb-lut-test.cpp000066400000000000000000000141111352751253100250040ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // Description: Test of ossimIndexToRgbLutFilter. // // $Id: ossim-index-to-rgb-lut-test.cpp 23068 2015-01-07 23:08:29Z okramer $ //---------------------------------------------------------------------------- #include using namespace std; #include // ossim contants... #include #include #include #include #include #include static const std::string kwl_literal = "type: ossimIndexToRgbLutFilter \n" "mode: literal \n" "entry0.index: 0 \n" "entry0.color: 1 2 3 \n" "entry1.index: 1.0 \n" "entry1.color: 255 1 1 \n" "entry2.index: 2.0 \n" "entry2.color: 1 255 1 \n"; static const std::string kwl_vertices = "type: ossimIndexToRgbLutFilter \n" "mode: vertices \n" "entry0.index: 0.5 \n" "entry0.color: 1 2 3 \n" "entry1.index: 127.5 \n" "entry1.color: 255 1 1 \n" "entry2.index: 250.0 \n" "entry2.color: 1 255 1 \n"; static const std::string kwl_regular = "type: ossimIndexToRgbLutFilter \n" "mode: regular \n" "entry0: 1 1 255 \n" "entry1: 1 255 1 \n" "entry2: 255 1 1 \n" "max_value: 250 \n" "min_value: 1 \n"; static const std::string kwl_regular2 = "type: ossimIndexToRgbLutFilter \n" "mode: regular \n" "entry0.r: 1 \n" "entry0.g: 1 \n" "entry0.b: 255 \n" "entry1.r: 1 \n" "entry1.g: 255 \n" "entry1.b: 1 \n" "entry2.r: 255 \n" "entry2.g: 1 \n" "entry2.b: 1 \n" "max_value: 250 \n" "min_value: 1 \n"; static const std::string kwl_regnorm = "type: ossimIndexToRgbLutFilter \n" "mode: regular \n" "entry0: 1 1 255 \n" "entry1: 1 255 1 \n" "entry2: 255 1 1 \n" "max_value: 1.0 \n" "min_value: 0 \n"; bool runTest(const std::string& kwlString, ossimRefPtr& lutFilter) { ossimKeywordlist kwl; kwl.parseString(kwlString); if (!lutFilter->loadState(kwl)) { cout << "ERROR: bad state returned from ossimIndexToRgbLutFilter::loadState()" << endl; return false; } lutFilter->initialize(); ossimIrect rect (lutFilter->getBoundingRect()); ossimRefPtr rgbBuffer = lutFilter->getTile(rect); ossim_uint8* outBuf[3]; outBuf[0] = (ossim_uint8*)(rgbBuffer->getBuf(0)); outBuf[1] = (ossim_uint8*)(rgbBuffer->getBuf(1)); outBuf[2] = (ossim_uint8*)(rgbBuffer->getBuf(2)); for (int x=0; x<256; ++x) { cout << "[" << x << "] : " << (int)outBuf[0][x] << " " << (int)outBuf[1][x] << " " << (int)outBuf[2][x] << endl; } cout << endl; return true; } int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); // For batch testing, permit assigning output dir for test tiff: ossimFilename tiffOutFile ("./test-tif.tif"); if (argc > 1) tiffOutFile = argv[1]; // Initialize the input index buffer: ossimRefPtr indexBuffer = ossimImageDataFactory::instance()->create(0, OSSIM_UINT8, 1, 256, 1); if(!indexBuffer.valid()) return -1; indexBuffer->initialize(); for (int x=0; x<256; ++x) indexBuffer->setValue(x, 0, x); indexBuffer->validate(); // Create output image chain: ossimRefPtr memSource = new ossimMemoryImageSource; memSource->setImage(indexBuffer); memSource->setRect(0, 0, 256, 1); ossimRefPtr lutFilter = new ossimIndexToRgbLutFilter(); lutFilter->connectMyInputTo(memSource.get()); bool success; // Test 1: LITERAL mode cout << "\nTEST 1 -- Running LITERAL mode test...\n"<create(0, OSSIM_FLOAT64, 1, 512, 512); indexBuffer->initialize(); for (int y=0; y<512; ++y) { for (int x=0; x<512; ++x) { double distance = sqrt((double) ((x-256)*(x-256) + (y-256)*(y-256))); double d = (256.0 - distance) / 256.0; if (d <= 0) d = 0.0; indexBuffer->setValue(x, y, d); } } indexBuffer->validate(); ossimRefPtr idxSource = new ossimMemoryImageSource; idxSource->setImage(indexBuffer); ossimRefPtr lut2Filter = new ossimIndexToRgbLutFilter(); lut2Filter->connectMyInputTo(idxSource.get()); ossimKeywordlist kwl; kwl.parseString(kwl_regnorm); lut2Filter->loadState(kwl); lut2Filter->initialize(); ossimIrect rect (lut2Filter->getBoundingRect()); ossimRefPtr rgbBuffer = lut2Filter->getTile(rect); ossimRefPtr rgbSource = new ossimMemoryImageSource; rgbSource->setImage(rgbBuffer); ossimRefPtr writer = new ossimTiffWriter; writer->setFilename(tiffOutFile); writer->connectMyInputTo(0, rgbSource.get()); writer->setAreaOfInterest(rect); writer->setGeotiffFlag(false); success = writer->execute(); if (success) cout << "Heat map image successfully written."< #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; void usage(char* appName) { cout << "\nUsage: "<] [--remap] []\n"< synthesizeInput() { // Create geometry: ossimGpt observerGpt (0, 0, 0); ossimDpt gsd (1.0, 1.0); // must be same value in both directions ossimRefPtr mapProj = new ossimEquDistCylProjection(); mapProj->setOrigin(observerGpt); mapProj->setMetersPerPixel(gsd); ossimDpt degPerPixel (mapProj->getDecimalDegreesPerPixel()); mapProj->setElevationLookupFlag(false); ossimGpt ulTiePt (observerGpt); ossimIpt image_size (512 , 512); ulTiePt.lat += degPerPixel.lat * (image_size.y-1)/2.0; ulTiePt.lon -= degPerPixel.lon * (image_size.x-1)/2.0; mapProj->setUlTiePoints(ulTiePt); ossimRefPtr geometry = new ossimImageGeometry(0, mapProj.get()); geometry->setImageSize(image_size); ossim_uint32 tile_size = 256; ossim_uint8 mean1 = 20; ossim_uint8 mean2 = 60; ossim_uint8 mean3 = 100; // Generate data: ossimRefPtr outTile = ossimImageDataFactory::instance()->create(0, OSSIM_UINT8, 1, tile_size, tile_size); outTile->initialize(); ossim_uint8* buf = outTile->getUcharBuf(); srand (time(NULL)); ossim_uint32 buf_size = tile_size*tile_size; ossim_uint32 buf_offset = buf_size / 4; double noiseAmplitude1 = 15; ossim_uint32 i=0; for (; i outImage = ossimImageDataFactory::instance()->create(0, OSSIM_UINT8, 1, image_size.x, image_size.y); if(outImage.valid()) outImage->initialize(); else { cout<<"Error encountered allocating tile for input data generation."<fill(0); ossimIpt tile_origin(0,0); for (tile_origin.y=0; tile_origin.ysetOrigin(tile_origin); outImage->loadTile(outTile.get()); } } // Create output image chain: ossimRefPtr memSource = new ossimMemoryImageSource; memSource->setImage(outImage); memSource->setImageGeometry(geometry.get()); // Write the synth image to disk: //ossimRefPtr writer = new ossimTiffWriter(); //writer->connectMyInputTo(0, memSource.get()); //ossimFilename test_raster ("generated-kmeans-input.tif"); //writer->setFilename(test_raster); //writer->setGeotiffFlag(true); //bool success = writer->execute(); ossimRefPtr pointer = memSource.get(); return pointer; } int main(int argc, char *argv[]) { int returnCode = 0; ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); std::string tempString; ossimArgumentParser::ossimParameter stringParam(tempString); if ( ap.read("-h") || ap.read("--help") ) { usage(ap[0]); return 0; } ossimFilename inputFilename; if ( ap.read("-i", stringParam)) inputFilename = tempString; bool doRemap = false; if ( ap.read("--remap")) doRemap = true; ap.reportRemainingOptionsAsUnrecognized(); if ( ap.errors() ) { ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE)); return -1; } ossimFilename outputFilename ("kmeans-out.tif"); if (ap.argc() > 1 ) outputFilename = ap.argv()[1]; ossimRefPtr inputImage = 0; if (inputFilename.empty()) inputImage = synthesizeInput(); else inputImage = ossimImageHandlerRegistry::instance()->open(inputFilename); if (!inputImage.valid()) { cout<< "Could not load input image <"<."< geometry = inputImage->getImageGeometry(); if (!geometry.valid()) { cout<< "Could not establish an input image geometry for input image <"<."< kmeans = new ossimKMeansFilter; kmeans->connectMyInputTo(inputImage.get()); ossim_uint32 lut [3] = { 32, 128, 255 }; kmeans->setClusterPixelValues(lut, 3); ossimRefPtr lastSource = kmeans.get(); if (doRemap) { // Remap to color for better visibility ossimKeywordlist lutkwl; lutkwl.add("type", "ossimIndexToRgbLutFilter"); lutkwl.add("mode", "literal"); lutkwl.add("entry0.index", "0"); lutkwl.add("entry0.color", "0 0 0"); lutkwl.add("entry1.index", "32"); lutkwl.add("entry1.color", "255 255 1"); lutkwl.add("entry2.index", "128"); lutkwl.add("entry2.color", "255 1 1"); lutkwl.add("entry3.index", "255"); lutkwl.add("entry3.color", "1 255 1"); ossimRefPtr lutfilter = new ossimIndexToRgbLutFilter; lutfilter->connectMyInputTo(kmeans.get()); lutfilter->loadState(lutkwl); lastSource = lutfilter.get(); } // Output the clustered image to disk: ossimRefPtr writer = new ossimTiffWriter(); writer->connectMyInputTo(0, lastSource.get()); writer->setFilename(outputFilename); writer->setGeotiffFlag(true); bool success = writer->execute(); return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-linear-stretch-remapper-test.cpp000066400000000000000000000056041352751253100264470ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test application for ossimPiecewiseRemapper class. // //---------------------------------------------------------------------------- // $Id: ossim-single-image-chain-test.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char* argv[]) { ossimTimer::instance()->setStartTick(); ossimInit::instance()->initialize(argc, argv); ossimTimer::Timer_t t1 = ossimTimer::instance()->tick(); cout << "elapsed time after initialize(ms): " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; if (argc < 5) { cout <<"\n"<< argv[0] << " " << "\nPerforms a linear stretch on and writes the result to . The input" " image is stretched between and provided.\n"<< endl; return 0; } ossimFilename infile = argv[3]; ossimFilename outfile = argv[4]; double min = atof(argv[1]); double max = atof(argv[2]); ossimRefPtr sic1 = new ossimSingleImageChain(); if ( !sic1->open( infile ) ) { cout<<"Error opening input file <"<"< remapper = new ossimLinearStretchRemapper(); remapper->setMinPixelValue(min, 0); remapper->setMaxPixelValue(max, 0); sic1->addFirst( remapper.get() ); sic1->initialize(); // Write image: ossimRefPtr writer = new ossimTiffWriter(); if ( !writer->open( outfile ) ) { cout<<"Error opening output file <"<"<addListener(&prog); writer->connectMyInputTo(0, sic1.get()); writer->execute(); ossimTimer::Timer_t t2 = ossimTimer::instance()->tick(); cout << "elapsed time after write(ms): " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; cout << "write time minus initialize: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->delta_s(t1, t2) << "\n"; return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-loadtile-test.cpp000066400000000000000000000105711352751253100235060ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-foo.cpp // // Author: David Burken // // Description: Test app: // // 1) Makes a 256x256 tile. Each line having a single value from 0 to 255. // 2) Test ossimImageData::loadTile where source is 16 bit, destination 8 bit. // 3) Test histogram. Should have 256 bins (0 to 255) each with count of 256. // // Returns 0 on success and outputs PASSED, 1 on failure and outputs FAILED. // // $Id$ //---------------------------------------------------------------------------- #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main( int argc, char* argv[] ) { enum { PASSED = 0, FAILED = 1 }; int status = PASSED; ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); try { ossimIrect rect(0,0,255,255); ossimRefPtr srcTile = new ossimImageData(0, OSSIM_UINT16, 1, 256, 256); srcTile->initialize(); srcTile->setImageRectangle( rect ); // Set max for conversion to 8 bit. srcTile->setMaxPix( 255, 0 ); ossim_uint16* src = srcTile->getUshortBuf(); const ossim_uint32 LINES = 256; const ossim_uint32 SAMPLES = 256; ossim_uint32 s = 0; // line loop for(ossim_uint32 line = 0; line < LINES; ++line) { // sample loop for(ossim_uint32 samp = 0; samp < SAMPLES; ++samp) { src[samp] = s; } src += SAMPLES; ++s; } ossimRefPtr destTile = new ossimImageData(0, OSSIM_UINT8, 1, 256, 256); destTile->initialize(); destTile->setImageRectangle( rect ); destTile->loadTile( srcTile.get() ); destTile->validate(); ossimRefPtr his = new ossimMultiBandHistogram( 1, 255, 1, 255, 0, OSSIM_UINT8); ossimIrect clipRect(0,0,255,255); cout << "clipRect: " << clipRect << endl; destTile->populateHistogram( his, clipRect ); const ossimRefPtr h = his->getHistogram( 0 ); if ( h.valid() ) { float count; // Skipping NULL pixel (i=0) since those are no longer being counted in the histogram // (OLK 04/2016) int bins = h->GetRes(); cout << "histogram:" << "\nbins: " << bins << "\nnull value: " << h->getNullValue() << "\nnull count: " << h->getNullCount() << "\n"; ossim_uint32 pixelValue = 0; ossim_int32 valIndex; for( ossim_uint32 i = 0; i < bins; ++i ) { pixelValue = h->GetValFromIndex( i ); valIndex = h->GetIndex( pixelValue ); count = h->GetCount( static_cast(pixelValue) ); cout << "pixelValueFromIndex: " << pixelValue << " indexFromPixelValue: " << valIndex << " bin[" << pixelValue << "] count: " << count << "\n"; if ( 0 ) // count != clipRect.width() ) { status = FAILED; cerr << "bin[" << i << "]: " << h->GetCount( i ) << "\nbin[" << i << "]: count = " << count << "\nShould be: " << clipRect.width() << "\nhistogram bin count: " << h->GetRes() << endl; const ossim_uint8* buf = destTile->getUcharBuf(); if ( buf ) { cerr << "tile buffer index(255, 255) = " << (int)buf[65535] << endl; } break; } } } else { status = FAILED; } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; status = FAILED; } cout << "ossim-loadtile-test: " << (status == PASSED ? "PASSED" : "FAILED") << endl; return status; } ossim-Miami-2.9.1/test/src/imaging/ossim-mask-filter-test.cpp000066400000000000000000000134031352751253100241240ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // File: ossim-mask-filter-test.cpp // // Author: David Burken // // Description: Test application for ossimMaskFilter. // //---------------------------------------------------------------------------- // $Id: ossim-mask-filter-test.cpp 21631 2012-09-06 18:10:55Z dburken $ #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include int main(int argc, char* argv[]) { ossimTimer::instance()->setStartTick(); ossimInit::instance()->initialize(argc, argv); if (argc != 6) { cout << argv[0] << " " << "\nCombines image and shape files with mask filter and writes " << "result to output file.\n" << "valid mask_types:\n" << "1 = OSSIM_MASK_TYPE_SELECT\n" << "2 = OSSIM_MASK_TYPE_INVERT\n" << "3 = OSSIM_MASK_TYPE_WEIGHTED\n" << "4 = OSSIM_MASK_TYPE_BINARY\n" << "5 = OSSIM_MASK_TYPE_BINARY_INVERSE\n" << "resample_flag if true the output will be rendered to a geographic projection.\n" << "output_file is a mask of image and shape.\n" << endl; return 0; } int i = atoi(argv[1]); if ( (i < 1) || (i > 5) ) { cerr << "mask type out of range!" << endl; return 1; } ossimMaskFilter::ossimFileSelectionMaskType mask_type = static_cast(i); i = atoi(argv[2]); bool resample_flag = (i?true:false); ossimFilename inputImgName = ossimFilename(argv[3]); ossimFilename inputShpName = ossimFilename(argv[4]); ossimFilename outputFile = ossimFilename(argv[5]); cout << "ossim-mask-filter-test:" << "\nmask_type: " << mask_type << "\nresample_flag: " << resample_flag << "\ninputImgName: " << inputImgName << "\ninputShpName: " << inputShpName << "\noutputFile: " << outputFile << endl; //--- // Test masking shape and image: //--- ossimRefPtr inputImg = 0; if ( !resample_flag ) { inputImg = ossimImageHandlerRegistry::instance()->open(inputImgName); } else { ossimRefPtr sic = new ossimSingleImageChain(); if ( sic->open( inputImgName ) ) { // Render the image chain. sic->createRenderedChain(); inputImg = sic.get(); } else { sic = 0; } } if ( inputImg.valid() == false ) { cout << "Could not open: " << inputImgName << endl; return 1; } ossimRefPtr inputShp = ossimImageHandlerRegistry::instance()->open(inputShpName); if ( inputShp.valid() ) { if ( inputShp->getClassName() == "ossimOgrGdalTileSource" ) { ossimViewInterface* shpView = PTR_CAST(ossimViewInterface, inputShp.get()); if (shpView) { //--- // Test masking image handler and shape file. //--- // Set the shape reader's view to that of the image's. shpView->setView(inputImg->getImageGeometry().get()); // Turn fill on... ossimRefPtr fillProp = new ossimStringProperty(ossimString("fill_flag"), ossimString("1")); inputShp->setProperty(fillProp); ossimRefPtr maskFlt = new ossimMaskFilter(); maskFlt->setMaskType(mask_type); maskFlt->connectMyInputTo( 0, inputImg.get() ); // maskFlt->connectMyInputTo(1, inputShp.get()); maskFlt->setMaskSource( inputShp.get() ); maskFlt->initialize(); ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()-> createWriterFromExtension(outputFile.ext()); if ( writer->open( outputFile ) ) { // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); writer->connectMyInputTo(0, maskFlt.get()); // Set the cut rect to the input image. writer->setAreaOfInterest(inputImg->getBoundingRect()); writer->execute(); cout << "Wrote file: " << outputFile << "\nElapsed time(seconds): " << ossimTimer::instance()->time_s() << "\n"; } else { cout << "Could not open: " << argv[3] << endl; } } else { cerr << "Could not get view interface..." << endl; } } else { cerr << "2nd argument must be a shape file." << endl; } } else { cerr << "Could not open: " << inputShpName << endl; } return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-piecewise-remapper-test.cpp000066400000000000000000000167001352751253100254770ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test application for ossimPiecewiseRemapper class. // //---------------------------------------------------------------------------- // $Id: ossim-single-image-chain-test.cpp 21631 2012-09-06 18:10:55Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char* argv[]) { ossimTimer::instance()->setStartTick(); ossimInit::instance()->initialize(argc, argv); ossimTimer::Timer_t t1 = ossimTimer::instance()->tick(); cout << "elapsed time after initialize(ms): " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; if (argc < 2) { cout << argv[0] << " " << "\nOpens up single image chain and dumps the state to keyword" << " list." << endl; return 0; } ossimRefPtr sic1 = new ossimSingleImageChain(); if ( sic1->open( ossimFilename(argv[1]) ) ) { cout << "Opened: " << argv[1] << endl; ossimRefPtr pwr = new ossimPiecewiseRemapper(); // Add to the end of the chain. So it's image_handler->piecewise_remapper. sic1->addFirst( pwr.get() ); ossimKeywordlist kwl; std::string key; std::string val; key = "number_bands"; val = "1"; kwl.addPair(key, val); key = "remap_type"; val = "linear_native"; kwl.addPair(key, val); // (( ),( )) key = "band0.remap0"; val = "((0, 127, 0, 127), (128, 255, 128, 382))"; kwl.addPair(key, val); key = "band0.remap1"; val = "((0, 382, 0, 255))"; kwl.addPair(key, val); key = "scalar_type"; val = "OSSIM_UINT8"; kwl.addPair(key, val); key = "type"; val = "ossimPiecewiseRemapper"; kwl.addPair(key, val); cout << "kwl:\n" << kwl << "\n"; pwr->loadState( kwl, 0 ); // pwr->initialize(); // sic1->addScalarRemapper(); sic1->addCache(); sic1->initialize(); // Set up chain: if ( sic1->getImageHandler()->getNumberOfOutputBands() == 4 ) { // Just guessing... // sic1->setThreeBandReverseFlag(true); } // Always have resampler cache. // sic1->setAddResamplerCacheFlag(true); // Histogram: // sic1->setAddHistogramFlag(true); // sic1->createRenderedChain(); kwl.clear(); sic1->saveState(kwl, 0); cout << "sic1 state: " << kwl << endl; } if (argc == 3) { // Write image: ossimRefPtr writer = new ossimTiffWriter(); if ( writer->open( ossimFilename(argv[2]) ) ) { cout << "Outputting file: " << ossimFilename(argv[2]) << endl; // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); writer->connectMyInputTo(0, sic1.get()); writer->execute(); ossimTimer::Timer_t t2 = ossimTimer::instance()->tick(); cout << "elapsed time after write(ms): " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; cout << "write time minus initialize: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->delta_s(t1, t2) << "\n"; } } return 0; } #if 0 // Histogram stretch: if ( sic1->openHistogram(ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX) == false ) { cout << "Could not do histogram stretch!" << endl; } if (argc == 3) { // Write image: ossimRefPtr writer = new ossimTiffWriter(); if ( writer->open( ossimFilename(argv[2]) ) ) { cout << "Outputting file: " << ossimFilename(argv[2]) << endl; // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); writer->connectMyInputTo(0, sic1.get()); writer->execute(); ossimTimer::Timer_t t2 = ossimTimer::instance()->tick(); cout << "elapsed time after write(ms): " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; cout << "write time minus initialize: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->delta_s(t1, t2) << "\n"; } } #endif #if 0 ossimRefPtr geom = sic1->getImageGeometry(); if (geom.valid()) { geom->print(cout); } // Test the load state. // ossimKeywordlist kwl; kwl.clear(); sic1->saveState(kwl, 0); ossimSingleImageChain* sic2 = new ossimSingleImageChain(); sic2->loadState(kwl, 0); kwl.clear(); sic2->saveState(kwl, 0); cout << "\n\nSingle image chain from load state kwl\n" << kwl; } #endif #if 0 // Create a normal chain. sic1 = new ossimSingleImageChain(true, // addHistogramFlag true, // addResamplerCacheFlag true, // addChainCacheFlag false, // remapToEightBitFlag false, // threeBandFlag false); // threeBandReverseFlag if ( sic1->open( ossimFilename(argv[1]) ) ) { sic1->createRenderedChain(); ossimKeywordlist kwl; sic1->saveState(kwl, 0); cout << "\n\nNormal single image chain kwl\n" << kwl; } // Create a stripped down chain. sic1 = new ossimSingleImageChain(); if ( sic1->open( ossimFilename(argv[1]) ) ) { sic1->createRenderedChain(); ossimKeywordlist kwl; sic1->saveState(kwl, 0); cout << "\n\nSingle image chain stripped down kwl\n" << kwl; } // Create a rgb reversed chain. sic1 = new ossimSingleImageChain(); if ( sic1->open( ossimFilename(argv[1]) ) ) { sic1->setThreeBandReverseFlag(true); sic1->createRenderedChain(); ossimKeywordlist kwl; sic1->saveState(kwl, 0); cout << "\n\nSingle image chain rgb reversed kwl\n" << kwl; } cout << "constness test:\n"; ossimRefPtr consSic = sic1.get(); ossimRefPtr ihConst = consSic->getImageHandler().get(); cout << "image handler bands: " << ihConst->getNumberOfOutputBands() << endl; return 0; } #endif ossim-Miami-2.9.1/test/src/imaging/ossim-pixel-flipper-test.cpp000066400000000000000000000130241352751253100244650ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Contains application definition "foo" app. // // NOTE: This is supplied for simple quick test. Makefile links with // libossim so you don't have to muck with that. // DO NOT checkin your test to the svn repository. Simply // edit foo.cc (Makefile if needed) and run your test. // After completion you can do a "svn revert foo.cpp" if you want to // keep your working repository up to snuff. Enjoy! // // $Id: ossim-pixel-flipper-test.cpp 22197 2013-03-12 02:00:55Z dburken $ //---------------------------------------------------------------------------- #include #include #include #include #include #include #include #include #include #include #include using namespace std; static int expected_0[] = {0,0,0,0,255,0,0,255,255,5,5,5,5,255,5,128,255,255}; static int expected_1[] = {11,11,11,11,255,11,11,255,255,11,11,11,11,255,11,128,255,255}; static int expected_2[] = {0,0,0,11,255,11,11,255,255,5,5,5,11,255,11,128,255,255}; static int expected_3[] = {0,0,0,11,11,11,11,11,11,5,5,5,11,11,11,128,255,255}; static int expected_4[] = {11,11,11,0,255,0,0,255,255,11,11,11,5,255,5,128,255,255}; static int expected_5[] = {8,8,8,8,200,8,8,200,200,8,8,8,8,200,8,128,200,200}; static int expected_6[] = {11,11,11,11,11,11,11,11,11,8,8,8,8,200,8,128,200,200}; //************************************************************************************************* void showPixels(const ossimRefPtr tile, const int* expected_values) { int j = 0; for (int i=0; i<6; i++) { int r = (int) tile->getPix(i, 0); int g = (int) tile->getPix(i, 1); int b = (int) tile->getPix(i, 2); // bool correct = true; if ((r==expected_values[j])&&(g==expected_values[j+1])&&(b==expected_values[j+2])) { cout << " PASSED ["<initialize(argc, argv); ossimFilename fname ("PixelFlipperTestChip.tif"); ossimRefPtr handler = ossimImageHandlerRegistry::instance()->open(fname); vector valid_vertices; valid_vertices.push_back(ossimIpt(0,0)); valid_vertices.push_back(ossimIpt(127,0)); valid_vertices.push_back(ossimIpt(127,127)); valid_vertices.push_back(ossimIpt(0,127)); handler->writeValidImageVertices(valid_vertices); // Fetch raw tile: ossimRefPtr flipper = new ossimPixelFlipper(); ossimIrect tile_rect(0,0,127,127); flipper->connectMyInputTo(handler.get()); ossimRefPtr tile = handler->getTile(tile_rect); cout<<"\nRaw Tile:"<setTargetRange(0, 10); flipper->setReplacementValue(11); flipper->setReplacementMode(ossimPixelFlipper::REPLACE_BAND_IF_TARGET); tile = flipper->getTile(tile_rect); cout<<"\nTarget Replacement REPLACE_BAND_IF_TARGET:"<setTargetRange(0, 10); flipper->setReplacementMode(ossimPixelFlipper::REPLACE_BAND_IF_PARTIAL_TARGET); tile = flipper->getTile(tile_rect); cout<<"\nTarget Replacement REPLACE_BAND_IF_PARTIAL_TARGET:"<setTargetRange(0, 10); flipper->setReplacementMode(ossimPixelFlipper::REPLACE_ALL_BANDS_IF_PARTIAL_TARGET); tile = flipper->getTile(tile_rect); cout<<"\nTarget Replacement REPLACE_ALL_BANDS_IF_PARTIAL_TARGET:"<setTargetRange(0, 10); flipper->setReplacementMode(ossimPixelFlipper::REPLACE_ONLY_FULL_TARGETS); tile = flipper->getTile(tile_rect); cout<<"\nTarget Replacement REPLACE_ONLY_FULL_TARGETS:"<setClampValues(8, 200); tile = flipper->getTile(tile_rect); cout<<"\nClamping:"<writeValidImageVertices(valid_vertices); flipper->initialize(); flipper->setClipMode(ossimPixelFlipper::VALID_VERTICES); tile = flipper->getTile(tile_rect); cout<<"\nValid Vertices (with clamping):"< #include #include #include #include #include #include #include #include #include #include /* for exit */ using namespace std; const char* globalData = "OSSIM_RANGE_DOMES 1.0\n" "# ID, Lat, Lon, Hgt, Radius, Classification [, Az_start, Az_end] [, \"Description\"]\n" "1, 25.8607, -80.1343, 0, 20, 1\n" "2, 25.8601, -80.1336, 0, 40, 3, 135, 45, NATO friendly dome\n" "3, 25.8605, -80.1343, 0, 40, 102, 135, 225, 50mm battery threat dome\n" "4, 25.8601, -80.1335, 0, 50, 103, 45, 135\n" "5, 25.8605, -80.1336, 0, 50, 104, 340, 20\n"; const char* lut = "type: ossimIndexToRgbLutFilter \n" "mode: literal \n" "entry0.index: 1 \n" "entry0.color: 48 48 255\n" "entry1.index: 2 \n" "entry1.color: 32 32 255 \n" "entry2.index: 3 \n" "entry2.color: 16 16 255 \n" "entry3.index: 4 \n" "entry3.color: 1 1 255 \n" "entry0.index: 101 \n" "entry0.color: 255 32 32 \n" "entry4.index: 102 \n" "entry4.color: 255 128 1 \n" "entry5.index: 103 \n" "entry5.color: 255 64 1 \n" "entry6.index: 104 \n" "entry6.color: 255 1 1 \n"; const char* TEMP_CSV_FILE = "rdtltest-default.csv"; const char* TEMP_LUT_FILE = "rdtltest-default.lut"; const char* DEFAULT_RESULTS_FILE = "rdtltest-RESULT.tif"; class Executive { public: Executive(ossimArgumentParser& ap); ~Executive(); bool run(); private: ossimFilename m_csvFile; ossimFilename m_lutFile; ossimFilename m_resultsFile; double m_gsd; bool m_saveFiles; }; Executive::Executive(ossimArgumentParser& ap) : m_gsd (1.0), m_saveFiles (false) { // Set the general usage: ossimApplicationUsage* au = ap.getApplicationUsage(); ossimString usageString = ap.getApplicationName(); usageString += " [options]"; au->setCommandLineUsage(usageString); // Set the command line options: au->addCommandLineOption( "--domes ", "Specifies the input range-dome specifications CSV file name."); au->addCommandLineOption( "--gsd ", "Specifies output GSD in meters. Defaults to 1 meter. "); au->addCommandLineOption( "--lut ", "Causes single-band, output range-dome raster to be remapped to the RGB LUT specified in " ". Implies \"--use-lut\" option."); au->addCommandLineOption( "--out ", "Specifies output filename. Defaults to ."); au->addCommandLineOption( "--save", "Prevents temporary domes CSV file and LUT file from being deleted after test so they " "can be used as examples for custom inputs."); au->addCommandLineOption( "--use-lut", "Causes single-band, output range-dome raster to be remapped to default " "range-dome RGB LUT."); if (ap.read("-h") || ap.read("--help")) { ap.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO)); return; } std::string ts1; ossimArgumentParser::ossimParameter sp1(ts1); m_csvFile = TEMP_CSV_FILE; m_resultsFile = DEFAULT_RESULTS_FILE; m_lutFile.clear(); if (ap.read("--gsd", sp1)) m_gsd = ossimString(ts1).toDouble(); if (ap.read("--domes", sp1)) m_csvFile = ts1; if (ap.read("--lut", sp1)) m_lutFile = ts1; if (ap.read("--out", sp1)) m_resultsFile = ts1; if (ap.read("--save")) m_saveFiles = true; if (ap.read("--use-lut")) m_lutFile = TEMP_LUT_FILE; } Executive::~Executive() { if (!m_saveFiles) { if (m_csvFile == TEMP_CSV_FILE) m_csvFile.remove(); if (m_lutFile == TEMP_LUT_FILE) m_lutFile.remove(); } } bool Executive::run() { if (m_resultsFile.empty()) return false; // Output temp datafile if none provided: if (m_csvFile == TEMP_CSV_FILE) { ofstream ofs (m_csvFile.string().c_str(), ios_base::trunc); if (ofs.fail()) { ossimNotify(ossimNotifyLevel_FATAL) << "Could not write out temporary CSV file to CWD. Check permissions." << endl; return false; } ofs << globalData << endl; ofs.close(); } // Use factory to open the RDTS: ossimRefPtr handler = ossimImageHandlerRegistry::instance()->open(m_csvFile); if (!handler.valid()) { ossimNotify(ossimNotifyLevel_FATAL) << "Error encountered instantiating threat dome handler from CSV." << std::endl; return false; } // Set up the range-dome filter chain: ossimRangeDomeTileSource* rdts = dynamic_cast(handler.get()); if (!rdts) { ossimNotify(ossimNotifyLevel_FATAL) << "Error encountered casting handler to ossimRangeDomeTileSource" << std::endl; return false; } ossimConnectableObject* chain_head = rdts; rdts->setGSD(m_gsd); cout<<" numLines = "<< rdts->getNumberOfLines()< lutFilter = new ossimIndexToRgbLutFilter(); lutFilter->connectMyInputTo(chain_head); lutFilter->setLut(m_lutFile); lutFilter->initialize(); chain_head = lutFilter.get(); } // Set up the writer for results file: ossimRefPtr tiffWriter = new ossimTiffWriter(); tiffWriter->connectMyInputTo(chain_head); tiffWriter->setFilename(m_resultsFile); if (!tiffWriter->execute()) { cout << "Could not write results file <"<." << endl; return false; } tiffWriter->close(); tiffWriter = 0; handler = 0; cout<<"\nTest completed. Output written to <"<.\n"<setApplicationName(argv[0]); ossimInit::instance()->initialize(ap); Executive* executive = new Executive(ap); bool success = executive->run(); delete executive; if (!success) exit(1); exit(0); } ossim-Miami-2.9.1/test/src/imaging/ossim-read-write-consistency-test.cpp000066400000000000000000000105751352751253100263170ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-mda-test.cpp // // Author: Oscar Kramer // // Tests MDA format reading and writing. Given an original MDA file, a chain is created // with an MDA reader on the left end and an MDA writer on the right with a simple sequencer // in between. An output file is written to disk then read back in with a new handler instance. // The test is successful only if both handlers are equal (minus the filename). // // $Id$ //---------------------------------------------------------------------------- #include #include #include // ossim contants... #include #include #include // Put your includes here: #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); try { if (argc < 2) ossimException ("Need an input original image filename. Cannot continue."); ossimFilename orig_fname (argv[1]); if (!orig_fname.isReadable()) ossimException ("Filename specified is not readable. Cannot continue."); // Open the original input file using factory (includes plugins) ossimRefPtr handler1 = ossimImageHandlerRegistry::instance()->open(orig_fname); if (!handler1.valid()) ossimException ("Could not open input file. Cannot continue."); handler1->print(cout); //### // Fetch image parameters needed for write: ossimIrect image_rect (handler1->getBoundingRect()); // int num_rlevels = handler1->getNumberOfDecimationLevels(); // Establish a sequencer to loop through all tiles: ossimRefPtr sequencer = new ossimImageSourceSequencer; sequencer->connectMyInputTo(handler1.get()); // Establish an output filename based on the input name: ossimFilename output_fname (orig_fname.noExtension()); output_fname += "-RWTestOut"; output_fname.setExtension(orig_fname.ext()); // Establish the associated writer object using factory scheme. This should pick up the // corresponding writer but no guaranties: ossimRefPtr writer = ossimImageWriterFactoryRegistry::instance()->createWriterFromExtension(output_fname.ext()); if (!writer.valid()) ossimException ("Could not create a writer object for this image file extension. Cannot continue."); // Connect the writer to the chain and write the file: writer->setOutputName(output_fname); writer->connectMyInputTo(sequencer.get()); bool write_successful = writer->execute(); if (!write_successful) ossimException ("Error encountered writing output image. Cannot continue."); // Use the new output file to initialize a new handler to compare against the original handler ossimRefPtr handler2 = ossimImageHandlerRegistry::instance()->open(output_fname); if (!handler2.valid()) ossimException ("Could not open test output file for comparison. Test failed."); // Save the states to KWL -- this is what will be compared. Need to remove the filename // keyword however since that differs: ossimKeywordlist kwl1; handler1->saveState(kwl1); kwl1.removeKeysThatMatch(ossimKeywordNames::FILENAME_KW); ossimKeywordlist kwl2; handler2->saveState(kwl2); kwl2.removeKeysThatMatch(ossimKeywordNames::FILENAME_KW); if (kwl1 == kwl2) { cout << "OSSIM successfully read and wrote image format associated with file <" << orig_fname << ">. Test PASSED." << endl; } else { ossimException ("Differences found between reader and writer. Test FAILED."); } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; return 1; } return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-remap-table-test.cpp000066400000000000000000000230751352751253100241050ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: Test normalized remap table. // //---------------------------------------------------------------------------- // $Id: ossim-remap-table-test.cpp 19751 2011-06-13 15:13:07Z dburken $ #include #include using namespace std; #include // ossim contants... #include #include #include #include int main(int argc, char *argv[]) { cout << setiosflags(std::ios::fixed) << setprecision(15); ossim_float64 n; ossim_int32 p; ossim_int32 i; cout << "//------------------------------------------\n" << "// *** ossimNormalizedS16RemapTable test ***\n" << "//------------------------------------------\n" << endl; ossimNormalizedS16RemapTable s16tbl; i = -32768; while (i < 32768) { n = s16tbl[i]; p = s16tbl.pixFromNorm(n); cout << "idx[" << i << "]: n (" << n << "), p(" << p << ")\n"; ++i; } n = -0.1; p = s16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.0; p = s16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.000000250; // Just above null pixel p = s16tbl.pixFromNorm(n); cout << "Just above null\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.000015250; // Slightly less than -32767 p = s16tbl.pixFromNorm(n); cout << "Slightly less than -32767\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.0000152588; // -32767 p = s16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.000015258; // Slightly bigger than -32767 p = s16tbl.pixFromNorm(n); cout << "Slightly bigger than -32767\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.000030518043793; // -32766 p = s16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.0000305180436; // Slightly to the left of -32766 p = s16tbl.pixFromNorm(n); cout << "Slightly less than -32766\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.5; p = s16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.999984740977; // Slightly less than 32766 p = s16tbl.pixFromNorm(n); cout << "Slightly less than 32766\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.999984740978103; // 32766 p = s16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.99998474098; // Slightly greater than 32766 p = s16tbl.pixFromNorm(n); cout << "Slightly greater than 32766\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.0; p = s16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.1; p = s16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; p = -32768; n = s16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = -32767; n = s16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 0; n = s16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 32766.99999999999; n = s16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 32767; n = s16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 32768; n = s16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; cout << "//------------------------------------------\n" << "// *** ossimNormalizedU16RemapTable test ***\n" << "//------------------------------------------\n" << endl; ossimNormalizedU16RemapTable u16tbl; i = 0; while (i < 65536) { n = u16tbl[i]; p = u16tbl.pixFromNorm(n); cout << "idx[" << i << "]: n (" << n << "), p(" << p << ")\n"; ++i; } n = -0.1; p = u16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.0; p = u16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.001; p = u16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.000000250; // Just above null pixel p = u16tbl.pixFromNorm(n); cout << "Just above null\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.0; p = u16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.1; p = u16tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; p = -1; n = u16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 0; n = u16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 1; n = u16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 65534; n = u16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 65535; n = u16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 65536; n = u16tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; cout << "\n\n//------------------------------------------\n" << "// *** ossimNormalizedU11RemapTable test ***\n" << "//------------------------------------------\n" << endl; ossimNormalizedU11RemapTable u11tbl; i = 0; while (i < 2048) { n = u11tbl[i]; p = u11tbl.pixFromNorm(n); cout << "idx[" << i << "]: n (" << n << "), p(" << p << ")\n"; ++i; } n = -0.1; p = u11tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.0; p = u11tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.00000852; // Just above null pixel p = u11tbl.pixFromNorm(n); cout << "Just above null\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.000; p = u11tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = .000488519785; // Slightly less than 1 p = u11tbl.pixFromNorm(n); cout << "Slightly less than 1\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.000488519785051; // 1 cout << "1\n"; p = u11tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.000488519786; // Slightly bigger than 1 p = u11tbl.pixFromNorm(n); cout << "Slightly bigger than 1\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.9995114802149; // Slightly less than 2046 p = u11tbl.pixFromNorm(n); cout << "Slightly less than 2046\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.999511480214949; // 2046 p = u11tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.999511480215; // Slightly greater than 2046 p = u11tbl.pixFromNorm(n); cout << "Slightly greater than 2046\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.0; p = u11tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.1; p = u11tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; p = -1; n = u11tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 0; n = u11tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 2046; n = u11tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 2047; n = u11tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 2048; n = u11tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; cout << "\n\n//------------------------------------------\n" << "// *** ossimNormalizedU8RemapTable test ***\n" << "//------------------------------------------\n" << endl; ossimNormalizedU8RemapTable u8tbl; i = 0; while (i < 256) { n = u8tbl[i]; p = u8tbl.pixFromNorm(n); cout << "idx[" << i << "]: n (" << n << "), p(" << p << ")\n"; ++i; } n = -0.1; p = u8tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.0; p = u8tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.00000625; // Just above null pixel p = u8tbl.pixFromNorm(n); cout << "Just above null\n"; cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 0.001; p = u8tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.0; p = u8tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.1; p = u8tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.0; p = u8tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; n = 1.1; p = u8tbl.pixFromNorm(n); cout << "pixFromNorm(" << n << "): " << p << "\n"; p = -1; n = u8tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 0; n = u8tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 254; n = u8tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 255; n = u8tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; p = 256; n = u8tbl.normFromPix(p); cout << "normFromPix(" << p << "): " << n << "\n"; return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-shift-filter-test.cpp000066400000000000000000000167061352751253100243170ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // File: ossim-viirs-proc // // Description: Application to extract VIIRS Radiance layer, shifting // min/max linearly to 16 bit space with coarse grid geometry file. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char* argv[]) { int status = 0; // Timer for elapsed time: ossimTimer::instance()->setStartTick(); ossimInit::instance()->initialize(argc, argv); if (argc == 2 ) { ossimFilename inputFile = argv[1]; if ( inputFile.exists() ) { ossimFilename outputFile = inputFile.expand().noExtension(); outputFile.string() += "_1.tif"; if ( inputFile != outputFile ) { std::string command = "ossim-cmm --null -9999.0 --reader-prop layer=/All_Data/VIIRS-DNB-SDR_All/Radiance "; command += inputFile.string(); cout << "Executing command: " << command << endl; status = system( command.c_str() ); if ( status == 0 ) { ossimRefPtr sic = new ossimSingleImageChain(); if ( sic->open( inputFile, false ) ) { cout << "Opened: " << inputFile << endl; // Set the entry to the Radiance layer. ossimRefPtr readerProp = new ossimStringProperty( ossimString("layer"), ossimString("/All_Data/VIIRS-DNB-SDR_All/Radiance") ); sic->getImageHandler()->setProperty( readerProp ); // Add filter to shift/stretch data uint16 range. ossimRefPtr sf = new ossimShiftFilter(); sf->setNullPixelValue( 0.0 ); sf->setMinPixelValue( 1.0 ); sf->setMaxPixelValue( 65535.0 ); sic->addFirst( sf.get() ); // Cast it to uint16: ossimRefPtr cf = new ossimCastTileSourceFilter(0, OSSIM_UINT16 ); sic->addFirst( cf.get() ); // Put a cache in front of resampler. sic->addCache(); // sic->addResampler(); sic->initialize(); // Write image: ossimRefPtr writer = new ossimTiffWriter(); if ( writer->open( outputFile ) ) { // Turn on overviews and histograms: writer->setWriteOverviewFlag( true ); writer->setWriteHistogramFlag( true ); // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); writer->connectMyInputTo(0, sic.get()); ossimIrect rect = writer->getAreaOfInterest(); writer->execute(); cout << "Wrote file: " << outputFile << endl; ossimRefPtr ih = sic->getImageHandler(); if ( ih.valid() ) { //--- // If there is a coarse grid model write it out so the // oqutput file will pick it up. //--- ossimRefPtr geom = sic->getImageHandler()-> getImageGeometry(); if ( geom.valid() ) { ossimRefPtr proj = geom->getProjection(); if ( proj.valid() ) { ossimRefPtr cg = dynamic_cast( proj.get() ); if ( cg.valid() ) { ossimFilename geomFile = outputFile.noExtension(); geomFile.string() += ".geom"; // this saves geom file as well cg->saveCoarseGrid( geomFile ); cout << "Wrote file: " << geomFile << endl; } } } //--- // If the image handler is a metadata interface pass the metadata // to the dot.omd file and rewrite it. //--- ossimMetadataInterface* mdi = dynamic_cast( ih.get() ); if ( mdi ) { ossimFilename omdFile = outputFile.noExtension(); omdFile += ".omd"; ossimRefPtr kwl = new ossimKeywordlist(); if ( omdFile.exists() ) { kwl->addFile( omdFile ); } std::string prefix = ""; mdi->addMetadata( kwl.get(), prefix ); kwl->write( omdFile.c_str() ); cout << "Wrote file: " << omdFile << endl; } } } else { cerr << "Could not open: " << outputFile << endl; } } } } else // Matches: { cerr << "Input file is same as output file! Returning..." << endl; status = -1; } } else // Match: if ( inputFile.exists() ){ ... } { cerr << "Input file does not exists!" << endl; status = -1; } } else // Matches: if (argc == 2 ){ ... } { cout << argv[0] << " " << "\n\nExtracts VIIRS Radiance layer from hdf5 file, shifting min/max " << "linearly to 16 bit space with coarse grid geometry file.\n" << endl; } cout << "Elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; return status; } ossim-Miami-2.9.1/test/src/imaging/ossim-single-image-chain-test.cpp000066400000000000000000000123571352751253100253360ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test application for ossimSingleImageChain class. // //---------------------------------------------------------------------------- // $Id: ossim-single-image-chain-test.cpp 22531 2013-12-28 18:13:34Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char* argv[]) { ossimTimer::instance()->setStartTick(); ossimInit::instance()->initialize(argc, argv); ossimTimer::Timer_t t1 = ossimTimer::instance()->tick(); cout << "elapsed time after initialize(ms): " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; if (argc < 2) { cout << argv[0] << " " << "\nOpens up single image chain and dumps the state to keyword" << " list." << endl; return 0; } ossimRefPtr sic1 = new ossimSingleImageChain(); if ( sic1->open( ossimFilename(argv[1]) ) ) { // Set up chain: if ( sic1->getImageHandler()->getNumberOfOutputBands() == 4 ) { // Just guessing... sic1->setThreeBandReverseFlag(true); } // Always have resampler cache. sic1->setAddResamplerCacheFlag(true); // Histogram: sic1->setAddHistogramFlag(true); sic1->createRenderedChain(); // Histogram stretch: if ( sic1->openHistogram(ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX) == false ) { cout << "Could not do histogram stretch!" << endl; } if (argc == 3) { // Write image: ossimRefPtr writer = new ossimTiffWriter(); if ( writer->open( ossimFilename(argv[2]) ) ) { cout << "Outputting file: " << ossimFilename(argv[2]) << endl; // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); writer->connectMyInputTo(0, sic1.get()); writer->execute(); ossimTimer::Timer_t t2 = ossimTimer::instance()->tick(); cout << "elapsed time after write(ms): " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; cout << "write time minus initialize: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->delta_s(t1, t2) << "\n"; } } ossimRefPtr geom = sic1->getImageGeometry(); if (geom.valid()) { geom->print(cout); } // Test the load state. ossimKeywordlist kwl; sic1->saveState(kwl, 0); ossimSingleImageChain* sic2 = new ossimSingleImageChain(); sic2->loadState(kwl, 0); kwl.clear(); sic2->saveState(kwl, 0); cout << "\n\nSingle image chain from load state kwl\n" << kwl; } // Create a normal chain. sic1 = new ossimSingleImageChain(false, // null flip true, // addHistogramFlag true, // addResamplerCacheFlag true, // addChainCacheFlag false, // remapToEightBitFlag false, // threeBandFlag false); // threeBandReverseFlag if ( sic1->open( ossimFilename(argv[1]) ) ) { sic1->createRenderedChain(); ossimKeywordlist kwl; sic1->saveState(kwl, 0); cout << "\n\nNormal single image chain kwl\n" << kwl; } // Create a stripped down chain. sic1 = new ossimSingleImageChain(); if ( sic1->open( ossimFilename(argv[1]) ) ) { sic1->createRenderedChain(); ossimKeywordlist kwl; sic1->saveState(kwl, 0); cout << "\n\nSingle image chain stripped down kwl\n" << kwl; } // Create a rgb reversed chain. sic1 = new ossimSingleImageChain(); if ( sic1->open( ossimFilename(argv[1]) ) ) { sic1->setThreeBandReverseFlag(true); sic1->createRenderedChain(); ossimKeywordlist kwl; sic1->saveState(kwl, 0); cout << "\n\nSingle image chain rgb reversed kwl\n" << kwl; } cout << "constness test:\n"; ossimRefPtr consSic = sic1.get(); ossimRefPtr ihConst = consSic->getImageHandler(); cout << "image handler bands: " << ihConst->getNumberOfOutputBands() << endl; return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-single-image-chain-threaded-test.cpp000066400000000000000000000061401352751253100271050ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File: ossim-single-image-chain-threaded-test.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test application for ossimSingleImageChain with a // ossimMultiThreadSequencer. // //---------------------------------------------------------------------------- // $Id: ossim-single-image-chain-threaded-test.cpp 20269 2011-11-18 15:40:56Z dburken $ #include using namespace std; #include #include #include #include #include #include #include #include #include int main(int argc, char* argv[]) { ossimTimer::instance()->setStartTick(); ossimInit::instance()->initialize(argc, argv); ossimTimer::Timer_t t1 = ossimTimer::instance()->tick(); cout << "elapsed time after initialize(ms): " << ossimTimer::instance()->time_s() << "\n"; if (argc < 4) { cout << argv[0] << " " << "\nOpens up single image chain and writes to output_file using N threads." << " list.\nNOTE: Hard wired tiff writer; hence, the output_file.tif." << endl; return 0; } ossim_uint32 threads = ossimString(argv[1]).toUInt32(); if ( threads == 0 ) { threads = ossim::getNumberOfThreads(); } ossimFilename image_file = argv[2]; ossimFilename output_file = argv[3]; cout << "threads: " << threads << "\nimage_file: " << image_file << "\noutput_file: " << output_file << "\n"; ossimRefPtr sic1 = new ossimSingleImageChain(); if ( sic1->open( image_file ) ) { sic1->createRenderedChain(); // Establish the MT sequencer: ossimRefPtr mts = new ossimMultiThreadSequencer( sic1.get(), threads ); ossimRefPtr writer = new ossimTiffWriter(); writer->changeSequencer( mts.get() ); if ( writer->open( output_file ) ) { // Add a listener to get percent complete. ossimStdOutProgress prog(0, true); writer->addListener(&prog); // Connect the chain to writer. writer->connectMyInputTo(0, sic1.get()); // Write the file. writer->execute(); ossimTimer::Timer_t t2 = ossimTimer::instance()->tick(); cout << "elapsed time after write(ms): " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; cout << "write time minus initialize: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->delta_s(t1, t2) << "\n"; } } return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-threaded-app-tile-cache-test.cpp000066400000000000000000000113551352751253100262440ustar00rootroot00000000000000#include /* for exit */ #include #include #include #include #include #include #include #include #include #include #include #include #include std::shared_ptr startBarrier; std::shared_ptr endBarrier; class TileCacheThread : public ossim::Thread { public: TileCacheThread(const ossimString& threadName="", const ossimIpt& regionSize=ossimIpt(4096,4096), const ossimIpt& tileSize=ossimIpt(64,64)) :m_threadName(threadName), m_regionSize(regionSize), m_tileSize(tileSize), m_cacheId(-1) { } virtual void run() { startBarrier->block(); m_cacheId = ossimAppFixedTileCache::instance()->newTileCache(); ossimAppFixedTileCache::instance()->setRect(m_cacheId,ossimIrect(0,0,m_regionSize.x-1, m_regionSize.y-1)); ossimAppFixedTileCache::instance()->setTileSize(m_cacheId, m_tileSize); ossimIpt origin; ossim_int32 x; ossim_int32 y; for(y = 0; y < m_regionSize.y;y+=m_tileSize.y) { for(x = 0; x < m_regionSize.x;x+=m_tileSize.x) { ossimRefPtr data = new ossimImageData(0, OSSIM_UINT8, 3, m_tileSize.x, m_tileSize.y); data->setImageRectangle(ossimIrect(x,y,x+(m_tileSize.x-1), y+(m_tileSize.y-1))); data->initialize(); ossimAppFixedTileCache::instance()->addTile(m_cacheId, data.get()); } } for(y = 0; y < m_regionSize.y;y+=m_tileSize.y) { for(x = 0; x < m_regionSize.x;x+=m_tileSize.x) { origin.x = x; origin.y = y; ossimRefPtr tempTile = ossimAppFixedTileCache::instance()->getTile(m_cacheId, origin); if(!tempTile.valid()) { std::cout << "TILE not found in cache, THIS MESSAGE SHOULD NEVER HAPPEN!!!" << std::endl; } } } ossimAppFixedTileCache::instance()->deleteCache(m_cacheId); // let all threads end at the same time std::cout << "THREAD FINISHED: " << m_threadName << std::endl; endBarrier->block(); m_cacheId = -1; } ossimString m_threadName; ossimIpt m_regionSize; ossimIpt m_tileSize; ossimAppFixedTileCache::ossimAppFixedCacheId m_cacheId; }; int main(int argc, char* argv[]) { ossimString tempString; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser argumentParser(&argc, argv); //ossimInit::instance()->addOptions(argumentParser); ossimInit::instance()->initialize(argumentParser); ossimAppFixedTileCache::instance()->setMaxCacheSize(1024*1024*1024); ossim_uint32 threads = 10; argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); argumentParser.getApplicationUsage()->addCommandLineOption("--threads","Specify the number of threads to test simultaneus access to elevation"); // argumentParser.getApplicationUsage()->addCommandLineOption("--random-seed", "value to use as the seed for the random elevation post generator"); if (argumentParser.read("-h") || argumentParser.read("--help")) { argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_WARN)); exit(0); } if(argumentParser.read("--threads", stringParam)) { threads = tempString.toUInt32(); } std::vector threadList(threads); startBarrier = std::make_shared(threads+1); // include the main thread for synching endBarrier = std::make_shared(threads+1); // include the main thread for synching ossim_uint32 idx = 0; for(idx = 0; idx < threads; ++ idx) { threadList[idx] = new TileCacheThread("Thread " + ossimString::toString(idx)); threadList[idx]->start(); } ossimTimer::Timer_t t1 = ossimTimer::instance()->tick(); // synch all threads to start at the same time startBarrier->block(); std::cout << "Number of threads: " << threads << "\n"; endBarrier->block(); std::cout << "All threads finished\n"; ossimTimer::Timer_t t2 = ossimTimer::instance()->tick(); std::cout << "Time elapsed: " << ossimTimer::instance()->delta_s(t1, t2) << " seconds" << "\n"; return 0; } ossim-Miami-2.9.1/test/src/imaging/ossim-threaded-chain-test.cpp000066400000000000000000000214021352751253100245440ustar00rootroot00000000000000//************************************************************************************************** // OSSIM -- Open Source Software Image Map // // License: See top level LICENSE.txt file. // // Authors: Oscar Kramer, David Burken // // Description: Test code for multi-threaded sequencer and associated logic. // // $Id$ //************************************************************************************************** #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //************************************************************************************************** // USAGE: ossim-threaded-chain-test //************************************************************************************************** int main(int argc, char *argv[]) { ossimTimer::instance()->setStartTick(); ossimArgumentParser ap(&argc, argv); ossimInit::instance()->initialize(ap); unsigned int tempUint; ossimArgumentParser::ossimParameter uintParam(tempUint); ossimMtDebug* mt_debug = ossimMtDebug::instance(); bool chainCacheEnabled=false; if (ap.read("--chain-cache")) chainCacheEnabled = true; if (ap.read("--handler-cache")) mt_debug->handlerCacheEnabled = true; if (ap.read("--faux-input")) mt_debug->handlerUseFauxTile = true; if (ap.read("--shared-handler")) mt_debug->chainSharedHandlers = true; if (ap.read("--seq-debug")) mt_debug->seqDebugEnabled = true; if (ap.read("--timer")) mt_debug->seqMetricsEnabled = true; if (ap.read("--tblocks", uintParam)) mt_debug->seqTimedBlocksDt = tempUint; if (ap.read("--cache-size", uintParam)) mt_debug->maxTileCacheSize = tempUint; // Parse command line " ": if (argc < 2) { cout << "\n "<< argv[0] << " [options] []\n" << "\n Opens up single image chain and writes to output_file using N threads." << "\n If N=0, this indicates a conventional (unthreaded) sequencer will be used." << "\n If no output file is specified, the processed tiles are dumped on the floor." << "\n Only TIFF file output is supported." << "\n" << "\n Options:" << "\n --threads Must be nonzero for multi-threading sequencer" << "\n --shared-handler Enable shared handlers" << "\n --handler-cache Adds cache to handler adaptor (valid only with shared handler)" << "\n --chain-cache Inserts cache source in the image chain" << "\n --faux-input Use faux input tiles" << "\n --seq-debug Enable sequencer debug" << "\n --timer Enable sequencer timing metrics" << "\n --tblocks Enable timed blocks at specified interval" << "\n --cache-size Specify the max tile cache factor in sequencer" << endl; return 0; } double t1 = (double)ossimTimer::instance()->time_m()/1000.0; ossim_uint32 num_threads = 0; if (ap.read("--threads", uintParam)) num_threads = tempUint; ossimFilename image_file = argv[1]; ossimFilename output_file; if (argc > 2) output_file = argv[2]; // Create original chain: ossimRefPtr singleImageChain = new ossimSingleImageChain(false, false, chainCacheEnabled, false, false, false, false); if (!singleImageChain->open(image_file)) { cout<<"\nUnable to open image file at <"<. Aborting..."<createRenderedChain(); ossimRefPtr renderer = singleImageChain->getImageRenderer(); if (renderer.valid()) renderer->getResampler()->setFilterType(ossimFilterResampler::ossimFilterResampler_GAUSSIAN); ossimIrect rect = singleImageChain->getBoundingRect(); // Create complex chain of chains: ossimRefPtr product_chain = new ossimImageChain; ossimRefPtr mosaicObject = new ossimImageMosaic; mosaicObject->connectMyInputTo(singleImageChain.get()); singleImageChain->changeOwner(mosaicObject.get()); product_chain->addFirst(mosaicObject.get()); // Make sequencer: ossimRefPtr mts = 0; ossimRefPtr seq = 0; ossimRefPtr writer = 0; const char* noyes[2]={"no","yes"}; if (num_threads > 0) { // Establish the MT sequencer: mts = new ossimMultiThreadSequencer(product_chain.get(), num_threads); seq = mts.get(); cout<<"\nUsing multi-threaded sequencer..." << "\n Input file: " << image_file << "\n Output file: " << output_file << "\n Number of threads: " << num_threads << "\n Using faux input tiles: " << noyes[(int)mt_debug->handlerUseFauxTile] << "\n Using shared handler: " << noyes[(int)mt_debug->chainSharedHandlers] << "\n Using handler cache: " << noyes[(int)mt_debug->handlerCacheEnabled] << "\n Using chain cache: " << noyes[(int)chainCacheEnabled]; if ( mt_debug->seqTimedBlocksDt > 0) cout<< "\n Using timed blocks: yes (" << mt_debug->seqTimedBlocksDt<<" ms)"; else cout<< "\n Using timed blocks: no"; cout<<"\n Sequencer cache size: " << mts->maxCacheSize() << endl; } else { cout<<"\nUsing conventional (unthreaded) sequencer..." << "\n Input file: " << image_file << "\n Output file: " << output_file<setToStartOfSequence(); ossim_uint32 num_tiles = seq->getNumberOfTiles(); ossim_uint32 show_every_n = num_tiles/20; ossim_uint32 percent_complete = 0; ossim_uint32 n = 0; cout << " 0% \r"<getNextTile(); if (++n >= show_every_n) { percent_complete += 5; cout << " "<connectMyInputTo(product_chain.get()); writer->setOutputName(output_file); writer->changeSequencer( seq.get() ); if ( !writer->open( output_file ) ) { cout<<"\nUnable to create output file at <"<. Aborting..."<addListener(&prog); // Write the file: double writeStartTime = ossimTimer::instance()->time_s(); writer->execute(); double writeStopTime = ossimTimer::instance()->time_s(); double writeTime = writeStopTime - writeStartTime; double bps = ((ossim_uint64)output_file.fileSize())/writeTime; double megaBytePerSecond = bps / ((double) 1024*1024); cout << " Write MB per second: " << setprecision(3) << megaBytePerSecond << endl; } double t2 = (double)ossimTimer::instance()->time_m()/1000.0; if (mts.valid()) { cout << " Max cache used: "<< mts->d_maxCacheUsed << endl; cout << " Cache emptied count: "<< ossimString::toString(mts->d_cacheEmptyCount) << endl; } cout << setprecision(3); if (mts.valid()) { double jgtt = mts->d_jobGetTileT; double jgttpj = jgtt/num_threads; cout << " Time waiting on jobs: "<d_idleTime2<<" s"<d_idleTime5<<" s"<handlerGetTileT()<<" s"< #include #include #include #include //************************************************************************************************** // MAIN MODULE // See ossimBatchTest.cpp for usage, or run executable with no args for usage. // Returns: // -1 if any error occurred during test // 1 if any test failed // 0 if all tests passed //************************************************************************************************** int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); ossimApplicationUsage* au = ap.getApplicationUsage(); au->setDescription( "This application is used for functional testing of OSSIM components. The tests are" "\nspecified within the configuration file passed in. The following status codes are" "\nreturned on exit:\n" "\n 0 Test passed" "\n 1 No test performed (disabled)" "\n 2 Problem encountered during test initialization." "\n 3 Error occurred during test execution." "\n 4 Test ran but failed.\n" "\nFor enabling individual tests, you can edit the \"enabled\" flag in the configuration" "\nfile or use the \"-r\" options described below. "); au->setCommandLineUsage(ap.getApplicationName()+" "); int return_status = 0; ossimBatchTest obt; if (!obt.initialize(ap)) { return_status = 2; } else { ossim_uint8 status = obt.execute(); // Bitwise and ops to isolate status bits (see ossimBatchTest.h for bit definitions) if (status == ossimBatchTest::TEST_TBD) return_status = 1; // nothing was done else if (status & ossimBatchTest::TEST_ERROR) return_status = 3; // an error occurred running a command else if (status & ossimBatchTest::TEST_FAILED) return_status = 4; // A test failed post-processing (diff) else return_status = 0; // Everything passed } return return_status; } ossim-Miami-2.9.1/test/src/ossim-foo.cpp000066400000000000000000000033001352751253100200740ustar00rootroot00000000000000//--- // // License: MIT // // File: ossim-foo.cpp // // Description: Contains application definition "ossim-foo" app. // // NOTE: This is supplied for simple quick test. DO NOT checkin your test to // the svn repository. Simply edit ossim-foo.cpp and run your test. // After completion you can do a "git checkout -- ossimfoo.cpp" if // you want to keep your working repository up to snuff. // // $Id$ //--- // System includes: #include #include #include #include #include #include #include // Put your includes here: using namespace std; int main(int argc, char *argv[]) { struct U { union { uint64_t u64; int32_t u32[2]; float f32[2]; char valueChars[8]; }; }; stringstream iostr; U u1; U u2; u1.f32[0] = 0.1; u1.f32[1] = 0.2; //iostr<>hex>>setw(16)>>u2.u64; iostr.write(reinterpret_cast(&u1.f32[0]), sizeof(float)); iostr.write(reinterpret_cast(&u1.f32[1]), sizeof(float)); float f1, f2; iostr.read(reinterpret_cast(&u2.u64), sizeof(uint64_t)); int32_t i1 = ((u2.u64>>32) & 0xffffffff); int32_t i2 = (u2.u64 & 0xffffffff); memcpy(&f1, &i1, sizeof(float)); memcpy(&f2, &i2, sizeof(float)); cout< #include using namespace std; #include #include #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); cout << "running ossim::isnan test..." << endl; double d = ossim::nan(); if (ossim::isnan(d)) { cout << "ossim::isnan test passed..." << endl; } else { cout << "ossim::isnan test failed..." << endl; } cout << "running ossimEnvironmentUtility test..." << "\ngetUserDir(): " << ossimEnvironmentUtility::instance()->getUserDir() << "\ngetUserName(): " << ossimEnvironmentUtility::instance()->getUserName() << "\ngetUserOssimSupportDir(): " << ossimEnvironmentUtility::instance()->getUserOssimSupportDir() << "\ngetUserOssimPreferences(): " << ossimEnvironmentUtility::instance()->getUserOssimPreferences() << "\ngetUserOssimPluginDir()" << ossimEnvironmentUtility::instance()->getUserOssimPluginDir() << "\ngetInstalledOssimSupportDir(): " << ossimEnvironmentUtility::instance()->getInstalledOssimSupportDir() << "\ngetInstalledOssimPluginDir(): " << ossimEnvironmentUtility::instance()->getInstalledOssimPluginDir() << "\ngetInstalledOssimPreferences(): " << ossimEnvironmentUtility::instance()->getInstalledOssimPreferences() << "\ngetCurrentWorkingDir(): " << ossimEnvironmentUtility::instance()->getCurrentWorkingDir() << endl; cout << "ossim::round<> test:"; ossim_float64 f1 = 8.193933404085605; cout << std::setiosflags(ios::fixed) << std::setprecision(15) << "\nf1: " << f1; f1 = ossim::round(f1 / 0.000005359188182); cout << std::setiosflags(ios::fixed) << std::setprecision(15) << "\nossim::round(d / 0.000005359188182): " << f1; return 0; } ossim-Miami-2.9.1/test/src/parallel/000077500000000000000000000000001352751253100172555ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/parallel/CMakeLists.txt000066400000000000000000000002701352751253100220140ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ OSSIM_SETUP_APPLICATION(ossim-jobqueue-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-jobqueue-test.cpp) ossim-Miami-2.9.1/test/src/parallel/ossim-jobqueue-test.cpp000066400000000000000000000040721352751253100237100ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include static const int INITIAL_THREADS = 10; static const int INITIAL_JOBS = 20; class ossimTestJob : public ossimJob { public: ossimTestJob(const ossimString& name) :ossimJob() { setName(name); } protected: virtual void run() { } }; class ossimTestJobCallback : public ossimJobCallback { public: ossimTestJobCallback() { } virtual void started(std::shared_ptr job) { std::cout << "I HAVE STARTED THE Job " << job->name() << "\n"; } virtual void finished(std::shared_ptr job) { std::cout << "I HAVE FINISHED THE Job " << job->name() << "\n"; } virtual void canceled(std::shared_ptr job) { std::cout << "I HAVE CANCELED THE Job " << job->name() << "\n"; } }; int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); std::shared_ptr q = std::make_shared(); std::shared_ptr threadQueue = std::make_shared(q, INITIAL_THREADS); std::shared_ptr callback = std::make_shared(); ossim_uint32 idx = 0; for(idx = 0; idx < INITIAL_JOBS; ++idx) { std::shared_ptr job = std::make_shared(ossimString::toString(idx+1)); job->setCallback(callback); job->ready(); q->add(job); } // FOREVER loop until all jobs are completed. while(true) { ossim::Thread::sleepInMicroSeconds(250); if ( threadQueue->hasJobsToProcess() == false ) { break; } ossim::Thread::yieldCurrentThread(); } return 0; } ossim-Miami-2.9.1/test/src/point_cloud/000077500000000000000000000000001352751253100200005ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/point_cloud/CMakeLists.txt000066400000000000000000000005531352751253100225430ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ OSSIM_SETUP_APPLICATION(ossim-point-cloud-handler-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-point-cloud-handler-test.cpp) OSSIM_SETUP_APPLICATION(ossim-point-cloud-image-handler-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-point-cloud-image-handler-test.cpp) ossim-Miami-2.9.1/test/src/point_cloud/ossim-point-cloud-handler-test.cpp000066400000000000000000000047661352751253100264760ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // Description: Unit test application for WKT Projection Factory. // // $Id$ //---------------------------------------------------------------------------- #include #include #include #include using namespace std; #include #include #include #include int main(int argc, char* argv[]) { cout << "ossim-point-cloud-handler Test:" << endl; ossimInit::instance()->initialize(argc, argv); if (argc < 2) { cout << "Missing input point-cloud data file name.\n" << "Usage: " << argv[0] << " []" << endl; return -1; } ossimFilename fname (argv[1]); bool genDatFile = false; ofstream outStream; if (argc > 2) { outStream.open(argv[2]); genDatFile = true; } cout << " Testing open() via factory registry... "; cout.flush(); ossimPointCloudHandlerRegistry* factory = ossimPointCloudHandlerRegistry::instance(); ossimPointCloudHandler* handler = factory->open(fname); assert(handler); cout << " Passed.\n"; cout << " Testing getPoints()... "<getPointId(); position = points[i]->getPosition(); outStream << position << endl; } checksum += points[i]->getField(ossimPointRecord::Intensity); } cout << " Intensity checksum for block "< #include #include #include using namespace std; #include #include #include #include int main(int argc, char* argv[]) { cout << "ossim-point-cloud-image-handler Test:" << endl; ossimInit::instance()->initialize(argc, argv); if (argc != 2) { cout << "Missing input point-cloud data file name.\n" << "Usage: " << argv[0] << " " << endl; return -1; } ossimFilename fname (argv[1]); cout << " Testing open() via image handler registry... "; cout.flush(); ossimImageHandlerRegistry* registry = ossimImageHandlerRegistry::instance(); ossimRefPtr iHandler = registry->open(fname, true, true); ossimPointCloudImageHandler* pciHandler = dynamic_cast(iHandler.get()); assert(pciHandler); cout << " Passed.\n"; cout << " Testing getImageGeometry()... "; cout.flush(); ossimRefPtr igeom = iHandler->getImageGeometry(); assert(igeom.valid() && igeom->hasProjection()); cout << " Passed.\n"; ossimRefPtr seq = new ossimImageSourceSequencer (iHandler.get()); seq->initialize(); seq->setToStartOfSequence(); int numTiles = seq->getNumberOfTiles(); cout << "Number of Tiles: "<getNumberOfTilesHorizontal()<getNumberOfTilesVertical()< tile = seq->getNextTile(); if (!tile.valid()) break; //ossim_uint32 numBandsIn = pciHandler->getNumberOfInputBands(); //ossim_uint32 numBandsOut = tile->getNumberOfBands(); //const ossim_float64* minpix = tile->getMinPix(); //const ossim_float64* maxpix = tile->getMaxPix(); if (count == 20) break; } cout << " Passed.\n"; seq = 0; igeom = 0; iHandler = 0; return 0; } ossim-Miami-2.9.1/test/src/projection/000077500000000000000000000000001352751253100176355ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/projection/CMakeLists.txt000066400000000000000000000021441352751253100223760ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ OSSIM_SETUP_APPLICATION(ossim-epsg-factory-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-epsg-factory-test.cpp) OSSIM_SETUP_APPLICATION(ossim-eq-projection-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-eq-projection-test.cpp) OSSIM_SETUP_APPLICATION(ossim-image-geometry-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-image-geometry-test.cpp) OSSIM_SETUP_APPLICATION(ossim-nitf-rsm-model-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-nitf-rsm-model-test.cpp) OSSIM_SETUP_APPLICATION(ossim-projection-factory-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-projection-factory-test.cpp) OSSIM_SETUP_APPLICATION(ossim-projection-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-projection-test.cpp) OSSIM_SETUP_APPLICATION(ossim-wkt-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-wkt-test.cpp) OSSIM_SETUP_APPLICATION(ossim-wkt-proj-factory-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-wkt-proj-factory-test.cpp) ossim-Miami-2.9.1/test/src/projection/ossim-epsg-factory-test.cpp000066400000000000000000000070351352751253100250560ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-epsg-factory-test.cpp // // Author: Oscar Kramer // // Description: Contains test of EPSG projection factory functionality // // NOTE: Returns 0 on success, 1 on failure. Outputs test results to stdout. // // $Id: ossim-epsg-factory-test.cpp 19751 2011-06-13 15:13:07Z dburken $ //---------------------------------------------------------------------------- #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); bool passed = true; try { ossimEpsgProjectionFactory* factory = ossimEpsgProjectionFactory::instance(); ossimRefPtr proj = 0; ossimString code = "EPSG:2236"; // "NAD83 / Florida East (ftUS)" proj = dynamic_cast(factory->createProjection(code)); if (proj.valid() && (proj->getProjectionName()=="ossimTransMercatorProjection")) cout << "\nPASSED for code <"<"<"<(factory->createProjection(name)); if (proj.valid() && (proj->getPcsCode() == 2283)) cout << "\nPASSED for name <"<"<"<(factory->createProjection(name)); if (proj.valid() && (proj->getPcsCode() == 2777)) cout << "\nPASSED for name <"<"<"<(factory->createProjection(name)); if (proj.valid() && (proj->getPcsCode() == 32146)) cout << "\nPASSED For name <"<"<"<(factory->createProjection(name)); if (proj.valid() && (proj->getPcsCode() == 26929)) cout << "\nPASSED for name <"<"<"<setPcsCode(0); ossim_uint32 lookup = proj->getPcsCode(); if ((lookup == 26929) || (lookup == 3465)) cout<<"\nPASSED PCS code lookup."< #include using namespace std; int main(int argc, char *argv[]) { ossimGpt gpt_ul (38.0, -77.0); ossimDpt ipt_ul (0.0, 0.0); ossimDpt ipt_lr (255.0, 255.0); ossimGpt gpt; ossimDpt gsd; ossimEquDistCylProjection proj; proj.setUlTiePoints(gpt_ul); proj.setDecimalDegreesPerPixel(ossimDpt(0.0000090,0.0000090)); cout << "\n Normal initialization ***************"< #include #include #include #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #include #include // Points in one direction. If 5, will get 5X5 or 25. static const ossim_int32 POINTS = 5; static std::string getDate() { // Get the build date in the format of (yyyymmdd). char s[9]; s[8] = '\0'; time_t t; time(&t); tm* lt = localtime(&t); strftime(s, 9, "%Y%m%d", lt); std::string date = s; return date; } static void usage() { cout << "ossimGeometryTest " << "\nTest image geometry." << endl; } static const ossim_uint32 W = 14; static void print(const std::string& prefix, const ossimDpt& ipt, const ossimGpt& wpt, const ossimDpt& rpt) { ossimDpt delta = ipt - rpt; ossim_uint32 w = (prefix.size() < W) ? (W - prefix.size()) : prefix.size(); cout << std::setfill(' ') << setiosflags(ios::left) << prefix << std::setw(w) << "ipt:" << ipt.toString().c_str() << "\n" << prefix << std::setw(w) << "wpt:" << wpt.toString().c_str() << "\n" << prefix << std::setw(w) << "rpt:" << rpt.toString().c_str() << "\n" << prefix << std::setw(w) << "delta:" << delta.toString() << "\n\n"; } int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if (argc != 2) { usage(); return 0; } ossimFilename imageFile = argv[argc - 1]; if ( !imageFile.exists() ) { usage(); return 1; } // Open up an image handler. ossimRefPtr ih = (ossimImageHandler*)ossimImageHandlerRegistry::instance()->open( ossimFilename(argv[argc - 1])); if ( !ih ) { cerr << "Could not open: " << imageFile << endl; return 1; } cout << "image_file: " << imageFile << "\n"; // cout << "date_yyyymmdd: " << getDate().c_str() << "\n"; // Get the entry list: std::vector entryList; ih->getEntryList(entryList); std::vector::const_iterator entry = entryList.begin(); while ( entry != entryList.end() ) { cout << "entry_index: " << (*entry) << "\n"; ih->setCurrentEntry( (*entry) ); ossimRefPtr geom = ih->getImageGeometry(); if ( geom.valid() ) { #if 1 /* Comment out to disable elevation for map projections. */ ossimRefPtr proj = geom->getProjection(); if (proj.valid() ) { ossimRefPtr mp = PTR_CAST(ossimMapProjection, proj.get()); if (mp.valid()) { cout << "setting elev lookup flag..." << endl; mp->setElevationLookupFlag(true); } } #endif ossimKeywordlist kwl; geom->saveState(kwl, 0); cout << kwl << "\n"; ossimDrect rect = ih->getImageRectangle(0); cout << "image_rect: " << rect << "\n\n"; // Do forward, inverse, forward on corners and center. std::string prefix; ossimDpt ipt; // image point ossimDpt rpt; // round trip image point ossimGpt wpt; // world point // Upper left: prefix = "ul."; ipt = rect.ul(); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); // Upper right: prefix = "ur."; ipt = rect.ur(); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); // Lower right: prefix = "lr."; ipt = rect.lr(); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); // Lower left: prefix = "ll."; ipt = rect.ll(); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); // center: prefix = "center."; ipt = rect.midPoint(); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); geom->setTargetRrds(2); cout << "geometry target rrds set to: " << geom->getTargetRrds() << "\n\n"; // Upper left: prefix = "ul-r2."; geom->rnToRn(rect.ul(), 0, 2, ipt); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); // Upper right: prefix = "ur-r2."; geom->rnToRn(rect.ur(), 0, 2, ipt); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); // Lower right: prefix = "lr-r2."; geom->rnToRn(rect.lr(), 0, 2, ipt); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); // Lower left: prefix = "ll-r2."; ipt = rect.ll(); geom->rnToRn(rect.ll(), 0, 2, ipt); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); // center: prefix = "center-r2."; ipt = rect.midPoint(); geom->rnToRn(ipt, 0, 2, ipt); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(prefix, ipt, wpt, rpt); // Test rnToWorld and world to rn: cout << "testing rnToWorld and worldToRn:\n\n"; prefix = "center-r3."; ipt = rect.midPoint(); geom->rnToRn(ipt, 0, 3, ipt); geom->rnToWorld(ipt, 3, wpt); geom->worldToRn(wpt, 3, rpt); print(prefix, ipt, wpt, rpt); geom->setTargetRrds(0); cout << "geometry target rrds set to: " << geom->getTargetRrds() << "\n\n"; prefix = "center-r3."; ipt = rect.midPoint(); geom->rnToRn(ipt, 0, 3, ipt); geom->rnToWorld(ipt, 3, wpt); geom->worldToRn(wpt, 3, rpt); print(prefix, ipt, wpt, rpt); ossim_int32 tenthW = rect.width() / POINTS; ossim_int32 tenthH = rect.height() / POINTS; ossim_int32 offW = tenthW / 2; ossim_int32 offH = tenthH / 2; ossimIpt ul = rect.ul(); ossimIpt lr = rect.lr(); ossim_int32 ptIndex = 0; // Line loop: for (ossim_int32 y = ul.y+offH; y < lr.y; y += tenthH) { ipt.y = y; // Sample loop: for (ossim_int32 x = ul.x+offW; x < lr.x; x += tenthW) { ipt.x = x; std::ostringstream s; s << std::setfill('0') << setiosflags(ios::right) << "pt" << std::setw(3) << ptIndex << "."; prefix = s.str(); geom->localToWorld(ipt, wpt); geom->worldToLocal(wpt, rpt); print(s.str(), ipt, wpt, rpt); ++ptIndex; } } // Test the decimationFactors method. ossim_uint32 level; std::vector decimations; geom->decimationFactors(decimations); for (level = 0; level < decimations.size(); ++level) { ossimNotify(ossimNotifyLevel_DEBUG) << "decimation[" << level << "]: " << decimations[level] << std::endl; } bool isAffectedByElevation = geom->isAffectedByElevation(); ossimNotify(ossimNotifyLevel_DEBUG) << "\nImage projection " << ( isAffectedByElevation ? "is" : "isn't") << " affected by elevation." << std::endl; // Test up is code: if ( isAffectedByElevation ) { ossim_float64 upIsUpAngle = geom->upIsUpAngle(); ossimNotify(ossimNotifyLevel_DEBUG) << "\nUp is up rotation angle: " << upIsUpAngle << "\n" << std::endl; } #if 0 /* commented out as one time test is good */ // Test the decimationFactor method. ossimDpt decimation; geom->decimationFactors(decimations); ossim_float64 r0_lines = ih->getNumberOfLines(0); ossim_float64 r0_samps = ih->getNumberOfSamples(0); for (level = 0; level < geom->getNumberOfDecimations(); ++level) { geom->decimationFactor(level, decimation); ossimNotify(ossimNotifyLevel_DEBUG) << "decimation[" << level << "]: " << decimation << "\nlines[" << level << "]: " << ih->getNumberOfLines(level) << "\nsamples[" << level << "]: " << ih->getNumberOfSamples(level) << "\ncomputed lines[" << level << "]: " << (r0_lines * decimation.y) << "\ncomputed samples[" << level << "]: " << (r0_samps * decimation.x) << std::endl; } #endif // Print out transform, if any: if ( geom->getTransform() != 0 ) { ossimNotify(ossimNotifyLevel_DEBUG) << "Image geometry 2d To 2d transform:\n" << *(geom->getTransform()) << "\n"; } else { ossimNotify(ossimNotifyLevel_DEBUG) << "Image geometry has no 2d To 2d transform.\n"; } } ++entry; // Go to next entry. } // matches: while ( entry != entryList.end() ) #if 0 // Dump the elevation cells used: std::vector cells; ossimElevManager::instance()->getOpenCellList(cells); for (ossim_uint32 cellIndex = 0; cellIndex < cells.size(); ++cellIndex) { std::ostringstream s; s << std::setfill('0') << "cell" << std::setw(3) << cellIndex << ": "; cout << std::setfill(' ') << setiosflags(ios::left) << std::setw(W) << s.str().c_str() << cells[cellIndex] << "\n"; } cout << endl; #endif return 0; } ossim-Miami-2.9.1/test/src/projection/ossim-nitf-rsm-model-test.cpp000066400000000000000000000334741352751253100253160ustar00rootroot00000000000000//--- // File: ossim-nitf-rsm-model-test.cpp // // Description: Test app for ossimNitfRsmModel class. // //--- #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; static ossimRefPtr getTag( const std::string& tagLine ); static ossimRefPtr getModel( const ossimFilename& file ); static ossimRefPtr getModelFromExtFile( const ossimFilename& file ); static ossimRefPtr getModelFromImage( const ossimFilename& file ); static void testGpts( ossimRefPtr& model, const ossimKeywordlist& kwl ); static void testIpts( ossimRefPtr& model, const ossimKeywordlist& kwl ); int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if ( argc == 3 ) { ossimFilename file = argv[1]; ossimKeywordlist kwl; if ( kwl.addFile( argv[2] ) ) { ossimRefPtr model = getModel( file ); if ( model.valid() ) { testGpts( model, kwl ); testIpts( model, kwl ); } else { cerr << "Could not create model!" << endl; } } else { cerr << "Could not open keyword list: " << argv[2] << endl; } } else { cout << "\n" << argv[0] << " " << "\ninput-test-file can be an input test file or a test.ext file.\n" << "\nPrints out debug info for model testing.." << "\ngpts test:" << "\nmodel->worldToLineSample(...), model->lineSampleToWorld(...)" << "\nipts test:" << "\nmodel->lineSampleHeightToWorld(...), model->worldToLineSample(...)" << "\noptions.kwl format example:\n" << "\n// Input line, sample type: area=upper left corner, point = center of pixel." << "\n// pixel_type: area" << "\ngtest_id0: E123456\n" << "gtest_gpt0: ( lat, lon, hgt )\n" << "gtest_gpt_id1: E123457\n" << "gtest_gpt1: ( lat, lon, hgt )\n" << "ggtest_pt_id2: E123458\n" << "gtest_gpt2: ( lat, lon, hgt )\n" << "gtest_gpt_id3: E123459\n" << "gtest_gpt3: ( lat, lon, hgt )\n" << "gtest_gpt_id4: E123459\n" << "gtest_pt4: ( lat, lon, hgt )\n" << "\nitest_height_units: feet\n" << "itest_id0: E123456\n" << "itest_ipt0: ( sample, line )\n" << "itest_hgt0: hgt\n" << "itest_id1: E123457\n" << "itest_ipt1: ( x, y )\n" << "itest_hgt1: hgt\n" << "itest_id2: E123458\n" << "itest_ipt2: ( x, y )\n" << "itest_hgt2: hgt\n" << "itest_id3: E123459\n" << "itest_ipt3: ( x, y )\n" << "itest_hgt3: hgt\n" << "itest_id4: E123459\n" << "itest_ipt4: ( x, y )\n" << "itest_hgt4: hgt\n" << "\nNotes:\n" << "* itest_hgt default = meters if units not specified.\n" << "* gpt0: ( lat, lon, hgt ) \"hgt\" is in meters.\n" << "* All test height output is in meters.\n" << "* \"rtd\"=round trip delta.\n" << endl; } return 0; } ossimRefPtr getTag( const std::string& tagLine ) { ossimRefPtr result = 0; if ( tagLine.size() > 6 ) { ossimString tagName = tagLine.substr(0, 6); result = ossimNitfTagFactoryRegistry::instance()->create( tagName ); if ( result.valid() ) { cout << "tag_name: " << tagName << "\n"; istringstream is( tagLine ); if ( is.good() ) { is.seekg( 6 ); char tagLength[6]; tagLength[5] = '\0'; is.read( tagLength, 5 ); cout << "tag_length: " << tagLength << "\n"; result->parseStream( is ); result->print( cout, std::string("") ); } } else { cerr << "unhandled_tag: " << tagName << endl; } } return result; } ossimRefPtr getModel( const ossimFilename& file ) { ossimRefPtr result = 0; if ( file.size() ) { // Get downcased extension: std::string ext = file.ext().downcase().string(); if ( ext == "ext" ) { result = getModelFromExtFile( file ); } else if ( ( ext == "ntf" ) || ( ext == "nitf" ) ) { result = getModelFromImage( file ); } } return result; } ossimRefPtr getModelFromExtFile( const ossimFilename& file ) { ossimRefPtr result = 0; if ( file.exists() ) { result = new ossimNitfRsmModel(); if ( result->parseFile( file, 0 ) ) // Hard coded entry index of 0 for now. { cout << "Initialize from ext file success!" << endl; } else { result = 0; cerr << "Could not open: " << file << endl; } } else { cerr << "File does not exists: " << file << endl; } return result; } // End: getModelFromExtFile(...) ossimRefPtr getModelFromImage( const ossimFilename& file ) { ossimRefPtr result = 0; ossimRefPtr ih = ossimImageHandlerRegistry::instance()->open(file, true, // try suffix first false); // open overview if ( ih.valid() ) { ossimRefPtr geom = ih->getImageGeometry(); if ( geom.valid() ) { ossimRefPtr proj = geom->getProjection(); if ( proj.valid() ) { result = dynamic_cast( proj.get() ); } } } return result; } void testGpts( ossimRefPtr& model, const ossimKeywordlist& kwl ) { if ( model.valid() ) { cout << std::setfill(' ') << setiosflags(ios::left); const std::string ID_KW = "gtest_id"; const std::string GPT_KW = "gtest_gpt"; const ossim_uint32 POINTS = kwl.numberOf( ID_KW.c_str() ); cout << "\ngtest begin ********************************\n\n" << "number_of_points_world_points: " << POINTS << "\n"; ossim_uint32 foundPts = 0; ossim_uint32 i = 0; std::string key; std::string value; while ( foundPts < POINTS ) { // ID: key = ID_KW + ossimString::toString( i ).string(); value = kwl.findKey( key ); if ( value.size() ) { cout << "gtest_id" << std::setw(6) << i << ": " << value << "\n"; } // World point : key = GPT_KW + ossimString::toString( i ).string(); value = kwl.findKey( key ); if ( value.size() ) { ossimDpt ipt; // image point ossimGpt wpt; // world point ossimGpt rtp; // round trip point ossimDpt rtd; // round trip delta; wpt.toPoint( value ); cout << "gtest_gpt" << std::setw(5) << i << ": " << wpt << "\n"; model->worldToLineSample( wpt, ipt ); if ( wpt.hasNans() == false ) { model->lineSampleHeightToWorld( ipt, wpt.hgt, rtp ); rtd.x = wpt.lon - rtp.lon; rtd.y = wpt.lat - rtp.lat; cout << "gtest_ipt" << std::setw(5) << i << ": " << ipt << "\n" << "gtest_rtp" << std::setw(5) << i << ": " << rtp << "\n" << "gtest_rtd" << std::setw(5) << i << ": " << rtd << "\n\n"; } else { cerr << "model->worldToLineSample(...) result has nans!\n" << wpt << endl; } ++foundPts; } ++i; if ( i > POINTS+100 ) { break; } } cout << "\ngtest end **********************************\n\n"; } } // End: testGpts void testIpts( ossimRefPtr& model, const ossimKeywordlist& kwl ) { if ( model.valid() ) { cout << std::setfill(' ') << setiosflags(ios::left); const std::string ID_KW = "itest_id"; const std::string IPT_KW = "itest_ipt"; const std::string IPT_GT_KW = "itest_gt"; // ground truth const std::string IPT_HGT_KW = "itest_hgt"; const ossim_uint32 POINTS = kwl.numberOf( ID_KW.c_str() ); // Test data height values can be in feet. ossimUnitType heightUnits = OSSIM_METERS; std::string key = "itest_height_units"; std::string value = kwl.findKey( key ); if ( value.size() ) { cout << key << ": " << value << "\n"; if ( value == "feet" ) { heightUnits = OSSIM_FEET; } } // Test the pixel type. ossim_float64 iptShift = 0.0; key = "pixel_type"; value = kwl.findKey( key ); if ( value.size() ) { if ( value == "area" ) { iptShift = -0.5; cout << key << ": " << value << "\n"; cout << "input_line_sample_shift: " << iptShift << "\n"; } } cout << "\nitest begin ********************************\n\n" << "number_of_line_sample_points: " << POINTS << "\n"; ossim_uint32 foundPts = 0; ossim_uint32 i = 0; while ( foundPts < POINTS ) { // ID: key = ID_KW + ossimString::toString( i ).string(); value = kwl.findKey( key ); if ( value.size() ) { cout << "itest_id" << std::setw(9) << i << ": " << value << "\n"; } // Image point, sample, line: key = IPT_KW + ossimString::toString( i ).string(); value = kwl.findKey( key ); if ( value.size() ) { ossimDpt ipt; // image point ossimGpt wpt; // world point ossimGpt gt; // ground truth ossimDpt gtd; // wpt to gt delta ossimDpt rtp; // round trip point ossimDpt rtd; // round trip delta; ipt.toPoint( value ); ipt.x += iptShift; ipt.y += iptShift; cout << "itest_ipt" << std::setw(8) << i << ": " << value << "\n"; // Get the height above ellipsoid: ossim_float64 hgt = 0.0; key = IPT_HGT_KW + ossimString::toString( i ).string(); value = kwl.findKey( key ); if ( value.size() ) { ossimString os ( value ); hgt = os.toFloat64(); if ( heightUnits == OSSIM_FEET ) { hgt *= MTRS_PER_FT; } } else { cerr << "missing height above ellipsoid for point! Using 0.0." << endl; } cout << "itest_hgt" << std::setw(8) << i << ": " << value << "\n"; model->lineSampleHeightToWorld( ipt, hgt, wpt ); cout << "itest_wpt" << std::setw(8) << i << ": " << wpt << "\n"; if ( wpt.hasNans() == false ) { model->worldToLineSample( wpt, rtp ); // Get the ground truth; key = IPT_GT_KW + ossimString::toString( i ).string(); value = kwl.findKey( key ); if ( value.size() ) { gt.toPoint( value ); cout << "itest_gt" << std::setw(9) << i << ": " << gt << "\n"; if ( gt.isNan() == false ) { gtd.x = wpt.lon - gt.lon; gtd.y = wpt.lat - gt.lat; ossimDpt mpd = wpt.metersPerDegree(); ossimDpt gtm; gtm.x = gtd.x * mpd.x; gtm.y = gtd.y * mpd.y; cout << "itest_gtd_dd" << std::setw(5) << i << ": " << gtd << "\n"; cout << "itest_gtd_mtrs" << std::setw(3) << i << ": " << gtm << "\n"; } } else { gt.makeNan(); } rtd = ipt - rtp; cout << "itest_rtp" << std::setw(8) << i << ": " << rtp << "\n" << "itest_rtd" << std::setw(8) << i << ": " << rtd << "\n\n"; } else { cerr << "model->worldToLineSample(...) result has nans!\n" << wpt << endl; } ++foundPts; } ++i; if ( i > POINTS+100 ) { break; } } cout << "\ntestIpts end **********************************\n\n"; } } // End: testIpts ossim-Miami-2.9.1/test/src/projection/ossim-projection-factory-test.cpp000066400000000000000000000032331352751253100262700ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Test application to spit out projection names from the // projection factory registry. // // $Id: ossim-projection-factory-test.cpp 19751 2011-06-13 15:13:07Z dburken $ //---------------------------------------------------------------------------- #include #include #include using namespace std; #include #include #include // #include // #include // #include // #include int main(int argc, char* argv[]) { ossimInit::instance()->initialize(argc, argv); std::vector typeList; std::vector::const_iterator i; cout << "ossimEpsgProjectionFactory:\n"; typeList.clear(); ossimEpsgProjectionFactory::instance()->getTypeNameList(typeList); i = typeList.begin(); while (i < typeList.end()) { std::cout << (*i) << std::endl; ++i; } return 0; } #if 0 int main() { ossimInit::instance()->initialize(); std::vector typeList; ossimProjectionFactoryRegistry::instance()->getTypeNameList(typeList); std::vector::const_iterator i = typeList.begin(); while (i < typeList.end()) { std::cout << (*i) << std::endl; ++i; } return 0; } #endif ossim-Miami-2.9.1/test/src/projection/ossim-projection-test.cpp000066400000000000000000000054571352751253100246350ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: David Burken // // Description: Test application to for projection classes. // //---------------------------------------------------------------------------- // $Id: ossim-projection-test.cpp 2777 2011-06-27 19:14:17Z david.burken $ #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char* argv[]) { ossimInit::instance()->initialize(argc, argv); ossimRefPtr proj1 = new ossimEquDistCylProjection(); cout << "\n\nproj1 orgin=(0,0):\n"; proj1->print(cout); ossim_float64 dpp = 1.0/3600.0; // Degrees per pixel. ossimDpt scale(dpp, dpp); proj1->setDecimalDegreesPerPixel(scale); cout << "\n\nproj1 after setDecimalDegreesPerPixel(0.000277778, 0.000277778):\n"; proj1->print(cout); ossimGpt origin(38.0, -123.0, 0.0); proj1->setOrigin(origin); cout << "\n\nproj1 after setOrgin=(38, -123):\n"; proj1->print(cout); proj1->setDecimalDegreesPerPixel(scale); cout << "\n\nproj1 after setDecimalDegreesPerPixel(0.000277778, 0.000277778) with origin lat of 38N:\n"; proj1->print(cout); ossimRefPtr proj2 = static_cast(proj1->dup()); cout << "\n\nproj2 a dup of proj1:\n"; proj2->print(cout); ossimKeywordlist kwl; proj2->saveState(kwl); cout << "\n\nproj2 save state:\n" << kwl << endl; ossimRefPtr proj3 = ossimProjectionFactoryRegistry::instance()-> createProjection(kwl); cout << "\n\nproj3 created from proj2's saveState via ossimProjectionFactoryRegistry::createProjection\n"; if ( proj3.valid() ) { proj3->print(cout); } ossimRefPtr proj4 = new ossimEquDistCylProjection(); proj4->loadState(kwl); cout << "\n\nproj4 from proj2 save state via ossimEquDistCylProjection::loadState:\n"; proj4->print(cout); ossimRefPtr proj5 = new ossimGoogleProjection(); ossimDpt dpt(-20037508.3428, 20037508.3428); ossimGpt gpt = proj5->inverse( dpt ); cout << "\n\nossimGoogleProjection test:" << "\ndpt: " << dpt << "\ninverse gpt: " << gpt << endl; dpt.x = 20037508.3428; dpt.y = -20037508.3428; gpt = proj5->inverse( dpt ); cout << "\ndpt: " << dpt << "\ninverse gpt: " << gpt << "\n" << endl; return 0; } ossim-Miami-2.9.1/test/src/projection/ossim-wkt-proj-factory-test.cpp000066400000000000000000000137471352751253100257040ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer // // Description: Unit test application for WKT Projection Factory. // // $Id$ //---------------------------------------------------------------------------- #include #include #include #include using namespace std; #include #include #include #include #include #include #include #include #include static const char* P1 = "PROJCS[\"NAD_1983_HARN_Lambert_Conformal_Conic\",\ GEOGCS[\"GCS_North_American_1983_HARN\",DATUM[\"NAD83_High_Accuracy_Regional_Network\",\ SPHEROID[\"GRS_1980\",6378137,298.257222101, AUTHORITY[\"EPSG\",\"7019\"]],\ AUTHORITY[\"EPSG\",\"6152\"]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]],\ PROJECTION[\"Lambert_Conformal_Conic_2SP\"],PARAMETER[\"standard_parallel_1\",43],\ PARAMETER[\"standard_parallel_2\",45.5],PARAMETER[\"latitude_of_origin\",41.75],\ PARAMETER[\"central_meridian\",-120.5],PARAMETER[\"false_easting\",1312335.958005249],\ PARAMETER[\"false_northing\",0],UNIT[\"foot\",0.3048, AUTHORITY[\"EPSG\",\"9002\"]]]"; static const char* P2 = "PROJCS[\"WGS_1984_UTM_Zone_41N\",\ AUTHORITY[\"EPSG\",\"32641\"]],GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",\ SPHEROID[\"WGS 84\",6378137,298.2572235630016, AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],\ PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],\ PARAMETER[\"latitude_of_origin\",0],PARAMETER[\"central_meridian\",63],PARAMETER[\"scale_factor\",0.9996],\ PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,\ AUTHORITY[\"EPSG\",\"9001\"]]]"; static const char* P3 = "PROJCS[\"Cylindrical_Equal_Area \",\ GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",\ SPHEROID[\"WGS 84\",6378137,298.2572235630016, AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],\ PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]],PROJECTION[\"Cylindrical_Equal_Area\"],\ PARAMETER[\"latitude_of_origin\",0],PARAMETER[\"central_meridian\",63],PARAMETER[\"scale_factor\",0.9996],\ PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,\ AUTHORITY[\"EPSG\",\"9001\"]]]"; static const char* P4 = "PROJCS[\"World_Equidistant_Cylindrical\",\ GEOGCS[\"GCS_WGS_1984\",DATUM[\"WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],\ PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Equirectangular\"],\ PARAMETER[\"False_Easting\",0],PARAMETER[\"False_Northing\",0],PARAMETER[\"Central_Meridian\",0],\ PARAMETER[\"Standard_Parallel_1\",60],UNIT[\"Meter\",1],AUTHORITY[\"EPSG\",\"54002\"]]"; static const char* P5 = "PROJCS[\"ETRS89 / Jersey Transverse Mercator\",\ GEOGCS[\"ETRS89\",DATUM[\"European_Terrestrial_Reference_System_1989\",\ SPHEROID[\"GRS 1980\",6378137,298.257222101,AUTHORITY[\"EPSG\",\"7019\"]],TOWGS84[0,0,0,0,0,0,0],\ AUTHORITY[\"EPSG\",\"6258\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],\ UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4258\"]],\ PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"latitude_of_origin\",49.225],\ PARAMETER[\"central_meridian\",-2.135],PARAMETER[\"scale_factor\",0.9999999],\ PARAMETER[\"false_easting\",40000],PARAMETER[\"false_northing\",70000],UNIT[\"metre\",1,\ AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"Easting\",EAST],AXIS[\"Northing\",NORTH]]"; static const char* P6 = "PROJCS[\"World_Mercator\",\ GEOGCS[\"GCS_WGS_1984\",DATUM[\"WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],\ PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Mercator_1SP\"],\ PARAMETER[\"False_Easting\",0],PARAMETER[\"False_Northing\",0],PARAMETER[\"Central_Meridian\",0],\ PARAMETER[\"latitude_of_origin\",0],UNIT[\"Meter\",1]]"; int main(int argc, char* argv[]) { cout << "ossimWktProjectionFactory Test:" << endl; ossimInit::instance()->initialize(argc, argv); cout << " Testing getTypeNameList()... "; cout.flush(); std::vector typeList; ossimWktProjectionFactory::instance()->getTypeNameList(typeList); std::size_t size = typeList.size(); assert(size == 2917); cout << " Passed.\n" << endl; ossimMapProjection* proj; // cout << " Testing Lambert_Conformal_Conic (P1)... "; cout.flush(); // assert(dynamic_cast( // ossimWktProjectionFactory::instance()->createProjection(ossimString(P1)))); // cout << " Passed.\n"; cout << " Testing WGS_1984_UTM_Zone_41N (P2)... "; cout.flush(); assert(dynamic_cast( ossimWktProjectionFactory::instance()->createProjection(ossimString(P2)))); cout << " Passed.\n"; cout << " Testing Cylindrical_Equal_Area (P3)... "; cout.flush(); assert(dynamic_cast( ossimWktProjectionFactory::instance()->createProjection(ossimString(P3)))); cout << " Passed.\n"; cout << " Testing Equidistant_Cylindrical (P4)... "; cout.flush(); assert(dynamic_cast( ossimWktProjectionFactory::instance()->createProjection(ossimString(P4)))); cout << " Passed.\n"; cout << " Testing Transverse_Mercator (P5)... "; cout.flush(); assert(dynamic_cast( ossimWktProjectionFactory::instance()->createProjection(ossimString(P5)))); cout << " Passed.\n"; cout << " Testing Mercator (P6)... "; cout.flush(); assert(dynamic_cast( ossimWktProjectionFactory::instance()->createProjection(ossimString(P6)))); cout << " Passed.\n"; return 0; } ossim-Miami-2.9.1/test/src/projection/ossim-wkt-test.cpp000066400000000000000000000037731352751253100232650ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-wkt-test.cpp // // Author: David Burken // // Description: Contains application definition "ossim-wkt-test" app. //---------------------------------------------------------------------------- #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { int returnCode = 0; ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); try { std::string wktString = "PROJCS[\"WGS 84 / UTM zone 55S\",GEOGCS[\"WGS 84\",DATUM[\"World Geodetic System_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Transverse Mercator\",AUTHORITY[\"EPSG\",\"9807\"]],PARAMETER[\"Latitude of natural origin\",0],PARAMETER[\"Longitude of natural origin\",147],PARAMETER[\"scale_factor\",0.9996],PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",10000000],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"Easting\",EAST],AXIS[\"Northing\",AUTHORITY[\"EPSG\",\"32755\"]]"; ossimWkt wkt; if ( wkt.parse( wktString ) ) { ossimNotify(ossimNotifyLevel_NOTICE) << wkt.getKwl() << endl; } else { ossimNotify(ossimNotifyLevel_WARN) << "wkt string parse failed!" << endl; returnCode = 1; } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } return returnCode; } ossim-Miami-2.9.1/test/src/support_data/000077500000000000000000000000001352751253100201665ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/support_data/CMakeLists.txt000066400000000000000000000017331352751253100227320ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ OSSIM_SETUP_APPLICATION(ossim-aux-dot-xml-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-aux-dot-xml-test.cpp) OSSIM_SETUP_APPLICATION(ossim-envi-hdr-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-envi-hdr-test.cpp) OSSIM_SETUP_APPLICATION(ossim-fgdc-txt-doc-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-fgdc-txt-doc-test.cpp) OSSIM_SETUP_APPLICATION(ossim-quickbird-metadata-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-quickbird-metadata-test.cpp) OSSIM_SETUP_APPLICATION(ossim-srtm-support-data-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-srtm-support-data-test.cpp) OSSIM_SETUP_APPLICATION(ossim-tiff-info-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-tiff-info-test.cpp) OSSIM_SETUP_APPLICATION(ossim-wavelength-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-wavelength-test.cpp) ossim-Miami-2.9.1/test/src/support_data/ossim-aux-dot-xml-test.cpp000066400000000000000000000032351352751253100251610ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: See top level LICENSE.txt file. // // File: ossim-aux-dot-xml-test.cpp // // Author: David Burken // // Description: Test application for ossimAuxXmlSupportData class. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->addOptions(ap); ossimInit::instance()->initialize(ap); int status = 0; if (argc == 2) { try { ossimFilename f = ossimFilename(argv[1]); ossimAuxXmlSupportData sd; ossimRefPtr proj = sd.getProjection( f ); if ( proj.valid() ) { proj->print( cout ); } else { cerr << "Could not get projection from: " << f << endl; status = 1; } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; status = 1; } } else { cout << argv[0] << " " << "\nAttempts to get/print a projection from aux dot xml file." << endl; } return status; } ossim-Miami-2.9.1/test/src/support_data/ossim-envi-hdr-test.cpp000066400000000000000000000020651352751253100245160ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test app for ossimEnviHeader class. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if (argc != 2) { cout << argv[0] << " " << "\nOpen, parse and print ossimEnviHeader object." << endl; return 0; } cout << "ossimEnviHeader test:\n"; ossimEnviHeader hdr; if ( hdr.open( ossimFilename( argv[1] ) ) ) { ossimString s = "Hello world..."; hdr.setDescription( s ); cout << hdr << endl; } else { cout << "Could not open: " << argv[1] << endl; } return 0; } ossim-Miami-2.9.1/test/src/support_data/ossim-fgdc-txt-doc-test.cpp000066400000000000000000000037271352751253100252730ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // File ossim-fgdc-txt-doc-test.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test application for ossimFgdcTxtDoc class. // //---------------------------------------------------------------------------- // $Id: ossim-info-test.cpp 19751 2011-06-13 15:13:07Z dburken $ #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { ossimArgumentParser ap(&argc, argv); // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); if ( ap.argc() == 2 ) { try { // Test the ossimFgdcTxtDoc ossimRefPtr fgdcDoc = new ossimFgdcTxtDoc(); ossimFilename file(argv[1]); if ( fgdcDoc->open( file ) ) { cout << "opened: " << file << endl; ossimRefPtr proj; fgdcDoc->getProjection(proj); if ( proj.valid() ) { proj->print(cout); } std::string units; fgdcDoc->getAltitudeDistanceUnits(units); cout << "units: " << units << endl; } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; return 1; } } // End: if ( ( ap.argc() == 2 ) ... else { cout << argv[0] << " \nTest ossimFgdcTxtDoc class..." << endl; } return 0; } // End of main... ossim-Miami-2.9.1/test/src/support_data/ossim-quickbird-metadata-test.cpp000066400000000000000000000027701352751253100265400ustar00rootroot00000000000000//--- // License: MIT // // File: ossim-quickbird-metadata-test.cpp // // Description: Test code for Quickbird/Digital Globe dot.IMD file. //--- // $Id$ #include #include #include #include #include #include using namespace std; static void usage() { cout << "ossim-quickbird-metadata-test " << endl; } int main(int argc, char *argv[]) { int returnCode = 0; ossimInit::instance()->initialize(argc, argv); if (argc == 2) { try { ossimFilename file = argv[argc - 1]; if ( file.exists() ) { ossimQuickbirdMetaData md; if ( md.open( file ) ) { md.print( cout ); } ossimKeywordlist kwl; if ( md.getMapProjectionKwl( file, kwl ) == true ) { cout << "kwl:\n" << kwl << endl; } } else { usage(); returnCode = 1; } } catch(const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; returnCode = 1; } catch( ... ) { ossimNotify(ossimNotifyLevel_WARN) << "ossim-foo caught unhandled exception!" << std::endl; returnCode = 1; } } else { usage(); } return returnCode; } ossim-Miami-2.9.1/test/src/support_data/ossim-srtm-support-data-test.cpp000066400000000000000000000022551352751253100264110ustar00rootroot00000000000000//---------------------------------------------------------------------------- // Copyright (C) 2005 David Burken, all rights reserved. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test application / example code for srtm support data class. // and using it. // // $Id: ossim-srtm-support-data-test.cpp 23497 2015-08-28 15:28:59Z okramer $ //---------------------------------------------------------------------------- #include using namespace std; #include #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if (argc != 2) { cout << "usage: " << argv[0] << " srtm_file" << endl; return 0; } ossimSrtmSupportData sd; if (sd.setFilename(ossimFilename(argv[1]), true)) { cout << sd << endl; ossimKeywordlist kwl; sd.getImageGeometry(kwl); cout << "geometry file:\n" << kwl << endl; } else { cout << "Could not open: " << argv[1] << endl; } return 0; } ossim-Miami-2.9.1/test/src/support_data/ossim-tiff-info-test.cpp000066400000000000000000000034761352751253100246720ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test app for ossimTiffInfo class. // //---------------------------------------------------------------------------- // $Id: ossim-tiff-info-test.cpp 19751 2011-06-13 15:13:07Z dburken $ #include using namespace std; #include #include #include #include int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if (argc != 2) { cout << argv[0] << "" << "\nPrint dump and geometry info for tiff_file." << endl; return 0; } cout << "ossimTiffInfo test:\n"; ossimTiffInfo* info = new ossimTiffInfo(); if ( info->open( ossimFilename(argv[1]) ) ) { cout << "ossimTiffInfo dump info:\n"; info->print(cout); ossimKeywordlist kwl; if ( info->getImageGeometry(kwl, 0) ) { cout << "ossimTiffInfo geometry info:\n" << kwl << endl; } else { cout << "ossimTiffInfo get image geometry failed..." << endl; } } else { cout << "Could not open: " << argv[1] << endl; } delete info; info = 0; cout << "ossimGeoTiff test:\n"; ossimGeoTiff* gtif = new ossimGeoTiff(); if ( gtif->readTags(argv[1], 0) ) { ossimKeywordlist kwl; if ( gtif->addImageGeometry(kwl, 0) ) { cout << "ossimGeoTiff geometry info:\n" << kwl << endl; } else { cout << "ossimGeoTiff get image geometry failed..." << endl; } } delete gtif; gtif = 0; return 0; } ossim-Miami-2.9.1/test/src/support_data/ossim-wavelength-test.cpp000066400000000000000000000067761352751253100251630ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: // // Test app for ossimWavelength class. // //---------------------------------------------------------------------------- // $Id$ #include #include #include #include #include using namespace std; static void usage() { cout << "\nUsage:\nossim-wavelength-test " << "\nWill output found closest index and wavelength." << "Note: Units in nanometers" << "\nContents of minimal header file:" << "\nwavelength units = Nanometers" << "\nwavelength = {374.323608, 382.530487, 390.737427, 398.944336, 407.150970}" << "\n" << endl; } int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if (argc != 4) { usage(); return 0; } ossimFilename hdrFile = argv[argc - 3]; ossimString waveLengthString = argv[argc - 2]; ossimString thresholdFromCenterString = argv[argc - 1]; ossim_float64 wavelength = waveLengthString.toFloat64(); ossim_float64 thresholdFromCenter = thresholdFromCenterString.toFloat64(); cout << "header file: " << hdrFile << "\nwavelength: " << waveLengthString << "\nthreshold from center: " << thresholdFromCenterString << "\n"; if ( hdrFile.exists() ) { ossimEnviHeader hdr; if ( hdr.open( hdrFile ) ) { ossimWavelength wl; if ( wl.initialize( hdr ) ) { cout << "\nossimWavelength::getRgbBands returned:\n"; std::vector bands; ossim_uint32 band = 0; if ( wl.getRgbBands( bands ) ) { std::vector::const_iterator i = bands.begin(); while ( i != bands.end() ) { cout << "band[" << band << "]: " << (*i) << "\n"; ++band; ++i; } } else { cout << "error...\n"; } cout << "\nossimWavelength::findClosestIterator(...) returned:\n"; ossimWavelength::WavelengthMap::const_iterator i = wl.findClosestIterator( wavelength, thresholdFromCenter ); if ( i != wl.end() ) { cout << "(*i).first: " << (*i).first << " (*i).second: " << (*i).second << "\n"; } else { cout << "error...\n"; } cout << "\nossimWavelength::findClosestIndex(...) returned:\n"; ossim_int32 index = wl.findClosestIndex( wavelength, thresholdFromCenter ); if ( index > -1 ) { cout << "index: " << index << "\n"; } else { cout << "error...\n"; } } else { cerr << "ossimWavelength::initialize( ossimEnviHeader ) failed!" << endl; } } else { cout << "Could not open: " << hdrFile << endl; } } else { cerr << "File: " << hdrFile << "\nDoes not exists!" << endl; usage(); } cout << endl; return 0; } // End of main... ossim-Miami-2.9.1/test/src/util/000077500000000000000000000000001352751253100164365ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/util/CMakeLists.txt000066400000000000000000000012351352751253100211770ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ OSSIM_SETUP_APPLICATION(ossim-chipper-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-chipper-test.cpp) OSSIM_SETUP_APPLICATION(ossim-info-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-info-test.cpp) OSSIM_SETUP_APPLICATION(ossim-viewshed-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-viewshed-test.cpp) OSSIM_SETUP_APPLICATION(ossim-tools-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-tools-test.cpp) OSSIM_SETUP_APPLICATION(ossim-remap-tool-test INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-remap-tool-test.cpp) ossim-Miami-2.9.1/test/src/util/ossim-chipper-test.cpp000066400000000000000000000065351352751253100227120ustar00rootroot00000000000000//--- // File: ossim-chipper-test.cpp // // License: MIT // // Author: David Burken // // Description: Test application for ossimChipperUtil class. //--- // $Id$ #include #include #include #include #include #include #include #include #include using namespace std; static void usage( const std::string& app ) { cout << app << " " << "\n\nWrites out a single image data raster buffer.\n" << "\nSample chipper options file that can be cut and pasted in a " << "\"chipper_options.kwl\" file for test.\n" << "hist_op: auto-minmax\n" << "image0.file: /data1/test/data/public/applanix/utm/17657707.tif\n" << "image0.entry: 0\n" << "operation: chip\n" << "thumbnail_resolution: 256\n" << "three_band_out: true\n" << "output_radiometry: U8\n" << "pad_thumbnail: true\n" << endl; } int main(int argc, char* argv[]) { int status = -1; if (argc != 3 ) { usage( std::string( argv[0] ) ); return 0; } ossimFilename chipperOptions = argv[1]; ossimFilename outputFile = argv[2]; ostringstream exceptionMsg; if ( !chipperOptions.exists() ) { cerr << "Input options file <"< does not exists!" << endl; return -1; } // Timer for elapsed time: ossimTimer::instance()->setStartTick(); try { ossimInit::instance()->initialize(argc, argv); ossimFilename chipperOptions = argv[1]; ossimFilename outputFile = argv[2]; cout << "chipper options file: " << chipperOptions << "output file: " << outputFile << "\n"; ossimKeywordlist kwl; if ( !kwl.addFile( chipperOptions ) ) { exceptionMsg<<"ERROR: Could not open <"< as keyword list." << ends; throw (ossimException(exceptionMsg.str())); } cout << "chipper input options:\n" << kwl << endl; ossimRefPtr chipper = new ossimChipperUtil(); chipper->initialize( kwl); ossimRefPtr chip = chipper->getChip( ); if ( !chip.valid() ) { exceptionMsg<<"ERROR: NULL chip returned from chipper->getChip()." << ends; throw (ossimException(exceptionMsg.str())); } status = chip->getDataObjectStatus(); if ( status == (int)OSSIM_NULL ) { exceptionMsg<<"ERROR: returned chip status OSSIM_NULL!" << ends; throw (ossimException(exceptionMsg.str())); } if ( !chip->write( outputFile ) ) { exceptionMsg<<"ERROR: Could not write <"<." << ends; throw (ossimException(exceptionMsg.str())); } cout << "Wrote file: " << outputFile << endl; status = 0; } catch( const ossimException& e ) { cerr << "Caught exception: " << e.what() << endl; } catch( ... ) { cerr << "Caught unknown exception!" << endl; } cout << "Elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << endl; return status; } // End of main(...) ossim-Miami-2.9.1/test/src/util/ossim-info-test.cpp000066400000000000000000000052761352751253100222140ustar00rootroot00000000000000//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test application for ossimInfo class. // //---------------------------------------------------------------------------- // $Id: ossim-info-test.cpp 22197 2013-03-12 02:00:55Z dburken $ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { //--- // Get the arg count so we can tell if an arg was consumed by // ossimInit::instance()->initialize //--- // int originalArgCount = argc; ossimArgumentParser ap(&argc, argv); // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); if ( ap.argc() == 2 ) { try { // Test the ossimInfo::getImageInfo method. ossimRefPtr oi = new ossimInfo; ossimFilename file(argv[1]); ossimKeywordlist kwl; oi->getImageInfo(file, true, // dump false, // dno true, // image geom true, // image info true, // metadata true, // palette kwl); cout << kwl << endl; cout << "\n\ntest info dump to a keyword list:\n"; std::shared_ptr info = ossimInfoFactoryRegistry::instance()->create(file); if (info) { info->setProcessOverviewFlag(false); ossimKeywordlist kwl; // if ( info->getKeywordlist( kwl, 9 ) ) if ( info->getKeywordlist( kwl ) ) { cout << kwl << endl; } info = 0; } else { ossimNotify(ossimNotifyLevel_INFO) << "No dump available for: " << file.c_str() << std::endl; } } catch (const ossimException& e) { ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl; return 1; } } // End: if ( ( ap.argc() == 2 ) ... else { cout << argv[0] << " \nTest ossimInfo class..." << endl; } return 0; } // End of main... ossim-Miami-2.9.1/test/src/util/ossim-remap-tool-test.cpp000066400000000000000000000046341352751253100233350ustar00rootroot00000000000000//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // // Author: oscar.kramer@maxar.com // //************************************************************************************************** #include #include #include #include #include #include using namespace std; void usage(char* argv0, int exitCode, std::string errMsg="") { if (!errMsg.empty()) std::cout<<"\n"<-remap.ext" "\n" "\nUsage: "< [] " "\n" "\nOptions:" "\n -e Entry index for multi-entry input files." "\n -h Dump this help." "\n -n Skip histogram stretch." "\n"<initialize(ap); ostringstream msg; int entryIndex=0, c=0; bool doHistoStretch=true; // Parse command line: while ((c = getopt(argc, argv, "e:hn")) != -1) { switch (c) { case 'e': entryIndex = atoi(optarg); break; case 'h': usage(argv[0], 0); break; case 'n': doHistoStretch = false; break; case '?': msg << "Unknown option '" << (char) optopt << "' specified."; usage(argv[0], 1, msg.str()); break; default: abort(); } } int numArgs = argc - optind; if (numArgs < 1) usage(argv[0], 1, "Input filename required."); ossimFilename inputFilename (argv[optind++]); ossimFilename outputFilename; if (numArgs > 1) outputFilename = argv[optind]; try { // Constructor does everything or throws exception: ossimRemapTool ort (inputFilename, entryIndex, doHistoStretch, outputFilename); } catch (const ossimException& e) { std::cerr << e.what() << std::endl; return 1; } return 0; } ossim-Miami-2.9.1/test/src/util/ossim-tools-test.cpp000066400000000000000000000047341352751253100224170ustar00rootroot00000000000000//--- // File: ossim-chipper-test.cpp // // License: MIT // // Author: David Burken // // Description: Test application for ossimChipperUtil class. //--- // $Id$ #include #include #include #include #include #include #include #include #include #include using namespace std; static void usage( const std::string& app ) { cout << app << " " << endl; } int main(int argc, char* argv[]) { int status = -1; // Timer for elapsed time: ossimTimer::instance()->setStartTick(); try { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->initialize(ap); ossimKeywordlist kwl; kwl.add("observer", "48.433324 -113.7850077"); //kwl.add("aoi_map_rect", "-12684715.289296463,6168162.4345005825,-12649344.0544575,6205998.763501747"); kwl.add("visibility_radius", "1000"); //kwl.add("srs", "3857"); kwl.add("height_of_eye", "5"); kwl.add("lut_file", "/data/TEST/HLZ/N48W114/vs.lut"); kwl.add("lz_min_radius", "100"); kwl.add("roughness_threshold", "1.5"); kwl.add("slope_threshold", "7.0"); kwl.add("output_file", "test.tif"); kwl.add("elev_sources", "N48W114.hgt"); if (argc < 2) { cout<<"\nNeed tool name!"< chipProcUtil = (ossimChipProcTool*) ossimToolRegistry::instance()->createTool(toolName); if (!chipProcUtil) cerr<<"OssimTools() Bad opeation requested: <"<. Ignoring."<initialize(kwl); ossimDrect map_bbox (-12684715.289296463, 6168162.4345005825, -12649344.0544575, 6205998.763501747); ossimDpt gsd (30, 30); ossimRefPtr tile = chipProcUtil->getChip(map_bbox, gsd); tile->write("debug_chip.ras"); } catch( const ossimException& e ) { cerr << "Caught exception: " << e.what() << endl; } catch( ... ) { cerr << "Caught unknown exception!" << endl; } cout << "Elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; return status; } // End of main(...) ossim-Miami-2.9.1/test/src/util/ossim-viewshed-test.cpp000066400000000000000000000036221352751253100230700ustar00rootroot00000000000000//--- // File: ossim-chipper-test.cpp // // License: MIT // // Author: David Burken // // Description: Test application for ossimChipperUtil class. //--- // $Id$ #include #include #include #include #include #include #include #include #include using namespace std; static void usage( const std::string& app ) { cout << app << " " << endl; } int main(int argc, char* argv[]) { int status = -1; // Timer for elapsed time: ossimTimer::instance()->setStartTick(); try { ossimArgumentParser ap(&argc, argv); ossimInit::instance()->initialize(ap); ossimKeywordlist kwl; kwl.add("observer", "48.48 -113.79"); kwl.add("aoi_map_rect", "-12684715.289296463,6168162.4345005825,-12649344.0544575,6205998.763501747"); //kwl.add("visibility_radius", "8000"); kwl.add("srs", "3857"); kwl.add("height_of_eye", "5"); kwl.add("lut_file", "/data/TEST/HLZ/N48W114/vs.lut"); ossimRefPtr viewshed = new ossimViewshedTool; viewshed->initialize(kwl); ossimDrect map_bbox (-12684715.289296463, 6168162.4345005825, -12649344.0544575, 6205998.763501747); ossimDpt gsd (30, 30); ossimRefPtr tile = viewshed->getChip(map_bbox, gsd); tile->write("debug_chip.ras"); } catch( const ossimException& e ) { cerr << "Caught exception: " << e.what() << endl; } catch( ... ) { cerr << "Caught unknown exception!" << endl; } cout << "Elapsed time in seconds: " << std::setiosflags(ios::fixed) << std::setprecision(3) << ossimTimer::instance()->time_s() << "\n"; return status; } // End of main(...) ossim-Miami-2.9.1/test/src/vec/000077500000000000000000000000001352751253100162365ustar00rootroot00000000000000ossim-Miami-2.9.1/test/src/vec/CMakeLists.txt000066400000000000000000000002721352751253100207770ustar00rootroot00000000000000# $Id: CMakeLists.txt 23496 2015-08-28 15:26:18Z okramer $ OSSIM_SETUP_APPLICATION(ossim-dump-vpf-table INSTALL COMMAND_LINE COMPONENT_NAME ossim SOURCE_FILES ossim-dump-vpf-table.cpp) ossim-Miami-2.9.1/test/src/vec/ossim-dump-vpf-table.cpp000066400000000000000000000014651352751253100227230ustar00rootroot00000000000000//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Garrett Potts (gpotts@imagelinks.com) // Description: Does a table dump on any vpf table. // //******************************************************************** // $Id: ossim-dump-vpf-table.cpp 23495 2015-08-28 15:25:19Z okramer $ #include #include #include using namespace std; void displayUsage() { cout << "usage:\ndump_table " << endl; } int main(int argc, char *argv[]) { if(argc == 2) { ossimVpfTable table; if(table.openTable(argv[1]) == ossimErrorCodes::OSSIM_OK) { cout << table << endl; } } else { displayUsage(); } }